-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1488 lines (1226 loc) · 70.7 KB
/
main.py
File metadata and controls
executable file
·1488 lines (1226 loc) · 70.7 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
#!/usr/bin/env python3
"""
NovaBoard Electronics Production Scheduling Agent
Step 1: Read Sales Orders from Arke API
Step 2: Choose Planning Policy
"""
from src.api.client import ArkeAPIClient
from src.models.order import SalesOrderLine
from src.scheduler.planner import ProductionPlanner
from src.messaging.notifier import ScheduleNotifier
from src.messaging.command_mapper import CommandMapper
import json
import os
import time
import requests
def main():
"""Main entry point for the scheduling agent"""
print("=" * 60)
print("NovaBoard Electronics - Production Scheduling Agent")
print("=" * 60)
print()
# Load Telegram credentials (needed for interactive prompts)
telegram_bot_token = os.getenv("TELEGRAM_BOT_TOKEN", "")
telegram_chat_id = os.getenv("TELEGRAM_CHAT_ID", "")
notifier = ScheduleNotifier()
# Initialize Gemini AI command mapper for natural language interpretation
gemini_api_key = os.getenv("GEMINI_API_KEY", "")
command_mapper = CommandMapper(api_key=gemini_api_key)
# Step 1: Initialize API client
print("Step 1: Initializing Arke API client...")
try:
client = ArkeAPIClient()
print("API client initialized successfully")
except ValueError as e:
print(f"Error: {e}")
print("\nPlease ensure you have:")
print("1. Copied .env.example to .env")
print("2. Filled in your API credentials in .env")
return
print()
# Step 2: Fetch accepted sales orders
print("Step 2: Fetching accepted sales orders...")
try:
sales_orders = client.get_sales_orders(status="accepted")
print(f"Successfully retrieved {len(sales_orders)} sales orders")
print()
# Fetch detailed information for each order (product and quantity)
print("Step 3: Fetching order details (products and quantities)...")
orders_with_details = []
for order in sales_orders:
order_id = order.get('id')
try:
details = client.get_sales_order_details(order_id)
order['details'] = details
orders_with_details.append(order)
except Exception as e:
print(f"Warning: Could not fetch details for {order.get('internal_id')}: {e}")
orders_with_details.append(order)
print(f"Successfully retrieved details for {len(orders_with_details)} orders")
print()
# Display complete order summary
print("=" * 80)
print("SALES ORDER SUMMARY (Sorted by Urgency - Earliest Deadline First)")
print("=" * 80)
# Sort by deadline
sorted_orders = sorted(orders_with_details, key=lambda x: x.get('expected_shipping_time', ''))
for i, order in enumerate(sorted_orders, 1):
internal_id = order.get('internal_id', 'N/A')
customer = order.get('customer_attr', {}).get('name', 'Unknown')
deadline = order.get('expected_shipping_time', 'N/A')[:16].replace('T', ' ')
priority = order.get('priority', 'N/A')
print(f"\n{i}. Order: {internal_id}")
print(f" Customer: {customer}")
print(f" Deadline: {deadline}")
print(f" Priority: P{priority}")
# Extract product and quantity from order details
if 'details' in order and order['details']:
products = order['details'].get('products', [])
if products:
print(f" Products:")
for item in products:
product_name = item.get('name', 'Unknown Product')
product_id = item.get('extra_id', 'N/A')
quantity = item.get('quantity', 'N/A')
print(f" - {product_name} (ID: {product_id}): {quantity} units")
else:
print(f" Products: No products found")
else:
print(f" Products: Details not available")
print()
print("=" * 80)
print()
# Analyze for conflicts
print("=" * 60)
print("CONFLICT ANALYSIS:")
print("=" * 60)
print()
# Sort orders by deadline (EDF - Earliest Deadline First)
sorted_by_deadline = sorted(sales_orders, key=lambda x: x.get('expected_shipping_time', ''))
# Sort orders by priority (higher priority first)
sorted_by_priority = sorted(sales_orders, key=lambda x: x.get('priority', 999))
print("Orders sorted by DEADLINE (EDF Strategy):")
print("-" * 60)
for i, order in enumerate(sorted_by_deadline[:5], 1):
customer = order.get('customer_attr', {}).get('name', 'Unknown')
deadline = order.get('expected_shipping_time', 'N/A')[:16].replace('T', ' ') # Date and time
priority = order.get('priority', 'N/A')
internal_id = order.get('internal_id', 'N/A')
print(f"{i}. {internal_id} - {customer}")
print(f" Deadline: {deadline}, Priority: P{priority}")
print()
print("Orders sorted by PRIORITY (Traditional Strategy):")
print("-" * 60)
for i, order in enumerate(sorted_by_priority[:5], 1):
customer = order.get('customer_attr', {}).get('name', 'Unknown')
deadline = order.get('expected_shipping_time', 'N/A')[:16].replace('T', ' ') # Date and time
priority = order.get('priority', 'N/A')
internal_id = order.get('internal_id', 'N/A')
print(f"{i}. {internal_id} - {customer}")
print(f" Deadline: {deadline}, Priority: P{priority}")
# Identify specific conflicts where priority and deadline disagree
print()
print("SCHEDULING CONFLICTS DETECTED:")
print("-" * 60)
conflicts_found = False
for i, deadline_order in enumerate(sorted_by_deadline):
priority_rank = sorted_by_priority.index(deadline_order)
if abs(i - priority_rank) > 2: # Significant difference in ranking
customer = deadline_order.get('customer_attr', {}).get('name', 'Unknown')
deadline = deadline_order.get('expected_shipping_time', 'N/A')[:16].replace('T', ' ')
priority = deadline_order.get('priority', 'N/A')
internal_id = deadline_order.get('internal_id', 'N/A')
print(f"Conflict: {internal_id} - {customer}")
print(f" Deadline rank: #{i+1}, Priority rank: #{priority_rank+1}")
print(f" Deadline: {deadline}, Priority: P{priority}")
print()
conflicts_found = True
if not conflicts_found:
print("No significant conflicts detected.")
print()
print("RECOMMENDATION:")
print("-" * 60)
print("Use EDF (Earliest Deadline First) scheduling to minimize late deliveries.")
print("This ensures orders are completed by their deadline, regardless of priority.")
# STEP 2: Choose Planning Policy
print()
print("=" * 80)
print("STEP 2: CHOOSE PLANNING POLICY")
print("=" * 80)
print()
print("Available planning policies:")
print("1. Level 1 (REQUIRED) - EDF: One production order per sales order line")
print("2. Level 2 (OPTIONAL) - Group by Product: Merge orders for same product")
print("3. Level 2 (OPTIONAL) - Split in Batches: Cap batch size (e.g., 10 units)")
print()
# Get user choice via Telegram or console
choice = None
batch_size = 10
if telegram_bot_token and telegram_chat_id and 'your_bot_token_here' not in telegram_bot_token:
# Send policy selection prompt to Telegram
policy_prompt = """🏭 *STEP 2: Choose Planning Policy*
Please select a planning policy:
*1.* Level 1 (REQUIRED) - EDF
→ One production order per sales order line
→ Sorted by deadline (earliest first)
*2.* Level 2 (OPTIONAL) - Group by Product
→ Merge orders for same product
→ Reduces machine changeovers
*3.* Level 2 (OPTIONAL) - Split in Batches
→ Cap batch size (e.g., max 10 units)
→ Better for large orders
💬 *Natural Language Supported!*
You can reply with:
• Numbers: *1*, *2*, *3* or *3:15* (with batch size)
• Ordinals: "first", "second", "third" or "1st", "2nd", "3rd"
• Words: "EDF", "group by product", "split in batches"
• Phrases: "earliest deadline first", "merge same products", "batch size 20"
"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, policy_prompt, None, None)
print("\nWaiting for policy selection via Telegram...")
# Wait for response
url = f"https://api.telegram.org/bot{telegram_bot_token}/getUpdates"
start_time = time.time()
last_update_id = None
timeout = 300 # 5 minutes
# Get latest update_id
try:
response = requests.get(url, params={"offset": -1}, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
last_update_id = data["result"][-1]["update_id"]
except Exception as e:
print(f"Warning: Could not get initial update ID: {e}")
while time.time() - start_time < timeout:
try:
params = {}
if last_update_id is not None:
params["offset"] = last_update_id + 1
params["timeout"] = 10
response = requests.get(url, params=params, timeout=15)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
for update in data["result"]:
last_update_id = update["update_id"]
if "message" in update:
msg = update["message"]
if str(msg.get("chat", {}).get("id")) == str(telegram_chat_id):
text = msg.get("text", "").strip()
# Use CommandMapper for natural language interpretation
interpreted_choice, interpreted_batch = command_mapper.interpret_policy(text)
if interpreted_choice in ['1', '2', '3']:
choice = interpreted_choice
if interpreted_batch:
batch_size = interpreted_batch
print(f"✓ Received: '{text}' → Policy {choice} with batch size {batch_size}")
else:
print(f"✓ Received: '{text}' → Policy {choice}")
break
else:
# Not recognized - ask again with the same prompt
print(f"⚠ Could not interpret: '{text}'")
retry_prompt = """❓ *Please select a planning policy*
I didn't understand your response. Please reply with:
*1* - EDF (Earliest Deadline First)
*2* - Group by Product
*3* - Split in Batches
Or use natural language like "first", "group by product", "batch size 20"
"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, retry_prompt, None, None)
if choice:
break
time.sleep(1)
except Exception as e:
print(f"Error polling Telegram: {e}")
time.sleep(2)
if not choice:
print("⚠ Timeout: No response received. Defaulting to Policy 1 (EDF)")
choice = '1'
# If policy 3 was selected without batch size, ask for it via Telegram
if choice == '3' and batch_size == 10: # Default value means not specified
batch_prompt = """📏 *Enter Batch Size*
You selected Policy 3 (Split in Batches).
Please enter the maximum batch size (number).
Example: *15* for max 15 units per batch
Or reply *10* to use the default."""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, batch_prompt, None, None)
print("\nWaiting for batch size via Telegram...")
url = f"https://api.telegram.org/bot{telegram_bot_token}/getUpdates"
start_time = time.time()
batch_received = False
timeout = 300
# Get latest update_id
try:
response = requests.get(url, params={"offset": -1}, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
last_update_id = data["result"][-1]["update_id"]
except Exception as e:
print(f"Warning: Could not get initial update ID: {e}")
while time.time() - start_time < timeout:
try:
params = {}
if last_update_id is not None:
params["offset"] = last_update_id + 1
params["timeout"] = 10
response = requests.get(url, params=params, timeout=15)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
for update in data["result"]:
last_update_id = update["update_id"]
if "message" in update:
msg = update["message"]
if str(msg.get("chat", {}).get("id")) == str(telegram_chat_id):
text = msg.get("text", "").strip()
if text.isdigit():
batch_size = int(text)
print(f"✓ Received batch size: {batch_size}")
batch_received = True
break
if batch_received:
break
time.sleep(1)
except Exception as e:
print(f"Error polling Telegram: {e}")
time.sleep(2)
if not batch_received:
print("⚠ Timeout: Using default batch size of 10")
batch_size = 10
else:
# Console input fallback
while True:
choice = input("Select planning policy (1, 2, or 3): ").strip()
if choice in ['1', '2', '3']:
break
print("Invalid choice. Please enter 1, 2, or 3.")
if choice == '3':
batch_input = input("Enter maximum batch size (default 10): ").strip()
batch_size = int(batch_input) if batch_input.isdigit() else 10
# Extract sales order lines from the detailed orders
sales_order_lines = []
for order in orders_with_details:
if 'details' in order and order['details']:
products = order['details'].get('products', [])
for item in products:
try:
line = SalesOrderLine.from_api_response(order, item)
sales_order_lines.append(line)
except Exception as e:
print(f"Warning: Could not parse product line: {e}")
import traceback
traceback.print_exc()
print(f"\nTotal sales order lines to plan: {len(sales_order_lines)}")
print()
# Apply selected planning policy
planner = ProductionPlanner()
policy_name = "" # Track which policy was selected
if choice == '1':
print("Applying LEVEL 1: EDF (Earliest Deadline First)")
print("One production order per sales order line, sorted by deadline")
print()
production_orders = planner.level1_edf(sales_order_lines)
planner.display_production_plan(production_orders, "Level 1: EDF")
policy_name = "EDF (Earliest Deadline First)"
elif choice == '2':
print("Applying LEVEL 2: Group by Product")
print("Merging orders with the same product to reduce changeovers")
print()
production_orders = planner.level2_group_by_product(sales_order_lines)
planner.display_production_plan(production_orders, "Level 2: Group by Product")
policy_name = "Group by Product"
elif choice == '3':
# batch_size already obtained via Telegram or console earlier
print(f"\nApplying LEVEL 2: Split in Batches (max {batch_size} units)")
print("Splitting large orders into smaller batches")
print()
production_orders = planner.level2_split_batches(sales_order_lines, batch_size)
planner.display_production_plan(production_orders, f"Level 2: Split in Batches (max {batch_size})")
policy_name = f"Split in Batches (max {batch_size} units)"
# Store production orders for next steps
print()
print("=" * 80)
print("STEP 2 COMPLETE")
print("=" * 80)
print(f"Generated {len(production_orders)} production orders using the selected policy.")
print()
# STEP 3: Create Production Orders in Arke
print("=" * 80)
print("STEP 3: CREATE PRODUCTION ORDERS IN ARKE")
print("=" * 80)
print()
# First, fetch all products to map names to IDs
print("Fetching product catalog...")
try:
products_catalog = client.get_products()
print(f"Found {len(products_catalog)} products in catalog")
# Map by internal_id (which matches the product names in sales orders)
product_map_by_internal_id = {p.get('internal_id', ''): p.get('id', '') for p in products_catalog}
product_map = {p.get('name', ''): p.get('id', '') for p in products_catalog}
product_map_by_extra = {p.get('extra_id', ''): p.get('id', '') for p in products_catalog}
print()
except Exception as e:
print(f"Error fetching products: {e}")
print("Will attempt to create production orders with available product info")
product_map = {}
product_map_by_extra = {}
print()
# Confirm with user before creating (via Telegram or console)
confirm = None
if telegram_bot_token and telegram_chat_id and 'your_bot_token_here' not in telegram_bot_token:
# Send confirmation prompt to Telegram
confirmation_prompt = f"""📦 *STEP 3: Create Production Orders*
Ready to create *{len(production_orders)}* production orders in Arke.
💬 *Natural Language Supported!*
You can reply with:
• *YES*, "sure", "go ahead", "confirm", "ok", "proceed"
• *NO*, "cancel", "stop", "nope", "abort"
"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, confirmation_prompt, None, None)
print(f"\nWaiting for confirmation via Telegram to create {len(production_orders)} orders...")
# Wait for response
url = f"https://api.telegram.org/bot{telegram_bot_token}/getUpdates"
start_time = time.time()
last_update_id = None
timeout = 300 # 5 minutes
# Get latest update_id
try:
response = requests.get(url, params={"offset": -1}, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
last_update_id = data["result"][-1]["update_id"]
except Exception as e:
print(f"Warning: Could not get initial update ID: {e}")
while time.time() - start_time < timeout:
try:
params = {}
if last_update_id is not None:
params["offset"] = last_update_id + 1
params["timeout"] = 10
response = requests.get(url, params=params, timeout=15)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
for update in data["result"]:
last_update_id = update["update_id"]
if "message" in update:
msg = update["message"]
if str(msg.get("chat", {}).get("id")) == str(telegram_chat_id):
text = msg.get("text", "").strip()
# Use CommandMapper for natural language interpretation
interpreted = command_mapper.interpret_confirmation(text)
if interpreted == "YES":
confirm = 'yes'
print(f"✓ Received: '{text}' → YES (Creating production orders)")
break
elif interpreted == "NO":
confirm = 'no'
print(f"✗ Received: '{text}' → NO (Cancelled)")
break
else:
# Not recognized - ask again
print(f"⚠ Could not interpret: '{text}'")
retry_prompt = """❓ *Please confirm*
I didn't understand your response. Please reply with:
• *YES* to create the orders
• *NO* to cancel"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, retry_prompt, None, None)
if confirm:
break
time.sleep(1)
except Exception as e:
print(f"Error polling Telegram: {e}")
time.sleep(2)
if not confirm:
print("⚠ Timeout: No response received. Cancelling production order creation.")
confirm = 'no'
else:
# Console input fallback
confirm = input(f"Create {len(production_orders)} production orders in Arke? (yes/no): ").strip().lower()
if confirm not in ['yes', 'y']:
print("Production order creation cancelled.")
return
print()
print("Creating production orders...")
from datetime import datetime, timezone, timedelta
created_orders = []
failed_orders = []
# Track the cumulative end time for sequential scheduling
current_start_time = datetime.now(timezone.utc)
for i, prod_order in enumerate(production_orders, 1):
try:
# Look up actual product ID from catalog
# Try internal_id first (matches product name from sales order), then name, then extra_id
product_id = (product_map_by_internal_id.get(prod_order.product_name) or
product_map_by_internal_id.get(prod_order.product_id) or
product_map.get(prod_order.product_name) or
product_map_by_extra.get(prod_order.product_id) or
prod_order.product_id)
if not product_id:
print(f" {i}/{len(production_orders)}: SKIPPED - No product ID for {prod_order.product_name}")
failed_orders.append(prod_order)
continue
# Prepare API payload with sequential start times
# Calculate estimated production end time (API will provide actual duration)
# Estimate: ~9 minutes per unit minimum 1 hour
estimated_duration_hours = max(1, prod_order.quantity * 0.15)
estimated_end_time = current_start_time + timedelta(hours=estimated_duration_hours)
payload = {
"product_id": product_id,
"quantity": prod_order.quantity,
"starts_at": current_start_time.isoformat(),
"ends_at": estimated_end_time.isoformat()
}
# Create production order
response = client.create_production_order(payload)
created_orders.append((prod_order, response))
order_id = response.get('id', 'Unknown')
print(f" {i}/{len(production_orders)}: Created - {prod_order.product_name} x{prod_order.quantity} (ID: {order_id})")
# Update start time for next order (sequential scheduling)
# The next order should start when this one ends
duration_minutes = response.get('duration')
if duration_minutes is None:
raise Exception(f"API did not return duration for order {order_id}. Cannot schedule sequentially.")
# Calculate actual production end time
production_end_time = current_start_time + timedelta(minutes=duration_minutes)
# Next order starts when this one ends
current_start_time = production_end_time
except Exception as e:
print(f" {i}/{len(production_orders)}: FAILED - {prod_order.product_name}: {str(e)[:50]}")
failed_orders.append(prod_order)
print()
print("=" * 80)
print("STEP 3 COMPLETE")
print("=" * 80)
print(f"Successfully created: {len(created_orders)}/{len(production_orders)} production orders")
if failed_orders:
print(f"Failed: {len(failed_orders)} orders")
print()
# STEP 4: Schedule Production Phases
scheduled_orders = []
if len(created_orders) > 0:
print("=" * 80)
print("STEP 4: SCHEDULE PRODUCTION PHASES")
print("=" * 80)
print()
print("Generating phase sequences for production orders...")
# Track sequential timing across all production orders
# Constraint: 480 minutes (8 hours) workday from 9 AM to 5 PM
WORKDAY_MINUTES = 480
WORKDAY_START_HOUR = 9 # 9 AM
WORKDAY_END_HOUR = 17 # 5 PM
# Start scheduling from next available workday slot
now = datetime.now(timezone.utc)
if now.hour < WORKDAY_START_HOUR:
# Before work starts today - start at 9 AM today
next_phase_start = now.replace(hour=WORKDAY_START_HOUR, minute=0, second=0, microsecond=0)
elif now.hour >= WORKDAY_END_HOUR:
# After work ends today - start at 9 AM tomorrow
tomorrow = now + timedelta(days=1)
next_phase_start = tomorrow.replace(hour=WORKDAY_START_HOUR, minute=0, second=0, microsecond=0)
else:
# During work hours - start now
next_phase_start = now
current_day_minutes_used = 0
if WORKDAY_START_HOUR <= now.hour < WORKDAY_END_HOUR:
# Calculate how many minutes already used today
current_day_minutes_used = (now.hour - WORKDAY_START_HOUR) * 60 + now.minute
def schedule_with_workday_constraint(start_time, duration_minutes, day_minutes_used):
"""
Schedule a phase respecting 8-hour workday (9 AM - 5 PM).
Work stops at 5 PM and resumes at 9 AM next day.
Uses partial days - if work doesn't fit in remaining time,
it starts today and continues tomorrow.
"""
phase_start = start_time
remaining_duration = duration_minutes
# Calculate end time accounting for workday breaks (9 AM - 5 PM)
current_time = phase_start
current_day_used = day_minutes_used
while remaining_duration > 0:
available_today = WORKDAY_MINUTES - current_day_used
if remaining_duration <= available_today:
# Phase completes today
current_time = current_time + timedelta(minutes=remaining_duration)
current_day_used += remaining_duration
remaining_duration = 0
else:
# Use remaining time today, continue tomorrow at 9 AM
remaining_duration -= available_today
# Move to next workday at 9 AM
next_day = current_time + timedelta(days=1)
current_time = next_day.replace(hour=WORKDAY_START_HOUR, minute=0, second=0, microsecond=0)
current_day_used = 0
phase_end = current_time
new_day_minutes = current_day_used
return phase_start, phase_end, new_day_minutes
for i, (prod_order, response) in enumerate(created_orders, 1):
order_id = response.get('id')
try:
# Generate phase sequence from BOM
scheduled_response = client.schedule_production_order(order_id)
# Get total duration from production order response (not from summing phases)
base_duration = scheduled_response.get('duration', 0)
quantity = prod_order.quantity
# WORKAROUND: API returns duration per batch (not scaled by quantity)
# Multiply by quantity to get realistic total production time
total_duration = base_duration * quantity
phases = scheduled_response.get('phases', [])
print(f" Base duration: {base_duration} min × {quantity} units = {total_duration} minutes ({len(phases)} phases)")
# Apply workday constraint to get production start/end times
production_start, production_end, current_day_minutes_used = schedule_with_workday_constraint(
next_phase_start, total_duration, current_day_minutes_used
)
# Update production order dates (API will reschedule phases accordingly)
print(f" → Setting: {production_start.strftime('%Y-%m-%d %H:%M')} to {production_end.strftime('%Y-%m-%d %H:%M')}")
try:
client.update_production_start_date(order_id, production_start.isoformat())
client.update_production_end_date(order_id, production_end.isoformat())
# Fetch updated production order
scheduled_response = client.get_production_order(order_id)
actual_start = scheduled_response.get('starts_at', 'N/A')[:16].replace('T', ' ')
actual_end = scheduled_response.get('ends_at', 'N/A')[:16].replace('T', ' ')
print(f" ✓ API returned: {actual_start} to {actual_end}")
except Exception as update_error:
print(f" ⚠ Warning: Could not update API dates: {update_error}")
scheduled_response = client.get_production_order(order_id)
# Override API times with our calculated sequential times
scheduled_response['starts_at'] = production_start.isoformat()
scheduled_response['ends_at'] = production_end.isoformat()
scheduled_response['duration'] = total_duration # Store our calculated duration
# Next order starts when this one ends
next_phase_start = production_end
scheduled_orders.append((prod_order, scheduled_response))
print(f" ✓ Using calculated times: {production_start.strftime('%Y-%m-%d %H:%M')} to {production_end.strftime('%Y-%m-%d %H:%M')}")
print(f" {i}/{len(created_orders)}: Scheduled - {prod_order.product_name} (ID: {order_id})")
except Exception as e:
print(f" {i}/{len(created_orders)}: Failed to schedule {order_id}: {e}")
print()
print("=" * 80)
print("STEP 4 COMPLETE")
print("=" * 80)
print(f"Successfully scheduled: {len(scheduled_orders)}/{len(created_orders)} production orders")
print()
# Validate deadlines are met
print("=" * 80)
print("DEADLINE VALIDATION")
print("=" * 80)
print()
late_orders = []
on_time_orders = []
for prod_order, scheduled_response in scheduled_orders:
production_end = scheduled_response.get('ends_at')
customer_deadline = prod_order.ends_at.isoformat()
if production_end and production_end > customer_deadline:
late_orders.append((prod_order, scheduled_response, production_end, customer_deadline))
else:
on_time_orders.append((prod_order, scheduled_response))
print(f"✓ On-time orders: {len(on_time_orders)}/{len(scheduled_orders)}")
if late_orders:
print(f"⚠ LATE orders: {len(late_orders)}/{len(scheduled_orders)}")
print()
print("Orders that will miss their deadline:")
for prod_order, scheduled_response, prod_end, deadline in late_orders:
from datetime import datetime
prod_end_dt = datetime.fromisoformat(prod_end.replace('Z', '+00:00'))
deadline_dt = datetime.fromisoformat(deadline.replace('Z', '+00:00'))
delay_hours = (prod_end_dt - deadline_dt).total_seconds() / 3600
print(f" - {prod_order.product_name} (Order: {', '.join(prod_order.source_sales_orders)})")
print(f" Production ends: {prod_end[:16].replace('T', ' ')}")
print(f" Customer deadline: {deadline[:16].replace('T', ' ')}")
print(f" Delay: {delay_hours:.1f} hours")
print()
else:
print("✓ All orders will be completed before their deadlines!")
print()
# STEP 5: Human in the Loop - Present Schedule for Approval
if len(scheduled_orders) > 0:
print("=" * 80)
print("STEP 5: HUMAN IN THE LOOP - SCHEDULE APPROVAL")
print("=" * 80)
print()
# Loop until schedule is approved
approved = False
while not approved:
# Format and display schedule
notifier.print_schedule(production_orders, scheduled_orders)
# Send to Telegram and wait for approval
approval = None
rejection_reason = None
if telegram_bot_token and telegram_chat_id and 'your_bot_token_here' not in telegram_bot_token:
message, scheduled_orders = notifier.format_schedule_message(production_orders, scheduled_orders, policy_name)
fig = ScheduleNotifier.build_gantt_chart(scheduled_orders, policy_name)
print("\nSending schedule to Telegram...")
if notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, message, scheduled_orders, fig):
# Wait for approval via Telegram
approval, rejection_reason = notifier.wait_for_telegram_approval(telegram_bot_token, telegram_chat_id, command_mapper)
if approval == "TIMEOUT":
print("\nFalling back to terminal input...")
approval = None
# Fallback to terminal input if Telegram not configured or timed out
if approval is None:
print()
user_input = input("Planner approval (APPROVE/REJECT): ").strip().upper()
if user_input.startswith("REJECT"):
approval = "REJECT"
rejection_reason = input("Reason for rejection: ").strip()
else:
approval = user_input
if approval == "APPROVE":
approved = True # Break the loop
print()
print("Confirming production orders...")
print()
confirmed_count = 0
for prod_order, scheduled_response in scheduled_orders:
order_id = scheduled_response.get('id')
try:
confirm_response = client.confirm_production_order(order_id)
if confirm_response.get('status') == 'in_progress':
print(f" ✓ Confirmed: {prod_order.product_name} (ID: {order_id}) → IN_PROGRESS")
confirmed_count += 1
else:
print(f" → {prod_order.product_name} (ID: {order_id}) - {confirm_response.get('status', 'scheduled')}")
except Exception as e:
print(f" ✗ Failed to confirm {order_id}: {e}")
print()
print("=" * 80)
print("STEP 5 COMPLETE")
print("=" * 80)
print(f"Production schedule APPROVED!")
if confirmed_count > 0:
print(f"✓ Confirmed: {confirmed_count}/{len(scheduled_orders)} orders moved to IN_PROGRESS")
print(" First phase is now READY TO START for confirmed orders")
else:
print(f"⚠ Note: _confirm endpoint not available on this API instance")
print(f" All {len(scheduled_orders)} orders remain in SCHEDULED status")
print(f" Orders are ready - phases can be started manually when needed")
print()
print("=" * 60)
print("SUMMARY:")
print(f" Total Production Orders: {len(scheduled_orders)}")
print(f" Total Phases Created: {len(scheduled_orders) * 7}")
print(f" Status: {'IN_PROGRESS' if confirmed_count > 0 else 'SCHEDULED'}")
print(f" Ready for: Step 6-7 (Physical Integration)")
print("=" * 60)
print()
# STEP 6: Physical Integration - Camera Monitoring
print("\n" + "=" * 80)
print("STEP 6: PHYSICAL INTEGRATION - PRODUCTION LINE MONITORING")
print("=" * 80)
print()
# Ask if user wants to enable camera monitoring (via Telegram or console)
enable_monitoring = None
if telegram_bot_token and telegram_chat_id and 'your_bot_token_here' not in telegram_bot_token:
# Send monitoring prompt to Telegram
monitoring_prompt = """📹 *STEP 6: Production Line Monitoring*
Enable camera monitoring for the production line?
💬 *Natural Language Supported!*
You can reply with:
• *YES*, "sure", "enable", "go ahead", "ok"
• *NO*, "skip", "nope", "disable"
If YES, you'll be asked which camera(s) to use.
💡 *Tip:* Once monitoring starts, send *CAPTURE* anytime to receive photos from all cameras on Telegram!"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, monitoring_prompt, None, None)
print("\nWaiting for camera monitoring decision via Telegram...")
# Wait for response
url = f"https://api.telegram.org/bot{telegram_bot_token}/getUpdates"
start_time = time.time()
last_update_id = None
timeout = 300
# Get latest update_id
try:
response = requests.get(url, params={"offset": -1}, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
last_update_id = data["result"][-1]["update_id"]
except Exception as e:
print(f"Warning: Could not get initial update ID: {e}")
while time.time() - start_time < timeout:
try:
params = {}
if last_update_id is not None:
params["offset"] = last_update_id + 1
params["timeout"] = 10
response = requests.get(url, params=params, timeout=15)
response.raise_for_status()
data = response.json()
if data.get("ok") and data.get("result"):
for update in data["result"]:
last_update_id = update["update_id"]
if "message" in update:
msg = update["message"]
if str(msg.get("chat", {}).get("id")) == str(telegram_chat_id):
text = msg.get("text", "").strip()
# Use CommandMapper for natural language interpretation
interpreted = command_mapper.interpret_confirmation(text)
if interpreted == "YES":
enable_monitoring = 'yes'
print(f"✓ Received: '{text}' → YES (Camera monitoring enabled)")
break
elif interpreted == "NO":
enable_monitoring = 'no'
print(f"✗ Received: '{text}' → NO (Camera monitoring disabled)")
break
else:
# Not recognized - send retry prompt
print(f"⚠ Could not interpret: '{text}'")
retry_prompt = """❓ *Please confirm*
I didn't understand your response. Please reply with:
• *YES* to enable camera monitoring
• *NO* to skip monitoring
Natural language also works:
• "sure", "enable", "go ahead" → YES
• "skip", "nope", "disable" → NO"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, retry_prompt, None, None)
if enable_monitoring:
break
time.sleep(1)
except Exception as e:
print(f"Error polling Telegram: {e}")
time.sleep(2)
if not enable_monitoring:
print("⚠ Timeout: Disabling camera monitoring")
enable_monitoring = 'no'
else:
# Console input fallback
enable_monitoring = input("Enable camera monitoring? (yes/no): ").strip().lower()
if enable_monitoring in ['yes', 'y']:
from src.monitoring.camera import SimpleLineMonitor
# Ask which cameras to use (via Telegram or console)
camera_indices = []
if telegram_bot_token and telegram_chat_id and 'your_bot_token_here' not in telegram_bot_token:
camera_prompt = """📷 *Select Camera(s)*
Which camera(s) would you like to use?
Reply with:
- *0* for camera 0 (default)
- *1* for camera 1
- *2* for camera 2
- *0,1* for multiple cameras (comma-separated)
💬 *Natural Language Supported!*
You can also say:
• "camera 0 and 1"
• "all cameras"
• "first camera"
• "cameras 1 and 2"
Example: *0,1* to use both camera 0 and 1"""
notifier.send_to_telegram(telegram_bot_token, telegram_chat_id, camera_prompt, None, None)
print("Waiting for camera selection via Telegram...")
url = f"https://api.telegram.org/bot{telegram_bot_token}/getUpdates"
start_time = time.time()
timeout = 300
camera_received = False
# Get latest update_id
try:
response = requests.get(url, params={"offset": -1}, timeout=10)
response.raise_for_status()
data = response.json()