def tokopedia_generate_delivery_line(self): tp_logistic_service_obj = self.env['mp.tokopedia.logistic.service'] for order in self: delivery_line = order.order_line.filtered(lambda l: l.is_delivery) if not delivery_line: tp_order_raw = json.loads(order.raw, strict=False) tp_order_shipping = json_digger(tp_order_raw, 'order_info/shipping_info') tp_logistic_service_id = str(tp_order_shipping.get('sp_id')) tp_logistic_service = tp_logistic_service_obj.search_mp_records('tokopedia', tp_logistic_service_id) tp_logistic_name = '%s - %s' % ( tp_logistic_service.logistic_id.shipper_name, tp_logistic_service.service_name) delivery_product = tp_logistic_service.get_delivery_product() if not delivery_product: raise ValidationError('Please define delivery product on "%s"' % tp_logistic_name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': delivery_product.id, 'name': tp_logistic_name, 'product_uom_qty': 1, 'price_unit': tp_order_shipping.get('shipping_price', 0), 'is_delivery': True })] })
def shopee_generate_delivery_line(self): sp_logistic_obj = self.env['mp.shopee.logistic'] for order in self: delivery_line = order.order_line.filtered(lambda l: l.is_delivery) sp_order_raw = json.loads(order.raw, strict=False) sp_order_shipping = json_digger(sp_order_raw, 'package_list')[0] sp_logistic_name = str(sp_order_shipping.get('shipping_carrier')) if not delivery_line: sp_logistic = sp_logistic_obj.search([('logistics_channel_name', '=', sp_logistic_name)], limit=1) delivery_product = sp_logistic.get_delivery_product() if not delivery_product: raise ValidationError('Please define delivery product on "%s"' % sp_logistic_name) shipping_fee = sp_order_raw.get('actual_shipping_fee', 0) if shipping_fee == 0: shipping_fee = sp_order_raw.get('estimated_shipping_fee', 0) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': delivery_product.id, 'name': sp_logistic_name, 'product_uom_qty': 1, 'price_unit': shipping_fee, 'is_delivery': True })] }) else: if delivery_line.name != sp_logistic_name: delivery_line.update({ 'name': sp_logistic_name, })
def generate_shop_address_data(self, mp_account, sp_order_raw): shop_address_list = [] address_list = json_digger(sp_order_raw, 'shipping_paramater/pickup/address_list') for address in address_list: address_dict = { 'shop_id': mp_account.sp_shop_id.id, 'address_id': address.get('address_id'), 'region': address.get('region'), 'state': address.get('state'), 'city': address.get('city'), 'district': address.get('district'), 'town': address.get('town'), 'address': address.get('address'), 'zipcode': address.get('zipcode'), 'is_default_address': False, 'is_return_address': False, 'is_pickup_address': False, } if 'default_address' in address['address_flag']: address_dict.update({'is_default_address': True}) if 'pickup_address' in address['address_flag']: address_dict.update({'is_pickup_address': True}) if 'return_address' in address['address_flag']: address_dict.update({'is_return_address': True}) shop_address_list.append(address_dict) return shop_address_list
def blibli_get_mp_product_variant(self): mp_product_obj = self.env['mp.product'] mp_product_variant_obj = self.env['mp.product.variant'] self.ensure_one() mp_account_ctx = self.generate_context() bli_account = self.blibli_get_account() bli_product_variant = BlibliProduct( bli_account, sanitizers=mp_product_variant_obj.get_sanitizers(self.marketplace)) mp_products = mp_product_obj.search([('bli_has_variant', '=', True), ('mp_account_id', '=', self.id)]) for mp_product in mp_products: if mp_product['mp_account_id'][ 'bli_shop_code'] != bli_account.shop_code: continue mp_product_raw = json.loads(mp_product.raw, strict=False) bli_variant_ids = json_digger(mp_product_raw, 'bli_variant_ids') for bli_variant_id in bli_variant_ids: bli_data_raw, bli_data_sanitized = bli_product_variant.get_product_variant( product_id=bli_variant_id) check_existing_records_params = { 'identifier_field': 'bli_variant_id', 'raw_data': bli_data_raw, 'mp_data': bli_data_sanitized, 'multi': isinstance(bli_data_sanitized, list) } check_existing_records = mp_product_variant_obj.with_context( mp_account_ctx).check_existing_records( **check_existing_records_params) mp_product_variant_obj.with_context( mp_account_ctx).handle_result_check_existing_records( check_existing_records)
def blibli_generate_delivery_line(self): bli_logistic_obj = self.env['mp.blibli.logistic'] for order in self: delivery_line = order.order_line.filtered(lambda l: l.is_delivery) if not delivery_line: bli_order_raw = json.loads(order.raw, strict=False) bli_order_shipping = json_digger(bli_order_raw, 'item_list')[0] bli_logistic_name = str( bli_order_shipping.get('logisticsProductName')) bli_logistic = bli_logistic_obj.search([ ('logistics_name', 'ilike', bli_logistic_name) ])[0] delivery_product = bli_logistic.get_delivery_product() if not delivery_product: raise ValidationError( 'Please define delivery product on "%s"' % bli_logistic_name) shipping_fee = bli_order_raw.get('actual_shipping_fee', 0) if shipping_fee == 0: shipping_fee = bli_order_raw.get('estimated_shipping_fee', 0) order.write({ 'order_line': [(0, 0, { 'product_id': delivery_product.id, 'name': bli_logistic_name, 'product_uom_qty': 1, 'price_unit': shipping_fee, 'is_delivery': True })] })
def shopee_generate_adjusment_line(self): for order in self: adjustment_line = order.order_line.filtered(lambda l: l.is_adjustment) if not adjustment_line: sp_order_raw = json.loads(order.raw, strict=False) total_adjustment = json_digger(sp_order_raw, 'order_income/buyer_transaction_fee', default=0) if total_adjustment > 0: adjustment_product = order.mp_account_id.adjustment_product_id if not adjustment_product: raise ValidationError( 'Please define global discount product on' ' this marketplace account: "%s"' % order.mp_account_id.name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': adjustment_product.id, 'product_uom_qty': 1, 'price_unit': total_adjustment, 'is_adjustment': True })] }) shopee_coins_line = order.order_line.filtered(lambda l: l.is_shopee_coins) if not shopee_coins_line: sp_order_raw = json.loads(order.raw, strict=False) total_coins = json_digger(sp_order_raw, 'order_income/coins', default=0) if total_coins > 0: shopee_coins_product = order.mp_account_id.sp_coins_product_id if not shopee_coins_product: raise ValidationError( 'Please define global discount product on' ' this marketplace account: "%s"' % order.mp_account_id.name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'name': 'Shopee Coins', 'product_id': shopee_coins_product.id, 'product_uom_qty': 1, 'price_unit': -total_coins, 'is_shopee_coins': True })] })
def _finish_create_records(self, records): mp_account = self.get_mp_account_from_context() mp_account_ctx = mp_account.generate_context() order_line_obj = self.env['sale.order.line'].with_context( mp_account_ctx) records = super(SaleOrder, self)._finish_create_records(records) bli_order_detail_raws, bli_order_detail_sanitizeds = [], [] if mp_account.marketplace == 'blibli': for record in records: bli_order_raw = json.loads(record.raw, strict=False) list_field = [ 'gdnItemSku', 'productItemName', 'merchantSku', 'productName', 'gdnSku' ] item_list = bli_order_raw['item_list'] for item in item_list: item['item_info'] = dict([(key, item[key]) for key in list_field]) bli_order_details = [ # Insert order_id into bli_order_detail_raw dict(bli_order_detail_raw, **dict([('order_id', record.id)])) for bli_order_detail_raw in json_digger( bli_order_raw, 'item_list') ] bli_data_raw, bli_data_sanitized = order_line_obj.with_context( mp_account_ctx)._prepare_mapping_raw_data( raw_data=bli_order_details) bli_order_detail_raws.extend(bli_data_raw) bli_order_detail_sanitizeds.extend(bli_data_sanitized) check_existing_records_params = { 'identifier_field': 'bli_order_item_id', 'raw_data': bli_order_detail_raws, 'mp_data': bli_order_detail_sanitizeds, 'multi': isinstance(bli_order_detail_sanitizeds, list) } check_existing_records = order_line_obj.with_context( mp_account_ctx).check_existing_records( **check_existing_records_params) order_line_obj.with_context( mp_account_ctx).handle_result_check_existing_records( check_existing_records) records = super(SaleOrder, self)._finish_create_records(records) return records
def get_active_logistics(self): mp_tokopedia_logistic_obj = self.env['mp.tokopedia.logistic'] mp_tokopedia_logistic_service_obj = self.env[ 'mp.tokopedia.logistic.service'] mp_tokopedia_shop_logistic_obj = self.env['mp.tokopedia.shop.logistic'] for shop in self: mp_account = shop.mp_account_id tp_account = mp_account.tokopedia_get_account() tp_logistic = TokopediaLogistic(tp_account) tp_raw_data = tp_logistic.get_logistic_active_info(shop.shop_id) active_logistic_raws = json_digger(tp_raw_data, 'Shops/ShipmentInfos')[0] for active_logistic_raw in active_logistic_raws: tp_logistic = mp_tokopedia_logistic_obj.search_mp_records( shop.marketplace, active_logistic_raw['ShipmentID']) active_logistic_service_ids = json_digger( active_logistic_raw, 'ShipmentPackages/ShippingProductID') tp_logistic_service_ids = [ mp_tokopedia_logistic_service_obj.search_mp_records( shop.marketplace, active_logistic_service_id).id for active_logistic_service_id in active_logistic_service_ids ] existing_shop_logistic = mp_tokopedia_shop_logistic_obj.search( [('shop_id', '=', shop.id), ('logistic_id', '=', tp_logistic.id)]) shop_logistic_values = { 'shop_id': shop.id, 'logistic_id': tp_logistic.id, 'service_ids': [(6, 0, tp_logistic_service_ids)], 'mp_account_id': mp_account.id } if not existing_shop_logistic.exists(): shop_logistic = mp_tokopedia_shop_logistic_obj.create( shop_logistic_values) shop.write({'shop_logistic_ids': [(4, shop_logistic.id)]}) else: existing_shop_logistic.write(shop_logistic_values)
def shopee_generate_global_discount_line(self): for order in self: global_discount_line = order.order_line.filtered(lambda l: l.is_global_discount) sp_order_raw = json.loads(order.raw, strict=False) seller_discount = json_digger(sp_order_raw, 'order_income/seller_discount', default=0) shopee_discount = json_digger(sp_order_raw, 'order_income/shopee_discount', default=0) voucher_from_seller = json_digger(sp_order_raw, 'order_income/voucher_from_seller', default=0) voucher_from_shopee = json_digger(sp_order_raw, 'order_income/voucher_from_shopee', default=0) total_discount = seller_discount + shopee_discount + voucher_from_seller + voucher_from_shopee if not global_discount_line: if total_discount > 0: discount_product = order.mp_account_id.global_discount_product_id if not discount_product: raise ValidationError( 'Please define global discount product on' ' this marketplace account: "%s"' % order.mp_account_id.name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': discount_product.id, 'product_uom_qty': 1, 'price_unit': -total_discount, 'is_global_discount': True })] }) else: if total_discount > 0: global_discount_line.write({ 'price_unit': total_discount, })
def sanitize(response=None, raw_data=None): if response: raw_data = response.json() if root_path: raw_data = raw_data[root_path] if mp_field_mapping: keys = mp_field_mapping.keys() mp_data = dict( (key, json_digger(raw_data, mp_field_mapping[key][0])) for key in keys) # return: (raw_data, sanitized_data) return raw_data, self.remap_raw_data(mp_data) else: # return: (raw_data, None) return raw_data, None
def tokopedia_generate_insurance_line(self): for order in self: insurance_line = order.order_line.filtered(lambda l: l.is_insurance) if not insurance_line: tp_order_raw = json.loads(order.raw, strict=False) insurance_cost = json_digger(tp_order_raw, 'order_summary/amt/insurance_cost', default=0) if insurance_cost > 0: insurance_product = order.mp_account_id.insurance_product_id if not insurance_product: raise ValidationError( 'Please define insurance product on this marketplace account: "%s"' % order.mp_account_id.name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': insurance_product.id, 'product_uom_qty': 1, 'price_unit': insurance_cost, 'is_insurance': True })] })
def tokopedia_generate_global_discount_line(self): for order in self: global_discount_line = order.order_line.filtered(lambda l: l.is_global_discount) if not global_discount_line: tp_order_raw = json.loads(order.raw, strict=False) total_global_discount = json_digger(tp_order_raw, 'order_summary/promo_order_detail/total_discount', default=0) if total_global_discount > 0: global_discount_product = order.mp_account_id.global_discount_product_id if not global_discount_product: raise ValidationError( 'Please define global discount product on' ' this marketplace account: "%s"' % order.mp_account_id.name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': global_discount_product.id, 'product_uom_qty': 1, 'price_unit': total_global_discount, 'is_global_discount': True })] })
def tokopedia_generate_adjusment_line(self): for order in self: adjustment_line = order.order_line.filtered(lambda l: l.is_adjustment) if not adjustment_line: tp_order_raw = json.loads(order.raw, strict=False) tp_amt = json_digger(tp_order_raw, 'order_summary/amt', default={}) adjustment_amount = tp_amt['ttl_amount'] - sum([value for key, value in tp_amt.items() if key in ['ttl_product_price', 'shipping_cost', 'insurance_cost']]) if adjustment_amount > 0: adjustment_product = order.mp_account_id.adjustment_product_id if not adjustment_product: raise ValidationError( 'Please define adjustment product on' ' this marketplace account: "%s"' % order.mp_account_id.name) order.write({ 'order_line': [(0, 0, { 'sequence': 999, 'product_id': adjustment_product.id, 'product_uom_qty': 1, 'price_unit': adjustment_amount, 'is_adjustment': True })] })
def generate_variant_data(self, mp_product_raw): variant_list = [] varian_model = json_digger(mp_product_raw, 'variants/model') varian_tier = json_digger(mp_product_raw, 'variants/tier_variation') def generate_tier_dict(tier_variation): tier_dict = {} num_attrs = len(tier_variation) if num_attrs == 1: attr = tier_variation[0] for attr_value_index, attr_value in enumerate( attr['option_list']): key = str([attr_value_index]) value = { 'name': [attr_value.get('option')], 'image': attr_value.get('image', {}) } tier_dict.update(dict([(key, value)])) elif num_attrs == 2: first_attr_values = [ dict([('name', attr_value.get('option')), ('image', attr_value.get('image', {}))]) for attr_value in tier_variation[0]['option_list'] ] second_attr_values = [ dict([('name', attr_value.get('option')), ('image', attr_value.get('image', {}))]) for attr_value in tier_variation[1]['option_list'] ] for first_attr_value_index, first_attr_value in enumerate( first_attr_values): for second_attr_value_index, second_attr_value in enumerate( second_attr_values): key = str( [first_attr_value_index, second_attr_value_index]) value = { 'name': [ first_attr_value['name'], second_attr_value['name'] ], 'image': first_attr_value.get('image', {}) } tier_dict.update(dict([(key, value)])) return tier_dict tier_dict = generate_tier_dict(varian_tier) for model in varian_model: variant_dict = { 'mp_product_id': mp_product_raw['item_id'], 'weight': mp_product_raw['weight'], 'sp_variant_id': json_digger(model, 'model_id'), 'list_price': json_digger(model, 'price_info/original_price')[0], 'default_code': json_digger(model, 'model_sku') } tier_index = str(json_digger(model, 'tier_index')) product_name = mp_product_raw['item_name'] product_variant_name = product_name + ' - %s' % (','.join( tier_dict[tier_index]['name'])) product_variant_image = tier_dict[tier_index]['image'].get( 'image_url', None) product_variant_image_id = tier_dict[tier_index]['image'].get( 'image_id', None) variant_dict.update({ 'name': product_variant_name, 'image': product_variant_image, 'image_id': product_variant_image_id }) variant_list.append(variant_dict) return variant_list
def shopee_request_pickup(self): mp_shopee_shop_address_obj = self.env['mp.shopee.shop.address'] mp_shopee_order_pickup_info_obj = self.env['mp.shopee.order.pickup.info'] allowed_status = ['in_process'] order_statuses = self.mapped('mp_order_status') if not all(order_status in allowed_status for order_status in order_statuses): raise ValidationError( "The status of your selected orders for shopee should be in {}".format(allowed_status)) allowed_invoice_status = ['invoiced'] invoice_statuses = self.mapped('invoice_status') if not all(invoice_status in allowed_invoice_status for invoice_status in invoice_statuses): raise ValidationError( "The sales order of your selected invoice status should be in {}".format(allowed_invoice_status)) for order in self: mp_account_ctx = order.mp_account_id.generate_context() sp_order_raw = json.loads(order.raw, strict=False) sp_shop_address_raw = mp_shopee_shop_address_obj.generate_shop_address_data( order.mp_account_id, sp_order_raw) sp_data_raw, sp_data_sanitized = mp_shopee_shop_address_obj.with_context( mp_account_ctx)._prepare_mapping_raw_data(raw_data=sp_shop_address_raw) check_existing_records_params = { 'identifier_field': 'address_id', 'raw_data': sp_data_raw, 'mp_data': sp_data_sanitized, 'multi': isinstance(sp_data_sanitized, list) } check_existing_records = mp_shopee_shop_address_obj.with_context(mp_account_ctx).check_existing_records( **check_existing_records_params) mp_shopee_shop_address_obj.with_context(mp_account_ctx).handle_result_check_existing_records( check_existing_records) if order.mp_account_id.mp_token_id.state == 'valid': params = {'access_token': order.mp_account_id.mp_token_id.name} sp_account = order.mp_account_id.shopee_get_account(**params) sp_order_v2 = ShopeeOrder(sp_account) action_params = { 'order_sn': order.mp_external_id, } shipping_paramater = sp_order_v2.get_shipping_parameter(**action_params) address_list = shipping_paramater['pickup']['address_list'] sp_order_pickup_raws, sp_order_pickup_sanitizeds = [], [] list_field = ['date_from_timestamp', 'time_text'] for addess in address_list: address_id = mp_shopee_shop_address_obj.search([('address_id', '=', addess['address_id'])]) pickup_info = [ dict(sp_order_detail_raw, **dict([('order_id', order.id)]), **dict([('address_id', address_id.id)]), **dict([('date_from_timestamp', sp_order_v2.from_api_timestamp( api_ts=sp_order_detail_raw.get('date')).strftime(DEFAULT_SERVER_DATETIME_FORMAT))])) for sp_order_detail_raw in json_digger(addess, 'time_slot_list') ] for pick in pickup_info: pick['time_info'] = dict([(key, pick[key]) for key in list_field]) sp_data_raw, sp_data_sanitized = mp_shopee_order_pickup_info_obj.with_context( mp_account_ctx)._prepare_mapping_raw_data(raw_data=pickup_info) sp_order_pickup_raws.extend(sp_data_raw) sp_order_pickup_sanitizeds.extend(sp_data_sanitized) for pickup in order.sp_pickup_ids: pickup.sudo().unlink() def identify_pickup_line(record_obj, values): return record_obj.search([('order_id', '=', values['order_id']), ('pickup_time_id', '=', values['pickup_time_id'])], limit=1) check_existing_records_params = { 'identifier_method': identify_pickup_line, 'raw_data': sp_order_pickup_raws, 'mp_data': sp_order_pickup_sanitizeds, 'multi': isinstance(sp_order_pickup_sanitizeds, list) } check_existing_records = mp_shopee_order_pickup_info_obj.with_context( mp_account_ctx).check_existing_records(**check_existing_records_params) mp_shopee_order_pickup_info_obj.with_context( mp_account_ctx).handle_result_check_existing_records(check_existing_records) return { 'name': 'Request Pickup Order(s)', 'view_mode': 'form', 'res_model': 'wiz.sp_order_pickup', 'type': 'ir.actions.act_window', 'target': 'new', 'context': { 'default_order_ids': [(6, 0, self.ids)], }, }
def _finish_create_records(self, records): mp_account = self.get_mp_account_from_context() mp_account_ctx = mp_account.generate_context() order_line_obj = self.env['sale.order.line'].with_context(mp_account_ctx) if mp_account.marketplace == 'tokopedia': tp_order_detail_raws, tp_order_detail_sanitizeds = [], [] for record in records: # cek if order in cancel request if record.tp_cancel_request_status and record.tp_order_status == '400': record.tp_order_status = '401' tp_order_raw = json.loads(record.raw, strict=False) tp_order_details = [ # Insert order_id into tp_order_detail_raw dict(tp_order_detail_raw, **dict([('order_id', record.id)]), **dict([('mp_order_exid', record.mp_invoice_number)])) for tp_order_detail_raw in json_digger(tp_order_raw, 'order_info/order_detail') ] tp_data_raw, tp_data_sanitized = order_line_obj._prepare_mapping_raw_data(raw_data=tp_order_details) tp_order_detail_raws.extend(tp_data_raw) tp_order_detail_sanitizeds.extend(tp_data_sanitized) check_existing_records_params = { 'identifier_field': 'tp_order_detail_id', 'raw_data': tp_order_detail_raws, 'mp_data': tp_order_detail_sanitizeds, 'multi': isinstance(tp_order_detail_sanitizeds, list) } check_existing_records = order_line_obj.check_existing_records(**check_existing_records_params) order_line_obj.handle_result_check_existing_records(check_existing_records) if self._context.get('skip_error'): record_ids_to_unlink = [] tp_logistic_service_obj = self.env['mp.tokopedia.logistic.service'] for record in records: tp_order_raw = json.loads(record.raw, strict=False) item_list = tp_order_raw.get('order_info').get('order_detail', []) record_line = record.order_line.mapped('product_type') tp_order_shipping = json_digger(tp_order_raw, 'order_info/shipping_info') tp_logistic_service_id = str(tp_order_shipping.get('sp_id')) tp_logistic_service = tp_logistic_service_obj.search_mp_records('tokopedia', tp_logistic_service_id) delivery_product = tp_logistic_service.get_delivery_product() delivery_carrier = self.env['delivery.carrier'].sudo().search( [('name', '=ilike', delivery_product.name)], limit=1) if delivery_carrier: record.write({ 'carrier_id': delivery_carrier.id, }) if not record_line: record_ids_to_unlink.append(record.id) elif 'product' not in record_line: record_ids_to_unlink.append(record.id) elif len(item_list) != record_line.count('product'): record_ids_to_unlink.append(record.id) records.filtered(lambda r: r.id in record_ids_to_unlink).unlink() records = super(SaleOrder, self)._finish_create_records(records) return records
def _finish_create_records(self, records): mp_account = self.get_mp_account_from_context() mp_account_ctx = mp_account.generate_context() order_line_obj = self.env['sale.order.line'].with_context(mp_account_ctx) sp_order_detail_raws, sp_order_detail_sanitizeds = [], [] if mp_account.marketplace == 'shopee': for record in records: sp_order_raw = json.loads(record.raw, strict=False) list_item_field = ['item_id', 'item_name', 'item_sku', 'model_id', 'model_name', 'model_sku', 'model_original_price', 'model_discounted_price'] item_list = sp_order_raw['item_list'] for item in item_list: item['item_info'] = dict([(key, item[key]) for key in list_item_field]) sp_order_details = [ # Insert order_id into tp_order_detail_raw dict(sp_order_detail_raw, **dict([('order_id', record.id)]), **dict([('mp_order_exid', record.mp_invoice_number)])) for sp_order_detail_raw in json_digger(sp_order_raw, 'item_list') ] sp_data_raw, sp_data_sanitized = order_line_obj.with_context( mp_account_ctx)._prepare_mapping_raw_data(raw_data=sp_order_details) sp_order_detail_raws.extend(sp_data_raw) sp_order_detail_sanitizeds.extend(sp_data_sanitized) def identify_order_line(record_obj, values): return record_obj.search([('order_id', '=', values['order_id']), ('product_id', '=', values['product_id'])], limit=1) check_existing_records_params = { 'identifier_method': identify_order_line, 'raw_data': sp_order_detail_raws, 'mp_data': sp_order_detail_sanitizeds, 'multi': isinstance(sp_order_detail_sanitizeds, list) } check_existing_records = order_line_obj.with_context( mp_account_ctx).check_existing_records(**check_existing_records_params) order_line_obj.with_context( mp_account_ctx).handle_result_check_existing_records(check_existing_records) if self._context.get('skip_error'): record_ids_to_unlink = [] sp_logistic_obj = self.env['mp.shopee.logistic'] for record in records: sp_order_raw = json.loads(record.raw, strict=False) item_list = sp_order_raw.get('item_list', []) record_line = record.order_line.mapped('product_type') sp_order_shipping = json_digger(sp_order_raw, 'package_list')[0] sp_logistic_name = str(sp_order_shipping.get('shipping_carrier')) sp_logistic = sp_logistic_obj.search([('logistics_channel_name', '=', sp_logistic_name)]) delivery_product = sp_logistic.get_delivery_product() delivery_carrier = self.env['delivery.carrier'].sudo().search( [('name', '=ilike', delivery_product.name)], limit=1) if delivery_carrier: record.write({ 'carrier_id': delivery_carrier.id, }) if not record_line: record_ids_to_unlink.append(record.id) elif 'product' not in record_line: record_ids_to_unlink.append(record.id) elif len(item_list) != record_line.count('product'): record_ids_to_unlink.append(record.id) records.filtered(lambda r: r.id in record_ids_to_unlink).unlink() records = super(SaleOrder, self)._finish_create_records(records) return records
def tokopedia_get_mp_product_variant(self): mp_product_obj = self.env['mp.product'] mp_product_variant_obj = self.env['mp.product.variant'] self.ensure_one() mp_account_ctx = self.generate_context() tp_account = self.tokopedia_get_account() tp_product_variant = TokopediaProduct( tp_account, sanitizers=mp_product_variant_obj.get_sanitizers(self.marketplace)) mp_products = mp_product_obj.search([('tp_has_variant', '=', True), ('mp_account_id', '=', self.id)]) tp_data_raws, tp_data_sanitizeds = [], [] tp_variant_ids = [] for mp_product in mp_products: variant_need_to_remove = [] mp_product_raw = json.loads(mp_product.raw, strict=False) tp_variant_ids.extend( json_digger(mp_product_raw, 'variant/childrenID')) mp_variant_exid_list = json_digger(mp_product_raw, 'variant/childrenID') for variant_obj in mp_product.mp_product_variant_ids: if int(variant_obj.tp_variant_id) not in mp_variant_exid_list: variant_need_to_remove.append(variant_obj.tp_variant_id) # archive variant mp_product.mp_product_variant_ids.filtered( lambda r: r.tp_variant_id in variant_need_to_remove).write( {'active': False}) tp_variant_ids_splited = mp_product_variant_obj.create_chunks( tp_variant_ids, 500) for tp_variant_ids in tp_variant_ids_splited: tp_data_raw, tp_data_sanitized = tp_product_variant.get_product_info( product_id=tp_variant_ids) tp_data_raws.extend(tp_data_raw) tp_data_sanitizeds.extend(tp_data_sanitized) check_existing_records_params = { 'identifier_field': 'tp_variant_id', 'raw_data': tp_data_raws, 'mp_data': tp_data_sanitizeds, 'multi': isinstance(tp_data_sanitizeds, list) } check_existing_records = mp_product_variant_obj.with_context( mp_account_ctx).check_existing_records( **check_existing_records_params) mp_product_variant_obj.with_context( mp_account_ctx).handle_result_check_existing_records( check_existing_records) # clean variant mp_products = mp_product_obj.search([('mp_product_variant_ids', '!=', False), ('tp_has_variant', '=', False), ('mp_account_id', '=', self.id)]) for product in mp_products: for variant in product.mp_product_variant_ids: variant.active = False