-
Notifications
You must be signed in to change notification settings - Fork 0
feat: upload several files #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
248 changes: 142 additions & 106 deletions
248
apps/web-app/server/api/kitchen/revenue/iiko-daily.post.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,139 +1,175 @@ | ||
| import type { Buffer } from 'node:buffer' | ||
| import { ACCEPTED_FILE_TYPES, MAX_FILE_SIZE } from '#shared/services/file' | ||
| import { repository } from '@roll-stack/database' | ||
| import xlsx from 'node-xlsx' | ||
|
|
||
| interface MultiPartData { | ||
| data: Buffer | ||
| name?: string | ||
| filename?: string | ||
| type?: string | ||
| } | ||
|
|
||
| export default defineEventHandler(async (event) => { | ||
| try { | ||
| const logger = useLogger('kitchen-revenue-iiko-daily') | ||
|
|
||
| const files = await readMultipartFormData(event) | ||
| const file = files?.[0] | ||
| if (!files?.length || !file) { | ||
| if (!files?.length) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Missing file', | ||
| message: 'Missing files', | ||
| }) | ||
| } | ||
|
|
||
| const maxFileSize = 20 * 1024 * 1024 // 20MB | ||
| if (file.data.length > maxFileSize) { | ||
| throw createError({ | ||
| statusCode: 413, | ||
| message: 'File too large', | ||
| }) | ||
| } | ||
| let rowsUpdated = 0 | ||
| const errors: string[] = [] | ||
|
|
||
| const allowedMimeTypes = [ | ||
| 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', | ||
| 'application/vnd.ms-excel', | ||
| ] | ||
| if (file.type && !allowedMimeTypes.includes(file.type)) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid file type', | ||
| }) | ||
| for (const file of files) { | ||
| const res = await parseFileAndUpdateData(file) | ||
| rowsUpdated += res.rowsUpdated | ||
| errors.push(...res.errors) | ||
| } | ||
|
|
||
| const workSheetsFromFile = xlsx.parse(file.data.buffer) | ||
| if (!workSheetsFromFile[0]) { | ||
| throw createError({ | ||
| statusCode: 404, | ||
| message: 'File not found', | ||
| }) | ||
| return { | ||
| ok: true, | ||
| result: { | ||
| rowsUpdated, | ||
| errors, | ||
| }, | ||
| } | ||
| } catch (error) { | ||
| throw errorResolver(error) | ||
| } | ||
| }) | ||
|
|
||
| const data = workSheetsFromFile[0].data | ||
| const dateRow = data[2] // 3rd row | ||
| if (!dateRow || typeof dateRow[0] !== 'string' || !dateRow[0].startsWith('Дата')) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid date', | ||
| }) | ||
| } | ||
| async function parseFileAndUpdateData(file: MultiPartData) { | ||
| const logger = useLogger('kitchen-revenue-iiko-daily') | ||
|
|
||
| const dateMatch = dateRow[0].match(/Дата:\s*(\d{1,2})\.(\d{1,2})\.(\d{4})/) | ||
| if (!dateMatch) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid date format. Expected "Дата: DD.MM.YYYY"', | ||
| }) | ||
| } | ||
| if (file.data.length > MAX_FILE_SIZE) { | ||
| throw createError({ | ||
| statusCode: 413, | ||
| message: 'File too large', | ||
| }) | ||
| } | ||
|
|
||
| const [, day, month, year] = dateMatch | ||
| const dateOnly = `${year}-${month?.padStart(2, '0')}-${day?.padStart(2, '0')}` | ||
| const date = new Date(`${dateOnly}T12:00:00.000Z`) | ||
| if (file.type && !ACCEPTED_FILE_TYPES.includes(file.type)) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid file type', | ||
| }) | ||
| } | ||
|
|
||
| if (Number.isNaN(date.getTime())) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid date values', | ||
| }) | ||
| } | ||
| const workSheetsFromFile = xlsx.parse(file.data.buffer) | ||
| if (!workSheetsFromFile[0]) { | ||
| throw createError({ | ||
| statusCode: 404, | ||
| message: 'File not found', | ||
| }) | ||
| } | ||
|
|
||
| // Remove first 4 rows and last row | ||
| const dataRows = data.slice(4, data.length - 1) | ||
| if (!dataRows) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid data', | ||
| }) | ||
| } | ||
| const data = workSheetsFromFile[0].data | ||
| const dateRow = data[2] // 3rd row | ||
| if (!dateRow || typeof dateRow[0] !== 'string' || !dateRow[0].startsWith('Дата')) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid date', | ||
| }) | ||
| } | ||
|
|
||
| const parsedKitchens: { name: string, total: number }[] = [] | ||
| const dictionary = data[3] | ||
| if (!dictionary) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid dictionary', | ||
| }) | ||
| } | ||
|
|
||
| for (const row of dataRows) { | ||
| const name = row[2] // 3rd column | ||
| const total = row[4] // 5th column | ||
| const indexOfName = dictionary.indexOf('Группа') | ||
| const indexOfTotal = dictionary.indexOf('Сумма со скидкой, р. Всего') | ||
| if (!dictionary || indexOfName < 0 || indexOfTotal < 0) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid dictionary', | ||
| }) | ||
| } | ||
|
|
||
| if (typeof name !== 'string' || typeof total !== 'number') { | ||
| continue | ||
| } | ||
| const dateMatch = dateRow[0].match(/Дата:\s*(\d{1,2})\.(\d{1,2})\.(\d{4})/) | ||
| if (!dateMatch) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid date format. Expected "Дата: DD.MM.YYYY"', | ||
| }) | ||
| } | ||
|
|
||
| parsedKitchens.push({ | ||
| name, | ||
| total, | ||
| }) | ||
| const [, day, month, year] = dateMatch | ||
| const dateOnly = `${year}-${month?.padStart(2, '0')}-${day?.padStart(2, '0')}` | ||
| const date = new Date(`${dateOnly}T12:00:00.000Z`) | ||
|
|
||
| if (Number.isNaN(date.getTime())) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid date values', | ||
| }) | ||
| } | ||
|
|
||
| // Remove first 4 rows and last row | ||
| const dataRows = data.slice(4, data.length - 1) | ||
| if (!dataRows) { | ||
| throw createError({ | ||
| statusCode: 400, | ||
| message: 'Invalid data', | ||
| }) | ||
| } | ||
|
|
||
| const parsedKitchens: { name: string, total: number }[] = [] | ||
|
|
||
| for (const row of dataRows) { | ||
| const name = row[indexOfName] | ||
| const total = row[indexOfTotal] | ||
|
|
||
| if (typeof name !== 'string' || typeof total !== 'number') { | ||
| continue | ||
| } | ||
|
|
||
| // Every kitchen: find in DB and add amount for this day | ||
| const kitchens = await repository.kitchen.list() | ||
| let rowsUpdated = 0 | ||
| const errors: string[] = [] | ||
| parsedKitchens.push({ | ||
| name, | ||
| total, | ||
| }) | ||
| } | ||
|
|
||
| for (const kitchen of parsedKitchens) { | ||
| const found = kitchens.find((k) => k.iikoAlias === kitchen.name) | ||
| if (found) { | ||
| // Create or update | ||
| const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date) | ||
| if (!revenue) { | ||
| await repository.kitchen.createRevenue({ | ||
| kitchenId: found.id, | ||
| date: dateOnly, | ||
| total: kitchen.total, | ||
| }) | ||
| } else { | ||
| await repository.kitchen.updateRevenue(revenue.id, { | ||
| total: kitchen.total, | ||
| }) | ||
| } | ||
|
|
||
| rowsUpdated++ | ||
| continue | ||
| // Every kitchen: find in DB and add amount for this day | ||
| const kitchens = await repository.kitchen.list() | ||
| let rowsUpdated = 0 | ||
| const errors: string[] = [] | ||
|
|
||
| for (const kitchen of parsedKitchens) { | ||
| const found = kitchens.find((k) => k.iikoAlias === kitchen.name) | ||
| if (found) { | ||
| // Create or update | ||
| const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date) | ||
| if (!revenue) { | ||
| await repository.kitchen.createRevenue({ | ||
| kitchenId: found.id, | ||
| date: dateOnly, | ||
| total: kitchen.total, | ||
| }) | ||
| } else { | ||
| await repository.kitchen.updateRevenue(revenue.id, { | ||
| total: kitchen.total, | ||
| }) | ||
| } | ||
|
|
||
| logger.warn(`Kitchen "${kitchen.name}" from file not found`) | ||
| errors.push(`"${kitchen.name}" не найдена.`) | ||
| rowsUpdated++ | ||
| continue | ||
| } | ||
|
|
||
| logger.log(rowsUpdated, date, parsedKitchens) | ||
| logger.warn(`Kitchen "${kitchen.name}" from file not found`) | ||
| errors.push(`"${kitchen.name}" не найдена.`) | ||
| } | ||
|
|
||
| return { | ||
| ok: true, | ||
| result: { | ||
| rowsUpdated, | ||
| errors, | ||
| }, | ||
| } | ||
| } catch (error) { | ||
| throw errorResolver(error) | ||
| logger.log(rowsUpdated, date, parsedKitchens) | ||
|
|
||
| return { | ||
| rowsUpdated, | ||
| errors, | ||
| } | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider adding database transaction support for better error handling.
Each file's database operations are not wrapped in a transaction. If an error occurs partway through processing a file's data, some records might be updated while others aren't, leading to inconsistent state.
Consider wrapping the database operations for each file in a transaction:
for (const kitchen of parsedKitchens) { const found = kitchens.find((k) => k.iikoAlias === kitchen.name) if (found) { + // Wrap in transaction if supported by your repository + await repository.transaction(async (tx) => { const revenue = await repository.kitchen.findRevenueByKitchenAndDate(found.id, date) if (!revenue) { await repository.kitchen.createRevenue({ kitchenId: found.id, date: dateOnly, total: kitchen.total, }) } else { await repository.kitchen.updateRevenue(revenue.id, { total: kitchen.total, }) } + }) rowsUpdated++ continue }📝 Committable suggestion
🤖 Prompt for AI Agents