module SolidusBling class Order < SolidusBling::Api def initialize order super(SolidusBling::Account.first) @order = order end def send if @order.present? contato = SolidusBling::Contact.new(@order, @account) hash_order = build_hash_order(@order, contato.info) begin attempts ||= 1 req = Typhoeus.post("#{@account.api_base_url}/pedidos/vendas", headers: @headers, body: JSON.dump(hash_order)) raise if req.code == 429 rescue retry if (attempts += 1) < 5 ensure json = JSON.parse(req.body) response_has_error?(json) if json.include? "data" @order.bling_order_id = json["data"]["id"] @order.save end end end end private def build_hash_order order, contato { "numeroLoja": order.number, "data": order.completed_at.strftime("%Y-%m-%d"), "loja": { "id": @account.external_store_id }, "contato": { "id": contato["id"] }, "itens": build_array_items(order.line_items), "vendedor": { "id": @account.sellers.first.external_id }, "transporte": build_hash_transporte(order), "parcelas": build_array_parcelas(order), "desconto": { "valor": order.promo_total&.to_f.abs || 0, "unidade": "REAL" }, "totalProdutos": order.item_total.to_f, "total": order.total.to_f, "observacoes": " NÂș Pedido Loja: #{order.number}", "observacoesInternas": "Pagamento: #{@parcelas}x R$ #{(order.total.to_f / @parcelas).round(2)}\nForma de envio: #{order.shipments.last.selected_shipping_rate.name}\n#{build_cupons(order.promotions)}", "categoria": { "id": @account.incoming_category_id } } end def build_array_items items items.map do |item| bling_product = SolidusBling::Product.find_by(sku: item.sku) { "id": bling_product.external_id, "quantidade": item.quantity, "valor": item.price.to_f, "produto": { "id": bling_product.external_id } } end end def build_array_parcelas order @parcelas = 1 if order.payments.last.source @parcelas = order.payments.last.source.try(:installments) || 1 end valor_parcela = order.total.to_f / @parcelas 1.upto(@parcelas).map do |parcela| { "dataVencimento": (order.completed_at + parcela.months).strftime("%Y-%m-%d"), "valor": valor_parcela, "formaPagamento": { "id": @account.payment_methods.find_by(spree_payment_method_id: order.payments.last.payment_method_id).external_id } } end end def build_hash_transporte order { "fretePorConta": 1, "frete": order.shipment_total.to_f, "quantidadeVolumes": 1, "etiqueta": { "nome": order.ship_address.name, "endereco": order.ship_address.address1, "numero": order.ship_address.number, "complemento": order.ship_address.address2, "municipio": order.ship_address.city, "uf": order.ship_address.state.abbr, "bairro": order.ship_address.district, "cep": order.ship_address.zipcode, "nomePais": "Brasil" }, "volumes": [ { "servico": @account.shipping_methods.find_by(spree_shipping_method_id: order.shipments.last.shipping_method.id).alias, "codigoRastreamento": "" } ] } end def build_cupons cupons string_cupons = '' if !cupons.empty? string_cupons = "Cupons utilizados: #{cupons.pluck(:name).join(", ")}" end string_cupons end end end