summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/sourcing_job_order.py
blob: 0e5334a8950288b6c32afdac82caf263ee2dd6b9 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
from odoo import models, fields, api, _
from odoo.exceptions import UserError
from datetime import date, datetime
import requests
import logging
import pytz
from pytz import timezone
import base64
import xlrd, xlwt
import io

_logger = logging.getLogger(__name__)


class SourcingJobOrder(models.Model):
    _name = 'sourcing.job.order'
    _description = 'Sourcing Job Order MD'
    _rec_name = 'name'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'is_priority desc, state asc, create_date desc'

    name = fields.Char(string='Job Number', default='New', copy=False, readonly=True)
    leads_id = fields.Many2one('crm.lead', string='Leads Number')
    md_user_id = fields.Many2many('res.users', string='MD Persons', compute="_compute_md_persons")
    so_id = fields.Many2one('sale.order', string='SO Number', tracking=True)
    state = fields.Selection([
        ('draft', 'Untaken'),
        ('taken', 'On Sourcing'),
        ('partial', 'Partial Complete'),
        ('done', 'Complete'),
        ('cancel', 'Cancelled')
    ], string='Status', default='draft', tracking=True)
    approval_sales = fields.Selection([
        ('draft', 'Requested'),
        ('approve', 'Approved'),
        ('reject', 'Rejected'),
    ], string='Approval Sales', tracking=True)
    takeover_request = fields.Many2one(
        'res.users',
        string='Takeover Requested By',
        readonly=True,
        tracking=True,
        help='MD yang meminta takeover'
    )
    is_priority = fields.Boolean(
        string="Priority",
        default=False,
        tracking=True,
        help="Otomatis aktif jika request approval ditolak oleh sales."
    )
    eta_sales = fields.Date(string='Expected Ready')
    eta_complete = fields.Date(string='Completed Date')
    cancel_reason = fields.Text(string="Reason for Cancel", tracking=True)
    line_ids = fields.One2many('sourcing.job.order.line', 'order_id', string='Products')
    line_sales_input_ids = fields.One2many(
        'sourcing.job.order.line', 'order_id',
        string='Sales Input Lines',
    )
    line_sales_view_ids = fields.One2many(
        'sourcing.job.order.line', 'order_id',
        string='Sales View Lines',
    )
    converted_product_ids = fields.One2many(
        "product.product",
        "sourcing_job_id",
        string="Converted Products",
        readonly=True,
    )
    converted_product_count = fields.Integer(
        compute="_compute_converted_product_count",
        string="Converted Product Count",
    )
    progress_status = fields.Char(
        string='Progress Status',
        compute='_compute_progress_status',
        default=''
    )

    has_price_in_lines = fields.Boolean(
        string='Has Line with Price',
        compute='_compute_has_price_in_lines',
    )

    def _get_jakarta_today(self):
        jakarta_tz = pytz.timezone('Asia/Jakarta')
        now_jakarta = datetime.now(jakarta_tz)
        return now_jakarta.date()

    @api.depends('eta_sales', 'eta_complete', 'create_date', 'state')
    def _compute_progress_status(self):
        for rec in self:

            if rec.state == 'cancel':
                rec.progress_status = 'โšซ Cancelled'
                continue

            if rec.state == 'done':
                if rec.eta_sales and rec.eta_complete:
                    delta = (rec.eta_complete - rec.eta_sales).days
                    if delta < 0:
                        rec.progress_status = f'๐ŸŸข Early {abs(delta)} hari'
                    elif delta == 0:
                        rec.progress_status = '๐Ÿ”ต Ontime'
                    else:
                        rec.progress_status = f'๐Ÿ”ด Delay {delta} hari'
                elif rec.create_date and rec.eta_complete:
                    durasi = (rec.eta_complete - rec.create_date.date()).days
                    rec.progress_status = f'โœ… Selesai dalam {durasi} hari'
                else:
                    rec.progress_status = 'โœ… Selesai'
                continue

            if rec.state in ['taken', 'partial', 'draft']:
                rec.progress_status = '๐ŸŸก On Track'

    @api.depends('line_ids.price', 'line_ids.vendor_id')
    def _compute_has_price_in_lines(self):
        for rec in self:
            # Cek apakah ada minimal satu line yang sudah punya price > 0 dan vendor_id
            has_price = any(
                (line.price and line.price > 0 and line.vendor_id)
                for line in rec.line_ids
            )
            rec.has_price_in_lines = bool(has_price)

    @api.depends('line_ids.md_person_ids')
    def _compute_md_persons(self):
        for rec in self:
            md_users = rec.line_ids.mapped('md_person_ids').filtered(lambda x: x)
            rec.md_user_id = [(6, 0, md_users.ids)]

    @api.depends("converted_product_ids")
    def _compute_converted_product_count(self):
        for rec in self:
            rec.converted_product_count = len(rec.converted_product_ids)

    @api.model
    def create(self, vals):
        """Hanya Sales & Merchandiser yang boleh membuat job."""
        if not (self.env.user.has_group('indoteknik_custom.group_role_sales') or
                self.env.user.has_group('indoteknik_custom.group_role_merchandiser')):
            raise UserError("โŒ Hanya Sales dan Merchandiser yang boleh membuat Sourcing Job.")

        if vals.get('name', 'New') == 'New':
            vals['name'] = self.env['ir.sequence'].next_by_code('sourcing.job.order') or 'New'

        rec = super().create(vals)

        return rec
        

    def write(self, vals):
        if self.env.uid != self.create_uid.id and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser'):
            raise UserError("โŒ Hanya Sales dan Merchandiser yang boleh mengedit Sourcing Job.")

        old_data = {}
        for rec in self:
            old_data[rec.id] = {
                'state': rec.state,
                'approval_sales': rec.approval_sales,
                'line_data': {
                    line.id: {
                        'state': line.state,
                        'vendor_id': line.vendor_id.id if line.vendor_id else False,
                        'price': line.price,
                    }
                    for line in rec.line_ids
                },
            }

        res = super().write(vals)
        if vals.get('product_assets'):
            for rec in self:
                rec._log_product_assets_upload()

        for rec in self:
            changes = []
            old = old_data.get(rec.id, {})

            if old.get('state') != rec.state:
                changes.append(f"State: <b>{old.get('state')}</b> โ†’ <b>{rec.state}</b>")
            if old.get('approval_sales') != rec.approval_sales:
                changes.append(f"Approval Status: <b>{old.get('approval_sales')}</b> โ†’ <b>{rec.approval_sales}</b>")

            old_lines = old.get('line_data', {})
            for line in rec.line_ids:
                old_line = old_lines.get(line.id)
                if not old_line:
                    continue  

                if (
                    old_line['vendor_id'] != (line.vendor_id.id if line.vendor_id else False)
                    and old_line['price'] == line.price
                ):
                    raise UserError(
                        f"โš ๏ธ Harga untuk produk {line.product_name} belum diperbarui setelah mengganti Vendor."
                    )

                sub_changes = []

                if old_line['state'] != line.state:
                    sub_changes.append(f"- state: <b>{old_line['state']}</b> โ†’ <b>{line.state}</b>")

                if old_line['vendor_id'] != (line.vendor_id.id if line.vendor_id else False):
                    old_vendor = self.env['res.partner'].browse(old_line['vendor_id']).name if old_line['vendor_id'] else '-'
                    sub_changes.append(f"- vendor: <b>{old_vendor}</b> โ†’ <b>{line.vendor_id.name if line.vendor_id else '-'}</b>")

                if old_line['price'] != line.price:
                    sub_changes.append(f"- price: <b>{old_line['price']}</b> โ†’ <b>{line.price}</b>")

                if sub_changes:
                    joined = "<br/>".join(sub_changes)
                    changes.append(f"<b>{line.product_name}</b>:<br/>{joined}")

            if changes:
                message = "<br/><br/>".join(changes)
                rec.message_post(
                    body=f"Perubahan pada Sourcing Job:<br/>{message}",
                    subtype_xmlid="mail.mt_comment",
                )

        return res

    def action_cancel(self):
        for rec in self:
            if not self.env.user.has_group('indoteknik_custom.group_role_sales'):
                raise UserError("โŒ Hanya Sales yang dapat mengcancel Sourcing Job.")

            if not rec.cancel_reason:
                raise UserError("โš ๏ธ Isi alasan pembatalan terlebih dahulu.")

            rec.write({'state': 'cancel'})
            rec.message_post(body=("Job <b>%s</b> dibatalkan oleh %s<br/>Alasan: %s") %
                                  (rec.name, self.env.user.name, rec.cancel_reason))

    def action_open_converted_products(self):
        """Open converted products related to this SJO."""
        self.ensure_one()
        return {
            'name': 'Converted Products',
            'type': 'ir.actions.act_window',
            'view_mode': 'tree,form',
            'res_model': 'product.product',
            'domain': [('id', 'in', self.converted_product_ids.ids)],
            'context': {'default_sourcing_job_id': self.id},
        }

    def action_open_export_wizard(self):
        self.ensure_one()

        return {
            'type': 'ir.actions.act_window',
            'name': 'Export Produk ke SO',
            'res_model': 'wizard.export.sjo.to.so',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_sjo_id': self.id,
            }
        }


class SourcingJobOrderLine(models.Model):
    _name = 'sourcing.job.order.line'
    _description = 'Sourcing Job Order Line'
    _inherit = ['mail.thread', 'mail.activity.mixin']

    order_id = fields.Many2one('sourcing.job.order', string='Job Order', ondelete='cascade')
    product_id = fields.Many2one('product.product', string='Product', ondelete='cascade')
    md_person_ids = fields.Many2one('res.users', string='MD Person', ondelete='cascade')
    brand_id = fields.Many2one('x_manufactures', string='Manufactures', ondelete='cascade')
    so_id = fields.Many2one('sale.order', string='SO Number', tracking=True, readonly=True)
    product_name_md = fields.Char(string='Nama Barang')
    descriptions_md = fields.Text(string='Deskripsi Barang')

    product_name = fields.Char(string='Nama Barang')
    brand = fields.Char(string='Brand')
    code = fields.Char(string='SKU')
    budget = fields.Char(string='Expected Price')
    note = fields.Text(string='Note Sourcing')
    attachment_type = fields.Selection([
        ('none', 'None'),
        ('pdf', '.PDF'),
        ('img', '.IMG'),
        ('other', 'Lainnya'),
    ], default='none') 
    product_attachment_pdf = fields.Binary(string="Product Attachment")
    product_attachment_img = fields.Binary(string="Product Attachment")
    product_attachment_other = fields.Binary(string="Product Attachment")
    product_attachment_filename = fields.Char(string="Filename")

    descriptions = fields.Text(string='Deskripsi / Spesifikasi')
    reason = fields.Text(string='Reason Unavailable')
    sla = fields.Char(string='SLA Product')
    quantity = fields.Float(string='Quantity Product', required=True)
    price = fields.Float(string='Purchase Price')
    now_price = fields.Float(string='Current Purchase Price', readonly=True)
    last_updated_price = fields.Datetime(string='Last Update Price', readonly=True)
    tax_id = fields.Many2one('account.tax', string='Tax', domain=[('active', '=', True), ('type_tax_use', '=', 'purchase')])
    vendor_id = fields.Many2one('res.partner', string="Vendor")
    product_category = fields.Many2one('product.category', string="Product Category")
    product_class = fields.Many2many('product.public.category', string="Categories")
    exported_to_so = fields.Boolean(string="Exported to SO", default=False)
    state = fields.Selection([
        ('draft', 'Unsource'),
        ('sourcing', 'On Sourcing'),
        ('sent', 'Approval Sent'),
        ('approve', 'Done Sourcing'),
        ('cancel', 'Unavailable')
    ], default='draft', tracking=True)
    product_type = fields.Selection([
        ('consu', 'Consumable'),
        ('servis', 'Service'),
        ('product', 'Storable Product'),
    ], default='product')
    subtotal = fields.Float(string='Subtotal', compute='_compute_subtotal')
    show_for_sales = fields.Boolean(
        string="Show for Sales",
        compute="_compute_show_for_sales",
    )
    show_salesperson = fields.Many2one(
        'res.users',
        string="Salesperson",
    )

    so_state = fields.Selection(
        [
            ('draft', 'Draft'),
            ('cancel', 'Cancel'),
            ('sale', 'Sale')
        ],
        string="SO State",
        compute="_compute_so_data"
    )

    so_name = fields.Char(
        string="SO Number",
        compute="_compute_so_data"
    )
    is_md_person = fields.Boolean(
        string="Is MD Person",
        compute="_compute_is_md_person"
    )
    is_receiver = fields.Boolean(
        string="Is MD Receiver",
        compute="_compute_is_md_person"
    )

    is_given = fields.Boolean(string='Is Given', tracking=True)
    given_to_id = fields.Many2one('res.users', string='Given To')
    previous_md_id = fields.Many2one('res.users', string='Previous MD')

    @api.depends('quantity', 'price', 'tax_id')
    def _compute_subtotal(self):
        for line in self:
            subtotal = (line.quantity or 0.0) * (line.price or 0.0)

            if line.tax_id:
                tax = line.tax_id.amount / 100

                if line.tax_id.price_include:
                    subtotal = subtotal / (1 + tax)

            line.subtotal = subtotal

    @api.depends('order_id.so_id.user_id', 'order_id.so_id.state', 'order_id.so_id.name')
    def _compute_so_data(self):
        for rec in self:
            so = rec.order_id.so_id
            if so:
                rec.so_state = so.state if so.state in ['draft', 'sale'] else False
                rec.so_name = so.name
            else:
                rec.so_state = False
                rec.so_name = False

    def _compute_is_md_person(self):
        current_user = self.env.user
        for rec in self:
            rec.is_md_person = bool(rec.md_person_ids == current_user)
            rec.is_receiver = bool(rec.given_to_id == current_user)

    @api.constrains('product_type', 'product_category', 'product_class')
    def _check_required_fields_for_md(self):
        for rec in self:
            if rec.state == 'cancel':
                continue
            is_md = self.env.user.has_group('indoteknik_custom.group_role_merchandiser')
            if is_md and (not rec.product_type or rec.product_category == False or rec.product_class == False):
                raise UserError("MD wajib mengisi SKU, Product Type, Product Category, dan Categories!")

    @api.depends('price', 'vendor_id', 'order_id')
    def _compute_show_for_sales(self):
        for rec in self:
            rec.show_for_sales = bool(
                rec.order_id and rec.price not in (None, 0) and rec.vendor_id
            )

    @api.model
    def create(self, vals):
        order_id = vals.get('order_id')
        if order_id:
            order = self.env['sourcing.job.order'].browse(order_id)
            if order.state == 'taken' and order.line_ids.md_person_ids != self.env.user:
                raise UserError("โŒ SJO sudah taken. Tidak boleh tambah line.")
            if order.so_id:
                vals['so_id'] = order.so_id.id
                vals['show_salesperson'] = order.so_id.user_id.id

        rec = super().create(vals)
        rec._check_line_limit()
        return rec

    def write(self, vals):
        for rec in self:
            if (
                rec.md_person_ids 
                and self.env.uid != rec.md_person_ids.id 
                and rec.order_id.create_uid != self.env.user
            ):
                raise UserError("โŒ Hanya MD yang memegang job yang boleh mengedit Sourcing Job.")
        
        res = super().write(vals)
        if 'state' in vals:
            self._update_parent_state()
        self._check_line_limit()
        return res

    def _check_line_limit(self):
        for rec in self:
            if not rec.order_id or not rec.order_id.so_id:
                continue

            so = rec.order_id.so_id

            so_line_count = len(so.order_line)

            sourcing_lines = self.search([
                ('order_id', '=', rec.order_id.id),
                ('state', '!=', 'cancel')
            ])

            if len(sourcing_lines) > so_line_count:
                raise UserError(
                    f"Jumlah Sourcing Line tidak boleh melebihi Sales Order Line.\n\n"
                    f"Sales Order Line : {so_line_count}\n"
                    f"Sourcing Line : {len(sourcing_lines)}"
                )

    def _update_parent_state(self):
        for rec in self:
            order = rec.order_id
            if not order:
                continue

            lines = order.line_ids
            if not lines:
                continue

            total = len(lines)

            if total == 1:
                line = lines[0]
                if line.state == 'approve':
                    order.state = 'done'
                elif line.state == 'cancel':
                    order.state = 'cancel'
                else:
                    order.state = 'taken'
                continue

            states = lines.mapped('state')

            all_cancel = all(s == 'cancel' for s in states)
            all_done_or_cancel = all(s in ['approve', 'cancel'] for s in states)
            any_done = any(s == 'approve' for s in states)
            any_progress = any(s not in ['approve', 'cancel', 'draft'] for s in states)

            if all_cancel:
                order.state = 'cancel'
                continue

            if all_done_or_cancel:
                order.state = 'done'
                continue

            if any_done and not all_done_or_cancel:
                order.state = 'partial'
                continue

            if any_progress:
                order.state = 'taken'
                continue
    
    def action_take(self):
        for rec in self:
            if not self.env.user.has_group('indoteknik_custom.group_role_merchandiser'):
                raise UserError("โŒ Hanya Merchandiser yang dapat mengambil Sourcing Job.")
            if rec.state != 'draft':
                continue
            rec.state = 'sourcing'
            rec.md_person_ids = self.env.uid
            rec.order_id.state = 'taken'

            line_no = 1
            if rec.order_id:
                all_lines = self.search(
                    [('order_id', '=', rec.order_id.id)],
                    order='id asc'
                )
                for i, r in enumerate(all_lines, start=1):
                    if r.id == rec.id:
                        line_no = i
                        break

            rec.message_post(
                body=("Line <b>%s</b> dari Order <b>%s</b> diambil oleh %s")
                % (line_no, rec.order_id.name or '-', self.env.user.name)
            )

    def action_multi_take(self):
        if not self.env.user.has_group('indoteknik_custom.group_role_merchandiser'):
                raise UserError("โŒ Hanya Merchandiser yang dapat mengambil Sourcing Job.")

        unsource = self.filtered(lambda r: r.state == 'draft')
        if not unsource:
            raise UserError("Tidak ada record Unsource untuk diambil.")

        unsource.write({
            'state': 'sourcing',
            'md_person_ids': self.env.uid
        })

        for rec in unsource:
            if rec.order_id.state == 'draft':
                rec.order_id.state = 'taken'

                line_no = self.search_count([
                    ('order_id', '=', rec.order_id.id),
                    ('id', '<=', rec.id)
                ]) 

                rec.message_post(
                    body=("Line <b>%s</b> dari Order <b>%s</b> diambil oleh %s")
                    % (line_no, rec.order_id.name or '-', self.env.user.name)
                )

            if rec.order_id.state != 'draft':
                continue

    def action_multi_ask_approval(self):
        bot_sjo = '8335015210:AAGbObP0jQf7ptyqJhYdBYn5Rm0CWOd_yIM'
        chat_sjo = '6076436058'
        api_base = f'https://api.telegram.org/bot{bot_sjo}/sendMessage'

        order_ids = self.mapped('order_id')
        if len(order_ids) != 1:
            raise UserError("โŒ Semua line harus berasal dari Sourcing Job yang sama.")

        order_ids = self.mapped('order_id')
        if len(order_ids) != 1:
            raise UserError("โŒ Semua line harus berasal dari Sourcing Job yang sama.")

        job = order_ids[0]

        md_users = self.mapped('md_person_ids')
        if len(md_users) != 1 or md_users[0] != self.env.user:
            raise UserError("โŒ Hanya MD yang memegang semua line ini yang bisa request approval.")

        for line in self:
            if line.state != 'sourcing':
                raise UserError(f"โš ๏ธ Produk '{line.product_name_md}' bukan status Sourcing.")

            if (
                not line.vendor_id
                or not line.product_name_md
                or not brand_id
                or not line.price or line.price <= 0
                or not line.tax_id
                or not line.subtotal or line.subtotal <= 0
                or not line.product_type
                or not line.product_category
                or not line.product_class
            ):
                raise UserError(f"โŒ Data produk '{line.product_name_md}' belum lengkap.")

        activity_type = self.env.ref('mail.mail_activity_data_todo')

        approved_lines_text = ""

        for line in self:
            line.state = 'sent'

            line.activity_schedule(
                activity_type_id=activity_type.id,
                user_id=job.create_uid.id,
                note=f"{self.env.user.name} meminta approval untuk produk '{line.product_name_md}' di SJO '{job.name}'.",
            )

            approved_lines_text += f"<li>{line.product_name_md} - {line.price or 0}</li>"

            line.message_post(
                body=f"๐Ÿ“ค <b>Request approval dikirim (Multi)</b>",
                subtype_xmlid="mail.mt_comment",
            )

        job.message_post(
            body=(
                f"๐Ÿ“ค <b>Multi Request Approval</b><br/>"
                f"<ul>{approved_lines_text}</ul>"
                f"<b>MD:</b> {self.env.user.name}"
            ),
            subtype_xmlid="mail.mt_comment",
        )

        self.env.user.notify_success(
            message=f"{len(self)} produk berhasil dikirim untuk approval.",
            title="Multi Request Sent"
        )

        # return {'type': 'ir.actions.client', 'tag': 'reload'}
    

    def action_ask_approval(self):
        bot_sjo = '8335015210:AAGbObP0jQf7ptyqJhYdBYn5Rm0CWOd_yIM'
        chat_sjo = '6076436058'
        api_base = f'https://api.telegram.org/bot{bot_sjo}/sendMessage'

        for line in self:
            job = line.order_id

            if line.md_person_ids != self.env.user:
                raise UserError("โŒ Hanya MD pada line ini yang dapat Request Approval.")

            if line.state != 'sourcing':
                raise UserError("โš ๏ธ Hanya line status 'Sourcing' yang bisa minta approval.")

            missing_fields = []

            if not line.vendor_id:
                missing_fields.append("Vendor")

            if not line.product_name_md:
                missing_fields.append("Product Name")

            if not line.brand_id:
                missing_fields.append("Manufactures")

            if not line.price or line.price <= 0:
                missing_fields.append("Price")

            if not line.tax_id:
                missing_fields.append("Tax")

            if not line.subtotal or line.subtotal <= 0:
                missing_fields.append("Subtotal")

            if not line.product_type:
                missing_fields.append("Product Type")

            if not line.product_category:
                missing_fields.append("Product Category")

            if not line.product_class:
                missing_fields.append("Product Class")

            if missing_fields:
                raise UserError(
                    "โŒ Lengkapi data berikut sebelum Ask Approval Sales:\n- " +
                    "\n- ".join(missing_fields)
                )

            line.state = 'sent'

            activity_type = self.env.ref('mail.mail_activity_data_todo')

            line.activity_schedule(
                activity_type_id=activity_type.id,
                user_id=job.create_uid.id,
                note=f"{self.env.user.name} meminta approval untuk produk '{line.product_name_md}' di SJO '{job.name}'.",
            )

            line.message_post(
                body=(
                    f"๐Ÿ“ค <b>Request approval dikirim</b><br/>"
                    f"Kepada: <b>{job.create_uid.name}</b><br/>"
                    f"Produk: <b>{line.product_name_md}</b>"
                ),
                subtype_xmlid="mail.mt_comment"
            )

            job.message_post(
                body=(
                    f"๐Ÿ“ค <b>Request approval line</b><br/>"
                    f"<ul>"
                    f"<li><b>Produk:</b> {line.product_name_md}</li>"
                    f"<li><b>MD:</b> {self.env.user.name}</li>"
                    f"<li><b>Vendor:</b> {line.vendor_id.display_name if line.vendor_id else '-'}</li>"
                    f"<li><b>Harga:</b> {line.price or 0}</li>"
                    f"</ul>"
                ),
                subtype_xmlid="mail.mt_comment"
            )

            self.env.user.notify_success(
                message=f"Request approval untuk '{line.product_name_md}' dikirim ke {job.create_uid.name}",
                title="Request Sent",
            )

            base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
            url = f"{base_url}/web#id={job.id}&model=sourcing.job.order&view_type=form"

            try:
                msg_text = (
                    f"๐Ÿ“ข <b>Request Approval Produk</b>\n\n"
                    f"๐Ÿงพ <b>Sourcing Job:</b> <a href='{url}'>๐Ÿ“Ž {job.name}</a>\n"
                    f"๐Ÿ“ฆ <b>Produk:</b> {line.product_name_md}\n"
                    f"๐Ÿ‘ค <b>MD:</b> {self.env.user.name}\n"
                    f"๐Ÿ’ฐ <b>Harga:</b> {line.price or 0}\n"
                    f"๐Ÿ“… <b>Tanggal:</b> {fields.Datetime.now().strftime('%d-%m-%Y %H:%M')}\n\n"
                    f"Silakan review di Odoo."
                )

                payload = {
                    'chat_id': chat_sjo,
                    'text': msg_text,
                    'parse_mode': 'HTML'
                }

                response = requests.post(api_base, data=payload, timeout=10)
                response.raise_for_status()

            except Exception as e:
                _logger.warning(f"Gagal kirim telegram approval line: {e}")

        return {'type': 'ir.actions.client', 'tag': 'reload'}

    def action_approve_approval(self):
        ProductProduct = self.env['product.product']
        PurchasePricelist = self.env['purchase.pricelist']
        SaleOrderLine = self.env['sale.order.line']

        for rec in self:
            job = rec.order_id

            if job.create_uid != self.env.user:
                raise UserError("โŒ Hanya pembuat Sourcing Job yang bisa approve.")

            rec.write({'state': 'approve'})

            product = False
            if rec.code:
                product = ProductProduct.search([
                    ('default_code', '=', rec.code),
                    ('active', '=', True)
                ], limit=1)

            if product:
                rec.product_id = product.id

                self.env.user.notify_warning(
                    message=f"SKU {rec.code} sudah ada. Tidak dibuat ulang.",
                    title="SKU Exists"
                )

            else:
                type_map = {
                    'servis': 'service',
                    'product': 'product',
                    'consu': 'consu',
                }

                product = ProductProduct.with_context(from_sourcing_approval=True).create({
                    'name': rec.product_name_md,
                    'default_code': rec.code or False,
                    'description': rec.descriptions_md or '',
                    'type': type_map.get(rec.product_type, 'product'),
                    'categ_id': rec.product_category.id if rec.product_category else False,
                    'x_manufacture': rec.brand_id.id if rec.brand_id else False,
                    'standard_price': rec.price or 0,
                    'public_categ_ids': [(6, 0, rec.product_class.ids)] if rec.product_class else False,
                    'active': True,
                    'sourcing_job_id': job.id if job else False,
                })

                if not rec.code:
                    padded_id = str(product.id).zfill(7)
                    sku_auto = f"IT.{padded_id}"
                    product.default_code = sku_auto
                    rec.code = sku_auto

                rec.product_id = product.id

                self.env.user.notify_success(
                    message=f"Produk baru '{product.name}' berhasil dibuat dengan SKU {product.default_code}.",
                    title="Product Created"
                )

            jakarta_tz = rec.order_id._get_jakarta_today()

            purchase_price = PurchasePricelist.search([
                ('product_id', '=', product.id),
                ('vendor_id', '=', rec.vendor_id.id),
            ], order="human_last_update desc", limit=1)

            pricelist_vals = {
                'product_id': product.id,
                'vendor_id': rec.vendor_id.id,
                'product_price': rec.price or 0,
                'include_price': rec.price or 0,
                'taxes_product_id': rec.tax_id.id if rec.tax_id else False,
                'brand_id': product.x_manufacture.id if product.x_manufacture else False,
                'human_last_update': jakarta_tz,
                'is_winner': True,
            }

            if not purchase_price:
                PurchasePricelist.create(pricelist_vals)

            elif purchase_price.product_price != (rec.price or 0):
                purchase_price.write(pricelist_vals)

            if rec.so_id and not rec.exported_to_so:
                so = rec.so_id

                so_line_new = SaleOrderLine.new({
                    "order_id": so.id,
                    "product_id": product.id,
                    "product_uom_qty": rec.quantity or 1,
                    "price_unit": rec.price or 0,
                    "name": rec.product_name_md,
                })

                so_line_new.product_id_change()
                vals = SaleOrderLine._convert_to_write(so_line_new._cache)
                SaleOrderLine.create(vals)

                rec.exported_to_so = True

            activities = self.env['mail.activity'].search([
                ('res_model', '=', rec._name),
                ('res_id', '=', rec.id),
            ])
            activities.unlink()

            rec.message_post(
                body=(
                    f"โœ… <b>Approval disetujui oleh {self.env.user.name}</b><br/>"
                    f"Produk siap untuk proses selanjutnya (convert / PO / SO)."
                ),
                subtype_xmlid="mail.mt_comment"
            )

            job.message_post(
                body=(
                    f"โœ… <b>Approval produk disetujui</b><br/>"
                    f"<ul>"
                    f"<li><b>Produk:</b> {rec.product_name_md}</li>"
                    f"<li><b>Vendor:</b> {rec.vendor_id.display_name if rec.vendor_id else '-'}</li>"
                    f"<li><b>Harga:</b> {rec.price or 0}</li>"
                    f"<li><b>Disetujui oleh:</b> {self.env.user.name}</li>"
                    f"</ul>"
                ),
                subtype_xmlid="mail.mt_comment"
            )

            if rec.md_person_ids:
                rec.md_person_ids.notify_success(
                    message=f"Produk '{rec.product_name_md}' telah di-approve sales.",
                    title="Approval Approved"
                )

            self.env.user.notify_success(
                message=f"Produk '{rec.product_name_md}' berhasil di-approve.",
                title="Approved"
            )

        so = self.mapped('so_id')[:1]
        if so:
            return {
                'type': 'ir.actions.act_window',
                'name': 'Sales Order',
                'res_model': 'sale.order',
                'view_mode': 'form',
                'res_id': so.id,
                'target': 'current',
            }

        return {'type': 'ir.actions.client', 'tag': 'reload'}

    def action_multi_approve(self):
        so_ids = self.mapped('so_id').ids

        if len(set(so_ids)) > 1:
            raise UserError("โŒ Multi approve hanya bisa dilakukan jika semua line berasal dari Sales Order yang sama.")
        self.action_approve_approval()

    def action_reject_approval(self):
        self.ensure_one()

        job = self.order_id
        if job.create_uid != self.env.user:
            raise UserError("โŒ Hanya pembuat Sourcing Job yang bisa reject approval.")
        
        return {
            'name': 'Reason Reject',
            'type': 'ir.actions.act_window',
            'res_model': 'sourcing.reject.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_line_id': self.id
            }
        }

    def action_cancel(self):
        for rec in self:
            if self.env.user != rec.md_person_ids:
                raise UserError("Hanya MD Person Job ini yang bisa Cancel.")

            if not rec.reason:
                raise UserError("Isi Reason untuk Cancel Job.")
                
            line_no = 1
            if rec.order_id:
                all_lines = self.search(
                    [('order_id', '=', rec.order_id.id)],
                    order='id asc'
                )
                for i, r in enumerate(all_lines, start=1):
                    if r.id == rec.id:
                        line_no = i
                        break

            rec.write({'state': 'cancel'})

            rec.message_post(
                body=(
                    "Line <b>%s</b> dari Order <b>%s</b> di Cancel oleh <b>%s</b><br/>"
                    "Reason: %s"
                ) % (
                    line_no,
                    rec.order_id.name or '-',
                    self.env.user.name,
                    rec.reason or '-'
                )
            )

    @api.onchange('product_id')
    def _oncange_code(self):
        for rec in self:
            if not rec.product_id:
                continue

            product = rec.product_id
            if not product:
                return
            template = product.product_tmpl_id
            attribute_values = product.product_template_attribute_value_ids.mapped(
                'product_attribute_value_id.name'
            )
            attribute_values_str = ', '.join(attribute_values) if attribute_values else ''

            # generate line name
            line_name = (
                ('[' + product.default_code + '] ' if product.default_code else '') +
                (product.name or '') +
                (' (' + attribute_values_str + ')' if attribute_values_str else '') +
                (' ' + product.short_spesification if product.short_spesification else '')
            )
            
            rec.code = product.default_code or rec.code
            rec.product_name_md = product.name or rec.product_name_md
            rec.descriptions_md = line_name.strip() or rec.descriptions_md
            rec.product_type = template.type or rec.product_type
            rec.brand_id = product.x_manufacture.id or rec.brand_id
            rec.product_category = template.categ_id.id or rec.product_category
            rec.product_class = [(6, 0, template.public_categ_ids.ids)] if template.public_categ_ids else []

            pricelist = self.env['purchase.pricelist'].search([('product_id', '=', product.id), ('is_winner', '=', True)], limit=1)
            if pricelist:
                rec.vendor_id = pricelist.vendor_id.id or False
                rec.price = pricelist.include_price or 0.0
                rec.now_price = pricelist.include_price or 0.0
                rec.last_updated_price = pricelist.write_date or 0.0
                rec.tax_id = pricelist.taxes_product_id.id or pricelist.taxes_system_id.id or False
    
    @api.onchange('attachment_type')
    def _onchange_attachment_type(self):
        for rec in self:
            if rec.attachment_type == 'pdf':
                rec.product_attachment_img = False
                rec.product_attachment_other = False

            elif rec.attachment_type == 'img':
                rec.product_attachment_pdf = False
                rec.product_attachment_other = False

            elif rec.attachment_type == 'other':
                rec.product_attachment_pdf = False
                rec.product_attachment_img = False

            else:
                rec.product_attachment_pdf = False
                rec.product_attachment_img = False
                rec.product_attachment_other = False

    @api.onchange(
        'product_attachment_pdf',
        'product_attachment_img',
        'product_attachment_other',
        'attachment_type'
    )
    def _onchange_set_filename(self):
        for rec in self:
            sjo_number = rec.order_id.name if rec.order_id and rec.order_id.name else 'SJO'

            if rec.attachment_type == 'pdf' and rec.product_attachment_pdf:
                rec.product_attachment_filename = f"{sjo_number}.pdf"

            elif rec.attachment_type == 'img' and rec.product_attachment_img:
                rec.product_attachment_filename = f"{sjo_number}.png"

            elif rec.attachment_type == 'other' and rec.product_attachment_other:
                rec.product_attachment_filename = f"{sjo_number}_file"

    def action_reopen_cancel(self):
        self.ensure_one()

        if self.state != 'cancel':
            raise UserError("Cuma line cancel yang bisa direopen.")
        if self.order_id.create_uid != self.env.user:
            raise UserError("Cuma Pemilik SJO yang bisa Re-Open.")

        return {
            'name': 'Reason Reopen',
            'type': 'ir.actions.act_window',
            'res_model': 'reopen.cancel.line.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_line_id': self.id
            }
        }

    def action_open_give_wizard(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': 'Give To MD',
            'res_model': 'sjo.give.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_line_id': self.id,
            }
        }

    def action_open_reject_given_wizard(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': 'Reject Request Give SJO Line',
            'res_model': 'sjo.reject.give.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'default_line_id': self.id,
            }
        }

    def action_take_given(self):
        for rec in self:
            if self.env.user != rec.given_to_id:
                raise UserError("Hanya MD yang diberikan Request yang bisa Take Sourcing")

            old_owner = rec.previous_md_id.name
            new_owner = rec.given_to_id.name
            receiver = rec.given_to_id 

            rec.with_context(bypass_md_check=True).write({
                'md_person_ids': rec.given_to_id.id,
                'given_to_id': False,
                'previous_md_id': False,
                'is_given': False,
            })

            rec._unlink_give_activity(receiver)
            rec.message_post(
                body=f"<b>{new_owner}<b/> Menerima Request Sourcing dari <b>{old_owner}<b/>"
            )

class SjoGiveWizard(models.TransientModel):
    _name = 'sjo.give.wizard'
    _description = 'Give SJO Line Wizard'

    line_id = fields.Many2one('sourcing.job.order.line')
    md_id = fields.Many2one('res.users', string='Give To', required=True, domain=lambda self: [
        ('groups_id', 'in', self.env.ref('base.group_user').ids),
        ('groups_id', 'in', self.env.ref('indoteknik_custom.group_role_merchandiser').ids),
        ('active', '=', True)
    ])

    def action_confirm(self):
        self.ensure_one()

        line = self.line_id

        if self.env.user != line.md_person_ids:
            raise UserError("Hanya Md Target yang bisa Confirm Give Sourcing")

        old_owner = line.md_person_ids.name
        new_owner = self.md_id.name

        line.write({
            'previous_md_id': line.md_person_ids.id,
            'given_to_id': self.md_id.id,
            'is_given': True,
        })

        activity_type = self.env.ref('mail.mail_activity_data_todo')
        line.activity_schedule(
            activity_type_id=activity_type.id,
            user_id=self.md_id.id,
            note="SJO Line diberikan ke Anda. Silakan Take atau Reject.",
        )

        line.message_post(
            body=f"""
                <b>MD {old_owner}</b> Mengirim Request Peralihan Sourcing Ke <b>{new_owner}</b>
            """,
            subtype_xmlid="mail.mt_comment"
        )

class SjoRejectGiveWizard(models.TransientModel):
    _name = 'sjo.reject.give.wizard'
    _description = 'Reject Given SJO Line Wizard'

    line_id = fields.Many2one('sourcing.job.order.line', required=True)
    reason = fields.Text(string="Reject Reason", required=True)

    def action_confirm(self):
        self.ensure_one()
        line = self.line_id

        if self.env.user != line.given_to_id:
            raise UserError("Hanya Penerima Request yang bisa Reject Give")

        from_md = line.previous_md_id.name or "-"
        receiver = line.given_to_id
        rejector = self.env.user.name

        line._unlink_give_activity(receiver)

        line.with_context(bypass_md_check=True).write({
            'given_to_id': False,
            'is_given': False,
        })

        line.message_post(
            body=f"""
                Request Peralihan dari <b>{from_md}</b> Rejected by <b>{rejector}</b><br/>
                Alasan: {self.reason}
            """,
            subtype_xmlid="mail.mt_comment"
        )   

class WizardExportSJOtoSO(models.TransientModel):
    _name = "wizard.export.sjo.to.so"
    _description = "Wizard Export SJO Products to SO"

    sjo_id = fields.Many2one("sourcing.job.order", string="Sourcing Job ID")
    line_ids = fields.Many2many("sourcing.job.order.line", string="SJO Lines")
    product_ids = fields.Many2many(
        "product.product",
        string="Products",
        compute="_compute_products",
        store=False,
    )

    @api.model
    def default_get(self, fields):
        res = super().default_get(fields)
        sjo_id = self.env.context.get("default_sjo_id")

        if sjo_id:
            # ambil line yg punya product & belum di export
            lines = self.env["sourcing.job.order.line"].search([
                ("order_id", "=", sjo_id),
                ("product_id", "!=", False),
                ("exported_to_so", "=", False),
                ("state", "=", "approve"),  # optional: cuma yg done
            ])
            res["line_ids"] = [(6, 0, lines.ids)]

        return res

    @api.depends("line_ids")
    def _compute_products(self):
        for rec in self:
            rec.product_ids = rec.line_ids.mapped("product_id")

    def action_confirm(self):
        self.ensure_one()
        sjo = self.sjo_id

        if not sjo.so_id:
            raise UserError("Sales Order belum dipilih di SJO!")

        so = sjo.so_id
        SaleOrderLine = self.env["sale.order.line"]

        for line in self.line_ids:
            if not line.product_id:
                continue

            # bikin SOL dari product
            so_line_new = SaleOrderLine.new({
                "order_id": so.id,
                "product_id": line.product_id.id,
                "product_uom_qty": line.quantity or 1,
                "price_unit": line.price or 0,
                "name": line.product_name,
            })

            so_line_new.product_id_change()
            vals = SaleOrderLine._convert_to_write(so_line_new._cache)
            new_line = SaleOrderLine.create(vals)

            # tandai sudah export
            line.exported_to_so = True

        return {
            'type': 'ir.actions.act_window',
            'res_model': 'sale.order',
            'view_mode': 'form',
            'res_id': so.id,
            'target': 'current',
        }

class SourcingJobOrderLineImportWizard(models.TransientModel):
    _name = 'sourcing.job.order.line.import.wizard'
    _description = 'Import SJO Line from Excel'

    excel_file = fields.Binary("Excel File", required=True)
    filename = fields.Char("Filename")
    order_id = fields.Many2one('sourcing.job.order', string="Sourcing Job Order", required=True)

    def action_import_excel(self):
        if not self.excel_file:
            raise UserError(_("โš ๏ธ Harap upload file Excel terlebih dahulu."))

        try:
            data = base64.b64decode(self.excel_file)
            book = xlrd.open_workbook(file_contents=data)
            sheet = book.sheet_by_index(0)
        except:
            raise UserError(_("โŒ Format Excel tidak valid atau rusak."))

        header = [str(sheet.cell(0, col).value).strip() for col in range(sheet.ncols)]
        required_headers = [
            'Nama Barang', 'SKU', 'Expected Price', 'Note Sourcing', 'Brand',
            'Deskripsi / Spesifikasi', 'SLA Product', 'Quantity Product',
            'Purchase Price', 'Tax', 'Vendor', 'Product Category',
            'Categories', 'Product Type'
        ]

        for req in required_headers:
            if req not in header:
                raise UserError(_("โŒ Kolom '%s' tidak ditemukan di file Excel.") % req)

        header_map = {h: idx for idx, h in enumerate(header)}
        lines_created = 0
        ProductLine = self.env['sourcing.job.order.line']
        Tax = self.env['account.tax']
        Vendor = self.env['res.partner']
        Category = self.env['product.category']
        PublicCategory = self.env['product.public.category']

        for row_idx in range(1, sheet.nrows):
            row = sheet.row(row_idx)
            def val(field):
                return str(sheet.cell(row_idx, header_map[field]).value).strip()

            if not val('Nama Barang'):
                continue  # skip kosong

            # Relations
            tax = Tax.search([('name', 'ilike', val('Tax'))], limit=1)
            vendor = Vendor.search([('name', 'ilike', val('Vendor'))], limit=1)
            category = Category.search([('name', 'ilike', val('Product Category'))], limit=1)

            # Many2many: Categories
            class_names = val('Categories').split(';')
            class_ids = []
            for name in class_names:
                name = name.strip()
                if name:
                    pc = PublicCategory.search([('name', 'ilike', name)], limit=1)
                    if pc:
                        class_ids.append(pc.id)

            # Build values
            vals = {
                'order_id': self.order_id.id,
                'product_name': val('Nama Barang'),
                'code': val('SKU'),
                'budget': val('Expected Price'),
                'note': val('Note Sourcing'),
                'brand': val('Brand'),
                'descriptions': val('Deskripsi / Spesifikasi'),
                'sla': val('SLA Product'),
                'quantity': float(val('Quantity Product') or 0),
                'price': float(val('Purchase Price') or 0),
                'tax_id': tax.id if tax else False,
                'vendor_id': vendor.id if vendor else False,
                'product_category': category.id if category else False,
                'product_type': val('Product Type') or 'product',
                'product_class': [(6, 0, class_ids)],
            }

            ProductLine.create(vals)
            lines_created += 1

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('โœ… Import Selesai'),
                'message': _('%s baris berhasil diimport.') % lines_created,
                'type': 'success',
                'sticky': False,
            }
        }

class SourcingJobOrderLineExportWizard(models.TransientModel):
    _name = 'sourcing.job.order.line.export.wizard'
    _description = 'Export SJO Line Wizard'

    order_id = fields.Many2one('sourcing.job.order', string="Sourcing Job Order", required=True)
    file = fields.Binary("CSV File", readonly=True)
    filename = fields.Char("Filename", readonly=True)

    def action_export(self):
        if not self.order_id:
            raise UserError("Silakan pilih Sourcing Job Order terlebih dahulu.")

        lines = self.env['sourcing.job.order.line'].search([('order_id', '=', self.order_id.id)])
        wb = xlwt.Workbook()
        sheet = wb.add_sheet("SJO Lines")

        headers = [
            'Nama Barang', 'SKU', 'Expected Price', 'Note Sourcing', 'Brand',
            'Deskripsi / Spesifikasi', 'SLA Product', 'Quantity Product',
            'Purchase Price', 'Tax', 'Vendor', 'Product Category',
            'Categories', 'Product Type'
        ]

        # Write header
        for col, header in enumerate(headers):
            sheet.write(0, col, header)

        for row_idx, line in enumerate(lines, start=1):
            categories = '; '.join(line.product_class.mapped('name')) or ''
            values = [
                line.product_name or '',
                line.code or '',
                line.budget or '',
                line.note or '',
                line.brand or '',
                line.descriptions or '',
                line.sla or '',
                line.quantity or 0,
                line.price or 0,
                line.tax_id.name if line.tax_id else '',
                line.vendor_id.name if line.vendor_id else '',
                line.product_category.name if line.product_category else '',
                categories,
                line.product_type or '',
            ]
            for col_idx, value in enumerate(values):
                sheet.write(row_idx, col_idx, value)

        # Save to binary
        fp = io.BytesIO()
        wb.save(fp)
        fp.seek(0)
        data = fp.read()
        fp.close()

        self.file = base64.b64encode(data)
        self.filename = f"SJO_{self.order_id.name}_lines.xls"  # Note: xlwt hanya mendukung .xls

        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'view_mode': 'form',
            'res_id': self.id,
            'target': 'new',
        }


class SourcingJobOrderLineTemplateWizard(models.TransientModel):
    _name = 'sourcing.job.order.line.template.wizard'
    _description = 'Download & Import Template SJO Line'

    file = fields.Binary("Template", readonly=True)
    filename = fields.Char("Filename", readonly=True)

    order_id = fields.Many2one(
        'sourcing.job.order',
        string="Sourcing Job Order",
        required=True,
        domain="[('state', '=', 'taken')]",
        default=lambda self: self.env.context.get('active_id')
    )

    excel_file = fields.Binary("Upload Excel")
    excel_filename = fields.Char("Excel Filename")

    def action_generate_template(self):
        output = io.BytesIO()
        wb = xlwt.Workbook()
        ws = wb.add_sheet('Template')

        headers = [
            'Nama Barang', 'SKU', 'Expected Price', 'Note Sourcing', 'Brand',
            'Deskripsi / Spesifikasi', 'SLA Product', 'Quantity Product',
            'Purchase Price', 'Tax', 'Vendor', 'Product Category',
            'Categories', 'Product Type'
        ]

        for col, header in enumerate(headers):
            ws.write(0, col, header)

        wb.save(output)
        output.seek(0)

        self.file = base64.b64encode(output.read())
        self.filename = "SJO_import_template.xls"

        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'view_mode': 'form',
            'res_id': self.id,
            'target': 'new',
        }

    def action_import_excel(self):
        if not self.excel_file:
            raise UserError(_("โš ๏ธ Harap upload file Excel terlebih dahulu."))

        if not self.order_id:
            raise UserError(_("โš ๏ธ Pilih Sourcing Job Order dulu."))

        try:
            data = base64.b64decode(self.excel_file)
            book = xlrd.open_workbook(file_contents=data)
            sheet = book.sheet_by_index(0)
        except:
            raise UserError(_("โŒ Format Excel tidak valid atau rusak."))

        header = [str(sheet.cell(0, col).value).strip() for col in range(sheet.ncols)]
        required_headers = [
            'Nama Barang', 'SKU', 'Expected Price', 'Note Sourcing', 'Brand',
            'Deskripsi / Spesifikasi', 'SLA Product', 'Quantity Product',
            'Purchase Price', 'Tax', 'Vendor', 'Product Category',
            'Categories', 'Product Type'
        ]

        for req in required_headers:
            if req not in header:
                raise UserError(_("โŒ Kolom '%s' tidak ditemukan di file Excel.") % req)

        header_map = {h: idx for idx, h in enumerate(header)}
        lines_created = 0

        ProductLine = self.env['sourcing.job.order.line']
        Tax = self.env['account.tax']
        Vendor = self.env['res.partner']
        Category = self.env['product.category']
        PublicCategory = self.env['product.public.category']

        for row_idx in range(1, sheet.nrows):

            def val(field):
                return str(sheet.cell(row_idx, header_map[field]).value).strip()

            if not val('Nama Barang'):
                continue

            tax = Tax.search([('name', 'ilike', val('Tax'))], limit=1)
            vendor = Vendor.search([('name', 'ilike', val('Vendor'))], limit=1)
            category = Category.search([('name', 'ilike', val('Product Category'))], limit=1)

            # many2many categories
            class_names = val('Categories').split(';')
            class_ids = []
            for name in class_names:
                name = name.strip()
                if name:
                    pc = PublicCategory.search([('name', 'ilike', name)], limit=1)
                    if pc:
                        class_ids.append(pc.id)

            vals = {
                'order_id': self.order_id.id,
                'product_name': val('Nama Barang'),
                'code': val('SKU'),
                'budget': float(val('Expected Price') or 0),
                'note': val('Note Sourcing'),
                'brand': val('Brand'),
                'descriptions': val('Deskripsi / Spesifikasi'),
                'sla': val('SLA Product'),
                'quantity': float(val('Quantity Product') or 0),
                'price': float(val('Purchase Price') or 0),
                'tax_id': tax.id if tax else False,
                'vendor_id': vendor.id if vendor else False,
                'product_category': category.id if category else False,
                'product_type': val('Product Type') or 'product',
                'product_class': [(6, 0, class_ids)],
                'state': 'sourcing',
                'md_person_id': self.env.user,
            }

            ProductLine.create(vals)
            lines_created += 1

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('โœ… Import Selesai'),
                'message': _('%s baris berhasil diimport.') % lines_created,
                'type': 'success',
                'sticky': False,
            }
        }

class SourcingRejectWizard(models.TransientModel):
    _name = 'sourcing.reject.wizard'
    _description = 'Wizard alasan reject produk sourcing oleh sales'

    line_id = fields.Many2one('sourcing.job.order.line', string='Sourcing Line', required=True)
    reason = fields.Text(string='Alasan Penolakan', required=True)

    def action_confirm_reject(self):
        self.ensure_one()
        line = self.line_id
        job = line.order_id

        line.state = 'sourcing'  

        activities = self.env['mail.activity'].search([
            ('res_model', '=', line._name),
            ('res_id', '=', line.id),
        ])

        activities.unlink()
        line.message_post(
            body=(
                f"โŒ <b>Approval ditolak oleh {self.env.user.name}</b><br/>"
                f"<b>Produk:</b> {line.product_name}<br/>"
                f"<b>Alasan:</b><br/>{self.reason}"
            ),
            subtype_xmlid="mail.mt_comment"
        )

        job.message_post(
            body=(
                f"โŒ <b>Approval produk ditolak</b><br/>"
                f"<ul>"
                f"<li><b>Produk:</b> {line.product_name}</li>"
                f"<li><b>Ditolak oleh:</b> {self.env.user.name}</li>"
                f"<li><b>Alasan:</b> {self.reason}</li>"
                f"</ul>"
            ),
            subtype_xmlid="mail.mt_comment"
        )

        if line.md_person_ids:
            line.md_person_ids.notify_warning(
                message=f"Produk '{line.product_name}' direject sales. Silakan sourcing ulang.",
                title="Approval Ditolak"
            )

        self.env.user.notify_info(
            message=f"Produk '{line.product_name}' berhasil direject.",
            title="Rejected"
        )

        return {'type': 'ir.actions.client', 'tag': 'reload'}

class ReopenCancelLineWizard(models.TransientModel):
    _name = 'reopen.cancel.line.wizard'
    _description = 'Reopen Cancel Line Reason'

    line_id = fields.Many2one('sourcing.job.order.line', required=True)
    reason = fields.Text(required=True, string="Reason Reopen")

    def action_confirm(self):
        self.ensure_one()
        line = self.line_id

        if line.order_id.create_uid != self.env.user:
            raise UserError("Line ini bukan bagian dari SJO anda.")

        # post message dulu
        line.message_post(
            body=(
                "Line <b>%s</b> di REOPEN oleh <b>%s</b><br/>"
                "<b>Reason:</b> %s"
            ) % (
                line.product_id.display_name or '-',
                self.env.user.name,
                self.reason
            )
        )

        # reset field
        line.write({
            'state': 'draft',
            'md_person_ids': False,
        })