Example #1
0
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
Example #2
0
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()
Example #3
0
    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 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)
Example #5
0
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 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))
Example #7
0
    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 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 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()
Example #10
0
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
Example #11
0
    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'])
Example #12
0
    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))
Example #13
0
 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')
Example #14
0
 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)
Example #15
0
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]
Example #16
0
 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
Example #17
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
Example #18
0
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']
Example #20
0
    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))
Example #21
0
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
Example #22
0
    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)
Example #23
0
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
Example #24
0
    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)
Example #25
0
 def test_delete(self):
     User = Model.get('res.user')
     test = User()
     test.name = 'Test delete'
     test.login = '******'
     test.save()
     test.delete()
Example #26
0
    def test_on_change_with(self):
        Attachment = Model.get('ir.attachment')

        attachment = Attachment()

        attachment.description = 'Test'
        self.assertEqual(attachment.summary, 'Test')
Example #27
0
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 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()
Example #29
0
 def test_delete(self):
     Group = Model.get('res.group')
     test = Group()
     test.name = 'Test delete'
     test.login = '******'
     test.save()
     test.delete()
Example #30
0
 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)
Example #31
0
def get_currency(code='USD', config=None):
    "Get currency with code"
    Currency = Model.get('currency.currency', config=config)
    CurrencyRate = Model.get('currency.currency.rate', config=config)

    currencies = Currency.find([('code', '=', code)])
    if not currencies:
        currency = Currency(name=_names.get(code, code),
                            symbol=_symbols.get(code, code),
                            code=code,
                            rounding=Decimal('0.01'))
        currency.save()
        rate = _rates.get(code)
        if rate is not None:
            CurrencyRate(date=datetime.date.min, rate=rate,
                         currency=currency).save()
    else:
        currency, = currencies
    return currency
Example #32
0
def components(database):
    get_tryton_connection()

    DBComponent = Model.get('nantic.database.component')

    components = DBComponent.find([('database.name', '=', database),
            ('state', '=', 'accepted')])

    for component in components:
        print component.component.name
Example #33
0
    def test_save_one2many(self):
        Group = Model.get('res.group')
        group = Group()
        group.name = 'Test save one2many'
        group.save()

        ModelAccess = Model.get('ir.model.access')
        Model_ = Model.get('ir.model')
        model_access = ModelAccess()
        model_access.model = Model_.find([('model', '=', 'res.group')])[0]
        model_access.perm_read = True
        model_access.perm_write = True
        model_access.perm_create = True
        model_access.perm_delete = True

        group.model_access.append(model_access)
        group.save()
        self.assertEqual(len(group.model_access), 1)

        model_access_id = group.model_access[0].id

        group.name = 'Test save one2many bis'
        group.model_access[0].description = 'Test save one2many'
        group.save()
        self.assertEqual(group.model_access[0].description,
                         'Test save one2many')

        group.model_access.pop()
        group.save()
        self.assertEqual(group.model_access, [])
        self.assertEqual(len(ModelAccess.find([('id', '=', model_access_id)])),
                         1)

        group.model_access.append(ModelAccess(model_access_id))
        group.save()
        self.assertEqual(len(group.model_access), 1)

        group.model_access.remove(group.model_access[0])
        group.save()
        self.assertEqual(group.model_access, [])
        self.assertEqual(len(ModelAccess.find([('id', '=', model_access_id)])),
                         0)
Example #34
0
def import_parties(database, config_file):
    config.set_trytond(database, config_file=config_file)
    Party = Model.get('party.party')
    fake = Faker()

    to_save = []
    for i in range(1000):
        party = Party()
        party.name = fake.name()
        to_save.append(party)
    Party.save(to_save)
Example #35
0
def get_invoice_types(company=None, pos=None, config=None):
    "Return invoices types per pos and company"
    Account = Model.get('account.account', config=config)
    PosSequence = Model.get('account.pos.sequence', config=config)

    if not company:
        company = get_company()

    if not pos:
        pos = get_pos(company)

    accounts = Account.find([
        ('kind', 'in', ['receivable', 'payable', 'revenue', 'expense']),
        ('company', '=', company.id),
    ])
    invoice_types = PosSequence.find([
        ('pos', '=', pos.id),
    ])
    invoice_types = {i.invoice_type: i for i in invoice_types}
    return invoice_types
def insert_content_by_filename(filename, user, pstate):
    """
    insert an example content by filename/uuid.
    """
    Content = Model.get('content')
    new_content = Content()
    new_content.id < 0
    new_content.uuid = filename
    new_content.user = user
    new_content.processing_state = pstate
    new_content.save()
Example #37
0
def LoadSequence():
    Sequence = Model.get('ir.sequence')
    sequence = Sequence()
    sequence.name = 'AC 2016'
    sequence.code = 'account.move'
    sequence.padding = 0
    sequence.prefix = 'AC-2016-'
    sequence.type = 'incremental'
    sequence.active = True
    sequence.save()
    print "Created sequence ", sequence
Example #38
0
def create_operation_type(name):
    OperationType = Model.get('production.operation.type')

    op = OperationType.find([('name', '=', name)])
    if op:
        return op[0]

    op = OperationType()
    op.name = name
    op.save()
    return op
Example #39
0
def _create_base_entry_tables(config=None):
    "Configuration / Entry"
    PackagingType = Model.get('lims.packaging.type', config=config)
    PackagingIntegrity = Model.get('lims.packaging.integrity', config=config)
    Zone = Model.get('lims.zone', config=config)
    EntrySuspensionReason = Model.get('lims.entry.suspension.reason',
                                      config=config)

    packaging_type = PackagingType(code='01', description='Package')
    packaging_type.save()

    packaging_integrity = PackagingIntegrity(code='OK', description='Ok')
    packaging_integrity.save()

    zone = Zone(code='N', description='North')
    zone.save()

    suspension_reason = EntrySuspensionReason(
        code='01', description='Administration pending', by_default=True)
    suspension_reason.save()
Example #40
0
def create_route(name):
    Route = Model.get('production.route')

    route = Route.find([('name', '=', name)])
    if route:
        return route[0]

    route = Route()
    route.name = name
    route.save()
    return route
Example #41
0
def create_analytic_account(name, type, parent, currency=None):
    Account = Model.get('analytic_account.account')
    account = Account(name=name,
                      type=type,
                      state='opened',
                      root=parent and parent.root or parent,
                      parent=parent,
                      display_balance='credit-debit')
    if currency:
        account.currency = currency
    return account
Example #42
0
def import_(data):
    Zip = Model.get('country.zip')
    Country = Model.get('country.country')
    Subdivision = Model.get('country.subdivision')
    print('Importing', file=sys.stderr)

    def get_country(code):
        country = countries.get(code)
        if not country:
            country, = Country.find([('code', '=', code)])
            countries[code] = country
        return country
    countries = {}

    def get_subdivision(country, code):
        code = '%s-%s' % (country, code)
        subdivision = subdivisions.get(code)
        if not subdivision:
            try:
                subdivision, = Subdivision.find([('code', '=', code)])
            except ValueError:
                return
            subdivisions[code] = subdivision
        return subdivision
    subdivisions = {}

    if ProgressBar:
        pbar = ProgressBar(
            widgets=[SimpleProgress(), Bar(), ETA()])
    else:
        pbar = iter
    f = StringIO(data.decode('utf-8'))
    zips = []
    for row in pbar(list(csv.DictReader(
                    f, fieldnames=_fieldnames, delimiter='\t'))):
        country = get_country(row['country'])
        subdivision = get_subdivision(row['country'], row['code1'])
        zips.append(
            Zip(country=country, subdivision=subdivision, zip=row['postal'],
            city=row['place']))
    Zip.save(zips)
Example #43
0
def import_products(filename):
    f = open(filename, 'rb')
    config.set_trytond(app.config['TRYTON_DATABASE_NAME'],
                       config_file=app.config['TRYTON_CONFIG_FILE'])
    try:
        print('Testing csv file structure for products')
        readertest = csv.DictReader(f)
        print(readertest.fieldnames)
        for row in readertest:
            print(row['code'], row['name'], row['description'],
                  row['quantity'], row['product.template_name'])

        f.seek(0)
        print('Start import')
        reader = csv.DictReader(f)
        Producttemplate = Model.get('product.template')
        producttemplatelist = Producttemplate.find([('id', '>', 0)])
        Product = Model.get('product.product')
        for row in reader:
            print(row['code'], row['name'], row['description'],
                  row['quantity'])
            product = Product()
            product.code = row['code']
            product.name = row['name']
            product.description = row['description']
            # attributes:
            new_attributes = {}
            for fieldname in reader.fieldnames:
                if fieldname[0:10] == 'attribute_':
                    if row[fieldname] == 'TRUE':
                        new_attributes[fieldname[10:]] = True
                    elif row[fieldname] == 'FALSE':
                        new_attributes[fieldname[10:]] = False
                    else:
                        new_attributes[fieldname[10:]] = row[fieldname]
            product.template = getProductTemplate(producttemplatelist,
                                                  row['product.template_name'])
            product.attributes = new_attributes
            product.save()
    finally:
        f.close()
Example #44
0
def add_advance_payment_accounts(accounts, company=None, config=None):
    "Add advance payment to accounts"
    Account = Model.get('account.account', config=config)

    if not company:
        company = get_company()

    accounts['advance_payment'], = Account.find([
            ('type.unearned_revenue', '=', True),
            ('company', '=', company.id),
            ], limit=1)
    return accounts
Example #45
0
    def check_fiscal_bug(self):
        """check if the fiscal year entry is present"""
        Fiscal = Model.get('account.fiscalyear')
        today = date.today()
        fiscalyear = Fiscal.find(['name', '=', str(today.year)])
        if not fiscalyear:
            company = self.User(id=1).main_company
            from fiscal_year_bug import create_fiscalyear

            create_fiscalyear(company=company,
                              config=config.get_config(),
                              today=today)
Example #46
0
def create_company(party=None, currency=None, config=None):
    "Create the company using the proteus config"
    Party = Model.get('party.party', config=config)
    User = Model.get('res.user', config=config)

    company_config = Wizard('company.company.config')
    company_config.execute('company')
    company = company_config.form
    if not party:
        party = Party(name='Dunder Mifflin')
        party.save()
    company.party = party
    if not currency:
        currency = get_currency()
    company.currency = currency
    company_config.execute('add')

    if not config:
        config = get_config()
    config._context = User.get_preferences(True, {})
    return company_config
Example #47
0
 def test_model_graph(self):
     IrModel = Model.get('ir.model')
     models = IrModel.find([])
     data = {
         'level': 1,
         'filter': '',
     }
     report = Report('ir.model.graph')
     type_, data, print_, name = report.execute(models, data)
     self.assertEqual(type_, 'png')
     self.assertEqual(print_, False)
     self.assertEqual(name, 'Graph')
Example #48
0
def _create_default_notebook_view(config=None):
    "Create default notebook view"
    NotebookView = Model.get('lims.notebook.view', config=config)
    NotebookViewColumn = Model.get('lims.notebook.view.column', config=config)
    Field = Model.get('ir.model.field', config=config)

    default_notebook_view = NotebookView()
    default_notebook_view.name = 'Default View'
    sequence = 1
    for field_name in ('analysis', ):
        column = NotebookViewColumn()
        default_notebook_view.columns.append(column)
        field, = Field.find([
            ('model.model', '=', 'lims.notebook.line'),
            ('name', '=', field_name),
        ])
        column.field = field
        column.sequence = sequence
        sequence += 1
    default_notebook_view.save()
    return default_notebook_view
Example #49
0
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)

    if not company:
        company = get_company()

    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

    post_move_sequence = Sequence(name=str(today.year), code='account.move',
        company=company)
    post_move_sequence.save()
    fiscalyear.post_move_sequence = post_move_sequence
    return fiscalyear
Example #50
0
def set_fiscalyear_invoice_sequences(fiscalyear, config=None):
    "Set invoice sequences to fiscalyear"
    SequenceStrict = Model.get('ir.sequence.strict', config=config)

    invoice_seq = SequenceStrict(name=fiscalyear.name, code='account.invoice',
        company=fiscalyear.company)
    invoice_seq.save()
    fiscalyear.out_invoice_sequence = invoice_seq
    fiscalyear.in_invoice_sequence = invoice_seq
    fiscalyear.out_credit_note_sequence = invoice_seq
    fiscalyear.in_credit_note_sequence = invoice_seq
    return fiscalyear
Example #51
0
def activate_modules(config, modules):
    Module = Model.get('ir.module')
    modules = Module.find([
            ('name', 'in', modules),
            ])
    for module in modules:
        if module.state == 'activated':
            module.click('upgrade')
        else:
            module.click('activate')
    modules = [x.name for x in Module.find([('state', '=', 'to activate')])]
    Wizard('ir.module.activate_upgrade').execute('upgrade')

    ConfigWizardItem = Model.get('ir.module.config_wizard.item')
    for item in ConfigWizardItem.find([('state', '!=', 'done')]):
        item.state = 'done'
        item.save()

    activated_modules = [m.name
        for m in Module.find([('state', '=', 'activated')])]
    return modules, activated_modules
Example #52
0
def input_results():
    LabTestLine = Model.get('gnuhealth.lab.test.critearea')
    csv_file = csv.reader(open(sys.argv[1], 'rb'))
    for line in csv_file:
        test_id = line[0]
        analyte = line[1]
        result = line[2]
        # Update the model with the result values
        for result_line in LabTestLine.find([('name','=',analyte), \
            ('gnuhealth_lab_id','=',test_id)]):
            result_line.result = float(result)
            result_line.save()
Example #53
0
def setup_account_payment(config, modules, company):
    Currency = Model.get('currency.currency')
    Journal = Model.get('account.payment.journal')
    Line = Model.get('account.move.line')
    Payment = Model.get('account.payment')

    usd, = Currency.find([('code', '=', 'USD')])
    journal = Journal(name='Manual',
                      currency=usd,
                      company=company,
                      process_method='manual')
    journal.save()

    lines = Line.find([
        ('account.kind', '=', 'payable'),
        ('party', '!=', None),
        ('reconciliation', '=', None),
        ('payment_amount', '!=', 0),
    ])
    lines = random.sample(lines, len(lines) * 2 // 3)
    if not lines:
        return

    pay_line = Wizard('account.move.line.pay', lines)
    pay_line.form.journal = journal
    pay_line.execute('start')

    payments = Payment.find([])
    payments = random.sample(payments, len(payments) * 2 // 3)

    for payment in payments:
        payment.click('approve')

    payments = random.sample(payments, len(payments) * 2 // 3)
    i = j = 0
    while i < len(payments):
        j = random.randint(1, 5)
        process = Wizard('account.payment.process', payments[i:i + j])
        process.execute('process')
        i += j
Example #54
0
    def test_many2one(self):
        User = Model.get('res.user')
        admin = User.find([('login', '=', 'admin')])[0]
        self.assert_(isinstance(admin.create_uid, User))
        try:
            admin.create_uid = 'test'
            self.fail()
        except AssertionError:
            pass
        admin.create_uid = admin
        admin.create_uid = None

        User(write_uid=None)
Example #55
0
def _create_company_contacts(company=None, config=None):
    "Create contacts for company party"
    if not company:
        company = get_company()

    Address = Model.get('party.address', config=config)
    address, = Address.find([('party', '=', company.party.id)])
    address.invoice_contact = True
    address.report_contact = True
    address.acknowledgment_contact = True
    address.email = '*****@*****.**'
    address.save()
    return address
Example #56
0
def search_product(productid=None):
    config.set_trytond(DATABASE_NAME, config_file=CONFIG)
    Product = Model.get('product.product')
    product = Product.find(['code', '=', productid])
    list = []
    for n in product:
        list.append({
            'id': str(n.id),
            'code': n.code,
            'name': n.name,
            'price': str(n.list_price)
        })
    return jsonify(result=list)
def InitDatabase():
    Module = Model.get('ir.module.module')
    inicio = 4

    for i in range(inicio - 1):
        modules.next()

    for index, row in enumerate(modules):
        print row[0]
        name = row[0]
        (module, ) = Module.find([('name', '=', name)])
        Module.install([module.id], config.context)
        Wizard('ir.module.module.install_upgrade').execute('upgrade')
Example #58
0
def create_supplier():
    Party = Model.get('party.party')
    existing_supplier = Party.find([('name', '=', DEFAULT_PARTY_SUPPLIER)],
                                   limit=1)
    if existing_supplier:
        print("Warning: Supplier '" + DEFAULT_PARTY_SUPPLIER +
              "' already exists!")
        return existing_supplier[0]
    else:
        supplier = Party(name=DEFAULT_PARTY_SUPPLIER)
        supplier.save()
        print("Success: Supplier '" + DEFAULT_PARTY_SUPPLIER + "' created!")
    return supplier
def get_pos(company=None, type='manual', number=1, config=None):
    "Return the only pos"
    Pos = Model.get('account.pos', config=config)

    if not company:
        company = get_company()

    pos, = Pos.find([
        ('company', '=', company.id),
        ('pos_type', '=', type),
        ('number', '=', number),
    ])
    return pos
Example #60
0
def loadInternalShipment():
    f = open(sys.argv[2], 'rb')
    csvlisttype = sys.argv[3]
    if csvlisttype is None:
        print "Please provide a listtype 'A' or 'B'"
    try:
        StockShipmentInternal = Model.get('stock.shipment.internal')
        stockshipmentinternal = StockShipmentInternal()
        stockshipmentinternal.reference = sys.argv[2]
        LocationFrom = Model.get('stock.location')
        locationfrom = LocationFrom.find([('code', '=', 'IN')])
        stockshipmentinternal.from_location = locationfrom[0]
        LocationTo = Model.get('stock.location')
        locationto = LocationTo.find([('code', '=', 'STO')])
        stockshipmentinternal.to_location = locationto[0]
        stockshipmentinternal.effective_date = date.today()
        stockshipmentinternal.save()
        reader = csv.DictReader(f)
        moves = []
        if stockshipmentinternal.id > 0:
            for row in reader:
                print(row['Price'], row['Shipping'], row['Manufacturer'])
                StockMove = Model.get('stock.move')
                stockmove = StockMove()
                stockmove.shipment = stockshipmentinternal
                Product = Model.get('product.product')
                product = Product.find([('code', '=', row['ArtNumber'])])
                stockmove.product = product[0]
                stockmove.quantity = 1
                stockmove.from_location = locationfrom[0]
                stockmove.to_location = locationto[0]
                stockmove.effective_date = date.today()
                stockmove.planned_date = date.today()
                stockmove.unit_price = Decimal(0.000)
                stockmove.cost_price = product[0].cost_price
                stockmove.save()
                moves.append(stockmove)
    finally:
        f.close()