def run(self): transaction = Transaction() Model = Pool().get(self.data['model']) with transaction.set_user(self.data['user']), \ transaction.set_context(self.data['context']): instances = self.data['instances'] # Ensure record ids still exist if isinstance(instances, int): with transaction.set_context(active_test=False): if Model.search([('id', '=', instances)]): instances = Model(instances) else: instances = None else: ids = set() with transaction.set_context(active_test=False): for sub_ids in grouped_slice(instances): records = Model.search([('id', 'in', list(sub_ids))]) ids.update(map(int, records)) if ids: instances = Model.browse( [i for i in instances if i in ids]) else: instances = None if instances is not None: getattr(Model, self.data['method'])( instances, *self.data['args'], **self.data['kwargs']) if not self.dequeued_at: self.dequeued_at = datetime.datetime.now() self.finished_at = datetime.datetime.now() self.save()
def get_current_liability(self): pool = Pool() Date = pool.get('ir.date') AccountType = pool.get('account.account.type') today = Date.today() liability = Decimal('0.0') transaction = Transaction() context = Transaction().context total_liability = liability = Decimal('0.0') 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, ): liability = Decimal('0.0') liabilities = AccountType.search([ ('company', '=', company['id']), ('name', '=', '3) PASIVOS CORRIENTES') ]) if len(liabilities) == 1: liability = liabilities[0].amount * Decimal('1.0') total_liability += liability return total_liability else: current_liability = Decimal('0.0') 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_liabilities = AccountType.search([ ('company', '=', company), ('name', '=', '3) PASIVOS CORRIENTES') ]) if len(current_liabilities) == 1: current_liability = current_liabilities[ 0].amount * Decimal('1.0') return current_liability
def wrapper(cls, moves): pool = Pool() Sale = pool.get('sale.sale') transaction = Transaction() context = transaction.context with transaction.set_context(_check_access=False): sales = set(m.sale for m in cls.browse(moves) if m.sale) func(cls, moves) if sales: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Sale.__queue__.process(sales)
def wrapper(cls, shipments): pool = Pool() Purchase = pool.get('purchase.purchase') transaction = Transaction() context = transaction.context with transaction.set_context(_check_access=False): purchases = set(m.purchase for s in cls.browse(shipments) for m in getattr(s, moves_field) if m.purchase) func(cls, shipments) if purchases: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Purchase.__queue__.process(purchases)
def wrapper(cls, invoices): pool = Pool() Purchase = pool.get('purchase.purchase') transaction = Transaction() context = transaction.context with transaction.set_context(_check_access=False): purchases = set( p for i in cls.browse(invoices) for p in i.purchases) func(cls, invoices) if purchases: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Purchase.__queue__.process(purchases)
def test_user_employee(self): "Test user employee" pool = Pool() User = pool.get('res.user') transaction = Transaction() company = create_company() employee1 = create_employee(company, "Jim Halper") employee2 = create_employee(company, "Pam Bessly") employee3 = create_employee(company, "Michael Scott") user1, user2 = User.create([{ 'name': "Jim Halper", 'login': "******", 'companies': [('add', [company.id])], 'company': company.id, 'employees': [('add', [employee1.id, employee2.id])], 'employee': employee1.id, }, { 'name': "Pam Beesly", 'login': "******", 'companies': [('add', [company.id])], 'company': company.id, 'employees': [('add', [employee2.id])], 'employee': employee2.id, }]) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee2.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee2) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=None): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, None) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2)
def delete(cls, lines): pool = Pool() Purchase = pool.get('purchase.purchase') transaction = Transaction() context = transaction.context with transaction.set_context(_check_access=False): invoices = (l.invoice for l in cls.browse(lines) if l.type == 'line' and l.invoice) purchases = set(p for i in invoices for p in i.purchases) super(InvoiceLine, cls).delete(lines) if purchases: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Purchase.__queue__.process(purchases)
def delete(cls, lines): pool = Pool() Sale = pool.get('sale.sale') transaction = Transaction() context = transaction.context with transaction.set_context(_check_access=False): invoices = (l.invoice for l in cls.browse(lines) if l.type == 'line' and l.invoice) sales = set(s for i in invoices for s in i.sales) super().delete(lines) if sales: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Sale.__queue__.process(sales)
def wrapper(cls, moves): pool = Pool() Purchase = pool.get('purchase.purchase') transaction = Transaction() context = transaction.context with transaction.set_context(_check_access=False): p_moves = cls.browse(moves) if without_shipment: p_moves = [m for m in p_moves if not m.shipment] purchases = set(m.purchase for m in p_moves if m.purchase) func(cls, moves) if purchases: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Purchase.__queue__.process(purchases)
def get_current_liability(self): pool = Pool() Date = pool.get('ir.date') AccountType = pool.get('account.account.type') today = Date.today() liability = Decimal('0.0') transaction = Transaction() context = Transaction().context total_liability = liability = Decimal('0.0') 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, ): liability = Decimal('0.0') liabilities = AccountType.search([('company','=',company['id']), ('name','=','3) PASIVOS CORRIENTES') ]) if len(liabilities)==1: liability = liabilities[0].amount * Decimal('1.0') total_liability += liability return total_liability else: current_liability = Decimal('0.0') 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_liabilities = AccountType.search([('company','=',company), ('name','=','3) PASIVOS CORRIENTES')]) if len(current_liabilities)==1: current_liability = current_liabilities[0].amount * Decimal('1.0') return current_liability
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 get_esale_quantity(cls, products, name): Date = Pool().get('ir.date') transaction = Transaction() context = transaction.context shop_id = context.get('shop', None) locations = [] if shop_id: shop = Pool().get('sale.shop')(shop_id) # storage and input location in warehouse if shop.warehouses: for w in shop.warehouses: locations.append(w.storage_location.id) locations.append(w.input_location.id) elif shop.warehouse: locations.append(shop.warehouse.storage_location.id) locations.append(shop.warehouse.input_location.id) context['locations'] = locations if name[6:] == 'forecast_quantity': context['forecast'] = True context['stock_date_end'] = datetime.date.max else: context['forecast'] = False context['stock_date_end'] = Date.today() context['stock_assign'] = True context['with_childs'] = True with transaction.set_context(context): return cls.get_quantity(products, name[6:])
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 transition_handle(self): pool = Pool() Sale = pool.get('sale.sale') Move = pool.get('stock.move') transaction = Transaction() context = transaction.context super().transition_handle() sales = set() moves = set() to_recreate = set(self.ask.recreate_moves) domain_moves = set(self.ask.domain_moves) for line in self.record.lines: if not set(line.moves) & domain_moves: continue if not any(m in to_recreate for m in line.moves): for request in line.requests: for sale_line in request.sale_lines: moves.update({ m for m in sale_line.moves if (m.state != 'done' and m.from_location.type == 'drop') }) sales.add(sale_line.sale) if moves: Move.cancel(moves) if sales: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Sale.__queue__.process(sales) return 'end'
def run(self): transaction = Transaction() Model = Pool().get(self.data['model']) with transaction.set_user(self.data['user']), \ transaction.set_context(self.data['context']): instances = self.data['instances'] # Ensure record ids still exist if isinstance(instances, int): if Model.search([('id', '=', instances)]): instances = Model(instances) else: instances = None else: ids = set() for sub_ids in grouped_slice(instances): records = Model.search([('id', 'in', list(sub_ids))]) ids.update(map(int, records)) if ids: instances = Model.browse( [i for i in instances if i in ids]) else: instances = None resultant_args = copy.copy(self.data['args']) if instances is not None: resultant_args = [instances] + resultant_args getattr(Model, self.data['method'])(*resultant_args, **self.data['kwargs']) self.finished()
def wrapper(request, *args, **kwargs): pool = Pool() UserApplication = pool.get('res.user.application') authorization = wsgi_to_bytes(request.headers['Authorization']) try: auth_type, auth_info = authorization.split(None, 1) auth_type = auth_type.lower() except ValueError: abort(HTTPStatus.UNAUTHORIZED) if auth_type != b'bearer': abort(HTTPStatus.FORBIDDEN) application = UserApplication.check(bytes_to_wsgi(auth_info), name) if not application: abort(HTTPStatus.FORBIDDEN) transaction = Transaction() # TODO language with transaction.set_user(application.user.id), \ transaction.set_context(_check_access=True): try: response = func(request, *args, **kwargs) except Exception as e: if isinstance(e, HTTPException): raise logger.error('%s', request, exc_info=True) abort(HTTPStatus.INTERNAL_SERVER_ERROR, e) if not isinstance(response, Response) and json: response = Response(json_.dumps(response, cls=JSONEncoder), content_type='application/json') return response
def wrapper(request, *args, **kwargs): pool = Pool() UserApplication = pool.get('res.user.application') authorization = request.headers['Authorization'] try: auth_type, auth_info = authorization.split(None, 1) auth_type = auth_type.lower() except ValueError: abort(401) if auth_type != b'bearer': abort(403) application = UserApplication.check(auth_info, name) if not application: abort(403) transaction = Transaction() # TODO language with transaction.set_user(application.user.id), \ transaction.set_context(_check_access=True): try: response = func(request, *args, **kwargs) except Exception, e: if isinstance(e, HTTPException): raise logger.error('%s', request, exc_info=True) abort(500, e)
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 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 test_user_employee(self): "Test user employee" pool = Pool() User = pool.get('res.user') transaction = Transaction() company = create_company() employee1 = create_employee(company, "Jim Halper") employee2 = create_employee(company, "Pam Bessly") employee3 = create_employee(company, "Michael Scott") user1, user2 = User.create([{ 'name': "Jim Halper", 'login': "******", 'main_company': company.id, 'company': company.id, 'employees': [('add', [employee1.id, employee2.id])], 'employee': employee1.id, }, { 'name': "Pam Beesly", 'login': "******", 'main_company': company.id, 'company': company.id, 'employees': [('add', [employee2.id])], 'employee': employee2.id, }]) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee2.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee2) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=None): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, None) self.assertEqual(user2.employee, employee2) with transaction.set_context(employee=employee3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.employee, employee1) self.assertEqual(user2.employee, employee2)
def test_user_company(self): 'Test user company' pool = Pool() User = pool.get('res.user') transaction = Transaction() company1 = create_company() company2 = create_company('Michael Scott Paper Company', currency=company1.currency) company2.save() company3 = create_company() user1, user2 = User.create([{ 'name': 'Jim Halper', 'login': '******', 'companies': [('add', [company1.id, company2.id])], 'company': company1.id, }, { 'name': 'Pam Beesly', 'login': '******', 'companies': [('add', [company2.id])], 'company': company2.id, }]) self.assertTrue(user1) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2) with transaction.set_context({'company': company2.id}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company2) self.assertEqual(user2.company, company2) with transaction.set_context({'company': None}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, None) self.assertEqual(user2.company, company2) with transaction.set_context(company=company3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2)
def get_account(self, name, **pattern): if self.account_parent: return self.parent.get_account(name, **pattern) else: transaction = Transaction() with transaction.reset_context(), \ transaction.set_context(self._context): return self.get_multivalue(name[:-5], **pattern)
def get_recommended_capital(self): pool = Pool() Date = pool.get('ir.date') Fiscalyear = pool.get('account.fiscalyear') Budget = pool.get('account.budget') today = Date.today() transaction = Transaction() context = Transaction().context company = context.get('company') balance = Decimal('0.0') if self.is_consolidated: companies = context.get('companies',[]) for company in context.get('companies', []): total_amount = Decimal('0.0') with transaction.set_context(company=company['id']): fiscalyears = Fiscalyear.search([('company','=',company['id']), ('start_date','<=',today), ('end_date','>=',today)]) fiscalyear = None if len(fiscalyears)==1: fiscalyear = fiscalyears[0].id budgets = Budget.search([('fiscalyear','=',fiscalyear), ('company','=',company['id']), ('parent','=',None)]) if len(budgets)==1: budget = Budget(budgets[0].id) balance += budget.children[1].amount * Decimal('0.15') #balance *= -1 else: fiscalyear = Transaction().context.get('fiscalyear') if fiscalyear is not None: fiscalyears = Fiscalyear.search([('company','=',company), ('id','=',fiscalyear) ]) else: fiscalyears = Fiscalyear.search([('company','=',company), ('start_date','<=',today), ('end_date','>=',today)]) if len(fiscalyears)==1: fiscalyear = fiscalyears[0].id budgets = Budget.search([('fiscalyear','=',fiscalyear), ('company','=',company), ('parent','=',None)]) if len(budgets)==1: budget = Budget(budgets[0].id) print("BUDGET: ", str(budget)) balance = budget.children[0].amount * Decimal('0.15') print("BALANCE: ", str(balance)) #balance *= -1 return balance
def test_user_company(self): 'Test user company' pool = Pool() User = pool.get('res.user') transaction = Transaction() company1 = create_company() company2 = create_company('Michael Scott Paper Company', currency=company1.currency) company2.parent = company1 company2.save() company3 = create_company() user1, user2 = User.create([{ 'name': 'Jim Halper', 'login': '******', 'main_company': company1.id, 'company': company1.id, }, { 'name': 'Pam Beesly', 'login': '******', 'main_company': company2.id, 'company': company2.id, }]) self.assertTrue(user1) with transaction.set_user(user1.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2) with transaction.set_context({'company': company2.id}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company2) self.assertEqual(user2.company, company2) with transaction.set_context({'company': None}): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, None) self.assertEqual(user2.company, company2) with transaction.set_context(company=company3.id): user1, user2 = User.browse([user1.id, user2.id]) self.assertEqual(user1.company, company1) self.assertEqual(user2.company, company2)
def html_editor(request, pool, model, record, field): Field = pool.get('ir.model.field') field, = Field.search([ ('name', '=', field), ('model.model', '=', model), ]) transaction = Transaction() language = request.args.get('language', transaction.language) with transaction.set_context(language=language): Model = pool.get(model) record = Model(record) status = HTTPStatus.OK error = '' if request.method == 'POST': setattr(record, field.name, request.form['text']) if request.form['_csrf_token'] == get_token(record): record.save() return redirect(request.url) else: status = HTTPStatus.BAD_REQUEST error = gettext('ir.msg_html_editor_save_fail') csrf_token = get_token(record) text = getattr(record, field.name) or '' if isinstance(text, bytes): try: text = text.decode('utf-8') except UnicodeDecodeError as e: error = str(e).replace("'", "\\'") text = '' elif not isinstance(text, str): abort(HTTPStatus.BAD_REQUEST) title = '%(model)s "%(name)s" %(field)s - %(title)s' % { 'model': field.model.name, 'name': record.rec_name, 'field': field.field_description, 'title': request.args.get('title', "Tryton"), } return Response( TEMPLATE % { 'source': SOURCE, 'plugins': get_config(['plugins', model, field.name], default=''), 'css': get_config(['css', model, field.name], default='[]'), 'class': get_config(['class', model, field.name], default="''"), 'language': transaction.language, 'title': title, 'text': text, 'csrf_token': csrf_token, 'error': error, }, status, content_type='text/html')
def get_recommended_capital(self): pool = Pool() Date = pool.get('ir.date') Fiscalyear = pool.get('account.fiscalyear') Budget = pool.get('account.budget') today = Date.today() transaction = Transaction() context = Transaction().context company = context.get('company') balance = Decimal('0.0') if self.is_consolidated: companies = context.get('companies', []) for company in context.get('companies', []): total_amount = Decimal('0.0') with transaction.set_context(company=company['id']): fiscalyears = Fiscalyear.search([ ('company', '=', company['id']), ('start_date', '<=', today), ('end_date', '>=', today) ]) fiscalyear = None if len(fiscalyears) == 1: fiscalyear = fiscalyears[0].id budgets = Budget.search([('fiscalyear', '=', fiscalyear), ('company', '=', company['id']), ('parent', '=', None)]) if len(budgets) == 1: budget = Budget(budgets[0].id) balance += budget.children[1].amount * Decimal('0.15') #balance *= -1 else: fiscalyear = Transaction().context.get('fiscalyear') if fiscalyear is not None: fiscalyears = Fiscalyear.search([('company', '=', company), ('id', '=', fiscalyear)]) else: fiscalyears = Fiscalyear.search([('company', '=', company), ('start_date', '<=', today), ('end_date', '>=', today)]) if len(fiscalyears) == 1: fiscalyear = fiscalyears[0].id budgets = Budget.search([('fiscalyear', '=', fiscalyear), ('company', '=', company), ('parent', '=', None)]) if len(budgets) == 1: budget = Budget(budgets[0].id) print("BUDGET: ", str(budget)) balance = budget.children[0].amount * Decimal('0.15') print("BALANCE: ", str(balance)) #balance *= -1 return balance
def delete(cls, reconciliations): Invoice = Pool().get('account.invoice') transaction = Transaction() context = transaction.context invoices_to_process = _invoices_to_process(reconciliations) super(Reconciliation, cls).delete(reconciliations) with transaction.set_context( queue_batch=context.get('queue_batch', True)): Invoice.__queue__.process(list(invoices_to_process))
def approve(cls, complaints): pool = Pool() Configuration = pool.get('sale.configuration') transaction = Transaction() context = transaction.context config = Configuration(1) with transaction.set_context( queue_scheduled_at=config.sale_process_after, queue_batch=context.get('queue_batch', True)): cls.__queue__.process(complaints)
def create(cls, vlist): Invoice = Pool().get('account.invoice') transaction = Transaction() context = transaction.context reconciliations = super(Reconciliation, cls).create(vlist) with transaction.set_context( queue_batch=context.get('queue_batch', True)): Invoice.__queue__.process( list(_invoices_to_process(reconciliations))) return reconciliations
def approve(cls, requisitions): pool = Pool() Configuration = pool.get('purchase.configuration') transaction = Transaction() context = transaction.context cls.store_cache(requisitions) config = Configuration(1) with transaction.set_context( queue_scheduled_at=config.purchase_process_after, queue_batch=context.get('queue_batch', True)): cls.__queue__.process(requisitions)
def get_amount_cmp(cls, types, name): transaction = Transaction() current = transaction.context if not current.get('comparison'): return dict.fromkeys([t.id for t in types], None) new = {} for key, value in current.iteritems(): if key.endswith('_cmp'): new[key[:-4]] = value with transaction.set_context(new): return cls.get_amount(types, name)
def _get_context(): User = Pool().get('res.user') transaction = Transaction() user_id = transaction.user with transaction.set_context(_check_access=False, _datetime=None), \ transaction.set_user(0): user = EvalEnvironment(User(user_id), User) return { 'user': user, 'groups': User.get_groups() }
def get_amount_cmp(cls, types, name): transaction = Transaction() current = transaction.context if not current.get('comparison'): return dict.fromkeys([t.id for t in types], None) new = {} for key, value in current.iteritems(): if key.endswith('_cmp'): new[key[:-4]] = value with transaction.set_context(new): return cls.get_amount(types, name)
def wrapper(cls, productions): pool = Pool() Sale = pool.get('sale.sale') transaction = Transaction() context = transaction.context sales = set() with transaction.set_context(_check_access=False): for sub_productions in grouped_slice(productions): ids = [p.id for p in sub_productions] sales.update([ s.id for s in Sale.search([ ('lines.productions', 'in', ids), ]) ]) func(cls, productions) if sales: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Sale.__queue__.process(sales)
def wrapper(cls, purchases): pool = Pool() Request = pool.get('purchase.request') Sale = pool.get('sale.sale') transaction = Transaction() context = transaction.context sales = set() with transaction.set_context(_check_access=False): for sub_purchases in grouped_slice(purchases): ids = [x.id for x in sub_purchases] requests = Request.search([ ('purchase_line.purchase.id', 'in', ids), ('origin', 'like', 'sale.sale,%'), ]) sales.update(r.origin.id for r in requests) func(cls, purchases) if sales: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Sale.__queue__.process(sales)
def post(cls, invoices): pool = Pool() Move = pool.get('stock.move') transaction = Transaction() context = transaction.context super().post(invoices) moves = sum( (l.stock_component_moves for i in invoices for l in i.lines), []) if moves: with transaction.set_context( queue_batch=context.get('queue_batch', True)): Move.__queue__.update_unit_price(moves)
def wrapper(self, *args, **kwargs): if not self.getter_with_context: transaction = Transaction() context = { k: v for k, v in transaction.context.items() if k in transaction.cache_keys } with transaction.reset_context(), \ transaction.set_context(context): return func(self, *args, **kwargs) else: return func(self, *args, **kwargs)
def test_search_cursor_max_histories(self): 'Test search with number of histories at cursor.IN_MAX' pool = Pool() History = pool.get('test.history') transaction = Transaction() cursor = transaction.cursor n = cursor.IN_MAX + 1 History.create([{'value': 1}] * n) with transaction.set_context(_datetime=datetime.datetime.max): records = History.search([]) self.assertEqual({r.value for r in records}, {1}) self.assertEqual(len(records), n)
def test_search_cursor_max(self): 'Test search with number of history entries at cursor.IN_MAX' pool = Pool() History = pool.get('test.history') transaction = Transaction() cursor = transaction.cursor history = History(value=-1) history.save() for history.value in range(cursor.IN_MAX + 1): history.save() with transaction.set_context(_datetime=datetime.datetime.max): record, = History.search([]) self.assertEqual(record.value, cursor.IN_MAX)
def get_amount(cls, types, name): pool = Pool() Account = pool.get('account.account') GeneralLedger = pool.get('account.general_ledger.account') transaction = Transaction() context = transaction.context res = {} for type_ in types: res[type_.id] = Decimal('0.0') childs = cls.search([ ('parent', 'child_of', [t.id for t in types]), ]) type_sum = {} for type_ in childs: type_sum[type_.id] = Decimal('0.0') start_period_ids = GeneralLedger.get_period_ids('start_%s' % name) end_period_ids = GeneralLedger.get_period_ids('end_%s' % name) period_ids = list( set(end_period_ids).difference(set(start_period_ids))) for company in context.get('companies', []): with transaction.set_context(company=company['id'], posted=True, cumulate=True): accounts = Account.search([ ('company', '=', company['id']), ('type.meta_type', 'in', [t.id for t in childs]), ('kind', '!=', 'view'), ]) for account in accounts: key = account.type.meta_type.id type_sum[key] += (account.debit - account.credit) for type_ in types: childs = cls.search([ ('parent', 'child_of', [type_.id]), ]) for child in childs: res[type_.id] += type_sum[child.id] exp = Decimal(str(10.0 ** -type_.currency_digits)) res[type_.id] = res[type_.id].quantize(exp) if type_.display_balance == 'credit-debit': res[type_.id] = - res[type_.id] return res
def test_search_cursor_max_entries(self): 'Test search for skipping first history entries at cursor.IN_MAX' pool = Pool() History = pool.get('test.history') transaction = Transaction() cursor = transaction.cursor for i in xrange(0, 2): history = History(value=-1) history.save() for history.value in range(cursor.IN_MAX + 1): history.save() with transaction.set_context(_datetime=datetime.datetime.max): records = History.search([]) self.assertEqual({r.value for r in records}, {cursor.IN_MAX}) self.assertEqual(len(records), 2)
def transition_create_account(self): pool = Pool() AnalyticAccountTemplate = \ pool.get('analytic_account.account.template') Config = pool.get('ir.configuration') Account = pool.get('analytic_account.account') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([('company', '=', company.id), ('type','=','root'), ('parent','=',None), ('root','=',None)]) if len(accounts)>=3: self.raise_user_warning('duplicated_chart.%d' % company, 'account_chart_exists', { 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): # Create analytic plan analytic_templates = AnalyticAccountTemplate.search([ ('type','=','root'), ('parent','=',None), ('root','=',None) ]) for template in analytic_templates: template2account = {} #print ("TEMPLATE: ", str(template)) template.create_analytic_account( company.id, template2account=template2account, ) return 'end'
def transition_create_budget(self): pool = Pool() BudgetTemplate = \ pool.get('account.budget.template') Budget = pool.get('account.budget') Config = pool.get('ir.configuration') transaction = Transaction() company = self.account.company fiscalyear = self.account.fiscalyear template = self.account.template # Skip access rule with transaction.set_user(0): budgets = Budget.search([ ('company', '=', company.id), ('fiscalyear','=',fiscalyear), ('parent','=',None), ]) if budgets: #raise BudgetExistForFiscalYear( # gettext('account_budget.msg_budget_already_exist', # fiscalyear=fiscalyear.name, # company=company.rec_name)) self.raise_user_error('budget_already_exists', { 'fiscalyear': fiscalyear.name, 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): template2budget = {} template.create_budget( company.id, fiscalyear.id, template2budget=template2budget, ) return 'end'
def transition_create_account(self): pool = Pool() Config = pool.get('ir.configuration') Account = pool.get('account.account.meta.type') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([()]) if accounts: self.raise_user_error('account_chart_exists') with transaction.set_context(language=Config.get_language(), company=company.id): account_template = self.account.account_template # Create account types template2type = {} account_template.create_type( company.id, template2type=template2type) return 'end'
def check_stock_quantity(self): pool = Pool() Product = pool.get('product.product') Date = pool.get('ir.date') Uom = pool.get('product.uom') Group = pool.get('res.group') User = pool.get('res.user') ModelData = pool.get('ir.model.data') Line = pool.get('sale.line') transaction = Transaction() def in_group(): group = Group(ModelData.get_id('sale_stock_quantity', 'group_sale_stock_quantity')) user_id = transaction.user if user_id == 0: user_id = transaction.context.get('user', user_id) if user_id == 0: return True user = User(user_id) return group in user.groups def filter_line(line): return (line.product and line.product.type == 'goods' and line.quantity > 0 # Use getattr as supply_on_sale comes from sale_supply module and not getattr(line, 'supply_on_sale', False)) def get_delta(date): 'Compute quantity delta at the date' if date in date2delta: return date2delta[date] with transaction.set_context(forecast=True, stock_date_start=date, stock_date_end=date): pbl = Product.products_by_location([self.warehouse.id], product_ids=list(product_ids), with_childs=True) delta = {} for key, qty in pbl.iteritems(): _, product_id = key delta[product_id] = qty date2delta[date] = delta return delta date2delta = {} def raise_(line_id, message_values): if not in_group(): self.raise_user_error('stock_quantity', message_values) warning_name = 'stock_quantity_warning_%s' % line_id self.raise_user_warning( warning_name, 'stock_quantity', message_values) today = Date.today() sale_date = self.sale_date or today product_ids = {l.product.id for l in ifilter(filter_line, self.lines)} # The product must be available at least the day before # for sale in the future stock_date = sale_date if sale_date > today: stock_date -= datetime.timedelta(1) with transaction.set_context( locations=[self.warehouse.id], stock_date_end=stock_date, stock_assign=True): products = Product.browse(product_ids) quantities = {p: p.forecast_quantity for p in products} # Remove quantities from other sales for sub_product_ids in grouped_slice(product_ids): lines = Line.search([ ('sale.company', '=', self.company.id), ('sale.state', 'in', self._stock_quantity_states()), ('sale.id', '!=', self.id), ['OR', ('sale.sale_date', '<=', sale_date), ('sale.sale_date', '=', None), ], ('product', 'in', sub_product_ids), ('quantity', '>', 0), ]) for line in lines: product = line.product date = line.sale.sale_date or today if date > today: continue quantity = Uom.compute_qty(line.unit, line.quantity, product.default_uom, round=False) quantities[product] -= quantity for line in ifilter(filter_line, self.lines): product = line.product quantity = Uom.compute_qty(line.unit, line.quantity, product.default_uom, round=False) next_supply_date = self._stock_quantity_next_supply_date(product) message_values = { 'line': line.rec_name, 'forecast_quantity': quantities[product], 'default_uom': product.default_uom.symbol, 'quantity': line.quantity, 'unit': line.unit.symbol, } if (quantities[product] < quantity and sale_date < next_supply_date): raise_(line.id, message_values) # Update quantities if the same product is many times in lines quantities[product] -= quantity # Check other dates until next supply date if next_supply_date != datetime.date.max: forecast_quantity = quantities[product] date = sale_date + datetime.timedelta(1) while date < next_supply_date: delta = get_delta(date) forecast_quantity += delta.get(product.id, 0) if forecast_quantity < 0: message_values['forecast_quantity'] = forecast_quantity raise_(line.id, message_values) date += datetime.timedelta(1)
def transition_create_account(self): pool = Pool() TaxCodeTemplate = pool.get('account.tax.code.template') TaxCodeLineTemplate = pool.get('account.tax.code.line.template') TaxTemplate = pool.get('account.tax.template') TaxRuleTemplate = pool.get('account.tax.rule.template') TaxRuleLineTemplate = \ pool.get('account.tax.rule.line.template') Config = pool.get('ir.configuration') Account = pool.get('account.account') transaction = Transaction() company = self.account.company # Skip access rule with transaction.set_user(0): accounts = Account.search([('company', '=', company.id)], limit=1) if accounts: self.raise_user_warning('duplicated_chart.%d' % company.id, 'account_chart_exists', { 'company': company.rec_name, }) with transaction.set_context(language=Config.get_language(), company=company.id): account_template = self.account.account_template account_meta_template = self.account.meta_type # Get account meta types template2meta_type = {} account_meta_template.update_type(template2type=template2meta_type) # Create account types template2type = {} account_template.type.create_type( company.id, template2type=template2type, template2meta_type=template2meta_type) # Create accounts template2account = {} account_template.create_account( company.id, template2account=template2account, template2type=template2type) # Create taxes template2tax = {} TaxTemplate.create_tax( account_template.id, company.id, template2account=template2account, template2tax=template2tax) # Create tax codes template2tax_code = {} TaxCodeTemplate.create_tax_code( account_template.id, company.id, template2tax_code=template2tax_code) # Create tax code lines template2tax_code_line = {} TaxCodeLineTemplate.create_tax_code_line( account_template.id, template2tax=template2tax, template2tax_code=template2tax_code, template2tax_code_line=template2tax_code_line) # Update taxes and replaced_by on accounts account_template.update_account2(template2account, template2tax) # Create tax rules template2rule = {} TaxRuleTemplate.create_rule( account_template.id, company.id, template2rule=template2rule) # Create tax rule lines template2rule_line = {} TaxRuleLineTemplate.create_rule_line( account_template.id, template2tax, template2rule, template2rule_line=template2rule_line) return 'properties'
def test_account_debit_credit(self): 'Test account debit/credit' pool = Pool() Party = pool.get('party.party') AnalyticAccount = pool.get('analytic_account.account') Journal = pool.get('account.journal') Account = pool.get('account.account') Move = pool.get('account.move') transaction = Transaction() party = Party(name='Party') party.save() company = create_company() with set_company(company): root, = AnalyticAccount.create([{ 'type': 'root', 'name': 'Root', }]) analytic_account, = AnalyticAccount.create([{ 'type': 'normal', 'name': 'Analytic Account', 'parent': root.id, 'root': root.id, }]) create_chart(company) fiscalyear = get_fiscalyear(company) fiscalyear.save() fiscalyear.create_period([fiscalyear]) period = fiscalyear.periods[0] journal_revenue, = Journal.search([ ('code', '=', 'REV'), ]) journal_expense, = Journal.search([ ('code', '=', 'EXP'), ]) revenue, = Account.search([ ('kind', '=', 'revenue'), ]) receivable, = Account.search([ ('kind', '=', 'receivable'), ]) expense, = Account.search([ ('kind', '=', 'expense'), ]) payable, = Account.search([ ('kind', '=', 'payable'), ]) first_account_line = { 'account': revenue.id, 'credit': Decimal(100), 'analytic_lines': [ ('create', [{ 'account': analytic_account.id, 'name': 'Analytic Line', 'credit': Decimal(100), 'debit': Decimal(0), 'journal': journal_revenue.id, 'date': period.start_date, }]) ]} second_account_line = { 'account': expense.id, 'debit': Decimal(30), 'analytic_lines': [ ('create', [{ 'account': analytic_account.id, 'name': 'Analytic Line', 'debit': Decimal(30), 'credit': Decimal(0), 'journal': journal_expense.id, 'date': period.start_date, }]) ]} # Create some moves vlist = [{ 'period': period.id, 'journal': journal_revenue.id, 'date': period.start_date, 'lines': [ ('create', [first_account_line, { 'account': receivable.id, 'debit': Decimal(100), 'party': party.id, }]), ], }, { 'period': period.id, 'journal': journal_expense.id, 'date': period.start_date, 'lines': [ ('create', [second_account_line, { 'account': payable.id, 'credit': Decimal(30), 'party': party.id, }]), ], }, ] Move.create(vlist) self.assertEqual((analytic_account.debit, analytic_account.credit), (Decimal(30), Decimal(100))) self.assertEqual(analytic_account.balance, Decimal(70)) with transaction.set_context(start_date=period.end_date): analytic_account = AnalyticAccount(analytic_account.id) self.assertEqual((analytic_account.debit, analytic_account.credit), (Decimal(0), Decimal(0))) self.assertEqual(analytic_account.balance, Decimal(0)) with transaction.set_context(end_date=period.end_date): analytic_account = AnalyticAccount(analytic_account.id) self.assertEqual((analytic_account.debit, analytic_account.credit), (Decimal(30), Decimal(100))) self.assertEqual(analytic_account.balance, Decimal(70))