Beispiel #1
0
 def to_python(self, value):
     if isinstance(value, IncompleteDate):
         return value
     if isinstance(value, datetime.date):
         # ~ return IncompleteDate(value.strftime("%Y-%m-%d"))
         # ~ return IncompleteDate(d2iso(value))
         return IncompleteDate.from_date(value)
     if value:
         return IncompleteDate.parse(value)
     return ""
Beispiel #2
0
 def to_python(self, value):
     if isinstance(value, IncompleteDate):
         return value
     if isinstance(value, datetime.date):
         #~ return IncompleteDate(value.strftime("%Y-%m-%d"))
         #~ return IncompleteDate(d2iso(value))
         return IncompleteDate.from_date(value)
     if value:
         return IncompleteDate.parse(value)
     return ''
Beispiel #3
0
 def date_converter(self,v):
     if not v: return None
     if isinstance(v,basestring):
         v = string2date(v)
         return IncompleteDate.from_date(v)
         #~ return v
     t = xldate_as_tuple(v,self.book.datemode)
     assert len(t) == 6
     t = t[:3]
     #~ print t
     return IncompleteDate(*t)
Beispiel #4
0
 def date_converter(self, v):
     if not v:
         return None
     if isinstance(v, basestring):
         v = string2date(v)
         return IncompleteDate.from_date(v)
     try:
         t = xldate_as_tuple(v, self.book.datemode or 0)
     except XLDateError as e:
         dd.logger.info("Failed to read date %s : %s", v, e)
         return None
     assert len(t) == 6
     t = t[:3]
     return IncompleteDate(*t)
Beispiel #5
0
 def parse_form_value(self, v, obj):
     if v:
         v = IncompleteDate(*settings.SITE.parse_date(v))
         # v = datetime.date(*settings.SITE.parse_date(v))
     return v
Beispiel #6
0
    def card2client(cls, data):
        "does the actual conversion"

        self = cls

        from lino.utils import ssin
        from lino.api import dd, rt
        from lino.mixins.beid import BeIdCardTypes
        from lino.utils import join_words
        from lino.utils import IncompleteDate
        from lino_xl.lib.contacts.utils import street2kw

        countries = dd.resolve_app('countries', strict=True)

        kw = dict()
        #~ def func(fldname,qname):
        #~ kw[fldname] = data[qname]
        kw.update(national_id=ssin.format_ssin(data['nationalNumber']))
        kw.update(first_name=join_words(data['firstName1'], data['firstName2'],
                                        data['firstName3']))
        #~ func('first_name','firstName1')
        kw.update(last_name=data['surname'])

        card_number = data['cardNumber']

        if 'picture' in data:
            fn = self.card_number_to_picture_file(card_number)
            if os.path.exists(fn):
                logger.warning("Overwriting existing image file %s.", fn)
            fp = file(fn, 'wb')
            fp.write(base64.b64decode(data['picture']))
            fp.close()
            #~ print 20121117, repr(data['picture'])
            #~ kw.update(picture_data_encoded=data['picture'])

        #~ func('card_valid_from','validityBeginDate')
        #~ func('card_valid_until','validityEndDate')
        #~ func('birth_date','birthDate')
        kw.update(birth_date=IncompleteDate(
            *settings.SITE.parse_date(data['birthDate'])))
        kw.update(card_valid_from=datetime.date(
            *settings.SITE.parse_date(data['validityBeginDate'])))
        kw.update(card_valid_until=datetime.date(
            *settings.SITE.parse_date(data['validityEndDate'])))
        kw.update(card_number=card_number)
        kw.update(card_issuer=data['issuingMunicipality'])
        kw.update(noble_condition=data['nobleCondition'])
        kw.update(street=data['street'])
        kw.update(street_no=data['streetNumber'])
        kw.update(street_box=data['boxNumber'])
        if kw['street'] and not (kw['street_no'] or kw['street_box']):
            kw = street2kw(kw['street'], **kw)
        kw.update(zip_code=data['zipCode'])
        kw.update(birth_place=data['birthLocation'])
        pk = data['country'].upper()

        msg1 = "BeIdReadCardToClientAction %s" % kw.get('national_id')

        #~ try:
        country = countries.Country.objects.get(isocode=pk)
        kw.update(country=country)
        #~ except countries.Country.DoesNotExist,e:
        #~ except Exception,e:
        #~ logger.warning("%s : no country with code %r",msg1,pk)
        #~ BE = countries.Country.objects.get(isocode='BE')
        #~ fld = countries.Place._meta.get_field()
        kw.update(city=countries.Place.lookup_or_create(
            'name', data['municipality'], country=country))

        def sex2gender(sex):
            if sex == 'M':
                return dd.Genders.male
            if sex in 'FVW':
                return dd.Genders.female
            logger.warning("%s : invalid gender code %r", msg1, sex)

        kw.update(gender=sex2gender(data['sex']))

        if False:

            def nationality2country(nationality):
                try:
                    return countries.Country.objects.get(
                        nationalities__icontains=nationality)
                except countries.Country.DoesNotExist, e:
                    logger.warning("%s : no country for nationality %r", msg1,
                                   nationality)
                except MultipleObjectsReturned, e:
                    logger.warning(
                        "%s : found more than one country for nationality %r",
                        msg1, nationality)
Beispiel #7
0
 def from_db_value(self, value, expression, connection, context):
     return IncompleteDate.parse(value) if value else self.get_default()
Beispiel #8
0
    def card2client(self, data):
        """
        Convert the data coming from the card into database fields to be
        stored in the card holder.
        """
        kw = dict()
        # raw_data = data['card_data']

        kw.update(national_id=ssin.format_ssin(str(data.national_number)))
        kw.update(first_name=data.firstnames or '')
        kw.update(middle_name=data.first_letter_of_third_given_name or '')
        kw.update(last_name=data.surname or '')

        card_number = str(data.card_number)
        holder_model = dd.plugins.beid.holder_model

        if data.PHOTO_FILE:
            if not card_number:
                raise Exception("20150730 photo data but no card_number ")

            fn = holder_model.card_number_to_image_path(card_number)
            if not fn.exists():
                # logger.warning("Overwriting existing image file %s.", fn)
                rt.makedirs_if_missing(os.path.dirname(fn))
            try:
                fp = open(fn, 'wb')
                # fp.write(data.PHOTO_FILE)
                fp.write(base64.b64decode(data.PHOTO_FILE))
                fp.close()
            except IOError as e:
                logger.warning("Failed to store image file %s : %s", fn, e)

            #~ print 20121117, repr(data['picture'])
            #~ kw.update(picture_data_encoded=data['picture'])

        if isinstance(data.date_of_birth, six.string_types):
            data.date_of_birth = IncompleteDate.parse(data.date_of_birth)
            # IncompleteDate(
            #     *data.date_of_birth.split('-'))
        kw.update(birth_date=data.date_of_birth)
        kw.update(
            card_valid_from=dateparser.parse(data.validity_begin_date).date())
        kw.update(
            card_valid_until=dateparser.parse(data.validity_end_date).date())

        kw.update(card_number=card_number)
        kw.update(card_issuer=data.issuing_municipality)
        if data.nobility:
            kw.update(noble_condition=data.nobility)
        if data.address_street_and_number:
            kw = street2kw(data.address_street_and_number, **kw)
        if data.address_zip:
            kw.update(zip_code=str(data.address_zip))
        if data.location_of_birth:
            kw.update(birth_place=data.location_of_birth)

        pk = data.eidreader_country
        country = rt.models.countries.Country.objects.get(isocode=pk)
        kw.update(country=country)
        if data.address_municipality:
            kw.update(city=rt.models.countries.Place.lookup_or_create(
                'name', data.address_municipality, country=country))

        msg1 = "BeIdReadCardToClientAction %s" % kw.get('national_id')

        def sex2gender(sex):
            c0 = sex[0].upper()
            if c0 == 'M':
                return dd.Genders.male
            if c0 in 'FWV':
                return dd.Genders.female
            logger.warning("%s : invalid gender code %r", msg1, sex)

        kw.update(gender=sex2gender(data.gender))

        def doctype2cardtype(dt):
            #~ if dt == 1: return BeIdCardTypes.get_by_value("1")
            rv = BeIdCardTypes.get_by_value(str(dt))
            # logger.info("20130103 documentType %r --> %r", dt, rv)
            return rv

        kw.update(card_type=doctype2cardtype(data.document_type))
        return kw
Beispiel #9
0
    def card2client_java(self, data):
        """
        Convert the data coming from the card into database fields to be
        stored in the card holder.
        """
        kw = dict()
        # raw_data = data['card_data']

        kw.update(national_id=ssin.format_ssin(str(data.nationalNumber)))
        kw.update(first_name=data.firstName or '')
        kw.update(middle_name=data.middleName or '')
        kw.update(last_name=data.name or '')

        card_number = str(data.cardNumber)

        if data.photo:
            if not card_number:
                raise Exception("20150730 photo data but no card_number ")
            fn = dd.plugins.beid.holder_model.card_number_to_image_path(
                card_number)
            if fn.exists():
                logger.warning("Overwriting existing image file %s.", fn)
            try:
                fp = file(fn, 'wb')
                fp.write(base64.b64decode(data.photo))
                fp.close()
            except IOError as e:
                logger.warning("Failed to store image file %s : %s", fn, e)

            #~ print 20121117, repr(data['picture'])
            #~ kw.update(picture_data_encoded=data['picture'])

        if isinstance(data.dateOfBirth, basestring):
            data.dateOfBirth = IncompleteDate(*data.dateOfBirth.split('-'))
        kw.update(birth_date=data.dateOfBirth)
        kw.update(card_valid_from=data.cardValidityDateBegin)
        kw.update(card_valid_until=data.cardValidityDateEnd)

        kw.update(card_number=card_number)
        kw.update(card_issuer=data.cardDeliveryMunicipality)
        if data.nobleCondition:
            kw.update(noble_condition=data.nobleCondition)
        if data.streetAndNumber:
            # kw.update(street=data.streetAndNumber)
            kw = street2kw(data.streetAndNumber, **kw)
        if data.zip:
            kw.update(zip_code=str(data.zip))
        if data.placeOfBirth:
            kw.update(birth_place=data.placeOfBirth)
        pk = data.reader.upper()

        msg1 = "BeIdReadCardToClientAction %s" % kw.get('national_id')

        country = rt.models.countries.Country.objects.get(isocode=pk)
        kw.update(country=country)
        if data.municipality:
            kw.update(city=rt.models.countries.Place.lookup_or_create(
                'name', data.municipality, country=country))

        def sex2gender(sex):
            if sex == 'MALE':
                return dd.Genders.male
            if sex == 'FEMALE':
                return dd.Genders.female
            logger.warning("%s : invalid gender code %r", msg1, sex)

        kw.update(gender=sex2gender(data.gender))

        def doctype2cardtype(dt):
            #~ if dt == 1: return BeIdCardTypes.get_by_value("1")
            rv = BeIdCardTypes.get_by_value(str(dt))
            # logger.info("20130103 documentType %r --> %r", dt, rv)
            return rv

        kw.update(card_type=doctype2cardtype(data.documentType))

        return kw
Beispiel #10
0
 def from_db_value(self, value, expression, connection, context):
     return IncompleteDate.parse(value) if value else self.get_default()
Beispiel #11
0
    def test01(self):

        # print("20180502 test_cbss.test01()")
        settings.SITE.startup()  # create cache/wsdl files

        root = create_and_get(settings.SITE.user_model, username='******')

        luc = create_and_get(rt.models.pcsw.Client,
                             first_name='Luc',
                             last_name='Saffre')

        # First IdentifyPersonRequest
        # Create an IPR with NISS just to have the XML validated.

        req = cbss.IdentifyPersonRequest(national_id="70100853190",
                                         user=root,
                                         person=luc)
        try:
            req.full_clean()
            self.fail('Expected ValidationError "birth_date cannot be blank."')
        except ValidationError:
            pass

        req.birth_date = IncompleteDate(1938, 6, 1)
        try:
            req.validate_request()
        except Warning as e:
            self.assertEqual(str(e), "")
            pass

        req.birth_date = IncompleteDate(1938, 0, 0)
        req.validate_request()
        req.execute_request(simulate_response='Foo', now=NOW)

        expected = """\
<ssdn:SSDNRequest xmlns:ssdn="http://www.ksz-bcss.fgov.be/XSD/SSDN/Service">
<ssdn:RequestContext>
<ssdn:AuthorizedUser>
<ssdn:UserID>00901234567</ssdn:UserID>
<ssdn:Email>[email protected]</ssdn:Email>
<ssdn:OrgUnit>0123456789</ssdn:OrgUnit>
<ssdn:MatrixID>17</ssdn:MatrixID>
<ssdn:MatrixSubID>1</ssdn:MatrixSubID>
</ssdn:AuthorizedUser>
<ssdn:Message>
<ssdn:Reference>IdentifyPersonRequest # 1</ssdn:Reference>
<ssdn:TimeRequest>20150511T183101</ssdn:TimeRequest>
</ssdn:Message>
</ssdn:RequestContext>
<ssdn:ServiceRequest>
<ssdn:ServiceId>OCMWCPASIdentifyPerson</ssdn:ServiceId>
<ssdn:Version>20050930</ssdn:Version>
<ipr:IdentifyPersonRequest xmlns:ipr="http://www.ksz-bcss.fgov.be/XSD/SSDN/OCMW_CPAS/IdentifyPerson">
<ipr:SearchCriteria>
<ipr:SSIN>70100853190</ipr:SSIN>
<ipr:PhoneticCriteria>
<ipr:LastName></ipr:LastName>
<ipr:FirstName></ipr:FirstName>
<ipr:MiddleName></ipr:MiddleName>
<ipr:BirthDate>1938-00-00</ipr:BirthDate>
</ipr:PhoneticCriteria>
</ipr:SearchCriteria>
<ipr:VerificationData>
<ipr:PersonData>
<ipr:LastName></ipr:LastName>
<ipr:FirstName></ipr:FirstName>
<ipr:MiddleName></ipr:MiddleName>
<ipr:BirthDate>1938-00-00</ipr:BirthDate>
</ipr:PersonData>
</ipr:VerificationData>
</ipr:IdentifyPersonRequest>
</ssdn:ServiceRequest>
</ssdn:SSDNRequest>"""
        self.assertEquivalent(expected, req.request_xml)

        ##

        req = cbss.IdentifyPersonRequest(last_name="MUSTERMANN",
                                         birth_date=IncompleteDate(1938, 0, 0))
        req.validate_request()

        # Create another one, this time a name search.
        # This time we also inspect the generated XML.

        req = cbss.IdentifyPersonRequest(user=root,
                                         person=luc,
                                         last_name="MUSTERMANN",
                                         first_name="Max",
                                         birth_date=IncompleteDate(1938, 6, 1))
        req.validate_request()
        req.execute_request(simulate_response='Foo', now=NOW)

        expected = """\
<ssdn:SSDNRequest xmlns:ssdn="http://www.ksz-bcss.fgov.be/XSD/SSDN/Service">
<ssdn:RequestContext>
<ssdn:AuthorizedUser>
<ssdn:UserID>00901234567</ssdn:UserID>
<ssdn:Email>[email protected]</ssdn:Email>
<ssdn:OrgUnit>0123456789</ssdn:OrgUnit>
<ssdn:MatrixID>17</ssdn:MatrixID>
<ssdn:MatrixSubID>1</ssdn:MatrixSubID>
</ssdn:AuthorizedUser>
<ssdn:Message>
<ssdn:Reference>IdentifyPersonRequest # 2</ssdn:Reference>
<ssdn:TimeRequest>20150511T183101</ssdn:TimeRequest>
</ssdn:Message>
</ssdn:RequestContext>
<ssdn:ServiceRequest>
<ssdn:ServiceId>OCMWCPASIdentifyPerson</ssdn:ServiceId>
<ssdn:Version>20050930</ssdn:Version>
<ipr:IdentifyPersonRequest xmlns:ipr="http://www.ksz-bcss.fgov.be/XSD/SSDN/OCMW_CPAS/IdentifyPerson">
<ipr:SearchCriteria>
<ipr:PhoneticCriteria>
<ipr:LastName>MUSTERMANN</ipr:LastName>
<ipr:FirstName>Max</ipr:FirstName>
<ipr:MiddleName></ipr:MiddleName>
<ipr:BirthDate>1938-06-01</ipr:BirthDate>
</ipr:PhoneticCriteria>
</ipr:SearchCriteria>
</ipr:IdentifyPersonRequest>
</ssdn:ServiceRequest>
</ssdn:SSDNRequest>"""

        self.assertEquivalent(expected, req.request_xml)

        if settings.SITE.plugins.cbss.cbss_environment != 'test':
            # Skip live tests unless we are in test environment.
            # Otherwise we would have to build /media/chache/wsdl files
            return

        # Execute a RetrieveTIGroupsRequest.

        req = cbss.RetrieveTIGroupsRequest(user=root,
                                           person=luc,
                                           national_id='12345678901',
                                           language='fr')

        # Try it without environment and see the XML.
        # Note that NewStyleRequests have no validate_request method.

        req.execute_request(simulate_response='Foo', now=NOW)
        expected = ""
        self.assertEquivalent(expected, req.request_xml)

        # Now a ManageAccessRequest

        today = datetime.date(2012, 5, 24)
        kw = dict()
        # dossier in onderzoek voor een maximale periode van twee maanden
        kw.update(purpose_id=1)
        kw.update(national_id='68060105329')
        kw.update(user=root)
        kw.update(person=luc)
        kw.update(start_date=today)
        kw.update(end_date=today)
        kw.update(action=cbss.ManageActions.REGISTER)
        kw.update(query_register=cbss.QueryRegisters.SECONDARY)
        #~ kw.update(id_card_no=)

        kw.update(last_name='SAFFRE')
        kw.update(first_name='LUC JOHANNES')
        kw.update(birth_date=IncompleteDate(1968, 6, 1))
        req = cbss.ManageAccessRequest(**kw)

        req.execute_request(simulate_response='Foo', now=NOW)
        expected = """<ssdn:SSDNRequest xmlns:ssdn="http://www.ksz-bcss.fgov.be/XSD/SSDN/Service">
<ssdn:RequestContext>
<ssdn:AuthorizedUser>
<ssdn:UserID>00901234567</ssdn:UserID>
<ssdn:Email>[email protected]</ssdn:Email>
<ssdn:OrgUnit>0123456789</ssdn:OrgUnit>
<ssdn:MatrixID>17</ssdn:MatrixID>
<ssdn:MatrixSubID>1</ssdn:MatrixSubID>
</ssdn:AuthorizedUser>
<ssdn:Message>
<ssdn:Reference>ManageAccessRequest # 1</ssdn:Reference>
<ssdn:TimeRequest>20150511T183101</ssdn:TimeRequest>
</ssdn:Message>
</ssdn:RequestContext>
<ssdn:ServiceRequest>
<ssdn:ServiceId>OCMWCPASManageAccess</ssdn:ServiceId>
<ssdn:Version>20050930</ssdn:Version>
<mar:ManageAccessRequest xmlns:mar="http://www.ksz-bcss.fgov.be/XSD/SSDN/OCMW_CPAS/ManageAccess">
<mar:SSIN>68060105329</mar:SSIN>
<mar:Purpose>10</mar:Purpose>
<mar:Period>
<common:StartDate xmlns:common="http://www.ksz-bcss.fgov.be/XSD/SSDN/Common">2012-05-24</common:StartDate>
<common:EndDate xmlns:common="http://www.ksz-bcss.fgov.be/XSD/SSDN/Common">2012-05-24</common:EndDate>
</mar:Period>
<mar:Action>REGISTER</mar:Action>
<mar:Sector>17</mar:Sector>
<mar:QueryRegister>SECONDARY</mar:QueryRegister>
<mar:ProofOfAuthentication>
<mar:PersonData>
<mar:LastName>SAFFRE</mar:LastName>
<mar:FirstName>LUC JOHANNES</mar:FirstName>
<mar:BirthDate>1968-06-01</mar:BirthDate>
</mar:PersonData>
</mar:ProofOfAuthentication>
</mar:ManageAccessRequest>
</ssdn:ServiceRequest>
</ssdn:SSDNRequest>
"""
        self.assertEquivalent(expected, req.request_xml)
Beispiel #12
0
def py2js(v):
    """
    Note that None values are rendered as ``null`` (not ``undefined``.
    """
    #~ assert _for_user_profile is not None
    #~ logger.debug("py2js(%r)",v)
    for cv in CONVERTERS:
        v = cv(v)

    #~ if isinstance(v,LanguageInfo):
        #~ return v.django_code

    if isinstance(v, Value):
        return v.as_ext()
        #~ v = v.as_ext()
        #~ if not isinstance(v, basestring):
            #~ raise Exception("20120121b %r is of type %s" % (v,type(v)))
        #~ return v
    if isinstance(v, Promise):
        #~ v = force_unicode(v)
        return json.dumps(force_unicode(v))

    if isinstance(v, types.GeneratorType):
        return "".join([py2js(x) for x in v])
    if etree.iselement(v):
    #~ if isinstance(v,etree.Element):
        return json.dumps(etree.tostring(v))

    #~ if type(v) is types.GeneratorType:
        #~ raise Exception("Please don't call the generator function yourself")
        #~ return "\n".join([ln for ln in v])
    if callable(v):
        #~ print 20120114, repr(v)
        #~ raise Exception("Please call the function yourself")
        return "\n".join([ln for ln in v()])
    if isinstance(v, js_code):
        return str(v.s)  # v.s might be a unicode
    if v is None:
        #~ return 'undefined'
        return 'null'
    if isinstance(v, (list, tuple)):  # (types.ListType, types.TupleType):
        #~ return "[ %s ]" % ", ".join([py2js(x) for x in v])
        elems = [py2js(x) for x in v
                 if (not isinstance(x, VisibleComponent)) or x.get_view_permission(_for_user_profile)]
        return "[ %s ]" % ", ".join(elems)
    if isinstance(v, dict):  # ) is types.DictType:
        #~ print 20100226, repr(v)
        return "{ %s }" % ", ".join([
            "%s: %s" % (py2js(k), py2js(v)) for k, v in v.items()
            if (not isinstance(v, VisibleComponent)) or v.get_view_permission(_for_user_profile)
        ])
            #~ "%s: %s" % (k,py2js(v)) for k,v in v.items()])
    if isinstance(v, bool):  # types.BooleanType:
        return str(v).lower()
    #~ if isinstance(v,CRL):
        #~ return str(v)
    if isinstance(v, Quantity):
        return '"%s"' % v
    if isinstance(v, (int, long, decimal.Decimal, fractions.Fraction)):
        return str(v)
    if isinstance(v, IncompleteDate):
        return '"%s"' % v.strftime(settings.SITE.date_format_strftime)
        #~ return '"%s"' % v
    if isinstance(v, datetime.datetime):
        #~ """20120120"""
        return '"%s"' % v.strftime(settings.SITE.datetime_format_strftime)
        #~ return '"%s"' % v.strftime('%Y-%m-%d %H:%M:%S')
    if isinstance(v, datetime.time):
        return '"%s"' % v.strftime(settings.SITE.time_format_strftime)
    if isinstance(v, datetime.date):
        if v.year < 1900:
            v = IncompleteDate(v)
            return '"%s"' % v.strftime(settings.SITE.date_format_strftime)
        return '"%s"' % v.strftime(settings.SITE.date_format_strftime)
        #~ return 'new Date(%d,%d,%d)' % (v.year,v.month-1,v.day)
        #~ return repr('%d.%d.%d' % (v.day,v.month,v.year))
        #~ return repr(str(v))

    if isinstance(v, float):
        return repr(v)
    # return json.encoder.encode_basestring(v)
    # print repr(v)
    # http://docs.djangoproject.com/en/dev/topics/serialization/
    #~ if not isinstance(v, (str,unicode)):
        #~ raise Exception("20120121 %r is of type %s" % (v,type(v)))
    return json.dumps(v)
Beispiel #13
0
    def test_this(self):

        Person = rt.modules.contacts.Person
        Link = rt.modules.humanlinks.Link
        LinkTypes = rt.modules.humanlinks.LinkTypes
        LinksByHuman = rt.modules.humanlinks.LinksByHuman

        father = create(Person,
                        first_name="John",
                        last_name="Doe",
                        gender="M",
                        birth_date='1980-07-31')
        try:
            son = create(Person,
                         first_name="Joseph",
                         last_name="Doe",
                         gender="M",
                         birth_date=IncompleteDate(2009, 2, 30))
        except ValidationError:
            pass
        else:
            self.fail("Expected ValidationError")
        son = create(Person,
                     first_name="Joseph",
                     last_name="Doe",
                     gender="M",
                     birth_date='2009-02-28')
        create(Link, parent=father, child=son, type=LinkTypes.parent)

        mary = create(Person,
                      first_name="Mary",
                      last_name="Doe",
                      gender="F",
                      birth_date='2010-01-30')
        create(Link, parent=father, child=mary, type=LinkTypes.parent)

        self.assertEqual(Person.objects.count(), 3)

        ar = LinksByHuman.request(father)
        s = ar.to_rst()
        # print(s)
        self.assertEquivalent(
            """

        John is Father of *Mary* (4 years) Father of *Joseph* (5
        years) """, s)

        # Create relationship as **Father**/**Son** **Adoptive
        # father**/**Adopted son** **Foster father**/**Foster son**
        # **Husband** **Partner** **Stepfather**/**Stepson** **Brother**
        # **Cousin** **Uncle**/**Nephew** **Relative** **Other** """, s)

        with translation.override('de'):
            ar = LinksByHuman.request(father)
            s = ar.to_rst()
            # print(s)
            self.assertEquivalent(
                """
            
            John ist Vater von *Mary* (4 Jahre) Vater von *Joseph* (5
            Jahre) """, s)

            # Beziehung erstellen als **Vater**/**Sohn**
            # **Adoptivvater**/**Adoptivsohn**
            # **Pflegevater**/**Pflegesohn** **Ehemann** **Partner**
            # **Stiefvater**/**Stiefsohn** **Bruder** **Vetter**
            # **Onkel**/**Neffe** **Verwandter** **Sonstiger** """, s)

        with translation.override('fr'):
            ar = LinksByHuman.request(father)
            s = ar.to_rst()
            # print(s)
            self.assertEquivalent(
                u"""

            John est Père de *Mary* (4 ans) Père de *Joseph* (5
            ans) """, s)

            # Créer lien de parenté en tant que **Père**/**Fils** **Père
            # adoptif**/**Fils adoptif** **Père nourricier**/**Fils
            # nourricier** **Mari** **Partenaire**
            # **Beau-père**/**Beau-fils** **Frère** **Cousin**
            # **Oncle**/**Nephew** **Parent** **Autre** """, s)

        # Here we are just testing whether no exception is risen. The
        # ouptut itself is more thoroughly tested elsewhere.
        html = LinksByHuman.get_slave_summary(father, ar)
        s = E.tostring(html)
        self.assertEqual(s[:5], '<div>')
Beispiel #14
0
def py2js(v):
    """Note that None values are rendered as ``null`` (not ``undefined``.

    """
    # assert _for_user_profile is not None
    # logger.debug("py2js(%r)",v)
    for cv in CONVERTERS:
        v = cv(v)

    # if isinstance(v,LanguageInfo):
        # return v.django_code

    if isinstance(v, Value):
        return v.as_ext()
        # v = v.as_ext()
        # if not isinstance(v, basestring):
            # raise Exception("20120121b %r is of type %s" % (v,type(v)))
        # return v
    if isinstance(v, Promise):
        # v = force_text(v)
        return json.dumps(force_text(v.encode('utf8')))

    if isinstance(v, types.GeneratorType):
        return "".join([py2js(x) for x in v])
    if etree.iselement(v):
        return json.dumps(force_text(etree.tostring(v)))

    # if type(v) is types.GeneratorType:
        # raise Exception("Please don't call the generator function yourself")
        # return "\n".join([ln for ln in v])
    if callable(v):
        # print 20120114, repr(v)
        # raise Exception("Please call the function yourself")
        return "\n".join([ln for ln in v()])
    if isinstance(v, js_code):
        return str(v.s)  # v.s might be a unicode
    if v is None:
        # return 'undefined'
        return 'null'
    if isinstance(v, (list, tuple)):  # (types.ListType, types.TupleType):
        elems = [py2js(x) for x in v
                 if (not isinstance(x, VisibleComponent))
                 or x.get_view_permission(_for_user_profile)]
        return "[ %s ]" % ", ".join(elems)

    if isinstance(v, dict):
        items = [
            # i for i in sorted(v.items(), key=lambda x: str(x))
            # i for i in sorted(v.items())
            i for i in v.items()
            if (not isinstance(v, VisibleComponent))
            or v.get_view_permission(_for_user_profile)]
        
        # "sorted(v.items())" without sortkey caused TypeError when
        # the dictionary contained a mixture of unicode and
        # future.types.newstr objects.
        def sortkey(x):
            if isinstance(x[0], newstr):
                return six.text_type(x[0])
            return x[0]
        items = sorted(items, key=sortkey)
        # try:
        #     items = sorted(items, key=sortkey)
        # except TypeError as e:
        #     raise TypeError("Failed to sort {0!r} : {1}".format(items, e))
        return "{ %s }" % ", ".join(
            ["%s: %s" % (py2js(k), py2js(i)) for k, i in items])

    if isinstance(v, bool):  # types.BooleanType:
        return str(v).lower()
    if isinstance(v, Quantity):
        return '"%s"' % v
    if isinstance(v, (int, decimal.Decimal, fractions.Fraction)):
        return str(v)
    if isinstance(v, IncompleteDate):
        return '"%s"' % v.strftime(settings.SITE.date_format_strftime)
    if isinstance(v, datetime.datetime):
        return '"%s"' % v.strftime(settings.SITE.datetime_format_strftime)
    if isinstance(v, datetime.time):
        return '"%s"' % v.strftime(settings.SITE.time_format_strftime)
    if isinstance(v, datetime.date):
        if v.year < 1900:
            v = IncompleteDate(v)
            return '"%s"' % v.strftime(settings.SITE.date_format_strftime)
        return '"%s"' % v.strftime(settings.SITE.date_format_strftime)

    if isinstance(v, float):
        return repr(v)
    # return json.encoder.encode_basestring(v)
    # print repr(v)
    # http://docs.djangoproject.com/en/dev/topics/serialization/
    # if not isinstance(v, (str,unicode)):
        # raise Exception("20120121 %r is of type %s" % (v,type(v)))
    return json.dumps(v)
Beispiel #15
0
    def card2client(self, data):
        """Convert the data coming from the card into database fields to be
        stored in the card holder.

        """
        countries = dd.resolve_app('countries', strict=True)

        kw = dict()
        raw_data = data['card_data']
        if not '\n' in raw_data:
            # a one-line string means that some error occured (e.g. no
            # card in reader). of course we want to show this to the
            # user.
            raise Warning(raw_data)

        #~ print cd
        data = AttrDict(yaml.load(raw_data))
        #~ raise Exception("20131108 cool: %s" % cd)

        kw.update(national_id=ssin.format_ssin(str(data.nationalNumber)))
        kw.update(first_name=data.firstName or '')
        kw.update(middle_name=data.middleName or '')
        kw.update(last_name=data.name or '')

        card_number = str(data.cardNumber)

        if data.photo:
            if not card_number:
                raise Exception("20150730 photo data but no card_number ")
            fn = get_image_path(card_number)
            if fn.exists():
                logger.warning("Overwriting existing image file %s.", fn)
            try:
                fp = file(fn, 'wb')
                fp.write(base64.b64decode(data.photo))
                fp.close()
            except IOError as e:
                logger.warning("Failed to store image file %s : %s", fn, e)

            #~ print 20121117, repr(data['picture'])
            #~ kw.update(picture_data_encoded=data['picture'])

        if isinstance(data.dateOfBirth, basestring):
            data.dateOfBirth = IncompleteDate(*data.dateOfBirth.split('-'))
        kw.update(birth_date=data.dateOfBirth)
        kw.update(card_valid_from=data.cardValidityDateBegin)
        kw.update(card_valid_until=data.cardValidityDateEnd)

        kw.update(card_number=card_number)
        kw.update(card_issuer=data.cardDeliveryMunicipality)
        if data.nobleCondition:
            kw.update(noble_condition=data.nobleCondition)
        if data.streetAndNumber:
            # kw.update(street=data.streetAndNumber)
            kw = street2kw(data.streetAndNumber, **kw)
        if data.zip:
            kw.update(zip_code=str(data.zip))
        if data.placeOfBirth:
            kw.update(birth_place=data.placeOfBirth)
        pk = data.reader.upper()

        msg1 = "BeIdReadCardToClientAction %s" % kw.get('national_id')

        country = countries.Country.objects.get(isocode=pk)
        kw.update(country=country)
        if data.municipality:
            kw.update(city=countries.Place.lookup_or_create(
                'name', data.municipality, country=country))

        def sex2gender(sex):
            if sex == 'MALE':
                return dd.Genders.male
            if sex == 'FEMALE':
                return dd.Genders.female
            logger.warning("%s : invalid gender code %r", msg1, sex)

        kw.update(gender=sex2gender(data.gender))

        def doctype2cardtype(dt):
            #~ if dt == 1: return BeIdCardTypes.get_by_value("1")
            rv = BeIdCardTypes.get_by_value(str(dt))
            # logger.info("20130103 documentType %r --> %r", dt, rv)
            return rv

        kw.update(card_type=doctype2cardtype(data.documentType))

        if config.data_collector_dir:
            logger.info("Gonna write raw eid card data: %r", raw_data)
            fn = os.path.join(config.data_collector_dir, card_number + '.txt')
            file(fn, "w").write(raw_data.encode('utf-8'))
            logger.info("Wrote eid card data to file %s", fn)

        return kw
Beispiel #16
0
    def card2client(self, data):
        """
        Convert the data coming from the card into database fields to be
        stored in the card holder.
        """
        kw = dict()
        # raw_data = data['card_data']

        kw.update(national_id=ssin.format_ssin(str(data.national_number)))
        kw.update(first_name=data.firstnames or '')
        kw.update(
            middle_name=data.first_letter_of_third_given_name or '')
        kw.update(last_name=data.surname or '')

        card_number = str(data.card_number)

        if data.PHOTO_FILE:
            if not card_number:
                raise Exception("20150730 photo data but no card_number ")
            fn = get_image_path(card_number)
            if fn.exists():
                logger.warning("Overwriting existing image file %s.", fn)
            try:
                fp = open(fn, 'wb')
                # fp.write(data.PHOTO_FILE)
                fp.write(base64.b64decode(data.PHOTO_FILE))
                fp.close()
            except IOError as e:
                logger.warning("Failed to store image file %s : %s", fn, e)
                
            #~ print 20121117, repr(data['picture'])
            #~ kw.update(picture_data_encoded=data['picture'])

        if isinstance(data.date_of_birth, six.string_types):
            data.date_of_birth = IncompleteDate.parse(data.date_of_birth)
            # IncompleteDate(
            #     *data.date_of_birth.split('-'))
        kw.update(birth_date=data.date_of_birth)
        kw.update(card_valid_from=dateparser.parse(
            data.validity_begin_date).date())
        kw.update(card_valid_until=dateparser.parse(
            data.validity_end_date).date())

        kw.update(card_number=card_number)
        kw.update(card_issuer=data.issuing_municipality)
        if data.nobility:
            kw.update(noble_condition=data.nobility)
        if data.address_street_and_number:
            kw = street2kw(data.address_street_and_number, **kw)
        if data.address_zip:
            kw.update(zip_code=str(data.address_zip))
        if data.location_of_birth:
            kw.update(birth_place=data.location_of_birth)
            
        pk = data.eidreader_country
        country = rt.models.countries.Country.objects.get(isocode=pk)
        kw.update(country=country)
        if data.address_municipality:
            kw.update(city=rt.models.countries.Place.lookup_or_create(
                'name', data.address_municipality, country=country))

        msg1 = "BeIdReadCardToClientAction %s" % kw.get('national_id')
        def sex2gender(sex):
            c0 = sex[0].upper()
            if c0 == 'M':
                return dd.Genders.male
            if c0 in 'FWV':
                return dd.Genders.female
            logger.warning("%s : invalid gender code %r", msg1, sex)
        kw.update(gender=sex2gender(data.gender))

        def doctype2cardtype(dt):
            #~ if dt == 1: return BeIdCardTypes.get_by_value("1")
            rv = BeIdCardTypes.get_by_value(str(dt))
            # logger.info("20130103 documentType %r --> %r", dt, rv)
            return rv
        kw.update(card_type=doctype2cardtype(data.document_type))

        return kw