Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
291 lines (235 loc) · 9.63 KB
/
Copy pathapp.py
File metadata and controls
291 lines (235 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
发货单处理 Web 应用
在任何设备上通过浏览器上传Excel文件并处理
"""
from flask import Flask, render_template, request, send_file, jsonify
from werkzeug.utils import secure_filename
import pandas as pd
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.cell.rich_text import TextBlock, CellRichText
from openpyxl.cell.text import InlineFont
import os
import re
from datetime import datetime
from io import BytesIO
import zipfile
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB
app.config['UPLOAD_FOLDER'] = 'temp_uploads'
# 创建临时文件夹
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
ALLOWED_EXTENSIONS = {'xlsx', 'xls'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def extract_date_from_filename(filename):
"""从文件名提取日期"""
cleaned = re.sub(r'[^\w\-]', '', filename)
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', cleaned)
if match:
year, month, day = match.groups()
return f"{year[2:]}{month}{day}"
match = re.search(r'(\d{4})(\d{2})(\d{2})', cleaned)
if match:
year, month, day = match.groups()
return f"{year[2:]}{month}{day}"
return datetime.now().strftime("%y%m%d")
def extract_model(attr):
"""从属性集提取产品型号用于排序"""
if pd.isna(attr):
return ('zzz', 0, '')
attr = str(attr).lower()
if 'galaxy' in attr or 'samsung' in attr:
match = re.search(r'galaxy\s+([a-z])(\d+)', attr)
if match:
line = match.group(1)
num = int(match.group(2))
prefix = 'aaa_galaxy_' + line
return (prefix, num, attr)
else:
return ('aaa_galaxy_zzz', 0, attr)
elif 'iphone' in attr:
match = re.search(r'iphone\s*(\d+)', attr)
if match:
num = int(match.group(1))
return ('bbb_iphone', num, attr)
else:
return ('bbb_iphone_zzz', 0, attr)
else:
return ('ccc_other', 0, attr)
def process_beijia(merchant_id, attr):
"""背夹处理"""
if pd.isna(merchant_id) or '背夹' not in str(merchant_id):
return attr
merchant_id = str(merchant_id)
attr = str(attr) if pd.notna(attr) else ''
if '-' in attr:
product = '-'.join(attr.split('-')[1:])
else:
product = attr
if '黑深蓝' in merchant_id:
return f"背夹黑蓝-{product}"
else:
return f"背夹黑色-{product}"
def create_fahuodan(df, output_path):
"""创建发货单"""
wb = Workbook()
ws = wb.active
ws.title = "发货单"
headers = ['序号', '订单号', '商家货号', '属性集', '下单数量']
gray_fill = PatternFill(start_color="D9D9D9", end_color="D9D9D9", fill_type="solid")
title_font = Font(name='宋体', size=13, bold=True)
body_font = Font(name='宋体', size=10)
center_align = Alignment(horizontal='center', vertical='center')
thin_border = Border(
left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin')
)
for col_idx, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col_idx, value=header)
cell.fill = gray_fill
cell.font = title_font
cell.alignment = center_align
cell.border = thin_border
for row_idx in range(len(df)):
row = df.iloc[row_idx]
for col_idx, col in enumerate(headers, 1):
cell = ws.cell(row=row_idx + 2, column=col_idx, value=row[col])
cell.font = body_font
cell.alignment = center_align
cell.border = thin_border
ws.column_dimensions['A'].width = 5
ws.column_dimensions['B'].width = 16.12
ws.column_dimensions['C'].width = 25.25
ws.column_dimensions['D'].width = 32
ws.column_dimensions['E'].width = 9
wb.save(output_path)
def create_fahuodan_jiandan(df, output_path):
"""创建发货单拣货"""
df_sorted = df.copy()
df_sorted['_sort'] = df_sorted['属性集'].apply(lambda x: extract_model(x))
df_sorted = df_sorted.sort_values('_sort')
df_sorted = df_sorted.drop('_sort', axis=1)
create_fahuodan(df_sorted, output_path)
def create_xuchaibao(df, output_path):
"""创建需拆包"""
wb = Workbook()
ws = wb.active
ws.title = "需拆包"
df_chaibao = df.copy()
df_chaibao['属性集'] = df_chaibao.apply(
lambda row: process_beijia(row['商家货号'], row['属性集']), axis=1
)
title_font = Font(name='宋体', size=18, bold=True)
body_font = Font(name='宋体', size=12)
number_font = Font(name='宋体', size=18, bold=True)
order_font = Font(name='Times New Roman', size=10)
center_align = Alignment(horizontal='center', vertical='center')
medium = Side(style='medium')
thin = Side(style='thin')
none = Side(style='none')
row = 1
for idx in range(len(df_chaibao)):
item = df_chaibao.iloc[idx]
c1 = ws.cell(row=row, column=1, value='序号')
c1.font = title_font
c1.alignment = center_align
c1.border = Border(left=medium, right=medium, top=medium, bottom=thin)
c2 = ws.cell(row=row, column=2, value=item['属性集'])
c2.font = body_font
c2.alignment = center_align
c2.border = Border(left=medium, right=medium, top=medium, bottom=thin)
ws.merge_cells(f'A{row+1}:A{row+3}')
c3 = ws.cell(row=row+1, column=1, value=item['序号'])
c3.font = number_font
c3.alignment = center_align
c3.border = Border(left=medium, right=medium, top=thin, bottom=thin)
number_inline = InlineFont(rFont='宋体', sz=18, b=True)
unit_inline = InlineFont(rFont='宋体', sz=14)
number_text = TextBlock(number_inline, str(item['下单数量']))
unit_text = TextBlock(unit_inline, " 个")
c4 = ws.cell(row=row+1, column=2)
c4.value = CellRichText(number_text, unit_text)
c4.alignment = center_align
c4.border = Border(left=medium, right=medium, top=thin, bottom=none)
c5 = ws.cell(row=row+2, column=2, value='需拆包')
c5.font = body_font
c5.alignment = center_align
c5.border = Border(left=medium, right=medium, top=none, bottom=none)
c6 = ws.cell(row=row+3, column=2, value=item['订单号'])
c6.font = order_font
c6.alignment = center_align
c6.border = Border(left=medium, right=medium, top=none, bottom=medium)
row += 4
ws.column_dimensions['A'].width = 8
ws.column_dimensions['B'].width = 37
wb.save(output_path)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
try:
# 检查文件
if 'file' not in request.files:
return jsonify({'error': '没有上传文件'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': '文件名为空'}), 400
if not allowed_file(file.filename):
return jsonify({'error': '只支持 .xlsx 或 .xls 文件'}), 400
# 保存上传的文件
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# 读取Excel
df = pd.read_excel(filepath)
# 验证列名
required_cols = ['订单号', '商家货号', '属性集', '下单数量']
missing_cols = [col for col in required_cols if col not in df.columns]
if missing_cols:
return jsonify({'error': f'Excel缺少列: {", ".join(missing_cols)}'}), 400
# 添加序号
if '序号' not in df.columns:
df.insert(0, '序号', range(1, len(df) + 1))
# 选择列
output_cols = ['序号', '订单号', '商家货号', '属性集', '下单数量']
df_output = df[output_cols].copy()
# 提取日期
date_str = extract_date_from_filename(filename)
# 创建临时文件
import tempfile
temp_dir = tempfile.mkdtemp()
file1 = os.path.join(temp_dir, f'发货单-{date_str}.xlsx')
file2 = os.path.join(temp_dir, f'发货单拣货-{date_str}.xlsx')
file3 = os.path.join(temp_dir, f'需拆包-{date_str}.xlsx')
create_fahuodan(df_output, file1)
create_fahuodan_jiandan(df_output, file2)
create_xuchaibao(df_output, file3)
# 创建ZIP文件
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
zip_file.write(file1, arcname=os.path.basename(file1))
zip_file.write(file2, arcname=os.path.basename(file2))
zip_file.write(file3, arcname=os.path.basename(file3))
zip_buffer.seek(0)
# 清理
os.remove(filepath)
os.remove(file1)
os.remove(file2)
os.remove(file3)
os.rmdir(temp_dir)
return send_file(
zip_buffer,
mimetype='application/zip',
as_attachment=True,
download_name=f'fahuodan_{date_str}.zip'
)
except Exception as e:
return jsonify({'error': str(e)}), 500
import os
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(debug=False, host='0.0.0.0', port=port)