const pg = require('../pg') const joinjs = require('join-js').default; const debug = require('debug')('sos:db:order') const mappings = require('../mappings') const easypost = new (require('@easypost/api'))(process.env.EASYPOST_API_KEY); const order = module.exports = {} order.create = async function(cart_uuid){ const query = { text: 'select * from sos.create_order($1)', values: [cart_uuid] } debug(query); const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'orderMap', 'order_')[0]; } order.findForCart = async function(cart_uuid) { const query = { text: 'select * from sos.find_order_for_cart($1)', values: [cart_uuid] } debug(query) const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'orderMap', 'order_')[0]; } order.addAddress = async function (transaction, address){ // Get parcel size const parcel = { weight: .2 * transaction.cart.items.length, width: 10, length: transaction.cart.items.length, height: 3 } // Create shipment const epShipment = new easypost.Shipment({ to_address: address.easypost_id, from_address: { street1: '11381 N. Sampson Drive', city: 'Highland', state: 'UT', zip: '84003', country: 'US' }, parcel }) await epShipment.save() // Get shipping price (as cents) const lowestRate = epShipment.lowestRate(['USPS']) const price = parseFloat(lowestRate && lowestRate.retail_rate) * 100 if(!price) throw new Error("Unable to estimate price"); // TODO: Update with real tax rate const tax = epShipment.to_address.state === 'UT' ? 200 : null // Update database const query = { text: 'select * from sos.add_address_to_order($1, $2, $3, $4)', values: [transaction.uuid, address.uuid, price, tax] } debug(query) const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'orderMap', 'order_')[0]; }