コード例 #1
0
ファイル: cli.py プロジェクト: camptocamp/anthem
    def _build_odoo_env(self, odoo_args):
        odoo.tools.config.parse_config(odoo_args)
        dbname = odoo.tools.config['db_name']
        odoo.tools.config['workers'] = 0
        odoo.tools.config['xmlrpc'] = False
        if not dbname:
            argparse.ArgumentParser().error(
                "please provide a database name though Odoo options (either "
                "-d or an Odoo configuration file)"
            )
        logging.getLogger(odoo_logger).setLevel(logging.ERROR)
        odoo.service.server.start(preload=[], stop=True)

        # odoo.service.server.start() modifies the SIGINT signal by its own
        # one which in fact prevents us to stop anthem with Ctrl-c.
        # Restore the default one.
        signal.signal(signal.SIGINT, signal.default_int_handler)

        if odoo.release.version_info[0] > 9:
            registry = odoo.modules.registry.Registry(dbname)
        else:
            registry = odoo.modules.registry.RegistryManager.get(dbname)
        cr = registry.cursor()
        uid = odoo.SUPERUSER_ID
        Environment.reset()
        context = Environment(cr, uid, {})['res.users'].context_get()
        return Environment(cr, uid, context)
コード例 #2
0
ファイル: test_frontend.py プロジェクト: GabbasovDinar/odoo
    def test_01_pos_basic_order(self):
        cr = self.registry.cursor()
        assert cr == self.registry.test_cr
        env = Environment(cr, self.uid, {})

        journal_obj = env['account.journal']
        account_obj = env['account.account']
        main_company = env.ref('base.main_company')
        main_pos_config = env.ref('point_of_sale.pos_config_main')

        account_receivable = account_obj.create({'code': 'X1012',
                                                 'name': 'Account Receivable - Test',
                                                 'user_type_id': env.ref('account.data_account_type_receivable').id,
                                                 'reconcile': True})
        field = self.env['ir.model.fields'].search([('name', '=', 'property_account_receivable_id'),
                                                    ('model', '=', 'res.partner'),
                                                    ('relation', '=', 'account.account')], limit=1)
        env['ir.property'].create({'name': 'property_account_receivable_id',
                                   'company_id': main_company.id,
                                   'fields_id': field.id,
                                   'value': 'account.account,' + str(account_receivable.id)})

        # set the company currency to USD, otherwise it will assume
        # euro's. this will cause issues as the sale journal is in
        # USD, because of this all products would have a different
        # price
        main_company.currency_id = env.ref('base.USD')

        test_sale_journal = journal_obj.create({'name': 'Sale Journal - Test',
                                                'code': 'TSJ',
                                                'type': 'sale',
                                                'company_id': main_company.id})

        env['product.pricelist'].search([]).write(dict(currency_id=main_company.currency_id.id))

        main_pos_config.journal_id = test_sale_journal
        main_pos_config.write({'journal_ids': [(0, 0, {'name': 'Cash Journal - Test',
                                                       'code': 'TSC',
                                                       'type': 'cash',
                                                       'company_id': main_company.id,
                                                       'journal_user': True})]})

        # open a session, the /pos/web controller will redirect to it
        main_pos_config.open_session_cb()

        # needed because tests are run before the module is marked as
        # installed. In js web will only load qweb coming from modules
        # that are returned by the backend in module_boot. Without
        # this you end up with js, css but no qweb.
        env['ir.module.module'].search([('name', '=', 'point_of_sale')], limit=1).state = 'installed'
        cr.release()

        self.phantom_js("/pos/web",
                        "odoo.__DEBUG__.services['web_tour.tour'].run('pos_basic_order')",
                        "odoo.__DEBUG__.services['web_tour.tour'].tours.pos_basic_order.ready",
                        login="******")

        for order in env['pos.order'].search([]):
            self.assertEqual(order.state, 'paid', "Validated order has payment of " + str(order.amount_paid) + " and total of " + str(order.amount_total))
コード例 #3
0
ファイル: openerplib.py プロジェクト: galtys/galtys-addons
def connect(dbname='trunk', uid=1, context=None):
    from odoo.modules.registry import RegistryManager
    from odoo.api import Environment
    r = RegistryManager.get(dbname)
    cr = r.cursor()
    Environment.reset()
    env = Environment(cr, uid, context or {})
    print('Connected to %s with user %s %s'
          % (dbname, env.uid, env.user.name))
    return env
コード例 #4
0
    def test_pos_product_available_negative(self):
        # needed because tests are run before the module is marked as
        # installed. In js web will only load qweb coming from modules
        # that are returned by the backend in module_boot. Without
        # this you end up with js, css but no qweb.
        cr = self.registry.cursor()
        env = Environment(cr, self.uid, {})
        env["ir.module.module"].search(
            [("name", "=", "pos_product_available")],
            limit=1).state = "installed"
        cr.release()

        env["product.template"].search([("name", "=", "Yellow Peppers")
                                        ]).write({"type": "product"})

        # without a delay there might be problems on the steps whilst opening a POS
        # caused by a not yet loaded button's action
        self.phantom_js(
            "/web",
            "odoo.__DEBUG__.services['web_tour.tour'].run('tour_pos_product_available_negative', 1000)",
            "odoo.__DEBUG__.services['web_tour.tour'].tours.tour_pos_product_available_negative.ready",
            login="******",
            timeout=150,
        )
    def setUpClass(cls):
        super().setUpClass()

        # Test using the demo user to prevent bugs related with access rights.
        cls.env = Environment(cls.env.cr, cls.env.ref('base.user_demo').id, {})

        cls.state_on = cls.env.ref('base.state_ca_on')
        cls.state_qc = cls.env.ref('base.state_ca_qc')

        cls.cron = cls.env.ref(
            'partner_duplicate_mgmt.ir_cron_create_duplicates')

        cls.account_move_group = cls.env.ref(
            'partner_duplicate_mgmt.group_contacts_merge_account_moves')

        cls.duplicate_email = cls.env.ref(
            'partner_duplicate_mgmt.duplicate_field_email')
        cls.duplicate_state = cls.env.ref(
            'partner_duplicate_mgmt.duplicate_field_state_id')

        cls.company_1 = cls.env['res.partner'].create({
            'name':
            'Company 1',
            'is_company':
            True,
            'state_id':
            cls.state_on.id,
        })
        cls.company_2 = cls.env['res.partner'].create({
            'name': 'Coompany 1',
            'is_company': True,
        })

        cls.contact_1 = cls.env['res.partner'].create({
            'name':
            'Partner inc.',
            'email':
            'contact_123@localhost',
            'parent_id':
            cls.company_1.id,
        })
        cls.contact_2 = cls.env['res.partner'].create({
            'name':
            'Paartner inc.',
            'email':
            'partners@localhost',
            'state_id':
            cls.state_qc.id,
        })

        cls.bank_1 = cls.env['res.partner.bank'].create({
            'acc_number':
            '1111',
            'partner_id':
            cls.contact_1.id,
        })
        cls.bank_2 = cls.env['res.partner.bank'].create({
            'acc_number':
            '2222',
            'partner_id':
            cls.contact_2.id,
        })

        cls.attachment_1 = cls.env['ir.attachment'].create({
            'name':
            'Attachment 1',
            'res_model':
            'res.partner',
            'res_id':
            cls.contact_1.id,
        })
        cls.attachment_2 = cls.env['ir.attachment'].create({
            'name':
            'Attachment 1',
            'res_model':
            'res.partner',
            'res_id':
            cls.contact_2.id,
        })

        cls.contacts = [cls.contact_1.id, cls.contact_2.id]
        cls.companies = [cls.company_1.id, cls.company_2.id]

        cls.contact_dup = cls.env['res.partner.duplicate'].search([
            ('partner_1_id', 'in', cls.contacts),
            ('partner_2_id', 'in', cls.contacts),
        ])
        assert cls.contact_dup

        cls.contact_dup.open_partner_merge_wizard()
        cls.contact_merge_lines = cls.contact_dup.merge_line_ids

        cls.company_dup = cls.env['res.partner.duplicate'].search([
            ('partner_1_id', 'in', cls.companies),
            ('partner_2_id', 'in', cls.companies),
        ])
        assert cls.company_dup

        cls.company_dup.open_partner_merge_wizard()
        cls.company_merge_lines = cls.company_dup.merge_line_ids
コード例 #6
0
def add_act_window_id_in_context(cr):
    env = Environment(cr, SUPERUSER_ID, {})
    env['ir.actions.act_window'].with_context(active_test=False).search(
        [])._update_context()
コード例 #7
0
ファイル: __init__.py プロジェクト: Avery1030/odoo12-dev
def uninstall_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    res_ids = env['ir.model.data'].search([('model', '=', 'ir.ui.menu'),
                                           ('module', '=', 'sale')
                                           ]).mapped('res_id')
    env['ir.ui.menu'].browse(res_ids).update({'active': False})
コード例 #8
0
    def auto_workflow_process(self, auto_workflow_process_id=False, ids=[]):
        transaction_log_obj = self.env['transaction.log.ept']
        with Environment.manage():
            env_thread1 = Environment(self._cr, self._uid, self._context)
            sale_order_obj = env_thread1['sale.order']
            sale_order_line_obj = env_thread1['sale.order.line']
            account_payment_obj = env_thread1['account.payment']
            workflow_process_obj = env_thread1['sale.workflow.process.ept']
            if not auto_workflow_process_id:
                work_flow_process_records = workflow_process_obj.search([])
            else:
                work_flow_process_records = workflow_process_obj.browse(
                    auto_workflow_process_id)

            if not work_flow_process_records:
                return True

            for work_flow_process_record in work_flow_process_records:
                if not ids:
                    orders = sale_order_obj.search([
                        ('auto_workflow_process_id', '=',
                         work_flow_process_record.id),
                        ('state', 'not in', ('done', 'cancel', 'sale')),
                        ('invoice_status', '!=', 'invoiced')
                    ])  #('invoiced','=',False)
                else:
                    orders = sale_order_obj.search([
                        ('auto_workflow_process_id', '=',
                         work_flow_process_record.id), ('id', 'in', ids)
                    ])
                if not orders:
                    continue
                for order in orders:
                    if order.invoice_status and order.invoice_status == 'invoiced':
                        continue
                    if work_flow_process_record.validate_order:
                        try:
                            order.action_confirm()
                            order.write(
                                {'confirmation_date': order.date_order})

                        except Exception as e:
                            transaction_log_obj.create({
                                'message':
                                "Error while confirm Sale Order %s\n%s" %
                                (order.name, e),
                                'mismatch_details':
                                True,
                                'type':
                                'sales'
                            })
                            order.state = 'draft'
                            continue
                    if work_flow_process_record.invoice_policy == 'delivery':
                        continue
                    if not work_flow_process_record.invoice_policy and not sale_order_line_obj.search(
                        [('product_id.invoice_policy', '!=', 'delivery'),
                         ('order_id', 'in', order.ids)]):
                        continue
                    if not order.invoice_ids:
                        if work_flow_process_record.create_invoice:
                            try:
                                order.action_invoice_create()
                            except Exception as e:
                                transaction_log_obj.create({
                                    'message':
                                    "Error while Create invoice for Order %s\n%s"
                                    % (order.name, e),
                                    'mismatch_details':
                                    True,
                                    'type':
                                    'invoice'
                                })
                                continue
                    if work_flow_process_record.validate_invoice:
                        for invoice in order.invoice_ids:
                            try:
                                invoice.action_invoice_open()
                            except Exception as e:
                                transaction_log_obj.create({
                                    'message':
                                    "Error while open Invoice for Order %s\n%s"
                                    % (order.name, e),
                                    'mismatch_details':
                                    True,
                                    'type':
                                    'invoice'
                                })
                                continue
                            if work_flow_process_record.register_payment:
                                if invoice.residual:
                                    # Create Invoice and Make Payment
                                    vals = {
                                        'journal_id':
                                        work_flow_process_record.journal_id.id,
                                        'invoice_ids': [(6, 0, [invoice.id])],
                                        'communication':
                                        invoice.reference,
                                        'currency_id':
                                        invoice.currency_id.id,
                                        'payment_type':
                                        'inbound',
                                        'partner_id':
                                        invoice.commercial_partner_id.id,
                                        'amount':
                                        invoice.residual,
                                        'payment_method_id':
                                        work_flow_process_record.
                                        inbound_payment_method_id.id,
                                        #                                         'payment_method_id':work_flow_process_record.journal_id.inbound_payment_method_ids.id,
                                        'partner_type':
                                        'customer'
                                    }
                                    try:
                                        new_rec = account_payment_obj.create(
                                            vals)
                                        new_rec.post()
                                    except Exception as e:
                                        transaction_log_obj.create({
                                            'message':
                                            "Error while Validating Invoice for Order %s\n%s"
                                            % (order.name, e),
                                            'mismatch_details':
                                            True,
                                            'type':
                                            'invoice'
                                        })
                                        continue
        return True
コード例 #9
0
def parameter_resolve_column_name(parameters, index):
    return parameter_can_2m(parameters, index) and PARAM_VALUES[
        parameters[index]['type']]['value_list'] % index or PARAM_VALUES[
            parameters[index]['type']]['value'] % index


# functions here will be passed a dictionary to evaluate reserved values. The dictionary should have:
#    'ids' - object ids in force
#    'uid' - the applicable user
#    'context' - the applicable context

RESERVED_PARAMS = {
    'ids':
    lambda s, cr, uid, d: d.get('ids', []),
    'user_id':
    lambda s, cr, uid, d: d.get('uid', 0),
    'user_name':
    lambda s, cr, uid, d: d.get('uid') and Environment(cr, uid, {})[
        'res.users'].browse(d['uid']).name or '',
    'context_lang':
    lambda s, cr, uid, d: d.get('context', {}).get('lang', ''),
    'context_tz':
    lambda s, cr, uid, d: d.get('context', {}).get('tz', ''),
}


def check_java_list(type):
    if type[0:2] == '[L':
        return True, type[2:-1]
    return False, type
コード例 #10
0
ファイル: __init__.py プロジェクト: kit9/odoo-vcls-module
def uninstall_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    for rec in env['ir.config_parameter'].search([]):
        if rec.key == "base_setup.ks_pivot_sticky_status":
            rec.sudo().unlink()
コード例 #11
0
ファイル: init_hook.py プロジェクト: tate11/pms
def post_init_hook(cr, _):
    with Environment.manage():
        env = Environment(cr, SUPERUSER_ID, {})
        env["ir.config_parameter"].sudo().set_param(
            "product.product_pricelist_setting", "advanced")
コード例 #12
0
ファイル: __init__.py プロジェクト: dream0892/jonescorp
def uninstall_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    for rec in env['ks_leaderboard.leaderboard'].search([]):
        rec.ks_leaderboard_action_id.unlink()
        rec.ks_leaderboard_menu_id.unlink()
コード例 #13
0
def post_init_hook(cr, pool):
    env = Environment(cr, SUPERUSER_ID, {})
    env['hr.employee']._update_employee_names()
コード例 #14
0
 def web_login(self, redirect=None, **kw):
     if request.httprequest.method == 'POST':
         ensure_db()
         remote = request.httprequest.remote_addr
         # Get registry and cursor
         with registry(request.session.db).cursor() as cursor:
             env = Environment(cursor, SUPERUSER_ID, {})
             config_obj = env['ir.config_parameter']
             attempt_obj = env['res.authentication.attempt']
             banned_remote_obj = env['res.banned.remote']
             # Get Settings
             max_attempts_qty = int(
                 config_obj.get_param('auth_brute_force.max_attempt_qty'))
             # Test if remote user is banned
             banned = banned_remote_obj.search([('remote', '=', remote)])
             if banned:
                 request.params['password'] = ''
                 _logger.warning(
                     "Authentication tried from remote '%s'. The request "
                     "has been ignored because the remote has been banned "
                     "after %d attempts without success. Login tried : '%s'"
                     "." %
                     (remote, max_attempts_qty, request.params['login']))
             else:
                 # Try to authenticate
                 result = request.session.authenticate(
                     request.session.db, request.params['login'],
                     request.params['password'])
             # Log attempt
             attempt_obj.create({
                 'attempt_date':
                 fields.Datetime.now(),
                 'login':
                 request.params['login'],
                 'remote':
                 remote,
                 'result':
                 banned and 'banned'
                 or (result and 'successfull' or 'failed'),
             })
             cursor.commit()
             if not banned and not result:
                 # Get last bad attempts quantity
                 attempts_qty = len(attempt_obj.search_last_failed(remote))
                 if max_attempts_qty <= attempts_qty:
                     # We ban the remote
                     _logger.warning(
                         "Authentication failed from remote '%s'. "
                         "The remote has been banned. Login tried : '%s'"
                         "." % (remote, request.params['login']))
                     banned_remote_obj.sudo().create({
                         'remote':
                         remote,
                         'ban_date':
                         fields.Datetime.now(),
                     })
                     cursor.commit()
                 else:
                     _logger.warning(
                         "Authentication failed from remote '%s'."
                         " Login tried : '%s'. Attempt %d / %d." %
                         (remote, request.params['login'], attempts_qty,
                          max_attempts_qty))
     return super(LoginController, self).web_login(redirect=redirect, **kw)
コード例 #15
0
def post_init_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    taxes = env['account.tax'].search([])
    op_key_taxes = taxes.filtered(lambda x: x.l10n_es_aeat_349_operation_key)
    update_account_move_line(cr, op_key_taxes)
コード例 #16
0
ファイル: order_refund.py プロジェクト: izzihector/Believa
    def create_refund(self):
        with Environment.manage():
            env_thread1 = Environment(self._cr, self._uid, self._context)
            #sale_order_obj=env_thread1['sale.order']
            for record in self:
                account_invoice_line_obj = env_thread1['account.invoice.line']
                journal_id = record.journal_id and record.journal_id.id
                inv_date = record.date_ept or fields.Date.context_today(self)
                payment_term = record.order_id.payment_term_id or False
                invoice_vals = {
                    'name':
                    record.order_id.name or '',
                    'origin':
                    account_invoice_line_obj.name,
                    'type':
                    'out_refund',
                    'reference':
                    record.order_id.client_order_ref or record.order_id.name,
                    'account_id':
                    record.order_id.partner_id.property_account_receivable_id.
                    id,
                    'partner_id':
                    record.order_id.partner_invoice_id.id,
                    'journal_id':
                    journal_id,
                    'currency_id':
                    record.order_id.pricelist_id.currency_id.id,
                    'comment':
                    record.order_id.note,
                    'payment_term_id':
                    payment_term.id,
                    'fiscal_position_id':
                    record.order_id.fiscal_position_id.id or
                    record.order_id.partner_id.property_account_position_id.id,
                    'company_id':
                    record.company_id.id,
                    'amazon_instance_id':
                    self.instance_id.id,
                    'user_id':
                    record._uid or False,
                    'date_invoice':
                    inv_date,
                    'team_id':
                    record.order_id.team_id and record.order_id.team_id.id,
                }
                invoice = env_thread1['account.invoice'].create(invoice_vals)
                record.invoice_id = invoice.id
                for line in record.amazon_refund_line_ids:
                    name = line.amazon_order_line_id.name
                    invoice_id = invoice.id
                    account = env_thread1[
                        'account.invoice.line'].get_invoice_line_account(
                            'out_refund', line.product_id,
                            record.order_id.fiscal_position_id,
                            record.company_id)
                    quantity = line.product_qty
                    price_unit = round(
                        line.total_refund / quantity,
                        self.env['decimal.precision'].precision_get(
                            'Product Price'))
                    uom_id = line.amazon_order_line_id.product_uom.id

                    vals = {
                        'product_id': line.product_id.id,
                        'name': name,
                        'invoice_id': invoice_id,
                        'account_id': account.id,
                        'price_unit': price_unit,
                        'quantity': quantity,
                        'uom_id': uom_id,
                    }
                    new_record = account_invoice_line_obj.new(vals)
                    new_record._onchange_product_id()
                    retval = new_record._convert_to_write(
                        {name: new_record[name]
                         for name in new_record._cache})
                    retval.update({
                        'price_unit': price_unit,
                        'quantity': quantity,
                        'uom_id': uom_id,
                    })

                    account_invoice_line_obj.create(retval)
                return True
コード例 #17
0
ファイル: init_hook.py プロジェクト: idreamoferp/ide_hr
def post_init_hook(cr, _):
    with Environment.manage():
        env = Environment(cr, SUPERUSER_ID, {})
        env["hr.employee"]._install_employee_firstname()
コード例 #18
0
ファイル: test_frontend.py プロジェクト: 1806933/odoo
    def test_01_pos_basic_order(self):
        cr = self.registry.cursor()
        assert cr == self.registry.test_cr
        env = Environment(cr, self.uid, {})

        # By default parent_store computation is deferred until end of
        # tests. Pricelist items however are sorted based on these
        # fields, so they need to be computed.
        env['product.category']._parent_store_compute()

        journal_obj = env['account.journal']
        account_obj = env['account.account']
        main_company = env.ref('base.main_company')
        main_pos_config = env.ref('point_of_sale.pos_config_main')

        account_receivable = account_obj.create({'code': 'X1012',
                                                 'name': 'Account Receivable - Test',
                                                 'user_type_id': env.ref('account.data_account_type_receivable').id,
                                                 'reconcile': True})
        field = self.env['ir.model.fields'].search([('name', '=', 'property_account_receivable_id'),
                                                    ('model', '=', 'res.partner'),
                                                    ('relation', '=', 'account.account')], limit=1)
        env['ir.property'].create({'name': 'property_account_receivable_id',
                                   'company_id': main_company.id,
                                   'fields_id': field.id,
                                   'value': 'account.account,' + str(account_receivable.id)})

        fixed_pricelist = env['product.pricelist'].create({
            'name': 'Fixed',
            'item_ids': [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.boni_orange').id,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 13.95,  # test for issues like in 7f260ab517ebde634fc274e928eb062463f0d88f
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.papillon_orange').id,
            })],
        })

        env['product.pricelist'].create({
            'name': 'Percentage',
            'item_ids': [(0, 0, {
                'compute_price': 'percentage',
                'percent_price': 100,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.boni_orange').id,
            }), (0, 0, {
                'compute_price': 'percentage',
                'percent_price': 99,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.papillon_orange').id,
            }), (0, 0, {
                'compute_price': 'percentage',
                'percent_price': 0,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.citron').id,
            })],
        })

        env['product.pricelist'].create({
            'name': 'Formula',
            'item_ids': [(0, 0, {
                'compute_price': 'formula',
                'price_discount': 6,
                'price_surcharge': 5,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.boni_orange').id,
            }), (0, 0, {
                # .99 prices
                'compute_price': 'formula',
                'price_surcharge': -0.01,
                'price_round': 1,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.papillon_orange').id,
            }), (0, 0, {
                'compute_price': 'formula',
                'price_min_margin': 10,
                'price_max_margin': 100,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.citron').id,
            }), (0, 0, {
                'compute_price': 'formula',
                'price_surcharge': 10,
                'price_max_margin': 5,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.limon').id,
            }), (0, 0, {
                'compute_price': 'formula',
                'price_discount': -100,
                'price_min_margin': 5,
                'price_max_margin': 20,
                'applied_on': '0_product_variant',
                'product_id': env.ref('point_of_sale.pamplemousse_rouge_pamplemousse').id,
            })],
        })

        env['product.pricelist'].create({
            'name': 'min_quantity ordering',
            'item_ids': [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'applied_on': '0_product_variant',
                'min_quantity': 2,
                'product_id': env.ref('point_of_sale.boni_orange').id,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
                'applied_on': '0_product_variant',
                'min_quantity': 1,
                'product_id': env.ref('point_of_sale.boni_orange').id,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
                'applied_on': '0_product_variant',
                'min_quantity': 2,
                'product_id': env.ref('point_of_sale.product_product_consumable').id,
            })],
        })

        env['product.pricelist'].create({
            'name': 'Product template',
            'item_ids': [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'applied_on': '1_product',
                'product_tmpl_id': env.ref('point_of_sale.boni_orange_product_template').id,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
            })],
        })

        env['product.pricelist'].create({
            # no category has precedence over category
            'name': 'Category vs no category',
            'item_ids': [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'applied_on': '2_product_category',
                'categ_id': env.ref('product.product_category_3').id,  # All / Saleable / Services
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
            })],
        })

        p = env['product.pricelist'].create({
            'name': 'Category',
            'item_ids': [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
                'applied_on': '2_product_category',
                'categ_id': env.ref('product.product_category_all').id,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'applied_on': '2_product_category',
                'categ_id': env.ref('product.product_category_3').id,  # All / Saleable / Services
            })],
        })

        today = date.today()
        one_week_ago = today - timedelta(weeks=1)
        two_weeks_ago = today - timedelta(weeks=2)
        one_week_from_now = today + timedelta(weeks=1)
        two_weeks_from_now = today + timedelta(weeks=2)

        env['product.pricelist'].create({
            'name': 'Dates',
            'item_ids': [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'date_start': two_weeks_ago.strftime(DEFAULT_SERVER_DATE_FORMAT),
                'date_end': one_week_ago.strftime(DEFAULT_SERVER_DATE_FORMAT),
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
                'date_start': today.strftime(DEFAULT_SERVER_DATE_FORMAT),
                'date_end': one_week_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT),
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 3,
                'date_start': one_week_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT),
                'date_end': two_weeks_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT),
            })],
        })

        cost_base_pricelist = env['product.pricelist'].create({
            'name': 'Cost base',
            'item_ids': [(0, 0, {
                'base': 'standard_price',
                'compute_price': 'percentage',
                'percent_price': 55,
            })],
        })

        pricelist_base_pricelist = env['product.pricelist'].create({
            'name': 'Pricelist base',
            'item_ids': [(0, 0, {
                'base': 'pricelist',
                'base_pricelist_id': cost_base_pricelist.id,
                'compute_price': 'percentage',
                'percent_price': 15,
            })],
        })

        env['product.pricelist'].create({
            'name': 'Pricelist base 2',
            'item_ids': [(0, 0, {
                'base': 'pricelist',
                'base_pricelist_id': pricelist_base_pricelist.id,
                'compute_price': 'percentage',
                'percent_price': 3,
            })],
        })

        env['product.pricelist'].create({
            'name': 'Pricelist base rounding',
            'item_ids': [(0, 0, {
                'base': 'pricelist',
                'base_pricelist_id': fixed_pricelist.id,
                'compute_price': 'percentage',
                'percent_price': 0.01,
            })],
        })

        excluded_pricelist = env['product.pricelist'].create({
            'name': 'Not loaded'
        })
        env.ref('base.res_partner_18').property_product_pricelist = excluded_pricelist

        # set the company currency to USD, otherwise it will assume
        # euro's. this will cause issues as the sales journal is in
        # USD, because of this all products would have a different
        # price
        main_company.currency_id = env.ref('base.USD')

        test_sale_journal = journal_obj.create({'name': 'Sales Journal - Test',
                                                'code': 'TSJ',
                                                'type': 'sale',
                                                'company_id': main_company.id})

        all_pricelists = env['product.pricelist'].search([('id', '!=', excluded_pricelist.id)])
        all_pricelists.write(dict(currency_id=main_company.currency_id.id))

        main_pos_config.write({
            'journal_id': test_sale_journal.id,
            'invoice_journal_id': test_sale_journal.id,
            'journal_ids': [(0, 0, {'name': 'Cash Journal - Test',
                                                       'code': 'TSC',
                                                       'type': 'cash',
                                                       'company_id': main_company.id,
                                                       'journal_user': True})],
            'available_pricelist_ids': [(4, pricelist.id) for pricelist in all_pricelists],
        })

        # open a session, the /pos/web controller will redirect to it
        main_pos_config.open_session_cb()

        # needed because tests are run before the module is marked as
        # installed. In js web will only load qweb coming from modules
        # that are returned by the backend in module_boot. Without
        # this you end up with js, css but no qweb.
        env['ir.module.module'].search([('name', '=', 'point_of_sale')], limit=1).state = 'installed'
        cr.release()

        self.phantom_js("/pos/web",
                        "odoo.__DEBUG__.services['web_tour.tour'].run('pos_pricelist')",
                        "odoo.__DEBUG__.services['web_tour.tour'].tours.pos_pricelist.ready",
                        login="******")

        self.phantom_js("/pos/web",
                        "odoo.__DEBUG__.services['web_tour.tour'].run('pos_basic_order')",
                        "odoo.__DEBUG__.services['web_tour.tour'].tours.pos_basic_order.ready",
                        login="******")

        for order in env['pos.order'].search([]):
            self.assertEqual(order.state, 'paid', "Validated order has payment of " + str(order.amount_paid) + " and total of " + str(order.amount_total))
コード例 #19
0
def migrate(cr, version):
    env = Environment(cr, SUPERUSER_ID, {})
    model_id = env['ir.model'].search([('name', '=', 'account.invoice')])
    line = env['account.documents.type'].search([('model_id', '=', model_id.id)
                                                 ])
    if not line:
        line.create({
            'model_id': model_id.id,
            'type': 'out_invoice',
            'state': 'draft',
            'print_name': 'Draft Invoice',
            'name': 'Draft Invoice',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'out_invoice',
            'state': 'open',
            'print_name': 'Invoice - %s',
            'name': 'Invoice',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'out_invoice',
            'state': 'paid',
            'print_name': 'Invoice - %s',
            'name': 'Invoice'
        })
        line.create({
            'model_id': model_id.id,
            'type': 'out_invoice',
            'state': 'cancel',
            'name': 'Cancelled Invoice',
            'display': True
        })

        line.create({
            'model_id': model_id.id,
            'type': 'out_refund',
            'state': 'draft',
            'print_name': 'Draft Credit Note',
            'name': 'Draft Credit Note',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'out_refund',
            'state': 'open',
            'print_name': 'Credit Note - %s',
            'name': 'Credit Note',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'out_refund',
            'state': 'paid',
            'print_name': 'Credit Note - %s',
            'name': 'Credit Note'
        })
        line.create({
            'model_id': model_id.id,
            'type': 'out_refund',
            'state': 'cancel',
            'name': 'Cancelled Credit Note',
            'display': True
        })

        line.create({
            'model_id': model_id.id,
            'type': 'in_invoice',
            'state': 'draft',
            'print_name': 'Vendor Bill',
            'name': 'Draft Vendor Bill',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'in_invoice',
            'state': 'open',
            'print_name': 'Vendor Bill - %s',
            'name': 'Vendor Bill',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'in_invoice',
            'state': 'paid',
            'print_name': 'Vendor Bill - %s',
            'name': 'Vendor Bill'
        })
        line.create({
            'model_id': model_id.id,
            'type': 'in_invoice',
            'state': 'cancel',
            'name': 'Cancelled Vendor Bill',
            'display': True
        })

        line.create({
            'model_id': model_id.id,
            'type': 'in_refund',
            'state': 'draft',
            'print_name': 'Draft Vendor Credit Note',
            'name': 'Vendor Credit Note',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'in_refund',
            'state': 'open',
            'print_name': 'Vendor Credit Note - %s',
            'name': 'Vendor Credit Note',
            'display': True
        })
        line.create({
            'model_id': model_id.id,
            'type': 'in_refund',
            'state': 'paid',
            'print_name': 'Vendor Credit Note - %s',
            'name': 'Vendor Credit Note'
        })
        line.create({
            'model_id': model_id.id,
            'type': 'in_refund',
            'state': 'cancel',
            'name': 'Cancelled Vendor Credit Note',
            'display': True
        })
コード例 #20
0
def post_init_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    env['res.partner'].search([])._calc_employee()
コード例 #21
0
 def test_website_price_difference_is_accessible_for_demo_user(self):
     uid = self.registry['res.users'].authenticate(db_name, 'demo', 'demo', {})
     with self.cursor() as cr:
         env = Environment(cr, uid, {})
         self._test_website_price_difference_is_accessible(env)
コード例 #22
0
ファイル: hooks.py プロジェクト: flachica/reporting-engine
def uninstall_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    recs = env["bi.sql.view"].search([])
    for rec in recs:
        rec.button_set_draft()
コード例 #23
0
def post_init_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    env.ref("access_limit_max_users.max_users_limit"
            ).max_records = env["res.users"].search_count([])
コード例 #24
0
    def action_confirm_client(self):

        try:
            new_client_id = False
            res_partner_bank_vals = {}
            res_partner_bank_obj = self.env['res.partner.bank']
            mail_server_obj = self.env['ir.mail_server']
            res_company_obj = self.env['res.company']
            clients_obj = self.env['saas_portal.client']
            ProductUOM = self.env['product.uom']

            # for country and state to be created in client db
            country_name = self.country_id.name
            country_code = self.country_id.code
            # state_name = self.state_id.name
            # state_code = self.state_id.code

            mail_server_rec = mail_server_obj.search([], limit=1)
            base_company = res_company_obj.sudo().search([], limit=1)
            self.check_outgoing_mail()

            if self.plan_id.plan_subscription_ids:
                pass
            else:
                raise Warning(
                    _('Sorry!!, Client will not be confirmed as no '
                      'Subscription is defined in the Plan '
                      'Subscription Page.'))

            res_partner_bank_obj = self.env['res.partner.bank']
            partner_iban_exist = res_partner_bank_obj.search(
                [('acc_number', '=', self.client_bank_acc),
                 ('iban', '=', self.client_bank_iban),
                 ('partner_id', '=', self.client_id.partner_id.id)],
                limit=1)

            other_partner_iban_exist = res_partner_bank_obj.search(
                [('acc_number', '=', self.client_bank_acc),
                 ('iban', '=', self.client_bank_iban),
                 ('partner_id', '!=', self.client_id.partner_id.id)],
                limit=1)

            if other_partner_iban_exist:
                raise Warning(
                    _("Bank Account no or IBAN already exist. "
                      "Please verify it again."))

            # Create his/her bank account detail and link to its partner
            if not (partner_iban_exist or other_partner_iban_exist):
                res_partner_bank_vals.update({
                    'bank_id':
                    self.client_bank_id.id,
                    'acc_number':
                    self.client_bank_acc,
                    'partner_id':
                    self.client_id.partner_id.id,
                    'iban':
                    self.client_bank_iban,
                })

                res_partner_bank_obj.sudo().create(res_partner_bank_vals)

            client_rec = clients_obj.sudo().search([
                ('partner_id', '=', self.client_id.partner_id.id),
                ('name', '=', self.database), ('state', '=', 'draft')
            ])

            # if alread the client is created by process stop due to server
            # disconnection or other sevrer related things then this will
            # delete the existing db and create another one
            if client_rec:
                client_rec._delete_database_server(force_delete=True)

            # ====== Keep this code for future use =================
            # if client_rec:
            #     new_client_id = self.plan_id.create_new_database(
            #         dbname = self.database,
            #         client_id = client_rec.client_id,
            #         partner_id = self.client_id.partner_id.id,
            #         user_id = self.client_id.id,
            #         notify_user = True,
            #         trial = False,
            #     )

            # Create New Databse with Subscription plan recordset
            trial = False
            if self.plan_type == 'trial':
                trial = True
            new_client_id = self.plan_id.create_new_database(
                dbname=self.database,
                partner_id=self.client_id.partner_id.id,
                user_id=self.client_id.id,
                notify_user=True,
                trial=trial,
            )

            new_client_rec = self.env['saas_portal.client'].browse(
                new_client_id['id'])
            vals = {
                'plan_price': self.plan_price,
                'sub_period': self.sub_period,
                'plan_type': self.plan_type,
                'merchant_id': self.merchant_id.id,
                'store_type': self.store_type,
                'req_no': self.request_no
                # 'store_id' : self.store_id.id,
            }
            new_client_rec.write(vals)

            line_dict = []
            analytic_account = self.env['account.analytic.account']
            account_invoice = self.env['account.invoice']

            ana_vals = {}
            if self.client_id.partner_id:
                ana_vals.update({
                    'partner_id':
                    self.client_id.partner_id.id,
                    'name':
                    'Subscription for ' + self.client_id.partner_id.name,
                    'recurring_rule_type':
                    self.plan_id.sub_period,
                    'recurring_invoices':
                    'True',
                    'client_id':
                    new_client_rec.id
                })

                quantity = 1
                if self.num_of_outlets > 0:
                    quantity = self.num_of_outlets

                for data in self.plan_id.plan_subscription_ids:
                    ana_vals_line = {}
                    ana_vals_line.update({
                        'product_id':
                        data.product_id.id,
                        'uom_id':
                        data.product_id.uom_id.id,
                        'name':
                        data.saas_prod_desc or data.product_id.name,
                        'price_unit':
                        data.subscription_price,
                        'quantity': (data.no_of_users * quantity) or 1
                    })
                    line_dict.append((0, 0, ana_vals_line))
                    ana_vals.update({'recurring_invoice_line_ids': line_dict})
                analytic_id = analytic_account.create(ana_vals)
                analytic_id.recurring_create_invoice()
                invoices = account_invoice.search([('contract_id', '=',
                                                    analytic_id.id)])
                invoices.action_invoice_open()
                new_client_rec.write({'subscription_id': analytic_id.id})

            res_user_vals = {
                'name': self.client_id.name,
                'login': self.client_id.login,
            }

            res_partner_vals = {
                'email': self.client_id.login,
                'website': self.company_website,
                'vat': self.vat,
                'mobile': self.contact_no,
                'phone': self.landline_no,
                'city': self.city,
                'street': self.street1,
                'street2': self.street2,
                'state_id': self.state_id.id or ''
                # 'zip' : self.zip,
            }

            # Host entry is done for the ip address and database name
            hosts = Hosts(path='/etc/hosts')
            new_entry = HostsEntry(entry_type='ipv4',
                                   address='127.0.0.1',
                                   names=[self.database])
            hosts.add([new_entry])
            hosts.write()

            # Cursor is being created of the new database created for the
            # User so that a reset password mail can be send to that user
            # of his database only
            new_cr = db_connect(self.database).cursor()
            old_vals = {
                'smtp_host': 'localhost',
                'smtp_port': 25,
                'smtp_encryption': 'none',
                'smtp_user': '',
                'smtp_pass': ''
            }

            # Outgoing mail server to be set in the users database as we
            # need to send the mail from users database
            new_vals = {
                'name': mail_server_rec.name,
                'sequence': mail_server_rec.sequence,
                'smtp_host': mail_server_rec.smtp_host,
                'smtp_port': mail_server_rec.smtp_port,
                'smtp_encryption': mail_server_rec.smtp_encryption,
                'smtp_user': mail_server_rec.smtp_user,
                'smtp_pass': mail_server_rec.smtp_pass
            }

            # Environment variable for the new db created by user
            new_env = Environment(new_cr, SUPERUSER_ID, {})
            # Get country, state and updated vals
            # country_rec, state_rec, res_partner_vals = \
            #     self.get_country_state_rec(new_env, country_name, country_code,
            #                                state_name, state_code,
            #                                res_partner_vals)
            country_rec, res_partner_vals = \
                self.get_country_state_rec(new_env, country_name, country_code,
                                           res_partner_vals)

            local_mail = new_env['ir.mail_server'].browse([1])
            # update the existing default outgoing mail server with main portal
            # outgoing mail server config
            local_mail.write(new_vals)

            # Base company vals to send base company email info in \
            # reset password mail template
            base_company_user_vals = {
                'logo': base_company.logo,
                'name': base_company.name,
                'rml_header1': base_company.rml_header1,
                'website': base_company.website,
                'phone': base_company.phone,
                'email': base_company.email,
            }

            # New user company name given by user at time of registration
            new_user_company_vals = {
                'logo': '',
                'name': self.company,
                'rml_header1': self.company,
                'website': self.company_website,
                'mobile': self.contact_no,
                'phone': self.landline_no,
                'email': self.client_id.partner_id.email,
                'vat': self.vat,
                'country_id': country_rec.id,
            }

            # finds the company in user database
            new_user_company = new_env['res.company'].search([], limit=1)
            # update the existing default company with the base company details
            new_user_company.write(base_company_user_vals)
            ir_config_obj = self.env['ir.config_parameter']
            client_url = new_env['ir.config_parameter'].get_param(
                'web.base.url')

            auth_vals = {
                'name':
                'Auth Provider for ' + self.client_id.name,
                'client_id':
                new_env['ir.config_parameter'].get_param('database.uuid'),
                'enabled':
                True,
                'body':
                'Login with Auth provider',
                'auth_endpoint':
                client_url + '/oauth2/auth',
                'scope':
                'userinfo',
                'validation_endpoint':
                client_url + '/oauth2/tokeninfo'
            }
            portal_provider = self.env['auth.oauth.provider'].create(auth_vals)

            self.client_id.write({
                'oauth_provider_id': portal_provider.id,
                'oauth_uid': 1
            })

            new_env['ir.config_parameter'].set_param('portal.database',
                                                     self.env.cr.dbname)
            new_env['ir.config_parameter'].set_param(
                'portal.url', ir_config_obj.get_param('web.base.url'))
            new_env['ir.config_parameter'].set_param('portal.provider',
                                                     portal_provider.id)
            new_env['ir.config_parameter'].set_param(
                'server.url', self.plan_id.server_id.name)
            new_cr.commit()

            # Search for the user in the new database for updating \
            # his related partner fields
            new_user = new_env['res.users'].search(
                [('login', '=', self.client_id.partner_id.email)], limit=1)
            new_res_partner = new_user.partner_id
            new_user.write(res_user_vals)
            new_res_partner.write(res_partner_vals)

            # Reset password action is called to send mail to the user
            new_user.action_reset_password_custom()
            new_cr.commit()
            # again replaces the old outgoing mail server in user db
            local_mail.write(old_vals)

            # again replace the company to the users company define
            new_user_company.write(new_user_company_vals)

            if self.store_type == 'multi':
                if self.num_of_outlets >= 0:
                    new_user_company.write({
                        'store_type':
                        self.store_type,
                        'number_of_outlets':
                        self.num_of_outlets
                    })
                    group_multi_company = new_env.ref(
                        'base.group_multi_company', False)
                    group_multi_company.write(
                        {'users': [(4, new_user.id), (4, 1)]})
            elif self.store_type == 'single':
                new_user_company.write({
                    'store_type': self.store_type,
                    'number_of_outlets': self.num_of_outlets
                })

            group_store_master = new_env.ref(
                'mint_client_multi_store.saas_store_manager')
            group_store_master.write({'users': [(4, new_user.id)]})
            new_cr.commit()
            new_cr.close()

            return self.write({'state': 'confirmed'})
        except Exception as e:
            raise UserError(
                _("Something Went Wrong while Creating the "
                  "Database. Instead We Got:\n%s") % ustr(e))
コード例 #25
0
def uninstall_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    for rec in env['ks_dashboard_ninja.board'].search([]):
        rec.ks_dashboard_client_action_id.unlink()
        rec.ks_dashboard_menu_id.unlink()
コード例 #26
0
def post_init_hook(cr, pool):
    env = Environment(cr, SUPERUSER_ID, {})
    ResUsers = env['res.users']
    users = ResUsers.with_context(active_test=False).search([])
    users.mapped('partner_id')._disable_users_partners()
コード例 #27
0
    def create_aeroo_report(self, cr, uid, ids, data, report_xml, context):
        """ Return an aeroo report generated with aeroolib
        """
        context = context.copy()
        assert report_xml.out_format.code in (
            'oo-odt',
            'oo-ods',
            'oo-doc',
            'oo-xls',
            'oo-csv',
            'oo-pdf',
        )
        assert report_xml.in_format in ('oo-odt', 'oo-ods')

        output_format = report_xml.out_format.code[3:]
        input_format = report_xml.in_format[3:]

        oo_parser = self.parser(cr, uid, self.name2, context=context)

        env = Environment(cr, uid, context)
        objects = env[self.table].browse(ids)

        oo_parser.localcontext.update(context)
        oo_parser.set_context(objects, data, ids, report_xml.report_type)

        oo_parser.localcontext['data'] = data
        oo_parser.localcontext['user_lang'] = context.get('lang', False)
        oo_parser.localcontext['o'] = objects[0]

        xfunc = ExtraFunctions(cr, uid, report_xml.id, oo_parser.localcontext)
        oo_parser.localcontext.update(xfunc.functions)

        template = report_xml.get_aeroo_report_template(objects[0])

        template_io = StringIO()
        template_io.write(template)
        serializer = OOSerializer(template_io)
        basic = Template(source=template_io,
                         serializer=serializer,
                         lookup=DynamicLookup)

        data = basic.generate(**oo_parser.localcontext).render().getvalue()

        if input_format != output_format:
            temp_file = self.generate_temporary_file(cr, uid, ids, data,
                                                     input_format)
            filedir, filename = os.path.split(temp_file.name)

            libreoffice_location = (
                report_xml.env['ir.config_parameter'].get_param(
                    'report_aeroo.libreoffice_location'))

            if not libreoffice_location:
                raise ValidationError(
                    _('Aeroo reports are wrongly configured. '
                      'The global parameter report_aeroo.libreoffice_location '
                      'must be defined.'))

            cmd = [
                libreoffice_location, "--headless", "--convert-to",
                output_format, "--outdir", filedir, temp_file.name
            ]

            self.run_subprocess(cr, uid, ids, report_xml, temp_file, cmd)

            output_filename = temp_file.name[:-3] + output_format

            with open(output_filename, 'r') as f:
                data = f.read()

            os.remove(temp_file.name)
            os.remove(output_filename)

        return data, output_format
コード例 #28
0
def migrate(cr, version):
    env = Environment(cr, SUPERUSER_ID, {})
    for line in env['account.move.line'].search([('tax_sign', '=', 0)]):
        line.write({'tax_sign': line.invoice_id and line.invoice_id.type in ['in_refund', 'out_refund'] and -1 or 1 or 1})
コード例 #29
0
def post_init_hook(cr, pool):
    env = Environment(cr, SUPERUSER_ID, {})
    env['res.partner'].search(
        [('birthdate', "!=", False)])._birthdate_inverse()
コード例 #30
0
ファイル: hooks.py プロジェクト: vialaurea/OCA-sale-workflow
def add_to_group_stock_packaging(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    conf_page = env['res.config.settings'].create({})
    conf_page.group_stock_packaging = True
    conf_page.execute()
コード例 #31
0
def disable_update_notification_cron(cr):
    env = Environment(cr, SUPERUSER_ID, {})
    cron = env.ref('mail.ir_cron_module_update_notification', False)
    if cron:
        cron.active = tools.config.get(
            'enable_publisher_warranty_contract_notification', False)
コード例 #32
0
ファイル: test_frontend.py プロジェクト: niulinlnc/cubicerp
    def test_01_pos_basic_order(self):
        cr = self.registry.cursor()
        assert cr == self.registry.test_cr
        env = Environment(cr, self.uid, {})

        # By default parent_store computation is deferred until end of
        # tests. Pricelist items however are sorted based on these
        # fields, so they need to be computed.
        env['product.category']._parent_store_compute()

        journal_obj = env['account.journal']
        account_obj = env['account.account']
        main_company = env.ref('base.main_company')
        main_pos_config = env.ref('point_of_sale.pos_config_main')

        account_receivable = account_obj.create({
            'code':
            'X1012',
            'name':
            'Account Receivable - Test',
            'user_type_id':
            env.ref('account.data_account_type_receivable').id,
            'reconcile':
            True
        })
        field = self.env['ir.model.fields'].search(
            [('name', '=', 'property_account_receivable_id'),
             ('model', '=', 'res.partner'),
             ('relation', '=', 'account.account')],
            limit=1)
        env['ir.property'].create({
            'name':
            'property_account_receivable_id',
            'company_id':
            main_company.id,
            'fields_id':
            field.id,
            'value':
            'account.account,' + str(account_receivable.id)
        })

        # test an extra price on an attribute
        pear = env.ref('point_of_sale.poire_conference')
        attribute_value = env['product.attribute.value'].create({
            'name':
            'add 2',
            'product_ids': [(6, 0, [pear.id])],
            'attribute_id':
            env['product.attribute'].create({
                'name': 'add 2',
            }).id,
        })
        env['product.attribute.price'].create({
            'product_tmpl_id':
            pear.product_tmpl_id.id,
            'price_extra':
            2,
            'value_id':
            attribute_value.id,
        })

        fixed_pricelist = env['product.pricelist'].create({
            'name':
            'Fixed',
            'item_ids': [
                (0, 0, {
                    'compute_price': 'fixed',
                    'fixed_price': 1,
                }),
                (0, 0, {
                    'compute_price': 'fixed',
                    'fixed_price': 2,
                    'applied_on': '0_product_variant',
                    'product_id': env.ref('point_of_sale.boni_orange').id,
                }),
                (
                    0,
                    0,
                    {
                        'compute_price': 'fixed',
                        'fixed_price':
                        13.95,  # test for issues like in 7f260ab517ebde634fc274e928eb062463f0d88f
                        'applied_on': '0_product_variant',
                        'product_id':
                        env.ref('point_of_sale.papillon_orange').id,
                    })
            ],
        })

        env['product.pricelist'].create({
            'name':
            'Percentage',
            'item_ids': [(0, 0, {
                'compute_price':
                'percentage',
                'percent_price':
                100,
                'applied_on':
                '0_product_variant',
                'product_id':
                env.ref('point_of_sale.boni_orange').id,
            }),
                         (0, 0, {
                             'compute_price':
                             'percentage',
                             'percent_price':
                             99,
                             'applied_on':
                             '0_product_variant',
                             'product_id':
                             env.ref('point_of_sale.papillon_orange').id,
                         }),
                         (0, 0, {
                             'compute_price': 'percentage',
                             'percent_price': 0,
                             'applied_on': '0_product_variant',
                             'product_id': env.ref('point_of_sale.citron').id,
                         })],
        })

        env['product.pricelist'].create({
            'name':
            'Formula',
            'item_ids': [
                (0, 0, {
                    'compute_price': 'formula',
                    'price_discount': 6,
                    'price_surcharge': 5,
                    'applied_on': '0_product_variant',
                    'product_id': env.ref('point_of_sale.boni_orange').id,
                }),
                (
                    0,
                    0,
                    {
                        # .99 prices
                        'compute_price': 'formula',
                        'price_surcharge': -0.01,
                        'price_round': 1,
                        'applied_on': '0_product_variant',
                        'product_id':
                        env.ref('point_of_sale.papillon_orange').id,
                    }),
                (0, 0, {
                    'compute_price': 'formula',
                    'price_min_margin': 10,
                    'price_max_margin': 100,
                    'applied_on': '0_product_variant',
                    'product_id': env.ref('point_of_sale.citron').id,
                }),
                (0, 0, {
                    'compute_price': 'formula',
                    'price_surcharge': 10,
                    'price_max_margin': 5,
                    'applied_on': '0_product_variant',
                    'product_id': env.ref('point_of_sale.limon').id,
                }),
                (0, 0, {
                    'compute_price':
                    'formula',
                    'price_discount':
                    -100,
                    'price_min_margin':
                    5,
                    'price_max_margin':
                    20,
                    'applied_on':
                    '0_product_variant',
                    'product_id':
                    env.ref(
                        'point_of_sale.pamplemousse_rouge_pamplemousse').id,
                })
            ],
        })

        env['product.pricelist'].create({
            'name':
            'min_quantity ordering',
            'item_ids':
            [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'applied_on': '0_product_variant',
                'min_quantity': 2,
                'product_id': env.ref('point_of_sale.boni_orange').id,
            }),
             (0, 0, {
                 'compute_price': 'fixed',
                 'fixed_price': 2,
                 'applied_on': '0_product_variant',
                 'min_quantity': 1,
                 'product_id': env.ref('point_of_sale.boni_orange').id,
             }),
             (0, 0, {
                 'compute_price':
                 'fixed',
                 'fixed_price':
                 2,
                 'applied_on':
                 '0_product_variant',
                 'min_quantity':
                 2,
                 'product_id':
                 env.ref('point_of_sale.product_product_consumable').id,
             })],
        })

        env['product.pricelist'].create({
            'name':
            'Product template',
            'item_ids': [(0, 0, {
                'compute_price':
                'fixed',
                'fixed_price':
                1,
                'applied_on':
                '1_product',
                'product_tmpl_id':
                env.ref('point_of_sale.boni_orange_product_template').id,
            }), (0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 2,
            })],
        })

        env['product.pricelist'].create({
            # no category has precedence over category
            'name':
            'Category vs no category',
            'item_ids': [
                (
                    0,
                    0,
                    {
                        'compute_price': 'fixed',
                        'fixed_price': 1,
                        'applied_on': '2_product_category',
                        'categ_id': env.ref('product.product_category_3').
                        id,  # All / Saleable / Services
                    }),
                (0, 0, {
                    'compute_price': 'fixed',
                    'fixed_price': 2,
                })
            ],
        })

        p = env['product.pricelist'].create({
            'name':
            'Category',
            'item_ids': [
                (0, 0, {
                    'compute_price': 'fixed',
                    'fixed_price': 2,
                    'applied_on': '2_product_category',
                    'categ_id': env.ref('product.product_category_all').id,
                }),
                (
                    0,
                    0,
                    {
                        'compute_price': 'fixed',
                        'fixed_price': 1,
                        'applied_on': '2_product_category',
                        'categ_id': env.ref('product.product_category_3').
                        id,  # All / Saleable / Services
                    })
            ],
        })

        today = date.today()
        one_week_ago = today - timedelta(weeks=1)
        two_weeks_ago = today - timedelta(weeks=2)
        one_week_from_now = today + timedelta(weeks=1)
        two_weeks_from_now = today + timedelta(weeks=2)

        public_pricelist = env['product.pricelist'].create({
            'name':
            'Public Pricelist',
        })

        env['product.pricelist'].create({
            'name':
            'Dates',
            'item_ids':
            [(0, 0, {
                'compute_price': 'fixed',
                'fixed_price': 1,
                'date_start':
                two_weeks_ago.strftime(DEFAULT_SERVER_DATE_FORMAT),
                'date_end': one_week_ago.strftime(DEFAULT_SERVER_DATE_FORMAT),
            }),
             (0, 0, {
                 'compute_price':
                 'fixed',
                 'fixed_price':
                 2,
                 'date_start':
                 today.strftime(DEFAULT_SERVER_DATE_FORMAT),
                 'date_end':
                 one_week_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT),
             }),
             (0, 0, {
                 'compute_price':
                 'fixed',
                 'fixed_price':
                 3,
                 'date_start':
                 one_week_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT),
                 'date_end':
                 two_weeks_from_now.strftime(DEFAULT_SERVER_DATE_FORMAT),
             })],
        })

        cost_base_pricelist = env['product.pricelist'].create({
            'name':
            'Cost base',
            'item_ids': [(0, 0, {
                'base': 'standard_price',
                'compute_price': 'percentage',
                'percent_price': 55,
            })],
        })

        pricelist_base_pricelist = env['product.pricelist'].create({
            'name':
            'Pricelist base',
            'item_ids': [(0, 0, {
                'base': 'pricelist',
                'base_pricelist_id': cost_base_pricelist.id,
                'compute_price': 'percentage',
                'percent_price': 15,
            })],
        })

        env['product.pricelist'].create({
            'name':
            'Pricelist base 2',
            'item_ids': [(0, 0, {
                'base': 'pricelist',
                'base_pricelist_id': pricelist_base_pricelist.id,
                'compute_price': 'percentage',
                'percent_price': 3,
            })],
        })

        env['product.pricelist'].create({
            'name':
            'Pricelist base rounding',
            'item_ids': [(0, 0, {
                'base': 'pricelist',
                'base_pricelist_id': fixed_pricelist.id,
                'compute_price': 'percentage',
                'percent_price': 0.01,
            })],
        })

        excluded_pricelist = env['product.pricelist'].create(
            {'name': 'Not loaded'})
        env.ref('base.res_partner_18'
                ).property_product_pricelist = excluded_pricelist

        # set the company currency to USD, otherwise it will assume
        # euro's. this will cause issues as the sales journal is in
        # USD, because of this all products would have a different
        # price
        main_company.currency_id = env.ref('base.USD')

        test_sale_journal = journal_obj.create({
            'name': 'Sales Journal - Test',
            'code': 'TSJ',
            'type': 'sale',
            'company_id': main_company.id
        })

        all_pricelists = env['product.pricelist'].search([
            ('id', '!=', excluded_pricelist.id)
        ])
        all_pricelists.write(dict(currency_id=main_company.currency_id.id))

        main_pos_config.write({
            'journal_id':
            test_sale_journal.id,
            'invoice_journal_id':
            test_sale_journal.id,
            'journal_ids': [(0, 0, {
                'name': 'Cash Journal - Test',
                'code': 'TSC',
                'type': 'cash',
                'company_id': main_company.id,
                'journal_user': True
            })],
            'pricelist_id':
            public_pricelist.id,
            'available_pricelist_ids':
            [(4, pricelist.id) for pricelist in all_pricelists],
        })

        # Change the default sale pricelist of customers,
        # so the js tests can expect deterministically this pricelist when selecting a customer.
        field = env['ir.model.fields']._get('res.partner',
                                            'property_product_pricelist')
        env['ir.property'].search([
            ('name', '=', 'property_product_pricelist'),
            ('fields_id', '=', field.id), ('res_id', '=', False)
        ]).write(
            {'value_reference': 'product.pricelist,%s' % public_pricelist.id})

        # open a session, the /pos/web controller will redirect to it
        main_pos_config.open_session_cb()

        # needed because tests are run before the module is marked as
        # installed. In js web will only load qweb coming from modules
        # that are returned by the backend in module_boot. Without
        # this you end up with js, css but no qweb.
        env['ir.module.module'].search([('name', '=', 'point_of_sale')],
                                       limit=1).state = 'installed'
        cr.release()

        self.phantom_js(
            "/pos/web",
            "odoo.__DEBUG__.services['web_tour.tour'].run('pos_pricelist')",
            "odoo.__DEBUG__.services['web_tour.tour'].tours.pos_pricelist.ready",
            login="******")

        self.phantom_js(
            "/pos/web",
            "odoo.__DEBUG__.services['web_tour.tour'].run('pos_basic_order')",
            "odoo.__DEBUG__.services['web_tour.tour'].tours.pos_basic_order.ready",
            login="******")

        for order in env['pos.order'].search([]):
            self.assertEqual(
                order.state, 'paid',
                "Validated order has payment of " + str(order.amount_paid) +
                " and total of " + str(order.amount_total))
コード例 #33
0
    def test_01_pos_basic_order(self):
        cr = self.registry.cursor()
        assert cr == self.registry.test_cr
        env = Environment(cr, self.uid, {})

        journal_obj = env['account.journal']
        account_obj = env['account.account']
        main_company = env.ref('base.main_company')
        main_pos_config = env.ref('point_of_sale.pos_config_main')

        account_receivable = account_obj.create({
            'code':
            'X1012',
            'name':
            'Account Receivable - Test',
            'user_type_id':
            env.ref('account.data_account_type_receivable').id,
            'reconcile':
            True
        })
        field = self.env['ir.model.fields'].search(
            [('name', '=', 'property_account_receivable_id'),
             ('model', '=', 'res.partner'),
             ('relation', '=', 'account.account')],
            limit=1)
        env['ir.property'].create({
            'name':
            'property_account_receivable_id',
            'company_id':
            main_company.id,
            'fields_id':
            field.id,
            'value':
            'account.account,' + str(account_receivable.id)
        })

        # set the company currency to USD, otherwise it will assume
        # euro's. this will cause issues as the sale journal is in
        # USD, because of this all products would have a different
        # price
        main_company.currency_id = env.ref('base.USD')

        test_sale_journal = journal_obj.create({
            'name': 'Sale Journal - Test',
            'code': 'TSJ',
            'type': 'sale',
            'company_id': main_company.id
        })

        main_pos_config.journal_id = test_sale_journal
        main_pos_config.write({
            'journal_ids': [(0, 0, {
                'name': 'Cash Journal - Test',
                'code': 'TSC',
                'type': 'cash',
                'company_id': main_company.id,
                'journal_user': True
            })]
        })

        # open a session, the /pos/web controller will redirect to it
        main_pos_config.open_session_cb()

        # needed because tests are run before the module is marked as
        # installed. In js web will only load qweb coming from modules
        # that are returned by the backend in module_boot. Without
        # this you end up with js, css but no qweb.
        env['ir.module.module'].search([('name', '=', 'point_of_sale')],
                                       limit=1).state = 'installed'
        cr.release()

        self.phantom_js(
            "/pos/web",
            "odoo.__DEBUG__.services['web.Tour'].run('pos_basic_order', 'test')",
            "odoo.__DEBUG__.services['web.Tour'].tours.pos_basic_order",
            login="******")

        for order in env['pos.order'].search([]):
            self.assertEqual(
                order.state, 'paid',
                "Validated order has payment of " + str(order.amount_paid) +
                " and total of " + str(order.amount_total))
コード例 #34
0
ファイル: __init__.py プロジェクト: niulinlnc/access-addons
def post_init_hook(cr, registry):
    env = Environment(cr, SUPERUSER_ID, {})
    ref_record = env.ref("access_limit_max_users.max_users_limit")
    ref_record.max_records = env["res.users"].search_count(
        safe_eval(ref_record.domain))