-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
239 lines (214 loc) · 9.78 KB
/
Copy pathserver.py
File metadata and controls
239 lines (214 loc) · 9.78 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
#!/usr/bin/env python3
"""STM Dashboard Server"""
from collections import defaultdict
from flask import Flask, request, jsonify, send_from_directory
from data_loader import load_all
app = Flask(__name__, static_folder='static')
PRODUCTS, DEPARTMENTS, HIERARCHY, SUMMARY, SUPPLIERS, CONTRACTS = load_all()
# Pre-compute ABC/XYZ for each product
def precompute_abc_xyz():
# Network-level margin
total_rev = sum(p['revenue'] for p in PRODUCTS)
total_prof = sum(p['profit'] for p in PRODUCTS)
net_margin = round(total_prof / max(total_rev, 1) * 100, 1)
# ABC across network (by revenue, 50/30/20)
sorted_net = sorted(PRODUCTS, key=lambda x: x['revenue'], reverse=True)
cum = 0
for p in sorted_net:
cum += p['revenue']
pct = cum / max(total_rev, 1) * 100
if pct <= 50: p['abc_network'] = 'A'
elif pct <= 80: p['abc_network'] = 'B'
else: p['abc_network'] = 'C'
# ABC across network by checks
total_ch = sum(p['checks'] for p in PRODUCTS)
sorted_net_ch = sorted(PRODUCTS, key=lambda x: x['checks'], reverse=True)
cum = 0
for p in sorted_net_ch:
cum += p['checks']
pct = cum / max(total_ch, 1) * 100
if pct <= 50: p['abc_checks_net'] = 'A'
elif pct <= 80: p['abc_checks_net'] = 'B'
else: p['abc_checks_net'] = 'C'
# Group by category for within-category ABC and XYZ
from collections import defaultdict as ddd
cat_groups = ddd(list)
for p in PRODUCTS:
cat_groups[f"{p['dept']}|{p['subgroup']}|{p['category']}"].append(p)
for cat_key, items in cat_groups.items():
# ABC within category by revenue
cat_rev = sum(p['revenue'] for p in items)
sorted_items = sorted(items, key=lambda x: x['revenue'], reverse=True)
cum = 0
for p in sorted_items:
cum += p['revenue']
pct = cum / max(cat_rev, 1) * 100
if pct <= 50: p['abc_category'] = 'A'
elif pct <= 80: p['abc_category'] = 'B'
else: p['abc_category'] = 'C'
# ABC within category by checks
cat_ch = sum(p['checks'] for p in items)
sorted_ch = sorted(items, key=lambda x: x['checks'], reverse=True)
cum = 0
for p in sorted_ch:
cum += p['checks']
pct = cum / max(cat_ch, 1) * 100
if pct <= 50: p['abc_checks_cat'] = 'A'
elif pct <= 80: p['abc_checks_cat'] = 'B'
else: p['abc_checks_cat'] = 'C'
# Margin vs network
for p in PRODUCTS:
p['margin_vs_network'] = 'Выше' if p['margin'] > net_margin else ('Ниже' if p['margin'] < net_margin else 'Равна')
print(f"📊 ABC/XYZ computed: net margin={net_margin}%, A/B/C = "
f"{sum(1 for p in PRODUCTS if p.get('abc_network')=='A')}/"
f"{sum(1 for p in PRODUCTS if p.get('abc_network')=='B')}/"
f"{sum(1 for p in PRODUCTS if p.get('abc_network')=='C')}")
precompute_abc_xyz()
@app.route('/')
def index(): return send_from_directory('static','index.html')
@app.route('/api/summary')
def api_summary(): return jsonify(SUMMARY)
@app.route('/api/departments')
def api_departments(): return jsonify(DEPARTMENTS)
@app.route('/api/hierarchy')
def api_hierarchy(): return jsonify(HIERARCHY)
@app.route('/api/suppliers')
def api_suppliers(): return jsonify(SUPPLIERS)
@app.route('/api/products')
def api_products():
a = request.args
f = PRODUCTS[:]
if a.get('dept'): f=[p for p in f if p['dept']==a['dept']]
if a.get('subgroup'): f=[p for p in f if p['subgroup']==a['subgroup']]
if a.get('category'): f=[p for p in f if p['category']==a['category']]
if a.get('search'):
q=a['search'].lower()
f=[p for p in f if q in p['name'].lower() or q in p['code'].lower()]
if a.get('supplier'):
q=a['supplier'].lower()
f=[p for p in f if q in p['supplier'].lower()]
if a.get('contract_type'): f=[p for p in f if p['contract_type']==a['contract_type']]
if a.get('has_sales')=='yes': f=[p for p in f if p['sales']>0]
elif a.get('has_sales')=='no': f=[p for p in f if p['sales']==0]
if a.get('min_margin'): f=[p for p in f if p['margin']>=float(a['min_margin'])]
if a.get('max_margin'): f=[p for p in f if p['margin']<=float(a['max_margin'])]
tr=sum(p['revenue'] for p in f)
tp=sum(p['profit'] for p in f)
sb=a.get('sort','revenue')
vs=['revenue','profit','sales','checks','margin','price','name','code','supplier','contract_type']
if sb not in vs: sb='revenue'
rv=a.get('dir','desc')=='desc'
if sb in('name','supplier','contract_type'):
f.sort(key=lambda x:x.get(sb,'')or'',reverse=rv)
else:
f.sort(key=lambda x:x.get(sb,0)or 0,reverse=rv)
pg=int(a.get('page',1))
pp=min(int(a.get('per_page',50)),200)
t=len(f); s=(pg-1)*pp
return jsonify({
'products':f[s:s+pp],'total':t,'page':pg,'per_page':pp,
'pages':(t+pp-1)//pp,
'stats':{'total_revenue':round(tr),'total_profit':round(tp),
'total_sales':round(sum(p['sales'] for p in f)),
'total_checks':sum(p['checks'] for p in f),
'avg_margin':round(tp/max(tr,1)*100,1)}
})
@app.route('/api/category_analysis')
def api_category_analysis():
a=request.args; f=PRODUCTS[:]
if a.get('dept'): f=[p for p in f if p['dept']==a['dept']]
if a.get('subgroup'): f=[p for p in f if p['subgroup']==a['subgroup']]
cd=defaultdict(lambda:{'r':0,'pr':0,'s':0,'ch':0,'cnt':0,'d':'','sg':'','sups':set(),'cts':set(),'prices':[]})
for p in f:
k=f"{p['dept']}|{p['subgroup']}|{p['category']}"
cd[k]['r']+=p['revenue']; cd[k]['pr']+=p['profit']
cd[k]['s']+=p['sales']; cd[k]['ch']+=p['checks']; cd[k]['cnt']+=1
cd[k]['d']=p['dept']; cd[k]['sg']=p['subgroup']
if p['supplier']: cd[k]['sups'].add(p['supplier'])
if p['contract_type']: cd[k]['cts'].add(p['contract_type'])
if p['price']>0: cd[k]['prices'].append(p['price'])
# Network average margin
total_rev_all = sum(v['r'] for v in cd.values())
total_prof_all = sum(v['pr'] for v in cd.values())
network_margin = round(total_prof_all / max(total_rev_all, 1) * 100, 1)
mr=float(a.get('min_revenue',0)); res=[]
for k,v in cd.items():
if v['r']<mr: continue
pts=k.split('|'); m=round(v['pr']/max(v['r'],1)*100,1)
ap=round(sum(v['prices'])/max(len(v['prices']),1),2)
res.append({'dept':pts[0],'subgroup':pts[1],'category':pts[2],
'revenue':round(v['r']),'profit':round(v['pr']),'sales':round(v['s']),
'checks':v['ch'],'count':v['cnt'],'margin':m,'avg_price':ap,
'avg_check':round(v['r']/max(v['ch'],1)),
'suppliers':len(v['sups']),'contracts':list(v['cts']),
'stm_score':round(v['r']*m/10000),
'margin_vs_network': 'Выше' if m > network_margin else ('Ниже' if m < network_margin else 'Равна')})
# ABC by revenue: A=top 50%, B=next 30%, C=remaining 20%
res_by_rev = sorted(res, key=lambda x: x['revenue'], reverse=True)
total_rev = sum(x['revenue'] for x in res_by_rev)
cum = 0
for item in res_by_rev:
cum += item['revenue']
pct = cum / max(total_rev, 1) * 100
if pct <= 50: item['abc_revenue'] = 'A'
elif pct <= 80: item['abc_revenue'] = 'B'
else: item['abc_revenue'] = 'C'
# ABC by checks: A=top 50%, B=next 30%, C=remaining 20%
res_by_ch = sorted(res, key=lambda x: x['checks'], reverse=True)
total_ch = sum(x['checks'] for x in res_by_ch)
cum = 0
for item in res_by_ch:
cum += item['checks']
pct = cum / max(total_ch, 1) * 100
if pct <= 50: item['abc_checks'] = 'A'
elif pct <= 80: item['abc_checks'] = 'B'
else: item['abc_checks'] = 'C'
# Revenue vs network mean
avg_rev = round(total_rev / max(len(res), 1)) if res else 0
for item in res:
item['revenue_vs_network'] = 'Выше' if item['revenue'] > avg_rev else ('Ниже' if item['revenue'] < avg_rev else 'Равна')
# Calculated role: ABC revenue + ABC checks combo
combo = item.get('abc_revenue','C') + item.get('abc_checks','C')
if combo[0] == 'C': # CA, CB, CC
item['role'] = 'Удобная'
elif combo in ('AA', 'AB'):
item['role'] = 'Приоритетная'
else: # AC, BA, BB, BC
item['role'] = 'Базовая'
res.sort(key=lambda x: x['revenue'], reverse=True)
return jsonify({'categories': res, 'network_margin': network_margin, 'avg_revenue': avg_rev})
@app.route('/api/margin_distribution')
def api_margin_distribution():
f=[p for p in PRODUCTS if p['sales']>0]
if request.args.get('dept'):
d=request.args['dept']; f=[p for p in f if p['dept']==d]
b={'< 10%':0,'10-15%':0,'15-20%':0,'20-25%':0,'25-30%':0,'30-35%':0,'35-40%':0,'40-50%':0,'> 50%':0}
for p in f:
m=p['margin']
if m<10: b['< 10%']+=1
elif m<15: b['10-15%']+=1
elif m<20: b['15-20%']+=1
elif m<25: b['20-25%']+=1
elif m<30: b['25-30%']+=1
elif m<35: b['30-35%']+=1
elif m<40: b['35-40%']+=1
elif m<50: b['40-50%']+=1
else: b['> 50%']+=1
return jsonify([{'range':k,'count':v} for k,v in b.items()])
@app.route('/api/top_stm_candidates')
def api_top_stm_candidates():
f=[p for p in PRODUCTS if p['sales']>0 and p['revenue']>0]
if request.args.get('dept'):
d=request.args['dept']; f=[p for p in f if p['dept']==d]
lim=int(request.args.get('limit',20))
for p in f:
p['_sc']=p['revenue']*(p['margin']/100)*(1+p['sales']/100)
f.sort(key=lambda x:x['_sc'],reverse=True)
res=[]
for p in f[:lim]:
r={k:v for k,v in p.items() if not k.startswith('_')}
r['stm_score']=round(p['_sc'])
res.append(r)
return jsonify(res)
if __name__=='__main__':
app.run(host='0.0.0.0',port=5555,debug=False)