-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrender_html_industry_profit.py
919 lines (856 loc) · 48.8 KB
/
render_html_industry_profit.py
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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
import typing
import math
import eve_esi_tools
import render_html
import profit
def get_pseudographics_prefix(
levels: typing.List[bool],
is_first_standard: bool = False,
is_first_nested: bool = False,
is_last: bool = False):
prfx: str = ''
for lv in levels:
if lv:
prfx += ' '
else:
prfx += '│ ' # │
if is_first_standard:
if is_last:
prfx += '└─' # └
else:
prfx += '├─' # └
elif is_first_nested:
if not prfx:
if is_last:
prfx += '└' # └
else:
prfx += '├' # └
else:
prfx += '│ └' # │ └
elif is_last:
prfx += '└─' # └─
else:
prfx += '├─' # ├─
return prfx
def get_industry_cost_indices_desc(
# индексы стоимости производства для различных систем (системы и продукция заданы в настройках роутинга)
industry_cost_indices: typing.List[profit.QIndustryCostIndices]) -> str:
desc: str = ''
if not industry_cost_indices:
desc = '(настройка не задана)'
else:
max0: int = len(industry_cost_indices) - 1
for lvl0, i in enumerate(industry_cost_indices):
desc += '<br>\n ' + get_pseudographics_prefix(
levels=[],
is_first_standard=lvl0 == 0,
is_last=lvl0 == max0)
desc += f' {i.factory_name} производит {f'{len(i.product_ids)} видов' if i.product_ids else 'все виды'} продукции'
bonuses: typing.List[str] = []
for num in range(2):
for activity in ['manufacturing', 'copying', 'invent', 'reaction']:
if num == 0:
me: float = i.factory_bonuses.get_role_bonus(activity, 'me')
jc: float = i.factory_bonuses.get_role_bonus(activity, 'job_cost')
prfx: str = f'{activity} бонус профиля сооружения: '
else:
me = i.factory_bonuses.get_rigs_bonus(activity, 'me')
jc = i.factory_bonuses.get_rigs_bonus(activity, 'job_cost')
prfx: str = f'установленный {activity} модификатор: '
if me < -0.001 or jc < -0.001:
bonus = prfx
if me < -0.001:
bonus += f'расход материалов {me*100.0:.1f}%'
bonus += ', ' if jc < -0.001 else ''
if jc < -0.001:
bonus += f'стоимость проекта {jc*100.0:.1f}%'
bonuses.append(bonus)
if bonuses:
max1: int = len(bonuses) - 1
for lvl1, bonus in enumerate(bonuses):
desc += '<br>\n ' + get_pseudographics_prefix(
levels=[lvl0 == max0],
is_first_standard=lvl1 == 0,
is_last=lvl1 == max1
) + ' ' + bonus
return desc
def get_common_components_desc(market_group_ids: typing.List[int], sde_market_groups):
groups: typing.List[str] = []
for market_group_id in market_group_ids:
group_name: str = sde_market_groups[str(market_group_id)]['nameID']['en']
groups.append(group_name)
desc: str = ''
max2: int = len(groups) - 1
for lvl2, group_name in enumerate(groups):
desc += '<br>\n' + get_pseudographics_prefix(
levels=[True, True],
is_first_standard=lvl2 == 0,
is_last=lvl2 == max2
) + ' ' + group_name
return desc + '<br>\n'
def render_report(
glf,
# данные о продуктах, которые надо отобразить в отчёте
industry_plan: profit.QIndustryPlan,
# sde данные, загруженные из .converted_xxx.json файлов
sde_type_ids,
sde_bp_materials,
sde_market_groups,
eve_market_prices_data,
sde_icon_ids,
# ордера, выставленные в Jita 4-4
eve_jita_orders_data: profit.QMarketOrders,
# индексы стоимости производства для различных систем (системы и продукция заданы в настройках роутинга)
industry_cost_indices: typing.List[profit.QIndustryCostIndices],
# формула производства (здесь для проверки)
industry_formula: profit.QIndustryFormula):
base_industry: profit.QIndustryTree = industry_plan.base_industry
customized_run_products: int = industry_plan.base_industry.products_per_single_run * industry_plan.customized_runs
def generate_manuf_materials_list(__it157: profit.QIndustryTree):
res: str = ''
for m in __it157.materials:
res += '<span style="white-space:nowrap">' \
'<img class="icn24" src="{src}"> {q:,d} x {nm} ' \
'</span>\n'.format(src=render_html.__get_img_src(m.type_id, 32), q=m.quantity, nm=m.name)
return res
industry_cost_indices_desc: str = get_industry_cost_indices_desc(industry_cost_indices)
glf.write(f"""
<div class="container-fluid">
<div class="media">
<div class="media-left"><img class="media-object icn64" src="{render_html.__get_img_src(base_industry.blueprint_type_id, 64)}" alt="{base_industry.blueprint_name}"></div>
<div class="media-body">
<h4 class="media-heading">{base_industry.blueprint_name}</h4>
<p>
EveUniversity {base_industry.product_name} wiki: <a href="https://wiki.eveuniversity.org/{base_industry.product_name}">https://wiki.eveuniversity.org/{base_industry.product_name}</a><br/>
EveMarketer {base_industry.product_name} tradings: <a href="https://evemarketer.com/types/{base_industry.product_type_id}">https://evemarketer.com/types/{base_industry.product_type_id}</a><br/>
EveMarketer {base_industry.product_name} Blueprint tradings: <a href="https://evemarketer.com/types/{base_industry.blueprint_type_id}">https://evemarketer.com/types/{base_industry.blueprint_type_id}</a><br/>
Adam4EVE {base_industry.product_name} manufacturing calculator: <a href="https://www.adam4eve.eu/manu_calc.php?typeID={base_industry.blueprint_type_id}">https://www.adam4eve.eu/manu_calc.php?typeID={base_industry.blueprint_type_id}</a><br/>
Adam4EVE {base_industry.product_name} price history: <a href="https://www.adam4eve.eu/commodity.php?typeID={base_industry.product_type_id}">https://www.adam4eve.eu/commodity.php?typeID={base_industry.product_type_id}</a><br/>
Adam4EVE {base_industry.product_name} Blueprint price history: <a href="https://www.adam4eve.eu/commodity.php?typeID={base_industry.blueprint_type_id}">https://www.adam4eve.eu/commodity.php?typeID={base_industry.blueprint_type_id}</a>
</p>
</div> <!--media-body-->
</div> <!--media-->
<hr>
<div class="media">
<div class="media-left"><img class="media-object icn64" src="{render_html.__get_img_src(base_industry.product_type_id, 64)}" alt="Требуемые комплектующие"></div>
<div class="media-body">
<h4 class="media-heading">Организация производства <small>Требуемые комплектующие</small></h4>
{generate_manuf_materials_list(base_industry)}
</div> <!--media-body-->
</div> <!--media-->
<hr>
<div class="media">
<div class="media-left"><img class="media-object icn64" src="{render_html.__get_icon_src(1436, sde_icon_ids)}"></div>
<div class="media-body">
<!--<p><var>Efficiency</var> = <var>Required</var> * (100 - <var>material_efficiency</var> - 1 - 4.2) / 100,
<br>where <var>material_efficiency</var> for unknown and unavailable blueprint is ?.</p>-->
<p>
Параметры чертежа:<br>
├─ Число прогонов: {industry_plan.customized_runs}<br>
│ └─ Выходное количество продуктов: {customized_run_products} шт<br>
└─ Экономия материалов при производстве: -{base_industry.me}.0%<br>
Экономия материалов промежуточных чертежей: {'(настройка не задана)' if not industry_plan.customization or industry_plan.customization.unknown_blueprints_me is None else
f'-{industry_plan.customization.unknown_blueprints_me}.0%'}<br>
<br>
Бонусы сооружений: {industry_cost_indices_desc}<br>
<br>
Длительность производственных работ общих компонентов: {'(настройка не задана)' if not industry_plan.customization or not industry_plan.customization.industry_time else
'{:.1f} часов'.format(float(industry_plan.customization.industry_time) / (5*60*60))}<br>
└─ Группы компонентов общего назначения: {'(настройка не задана)' if not industry_plan.customization or not industry_plan.customization.common_components else
f'{get_common_components_desc(industry_plan.customization.common_components, sde_market_groups)}'}<br>
Длительность запуска формул и реакций: {'(настройка не задана)' if not industry_plan.customization or not industry_plan.customization.reaction_runs else
'{} прогонов'.format(industry_plan.customization.reaction_runs)}<br>
Минимальная вероятность успеха по навыкам и имплантам: {'(настройка не задана)' if not industry_plan.customization or not industry_plan.customization.min_probability else
'{:.1f}%'.format(industry_plan.customization.min_probability)}
</p>
<hr>""")
def generate_components_header(with_current_industry_progress: bool):
glf.write('<tr>\n'
'<th style="width:50px;">#</th>\n'
'<th>Материалы</th>\n'
+ ('<th>Имеется +<br/>Производится</th>\n' if with_current_industry_progress else '')
+ '<th>Без<br/>ME</th>\n'
+ '<th>Учёт<br/>ME</th>\n'
+ '<th>Выход<br/>(произв.)</th>\n'
+ ('<th>Требуется<br/>(недостаточно)</th>\n' if with_current_industry_progress else '')
+ '<th>План<br/>(произв.)</th>\n'
'<th>Остаток<br/>(произв.)</th>\n'
'<th>Соотношение<br/>(как часть целого)</th>\n'
'<th>Итог<br/>(закуп.)</th>\n'
'<th>Итог<br/>(рентаб.)</th>\n'
'</tr>\n')
linear_cost_verification: profit.QIndustryJobCostAccumulator = profit.QIndustryJobCostAccumulator()
def generate_grayed_reused_duplicate(plan: profit.QIndustryObtainingPlan, before: bool) -> str:
if not plan or not plan.reused_duplicate:
return ''
return '<span style="color:lightgray;">' if before else '</span>'
def generate_industry_plan_item(
row0_prefix: str,
row1_num: int,
row0_levels,
__pa339: profit.QPlannedActivity,
__op340: typing.Optional[profit.QIndustryObtainingPlan],
usage_chain: float):
bp_tid = __pa339.industry.blueprint_type_id
bp_action = __pa339.industry.action
# bp_nm = __pa339.industry.blueprint_name
# planned_material: profit.QPlannedMaterial = __pa339.planned_blueprint
planned_blueprints: int = __pa339.planned_blueprints
planned_runs: int = __pa339.planned_runs
job_cost: typing.Optional[profit.QPlannedJobCost] = __pa339.industry_job_cost
assert job_cost is not None
current_level_job_cost: int = math.ceil(planned_blueprints * planned_runs * job_cost.total_job_cost)
usage_chain_job_cost: float = usage_chain * current_level_job_cost
fmt: str = \
'<tr{tr_class}>\n' \
+ '<th scope="row"><span class="text-muted">{num_prfx}</span>{num}</th>\n' \
+ '<td><img class="icn24" src="{src}"> {prfx} {nm}{pstfx}</td>\n' \
+ '<td></td>' \
+ '<td></td>' \
+ '<td></td>' \
+ '<td>{qp}</td>' \
+ '<td></td>' \
+ '<td>{qu}</td>' \
+ '<td></td>' \
+ '<td>{qsr}</td>' \
'</tr>'
glf.write(
fmt.format(
tr_class=' class="active"' if not row0_prefix else '',
num_prfx=row0_prefix, num=row1_num,
prfx='<tt><span class="text-muted">{}</span></tt>'.format(
get_pseudographics_prefix(row0_levels, is_first_nested=True, is_last=False)),
nm="<span class='text-muted'>{act}</span>".format(
act=str(bp_action),
),
pstfx="<sup> <strong style='color:maroon;'>{bp}×{run}</strong></sup>".format(
bp=planned_blueprints,
run=planned_runs,
),
src=render_html.__get_img_src(bp_tid, 32),
qp='<small>{}'
'{}<sup>eiv</sup>*{}<sup>runs</sup>*{:.2f}%<sup>{}</sup>{}'
'*{}%<sup>tax</sup> => {}<sup>job</sup>'
'{}</small>'.format(
generate_grayed_reused_duplicate(__op340, True), # before ALL
job_cost.estimated_items_value, # 1.eiv
planned_blueprints * planned_runs, # 1.runs
job_cost.industry_cost_index * 100.0, # 1.const_index
job_cost.system_indices.solar_system, # 1.solar_system
'' if not job_cost.role_bonus_job_cost and not job_cost.rigs_bonus_job_cost else
f'*{(job_cost.role_bonus_job_cost + job_cost.rigs_bonus_job_cost) * 100.0:.2f}%<sup>rig</sup>', # 1.rig
(job_cost.scc_surcharge + job_cost.facility_tax) * 100.0, # 1.tax
current_level_job_cost, # 2.out
generate_grayed_reused_duplicate(__op340, False), # after ALL
),
qu='<small style="color:maroon;">'
'{:.8f}<sup>chain</sup>*{}<sup>job</sup> => '
'{:.2f}<sup>ratio</sup>'
'</small>'.format(
usage_chain,
current_level_job_cost,
usage_chain_job_cost,
),
qsr='<small style="color:maroon;">'
'{:.2f}=<sup>{:d}+{:d}</sup>'
'</small>'.format(
linear_cost_verification.total_paid + usage_chain_job_cost, # 1.sum
math.ceil(linear_cost_verification.total_paid), # 2.total
math.ceil(usage_chain_job_cost) # 1.job
)
)
)
linear_cost_verification.increment_total_paid(usage_chain_job_cost)
def generate_components_list(
with_current_industry_progress: bool,
row0_prefix: str,
row0_levels,
__ap344: profit.QPlannedActivity):
# вывод информации о материалах
row1_max: int = len(__ap344.planned_materials)
for m1 in enumerate(__ap344.planned_materials, start=1):
row1_num: int = int(m1[0])
m1_planned_material: profit.QPlannedMaterial = m1[1]
m1_obtaining_plan: profit.QIndustryObtainingPlan = m1_planned_material.obtaining_plan
m1_obtaining_activity: profit.QPlannedActivity = m1_obtaining_plan.activity_plan
m1_material: profit.QMaterial = m1[1].material
m1_industry: profit.QIndustryTree = m1_material.industry
m1_tid: int = m1_material.type_id
m1_tnm: str = m1_material.name
m1_quantity: int = m1_material.quantity
m1_copying: bool = m1_industry and m1_industry.action == profit.QIndustryAction.copying
m1_invention: bool = m1_industry and m1_industry.action == profit.QIndustryAction.invention
if m1_copying or m1_invention:
m1_planned_blueprints: int = m1_obtaining_activity.planned_blueprints
m1_planned_runs: int = m1_obtaining_activity.planned_runs
else:
m1_planned_blueprints: int = __ap344.planned_blueprints
m1_planned_runs: int = __ap344.planned_runs
fmt: str = \
'<tr{tr_class}>\n' \
+ '<th scope="row"><span class="text-muted">{num_prfx}</span>{num}</th>\n' \
+ '<td><img class="icn24" src="{src}"> {prfx} {nm}{pstfx}</td>\n' \
+ ('<td>{qa:,d}{qip}</td>\n' if with_current_industry_progress else '') \
+ '<td>{qwome:,d}</td>\n' \
+ '<td>{qe}</td>\n' \
+ ('<td>{qne}</td>\n' if with_current_industry_progress else '') \
+ '<td>{qo}</td>\n' \
+ '<td>{qp}</td>\n' \
+ '<td>{qr}</td>\n' \
+ '<td>{qu}</td>\n' \
+ '<td>{qsq}</td>\n' \
+ '<td>{qsr}</td>\n' \
'</tr>'
glf.write(
fmt.format(
tr_class=' class="active"' if not row0_prefix else '',
num_prfx=row0_prefix, num=row1_num,
prfx='<tt><span class="text-muted">{}</span></tt>'.format(
get_pseudographics_prefix(row0_levels, is_first_standard=False, is_last=row1_num == row1_max)),
nm=m1_tnm,
pstfx='{qm}{bpq}'.format(
qm="<sup> <strong style='color:darkblue;'>x{}</strong></sup>".format(m1_quantity),
bpq='' if m1_industry is None or m1_industry.products_per_single_run == 1 else
' <strong>x{}</strong>'.format(m1_industry.products_per_single_run),
),
src=render_html.__get_img_src(m1_tid, 32),
qa=-1,
qip='',
qwome=m1_material.quantity * m1_planned_blueprints * m1_planned_runs,
qe='{:,d}'.format(m1_planned_material.quantity_with_efficiency) if m1_industry is not None else
'{}{:,d}{}'.format(
generate_grayed_reused_duplicate(m1_obtaining_plan, True),
m1_planned_material.quantity_with_efficiency,
generate_grayed_reused_duplicate(m1_obtaining_plan, False)
),
qo='' if not m1_material.industry else
'{}{}{}'.format(
generate_grayed_reused_duplicate(m1_obtaining_plan, True),
m1_obtaining_plan.industry_output,
generate_grayed_reused_duplicate(m1_obtaining_plan, False)
),
qp='' if not m1_material.industry else
'<small>'
'{}<sup>bp</sup>*{}<sup>run</sup>*{}<sup>qty</sup>*{}<sup>%</sup> => '
'{:.1f}<sup>%</sup>'
'</small>'.format(
m1_planned_blueprints, # 1.bp
m1_planned_runs, # 1.run
m1_material.quantity, # 1.qty
'{:.1f}{}'.format( # 1.prob
100.0*m1_industry.invent_probability,
'' if m1_industry.decryptor_probability is None else
'×{:.1f}'.format(100.0*m1_industry.decryptor_probability)
) if not industry_plan.customization or not industry_plan.customization.min_probability else
'({:.1f}{}×{:.1f})'.format(
100.0*m1_industry.invent_probability,
'' if m1_industry.decryptor_probability is None else
'×{:.1f}'.format(100.0*m1_industry.decryptor_probability),
industry_plan.customization.min_probability
),
m1_planned_blueprints * \
m1_planned_runs * \
m1_material.quantity * \
m1_industry.invent_probability * ( # Purifier : 30x20x27.5 => 0.3*1.2*1.275 => 45.9%
1.0 if m1_industry.decryptor_probability is None else
(1.0+m1_industry.decryptor_probability)
) * (
1.0 if not industry_plan.customization or
not industry_plan.customization.min_probability else
(100.0+industry_plan.customization.min_probability)/100.0
) * 100.0 # 2.out
) if m1_invention else
'<small>'
'{}<sup>bp</sup>*{}<sup>run</sup>*{}<sup>qty</sup> => '
'{:.1f}<sup>out</sup>'
'</small>'.format(
m1_planned_blueprints, # 1.bp
m1_planned_runs, # 1.run
m1_material.quantity, # 1.qty
m1_planned_blueprints * \
m1_planned_runs * \
m1_material.quantity # 2.out
) if m1_copying else
'<small>'
'{}<sup>bp</sup>*{}<sup>run</sup>*{}<sup>qty</sup> => '
'{}<sup>me</sup> '
'{}=> '
'{}<sup>bp</sup>*{}<sup>run</sup>*{}<sup>dose</sup> => '
'{}<sup>out</sup>'
'{}'
'</small>'.format(
m1_planned_blueprints, # 1.bp
m1_planned_runs, # 1.run
m1_material.quantity, # 1.qty
m1_planned_material.quantity_with_efficiency, # 2.me
generate_grayed_reused_duplicate(m1_obtaining_plan, True), # before 3
'TODO' if not m1_obtaining_activity else m1_obtaining_activity.planned_blueprints, # 3.bp
'TODO' if not m1_obtaining_activity else m1_obtaining_activity.planned_runs, # 3.run
m1_industry.products_per_single_run, # 3.dose
m1_obtaining_plan.industry_output, # 4.out
generate_grayed_reused_duplicate(m1_obtaining_plan, False) # after 4
),
qr='' if not m1_material.industry else
'{:,d}{}'.format(
m1_obtaining_plan.rest_quantity,
'' if not m1_obtaining_plan.reused_duplicate else
'<small>=<sup>{}-{}</sup></small>'.format(
m1_obtaining_plan.rest_quantity + m1_planned_material.quantity_with_efficiency,
m1_planned_material.quantity_with_efficiency
)
),
qu='<small>'
'{:.8f}<sup>chain</sup>*{}<sup>pcs</sup> => '
'{:.8f}<sup>ratio</sup>'
'</small>'.format(
m1_planned_material.usage_chain,
m1_planned_material.quantity_with_efficiency,
m1_planned_material.usage_chain * m1_planned_material.usage_ratio
) if not m1_material.industry else
# '<small>'
# '{:.8f}<sup>chain</sup> => {}<sup>runs'
# '</small>'.format(
# m1_planned_material.usage_chain,
# m1_planned_material.quantity_with_efficiency
# ) if m1_material.industry.action == profit.QIndustryAction.copying else
'<small>'
'{:.8f}<sup>chain</sup> * '
'({}<sup>me</sup>/{}{}<sup>out</sup>{} => {:.4f}) => '
'{:.8f}<sup>ratio</sup>'
'</small>'.format(
m1_planned_material.usage_chain, # chain
m1_planned_material.quantity_with_efficiency, # me
generate_grayed_reused_duplicate(m1_obtaining_plan, True), # before out
m1_obtaining_plan.industry_output, # out
generate_grayed_reused_duplicate(m1_obtaining_plan, False), # after out
m1_planned_material.usage_ratio, # me/out
m1_planned_material.usage_chain * m1_planned_material.usage_ratio # ratio
),
qne='' if not m1_obtaining_plan.not_enough_quantity else
'{:,d}'.format(m1_obtaining_plan.not_enough_quantity),
qsq='<small>'
'{:,d}{}=<sup>{}+{}</sup>{}'
'</small>'.format(
m1_planned_material.summary_quantity_after, # sum
generate_grayed_reused_duplicate(m1_obtaining_plan, True), # before =
m1_planned_material.summary_quantity_before, # 1
m1_planned_material.summary_quantity_after-m1_planned_material.summary_quantity_before, # 2
generate_grayed_reused_duplicate(m1_obtaining_plan, False) # after =
),
qsr='' if m1_material.industry else
'<small>'
'{:.8f}=<sup>{:.4f}+{:.4f}</sup>'
'</small>'.format(
m1_planned_material.summary_ratio_after,
m1_planned_material.summary_ratio_before,
m1_planned_material.summary_ratio_after-m1_planned_material.summary_ratio_before
)
))
if m1_obtaining_activity:
row2_levels = row0_levels[:]
row2_levels.append(row1_num == row1_max)
row2_prefix: str = "{prfx}{num1}.".format(prfx=row0_prefix, num1=row1_num)
generate_industry_plan_item(
row2_prefix, 0, row2_levels,
m1_obtaining_activity,
m1_obtaining_plan,
# 1.0 if m1_copying or m1_invention else
m1_planned_material.usage_chain * m1_planned_material.usage_ratio
)
generate_components_list(
with_current_industry_progress,
row2_prefix,
row2_levels,
m1_obtaining_activity)
glf.write("""
<style>
.table-borderless > tbody > tr > td,
.table-borderless > tbody > tr > th,
.table-borderless > tfoot > tr > td,
.table-borderless > tfoot > tr > th,
.table-borderless > thead > tr > td,
.table-borderless > thead > tr > th {
border: none;
padding: 0px;
}
</style>
<table class="table table-borderless table-condensed" style="font-size:small">
<thead>""")
generate_components_header(False)
glf.write("""
</thead>
<tbody>""")
# вывод информации о работе и чертеже
generate_industry_plan_item(
'', 0, [],
industry_plan.base_planned_activity,
None,
1.0)
# вывод информации о чертежах
generate_components_list(False, '', [], industry_plan.base_planned_activity)
glf.write(f"""
</tbody>
</table>
</div> <!--media-body-->
</div> <!--media-->
<hr>
<div class="media">
<div class="media-left">
<img class="media-object icn64" src="{render_html.__get_icon_src(1201, sde_icon_ids)}" alt="Сводная таблица производства">
</div>
<div class="media-body">
<h4 class="media-heading">Сводная таблица производства</h4>""")
def generate_summary_raw_header(with_current_industry_progress: bool):
glf.write('<tr>\n'
'<th style="width:40px;">#</th>'
'<th>Материалы</th>'
+ ('<th>Имеется +<br/>Производится</th>\n' if with_current_industry_progress else '')
+ '<th>Требуется</th>'
+ ('<th>Прогресс, %</th>\n' if with_current_industry_progress else '')
+ '<th style="text-align:right;">Цена, ISK/шт.</th>'
'<th style="text-align:right;">Цена, ISK</th>'
'<th style="text-align:right;">Пропорция,<br>шт.</th>'
'<th style="text-align:right;">Пропорция,<br>ISK</th>'
'<th style="text-align:right;color:maroon;">Доля 1шт<br>продукта, ISK</th>'
'<th style="text-align:right;"><strike>Объём, m³</strike></th>'
'</tr>\n')
def generate_group_header(group_name: str) -> None:
clbrd: str = ''
glf.write(f'<tr><td class="active" colspan="11"><strong>{group_name}</strong><!--{id}-->{clbrd}</td></tr>\n')
glf.write("""
<div class="table-responsive">
<table class="table table-condensed" style="font-size:small">
<thead>""")
generate_summary_raw_header(True)
glf.write("""
</thead>
<tbody>""")
def get_grayed_material_not_purchased(is_purchased: int, is_first: bool) -> str:
if is_purchased:
return ''
else:
return '<span style="color:#aaa;">' if is_first else '</span>'
def get_material_buy_price(__type_id565: int, fake_price: float) -> float:
__p566: typing.Optional[float] = None
if eve_jita_orders_data:
__maxbuy568: typing.Optional[profit.QMarketOrder] = eve_jita_orders_data.get_max_buy_order(__type_id565)
if __maxbuy568:
__p566 = profit.eve_ceiling_change_by_point(__maxbuy568.price, +1)
else:
__minsell572: typing.Optional[profit.QMarketOrder] = eve_jita_orders_data.get_min_sell_order(__type_id565)
if __minsell572:
__p566 = __minsell572.price
# TODO: внимание, с этой цены налог не выплачивается! (в формулах ниже налог считается безусловно)
if not __p566:
__p566 = eve_esi_tools.get_material_price(__type_id565, sde_type_ids, eve_market_prices_data)
if not __p566:
__p566 = fake_price
return __p566
material_groups: typing.Dict[int, typing.List[profit.QIndustryMaterial]] = {}
for type_id in industry_plan.materials_repository.materials.keys():
m: profit.QIndustryMaterial = industry_plan.materials_repository.get_material(type_id)
mg: typing.List[profit.QIndustryMaterial] = material_groups.get(m.base.market_group_id)
if mg is None:
mg = []
material_groups[m.base.market_group_id] = mg
mg.append(m)
row3_num: int = 0
total_purchase: float = 0.0
total_purchase_volume: float = 0.0
for group_id in material_groups.keys():
mg: typing.List[profit.QIndustryMaterial] = material_groups.get(group_id)
if group_id == 1857:
mg.sort(key=lambda __m685: __m685.purchased+__m685.manufactured, reverse=True)
else:
mg.sort(key=lambda __m685: __m685.purchased+__m685.manufactured)
# рисуем заголовок группы
generate_group_header(mg[0].base.market_group_name)
# выводим товары группы
for m in mg:
row3_num += 1
# получение данных по материалу
m3_tid: int = m.base.type_id
m3_tnm: str = m.base.name
m3_q = m.purchased + m.manufactured # количество (общее всоответствии с настройками производства)
m3_r = m.purchased_ratio # количество (доля от требуемого кол-ва с учётом вложенных уровней)
m3_a = m.available_in_assets # available in assets
m3_j = m.in_progress # in progress (runs of jobs)
m3_v = m.base.volume # volume
# получение стоимости закупа материала (или стоимость копирки/инвента чертежей)
m3_p: typing.Optional[float] = None
is_blueprints_group: bool = m.base.market_group_id == 2
if not is_blueprints_group:
m3_p = get_material_buy_price(m3_tid, -1000000000.00)
else:
m3_p = m.job_cost # blueprints * runs * job_cost
# расчёт прогресса выполнения (постройки, сбора) материалов (m1_j пропускаем, т.к. они не готовы ещё)
if m.available_in_assets >= m3_q:
m3_progress = 100.0
elif m3_q == 0:
m3_progress = 100.0
else:
m3_progress = float(100.0 * float(m3_a) / m3_q)
# получение стоимости за одну штуку
if m.purchased:
total_purchase += (m3_p * m3_r) # цену 1 шт. умножаем на долю
total_purchase_volume += (m3_v * m3_r) # объём (ЭТО НЕ ОБЪЁМ ТОЛЬКО МАТЕРИАЛОВ) 1 шт. умножаем на долю
# вывод наименования ресурса
glf.write(
'<tr>\n'
' <th scope="row">{num}</th>\n'
' <td data-copy="{nm}"><img class="icn24" src="{src}"> {nm}{me_te}</td>\n'
' <td>{qa}{qip}</td>\n'
' <td quantity="{qneed}">{qrn:,d}</td>\n'
' <td><div class="progress" style="margin-bottom:0px"><div class="progress-bar{prcnt100}"'
' role="progressbar" aria-valuenow="{prcnt}" aria-valuemin="0" aria-valuemax="100"'
' style="width: {prcnt}%;">{fprcnt:.1f}%</div></div></td>\n'
' <td align="right">{price}</td>'
' <td align="right">{costn}</td>'
' <td align="right">{qratio}</td>'
' <td align="right">{pratio}</td>'
' <td align="right" style="color:maroon;">{instance_isk}</td>'
' <td align="right">{volume}</td>'
'</tr>'.format(
num=row3_num,
nm=m3_tnm,
me_te='',
src=render_html.__get_img_src(m3_tid, 32),
qrn=m3_q,
qneed=m3_q-m3_a-m3_j if m3_q > (m3_a+m3_j) else 0,
qa='{:,d}'.format(m3_a) if m3_a >= 0 else
'∞ <small>runs</small>',
qip='' if m3_j == 0 else
'<mark>+ {}</mark>'.format(m3_j),
prcnt=int(m3_progress),
fprcnt=m3_progress,
prcnt100=" progress-bar-success" if m3_progress == 100 else '',
price='' if is_blueprints_group else
'{}{:,.2f}{}'.format(
get_grayed_material_not_purchased(m.purchased, True),
m3_p,
get_grayed_material_not_purchased(m.purchased, False),
) if m3_p is not None else
'',
costn='{:,d}'.format(m3_p) if is_blueprints_group else
'{}{:,.2f}{}'.format(
get_grayed_material_not_purchased(m.purchased, True),
m3_p * m3_q,
get_grayed_material_not_purchased(m.purchased, False),
) if m3_p is not None else
'',
qratio='' if is_blueprints_group else
'' if not m.purchased else
'{:,.5f}'.format(m3_r),
pratio='' if is_blueprints_group else
'' if not m.purchased or m3_p is None else
'{:,.1f}'.format(m3_p*m3_r+0.004999),
instance_isk='{}{:,.2f}{}'.format(
get_grayed_material_not_purchased(False, True),
m3_p / industry_plan.customized_runs,
get_grayed_material_not_purchased(False, True),
) if is_blueprints_group else
'' if not m.purchased else
'{:,.2f}'.format((m3_p*m3_r+0.004999) / industry_plan.customized_runs),
volume='<strike>{:,.2f}</strike>'.format(m3_v * m3_r) if not is_blueprints_group else ''
))
glf.write(f"""
</tbody>
</table>
</div> <!--table-responsive-->
</div> <!--media-body-->
</div> <!--media-->
<hr>
<div class="media">
<div class="media-left">
<img class="media-object icn64" src="{render_html.__get_icon_src(2512, sde_icon_ids)}" alt="Общая стоимость проекта">
</div>
<div class="media-body">
<h4 class="media-heading">Общая стоимость проекта</h4>
<div class="table-responsive">
<table class="table table-condensed" style="font-size:small">
<thead>
<tr>
<th class="active">{base_industry.product_name}</th>
<th class="active" style="text-align:right;">Производство {customized_run_products}шт продукта</th>
<th class="active" style="text-align:right;">Доля 1шт продукта</th>
</tr>
</thead>
<tbody>""")
def get_buy_material_price(material_type_id: int) -> float:
return get_material_buy_price(material_type_id, -1000000000.00)
def calc_estimated_items_value(blueprint_type_id: int, activity_eiv: int) -> float:
activity: str = str(profit.QIndustryAction.from_code(activity_eiv))
return profit.calc_estimated_items_value(
blueprint_type_id,
activity,
sde_bp_materials,
eve_market_prices_data)
def get_industry_cost_index(solar_system_id: int, activity_code: int) -> float:
cost_indices = next((_.cost_indices for _ in industry_cost_indices if _.solar_system_id==solar_system_id), None)
assert cost_indices is not None
activity: str = str(profit.QIndustryAction.from_code(activity_code))
cost_index: float = next((_['cost_index'] for _ in cost_indices if _['activity'] == activity), None)
assert cost_index is not None
return cost_index
formula_purchase_verification: float = \
industry_formula.calc_materials_cost(get_buy_material_price) / \
(industry_formula.customized_runs * industry_plan.base_industry.products_per_single_run)
formula_cost_verification: float = \
industry_formula.calc_industry_cost(calc_estimated_items_value, get_industry_cost_index) / \
(industry_formula.customized_runs * industry_plan.base_industry.products_per_single_run)
def generate_summary_lines(
caption: str,
total_summary: str,
one_instance_summary: str):
glf.write(f"""<tr>
<td class="active">{caption}</td>
<td style="text-align:right">{total_summary}</td>
<td style="text-align:right;">{one_instance_summary}</td>
</tr>""")
total_gross_cost: float = 0.0
generate_summary_lines(
'Стоимость закупки материалов, ISK',
f'{total_purchase * 1.02:,.2f}',
f'{(total_purchase * 1.02) / customized_run_products:,.2f}')
generate_summary_lines(
'├─ Стоимость материалов, ISK',
f'{total_purchase:,.2f}',
f'{total_purchase / customized_run_products:,.2f}<br>'
f'<span style="color:lightgray;">проверка: {formula_purchase_verification:,.2f}</span>')
generate_summary_lines(
'└─ Брокерская комиссия, ISK',
f'{total_purchase * 0.02:,.2f}',
f'{(total_purchase * 0.02) / customized_run_products:,.2f}')
total_gross_cost += total_purchase * 1.02
# Nitrogen Isotopes, hardcoded price (august 2024)
nitrogen_isotopes_isk = get_material_buy_price(17888, 545.40) * 1.02
# Rhea с 3x ORE Expanded Cargohold имеет 386'404.0 куб.м
# из Jita дистанция 35.6 свет.лет со всеми скилами в 5 понадобится сжечь 88'998 Nitrogen Isotopes (buy 545.40 ISK)
# до Jita дистанция 27.884 свет.лет со всеми скилами в 5 понадобится сжечь 69'708 Nitrogen Isotopes (buy 545.40 ISK)
input_transfer_cost: float = total_purchase_volume * ((88998 * nitrogen_isotopes_isk) / 386404)
generate_summary_lines(
'Стоимость доставки закупаемых материалов, ISK',
f'{input_transfer_cost:,.2f}',
f'{input_transfer_cost / customized_run_products:,.2f}')
generate_summary_lines(
'└─ Объём закупаемых материалов, m³',
f'{total_purchase_volume:,.1f} m³',
f'{total_purchase_volume / customized_run_products:,.1f} m³')
total_gross_cost += input_transfer_cost
generate_summary_lines(
'Стоимость запуска работ, ISK',
f'{industry_plan.job_cost_accumulator.total_paid:,.2f}<br>'
f'<span style="color:lightgray;">проверка: {linear_cost_verification.total_paid:,.2f}</span>',
f'{industry_plan.job_cost_accumulator.total_paid / customized_run_products:,.2f}<br>'
f'<span style="color:lightgray;">проверка: {formula_cost_verification:,.2f}</span>')
total_gross_cost += industry_plan.job_cost_accumulator.total_paid * 0.0
total_ready_volume: float = industry_plan.base_industry.product.volume * customized_run_products
# TODO: total_ready_volume: float = 50000 * customized_run_products
# TODO: total_ready_volume: float = 2500 * customized_run_products
output_transfer_cost: float = total_ready_volume * ((69708 * nitrogen_isotopes_isk) / 386404) * 1.02
generate_summary_lines(
'Стоимость отправки готовой продукции, ISK',
f'{output_transfer_cost:,.2f}',
f'{output_transfer_cost / customized_run_products:,.2f}')
generate_summary_lines(
'└─ Объём готовой продукции, m³',
f'{total_ready_volume:,.1f} m³',
f'{total_ready_volume / customized_run_products:,.1f} m³')
total_gross_cost += output_transfer_cost
generate_summary_lines(
'Общая стоимость проекта, ISK',
f'<b>{total_gross_cost:,.2f}</b>',
f'<b>{total_gross_cost / customized_run_products:,.2f}</b>')
product_type_id: int = industry_plan.base_industry.product.type_id
product_sell_order_isk: typing.Optional[float] = None
if eve_jita_orders_data:
min_sell: typing.Optional[profit.QMarketOrder] = eve_jita_orders_data.get_min_sell_order(product_type_id)
if min_sell:
product_sell_order_isk = profit.eve_ceiling_change_by_point(min_sell.price, -1)
if not product_sell_order_isk:
product_sell_order_isk = eve_esi_tools.get_material_price(product_type_id, sde_type_ids, eve_market_prices_data)
if not product_sell_order_isk:
product_sell_order_isk = 1000000000.00 # fake price
product_sell_order_isk *= customized_run_products
sales_broker_fee: float = product_sell_order_isk * 0.02
sales_tax: float = product_sell_order_isk * 0.016
sales_profit: float = product_sell_order_isk - sales_broker_fee - sales_tax
generate_summary_lines(
'Доход с продаж, ISK',
f'{sales_profit:,.2f}',
f'{sales_profit / customized_run_products:,.2f}')
generate_summary_lines(
'├─ Рыночная цена, ISK',
f'{product_sell_order_isk:,.2f}',
f'{product_sell_order_isk / customized_run_products:,.2f}')
generate_summary_lines(
'├─ Брокерская комиссия, ISK',
f'{sales_broker_fee:,.2f}',
f'{sales_broker_fee / customized_run_products:,.2f}')
generate_summary_lines(
'└─ Налог с продаж, ISK',
f'{sales_tax:,.2f}',
f'{sales_tax / customized_run_products:,.2f}')
generate_summary_lines(
'Итоговый профит проекта, ISK',
f'<b>{sales_profit-total_gross_cost:,.2f}</b>',
f'<b>{(sales_profit-total_gross_cost) / customized_run_products:,.2f}</b>')
glf.write("""
</tbody>
</table>
</div> <!--table-responsive-->
</div> <!--media-body-->
</div> <!--media-->
</div> <!--container-fluid-->""")
def dump_industry_plan(
# данные о продуктах, которые надо отобразить в отчёте
industry_plan: profit.QIndustryPlan,
# путь, где будет сохранён отчёт
ws_dir,
# sde данные, загруженные из .converted_xxx.json файлов
sde_type_ids,
sde_bp_materials,
sde_market_groups,
eve_market_prices_data,
sde_icon_ids,
# ордера, выставленные в Jita 4-4
eve_jita_orders_data: profit.QMarketOrders,
# индексы стоимости производства для различных систем (системы и продукция заданы в настройках роутинга)
industry_cost_indices: typing.List[profit.QIndustryCostIndices],
# формула производства (здесь для проверки)
industry_formula: profit.QIndustryFormula,
# признак использования человеко-понятного названия файла:
# * или kirin_r1_me2_te4_pbp683.html - здесь название продукта
# * или bp39581_r1_me2_te4_pbp683.html - здесь код чертежа
human_readable_filename: bool = True):
assert industry_plan.base_industry
base: profit.QIndustryTree = industry_plan.base_industry
product_name: str = industry_plan.base_industry.product_name
if human_readable_filename:
file_name_c2s: str = render_html.__camel_to_snake(product_name, True)
else:
file_name_c2s: str = f"bp{base.blueprint_type_id}"
file_name_c2s += f"_r{industry_plan.customized_runs}_me{base.me}_te{base.te}"
# получаем информацию об исходном чертеже (актуально для чертежей, в которые инвентятся разные варианты)
prior_blueprint_type_id: typing.Optional[int] = next((
_.industry.blueprint_type_id for _ in industry_plan.base_industry.materials
if _.industry and _.industry.action == profit.QIndustryAction.invention), None)
if prior_blueprint_type_id:
file_name_c2s += f"_pbp{prior_blueprint_type_id}"
ghf = open('{dir}/{fnm}.html'.format(dir=ws_dir, fnm=file_name_c2s), "wt+", encoding='utf8')
try:
render_html.__dump_header(ghf, product_name)
render_report(
ghf,
industry_plan,
sde_type_ids,
sde_bp_materials,
sde_market_groups,
eve_market_prices_data,
sde_icon_ids,
eve_jita_orders_data,
industry_cost_indices,
industry_formula)
render_html.__dump_footer(ghf)
finally:
ghf.close()