Example #1
0
    def test_boolean(self):
        'Test boolean'
        pool = Pool()
        Boolean = pool.get('test.import_data.boolean')

        self.assertEqual(Boolean.import_data(['boolean'],
            [['True']]), 1)

        self.assertEqual(Boolean.import_data(['boolean'],
            [['1']]), 1)

        self.assertEqual(Boolean.import_data(['boolean'],
            [['False']]), 1)

        self.assertEqual(Boolean.import_data(['boolean'],
            [['0']]), 1)

        self.assertEqual(Boolean.import_data(['boolean'],
            [['']]), 1)

        self.assertEqual(Boolean.import_data(['boolean'],
            [['True'], ['False']]), 2)

        self.assertRaises(ValueError, Boolean.import_data,
            ['boolean'], [['foo']])
Example #2
0
    def get_quantity(cls, products, name):
        Date = Pool().get('ir.date')

        quantities = dict((p.id, 0.0) for p in products)
        if not Transaction().context.get('locations'):
            return quantities

        context = {}
        if (name == 'quantity'
                and Transaction().context.get('stock_date_end')
                and Transaction().context.get('stock_date_end') >
                Date.today()):
            context['stock_date_end'] = Date.today()

        if name == 'forecast_quantity':
            context['forecast'] = True
            if not Transaction().context.get('stock_date_end'):
                context['stock_date_end'] = datetime.date.max
        with Transaction().set_context(context):
            pbl = cls.products_by_location(
                location_ids=Transaction().context['locations'],
                product_ids=quantities.keys(), with_childs=True)

        for location in Transaction().context['locations']:
            for product in products:
                quantities[product.id] += pbl.get((location, product.id), 0.0)
        return quantities
Example #3
0
    def test_float_required(self):
        'Test required float'
        pool = Pool()
        FloatRequired = pool.get('test.import_data.float_required')
        transaction = Transaction()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['-1.1']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1']]), 1)

        self.assertRaises(UserError, FloatRequired.import_data,
            ['float'], [['']])
        transaction.cursor.rollback()

        self.assertEqual(FloatRequired.import_data(['float'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(ValueError, FloatRequired.import_data,
            ['float'], [['foo']])

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0']]), 1)

        self.assertEqual(FloatRequired.import_data(['float'],
            [['0.0']]), 1)
Example #4
0
    def test_numeric(self):
        'Test numeric'
        pool = Pool()
        Numeric = pool.get('test.import_data.numeric')

        self.assertEqual(Numeric.import_data(['numeric'],
            [['1.1']]), 1)

        self.assertEqual(Numeric.import_data(['numeric'],
            [['-1.1']]), 1)

        self.assertEqual(Numeric.import_data(['numeric'],
            [['1']]), 1)

        self.assertEqual(Numeric.import_data(['numeric'],
            [['']]), 1)

        self.assertEqual(Numeric.import_data(['numeric'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(InvalidOperation, Numeric.import_data,
            ['numeric'], [['foo']])

        self.assertEqual(Numeric.import_data(['numeric'],
            [['0']]), 1)

        self.assertEqual(Numeric.import_data(['numeric'],
            [['0.0']]), 1)
Example #5
0
    def transition_force(self):
        pool = Pool()
        Production = pool.get('production')

        Production.assign_force(
            [Production(Transaction().context['active_id'])])
        return 'end'
Example #6
0
    def test_float(self):
        'Test float'
        pool = Pool()
        Float = pool.get('test.import_data.float')

        self.assertEqual(Float.import_data(['float'],
            [['1.1']]), 1)

        self.assertEqual(Float.import_data(['float'],
            [['-1.1']]), 1)

        self.assertEqual(Float.import_data(['float'],
            [['1']]), 1)

        self.assertEqual(Float.import_data(['float'],
            [['']]), 1)

        self.assertEqual(Float.import_data(['float'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(ValueError, Float.import_data,
            ['float'], [['foo']])

        self.assertEqual(Float.import_data(['float'],
            [['0']]), 1)

        self.assertEqual(Float.import_data(['float'],
            [['0.0']]), 1)
Example #7
0
 def get_origin(cls):
     Model = Pool().get('ir.model')
     models = cls._get_origin()
     models = Model.search([
             ('model', 'in', models),
             ])
     return [(None, '')] + [(m.model, m.name) for m in models]
Example #8
0
    def do_process(self, action):
        pool = Pool()
        Payment = pool.get('account.payment')
        payments = Payment.browse(Transaction().context['active_ids'])

        for payment in payments:
            if payment.line and payment.line.payment_amount < 0:
                self.raise_user_warning(str(payment),
                    'overpay', {
                        'payment': payment.rec_name,
                        'line': payment.line.rec_name,
                        })

        groups = []
        payments = sorted(payments, key=self._group_payment_key)
        for key, grouped_payments in groupby(payments,
                key=self._group_payment_key):
            def group():
                group = self._new_group(dict(key))
                group.save()
                groups.append(group)
                return group
            Payment.process(list(grouped_payments), group)

        return action, {
            'res_id': [g.id for g in groups],
            }
Example #9
0
    def get_sale_price(self):
        """Estimates the shipment rate for the current shipment

        The get_sale_price implementation by tryton's carrier module
        returns a tuple of (value, currency_id)

        :returns: A tuple of (value, currency_id which in this case is USD)
        """
        Sale = Pool().get('sale.sale')
        Shipment = Pool().get('stock.shipment.out')
        Currency = Pool().get('currency.currency')

        shipment_id = Transaction().context.get('shipment')
        sale_id = Transaction().context.get('sale')
        default_currency, = Currency.search([('code', '=', 'USD')])

        if Transaction().context.get('ignore_carrier_computation'):
            return Decimal('0'), default_currency.id
        if not (sale_id or shipment_id):
            return Decimal('0'), default_currency.id

        if self.carrier_cost_method != 'ups':
            return super(Carrier, self).get_sale_price()

        if sale_id:
            return Sale(sale_id).get_ups_shipping_cost()

        if shipment_id and shipment_id > 0:
            # get_ups_shipping_cost must not be called if shipment is not saved.
            # If shipment is saved/active record is created properly,
            # then the ID must be a positive integer.
            return Shipment(shipment_id).get_ups_shipping_cost()

        return Decimal('0'), default_currency.id
    def get_context(cls, objects, data):
        Product = Pool().get('product.product')
        Locations = Pool().get('stock.location')

        report_context = super(ProductLedgerReport, cls).get_context(
            objects, data
        )
        records = []
        summary = {}
        for product_id in data['products']:
            product = Product(product_id)
            record = {
                'product': product,
                'purchases': cls.get_purchases(product.id, data),
                'productions': cls.get_productions(product.id, data),
                'customers': cls.get_customers(product.id, data),
                'lost_and_founds': cls.get_lost_and_founds(product.id, data),
                'consumed': cls.get_consumed(product.id, data)
            }
            records.append(record)
            summary[product] = cls.get_summary(record, data)

        report_context['summary'] = summary
        report_context['warehouses'] = Locations.browse(data['warehouses'])
        return report_context
Example #11
0
    def read(cls, ids, fields_names=None):
        res = super(View, cls).read(ids, fields_names=fields_names)

        if Transaction().user == 0:
            return res

        pool = Pool()
        action = pool.get('ir.action')
        ids_action = action.search([('name', '=', 'Surface Terriere'),
                ('type', '=', 'ir.action.act_window')])

        assert(len(ids_action) == 1), len(ids_action)

        #act_window = pool.get('ir.action.act_window')
        #ids_act_window = act_window.search([('action', '=', ids_action[0])])

        dynamic_view_id = cls.dynamic_view_id()
        if not dynamic_view_id:
            # Restart the cache
            cls._dynamic_view_cache.reset()

        #print "dview"
        if fields_names is None \
                or 'arch' in fields_names:
            #print ids, dynamic_view_id
            if dynamic_view_id in ids:
                for res2 in res:
                    if res2['id'] == dynamic_view_id:
                        #print "dview2"
                        res2['arch'] ='<board string="Comparaison surfaces terrieres"><action name="6100"/></board>'
        #from pprint import pprint
        #print "pprint psdrf"
        #pprint(Transaction().context)
        #pprint(res)
        return res
Example #12
0
    def nereid_add_payment_profile(cls):
        """
        Add card to user profile.
        """
        AddPaymentProfileWizard = Pool().get(
            'party.party.payment_profile.add', type='wizard'
        )
        Address = Pool().get('party.address')

        gateway = request.nereid_website.credit_card_gateway
        form = PaymentProfileForm()

        if form.validate_on_submit():
            profile_wiz = AddPaymentProfileWizard(
                AddPaymentProfileWizard.create()[0]
            )
            profile_wiz.card_info.party = current_user.party
            profile_wiz.card_info.address = Address(form.address.data)
            profile_wiz.card_info.provider = gateway.provider
            profile_wiz.card_info.gateway = gateway
            profile_wiz.card_info.owner = form.owner.data
            profile_wiz.card_info.number = form.number.data
            profile_wiz.card_info.expiry_month = form.expiry_month.data
            profile_wiz.card_info.expiry_year = \
                unicode(form.expiry_year.data)
            profile_wiz.card_info.csc = form.cvv.data

            try:
                profile_wiz.transition_add()
                flash(_('Credit Card added successfully!'))
            except UserError, e:  # pragma: no cover
                flash(_(e.message))
            finally:
Example #13
0
    def write(cls, *args):
        pool = Pool()
        Sale = pool.get('sale.sale')
        SaleLine = pool.get('sale.line')

        super(ShipmentOutReturn, cls).write(*args)

        actions = iter(args)
        for shipments, values in zip(actions, actions):
            if values.get('state') != 'received':
                continue
            sales = []
            move_ids = []
            for shipment in shipments:
                move_ids.extend([x.id for x in shipment.incoming_moves])

            with Transaction().set_context(_check_access=False):
                sale_lines = SaleLine.search([
                        ('moves', 'in', move_ids),
                        ])
                if sale_lines:
                    for sale_line in sale_lines:
                        if sale_line.sale not in sales:
                            sales.append(sale_line.sale)

                    sales = Sale.browse([s.id for s in sales])
                    Sale.process(sales)
Example #14
0
 def origin_name(self):
     pool = Pool()
     SaleLine = pool.get('sale.line')
     name = super(Move, self).origin_name
     if isinstance(self.origin, SaleLine):
         name = self.origin.sale.rec_name
     return name
Example #15
0
 def check_sled_period_closed(cls, lots):
     Period = Pool().get('stock.period')
     Move = Pool().get('stock.move')
     periods = Period.search([
             ('state', '=', 'closed'),
             ], order=[('date', 'DESC')], limit=1)
     if not periods:
         return
     period, = periods
     for lots in grouped_slice(lots):
         lot_ids = [l.id for l in lots]
         moves = Move.search([
                 ('lot', 'in', lot_ids),
                 ['OR', [
                         ('effective_date', '=', None),
                         ('planned_date', '<=', period.date),
                         ],
                     ('effective_date', '<=', period.date),
                     ]], limit=1)
         if moves:
             move, = moves
             cls.raise_user_error('period_closed_expiration_dates', {
                     'lot': move.lot.rec_name,
                     'move': move.rec_name,
                     })
Example #16
0
 def default_warehouse():
     Location = Pool().get('stock.location')
     warehouses = Location.search([
             ('type', '=', 'warehouse'),
             ])
     if len(warehouses) == 1:
         return warehouses[0].id
Example #17
0
    def get_quantity(cls, lines, name):
        Product = Pool().get('product.product')

        product_id = Transaction().context.get('product')
        warehouse_id = Transaction().context.get('warehouse')

        dates = sorted(l.date for l in lines)
        quantities = {}
        date_start = None
        for date in dates:
            context = {
                'stock_date_start': date_start,
                'stock_date_end': date,
                'forecast': True,
                }
            with Transaction().set_context(**context):
                quantities[date] = Product.products_by_location(
                    [warehouse_id], [product_id], with_childs=True,
                    skip_zero=False)[(warehouse_id, product_id)]
            try:
                date_start = date + datetime.timedelta(1)
            except OverflowError:
                pass
        cumulate = 0
        for date in dates:
            cumulate += quantities[date]
            quantities[date] = cumulate

        return dict((l.id, quantities[l.date]) for l in lines)
Example #18
0
    def test_numeric_required(self):
        'Test required numeric'
        pool = Pool()
        NumericRequired = pool.get('test.import_data.numeric_required')
        transaction = Transaction()

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1.1']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['-1.1']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1']]), 1)

        self.assertRaises(UserError, NumericRequired.import_data,
            ['numeric'], [['']])
        transaction.cursor.rollback()

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['1.1'], ['2.2']]), 2)

        self.assertRaises(InvalidOperation,
            NumericRequired.import_data, ['numeric'], [['foo']])

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['0']]), 1)

        self.assertEqual(NumericRequired.import_data(['numeric'],
            [['0.0']]), 1)
Example #19
0
    def search_quantity(cls, name, domain=None):
        Date = Pool().get('ir.date')

        if not (Transaction().context.get('locations') and domain):
            return []

        context = {}
        if (name == 'quantity'
                and Transaction().context.get('stock_date_end')
                and Transaction().context.get('stock_date_end') >
                Date.today()):
            context['stock_date_end'] = Date.today()

        if name == 'forecast_quantity':
            context['forecast'] = True
            if not Transaction().context.get('stock_date_end'):
                context['stock_date_end'] = datetime.date.max

        with Transaction().set_context(context):
            pbl = cls.products_by_location(
                    location_ids=Transaction().context['locations'],
                    with_childs=True, skip_zero=False).iteritems()

        processed_lines = []
        for (location, product), quantity in pbl:
            processed_lines.append({
                    'location': location,  # XXX useful ?
                    'product': product,
                    name: quantity,
                    })

        res = [line['product'] for line in processed_lines
            if cls._search_quantity_eval_domain(line, domain)]
        return [('id', 'in', res)]
Example #20
0
    def do_open(self, action):
        pool = Pool()
        Product = pool.get('product.product')
        Lang = pool.get('ir.lang')

        context = {}
        product_id = Transaction().context['active_id']
        context['product'] = product_id
        if self.start.forecast_date:
            context['stock_date_end'] = self.start.forecast_date
        else:
            context['stock_date_end'] = datetime.date.max
        action['pyson_context'] = PYSONEncoder().encode(context)
        product = Product(product_id)

        for code in [Transaction().language, 'en_US']:
            langs = Lang.search([
                    ('code', '=', code),
                    ])
            if langs:
                break
        lang, = langs
        date = Lang.strftime(context['stock_date_end'],
            lang.code, lang.date)

        action['name'] += ' - %s (%s) @ %s' % (product.rec_name,
            product.default_uom.rec_name, date)
        return action, {}
    def transition_create_(self):
        pool = Pool()
        Appointment = pool.get('gnuhealth.appointment')
        Company = pool.get('company.company')

        timezone = None
        company_id = Transaction().context.get('company')
        if company_id:
            company = Company(company_id)
            if company.timezone:
                timezone = pytz.timezone(company.timezone)
            else:
                self.raise_user_error('no_company_timezone')

        appointments = []

        # Iterate over days
        day_count = (self.start.date_end - self.start.date_start).days + 1
        
        # Validate dates
        if (self.start.date_start and self.start.date_end):
            if (self.start.date_end < self.start.date_start):
                self.raise_user_error('end_before_start')

            if (day_count > 31):
                self.raise_user_error('period_too_long')
        
        for single_date in (self.start.date_start + timedelta(n)
            for n in range(day_count)):
            if ((single_date.weekday() == 0 and self.start.monday)
            or (single_date.weekday() == 1 and self.start.tuesday)
            or (single_date.weekday() == 2 and self.start.wednesday)
            or (single_date.weekday() == 3 and self.start.thursday)
            or (single_date.weekday() == 4 and self.start.friday)
            or (single_date.weekday() == 5 and self.start.saturday)
            or (single_date.weekday() == 6 and self.start.sunday)):
                # Iterate over time
                dt = datetime.combine(
                    single_date, self.start.time_start)
                dt = timezone.localize(dt)
                dt = dt.astimezone(pytz.utc) 
                dt_end = datetime.combine(
                    single_date, self.start.time_end)
                dt_end = timezone.localize(dt_end)
                dt_end = dt_end.astimezone(pytz.utc) 
                while dt < dt_end:
                    appointment = {
                        'healthprof': self.start.healthprof.id,
                        'speciality': self.start.specialty.id,
                        'institution': self.start.institution.id,
                        'appointment_date': dt,
                        'appointment_date_end': dt +
                            timedelta(minutes=self.start.appointment_minutes),
                        'state': 'free',
                        }
                    appointments.append(appointment)
                    dt += timedelta(minutes=self.start.appointment_minutes)
        if appointments:
            Appointment.create(appointments)
        return 'open_'
Example #22
0
    def do_open(self, action):
        pool = Pool()
        Location = pool.get('stock.location')
        Lang = pool.get('ir.lang')

        context = {}
        context['locations'] = Transaction().context.get('active_ids')
        date = self.start.forecast_date or datetime.date.max
        context['stock_date_end'] = Date(date.year, date.month, date.day)
        action['pyson_context'] = PYSONEncoder().encode(context)

        locations = Location.browse(context['locations'])

        for code in [Transaction().language, 'en_US']:
            langs = Lang.search([
                    ('code', '=', code),
                    ])
            if langs:
                break
        lang = langs[0]
        date = Lang.strftime(date, lang.code, lang.date)

        action['name'] += ' - (%s) @ %s' % (
            ','.join(l.name for l in locations), date)
        return action, {}
Example #23
0
    def invoice(cls, works):
        pool = Pool()
        Invoice = pool.get('account.invoice')

        invoices = []
        for work in works:
            invoice_lines = work._get_lines_to_invoice()
            if not invoice_lines:
                continue
            invoice = work._get_invoice()
            invoice.save()
            invoices.append(invoice)
            for key, lines in groupby(invoice_lines,
                    key=work._group_lines_to_invoice_key):
                lines = list(lines)
                key = dict(key)
                invoice_line = work._get_invoice_line(key, invoice, lines)
                invoice_line.invoice = invoice.id
                invoice_line.save()
                origins = {}
                for line in lines:
                    origin = line['origin']
                    origins.setdefault(origin.__class__, []).append(origin)
                for klass, records in origins.iteritems():
                    klass.write(records, {
                            'invoice_line': invoice_line.id,
                            })
        with Transaction().set_user(0, set_context=True):
            Invoice.update_taxes(invoices)
Example #24
0
    def _get_invoice(self):
        "Return invoice for the work"
        pool = Pool()
        Invoice = pool.get('account.invoice')
        Journal = pool.get('account.journal')

        journals = Journal.search([
                ('type', '=', 'revenue'),
                ], limit=1)
        if journals:
            journal, = journals
        else:
            journal = None

        if not self.party:
            self.raise_user_error('missing_party', (self.rec_name,))

        with Transaction().set_user(0, set_context=True):
            return Invoice(
                company=self.company,
                type='out_invoice',
                journal=journal,
                party=self.party,
                invoice_address=self.party.address_get(type='invoice'),
                currency=self.company.currency,
                account=self.party.account_receivable,
                payment_term=self.party.customer_payment_term,
                description=self.work.name,
                )
Example #25
0
    def find(cls, company_id, date=None, exception=True):
        '''
        Return the fiscal year for the company_id
            at the date or the current date.
        If exception is set the function will raise an exception
            if any fiscal year is found.
        '''
        pool = Pool()
        Lang = pool.get('ir.lang')
        Date = pool.get('ir.date')

        if not date:
            date = Date.today()
        fiscalyears = cls.search([
            ('start_date', '<=', date),
            ('end_date', '>=', date),
            ('company', '=', company_id),
            ], order=[('start_date', 'DESC')], limit=1)
        if not fiscalyears:
            if exception:
                language = Transaction().language
                languages = Lang.search([('code', '=', language)])
                if not languages:
                    languages = Lang.search([('code', '=', 'en_US')])
                language, = languages
                formatted = Lang.strftime(date, language.code, language.date)
                cls.raise_user_error('no_fiscalyear_date', (formatted,))
            else:
                return None
        return fiscalyears[0].id
Example #26
0
    def close(cls, fiscalyears):
        '''
        Close a fiscal year
        '''
        pool = Pool()
        Period = pool.get('account.period')
        Account = pool.get('account.account')

        for fiscalyear in fiscalyears:
            if cls.search([
                        ('end_date', '<=', fiscalyear.start_date),
                        ('state', '=', 'open'),
                        ('company', '=', fiscalyear.company.id),
                        ]):
                cls.raise_user_error('close_error', (fiscalyear.rec_name,))

            #First close the fiscalyear to be sure
            #it will not have new period created between.
            cls.write([fiscalyear], {
                'state': 'close',
                })
            periods = Period.search([
                    ('fiscalyear', '=', fiscalyear.id),
                    ])
            Period.close(periods)

            with Transaction().set_context(fiscalyear=fiscalyear.id,
                    date=None, cumulate=True):
                accounts = Account.search([
                        ('company', '=', fiscalyear.company.id),
                        ])
            for account in accounts:
                fiscalyear._process_account(account)
Example #27
0
 def create_period(cls, fiscalyears, interval=1):
     '''
     Create periods for the fiscal years with month interval
     '''
     Period = Pool().get('account.period')
     to_create = []
     for fiscalyear in fiscalyears:
         period_start_date = fiscalyear.start_date
         while period_start_date < fiscalyear.end_date:
             period_end_date = period_start_date + \
                 relativedelta(months=interval - 1) + \
                 relativedelta(day=31)
             if period_end_date > fiscalyear.end_date:
                 period_end_date = fiscalyear.end_date
             name = datetime_strftime(period_start_date, '%Y-%m')
             if name != datetime_strftime(period_end_date, '%Y-%m'):
                 name += ' - ' + datetime_strftime(period_end_date, '%Y-%m')
             to_create.append({
                 'name': name,
                 'start_date': period_start_date,
                 'end_date': period_end_date,
                 'fiscalyear': fiscalyear.id,
                 'type': 'standard',
                 })
             period_start_date = period_end_date + relativedelta(days=1)
     if to_create:
         Period.create(to_create)
Example #28
0
    def test_integer_required(self):
        'Test required integer'
        pool = Pool()
        IntegerRequired = pool.get('test.import_data.integer_required')
        transaction = Transaction()

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['1']]), 1)

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['-1']]), 1)

        self.assertRaises(UserError, IntegerRequired.import_data,
            ['integer'], [['']])
        transaction.cursor.rollback()

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['1'], ['2']]), 2)

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['1.1']])

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['-1.1']])

        self.assertRaises(ValueError, IntegerRequired.import_data,
            ['integer'], [['foo']])

        self.assertEqual(IntegerRequired.import_data(['integer'],
            [['0']]), 1)
Example #29
0
    def test_integer(self):
        'Test integer'
        pool = Pool()
        Integer = pool.get('test.import_data.integer')

        self.assertEqual(Integer.import_data(['integer'],
            [['1']]), 1)

        self.assertEqual(Integer.import_data(['integer'],
            [['-1']]), 1)

        self.assertEqual(Integer.import_data(['integer'],
            [['']]), 1)

        self.assertEqual(Integer.import_data(['integer'],
            [['1'], ['2']]), 2)

        self.assertRaises(ValueError, Integer.import_data,
            ['integer'], [['1.1']])

        self.assertRaises(ValueError, Integer.import_data,
            ['integer'], [['-1.1']])

        self.assertRaises(ValueError, Integer.import_data,
            ['integer'], [['foo']])

        self.assertEqual(Integer.import_data(['integer'],
            [['0']]), 1)
Example #30
0
    def test_many2one(self):
        'Test many2one'
        pool = Pool()
        Many2one = pool.get('test.import_data.many2one')
        transaction = Transaction()

        self.assertEqual(Many2one.import_data(['many2one'],
            [['Test']]), 1)

        self.assertEqual(Many2one.import_data(['many2one:id'],
            [['tests.import_data_many2one_target_test']]), 1)

        self.assertEqual(Many2one.import_data(['many2one'],
            [['']]), 1)

        self.assertEqual(Many2one.import_data(['many2one'],
            [['Test'], ['Test']]), 2)

        self.assertRaises(UserError, Many2one.import_data,
            ['many2one'], [['foo']])
        transaction.cursor.rollback()

        self.assertRaises(UserError, Many2one.import_data,
            ['many2one'], [['Duplicate']])
        transaction.cursor.rollback()

        self.assertRaises(UserError, Many2one.import_data,
            ['many2one:id'], [['foo']])
        transaction.cursor.rollback()

        self.assertRaises(Exception, Many2one.import_data,
            ['many2one:id'], [['tests.foo']])
        transaction.cursor.rollback()
Example #31
0
 def _get_execution_user():
     return Pool().get('ir.model.data').get_id(
         'apar', 'user_managing_crons')
Example #32
0
    def test_purchase_price(self):
        'Test purchase price'
        pool = Pool()
        Account = pool.get('account.account')
        Template = pool.get('product.template')
        Product = pool.get('product.product')
        Uom = pool.get('product.uom')
        ProductSupplier = pool.get('purchase.product_supplier')
        Party = pool.get('party.party')

        company = create_company()
        with set_company(company):
            create_chart(company)

            receivable, = Account.search([
                ('kind', '=', 'receivable'),
                ('company', '=', company.id),
            ])
            payable, = Account.search([
                ('kind', '=', 'payable'),
                ('company', '=', company.id),
            ])

            kg, = Uom.search([('name', '=', 'Kilogram')])
            g, = Uom.search([('name', '=', 'Gram')])

            template, = Template.create([{
                'name': 'Product',
                'default_uom': g.id,
                'purchase_uom': kg.id,
                'list_price': Decimal(5),
                'cost_price': Decimal(2),
                'products': [('create', [{}])],
            }])
            product, = template.products

            supplier, = Party.create([{
                'name': 'Supplier',
                'account_receivable': receivable.id,
                'account_payable': payable.id,
            }])
            product_supplier, = ProductSupplier.create([{
                'product':
                template.id,
                'party':
                supplier.id,
                'prices': [('create', [{
                    'sequence': 1,
                    'quantity': 1,
                    'unit_price': Decimal(3000),
                }, {
                    'sequence': 2,
                    'quantity': 2,
                    'unit_price': Decimal(2500),
                }])],
            }])

            prices = Product.get_purchase_price([product], quantity=100)
            self.assertEqual(prices, {product.id: Decimal(2)})
            prices = Product.get_purchase_price([product], quantity=1500)
            self.assertEqual(prices, {product.id: Decimal(2)})

            with Transaction().set_context(uom=kg.id):
                prices = Product.get_purchase_price([product], quantity=0.5)
                self.assertEqual(prices, {product.id: Decimal(2000)})
                prices = Product.get_purchase_price([product], quantity=1.5)
                self.assertEqual(prices, {product.id: Decimal(2000)})

            with Transaction().set_context(supplier=supplier.id):
                prices = Product.get_purchase_price([product], quantity=100)
                self.assertEqual(prices, {product.id: Decimal(2)})
                prices = Product.get_purchase_price([product], quantity=1500)
                self.assertEqual(prices, {product.id: Decimal(3)})
                prices = Product.get_purchase_price([product], quantity=3000)
                self.assertEqual(prices, {product.id: Decimal('2.5')})

            with Transaction().set_context(uom=kg.id, supplier=supplier.id):
                prices = Product.get_purchase_price([product], quantity=0.5)
                self.assertEqual(prices, {product.id: Decimal(2000)})
                prices = Product.get_purchase_price([product], quantity=1.5)
                self.assertEqual(prices, {product.id: Decimal(3000)})
                prices = Product.get_purchase_price([product], quantity=3)
                self.assertEqual(prices, {product.id: Decimal(2500)})
Example #33
0
 def test_global_search(self):
     'Test Global Search'
     pool = Pool()
     Model = pool.get('ir.model')
     Model.global_search('User', 10)
Example #34
0
 def _get_request_user():
     # TODO: Find a better solution to get the user from apar technical admin 
     return Pool().get('ir.model.data').get_id(
         'res', 'user_admin')