odoo 12 导入功能二开,导入多规格属性(变体)的产品

  • 创建 HrEmployeeImport 类,加入到_init_.py。该类继承import基础模块base_import.import
  • 重写base_import.import 对应类下的do 方法。也可根据需要重写其他方法

class HrEmployeeImport(models.TransientModel):
    _inherit = 'base_import.import'

    @api.multi
    def do(self, fields, columns, options, dryrun=False):

        self.ensure_one()
        self._cr.execute('SAVEPOINT import')

        try:
            data, import_fields = self._convert_import_data(fields, options)
            # Parse date and float field
            data = self._parse_import_data(data, import_fields, options)
        except ValueError as error:
            return {
                'messages': [{
                    'type': 'error',
                    'message': pycompat.text_type(error),
                    'record': False,
                }]
            }

        _logger.info('importing %d rows...', len(data))

        name_create_enabled_fields = options.pop('name_create_enabled_fields', {})
        model = self.env[self.res_model].with_context(import_file=True,
                                                      name_create_enabled_fields=name_create_enabled_fields)
        # 过滤属性名和属性值
        # 属性名ids
        attrName_ids = []
        # 属性值ids
        attrValue_ids = []
        # 属性名 和 属性值 id的字典
        attr_id_d = {}
        if model._name == 'product.template':
            for item in data:
                # 属性
                attrName = item[-2].split(';')
                # 属性值
                attr_Values = item[-1].split(';')
                # 属性名 属性值 的字典
                attr = {}
                for index, a_name in enumerate(attrName):
                    attrValue = attr_Values[index].split(',')
                    attr.update({a_name: attrValue})
                for key, value in attr.items():
                    attr_id = self.env['product.attribute'].search([('name', '=', key)])
                    v_list = []
                    if attr_id:
                        attr_value_list = [i.name for i in attr_id.value_ids]
                        for v in value:
                            if v in attr_value_list:
                                attr_value_id = self.env['product.attribute.value'].search(
                                    [('attribute_id', '=', attr_id.id), ('name', '=', v)])
                                v_list += (attr_value_id.id)
                            else:
                                new_attr_value_id = self.env['product.attribute.value'].create({
                                    'attribute_id': attr_id.id,
                                    'name': v
                                })
                                v_list += (new_attr_value_id.id)
                        attr_id_d.update({attr_id.id: v_list})
                        attrName_ids.append(attr_id.id)
                        attrValue_ids.append(v_list)
                    else:
                        new_attr_id = self.env['product.attribute'].create({
                            # 'value_ids.name': value,
                            'name': key
                        })
                        for v in value:
                            new_attr_value_id = self.env['product.attribute.value'].create({
                                'attribute_id': new_attr_id.id,
                                'name': v
                            })
                        v_list += (new_attr_id.value_ids.ids)
                        value_name = [i.name for i in new_attr_id.value_ids]
                        value_id = [i.id for i in new_attr_id.value_ids]
                        attr_id_d.update({new_attr_id.id: v_list})
                        attrName_ids.append(new_attr_id.id)
                        attrValue_ids.append(v_list)
                # print(attr_id_d)
                # print(item)

            # 处理属性名和属性值  字段匹配问题
            del import_fields[-1]
            del import_fields[-1]

        import_result = model.load(import_fields, data)
        _logger.info('done')

        _logger.info(import_result)

        try:
            if dryrun:
                # 测试产品多规格导入
                if model._name == 'product.template':
                    if import_result['ids']:
                        for index, id in enumerate(import_result['ids']):
                            if data[index][-2]:
                                # 每行属性名的长度
                                attrName_len = len(data[index][-2].split(';'))
                                # 每行属性名对应的ids
                                item_arrtNameIds = attrName_ids[0:attrName_len:1]
                                # 每行属性名对应的 属性值ids
                                item_attrValueIds = attrValue_ids[0:attrName_len:1]

                                for index, i in enumerate(item_arrtNameIds):
                                    self.env['product.template.attribute.line'].create({
                                        'product_tmpl_id': id,
                                        'attribute_id': i,
                                        'value_ids': [(6, 0, item_attrValueIds[index])]
                                    })
                                # self.env['product.template'].write()

                                # 删除操作之后的ids
                                del attrName_ids[0: attrName_len]
                                del attrValue_ids[0: attrName_len]

                self._cr.execute('ROLLBACK TO SAVEPOINT import')
                self.pool.reset_changes()
            else:
                # 产品多规格导入
                if model._name == 'product.template':
                    if import_result['ids']:
                        for index, id in enumerate(import_result['ids']):
                            if data[index][-2]:
                                # 每行属性名的长度
                                attrName_len = len(data[index][-2].split(';'))
                                # 每行属性名对应的ids
                                item_arrtNameIds = attrName_ids[0:attrName_len:1]
                                # 每行属性名对应的 属性值ids
                                item_attrValueIds = attrValue_ids[0:attrName_len:1]

                                for index, i in enumerate(item_arrtNameIds):
                                    self.env['product.template.attribute.line'].create({
                                        'product_tmpl_id': id,
                                        'attribute_id': i,
                                        'value_ids': [(6, 0, item_attrValueIds[index])]
                                    })
                                # self.env['product.template'].write()

                                # 删除操作之后的ids
                                del attrName_ids[0: attrName_len]
                                del attrValue_ids[0: attrName_len]

                self._cr.execute('RELEASE SAVEPOINT import')
        except psycopg2.InternalError:
            pass

        # Insert/Update mapping columns when import complete successfully
        if import_result['ids'] and options.get('headers'):
            BaseImportMapping = self.env['base_import.mapping']
            for index, column_name in enumerate(columns):
                if column_name:
                    # Update to latest selected field
                    exist_records = BaseImportMapping.search(
                        [('res_model', '=', self.res_model), ('column_name', '=', column_name)])
                    if exist_records:
                        exist_records.write({'field_name': fields[index]})
                    else:
                        BaseImportMapping.create({
                            'res_model': self.res_model,
                            'column_name': column_name,
                            'field_name': fields[index]
                        })

        return import_result
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值