-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
396 lines (328 loc) · 9.34 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
const fs = require('fs')
const path = require('path')
const puppeteer = require('puppeteer')
const _ = require('lodash')
const csvToJson = require('csvtojson')
const maxMessageLength = 250
const borderColor = 'pink'
const halloweenBorderColor = 'darkorange'
const christmasBorderColor = 'forestgreen'
const textColor = 'black'
const date = new Date().toISOString().split('.')[0].replace(/:/g, '-')
const messagesPdfName = `hey-sweetie-messages_${date}.pdf`
const postageLabelsPdfName = `hey-sweetie-address-labels_${date}.pdf`
const messagesPdfOptions = {
format: 'A4',
displayHeaderFooter: false,
margin: {
top: '15px',
right: '15px',
bottom: '15px',
left: '15px',
},
path: path.join(__dirname, 'pdf', messagesPdfName),
}
const postageLabelsPdfOptions = {
...messagesPdfOptions,
margin: {
top: '45px',
right: '12px',
bottom: '45px',
left: '12px',
},
path: path.join(__dirname, 'pdf', postageLabelsPdfName),
}
const style = `
<style>
@font-face {
font-family: "Lemon Yellow Sun";
src: url("data:application/x-font-opentype;charset=utf-8;base64,${fs
.readFileSync(
path.resolve(__dirname, './fonts/DK_Lemon_Yellow_Sun.otf')
)
.toString('base64')}") format("opentype");
}
body {
font-family: 'Lemon Yellow Sun';
-webkit-print-color-adjust: exact;
margin: 0;
padding: 0;
}
@page {
size: A4;
}
.page {
height: 100vh;
display: grid;
column-gap: 30px;
row-gap: 30px;
grid-template-rows: repeat(3, 300px);
grid-template-columns: 1fr 1fr;
justify-items: stretch;
align-items: stretch;
margin: 0;
padding: 0;
box-sizing: border-box;
page-break-after: always;
}
</style>
`
try {
createPDF()
} catch (e) {
console.log(e)
}
const chunkArray = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
)
const createMessagesHtml = (orders) => {
// Only use orders that have a personalised message
orders = orders.filter((order) => !!order.message)
// Chunk orders into groups of 6, so that 6 messages are displayed per page
const pages = chunkArray(orders, 6)
console.log(`${orders.length} messages found on ${pages.length} pages...`)
const html = `
${style}
<style>
.box {
border: 10px solid ${borderColor};
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
box-sizing: border-box;
padding: 24px;
}
.box.halloween {
border-color: ${halloweenBorderColor};
}
.box.christmas {
border-color: ${christmasBorderColor};
}
h1 {
color: ${textColor};
font-weight: normal;
white-space: pre-line;
}
</style>
${pages
.map(
(page) => `
<div class="page">
${page
.map((order) => {
const minFontSize = 1.25
const maxFontSize = 3
// Replace multiple linebreaks with a single linebreak
// TODO: How do the linebreaks work in Wix and the bulk orders?
const message = _.unescape(
order.message.replace(/(\r\n|\n){2,}/g, '\r\n')
)
// Count the number of line breaks to help guesstimate to message length
const lineBreaks = message.match(/(\r\n|\n)/g)
const lineBreakCount = lineBreaks ? lineBreaks.length : 0
const messageLength = Math.min(
maxMessageLength,
message.length + 15 * lineBreakCount
)
const fontSize = Math.max(
minFontSize,
Math.min(
((maxMessageLength - messageLength) / maxMessageLength) *
(maxFontSize - minFontSize) +
minFontSize,
maxFontSize
)
)
return `
<div class="box ${
typeof order.itemName === 'string' &&
order.itemName.toLowerCase().includes('christmas chocolate ')
? 'christmas'
: ''
}">
<h1 style="font-size: ${fontSize}em">${message}</h1>
</div>
`
})
.join('')}
</div>
`
)
.join('')}
`
return html
}
const createAddressLabel = (order) =>
[
order['name'],
order['address1'],
order['address2'],
order['address3'],
order['address4'],
order['postcode'],
]
.filter(Boolean)
.join('\n')
// Creates a new item in the array for each order with a quantity of more than 1
const reduceMultipleQuantityOrders = (allOrders, order) => {
const quantity = parseInt(order.quantity, 10) || 1
return allOrders.concat(Array(quantity).fill(order))
}
const createPostageLabelsHtml = (orders) => {
// Chunk orders into groups of 14, so that 14 labels are displayed per page
const pages = chunkArray(orders.map(createAddressLabel), 14)
console.log(
`${orders.length} postage labels found on ${pages.length} pages...`
)
const html = `
${style}
<style>
.page {
height: 100%;
column-gap: 10px;
row-gap: 0px;
grid-template-rows: repeat(7, 1fr);
}
.box {
min-height: 0;
display: flex;
align-items: center;
justify-content: center;
text-align: left;
box-sizing: border-box;
padding-left: 16px;
padding-right: 16px;
}
h4 {
font-family: "Segoe UI", Arial;
color: ${textColor};
font-weight: normal;
white-space: pre-line;
}
</style>
${pages
.map(
(page) => `
<div class="page">
${page
.map((address) => {
return `
<div class="box">
<h4>${address}</h4>
</div>
`
})
.join('')}
</div>
`
)
.join('')}
`
return html
}
const isAwaitingFulfillment = (order, origin) => {
if (origin === 'wix') {
return order.Fulfillment === 'notFulfilled'
}
if (origin === 'etsy') {
return !order['Date Posted']
}
return true
}
// Check against some random fields unique to each website to figure out the service used
const getOrderOrigin = (order) => {
if (order['Transaction ID']) {
return 'etsy'
}
if (!!order['Order #']) {
return 'wix'
}
return 'bulk'
}
const stripMessageHelpText = (message, origin) => {
if (!message) {
return undefined
}
// Etsy and Wix both prepend the help text to the message followed by ':'
const match = message.match(
/(Personalisation|details.|for the gift card):(.+)/s
)
if (match && match.length) {
return match[2] // Second capturing group of the regular expression i.e. the message after the colon
}
return message
}
// Make order data consistent regardless of whether it's from wix, etsy or the bulk csv
const formatOrder = (o) => {
const origin = getOrderOrigin(o)
// Delete wix state (ENG, SCT, WAL blah) and remove inverted commas from zip
if (origin === 'wix') {
o['Delivery State'] = "";
o['Delivery Zip Code'] = o['Delivery Zip Code'].replace(/\"/g,"");
}
return {
name: o['Delivery Name'] || o['Delivery Customer'] || o.name,
address1:
o['Delivery Address1'] || o['Delivery Street Name&Number'] || o.address1,
address2: o['Delivery Address2'] || o.address2,
address3: o['Delivery City'] || o['Delivery City'] || o.address3,
address4: o['Delivery State'] || o.address4,
postcode: o['Delivery Zipcode'] || o['Delivery Zip Code'] || o.postcode,
message: stripMessageHelpText(
o.Variations || o["Item's Custom Text"] || o.message,
origin
),
itemName: o['Item Name'] || o['Item\'s Name'],
awaitingFulfillment: isAwaitingFulfillment(o, origin),
origin,
quantity: o.Quantity || o.Qty || o.quantity || 1,
}
}
async function createPDF() {
const filePath = process.argv[2]
if (!filePath) {
throw new Error("A csv file wasn't specified")
}
console.log('')
console.log('Creating those PDFs...')
console.log('Using all unfilfilled orders...')
let orders = await csvToJson().fromFile(filePath)
orders = orders
.map(formatOrder)
.filter((order) => order.awaitingFulfillment)
.reduce(reduceMultipleQuantityOrders, [])
if (!orders.length) {
console.log('No orders were found for printing! :(')
return
}
console.log(`${orders.length} orders to print`)
const browser = await puppeteer.launch({
args: ['--no-sandbox'],
headless: true,
})
const page = await browser.newPage()
console.log('')
// Create personalised messages pdf
const messagesHtml = createMessagesHtml(orders)
await page.setContent(messagesHtml, { waitUntil: 'networkidle0' })
await page.pdf(messagesPdfOptions)
console.log(`Personalised messages done! ${messagesPdfName} created`)
console.log('')
// Create address labels pdf
const postageLabelsHtml = createPostageLabelsHtml(orders)
await page.setContent(postageLabelsHtml, { waitUntil: 'networkidle0' })
await page.pdf(postageLabelsPdfOptions)
console.log(`Postage labels done! ${postageLabelsPdfName} created`)
await browser.close()
console.log(`
(\\ (\\
\\_O \\_O
_____\\/)_____ _____\\/)_____
~~~~~~~~~~~~\`----\\----'~~~~~~~ ~\`----\\----'~
ds/jhs ~~~~ ~~~~ \\ ~~~~~~ ~~~ ~~~~~ \\ ~~~~~
`)
console.log('All done, ship them sweeties yo!')
}