def copy_selection_options(): """ Copy the selection field options and create options for the selection field. """ Option = Pool().get('product.attribute.selection_option') cursor = Transaction().cursor cursor.execute( """ SELECT id, selection FROM product_attribute WHERE type_='selection' """ ) # Key value map attribute_kv_map = defaultdict(dict) for row in cursor.fetchall(): id, selection = row for k, v in get_selection_json(selection): option = Option( name=v, attribute=id ) option.save() attribute_kv_map[id][k] = option.id print "Created selection values for %d attributes" % len(attribute_kv_map) return attribute_kv_map
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor super(ProductMedia, cls).__register__(module_name) media_table = cls.__table__() if TableHandler.table_exist(cursor, 'product_product_imageset'): # Migrate data from ProductImageSet table to ProductMedia table imageset_table = Table('product_product_imageset') cursor.execute(*media_table.insert( columns=[ media_table.sequence, media_table.product, media_table.template, media_table.static_file, ], values=imageset_table.select( Literal(10), imageset_table.product, imageset_table.template, imageset_table.image ) )) TableHandler.drop_table( cursor, 'product.product.imageset', 'product_product_imageset', cascade=True )
def get_cash(self): pool = Pool() Date = pool.get('ir.date') AccountType = pool.get('account.account.type') today = Date.today() company = Transaction().context.get('company') balance = Decimal('0.0') transaction = Transaction() context = Transaction().context total_cash = Decimal('0.0') if self.is_consolidated: companies = context.get('companies',[]) for company in context.get('companies', []): with transaction.set_context(company=company['id']): cash = Decimal('0.0') accounts = AccountType.search([('company','=',company['id']), ('name','=','10. Efectivo y Equivalencias de Efectivo') ]) if len(accounts)==1: cash = accounts[0].amount * Decimal('1.0') total_cash += cash return total_cash else: accounts = AccountType.search([('company','=',company), ('name','=','10. Efectivo y Equivalencias de Efectivo')]) if len(accounts)==1: balance = accounts[0].amount * Decimal('1.0') return balance
def default_date_account(self ): context = Transaction().context if context.get('date_account'): return context.get('date_account') elif context.get('current_date'): return context.get('current_date') return datetime.datetime.now()
def get_expenses(self): pool = Pool() Date = pool.get('ir.date') AccountType = pool.get('account.account.type') today = Date.today() transaction = Transaction() context = Transaction().context total_expense = expense = Decimal('0.0') if self.is_consolidated: companies = context.get('companies',[]) for company in context.get('companies', []): with transaction.set_context(company=company['id']): expense = Decimal('0.0') expenses = AccountType.search([('company','=',company['id']), ('name','=','GASTOS FINANCIEROS') ]) if len(expenses)==1: expense = expenses[0].amount * Decimal('1.0') total_expense += expense return total_expense else: company = Transaction().context.get('company') expense = Decimal('0.0') expenses = AccountType.search([('company','=',company), ('name','=','GASTOS FINANCIEROS')]) if len(expenses)==1: expense = expenses[0].amount * Decimal('1.0') return expense
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') sql_table = cls.__table__() super(PaymentTermLine, cls).__register__(module_name) cursor = Transaction().cursor table = TableHandler(cursor, cls, module_name) # Migration from 1.0 percent change into percentage if table.column_exist('percent'): cursor.execute(*sql_table.update( columns=[sql_table.percentage], values=[sql_table.percent * 100])) table.drop_column('percent', exception=True) # Migration from 2.2 if table.column_exist('delay'): cursor.execute(*sql_table.update( columns=[sql_table.day], values=[31], where=sql_table.delay == 'end_month')) table.drop_column('delay', exception=True) lines = cls.search([]) for line in lines: if line.percentage: cls.write([line], { 'divisor': cls.round(Decimal('100.0') / line.percentage, cls.divisor.digits[1]), }) # Migration from 2.4: drop required on sequence table.not_null_action('sequence', action='remove')
def default_currency_digits(self): company_obj = self.pool.get("company.company") context = Transaction().context if context.get("company"): company = company_obj.browse(context["company"]) return company.currency.digits return 2
def init(self, module_name): cursor = Transaction().cursor # Migration from 1.6: corrected misspelling of ounce (was once) cursor.execute("UPDATE ir_model_data "\ "SET fs_id = REPLACE(fs_id, 'uom_once', 'uom_ounce') "\ "WHERE fs_id = 'uom_once' AND module = 'product'") super(Uom, self).init(module_name)
def get_creationdate(cls, uri, cache=None): Party = Pool().get('party.party') party = Party.__table__() party_id = cls.vcard(uri) cursor = Transaction().cursor if party_id is None: raise DAV_NotFound if party_id: if cache is not None: cache.setdefault('_contact', {}) ids = cache['_contact'].keys() if party_id not in ids: ids.append(party_id) elif 'creationdate' in cache['_contact'][party_id]: return cache['_contact'][party_id]['creationdate'] else: ids = [party_id] res = None for sub_ids in grouped_slice(ids): red_sql = reduce_ids(party.id, sub_ids) cursor.execute(*party.select(party.id, Extract('EPOCH', party.create_date), where=red_sql)) for party_id2, date in cursor.fetchall(): if party_id2 == party_id: res = date if cache is not None: cache['_contact'].setdefault(party_id2, {}) cache['_contact'][party_id2]['creationdate'] = date if res is not None: return res return super(Collection, cls).get_creationdate(uri, cache=cache)
def restore_default_party_lang_from_4_2(cls): from trytond.transaction import Transaction from sql import Null, Table, Cast from sql.operators import Concat from trytond.pool import Pool TableHandler = backend.get('TableHandler') if not TableHandler.table_exist('ir_property'): return pool = Pool() property = Table('ir_property') Lang = pool.get('ir.lang') field = pool.get('ir.model.field').__table__() lang = Lang.__table__() cursor = Transaction().connection.cursor() query_table = property.join(lang, condition=( property.value == Concat('ir.lang,', Cast(lang.id, 'VARCHAR')) )).join(field, condition=((property.field == field.id) & (field.name == 'lang'))) cursor.execute( *query_table.select(lang.id, where=property.res == Null)) result = cursor.fetchone() if result: result = list(result) default_lang = Lang(result[0]) print('Default Language restored [%s]' % default_lang.rec_name) pool.get('party.configuration.party_lang' ).create([{'party_lang': default_lang}]) else: print('No default language on party configuration found')
def get_pending_amount(cls, agents, name): pool = Pool() Commission = pool.get('commission') commission = Commission.__table__() cursor = Transaction().connection.cursor() ids = [a.id for a in agents] amounts = dict.fromkeys(ids, None) for sub_ids in grouped_slice(ids): where = reduce_ids(commission.agent, sub_ids) where &= commission.invoice_line == Null query = commission.select(commission.agent, Sum(commission.amount), where=where, group_by=commission.agent) cursor.execute(*query) amounts.update(dict(cursor.fetchall())) digits = cls.pending_amount.digits exp = Decimal(str(10.0 ** -digits[1])) for agent_id, amount in amounts.items(): if amount: # SQLite uses float for SUM if not isinstance(amount, Decimal): amount = Decimal(str(amount)) amounts[agent_id] = amount.quantize(exp) return amounts
def count(self): "Return the count of the Items" from trytond.transaction import Transaction # XXX: Ideal case should make a copy of Select query # # https://code.google.com/p/python-sql/issues/detail?id=22 query = self.query query.columns = (Count(Distinct(self.primary_table.id)), ) cursor = Transaction().connection.cursor() # temporarily remove order_by order_by = query.order_by query.order_by = None try: cursor.execute(*query) finally: # XXX: This can be removed when SQL queries can be copied # See comment above query.order_by = order_by res = cursor.fetchone() if res: return res[0] # There can be a case when query return None and then count # will be zero return 0
def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor sql_table = cls.__table__() # Migration from 1.8: new field company table = TableHandler(cursor, cls, module_name) company_exist = table.column_exist('company') super(Statement, cls).__register__(module_name) # Migration from 1.8: fill new field company if not company_exist: offset = 0 limit = cursor.IN_MAX statements = True while statements: statements = cls.search([], offset=offset, limit=limit) offset += limit for statement in statements: cls.write([statement], { 'company': statement.journal.company.id, }) table = TableHandler(cursor, cls, module_name) table.not_null_action('company', action='add') # Migration from 3.2: remove required on start/end balance table.not_null_action('start_balance', action='remove') table.not_null_action('end_balance', action='remove') # Migration from 3.2: add required name cursor.execute(*sql_table.update([sql_table.name], [sql_table.id.cast(cls.name.sql_type().base)], where=sql_table.name == None))
def confirmed(cls, surgeries): surgery_id = surgeries[0] Operating_room = Pool().get('gnuhealth.hospital.or') cursor = Transaction().cursor # Operating Room and end surgery time check if (not surgery_id.operating_room or not surgery_id.surgery_end_date): cls.raise_user_error("Operating Room and estimated end time " "are needed in order to confirm the surgery") or_id = surgery_id.operating_room.id cursor.execute("SELECT COUNT(*) \ FROM gnuhealth_surgery \ WHERE (surgery_date::timestamp,surgery_end_date::timestamp) \ OVERLAPS (timestamp %s, timestamp %s) \ AND (state = %s or state = %s) \ AND operating_room = CAST(%s AS INTEGER) ", (surgery_id.surgery_date, surgery_id.surgery_end_date, 'confirmed', 'in_progress', str(or_id))) res = cursor.fetchone() if (surgery_id.surgery_end_date < surgery_id.surgery_date): cls.raise_user_error("The Surgery end date must later than the \ Start") if res[0] > 0: cls.raise_user_error('or_is_not_available') else: cls.write(surgeries, {'state': 'confirmed'})
def get_translation_4_nereid(cls, module, ttype, lang, source): "Return translation for source" ttype = unicode(ttype) lang = unicode(lang) source = unicode(source) cache_key = (lang, ttype, source, module) trans = cls._nereid_translation_cache.get(cache_key, -1) if trans != -1: return trans cursor = Transaction().cursor table = cls.__table__() where = ( (table.lang == lang) & (table.type == ttype) & (table.value != '') & (table.value != None) & (table.fuzzy == False) & (table.src == source) ) if module is not None: where &= (table.module == module) cursor.execute(*table.select(table.value, where=where)) res = cursor.fetchone() if res: cls._nereid_translation_cache.set(cache_key, res[0]) return res[0] else: cls._nereid_translation_cache.set(cache_key, False) return None
def __register__(cls, module_name): pool = Pool() Sequence = pool.get('account.fiscalyear.invoice_sequence') sequence = Sequence.__table__() sql_table = cls.__table__() super(FiscalYear, cls).__register__(module_name) cursor = Transaction().connection.cursor() table = cls.__table_handler__(module_name) # Migration from 4.2: Use Match pattern for sequences if (table.column_exist('in_invoice_sequence') and table.column_exist('in_credit_note_sequence') and table.column_exist('out_invoice_sequence') and table.column_exist('out_credit_note_sequence')): cursor.execute(*sequence.insert(columns=[ sequence.sequence, sequence.fiscalyear, sequence.company, sequence.out_invoice_sequence, sequence.out_credit_note_sequence, sequence.in_invoice_sequence, sequence.in_credit_note_sequence], values=sql_table.select( Literal(20), sql_table.id, sql_table.company, sql_table.out_invoice_sequence, sql_table.out_credit_note_sequence, sql_table.in_invoice_sequence, sql_table.in_credit_note_sequence))) table.drop_column('out_invoice_sequence') table.drop_column('out_credit_note_sequence') table.drop_column('in_invoice_sequence') table.drop_column('in_credit_note_sequence')
def confirmed(cls, registrations): registration_id = registrations[0] Bed = Pool().get("gnuhealth.hospital.bed") cursor = Transaction().cursor bed_id = registration_id.bed.id cursor.execute( "SELECT COUNT(*) \ FROM gnuhealth_inpatient_registration \ WHERE (hospitalization_date::timestamp,discharge_date::timestamp) \ OVERLAPS (timestamp %s, timestamp %s) \ AND (state = %s or state = %s) \ AND bed = CAST(%s AS INTEGER) ", ( registration_id.hospitalization_date, registration_id.discharge_date, "confirmed", "hospitalized", str(bed_id), ), ) res = cursor.fetchone() if registration_id.discharge_date.date() < registration_id.hospitalization_date.date(): cls.raise_user_error( "The Discharge date must later than the \ Admission" ) if res[0] > 0: cls.raise_user_error("bed_is_not_available") else: cls.write(registrations, {"state": "confirmed"}) Bed.write([registration_id.bed], {"state": "reserved"})
def test_integer_required(self): 'Test required integer' pool = Pool() IntegerRequired = pool.get('test.import_data.integer_required') transaction = Transaction() self.assertEqual(IntegerRequired.import_data(['integer'], [['1']]), 1) self.assertEqual(IntegerRequired.import_data(['integer'], [['-1']]), 1) self.assertRaises(UserError, IntegerRequired.import_data, ['integer'], [['']]) transaction.rollback() self.assertEqual(IntegerRequired.import_data(['integer'], [['1'], ['2']]), 2) self.assertRaises(ValueError, IntegerRequired.import_data, ['integer'], [['1.1']]) self.assertRaises(ValueError, IntegerRequired.import_data, ['integer'], [['-1.1']]) self.assertRaises(ValueError, IntegerRequired.import_data, ['integer'], [['foo']]) self.assertEqual(IntegerRequired.import_data(['integer'], [['0']]), 1)
def add_fk(self, column_name, reference, on_delete=None): if on_delete is not None: on_delete = on_delete.upper() else: on_delete = 'SET NULL' cursor = Transaction().connection.cursor() name = self.table_name + '_' + column_name + '_fkey' name = truncate_constraint_name(name) cursor.execute('SELECT 1 ' 'FROM information_schema.key_column_usage ' 'WHERE table_name = %s AND table_schema = %s ' 'AND constraint_name = %s', (self.table_name, self.table_schema, name)) add = False if not cursor.rowcount: add = True elif self._fk_deltypes.get(column_name) != on_delete: self.drop_fk(column_name) add = True if add: cursor.execute('ALTER TABLE "' + self.table_name + '" ' 'ADD CONSTRAINT "' + name + '" ' 'FOREIGN KEY ("' + column_name + '") ' 'REFERENCES "' + reference + '" ' 'ON DELETE ' + on_delete) self._update_definitions(constraints=True)
def test_float_required(self): 'Test required float' pool = Pool() FloatRequired = pool.get('test.import_data.float_required') transaction = Transaction() self.assertEqual(FloatRequired.import_data(['float'], [['1.1']]), 1) self.assertEqual(FloatRequired.import_data(['float'], [['-1.1']]), 1) self.assertEqual(FloatRequired.import_data(['float'], [['1']]), 1) self.assertRaises(UserError, FloatRequired.import_data, ['float'], [['']]) transaction.rollback() self.assertEqual(FloatRequired.import_data(['float'], [['1.1'], ['2.2']]), 2) self.assertRaises(ValueError, FloatRequired.import_data, ['float'], [['foo']]) self.assertEqual(FloatRequired.import_data(['float'], [['0']]), 1) self.assertEqual(FloatRequired.import_data(['float'], [['0.0']]), 1)
def test_numeric_required(self): 'Test required numeric' pool = Pool() NumericRequired = pool.get('test.import_data.numeric_required') transaction = Transaction() self.assertEqual(NumericRequired.import_data(['numeric'], [['1.1']]), 1) self.assertEqual(NumericRequired.import_data(['numeric'], [['-1.1']]), 1) self.assertEqual(NumericRequired.import_data(['numeric'], [['1']]), 1) self.assertRaises(UserError, NumericRequired.import_data, ['numeric'], [['']]) transaction.rollback() self.assertEqual(NumericRequired.import_data(['numeric'], [['1.1'], ['2.2']]), 2) self.assertRaises(InvalidOperation, NumericRequired.import_data, ['numeric'], [['foo']]) self.assertEqual(NumericRequired.import_data(['numeric'], [['0']]), 1) self.assertEqual(NumericRequired.import_data(['numeric'], [['0.0']]), 1)
def wrap(self, *args, **kwargs): message_res = met(self, *args, **kwargs) if self.logger_enabled: message_req = self.incoming_message logger.debug("Saving transition:\nIN: %s\nOUT: %s\nHandler: %s\n" % (message_req, message_res, self.__class__.__name__)) transaction = Transaction() logger.debug("Starting db transaction for domain:%s" % self.pool_manager.get_domain()) transaction.start(self.pool_manager.get_domain(), 0) logger.debug("Connecting to table") hl7_message_logger = self.pool_manager.get_table("hl7.message_logger") logger.debug("Preparing query for table:::%s" % hl7_message_logger) cursor = transaction.cursor insert_columns = [hl7_message_logger.create_uid, hl7_message_logger.create_date, hl7_message_logger.creation_date, hl7_message_logger.request, hl7_message_logger.response, hl7_message_logger.handler_module] insert_values = [transaction.user, Now(), Now(), message_req, message_res[1:-2], self.__class__.__name__] cursor.execute(*hl7_message_logger.insert(insert_columns, [insert_values])) cursor.execute("commit") logger.debug("Query executed") transaction.stop() return message_res
def alter_type(self, column_name, column_type): cursor = Transaction().connection.cursor() cursor.execute('ALTER TABLE `%s` ' 'MODIFY COLUMN `%s` %s' % (self.table_name, column_name, self._column_definition(column_name, typname=column_type))) self._update_definitions(columns=True)
def ejecutar_nc(self): if self.start.tipoemi=='porid': query = '''SELECT ac.id, ac.number from account_invoice ac left join sigcoop_suministro_suministro ss on ss.id=ac.suministro where ac.state in ('posted') and ac.type = 'out_invoice' and ac.id between \'%s\' and \'%s\' and ss.servicio = \'%s\' order by ac.id ''' % (self.start.desdeid, self.start.hastaid, self.start.servicio.id) elif self.start.consumo_cero: #genero NC para las facturas con cero consumo query = '''SELECT ac.id, ac.number from account_invoice ac left join sigcoop_suministro_suministro ss on ss.id=ac.suministro join sigcoop_consumos_consumo c on c.invoice = ac.id where ac.state in ('posted') and ac.type = 'out_invoice' and c.consumo_neto = 0 and ss.servicio = \'%s\' and ac.periodo = \'%s\' order by ac.id ''' % (self.start.servicio.id, self.start.periodo.id) else: query = '''SELECT ac.id, ac.number from account_invoice ac left join sigcoop_suministro_suministro ss on ss.id=ac.suministro where ac.state in ('posted') and ac.type = 'out_invoice' and ss.servicio = \'%s\' and ss.lista_precios = \'%s\' and ac.periodo = \'%s\' order by ac.id ''' % (self.start.servicio.id, self.start.lista_precios.id, self.start.periodo.id) cursor = Transaction().cursor cursor.execute(query) facturas = cursor.fetchall() self.exito.resumen = "Se van a generar notas de creditos para las siguientes facturas: %s" % map(lambda x: str(x[1]), facturas) return 'exito'
def __register__(cls, z_fix__invoice_ar__sale_pos): #super(AfipWSTransaction, cls).__register__(z_fix__invoice_ar__sale_pos) TableHandler = backend.get('TableHandler') cursor = Transaction().cursor table = TableHandler(cursor, cls, z_fix__invoice_ar__sale_pos) cursor.execute("ALTER TABLE account_invoice_ar_afip_transaction\ DROP CONSTRAINT IF EXISTS account_invoice_ar_afip_transaction_invoice_fkey;")
def column_rename(self, old_name, new_name, exception=False): cursor = Transaction().connection.cursor() if self.column_exist(old_name) and not self.column_exist(new_name): temp_table = "_temp_%s" % self.table_name TableHandler.table_rename(self.table_name, temp_table) new_table = TableHandler(self._model, history=self.history) for column, (notnull, hasdef, size, typname) in self._columns.iteritems(): if column == old_name: column = new_name new_table.add_raw_column(column, typname, False, field_size=size) new_columns = new_table._columns.keys() old_columns = [x if x != old_name else new_name for x in new_columns] cursor.execute( ( 'INSERT INTO "%s" (' + ",".join('"%s"' % x for x in new_columns) + ") SELECT " + ",".join('"%s"' % x for x in old_columns) + " " + 'FROM "%s"' ) % (self.table_name, temp_table) ) cursor.execute('DROP TABLE "%s"' % temp_table) self._update_definitions() elif exception and self.column_exist(new_name): raise Exception( "Unable to rename column %s.%s to %s.%s: " "%s.%s already exist!" % (self.table_name, old_name, self.table_name, new_name, self.table_name, new_name) )
def check_date_overlap(self): cursor = Transaction().cursor if self.state != "done": return True cursor.execute( "SELECT id " "FROM stock_forecast " "WHERE ((from_date <= %s AND to_date >= %s) " "OR (from_date <= %s AND to_date >= %s) " "OR (from_date >= %s AND to_date <= %s)) " "AND warehouse = %s " "AND destination = %s " "AND state = 'done' " "AND company = %s " "AND id != %s", ( self.from_date, self.from_date, self.to_date, self.to_date, self.from_date, self.to_date, self.warehouse.id, self.destination.id, self.company.id, self.id, ), ) forecast_id = cursor.fetchone() if forecast_id: second = self.__class__(forecast_id[0]) self.raise_user_error("date_overlap", {"first": self.rec_name, "second": second.rec_name})
def db_default(self, column_name, value): cursor = Transaction().connection.cursor() cursor.execute('ALTER TABLE `%s` ' 'MODIFY COLUMN `%s` %s' % (self.table_name, column_name, self._column_definition(column_name, default=value))) self._update_definitions(columns=True)
def test_check_timestamp(self): 'Test check timestamp' pool = Pool() ModelsqlTimestamp = pool.get('test.modelsql.timestamp') transaction = Transaction() # cursor must be committed between each changes otherwise NOW() returns # always the same timestamp. cursor = transaction.cursor record, = ModelsqlTimestamp.create([{}]) cursor.commit() timestamp = ModelsqlTimestamp.read([record.id], ['_timestamp'])[0]['_timestamp'] if backend.name() in ('sqlite', 'mysql'): # timestamp precision of sqlite is the second time.sleep(1) ModelsqlTimestamp.write([record], {}) cursor.commit() transaction.timestamp[str(record)] = timestamp self.assertRaises(ConcurrencyException, ModelsqlTimestamp.write, [record], {}) transaction.timestamp[str(record)] = timestamp self.assertRaises(ConcurrencyException, ModelsqlTimestamp.delete, [record]) transaction.timestamp.pop(str(record), None) ModelsqlTimestamp.write([record], {}) cursor.commit() ModelsqlTimestamp.delete([record]) cursor.commit()
def __register__(cls, module_name): cursor = Transaction().cursor # Migration from 1.6: corrected misspelling of ounce (was once) cursor.execute("UPDATE ir_model_data " "SET fs_id = REPLACE(fs_id, 'uom_once', 'uom_ounce') " "WHERE fs_id = 'uom_once' AND module = 'product'") super(Uom, cls).__register__(module_name)
def wrapper(*args, **kwargs): with Transaction().set_context(active_test=False): return func(*args, **kwargs)
def table_exist(table_name): cursor = Transaction().connection.cursor() cursor.execute( "SELECT sql FROM sqlite_master " "WHERE type = 'table' AND name = ?", (table_name, )) res = cursor.fetchone() if not res: return False sql, = res # Migration from 1.6 add autoincrement if 'AUTOINCREMENT' not in sql.upper(): temp_sql = sql.replace(table_name, '_temp_%s' % table_name) cursor.execute(temp_sql) cursor.execute('PRAGMA table_info("' + table_name + '")') columns = [ '"%s"' % column for _, column, _, _, _, _ in cursor.fetchall() ] cursor.execute(('INSERT INTO "_temp_%s" ' '(' + ','.join(columns) + ') ' 'SELECT ' + ','.join(columns) + ' FROM "%s"') % (table_name, table_name)) cursor.execute('DROP TABLE "%s"' % table_name) new_sql = sql.replace('PRIMARY KEY', 'PRIMARY KEY AUTOINCREMENT') cursor.execute(new_sql) cursor.execute( ('INSERT INTO "%s" ' '(' + ','.join(columns) + ') ' 'SELECT ' + ','.join(columns) + ' FROM "_temp_%s"') % (table_name, table_name)) cursor.execute('DROP TABLE "_temp_%s"' % table_name) return True
def complete_lines(cls, inventories, fill=True): ''' Complete or update the inventories ''' pool = Pool() Line = pool.get('stock.inventory.line') Product = pool.get('product.product') grouping = cls.grouping() to_create, to_write = [], [] for inventory in inventories: # Once done computation is wrong because include created moves if inventory.state == 'done': continue # Compute product quantities if fill: product_ids = None else: product_ids = [l.product.id for l in inventory.lines] with Transaction().set_context(stock_date_end=inventory.date): pbl = Product.products_by_location( [inventory.location.id], grouping=grouping, grouping_filter=(product_ids, )) # Index some data product2type = {} product2consumable = {} for product in Product.browse([line[1] for line in pbl]): product2type[product.id] = product.type product2consumable[product.id] = product.consumable # Update existing lines for line in inventory.lines: if line.product.type != 'goods': Line.delete([line]) continue key = (inventory.location.id, ) + line.unique_key if key in pbl: quantity = pbl.pop(key) else: quantity = 0.0 values = line.update_values4complete(quantity) if values: to_write.extend(([line], values)) if not fill: continue # Create lines if needed for key, quantity in pbl.items(): product_id = key[grouping.index('product') + 1] if (product2type[product_id] != 'goods' or product2consumable[product_id]): continue if not quantity: continue values = Line.create_values4complete(inventory, quantity) for i, fname in enumerate(grouping, 1): values[fname] = key[i] to_create.append(values) if to_create: Line.create(to_create) if to_write: Line.write(*to_write)
def default_company(): return Transaction().context.get('company')
def do_open(self): pool = Pool() UomCategory = Pool().get('product.category') Hrp_Order = Pool().get('hrp_order_point.purchaser_reference') OrderPoint = pool.get('stock.order_point') PurchaseNewProduct = pool.get("hrp_new_product.new_product") orderpoints = OrderPoint.search([ ('type', '=', 'internal') ]) Date = Pool().get('ir.date') Product = pool.get('product.product') delete_move = PurchaseNewProduct.search([]) PurchaseNewProduct.delete(delete_move) for orderpoint in orderpoints: order_product_id = [] # 订货点产品id try: party = orderpoint.product.template.product_suppliers[0].party.id except: party = None unit_price = orderpoint.product.cost_price warehouse_location = orderpoint.warehouse_location retrieve_the_code = orderpoint.retrieve_the_code secondary = orderpoint.secondary storage_location = orderpoint.provisioning_location.id # 来自库存低 provisioning_location = orderpoint.storage_location.id # 到达库存地 product = orderpoint.product.id # 产品 interim = orderpoint.product.interim # 产品 hrp_order = Hrp_Order.search([ ('warehouse', '=', secondary), ('product', '=', product), ]) if hrp_order: seven_days = hrp_order[0].seven_days else: seven_days = 0 purchase_new = OrderPoint.search([ ('storage_location', '=', provisioning_location), ]) if purchase_new: for i in purchase_new: order_product_id.append(i.product.id) categories = [i.id for i in orderpoint.product.categories] uom_category = UomCategory.search([('id', '=', categories[0])]) uom_name = uom_category[0].name code = orderpoint.product.code # 编码 drug_specifications = orderpoint.product.drug_specifications # 规格 a_charge = orderpoint.product.template.a_charge # 件装量 is_direct_sending = orderpoint.product.template.is_direct_sending # 直送 unit = orderpoint.unit.id # 单位 with Transaction().set_context(stock_date_end=Date.today(), stock_assign=True): quantities = Product.products_by_location([provisioning_location], [product], with_childs=True) if quantities.values(): stock_level = [v for v in quantities.values()][0] else: stock_level = 0 proposal = seven_days - stock_level lv = {} lv['drug_specifications'] = drug_specifications lv['stock_level'] = int(stock_level) lv['warehouse_location'] = warehouse_location if uom_name == u'中成药': lv['drug_type'] = '01' if uom_name == u'中草药': lv['drug_type'] = '02' if uom_name == u'原料药': lv['drug_type'] = '04' if uom_name == u'敷药': lv['drug_type'] = '05' if uom_name == u'西药': lv['drug_type'] = '00' if uom_name == u'颗粒中': lv['drug_type'] = '03' if uom_name == u'同位素': lv['drug_type'] = '07' if uom_name == '': lv['drug_type'] = '06' lv['product'] = product lv['code'] = code if a_charge == None: lv['a_charge'] = '' else: lv['a_charge'] = str(a_charge) lv['from_location'] = storage_location lv['retrieve_the_code'] = str(retrieve_the_code) lv['to_location'] = provisioning_location lv['is_direct_sending'] = is_direct_sending lv['unit_price'] = unit_price lv['uom'] = unit lv['outpatient_7days'] = seven_days lv['party'] = party # 供应商 lv['proposal'] = proposal # 建议采购量 if interim == '1' or '00': lv['interim'] = '1' elif interim == '01': lv['interim'] == '2' else: lv['interim'] = interim PurchaseNew = PurchaseNewProduct.search([ ('to_location', '=', provisioning_location), ('product', '=', product) ]) if PurchaseNew: PurchaseNewProduct.write(PurchaseNew, lv) else: PurchaseNewProduct.create([lv])
def default_plant(): return Transaction().context.get('plant', None)
def get_context(cls, records, data): report_context = super(FinancialIndicator, cls).get_context(records, data) pool = Pool() Company = pool.get('company.company') Account = pool.get('analytic_account.account') company = Company(data['company']) capital_operativo = liquidez = sosten_propio = 0 with Transaction().set_context( company=data['company'], date=data['end_date'], cumulate=True, posted=True, ): accounts = Account.search([('type', '=', 'root'), ('company', '=', company)]) if len(accounts) == 3: capital_operativo = Account(accounts[0].id) liquidez = Account(accounts[1].id) sosten_propio = Account(accounts[2].id) capital_actual = Account(capital_operativo.childs[0].id) capital_recomendado = Account(capital_operativo.childs[1].id) caja_y_bancos = Account(liquidez.childs[0].id) pasivo_corriente = Account(liquidez.childs[1].id) activo_corriente = Account(capital_actual.childs[0].id) report_context['company'] = company report_context['digits'] = company.currency.digits #report_context['fiscalyear'] = data['fiscalyear'] report_context['start_date'] = data['start_date'] report_context['end_date'] = data['end_date'] report_context['capital_operativo'] = capital_operativo report_context['liquidez'] = liquidez report_context['sosten_propio'] = sosten_propio report_context['capital_actual'] = capital_actual report_context['capital_recomendado'] = capital_recomendado report_context['caja_y_bancos'] = caja_y_bancos report_context['pasivo_corriente'] = pasivo_corriente report_context['activo_corriente'] = activo_corriente report_context['indice_capital_operativo'] = round( capital_operativo.financial_indicator, 2) report_context['indice_liquidez'] = round( liquidez.financial_indicator, 2) with Transaction().set_context( company=data['company'], start_date=data['start_date'], end_date=data['end_date'], cumulate=True, posted=True, ): accounts = Account.search([('type', '=', 'root'), ('company', '=', company)]) if len(accounts) == 3: sosten_propio = Account(accounts[2].id) ingresos = Account(sosten_propio.childs[0].id) gastos = Account(sosten_propio.childs[1].id) report_context['ingresos'] = ingresos report_context['gastos'] = gastos report_context['indice_sosten_propio'] = round( sosten_propio.financial_indicator, 2) return report_context
def default_module(): return Transaction().context.get('module') or ''
def timesheet_employees(request, pool): User = pool.get('res.user') user = User(Transaction().user) return [{'id': e.id, 'name': e.rec_name} for e in user.employees]
def get_current_asset(self): pool = Pool() Date = pool.get('ir.date') AccountType = pool.get('account.account.type') today = Date.today() company = Transaction().context.get('company') transaction = Transaction() context = Transaction().context total_current_asset = current_asset = Decimal('0.0') today = Date.today() company = Transaction().context.get('company') to_date = Transaction().context.get('to_date') if self.is_consolidated: companies = context.get('companies', []) date = today if to_date is None else to_date for company in context.get('companies', []): with transaction.set_context(company=company['id'], posted=True, cumulate=True, date=date, to_date=date, from_date=None): current_asset = Decimal('0.0') current_assets = AccountType.search([ ('company', '=', company['id']), ('name', '=', '1) ACTIVOS CORRIENTES') ]) if len(current_assets) == 1: current_asset = current_assets[0].amount * Decimal( '1.0') total_current_asset += current_asset return total_current_asset else: date = today if to_date is None else to_date with transaction.set_context( posted=True, cumulate=True, date=date, to_date=date, from_date=None, ): current_assets = AccountType.search([ ('company', '=', company), ('name', '=', '1) ACTIVOS CORRIENTES') ]) if len(current_assets) == 1: current_asset = current_assets[0].amount * Decimal('1.0') return current_asset
def test_9999_transaction_safety(self): """ Test the transaction safety of email sender. * This test is expected to work only on postgres * This should be the last test since this breaks the rule to commit within the test creating records """ EmailQueue = POOL.get('email.queue') with Transaction().start(DB_NAME, USER, CONTEXT) as transaction: # Put some emails in queue f = Faker() for item in xrange(10): EmailQueue.queue_mail(f.email(), f.email(), f.text()) transaction.cursor.commit() # A queue is used to handle the ones which errored. searialization_error_q = Queue.Queue(3) # A fake smtp server which just sleeps for 5 seconds when sendmail # is called. smtp_server = stub(sendmail=lambda *args: time.sleep(5)) def threaded_send_email(email, smtp_server): """ A new threaded email sender. This is required because there is no transaction in the new thread that is spawned and sendemail tries to create a new cursor from an existing transaction. So create the new transaction here, refresh the active record objects and call sendmail like the cron would have """ with Transaction().start(DB_NAME, USER, context=CONTEXT): # email active record is from old transaction, so referesh it. email = EmailQueue(email.id) database = backend.get('database') try: # Now send the email email.send(smtp_server) except database.DatabaseOperationalError: # This specific email could not be sent because of a # transaction serialization error searialization_error_q.put(email.id) with Transaction().start(DB_NAME, USER, CONTEXT) as transaction: email1, email2 = EmailQueue.search( [('state', '=', 'outbox')], limit=2 ) t1 = threading.Thread( target=threaded_send_email, args=(email1, smtp_server) ) t2 = threading.Thread( target=threaded_send_email, args=(email2, smtp_server) ) # create another thread with **email1** again. This is expected to # fail, though even t1 might fail and this would succeed. Either # way we dont care because we only make sure that there is 1 # failure and that both email1 and 2 are sent. t3 = threading.Thread( target=threaded_send_email, args=(email1, smtp_server) ) # start all the threads. Since there is a time.sleep of 5 seconds # in the sendmail call, it simulates a case of delayed execution. # thread3 is guaranteed to start within 5 seconds of thread1 and # the error that is asserted also specifically looks for a # concurrency triggered transaction serialisation exception. t1.start() t2.start() t3.start() # Blockingly wait till the threads complete t1.join() t2.join() t3.join() # 1: Assert that the email1's ID is in the serialization_error_q self.assertEqual(searialization_error_q.qsize(), 1) # 1B: Ensure that the ID is of email1 which was the one sent twice self.assertEqual(searialization_error_q.get(), email1.id) # 2: Assert that both email 1 and 2 have the sent state with Transaction().start(DB_NAME, USER, CONTEXT) as transaction: self.assertEqual(EmailQueue(email1.id).state, 'sent') self.assertEqual(EmailQueue(email2.id).state, 'sent') # 3: Assert that there are 8 emails left in outbox with Transaction().start(DB_NAME, USER, CONTEXT) as transaction: self.assertEqual( EmailQueue.search([('state', '=', 'outbox')], count=True), 8 )
def default_user(): return Transaction().user
def test_0030_test_transaction_auth_only(self): """ Test auth_only transaction """ self.setup_defaults() with Transaction().set_context({'company': self.company.id}): # Case I: Payment Profile transaction1, = self.PaymentTransaction.create([{ 'party': self.party1.id, 'address': self.party1.addresses[0].id, 'payment_profile': self.payment_profile.id, 'gateway': self.auth_net_gateway.id, 'amount': random.randint(6, 10), 'credit_account': self.party1.account_receivable.id, }]) self.assert_(transaction1) self.assertEqual(transaction1.state, 'draft') # Authorize transaction self.PaymentTransaction.authorize([transaction1]) self.assertEqual(transaction1.state, 'authorized') # Case II: No Payment Profile transaction2, = self.PaymentTransaction.create([{ 'party': self.party2.id, 'address': self.party2.addresses[0].id, 'gateway': self.auth_net_gateway.id, 'amount': random.randint(1, 5), 'credit_account': self.party2.account_receivable.id, }]) self.assert_(transaction2) self.assertEqual(transaction2.state, 'draft') # Authorize transaction transaction2.authorize_authorize_net(card_info=self.card_data1) self.assertEqual(transaction2.state, 'authorized') # Case III: Transaction Failure on invalid amount transaction3, = self.PaymentTransaction.create([{ 'party': self.party1.id, 'address': self.party1.addresses[0].id, 'payment_profile': self.payment_profile.id, 'gateway': self.auth_net_gateway.id, 'amount': 0, 'credit_account': self.party1.account_receivable.id, }]) self.assert_(transaction3) self.assertEqual(transaction3.state, 'draft') # Authorize transaction self.PaymentTransaction.authorize([transaction3]) self.assertEqual(transaction3.state, 'failed') # Case IV: Assert error when new customer is there with # no payment profile and card info transaction3, = self.PaymentTransaction.create([{ 'party': self.party3.id, 'address': self.party3.addresses[0].id, 'gateway': self.auth_net_gateway.id, 'amount': random.randint(1, 5), 'credit_account': self.party3.account_receivable.id, }]) self.assert_(transaction3) self.assertEqual(transaction3.state, 'draft') # Authorize transaction with self.assertRaises(UserError): self.PaymentTransaction.authorize([transaction3])
def wrapper(*args, **kwargs): EmailQueue = POOL.get('email.queue') with Transaction().start(DB_NAME, USER, CONTEXT) as transaction: EmailQueue.delete(EmailQueue.search([])) transaction.cursor.commit() return function(*args, **kwargs)
def test_check_timestamp(self): 'Test check timestamp' pool = Pool() ModelsqlTimestamp = pool.get('test.modelsql.timestamp') transaction = Transaction() # transaction must be committed between each changes otherwise NOW() # returns always the same timestamp. record, = ModelsqlTimestamp.create([{}]) transaction.commit() timestamp = ModelsqlTimestamp.read([record.id], ['_timestamp'])[0]['_timestamp'] if backend.name() in ('sqlite', 'mysql'): # timestamp precision of sqlite is the second time.sleep(1) ModelsqlTimestamp.write([record], {}) transaction.commit() transaction.timestamp[str(record)] = timestamp self.assertRaises(ConcurrencyException, ModelsqlTimestamp.write, [record], {}) transaction.timestamp[str(record)] = timestamp self.assertRaises(ConcurrencyException, ModelsqlTimestamp.delete, [record]) transaction.timestamp.pop(str(record), None) ModelsqlTimestamp.write([record], {}) transaction.commit() ModelsqlTimestamp.delete([record]) transaction.commit()
def test_0060_test_duplicate_payment_profile(self): """ Test that workflow is not effected if duplicate payment profile is there on authorize.net """ self.setup_defaults() customer = authorize.Customer.create() authorize.CreditCard.create(customer.customer_id, { 'card_number': '4111111111111111', 'card_code': '523', 'expiration_date': '05/2023', 'billing': self.party2.addresses[0].get_authorize_address( 'Test User' ), }) # Create a payment profile with some random payment id payment_profile = self.PaymentProfile( party=self.party2, address=self.party2.addresses[0].id, gateway=self.auth_net_gateway.id, last_4_digits='1111', expiry_month='05', expiry_year='2023', provider_reference='67382920', authorize_profile_id=customer.customer_id, ) payment_profile.save() # Create payment profile with same details as above ProfileWizard = POOL.get( 'party.party.payment_profile.add', type="wizard" ) profile_wizard = ProfileWizard( ProfileWizard.create()[0] ) profile_wizard.card_info.owner = 'Test User' profile_wizard.card_info.number = '4111111111111111' profile_wizard.card_info.expiry_month = '05' profile_wizard.card_info.expiry_year = '2023' profile_wizard.card_info.csc = '523' profile_wizard.card_info.gateway = self.auth_net_gateway profile_wizard.card_info.provider = self.auth_net_gateway.provider profile_wizard.card_info.address = self.party2.addresses[0] profile_wizard.card_info.party = self.party2 with Transaction().set_context(return_profile=True): profile = profile_wizard.transition_add() self.assertEqual(profile.party.id, self.party2.id) self.assertEqual(profile.gateway, self.auth_net_gateway) self.assertEqual( profile.last_4_digits, '1111' ) self.assertEqual( profile.expiry_month, '05' ) self.assertEqual( profile.expiry_year, '2023' ) self.assertIsNotNone(profile.authorize_profile_id) self.assertEqual( profile.authorize_profile_id, payment_profile.authorize_profile_id )
def __view_look_dom(cls, element, type, fields_width=None, _fields_attrs=None): pool = Pool() Translation = pool.get('ir.translation') ModelData = pool.get('ir.model.data') ModelAccess = pool.get('ir.model.access') Button = pool.get('ir.model.button') User = pool.get('res.user') ActionWindow = pool.get('ir.action.act_window') if fields_width is None: fields_width = {} if _fields_attrs is None: fields_attrs = {} else: fields_attrs = _fields_attrs def set_view_ids(element): view_ids = [] if element.get('view_ids'): for view_id in element.get('view_ids').split(','): try: view_ids.append(int(view_id)) except ValueError: view_ids.append(ModelData.get_id(*view_id.split('.'))) element.attrib['view_ids'] = ','.join(map(str, view_ids)) return view_ids def get_relation(field): if hasattr(field, 'model_name'): return field.model_name elif hasattr(field, 'get_target'): return field.get_target().__name__ def get_views(relation, widget, view_ids, mode): Relation = pool.get(relation) views = {} if widget in {'one2many', 'many2many'}: # Prefetch only the first view to prevent infinite loop if view_ids: for view_id in view_ids: view = Relation.fields_view_get(view_id=view_id) views[str(view_id)] = view break else: for view_type in mode: views[view_type] = ( Relation.fields_view_get(view_type=view_type)) break return views for attr in ('name', 'icon'): if not element.get(attr): continue fields_attrs.setdefault(element.get(attr), {}) if element.tag == 'field' and type in ['tree', 'form']: for attr in ('name', 'icon'): fname = element.get(attr) if not fname: continue view_ids = set_view_ids(element) if type != 'form': continue # Coog Spec : Ignore fields which are not in the view, to allow # dynamic sub_fields for Dict fields if fname not in cls._fields: continue field = cls._fields[fname] relation = get_relation(field) if element.get('relation'): relation = element.get('relation') if not relation: continue mode = ( element.attrib.pop('mode', None) or 'tree,form').split(',') widget = element.attrib.get('widget', field._type) views = get_views(relation, widget, view_ids, mode) element.attrib['mode'] = ','.join(mode) if not element.get('relation'): fields_attrs[fname].setdefault('views', {}).update(views) if type == 'tree' and element.get('name') in fields_width: element.set('width', str(fields_width[element.get('name')])) encoder = PYSONEncoder() if element.tag == 'button': button_name = element.attrib['name'] if button_name in cls._buttons: states = cls._buttons[button_name] else: states = {} groups = set(User.get_groups()) button_attr = Button.get_view_attributes( cls.__name__, button_name) for attr, value in button_attr.items(): if not element.get(attr): element.set(attr, value or '') button_groups = Button.get_groups(cls.__name__, button_name) if ((button_groups and not groups & button_groups) or (not button_groups and not ModelAccess.check( cls.__name__, 'write', raise_exception=False))): states = states.copy() states['readonly'] = True element.set('states', encoder.encode(states)) button_rules = Button.get_rules(cls.__name__, button_name) if button_rules: element.set('rule', '1') change = cls.__change_buttons[button_name] if change: change = list(change) # Add id to change if the button is not cached # Not having the id increase the efficiency of the cache if cls.__rpc__[button_name].cache: change.append('id') element.set('change', encoder.encode(change)) if not is_instance_method(cls, button_name): element.set('type', 'class') else: element.set('type', 'instance') for depend in states.get('depends', []): fields_attrs.setdefault(depend, {}) if element.tag == 'link': link_name = element.attrib['name'] action_id = ModelData.get_id(*link_name.split('.')) try: action, = ActionWindow.search([('id', '=', action_id)]) except ValueError: action = None if (not action or not action.res_model or not ModelAccess.check( action.res_model, 'read', raise_exception=False)): element.tag = 'label' colspan = element.attrib.get('colspan') element.attrib.clear() if colspan is not None: element.attrib['colspan'] = colspan else: element.attrib['id'] = str(action.action.id) # translate view if Transaction().language != 'en': for attr in ('string', 'sum', 'confirm', 'help'): if element.get(attr): trans = Translation.get_source(cls.__name__, 'view', Transaction().language, element.get(attr)) if trans: element.set(attr, trans) if element.tag == 'tree' and element.get('sequence'): fields_attrs.setdefault(element.get('sequence'), {}) if element.tag == 'calendar': for attr in ['dtstart', 'dtend', 'color', 'background_color']: if element.get(attr): fields_attrs.setdefault(element.get(attr), {}) for field in element: fields_attrs = cls.__view_look_dom(field, type, fields_width=fields_width, _fields_attrs=fields_attrs) return fields_attrs
def setup_defaults(self): """ Creates default data for testing """ currency, = self.Currency.create([{ 'name': 'US Dollar', 'code': 'USD', 'symbol': '$', }]) with Transaction().set_context(company=None): company_party, = self.Party.create([{ 'name': 'Openlabs' }]) self.company, = self.Company.create([{ 'party': company_party, 'currency': currency, }]) self.User.write([self.User(USER)], { 'company': self.company, 'main_company': self.company, }) CONTEXT.update(self.User.get_preferences(context_only=True)) # Create Fiscal Year self._create_fiscal_year(company=self.company.id) # Create Chart of Accounts self._create_coa_minimal(company=self.company.id) # Create Cash journal self.cash_journal, = self.Journal.search( [('type', '=', 'cash')], limit=1 ) self.Journal.write([self.cash_journal], { 'debit_account': self._get_account_by_kind('expense').id }) self.auth_net_gateway = self.PaymentGateway( name='Authorize.net', journal=self.cash_journal, provider='authorize_net', method='credit_card', authorize_net_login='******', authorize_net_transaction_key='32jF65cTxja88ZA2', test=True ) self.auth_net_gateway.save() # Create parties self.party1, = self.Party.create([{ 'name': 'Test party - 1', 'addresses': [('create', [{ 'name': 'Test Party %s' % random.randint(1, 999), 'street': 'Test Street %s' % random.randint(1, 999), 'city': 'Test City %s' % random.randint(1, 999), }])], 'account_receivable': self._get_account_by_kind( 'receivable').id, }]) self.party2, = self.Party.create([{ 'name': 'Test party - 2', 'addresses': [('create', [{ 'name': 'Test Party', 'street': 'Test Street', 'city': 'Test City', }])], 'account_receivable': self._get_account_by_kind( 'receivable').id, }]) self.party3, = self.Party.create([{ 'name': 'Test party - 3', 'addresses': [('create', [{ 'name': 'Test Party', 'street': 'Test Street', 'city': 'Test City', }])], 'account_receivable': self._get_account_by_kind( 'receivable').id, }]) self.card_data1 = self.UseCardView( number='4111111111111111', expiry_month='04', expiry_year=str(random.randint(2016, 2020)), csc=str(random.randint(100, 555)), owner='Test User -1', ) self.card_data2 = self.UseCardView( number='4111111111111111', expiry_month='08', expiry_year=str(random.randint(2016, 2020)), csc=str(random.randint(556, 999)), owner='Test User -2', ) self.invalid_card_data = self.UseCardView( number='4111111111111111', expiry_month='08', expiry_year='2022', csc=str(911), owner='Test User -2', ) self.payment_profile = self.PaymentProfile( party=self.party1, address=self.party1.addresses[0].id, gateway=self.auth_net_gateway.id, last_4_digits='1111', expiry_month='01', expiry_year='2018', provider_reference='27527167', authorize_profile_id='28545177', ) self.payment_profile.save()
def fields_view_get(cls, view_id=None, view_type='form', level=None): ''' Return a view definition. If view_id is None the first one will be used of view_type. The definition is a dictionary with keys: - model: the model name - type: the type of the view - view_id: the id of the view - arch: the xml description of the view - fields: a dictionary with the definition of each field in the view - field_childs: the name of the childs field for tree ''' key = (cls.__name__, view_id, view_type, level) result = cls._fields_view_get_cache.get(key) if result: return result result = {'model': cls.__name__} pool = Pool() View = pool.get('ir.ui.view') view = None inherit_view_id = None if view_id: view = View(view_id) else: domain = [ ('model', '=', cls.__name__), ['OR', ('inherit', '=', None), ('inherit.model', '!=', cls.__name__), ], ] views = View.search(domain) views = [v for v in views if v.rng_type == view_type] if views: view = views[0] if view: if view.inherit: inherit_view_id = view.id view = view.inherit # if a view was found if view: result['type'] = view.rng_type result['view_id'] = view_id result['arch'] = view.arch result['field_childs'] = view.field_childs # Check if view is not from an inherited model if view.model != cls.__name__: Inherit = pool.get(view.model) result['arch'] = Inherit.fields_view_get(view.id)['arch'] real_view_id = inherit_view_id else: real_view_id = view.id # get all views which inherit from (ie modify) this view views = View.search([ 'OR', [ ('inherit', '=', real_view_id), ('model', '=', cls.__name__), ], [ ('id', '=', real_view_id), ('inherit', '!=', None), ], ]) raise_p = False while True: try: views.sort(key=lambda x: cls._modules_list.index(x.module or None)) break except ValueError: if raise_p: raise # There is perhaps a new module in the directory ModelView._reset_modules_list() raise_p = True parser = etree.XMLParser(remove_comments=True) try: encoded_arch = result['arch'].encode('utf-8') except UnicodeEncodeError: encoded_arch = result['arch'] tree = etree.fromstring(encoded_arch, parser=parser) for view in views: if view.domain: if not PYSONDecoder({'context': Transaction().context} ).decode(view.domain): continue if not view.arch or not view.arch.strip(): continue tree_inherit = etree.fromstring(view.arch, parser=parser) tree = _inherit_apply(tree, tree_inherit) result['arch'] = etree.tostring( tree, encoding='utf-8').decode('utf-8') # otherwise, build some kind of default view else: if view_type == 'form': res = cls.fields_get() xml = '''<?xml version="1.0"?>''' \ '''<form col="4">''' for i in res: if i in ('create_uid', 'create_date', 'write_uid', 'write_date', 'id', 'rec_name'): continue if res[i]['type'] not in ('one2many', 'many2many'): xml += '<label name="%s"/>' % (i,) xml += '<field name="%s"/>' % (i,) if res[i]['type'] == 'text': xml += "<newline/>" else: xml += '<field name="%s" colspan="4"/>' % (i,) xml += "</form>" elif view_type == 'tree': field = 'id' if cls._rec_name in cls._fields: field = cls._rec_name xml = '''<?xml version="1.0"?>''' \ '''<tree><field name="%s"/></tree>''' \ % (field,) else: xml = '' result['type'] = view_type result['arch'] = xml result['field_childs'] = None result['view_id'] = view_id if level is None: level = 1 if result['type'] == 'tree' else 0 # Update arch and compute fields from arch parser = etree.XMLParser(remove_blank_text=True) try: encoded_arch = result['arch'].encode('utf-8') except UnicodeEncodeError: encoded_arch = result['arch'] tree = etree.fromstring(encoded_arch, parser) xarch, xfields = cls._view_look_dom_arch( tree, result['type'], result['field_childs'], level=level) result['arch'] = xarch result['fields'] = xfields if result['field_childs']: child_field = result['field_childs'] result['children_definitions'] = defs = {} model = cls requisite_fields = list(result['fields'].keys()) requisite_fields.remove(child_field) while model and model.__name__ not in defs: fields_to_get = [rfield for rfield in requisite_fields if hasattr(model, rfield)] defs[model.__name__] = model.fields_get(fields_to_get + [child_field]) field = getattr(model, child_field, None) if field: model = pool.get(field.model_name) else: model = None else: result['children_definitions'] = {} if not config.getboolean('cache', 'disable_fields_view_get_cache', default=False): cls._fields_view_get_cache.set(key, result) return result
def transition_update_asset(self): Asset = Pool().get('account.asset') asset = Asset(Transaction().context['active_id']) if self.start.value != asset.value: return 'show_move' return 'create_lines'
def create_move(self): pool = Pool() Move = pool.get('account.move') Period = pool.get('account.period') Invoice = pool.get('account.invoice') Currency = pool.get('currency.currency') MoveLine = pool.get('account.move.line') if self.move: return period_id = Period.find(self.statement.company.id, date=self.date) move_lines = self._get_move_lines() move = Move( period=period_id, journal=self.statement.journal.journal, date=self.date, origin=self, lines=move_lines, ) move.save() self.write([self], { 'move': move.id, }) if self.invoice: with Transaction().set_context(date=self.invoice.currency_date): amount = Currency.compute(self.statement.journal.currency, self.amount, self.statement.company.currency) reconcile_lines = self.invoice.get_reconcile_lines_for_amount( abs(amount)) moves_payment = Move.search([('description', '=', self.description)]) lines_advanced = [] account = self.party.account_receivable amount2 = Decimal(0.0) for move_payment in moves_payment: if not move_payment: continue for line in move_payment.lines: if (not line.reconciliation and line.account.id == account.id): lines_advanced.append(line) amount2 += line.debit - line.credit for move_line in move.lines: if move_line.account == self.invoice.account: Invoice.write([self.invoice], { 'payment_lines': [('add', [move_line.id])], }) break for move_line_advanced in lines_advanced: if move_line_advanced.account == self.invoice.account: Invoice.write([self.invoice], { 'payment_lines': [('add', [move_line_advanced.id])], }) break if lines_advanced: if amount2 < 0: amount2 = Decimal(amount2*-1) if (reconcile_lines[1] - amount2) == Decimal('0.0'): lines = reconcile_lines[0] + [move_line] + lines_advanced MoveLine.reconcile(lines) else: if reconcile_lines[1] == Decimal('0.0'): lines = reconcile_lines[0] + [move_line] MoveLine.reconcile(lines) return move
def _view_look_dom_arch(cls, tree, type, field_children=None, level=0): pool = Pool() ModelAccess = pool.get('ir.model.access') FieldAccess = pool.get('ir.model.field.access') encoder = PYSONEncoder() view_depends = [] for xpath, attribute, value, *extra in cls.view_attributes(): depends = [] if extra: depends, = extra nodes = tree.xpath(xpath) for element in nodes: element.set(attribute, encoder.encode(value)) if nodes and depends: view_depends.extend(depends) fields_width = {} tree_root = tree.getroottree().getroot() # Find field without read access fread_accesses = FieldAccess.check(cls.__name__, list(cls._fields.keys()), 'read', access=True) fields_to_remove = set( x for x, y in fread_accesses.items() if not y) # Find relation field without read access for name, field in cls._fields.items(): if not ModelAccess.check_relation(cls.__name__, name, mode='read'): fields_to_remove.add(name) checked = set() while checked < fields_to_remove: to_check = fields_to_remove - checked for name, field in cls._fields.items(): for field_to_remove in to_check: if field_to_remove in field.depends: fields_to_remove.add(name) checked |= to_check buttons_to_remove = set() for name, definition in cls._buttons.items(): if fields_to_remove & set(definition.get('depends', [])): buttons_to_remove.add(name) field_xpath = ('//field[@name="%(name)s"]' '| //label[@name="%(name)s"] | //page[@name="%(name)s"]' '| //group[@name="%(name)s"] | //separator[@name="%(name)s"]') button_xpath = '//button[@name="%(name)s"]' # Remove field and button without read acces for xpath, names in ( (field_xpath, fields_to_remove), (button_xpath, buttons_to_remove), ): for name in names: path = xpath % {'name': name} for i, element in enumerate(tree.xpath(path)): if type == 'tree' or element.tag == 'page': parent = element.getparent() parent.remove(element) elif type == 'form': element.tag = 'label' colspan = element.attrib.get('colspan') element.attrib.clear() element.attrib['id'] = 'hidden %s-%s' % (name, i) if colspan is not None: element.attrib['colspan'] = colspan # Remove empty pages if type == 'form': for page in tree.xpath('//page[not(descendant::*)]'): page.getparent().remove(page) if type == 'tree' and Transaction().context.get('view_tree_width'): ViewTreeWidth = pool.get('ir.ui.view_tree_width') viewtreewidth_ids = ViewTreeWidth.search([ ('model', '=', cls.__name__), ('user', '=', Transaction().user), ]) for viewtreewidth in ViewTreeWidth.browse(viewtreewidth_ids): if viewtreewidth.width > 0: fields_width[viewtreewidth.field] = viewtreewidth.width fields_def = cls.__view_look_dom(tree_root, type, fields_width=fields_width) if hasattr(cls, 'active'): fields_def.setdefault('active', {'name': 'active'}) if field_children: fields_def.setdefault(field_children, {'name': field_children}) if field_children in cls._fields: field = cls._fields[field_children] if hasattr(field, 'field'): fields_def.setdefault(field.field, {'name': field.field}) for field_name in list(fields_def.keys()): if field_name in cls._fields: field = cls._fields[field_name] else: continue for depend in field.depends: fields_def.setdefault(depend, {'name': depend}) for depend in view_depends: if depend not in fields_to_remove: fields_def.setdefault(depend, {'name': depend}) arch = etree.tostring( tree, encoding='utf-8', pretty_print=False).decode('utf-8') # Do not call fields_def without fields as it returns all fields if fields_def: fields2 = cls.fields_get(list(fields_def.keys()), level=level) else: fields2 = {} for field in fields_def: if field in fields2: fields2[field].update(fields_def[field]) return arch, fields2
def _domain_column(self, operator, column): column = super(Char, self)._domain_column(operator, column) if self.search_unaccented and operator.endswith('ilike'): database = Transaction().database column = database.unaccent(column) return column
def test_0110_email_with_attachments(self): ''' Send an email with text, html and an attachment ''' with Transaction().start(DB_NAME, USER, CONTEXT): self.setup_defaults() app = self.get_app() sender = u'Sender <*****@*****.**>' with app.test_request_context('/'): email_message = render_email( sender, u'*****@*****.**', u'Dummy subject of email', text_template='from-local.html', html_template='from-local.html', attachments={'filename.pdf': 'my glorious PDF content'}, ) self.assertEqual( decode_header(email_message['Subject'])[0], ('Dummy subject of email', None) ) # Message type should be multipart/alternative self.assertTrue(email_message.is_multipart()) self.assertEqual( email_message.get_content_type(), 'multipart/mixed' ) # Ensure that there are two subparts self.assertEqual( len(email_message.get_payload()), 2 ) # Ensure that the subparts are 1 alternative and # octet-stream part payload_types = set([ p.get_content_type() for p in email_message.get_payload() ]) self.assertEqual( set(['multipart/alternative', 'application/octet-stream']), payload_types ) # Drill into the alternative part and ensure that there is # both the text part and html part in it. for part in email_message.get_payload(): if part.get_content_type() == 'multipart/alternative': # Ensure that there are two subparts # 1. text/plain # 2. text/html self.assertEqual( len(email_message.get_payload()), 2 ) payload_types = set([ p.get_content_type() for p in part.get_payload() ]) self.assertEqual( set(['text/plain', 'text/html']), payload_types ) break else: self.fail('Alternative part not found')
def default_user(cls): pool = Pool() User = pool.get('res.user') cursor = Transaction().connection.cursor() user = User(Transaction().user).id return user
def _domain_value(self, operator, value): value = super(Char, self)._domain_value(operator, value) if self.search_unaccented and operator.endswith('ilike'): database = Transaction().database value = database.unaccent(value) return value
def __register__(cls, module_name): TimesheetWork = Pool().get('timesheet.work') cursor = Transaction().connection.cursor() table_project_work = cls.__table_handler__(module_name) project = cls.__table__() timesheet = TimesheetWork.__table__() work_exist = table_project_work.column_exist('work') add_parent = (not table_project_work.column_exist('parent') and work_exist) add_company = (not table_project_work.column_exist('company') and work_exist) add_name = (not table_project_work.column_exist('name') and work_exist) super(Work, cls).__register__(module_name) # Migration from 3.4: change effort into timedelta effort_duration if table_project_work.column_exist('effort'): cursor.execute(*project.select( project.id, project.effort, where=project.effort != Null)) for id_, effort in cursor.fetchall(): duration = datetime.timedelta(hours=effort) cursor.execute( *project.update([project.effort_duration], [duration], where=project.id == id_)) table_project_work.drop_column('effort') # Migration from 3.6: add parent, company, drop required on work, # fill name if add_parent: second_project = cls.__table__() query = project.join( timesheet, condition=project.work == timesheet.id).join( second_project, condition=timesheet.parent == second_project.work).select( project.id, second_project.id) cursor.execute(*query) for id_, parent in cursor.fetchall(): cursor.execute(*project.update([project.parent], [parent], where=project.id == id_)) cls._rebuild_tree('parent', None, 0) if add_company: cursor.execute(*project.join( timesheet, condition=project.work == timesheet.id).select( project.id, timesheet.company)) for id_, company in cursor.fetchall(): cursor.execute(*project.update([project.company], [company], where=project.id == id_)) table_project_work.not_null_action('work', action='remove') if add_name: cursor.execute(*project.join( timesheet, condition=project.work == timesheet.id).select( project.id, timesheet.name)) for id_, name in cursor.fetchall(): cursor.execute(*project.update([project.name], [name], where=project.id == id_)) # Migration from 4.0: remove work if work_exist: table_project_work.drop_constraint('work_uniq') update = Transaction().connection.cursor() cursor.execute(*project.select( project.id, project.work, where=project.work != Null)) for project_id, work_id in cursor: update.execute(*timesheet.update( [timesheet.origin, timesheet.name], ['%s,%s' % (cls.__name__, project_id), Null], where=timesheet.id == work_id)) table_project_work.drop_column('work')
def generate_invoice(cls, date=None, party=None, enrolment=None): pool = Pool() Date = pool.get('ir.date') Consumption = pool.get('sale.subscription.line.consumption') Invoice = pool.get('account.invoice') InvoiceLine = pool.get('account.invoice.line') Subscription = pool.get('sale.subscription') company = Transaction().context.get('company') if date is None: date = Date.today() consumptions = Consumption.search( [('invoice_line', '=', None), ('line.subscription.next_invoice_date', '<=', date), ('line.subscription.state', 'in', ['running', 'closed']), ('company', '=', company)], order=[ ('line.subscription.id', 'DESC'), ]) def keyfunc(consumption): return consumption.line.subscription invoices = {} lines = {} if consumptions: invoice_date = consumptions[0].date for subscription, consumptions in groupby(consumptions, key=keyfunc): invoices[subscription] = invoice = subscription._get_invoice( invoice_date) lines[subscription] = Consumption.get_invoice_lines( consumptions, invoice) all_invoices = invoices.values() Invoice.save(all_invoices) all_invoice_lines = [] for subscription, invoice in invoices.items(): invoice_lines, _ = lines[subscription] for line in invoice_lines: line.invoice = invoice all_invoice_lines.extend(invoice_lines) InvoiceLine.save(all_invoice_lines) all_consumptions = [] for values in lines.values(): for invoice_line, consumptions in zip(*values): for consumption in consumptions: assert not consumption.invoice_line consumption.invoice_line = invoice_line all_consumptions.append(consumption) Consumption.save(all_consumptions) Invoice.update_taxes(all_invoices) subscriptions = cls.search([('next_invoice_date', '<=', date), ('company', '=', company)]) for subscription in subscriptions: if subscription.state == 'running': while subscription.next_invoice_date <= date: subscription.next_invoice_date = ( subscription.compute_next_invoice_date()) else: subscription.next_invoice_date = None for subscription in subscriptions: # check invoice enrolment party = subscription.student.id subscription_reference = 'MAT: ' + str(subscription.number) exist_enrolment = subscription._check_enrolment( party, subscription_reference) if not exist_enrolment: subscription.create_enrolment_invoice() cls.save(subscriptions)
def default_currency(): Company = Pool().get('company.company') company = Transaction().context.get('company') if company: return Company(company).currency.id
"Error on URI creation for Category ID:%s\n%s" % (cat_id, exc)) else: raise exc logging.info("URI creation completed") if __name__ == '__main__': usage = "Usage: %prog [options] database category_file" parser = OptionParser(usage=usage) parser.add_option("-c", "--config", dest="config", default=None) (options, args) = parser.parse_args() DATABASE, FILE = args if options.config: from trytond.config import CONFIG CONFIG.update_etc(options.config) from trytond.modules import register_classes register_classes() from trytond.pool import Pool pool = Pool(DATABASE) pool.init() from trytond.transaction import Transaction with Transaction().start(DATABASE, 1, None) as txn: create_categories_from_file(FILE) txn.cursor.commit()