Exemple #1
0
 def _onchange_partner_journal(self):
     """ This method is used when the invoice is created from the sale or subscription """
     expo_journals = ['FEERCEL', 'FEEWS', 'FEERCELP']
     for rec in self.filtered(
             lambda x: x.company_id.country_id == self.env.ref('base.ar')
             and x.journal_id.type == 'sale' and x.l10n_latam_use_documents
             and x.partner_id.l10n_ar_afip_responsibility_type_id):
         res_code = rec.partner_id.l10n_ar_afip_responsibility_type_id.code
         domain = [('company_id', '=', rec.company_id.id),
                   ('l10n_latam_use_documents', '=', True),
                   ('type', '=', 'sale')]
         journal = self.env['account.journal']
         msg = False
         if res_code in [
                 '9', '10'
         ] and rec.journal_id.l10n_ar_afip_pos_system not in expo_journals:
             # if partner is foregin and journal is not of expo, we try to change to expo journal
             journal = journal.search(
                 domain +
                 [('l10n_ar_afip_pos_system', 'in', expo_journals)],
                 limit=1)
             msg = _(
                 'You are trying to create an invoice for foreign partner but you don\'t have an exportation journal'
             )
         elif res_code not in [
                 '9', '10'
         ] and rec.journal_id.l10n_ar_afip_pos_system in expo_journals:
             # if partner is NOT foregin and journal is for expo, we try to change to local journal
             journal = journal.search(
                 domain +
                 [('l10n_ar_afip_pos_system', 'not in', expo_journals)],
                 limit=1)
             msg = _(
                 'You are trying to create an invoice for domestic partner but you don\'t have an domestic market journal'
             )
         if journal:
             rec.journal_id = journal.id
         elif msg:
             # Throw an error to user in order to proper configure the journal for the type of operation
             action = self.env.ref('account.action_account_journal_form')
             raise RedirectWarning(msg, action.id, _('Go to Journals'))
Exemple #2
0
    def _get_sample_invoice(self):
        """ Get a sample invoice or create one if it does not exist. """
        # use current user as partner
        partner = self.env.user.partner_id

        company_id = self.env.company.id
        # try to find an existing sample invoice
        sample_invoice = self.env['account.move'].search(
            [('company_id', '=', company_id),
             ('partner_id', '=', partner.id)], limit=1)

        if len(sample_invoice) == 0:
            # If there are no existing accounts or no journal, fail
            account = self.env.company.get_chart_of_accounts_or_fail()

            journal = self.env['account.journal'].search([('company_id', '=', company_id)], limit=1)
            if len(journal) == 0:
                action = self.env.ref('account.action_account_journal_form')
                msg = _("We cannot find any journal for this company. You should create one."
                        "\nPlease go to Configuration > Journals.")
                raise RedirectWarning(msg, action.id, _("Go to the journal configuration"))

            sample_invoice = self.env['account.move'].with_context(default_type='out_invoice', default_journal_id=journal.id).create({
                'invoice_payment_ref': _('Sample invoice'),
                'partner_id': partner.id,
                'invoice_line_ids': [
                    (0, 0, {
                        'name': _('Sample invoice line name'),
                        'account_id': account.id,
                        'quantity': 2,
                        'price_unit': 199.99,
                    }),
                    (0, 0, {
                        'name': _('Sample invoice line name 2'),
                        'account_id': account.id,
                        'quantity': 1,
                        'price_unit': 25.0,
                    }),
                ],
            })
        return sample_invoice
 def default_get(self, fields):
     res_model = self._context.get("active_model", False)
     res_id = self._context.get("active_id", False)
     template_domain = self._context.get("template_domain", [])
     templates = self.env["xlsx.template"].search(template_domain)
     if not templates:
         raise ValidationError(_("No template found"))
     defaults = super(ImportXLSXWizard, self).default_get(fields)
     for template in templates:
         if not template.datas:
             act = self.env.ref("excel_import_export.action_xlsx_template")
             raise RedirectWarning(
                 _('File "%s" not found in template, %s.') %
                 (template.fname, template.name),
                 act.id,
                 _("Set Templates"),
             )
     defaults["template_id"] = len(templates) == 1 and template.id or False
     defaults["res_id"] = res_id
     defaults["res_model"] = res_model
     return defaults
Exemple #4
0
 def _get_default_category_id(self):
     for ou_id in self.env.user.operating_unit_ids:
         category = self.env['product.category'].\
             search([], limit=1)
         if category:
             return category.id
         else:
             try:
                 self.env.ref('product.product_category_all',
                              raise_if_not_found=False).name
             except AccessError:
                 err_msg = _('You must define at least one product \
                     category within your Operating Unit in order to be \
                     able to create products.')
                 redir_msg = _('Go to Product Categories')
                 raise RedirectWarning(
                     err_msg,
                     self.env.ref(
                         'product.product_category_action_form').id,
                     redir_msg)
             return super()._get_default_category_id()
Exemple #5
0
    def _retrieve_currency(self, code):
        '''Search all currencies and find one that matches the code.

        :param code: The code of the currency.
        :returns:    A currency or an empty recordset if not found.
        '''
        currency = self.env['res.currency'].with_context(active_test=False).search([('name', '=', code.upper())], limit=1)
        if currency and not currency.active:
            error_msg = _('The currency (%s) of the document you are uploading is not active in this database.\n'
                          'Please activate it and update the currency rate if needed before trying again to import.',
                          currency.name)
            error_action = {
                'view_mode': 'form',
                'res_model': 'res.currency',
                'type': 'ir.actions.act_window',
                'target': 'new',
                'res_id': currency.id,
                'views': [[False, 'form']]
            }
            raise RedirectWarning(error_msg, error_action, _('Display the currency'))
        return currency
Exemple #6
0
 def action_replenish(self):
     try:
         self._procure_orderpoint_confirm(company_id=self.env.company)
     except UserError as e:
         if len(self) != 1:
             raise e
         raise RedirectWarning(e, {
             'name': self.product_id.display_name,
             'type': 'ir.actions.act_window',
             'res_model': 'product.product',
             'res_id': self.product_id.id,
             'views': [(self.env.ref('product.product_normal_form_view').id, 'form')],
             'context': {'form_view_initial_mode': 'edit'}
         }, _('Edit Product'))
     notification = False
     if len(self) == 1:
         notification = self._get_replenishment_order_notification()
     # Forced to call compute quantity because we don't have a link.
     self._compute_qty()
     self.filtered(lambda o: o.create_uid.id == SUPERUSER_ID and o.qty_to_order <= 0.0 and o.trigger == 'manual').unlink()
     return notification
Exemple #7
0
    def _onchange_partner_id(self):
        res = super(AccountInvoice, self)._onchange_partner_id()
        company_id = self.company_id.id
        domain = {}
        if self.type in ('in_invoice', 'out_refund') and \
                self.alternate_payer_id:
            bank_ids = self.alternate_payer_id.bank_ids.filtered(
                lambda b: b.company_id.id == company_id or not b.company_id)
            bank_id = bank_ids[0].id if bank_ids else False
            self.partner_bank_id = bank_id
            domain = {'partner_bank_id': [('id', 'in', bank_ids.ids)]}
        if domain:
            res['domain'] = domain
        if self.alternate_payer_id:
            account_id = False
            payment_term_id = False
            p = self.alternate_payer_id if not company_id else \
                self.alternate_payer_id.with_context(force_company=company_id)
            type = self.type
            if p:
                rec_account = p.property_account_receivable_id
                pay_account = p.property_account_payable_id
                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
            self.account_id = account_id
            self.payment_term_id = payment_term_id
        return res
Exemple #8
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,
        }
Exemple #9
0
 def _unlink_except_contains_entries(self):
     """
     If some tasks to unlink have some timesheets entries, these
     timesheets entries must be unlinked first.
     In this case, a warning message is displayed through a RedirectWarning
     and allows the user to see timesheets entries to unlink.
     """
     tasks_with_timesheets = self.filtered(lambda t: t.timesheet_ids)
     if tasks_with_timesheets:
         if len(tasks_with_timesheets) > 1:
             warning_msg = _(
                 "These tasks have some timesheet entries referencing them. Before removing these tasks, you have to remove these timesheet entries."
             )
         else:
             warning_msg = _(
                 "This task has some timesheet entries referencing it. Before removing this task, you have to remove these timesheet entries."
             )
         raise RedirectWarning(
             warning_msg,
             self.env.ref('hr_timesheet.timesheet_action_task').id,
             _('See timesheet entries'),
             {'active_ids': tasks_with_timesheets.ids})
 def _get_default_category_id(self):
     for ou_id in self.env.user.operating_unit_ids:
         _logger.info("%s" % (ou_id.name))
         category = self.env["product.category"].search([], limit=1)
         if category:
             return category.id
         else:
             try:
                 self.env.ref("product.product_category_all",
                              raise_if_not_found=False).name
             except AccessError:
                 err_msg = _("You must define at least one product \
                     category within your Operating Unit in order to be \
                     able to create products.")
                 redir_msg = _("Go to Product Categories")
                 raise RedirectWarning(
                     err_msg,
                     self.env.ref(
                         "product.product_category_action_form").id,
                     redir_msg,
                 )
             return super()._get_default_category_id()
Exemple #11
0
 def _compute_period(self):
     """
     Obtenemos el período contable dependiendo de la  fecha del documento
     :return:
     """
     date = self.date_invoice
     period = self.env['account.fiscal.year'].search([('name', '=',
                                                       date.year)])
     # Si no existe rederiguimos a crear un período contable
     if not period:
         err_msg = _(
             "Debes definir algún período contable para comenzar a transaccionar."
         )
         redir_msg = _("Ir a período contable")
         raise RedirectWarning(
             err_msg,
             self.env.ref('account.actions_account_fiscal_year').id,
             redir_msg)
     else:
         period_id = period.period_lines.filtered(
             lambda x: x.code == date.month)
         self.period_id = period_id.id
Exemple #12
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,
        }
Exemple #13
0
 def import_category(self):
     browse_node=self.env['amazon.browse.node.ept']
     root_node_ids=self._context.get('active_ids',[])
     instance_obj=self.env['amazon.instance.ept']
     records=browse_node.search([('id','in',root_node_ids),('parent_id','=',False)])
     
     if len(root_node_ids) != len(records.ids):
         raise Warning(_("You have selected the category which is not root category..."))              
     for node in records:
         country_id=node.country_id.id
         if not country_id:
             raise Warning(_("Browse node '%s' not have country")%(node.name)) 
         instance=instance_obj.search([('country_id','=',country_id)])
         if instance:
             if not instance.pro_advt_access_key or not instance.pro_advt_scrt_access_key or not instance.pro_advt_associate_tag:
                 action = self.env.ref('amazon_ept.action_amazon_config')
                 msg = _('You have not configure Product Advertising Account, You should configure it. \nPlease go to Amazon Configuration.')
                 raise RedirectWarning(msg, action.id, _('Go to the configuration panel'))            
         Instance=AmazonAPI(str(instance.pro_advt_access_key),str(instance.pro_advt_scrt_access_key),aws_associate_tag=str(instance.pro_advt_associate_tag),region=str(instance.country_id.amazon_marketplace_code or instance.country_id.code),MaxQPS=0.5,Timeout=10)
         ancestor=False
         results=[]
         try:
             results=Instance.browse_node_lookup(BrowseNodeId=int(node.ama_category_code))
         except Exception as e:
             raise Warning(str(e))
         if not results:
             continue
                          
         for result in results:
             if result.is_category_root:
                 ancestor=browse_node.check_ancestor_exist_or_not(result,node)
                 try:                                                                                             
                     for children in result.children:
                         parent=ancestor and ancestor.id or node.id
                         browse_node.check_children_exist_or_not(children, node, parent)
                 except Exception as e:
                     raise Warning(str(e))
     return True        
Exemple #14
0
 def finds(self, dt=None, exception=True, previous=False):
     """
         parameters: dt = Date, exception = 'True' or 'False'
         Check the public year configuration is available or not.
     """
     if not dt:
         dt = fields.date.context_today()
     args = [('date_start', '<=', dt), ('date_stop', '>=', dt)]
     company_id = self.env.context['company_id'] if self.env.context.get(
         'company_id') else self.env.user.company_id.id
     args.append(('company_id', '=', company_id))
     ids = self.search(args)
     if not ids and not previous:
         if exception:
             action_id = self.env.ref('hr_fiscal_year.action_public_year')
             msg = _(
                 'There is no period defined for this date: %s.\nPlease go to Configuration/Periods and configure a Year.'
             ) % dt
             raise RedirectWarning(msg, action_id.id,
                                   _('Go to the configuration panel'))
         else:
             return []
     return ids
Exemple #15
0
 def _get_default_category_id(self):
     if self._context.get('categ_id') or self._context.get(
             'default_categ_id'):
         return self._context.get('categ_id') or self._context.get(
             'default_categ_id')
     category = self.env.ref('product.product_category_all',
                             raise_if_not_found=False)
     if category and category.type == 'normal':
         return category.id
     # fallback if no category "All" exists, because yes, users do delete default data!
     category = self.env['product.category'].search(
         [('type', '=', 'normal')], limit=1)
     if category:
         return category.id
     else:
         err_msg = _(
             'You must define at least one product category (that is not a view) in order to be able to create products.'
         )
         redir_msg = _('Go to Internal Categories')
         raise RedirectWarning(
             err_msg,
             self.env.ref('product.product_category_action_form').id,
             redir_msg)
Exemple #16
0
    def check_booking_order(self,except_raise=False):
        team_leader_overlap = self._check_team_leader_book_overlap()        
        employees_overlap = self._check_employees_book_overlap()
        equipment_overlap = self._check_equipments_book_overlap()

        
        base_str=' has an event on that day and time.'
        temp_list=[]
        res_str=''
        for x in [team_leader_overlap,employees_overlap,equipment_overlap]:
            if x:
                temp_list+=x
        if temp_list:
            res_str=_(" and ".join([", ".join(temp_list[:-1]),temp_list[-1]])+base_str)

        
        if not except_raise:

            if temp_list:
                raise ValidationError(res_str)
            else:
                raise RedirectWarning(_(' Everyone is available for the booking'))
        return res_str
Exemple #17
0
 def unlink(self):
     """
     If some projects to unlink have some timesheets entries, these
     timesheets entries must be unlinked first.
     In this case, a warning message is displayed through a RedirectWarning
     and allows the user to see timesheets entries to unlink.
     """
     projects_with_timesheets = self.filtered(lambda p: p.timesheet_ids)
     if projects_with_timesheets:
         if len(projects_with_timesheets) > 1:
             warning_msg = _(
                 "These projects have some timesheet entries referencing them. Before removing these projects, you have to remove these timesheet entries."
             )
         else:
             warning_msg = _(
                 "This project has some timesheet entries referencing it. Before removing this project, you have to remove these timesheet entries."
             )
         raise RedirectWarning(
             warning_msg,
             self.env.ref('hr_timesheet.timesheet_action_project').id,
             _('See timesheet entries'),
             {'active_ids': projects_with_timesheets.ids})
     return super(Project, self).unlink()
Exemple #18
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 find(self, dt=None, exception=True):
     if not dt:
         dt = fields.date.today()
     args = [('date_start', '<=', dt), ('date_stop', '>=', dt)]
     if self.env.context.get('company_id', False):
         company_id = self.env.context['company_id']
     else:
         user_id = self.env['res.users'].browse(self.env.uid)
         company_id = user_id.company_id.id
     args.append(('company_id', '=', company_id))
     ids = self.search(args)
     if not ids:
         if exception:
             obj_ref = self.env['ir.model.data'].get_object_reference
             model, action_id = obj_ref('fal_account_periods_lock',
                                        'action_fal_account_periods_lock')
             msg = _('There is no period defined for this date: %s.'
                     '\nPlease go to Configuration/Periods and configure '
                     'a fiscal year.') % dt
             raise RedirectWarning(msg, action_id,
                                   _('Go to the configuration panel'))
         else:
             return []
     return ids
Exemple #20
0
 def seq_cod_site_kk(self, vals):
     sites = self.search(
         [('partner_id', '=', vals['partner_id'])])
     partner = self.env['res.partner'].search(
         [('id', '=', vals['partner_id'])])
     cod = ''
     if vals.get('cod_site_kk'):
         self.check_cod_site_kk(vals['cod_site_kk'], partner, sites)
         cod = vals['cod_site_kk']
     else:
         seq = [0]
         for site in sites:
             try:
                 seq.append(int(site.cod_site_kk.split('/')[1]))
             except Exception:
                 seq.append(0)
         seq.sort()
         if not partner.ref:
             action = self.env.ref('contacts.action_contacts')
             raise RedirectWarning(
                 'Configure a Referência Interna do cliente.',
                 action.id, 'Ir para contatos')
         cod = "%s/%s" % (partner.ref, str(seq[-1] + 1).zfill(2))
     return cod
Exemple #21
0
    def _import_facturx(self, tree, invoice):
        """ Decodes a factur-x invoice into an invoice.

        :param tree:    the factur-x tree to decode.
        :param invoice: the invoice to update or an empty recordset.
        :returns:       the invoice where the factur-x data was imported.
        """
        def _find_value(xpath, element=tree):
            return self._find_value(xpath, element, tree.nsmap)

        amount_total_import = None

        default_move_type = False
        if invoice._context.get('default_journal_id'):
            journal = self.env['account.journal'].browse(
                self.env.context['default_journal_id'])
            default_move_type = 'out_invoice' if journal.type == 'sale' else 'in_invoice'
        elif invoice._context.get('default_move_type'):
            default_move_type = self._context['default_move_type']
        elif invoice.move_type in self.env['account.move'].get_invoice_types(
                include_receipts=True):
            # in case an attachment is saved on a draft invoice previously created, we might
            # have lost the default value in context but the type was already set
            default_move_type = invoice.move_type

        if not default_move_type:
            raise UserError(
                _("No information about the journal or the type of invoice is passed"
                  ))
        if default_move_type == 'entry':
            return

        # Total amount.
        elements = tree.xpath('//ram:GrandTotalAmount', namespaces=tree.nsmap)
        total_amount = elements and float(elements[0].text) or 0.0

        # Refund type.
        # There is two modes to handle refund in Factur-X:
        # a) type_code == 380 for invoice, type_code == 381 for refund, all positive amounts.
        # b) type_code == 380, negative amounts in case of refund.
        # To handle both, we consider the 'a' mode and switch to 'b' if a negative amount is encountered.
        elements = tree.xpath('//rsm:ExchangedDocument/ram:TypeCode',
                              namespaces=tree.nsmap)
        type_code = elements[0].text

        default_move_type.replace('_refund', '_invoice')
        if type_code == '381':
            default_move_type = 'out_refund' if default_move_type == 'out_invoice' else 'in_refund'
            refund_sign = -1
        else:
            # Handle 'b' refund mode.
            if total_amount < 0:
                default_move_type = 'out_refund' if default_move_type == 'out_invoice' else 'in_refund'
            refund_sign = -1 if 'refund' in default_move_type else 1

        # Write the type as the journal entry is already created.
        invoice.move_type = default_move_type

        # self could be a single record (editing) or be empty (new).
        with Form(invoice.with_context(
                default_move_type=default_move_type)) as invoice_form:
            self_ctx = self.with_company(invoice.company_id)

            # Partner (first step to avoid warning 'Warning! You must first select a partner.').
            partner_type = invoice_form.journal_id.type == 'purchase' and 'SellerTradeParty' or 'BuyerTradeParty'
            invoice_form.partner_id = self_ctx._retrieve_partner(
                name=self._find_value('//ram:' + partner_type + '/ram:Name',
                                      tree,
                                      namespaces=tree.nsmap),
                mail=self._find_value('//ram:' + partner_type +
                                      '//ram:URIID[@schemeID=\'SMTP\']',
                                      tree,
                                      namespaces=tree.nsmap),
                vat=self._find_value('//ram:' + partner_type +
                                     '/ram:SpecifiedTaxRegistration/ram:ID',
                                     tree,
                                     namespaces=tree.nsmap),
            )

            # Reference.
            elements = tree.xpath('//rsm:ExchangedDocument/ram:ID',
                                  namespaces=tree.nsmap)
            if elements:
                invoice_form.ref = elements[0].text

            # Name.
            elements = tree.xpath(
                '//ram:BuyerOrderReferencedDocument/ram:IssuerAssignedID',
                namespaces=tree.nsmap)
            if elements:
                invoice_form.payment_reference = elements[0].text

            # Comment.
            elements = tree.xpath('//ram:IncludedNote/ram:Content',
                                  namespaces=tree.nsmap)
            if elements:
                invoice_form.narration = elements[0].text

            # Total amount.
            elements = tree.xpath('//ram:GrandTotalAmount',
                                  namespaces=tree.nsmap)
            if elements:

                # Currency.
                if elements[0].attrib.get('currencyID'):
                    currency_str = elements[0].attrib['currencyID']
                    currency = self.env.ref('base.%s' % currency_str.upper(),
                                            raise_if_not_found=False)
                    if currency and not currency.active:
                        error_msg = _(
                            'The currency (%s) of the document you are uploading is not active in this database.\n'
                            'Please activate it before trying again to import.',
                            currency.name)
                        error_action = {
                            'view_mode': 'form',
                            'res_model': 'res.currency',
                            'type': 'ir.actions.act_window',
                            'target': 'new',
                            'res_id': currency.id,
                            'views': [[False, 'form']]
                        }
                        raise RedirectWarning(error_msg, error_action,
                                              _('Display the currency'))
                    if currency != self.env.company.currency_id and currency.active:
                        invoice_form.currency_id = currency

                    # Store xml total amount.
                    amount_total_import = total_amount * refund_sign

            # Date.
            elements = tree.xpath(
                '//rsm:ExchangedDocument/ram:IssueDateTime/udt:DateTimeString',
                namespaces=tree.nsmap)
            if elements:
                date_str = elements[0].text
                date_obj = datetime.strptime(date_str,
                                             DEFAULT_FACTURX_DATE_FORMAT)
                invoice_form.invoice_date = date_obj.strftime(
                    DEFAULT_SERVER_DATE_FORMAT)

            # Due date.
            elements = tree.xpath(
                '//ram:SpecifiedTradePaymentTerms/ram:DueDateDateTime/udt:DateTimeString',
                namespaces=tree.nsmap)
            if elements:
                date_str = elements[0].text
                date_obj = datetime.strptime(date_str,
                                             DEFAULT_FACTURX_DATE_FORMAT)
                invoice_form.invoice_date_due = date_obj.strftime(
                    DEFAULT_SERVER_DATE_FORMAT)

            # Invoice lines.
            elements = tree.xpath('//ram:IncludedSupplyChainTradeLineItem',
                                  namespaces=tree.nsmap)
            if elements:
                for element in elements:
                    with invoice_form.invoice_line_ids.new(
                    ) as invoice_line_form:

                        # Sequence.
                        line_elements = element.xpath(
                            './/ram:AssociatedDocumentLineDocument/ram:LineID',
                            namespaces=tree.nsmap)
                        if line_elements:
                            invoice_line_form.sequence = int(
                                line_elements[0].text)

                        # Product.
                        name = _find_value(
                            './/ram:SpecifiedTradeProduct/ram:Name', element)
                        if name:
                            invoice_line_form.name = name
                        invoice_line_form.product_id = self_ctx._retrieve_product(
                            default_code=_find_value(
                                './/ram:SpecifiedTradeProduct/ram:SellerAssignedID',
                                element),
                            name=_find_value(
                                './/ram:SpecifiedTradeProduct/ram:Name',
                                element),
                            barcode=_find_value(
                                './/ram:SpecifiedTradeProduct/ram:GlobalID',
                                element))

                        # Quantity.
                        line_elements = element.xpath(
                            './/ram:SpecifiedLineTradeDelivery/ram:BilledQuantity',
                            namespaces=tree.nsmap)
                        if line_elements:
                            invoice_line_form.quantity = float(
                                line_elements[0].text)

                        # Price Unit.
                        line_elements = element.xpath(
                            './/ram:GrossPriceProductTradePrice/ram:ChargeAmount',
                            namespaces=tree.nsmap)
                        if line_elements:
                            quantity_elements = element.xpath(
                                './/ram:GrossPriceProductTradePrice/ram:BasisQuantity',
                                namespaces=tree.nsmap)
                            if quantity_elements:
                                invoice_line_form.price_unit = float(
                                    line_elements[0].text) / float(
                                        quantity_elements[0].text)
                            else:
                                invoice_line_form.price_unit = float(
                                    line_elements[0].text)
                        else:
                            line_elements = element.xpath(
                                './/ram:NetPriceProductTradePrice/ram:ChargeAmount',
                                namespaces=tree.nsmap)
                            if line_elements:
                                quantity_elements = element.xpath(
                                    './/ram:NetPriceProductTradePrice/ram:BasisQuantity',
                                    namespaces=tree.nsmap)
                                if quantity_elements:
                                    invoice_line_form.price_unit = float(
                                        line_elements[0].text) / float(
                                            quantity_elements[0].text)
                                else:
                                    invoice_line_form.price_unit = float(
                                        line_elements[0].text)
                        # Discount.
                        line_elements = element.xpath(
                            './/ram:AppliedTradeAllowanceCharge/ram:CalculationPercent',
                            namespaces=tree.nsmap)
                        if line_elements:
                            invoice_line_form.discount = float(
                                line_elements[0].text)

                        # Taxes
                        tax_element = element.xpath(
                            './/ram:SpecifiedLineTradeSettlement/ram:ApplicableTradeTax/ram:RateApplicablePercent',
                            namespaces=tree.nsmap)
                        invoice_line_form.tax_ids.clear()
                        for eline in tax_element:
                            tax = self_ctx._retrieve_tax(
                                amount=eline.text,
                                type_tax_use=invoice_form.journal_id.type)
                            if tax:
                                invoice_line_form.tax_ids.add(tax)
            elif amount_total_import:
                # No lines in BASICWL.
                with invoice_form.invoice_line_ids.new() as invoice_line_form:
                    invoice_line_form.name = invoice_form.comment or '/'
                    invoice_line_form.quantity = 1
                    invoice_line_form.price_unit = amount_total_import

        return invoice_form.save()
Exemple #22
0
 def _account_config_warning(self, msg):
     action = self.env.ref('account.action_account_config')
     raise RedirectWarning(
         msg, action.id,
         _('Go to Accounting Configuration Settings screen'))
    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
 def _get_move_line_vals(self, default=None, reverse=False, transfer=None):
     self.ensure_one()
     amount = self.depreciation_value
     main_related_object = self.category_id
     second_related_object = None
     depreciation_type = '%s_depreciation' % self.depreciation_type
     if transfer:
         depreciation_type = 'exceptional_amortization'
     account_field = '%s_account_id' % depreciation_type
     expense_account_field = '%s_expense_account_id' % \
         depreciation_type
     income_account_field = '%s_income_account_id' % \
         depreciation_type
     if self.depreciation_type == 'fiscal':
         if not self.company_id[expense_account_field] or \
                 not self.company_id[income_account_field] or \
                 not self.company_id[account_field]:
             raise RedirectWarning(
                 _('Please indicate fiscal amortization '
                   'accounts in company form!'),
                 self.env.ref('base.action_res_company_form').id,
                 _('Go to company configuration screen'))
         amount = self.accelerated_value
         main_related_object = self.company_id
     if transfer:
         if not self.company_id[expense_account_field] or \
                 not self.company_id[income_account_field]:
             raise RedirectWarning(
                 _('Please indicate exceptional amortization '
                   'accounts in company form!'),
                 self.env.ref('base.action_res_company_form').id,
                 _('Go to company configuration screen'))
         # INFO: always >= 0.0 by defintion, see French law
         amount = self.book_value_wo_exceptional - self.book_value
         second_related_object = self.company_id
         if transfer == 'from_depreciation':
             account_field = 'exceptional_depreciation_account_id'
         elif transfer == 'to_exceptional_amortization':
             amount *= -1.0
             account_field = 'accounting_depreciation_account_id'
     if self._context.get('force_account_move_amount'):
         amount = self._context['force_account_move_amount']
     if not amount:
         return []
     debit, credit = 0.0, abs(amount)
     if (self.asset_type == 'purchase_refund') ^ ((amount < 0.0) ^ reverse):
         debit, credit = abs(credit), abs(debit)
     default = default or {}
     default.update({
         'partner_id': self.asset_id.supplier_id.id,
         'currency_id': self.currency_id.id,
     })
     depreciation_line_vals = default.copy()
     depreciation_line_vals.update({
         'debit':
         debit,
         'credit':
         credit,
         'account_id':
         main_related_object[account_field].id,
         'analytic_account_id':
         self.category_id.asset_analytic_account_id.id,
         'asset_id':
         self.asset_id.id,
     })
     expense_or_income_line_vals = default.copy()
     related_object = second_related_object or main_related_object
     account_field = amount > 0 and expense_account_field or \
         income_account_field
     expense_or_income_line_vals.update({
         'debit':
         credit,
         'credit':
         debit,
         'account_id':
         related_object[account_field].id,
     })
     return [depreciation_line_vals, expense_or_income_line_vals]
Exemple #25
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'))
Exemple #26
0
    def onchange_company_id(self, company_id, part_id, type, invoice_line_ids, currency_id):

        dom = {}
        val = {}
        #val = super(account_invoice, self).onchange_company_id(company_id=company_id, part_id=part_id, type=type, invoice_line_ids=invoice_line_ids, currency_id=currency_id)
        # 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:
                prop = self.env['ir.property']
                rec_dom = [('name', '=', 'property_account_receivable'), ('company_id', '=', company_id)]
                pay_dom = [('name', '=', 'property_account_payable'), ('company_id', '=', company_id)]
                res_dom = [('res_id', '=', 'res.partner,%s' % part_id)]
                rec_prop = prop.search(rec_dom + res_dom) or prop.search(rec_dom)
                pay_prop = prop.search(pay_dom + res_dom) or prop.search(pay_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'):
                    acc_id = rec_account.id
                else:
                    acc_id = pay_account.id
                val= {'account_id': acc_id}

            if self:
                if company_id:
                    for line in self.invoice_line_ids:
                        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)])
                        if not accounts:
                            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'))
                        line.write({'account_id': accounts[-1].id})
            else:
                for line_cmd in invoice_line_ids or []:
                    if len(line_cmd) >= 3 and isinstance(line_cmd[2], dict):
                        line = self.env['account.account'].browse(line_cmd[2]['account_id'])
                        if line.company_id.id != company_id:
                            raise except_orm(
                                _('Configuration Error!'),
                                _("Invoice line account's company and invoice's company does not match.")
                            )


        account_journal = self.env['account.journal']
        if company_id and type:
            if type in ('out_invoice', 'out_debit'):  # Modified
                journal_type = 'sale'
            elif type in ('out_refund'):
                journal_type = 'sale_refund'
            elif type in ('in_refund', 'in_debit'):  # Modified
                journal_type = 'purchase_refund'
            else:
                journal_type = 'purchase'
            journal_ids = account_journal.search([('type', '=', journal_type), ('company_id', '=', company_id)])
            if journal_ids:
                val['journal_id'] = journal_ids.id
            res_journal_default = self.env['ir.values'].get('default', 'type=%s' %(type), ['account.invoice'])
            for r in res_journal_default:
                if r[1] == 'journal_id' and r[2] in journal_ids:
                    val['journal_id'] = r[2]
            if not val.get('journal_id', False):
                raise except_orm(_('Configuration Error !'), (_('Can\'t find any account journal of %s type for this company.\n\nYou can create one in the menu: \nConfiguration\Financial Accounting\Accounts\Journals.') % (journal_type)))
            dom = {'journal_id':  [('id', 'in', journal_ids.ids)]}
        else:
            journal_ids = account_journal.search([])

        if currency_id and company_id:
            currency = self.env['res.currency'].browse(currency_id)
            if currency.company_id and currency.company_id.id != company_id:
                val['currency_id'] = False
            else:
                val['currency_id'] = currency.id
        if company_id:
            company = self.env['res.company'].browse(company_id)
            if company.currency_id.company_id and company.currency_id.company_id.id != company_id:
                val['currency_id'] = False
            else:
                val['currency_id'] = company.currency_id.id
        return {'value': val, 'domain': dom}
Exemple #27
0
    def _onchange_partner_id(self):
        account_id = False
        payment_term_id = False
        fiscal_position = False
        bank_id = False
        warning = {}
        domain = {}
        company_id = self.company_id.id
        p = self.partner_id if not company_id else self.partner_id.with_context(
            force_company=company_id)
        type = self.type
        if p:
            rec_account = p.property_account_receivable_id
            pay_account = p.property_account_payable_id
            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 ('in_invoice', 'in_refund'):
                account_id = pay_account.id
                payment_term_id = p.property_supplier_payment_term_id.id
            else:
                account_id = rec_account.id
                payment_term_id = p.property_payment_term_id.id

            delivery_partner_id = self.get_delivery_partner_id()
            fiscal_position = self.env[
                'account.fiscal.position'].get_fiscal_position(
                    self.partner_id.id, delivery_id=delivery_partner_id)

            # If partner has no warning, check its company
            if p.invoice_warn == 'no-message' and p.parent_id:
                p = p.parent_id
            if p.invoice_warn and p.invoice_warn != 'no-message':
                # Block if partner only has warning but parent company is blocked
                if p.invoice_warn != 'block' and p.parent_id and p.parent_id.invoice_warn == 'block':
                    p = p.parent_id
                warning = {
                    'title': _("Warning for %s") % p.name,
                    'message': p.invoice_warn_msg
                }
                if p.invoice_warn == 'block':
                    self.partner_id = False

        self.account_id = account_id

        # print(p.account_repayment_id)
        # print(p)
        self.account_repayment_id = p.account_repayment_id
        self.payment_term_id = payment_term_id
        self.date_due = False
        self.fiscal_position_id = fiscal_position

        if type in ('in_invoice', 'out_refund'):
            bank_ids = p.commercial_partner_id.bank_ids
            bank_id = bank_ids[0].id if bank_ids else False
            self.partner_bank_id = bank_id
            domain = {'partner_bank_id': [('id', 'in', bank_ids.ids)]}

        res = {}
        if warning:
            res['warning'] = warning
        if domain:
            res['domain'] = domain
        return res
Exemple #28
0
# special case: change/extend context
recs2 = self.with_context(context2)  # change context by context2
#ou
self = self.with_context(lang='fr')  # extend current context
self.env['res.currency'].with_context(date=signature_date).compute()
super(ProductPriceList, self.with_context(fiscal_position_id=self.fiscal_position_id.id)).print_report()

# special case: change the uid
recs2 = self.sudo(user.id)
recs2 = self.sudo()  # uid = SUPERUSER_ID

# RedirectWarning
action = self.env.ref('account.action_account_config')  # ok v14
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'))

# Récupérer une action sous forme de dico
action = self.env['ir.actions.act_window'].for_xml_id('stock', 'action_package_view')
action = self.env.ref('stock.action_package_view').read()[0]
ex:
action = self.env.ref('account.action_invoice_tree1').read()[0]
action.update({
    'views': [(self.env.ref('account.invoice_form').id, 'form')],
    'view_mode': 'form,tree,kanban,calendar',
    'res_id': out_invoice.id,
    })

# v14+
action = self.env["ir.actions.actions"]._for_xml_id("stock.action_stock_rules_report")
Exemple #29
0
 def get_real_datetime(self):
     if not self.env.user.tz :
         action = self.env.ref('base.action_res_users')
         msg = _("Please set your timezone in Users menu.")
         raise RedirectWarning(msg, action.id, _("Go to Users menu"))
     return pytz.UTC.localize(datetime.now()).astimezone(timezone(self.env.user.tz))
Exemple #30
0
    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
        if self._context.get('type') == 'in_invoice':
            journal_id = self.env['account.journal'].search([
                ('type', '=', 'purchase'), ('company_id', '=', company_id)
            ])
        elif self._context.get('type') == 'out_invoice':
            journal_id = self.env['account.journal'].search([
                ('type', '=', 'sale'), ('company_id', '=', company_id)
            ])
        else:
            journal_id = self._default_journal()
        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)]
                    rec_prop = prop.search(rec_dom +
                                           res_dom) or prop.search(rec_dom)
                    pay_prop = prop.search(pay_dom +
                                           res_dom) or prop.search(pay_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
        self.journal_id = journal_id[0].id
        ctx = dict(self._context or {})
        ctx['company_id'] = self.company_id.id

        property_obj = self.env['ir.property']
        field_obj = self.env['ir.model.fields']
        '''Account income property '''
        field_id = field_obj.search([
            ('field_description', '=', 'Income Account'),
            ('name', '=', 'property_account_income_id')
        ])
        if field_id:
            property_id = property_obj.search([
                ('fields_id', '=', field_id[0].id),
                ('company_id', '=', self.company_id.id)
            ])
        else:
            property_id = False
        if property_id:
            acc_ref = property_id.browse(property_id[0].id).value_reference
            acc_income_acc = acc_ref and acc_ref.split(',') and acc_ref.split(
                ',')[1]

            acc_income_acc = int(acc_income_acc)
        else:
            acc_income_acc = False
        if not acc_income_acc:
            field_id = field_id.search([
                ('field_description', '=', 'Income Account'),
                ('name', '=', 'property_account_income_categ_id')
            ])
            if field_id:
                property_id = property_id.search([
                    ('fields_id', '=', field_id[0].id),
                    ('company_id', '=', self.company_id.id)
                ])
            else:
                property_id = False
            if property_id:
                acc_ref = property_id.browse(property_id[0].id).value_reference
                acc_income_acc = acc_ref and acc_ref.split(
                    ',') and acc_ref.split(',')[1]
                acc_income_acc = int(acc_income_acc)
        '''Expence Account   '''
        field_id = field_obj.search([
            ('field_description', '=', 'Expense Account'),
            ('name', '=', 'property_account_expense_id')
        ])
        if field_id:
            property_id = property_obj.search([
                ('fields_id', '=', field_id[0].id),
                ('company_id', '=', self.company_id.id)
            ])
        else:
            property_id = False
        if property_id:
            acc_ref = property_id.browse(property_id[0].id).value_reference
            acc_exp_acc = acc_ref and acc_ref.split(',') and acc_ref.split(
                ',')[1]

            acc_exp_acc = int(acc_exp_acc)
        else:
            acc_exp_acc = False
        if not acc_exp_acc:
            field_id = field_id.search([
                ('field_description', '=', 'Expense Account'),
                ('name', '=', 'property_account_expense_categ_id')
            ])
            if field_id:
                property_id = property_id.search([
                    ('fields_id', '=', field_id[0].id),
                    ('company_id', '=', self.company_id.id)
                ])
            else:
                property_id = False
            if property_id:
                acc_ref = property_id.browse(property_id[0].id).value_reference
                acc_exp_acc = acc_ref and acc_ref.split(',') and acc_ref.split(
                    ',')[1]
                acc_exp_acc = int(acc_exp_acc)
        if (self.invoice_line_ids and ctx.get('type') == 'out_invoice') or (
                self.invoice_line_ids
                and ctx.get('default_type') == 'out_invoice'):
            for i in self.invoice_line_ids:
                if i:
                    i.account_id = acc_income_acc
        if (self.invoice_line_ids and ctx.get('type') == 'in_invoice') or (
                self.invoice_line_ids
                and ctx.get('default_type') == 'in_invoice'):
            for i in self.invoice_line_ids:
                if i:
                    i.account_id = acc_exp_acc
        if type in ('in_invoice', 'in_refund'):
            self.partner_bank_id = bank_id