コード例 #1
0
class CreateVaccinationStockMove(Wizard):
    'Create Vaccination Stock Move'
    __name__ = 'gnuhealth.vaccination.stock.move.create'

    start = StateView('gnuhealth.vaccination.stock.move.init',
                      'health_stock.view_create_vaccination_stock_move', [
                          Button('Cancel', 'end', 'tryton-cancel'),
                          Button('Create Stock Move', 'create_stock_move',
                                 'tryton-ok', True),
                      ])
    create_stock_move = StateTransition()

    def transition_create_stock_move(self):
        pool = Pool()
        StockMove = pool.get('stock.move')
        Vaccination = pool.get('gnuhealth.vaccination')

        vaccinations = Vaccination.browse(
            Transaction().context.get('active_ids'))
        for vaccination in vaccinations:

            if vaccination.moves:
                self.raise_user_error('stock_move_exists')

            lines = []

            line_data = {}
            line_data['origin'] = str(vaccination)
            line_data['from_location'] = \
                vaccination.location.id
            line_data['to_location'] = \
                vaccination.name.name.customer_location.id
            line_data['product'] = \
                vaccination.vaccine.name.id
            line_data['unit_price'] = \
                vaccination.vaccine.name.list_price
            line_data['quantity'] = 1
            line_data['uom'] = \
                vaccination.vaccine.name.default_uom.id
            line_data['state'] = 'draft'
            lines.append(line_data)

            moves = StockMove.create(lines)

            StockMove.assign(moves)
            StockMove.do(moves)

        return 'end'

    @classmethod
    def __setup__(cls):
        super(CreateVaccinationStockMove, cls).__setup__()
        cls._error_messages.update({
            'stock_move_exists':
            'Stock moves already exists!.',
        })
コード例 #2
0
class CreateTransactions(Wizard):
    'Create transactions from bank statement lines'
    __name__ = 'account.create_transactions'

    start = StateView(
        'account.create_transactions.start',
        'create_transactions.create_transactions_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Generate', 'generate', 'tryton-ok', True),
        ])

    generate = StateTransition()

    def default_start(self, args):
        active_ids = Transaction().context['active_ids']
        self.check_selection(active_ids)

        return {'lines': active_ids}

    def check_selection(self, active_ids):
        StatementLine = Pool().get('account.bank.statement.line')

        if not active_ids:
            raise UserError(gettext('create_transactions.no_active_ids'))

        lines = StatementLine.browse(active_ids)
        if any([line.state != 'confirmed' for line in lines]):
            raise UserError(gettext('create_transactions.invalid_state'))
        if any([line.reconciled for line in lines]):
            raise UserError(
                gettext('create_transactions.must_not_be_reconciled'))

    def transition_generate(self):
        StatementMoveLine = Pool().get('account.bank.statement.move.line')
        if self.start.lines:
            analytic_accounts = [{
                'account': acc.account,
                'root': acc.root,
            } for acc in self.start.analytic_accounts]

            StatementMoveLine.create([{
                'line':
                line.id,
                'date':
                line.date.date(),
                'amount':
                line.amount,
                'account':
                self.start.account,
                'analytic_accounts': [
                    ('create', analytic_accounts),
                ] if analytic_accounts else [],
                'description':
                self.start.description,
            } for line in self.start.lines])
        return 'end'
コード例 #3
0
class CreatePrescriptionStockMove(Wizard):
    'Create Prescription Stock Move'
    __name__ = 'gnuhealth.prescription.stock.move.create'

    start = StateView('gnuhealth.prescription.stock.move.init',
                      'health_stock.view_create_prescription_stock_move', [
                          Button('Cancel', 'end', 'tryton-cancel'),
                          Button('Create Stock Move', 'create_stock_move',
                                 'tryton-ok', True),
                      ])
    create_stock_move = StateTransition()

    def transition_create_stock_move(self):
        pool = Pool()
        StockMove = pool.get('stock.move')
        Prescription = pool.get('gnuhealth.prescription.order')

        moves = []
        prescriptions = Prescription.browse(
            Transaction().context.get('active_ids'))
        for prescription in prescriptions:

            if prescription.moves:
                self.raise_user_error('stock_move_exists')

            if not prescription.pharmacy:
                self.raise_user_error('no_pharmacy_selected')

            from_location = prescription.pharmacy.warehouse
            if from_location.type == 'warehouse':
                from_location = from_location.storage_location
            to_location = prescription.patient.name.customer_location

            for line in prescription.prescription_line:
                move = StockMove()
                move.origin = prescription
                move.from_location = from_location
                move.to_location = to_location
                move.product = line.medicament.name
                move.unit_price = line.medicament.name.list_price
                move.quantity = line.quantity
                move.uom = line.medicament.name.default_uom
                moves.append(move)
        StockMove.save(moves)
        StockMove.do(moves)
        return 'end'

    @classmethod
    def __setup__(cls):
        super(CreatePrescriptionStockMove, cls).__setup__()
        cls._error_messages.update({
            'stock_move_exists':
            'Stock moves already exists!.',
            'no_pharmacy_selected':
            'You need to select a pharmacy.',
        })
コード例 #4
0
ファイル: payment.py プロジェクト: niezhiyuan1/learngit
class ProcessPayment(Wizard):
    'Process Payment'
    __name__ = 'account.payment.process'
    start = StateView(
        'account.payment.process.start',
        'account_payment.payment_process_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Process', 'process', 'tryton-ok', default=True),
        ])
    process = StateAction('account_payment.act_payment_group_form')

    @classmethod
    def __setup__(cls):
        super(ProcessPayment, cls).__setup__()
        cls._error_messages.update({
            'overpay':
            'The Payment "%(payment)s" overpays '
            'the Line "%(line)s".',
        })

    def _group_payment_key(self, payment):
        return (('journal', payment.journal.id), ('kind', payment.kind))

    def _new_group(self, values):
        pool = Pool()
        Group = pool.get('account.payment.group')
        return Group(**values)

    def do_process(self, action):
        pool = Pool()
        Payment = pool.get('account.payment')
        payments = Payment.browse(Transaction().context['active_ids'])

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

        groups = []
        payments = sorted(payments, key=self._group_payment_key)
        for key, grouped_payments in groupby(payments,
                                             key=self._group_payment_key):

            def group():
                group = self._new_group(dict(key))
                group.save()
                groups.append(group)
                return group

            Payment.process(list(grouped_payments), group)

        return action, {
            'res_id': [g.id for g in groups],
        }
コード例 #5
0
class CreateMove(Wizard):
    'Create Move from Template'
    __name__ = 'account.move.template.create'
    start = StateTransition()
    template = StateView('account.move.template.create.template',
        'account.move_template_create_template_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Next', 'keywords', 'tryton-go-next', default=True),
            ])
    keywords = KeywordStateView('account.move.template.create.keywords',
        None, [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Create', 'create_', 'tryton-ok', default=True),
            ])
    create_ = StateTransition()
    open_ = StateAction('account.act_move_form')

    def create_move(self):
        template = self.template.template
        values = {}
        for keyword in template.keywords:
            values[keyword.name] = getattr(self.keywords, keyword.name, None)
        move = template.get_move(values)
        move.period = self.template.period
        move.save()
        return move

    def transition_start(self):
        context = Transaction().context
        model = context.get('active_model')
        action_id = context.get('action_id')
        period = context.get('period')
        if model == 'account.move.line':
            # Template id is used as action
            self.template.template = action_id
            self.template.period = period
            return 'keywords'
        else:
            return 'template'

    def transition_create_(self):
        model = Transaction().context.get('active_model')
        if model:
            self.create_move()
            return 'end'
        else:
            return 'open_'

    def do_open_(self, action):
        move = self.create_move()
        action['res_id'] = [move.id]
        return action, {}

    def end(self):
        # XXX only for model account.move.line
        return 'reload'
コード例 #6
0
class TestConnection(Wizard):
    """
    Test Connection Wizard
    """
    __name__ = 'shipping_dhl_de.wizard_test_connection'

    start = StateView('shipping_dhl_de.wizard_test_connection.start',
                      'shipping_dhl_de.wizard_test_connection_view_form', [
                          Button('Ok', 'end', 'tryton-ok'),
                      ])
コード例 #7
0
ファイル: account.py プロジェクト: fabyc/nodux_account_ats
class ATSExport(Wizard):
    "Export ATS"
    __name__ = "nodux_account_ats.ats.export"

    start = StateView(
        'nodux_account_ats.print_ats.start',
        'nodux_account_ats.print_ats_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Export', 'export', 'tryton-ok', default=True),
        ])
    export = StateTransition()
    result = StateView('nodux_account_ats.ats.export.result',
                       'nodux_account_ats.ats_export_result_view_form', [
                           Button('Close', 'end', 'tryton-close'),
                       ])

    def transition_export(cls):
        pool = Pool()
        Account = pool.get('nodux_account_ats.print_ats.start')

        if cls.start.fiscalyear:
            anio = cls.start.fiscalyear
        else:
            anio = None

        if cls.start.periodo:
            period = cls.start.periodo
        else:
            period = None
        data = {
            'fiscalyear': anio,
            'periodo': period,
        }
        file_data = Account.generate_ats(data)
        cls.result.file = buffer(file_data) if file_data else None
        return 'result'

    def default_result(cls, fields):
        file_ = cls.result.file
        cls.result.file = False  # No need to store it in session
        return {
            'file': file_,
        }
コード例 #8
0
class ExportAmazonCatalog(Wizard):
    '''Export catalog to Amazon

    Export the products selected to this amazon account
    '''
    __name__ = 'amazon.export_catalog'

    start = StateView(
        'amazon.export_catalog.start', 'amazon_mws.export_catalog_start', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Continue', 'export_', 'tryton-ok', default=True),
        ])
    export_ = StateTransition()
    done = StateView('amazon.export_catalog.done',
                     'amazon_mws.export_catalog_done', [
                         Button('OK', 'end', 'tryton-cancel'),
                     ])

    def transition_export_(self):
        """
        Export the products selected to this amazon account
        """
        SaleChannel = Pool().get('sale.channel')

        amazon_channel = SaleChannel(Transaction().context.get('active_id'))

        # TODO: Move this wizard to sale channel module

        response = amazon_channel.export_product_catalog()

        Transaction().set_context({'response': response})

        return 'done'

    def default_done(self, fields):
        "Display response"
        response = Transaction().context['response']
        return {
            'status':
            response['FeedSubmissionInfo']['FeedProcessingStatus']['value'],
            'submission_id':
            response['FeedSubmissionInfo']['FeedSubmissionId']['value']
        }
コード例 #9
0
class CreatePrescriptionShipment(Wizard):
    'Create Prescription Shipment'
    __name__ = 'gnuhealth.prescription.shipment.create'

    start = StateView('gnuhealth.prescription.shipment.init',
            'health_stock.view_create_prescription_shipment', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Create Shipment', 'create_shipment',
                'tryton-ok', True),
            ])
    create_shipment = StateTransition()

    def transition_create_shipment(self):
        pool = Pool()
        Shipment = pool.get('stock.shipment.out')
        ShipmentLine = pool.get('stock.move')
        StockLocation = Pool().get('stock.location')
        Prescription = pool.get('gnuhealth.prescription.order')

        prescriptions = Prescription.browse(Transaction().context.get(
            'active_ids'))
        shipment_data = {}
        for prescription in prescriptions:
            shipment_data['customer'] = prescription.patient.name.id
            shipment_data['company'] = Transaction().context['company']
            shipment_data['warehouse'] = prescription.pharmacy.warehouse
            shipment_data['prescription_order'] = prescription.id
            if prescription.patient.name.addresses:
                shipment_data['delivery_address'] = \
                    prescription.patient.name.addresses[0]
            else:
                raise Exception('You need to define an address in the party \
                    form.')

            shipment = Shipment.create(shipment_data)

            #Create Shipment Lines
            warehouse = StockLocation(prescription.pharmacy.warehouse)
            Shipment.wait([shipment])
            for line in prescription.prescription_line:
                shipment_line_data = {}
                shipment_line_data['shipment_out'] = shipment.id
                shipment_line_data['from_location'] = \
                    warehouse.storage_location.id
                shipment_line_data['to_location'] = \
                    warehouse.output_location.id
                shipment_line_data['product'] = \
                    line.template.medicament.name.id
                shipment_line_data['quantity'] = line.quantity
                shipment_line_data['uom'] = \
                    line.template.medicament.name.default_uom.id
                shipment_line_data['state'] = 'assigned'
                ShipmentLine.create(shipment_line_data)

        return 'end'
コード例 #10
0
class MoveAddLots(Wizard):
    "Add Lots"
    __name__ = 'stock.move.add.lots'
    start = StateView('stock.move.add.lots.start',
                      'stock_lot.move_add_lots_start_view_form', [
                          Button("Cancel", 'end', 'tryton-cancel'),
                          Button("Add", 'add', 'tryton-ok', default=True),
                      ])
    add = StateTransition()

    def default_start(self, fields):
        default = {}
        if 'product' in fields:
            default['product'] = self.record.product.id
        if 'quantity' in fields:
            default['quantity'] = self.record.quantity
        if 'unit' in fields:
            default['unit'] = self.record.uom.id
        return default

    def transition_add(self):
        pool = Pool()
        Lang = pool.get('ir.lang')
        Lot = pool.get('stock.lot')
        lang = Lang.get()
        quantity_remaining = self.start.on_change_with_quantity_remaining()
        if quantity_remaining < 0:
            digits = self.record.uom.digits
            move_quantity = self.record.quantity
            lot_quantity = self.record.quantity - quantity_remaining
            raise ValidationError(
                gettext('stock_lot.msg_move_add_lot_quantity',
                        lot_quantity=lang.format_number(lot_quantity, digits),
                        move_quantity=lang.format_number(
                            move_quantity, digits)))
        lots = []
        for line in self.start.lots:
            lot = line.get_lot(self.record)
            lots.append(lot)
        Lot.save(lots)
        if quantity_remaining:
            self.record.quantity = quantity_remaining
            self.record.save()
        for i, (line, lot) in enumerate(zip(self.start.lots, lots)):
            if not i and not quantity_remaining:
                self.record.quantity = line.quantity
                self.record.lot = lot
                self.record.save()
            else:
                with Transaction().set_context(_stock_move_split=True):
                    self.model.copy([self.record], {
                        'quantity': line.quantity,
                        'lot': lot.id,
                    })
        return 'end'
コード例 #11
0
class UpdateChart(Wizard):
    'Update Chart'
    __name__ = 'analytic_account.update_chart'
    start = StateView(
        'analytic_account.update_chart.start',
        'account_financial_indicator.update_chart_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Update', 'update', 'tryton-ok', default=True),
        ])
    update = StateTransition()
    succeed = StateView(
        'analytic_account.update_chart.succeed',
        'account_financial_indicator.update_chart_succeed_view_form', [
            Button('OK', 'end', 'tryton-ok', default=True),
        ])

    @inactive_records
    def transition_update(self):
        pool = Pool()
        AnalyticAccount = \
            pool.get('analytic_account.account')
        company = self.start.company

        # Update analytic accounts
        template2analytic_account = {}

        analytic_accounts = AnalyticAccount.search([('type', '=', 'root'),
                                                    ('company', '=',
                                                     company.id)])

        #print ("ANALYTIC ACCOUNTS: ", str(analytic_accounts))

        for analytic_account in analytic_accounts:
            analytic_account.update_analytic_account(
                template2account=template2analytic_account)

            # Create missing accounts
            if analytic_account.template:
                analytic_account.template.create_analytic_account(
                    company.id, template2account=template2analytic_account)

        return 'succeed'
コード例 #12
0
class BuyPostageWizard(Wizard):
    """Buy Postage Wizard
    """
    __name__ = 'buy.postage.wizard'

    start = StateView(
        'buy.postage.wizard.view',
        'shipping_endicia.endicia_buy_postage_wizard_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Buy Postage', 'buy_postage', 'tryton-ok', default=True),
        ])
    buy_postage = StateView(
        'buy.postage.wizard.view',
        'shipping_endicia.endicia_buy_postage_wizard_view_form', [
            Button('OK', 'end', 'tryton-ok', default=True),
        ])

    def default_buy_postage(self, data):
        """
        Generate the SCAN Form for the current shipment record
        """
        default = {}

        buy_postage_api = BuyingPostageAPI(
            request_id=Transaction().user,
            recredit_amount=self.start.amount,
            requesterid=self.start.carrier.endicia_requester_id,
            accountid=self.start.carrier.endicia_account_id,
            passphrase=self.start.carrier.endicia_passphrase,
            test=self.start.carrier.endicia_is_test,
        )
        try:
            response = buy_postage_api.send_request()
        except RequestError, error:
            self.raise_user_error('error_label', error_args=(error, ))

        result = objectify_response(response)
        default['amount'] = self.start.amount
        default['carrier'] = self.start.carrier
        default['response'] = str(result.ErrorMessage) \
            if hasattr(result, 'ErrorMessage') else 'Success'
        return default
コード例 #13
0
class MoveProductStock(Wizard):
    'Move Product Stock'
    __name__ = 'move_product_stock'
    #crear referencias:
    start = StateView('move_product_stock.start',
        'nodux_purchase_product_stock_one.move_product_stock_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Move', 'move_', 'tryton-ok', default=True),
            ])
    move_ = StateTransition()

    @classmethod
    def __setup__(cls):
        super(MoveProductStock, cls).__setup__()

    def default_start(self, fields):

        return {
            'total': Decimal(0.0),
            }

    def transition_move_(self):
        pool = Pool()
        Product = pool.get('product.template')
        products = Product.browse(Transaction().context['active_ids'])

        form = self.start

        for product in products:
            if product.type == "goods":
                if product.total_warehouse != None:
                    if product.total_warehouse >= Decimal(form.total):
                        if product.total == None:
                            if product.transferidos == None:
                                product.total = Decimal(form.total)
                                product.transferidos = Decimal(form.total)
                            else:
                                product.total = Decimal(form.total)
                                product.transferidos = product.transferidos + Decimal(form.total)
                        else:
                            if product.transferidos == None:
                                product.total = Decimal(product.total) + Decimal(form.total)
                                product.transferidos = Decimal(form.total)
                            else:
                                product.total = Decimal(product.total) + Decimal(form.total)
                                product.transferidos = product.transferidos + Decimal(form.total)

                        product.total_warehouse = product.total_warehouse - Decimal(form.total)
                        product.save()
                    else:
                        self.raise_user_error('La cantidad disponible en bodega es %s', product.total_warehouse)
                else:
                    self.raise_user_error('No existe stock disponible en Bodega')
            return 'end'
コード例 #14
0
ファイル: configuration.py プロジェクト: uzayr/nereid
class NereidConfig(Wizard):
    'Configure Nereid'
    __name__ = 'nereid.website.config'
    start = StateView('nereid.website.config.start',
                      'nereid.website_config_start_view_form', [
                          Button('Cancel', 'end', 'tryton-cancel'),
                          Button('Ok', 'website', 'tryton-ok', True),
                      ])
    website = StateView('nereid.website', 'nereid.website_view_form', [
        Button('Cancel', 'end', 'tryton-cancel'),
        Button('Add', 'add', 'tryton-ok', True),
    ])
    add = StateTransition()

    def transition_add(self):
        """
        Add website during transition and close the wizard.
        """
        self.website.save()
        return 'end'
コード例 #15
0
class WizardAddListPrice(Wizard):
    'Wizard Add Term'
    __name__ = 'nodux_product_price_list_by_product_in_purchase.add_price_list'
    start = StateView(
        'nodux_product_price_list_by_product_in_purchase.add_price_list_form',
        'product.template_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Update', 'update_', 'tryton-ok'),
        ])
    update_ = StateTransition()
    """
コード例 #16
0
class InInvoicetoDraft(Wizard):
    'In Invoice To Draft'
    __name__ = 'nodux.account.in.invoice.to.draft'

    start = StateView('nodux.account.in.invoice.to.draft.start',
        'nodux_in_invoice2draft.in_invoice_to_draft_start_view_form', [
        Button('Cancel', 'end', 'tryton-cancel'),
        Button('Draft', 'draft_', 'tryton-ok', default=True),
        ])
    draft_ = StateAction('account_invoice.act_invoice_form')
    #accept = StateTransition()

    def do_draft_(self, action):
        pool = Pool()
        Sale = pool.get('sale.sale')
        Invoice = pool.get('account.invoice')
        invoices = Invoice.browse(Transaction().context['active_ids'])
        ModelData = pool.get('ir.model.data')
        User = pool.get('res.user')
        Group = pool.get('res.group')
        for invoice in invoices:
            cursor = Transaction().cursor
            def in_group():
                origin = str(invoice)
                group = Group(ModelData.get_id('nodux_in_invoice2draft',
                        'group_in_invoice_draft'))
                transaction = Transaction()

                user_id = transaction.user
                if user_id == 0:
                    user_id = transaction.context.get('user', user_id)
                if user_id == 0:
                    return True
                user = User(user_id)
                return origin and group in user.groups

            if not in_group():
                self.raise_user_error('No tiene permiso para modificar la factura %s', invoice.number)
            else:
                if invoice.type == "in_invoice":
                    if invoice.ref_withholding != "":
                        self.raise_user_error('No puede reversar una factura de compra que ya tiene Retencion autorizada por el SRI')
                    else:
                        if invoice.move:
                            cursor.execute('DELETE FROM account_move_line WHERE move = %s' %invoice.move.id)
                            cursor.execute('DELETE FROM account_move WHERE id = %s' %invoice.move.id)
                            #for line in invoice.lines:
                                #cursor.execute('DELETE FROM account_invoice_line WHERE id = %s' %line.id)
                            #cursor.execute('DELETE FROM account_invoice WHERE id = %s' %invoice.id)
                        invoice.state = "draft"
                        invoice.move = None
                        invoice.save()
                else:
                    self.raise_user_error('No puede modificar una factura de venta. Dirijase a Ventas->Ventas TPV')
コード例 #17
0
class CheckVIES(Wizard):
    'Check VIES'
    __name__ = 'party.check_vies'
    start_state = 'check'

    check = StateTransition()
    result = StateView('party.check_vies.result', 'party.check_vies_result', [
        Button('OK', 'end', 'tryton-ok', True),
    ])

    @classmethod
    def __setup__(cls):
        super(CheckVIES, cls).__setup__()
        cls._error_messages.update({
            'vies_unavailable': ('The VIES service is unavailable, '
                                 'try again later.'),
        })

    def transition_check(self):
        Party = Pool().get('party.party')

        parties_succeed = []
        parties_failed = []
        parties = Party.browse(Transaction().context.get('active_ids'))
        for party in parties:
            for identifier in party.identifiers:
                if identifier.type != 'eu_vat':
                    continue
                try:
                    if not vat.check_vies(identifier.code):
                        parties_failed.append(party.id)
                    else:
                        parties_succeed.append(party.id)
                except Exception as e:
                    if hasattr(e, 'faultstring') \
                            and hasattr(e.faultstring, 'find'):
                        if e.faultstring.find('INVALID_INPUT'):
                            parties_failed.append(party.id)
                            continue
                        if e.faultstring.find('SERVICE_UNAVAILABLE') \
                                or e.faultstring.find('MS_UNAVAILABLE') \
                                or e.faultstring.find('TIMEOUT') \
                                or e.faultstring.find('SERVER_BUSY'):
                            self.raise_user_error('vies_unavailable')
                    raise
        self.result.parties_succeed = parties_succeed
        self.result.parties_failed = parties_failed
        return 'result'

    def default_result(self, fields):
        return {
            'parties_succeed': [p.id for p in self.result.parties_succeed],
            'parties_failed': [p.id for p in self.result.parties_failed],
        }
コード例 #18
0
class BuyPostageWizard(Wizard):
    """Buy Postage Wizard
    """
    __name__ = 'buy.postage.wizard'

    start = StateView(
        'buy.postage.wizard.view',
        'endicia_integration.endicia_buy_postage_wizard_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Buy Postage', 'buy_postage', 'tryton-ok'),
        ])
    buy_postage = StateView(
        'buy.postage.wizard.view',
        'endicia_integration.endicia_buy_postage_wizard_view_form', [
            Button('OK', 'end', 'tryton-ok'),
        ])

    def default_buy_postage(self, data):
        """
        Generate the SCAN Form for the current shipment record
        """
        default = {}
        company = self.start.company
        endicia_credentials = company.get_endicia_credentials()

        buy_postage_api = BuyingPostageAPI(
            request_id=Transaction().user,
            recredit_amount=self.start.amount,
            requesterid=endicia_credentials.requester_id,
            accountid=endicia_credentials.account_id,
            passphrase=endicia_credentials.passphrase,
            test=endicia_credentials.usps_test,
        )
        response = buy_postage_api.send_request()

        result = objectify_response(response)
        default['company'] = self.start.company
        default['amount'] = self.start.amount
        default['response'] = str(result.ErrorMessage) \
            if hasattr(result, 'ErrorMessage') else 'Success'
        return default
コード例 #19
0
class EsaleSaleExportCSV(Wizard):
    'eSale Sale Export CSV'
    __name__ = "esale.sale.export.csv"
    start = StateView('esale.sale.export.csv.start',
        'esale.esale_sale_export_csv_start', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Export', 'export', 'tryton-ok', default=True),
            ])
    export = StateTransition()
    result = StateView('esale.sale.export.csv.result',
        'esale.esale_sale_export_csv_result', [
            Button('Close', 'end', 'tryton-close'),
            ])

    def transition_export(self):
        pool = Pool()
        Shop = pool.get('sale.shop')

        shop = self.start.shop
        from_date = self.start.from_date

        output = shop.esale_sale_export_csv(from_date)

        # Update date last import
        Shop.write([shop], {'esale_last_state_orders': from_date})

        self.result.csv_file = fields.Binary.cast(output.getvalue())
        if shop.esale_export_sale_filename:
            context = shop.get_export_csv_context_formula()
            filename = simple_eval(shop.esale_export_sale_filename, **context)
        else:
            filename = '%s-sales.csv' % (slugify(shop.name.replace('.', '-')))
        self.result.file_name = filename

        return 'result'

    def default_result(self, fields):
        return {
            'csv_file': self.result.csv_file,
            'file_name': self.result.file_name,
            }
コード例 #20
0
class ExportPrices(Wizard):
    """
    Export Tier Prices Wizard
    """
    __name__ = 'sale.channel.export_prices'

    start = StateView(
        'sale.channel.export_prices.start',
        'sale_channel.export_prices_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Continue', 'export_', 'tryton-ok', default=True),
        ])

    export_ = StateView('sale.channel.export_prices.status',
                        'sale_channel.export_prices_status_view_form', [
                            Button('OK', 'end', 'tryton-ok'),
                        ])

    def default_start(self, fields):
        """
        Return message to display
        """
        Channel = Pool().get('sale.channel')

        channel = Channel(Transaction().context.get('active_id'))

        return {
            'message':
            "This wizard will export product prices to %s "
            "channel (%s). " % (channel.name, channel.source)
        }

    def default_export_(self, fields):
        """
        Export prices and return count of products
        """
        Channel = Pool().get('sale.channel')

        channel = Channel(Transaction().context.get('active_id'))

        return {'products_count': channel.export_product_prices()}
コード例 #21
0
class ProcessPayment(Wizard):
    'Process Payment'
    __name__ = 'account.payment.process'
    start = StateView(
        'account.payment.process.start',
        'account_payment.payment_process_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Process', 'process', 'tryton-ok', default=True),
        ])
    process = StateAction('account_payment.act_payment_group_form')

    def _group_payment_key(self, payment):
        return (('journal', payment.journal.id), ('kind', payment.kind))

    def _new_group(self, values):
        pool = Pool()
        Group = pool.get('account.payment.group')
        return Group(**values)

    def do_process(self, action):
        pool = Pool()
        Payment = pool.get('account.payment')
        Warning = pool.get('res.user.warning')
        payments = Payment.browse(Transaction().context['active_ids'])

        for payment in payments:
            if payment.line and payment.line.payment_amount < 0:
                if Warning.check(str(payment)):
                    raise OverpayWarning(
                        str(payment),
                        gettext('account_payment.msg_payment_overpay',
                                payment=payment.rec_name,
                                line=payment.line.rec_name))

        groups = []
        payments = sorted(payments, key=self._group_payment_key)
        for key, grouped_payments in groupby(payments,
                                             key=self._group_payment_key):

            def group():
                group = self._new_group(dict(key))
                group.save()
                groups.append(group)
                return group

            Payment.process(list(grouped_payments), group)

        return action, {
            'res_id': [g.id for g in groups],
        }

    def default_start(self, name):
        return {}
コード例 #22
0
ファイル: wizards.py プロジェクト: beezzy1984/healthjm
class PartyMasterSearchWizard(Wizard):
    'Party Master Search'
    __name__ = 'party.party.mastersearch.wizard'
    start = StateView(
        'party.party.mastersearch.start',
        'health_jamaica_sync.party_master_search_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Find', 'performsearch', 'tryton-search', default=True),
        ])
    search_result = StateView(
        'party.party.remote', 'health_jamaica_sync.party_master_search_tree', [
            Button('New Search', 'start', 'tryton-search', default=True),
            Button('Close', 'end', 'tryton-cancel'),
        ])
    performsearch = StateAction('health_jamaica_sync.remote_party_tree')

    def transition_performsearch(self):
        return 'search_result'

    def do_performsearch(self, action):
        pass
コード例 #23
0
class LabDeviceRelateAnalysis(Wizard):
    'Relate Analysis to Device'
    __name__ = 'lims.lab.device.relate_analysis'

    start = StateView('lims.lab.device.relate_analysis.start',
        'lims.lab_device_relate_analysis_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Relate', 'relate', 'tryton-ok', default=True),
            ])
    relate = StateTransition()

    def default_start(self, fields):
        Device = Pool().get('lims.lab.device')

        device = Device(Transaction().context['active_id'])
        default = {
            'laboratory_domain': [l.laboratory.id
                for l in device.laboratories],
            }
        return default

    def transition_relate(self):
        AnalysisDevice = Pool().get('lims.analysis.device')

        device_id = Transaction().context['active_id']
        laboratory_id = self.start.laboratory.id

        to_create = []
        for a in self.start.analysis:
            if AnalysisDevice.search([
                    ('analysis', '=', a.id),
                    ('laboratory', '=', laboratory_id),
                    ('device', '=', device_id),
                    ]):
                continue

            by_default = True
            if (AnalysisDevice.search_count([
                    ('analysis', '=', a.id),
                    ('laboratory', '=', laboratory_id),
                    ('by_default', '=', True),
                    ]) > 0):
                by_default = False
            to_create.append({
                'analysis': a.id,
                'laboratory': laboratory_id,
                'device': device_id,
                'by_default': by_default,
                })

        if to_create:
            AnalysisDevice.create(to_create)
        return 'end'
コード例 #24
0
ファイル: invoice.py プロジェクト: geneos/policoop
class PayInvoice(Wizard):
    'Pay Invoice'
    __name__ = 'account.invoice.pay'

    start = StateView('account.voucher',
                      'account_voucher_ar.account_voucher_form', [
                          Button('Close', 'end', 'tryton-ok', default=True),
                      ])

    def default_start(self, fields):
        pool = Pool()
        Invoice = pool.get('account.invoice')
        Date = pool.get('ir.date')

        default = {
            'lines': [],
        }

        invoice = Invoice(Transaction().context.get('active_id'))
        default['date'] = Date.today()
        default['party'] = invoice.party.id
        default['currency'] = invoice.currency.id
        default['pay_invoice'] = invoice.id

        if invoice.type == 'in':
            default['voucher_type'] = 'payment'
            line_type = 'cr'
            name = invoice.reference
        elif invoice.type == 'out':
            default['voucher_type'] = 'receipt'
            line_type = 'dr'
            name = invoice.number

        for line in invoice.lines_to_pay:
            if line_type == 'cr':
                amount = line.credit
            else:
                amount = line.debit
            amount_residual = abs(line.amount_residual)

            lines = {
                'name': name,
                'account': invoice.account.id,
                'amount': abs(line.amount),
                'amount_original': amount,
                'amount_unreconciled': amount_residual,
                'line_type': line_type,
                'move_line': line.id,
                'date': invoice.invoice_date,
            }
            default['lines'].append(lines)

        return default
コード例 #25
0
class UpdateMagentoCatalog(Wizard):
    '''
    Update Catalog

    This is a wizard to update already imported products
    '''
    __name__ = 'magento.update_catalog'

    start = StateView(
        'magento.update_catalog.start',
        'magento.magento_update_catalog_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Continue', 'update_', 'tryton-ok', default=True),
        ])
    update_ = StateAction('product.act_template_form')

    def do_update_(self, action):
        """Handles the transition"""

        Channel = Pool().get('sale.channel')

        channel = Channel(Transaction().context.get('active_id'))
        channel.validate_magento_channel()

        product_template_ids = self.update_products(channel)

        action['pyson_domain'] = PYSONEncoder().encode([
            ('id', 'in', product_template_ids)
        ])
        return action, {}

    def transition_import_(self):
        return 'end'

    def update_products(self, channel):
        """
        Updates products for current magento_channel

        :param channel: Browse record of channel
        :return: List of product IDs
        """
        ChannelListing = Pool().get('product.product.channel_listing')

        products = []
        channel_listings = ChannelListing.search([
            ('channel', '=', self),
            ('state', '=', 'active'),
        ])
        with Transaction().set_context({'current_channel': channel.id}):
            for listing in channel_listings:
                products.append(listing.product.update_from_magento())

        return map(int, products)
コード例 #26
0
ファイル: user.py プロジェクト: zarumaru/trytond
class UserConfig(Wizard):
    'Configure users'
    __name__ = 'res.user.config'

    start = StateView('res.user.config.start',
                      'res.user_config_start_view_form', [
                          Button('Cancel', 'end', 'tryton-cancel'),
                          Button('OK', 'user', 'tryton-ok', default=True),
                      ])
    user = StateView('res.user', 'res.user_view_form', [
        Button('End', 'end', 'tryton-cancel'),
        Button('Add', 'add', 'tryton-ok'),
    ])
    add = StateTransition()

    def transition_add(self):
        pool = Pool()
        User = pool.get('res.user')
        self.user.save()
        self.user = User()
        return 'user'
コード例 #27
0
class CreateLabTestOrder(Wizard):
    'Create Lab Test Report'
    __name__ = 'gnuhealth.lab.test.create'

    start = StateView('gnuhealth.lab.test.create.init',
        'health_lab.view_lab_make_test', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Create Test Order', 'create_lab_test', 'tryton-ok', True),
            ])

    create_lab_test = StateTransition()

    def transition_create_lab_test(self):
        TestRequest = Pool().get('gnuhealth.patient.lab.test')
        Lab = Pool().get('gnuhealth.lab')

        tests_report_data = []

        tests = TestRequest.browse(Transaction().context.get('active_ids'))

        for lab_test_order in tests:

            test_cases = []
            test_report_data = {}

            if lab_test_order.state == 'ordered':
                self.raise_user_error(
                    "The Lab test order is already created")

            test_report_data['test'] = lab_test_order.name.id
            test_report_data['patient'] = lab_test_order.patient_id.id
            if lab_test_order.doctor_id:
                test_report_data['requestor'] = lab_test_order.doctor_id.id
            test_report_data['date_requested'] = lab_test_order.date

            for critearea in lab_test_order.name.critearea:
                test_cases.append(('create', [{
                        'name': critearea.name,
                        'sequence': critearea.sequence,
                        'lower_limit': critearea.lower_limit,
                        'upper_limit': critearea.upper_limit,
                        'normal_range': critearea.normal_range,
                        'units': critearea.units and critearea.units.id,
                    }]))
            test_report_data['critearea'] = test_cases

            tests_report_data.append(test_report_data)

        Lab.create(tests_report_data)
        TestRequest.write(tests, {'state': 'ordered'})

        return 'end'
コード例 #28
0
class InvoiceService(Wizard):
    'Draft Service'
    __name__ = 'service.invoice_service'
    start = StateView(
        'service.invoice_service.start',
        'nodux_technical_service_invoice.invoice_service_start_view_form', [
            Button('Exit', 'end', 'tryton-cancel'),
            Button('Facturar', 'invoice_', 'tryton-ok', default=True),
        ])
    invoice_ = StateAction('sale_pos.act_sale_form')

    def do_invoice_(self, action):
        pool = Pool()
        Service = pool.get('service.service')
        Sale = pool.get('sale.sale')
        Line = pool.get('sale.line')
        services = Service.browse(Transaction().context['active_ids'])

        origin = str(services)

        def in_group():
            pool = Pool()
            ModelData = pool.get('ir.model.data')
            User = pool.get('res.user')
            Group = pool.get('res.group')
            group = Group(
                ModelData.get_id('nodux_technical_service_invoice',
                                 'group_service_invoice'))
            transaction = Transaction()
            user_id = transaction.user
            if user_id == 0:
                user_id = transaction.context.get('user', user_id)
            if user_id == 0:
                return True
            user = User(user_id)
            return origin and group in user.groups

        if not in_group():
            self.raise_user_error("No esta autorizado a Facturar un Servicio")

        for service in services:
            sales = Sale.search([('ref_technical', '=', service.id)])
            if service.state in ['pending', 'review']:
                self.raise_user_error(
                    u'No puede facturar un servicio que se encuentra pendiente/revisión'
                )
            if sales:
                self.raise_user_error('Servicio ya ha sido facturado')

        service_invoices = Sale.invoice_service(services)
        data = {'id': [s.ref_technical.id for s in service_invoices]}
        return action, data
コード例 #29
0
class OpenEvaluations(Wizard):
    'Open Evaluations'
    __name__ = 'gnuhealth.evaluations.open'

    start = StateView('gnuhealth.evaluations.open.start',
                      'health_reporting.evaluations_open_start_view_form', [
                          Button('Cancel', 'end', 'tryton-cancel'),
                          Button('Open', 'select', 'tryton-ok', default=True),
                      ])
    select = StateTransition()
    open_doctor = StateAction('health_reporting.act_evaluations_doctor')
    open_specialty = StateAction('health_reporting.act_evaluations_specialty')
    open_sector = StateAction('health_reporting.act_evaluations_sector')

    def transition_select(self):
        return 'open_' + self.start.group_by

    def do_open_doctor(self, action):
        action['pyson_context'] = PYSONEncoder().encode({
            'start_date':
            self.start.start_date,
            'end_date':
            self.start.end_date,
        })
        return action, {}

    def do_open_specialty(self, action):
        action['pyson_context'] = PYSONEncoder().encode({
            'start_date':
            self.start.start_date,
            'end_date':
            self.start.end_date,
        })
        return action, {}

    def do_open_sector(self, action):
        action['pyson_context'] = PYSONEncoder().encode({
            'start_date':
            self.start.start_date,
            'end_date':
            self.start.end_date,
        })
        return action, {}

    def transition_open_doctor(self):
        return 'end'

    def transition_open_specialty(self):
        return 'end'

    def transition_open_sector(self):
        return 'end'
コード例 #30
0
ファイル: stock.py プロジェクト: tryton/stock_assign_manual
class ShipmentAssignManual(Wizard):
    "Manual Assign Shipment"
    __name__ = 'stock.shipment.assign.manual'
    start_state = 'next_'
    next_ = StateTransition()
    show = StateView('stock.shipment.assign.manual.show',
        'stock_assign_manual.shipment_assign_manual_show_view_form', [
            Button("Cancel", 'end', 'tryton-cancel'),
            Button("Skip", 'skip', 'tryton-forward', validate=False),
            Button("Assign", 'assign', 'tryton-ok', default=True),
            ])
    skip = StateTransition()
    assign = StateTransition()

    def transition_next_(self):

        def next_move():
            for move in self.record.assign_moves:
                if move.state == 'draft' and move not in self.show.skipped:
                    self.show.move = move
                    return move

        if getattr(self.show, 'skipped', None) is None:
            self.show.skipped = []

        if not next_move():
            if all(m.state == 'assigned' for m in self.record.assign_moves):
                self.model.assign([self.record])
            return 'end'
        return 'show'

    def default_show(self, fields):
        defaults = {}
        if 'skipped' in fields:
            defaults['skipped'] = [m.id for m in self.show.skipped]
        if 'move' in fields:
            defaults['move'] = self.show.move.id
        if 'unit' in fields:
            defaults['unit'] = self.show.move.uom.id
        if 'move_quantity' in fields:
            defaults['move_quantity'] = self.show.move.quantity
        return defaults

    def transition_skip(self):
        moves = list(self.show.skipped)
        moves.append(self.show.move)
        self.show.skipped = moves
        return 'next_'

    def transition_assign(self):
        self.show.assign()
        return 'next_'