def crear_company(config, lang): """ Crear company. Traer datos de AFIP""" Currency = Model.get('currency.currency') Company = Model.get('company.company') Party = Model.get('party.party') # crear company # obtener nombre de la compania de un archivo. print u'\n>>> creando company...' import ConfigParser ini_config = ConfigParser.ConfigParser() ini_config.read('company.ini') currencies = Currency.find([('code', '=', 'ARS')]) currency, = currencies company_config = Wizard('company.company.config') company_config.execute('company') company = company_config.form party = Party(name='NOMBRE COMPANY') party.lang = lang party.vat_country = 'AR' try: party.vat_number = ini_config.get('company', 'cuit') party.iva_condition = ini_config.get('company', 'iva_condition') except Exception,e: print 'Error: No se ha configurado correctamente company.ini\n' raise SystemExit(repr(e))
def import_sheetmetal_products(): # assumes you got a Product Template called "Blechteil" # which will be the template for all of these Prod = Model.get('product.product') ProdTpl = Model.get('product.template') ptBlech = ProdTpl.find([('name', '=', 'Blechteil')])[0] #data from SQL DB BLV: # SELECT mat.name, min(s.thickness), max(s.thickness) FROM blv_sheet AS s INNER JOIN blv_material mat ON s.material_id = mat.id WHERE mat.parent_id NOT IN (9,10,114) AND mat.name NOT LIKE 'Tischpl%'AND mat.name NOT LIKE 'Hartf%' AND mat.name NOT LIKE 'PE Pl%' AND mat.name NOT LIKE 'Pert%' GROUP BY mat.name ORDER BY mat.name ; # with manual adjustments to outputbased on personal knowledge data_fname = 'blv_2021_04_05_minmax_mat.csv' with codecs.open(data_fname, 'r', ENCODING) as fp: reader = csv.reader(fp) headers = next(reader) log(f'{headers}') for row in reader: for thick in thicknesses: if thick >= float(row[1]) and thick <= float(row[2]): #ignore thicknesses outside min, max for values matnam = row[0].strip() + f' - {thick:.2f} mm'.replace( '.', ',') log(matnam) np = Prod() np.suffix_code = matnam np.material = row[0].strip() np.sheet_thickness = thick np.template = ptBlech try: np.save() except Exception as e: log(f'Error saving {matnam} {thick}: {e}')
def crear_account_invoice_ar_pos(config, lang): """ Crear Punto de Venta Electronico con Factura A, B y C """ print u'\n>>> Comienza creacion de POS Electronico para Facturas A, B y C' Company = Model.get('company.company') Pos = Model.get('account.pos') PosSequence = Model.get('account.pos.sequence') company, = Company.find([]) punto_de_venta = Pos() punto_de_venta.pos_type = 'electronic' punto_de_venta.number = 2 punto_de_venta.pyafipws_electronic_invoice_service = 'wsfe' punto_de_venta.save() facturas = { '1': '01-Factura A', '6': '06-Factura B', '11': '11-Factura C' } for key, name in facturas.iteritems(): print u'\n>>> Creamos POS para '+name pos_sequence = PosSequence() pos_sequence.invoice_type = key pos_sequence.invoice_sequence = _crear_seq(config, name, company) pos_sequence.pos = punto_de_venta pos_sequence.save()
def create_test_task(log_file): get_tryton_connection() settings = get_config() tryton = settings['tryton'] Project = Model.get('project.work') Employee = Model.get('company.employee') Party = Model.get('party.party') Tracker = Model.get('project.work.tracker') employee = Employee(int(tryton.get('default_employee_id'))) parent = Project(int(tryton.get('default_project_id'))) party = Party(int(tryton.get('default_party_id'))) tracker = Tracker(int(tryton.get('default_tracker_id'))) f = open(log_file, 'r') lines = [] for line in f.readlines(): if 'init' in line or 'modules' in line: continue lines.append(line) f.close() work = Project() work.type = 'task' work.product = None work.timesheet_work_name = 'Test Exception' work.parent = parent work.tracker = tracker work.party = party work.problem = "\n".join(lines) work.assigned_employee = employee work.save()
def create_fiscalyear(company=None, today=None, config=None): """Create a fiscal year for the company on today""" FiscalYear = Model.get('account.fiscalyear', config=config) Sequence = Model.get('ir.sequence', config=config) SequenceStrict = Model.get('ir.sequence.strict', config=config) if not company: company = get_company() if not today: today = datetime.date.today() existing_fy = FiscalYear.find([('name', '=', str(today.year))], limit=1) if existing_fy: print("Warning: Fiscal year " + str(today.year) + " already exists!") return existing_fy[0] fiscalyear = FiscalYear(name=str(today.year)) fiscalyear.start_date = today + relativedelta(month=1, day=1) fiscalyear.end_date = today + relativedelta(month=12, day=31) fiscalyear.company = company fiscalyear.account_stock_method = ACCOUNT_STOCK_METHOD post_move_sequence = Sequence(name=POST_MOVE_SEQ, code='account.move', number_next=10000, company=company) customer_invoice_sequence = SequenceStrict(name=CUSTOMER_INVOICE_SEQ, code='account.invoice', number_next=200000, company=company) customer_credit_note_sequence = SequenceStrict( name=CUSTOMER_CREDIT_NOTE_SEQ, code='account.invoice', number_next=100000, company=company) supplier_invoice_sequence = SequenceStrict(name=SUPPLIER_INVOICE_SEQ, code='account.invoice', number_next=600000, company=company) supplier_credit_note_sequence = SequenceStrict( name=SUPPLIER_CREDIT_NOTE_SEQ, code='account.invoice', number_next=500000, company=company) post_move_sequence.save() customer_invoice_sequence.save() customer_credit_note_sequence.save() supplier_invoice_sequence.save() supplier_credit_note_sequence.save() fiscalyear.post_move_sequence = post_move_sequence fiscalyear.out_invoice_sequence = customer_invoice_sequence fiscalyear.out_credit_note_sequence = customer_credit_note_sequence fiscalyear.in_invoice_sequence = supplier_invoice_sequence fiscalyear.in_credit_note_sequence = supplier_credit_note_sequence fiscalyear.save() fiscalyear.click('create_period') period = fiscalyear.periods[0] print("Success: Fiscal year " + str(today.year) + "' created!") return fiscalyear
def create_fiscalyear(company=None, today=None, config=None): "Create a fiscal year for the company on today" FiscalYear = Model.get('account.fiscalyear', config=config) Sequence = Model.get('ir.sequence', config=config) SequenceType = Model.get('ir.sequence.type', config=config) if not company: company = get_company(config=config) if not today: today = datetime.date.today() fiscalyear = FiscalYear(name=str(today.year)) fiscalyear.start_date = today + relativedelta(month=1, day=1) fiscalyear.end_date = today + relativedelta(month=12, day=31) fiscalyear.company = company sequence_type, = SequenceType.find([('name', '=', "Account Move")], limit=1) post_move_sequence = Sequence(name=str(today.year), sequence_type=sequence_type, company=company) post_move_sequence.save() fiscalyear.post_move_sequence = post_move_sequence return fiscalyear
def merge_review(ctx, work, review_id=None, message=None): get_tryton_connection() Review = Model.get('project.work.codereview') Task = Model.get('project.work') tasks = Task.find([('code', '=', work)]) if not tasks: print(t.red('Error: Task %s was not found.' % work), file=sys.stderr) sys.exit(1) w = tasks[0] reviews = Review.find([('work', '=', w.id), ('state', '=', 'opened')]) for review in reviews: if review_id and str(review.id) != review_id: print(review_id, review.id) continue show_review(review) if not review_id: continue confirm = choice.Binary('Are you sure you want to merge?', False).ask() if confirm: owner, repo, request_id = get_request_info(review.url) res = pullrequests.merge(owner, repo, request_id, message) if res and res['state'] == 'MERGED': review.state = 'closed' review.save()
def loadCustomers(): f = open(sys.argv[2], 'rb') countrycode = sys.argv[3] if countrycode is None: print "Please provide a country code. e.g. 'CH'" try: reader = csv.DictReader(f) Lang = Model.get('ir.lang') (en,) = Lang.find([('code', '=', 'en_US')]) Country = Model.get('country.country') (ch, ) = Country.find([('code', '=', countrycode)]) for row in reader: print(row['first_name'], row['last_name'], row['company_name']) Party = Model.get('party.party') party = Party() if party.id < 0: party.name = row['company_name'] party.lang = en party.addresses[0].name = row['first_name']+' '+row['last_name'] party.addresses[0].street = row['address'] party.addresses[0].streetbis = None party.addresses[0].zip = row['zip'] party.addresses[0].city = row['city'] party.addresses[0].country = ch # party.addresses[0].subdivision = row['state'] party.addresses[0].invoice = True party.addresses[0].delivery = True party.save() finally: f.close()
def test_default_set(self): User = Model.get('res.user') Group = Model.get('res.group') group_ids = [x.id for x in Group.find()] test = User() test._default_set({ 'name': 'Test', 'groups': group_ids, }) self.assertEqual(test.name, 'Test') self.assertEqual([x.id for x in test.groups], group_ids) test = User() test._default_set({ 'name': 'Test', 'groups': [ { 'name': 'Group 1', }, { 'name': 'Group 2', }, ], }) self.assertEqual(test.name, 'Test') self.assertEqual([x.name for x in test.groups], ['Group 1', 'Group 2'])
def setup_purchase(config, modules, company, suppliers): Purchase = Model.get('purchase.purchase') Product = Model.get('product.product') all_products = Product.find([ ('purchasable', '=', True), ]) purchase_date = TODAY - relativedelta(days=60) while purchase_date <= TODAY + relativedelta(days=20): supplier = random.choice(suppliers) purchase = Purchase() purchase.party = supplier purchase.purchase_date = purchase_date products = random.sample(all_products, random.randint(1, 15)) for product in products: purchase_line = purchase.lines.new() purchase_line.product = product purchase_line.quantity = random.randint(20, 100) purchase.save() threshold = 2. / 3. if random.random() <= threshold: purchase.click('quote') if random.random() <= threshold: purchase.click('confirm') purchase.click('process') elif random.choice([True, False]): purchase.click('cancel') purchase_date += relativedelta(days=random.randint(5, 10))
def LoadUserEmployee(): User = Model.get('res.user') Employe = Model.get('company.employee') users = csv.reader(open('usuarios.csv', 'r')) header=True inicio=1 user = User() if (inicio == 1): inicio = 2 for i in range(inicio - 1): users.next() for index,row in enumerate(users): usuario = row[0] empleado = row[0] empresa = row[3] users = User.find([('name','=', usuario)]) employees = Employe.find([('party.name','=',empleado)]) if len(Employe.find([('party.name', '=', empleado)])) == 1: employee, = Employe.find([('party.name','=',empleado)]) if len(Company.find([('party.vat_number', '=', empresa)])) == 1: company, = Company.find([('party.vat_number','=',empresa)]) for user in users: user.employees.append(employees[0]) user.employee = employee user.save()
def create_entity(values): if not values.get("model"): print "Falta el modelo. Que estamos haciendo??" return None if (values.get("id") is None): print "Falta el id. Que estamos haciendo??" return None model = values.pop("model") _id = values.pop("id") print "Creando la entidad %s para el registro numero %s" % (model, _id) #Contructor del modelo const = Model.get(model) entity = const() save_for_last = [] for k,v in values.iteritems(): if (isinstance(v, tuple)): ref = Model.get(v[0]).find(v[1])[0] setattr(entity, k, ref) elif (isinstance(v, list)): constructor = Model.get(v[0]) to_save = [] for elem in v[1]: to_save.append(constructor.find([elem])[0]) save_for_last.append((k, to_save)) else: setattr(entity, k, v) for i in save_for_last: getattr(entity, i[0]).extend(i[1]) entity.save() return entity
def setup_timesheet(config, activated, company): Work = Model.get('timesheet.work') Employee = Model.get('company.employee') Line = Model.get('timesheet.line') for name in ['Marketing', 'Accounting', 'Secretary']: work = Work(name=name) work.save() employees = Employee.find([('company', '=', company.id)]) works = Work.find([]) date = TODAY + relativedelta(months=-1) day = datetime.timedelta(hours=8) while date <= TODAY: if date.weekday() < 5: for employee in employees: total = datetime.timedelta() while total < day: if random.random() > 0.8: break line = Line(employee=employee, date=date) line.work = random.choice(works) duration = datetime.timedelta(hours=random.randint(1, 8)) line.duration = min(duration, day - total) line.save() date += datetime.timedelta(days=1)
def account_reconcile(database, lines=2, months=6, config_file=os.environ.get('TRYTOND_CONFIG')): pref = config.set_trytond(database=database, config_file=config_file) Module = Model.get('ir.module.module') Company = Model.get('company.company') modules = Module.find([ ('name', '=', 'account_reconcile'), ]) if not modules: print t.bold('Module account_reconcile not found') return reconcile, = modules if reconcile.state != 'installed': Module.install([reconcile.id], pref.context) Wizard('ir.module.module.install_upgrade').execute('upgrade') for company in Company.find([]): print t.bold('Start reconcile for company %s (Lines %s, Months %s)' % (company.rec_name, lines, months)) with pref.set_context({'company': company.id}): reconcile = Wizard('account.move_reconcile') reconcile.form.max_lines = str(lines) reconcile.form.max_months = months reconcile.form.start_date = None reconcile.form.end_date = None reconcile.execute('reconcile')
def crear_inmuebles(): Address = Model.get("party.address") address = Address.find([]) for item in address: print item.street new_inmueble = Model.get('sigcoop_inmueble.inmueble')() if len(item.street)==0: new_inmueble.calle_dom = 'SIN DATOS' else: new_inmueble.calle_dom = item.street if len(item.streetbis)==0: new_inmueble.numero_dom = '0' else: new_inmueble.numero_dom = item.streetbis new_inmueble.localidad_dom = 'PUAN' new_inmueble.partido_dom = 'PUAN' new_inmueble.cp_dom = '8180' new_inmueble.save() inmuebleid = new_inmueble.id #crea la relacion con party crear_relacion_titular(inmuebleid, item.party.id)
def testpayment(): config.set_trytond(DATABASE_NAME, config_file=CONFIG) Sale = Model.get('sale.sale') saleid = 15 payment_gross = 55.00 saleList = Sale.find(['id', '=', saleid]) if saleList is not None: check_order = True if (saleList[0].state != 'draft'): check_order = False if (saleList[0].currency.symbol != 'CHF'): check_order = False SaleLine = Model.get('sale.line') saleLine = SaleLine.find(['sale', '=', saleid]) saleTotal = Decimal(0.00) for n in saleLine: saleTotal += n.unit_price * Decimal(n.quantity) if (Decimal(payment_gross) < saleTotal): check_order = False if check_order: # change sale state to 'confirmed' saleList[0].comment += 'PAYPAL IPN DATA\n'+'\n' saleList[0].save() saleList[0].click('quote') else: # add note that something failed in payment saleList[0].comment = 'ERROR WITH PAYPAL IPN DATA\n'+'\n' saleList[0].save()
def create_chart(company=None, config=None): "Create chart of accounts" AccountTemplate = Model.get('account.account.template', config=config) ModelData = Model.get('ir.model.data') if not company: company = get_company() data, = ModelData.find([ ('module', '=', 'account'), ('fs_id', '=', 'account_template_root_en'), ], limit=1) account_template = AccountTemplate(data.db_id) create_chart = Wizard('account.create_chart') create_chart.execute('account') create_chart.form.account_template = account_template create_chart.form.company = company create_chart.execute('create_account') accounts = get_accounts(company, config=config) create_chart.form.account_receivable = accounts['receivable'] create_chart.form.account_payable = accounts['payable'] create_chart.execute('create_properties') return create_chart
def test_on_change_set(self): User = Model.get('res.user') Group = Model.get('res.group') test = User() test._on_change_set('name', 'Test') self.assertEqual(test.name, 'Test') group_ids = [x.id for x in Group.find()] test._on_change_set('groups', group_ids) self.assertEqual([x.id for x in test.groups], group_ids) test._on_change_set('groups', {'remove': [group_ids[0]]}) self.assertEqual([x.id for x in test.groups], group_ids[1:]) test._on_change_set('groups', {'add': [(-1, { 'name': 'Bar', })]}) self.assert_([x for x in test.groups if x.name == 'Bar']) test.groups.extend(Group.find()) group = test.groups[0] test._on_change_set('groups', {'update': [{ 'id': group.id, 'name': 'Foo', }]}) self.assert_([x for x in test.groups if x.name == 'Foo'])
def create_pos(company=None, config=None): "Create a Point of Sale" Pos = Model.get('account.pos', config=config) Sequence = Model.get('ir.sequence', config=config) if not company: company = get_company() pos = Pos( company=company.id, number=1, pos_type='manual', ) for attr, name in (('1', '01-Factura A'), ('2', '02-Nota de Debito A'), ('3', '03-Nota de Credito A'), ('6', '06-Factura B'), ('7', '07-Nota de Debito B'), ('8', '08-Nota de Credito B'), ('11', '11-Factura C'), ('12', '12-Nota de Debito C'), ('13', '13-Nota de Credito C')): sequence = Sequence(name='%s %s' % (name, 'manual'), code='account.invoice', company=company) sequence.save() pos.pos_sequences.new( invoice_type=attr, invoice_sequence=sequence, ) pos.save() return pos
def upgrade_modules(config, modules=None, all=False): ''' Function get from tryton_demo.py in tryton-tools repo: http://hg.tryton.org/tryton-tools ''' assert all or modules Module = Model.get('ir.module.module') if all: modules = Module.find([ ('state', '=', 'installed'), ]) else: modules = Module.find([ ('name', 'in', modules), ('state', '=', 'installed'), ]) Module.upgrade([x.id for x in modules], config.context) Wizard('ir.module.module.install_upgrade').execute('upgrade') ConfigWizardItem = Model.get('ir.module.module.config_wizard.item') for item in ConfigWizardItem.find([('state', '!=', 'done')]): item.state = 'done' item.save() upgraded_modules = [ x.name for x in Module.find([ ('state', '=', 'to_upgrade'), ]) ] return upgraded_modules
def LoadPlanNIIF(): AccountC = Model.get('account.create_chart.account') Company = Model.get('company.company') empresa = '1191758435001' Template = Model.get('account.account.template') Account = Model.get('account.account') account = Account() account_template = Template.find([('name', '=', 'PLAN DE CUENTAS NIIF ECUADOR'), ('parent', '=', None)]) if len(account_template) == 1: account_t, = account_template account_template = account_t if len(Company.find([('party.vat_number', '=', empresa)])) == 1: company, = Company.find([('party.vat_number', '=', empresa)]) company = company create_chart = Wizard('account.create_chart') create_chart.execute('account') create_chart.form.account_template = account_template create_chart.form.company = company create_chart.execute('create_account') print "Created chart account"
def install_modules(): print u'\n>>> instalando modulos...' Module = Model.get('ir.module.module') modules_to_install=[ 'account_ar', 'account_voucher_ar', 'account_check_ar', 'account_bank_ar', 'account_retencion_ar', 'account_coop_ar', 'company_logo', 'account_invoice_ar', ] modules = Module.find([ ('name', 'in', modules_to_install), ]) for module in modules: module.click('install') Wizard('ir.module.module.install_upgrade').execute('upgrade') print u'\n>>> wizards de configuracion se marcan como done...' ConfigWizardItem = Model.get('ir.module.module.config_wizard.item') for item in ConfigWizardItem.find([('state', '!=', 'done')]): item.state = 'done' item.save()
def _create_default_entry_control(company=None, today=None, config=None): "Create default entry control" Entry = Model.get('lims.entry', config=config) InvoiceContact = Model.get('lims.entry.invoice_contacts', config=config) ReportContact = Model.get('lims.entry.report_contacts', config=config) AcknowledgmentContact = Model.get('lims.entry.acknowledgment_contacts', config=config) default_entry_control = Entry() default_entry_control.date = datetime.datetime.combine( today, datetime.time.min) default_entry_control.party = company.party default_entry_control.invoice_party = company.party # Set party contacts contact = _create_company_contacts(company, config) invoice_contact = InvoiceContact() default_entry_control.invoice_contacts.append(invoice_contact) invoice_contact.contact = contact report_contact = ReportContact() default_entry_control.report_contacts.append(report_contact) report_contact.contact = contact acknowledgment_contact = AcknowledgmentContact() default_entry_control.acknowledgment_contacts.append( acknowledgment_contact) acknowledgment_contact.contact = contact default_entry_control.no_acknowledgment_of_receipt = True default_entry_control.state = 'draft' default_entry_control.save() # Confirm entry default_entry_control.click('confirm') return default_entry_control
def setup_company(config): Party = Model.get('party.party') Company = Model.get('company.company') Currency = Model.get('currency.currency') Country = Model.get('country.country') ars, = Currency.find([('code', '=', 'ARS')]) ar, = Country.find([('code', '=', 'AR')]) company_config = Wizard('company.company.config') company_config.execute('company') company = company_config.form party = Party(name='Union Papelera Platense') party.vat_number = '30709170046' party.iva_condition = 'responsable_inscripto' party.save() company.party = party company.currency = ars company_config.execute('add') # Reload context User = Model.get('res.user') config._context = User.get_preferences(True, config.context) company, = Company.find() return company
def setup_account_invoice_ar(config, modules, company): Pos = Model.get('account.pos') PosSequence = Model.get('account.pos.sequence') Sequence = Model.get('ir.sequence') punto_de_venta = Pos() punto_de_venta.pos_type = 'manual' punto_de_venta.number = 2 punto_de_venta.save() for attr, name in ( ('1', '01-Factura A'), ('3', '03-Nota de Credito A'), ('6', '06-Factura B'), ('8', '08-Nota de Credito B'), ('11', '11-Factura C'), ('13', '13-Nota de Credito C')): sequence = Sequence( name='%s %s' % (name, 'manual'), code='account.invoice', company=company) sequence.save() pos_sequence = PosSequence() pos_sequence.invoice_type = attr pos_sequence.invoice_sequence = sequence pos_sequence.pos = punto_de_venta pos_sequence.save() return punto_de_venta
def loadCustomers(): f = open(sys.argv[2], 'rb') countrycode = sys.argv[3] if countrycode is None: print "Please provide a country code. e.g. 'CH'" try: reader = csv.DictReader(f) Lang = Model.get('ir.lang') (en, ) = Lang.find([('code', '=', 'en_US')]) Country = Model.get('country.country') (ch, ) = Country.find([('code', '=', countrycode)]) for row in reader: print(row['first_name'], row['last_name'], row['company_name']) Party = Model.get('party.party') party = Party() if party.id < 0: party.name = row['company_name'] party.lang = en party.addresses[ 0].name = row['first_name'] + ' ' + row['last_name'] party.addresses[0].street = row['address'] party.addresses[0].streetbis = None party.addresses[0].zip = row['zip'] party.addresses[0].city = row['city'] party.addresses[0].country = ch # party.addresses[0].subdivision = row['state'] party.addresses[0].invoice = True party.addresses[0].delivery = True party.save() finally: f.close()
def LoadCategoryG(): Account = Model.get('account.account') Tax = Model.get('account.tax') category = Category() category.name = "CATEGORIA GENERAL" category.taxes_parent = False category.account_parent = False category.iva_tarifa = "2" if len(Account.find([('name', '=', 'VENTA DE BIENES')])) == 1: revenue, = Account.find([('name', '=', 'VENTA DE BIENES')]) category.account_revenue = revenue if len(Account.find([('name', '=', 'COSTO DE VENTAS')])) == 1: expense, = Account.find([('name', '=', 'COSTO DE VENTAS')]) category.account_expense = expense category.save() categories = Category.find([('name', '=', 'CATEGORIA GENERAL')]) taxes_c = Tax.find([ ('description', '=', 'IVA VENTAS LOCALES (EXCLUYE ACTIVOS FIJOS) GRAVADAS TARIFA 12%') ]) taxes_s = Tax.find([( 'description', '=', 'IVA ADQUISICIONES Y PAGOS (EXCLUYE ACTIVOS FIJOS) GRAVADOS TARIFA 12% (CON DERECHO A CRÉDITO TRIBUTARIO)' )]) for category in categories: category.customer_taxes.append(taxes_c[0]) category.supplier_taxes.append(taxes_s[0]) category.save() print "Created category ", category
def AccountConfiguration(): print "Load account configuration " Account = Model.get('account.account') AccountConfiguration = Model.get('account.configuration') account_configuration = AccountConfiguration() if len( Account.find([ ('name', '=', 'DOCUMENTOS Y CUENTAS POR COBRAR CLIENTES RELACIONADOS') ])) == 1: default_account_receivable, = Account.find([ ('name', '=', 'DOCUMENTOS Y CUENTAS POR COBRAR CLIENTES RELACIONADOS') ]) account_configuration.default_account_receivable = default_account_receivable if len(Account.find([('name', '=', 'CUENTAS POR PAGAR PROVEEDORES') ])) == 1: default_account_payable, = Account.find([ ('name', '=', 'CUENTAS POR PAGAR PROVEEDORES') ]) account_configuration.default_account_payable = default_account_payable tax_roundings = account_configuration.tax_roundings.new() if len(Company.find([('party.vat_number', '=', company_context)])) == 1: company, = Company.find([('party.vat_number', '=', company_context)]) tax_roundings.company = company tax_roundings.method = 'document' account_configuration.save() print "Created account configuration ", account_configuration
def test_save(self): User = Model.get('res.user') test = User() test.name = 'Test' test.login = '******' test.save() self.assert_(test.id > 0) test = User(test.id) self.assertEqual(test.name, 'Test') self.assertEqual(test.login, 'test') self.assert_(test.active) test.signature = 'Test signature' self.assertEqual(test.signature, 'Test signature') test.save() self.assertEqual(test.signature, 'Test signature') test = User(test.id) self.assertEqual(test.signature, 'Test signature') Group = Model.get('res.group') test2 = User(name='Test 2', login='******', groups=[Group(name='Test 2')]) test2.save() self.assert_(test2.id > 0) self.assertEqual(test2.name, 'Test 2') self.assertEqual(test2.login, 'test2')
def create_chart(company=None, config=None): """Create chart of accounts""" AccountTemplate = Model.get('account.account.template', config=config) ModelData = Model.get('ir.model.data') AccountChart = Model.get('account.account', config=config) existing_chart = AccountChart.find([('name', '=', CHART_OF_ACCOUNT_NAME)], limit=1) if existing_chart: print("Warning: Account Chart '" + CHART_OF_ACCOUNT_NAME + "' already exists!") return existing_chart[0] if not company: company = get_company() data, = ModelData.find([ ('module', '=', 'account'), ('fs_id', '=', 'account_template_root_en'), ], limit=1) account_template = AccountTemplate(data.db_id) create_chart = Wizard('account.create_chart') create_chart.execute('account') create_chart.form.account_template = account_template create_chart.form.company = company create_chart.execute('create_account') accounts = get_accounts(company, config=config) create_chart.form.account_receivable = accounts['receivable'] create_chart.form.account_payable = accounts['payable'] create_chart.execute('create_properties') print("Success: Account Chart '" + CHART_OF_ACCOUNT_NAME + "' created!") return create_chart
def setup_production_routing(config, activated, company): Routing = Model.get('production.routing') Operation = Model.get('production.routing.operation') Product = Model.get('product.product') routing = Routing(name='Computer routing rev1') operation1 = Operation(name='Assemble pieces') operation1.save() step1 = routing.steps.new() step1.operation = operation1 operation2 = Operation(name='Install software') operation2.save() step2 = routing.steps.new() step2.operation = operation2 operation3 = Operation(name='Test') operation3.save() step3 = routing.steps.new() step3.operation = operation3 operation4 = Operation(name='Package') operation4.save() step4 = routing.steps.new() step4.operation = operation4 routing.boms.extend(routing.boms.find([('name', '=', 'Computer rev1')])) routing.save() computer, = Product.find([('name', '=', 'Computer')]) bom, = computer.boms bom.routing = routing bom.save()
def test_on_change_set(self): User = Model.get('res.user') Group = Model.get('res.group') test = User() test._on_change_set('name', 'Test') self.assertEqual(test.name, 'Test') group_ids = [x.id for x in Group.find()] test._on_change_set('groups', group_ids) self.assertEqual([x.id for x in test.groups], group_ids) test._on_change_set('groups', {'remove': [group_ids[0]]}) self.assertEqual([x.id for x in test.groups], group_ids[1:]) test._on_change_set('groups', {'add': [{ 'name': 'Bar', }]}) self.assert_([x for x in test.groups if x.name == 'Bar']) test.groups.extend(Group.find()) group = test.groups[0] test._on_change_set('groups', {'update': [{ 'id': group.id, 'name': 'Foo', }]}) self.assert_([x for x in test.groups if x.name == 'Foo'])
def setup_company(config): Party = Model.get('party.party') Company = Model.get('company.company') Currency = Model.get('currency.currency') Country = Model.get('country.country') ars, = Currency.find([('code', '=', 'ARS')]) rate = ars.rates.new() rate.date = datetime.date(TODAY.year, 1, 1) rate.rate = Decimal('44.30') ars.save() ar, = Country.find([('code', '=', 'AR')]) company_config = Wizard('company.company.config') company_config.execute('company') company = company_config.form party = Party(name='Cooperativa de Trabajo La Metalurgica LTDA') party.vat_number = '30710288565' party.iva_condition = 'responsable_inscripto' party.save() company.party = party company.currency = ars company_config.execute('add') # Reload context User = Model.get('res.user') config._context = User.get_preferences(True, {}) company, = Company.find() return company
def install_modules(config, modules): ''' Function get from tryton_demo.py in tryton-tools repo: http://hg.tryton.org/tryton-tools ''' Module = Model.get('ir.module.module') modules = Module.find([ ('name', 'in', modules), #('state', '!=', 'installed'), ]) Module.install([x.id for x in modules], config.context) modules = [ x.name for x in Module.find([ ('state', 'in', ('to install', 'to_upgrade')), ]) ] Wizard('ir.module.module.install_upgrade').execute('upgrade') ConfigWizardItem = Model.get('ir.module.module.config_wizard.item') for item in ConfigWizardItem.find([('state', '!=', 'done')]): item.state = 'done' item.save() installed_modules = [ m.name for m in Module.find([('state', '=', 'installed')]) ] return modules, installed_modules
def create_product_category(name, parent=None, account_parent=False, account_expense=None, account_revenue=None, taxes_parent=False, customer_taxes=None, supplier_taxes=None): ProductCategory = Model.get('product.category') Tax = Model.get('account.tax') categories = ProductCategory.find([ ('name', '=', name), ('parent', '=', parent), ]) if categories: return categories[0] if customer_taxes is None: customer_taxes = [] if supplier_taxes is None: supplier_taxes = [] category = ProductCategory(name=name, parent=parent) category.account_parent = account_parent category.account_expense = account_expense category.account_revenue = account_revenue category.taxes_parent = taxes_parent if not taxes_parent: for ct in customer_taxes: category.customer_taxes.append(Tax(ct.id)) for st in supplier_taxes: category.supplier_taxes.append(Tax(st.id)) category.save() return category
def set_active_languages(config, lang_codes=None): Lang = Model.get('ir.lang') User = Model.get('res.user') if not lang_codes: lang_codes = ['ca_ES', 'es_ES'] langs = Lang.find([ ('code', 'in', lang_codes), ]) assert len(langs) > 0 Lang.write([l.id for l in langs], { 'translatable': True, }, config.context) default_langs = [l for l in langs if l.code == lang_codes[0]] if not default_langs: default_langs = langs users = User.find([]) if users: User.write([u.id for u in users], { 'language': default_langs[0].id, }, config.context) # Reload context User = Model.get('res.user') config._context = User.get_preferences(True, config.context) if not all(l.translatable for l in langs): # langs is fetched before wet all translatable print "Upgrading all because new translatable languages has been added" upgrade_modules(config, all=True)
def test_class_cache(self): User1 = Model.get('res.user') User2 = Model.get('res.user') self.assertEqual(id(User1), id(User2)) Model.reset() User3 = Model.get('res.user') self.assertNotEqual(id(User1), id(User3))
def test_reference(self): Attachment = Model.get('ir.attachment') User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] attachment = Attachment() attachment.name = 'Test' attachment.resource = admin attachment.save() self.assertEqual(attachment.resource, admin)
def test_translation_export(self): Lang = Model.get('ir.lang') Module = Model.get('ir.module.module') translation_export = Wizard('ir.translation.export') translation_export.form.language, = Lang.find([('code', '=', 'en_US')]) translation_export.form.module, = Module.find([('name', '=', 'ir')]) translation_export.execute('export') self.assert_(translation_export.form.file) translation_export.execute('end')
def check_category(cat_name, simulate): cats = Model.get('product.category').find([("name", "=", cat_name)]) if not cats: if not simulate: cat = Model.get('product.category')() cat.name = cat_name cat.save() return cat return None return cats[0]
def test_one2many(self): Group = Model.get('res.group') administration = Group.find([('name', '=', 'Administration')])[0] self.assert_(isinstance(administration.model_access, list)) self.assert_(isinstance(administration.model_access[0], Model.get('ir.model.access'))) try: administration.model_access = [] self.fail() except AttributeError: pass
def test_many2many(self): User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] self.assert_(isinstance(admin.groups, list)) self.assert_(isinstance(admin.groups[0], Model.get('res.group'))) try: admin.groups = [] self.fail() except AttributeError: pass
def create_calendar(login, user, config): Calendar = Model.get('calendar.calendar') User = Model.get('res.user') current_user, = User.find([('login', '=', login)]) main_user, = User.find([('login', '=', user)]) for calendar in Calendar.find([('owner', '=', login)]): calendar.write_users.append(User(main_user.id)) calendar.save() calendar.delete() calendar = Calendar(name=login, owner=current_user) if login != 'bar': calendar.read_users.append(main_user) calendar.save()
def done(context): from trytond.modules.company.tests.tools import create_company, \ get_company from trytond.modules.account.tests.tools import create_fiscalyear, \ create_chart, get_accounts from.trytond.modules.account_invoice.tests.tools import \ set_fiscalyear_invoice_sequences, create_payment_term from trytond.modules.account_asset.tests.tools \ import add_asset_accounts #step('Create database') config = config.set_trytond() config.pool.test = True #step('Install account_asset') Module = Model.get('ir.module.module') module, = Module.find([ ('name', '=', 'account_asset'), ]) module.click('install') Wizard('ir.module.module.install_upgrade').execute('upgrade') #@step('Create company') _ = create_company() company = get_company() #@step('Reload the context') User = Model.get('res.user') config._context = User.get_preferences(True, config.context) #@step('Create fiscal year') fiscalyear = set_fiscalyear_invoice_sequences( create_fiscalyear(company)) fiscalyear.click('create_period') #@step('Create chart of accounts') _ = create_chart(company) accounts = add_asset_accounts(get_accounts(company), company) revenue = accounts['revenue'] asset_account = accounts['asset'] expense = accounts['expense'] depreciation_account = accounts['depreciation']
def test_init(self): User = Model.get('res.user') self.assertEqual(User(1).id, 1) self.assertEqual(User(name='Foo').name, 'Foo') Lang = Model.get('ir.lang') en_US = Lang.find([('code', '=', 'en_US')])[0] self.assertEqual(User(language=en_US).language, en_US) self.assertEqual(User(language=en_US.id).language, en_US) Group = Model.get('res.group') groups = Group.find() self.assertEqual(len(User(groups=groups).groups), len(groups)) self.assertEqual(len(User(groups=[x.id for x in groups]).groups), len(groups))
def create_fiscalyear(company=None, today=None, config=None): """Create a fiscal year for the company on today""" FiscalYear = Model.get('account.fiscalyear', config=config) Sequence = Model.get('ir.sequence', config=config) SequenceStrict = Model.get('ir.sequence.strict', config=config) if not company: company = get_company() if not today: today = datetime.date.today() existing_fy = FiscalYear.find([('name', '=', str(today.year))], limit=1) if existing_fy: print("Warning: Fiscal year " + str(today.year) + " already exists!") return existing_fy[0] fiscalyear = FiscalYear(name=str(today.year)) fiscalyear.start_date = today + relativedelta(month=1, day=1) fiscalyear.end_date = today + relativedelta(month=12, day=31) fiscalyear.company = company fiscalyear.account_stock_method = ACCOUNT_STOCK_METHOD post_move_sequence = Sequence(name=POST_MOVE_SEQ, code='account.move', number_next=10000, company=company) customer_invoice_sequence = SequenceStrict(name=CUSTOMER_INVOICE_SEQ, code='account.invoice', number_next=200000, company=company) customer_credit_note_sequence = SequenceStrict(name=CUSTOMER_CREDIT_NOTE_SEQ, code='account.invoice', number_next=100000, company=company) supplier_invoice_sequence = SequenceStrict(name=SUPPLIER_INVOICE_SEQ, code='account.invoice', number_next=600000, company=company) supplier_credit_note_sequence = SequenceStrict(name=SUPPLIER_CREDIT_NOTE_SEQ, code='account.invoice', number_next=500000, company=company) post_move_sequence.save() customer_invoice_sequence.save() customer_credit_note_sequence.save() supplier_invoice_sequence.save() supplier_credit_note_sequence.save() fiscalyear.post_move_sequence = post_move_sequence fiscalyear.out_invoice_sequence = customer_invoice_sequence fiscalyear.out_credit_note_sequence = customer_credit_note_sequence fiscalyear.in_invoice_sequence = supplier_invoice_sequence fiscalyear.in_credit_note_sequence = supplier_credit_note_sequence fiscalyear.save() fiscalyear.click('create_period') period = fiscalyear.periods[0] print("Success: Fiscal year " + str(today.year) + "' created!") return fiscalyear
def test0050create_event_attendee(self): 'Create event with attendee' ical = vobject.iCalendar() vevent = ical.add('vevent') vevent.add('summary') vevent.summary.value = 'Test event with attendee' vevent.add('dtstart') vevent.dtstart.value = datetime.datetime.now() + relativedelta(days=10) vevent.add('dtend') vevent.dtend.value = datetime.datetime.now() + relativedelta(days=10, hours=4) vevent.add('organizer') vevent.organizer.value = '*****@*****.**' % user attendees = [] for name in ('foo', 'bar'): attendee = vobject.base.ContentLine('ATTENDEE', [], '') attendee.partstat_param = 'TENTATIVE' attendee.value = 'MAILTO:%[email protected]' % name attendees.append(attendee) vevent.attendee_list = attendees caldav.Event(self.client, data=ical.serialize(), parent=self.calendar).save() Event = Model.get('calendar.event') owner_event, = Event.find([ ('calendar.owner.email', '=', '*****@*****.**' % user), ('summary', '=', vevent.summary.value), ]) attendee_event, = Event.find([ ('calendar.owner.email', '=', '*****@*****.**'), ]) self.assertEqual(attendee_event.uuid, owner_event.uuid)
def create_payment_term(config=None): "Create a direct payment term" PaymentTerm = Model.get('account.invoice.payment_term') payment_term = PaymentTerm(name='Direct') payment_term.lines.new(type='remainder') return payment_term
def get_accounts(company=None, config=None): "Return accounts per kind" Account = Model.get('account.account', config=config) if not company: company = get_company() accounts = Account.find([ ('kind', 'in', ['receivable', 'payable', 'revenue', 'expense']), ('company', '=', company.id), ]) accounts = {a.kind: a for a in accounts} cash, = Account.find([ ('kind', '=', 'other'), ('company', '=', company.id), ('name', '=', 'Main Cash'), ]) accounts['cash'] = cash tax, = Account.find([ ('kind', '=', 'other'), ('company', '=', company.id), ('name', '=', 'Main Tax'), ]) accounts['tax'] = tax return accounts
def test_delete(self): Group = Model.get('res.group') test = Group() test.name = 'Test delete' test.login = '******' test.save() test.delete()
def crear_medidores(): # # # os.system('clear') sql = (r"SELECT r.NRO_MEDIDOR, r.CANT_ESFERAS, r.MARCA, r.FECHA_ALTA " "FROM USU_AGUA r " "where r.NRO_MEDIDOR is not null " "order by r.NRO_MEDIDOR ") cur.execute(sql) for row in cur: mensaje='Importando Medidor Nro. ' print mensaje, row[0] new_med = Model.get('sigcoop_medidor.medidor')() new_med.servicio = 'Agua' new_med.name = str(row[0]).strip() #new_med.numero_serie = str(row[1]).strip() new_med.marca = str(row[2]).strip() new_med.cantidad_esferas = str(row[1]).strip() new_med.modelo = str(row[2]).strip() new_med.save()
def test_save_many2one(self): User = Model.get('res.user') test = User() test.name = 'Test save many2one' test.login = '******' test.save() Lang = Model.get('ir.lang') en_US = Lang.find([('code', '=', 'en_US')])[0] test.language = en_US test.save() self.assertEqual(test.language, en_US) test.language = None test.save() self.assertFalse(test.language)
def test_delete(self): User = Model.get('res.user') test = User() test.name = 'Test delete' test.login = '******' test.save() test.delete()
def test_on_change_with(self): Attachment = Model.get('ir.attachment') attachment = Attachment() attachment.description = 'Test' self.assertEqual(attachment.summary, 'Test')
def test_id_counter(self): User = Model.get('res.user') test1 = User() self.assert_(test1.id < 0) test2 = User() self.assert_(test2.id < 0) self.assertNotEqual(test1.id, test2.id)