示例#1
0
    def __register__(cls, module_name):
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().connection.cursor()

        super(Attachment, cls).__register__(module_name)

        table = TableHandler(cls, module_name)
        attachment = cls.__table__()

        # Migration from 1.4 res_model and res_id merged into resource
        # Reference
        if table.column_exist('res_model') and \
                table.column_exist('res_id'):
            table.drop_constraint('res_model_res_id_name')
            cursor.execute(*attachment.update(
                [attachment.resource],
                [Concat(Concat(attachment.resource, ','), attachment.res_id)]))
            table.drop_column('res_model')
            table.drop_column('res_id')

        # Migration from 4.0: merge digest and collision into file_id
        if table.column_exist('digest') and table.column_exist('collision'):
            cursor.execute(
                *attachment.update([attachment.file_id], [attachment.digest],
                                   where=(attachment.collision == 0)
                                   | (attachment.collision == Null)))
            cursor.execute(*attachment.update(
                [attachment.file_id],
                [Concat(Concat(attachment.digest, '-'), attachment.collision)],
                where=(attachment.collision != 0)
                & (attachment.collision != Null)))
            table.drop_column('digest')
            table.drop_column('collision')
示例#2
0
 def _get_translation_join(self, Model, name, translation, model, table,
                           from_, language):
     if Model.__name__ == 'ir.model':
         return from_.join(translation,
                           'LEFT',
                           condition=(translation.name == Concat(
                               Concat(table.model, ','), name))
                           & (translation.res_id == -1)
                           & (translation.lang == language)
                           & (translation.type == 'model')
                           & (translation.fuzzy == False))
     elif Model.__name__ == 'ir.model.field':
         if name == 'field_description':
             type_ = 'field'
         else:
             type_ = 'help'
         return from_.join(model, 'LEFT',
                           condition=model.id == table.model).join(
                               translation,
                               'LEFT',
                               condition=(translation.name == Concat(
                                   Concat(model.model, ','), table.name))
                               & (translation.res_id == -1)
                               & (translation.lang == language)
                               & (translation.type == type_)
                               & (translation.fuzzy == False))
     else:
         return from_.join(translation,
                           'LEFT',
                           condition=(translation.res_id == table.id)
                           & (translation.name == '%s,%s' %
                              (Model.__name__, name))
                           & (translation.lang == language)
                           & (translation.type == 'model')
                           & (translation.fuzzy == False))
示例#3
0
    def __register__(cls, module_name):
        pool = Pool()
        Move = pool.get('stock.move')
        PurchaseLine = pool.get('purchase.line')
        Purchase = pool.get('purchase.purchase')
        cursor = Transaction().connection.cursor()
        sql_table = cls.__table__()
        move = Move.__table__()
        line = PurchaseLine.__table__()
        purchase = Purchase.__table__()

        # Migration from 3.8: New supplier field
        cursor.execute(*sql_table.select(
            sql_table.supplier, where=sql_table.supplier == Null, limit=1))
        if cursor.fetchone():
            value = sql_table.join(
                move,
                condition=(Concat(
                    cls.__name__ + ',', sql_table.id) == move.shipment)).join(
                        line,
                        condition=(Concat(
                            PurchaseLine.__name__ + ',',
                            line.id) == move.origin)).join(
                                purchase,
                                condition=(
                                    purchase.id == line.purchase)).select(
                                        Max(purchase.party))
            cursor.execute(*sql_table.update(columns=[sql_table.supplier],
                                             values=[value]))
        super(ShipmentInReturn, cls).__register__(module_name)
示例#4
0
文件: user.py 项目: zarumaru/trytond
    def __register__(cls, module_name):
        pool = Pool()
        ModelData = pool.get('ir.model.data')
        model_data = ModelData.__table__()
        cursor = Transaction().connection.cursor()
        super(User, cls).__register__(module_name)
        table = cls.__table_handler__(module_name)

        # Migration from 3.0
        if table.column_exist('password') and table.column_exist('salt'):
            sqltable = cls.__table__()
            password_hash_new = Concat(
                'sha1$',
                Concat(sqltable.password,
                       Concat('$', Coalesce(sqltable.salt, ''))))
            cursor.execute(*sqltable.update(columns=[sqltable.password_hash],
                                            values=[password_hash_new]))
            table.drop_column('password')
            table.drop_column('salt')

        # Migration from 4.2: Remove required on name
        table.not_null_action('name', action='remove')

        # Migration from 5.6: Set noupdate to admin
        cursor.execute(
            *model_data.update([model_data.noupdate], [True],
                               where=(model_data.model == cls.__name__)
                               & (model_data.module == 'res')
                               & (model_data.fs_id == 'user_admin')))
示例#5
0
    def __register__(cls, module_name):
        cursor = Transaction().connection.cursor()

        super(Attachment, cls).__register__(module_name)

        table = cls.__table_handler__(module_name)
        attachment = cls.__table__()

        # Migration from 4.0: merge digest and collision into file_id
        if table.column_exist('digest') and table.column_exist('collision'):
            cursor.execute(*attachment.update(
                    [attachment.file_id],
                    [attachment.digest],
                    where=(attachment.collision == 0)
                    | (attachment.collision == Null)))
            cursor.execute(*attachment.update(
                    [attachment.file_id],
                    [Concat(Concat(attachment.digest, '-'),
                            attachment.collision)],
                    where=(attachment.collision != 0)
                    & (attachment.collision != Null)))
            table.drop_column('digest')
            table.drop_column('collision')

        # Migration from 4.8: remove unique constraint
        table.drop_constraint('resource_name')
示例#6
0
    def __register__(cls, module_name):
        pool = Pool()
        Move = pool.get('stock.move')
        PurchaseLine = pool.get('purchase.line')
        PurchaseRequest = pool.get('purchase.request')
        SaleLine = pool.get('sale.line')
        Location = pool.get('stock.location')
        move = Move.__table__()
        purchase_line = PurchaseLine.__table__()
        purchase_request = PurchaseRequest.__table__()
        sale_line = SaleLine.__table__()
        location = Location.__table__()
        cursor = Transaction().cursor

        super(ShipmentDrop, cls).__register__(module_name)

        # Migration from 3.6
        cursor.execute(*location.select(Count(location.id),
                where=(location.type == 'drop')))
        has_drop_shipment, = cursor.fetchone()

        if not has_drop_shipment:
            drop_shipment = Location(name='Migration Drop Shipment',
                type='drop', active=False)
            drop_shipment.save()
            drop_shipment_location = drop_shipment.id

            move_sale_query = move.join(purchase_line,
                condition=move.origin == Concat('purchase.line,',
                    purchase_line.id)
                ).join(purchase_request,
                condition=purchase_request.purchase_line == purchase_line.id
                ).join(sale_line,
                condition=sale_line.purchase_request == purchase_request.id
                ).select(
                    move.id, move.to_location, sale_line.id,
                    where=move.shipment.like('stock.shipment.drop,%'))
            cursor.execute(*move_sale_query)
            move_sales = cursor.fetchall()

            for sub_move in grouped_slice(move_sales):
                sub_ids = [s[0] for s in sub_move]
                cursor.execute(*move.update(
                        columns=[move.to_location],
                        values=[drop_shipment_location],
                        where=move.id.in_(sub_ids)))

            create_move = move.insert(values=move.select(
                    where=move.shipment.like('stock.shipment.drop,%')))
            cursor.execute(*create_move)

            for move_id, customer_location, line_id in move_sales:
                cursor.execute(move.update(
                        columns=[move.origin, move.from_location,
                            move.to_location],
                        values=[Concat('sale.line,', str(line_id)),
                            drop_shipment_location, customer_location],
                        where=(move.id == move_id)))
示例#7
0
    def __register__(cls, module_name):
        cursor = Transaction().connection.cursor()
        sql_table = cls.__table__()

        super(Address, cls).__register__(module_name)

        table = cls.__table_handler__(module_name)

        # Migration from 4.0: remove streetbis
        if table.column_exist('streetbis'):
            value = Concat(Coalesce(sql_table.street, ''),
                           Concat('\n', Coalesce(sql_table.streetbis, '')))
            cursor.execute(*sql_table.update([sql_table.street], [value]))
            table.drop_column('streetbis')
示例#8
0
    def get_lines_to_pay(cls, invoices, name):
        pool = Pool()
        Move = pool.get('account.move')
        Line = pool.get('account.move.line')
        Account = pool.get('account.account')
        line = Line.__table__()
        account = Account.__table__()
        move = Move.__table__()
        invoice = cls.__table__()
        cursor = Transaction().connection.cursor()
        _, origin_type = Move.origin.sql_type()

        lines = super(Invoice, cls).get_lines_to_pay(invoices, name)
        for sub_ids in grouped_slice(invoices):
            red_sql = reduce_ids(invoice.id, sub_ids)
            query = invoice.join(move,
                condition=((move.origin == Concat('account.invoice,',
                                Cast(invoice.id, origin_type))))
                    ).join(line, condition=(line.move == move.id)
                    ).join(account, condition=(
                        (line.account == account.id) &
                        Case((invoice.type == 'out',
                            account.kind == 'receivable'),
                            else_=account.kind == 'payable'))).select(
                    invoice.id, line.id,
                    where=(line.maturity_date != None) & red_sql,
                    order_by=(invoice.id, line.maturity_date))
            cursor.execute(*query)
            for invoice_id, line_id in cursor.fetchall():
                if line_id not in lines[invoice_id]:
                    lines[invoice_id].append(line_id)
        return lines
示例#9
0
 def format_full_text(self, *documents, language=None):
     size = max(len(documents) // 4, 1)
     if len(documents) > 1:
         weights = chain(
             ['A'] * size, ['B'] * size, ['C'] * size, repeat('D'))
     else:
         weights = [None]
     expression = None
     if language:
         config_name = self._search_full_text_language(language)
     else:
         config_name = None
     for document, weight in zip(documents, weights):
         if not document:
             continue
         if config_name:
             ts_vector = ToTsvector(config_name, document)
         else:
             ts_vector = ToTsvector('simple', document)
         if weight:
             ts_vector = Setweight(ts_vector, weight)
         if expression is None:
             expression = ts_vector
         else:
             expression = Concat(expression, ts_vector)
     return expression
示例#10
0
    def __register__(cls, module_name):
        pool = Pool()
        Model = pool.get('ir.model')
        Trigger = pool.get('ir.trigger')
        model = Model.__table__()
        trigger = Trigger.__table__()
        table = cls.__table__()
        super().__register__(module_name)

        table_h = cls.__table_handler__(module_name)
        cursor = Transaction().connection.cursor()

        # Migration from 5.6:
        # fill notification and resource
        # remove required on trigger
        notification = trigger.select(trigger.notification_email,
                                      where=trigger.id == table.trigger)
        resource = (trigger.join(model,
                                 condition=trigger.model == model.id).select(
                                     Concat(model.model, ',-1'),
                                     where=trigger.id == table.trigger))
        cursor.execute(*table.update(
            [table.notification, table.resource], [notification, resource],
            where=(table.trigger != Null) & (table.resource == Null)))
        table_h.not_null_action('trigger', 'remove')
示例#11
0
    def __register__(cls, module_name):
        pool = Pool()
        StatementLine = pool.get('account.statement.line')
        cursor = Transaction().cursor
        sql_table = cls.__table__()

        super(Move, cls).__register__(module_name)

        # Migration from 3.4:
        # account.statement.line origin changed to account.statement
        statement_line = StatementLine.__table__()
        cursor.execute(*sql_table.join(statement_line,
                condition=(
                    Concat(StatementLine.__name__ + ',', statement_line.id)
                    == sql_table.origin
                    )
                ).select(sql_table.id, statement_line.statement,
                order_by=(sql_table.id, statement_line.statement)))
        for statement_id, values in groupby(cursor.fetchall(), itemgetter(1)):
            ids = [x[0] for x in values]
            for sub_ids in grouped_slice(ids):
                red_sql = reduce_ids(sql_table.id, sub_ids)
                cursor.execute(*sql_table.update(
                        columns=[sql_table.origin],
                        values=['account.statement,%s' % statement_id],
                        where=red_sql))
示例#12
0
    def __register__(cls, module_name):
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().connection.cursor()
        table = TableHandler(cls, module_name)
        sql_table = cls.__table__()

        super(Address, cls).__register__(module_name)

        # Migration from 2.4: drop required on sequence
        table.not_null_action('sequence', action='remove')

        # Migration from 4.0: remove streetbis
        if table.column_exist('streetbis'):
            value = Concat(Coalesce(sql_table.street, ''),
                           Concat('\n', Coalesce(sql_table.streetbis, '')))
            cursor.execute(*sql_table.update([sql_table.street], [value]))
            table.drop_column('streetbis')
示例#13
0
    def __register__(cls, module_name):
        cursor = Transaction().connection.cursor()
        super(User, cls).__register__(module_name)
        table = cls.__table_handler__(module_name)

        # Migration from 3.0
        if table.column_exist('password') and table.column_exist('salt'):
            sqltable = cls.__table__()
            password_hash_new = Concat('sha1$', Concat(sqltable.password,
                Concat('$', Coalesce(sqltable.salt, ''))))
            cursor.execute(*sqltable.update(
                columns=[sqltable.password_hash],
                values=[password_hash_new]))
            table.drop_column('password')
            table.drop_column('salt')

        # Migration from 4.2: Remove required on name
        table.not_null_action('name', action='remove')
示例#14
0
    def order_rec_name(cls, tables):
        exemplary, _ = tables[None]
        book = tables.get('book')

        if book is None:
            book = Pool().get('library.book').__table__()
            tables['book'] = {None: (book, book.id == exemplary.book)}

        return [Concat(book.title, exemplary.identifier)]
示例#15
0
    def _purchase_cost(cls, works):
        'Compute direct purchase cost'
        pool = Pool()
        Currency = pool.get('currency.currency')
        PurchaseLine = pool.get('purchase.line')
        InvoiceLine = pool.get('account.invoice.line')
        Invoice = pool.get('account.invoice')
        Company = pool.get('company.company')

        cursor = Transaction().connection.cursor()
        table = cls.__table__()
        purchase_line = PurchaseLine.__table__()
        invoice_line = InvoiceLine.__table__()
        invoice = Invoice.__table__()
        company = Company.__table__()

        amounts = defaultdict(Decimal)
        work_ids = [w.id for w in works]
        work2currency = {}
        iline2work = {}
        for sub_ids in grouped_slice(work_ids):
            where = reduce_ids(table.id, sub_ids)
            cursor.execute(*table.join(purchase_line,
                    condition=purchase_line.work == table.id
                    ).join(invoice_line,
                    condition=invoice_line.origin == Concat(
                        'purchase.line,', purchase_line.id)
                    ).join(invoice,
                    condition=invoice_line.invoice == invoice.id
                    ).select(invoice_line.id, table.id,
                    where=where & ~invoice.state.in_(['draft', 'cancel'])))
            iline2work.update(cursor.fetchall())

            cursor.execute(*table.join(company,
                    condition=table.company == company.id
                    ).select(table.id, company.currency,
                    where=where))
            work2currency.update(cursor.fetchall())

        currencies = Currency.browse(set(work2currency.values()))
        id2currency = {c.id: c for c in currencies}

        invoice_lines = InvoiceLine.browse(list(iline2work.keys()))
        for invoice_line in invoice_lines:
            invoice = invoice_line.invoice
            work_id = iline2work[invoice_line.id]
            currency_id = work2currency[work_id]
            currency = id2currency[currency_id]
            if currency != invoice.currency:
                with Transaction().set_context(date=invoice.currency_date):
                    amount = Currency.compute(invoice.currency,
                        invoice_line.amount, currency)
            else:
                amount = invoice_line.amount
            amounts[work_id] += amount
        return amounts
示例#16
0
    def __register__(cls, module_name):
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor

        super(Attachment, cls).__register__(module_name)

        table = TableHandler(cursor, cls, module_name)
        attachment = cls.__table__()

        # Migration from 1.4 res_model and res_id merged into resource
        # Reference
        if table.column_exist('res_model') and \
                table.column_exist('res_id'):
            table.drop_constraint('res_model_res_id_name')
            cursor.execute(*attachment.update(
                [attachment.resource],
                [Concat(Concat(attachment.resource, ','), attachment.res_id)]))
            table.drop_column('res_model')
            table.drop_column('res_id')
示例#17
0
    def __register__(cls, module_name):
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().connection.cursor()
        super(User, cls).__register__(module_name)
        table = TableHandler(cls, module_name)

        # Migration from 1.6

        # For module dashboard
        table.module_name = 'dashboard'
        table.not_null_action('dashboard_layout', action='remove')

        # For module calendar_scheduling
        table.module_name = 'calendar_scheduling'
        for field in (
                'calendar_email_notification_new',
                'calendar_email_notification_update',
                'calendar_email_notification_cancel',
                'calendar_email_notification_partstat',
        ):
            table.not_null_action(field, action='remove')

        # Migration from 2.2
        table.not_null_action('menu', action='remove')

        # Migration from 2.6
        table.drop_column('login_try')

        # Migration from 3.0
        if table.column_exist('password') and table.column_exist('salt'):
            sqltable = cls.__table__()
            password_hash_new = Concat(
                'sha1$',
                Concat(sqltable.password,
                       Concat('$', Coalesce(sqltable.salt, ''))))
            cursor.execute(*sqltable.update(columns=[sqltable.password_hash],
                                            values=[password_hash_new]))
            table.drop_column('password')
            table.drop_column('salt')

        # Migration from 4.2: Remove required on name
        table.not_null_action('name', action='remove')
示例#18
0
    def __register__(cls, module):
        table = cls.__table__()

        super().__register__(module)

        table_h = cls.__table_handler__(module)
        cursor = Transaction().connection.cursor()
        if table_h.column_exist('invoice'):
            cursor.execute(*table.update(
                    [table.related_to],
                    [Concat('account.invoice,', table.invoice)],
                    where=table.invoice != Null))
            table_h.drop_column('invoice')
示例#19
0
    def _get_invoiced_amount_timesheet(cls, works):
        pool = Pool()
        TimesheetWork = pool.get('timesheet.work')
        TimesheetLine = pool.get('timesheet.line')
        InvoiceLine = pool.get('account.invoice.line')
        Company = pool.get('company.company')
        Currency = pool.get('currency.currency')

        cursor = Transaction().connection.cursor()
        table = cls.__table__()
        timesheet_work = TimesheetWork.__table__()
        timesheet_line = TimesheetLine.__table__()
        invoice_line = InvoiceLine.__table__()
        company = Company.__table__()

        amounts = {}
        work2currency = {}
        work_ids = [w.id for w in works]
        for sub_ids in grouped_slice(work_ids):
            where = reduce_ids(table.id, sub_ids)
            cursor.execute(*table.join(timesheet_work,
                    condition=(
                        Concat(cls.__name__ + ',', table.id)
                        == timesheet_work.origin)
                    ).join(timesheet_line,
                    condition=timesheet_line.work == timesheet_work.id
                    ).join(invoice_line,
                    condition=timesheet_line.invoice_line == invoice_line.id
                    ).select(table.id,
                    Sum(timesheet_line.duration * invoice_line.unit_price),
                    where=where,
                    group_by=table.id))
            amounts.update(cursor.fetchall())

            cursor.execute(*table.join(company,
                    condition=table.company == company.id
                    ).select(table.id, company.currency,
                    where=where))
            work2currency.update(cursor.fetchall())

        currencies = Currency.browse(set(work2currency.itervalues()))
        id2currency = {c.id: c for c in currencies}

        for work in works:
            currency = id2currency[work2currency[work.id]]
            amount = amounts.get(work.id, 0)
            if isinstance(amount, datetime.timedelta):
                amount = amount.total_seconds()
            amount = amount / 60 / 60
            amounts[work.id] = currency.round(Decimal(str(amount)))
        return amounts
示例#20
0
    def __register__(cls, module_name):
        pool = Pool()
        ModelData = pool.get('ir.model.data')
        cursor = Transaction().cursor
        model_data = ModelData.__table__()

        # Migration from 3.4: translation of the account chart
        cursor.execute(
            *model_data.update(columns=[model_data.fs_id],
                               values=[Concat(model_data.fs_id, '_fr')],
                               where=((Position('_fr', model_data.fs_id) == 0)
                                      & (model_data.module == 'account_be'))))

        super(AccountTemplate, cls).__register__(module_name)
示例#21
0
文件: trigger.py 项目: tryton/trytond
    def __register__(cls, module_name):
        cursor = Transaction().connection.cursor()
        table = cls.__table_handler__(cls, module_name)
        sql_table = cls.__table__()

        super(Trigger, cls).__register__(module_name)

        table_h = cls.__table_handler__(module_name)

        # Migration from 3.4:
        # change minimum_delay into timedelta minimum_time_delay
        if table.column_exist('minimum_delay'):
            cursor.execute(*sql_table.select(
                    sql_table.id, sql_table.minimum_delay,
                    where=sql_table.minimum_delay != Null))
            for id_, delay in cursor:
                delay = datetime.timedelta(hours=delay)
                cursor.execute(*sql_table.update(
                        [sql_table.minimum_time_delay],
                        [delay],
                        where=sql_table.id == id_))
            table.drop_column('minimum_delay')

        # Migration from 5.4: merge action
        if (table_h.column_exist('action_model')
                and table_h.column_exist('action_function')):
            pool = Pool()
            Model = pool.get('ir.model')
            model = Model.__table__()
            action_model = model.select(
                model.model, where=model.id == sql_table.action_model)
            cursor.execute(*sql_table.update(
                    [sql_table.action],
                    [Concat(action_model, Concat(
                                '|', sql_table.action_function))]))
            table_h.drop_column('action_model')
            table_h.drop_column('action_function')
示例#22
0
    def __register__(cls, module_name):
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor
        sql_table = cls.__table__()

        super(Move, cls).__register__(module_name)

        table = TableHandler(cursor, cls, module_name)

        # Migration from 2.6: remove purchase_line
        if table.column_exist('purchase_line'):
            cursor.execute(*sql_table.update(
                    columns=[sql_table.origin],
                    values=[Concat('purchase.line,', sql_table.purchase_line)],
                    where=sql_table.purchase_line != Null))
            table.drop_column('purchase_line')
示例#23
0
    def __register__(cls, module):
        pool = Pool()
        Party = pool.get('party.party')
        Identifier = pool.get('party.identifier')
        cursor = Transaction().connection.cursor()
        party = Party.__table__()
        address = cls.__table__()
        identifier = Identifier.__table__()

        super().__register__(module)

        table_h = cls.__table_handler__(module)
        party_h = Party.__table_handler__(module)

        # Migrate from 6.2: replace siren and siret by identifier
        if party_h.column_exist('siren'):
            cursor.execute(
                *identifier.insert([
                    identifier.party, identifier.type, identifier.code,
                    identifier.active
                ],
                                   party.select(party.id,
                                                Literal('fr_siren'),
                                                party.siren,
                                                party.active,
                                                where=(party.siren != Null)
                                                & (party.siren != ''))))
            if table_h.column_exist('siret_nic'):
                cursor.execute(*identifier.insert(
                    [
                        identifier.party, identifier.address, identifier.type,
                        identifier.code, identifier.active
                    ],
                    address.join(party, condition=address.party == party.id).
                    select(address.party,
                           address.id,
                           Literal('fr_siret'),
                           Concat(party.siren, address.siret_nic),
                           address.active,
                           where=(address.siret_nic != Null)
                           & (address.siret_nic != '')
                           & (party.siren != Null)
                           & (party.siren != ''))))
                table_h.drop_column('siret_nic')
            party_h.drop_column('siren')
示例#24
0
    def clean_properties_from_4_2(cls):
        from sql import Null, Table, Cast
        from sql.operators import Like, Concat

        TableHandler = backend.get('TableHandler')
        if not TableHandler.table_exist('ir_property'):
            return

        property = Table('ir_property')

        cursor = Transaction().connection.cursor()
        cursor.execute(
            *property.select(property.res, where=property.res != Null))

        res_model_names = list(
            set([x[0].split(',')[0] for x in cursor.fetchall()]))

        to_delete = {}

        for res_model_name in res_model_names:
            table_name = res_model_name.replace('.', '_')
            res_model = Table(table_name)
            query_table = property.join(res_model,
                                        'LEFT OUTER',
                                        condition=(property.res == Concat(
                                            res_model_name + ',',
                                            Cast(res_model.id, 'VARCHAR'))))
            cursor.execute(
                *query_table.select(property.id,
                                    where=Like(property.res, res_model_name +
                                               ',%') & (res_model.id == Null)))
            property_ids = [x[0] for x in cursor.fetchall()]
            if property_ids:
                to_delete[res_model_name] = property_ids
        if to_delete:
            cursor.execute(*property.delete(
                where=property.id.in_(sum([p
                                           for p in to_delete.values()], []))))
            for res_model_name, property_ids in to_delete.items():
                if property_ids:
                    print '[%s] - %s Inconsistent record(s) removed' % (
                        res_model_name, len(property_ids))
        else:
            print 'Nothing to do - Exisiting property records are clean'
示例#25
0
    def _get_cost(cls, works):
        pool = Pool()
        Line = pool.get('timesheet.line')
        Work = pool.get('timesheet.work')
        transaction = Transaction()
        cursor = transaction.connection.cursor()

        costs = dict.fromkeys([w.id for w in works], 0)

        table = cls.__table__()
        work = Work.__table__()
        line = Line.__table__()

        # Timesheet cost
        work_ids = [w.id for w in works]
        for sub_ids in grouped_slice(work_ids):
            red_sql = reduce_ids(table.id, sub_ids)
            cursor.execute(
                *table.join(work,
                            condition=(Concat(cls.__name__ +
                                              ',', table.id) == work.origin)).
                join(line, condition=line.work == work.id).select(
                    table.id,
                    Sum(line.cost_price * line.duration),
                    where=red_sql,
                    group_by=[table.id]))
            for work_id, cost in cursor:
                # SQLite stores timedelta as float
                if not isinstance(cost, float):
                    cost = cost.total_seconds()
                # Convert from seconds
                cost /= 60 * 60
                costs[work_id] += Decimal(str(cost))

        # Purchase cost
        if hasattr(cls, 'purchase_lines'):
            for work_id, cost in cls._purchase_cost(works).items():
                costs[work_id] += cost

        for work in works:
            costs[work.id] = work.company.currency.round(costs[work.id])
        return costs
示例#26
0
    def restore_default_party_lang_from_4_2(cls):
        from trytond.transaction import Transaction
        from sql import Null, Table, Cast
        from sql.operators import Concat
        from trytond.pool import Pool

        TableHandler = backend.get('TableHandler')
        if not TableHandler.table_exist('ir_property'):
            return

        pool = Pool()
        property = Table('ir_property')
        Lang = pool.get('ir.lang')
        field = pool.get('ir.model.field').__table__()
        lang = Lang.__table__()
        cursor = Transaction().connection.cursor()

        query_table = property.join(
            lang,
            condition=(property.value == Concat(
                'ir.lang,',
                Cast(lang.id,
                     'VARCHAR')))).join(field,
                                        condition=((property.field == field.id)
                                                   & (field.name == 'lang')))

        cursor.execute(
            *query_table.select(lang.id, where=property.res == Null))
        result = cursor.fetchone()
        if result:
            result = list(result)
            default_lang = Lang(result[0])
            print 'Default Language restored [%s]' % default_lang.rec_name
            pool.get('party.configuration.party_lang').create([{
                'party_lang':
                default_lang
            }])
        else:
            print 'No default language on party configuration found'
示例#27
0
    def _sale_line(cls, length, index, company_id=None):
        pool = Pool()
        Line = pool.get('sale.line')
        Sale = pool.get('sale.sale')

        line = Line.__table__()
        sale = Sale.__table__()

        return (line.join(sale, condition=line.sale == sale.id).select(
            (line.id * length + index).as_('id'),
            line.product.as_('product'),
            Coalesce(line.actual_quantity, line.quantity).as_('quantity'),
            line.unit_price.as_('unit_price'),
            Concat('sale.sale,', line.sale).as_('order'),
            sale.sale_date.as_('date'),
            sale.company.as_('company'),
            sale.currency.as_('currency'),
            sale.party.as_('customer'),
            sale.warehouse.as_('location'),
            sale.shipment_address.as_('shipment_address'),
            where=sale.state.in_(cls._sale_states())
            & (sale.company == company_id),
        ))
示例#28
0
            sel = join2.select(t.id.as_('id'))
            sel.where = And((t3.code == 34,))
            expect(tuple(sql)).to(equal(tuple(sel)))

        with it('must support group by'):
            q = OOQuery('table')
            sel = q.select([Max('field1')], group_by=['field2'])
            sel2 = q.table.select(
                Max(q.table.field1).as_('max_field1'),
                group_by=[q.table.field2]
            )
            expect(str(sel._select)).to(equal(str(sel2)))

        with it('must support concat'):
            q = OOQuery('table')
            sel = q.select([Concat('field1', Literal(' 01:00'))])
            sel2 = q.table.select(Concat(q.table.field1, ' 01:00'))
            expect(str(sel._select)).to(equal(str(sel2)))

        with it('must support coalesce'):
            q = OOQuery('table')
            sel = q.select([Coalesce('field1', Literal(3))])
            sel2 = q.table.select(Coalesce(q.table.field1, 3))
            expect(str(sel._select)).to(equal(str(sel2)))

        with it('must support greatest'):
            q = OOQuery('table')
            sel = q.select([Greatest('field1', 'field2')])
            sel2 = q.table.select(Greatest(q.table.field1, q.table.field2))
            expect(str(sel._select)).to(equal(str(sel2)))
示例#29
0
 def _measurements_move_condition(cls, table, move):
     return Concat(cls.__name__ + ',', table.id) == move.shipment
示例#30
0
    def __register__(cls, module_name):
        Party = Pool().get('party.party')
        Model = Pool().get('ir.model')
        ModelField = Pool().get('ir.model.field')
        Property = Pool().get('ir.property')
        PaymentProfile = Pool().get('party.payment_profile')
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor
        table = TableHandler(cursor, cls, module_name)

        migration_needed = False
        if not table.column_exist('credit_account'):
            migration_needed = True

        migrate_last_four_digits = False
        if not table.column_exist('last_four_digits'):
            migrate_last_four_digits = True

        super(PaymentTransaction, cls).__register__(module_name)

        if migration_needed and not Pool.test:
            # Migration
            # Set party's receivable account as the credit_account on
            # transactions
            transaction = cls.__table__()
            party = Party.__table__()
            property = Property.__table__()

            account_model, = Model.search([
                ('model', '=', 'party.party'),
            ])
            account_receivable_field, = ModelField.search([
                ('model', '=', account_model.id),
                ('name', '=', 'account_receivable'),
                ('ttype', '=', 'many2one'),
            ])

            update = transaction.update(
                columns=[transaction.credit_account],
                values=[
                    Trim(
                        Substring(property.value, ',.*'), 'LEADING', ','
                    ).cast(cls.credit_account.sql_type().base)
                ],
                from_=[party, property],
                where=(
                    transaction.party == party.id
                ) & (
                    property.res == Concat(Party.__name__ + ',', party.id)
                ) & (
                    property.field == account_receivable_field.id
                ) & (
                    property.company == transaction.company
                )

            )
            cursor.execute(*update)

        if migrate_last_four_digits and not Pool.test:
            transaction = cls.__table__()
            payment_profile = PaymentProfile.__table__()
            cursor.execute(*transaction.update(
                columns=[transaction.last_four_digits],
                values=[payment_profile.last_4_digits],
                from_=[payment_profile],
                where=(transaction.payment_profile == payment_profile.id)
            ))