Ejemplo n.º 1
0
    def test_product_margin(self):
        ''' In order to test the product_margin module '''

        # load account_minimal_test.xml file for chart of account in configuration
        tools.convert_file(
            self.cr, 'product_margin',
            get_resource_path('account', 'test', 'account_minimal_test.xml'),
            {}, 'init', False, 'test', self.registry._assertion_report)

        supplier = self.env['res.partner'].create({
            'name': 'Supplier',
            'supplier': True
        })
        customer = self.env['res.partner'].create({
            'name': 'Customer',
            'customer': True
        })
        ipad = self.env.ref("product.product_product_4")

        # Create supplier invoice and customer invoice to test product margin.
        # Define supplier invoices
        self.create_account_invoice('in_invoice', supplier, ipad, 10.0, 300.00)
        self.create_account_invoice('in_invoice', supplier, ipad, 4.0, 450.00)
        # Define Customer Invoices
        self.create_account_invoice('out_invoice', customer, ipad, 20.0,
                                    750.00)
        self.create_account_invoice('out_invoice', customer, ipad, 10.0,
                                    550.00)

        result = ipad._compute_product_margin_fields_values()

        # Sale turnover ( Quantity * Price Subtotal / Quantity)
        sale_turnover = ((20.0 * 750.00) + (10.0 * 550.00))

        # Expected sale (Total quantity * Sale price)
        sale_expected = (750.00 * 30.0)

        # Purchase total cost (Quantity * Unit price)
        purchase_total_cost = ((10.0 * 300.00) + (4.0 * 450.00))

        # Purchase normal cost ( Total quantity * Cost price)
        purchase_normal_cost = (14.0 * 500.00)

        total_margin = sale_turnover - purchase_total_cost
        expected_margin = sale_expected - purchase_normal_cost

        # Check total margin
        self.assertEqual(result[ipad.id]['total_margin'], total_margin,
                         "Wrong Total Margin.")

        # Check expected margin
        self.assertEqual(result[ipad.id]['expected_margin'], expected_margin,
                         "Wrong Expected Margin.")
Ejemplo n.º 2
0
def load_data(cr, idref, mode, kind, package, report):
    """

    kind: data, demo, test, init_xml, update_xml, demo_xml.

    noupdate is False, unless it is demo data or it is csv data in
    init mode.

    """
    def _get_files_of_kind(kind):
        if kind == 'demo':
            kind = ['demo_xml', 'demo']
        elif kind == 'data':
            kind = ['init_xml', 'update_xml', 'data']
        if isinstance(kind, str):
            kind = [kind]
        files = []
        for k in kind:
            for f in package.data[k]:
                files.append(f)
                if k.endswith('_xml') and not (k == 'init_xml'
                                               and not f.endswith('.xml')):
                    # init_xml, update_xml and demo_xml are deprecated except
                    # for the case of init_xml with csv and sql files as
                    # we can't specify noupdate for those file.
                    correct_key = 'demo' if k.count('demo') else 'data'
                    _logger.warning(
                        "module %s: key '%s' is deprecated in favor of '%s' for file '%s'.",
                        package.name, k, correct_key, f)
        return files

    try:
        if kind in ('demo', 'test'):
            threading.currentThread().testing = True
        for filename in _get_files_of_kind(kind):
            _logger.info("loading %s/%s", package.name, filename)
            noupdate = False
            if kind in ('demo', 'demo_xml') or (filename.endswith('.csv') and
                                                kind in ('init', 'init_xml')):
                noupdate = True
            tools.convert_file(cr, package.name, filename, idref, mode,
                               noupdate, kind, report)
    finally:
        if kind in ('demo', 'test'):
            threading.currentThread().testing = False
Ejemplo n.º 3
0
 def _load(self, module, *args):
     tools.convert_file(self.cr, 'account_voucher',
                        get_resource_path(module, *args),
                        {}, 'init', False, 'test', self.registry._assertion_report)
Ejemplo n.º 4
0
 def _load(self, module, *args):
     tools.convert_file(self.cr, 'hr_payroll_account',
                        get_module_resource(module, *args), {}, 'init',
                        False, 'test', self.registry._assertion_report)
Ejemplo n.º 5
0
    def _import_module(self, module, path, force=False):
        known_mods = self.search([])
        known_mods_names = {m.name: m for m in known_mods}
        installed_mods = [m.name for m in known_mods if m.state == 'installed']

        terp = load_information_from_description_file(module, mod_path=path)
        if not terp:
            return False
        values = self.get_values_from_terp(terp)
        if 'version' in terp:
            values['latest_version'] = terp['version']

        unmet_dependencies = set(terp['depends']).difference(installed_mods)

        if unmet_dependencies:
            if (unmet_dependencies == set(['web_studio'])
                    and _is_studio_custom(path)):
                err = _("Studio customizations require Studio")
            else:
                err = _("Unmet module dependencies: %s") % ', '.join(
                    unmet_dependencies, )
            raise UserError(err)
        elif 'web_studio' not in installed_mods and _is_studio_custom(path):
            raise UserError(
                _("Studio customizations require the Swerp Studio app."))

        mod = known_mods_names.get(module)
        if mod:
            mod.write(dict(state='installed', **values))
            mode = 'update' if not force else 'init'
        else:
            assert terp.get('installable', True), "Module not installable"
            self.create(
                dict(name=module, state='installed', imported=True, **values))
            mode = 'init'

        for kind in ['data', 'init_xml', 'update_xml']:
            for filename in terp[kind]:
                ext = os.path.splitext(filename)[1].lower()
                if ext not in ('.xml', '.csv', '.sql'):
                    _logger.info("module %s: skip unsupported file %s", module,
                                 filename)
                    continue
                _logger.info("module %s: loading %s", module, filename)
                noupdate = False
                if ext == '.csv' and kind in ('init', 'init_xml'):
                    noupdate = True
                pathname = opj(path, filename)
                idref = {}
                convert_file(self.env.cr,
                             module,
                             filename,
                             idref,
                             mode=mode,
                             noupdate=noupdate,
                             kind=kind,
                             pathname=pathname)

        path_static = opj(path, 'static')
        IrAttachment = self.env['ir.attachment']
        if os.path.isdir(path_static):
            for root, dirs, files in os.walk(path_static):
                for static_file in files:
                    full_path = opj(root, static_file)
                    with open(full_path, 'rb') as fp:
                        data = base64.b64encode(fp.read())
                    url_path = '/{}{}'.format(
                        module,
                        full_path.split(path)[1].replace(os.path.sep, '/'))
                    if not isinstance(url_path, pycompat.text_type):
                        url_path = url_path.decode(sys.getfilesystemencoding())
                    filename = os.path.split(url_path)[1]
                    values = dict(
                        name=filename,
                        datas_fname=filename,
                        url=url_path,
                        res_model='ir.ui.view',
                        type='binary',
                        datas=data,
                    )
                    attachment = IrAttachment.search([('url', '=', url_path),
                                                      ('type', '=', 'binary'),
                                                      ('res_model', '=',
                                                       'ir.ui.view')])
                    if attachment:
                        attachment.write(values)
                    else:
                        IrAttachment.create(values)

        return True
Ejemplo n.º 6
0
 def _load(self, module, *args):
     tools.convert_file(self.cr, 'stock_dropshipping',
                        get_module_resource(module, *args), {}, 'init',
                        False, 'test', self.registry._assertion_report)