Repository navigation
Expand file tree
/
Copy pathdata_handlers.py
More file actions
2683 lines (2376 loc) · 111 KB
/
Copy pathdata_handlers.py
File metadata and controls
2683 lines (2376 loc) · 111 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_handlers.py
import asyncio
import csv
import json
import logging
import os
import time
import uuid
from collections import defaultdict
from datetime import datetime
from decimal import Decimal
from io import StringIO
from typing import Any, Dict, List, Optional
import asyncpg
from fastapi import (
APIRouter,
BackgroundTasks,
Depends,
HTTPException,
Path,
Request,
Response,
status,
)
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from starlette.requests import ClientDisconnect
from auth import get_current_user_id
from db import Database
from helpers.production_lines import get_production_data_nested
data_router = APIRouter()
logger = logging.getLogger(__name__)
# The message object with a flexible payload
class Message(BaseModel):
messageType: str
payload: Dict[str, Any]
# The items inside the nested list
class DataItem(BaseModel):
id: str
message: Message
# The top-level payload model
class DataBatchPayload(BaseModel):
# This expects a list of lists of DataItem objects
data: List[DataItem]
MAX_PAYLOAD_SIZE = 200 * 1024 * 1024
@data_router.post("/data_batch")
async def data_batch(
request: Request,
user_id: str = Depends(get_current_user_id),
background_tasks: BackgroundTasks = BackgroundTasks(),
):
# 1. IMMEDIATE HEADER CHECK (Pre-download)
# This prevents the server from even trying to download a 1GB file
content_length = request.headers.get("content-length")
if content_length and int(content_length) > MAX_PAYLOAD_SIZE:
logger.warning(f"SECURITY: Blocked oversized header ({content_length} bytes) from User: {user_id}")
raise HTTPException(status_code=413, detail="Payload too large.")
# 2. SAFE BODY RETRIEVAL
# Wrapping in try/except handles the 'starlette.requests.ClientDisconnect'
try:
body_bytes = await request.body()
except ClientDisconnect:
logger.warning(f"Network: Client {user_id} disconnected during upload.")
return JSONResponse(status_code=408, content={"detail": "Connection closed by client"})
except Exception as e:
logger.error(f"Unexpected error during body read for {user_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error during data transfer")
# 3. SECONDARY SIZE CHECK (Post-Decompression)
original_size = request.scope.get("original_gzip_size", len(body_bytes))
if original_size > MAX_PAYLOAD_SIZE:
logger.warning(f"SECURITY: Blocked oversized payload ({original_size} bytes) from User: {user_id}")
raise HTTPException(status_code=413, detail="Payload too large.")
# 4. PARSE JSON
try:
payload = json.loads(body_bytes)
except Exception as e:
# Get REAL IP for security logging
x_forwarded_for = request.headers.get("X-Forwarded-For")
ip_address = x_forwarded_for.split(",")[0].strip() if x_forwarded_for else (request.client.host if request.client else "N/A")
logger.warning(f"SECURITY: {ip_address} | User: {user_id} | JSON Parse Error: {str(e)}")
raise HTTPException(status_code=400, detail="Invalid JSON payload")
# 5. VALIDATE STRUCTURE
items_to_process = payload.get("data")
if not isinstance(items_to_process, list) or not items_to_process:
# If the data is bad, we still return a 400 so the extension knows to clear the batch
raise HTTPException(status_code=400, detail="Payload 'data' must be a non-empty list.")
# 6. UPDATE USER TIMESTAMP
try:
async with request.app.state.db.pool.acquire() as conn:
await conn.execute(
"UPDATE users SET xata_updatedat = $2 WHERE accountid = $1;",
user_id,
datetime.now()
)
except Exception as e:
# We log the error but don't stop processing; data is more important than the timestamp
logger.error(f"DB Update failed for user {user_id}: {e}")
# 7. HAND OFF TO BACKGROUND TASK
from tasks import process_data_batch_task
background_tasks.add_task(
process_data_batch_task,
items_to_process=items_to_process,
user_id=user_id,
db=request.app.state.db,
)
return {"success": True, "count": len(items_to_process)}
# FIXME: FROM THIS POINT EVERYTHING UNDER THIS IS MIX OF ENDPOINTS THAT NEED TO BE REFACTORED TO THE CORRECT PLACES
@data_router.get("/market_price_all")
async def get_market(request: Request):
try:
data = await get_market_data(request.app.state.db)
return JSONResponse(content={"success": True, "data": data})
except Exception as e:
logger.error(f"Failed to fetch market data: {e}", exc_info=True)
return {"success": False, "message": "Failed to retrieve market data."}
@data_router.get("/market_price_csv")
async def get_market_csv(request: Request):
try:
csv_content = await get_market_data_for_csv(request.app.state.db)
return Response(
content=csv_content,
media_type="text/csv",
# headers={"Content-Disposition": "attachment; filename=market_data.csv"}
)
except Exception as e:
logger.error(f"Failed to fetch market data: {e}", exc_info=True)
return {"success": False, "message": "Failed to retrieve market data."}
async def get_market_data(db: Database) -> List[Dict[str, Any]]:
"""
Fetches market data from the database and handles Decimal serialization.
"""
sql_query = """
SELECT
SPLIT_PART(cb.ticker, '.', 1) AS Ticker,
COALESCE(SUM(cbb_mm.priceamount), 0) AS MMBuy,
COALESCE(SUM(cbs_mm.priceamount), 0) AS MMSell,
-- AI1 Data
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.priceaverage END) AS "AI1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.askamount END) AS "AI1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.askprice END) AS "AI1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.bidamount END) AS "AI1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.bidprice END) AS "AI1-BidPrice",
TO_CHAR(MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb."xata_updatedat" END), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "AI1-UpdatedAt",
-- CI1 Data
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.priceaverage END) AS "CI1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.askamount END) AS "CI1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.askprice END) AS "CI1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.bidamount END) AS "CI1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.bidprice END) AS "CI1-BidPrice",
TO_CHAR(MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb."xata_updatedat" END), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "CI1-UpdatedAt",
-- CI2 Data
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.priceaverage END) AS "CI2-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.askamount END) AS "CI2-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.askprice END) AS "CI2-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.bidamount END) AS "CI2-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.bidprice END) AS "CI2-BidPrice",
TO_CHAR(MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb."xata_updatedat" END), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "CI2-UpdatedAt",
-- NC1 Data
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.priceaverage END) AS "NC1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.askamount END) AS "NC1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.askprice END) AS "NC1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.bidamount END) AS "NC1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.bidprice END) AS "NC1-BidPrice",
TO_CHAR(MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb."xata_updatedat" END), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "NC1-UpdatedAt",
-- NC2 Data
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.priceaverage END) AS "NC2-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.askamount END) AS "NC2-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.askprice END) AS "NC2-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.bidamount END) AS "NC2-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.bidprice END) AS "NC2-BidPrice",
TO_CHAR(MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb."xata_updatedat" END), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "NC2-UpdatedAt",
-- IC1 Data
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.priceaverage END) AS "IC1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.askamount END) AS "IC1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.askprice END) AS "IC1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.bidamount END) AS "IC1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.bidprice END) AS "IC1-BidPrice",
TO_CHAR(MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb."xata_updatedat" END), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "IC1-UpdatedAt",
-- Global Fallback
TO_CHAR(MAX(cb."xata_updatedat"), 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "last_update"
FROM
cx_brokers AS cb
LEFT JOIN
cx_brokers_buy_orders AS cbb_mm
ON cb.brokermaterialid = cbb_mm.brokermaterialid AND cbb_mm.tradername = 'Insitor Cooperative Market Maker'
LEFT JOIN
cx_brokers_sell_orders AS cbs_mm
ON cb.brokermaterialid = cbs_mm.brokermaterialid AND cbs_mm.tradername = 'Insitor Cooperative Market Maker'
WHERE
cb.ticker IS NOT NULL AND POSITION('.' IN cb.ticker) > 0
GROUP BY
SPLIT_PART(cb.ticker, '.', 1)
ORDER BY
SPLIT_PART(cb.ticker, '.', 1);
"""
try:
async with db.pool.acquire() as con:
data = await con.fetch(sql_query)
data_formatted = []
for record in data:
row = dict(record)
for key, value in row.items():
if isinstance(value, Decimal):
row[key] = float(value)
data_formatted.append(row)
return data_formatted
except Exception as e:
logger.error(f"Failed to fetch market data: {e}", exc_info=True)
return []
async def get_market_data_for_csv(db: Database) -> str:
"""
Fetches market data from the database, pivots it for CSV output,
and returns it as a CSV string.
"""
sql_query = """
SELECT
SPLIT_PART(cb.ticker, '.', 1) AS Ticker,
COALESCE(SUM(cbb_mm.priceamount), 0) AS MMBuy,
COALESCE(SUM(cbs_mm.priceamount), 0) AS MMSell,
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.priceaverage END) AS "AI1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.askamount END) AS "AI1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.askprice END) AS "AI1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.askamount END) AS "AI1-AskAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.bidamount END) AS "AI1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.bidprice END) AS "AI1-BidPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'AI1' THEN cb.bidamount END) AS "AI1-BidAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.priceaverage END) AS "CI1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.askamount END) AS "CI1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.askprice END) AS "CI1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.askamount END) AS "CI1-AskAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.bidamount END) AS "CI1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.bidprice END) AS "CI1-BidPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI1' THEN cb.bidamount END) AS "CI1-BidAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.priceaverage END) AS "CI2-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.askamount END) AS "CI2-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.askprice END) AS "CI2-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.askamount END) AS "CI2-AskAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.bidamount END) AS "CI2-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.bidprice END) AS "CI2-BidPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'CI2' THEN cb.bidamount END) AS "CI2-BidAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.priceaverage END) AS "NC1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.askamount END) AS "NC1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.askprice END) AS "NC1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.askamount END) AS "NC1-AskAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.bidamount END) AS "NC1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.bidprice END) AS "NC1-BidPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC1' THEN cb.bidamount END) AS "NC1-BidAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.priceaverage END) AS "NC2-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.askamount END) AS "NC2-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.askprice END) AS "NC2-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.askamount END) AS "NC2-AskAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.bidamount END) AS "NC2-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.bidprice END) AS "NC2-BidPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'NC2' THEN cb.bidamount END) AS "NC2-BidAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.priceaverage END) AS "IC1-Average",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.askamount END) AS "IC1-AskAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.askprice END) AS "IC1-AskPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.askamount END) AS "IC1-AskAvail",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.bidamount END) AS "IC1-BidAmt",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.bidprice END) AS "IC1-BidPrice",
MAX(CASE WHEN SPLIT_PART(cb.ticker, '.', 2) = 'IC1' THEN cb.bidamount END) AS "IC1-BidAvail",
MAX(cb."xata_updatedat") AS "last_update"
FROM
cx_brokers AS cb
LEFT JOIN
cx_brokers_buy_orders AS cbb_mm
ON cb.brokermaterialid = cbb_mm.brokermaterialid AND cbb_mm.tradername = 'Insitor Cooperative Market Maker'
LEFT JOIN
cx_brokers_sell_orders AS cbs_mm
ON cb.brokermaterialid = cbs_mm.brokermaterialid AND cbs_mm.tradername = 'Insitor Cooperative Market Maker'
WHERE
cb.ticker IS NOT NULL AND POSITION('.' IN cb.ticker) > 0
GROUP BY
SPLIT_PART(cb.ticker, '.', 1)
ORDER BY
SPLIT_PART(cb.ticker, '.', 1);
"""
# Define the exact CSV headers in order
csv_headers = [
"Ticker",
"last_update",
"MMBuy",
"MMSell",
"AI1-Average",
"AI1-AskAmt",
"AI1-AskPrice",
"AI1-AskAvail",
"AI1-BidAmt",
"AI1-BidPrice",
"AI1-BidAvail",
"CI1-Average",
"CI1-AskAmt",
"CI1-AskPrice",
"CI1-AskAvail",
"CI1-BidAmt",
"CI1-BidPrice",
"CI1-BidAvail",
"CI2-Average",
"CI2-AskAmt",
"CI2-AskPrice",
"CI2-AskAvail",
"CI2-BidAmt",
"CI2-BidPrice",
"CI2-BidAvail",
"NC1-Average",
"NC1-AskAmt",
"NC1-AskPrice",
"NC1-AskAvail",
"NC1-BidAmt",
"NC1-BidPrice",
"NC1-BidAvail",
"NC2-Average",
"NC2-AskAmt",
"NC2-AskPrice",
"NC2-AskAvail",
"NC2-BidAmt",
"NC2-BidPrice",
"NC2-BidAvail",
"IC1-Average",
"IC1-AskAmt",
"IC1-AskPrice",
"IC1-AskAvail",
"IC1-BidAmt",
"IC1-BidPrice",
"IC1-BidAvail",
]
try:
records = []
async with db.pool.acquire() as con:
# Set a lock_timeout in case another process is holding a lock
await con.execute("SET lock_timeout = '10s';")
records = await con.fetch(sql_query)
# Use StringIO to build the CSV string in memory
output = StringIO()
writer = csv.writer(output)
# Write the header row
writer.writerow(csv_headers)
# Write data rows
for record in records:
row_data = []
for header in csv_headers:
# Get value by header name, default to empty string for None
value = record.get(header)
# Handle potential float values that might appear like integers
if isinstance(value, float) and value.is_integer():
value = int(value)
row_data.append(str(value) if value is not None else "")
writer.writerow(row_data)
csv_string = output.getvalue()
output.close()
return csv_string
except Exception as e:
logger.error(f"Failed to generate CSV for market data: {e}", exc_info=True)
raise
@data_router.get("/corp_prices_all")
async def get_corp_prices(request: Request):
try:
pool = request.app.state.db.pool
async with pool.acquire() as con:
data = await con.fetch("""
SELECT ticker, price FROM material_prices;
""")
material_data = [{"ticker": record["ticker"], "price": float(record["price"])} for record in data]
except Exception as e:
print(f"An error occurred: {e}")
return JSONResponse(
content={"success": False, "message": "Failed to retrieve data."},
status_code=500,
)
return JSONResponse(content={"success": True, "data": material_data})
fio_url = "https://rest.fnar.net/storage/Filefolders/0543343118b30be210a472db8c4a13d6"
fio_auth_token = os.environ.get("ffApi")
@data_router.post("/get_ship_production")
async def get_ship_production(request: Request, payload: Optional[Dict[str, bool]] = None):
"""
Fetches ship production and storage data. Can fetch storage data from either the local database
or an external FIO API based on the 'fio' flag in the request payload.
"""
try:
pool = request.app.state.db.pool
fio = payload.get("fio", False) if payload else False
# Acquire a connection from the pool for the database calls
async with pool.acquire() as conn:
# Always fetch ship_production data from the database
records = await conn.fetch(
"SELECT orderid, orderwaittime, price, shiptype, username, position FROM ship_production ORDER BY orderid ASC"
)
ship_orders = [dict(record) for record in records]
storage_items = []
""" if fio:
# Use httpx to make an asynchronous GET request to the FIO API
headers = {
"accept": "application/json",
"Authorization": fio_auth_token,
}
async with httpx.AsyncClient() as client:
try:
response = await client.get(fio_url, headers=headers, timeout=10.0)
response.raise_for_status() # Raises an exception for 4xx/5xx responses
fio_data = response.json()
tickers_of_interest = {
"MSL",
"FFC",
"LHP",
"CQL",
"QCR",
"WCB",
"LFL",
"HCB",
"BR1",
"SFE",
"MFE",
"SSC",
"LFE",
"FSE",
"CQM",
"LCB",
"VCB",
"CQS",
"BRS",
"SSL",
}
# Process the StorageItems from the FIO API response
if "StorageItems" in fio_data and isinstance(fio_data["StorageItems"], list):
for item in fio_data["StorageItems"]:
material_ticker = item.get("MaterialTicker")
if material_ticker in tickers_of_interest:
storage_items.append(
{
"ticker": material_ticker,
"quantity": item.get("MaterialAmount"),
}
)
else:
raise ValueError("FIO API response is missing 'StorageItems' or it's not a list.")
except httpx.HTTPStatusError as e:
logger.error(f"HTTP error fetching FIO data: {e.response.status_code} - {e.response.text}")
raise HTTPException(
status_code=e.response.status_code,
detail=f"FIO API error: {e.response.status_code} - {e.response.text}",
)
except httpx.RequestError as e:
logger.error(f"Network error fetching FIO data: {e}")
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Could not connect to FIO API.",
)
except (ValueError, KeyError) as e:
logger.error(f"Error parsing FIO API response: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to parse FIO API response data.",
)
else:
"""
# Fallback to fetching storage data from the local database
storage_records = await conn.fetch("""SELECT
mt.ticker,
si.quantity
FROM
storages AS s
INNER JOIN
warehouses AS w ON w.warehouseid = s.addressableid
INNER JOIN
storage_items AS si ON si.storageid = s.storageid
INNER JOIN
materials AS mt ON mt.materialid = si.materialid
INNER JOIN
systems AS sys ON w.addresssystem = sys.systemid
INNER JOIN
users_data AS ud ON ud.userid = s.userid
INNER JOIN
stations AS st ON st.warehouseid = w.warehouseid
WHERE
sys.name = 'Hortus'
AND ud.displayname = 'Filefolders'
AND st.name != 'Hortus'
AND mt.ticker IN ('MSL', 'FFC', 'LHP', 'CQL', 'QCR', 'WCB', 'LFL', 'HCB', 'BR1', 'SFE', 'MFE', 'SSC', 'LFE', 'FSE', 'CQM', 'LCB', 'VCB', 'CQS', 'BRS', 'SSL');
""")
storage_items = [dict(record) for record in storage_records]
data = {"shiporders": ship_orders, "storageitems": storage_items}
return JSONResponse(content={"success": True, "data": data})
except HTTPException:
raise
except Exception as e:
logger.error(f"Failed to fetch ship production data: {e}", exc_info=True)
return JSONResponse(
status_code=500,
content={
"success": False,
"message": f"Failed to retrieve ship production data: {e}",
},
)
@data_router.get("/planet_shipments")
async def get_shipments(request: Request, planetId: str):
"""
Fetches shipments from the database based on a planet ID.
Args:
request: The FastAPI request object.
planetId: The ID of the planet to filter by.
"""
try:
# Get the database pool from the request state (assuming middleware setup)
pool = request.app.state.db.pool
if not pool:
return JSONResponse(
status_code=500,
content={"success": False, "message": "Database pool not configured."},
)
# Acquire a connection from the pool
async with pool.acquire() as conn:
# Query the database for shipments on the specified planetId
records = await conn.fetch(
"SELECT * FROM planet_shipments WHERE planetid = $1 ORDER BY id",
planetId,
)
# Convert the asyncpg.Record objects to a list of dictionaries
shipments = [dict(record) for record in records]
return JSONResponse(content={"success": True, "data": shipments})
except asyncpg.exceptions.PostgresError as e:
logger.error(f"PostgreSQL error when fetching shipments: {e}", exc_info=True)
return JSONResponse(
status_code=500,
content={"success": False, "message": "A database error occurred."},
)
except Exception as e:
logger.error(f"Failed to fetch shipments: {e}", exc_info=True)
return JSONResponse(
status_code=500,
content={"success": False, "message": "An unexpected error occurred."},
)
@data_router.post("/create_vendor_store")
async def create_vendor_store(
payload: Dict[str, Any],
request: Request,
user_id: str = Depends(get_current_user_id),
):
"""
Creates a new vendor store and its associated orders in a single transaction.
Returns the created vendor store object.
"""
try:
pool = request.app.state.db.pool
vendor_data = payload.get("vendor_data", {})
orders_data = payload.get("materials", [])
vendor_id = str(uuid.uuid4())
# Extract vendor details
company_name = vendor_data.get("companyname")
game_name = vendor_data.get("gamename")
company_code = vendor_data.get("companycode")
corp_name = vendor_data.get("corpname")
is_active = vendor_data.get("isactive", True)
cx = vendor_data.get("cx")
required_fields = {
"Company Name": company_name,
"Game Name": game_name,
"Company Code": company_code,
"CX": cx,
}
for name, value in required_fields.items():
if isinstance(value, str):
cleaned_value = value.strip()
else:
cleaned_value = value
if not cleaned_value:
return JSONResponse(
status_code=400,
content={
"success": False,
"message": f"Vendor {name} is required.",
},
)
company_name = company_name.strip() if company_name else None
game_name = game_name.strip() if game_name else None
company_code = company_code.strip() if company_code else None
corp_name = corp_name.strip() if corp_name else None
cx = cx.strip() if cx else None
async with pool.acquire() as conn:
async with conn.transaction():
vendor_query = """
INSERT INTO user_vendors (
vendorid, userid, companyname, gamename, companycode, isactive, corpname, cx
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8
);
"""
try:
await conn.execute(
vendor_query,
vendor_id,
user_id,
company_name,
game_name,
company_code,
is_active,
corp_name,
cx,
)
except Exception as e:
logger.error(f"Failed on inserting vendorData: {e}.")
raise
order_records = []
created_orders = []
for order in orders_data:
order_id = str(uuid.uuid4())
fixed_price = order.get("fixedprice")
reserved_quantity = order.get("reserved")
material_id = order.get("materialid")
ticker = order.get("ticker")
order_type = order.get("orderType")
# Tuple for batch insertion
order_records.append(
(
order_id,
vendor_id,
material_id,
ticker,
order_type,
fixed_price,
reserved_quantity,
)
)
created_orders.append(
{
"orderid": order_id,
"vendorid": vendor_id,
"materialid": material_id,
"materialticker": ticker,
"ordertype": order_type,
"fixedprice": fixed_price,
"reserved": reserved_quantity,
}
)
orders_query = """
INSERT INTO user_vendor_orders (
orderid, vendorid, materialid, materialticker, ordertype, fixedprice, reserved
) VALUES (
$1, $2, $3, $4, $5, $6, $7
);
"""
try:
if order_records:
await conn.executemany(orders_query, order_records)
except Exception as e:
logger.error(f"Failed to insert orders: {e}")
raise
response_vendor = {
"vendorid": vendor_id,
"userid": user_id,
"companyname": company_name,
"gamename": game_name,
"companycode": company_code,
"isactive": is_active,
"corpname": corp_name,
"cx": cx,
}
return JSONResponse(
content={
"success": True,
"message": "Vendor store and orders created.",
"vendor_store": {
"vendor": response_vendor,
"orders": created_orders,
},
}
)
except asyncpg.UniqueViolationError:
logger.warning(f"Attempt to create a second vendor store for user '{user_id}'.")
return JSONResponse(
status_code=409,
content={
"success": False,
"message": "A vendor store already exists for this user.",
},
)
except Exception as e:
logger.error(
f"Failed to create vendor store and orders for user '{user_id}': {e}",
exc_info=True,
)
return JSONResponse(
status_code=500,
content={
"success": False,
"message": "An unexpected server error occurred.",
},
)
def serialize_record(record):
# This helper function converts non-JSON serializable objects
return {
key: value.isoformat() if isinstance(value, datetime) else float(value) if isinstance(value, Decimal) else value
for key, value in record.items()
}
@data_router.get("/user_vendor_store")
async def get_user_vendor_stores(request: Request, user_id: str = Depends(get_current_user_id)):
try:
pool = request.app.state.db.pool
async with pool.acquire() as conn:
# Step 1: Fetch vendor
vendor_record = await conn.fetchrow(
"SELECT vendorid, companycode, companyname, corpname, cx, gamename, isactive FROM user_vendors WHERE userid = $1;",
user_id,
)
if not vendor_record:
return JSONResponse(
status_code=404,
content={"success": False, "message": "No vendor store found."},
)
# Step 2: Fetch Inventory (Optimized)
inventory_records = await conn.fetch(
"""
SELECT
si.materialid,
m.ticker,
COALESCE(st.stationid, pl_site.planetid, pl_w.planetid)::text AS location_id,
COALESCE(st.name, pl_site.name, pl_w.name)::text AS location_name,
COALESCE(st.naturalid, pl_site.naturalid, pl_w.naturalid)::text AS location_code,
COALESCE(SUM(si.quantity), 0) AS available
FROM storages s
JOIN storage_items si ON si.storageid = s.storageid
LEFT JOIN materials m ON m.materialid = si.materialid
LEFT JOIN warehouses w ON w.storeid = s.storageid AND s.type = 'WAREHOUSE_STORE'
LEFT JOIN stations st ON st.warehouseid = w.warehouseid
LEFT JOIN sites site ON site.siteid = s.addressableid AND s.type = 'STORE'
LEFT JOIN planets pl_site ON pl_site.planetid = site.addressplanetid
LEFT JOIN planets pl_w ON pl_w.planetid = w.addressplanet
WHERE s.userid = (SELECT userdataid FROM users WHERE accountid = $1 LIMIT 1)
AND s.type IN ('STORE', 'WAREHOUSE_STORE')
-- ADD THIS LINE TO FILTER OUT SHIPMENTS
AND si.type = 'INVENTORY'
GROUP BY
si.materialid,
m.ticker,
location_id,
location_name,
location_code;
""",
user_id,
)
inventory_map = {
(r["ticker"], r["location_id"]): float(r["available"]) for r in inventory_records if r["location_id"]
}
# Step 3: Fetch Orders
orders_records = await conn.fetch(
"""
SELECT
uvo.orderid, uvo.materialticker, uvo.ordertype, uvo.fixedprice, uvo.reserved, uvo.materialid,
COALESCE(uvo.location, '[]'::jsonb) AS locations,
mp.price AS corpprice,
CASE WHEN uvo.ordertype = 'buy' THEN cxb.askprice ELSE cxb.bidprice END AS cxprice
FROM user_vendor_orders AS uvo
LEFT JOIN material_prices AS mp ON mp.ticker = uvo.materialticker
LEFT JOIN cx_brokers AS cxb ON cxb.ticker = (uvo.materialticker || '.' || $2)
WHERE uvo.vendorid = $1;
""",
vendor_record["vendorid"],
vendor_record["cx"],
)
# --- LOCATION LOOKUP START ---
import json
all_location_ids = set()
parsed_orders = []
# 3a. Extract IDs
for r in orders_records:
r_dict = dict(r)
raw = r_dict["locations"]
locs = []
if raw:
locs = json.loads(raw) if isinstance(raw, str) else raw
r_dict["parsed_locs"] = locs
parsed_orders.append(r_dict)
for l in locs:
if "id" in l:
all_location_ids.add(l["id"])
# 3b. Fetch Details
loc_lookup = {}
if all_location_ids:
loc_rows = await conn.fetch(
"""
SELECT stationid::text as id, name, naturalid FROM stations WHERE stationid::text = ANY($1)
UNION ALL
SELECT planetid::text as id, name, naturalid FROM planets WHERE planetid::text = ANY($1)
""",
list(all_location_ids),
)
for row in loc_rows:
loc_lookup[row["id"]] = {
"name": row["name"],
"code": row["naturalid"],
}
# --- LOCATION LOOKUP END ---
# Step 4: Construct Response
orders_list = []
for r in parsed_orders:
final_locations = []
total_in_store = 0
for loc in r["parsed_locs"]:
lid = loc.get("id")
details = loc_lookup.get(lid)
# Storage injection
storage_qty = inventory_map.get((r["materialticker"], lid), 0.0)
total_in_store += storage_qty
final_locations.append(
{
"id": lid,
"amount": loc.get("amount", 0),
"location_name": details["name"] if details else "Unknown", # Added
"location_code": details["code"] if details else "???", # Added
"storage_amount": storage_qty,
}
)
orders_list.append(
{
"orderid": str(r["orderid"]),
"materialid": r["materialid"],
"materialticker": r["materialticker"],
"ordertype": r["ordertype"],
"reserved": int(r["reserved"]) if r["reserved"] else 0,
"location": final_locations,
"quantity": total_in_store,
"price": {
"fixedprice": float(r["fixedprice"]) if r["fixedprice"] else 0,
"corpprice": float(r["corpprice"]) if r["corpprice"] else 0,
"cxprice": float(r["cxprice"]) if r["cxprice"] else 0,
},
}
)
return JSONResponse(
content={
"success": True,
"data": {"vendor": dict(vendor_record), "orders": orders_list},
}
)
except Exception as e:
logger.error(f"Failed user vendor fetch: {e}", exc_info=True)
return JSONResponse(status_code=500, content={"success": False, "message": "Server error."})
@data_router.get("/vendor_stores")
async def get_vendor_stores(request: Request):
try:
from endpoints.Public.repositories.vendors_repo import fetch_public_vendors
vendors_data = await fetch_public_vendors(request.app.state.db)
return JSONResponse(
status_code=200,
content={"success": True, "vendors": vendors_data},
)
except Exception as e:
logger.error(f"Failed to fetch vendor stores: {e}", exc_info=True)
return JSONResponse(status_code=500, content={"success": False, "message": "Server error."})
except Exception as e:
logger.error(f"Failed to get vendor stores: {e}", exc_info=True)
return JSONResponse(status_code=500, content={"success": False, "message": "Server error."})
@data_router.post("/materials_price_list")
async def get_materials_price_list(
payload: Dict[str, Any],
request: Request,
user_id: str = Depends(get_current_user_id),
):
try:
pool = request.app.state.db.pool
cx = payload.get("cx", None)
if not cx:
raise HTTPException(
status_code=400,
detail={
"success": False,
"message": "The 'cx' field is required in the request payload.",
},
)
current_user_id_str = str(user_id)
query_materials = """
SELECT
mt.ticker,
mt.materialid,
mp.price AS corpprice
FROM
cx_brokers AS cxb
INNER JOIN
materials AS mt ON mt.materialid = cxb.materialid
INNER JOIN
material_prices AS mp ON mp.ticker = mt.ticker