def study_abroad(request): if request.method == 'POST': form = StudyAbroadForm(request.POST) if form.is_valid(): cd = form.cleaned_data cd['user'] = request.user email = request.user.email if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = [ settings.STUDY_ABROAD_EMAIL, email ] subject = "Student Information for Study Abroad" send_mail( request, TO_LIST, subject, email, 'languages/studyabroad/email.html', cd, settings.MANAGERS ) return HttpResponseRedirect( reverse_lazy('study_abroad_success') ) else: form = StudyAbroadForm() return render( request, 'languages/studyabroad/form.html', {'form': form} )
def candidate(request): if request.method=='POST': form = CandidateForm(request.POST) if form.is_valid(): candidate = form.save(commit=False) candidate.user = request.user candidate.save() # set the time slot active state to False candidate.time_slot.active = False candidate.time_slot.save() if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL,] else: TO_LIST = [candidate.user.email,] send_mail( request, TO_LIST, u"[Choral Tryout Reservation] {} {}".format( candidate.user.first_name,candidate.user.last_name ), settings.CHORAL_TRYOUTS_FROM, 'music/ensembles/choral/email.html', candidate, settings.MANAGERS ) return HttpResponseRedirect( reverse_lazy('choral_tryout_success') ) else: form = CandidateForm() return render( request, 'music/ensembles/choral/form.html', {'form': form,} )
def application_profile_form(request): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = list(settings.CHARACTER_QUEST_TO_LIST) BCC = settings.MANAGERS s_date = date( TODAY.year, settings.CHARACTER_QUEST_START_MONTH, settings.CHARACTER_QUEST_START_DAY ) x_date = date( TODAY.year, settings.CHARACTER_QUEST_END_MONTH, settings.CHARACTER_QUEST_END_DAY ) expired = False if x_date < TODAY or s_date > TODAY: if not request.user.is_staff and \ not request.user.has_perm('characterquest.change_applicationprofile'): expired = True try: profile = request.user.userprofile except: p = UserProfile(user=request.user) p.save() profile = request.user.userprofile if request.method=='POST': form = ApplicationForm(request.POST, prefix='applicant') profile_form = ApplicationProfileForm( request.POST, prefix='profile', instance=profile ) if form.is_valid() and profile_form.is_valid(): profile = profile_form.save() applicant = form.save(commit=False) applicant.profile = profile applicant.save() if not settings.DEBUG: TO_LIST.append(request.user.email) subject = "LEAD Retreat Application: {} {}".format( applicant.profile.user.first_name, applicant.profile.user.last_name ) send_mail ( request, TO_LIST, subject, request.user.email, 'characterquest/application_email.txt', applicant, BCC ) return HttpResponseRedirect('/forms/character-quest/success/') else: form = ApplicationForm(prefix='applicant') profile_form=ApplicationProfileForm(prefix='profile',instance=profile) return render( request, 'characterquest/application_form.html', {'form': form, 'profile_form':profile_form, 'expired':expired} )
def index(request): if request.method=='POST': form = CardRequestForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = [ settings.COPYPRINT_CARD_REQUEST_EMAIL, data.user.email ] subject = 'Copy Print Card Request: {}, {} from {}'.format( data.user.last_name, data.user.first_name, data.entity_name ) send_mail( request, TO_LIST, subject, data.user.email, 'lis/copyprint/email.html', data, settings.MANAGERS ) return HttpResponseRedirect( reverse_lazy('lis_success') ) else: form = CardRequestForm() return render( request, 'lis/copyprint/form.html', {'form':form,} )
def interest_form(request): if request.method=='POST': form = InterestForm(request.POST) if form.is_valid(): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = settings.ADMISSIONS_CHINA_EMAIL_LIST BCC = settings.MANAGERS data = form.cleaned_data subject = "[Admissions][China] Prospective Student ({} {})".format( data['last_name'],data['first_name'] ) send_mail( request, TO_LIST, subject, data['email'], 'admissions/china/email.html', data, BCC ) return HttpResponseRedirect( reverse_lazy('admissions_china_success') ) else: form = InterestForm() return render( request, 'admissions/china/form.html', { 'form': form, } )
def contact(request): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = settings.ALUMNI_CLASSNOTES_EMAILS BCC = settings.MANAGERS if request.method=='POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): contact = form.save() email = settings.DEFAULT_FROM_EMAIL if contact.email: email = contact.email subject = "[Alumni Class Notes] {} {}".format( contact.first_name,contact.last_name ) send_mail( request,TO_LIST, subject, email, 'alumni/classnotes/email.html', contact, BCC ) return HttpResponseRedirect( reverse_lazy('classnotes_success') ) else: form = ContactForm() manager = request.user.has_perm('classnotes.change_contact') return render( request, 'alumni/classnotes/form.html', {'form': form,'manager':manager,} )
def sftp_upload(upload_filename): # cnopts authorizes the program to ignore the host key cnopts = pysftp.CnOpts() cnopts.hostkeys = None # ignore known host key checking # sFTP connection information for Adironcack XTRNL_CONNECTION = { 'host': settings.ADIRONDACK_HOST, 'username': settings.ADIRONDACK_USER, 'password': settings.ADIRONDACK_PASS, 'port': settings.ADIRONDACK_PORT, 'cnopts': cnopts } try: # print("Make Connection") with pysftp.Connection(**XTRNL_CONNECTION) as sftp: # change directory # sftp.chdir("test/in/") sftp.chdir("prod/in/") # print(upload_filename) sftp.put(upload_filename, preserve_mtime=True) # close sftp connection sftp.close() except Exception as e: SUBJECT = '[Adirondack] UPLOAD failed' BODY = 'Unable to PUT .txt file to adirondack server.\n\n{0}'.format( repr(e) ) send_mail ( None, [settings.ADIRONDACK_TO_EMAIL,], SUBJECT, settings.ADIRONDACK_FROM_EMAIL, 'email/default.html', BODY, [settings.ADMINS[0][1],] ) logger.error(BODY)
def main(): """Update request tracker tickets for name change requests.""" tickets = Tickets.objects.using('rt4').filter( subject__contains='Name Change', ).filter(creator=167207).filter( queue=26).filter(ismerged__isnull=True, ).filter(status='new') if tickets: for ticket in tickets: context_dict = { 'status': ticket.status, 'creator': ticket.creator.name, 'creator email': ticket.creator.emailaddress, 'queue': ticket.queue, 'id': ticket.id, 'subject': ticket.subject, 'owner': ticket.owner.name, 'owner email': ticket.owner.emailaddress, } send_mail(None, TO, SUBJECT, FROM, 'email.html', context_dict) user = Users.objects.using('rt4').get(pk=149) ticket.status = 'resolved' ticket.owner = user ticket.resolved = NOW ticket.lastupdated = NOW ticket.lastupdatedby = 1873 ticket.save()
def phage_hunter_form(request): if request.method=='POST': form = PhageHunterForm(request.POST) if form.is_valid(): data = form.save() if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = settings.BIOLOGY_GENOMICS subject = "[Phage Hunters Application] {} {}".format( data.first_name, data.last_name ) send_mail( request, TO_LIST, subject, data.email, 'biology/genomics/phage_hunter_email.html', data, settings.MANAGERS ) return HttpResponseRedirect( reverse_lazy('phage_hunters_success') ) else: form = PhageHunterForm() return render( request, 'biology/genomics/phage_hunter_form.html', {'form': form,} )
def file_upload(phile): """Transfers the students.csv file to the Package Concierge server.""" # by adding cnopts, I'm authorizing the program to ignore the host key # and just continue cnopts = pysftp.CnOpts() # ignore known host key checking cnopts.hostkeys = None # sFTP connection information for Package Concierge xtrnl_connection = { 'host': settings.CONCIERGE_HOST, 'username': settings.CONCIERGE_USER, 'password': settings.CONCIERGE_PASS, 'port': settings.CONCIERGE_PORT, 'cnopts': cnopts, } try: with pysftp.Connection(**xtrnl_connection) as sftp: # sftp files if they end in .csv sftp.put(phile, preserve_mtime=True) # delete original files from our server os.remove(phile) except Exception as error: body = """ Unable to PUT .csv files to Package Concierge server.\n\n{0} """.format(error) send_mail( None, TO, SUBJECT(status='failed'), FROM, 'email.html', body, ) if DEBUG: print(error)
def index(request): if request.method=='POST': form = PrintRequestForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data data['date'] = datetime.date.today() BCC = settings.MANAGERS if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = [settings.LIS_PRINT_REQUEST_EMAIL, data['email']] subject = "[Print Request]: {} from the {} Department".format( data['name'],data['department'] ) send_mail( request, TO_LIST, subject, data['email'], 'lis/printjobs/email.html', data, BCC, attach=True ) return HttpResponseRedirect( reverse_lazy('lis_success') ) else: form = PrintRequestForm() return render( request, 'lis/printjobs/form.html', {'form': form,} )
def parking_ticket_appeal_form(request): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = [settings.SECURITY_PARKING_TICKET_APPEAL_EMAIL] if request.method == 'POST': form = ParkingTicketAppealForm(request.POST) if form.is_valid(): data = form.cleaned_data form.save() subject = "Parking Violation Appeal Request" send_mail( request, TO_LIST, subject, data['email'], 'security/parking_ticket_appeal/email.html', data, settings.MANAGERS ) return HttpResponseRedirect( reverse_lazy('parking_ticket_appeal_success') ) else: form = ParkingTicketAppealForm() return render( request, 'security/parking_ticket_appeal/form.html', {'form': form} )
def myview(request, pid=None): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL,] else: TO_LIST = [settings.MY_APP_EMAIL,] BCC = settings.MANAGERS if request.method=='POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): data = form.save() email = settings.DEFAULT_FROM_EMAIL if data.email: email = data.email subject = "[Submit] {} {}".format(data.first_name,data.last_name) send_mail( request,TO_LIST, subject, email,'myapp/email.html', data, BCC ) return HttpResponseRedirect( reverse_lazy('myapp_success') ) else: form = MyForm() return render( request, 'myapp/form.html', {'form': form,} )
def counseling(request): """Exit counseling document upload form.""" user = request.user try: questionnaire = user.questionnaire except Exception: questionnaire = None if questionnaire: if request.method == 'POST': form = CounselingForm( request.POST, request.FILES, use_required_attribute=REQ_ATTR, ) if form.is_valid(): doc = form.save(commit=False) doc.questionnaire = user.questionnaire doc.created_by = user doc.updated_by = user doc.save() doc.tags.add('Finaid') messages.add_message( request, messages.SUCCESS, "Document saved", extra_tags='alert-success', ) frum = user.email if doc.questionnaire.email: frum = doc.questionnaire.email subject = "[Exit Counseling Form] {0} {1}".format( user.first_name, user.last_name, ) send_mail( request, [settings.EXIT_COUNSELING_EMAIL], subject, frum, 'gearup/counseling_email.html', doc, ) return HttpResponseRedirect(reverse_lazy('home')) else: form = CounselingForm(use_required_attribute=REQ_ATTR) else: messages.add_message( request, messages.WARNING, "Please submit the Gear Up questionnaire", extra_tags='alert-warning', ) return HttpResponseRedirect(reverse_lazy('home')) return render( request, 'gearup/counseling.html', {'form': form}, )
def main(): """Maxient Upload via sftp.""" phile = os.path.join( settings.BASE_DIR, 'sql/maxient/demographic.sql', ) with open(phile) as incantation: sql = incantation.read() with get_connection() as connection: rows = xsql(sql, connection, key=settings.INFORMIX_DEBUG).fetchall() if rows: # set directory and filename filename = ('{0}CARTHAGE_DEMOGRAPHICS_DATA.txt'.format( settings.MAXIENT_CSV_OUTPUT, )) # create txt file using pipe delimiter with open(filename, 'w') as maxientfile: output = csv.writer(maxientfile, delimiter='|') if DEBUG: # No Header required but used for testing output.writerow(settings.MAXIENT_HEADERS) for row in rows: output.writerow(row) # SFTP connection information cnopts = pysftp.CnOpts() cnopts.hostkeys = None xtrnl_connection = { 'host': settings.MAXIENT_HOST, 'username': settings.MAXIENT_USER, 'private_key': settings.MAXIENT_PKEY, 'private_key_pass': settings.MAXIENT_PASS, 'cnopts': cnopts, } # go to our storage directory on the server os.chdir(settings.MAXIENT_CSV_OUTPUT) try: with pysftp.Connection(**xtrnl_connection) as sftp: sftp.chdir('incoming/') sftp.put(filename, preserve_mtime=True) if DEBUG: print("success: MAXIENT UPLOAD") except Exception as error: send_mail( None, settings.MAXIENT_TO_EMAIL, '[Maxient SFTP] MAXIENT UPLOAD failed', settings.MAXIENT_FROM_EMAIL, 'email.html', 'Unable to upload to Maxient server.\n\n{0}'.format(error), ) if DEBUG: print(error) else: print('There was a no values in list error')
def sendmail(request): message = 'error' if request.POST: email = request.POST['email'] subject = request.POST['subject'] data = {'content': request.POST['content']} send_mail( request, [email], subject, request.user.email, 'sendmail.html', data, settings.MANAGERS ) message = "success" return HttpResponse(message, content_type='text/plain; charset=utf-8')
def main(): """Package concierge upload.""" # determines which database is being called from the command line if database == 'cars': earl = settings.INFORMIX_ODBC elif database == 'train': earl = settings.INFORMIX_ODBC_TRAIN else: print('invalid database name: {0}'.format(database)) sys.exit() phile = os.path.join( settings.BASE_DIR, 'sql/concierge/students.sql', ) with open(phile) as incantation: sql = incantation.read() with get_connection(earl) as connection: rows = xsql(sql, connection, key=settings.INFORMIX_DEBUG).fetchall() if rows: # set directory and filename to be stored filename = '{0}students.csv'.format(settings.CONCIERGE_CSV_OUTPUT) # create .csv file with open(filename, 'w') as csvfile: output = csv.writer(csvfile) output.writerow([ 'Unit Code', 'First Name', 'Last Name', 'Email Address', 'Cell Phone', ]) # creating the data rows for the .csv files for row in rows: output.writerow([ row.unitcode, row.firstname, row.lastname, row.emailaddress, row.cellphone, ]) if not DEBUG: file_upload(filename) else: send_mail( None, TO, SUBJECT(status='failed'), FROM, 'email.html', 'No values in list.', )
def save_model(self, request, obj, form, change): obj.save() if "alumnistatus" in form.changed_data: if obj.alumnistatus: if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = ["*****@*****.**",] email = settings.DEFAULT_FROM_EMAIL subject = "[Alumni Class Notes] Alumni Office has approved this note" send_mail( request, TO_LIST, subject, email, "alumni/classnotes/email.html",obj,settings.MANAGERS)
def _send_mail(obj, request, registration): """ private function for sending an email """ to_list = [settings.WSGC_EMAIL,settings.WSGC_APPLICATIONS] # send email to managers send_mail( request, to_list, "[WSGC {} Registration] Other Institute".format(registration), settings.SERVER_MAIL, 'registration/email_wsgc_affiliate_other.html', obj, [settings.MANAGERS[0][1],] )
def registration_notify(request, action, user): subject = u"[WSGC Profile Registration: {}D] {}, {}".format( action.upper(), user.last_name, user.first_name ) if settings.DEBUG: TO_LIST = [settings.ADMINS[0][1],] else: TO_LIST = [settings.WSGC_APPLICATIONS,] template = 'account/registration_alert_email.html' context = { 'user':user, 'action':action, 'server_url':settings.SERVER_URL, 'media_url':settings.MEDIA_URL } send_mail( request,TO_LIST,subject,user.email,template,context,settings.MANAGERS )
def email_form(request, aid, action): """Send an email.""" form_data = None alert = get_object_or_404(Alert, pk=aid) if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): form_data = form.cleaned_data if 'execute' in request.POST: if DEBUG: to_list = [MANAGER] else: to_list = [] send_mail( request, to_list, "[Student Outreach System] {0}".format( form_data['subject']), request.user.email, 'email_form.html', {'content': form_data['content']}, [settings.ADMINS[0][1]], ) return HttpResponseRedirect(reverse_lazy('email_done')) else: return render( request, 'email_form.html', { 'form': form, 'data': form_data, 'p': proposal }, ) else: form = EmailForm() return render( request, 'email_form.html', { 'form': form, 'data': form_data, 'alert': alert, 'action': action }, )
def pledge_form(request): ''' simple form to submitting a pledge of fealty. ''' if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = settings.SUSTAINABILITY_EMAIL_LIST BCC = settings.MANAGERS user = request.user anon = True pledge = None if user.username: anon = False try: pledge = Pledge.objects.get(user=user) except: pledge = None if request.method=='POST': form = PledgeForm(request.POST) if form.is_valid() and not pledge: data = form.save(commit=False) data.user = request.user data.save() subject = "[Sustainability Pledge] {} {}".format( user.first_name,user.last_name ) send_mail( request,TO_LIST,subject,user.email, 'sustainability/green/email.html', data, BCC ) return HttpResponseRedirect( reverse_lazy('green_pledge_success') ) else: form = PledgeForm(initial={'user':user}) return render( request, 'sustainability/green/form.html', {'form': form, 'anon': anon, 'pledge':pledge,} )
def main(): ''' main function ''' from djtools.utils.mail import send_mail request = False alert = Alert.objects.get(pk=aid) user = User.objects.get(email=email) send_mail(request, [ email, ], "Assignment to Intervention Team", settings.CSS_FROM_EMAIL, 'alert/email_team_added.html', { 'alert': alert, 'user': user }, [ settings.ADMINS[0][1], ])
def chance_of_form(request): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = settings.ADMISSIONS_ADMITTED_EMAIL_LIST BCC = ( ('Confirmation', '*****@*****.**'), ) prospect_status = None if request.GET.keys(): prospect_status = request.GET.keys()[0] if request.method=='POST': form = ChanceOfForm(request.POST) if form.is_valid(): data = form.save() if data.gpa_scale == '100': data.adjusted_gpa = (float(data.gpa) - 60)/10 else: data.adjusted_gpa = (float(data.gpa) * 4) / float(data.gpa_scale) data.save() subject = u"Carthage, will I be admitted? ({})".format( data.first_name ) send_mail( request, TO_LIST, subject, data.email, 'admissions/admitted/email.html', data, BCC ) return HttpResponseRedirect( reverse_lazy('admitted_success') ) else: prospect_status = request.POST.get('prospect_status') else: form = ChanceOfForm() return render( request, 'admissions/admitted/form.html', { 'form': form, 'prospect_status':prospect_status } )
def save(self, *args, **kwargs): # send email if approved if self.pk is not None: prez = Presentation.objects.get(pk=self.pk) if (prez.status != self.status) and self.status: if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = [self.user.email,] BCC = settings.MANAGERS email = settings.DEFAULT_FROM_EMAIL subject = "[Celebration of Scholars] Presentation has been approved" send_mail( None,TO_LIST,subject,email, 'scholars/presentation/approved_mail.html',self,BCC ) else: self.updated_by = self.user super(Presentation, self).save()
def email_presenters(request,pid,action): """ method to send an email to the presenters and faculty sponsor """ form_data = None presentation = get_object_or_404(Presentation,id=pid) if request.method=='POST': form = EmailPresentersForm(request.POST) if form.is_valid(): form_data = form.cleaned_data if 'confirm' in request.POST: context = {'form':form,'data':form_data,'p':presentation} return render( request, 'scholars/presenters/email_form.html', context ) elif 'execute' in request.POST: FEMAIL = request.user.email TO_LIST = [presentation.user.email,] if presentation.leader.sponsor_email: if settings.DEBUG: TO_LIST.append(settings.SERVER_EMAIL) else: TO_LIST.append(presentation.leader.sponsor_email) data = {'content':form_data['content']} sub = "[Celebration of Scholars] Info about your presentation" send_mail ( request, TO_LIST, sub, FEMAIL, 'scholars/presenters/email_data.html', data, BCC ) return HttpResponseRedirect(reverse('email_presenters_done')) else: return HttpResponseRedirect( reverse('email_presenters_form', args=[pid,action]) ) else: form = EmailPresentersForm() return render( request, 'scholars/presenters/email_form.html', {'form': form,'data':form_data,'p':presentation,'action':action} )
def main(): """Send emails to recipients of thank you notes.""" notes = Annotation.objects.all() for note in notes: if note.status: to = [note.recipients.all()[0].email] frum = note.questionnaire.email if not frum: frum = note.created_by.email if DEBUG: note.to = to note.frum = frum to = [settings.MANAGERS[0][1]] subject = "A Thank You Note from {0} {1}".format( note.created_by.first_name, note.created_by.last_name, ) print(to, frum, subject) send_mail(None, to, subject, frum, 'gearup/notes_email.html', note) note.status = False note.save()
def info_request(request): if request.method == 'POST': form = InfoRequestForm(request.POST) if form.is_valid(): cd = form.cleaned_data to = settings.INFORMATION_REQUEST_EMAIL_LIST if settings.DEBUG: to = [settings.SERVER_MAIL,] subject = "OCS Information Request" send_mail( request, to, subject, cd['email'], 'admissions/inforequest.txt', cd, BCC, content='' ) return HttpResponseRedirect( reverse_lazy('info_request_success') ) else: form = InfoRequestForm() return render( request, 'admissions/inforequest.html',{'form': form,} )
def send_message(request): recipient_id = request.POST.get('recipientID') recipient = get_message_info(recipient_id) attachEmail = request.POST.get('addEmail', 'N') emailBody = request.POST.get('emailBody') sender = get_message_info(request.user.id) # If the inforamation about the sender is unavailable, # create empty/default values if sender == None or len(sender) == 0: sender = { 'id':0, 'email':settings.DEFAULT_FROM_EMAIL, 'firstname':'a', 'lastname':'friend', } autoAddOn = '' if attachEmail == 'Y': autoAddOn = 'Y' # Initialize necessary components to generate email data = { 'body':emailBody,'recipient':recipient,'auto':autoAddOn,'sender':sender } subject = u"Message from {} {} via the Carthage Alumni Directory".format( sender.firstname, sender.lastname ) send_mail( request, [recipient.email,], subject, sender.email, 'manager/send_message.html', data, settings.MANAGERS ) # Reuse the search page return HttpResponseRedirect( reverse('manager_search_sent', kwargs={'messageSent':True}) )
def info_session(request, session_type): try: STYPES[session_type] except: raise Http404, "Page not found" if request.method == 'POST': form = InfoSessionForm(session_type,request.POST) if form.is_valid(): cd = form.cleaned_data cd['session_type'] = session_type # fetch event event = Event.objects.using('livewhale').get(pk=cd['event']) cd['event'] = event # munge datetime lc = localtime(event.date_dt) df = DateFormat(lc) day = df.format('D') date = df.format('M d, Y') time = df.format('h:ia') datetime = '%s. %s at %s' % (day, date, time) cd['datetime'] = datetime # to recipients = settings.CONTINUING_EDUCATION_INFOSESSION_RECIPIENTS to = recipients[session_type] if settings.DEBUG: to = [settings.SERVER_MAIL,] subject = "OCS Information Session Request: " subject +="%s on %s" % (session_type, datetime) send_mail( request, to, subject, cd['email'], 'admissions/infosession.txt', cd, BCC, content='' ) return HttpResponseRedirect( reverse_lazy('info_session_success') ) else: form = InfoSessionForm(session_type) return render( request, 'admissions/infosession.html',{'form': form,} )
def main(): # execute SQL statement sqlresult = do_sql(GET_GL_ACCTS, earl=EARL) # formatting date and time string datetimestr = time.strftime("%Y-%m-%d") # set directory and filename filename = ('{0}gl_data/glrec_data.csv'.format( settings.PAPERCUT_CSV_OUTPUT)) # set destination path and new filename that it will be renamed # to when archived archive_destination = ('{0}/gl_data/{1}_{2}.csv'.format( settings.PAPERCUT_CSV_ARCHIVED, 'glrec_data_bak', datetimestr)) # opens a file for writing with open(filename, 'w') as glrecfile: for row in sqlresult: try: # creates a formatted string accountName = ("{0}/{1}-{2}-{3}".format( row['acct_descr'].split('/', 1)[1], row['fund'], row['func'], row['obj'])) # writes a formatted string to the file glrecfile.write('{0}\n'.format(accountName)) except Exception as e: #print "Exception: {0}".format(str(e)) # Email that there was an exception error while processing .csv SUBJECT = "[Papercut] GL Exception Error" BODY = "There was an exception error: {0}".format(str(e)) send_mail(None, TO, SUBJECT, FROM, TEMPLATE, BODY, bcc=BCC) # close file glrecfile.close() # removed for now S. Smolik 1/19/2018 # sends email attachment # file_attach = '{0}glrec_data.csv'.format(settings.PAPERCUT_CSV_OUTPUT) # subject = "[GL Account Names] attachment" # send_mail( # None, TO, SUBJECT, FROM, TEMPLATE, BODY, bcc=BCC, attach=file_attach #) # renaming old filename to newfilename and move to archive location shutil.copy(filename, archive_destination)
def print_request(request): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = [settings.COMMUNICATIONS_PRINT_REQUEST_EMAIL] if request.method == 'POST': form = PrintRequestForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user = request.user data.updated_by = request.user data.save() if not settings.DEBUG: TO_LIST.append(data.user.email) subject = u"[Print request] {}: {}".format( data.project_name, data.date_created ).encode('utf-8').strip() send_mail( request, TO_LIST, subject, data.user.email, 'communications/printrequest/email.html', data, settings.MANAGERS ) return HttpResponseRedirect(reverse('print_request_success')) else: return render( request, 'communications/printrequest/email.html', {'data': data,} ) else: form = PrintRequestForm() return render( request, 'communications/printrequest/form.html', { 'form': form, } )
def registration(request): if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = settings.POLISCI_MUN_EMAIL_LIST BCC = settings.MANAGERS if request.method=='POST': form_cont = AttenderForm(request.POST, prefix='cont') form_pais = CountryForm(request.POST, prefix='pais') if form_cont.is_valid() and form_pais.is_valid(): contact = form_cont.save() paises = form_pais.cleaned_data contact.delegation_1 = paises['delegation_1'] contact.delegation_2 = paises['delegation_2'] contact.delegation_3 = paises['delegation_3'] contact.delegation_4 = paises['delegation_4'] contact.delegation_5 = paises['delegation_5'] contact.save() data = {'object':contact} subject = "[Model United Nations Registration] {} {} of {}".format( contact.first_name, contact.last_name, contact.school_name ) send_mail( request, TO_LIST, subject, contact.email, 'polisci/model_united_nations/email.html', data, BCC ) return HttpResponseRedirect( reverse_lazy('model_united_nations_success') ) else: form_cont = AttenderForm(prefix='cont') form_pais = CountryForm(prefix='pais') return render( request, 'polisci/model_united_nations/form.html', { 'form_cont':form_cont,'form_pais':form_pais, } )
def email_investigator(request, pid, action): ''' send an email to the primary investigator ''' form_data = None proposal = get_object_or_404(Proposal, id=pid) if request.method=='POST': form = EmailInvestigatorForm(request.POST) if form.is_valid(): form_data = form.cleaned_data if 'execute' in request.POST: if DEBUG: to_list = [MANAGER] else: to_list = [proposal.user.email] send_mail ( request, to_list, u"[Office of Sponsored Programs] Grant Proposal: {}".format( proposal.title ), request.user.email, 'investigator/email_data.html', {'content':form_data['content']}, BCC ) return HttpResponseRedirect( reverse_lazy('email_investigator_done') ) else: return render ( request, 'investigator/email_form.html', {'form':form,'data':form_data,'p':proposal} ) else: form = EmailInvestigatorForm() return render( request, 'investigator/email_form.html', {'form': form,'data':form_data,'p':proposal,'action':action} )
def sendmail(request, redirect): """ Send emails to program applicants. POST from admin action email_applicants. """ redirect = '{}/{}'.format(settings.ROOT_URL, redirect) if request.POST: # form stuff form = EmailApplicantsForm(request.POST) form.is_valid() data = form.cleaned_data # content type ct = ContentType.objects.get_for_id(data['content_type']) # program ids pids = request.POST.getlist('pids[]') # email subject sub = "WSGC: Information about your {} application".format( data['title'] ) bcc = [request.user.email,settings.SERVER_MAIL] for pid in pids: obj = ct.get_object_for_this_type(pk=pid) to = [obj.user.email] send_mail( request, to, sub, settings.SERVER_EMAIL, 'admin/email_data.html', {'obj':obj,'content':data['content']}, bcc ) messages.add_message( request, messages.SUCCESS, 'Your message was sent successfully.', extra_tags='success' ) return HttpResponseRedirect(redirect) else: return HttpResponseRedirect(redirect)
def insurance_card(request): if request.POST: form = SoccerCampInsuranceCardForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data subject = u"[Insurance card]: {}, {}".format( data['last_name'], data['first_name'] ) send_mail( request, INSURANCE_TO_LIST, subject, data['email'], 'athletics/soccer/camp_insurance_card_email.html', data, BCC, attach=True ) return HttpResponseRedirect( reverse('soccer_camp_insurance_card_success') ) else: form = SoccerCampInsuranceCardForm() return render( request, 'athletics/soccer/camp_insurance_card_form.html', {'form': form,} )
def done(self, form_list, **kwargs): # keeps python from concatenating other sessions if settings.DEBUG: TO_LIST = [settings.SERVER_EMAIL] else: TO_LIST = list(settings.CATERING_TO_LIST) event = Event() xfields = {'open_to':'', 'room_set_up':'', 'beverages':''} for form in form_list: for field, value in form.cleaned_data.iteritems(): if field not in xfields: setattr(event, field, value) else: xfields[field] = value event.user = self.request.user event.save() event.open_to = xfields['open_to'] event.room_set_up = xfields['room_set_up'] event.beverages = xfields['beverages'] event.save() # send mail email = event.user.email TO_LIST.append(email) subject = "[Event Request Form] {}: {} {}".format( event.department,event.user.first_name,event.user.last_name ) send_mail( self.request, TO_LIST, subject, email, 'catering/event_email.html', {'event':event,}, settings.MANAGERS ) return HttpResponseRedirect( reverse_lazy('catering_event_success') )
def subscription(request,action): """ subscribe or unsubscribe a contact to a newsletter via ajax POST or GET. POST/GET data: list id email returns response message for display to user """ # we will need GET for email confirmations if request.POST: lid = request.POST['lid'] email = request.POST['email'] elif request.GET: lid = request.GET['lid'] email = request.GET['email'] #action = request.GET.get('action') else: return HttpResponseRedirect( reverse('newsletters_home') ) cs = CreateSend({'api_key': settings.API_KEY}) subscriber = Subscriber( list_id=lid, email_address=email, auth={'api_key': settings.API_KEY} ) list_obj = List(list_id=lid, auth={'api_key': settings.API_KEY}) # action if action == 'unsubscribe': response = subscriber.unsubscribe() elif action == 'subscribe': response = subscriber.add(lid, email, '', [], True, 'unchanged') else: return HttpResponseRedirect( reverse('newsletters_home') ) # send email confirmation subject = '{} request for Carthage Newsletter: {}'.format( action.capitalize(),list_obj.details().Title ) template = 'confirmation_email.html' for d in settings.DESCRIPTIONS: if d[0] == lid: desc = d[1] data = { 'id':lid,'title':list_obj.details().Title, 'description':desc,'email':email,'action':action } send_mail(request, [email,], subject, FEMAIL, template, data) # check user status on lists sub = False count = 0 client = Client( client_id=settings.CARTHAGE_CM_ID, auth={'api_key': settings.API_KEY} ) for l in client.lists(): list_obj = List(list_id=l.ListID, auth={'api_key': settings.API_KEY}) subscriber = Subscriber( list_id=l.ListID, auth={'api_key': settings.API_KEY} ) try: me = subscriber.get(list_id=l.ListID, email_address=email) if me.State == 'Active': sub = True count += 1 except: pass # send notification if no lists or first list. # OJO: eventually this will go directly to CX if (action == 'unsubscribe' and not sub) or ( action == 'subscribe' and count == 1): subject = '{} request: {}'.format(action.capitalize(), email) template = 'alert.html' data = {'email':email,'action':action,} send_mail( request, settings.EMAIL_NOTIFICATION, subject, FEMAIL, template, data ) if request.POST: return render( request, 'ajax_response.html', {'response':response, } ) else: return HttpResponseRedirect( reverse('newsletters_manager') + '?email={}'.format(email) )
def manager(request): """Manage object relationships for an Alert and for Alert values.""" user = request.user data = {'msg': "Success", 'id': ''} if request.is_ajax() and request.method == 'POST': post = request.POST # simple error handling to prevent malicious values try: oid = int(post.get('oid')) aid = int(post.get('aid')) except: raise Http404("Invalid alert or object ID") mod = post.get('mod') alert = get_object_or_404(Alert, pk=aid) action = post.get('action') if mod == 'category': obj = get_object_or_404(GenericChoice, pk=oid) if action == 'add': alert.category.add(obj) elif action == 'remove': alert.category.remove(obj) else: data['msg'] = "Options: add or remove" elif mod == 'team': try: user = User.objects.get(pk=oid) except User.DoesNotExist: # chapuza because the LDAP attribute for user ID has a space # in the name and we cannot search on it. sql = 'SELECT * FROM cvid_rec WHERE cx_id={0}'.format(oid) with get_connection() as connection: cvid_rec = xsql(sql, connection).fetchone() if cvid_rec: username = cvid_rec.ldap_name.strip() eldap = LDAPManager() result_data = eldap.search(username, field='cn') groups = eldap.get_groups(result_data) user = eldap.dj_create(result_data, groups=groups) else: user = None if user: if action == 'add': mail = False if not alert.team.all() and alert.status != 'In progress': alert.status = 'Assigned' alert.save() try: member = Member.objects.get(user=user, alert=alert) if member.status: data['msg'] = "User is already a team member" else: member.status = True member.save() data['msg'] = "User has been reactivated" data['id'] = member.id mail = True except Exception: member = Member.objects.create(user=user, alert=alert) alert.team.add(member) data['msg'] = "User added to team" data['id'] = member.id mail = True if mail: to_list = [member.user.email] bcc = [ settings.ADMINS[0][1], ] if settings.DEBUG: to_list = bcc send_mail( request, to_list, "Assignment to Outreach Team", settings.CSS_FROM_EMAIL, 'alert/email_team_added.html', { 'alert': alert, 'user': member.user }, bcc, ) elif action == 'remove': member = get_object_or_404(Member, user=user, alert=alert) member.status = False member.case_manager = False member.save() else: data['msg'] = "Options: add or remove" else: data['msg'] = "User not found" elif mod == 'comment': note = None body = post.get('value') t = loader.get_template('alert/annotation.inc.html') if oid == 0: if not alert.notes.all(): alert.status = 'In progress' alert.save() note = Annotation.objects.create(alert=alert, created_by=user, updated_by=user, body=body, tags='Comments') alert.notes.add(note) context = {'obj': note, 'bgcolor': 'bg-warning'} data['msg'] = t.render(context, request) else: try: note = Annotation.objects.get(pk=oid) if action == 'fetch': data['msg'] = note.body elif action == 'delete': note.delete() else: note.body = body note.updated_by = user note.save() context = {'obj': note, 'bgcolor': 'bg-warning'} data['msg'] = t.render(context, request) data['id'] = note.id except: data['msg'] = "Follow-up not found" elif mod == 'concern': name = post.get('name') data['id'] = aid if action == 'fetch': data['msg'] = getattr(alert, name) else: value = post.get('value') # 'type of concern' / category is a list and m2m from alert if name == 'category': # disassociate the related objects alert.category.clear() # set the current relationships for gid in post.getlist('value[]'): gc = GenericChoice.objects.get(pk=gid) alert.category.add(gc) else: setattr(alert, name, value) alert.save() if name in ['description', 'interaction_details']: data[ 'msg'] = '<div class="card-text" id="oid_{}_{}">{}</div>'.format( name, aid, value) else: data['msg'] = 'Success' else: data['msg'] = "Invalid Data Model" else: data['msg'] = "Requires AJAX POST" return HttpResponse( json.dumps(data), content_type='application/json; charset=utf-8', )
def main(): """Send all student, adult, facstaff records to everbridge.""" # determines which database is being called from the command line if database == 'cars': earl = settings.INFORMIX_ODBC elif database == 'sandbox': earl = settings.INFORMIX_ODBC_SANDBOX elif database == 'train': earl = settings.INFORMIX_ODBC_TRAIN else: print('invalid database name: {0}'.format(database)) sys.exit() for key in ('students', 'adult', 'facstaff'): sql_file = os.path.join( settings.BASE_DIR, 'sql/everbridge/{0}.sql'.format(key), ) with open(sql_file) as incantation: sql = incantation.read() if limit: sql += 'LIMIT {0}'.format(limit) if test: print('key = {0}, sql = {1}'.format(key, sql)) badmatches = [] with get_connection(earl) as connection: rows = xsql(sql, connection, key=settings.INFORMIX_DEBUG).fetchall() if rows: if test: print("rows {0}".format(len(rows))) filename = ('{0}{1}_upload_{2}.csv'.format( settings.EVERBRIDGE_CSV_OUTPUT, key, time.strftime('%Y%m%d%H%M%S'), )) with open(filename, 'w') as csv_file: output = csv.writer( csv_file, dialect='excel', lineterminator='\n', ) if key == 'facstaff': # write header row for FacStaff output.writerow(settings.EVERBRIDGE_FACSTAFF_HEADERS) else: # write header row for Student and Adult output.writerow(settings.EVERBRIDGE_STUDENT_HEADERS) for row in rows: if row.customvalue1: row.customvalue1 = row.customvalue1.strip() output.writerow(row) if test: print("row = \n{0}".format(row)) # checking for Bad match in either students or facstaff if row and ((row.customvalue1 and 'Bad match:' in row.customvalue1) \ or (row.customvalue2 and 'Bad match:' in row.customvalue2)): badmatches.append(""" {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10} {11} {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19} {20}\n\n """.format( row.lastname, row.firstname, row.middleinitial, row.suffix, row.externalid, row.country, row.businessname, row.recordtype, row.phone1, row.phonecountry1, row.emailaddress1, row.emailaddress2, row.sms1, row.sms1country, row.customfield1, row.customvalue1, row.customfield2, row.customvalue2, row.customfield3, row.customvalue3, row.end, )) badmatches_table = ''.join(badmatches) if test: print("badmatches = \n{0}".format(badmatches)) if badmatches: if test: print("badmatches_table = \n{0}".format( badmatches_table, )) print("length of badmatches = {0}.".format( len(badmatches), )) body = """ A bad match exists in the file we are sending to Everbridge.\n\n{0}\n\n Bad match records: {1} """.format(badmatches_table, len(badmatches)) send_mail( None, TO, '[Everbridge] Bad match', FROM, 'email.html', body, ) else: print('No bad matches found.') if not test: # SFTP the CSV try: print('sftp attempt') print(filename) # go to our storage directory on the server os.chdir(settings.EVERBRIDGE_CSV_OUTPUT) cnopts = pysftp.CnOpts() cnopts.hostkeys = None xtrnl_connection = { 'host': settings.EVERBRIDGE_HOST, 'username': settings.EVERBRIDGE_USER, 'private_key': settings.EVERBRIDGE_PKEY, 'cnopts': cnopts, } with pysftp.Connection(**xtrnl_connection) as sftp: sftp.chdir("replace/") print("current working directory: {0}".format( sftp.getcwd(), )) sftp.put(filename, preserve_mtime=True) print("file uploaded:") for phile in sftp.listdir(): print(phile) print(str(sftp.lstat(phile))) sftp.close() print("sftp put success: {0}".format(key)) except Exception as error: print('sftp put fail [{0}]: {1}'.format(key, error)) body = """ Unable to PUT upload to Everbridge server.\n\n{0} """.format(error) send_mail( None, TO, '[Everbridge SFTP] {0} failed'.format(key), FROM, 'email.html', body, ) else: print("TEST: no sftp") else: print("No results from the database for {0}".format(key)) print("Done")
def impact_form(request, pid): ''' Proposal Form Part B view ''' proposal = get_object_or_404(Proposal, id=pid) user = request.user perms = proposal.permissions(user) # we do not allow PIs to update their proposals after save-submit # but OSP can do so group = in_group(user, OSP_GROUP) if (user != proposal.user and not group) or \ (proposal.save_submit and user == proposal.user) or \ (proposal.decline and user == proposal.user) or \ (proposal.closed and user == proposal.user) or \ (proposal.closed or proposal.decline and group): return HttpResponseRedirect(reverse_lazy('home')) # budget and impact try: impact = proposal.proposal_impact budget = proposal.proposal_budget except: impact = budget = None # documents docs = [None,None,None] for c, d in enumerate(proposal.proposal_documents.all()): docs[c] = d if request.method=='POST': form_impact = ImpactForm( request.POST, instance=impact, label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_budget = BudgetForm( request.POST, request.FILES, instance=budget, prefix='budget', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_comments = CommentsForm( request.POST, prefix='comments', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_doc1 = DocumentForm( request.POST, request.FILES, instance=docs[0], prefix='doc1', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_doc2 = DocumentForm( request.POST, request.FILES, instance=docs[1], prefix='doc2', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_doc3 = DocumentForm( request.POST, request.FILES, instance=docs[2], prefix='doc3', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) if form_impact.is_valid() and form_budget.is_valid() and \ form_doc1.is_valid() and form_doc2.is_valid() and \ form_doc3.is_valid(): # proposal impact impact = form_impact.save(commit=False) impact.proposal = proposal impact.save() # set proposal opened to False if it was True if proposal.opened: proposal.opened = False proposal.save() # proposal budget budget = form_budget.save(commit=False) budget.proposal = proposal budget.save() # proposal comments (not a ModelForm) if request.POST.get('comments-comments'): form_comments.is_valid() comments = form_comments.cleaned_data proposal.comments = comments['comments'] proposal.save() # document 1 doc1 = form_doc1.save(commit=False) doc1.proposal = proposal doc1.save() # document 2 doc2 = form_doc2.save(commit=False) doc2.proposal = proposal doc2.save() # document 3 doc3 = form_doc3.save(commit=False) doc3.proposal = proposal doc3.save() # Send email to Approvers and Division Dean if the PI is finished # with the proposal # (i.e. hits 'submit-save' rather than 'save and continue') post = request.POST if post.get('save_submit') and not proposal.save_submit: # set the save submit flag so PI cannot update proposal.save_submit = True proposal.save() # email approvers subject = ( u'Routing & Authorization Form Part B: ' 'Your Approval Needed for "{}" by {}, {}' ).format( proposal.title, proposal.user.last_name, proposal.user.first_name ) to_list = [] for a in proposal.approvers.all(): to_list.append(a.user.email) if DEBUG: proposal.to_list = to_list to_list = [MANAGER] if to_list: # send the email to Approvers send_mail( request, to_list, subject, proposal.user.email, 'impact/email_approve_approvers.html', proposal, BCC ) # email Division Dean (level3) where = 'PT.pcn_03 = "{}"'.format(proposal.department) chairs = department_division_chairs(where) # staff do not have deans so len will be 0 in that case if len(chairs) > 0: subject = ( u'Review and Provide Final Authorization for PART B: ' '"{}" by {}, {}' ).format( proposal.title, proposal.user.last_name, proposal.user.first_name ) # we need department full name in email proposal.department_name = chairs[0][0] # Division dean's email to_list = [chairs[0][8]] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] # send the email send_mail( request, to_list, subject, proposal.user.email, 'impact/email_approve_level3.html', proposal, BCC ) # send confirmation to the Primary Investigator (PI) # who submitted the form subject = u"[Part B] Submission Received: {}".format( proposal.title ) to_list = [proposal.user.email] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] # send the email send_mail( request, to_list, subject, PROPOSAL_EMAIL_LIST[0], 'impact/email_confirmation.html', proposal, BCC ) return HttpResponseRedirect( reverse_lazy('impact_success') ) else: messages.add_message( request, messages.SUCCESS, ''' Your proposal data have been saved. ''', extra_tags='success' ) return HttpResponseRedirect( reverse_lazy('impact_form', kwargs={'pid': proposal.id}) ) else: form_impact = ImpactForm( instance=impact, label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_budget = BudgetForm( instance=budget, prefix='budget', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_comments = CommentsForm( initial={'comments':proposal.comments}, prefix='comments', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_doc1 = DocumentForm( instance=docs[0], prefix='doc1', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_doc2 = DocumentForm( instance=docs[1], prefix='doc2', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) form_doc3 = DocumentForm( instance=docs[2], prefix='doc3', label_suffix='', use_required_attribute = REQUIRED_ATTRIBUTE ) return render( request, 'impact/form.html', { 'form_budget': form_budget, 'form_comments': form_comments, 'form_impact': form_impact, 'form_doc1': form_doc1, 'form_doc2': form_doc2, 'form_doc3': form_doc3, 'perms': perms } )
def proposal_status(request): ''' scope: set the status on a proposal. options: approve, decline, open, close, needs work method: AJAX POST ''' # requires POST request if request.POST: pid = request.POST.get('pid') try: pid = int(pid) except: return HttpResponse("Access Denied") user = request.user approver = False proposal = get_object_or_404(Proposal, id=pid) perms = proposal.permissions(user) # if user does not have 'approve' permissions, we can stop here, # regardless of whether we are approving/declining, closing/opening, # or indicating that the proposal "needs work". if not perms['approve'] and not perms['open']: return HttpResponse("Access Denied") else: status = request.POST.get('status') if not status: return HttpResponse("No status") # close if status == 'close': if perms['close']: proposal.closed = True proposal.opened = False proposal.decline = False proposal.level3 = False proposal.email_approved = False proposal.save_submit = False proposal.save() # we might not have a proposal impact relationship if proposal.impact(): proposal.proposal_impact.disclosure_assurance = False proposal.proposal_impact.level3 = False proposal.proposal_impact.level2 = False proposal.proposal_impact.level1 = False proposal.proposal_impact.save() # Approvers for a in proposal.approvers.all(): a.step1 = False a.step2 = False a.save() return HttpResponse("Proposal has been closed") else: return HttpResponse("You do not have permission to close") # open if status == 'open': if perms['open']: # Approvers for a in proposal.approvers.all(): if not proposal.step1() and not proposal.closed: a.step1 = False if proposal.step1() and not proposal.closed: a.step2 = False a.save() # reset booleans back to False if not proposal.step1() and not proposal.closed: proposal.level3 = False proposal.closed = False proposal.opened = True proposal.decline = False proposal.email_approved = False proposal.save_submit = False proposal.proposal_type = 'resubmission' proposal.save() # we might not have a proposal impact relationship if proposal.step1() and proposal.impact(): proposal.proposal_impact.disclosure_assurance = False proposal.proposal_impact.level3 = False proposal.proposal_impact.level2 = False proposal.proposal_impact.level1 = False proposal.proposal_impact.save() return HttpResponse("Proposal has been reopened") else: return HttpResponse("You do not have permission to open") # find out on which step we are decline_template = 'impact/email_decline.html' decline_subject = u'Part B: Not approved, requires \ additional clarrification: "{}"'.format(proposal.title) needs_work_template = 'impact/email_needswork.html' needs_work_subject = u'Part B: Needs work, requires \ additional clarrification: "{}"'.format(proposal.title) if not proposal.step1(): step = 'step1' decline_template = 'proposal/email_decline.html' decline_subject = u'Part A: Not approved, requires \ additonal clarrification: "{}"'.format(proposal.title) needs_work_template = 'proposal/email_needswork.html' needs_work_subject = u'Part A: Needs work, requires \ additonal clarrification: "{}"'.format(proposal.title) elif proposal.step1() and not proposal.impact(): return HttpResponse("Step 2 has not been initiated") elif proposal.impact() and not proposal.save_submit: return HttpResponse("Step 2 has not been completed") else: step = 'step2' # anyone can decline, for now. i suspect that will change # and thus the data model will have to change. if status == 'decline': if perms['decline']: # Proposal object proposal.decline = True proposal.opened = False proposal.email_approved = False proposal.save_submit = False if step == 'step1': proposal.level3 = False proposal.save() # ProposalImpact object if step == 'step2': proposal.proposal_impact.level1 = False proposal.proposal_impact.level2 = False proposal.proposal_impact.level3 = False proposal.proposal_impact.disclosure_assurance = False proposal.proposal_impact.save() # Approvers for a in proposal.approvers.all(): if a.user == user: if step == 'step1': a.step1 = False else: a.step2 = False a.save() break # send email to PI to_list = [proposal.user.email] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] send_mail( request, to_list, decline_subject, user.email, decline_template, proposal, BCC ) return HttpResponse("Proposal Declined") else: return HttpResponse("You don't have permission to decline") # we can stop here if 'needs work', just like decline. if status == 'needswork': if perms['needswork']: # Proposal object proposal.decline = False proposal.closed = False proposal.opened = True proposal.email_approved = False proposal.save_submit = False proposal.proposal_type = 'revised' if step == 'step1': proposal.level3 = False proposal.save() # ProposalImpact object if step == 'step2': proposal.proposal_impact.level1 = False proposal.proposal_impact.level2 = False proposal.proposal_impact.level3 = False proposal.proposal_impact.disclosure_assurance = False proposal.proposal_impact.save() # Approvers for a in proposal.approvers.all(): if step == 'step1': a.step1 = False else: a.step2 = False a.save() break to_list = [proposal.user.email] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] send_mail( request, to_list, needs_work_subject, user.email, needs_work_template, proposal, BCC ) return HttpResponse('Proposal "needs work" email sent') else: return HttpResponse("Permission denied") # # begin approve logic # # default email subject subject = u'{}: "{}"'.format( 'You are Approved to begin Part B', proposal.title ) # establish the email distribution list to_list = [proposal.user.email] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] # default message for when none of the conditions below are met message = "You do not have permission to '{}'".format(status) # if step1 and Division Dean if step == 'step1' and perms['level3']: proposal.level3 = True proposal.save() # send email to PI informing them that they are approved # to begin Part B send_mail( request, to_list, subject, proposal.user.email, 'proposal/email_authorized.html', proposal, BCC ) message = "Dean approved Part A" # if step2 and Division Dean elif step == 'step2' and perms['level3']: proposal.proposal_impact.level3 = True proposal.proposal_impact.save() message = "Division Dean approved Part B" # send email to Provost and VP for Business informing # them that the Division Dean has approved Part B # and the proposal is awaiting their approval. if proposal.ready_level1(): to_list = [VEEP.email, PROVOST.email] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] subject = u'Review and Provide Final Authorization for PART B: "{}" by {}, {}'.format( proposal.title, proposal.user.last_name, proposal.user.first_name ) send_mail( request, to_list, subject, PROPOSAL_EMAIL_LIST[0], 'impact/email_approve_level1.html', proposal, BCC ) # VP for Business? elif user.id == VEEP.id and step == 'step2': proposal.proposal_impact.level2 = True proposal.proposal_impact.save() message = "VP for Business approved Part B" # Provost? elif user.id == PROVOST.id and step == 'step2': proposal.proposal_impact.level1 = True proposal.proposal_impact.save() message = "Provost approved Part B" # approvers else: try: a = proposal.approvers.get(user=user) a.__dict__[step] = True a.save() # if approver replaces Division Dean set level3 to True if a.replace == 'level3': if step == 'step1': proposal.level3 = True proposal.save() else: proposal.proposal_impact.level3 = True proposal.proposal_impact.save() # if step 1 is complete send email notification if (proposal.step1() and step == 'step1'): send_mail( request, to_list, subject, proposal.user.email, 'proposal/email_authorized.html', proposal, BCC ) # if step 2 is complete and we are ready for # VP for Business and Provost to weight in, send email if proposal.ready_level1(): to_list = [VEEP.email, PROVOST.email] if DEBUG: proposal.to_list = to_list to_list = [MANAGER] subject = ( u'Review and Provide Final Authorization for PART B: ' '"{}" by {}, {}' ).format( proposal.title, proposal.user.last_name, proposal.user.first_name ) send_mail( request, to_list, subject, PROPOSAL_EMAIL_LIST[0], 'impact/email_approve_level1.html', proposal, BCC ) message = u"Approved by {} {}".format( a.user.first_name, a.user.last_name ) except: message = "You cannot change the status for this proposal" else: message = "Requires POST request" return HttpResponse(message)
def main(): """Barnes and Noble Upload.""" ########################################################################### # OpenSSH 7.0 and greater disable the ssh-dss (DSA) public key algorithm, # which B&N use for authentication on their servers, so you have to add # ssh-dss to the ssh/sftp command: # # -oHostKeyAlgorithms=+ssh-dss # # or add the following to the cron user's .ssh/config file: # # Host rex-sftp.bncollege.com # HostName rex-sftp.bncollege.com # HostKeyAlgorithms=+ssh-dss ########################################################################### cnopts = pysftp.CnOpts() cnopts.hostkeys = None xtrnl_connection = { 'host': settings.BARNESNOBLE_AIP_HOST, 'username': settings.BARNESNOBLE_AIP_USER, 'port': settings.BARNESNOBLE_AIP_PORT, 'private_key': settings.BARNESNOBLE_AIP_KEY, 'cnopts': cnopts, } phile = os.path.join(settings.BARNESNOBLE_AIP_DATA, 'test.csv') try: with pysftp.Connection(**xtrnl_connection) as sftp: sftp.cwd('inbox') if DEBUG: print('put phile') print(phile) sftp.put(phile) if DEBUG: for attr in sftp.listdir_attr(): print(attr.filename, attr) sftp.close() success = True except Exception as error: success = False body = """ Unable to PUT AIP file to Barnes and Noble server.\n\n{0} """.format(error) send_mail( None, TO, SUBJECT(status='failed'), FROM, 'email.html', body, ) if DEBUG: print(error) # sFTP upload complete send success message if success: body = '[Barnes and Noble] AIP files were successfully uploaded.' subject = SUBJECT(status='success') send_mail(None, TO, subject, FROM, 'email.html', body)
def main(): ''' main function ''' logger.error('skeletor is here') # Defines file names and directory location adirondackdata = ('{0}carthage_students.txt'.format( settings.ADIRONDACK_TXT_OUTPUT) ) try: # set global variable global EARL # determines which database is being called from the command line if database == 'cars': EARL = settings.INFORMIX_ODBC elif database == 'train': EARL = settings.INFORMIX_ODBC_TRAIN else: print("database must be: 'cars' or 'train'") exit(-1) # -------------------------- # Create the txt file # print(ADIRONDACK_QUERY) connection = get_connection(EARL) # connection closes when exiting the 'with' block with connection: data_result = xsql( ADIRONDACK_QUERY, connection, key=settings.INFORMIX_DEBUG ).fetchall() # print(data_result) ret = list(data_result) if ret is None: SUBJECT = "[Adirondack] Application failed" BODY = "SQL Query returned no data." send_mail ( None, [settings.ADIRONDACK_TO_EMAIL,], SUBJECT, settings.ADIRONDACK_FROM_EMAIL, 'email/default.html', BODY, [settings.ADMINS[0][1],] ) else: fn_write_student_bio_header() # print("Query successful") # print(ret) with open(adirondackdata, 'w') as file_out: csvWriter = csv.writer(file_out, delimiter='|') encoded_rows = fn_encode_rows_to_utf8(ret) for row in encoded_rows: # for row in ret: # print(row) csvWriter.writerow(row) file_out.close() # send file to SFTP Site.. sftp_upload(adirondackdata) if test: SUBJECT = "[Adirondack] Student Bio data success" BODY = "Retreieved data and sent it via SFTP to the eater of trees." send_mail( None, [settings.ADIRONDACK_TO_EMAIL,], SUBJECT, settings.ADIRONDACK_FROM_EMAIL, 'email/default.html', BODY, [settings.ADMINS[0][1],] ) print('done') logger.error(BODY) except Exception as e: # print(str(e)) logger.error("Error in adirondack student_bio.py, Error = " + repr(e)) SUBJECT = '[Adirondack] Application Error' BODY = "Error in adirondack student_bio.py, Error = " + repr(e) send_mail ( None, [settings.ADIRONDACK_TO_EMAIL,], SUBJECT, settings.ADIRONDACK_FROM_EMAIL, 'email/default.html', BODY, [settings.ADMINS[0][1],] )
def form_home(request): """Submit a PAF.""" user = request.user if request.method == 'POST': p = request.POST form = OperationForm(request.POST, label_suffix='') if form.is_valid(): paf = form.save(commit=False) # deal with level 3 approver level3 = User.objects.get(username=form.cleaned_data['approver']) paf.created_by = user paf.updated_by = user paf.level3_approver = level3 paf.save() # send email or display it for dev if not settings.DEBUG: # email distribution list and bcc parameters bcc = [settings.ADMINS[0][1], settings.HR_EMAIL] # send confirmation email to user who submitted the form to_list = [paf.created_by.email] template = 'transaction/email/created_by.html' # subject subject = "[PAF Submission] {0}, {1}".format( paf.created_by.last_name, paf.created_by.first_name, ) send_mail( request, to_list, subject, settings.HR_EMAIL, template, paf, bcc, ) # send email to level3 approver template = 'transaction/email/approver.html' to_list = [level3.email] send_mail( request, to_list, subject, paf.created_by.email, template, paf, bcc, ) return HttpResponseRedirect( reverse_lazy('transaction_form_success'), ) else: # display the email template template = 'transaction/email/approver.html' return render(request, template, {'paf': paf, 'form': form}) else: form = OperationForm(label_suffix='') hr = in_group(user, settings.HR_GROUP) return render(request, 'transaction/form.html', {'form': form, 'hr': hr})
def main(): """Barnes and Noble Upload.""" ########################################################################### # OpenSSH 7.0 and greater disable the ssh-dss (DSA) public key algorithm, # which B&N use for authentication on their servers, so you have to add # ssh-dss to the ssh/sftp command: # # -oHostKeyAlgorithms=+ssh-dss # # or add the following to the cron user's .ssh/config file: # # Host sftp.bncollege.com # HostName sftp.bncollege.com # HostKeyAlgorithms=+ssh-dss ########################################################################### datetimestr = time.strftime('%Y%m%d%H%M%S') sqldict = { 'AR100': 'stu_acad_rec_100', 'AR200': 'stu_acad_rec_200', 'EXENRCRS': 'exenrcrs', } ########################################################################### # Dict Value stu_acad_rec_100 selects active students and sets budget # limit for export (books = '100' & $3000.00) # # Dict Value stu_acad_rec_200 selects active students and sets budget # limit for export (supplies = '200' & $50.00) # # Dict Value 'EXENCRS' selects all current and future course-sections # (sec_rec) and instructor for Bookstore to order ISBN inventory ########################################################################### for name, incantation in sqldict.items(): phile = os.path.join( BASE_DIR, 'sql/barnesandnoble/{0}.sql'.format(incantation), ) with open(phile) as sql_file: sqldict[name] = sql_file.read() cnopts = pysftp.CnOpts() cnopts.hostkeys = None # sFTP connection information for Barnes and Noble 1 xtrnl_connection1 = { 'host': settings.BARNESNOBLE1_HOST, 'username': settings.BARNESNOBLE1_USER, 'password': settings.BARNESNOBLE1_PASS, 'port': settings.BARNESNOBLE1_PORT, 'cnopts': cnopts, } # sFTP connection information for Barnes and Noble 2 xtrnl_connection2 = { 'host': settings.BARNESNOBLE2_HOST, 'username': settings.BARNESNOBLE2_USER, 'password': settings.BARNESNOBLE2_PASS, 'port': settings.BARNESNOBLE2_PORT, 'cnopts': cnopts, } for key, sql in sqldict.items(): if DEBUG: print(key) # print(sql) with get_connection() as connection: rows = xsql(sql, connection, key=INFORMIX_DEBUG).fetchall() if rows: # set directory and filename to be stored filename = ( '{0}{1}.csv'.format(settings.BARNESNOBLE_CSV_OUTPUT, key) ) # set destination path and new filename to which it # will be renamed when archived archive_destination = ('{0}{1}_{2}_{3}.csv'.format( settings.BARNESNOBLE_CSV_ARCHIVED, 'CCBAK', key, datetimestr, )) # create .csv file with open(filename, 'w') as csvfile: output = csv.writer(csvfile) # write header row to file if DEBUG: # write header row for (AR100, AR200) if key in {'AR100', 'AR200'}: output.writerow([ 'StudentID', 'Elastname', 'Efirstname', 'Xmiddleinit', 'Xcred_limit', 'EProviderCode', 'Ebegdate', 'Eenddate', 'Eidtype', 'Erecordtype', 'Eaccttype', ]) else: # write header row for EXENCRS output.writerow([ 'bnUnitNo', 'bnTerm', 'bnYear', 'bnDept', 'bnCourseNo', 'bnSectionNo', 'bnProfName', 'bnMaxCapcty', 'bnEstEnrlmnt', 'bnActEnrlmnt', 'bnContdClss', 'bnEvngClss', 'bnExtnsnClss', 'bnTxtnetClss', 'bnLoctn', 'bnCourseTitl', 'bnCourseID', ]) for row in rows: output.writerow(row) else: # no rows print('No values in list') # renaming old filename to newfilename and move to archive location shutil.copy(filename, archive_destination) # end loop on rows # set local path {/data2/www/data/barnesandnoble/} source_dir = ('{0}'.format(settings.BARNESNOBLE_CSV_OUTPUT)) # set local path and filenames # variable == /data2/www/data/barnesandnoble/{filename.csv} file_ar100 = '{0}AR100.csv'.format(source_dir) file_ar200 = '{0}AR200.csv'.format(source_dir) file_exencrs = '{0}EXENRCRS.csv'.format(source_dir) # for final email status success = True # sFTP PUT moves the EXENCRS.csv file to the Barnes & Noble server 1 try: with pysftp.Connection(**xtrnl_connection1) as sftp: if DEBUG: print(file_exencrs) sftp.put(file_exencrs, preserve_mtime=True) # deletes original file from our server os.remove(file_exencrs) except Exception as error: success = False body = """ Unable to PUT EXENCRS.csv to Barnes and Noble server.\n\n{0} """.format(error) send_mail( None, TO, SUBJECT(status='failed'), FROM, 'email.html', body, ) if DEBUG: print(error) # sFTP PUT moves the AR100.csv file to the Barnes & Noble server 2 try: with pysftp.Connection(**xtrnl_connection2) as sftp_ar100: if DEBUG: sftp_ar100.chdir('TestFiles/') print(file_ar100) sftp_ar100.put(file_ar100, preserve_mtime=True) sftp_ar100.chdir('ToBNCB/') sftp_ar100.put(file_ar100, preserve_mtime=True) # deletes original file from our server os.remove(file_ar100) except Exception as error_ar100: success = False body = """ Unable to PUT AR100.csv to Barnes and Noble server.\n\n{0} """.format(error_ar100) send_mail( None, TO, SUBJECT(status='failed'), FROM, 'email.html', body, ) if DEBUG: print(error_ar100) # sFTP PUT moves the AR200.csv file to the Barnes & Noble server 2 try: with pysftp.Connection(**xtrnl_connection2) as sftp_ar200: sftp_ar200.put(file_ar200, preserve_mtime=True) sftp_ar200.chdir('ToBNCB/') sftp_ar200.put(file_ar200, preserve_mtime=True) # deletes original file from our server os.remove(file_ar200) except Exception as error_ar200: success = False body = """ Unable to PUT AR200.csv to Barnes and Noble server.\n\n{0} """.format(error_ar200) send_mail( None, TO, SUBJECT(status='failed'), FROM, 'email.html', body, ) if DEBUG: print(error_ar200) # sFTP upload complete send success message if success: body = 'The Barnes and Noble files were successfully uploaded.' subject = SUBJECT(status='success') send_mail(None, TO, subject, FROM, 'email.html', body)
def operation_status(request): """ scope: set the status on a operation options: approve, decline method: AJAX POST """ # requires POST request if request.POST: user = request.user oid = request.POST.get('oid') app = request.POST.get('app') model = apps.get_model(app_label=app, model_name='Operation') status = request.POST.get('status') obj = get_object_or_404(model, id=oid) perms = obj.permissions(user) if not obj.declined: # we verify that the user has permission to approve/decline # in the permissions method if perms['approver'] and status in ['approved','declined']: from djtools.fields import NOW if status == 'approved': for level in perms['level']: setattr(obj, level, True) setattr(obj, '{}_date'.format(level), NOW) if status == 'declined': obj.declined = True obj.save() # we will always use the first level in the list unless: # 1. VPFA is a level3 approver; or # 2. provost is a level3 approver and PAF from faculty # 3. HR is a level3 approver and no budget impact try: level = perms['level'][1] except: level = perms['level'][0] template = '{}/email/{}_{}.html'.format(app, level, status) # we send an email to Level2 if money is involved # and then to HR for final decision. if no money, we send an # email to Provost if need be and then to HR for final approval. # # VPFA will be notified only if the submission does not impact # the budget and she is not the level3 approver. # at the moment, the VPFA is not a LEVEL3 approver # so that last AND clause in elif will never be True but LEVEL2 # might become a LEVEL3 approver in the future if app != 'requisition' and obj.notify_provost() and not obj.provost: to_approver = [PROVOST.email] elif obj.notify_level2() and not obj.level2 and obj.level3_approver.id != LEVEL2.id: to_approver = [LEVEL2.email] else: to_approver = settings.ACCOUNTING_EMAIL to_approver.append(settings.HR_EMAIL) bcc = [settings.ADMINS[0][1]] frum = user.email to_creator = [obj.created_by.email] subject = "[Personnel {0} Form] {1}".format( app.capitalize(), status, ) if settings.DEBUG: obj.to_creator = to_creator to_creator = [settings.MANAGERS[0][1]] obj.to_approver = to_approver to_approver = [settings.MANAGERS[0][1]] # notify the creator of current status send_mail( request, to_creator, subject, frum, template, obj, bcc, ) # notify the next approver if it is not completely approved # and the submission has not been declined if not obj.approved() and status == 'approved': send_mail( request, to_approver, subject, frum, '{}/email/approver.html'.format(app), obj, bcc ) message = "Personnel {} has been {}".format(app, status) else: message = "Access Denied" else: message = "Personnel {} has already been declined".format(app) else: message = "Requires HTTP POST" return HttpResponse(message)
def main(): """Barnes and Noble Upload.""" ########################################################################### # OpenSSH 7.0 and greater disable the ssh-dss (DSA) public key algorithm, # which B&N use for authentication on their servers, so you have to add # ssh-dss to the ssh/sftp command: # # -oHostKeyAlgorithms=+ssh-dss # # or add the following to the cron user's .ssh/config file: # # Host rex-sftp.bncollege.com # HostName rex-sftp.bncollege.com # HostKeyAlgorithms=+ssh-dss ########################################################################### # Defines file names and directory location # bn_course_fil = ('{0}carthage_students.txt'.format( # settings.ADIRONDACK_TXT_OUTPUT) # ) # bn_course_file = settings.BARNES_N_NOBLE_CSV_OUTPUT + "courses.csv" # bn_enr_fil = settings.BARNES_N_NOBLE_CSV_OUTPUT + "enrollments.csv" # bn_usr_fil = settings.BARNES_N_NOBLE_CSV_OUTPUT + "users.csv" # bn_zip_fil = settings.BARNES_N_NOBLE_CSV_OUTPUT + "carthage_bn" """To get the last query date from cache""" last_sql_date = cache.get('BN_Sql_date') # print(last_sql_date) bn_course_file = "courses.csv" bn_enr_fil = "enrollments.csv" bn_usr_fil = "users.csv" bn_zip_fil = "carthage_bncroster.zip" # /data2/www/data/barnesandnoble/enrollments/carthage_bncroster.zip"" # print(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil) if path.exists(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil): os.remove(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil) """Create the headers for the three files""" fil = open(bn_course_file, 'w') fil.write("recordNumber,campus,school,institutionDepartment,term," "department,course,section,campusTitle,schoolTitle," "institutionDepartmentTitle,courseTitle," "institutionCourseCode,institutionClassCode," "institutionSubjectCodes,institutionSubjectsTitle," "crn,termTitle,termType,termStartDate,termEndDate," "sectionStartDate,sectionEndDate,classGroupId," "estimatedEnrollment" + "\n") fil.close() fil1 = open(bn_enr_fil, 'w') fil1.write("recordNumber,campus,school,institutionDepartment,term," "department,course,section,email,firstName,middleName," "lastName,userRole,sisUserId,includedInCourseFee," "studentFullPartTimeStatus,creditHours" + "\n") fil1.close() fil2 = open(bn_usr_fil, 'w') fil2.write("recordNumber,campus,school,email,firstName,middleName," "lastName,userRole,sisUserId" + "\n") fil2.close() try: # set global variable # global EARL # # determines which database is being called from the command line # if database == 'cars': EARL = settings.INFORMIX_ODBC # elif database == 'train': # EARL = settings.INFORMIX_ODBC_TRAIN # else: # print("database must be: 'cars' or 'train'") # exit(-1) crs_qry = COURSES connection = get_connection(EARL) # connection closes when exiting the 'with' block blank = "" with connection: data_result = xsql( crs_qry, connection, key=settings.INFORMIX_DEBUG ).fetchall() ret = list(data_result) if ret is None: # print("No result") SUBJECT = "[Barnes and Noble Crs Enr] Application failed" BODY = "Course Query returned no data." send_mail( None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT, settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, ) else: # print(ret)cd cnt = 1 # print("Open file 1") fil = open(bn_course_file, 'a') for row in ret: # fil.write(row) campus = '"' + row[0] + '"' # school = '"' + row[1] + '"' school = '"' + blank + '"' institutionDepartment = row[2] term = '"' + row[3] + '"' department = '"' + row[4] + '"' course = '"' + row[5] + '"' SectionCode = '"' + row[6] + '"' campusTitle = '"' + row[7] + '"' # schoolTitle = '"' + row[8] + '"' schoolTitle = '"' + blank + '"' institutionDepartmentTitle = '"' + row[9] + '"' courseTitle = '"' + row[10].strip() + '"' institutionCourseCode = '"' + row[11] + '"' institutionClassCode = '"' + row[12] + '"' institutionSubjectCodes = '"' + row[13] + '"' institutionSubjectsTitle = '"' + row[14].strip() + '"' crn = '"' + row[15] + '"' termTitle = '"' + row[16] + '"' termType = '"' + row[17] + '"' termStartDate = '"' + fn_format_date(row[18]) + '"' termEndDate = '"' + fn_format_date(row[19]) + '"' sectionStartDate = '"' + fn_format_date(row[20]) + '"' sectionEndDate = '"' + fn_format_date(row[21]) + '"' classGroupId = '"' + row[22] + '"' estimatedEnrollment = str(row[23]) lin = str(cnt) + "," + campus + "," + school + "," + \ institutionDepartment + "," + term + "," + \ department + "," + course + "," + SectionCode + "," + \ campusTitle + "," + schoolTitle + "," + \ institutionDepartmentTitle + "," + courseTitle \ + "," + institutionCourseCode + "," + \ institutionClassCode + "," + institutionSubjectCodes \ + "," + institutionSubjectsTitle + "," + crn + "," + \ termTitle + "," + termType + "," + termStartDate \ + "," + termEndDate + "," + sectionStartDate + "," + \ sectionEndDate + "," + classGroupId + "," + \ estimatedEnrollment + "\n" fil.write(lin) cnt = cnt + 1 fil.close() # print("Close file 1") connection = get_connection(EARL) # connection closes when exiting the 'with' block with connection: data_result = xsql( USERS, connection, key=settings.INFORMIX_DEBUG ).fetchall() ret = list(data_result) if ret is None: # print("No result") SUBJECT = "[Barnes and Noble Crs Enr] Application failed" BODY = "User Query returned no data." send_mail( None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT, settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, ) else: # print(ret) cnt = 1 # print("Open file 2") fil2 = open(bn_usr_fil, 'a') for row in ret: # print(row) campus = '"' + row[0] + '"' school = '"' + blank + '"' email = '"' + row[2] + '"' firstname = '"' + row[3] + '"' middlename = '"' + row[4] + '"' lastname = '"' + row[5] + '"' role = '"' + row[6].strip() + '"' username = '******' + str(row[8]) + '"' lin = str(cnt) + "," + campus + "," + school + "," + \ email + "," + firstname + "," + \ middlename + "," + lastname + "," + role + "," + \ username + "\n" # print(lin) fil2.write(lin) cnt = cnt + 1 fil2.close() # print("Close file 2") """Connect to Database""" connection = get_connection(EARL) # connection closes when exiting the 'with' block with connection: data_result = xsql( ENROLLMENTS, connection, key=settings.INFORMIX_DEBUG ).fetchall() ret = list(data_result) if ret is None: # print("No result") SUBJECT = "[Barnes and Noble Crs Enr] Application failed" BODY = "ENROLLMENTS Query returned no data." send_mail( None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT, settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, ) else: # print(ret) cnt = 1 # print("Open file 3") fil3 = open(bn_enr_fil, 'a') for row in ret: # print(row) campus = '"' + row[0] + '"' school = '"' + blank + '"' inst_dept = '"' + row[2] + '"' term = '"' + row[3] + '"' dept = '"' + row[4] + '"' course = '"' + row[5] + '"' section = '"' + row[6].strip() + '"' email = '"' + row[7] + '"' firstname = '"' + row[8] + '"' middlename = '"' + row[9] + '"' lastname = '"' + row[10] + '"' role = '"' + row[11] + '"' userid = '"' + str(row[12]) + '"' includeinfee = '"' + row[13] + '"' fulltimestatus = '"' + row[14] + '"' credit_hours = '"' + str(row[15]) + '"' lin = str(cnt) + "," + campus + "," + school + "," + \ inst_dept + "," + term + "," + \ dept + "," + course + "," + \ section + "," + email + "," + \ firstname + "," + middlename + "," + \ lastname + "," + role + "," + userid + "," + \ includeinfee + "," + fulltimestatus + "," + \ credit_hours + "\n" # print(lin) fil3.write(lin) cnt = cnt + 1 fil3.close() # print("Close file 1") """Create Archive""" zf = zipfile.ZipFile(bn_zip_fil, mode='w') zf.write(bn_course_file) zf.write(bn_usr_fil) zf.write(bn_enr_fil) """Move Zip File""" shutil.move(bn_zip_fil, settings.BARNES_N_NOBLE_CSV_OUTPUT) """Send the file...""" cnopts = pysftp.CnOpts() cnopts.hostkeys = None xtrnl_connection = { 'host': settings.BARNESNOBLE_AIP_HOST, 'username': settings.BARNESNOBLE_AIP_USER, 'port': settings.BARNESNOBLE_AIP_PORT, 'private_key': settings.BARNESNOBLE_AIP_KEY, 'cnopts': cnopts, } try: with pysftp.Connection(**xtrnl_connection) as sftp: sftp.cwd('inbox') # print("Connected") remotepath = sftp.listdir() # print(remotepath) # phile = os.path.join(settings.BARNES_N_NOBLE_CSV_OUTPUT + bn_zip_fil) # print("Put " + phile) sftp.put(phile) sftp.close() # print("Remove temp csv files") os.remove(bn_usr_fil) os.remove(bn_course_file) os.remove(bn_enr_fil) except Exception as error: # print("Unable to PUT settings.BARNES_N_NOBLE_CSV_OUTPUT + " # "bn_zip_fil to Barnes and Noble " # "server.\n\n{0}".format(error)) SUBJECT = "[Barnes and Noble Crs Enr] Application failed" BODY = "Unable to PUT settings.BARNES_N_NOBLE_CSV_OUTPUT " \ + bn_zip_fil \ + " to Barnes and Noble server.\n\n{0}".format(error) send_mail(None, TO, SUBJECT(status='failed'), FROM, 'email.html', body, ) send_mail( None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT, settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, ) #To set a new date in cache a = datetime.now() last_sql_date = a.strftime('%Y-%m-%d %H:%M:%S') cache.set('BN_Sql_date', last_sql_date) except Exception as e: print("Error in main: " + str(e)) SUBJECT = "[Barnes and Noble Crs Enr] Application failed" BODY = "Error" send_mail( None, settings.BARNES_N_NOBLE_TO_EMAIL, SUBJECT, settings.BARNES_N_NOBLE_FROM_EMAIL, 'email.html', BODY, )
def form_home(request, rid=None): user = request.user obj = None if rid: obj = get_object_or_404(Operation, pk=rid) # only HR folks can update PRF at the moment if not in_group(user, settings.HR_GROUP): return HttpResponseRedirect(reverse_lazy('access_denied')) if request.method == 'POST': form = OperationForm( data=request.POST, instance=obj, files=request.FILES, label_suffix='', use_required_attribute=False, ) if form.is_valid(): data = form.save(commit=False) data.created_by = user data.updated_by = user data.save() # send email to creator and approver or display it for dev, # and do not send it if we are updating the object template = 'requisition/email/approver.html' if not settings.DEBUG and not obj: # send confirmation email to user who submitted the form to_list = [data.created_by.email] bcc = [settings.ADMINS[0][1], settings.HR_EMAIL] # subject subject = "[PRF Submission] {0}, {1}".format( data.created_by.last_name, data.created_by.first_name, ) template = 'requisition/email/created_by.html' send_mail( request, to_list, subject, settings.HR_EMAIL, template, data, bcc, ) # send email to level3 approver and Provost, if need be # (the latter of whom just needs notification and # does not approve anything template = 'requisition/email/approver.html' to_list = [data.level3_approver.email] if data.notify_provost(): to_list.append(PROVOST.email) send_mail( request, to_list, subject, data.created_by.email, template, data, bcc, ) return HttpResponseRedirect( reverse_lazy('requisition_form_success'), ) else: # display the email template return render( request, template, { 'data': data, 'form': form }, ) else: form = OperationForm( instance=obj, label_suffix='', use_required_attribute=False, ) hr = in_group(user, settings.HR_GROUP) return render(request, 'requisition/form.html', {'hr': hr, 'form': form})