From 3ca53ea0afef07cb79040c9f3c5aa29fa2355c90 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Thu, 27 Mar 2025 08:48:27 +0700 Subject: sale order delay --- indoteknik_custom/__manifest__.py | 1 + indoteknik_custom/models/__init__.py | 1 + indoteknik_custom/models/sale_order_delay.py | 25 +++++++++++++++ indoteknik_custom/models/stock_picking.py | 6 ++-- indoteknik_custom/security/ir.model.access.csv | 1 + indoteknik_custom/views/sale_order_delay.xml | 44 ++++++++++++++++++++++++++ 6 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 indoteknik_custom/models/sale_order_delay.py create mode 100644 indoteknik_custom/views/sale_order_delay.xml (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/__manifest__.py b/indoteknik_custom/__manifest__.py index a7096346..eb00f527 100755 --- a/indoteknik_custom/__manifest__.py +++ b/indoteknik_custom/__manifest__.py @@ -165,6 +165,7 @@ 'views/coretax_faktur.xml', 'views/public_holiday.xml', 'views/stock_inventory.xml', + 'views/sale_order_delay.xml', ], 'demo': [], 'css': [], diff --git a/indoteknik_custom/models/__init__.py b/indoteknik_custom/models/__init__.py index 37a49332..d5cededa 100755 --- a/indoteknik_custom/models/__init__.py +++ b/indoteknik_custom/models/__init__.py @@ -147,3 +147,4 @@ from . import ir_actions_report from . import barcoding_product from . import account_payment_register from . import stock_inventory +from . import sale_order_delay diff --git a/indoteknik_custom/models/sale_order_delay.py b/indoteknik_custom/models/sale_order_delay.py new file mode 100644 index 00000000..7440cd2d --- /dev/null +++ b/indoteknik_custom/models/sale_order_delay.py @@ -0,0 +1,25 @@ +from odoo import api, fields, models + + +class SaleOrderDelay(models.Model): + _name = 'sale.order.delay' + _description = 'Sale Order Delay' + _rec_name = 'so_number' + + so_number = fields.Char(string="SO Number", required=True) + days_delayed = fields.Integer(string="Day ", required=True) + status = fields.Selection([ + ('delayed', 'Delayed'), + ('on track', 'On Track'), + ('early', 'Early') + ], string='Status', required=True) + + @api.model + def create(self, vals): + vals['updated_at'] = fields.Datetime.now() + return super(SaleOrderDelay, self).create(vals) + + def write(self, vals): + vals['updated_at'] = fields.Datetime.now() + return super(SaleOrderDelay, self).write(vals) + \ No newline at end of file diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 6c6cbaa1..a11bf29f 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -16,8 +16,8 @@ import re _logger = logging.getLogger(__name__) _biteship_url = "https://api.biteship.com/v1" -_biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" -# _biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" +# _biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" +_biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" @@ -1241,7 +1241,7 @@ class StockPicking(models.Model): 'confirmed' : 'Indoteknik telah melakukan permintaan pick-up', 'allocated' : 'Kurir akan melakukan pick-up pesanan', 'picking_up' : 'Kurir sedang dalam perjalanan menuju lokasi pick-up', - 'picked' : 'Pesanan sudah di pick-up kurir '+result.get("courier", {}).get("name", ""), + 'picked' : 'Pesanan sudah di pick-up kurir '+result.get("courier", {}).get("company", ""), 'on_hold' : 'Pesanan ditahan sementara karena masalah pengiriman', 'dropping_off' : 'Kurir sudah ditugaskan dan pesanan akan segera diantar ke pembeli', 'delivered' : 'Pesanan telah sampai dan diterima oleh '+result.get("destination", {}).get("contact_name", "") diff --git a/indoteknik_custom/security/ir.model.access.csv b/indoteknik_custom/security/ir.model.access.csv index 4d0e51eb..58562487 100755 --- a/indoteknik_custom/security/ir.model.access.csv +++ b/indoteknik_custom/security/ir.model.access.csv @@ -168,3 +168,4 @@ access_account_payment_register,access.account.payment.register,model_account_pa access_stock_inventory,access.stock.inventory,model_stock_inventory,,1,1,1,1 access_cancel_reason_order,cancel.reason.order,model_cancel_reason_order,,1,1,1,0 access_shipping_option,shipping.option,model_shipping_option,,1,1,1,1 +access_sale_order_delay,sale.order.delay,model_sale_order_delay,,1,1,1,1 diff --git a/indoteknik_custom/views/sale_order_delay.xml b/indoteknik_custom/views/sale_order_delay.xml new file mode 100644 index 00000000..b2aad8eb --- /dev/null +++ b/indoteknik_custom/views/sale_order_delay.xml @@ -0,0 +1,44 @@ + + + + sale.order.delay.tree + sale.order.delay + + + + + + + + + + + Sale Order Delay + ir.actions.act_window + sale.order.delay + tree,form + + + + sale.order.delay.form + sale.order.delay + +
+ + + + + + + +
+
+
+ + +
\ No newline at end of file -- cgit v1.2.3 From 87dad63e8ee0ace13b2d87bae26a045b80409572 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Thu, 27 Mar 2025 10:21:06 +0700 Subject: schduled --- indoteknik_custom/models/sale_order_delay.py | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order_delay.py b/indoteknik_custom/models/sale_order_delay.py index 7440cd2d..e2735a3c 100644 --- a/indoteknik_custom/models/sale_order_delay.py +++ b/indoteknik_custom/models/sale_order_delay.py @@ -14,6 +14,10 @@ class SaleOrderDelay(models.Model): ('early', 'Early') ], string='Status', required=True) + def update_delay(self): + query = "SELECT check_so_delay();" + self.env.cr.execute(query) + @api.model def create(self, vals): vals['updated_at'] = fields.Datetime.now() -- cgit v1.2.3 From 337e86c31691544a49a04e3f8d3a4b259e6b126a Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Thu, 10 Apr 2025 08:51:12 +0700 Subject: testing biteship dinamis eta --- indoteknik_custom/models/sale_order_delay.py | 10 +-- indoteknik_custom/models/stock_picking.py | 91 ++++++++++------------------ 2 files changed, 39 insertions(+), 62 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order_delay.py b/indoteknik_custom/models/sale_order_delay.py index e2735a3c..dfd94650 100644 --- a/indoteknik_custom/models/sale_order_delay.py +++ b/indoteknik_custom/models/sale_order_delay.py @@ -4,26 +4,28 @@ from odoo import api, fields, models class SaleOrderDelay(models.Model): _name = 'sale.order.delay' _description = 'Sale Order Delay' - _rec_name = 'so_number' + _primary_key = 'so_number' so_number = fields.Char(string="SO Number", required=True) - days_delayed = fields.Integer(string="Day ", required=True) + days_delayed = fields.Integer(string="Day Delayed or Erly") status = fields.Selection([ ('delayed', 'Delayed'), ('on track', 'On Track'), ('early', 'Early') ], string='Status', required=True) + _sql_constraints = [ + ('unique_so_number', 'unique(so_number)', 'SO Number must be unique!') + ] + def update_delay(self): query = "SELECT check_so_delay();" self.env.cr.execute(query) @api.model def create(self, vals): - vals['updated_at'] = fields.Datetime.now() return super(SaleOrderDelay, self).create(vals) def write(self, vals): - vals['updated_at'] = fields.Datetime.now() return super(SaleOrderDelay, self).write(vals) \ No newline at end of file diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index a11bf29f..b741e94e 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -16,8 +16,8 @@ import re _logger = logging.getLogger(__name__) _biteship_url = "https://api.biteship.com/v1" -# _biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" -_biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" +_biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" +# _biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" @@ -189,63 +189,12 @@ class StockPicking(models.Model): biteship_id = fields.Char(string="Biteship Respon ID") biteship_tracking_id = fields.Char(string="Biteship Trackcking ID") biteship_waybill_id = fields.Char(string="Biteship Waybill ID") - # estimated_ready_ship_date = fields.Datetime(string='ET Ready to Ship', copy=False, related='sale_id.estimated_ready_ship_date') - # countdown_hours = fields.Float(string='Countdown in Hours', compute='_callculate_sequance', default=False, store=False, compute_sudo=False) - # countdown_ready_to_ship = fields.Char(string='Countdown Ready to Ship', compute='_callculate_sequance', store=False, compute_sudo=False) final_seq = fields.Float(string='Remaining Time') def schduled_update_sequance(self): query = "SELECT update_sequance_stock_picking();" self.env.cr.execute(query) - - - # @api.depends('estimated_ready_ship_date', 'state') - # def _callculate_sequance(self): - # for record in self: - # try : - # if record.estimated_ready_ship_date and record.state not in ('cancel', 'done'): - # rts = record.estimated_ready_ship_date - waktu.now() - # rts_days = rts.days - # rts_hours = divmod(rts.seconds, 3600) - - # estimated_by_erts = rts.total_seconds() / 3600 - - # record.countdown_ready_to_ship = f"{rts_days} days, {rts_hours} hours" - # record.countdown_hours = estimated_by_erts - # else: - # record.countdown_hours = 999999999999 - # record.countdown_ready_to_ship = False - # except Exception as e : - # _logger.error(f"Error calculating sequance {record.id}: {str(e)}") - # print(str(e)) - # return { 'error': str(e) } - - - # @api.depends('estimated_ready_ship_date', 'state') - # def _compute_countdown_hours(self): - # for record in self: - # if record.state in ('cancel', 'done') or not record.estimated_ready_ship_date: - # # Gunakan nilai yang sangat besar sebagai placeholder - # record.countdown_hours = 999999 - # else: - # delta = record.estimated_ready_ship_date - waktu.now() - # record.countdown_hours = delta.total_seconds() / 3600 - - # @api.depends('estimated_ready_ship_date', 'state') - # def _compute_countdown_ready_to_ship(self): - # for record in self: - # if record.state in ('cancel', 'done'): - # record.countdown_ready_to_ship = False - # else: - # if record.estimated_ready_ship_date: - # delta = record.estimated_ready_ship_date - waktu.now() - # days = delta.days - # hours, remainder = divmod(delta.seconds, 3600) - # record.countdown_ready_to_ship = f"{days} days, {hours} hours" - # record.countdown_hours = delta.total_seconds() / 3600 - # else: - # record.countdown_ready_to_ship = False def _compute_lalamove_image_html(self): for record in self: @@ -1182,6 +1131,8 @@ class StockPicking(models.Model): self.ensure_one() order = self.env['sale.order'].search([('name', '=', self.sale_id.name)], limit=1) + + sale_order_delay = self.env['sale.order.delay'].search([('so_number', '=', order.name)], limit=1) response = { 'delivery_order': { @@ -1197,13 +1148,24 @@ class StockPicking(models.Model): 'delivery_status': None, 'eta': self.generate_eta_delivery(), 'is_biteship': True if self.biteship_id else False, - 'manifests': self.get_manifests() + 'manifests': self.get_manifests(), + 'is_delay': True if sale_order_delay and sale_order_delay.status == 'delayed' else False } if self.biteship_id : histori = self.get_manifest_biteship() - eta_start = order.date_order + timedelta(days=order.estimated_arrival_days_start) - eta_end = order.date_order + timedelta(days=order.estimated_arrival_days) + day_start = order.estomated_arrival_days_start + day_end = order.estomated_arrival_days + if sale_order_delay: + if sale_order_delay.status == 'delayed': + day_start = day_start + sale_order_delay.days_delayed + day_end = day_end + sale_order_delay.days_delayed + elif sale_order_delay.status == 'early': + day_start = day_start - sale_order_delay.days_delayed + day_end = day_end - sale_order_delay.days_delayed + + eta_start = order.date_order + timedelta(days=day_start) + eta_end = order.date_order + timedelta(days=day_end) formatted_eta = f"{eta_start.strftime('%d %b')} - {eta_end.strftime('%d %b %Y')}" response['eta'] = formatted_eta response['manifests'] = histori.get("manifests", []) @@ -1297,18 +1259,31 @@ class StockPicking(models.Model): current_date = datetime.datetime.now() prepare_days = 3 start_date = self.driver_departure_date or self.create_date + + + add_day_start = 0 + add_day_end = 0 + sale_order_delay = self.env['sale.order.delay'].search([('so_number', '=', self.sale_id.name)], limit=1) + if sale_order_delay: + if sale_order_delay.status == 'delayed': + add_day_start = sale_order_delay.days_delayed + add_day_end = sale_order_delay.days_delayed + elif sale_order_delay.status == 'early': + add_day_start = -abs(sale_order_delay.days_delayed) + add_day_end = -abs(sale_order_delay.days_delayed) ead = self.sale_id.estimated_arrival_days or 0 if not self.driver_departure_date: ead += prepare_days ead_datetime = datetime.timedelta(days=ead) - fastest_eta = start_date + ead_datetime + fastest_eta = start_date + ead_datetime + datetime.timedelta(days=add_day_start) + if not self.driver_departure_date and fastest_eta < current_date: fastest_eta = current_date + ead_datetime longest_days = 3 - longest_eta = fastest_eta + datetime.timedelta(days=longest_days) + longest_eta = fastest_eta + datetime.timedelta(days=longest_days + add_day_end) format_time = '%d %b %Y' format_time_fastest = '%d %b' if fastest_eta.year == longest_eta.year else format_time -- cgit v1.2.3 From 62f9c93c02a1f8b12ecd7bf50f850c43dd7c2c49 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Fri, 11 Apr 2025 10:14:08 +0700 Subject: dirver departure date --- indoteknik_custom/models/stock_picking.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index b741e94e..d7e8e0e8 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -16,8 +16,8 @@ import re _logger = logging.getLogger(__name__) _biteship_url = "https://api.biteship.com/v1" -_biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" -# _biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" +# _biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" +_biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" @@ -1142,6 +1142,7 @@ class StockPicking(models.Model): 'receiver_name': '', 'receiver_city': '' }, + 'delivered_date': self.driver_departure_date or False, 'delivered': False, 'status': self.shipping_status, 'waybill_number': self.delivery_tracking_no or '', @@ -1154,8 +1155,8 @@ class StockPicking(models.Model): if self.biteship_id : histori = self.get_manifest_biteship() - day_start = order.estomated_arrival_days_start - day_end = order.estomated_arrival_days + day_start = order.estimated_arrival_days_start + day_end = order.estimated_arrival_days if sale_order_delay: if sale_order_delay.status == 'delayed': day_start = day_start + sale_order_delay.days_delayed @@ -1192,7 +1193,6 @@ class StockPicking(models.Model): "Content-Type": "application/json" } - manifests = [] try: @@ -1206,7 +1206,7 @@ class StockPicking(models.Model): 'picked' : 'Pesanan sudah di pick-up kurir '+result.get("courier", {}).get("company", ""), 'on_hold' : 'Pesanan ditahan sementara karena masalah pengiriman', 'dropping_off' : 'Kurir sudah ditugaskan dan pesanan akan segera diantar ke pembeli', - 'delivered' : 'Pesanan telah sampai dan diterima oleh '+result.get("destination", {}).get("contact_name", "") + 'delivered' : f'Pesanan telah sampai dan diterima oleh {result.get("destination", {}).get("contact_name", "")}' } if(result.get('success') == True): history = result.get("history", []) -- cgit v1.2.3 From ef00237c7b6b3aed4f6040d1f124199d3551561e Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Fri, 11 Apr 2025 14:50:53 +0700 Subject: expected delivery date manifest --- indoteknik_custom/models/stock_picking.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index d7e8e0e8..54256299 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -1137,15 +1137,15 @@ class StockPicking(models.Model): response = { 'delivery_order': { 'name': self.name, - 'carrier': self.carrier_id.name or '', - 'service' : order.delivery_service_type or '', + 'carrier': self.carrier_id.name or '-', + 'service' : order.delivery_service_type or '-', 'receiver_name': '', 'receiver_city': '' }, - 'delivered_date': self.driver_departure_date or False, + 'delivered_date': self.driver_departure_date.strftime('%d %b %Y') if self.driver_departure_date != False else '-', 'delivered': False, 'status': self.shipping_status, - 'waybill_number': self.delivery_tracking_no or '', + 'waybill_number': self.delivery_tracking_no or '-', 'delivery_status': None, 'eta': self.generate_eta_delivery(), 'is_biteship': True if self.biteship_id else False, @@ -1205,7 +1205,7 @@ class StockPicking(models.Model): 'picking_up' : 'Kurir sedang dalam perjalanan menuju lokasi pick-up', 'picked' : 'Pesanan sudah di pick-up kurir '+result.get("courier", {}).get("company", ""), 'on_hold' : 'Pesanan ditahan sementara karena masalah pengiriman', - 'dropping_off' : 'Kurir sudah ditugaskan dan pesanan akan segera diantar ke pembeli', + 'dropping_off' : 'Kurir sudah ditugaskan dan pesanan akan segera diantar ke pembeli', 'delivered' : f'Pesanan telah sampai dan diterima oleh {result.get("destination", {}).get("contact_name", "")}' } if(result.get('success') == True): -- cgit v1.2.3 From 6eb0b48ad5c418f565efdf1a60d221a10465b0b8 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Mon, 14 Apr 2025 16:48:09 +0700 Subject: stock picking mapping --- indoteknik_custom/models/stock_picking.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 54256299..ba7a9452 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -16,8 +16,8 @@ import re _logger = logging.getLogger(__name__) _biteship_url = "https://api.biteship.com/v1" -# _biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" -_biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" +_biteship_api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" +# _biteship_api_key = "biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTc0MTE1NTU4M30.pbFCai9QJv8iWhgdosf8ScVmEeP3e5blrn33CHe7Hgo" -- cgit v1.2.3 From fb50d10576f2e5d16faba612dfd1565f7168f655 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Wed, 16 Apr 2025 14:33:31 +0700 Subject: FEEDBACK --- indoteknik_custom/models/stock_picking.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 4a200ac5..f2b69b55 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -1406,7 +1406,10 @@ class StockPicking(models.Model): "delivered": status } - return manifests + return { + "manifests": [], + "delivered": False + } except Exception as e : _logger.error(f"Error fetching Biteship order for picking {self.id}: {str(e)}") return { 'error': str(e) } -- cgit v1.2.3 From d9d8b9f3afc0ad60ca1199b08ab6e2836663a0de Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Thu, 24 Apr 2025 13:54:06 +0700 Subject: fixing revisi renca --- indoteknik_custom/models/sale_order.py | 22 +++++++++++++++++----- indoteknik_custom/models/stock_picking.py | 19 ++++++------------- 2 files changed, 23 insertions(+), 18 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index c83ffd61..a7ee9db8 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -496,7 +496,7 @@ class SaleOrder(models.Model): @api.depends('date_order', 'estimated_arrival_days', 'state', 'estimated_arrival_days_start') def _compute_eta_date(self): - current_date = datetime.now().date() + current_date = datetime.now() for rec in self: if rec.date_order and rec.state not in ['cancel'] and rec.estimated_arrival_days and rec.estimated_arrival_days_start: rec.eta_date = current_date + timedelta(days=rec.estimated_arrival_days) @@ -507,7 +507,19 @@ class SaleOrder(models.Model): def get_days_until_next_business_day(self,start_date=None, *args, **kwargs): - today = start_date or datetime.today().date() + now = start_date or datetime.now() + + # Jika hanya diberikan tanggal (tanpa jam), asumsikan jam 00:00 + if isinstance(now, datetime): + order_datetime = now + else: + order_datetime = datetime.combine(now, datetime.min.time()) + + today = order_datetime.date() + + if order_datetime.time() > datetime.strptime("15:00", "%H:%M").time(): + today += timedelta(days=1) + offset = 0 # Counter jumlah hari yang ditambahkan holiday = self.env['hr.public.holiday'] @@ -568,13 +580,13 @@ class SaleOrder(models.Model): rec.expected_ready_to_ship = False return - current_date = datetime.now().date() + current_date = datetime.now() max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - sum_days = max_slatime + self.get_days_until_next_business_day(current_date) - 1 + sum_days = max_slatime + self.get_days_until_next_business_day(current_date) if not rec.estimated_arrival_days: rec.estimated_arrival_days = sum_days @@ -597,7 +609,7 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - sum_days = max_slatime + self.get_days_until_next_business_day(current_date) - 1 + sum_days = max_slatime + self.get_days_until_next_business_day(current_date) eta_minimum = current_date + timedelta(days=sum_days) if expected_date < eta_minimum: diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index f2b69b55..aa616e62 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -1442,8 +1442,10 @@ class StockPicking(models.Model): def generate_eta_delivery(self): current_date = datetime.datetime.now() - prepare_days = 3 - start_date = self.driver_departure_date or self.create_date + days_start = self.sale_id.estimated_arrival_days_start or self.sale_id.estimated_arrival_days + days_end = self.sale_id.estimated_arrival_days or (self.sale_id.estimated_arrival_days + 3) + start_date = self.sale_id.create_date + datetime.timedelta(days=days_start) + end_date = self.sale_id.create_date + datetime.timedelta(days=days_end) add_day_start = 0 @@ -1456,19 +1458,10 @@ class StockPicking(models.Model): elif sale_order_delay.status == 'early': add_day_start = -abs(sale_order_delay.days_delayed) add_day_end = -abs(sale_order_delay.days_delayed) - - ead = self.sale_id.estimated_arrival_days or 0 - if not self.driver_departure_date: - ead += prepare_days - - ead_datetime = datetime.timedelta(days=ead) - fastest_eta = start_date + ead_datetime + datetime.timedelta(days=add_day_start) - if not self.driver_departure_date and fastest_eta < current_date: - fastest_eta = current_date + ead_datetime + fastest_eta = start_date +datetime.timedelta(days=add_day_start + add_day_start) - longest_days = 3 - longest_eta = fastest_eta + datetime.timedelta(days=longest_days + add_day_end) + longest_eta = end_date + datetime.timedelta(days=add_day_end) format_time = '%d %b %Y' format_time_fastest = '%d %b' if fastest_eta.year == longest_eta.year else format_time -- cgit v1.2.3 From 914705630f61f2e02f15ee24a479191e945a0f22 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Sat, 26 Apr 2025 08:39:32 +0700 Subject: handle bugs additional time when checkout > 15.00 --- indoteknik_custom/models/sale_order.py | 49 ++++++++++++++++++------------- indoteknik_custom/models/stock_picking.py | 8 ++--- 2 files changed, 33 insertions(+), 24 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 3117a330..1e40d15e 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -6,6 +6,7 @@ from datetime import datetime, timedelta import logging, random, string, requests, math, json, re, qrcode, base64 from io import BytesIO from collections import defaultdict +import pytz _logger = logging.getLogger(__name__) @@ -540,34 +541,42 @@ class SaleOrder(models.Model): rec.eta_date_start = False - def get_days_until_next_business_day(self,start_date=None, *args, **kwargs): - now = start_date or datetime.now() - - # Jika hanya diberikan tanggal (tanpa jam), asumsikan jam 00:00 - if isinstance(now, datetime): - order_datetime = now - else: - order_datetime = datetime.combine(now, datetime.min.time()) - - today = order_datetime.date() - - if order_datetime.time() > datetime.strptime("15:00", "%H:%M").time(): - today += timedelta(days=1) + def get_days_until_next_business_day(self, start_date=None, *args, **kwargs): + jakarta = pytz.timezone("Asia/Jakarta") + current = datetime.now(jakarta) - offset = 0 # Counter jumlah hari yang ditambahkan + offset = 0 + + # Gunakan current time kalau start_date tidak diberikan + if start_date is None: + start_date = current + + # Pastikan start_date pakai timezone Jakarta + if start_date.tzinfo is None: + start_date = jakarta.localize(start_date) + + # Jika sudah lewat jam 15:00, mulai dari hari berikutnya + batas_waktu = datetime.strptime("15:00", "%H:%M").time() + if start_date.time() > batas_waktu: + offset += 1 + + current_day = start_date.date() holiday = self.env['hr.public.holiday'] - while True : - today += timedelta(days=1) + while True: + # Tambah satu hari, cek apakah hari kerja + current_day += timedelta(days=1) offset += 1 - - if today.weekday() >= 5: + + # Lewati weekend + if current_day.weekday() >= 5: continue - is_holiday = holiday.search([("start_date", "=", today)]) + # Lewati hari libur + is_holiday = holiday.search([("start_date", "=", current_day)]) if is_holiday: continue - + break return offset diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 36129f00..38a1173c 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -562,6 +562,10 @@ class StockPicking(models.Model): }) payload = { + "origin_coordinate" :{ + "latitude": -6.3031123, + "longitude" : 106.7794934999 + }, "reference_id " : self.sale_id.name, "shipper_contact_name": self.carrier_id.pic_name or '', "shipper_contact_phone": self.carrier_id.pic_phone or '', @@ -585,10 +589,6 @@ class StockPicking(models.Model): # Cek jika pengiriman instant atau same_day if self.sale_id.delivery_service_type and ("instant" in self.sale_id.delivery_service_type or "same_day" in self.sale_id.delivery_service_type): payload.update({ - "origin_coordinate" :{ - "latitude": -6.3031123, - "longitude" : 106.7794934999 - }, "destination_coordinate" : { "latitude": self.real_shipping_id.latitude, "longitude": self.real_shipping_id.longtitude, -- cgit v1.2.3 From 509eb9406e6c48caf3e6366c3d8ac60643b71546 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Tue, 29 Apr 2025 09:09:05 +0700 Subject: fixing jam 15 --- indoteknik_custom/models/sale_order.py | 24 +++++++++++++++--------- indoteknik_custom/models/stock_picking.py | 1 - 2 files changed, 15 insertions(+), 10 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 1e40d15e..91905037 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -2,7 +2,7 @@ from re import search from odoo import fields, models, api, _ from odoo.exceptions import UserError, ValidationError -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone import logging, random, string, requests, math, json, re, qrcode, base64 from io import BytesIO from collections import defaultdict @@ -566,16 +566,20 @@ class SaleOrder(models.Model): while True: # Tambah satu hari, cek apakah hari kerja current_day += timedelta(days=1) - offset += 1 # Lewati weekend - if current_day.weekday() >= 5: - continue + is_weekend = current_day.weekday() >= 5 + + if is_weekend: + offset += 1 + continue # Lewati hari libur is_holiday = holiday.search([("start_date", "=", current_day)]) + if is_holiday: - continue + offset += 1 + continue break @@ -588,7 +592,7 @@ class SaleOrder(models.Model): # Cek apakah SEMUA produk memiliki qty_free_bandengan >= qty_needed all_fast_products = all(product.product_id.qty_free_bandengan >= product.product_uom_qty for product in products) if all_fast_products: - return {'slatime': 1, 'include_instant': include_instant} + return {'slatime': 0, 'include_instant': include_instant} # Cari semua vendor pemenang untuk produk yang diberikan vendors = self.env['purchase.pricelist'].search([ @@ -623,7 +627,8 @@ class SaleOrder(models.Model): rec.expected_ready_to_ship = False return - current_date = datetime.now() + jakarta = pytz.timezone("Asia/Jakarta") + current_date = datetime.now(jakarta) max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) @@ -634,6 +639,7 @@ class SaleOrder(models.Model): rec.estimated_arrival_days = sum_days eta_date = current_date + timedelta(days=sum_days) + eta_date = eta_date.astimezone(timezone.utc).replace(tzinfo=None) rec.commitment_date = eta_date rec.expected_ready_to_ship = eta_date @@ -645,7 +651,7 @@ class SaleOrder(models.Model): def _validate_expected_ready_ship_date(self): for rec in self: if rec.expected_ready_to_ship and rec.commitment_date: - current_date = datetime.now().date() + current_date = datetime.now() # Hanya membandingkan tanggal saja, tanpa jam expected_date = rec.expected_ready_to_ship.date() @@ -655,7 +661,7 @@ class SaleOrder(models.Model): sum_days = max_slatime + self.get_days_until_next_business_day(current_date) eta_minimum = current_date + timedelta(days=sum_days) - if expected_date < eta_minimum: + if expected_date < eta_minimum.date(): rec.expected_ready_to_ship = eta_minimum raise ValidationError( "Tanggal 'Expected Ready to Ship' tidak boleh lebih kecil dari {}. Mohon pilih tanggal minimal {}." diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 38a1173c..39c74aa2 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -523,7 +523,6 @@ class StockPicking(models.Model): raise UserError(f"Kesalahan tidak terduga: {str(e)}") def action_send_to_biteship(self): - if self.biteship_tracking_id: raise UserError(f"Order ini sudah dikirim ke Biteship. Dengan Tracking Id: {self.biteship_tracking_id}") -- cgit v1.2.3 From c77d250353dbed0ba1ec5cd8abd940ba95a011fc Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Wed, 30 Apr 2025 13:55:26 +0700 Subject: handle 15am dan holidays --- indoteknik_custom/models/sale_order.py | 45 +++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 17 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 91905037..25c1b3a8 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -541,12 +541,13 @@ class SaleOrder(models.Model): rec.eta_date_start = False - def get_days_until_next_business_day(self, start_date=None, *args, **kwargs): + def handling_order_after_3pm(self, start_date=None, *args, **kwargs): jakarta = pytz.timezone("Asia/Jakarta") current = datetime.now(jakarta) offset = 0 - + + # Gunakan current time kalau start_date tidak diberikan if start_date is None: start_date = current @@ -559,28 +560,31 @@ class SaleOrder(models.Model): batas_waktu = datetime.strptime("15:00", "%H:%M").time() if start_date.time() > batas_waktu: offset += 1 + + return offset + + def get_days_until_next_business_day(self, start_date=None, *args, **kwargs): + jakarta = pytz.timezone("Asia/Jakarta") + current = datetime.now(jakarta) + + offset = 0 + i = 0 current_day = start_date.date() holiday = self.env['hr.public.holiday'] - + while True: - # Tambah satu hari, cek apakah hari kerja - current_day += timedelta(days=1) - + # # Tambah satu hari, cek apakah hari kerja + current_day += timedelta(days=i) + i = 1 + # Lewati weekend is_weekend = current_day.weekday() >= 5 - - if is_weekend: - offset += 1 - continue - - # Lewati hari libur is_holiday = holiday.search([("start_date", "=", current_day)]) - - if is_holiday: + if is_weekend or is_holiday: offset += 1 continue - + break return offset @@ -633,8 +637,11 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) + + days_after_3pm = self.handling_order_after_3pm(current_date) + date_after_3pm = current_date + timedelta(days=days_after_3pm) - sum_days = max_slatime + self.get_days_until_next_business_day(current_date) + sum_days = max_slatime + self.get_days_until_next_business_day(date_after_3pm) if not rec.estimated_arrival_days: rec.estimated_arrival_days = sum_days @@ -658,7 +665,11 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - sum_days = max_slatime + self.get_days_until_next_business_day(current_date) + + days_after_3pm = self.handling_order_after_3pm(current_date) + date_after_3pm = current_date + timedelta(days=days_after_3pm) + + sum_days = max_slatime + self.get_days_until_next_business_day(date_after_3pm) eta_minimum = current_date + timedelta(days=sum_days) if expected_date < eta_minimum.date(): -- cgit v1.2.3 From 7897614cee8a347dfdd933df72db95859cb1a558 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Wed, 30 Apr 2025 16:43:38 +0700 Subject: fixing handle 15 pm, weekend, and holidays --- indoteknik_custom/models/product_template.py | 3 ++ indoteknik_custom/models/sale_order.py | 71 +++++++++++++++++++--------- 2 files changed, 51 insertions(+), 23 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/product_template.py b/indoteknik_custom/models/product_template.py index e6a01a04..56ae3087 100755 --- a/indoteknik_custom/models/product_template.py +++ b/indoteknik_custom/models/product_template.py @@ -341,6 +341,9 @@ class ProductTemplate(models.Model): 'search_key':[item_code], } response = requests.post(url, headers=headers, json=json_data) + if response.status_code != 200: + return 0 + datas = json.loads(response.text)['data'] qty = 0 for data in datas: diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 25c1b3a8..795bfa0b 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -565,29 +565,58 @@ class SaleOrder(models.Model): def get_days_until_next_business_day(self, start_date=None, *args, **kwargs): jakarta = pytz.timezone("Asia/Jakarta") - current = datetime.now(jakarta) - + now = datetime.now(jakarta) + + if start_date is None: + start_date = now + + if start_date.tzinfo is None: + start_date = jakarta.localize(start_date) + + holiday = self.env['hr.public.holiday'] + batas_waktu = datetime.strptime("15:00", "%H:%M").time() + current_day = start_date.date() offset = 0 + + # Step 1: Lewat jam 15 → Tambah 1 hari + if start_date.time() > batas_waktu: + offset += 1 + + # Step 2: Hitung hari libur selama offset itu + i = 0 + total_days = 0 + while i < offset: + current_day += timedelta(days=1) + total_days += 1 + is_weekend = current_day.weekday() >= 5 + is_holiday = holiday.search([("start_date", "=", current_day)]) + if not is_weekend and not is_holiday: + i += 1 # hanya hitung hari kerja + + # Step 3: Tambah 1 hari masa persiapan gudang i = 0 + while i < 1: + current_day += timedelta(days=1) + total_days += 1 + is_weekend = current_day.weekday() >= 5 + is_holiday = holiday.search([("start_date", "=", current_day)]) + if not is_weekend and not is_holiday: + i += 1 - current_day = start_date.date() - holiday = self.env['hr.public.holiday'] - + # Step 4: Kalau current_day ternyata weekend/libur, cari hari kerja berikutnya while True: - # # Tambah satu hari, cek apakah hari kerja - current_day += timedelta(days=i) - i = 1 - - # Lewati weekend is_weekend = current_day.weekday() >= 5 is_holiday = holiday.search([("start_date", "=", current_day)]) if is_weekend or is_holiday: - offset += 1 - continue - - break + current_day += timedelta(days=1) + total_days += 1 + else: + break + + final_offset = (current_day - start_date.date()).days + return final_offset + - return offset def calculate_sla_by_vendor(self, products): product_ids = products.mapped('product_id.id') # Kumpulkan semua ID produk @@ -637,11 +666,9 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - - days_after_3pm = self.handling_order_after_3pm(current_date) - date_after_3pm = current_date + timedelta(days=days_after_3pm) - sum_days = max_slatime + self.get_days_until_next_business_day(date_after_3pm) + sum_days = max_slatime + self.get_days_until_next_business_day(current_date) + sum_days -= 1 if not rec.estimated_arrival_days: rec.estimated_arrival_days = sum_days @@ -665,11 +692,9 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - - days_after_3pm = self.handling_order_after_3pm(current_date) - date_after_3pm = current_date + timedelta(days=days_after_3pm) - sum_days = max_slatime + self.get_days_until_next_business_day(date_after_3pm) + sum_days = max_slatime + self.get_days_until_next_business_day(current_date) + sum_days -= 1 eta_minimum = current_date + timedelta(days=sum_days) if expected_date < eta_minimum.date(): -- cgit v1.2.3 From 4688c123005c7c8038c4d56ef25307e309ef815e Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Tue, 13 May 2025 15:26:01 +0700 Subject: (andri) add field Selection Option dan menambahkan opsi biteship --- indoteknik_custom/models/sale_order.py | 36 ++++++++++++++++++++++++++++++++++ indoteknik_custom/views/sale_order.xml | 1 + 2 files changed, 37 insertions(+) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 795bfa0b..90c32e2a 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -249,6 +249,30 @@ class SaleOrder(models.Model): nomor_so_pengganti = fields.Char(string='Nomor SO Pengganti', copy=False, tracking=3) shipping_option_id = fields.Many2one("shipping.option", string="Selected Shipping Option", domain="['|', ('sale_order_id', '=', False), ('sale_order_id', '=', id)]") + select_shipping_option = fields.Selection([ + ('biteship', 'Biteship'), + ('custom', 'Custom'), + ], string='Select Shipping Option', help="Select shipping option for delivery") + + @api.onchange('shipping_option_id') + def _onchange_shipping_option_id(self): + if self.shipping_option_id: + self.delivery_amt = self.shipping_option_id.price + + @api.onchange('select_shipping_option') + def _onchange_select_shipping_option(self): + # Reset shipping option when the shipping type changes + self.shipping_option_id = False + + if self.select_shipping_option == 'custom': + return {'domain': {'carrier_id': []}} + + elif self.select_shipping_option == 'biteship': + # Reset delivery amount as it will be calculated through Biteship API + self.delivery_amt = 0 + self.carrier_id = False + return {'domain': {'carrier_id': [('id', '=', -1)]}} + @api.constrains('fee_third_party', 'delivery_amt', 'biaya_lain_lain') def _check_total_margin_excl_third_party(self): for rec in self: @@ -404,6 +428,18 @@ class SaleOrder(models.Model): else: raise UserError("Gagal mendapatkan estimasi ongkir.") + def _call_biteship_api(self, total_weight, destination_zip): + + url = 'https://api.biteship.com/v1/rates/couriers' + api_key = 'biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiUFQuSW5kb3Rla25payBEb3Rjb20gR2VtaWxhbmciLCJ1c2VySWQiOiI2NTIxMTU5YmRkNGIzZTAwMTUzNWIzMmYiLCJlbWFpbCI6InNhbGVzQGluZG90ZWtuaWsuY29tIiwibWVyY2hhbnRJZCI6IjY1MjExNTliOWNkN2JkMDAxNTJhNDM1ZSIsImlhdCI6MTcwNTE0Njc0NywiZXhwIjoxNzczMjk5MTQ3fQ.yR20t00sRR3fj-5eHI7G_rJPt9gv4Bi5iOIgB9sZ67c' + + headers = { + 'Authorization': api_key, + 'Content-Type': 'application/json' + } + + + def _call_rajaongkir_api(self, total_weight, destination_subsdistrict_id): url = 'https://pro.rajaongkir.com/api/cost' diff --git a/indoteknik_custom/views/sale_order.xml b/indoteknik_custom/views/sale_order.xml index 79a095fb..080549a4 100755 --- a/indoteknik_custom/views/sale_order.xml +++ b/indoteknik_custom/views/sale_order.xml @@ -118,6 +118,7 @@ + -- cgit v1.2.3 From 847a025e889ae9dcfe9ff97c913c9310695fc2c5 Mon Sep 17 00:00:00 2001 From: trisusilo48 Date: Fri, 16 May 2025 08:46:53 +0700 Subject: handle is 3 pm --- indoteknik_custom/models/sale_order.py | 45 ++++++++++++---------------------- 1 file changed, 16 insertions(+), 29 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 795bfa0b..1d318c46 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -2,7 +2,7 @@ from re import search from odoo import fields, models, api, _ from odoo.exceptions import UserError, ValidationError -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta, timezone, time import logging, random, string, requests, math, json, re, qrcode, base64 from io import BytesIO from collections import defaultdict @@ -541,28 +541,6 @@ class SaleOrder(models.Model): rec.eta_date_start = False - def handling_order_after_3pm(self, start_date=None, *args, **kwargs): - jakarta = pytz.timezone("Asia/Jakarta") - current = datetime.now(jakarta) - - offset = 0 - - - # Gunakan current time kalau start_date tidak diberikan - if start_date is None: - start_date = current - - # Pastikan start_date pakai timezone Jakarta - if start_date.tzinfo is None: - start_date = jakarta.localize(start_date) - - # Jika sudah lewat jam 15:00, mulai dari hari berikutnya - batas_waktu = datetime.strptime("15:00", "%H:%M").time() - if start_date.time() > batas_waktu: - offset += 1 - - return offset - def get_days_until_next_business_day(self, start_date=None, *args, **kwargs): jakarta = pytz.timezone("Asia/Jakarta") now = datetime.now(jakarta) @@ -577,9 +555,11 @@ class SaleOrder(models.Model): batas_waktu = datetime.strptime("15:00", "%H:%M").time() current_day = start_date.date() offset = 0 + is3pm = False # Step 1: Lewat jam 15 → Tambah 1 hari if start_date.time() > batas_waktu: + is3pm = True offset += 1 # Step 2: Hitung hari libur selama offset itu @@ -613,8 +593,8 @@ class SaleOrder(models.Model): else: break - final_offset = (current_day - start_date.date()).days - return final_offset + offset = (current_day - start_date.date()).days + return offset, is3pm @@ -666,13 +646,19 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - - sum_days = max_slatime + self.get_days_until_next_business_day(current_date) + + offset , is3pm = self.get_days_until_next_business_day(current_date) + sum_days = max_slatime + offset sum_days -= 1 if not rec.estimated_arrival_days: rec.estimated_arrival_days = sum_days eta_date = current_date + timedelta(days=sum_days) + if is3pm: + eta_date = datetime.combine(eta_date, time(10, 0)) # jam 10:00 + eta_date = jakarta.localize(eta_date).astimezone(timezone.utc) # ubah ke UTC + + eta_date = eta_date.astimezone(timezone.utc).replace(tzinfo=None) rec.commitment_date = eta_date rec.expected_ready_to_ship = eta_date @@ -692,8 +678,9 @@ class SaleOrder(models.Model): max_slatime = 1 # Default SLA jika tidak ada slatime = self.calculate_sla_by_vendor(rec.order_line) max_slatime = max(max_slatime, slatime['slatime']) - - sum_days = max_slatime + self.get_days_until_next_business_day(current_date) + + offset , is3pm = self.get_days_until_next_business_day(current_date) + sum_days = max_slatime + offset sum_days -= 1 eta_minimum = current_date + timedelta(days=sum_days) -- cgit v1.2.3 From 2c4ab23bdf0ab6073195144879639a0dae863fde Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Fri, 16 May 2025 14:45:54 +0700 Subject: (andri) revisi field shipping option --- indoteknik_custom/models/sale_order.py | 38 +++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 10 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 90c32e2a..902c6db1 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -259,19 +259,41 @@ class SaleOrder(models.Model): if self.shipping_option_id: self.delivery_amt = self.shipping_option_id.price + def _get_biteship_courier_codes(self): + return [ + 'jne', 'pos', 'tiki', 'rpx', 'wahana', 'sicepat', 'jnt', 'sap', + 'ninja', 'lion', 'anteraja', 'paxel', 'idexpress', 'rex', 'ide', + 'sentral', 'first', 'dse', 'ncs', 'jdl', 'slis', 'expedito' + ] + @api.onchange('select_shipping_option') def _onchange_select_shipping_option(self): - # Reset shipping option when the shipping type changes self.shipping_option_id = False + self.delivery_amt = 0 + + biteship_courier_codes = self._get_biteship_courier_codes() + + # Cari carrier yang namanya mengandung kode Biteship + biteship_carrier_ids = [] + for code in biteship_courier_codes: + carriers = self.env['delivery.carrier'].search([ + ('name', 'ilike', code) + ]) + if carriers: + biteship_carrier_ids.extend(carriers.ids) + + # Hapus duplikat + biteship_carrier_ids = list(set(biteship_carrier_ids)) if self.select_shipping_option == 'custom': - return {'domain': {'carrier_id': []}} + # Tampilkan carrier yang bukan dari Biteship + domain = [('id', 'not in', biteship_carrier_ids)] if biteship_carrier_ids else [] + return {'domain': {'carrier_id': domain}} elif self.select_shipping_option == 'biteship': - # Reset delivery amount as it will be calculated through Biteship API - self.delivery_amt = 0 - self.carrier_id = False - return {'domain': {'carrier_id': [('id', '=', -1)]}} + # Tampilkan hanya carrier dari Biteship + domain = [('id', 'in', biteship_carrier_ids)] if biteship_carrier_ids else [] + return {'domain': {'carrier_id': domain}} @api.constrains('fee_third_party', 'delivery_amt', 'biaya_lain_lain') def _check_total_margin_excl_third_party(self): @@ -429,7 +451,6 @@ class SaleOrder(models.Model): raise UserError("Gagal mendapatkan estimasi ongkir.") def _call_biteship_api(self, total_weight, destination_zip): - url = 'https://api.biteship.com/v1/rates/couriers' api_key = 'biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiUFQuSW5kb3Rla25payBEb3Rjb20gR2VtaWxhbmciLCJ1c2VySWQiOiI2NTIxMTU5YmRkNGIzZTAwMTUzNWIzMmYiLCJlbWFpbCI6InNhbGVzQGluZG90ZWtuaWsuY29tIiwibWVyY2hhbnRJZCI6IjY1MjExNTliOWNkN2JkMDAxNTJhNDM1ZSIsImlhdCI6MTcwNTE0Njc0NywiZXhwIjoxNzczMjk5MTQ3fQ.yR20t00sRR3fj-5eHI7G_rJPt9gv4Bi5iOIgB9sZ67c' @@ -438,9 +459,6 @@ class SaleOrder(models.Model): 'Content-Type': 'application/json' } - - - def _call_rajaongkir_api(self, total_weight, destination_subsdistrict_id): url = 'https://pro.rajaongkir.com/api/cost' headers = { -- cgit v1.2.3 From 0f7e05108336ea9de64348783cbec6e97edd1d64 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Mon, 19 May 2025 00:11:58 +0700 Subject: (andri) mendapatkan tarif pengiriman --- indoteknik_custom/models/sale_order.py | 383 ++++++++++++++++++++++++++++----- 1 file changed, 335 insertions(+), 48 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 902c6db1..69982a47 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -261,11 +261,9 @@ class SaleOrder(models.Model): def _get_biteship_courier_codes(self): return [ - 'jne', 'pos', 'tiki', 'rpx', 'wahana', 'sicepat', 'jnt', 'sap', - 'ninja', 'lion', 'anteraja', 'paxel', 'idexpress', 'rex', 'ide', - 'sentral', 'first', 'dse', 'ncs', 'jdl', 'slis', 'expedito' + 'gojek','grab','deliveree','lalamove','jne','tiki','ninja','lion','rara','sicepat','jnt','pos','idexpress','rpx','wahana','jdl','pos','anteraja','sap','paxel','borzo' ] - + @api.onchange('select_shipping_option') def _onchange_select_shipping_option(self): self.shipping_option_id = False @@ -385,10 +383,78 @@ class SaleOrder(models.Model): ) def action_estimate_shipping(self): - if self.carrier_id.id in [1, 151]: - self.action_indoteknik_estimate_shipping() - return + # if self.carrier_id.id in [1, 151]: + # self.action_indoteknik_estimate_shipping() + # return + + if self.select_shipping_option == 'biteship': + return self.action_estimate_shipping_biteship() + elif self.carrier_id.id in [1, 151]: # ID untuk Indoteknik Delivery + return self.action_indoteknik_estimate_shipping() + else: + total_weight = 0 + missing_weight_products = [] + + for line in self.order_line: + if line.weight > 0: + total_weight += line.weight * line.product_uom_qty + line.product_id.weight = line.weight + else: + missing_weight_products.append(line.product_id.name) + + if missing_weight_products: + product_names = '
'.join(missing_weight_products) + self.message_post(body=f"Produk berikut tidak memiliki berat:
{product_names}") + + if total_weight == 0: + raise UserError("Tidak dapat mengestimasi ongkir tanpa berat yang valid.") + + destination_subsdistrict_id = self.real_shipping_id.kecamatan_id.rajaongkir_id + if not destination_subsdistrict_id: + raise UserError("Gagal mendapatkan ID kota tujuan.") + + result = self._call_rajaongkir_api(total_weight, destination_subsdistrict_id) + if result: + shipping_options = [] + for courier in result['rajaongkir']['results']: + for cost_detail in courier['costs']: + service = cost_detail['service'] + description = cost_detail['description'] + etd = cost_detail['cost'][0]['etd'] + value = cost_detail['cost'][0]['value'] + shipping_options.append((service, description, etd, value, courier['code'])) + + self.env["shipping.option"].search([('sale_order_id', '=', self.id)]).unlink() + + _logger.info(f"Shipping options: {shipping_options}") + + for service, description, etd, value, provider in shipping_options: + self.env["shipping.option"].create({ + "name": service, + "price": value, + "provider": provider, + "etd": etd, + "sale_order_id": self.id, + }) + + + self.shipping_option_id = self.env["shipping.option"].search([('sale_order_id', '=', self.id)], limit=1).id + + _logger.info(f"Shipping option SO ID: {self.shipping_option_id}") + + self.message_post( + body=f"Estimasi Ongkos Kirim: Rp{self.delivery_amt}
Detail Lain:
" + f"{'
'.join([f'Service: {s[0]}, Description: {s[1]}, ETD: {s[2]} hari, Cost: Rp {s[3]}' for s in shipping_options])}", + message_type="comment" + ) + + # self.message_post(body=f"Estimasi Ongkos Kirim: Rp{self.delivery_amt}
Detail Lain:
{'
'.join([f'Service: {s[0]}, Description: {s[1]}, ETD: {s[2]} hari, Cost: Rp {s[3]}' for s in shipping_options])}", message_type="comment") + else: + raise UserError("Gagal mendapatkan estimasi ongkir.") + + def _validate_for_shipping_estimate(self): + # Cek berat produk total_weight = 0 missing_weight_products = [] @@ -405,59 +471,280 @@ class SaleOrder(models.Model): if total_weight == 0: raise UserError("Tidak dapat mengestimasi ongkir tanpa berat yang valid.") + + # Validasi alamat pengiriman + if not self.real_shipping_id: + raise UserError("Alamat pengiriman (Real Delivery Address) harus diisi.") + + if not self.real_shipping_id.kota_id: + raise UserError("Kota pada alamat pengiriman harus diisi.") + + if not self.real_shipping_id.zip: + raise UserError("Kode pos pada alamat pengiriman harus diisi.") + + if not self.real_shipping_id.state_id: + raise UserError("Provinsi pada alamat pengiriman harus diisi.") + + return total_weight - destination_subsdistrict_id = self.real_shipping_id.kecamatan_id.rajaongkir_id - if not destination_subsdistrict_id: - raise UserError("Gagal mendapatkan ID kota tujuan.") - - result = self._call_rajaongkir_api(total_weight, destination_subsdistrict_id) - if result: - shipping_options = [] - for courier in result['rajaongkir']['results']: - for cost_detail in courier['costs']: - service = cost_detail['service'] - description = cost_detail['description'] - etd = cost_detail['cost'][0]['etd'] - value = cost_detail['cost'][0]['value'] - shipping_options.append((service, description, etd, value, courier['code'])) - - self.env["shipping.option"].search([('sale_order_id', '=', self.id)]).unlink() + def action_estimate_shipping_biteship(self): + # Validasi data + total_weight = self._validate_for_shipping_estimate() + + # Konversi berat ke gram untuk Biteship + weight_gram = int(total_weight * 1000) + if weight_gram < 100: + weight_gram = 100 # Minimum weight untuk Biteship + + # Persiapkan data item + items = [{ + "name": "Paket Pesanan", + "description": f"Sale Order {self.name}", + "value": int(self.amount_untaxed), + "weight": weight_gram, + "quantity": 1, + "height": 10, + "width": 10, + "length": 10 + }] + + # Coba dapatkan data alamat tujuan + destination_data = {} + origin_data = {} + + # Persiapkan data alamat asal (Gudang) + # 1. Data tetap gudang Bandengan + origin_data = { + "origin_postal_code" : 14440, + # "origin_latitude": -6.1753924, + # "origin_longitude": 106.7794935, + } - _logger.info(f"Shipping options: {shipping_options}") + # Coba dapatkan data alamat tujuan + if not self.real_shipping_id: + raise UserError("Alamat pengiriman (Real Delivery Address) harus diisi.") + + shipping_address = self.real_shipping_id + _logger.info(f"Shipping Address: {shipping_address}") + _logger.info(f"Shipping Address: {shipping_address.zip}") + + # # Coba dapatkan koordinat dulu (jika tersedia) + # if hasattr(shipping_address, 'partner_latitude') and hasattr(shipping_address, 'partner_longitude'): + # if shipping_address.partner_latitude and shipping_address.partner_longitude: + # destination_data = { + # "destination_latitude": shipping_address.partner_latitude, + # "destination_longitude": shipping_address.partner_longitude + # } + + # Jika koordinat tidak tersedia, gunakan kode pos + if not destination_data and shipping_address.zip: + destination_data = { + "destination_postal_code": shipping_address.zip + } + + # Jika kode pos tidak tersedia, gunakan alamat lengkap + # if not destination_data: + # # Buat alamat lengkap + # full_address = f"{shipping_address.street or ''}" + # if shipping_address.street2: + # full_address += f", {shipping_address.street2}" + + # destination_data = { + # "address": full_address, + # "area": shipping_address.kota_id.name if shipping_address.kota_id else "", + # "suburb": shipping_address.kecamatan_id.name if shipping_address.kecamatan_id else "", + # "province": shipping_address.state_id.name if shipping_address.state_id else "", + # "postcode": shipping_address.zip or "" + # } + + # Siapkan daftar kurir yang valid untuk Biteship + couriers = ','.join(self._get_biteship_courier_codes()) + + # Jika tidak ada data tujuan yang valid + if not destination_data: + raise UserError("Tidak dapat mengestimasikan ongkir: Alamat pengiriman tidak lengkap.") + + # Panggil API Biteship dengan format yang benar + result = self._call_biteship_api(origin_data, destination_data, items, couriers) + + if not result: + raise UserError("Gagal mendapatkan estimasi ongkir dari Biteship.") + + # Hapus shipping_option lama + self.env["shipping.option"].search([('sale_order_id', '=', self.id)]).unlink() + + # Proses hasil API + shipping_options = [] + shipping_services = result.get('pricing', []) + + _logger.info(f"Ditemukan {len(shipping_services)} layanan pengiriman") + + for service in shipping_services: + courier_code = service.get('courier_code', '').lower() + courier_name = service.get('courier_name', '') + service_name = service.get('courier_service_name', '') + price = service.get('price', 0) + + _logger.info(f"Layanan: {courier_name} - {service_name}, Harga: {price}") + + # Lewati layanan dengan harga 0 + if not price: + _logger.warning(f"Melewati layanan dengan harga 0: {courier_name} - {service_name}") + continue - for service, description, etd, value, provider in shipping_options: - self.env["shipping.option"].create({ - "name": service, - "price": value, - "provider": provider, + # Format estimasi waktu + duration = service.get('duration', '') + shipment_range = service.get('shipment_duration_range', '') + shipment_unit = service.get('shipment_duration_unit', 'days') + + # Gunakan duration jika tersedia, jika tidak, buat dari range + if duration: + etd = duration + elif shipment_range: + etd = f"{shipment_range} {shipment_unit}" + else: + etd = "1-3 days" # Default fallback + + # Buat shipping option + try: + shipping_option = self.env["shipping.option"].create({ + "name": f"{courier_name} - {service_name}", + "price": price, + "provider": courier_code, "etd": etd, "sale_order_id": self.id, }) - - - self.shipping_option_id = self.env["shipping.option"].search([('sale_order_id', '=', self.id)], limit=1).id - - _logger.info(f"Shipping option SO ID: {self.shipping_option_id}") - - self.message_post( - body=f"Estimasi Ongkos Kirim: Rp{self.delivery_amt}
Detail Lain:
" - f"{'
'.join([f'Service: {s[0]}, Description: {s[1]}, ETD: {s[2]} hari, Cost: Rp {s[3]}' for s in shipping_options])}", - message_type="comment" - ) - - # self.message_post(body=f"Estimasi Ongkos Kirim: Rp{self.delivery_amt}
Detail Lain:
{'
'.join([f'Service: {s[0]}, Description: {s[1]}, ETD: {s[2]} hari, Cost: Rp {s[3]}' for s in shipping_options])}", message_type="comment") - - else: - raise UserError("Gagal mendapatkan estimasi ongkir.") + + shipping_options.append(shipping_option) + _logger.info(f"Berhasil membuat opsi pengiriman: {courier_name} - {service_name}") + except Exception as e: + _logger.error(f"Gagal membuat opsi pengiriman: {str(e)}") + + # Jika tidak ada opsi pengiriman + if not shipping_options: + raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") + + # Set opsi pertama sebagai default + self.shipping_option_id = shipping_options[0].id + self.delivery_amt = shipping_options[0].price + + # Format pesan untuk log + option_list = '
'.join([ + f"{opt.name}: Rp {opt.price:,.0f} ({opt.etd})" + for opt in shipping_options + ]) + + # Log hasil estimasi + self.message_post( + body=f"Estimasi Ongkir Biteship (Kode Pos {origin_data} → {destination_data}):
{option_list}", + message_type="comment" + ) + + return { + 'type': 'ir.actions.client', + 'tag': 'display_notification', + 'params': { + 'title': 'Estimasi Ongkir Berhasil', + 'message': f'Mendapatkan {len(shipping_options)} opsi pengiriman', + 'type': 'success', + 'sticky': False, + } + } - def _call_biteship_api(self, total_weight, destination_zip): + def _call_biteship_api(self, origin_data, destination_data, items, couriers=None): + url = 'https://api.biteship.com/v1/rates/couriers' - api_key = 'biteship_live.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiUFQuSW5kb3Rla25payBEb3Rjb20gR2VtaWxhbmciLCJ1c2VySWQiOiI2NTIxMTU5YmRkNGIzZTAwMTUzNWIzMmYiLCJlbWFpbCI6InNhbGVzQGluZG90ZWtuaWsuY29tIiwibWVyY2hhbnRJZCI6IjY1MjExNTliOWNkN2JkMDAxNTJhNDM1ZSIsImlhdCI6MTcwNTE0Njc0NywiZXhwIjoxNzczMjk5MTQ3fQ.yR20t00sRR3fj-5eHI7G_rJPt9gv4Bi5iOIgB9sZ67c' - + api_key = 'biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA' + headers = { 'Authorization': api_key, 'Content-Type': 'application/json' } + + if not couriers: + couriers = ','.join(self._get_biteship_courier_codes()) + + # # Cek apakah kita menggunakan koordinat (paling akurat) + # has_origin_coords = ('origin_latitude' in origin_data and 'origin_longitude' in origin_data) + # has_dest_coords = ('destination_latitude' in destination_data and 'destination_longitude' in destination_data) + + # Cek apakah kita menggunakan kode pos + has_origin_postal = ('origin_postal_code' in origin_data) + has_dest_postal = ('destination_postal_code' in destination_data) + _logger.info(f"Origin Data: {has_origin_postal}") + _logger.info(f"Destination Data: {has_dest_postal}") + # Tentukan payload berdasarkan data yang tersedia + # if has_origin_coords and has_dest_coords: + # # Mode koordinat - paling akurat + # payload = { + # "origin_latitude": origin_data.get('origin_latitude'), + # "origin_longitude": origin_data.get('origin_longitude'), + # "destination_latitude": destination_data.get('destination_latitude'), + # "destination_longitude": destination_data.get('destination_longitude'), + # "couriers": couriers, + # "items": items + # } + # api_mode = "koordinat" + # elif has_origin_postal and has_dest_postal: + if has_origin_postal and has_dest_postal: + # Mode kode pos - fallback 1 + payload = { + "origin_postal_code": origin_data.get('origin_postal_code'), + "destination_postal_code": destination_data.get('destination_postal_code'), + "couriers": couriers, + "items": items + } + api_mode = "kode_pos" + # else: + # # Mode alamat lengkap - fallback 2 + # payload = { + # "origin": { + # "address": origin_data.get('address', ''), + # "area": origin_data.get('area', ''), + # "suburb": origin_data.get('suburb', ''), + # "province": origin_data.get('province', ''), + # "postcode": origin_data.get('postcode', '') + # }, + # "destination": { + # "address": destination_data.get('address', ''), + # "area": destination_data.get('area', ''), + # "suburb": destination_data.get('suburb', ''), + # "province": destination_data.get('province', ''), + # "postcode": destination_data.get('postcode', '') + # }, + # "couriers": couriers, + # "items": items + # } + # api_mode = "alamat_lengkap" + + try: + _logger.info(f"Calling Biteship API with mode: {api_mode}") + _logger.info(f"Payload: {payload}") + + response = requests.post(url, headers=headers, json=payload, timeout=30) + + # Log response untuk debugging + _logger.info(f"Biteship API Status Code: {response.status_code}") + if response.status_code != 200: + _logger.error(f"Biteship API Error Response: {response.text}") + + if response.status_code == 200: + result = response.json() + result['api_mode'] = api_mode # Tambahkan info mode API untuk referensi + return result + else: + error_msg = response.text + _logger.error(f"Error calling Biteship API: {response.status_code} - {error_msg}") + return False + except requests.exceptions.Timeout: + _logger.error("Timeout connecting to Biteship API") + return False + except requests.exceptions.ConnectionError: + _logger.error("Connection error to Biteship API") + return False + except Exception as e: + _logger.error(f"Exception calling Biteship API: {str(e)}") + return False def _call_rajaongkir_api(self, total_weight, destination_subsdistrict_id): url = 'https://pro.rajaongkir.com/api/cost' -- cgit v1.2.3 From 60f1f3b3dbe988d8c0fda706fd25d3abe892238a Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Mon, 19 May 2025 11:08:11 +0700 Subject: (andri) penyesuaian selected shipping ketika estimate shipping --- indoteknik_custom/models/sale_order.py | 193 ++++++++++++--------------------- 1 file changed, 68 insertions(+), 125 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 12c04f19..4ee82100 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -252,12 +252,13 @@ class SaleOrder(models.Model): select_shipping_option = fields.Selection([ ('biteship', 'Biteship'), ('custom', 'Custom'), - ], string='Select Shipping Option', help="Select shipping option for delivery") + ], string='Select Shipping Option', help="Select shipping option for delivery", Tracking=True) @api.onchange('shipping_option_id') def _onchange_shipping_option_id(self): if self.shipping_option_id: self.delivery_amt = self.shipping_option_id.price + self.note_ekspedisi = f"Pengiriman: {self.shipping_option_id.name} - Rp {self.shipping_option_id.price:,.0f} ({self.shipping_option_id.etd})" def _get_biteship_courier_codes(self): return [ @@ -267,6 +268,7 @@ class SaleOrder(models.Model): @api.onchange('select_shipping_option') def _onchange_select_shipping_option(self): self.shipping_option_id = False + self.carrier_id = False self.delivery_amt = 0 biteship_courier_codes = self._get_biteship_courier_codes() @@ -488,7 +490,6 @@ class SaleOrder(models.Model): return total_weight def action_estimate_shipping_biteship(self): - # Validasi data total_weight = self._validate_for_shipping_estimate() # Konversi berat ke gram untuk Biteship @@ -508,63 +509,47 @@ class SaleOrder(models.Model): "length": 10 }] - # Coba dapatkan data alamat tujuan - destination_data = {} - origin_data = {} - - # Persiapkan data alamat asal (Gudang) - # 1. Data tetap gudang Bandengan + # Data asal (tetap gudang Bandengan) origin_data = { - "origin_postal_code" : 14440, - # "origin_latitude": -6.1753924, - # "origin_longitude": 106.7794935, + "origin_latitude": -6.3031123, + "origin_longitude": 106.7794934, } - - # Coba dapatkan data alamat tujuan - if not self.real_shipping_id: - raise UserError("Alamat pengiriman (Real Delivery Address) harus diisi.") + + # Prioritaskan penggunaan koordinat jika tersedia + destination_data = {} + use_coordinate = False shipping_address = self.real_shipping_id - _logger.info(f"Shipping Address: {shipping_address}") - _logger.info(f"Shipping Address: {shipping_address.zip}") - # # Coba dapatkan koordinat dulu (jika tersedia) - # if hasattr(shipping_address, 'partner_latitude') and hasattr(shipping_address, 'partner_longitude'): - # if shipping_address.partner_latitude and shipping_address.partner_longitude: - # destination_data = { - # "destination_latitude": shipping_address.partner_latitude, - # "destination_longitude": shipping_address.partner_longitude - # } + # Cek apakah latitude dan longitude tersedia dan valid + if hasattr(shipping_address, 'latitude') and hasattr(shipping_address, 'longitude'): + if shipping_address.latitude and shipping_address.longitude: + try: + lat = float(shipping_address.latitude) + lng = float(shipping_address.longitude) + destination_data = { + "destination_latitude": lat, + "destination_longitude": lng + } + use_coordinate = True + except (ValueError, TypeError): + use_coordinate = False # Jika koordinat tidak tersedia, gunakan kode pos - if not destination_data and shipping_address.zip: - destination_data = { - "destination_postal_code": shipping_address.zip - } + if not use_coordinate: + if shipping_address.zip: + origin_data = {"origin_postal_code": 14440} + destination_data = { + "destination_postal_code": shipping_address.zip + } + else: + raise UserError("Tidak dapat mengestimasikan ongkir: Kode pos tujuan tidak tersedia.") - # Jika kode pos tidak tersedia, gunakan alamat lengkap - # if not destination_data: - # # Buat alamat lengkap - # full_address = f"{shipping_address.street or ''}" - # if shipping_address.street2: - # full_address += f", {shipping_address.street2}" - - # destination_data = { - # "address": full_address, - # "area": shipping_address.kota_id.name if shipping_address.kota_id else "", - # "suburb": shipping_address.kecamatan_id.name if shipping_address.kecamatan_id else "", - # "province": shipping_address.state_id.name if shipping_address.state_id else "", - # "postcode": shipping_address.zip or "" - # } - - # Siapkan daftar kurir yang valid untuk Biteship - couriers = ','.join(self._get_biteship_courier_codes()) - - # Jika tidak ada data tujuan yang valid - if not destination_data: - raise UserError("Tidak dapat mengestimasikan ongkir: Alamat pengiriman tidak lengkap.") - - # Panggil API Biteship dengan format yang benar + # Filter kurir berdasarkan shipping method jika dipilih + couriers = self.carrier_id.name.lower() if self.carrier_id else ','.join(self._get_biteship_courier_codes()) + + # Panggil API Biteship + api_mode = "koordinat" if use_coordinate else "kode_pos" result = self._call_biteship_api(origin_data, destination_data, items, couriers) if not result: @@ -577,19 +562,14 @@ class SaleOrder(models.Model): shipping_options = [] shipping_services = result.get('pricing', []) - _logger.info(f"Ditemukan {len(shipping_services)} layanan pengiriman") - for service in shipping_services: courier_code = service.get('courier_code', '').lower() courier_name = service.get('courier_name', '') service_name = service.get('courier_service_name', '') price = service.get('price', 0) - _logger.info(f"Layanan: {courier_name} - {service_name}, Harga: {price}") - # Lewati layanan dengan harga 0 if not price: - _logger.warning(f"Melewati layanan dengan harga 0: {courier_name} - {service_name}") continue # Format estimasi waktu @@ -597,13 +577,12 @@ class SaleOrder(models.Model): shipment_range = service.get('shipment_duration_range', '') shipment_unit = service.get('shipment_duration_unit', 'days') - # Gunakan duration jika tersedia, jika tidak, buat dari range if duration: etd = duration elif shipment_range: etd = f"{shipment_range} {shipment_unit}" else: - etd = "1-3 days" # Default fallback + etd = "1-3 days" # Buat shipping option try: @@ -616,36 +595,50 @@ class SaleOrder(models.Model): }) shipping_options.append(shipping_option) - _logger.info(f"Berhasil membuat opsi pengiriman: {courier_name} - {service_name}") except Exception as e: _logger.error(f"Gagal membuat opsi pengiriman: {str(e)}") # Jika tidak ada opsi pengiriman if not shipping_options: - raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") + raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data}.") # Set opsi pertama sebagai default self.shipping_option_id = shipping_options[0].id self.delivery_amt = shipping_options[0].price - # Format pesan untuk log + # Tampilkan lokasi pengiriman dengan format yang lebih baik + if use_coordinate: + origin_info = f"Koordinat ({origin_data.get('origin_latitude')}, {origin_data.get('origin_longitude')})" + destination_info = f"Koordinat ({destination_data.get('destination_latitude')}, {destination_data.get('destination_longitude')})" + else: + origin_info = f"Kode Pos {origin_data.get('origin_postal_code')}" + destination_info = f"Kode Pos {destination_data.get('destination_postal_code')}" + + # Format daftar opsi pengiriman option_list = '
'.join([ f"{opt.name}: Rp {opt.price:,.0f} ({opt.etd})" for opt in shipping_options ]) - # Log hasil estimasi + # Tampilkan informasi tentang kurir yang dipilih + selected_option = shipping_options[0] + shipping_method_info = f"Metode Pengiriman: {self.carrier_id.name}" if self.carrier_id else "" + + # Log hasil estimasi dengan format yang lebih baik dan informasi kurir self.message_post( - body=f"Estimasi Ongkir Biteship (Kode Pos {origin_data} → {destination_data}):
{option_list}", + body=f"Estimasi Ongkir Biteship ({origin_info} → {destination_info}):
{shipping_method_info}
{option_list}", message_type="comment" ) + # Simpan informasi untuk note ekspedisi + self.note_ekspedisi = f"Pengiriman: {selected_option.name} - Rp {selected_option.price:,.0f} ({selected_option.etd}) [via {api_mode}]" + return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'title': 'Estimasi Ongkir Berhasil', - 'message': f'Mendapatkan {len(shipping_options)} opsi pengiriman', + 'message': f'Mendapatkan {len(shipping_options)} opsi pengiriman menggunakan {api_mode}', 'type': 'success', 'sticky': False, } @@ -663,59 +656,16 @@ class SaleOrder(models.Model): if not couriers: couriers = ','.join(self._get_biteship_courier_codes()) - - # # Cek apakah kita menggunakan koordinat (paling akurat) - # has_origin_coords = ('origin_latitude' in origin_data and 'origin_longitude' in origin_data) - # has_dest_coords = ('destination_latitude' in destination_data and 'destination_longitude' in destination_data) - - # Cek apakah kita menggunakan kode pos - has_origin_postal = ('origin_postal_code' in origin_data) - has_dest_postal = ('destination_postal_code' in destination_data) - _logger.info(f"Origin Data: {has_origin_postal}") - _logger.info(f"Destination Data: {has_dest_postal}") - # Tentukan payload berdasarkan data yang tersedia - # if has_origin_coords and has_dest_coords: - # # Mode koordinat - paling akurat - # payload = { - # "origin_latitude": origin_data.get('origin_latitude'), - # "origin_longitude": origin_data.get('origin_longitude'), - # "destination_latitude": destination_data.get('destination_latitude'), - # "destination_longitude": destination_data.get('destination_longitude'), - # "couriers": couriers, - # "items": items - # } - # api_mode = "koordinat" - # elif has_origin_postal and has_dest_postal: - if has_origin_postal and has_dest_postal: - # Mode kode pos - fallback 1 - payload = { - "origin_postal_code": origin_data.get('origin_postal_code'), - "destination_postal_code": destination_data.get('destination_postal_code'), - "couriers": couriers, - "items": items - } - api_mode = "kode_pos" - # else: - # # Mode alamat lengkap - fallback 2 - # payload = { - # "origin": { - # "address": origin_data.get('address', ''), - # "area": origin_data.get('area', ''), - # "suburb": origin_data.get('suburb', ''), - # "province": origin_data.get('province', ''), - # "postcode": origin_data.get('postcode', '') - # }, - # "destination": { - # "address": destination_data.get('address', ''), - # "area": destination_data.get('area', ''), - # "suburb": destination_data.get('suburb', ''), - # "province": destination_data.get('province', ''), - # "postcode": destination_data.get('postcode', '') - # }, - # "couriers": couriers, - # "items": items - # } - # api_mode = "alamat_lengkap" + + # Persiapkan payload dengan menggabungkan origin, destination, dan items + payload = { + **origin_data, + **destination_data, + "couriers": couriers, + "items": items + } + + api_mode = "koordinat" if "destination_latitude" in destination_data else "kode_pos" try: _logger.info(f"Calling Biteship API with mode: {api_mode}") @@ -723,25 +673,18 @@ class SaleOrder(models.Model): response = requests.post(url, headers=headers, json=payload, timeout=30) - # Log response untuk debugging _logger.info(f"Biteship API Status Code: {response.status_code}") if response.status_code != 200: _logger.error(f"Biteship API Error Response: {response.text}") if response.status_code == 200: result = response.json() - result['api_mode'] = api_mode # Tambahkan info mode API untuk referensi + result['api_mode'] = api_mode # Tambahkan info mode API return result else: error_msg = response.text _logger.error(f"Error calling Biteship API: {response.status_code} - {error_msg}") return False - except requests.exceptions.Timeout: - _logger.error("Timeout connecting to Biteship API") - return False - except requests.exceptions.ConnectionError: - _logger.error("Connection error to Biteship API") - return False except Exception as e: _logger.error(f"Exception calling Biteship API: {str(e)}") return False -- cgit v1.2.3 From 63243a7b70292e9c48a21e2badbb07c398bc4166 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Mon, 19 May 2025 16:07:03 +0700 Subject: (andri) add field langitude & longitude pada customer & perbaikan biteship --- indoteknik_custom/models/sale_order.py | 90 ++++++++++++++++++--------------- indoteknik_custom/views/res_partner.xml | 4 ++ 2 files changed, 53 insertions(+), 41 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 4ee82100..f09869da 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -258,7 +258,6 @@ class SaleOrder(models.Model): def _onchange_shipping_option_id(self): if self.shipping_option_id: self.delivery_amt = self.shipping_option_id.price - self.note_ekspedisi = f"Pengiriman: {self.shipping_option_id.name} - Rp {self.shipping_option_id.price:,.0f} ({self.shipping_option_id.etd})" def _get_biteship_courier_codes(self): return [ @@ -271,29 +270,25 @@ class SaleOrder(models.Model): self.carrier_id = False self.delivery_amt = 0 - biteship_courier_codes = self._get_biteship_courier_codes() - - # Cari carrier yang namanya mengandung kode Biteship + # Dapatkan semua ID carrier untuk Biteship biteship_carrier_ids = [] - for code in biteship_courier_codes: - carriers = self.env['delivery.carrier'].search([ - ('name', 'ilike', code) - ]) - if carriers: - biteship_carrier_ids.extend(carriers.ids) - # Hapus duplikat - biteship_carrier_ids = list(set(biteship_carrier_ids)) + # Gunakan SQL langsung untuk menghindari masalah ORM + self.env.cr.execute(""" + SELECT delivery_carrier_id + FROM rajaongkir_kurir + WHERE name IN %s + """, (tuple(self._get_biteship_courier_codes()),)) - if self.select_shipping_option == 'custom': - # Tampilkan carrier yang bukan dari Biteship - domain = [('id', 'not in', biteship_carrier_ids)] if biteship_carrier_ids else [] - return {'domain': {'carrier_id': domain}} + # Ambil ID numerik hasil query + biteship_carrier_ids = [row[0] for row in self.env.cr.fetchall() if row[0]] - elif self.select_shipping_option == 'biteship': - # Tampilkan hanya carrier dari Biteship + if self.select_shipping_option == 'biteship': domain = [('id', 'in', biteship_carrier_ids)] if biteship_carrier_ids else [] - return {'domain': {'carrier_id': domain}} + else: # 'custom' + domain = [('id', 'not in', biteship_carrier_ids)] if biteship_carrier_ids else [] + + return {'domain': {'carrier_id': domain}} @api.constrains('fee_third_party', 'delivery_amt', 'biaya_lain_lain') def _check_total_margin_excl_third_party(self): @@ -490,6 +485,7 @@ class SaleOrder(models.Model): return total_weight def action_estimate_shipping_biteship(self): + total_weight = self._validate_for_shipping_estimate() # Konversi berat ke gram untuk Biteship @@ -509,6 +505,10 @@ class SaleOrder(models.Model): "length": 10 }] + # Coba dapatkan data koordinat dari alamat pengiriman + shipping_address = self.real_shipping_id + _logger.info(f"Shipping Address: {shipping_address}") + # Data asal (tetap gudang Bandengan) origin_data = { "origin_latitude": -6.3031123, @@ -519,37 +519,41 @@ class SaleOrder(models.Model): destination_data = {} use_coordinate = False - shipping_address = self.real_shipping_id - # Cek apakah latitude dan longitude tersedia dan valid - if hasattr(shipping_address, 'latitude') and hasattr(shipping_address, 'longitude'): - if shipping_address.latitude and shipping_address.longitude: + if hasattr(shipping_address, 'latitude') and hasattr(shipping_address, 'longtitude'): + if shipping_address.latitude and shipping_address.longtitude: try: + # Validasi format koordinat lat = float(shipping_address.latitude) - lng = float(shipping_address.longitude) + lng = float(shipping_address.longtitude) destination_data = { "destination_latitude": lat, "destination_longitude": lng } use_coordinate = True + _logger.info(f"Using coordinates: lat={lat}, lng={lng}") except (ValueError, TypeError): + _logger.warning(f"Invalid coordinates, falling back to postal code") use_coordinate = False - # Jika koordinat tidak tersedia, gunakan kode pos + # Jika koordinat tidak tersedia atau tidak valid, gunakan kode pos if not use_coordinate: if shipping_address.zip: - origin_data = {"origin_postal_code": 14440} + origin_data = {"origin_postal_code": 14440} # Reset origin untuk mode kode pos destination_data = { "destination_postal_code": shipping_address.zip } + _logger.info(f"Using postal code: {shipping_address.zip}") else: raise UserError("Tidak dapat mengestimasikan ongkir: Kode pos tujuan tidak tersedia.") - # Filter kurir berdasarkan shipping method jika dipilih - couriers = self.carrier_id.name.lower() if self.carrier_id else ','.join(self._get_biteship_courier_codes()) + # Siapkan daftar kurir + couriers = ','.join(self._get_biteship_courier_codes()) - # Panggil API Biteship + # Panggil API Biteship dengan format yang benar api_mode = "koordinat" if use_coordinate else "kode_pos" + _logger.info(f"Calling Biteship API with mode: {api_mode}") + result = self._call_biteship_api(origin_data, destination_data, items, couriers) if not result: @@ -562,14 +566,19 @@ class SaleOrder(models.Model): shipping_options = [] shipping_services = result.get('pricing', []) + _logger.info(f"Ditemukan {len(shipping_services)} layanan pengiriman") + for service in shipping_services: courier_code = service.get('courier_code', '').lower() courier_name = service.get('courier_name', '') service_name = service.get('courier_service_name', '') price = service.get('price', 0) + _logger.info(f"Layanan: {courier_name} - {service_name}, Harga: {price}") + # Lewati layanan dengan harga 0 if not price: + _logger.warning(f"Melewati layanan dengan harga 0: {courier_name} - {service_name}") continue # Format estimasi waktu @@ -577,12 +586,13 @@ class SaleOrder(models.Model): shipment_range = service.get('shipment_duration_range', '') shipment_unit = service.get('shipment_duration_unit', 'days') + # Gunakan duration jika tersedia, jika tidak, buat dari range if duration: etd = duration elif shipment_range: etd = f"{shipment_range} {shipment_unit}" else: - etd = "1-3 days" + etd = "1-3 days" # Default fallback # Buat shipping option try: @@ -595,18 +605,19 @@ class SaleOrder(models.Model): }) shipping_options.append(shipping_option) + _logger.info(f"Berhasil membuat opsi pengiriman: {courier_name} - {service_name}") except Exception as e: _logger.error(f"Gagal membuat opsi pengiriman: {str(e)}") # Jika tidak ada opsi pengiriman if not shipping_options: - raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data}.") + raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") # Set opsi pertama sebagai default self.shipping_option_id = shipping_options[0].id self.delivery_amt = shipping_options[0].price - # Tampilkan lokasi pengiriman dengan format yang lebih baik + # Format pesan untuk log yang lebih informatif if use_coordinate: origin_info = f"Koordinat ({origin_data.get('origin_latitude')}, {origin_data.get('origin_longitude')})" destination_info = f"Koordinat ({destination_data.get('destination_latitude')}, {destination_data.get('destination_longitude')})" @@ -620,17 +631,14 @@ class SaleOrder(models.Model): for opt in shipping_options ]) - # Tampilkan informasi tentang kurir yang dipilih - selected_option = shipping_options[0] - shipping_method_info = f"Metode Pengiriman: {self.carrier_id.name}" if self.carrier_id else "" - - # Log hasil estimasi dengan format yang lebih baik dan informasi kurir + # Log hasil estimasi dengan format yang lebih baik self.message_post( - body=f"Estimasi Ongkir Biteship ({origin_info} → {destination_info}):
{shipping_method_info}
{option_list}", + body=f"Estimasi Ongkir Biteship ({origin_info} → {destination_info}):
{option_list}", message_type="comment" ) # Simpan informasi untuk note ekspedisi + selected_option = shipping_options[0] # Opsi pertama dipilih sebagai default self.note_ekspedisi = f"Pengiriman: {selected_option.name} - Rp {selected_option.price:,.0f} ({selected_option.etd}) [via {api_mode}]" return { @@ -1435,7 +1443,7 @@ class SaleOrder(models.Model): 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") + raise UserError("Customer Reference kosong, di isi dengan NO PO jika PO tidak ada mohon ditulis Tanpa PO") if not order.commitment_date and order.create_date > datetime(2024, 9, 12): raise UserError("Expected Delivery Date kosong, wajib diisi") @@ -1462,7 +1470,7 @@ class SaleOrder(models.Model): 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") + 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") @@ -1673,7 +1681,7 @@ class SaleOrder(models.Model): 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") + raise UserError("Customer Reference kosong, di isi dengan NO PO jika PO tidak ada mohon ditulis Tanpa PO") if not order.commitment_date and order.create_date > datetime(2024, 9, 12): raise UserError("Expected Delivery Date kosong, wajib diisi") diff --git a/indoteknik_custom/views/res_partner.xml b/indoteknik_custom/views/res_partner.xml index cb9fa3ac..9fb6530c 100644 --- a/indoteknik_custom/views/res_partner.xml +++ b/indoteknik_custom/views/res_partner.xml @@ -65,6 +65,10 @@ + + + + -- cgit v1.2.3 From e987dc891e999ebd1d04fb4f8cdeb44134c67aed Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Mon, 19 May 2025 22:21:31 +0700 Subject: (andri) fix bug shipping method --- indoteknik_custom/models/sale_order.py | 40 +++++++++++++++++++++++++++++++++- indoteknik_custom/views/sale_order.xml | 2 +- 2 files changed, 40 insertions(+), 2 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index f09869da..382272b9 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -7,6 +7,7 @@ import logging, random, string, requests, math, json, re, qrcode, base64 from io import BytesIO from collections import defaultdict import pytz +from lxml import etree _logger = logging.getLogger(__name__) @@ -252,7 +253,44 @@ class SaleOrder(models.Model): select_shipping_option = fields.Selection([ ('biteship', 'Biteship'), ('custom', 'Custom'), - ], string='Select Shipping Option', help="Select shipping option for delivery", Tracking=True) + ], string='Select Shipping Option', help="Select shipping option for delivery", tracking=True) + + def get_biteship_carrier_ids(self): + courier_codes = tuple(self._get_biteship_courier_codes() or []) + if not courier_codes: + return [] + + self.env.cr.execute(""" + SELECT delivery_carrier_id + FROM rajaongkir_kurir + WHERE name IN %s AND delivery_carrier_id IS NOT NULL + """, (courier_codes,)) + result = self.env.cr.fetchall() + carrier_ids = [row[0] for row in result if row[0]] + return carrier_ids + + @api.model + def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): + res = super(SaleOrder, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) + + if view_type == 'form': + doc = etree.XML(res['arch']) + + carrier_ids = self.get_biteship_carrier_ids() + if carrier_ids: + carrier_ids_str = '(' + ','.join(str(x) for x in carrier_ids) + ')' + else: + carrier_ids_str = '(-1,)' # aman kalau kosong + + # ✅ Tambahkan log di sini + _logger.info("🛰️ Biteship Carrier IDs: %s", carrier_ids) + _logger.info("📦 Domain string to apply: [('id', 'in', %s)]", carrier_ids_str) + + for node in doc.xpath("//field[@name='carrier_id']"): + node.set('domain', "[('id', 'in', %s)]" % carrier_ids_str) + + res['arch'] = etree.tostring(doc, encoding='unicode') + return res @api.onchange('shipping_option_id') def _onchange_shipping_option_id(self): diff --git a/indoteknik_custom/views/sale_order.xml b/indoteknik_custom/views/sale_order.xml index 080549a4..eabd5aba 100755 --- a/indoteknik_custom/views/sale_order.xml +++ b/indoteknik_custom/views/sale_order.xml @@ -119,7 +119,7 @@ - + -- cgit v1.2.3 From 2acd9dadd20499ab93c8ece237518f2a9cc7e296 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Mon, 19 May 2025 23:02:46 +0700 Subject: (andri) merapihkan log note estimate shipping --- indoteknik_custom/models/sale_order.py | 59 ++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 25 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 382272b9..f21f35b4 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -523,7 +523,6 @@ class SaleOrder(models.Model): return total_weight def action_estimate_shipping_biteship(self): - total_weight = self._validate_for_shipping_estimate() # Konversi berat ke gram untuk Biteship @@ -602,6 +601,7 @@ class SaleOrder(models.Model): # Proses hasil API shipping_options = [] + courier_options = {} # Dictionary untuk mengelompokkan opsi per kurir shipping_services = result.get('pricing', []) _logger.info(f"Ditemukan {len(shipping_services)} layanan pengiriman") @@ -643,19 +643,30 @@ class SaleOrder(models.Model): }) shipping_options.append(shipping_option) + + # Kelompokkan opsi berdasarkan kurir + courier_upper = courier_code.upper() + if courier_upper not in courier_options: + courier_options[courier_upper] = [] + courier_options[courier_upper].append({ + "name": service_name, + "etd": etd, + "price": price + }) + _logger.info(f"Berhasil membuat opsi pengiriman: {courier_name} - {service_name}") except Exception as e: _logger.error(f"Gagal membuat opsi pengiriman: {str(e)}") # Jika tidak ada opsi pengiriman if not shipping_options: - raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") + raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data.get('destination_postal_code', '')}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") # Set opsi pertama sebagai default - self.shipping_option_id = shipping_options[0].id - self.delivery_amt = shipping_options[0].price + # self.shipping_option_id = shipping_options[0].id + # self.delivery_amt = shipping_options[0].price - # Format pesan untuk log yang lebih informatif + # Format untuk pesan log if use_coordinate: origin_info = f"Koordinat ({origin_data.get('origin_latitude')}, {origin_data.get('origin_longitude')})" destination_info = f"Koordinat ({destination_data.get('destination_latitude')}, {destination_data.get('destination_longitude')})" @@ -663,32 +674,30 @@ class SaleOrder(models.Model): origin_info = f"Kode Pos {origin_data.get('origin_postal_code')}" destination_info = f"Kode Pos {destination_data.get('destination_postal_code')}" - # Format daftar opsi pengiriman - option_list = '
'.join([ - f"{opt.name}: Rp {opt.price:,.0f} ({opt.etd})" - for opt in shipping_options - ]) + # PENTING: Gunakan HTML untuk teks preformatted agar jarak baris terjaga + message_lines = [f"Estimasi Ongkos Kirim Biteship ({origin_info} → {destination_info}):
"] + + # Format setiap kurir dan layanannya + for courier, options in courier_options.items(): + message_lines.append(f"{courier}:
") + for opt in options: + message_lines.append(f"Service: {opt['name']}, ETD: {opt['etd']}, Cost: Rp {int(opt['price']):,}
") + # Tambahkan baris kosong setelah setiap kurir (kecuali yang terakhir) + if courier != list(courier_options.keys())[-1]: + message_lines.append("
") + + # Gabungkan baris pesan dengan HTML line breaks + message_body = "".join(message_lines) - # Log hasil estimasi dengan format yang lebih baik + # Log hasil estimasi dengan format yang diinginkan self.message_post( - body=f"Estimasi Ongkir Biteship ({origin_info} → {destination_info}):
{option_list}", + body=message_body, message_type="comment" ) # Simpan informasi untuk note ekspedisi - selected_option = shipping_options[0] # Opsi pertama dipilih sebagai default - self.note_ekspedisi = f"Pengiriman: {selected_option.name} - Rp {selected_option.price:,.0f} ({selected_option.etd}) [via {api_mode}]" - - return { - 'type': 'ir.actions.client', - 'tag': 'display_notification', - 'params': { - 'title': 'Estimasi Ongkir Berhasil', - 'message': f'Mendapatkan {len(shipping_options)} opsi pengiriman menggunakan {api_mode}', - 'type': 'success', - 'sticky': False, - } - } + # selected_option = shipping_options[0] # Opsi pertama dipilih sebagai default + # self.note_ekspedisi = f"Pengiriman: {selected_option.name} - Rp {selected_option.price:,.0f} ({selected_option.etd}) [via {api_mode}]" def _call_biteship_api(self, origin_data, destination_data, items, couriers=None): -- cgit v1.2.3 From d38635f75fe52cbc958d96e577a83d8b3e1e1272 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Tue, 20 May 2025 13:47:18 +0700 Subject: (andri) fix set shipping option sesuai dengan method yang dipilih --- indoteknik_custom/models/sale_order.py | 60 +++++++++++++++++++++++++++------- indoteknik_custom/views/sale_order.xml | 2 +- 2 files changed, 50 insertions(+), 12 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index f21f35b4..2b2e518a 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -248,7 +248,7 @@ class SaleOrder(models.Model): string="Attachment Bukti Cancel", readonly=False, ) nomor_so_pengganti = fields.Char(string='Nomor SO Pengganti', copy=False, tracking=3) - shipping_option_id = fields.Many2one("shipping.option", string="Selected Shipping Option", domain="['|', ('sale_order_id', '=', False), ('sale_order_id', '=', id)]") + shipping_option_id = fields.Many2one("shipping.option", string="Selected Shipping Option", domain="['|', ('sale_order_id', '=', False), ('sale_order_id', '=', id)]") select_shipping_option = fields.Selection([ ('biteship', 'Biteship'), @@ -295,7 +295,7 @@ class SaleOrder(models.Model): @api.onchange('shipping_option_id') def _onchange_shipping_option_id(self): if self.shipping_option_id: - self.delivery_amt = self.shipping_option_id.price + self.delivery_amt = self.shipping_option_id.price def _get_biteship_courier_codes(self): return [ @@ -340,12 +340,6 @@ class SaleOrder(models.Model): """, (rec.total_percent_margin, rec.id)) self.invalidate_cache() - @api.constrains('shipping_option_id') - def _check_shipping_option(self): - for rec in self: - if rec.shipping_option_id: - rec.delivery_amt = rec.shipping_option_id.price - def _compute_shipping_method_picking(self): for order in self: if order.picking_ids: @@ -662,9 +656,53 @@ class SaleOrder(models.Model): if not shipping_options: raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data.get('destination_postal_code', '')}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") - # Set opsi pertama sebagai default - # self.shipping_option_id = shipping_options[0].id - # self.delivery_amt = shipping_options[0].price + # Set opsi sesuai dengan carrier yang sudah dipilih, atau set opsi pertama sebagai default + selected_option = None + + if self.carrier_id: + # Dapatkan kode kurir dari carrier + rajaongkir_kurir = self.env['rajaongkir.kurir'].search([ + ('delivery_carrier_id', '=', self.carrier_id.id) + ], limit=1) + + # Jika ditemukan rajaongkir_kurir, cari shipping option yang sesuai + if rajaongkir_kurir: + courier_code = rajaongkir_kurir.name.lower() + carrier_name = self.carrier_id.name.lower() + + # Mencoba beberapa kemungkinan format untuk pencocokan + possible_codes = [ + courier_code, + carrier_name, + carrier_name.split()[0] if ' ' in carrier_name else carrier_name + ] + + _logger.info(f"Mencari shipping option untuk kurir: {possible_codes}") + + # Coba temukan shipping option yang sesuai dengan carrier + for option in shipping_options: + option_provider = option.provider.lower() if option.provider else '' + option_name = option.name.lower() if option.name else '' + + # Cek pencocokan untuk provider atau nama + for code in possible_codes: + if code in option_provider or code in option_name: + selected_option = option + _logger.info(f"Menemukan shipping option yang cocok: {option.name}") + break + + if selected_option: + break + + # Jika tidak ada opsi yang cocok dengan carrier, gunakan opsi pertama + if not selected_option and shipping_options: + selected_option = shipping_options[0] + _logger.info(f"Menggunakan opsi pertama: {selected_option.name}") + + # Set shipping option yang terpilih + if selected_option: + self.shipping_option_id = selected_option.id + self.delivery_amt = selected_option.price # Format untuk pesan log if use_coordinate: diff --git a/indoteknik_custom/views/sale_order.xml b/indoteknik_custom/views/sale_order.xml index eabd5aba..1a0895dc 100755 --- a/indoteknik_custom/views/sale_order.xml +++ b/indoteknik_custom/views/sale_order.xml @@ -121,7 +121,7 @@ - + -- cgit v1.2.3 From c109f6704106c59d37715b9e22f464e6f5b106db Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Tue, 20 May 2025 23:16:24 +0700 Subject: (andri) fix list shipping option sesuai dengan method yang dipilih --- indoteknik_custom/models/sale_order.py | 130 +++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 2b2e518a..b2faf9f3 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -302,6 +302,136 @@ class SaleOrder(models.Model): 'gojek','grab','deliveree','lalamove','jne','tiki','ninja','lion','rara','sicepat','jnt','pos','idexpress','rpx','wahana','jdl','pos','anteraja','sap','paxel','borzo' ] + @api.onchange('carrier_id') + def _onchange_carrier_id(self): + self.shipping_option_id = False + self.delivery_amt = 0 + + if not self.carrier_id: + return {'domain': {'shipping_option_id': [('id', '=', -1)]}} + + # Cari provider dari carrier yang dipilih langsung dari rajaongkir_kurir + self.env.cr.execute(""" + SELECT name FROM rajaongkir_kurir + WHERE delivery_carrier_id = %s + LIMIT 1 + """, (self.carrier_id.id,)) + + result = self.env.cr.fetchone() + provider = result[0].lower() if result and result[0] else False + + # Fallback jika tidak ditemukan di rajaongkir_kurir + if not provider: + # Gunakan nama carrier, ambil kata pertama + provider = self.carrier_id.name.lower().split()[0] if self.carrier_id.name else False + + # Log untuk debugging + _logger.info(f"Carrier changed to {self.carrier_id.name}, provider: {provider}") + + # PENTING: self.id mungkin False atau NewId pada saat onchange + # Perlu memeriksa apakah ini adalah record baru atau yang sudah ada + sale_order_id = False + if hasattr(self, '_origin') and self._origin: + sale_order_id = self._origin.id + + # Cek jika ada shipping options dengan provider ini (tanpa filter sale_order_id dulu) + self.env.cr.execute(""" + SELECT COUNT(*) FROM shipping_option + WHERE LOWER(provider) LIKE %s + """, (f'%{provider}%',)) + + count = self.env.cr.fetchone()[0] + _logger.info(f"Found {count} shipping options for provider {provider}") + + # Buat domain untuk shipping_option_id + if count > 0: + # Jika ada options yang tersedia, buat domain yang lebih permisif + domain = [ + '|', + ('provider', 'ilike', f'%{provider}%'), + ('provider', '=', provider) + ] + + # Jika ini record yang sudah ada, tambahkan filter sale_order_id + if sale_order_id: + domain = [ + '|', + '&', ('sale_order_id', '=', sale_order_id), ('provider', 'ilike', f'%{provider}%'), + '&', ('sale_order_id', '=', False), ('provider', 'ilike', f'%{provider}%') + ] + else: + domain = [('id', '=', -1)] # Tidak ada opsi + + _logger.info(f"Final domain for shipping_option_id: {domain}") + + # Masih menggunakan pendekatan mengembalikan domain karena ini yang paling efektif + # meskipun ada peringatan deprecated + return {'domain': {'shipping_option_id': domain}} + + @api.model + def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): + res = super(SaleOrder, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) + + if view_type == 'form': + doc = etree.XML(res['arch']) + + # Filter carrier_id: hanya yang dari Biteship + carrier_ids = self.get_biteship_carrier_ids() + carrier_ids_str = '(' + ','.join(str(x) for x in carrier_ids) + ')' if carrier_ids else '(-1,)' + for node in doc.xpath("//field[@name='carrier_id']"): + node.set('domain', "[('id', 'in', %s)]" % carrier_ids_str) + + # PERBAIKAN UTAMA: Filter shipping_option_id saat form dibuka dalam mode edit + sale_id = self._context.get('active_id') + if sale_id: + # Ambil carrier_id dari database untuk record yang sedang diedit + self.env.cr.execute("SELECT carrier_id FROM sale_order WHERE id = %s", (sale_id,)) + carrier_result = self.env.cr.fetchone() + carrier_id = carrier_result[0] if carrier_result else None + + if carrier_id: + # Cari provider dari rajaongkir_kurir + self.env.cr.execute(""" + SELECT name FROM rajaongkir_kurir + WHERE delivery_carrier_id = %s + LIMIT 1 + """, (carrier_id,)) + row = self.env.cr.fetchone() + provider = None + + if row and row[0]: + provider = row[0].lower() + else: + # Fallback ke nama carrier + self.env.cr.execute("SELECT name FROM delivery_carrier WHERE id = %s", (carrier_id,)) + row = self.env.cr.fetchone() + if row and row[0]: + provider = row[0].lower().split()[0] + + if provider: + _logger.info(f"fields_view_get - Found provider: {provider} for carrier_id: {carrier_id}") + + # PENTING: Query untuk mendapatkan shipping options yang sesuai + # Ambil semua options yang memiliki provider yang cocok + # Dan prioritaskan yang terkait dengan sale_order ini + domain_str = f""" + [ + '|', + '&', ('sale_order_id', '=', {sale_id}), ('provider', 'ilike', '%{provider}%'), + '&', ('sale_order_id', '=', False), ('provider', 'ilike', '%{provider}%') + ] + """ + + # Set domain ke field shipping_option_id + for node in doc.xpath("//field[@name='shipping_option_id']"): + node.set('domain', domain_str) + # Tambahkan options untuk mencegah quick create + node.set('options', "{'no_create': True, 'no_quick_create': True}") + + _logger.info(f"Setting domain in fields_view_get: {domain_str}") + + res['arch'] = etree.tostring(doc, encoding='unicode') + return res @api.onchange('select_shipping_option') def _onchange_select_shipping_option(self): self.shipping_option_id = False -- cgit v1.2.3 From afb745b1e000f4d3c3dba1723ce4a19f44b8c510 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Wed, 21 May 2025 09:18:39 +0700 Subject: (andri) fix edit shipping option --- indoteknik_custom/models/sale_order.py | 95 +++++++++++++--------------------- 1 file changed, 35 insertions(+), 60 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index b2faf9f3..bcc4d5c4 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -363,75 +363,50 @@ class SaleOrder(models.Model): domain = [('id', '=', -1)] # Tidak ada opsi _logger.info(f"Final domain for shipping_option_id: {domain}") - - # Masih menggunakan pendekatan mengembalikan domain karena ini yang paling efektif - # meskipun ada peringatan deprecated return {'domain': {'shipping_option_id': domain}} @api.model - def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): - res = super(SaleOrder, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) + def fields_get(self, allfields=None, attributes=None): + res = super().fields_get(allfields=allfields, attributes=attributes) - if view_type == 'form': - doc = etree.XML(res['arch']) + # Aktifkan hanya kalau sedang buka form Sales Order (safety check) + if self.env.context.get('params', {}).get('model') == 'sale.order' and \ + self.env.context.get('params', {}).get('id'): - # Filter carrier_id: hanya yang dari Biteship - carrier_ids = self.get_biteship_carrier_ids() - carrier_ids_str = '(' + ','.join(str(x) for x in carrier_ids) + ')' if carrier_ids else '(-1,)' - for node in doc.xpath("//field[@name='carrier_id']"): - node.set('domain', "[('id', 'in', %s)]" % carrier_ids_str) + sale_id = self.env.context['params']['id'] - # PERBAIKAN UTAMA: Filter shipping_option_id saat form dibuka dalam mode edit - sale_id = self._context.get('active_id') - if sale_id: - # Ambil carrier_id dari database untuk record yang sedang diedit - self.env.cr.execute("SELECT carrier_id FROM sale_order WHERE id = %s", (sale_id,)) - carrier_result = self.env.cr.fetchone() - carrier_id = carrier_result[0] if carrier_result else None - - if carrier_id: - # Cari provider dari rajaongkir_kurir - self.env.cr.execute(""" - SELECT name FROM rajaongkir_kurir - WHERE delivery_carrier_id = %s - LIMIT 1 - """, (carrier_id,)) + # Ambil carrier_id dari SO yang sedang dibuka + self.env.cr.execute("SELECT carrier_id FROM sale_order WHERE id = %s", (sale_id,)) + row = self.env.cr.fetchone() + carrier_id = row[0] if row else None + + provider = None + if carrier_id: + self.env.cr.execute(""" + SELECT name FROM rajaongkir_kurir WHERE delivery_carrier_id = %s LIMIT 1 + """, (carrier_id,)) + row = self.env.cr.fetchone() + if row and row[0]: + provider = row[0].lower() + else: + self.env.cr.execute("SELECT name FROM delivery_carrier WHERE id = %s", (carrier_id,)) row = self.env.cr.fetchone() - provider = None - - if row and row[0]: - provider = row[0].lower() - else: - # Fallback ke nama carrier - self.env.cr.execute("SELECT name FROM delivery_carrier WHERE id = %s", (carrier_id,)) - row = self.env.cr.fetchone() - if row and row[0]: - provider = row[0].lower().split()[0] - - if provider: - _logger.info(f"fields_view_get - Found provider: {provider} for carrier_id: {carrier_id}") - - # PENTING: Query untuk mendapatkan shipping options yang sesuai - # Ambil semua options yang memiliki provider yang cocok - # Dan prioritaskan yang terkait dengan sale_order ini - domain_str = f""" - [ - '|', - '&', ('sale_order_id', '=', {sale_id}), ('provider', 'ilike', '%{provider}%'), - '&', ('sale_order_id', '=', False), ('provider', 'ilike', '%{provider}%') - ] - """ - - # Set domain ke field shipping_option_id - for node in doc.xpath("//field[@name='shipping_option_id']"): - node.set('domain', domain_str) - # Tambahkan options untuk mencegah quick create - node.set('options', "{'no_create': True, 'no_quick_create': True}") - - _logger.info(f"Setting domain in fields_view_get: {domain_str}") + provider = row[0].lower().split()[0] if row and row[0] else '' + + if provider: + domain = [ + '|', + '&', ('sale_order_id', '=', sale_id), ('provider', 'ilike', f'%{provider}%'), + '&', ('sale_order_id', '=', False), ('provider', 'ilike', f'%{provider}%') + ] + + if 'shipping_option_id' in res: + res['shipping_option_id']['domain'] = domain + _logger.info(f"fields_get - Injected domain for shipping_option_id: {domain}") - res['arch'] = etree.tostring(doc, encoding='unicode') return res + + @api.onchange('select_shipping_option') def _onchange_select_shipping_option(self): self.shipping_option_id = False -- cgit v1.2.3 From 34174e95638e1337169dfa5f3be56b9ef57021a1 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Thu, 22 May 2025 11:14:35 +0700 Subject: (andri) sync quotation web ke odoo terkait kurir, service, & tarif --- indoteknik_custom/models/sale_order.py | 173 ++++++++++++++++++--------------- indoteknik_custom/views/sale_order.xml | 4 +- 2 files changed, 99 insertions(+), 78 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index bcc4d5c4..5a5255b3 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -64,6 +64,7 @@ class ShippingOption(models.Model): price = fields.Float(string="Price", required=True) provider = fields.Char(string="Provider") etd = fields.Char(string="Estimated Delivery Time") + courier_service_code = fields.Char(string="Courier Service Code") sale_order_id = fields.Many2one('sale.order', string="Sale Order", ondelete="cascade") class SaleOrder(models.Model): @@ -253,7 +254,7 @@ class SaleOrder(models.Model): select_shipping_option = fields.Selection([ ('biteship', 'Biteship'), ('custom', 'Custom'), - ], string='Select Shipping Option', help="Select shipping option for delivery", tracking=True) + ], string='Shipping Option', help="Select shipping option for delivery", tracking=True) def get_biteship_carrier_ids(self): courier_codes = tuple(self._get_biteship_courier_codes() or []) @@ -603,8 +604,8 @@ class SaleOrder(models.Model): product_names = '
'.join(missing_weight_products) self.message_post(body=f"Produk berikut tidak memiliki berat:
{product_names}") - if total_weight == 0: - raise UserError("Tidak dapat mengestimasi ongkir tanpa berat yang valid.") + # if total_weight == 0: + # raise UserError("Tidak dapat mengestimasi ongkir tanpa berat yang valid.") # Validasi alamat pengiriman if not self.real_shipping_id: @@ -623,13 +624,11 @@ class SaleOrder(models.Model): def action_estimate_shipping_biteship(self): total_weight = self._validate_for_shipping_estimate() - - # Konversi berat ke gram untuk Biteship + weight_gram = int(total_weight * 1000) if weight_gram < 100: - weight_gram = 100 # Minimum weight untuk Biteship - - # Persiapkan data item + weight_gram = 100 + items = [{ "name": "Paket Pesanan", "description": f"Sale Order {self.name}", @@ -640,26 +639,21 @@ class SaleOrder(models.Model): "width": 10, "length": 10 }] - - # Coba dapatkan data koordinat dari alamat pengiriman + shipping_address = self.real_shipping_id _logger.info(f"Shipping Address: {shipping_address}") - - # Data asal (tetap gudang Bandengan) + origin_data = { "origin_latitude": -6.3031123, "origin_longitude": 106.7794934, } - - # Prioritaskan penggunaan koordinat jika tersedia + destination_data = {} use_coordinate = False - - # Cek apakah latitude dan longitude tersedia dan valid + if hasattr(shipping_address, 'latitude') and hasattr(shipping_address, 'longtitude'): if shipping_address.latitude and shipping_address.longtitude: try: - # Validasi format koordinat lat = float(shipping_address.latitude) lng = float(shipping_address.longtitude) destination_data = { @@ -671,79 +665,72 @@ class SaleOrder(models.Model): except (ValueError, TypeError): _logger.warning(f"Invalid coordinates, falling back to postal code") use_coordinate = False - - # Jika koordinat tidak tersedia atau tidak valid, gunakan kode pos + if not use_coordinate: if shipping_address.zip: - origin_data = {"origin_postal_code": 14440} # Reset origin untuk mode kode pos + origin_data = {"origin_postal_code": 14440} destination_data = { "destination_postal_code": shipping_address.zip } _logger.info(f"Using postal code: {shipping_address.zip}") else: raise UserError("Tidak dapat mengestimasikan ongkir: Kode pos tujuan tidak tersedia.") - - # Siapkan daftar kurir + couriers = ','.join(self._get_biteship_courier_codes()) - - # Panggil API Biteship dengan format yang benar + api_mode = "koordinat" if use_coordinate else "kode_pos" _logger.info(f"Calling Biteship API with mode: {api_mode}") - + result = self._call_biteship_api(origin_data, destination_data, items, couriers) - + if not result: raise UserError("Gagal mendapatkan estimasi ongkir dari Biteship.") - - # Hapus shipping_option lama + self.env["shipping.option"].search([('sale_order_id', '=', self.id)]).unlink() - - # Proses hasil API + shipping_options = [] - courier_options = {} # Dictionary untuk mengelompokkan opsi per kurir + courier_options = {} shipping_services = result.get('pricing', []) - + _logger.info(f"Ditemukan {len(shipping_services)} layanan pengiriman") - + for service in shipping_services: courier_code = service.get('courier_code', '').lower() courier_name = service.get('courier_name', '') service_name = service.get('courier_service_name', '') - price = service.get('price', 0) - + raw_price = service.get('price', 0) + markup_price = int(raw_price * 1.1) + price = round(markup_price / 1000) * 1000 + _logger.info(f"Layanan: {courier_name} - {service_name}, Harga: {price}") - - # Lewati layanan dengan harga 0 + if not price: _logger.warning(f"Melewati layanan dengan harga 0: {courier_name} - {service_name}") continue - - # Format estimasi waktu + duration = service.get('duration', '') shipment_range = service.get('shipment_duration_range', '') shipment_unit = service.get('shipment_duration_unit', 'days') - - # Gunakan duration jika tersedia, jika tidak, buat dari range + if duration: etd = duration elif shipment_range: etd = f"{shipment_range} {shipment_unit}" else: - etd = "1-3 days" # Default fallback - - # Buat shipping option + etd = "1-3 days" + try: shipping_option = self.env["shipping.option"].create({ "name": f"{courier_name} - {service_name}", "price": price, "provider": courier_code, "etd": etd, + "courier_service_code": service.get('courier_service_code'), "sale_order_id": self.id, }) - + shipping_options.append(shipping_option) - - # Kelompokkan opsi berdasarkan kurir + courier_upper = courier_code.upper() if courier_upper not in courier_options: courier_options[courier_upper] = [] @@ -752,87 +739,72 @@ class SaleOrder(models.Model): "etd": etd, "price": price }) - + _logger.info(f"Berhasil membuat opsi pengiriman: {courier_name} - {service_name}") except Exception as e: _logger.error(f"Gagal membuat opsi pengiriman: {str(e)}") - - # Jika tidak ada opsi pengiriman + if not shipping_options: raise UserError(f"Tidak ada layanan pengiriman ditemukan untuk kode pos {destination_data.get('destination_postal_code', '')}. Mohon periksa kembali kode pos atau gunakan metode pengiriman lain.") - - # Set opsi sesuai dengan carrier yang sudah dipilih, atau set opsi pertama sebagai default + selected_option = None if self.carrier_id: - # Dapatkan kode kurir dari carrier rajaongkir_kurir = self.env['rajaongkir.kurir'].search([ ('delivery_carrier_id', '=', self.carrier_id.id) ], limit=1) - - # Jika ditemukan rajaongkir_kurir, cari shipping option yang sesuai + if rajaongkir_kurir: courier_code = rajaongkir_kurir.name.lower() carrier_name = self.carrier_id.name.lower() - - # Mencoba beberapa kemungkinan format untuk pencocokan + possible_codes = [ courier_code, carrier_name, carrier_name.split()[0] if ' ' in carrier_name else carrier_name ] - + _logger.info(f"Mencari shipping option untuk kurir: {possible_codes}") - - # Coba temukan shipping option yang sesuai dengan carrier + for option in shipping_options: option_provider = option.provider.lower() if option.provider else '' option_name = option.name.lower() if option.name else '' - - # Cek pencocokan untuk provider atau nama + for code in possible_codes: if code in option_provider or code in option_name: selected_option = option _logger.info(f"Menemukan shipping option yang cocok: {option.name}") break - + if selected_option: break - # Jika tidak ada opsi yang cocok dengan carrier, gunakan opsi pertama if not selected_option and shipping_options: selected_option = shipping_options[0] _logger.info(f"Menggunakan opsi pertama: {selected_option.name}") - # Set shipping option yang terpilih if selected_option: self.shipping_option_id = selected_option.id self.delivery_amt = selected_option.price - - # Format untuk pesan log + if use_coordinate: origin_info = f"Koordinat ({origin_data.get('origin_latitude')}, {origin_data.get('origin_longitude')})" destination_info = f"Koordinat ({destination_data.get('destination_latitude')}, {destination_data.get('destination_longitude')})" else: origin_info = f"Kode Pos {origin_data.get('origin_postal_code')}" destination_info = f"Kode Pos {destination_data.get('destination_postal_code')}" - - # PENTING: Gunakan HTML untuk teks preformatted agar jarak baris terjaga + message_lines = [f"Estimasi Ongkos Kirim Biteship ({origin_info} → {destination_info}):
"] - - # Format setiap kurir dan layanannya + for courier, options in courier_options.items(): message_lines.append(f"{courier}:
") for opt in options: message_lines.append(f"Service: {opt['name']}, ETD: {opt['etd']}, Cost: Rp {int(opt['price']):,}
") - # Tambahkan baris kosong setelah setiap kurir (kecuali yang terakhir) if courier != list(courier_options.keys())[-1]: message_lines.append("
") - - # Gabungkan baris pesan dengan HTML line breaks + message_body = "".join(message_lines) - - # Log hasil estimasi dengan format yang diinginkan + self.message_post( body=message_body, message_type="comment" @@ -2290,10 +2262,59 @@ class SaleOrder(models.Model): order_line.discount = discount order_line.order_id.use_button = True + def _auto_set_shipping_from_website(self): + for order in self: + # Jalankan hanya untuk SO dari website (ID 59) + if not order.source_id or order.source_id.id != 59: + continue + + # Jika shipping method adalah Self Pick Up (ID 32), atur ke custom + if order.carrier_id and order.carrier_id.id == 32: + order.select_shipping_option = 'custom' + continue + + # Set shipping option ke biteship dan jalankan estimasi + order.select_shipping_option = 'biteship' + order.action_estimate_shipping() + + if not (order.delivery_service_type and order.carrier_id): + continue + + # Ambil provider dari rajaongkir_kurir + self.env.cr.execute(""" + SELECT name FROM rajaongkir_kurir + WHERE delivery_carrier_id = %s LIMIT 1 + """, (order.carrier_id.id,)) + result = self.env.cr.fetchone() + provider = result[0].lower() if result and result[0] else '' + + if not provider and order.carrier_id.name: + provider = order.carrier_id.name.lower().split()[0] + + if not provider: + _logger.warning(f"[AutoSetShipping] Provider tidak ditemukan untuk carrier_id: {order.carrier_id.id}") + continue + + # Cari shipping option berdasarkan provider dan courier_service_code + matched_option = self.env['shipping.option'].search([ + ('sale_order_id', '=', order.id), + ('courier_service_code', '=', order.delivery_service_type), + ('provider', 'ilike', provider), + ], limit=1) + + if matched_option: + order.shipping_option_id = matched_option.id + order.delivery_amt = matched_option.price + _logger.info(f"[AutoSetShipping] Matched via courier_service_code: {matched_option.name} | Provider: {provider}") + else: + _logger.warning(f"[AutoSetShipping] No match for service code '{order.delivery_service_type}' and provider '{provider}' in SO {order.name}") + + @api.model def create(self, vals): # Ensure partner details are updated when a sale order is created order = super(SaleOrder, self).create(vals) + order._auto_set_shipping_from_website() order._compute_etrts_date() order._validate_expected_ready_ship_date() order._validate_delivery_amt() diff --git a/indoteknik_custom/views/sale_order.xml b/indoteknik_custom/views/sale_order.xml index 1a0895dc..34397fc7 100755 --- a/indoteknik_custom/views/sale_order.xml +++ b/indoteknik_custom/views/sale_order.xml @@ -118,10 +118,10 @@ - + - + -- cgit v1.2.3 From fad209db285b0a6204dc1fcbf2e2e0cb13f872b0 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Fri, 23 May 2025 09:05:27 +0700 Subject: (andri) penyesuaian data quotation SO ke delivery biteship --- indoteknik_custom/models/sale_order.py | 6 ++++-- indoteknik_custom/models/stock_picking.py | 5 ++++- indoteknik_custom/views/sale_order.xml | 6 ++++++ 3 files changed, 14 insertions(+), 3 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 5a5255b3..38d2505d 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -249,7 +249,7 @@ class SaleOrder(models.Model): string="Attachment Bukti Cancel", readonly=False, ) nomor_so_pengganti = fields.Char(string='Nomor SO Pengganti', copy=False, tracking=3) - shipping_option_id = fields.Many2one("shipping.option", string="Selected Shipping Option", domain="['|', ('sale_order_id', '=', False), ('sale_order_id', '=', id)]") + shipping_option_id = fields.Many2one("shipping.option", string="Selected Service Option", domain="['|', ('sale_order_id', '=', False), ('sale_order_id', '=', id)]") select_shipping_option = fields.Selection([ ('biteship', 'Biteship'), @@ -296,7 +296,8 @@ class SaleOrder(models.Model): @api.onchange('shipping_option_id') def _onchange_shipping_option_id(self): if self.shipping_option_id: - self.delivery_amt = self.shipping_option_id.price + self.delivery_amt = self.shipping_option_id.price + self.delivery_service_type = self.shipping_option_id.courier_service_code def _get_biteship_courier_codes(self): return [ @@ -786,6 +787,7 @@ class SaleOrder(models.Model): if selected_option: self.shipping_option_id = selected_option.id self.delivery_amt = selected_option.price + self.delivery_service_type = selected_option.courier_service_code if use_coordinate: origin_info = f"Koordinat ({origin_data.get('origin_latitude')}, {origin_data.get('origin_longitude')})" diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 39c74aa2..5548db75 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -565,7 +565,7 @@ class StockPicking(models.Model): "latitude": -6.3031123, "longitude" : 106.7794934999 }, - "reference_id " : self.sale_id.name, + "reference_id" : self.sale_id.name, "shipper_contact_name": self.carrier_id.pic_name or '', "shipper_contact_phone": self.carrier_id.pic_phone or '', "shipper_organization": self.carrier_id.name, @@ -585,6 +585,8 @@ class StockPicking(models.Model): "items": items_data_standard } + _logger.info(f"Payload untuk Biteship: {payload}") + # Cek jika pengiriman instant atau same_day if self.sale_id.delivery_service_type and ("instant" in self.sale_id.delivery_service_type or "same_day" in self.sale_id.delivery_service_type): payload.update({ @@ -603,6 +605,7 @@ class StockPicking(models.Model): # Kirim request ke Biteship response = requests.post(_biteship_url+'/orders', headers=headers, json=payload) + _logger.info(f"Response dari Biteship: {response.text}") if response.status_code == 200: data = response.json() diff --git a/indoteknik_custom/views/sale_order.xml b/indoteknik_custom/views/sale_order.xml index 34397fc7..7e01ba0b 100755 --- a/indoteknik_custom/views/sale_order.xml +++ b/indoteknik_custom/views/sale_order.xml @@ -279,6 +279,12 @@ + + + {'readonly': [('approval_status', '=', 'approved'), ('state', 'not in', + ['cancel','draft'])]} + + {'readonly': [('approval_status', '=', 'approved'), ('state', 'not in', -- cgit v1.2.3 From 48a2eae94b66f7bb8916dcd984bce17fbb36d45e Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Fri, 23 May 2025 09:44:34 +0700 Subject: (andri) add flag di API untuk mengetahui quotation SO dibuat dari website atau bukan --- indoteknik_custom/models/sale_order.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 38d2505d..a41e001b 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -2265,24 +2265,33 @@ class SaleOrder(models.Model): order_line.order_id.use_button = True def _auto_set_shipping_from_website(self): + # Jalankan hanya jika context menandakan ini proses checkout + if not self.env.context.get('from_website_checkout'): + _logger.info("[AutoSetShipping] Dilewati karena bukan dari website checkout (context tidak ada)") + return + for order in self: - # Jalankan hanya untuk SO dari website (ID 59) + _logger.info(f"[AutoSetShipping] Proses otomatis untuk SO: {order.name}") + + # Validasi: pastikan source_id = Website if not order.source_id or order.source_id.id != 59: + _logger.warning(f"[AutoSetShipping] SO {order.name} bukan dari Website (source_id.id != 59)") continue - # Jika shipping method adalah Self Pick Up (ID 32), atur ke custom + # Abaikan jika shipping method adalah Self Pick Up if order.carrier_id and order.carrier_id.id == 32: order.select_shipping_option = 'custom' + _logger.info(f"[AutoSetShipping] SO {order.name} menggunakan Self Pick Up. Set ke custom.") continue - # Set shipping option ke biteship dan jalankan estimasi order.select_shipping_option = 'biteship' order.action_estimate_shipping() if not (order.delivery_service_type and order.carrier_id): + _logger.warning(f"[AutoSetShipping] SO {order.name} tidak memiliki delivery_service_type atau carrier_id") continue - # Ambil provider dari rajaongkir_kurir + # Cari provider dari mapping rajaongkir_kurir self.env.cr.execute(""" SELECT name FROM rajaongkir_kurir WHERE delivery_carrier_id = %s LIMIT 1 @@ -2297,7 +2306,7 @@ class SaleOrder(models.Model): _logger.warning(f"[AutoSetShipping] Provider tidak ditemukan untuk carrier_id: {order.carrier_id.id}") continue - # Cari shipping option berdasarkan provider dan courier_service_code + # Cari shipping option berdasarkan courier_service_code + provider matched_option = self.env['shipping.option'].search([ ('sale_order_id', '=', order.id), ('courier_service_code', '=', order.delivery_service_type), @@ -2307,15 +2316,16 @@ class SaleOrder(models.Model): if matched_option: order.shipping_option_id = matched_option.id order.delivery_amt = matched_option.price - _logger.info(f"[AutoSetShipping] Matched via courier_service_code: {matched_option.name} | Provider: {provider}") + _logger.info(f"[AutoSetShipping] Match: {matched_option.name} | Provider: {provider} | Price: {matched_option.price}") else: - _logger.warning(f"[AutoSetShipping] No match for service code '{order.delivery_service_type}' and provider '{provider}' in SO {order.name}") + _logger.warning(f"[AutoSetShipping] Tidak ditemukan match untuk SO {order.name} dengan service_code '{order.delivery_service_type}' dan provider '{provider}'") @api.model def create(self, vals): # Ensure partner details are updated when a sale order is created order = super(SaleOrder, self).create(vals) + _logger.info(f"[CREATE CONTEXT] {self.env.context}") order._auto_set_shipping_from_website() order._compute_etrts_date() order._validate_expected_ready_ship_date() -- cgit v1.2.3 From 89b157500f517659bb931f6ec81d47f2390ebfd2 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Sat, 24 May 2025 10:15:37 +0700 Subject: (andri) validasi shipping option jika tidak sesuai dengan shipping method --- indoteknik_custom/models/sale_order.py | 100 +++++++++++++++++++++------------ 1 file changed, 64 insertions(+), 36 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index a41e001b..d61e3641 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -367,46 +367,74 @@ class SaleOrder(models.Model): _logger.info(f"Final domain for shipping_option_id: {domain}") return {'domain': {'shipping_option_id': domain}} - @api.model - def fields_get(self, allfields=None, attributes=None): - res = super().fields_get(allfields=allfields, attributes=attributes) - - # Aktifkan hanya kalau sedang buka form Sales Order (safety check) - if self.env.context.get('params', {}).get('model') == 'sale.order' and \ - self.env.context.get('params', {}).get('id'): - - sale_id = self.env.context['params']['id'] - - # Ambil carrier_id dari SO yang sedang dibuka - self.env.cr.execute("SELECT carrier_id FROM sale_order WHERE id = %s", (sale_id,)) - row = self.env.cr.fetchone() - carrier_id = row[0] if row else None + @api.onchange('shipping_option_id') + def _onchange_shipping_option_id(self): + if not self.shipping_option_id or not self.carrier_id: + return - provider = None - if carrier_id: - self.env.cr.execute(""" - SELECT name FROM rajaongkir_kurir WHERE delivery_carrier_id = %s LIMIT 1 - """, (carrier_id,)) - row = self.env.cr.fetchone() - if row and row[0]: - provider = row[0].lower() - else: - self.env.cr.execute("SELECT name FROM delivery_carrier WHERE id = %s", (carrier_id,)) - row = self.env.cr.fetchone() - provider = row[0].lower().split()[0] if row and row[0] else '' + # Ambil provider dari carrier + self.env.cr.execute(""" + SELECT name FROM rajaongkir_kurir + WHERE delivery_carrier_id = %s LIMIT 1 + """, (self.carrier_id.id,)) + row = self.env.cr.fetchone() + provider = row[0].lower() if row and row[0] else self.carrier_id.name.lower().split()[0] - if provider: - domain = [ - '|', - '&', ('sale_order_id', '=', sale_id), ('provider', 'ilike', f'%{provider}%'), - '&', ('sale_order_id', '=', False), ('provider', 'ilike', f'%{provider}%') - ] + selected_provider = (self.shipping_option_id.provider or '').lower() - if 'shipping_option_id' in res: - res['shipping_option_id']['domain'] = domain - _logger.info(f"fields_get - Injected domain for shipping_option_id: {domain}") + if provider not in selected_provider: + warning_msg = { + 'title': "Opsi Tidak Valid", + 'message': f"Opsi pengiriman '{self.shipping_option_id.name}' tidak cocok dengan metode '{self.carrier_id.name}'. Dikembalikan ke sebelumnya." + } - return res + # Kembalikan ke nilai lama (jika record sudah disimpan) + self.shipping_option_id = self._origin.shipping_option_id if self._origin else False + return {'warning': warning_msg} + + # Jika valid + self.delivery_amt = self.shipping_option_id.price + self.delivery_service_type = self.shipping_option_id.courier_service_code + + # @api.model + # def fields_get(self, allfields=None, attributes=None): + # res = super().fields_get(allfields=allfields, attributes=attributes) + + # # Aktifkan hanya kalau sedang buka form Sales Order (safety check) + # if self.env.context.get('params', {}).get('model') == 'sale.order' and \ + # self.env.context.get('params', {}).get('id'): + + # sale_id = self.env.context['params']['id'] + + # # Ambil carrier_id dari SO yang sedang dibuka + # self.env.cr.execute("SELECT carrier_id FROM sale_order WHERE id = %s", (sale_id,)) + # row = self.env.cr.fetchone() + # carrier_id = row[0] if row else None + + # provider = None + # if carrier_id: + # self.env.cr.execute(""" + # SELECT name FROM rajaongkir_kurir WHERE delivery_carrier_id = %s LIMIT 1 + # """, (carrier_id,)) + # row = self.env.cr.fetchone() + # if row and row[0]: + # provider = row[0].lower() + # else: + # self.env.cr.execute("SELECT name FROM delivery_carrier WHERE id = %s", (carrier_id,)) + # row = self.env.cr.fetchone() + # provider = row[0].lower().split()[0] if row and row[0] else '' + + # if provider: + # domain = [ + # '|', + # '&', ('sale_order_id', '=', sale_id), ('provider', 'ilike', f'%{provider}%'), + # '&', ('sale_order_id', '=', False), ('provider', 'ilike', f'%{provider}%') + # ] + + # if 'shipping_option_id' in res: + # res['shipping_option_id']['domain'] = domain + # _logger.info(f"fields_get - Injected domain for shipping_option_id: {domain}") + # return res @api.onchange('select_shipping_option') -- cgit v1.2.3 From efb7581b37cb6b007e249c201a4e48a3e5261dd1 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Sun, 25 May 2025 17:47:13 +0700 Subject: (andri) fix bug value delivery service type yang kembali ke nilai awal ketika di save --- indoteknik_custom/models/sale_order.py | 40 +++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index d61e3641..8cf38040 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -293,11 +293,11 @@ class SaleOrder(models.Model): res['arch'] = etree.tostring(doc, encoding='unicode') return res - @api.onchange('shipping_option_id') - def _onchange_shipping_option_id(self): - if self.shipping_option_id: - self.delivery_amt = self.shipping_option_id.price - self.delivery_service_type = self.shipping_option_id.courier_service_code + # @api.onchange('shipping_option_id') + # def _onchange_shipping_option_id(self): + # if self.shipping_option_id: + # self.delivery_amt = self.shipping_option_id.price + # self.delivery_service_type = self.shipping_option_id.courier_service_code def _get_biteship_courier_codes(self): return [ @@ -369,7 +369,13 @@ class SaleOrder(models.Model): @api.onchange('shipping_option_id') def _onchange_shipping_option_id(self): - if not self.shipping_option_id or not self.carrier_id: + if not self.shipping_option_id: + return + + if not self.carrier_id: + # Jika belum pilih carrier, tetap update harga dan service type + self.delivery_amt = self.shipping_option_id.price + self.delivery_service_type = self.shipping_option_id.courier_service_code return # Ambil provider dari carrier @@ -396,6 +402,19 @@ class SaleOrder(models.Model): self.delivery_amt = self.shipping_option_id.price self.delivery_service_type = self.shipping_option_id.courier_service_code + def _update_delivery_service_type_from_shipping_option(self, vals): + shipping_option_id = vals.get('shipping_option_id') or self.shipping_option_id.id + if shipping_option_id: + shipping_option = self.env['shipping.option'].browse(shipping_option_id) + if shipping_option.exists(): + courier_service = shipping_option.courier_service_code + vals['delivery_service_type'] = courier_service + _logger.info("🛰️ Set delivery_service_type: %s from shipping_option_id: %s", courier_service, shipping_option_id) + else: + _logger.warning("⚠️ shipping_option_id %s not found or invalid.", shipping_option_id) + else: + _logger.info("ℹ️ shipping_option_id not found in vals or record.") + # @api.model # def fields_get(self, allfields=None, attributes=None): # res = super().fields_get(allfields=allfields, attributes=attributes) @@ -2390,6 +2409,13 @@ class SaleOrder(models.Model): 'customer_type': partner.customer_type, }) + def write(self, vals): + if 'shipping_option_id' in vals and vals['shipping_option_id']: + shipping_option = self.env['shipping.option'].browse(vals['shipping_option_id']) + if shipping_option: + vals['delivery_service_type'] = shipping_option.courier_service_code + return super(SaleOrder, self).write(vals) + def write(self, vals): for order in self: if order.state in ['sale', 'cancel']: @@ -2399,6 +2425,8 @@ class SaleOrder(models.Model): if command[0] == 0: # A new line is being added raise UserError( "SO tidak dapat ditambahkan produk baru karena SO sudah menjadi sale order.") + + order._update_delivery_service_type_from_shipping_option(vals) res = super(SaleOrder, self).write(vals) # self._check_total_margin_excl_third_party() -- cgit v1.2.3 From 85f9481cce4fbec278d2cde48f009d480b8a35ed Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Mon, 26 May 2025 17:40:50 +0700 Subject: (andri) match selected service type pada web dan juga odoo --- indoteknik_custom/models/sale_order.py | 91 +++++++++++++++++++--------------- 1 file changed, 50 insertions(+), 41 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 8cf38040..e5297011 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -2312,61 +2312,70 @@ class SaleOrder(models.Model): order_line.order_id.use_button = True def _auto_set_shipping_from_website(self): - # Jalankan hanya jika context menandakan ini proses checkout if not self.env.context.get('from_website_checkout'): - _logger.info("[AutoSetShipping] Dilewati karena bukan dari website checkout (context tidak ada)") return for order in self: - _logger.info(f"[AutoSetShipping] Proses otomatis untuk SO: {order.name}") - - # Validasi: pastikan source_id = Website + # Validasi source website if not order.source_id or order.source_id.id != 59: - _logger.warning(f"[AutoSetShipping] SO {order.name} bukan dari Website (source_id.id != 59)") continue - # Abaikan jika shipping method adalah Self Pick Up + # Skip jika Self Pick Up if order.carrier_id and order.carrier_id.id == 32: order.select_shipping_option = 'custom' - _logger.info(f"[AutoSetShipping] SO {order.name} menggunakan Self Pick Up. Set ke custom.") continue + # Simpan pilihan user sebelum estimasi + user_carrier_id = order.carrier_id.id if order.carrier_id else None + user_service = order.delivery_service_type + user_amount = order.delivery_amt + + # Jalankan estimasi untuk refresh data order.select_shipping_option = 'biteship' order.action_estimate_shipping() - if not (order.delivery_service_type and order.carrier_id): - _logger.warning(f"[AutoSetShipping] SO {order.name} tidak memiliki delivery_service_type atau carrier_id") - continue - - # Cari provider dari mapping rajaongkir_kurir - self.env.cr.execute(""" - SELECT name FROM rajaongkir_kurir - WHERE delivery_carrier_id = %s LIMIT 1 - """, (order.carrier_id.id,)) - result = self.env.cr.fetchone() - provider = result[0].lower() if result and result[0] else '' - - if not provider and order.carrier_id.name: - provider = order.carrier_id.name.lower().split()[0] - - if not provider: - _logger.warning(f"[AutoSetShipping] Provider tidak ditemukan untuk carrier_id: {order.carrier_id.id}") - continue - - # Cari shipping option berdasarkan courier_service_code + provider - matched_option = self.env['shipping.option'].search([ - ('sale_order_id', '=', order.id), - ('courier_service_code', '=', order.delivery_service_type), - ('provider', 'ilike', provider), - ], limit=1) - - if matched_option: - order.shipping_option_id = matched_option.id - order.delivery_amt = matched_option.price - _logger.info(f"[AutoSetShipping] Match: {matched_option.name} | Provider: {provider} | Price: {matched_option.price}") - else: - _logger.warning(f"[AutoSetShipping] Tidak ditemukan match untuk SO {order.name} dengan service_code '{order.delivery_service_type}' dan provider '{provider}'") - + # Restore pilihan user setelah estimasi + if user_carrier_id and user_service: + # Dapatkan provider + self.env.cr.execute("SELECT name FROM rajaongkir_kurir WHERE delivery_carrier_id = %s LIMIT 1", (user_carrier_id,)) + result = self.env.cr.fetchone() + provider = result[0].lower() if result else order.env['delivery.carrier'].browse(user_carrier_id).name.lower().split()[0] + + # Cari opsi yang cocok (prioritas: service code > nama > harga > fallback) + domain_options = [ + [('courier_service_code', '=', user_service), ('provider', 'ilike', provider)], # exact service + [('name', 'ilike', user_service), ('provider', 'ilike', provider)], # nama service + [('price', '=', user_amount), ('provider', 'ilike', provider)] if user_amount > 0 else None, # harga sama + [('provider', 'ilike', provider)] # fallback + ] + + matched_option = None + for domain in domain_options: + if domain: + matched_option = self.env['shipping.option'].search([('sale_order_id', '=', order.id)] + domain, limit=1) + if matched_option: + break + + # Set opsi yang cocok atau buat manual + if matched_option: + order.shipping_option_id = matched_option.id + order.delivery_amt = matched_option.price + order.delivery_service_type = matched_option.courier_service_code + + # Notif jika harga berubah + if user_amount > 0 and abs(matched_option.price - user_amount) > 1000: + order.message_post(body=f"Harga shipping berubah dari Rp {user_amount:,} ke Rp {matched_option.price:,}") + + elif user_amount > 0: + # Buat opsi manual jika tidak ada yang cocok + manual_option = self.env['shipping.option'].create({ + 'name': f"{provider.upper()} - {user_service}", + 'price': user_amount, + 'provider': provider, + 'courier_service_code': user_service, + 'sale_order_id': order.id, + }) + order.shipping_option_id = manual_option.id @api.model def create(self, vals): -- cgit v1.2.3 From 76c8db3d444197af6e29a9b4071054383db9d4f7 Mon Sep 17 00:00:00 2001 From: Miqdad Date: Mon, 26 May 2025 21:17:48 +0700 Subject: vendor_id return false/null instead of empty string --- indoteknik_custom/models/sale_order_line.py | 87 +++++++++++++++++------------ 1 file changed, 51 insertions(+), 36 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order_line.py b/indoteknik_custom/models/sale_order_line.py index 9247d1c1..c8066961 100644 --- a/indoteknik_custom/models/sale_order_line.py +++ b/indoteknik_custom/models/sale_order_line.py @@ -6,19 +6,22 @@ from datetime import datetime, timedelta class SaleOrderLine(models.Model): _inherit = 'sale.order.line' item_margin = fields.Float('Margin', compute='compute_item_margin', help="Total Margin in Sales Order Header") - item_before_margin = fields.Float('Before Margin', compute='compute_item_before_margin', help="Total Margin in Sales Order Header") - item_percent_margin = fields.Float('%Margin', compute='compute_item_margin', help="Total % Margin in Sales Order Header") + item_before_margin = fields.Float('Before Margin', compute='compute_item_before_margin', + help="Total Margin in Sales Order Header") + item_percent_margin = fields.Float('%Margin', compute='compute_item_margin', + help="Total % Margin in Sales Order Header") initial_discount = fields.Float('Initial Discount') vendor_id = fields.Many2one( 'res.partner', string='Vendor', readonly=True, change_default=True, index=True, tracking=1, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]" - ) - vendor_md_id = fields.Many2one('res.partner', string='MD Vendor') + ) + vendor_md_id = fields.Many2one('res.partner', string='MD Vendor') purchase_price = fields.Float('Purchase', required=True, digits='Product Price', default=0.0) purchase_price_md = fields.Float('MD Purchase') - purchase_tax_id = fields.Many2one('account.tax', string='Tax', domain=['|', ('active', '=', False), ('active', '=', True)]) + purchase_tax_id = fields.Many2one('account.tax', string='Tax', + domain=['|', ('active', '=', False), ('active', '=', True)]) delivery_amt_line = fields.Float('DeliveryAmtLine', compute='compute_delivery_amt_line') fee_third_party_line = fields.Float('FeeThirdPartyLine', compute='compute_fee_third_party_line', default=0) line_no = fields.Integer('No', default=0, copy=False) @@ -28,13 +31,15 @@ class SaleOrderLine(models.Model): ('info_vendor', 'Info Vendor'), ('penggabungan', 'Penggabungan'), ], string='Note', help="Harap diisi jika ada keterangan tambahan dari Procurement, agar dapat dimonitoring") - note_procurement = fields.Char(string='Note Detail', help="Harap diisi jika ada keterangan tambahan dari Procurement, agar dapat dimonitoring") + note_procurement = fields.Char(string='Note Detail', + help="Harap diisi jika ada keterangan tambahan dari Procurement, agar dapat dimonitoring") vendor_subtotal = fields.Float(string='Vendor Subtotal', compute="_compute_vendor_subtotal") amount_voucher_disc = fields.Float(string='Voucher Discount') qty_reserved = fields.Float(string='Qty Reserved', compute='_compute_qty_reserved') - product_available_quantity = fields.Float(string='Qty pickup by user',) + product_available_quantity = fields.Float(string='Qty pickup by user', ) reserved_from = fields.Char(string='Reserved From', copy=False) - item_percent_margin_without_deduction = fields.Float('Margin Without Deduction', compute='_compute_item_margin_without_deduction') + item_percent_margin_without_deduction = fields.Float('Margin Without Deduction', + compute='_compute_item_margin_without_deduction') weight = fields.Float(string='Weight') md_vendor_id = fields.Many2one('res.partner', string='MD Vendor', readonly=True) margin_md = fields.Float(string='Margin MD') @@ -45,7 +50,8 @@ class SaleOrderLine(models.Model): outgoing_moves = self.env['stock.move'] incoming_moves = self.env['stock.move'] - for move in self.move_ids.filtered(lambda r: r.state != 'cancel' and not r.scrapped and self.product_id == r.product_id): + for move in self.move_ids.filtered( + lambda r: r.state != 'cancel' and not r.scrapped and self.product_id == r.product_id): if move.location_dest_id.usage == "customer": if not move.origin_returned_move_id or (move.origin_returned_move_id and move.to_refund): outgoing_moves |= move @@ -80,7 +86,7 @@ class SaleOrderLine(models.Model): if not self.product_uom or not self.product_id: self.price_unit = 0.0 return - + self.price_unit = self.price_unit def _compute_qty_reserved(self): @@ -158,7 +164,7 @@ class SaleOrderLine(models.Model): line.item_percent_margin = 0 if not line.margin_md: - line.margin_md = line.item_percent_margin + line.margin_md = line.item_percent_margin def compute_item_before_margin(self): for line in self: @@ -169,7 +175,7 @@ class SaleOrderLine(models.Model): continue # calculate margin without tax sales_price = line.price_reduce_taxexcl * line.product_uom_qty - + purchase_price = line.purchase_price if line.purchase_tax_id.price_include: purchase_price = line.purchase_price / 1.11 @@ -183,7 +189,7 @@ class SaleOrderLine(models.Model): # TODO : need to change this logic @stephan if not self.product_id or self.product_id.type == 'service': return - elif self.product_id.categ_id.id == 34: # finish good / manufacturing only + elif self.product_id.categ_id.id == 34: # finish good / manufacturing only cost = self.product_id.standard_price self.purchase_price = cost elif self.product_id.x_manufacture.override_vendor_id: @@ -195,12 +201,12 @@ class SaleOrderLine(models.Model): self.purchase_price = price self.purchase_tax_id = taxes # else: - # purchase_price = self.env['purchase.pricelist'].search( - # [('vendor_id', '=', self.vendor_id.id), ('product_id', '=', self.product_id.id)], - # limit=1, order='count_trx_po desc, count_trx_po_vendor desc') - # price, taxes = self._get_valid_purchase_price(purchase_price) - # self.purchase_price = price - # self.purchase_tax_id = taxes + # purchase_price = self.env['purchase.pricelist'].search( + # [('vendor_id', '=', self.vendor_id.id), ('product_id', '=', self.product_id.id)], + # limit=1, order='count_trx_po desc, count_trx_po_vendor desc') + # price, taxes = self._get_valid_purchase_price(purchase_price) + # self.purchase_price = price + # self.purchase_tax_id = taxes # def _calculate_selling_price(self): # rec_purchase_price, rec_taxes, rec_vendor_id = self._get_purchase_price(self.product_id) @@ -260,7 +266,7 @@ class SaleOrderLine(models.Model): price = 0 taxes = 24 - vendor_id = '' + vendor_id = False human_last_update = purchase_price.human_last_update or datetime.min system_last_update = purchase_price.system_last_update or datetime.min @@ -271,18 +277,18 @@ class SaleOrderLine(models.Model): if delta_time > human_last_update: price = 0 taxes = 24 - vendor_id = '' + vendor_id = False if system_last_update > human_last_update: - #if purchase_price.taxes_system_id.type_tax_use == 'purchase': + # if purchase_price.taxes_system_id.type_tax_use == 'purchase': price = purchase_price.system_price taxes = purchase_price.taxes_system_id.id or 24 vendor_id = purchase_price.vendor_id.id if delta_time > system_last_update: price = 0 taxes = 24 - vendor_id = '' - + vendor_id = False + return price, taxes, vendor_id @api.onchange('product_id') @@ -302,11 +308,11 @@ class SaleOrderLine(models.Model): line.tax_id = line.order_id.sales_tax_id # price, taxes = line._get_valid_purchase_price(purchase_price) line.purchase_price = price - line.purchase_tax_id = taxes + line.purchase_tax_id = taxes attribute_values = line.product_id.product_template_attribute_value_ids.mapped('name') attribute_values_str = ', '.join(attribute_values) if attribute_values else '' - + line_name = ('[' + line.product_id.default_code + ']' if line.product_id.default_code else '') + ' ' + \ (line.product_id.name if line.product_id.name else '') + ' ' + \ ('(' + attribute_values_str + ')' if attribute_values_str else '') + ' ' + \ @@ -324,7 +330,7 @@ class SaleOrderLine(models.Model): price, taxes, vendor_id = self._get_purchase_price(line.product_id) line.vendor_md_id = vendor_id if vendor_id else None line.margin_md = line.item_percent_margin - line.purchase_price_md = price + line.purchase_price_md = price def compute_delivery_amt_line(self): for line in self: @@ -363,11 +369,15 @@ class SaleOrderLine(models.Model): fiscal_position=self.env.context.get('fiscal_position') ) - product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id) + product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, + uom=self.product_uom.id) price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule( self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id) - new_list_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id) + new_list_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, + self.product_uom_qty, + self.product_uom, + self.order_id.pricelist_id.id) new_list_price = product.web_price if new_list_price != 0: @@ -390,8 +400,8 @@ class SaleOrderLine(models.Model): no_variant_attributes_price_extra = [ ptav.price_extra for ptav in self.product_no_variant_attribute_value_ids.filtered( lambda ptav: - ptav.price_extra and - ptav not in product.product_template_attribute_value_ids + ptav.price_extra and + ptav not in product.product_template_attribute_value_ids ) ] if no_variant_attributes_price_extra: @@ -401,10 +411,15 @@ class SaleOrderLine(models.Model): if self.order_id.pricelist_id.discount_policy == 'with_discount': return product.with_context(pricelist=self.order_id.pricelist_id.id, uom=self.product_uom.id).price - product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, uom=self.product_uom.id) - - final_price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule(product or self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id) - base_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id) + product_context = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order, + uom=self.product_uom.id) + + final_price, rule_id = self.order_id.pricelist_id.with_context(product_context).get_product_price_rule( + product or self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id) + base_price, currency = self.with_context(product_context)._get_real_price_currency(product, rule_id, + self.product_uom_qty, + self.product_uom, + self.order_id.pricelist_id.id) base_price = product.web_price if currency != self.order_id.pricelist_id.currency_id: base_price = currency._convert( @@ -413,7 +428,7 @@ class SaleOrderLine(models.Model): # negative discounts (= surcharge) are included in the display price return max(base_price, final_price) - + def validate_line(self): for line in self: if line.product_id.id in [385544, 224484, 417724]: -- cgit v1.2.3 From 121f5f732fc837e1f8b801eaaed038962aa574fd Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 09:54:41 +0700 Subject: notif diffrent vendor so and po --- indoteknik_custom/models/purchase_order.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/purchase_order.py b/indoteknik_custom/models/purchase_order.py index cbfd4acd..36c4c7b9 100755 --- a/indoteknik_custom/models/purchase_order.py +++ b/indoteknik_custom/models/purchase_order.py @@ -817,7 +817,11 @@ class PurchaseOrder(models.Model): if not line.so_line_id: continue if line.so_line_id.vendor_id.id != vendor_po and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser'): - raise UserError("Produk "+line.product_id.name+" memiliki vendor berbeda dengan SO (Vendor PO: "+str(self.partner_id.name)+", Vendor SO: "+str(line.so_line_id.vendor_id.name)+")") + self.env.user.notify_danger( + title='WARNING!!!', + message="Produk "+line.product_id.name+" memiliki vendor berbeda dengan SO (Vendor PO: "+str(self.partner_id.name)+", Vendor SO: "+str(line.so_line_id.vendor_id.name)+")", + sticky=True + ) def button_confirm(self): # self._check_payment_term() # check payment term -- cgit v1.2.3 From b7cb8418e18de4507bc81d04e8c150f78343b92e Mon Sep 17 00:00:00 2001 From: it-fixcomart Date: Tue, 27 May 2025 10:09:54 +0700 Subject: validation qty demand --- indoteknik_custom/models/stock_picking.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 0fcb7ca1..cbfcda22 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -1269,6 +1269,20 @@ class StockPicking(models.Model): current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.date_reserved = current_time + # Validate Qty Demand Can't higher than Qty Product + for move_line in self.move_line_ids_without_package: + purchase_line = move_line.move_id.purchase_line_id + if purchase_line: + if purchase_line.product_uom_qty < move_line.product_uom_qty: + raise UserError( + _("Quantity demand (%s) tidak bisa lebih besar dari qty product (%s) untuk produk %s") % ( + move_line.product_uom_qty, + purchase_line.product_uom_qty, + move_line.product_id.display_name + ) + ) + + self.validation_minus_onhand_quantity() self.responsible = self.env.user.id # self.send_koli_to_so() -- cgit v1.2.3 From 44dc882a2af128a523ad8c594056261ad294be34 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 10:11:58 +0700 Subject: cr akses approval on rpo --- indoteknik_custom/models/requisition.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/requisition.py b/indoteknik_custom/models/requisition.py index 74236850..775acfb9 100644 --- a/indoteknik_custom/models/requisition.py +++ b/indoteknik_custom/models/requisition.py @@ -82,20 +82,20 @@ class Requisition(models.Model): state = ['done', 'sale'] if self.sale_order_id.state in state: raise UserError('SO sudah Confirm, akan berakibat double Purchase melalui PJ') - if self.env.user.id not in [377, 19, 28]: - raise UserError('Hanya Vita dan Darren Yang Bisa Approve') - if self.env.user.id == 377 or self.env.user.id == 28: + if self.env.user.id not in [21, 19, 28]: + raise UserError('Hanya Rafly dan Darren Yang Bisa Approve') + if self.env.user.id == 19 or self.env.user.id == 28: self.sales_approve = True - elif self.env.user.id == 19 or self.env.user.id == 28: + elif self.env.user.id == 21 or self.env.user.id == 28: if not self.sales_approve: raise UserError('Vita Belum Approve') self.merchandise_approve = True def create_po_from_requisition(self): if not self.sales_approve: - raise UserError('Harus Di Approve oleh Vita') - if not self.merchandise_approve: raise UserError('Harus Di Approve oleh Darren') + if not self.merchandise_approve: + raise UserError('Harus Di Approve oleh Rafly') if not self.requisition_lines: raise UserError('Tidak ada Lines, belum bisa create PO') if self.is_po: -- cgit v1.2.3 From b5bc5c5bc63ecbfa7efe9ff06a373bbedfcf7d42 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 10:12:26 +0700 Subject: push --- indoteknik_custom/models/requisition.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/requisition.py b/indoteknik_custom/models/requisition.py index 775acfb9..25133e72 100644 --- a/indoteknik_custom/models/requisition.py +++ b/indoteknik_custom/models/requisition.py @@ -88,7 +88,7 @@ class Requisition(models.Model): self.sales_approve = True elif self.env.user.id == 21 or self.env.user.id == 28: if not self.sales_approve: - raise UserError('Vita Belum Approve') + raise UserError('Darren Belum Approve') self.merchandise_approve = True def create_po_from_requisition(self): -- cgit v1.2.3 From a01f05f50dd852e76b44709259e8baaf33e4b462 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 10:35:08 +0700 Subject: push --- indoteknik_custom/models/shipment_group.py | 4 ++-- indoteknik_custom/models/stock_picking.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/shipment_group.py b/indoteknik_custom/models/shipment_group.py index 87d222a6..2d84d54c 100644 --- a/indoteknik_custom/models/shipment_group.py +++ b/indoteknik_custom/models/shipment_group.py @@ -19,10 +19,10 @@ class ShipmentGroup(models.Model): def sync_api_shipping(self): for rec in self.shipment_line: - if rec.shipment_id.carrier_id == 173: + if rec.shipment_id.carrier_id.id == 173: rec.picking_id.action_get_kgx_pod() - if rec.shipment_id.carrier_id == 151: + if rec.shipment_id.carrier_id.id == 151: rec.picking_id.track_envio_shipment() @api.depends('shipment_line.total_colly') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 0fcb7ca1..05f946fd 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -288,7 +288,7 @@ class StockPicking(models.Model): self.ensure_one() if not self.name or not self.origin: return False - return f"{self.name} {self.origin}" + return f"{self.name}, {self.origin}" def _download_pod_photo(self, url): """Mengunduh foto POD dari URL""" -- cgit v1.2.3 From c4aebb9fc2cb875554b26e21231de0ad0bfd48ce Mon Sep 17 00:00:00 2001 From: stephanchrst Date: Tue, 27 May 2025 10:38:38 +0700 Subject: add qty outgoing manufacturing order formula in free qty --- indoteknik_custom/models/product_template.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/product_template.py b/indoteknik_custom/models/product_template.py index 3bb54f44..2c07824a 100755 --- a/indoteknik_custom/models/product_template.py +++ b/indoteknik_custom/models/product_template.py @@ -1146,7 +1146,7 @@ class ProductProduct(models.Model): def _get_qty_free_bandengan(self): for product in self: - qty_free = product.qty_onhand_bandengan - product.qty_outgoing_bandengan + qty_free = product.qty_onhand_bandengan - product.qty_outgoing_bandengan - product.qty_outgoing_mo_bandengan product.qty_free_bandengan = qty_free def _get_max_qty_reordering_rule(self): -- cgit v1.2.3 From af127b94e7b597a3451f42199df56e27899272fd Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 10:45:11 +0700 Subject: push --- indoteknik_custom/models/stock_picking.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 05f946fd..887b2f92 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -625,7 +625,7 @@ class StockPicking(models.Model): ('state', '=', 'done'), ('carrier_id', '=', 151) ]) - for picking in pickings: + for picking in self: if not picking.name: raise UserError("Name pada stock.picking tidak ditemukan.") -- cgit v1.2.3 From 755f6efe380cbbdd05ba592f651ca87030a22143 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 10:57:24 +0700 Subject: fix api shipment group --- indoteknik_custom/models/purchase_order.py | 4 ++-- indoteknik_custom/models/shipment_group.py | 10 ++++++---- indoteknik_custom/models/stock_picking.py | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/purchase_order.py b/indoteknik_custom/models/purchase_order.py index 36c4c7b9..2513f8fd 100755 --- a/indoteknik_custom/models/purchase_order.py +++ b/indoteknik_custom/models/purchase_order.py @@ -849,8 +849,8 @@ class PurchaseOrder(models.Model): ) if not self.from_apo: - if not self.matches_so and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser') and not self.env.user.is_leader: - raise UserError("Tidak ada link dengan SO, harus approval Merchandise") + if not self.matches_so and not self.env.user.id == 21: + raise UserError("Tidak ada link dengan SO, harus approval Rafly") send_email = False if not self.not_update_purchasepricelist: diff --git a/indoteknik_custom/models/shipment_group.py b/indoteknik_custom/models/shipment_group.py index 2d84d54c..ea91238a 100644 --- a/indoteknik_custom/models/shipment_group.py +++ b/indoteknik_custom/models/shipment_group.py @@ -19,11 +19,13 @@ class ShipmentGroup(models.Model): def sync_api_shipping(self): for rec in self.shipment_line: + picking_names = [picking.name for picking in rec.picking_id] if rec.shipment_id.carrier_id.id == 173: - rec.picking_id.action_get_kgx_pod() - - if rec.shipment_id.carrier_id.id == 151: - rec.picking_id.track_envio_shipment() + rec.picking_id.action_get_kgx_pod( + shipment=f"{self.number},{','.join(picking_names)}" + ) + elif rec.shipment_id.carrier_id.id == 151: + rec.picking_id.track_envio_shipment() @api.depends('shipment_line.total_colly') def _compute_total_colly_line(self): diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 887b2f92..3223377c 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -310,10 +310,10 @@ class StockPicking(models.Model): except ValueError: return False - def action_get_kgx_pod(self): + def action_get_kgx_pod(self, shipment=False): self.ensure_one() - awb_number = self._get_kgx_awb_number() + awb_number = shipment or self._get_kgx_awb_number() if not awb_number: raise UserError("Nomor AWB tidak dapat dibuat, pastikan picking memiliki name dan origin") -- cgit v1.2.3 From 660d79ee317460e79a61287bda7d7a8e8b423b48 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 11:00:46 +0700 Subject: push --- indoteknik_custom/models/purchase_order.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/purchase_order.py b/indoteknik_custom/models/purchase_order.py index 2513f8fd..53037703 100755 --- a/indoteknik_custom/models/purchase_order.py +++ b/indoteknik_custom/models/purchase_order.py @@ -808,8 +808,8 @@ class PurchaseOrder(models.Model): # test = line.product_uom_qty # test2 = line.product_id.plafon_qty # test3 = test2 + line.product_uom_qty - if line.product_uom_qty > line.product_id.plafon_qty + line.product_uom_qty and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser'): - raise UserError('Product '+line.product_id.name+' melebihi plafon, harus Approval MD') + if line.product_uom_qty > line.product_id.plafon_qty + line.product_uom_qty and not self.env.user.id == 21: + raise UserError('Product '+line.product_id.name+' melebihi plafon, harus Approval Rafly') def check_different_vendor_so_po(self): vendor_po = self.partner_id.id -- cgit v1.2.3 From 4ba7242388db36fa641ea2008af08319a3dc014c Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 11:03:53 +0700 Subject: fix syntax get name picking --- indoteknik_custom/models/shipment_group.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/shipment_group.py b/indoteknik_custom/models/shipment_group.py index ea91238a..09a4fba9 100644 --- a/indoteknik_custom/models/shipment_group.py +++ b/indoteknik_custom/models/shipment_group.py @@ -19,7 +19,7 @@ class ShipmentGroup(models.Model): def sync_api_shipping(self): for rec in self.shipment_line: - picking_names = [picking.name for picking in rec.picking_id] + picking_names = [picking.picking_id.name for picking in rec] if rec.shipment_id.carrier_id.id == 173: rec.picking_id.action_get_kgx_pod( shipment=f"{self.number},{','.join(picking_names)}" -- cgit v1.2.3 From dad6bca8abdda9e5987a0adb8cae75540b6176eb Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 11:10:09 +0700 Subject: push --- indoteknik_custom/models/shipment_group.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/shipment_group.py b/indoteknik_custom/models/shipment_group.py index 09a4fba9..9ebf36c0 100644 --- a/indoteknik_custom/models/shipment_group.py +++ b/indoteknik_custom/models/shipment_group.py @@ -19,10 +19,10 @@ class ShipmentGroup(models.Model): def sync_api_shipping(self): for rec in self.shipment_line: - picking_names = [picking.picking_id.name for picking in rec] + picking_names = [lines.picking_id.name for lines in self.shipment_line] if rec.shipment_id.carrier_id.id == 173: rec.picking_id.action_get_kgx_pod( - shipment=f"{self.number},{','.join(picking_names)}" + shipment=f"{self.number}, {', '.join(picking_names)}" ) elif rec.shipment_id.carrier_id.id == 151: rec.picking_id.track_envio_shipment() -- cgit v1.2.3 From ae9766498d304a8336737453310e4272929cea73 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Tue, 27 May 2025 11:20:09 +0700 Subject: push --- indoteknik_custom/models/shipment_group.py | 2 +- indoteknik_custom/models/stock_picking.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/shipment_group.py b/indoteknik_custom/models/shipment_group.py index 9ebf36c0..fcde39c9 100644 --- a/indoteknik_custom/models/shipment_group.py +++ b/indoteknik_custom/models/shipment_group.py @@ -25,7 +25,7 @@ class ShipmentGroup(models.Model): shipment=f"{self.number}, {', '.join(picking_names)}" ) elif rec.shipment_id.carrier_id.id == 151: - rec.picking_id.track_envio_shipment() + rec.picking_id.track_envio_shipment(shipment=f"{self.number}") @api.depends('shipment_line.total_colly') def _compute_total_colly_line(self): diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 3223377c..ea52450e 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -619,18 +619,19 @@ class StockPicking(models.Model): except ValueError: raise UserError(f"Format waktu tidak sesuai: {date_str}") - def track_envio_shipment(self): + def track_envio_shipment(self, shipment=False): pickings = self.env['stock.picking'].search([ ('picking_type_code', '=', 'outgoing'), ('state', '=', 'done'), ('carrier_id', '=', 151) ]) for picking in self: + name = shipment or picking.name if not picking.name: raise UserError("Name pada stock.picking tidak ditemukan.") # API URL dan headers - url = f"https://api.envio.co.id/v1/tracking/distribution?code={picking.name}" + url = f"https://api.envio.co.id/v1/tracking/distribution?code={name}" headers = { 'Authorization': 'Bearer JZ0Seh6qpYJAC3CJHdhF7sPqv8B/uSSfZe1VX5BL?vPYdo', 'Content-Type': 'application/json', -- cgit v1.2.3 From 4ed94e9e1de027aba326ff3dce954b765f752009 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Wed, 28 May 2025 09:00:30 +0700 Subject: (andri) penambahan log note ketika biteship berhasil & penyesuaian field required pada SO --- indoteknik_custom/models/sale_order.py | 11 ++++------- indoteknik_custom/models/stock_picking.py | 8 ++++++++ indoteknik_custom/views/sale_order.xml | 2 +- 3 files changed, 13 insertions(+), 8 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index e5297011..f2bb27ad 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -652,8 +652,8 @@ class SaleOrder(models.Model): product_names = '
'.join(missing_weight_products) self.message_post(body=f"Produk berikut tidak memiliki berat:
{product_names}") - # if total_weight == 0: - # raise UserError("Tidak dapat mengestimasi ongkir tanpa berat yang valid.") + if total_weight == 0: + raise UserError("Tidak dapat mengestimasi ongkir tanpa karena berat produk = 0 kg.") # Validasi alamat pengiriman if not self.real_shipping_id: @@ -674,8 +674,8 @@ class SaleOrder(models.Model): total_weight = self._validate_for_shipping_estimate() weight_gram = int(total_weight * 1000) - if weight_gram < 100: - weight_gram = 100 + # if weight_gram < 100: + # weight_gram = 100 items = [{ "name": "Paket Pesanan", @@ -683,9 +683,6 @@ class SaleOrder(models.Model): "value": int(self.amount_untaxed), "weight": weight_gram, "quantity": 1, - "height": 10, - "width": 10, - "length": 10 }] shipping_address = self.real_shipping_id diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 5548db75..4522dac0 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -617,6 +617,14 @@ class StockPicking(models.Model): waybill_id = data.get("courier", {}).get("waybill_id", "") + self.message_post( + body=f"📦 Biteship berhasil dilakukan.
" + f"Kurir: {self.carrier_id.name}
" + f"Tracking ID: {self.biteship_tracking_id or '-'}
" + f"Resi: {waybill_id or '-'}", + message_type="comment" + ) + message = f"✅ Berhasil Order ke Biteship! Resi: {waybill_id}" if waybill_id else "⚠️ Order berhasil, tetapi tidak ada nomor resi." return { diff --git a/indoteknik_custom/views/sale_order.xml b/indoteknik_custom/views/sale_order.xml index 7e01ba0b..c00d68a1 100755 --- a/indoteknik_custom/views/sale_order.xml +++ b/indoteknik_custom/views/sale_order.xml @@ -118,7 +118,7 @@ - + -- cgit v1.2.3 From c2c8fff66b2aab1fa034fc2b6a12ebb9b4f9fbc6 Mon Sep 17 00:00:00 2001 From: stephanchrst Date: Wed, 28 May 2025 11:26:42 +0700 Subject: fixed approval by purchasing manager if not linked with sales order request by rafly hanggara --- indoteknik_custom/models/purchase_order.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/purchase_order.py b/indoteknik_custom/models/purchase_order.py index 36c4c7b9..b08dcf62 100755 --- a/indoteknik_custom/models/purchase_order.py +++ b/indoteknik_custom/models/purchase_order.py @@ -834,23 +834,23 @@ class PurchaseOrder(models.Model): if self.amount_untaxed >= 50000000 and not self.env.user.id == 21: raise UserError("Hanya Rafly Hanggara yang bisa approve") - if self.total_percent_margin < self.total_so_percent_margin and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser') and not self.env.user.is_leader: + if self.total_percent_margin < self.total_so_percent_margin and not self.env.user.is_leader: self.env.user.notify_danger( title='WARNING!!!', message='Beda Margin dengan Sale Order', sticky=True ) - if len(self.order_sales_match_line) == 0 and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser') and not self.env.user.is_leader: - self.env.user.notify_danger( - title='WARNING!!!', - message='Tidak ada matches SO', - sticky=True - ) + # if len(self.order_sales_match_line) == 0 and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser') and not self.env.user.is_leader: + # self.env.user.notify_danger( + # title='WARNING!!!', + # message='Tidak ada matches SO', + # sticky=True + # ) if not self.from_apo: - if not self.matches_so and not self.env.user.has_group('indoteknik_custom.group_role_merchandiser') and not self.env.user.is_leader: - raise UserError("Tidak ada link dengan SO, harus approval Merchandise") + if not self.matches_so and not self.env.user.is_purchasing_manager and not self.env.user.is_leader: + raise UserError("Tidak ada link dengan SO, harus approval Purchasing Manager") send_email = False if not self.not_update_purchasepricelist: -- cgit v1.2.3 From cf4b57fe825ae3522b7d893344eb9649c7bd10b3 Mon Sep 17 00:00:00 2001 From: stephanchrst Date: Wed, 28 May 2025 13:13:44 +0700 Subject: add purchasing manager as approval manufacturing order while confirm --- indoteknik_custom/models/manufacturing.py | 3 +++ indoteknik_custom/models/purchase_order.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/manufacturing.py b/indoteknik_custom/models/manufacturing.py index 715d8513..aea01362 100644 --- a/indoteknik_custom/models/manufacturing.py +++ b/indoteknik_custom/models/manufacturing.py @@ -11,6 +11,9 @@ class Manufacturing(models.Model): def action_confirm(self): if self._name != 'mrp.production': return super(Manufacturing, self).action_confirm() + + if not self.env.user.is_purchasing_manager: + raise UserError("Hanya bisa di confirm oleh Purchasing Manager") # if self.location_src_id.id != 75: # raise UserError('Component Location hanya bisa di AS/Stock') diff --git a/indoteknik_custom/models/purchase_order.py b/indoteknik_custom/models/purchase_order.py index d6b449fd..21ca55eb 100755 --- a/indoteknik_custom/models/purchase_order.py +++ b/indoteknik_custom/models/purchase_order.py @@ -850,7 +850,7 @@ class PurchaseOrder(models.Model): if not self.from_apo: if not self.matches_so and not self.env.user.is_purchasing_manager and not self.env.user.is_leader: - raise UserError("Tidak ada link dengan SO, harus approval Purchasing Manager") + raise UserError("Tidak ada link dengan SO, harus di confirm oleh Purchasing Manager") send_email = False if not self.not_update_purchasepricelist: -- cgit v1.2.3 From 104046bcaedf97dd97e604c24ceacf3797974713 Mon Sep 17 00:00:00 2001 From: stephanchrst Date: Wed, 28 May 2025 14:27:01 +0700 Subject: error recursive method, must change to compute field --- indoteknik_custom/models/res_partner.py | 352 ++++++++++++++++---------------- 1 file changed, 176 insertions(+), 176 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/res_partner.py b/indoteknik_custom/models/res_partner.py index 191a44c9..f1e362e6 100644 --- a/indoteknik_custom/models/res_partner.py +++ b/indoteknik_custom/models/res_partner.py @@ -235,182 +235,182 @@ class ResPartner(models.Model): raise ValidationError("Digit NPWP yang dimasukkan tidak sesuai. Pastikan NPWP memiliki 15 digit dengan format tertentu (99.999.999.9-999.999) atau 16 digit tanpa tanda hubung.") - def write(self, vals): - # Fungsi rekursif untuk meng-update semua child, termasuk child dari child - def update_children_recursively(partner, vals_for_child): - # Lakukan update pada partner saat ini hanya dengan field yang diizinkan - partner.write(vals_for_child) - - # Untuk setiap child dari partner ini, update juga child-nya - for child in partner.child_ids: - update_children_recursively(child, vals_for_child) - - # Jika self tidak memiliki parent_id, artinya self adalah parent - if not self.parent_id: - # Ambil semua child dari parent ini - children = self.child_ids - - # Perbarui vals dengan nilai dari parent jika tidak ada dalam vals - vals['customer_type'] = vals.get('customer_type', self.customer_type) - vals['nama_wajib_pajak'] = vals.get('nama_wajib_pajak', self.nama_wajib_pajak) - vals['npwp'] = vals.get('npwp', self.npwp) - vals['sppkp'] = vals.get('sppkp', self.sppkp) - vals['alamat_lengkap_text'] = vals.get('alamat_lengkap_text', self.alamat_lengkap_text) - vals['industry_id'] = vals.get('industry_id', self.industry_id.id if self.industry_id else None) - vals['company_type_id'] = vals.get('company_type_id', self.company_type_id.id if self.company_type_id else None) - - # Referensi - vals['supplier_ids'] = vals.get('supplier_ids', self.supplier_ids) - - # informasi perusahaan - vals['name_tempo'] = vals.get('name_tempo', self.name_tempo) - vals['industry_id_tempo'] = vals.get('industry_id_tempo', self.industry_id_tempo) - vals['street_tempo'] = vals.get('street_tempo', self.street_tempo) - vals['state_id_tempo'] = vals.get('state_id_tempo', self.state_id_tempo) - vals['city_id_tempo'] = vals.get('city_id_tempo', self.city_id_tempo) - vals['zip_tempo'] = vals.get('zip_tempo', self.zip_tempo) - vals['bank_name_tempo'] = vals.get('bank_name_tempo', self.bank_name_tempo) - vals['account_name_tempo'] = vals.get('account_name_tempo', self.account_name_tempo) - vals['account_number_tempo'] = vals.get('account_number_tempo', self.account_number_tempo) - vals['website_tempo'] = vals.get('website_tempo', self.website_tempo) - vals['portal'] = vals.get('portal', self.portal) - vals['estimasi_tempo'] = vals.get('estimasi_tempo', self.estimasi_tempo) - vals['tempo_duration'] = vals.get('tempo_duration', self.tempo_duration) - vals['tempo_limit'] = vals.get('tempo_limit', self.tempo_limit) - vals['category_produk_ids'] = vals.get('category_produk_ids', self.category_produk_ids) - - # Kontak Perusahaan - vals['direktur_name'] = vals.get('direktur_name', self.direktur_name) - vals['direktur_mobile'] = vals.get('direktur_mobile', self.direktur_mobile) - vals['direktur_email'] = vals.get('direktur_email', self.direktur_email) - vals['purchasing_name'] = vals.get('purchasing_name', self.purchasing_name) - vals['purchasing_mobile'] = vals.get('purchasing_mobile', self.purchasing_mobile) - vals['purchasing_email'] = vals.get('purchasing_email', self.purchasing_email) - vals['finance_name'] = vals.get('finance_name', self.finance_name) - vals['finance_mobile'] = vals.get('finance_mobile', self.finance_mobile) - vals['finance_email'] = vals.get('finance_email', self.finance_email) - - # Pengiriman - vals['pic_name'] = vals.get('pic_name', self.pic_name) - vals['pic_mobile'] = vals.get('pic_mobile', self.pic_mobile) - vals['street_pengiriman'] = vals.get('street_pengiriman', self.street_pengiriman) - vals['state_id_pengiriman'] = vals.get('state_id_pengiriman', self.state_id_pengiriman) - vals['city_id_pengiriman'] = vals.get('city_id_pengiriman', self.city_id_pengiriman) - vals['district_id_pengiriman'] = vals.get('district_id_pengiriman', self.district_id_pengiriman) - vals['subDistrict_id_pengiriman'] = vals.get('subDistrict_id_pengiriman', self.subDistrict_id_pengiriman) - vals['zip_pengiriman'] = vals.get('zip_pengiriman', self.zip_pengiriman) - vals['invoice_pic'] = vals.get('invoice_pic', self.invoice_pic) - vals['invoice_pic_mobile'] = vals.get('invoice_pic_mobile', self.invoice_pic_mobile) - vals['street_invoice'] = vals.get('street_invoice', self.street_invoice) - vals['state_id_invoice'] = vals.get('state_id_invoice', self.state_id_invoice) - vals['city_id_invoice'] = vals.get('city_id_invoice', self.city_id_invoice) - vals['district_id_invoice'] = vals.get('district_id_invoice', self.district_id_invoice) - vals['subDistrict_id_invoice'] = vals.get('subDistrict_id_invoice', self.subDistrict_id_invoice) - vals['zip_invoice'] = vals.get('zip_invoice', self.zip_invoice) - vals['tukar_invoice'] = vals.get('tukar_invoice', self.tukar_invoice) - vals['jadwal_bayar'] = vals.get('jadwal_bayar', self.jadwal_bayar) - vals['dokumen_prosedur'] = vals.get('dokumen_prosedur', self.dokumen_prosedur) - vals['dokumen_pengiriman'] = vals.get('dokumen_pengiriman', self.dokumen_pengiriman) - vals['dokumen_pengiriman_input'] = vals.get('dokumen_pengiriman_input', self.dokumen_pengiriman_input) - vals['dokumen_invoice'] = vals.get('dokumen_invoice', self.dokumen_invoice) - - # Dokumen - vals['dokumen_npwp'] = vals.get('dokumen_npwp', self.dokumen_npwp) - vals['dokumen_sppkp'] = vals.get('dokumen_sppkp', self.dokumen_sppkp) - vals['dokumen_nib'] = vals.get('dokumen_nib', self.dokumen_nib) - vals['dokumen_siup'] = vals.get('dokumen_siup', self.dokumen_siup) - vals['dokumen_tdp'] = vals.get('dokumen_tdp', self.dokumen_tdp) - vals['dokumen_skdp'] = vals.get('dokumen_skdp', self.dokumen_skdp) - vals['dokumen_skt'] = vals.get('dokumen_skt', self.dokumen_skt) - vals['dokumen_akta_perubahan'] = vals.get('dokumen_akta_perubahan', self.dokumen_akta_perubahan) - vals['dokumen_ktp_dirut'] = vals.get('dokumen_ktp_dirut', self.dokumen_ktp_dirut) - vals['dokumen_akta_pendirian'] = vals.get('dokumen_akta_pendirian', self.dokumen_akta_pendirian) - vals['dokumen_laporan_keuangan'] = vals.get('dokumen_laporan_keuangan', self.dokumen_laporan_keuangan) - vals['dokumen_foto_kantor'] = vals.get('dokumen_foto_kantor', self.dokumen_foto_kantor) - vals['dokumen_tempat_bekerja'] = vals.get('dokumen_tempat_bekerja', self.dokumen_tempat_bekerja) - - # Simpan hanya field yang perlu di-update pada child - vals_for_child = { - 'customer_type': vals.get('customer_type'), - 'nama_wajib_pajak': vals.get('nama_wajib_pajak'), - 'npwp': vals.get('npwp'), - 'sppkp': vals.get('sppkp'), - 'alamat_lengkap_text': vals.get('alamat_lengkap_text'), - 'industry_id': vals.get('industry_id'), - 'company_type_id': vals.get('company_type_id'), - 'supplier_ids': vals.get('supplier_ids'), - 'name_tempo': vals.get('name_tempo'), - 'industry_id_tempo': vals.get('industry_id_tempo'), - 'street_tempo': vals.get('street_tempo'), - 'state_id_tempo': vals.get('state_id_tempo'), - 'city_id_tempo': vals.get('city_id_tempo'), - 'zip_tempo': vals.get('zip_tempo'), - 'bank_name_tempo': vals.get('bank_name_tempo'), - 'account_name_tempo': vals.get('account_name_tempo'), - 'account_number_tempo': vals.get('account_number_tempo'), - 'website_tempo': vals.get('website_tempo'), - 'portal': vals.get('portal'), - 'estimasi_tempo': vals.get('estimasi_tempo'), - 'tempo_duration': vals.get('tempo_duration'), - 'tempo_limit': vals.get('tempo_limit'), - 'category_produk_ids': vals.get('category_produk_ids'), - 'direktur_name': vals.get('direktur_name'), - 'direktur_mobile': vals.get('direktur_mobile'), - 'direktur_email': vals.get('direktur_email'), - 'purchasing_name': vals.get('purchasing_name'), - 'purchasing_mobile': vals.get('purchasing_mobile'), - 'purchasing_email': vals.get('purchasing_email'), - 'finance_name': vals.get('finance_name'), - 'finance_mobile': vals.get('finance_mobile'), - 'finance_email': vals.get('finance_email'), - 'pic_name': vals.get('pic_name'), - 'pic_mobile': vals.get('pic_mobile'), - 'street_pengiriman': vals.get('street_pengiriman'), - 'state_id_pengiriman': vals.get('state_id_pengiriman'), - 'city_id_pengiriman': vals.get('city_id_pengiriman'), - 'district_id_pengiriman': vals.get('district_id_pengiriman'), - 'subDistrict_id_pengiriman': vals.get('subDistrict_id_pengiriman'), - 'zip_pengiriman': vals.get('zip_pengiriman'), - 'invoice_pic': vals.get('invoice_pic'), - 'invoice_pic_mobile': vals.get('invoice_pic_mobile'), - 'street_invoice': vals.get('street_invoice'), - 'state_id_invoice': vals.get('state_id_invoice'), - 'city_id_invoice': vals.get('city_id_invoice'), - 'district_id_invoice': vals.get('district_id_invoice'), - 'subDistrict_id_invoice': vals.get('subDistrict_id_invoice'), - 'zip_invoice': vals.get('zip_invoice'), - 'tukar_invoice': vals.get('tukar_invoice'), - 'jadwal_bayar': vals.get('jadwal_bayar'), - 'dokumen_prosedur': vals.get('dokumen_prosedur'), - 'dokumen_pengiriman': vals.get('dokumen_pengiriman'), - 'dokumen_pengiriman_input': vals.get('dokumen_pengiriman_input'), - 'dokumen_invoice': vals.get('dokumen_invoice'), - 'dokumen_npwp': vals.get('dokumen_npwp'), - 'dokumen_sppkp': vals.get('dokumen_sppkp'), - 'dokumen_nib': vals.get('dokumen_nib'), - 'dokumen_siup': vals.get('dokumen_siup'), - 'dokumen_tdp': vals.get('dokumen_tdp'), - 'dokumen_skdp': vals.get('dokumen_skdp'), - 'dokumen_skt': vals.get('dokumen_skt'), - 'dokumen_akta_perubahan': vals.get('dokumen_akta_perubahan'), - 'dokumen_ktp_dirut': vals.get('dokumen_ktp_dirut'), - 'dokumen_akta_pendirian': vals.get('dokumen_akta_pendirian'), - 'dokumen_laporan_keuangan': vals.get('dokumen_laporan_keuangan'), - 'dokumen_foto_kantor': vals.get('dokumen_foto_kantor'), - 'dokumen_tempat_bekerja': vals.get('dokumen_tempat_bekerja'), - - # internal_notes - 'comment': vals.get('comment') - } - - # Lakukan update pada semua child secara rekursif - for child in children: - update_children_recursively(child, vals_for_child) - - # Lakukan write untuk parent dengan vals asli - res = super(ResPartner, self).write(vals) - - return res + # def write(self, vals): + # # Fungsi rekursif untuk meng-update semua child, termasuk child dari child + # def update_children_recursively(partner, vals_for_child): + # # Lakukan update pada partner saat ini hanya dengan field yang diizinkan + # partner.write(vals_for_child) + # + # # Untuk setiap child dari partner ini, update juga child-nya + # for child in partner.child_ids: + # update_children_recursively(child, vals_for_child) + # + # # Jika self tidak memiliki parent_id, artinya self adalah parent + # if not self.parent_id: + # # Ambil semua child dari parent ini + # children = self.child_ids + # + # # Perbarui vals dengan nilai dari parent jika tidak ada dalam vals + # vals['customer_type'] = vals.get('customer_type', self.customer_type) + # vals['nama_wajib_pajak'] = vals.get('nama_wajib_pajak', self.nama_wajib_pajak) + # vals['npwp'] = vals.get('npwp', self.npwp) + # vals['sppkp'] = vals.get('sppkp', self.sppkp) + # vals['alamat_lengkap_text'] = vals.get('alamat_lengkap_text', self.alamat_lengkap_text) + # vals['industry_id'] = vals.get('industry_id', self.industry_id.id if self.industry_id else None) + # vals['company_type_id'] = vals.get('company_type_id', self.company_type_id.id if self.company_type_id else None) + # + # # Referensi + # vals['supplier_ids'] = vals.get('supplier_ids', self.supplier_ids) + # + # # informasi perusahaan + # vals['name_tempo'] = vals.get('name_tempo', self.name_tempo) + # vals['industry_id_tempo'] = vals.get('industry_id_tempo', self.industry_id_tempo) + # vals['street_tempo'] = vals.get('street_tempo', self.street_tempo) + # vals['state_id_tempo'] = vals.get('state_id_tempo', self.state_id_tempo) + # vals['city_id_tempo'] = vals.get('city_id_tempo', self.city_id_tempo) + # vals['zip_tempo'] = vals.get('zip_tempo', self.zip_tempo) + # vals['bank_name_tempo'] = vals.get('bank_name_tempo', self.bank_name_tempo) + # vals['account_name_tempo'] = vals.get('account_name_tempo', self.account_name_tempo) + # vals['account_number_tempo'] = vals.get('account_number_tempo', self.account_number_tempo) + # vals['website_tempo'] = vals.get('website_tempo', self.website_tempo) + # vals['portal'] = vals.get('portal', self.portal) + # vals['estimasi_tempo'] = vals.get('estimasi_tempo', self.estimasi_tempo) + # vals['tempo_duration'] = vals.get('tempo_duration', self.tempo_duration) + # vals['tempo_limit'] = vals.get('tempo_limit', self.tempo_limit) + # vals['category_produk_ids'] = vals.get('category_produk_ids', self.category_produk_ids) + # + # # Kontak Perusahaan + # vals['direktur_name'] = vals.get('direktur_name', self.direktur_name) + # vals['direktur_mobile'] = vals.get('direktur_mobile', self.direktur_mobile) + # vals['direktur_email'] = vals.get('direktur_email', self.direktur_email) + # vals['purchasing_name'] = vals.get('purchasing_name', self.purchasing_name) + # vals['purchasing_mobile'] = vals.get('purchasing_mobile', self.purchasing_mobile) + # vals['purchasing_email'] = vals.get('purchasing_email', self.purchasing_email) + # vals['finance_name'] = vals.get('finance_name', self.finance_name) + # vals['finance_mobile'] = vals.get('finance_mobile', self.finance_mobile) + # vals['finance_email'] = vals.get('finance_email', self.finance_email) + # + # # Pengiriman + # vals['pic_name'] = vals.get('pic_name', self.pic_name) + # vals['pic_mobile'] = vals.get('pic_mobile', self.pic_mobile) + # vals['street_pengiriman'] = vals.get('street_pengiriman', self.street_pengiriman) + # vals['state_id_pengiriman'] = vals.get('state_id_pengiriman', self.state_id_pengiriman) + # vals['city_id_pengiriman'] = vals.get('city_id_pengiriman', self.city_id_pengiriman) + # vals['district_id_pengiriman'] = vals.get('district_id_pengiriman', self.district_id_pengiriman) + # vals['subDistrict_id_pengiriman'] = vals.get('subDistrict_id_pengiriman', self.subDistrict_id_pengiriman) + # vals['zip_pengiriman'] = vals.get('zip_pengiriman', self.zip_pengiriman) + # vals['invoice_pic'] = vals.get('invoice_pic', self.invoice_pic) + # vals['invoice_pic_mobile'] = vals.get('invoice_pic_mobile', self.invoice_pic_mobile) + # vals['street_invoice'] = vals.get('street_invoice', self.street_invoice) + # vals['state_id_invoice'] = vals.get('state_id_invoice', self.state_id_invoice) + # vals['city_id_invoice'] = vals.get('city_id_invoice', self.city_id_invoice) + # vals['district_id_invoice'] = vals.get('district_id_invoice', self.district_id_invoice) + # vals['subDistrict_id_invoice'] = vals.get('subDistrict_id_invoice', self.subDistrict_id_invoice) + # vals['zip_invoice'] = vals.get('zip_invoice', self.zip_invoice) + # vals['tukar_invoice'] = vals.get('tukar_invoice', self.tukar_invoice) + # vals['jadwal_bayar'] = vals.get('jadwal_bayar', self.jadwal_bayar) + # vals['dokumen_prosedur'] = vals.get('dokumen_prosedur', self.dokumen_prosedur) + # vals['dokumen_pengiriman'] = vals.get('dokumen_pengiriman', self.dokumen_pengiriman) + # vals['dokumen_pengiriman_input'] = vals.get('dokumen_pengiriman_input', self.dokumen_pengiriman_input) + # vals['dokumen_invoice'] = vals.get('dokumen_invoice', self.dokumen_invoice) + # + # # Dokumen + # vals['dokumen_npwp'] = vals.get('dokumen_npwp', self.dokumen_npwp) + # vals['dokumen_sppkp'] = vals.get('dokumen_sppkp', self.dokumen_sppkp) + # vals['dokumen_nib'] = vals.get('dokumen_nib', self.dokumen_nib) + # vals['dokumen_siup'] = vals.get('dokumen_siup', self.dokumen_siup) + # vals['dokumen_tdp'] = vals.get('dokumen_tdp', self.dokumen_tdp) + # vals['dokumen_skdp'] = vals.get('dokumen_skdp', self.dokumen_skdp) + # vals['dokumen_skt'] = vals.get('dokumen_skt', self.dokumen_skt) + # vals['dokumen_akta_perubahan'] = vals.get('dokumen_akta_perubahan', self.dokumen_akta_perubahan) + # vals['dokumen_ktp_dirut'] = vals.get('dokumen_ktp_dirut', self.dokumen_ktp_dirut) + # vals['dokumen_akta_pendirian'] = vals.get('dokumen_akta_pendirian', self.dokumen_akta_pendirian) + # vals['dokumen_laporan_keuangan'] = vals.get('dokumen_laporan_keuangan', self.dokumen_laporan_keuangan) + # vals['dokumen_foto_kantor'] = vals.get('dokumen_foto_kantor', self.dokumen_foto_kantor) + # vals['dokumen_tempat_bekerja'] = vals.get('dokumen_tempat_bekerja', self.dokumen_tempat_bekerja) + # + # # Simpan hanya field yang perlu di-update pada child + # vals_for_child = { + # 'customer_type': vals.get('customer_type'), + # 'nama_wajib_pajak': vals.get('nama_wajib_pajak'), + # 'npwp': vals.get('npwp'), + # 'sppkp': vals.get('sppkp'), + # 'alamat_lengkap_text': vals.get('alamat_lengkap_text'), + # 'industry_id': vals.get('industry_id'), + # 'company_type_id': vals.get('company_type_id'), + # 'supplier_ids': vals.get('supplier_ids'), + # 'name_tempo': vals.get('name_tempo'), + # 'industry_id_tempo': vals.get('industry_id_tempo'), + # 'street_tempo': vals.get('street_tempo'), + # 'state_id_tempo': vals.get('state_id_tempo'), + # 'city_id_tempo': vals.get('city_id_tempo'), + # 'zip_tempo': vals.get('zip_tempo'), + # 'bank_name_tempo': vals.get('bank_name_tempo'), + # 'account_name_tempo': vals.get('account_name_tempo'), + # 'account_number_tempo': vals.get('account_number_tempo'), + # 'website_tempo': vals.get('website_tempo'), + # 'portal': vals.get('portal'), + # 'estimasi_tempo': vals.get('estimasi_tempo'), + # 'tempo_duration': vals.get('tempo_duration'), + # 'tempo_limit': vals.get('tempo_limit'), + # 'category_produk_ids': vals.get('category_produk_ids'), + # 'direktur_name': vals.get('direktur_name'), + # 'direktur_mobile': vals.get('direktur_mobile'), + # 'direktur_email': vals.get('direktur_email'), + # 'purchasing_name': vals.get('purchasing_name'), + # 'purchasing_mobile': vals.get('purchasing_mobile'), + # 'purchasing_email': vals.get('purchasing_email'), + # 'finance_name': vals.get('finance_name'), + # 'finance_mobile': vals.get('finance_mobile'), + # 'finance_email': vals.get('finance_email'), + # 'pic_name': vals.get('pic_name'), + # 'pic_mobile': vals.get('pic_mobile'), + # 'street_pengiriman': vals.get('street_pengiriman'), + # 'state_id_pengiriman': vals.get('state_id_pengiriman'), + # 'city_id_pengiriman': vals.get('city_id_pengiriman'), + # 'district_id_pengiriman': vals.get('district_id_pengiriman'), + # 'subDistrict_id_pengiriman': vals.get('subDistrict_id_pengiriman'), + # 'zip_pengiriman': vals.get('zip_pengiriman'), + # 'invoice_pic': vals.get('invoice_pic'), + # 'invoice_pic_mobile': vals.get('invoice_pic_mobile'), + # 'street_invoice': vals.get('street_invoice'), + # 'state_id_invoice': vals.get('state_id_invoice'), + # 'city_id_invoice': vals.get('city_id_invoice'), + # 'district_id_invoice': vals.get('district_id_invoice'), + # 'subDistrict_id_invoice': vals.get('subDistrict_id_invoice'), + # 'zip_invoice': vals.get('zip_invoice'), + # 'tukar_invoice': vals.get('tukar_invoice'), + # 'jadwal_bayar': vals.get('jadwal_bayar'), + # 'dokumen_prosedur': vals.get('dokumen_prosedur'), + # 'dokumen_pengiriman': vals.get('dokumen_pengiriman'), + # 'dokumen_pengiriman_input': vals.get('dokumen_pengiriman_input'), + # 'dokumen_invoice': vals.get('dokumen_invoice'), + # 'dokumen_npwp': vals.get('dokumen_npwp'), + # 'dokumen_sppkp': vals.get('dokumen_sppkp'), + # 'dokumen_nib': vals.get('dokumen_nib'), + # 'dokumen_siup': vals.get('dokumen_siup'), + # 'dokumen_tdp': vals.get('dokumen_tdp'), + # 'dokumen_skdp': vals.get('dokumen_skdp'), + # 'dokumen_skt': vals.get('dokumen_skt'), + # 'dokumen_akta_perubahan': vals.get('dokumen_akta_perubahan'), + # 'dokumen_ktp_dirut': vals.get('dokumen_ktp_dirut'), + # 'dokumen_akta_pendirian': vals.get('dokumen_akta_pendirian'), + # 'dokumen_laporan_keuangan': vals.get('dokumen_laporan_keuangan'), + # 'dokumen_foto_kantor': vals.get('dokumen_foto_kantor'), + # 'dokumen_tempat_bekerja': vals.get('dokumen_tempat_bekerja'), + # + # # internal_notes + # 'comment': vals.get('comment') + # } + # + # # Lakukan update pada semua child secara rekursif + # for child in children: + # update_children_recursively(child, vals_for_child) + # + # # Lakukan write untuk parent dengan vals asli + # res = super(ResPartner, self).write(vals) + # + # return res # if self.company_type == 'person' and not partner.parent_id: # if self.parent_id: -- cgit v1.2.3 From 9b1ff130cfcec243c698ff4a8b2a5412d3e79011 Mon Sep 17 00:00:00 2001 From: Azka Nathan Date: Wed, 28 May 2025 14:47:16 +0700 Subject: push --- indoteknik_custom/models/stock_picking.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index ea52450e..e83ab13f 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -288,7 +288,7 @@ class StockPicking(models.Model): self.ensure_one() if not self.name or not self.origin: return False - return f"{self.name}, {self.origin}" + return f"{self.name} {self.origin}" def _download_pod_photo(self, url): """Mengunduh foto POD dari URL""" -- cgit v1.2.3 From 6e56ffc2c5b5ee22bc97d2518274eeb8a959e80e Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Wed, 28 May 2025 15:16:40 +0700 Subject: (andri) penyesuaian request biteship di stock picking --- indoteknik_custom/models/sale_order.py | 4 +- indoteknik_custom/models/stock_picking.py | 73 ++++++++++++++++++++----------- 2 files changed, 49 insertions(+), 28 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index f2bb27ad..a4166016 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -862,8 +862,8 @@ class SaleOrder(models.Model): def _call_biteship_api(self, origin_data, destination_data, items, couriers=None): - url = 'https://api.biteship.com/v1/rates/couriers' - api_key = 'biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA' + url = "https://api.biteship.com/v1/rates/couriers" + api_key = "biteship_test.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSW5kb3Rla25payIsInVzZXJJZCI6IjY3MTViYTJkYzVkMjdkMDAxMjRjODk2MiIsImlhdCI6MTcyOTQ5ODAwMX0.L6C73couP4-cgVEfhKI2g7eMCMo3YOFSRZhS-KSuHNA" headers = { 'Authorization': api_key, diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 4522dac0..54da700b 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -526,46 +526,55 @@ class StockPicking(models.Model): if self.biteship_tracking_id: raise UserError(f"Order ini sudah dikirim ke Biteship. Dengan Tracking Id: {self.biteship_tracking_id}") - # Mencari data sale.order.line berdasarkan sale_id + # Fungsi bantu: menentukan apakah kurir perlu koordinat + def is_courier_need_coordinates(service_code): + return service_code in [ + "instant", "same_day", "instant_car", + "instant_bike", "motorcycle", "mpv", "van", "truck", + "cdd_bak", "cdd_box", "engkel_box", "engkel_bak" + ] + + # Ambil order line products = self.env['sale.order.line'].search([('order_id', '=', self.sale_id.id)]) - - # Fungsi untuk membangun items_data dari order lines + + # Bangun data items untuk standard def build_items_data(lines): return [{ "name": line.product_id.name, "description": line.name, "value": line.price_unit, "quantity": line.product_uom_qty, - "weight": line.weight + "weight": line.weight*1000 } for line in lines] - # Items untuk pengiriman standard items_data_standard = build_items_data(products) - # Items untuk pengiriman instant, mengambil product_id dari move_line_ids_without_package + # Bangun data items untuk pengiriman instant items_data_instant = [] for move_line in self.move_line_ids_without_package: - # Mencari baris di sale.order.line berdasarkan product_id dari move_line order_line = self.env['sale.order.line'].search([ ('order_id', '=', self.sale_id.id), ('product_id', '=', move_line.product_id.id) ], limit=1) - + if order_line: items_data_instant.append({ "name": order_line.product_id.name, "description": order_line.name, "value": order_line.price_unit, "quantity": move_line.qty_done, - "weight": order_line.weight + "weight": order_line.weight*1000 }) + _logger.info(f"Items data standard: {items_data_standard}") + _logger.info(f"Items data instant: {items_data_instant}") + # Bangun payload dasar payload = { - "origin_coordinate" :{ + "origin_coordinate": { "latitude": -6.3031123, - "longitude" : 106.7794934999 + "longitude": 106.7794934999 }, - "reference_id" : self.sale_id.name, + "reference_id": self.sale_id.name, "shipper_contact_name": self.carrier_id.pic_name or '', "shipper_contact_phone": self.carrier_id.pic_phone or '', "shipper_organization": self.carrier_id.name, @@ -581,30 +590,40 @@ class StockPicking(models.Model): "courier_type": self.sale_id.delivery_service_type or "reg", "courier_company": self.carrier_id.name.lower(), "delivery_type": "now", - "destination_postal_code": self.real_shipping_id.zip, "items": items_data_standard } - _logger.info(f"Payload untuk Biteship: {payload}") + _logger.info(f"Delivery service type: {self.sale_id.delivery_service_type}") + _logger.info(f"Carrier: {self.carrier_id.name}") + _logger.info(f"Payload awal: {payload}") + + # Tambahkan destination_coordinate jika diperlukan + if is_courier_need_coordinates(self.sale_id.delivery_service_type): + if not self.real_shipping_id.latitude or not self.real_shipping_id.longtitude: + raise UserError("Alamat tujuan tidak memiliki koordinat (latitude/longitude).") + + # items_to_use = items_data_instant if items_data_instant else items_data_standard + if not items_data_instant: + raise UserError("Pengiriman instant membutuhkan produk yang sudah diproses (qty_done > 0). Harap lakukan validasi picking terlebih dahulu.") - # Cek jika pengiriman instant atau same_day - if self.sale_id.delivery_service_type and ("instant" in self.sale_id.delivery_service_type or "same_day" in self.sale_id.delivery_service_type): payload.update({ - "destination_coordinate" : { + "destination_coordinate": { "latitude": self.real_shipping_id.latitude, "longitude": self.real_shipping_id.longtitude, }, "items": items_data_instant }) - + + _logger.info(f"Payload untuk Biteship: {payload}") + + # Kirim ke Biteship api_key = _biteship_api_key headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } - # Kirim request ke Biteship - response = requests.post(_biteship_url+'/orders', headers=headers, json=payload) + response = requests.post(_biteship_url + '/orders', headers=headers, json=payload) _logger.info(f"Response dari Biteship: {response.text}") if response.status_code == 200: @@ -614,11 +633,11 @@ class StockPicking(models.Model): self.biteship_tracking_id = data.get("courier", {}).get("tracking_id", "") self.biteship_waybill_id = data.get("courier", {}).get("waybill_id", "") self.delivery_tracking_no = data.get("courier", {}).get("waybill_id", "") - - waybill_id = data.get("courier", {}).get("waybill_id", "") + + waybill_id = self.biteship_waybill_id self.message_post( - body=f"📦 Biteship berhasil dilakukan.
" + body=f"Biteship berhasil dilakukan.
" f"Kurir: {self.carrier_id.name}
" f"Tracking ID: {self.biteship_tracking_id or '-'}
" f"Resi: {waybill_id or '-'}", @@ -629,16 +648,18 @@ class StockPicking(models.Model): return { 'effect': { - 'fadeout': 'slow', # Efek menghilang perlahan - 'message': message, # Pesan sukses - 'type': 'rainbow_man', # Efek animasi lucu Odoo + 'fadeout': 'slow', + 'message': message, + 'type': 'rainbow_man', } } + else: error_data = response.json() error_message = error_data.get("error", "Unknown error") error_code = error_data.get("code", "No code provided") raise UserError(f"Error saat mengirim ke Biteship: {error_message} (Code: {error_code})") + @api.constrains('driver_departure_date') def constrains_driver_departure_date(self): -- cgit v1.2.3 From ea3d8ab967d6f02c81b92115f2c82a2a17dae99d Mon Sep 17 00:00:00 2001 From: stephanchrst Date: Wed, 28 May 2025 15:52:19 +0700 Subject: remove validation on create, cause of error while duplicate --- indoteknik_custom/models/sale_order.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index f89dfb10..fa570819 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -1259,6 +1259,7 @@ class SaleOrder(models.Model): self._validate_order() for order in self: + order._validate_delivery_amt() order._validate_uniform_taxes() order.order_line.validate_line() order.check_data_real_delivery_address() @@ -1501,6 +1502,7 @@ class SaleOrder(models.Model): def action_confirm(self): for order in self: + order._validate_delivery_amt() order._validate_uniform_taxes() order.check_duplicate_product() order.check_product_bom() @@ -1962,7 +1964,7 @@ class SaleOrder(models.Model): order = super(SaleOrder, self).create(vals) order._compute_etrts_date() order._validate_expected_ready_ship_date() - order._validate_delivery_amt() + # order._validate_delivery_amt() # order._check_total_margin_excl_third_party() # order._update_partner_details() return order -- cgit v1.2.3 From b641951b811590231c060ac40ef633f59037bfbb Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Thu, 29 May 2025 20:26:55 +0700 Subject: (andri) revisi biteship terkait berat --- indoteknik_custom/models/sale_order.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index a4166016..94cbfb84 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -652,8 +652,8 @@ class SaleOrder(models.Model): product_names = '
'.join(missing_weight_products) self.message_post(body=f"Produk berikut tidak memiliki berat:
{product_names}") - if total_weight == 0: - raise UserError("Tidak dapat mengestimasi ongkir tanpa karena berat produk = 0 kg.") + # if total_weight == 0: + # raise UserError("Tidak dapat mengestimasi ongkir tanpa karena berat produk = 0 kg.") # Validasi alamat pengiriman if not self.real_shipping_id: @@ -674,8 +674,8 @@ class SaleOrder(models.Model): total_weight = self._validate_for_shipping_estimate() weight_gram = int(total_weight * 1000) - # if weight_gram < 100: - # weight_gram = 100 + if weight_gram < 100: + weight_gram = 100 items = [{ "name": "Paket Pesanan", -- cgit v1.2.3 From 711885733186a090be447099f1b7979e89ada85d Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Thu, 29 May 2025 21:58:53 +0700 Subject: (andri) pilihan shipping method akan terganti jika pilihan kurir tsb tidak ada pada hasil estimate shipping (otomatis akan keganti di opsi pertama) --- indoteknik_custom/models/sale_order.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 94cbfb84..e4564c7d 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -828,6 +828,19 @@ class SaleOrder(models.Model): selected_option = shipping_options[0] _logger.info(f"Menggunakan opsi pertama: {selected_option.name}") + # Ganti carrier_id otomatis sesuai provider dari shipping option + provider = selected_option.provider.lower() + self.env.cr.execute(""" + SELECT delivery_carrier_id FROM rajaongkir_kurir + WHERE LOWER(name) = %s AND delivery_carrier_id IS NOT NULL + LIMIT 1 + """, (provider,)) + row = self.env.cr.fetchone() + matched_carrier_id = row[0] if row else False + if matched_carrier_id: + self.carrier_id = matched_carrier_id + _logger.info(f"Carrier diganti otomatis ke ID {matched_carrier_id} berdasarkan provider {provider}") + if selected_option: self.shipping_option_id = selected_option.id self.delivery_amt = selected_option.price -- cgit v1.2.3 From d6c59069035919e270d4940a39242fe5d5291982 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Thu, 29 May 2025 22:13:46 +0700 Subject: (andri) tambah validasi pada shipping method --- indoteknik_custom/models/sale_order.py | 83 +++++++++++++++++----------------- 1 file changed, 41 insertions(+), 42 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index e4564c7d..946761ce 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -306,64 +306,63 @@ class SaleOrder(models.Model): @api.onchange('carrier_id') def _onchange_carrier_id(self): - self.shipping_option_id = False - self.delivery_amt = 0 - if not self.carrier_id: + self.shipping_option_id = False + self.delivery_amt = 0 return {'domain': {'shipping_option_id': [('id', '=', -1)]}} - - # Cari provider dari carrier yang dipilih langsung dari rajaongkir_kurir + + # Ambil provider dari rajaongkir_kurir self.env.cr.execute(""" SELECT name FROM rajaongkir_kurir WHERE delivery_carrier_id = %s LIMIT 1 """, (self.carrier_id.id,)) - result = self.env.cr.fetchone() provider = result[0].lower() if result and result[0] else False - - # Fallback jika tidak ditemukan di rajaongkir_kurir + + # Fallback: pakai nama carrier if not provider: - # Gunakan nama carrier, ambil kata pertama provider = self.carrier_id.name.lower().split()[0] if self.carrier_id.name else False - - # Log untuk debugging + _logger.info(f"Carrier changed to {self.carrier_id.name}, provider: {provider}") - - # PENTING: self.id mungkin False atau NewId pada saat onchange - # Perlu memeriksa apakah ini adalah record baru atau yang sudah ada - sale_order_id = False - if hasattr(self, '_origin') and self._origin: - sale_order_id = self._origin.id - - # Cek jika ada shipping options dengan provider ini (tanpa filter sale_order_id dulu) + + sale_order_id = self._origin.id if self._origin else False + + # Cek jumlah shipping option dengan provider tersebut self.env.cr.execute(""" SELECT COUNT(*) FROM shipping_option - WHERE LOWER(provider) LIKE %s - """, (f'%{provider}%',)) - + WHERE LOWER(provider) LIKE %s AND sale_order_id = %s + """, (f'%{provider}%', sale_order_id)) count = self.env.cr.fetchone()[0] + _logger.info(f"Found {count} shipping options for provider {provider}") - - # Buat domain untuk shipping_option_id - if count > 0: - # Jika ada options yang tersedia, buat domain yang lebih permisif - domain = [ - '|', - ('provider', 'ilike', f'%{provider}%'), - ('provider', '=', provider) - ] - - # Jika ini record yang sudah ada, tambahkan filter sale_order_id - if sale_order_id: - domain = [ - '|', - '&', ('sale_order_id', '=', sale_order_id), ('provider', 'ilike', f'%{provider}%'), - '&', ('sale_order_id', '=', False), ('provider', 'ilike', f'%{provider}%') - ] - else: - domain = [('id', '=', -1)] # Tidak ada opsi - + + # VALIDASI GAGAL + if count == 0: + previous_carrier = self._origin.carrier_id if self._origin else False + self.carrier_id = previous_carrier + + return { + 'warning': { + 'title': "Shipping Method Tidak Tersedia", + 'message': ( + f"Shipping method '{provider}' tidak tersedia pada pengiriman ini.\n" + f"Pilihan dikembalikan ke sebelumnya." + ) + }, + 'domain': {'shipping_option_id': [('id', '=', -1)]} + } + + # ✅ Valid, baru reset shipping_option dan delivery amount + self.shipping_option_id = False + self.delivery_amt = 0 + + domain = [ + '|', + '&', ('sale_order_id', '=', sale_order_id), ('provider', 'ilike', f'%{provider}%'), + '&', ('sale_order_id', '=', False), ('provider', 'ilike', f'%{provider}%') + ] + _logger.info(f"Final domain for shipping_option_id: {domain}") return {'domain': {'shipping_option_id': domain}} -- cgit v1.2.3 From 2f89da69c9ec8d78f187be5afd254cdd594ee24a Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Fri, 30 May 2025 09:19:22 +0700 Subject: (andri) fix bug shipping method custom --- indoteknik_custom/models/sale_order.py | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index 946761ce..f1280b37 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -311,6 +311,15 @@ class SaleOrder(models.Model): self.delivery_amt = 0 return {'domain': {'shipping_option_id': [('id', '=', -1)]}} + # ✅ Lewati validasi jika carrier bukan Biteship + if self.carrier_id.delivery_type != 'biteship': + _logger.info(f"Carrier {self.carrier_id.name} bertipe custom ({self.carrier_id.delivery_type}), tidak divalidasi.") + self.shipping_option_id = False + self.delivery_amt = 0 + return { + 'domain': {'shipping_option_id': [('id', '=', -1)]} + } + # Ambil provider dari rajaongkir_kurir self.env.cr.execute(""" SELECT name FROM rajaongkir_kurir @@ -320,21 +329,27 @@ class SaleOrder(models.Model): result = self.env.cr.fetchone() provider = result[0].lower() if result and result[0] else False - # Fallback: pakai nama carrier + # Fallback ke nama carrier jika tidak ada di rajaongkir_kurir if not provider: provider = self.carrier_id.name.lower().split()[0] if self.carrier_id.name else False _logger.info(f"Carrier changed to {self.carrier_id.name}, provider: {provider}") - sale_order_id = self._origin.id if self._origin else False + sale_order_id = self._origin.id if self._origin and self._origin.id else None - # Cek jumlah shipping option dengan provider tersebut - self.env.cr.execute(""" - SELECT COUNT(*) FROM shipping_option - WHERE LOWER(provider) LIKE %s AND sale_order_id = %s - """, (f'%{provider}%', sale_order_id)) - count = self.env.cr.fetchone()[0] + # Cek shipping option untuk provider ini + if sale_order_id: + self.env.cr.execute(""" + SELECT COUNT(*) FROM shipping_option + WHERE LOWER(provider) LIKE %s AND sale_order_id = %s + """, (f'%{provider}%', sale_order_id)) + else: + self.env.cr.execute(""" + SELECT COUNT(*) FROM shipping_option + WHERE LOWER(provider) LIKE %s AND sale_order_id IS NULL + """, (f'%{provider}%',)) + count = self.env.cr.fetchone()[0] _logger.info(f"Found {count} shipping options for provider {provider}") # VALIDASI GAGAL @@ -346,7 +361,7 @@ class SaleOrder(models.Model): 'warning': { 'title': "Shipping Method Tidak Tersedia", 'message': ( - f"Shipping method '{provider}' tidak tersedia pada pengiriman ini.\n" + f"Shipping method '{self.carrier_id.name}' tidak tersedia pada pengiriman ini.\n" f"Pilihan dikembalikan ke sebelumnya." ) }, @@ -366,6 +381,7 @@ class SaleOrder(models.Model): _logger.info(f"Final domain for shipping_option_id: {domain}") return {'domain': {'shipping_option_id': domain}} + @api.onchange('shipping_option_id') def _onchange_shipping_option_id(self): if not self.shipping_option_id: -- cgit v1.2.3 From e3856970da63328c820833893c894f18dc6700bd Mon Sep 17 00:00:00 2001 From: Miqdad Date: Fri, 30 May 2025 15:11:42 +0700 Subject: fix bug total percent margin --- indoteknik_custom/models/sale_order.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index fa570819..d1dc3324 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -403,14 +403,14 @@ class SaleOrder(models.Model): if len(tax_sets) > 1: raise ValidationError("Semua produk dalam Sales Order harus memiliki kombinasi pajak yang sama.") - # @api.constrains('fee_third_party', 'delivery_amt', 'biaya_lain_lain') + # @api.constrains('fee_third_party', 'delivery_amt', 'biaya_lain_lain', 'ongkir_ke_xpdc') # def _check_total_margin_excl_third_party(self): # for rec in self: # if rec.fee_third_party == 0 and rec.total_margin_excl_third_party != rec.total_percent_margin: # # Gunakan direct SQL atau flag context untuk menghindari rekursi # self.env.cr.execute(""" - # UPDATE sale_order - # SET total_margin_excl_third_party = %s + # UPDATE sale_order + # SET total_margin_excl_third_party = %s # WHERE id = %s # """, (rec.total_percent_margin, rec.id)) # self.invalidate_cache() @@ -1703,9 +1703,14 @@ class SaleOrder(models.Model): else: delivery_amt = 0 - # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt-order.fee_third_party)) * 100, 2) + net_margin = order.total_margin - order.biaya_lain_lain + order.total_percent_margin = round( - (order.total_margin / (order.amount_untaxed - order.fee_third_party - order.biaya_lain_lain)) * 100, 2) + (net_margin / (order.amount_untaxed - order.fee_third_party)) * 100, 2) + + # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt-order.fee_third_party)) * 100, 2) + # order.total_percent_margin = round( + # (order.total_margin / (order.amount_untaxed - order.fee_third_party - order.biaya_lain_lain)) * 100, 2) # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed)) * 100, 2) @api.onchange('sales_tax_id') -- cgit v1.2.3 From b6962acb39ad373f2aded4bebfa1e7a2dbbb0a8a Mon Sep 17 00:00:00 2001 From: Miqdad Date: Sat, 31 May 2025 09:17:01 +0700 Subject: before margin --- indoteknik_custom/models/sale_order.py | 228 ++++++++++++++++++++++++++------- 1 file changed, 182 insertions(+), 46 deletions(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/sale_order.py b/indoteknik_custom/models/sale_order.py index d1dc3324..3c69c3d1 100755 --- a/indoteknik_custom/models/sale_order.py +++ b/indoteknik_custom/models/sale_order.py @@ -148,8 +148,8 @@ class SaleOrder(models.Model): 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") - total_margin_excl_third_party = fields.Float('Before Margin', help="Before Margin in Sales Order Header", - compute='_compute_total_margin_excl_third_party') + total_margin_excl_third_party = fields.Float('Before Margin', help="Before Margin in Sales Order Header") + approval_status = fields.Selection([ ('pengajuan1', 'Approval Manager'), ('pengajuan2', 'Approval Pimpinan'), @@ -340,16 +340,16 @@ class SaleOrder(models.Model): date_unhold = fields.Datetime(string='Date Unhold', tracking=True, readonly=True, help='Waktu ketika SO di Unhold' ) - def _compute_total_margin_excl_third_party(self): - for order in self: - if order.amount_untaxed == 0: - order.total_margin_excl_third_party = 0 - continue - - # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt-order.fee_third_party)) * 100, 2) - order.total_margin_excl_third_party = round((order.total_before_margin / (order.amount_untaxed)) * 100, 2) - # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed)) * 100, 2) - + # def _compute_total_margin_excl_third_party(self): + # for order in self: + # if order.amount_untaxed == 0: + # order.total_margin_excl_third_party = 0 + # continue + # + # # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt-order.fee_third_party)) * 100, 2) + # order.total_margin_excl_third_party = round((order.total_before_margin / (order.amount_untaxed)) * 100, 2) + # # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed)) * 100, 2) + # def ask_retur_cancel_purchasing(self): for rec in self: if self.env.user.has_group('indoteknik_custom.group_role_purchasing'): @@ -1035,11 +1035,11 @@ class SaleOrder(models.Model): line_no += 1 line.line_no = line_no - def write(self, vals): - if 'carrier_id' in vals: - for picking in self.picking_ids: - if picking.state == 'assigned': - picking.carrier_id = self.carrier_id + # def write(self, vals): + # if 'carrier_id' in vals: + # for picking in self.picking_ids: + # if picking.state == 'assigned': + # picking.carrier_id = self.carrier_id def calculate_so_status(self): so_state = ['sale'] @@ -1157,12 +1157,12 @@ class SaleOrder(models.Model): 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 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""" @@ -1693,25 +1693,161 @@ class SaleOrder(models.Model): total_before_margin = sum(line.item_before_margin for line in order.order_line if line.product_id) order.total_before_margin = total_before_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 + # + # net_margin = order.total_margin - order.biaya_lain_lain + # + # order.total_percent_margin = round( + # (net_margin / (order.amount_untaxed - order.fee_third_party)) * 100, 2) + + # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt-order.fee_third_party)) * 100, 2) + # order.total_percent_margin = round( + # (order.total_margin / (order.amount_untaxed - order.fee_third_party - order.biaya_lain_lain)) * 100, 2) + # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed)) * 100, 2) + 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 + # Net margin = total margin - biaya tambahan net_margin = order.total_margin - order.biaya_lain_lain + denominator = order.amount_untaxed - order.fee_third_party - order.total_percent_margin = round( - (net_margin / (order.amount_untaxed - order.fee_third_party)) * 100, 2) + if denominator > 0: + order.total_percent_margin = round((net_margin / denominator) * 100, 2) + else: + order.total_percent_margin = 0 - # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed-delivery_amt-order.fee_third_party)) * 100, 2) - # order.total_percent_margin = round( - # (order.total_margin / (order.amount_untaxed - order.fee_third_party - order.biaya_lain_lain)) * 100, 2) - # order.total_percent_margin = round((order.total_margin / (order.amount_untaxed)) * 100, 2) + # @api.onchange('biaya_lain_lain') + # def _onchange_biaya_lain_lain(self): + # """Ketika biaya_lain_lain berubah, simpan nilai margin sebelumnya""" + # if hasattr(self, '_origin') and self._origin.id: + # # Hitung margin sebelum biaya_lain_lain ditambahkan + # if self.amount_untaxed > 0: + # original_net_margin = self.total_margin # tanpa biaya_lain_lain + # self.total_margin_excl_third_party = round( + # (original_net_margin / (self.amount_untaxed - self.fee_third_party)) * 100, 2) + + def write(self, vals): + import logging + _logger = logging.getLogger(__name__) + + # Simpan nilai margin sebelumnya untuk field yang mempengaruhi perhitungan + margin_sebelumnya = {} + + margin_affecting_fields = [ + 'biaya_lain_lain', 'fee_third_party', 'delivery_amt', + 'ongkir_ke_xpdc', 'shipping_cost_covered', 'order_line' + ] + + if any(field in vals for field in margin_affecting_fields): + for order in self: + if order.amount_untaxed > 0: + # LOGIC PENTING: Kapan Before Margin harus diupdate? + + current_before = order.total_margin_excl_third_party or 0 + + # CASE 1: Before margin masih kosong, simpan margin saat ini + if current_before == 0: + margin_sebelumnya[order.id] = order.total_percent_margin + _logger.info( + f"CASE 1 - SO {order.name}: Before margin kosong, simpan {order.total_percent_margin}%") + + # CASE 2: Ada perubahan biaya_lain_lain + elif 'biaya_lain_lain' in vals: + old_biaya = order.biaya_lain_lain or 0 + new_biaya = vals['biaya_lain_lain'] or 0 + + _logger.info(f"SO {order.name}: Biaya lain-lain berubah dari {old_biaya} ke {new_biaya}") + + # Jika sebelumnya tidak ada biaya_lain_lain, dan sekarang ada + if old_biaya == 0 and new_biaya > 0: + # Simpan margin saat ini sebagai "before margin" + margin_sebelumnya[order.id] = order.total_percent_margin + _logger.info(f"Menyimpan before margin: {order.total_percent_margin}%") + + # Jika biaya_lain_lain dihapus (dari ada jadi 0) + elif old_biaya > 0 and new_biaya == 0: + # Before margin tetap tidak berubah (sudah tersimpan sebelumnya) + _logger.info(f"Biaya dihapus, before margin tetap: {current_before}%") + # TIDAK mengubah before margin + + # CASE 3: Perubahan field lain (fee_third_party, dll) + elif any(field in vals for field in + ['fee_third_party', 'delivery_amt', 'ongkir_ke_xpdc', 'order_line']): + # Simpan margin saat ini sebelum perubahan + margin_sebelumnya[order.id] = order.total_percent_margin + _logger.info(f"CASE 3 - Field lain berubah, simpan {order.total_percent_margin}%") + + # Validasi dan proses lainnya... + for order in self: + if order.state in ['sale', 'cancel']: + if 'order_line' in vals: + new_lines = vals.get('order_line', []) + for command in new_lines: + if command[0] == 0: + raise UserError( + "SO tidak dapat ditambahkan produk baru karena SO sudah menjadi sale order.") + + if 'carrier_id' in vals: + for order in self: + for picking in order.picking_ids: + if picking.state == 'assigned': + picking.carrier_id = vals['carrier_id'] + + try: + helper_ids = self._get_helper_ids() + if str(self.env.user.id) in helper_ids: + vals['helper_by_id'] = self.env.user.id + except: + pass + + # Jalankan super write + res = super(SaleOrder, self).write(vals) + + # Update before margin jika diperlukan + if margin_sebelumnya: + for order_id, margin_value in margin_sebelumnya.items(): + _logger.info(f"Updating before margin untuk SO {order_id}: {margin_value}%") + + self.env.cr.execute(""" + UPDATE sale_order + SET total_margin_excl_third_party = %s + WHERE id = %s + """, (margin_value, order_id)) + + self.env.cr.commit() + self.invalidate_cache(['total_margin_excl_third_party']) + + # Validasi lainnya + if any(field in vals for field in ['delivery_amt', 'carrier_id', 'shipping_cost_covered']): + try: + self._validate_delivery_amt() + except: + pass + + if any(field in vals for field in ["order_line", "client_order_ref"]): + try: + self._calculate_etrts_date() + except: + pass + + return res @api.onchange('sales_tax_id') def onchange_sales_tax_id(self): @@ -2002,23 +2138,23 @@ class SaleOrder(models.Model): 'customer_type': partner.customer_type, }) - def write(self, vals): - for order in self: - if order.state in ['sale', 'cancel']: - if 'order_line' in vals: - new_lines = vals.get('order_line', []) - for command in new_lines: - if command[0] == 0: # A new line is being added - raise UserError( - "SO tidak dapat ditambahkan produk baru karena SO sudah menjadi sale order.") - - res = super(SaleOrder, self).write(vals) - # self._check_total_margin_excl_third_party() - if any(fields in vals for fields in ['delivery_amt', 'carrier_id', 'shipping_cost_covered']): - self._validate_delivery_amt() - if any(field in vals for field in ["order_line", "client_order_ref"]): - self._calculate_etrts_date() - return res + # def write(self, vals): + # for order in self: + # if order.state in ['sale', 'cancel']: + # if 'order_line' in vals: + # new_lines = vals.get('order_line', []) + # for command in new_lines: + # if command[0] == 0: # A new line is being added + # raise UserError( + # "SO tidak dapat ditambahkan produk baru karena SO sudah menjadi sale order.") + # + # res = super(SaleOrder, self).write(vals) + # # self._check_total_margin_excl_third_party() + # if any(fields in vals for fields in ['delivery_amt', 'carrier_id', 'shipping_cost_covered']): + # self._validate_delivery_amt() + # if any(field in vals for field in ["order_line", "client_order_ref"]): + # self._calculate_etrts_date() + # return res # @api.depends('commitment_date') def _compute_ready_to_ship_status_detail(self): -- cgit v1.2.3 From c652ee3e1f652d23e37833f01e3fdd7aa8e52021 Mon Sep 17 00:00:00 2001 From: "Indoteknik ." Date: Sat, 31 May 2025 11:03:06 +0700 Subject: (andri) add tracking biteship pada BU OUT & fix delivery departure & arrival date --- indoteknik_custom/models/stock_picking.py | 55 ++++++++++++++++++++++++++++++- indoteknik_custom/views/stock_picking.xml | 7 ++++ 2 files changed, 61 insertions(+), 1 deletion(-) (limited to 'indoteknik_custom') diff --git a/indoteknik_custom/models/stock_picking.py b/indoteknik_custom/models/stock_picking.py index 54da700b..4d38e5b3 100644 --- a/indoteknik_custom/models/stock_picking.py +++ b/indoteknik_custom/models/stock_picking.py @@ -1551,7 +1551,60 @@ class StockPicking(models.Model): except Exception as e : _logger.error(f"Error fetching Biteship order for picking {self.id}: {str(e)}") return { 'error': str(e) } - + + def action_sync_biteship_tracking(self): + for picking in self: + if not picking.biteship_id: + raise UserError("Tracking Biteship tidak tersedia.") + + histori = picking.get_manifest_biteship() + updated_fields = {} + seen_logs = set() + + manifests = sorted(histori.get("manifests", []), key=lambda m: m.get("datetime") or "") + + for manifest in manifests: + status = manifest.get("status", "").lower() + dt_str = manifest.get("datetime") + desc = manifest.get("description") + dt = False + + try: + local_dt_str = picking._convert_to_local_time(dt_str) + dt = fields.Datetime.from_string(local_dt_str) + except Exception as e: + _logger.warning(f"[Biteship Sync] Gagal parse datetime: {e}") + continue + + # Update tanggal ke field + if status == "picked" and dt and not picking.driver_departure_date: + updated_fields["driver_departure_date"] = dt + + if status == "delivered" and dt and not picking.driver_arrival_date: + updated_fields["driver_arrival_date"] = dt + + # Buat log unik + if dt and desc: + desc_clean = ' '.join(desc.strip().split()) + log_line = f"[TRACKING] {status} - {dt.strftime('%d %b %Y %H:%M')}: {desc_clean}" + if not picking._has_existing_log(log_line): + picking.message_post(body=log_line) + seen_logs.add(log_line) + + if updated_fields: + picking.write(updated_fields) + + def _has_existing_log(self, log_line): + self.ensure_one() + self.env.cr.execute(""" + SELECT 1 FROM mail_message + WHERE model = %s AND res_id = %s + AND subtype_id IS NOT NULL + AND body ILIKE %s + LIMIT 1 + """, (self._name, self.id, f"%{log_line}%")) + return self.env.cr.fetchone() is not None + def _convert_to_local_time(self, iso_date): try: dt_with_tz = waktu.fromisoformat(iso_date) diff --git a/indoteknik_custom/views/stock_picking.xml b/indoteknik_custom/views/stock_picking.xml index c916f2ef..9b16639c 100644 --- a/indoteknik_custom/views/stock_picking.xml +++ b/indoteknik_custom/views/stock_picking.xml @@ -61,6 +61,12 @@