-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
291 lines (259 loc) · 8.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
require('dotenv').config()
import config from './config.js'
const EasyPost = require('@easypost/api')
const api = new EasyPost(process.env.EASYPOST_API_KEY)
const download = require('image-downloader')
const PDFDocument = require('pdfkit')
const parse = require('csv-parse')
const createCsvWriter = require('csv-writer').createObjectCsvWriter
const fs = require('fs')
const chalk = require('chalk')
import { transformAddress, savePdfToFile } from './utils/index.js'
const processedWriter = createCsvWriter({
path: './output/processed.csv',
// append: true,
header: [
{ id: 'order', title: 'ORDER NUMBER' },
{ id: 'quantity', title: 'QUANTITY' },
{ id: 'email', title: 'CUSTOMER EMAIL' },
{ id: 'trackingCode', title: 'TRACKING CODE' },
{ id: 'trackingUrl', title: 'URL' },
{ id: 'shippingService', title: 'SHIPPING SERVICE' },
{ id: 'shippingCost', title: 'SHIPPING COST' }
]
})
const unprocessedWriter = createCsvWriter({
path: './output/unprocessed.csv',
// append: true,
header: [
{ id: 'invoiceNumber', title: 'Invoice number' },
{ id: 'quantity', title: 'Quantity' },
{ id: 'customerName', title: 'Customer name' },
{ id: 'customerEmail', title: 'Customer email' },
{ id: 'orderStatus', title: 'Order status' },
{ id: 'shipToName', title: 'Ship to' },
{ id: 'street1', title: 'Shipping address' },
{ id: 'street2', title: 'Shipping address 2' },
{ id: 'city', title: 'Shipping address city' },
{ id: 'state', title: 'Shipping address province/state' },
{ id: 'zip', title: 'Shipping address postal code' },
{ id: 'country', title: 'Shipping address country' },
{ id: 'refundAmount', title: 'Refunds amount' },
{ id: 'error', title: 'Error' }
]
})
var currentIndex = 0
var rows = []
var doc = null
var currentBatch = 0
var labelsGenerated = 0
const batchAmount = config.batchAmount
// take a csv of orders, generate a printable pdf of shipping labels
// and export a csv of email addresses, names and tracking numbers
async function parseCSV(file) {
var rows = []
const reader = fs
.createReadStream(file)
.pipe(
parse({ columns: true, trim: true }).on('data', (data) => rows.push(data))
)
return new Promise((resolve, reject) => {
reader.on('end', () => resolve(rows)), reader.on('error', reject)
})
}
function updateBatch() {
process.stdout.write('Saving batch pdf... ')
return savePdfToFile(doc, `./labels/labels-${currentBatch}.pdf`).then(() => {
console.log('saved')
doc = new PDFDocument({ autoFirstPage: false })
currentBatch++
console.log(chalk.yellow(`\n--- Batch ${currentBatch} ---`))
})
}
function onComplete(index) {
console.log(`Processing ${index} orders complete.`)
savePdfToFile(doc)
}
function checkProgress(currentIndex, skipDelay) {
if (currentIndex === rows.length - 1) {
return onComplete(currentIndex)
}
return setTimeout(
() => {
if (
!skipDelay &&
currentIndex > 0 &&
labelsGenerated % batchAmount === 0
) {
return updateBatch().then(() => {
currentIndex++
return processRow(currentIndex)
})
} else {
currentIndex++
return processRow(currentIndex)
}
},
skipDelay ? 0 : 5000
)
}
function filterOrder(row) {
if (
row['Shipping address country'] !== 'US' ||
row['Order status'] !== 'Processed' ||
row['Refunds amount'] !== '0.00'
)
return false
return row
}
// return addressID
function verifyAddress(row) {
const toAddress = new api.Address({
verify: ['delivery'],
...transformAddress(row)
})
return toAddress
.save()
.then((result) => result)
.catch(console.log)
}
function onAddressError(order, errors) {
console.log(
chalk.red(
'❓ Address verification failed, skipping',
order['Invoice number']
)
)
unprocessedWriter.writeRecords([
{
invoiceNumber: order['Invoice number'],
quantity: order['Quantity'],
customerName: order['Customer name'],
customerEmail: order['Customer email'],
orderStatus: order['Order status'],
shipToName: order['Ship to'],
street1: order['Shipping address'],
street2: order['Shipping address 2'],
city: order['Shipping address city'],
state: order['Shipping address province/state'],
zip: order['Shipping address postal code'],
country: order['Shipping address country'],
refundAmount: order['Refunds amount'],
error: JSON.stringify(errors)
}
])
}
async function processRow(index) {
const row = rows[index]
const order = filterOrder(row)
if (order) {
const orderNumber = order['Invoice number']
console.log(chalk.green(`\n--- ${orderNumber} ---`))
process.stdout.write(`🏠 Verifying delivery address for ${orderNumber}... `)
const result = await verifyAddress(row)
if (!result.verifications.delivery.success) {
onAddressError(order, result.verifications.delivery.errors)
return checkProgress(index, false)
}
console.log('✅')
await processOrder(order, result.id)
return checkProgress(index, false)
}
console.log(
chalk.gray(
`Skipping Non-US order (${row['Shipping address country']}) ${row['Invoice number']} placed by ${row['Customer name']} <${row['Customer email']}>.`
)
)
return checkProgress(index, true)
}
async function processOrder(order, addressId) {
// calculate correct shipping rate
var baseItem = config.parcel
const orderQuantity = parseInt(order['Quantity'])
const tempParcel = {
...baseItem,
height: baseItem.height * orderQuantity,
weight: baseItem.weight * orderQuantity
}
const parcel = new api.Parcel(tempParcel)
// set up addresses
const fromAddress = new api.Address(config.fromAddress)
const customerEmail = order['Customer email']
const orderNumber = order['Invoice number']
const shipment = new api.Shipment({
to_address: addressId,
from_address: fromAddress,
parcel: parcel,
invoice_number: orderNumber,
options: {
special_rates_eligibility: 'USPS.MEDIAMAIL'
}
})
return shipment
.save()
.then((shipment) => {
console.log(
`📦 Lowest rate for parcel weighing ${tempParcel.weight}oz using ${
shipment.lowestRate().service
} is ${shipment.lowestRate().rate} ${shipment.lowestRate().currency}`
)
return shipment.buy(shipment.lowestRate())
})
.then((result) => {
return {
orderNumber: orderNumber,
quantity: orderQuantity,
customerEmail: customerEmail,
tracking: {
code: result.tracker.tracking_code,
url: result.tracker.public_url
},
service: {
type: result.selected_rate.service,
rate: result.selected_rate.rate
},
labelUrl: result.postage_label.label_url
}
})
.then((shipment) => {
return addLabelToPdf(orderNumber, shipment.labelUrl).then(() => {
labelsGenerated++
return shipment
})
})
.then((shipment) => {
processedWriter.writeRecords([
{
order: shipment.orderNumber,
quantity: shipment.quantity,
email: shipment.customerEmail,
trackingCode: shipment.tracking.code,
trackingUrl: shipment.tracking.url,
shippingService: shipment.service.type,
shippingCost: shipment.service.rate
}
])
})
.catch((error) => console.log(error))
}
function addLabelToPdf(orderNumber, labelUrl) {
return download
.image({ url: labelUrl, dest: `./labels/source/${orderNumber}.png` })
.then(({ filename }) => {
console.log(`⬇️ Label saved to ${filename}.\n`)
doc.addPage({ size: [4 * 72, 6 * 72], margin: 0 }).image(filename, {
fit: [4 * 72, 6 * 72],
align: 'center',
valign: 'center'
})
})
.catch((error) => console.log(error))
}
async function beginProcessing() {
rows = await parseCSV('./orders.csv')
doc = new PDFDocument({ autoFirstPage: false })
processRow(currentIndex)
}
beginProcessing()