Exemple #1
0
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)
Exemple #2
0
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
Exemple #3
0
 def save_data(self, subject, description, ticket_dict):
     self.subject = subject
     self.description = description
     set_as_dict(self,
                 ticket_dict,
                 fields_to_pop=[
                     settings.TICKET_SUBJECT_ID,
                     settings.TICKET_DESCRIPTION_ID
                 ])
Exemple #4
0
def modifica_titolo_form(request,
                         bando,
                         descrizione_indicatore,
                         mdb,
                         allegati,
                         path_allegati,
                         return_url,
                         log=False):
    json_response = json.loads(get_POST_as_json(request))
    # Costruisco il form con il json dei dati inviati e tutti gli allegati
    json_response["allegati"] = allegati
    # rimuovo solo gli allegati che sono stati già inseriti
    form = descrizione_indicatore.get_form(data=json_response,
                                           files=request.FILES,
                                           domanda_bando=mdb.domanda_bando,
                                           remove_filefields=allegati)
    if form.is_valid():
        if request.FILES:
            for key, value in request.FILES.items():
                # form.validate_attachment(request.FILES[key])
                salva_file(request.FILES[key],
                            path_allegati,
                            request.FILES[key]._name)
                nome_allegato = request.FILES[key]._name
                json_response["allegati"]["{}".format(key)] = "{}".format(nome_allegato)
        else:
            # Se non ho aggiornato i miei allegati lasciandoli invariati rispetto
            # all'inserimento precedente
            json_response["allegati"] = allegati

        # salva il modulo
        set_as_dict(mdb, json_response)
        # data di modifica
        mdb.mark_as_modified()
        #Allega il messaggio al redirect
        msg = 'Modifica {} - Etichetta: {} - effettuata con successo!'.format(mdb,
                                                                              request.POST.get(ETICHETTA_INSERIMENTI_ID))
        messages.success(request, msg)
        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)
    else:
        dictionary = {}
        # il form non è valido, ripetere inserimento
        dictionary['form'] = form
        return dictionary
Exemple #5
0
def _save_new_ticket_attachments(ticket, json_stored, form, request_files):
    if request_files:
        json_stored[settings.ATTACHMENTS_DICT_PREFIX] = {}
        path_allegati = get_path(ticket.get_folder())
        for key, value in request_files.items():
            save_file(form.cleaned_data[key], path_allegati,
                      form.cleaned_data[key]._name)
            value = form.cleaned_data[key]._name
            json_stored[settings.ATTACHMENTS_DICT_PREFIX][key] = value

            # log action
            logger.info('[{}] attachment {} saved in {}'.format(
                timezone.now(), form.cleaned_data[key], path_allegati))

        set_as_dict(ticket, json_stored)
Exemple #6
0
 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
Exemple #7
0
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)
Exemple #8
0
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)
Exemple #9
0
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)