예제 #1
0
    def __register__(cls, module_name):
        pool = Pool()
        Party = pool.get('party.party')
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().connection.cursor()
        party = Party.__table__()

        super(PartyIdentifier, cls).__register__(module_name)

        party_h = TableHandler(Party, module_name)
        if (party_h.column_exist('vat_number')
                and party_h.column_exist('vat_country')):
            identifiers = []
            cursor.execute(*party.select(party.id,
                                         party.vat_number,
                                         party.vat_country,
                                         where=(party.vat_number != Null)
                                         | (party.vat_country != Null)))
            for party_id, number, country in cursor.fetchall():
                code = (country or '') + (number or '')
                if not code:
                    continue
                type = None
                if vat.is_valid(code):
                    type = 'eu_vat'
                identifiers.append(cls(party=party_id, code=code, type=type))
            cls.save(identifiers)
            party_h.drop_column('vat_number')
            party_h.drop_column('vat_country')
예제 #2
0
파일: party.py 프로젝트: kret0s/tryton3_8
 def check_code(self):
     if self.type == 'eu_vat':
         if not vat.is_valid(self.code):
             self.raise_user_error('invalid_vat', {
                     'code': self.code,
                     'party': self.party.rec_name,
                     })
예제 #3
0
파일: party.py 프로젝트: kret0s/tryton3_8
    def __register__(cls, module_name):
        pool = Pool()
        Party = pool.get('party.party')
        TableHandler = backend.get('TableHandler')
        cursor = Transaction().cursor
        party = Party.__table__()

        super(PartyIdentifier, cls).__register__(module_name)

        party_h = TableHandler(cursor, Party, module_name)
        if (party_h.column_exist('vat_number')
                and party_h.column_exist('vat_country')):
            identifiers = []
            cursor.execute(*party.select(
                    party.id, party.vat_number, party.vat_country,
                    where=(party.vat_number != Null)
                    | (party.vat_country != Null)))
            for party_id, number, country in cursor.fetchall():
                code = (country or '') + (number or '')
                if not code:
                    continue
                type = None
                if vat.is_valid(code):
                    type = 'eu_vat'
                identifiers.append(
                    cls(party=party_id, code=code, type=type))
            cls.save(identifiers)
            party_h.drop_column('vat_number')
            party_h.drop_column('vat_country')
예제 #4
0
def Validate(begin, end, items):

    content = []

    for i in items:
        errors = []
        d = i.info.invoice_date
        if d < begin or d > end:
            errors.append(
                "Data <b>{}</b> wykracza poza okres raportu: <b>{}</b> - <b>{}</b>"
                .format(escape(str(d)), escape(str(begin)), escape(str(end))))

        if not nip.is_valid(i.info.merchant_nip):
            if not vat.is_valid(i.info.merchant_nip):
                errors.append("NIP <b>{}</b> jest nieprawidłowy".format(
                    escape(i.info.merchant_nip)))
        else:
            imerchant_nip = nip.compact(i.info.merchant_nip)

        if errors:
            content.append("Pozycja <b>{}</b> <small>({})</small>".format(
                escape(','.join(i.invoice_pos)), escape(i.info.merchant_name)))
            content.append("""<ul class="errors">""")

            for err in errors:
                content.append("<li>{}</li>".format(err))

            content.append("""</ul>""")

    return content
예제 #5
0
 def check_code(self):
     if self.type == 'eu_vat':
         if not vat.is_valid(self.code):
             self.raise_user_error('invalid_vat', {
                     'code': self.code,
                     'party': self.party.rec_name,
                     })
예제 #6
0
 def check_code(self):
     if self.type == 'eu_vat':
         if not vat.is_valid(self.code):
             if self.party and self.party.id > 0:
                 party = self.party.rec_name
             else:
                 party = ''
             self.raise_user_error('invalid_vat', {
                 'code': self.code,
                 'party': party,
             })
예제 #7
0
파일: party.py 프로젝트: coopengo/party
 def check_code(self):
     if self.type == 'eu_vat':
         if not vat.is_valid(self.code):
             if self.party and self.party.id > 0:
                 party = self.party.rec_name
             else:
                 party = ''
             self.raise_user_error('invalid_vat', {
                     'code': self.code,
                     'party': party,
                     })
예제 #8
0
    def __init__(self, invoice_number, invoice_date, ship_date, merchant_nip,
                 merchant_name, merchant_adr, country, codes):
        self.invoice_number = invoice_number
        self.invoice_date = invoice_date
        self.ship_date = ship_date

        self.merchant_name = merchant_name
        self.merchant_adr = merchant_adr
        self.country = country
        self.codes = codes

        if nip.is_valid(merchant_nip):
            self.merchant_nip = nip.compact(merchant_nip)
            self.is_eu_vat = False
        elif vat.is_valid(merchant_nip):
            self.merchant_nip = vat.compact(merchant_nip)
            self.is_eu_vat = True
        else:
            self.merchant_nip = merchant_nip
            self.is_eu_vat = None
def get_and_check_data(doc, data_sheet):
    fields = {
        'issuer_name': {
            'type': 'char',
            'required': True,
            'line': 3,
        },
        'issuer_vat_number': {
            'type': 'char',
            'required': False,
            'line': 4,
        },
        'issuer_siret': {
            'type': 'char',
            'required': False,
            'line': 5,
        },
        'issuer_country_code': {
            'type': 'char',
            'required': True,
            'line': 6,
        },
        'customer_name': {
            'type': 'char',
            'required': True,
            'line': 8,
        },
        'customer_vat_number': {
            'type': 'char',
            'required': False,
            'line': 9,
        },
        'customer_siret': {
            'type': 'char',
            'required': False,
            'line': 10,
        },
        'customer_country_code': {
            'type': 'char',
            'required': True,
            'line': 11,
        },
        'customer_chorus_service_code': {
            'type': 'char',
            'required': False,
            'line': 12,
        },
        'invoice_or_refund': {
            'type': 'char',
            'required': False,
            'line': 14,
        },
        'customer_order_ref': {
            'type': 'char',
            'required': False,
            'line': 15,
        },
        'invoice_number': {
            'type': 'char',
            'required': True,
            'line': 16,
        },
        'invoice_date': {
            'type': 'date',
            'required': True,
            'line': 17,
        },
        'invoice_currency': {
            'type': 'char',
            'required': True,
            'line': 18,
        },
        'total_without_tax': {
            'type': 'float',
            'required': True,
            'line': 20,
        },
        'total_tax': {
            'type': 'float',
            'required': True,
            'line': 21,
        },
        'total_with_tax': {
            'type': 'float',
            'required': True,
            'line': 22,
        },
        'total_due': {
            'type': 'float',
            'required': True,
            'line': 23,
        },
        'attachment_count': {
            'type': 'int',
            'required': False,
            'line': 25,
        },
    }

    data = {}
    # Read data
    for field, fdict in fields.items():
        valuecell = data_sheet.getCellByPosition(1, fdict['line'] - 1)
        labelcell = data_sheet.getCellByPosition(0, fdict['line'] - 1)
        fdict['label'] = labelcell.String
        if fdict['type'] == 'float':
            value = valuecell.Value
        elif fdict['type'] == 'int':
            value = valuecell.Value
            try:
                value = int(value)
            except Exception:
                value = 0
        elif fdict['type'] == 'date':
            # when the cell is not recognised as a date, valuecell.Value = 0.0
            if valuecell.Value < 2:
                return msg_box(
                    doc,
                    _("In the second tab, cell B%s (%s) doesn't seem to be a date field. Check that the type of the cell has a date format. For that, right clic on the cell and select 'Format Cells': in the first tab, select 'Date' as 'Category' and check that the selected 'Format' matches the format currently used in the cell."
                      ) % (fdict['line'], fdict['label']))
            date_as_int = int(valuecell.Value)
            value = datetime.fromordinal(
                datetime(1900, 1, 1).toordinal() + date_as_int - 2)
        else:
            value = valuecell.String
        # check required fields are set
        if fdict['required']:
            if fdict['type'] in ('date', 'char') and not value:
                return msg_box(
                    doc,
                    _("In the second tab, cell B%s (%s) is a required field but it is currently empty or its type is wrong."
                      ) % (fdict['line'], fdict['label']))
            elif fdict['type'] == 'float' and not value:
                value = 0.0
        if value or (fdict['type'] in ('float', 'int') and fdict['required']):
            data[field] = value

    # Check data
    for field, fdict in fields.items():
        if field in data:
            value_display = data[field]
            if fdict['type'] == 'date':
                value_display = data[field].strftime('%d %B %Y')
            msg_start = _(
                "In the second tab, the value of cell B%s (%s) is '%s';") % (
                    fdict['line'], fdict['label'], value_display)
            msg_start += ' '
            # check type
            if fdict['type'] == 'float':
                if not isinstance(data[field], float):
                    return msg_box(doc, msg_start + _("it must be a float."))
                if data[field] < 0:
                    return msg_box(doc, msg_start + _("it must be positive."))
            elif fdict['type'] == 'int':
                if not isinstance(data[field], int):
                    return msg_box(doc,
                                   msg_start + _("it must be an integer."))
                if data[field] < 0:
                    return msg_box(doc, msg_start + _("it must be positive."))
            elif fdict['type'] == 'date':
                if not isinstance(data[field], datetime):
                    return msg_box(doc, msg_start + _("it must be a date."))
            elif fdict['type'] == 'char':
                if not isinstance(data[field], str):
                    return msg_box(doc, msg_start + _("it must be a string."))
                data[field] = data[field].strip()
            # check specific fields
            if field.endswith('country_code'):  # required field
                if len(data[field]) != 2 or not data[field].isalpha():
                    return msg_box(
                        doc,
                        msg_start + _("country codes must have 2 letters."))
                data[field] = data[field].upper()
            if field.endswith('_siret') and data[field]:
                data[field] = data[field].replace(' ', '')
                try:
                    validate(data[field])
                except (InvalidChecksum, InvalidComponent, InvalidFormat,
                        InvalidLength) as e:
                    return msg_box(doc, msg_start + str(e))
            if field.endswith('_vat_number'):
                data[field] = data[field].replace(' ', '').upper()
                if data[field].startswith('CHE'):
                    if not ch_is_valid(data[field]):
                        return msg_box(
                            doc, msg_start + _("this VAT number is invalid."))
                else:
                    if not is_valid(data[field]):
                        return msg_box(
                            doc, msg_start + _("this VAT number is invalid."))
            if field == 'invoice_currency':  # required field
                if len(data[field]) != 3 or not data[field].isalpha():
                    return msg_box(
                        doc,
                        msg_start + _("currency codes must have 3 letters."))
                data[field] = data[field].upper()
            elif field == 'invoice_date':
                max_future_days = 3
                max_past_years = 5
                near_future = datetime.today() + timedelta(
                    days=max_future_days)
                # I want to stick to the standard lib, so I don't use relativedelta
                distant_past = datetime.today() - timedelta(
                    days=max_past_years * 365)
                if data['invoice_date'] > near_future or data[
                        'invoice_date'] < distant_past:
                    return msg_box(
                        doc, msg_start +
                        _("this date must be today or within the %d past years or within the %d next days."
                          ) % (max_past_years, max_future_days))

    # Global checks
    if data['issuer_country_code'] == 'FR' and not data.get('issuer_siret'):
        return msg_box(
            doc,
            _("In the second tab, cell B%s (%s) must have a value because the issuer's country is France."
              ) %
            (fields['issuer_siret']['line'], fields['issuer_siret']['label']))
    diff = data['total_with_tax'] - data['total_without_tax'] - data[
        'total_tax']
    if abs(diff) > 0.00001:
        return msg_box(
            doc,
            _("In the second tab, the value of cell B%s (%s: %s) must be equal to the value of cell B%s (%s: %s) plus cell B%s (%s: %s)."
              ) % (fields['total_with_tax']['line'],
                   fields['total_with_tax']['label'], data['total_with_tax'],
                   fields['total_without_tax']['line'],
                   fields['total_without_tax']['label'],
                   data['total_without_tax'], fields['total_tax']['line'],
                   fields['total_tax']['label'], data['total_tax']))
    if data['total_due'] - 0.00001 > data['total_with_tax']:
        return msg_box(
            doc,
            _("In the second tab, the value of cell B%s (%s: %s) cannot be superior to the value of cell B%s (%s: %s)."
              ) % (fields['total_due']['line'], fields['total_due']['label'],
                   data['total_due'], fields['total_with_tax']['line'],
                   fields['total_with_tax']['label'], data['total_with_tax']))
    if not data.get('invoice_or_refund'):
        data['invoice_or_refund'] = '380'  # default value is invoice
    elif data['invoice_or_refund'].lower() in INVOICE_REFUND_LANG:
        data['invoice_or_refund'] = INVOICE_REFUND_LANG[
            data['invoice_or_refund'].lower()]
    else:
        return msg_box(
            doc,
            _("In the second tab, the value of cell B%s (%s) is '%s'; it must be either 'invoice' or 'refund'."
              ) %
            (fields['invoice_or_refund']['line'],
             fields['invoice_or_refund']['label'], data['invoice_or_refund']))
    return data
예제 #10
0
    def esale_create_party(self, shop, values):
        '''
        Create Party
        :param shop: obj
        :param values: dict
        return party object
        '''
        pool = Pool()
        Party = pool.get('party.party')
        Identifier = pool.get('party.identifier')
        ContactMechanism = pool.get('party.contact_mechanism')

        vat_code = values.get('vat_code')
        vat_country = values.get('vat_country')

        is_vat = False
        if vat_country and vat_code:
            code = '%s%s' % (vat_country.upper(), vat_code)
            if vat.is_valid(code):
                vat_code = code
                is_vat = True

        #  Search party by:
        #  - VAT country + VAT code
        #  - VAT code
        #  - Party eSale Email
        #  - Party Email

        # search by VAT
        if shop.esale_get_party_by_vat and vat_code:
            parties = Party.search([
                ('identifier_code', '=', vat_code),
            ],
                                   limit=1)
            if not parties and is_vat:
                parties = Party.search([
                    ('identifier_code', '=', vat_code[2:]),
                ],
                                       limit=1)
            if parties:
                party, = parties
                return party

        # search by esale email
        if values.get('esale_email'):
            parties = Party.search([
                ('esale_email', '=', values.get('esale_email')),
            ],
                                   limit=1)
            if parties:
                party, = parties
                return party

            # search by mechanism email
            mechanisms = ContactMechanism.search([
                ('type', '=', 'email'),
                ('value', '=', values.get('esale_email')),
            ],
                                                 limit=1)
            if mechanisms:
                mechanism, = mechanisms
                return mechanism.party

        # not found, create
        party = Party()
        for k, v in values.items():
            if k not in _ESALE_PARTY_EXCLUDE_FIELDS:
                setattr(party, k, v)
        party.addresses = None
        if vat_code:
            identifier = Identifier()
            identifier.code = vat_code
            identifier.type = 'eu_vat' if is_vat else None
            party.identifiers = [identifier]
        party.save()
        logger.info('Shop %s. Created party ID %s' % (shop.name, party.id))
        return party