def download_attachment(request, ticket_id, attachment, ticket): """ Downloads ticket attachment :type ticket_id:String :type attachment: String :type ticket: Ticket (from @has_access_to_ticket) :param ticket_id: ticket code :param attachment: attachment name :param ticket: ticket object (from @has_access_to_ticket) :return: file """ # get ticket json dictionary json_dict = ticket.get_modulo_compilato() ticket_details = get_as_dict(compiled_module_json=json_dict) if attachment: # get ticket attachments attachments = ticket_details[settings.ATTACHMENTS_DICT_PREFIX] # get the attachment documento = attachments[attachment] # get ticket folder path path_allegato = get_path(ticket.get_folder()) # get file result = download_file(path_allegato, documento) return result raise Http404
def delete_my_attachment(request, ticket_id, attachment): """ Delete ticket attachment while it is unassigned Note: it must be called by a dialogbox with user confirmation :type ticket_id: String :type attachment: String :param ticket_id: ticket code :param attachment: attachment name :return: redirect """ ticket = get_object_or_404(Ticket, code=ticket_id) json_dict = json.loads(ticket.modulo_compilato) ticket_details = get_as_dict(compiled_module_json=json_dict) nome_file = ticket_details["allegati"]["{}".format(attachment)] # Rimuove il riferimento all'allegato dalla base dati del ticket_details["allegati"]["{}".format(attachment)] path_allegato = get_path_allegato(ticket) # Rimuove l'allegato dal disco elimina_file(file_name=nome_file, path=path_allegato) set_as_dict(ticket, ticket_details) allegati = ticket.get_allegati_dict(ticket_dict=ticket_details) ticket.update_history(user=request.user, note=_("Elimina allegato")) messages.add_message(request, messages.SUCCESS, _("Allegato eliminato correttamente")) return redirect('uni_ticket:ticket_edit', ticket_id=ticket_id)
def vedi_modulo_inserito(request, bando_id, modulo_domanda_bando_id): """ usato in admin per avere una anteprima dei campi scelti """ modulo_domanda_bando = get_object_or_404(ModuloDomandaBando, pk=modulo_domanda_bando_id) bando = _get_bando_queryset(bando_id).first() descrizione_indicatore = modulo_domanda_bando.descrizione_indicatore json_dict = json.loads(modulo_domanda_bando.modulo_compilato) data = get_as_dict(json_dict, allegati=False) allegati = get_allegati_dict(modulo_domanda_bando) form = SavedFormContent.compiled_form_readonly( modulo_domanda_bando.compiled_form(remove_filefields=allegati)) # form con i soli campi File da dare in pasto al tag della firma digitale form_allegati = descrizione_indicatore.get_form(remove_datafields=True) d = { 'allegati': allegati, 'form': form, 'form_allegati': form_allegati, 'bando': bando, 'descrizione_indicatore': descrizione_indicatore, 'modulo_domanda_bando': modulo_domanda_bando, 'readonly': True } return render(request, 'modulo_form_readonly_user.html', d)
def aggiungi_titolo_form(request, bando, descrizione_indicatore, domanda_bando, dipendente, return_url, log=False): form = descrizione_indicatore.get_form(data=request.POST, files=request.FILES, domanda_bando=domanda_bando) if form.is_valid(): # qui chiedere conferma prima del salvataggio json_data = get_POST_as_json(request) mdb_model = apps.get_model(app_label='domande_peo', model_name='ModuloDomandaBando') mdb = mdb_model.objects.create( domanda_bando = domanda_bando, modulo_compilato = json_data, descrizione_indicatore = descrizione_indicatore, modified=timezone.localtime(), ) # salvataggio degli allegati nella cartella relativa # Ogni file viene rinominato con l'ID del ModuloDomandaBando # appena creato e lo "slug" del campo FileField # json_stored = mdb.get_as_dict() json_dict = json.loads(mdb.modulo_compilato) json_stored = get_as_dict(json_dict) if request.FILES: json_stored["allegati"] = {} path_allegati = get_path_allegato(dipendente.matricola, bando.slug, mdb.pk) for key, value in request.FILES.items(): salva_file(request.FILES[key], path_allegati, request.FILES[key]._name) json_stored["allegati"]["{}".format(key)] = "{}".format(request.FILES[key]._name) set_as_dict(mdb, json_stored) # mdb.set_as_dict(json_stored) domanda_bando.mark_as_modified() msg = 'Inserimento {} - Etichetta: {} - effettuato con successo!'.format(mdb, request.POST.get(ETICHETTA_INSERIMENTI_ID)) #Allega il messaggio al redirect messages.success(request, msg) if log: LogEntry.objects.log_action(user_id = request.user.pk, content_type_id = ContentType.objects.get_for_model(domanda_bando).pk, object_id = domanda_bando.pk, object_repr = domanda_bando.__str__(), action_flag = CHANGE, change_message = msg) # url = reverse('gestione_peo:commissione_domanda_manage', args=[commissione.pk, domanda_bando.pk,]) return HttpResponseRedirect(return_url) else: dictionary = {} # il form non è valido, ripetere inserimento dictionary['form'] = form return dictionary
def contain_sub_descr_ind(self): """ True se il modulo compilato contiene un SubDescrizioneIndicatore """ json_dict = json.loads(self.modulo_compilato) dati_inseriti = get_as_dict(json_dict) if "sub_descrizione_indicatore" in dati_inseriti: return dati_inseriti.get("sub_descrizione_indicatore")
def get_allegati_dict(self, ticket_dict={}): allegati_dict = {} if ticket_dict: allegati_dict = ticket_dict.get('allegati') else: json_dict = json.loads(self.modulo_compilato) allegati_dict = get_as_dict(compiled_module_json=json_dict).get('allegati') return allegati_dict
def get_allegati_dict(self, ticket_dict={}): allegati_dict = {} if ticket_dict: allegati_dict = ticket_dict.get(settings.ATTACHMENTS_DICT_PREFIX) else: # json_dict = json.loads(self.get_modulo_compilato()) json_dict = self.get_modulo_compilato() allegati_dict = get_as_dict(compiled_module_json=json_dict).get( settings.ATTACHMENTS_DICT_PREFIX) return allegati_dict or {}
def ticket_detail(request, ticket_id, template='user/ticket_detail.html'): """ Shows ticket details :type ticket_id: String :type template: String :param ticket_id: ticket code :param attachment: template to user (can change if specified) :return: render """ ticket = get_object_or_404(Ticket, code=ticket_id) modulo_compilato = ticket.get_modulo_compilato() ticket_details = get_as_dict(compiled_module_json=modulo_compilato, allegati=False, formset_management=False) allegati = ticket.get_allegati_dict() path_allegati = get_path(ticket.get_folder()) ticket_form = ticket.input_module.get_form(files=allegati, remove_filefields=False) priority = ticket.get_priority() ticket_logs = LogEntry.objects.filter( content_type_id=ContentType.objects.get_for_model(ticket).pk, object_id=ticket.pk) ticket_replies = TicketReply.objects.filter(ticket=ticket) ticket_task = Task.objects.filter(ticket=ticket) ticket_dependences = ticket.get_dependences() title = ticket.subject sub_title = ticket.code assigned_to = [] ticket_assignments = TicketAssignment.objects.filter(ticket=ticket) category_conditions = ticket.input_module.ticket_category.get_conditions( is_printable=True) d = { 'allegati': allegati, 'category_conditions': category_conditions, 'dependences': ticket_dependences, 'details': ticket_details, 'path_allegati': path_allegati, 'priority': priority, 'sub_title': sub_title, 'ticket': ticket, 'ticket_assignments': ticket_assignments, 'ticket_form': ticket_form, 'logs': ticket_logs, 'ticket_task': ticket_task, 'title': title, } template = template return render(request, template, d)
def is_valid(self): """ """ json_dict = json.loads(self.modulo_compilato) ticket_dict = get_as_dict(json_dict) if not "allegati" in ticket_dict: return True allegati = ticket_dict.get('allegati') # valido solo i campi File vuoti del form # evito di validare tutti gli altri campi, sicuramente corretti form = self.compiled_form(files=None, remove_filefields=allegati, remove_datafields=True) if form.is_valid(): return True return False
def is_valid(self): """ """ json_dict = self.get_modulo_compilato() ticket_dict = get_as_dict(json_dict) if not settings.ATTACHMENTS_DICT_PREFIX in ticket_dict: return True allegati = ticket_dict.get(settings.ATTACHMENTS_DICT_PREFIX) # valido solo i campi File vuoti del form # evito di validare tutti gli altri campi, sicuramente corretti form = self.compiled_form(files=None, remove_filefields=allegati, remove_datafields=True) if form.is_valid(): return True return False
def punteggio_titolo_studio(self): """ Calcolo del punteggio attribuito al titolo di studio """ if self.descrizione_indicatore.calcolo_punteggio_automatico: json_dict = json.loads(self.modulo_compilato) dati_inseriti = get_as_dict(json_dict) if "titolo_di_studio_superiore" in dati_inseriti: titolo_studio = Punteggio_TitoloStudio.objects.get( pk=dati_inseriti.get("titolo_di_studio_superiore")) result = [ titolo_studio.titolo, titolo_studio.punteggio, titolo_studio.cumulabile ] return result
def migrate_fieldname(self, old, new, save=True, strict=False): """ change fieldname for migration purpose """ # d = self.get_as_dict() json_dict = json.loads(self.modulo_compilato) d = get_as_dict(json_dict) if not d.get(old): if strict: raise Exception('{} does not exist'.format(old)) return d[new] = ''.join(d[old]) del d[old] if save: set_as_dict(self, d) # self.set_as_dict(d) return d
def download_allegato_from_mdb(bando, mdb, dipendente, allegato): # json_stored = mdb.get_as_dict() json_dict = json.loads(mdb.modulo_compilato) json_stored = get_as_dict(json_dict) nome_file = json_stored["allegati"]["{}".format(allegato)] path_allegato = get_path_allegato(dipendente.matricola, bando.slug, mdb.pk) result = download_file(path_allegato, nome_file) if result is None: raise Http404 return result
def ticket_detail(request, ticket_id, template='user/ticket_detail.html'): """ Shows ticket details :type ticket_id: String :type template: String :param ticket_id: ticket code :param attachment: template to user (can change if specified) :return: render """ ticket = get_object_or_404(Ticket, code=ticket_id) json_dict = json.loads(ticket.modulo_compilato) ticket_details = get_as_dict(compiled_module_json=json_dict, allegati=False, formset_management=False) allegati = ticket.get_allegati_dict() path_allegati = get_path_allegato(ticket) ticket_form = ticket.input_module.get_form(files=allegati, remove_filefields=False) priority = ticket.get_priority() ticket_history = TicketHistory.objects.filter(ticket=ticket) ticket_replies = TicketReply.objects.filter(ticket=ticket) ticket_task = Task.objects.filter(ticket=ticket) ticket_dependences = ticket.get_dependences() title = _("Dettaglio ticket") sub_title = ticket assigned_to = [] ticket_assignments = TicketAssignment.objects.filter(ticket=ticket) d={'allegati': allegati, 'dependences': ticket_dependences, 'details': ticket_details, 'path_allegati': path_allegati, 'priority': priority, 'sub_title': sub_title, 'ticket': ticket, 'ticket_assignments': ticket_assignments, 'ticket_form': ticket_form, 'ticket_history': ticket_history, 'ticket_task': ticket_task, 'title': title,} template = template return render(request, template, d)
def get_modulo_anteprima(self, obj): json_dict = json.loads(obj.modulo_compilato) data = get_as_dict(json_dict, allegati=False) allegati = get_allegati(obj) form = SavedFormContent.compiled_form_readonly(obj.compiled_form()) table_tmpl = '<table margin-left: 15px;">{}</table>' allegati_html = '' for k, v in allegati: allegato_url = reverse( 'domande_peo:download_allegato', args=[obj.domanda_bando.bando.pk, obj.pk, k]) allegati_html += '<tr><td>{}</td><td><a href="{}">{}</a><td></tr>'.format( k, allegato_url, v) value = form.as_table() v = table_tmpl.format(value) return mark_safe(v + table_tmpl.format(allegati_html))
def delete_my_attachment(request, ticket_id, attachment): """ Delete ticket attachment while it is unassigned Note: it must be called by a dialogbox with user confirmation :type ticket_id: String :type attachment: String :param ticket_id: ticket code :param attachment: attachment name :return: redirect """ ticket = get_object_or_404(Ticket, code=ticket_id) json_dict = ticket.get_modulo_compilato() ticket_details = get_as_dict(compiled_module_json=json_dict) nome_file = ticket_details[settings.ATTACHMENTS_DICT_PREFIX][attachment] # Rimuove il riferimento all'allegato dalla base dati del ticket_details[settings.ATTACHMENTS_DICT_PREFIX][attachment] path_allegato = get_path(ticket.get_folder()) # Rimuove l'allegato dal disco delete_file(file_name=nome_file, path=path_allegato) # log action logger.info('[{}] user {} deleted file {}'.format(timezone.now(), request.user.username, path_allegato)) set_as_dict(ticket, ticket_details) allegati = ticket.get_allegati_dict(ticket_dict=ticket_details) ticket.update_log(user=request.user, note=_("Elimina allegato")) # log action logger.info('[{}] user {} deleted attachment ' '{} for ticket {}'.format(timezone.now(), request.user.username, nome_file, ticket)) messages.add_message(request, messages.SUCCESS, _("Allegato eliminato correttamente")) return redirect('uni_ticket:ticket_edit', ticket_id=ticket_id)
def ticket_delete(request, ticket_id): """ Delete ticket while it is unassigned Note: it must be called by a dialogbox with user confirmation :type ticket_id: String :param ticket_id: ticket code :return: redirect """ ticket = get_object_or_404(Ticket, code=ticket_id) code = ticket.code json_dict = json.loads(ticket.modulo_compilato) ticket_details = get_as_dict(compiled_module_json=json_dict) if "allegati" in ticket_details: elimina_directory(ticket_id) ticket_assignment = TicketAssignment.objects.filter(ticket=ticket).first() ticket_assignment.delete() ticket_history = TicketHistory.objects.filter(ticket=ticket) for event in ticket_history: event.delete() # Send mail to ticket owner mail_params = {'hostname': settings.HOSTNAME, 'user': request.user, 'status': _('deleted'), 'ticket': ticket } m_subject = _('{} - ticket {} deleted'.format(settings.HOSTNAME, ticket)) send_custom_mail(subject=m_subject, body=NEW_TICKET_UPDATE.format(**mail_params), recipient=request.user) # END Send mail to ticket owner ticket.delete() messages.add_message(request, messages.SUCCESS, _("Ticket {} eliminato correttamente".format(code))) return redirect('uni_ticket:user_unassigned_ticket')
def elimina_allegato_from_mdb(request, bando, dipendente, mdb, allegato, return_url, log=False): # json_stored = mdb.get_as_dict() json_dict = json.loads(mdb.modulo_compilato) json_stored = get_as_dict(json_dict) nome_file = json_stored["allegati"]["{}".format(allegato)] # Rimuove il riferimento all'allegato dalla base dati del json_stored["allegati"]["{}".format(allegato)] # mdb.set_as_dict(json_stored) set_as_dict(mdb, json_stored) mdb.mark_as_modified() mdb.domanda_bando.mark_as_modified() path_allegato = get_path_allegato(dipendente.matricola, bando.slug, mdb.pk) # Rimuove l'allegato dal disco elimina_file(path_allegato, nome_file) etichetta = mdb.get_identificativo_veloce() msg = 'Allegato {} eliminato con successo da {} - Etichetta: {}'.format(nome_file, mdb, etichetta) if log: LogEntry.objects.log_action(user_id = request.user.pk, content_type_id = ContentType.objects.get_for_model(mdb.domanda_bando).pk, object_id = mdb.domanda_bando.pk, object_repr = mdb.domanda_bando.__str__(), action_flag = CHANGE, change_message = msg) return HttpResponseRedirect(return_url)
def ticket_add_new(request, structure_slug, category_slug): """ Create the ticket :type structure_slug: String :type category_slug: String :param structure_slug: slug of structure :param category_slug: slug of category :return: render """ struttura = get_object_or_404(OrganizationalStructure, slug=structure_slug, is_active=True) category = get_object_or_404(TicketCategory, slug=category_slug) if not category.is_active: return custom_message(request, category.not_available_message, status=404) # if anonymous user and category only for logged users if not category.allow_anonymous and not request.user.is_authenticated: return redirect('{}?next={}'.format(settings.LOGIN_URL, request.path)) # is user is authenticated if request.user.is_authenticated: # check ticket number limit if Ticket.number_limit_reached_by_user(request.user): messages.add_message( request, messages.ERROR, _("Hai raggiunto il limite massimo giornaliero" " di ticket: <b>{}</b>" "".format(settings.MAX_DAILY_TICKET_PER_USER))) return redirect('uni_ticket:user_dashboard') # check if user is allowed to access this category if not category.allowed_to_user(request.user): return custom_message( request, _("Permesso negato a questa tipologia di utente.")) title = category template = 'user/ticket_add_new.html' sub_title = category.description if category.description else _( "Compila i campi richiesti") modulo = get_object_or_404(TicketCategoryModule, ticket_category=category, is_active=True) form = modulo.get_form(show_conditions=True, current_user=request.user) clausole_categoria = category.get_conditions() d = { 'categoria': category, 'category_conditions': clausole_categoria, 'form': form, 'struttura': struttura, 'sub_title': '{} - {}'.format(struttura, sub_title), 'title': title } # after form submit if request.POST: form = modulo.get_form(data=request.POST, files=request.FILES, show_conditions=True, current_user=request.user) d['form'] = form if form.is_valid(): fields_to_pop = [ settings.TICKET_CONDITIONS_FIELD_ID, settings.TICKET_SUBJECT_ID, settings.TICKET_DESCRIPTION_ID, settings.TICKET_CAPTCHA_ID, settings.TICKET_CAPTCHA_HIDDEN_ID ] json_data = get_POST_as_json(request=request, fields_to_pop=fields_to_pop) # make a UUID based on the host ID and current time code = uuid_code() subject = form.cleaned_data[settings.TICKET_SUBJECT_ID] description = form.cleaned_data[settings.TICKET_DESCRIPTION_ID] # destination office office = category.organizational_office # take a random operator (or manager) # only if category is_notify or user is anonymous random_office_operator = None if category.is_notify or not request.user.is_authenticated: # get random operator from the office random_office_operator = OrganizationalStructureOfficeEmployee.get_default_operator_or_manager( office) # set users (for current operation and for log) current_user = request.user if request.user.is_authenticated else random_office_operator log_user = request.user.username if request.user.is_authenticated else 'anonymous' # create ticket ticket = Ticket(code=code, subject=subject, description=description, modulo_compilato=json_data, created_by=current_user, input_module=modulo) ticket.save() # log action logger.info('[{}] user {} created new ticket {}' ' in category {}'.format(timezone.now(), log_user, ticket, category)) # salvataggio degli allegati nella cartella relativa json_dict = json.loads(json_data) json_stored = get_as_dict(compiled_module_json=json_dict) _save_new_ticket_attachments(ticket=ticket, json_stored=json_stored, form=form, request_files=request.FILES) ticket_assignment = TicketAssignment(ticket=ticket, office=office) ticket_assignment.save() # if it's a notification ticket, take and close the ticket if category.is_notify: _close_notification_ticket(ticket=ticket, user=current_user, operator=random_office_operator, ticket_assignment=ticket_assignment) # log action logger.info('[{}] ticket {} assigned to ' '{} office'.format(timezone.now(), ticket, office)) # category default tasks _assign_default_tasks_to_new_ticket(ticket=ticket, category=category, log_user=log_user) ticket_message = ticket.input_module.ticket_category.confirm_message_text or \ settings.NEW_TICKET_CREATED_ALERT compiled_message = ticket_message.format(ticket.subject) messages.add_message(request, messages.SUCCESS, compiled_message) # if office operators must receive notification email if category.receive_email: # Send mail to ticket owner _send_new_ticket_mail_to_operators(request=request, ticket=ticket, category=category) # if user is authenticated send mail and redirect to ticket page if request.user.is_authenticated: # Send mail to ticket owner mail_params = { 'hostname': settings.HOSTNAME, 'user': request.user, 'ticket': ticket.code, 'ticket_subject': subject, 'url': request.build_absolute_uri( reverse('uni_ticket:ticket_detail', kwargs={'ticket_id': ticket.code})), 'added_text': compiled_message } m_subject = _('{} - {}'.format(settings.HOSTNAME, compiled_message)) m_subject = m_subject[:80] + (m_subject[80:] and '...') send_custom_mail(subject=m_subject, recipient=request.user, body=settings.NEW_TICKET_CREATED, params=mail_params) # END Send mail to ticket owner return redirect('uni_ticket:ticket_detail', ticket_id=ticket.code) else: return redirect('uni_ticket:add_new_ticket', structure_slug=structure_slug, category_slug=category_slug) else: for k, v in get_labeled_errors(form).items(): messages.add_message(request, messages.ERROR, "<b>{}</b>: {}".format(k, strip_tags(v))) return render(request, template, d)
bando = Bando.objects.get(slug='peo-2018') field_name = 'titolo_di_studio_superiore' lista_errati = [] salva = False for dom in DomandaBando.objects.filter(bando=bando): dipendente = dom.dipendente # pos_eco = dipendente.livello.posizione_economica pos_eco = dom.livello.posizione_economica punteggio_titoli_pos_eco = bando.get_punteggio_titoli_pos_eco(pos_eco) for mdb in dom.modulodomandabando_set.all(): if mdb.disabilita: continue json_dict = json.loads(mdb.modulo_compilato) d = get_as_dict(json_dict) if field_name in d.keys(): punteggio = Punteggio_TitoloStudio.objects.get(pk=d[field_name]) if punteggio not in punteggio_titoli_pos_eco: errato = (dipendente, mdb.descrizione_indicatore, ' - livello {}'.format(pos_eco)) print(*errato) print(bando.punteggio_titolostudio_set.get(pk=d[field_name]), '::', d.get('etichetta_inserimento'), '::', d.get('rilasciato_da')) print() lista_errati.append(errato) if salva: mdb.disabilita = True mdb.motivazione = _motivazione mdb.save()
def download_modulo_inserito_pdf(request, bando_id, modulo_compilato_id): """ Esegue l'output in pdf riutilizzando le view precedenti evitiamo di rifare gli stessi controlli ricicliamo query e decoratori """ bando = _get_bando_queryset(bando_id).first() # se scarica un utente staff o un membro della commissione può accedervi if _user_is_staff_or_in_commission(request.user, bando): mdb = get_object_or_404(ModuloDomandaBando, pk=modulo_compilato_id, domanda_bando__bando=bando) dipendente = mdb.domanda_bando.dipendente # altrimenti solo se l'utente è il proprietario e la domanda è attiva else: dipendente = get_object_or_404(Dipendente, matricola=request.user.matricola) mdb = get_object_or_404(ModuloDomandaBando, pk=modulo_compilato_id, domanda_bando__dipendente=dipendente, domanda_bando__bando=bando) descrizione_indicatore = mdb.descrizione_indicatore form = mdb.compiled_form(remove_filefields=True) d = { 'form': form, 'dipendente': dipendente, 'bando': bando, 'modulo_domanda_bando': mdb, 'descrizione_indicatore': descrizione_indicatore } response = render(request, 'modulo_form_readonly_pdf.html', d) # file names pdf_fname = 'modulo_inserito_{}.pdf'.format(mdb.pk) pdf_path = settings.TMP_DIR + os.path.sep + pdf_fname # prendo il pdf principale main_pdf_file = response_as_pdf(response, pdf_fname).content merger = PdfFileMerger(strict=False) main_pdf_file = BytesIO(main_pdf_file) merger.append(main_pdf_file) try: # gli appendo gli allegati for allegato in mdb.get_allegati_path(): merger.append(allegato) merger.write(pdf_path) # torno il tutto in response f = open(pdf_path, 'rb') response = HttpResponse(f.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=' + pdf_fname except Exception as e: #mdb_dict = mdb.get_as_dict() json_dict = json.loads(mdb.modulo_compilato) mdb_dict = get_as_dict(json_dict) return render( request, 'custom_message.html', { 'avviso': ("E' stato incorso un errore relativo alla interpretazione " "dei file PDF da te immessi come allegato.<br>" "Nello specifico: '{}' presenta delle anomalie di formato" ". Questo è dovuto " "al processo di produzione " "del PDF. <br>E' necessario ricreare il PDF " "con una procedura differente da quella " "precedenemente utilizzata oppure, più " "semplicemente, ristampare il PDF come file, " "rimuovere il vecchio allegato dal modulo inserito " "e caricare il nuovo appena ristampato/riconvertito.").format( mdb_dict.get('allegati')) }) # pulizia f.close() main_pdf_file.close() os.remove(pdf_path) return response
def calcolo_punteggio(self, save=False): """ Calcolo automatico del punteggio assegnato al Modulo Compilato che è collegato a una particolare DescrizioneIndicatore Questo metodo non tiene conto del limite max di punteggio assegnabile che sarà rispettato in fase di assegnazione del punteggio alla Domanda """ punteggio = 0 descr_ind = self.descrizione_indicatore # Se la DescrizioneIndicatore ha il calcolo punteggio automatico if descr_ind.calcolo_punteggio_automatico: json_dict = json.loads(self.modulo_compilato) dati_inseriti = get_as_dict(json_dict) dipendente = self.domanda_bando.dipendente cat_eco = self.domanda_bando.get_livello_dipendente( ).posizione_economica # Se il form prevede un campo Punteggio if "punteggio_dyn" in dati_inseriti: punteggio = float(dati_inseriti.get("punteggio_dyn")) # Se il form prevede un campo "Titolo di Studio" con punteggio elif "titolo_di_studio_superiore" in dati_inseriti: punteggio_titolo = self.punteggio_titolo_studio() punteggio = float(punteggio_titolo[1]) # Se il form prevede la selezione di un SubDescrizioneIndicatore elif "sub_descrizione_indicatore" in dati_inseriti: subdescrind_id = dati_inseriti.get( "sub_descrizione_indicatore") subdescrind = descr_ind.subdescrizioneindicatore_set.filter( pk=subdescrind_id).first() if subdescrind.punteggio_subdescrizioneindicatore_set.first(): punteggio = self.punteggio_descrizione_indicatore( cat_eco, subdescrind) elif subdescrind.punteggio_subdescrizioneindicatore_timedelta_set.first( ): durata_inserita = int( dati_inseriti.get("durata_come_intero", 0)) durata = self.get_durata_int( durata_inserita, dati_inseriti.get("data_inizio_dyn_inner"), dati_inseriti.get("data_fine_dyn_inner"), dati_inseriti.get("in_corso_dyn"), dati_inseriti.get("data_inizio_dyn_out"), dati_inseriti.get("data_fine_dyn_out")) punteggio = self.punteggio_descr_timedelta( cat_eco, durata, subdescrind) # Se la DescrizioneIndicatore prevede un punteggio "fisso" per categoria elif descr_ind.punteggio_descrizioneindicatore_set.first(): punteggio = self.punteggio_descrizione_indicatore(cat_eco) # Se la DescrizioneIndicatore prevede un punteggio per durata temporale # WARNING: stiamo usando costanti, da ricodare con metodi che tornano i valori/tipi elif descr_ind.punteggio_descrizioneindicatore_timedelta_set.first( ): try: durata_inserita = int( dati_inseriti.get("durata_come_intero", 0)) except ValueError as excp: durata_inserita = 0 # aggiungere logger.error in ogni dove ... durata = self.get_durata_int( durata_inserita, dati_inseriti.get("data_inizio_dyn_inner"), dati_inseriti.get("data_fine_dyn_inner"), dati_inseriti.get("in_corso_dyn"), dati_inseriti.get("data_inizio_dyn_out"), dati_inseriti.get("data_fine_dyn_out")) punteggio = self.punteggio_descr_timedelta(cat_eco, durata) if save: self.punteggio_calcolato = punteggio self.save() return punteggio
def ticket_add_new(request, struttura_slug, categoria_slug): """ Create the ticket :type structure_slug: String :type categoria_slug: String :param structure_slug: slug of structure :param categoria_slug: slug of category :return: render """ if Ticket.number_limit_reached_by_user(request.user): messages.add_message(request, messages.ERROR, _("Hai raggiunto il limite massimo giornaliero" " di ticket: {}".format(MAX_DAILY_TICKET_PER_USER))) return redirect(reverse('uni_ticket:user_dashboard')) struttura = get_object_or_404(OrganizationalStructure, slug=struttura_slug, is_active=True) categoria = get_object_or_404(TicketCategory, slug=categoria_slug, is_active=True) if not categoria.allowed_to_user(request.user): return custom_message(request, _("Permesso negato a questa tipologia di utente."), struttura.slug) title = _("Apri un nuovo ticket") template = 'user/ticket_add_new.html' sub_title = _("Compila i campi richiesti") modulo = get_object_or_404(TicketCategoryModule, ticket_category=categoria, is_active=True) form = modulo.get_form(show_conditions=True) clausole_categoria = categoria.get_conditions() d={'categoria': categoria, 'conditions': clausole_categoria, 'form': form, 'struttura': struttura, 'sub_title': sub_title, 'title': title} if request.POST: form = modulo.get_form(data=request.POST, files=request.FILES, show_conditions=True) d['form'] = form if form.is_valid(): fields_to_pop = [TICKET_CONDITIONS_FIELD_ID, TICKET_SUBJECT_ID, TICKET_DESCRIPTION_ID] json_data = get_POST_as_json(request=request, fields_to_pop=fields_to_pop) # make a UUID based on the host ID and current time code = uuid_code() subject = request.POST.get(TICKET_SUBJECT_ID) description = request.POST.get(TICKET_DESCRIPTION_ID) ticket = Ticket(code=code, subject=subject, description=description, modulo_compilato=json_data, created_by=request.user, input_module=modulo) ticket.save() # salvataggio degli allegati nella cartella relativa json_dict = json.loads(ticket.modulo_compilato) json_stored = get_as_dict(compiled_module_json=json_dict) if request.FILES: json_stored["allegati"] = {} path_allegati = get_path_allegato(ticket) for key, value in request.FILES.items(): salva_file(request.FILES.get(key), path_allegati, request.FILES.get(key)._name) value = request.FILES.get(key)._name json_stored["allegati"]["{}".format(key)]="{}".format(value) set_as_dict(ticket, json_stored) office = categoria.organizational_office or struttura.get_default_office() if not office: messages.add_message(request, messages.ERROR, _("Nessun ufficio di default impostato")) return redirect(reverse('uni_ticket:user_dashboard')) ticket_assignment = TicketAssignment(ticket=ticket, office=office, assigned_by=request.user) ticket_assignment.save() ticket_detail_url = reverse('uni_ticket:ticket_detail', args=[code]) # Send mail to ticket owner mail_params = {'hostname': settings.HOSTNAME, 'user': request.user, 'status': _('submitted'), 'ticket': ticket } m_subject = _('{} - ticket {} submitted'.format(settings.HOSTNAME, ticket)) send_custom_mail(subject = m_subject, body=NEW_TICKET_UPDATE.format(**mail_params), recipient=request.user) # END Send mail to ticket owner messages.add_message(request, messages.SUCCESS, _("Ticket creato con successo " "con il codice <b>{}</b>").format(code)) return redirect('uni_ticket:ticket_detail', ticket_id=ticket.code) else: for k,v in get_labeled_errors(form).items(): messages.add_message(request, messages.ERROR, "<b>{}</b>: {}".format(k, strip_tags(v))) return render(request, template, d)
def ticket_clone(request, ticket_id): master_ticket = get_object_or_404(Ticket, code=ticket_id, created_by=request.user) # if ticket is not closed and owner has closed it if not master_ticket.is_closed: return custom_message( request, _("Operazione non permessa. " "Il ticket è ancora attivo")) # if ticket module is out of date if not master_ticket.input_module.is_active: return custom_message( request, _("Il modulo che stai cercando " "di usare non è più attivo.")) category = master_ticket.input_module.ticket_category data = master_ticket.get_modulo_compilato() data['ticket_subject'] = master_ticket.subject data['ticket_description'] = master_ticket.description form = master_ticket.input_module.get_form(data=data, show_conditions=True) title = category template = 'user/ticket_add_new.html' sub_title = category.description if category.description else _( "Compila i campi richiesti") clausole_categoria = category.get_conditions() d = { 'categoria': category, 'category_conditions': clausole_categoria, 'form': form, 'struttura': category.organizational_structure, 'sub_title': '{} - {}'.format(category.organizational_structure, sub_title), 'title': title } if request.POST: form = master_ticket.input_module.get_form(data=request.POST, files=request.FILES, show_conditions=True) d['form'] = form if form.is_valid(): fields_to_pop = [ settings.TICKET_CONDITIONS_FIELD_ID, settings.TICKET_SUBJECT_ID, settings.TICKET_DESCRIPTION_ID ] json_data = get_POST_as_json(request=request, fields_to_pop=fields_to_pop) # make a UUID based on the host ID and current time code = uuid_code() subject = form.cleaned_data[settings.TICKET_SUBJECT_ID] description = form.cleaned_data[settings.TICKET_DESCRIPTION_ID] ticket = Ticket(code=code, subject=subject, description=description, modulo_compilato=json_data, created_by=request.user, input_module=master_ticket.input_module) ticket.save() # log action logger.info('[{}] user {} created new ticket {}' ' in category {}'.format(timezone.now(), request.user.username, ticket, category)) # salvataggio degli allegati nella cartella relativa json_dict = ticket.get_modulo_compilato() json_stored = get_as_dict(compiled_module_json=json_dict) _save_new_ticket_attachments(ticket=ticket, json_stored=json_stored, form=form, request_files=request.FILES) # Old version. Now a category MUST have an office! # office = categoria.organizational_office or struttura.get_default_office() office = category.organizational_office ticket_assignment = TicketAssignment(ticket=ticket, office=office) # assigned_by=request.user) ticket_assignment.save() if category.is_notify: random_office_operator = OrganizationalStructureOfficeEmployee.get_default_operator_or_manager( office) # if ticket is a notify, take the ticket _close_notification_ticket(ticket=ticket, user=request.user, operator=random_office_operator, ticket_assignment=ticket_assignment) # log action logger.info('[{}] ticket {} assigned to ' '{} office'.format(timezone.now(), ticket, office)) # category default tasks _assign_default_tasks_to_new_ticket(ticket=ticket, category=category, log_user=request.user) # Send mail to ticket owner ticket_message = ticket.input_module.ticket_category.confirm_message_text or \ settings.NEW_TICKET_CREATED_ALERT compiled_message = ticket_message.format(ticket.subject) mail_params = { 'hostname': settings.HOSTNAME, 'user': request.user, 'ticket': ticket.code, 'ticket_subject': subject, 'url': request.build_absolute_uri( reverse('uni_ticket:ticket_detail', kwargs={'ticket_id': ticket.code})), 'added_text': compiled_message } # if office operators must receive notification email if category.receive_email: # Send mail to ticket owner _send_new_ticket_mail_to_operators(request=request, ticket=ticket, category=category) m_subject = _('{} - {}'.format(settings.HOSTNAME, compiled_message)) m_subject = m_subject[:80] + (m_subject[80:] and '...') send_custom_mail(subject=m_subject, recipient=request.user, body=settings.NEW_TICKET_CREATED, params=mail_params) # END Send mail to ticket owner messages.add_message(request, messages.SUCCESS, compiled_message) return redirect('uni_ticket:ticket_detail', ticket_id=ticket.code) else: for k, v in get_labeled_errors(form).items(): messages.add_message(request, messages.ERROR, "<b>{}</b>: {}".format(k, strip_tags(v))) return render(request, template, d)