Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
164 lines (146 loc) · 6.62 KB
/
Copy pathutils.js
File metadata and controls
164 lines (146 loc) · 6.62 KB
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
// utils.js — helpers: logging, price parsing, file/CSV parsing, history
import chalk from 'chalk';
import path from 'path';
import fs from 'fs';
// ================================================================
// LOGGER
// ================================================================
const ts = () => chalk.gray(`[${new Date().toLocaleTimeString('vi-VN')}]`);
export const log = {
info: (msg) => console.log(`${ts()} ${chalk.blueBright('ℹ')} ${msg}`),
success: (msg) => console.log(`${ts()} ${chalk.greenBright('✅')} ${msg}`),
error: (msg) => console.log(`${ts()} ${chalk.redBright('❌')} ${msg}`),
warn: (msg) => console.log(`${ts()} ${chalk.yellowBright('⚠')} ${msg}`),
dryrun: (msg) => console.log(`${ts()} ${chalk.magentaBright('🧪')} ${msg}`),
step: (msg) => console.log(`\n${chalk.bgGreen.black.bold(` ${msg} `)}\n`),
divider: () => console.log(chalk.gray('─'.repeat(60))),
};
// ================================================================
// PRICE FORMAT — Vietnamese shorthand → full VND amount
// 500k → 500000 · 1m5 → 1500000 · 2.5m → 2500000 · 1tr2 → 1200000
// short numbers (≤ 5 digits) are treated as thousands: 120 → 120000
// ================================================================
export function formatPrice(raw) {
const s = String(raw).toLowerCase().trim().replace(/\s/g, '');
if (/^\d+(\.\d+)?k$/.test(s)) return Math.round(parseFloat(s) * 1_000).toString();
if (/^\d+\.\d+m$/.test(s)) return Math.round(parseFloat(s) * 1_000_000).toString();
if (/^\d+m\d*$/.test(s)) {
const [pre, post] = s.split('m');
return (parseInt(pre) * 1_000_000 + (post ? parseInt(post) * 100_000 : 0)).toString();
}
if (/^\d+(tr|t)\d*$/.test(s)) {
const p = s.replace('tr', 'm').replace(/^(\d+)t(\d*)$/, '$1m$2');
const [pre, post] = p.split('m');
return (parseInt(pre) * 1_000_000 + (post ? parseInt(post) * 100_000 : 0)).toString();
}
const num = parseInt(s);
if (isNaN(num)) return s;
return s.replace(/\D/g, '').length <= 5 ? (num * 1000).toString() : s;
}
// ================================================================
// FILE NAME → { maSP, gia } ("SP001 1m5.png" → SP001, 1500000)
// ================================================================
export function parseFileName(fileName, autoFormat = true) {
const base = path.basename(fileName, path.extname(fileName));
const parts = base.trim().split(/\s+/);
if (parts.length < 2) return null;
const maSP = parts[0];
const rawGia = parts[parts.length - 1];
const gia = autoFormat ? formatPrice(rawGia) : rawGia;
return { maSP, gia };
}
// ================================================================
// SCAN IMAGE FOLDER → product list
// ================================================================
export function scanImages(dir, autoFormat = true) {
if (!fs.existsSync(dir)) {
log.error(`Thư mục "${dir}" không tồn tại!`);
return [];
}
const exts = ['.png', '.jpg', '.jpeg'];
const files = fs.readdirSync(dir)
.filter(f => exts.includes(path.extname(f).toLowerCase()))
.sort();
const products = [];
for (const f of files) {
const parsed = parseFileName(f, autoFormat);
if (!parsed) {
log.warn(`Bỏ qua "${f}" — sai format (cần: MÃSP GIÁ.png)`);
continue;
}
products.push({ ...parsed, note: '', filePath: path.resolve(dir, f), fileName: f });
}
return products;
}
// ================================================================
// PARSE CSV — flexible headers (masp/code/id, gia/price, note/...)
// supports , ; | and tab as separators
// ================================================================
export function parseCSV(csvPath, autoFormat = true) {
if (!fs.existsSync(csvPath)) {
log.error(`File CSV "${csvPath}" không tồn tại!`);
return [];
}
const lines = fs.readFileSync(csvPath, 'utf-8')
.replace(/^/, '')
.split(/\r?\n/)
.map(l => l.trim())
.filter(Boolean);
if (lines.length < 2) return [];
const headers = lines[0].toLowerCase().split(/[,;|\t]/).map(h => h.trim());
const iCol = (names) => names.map(n => headers.indexOf(n)).find(i => i >= 0) ?? -1;
const colMaSP = iCol(['masp', 'ma_sp', 'mã sp', 'mã', 'id', 'code']);
const colGia = iCol(['gia', 'giá', 'price', 'giatien']);
const colNote = iCol(['note', 'ghichu', 'ghi chú', 'ghi_chu', 'mo_ta', 'mô tả']);
if (colMaSP < 0 || colGia < 0) {
log.error('CSV thiếu cột masp hoặc gia!');
return [];
}
const products = [];
for (let i = 1; i < lines.length; i++) {
const cells = lines[i].split(/[,;|\t]/).map(c => c.trim().replace(/^["']|["']$/g, ''));
const maSP = cells[colMaSP];
const rawGia = cells[colGia];
if (!maSP || !rawGia) continue;
const gia = autoFormat ? formatPrice(rawGia) : rawGia;
const note = colNote >= 0 ? (cells[colNote] || '') : '';
products.push({ maSP, gia, note, filePath: null, fileName: null });
}
return products;
}
// ================================================================
// MERGE images + CSV rows (matched by product code, case-insensitive)
// ================================================================
export function mergeImagesAndCSV(images, csvRows) {
if (!csvRows.length) return images;
if (!images.length) return csvRows;
const imgMap = new Map(images.map(p => [p.maSP.toLowerCase(), p]));
return csvRows.map(row => {
const img = imgMap.get(row.maSP.toLowerCase());
return { ...row, filePath: img?.filePath || null, fileName: img?.fileName || null };
});
}
// ================================================================
// TEMPLATE — "{maSP} | {note}" → "SP001 | New arrival"
// ================================================================
export function applyTemplate(template, maSP, gia, note) {
return (template || '{maSP} | {note}')
.replace(/\{maSP\}/g, maSP || '')
.replace(/\{gia\}/g, gia || '')
.replace(/\{note\}/g, note || '');
}
export function displayPrice(gia) {
const n = parseInt(gia);
return isNaN(n) ? gia : n.toLocaleString('vi-VN') + 'đ';
}
export const sleep = ms => new Promise(r => setTimeout(r, ms));
// ================================================================
// HISTORY — keeps the last 100 sessions in upload_history.json
// ================================================================
export function saveHistory(session, histFile = './upload_history.json') {
let history = [];
try { history = JSON.parse(fs.readFileSync(histFile, 'utf-8')); } catch {}
history.unshift(session);
if (history.length > 100) history.splice(100);
fs.writeFileSync(histFile, JSON.stringify(history, null, 2), 'utf-8');
}