acf1349c
tangwang
fake 批量导入数据的脚步 ( ...
|
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
# Color definitions
COLORS = [
"Red", "Blue", "Green", "Yellow", "Black", "White", "Orange", "Purple",
"Pink", "Brown", "Gray", "Navy", "Beige", "Cream", "Maroon", "Olive",
"Teal", "Cyan", "Magenta", "Lime", "Indigo", "Gold", "Silver", "Bronze",
"Coral", "Turquoise", "Violet", "Khaki", "Charcoal", "Ivory"
]
def clean_value(value):
"""
Clean and normalize value.
Args:
value: Value to clean
Returns:
Cleaned string value
"""
if value is None:
return ''
value = str(value).strip()
# Remove surrounding quotes
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
return value
def parse_csv_row(row: dict) -> dict:
"""
Parse CSV row and extract fields.
Args:
row: CSV row dictionary
Returns:
Parsed data dictionary
"""
return {
'skuId': clean_value(row.get('skuId', '')),
'name': clean_value(row.get('name', '')),
'name_pinyin': clean_value(row.get('name_pinyin', '')),
'create_time': clean_value(row.get('create_time', '')),
'ruSkuName': clean_value(row.get('ruSkuName', '')),
'enSpuName': clean_value(row.get('enSpuName', '')),
'categoryName': clean_value(row.get('categoryName', '')),
'supplierName': clean_value(row.get('supplierName', '')),
'brandName': clean_value(row.get('brandName', '')),
'file_id': clean_value(row.get('file_id', '')),
'days_since_last_update': clean_value(row.get('days_since_last_update', '')),
'id': clean_value(row.get('id', '')),
'imageUrl': clean_value(row.get('imageUrl', ''))
}
def generate_handle(title: str) -> str:
"""
Generate URL-friendly handle from title.
Args:
title: Product title
Returns:
URL-friendly handle (ASCII only)
"""
|
acf1349c
tangwang
fake 批量导入数据的脚步 ( ...
|
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
|
def extract_material_from_title(title: str) -> str:
"""
Extract material from title by taking the last word after splitting by space.
按照商品标题空格分割后的最后一个字符串作为material。
例如:"消防套 塑料【英文包装】" -> 最后一个字符串是 "塑料【英文包装】"
Args:
title: Product title
Returns:
Material string (single value)
"""
if not title:
return 'default'
# Split by spaces (只按空格分割,保持原样)
parts = title.strip().split()
if parts:
# Get last part (最后一个字符串)
material = parts[-1]
# Remove brackets but keep content
material = re.sub(r'[【】\[\]()()]', '', material)
material = material.strip()
if material:
return material
return 'default'
def generate_single_variant_row(csv_data: dict, base_sku_id: int = 1) -> dict:
"""
Generate Excel row for Single variant (S type) product.
Args:
csv_data: Parsed CSV row data
base_sku_id: Base SKU ID for generating SKU code
Returns:
Dictionary mapping Excel column names to values
"""
# Parse create_time
try:
created_at = datetime.strptime(csv_data['create_time'], '%Y-%m-%d %H:%M:%S')
create_time_str = created_at.strftime('%Y-%m-%d %H:%M:%S')
except:
created_at = datetime.now() - timedelta(days=random.randint(1, 365))
create_time_str = created_at.strftime('%Y-%m-%d %H:%M:%S')
# Generate title - use name or enSpuName
title = csv_data['name'] or csv_data['enSpuName'] or 'Product'
# Generate handle - prefer enSpuName, then name_pinyin, then title
handle_source = csv_data['enSpuName'] or csv_data['name_pinyin'] or title
handle = generate_handle(handle_source)
if handle and not handle.startswith('products/'):
handle = f'products/{handle}'
# Generate SEO fields
seo_title = f"{title} - {csv_data['categoryName']}" if csv_data['categoryName'] else title
seo_description = f"购买{csv_data['brandName']}{title}" if csv_data['brandName'] else title
seo_keywords_parts = [title]
if csv_data['categoryName']:
seo_keywords_parts.append(csv_data['categoryName'])
if csv_data['brandName']:
seo_keywords_parts.append(csv_data['brandName'])
seo_keywords = ','.join(seo_keywords_parts)
# Generate tags from category and brand
tags_parts = []
if csv_data['categoryName']:
tags_parts.append(csv_data['categoryName'])
if csv_data['brandName']:
tags_parts.append(csv_data['brandName'])
tags = ','.join(tags_parts) if tags_parts else ''
# Generate prices
price = round(random.uniform(50, 500), 2)
compare_at_price = round(price * random.uniform(1.2, 1.5), 2)
cost_price = round(price * 0.6, 2)
# Generate random stock
inventory_quantity = random.randint(0, 100)
# Generate random weight
weight = round(random.uniform(0.1, 5.0), 2)
weight_unit = 'kg'
# Use skuId as SKU code
sku_code = csv_data['skuId'] or f'SKU-{base_sku_id}'
# Generate barcode
try:
sku_id = int(csv_data['skuId']) if csv_data['skuId'] else base_sku_id
barcode = f"BAR{sku_id:08d}"
except:
barcode = f"BAR{base_sku_id:08d}"
# Build description
description = f"<p>{csv_data['name']}</p>" if csv_data['name'] else ''
# Build brief (subtitle)
brief = csv_data['name'] or ''
# Excel row data
excel_row = {
'商品ID': '', # Empty for new products
'创建时间': create_time_str,
'商品标题*': title,
'商品属性*': 'S', # Single variant product
'商品副标题': brief,
'商品描述': description,
'SEO标题': seo_title,
'SEO描述': seo_description,
'SEO URL Handle': handle,
'SEO URL 重定向': 'N',
'SEO关键词': seo_keywords,
'商品上架': 'Y',
'需要物流': 'Y',
'商品收税': 'N',
'商品spu': '',
'启用虚拟销量': 'N',
'虚拟销量值': '',
'跟踪库存': 'Y',
'库存规则*': '1',
'专辑名称': csv_data['categoryName'] or '',
'标签': tags,
'供应商名称': csv_data['supplierName'] or '',
'供应商URL': '',
'款式1': '', # Empty for S type
'款式2': '', # Empty for S type
'款式3': '', # Empty for S type
'商品售价*': price,
'商品原价': compare_at_price,
'成本价': cost_price,
'商品SKU': sku_code,
'商品重量': weight,
'重量单位': weight_unit,
'商品条形码': barcode,
'商品库存': inventory_quantity,
'尺寸信息': '',
'原产地国别': '',
'HS(协调制度)代码': '',
'商品图片*': csv_data['imageUrl'] or '',
'商品备注': '',
'款式备注': '',
'商品主图': csv_data['imageUrl'] or '',
}
return excel_row
def generate_multi_variant_rows(csv_data: dict, base_sku_id: int = 1) -> list:
"""
Generate Excel rows for Multi variant (M+P type) product.
Returns a list of rows:
- First row: M (主商品) with option names
- Following rows: P (子款式) with option values
Args:
csv_data: Parsed CSV row data
base_sku_id: Base SKU ID for generating SKU codes
Returns:
List of dictionaries mapping Excel column names to values
"""
rows = []
# Parse create_time
try:
created_at = datetime.strptime(csv_data['create_time'], '%Y-%m-%d %H:%M:%S')
create_time_str = created_at.strftime('%Y-%m-%d %H:%M:%S')
except:
created_at = datetime.now() - timedelta(days=random.randint(1, 365))
create_time_str = created_at.strftime('%Y-%m-%d %H:%M:%S')
# Generate title
title = csv_data['name'] or csv_data['enSpuName'] or 'Product'
# Generate handle
handle_source = csv_data['enSpuName'] or csv_data['name_pinyin'] or title
handle = generate_handle(handle_source)
if handle and not handle.startswith('products/'):
handle = f'products/{handle}'
# Generate SEO fields
seo_title = f"{title} - {csv_data['categoryName']}" if csv_data['categoryName'] else title
seo_description = f"购买{csv_data['brandName']}{title}" if csv_data['brandName'] else title
seo_keywords_parts = [title]
if csv_data['categoryName']:
seo_keywords_parts.append(csv_data['categoryName'])
if csv_data['brandName']:
seo_keywords_parts.append(csv_data['brandName'])
seo_keywords = ','.join(seo_keywords_parts)
# Generate tags
tags_parts = []
if csv_data['categoryName']:
tags_parts.append(csv_data['categoryName'])
if csv_data['brandName']:
tags_parts.append(csv_data['brandName'])
tags = ','.join(tags_parts) if tags_parts else ''
# Extract material from title (last word after splitting by space)
material = extract_material_from_title(title)
# Generate color options: randomly select 2-10 colors from COLORS list
num_colors = random.randint(2, 10)
selected_colors = random.sample(COLORS, min(num_colors, len(COLORS)))
# Generate size options: 1-30, randomly select 4-8
num_sizes = random.randint(4, 8)
all_sizes = [str(i) for i in range(1, 31)]
selected_sizes = random.sample(all_sizes, num_sizes)
# Material has only one value
materials = [material]
# Generate all combinations (Cartesian product)
variants = list(itertools.product(selected_colors, selected_sizes, materials))
# Generate M row (主商品)
description = f"<p>{csv_data['name']}</p>" if csv_data['name'] else ''
brief = csv_data['name'] or ''
m_row = {
'商品ID': '',
'创建时间': create_time_str,
'商品标题*': title,
'商品属性*': 'M', # Main product
'商品副标题': brief,
'商品描述': description,
'SEO标题': seo_title,
'SEO描述': seo_description,
'SEO URL Handle': handle,
'SEO URL 重定向': 'N',
'SEO关键词': seo_keywords,
'商品上架': 'Y',
'需要物流': 'Y',
'商品收税': 'N',
'商品spu': '',
'启用虚拟销量': 'N',
'虚拟销量值': '',
'跟踪库存': 'Y',
'库存规则*': '1',
'专辑名称': csv_data['categoryName'] or '',
'标签': tags,
'供应商名称': csv_data['supplierName'] or '',
'供应商URL': '',
'款式1': 'color', # Option name
'款式2': 'size', # Option name
'款式3': 'material', # Option name
'商品售价*': '', # Empty for M row
'商品原价': '',
'成本价': '',
'商品SKU': '', # Empty for M row
'商品重量': '',
'重量单位': '',
'商品条形码': '',
'商品库存': '', # Empty for M row
'尺寸信息': '',
'原产地国别': '',
'HS(协调制度)代码': '',
'商品图片*': csv_data['imageUrl'] or '', # Main product image
'商品备注': '',
'款式备注': '',
'商品主图': csv_data['imageUrl'] or '',
}
rows.append(m_row)
# Generate P rows (子款式) for each variant combination
base_price = round(random.uniform(50, 500), 2)
for variant_idx, (color, size, mat) in enumerate(variants):
# Generate price variation (within ±20% of base)
price = round(base_price * random.uniform(0.8, 1.2), 2)
compare_at_price = round(price * random.uniform(1.2, 1.5), 2)
cost_price = round(price * 0.6, 2)
# Generate random stock
inventory_quantity = random.randint(0, 100)
# Generate random weight
weight = round(random.uniform(0.1, 5.0), 2)
weight_unit = 'kg'
# Generate SKU code
sku_code = f"{csv_data['skuId']}-{color}-{size}-{mat}" if csv_data['skuId'] else f'SKU-{base_sku_id}-{variant_idx+1}'
# Generate barcode
barcode = f"BAR{base_sku_id:08d}{variant_idx+1:03d}"
p_row = {
'商品ID': '',
'创建时间': create_time_str,
'商品标题*': title, # Same as M row
'商品属性*': 'P', # Variant
'商品副标题': '', # Empty for P row
'商品描述': '', # Empty for P row
'SEO标题': '', # Empty for P row
'SEO描述': '', # Empty for P row
'SEO URL Handle': '', # Empty for P row
'SEO URL 重定向': '',
'SEO关键词': '',
'商品上架': 'Y',
'需要物流': 'Y',
'商品收税': 'N',
'商品spu': '',
'启用虚拟销量': 'N',
'虚拟销量值': '',
'跟踪库存': 'Y',
'库存规则*': '1',
'专辑名称': '', # Empty for P row
'标签': '', # Empty for P row
'供应商名称': '', # Empty for P row
'供应商URL': '',
'款式1': color, # Option value
'款式2': size, # Option value
'款式3': mat, # Option value
'商品售价*': price,
'商品原价': compare_at_price,
'成本价': cost_price,
'商品SKU': sku_code,
'商品重量': weight,
'重量单位': weight_unit,
'商品条形码': barcode,
'商品库存': inventory_quantity,
'尺寸信息': '',
'原产地国别': '',
'HS(协调制度)代码': '',
'商品图片*': '', # Empty for P row (uses main product image)
'商品备注': '',
'款式备注': '',
'商品主图': '',
}
rows.append(p_row)
return rows
def read_csv_file(csv_file: str) -> list:
"""
Read CSV file and return list of parsed rows.
Args:
csv_file: Path to CSV file
Returns:
List of parsed CSV data dictionaries
"""
csv_data_list = []
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
parsed = parse_csv_row(row)
csv_data_list.append(parsed)
return csv_data_list
def create_excel_from_template(template_file: str, output_file: str, excel_rows: list):
"""
Create Excel file from template and fill with data rows.
Args:
template_file: Path to Excel template file
output_file: Path to output Excel file
excel_rows: List of dictionaries mapping Excel column names to values
"""
|