def register_repas(self, postValues): """ we assume we will not register a child without a parent, and a parent without a child :param postValues: :return: """ repas = None params = postValues.copy() if params.get('components'): try: repas = Repas.objects.get(id=params.get('repas_id')) repas.unit_price = params.get('unit_price') repas.date_time = datetime.now() except Repas.DoesNotExist: repas = Repas(unit_price=params.get('unit_price'), date_time=datetime.now()) try: repas.save() components = params.get('components') for comp in components: self.add_component(repas, comp_name=comp) if repas.menu.count() == 0: raise CriticalError( {'message': "The menu was not saved. Try again."}) except Exception: raise CriticalError({ 'message': "Unkwon Error while saving repas and menu. Try again or contact system admin " }) return repas
def decodeDataToExport(self, data, exportProperties): #This is my star code, enyewe I had done some nice stuff during my time. Five stars for this, hata mimi am impressed by myself #quickly get the available columns from this resultset data structure records = data['records'] if not records: raise CriticalError({'message': "Sorry, no data to export."}) if not exportProperties: raise CriticalError({ 'message': "Sorry, no export properties specified for export." }) result = [] exportProperties = json.loads(exportProperties, object_pairs_hook=ordereddict.OrderedDict ) #ast.literal_eval(exportProperties) exportColumns = exportProperties.keys( ) #this will hold the export columns as per the data names e.g gf_grant__grant_number for record in records: d = ordereddict.OrderedDict() for entityProperty in exportColumns: if entityProperty in record: if isinstance(record[entityProperty], Decimal): d[exportProperties[entityProperty]] = round( record[entityProperty], 4) elif isinstance(record[entityProperty], unicode): d[exportProperties[entityProperty]] = record[ entityProperty].encode('utf-8') else: d[exportProperties[entityProperty]] = record[ entityProperty] result.append(d) #now decode the field names aka headers headers = exportProperties.values() formatted_headers = [] for header in headers: h = header.replace("<br/>", " ") formatted_headers.append(h) return formatted_headers, result
def save_activity(self, postValues): activity = None params = postValues.copy() if params.get("activity"): try: activity = ChildActivity.objects.get( id=params.get('activity_id')) activity.name = params.get('activity'), activity.category = params.get('category'), activity.unit_price = params.get('unit_price') except ChildActivity.DoesNotExist: activity = ChildActivity(name=params.get('activity'), category=params.get('category'), unit_price=params.get('unit_price')) try: activity.save() except Exception: raise CriticalError({ 'message': "Unkwon Error while saving activity '" + params.get('activity') + "'. Try again or contact system admin " }) return activity
def save_principal(self, postValues): principal = None params = postValues.copy() if params.get("principal_names"): try: principal = CrechePrincipal.objects.get( id=params.get('principal_id')) principal.names = params.get('principal_names') principal.telephone = params.get('telephone') principal.identity_document = params.get('id_number') principal.role = params.get('role') principal.full_address = params.get('full_address') principal.email = params.get('email') principal.last_updated = datetime.now() except CrechePrincipal.DoesNotExist: principal = CrechePrincipal( names=params.get('principal_names'), telephone=params.get('telephone'), identity_document=params.get('id_number'), role=params.get('role'), full_address=params.get('full_address'), email=params.get('email'), date_created=datetime.now(), last_updated=datetime.now()) try: principal.save() except Exception: raise CriticalError({ 'message': "Unkwon Error while saving principal '" + params.get('principal_names') + "'. Try again or contact system admin " }) return principal
def save_child(self, postValues): child = None params = postValues.copy() if params.get("child_names"): try: child = CrecheChild.objects.get(id=params.get('child_id')) child.names = params.get('child_names') child.date_of_birth = params.get('dob') child.group = params.get('group') child.gender = params.get('gender') child.last_updated = datetime.now() except CrecheChild.DoesNotExist: regno = self.generate_regno() if self.get_child(regno=regno): regno = self.generate_regno() child = CrecheChild( names=params.get('child_names'), regno= regno, #TODO need to find asolution while saving concurrently date_of_birth=params.get('dob'), group=params.get('group'), gender=params.get('gender'), date_created=datetime.now(), last_updated=datetime.now()) try: child.save() except Exception: raise CriticalError({ 'message': "Unkwon Error while saving child '" + params.get('child_names') + "'. Try again or contact system admin " }) return child
def register_report(self, postValues): """ we assume we will not register a child without a report, and a report without a child :param postValues: :return: """ report = None params = postValues.copy() if params.get('child'): try: report = DailyChildReport.objects.get(id = params.get('report_id')) day_price = params.get('day_price') except DailyChildReport.DoesNotExist: report = DailyChildReport( day_price = params.get('day_price'), date_created=datetime.now(), day = datetime.today() ) try: child = ChildService.get_child(child = params.get('child')) if not child: raise CriticalError({'message': "Report was not saved, child not found. Try again."}) repas = RepasService.register_repas(postValues) if not repas: raise CriticalError({'message': "Report was not saved, repas was not saved. Try again."}) principal = PrincipalService.get_principal(principal_id=params.get('principal')) if not principal: raise CriticalError({'message': "Report was not saved, accueillante was not saved. Try again."}) report.child = child report.accueillante = principal report.repas = repas report.save() activities = params.get('activities') for act in activities: self.add_activity(report, act) if report.activities.count() == 0: raise CriticalError({'message': "The activities were not saved. Try again."}) except Exception: raise CriticalError({'message': "Unkwon Error while saving child daily report. Try again or contact system admin "}) return report
def save_parent(self, postValues): """ we assume we will not register a child without a parent, and a parent without a child :param postValues: :return: """ parent = None params = postValues.copy() if params.get('parent_names'): try: parent = CrecheParent.objects.get(id=params.get('id_number')) parent.names = params.get('parent_names') parent.telephone = params.get('telephone') parent.identity_number = params.get('id_number') parent.relationship = params.get('relationship') parent.full_address = params.get('full_address') parent.email = params.get('email'), parent.last_updated = datetime.now() except CrecheParent.DoesNotExist: parent = CrecheParent(names=params.get('parent_names'), telephone=params.get('telephone'), identity_number=params.get('id_number'), relationship=params.get('relationship'), full_address=params.get('full_address'), email=params.get('email'), date_created=datetime.now(), last_updated=datetime.now()) try: parent.save() except Exception: raise CriticalError({ 'message': "Unkwon Error while saving parent '" + params.get("parent_names") + "'. Try again or contact system admin " }) return parent
def processEmailQueue(self, eventId=None, eventTypeId=None, language='English'): """Process all the queued email in the database""" recipients = None #before running, ensure that there is no other COREAPP email process running #check if the pid file is present pidFile = settings.APPLICATION_SETTINGS[ 'COREAPP_HOME'] + '/pidfile/message_' + language + '.pid' if AppUtil.checkFileExistence(pidFile): raise CriticalError({ "message": "Email relay process halted.<br/>There is another process that has a lock on the email relay pid file (" + language + ")." }) else: #create the file, to indicate that the message relay process is active f = open(pidFile, 'w') f.write(str(datetime.now())) f.close() #proceed with the email relaying process queuedEmails = self.__retrieveQueue(eventId, eventTypeId) recipients = self.__relayEmails(queuedEmails, eventId, eventTypeId, language) #clean up self.connection.commit() self.connection.close() self.smtpObj.quit() os.unlink(pidFile) return recipients
def save_component(self, postValues): component = None params = postValues.copy() if params.get("component"): try: component = ComposantRepas.objects.get( id=params.get('component_id')) component.component_name = params.get('component') component.description = params.get('description') except ComposantRepas.DoesNotExist: component = ComposantRepas( component_name=params.get('component'), description=params.get('description')) try: component.save() except Exception: raise CriticalError({ 'message': "Unkwon Error while saving component '" + params.get('component') + "'. Try again or contact system admin " }) return component
def __relayEmails(self, queuedEmails, eventId, eventTypeId, language): """Send emails""" emailBody = None if self.__isEmailRelay(eventTypeId): #for special cases like facturation, the email body is gotten from a text file, as opposed to the db sql = 'SELECT entity_reference_id FROM event WHERE id = %d' cursor = self.connection.cursor() cursor.execute(sql % (eventId)) event = cursor.fetchone() issue_number = event[0] file_name = 'Document' + "-" + str(issue_number) + ".htm" if 'French' == language: file_name = 'Document-FR' + "-" + str(issue_number) + ".htm" dest_path = str(issue_number) + "/" + language path = settings.APPLICATION_SETTINGS[ 'EMAIL_HOME'] + '/' + dest_path + '/' + file_name #check if the file exists if not os.path.exists(path): raise CriticalError({ "message": "The path " + path + " is invalid. Cannot send email." }) f = open(path, 'r', encoding='utf-8') emailBody = f.read() f.close() cursor = self.connection.cursor() result = {} for record in queuedEmails: #for emails relay, lets check to see if it has been aborted if emailBody: sql = 'SELECT is_abort FROM web_email_audit WHERE issue_number = %d' cursor.execute(sql % (issue_number)) audits = cursor.fetchone() if audits and True == audits[0]: #abort command must have been issued, lets break from the for loop break recipient = record[0] sender = record[1] # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['From'] = sender msg['To'] = recipient msg['Subject'] = record[2] # Create the body of the message. Record the MIME types - text/html. if emailBody: finalContent = emailBody #go ahead to substitute the dynamic stuff finalContent = finalContent.replace( '{subscriber_email_address}', recipient) hash = hashlib.md5() hash.update(str(random.random()).encode("utf-8")) finalContent = finalContent.replace('{throwoff1}', hash.hexdigest()) hash1 = hashlib.md5() hash1.update(recipient.encode("utf-8")) finalContent = finalContent.replace('{user_hash}', hash1.hexdigest()) hash2 = hashlib.md5() hash2.update(str(random.random()).encode("utf-8")) finalContent = finalContent.replace('{throwoff2}', hash2.hexdigest()) part = MIMEText(finalContent, 'html', 'utf-8') else: part = MIMEText(record[3], 'html', 'utf-8') msg.attach(part) #if not abortSending: #mark that we have invoked the SMTP Relay agent to send the email params = {} params['sent_at'] = datetime.now() values = ', '.join(['%s = %%(%s)s' % (x, x) for x in params]) query = 'UPDATE email_schedule SET %s WHERE id = %d' % (values, record[4]) cursor.execute(query, params) #send the email status = self.sendEmail(sender, recipient, msg.as_string()) if status: #means that everything went OK, so lets mark the email as sent params = {} params['delivery_date'] = datetime.now() values = ', '.join(['%s = %%(%s)s' % (x, x) for x in params]) query = 'UPDATE email_schedule SET %s WHERE id = %d' % ( values, record[4]) cursor.execute(query, params) self.connection.commit() result[recipient + ' at id : ' + str( record[4] )] = status #;audit this, because we want to know the number of recipients of the email cursor.close() return result
def save_parent_child(self, postValues): """ we assume we will not register a child without a parent, and a parent without a child :param postValues: :return: """ parent = None child = None params = postValues.copy() if params.get('parent_names'): try: parent = CrecheParent.objects.get(id=params.get('id_number')) parent.names = params.get('parent_names') parent.telephone = params.get('telephone') parent.identity_document = params.get('id_number') parent.relationship = params.get('relationship') parent.full_address = params.get('full_address') parent.email = params.get('email'), parent.last_updated = datetime.now() except CrecheParent.DoesNotExist: parent = CrecheParent( names=params.get('parent_names'), telephone=params.get('telephone'), identity_document=params.get('id_number'), relationship=params.get('relationship'), full_address=params.get('full_address'), email=params.get('email'), date_created=datetime.now(), last_updated=datetime.now()) try: child_service = ChildService() child = child_service.save_child(postValues) print("CHILD : ", child.__dict__) if child: parent.save() parent.children.add(child) #parent.save() else: raise CriticalError({ 'message': "The child '" + params.get('child_names') + "' of parent '" + params.get("parent_names") + "' was not saved. Try again " }) except Exception as e: try: child.delete() parent.delete() except Exception as ex: print("ERROR ROLLING BACK", ex) print("PARENT CHILD ERROR ", e) raise CriticalError({ 'message': "Unkwon Error while saving child '" + params.get('child_names') + "' of parent '" + params.get("parent_names") + "'. Try again or contact system admin " }) return parent, child