summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/sale_order.py
blob: 3ad19a8e07463f41169514324458445b55fc56db (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
from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError
from datetime import datetime, timedelta
import logging, random, string, requests, math, json, re, qrcode, base64
from io import BytesIO
from collections import defaultdict

_logger = logging.getLogger(__name__)


class SaleOrder(models.Model):
    _inherit = "sale.order"

    fullfillment_line = fields.One2many('sales.order.fullfillment', 'sales_order_id', string='Fullfillment')
    reject_line = fields.One2many('sales.order.reject', 'sale_order_id', string='Reject Lines')
    order_sales_match_line = fields.One2many('sales.order.purchase.match', 'sales_order_id', string='Purchase Match Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True)
    total_margin = fields.Float('Total Margin', compute='_compute_total_margin', help="Total Margin in Sales Order Header")
    total_percent_margin = fields.Float('Total Percent Margin', compute='_compute_total_percent_margin', help="Total % Margin in Sales Order Header")
    approval_status = fields.Selection([
        ('pengajuan1', 'Approval Manager'),
        ('pengajuan2', 'Approval Pimpinan'),
        ('approved', 'Approved'),
    ], string='Approval Status', readonly=True, copy=False, index=True, tracking=3)
    carrier_id = fields.Many2one('delivery.carrier', string='Shipping Method', tracking=3)
    have_visit_service = fields.Boolean(string='Have Visit Service', compute='_have_visit_service', help='To compute is customer get visit service')
    delivery_amt = fields.Float(string='Delivery Amt', copy=False)
    shipping_cost_covered = fields.Selection([
        ('indoteknik', 'Indoteknik'),
        ('customer', 'Customer')
    ], string='Shipping Covered by', help='Siapa yang menanggung biaya ekspedisi?', copy=False)
    shipping_paid_by = fields.Selection([
        ('indoteknik', 'Indoteknik'),
        ('customer', 'Customer')
    ], string='Shipping Paid by', help='Siapa yang talangin dulu Biaya ekspedisi-nya?', copy=False)
    sales_tax_id = fields.Many2one('account.tax', string='Tax', domain=['|', ('active', '=', False), ('active', '=', True)])
    have_outstanding_invoice = fields.Boolean('Have Outstanding Invoice', compute='_have_outstanding_invoice')
    have_outstanding_picking = fields.Boolean('Have Outstanding Picking', compute='_have_outstanding_picking')
    have_outstanding_po = fields.Boolean('Have Outstanding PO', compute='_have_outstanding_po')
    purchase_ids = fields.Many2many('purchase.order', string='Purchases', compute='_get_purchases')
    real_shipping_id = fields.Many2one(
        'res.partner', string='Real Delivery Address', readonly=True, required=True,
        states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'sale': [('readonly', False)]},
        domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
        help="Dipakai untuk alamat tempel")
    real_invoice_id = fields.Many2one(
        'res.partner', string='Delivery Invoice Address', required=True,
        domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
        help="Dipakai untuk alamat tempel")
    fee_third_party = fields.Float('Fee Pihak Ketiga')
    so_status = fields.Selection([
        ('terproses', 'Terproses'),
        ('sebagian', 'Sebagian Diproses'),
        ('menunggu', 'Menunggu Diproses'),
    ], copy=False)
    partner_purchase_order_name = fields.Char(string='Nama PO Customer', copy=False, help="Nama purchase order customer, diisi oleh customer melalui website.", tracking=3)
    partner_purchase_order_description = fields.Text(string='Keterangan PO Customer', copy=False, help="Keterangan purchase order customer, diisi oleh customer melalui website.", tracking=3)
    partner_purchase_order_file = fields.Binary(string='File PO Customer', copy=False, help="File purchase order customer, diisi oleh customer melalui website.")
    payment_status = fields.Selection([
        ('pending', 'Pending'),
        ('capture', 'Capture'),
        ('settlement', 'Settlement'),
        ('deny', 'Deny'),
        ('cancel', 'Cancel'),
        ('expire', 'Expire'),
        ('failure', 'Failure'),
        ('refund', 'Refund'),
        ('chargeback', 'Chargeback'),
        ('partial_refund', 'Partial Refund'),
        ('partial_chargeback', 'Partial Chargeback'),
        ('authorize', 'Authorize'),
    ], tracking=True, string='Payment Status', help='Payment Gateway Status / Midtrans / Web, https://docs.midtrans.com/en/after-payment/status-cycle')
    date_doc_kirim = fields.Datetime(string='Tanggal Kirim di SJ', help="Tanggal Kirim di cetakan SJ yang terakhir, tidak berpengaruh ke Accounting")
    payment_type = fields.Char(string='Payment Type', help='Jenis pembayaran dengan Midtrans')
    gross_amount = fields.Float(string='Gross Amount', help='Jumlah pembayaran yang dilakukan dengan Midtrans')
    notification = fields.Char(string='Notification', help='Dapat membantu error dari approval')
    delivery_service_type = fields.Char(string='Delivery Service Type', help='data dari rajaongkir')
    grand_total = fields.Monetary(string='Grand Total', help='Amount total + amount delivery', compute='_compute_grand_total')
    payment_link_midtrans = fields.Char(string='Payment Link', help='Url payment yg digenerate oleh midtrans, harap diserahkan ke customer agar dapat dilakukan pembayaran secara mandiri')
    payment_qr_code = fields.Binary("Payment QR Code")
    due_id = fields.Many2one('due.extension', string="Due Extension", readonly=True, tracking=True)   
    customer_type = fields.Selection([
        ('pkp', 'PKP'),
        ('nonpkp', 'Non PKP')
    ], required=True)
    sppkp = fields.Char(string="SPPKP", required=True, tracking=True)
    npwp = fields.Char(string="NPWP", required=True, tracking=True)
    purchase_total = fields.Monetary(string='Purchase Total', compute='_compute_purchase_total')
    voucher_id = fields.Many2one(comodel_name='voucher', string='Voucher', copy=False)
    applied_voucher_id = fields.Many2one(comodel_name='voucher', string='Applied Voucher', copy=False)
    amount_voucher_disc = fields.Float(string='Voucher Discount')
    source_id = fields.Many2one('utm.source', 'Source', domain="[('id', 'in', [32, 59, 60, 61])]", required=True)
    estimated_arrival_days = fields.Integer('Estimated Arrival Days', default=0)
    email = fields.Char(string='Email')
    picking_iu_id = fields.Many2one('stock.picking', 'Picking IU')
    helper_by_id = fields.Many2one('res.users', 'Helper By')
    eta_date = fields.Datetime(string='ETA Date', copy=False, compute='_compute_eta_date')
    flash_sale = fields.Boolean(string='Flash Sale', help='Data dari web')
    web_approval = fields.Selection([
        ('company', 'Company'),
        ('cust_manager', 'Customer Manager'),
        ('cust_director', 'Customer Director'),
        ('cust_procurement', 'Customer Procurement')
    ], string='Web Approval', copy=False)
    compute_fullfillment = fields.Boolean(string='Compute Fullfillment', compute="_compute_fullfillment")
    note_ekspedisi = fields.Char(string="Note Ekspedisi")
    date_kirim_ril = fields.Datetime(string='Tanggal Kirim SJ', compute='_compute_date_kirim', copy=False)
    date_status_done = fields.Datetime(string='Date Done DO', compute='_compute_date_kirim', copy=False)
    date_driver_arrival = fields.Datetime(string='Arrival Date', compute='_compute_date_kirim', copy=False)
    date_driver_departure = fields.Datetime(string='Departure Date', compute='_compute_date_kirim', copy=False)
    note_website = fields.Char(string="Note Website")
    use_button = fields.Boolean(string='Using Calculate Selling Price', copy=False)

    def _compute_date_kirim(self):
        for rec in self:
            picking = self.env['stock.picking'].search([('sale_id', '=', rec.id), ('state', 'not in', ['cancel'])], order='date_doc_kirim desc', limit=1)
            rec.date_kirim_ril = picking.date_doc_kirim
            rec.date_status_done = picking.date_done
            rec.date_driver_arrival = picking.driver_arrival_date
            rec.date_driver_departure = picking.driver_departure_date

    def open_form_multi_create_uang_muka(self):
        action = self.env['ir.actions.act_window']._for_xml_id('indoteknik_custom.action_sale_order_multi_uangmuka')
        action['context'] = {
            'so_ids': [x.id for x in self]
        }
        return action
    
    def _compute_fullfillment(self):
        for rec in self:
            rec.fullfillment_line.unlink()

            for line in rec.order_line:
                line._compute_reserved_from()

            rec.compute_fullfillment = True

    def _compute_eta_date(self):
        max_leadtime = 0

        for line in self.order_line:
            leadtime = line.vendor_id.leadtime
            max_leadtime = max(max_leadtime, leadtime)

        for rec in self:
            if rec.date_order and rec.state not in ['cancel', 'draft']:
                eta_date = datetime.now() + timedelta(days=max_leadtime)
                rec.eta_date = eta_date
            else:
                rec.eta_date = False

    def _prepare_invoice(self):
        """
        Prepare the dict of values to create the new invoice for a sales order. This method may be
        overridden to implement custom invoice generation (making sure to call super() to establish
        a clean extension chain).
        """
        self.ensure_one()
        journal = self.env['account.move'].with_context(default_move_type='out_invoice')._get_default_journal()
        if not journal:
            raise UserError(_('Please define an accounting sales journal for the company %s (%s).') % (self.company_id.name, self.company_id.id))

        parent_id = self.partner_id.parent_id
        parent_id =  parent_id if parent_id else self.partner_id

        invoice_vals = {
            'ref': self.client_order_ref or '',
            'move_type': 'out_invoice',
            'narration': self.note,
            'currency_id': self.pricelist_id.currency_id.id,
            'campaign_id': self.campaign_id.id,
            'medium_id': self.medium_id.id,
            'source_id': self.source_id.id,
            'user_id': self.user_id.id,
            'sale_id': self.id,
            'invoice_user_id': self.user_id.id,
            'team_id': self.team_id.id,
            'partner_id': parent_id.id,
            'partner_shipping_id': parent_id.id,
            'real_invoice_id': self.real_invoice_id.id,
            'fiscal_position_id': (self.fiscal_position_id or self.fiscal_position_id.get_fiscal_position(self.partner_invoice_id.id)).id,
            'partner_bank_id': self.company_id.partner_id.bank_ids[:1].id,
            'journal_id': journal.id,  # company comes from the journal
            'invoice_origin': self.name,
            'invoice_payment_term_id': self.payment_term_id.id,
            'payment_reference': self.reference,
            'transaction_ids': [(6, 0, self.transaction_ids.ids)],
            'invoice_line_ids': [],
            'company_id': self.company_id.id,
        }
        return invoice_vals

    @api.constrains('email')
    def _validate_email(self):
        rule_regex = self.env['ir.config_parameter'].sudo().get_param('sale.order.validate_email') or ''
        pattern = rf'^{rule_regex}$'
        
        if self.email and not re.match(pattern, self.email):
            raise UserError('Email yang anda input kurang valid')
        
    def override_allow_create_invoice(self):
        if not self.env.user.is_accounting:
            raise UserError('Hanya Finance Accounting yang dapat klik tombol ini')
        for term in self.payment_term_id.line_ids:
            if term.days > 0:
                raise UserError('Hanya dapat digunakan pada Cash Before Delivery')
        for line in self.order_line:
            line.qty_to_invoice = line.product_uom_qty

    # def _get_pickings(self):
    #     state = ['assigned']
    #     for order in self:
    #         pickings = self.env['stock.picking'].search([
    #             ('sale_id.id', '=', order.id),
    #             ('state', 'in', state)
    #         ])
    #         order.picking_ids = pickings

    @api.model
    def action_multi_update_state(self):
        for sale in self:
            for picking_ids in sale.picking_ids:
                if not picking_ids.state == 'cancel':
                    raise UserError('DO harus cancel terlebih dahulu')

            sale.update({
                'state': 'cancel',
            })

            if sale.state == 'cancel':
                sale.update({
                    'approval_status': False,
                })

    def open_form_multi_update_status(self):
        action = self.env['ir.actions.act_window']._for_xml_id('indoteknik_custom.action_sale_orders_multi_update')
        action['context'] = {
            'sale_ids': [x.id for x in self]
        }
        return action
    
    def open_form_multi_update_state(self):
        action = self.env['ir.actions.act_window']._for_xml_id('indoteknik_custom.action_quotation_so_multi_update')
        action['context'] = {
            'quotation_ids': [x.id for x in self]
        }
        return action
    
    def action_multi_update_invoice_status(self):
        for sale in self:
            sale.update({
                'invoice_status': 'invoiced',
            })

    def _compute_purchase_total(self):
        for order in self:
            total = 0
            for line in order.order_line:
                total += line.vendor_subtotal
            order.purchase_total = total

    def generate_payment_link_midtrans_sales_order(self):
        # midtrans_url = 'https://app.sandbox.midtrans.com/snap/v1/transactions' # dev - sandbox
        # midtrans_auth = 'Basic U0ItTWlkLXNlcnZlci1uLVY3ZDJjMlpCMFNWRUQyOU95Q1dWWXA6' # dev - sandbox
        midtrans_url = 'https://app.midtrans.com/snap/v1/transactions' # production
        midtrans_auth = 'Basic TWlkLXNlcnZlci1SbGMxZ2gzWGpSVW5scl9JblZzTV9OTnU6' # production
        so_number = self.name
        so_number = so_number.replace('/', '-')
        so_grandtotal = math.floor(self.grand_total)
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': midtrans_auth,
        }

        check_url = f'https://api.midtrans.com/v2/{so_number}/status'
        check_response = requests.get(check_url, headers=headers)

        if check_response.status_code == 200:
            status_response = check_response.json()
            if status_response.get('transaction_status') == 'expire':
                so_number = so_number + '-cpl'

        json_data = {
            'transaction_details': {
                'order_id': so_number,
                'gross_amount': so_grandtotal,
            },
            'credit_card': {
                'secure': True,
            },
        }

        response = requests.post(midtrans_url, headers=headers, json=json_data).json()
        lookup_json = json.dumps(response, indent=4, sort_keys=True)
        redirect_url = json.loads(lookup_json)['redirect_url']
        self.payment_link_midtrans = str(redirect_url)

        # Generate QR code
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(redirect_url)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")

        buffer = BytesIO()
        img.save(buffer, format="PNG")
        qr_code_img = base64.b64encode(buffer.getvalue()).decode()

        self.payment_qr_code = qr_code_img

    @api.model
    def _generate_so_access_token(self, limit=50):
        orders = self.search([('access_token', '=', False)], limit=limit)
        for order in orders:
            token_source = string.ascii_letters + string.digits
            order.access_token = ''.join(random.choice(token_source) for i in range(20))

    def calculate_line_no(self):
        line_no = 0
        for line in self.order_line:
            if line.product_id.type == 'product':
                line_no += 1
                line.line_no = line_no
    
    def write(self, vals):
        res = super(SaleOrder, self).write(vals)
        
        if 'carrier_id' in vals:
            for picking in self.picking_ids:
                if picking.state == 'assigned':
                    picking.carrier_id = self.carrier_id

        return res

    def calculate_so_status(self):
        so_state = ['sale']
        sales = self.search([
            ('state', 'in', so_state),
            ('so_status', '!=', 'terproses'),
        ])
        
        for sale in sales:
            picking_states = ['draft', 'assigned', 'confirmed', 'waiting']
            have_outstanding_pick = any(x.state in picking_states for x in sale.picking_ids)

            sum_qty_so = sum(so_line.product_uom_qty for so_line in sale.order_line)
            sum_qty_ship = sum(so_line.qty_delivered for so_line in sale.order_line)

            if sum_qty_so > sum_qty_ship > 0:
                sale.so_status = 'sebagian'
            elif not have_outstanding_pick:
                sale.so_status = 'terproses'
            else:
                sale.so_status = 'menunggu'
            
            for picking in sale.picking_ids:
                sum_qty_pick = sum(move_line.product_uom_qty for move_line in picking.move_ids_without_package)
                sum_qty_reserved = sum(move_line.product_uom_qty for move_line in picking.move_line_ids_without_package)
                if picking.state == 'done':
                    continue
                elif sum_qty_pick == sum_qty_reserved and not picking.date_reserved:# baru ke reserved
                    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    picking.date_reserved = current_time
                elif sum_qty_pick == sum_qty_reserved:# sudah ada data reserved
                    picking.date_reserved = picking.date_reserved
                else:
                    picking.date_reserved = ''

            _logger.info('Calculate SO Status %s' % sale.id)

    # def _search_picking_ids(self, operator, value):
    #     if operator == 'in' and value:
    #         self.env.cr.execute("""
    #             SELECT array_agg(so.sale_id)
    #                 FROM stock_picking so
    #             WHERE
    #                 so.sale_id is not null and so.id = ANY(%s)
    #         """, (list(value),))
    #         so_ids = self.env.cr.fetchone()[0] or []
    #         return [('id', 'in', so_ids)]
    #     elif operator == '=' and not value:
    #         order_ids = self._search([
    #             ('order_line.invoice_lines.move_id.move_type', 'in', ('out_invoice', 'out_refund'))
    #         ])
    #         return [('id', 'not in', order_ids)]
    #     return ['&', ('order_line.invoice_lines.move_id.move_type', 'in', ('out_invoice', 'out_refund')), ('order_line.invoice_lines.move_id', operator, value)]

    @api.onchange('partner_shipping_id')
    def onchange_partner_shipping(self):
        self.real_shipping_id = self.partner_shipping_id
        self.real_invoice_id = self.partner_invoice_id

    @api.onchange('partner_id')
    def onchange_partner_contact(self):
        parent_id = self.partner_id.parent_id
        parent_id =  parent_id if parent_id else self.partner_id

        self.npwp = parent_id.npwp
        self.sppkp = parent_id.sppkp
        self.customer_type = parent_id.customer_type
        self.email = parent_id.email
    
    @api.onchange('partner_id')
    def onchange_partner_id(self):
        # INHERIT
        result = super(SaleOrder, self).onchange_partner_id()
        parent_id = self.partner_id.parent_id
        parent_id =  parent_id if parent_id else self.partner_id

        self.partner_invoice_id = parent_id
        return result

    def _get_purchases(self):
        po_state = ['done', 'draft', 'purchase']
        for order in self:
            purchases = self.env['purchase.order'].search([
                ('sale_order_id', '=', order.id),
                ('state', 'in', po_state)
            ])
            order.purchase_ids = purchases

    def _have_outstanding_invoice(self):
        invoice_state = ['posted', 'draft']
        for order in self:
            order.have_outstanding_invoice = any(inv.state in invoice_state for inv in order.invoice_ids)

    def _have_outstanding_picking(self):
        picking_state = ['done', 'confirmed', 'draft']
        for order in self:
            order.have_outstanding_picking = any(pick.state in picking_state for pick in order.picking_ids)

    def _have_outstanding_po(self):
        po_state = ['done', 'draft', 'purchase']
        for order in self:
            order.have_outstanding_po = any(po.state in po_state for po in order.purchase_ids)

    def _have_visit_service(self):
        minimum_amount = 20000000
        for order in self:
            order.have_visit_service = self.amount_total > minimum_amount
            
    def _get_helper_ids(self):
        helper_ids_str = self.env['ir.config_parameter'].sudo().get_param('sale.order.user_helper_ids')
        return helper_ids_str.split(', ')
    
    def write(self, values):
        helper_ids = self._get_helper_ids()
        if str(self.env.user.id) in helper_ids:
            values['helper_by_id'] = self.env.user.id
            
        return super(SaleOrder, self).write(values)

    def check_due(self):
        """To show the due amount and warning stage"""
        for order in self:
            partner = order.partner_id.parent_id or order.partner_id
            if partner and partner.active_limit and partner.enable_credit_limit:
                order.has_due = partner.due_amount > 0
                if order.outstanding_amount >= partner.warning_stage and partner.warning_stage != 0:
                    order.is_warning = True
            else:
                order.has_due = False
                order.is_warning = False

    def _validate_order(self):
        if self.payment_term_id.id == 31 and self.total_percent_margin < 25:
            raise UserError("Jika ingin menggunakan Tempo 90 Hari maka margin harus di atas 25%")
        
        if self.warehouse_id.id != 8 and self.warehouse_id.id != 10: #GD Bandengan
            raise UserError('Gudang harus Bandengan')
        
        if self.state not in ['draft', 'sent']:
            raise UserError("Status harus draft atau sent")
        
        self._validate_npwp()
        
    def _validate_npwp(self):
        num_digits = sum(c.isdigit() for c in self.npwp)

        if num_digits < 10:
            raise UserError("NPWP harus memiliki minimal 10 digit")
        
        # pattern = r'^\d{10,}$'
        # return re.match(pattern, self.npwp) is not None

    def sale_order_check_approve(self):
        self.check_due()

        self._validate_order()
        for order in self:
            order.order_line.validate_line()

            partner = order.partner_id.parent_id or order.partner_id
            if not partner.property_payment_term_id:
                raise UserError("Payment Term pada Master Data Customer harus diisi")
            if not partner.active_limit:
                raise UserError("Credit Limit pada Master Data Customer harus diisi")
            if order.payment_term_id != partner.property_payment_term_id:
                raise UserError("Payment Term berbeda pada Master Data Customer")
            if (partner.customer_type == 'pkp' or order.customer_type == 'pkp') and order.npwp != partner.npwp:
                raise UserError("NPWP berbeda pada Master Data Customer")
            if (partner.customer_type == 'pkp' or order.customer_type == 'pkp') and order.sppkp != partner.sppkp:
                raise UserError("SPPKP berbeda pada Master Data Customer")
            if not order.client_order_ref and order.create_date > datetime(2024, 6, 27):
                raise UserError("Customer Reference kosong, di isi dengan NO PO jika PO tidak ada mohon ditulis Tanpa PO")
            if not order.user_id.active:
                raise UserError("Salesperson sudah tidak aktif, mohon diisi yang benar pada data SO dan Contact")
            
    def sale_order_approve(self):
        self.check_due()

        self._validate_order()
        for order in self:
            order.order_line.validate_line()

            partner = order.partner_id.parent_id or order.partner_id
            if not partner.property_payment_term_id:
                raise UserError("Payment Term pada Master Data Customer harus diisi")
            if not partner.active_limit:
                raise UserError("Credit Limit pada Master Data Customer harus diisi")
            if order.payment_term_id != partner.property_payment_term_id:
                raise UserError("Payment Term berbeda pada Master Data Customer")
            if (partner.customer_type == 'pkp' or order.customer_type == 'pkp') and order.npwp != partner.npwp:
                raise UserError("NPWP berbeda pada Master Data Customer")
            if (partner.customer_type == 'pkp' or order.customer_type == 'pkp') and order.sppkp != partner.sppkp:
                raise UserError("SPPKP berbeda pada Master Data Customer")
            if not order.client_order_ref and order.create_date > datetime(2024, 6, 27):
                raise UserError("Customer Reference kosong, di isi dengan NO PO jika PO tidak ada mohon ditulis Tanpa PO")
            if not order.user_id.active:
                raise UserError("Salesperson sudah tidak aktif, mohon diisi yang benar pada data SO dan Contact")
            
            if order.validate_partner_invoice_due():
                return self._create_notification_action('Notification', 'Terdapat invoice yang telah melewati batas waktu, mohon perbarui pada dokumen Due Extension')
            
            if order._requires_approval_margin_leader():
                order.approval_status = 'pengajuan2'
                return self._create_approval_notification('Pimpinan')
            elif order._requires_approval_margin_manager():
                order.approval_status = 'pengajuan1'
                return self._create_approval_notification('Sales Manager')
            
            raise UserError("Bisa langsung Confirm")
        
    def send_notif_to_salesperson(self, cancel=False):

        if not cancel:
            grouping_so = self.search([
                ('partner_id.parent_id.id', '=', self.partner_id.parent_id.id),
                ('partner_id.site_id.id', '=', self.partner_id.site_id.id),
            ])
        else:
            grouping_so = self.search([
                ('partner_id.parent_id.id', '=', self.partner_id.parent_id.id),
                ('partner_id.site_id.id', '=', self.partner_id.site_id.id),
                ('id', '!=', self.id),
            ])
        # Kelompokkan data berdasarkan salesperson
        salesperson_data = {}
        for rec in grouping_so:
            if rec.user_id.id not in salesperson_data:
                salesperson_data[rec.user_id.id] = {'name': rec.user_id.name, 'orders': [], 'total_amount': 0, 'sum_total_amount': 0, 'business_partner': '', 'site': ''}  # Menetapkan nilai awal untuk 'site'
            if rec.picking_ids:
                if not any(picking.state in ['assigned', 'confirmed', 'waiting'] for picking in rec.picking_ids):
                    continue
                if all(picking.state == 'done' for picking in rec.picking_ids):
                    continue
                if all(picking.state == 'cancel' for picking in rec.picking_ids):
                    continue
            if not rec.partner_id.main_parent_id.use_so_approval:
                continue
            order_total_amount = rec.amount_total  # Mengakses langsung rec.amount_total
            salesperson_data[rec.user_id.id]['orders'].append({
                'order_name': rec.name,
                'parent_name': rec.partner_id.name,
                'site_name': rec.partner_id.site_id.name,
                'total_amount': rec.amount_total,
            })
            salesperson_data[rec.user_id.id]['sum_total_amount'] += order_total_amount
            salesperson_data[rec.user_id.id]['business_partner'] = grouping_so[0].partner_id.main_parent_id.name
            salesperson_data[rec.user_id.id]['site'] = grouping_so[0].partner_id.site_id.name  # Menambahkan nilai hanya jika ada

        # Kirim email untuk setiap salesperson
        for salesperson_id, data in salesperson_data.items():
            if data['orders']:
                # Buat isi tabel untuk email
                table_content = ''
                for order_data in data['orders']:
                    table_content += f"""
                        <tr>
                            <td>{order_data['order_name']}</td>
                            <td>{order_data['parent_name']}</td>
                            <td>{order_data['site_name']}</td>
                            <td>{order_data['total_amount']}</td>
                        </tr>
                    """

                # Dapatkan email salesperson
                salesperson_email = self.env['res.users'].browse(salesperson_id).partner_id.email

                # Kirim email hanya jika ada data yang dikumpulkan
                template = self.env.ref('indoteknik_custom.mail_template_sale_order_notification_to_salesperson')
                email_body = template.body_html.replace('${table_content}', table_content)
                email_body = email_body.replace('${salesperson_name}', data['name'])
                email_body = email_body.replace('${sum_total_amount}', str(data['sum_total_amount']))  
                email_body = email_body.replace('${site}', str(data['site']))  
                email_body = email_body.replace('${business_partner}', str(data['business_partner']))  
                # Kirim email
                self.env['mail.mail'].create({
                    'subject': 'Notification: Sale Orders',
                    'body_html': email_body,
                    'email_to': salesperson_email,
                }).send()
        
    def action_confirm(self):
        for order in self:
            order.sale_order_check_approve()
            order._validate_order()
            order.order_line.validate_line()
            
            main_parent = order.partner_id.get_main_parent()
            SYSTEM_UID = 25
            FROM_WEBSITE = order.create_uid.id == SYSTEM_UID
            
            if FROM_WEBSITE and main_parent.use_so_approval and order.web_approval not in ['cust_procurement', 'cust_director']:
                raise UserError("This order not yet approved by customer procurement or director")

            if not order.client_order_ref and order.create_date > datetime(2024, 6, 27):
                raise UserError("Customer Reference kosong, di isi dengan NO PO jika PO tidak ada mohon ditulis Tanpa PO")
            
            if order.validate_partner_invoice_due():
                return self._create_notification_action('Notification', 'Terdapat invoice yang telah melewati batas waktu, mohon perbarui pada dokumen Due Extension')
            
            if order._requires_approval_margin_leader():
                order.approval_status = 'pengajuan2'
                return self._create_approval_notification('Pimpinan')
            elif order._requires_approval_margin_manager():
                order.approval_status = 'pengajuan1'
                return self._create_approval_notification('Sales Manager')
            
            order.approval_status = 'approved'
            order._set_sppkp_npwp_contact()
            order.calculate_line_no()
            order.send_notif_to_salesperson()
            # order.order_line.get_reserved_from()

        res = super(SaleOrder, self).action_confirm()
        return res

    def action_cancel(self):
        # TODO stephan prevent cancel if have invoice, do, and po
        main_parent = self.partner_id.get_main_parent()
        if self._name != 'sale.order':
            return super(SaleOrder, self).action_cancel()
        
        if self.have_outstanding_invoice:
            raise UserError("Invoice harus di Cancel dahulu")
        elif self.have_outstanding_picking:
            raise UserError("DO harus di Cancel dahulu")
        
        if not self.web_approval:
            self.web_approval = 'company'
        # elif self.have_outstanding_po:
        #     raise UserError("PO harus di Cancel dahulu")

        self.approval_status = False
        self.due_id = False
        if main_parent.use_so_approval:
            self.send_notif_to_salesperson(cancel=True)
        return super(SaleOrder, self).action_cancel()
    
    def validate_partner_invoice_due(self):
        parent_id = self.partner_id.parent_id.id
        parent_id =  parent_id if parent_id else self.partner_id.id

        if self.due_id and self.due_id.is_approve == False:
            raise UserError('Document Over Due Yang Anda Buat Belum Di Approve')
        
        query = [
            ('partner_id', '=', parent_id),
            ('state', '=', 'posted'),
            ('move_type', '=', 'out_invoice'),
            ('amount_residual_signed', '>', 0)
        ]
        invoices = self.env['account.move'].search(query, order='invoice_date')

        if invoices:
            if not self.env.user.is_leader and not self.env.user.is_sales_manager:
                due_extension = self.env['due.extension'].create([{
                    'partner_id': parent_id,
                    'day_extension': '3',
                    'order_id': self.id,
                }])
                due_extension.generate_due_line()
                self.due_id = due_extension.id
                if len(self.due_id.due_line) > 0:
                    return True
                else:
                    due_extension.unlink()
                    return False
            
    def _requires_approval_margin_leader(self):
        return self.total_percent_margin <= 13 and not self.env.user.is_leader
            
    def _requires_approval_margin_manager(self):
        return self.total_percent_margin <= 20 and not self.env.user.is_leader and not self.env.user.is_sales_manager
    
    def _create_approval_notification(self, approval_role):
        title = 'Warning'
        message = f'SO butuh approval {approval_role}'
        return self._create_notification_action(title, message)
    
    def _create_notification_action(self, title, message):
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': { 'title': title, 'message': message, 'next': {'type': 'ir.actions.act_window_close'} },
        }
    
    def _set_sppkp_npwp_contact(self): 
        partner = self.partner_id.parent_id or self.partner_id

        if not partner.sppkp or not partner.npwp or not partner.email or partner.customer_type:
            partner.customer_type = self.customer_type
            partner.npwp = self.npwp
            partner.sppkp = self.sppkp
            partner.email = self.email
    
    def _compute_total_margin(self):
        for order in self:
            total_margin = sum(line.item_margin for line in order.order_line if line.product_id)
            order.total_margin = total_margin
    
    def _compute_total_percent_margin(self):
        for order in self:
            if order.amount_untaxed == 0:
                order.total_percent_margin = 0
                continue
            if order.shipping_cost_covered == 'indoteknik':
                delivery_amt = order.delivery_amt
            else:
                delivery_amt = 0
            order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt)) * 100, 2)
            # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed)) * 100, 2)

    @api.onchange('sales_tax_id')
    def onchange_sales_tax_id(self):
        for line in self.order_line:
            line.product_id_change()

    def _compute_grand_total(self):
        for order in self:
            if order.shipping_cost_covered == 'customer':
                order.grand_total = order.delivery_amt + order.amount_total
            else:
                order.grand_total = order.amount_total

    def action_apply_voucher(self):
        for line in self.order_line:
            if line.order_promotion_id:
                raise UserError('Voucher tidak dapat digabung dengan promotion program')

        voucher = self.voucher_id
        if voucher.limit > 0 and voucher.count_order >= voucher.limit:
            raise UserError('Voucher tidak dapat digunakan karena sudah habis digunakan')
        
        partner_voucher_orders = []
        for order in voucher.order_ids:
            if order.partner_id.id == self.partner_id.id:
                partner_voucher_orders.append(order)
        
        if voucher.limit_user > 0 and len(partner_voucher_orders) >= voucher.limit_user:
            raise UserError('Voucher tidak dapat digunakan karena Customer ini sudah menghabiskan kuota voucher')
        
        if self.pricelist_id.id in [x.id for x in voucher.excl_pricelist_ids]:
            raise UserError('Voucher tidak dapat digunakan karena pricelist ini tidak berlaku pada voucher')
        
        self.apply_voucher()
    
    def apply_voucher(self):
        order_line = []
        for line in self.order_line:
            order_line.append({
                'product_id': line.product_id,
                'price': line.price_unit,
                'discount': line.discount,
                'qty': line.product_uom_qty,
                'subtotal': line.price_subtotal
            })
        voucher = self.voucher_id.apply(order_line)

        for line in self.order_line:
            line.initial_discount = line.discount
            
            voucher_type = voucher['type']
            used_total = voucher['total'][voucher_type]
            used_discount = voucher['discount'][voucher_type]

            manufacture_id = line.product_id.x_manufacture.id
            if voucher_type == 'brand':
                used_total = used_total.get(manufacture_id)
                used_discount = used_discount.get(manufacture_id)

            if not used_total or not used_discount:
                continue

            line_contribution = line.price_subtotal / used_total
            line_voucher = used_discount * line_contribution
            line_voucher_item = line_voucher / line.product_uom_qty
            
            line_price_unit = line.price_unit / 1.11 if any(tax.id == 23 for tax in line.tax_id) else line.price_unit
            line_discount_item = line_price_unit * line.discount / 100 + line_voucher_item
            line_voucher_item = line_discount_item / line_price_unit * 100
            
            line.amount_voucher_disc = line_voucher
            line.discount = line_voucher_item

        self.amount_voucher_disc = voucher['discount']['all']
        self.applied_voucher_id = self.voucher_id

    def cancel_voucher(self):
        self.applied_voucher_id = False 
        self.amount_voucher_disc = 0
        for line in self.order_line:
            line.amount_voucher_disc = 0
            line.discount = line.initial_discount
            line.initial_discount = False

    def action_web_approve(self):
        if self.env.uid != self.partner_id.user_id.id:
            raise UserError('You are not authorized to approve this order. Only %s can approve this order.' % self.partner_id.user_id.name)
        
        self.web_approval = 'company'
        template = self.env.ref('indoteknik_custom.mail_template_sale_order_web_approve_notification')
        template.send_mail(self.id, force_send=True)
        
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': 'Notification',
                'message': 'Berhasil approve web order',
                'next': {'type': 'ir.actions.act_window_close'},
            }
        }

    def calculate_selling_price(self):
        # ongkos kirim, biaya pihak ketiga calculate @stephan
        # TODO voucher @stephan
        # vendor hilangin child di field SO Line @stephan
        # button pindahin @stephan
        # last so 1 tahun ke belakang @stephan
        # pastikan harga beli 1 tahun ke belakang jg
        # harga yg didapat dari semua kumpulan parent parner dan child nya
        # counter di klik berapa banyak @stephan
        for order_line in self.order_line:
            if not order_line.product_id:
                continue
            current_time = datetime.now()
            delta_time = current_time - timedelta(days=365)
            delta_time = delta_time.strftime('%Y-%m-%d %H:%M:%S')

            # Initialize partners list with parent_id or partner_id
            partners = []
            parent_id = self.partner_id.parent_id or self.partner_id

            # Add all child_ids and the parent itself to partners as IDs
            partners.extend(parent_id.child_ids.ids)
            partners.append(parent_id.id)

            rec_purchase_price, rec_taxes_id, rec_vendor_id = order_line._get_purchase_price(order_line.product_id)
            state = ['sale', 'done']
            last_so = self.env['sale.order.line'].search([
                # ('order_id.partner_id.id', '=', order_line.order_id.partner_id.id),
                ('order_id.partner_id', 'in', partners),
                ('product_id.id', '=', order_line.product_id.id),
                ('order_id.state', 'in', state),
                ('id', '!=', order_line.id),
                ('order_id.date_order', '>=', delta_time)
            ], limit=1, order='create_date desc')

            if last_so and rec_vendor_id != last_so.vendor_id.id:
                last_so = self.env['sale.order.line'].search([
                    # ('order_id.partner_id.id', '=', order_line.order_id.partner_id.id),
                    ('order_id.partner_id', 'in', partners),
                    ('product_id.id', '=', order_line.product_id.id),
                    ('order_id.state', 'in', state),
                    ('vendor_id', '=', rec_vendor_id),
                    ('id', '!=', order_line.id),
                    ('order_id.date_order', '>=', delta_time)
                ], limit=1, order='create_date desc')

                if last_so and rec_purchase_price != last_so.purchase_price:
                    rec_taxes = self.env['account.tax'].search([('id', '=', rec_taxes_id)], limit=1)
                    if rec_taxes.price_include:
                        selling_price = (rec_purchase_price / 1.11) / (1 - (last_so.item_percent_margin_without_deduction / 100))
                    else:
                        selling_price = rec_purchase_price / (1 - (last_so.item_percent_margin_without_deduction / 100))
                    tax_id = last_so.tax_id
                    for tax in tax_id:
                        if tax.price_include:
                            selling_price = selling_price + (selling_price*11/100)
                        else:
                            selling_price = selling_price
                    discount = 0
                elif last_so:
                    selling_price = last_so.price_unit
                    tax_id = last_so.tax_id
                    discount = last_so.discount
                else:
                    selling_price = order_line.price_unit
                    tax_id = order_line.tax_id
                    discount = order_line.discount

            elif last_so and rec_vendor_id == order_line.vendor_id.id and rec_purchase_price != last_so.purchase_price:
                rec_taxes = self.env['account.tax'].search([('id', '=', rec_taxes_id)], limit=1)
                if rec_taxes.price_include:
                    selling_price = (rec_purchase_price / 1.11) / (1 - (last_so.item_percent_margin_without_deduction / 100))
                else:
                    selling_price = rec_purchase_price / (1 - (last_so.item_percent_margin_without_deduction / 100))
                tax_id = last_so.tax_id
                for tax in tax_id:
                    if tax.price_include:
                        selling_price = selling_price + (selling_price*11/100)
                    else:
                        selling_price = selling_price
                discount = 0

            elif last_so:
                selling_price = last_so.price_unit
                tax_id = last_so.tax_id
                discount = last_so.discount

            else:
                selling_price = order_line.price_unit
                tax_id = order_line.tax_id
                discount = order_line.discount
            order_line.price_unit = selling_price
            order_line.tax_id = tax_id
            order_line.discount = discount
            order_line.order_id.use_button = True