Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
196 lines (170 loc) · 7.15 KB
/
Copy pathindex.js
File metadata and controls
196 lines (170 loc) · 7.15 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
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
#!/usr/bin/env node
// index.js — Auto Upload CLI
// Usage: node index.js [--yes]
import 'dotenv/config';
import puppeteer from 'puppeteer';
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import chalk from 'chalk';
import ora from 'ora';
import { log, scanImages, parseCSV, mergeImagesAndCSV, displayPrice, saveHistory } from './utils.js';
import { uploadOne } from './uploader.js';
// Allow relative file URLs such as file://./examples/mock-admin.html
function resolveUrl(url) {
if (url.startsWith('file://.')) return pathToFileURL(path.resolve(url.slice('file://'.length))).href;
return url;
}
const CONFIG = {
adminUrl: resolveUrl(process.env.ADMIN_URL || ''),
imagesDir: process.env.IMAGES_DIR || './images',
csvFile: process.env.CSV_FILE || '',
note: process.env.NOTE || '',
dataTemplate: process.env.DATA_TEMPLATE || '{maSP} | {note}',
delay: (parseFloat(process.env.DELAY) || 0) * 1000,
limit: parseInt(process.env.LIMIT) || 0,
dryRun: process.env.DRY_RUN === 'true',
headless: process.env.HEADLESS === 'true',
autoFormatPrice: process.env.AUTO_FORMAT_PRICE !== 'false',
chromePath: process.env.CHROME_PATH || undefined,
autoConfirm: process.argv.includes('--yes') || process.argv.includes('-y'),
};
function printBanner() {
console.log('\n' + chalk.bgGreen.black.bold(' AUTO UPLOAD CLI v2 '));
console.log(chalk.gray(' Node.js + Puppeteer\n'));
}
function validateConfig() {
const errors = [];
if (!CONFIG.adminUrl) errors.push('ADMIN_URL chưa được cấu hình trong .env');
if (!CONFIG.imagesDir && !CONFIG.csvFile) errors.push('Cần IMAGES_DIR hoặc CSV_FILE');
if (errors.length) {
errors.forEach(e => log.error(e));
console.log(chalk.yellow('\n💡 Copy .env.example thành .env rồi điền thông tin.\n'));
process.exit(1);
}
}
function loadProducts() {
let images = [];
let csvRows = [];
if (CONFIG.imagesDir && fs.existsSync(CONFIG.imagesDir)) {
images = scanImages(CONFIG.imagesDir, CONFIG.autoFormatPrice);
log.info(`Tìm thấy ${chalk.bold(images.length)} ảnh trong "${CONFIG.imagesDir}"`);
}
if (CONFIG.csvFile && fs.existsSync(CONFIG.csvFile)) {
csvRows = parseCSV(CONFIG.csvFile, CONFIG.autoFormatPrice);
log.info(`Đọc được ${chalk.bold(csvRows.length)} dòng từ CSV`);
}
let products = mergeImagesAndCSV(images, csvRows);
if (CONFIG.limit > 0) {
products = products.slice(0, CONFIG.limit);
log.info(`Giới hạn: ${chalk.bold(CONFIG.limit)} SP`);
}
return products;
}
function printProductList(products) {
log.divider();
console.log(chalk.bold(`\n📋 Danh sách ${products.length} sản phẩm sẽ upload:\n`));
products.forEach((p, i) => {
const hasImg = p.filePath ? chalk.green('🖼') : chalk.gray('—');
const note = p.note ? chalk.gray(` (${p.note})`) : '';
console.log(` ${chalk.gray(String(i + 1).padStart(3, '0'))}. ${hasImg} ${chalk.cyan.bold(p.maSP.padEnd(15))} ${chalk.yellow(displayPrice(p.gia))}${note}`);
});
console.log();
log.divider();
}
async function confirmRun(count) {
if (CONFIG.autoConfirm) return true;
const readline = await import('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ans = await new Promise(res => rl.question(chalk.yellow(`▶ Xác nhận upload ${count} sản phẩm? (y/n): `), a => { rl.close(); res(a); }));
return ['y', 'yes'].includes(ans.trim().toLowerCase());
}
async function main() {
printBanner();
validateConfig();
const products = loadProducts();
if (!products.length) {
log.error('Không có sản phẩm nào để upload!');
process.exit(1);
}
printProductList(products);
console.log(chalk.bold('\n⚙️ Cấu hình:\n'));
console.log(` Admin URL : ${chalk.cyan(CONFIG.adminUrl)}`);
console.log(` Template : ${chalk.cyan(CONFIG.dataTemplate)}`);
console.log(` Delay : ${chalk.cyan(CONFIG.delay / 1000 + 's')}`);
console.log(` Headless : ${chalk.cyan(CONFIG.headless)}`);
console.log(` Dry Run : ${CONFIG.dryRun ? chalk.magenta('BẬT — sẽ KHÔNG nhấn LƯU') : chalk.green('tắt')}`);
if (CONFIG.note) console.log(` Ghi chú : ${chalk.cyan(CONFIG.note)}`);
console.log();
if (!(await confirmRun(products.length))) {
log.warn('Đã huỷ.');
process.exit(0);
}
const spinner = ora('Đang mở Chrome...').start();
const browser = await puppeteer.launch({
headless: CONFIG.headless,
executablePath: CONFIG.chromePath,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--start-maximized'],
defaultViewport: CONFIG.headless ? { width: 1366, height: 768 } : null,
});
const page = await browser.newPage();
spinner.succeed('Chrome đã mở');
// Ctrl+C closes the browser cleanly
let stopped = false;
process.on('SIGINT', async () => {
if (stopped) return;
stopped = true;
log.warn('\nĐã nhận Ctrl+C — đang dừng...');
await browser.close().catch(() => {});
process.exit(0);
});
log.step(`BẮT ĐẦU UPLOAD — ${products.length} SẢN PHẨM`);
let successCount = 0;
let errorCount = 0;
const sessionResults = [];
const startTime = Date.now();
for (let i = 0; i < products.length; i++) {
if (stopped) break;
const product = products[i];
const idx = `[${i + 1}/${products.length}]`;
log.info(`${chalk.bold(idx)} ${chalk.cyan(product.maSP)} — ${displayPrice(product.gia)}`);
try {
await uploadOne(page, product, CONFIG);
CONFIG.dryRun ? log.dryrun(`${idx} DRY RUN OK: ${product.maSP}`) : log.success(`${idx} OK: ${chalk.bold(product.maSP)}`);
successCount++;
sessionResults.push({ maSP: product.maSP, status: 'success' });
} catch (err) {
log.error(`${idx} THẤT BẠI: ${product.maSP} — ${err.message}`);
errorCount++;
sessionResults.push({ maSP: product.maSP, status: 'failed', error: err.message });
}
const pct = Math.round(((i + 1) / products.length) * 100);
const fill = Math.round(pct / 5);
const bar = chalk.green('█'.repeat(fill)) + chalk.gray('░'.repeat(20 - fill));
console.log(` ${bar} ${pct}% ✅ ${successCount} ❌ ${errorCount}`);
}
const duration = Math.round((Date.now() - startTime) / 1000);
log.step('HOÀN THÀNH');
console.log(` ✅ Thành công : ${chalk.greenBright.bold(successCount)}`);
console.log(` ❌ Thất bại : ${chalk.redBright.bold(errorCount)}`);
console.log(` ⏱ Thời gian : ${chalk.gray(duration + 's')}`);
if (CONFIG.dryRun) console.log(` 🧪 Chế độ : ${chalk.magenta('DRY RUN')}`);
console.log();
saveHistory({
date: new Date().toISOString(),
site: CONFIG.adminUrl,
status: stopped ? 'stopped' : (CONFIG.dryRun ? 'dryrun' : 'completed'),
total: products.length,
success: successCount,
failed: errorCount,
duration,
products: sessionResults,
});
log.info('Đã lưu lịch sử vào upload_history.json');
await browser.close();
}
main().catch(err => {
log.error('Lỗi nghiêm trọng: ' + err.message);
console.error(err);
process.exit(1);
});