Repository navigation
Expand file tree
/
Copy pathdata_converter.py
More file actions
3721 lines (3211 loc) · 145 KB
/
Copy pathdata_converter.py
File metadata and controls
3721 lines (3211 loc) · 145 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
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# data_converter.py
import datetime
import hashlib
import json
import string
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple, Union
from converters.gateway import convert_gateway_data
# ==============================================================================
# CONVERSION FUNCTIONS FOR EACH DATABASE TABLE
# Each function takes raw JSON data and transforms it into a list of dictionaries
# formatted for a specific table.
# ==============================================================================
# FIXME: ALL OF THESE NEEDS TO GO INTO CONVERTERS FOLDER SEPARATELY MOST OF THEM ARE TEMPLATES AND WHOLE FILE IS JUST MESS NEED REFACTORING PRIORITY 1
def convert_users_data_table(raw_records: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Converts raw data to match the 'users_data' table schema, handling
None values by replacing them with a specific default value.
"""
converted_records = []
# Safely get the payload, defaulting to an empty dict if not found
payload = raw_records.get("payload", {})
# Helper function to get a value and replace None with a specified default
def get_value_or_default(key: str, default: Any = None):
value = payload.get(key)
return value if value is not None else default
# Handle subscription expiry timestamp
subscription_expiry_data = payload.get("subscriptionExpiry")
if subscription_expiry_data is not None and subscription_expiry_data.get("timestamp") is not None:
subscription_expiry = datetime.fromtimestamp(subscription_expiry_data["timestamp"] / 1000)
else:
subscription_expiry = None
# Handle created timestamp
created_data = payload.get("created")
if created_data is not None and created_data.get("timestamp") is not None:
created = datetime.fromtimestamp(created_data["timestamp"] / 1000)
else:
created = None
converted_records.append(
{
"userid": get_value_or_default("id", "null"),
"displayname": get_value_or_default("username", "null"),
"companyid": get_value_or_default("companyId", "null"),
"subscriptionlevel": get_value_or_default("subscriptionLevel", "null"),
"subscriptionexpiry": subscription_expiry,
"created": created,
"preferredlocale": get_value_or_default("preferredLocale", "null"),
"highesttier": get_value_or_default("highestTier", "null"),
"ispayinguser": get_value_or_default("isPayingUser", "null"),
"ismuted": get_value_or_default("isMuted", "null"),
"preferredlocale": get_value_or_default("preferredLocale", "null"),
}
)
return converted_records
def convert_user_gifts_received_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'user_gifts_received' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"id": record.get("id"),
"userId": record.get("userId"),
"giftId": record.get("giftId"),
}
)
return converted_records
def convert_user_gifts_sent_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'user_gifts_sent' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"id": record.get("id"),
"userId": record.get("userId"),
"giftId": record.get("giftId"),
}
)
return converted_records
def convert_user_starting_profiles_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""
Converts raw data to match the 'user_starting_profiles' table schema.
Note: 'baseMaterials', 'buildingTickers', 'workforce', and 'commodities' are JSON columns.
"""
converted_records = []
for record in raw_records:
converted_records.append(
{
"name": record.get("name"),
"ships": record.get("ships"),
"baseMaterials": record.get("baseMaterials"),
"buildingTickers": record.get("buildingTickers"),
"workforce": record.get("workforce"),
"commodities": record.get("commodities"),
}
)
return converted_records
def convert_public_user_data(raw_payload: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Converts raw user data to match the 'public_users_data' table schema.
Accepts either a single dictionary or a list of dictionaries.
"""
payload = raw_payload["payload"]
if isinstance(payload, dict):
raw_records = [payload]
else:
raw_records = payload
converted_records = []
for record in raw_records:
# Extract the payload whether it is nested under 'body' or passed directly
data = record
company = data.get("company") or {}
created = data.get("created") or {}
gifts = data.get("gifts") or {}
converted_records.append(
{
"id": data.get("id"),
"username": data.get("username"),
"company_id": company.get("id"),
"company_name": company.get("name"),
"company_code": company.get("code"),
"subscription_level": data.get("subscriptionLevel"),
"highest_tier": data.get("highestTier"),
"pioneer": data.get("pioneer", False),
"moderator": data.get("moderator", False),
"team": data.get("team", False),
"translator": data.get("translator", False),
"active_days_per_week": data.get("activeDaysPerWeek"),
"created_timestamp": created.get("timestamp"),
# Serialize JSONB payload for database insertion
"gifts": json.dumps(gifts) if gifts else None
}
)
return converted_records
def convert_user_tokens_data(raw_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'user_tokens' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"id": record.get("id"),
"userId": record.get("userId"),
"token": record.get("token"),
"refreshToken": record.get("refreshToken"),
"expiresAt": record.get("expiresAt"),
}
)
return converted_records
def convert_user_data_tokens_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'user_data_tokens' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"id": record.get("id"),
"userId": record.get("userId"),
"token": record.get("token"),
"permissions": record.get("permissions"),
"status": record.get("status"),
"createdAt": record.get("createdAt"),
"expiresAt": record.get("expiresAt"),
}
)
return converted_records
def convert_company_data(raw_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'company_data' table schema."""
converted_records = []
company_data = {}
representation = {}
representationContrubutors = []
rating_report = {}
headquarters = {}
headquarters_upgrade_items = []
headquarters_efficiency_gains = []
headquarters_efficiency_gains_next_level = []
record = raw_records["payload"]
representation = {
"representationid": uuid.uuid4(),
"contributednextlevelamount": record.get("representation").get("contributedNextLevel").get("amount"),
"contributednextlevelcurrency": record.get("representation").get("contributedNextLevel").get("currency"),
"contributedtotalamount": record.get("representation").get("contributedTotal").get("amount"),
"contributedtotalcurrency": record.get("representation").get("contributedTotal").get("currency"),
"currentlevel": record.get("representation").get("currentLevel"),
"costnextlevelamount": record.get("representation").get("costNextLevel").get("amount"),
"costnextlevelcurrency": record.get("representation").get("costNextLevel").get("currency"),
"leftnextlevelamount": record.get("representation").get("leftNextLevel").get("amount"),
"leftnextlevelcurrency": record.get("representation").get("leftNextLevel").get("currency"),
}
for contributor in record.get("representation").get("contributors"):
print("Company data representation contributors - Fail not finished!!")
# Handle earliest contract timestamp
earliest_contract = record.get("ratingReport").get("earliestContract")
if earliest_contract is not None and earliest_contract.get("timestamp") is not None:
earliest_contract = datetime.fromtimestamp(earliest_contract["timestamp"] / 1000)
else:
earliest_contract = None # Or None, 0, etc. based on your needs
rating_report = {
"contractcount": record.get("ratingReport").get("contractCount"),
"earliestcontract": earliest_contract,
"overallrating": record.get("ratingReport").get("overallRating"),
}
# Handle subscription expiry timestamp
next_relocation_time = record.get("headquarters").get("nextRelocationTime")
if next_relocation_time is not None and next_relocation_time.get("timestamp") is not None:
next_relocation_time = datetime.fromtimestamp(next_relocation_time["timestamp"] / 1000)
else:
next_relocation_time = None # Or None, 0, etc. based on your needs
headquarters = {
"addresssystemid": record.get("headquarters").get("address").get("lines")[0].get("entity").get("id"),
"addressplanetid": record.get("headquarters").get("address").get("lines")[1].get("entity").get("id"),
"headquarterslevel": record.get("headquarters").get("level"),
"nextrelocationtime": next_relocation_time,
"relocationlocked": record.get("headquarters").get("relocationLocked"),
"basepermits": record.get("headquarters").get("basePermits"),
"usedbasepermits": record.get("headquarters").get("usedBasePermits"),
"additionalbasepermits": record.get("headquarters").get("additionalBasePermits"),
"additionalproductionqueueslots": record.get("headquarters").get("additionalProductionQueueSlots"),
}
for item in record.get("headquarters").get("inventory").get("items"):
headquarters_upgrade_items.append(
{
"materialid": item.get("material").get("id"),
"amount": item.get("amount"),
"amountlimit": item.get("limit"),
}
)
for efficiency_gain in record.get("headquarters").get("efficiencyGains"):
headquarters_efficiency_gains.append(
{
"category": efficiency_gain.get("category"),
"gain": efficiency_gain.get("gain"),
}
)
for efficiency_gain in record.get("headquarters").get("efficiencyGainsNextLevel"):
headquarters_efficiency_gains_next_level.append(
{
"category": efficiency_gain.get("category"),
"gain": efficiency_gain.get("gain"),
}
)
converted_records = {
"company_data": {
"companyid": record.get("id"),
"companyname": record.get("name"),
"companycode": record.get("code"),
"startinglocationsystemid": record.get("startingLocation").get("lines")[0].get("entity").get("id"),
"startinglocationplanetid": record.get("startingLocation").get("lines")[1].get("entity").get("id"),
"startingprofile": record.get("startingProfile"),
"countryid": record.get("countryId"),
},
"representation": representation,
"representationContributors": representationContrubutors,
"ratingReport": rating_report,
"headquarters": headquarters,
"headquartersUpgradeItems": headquarters_upgrade_items,
"headquarters_efficiency_gains": headquarters_efficiency_gains,
"headquarters_efficiency_gains_next_level": headquarters_efficiency_gains_next_level,
}
return converted_records
def convert_world_materials_data(
raw_data: Dict[str, Any],
) -> Dict[str, List[Dict[str, Any]]]:
"""
Converts raw material data into two separate lists of dictionaries,
one for material_categories and one for materials.
"""
converted_categories = []
converted_materials = []
categories_data = raw_data["payload"].get("categories", [])
for category in categories_data:
category_id = category.get("id")
name = category.get("name")
children_ids = category.get("children")
# Add a record for the material_categories table
converted_categories.append(
{
"id": category_id if category_id is not None else "null",
"name": name if name is not None else "null",
#'children': json.dumps(children_ids if children_ids is not None else [])
}
)
materials = category.get("materials", [])
for material in materials:
material_id = material.get("id")
name = material.get("name")
ticker = material.get("ticker")
weight = material.get("weight")
volume = material.get("volume")
resource = material.get("resource")
# Add a record for the materials table
converted_materials.append(
{
"materialid": material_id if material_id is not None else "null",
"name": name if name is not None else "null",
"ticker": ticker if ticker is not None else "null",
"category": category_id if category_id is not None else "null",
"weight": weight if weight is not None else 0.0,
"volume": volume if volume is not None else 0.0,
"resource": resource if resource is not None else False,
}
)
return {
"material_categories": converted_categories,
"materials": converted_materials,
}
def convert_headquarters_upgrade_items_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'headquarters_upgrade_items' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"id": record.get("id"),
"headquartersId": record.get("headquartersId"),
"materialId": record.get("materialId"),
"amount": record.get("amount"),
"limit": record.get("limit"),
}
)
return converted_records
def convert_storage_removed(raw_record: Dict[str, Any]) -> List[Dict[str, Any]]:
converted_record = []
for storeid in raw_record["payload"]["storeIds"]:
converted_record.append({"storageid": storeid, "removed": True})
return converted_record
def convert_full_refresh_storage_data(
raw_records: List[Dict[str, Any]],
) -> [Dict[str, Any]]:
"""Converts raw data to match the 'storages' table schema for full refresh."""
return convert_storages_data(raw_records, full_refresh=True)
def convert_storages_data(raw_records: List[Dict[str, Any]], full_refresh: bool = False) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'storages' table schema."""
storages = []
for record in raw_records["payload"]["stores"]:
storages_items = []
storage = {
"storageid": record.get("id"),
"addressableid": record.get("addressableId"),
"name": record.get("name"),
"weightload": record.get("weightLoad"),
"weightcapacity": record.get("weightCapacity"),
"volumeload": record.get("volumeLoad"),
"volumecapacity": record.get("volumeCapacity"),
"fixed": record.get("fixed"),
"tradestore": record.get("tradeStore"),
"rank": record.get("rank"),
"locked": record.get("locked"),
"type": record.get("type"),
"xata_updatedat": datetime.fromtimestamp(datetime.now().timestamp()),
}
for item in record.get("items", []):
# Skip items of type 'BLOCKED' as per your original logic
if item.get("type") == "BLOCKED":
storages_items.append(
{
"storageid": record.get("id"),
"materialid": item.get("id"),
"quantity": None,
"totalweight": item.get("weight"),
"totalvolume": item.get("volume"),
"currencyamount": None,
"currencytype": None,
"type": item.get("type"),
}
)
continue
# New check: Skip the item if the 'quantity' key is missing
if item.get("quantity") is None:
storages_items.append(
{
"storageid": record.get("id"),
"materialid": item.get("id"),
"quantity": None,
"totalweight": item.get("weight"),
"totalvolume": item.get("volume"),
"currencyamount": None,
"currencytype": None,
"type": item.get("type"),
}
)
continue
quantity_data = item.get("quantity") or {}
currency_value = (quantity_data.get("value") or {}) if isinstance(quantity_data, dict) else {}
storages_items.append(
{
"storageid": record.get("id"),
"materialid": item.get("id") or item.get("materialId"),
"quantity": quantity_data.get("amount") if isinstance(quantity_data, dict) else (quantity_data if isinstance(quantity_data, (int, float)) else None),
"totalweight": item.get("weight"),
"totalvolume": item.get("volume"),
"currencyamount": currency_value.get("amount") if isinstance(currency_value, dict) else None,
"currencytype": currency_value.get("currency") if isinstance(currency_value, dict) else None,
"type": item.get("type"),
}
)
storage["storage_items"] = storages_items
storages.append(storage)
return {"full_refresh": full_refresh, "storages": storages}
def convert_gateway_data_wrapper(raw_payload: Dict[str, Any]) -> Dict[str, Any]:
"""Converts raw data to match the 'gateways' table schema."""
return convert_gateway_data(raw_payload)
def convert_warehouses_data(raw_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'warehouses' table schema."""
converted_records = []
for record in raw_records["payload"]["storages"]:
# Handle founded timestamp
next_payment = record.get("nextPayment")
if next_payment is not None and next_payment.get("timestamp") is not None:
next_payment = datetime.fromtimestamp(next_payment["timestamp"] / 1000)
else:
next_payment = None
converted_records.append(
{
"warehouseid": record.get("warehouseId"),
"storeid": record.get("storeId"),
"units": record.get("units"),
"weightcapacity": record.get("weightCapacity"),
"volumecapacity": record.get("volumeCapacity"),
"nextpayment": next_payment,
"feeamount": record.get("fee").get("amount"),
"feecurrency": record.get("fee").get("currency"),
"status": record.get("status"),
"addresssystem": record.get("address").get("lines")[0].get("entity").get("id"),
"addressplanet": record.get("address").get("lines")[1].get("entity").get("id"),
}
)
return converted_records
def convert_storage_items_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'storage_items' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"storageId": record.get("storageId"),
"materialId": record.get("materialId"),
"quantity": record.get("quantity"),
"totalWeight": record.get("totalWeight"),
"totalVolume": record.get("totalVolume"),
"currencyAmount": record.get("currencyAmount"),
"currencyType": record.get("currencyType"),
}
)
return converted_records
def convert_production_lines_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'production_lines' table schema."""
converted_records = []
for record in raw_records["payload"]["productionLines"]:
converted_records.append(
{
"productionlineid": record.get("id"),
"siteid": record.get("siteId"),
"type": record.get("type"),
"capacity": record.get("capacity"),
"slots": record.get("slots"),
"efficiency": record.get("efficiency"),
"condition": record.get("condition"),
"orders": convert_production_line_orders_data(record.get("orders")),
"production_templates": convert_production_line_order_production_templates_data(
record.get("productionTemplates"), record.get("id")
),
"efficiency_factors": convert_production_line_efficiency_factors(
record.get("efficiencyFactors"), record.get("id")
),
"workforces": convert_production_workforces_data(record.get("workforces"), record.get("id")),
}
)
return {
"siteid": raw_records["payload"].get("siteId"),
"production_lines": converted_records,
}
def convert_production_workforces_data(
raw_records: List[Dict[str, Any]], production_line_id: string
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'production_workforces' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"productionlineid": production_line_id,
"level": record.get("level"),
"efficiency": record.get("efficiency"),
}
)
return converted_records
def convert_production_line_orders_data(
raw_records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'production_line_orders' table schema."""
converted_records = []
for record in raw_records:
# Handle created timestamp
created = record.get("created")
if created is not None and created.get("timestamp") is not None:
created = datetime.fromtimestamp(created["timestamp"] / 1000)
else:
created = None
# Handle created timestamp
started = record.get("started")
if started is not None and started.get("timestamp") is not None:
started = datetime.fromtimestamp(started["timestamp"] / 1000)
else:
started = None
# Handle created timestamp
completion = record.get("completion")
if completion is not None and completion.get("timestamp") is not None:
completion = datetime.fromtimestamp(completion["timestamp"] / 1000)
else:
completion = None
# Handle created timestamp
lastupdated = record.get("lastUpdated")
if lastupdated is not None and lastupdated.get("timestamp") is not None:
lastupdated = datetime.fromtimestamp(lastupdated["timestamp"] / 1000)
else:
lastupdated = None
duration = record.get("duration")
if duration is not None and duration.get("millis") is not None:
duration = duration.get("millis")
else:
duration = None
converted_records.append(
{
"orderid": record.get("id"),
"productionlineid": record.get("productionLineId"),
"recipeid": record.get("recipeId"),
"created": created,
"started": started,
"completion": completion,
"duration": duration,
"lastupdated": lastupdated,
"completed": bool(record.get("completed")),
"halted": record.get("halted"),
"recurring": record.get("recurring"),
"productionfeeamount": record.get("productionFee").get("amount"),
"productionfeecurrency": record.get("productionFee").get("currency"),
"inputs": convert_production_line_order_materials_data(record.get("inputs"), record.get("id"), "input"),
"outputs": convert_production_line_order_materials_data(
record.get("outputs"), record.get("id"), "output"
),
}
)
return converted_records
def convert_production_line_order_materials_data(
raw_records: List[Dict[str, Any]], order_id: string, material_type: string
) -> List[Dict[str, Any]]:
"""Converts raw data to match the 'production_line_order_materials' table schema."""
converted_records = []
for record in raw_records:
converted_records.append(
{
"orderid": order_id,
"materialId": record.get("material").get("id"),
"type": material_type,
"amount": record.get("amount"),
"valueAmount": record.get("value").get("amount"),
"valueCurrency": record.get("value").get("currency"),
}
)
return converted_records
def convert_production_line_order_production_templates_data(
raw_records: List[Dict[str, Any]], production_line_id: str
) -> List[Dict[str, Any]]:
converted_records = []
for record in raw_records:
duration = record.get("duration")
if duration is not None and duration.get("millis") is not None:
duration = duration.get("millis")
else:
duration = None
converted_records.append(
{
"productiontemplateid": record.get("id"),
"productionlineid": production_line_id,
"name": record.get("name"),
"duration": duration,
"efficiency": record.get("efficiency"),
"effortfactor": record.get("effortFactor"),
"experience": record.get("experience"),
"productionfee": record.get("productionFeeFactor").get("amount"),
"productionfeecurrency": record.get("productionFeeFactor").get("currency"),
"input_factors": convert_templates_factors_data(
record.get("inputFactors"),
record.get("id"),
"input",
production_line_id,
),
"output_factors": convert_templates_factors_data(
record.get("outputFactors"),
record.get("id"),
"output",
production_line_id,
),
}
)
return converted_records
def convert_templates_factors_data(
raw_records: List[Dict[str, Any]],
production_template_id: string,
material_type: string,
production_line_id: str,
) -> List[Dict[str, Any]]:
converted_records = []
for record in raw_records:
converted_records.append(
{
"productiontemplateid": production_template_id,
"productionlineid": production_line_id,
"materialid": record.get("material").get("id"),
"factor": record.get("factor"),
}
)
return converted_records
def convert_production_line_efficiency_factors(
raw_records: List[Dict[str, Any]], production_line_id: string
) -> List[Dict[str, Any]]:
converted_records = []
for record in raw_records:
converted_records.append(
{
"productionlineid": production_line_id,
"expertisecategory": record.get("expertiseCategory", None),
"type": record.get("type"),
"effectivity": record.get("effectivity"),
"value": record.get("value"),
}
)
return converted_records
def convert_production_line_added(raw_record: Dict[str, Any]) -> Dict[str, Any]:
record = raw_record["payload"]
order = convert_production_line_orders_data([record])[0]
return order
def convert_production_line_updated(raw_record: Dict[str, Any]) -> Dict[str, Any]:
record = raw_record["payload"]
order = convert_production_line_orders_data([record])[0]
return order
def convert_production_line_removed(raw_record: Dict[str, Any]) -> Dict[str, Any]:
payload = raw_record.get("payload") if isinstance(raw_record, dict) else {}
if not isinstance(payload, dict):
payload = {}
order_id = payload.get("orderId") or payload.get("orderid") or payload.get("id")
production_line_id = (
payload.get("productionLineId") or payload.get("productionlineid") or payload.get("lineId")
)
return {
"orderid": order_id,
"productionlineid": production_line_id,
}
# ship flight
def get_entity_id(lines, entity_type):
"""
Helper function to safely extract the ID of a specific entity type
(SYSTEM, PLANET, or STATION) from the 'lines' list.
"""
if lines:
for line in lines:
if line.get("type") == entity_type and "entity" in line:
return line["entity"].get("id")
return None
def get_total_fuel_consumption(segments, fuel_type):
"""
Helper function to calculate the total fuel consumption (STL or FTL)
across all segments.
"""
total_consumption = 0
consumption_key = f"{fuel_type}FuelConsumption"
for segment in segments:
consumption = segment.get(consumption_key)
if consumption is not None:
total_consumption += consumption
return total_consumption
def get_total_damage(segments):
"""
Helper function to calculate the total damage across all segments.
"""
total_damage = 0.0
for segment in segments:
damage = segment.get("damage")
if damage is not None:
total_damage += damage
return total_damage
def convert_flight_record(record: Dict[str, Any]) -> Dict[str, Any]:
"""
Converts a single raw flight data record into a flat object with lowercase keys
based on the desired schema, calculating aggregate values from segments.
"""
record = record.get("payload", record)
# 1. Arrival/Departure Timestamps and Datetime Objects
arrival_ts_ms = record.get("arrival", {}).get("timestamp")
departure_ts_ms = record.get("departure", {}).get("timestamp")
arrival = None
if arrival_ts_ms is not None:
arrival = datetime.fromtimestamp(arrival_ts_ms / 1000, tz=timezone.utc)
else:
arrival = None
departure = None
if departure_ts_ms is not None:
departure = datetime.fromtimestamp(departure_ts_ms / 1000, tz=timezone.utc)
else:
departure = None
# 2. Extract Origin/Destination IDs
origin_lines = record.get("origin", {}).get("lines", [])
destination_lines = record.get("destination", {}).get("lines", [])
origin_system_id = get_entity_id(origin_lines, "SYSTEM")
origin_planet_id = get_entity_id(origin_lines, "PLANET")
origin_station_id = get_entity_id(origin_lines, "STATION")
destination_system_id = get_entity_id(destination_lines, "SYSTEM")
destination_planet_id = get_entity_id(destination_lines, "PLANET")
destination_station_id = get_entity_id(destination_lines, "STATION")
# 3. Aggregate Segment Data
segments = record.get("segments", [])
stl_total_consumption = get_total_fuel_consumption(segments, "stl")
ftl_total_consumption = get_total_fuel_consumption(segments, "ftl")
total_damage = get_total_damage(segments)
# Note: stlDistance and ftlDistance are taken from the top level,
# as per the structure, which likely represents the total distance.
# 4. Construct the converted record with lowercase keys
converted_record = {
"id": record.get("id"),
"aborted": record.get("aborted"),
"damage": total_damage, # Use aggregated damage from segments
"shipid": record.get("shipId"),
# Origin/Destination IDs
"originsystemid": origin_system_id,
"originplanetid": origin_planet_id,
"originstationid": origin_station_id,
"destinationsystemid": destination_system_id,
"destinationplanetid": destination_planet_id,
"destinationstationid": destination_station_id,
"currentsegmentindex": record.get("currentSegmentIndex"),
"segments": [
convert_segment(segment, record.get("id"), index)
for index, segment in enumerate(segments)
if convert_segment(segment, record.get("id"), index) is not None
],
# Timestamps
"departuretimestamp": departure,
"arrivaltimestamp": arrival,
# Distance and Fuel Consumption
"stldistance": record.get("stlDistance"),
"ftldistance": record.get("ftlDistance"),
"stltotalconsumption": stl_total_consumption,
"ftltotalconsumption": ftl_total_consumption,
}
return converted_record
def convert_flight_ended_record(raw_record: Dict[str, Any]) -> Dict[str, Any]:
record = raw_record.get("payload", {})
def get_entity_id(lines, entity_type):
if not lines:
return None
for line in lines:
if line.get("type") == entity_type and "entity" in line:
return line["entity"].get("id")
return None
# FIX: Generating a timezone-aware UTC datetime
return {
"id": record.get("id"),
"shipId": record.get("shipId"),
"destinationSystemId": get_entity_id(record.get("destination", {}).get("lines", []), "SYSTEM"),
"destinationPlanetId": get_entity_id(record.get("destination", {}).get("lines", []), "PLANET"),
"destinationStationId": get_entity_id(record.get("destination", {}).get("lines", []), "STATION"),
"ended_at": datetime.now(timezone.utc)
}
def convert_flight_records(raw_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
records = raw_records["payload"]
converted_records = []
for record in records["flights"]:
converted_record = convert_flight_record(record)
converted_records.append(converted_record)
return converted_records
def convert_segment(raw_segment: Dict[str, Any], flight_id: str, segment_index: int) -> Optional[Dict[str, Any]]:
"""
Converts a raw flight segment JSON object into a standardized dictionary
for database upsert, handling different segment types and nested data.
Args:
raw_segment: The raw JSON dictionary for a single segment.
flight_id: The ID of the parent flight (to link the segment).
segment_index: The order of the segment within the flight.
Returns:
A standardized dictionary of segment data, or None if the segment is invalid.
"""
if not raw_segment or not isinstance(raw_segment, dict):
return None
segment_type = raw_segment.get("type")
# --- Helper to extract entity details from a location dictionary ---
def extract_location_details(location: Dict[str, Any]) -> Dict[str, Any]:
details = {
"system_id": None,
"station_id": None,
"planet_id": None,
"orbit_semi_major_axis": None,
"orbit_eccentricity": None,
"orbit_inclination": None,
"orbit_periapsis": None,
"orbit_right_ascension": None,
"location_type": None, # e.g., 'STATION' or 'ORBIT'
}
lines = location.get("lines", [])
if not lines:
return details
for line in lines:
entity = line.get("entity")
line_type = line.get("type")
if entity and line_type == "SYSTEM":
details["system_id"] = entity.get("id")
elif entity and line_type == "STATION":
details["station_id"] = entity.get("id")
details["location_type"] = "STATION"
elif entity and line_type == "PLANET":
details["station_id"] = entity.get("id")
details["location_type"] = "PLANET"
elif line.get("orbit") and line_type == "ORBIT":
orbit = line["orbit"]
details["orbit_semi_major_axis"] = orbit.get("semiMajorAxis")
details["orbit_eccentricity"] = orbit.get("eccentricity")
details["orbit_inclination"] = orbit.get("inclination")
details["orbit_periapsis"] = orbit.get("periapsis")
details["orbit_right_ascension"] = orbit.get("rightAscension")
details["location_type"] = "ORBIT"
return details
# --- Extract core fields ---
departure_ts_ms = raw_segment.get("departure", {}).get("timestamp")
arrival_ts_ms = raw_segment.get("arrival", {}).get("timestamp")
# Calculate duration in seconds
duration_s = None
if departure_ts_ms and arrival_ts_ms:
duration_s = (arrival_ts_ms - departure_ts_ms) / 1000
# Extract Origin/Destination details
origin_details = extract_location_details(raw_segment.get("origin", {}))
destination_details = extract_location_details(raw_segment.get("destination", {}))
origin_orbit_data = {
"semimajoraxis": origin_details["orbit_semi_major_axis"],
"eccentricity": origin_details["orbit_eccentricity"],
"inclination": origin_details["orbit_inclination"],
"periapsis": origin_details["orbit_periapsis"],
"rightascension": origin_details["orbit_right_ascension"],
}
destination_orbit_data = {
"semimajoraxis": destination_details["orbit_semi_major_axis"],
"eccentricity": destination_details["orbit_eccentricity"],
"inclination": destination_details["orbit_inclination"],
"periapsis": destination_details["orbit_periapsis"],
"rightascension": destination_details["orbit_right_ascension"],
}
transferEllipse_raw = raw_segment.get("transferEllipse")
transferEllipse = {}
if transferEllipse_raw:
transferEllipse = {
"alpha": transferEllipse_raw.get("alpha"),
"semimajoraxis": transferEllipse_raw.get("semiMajorAxis"),
"semiminoraxis": transferEllipse_raw.get("semiMinorAxis"),
"centerx": transferEllipse_raw.get("center").get("x"),
"centery": transferEllipse_raw.get("center").get("y"),
"centerz": transferEllipse_raw.get("center").get("z"),
"startpositionx": transferEllipse_raw.get("startPosition").get("x"),
"startpositiony": transferEllipse_raw.get("startPosition").get("y"),
"startpositionz": transferEllipse_raw.get("startPosition").get("z"),
"targetpositionx": transferEllipse_raw.get("targetPosition").get("x"),