示例#1
0
    def nfe_export(self):

        for inv in self:

            validate_nfe_configuration(inv.company_id)

            nfe_obj = self._get_nfe_factory(inv.nfe_version)

            # nfe_obj = NFe310()
            nfes = nfe_obj.get_xml(self.env.cr, self.env.uid, self.ids,
                                   int(inv.company_id.nfe_environment),
                                   self.env.context)

            for nfe in nfes:
                # erro = nfe_obj.validation(nfe['nfe'])
                erro = XMLValidator.validation(nfe['nfe'], nfe_obj)
                nfe_key = nfe['key'][3:]
                if erro:
                    raise RedirectWarning(
                        erro, _(u'Erro na validaço da NFe!'))

                inv.write({'nfe_access_key': nfe_key})
                save_dir = os.path.join(
                    monta_caminho_nfe(
                        inv.company_id,
                        chave_nfe=nfe_key) +
                    'tmp/')
                nfe_file = nfe['nfe'].encode('utf8')

                file_path = save_dir + nfe_key + '-nfe.xml'
                try:
                    if not os.path.exists(save_dir):
                        os.makedirs(save_dir)
                    f = open(file_path, 'w')
                except IOError:
                    raise RedirectWarning(
                        _(u'Erro!'), _(u"""Não foi possível salvar o arquivo
                            em disco, verifique as permissões de escrita
                            e o caminho da pasta"""))
                else:
                    f.write(nfe_file)
                    f.close()

                    event_obj = self.env['l10n_br_account.document_event']
                    event_obj.create({
                        'type': '0',
                        'company_id': inv.company_id.id,
                        'origin': '[NF-E]' + inv.internal_number,
                        'file_sent': file_path,
                        'create_date': datetime.datetime.now(),
                        'state': 'draft',
                        'document_event_ids': inv.id
                    })
                    inv.write({'state': 'sefaz_export'})
    def _gather_invoices_init(self):
        if self.company_id.country_id.code not in ('be', 'BE'):
            raise UserError(
                _("The Belgian Intrastat Declaration requires "
                  "the Company's Country to be equal to 'Belgium'."))

        module = __name__.split('addons.')[1].split('.')[0]

        # Special commodity codes
        # Current version implements only regular credit notes
        special_code = '99600000'
        hs_code = self.env['hs.code'].search(
            [('local_code', '=', special_code)])
        if not hs_code:
            action = self.env.ref(
                '%s.intrastat_installer_action' % module)
            msg = _(
                "Intrastat Code '%s' not found. "
                "\nYou can update your codes "
                "via the Intrastat Configuration Wizard."
                ) % special_code
            raise RedirectWarning(
                msg, action.id,
                _("Go to the Intrastat Configuration Wizard."))
        self._credit_note_code = hs_code[0]

        self._transaction_2 = self.env.ref(
            '%s.intrastat_transaction_2' % module)
示例#3
0
    def post_entries(self):

        #check state draft more than one
        check_state_draft = self.env['pabi.asset.depre.batch'].search([('state', '=', 'draft')])
        count_state_draft = len(check_state_draft.ids)
        if(count_state_draft>=2):
            raise UserError(
            _('Please check the Asset Depre. Batch menu, don\'t list the Draft state more than one!!'))

        self.ensure_one()
        if self._context.get('job_uuid', False):  # Called from @job
            return self.action_post_entries()
        # Enqueue
        if self.async_process:
            if self.job_id:
                message = _('Post Asset Depre. Batch')
                action = self.env.ref('pabi_utils.action_my_queue_job')
                raise RedirectWarning(message, action.id, _('Go to My Jobs'))
            session = ConnectorSession(self._cr, self._uid, self._context)
            description = '%s - Post Asset Depre. Batch' % self.name
            uuid = action_post_asset_depre_batch.delay(
                session, self._name, self.id, description=description)
            job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
            # Process Name
            job.process_id = self.env.ref('pabi_async_process.'
                                          'post_asset_depre_batch')
        else:
            return self.action_post_entries()
示例#4
0
    def _check_queue(self, task_name, desc=False, type='always'):
        """ Checking Type
        'never' : No checking on task, simply show the RedirectWarning to myJob
            - no check in any case
        'always' : Check any duplicated task (regardless of who starts it)
            - for document with document id
        'mytask' : Check duplicate task on the same user only
            - for reports
        """
        if type and type not in ['never', 'always', 'mytask']:
            raise ValidationError(_('Wrong job checking type!'))

        if type == 'never':
            jobs = self._get_running_jobs(task_name, type)
            self._cr.commit()
            uuid = jobs[0].uuid
        elif type in ['always', 'mytask']:
            jobs = self._get_running_jobs(task_name, type)
            if not jobs:
                raise ValidationError(_('Something wrong, job not created!'))
            if len(jobs) == 1:  # 1 Job ok, we can commit. Else, not create.
                self._cr.commit()
            print jobs
            uuid = jobs[0].uuid
        # Show RedirectWarning Message
        message = False
        if desc:
            message = _('This action is enqueued -- %s') % desc
        else:
            message = _('This action is enqueued')
        if uuid:
            message += '\nUUID: %s' % uuid
        action = self.env.ref('pabi_utils.action_my_queue_job')
        raise RedirectWarning(message, action.id, _('Go to My Jobs'))
示例#5
0
 def _getAnalyticJournal(self):
     if self.env.context is None:
         self.env.context = {}
     if not self.officer:
         emp_obj = self.env['hr.employee']
         if self.env.context.get('employee_id'):
             emp = emp_obj.search([('id', '=', context.get('employee_id'))])
         else:
             emp = emp_obj.search(
                 [('user_id', '=', self.env.context.get('user_id')
                   or self.env.uid)],
                 limit=1)
     else:
         emp = self.employee_id
     if not emp:
         model, action_id = self.env['ir.model.data'].get_object_reference(
             'hr', 'open_view_employee_list_my')
         msg = _(
             "Employee is not created for this user. Please create one from configuration panel."
         )
         raise RedirectWarning(msg, action_id,
                               _('Go to the configuration panel'))
     if emp.journal_id:
         return emp.journal_id.id
     else:
         raise Warning(
             _('No analytic journal defined for \'%s\'.\n'
               'You should assign an analytic journal on the employee form.'
               ) % (emp.name))
def _onchange_partner_id(self):
    account_id = False
    payment_term_id = False
    fiscal_position = False
    bank_id = False
    p = self.partner_id
    company_id = self.company_id.id
    type = self.type
    if p:
        partner_id = p.id
        rec_account = p.property_account_receivable_id
        pay_account = p.property_account_payable_id
        if company_id:
            if p.property_account_receivable_id.company_id and \
                    p.property_account_receivable_id.company_id.id != company_id and \
                    p.property_account_payable_id.company_id and \
                    p.property_account_payable_id.company_id.id != company_id:
                prop = self.env['ir.property']
                rec_dom = [('name', '=', 'property_account_receivable_id'),
                           ('company_id', '=', company_id)]
                pay_dom = [('name', '=', 'property_account_payable_id'),
                           ('company_id', '=', company_id)]
                res_dom = [('res_id', '=', 'res.partner,%s' % partner_id)]
                no_res_dom = [('res_id', '=', False)]
                rec_prop = prop.search(rec_dom +
                                       res_dom) or prop.search(rec_dom +
                                                               no_res_dom)
                pay_prop = prop.search(pay_dom +
                                       res_dom) or prop.search(pay_dom +
                                                               no_res_dom)
                rec_account = rec_prop.get_by_record(rec_prop)
                pay_account = pay_prop.get_by_record(pay_prop)
                if not rec_account and not pay_account:
                    action = self.env.ref('account.action_account_config')
                    msg = _(
                        'Cannot find a chart of accounts for this company, You should configure it. \nPlease go to Account Configuration.'
                    )
                    raise RedirectWarning(msg, action.id,
                                          _('Go to the configuration panel'))

        if type in ('out_invoice', 'out_refund'):
            account_id = rec_account.id
            payment_term_id = p.property_payment_term_id.id
        else:
            account_id = pay_account.id
            payment_term_id = p.property_supplier_payment_term_id.id
        fiscal_position = p.property_account_position_id.id
        bank_id = p.bank_ids and p.bank_ids.ids[0] or False
    self.account_id = account_id
    self.payment_term_id = payment_term_id
    self.fiscal_position_id = fiscal_position

    if type in ('in_invoice', 'in_refund'):
        self.partner_bank_id = bank_id
    def action_draft_done(self):
        if len(self.ids) == 1:
            record = self.browse(self.id)
            wf_service = netsvc.LocalService('workflow')
            wf_service.trg_validate('account.invoice', record.invoice_id.id,
                                    'invoice_cancel')

            self.write({'state': 'done'})
        else:
            raise RedirectWarning(
                _(u'Erro!'),
                _(u'Você pode cancelar '
                  u'apenas uma fatura por vez.'))

        return True
def mount_path_nfe(company, document='nfe'):
    db_name = company._cr.dbname
    cnpj = punctuation_rm(company.cnpj_cpf)

    filestore = config.filestore(db_name)
    nfe_path = '/'.join([filestore, 'PySPED', document, cnpj])
    if not os.path.exists(nfe_path):
        try:
            os.makedirs(nfe_path)
        except OSError:
            raise RedirectWarning(
                _(u'Erro!'),
                _(u"""Verifique as permissões de escrita
                    e o caminho da pasta"""))
    return nfe_path
示例#9
0
 def action_carry_over_background(self):
     if self._context.get('button_carry_over_async_process', False):
         self.ensure_one()
         self.name = '{:03d}'.format(self.id)
         if self._context.get('job_uuid', False):  # Called from @job
             return self.action_done()
         if self.button_carry_over_job_id:
             message = ('Carry Over')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, ('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Commitment Carry Over' % (self.doctype)
         uuid = action_done_async_process.delay(
             session, self._name, self.id, description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
     else:
         return self.action_done()
示例#10
0
 def action_done_background(self):
     if self._context.get('button_use_model_async_process', False):
         self.ensure_one()
         if self._context.get('job_uuid', False):  # Called from @job
             return self.action_done()
         if self.button_use_model_job_id:
             message = _('Use Model')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Use Model' % (self.special_type or self.name)
         uuid = action_done_async_process.delay(
             session, self._name, self.id, description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         job.process_id = 8
     else:
         return self.action_done()
示例#11
0
 def action_done_background(self):
     self.ensure_one()
     if self._context.get('job_uuid', False):  # Called from @job
         return self.action_done()
     if self.queue_job_id:
         message = ('Remove Asset')
         action = self.env.ref('pabi_utils.action_my_queue_job')
         raise RedirectWarning(message, action.id, ('Go to My Jobs'))
     session = ConnectorSession(self._cr, self._uid, self._context)
     description = '%s - Commitment Asset Removal' % (self.name)
     uuid = action_done_async_process.delay(session,
                                            self._name,
                                            self.id,
                                            description=description)
     job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
     self.queue_job_id = job.id
     self.queue_job_uuid = uuid
示例#12
0
 def action_done_backgruond(self):
     if self._context.get('transfer_async_process', False):
         self.ensure_one()
         if self._context.get('job_uuid', False):  # Called from @job
             return self.action_done()
         if self.transfer_job_id:
             message = _('Confirm Transfer')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Confirm Transfer' % self.name
         uuid = action_done_async_process.delay(session,
                                                self._name,
                                                self.id,
                                                description=description)
         self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
     else:
         return self.action_done()
示例#13
0
    def default_get(self, fields_list):
        product_obj = self.env['product.template']
        product_ids = product_obj.browse(self._context.get("active_ids"))

        if all(not product.image for product in product_ids):
            raise RedirectWarning(_('No any product has image to export'))
        for product in product_ids:
            if not product.image:
                product_ids -= product

        rows = len(product_ids) / 3

        html_str = "<table style='width:100%'>"
        cnt = 0
        for row in range(0, rows + 1):
            html_str = html_str + "<tr>"
            for col in range(0, 3):
                if len(product_ids.ids) == cnt:
                    break
                product_image = '<img src="data:image/*;base64,%s" width="150"/>' % (
                    str(product_ids[cnt].image))
                html_str += """<td>%s</td>
                               <td nowrap>
                                    Name: %s<br>
                                    Price: %.2f
                               </td>""" % \
                            (product_image, product_ids[cnt].name,
                             product_ids[cnt].list_price)
                cnt += 1
            html_str = html_str + "</tr>"
        html_str = html_str + "</table>"
        Html_file = open("product_image.html", "w")
        Html_file.write(html_str)
        Html_file.close()

        image = imgkit.from_file("product_image.html", 'product_image.png')
        res = super(ExportProductImage, self).default_get(fields_list)
        stream = cStringIO.StringIO(file("product_image.png").read())
        res.update({'image_download': base64.encodestring(stream.getvalue())})

        os.remove("product_image.html")
        os.remove("product_image.png")
        return res
示例#14
0
 def action_remove(self):
     bank_transfer_obj = self.env['dym.bank.transfer']
     bank_transfer = bank_transfer_obj.search([('bank_trf_advice_id', '=',
                                                self.advice_id.id),
                                               ('state', '!=', 'cancel')])
     if bank_transfer:
         for btr in bank_transfer:
             if btr.state != 'draft':
                 raise RedirectWarning(
                     _('Maaf item tidak dapat di delete karena BTR sudah di proses, \n \
                     mohon hubungi PIC terkait untuk mengubah BTR kembali ke draft.'
                       ))
     for rec in self:
         if bank_transfer:
             bank_transfer.line_ids1.amount -= rec.amount
             bank_transfer.amount = bank_transfer.line_ids1.amount
         advice_id = rec.advice_id
         rec.advice_id = False
         rec.transfer_id = False
     return {'type': 'ir.actions.client', 'tag': 'reload'}
示例#15
0
 def action_invoice_create(self):
     self.ensure_one()
     if self._context.get('job_uuid', False):  # Called from @job
         return super(PurchaseOrder, self).action_invoice_create()
     # Enqueue
     if self.use_invoice_plan and self.async_process:
         if self.job_id:
             message = _('Creating Invoice(s)')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Creating Invoice(s)' % self.name
         uuid = action_purchase_create_invoice.delay(
             session, self._name, self.id, description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         # Process Name
         job.process_id = self.env.ref('pabi_async_process.'
                                       'purchase_invoice_plan')
     else:
         return super(PurchaseOrder, self).action_invoice_create()
 def action_done_background(self):
     if self._context.get('button_use_model_async_process', False):
         self.ensure_one()
         if self._context.get('job_uuid', False):  # Called from @job
             return self.compute_prev_fy_performance()
         if self.job_id:
             message = _('Budget Plan Project')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = 'Budget Plan Project - %s' % (self.name
                                                     or self._name)
         uuid = action_done_async_process.delay(session,
                                                self._name,
                                                self.id,
                                                description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         job.process_id = 7
     else:
         return self.compute_prev_fy_performance()
示例#17
0
文件: sale.py 项目: pabi2/pb2_addons
 def action_button_confirm(self):
     if self._context.get('pos_async_process', False):
         self.ensure_one()
         if self._context.get('job_uuid', False):  # Called from @job
             return super(SaleOrder, self).action_button_confirm()
         if self.pos_job_id:
             message = _('Confirm POS Order')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Confirm POS Order' % self.name
         uuid = action_confirm_pos_order.delay(session,
                                               self._name,
                                               self.id,
                                               description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         # Process Name
         job.process_id = self.env.ref('pabi_async_process.'
                                       'confirm_pos_order')
     else:
         return super(SaleOrder, self).action_button_confirm()
示例#18
0
 def split_entries(self):
     """ Inherit existing function, and test if it async_process is True """
     self.ensure_one()
     if self._context.get('job_uuid', False):  # Called from @job
         return super(PabiImportJournalEntries, self).split_entries()
     # Enqueue
     if self.async_process:
         if self.job_id:  # Job already started, check at My Jobs menu
             message = _('Import JE - Split Entries')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Import JE - Split Entries(s)' % self.name
         uuid = action_import_je_split_entries.delay(
             session, self._name, self.id, description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         # Process Name
         job.process_id = self.env.ref('sample_pabi_async_process.'
                                       'import_je_split_entries')
     else:
         return super(PabiImportJournalEntries, self).split_entries()
示例#19
0
 def action_done_background(self):
     if self._context.get('button_validate_async_process', False):
         self.ensure_one()
         if self._context.get('job_uuid', False):  # Called from @job
             return self.action_done()
         if self.button_validate_job_id:
             message = _('Confirm Post')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Confirm Post' % (self.ref or self.name)
         uuid = action_done_async_process.delay(session,
                                                self._name,
                                                self.id,
                                                description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         # Process Name
         # job.process_id = self.env.ref('pabi_async_process.'
         #                              'confirm_pos_order')
     else:
         return self.action_done()
示例#20
0
 def compute_depreciation_board(self):
     self.ensure_one()
     if self._context.get('job_uuid', False):  # Called from @job
         return super(AccountAsset, self).compute_depreciation_board()
     # Enqueue
     if self.async_process:
         if self.job_id:
             message = _('Compute asset depreciation job is still running!')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s  - Asset Depreciation Job' % self.name
         uuid = action_compute_depreciation_board.delay(
             session, self._name, self.id, description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         # Process Name
         job.process_id = self.env.ref('pabi_async_process.'
                                       'asset_compute_depreciation_board')
         return True
     else:
         return super(AccountAsset, self).compute_depreciation_board()
    def action_draft_done(self):
        try:
            processo = self.send_request_to_sefaz()
            values = {
                'message': processo.resposta.infInut.xMotivo.valor,
            }

            if processo.resposta.infInut.cStat.valor == '102':
                values['state'] = 'done'
                values['status'] = '102'
                self.write(values)
                # context['caminho'] = processo.arquivos[0]['arquivo']
                self.attach_file_event(None, 'inu', 'xml')
            else:
                values['state'] = 'not_authorized'
                values['status'] = processo.resposta.infInut.cStat.valor
                self.write(values)

        except Exception as e:
            raise RedirectWarning(_(u'Erro!'), e.message)
        return True
示例#22
0
    def pay_loan(self):
        if self.state == "draft":
            raise ValidationError(
                _("Can not generate the payment of a loan in draft state!"))

        account_id = self.employee_id.company_id.loan_account_id
        if not account_id:
            action = self.env.ref("base.action_res_company_form")
            raise RedirectWarning(
                _("Please config your Loan's Account!."),
                action.id,
                _("Go to the company configuration"),
            )
        amount = self.amount
        payment_form = self.env.ref("account.view_account_payment_form", False)
        ctx = {
            "default_model": "hr.payslip.loans",
            "default_secuencial": self.number,
            "default_partner_id": self.employee_id.address_home_id.id,
            "default_payment_type": "outbound",
            "default_res_id": self.id,
            "default_amount": amount,
            "default_name": self.name,
            "default_prepayment": True,
            "default_contrapartida_id": int(account_id),
            "default_communication": self.number,
            "default_payment_reference": self.number,
            "default_loan_id": self.id,
        }
        return {
            "name": _("Payment Loan"),
            "type": "ir.actions.act_window",
            "view_type": "form",
            "view_mode": "form",
            "res_model": "account.payment",
            "views": [(payment_form.id, "form")],
            "view_id": payment_form.id,
            "target": "new",
            "context": ctx,
        }
示例#23
0
    def onchange_fiscal_document_id(self):
        serie = False
        if self.issuer == '0':
            if self.fiscal_type == 'product':
                series = [doc_serie for doc_serie in
                          self.company_id.document_serie_product_ids if
                          doc_serie.fiscal_document_id.id ==
                          self.fiscal_document_id.id and doc_serie.active]
                if series:
                    serie = series[0]
            else:
                serie = self.company_id.document_serie_service_id

            if not serie:
                action = self.env.ref(
                    'l10n_br_account.'
                    'action_l10n_br_account_document_serie_form')
                msg = _(u'Você deve ser uma série de documento fiscal'
                        u'para este documento fiscal.')
                raise RedirectWarning(
                    msg, action.id, _(u'Criar uma nova série'))
            self.document_serie_id = serie
示例#24
0
 def default_get(self, fields):
     res_model = self._context.get('active_model', False)
     template_dom = [('res_model', '=', res_model),
                     ('parent_id', '!=', False)]
     template_fname = self._context.get('template_fname', False)
     if template_fname:  # Specific template
         template_dom.append(('datas_fname', '=', template_fname))
     templates = self.env['ir.attachment'].search(template_dom)
     if not templates:
         raise ValidationError(_('No template found!'))
     defaults = super(XLSXImport, self).default_get(fields)
     for template in templates:
         if not template.datas:
             act = self.env.ref('document.action_document_directory_tree')
             raise RedirectWarning(
                 _('File "%s" not found in template, %s.') %
                 (template.datas_fname, template.name), act.id,
                 _('Set Templates'))
     defaults['template_id'] = len(templates) == 1 and template.id or False
     defaults['res_model'] = res_model
     defaults['domain_template_ids'] = templates.ids
     return defaults
示例#25
0
 def do_transfer(self):
     self.ensure_one()
     if self._context.get('job_uuid', False):  # Called from @job
         return super(StockPicking, self).do_transfer()
     # Enqueue
     if self.async_process:
         if self.job_id:
             message = _('Do Transfer(s)')
             action = self.env.ref('pabi_utils.action_my_queue_job')
             raise RedirectWarning(message, action.id, _('Go to My Jobs'))
         session = ConnectorSession(self._cr, self._uid, self._context)
         description = '%s - Do Transfer(s)' % self.name
         uuid = action_do_transfer.delay(session,
                                         self._name,
                                         self.id,
                                         description=description)
         job = self.env['queue.job'].search([('uuid', '=', uuid)], limit=1)
         # Process Name
         job.process_id = self.env.ref('pabi_async_process.'
                                       'stock_transfer')
     else:
         return super(StockPicking, self).do_transfer()
示例#26
0
    def pay_loan(self):
        if self.state == 'draft':
            raise ValidationError(
                _("Can not generate the payment of a loan in draft state!"))

        account_id = self.employee_id.company_id.loan_account_id
        if not account_id:
            action = self.env.ref('base.action_res_company_form')
            raise RedirectWarning(_("Please config your Loan's Account!."),
                                  action.id,
                                  _('Go to the company configuration'))
        amount = self.amount
        payment_form = self.env.ref('account.view_account_payment_form', False)
        ctx = {
            'default_model': 'hr.payslip.loans',
            'default_secuencial': self.number,
            'default_partner_id': self.employee_id.address_home_id.id,
            'default_payment_type': 'outbound',
            'default_res_id': self.id,
            'default_amount': amount,
            'default_name': self.name,
            'default_prepayment': True,
            'default_contrapartida_id': int(account_id),
            'default_communication': self.number,
            'default_payment_reference': self.number,
            'default_loan_id': self.id,
        }
        return {
            'name': _('Payment Loan'),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'account.payment',
            'views': [(payment_form.id, 'form')],
            'view_id': payment_form.id,
            'target': 'new',
            'context': ctx,
        }
示例#27
0
    def onchange_company_id(self, company_id, part_id, type, invoice_line,
                            currency_id):
        res = super(AccountInvoice,
                    self).onchange_company_id(company_id, part_id, type,
                                              invoice_line, currency_id)
        values = {}

        if company_id and type:
            journal_type = TYPE2JOURNAL[type]
            journal_code = self._context.get('journal_code')
            domain = [('type', '=', journal_type),
                      ('company_id', '=', company_id)]
            if journal_type == 'sale':
                if journal_code == 'Nota':
                    domain.append(('code', '=', 'Nota'))
                else:
                    domain.append(('code', '!=', 'Nota'))
            journals = self.env['account.journal'].search(domain)
            if journals:
                values['journal_id'] = journals[0].id
            journal_defaults = self.env['ir.values'].get_defaults_dict(
                'account.invoice', 'type=%s' % type)
            if 'journal_id' in journal_defaults:
                values['journal_id'] = journal_defaults['journal_id']
            if not values.get('journal_id'):
                field_desc = journals.fields_get(['type'])
                type_label = next(
                    t for t, label in field_desc['type']['selection']
                    if t == journal_type)
                action = self.env.ref('account.action_account_journal_form')
                msg = _(
                    'Cannot find any account journal of type "%s" for this company, You should create one.\n Please go to Journal Configuration'
                ) % type_label
                raise RedirectWarning(msg, action.id,
                                      _('Go to the configuration panel'))
            domain = {'journal_id': [('id', 'in', journals.ids)]}
            res.update({'domain': domain, 'value': values})
        return res
    def _prepare_stay_line(self, stay, date):
        stay_vals = {}
        eating_map = {
            'morning': {
                'arrival': {'lunch_multi': 1, 'dinner_multi': 1},
                'departure': {'lunch_multi': 0, 'dinner_multi': 0}
                },
            'afternoon': {
                'arrival': {'lunch_multi': 0, 'dinner_multi': 1},
                'departure': {'lunch_multi': 1, 'dinner_multi': 0}
                },
            'evening': {
                'arrival': {'lunch_multi': 0, 'dinner_multi': 0},
                'departure': {'lunch_multi': 1, 'dinner_multi': 1}
                },
            }

        if date == stay.arrival_date:
            stay_vals = {
                'lunch_qty':
                stay.guest_qty * eating_map[stay.arrival_time]
                ['arrival']['lunch_multi'],
                'dinner_qty':
                stay.guest_qty * eating_map[stay.arrival_time]
                ['arrival']['dinner_multi'],
                'bed_night_qty': stay.guest_qty,
                }
        elif date == stay.departure_date:
            if stay.departure_time == 'morning':
                return {}
            stay_vals = {
                'lunch_qty':
                stay.guest_qty * eating_map[stay.departure_time]
                ['departure']['lunch_multi'],
                'dinner_qty':
                stay.guest_qty * eating_map[stay.departure_time]
                ['departure']['dinner_multi'],
                'bed_night_qty': 0,
                }
        else:
            stay_vals = {
                'lunch_qty': stay.guest_qty,
                'dinner_qty': stay.guest_qty,
                'bed_night_qty': stay.guest_qty,
                }
        if not stay.company_id.default_refectory_id:
            msg = _("Missing default refectory on the company '%s'.") % (
                stay.company_id.name)
            action = self.env.ref('base.action_res_company_form')
            raise RedirectWarning(
                msg, action.id, 'Go to the Company')
        stay_vals.update({
            'date': date,
            'stay_id': stay.id,
            'partner_id': stay.partner_id.id,
            'partner_name': stay.partner_name,
            'refectory_id': stay.company_id.default_refectory_id.id,
            'room_id': stay.room_id.id,
            'company_id': stay.company_id.id,
            })
        if stay.no_meals:
            stay_vals.update(
                {'lunch_qty': 0, 'dinner_qty': 0, 'refectory_id': False})
        return stay_vals
示例#29
0
    def onchange_company_id(self, company_id, part_id, type, invoice_line,
                            currency_id):  # noqa
        """
        TODO: add the missing context parameter
        when forward-porting in trunk so we can remove
        this hack!
        """
        self = self.with_context(self.env['res.users'].context_get())

        values = {}
        domain = {}

        if company_id and part_id and type:
            p = self.env['res.partner'].browse(part_id)
            if p.property_account_payable and p.property_account_receivable and p.property_account_payable.company_id.id != company_id and p.property_account_receivable.company_id.id != company_id:  # noqa
                prop = self.env['ir.property']
                rec_dom = [('name', '=', 'property_account_receivable'),
                           ('company_id', '=', company_id)]  # noqa
                pay_dom = [('name', '=', 'property_account_payable'),
                           ('company_id', '=', company_id)]  # noqa
                res_dom = [('res_id', '=', 'res.partner,%s' % part_id)]
                rec_prop = prop.search(rec_dom + res_dom) or prop.search(
                    rec_dom)  # noqa
                pay_prop = prop.search(pay_dom + res_dom) or prop.search(
                    pay_dom)  # noqa
                rec_account = rec_prop.get_by_record(rec_prop)
                pay_account = pay_prop.get_by_record(pay_prop)
                if not rec_account and not pay_account:
                    action = self.env.ref('account.action_account_config')
                    msg = _(
                        'Cannot find a chart of account for this company, You should configure it. \nPlease go to Account Configuration.'
                    )  # noqa
                    raise RedirectWaring(
                        msg, action.id,
                        _('Go to the configuration panel'))  # noqa

                if type in ('out_invoice', 'out_refund'):
                    acc_id = rec_account.id
                else:
                    acc_id = pay_account.id
                values = {'account_id': acc_id}

            if self:
                if company_id:
                    for line in self.invoice_line:
                        if not line.account_id:
                            continue
                        if line.account_id.company_id.id == company_id:
                            continue
                        accounts = self.env['account.account'].search([
                            ('name', '=', line.account_id.name),
                            ('company_id', '=', company_id)
                        ])  # noqa
                        if not accounts:
                            action = self.env.ref(
                                'account.action_account_config')  # noqa
                            msg = _(
                                'Cannot find a chart of accounts for this company, You should configure it. \nPlease go to Account Configuration.'
                            )  # noqa
                            raise RedirectWarning(
                                msg, action.id,
                                _('Go to the configuration panel'))  # noqa
                        line.write({'account_id': accounts[-1].id})
            else:
                for line_cmd in invoice_line or []:
                    if len(line_cmd) >= 3 and isinstance(line_cmd[2], dict):
                        line = self.env['account.account'].browse(
                            line_cmd[2]['account_id'])  # noqa
                        if line.company_id.id != company_id:
                            raise except_orm(
                                _('Configuration Error!'),
                                _("Invoice line account's company and invoice's company does not match."
                                  ))  # noqa

        if company_id and type:
            journal_type = TYPE2JOURNAL[type]
            journals = self.env['account.journal'].search([
                ('type', '=', journal_type), ('company_id', '=', company_id)
            ])  # noqa
            if journals:
                values['journal_id'] = journals[0].id
            journal_defaults = self.env['ir.values'].get_defaults_dict(
                'account.invoice', 'type=%s' % type)  # noqa
            if 'journal_id' in journal_defaults:
                values['journal_id'] = journal_defaults['journal_id']  # noqa
            if not values.get('journal_id'):
                field_desc = journals.fields_get(['type'])
                type_label = next(
                    t for t, label in field_desc['type']['selection']
                    if t == journal_type)  # noqa
                action = self.env.ref('account.action_account_journal_form')
                msg = _(
                    'Cannot find any account journal of type "%s" for this company, You should create one.\n Please go to Journal Configuration'
                ) % type_label  # noqa
                raise RedirectWarning(
                    msg, action.id, _('Go to the configuration panel'))  # noqa
            domain = {'journal_id': [('id', 'in', journals.ids)]}

        return {'value': values, 'domain': domain}
示例#30
0
 def _company_warning(self, msg):
     action = self.env.ref('base.action_res_company_form')
     raise RedirectWarning(msg, action.id,
                           _('Go to company configuration screen'))