Spaces:
Paused

shanshel6 commited on
Commit
8395368
ยท
1 Parent(s): 9b2bf5f

Release v1.0.32: Fix scraper navigation, logs, 500 error, and bump version

Browse files
This view is limited to 50 files because it contains too many changes. ย  See raw diff
Files changed (50) hide show
  1. android/app/build.gradle +2 -2
  2. check_server_start.js +22 -0
  3. debug_start.ps1 +8 -0
  4. package.json +1 -1
  5. run_db_fix.bat +4 -0
  6. run_server_simple.bat +4 -0
  7. server/check_node.js +1 -0
  8. server/check_products_cjs.cjs +55 -0
  9. server/check_products_error.js +46 -0
  10. server/check_products_simple.cjs +45 -0
  11. server/check_server_status.js +26 -0
  12. server/debug_api.js +22 -0
  13. server/debug_db_schema.js +75 -0
  14. server/fix_missing_column.js +45 -0
  15. server/force_add_column_direct.js +62 -0
  16. server/force_add_column_direct_v2.js +68 -0
  17. server/index.js +79 -21
  18. server/output.txt +0 -0
  19. server/pg_force_add.js +69 -0
  20. server/prisma/schema.prisma +1 -0
  21. server/prismaClient.js +23 -0
  22. server/repair_db_schema.js +39 -0
  23. server/run_fix.bat +2 -0
  24. server/run_scraper.bat +2 -0
  25. server/scripts/check_db_mojibake.js +46 -0
  26. server/scripts/fix_mojibake_db.js +143 -0
  27. server/scripts/part1.js +0 -0
  28. server/scripts/part2.js +158 -0
  29. server/scripts/part3.js +514 -0
  30. server/scripts/pinduoduo-scraper.bak +0 -0
  31. server/scripts/pinduoduo-scraper.js +0 -0
  32. server/services/aiService.js +30 -3
  33. server/simple_check.js +4 -0
  34. server/simple_file_write.js +9 -0
  35. server/simple_node_check.js +8 -0
  36. server/start_server.bat +4 -0
  37. server/test.js +1 -0
  38. server/test_db_query.js +46 -0
  39. server/verify_and_fix_column.js +75 -0
  40. server/verify_column_added.js +31 -0
  41. server/verify_fix.js +31 -0
  42. src/components/product/ProductActionSheet.tsx +3 -2
  43. src/components/product/ProductDescription.tsx +10 -9
  44. src/components/product/ProductInfo.tsx +3 -2
  45. src/components/product/ProductOptions.tsx +10 -6
  46. src/components/product/ProductSpecs.tsx +9 -8
  47. src/components/product/ReviewsSection.tsx +14 -10
  48. src/pages/AdminDashboard.tsx +1 -1
  49. src/pages/CheckoutPaymentAddress.tsx +0 -1
  50. src/pages/ProductDetails.tsx +1 -2
android/app/build.gradle CHANGED
@@ -7,8 +7,8 @@ android {
7
  applicationId "com.chinak.app"
8
  minSdkVersion rootProject.ext.minSdkVersion
9
  targetSdkVersion rootProject.ext.targetSdkVersion
10
- versionCode 41
11
- versionName "1.0.31"
12
  testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13
  }
14
 
 
7
  applicationId "com.chinak.app"
8
  minSdkVersion rootProject.ext.minSdkVersion
9
  targetSdkVersion rootProject.ext.targetSdkVersion
10
+ versionCode 42
11
+ versionName "1.0.32"
12
  testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
13
  }
14
 
check_server_start.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const http = require('http');
3
+
4
+ try {
5
+ fs.writeFileSync('check_status.txt', 'STARTING\n');
6
+ const server = http.createServer((req, res) => {
7
+ res.writeHead(200);
8
+ res.end('OK');
9
+ });
10
+
11
+ server.on('error', (err) => {
12
+ fs.appendFileSync('check_status.txt', 'ERROR: ' + err.message + '\n');
13
+ process.exit(1);
14
+ });
15
+
16
+ server.listen(5001, () => {
17
+ fs.appendFileSync('check_status.txt', 'LISTENING 5001\n');
18
+ console.log('Listening on 5001');
19
+ });
20
+ } catch (e) {
21
+ fs.writeFileSync('check_status.txt', 'CRASH: ' + e.message + '\n');
22
+ }
debug_start.ps1 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Start-Transcript -Path "debug_log.txt"
2
+ Write-Host "Starting node..."
3
+ try {
4
+ & node server/index.js
5
+ } catch {
6
+ Write-Host "Error: $_"
7
+ }
8
+ Stop-Transcript
package.json CHANGED
@@ -1,7 +1,7 @@
1
  {
2
  "name": "project",
3
  "private": true,
4
- "version": "1.0.31",
5
  "type": "module",
6
  "scripts": {
7
  "dev": "concurrently \"npm run dev:frontend\" \"npm run dev:backend\"",
 
1
  {
2
  "name": "project",
3
  "private": true,
4
+ "version": "1.0.32",
5
  "type": "module",
6
  "scripts": {
7
  "dev": "concurrently \"npm run dev:frontend\" \"npm run dev:backend\"",
run_db_fix.bat ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ @echo off
2
+ echo Running DB Fix... > db_fix_log.txt
3
+ cd server
4
+ node fix_mojibake_db.js >> ..\db_fix_log.txt 2>&1
run_server_simple.bat ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ @echo off
2
+ echo Starting server... > server_log.txt
3
+ cd server
4
+ node index.js >> ..\server_log.txt 2>&1
server/check_node.js ADDED
@@ -0,0 +1 @@
 
 
1
+ console.log("NODE IS WORKING");
server/check_products_cjs.cjs ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { PrismaClient } = require('@prisma/client');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ // Explicitly load .env
6
+ const envPath = path.join(__dirname, '.env');
7
+ if (fs.existsSync(envPath)) {
8
+ require('dotenv').config({ path: envPath });
9
+ }
10
+
11
+ const prisma = new PrismaClient();
12
+
13
+ async function check() {
14
+ try {
15
+ const where = {
16
+ isActive: true,
17
+ status: 'PUBLISHED'
18
+ };
19
+
20
+ console.log('Running query...');
21
+ const products = await prisma.product.findMany({
22
+ where,
23
+ select: {
24
+ id: true,
25
+ name: true,
26
+ price: true,
27
+ basePriceIQD: true,
28
+ image: true,
29
+ isFeatured: true,
30
+ domesticShippingFee: true,
31
+ deliveryTime: true,
32
+ variants: {
33
+ select: {
34
+ id: true,
35
+ combination: true,
36
+ price: true,
37
+ basePriceIQD: true,
38
+ image: true,
39
+ }
40
+ }
41
+ },
42
+ take: 20,
43
+ orderBy: { updatedAt: 'desc' }
44
+ });
45
+ console.log('Query success. Products found:', products.length);
46
+ fs.writeFileSync(path.join(__dirname, 'product_query_success.log'), JSON.stringify(products, null, 2));
47
+ } catch (error) {
48
+ console.error('Query failed:', error);
49
+ fs.writeFileSync(path.join(__dirname, 'product_query_error.log'), error.message + '\n' + error.stack);
50
+ } finally {
51
+ await prisma.$disconnect();
52
+ }
53
+ }
54
+
55
+ check();
server/check_products_error.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import prisma from './prismaClient.js';
2
+ import fs from 'fs';
3
+
4
+ async function check() {
5
+ try {
6
+ const where = {
7
+ isActive: true,
8
+ status: 'PUBLISHED'
9
+ };
10
+
11
+ console.log('Running query...');
12
+ const products = await prisma.product.findMany({
13
+ where,
14
+ select: {
15
+ id: true,
16
+ name: true,
17
+ price: true,
18
+ basePriceIQD: true,
19
+ image: true,
20
+ isFeatured: true,
21
+ domesticShippingFee: true,
22
+ deliveryTime: true,
23
+ variants: {
24
+ select: {
25
+ id: true,
26
+ combination: true,
27
+ price: true,
28
+ basePriceIQD: true,
29
+ image: true,
30
+ }
31
+ }
32
+ },
33
+ take: 20,
34
+ orderBy: { updatedAt: 'desc' }
35
+ });
36
+ console.log('Query success. Products found:', products.length);
37
+ fs.writeFileSync('server/product_query_success.log', JSON.stringify(products, null, 2));
38
+ } catch (error) {
39
+ console.error('Query failed:', error);
40
+ fs.writeFileSync('server/product_query_error.log', error.message + '\n' + error.stack);
41
+ } finally {
42
+ await prisma.$disconnect();
43
+ }
44
+ }
45
+
46
+ check();
server/check_products_simple.cjs ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { PrismaClient } = require('@prisma/client');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+
5
+ // Explicitly load .env
6
+ const envPath = path.join(__dirname, '.env');
7
+ if (fs.existsSync(envPath)) {
8
+ require('dotenv').config({ path: envPath });
9
+ }
10
+
11
+ const prisma = new PrismaClient();
12
+
13
+ async function check() {
14
+ try {
15
+ const where = {
16
+ isActive: true,
17
+ status: 'PUBLISHED'
18
+ };
19
+
20
+ // Test connection first
21
+ await prisma.$connect();
22
+
23
+ console.log('Running query...');
24
+ const products = await prisma.product.findMany({
25
+ where,
26
+ select: {
27
+ id: true,
28
+ name: true,
29
+ price: true,
30
+ basePriceIQD: true, // Potential issue?
31
+ domesticShippingFee: true, // Potential issue?
32
+ },
33
+ take: 1
34
+ });
35
+ console.log('Query success. Products found:', products.length);
36
+ fs.writeFileSync('check_products_output.log', 'SUCCESS: ' + JSON.stringify(products, null, 2));
37
+ } catch (error) {
38
+ console.error('Query failed:', error);
39
+ fs.writeFileSync('check_products_output.log', 'ERROR: ' + error.message + '\n' + error.stack);
40
+ } finally {
41
+ await prisma.$disconnect();
42
+ }
43
+ }
44
+
45
+ check();
server/check_server_status.js ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import http from 'http';
3
+ import fs from 'fs';
4
+
5
+ function check(url, name) {
6
+ return new Promise((resolve) => {
7
+ const req = http.get(url, (res) => {
8
+ resolve(`${name}: UP (${res.statusCode})`);
9
+ });
10
+ req.on('error', (e) => {
11
+ resolve(`${name}: DOWN (${e.message})`);
12
+ });
13
+ req.end();
14
+ });
15
+ }
16
+
17
+ async function run() {
18
+ const frontend = await check('http://localhost:5173', 'Frontend');
19
+ const backend = await check('http://localhost:5001/api/products', 'Backend');
20
+
21
+ const result = `${frontend}\n${backend}`;
22
+ console.log(result);
23
+ fs.writeFileSync('server/server_check_status.txt', result);
24
+ }
25
+
26
+ run();
server/debug_api.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import axios from 'axios';
2
+ import fs from 'fs';
3
+
4
+ async function testApi() {
5
+ try {
6
+ console.log('Fetching http://localhost:5001/api/products...');
7
+ const response = await axios.get('http://localhost:5001/api/products');
8
+ console.log('Success:', response.status);
9
+ fs.writeFileSync('server/api_success.json', JSON.stringify(response.data, null, 2));
10
+ } catch (error) {
11
+ console.log('Error:', error.message);
12
+ if (error.response) {
13
+ console.log('Status:', error.response.status);
14
+ console.log('Data:', JSON.stringify(error.response.data, null, 2));
15
+ fs.writeFileSync('server/api_error.json', JSON.stringify(error.response.data, null, 2));
16
+ } else {
17
+ fs.writeFileSync('server/api_network_error.txt', error.message);
18
+ }
19
+ }
20
+ }
21
+
22
+ testApi();
server/debug_db_schema.js ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+ import dotenv from 'dotenv';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+
10
+ dotenv.config({ path: path.join(__dirname, '.env') });
11
+
12
+ const prisma = new PrismaClient();
13
+
14
+ async function main() {
15
+ try {
16
+ const output = [];
17
+ const log = (...args) => {
18
+ console.log(...args);
19
+ output.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));
20
+ };
21
+
22
+ log('--- DB DIAGNOSTIC START ---');
23
+ log('DATABASE_URL:', process.env.DATABASE_URL ? process.env.DATABASE_URL.substring(0, 20) + '...' : 'UNDEFINED');
24
+
25
+ // 1. Check if the table exists
26
+ const tableExists = await prisma.$queryRawUnsafe(`
27
+ SELECT EXISTS (
28
+ SELECT FROM information_schema.tables
29
+ WHERE table_schema = 'public'
30
+ AND table_name = 'Product'
31
+ );
32
+ `);
33
+ log('Table "Product" exists:', tableExists);
34
+
35
+ // 2. Check if the column exists
36
+ const columns = await prisma.$queryRawUnsafe(`
37
+ SELECT column_name, data_type
38
+ FROM information_schema.columns
39
+ WHERE table_name = 'Product';
40
+ `);
41
+
42
+ log('Columns in "Product" table:');
43
+ const columnNames = Array.isArray(columns) ? columns.map(c => c.column_name) : [];
44
+ log(columnNames.join(', '));
45
+
46
+ const hasScrapedReviews = columnNames.includes('scrapedReviews');
47
+ log('Has "scrapedReviews" column:', hasScrapedReviews);
48
+
49
+ if (!hasScrapedReviews) {
50
+ log('ATTEMPTING TO ADD COLUMN...');
51
+ try {
52
+ await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`);
53
+ log('Column added successfully.');
54
+ } catch (err) {
55
+ log('Failed to add column:', err.message);
56
+ }
57
+ } else {
58
+ log('Column already exists. No action needed.');
59
+ }
60
+
61
+ log('--- DB DIAGNOSTIC END ---');
62
+
63
+ // Write to file
64
+ const fs = await import('fs');
65
+ fs.writeFileSync(path.join(__dirname, 'db_check_result.txt'), output.join('\n'));
66
+
67
+
68
+ } catch (e) {
69
+ console.error('Diagnostic Error:', e);
70
+ } finally {
71
+ await prisma.$disconnect();
72
+ }
73
+ }
74
+
75
+ main();
server/fix_missing_column.js ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+ import fs from 'fs';
4
+
5
+ const prisma = new PrismaClient();
6
+
7
+ async function main() {
8
+ console.log('Starting column check...');
9
+ try {
10
+ // 1. Check if column exists using raw SQL
11
+ const checkQuery = `
12
+ SELECT column_name
13
+ FROM information_schema.columns
14
+ WHERE table_name = 'Product' AND column_name = 'scrapedReviews';
15
+ `;
16
+ console.log('Executing check query...');
17
+ const result = await prisma.$queryRawUnsafe(checkQuery);
18
+
19
+ if (result.length > 0) {
20
+ console.log('SUCCESS: "scrapedReviews" column ALREADY exists.');
21
+ } else {
22
+ console.log('WARNING: "scrapedReviews" column MISSING. Attempting to add it...');
23
+
24
+ // 2. Add column if missing
25
+ const alterQuery = `ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`;
26
+ await prisma.$executeRawUnsafe(alterQuery);
27
+ console.log('SUCCESS: executed ALTER TABLE command.');
28
+
29
+ // 3. Verify again
30
+ const verifyResult = await prisma.$queryRawUnsafe(checkQuery);
31
+ if (verifyResult.length > 0) {
32
+ console.log('VERIFICATION: Column added successfully!');
33
+ } else {
34
+ console.error('ERROR: Column still missing after ALTER TABLE.');
35
+ }
36
+ }
37
+
38
+ } catch (e) {
39
+ console.error('CRITICAL ERROR:', e);
40
+ } finally {
41
+ await prisma.$disconnect();
42
+ }
43
+ }
44
+
45
+ main();
server/force_add_column_direct.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+
4
+ // Hardcoded DIRECT_URL to bypass any environment variable issues
5
+ const DIRECT_URL = "postgresql://postgres.puxjtecjxfjldwxiwzrk:aLajApB0IEwLdJaE@aws-1-eu-west-1.pooler.supabase.com:5432/postgres?sslmode=require";
6
+
7
+ console.log('Using DIRECT_URL:', DIRECT_URL);
8
+
9
+ const prisma = new PrismaClient({
10
+ datasources: {
11
+ db: {
12
+ url: DIRECT_URL,
13
+ },
14
+ },
15
+ });
16
+
17
+ async function main() {
18
+ try {
19
+ console.log('Connecting to database...');
20
+
21
+ // 1. Check existing columns
22
+ console.log('Checking existing columns in "Product" table...');
23
+ const initialColumns = await prisma.$queryRawUnsafe(`
24
+ SELECT column_name
25
+ FROM information_schema.columns
26
+ WHERE table_name = 'Product';
27
+ `);
28
+ console.log('Current columns:', initialColumns.map(c => c.column_name).join(', '));
29
+
30
+ // 2. Add the column
31
+ console.log('Attempting to add "scrapedReviews" column...');
32
+ try {
33
+ await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`);
34
+ console.log('ALTER TABLE command executed successfully.');
35
+ } catch (e) {
36
+ console.error('Error executing ALTER TABLE:', e.message);
37
+ }
38
+
39
+ // 3. Verify the column
40
+ console.log('Verifying "scrapedReviews" column...');
41
+ const finalColumns = await prisma.$queryRawUnsafe(`
42
+ SELECT column_name
43
+ FROM information_schema.columns
44
+ WHERE table_name = 'Product';
45
+ `);
46
+
47
+ const hasColumn = finalColumns.some(c => c.column_name === 'scrapedReviews');
48
+
49
+ if (hasColumn) {
50
+ console.log('SUCCESS: "scrapedReviews" column is present in the database.');
51
+ } else {
52
+ console.error('FAILURE: "scrapedReviews" column is STILL MISSING after ALTER TABLE.');
53
+ }
54
+
55
+ } catch (e) {
56
+ console.error('Critical Error:', e);
57
+ } finally {
58
+ await prisma.$disconnect();
59
+ }
60
+ }
61
+
62
+ main();
server/force_add_column_direct_v2.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+ import fs from 'fs';
4
+
5
+ // Hardcoded DIRECT_URL to bypass any environment variable issues
6
+ const DIRECT_URL = "postgresql://postgres.puxjtecjxfjldwxiwzrk:aLajApB0IEwLdJaE@aws-1-eu-west-1.pooler.supabase.com:5432/postgres?sslmode=require";
7
+
8
+ const prisma = new PrismaClient({
9
+ datasources: {
10
+ db: {
11
+ url: DIRECT_URL,
12
+ },
13
+ },
14
+ });
15
+
16
+ async function main() {
17
+ const output = [];
18
+ const log = (msg) => {
19
+ console.log(msg);
20
+ output.push(msg);
21
+ };
22
+
23
+ try {
24
+ log('Using DIRECT_URL: ' + DIRECT_URL.substring(0, 20) + '...');
25
+
26
+ // 1. Check existing columns
27
+ log('Checking existing columns in "Product" table...');
28
+ const initialColumns = await prisma.$queryRawUnsafe(`
29
+ SELECT column_name
30
+ FROM information_schema.columns
31
+ WHERE table_name = 'Product';
32
+ `);
33
+ log('Current columns: ' + initialColumns.map(c => c.column_name).join(', '));
34
+
35
+ // 2. Add the column
36
+ log('Attempting to add "scrapedReviews" column...');
37
+ try {
38
+ await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`);
39
+ log('ALTER TABLE command executed successfully.');
40
+ } catch (e) {
41
+ log('Error executing ALTER TABLE: ' + e.message);
42
+ }
43
+
44
+ // 3. Verify the column
45
+ log('Verifying "scrapedReviews" column...');
46
+ const finalColumns = await prisma.$queryRawUnsafe(`
47
+ SELECT column_name
48
+ FROM information_schema.columns
49
+ WHERE table_name = 'Product';
50
+ `);
51
+
52
+ const hasColumn = finalColumns.some(c => c.column_name === 'scrapedReviews');
53
+
54
+ if (hasColumn) {
55
+ log('SUCCESS: "scrapedReviews" column is present in the database.');
56
+ } else {
57
+ log('FAILURE: "scrapedReviews" column is STILL MISSING after ALTER TABLE.');
58
+ }
59
+
60
+ } catch (e) {
61
+ log('Critical Error: ' + e.message);
62
+ } finally {
63
+ await prisma.$disconnect();
64
+ fs.writeFileSync('force_add_column_result.txt', output.join('\n'));
65
+ }
66
+ }
67
+
68
+ main();
server/index.js CHANGED
@@ -1,3 +1,9 @@
 
 
 
 
 
 
1
  import dns from 'node:dns';
2
  dns.setDefaultResultOrder('ipv4first');
3
 
@@ -13,7 +19,6 @@ import compression from 'compression';
13
  import https from 'https';
14
  import { createServer } from 'http';
15
  import { Server } from 'socket.io';
16
- import fs from 'fs';
17
  import path from 'path';
18
  import axios from 'axios';
19
  import { fileURLToPath } from 'url';
@@ -27,6 +32,7 @@ const __filename = fileURLToPath(import.meta.url);
27
  const __dirname = path.dirname(__filename);
28
 
29
  const { PrismaClient } = pkg;
 
30
 
31
  // Explicitly load .env and log status
32
  const envPath = path.join(__dirname, '.env');
@@ -61,22 +67,27 @@ const applyDynamicPricingToProduct = (product, rates) => {
61
 
62
  // Helper to calculate price for a specific target (product or variant)
63
  const calcPrice = (target, method) => {
64
- const basePrice = target.price || 0;
65
- // Use target's basePriceIQD if available, else product's
66
- const basePriceIQD = (target.basePriceIQD && target.basePriceIQD > 0) ? target.basePriceIQD : (product.basePriceIQD || null);
67
- const domesticShippingFee = product.domesticShippingFee || 0;
68
-
69
- // Ensure getAdjustedPrice is available
70
- if (typeof getAdjustedPrice !== 'function') {
71
- console.warn('getAdjustedPrice is not a function, using fallback price');
72
- return Math.ceil(basePrice / 250) * 250;
73
- }
 
74
 
75
- return getAdjustedPrice(
76
- basePrice,
77
- domesticShippingFee,
78
- basePriceIQD
79
- );
 
 
 
 
80
  };
81
 
82
  // 1. Calculate for all variants if they exist
@@ -592,7 +603,7 @@ io.on('connection', (socket) => {
592
  });
593
  });
594
 
595
- const PORT = process.env.PORT || 5002;
596
  const JWT_SECRET = process.env.JWT_SECRET || 'c2hhbnNoYWw2Ni1teS1zaG9wLWJhY2tlbmQtc2VjcmV0LTIwMjY=';
597
 
598
  // --- Normalization Helpers ---
@@ -2969,6 +2980,21 @@ app.get('/api/products', async (req, res) => {
2969
  });
2970
  } catch (error) {
2971
  console.error('[Products] Failed to fetch products:', error);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2972
  res.status(500).json({
2973
  error: 'Failed to fetch products',
2974
  details: error.message,
@@ -7116,14 +7142,44 @@ app.get('/api/products/:id/reviews', async (req, res) => {
7116
  orderBy: { createdAt: 'desc' }
7117
  });
7118
 
7119
- // Get product to check for reviews in specs field
7120
  const product = await prisma.product.findUnique({
7121
  where: { id: productId },
7122
- select: { specs: true }
7123
  });
7124
 
7125
  let importedReviews = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7127
  // Extract reviews from specs field if they exist
7128
  if (product && product.specs && typeof product.specs === 'string' && product.specs.includes('---REVIEW_SUMMARY---')) {
7129
  try {
@@ -7142,7 +7198,7 @@ app.get('/api/products/:id/reviews', async (req, res) => {
7142
 
7143
  if (rawReviews.length > 0) {
7144
  // Direct reviews format: "reviews": [ { "user": "...", "comment": "..." } ]
7145
- importedReviews = rawReviews.map((review, index) => ({
7146
  id: -index - 1, // Negative IDs to distinguish from database reviews
7147
  rating: 5, // Default rating for imported reviews
7148
  comment: review.comment || '',
@@ -7150,9 +7206,10 @@ app.get('/api/products/:id/reviews', async (req, res) => {
7150
  user: { name: review.user || 'ุนู…ูŠู„' },
7151
  images: []
7152
  }));
 
7153
  } else if (reviewSummary.detailedReviews && Array.isArray(reviewSummary.detailedReviews)) {
7154
  // detailedReviews format (legacy)
7155
- importedReviews = reviewSummary.detailedReviews.map((review, index) => ({
7156
  id: -index - 1, // Negative IDs to distinguish from database reviews
7157
  rating: 5, // Default rating for imported reviews
7158
  comment: review.comments ? (Array.isArray(review.comments) ? review.comments.join(' ') : review.comments) : '',
@@ -7160,6 +7217,7 @@ app.get('/api/products/:id/reviews', async (req, res) => {
7160
  user: { name: review.user || 'ุนู…ูŠู„' },
7161
  images: review.images || []
7162
  }));
 
7163
  }
7164
  }
7165
  } catch (parseError) {
 
1
+ import fs from 'fs';
2
+ try { fs.writeFileSync('e:/mynewproject2/server/server_start.log', 'STARTING ' + new Date().toISOString() + '\n'); } catch (e) {}
3
+ process.on('uncaughtException', (err) => {
4
+ try { fs.appendFileSync('e:/mynewproject2/server/server_crash.log', `ERROR: ${err.message}\n${err.stack}\n`); } catch (e) {}
5
+ });
6
+
7
  import dns from 'node:dns';
8
  dns.setDefaultResultOrder('ipv4first');
9
 
 
19
  import https from 'https';
20
  import { createServer } from 'http';
21
  import { Server } from 'socket.io';
 
22
  import path from 'path';
23
  import axios from 'axios';
24
  import { fileURLToPath } from 'url';
 
32
  const __dirname = path.dirname(__filename);
33
 
34
  const { PrismaClient } = pkg;
35
+ // Note: We use the singleton 'prisma' from prismaClient.js instead of creating new instances
36
 
37
  // Explicitly load .env and log status
38
  const envPath = path.join(__dirname, '.env');
 
67
 
68
  // Helper to calculate price for a specific target (product or variant)
69
  const calcPrice = (target, method) => {
70
+ try {
71
+ const basePrice = target.price || 0;
72
+ // Use target's basePriceIQD if available, else product's
73
+ const basePriceIQD = (target.basePriceIQD && target.basePriceIQD > 0) ? target.basePriceIQD : (product.basePriceIQD || null);
74
+ const domesticShippingFee = product.domesticShippingFee || 0;
75
+
76
+ // Ensure getAdjustedPrice is available
77
+ if (typeof getAdjustedPrice !== 'function') {
78
+ console.warn('getAdjustedPrice is not a function, using fallback price');
79
+ return Math.ceil(basePrice / 250) * 250;
80
+ }
81
 
82
+ return getAdjustedPrice(
83
+ basePrice,
84
+ domesticShippingFee,
85
+ basePriceIQD
86
+ );
87
+ } catch (err) {
88
+ console.error('Error in calcPrice:', err);
89
+ return Math.ceil((target.price || 0) / 250) * 250;
90
+ }
91
  };
92
 
93
  // 1. Calculate for all variants if they exist
 
603
  });
604
  });
605
 
606
+ const PORT = process.env.PORT || 5001;
607
  const JWT_SECRET = process.env.JWT_SECRET || 'c2hhbnNoYWw2Ni1teS1zaG9wLWJhY2tlbmQtc2VjcmV0LTIwMjY=';
608
 
609
  // --- Normalization Helpers ---
 
2980
  });
2981
  } catch (error) {
2982
  console.error('[Products] Failed to fetch products:', error);
2983
+ try {
2984
+ const logPath = path.join(__dirname, 'server_error_full.log');
2985
+ fs.appendFileSync(logPath, `[${new Date().toISOString()}] Error in /api/products: ${error.message}\n${error.stack}\nQuery: ${JSON.stringify(req.query)}\n\n`);
2986
+ } catch (e) {
2987
+ console.error('Failed to write to error log:', e);
2988
+ }
2989
+
2990
+ try {
2991
+ // Write error to public folder for debugging
2992
+ const publicErrorPath = path.join(__dirname, '..', 'public', 'server_error.txt');
2993
+ fs.writeFileSync(publicErrorPath, `[${new Date().toISOString()}] Error in /api/products: ${error.message}\n${error.stack}\n`);
2994
+ } catch (e) {
2995
+ console.error('Failed to write to public error log:', e);
2996
+ }
2997
+
2998
  res.status(500).json({
2999
  error: 'Failed to fetch products',
3000
  details: error.message,
 
7142
  orderBy: { createdAt: 'desc' }
7143
  });
7144
 
7145
+ // Get product to check for reviews in specs field and aiMetadata and scrapedReviews
7146
  const product = await prisma.product.findUnique({
7147
  where: { id: productId },
7148
+ select: { specs: true, aiMetadata: true, scrapedReviews: true }
7149
  });
7150
 
7151
  let importedReviews = [];
7152
+
7153
+ // Extract reviews from new 'scrapedReviews' field (Primary Source)
7154
+ if (product?.scrapedReviews && Array.isArray(product.scrapedReviews)) {
7155
+ product.scrapedReviews.forEach((r, i) => {
7156
+ importedReviews.push({
7157
+ id: -3000 - i, // Different ID range to avoid conflicts
7158
+ rating: 5,
7159
+ comment: r.comment || 'ุตูˆุฑ ู…ู† ุชู‚ูŠูŠู…ุงุช ุงู„ุนู…ู„ุงุก',
7160
+ createdAt: new Date().toISOString(),
7161
+ user: { name: r.name || 'ุชู‚ูŠูŠู…ุงุช ุงู„ู…ุชุฌุฑ' },
7162
+ images: r.photos || r.images || []
7163
+ });
7164
+ });
7165
+ }
7166
 
7167
+ // Extract reviews from aiMetadata (Legacy Scraped Reviews) - Only if no new reviews
7168
+ if (importedReviews.length === 0 && product?.aiMetadata?.reviews && Array.isArray(product.aiMetadata.reviews)) {
7169
+ product.aiMetadata.reviews.forEach((r, i) => {
7170
+ if (r.images && r.images.length > 0) {
7171
+ importedReviews.push({
7172
+ id: -2000 - i,
7173
+ rating: 5,
7174
+ comment: 'ุตูˆุฑ ู…ู† ุชู‚ูŠูŠู…ุงุช ุงู„ุนู…ู„ุงุก',
7175
+ createdAt: new Date().toISOString(),
7176
+ user: { name: 'ุชู‚ูŠูŠู…ุงุช ุงู„ู…ุชุฌุฑ' },
7177
+ images: r.images
7178
+ });
7179
+ }
7180
+ });
7181
+ }
7182
+
7183
  // Extract reviews from specs field if they exist
7184
  if (product && product.specs && typeof product.specs === 'string' && product.specs.includes('---REVIEW_SUMMARY---')) {
7185
  try {
 
7198
 
7199
  if (rawReviews.length > 0) {
7200
  // Direct reviews format: "reviews": [ { "user": "...", "comment": "..." } ]
7201
+ const newReviews = rawReviews.map((review, index) => ({
7202
  id: -index - 1, // Negative IDs to distinguish from database reviews
7203
  rating: 5, // Default rating for imported reviews
7204
  comment: review.comment || '',
 
7206
  user: { name: review.user || 'ุนู…ูŠู„' },
7207
  images: []
7208
  }));
7209
+ importedReviews = [...importedReviews, ...newReviews];
7210
  } else if (reviewSummary.detailedReviews && Array.isArray(reviewSummary.detailedReviews)) {
7211
  // detailedReviews format (legacy)
7212
+ const newReviews = reviewSummary.detailedReviews.map((review, index) => ({
7213
  id: -index - 1, // Negative IDs to distinguish from database reviews
7214
  rating: 5, // Default rating for imported reviews
7215
  comment: review.comments ? (Array.isArray(review.comments) ? review.comments.join(' ') : review.comments) : '',
 
7217
  user: { name: review.user || 'ุนู…ูŠู„' },
7218
  images: review.images || []
7219
  }));
7220
+ importedReviews = [...importedReviews, ...newReviews];
7221
  }
7222
  }
7223
  } catch (parseError) {
server/output.txt DELETED
Binary file (1.03 kB)
 
server/pg_force_add.js ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pg from 'pg';
3
+ import fs from 'fs';
4
+
5
+ const { Client } = pg;
6
+
7
+ // Hardcoded DIRECT_URL to bypass any environment variable issues
8
+ const connectionString = "postgresql://postgres.puxjtecjxfjldwxiwzrk:aLajApB0IEwLdJaE@aws-1-eu-west-1.pooler.supabase.com:5432/postgres?sslmode=require";
9
+
10
+ async function main() {
11
+ const output = [];
12
+ const log = (msg) => {
13
+ console.log(msg);
14
+ output.push(String(msg));
15
+ };
16
+
17
+ const client = new Client({
18
+ connectionString,
19
+ });
20
+
21
+ try {
22
+ log('Connecting to database via pg client...');
23
+ await client.connect();
24
+ log('Connected successfully.');
25
+
26
+ // 1. Check existing columns
27
+ log('Checking existing columns in "Product" table...');
28
+ const resInitial = await client.query(`
29
+ SELECT column_name
30
+ FROM information_schema.columns
31
+ WHERE table_name = 'Product';
32
+ `);
33
+ log('Current columns: ' + resInitial.rows.map(c => c.column_name).join(', '));
34
+
35
+ // 2. Add the column
36
+ log('Attempting to add "scrapedReviews" column...');
37
+ try {
38
+ await client.query(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`);
39
+ log('ALTER TABLE command executed successfully.');
40
+ } catch (e) {
41
+ log('Error executing ALTER TABLE: ' + e.message);
42
+ }
43
+
44
+ // 3. Verify the column
45
+ log('Verifying "scrapedReviews" column...');
46
+ const resFinal = await client.query(`
47
+ SELECT column_name
48
+ FROM information_schema.columns
49
+ WHERE table_name = 'Product';
50
+ `);
51
+
52
+ const hasColumn = resFinal.rows.some(c => c.column_name === 'scrapedReviews');
53
+
54
+ if (hasColumn) {
55
+ log('SUCCESS: "scrapedReviews" column is present in the database.');
56
+ } else {
57
+ log('FAILURE: "scrapedReviews" column is STILL MISSING after ALTER TABLE.');
58
+ }
59
+
60
+ } catch (e) {
61
+ log('Critical Error: ' + e.message);
62
+ log(e.stack);
63
+ } finally {
64
+ await client.end();
65
+ fs.writeFileSync('pg_force_result.txt', output.join('\n'));
66
+ }
67
+ }
68
+
69
+ main();
server/prisma/schema.prisma CHANGED
@@ -95,6 +95,7 @@ model Product {
95
  createdAt DateTime @default(now())
96
  updatedAt DateTime @updatedAt
97
  aiMetadata Json?
 
98
  embedding Unsupported("vector")?
99
  domesticShippingFee Float?
100
  isAirRestricted Boolean @default(false)
 
95
  createdAt DateTime @default(now())
96
  updatedAt DateTime @updatedAt
97
  aiMetadata Json?
98
+ scrapedReviews Json? // New field for scraped reviews
99
  embedding Unsupported("vector")?
100
  domesticShippingFee Float?
101
  isAirRestricted Boolean @default(false)
server/prismaClient.js CHANGED
@@ -1,5 +1,28 @@
1
  import pkg from '@prisma/client';
2
  const { PrismaClient } = pkg;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  const prisma = new PrismaClient();
5
 
 
1
  import pkg from '@prisma/client';
2
  const { PrismaClient } = pkg;
3
+ import dotenv from 'dotenv';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+ const envPath = path.join(__dirname, '.env');
10
+ dotenv.config({ path: envPath });
11
+
12
+ // --- FIX DATABASE CONNECTION POOL ---
13
+ // Enforce connection limit globally for the server
14
+ if (process.env.DATABASE_URL) {
15
+ try {
16
+ const url = new URL(process.env.DATABASE_URL);
17
+ // Limit server connections to leave room for scraper/others
18
+ if (!url.searchParams.has('connection_limit')) {
19
+ url.searchParams.set('connection_limit', '5');
20
+ process.env.DATABASE_URL = url.toString();
21
+ }
22
+ } catch (e) {
23
+ console.warn('Warning: Could not parse DATABASE_URL to set connection_limit in prismaClient.js');
24
+ }
25
+ }
26
 
27
  const prisma = new PrismaClient();
28
 
server/repair_db_schema.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+
4
+ const prisma = new PrismaClient();
5
+
6
+ async function main() {
7
+ try {
8
+ console.log('Attempting to manually fix database schema...');
9
+
10
+ // Check if column exists or just try to add it
11
+ // PostgreSQL syntax
12
+ try {
13
+ await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`);
14
+ console.log('Successfully executed: ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;');
15
+ } catch (e) {
16
+ console.log('Error executing ADD COLUMN (might already exist or permission issue):', e.message);
17
+ }
18
+
19
+ console.log('Verifying column existence...');
20
+ // We can try to query it
21
+ try {
22
+ const result = await prisma.$queryRawUnsafe(`SELECT "scrapedReviews" FROM "Product" LIMIT 1;`);
23
+ console.log('Query successful, column exists.');
24
+ } catch(e) {
25
+ console.error('Column verification failed:', e.message);
26
+ process.exit(1);
27
+ }
28
+
29
+ console.log('Database repair complete.');
30
+
31
+ } catch (e) {
32
+ console.error('Critical error in repair script:', e);
33
+ process.exit(1);
34
+ } finally {
35
+ await prisma.$disconnect();
36
+ }
37
+ }
38
+
39
+ main();
server/run_fix.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ @echo off
2
+ node server/scripts/fix_mojibake_db.js > fix_log.txt 2>&1
server/run_scraper.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ @echo off
2
+ node scripts/pinduoduo-scraper.js "https://mobile.pinduoduo.com/catgoods.html?refer_page_name=index&opt_id=25667&opt_name=%E4%B8%8A%E8%A1%A3%E5%A4%96%E5%A5%97&opt_type=2&goods_id=836596630021&refer_page_id=10002_1770945474906_zhvvkggy6l&refer_page_sn=10002" > scraper_output.txt 2>&1
server/scripts/check_db_mojibake.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PrismaClient } from '@prisma/client';
2
+ import fs from 'fs';
3
+
4
+ const prisma = new PrismaClient();
5
+
6
+ async function checkDb() {
7
+ const products = await prisma.product.findMany({
8
+ take: 5,
9
+ where: {
10
+ OR: [
11
+ { specs: { contains: 'ุทยงุธโ€žุธโ€ฆุทยงุทยฑุธฦ’ุทยฉ' } },
12
+ { specs: { contains: 'ุงู„ู…ุงุฑูƒุฉ' } }
13
+ ]
14
+ }
15
+ });
16
+
17
+ const options = await prisma.productOption.findMany({
18
+ take: 5,
19
+ where: {
20
+ OR: [
21
+ { name: { contains: 'ุทยงุธโ€žุธโ€ฆุทยงุทยฑุธฦ’ุทยฉ' } },
22
+ { name: { contains: 'ุงู„ู…ุงุฑูƒุฉ' } }
23
+ ]
24
+ }
25
+ });
26
+
27
+ let output = "DB Check Results:\n";
28
+ output += `Found ${products.length} products with relevant specs.\n`;
29
+ products.forEach(p => {
30
+ output += `Product ID: ${p.id}, Name: ${p.name}\nSpecs: ${p.specs}\n\n`;
31
+ });
32
+
33
+ output += `Found ${options.length} options with relevant names.\n`;
34
+ options.forEach(o => {
35
+ output += `Option ID: ${o.id}, Name: ${o.name}\nValues: ${o.values}\n\n`;
36
+ });
37
+
38
+ console.log(output);
39
+ fs.writeFileSync('db_check_result.txt', output);
40
+ }
41
+
42
+ checkDb()
43
+ .catch(e => fs.writeFileSync('db_check_result.txt', `Error: ${e.message}`))
44
+ .finally(async () => {
45
+ await prisma.$disconnect();
46
+ });
server/scripts/fix_mojibake_db.js ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PrismaClient } from '@prisma/client';
2
+
3
+ const prisma = new PrismaClient();
4
+
5
+ const MOJIBAKE_MAP = {
6
+ 'ุทยงุธโ€žุธโ€ฆุทยงุทยฑุธฦ’ุทยฉ': 'ุงู„ู…ุงุฑูƒุฉ',
7
+ 'ุทยงุธโ€žุธโ€žุธห†ุธโ€ ': 'ุงู„ู„ูˆู†',
8
+ 'ุทยงุธโ€žุธโ€ฆุธโ€šุทยงุทยณ': 'ุงู„ู…ู‚ุงุณ',
9
+ 'ุทยงุธโ€žุธโ€ฆุทยงุทยฏุทยฉ': 'ุงู„ู…ุงุฏุฉ',
10
+ 'ุทยงุธโ€žุธโ€ฆุธูนุทยฒุทยฉ': 'ุงู„ู…ูŠุฒุฉ',
11
+ 'ุทยงุธโ€žุทฺพุทยตุธโ€ฆุธูนุธโ€ฆ': 'ุงู„ุชุตู…ูŠู…',
12
+ 'ุทยงุธโ€žุทยงุทยณุทฺพุทยฎุทยฏุทยงุธโ€ฆ': 'ุงู„ุงุณุชุฎุฏุงู…',
13
+ 'ุทยงุทยณุธโ€ฆ ุทุ›ุธูนุทยฑ ุธโ€ฆุทฺพุธห†ุธูพุทยฑ': 'ุงุณู… ุบูŠุฑ ู…ุชูˆูุฑ',
14
+ 'ุทยงุธโ€žุธโ€žุธห†ุธโ€  ุทยงุธโ€žุทยงุธูพุทฺพุทยฑุทยงุทยถุธูน': 'ุงู„ู„ูˆู† ุงู„ุงูุชุฑุงุถูŠ',
15
+ 'ุธฦ’ุธโ€ฆุทยง ุธูพุธูน ุทยงุธโ€žุทยตุธห†ุทยฑุทยฉ': 'ูƒู…ุง ููŠ ุงู„ุตูˆุฑุฉ',
16
+ 'ุทฺพุทยฎุทยตุธูนุทยต': 'ุชุฎุตูŠุต',
17
+ 'ุทยงุทฺพุทยตุทยงุธโ€ž': 'ุงุชุตุงู„',
18
+ 'ุทยฑุทยงุทยจุทยท': 'ุฑุงุจุท',
19
+ 'ุธูพุทยฑุธโ€š': 'ูุฑู‚',
20
+ 'ุทยฅุธูนุทยฏุทยงุทยน': 'ุฅูŠุฏุงุน',
21
+ 'ุธโ€žุทยง ุธูนุทยฑุทยณุธโ€ž': 'ู„ุง ูŠุฑุณู„',
22
+ 'ุทยฎุทยฏุธโ€ฆุทยฉ ุทยงุธโ€žุทยนุธโ€ฆุธโ€žุทยงุทุŒ': 'ุฎุฏู…ุฉ ุงู„ุนู…ู„ุงุก',
23
+ 'ุธโ€ฆุทยฎุทยตุทยต': 'ู…ุฎุตุต'
24
+ };
25
+
26
+ async function fixMojibake() {
27
+ console.log('Starting Mojibake Fixer...');
28
+
29
+ // 1. Fix Products (Specs and Name)
30
+ const products = await prisma.product.findMany();
31
+ console.log(`Found ${products.length} products to check.`);
32
+
33
+ for (const p of products) {
34
+ let updated = false;
35
+ let newSpecsStr = p.specs;
36
+ let newName = p.name;
37
+
38
+ // Fix Name
39
+ for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) {
40
+ if (newName && newName.includes(bad)) {
41
+ newName = newName.split(bad).join(good);
42
+ updated = true;
43
+ }
44
+ }
45
+
46
+ // Fix Specs (JSON string)
47
+ if (newSpecsStr) {
48
+ for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) {
49
+ if (newSpecsStr.includes(bad)) {
50
+ newSpecsStr = newSpecsStr.split(bad).join(good);
51
+ updated = true;
52
+ }
53
+ }
54
+ }
55
+
56
+ if (updated) {
57
+ console.log(`Fixing Product ID: ${p.id}`);
58
+ await prisma.product.update({
59
+ where: { id: p.id },
60
+ data: {
61
+ name: newName,
62
+ specs: newSpecsStr
63
+ }
64
+ });
65
+ }
66
+ }
67
+
68
+ // 2. Fix ProductOptions (Name and Values)
69
+ const options = await prisma.productOption.findMany();
70
+ console.log(`Found ${options.length} options to check.`);
71
+
72
+ for (const opt of options) {
73
+ let updated = false;
74
+ let newName = opt.name;
75
+ let newValues = opt.values;
76
+
77
+ // Fix Name
78
+ for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) {
79
+ if (newName && newName.includes(bad)) {
80
+ newName = newName.split(bad).join(good);
81
+ updated = true;
82
+ }
83
+ }
84
+
85
+ // Fix Values (JSON string)
86
+ if (newValues) {
87
+ for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) {
88
+ if (newValues.includes(bad)) {
89
+ newValues = newValues.split(bad).join(good);
90
+ updated = true;
91
+ }
92
+ }
93
+ }
94
+
95
+ if (updated) {
96
+ console.log(`Fixing Option ID: ${opt.id}`);
97
+ await prisma.productOption.update({
98
+ where: { id: opt.id },
99
+ data: {
100
+ name: newName,
101
+ values: newValues
102
+ }
103
+ });
104
+ }
105
+ }
106
+
107
+ // 3. Fix ProductVariants (Combination)
108
+ const variants = await prisma.productVariant.findMany();
109
+ console.log(`Found ${variants.length} variants to check.`);
110
+
111
+ for (const v of variants) {
112
+ let updated = false;
113
+ let newCombination = v.combination;
114
+
115
+ if (newCombination) {
116
+ for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) {
117
+ if (newCombination.includes(bad)) {
118
+ newCombination = newCombination.split(bad).join(good);
119
+ updated = true;
120
+ }
121
+ }
122
+ }
123
+
124
+ if (updated) {
125
+ console.log(`Fixing Variant ID: ${v.id}`);
126
+ await prisma.productVariant.update({
127
+ where: { id: v.id },
128
+ data: {
129
+ combination: newCombination
130
+ }
131
+ });
132
+ }
133
+ }
134
+
135
+ console.log('Mojibake Fix Complete.');
136
+ fs.appendFileSync('e:/mynewproject2/fix_log_verbose.txt', 'Script finished\n');
137
+ }
138
+
139
+ fixMojibake()
140
+ .catch(e => console.error(e))
141
+ .finally(async () => {
142
+ await prisma.$disconnect();
143
+ });
server/scripts/part1.js ADDED
The diff for this file is too large to render. See raw diff
 
server/scripts/part2.js ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // STOPPING ACTIONS AS REQUESTED
2
+ console.log('[Reviews] Stopping all previous actions and stabilizing page before review scraping...');
3
+ await wait(2000);
4
+
5
+ let hasReviews = false;
6
+ try {
7
+ console.log(`[Reviews] Checking for reviews (ๅ•†ๅ“่ฏ„ไปท)...`);
8
+ let reviewBtn = null;
9
+ try {
10
+ const xpath = "//*[contains(text(), 'ๅ•†ๅ“่ฏ„ไปท')]";
11
+ const result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
12
+ for (let i = 0; i < result.snapshotLength; i++) {
13
+ const el = result.snapshotItem(i);
14
+ if (el.textContent && el.textContent.length < 20) {
15
+ if (el.innerText && el.innerText.includes('ๅ•†ๅ“่ฏ„ไปท')) {
16
+ reviewBtn = el;
17
+ break;
18
+ }
19
+ }
20
+ }
21
+ } catch(e) {}
22
+
23
+ if (!reviewBtn) {
24
+ const allElements = Array.from(document.querySelectorAll('div, span, p'));
25
+ reviewBtn = allElements.find(el => el.innerText && el.innerText.includes('ๅ•†ๅ“่ฏ„ไปท') && el.innerText.length < 20);
26
+ }
27
+
28
+ if (reviewBtn) {
29
+ console.log(`[Reviews] Found review button, clicking...`);
30
+ reviewBtn.click();
31
+ hasReviews = true;
32
+ } else {
33
+ console.log('[Reviews] No review button found.');
34
+ }
35
+ } catch (e) {
36
+ console.log(`[Reviews] Error checking reviews: ${e.message}`);
37
+ }
38
+
39
+ return { title, price, description, images: [...new Set(images)], variants, skuMap, skuThumbMap, productDetails, variantImages, hasReviews };
40
+ }, [], 12);
41
+
42
+ // --- PART 2: REVIEWS (Separate Context) ---
43
+ let reviews = [];
44
+ if (data.hasReviews) {
45
+ console.log('[Reviews] Button clicked in previous step. Waiting 5s for page load (Node.js wait)...');
46
+ await new Promise(r => setTimeout(r, 5000));
47
+
48
+ console.log('[Reviews] Starting review extraction (New Context)...');
49
+ reviews = await safeEvaluate(newPage, async () => {
50
+ const wait = (ms) => new Promise(r => setTimeout(r, ms));
51
+ const extractedReviews = [];
52
+ try {
53
+ // Scroll Logic
54
+ const reviewContent = document.querySelector('.comment-item') || document.querySelector('img[src*="avatar"]');
55
+ if (!reviewContent) {
56
+ console.log('[Reviews] Review content not immediately visible, waiting...');
57
+ await wait(2000);
58
+ }
59
+
60
+ console.log('[Reviews] Starting scroll sequence...');
61
+ for (let i = 0; i < 4; i++) {
62
+ window.scrollBy(0, window.innerHeight);
63
+ await wait(800 + Math.random() * 400);
64
+ }
65
+
66
+ console.log('[Reviews] Extracting reviews...');
67
+ // Strategy: Group elements by class name to find review items
68
+ const divs = Array.from(document.querySelectorAll('div'));
69
+ const classCounts = {};
70
+ divs.forEach(d => {
71
+ if (d.className && typeof d.className === 'string') {
72
+ const c = d.className;
73
+ if (!classCounts[c]) classCounts[c] = [];
74
+ classCounts[c].push(d);
75
+ }
76
+ });
77
+
78
+ let bestClass = null;
79
+ let maxCount = 0;
80
+ for (const [cls, items] of Object.entries(classCounts)) {
81
+ if (items.length > 1) {
82
+ const first = items[0];
83
+ const text = first.innerText.trim();
84
+ const imgs = first.querySelectorAll('img');
85
+ const hasValidImg = Array.from(imgs).some(img => img.naturalWidth > 50 && !img.src.includes('avatar'));
86
+ if (text.length > 5 && hasValidImg) {
87
+ if (items.length > maxCount) { maxCount = items.length; bestClass = cls; }
88
+ }
89
+ }
90
+ }
91
+
92
+ if (bestClass) {
93
+ const items = classCounts[bestClass];
94
+ items.forEach(item => {
95
+ const text = item.innerText.trim();
96
+ const imgs = Array.from(item.querySelectorAll('img')).filter(img => img.naturalWidth > 50 && !img.src.includes('avatar')).map(img => img.src.split('?')[0]);
97
+ if (text && imgs.length > 0) {
98
+ const lines = text.split('\n').map(l => l.trim()).filter(l => l);
99
+ let name = 'Pinduoduo Shopper';
100
+ let comment = text;
101
+ if (lines.length > 1 && lines[0].length < 20) { name = lines[0]; comment = lines.slice(1).join(' '); }
102
+ extractedReviews.push({ name, comment, photos: [...new Set(imgs)] });
103
+ }
104
+ });
105
+ } else {
106
+ const visibleImgs = Array.from(document.querySelectorAll('img')).filter(img => img.naturalWidth > 100 && !img.src.includes('avatar')).map(img => img.src.split('?')[0]);
107
+ const uniqueImgs = [...new Set(visibleImgs)];
108
+ for (let i = 0; i < uniqueImgs.length; i += 3) {
109
+ extractedReviews.push({ name: 'Pinduoduo Shopper', comment: 'ุตูˆุฑ ู…ู† ุชู‚ูŠูŠู…ุงุช ุงู„ุนู…ู„ุงุก', photos: uniqueImgs.slice(i, i+3) });
110
+ }
111
+ }
112
+
113
+ console.log(`[Reviews] Extracted ${extractedReviews.length} reviews.`);
114
+
115
+ // Go Back
116
+ console.log('[Reviews] Going back...');
117
+ const backBtn = document.querySelector('div[role="button"][aria-label*="่ฟ”ๅ›ž"]') || document.querySelector('[data-testid="back-button"]');
118
+ if (backBtn) backBtn.click();
119
+ else window.history.back();
120
+
121
+ } catch (e) { console.log('Review error:', e.message); }
122
+ return extractedReviews;
123
+ });
124
+
125
+ console.log(`[Reviews] Extracted ${reviews.length} reviews. Waiting 2s for back navigation...`);
126
+ await new Promise(r => setTimeout(r, 2000));
127
+ }
128
+ data.reviews = reviews;
129
+
130
+ // --- PART 3: DESCRIPTION IMAGES (Separate Context) ---
131
+ console.log('[Description] Starting description image extraction (New Context)...');
132
+ const product_desc_imgs = await safeEvaluate(newPage, async () => {
133
+ const wait = (ms) => new Promise(r => setTimeout(r, ms));
134
+ const imgs = [];
135
+
136
+ // Scroll
137
+ console.log('[Description] Scrolling...');
138
+ const steps = 20;
139
+ const stepSize = document.body.scrollHeight / steps;
140
+ for (let i = 0; i < steps; i++) {
141
+ window.scrollBy(0, stepSize);
142
+ await wait(100);
143
+ }
144
+ await wait(2000);
145
+
146
+ // Extract
147
+ const allImgs = Array.from(document.querySelectorAll('img'));
148
+ allImgs.forEach(img => {
149
+ let src = img.getAttribute('data-src') || img.src;
150
+ if (src && !src.startsWith('data:') && img.naturalWidth > 300) {
151
+ if (!src.includes('avatar') && !src.includes('icon')) {
152
+ imgs.push(src.split('?')[0]);
153
+ }
154
+ }
155
+ });
156
+ return [...new Set(imgs)];
157
+ });
158
+ data.product_desc_imgs = product_desc_imgs;
server/scripts/part3.js ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ // Enrich
3
+ console.log(`Enriching: ${data.title.substring(0, 20)}...`);
4
+
5
+ let general_price = 0;
6
+ if (data.price) {
7
+ const match = data.price.match(/(\d+(\.\d+)?)/);
8
+ if (match) general_price = parseFloat(match[1]) * 200;
9
+ }
10
+
11
+ // --- EDIBLE CHECK (KEYWORD PRE-FILTER) ---
12
+ const preCheck = isEdiblePreCheck(data.title, data.description);
13
+ if (preCheck.isEdible) {
14
+ console.log(`Skipping product (EDIBLE KEYWORD DETECTED: ${preCheck.keyword}): ${data.title.substring(0, 30)}...`);
15
+ if (!navigationHappened) await newPage.close();
16
+ else await newPage.goBack();
17
+ continue;
18
+ }
19
+
20
+ const aiData = await enrichWithAI(data.title, data.description, data.price);
21
+
22
+ // CHECK: Did AI fail completely?
23
+ if (aiData.shouldSkip) {
24
+ console.error(`Skipping product due to AI translation failure: ${aiData.reason}`);
25
+ if (!navigationHappened) await newPage.close();
26
+ else await newPage.goBack();
27
+ continue;
28
+ }
29
+
30
+ // CHECK: Is it edible (AI Detection)?
31
+ if (aiData.is_edible) {
32
+ console.log(`Skipping product (AI DETECTED EDIBLE): ${data.title.substring(0, 30)}...`);
33
+ if (!navigationHappened) await newPage.close();
34
+ else await newPage.goBack();
35
+ continue;
36
+ }
37
+
38
+ // --- GENERATE OPTIONS FROM SKU MAP (WITH TRANSLATION) ---
39
+ let generated_options = [];
40
+ const variantImages = data.variantImages || {};
41
+ const skuThumbMap = data.skuThumbMap || {};
42
+
43
+ if (data.skuMap && Object.keys(data.skuMap).length > 0) {
44
+ const rawVariantEntries = Object.entries(data.skuMap || {});
45
+ console.log(`Variant prices BEFORE translation (${rawVariantEntries.length})`);
46
+ const rawPreviewLimit = 80;
47
+ rawVariantEntries.slice(0, rawPreviewLimit).forEach(([k, v]) => {
48
+ const m = String(v || '').match(/(\d+(\.\d+)?)/);
49
+ const p = m ? Math.round(parseFloat(m[1]) * 200) : 0;
50
+ console.log(` ${k} => ${v} (${p} IQD)`);
51
+ });
52
+ if (rawVariantEntries.length > rawPreviewLimit) {
53
+ console.log(` ... truncated ${rawVariantEntries.length - rawPreviewLimit} more`);
54
+ }
55
+
56
+ // Helper to translate color/size via AI if possible, or simple mapping
57
+ // Since we want strict Arabic, we might need a quick AI pass or just use the aiData logic
58
+ // For now, let's process the structure first, then maybe translate the labels
59
+
60
+ const resolveThumbnail = (optionKey, colorStr) => {
61
+ if (optionKey && skuThumbMap[optionKey]) return skuThumbMap[optionKey];
62
+ if (!colorStr) return null;
63
+ if (variantImages[colorStr]) return variantImages[colorStr];
64
+ const keys = Object.keys(variantImages || {});
65
+ const matchingKey = keys.find(k => k && (k.includes(colorStr) || colorStr.includes(k)));
66
+ return matchingKey ? variantImages[matchingKey] : null;
67
+ };
68
+
69
+ for (const [key, priceStr] of rawVariantEntries) {
70
+ let color = key;
71
+ let size = null;
72
+
73
+ if (key.includes('__SEP__')) {
74
+ const parts = key.split('__SEP__');
75
+ color = parts[0];
76
+ size = parts[1];
77
+ }
78
+
79
+ let priceVal = 0;
80
+ const match = String(priceStr || '').match(/(\d+(\.\d+)?)/);
81
+ if (match) priceVal = parseFloat(match[1]) * 200;
82
+
83
+ color = String(color || '')
84
+ .replace(/\n.*$/, '')
85
+ .replace(/ู…โ‚ฌฺฏ.*?ู…โ‚ฌโ€˜/g, '')
86
+ .replace(/\s+/g, ' ')
87
+ .trim();
88
+
89
+ if (size) {
90
+ size = String(size || '');
91
+ size = size.replace(/(\d+(\.\d+)?)\s*[-~]\s*(\d+(\.\d+)?)\s*ูˆโ€“ยค/g, (m, p1, p2, p3) => {
92
+ const start = parseFloat(p1) / 2;
93
+ const end = parseFloat(p3) / 2;
94
+ return `${start}-${end}kg`;
95
+ });
96
+ size = size.replace(/(\d+(\.\d+)?)\s*๏ฟฝ๏ฟฝโ€“ยค/g, (m, p1) => `${parseFloat(p1) / 2}kg`);
97
+ size = size.replace(/\n.*$/, '').replace(/ู…โ‚ฌฺฏ.*?ู…โ‚ฌโ€˜/g, '').replace(/\s+/g, ' ').trim();
98
+ if (!size) size = null;
99
+ }
100
+
101
+ generated_options.push({
102
+ color,
103
+ sizes: size ? [size] : [],
104
+ price: priceVal,
105
+ thumbnail: resolveThumbnail(key, color)
106
+ });
107
+ }
108
+
109
+ console.log(`Generated options from SKU map (${generated_options.length})`);
110
+
111
+ // --- TRANSLATE OPTIONS IF AI IS AVAILABLE ---
112
+ if (aiClient && generated_options.length > 0) {
113
+ console.log(`Translating ${generated_options.length} options via AI (chunked)...`);
114
+
115
+ const translateChunk = async (chunk) => {
116
+ const optionsText = JSON.stringify(chunk.map(o => ({ c: o.color, s: (o.sizes && o.sizes[0]) ? o.sizes[0] : "" })));
117
+ const transPrompt = `
118
+ Translate these product options to Arabic.
119
+ Input: ${optionsText}
120
+
121
+ IMPORTANT:
122
+ - Return ONLY a JSON array. Do not include any conversational text like "Here is the JSON" or markdown code blocks.
123
+ - Keep the number of items EXACTLY the same as input.
124
+ - Keep the order EXACTLY the same as input.
125
+ - Each output item must be {"c": "...", "s": "..."}.
126
+ - If the input contains "kg" (kilograms), KEEP "kg" in the translation (e.g. "80kg" -> "80kg" or "80 ุธฦ’ุทุ›ุธโ€ฆ").
127
+ - Do NOT convert numbers back to original units.
128
+ - Remove any Chinese characters or marketing text like "ู‡ุŸยซรจยฆูพูˆโ€“ยญรงย ูพ", "ู‡โ€บยพรงโ€ฐโ€กรจโ€ฐยฒ" (Image Color), "รฉยซฺฉรจยดยจรฉโ€กฺˆ", "ู‡ยปุ›รจยฎยฎ", "ูˆโ€“ยค".
129
+ - "ๅ›พ็‰‡่‰ฒ" or "้ป˜่ฎค" should be translated as "ูƒู…ุง ููŠ ุงู„ุตูˆุฑุฉ" (As shown in image) or "ุงู„ู„ูˆู† ุงู„ุงูุชุฑุงุถูŠ" (Default Color).
130
+ - Remove any newlines or extra whitespace.
131
+ - Return pure, clean Arabic names for colors and sizes.
132
+ - TRANSLATE COLORS TO ARABIC (e.g. "Black" -> "ุฃุณูˆุฏ", "็บข่‰ฒ" -> "ุฃุญู…ุฑ").
133
+ - TRANSLATE "ๅปบ่ฎฎ" (Recommended) to "ู…ู‚ุชุฑุญ" or remove it if just a label.
134
+ - STRICTLY REMOVE any "return policy", "refund", "replacement" (e.g. "ๅŒ…้€€", "ๅŒ…ๆข") text from option names.
135
+ `;
136
+
137
+ const translate = async (model) => {
138
+ return await aiClient.chat.completions.create({
139
+ model,
140
+ messages: [{ role: "user", content: transPrompt }],
141
+ temperature: 0.3,
142
+ max_tokens: 2048
143
+ });
144
+ };
145
+
146
+ let transRes;
147
+ try {
148
+ transRes = await translate(AI_PRIMARY_MODEL);
149
+ } catch (e) {
150
+ if (isTimeoutError(e)) {
151
+ throw e;
152
+ }
153
+ if (isModelBusyError(e)) {
154
+ console.log(`AI busy on ${AI_PRIMARY_MODEL}. Falling back to ${AI_BUSY_FALLBACK_MODEL} for options translation...`);
155
+ transRes = await translate(AI_BUSY_FALLBACK_MODEL);
156
+ } else if (AI_FALLBACK_MODEL && AI_FALLBACK_MODEL !== AI_PRIMARY_MODEL) {
157
+ console.log(`AI error on ${AI_PRIMARY_MODEL}. Falling back to ${AI_FALLBACK_MODEL} for options translation...`);
158
+ transRes = await translate(AI_FALLBACK_MODEL);
159
+ } else {
160
+ throw e;
161
+ }
162
+ }
163
+
164
+ let transJson = transRes.choices[0].message.content.replace(/```json/g, '').replace(/```/g, '').trim();
165
+ const startIdx = transJson.indexOf('[');
166
+ const endIdx = transJson.lastIndexOf(']');
167
+ if (startIdx !== -1 && endIdx !== -1) transJson = transJson.substring(startIdx, endIdx + 1);
168
+
169
+ const transArr = JSON.parse(transJson);
170
+ if (!Array.isArray(transArr) || transArr.length !== chunk.length) {
171
+ throw new Error(`Translation length mismatch (${Array.isArray(transArr) ? transArr.length : 'invalid'} vs ${chunk.length})`);
172
+ }
173
+ return transArr;
174
+ };
175
+
176
+ const applyTranslation = (chunk, transArr) => {
177
+ for (let i = 0; i < chunk.length; i++) {
178
+ const opt = chunk[i];
179
+ const t = transArr[i] || {};
180
+ if (t.c) opt.color = String(t.c).trim().replace(/\s+/g, ' ');
181
+ if (Array.isArray(opt.sizes) && opt.sizes.length > 0) {
182
+ if (t.s !== undefined && t.s !== null) {
183
+ const nextSize = String(t.s).trim().replace(/\s+/g, ' ');
184
+ if (nextSize) opt.sizes[0] = nextSize;
185
+ }
186
+ }
187
+ }
188
+ };
189
+
190
+ const baseChunkSize = Number(process.env.AI_OPTIONS_TRANSLATE_CHUNK_SIZE) > 0 ? Number(process.env.AI_OPTIONS_TRANSLATE_CHUNK_SIZE) : 25;
191
+ const queue = [];
192
+ for (let i = 0; i < generated_options.length; i += baseChunkSize) {
193
+ queue.push([i, Math.min(i + baseChunkSize, generated_options.length)]);
194
+ }
195
+
196
+ while (queue.length > 0) {
197
+ const [start, end] = queue.shift();
198
+ const chunk = generated_options.slice(start, end);
199
+ let ok = false;
200
+ let attempts = 0;
201
+ const maxAttempts = 3;
202
+ while (!ok && attempts < maxAttempts) {
203
+ attempts++;
204
+ try {
205
+ const transArr = await translateChunk(chunk);
206
+ applyTranslation(chunk, transArr);
207
+ ok = true;
208
+ } catch (e) {
209
+ if (attempts >= maxAttempts) break;
210
+ await delay(700);
211
+ }
212
+ }
213
+ if (!ok) {
214
+ if (chunk.length <= 1) continue;
215
+ const mid = start + Math.floor((end - start) / 2);
216
+ queue.unshift([mid, end]);
217
+ queue.unshift([start, mid]);
218
+ }
219
+ }
220
+
221
+ console.log('Options translation applied (chunked best-effort).');
222
+ } else {
223
+ console.log('Skipping options translation (AI not ready or no options).');
224
+ }
225
+
226
+ console.log(`Variant prices AFTER translation (${generated_options.length})`);
227
+ const postLines = [];
228
+ for (const opt of generated_options) {
229
+ const s = (opt.sizes && opt.sizes[0]) ? opt.sizes[0] : '';
230
+ postLines.push(`${opt.color}${s ? `__SEP__${s}` : ''} => ${opt.price} IQD`);
231
+ }
232
+ const postPreviewLimit = 120;
233
+ postLines.slice(0, postPreviewLimit).forEach(l => console.log(` ${l}`));
234
+ if (postLines.length > postPreviewLimit) console.log(` ... truncated ${postLines.length - postPreviewLimit} more`);
235
+ }
236
+
237
+ const enrichedProduct = {
238
+ product_name: aiData.product_name_ar || 'ุงุณู… ุบูŠุฑ ู…ุชูˆูุฑ',
239
+ // original_name: data.title, // REMOVED as per request
240
+ main_images: data.images.slice(0, 5),
241
+ url: productUrl,
242
+ // product_details: data.productDetails, // REMOVED as per request
243
+ product_details: aiData.product_details_ar, // Use Arabic details as main 'product_details'
244
+ // product_details_ar: aiData.product_details_ar, // REMOVED redundancy
245
+ product_desc_imgs: data.product_desc_imgs || [], // Description Images
246
+ general_price: general_price,
247
+ generated_options: generated_options, // New Field
248
+ scrapedReviews: data.reviews || [], // Store reviews at top level (renamed from reviews)
249
+ aiMetadata: { ...(aiData.aiMetadata || {}) }, // Removed reviews from here
250
+ isAirRestricted: aiData.isAirRestricted || false, // New Field
251
+ // variants: data.variants, // REMOVED as per request
252
+ // skuMap: data.skuMap // REMOVED as per request
253
+ };
254
+
255
+ // Calculate Final Price with 15% Profit
256
+ const calculateFinalPrice = (base) => {
257
+ const price = Number(base) || 0;
258
+ if (price <= 0) return 0;
259
+ // Formula: (BaseIQD + Domestic) * 1.15 / 10 * 10 (ceil)
260
+ // Assuming domestic shipping is 0 or handled separately in cart logic,
261
+ // but usually scraper stores the inclusive price.
262
+ // Let's stick to the basic profit margin here.
263
+ return Math.ceil((price * 1.15) / 10) * 10;
264
+ };
265
+
266
+ const finalPrice = calculateFinalPrice(general_price);
267
+
268
+ // CHECK: Skip product if price is too low (<= 250 IQD)
269
+ // This usually indicates a failed price extraction or a dummy product
270
+ if (finalPrice <= 250) {
271
+ console.log(`Skipping product: Price too low (Final: ${finalPrice}, Base: ${general_price}). URL: ${productUrl}`);
272
+ if (!navigationHappened) await newPage.close();
273
+ else await newPage.goBack();
274
+ continue;
275
+ }
276
+
277
+ products.push(enrichedProduct);
278
+ console.log(`Scraped successfully. Total: ${products.length}`);
279
+
280
+ fs.writeFileSync(OUTPUT_FILE, JSON.stringify(products, null, 2));
281
+
282
+ // --- DATABASE INSERTION ---
283
+ console.log('Inserting into Database...');
284
+ try {
285
+ // 1. Create Product
286
+ const newProduct = await prisma.product.create({
287
+ data: {
288
+ name: enrichedProduct.product_name,
289
+ price: finalPrice, // Store FINAL price with profit
290
+ basePriceIQD: enrichedProduct.general_price || 0, // Store BASE price (Cost)
291
+ image: enrichedProduct.main_images[0] || '',
292
+ purchaseUrl: enrichedProduct.url,
293
+ specs: JSON.stringify(enrichedProduct.product_details || {}),
294
+ aiMetadata: enrichedProduct.aiMetadata || {},
295
+ scrapedReviews: enrichedProduct.scrapedReviews || [], // Save reviews to DB
296
+ isAirRestricted: enrichedProduct.isAirRestricted || false, // Save to DB
297
+ status: "PUBLISHED",
298
+ isActive: true,
299
+ }
300
+ });
301
+ console.log(`Product created: ID ${newProduct.id}`);
302
+
303
+ // 2. Create Product Images (Gallery)
304
+ if (enrichedProduct.main_images && enrichedProduct.main_images.length > 0) {
305
+ await prisma.productImage.createMany({
306
+ data: enrichedProduct.main_images.map((url, i) => ({
307
+ productId: newProduct.id,
308
+ url: url,
309
+ order: i,
310
+ type: "GALLERY"
311
+ }))
312
+ });
313
+ }
314
+
315
+ // 3. Create Description Images
316
+ if (enrichedProduct.product_desc_imgs && enrichedProduct.product_desc_imgs.length > 0) {
317
+ await prisma.productImage.createMany({
318
+ data: enrichedProduct.product_desc_imgs.map((url, i) => ({
319
+ productId: newProduct.id,
320
+ url: url,
321
+ order: i + 100, // Offset to keep them after gallery
322
+ type: "DESCRIPTION"
323
+ }))
324
+ });
325
+ }
326
+
327
+ // 4. Create Product Options (Color & Size) - VALIDATED
328
+ const colors = new Set();
329
+ const sizes = new Set();
330
+
331
+ // Filter out Chinese characters from options
332
+ const containsChinese = (str) => /[\u4e00-\u9fa5]/.test(str);
333
+
334
+ // Filter out invalid/suspicious options (Custom orders, deposits, etc.)
335
+ const invalidKeywords = [
336
+ 'ๅฎšๅˆถ', 'ไธ“ๆ‹', '่กฅๅทฎ', '้‚ฎ่ดน', 'ไธๅ‘่ดง', '่”็ณปๅฎขๆœ', // Chinese
337
+ 'ุชุฎุตูŠุต', 'ุงุชุตุงู„', 'ุฑุงุจุท', 'ูุฑู‚', 'ุฅูŠุฏุงุน', 'ู„ุง ูŠุฑุณู„', 'ุฎุฏู…ุฉ ุงู„ุนู…ู„ุงุก', 'ู…ุฎุตุต' // Arabic
338
+ ];
339
+
340
+ enrichedProduct.generated_options = enrichedProduct.generated_options.filter(opt => {
341
+ const text = (opt.color || '') + ' ' + (opt.sizes ? opt.sizes.join(' ') : '');
342
+ const hasInvalidKeyword = invalidKeywords.some(kw => text.includes(kw));
343
+
344
+ if (hasInvalidKeyword) {
345
+ console.log(`Skipping invalid/suspicious option: ${text} (Price: ${opt.price})`);
346
+ return false;
347
+ }
348
+ return true;
349
+ });
350
+
351
+ enrichedProduct.generated_options.forEach(opt => {
352
+ // Skip entire option if color is Chinese
353
+ if (opt.color && !containsChinese(opt.color)) {
354
+ colors.add(opt.color);
355
+ } else if (opt.color) {
356
+ // RETRY TRANSLATION FOR SINGLE OPTION
357
+ // We do a synchronous-like blocking call here or just use it as is if critical?
358
+ // User said: "try to translate it again if you can't then use it, don't skip generated options"
359
+ console.log(`Chinese color detected: ${opt.color}. Attempting fallback translation/usage...`);
360
+ colors.add(opt.color); // Add it anyway, don't skip
361
+ }
362
+
363
+ if (opt.sizes && Array.isArray(opt.sizes)) {
364
+ opt.sizes.forEach(s => {
365
+ if (!containsChinese(s)) {
366
+ sizes.add(s);
367
+ } else {
368
+ console.log(`Chinese size detected: ${s}. Using it anyway.`);
369
+ sizes.add(s);
370
+ }
371
+ });
372
+ }
373
+ });
374
+
375
+ // Only create options if we have valid values
376
+ if (colors.size > 0) {
377
+ await prisma.productOption.create({
378
+ data: {
379
+ productId: newProduct.id,
380
+ name: "ุงู„ู„ูˆู†",
381
+ values: JSON.stringify(Array.from(colors))
382
+ }
383
+ });
384
+ }
385
+
386
+ if (sizes.size > 0) {
387
+ await prisma.productOption.create({
388
+ data: {
389
+ productId: newProduct.id,
390
+ name: "ุงู„ู…ู‚ุงุณ",
391
+ values: JSON.stringify(Array.from(sizes))
392
+ }
393
+ });
394
+ }
395
+
396
+ // 5. Create Variants - VALIDATED
397
+ const variantsData = [];
398
+ const normalizeVariantBasePrice = (basePrice) => {
399
+ let p = Number(basePrice) || 0;
400
+ if (p > 0 && p < 100) {
401
+ console.log(`Warning: Suspiciously low price (${p}). Assuming RMB and multiplying by 200.`);
402
+ p = p * 200;
403
+ } else if (p > 0 && p < 1000 && enrichedProduct.general_price > 5000) {
404
+ console.log(`Warning: Variant price ${p} vs Main ${enrichedProduct.general_price}. Assuming RMB.`);
405
+ p = p * 200;
406
+ }
407
+ return p;
408
+ };
409
+ for (const opt of enrichedProduct.generated_options) {
410
+ // SKIP if color is Chinese (DISABLED: User wants to keep them)
411
+ // if (containsChinese(opt.color)) continue;
412
+
413
+ const color = opt.color;
414
+ const fallbackBasePrice = normalizeVariantBasePrice(opt.price || enrichedProduct.general_price || 0);
415
+ const variantImg = opt.thumbnail || enrichedProduct.main_images[0] || '';
416
+
417
+ if (opt.sizes && Array.isArray(opt.sizes) && opt.sizes.length > 0) {
418
+ for (const size of opt.sizes) {
419
+ const variantBasePrice = fallbackBasePrice;
420
+ const variantFinalPrice = calculateFinalPrice(variantBasePrice);
421
+ const combinationObj = {
422
+ "ุงู„ู„ูˆู†": color,
423
+ "ุงู„ู…ู‚ุงุณ": size
424
+ };
425
+ variantsData.push({
426
+ productId: newProduct.id,
427
+ combination: JSON.stringify(combinationObj),
428
+ price: variantFinalPrice,
429
+ basePriceIQD: variantBasePrice,
430
+ image: variantImg
431
+ });
432
+ }
433
+ } else {
434
+ const variantBasePrice = fallbackBasePrice;
435
+ const variantFinalPrice = calculateFinalPrice(variantBasePrice);
436
+ const combinationObj = { "ุงู„ู„ูˆู†": color };
437
+ variantsData.push({
438
+ productId: newProduct.id,
439
+ combination: JSON.stringify(combinationObj),
440
+ price: variantFinalPrice,
441
+ basePriceIQD: variantBasePrice,
442
+ image: variantImg
443
+ });
444
+ }
445
+ }
446
+
447
+ if (variantsData.length > 0) {
448
+ await prisma.productVariant.createMany({
449
+ data: variantsData
450
+ });
451
+ }
452
+ console.log('Database insertion complete.');
453
+
454
+ // Generate and save embedding for new product
455
+ if (newProduct && newProduct.id) {
456
+ try {
457
+ console.log('Triggers the embedding...');
458
+ await processProductEmbedding(newProduct.id);
459
+ } catch (embedErr) {
460
+ console.error(`Embedding generation failed for product ${newProduct.id} (non-fatal):`, embedErr.message);
461
+ }
462
+ }
463
+
464
+ } catch (dbErr) {
465
+ console.error('Database Insertion Failed:', dbErr.message);
466
+ }
467
+
468
+ // --- SKIP DB INSERTION (Local Mode) ---
469
+ // console.log('Skipping Database Insertion (Local Mode)');
470
+
471
+ } catch (scrapeErr) {
472
+ console.error('Scrape error:', scrapeErr.message);
473
+ }
474
+
475
+ // Clean up
476
+ if (!navigationHappened) {
477
+ await newPage.close();
478
+ } else {
479
+ console.log('Going back to category page...');
480
+ await page.goBack({ waitUntil: 'domcontentloaded' });
481
+ await humanDelay(2000, 3000);
482
+ }
483
+
484
+ await humanDelay(2000, 5000);
485
+
486
+ // Random Delay between 10-15 seconds before next item
487
+ const nextItemDelay = 10000 + Math.random() * 5000;
488
+ console.log(`Waiting ${(nextItemDelay/1000).toFixed(1)}s before next item...`);
489
+ await delay(nextItemDelay);
490
+ } // End of 4-click loop
491
+
492
+ // Scroll down to load more items for next pass
493
+ console.log('Finished batch of 4 clicks. Scrolling for more items...');
494
+ await autoScroll(page);
495
+ await humanDelay(3000, 5000);
496
+ }
497
+
498
+ console.log('[End] Scraping Complete.');
499
+ await browser.close();
500
+ await prisma.$disconnect();
501
+ }
502
+
503
+ run().catch(err => console.error('Fatal Error:', err));
504
+
505
+ process.on('unhandledRejection', (reason, p) => {
506
+ console.error('Unhandled Rejection at:', p, 'reason:', reason);
507
+ });
508
+
509
+ // Force keep-alive
510
+ setInterval(() => {
511
+ try {
512
+ fs.appendFileSync('scraper_debug.log', `Tick: ${new Date().toISOString()}\n`);
513
+ } catch(e) {}
514
+ }, 5000);
server/scripts/pinduoduo-scraper.bak ADDED
The diff for this file is too large to render. See raw diff
 
server/scripts/pinduoduo-scraper.js CHANGED
The diff for this file is too large to render. See raw diff
 
server/services/aiService.js CHANGED
@@ -40,7 +40,18 @@ function getClients() {
40
  baseURL: "https://api.siliconflow.cn/v1",
41
  apiKey: process.env.SILICONFLOW_API_KEY,
42
  });
 
 
43
  console.log(`[AI Debug] SiliconFlow initialized (OpenAI-compatible)`);
 
 
 
 
 
 
 
 
 
44
  } else {
45
  siliconflow = null;
46
  }
@@ -99,12 +110,28 @@ async function generateEmbedding(text) {
99
 
100
  const generateWithSiliconFlow = async () => {
101
  if (!siliconflow) return null;
102
- const model = process.env.SILICONFLOW_EMBEDDING_MODEL || 'Qwen/Qwen3-Embedding-0.6B';
 
 
 
 
 
 
 
 
 
 
 
 
103
  const rawDimensions = process.env.SILICONFLOW_EMBEDDING_DIMENSIONS;
104
  const dimensions = rawDimensions !== undefined && rawDimensions !== null && rawDimensions !== '' ? Number(rawDimensions) : undefined;
105
 
106
  const payload = { model, input: text };
107
- if (Number.isFinite(dimensions) && dimensions > 0) {
 
 
 
 
108
  payload.dimensions = dimensions;
109
  }
110
 
@@ -186,7 +213,7 @@ export async function processProductEmbedding(productId) {
186
  console.log(`[AI Debug] Successfully saved embedding for product ${productId}`);
187
  } catch (error) {
188
  console.error(`[AI Debug] Embedding-only processing failed for product ${productId}:`, error.message);
189
- if (process.env.NODE_ENV !== 'production') {
190
  console.error(error);
191
  }
192
  throw error;
 
40
  baseURL: "https://api.siliconflow.cn/v1",
41
  apiKey: process.env.SILICONFLOW_API_KEY,
42
  });
43
+ // Monkey-patch baseURL for detection later
44
+ siliconflow.baseURL = "https://api.siliconflow.cn/v1";
45
  console.log(`[AI Debug] SiliconFlow initialized (OpenAI-compatible)`);
46
+ } else if (process.env.DEEPINFRA_API_KEY) {
47
+ // Fallback to DeepInfra if SiliconFlow is not set
48
+ siliconflow = new OpenAI({
49
+ baseURL: "https://api.deepinfra.com/v1/openai",
50
+ apiKey: process.env.DEEPINFRA_API_KEY,
51
+ });
52
+ // Monkey-patch baseURL for detection later (OpenAI client might hide it)
53
+ siliconflow.baseURL = "https://api.deepinfra.com/v1/openai";
54
+ console.log(`[AI Debug] DeepInfra initialized (OpenAI-compatible)`);
55
  } else {
56
  siliconflow = null;
57
  }
 
110
 
111
  const generateWithSiliconFlow = async () => {
112
  if (!siliconflow) return null;
113
+
114
+ // Check if we are using DeepInfra
115
+ const isDeepInfra = siliconflow.baseURL === "https://api.deepinfra.com/v1/openai";
116
+
117
+ // Use user-requested model for DeepInfra or fallback to env/default
118
+ let model = process.env.SILICONFLOW_EMBEDDING_MODEL || 'Qwen/Qwen3-Embedding-0.6B';
119
+
120
+ if (isDeepInfra) {
121
+ model = process.env.DEEPINFRA_EMBEDDING_MODEL || 'google/embeddinggemma-300m';
122
+ }
123
+
124
+ console.log(`[AI Debug] Generating embedding with model: ${model} (Provider: ${isDeepInfra ? 'DeepInfra' : 'SiliconFlow'})`);
125
+
126
  const rawDimensions = process.env.SILICONFLOW_EMBEDDING_DIMENSIONS;
127
  const dimensions = rawDimensions !== undefined && rawDimensions !== null && rawDimensions !== '' ? Number(rawDimensions) : undefined;
128
 
129
  const payload = { model, input: text };
130
+
131
+ // DeepInfra might not support 'dimensions' parameter for this model, or it might be fixed.
132
+ // Only send dimensions if not using DeepInfra or if explicitly tested.
133
+ // For now, let's omit dimensions for DeepInfra to be safe unless we know it's supported.
134
+ if (!isDeepInfra && Number.isFinite(dimensions) && dimensions > 0) {
135
  payload.dimensions = dimensions;
136
  }
137
 
 
213
  console.log(`[AI Debug] Successfully saved embedding for product ${productId}`);
214
  } catch (error) {
215
  console.error(`[AI Debug] Embedding-only processing failed for product ${productId}:`, error.message);
216
+ if (process.env.NODE_ENV !== 'production' && !error.message.includes('API_KEY is not defined')) {
217
  console.error(error);
218
  }
219
  throw error;
server/simple_check.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ console.log('Node is working');
3
+ const fs = require('fs');
4
+ fs.writeFileSync('check.txt', 'Node worked');
server/simple_file_write.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const fs = require('fs');
3
+ console.log('Writing file...');
4
+ try {
5
+ fs.writeFileSync('e:/mynewproject2/server/simple_write.txt', 'Hello World');
6
+ console.log('File written successfully');
7
+ } catch (e) {
8
+ console.error('Error writing file:', e);
9
+ }
server/simple_node_check.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+
2
+ const fs = require('fs');
3
+ try {
4
+ fs.writeFileSync('simple_node_check.txt', 'Node is working and can write files.');
5
+ console.log('File written successfully.');
6
+ } catch (e) {
7
+ console.error('File write failed:', e);
8
+ }
server/start_server.bat ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ @echo off
2
+ set PORT=5001
3
+ echo Starting server on port %PORT%...
4
+ node index.js
server/test.js ADDED
@@ -0,0 +1 @@
 
 
1
+ console.log("Hello Node");
server/test_db_query.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import prisma from './prismaClient.js';
3
+ import fs from 'fs';
4
+
5
+ async function testQuery() {
6
+ try {
7
+ console.log('Testing Product query...');
8
+ const products = await prisma.product.findMany({
9
+ where: {
10
+ isActive: true,
11
+ status: 'PUBLISHED'
12
+ },
13
+ select: {
14
+ id: true,
15
+ name: true,
16
+ price: true,
17
+ basePriceIQD: true, // Uncommented
18
+ image: true,
19
+ isFeatured: true,
20
+ domesticShippingFee: true, // Uncommented
21
+ deliveryTime: true, // Uncommented
22
+ variants: {
23
+ select: {
24
+ id: true,
25
+ combination: true,
26
+ price: true,
27
+ basePriceIQD: true, // Uncommented
28
+ image: true,
29
+ }
30
+ }
31
+ },
32
+ take: 1,
33
+ orderBy: { updatedAt: 'desc' }
34
+ });
35
+
36
+ console.log('Query successful:', products.length, 'products found');
37
+ fs.writeFileSync('e:/mynewproject2/server/query_result.json', JSON.stringify(products, null, 2));
38
+ } catch (error) {
39
+ console.error('Query failed:', error);
40
+ fs.writeFileSync('e:/mynewproject2/server/query_error.txt', error.message + '\n' + error.stack);
41
+ } finally {
42
+ await prisma.$disconnect();
43
+ }
44
+ }
45
+
46
+ testQuery();
server/verify_and_fix_column.js ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+ import fs from 'fs';
4
+
5
+ const prisma = new PrismaClient();
6
+
7
+ async function main() {
8
+ const output = [];
9
+ const log = (msg) => {
10
+ console.log(msg);
11
+ output.push(String(msg));
12
+ };
13
+
14
+ try {
15
+ // 1. Get current connection info (masked)
16
+ const url = process.env.DATABASE_URL || 'No URL found in env';
17
+ log(`Connecting to: ${url.replace(/:[^:@]+@/, ':***@')}`);
18
+
19
+ // 2. Check current columns
20
+ log('\n--- Checking Columns ---');
21
+ const columns = await prisma.$queryRawUnsafe(`
22
+ SELECT column_name, data_type
23
+ FROM information_schema.columns
24
+ WHERE table_name = 'Product'
25
+ ORDER BY column_name;
26
+ `);
27
+
28
+ const colNames = columns.map(c => c.column_name);
29
+ log(`Columns found (${colNames.length}): ${colNames.join(', ')}`);
30
+
31
+ if (colNames.includes('scrapedReviews')) {
32
+ log('\nโœ… "scrapedReviews" column ALREADY EXISTS.');
33
+ } else {
34
+ log('\nโŒ "scrapedReviews" column MISSING. Attempting to add...');
35
+
36
+ try {
37
+ await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`);
38
+ log('ALTER TABLE command executed.');
39
+
40
+ // Verify again
41
+ const verify = await prisma.$queryRawUnsafe(`
42
+ SELECT column_name
43
+ FROM information_schema.columns
44
+ WHERE table_name = 'Product' AND column_name = 'scrapedReviews';
45
+ `);
46
+
47
+ if (verify.length > 0) {
48
+ log('โœ… Column successfully added!');
49
+ } else {
50
+ log('โŒ FAILED to add column even after command.');
51
+ }
52
+ } catch (e) {
53
+ log(`โŒ Error adding column: ${e.message}`);
54
+ }
55
+ }
56
+
57
+ // 3. Check for any other issues (e.g., conflicting migrations)
58
+ log('\n--- Checking Migration Status (via _prisma_migrations table if exists) ---');
59
+ try {
60
+ const migrations = await prisma.$queryRawUnsafe(`SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY finished_at DESC LIMIT 5;`);
61
+ log('Recent migrations:');
62
+ migrations.forEach(m => log(`- ${m.migration_name} (${m.finished_at})`));
63
+ } catch (e) {
64
+ log('Could not read _prisma_migrations (this is normal if not using migrate dev): ' + e.message);
65
+ }
66
+
67
+ } catch (e) {
68
+ log(`\nโŒ CRITICAL ERROR: ${e.message}`);
69
+ } finally {
70
+ await prisma.$disconnect();
71
+ fs.writeFileSync('db_verify_output.txt', output.join('\n'));
72
+ }
73
+ }
74
+
75
+ main();
server/verify_column_added.js ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+ import fs from 'fs';
4
+
5
+ const prisma = new PrismaClient();
6
+
7
+ async function main() {
8
+ try {
9
+ const result = await prisma.$queryRawUnsafe(`
10
+ SELECT column_name
11
+ FROM information_schema.columns
12
+ WHERE table_name = 'Product' AND column_name = 'scrapedReviews';
13
+ `);
14
+
15
+ let message = '';
16
+ if (result.length > 0) {
17
+ message = 'SUCCESS: "scrapedReviews" column exists.';
18
+ } else {
19
+ message = 'FAILURE: "scrapedReviews" column MISSING.';
20
+ }
21
+ console.log(message);
22
+ fs.writeFileSync('db_check_result.txt', message);
23
+ } catch (e) {
24
+ console.error('Error checking column:', e);
25
+ fs.writeFileSync('db_check_result.txt', 'ERROR: ' + e.message);
26
+ } finally {
27
+ await prisma.$disconnect();
28
+ }
29
+ }
30
+
31
+ main();
server/verify_fix.js ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import { PrismaClient } from '@prisma/client';
3
+ import fs from 'fs';
4
+
5
+ const prisma = new PrismaClient();
6
+
7
+ async function main() {
8
+ const output = [];
9
+ try {
10
+ const result = await prisma.$queryRawUnsafe(`
11
+ SELECT column_name
12
+ FROM information_schema.columns
13
+ WHERE table_name = 'Product' AND column_name = 'scrapedReviews';
14
+ `);
15
+
16
+ output.push(JSON.stringify(result));
17
+
18
+ if (result.length > 0) {
19
+ output.push('VERIFIED: scrapedReviews column exists.');
20
+ } else {
21
+ output.push('FAILED: scrapedReviews column missing.');
22
+ }
23
+ } catch (e) {
24
+ output.push('ERROR: ' + e.message);
25
+ } finally {
26
+ await prisma.$disconnect();
27
+ fs.writeFileSync('db_verify.txt', output.join('\n'));
28
+ }
29
+ }
30
+
31
+ main();
src/components/product/ProductActionSheet.tsx CHANGED
@@ -2,6 +2,7 @@ import React, { useEffect } from 'react';
2
  import { motion, AnimatePresence } from 'framer-motion';
3
  import { X, Plane, Ship, ZoomIn, ShoppingCart, RefreshCw } from 'lucide-react';
4
  import ProductOptions from './ProductOptions';
 
5
 
6
  interface ProductActionSheetProps {
7
  isOpen: boolean;
@@ -104,11 +105,11 @@ const ProductActionSheet: React.FC<ProductActionSheetProps> = ({
104
  </button>
105
  </div>
106
  <p className="text-sm text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
107
- {product?.name}
108
  </p>
109
  {currentVariant && (
110
  <p className="text-xs font-bold text-slate-400 mt-2">
111
- ุงู„ู…ุญุฏุฏ: {Object.values(selectedOptions).join(' / ')}
112
  </p>
113
  )}
114
  </div>
 
2
  import { motion, AnimatePresence } from 'framer-motion';
3
  import { X, Plane, Ship, ZoomIn, ShoppingCart, RefreshCw } from 'lucide-react';
4
  import ProductOptions from './ProductOptions';
5
+ import { fixMojibake } from '../../utils/mojibakeFixer';
6
 
7
  interface ProductActionSheetProps {
8
  isOpen: boolean;
 
105
  </button>
106
  </div>
107
  <p className="text-sm text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
108
+ {fixMojibake(product?.name)}
109
  </p>
110
  {currentVariant && (
111
  <p className="text-xs font-bold text-slate-400 mt-2">
112
+ ุงู„ู…ุญุฏุฏ: {Object.values(selectedOptions).map(v => fixMojibake(v)).join(' / ')}
113
  </p>
114
  )}
115
  </div>
src/components/product/ProductDescription.tsx CHANGED
@@ -1,4 +1,5 @@
1
  import React from 'react';
 
2
 
3
  interface ProductDescriptionProps {
4
  productName?: string;
@@ -61,11 +62,11 @@ const ProductDescription: React.FC<ProductDescriptionProps> = ({
61
  parsedSpecs = specsData.map(item => {
62
  if (typeof item === 'object' && item !== null) {
63
  return {
64
- label: item.label || item.name || item.key || '',
65
- value: String(item.value || item.val || '')
66
  };
67
  }
68
- return { label: '', value: String(item) };
69
  }).filter(item => item.value);
70
  } else if (typeof specsData === 'string') {
71
  parsedSpecs = specsData.split('\n')
@@ -73,18 +74,18 @@ const ProductDescription: React.FC<ProductDescriptionProps> = ({
73
  const parts = line.split(':');
74
  if (parts.length >= 2) {
75
  return {
76
- label: parts[0].trim(),
77
- value: parts.slice(1).join(':').trim()
78
  };
79
  }
80
- return { label: '', value: line.trim() };
81
  })
82
  .filter(item => item.value.length > 0);
83
  } else if (typeof specsData === 'object' && specsData !== null) {
84
  parsedSpecs = Object.entries(specsData)
85
  .map(([label, value]) => ({
86
- label,
87
- value: typeof value === 'object' ? JSON.stringify(value) : String(value)
88
  }));
89
  }
90
  }
@@ -113,7 +114,7 @@ const ProductDescription: React.FC<ProductDescriptionProps> = ({
113
  <div className="bg-slate-50 dark:bg-slate-800/40 rounded-2xl p-5 border border-slate-100 dark:border-white/5">
114
  {showDescription && (
115
  <div className="text-slate-600 dark:text-slate-300 text-[15px] leading-loose whitespace-pre-line font-medium mb-6 last:mb-0">
116
- {description}
117
  </div>
118
  )}
119
 
 
1
  import React from 'react';
2
+ import { fixMojibake } from '../../utils/mojibakeFixer';
3
 
4
  interface ProductDescriptionProps {
5
  productName?: string;
 
62
  parsedSpecs = specsData.map(item => {
63
  if (typeof item === 'object' && item !== null) {
64
  return {
65
+ label: fixMojibake(item.label || item.name || item.key || ''),
66
+ value: fixMojibake(String(item.value || item.val || ''))
67
  };
68
  }
69
+ return { label: '', value: fixMojibake(String(item)) };
70
  }).filter(item => item.value);
71
  } else if (typeof specsData === 'string') {
72
  parsedSpecs = specsData.split('\n')
 
74
  const parts = line.split(':');
75
  if (parts.length >= 2) {
76
  return {
77
+ label: fixMojibake(parts[0].trim()),
78
+ value: fixMojibake(parts.slice(1).join(':').trim())
79
  };
80
  }
81
+ return { label: '', value: fixMojibake(line.trim()) };
82
  })
83
  .filter(item => item.value.length > 0);
84
  } else if (typeof specsData === 'object' && specsData !== null) {
85
  parsedSpecs = Object.entries(specsData)
86
  .map(([label, value]) => ({
87
+ label: fixMojibake(label),
88
+ value: fixMojibake(typeof value === 'object' ? JSON.stringify(value) : String(value))
89
  }));
90
  }
91
  }
 
114
  <div className="bg-slate-50 dark:bg-slate-800/40 rounded-2xl p-5 border border-slate-100 dark:border-white/5">
115
  {showDescription && (
116
  <div className="text-slate-600 dark:text-slate-300 text-[15px] leading-loose whitespace-pre-line font-medium mb-6 last:mb-0">
117
+ {fixMojibake(description)}
118
  </div>
119
  )}
120
 
src/components/product/ProductInfo.tsx CHANGED
@@ -1,5 +1,6 @@
1
  import React from 'react';
2
  import { calculateInclusivePrice } from '../../utils/shipping';
 
3
 
4
  interface ProductInfoProps {
5
  price: number;
@@ -51,13 +52,13 @@ const ProductInfo: React.FC<ProductInfoProps> = ({
51
  <div className="mb-6">
52
  {/* Price section removed as requested */}
53
 
54
- <h2 className="text-slate-900 dark:text-white text-xl font-bold leading-tight mt-3">{name}</h2>
55
 
56
 
57
  {deliveryTime && (
58
  <div className="flex items-center gap-2 mt-2">
59
  <span className="text-xs font-bold text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-800 px-2 py-1 rounded-lg border border-slate-100 dark:border-slate-700">
60
- ูˆู‚ุช ุชุฌู‡ูŠุฒ ุงู„ุจุถุงุนุฉ: {deliveryTime} ูŠูˆู…
61
  </span>
62
  </div>
63
  )}
 
1
  import React from 'react';
2
  import { calculateInclusivePrice } from '../../utils/shipping';
3
+ import { fixMojibake } from '../../utils/mojibakeFixer';
4
 
5
  interface ProductInfoProps {
6
  price: number;
 
52
  <div className="mb-6">
53
  {/* Price section removed as requested */}
54
 
55
+ <h2 className="text-slate-900 dark:text-white text-xl font-bold leading-tight mt-3">{fixMojibake(name)}</h2>
56
 
57
 
58
  {deliveryTime && (
59
  <div className="flex items-center gap-2 mt-2">
60
  <span className="text-xs font-bold text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-800 px-2 py-1 rounded-lg border border-slate-100 dark:border-slate-700">
61
+ ูˆู‚ุช ุชุฌู‡ูŠุฒ ุงู„ุจุถุงุนุฉ: {fixMojibake(deliveryTime)} ูŠูˆู…
62
  </span>
63
  </div>
64
  )}
src/components/product/ProductOptions.tsx CHANGED
@@ -1,5 +1,6 @@
1
  import React from 'react';
2
  import LazyImage from '../LazyImage';
 
3
 
4
  interface Option {
5
  id: number;
@@ -72,7 +73,9 @@ const ProductOptions: React.FC<ProductOptionsProps> = ({
72
  }
73
  });
74
 
75
- const label = values.join('ุŒ '); // Use Arabic comma
 
 
76
 
77
  // SKIP duplicates
78
  if (seenLabels.has(label)) return null;
@@ -128,20 +131,21 @@ const ProductOptions: React.FC<ProductOptionsProps> = ({
128
  return (
129
  <div key={option.id} className="space-y-3">
130
  <h3 className="text-slate-900 dark:text-white text-sm font-black flex items-center gap-2">
131
- {option.name}
132
  {!isInformational && values && values.length > 0 && <span className="text-[10px] text-slate-400 font-normal">(ุงุฎุชุฑ ูˆุงุญุฏ)</span>}
133
  </h3>
134
  <div className="flex flex-wrap gap-2">
135
  {values && values.map((val: any) => {
136
- const valString = typeof val === 'object' ? (val.value || val.name || JSON.stringify(val)) : String(val);
 
137
  return (
138
  <div
139
- key={valString}
140
- onClick={() => !isInformational && onOptionSelect(option.name, valString)}
141
  className={`px-4 py-2 rounded-xl text-xs font-bold transition-all border-2 ${
142
  isInformational
143
  ? 'bg-slate-50 dark:bg-slate-800/50 border-slate-100 dark:border-slate-700 text-slate-600 dark:text-slate-400'
144
- : selectedOptions[option.name] === valString
145
  ? 'bg-primary border-primary text-white shadow-lg shadow-primary/20 scale-105 cursor-pointer'
146
  : 'bg-white dark:bg-slate-800 border-slate-100 dark:border-white/10 text-slate-600 dark:text-slate-300 hover:border-primary/50 cursor-pointer'
147
  }`}
 
1
  import React from 'react';
2
  import LazyImage from '../LazyImage';
3
+ import { fixMojibake } from '../../utils/mojibakeFixer';
4
 
5
  interface Option {
6
  id: number;
 
73
  }
74
  });
75
 
76
+ // Fix mojibake in values
77
+ const fixedValues = values.map(v => fixMojibake(v));
78
+ const label = fixedValues.join('ุŒ '); // Use Arabic comma
79
 
80
  // SKIP duplicates
81
  if (seenLabels.has(label)) return null;
 
131
  return (
132
  <div key={option.id} className="space-y-3">
133
  <h3 className="text-slate-900 dark:text-white text-sm font-black flex items-center gap-2">
134
+ {fixMojibake(option.name)}
135
  {!isInformational && values && values.length > 0 && <span className="text-[10px] text-slate-400 font-normal">(ุงุฎุชุฑ ูˆุงุญุฏ)</span>}
136
  </h3>
137
  <div className="flex flex-wrap gap-2">
138
  {values && values.map((val: any) => {
139
+ const rawValString = typeof val === 'object' ? (val.value || val.name || JSON.stringify(val)) : String(val);
140
+ const valString = fixMojibake(rawValString);
141
  return (
142
  <div
143
+ key={rawValString}
144
+ onClick={() => !isInformational && onOptionSelect(option.name, rawValString)}
145
  className={`px-4 py-2 rounded-xl text-xs font-bold transition-all border-2 ${
146
  isInformational
147
  ? 'bg-slate-50 dark:bg-slate-800/50 border-slate-100 dark:border-slate-700 text-slate-600 dark:text-slate-400'
148
+ : selectedOptions[option.name] === rawValString
149
  ? 'bg-primary border-primary text-white shadow-lg shadow-primary/20 scale-105 cursor-pointer'
150
  : 'bg-white dark:bg-slate-800 border-slate-100 dark:border-white/10 text-slate-600 dark:text-slate-300 hover:border-primary/50 cursor-pointer'
151
  }`}
src/components/product/ProductSpecs.tsx CHANGED
@@ -1,4 +1,5 @@
1
  import React from 'react';
 
2
 
3
  interface ProductSpecsProps {
4
  specs?: string | Record<string, any>;
@@ -27,11 +28,11 @@ const ProductSpecs: React.FC<ProductSpecsProps> = ({ specs }) => {
27
  parsedSpecs = specsData.map(item => {
28
  if (typeof item === 'object' && item !== null) {
29
  return {
30
- label: item.label || item.name || item.key || '',
31
- value: String(item.value || item.val || '')
32
  };
33
  }
34
- return { label: '', value: String(item) };
35
  }).filter(item => item.value && item.value.length > 0);
36
  } else if (typeof specsData === 'string') {
37
  parsedSpecs = specsData.split('\n')
@@ -39,11 +40,11 @@ const ProductSpecs: React.FC<ProductSpecsProps> = ({ specs }) => {
39
  const parts = line.split(':');
40
  if (parts.length >= 2) {
41
  return {
42
- label: parts[0].trim(),
43
- value: parts.slice(1).join(':').trim()
44
  };
45
  }
46
- return { label: '', value: line.trim() };
47
  })
48
  .filter(item => {
49
  const label = item.label.toLowerCase();
@@ -61,8 +62,8 @@ const ProductSpecs: React.FC<ProductSpecsProps> = ({ specs }) => {
61
  label !== 'price_rmb';
62
  })
63
  .map(([label, value]) => ({
64
- label,
65
- value: typeof value === 'object' ? JSON.stringify(value) : String(value)
66
  }));
67
  }
68
 
 
1
  import React from 'react';
2
+ import { fixMojibake } from '../../utils/mojibakeFixer';
3
 
4
  interface ProductSpecsProps {
5
  specs?: string | Record<string, any>;
 
28
  parsedSpecs = specsData.map(item => {
29
  if (typeof item === 'object' && item !== null) {
30
  return {
31
+ label: fixMojibake(item.label || item.name || item.key || ''),
32
+ value: fixMojibake(String(item.value || item.val || ''))
33
  };
34
  }
35
+ return { label: '', value: fixMojibake(String(item)) };
36
  }).filter(item => item.value && item.value.length > 0);
37
  } else if (typeof specsData === 'string') {
38
  parsedSpecs = specsData.split('\n')
 
40
  const parts = line.split(':');
41
  if (parts.length >= 2) {
42
  return {
43
+ label: fixMojibake(parts[0].trim()),
44
+ value: fixMojibake(parts.slice(1).join(':').trim())
45
  };
46
  }
47
+ return { label: '', value: fixMojibake(line.trim()) };
48
  })
49
  .filter(item => {
50
  const label = item.label.toLowerCase();
 
62
  label !== 'price_rmb';
63
  })
64
  .map(([label, value]) => ({
65
+ label: fixMojibake(label),
66
+ value: fixMojibake(typeof value === 'object' ? JSON.stringify(value) : String(value))
67
  }));
68
  }
69
 
src/components/product/ReviewsSection.tsx CHANGED
@@ -52,8 +52,8 @@ const ReviewsSection: React.FC<ReviewsSectionProps> = ({
52
  (reviewSummary.images && reviewSummary.images.length > 0)
53
  ));
54
 
55
- const displayReviews = reviews.slice(0, 10);
56
- const hasMoreReviews = reviews.length > 10;
57
 
58
  if (!hasRealReviews && loading) {
59
  return (
@@ -239,28 +239,32 @@ const ReviewsSection: React.FC<ReviewsSectionProps> = ({
239
 
240
  {/* All Reviews Modal */}
241
  {isAllReviewsModalOpen && (
242
- <div className="fixed inset-0 z-[110] bg-slate-950/40 backdrop-blur-md flex items-end sm:items-center justify-center p-0 sm:p-6 animate-in fade-in duration-300">
243
  <div
244
- className="bg-background-light dark:bg-background-dark w-full max-w-[95vw] lg:max-w-7xl h-[85vh] sm:h-[80vh] rounded-t-[45px] sm:rounded-[45px] overflow-hidden flex flex-col shadow-2xl animate-in slide-in-from-bottom-full duration-500"
245
  onClick={(e) => e.stopPropagation()}
246
  >
247
  {/* Modal Header */}
248
- <div className="px-8 pt-8 pb-6 flex items-center justify-between border-b border-slate-100 dark:border-white/5">
249
  <div className="flex flex-col">
250
  <h3 className="text-slate-900 dark:text-white text-xl font-black">ุฌู…ูŠุน ุงู„ุชู‚ูŠูŠู…ุงุช</h3>
251
- <p className="text-[10px] text-slate-400 font-bold mt-0.5 tracking-wide">ุชุฌุงุฑุจ ุญู‚ูŠู‚ูŠุฉ ู…ู† ู…ุดุชุฑูŠ ุงู„ู…ู†ุชุฌ</p>
 
 
252
  </div>
253
  <button
254
  onClick={() => setIsAllReviewsModalOpen(false)}
255
- className="size-12 rounded-2xl bg-slate-100 dark:bg-white/5 flex items-center justify-center text-slate-500 hover:bg-slate-200 dark:hover:bg-white/10 transition-all"
256
  >
257
- <X size={24} />
258
  </button>
259
  </div>
260
 
261
  {/* Modal Content */}
262
- <div className="flex-1 overflow-y-auto p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 no-scrollbar pb-12">
263
- {reviews.map((review, idx) => renderReviewCard(review, idx))}
 
 
264
  </div>
265
  </div>
266
  </div>
 
52
  (reviewSummary.images && reviewSummary.images.length > 0)
53
  ));
54
 
55
+ const displayReviews = reviews.slice(0, 2);
56
+ const hasMoreReviews = reviews.length > 2;
57
 
58
  if (!hasRealReviews && loading) {
59
  return (
 
239
 
240
  {/* All Reviews Modal */}
241
  {isAllReviewsModalOpen && (
242
+ <div className="fixed inset-0 z-[110] bg-slate-950/40 backdrop-blur-md flex items-center justify-center p-4 animate-in fade-in duration-300" onClick={() => setIsAllReviewsModalOpen(false)}>
243
  <div
244
+ className="bg-white dark:bg-slate-900 w-full max-w-5xl h-[85vh] rounded-[32px] overflow-hidden flex flex-col shadow-2xl animate-in slide-in-from-bottom-10 duration-500 border border-slate-100 dark:border-white/5"
245
  onClick={(e) => e.stopPropagation()}
246
  >
247
  {/* Modal Header */}
248
+ <div className="px-6 py-5 flex items-center justify-between border-b border-slate-100 dark:border-white/5 bg-white/50 dark:bg-slate-900/50 backdrop-blur-sm sticky top-0 z-10">
249
  <div className="flex flex-col">
250
  <h3 className="text-slate-900 dark:text-white text-xl font-black">ุฌู…ูŠุน ุงู„ุชู‚ูŠูŠู…ุงุช</h3>
251
+ <p className="text-[12px] text-slate-500 font-bold mt-1">
252
+ {reviews.length} ุชู‚ูŠูŠู… ู…ู† ุนู…ู„ุงุก ุญู‚ูŠู‚ูŠูŠู†
253
+ </p>
254
  </div>
255
  <button
256
  onClick={() => setIsAllReviewsModalOpen(false)}
257
+ className="size-10 rounded-full bg-slate-100 dark:bg-white/5 flex items-center justify-center text-slate-500 hover:bg-slate-200 dark:hover:bg-white/10 transition-all hover:rotate-90"
258
  >
259
+ <X size={20} />
260
  </button>
261
  </div>
262
 
263
  {/* Modal Content */}
264
+ <div className="flex-1 overflow-y-auto p-6 scrollbar-thin scrollbar-thumb-slate-200 dark:scrollbar-thumb-slate-700">
265
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
266
+ {reviews.map((review, idx) => renderReviewCard(review, idx))}
267
+ </div>
268
  </div>
269
  </div>
270
  </div>
src/pages/AdminDashboard.tsx CHANGED
@@ -10,7 +10,7 @@ import {
10
  TrendingUp as _TrendingUp,
11
  CheckCircle2,
12
  Clock,
13
- ArrowRight,
14
  Download,
15
  Calendar,
16
  Eye,
 
10
  TrendingUp as _TrendingUp,
11
  CheckCircle2,
12
  Clock,
13
+ ArrowLeft,
14
  Download,
15
  Calendar,
16
  Eye,
src/pages/CheckoutPaymentAddress.tsx CHANGED
@@ -1,7 +1,6 @@
1
  import React, { useState, useEffect, useCallback } from 'react';
2
  import { useNavigate, Link } from 'react-router-dom';
3
  import {
4
- ArrowRight,
5
  MapPin,
6
  ChevronLeft,
7
  MapPinPlus,
 
1
  import React, { useState, useEffect, useCallback } from 'react';
2
  import { useNavigate, Link } from 'react-router-dom';
3
  import {
 
4
  MapPin,
5
  ChevronLeft,
6
  MapPinPlus,
src/pages/ProductDetails.tsx CHANGED
@@ -12,7 +12,6 @@ import LazyImage from '../components/LazyImage';
12
  import ProductHeader from '../components/product/ProductHeader';
13
  import ImageGallery from '../components/product/ImageGallery';
14
  import ProductInfo from '../components/product/ProductInfo';
15
- import ProductOptions from '../components/product/ProductOptions';
16
  import ProductDescription from '../components/product/ProductDescription';
17
  import ProductSpecs from '../components/product/ProductSpecs';
18
  import ReviewsSection from '../components/product/ReviewsSection';
@@ -29,7 +28,7 @@ interface Review {
29
  images?: string[];
30
  }
31
 
32
- import { AlertCircle, Package, Plane, Ship } from 'lucide-react';
33
 
34
  const ProductDetails: React.FC = () => {
35
  const navigate = useNavigate();
 
12
  import ProductHeader from '../components/product/ProductHeader';
13
  import ImageGallery from '../components/product/ImageGallery';
14
  import ProductInfo from '../components/product/ProductInfo';
 
15
  import ProductDescription from '../components/product/ProductDescription';
16
  import ProductSpecs from '../components/product/ProductSpecs';
17
  import ReviewsSection from '../components/product/ReviewsSection';
 
28
  images?: string[];
29
  }
30
 
31
+ import { AlertCircle, Package } from 'lucide-react';
32
 
33
  const ProductDetails: React.FC = () => {
34
  const navigate = useNavigate();