Beispiel #1
0
 def set(cls, menu_id):
     user = Transaction().user
     cls.create([{
                 'menu': menu_id,
                 'user': user,
                 }])
Beispiel #2
0
    def transition_import_icd10(self):
        pool = Pool()
        Group = pool.get('galeno.disease.group')
        Category = pool.get('galeno.disease.category')
        Disease = pool.get('galeno.disease')
        Procedure = pool.get('galeno.procedure')
        cursor = Transaction().connection.cursor()
        lang = self.start.language.code
        path = 'galeno_base_data/data/diseases/groups_' + lang + '.csv'
        with file_open(path, mode='r', encoding='utf-8') as group_file:
            fieldnames = ['code', 'name', 'description', 'information']
            reader = csv.DictReader(group_file,
                                    delimiter='|',
                                    fieldnames=fieldnames)
            next(reader)  # Skip header
            for row in reader:
                group = Group()
                for field in row:
                    if row[field] == '':
                        value = None
                    else:
                        value = row[field]
                    setattr(group, field, value)
                group.core = True
                group.save()

        path = 'galeno_base_data/data/diseases/categories_' + lang + '.csv'
        with file_open(path, mode='r', encoding='utf-8') as category_file:
            fieldnames = ['code', 'name', 'parent']
            reader = csv.DictReader(category_file,
                                    delimiter='|',
                                    fieldnames=fieldnames)
            next(reader)  # Skip header
            for row in reader:
                if row['parent'] != '':
                    parent, = Category.search([('code', '=', row['parent'])])
                else:
                    parent = None
                category = Category()
                category.code = row['code']
                category.name = row['name']
                category.parent = parent
                category.core = True
                category.save()

        groups = {}
        categories = {}
        for group in Group.search([]):
            groups[group.code] = group
        for category in Category.search([]):
            categories[category.code] = category

        to_save = []
        path = 'galeno_base_data/data/diseases/diseases_' + lang + '.csv'
        with file_open(path, mode='r', encoding='utf-8') as disease_file:
            fieldnames = [
                'code', 'name', 'category', 'groups', 'chromosome', 'protein',
                'gene', 'information', 'active'
            ]
            reader = csv.DictReader(disease_file,
                                    delimiter='|',
                                    fieldnames=fieldnames)
            next(reader)  # Skip header
            for row in reader:
                disease = Disease()
                for field in row:
                    if row[field] == '':
                        value = None
                    else:
                        if field == 'active':
                            value = bool(row[field])
                        elif field == 'category':
                            value = categories[row[field]]
                        elif field == 'groups':
                            value = []
                            for group_code in row[field].split(','):
                                value.append(groups[group_code].id)
                        else:
                            value = row[field]
                    setattr(disease, field, value)
                disease.core = True
                to_save.append(disease)
            Disease.save(to_save)

        table = Procedure.__table__()
        columns = [table.code, table.name, table.core]
        values = []
        path = 'galeno_base_data/data/procedures/procedures_' + lang + '.csv'
        with file_open(path, mode='r', encoding='utf-8') as procedure_file:
            fieldnames = ['code', 'name']
            reader = csv.DictReader(procedure_file,
                                    delimiter='|',
                                    fieldnames=fieldnames)
            next(reader)  # Skip header
            for row in reader:
                record = []
                for field in row:
                    if row[field] == '':
                        value = None
                    else:
                        value = row[field]
                    record.append(value)
                record.append(True)
                values.append(record)

            cursor.execute(*table.insert(columns, values))
            Procedure.save(to_save)

        return 'succeed'
Beispiel #3
0
    def close(cls, periods):
        pool = Pool()
        Product = pool.get('product.product')
        Location = pool.get('stock.location')
        Move = pool.get('stock.move')
        Date = pool.get('ir.date')
        transaction = Transaction()
        connection = transaction.connection
        database = transaction.database

        # XXX: A move in the period could be inserted before the lock
        # from a different transaction. It will not be taken in the pbl
        # computation but it is quite rare because only past periods are
        # closed.
        database.lock(connection, Move._table)
        if database.has_select_for():
            move = Move.__table__()
            query = move.select(Literal(1), for_=For('UPDATE', nowait=True))
            with connection.cursor() as cursor:
                cursor.execute(*query)

        locations = Location.search([
            ('type', 'not in', ['warehouse', 'view']),
        ],
                                    order=[])
        today = Date.today()

        recent_date = max(period.date for period in periods)
        if recent_date >= today:
            raise PeriodCloseError(gettext('stock.msg_period_close_date'))
        if Move.search([('state', '=', 'assigned'),
                        [
                            'OR',
                            [
                                ('effective_date', '=', None),
                                ('planned_date', '<=', recent_date),
                            ],
                            ('effective_date', '<=', recent_date),
                        ]]):
            raise PeriodCloseError(
                gettext('stock.msg_period_close_assigned_move'))

        for grouping in cls.groupings():
            Cache = cls.get_cache(grouping)
            to_create = []
            for period in periods:
                with Transaction().set_context(
                        stock_date_end=period.date,
                        stock_date_start=None,
                        stock_assign=False,
                        forecast=False,
                        stock_destinations=None,
                ):
                    pbl = Product.products_by_location(
                        [l.id for l in locations], grouping=grouping)
                for key, quantity in pbl.items():
                    values = {
                        'location': key[0],
                        'period': period.id,
                        'internal_quantity': quantity,
                    }
                    for i, field in enumerate(grouping, 1):
                        values[field] = key[i]
                    to_create.append(values)
            if to_create:
                Cache.create(to_create)
Beispiel #4
0
 def transition_recall(self):
     pool = Pool()
     Invoice = pool.get('account.invoice')
     invoice = Invoice(Transaction().context['active_id'])
     invoice.call_deposit(self.start.account, self.start.description)
     return 'end'
Beispiel #5
0
    def __register__(cls, module_name):

        # Upgrade to release 3.0
        # Move existing ICU EGC records to the generic gnuhealth.patient.ecg
        # model

        super(ECG, cls).__register__(module_name)

        cursor = Transaction().cursor
        TableHandler = backend.get('TableHandler')

        if TableHandler.table_exist(cursor, 'gnuhealth_icu_ecg'):

            table = TableHandler(cursor, cls, module_name)

            # Retrieve IDs from ECGs at ICU

            cursor.execute('select id,name from gnuhealth_icu_ecg')

            icu_ecg_ids = cursor.fetchall()

            # Traverse each record on the icu_ecg table
            for icu_ecg in icu_ecg_ids:

                registration = str(icu_ecg[1])

                # Get the patient ID related to the registration
                cursor.execute(
                    'select patient FROM \
                gnuhealth_inpatient_registration \
                where id = %s', registration)

                patient_id = cursor.fetchone()

                cursor.execute(
                    'select name, ecg_date, lead, axis, rate,\
                rhythm, pacemaker, pr, qrs, qt, st_segment, twave_inversion, \
                interpretation, ecg_strip FROM gnuhealth_icu_ecg where \
                name = %s and id = %s', (registration, icu_ecg[0]))

                ecg = cursor.fetchone()

                (name, ecg_date, lead, axis, rate, rhythm, \
                pacemaker, pr, qrs, qt, st_segment, twave_inversion, \
                interpretation, ecg_strip) = ecg

                # Insert the values on the new ECG table
                cursor.execute('insert into gnuhealth_patient_ecg \
                (name, inpatient_registration_code, ecg_date, lead, axis, \
                rate,rhythm,pacemaker, pr, qrs, qt, st_segment, \
                twave_inversion, interpretation, ecg_strip) \
                VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'                                                                      ,
                (patient_id, registration, ecg_date, lead, axis, rate, \
                rhythm, pacemaker, pr, qrs, qt, st_segment, \
                twave_inversion, interpretation, ecg_strip))

                # Rename obsolete table gnuhealth_icu_ecg
                # Once we know everything is OK we can drop it

                cursor.execute('alter table gnuhealth_icu_ecg rename \
                to old_icu_ecg')
    def test0030create_moves(self):
        'Test create_moves'
        with Transaction().start(DB_NAME, USER, context=CONTEXT):
            category, = self.category.create([{
                'name': 'Test create_moves',
            }])
            unit, = self.uom.search([('name', '=', 'Unit')])
            template, = self.template.create([{
                'name': 'Test create_moves',
                'type': 'goods',
                'category': category.id,
                'cost_price_method': 'fixed',
                'default_uom': unit.id,
                'list_price': Decimal('1'),
                'cost_price': Decimal(0),
            }])
            product, = self.product.create([{
                'template': template.id,
            }])
            customer, = self.location.search([('code', '=', 'CUS')])
            warehouse, = self.location.search([('code', '=', 'WH')])
            storage, = self.location.search([('code', '=', 'STO')])
            company, = self.company.search([
                ('rec_name', '=', 'Dunder Mifflin'),
            ])
            self.user.write([self.user(USER)], {
                'main_company': company.id,
                'company': company.id,
            })

            today = datetime.date.today()

            forecast, = self.forecast.create([{
                'warehouse':
                warehouse.id,
                'destination':
                customer.id,
                'from_date':
                today + relativedelta(months=1, day=1),
                'to_date':
                today + relativedelta(months=1, day=20),
                'company':
                company.id,
                'lines': [
                    (
                        'create',
                        [{
                            'product': product.id,
                            'quantity': 10,
                            'uom': unit.id,
                            'minimal_quantity': 2,
                        }],
                    ),
                ],
            }])
            self.forecast.confirm([forecast])

            self.forecast.create_moves([forecast])
            line, = forecast.lines
            self.assertEqual(line.quantity_executed, 0)
            self.assertEqual(len(line.moves), 5)
            self.assertEqual(sum(move.quantity for move in line.moves), 10)

            self.forecast.delete_moves([forecast])
            line, = forecast.lines
            self.assertEqual(len(line.moves), 0)

            self.move.create([{
                'from_location':
                storage.id,
                'to_location':
                customer.id,
                'product':
                product.id,
                'uom':
                unit.id,
                'quantity':
                2,
                'planned_date':
                today + relativedelta(months=1, day=5),
                'company':
                company.id,
                'currency':
                company.currency.id,
                'unit_price':
                Decimal('1'),
            }])
            line, = forecast.lines
            self.assertEqual(line.quantity_executed, 2)

            self.forecast.create_moves([forecast])
            line, = forecast.lines
            self.assertEqual(line.quantity_executed, 2)
            self.assertEqual(len(line.moves), 4)
            self.assertEqual(sum(move.quantity for move in line.moves), 8)
Beispiel #7
0
def load_module_graph(graph, pool, update=None, lang=None):
    # Prevent to import backend when importing module
    from trytond.cache import Cache
    from trytond.ir.lang import get_parent_language

    if lang is None:
        lang = [config.get('database', 'language')]
    if update is None:
        update = []
    modules_todo = []
    models_to_update_history = set()

    # Load also parent languages
    lang = set(lang)
    for code in list(lang):
        while code:
            lang.add(code)
            code = get_parent_language(code)

    transaction = Transaction()
    with transaction.connection.cursor() as cursor:
        modules = [x.name for x in graph]
        module2state = dict()
        for sub_modules in tools.grouped_slice(modules):
            cursor.execute(*ir_module.select(ir_module.name, ir_module.state,
                    where=ir_module.name.in_(list(sub_modules))))
            module2state.update(cursor.fetchall())
        modules = set(modules)

        for node in graph:
            module = node.name
            if module not in MODULES:
                continue
            logger.info(module)
            classes = pool.fill(module, modules)
            if update:
                pool.setup(classes)
            package_state = module2state.get(module, 'not activated')
            if (is_module_to_install(module, update)
                    or (update
                        and package_state in ('to activate', 'to upgrade'))):
                if package_state not in ('to activate', 'to upgrade'):
                    if package_state == 'activated':
                        package_state = 'to upgrade'
                    elif package_state != 'to remove':
                        package_state = 'to activate'
                for child in node:
                    module2state[child.name] = package_state
                for type in list(classes.keys()):
                    for cls in classes[type]:
                        logger.info('%s:register %s', module, cls.__name__)
                        cls.__register__(module)
                for model in classes['model']:
                    if hasattr(model, '_history'):
                        models_to_update_history.add(model.__name__)

                # Instanciate a new parser for the module
                tryton_parser = convert.TrytondXmlHandler(
                    pool, module, package_state, modules, lang)

                for filename in node.info.get('xml', []):
                    filename = filename.replace('/', os.sep)
                    logger.info('%s:loading %s', module, filename)
                    # Feed the parser with xml content:
                    with tools.file_open(OPJ(module, filename), 'rb') as fp:
                        tryton_parser.parse_xmlstream(fp)

                modules_todo.append((module, list(tryton_parser.to_delete)))

                load_translations(pool, node, lang)

                if package_state == 'to remove':
                    continue
                cursor.execute(*ir_module.select(ir_module.id,
                        where=(ir_module.name == module)))
                try:
                    module_id, = cursor.fetchone()
                    cursor.execute(*ir_module.update([ir_module.state],
                            ['activated'], where=(ir_module.id == module_id)))
                except TypeError:
                    cursor.execute(*ir_module.insert(
                            [ir_module.create_uid, ir_module.create_date,
                                ir_module.name, ir_module.state],
                            [[0, CurrentTimestamp(), module, 'activated'],
                                ]))
                module2state[module] = 'activated'

            # Avoid clearing cache to prevent dead lock on ir.cache table
            Cache.rollback(transaction)
            transaction.commit()
            # Clear transaction cache to update default_factory
            transaction.cache.clear()

        if not update:
            pool.setup()
        else:
            # Remove unknown models and fields
            Model = pool.get('ir.model')
            Model.clean()
            ModelField = pool.get('ir.model.field')
            ModelField.clean()
            transaction.commit()

        pool.setup_mixin(modules)

        for model_name in models_to_update_history:
            model = pool.get(model_name)
            if model._history:
                logger.info('history:update %s', model.__name__)
                model._update_history_table()

        # Vacuum :
        while modules_todo:
            (module, to_delete) = modules_todo.pop()
            convert.post_import(pool, module, to_delete)
    logger.info('all modules loaded')
 def get_balance_period(self, ids, names):
     if not ids:
         return {}
     res={}
     fiscalyear_obj = self.pool.get('ekd.fiscalyear')
     type_balance = self.browse(ids[0]).account.type_balance
     period_obj = self.pool.get('ekd.period')
     context = Transaction().context
     if context.get('current_period'):
         period_id = period_obj.browse(context.get('current_period'))
         current_period = context.get('current_period')
     elif context.get('current_date'):
         current_period = period_obj.search([
                 ('company','=',context.get('company')),
                 ('start_date','<=',context.get('current_date')),
                 ('end_date','>=',context.get('current_date')),
                 ], limit=1)
     cr = Transaction().cursor
     cr.execute('SELECT id, account, balance_dt, balance_ct, '\
                 'debit, credit, '\
                 ' balance_dt-balance_ct+debit-credit as balance_end, '\
                 ' balance_dt+debit as balance_dt_end, '\
                 ' balance_ct+credit as balance_ct_end '\
                 'FROM ekd_balances_party_period '\
                 'WHERE period=%s AND account in ('%(current_period)+','.join(map(str,ids))+')')
     for amount_id, account, balance_dt, balance_ct,\
         debit, credit, balance_end,\
         balance_dt_end, balance_ct_end in cr.fetchall():
         # SQLite uses float for SUM
         if not isinstance(balance_dt, Decimal):
             balance_dt = Decimal(str(balance_dt))
         if not isinstance(balance_ct, Decimal):
             balance_ct = Decimal(str(balance_ct))
         if not isinstance(balance_dt_end, Decimal):
             balance_dt = Decimal(str(balance_dt_end))
         if not isinstance(balance_ct_end, Decimal):
             balance_ct = Decimal(str(balance_ct_end))
         if not isinstance(debit, Decimal):
             debit = Decimal(str(debit))
         if not isinstance(credit, Decimal):
             credit = Decimal(str(credit))
         for name in names:
             res.setdefault(name, {})
             res[name].setdefault(account, Decimal('0.0'))
             amount_balance= Decimal('0.0')
             if name == 'balance_dt_end':
                 if type_balance == 'active':
                     res[name][account] = balance_end
                 #elif type_balance == 'passive':
                 #    res[name][account] = balance_end
                 elif type_balance == 'both':
                     if balance_end > 0:
                         res[name][account] = balance_end
             if name == 'balance_ct_end':
                 if type_balance == 'passive':
                     res[name][account] = -balance_end
                 elif type_balance == 'both':
                     if balance_end < 0:
                         res[name][account] = -balance_end
             elif name == 'balance_end':
                 res[name][account] = balance_end
             elif name == 'balance':
                 res[name][account] = balance_dt-balance_ct
             elif name == 'debit':
                 res[name][account] = debit
             elif name == 'credit':
                 res[name][account] = credit
     return res
    def get_balance_year(self, ids, names):
        if not ids:
            return {}
        res={}
        fiscalyear_obj = self.pool.get('ekd.fiscalyear')
        period_obj = self.pool.get('ekd.period')
        context = Transaction().context
        if context.get('current_period'):
            period_id = period_object.browse(context.get('current_period'))
            start_month = period_id.start_date.strftime('%m')
            end_month = period_id.end_date.strftime('%m')
            fiscalyear = period_id.fiscalyear.id
            if start_month == end_month:
                current_period = context.get('current_period').strftime('%m')
            else:
                begin_period = False
                for month in _MOUNTH:
                    if start_month == month:
                        current_period.append(month)
                        begin_period = True
                    elif begin_period:
                        current_period.append(month)
                    elif end_month == month:
                        current_period.append(month)
                        break
        else:
            if context.get('current_fiscalyear'):
                fiscalyear = context.get('current_fiscalyear')
            else:
                fiscalyear = fiscalyear_obj.search([
                                ('company','=',context.get('company')),
                                ('state','=','current')
                                ], limit=1)
            current_period = datetime.datetime.now().strftime('%m')

        if isinstance(current_period, list):
            field_debit = []
            field_credit = []
            for month in current_period:
                field_debit.append("debit_%s"%(month))
                field_credit.append("credit_%s"%(month))
            field_debits = []
            field_credits = []
            for month in _MOUNTH:
                if month == start_month:
                    break
                field_debits.append("debit_%s"%(month))
                field_credits.append("credit_%s"%(month))
        else:
            field_debit = "debit_%s"%(current_period)
            field_credit = "credit_%s"%(current_period)
            field_debits = []
            field_credits = []
            for month in _MOUNTH:
                if month == current_period:
                    break
                field_debits.append("debit_%s"%(month))
                field_credits.append("credit_%s"%(month))

        cr = Transaction().cursor
        if isinstance(current_period, list):
            cr.execute('SELECT id, balance_dt+'+'+'.join(field_debits)+','\
                    'balance_ct+'+'+'.join(field_credits)+','\
                    '+'.join(field_debit)+' as debit,'\
                    '+'.join(field_credit)+' as credit'\
                    'FROM ekd_balances_party_period'\
                    'WHERE fiscalyear=%s AND account in ('+','.join(map(str,ids))+')'%(field_debit,field_credit,fiscalyear))
        else:
            cr.execute('SELECT id, balance_dt+'+'+'.join(field_debits)+','\
                    'balance_ct+'+'+'.join(field_credits)+','\
                    '%s, %s'\
                    'FROM ekd_balances_party_period'\
                    'WHERE fiscalyear=%s AND account in ('+','.join(map(str,ids))+')'%(field_debit,field_credit,fiscalyear))

        for id, balance_dt, balance_ct, debit, credit in cr.fetchall():
            # SQLite uses float for SUM
            if not isinstance(balance_dt, Decimal):
                balance_dt = Decimal(str(balance_dt))
            if not isinstance(balance_ct, Decimal):
                balance_ct = Decimal(str(balance_ct))
            if not isinstance(debit, Decimal):
                debit = Decimal(str(debit))
            if not isinstance(credit, Decimal):
                credit = Decimal(str(credit))
            for name in names:
                res.setdefault(name, {})
                res[name].setdefault(balance.id, Decimal('0.0'))
                amount_balance= Decimal('0.0')
                if not balance.amount:
                    continue
                if name == 'balance_dt_end':
                    res[name][balance.id] = balance_end
                elif name == 'balance_ct_end':
                    res[name][balance.id] = balance_end
                elif name == 'balance_end':
                    res[name][balance.id] = balance_end 
                elif name == 'balance':
                    res[name][balance.id] = balance_dt-balance_ct
                elif name == 'debit':
                    res[name][balance.id] = debit
                elif name == 'credit':
                    res[name][balance.id] = credit

        return res
 def default_currency(self):
     return Transaction().context.get('currency')
 def get_company(self, ids, name):
     res={}
     context = Transaction().context
     res = {}.fromkeys(ids, context.get('company'))
     return res
Beispiel #12
0
 def execute(cls, ids, data):
     with Transaction().set_context(address_with_party=True):
         return super(Letter, cls).execute(ids, data)
    def generate_internal_shipment(self):
        """
        Generate internal shipments to meet order points defined on
        non-warehouse location.
        """
        order_point_obj = self.pool.get('stock.order_point')
        uom_obj = self.pool.get('product.uom')
        product_obj = self.pool.get('product.product')
        date_obj = self.pool.get('ir.date')
        user_obj = self.pool.get('res.user')
        user_record = user_obj.browse(Transaction().user)
        today = date_obj.today()
        # fetch quantities on order points
        op_ids = order_point_obj.search([
            ('type', '=', 'internal'),
        ])
        order_points = order_point_obj.browse(op_ids)
        id2product = {}
        location_ids = []
        for op in order_points:
            id2product[op.product.id] = op.product
            location_ids.append(op.storage_location.id)

        with Transaction().set_context(stock_date_end=today):
            pbl = product_obj.products_by_location(location_ids,
                                                   list(id2product.iterkeys()),
                                                   with_childs=True)

        # Create a list of move to create
        moves = {}
        for op in order_points:
            qty = pbl.get((op.storage_location.id, op.product.id), 0)
            if qty < op.min_quantity:
                key = (op.storage_location.id, op.provisioning_location.id,
                       op.product.id)
                moves[key] = op.max_quantity - qty

        # Compare with existing draft shipments
        shipment_ids = self.search([
            ('state', '=', 'draft'),
            [
                'OR',
                ('planned_date', '<=', today),
                ('planned_date', '=', False),
            ],
        ])
        for shipment in self.browse(shipment_ids):
            for move in shipment.moves:
                key = (shipment.to_location.id, shipment.from_location.id,
                       move.product.id)
                if key not in moves:
                    continue
                quantity = uom_obj.compute_qty(
                    move.uom, move.quantity,
                    id2product[move.product.id].default_uom)
                moves[key] = max(0, moves[key] - quantity)

        # Group moves by {from,to}_location
        shipments = {}
        for key, qty in moves.iteritems():
            from_location, to_location, product = key
            shipments.setdefault((from_location, to_location), []).append(
                (product, qty))
        # Create shipments and moves
        for shipment, moves in shipments.iteritems():
            from_location, to_location = shipment
            values = {
                'from_location': from_location,
                'to_location': to_location,
                'planned_date': today,
                'moves': [],
            }
            for move in moves:
                product, qty = move
                values['moves'].append(('create', {
                    'from_location':
                    from_location,
                    'to_location':
                    to_location,
                    'product':
                    product,
                    'quantity':
                    qty,
                    'uom':
                    id2product[product].default_uom.id,
                    'company':
                    user_record.company.id,
                }))
            self.create(values)
Beispiel #14
0
    def default_configure(self, data):
        Channel = Pool().get('sale.channel')

        channel = Channel(Transaction().context.get('active_id'))
        return {'channel_source': channel.source}
Beispiel #15
0
 def default_period():
     pool = Pool()
     Period = pool.get('account.period')
     company = Transaction().context.get('company')
     return Period.find(company, exception=False)
 def default_state(self):
     return Transaction().context.get('state') or 'draft'
    def test0040complete(self):
        '''
        Test complete.
        '''
        with Transaction().start(DB_NAME, USER, context=CONTEXT):
            category, = self.category.create([{
                'name': 'Test complete',
            }])
            unit, = self.uom.search([('name', '=', 'Unit')])
            template, = self.template.create([{
                'name': 'Test complete',
                'type': 'goods',
                'category': category.id,
                'cost_price_method': 'fixed',
                'default_uom': unit.id,
                'list_price': Decimal('1'),
                'cost_price': Decimal(0),
            }])
            product, = self.product.create([{
                'template': template.id,
            }])
            customer, = self.location.search([('code', '=', 'CUS')])
            supplier, = self.location.search([('code', '=', 'SUP')])
            warehouse, = self.location.search([('code', '=', 'WH')])
            storage, = self.location.search([('code', '=', 'STO')])
            company, = self.company.search([
                ('rec_name', '=', 'Dunder Mifflin'),
            ])
            self.user.write([self.user(USER)], {
                'main_company': company.id,
                'company': company.id,
            })

            today = datetime.date.today()

            moves = self.move.create([{
                'from_location':
                supplier.id,
                'to_location':
                storage.id,
                'product':
                product.id,
                'uom':
                unit.id,
                'quantity':
                10,
                'effective_date': (today + relativedelta(months=-1, day=1)),
                'company':
                company.id,
                'currency':
                company.currency.id,
                'unit_price':
                Decimal('1'),
            }, {
                'from_location':
                storage.id,
                'to_location':
                customer.id,
                'product':
                product.id,
                'uom':
                unit.id,
                'quantity':
                5,
                'effective_date': (today + relativedelta(months=-1, day=15)),
                'company':
                company.id,
                'currency':
                company.currency.id,
                'unit_price':
                Decimal('1'),
            }])
            self.move.do(moves)

            forecast, = self.forecast.create([{
                'warehouse':
                warehouse.id,
                'destination':
                customer.id,
                'from_date':
                today + relativedelta(months=1, day=1),
                'to_date':
                today + relativedelta(months=1, day=20),
                'company':
                company.id,
            }])

            with Transaction().set_context(active_id=forecast.id):
                session_id, _, _ = self.forecast_complete.create()
                forecast_complete = self.forecast_complete(session_id)
                forecast_complete.ask.from_date = (
                    today + relativedelta(months=-1, day=1))
                forecast_complete.ask.to_date = (
                    today + relativedelta(months=-1, day=20))
                forecast_complete.transition_complete()

            self.assertEqual(len(forecast.lines), 1)
            forecast_line, = forecast.lines
            self.assertEqual(forecast_line.product, product)
            self.assertEqual(forecast_line.uom, unit)
            self.assertEqual(forecast_line.quantity, 5)
            self.assertEqual(forecast_line.minimal_quantity, 1)
Beispiel #18
0
    def fields_view_get(cls, view_id=None, view_type='form'):
        '''
        Return a view definition.
        If view_id is None the first one will be used of view_type.
        The definition is a dictionary with keys:
           - model: the model name
           - type: the type of the view
           - view_id: the id of the view
           - arch: the xml description of the view
           - fields: a dictionary with the definition of each field in the view
           - field_childs: the name of the childs field for tree
        '''
        key = (cls.__name__, view_id, view_type)
        result = cls._fields_view_get_cache.get(key)
        if result:
            return result
        result = {'model': cls.__name__}
        pool = Pool()
        View = pool.get('ir.ui.view')

        view = None
        inherit_view_id = None
        if view_id:
            view = View(view_id)
        else:
            domain = [
                ('model', '=', cls.__name__),
                [
                    'OR',
                    ('inherit', '=', None),
                    ('inherit.model', '!=', cls.__name__),
                ],
            ]
            views = View.search(domain)
            views = filter(lambda v: v.rng_type == view_type, views)
            if views:
                view = views[0]
        if view:
            if view.inherit:
                inherit_view_id = view.id
                view = view.inherit
            view_id = view.id

        # if a view was found
        if view:
            result['type'] = view.rng_type
            result['view_id'] = view_id
            result['arch'] = view.arch
            result['field_childs'] = view.field_childs

            # Check if view is not from an inherited model
            if view.model != cls.__name__:
                Inherit = pool.get(view.model)
                result['arch'] = Inherit.fields_view_get(
                    result['view_id'])['arch']
                view_id = inherit_view_id

            # get all views which inherit from (ie modify) this view
            views = View.search([
                'OR',
                [
                    ('inherit', '=', view_id),
                    ('model', '=', cls.__name__),
                ],
                [
                    ('id', '=', view_id),
                    ('inherit', '!=', None),
                ],
            ])
            raise_p = False
            while True:
                try:
                    views.sort(key=lambda x: cls._modules_list.index(x.module
                                                                     or None))
                    break
                except ValueError:
                    if raise_p:
                        raise
                    # There is perhaps a new module in the directory
                    ModelView._reset_modules_list()
                    raise_p = True
            parser = etree.XMLParser(remove_comments=True)
            tree = etree.fromstring(result['arch'], parser=parser)
            for view in views:
                if view.domain:
                    if not PYSONDecoder({
                            'context': Transaction().context
                    }).decode(view.domain):
                        continue
                if not view.arch or not view.arch.strip():
                    continue
                tree_inherit = etree.fromstring(view.arch, parser=parser)
                tree = _inherit_apply(tree, tree_inherit)
            result['arch'] = etree.tostring(tree,
                                            encoding='utf-8').decode('utf-8')

        # otherwise, build some kind of default view
        else:
            if view_type == 'form':
                res = cls.fields_get()
                xml = '''<?xml version="1.0"?>''' \
                    '''<form string="%s" col="4">''' % (cls.__doc__,)
                for i in res:
                    if i in ('create_uid', 'create_date', 'write_uid',
                             'write_date', 'id', 'rec_name'):
                        continue
                    if res[i]['type'] not in ('one2many', 'many2many'):
                        xml += '<label name="%s"/>' % (i, )
                        xml += '<field name="%s"/>' % (i, )
                        if res[i]['type'] == 'text':
                            xml += "<newline/>"
                    else:
                        xml += '<field name="%s" colspan="4"/>' % (i, )
                xml += "</form>"
            elif view_type == 'tree':
                field = 'id'
                if cls._rec_name in cls._fields:
                    field = cls._rec_name
                xml = '''<?xml version="1.0"?>''' \
                    '''<tree string="%s"><field name="%s"/></tree>''' \
                    % (cls.__doc__, field)
            else:
                xml = ''
            result['type'] = view_type
            result['arch'] = xml
            result['field_childs'] = None
            result['view_id'] = 0

        # Update arch and compute fields from arch
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.fromstring(result['arch'], parser)
        xarch, xfields = cls._view_look_dom_arch(tree, result['type'],
                                                 result['field_childs'])
        result['arch'] = xarch
        result['fields'] = xfields

        cls._fields_view_get_cache.set(key, result)
        return result
Beispiel #19
0
def migrate_property(model_name,
                     field_names,
                     ValueModel,
                     value_names,
                     parent=None,
                     fields=None):
    "Migrate property from model_name.field_name to ValueModel.value_name"
    pool = Pool()
    Field = pool.get('ir.model.field')
    Model = pool.get('ir.model')
    if not backend.TableHandler.table_exist('ir_property'):
        return
    cursor = Transaction().connection.cursor()
    field = Field.__table__()
    model = Model.__table__()
    table = ValueModel.__table__()

    if fields is None:
        fields = []
    if isinstance(field_names, str):
        field_names = [field_names]
    if isinstance(value_names, str):
        value_names = [value_names]

    def split_value(value):
        return value.split(',')[1]

    cast_funcs = {
        'numeric': lambda v: Decimal(split_value(v)) if v else None,
        'integer': lambda v: int(split_value(v)) if v else None,
        'float': lambda v: float(split_value(v)) if v else None,
        'char': lambda v: split_value(v) if v else None,
        'selection': lambda v: split_value(v) if v else None,
        'many2one': lambda v: int(split_value(v)) if v else None,
        'reference': lambda v: v,
    }

    casts = []
    queries = []
    for field_name, value_name in zip(field_names, value_names):
        value_field = getattr(ValueModel, value_name)
        casts.append(cast_funcs[value_field._type])

        property_ = Table('ir_property')
        columns = [
            Literal(None).as_(f)
            if f != value_name else property_.value.as_(value_name)
            for f in value_names
        ]
        if parent:
            columns.append(property_.res.as_(parent))
            where = property_.res.like(model_name + ',%')
        else:
            where = property_.res == Null
        columns.extend([Column(property_, f).as_(f) for f in fields])
        query = property_.join(field,
                               condition=property_.field == field.id).join(
                                   model,
                                   condition=field.model == model.id).select(
                                       *columns,
                                       where=where
                                       & (field.name == field_name)
                                       & (model.model == model_name))
        queries.append(query)

    union = Union(*queries)
    columns = [Max(Column(union, f)).as_(f) for f in value_names]
    if parent:
        columns.append(Column(union, parent).as_(parent))
        pcolumns = [Column(union, parent)]
    else:
        pcolumns = []
    vcolumns = [Column(union, f).as_(f) for f in fields]
    cursor.execute(
        *union.select(*(columns + vcolumns), group_by=pcolumns + vcolumns))

    columns = [Column(table, f) for f in value_names]
    if parent:
        pcolumns = [Column(table, parent)]
    else:
        pcolumns = []
    vcolumns = [Column(table, f) for f in fields]
    values = []
    l = len(value_names)
    for row in cursor.fetchall():
        value = [c(v) for v, c in zip(row, casts)]
        if parent:
            value.append(int(row[l].split(',')[1]) if row[l] else None)
            i = 1
        else:
            i = 0
        value.extend(row[l + i:])
        values.append(value)
    if (values and not (
            # No property defined
            len(values) == 1 and all(x is None
                                     for x in values[0][:len(columns)]))):

        # Delete previous migrated values
        cursor.execute(*table.delete())

        cursor.execute(
            *table.insert(columns + pcolumns + vcolumns, values=values))
Beispiel #20
0
    def _view_look_dom_arch(cls, tree, type, field_children=None):
        pool = Pool()
        ModelAccess = pool.get('ir.model.access')
        FieldAccess = pool.get('ir.model.field.access')

        encoder = PYSONEncoder()
        for xpath, attribute, value in cls.view_attributes():
            for element in tree.xpath(xpath):
                element.set(attribute, encoder.encode(value))

        fields_width = {}
        tree_root = tree.getroottree().getroot()

        # Find field without read access
        fread_accesses = FieldAccess.check(cls.__name__,
                                           cls._fields.keys(),
                                           'read',
                                           access=True)
        fields_to_remove = list(x for x, y in fread_accesses.iteritems()
                                if not y)

        # Find relation field without read access
        for name, field in cls._fields.iteritems():
            if not ModelAccess.check_relation(cls.__name__, name, mode='read'):
                fields_to_remove.append(name)

        for name, field in cls._fields.iteritems():
            for field_to_remove in fields_to_remove:
                if field_to_remove in field.depends:
                    fields_to_remove.append(name)

        # Remove field without read access
        for field in fields_to_remove:
            xpath = (
                '//field[@name="%(field)s"] | //label[@name="%(field)s"]'
                ' | //page[@name="%(field)s"] | //group[@name="%(field)s"]'
                ' | //separator[@name="%(field)s"]') % {
                    'field': field
                }
            for i, element in enumerate(tree.xpath(xpath)):
                if type == 'tree' or element.tag == 'page':
                    parent = element.getparent()
                    parent.remove(element)
                elif type == 'form':
                    element.tag = 'label'
                    colspan = element.attrib.get('colspan')
                    element.attrib.clear()
                    element.attrib['id'] = 'hidden %s-%s' % (field, i)
                    if colspan is not None:
                        element.attrib['colspan'] = colspan

        if type == 'tree':
            ViewTreeWidth = pool.get('ir.ui.view_tree_width')
            viewtreewidth_ids = ViewTreeWidth.search([
                ('model', '=', cls.__name__),
                ('user', '=', Transaction().user),
            ])
            for viewtreewidth in ViewTreeWidth.browse(viewtreewidth_ids):
                if viewtreewidth.width > 0:
                    fields_width[viewtreewidth.field] = viewtreewidth.width

        fields_def = cls.__view_look_dom(tree_root,
                                         type,
                                         fields_width=fields_width)

        if field_children:
            fields_def.setdefault(field_children, {'name': field_children})
            if field_children in cls._fields:
                field = cls._fields[field_children]
                if hasattr(field, 'field'):
                    fields_def.setdefault(field.field, {'name': field.field})

        for field_name in fields_def.keys():
            if field_name in cls._fields:
                field = cls._fields[field_name]
            else:
                continue
            for depend in field.depends:
                fields_def.setdefault(depend, {'name': depend})

        if 'active' in cls._fields:
            fields_def.setdefault('active', {'name': 'active'})

        arch = etree.tostring(tree, encoding='utf-8',
                              pretty_print=False).decode('utf-8')
        fields2 = cls.fields_get(fields_def.keys())
        for field in fields_def:
            if field in fields2:
                fields2[field].update(fields_def[field])
        return arch, fields2
Beispiel #21
0
    def _load_modules(update):
        global res
        transaction = Transaction()

        with transaction.set_context(_no_trigger=True), \
                transaction.connection.cursor() as cursor:
            # Migration from 3.6: remove double module
            old_table = 'ir_module_module'
            new_table = 'ir_module'
            if backend.TableHandler.table_exist(old_table):
                backend.TableHandler.table_rename(old_table, new_table)

            # Migration from 4.0: rename installed to activated
            cursor.execute(*ir_module.select(ir_module.name,
                    where=ir_module.state.in_(('installed', 'uninstalled'))))
            if cursor.fetchone():
                cursor.execute(*ir_module.update(
                        [ir_module.state], ['activated'],
                        where=ir_module.state == 'installed'))
                cursor.execute(*ir_module.update(
                        [ir_module.state], ['not activated'],
                        where=ir_module.state == 'uninstalled'))

            if update:
                cursor.execute(*ir_module.select(ir_module.name,
                        where=ir_module.state.in_(('activated', 'to activate',
                                'to upgrade', 'to remove'))))
            else:
                cursor.execute(*ir_module.select(ir_module.name,
                        where=ir_module.state.in_(('activated', 'to upgrade',
                                'to remove'))))
            module_list = [name for (name,) in cursor.fetchall()]
            graph = None
            while graph is None:
                module_list += update
                try:
                    graph = create_graph(module_list)
                except MissingDependenciesException as e:
                    if not activatedeps:
                        raise
                    update += e.missings

            load_module_graph(graph, pool, update, lang)

            Configuration = pool.get('ir.configuration')
            Configuration(1).check()

            if update:
                cursor.execute(*ir_module.select(ir_module.name,
                        where=(ir_module.state == 'to remove')))
                fetchall = cursor.fetchall()
                if fetchall:
                    for (mod_name,) in fetchall:
                        # TODO check if ressource not updated by the user
                        cursor.execute(*ir_model_data.select(
                                ir_model_data.model, ir_model_data.db_id,
                                where=(ir_model_data.module == mod_name),
                                order_by=ir_model_data.id.desc))
                        for rmod, rid in cursor.fetchall():
                            Model = pool.get(rmod)
                            Model.delete([Model(rid)])
                        Transaction().connection.commit()
                    cursor.execute(*ir_module.update([ir_module.state],
                            ['not activated'],
                            where=(ir_module.state == 'to remove')))
                    Transaction().connection.commit()
                    res = False

                Module = pool.get('ir.module')
                Module.update_list()
        # Need to commit to unlock SQLite database
        transaction.commit()
Beispiel #22
0
    def __view_look_dom(cls,
                        element,
                        type,
                        fields_width=None,
                        fields_attrs=None):
        pool = Pool()
        Translation = pool.get('ir.translation')
        ModelData = pool.get('ir.model.data')
        Button = pool.get('ir.model.button')
        User = pool.get('res.user')

        if fields_width is None:
            fields_width = {}
        if not fields_attrs:
            fields_attrs = {}
        else:
            fields_attrs = copy.deepcopy(fields_attrs)

        def set_view_ids(element):
            view_ids = []
            if element.get('view_ids'):
                for view_id in element.get('view_ids').split(','):
                    try:
                        view_ids.append(int(view_id))
                    except ValueError:
                        view_ids.append(ModelData.get_id(*view_id.split('.')))
                element.attrib['view_ids'] = ','.join(map(str, view_ids))
            return view_ids

        def get_relation(field):
            if hasattr(field, 'model_name'):
                return field.model_name
            elif hasattr(field, 'get_target'):
                return field.get_target().__name__

        def get_views(relation, view_ids, mode):
            Relation = pool.get(relation)
            views = {}
            if field._type in ['one2many', 'many2many']:
                # Prefetch only the first view to prevent infinite loop
                if view_ids:
                    for view_id in view_ids:
                        view = Relation.fields_view_get(view_id=view_id)
                        views[str(view_id)] = view
                        break
                else:
                    for view_type in mode:
                        views[view_type] = (Relation.fields_view_get(
                            view_type=view_type))
                        break
            return views

        for attr in ('name', 'icon'):
            if not element.get(attr):
                continue
            fields_attrs.setdefault(element.get(attr), {})

        if element.tag == 'field' and type in ['tree', 'form']:
            for attr in ('name', 'icon'):
                fname = element.get(attr)
                if not fname:
                    continue
                view_ids = set_view_ids(element)
                if type != 'form':
                    continue
                field = cls._fields[fname]
                relation = get_relation(field)
                if not relation:
                    continue
                mode = (element.attrib.pop('mode', None)
                        or 'tree,form').split(',')
                views = get_views(relation, view_ids, mode)
                element.attrib['mode'] = ','.join(mode)
                fields_attrs[fname].setdefault('views', {}).update(views)

            if type == 'tree' and element.get('name') in fields_width:
                element.set('width', str(fields_width[element.get('name')]))

        encoder = PYSONEncoder()
        if element.tag == 'button':
            button_name = element.attrib['name']
            if button_name in cls._buttons:
                states = cls._buttons[button_name]
            else:
                states = {}
            groups = set(User.get_groups())
            button_groups = Button.get_groups(cls.__name__, button_name)
            if button_groups and not groups & button_groups:
                states = states.copy()
                states['readonly'] = True
            element.set('states', encoder.encode(states))

            change = cls.__change_buttons[button_name]
            if change:
                element.set('change', encoder.encode(list(change)))
            if not is_instance_method(cls, button_name):
                element.set('type', 'class')
            else:
                element.set('type', 'instance')

        # translate view
        if Transaction().language != 'en_US':
            for attr in ('string', 'sum', 'confirm', 'help'):
                if element.get(attr):
                    trans = Translation.get_source(cls.__name__, 'view',
                                                   Transaction().language,
                                                   element.get(attr))
                    if trans:
                        element.set(attr, trans)

        # Set header string
        if element.tag in ('form', 'tree', 'graph'):
            element.set(
                'string',
                cls.view_header_get(element.get('string') or '',
                                    view_type=element.tag))

        if element.tag == 'tree' and element.get('sequence'):
            fields_attrs.setdefault(element.get('sequence'), {})

        if element.tag == 'calendar':
            for attr in ('dtstart', 'dtend'):
                if element.get(attr):
                    fields_attrs.setdefault(element.get(attr), {})

        for field in element:
            fields_attrs = cls.__view_look_dom(field,
                                               type,
                                               fields_width=fields_width,
                                               fields_attrs=fields_attrs)
        return fields_attrs
 def execute(cls, ids, data):
     with Transaction().set_context({
                 'html_report_ids': ids,
                 'html_report_data': data,
                 }):
         return super().execute(ids, data)
Beispiel #24
0
 def analytic_accounts_domain(cls):
     context = Transaction().context.copy()
     context['context'] = context
     return PYSONDecoder(context).decode(PYSONEncoder().encode(
         cls.analytic_accounts.domain))
Beispiel #25
0
 def _deactivate_extension(cls):
     connection = Transaction().connection
     cursor = connection.cursor()
     cursor.execute('DROP EXTENSION "unaccent"')
     connection.commit()
     cls._clear_unaccent_cache()
    def default_start(self, fields):

        Invoice = Pool().get('account.invoice')
        Journal = Pool().get('account.journal')
        Date = Pool().get('ir.date')
        fecha_actual = Date.today()

        default = {}
        journals = Journal.search([('type', '=', 'expense')])
        for j in journals:
            journal = j

        invoice = Invoice(Transaction().context.get('active_id'))

        invoice.set_number()
        #invoice.create_move()

        pool = Pool()
        Taxes = pool.get('account.tax')
        taxes_1 = Taxes.search([('type', '=', 'percentage')])

        if invoice.type == 'in_invoice':
            default['type'] = 'in_withholding'

        if invoice.reference:
            default['number_w'] = invoice.reference

        default['account'] = j.id
        default['withholding_address'] = invoice.invoice_address.id
        default['description'] = invoice.description
        default['reference'] = invoice.number
        default['comment'] = invoice.comment
        default['company'] = invoice.company.id
        default['party'] = invoice.party.id
        default['currency'] = invoice.currency.id
        default['journal'] = journal.id
        default['taxes'] = []
        if invoice.taxes:
            default['base_imponible'] = invoice.taxes[0].base
            default['iva'] = invoice.taxes[0].amount
        else:
            self.raise_user_error('Verifique los impuestos de la factura')
        default['withholding_date'] = fecha_actual

        if invoice.party.impuesto_iva and invoice.party.impuestos_renta:
            pool = Pool()
            Tax = pool.get('account.tax')
            w_iva = invoice.party.impuesto_iva
            w_renta = invoice.party.impuestos_renta
            amount_i = Tax.compute([w_iva], invoice.taxes[0].amount, 1)
            amount_r = Tax.compute([w_renta], invoice.taxes[0].base, 1)
            for value in amount_i:
                amount_w_i = value['amount']
            for value in amount_r:
                amount_w_r = value['amount']
            print "Valores ", amount_w_i, amount_w_r
            taxes = {
                'tax': w_iva.id,
                'manual': True,
                'base': invoice.taxes[0].amount,
                'amount': amount_w_i,
                'tipo': 'IVA',
            }
            default['taxes'].append(taxes)
            taxes = {
                'tax': w_renta.id,
                'manual': True,
                'base': invoice.taxes[0].base,
                'amount': amount_w_r,
                'tipo': 'RENTA',
            }
            default['taxes'].append(taxes)
            return default
        else:
            return self.raise_user_error(
                'No ha configurado los impuestos de retencion del proveedor')
Beispiel #27
0
def getControllerName():
    if Transaction().language in ('es', 'es_419'):
        return 'Formulario genérico - XLS'
    else:
        return 'Generic Form - XLS'
Beispiel #28
0
 def end(self):
     model = Transaction().context.get('active_model')
     if model == 'account.move.line':
         return 'reload'
Beispiel #29
0
 def default_company():
     return Transaction().context.get('company')
Beispiel #30
0
 def get(cls):
     user = Transaction().user
     favorites = cls.search([
             ('user', '=', user),
             ])
     return [(f.menu.id, f.menu.rec_name, f.menu.icon) for f in favorites]