class IEvent(Interface): title = schema.TextLine( title=_(u'Title'), required=True, ) description = schema.Text( title=_(u'Description'), required=False, )
class IWorkshop(Interface): """Workshop """ code = schema.TextLine( title=_(u'label_cmo_workshop_code', u'Workshop ID'), required=False, ) # form.mode(title='hidden') title = schema.TextLine( title=_(u'label_cmo_workshop_name', u'Workshop Name'), required=False, ) short_name = schema.TextLine( title=_(u'Shortname'), required=False, ) start_date = schema.Date( title=_(u'label_cmo_workshop_start_date', u'Workshop Start Date'), required=False, ) end_date = schema.Date( title=_(u'label_cmo_workshop_end_date', u'Workshop End Date'), required=False, ) event_type = schema.TextLine( title=_(u'label_cmo_workshop_type', u'Workshop Type'), required=False, ) max_participants = schema.Int( title=_(u'label_cmo_workshop_max_participants', u'Maximum Number of Participants'), required=False, ) description = schema.Text( title=_(u'label_cmo_workshop_description', u'Workshop Description'), required=False, ) press_release = RichText( title=_(u'label_cmo_workshop_press_release', u'Press Release'), required=False, ) @invariant def validate_start_end(data): if (data.start_date and data.end_date and data.start_date > data.end_date): raise StartBeforeEnd( _('error_end_must_be_after_start_date', default=u'End date must be after start date.'))
class IParticipant(Interface): """An application form for renewal scholarship. """ # form.mode(title='hidden') title = schema.TextLine( title=_(u'Title'), required=False, # default=u'solicitud-20171' ) workshop = schema.TextLine( title=_(u'label_cmo_workshop', u'Workshop'), required=False, )
class IAcommodation(model.Schema): """Behavior Information about the person """ model.fieldset( 'acommodationInformation', label=_( u'label_cmo_acommodationInformation', u'Acommodation' ), fields=[ 'hotel', 'visa', 'externalHotel', 'nameGuest', ] ) hotel = schema.Choice( title=_( u'label_cmo_hotel', default=u'Hotel' ), values=[u'Los Laureles', u'Angel Inn', u'Sin Hotel'], required=False, ) visa = schema.TextLine( title=_( u'label_cmo_visa', default=u'Visa' ), required=False, ) externalHotel = schema.TextLine( title=_( u'label_cmo_externalHotel', default=u'External Hotel' ), required=False, ) nameGuest = schema.TextLine( title=_( u'label_cmo_nameGuest', default=u'Name Guest' ), required=False, )
def handle_update_workshops_db(self, action): """Update workshops list from CIMAT db """ logger.info('Updating Workshops') data, errors = self.extractData() year = data['year'] try: cnx = mysql.connector.connect(**config) except mysql.connector.Error as err: api.portal.show_message(err, self.request, type=u'error') else: # A MySQLCursorDict cursor returns each row as a dictionary cursor = cnx.cursor(dictionary=True) query = ( 'SELECT * FROM eventos WHERE fechaIni BETWEEN %s AND %s ORDER BY fechaIni' ) event_start = date(int(year), 1, 1) event_end = date(int(year), 12, 31) cursor.execute(query, (event_start, event_end)) json_data = [self.workshop_to_birs(row) for row in cursor] self.update_workshops(year, json_data) cursor.close() cnx.close() api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.')
class IMyForm(model.Schema): year = schema.Choice( title=_(u'Year'), values=[ u'2015', u'2016', u'2017', u'2018', u'2019', u'2020', u'2021', u'2022' ], required=False, )
def handle_update_participants(self, action): """Update participants list from Birs API """ logger.info('Updating participants for {0}'.format(self.context.id)) birs_uri = api.portal.get_registry_record('cmo.birs_api_uri') if birs_uri is None: api.portal.show_message(_(u'CMO Settings: No Birs API defined!'), self.request, type=u'error') return url = '/'.join([birs_uri, 'members', self.context.id]) try: req = requests.get(url) req.raise_for_status() except (ConnectionError, HTTPError) as err: api.portal.show_message(err, self.request, type=u'error') else: self.update_participants(req.json()) api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.')
def handle_update_workshops(self, action): """Update workshops list from Birs API """ logger.info('Updating Workshops') data, errors = self.extractData() year = data['year'] birs_uri = api.portal.get_registry_record('cmo.birs_api_uri') if birs_uri is None: api.portal.show_message(_(u'CMO Settings: No Birs API defined!'), self.request, type=u'error') return url = '/'.join([birs_uri, 'event_data_for_year', year]) try: req = requests.get(url) req.raise_for_status() except (ConnectionError, HTTPError) as err: api.portal.show_message(err, self.request, type=u'error') else: self.update_workshops(year, req.json()) api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.')
def handle_update_participants_db(self, action): """Update participants list from CIMAT db """ logger.info('Updating participants for {0}'.format(self.context.id)) try: cnx = mysql.connector.connect(**config) # cnx.set_charset_collation('utf-8') except mysql.connector.Error as err: api.portal.show_message(err, self.request, type=u'error') else: # A MySQLCursorDict cursor returns each row as a dictionary cursor = cnx.cursor(dictionary=True) query = ('SELECT * FROM user WHERE evento = %s ORDER BY lastname') cursor.execute(query, (self.context.id, )) json_data = [self.person_to_birs(row) for row in cursor] self.update_participants(json_data) cursor.close() cnx.close() api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.')
def update_participants(self, json_data): """Update participants list """ newparticipants = [] for item in json_data: userid = idnormalizer.normalize(item['Person']['email']) if userid not in self.context: kargs = dict(item['Person']) kargs.update(item['Membership']) kargs['workshop'] = item['Workshop'] for d in ['arrival_date', 'replied_at', 'departure_date']: if kargs[d] is not None and kargs[ d] != '0000-00-00 00:00:00': try: datetime.strptime(kargs[d], '%Y-%m-%d %H:%M:%S') # noqa except Exception: del kargs[d] else: del kargs[d] api.content.create( type='Participant', id=idnormalizer.normalize(kargs['email']), title=' '.join([kargs['firstname'], kargs['lastname']]), container=self.context, **kargs) newparticipants.append(' '.join( [kargs['firstname'], kargs['lastname']])) else: participant = self.context[userid] participant.title = ' '.join( [item['Person']['firstname'], item['Person']['lastname']]) participant.lastname = item['Person']['lastname'] participant.firstname = item['Person']['firstname'] participant.country = item['Person']['country'] participant.gender = item['Person']['gender'] # if not participant.country and item['Person']['country']: # participant.country = item['Person']['country'] # if not participant.gender and item['Person']['gender']: # participant.gender = item['Person']['gender'] participant.affiliation = item['Person']['affiliation'] participant.salutation = item['Person']['salutation'] participant.url = item['Person']['url'] participant.phone = item['Person']['phone'] participant.phd_year = item['Person']['phd_year'] participant.academic_status = item['Person']['academic_status'] participant.attendance = item['Membership']['attendance'] participant.role = item['Membership']['role'] participant.replied_at = item['Membership']['replied_at'] participant.has_guest = item['Membership']['has_guest'] participant.special_info = item['Membership']['special_info'] participant.event_notes = item['Membership']['event_notes'] try: datetime.strptime(item['Membership']['arrival_date'], '%Y-%m-%d %H:%M:%S') arrival_date = item['Membership']['arrival_date'] except ValueError: arrival_date = None if participant.arrival_date != arrival_date: participant.arrival_date = arrival_date try: datetime.strptime(item['Membership']['departure_date'], '%Y-%m-%d %H:%M:%S') departure_date = item['Membership']['departure_date'] except ValueError: departure_date = None if participant.departure_date != departure_date: participant.departure_date = departure_date participant.reindexObject() if newparticipants: msg = _(u'New participants: ') + ', '.join(newparticipants) api.portal.show_message(msg, self.request, type=u'info')
class UpdateWorkshopsForm(form.Form): """Update workshops list.""" fields = field.Fields(IMyForm) ignoreContext = True label = _(u'Workshops Administration') @button.buttonAndHandler(_(u'Update Workshops')) def handle_update_workshops(self, action): """Update workshops list from Birs API """ logger.info('Updating Workshops') data, errors = self.extractData() year = data['year'] birs_uri = api.portal.get_registry_record('cmo.birs_api_uri') if birs_uri is None: api.portal.show_message(_(u'CMO Settings: No Birs API defined!'), self.request, type=u'error') return url = '/'.join([birs_uri, 'event_data_for_year', year]) try: req = requests.get(url) req.raise_for_status() except (ConnectionError, HTTPError) as err: api.portal.show_message(err, self.request, type=u'error') else: self.update_workshops(year, req.json()) api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.') def update_workshops(self, year, json_data): """Update workshops for year """ folder = api.content.get(path='/{0}'.format(year)) if not folder: folder = api.content.create(type='Folder', title=year, container=api.portal.get()) for item in json_data: if item['code'] not in folder: item['start_date'] = datetime.strptime(item['start_date'], '%Y-%m-%d') # noqa item['end_date'] = datetime.strptime(item['end_date'], '%Y-%m-%d') # noqa item['max_participants'] = int(item['max_participants']) workshop = api.content.create(type='Workshop', id=item['code'], title=item['name'], container=folder, **item) # create certificate template = api.content.get( '/templates-for-certificates/latex-template') api.content.create( type='Certificate', id='Certificate', title='Certificate', container=workshop, ctemplate=api.content.get_uuid(obj=template)) # update participants from MYSQL database # workshopview = getMultiAdapter((workshop, self.request), name='update-participants') # workshopview.handle_update_participants_db(workshopview, '') # @button.buttonAndHandler(_(u'Update Workshops from DB')) def handle_update_workshops_db(self, action): """Update workshops list from CIMAT db """ logger.info('Updating Workshops') data, errors = self.extractData() year = data['year'] try: cnx = mysql.connector.connect(**config) except mysql.connector.Error as err: api.portal.show_message(err, self.request, type=u'error') else: # A MySQLCursorDict cursor returns each row as a dictionary cursor = cnx.cursor(dictionary=True) query = ( 'SELECT * FROM eventos WHERE fechaIni BETWEEN %s AND %s ORDER BY fechaIni' ) event_start = date(int(year), 1, 1) event_end = date(int(year), 12, 31) cursor.execute(query, (event_start, event_end)) json_data = [self.workshop_to_birs(row) for row in cursor] self.update_workshops(year, json_data) cursor.close() cnx.close() api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.') def workshop_to_birs(self, data): """Returns a workshop with birs api format """ workshop = { 'code': data['codigo'], 'name': data['nombre'], 'short_name': data['nombreCorto'], 'start_date': str(data['fechaIni']), 'end_date': str(data['fechaFin']), 'event_type': data['tipoEvento'], 'max_participants': data['maximoParticipante'], 'description': data['descripcion'], # 'press_release': '<p></p>', } return workshop
class UpdateParticipantsForm(form.Form): """Update Participants lists.""" @button.buttonAndHandler(_(u'Update Participants')) def handle_update_participants(self, action): """Update participants list from Birs API """ logger.info('Updating participants for {0}'.format(self.context.id)) birs_uri = api.portal.get_registry_record('cmo.birs_api_uri') if birs_uri is None: api.portal.show_message(_(u'CMO Settings: No Birs API defined!'), self.request, type=u'error') return url = '/'.join([birs_uri, 'members', self.context.id]) try: req = requests.get(url) req.raise_for_status() except (ConnectionError, HTTPError) as err: api.portal.show_message(err, self.request, type=u'error') else: self.update_participants(req.json()) api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.') def update_participants(self, json_data): """Update participants list """ for item in json_data: item_id = idnormalizer.normalize(item['Person']['email']) if item_id not in self.context: kargs = dict(item['Person']) kargs.update(item['Membership']) kargs['workshop'] = item['Workshop'] for d in ['arrival_date', 'replied_at', 'departure_date']: if kargs[d] is not None and kargs[ d] != '0000-00-00 00:00:00': kargs[d] = datetime.strptime( kargs[d], '%Y-%m-%d %H:%M:%S') # noqa else: del kargs[d] api.content.create( type='Participant', id=item_id, title=' '.join([kargs['firstname'], kargs['lastname']]), container=self.context, **kargs) # @button.buttonAndHandler(_(u'Update Participants from DB')) def handle_update_participants_db(self, action): """Update participants list from CIMAT db """ logger.info('Updating participants for {0}'.format(self.context.id)) try: cnx = mysql.connector.connect(**config) # cnx.set_charset_collation('utf-8') except mysql.connector.Error as err: api.portal.show_message(err, self.request, type=u'error') else: # A MySQLCursorDict cursor returns each row as a dictionary cursor = cnx.cursor(dictionary=True) query = ('SELECT * FROM user WHERE evento = %s ORDER BY lastname') cursor.execute(query, (self.context.id, )) json_data = [self.person_to_birs(row) for row in cursor] self.update_participants(json_data) cursor.close() cnx.close() api.portal.show_message(_(u'Updated!'), self.request, type=u'info') logger.info('Done.') def person_to_birs(self, data): """Returns a workshop with birs api format """ try: lastname = data['lastname'].encode('iso-8859-1').decode('utf-8') except UnicodeEncodeError: lastname = data['lastname'].encode('cp1252').decode('utf-8') try: firstname = data['name'].encode('iso-8859-1').decode('utf-8') except UnicodeEncodeError: firstname = data['name'].encode('cp1252').decode('utf-8') try: affiliation = data['company'].encode('iso-8859-1').decode('utf-8') except UnicodeEncodeError: affiliation = data['company'].encode('cp1252').decode('utf-8') try: special_info = data['informacion'].encode('iso-8859-1').decode( 'utf-8') except UnicodeEncodeError: special_info = data['informacion'].encode('cp1252').decode('utf-8') person = { 'Workshop': data['evento'], 'Person': { 'lastname': lastname, 'firstname': firstname, 'country': data['pais'], 'email': data['email'], 'gender': data['genero'], 'affiliation': affiliation, 'salutation': data['grado'], 'url': data['pagina'], 'phone': data['phone'], 'phd_year': data['graduacion'] or None, 'academic_status': data['status'], }, 'Membership': { 'arrival_date': str(data['arrival_date']) or None, 'departure_date': str(data['departure_date']) or None, 'attendance': data['confirmed'], 'role': data['rol'], 'replied_at': None, 'has_guest': data['acompanante'], 'special_info': special_info or data['requerimientos'], 'off_site': data['reserva'], # 'event_notes': None 'visa': data['visa'], 'nameGuest': data['acompaname'], 'hotel': string.capwords(data['hotel']) or None, } } return person
class IMembership(model.Schema): """Behavior Information about the person """ model.fieldset('membershipInformation', label=_(u'label_cmo_membershipInformation', u'Membership'), fields=[ 'arrival_date', 'departure_date', 'attendance', 'role', 'replied_at', 'has_guest', 'special_info', 'off_site', 'event_notes', 'certificatesended', 'certificaterequested', ]) arrival_date = schema.TextLine( title=_(u'label_cmo_arrival', default=u'Arrival Date'), required=False, ) departure_date = schema.TextLine( title=_(u'label_cmo_departure', default=u'Departure'), required=False, ) attendance = schema.TextLine( title=_(u'label_cmo_attendance', default=u'Attendance'), required=False, ) role = schema.TextLine( title=_(u'label_cmo_role', default=u'Role'), required=False, ) replied_at = schema.TextLine( title=_(u'label_cmo_replied', default=u'Replied At'), required=False, ) has_guest = schema.TextLine( title=_(u'label_cmo_hasguest', default=u'Has Guest'), required=False, ) special_info = schema.TextLine( title=_(u'label_cmo_specialInfo', default=u'Special Info'), required=False, ) off_site = schema.TextLine( title=_(u'label_cmo_offsite', default=u'Offsite'), required=False, ) event_notes = schema.TextLine( title=_(u'label_cmo_eventNotes', default=u'Event Notes'), required=False, ) certificatesended = schema.Choice(title=_(u'label_cmo_certificatesended', default=u'Certificate Sended'), values=[u'Yes', u'No'], required=True, default=u'No') certificaterequested = schema.Choice(title=_( u'label_cmo_certificaterequested', default=u'Certificate Requested'), values=[u'Yes', u'No'], required=True, default=u'No')
class StartBeforeEnd(Invalid): __doc__ = _('error_invalid_date', default=u'Invalid start or end date')
class ICertificate(Interface): """Certificate """ title = schema.TextLine(title=_(u'label_cmo_certificate_name', u'Certificate Name'), required=False, default=u'Certificate') # show_fields = schema.List( # title=_( # u'label_cmo_certificate_showfields', # default=u'Show Fields' # ), # value_type=schema.Choice( # vocabulary='cmo.events.showfields', # ), # required=False, # ) ctemplate = schema.Choice( title=_(u'label_cmo_certificate_ctemplate', default=u'Template'), vocabulary='cmo.events.certificatestemplates', required=False, ) subheader = schema.Text( title=_(u'label_cmo_certificate_subheader', u'Sub Header'), required=False, default=u'CERTIFICATE', ) preamble = schema.Text(title=_(u'label_cmo_certificate_preamble', u'Preamble'), required=False, default=u'This is to certify that:') participantdata = schema.Text( title=_(u'label_cmo_certificate_participantdata', u'Participant Data'), required=False, default=u'$Participant:firstname $Participant:lastname') bodydescription = schema.Text( title=_(u'label_cmo_certificate_description', u'Body Description'), required=False, default= u'has attended the "$Workshop:title" workshop, held from $fancyDate, at Hotel Hacienda Los Laureles, Oaxaca, Oax. Mexico.' ) onlinebodydescription = schema.Text( title=_(u'label_cmo_certificate_onlinedescription', u'On Line Body Description'), required=False, default= u'has attended the "$Workshop:title" online workshop, held via Zoom from $fancyDate.' ) signaturename = schema.Text(title=_(u'label_cmo_certificate_signaturename', u'Signature Name'), required=False, default=u'Dr. José Antonio Seade Kuri') signatureappointment = schema.Text(title=_( u'label_cmo_certificate_appointment', u'Signature Appointment'), required=False, default=u'Director') signatureinst = schema.Text(title=_(u'label_cmo_certificate_signatureinst', u'Signature Institution'), required=False, default=u'Casa Matemática Oaxaca')
def validate_start_end(data): if (data.start_date and data.end_date and data.start_date > data.end_date): raise StartBeforeEnd( _('error_end_must_be_after_start_date', default=u'End date must be after start date.'))