const pg = require('../pg') const joinjs = require('join-js').default; const debug = require('debug')('sos:db:address') const mappings = require('../mappings') const dbUtil = require('../util') const easypost = new (require('@easypost/api'))(process.env.EASYPOST_API_KEY); const address = module.exports = {} address.create = async (name, street1, street2, city, state, zip, country, phone) => { const epAddress = new easypost.Address({ name, street1, street2, city, state, zip, country, phone, verify: ['delivery'] }) await epAddress.save() const {success} = epAddress.verifications.delivery if (!success) console.error(`Could not verify address: ${epAddress.id}`) const query = { text: 'select * from sos.create_address($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)', values: [ epAddress.name, epAddress.company, epAddress.street1, epAddress.street2, epAddress.city, epAddress.state, epAddress.zip, epAddress.country, epAddress.phone, epAddress.id, !!success ] } debug(query) const {rows} = await pg.query(query) return joinjs.map(rows, mappings, 'addressMap', 'address_')[0] } address.findByUUID = async (address_uuid, user_uuid) => dbUtil.executeQuery({ query: { text: ` select * from sos.v_order where address_uuid = $1 and order_user_uuid = $2;`, values: [ address_uuid, user_uuid ] }, returnType: 'address', single: true }) address.findAllForUser = async (user_uuid) => dbUtil.executeQuery({ query: { text: ` select * from sos.v_order where order_user_uuid = $1 and transaction_payment_state = 'completed';`, values: [ user_uuid ] }, returnType: 'address' })