def alta_cliente(cliente):
    cliente_id = False
    dbf_cliente = ydbf.open(ruta_dbf + '/Clientes.dbf', encoding='cp1252')
    i=0
    cont=0
    for record in dbf_cliente:
        ccodcli = int(record['CCODCLI'])
        if ccodcli == cliente:
            record['CDNICIF'] = record['CDNICIF'].replace(" ","")
            record['CDNICIF'] = record['CDNICIF'].replace("/","")
            record['CDNICIF'] = record['CDNICIF'].replace("-","")
            vat = check_vat(record['CDNICIF'])
                  
            cuenta = _arreglar_cuenta(record['CSUBCTA'])
                  
            nombre = record['CNOMCLI']
            if len(nombre)>40:
                nombre = nombre[:40]
                      
            cliente_id = _alta_partner_y_direccion(record, vat, nombre)
            account_id = _alta_cuenta_cliente(cliente_id, cuenta, nombre)
            banco_id = _alta_banco(record, cliente_id)
            break
#        else:
#            linea = []
#            linea.append(cliente)
#            num_fac_int=int(num_fac)
#            linea.append(num_fac_int)
#            writer_cliente_no_encontrado.writerow(linea)
    dbf_cliente.close()
    return cliente_id
예제 #2
0
def importar():
    dbf = ydbf.open(os.path.join('dbfs', 'FacCliL.dbf'), encoding='latin-1')
    for row in dbf:

        product_obj = origen.model('product.product')
        product_id = product_obj.browse([('default_code', '=',
                                          row['CREF'].strip())])
        if product_id:
            product_id = product_id[0].id
        else:
            product_id = product_obj.browse([('default_code', '=',
                                              'Facturaplus')])
            if not product_id:
                product = {
                    'name': 'Producto',
                    'default_code': 'Facturaplus',
                    'type': 'product',
                }
                product_id = product_obj.create(product)
            else:
                product_id = product_id[0].id
        # BÚSQUEDA DE CABECERAS DE FACTURAS
        invoice_obj = origen.model('account.invoice')
        invoice_id = invoice_obj.browse([
            ('name', '=', str(row['CSERIE']) + '0' + str(row['NNUMFAC']))
        ])

        if invoice_id:
            invoice_id = invoice_id[0]

        # CREACION DE LINEAS DE FACTURA

        invoice_vals = {
            'name':
            row['CDETALLE'].strip(),
            'invoice_id':
            invoice_id.id,
            'product_id':
            product_id,
            'quantity':
            float(row['NCANENT']),
            'discount':
            float(row['NDTO']),
            'account_id':
            VentasAccount.id,
            'invoice_line_tax_ids':
            [(4, iva21b.id)] if bool(float(row['NIVA'])) else False,
            'price_unit':
            float(row['NPREUNIT']),
            'price_subtotal':
            float(row['NTOTLINEA']),
            'origin':
            str(row['NNUMFAC']),
            'facturaplus':
            True,
        }

        invoice_line_obj = origen.model('account.invoice.line')
        invoice_line_id = invoice_line_obj.create(invoice_vals)
        invoice_id.compute_taxes()
예제 #3
0
def importar():
    dbf = ydbf.open(os.path.join('dbf', 'Articulo.dbf'), encoding='latin-1')
    for row in dbf:

        product = {
            'name': row['CDETALLE'],
            'default_code': row['CREF'],
            'lst_price': float(row['NPVP']),
            'type': 'product'
        }

        product_obj = origen.model(name='product.product')
        product = product_obj.create(product)
예제 #4
0
def importar():
    dbf = ydbf.open(os.path.join('dbf', 'Diario.dbf'), encoding='latin-1')
    antNumero = 0
    apuntes = []
    for row in dbf:
        if antNumero != row['ASIEN']:
            if len(apuntes):
                crearAsiento(apuntes)
            antNumero = row['ASIEN']
            apuntes = []
        apuntes.append(row)

    if len(apuntes):
        crearAsiento(apuntes)
예제 #5
0
파일: dbf2sa.py 프로젝트: Jhougo/Python_API
def dbf2sa(dbf_name, sa_uri):
    """
    Move DBF data (as single table) from file to RDBMS 
    
    Arguments:
        
        ``dbf_name``
            Full path to DBF file, move data from
        
        ``sa_uri``
            SQLAlchemy DB URI, move data to
    """
    reader = ydbf.open(dbf_name)
    meta = make_meta(sa_uri)
    table = make_table(meta, reader)
    push_data(table, convert_data(reader))
예제 #6
0
def dbf2sa(dbf_name, sa_uri):
    """
    Move DBF data (as single table) from file to RDBMS 
    
    Arguments:
        
        ``dbf_name``
            Full path to DBF file, move data from
        
        ``sa_uri``
            SQLAlchemy DB URI, move data to
    """
    reader = ydbf.open(dbf_name)
    meta = make_meta(sa_uri)
    table = make_table(meta, reader)
    push_data(table, convert_data(reader))
예제 #7
0
파일: load_dbf.py 프로젝트: H359/BarboskeRu
 def handle(self, *args, **kwargs):
     #fh = urllib2.urlopen(self.dbf_url)
     #tf = tempfile.NamedTemporaryFile()
     #tf.write(fh.read())
     #fh.close()
     unknown_brand, _ = Brand.objects.get_or_create(title=u'Неизвестный')
     unknown_category, _ = Category.objects.get_or_create(title=u'Неразобранное', parent=None)
     coeff = Entry.get('shop.discount.markup')
     print coeff
     return
     with transaction.commit_on_success():
 	    dbf = ydbf.open(tf, encoding='cp866')
         for record in dbf:
             created = False
             try:
                 variant = Variant.objects.select_related().get(articul=record['COD_ARTIC'])
             except ObjectDoesNotExist, e:
                 ware = Ware.objects.create(
                     enabled=False,
                     title=record['NAME_ARTIC'],
                     category=unknown_category,
                     brand=unknown_brand
                 )
                 variant = Variant()
                 variant.ware = ware
                 variant.articul = record['COD_ARTIC']
                 created = True
                 try:
             	variant.original_title = record['NAME_ARTIC']
                     variant.store_qty = int(record['REZ_KOLCH'])
                     variant.base_price = record['CENA_ARTIC']
                     variant.pack = int(record['EDN_V_UPAK'])
                     variant.units = record['EDIN_IZMER']
                     if variant.fix_price:
                         raise Exception, u'Цена для товара зафиксирована, цена из базы -- %s' % record['CENA_ARTIC']
                     else:
                         variant.price = coeff*variant['base_price']
                     variant.save()
                     if created:
                         raise Exception, u'Создан новый товар и вариант -- %s' % record['NAME_ARTIC']
                 except Exception, e:
                     print unicode(e)
                     ImportIssue.objects.create(
                         variant=variant,
                         description=unicode(e)
                     )
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)
예제 #9
0
    def handle(self, *args, **kwargs):
	main_category, _ = Category.objects.get_or_create(title=u'Магазин', parent=None)
	unknown_brand, _ = Brand.objects.get_or_create(title=u'Неизвестный')
	markup = Entry.get('shop.discount.markup')
	weights_re = re.compile(ur'[ ]+(?P<wght>([0-9]+[,]*[/-xх*]+)*([0-9]+[,]*)+)+[ ]*(%s)+[ ]*' % self.weights, re.U | re.I)
	abbr_re = re.compile(ur'[ ]+д/[ ]*(\S+)', re.U | re.I)
	spaces_re = re.compile(ur'[ ]+', re.U)
	useless_symb_re = re.compile(ur'^[-+*]*[0-9-/]*|\s+(\*[0-9]+)+|НОВИНКА|[ ]+-[ ]+', re.U | re.I)
	brand_re = re.compile(ur'^[*]*\"(?P<brand>[^\"]+)\"', re.U)
	def get_common_name(cluster):
	    spls = map(lambda w: w.split(u' '), map(lambda w: w['NAME_ARTIC'], cluster))
	    min_length = min(map(len, spls))
	    res = []
	    for x in range(min_length):
		default = spls[0][x]
		if reduce(lambda acc, w: acc and (w[x] == default), spls, True):
		    res.append(default)
	    return u' '.join(res)
	def get_distance(a,b):
	    return Levenshtein.distance(a['NAME_ARTIC'].lower(), b['NAME_ARTIC'].lower())
	def transform(record):
	    name = unicode(record['NAME_ARTIC']) #.encode('utf-8')
	    record['ORIGINAL_NAME'] = name
	    subs = weights_re.search(name)
	    if subs is not None:
		record['WEIGHT_ZAM'] = subs.groupdict()['wght']
		name = weights_re.sub(u' ', name)
	    subs = brand_re.search(name)
	    if subs is not None:
		record['BRAND'] = subs.groupdict()['brand']
		name = brand_re.sub(' ', name)
	    name = abbr_re.sub(u' для \\1', name)
	    name = useless_symb_re.sub(' ', name)
	    name = spaces_re.sub(u' ', name)
	    record['NAME_ARTIC'] = name.strip()
	    return record
	with open('/home/zw0rk/Downloads/price_kolc_zoost.dbf', 'rb') as f:
	    dbf = ydbf.open(f, encoding='cp866')
	    clusters = []
	    records = map(transform, dbf)
	    records.sort(key=lambda w: w['NAME_ARTIC'])
	    threshold = 10
	    cur = 0
	    l = len(records)
	    cluster = []
	    for i in range(l):
		distance = get_distance(records[cur], records[i])
		if distance > threshold:
		    clusters.append(cluster)
		    cluster = [records[i]]
		    cur = i
		else:
		    cluster.append(records[i])
	    with transaction.commit_on_success():
		for x in clusters:
		    """
		    for y in x:
			print y['NAME_ARTIC'].encode('utf-8'), ' ||| ',  y['ORIGINAL_NAME'].encode('utf-8')
		    print '-'*80
		    """
		    brand, _ = Brand.objects.get_or_create(title=x[0].get('BRAND', u'Неизвестный'))
		    ware = Ware.objects.create(title=get_common_name(x), category=main_category, brand=brand)
		    for y in x:
			Variant.objects.create(
			    price=(1+Decimal(markup/100.0))*y['CENA_ARTIC'],
			    articul=y['COD_ARTIC'],
			    ware=ware,
			    title=y['NAME_ARTIC'],
			    base_price=y['CENA_ARTIC'],
			    pack=y['EDN_V_UPAK'],
			    units=y['EDIN_IZMER'],
			    weight=y.get('WEIGHT_ZAM', ''),
			    original_title=y['ORIGINAL_NAME']
			)
예제 #10
0
b = os.system("cp /mnt/conta/CON2012/EmpAF/*.dbf /home/ddiz/workspace/openerp/trunk/oerp/addons/prevencontrol_import/data/dbf/")
print b
c = os.system("cp /mnt/conta/GES2012/DBF03/*.dbf /home/ddiz/workspace/openerp/trunk/oerp/addons/prevencontrol_import/data/dbf/")
print c

os.chdir(ruta_dbf)
lista_dbf = glob.glob("*.dbf")
print "lista de ficheros:   %s"%lista_dbf
os.chdir(ruta_script_actual)

for f in lista_dbf:
#    if f == "dCarta.dbf" or f == "pygpnor.dbf" or f == "DTalon.dbf" or f == "Importar.dbf" or f == "DCarta.dbf":
    if (f != "Facclit.dbf") and (f != "Facclil.dbf") and (f != "Facclib.dbf") and (f != "Clientes.dbf") and (f != "Agentes.dbf") and (f != "Albclil.dbf") and (f != "Albclib.dbf") and (f != "Albclit.dbf") and (f != "Articulo.dbf") and (f != "BancosCl.dbf") and (f != "Claves.dbf") and (f != "Diario.dbf") and (f != "Dircli.dbf") and (f != "Familias.dbf") and (f != "Fpago.dbf") and (f != "Pedclit.dbf") and (f != "Preclit.dbf") and (f != "RatSit.dbf") and (f != "Recibos.dbf") and (f != "Rutas.dbf") and (f != "SCtaB.dbf") and (f != "Stocks.dbf") and (f != "SubCta.dbf") and (f != "Subnic.dbf") and (f != "Agentes.dbf") and (f != "Cta_Rem.dbf") and (f != "Liquidl.dbf") and (f != "Liquidt.dbf"):
        continue
    print "Convirtiendo:   %s"%f
    dbf_f = ydbf.open(ruta_dbf + '/' + f, encoding='cp1252')
    f_mod = f[:-4]
    csv_f = open(ruta_dbf2csv + '/' + f_mod + '.csv', 'wb')
    writer_f = csv.writer(csv_f, dialect='nuevo_dialecto')
    i=0
    contt=0
    for record in dbf_f:
        contt+=1
        print "linea del archivo numero::   %s"%contt
        cabecera=[]
        if i==0:
            j=0
            for key,value in record.iteritems():
                cabecera.append("valor")
                cabecera[j]=key
                j+=1
예제 #11
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)
예제 #12
0
파일: gendbf.py 프로젝트: Jhougo/Python_API
def gendbf(filename, number_of_records=2000, fields_number=20):
    fh = open(filename, 'wb')
    fields = get_fields_structure(fields_number)
    dbf = ydbf.open(filename, 'w', fields, encoding='cp1251')
    dbf.write(get_data(fields, number_of_records))
    dbf.close()
	def parse_ydbf(fp, *args, **kwargs):

		if not hasattr(fp, 'read'):
			fp = StringIO(fp)

		return ydbf.open(fp, *args, **kwargs)
예제 #14
0
파일: importer.py 프로젝트: s9gf4ult/dbfxml
    def processTable(self, table_name):
        """processes table table_name if any file is assigned to it"""
        if self.sq_connection.execute("select * from processed_files where table_name = '{0}'".format(table_name)).fetchall() == [] :
            raise Exception("there is no files attached to table {0}".format(table_name))
        files_list = map(lambda a: a[0], self.sq_connection.execute("select full_path from processed_files where table_name = '{0}' and processed = 0".format(table_name)).fetchall())
        if files_list == []:
            log.log("no one file assigned to table {0}".format(table_name))
        if not sql_helpers.isTableAre(self.sq_connection, table_name):
            #таблицы еще нет в базе - создаем, узнаем типы и имена полей из дбф файлов, проверяем соответствия полей типам 
            for filename in files_list:
                log.log("reading structure of {0}".format(filename))
                dbfcon = ydbf.open(filename, encoding = self.encoding)
                if not vars().has_key("fields"): # если еще не поеределили переменную
                    fields = {} # тут храним имена и типы полей, которые будем создавать
                    for field in dbfcon.fields:
                        fields[field[0]] = [field[1], field[3]]
                else: # переменная уже определена, если встретятся поля с другим типом - выбросим исключение
                    for field in dbfcon.fields:
                        if fields.has_key(field[0]):
                            if fields[field[0]] != [field[1], field[3]]:
                                raise Exception("file {file} has field {field} with type {type1}, another fields in another files has type {type2}".format(file = filename, field = field[0], type1 = field[1], type2 = fields[field[0]]))
                        else:
                            fields[field[0]] = [field[1], field[3]]
                dbfcon.close()
            # теперь надо создать таблицу в базе
            def mapdatatype(a):         # отображение типов из dbf в типы sqlite3
                if a[0] == 'C':
                    return "text"
                elif a[0] == 'D':
                    return "date"
                elif a[0] == 'N' and a[1]:
                    return "decimal"
                elif a[0] == 'N' and not a[1]:
                    return "integer"
                elif a == 'L':
                    return "bool"
                else:
                    raise Exception("can not create field with type {0}".format(a))

            for field in fields:
                fields[field] = mapdatatype(fields[field])
            sql_helpers.makeTableIfNotExists(self.sq_connection, table_name, fields)
            sql_helpers.makeTableIfNotExists(self.sq_connection, "file_assigns", {"file_id" : "integer", "record_id": "integer"}, ["foreign key (file_id) references processed_files(id) on delete cascade", "unique(file_id, record_id)"])
        #таблица существует - заносим в нее данные из файлов
        table_id = sql_helpers.getIdForTable(self.sq_connection, table_name)
        assign_id = sql_helpers.getIdForTable(self.sq_connection, "file_assigns")
        
        try:
            for file_tuple in self.sq_connection.execute("select id, full_path from processed_files where table_name = '{0}' and processed = 0".format(table_name)).fetchall():
                log.log("inserting records from {0}".format(file_tuple[1]))
                for rec in ydbf.open(file_tuple[1], encoding = self.encoding):
                    rec["id"] = table_id
                    sql_helpers.insertInto(self.sq_connection, table_name, rec)
                    sql_helpers.insertInto(self.sq_connection, "file_assigns", {"id" : assign_id, "file_id" : file_tuple[0], "record_id" : table_id})
                    table_id += 1
                    assign_id += 1
                self.sq_connection.execute("update processed_files set processed = 1 where id = {0}".format(file_tuple[0]))
        except:
            self.sq_connection.rollback()
            raise
        else:
            self.sq_connection.commit()
예제 #15
0
def alta_factura(factura):
    num_fac = int(factura[0])
    fecha = factura[1]
    agente = factura[2]
    comision = factura[3]
    base = factura[4]
    total_iva = factura[5]
    total = factura[6]
    imp_comision = factura[7]
    cliente = int(factura[8])
    tipo_fac = factura[9]
    fecha_vencimiento = factura[10]
    tipo_pago = factura[11]
    cliente_nombre = factura[12]
    cliente_cif = factura[13]
          
    if tipo_fac == "C":
        type = 'out_refund'
        journal_id = 6
    else:
        type = 'out_invoice'
        journal_id = 4
              
    cliente_args = [('ref', '=', cliente)]
    cliente_ids = oerp.execute('res.partner', 'search', cliente_args)
    if cliente_ids:
        cliente_id = cliente_ids[0]
    else:
        comment = "El código de cliente en Facturaplus era: "+str(cliente)
        cliente_args2 = [('comment', '=', comment)]
        cliente_ids = oerp.execute('res.partner', 'search', cliente_args2)
        if cliente_ids:
            cliente_id = cliente_ids[0]
        else:
            cliente_args2 = [('vat', '=', cliente_cif)]
            cliente_ids = oerp.execute('res.partner', 'search', cliente_args2)
            if cliente_ids:
                cliente_id = cliente_ids[0]
            else:
                cliente_args2 = [('name', '=', cliente_nombre)]
                cliente_ids = oerp.execute('res.partner', 'search', cliente_args2)
                if cliente_ids:
                    cliente_id = cliente_ids[0]
                else:
                    cliente_id = alta_cliente(cliente)
          
    address_args = [('partner_id', '=', cliente_id)]
    address_ids = oerp.execute('res.partner.address', 'search', address_args)
    if address_ids:
        address_id = address_ids[0]
    else:
        linea = []
        linea.append(cliente)
        num_fac_int=int(num_fac)
        linea.append(num_fac_int)
        writer_direcccion_no_encontrada.writerow(linea)
        return False
      
    csv_agentes = open(ruta_dbf2csv + '/Agentes.csv', 'rb')
    reader_agentes = csv.reader(csv_agentes, dialect='nuevo_dialecto')
    ag = 0
    j = 0
    for agente_csv in reader_agentes:
        if j==0:
            j+=1
            continue
        else:
            j+=1
            agente = int(agente)
            a_csv = agente_csv[0]
            a_csv = int(a_csv)
            if a_csv==agente:
                agente_nombre = agente_csv[2]
                agent_args = [('name', '=', agente_nombre)]
                agent_ids = oerp.execute('sale.agent', 'search', agent_args)
                if agent_ids:
                    agent_id = agent_ids[0]
                    ag = 1
                    break
    prov = 1570
    if ag==0:
        ccodagente = int(agente)
        dbf_agente = ydbf.open(ruta_dbf + '/Agentes.dbf', encoding='cp1252')
        find = 0
        for record in dbf_agente:
            record['CCODAGE'] = int(record['CCODAGE'])
            if record['CCODAGE'] == ccodagente:
                find = 1            
                print "        agente encontrado en el dbf"
                agent_id = _altas_agent(record, prov)         
                break    
        if find == 0:
            print "        no se ha encontrado en el dbf el agente:  %s"%ccodagente
#            linea = []
#            linea.append(ccodagente)
#            writer_restos2.writerow(linea)
#            continue
        dbf_agente.close()
              
        linea = []
        linea.append(agente)
        writer_agent_no_encontrado.writerow(linea)
          
    payment_term_args = [('name', '=', "180 días")]
    payment_term_ids = oerp.execute('account.payment.term', 'search', payment_term_args)
          
    if not payment_term_ids:
        term = {
            'active': True,
            'note': "180 días",
            'name': "180 días",
            }
        p_term = oerp.execute('account.payment.term', 'create', term)
        term_line = {
                'payment_id': p_term,
                'name': "180 días",
                'sequence': 5,
                'days2': 0,
                'days': 180,
                'value': "balance",
                }
        p_term_line = oerp.execute('account.payment.term.line', 'create', term_line)
          
    acc = oerp.execute('res.partner', 'read', cliente_id, ['property_account_receivable'])
    account_id = acc['property_account_receivable'][0]
    comision
    fecha_p = time.strptime( fecha , '%Y-%m-%d')
    mes = fecha_p.tm_mon
    if mes==1:
        period_id=4
    elif mes==2:
        period_id=5
    elif mes==3:
        period_id=6
    elif mes==4:
         period_id=7
    elif mes==5:
         period_id=8
    elif mes==6:
         period_id=9
    elif mes==7:
         period_id=10
    elif mes==8:
         period_id=11
    elif mes==9:
         period_id=12
    elif mes==10:
         period_id=13
    elif mes==11:
         period_id=14
    elif mes==12:
         period_id=15
      
    if tipo_pago in ("0", "1", "CO"):
        payment_type = 6
        payment_term =  2
    elif tipo_pago=="2":
        payment_type = 1
        payment_term =  3
    elif tipo_pago=="34":
        payment_type = 1
        payment_term =  8
    elif tipo_pago=="8":
        payment_type = 1
        payment_term =  4
    elif tipo_pago=="15":
        payment_type = 1
        payment_term =  2
    elif tipo_pago=="18":
        payment_type = 1
        payment_term =  5
    elif tipo_pago=="29":
        payment_type = 1
        payment_term =  10
    elif tipo_pago=="10":
        payment_type = 4
        payment_term =  3
    elif tipo_pago=="13":
        payment_type = 4
        payment_term =  5
    elif tipo_pago=="11":
        payment_type = 3
        payment_term =  3
    elif tipo_pago=="22":
        payment_type = 3
        payment_term =  2
    elif tipo_pago=="14":
        payment_type = 3
        payment_term =  5
    elif tipo_pago=="16":
        payment_type = 3
        payment_term =  4
    elif tipo_pago=="19":
        payment_type = 6
        payment_term =  3
    elif tipo_pago=="12":
        payment_type = 2
        payment_term =  2
    elif tipo_pago=="17":
        payment_type = 2
        payment_term =  5
    elif tipo_pago=="20":
        payment_type = 2
        payment_term =  3
    elif tipo_pago=="21":
        payment_type = 2
        payment_term =  3
    elif tipo_pago=="23":
        payment_type = 2
        payment_term =  4
    elif tipo_pago=="24":
        payment_type = 2
        payment_term =  2
    elif tipo_pago=="26":
        payment_type = 2
        payment_term =  10
    elif tipo_pago=="31":
        payment_type = 2
        payment_term =  5
    elif tipo_pago=="33":
        payment_type = 2
        payment_term =  9
    elif tipo_pago=="30":
        payment_type = 2
        payment_term = 11
    else:
        #######################   alta de la forma de pago   ##################################################
        linea = []
        linea.append(tipo_pago)
        writer_fpago_no_encontrada.writerow(linea)
        return False
          
    factura = {
        'type': type,
        'operation_key': "Nothing",
        'number_tickets': 0,
        'company_id': 2,
        'currency_id': 1,
        'state': "draft",
        'partner_id': cliente_id,
        'address_invoice_id': address_id,
        'address_contact_id': address_id,
        'journal_id': journal_id,
        'account_id': account_id,
        'agent_id': agent_id,
        'date_invoice': fecha,
        'period_id': period_id,
#             'date_due': fecha_vencimiento,
        'payment_term': payment_term,
        'payment_type': payment_type,
        'name': num_fac,
    }
    factura_id = oerp.execute('account.invoice', 'create', factura)
    print "se creó la factura_id:  %s"%factura_id
    return factura_id
예제 #16
0
def importar():
    dbf = ydbf.open(os.path.join('dbf', 'FacCliL.dbf'), encoding='latin-1')
    for row in dbf:

        product_obj = origen.model('product.product')
        product_id = product_obj.browse([('default_code', '=',
                                          row['CREF'].strip())])
        if product_id:
            product_id = product_id[0].id
        else:
            product_id = product_obj.browse([('default_code', '=',
                                              'Facturaplus')])
            if not product_id:
                product = {
                    'name': 'Producto',
                    'default_code': 'Facturaplus',
                    'type': 'product'
                }
                product_id = product_obj.create(product)
            else:
                product_id = product_id[0].id
        # BÚSQUEDA DE CABECERAS DE FACTURAS
        invoice_obj = origen.model('account.invoice')
        invoice_id = invoice_obj.browse([('name', '=', str(row['NNUMFAC']))])

        # CREACION DE FACTURAS RECTIFICATIVAS
        if row['NPREUNIT'] < 0:
            invoice_rect_vals = {
                'name': 'Rectificativa - ' + invoice_id[0].name,
                'account_id': invoice_id[0].account_id.id,
                'partner_id': invoice_id[0].partner_id.id,
                'date_invoice': invoice_id[0].date_invoice,
                'type': 'out_refund'
            }

            invoice_refund_id = invoice_obj.create(invoice_rect_vals)
            invoice_id.write(
                {'refund_invoice_ids': [(4, invoice_refund_id.id)]})

            invoice_ref_vals = {
                'name':
                row['CDETALLE'].strip(),
                'invoice_id':
                invoice_refund_id.id,
                'product_id':
                product_id,
                'quantity':
                float(row['NCANENT']),
                'discount':
                float(row['NDTO']),
                'account_id':
                VentasAccount.id,
                'invoice_line_tax_ids':
                [(4, iva21b.id)] if bool(float(row['NIVA'])) else False,
                'price_unit':
                abs(float(row['NPREUNIT'])),
                'price_subtotal':
                abs(float(row['NTOTLINEA'])),
                'origin':
                'Rectificativa - ' + str(row['NNUMFAC']),
            }

            invoice_line_obj = origen.model('account.invoice.line')
            invoice_line_id = invoice_line_obj.create(invoice_ref_vals)
            invoice_refund_id.compute_taxes()
            continue

        if invoice_id:
            invoice_id = invoice_id[0]

        # CREACION DE LINEAS DE FACTURA

        invoice_vals = {
            'name':
            row['CDETALLE'].strip(),
            'invoice_id':
            invoice_id.id,
            'product_id':
            product_id,
            'quantity':
            float(row['NCANENT']),
            'discount':
            float(row['NDTO']),
            'account_id':
            VentasAccount.id,
            'invoice_line_tax_ids':
            [(4, iva21b.id)] if bool(float(row['NIVA'])) else False,
            'price_unit':
            float(row['NPREUNIT']),
            'price_subtotal':
            float(row['NTOTLINEA']),
            'origin':
            str(row['NNUMFAC']),
        }

        invoice_line_obj = origen.model('account.invoice.line')
        invoice_line_id = invoice_line_obj.create(invoice_vals)
        invoice_id.compute_taxes()