Пример #1
0
 def _check_bvr(self):
     """
     Function to validate a bvr reference like :
     0100054150009>132000000000000000000000014+ 1300132412>
     The validation is based on l10n_ch
     """
     for invoice in self:
         if invoice.reference_type == 'bvr':
             if not invoice.reference:
                 raise exceptions.ValidationError(
                     _('BVR/ESR Reference is required')
                 )
             # In this case
             # <010001000060190> 052550152684006+ 43435>
             # the reference 052550152684006 do not match modulo 10
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference and \
                     len(invoice.reference) == 15:
                 return True
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference:
                 raise exceptions.ValidationError(
                     _('Invalid BVR/ESR Number (wrong checksum).')
                 )
     return True
Пример #2
0
    def on_change_bvr_ref(self, cr, uid, ids, bvr_reference, context=None):
        ''' Test the validity of a reference number. '''
        is_valid = bvr_reference and bvr_reference.isdigit()
        if is_valid and len(bvr_reference) == 26:
            bvr_reference = mod10r(bvr_reference)
        elif is_valid and len(bvr_reference) == 27:
            valid_ref = mod10r(bvr_reference[:-1])
            is_valid = (valid_ref == bvr_reference)
        else:
            is_valid = False

        res = {}
        if is_valid:
            res['value'] = {'bvr_reference': bvr_reference}
        elif bvr_reference:
            res['warning'] = {
                'title':
                _('Warning'),
                'message':
                _('The reference of the partner '
                  'has not been set, or is in '
                  'wrong format. Please make sure'
                  ' to enter a valid BVR '
                  'reference for the contract.')
            }
        return res
Пример #3
0
    def get_bvr_ref(self, cursor, uid, move_line_id, context=None):
        """Retrieve ESR/BVR reference from move line in order to print it

        Returns False when no BVR reference should be generated.  No
        reference is generated when a transaction reference already
        exists for the line (likely been generated by a payment service).
        """
        res = ''
        if isinstance(move_line_id, (tuple, list)):
            assert len(move_line_id) == 1, "Only 1 ID expected"
            move_line_id = move_line_id[0]
        move_line = self.browse(cursor, uid, move_line_id, context=context)
        ## We check if the type is bvr, if not we return false
        if move_line.invoice.partner_bank_id.state != 'bvr':
            return ''
        ##
        if move_line.invoice.partner_bank_id.bvr_adherent_num:
            res = move_line.invoice.partner_bank_id.bvr_adherent_num
        move_number = ''
        if move_line.invoice.number:
            move_number = self._compile_get_ref.sub('', str(move_line.invoice.number) + str(move_line_id))
        reference = mod10r(res + move_number.rjust(26 - len(res), '0'))
        if (move_line.transaction_ref and
                move_line.transaction_ref != reference):
            # the line has already a transaction id and it is not
            # a BVR reference
            return ''
        return reference
Пример #4
0
    def _parse_lines(self, cursor, uid, inlines, context=None):
        """Parses raw v11 line and populate records list with dict"""
        records = []
        total_amount = 0
        total_cost = 0
        find_total = False
        for lines in inlines:
            if not lines:  # manage new line at end of file
                continue
            (line, lines) = (lines[:128], lines[128:])
            record = {}
            if line[0:3] in ('999', '995'):
                if find_total:
                    raise except_osv(_('Error'),
                                     _('Too much total record found!'))
                find_total = True
                if lines:
                    raise except_osv(_('Error'),
                                     _('Record found after total record!'))
                amount = float(line[39:49]) + (float(line[49:51]) / 100)
                cost = float(line[69:76]) + (float(line[76:78]) / 100)
                if line[2] == '5':
                    amount *= -1
                    cost *= -1

                if round(amount - total_amount, 2) >= 0.01 \
                        or round(cost - total_cost, 2) >= 0.01:
                    raise except_osv(
                        _('Error'),
                        _('Total record different from the computed!'))
                if int(line[51:63]) != len(records):
                    raise except_osv(
                        _('Error'),
                        _('Number record different from the computed!'))
            else:
                record = {
                    'reference':
                    line[12:39],
                    'amount':
                    float(line[39:47]) + (float(line[47:49]) / 100),
                    'date':
                    time.strftime('%Y-%m-%d',
                                  time.strptime(line[65:71], '%y%m%d')),
                    'cost':
                    float(line[96:98]) + (float(line[98:100]) / 100),
                }

                if record['reference'] != mod10r(record['reference'][:-1]):
                    raise except_osv(
                        _('Error'),
                        _('Recursive mod10 is invalid for reference: %s') %
                        record['reference'])

                if line[2] == '5':
                    record['amount'] *= -1
                    record['cost'] *= -1
                total_amount += record['amount']
                total_cost += record['cost']
                records.append(record)
        return records
Пример #5
0
    def get_bvr_ref(self, cursor, uid, move_line_id, context=None):
        """Retrieve ESR/BVR reference from move line in order to print it

        Returns False when no BVR reference should be generated.  No
        reference is generated when a transaction reference already
        exists for the line (likely been generated by a payment service).
        """
        res = ''
        if isinstance(move_line_id, (tuple, list)):
            assert len(move_line_id) == 1, "Only 1 ID expected"
            move_line_id = move_line_id[0]
        move_line = self.browse(cursor, uid, move_line_id, context=context)
        ## We check if the type is bvr, if not we return false
        if move_line.invoice.partner_bank_id.state != 'bvr':
            return ''
        ##
        if move_line.invoice.partner_bank_id.bvr_adherent_num:
            res = move_line.invoice.partner_bank_id.bvr_adherent_num
        move_number = ''
        if move_line.invoice.number:
            move_number = self._compile_get_ref.sub(
                '',
                str(move_line.invoice.number) + str(move_line_id))
        reference = mod10r(res + move_number.rjust(26 - len(res), '0'))
        if (move_line.transaction_ref
                and move_line.transaction_ref != reference):
            # the line has already a transaction id and it is not
            # a BVR reference
            return ''
        return reference
Пример #6
0
    def _is_bvr_ref(self, ref):
        if not ref:
            return False  # Empty is not valid
        clean_ref = ref.replace(' ', '')
        if not clean_ref.isdigit() or len(clean_ref) > 27:
            return False
        clean_ref = clean_ref.rjust(27, '0')  # Add zeros to the left
        if not clean_ref == mod10r(clean_ref[0:26]):
            return False

        return True
Пример #7
0
    def on_change_bvr_ref(self):
        """ Test the validity of a reference number. """
        bvr_reference = self.bvr_reference
        is_valid = bvr_reference and bvr_reference.isdigit()
        if is_valid and len(bvr_reference) == 26:
            bvr_reference = mod10r(bvr_reference)
        elif is_valid and len(bvr_reference) == 27:
            valid_ref = mod10r(bvr_reference[:-1])
            is_valid = (valid_ref == bvr_reference)
        else:
            is_valid = False

        if is_valid:
            self.bvr_reference = bvr_reference
        elif bvr_reference:
            raise exceptions.Warning(
                _('Warning'),
                _('The reference of the partner has not been set, or is in '
                  'wrong format. Please make sure to enter a valid BVR '
                  'reference for the contract.'))
    def _generate_bvr_reference(self, contract, product):
        ref = contract.partner_id.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        num_pol_ga = str(contract.num_pol_ga)
        bvr_reference += '0' * (5 - len(num_pol_ga)) + num_pol_ga
        # Type of gift
        bvr_reference += str(GIFT_TYPES.index(product.name)+1)
        bvr_reference += '0' * 4

        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
    def _generate_bvr_reference(self, contract, product):
        ref = contract.partner_id.ref
        bvr_reference = "0" * (9 + (7 - len(ref))) + ref
        num_pol_ga = str(contract.num_pol_ga)
        bvr_reference += "0" * (5 - len(num_pol_ga)) + num_pol_ga
        # Type of gift
        bvr_reference += str(GIFT_TYPES.index(product.name) + 1)
        bvr_reference += "0" * 4

        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
Пример #10
0
    def on_change_bvr_ref(self):
        """ Test the validity of a reference number. """
        bvr_reference = self.bvr_reference
        is_valid = bvr_reference and bvr_reference.isdigit()
        if is_valid and len(bvr_reference) == 26:
            bvr_reference = mod10r(bvr_reference)
        elif is_valid and len(bvr_reference) == 27:
            valid_ref = mod10r(bvr_reference[:-1])
            is_valid = (valid_ref == bvr_reference)
        else:
            is_valid = False

        if is_valid:
            self.bvr_reference = bvr_reference
        elif bvr_reference:
            raise exceptions.Warning(
                _('Warning'),
                _('The reference of the partner has not been set, or is in '
                  'wrong format. Please make sure to enter a valid BVR '
                  'reference for the contract.'))
Пример #11
0
    def validate_global_context_dict(self):
        """Validate BVR record values"""
        super(record_gt826, self).validate_global_context_dict()
        if not self.global_values['reference']:
            raise except_orm(
                _('Error'),
                _('You must provide a BVR reference'
                  'number \n for the line: %s') % self.pline.name
            )
        ref = self.global_values['reference'].replace(' ', '')
        self.global_values['reference'] = ref
        if self.is_9_pos_adherent:
            if len(ref) > 27:
                raise except_orm(
                    _('Error'),
                    _('BVR reference number is not valid \n'
                      'for the line: %s. \n'
                      'Reference is too long.') % self.pline.name
                )
            # do a mod10 check
            if mod10r(ref[:-1]) != ref:
                raise except_orm(
                    _('Error'),
                    _('BVR reference number is not valid \n'
                      'for the line: %s. \n'
                      'Mod10 check failed') % self.pline.name
                )
            # fill reference with 0
            self.global_values['reference'] = ref.rjust(27, '0')
        else:
            # reference of BVR adherent with 5 positions number
            # have 15 positions references
            if len(ref) > 15:
                raise except_orm(
                    _('Error'),
                    _('BVR reference number is not valid \n'
                      'for the line: %s. \n Reference is too long '
                      'for this type of beneficiary.') % self.pline.name
                )
            # complete 15 first digit with 0 on left and complete 27 digits
            # with trailing spaces
            # exemple: 123456 becomes 00000000012345____________
            adjust = ref.rjust(15, '0').ljust(27, ' ')
            self.global_values['reference'] = adjust

        if not self.global_values['partner_bvr']:
            raise except_orm(
                _('Error'),
                _('You must provide a BVR number\n'
                  'for the bank account: %s'
                  'on line: %s') % (self.pline.bank_id.get_account_number(),
                                    self.pline.name)
            )
Пример #12
0
    def _compute_bvr_ref(self, cr, uid, move_line, context=None):
        ''' Default BVR reference computation '''
        res = ''
        if move_line.invoice.partner_bank_id.bvr_adherent_num:
            res = move_line.invoice.partner_bank_id.bvr_adherent_num
        move_number = ''

        if move_line.invoice.number:
            compound = str(move_line.invoice.number) + str(move_line.id)
            move_number = self._compile_get_ref.sub('', compound)
        reference = mod10r(res + move_number.rjust(26 - len(res), '0'))
        return reference
Пример #13
0
    def _check_bvr_ref(self, cr, uid, ids, context=None):
        record = self.browse(cr, uid, ids, context=context)
        for data in record:
            if not data.bvr_reference:
                return True  # No check if no reference
            clean_ref = data.bvr_reference.replace(' ', '')
            if not clean_ref.isdigit() or len(clean_ref) > 27:
                return False
            clean_ref = clean_ref.rjust(27, '0')  # Add zeros to the left
            if not clean_ref == mod10r(clean_ref[0:26]):
                return False

        return True
Пример #14
0
 def _check_bvr(self, cr, uid, ids, context=None):
     """
     Function to validate a bvr reference like :
     0100054150009>132000000000000000000000014+ 1300132412>
     The validation is based on l10n_ch
     """
     invoices = self.browse(cr, uid, ids)
     for invoice in invoices:
         if invoice.reference_type == 'bvr' and invoice.state != 'draft':
             if not invoice.reference:
                 return False
             ## In this case
             # <010001000060190> 052550152684006+ 43435>
             # the reference 052550152684006 do not match modulo 10
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference and \
                     len(invoice.reference) == 15:
                 return True
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference:
                 return False
     return True
Пример #15
0
 def _check_bvr(self, cr, uid, ids, context=None):
     """
     Function to validate a bvr reference like :
     0100054150009>132000000000000000000000014+ 1300132412>
     The validation is based on l10n_ch
     """
     invoices = self.browse(cr, uid, ids)
     for invoice in invoices:
         if invoice.reference_type == 'bvr' and invoice.state != 'draft':
             if not invoice.reference:
                 return False
             ## In this case
             # <010001000060190> 052550152684006+ 43435>
             # the reference 052550152684006 do not match modulo 10
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference and \
                     len(invoice.reference) == 15:
                 return True
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference:
                 return False
     return True
Пример #16
0
 def _is_bvr_reference(self):
     """
     Function to validate a bvr reference like :
     0100054150009>132000000000000000000000014+ 1300132412>
     The validation is based on l10n_ch
     """
     if not self.reference:
         raise exceptions.ValidationError(
             _('BVR/ESR Reference is required')
         )
     # In this case
     # <010001000060190> 052550152684006+ 43435>
     # the reference 052550152684006 do not match modulo 10
     #
     if (mod10r(self.reference[:-1]) != self.reference and
             len(self.reference) == 15):
         return True
     #
     if mod10r(self.reference[:-1]) != self.reference:
         raise exceptions.ValidationError(
             _('Invalid BVR/ESR Number (wrong checksum).')
         )
Пример #17
0
    def _check_bvr_ref(self, cr, uid, ids, context=None):
        record = self.browse(cr, uid, ids, context=context)
        for data in record:
            if not data.bvr_reference:
                return True  # No check if no reference
            clean_ref = data.bvr_reference.replace(' ', '')
            if not clean_ref.isdigit() or len(clean_ref) > 27:
                return False
            clean_ref = clean_ref.rjust(27, '0')  # Add zeros to the left
            if not clean_ref == mod10r(clean_ref[0:26]):
                return False

        return True
Пример #18
0
    def _parse_lines(self, cursor, uid, inlines, context=None):
        """Parses raw v11 line and populate records list with dict"""
        records = []
        total_amount = 0
        total_cost = 0
        find_total = False
        for lines in inlines:
            if not lines:  # manage new line at end of file
                continue
            (line, lines) = (lines[:128], lines[128:])
            record = {}
            if line[0:3] in ('999', '995'):
                if find_total:
                    raise except_osv(_('Error'),
                                     _('Too much total record found!'))
                find_total = True
                if lines:
                    raise except_osv(_('Error'),
                                     _('Record found after total record!'))
                amount = float(line[39:49]) + (float(line[49:51]) / 100)
                cost = float(line[69:76]) + (float(line[76:78]) / 100)
                if line[2] == '5':
                    amount *= -1
                    cost *= -1

                if round(amount - total_amount, 2) >= 0.01 \
                        or round(cost - total_cost, 2) >= 0.01:
                    raise except_osv(_('Error'),
                                     _('Total record different from the computed!'))
                if int(line[51:63]) != len(records):
                    raise except_osv(_('Error'),
                                     _('Number record different from the computed!'))
            else:
                record = {
                    'reference': line[12:39],
                    'amount': float(line[39:47]) + (float(line[47:49]) / 100),
                    'date': time.strftime('%Y-%m-%d', time.strptime(line[65:71], '%y%m%d')),
                    'cost': float(line[96:98]) + (float(line[98:100]) / 100),
                }

                if record['reference'] != mod10r(record['reference'][:-1]):
                    raise except_osv(_('Error'),
                                     _('Recursive mod10 is invalid for reference: %s') % record['reference'])

                if line[2] == '5':
                    record['amount'] *= -1
                    record['cost'] *= -1
                total_amount += record['amount']
                total_cost += record['cost']
                records.append(record)
        return records
Пример #19
0
 def _check_bvr_ref(self):
     for data in self:
         if not data.bvr_reference:
             return True  # No check if no reference
         clean_ref = data.bvr_reference.replace(' ', '')
         if not clean_ref.isdigit() or len(clean_ref) > 27:
             raise exceptions.ValidationError('Error: BVR ref should only' +
                                              'contain number (max. 27) ' +
                                              'and spaces.')
         clean_ref = clean_ref.rjust(27, '0')  # Add zeros to the left
         if not clean_ref == mod10r(clean_ref[0:26]):
             raise exceptions.ValidationError('Invalid BVR ref number. ' +
                                              'Please check the number.')
     return True
    def _generate_bvr_reference(self, contract, product):
        ref = contract.partner_id.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        num_pol_ga = str(contract.num_pol_ga)
        bvr_reference += '0' * (5 - len(num_pol_ga)) + num_pol_ga
        # Type of gift
        bvr_reference += str(GIFT_TYPES.index(product.name) + 1)
        bvr_reference += '0' * 4

        if contract.group_id.payment_term_id and \
                'LSV' in contract.group_id.payment_term_id.name:
            bvr_reference = '004874969' + bvr_reference[9:]
        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
    def on_change_bvr_ref(self, cr, uid, ids, bvr_reference,
                          context=None):
        """ Test the validity of a reference number. """
        is_valid = bvr_reference and bvr_reference.isdigit()
        if is_valid and len(bvr_reference) == 26:
            bvr_reference = mod10r(bvr_reference)
        elif is_valid and len(bvr_reference) == 27:
            valid_ref = mod10r(bvr_reference[:-1])
            is_valid = (valid_ref == bvr_reference)
        else:
            is_valid = False

        res = dict()
        if is_valid:
            res['value'] = {'bvr_reference': bvr_reference}
        elif bvr_reference:
            res['warning'] = {'title': _('Warning'),
                              'message': _('The reference of the partner '
                                           'has not been set, or is in '
                                           'wrong format. Please make sure'
                                           ' to enter a valid BVR '
                                           'reference for the contract.')}
        return res
Пример #22
0
 def _check_bvr(self):
     """
     Function to validate a bvr reference like :
     0100054150009>132000000000000000000000014+ 1300132412>
     The validation is based on l10n_ch
     """
     for invoice in self:
         if invoice.reference_type == 'bvr':
             if not invoice.reference:
                 raise exceptions.ValidationError(
                     _('BVR/ESR Reference is required'))
             # In this case
             # <010001000060190> 052550152684006+ 43435>
             # the reference 052550152684006 do not match modulo 10
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference and \
                     len(invoice.reference) == 15:
                 return True
             #
             if mod10r(invoice.reference[:-1]) != invoice.reference:
                 raise exceptions.ValidationError(
                     _('Invalid BVR/ESR Number (wrong checksum).'))
     return True
Пример #23
0
 def _update_invoice_lines(self, invoices):
     super(recurring_contract, self)._update_invoice_lines(invoices)
     # Update bvr_reference of invoices
     ref = False
     bank_terms = self.env['account.payment.term'].with_context(
         lang='en_US').search([
             '|', ('name', 'like', 'LSV'), ('name', 'like', 'Postfinance')
         ])
     if self.group_id.bvr_reference:
         ref = self.group_id.bvr_reference
     elif self.group_id.payment_term_id in bank_terms:
         seq = self.env['ir.sequence']
         ref = mod10r(seq.next_by_code('contract.bvr.ref'))
     invoices.write({'bvr_reference': ref})
Пример #24
0
 def _check_9_pos_postal_num(self, number):
     """
     check if a postal number in format xx-xxxxxx-x is correct,
     return true if it matches the pattern
     and if check sum mod10 is ok
     """
     pattern = r'^[0-9]{2}-[0-9]{1,6}-[0-9]$'
     if not re.search(pattern, number):
         return False
     nums = number.split('-')
     prefix = nums[0]
     num = nums[1].rjust(6, '0')
     checksum = nums[2]
     expected_checksum = mod10r(prefix + num)[-1]
     return expected_checksum == checksum
Пример #25
0
 def _check_9_pos_postal_num(self, number):
     """
     check if a postal number in format xx-xxxxxx-x is correct,
     return true if it matches the pattern
     and if check sum mod10 is ok
     """
     pattern = r'^[0-9]{2}-[0-9]{1,6}-[0-9]$'
     if not re.search(pattern, number):
         return False
     nums = number.split('-')
     prefix = nums[0]
     num = nums[1].rjust(6, '0')
     checksum = nums[2]
     expected_checksum = mod10r(prefix + num)[-1]
     return expected_checksum == checksum
Пример #26
0
    def compute_partner_bvr_ref(self, cr, uid, ids, partner=None,
                                context=None):
        """ Generates a new BVR Reference.
        See file \\nas\it\devel\Code_ref_BVR.xls for more information."""
        partner = partner or self.browse(cr, uid, ids[0], context).partner_id
        result = '0' * (9 + (7 - len(partner.ref))) + partner.ref
        count_groups = str(self.search(
            cr, uid, [('partner_id', '=', partner.id)], context=context,
            count=True))
        result += '0' * (5 - len(count_groups)) + count_groups
        # Type '0' = Sponsorship
        result += '0'
        result += '0' * 4

        if len(result) == 26:
            return mod10r(result)
Пример #27
0
 def get_bvr_ref(self, cursor, uid, inv_id, context=None):
     """Retrieve ESR/BVR reference form invoice in order to print it"""
     res = ''
     if isinstance(inv_id, list):
         inv_id = inv_id[0]
     inv = self.browse(cursor, uid, inv_id, context=context)
     ## We check if the type is bvr, if not we return false
     if inv.partner_bank_id.state != 'bvr':
         return ''
     ##
     if inv.partner_bank_id.bvr_adherent_num:
         res = inv.partner_bank_id.bvr_adherent_num
     invoice_number = ''
     if inv.number:
         invoice_number = self._compile_get_ref.sub('', inv.number)
     return mod10r(res + invoice_number.rjust(26 - len(res), '0'))
 def get_bvr_ref(self, cursor, uid, inv_id, context=None):
     """Retrieve ESR/BVR reference form invoice in order to print it"""
     res = ''
     if isinstance(inv_id, list):
         inv_id = inv_id[0]
     inv = self.browse(cursor, uid, inv_id, context=context)
     ## We check if the type is bvr, if not we return false
     if inv.partner_bank_id.state != 'bvr':
         return ''
     ##
     if inv.partner_bank_id.bvr_adherent_num:
         res = inv.partner_bank_id.bvr_adherent_num
     invoice_number = ''
     if inv.number:
         invoice_number = self._compile_get_ref.sub('', inv.number)
     return mod10r(res + invoice_number.rjust(26 - len(res), '0'))
Пример #29
0
    def _parse_lines(self, cursor, uid, inlines, context=None):
        """Parses raw v11 line and populate records list with dict"""
        records = []
        total_amount = 0
        total_cost = 0
        find_total = False
        for lines in inlines:
            if not lines:  # manage new line at end of file
                continue
            (line, lines) = (lines[:128], lines[128:])
            record = {}
            if line[0:3] in ("999", "995"):
                if find_total:
                    raise except_osv(_("Error"), _("Too much total record found!"))
                find_total = True
                if lines:
                    raise except_osv(_("Error"), _("Record found after total record!"))
                amount = float(line[39:49]) + (float(line[49:51]) / 100)
                cost = float(line[69:76]) + (float(line[76:78]) / 100)
                if line[2] == "5":
                    amount *= -1
                    cost *= -1

                if round(amount - total_amount, 2) >= 0.01 or round(cost - total_cost, 2) >= 0.01:
                    raise except_osv(_("Error"), _("Total record different from the computed!"))
                if int(line[51:63]) != len(records):
                    raise except_osv(_("Error"), _("Number record different from the computed!"))
            else:
                record = {
                    "reference": line[12:39],
                    "amount": float(line[39:47]) + (float(line[47:49]) / 100),
                    "date": time.strftime("%Y-%m-%d", time.strptime(line[65:71], "%y%m%d")),
                    "cost": float(line[96:98]) + (float(line[98:100]) / 100),
                }

                if record["reference"] != mod10r(record["reference"][:-1]):
                    raise except_osv(
                        _("Error"), _("Recursive mod10 is invalid for reference: %s") % record["reference"]
                    )

                if line[2] == "5":
                    record["amount"] *= -1
                    record["cost"] *= -1
                total_amount += record["amount"]
                total_cost += record["cost"]
                records.append(record)
        return records
 def get_bvr_ref(self, cursor, uid, move_line_id, context=None):
     """Retrieve ESR/BVR reference from move line in order to print it"""
     res = ''
     if isinstance(move_line_id, (tuple, list)):
         assert len(move_line_id) == 1, "Only 1 ID expected"
         move_line_id = move_line_id[0]
     move_line = self.browse(cursor, uid, move_line_id, context=context)
     ## We check if the type is bvr, if not we return false
     if move_line.invoice.partner_bank_id.state != 'bvr':
         return ''
     ##
     if move_line.invoice.partner_bank_id.bvr_adherent_num:
         res = move_line.invoice.partner_bank_id.bvr_adherent_num
     move_number = ''
     if move_line.invoice.number:
         move_number = self._compile_get_ref.sub('', str(move_line.invoice.number) + str(move_line_id))
     return mod10r(res + move_number.rjust(26 - len(res), '0'))
Пример #31
0
    def is_post_dd_ident_valid(self, dd_identifier):
        """ Check if given Postfinance DD Identifier is valid """
        if not isinstance(dd_identifier, basestring):
            return False
        try:
            dd_identifier.decode('ascii')
        except UnicodeDecodeError:
            raise exceptions.ValidationError(
                _('DD identifier should contain only ASCII caracters.'))

        if not len(dd_identifier) == 6:
            return False

        if not dd_identifier == mod10r(dd_identifier[:5]):
            return False

        return True
Пример #32
0
    def _get_bvr_ref(self, cr, uid, invoice, context=None):
        """Retrieve ESR/BVR reference form invoice in order to print it

        Receive a browse record so it can be overloaded without rebrowsing
        the invoice.
        """
        res = ''
        ## We check if the type is bvr, if not we return false
        if invoice.partner_bank_id.state != 'bvr':
            return ''
        ##
        if invoice.partner_bank_id.bvr_adherent_num:
            res = invoice.partner_bank_id.bvr_adherent_num
        invoice_number = ''
        if invoice.number:
            invoice_number = self._compile_get_ref.sub('', invoice.number)
        return mod10r(res + invoice_number.rjust(26 - len(res), '0'))
Пример #33
0
    def _setup_inv_data(self, journal_ids, invoicer):
        """ Inherit to add BVR ref """
        self.ensure_one()
        inv_data = super(contract_group,
                         self)._setup_inv_data(journal_ids, invoicer)

        ref = ''
        if self.bvr_reference:
            ref = self.bvr_reference
        elif (self.payment_term_id
              and (_('LSV') in self.payment_term_id.name
                   or _('Direct Debit') in self.payment_term_id.name)):
            seq = self.pool['ir.sequence']
            ref = mod10r(seq.next_by_code('contract.bvr.ref'))
        inv_data.update({'bvr_reference': ref})

        return inv_data
Пример #34
0
    def _get_bvr_ref(self, cr, uid, invoice, context=None):
        """Retrieve ESR/BVR reference form invoice in order to print it

        Receive a browse record so it can be overloaded without rebrowsing
        the invoice.
        """
        res = ''
        ## We check if the type is bvr, if not we return false
        if invoice.partner_bank_id.state != 'bvr':
            return ''
        ##
        if invoice.partner_bank_id.bvr_adherent_num:
            res = invoice.partner_bank_id.bvr_adherent_num
        invoice_number = ''
        if invoice.number:
            invoice_number = self._compile_get_ref.sub('', invoice.number)
        return mod10r(res + invoice_number.rjust(26 - len(res), '0'))
Пример #35
0
    def compute_partner_bvr_ref(self, cr, uid, ids, partner=None,
                                is_lsv=False, context=None):
        """ Generates a new BVR Reference.
        See file \\nas\it\devel\Code_ref_BVR.xls for more information."""
        partner = partner or self.browse(cr, uid, ids[0], context).partner_id
        result = '0' * (9 + (7 - len(partner.ref))) + partner.ref
        count_groups = str(self.search(
            cr, uid, [('partner_id', '=', partner.id)], context=context,
            count=True))
        result += '0' * (5 - len(count_groups)) + count_groups
        # Type '0' = Sponsorship
        result += '0'
        result += '0' * 4

        if is_lsv:
            result = '004874969' + result[9:]
        if len(result) == 26:
            return mod10r(result)
Пример #36
0
    def _setup_inv_data(self, journal_ids, invoicer):
        """ Inherit to add BVR ref """
        self.ensure_one()
        inv_data = super(contract_group, self)._setup_inv_data(
            journal_ids, invoicer)

        ref = ''
        if self.bvr_reference:
            ref = self.bvr_reference
        elif (self.payment_term_id and
              (_('LSV') in self.payment_term_id.name or
               _('Direct Debit') in self.payment_term_id.name)):
            seq = self.env['ir.sequence']
            ref = mod10r(seq.next_by_code('contract.bvr.ref'))
        inv_data.update({
            'bvr_reference': ref})

        return inv_data
    def _setup_inv_data(self, cr, uid, con_gr, journal_ids, invoicer_id,
                        context=None):
        """ Inherit to add BVR ref """
        inv_data = super(contract_group, self)._setup_inv_data(
            cr, uid, con_gr, journal_ids, invoicer_id, context)

        ref = ''
        if con_gr.bvr_reference:
            ref = con_gr.bvr_reference
        elif (con_gr.payment_term_id and
              (_('LSV') in con_gr.payment_term_id.name or
               _('Direct Debit') in con_gr.payment_term_id.name)):
            seq = self.pool['ir.sequence']
            ref = mod10r(seq.next_by_code(cr, uid, 'contract.bvr.ref'))
        inv_data.update({
            'bvr_reference': ref})

        return inv_data
    def _setup_inv_data(self, journal_ids, invoicer):
        """ Inherit to add BVR ref """
        self.ensure_one()
        inv_data = super(contract_group, self)._setup_inv_data(
            journal_ids, invoicer)

        ref = ''
        bank_terms = self.env['account.payment.term'].with_context(
            lang='en_US').search(
            ['|', ('name', 'like', 'LSV'), ('name', 'like', 'Postfinance')])
        if self.bvr_reference:
            ref = self.bvr_reference
        elif self.payment_term_id in bank_terms:
            seq = self.env['ir.sequence']
            ref = mod10r(seq.next_by_code('contract.bvr.ref'))
        inv_data.update({
            'bvr_reference': ref})

        return inv_data
Пример #39
0
 def get_bvr_ref(self, cursor, uid, move_line_id, context=None):
     """Retrieve ESR/BVR reference from move line in order to print it"""
     res = ''
     if isinstance(move_line_id, (tuple, list)):
         assert len(move_line_id) == 1, "Only 1 ID expected"
         move_line_id = move_line_id[0]
     move_line = self.browse(cursor, uid, move_line_id, context=context)
     ## We check if the type is bvr, if not we return false
     if move_line.invoice.partner_bank_id.state != 'bvr':
         return ''
     ##
     if move_line.invoice.partner_bank_id.bvr_adherent_num:
         res = move_line.invoice.partner_bank_id.bvr_adherent_num
     move_number = ''
     if move_line.invoice.number:
         move_number = self._compile_get_ref.sub(
             '',
             str(move_line.invoice.number) + str(move_line_id))
     return mod10r(res + move_number.rjust(26 - len(res), '0'))
Пример #40
0
    def _setup_inv_data(self, cr, uid, con_gr, journal_ids, invoicer_id,
                        context=None):
        ''' Inherit to add BVR ref '''
        inv_data = super(contract_group, self)._setup_inv_data(cr, uid, con_gr,
                                                               journal_ids,
                                                               invoicer_id,
                                                               context)

        ref = ''
        if con_gr.bvr_reference:
            ref = con_gr.bvr_reference
        elif (con_gr.payment_term_id and
              (_('LSV') in con_gr.payment_term_id.name or
               _('Direct Debit') in con_gr.payment_term_id.name)):
            seq = self.pool['ir.sequence']
            ref = mod10r(seq.next_by_code(cr, uid, 'contract.bvr.ref'))
        inv_data.update({
            'bvr_reference': ref})

        return inv_data
Пример #41
0
    def _check_9_pos_postal_num(self, number):
        """
        Predicate that checks if a postal number
        is in format xx-xxxxxx-x is correct,
        return true if it matches the pattern
        and if check sum mod10 is ok

        :param number: postal number to validate
        :returns: True if is it a 9 len postal account
        :rtype: bool
        """
        pattern = r'^[0-9]{2}-[0-9]{1,6}-[0-9]$'
        if not re.search(pattern, number):
            return False
        nums = number.split('-')
        prefix = nums[0]
        num = nums[1].rjust(6, '0')
        checksum = nums[2]
        expected_checksum = mod10r(prefix + num)[-1]
        return expected_checksum == checksum
    def _generate_bvr_reference(self, contract, product):
        gift_bvr_ref = {
            'Birthday Gift': 1,
            'General Gift': 2,
            'Family Gift': 3,
            'Project Gift': 4,
            'Graduation Gift': 5
        }
        ref = contract.partner_id.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        num_pol_ga = str(contract.num_pol_ga)
        bvr_reference += '0' * (5 - len(num_pol_ga)) + num_pol_ga
        # Type of gift
        bvr_reference += str(gift_bvr_ref[product.name])
        bvr_reference += '0' * 4

        if contract.group_id.payment_term_id and \
                'LSV' in contract.group_id.payment_term_id.name:
            bvr_reference = '004874969' + bvr_reference[9:]
        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
Пример #43
0
    def action_date_assign(self):
        """Method called when invoice is validated.
            - Add BVR Reference if payment term is LSV and no reference is
              set.
            - Prevent validating invoices missing related contract.
        """
        for invoice in self:
            if invoice.payment_term and 'LSV' in invoice.payment_term.name \
                    and not invoice.bvr_reference:
                seq = self.env['ir.sequence']
                ref = mod10r(seq.next_by_code('contract.bvr.ref'))
                invoice.write({'bvr_reference': ref})
            for invl in invoice.invoice_line:
                if not invl.contract_id and invl.product_id.categ_name in (
                        SPONSORSHIP_CATEGORY, GIFT_CATEGORY):
                    raise exceptions.Warning(
                        _('Sponsorship missing in invoice'),
                        _("Invoice %s for '%s' is missing a sponsorship.") %
                        (str(invoice.id), invoice.partner_id.name))

        return super(account_invoice, self).action_date_assign()
Пример #44
0
    def action_date_assign(self):
        """Method called when invoice is validated.
            - Add BVR Reference if payment term is LSV and no reference is
              set.
            - Prevent validating invoices missing related contract.
        """
        for invoice in self:
            if invoice.payment_term and 'LSV' in invoice.payment_term.name \
                    and not invoice.bvr_reference:
                seq = self.env['ir.sequence']
                ref = mod10r(seq.next_by_code('contract.bvr.ref'))
                invoice.write({'bvr_reference': ref})
            for invl in invoice.invoice_line:
                if not invl.contract_id and invl.product_id.categ_name in (
                        SPONSORSHIP_CATEGORY, GIFT_CATEGORY):
                    raise exceptions.Warning(
                        _('Sponsorship missing in invoice'),
                        _("Invoice %s for '%s' is missing a sponsorship.") %
                        (str(invoice.id), invoice.partner_id.name))

        return super(account_invoice, self).action_date_assign()
Пример #45
0
    def compute_partner_bvr_ref(self, partner=None, is_lsv=False):
        """ Generates a new BVR Reference.
        See file \\nas\it\devel\Code_ref_BVR.xls for more information."""
        self.ensure_one()
        if self.exists():
            # If group was already existing, retrieve any existing reference
            ref = self.bvr_reference
            if ref:
                return ref
        partner = partner or self.partner_id
        result = '0' * (9 + (7 - len(partner.ref))) + partner.ref
        count_groups = str(self.search_count(
            [('partner_id', '=', partner.id)]))
        result += '0' * (5 - len(count_groups)) + count_groups
        # Type '0' = Sponsorship
        result += '0'
        result += '0' * 4

        if is_lsv:
            result = '004874969' + result[9:]
        if len(result) == 26:
            return mod10r(result)
Пример #46
0
    def compute_partner_bvr_ref(self, partner=None, is_lsv=False):
        """ Generates a new BVR Reference.
        See file \\nas\it\devel\Code_ref_BVR.xls for more information."""
        self.ensure_one()
        if self.exists():
            # If group was already existing, retrieve any existing reference
            ref = self.bvr_reference
            if ref:
                return ref
        partner = partner or self.partner_id
        result = '0' * (9 + (7 - len(partner.ref))) + partner.ref
        count_groups = str(self.search_count([('partner_id', '=', partner.id)
                                              ]))
        result += '0' * (5 - len(count_groups)) + count_groups
        # Type '0' = Sponsorship
        result += '0'
        result += '0' * 4

        if is_lsv:
            result = '004874969' + result[9:]
        if len(result) == 26:
            return mod10r(result)
Пример #47
0
    def generate_bvr_reference(self, contract, product):
        product = product.with_context(lang='en_US')
        ref = contract.partner_id.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        num_pol_ga = str(contract.num_pol_ga)
        bvr_reference += '0' * (5 - len(num_pol_ga)) + num_pol_ga
        # Type of gift
        bvr_reference += str(GIFT_NAMES.index(product.name) + 1)
        bvr_reference += '0' * 4

        if contract.group_id.payment_term_id and \
                'LSV' in contract.group_id.payment_term_id.name:
            # Get company BVR adherent number
            user = self.env.user
            bank_obj = self.env['res.partner.bank']
            company_bank = bank_obj.search([
                ('partner_id', '=', user.company_id.partner_id.id),
                ('bvr_adherent_num', '!=', False)])
            if company_bank:
                bvr_reference = company_bank.bvr_adherent_num +\
                    bvr_reference[9:]
        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
    def _generate_bvr_reference(self, contract, product):
        self.ensure_one()
        ref = contract.partner_id.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        num_pol_ga = str(contract.num_pol_ga)
        bvr_reference += '0' * (5 - len(num_pol_ga)) + num_pol_ga
        # Type of gift
        bvr_reference += str(GIFT_NAMES.index(product.name) + 1)
        bvr_reference += '0' * 4

        if contract.group_id.payment_term_id and \
                'LSV' in contract.group_id.payment_term_id.name:
            # Get company BVR adherent number
            user = self.env.user
            bank_obj = self.env['res.partner.bank']
            company_bank = bank_obj.search([
                ('partner_id', '=', user.company_id.partner_id.id),
                ('bvr_adherent_num', '!=', False)])
            if company_bank:
                bvr_reference = company_bank.bvr_adherent_num +\
                    bvr_reference[9:]
        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
Пример #49
0
    def _generate_bvr_reference(self, partner, payment_term):
        ref = partner.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        # Not related to a sponsorship -> NumPole is 0
        bvr_reference += '0' * 5
        # Type for campaign
        bvr_reference += '7'
        # Christmas fund id
        bvr_reference += '0' * 2
        bvr_reference += '23'

        if 'LSV' in payment_term.sudo().name:
            # Get company BVR adherent number
            company = request.env['res.company'].sudo().browse(1)
            bank_obj = request.env['res.partner.bank'].sudo()
            company_bank = bank_obj.search([('partner_id', '=',
                                             company.partner_id.id),
                                            ('bvr_adherent_num', '!=', False)])
            if company_bank:
                bvr_reference = company_bank.bvr_adherent_num + \
                                bvr_reference[9:]
        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
    def _generate_bvr_reference(self, partner, payment_term):
        ref = partner.ref
        bvr_reference = '0' * (9 + (7 - len(ref))) + ref
        # Not related to a sponsorship -> NumPole is 0
        bvr_reference += '0' * 5
        # Type for campaign
        bvr_reference += '7'
        # Christmas fund id
        bvr_reference += '0' * 2
        bvr_reference += '23'

        if 'LSV' in payment_term.sudo().name:
            # Get company BVR adherent number
            company = request.env['res.company'].sudo().browse(1)
            bank_obj = request.env['res.partner.bank'].sudo()
            company_bank = bank_obj.search([
                ('partner_id', '=', company.partner_id.id),
                ('bvr_adherent_num', '!=', False)])
            if company_bank:
                bvr_reference = company_bank.bvr_adherent_num + \
                                bvr_reference[9:]
        if len(bvr_reference) == 26:
            return mod10r(bvr_reference)
Пример #51
0
    def validate_global_context_dict(self):
        super(record_gt826, self).validate_global_context_dict()
        if not self.global_values['reference']:
            raise except_osv(_('Error'),
                             _('You must provide a BVR reference'
                               'number \n for the line: %s') % self.pline.name)

        self.global_values['reference'] = self.global_values['reference'].replace(' ', '')
        if self.is_9_pos_adherent:
            if len(self.global_values['reference']) > 27:
                raise except_osv(_('Error'),
                                 _('BVR reference number is not valid \n for the line: %s. \n'
                                   'Reference is too long.') % self.pline.name)
            # do a mod10 check
            if mod10r(self.global_values['reference'][:-1]) != self.global_values['reference']:
                raise except_osv(_('Error'),
                                 _('BVR reference number is not valid \n for the line: %s. \n'
                                   'Mod10 check failed') % self.pline.name)
            # fill reference with 0
            self.global_values['reference'] = self.global_values['reference'].rjust(27, '0')
        else:
            # reference of BVR adherent with 5 positions number
            # have 15 positions references
            if len(self.global_values['reference']) > 15:
                raise except_osv(_('Error'),
                                 _('BVR reference number is not valid \n'
                                   'for the line: %s. \n Reference is too long '
                                   'for this type of beneficiary.') % self.pline.name)
            # complete 15 first digit with 0 on left and complete 27 digits with trailing spaces
            # exemple: 123456 becomes 00000000012345____________
            self.global_values['reference'] = self.global_values['reference'].rjust(15, '0').ljust(27, ' ')

        if not self.global_values['partner_bvr']:
            raise except_osv(_('Error'),
                             _('You must provide a BVR number\n'
                               'for the bank account: %s'
                               'on line: %s') % (self.pline.bank_id.get_account_number(), self.pline.name))
    def _create_invoice_from_mv_lines(self, mv_line_dicts, invoice=None):
        # Get the attached recurring invoicer
        invoicer = self.statement_id.recurring_invoicer_id
        if not invoicer:
            invoicer_obj = self.env['recurring.invoicer']
            invoicer = invoicer_obj.create({'source': self._name})
            self.statement_id.write({'recurring_invoicer_id': invoicer.id})

        # Generate a unique bvr_reference
        if self.ref and len(self.ref) == 27:
            ref = self.ref
        elif self.ref and len(self.ref) > 27:
            ref = mod10r(self.ref[:26])
        else:
            ref = mod10r(
                (self.date.replace('-', '') + str(self.statement_id.id) +
                 str(self.id)).ljust(26, '0'))

        if invoice:
            invoice.action_cancel()
            invoice.action_cancel_draft()
            invoice.write({'recurring_invoicer_id': invoicer.id})

        else:
            # Lookup for an existing open invoice matching the criterias
            invoices = self._find_open_invoice(mv_line_dicts)
            if invoices:
                # Get the bvr reference of the invoice or set it
                invoice = invoices[0]
                invoice.write({'recurring_invoicer_id': invoicer.id})
                if invoice.bvr_reference and not self.ref:
                    ref = invoice.bvr_reference
                else:
                    invoice.write({'bvr_reference': ref})
                self.write({'ref': ref, 'invoice_id': invoice.id})
                return True

            # Setup a new invoice if no existing invoice is found
            journal_id = self.env['account.journal'].search(
                [('type', '=', 'sale')], limit=1).id
            if self.journal_id.code == 'BVR':
                payment_term_id = self.env.ref(
                    'contract_compassion.payment_term_bvr').id
            else:
                payment_term_id = self.env.ref(
                    'contract_compassion.payment_term_virement').id
            inv_data = {
                'account_id': self.partner_id.property_account_receivable.id,
                'type': 'out_invoice',
                'partner_id': self.partner_id.id,
                'journal_id': journal_id,
                'date_invoice': self.date,
                'payment_term': payment_term_id,
                'bvr_reference': ref,
                'recurring_invoicer_id': invoicer.id,
                'currency_id': self.statement_id.currency.id,
            }
            invoice = self.env['account.invoice'].create(inv_data)

        for mv_line_dict in mv_line_dicts:
            product = self.env['product.product'].browse(
                mv_line_dict['product_id'])
            sponsorship_id = mv_line_dict.get('sponsorship_id')
            if not sponsorship_id:
                related_contracts = invoice.mapped('invoice_line.contract_id')
                if related_contracts:
                    sponsorship_id = related_contracts[0].id
            contract = self.env['recurring.contract'].browse(sponsorship_id)
            if product.name == GIFT_NAMES[0] and contract and \
                    contract.child_id and contract.child_id.birthdate:
                invoice.date_invoice = self.env[
                    'generate.gift.wizard'].compute_date_birthday_invoice(
                        contract.child_id.birthdate, self.date)

            amount = mv_line_dict['credit']
            inv_line_data = {
                'name':
                self.name,
                'account_id':
                product.property_account_income.id,
                'price_unit':
                amount,
                'price_subtotal':
                amount,
                'contract_id':
                contract.id,
                'user_id':
                mv_line_dict.get('user_id'),
                'quantity':
                1,
                'uos_id':
                False,
                'product_id':
                product.id,
                'partner_id':
                contract.partner_id.id if contract else self.partner_id.id,
                'invoice_id':
                invoice.id,
                # Remove analytic account from bank journal item:
                # it is only useful in the invoice journal item
                'account_analytic_id':
                mv_line_dict.pop(
                    'analytic_account_id',
                    self.env['account.analytic.default'].account_get(
                        product.id, self.partner_id.id).analytic_id.id)
            }

            if product.categ_name in (GIFT_CATEGORY,
                                      SPONSORSHIP_CATEGORY) and not contract:
                raise exceptions.Warning(_('A field is required'),
                                         _('Add a Sponsorship'))

            self.env['account.invoice.line'].create(inv_line_data)
            # Put payer as partner
            if contract:
                invoice.partner_id = contract.partner_id

        invoice.button_compute()
        invoice.signal_workflow('invoice_open')
        self.ref = ref

        # Update move_lines data
        counterpart_id = invoice.move_id.line_id.filtered(
            lambda ml: ml.debit > 0).id
        for mv_line_dict in mv_line_dicts:
            mv_line_dict['counterpart_move_line_id'] = counterpart_id
            if 'sponsorship_id' in mv_line_dict:
                del mv_line_dict['sponsorship_id']
        return counterpart_id
    def _create_invoice_from_mv_lines(self, mv_line_dicts, invoice=None):
        # Get the attached recurring invoicer
        invoicer = self.statement_id.recurring_invoicer_id
        if not invoicer:
            invoicer_obj = self.env['recurring.invoicer']
            invoicer = invoicer_obj.create({'source': self._name})
            self.statement_id.write({'recurring_invoicer_id': invoicer.id})

        # Generate a unique bvr_reference
        if self.ref and len(self.ref) == 27:
            ref = self.ref
        elif self.ref and len(self.ref) > 27:
            ref = mod10r(self.ref[:26])
        else:
            ref = mod10r((self.date.replace('-', '') + str(
                self.statement_id.id) + str(self.id)).ljust(26, '0'))

        if invoice:
            invoice.action_cancel()
            invoice.action_cancel_draft()
            invoice.write({'recurring_invoicer_id': invoicer.id})

        else:
            # Lookup for an existing open invoice matching the criterias
            invoices = self._find_open_invoice(mv_line_dicts)
            if invoices:
                # Get the bvr reference of the invoice or set it
                invoice = invoices[0]
                invoice.write({'recurring_invoicer_id': invoicer.id})
                if invoice.bvr_reference and not self.ref:
                    ref = invoice.bvr_reference
                else:
                    invoice.write({'bvr_reference': ref})
                self.write({
                    'ref': ref,
                    'invoice_id': invoice.id})
                return True

            # Setup a new invoice if no existing invoice is found
            journal_id = self.env['account.journal'].search(
                [('type', '=', 'sale')], limit=1).id
            if self.journal_id.code == 'BVR':
                payment_term_id = self.env.ref(
                    'contract_compassion.payment_term_bvr').id
            else:
                payment_term_id = self.env.ref(
                    'contract_compassion.payment_term_virement').id
            inv_data = {
                'account_id': self.partner_id.property_account_receivable.id,
                'type': 'out_invoice',
                'partner_id': self.partner_id.id,
                'journal_id': journal_id,
                'date_invoice': self.date,
                'payment_term': payment_term_id,
                'bvr_reference': ref,
                'recurring_invoicer_id': invoicer.id,
                'currency_id': self.statement_id.currency.id,
            }
            invoice = self.env['account.invoice'].create(inv_data)

        for mv_line_dict in mv_line_dicts:
            product = self.env['product.product'].browse(
                mv_line_dict['product_id'])
            sponsorship_id = mv_line_dict.get('sponsorship_id')
            if not sponsorship_id:
                related_contracts = invoice.mapped('invoice_line.contract_id')
                if related_contracts:
                    sponsorship_id = related_contracts[0].id
            contract = self.env['recurring.contract'].browse(sponsorship_id)
            if product.name == GIFT_NAMES[0] and contract and \
                    contract.child_id and contract.child_id.birthdate:
                invoice.date_invoice = self.env[
                    'generate.gift.wizard'].compute_date_birthday_invoice(
                    contract.child_id.birthdate, self.date)

            amount = mv_line_dict['credit']
            inv_line_data = {
                'name': self.name,
                'account_id': product.property_account_income.id,
                'price_unit': amount,
                'price_subtotal': amount,
                'contract_id': contract.id,
                'user_id': mv_line_dict.get('user_id'),
                'quantity': 1,
                'uos_id': False,
                'product_id': product.id,
                'partner_id': contract.partner_id.id if contract else
                self.partner_id.id,
                'invoice_id': invoice.id,
                # Remove analytic account from bank journal item:
                # it is only useful in the invoice journal item
                'account_analytic_id': mv_line_dict.pop(
                    'analytic_account_id',
                    self.env['account.analytic.default'].account_get(
                        product.id, self.partner_id.id).analytic_id.id)
            }

            if product.categ_name in (
                    GIFT_CATEGORY, SPONSORSHIP_CATEGORY) and not contract:
                raise exceptions.Warning(_('A field is required'),
                                         _('Add a Sponsorship'))

            self.env['account.invoice.line'].create(inv_line_data)
            # Put payer as partner
            if contract:
                invoice.partner_id = contract.partner_id

        invoice.button_compute()
        invoice.signal_workflow('invoice_open')
        self.ref = ref

        # Update move_lines data
        counterpart_id = invoice.move_id.line_id.filtered(
            lambda ml: ml.debit > 0).id
        for mv_line_dict in mv_line_dicts:
            mv_line_dict['counterpart_move_line_id'] = counterpart_id
            if 'sponsorship_id' in mv_line_dict:
                del mv_line_dict['sponsorship_id']
        return counterpart_id
def get_pz(ref_number):
    number = 0
    number += mod10r(ref_number)
    return number
Пример #55
0
    def _create_invoice_from_line(self, cr, uid, b_line, context=None):
        if not b_line.product_id:
            return True
        # Get the attached recurring invoicer
        invoicer = b_line.statement_id.recurring_invoicer_id
        invoice_obj = self.pool.get('account.invoice')
        if not invoicer:
            invoicer_obj = self.pool.get('recurring.invoicer')
            invoicer_id = invoicer_obj.create(cr, uid, {'source': self._name},
                                              context)
            b_line.statement_id.write(
                {'recurring_invoicer_id': invoicer_id})
            invoicer = invoicer_obj.browse(cr, uid, invoicer_id, context)

        # Generate a unique bvr_reference
        ref = mod10r((b_line.date.replace('-', '') + str(
            b_line.statement_id.id) + str(b_line.id)).ljust(26, '0'))

        # Lookup for an existing open invoice matching the criterias
        invoice_ids = self._find_open_invoice(cr, uid, b_line, context)
        if invoice_ids:
            # Get the bvr reference of the invoice or set it
            invoice = invoice_obj.browse(cr, uid, invoice_ids[0], context)
            invoice.write({'recurring_invoicer_id': invoicer.id})
            if invoice.bvr_reference:
                ref = invoice.bvr_reference
            else:
                invoice.write({'bvr_reference': ref})
            b_line.write({
                'ref': ref,
                'invoice_id': invoice.id})
            return True

        # Setup a new invoice if no existing invoice is found
        journal_ids = self.pool.get('account.journal').search(
            cr, uid, [('type', '=', 'sale')], limit=1)
        payment_term_ids = self.pool.get('account.payment.term').search(
            cr, uid, [('name', '=', 'Bank Transfer')],
            context={'lang': 'en_US'})
        inv_data = {
            'account_id': b_line.partner_id.property_account_receivable.id,
            'type': 'out_invoice',
            'partner_id': b_line.partner_id.id,
            'journal_id': journal_ids[0] if journal_ids else False,
            'date_invoice': b_line.date,
            'payment_term': payment_term_ids and payment_term_ids[0] or 1,
            'bvr_reference': ref,
            'recurring_invoicer_id': invoicer.id,
            'currency_id': b_line.statement_id.currency.id,
        }
        if b_line.product_id.name == GIFT_NAMES[0] and b_line.contract_id \
                and b_line.contract_id.child_id and \
                b_line.contract_id.child_id.birthdate:
            inv_data['date_invoice'] = self.pool.get(
                'generate.gift.wizard').compute_date_birthday_invoice(
                b_line.contract_id.child_id.birthdate, b_line.date)
        invoice_id = invoice_obj.create(cr, uid, inv_data, context)

        inv_line_data = {
            'name': b_line.name,
            'account_id': b_line.product_id.property_account_income.id,
            'price_unit': b_line.amount,
            'price_subtotal': b_line.amount,
            'contract_id': b_line.contract_id and
            b_line.contract_id.id or False,
            'user_id': b_line.user_id and b_line.user_id.id or False,
            'quantity': 1,
            'uos_id': False,
            'product_id': b_line.product_id.id,
            'partner_id': b_line.partner_id.id,
            'invoice_id': invoice_id,
        }

        if b_line.product_id.categ_name in (GIFT_CATEGORY,
                                            SPONSORSHIP_CATEGORY) and not \
                b_line.contract_id:
            raise orm.except_orm(_('A field is required'),
                                 _('Add a Sponsorship'))

        if b_line.analytic_account_id:
            inv_line_data['account_analytic_id'] = \
                b_line.analytic_account_id.id
        else:
            analytic = self.pool.get('account.analytic.default').account_get(
                cr, uid, b_line.product_id.id, b_line.partner_id.id, uid,
                time.strftime('%Y-%m-%d'), context=context)
            if analytic and analytic.analytics_id:
                inv_line_data['analytics_id'] = analytic.analytics_id.id

        self.pool.get('account.invoice.line').create(
            cr, uid, inv_line_data, context)

        invoice_obj.button_compute(cr, uid, [invoice_id], context)
        b_line.write({
            'ref': ref,
            'invoice_id': invoice_id})

        return True