Ejemplo n.º 1
0
 def default_get(self, cr, uid, fields, context=None):
     """
         Default get for name, opportunity_ids
         if there is an exisitng  partner link to the lead, find all existing opportunity link with this partnet to merge
         all information together
     """
     lead_obj = self.pool["crm.lead"]
     res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
     for lead in lead_obj.browse(cr, uid, context.get("active_ids"), context=context):
         if lead.vat:
             if vatnumber.check_vat(lead.vat):
                 res["vat"] = lead.vat
                 partner_ids = self.pool["res.partner"].search(
                     cr, uid, [("vat", "ilike", lead.vat)], context=context
                 )
                 if partner_ids:
                     partner = self.pool["res.partner"].browse(cr, uid, partner_ids[0], context=context)
                     res["partner_id"] = partner.id
                     res["action"] = "exist"
             else:
                 raise orm.except_orm(_("Error :"), _("VAT '%s' not valid.") % lead.vat)
         res["street"] = lead.street or ""
         res["street2"] = lead.street2 or ""
         res["zip"] = lead.zip or ""
         res["city"] = lead.city or ""
     return res
Ejemplo n.º 2
0
 def default_get(self, cr, uid, fields, context=None):
     """
         Default get for name, opportunity_ids
         if there is an exisitng  partner link to the lead, find all existing opportunity link with this partnet to merge
         all information together
     """
     lead_obj = self.pool['crm.lead']
     res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
     for lead in lead_obj.browse(cr, uid, context.get('active_ids'), context=context):
         if lead.vat:
             if vatnumber.check_vat(lead.vat):
                 res['vat'] = lead.vat
                 partner_ids = self.pool['res.partner'].search(cr, uid, [('vat', 'ilike', lead.vat)], context=context)
                 if partner_ids:
                     partner = self.pool['res.partner'].browse(cr, uid, partner_ids[0], context=context)
                     res['partner_id'] = partner.id
                     res['action'] = 'exist'
             else:
                 raise orm.except_orm(_('Error :'), _("VAT '%s' not valid.") % lead.vat)
         res.update({
             'street': lead.street or '',
             'street2': lead.street2 or '',
             'zip': lead.zip or '',
             'city': lead.city or '',
         })
     return res
Ejemplo n.º 3
0
 def default_get(self, cr, uid, fields, context=None):
     """
         Default get for name, opportunity_ids
         if there is an exisitng  partner link to the lead, find all existing opportunity link with this partnet to merge
         all information together
     """
     lead_obj = self.pool['crm.lead']
     res = super(crm_lead2opportunity_partner,
                 self).default_get(cr, uid, fields, context=context)
     for lead in lead_obj.browse(cr,
                                 uid,
                                 context.get('active_ids'),
                                 context=context):
         if lead.vat:
             if vatnumber.check_vat(lead.vat):
                 res['vat'] = lead.vat
                 partner_ids = self.pool['res.partner'].search(
                     cr, uid, [('vat', 'ilike', lead.vat)], context=context)
                 if partner_ids:
                     partner = self.pool['res.partner'].browse(
                         cr, uid, partner_ids[0], context=context)
                     res['partner_id'] = partner.id
                     res['action'] = 'exist'
             else:
                 raise orm.except_orm(_('Error :'),
                                      _("VAT '%s' not valid.") % lead.vat)
         res.update({
             'street': lead.street or '',
             'street2': lead.street2 or '',
             'zip': lead.zip or '',
             'city': lead.city or '',
         })
     return res
Ejemplo n.º 4
0
 def test_vat_numbers(self):
     '''
     Test VAT numbers
     '''
     for code, number, result in VAT_NUMBERS:
         if result:
             test = self.assertTrue
         else:
             test = self.assertFalse
         test(vatnumber.check_vat(code + number), code + number)
Ejemplo n.º 5
0
 def test_vat_numbers(self):
     '''
     Test VAT numbers
     '''
     for code, number, result in VAT_NUMBERS:
         if result:
             test = self.assertTrue
         else:
             test = self.assertFalse
         test(vatnumber.check_vat(code + number), code + number)
Ejemplo n.º 6
0
    def __call__(self, value):
        # check country code
        country_code = str(value[:2])
        country = Country(code=country_code.upper(), flag_url=None)
        if not country:
            raise ValidationError(_('{0} is not a valid country code.').format(country_code))

        if not vatnumber.check_vat(value):
            raise ValidationError(_('{0} is not a valid VAT number').format(value))

        if self.use_vies_validation and EUTaxationPolicy.is_in_EU(country_code):
            if not vatnumber.check_vies(value):
                raise ValidationError(_('{0} is not a valid VAT number').format(value))
Ejemplo n.º 7
0
def check_vat(vat):
    if vat[:2] == "ES":
        vat_format = vat
        country_id = 69
    else:
        vat_format = "ES" + vat
        country_id = 69

    if vatnumber.check_vat(vat_format) == False:
        vat_subjected = False
        comment = "NIF: " + vat_format
        vat_format = ""
    else:
        vat_subjected = True
        comment = ""
    return [vat_format, vat_subjected, comment, country_id]
Ejemplo n.º 8
0
    def __call__(self, value):
        # check country code
        country_code = str(value[:2])
        country = Country(code=country_code.upper(), flag_url=None)
        if not country:
            raise ValidationError(
                _('{0} is not a valid country code.').format(country_code))

        if not vatnumber.check_vat(value):
            raise ValidationError(
                _('{0} is not a valid VAT number').format(value))

        if self.use_vies_validation and EUTaxationPolicy.is_in_EU(
                country_code):
            if not vatnumber.check_vies(value):
                raise ValidationError(
                    _('{0} is not a valid VAT number').format(value))
 def validate_vies(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     values = {}
     partner_obj = self.pool.get('res.partner')
     for partner in partner_obj.browse(cr, uid, context.get('active_ids'), context=context):
         values['valid_vies_vat'] = False
         if partner.vat:
             vat = self._split_vat(partner.vat)
             #if self.check_customer_vat(cr, uid, vat[0], vat[1]):
             if vatnumber.check_vat(partner.vat):
                 if vatnumber.check_vies(partner.vat):
                     values['valid_vies_vat'] = True
             else:
                 raise osv.except_osv(_("Error"), _("Client Vat Number not have a valid format"))
                 return {'type': 'ir.actions.act_window_close'}                    
         partner_obj.write(cr, uid, [partner.id], values)
     return {'type': 'ir.actions.act_window_close'}
Ejemplo n.º 10
0
    def clean_tax_number(tax_number, country):
        tax_number = re.sub(r'[^A-Z0-9]', '', tax_number.upper())
        if tax_number and country:

            if country in vatnumber.countries():
                number = tax_number
                if tax_number.startswith(country):
                    number = tax_number[len(country):]

                if not vatnumber.check_vat(country + number):
                    #           This is a proper solution to bind ValidationError to a Field but it is not
                    #           working due to django bug :(
                    #                    errors = defaultdict(list)
                    #                    errors['tax_number'].append(_('VAT ID is not correct'))
                    #                    raise ValidationError(errors)
                    raise ValidationError(_('VAT ID is not correct'))

            return tax_number
        else:
            return ''
Ejemplo n.º 11
0
    def clean_tax_number(tax_number, country):
        tax_number = re.sub(r'[^A-Z0-9]', '', tax_number.upper())
        if tax_number and country:

            if country in vatnumber.countries():
                number = tax_number
                if tax_number.startswith(country):
                    number = tax_number[len(country):]

                if not vatnumber.check_vat(country + number):
                    #           This is a proper solution to bind ValidationError to a Field but it is not
                    #           working due to django bug :(
                    #                    errors = defaultdict(list)
                    #                    errors['tax_number'].append(_('VAT ID is not correct'))
                    #                    raise ValidationError(errors)
                    raise ValidationError(_('VAT ID is not correct'))

            return tax_number
        else:
            return ''
Ejemplo n.º 12
0
 def validate_vies(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     values = {}
     partner_obj = self.pool.get('res.partner')
     for partner in partner_obj.browse(cr,
                                       uid,
                                       context.get('active_ids'),
                                       context=context):
         values['valid_vies_vat'] = False
         if partner.vat:
             vat = self._split_vat(partner.vat)
             #if self.check_customer_vat(cr, uid, vat[0], vat[1]):
             if vatnumber.check_vat(partner.vat):
                 if vatnumber.check_vies(partner.vat):
                     values['valid_vies_vat'] = True
             else:
                 raise osv.except_osv(
                     _("Error"),
                     _("Client Vat Number not have a valid format"))
                 return {'type': 'ir.actions.act_window_close'}
         partner_obj.write(cr, uid, [partner.id], values)
     return {'type': 'ir.actions.act_window_close'}
Ejemplo n.º 13
0
def check_vat(value):
    if value != "" and not vatnumber.check_vat(value):
        raise ValidationError(_(u"%s is not a valid VAT number") % value)
Ejemplo n.º 14
0
    def import_row(self, cr, uid, row_list, book_datemode):
        if not len(row_list) == len(self.HEADER):
            error = u'Riga {0} non importata. Colonne non corrsipondono al Header definito'.format(
                self.processed_lines)
            _logger.debug(error)
            self.error.append(error)
            return False

        if DEBUG:
            # pprint(row_list)
            row_str_list = [self.simple_string(value) for value in row_list]
            pprint(zip(self.HEADER, row_str_list))

        record = self.Record._make([self.toStr(value) for value in row_list])

        if self.first_row:
            if not record.name:
                warning = u'Riga {0}: Trovato Header'.format(
                    self.processed_lines)
                _logger.debug(warning)
                self.warning.append(warning)
                return True
            else:
                for column in record:
                    # column_ascii = unicodedata.normalize('NFKD', column).encode('ascii', 'ignore').lower()
                    if column in self.HEADER:
                        warning = u'Riga {0}: Trovato Header'.format(
                            self.processed_lines)
                        _logger.debug(warning)
                        self.warning.append(warning)
                        return True

        self.first_row = False

        for field in self.REQUIRED:
            if not getattr(record, field):
                error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format(
                    self.processed_lines, field)
                _logger.debug(error)
                self.error.append(error)
                return False

        # manage partners
        vals_partner = {
            'name': record.name,
            'fiscalcode': record.fiscalcode,
            self.partner_type: True
        }

        if self.PARTNER_UNIQUE_OFFICE_CODE:
            if hasattr(record, 'fiscalcode') and record.fiscalcode:
                if len(vals_partner['fiscalcode']) == 6:
                    vals_partner['unique_office_code'] = vals_partner[
                        'fiscalcode']

                    if hasattr(record,
                               'additiona_id') and record.additional_id:
                        vals_partner['fiscalcode'] = vals_partner[
                            'additional_id']
                    else:
                        vals_partner['fiscalcode'] = False
            else:
                vals_partner['fiscalcode'] = False

        if 'supplier' in vals_partner:
            vals_partner.update({'customer': False, 'supplier': True})

        if hasattr(record, 'person_name') and record.person_name:
            vals_partner['name'] += ' {0}'.format(record.person_name)

        if hasattr(record, 'country_code'):
            country_code = COUNTRY_CODES.get(record.country_code,
                                             record.country_code)
        else:
            if hasattr(record,
                       'vat') and record.vat and record.vat[:2] in VAT_CODES:
                country_code = record.vat[:2]
            else:
                country_code = ''

        if country_code:
            country_id = self._contry_by_code(cr, uid, country_code)
            if country_id:
                country = self.pool['res.country'].browse(
                    cr, uid, country_id, self.context)

                fiscal_position_ids = self.account_fiscal_position_obj.search(
                    cr,
                    uid, [('name', '=ilike', country.name)],
                    context=self.context)

                if fiscal_position_ids and len(fiscal_position_ids) == 1:
                    vals_partner[
                        'property_account_position'] = fiscal_position_ids[0]
                else:
                    warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format(
                        self.processed_lines, vals_partner['name'])
                    _logger.debug(warning)
                    self.warning.append(warning)
            else:
                error = u"Riga {0}: Country code '{1}' non è riconosciuto. La riga viene ignorata.".format(
                    self.processed_lines, country_code)
                _logger.debug(error)
                self.error.append(error)
                return False

        if hasattr(record, 'fiscal_position') and record.fiscal_position:
            fiscal_position = self.partner_template.map_account_fiscal_position(
                cr, uid, self.partner_template_id, record.fiscal_position)
            if fiscal_position:
                vals_partner['property_account_position'] = fiscal_position

        if hasattr(record, 'payment_term') and record.payment_term:
            vals_payment = self.partner_template.map_payment_term(
                cr, uid, self.partner_template_id, record.payment_term)
            if vals_payment.get('property_payment_term', False):
                vals_partner['property_payment_term'] = vals_payment[
                    'property_payment_term']
            if vals_payment.get('company_bank_id', False):
                vals_partner['company_bank_id'] = vals_payment[
                    'company_bank_id']

        if hasattr(record, 'credit_limit') and record.credit_limit:
            vals_partner['credit_limit'] = record.credit_limit

        if record.vat and len(record.vat) > 3:
            vals_partner['vat_subjected'] = True
            vals_partner['individual'] = False

            if country_code:
                country_code = country_code[:2]
            else:
                country_code = ''

            vat = record.vat
            if vat and len(vat) == 10 and country_code[:2] == 'IT':
                vat = '0' + vat
            if vat and len(vat) == 9 and country_code[:2] == 'IT':
                vat = '00' + vat
            if not country_code == record.vat[:2]:
                vals_partner['vat'] = country_code + vat
            else:
                vals_partner['vat'] = vat

            vals_partner['vat'] = vals_partner['vat'].replace(' ', '')
            # if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None):
            if vatnumber.check_vat(vals_partner['vat']):
                if record.vat == record.fiscalcode:
                    vals_partner['fiscalcode'] = vals_partner['vat']
            else:
                error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: <strong>'{vat}'</strong>".format(
                    line=self.processed_lines,
                    record=record,
                    vat=vals_partner['vat'])
                _logger.debug(error)
                self.error.append(error)
                if DONT_STOP_ON_WRONG_VAT:
                    del vals_partner['vat']
                    if vals_partner.get('fiscalcode'):
                        del vals_partner['fiscalcode']
                else:
                    return False

        # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16:
        #    error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode)
        #    _logger.debug(error)
        #    self.error.append(error)
        #    return False
        # elif record.fiscalcode and not record.vat:
        #    vals_partner['individual'] = True

        if vals_partner.get('fiscalcode') and not vals_partner.get('vat'):
            vals_partner['individual'] = True

        # if country_code == 'IT':
        #    vals_partner['property_account_position'] = self.italy_fiscal_position_id
        #    if record.vat:
        #        pdb.set_trace()
        #        old_vat = vals_input['Partita IVA']
        #        if len(vals_input['Partita IVA']) < 11:
        #            zero_add = 11 - len(vals_input['Partita IVA'])
        #            for zero in range(0, zero_add):
        #                vals_input['Partita IVA'] = '0' + vals_input['Partita IVA']

        if hasattr(record, 'comment') and record.comment:
            vals_partner['comment'] = record.comment

        record_code = self.simple_string(record.code, as_integer=True)

        if self.UPDATE_ON_CODE and PROPERTY_REF_MAP[self.partner_type]:
            code_partner_ids = self.partner_obj.search(
                cr,
                uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)],
                context=self.context)
        else:
            code_partner_ids = False

        if code_partner_ids and not self.UPDATE_ON_CODE:
            code_partner_data = self.partner_obj.browse(
                cr, uid, code_partner_ids[0], self.context)
            if vals_partner.get(
                    'vat', False
            ) and not code_partner_data.vat == vals_partner['vat']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(
                    self.processed_lines, record_code, vals_partner['name'],
                    code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
            elif vals_partner.get(
                    'fiscalcode', False
            ) and not code_partner_data.fiscalcode == vals_partner[
                    'fiscalcode']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(
                    self.processed_lines, record_code, vals_partner['name'],
                    code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
        elif code_partner_ids and self.UPDATE_ON_CODE:
            vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code
            if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH:
                self.PARTNER_SEARCH.insert(0,
                                           PROPERTY_REF_MAP[self.partner_type])
        else:
            if record_code:
                vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code

        if hasattr(record, 'category') and record.category:
            category_ids = self.category_obj.search(
                cr,
                uid, [('name', 'ilike', record.category)],
                context=self.context)

            if len(category_ids) == 1:
                vals_partner['category_id'] = [(6, 0, category_ids)]
            else:
                vals_partner['category_id'] = [(6, 0, [
                    self.category_obj.create(cr, uid, {
                        'name': record.category,
                        'active': True
                    }), self.context
                ])]

        # partner_id = self._find_partner(cr, uid, record)
        partner_id = self._find_partner(cr, uid, vals_partner)

        if partner_id and partner_id > 0:
            self.partner_obj.write(cr, uid, partner_id, vals_partner,
                                   self.context)
            self.updated += 1
        elif partner_id and partner_id < 0:
            return False
        else:
            self.context['import'] = True
            try:
                partner_id = self.partner_obj.create(cr, uid, vals_partner,
                                                     self.context)
                self.uo_new += 1
            # except ValidateError as e:
            except Exception as e:
                # e = sys.exc_info()[0]
                e = e[1].split(':')[1]
                error = u"Riga {0}: Partner '{1} {2}'. I dati non corretti. (Error: {3}) La riga viene ignorata.".format(
                    self.processed_lines, record_code, vals_partner['name'], e)
                _logger.debug(error)
                self.error.append(error)
                return False

        address_type_1 = self.ADDRESS_TYPE[0]
        address_type_2 = self.ADDRESS_TYPE[1]

        if getattr(record, 'street_' + address_type_1) or getattr(
                record, 'zip_' + address_type_1) or getattr(
                    record, 'city_' + address_type_1) or getattr(
                        record, 'province_' + address_type_1):
            first_address = True
        else:
            first_address = False

        if getattr(record, 'street_' + address_type_2) or getattr(
                record, 'zip_' + address_type_2) or getattr(
                    record, 'city_' + address_type_2) or getattr(
                        record, 'province_' + address_type_2):
            second_address = True
        else:
            second_address = False

        if first_address and second_address:
            self.write_address(cr, uid, address_type_1, partner_id, record,
                               vals_partner, country_code)
            self.write_address(cr, uid, address_type_2, partner_id, record,
                               vals_partner, country_code)
        elif first_address:
            self.write_address(cr,
                               uid,
                               address_type_1,
                               partner_id,
                               record,
                               vals_partner,
                               country_code,
                               force_default=True)
        elif second_address:
            self.write_address(cr,
                               uid,
                               address_type_2,
                               partner_id,
                               record,
                               vals_partner,
                               country_code,
                               force_default=True)

        return partner_id
def importar():
    dbf = ydbf.open(os.path.join('dbf', 'Subcta.dbf'), encoding='latin-1')
    for row in dbf:

        # PARA PROVEEDORES

        if ((row["COD"].startswith('410') and row["COD"] != "41000000") or
            (row["COD"].startswith('400') and row["COD"] != "40000000")):

            country_obj = origen.model('res.country.state')
            country_id = country_obj.browse([('name', 'ilike',
                                              row['PROVINCIA'])])

            if country_id:
                country_id = country_id[0].id

            else:
                country_id = False

            partner = {
                'name': row['TITULO'].strip(),
                'vat': decodeCIF(row['NIF']),
                'supplier': True,
                'customer': False,
                'opt_out': True,
                'street': row['DOMICILIO'].strip(),
                'zip': row['CODPOSTAL'],
                'city': row['POBLACION'],
                'state_id': country_id
            }

            if not vatnumber.check_vat(partner['vat']):
                partner['vat'] = False

            partner_obj = origen.model(name='res.partner')
            if not partner_obj.browse([('name', '=', row['TITULO'])]):
                partner = partner_obj.create(partner)

        # PARA CLIENTES

        if ((row["COD"].startswith('430') and row["COD"] != "43000000") or
            (row["COD"].startswith('440') and row["COD"] != "44000000")):

            country_obj = origen.model('res.country.state')
            country_id = country_obj.browse([('name', 'ilike',
                                              row['PROVINCIA'])])

            if country_id:
                country_id = country_id[0].id

            else:
                country_id = False

            partner = {
                'name': row['TITULO'].strip(),
                'vat': decodeCIF(row['NIF']),
                'supplier': False,
                'customer': True,
                'opt_out': True,
                'street': row['DOMICILIO'].strip(),
                'zip': row['CODPOSTAL'],
                'city': row['POBLACION'],
                'state_id': country_id
            }

            if not vatnumber.check_vat(partner['vat']):
                partner['vat'] = False

            partner_obj = origen.model(name='res.partner')
            if not partner_obj.browse([('name', '=', row['TITULO'])]):
                partner = partner_obj.create(partner)

        # CREACIÓN DE CUENTAS

        account_obj = origen.model(name='account.account')
        accounts = account_obj.browse([("code", "=", row['COD'][0:2] + '0000')
                                       ])
        if not accounts:
            accounts = account_obj.browse([("code", "like", row['COD'][0:2])])

        account = {
            'name': row['TITULO'].strip(),
            'code': row['COD'],
            'user_type_id': accounts[0].user_type_id.id or 1,
            'reconcile': accounts[0].reconcile
        }

        if not account_obj.browse([('code', '=', row['COD'])]):
            account = account_obj.create(account)
Ejemplo n.º 16
0
    def import_row(self, cr, uid, row_list, book_datemode):
        if not len(row_list) == len(self.HEADER):
            error = u'Riga {0} non importata. Colonne non corrsipondono al Header definito'.format(self.processed_lines)
            _logger.debug(error)
            self.error.append(error)
            return False

        if DEBUG:
            # pprint(row_list)
            row_str_list = [self.simple_string(value) for value in row_list]
            pprint(zip(self.HEADER, row_str_list))

        record = self.Record._make([self.toStr(value) for value in row_list])

        if self.first_row:
            if not record.name:
                warning = u'Riga {0}: Trovato Header'.format(self.processed_lines)
                _logger.debug(warning)
                self.warning.append(warning)
                return True
            else:
                for column in record:
                    #column_ascii = unicodedata.normalize('NFKD', column).encode('ascii', 'ignore').lower()
                    if column in self.HEADER:
                        warning = u'Riga {0}: Trovato Header'.format(self.processed_lines)
                        _logger.debug(warning)
                        self.warning.append(warning)
                        return True

        self.first_row = False

        for field in self.REQUIRED:
            if not getattr(record, field):
                error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format(self.processed_lines, field)
                _logger.debug(error)
                self.error.append(error)
                return False

        # manage partners
        vals_partner = {
            'name': record.name,
            'fiscalcode': record.fiscalcode,
            self.partner_type: True
        }

        if 'supplier' in vals_partner:
            vals_partner['customer'] = False

        if hasattr(record, 'person_name') and record.person_name:
            vals_partner['name'] += ' {0}'.format(record.person_name)

        country_code = COUNTRY_CODES.get(record.country_code, record.country_code)

        if country_code:
            country_id = self._contry_by_code(cr, uid, country_code)
            if country_id:
                country = self.pool['res.country'].browse(cr, uid, country_id)

                fiscal_position_ids = self.account_fiscal_position_obj.search(cr, uid, [('name', '=ilike', country.name)])

                if fiscal_position_ids and len(fiscal_position_ids) == 1:
                    vals_partner['property_account_position'] = fiscal_position_ids[0]
                else:
                    warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format(self.processed_lines, vals_partner['name'])
                    _logger.debug(warning)
                    self.warning.append(warning)
            else:
                error = u"Riga {0}: Country code '{1}' non è riconosciuto. La riga viene ignorata.".format(self.processed_lines, country_code)
                _logger.debug(error)
                self.error.append(error)
                return False

        if hasattr(record, 'fiscal_position') and record.fiscal_position:
            fiscal_position = self.partner_template.map_account_fiscal_position(cr, uid, self.partner_template_id, record.fiscal_position)
            if fiscal_position:
                vals_partner['property_account_position'] = fiscal_position

        if hasattr(record, 'payment_term') and record.payment_term:
            vals_payment = self.partner_template.map_payment_term(cr, uid, self.partner_template_id, record.payment_term)
            if vals_payment.get('property_payment_term', False):
                vals_partner['property_payment_term'] = vals_payment['property_payment_term']
            if vals_payment.get('company_bank_id', False):
                vals_partner['company_bank_id'] = vals_payment['company_bank_id']

        if record.vat and len(record.vat) > 3:
            vals_partner['vat_subjected'] = True
            vals_partner['individual'] = False

            if not country_code == record.vat[:2]:
                vals_partner['vat'] = country_code + record.vat
            else:
                vals_partner['vat'] = record.vat

            #if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None):
            if not vatnumber.check_vat(vals_partner['vat']):
                error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: {record.vat}".format(line=self.processed_lines, record=record)
                _logger.debug(error)
                self.error.append(error)
                if DONT_STOP_ON_WRONG_VAT:
                    del vals_partner['vat']
                else:
                    return False

            if record.vat == record.fiscalcode:
                vals_partner['fiscalcode'] = vals_partner['vat']

        # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16:
        #    error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode)
        #    _logger.debug(error)
        #    self.error.append(error)
        #    return False
        # elif record.fiscalcode and not record.vat:
        #    vals_partner['individual'] = True

        if record.fiscalcode and not record.vat:
            vals_partner['individual'] = True

        # if country_code == 'IT':
        #    vals_partner['property_account_position'] = self.italy_fiscal_position_id
        #    if record.vat:
        #        pdb.set_trace()
        #        old_vat = vals_input['Partita IVA']
        #        if len(vals_input['Partita IVA']) < 11:
        #            zero_add = 11 - len(vals_input['Partita IVA'])
        #            for zero in range(0, zero_add):
        #                vals_input['Partita IVA'] = '0' + vals_input['Partita IVA']

        if hasattr(record, 'comment') and record.comment:
            vals_partner['comment'] = record.comment

        record_code = self.simple_string(record.code, as_integer=True)
        code_partner_ids = self.partner_obj.search(cr, uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)])

        if code_partner_ids and not UPDATE_ON_CODE:
            code_partner_data = self.partner_obj.browse(cr, uid, code_partner_ids[0])
            if vals_partner.get('vat', False) and not code_partner_data.vat == vals_partner['vat']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
            elif vals_partner.get('fiscalcode', False) and not code_partner_data.fiscalcode == vals_partner['fiscalcode']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
        elif code_partner_ids and UPDATE_ON_CODE:
            vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code
            if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH:
                self.PARTNER_SEARCH.insert(0, PROPERTY_REF_MAP[self.partner_type])
        else:
            vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code

        if hasattr(record, 'category') and record.category:
            category_ids = self.category_obj.search(cr, uid, [('name', 'ilike', record.category)])

            if len(category_ids) == 1:
                vals_partner['category_id'] = [(6, 0, category_ids)]
            else:
                vals_partner['category_id'] = [(6, 0, [self.category_obj.create(cr, uid, {
                    'name': record.category,
                    'active': True
                })])]

        # partner_id = self._find_partner(cr, uid, record)
        partner_id = self._find_partner(cr, uid, vals_partner)

        if partner_id and partner_id > 0:
            self.partner_obj.write(cr, uid, partner_id, vals_partner, self.context)
            self.updated += 1
        elif partner_id and partner_id < 0:
            return False
        else:
            self.context['import'] = True
            partner_id = self.partner_obj.create(cr, uid, vals_partner, self.context)
            self.uo_new += 1

        address_type_1 = self.ADDRESS_TYPE[0]
        address_type_2 = self.ADDRESS_TYPE[1]

        if getattr(record, 'street_' + address_type_1) or getattr(record, 'zip_' + address_type_1) or getattr(record, 'city_' + address_type_1) or getattr(record, 'province_' + address_type_1):
            first_address = True
        else:
            first_address = False

        if getattr(record, 'street_' + address_type_2) or getattr(record, 'zip_' + address_type_2) or getattr(record, 'city_' + address_type_2) or getattr(record, 'province_' + address_type_2):
            second_address = True
        else:
            second_address = False

        if first_address and second_address:
            self.write_address(cr, uid, address_type_1, partner_id, record, vals_partner, country_code)
            self.write_address(cr, uid, address_type_2, partner_id, record, vals_partner, country_code)
        elif first_address:
            self.write_address(cr, uid, address_type_1, partner_id, record, vals_partner, country_code, force_default=True)
        elif second_address:
            self.write_address(cr, uid, address_type_2, partner_id, record, vals_partner, country_code, force_default=True)

        return partner_id
Ejemplo n.º 17
0
    def collect_values(self, cr, uid, record):
        self.first_row = False

        for field in self.REQUIRED:
            if not getattr(record, field):
                error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format(
                    self.processed_lines, field)
                _logger.debug(error)
                self.error.append(error)
                return False

        if self.FORMAT == 'FormatOmnitron':
            if record.client_supplier == u'1':
                self.partner_type = 'supplier'
            else:
                self.partner_type = 'customer'

        # manage partners
        vals_partner = {
            'name': record.name,
            'fiscalcode': record.fiscalcode,
            self.partner_type: True
        }

        if self.is_fiscalcode(record.fiscalcode):
            vals_partner['fiscalcode'] = record.fiscalcode
        else:
            error = u"Riga {0}: Fiscalcode {1} is not valid".format(
                self.processed_lines, record.fiscalcode)
            _logger.debug(error)
            self.error.append(error)
            vals_partner['fiscalcode'] = ''

        if self.PARTNER_UNIQUE_OFFICE_CODE:
            if hasattr(record, 'fiscalcode') and record.fiscalcode:
                if len(vals_partner['fiscalcode']) == 6:
                    vals_partner['unique_office_code'] = vals_partner[
                        'fiscalcode']

                    if hasattr(record,
                               'additiona_id') and record.additional_id:
                        vals_partner['fiscalcode'] = vals_partner[
                            'additional_id']
                    else:
                        vals_partner['fiscalcode'] = False
            else:
                vals_partner['fiscalcode'] = False

        if self.FORMAT == 'FormatOmnitron':
            if 'customer' in vals_partner:
                del vals_partner['customer']

            if record.client_supplier == u'1':
                vals_partner.update({
                    'supplier': True,
                })
            else:
                vals_partner.update({'customer': True})
        else:
            # TODO: Check this code!!!
            if 'supplier' in vals_partner:
                vals_partner.update({'customer': False, 'supplier': True})

        if hasattr(record, 'person_name') and record.person_name:
            vals_partner['name'] += ' {0}'.format(record.person_name)

        if hasattr(record, 'country_code'):
            country_id = self._country_by_code(cr, uid, record.country_code)
        elif getattr(record, 'country_name'):
            country_id = self._country_by_code(cr, uid, record.country_name)
            if not country_id:
                _logger.error("Can't find country {}".format(
                    record.country_name))
        else:
            country_id = False

        if country_id:
            country = self.pool['res.country'].browse(cr, uid, country_id,
                                                      self.context)
            country_code = country.code
        else:
            if hasattr(record,
                       'vat') and record.vat and record.vat[:2] in VAT_CODES:
                country_code = record.vat[:2]
                country_id = self._country_by_code(cr, uid, country_code)
                country = self.pool['res.country'].browse(
                    cr, uid, country_id, self.context)
            else:
                country_code = ''

        if country_id:
            fiscal_position_ids = self.account_fiscal_position_obj.search(
                cr,
                uid, [('name', '=ilike', country.name)],
                context=self.context)
            if fiscal_position_ids and len(fiscal_position_ids) == 1:
                vals_partner[
                    'property_account_position'] = fiscal_position_ids[0]
            else:
                warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format(
                    self.processed_lines, vals_partner['name'])
                _logger.debug(warning)
                self.warning.append(warning)
        else:
            error = u"Riga {0}: {1} Country non è riconosciuto".format(
                self.processed_lines, vals_partner['name'])
            _logger.debug(error)
            self.error.append(error)

        if hasattr(record, 'fiscal_position') and record.fiscal_position:
            fiscal_position = self.partner_template.map_account_fiscal_position(
                cr, uid, self.partner_template_id, record.fiscal_position)
            if fiscal_position:
                vals_partner['property_account_position'] = fiscal_position

        if hasattr(record, 'payment_term') and record.payment_term:
            vals_payment = self.partner_template.map_payment_term(
                cr, uid, self.partner_template_id, record.payment_term)
            if vals_payment.get('property_payment_term', False):
                vals_partner['property_payment_term'] = vals_payment[
                    'property_payment_term']
            if vals_payment.get('company_bank_id', False):
                vals_partner['company_bank_id'] = vals_payment[
                    'company_bank_id']

        if hasattr(record, 'credit_limit') and record.credit_limit:
            vals_partner['credit_limit'] = record.credit_limit

        if record.vat and len(record.vat) > 3:
            vals_partner['vat_subjected'] = True
            vals_partner['individual'] = False

            vat = record.vat
            if vat and len(vat) == 10 and country_code[:2] == 'IT':
                vat = '0' + vat
            if vat and len(vat) == 9 and country_code[:2] == 'IT':
                vat = '00' + vat

            if not country_code == record.vat[:2]:
                vals_partner['vat'] = country_code + vat
            else:
                vals_partner['vat'] = vat

            vals_partner['vat'] = vals_partner['vat'].replace(' ', '')
            # if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None):
            if vatnumber.check_vat(vals_partner['vat']) or vatnumber.check_vat(
                    'IT' + vals_partner['vat']):
                if vatnumber.check_vat('IT' + vals_partner['vat']):
                    vals_partner['vat'] = 'IT' + vals_partner['vat']
                if record.vat == record.fiscalcode:
                    if codicefiscale.isvalid(record.vat):
                        vals_partner['fiscalcode'] = vals_partner['vat']
                    else:
                        vals_partner['fiscalcode'] = False
            else:
                error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: <strong>'{vat}'</strong>".format(
                    line=self.processed_lines,
                    record=record,
                    vat=vals_partner['vat'])
                _logger.debug(error)
                self.error.append(error)
                if DONT_STOP_ON_WRONG_VAT:
                    del vals_partner['vat']
                    if vals_partner.get('fiscalcode'):
                        del vals_partner['fiscalcode']
                else:
                    return False

        # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16:
        #    error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode)
        #    _logger.debug(error)
        #    self.error.append(error)
        #    return False
        # elif record.fiscalcode and not record.vat:
        #    vals_partner['individual'] = True

        if vals_partner.get('fiscalcode') and not vals_partner.get('vat'):
            vals_partner['individual'] = True

        # if country_code == 'IT':
        #    vals_partner['property_account_position'] = self.italy_fiscal_position_id
        #    if record.vat:
        #        pdb.set_trace()
        #        old_vat = vals_input['Partita IVA']
        #        if len(vals_input['Partita IVA']) < 11:
        #            zero_add = 11 - len(vals_input['Partita IVA'])
        #            for zero in range(0, zero_add):
        #                vals_input['Partita IVA'] = '0' + vals_input['Partita IVA']

        if hasattr(record, 'comment') and record.comment:
            vals_partner['comment'] = record.comment

        record_code = self.simple_string(record.code, as_integer=True)

        if self.UPDATE_ON_CODE and PROPERTY_REF_MAP[self.partner_type]:
            code_partner_ids = self.partner_obj.search(
                cr,
                uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)],
                context=self.context)
        else:
            code_partner_ids = False

        if code_partner_ids and not self.UPDATE_ON_CODE:
            code_partner_data = self.partner_obj.browse(
                cr, uid, code_partner_ids[0], self.context)
            if vals_partner.get(
                    'vat', False
            ) and not code_partner_data.vat == vals_partner['vat']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(
                    self.processed_lines, record_code, vals_partner['name'],
                    code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
            elif vals_partner.get(
                    'fiscalcode', False
            ) and not code_partner_data.fiscalcode == vals_partner[
                    'fiscalcode']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(
                    self.processed_lines, record_code, vals_partner['name'],
                    code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
        elif code_partner_ids and self.UPDATE_ON_CODE:
            vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code
            if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH:
                self.PARTNER_SEARCH.insert(0,
                                           PROPERTY_REF_MAP[self.partner_type])
        else:
            if record_code:
                vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code

        if hasattr(record, 'category') and record.category:
            category_ids = self.category_obj.search(
                cr,
                uid, [('name', '=', record.category)],
                context=self.context)

            if len(category_ids):
                vals_partner['category_id'] = [(6, 0, category_ids)]
            else:
                category_id = self.category_obj.create(cr, uid, {
                    'name': record.category,
                    'active': True
                }, self.context)
                vals_partner['category_id'] = [(6, 0, [category_id])]

        return vals_partner, country_id
Ejemplo n.º 18
0
    def collect_values(self, cr, uid, record):
        self.first_row = False

        for field in self.REQUIRED:
            if not getattr(record, field):
                error = u"Riga {0}: Manca il valore della {1}. La riga viene ignorata.".format(self.processed_lines, field)
                _logger.debug(error)
                self.error.append(error)
                return False

        if self.FORMAT == 'FormatOmnitron':
            if record.client_supplier == u'1':
                self.partner_type = 'supplier'
            else:
                self.partner_type = 'customer'

        # manage partners
        vals_partner = {
            'name': record.name,
            'fiscalcode': record.fiscalcode,
            self.partner_type: True
        }

        if self.is_fiscalcode(record.fiscalcode):
            vals_partner['fiscalcode'] = record.fiscalcode
        else:
            error = u"Riga {0}: Fiscalcode {1} is not valid".format(self.processed_lines, record.fiscalcode)
            _logger.debug(error)
            self.error.append(error)
            vals_partner['fiscalcode'] = ''

        if self.PARTNER_UNIQUE_OFFICE_CODE:
            if hasattr(record, 'fiscalcode') and record.fiscalcode:
                if len(vals_partner['fiscalcode']) == 6:
                    vals_partner['unique_office_code'] = vals_partner['fiscalcode']

                    if hasattr(record, 'additiona_id') and record.additional_id:
                        vals_partner['fiscalcode'] = vals_partner['additional_id']
                    else:
                        vals_partner['fiscalcode'] = False
            else:
                vals_partner['fiscalcode'] = False

        if self.FORMAT == 'FormatOmnitron':
            if 'customer' in vals_partner:
                del vals_partner['customer']

            if record.client_supplier == u'1':
                vals_partner.update({
                    'supplier': True,
                })
            else:
                vals_partner.update({
                    'customer': True
                })
        else:
            # TODO: Check this code!!!
            if 'supplier' in vals_partner:
                vals_partner.update({
                    'customer': False,
                    'supplier': True
                })

        if hasattr(record, 'person_name') and record.person_name:
            vals_partner['name'] += ' {0}'.format(record.person_name)

        if hasattr(record, 'country_code'):
            country_id = self._country_by_code(cr, uid, record.country_code)
        elif getattr(record, 'country_name'):
            country_id = self._country_by_code(cr, uid, record.country_name)
            if not country_id:
                _logger.error("Can't find country {}".format(record.country_name))
        else:
            country_id = False

        if country_id:
            country = self.pool['res.country'].browse(cr, uid, country_id, self.context)
            country_code = country.code
        else:
            if hasattr(record, 'vat') and record.vat and record.vat[:2] in VAT_CODES:
                country_code = record.vat[:2]
                country_id = self._country_by_code(cr, uid, country_code)
                country = self.pool['res.country'].browse(cr, uid, country_id, self.context)
            else:
                country_code = ''

        if country_id:
            fiscal_position_ids = self.account_fiscal_position_obj.search(
                cr, uid, [('name', '=ilike', country.name)], context=self.context
            )
            if fiscal_position_ids and len(fiscal_position_ids) == 1:
                vals_partner['property_account_position'] = fiscal_position_ids[0]
            else:
                warning = u"Riga {0}: Fiscal position can't be determined for partner {1}".format(
                    self.processed_lines, vals_partner['name'])
                _logger.debug(warning)
                self.warning.append(warning)
        else:
            error = u"Riga {0}: {1} Country non è riconosciuto".format(
                self.processed_lines, vals_partner['name'])
            _logger.debug(error)
            self.error.append(error)

        if hasattr(record, 'fiscal_position') and record.fiscal_position:
            fiscal_position = self.partner_template.map_account_fiscal_position(
                cr, uid, self.partner_template_id, record.fiscal_position)
            if fiscal_position:
                vals_partner['property_account_position'] = fiscal_position

        if hasattr(record, 'payment_term') and record.payment_term:
            vals_payment = self.partner_template.map_payment_term(
                cr, uid, self.partner_template_id, record.payment_term)
            if vals_payment.get('property_payment_term', False):
                vals_partner['property_payment_term'] = vals_payment['property_payment_term']
            if vals_payment.get('company_bank_id', False):
                vals_partner['company_bank_id'] = vals_payment['company_bank_id']

        if hasattr(record, 'credit_limit') and record.credit_limit:
            vals_partner['credit_limit'] = record.credit_limit

        if record.vat and len(record.vat) > 3:
            vals_partner['vat_subjected'] = True
            vals_partner['individual'] = False

            vat = record.vat
            if vat and len(vat) == 10 and country_code[:2] == 'IT':
                vat = '0' + vat
            if vat and len(vat) == 9 and country_code[:2] == 'IT':
                vat = '00' + vat

            if not country_code == record.vat[:2]:
                vals_partner['vat'] = country_code + vat
            else:
                vals_partner['vat'] = vat

            vals_partner['vat'] = vals_partner['vat'].replace(' ', '')
            # if not self.partner_obj.simple_vat_check(cr, uid, country_code.lower(), vals_partner['vat'][2:], None):
            if vatnumber.check_vat(vals_partner['vat']) or vatnumber.check_vat('IT' + vals_partner['vat']):
                if vatnumber.check_vat('IT' + vals_partner['vat']):
                    vals_partner['vat'] = 'IT' + vals_partner['vat']
                if record.vat == record.fiscalcode:
                    if codicefiscale.isvalid(record.vat):
                        vals_partner['fiscalcode'] = vals_partner['vat']
                    else:
                        vals_partner['fiscalcode'] = False
            else:
                error = u"Riga {line}: Partner '{record.code} {record.name}'; Partita IVA errata: <strong>'{vat}'</strong>".format(
                    line=self.processed_lines, record=record, vat=vals_partner['vat']
                )
                _logger.debug(error)
                self.error.append(error)
                if DONT_STOP_ON_WRONG_VAT:
                    del vals_partner['vat']
                    if vals_partner.get('fiscalcode'):
                        del vals_partner['fiscalcode']
                else:
                    return False

        # if record.fiscalcode and not record.fiscalcode == record.vat and not len(record.fiscalcode) == 16:
        #    error = u"Riga {0}: Codice Fiscale {1} errato".format(self.processed_lines, record.fiscalcode)
        #    _logger.debug(error)
        #    self.error.append(error)
        #    return False
        # elif record.fiscalcode and not record.vat:
        #    vals_partner['individual'] = True

        if vals_partner.get('fiscalcode') and not vals_partner.get('vat'):
            vals_partner['individual'] = True

        # if country_code == 'IT':
        #    vals_partner['property_account_position'] = self.italy_fiscal_position_id
        #    if record.vat:
        #        pdb.set_trace()
        #        old_vat = vals_input['Partita IVA']
        #        if len(vals_input['Partita IVA']) < 11:
        #            zero_add = 11 - len(vals_input['Partita IVA'])
        #            for zero in range(0, zero_add):
        #                vals_input['Partita IVA'] = '0' + vals_input['Partita IVA']

        if hasattr(record, 'comment') and record.comment:
            vals_partner['comment'] = record.comment

        record_code = self.simple_string(record.code, as_integer=True)

        if self.UPDATE_ON_CODE and PROPERTY_REF_MAP[self.partner_type]:
            code_partner_ids = self.partner_obj.search(cr, uid, [(PROPERTY_REF_MAP[self.partner_type], '=', record_code)], context=self.context)
        else:
            code_partner_ids = False

        if code_partner_ids and not self.UPDATE_ON_CODE:
            code_partner_data = self.partner_obj.browse(cr, uid, code_partner_ids[0], self.context)
            if vals_partner.get('vat', False) and not code_partner_data.vat == vals_partner['vat']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
            elif vals_partner.get('fiscalcode', False) and not code_partner_data.fiscalcode == vals_partner['fiscalcode']:
                error = u"Riga {0}: Partner '{1} {2}'; codice gia utilizzato per partner {3}. La riga viene ignorata.".format(self.processed_lines, record_code, vals_partner['name'], code_partner_data['name'])
                _logger.debug(error)
                self.error.append(error)
                return False
        elif code_partner_ids and self.UPDATE_ON_CODE:
            vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code
            if PROPERTY_REF_MAP[self.partner_type] not in self.PARTNER_SEARCH:
                self.PARTNER_SEARCH.insert(0, PROPERTY_REF_MAP[self.partner_type])
        else:
            if record_code:
                vals_partner[PROPERTY_REF_MAP[self.partner_type]] = record_code

        if hasattr(record, 'category') and record.category:
            category_ids = self.category_obj.search(cr, uid, [('name', '=', record.category)], context=self.context)

            if len(category_ids):
                vals_partner['category_id'] = [(6, 0, category_ids)]
            else:
                category_id = self.category_obj.create(cr, uid, {
                    'name': record.category,
                    'active': True
                }, self.context)
                vals_partner['category_id'] = [(6, 0, [category_id])]

        return vals_partner, country_id
Ejemplo n.º 19
0
def importar():
    dbf = ydbf.open(os.path.join('dbfs', 'FacCliT.dbf'), encoding='latin-1')
    for row in dbf:

        # COMPROBAR SI ESTA EL CLIENTE

        partner_obj = origen.model(name='res.partner')
        partner_id = partner_obj.browse([('name', '=', row['CNOMCLI'].strip())
                                         ])
        if partner_id:
            partner_id[0].ref = row['CCODCLI'].strip()
            if not partner_id[0].customer:
                partner_id[0].customer = True
            partner_id = partner_id[0].id

        # partner_id = partner_obj.search([('ref','=',row['CCODCLI'].strip())])

        else:

            country_obj = origen.model('res.country')
            country_id = country_obj.browse([('name', 'ilike', row['CNACCLI'])
                                             ])

            if country_id:
                country_id = country_id[0].id

            else:
                country_id = False

            #CREACION DE CLIENTES SI NO ESTÁN

            partner = {
                'name': row['CNOMCLI'].strip(),
                'ref': row['CCODCLI'].strip(),
                'vat': decodeCIF(row['CDNICIF']),
                'supplier': False,
                'customer': True,
                'opt_out': True,
                'street': row['CDIRCLI'].strip(),
                'zip': row['CPTLCLI'].strip(),
                'city': row['CPOBCLI'],
                'country_id': country_id,
                # 'company_id': company_id.id
            }

            if not vatnumber.check_vat(partner['vat']):
                partner['vat'] = False

            partner = partner_obj.create(partner)
            partner_id = partner.id

        invoice_obj = origen.model('account.invoice')
        #CREACION DE FACTURAS RECTIFICATIVAS
        if 'Abono' in row['COBSERV']:
            invoice_rect_vals = {
                'name': str(row['CSERIE']) + '0' + str(row['NNUMFAC']),
                # 'account_id': invoice_id[0].account_id.id,
                'partner_id': partner_id,
                'date_invoice': row['DFECFAC'].strftime("%Y-%m-%d"),
                'type': 'out_refund',
                # 'company_id': company_id.id
            }
            invoice_obj.create(invoice_rect_vals)
        else:
            #CREACION DE FACTURAS

            invoice_vals = {
                'name': str(row['CSERIE']) + '0' + str(row['NNUMFAC']),
                # 'account_id': customerAccount.id,
                'partner_id': partner_id,
                'date_invoice': row['DFECFAC'].strftime("%Y-%m-%d"),
                'type': 'out_invoice',
                # 'company_id': company_id.id
            }
            invoice_obj.create(invoice_vals)
Ejemplo n.º 20
0
    def import_partner(self, partner_data):
        partner_obj = self.env['res.partner']
        state_obj = self.env['res.country.state']
        country_obj = self.env['res.country']
        partner_array = []
        for partner in partner_data:
            partner_id = partner_obj.search([('invoiceplane_id', '=',
                                              partner['client_id'])])

            if not partner_id:
                partner_id = partner_obj.search([('name', '=',
                                                  partner['client_name']),
                                                 ('customer', '=', True)])
                if partner_id:
                    partner_id = partner_id[0]
                    partner_id.write({'invoiceplane_id': partner['client_id']})

            country_id = country_obj.search([('code', '=',
                                              partner['client_country'])])
            if not country_id:
                country_id = country_obj.search([('code', '=', 'ES')])
            state_id = state_obj.search([('name', '=',
                                          partner['client_state']),
                                         ('country_id', '=', country_id.id)])
            if not partner_id:
                values = {
                    'invoiceplane_id':
                    partner['client_id'],
                    'name':
                    partner['client_name'],
                    'mobile':
                    partner['client_mobile'],
                    'phone':
                    partner['client_phone'],
                    'email':
                    partner['client_email'],
                    'street':
                    partner['client_address_1'],
                    'city':
                    partner['client_city'],
                    'state_id':
                    state_id[0].id if state_id else False,
                    'zip':
                    partner['client_zip'],
                    'country_id':
                    country_id.id if country_id else False,
                    'customer':
                    True,
                    'supplier':
                    False,
                    'opt_out':
                    True,
                    'vat':
                    partner['client_vat_id'] if vatnumber.check_vat(
                        partner['client_vat_id']) else False,
                    'type':
                    'invoice',
                    'invoiceplane_import':
                    True,
                }

                partner_id = partner_obj.create(values)
                partner_array.append(partner_id.id)
        return partner_array