|
| 1 | +import type { Buffer } from 'node:buffer' |
| 2 | +import { ACCEPTED_FILE_TYPES, MAX_FILE_SIZE } from '#shared/services/file' |
1 | 3 | import { repository } from '@roll-stack/database' |
2 | 4 | import xlsx from 'node-xlsx' |
3 | 5 |
|
| 6 | +interface MultiPartData { |
| 7 | + data: Buffer |
| 8 | + name?: string |
| 9 | + filename?: string |
| 10 | + type?: string |
| 11 | +} |
| 12 | + |
4 | 13 | export default defineEventHandler(async (event) => { |
5 | 14 | try { |
6 | | - const logger = useLogger('kitchen-revenue-iiko-daily') |
7 | | - |
8 | 15 | const files = await readMultipartFormData(event) |
9 | | - const file = files?.[0] |
10 | | - if (!files?.length || !file) { |
| 16 | + if (!files?.length) { |
11 | 17 | throw createError({ |
12 | 18 | statusCode: 400, |
13 | | - message: 'Missing file', |
| 19 | + message: 'Missing files', |
14 | 20 | }) |
15 | 21 | } |
16 | 22 |
|
17 | | - const maxFileSize = 20 * 1024 * 1024 // 20MB |
18 | | - if (file.data.length > maxFileSize) { |
19 | | - throw createError({ |
20 | | - statusCode: 413, |
21 | | - message: 'File too large', |
22 | | - }) |
23 | | - } |
| 23 | + let rowsUpdated = 0 |
| 24 | + const errors: string[] = [] |
24 | 25 |
|
25 | | - const allowedMimeTypes = [ |
26 | | - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', |
27 | | - 'application/vnd.ms-excel', |
28 | | - ] |
29 | | - if (file.type && !allowedMimeTypes.includes(file.type)) { |
30 | | - throw createError({ |
31 | | - statusCode: 400, |
32 | | - message: 'Invalid file type', |
33 | | - }) |
| 26 | + for (const file of files) { |
| 27 | + const res = await parseFileAndUpdateData(file) |
| 28 | + rowsUpdated += res.rowsUpdated |
| 29 | + errors.push(...res.errors) |
34 | 30 | } |
35 | 31 |
|
36 | | - const workSheetsFromFile = xlsx.parse(file.data.buffer) |
37 | | - if (!workSheetsFromFile[0]) { |
38 | | - throw createError({ |
39 | | - statusCode: 404, |
40 | | - message: 'File not found', |
41 | | - }) |
| 32 | + return { |
| 33 | + ok: true, |
| 34 | + result: { |
| 35 | + rowsUpdated, |
| 36 | + errors, |
| 37 | + }, |
42 | 38 | } |
| 39 | + } catch (error) { |
| 40 | + throw errorResolver(error) |
| 41 | + } |
| 42 | +}) |
43 | 43 |
|
44 | | - const data = workSheetsFromFile[0].data |
45 | | - const dateRow = data[2] // 3rd row |
46 | | - if (!dateRow || typeof dateRow[0] !== 'string' || !dateRow[0].startsWith('Дата')) { |
47 | | - throw createError({ |
48 | | - statusCode: 400, |
49 | | - message: 'Invalid date', |
50 | | - }) |
51 | | - } |
| 44 | +async function parseFileAndUpdateData(file: MultiPartData) { |
| 45 | + const logger = useLogger('kitchen-revenue-iiko-daily') |
52 | 46 |
|
53 | | - const dateMatch = dateRow[0].match(/Дата:\s*(\d{1,2})\.(\d{1,2})\.(\d{4})/) |
54 | | - if (!dateMatch) { |
55 | | - throw createError({ |
56 | | - statusCode: 400, |
57 | | - message: 'Invalid date format. Expected "Дата: DD.MM.YYYY"', |
58 | | - }) |
59 | | - } |
| 47 | + if (file.data.length > MAX_FILE_SIZE) { |
| 48 | + throw createError({ |
| 49 | + statusCode: 413, |
| 50 | + message: 'File too large', |
| 51 | + }) |
| 52 | + } |
60 | 53 |
|
61 | | - const [, day, month, year] = dateMatch |
62 | | - const dateOnly = `${year}-${month?.padStart(2, '0')}-${day?.padStart(2, '0')}` |
63 | | - const date = new Date(`${dateOnly}T12:00:00.000Z`) |
| 54 | + if (file.type && !ACCEPTED_FILE_TYPES.includes(file.type)) { |
| 55 | + throw createError({ |
| 56 | + statusCode: 400, |
| 57 | + message: 'Invalid file type', |
| 58 | + }) |
| 59 | + } |
64 | 60 |
|
65 | | - if (Number.isNaN(date.getTime())) { |
66 | | - throw createError({ |
67 | | - statusCode: 400, |
68 | | - message: 'Invalid date values', |
69 | | - }) |
70 | | - } |
| 61 | + const workSheetsFromFile = xlsx.parse(file.data.buffer) |
| 62 | + if (!workSheetsFromFile[0]) { |
| 63 | + throw createError({ |
| 64 | + statusCode: 404, |
| 65 | + message: 'File not found', |
| 66 | + }) |
| 67 | + } |
71 | 68 |
|
72 | | - // Remove first 4 rows and last row |
73 | | - const dataRows = data.slice(4, data.length - 1) |
74 | | - if (!dataRows) { |
75 | | - throw createError({ |
76 | | - statusCode: 400, |
77 | | - message: 'Invalid data', |
78 | | - }) |
79 | | - } |
| 69 | + const data = workSheetsFromFile[0].data |
| 70 | + const dateRow = data[2] // 3rd row |
| 71 | + if (!dateRow || typeof dateRow[0] !== 'string' || !dateRow[0].startsWith('Дата')) { |
| 72 | + throw createError({ |
| 73 | + statusCode: 400, |
| 74 | + message: 'Invalid date', |
| 75 | + }) |
| 76 | + } |
80 | 77 |
|
81 | | - const parsedKitchens: { name: string, total: number }[] = [] |
| 78 | + const dictionary = data[3] |
| 79 | + if (!dictionary) { |
| 80 | + throw createError({ |
| 81 | + statusCode: 400, |
| 82 | + message: 'Invalid dictionary', |
| 83 | + }) |
| 84 | + } |
82 | 85 |
|
83 | | - for (const row of dataRows) { |
84 | | - const name = row[2] // 3rd column |
85 | | - const total = row[4] // 5th column |
| 86 | + const indexOfName = dictionary.indexOf('Группа') |
| 87 | + const indexOfTotal = dictionary.indexOf('Сумма со скидкой, р. Всего') |
| 88 | + if (!dictionary || indexOfName < 0 || indexOfTotal < 0) { |
| 89 | + throw createError({ |
| 90 | + statusCode: 400, |
| 91 | + message: 'Invalid dictionary', |
| 92 | + }) |
| 93 | + } |
86 | 94 |
|
87 | | - if (typeof name !== 'string' || typeof total !== 'number') { |
88 | | - continue |
89 | | - } |
| 95 | + const dateMatch = dateRow[0].match(/Дата:\s*(\d{1,2})\.(\d{1,2})\.(\d{4})/) |
| 96 | + if (!dateMatch) { |
| 97 | + throw createError({ |
| 98 | + statusCode: 400, |
| 99 | + message: 'Invalid date format. Expected "Дата: DD.MM.YYYY"', |
| 100 | + }) |
| 101 | + } |
90 | 102 |
|
91 | | - parsedKitchens.push({ |
92 | | - name, |
93 | | - total, |
94 | | - }) |
| 103 | + const [, day, month, year] = dateMatch |
| 104 | + const dateOnly = `${year}-${month?.padStart(2, '0')}-${day?.padStart(2, '0')}` |
| 105 | + const date = new Date(`${dateOnly}T12:00:00.000Z`) |
| 106 | + |
| 107 | + if (Number.isNaN(date.getTime())) { |
| 108 | + throw createError({ |
| 109 | + statusCode: 400, |
| 110 | + message: 'Invalid date values', |
| 111 | + }) |
| 112 | + } |
| 113 | + |
| 114 | + // Remove first 4 rows and last row |
| 115 | + const dataRows = data.slice(4, data.length - 1) |
| 116 | + if (!dataRows) { |
| 117 | + throw createError({ |
| 118 | + statusCode: 400, |
| 119 | + message: 'Invalid data', |
| 120 | + }) |
| 121 | + } |
| 122 | + |
| 123 | + const parsedKitchens: { name: string, total: number }[] = [] |
| 124 | + |
| 125 | + for (const row of dataRows) { |
| 126 | + const name = row[indexOfName] |
| 127 | + const total = row[indexOfTotal] |
| 128 | + |
| 129 | + if (typeof name !== 'string' || typeof total !== 'number') { |
| 130 | + continue |
95 | 131 | } |
96 | 132 |
|
97 | | - // Every kitchen: find in DB and add amount for this day |
98 | | - const kitchens = await repository.kitchen.list() |
99 | | - let rowsUpdated = 0 |
100 | | - const errors: string[] = [] |
| 133 | + parsedKitchens.push({ |
| 134 | + name, |
| 135 | + total, |
| 136 | + }) |
| 137 | + } |
101 | 138 |
|
102 | | - for (const kitchen of parsedKitchens) { |
103 | | - const found = kitchens.find((k) => k.iikoAlias === kitchen.name) |
104 | | - if (found) { |
105 | | - // Create or update |
106 | | - const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date) |
107 | | - if (!revenue) { |
108 | | - await repository.kitchen.createRevenue({ |
109 | | - kitchenId: found.id, |
110 | | - date: dateOnly, |
111 | | - total: kitchen.total, |
112 | | - }) |
113 | | - } else { |
114 | | - await repository.kitchen.updateRevenue(revenue.id, { |
115 | | - total: kitchen.total, |
116 | | - }) |
117 | | - } |
118 | | - |
119 | | - rowsUpdated++ |
120 | | - continue |
| 139 | + // Every kitchen: find in DB and add amount for this day |
| 140 | + const kitchens = await repository.kitchen.list() |
| 141 | + let rowsUpdated = 0 |
| 142 | + const errors: string[] = [] |
| 143 | + |
| 144 | + for (const kitchen of parsedKitchens) { |
| 145 | + const found = kitchens.find((k) => k.iikoAlias === kitchen.name) |
| 146 | + if (found) { |
| 147 | + // Create or update |
| 148 | + const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date) |
| 149 | + if (!revenue) { |
| 150 | + await repository.kitchen.createRevenue({ |
| 151 | + kitchenId: found.id, |
| 152 | + date: dateOnly, |
| 153 | + total: kitchen.total, |
| 154 | + }) |
| 155 | + } else { |
| 156 | + await repository.kitchen.updateRevenue(revenue.id, { |
| 157 | + total: kitchen.total, |
| 158 | + }) |
121 | 159 | } |
122 | 160 |
|
123 | | - logger.warn(`Kitchen "${kitchen.name}" from file not found`) |
124 | | - errors.push(`"${kitchen.name}" не найдена.`) |
| 161 | + rowsUpdated++ |
| 162 | + continue |
125 | 163 | } |
126 | 164 |
|
127 | | - logger.log(rowsUpdated, date, parsedKitchens) |
| 165 | + logger.warn(`Kitchen "${kitchen.name}" from file not found`) |
| 166 | + errors.push(`"${kitchen.name}" не найдена.`) |
| 167 | + } |
128 | 168 |
|
129 | | - return { |
130 | | - ok: true, |
131 | | - result: { |
132 | | - rowsUpdated, |
133 | | - errors, |
134 | | - }, |
135 | | - } |
136 | | - } catch (error) { |
137 | | - throw errorResolver(error) |
| 169 | + logger.log(rowsUpdated, date, parsedKitchens) |
| 170 | + |
| 171 | + return { |
| 172 | + rowsUpdated, |
| 173 | + errors, |
138 | 174 | } |
139 | | -}) |
| 175 | +} |
0 commit comments