コード例 #1
0
    def get_context_data(self, **kwargs):
        context = super(CalendarManage, self).get_context_data(**kwargs)
        day_string = self.request.GET.get('day', None)
        day = tamdates.parse_datestring(day_string, default=ita_today())
        # this filter is valid until the next day
        nextday = day + datetime.timedelta(days=1)
        context[
            'nextday'] = nextday  # I'll use this to check if the range goes ahead on days
        context['day'] = day
        context['selected_day'] = day.strftime('%d/%m/%Y')
        calendars = copy.copy(settings.CALENDAR_DESC)
        # I don't use the date-interval cross detection anymore...
        #  let's see only the event's starting in the day
        calendars_in_the_day = Calendar.objects.filter(
            date_start__range=(day, nextday), )
        # one query to get the calendars, then regrouped
        for caltype, calDesc in calendars.items():
            calDesc['elements'] = [
                c for c in calendars_in_the_day if c.type == caltype
            ]

        context['calendars'] = calendars
        context['conducenti'] = Conducente.objects.filter(attivo=True)
        context.update({
            "mediabundleJS": ('tamUI', ),  # I need the datepicker
            "mediabundleCSS": ('tamUI', ),
        })
        context['form'] = CalendarForm(
            self.request.POST if self.request.method == 'POST' else None)
        context['dontHilightFirst'] = True
        is_old_day = day < ita_today()
        context['can_edit'] = not is_old_day or self.request.user.has_perm(
            'calendariopresenze.change_oldcalendar')
        return context
コード例 #2
0
ファイル: views.py プロジェクト: dariosky/tam
    def get_context_data(self, **kwargs):
        context = super(CalendarManage, self).get_context_data(**kwargs)
        day_string = self.request.GET.get('day', None)
        day = tamdates.parse_datestring(day_string, default=ita_today())
        # this filter is valid until the next day
        nextday = day + datetime.timedelta(days=1)
        context['nextday'] = nextday  # I'll use this to check if the range goes ahead on days
        context['day'] = day
        context['selected_day'] = day.strftime('%d/%m/%Y')
        calendars = copy.copy(settings.CALENDAR_DESC)
        # I don't use the date-interval cross detection anymore...
        #  let's see only the event's starting in the day
        calendars_in_the_day = Calendar.objects.filter(
            date_start__range=(day, nextday),
        )
        # one query to get the calendars, then regrouped
        for caltype, calDesc in calendars.items():
            calDesc['elements'] = [c for c in calendars_in_the_day if c.type == caltype]

        context['calendars'] = calendars
        context['conducenti'] = Conducente.objects.filter(attivo=True)
        context.update({"mediabundleJS": ('tamUI',),  # I need the datepicker
                        "mediabundleCSS": ('tamUI',),
                        })
        context['form'] = CalendarForm(self.request.POST if self.request.method == 'POST' else None)
        context['dontHilightFirst'] = True
        is_old_day = day < ita_today()
        context['can_edit'] = not is_old_day or self.request.user.has_perm(
            'calendariopresenze.change_oldcalendar')
        return context
コード例 #3
0
ファイル: main.py プロジェクト: AdhlanFauzan/tam
def attachments_list(request):
    get_mese = request.GET.get('mese', None)
    oggi = tamdates.ita_today()
    quick_month_names = [
        MONTH_NAMES[(oggi.month - 3) % 12], MONTH_NAMES[(oggi.month - 2) % 12],
        MONTH_NAMES[(oggi.month - 1) % 12]
    ]  # current month
    quick_month_names.reverse()

    if get_mese:
        if get_mese == "cur":
            data_start = oggi.replace(day=1)
            data_end = (data_start + datetime.timedelta(days=32)).replace(
                day=1) - datetime.timedelta(days=1)
        elif get_mese == 'prev':
            data_end = oggi.replace(day=1) - datetime.timedelta(
                days=1)  # vado a fine mese scorso
            data_start = data_end.replace(
                day=1)  # vado a inizio del mese precedente
        elif get_mese == 'prevprev':  # due mesi fa
            data_end = (oggi.replace(day=1) - datetime.timedelta(days=1)
                        ).replace(day=1) - datetime.timedelta(
                            days=1)  # vado a inizio mese scorso
            data_start = data_end.replace(
                day=1)  # vado a inizio di due mesi fa
        else:
            raise Exception("Unexpected get mese fatture %s" % get_mese)
    else:
        data_start = parse_datestring(  # dal primo del mese scorso
            request.GET.get("data_start"),
            default=(tamdates.ita_today().replace(day=1) -
                     datetime.timedelta(days=1)).replace(day=1))
        data_end = parse_datestring(  # all'ultimo del mese scorso
            request.GET.get("data_end"),
            default=tamdates.ita_today())

    prenotazioni = Prenotazione.objects.filter(had_attachment=True,
                                               data_corsa__gte=data_start,
                                               data_corsa__lt=data_end +
                                               datetime.timedelta(days=1))
    gruppo_prenotazioni = OrderedDict()
    for prenotazione in prenotazioni:
        if prenotazione.cliente not in gruppo_prenotazioni:
            gruppo_prenotazioni[prenotazione.cliente] = []
        gruppo_prenotazioni[prenotazione.cliente].append(prenotazione)

    return render(
        request,
        'attachments_list.html',
        {
            "data_start": data_start.date(),
            "data_end": data_end.date(),
            "quick_month_names": quick_month_names,
            "dontHilightFirst": True,
            "mediabundleJS": ('tamUI', ),
            "mediabundleCSS": ('tamUI', ),
            "gruppo_prenotazioni": gruppo_prenotazioni,
        },
    )
コード例 #4
0
    def get_context_data(self, **kwargs):
        context = super(MonthDatesMixin, self).get_context_data(**kwargs)
        get_mese_fatture = self.request.GET.get('mese', None)
        oggi = tamdates.ita_today()
        quick_month_names = [
            MONTH_NAMES[(oggi.month - 3) % 12],
            MONTH_NAMES[(oggi.month - 2) % 12],
            MONTH_NAMES[(oggi.month - 1) % 12]
        ]  # current month
        quick_month_names.reverse()

        if get_mese_fatture:
            if get_mese_fatture == "cur":
                data_start = oggi.replace(day=1)
                data_end = (data_start + datetime.timedelta(days=32)).replace(
                    day=1) - datetime.timedelta(days=1)
            elif get_mese_fatture == 'prev':
                data_end = oggi.replace(day=1) - datetime.timedelta(
                    days=1)  # vado a fine mese scorso
                data_start = data_end.replace(
                    day=1)  # vado a inizio del mese precedente
            elif get_mese_fatture == 'prevprev':  # due mesi fa
                data_end = (oggi.replace(day=1) - datetime.timedelta(days=1)
                            ).replace(day=1) - datetime.timedelta(
                                days=1)  # vado a inizio mese scorso
                data_start = data_end.replace(
                    day=1)  # vado a inizio di due mesi fa
            else:
                raise Exception("Unexpected get mese fatture %s" %
                                get_mese_fatture)
        else:
            data_start = parse_datestring(  # dal primo del mese scorso
                (self.request.GET.get("data_start")
                 or self.request.session.get('{}data_start'.format(
                     self.session_prefix))),
                default=(tamdates.ita_today().replace(day=1) -
                         datetime.timedelta(days=1)).replace(day=1))
            data_end = parse_datestring(  # a oggi
                (self.request.GET.get("data_end") or self.request.session.get(
                    '{}data_end'.format(self.session_prefix))),
                default=tamdates.ita_today())
        context.update(locals())
        context.update({
            "dontHilightFirst": True,
            "mediabundleJS": ('tamUI', ),
            "mediabundleCSS": ('tamUI', ),
        })
        return context
コード例 #5
0
def action(request, template_name="archive/action.html"):
    """ Archivia le corse, mantenendo le classifiche inalterate """
    if not request.user.has_perm('tamArchive.archive'):
        messages.error(request, "Devi avere accesso all'archiviazione.")
        return HttpResponseRedirect(reverse("tamArchiveUtil"))

    end_date_string = request.POST.get("end_date")
    try:
        timetuple = time.strptime(end_date_string, '%d/%m/%Y')
        end_date = tamdates.tz_italy.localize(
            datetime.datetime(timetuple.tm_year, timetuple.tm_mon,
                              timetuple.tm_mday))
    except:
        end_date = None
    if end_date is None:
        messages.error(request,
                       "Devi specificare una data valida per archiviare.")
        return HttpResponseRedirect(reverse("tamArchiveUtil"))
    max_date = tamdates.ita_today() - datetime.timedelta(
        days=archiveNotBefore_days)
    if end_date > max_date:
        messages.error(
            request,
            "La data che hai scelto è troppo recente. Deve essere al massimo il %s."
            % max_date)
        return HttpResponseRedirect(reverse("tamArchiveUtil"))

    # non archivio le non confermate

    total_count = Viaggio.objects.count()
    count = Viaggio.objects.filter(data__lt=end_date,
                                   conducente__isnull=False).count()

    log_total = ActionLog.objects.count()
    log_count = ActionLog.objects.filter(data__lt=end_date).count()
    archive_needed = count or log_count

    if "archive" in request.POST:
        from tamArchive.tasks import do_archiviazioneTask

        do_archiviazioneTask(request.user, end_date)  # @UndefinedVariable
        messages.info(request, "Archiviazione iniziata.")

        return HttpResponseRedirect(reverse("tamArchiveUtil"))

    return render(
        request,
        template_name,
        {
            "archiveCount": count,
            "archiveTotalCount": total_count,
            "logCount": log_count,
            "logTotalCount": log_total,
            "archive_needed": archive_needed,
            "end_date": end_date,
            "end_date_string": end_date_string,
        },
    )
コード例 #6
0
ファイル: views.py プロジェクト: dariosky/tam
    def get_context_data(self, **kwargs):
        context = super(MonthDatesMixin, self).get_context_data(**kwargs)
        get_mese_fatture = self.request.GET.get('mese', None)
        oggi = tamdates.ita_today()
        quick_month_names = [MONTH_NAMES[(oggi.month - 3) % 12],
                             MONTH_NAMES[(oggi.month - 2) % 12],
                             MONTH_NAMES[(oggi.month - 1) % 12]]  # current month
        quick_month_names.reverse()

        if get_mese_fatture:
            if get_mese_fatture == "cur":
                data_start = oggi.replace(day=1)
                data_end = (data_start + datetime.timedelta(days=32)).replace(
                    day=1) - datetime.timedelta(days=1)
            elif get_mese_fatture == 'prev':
                data_end = oggi.replace(day=1) - datetime.timedelta(
                    days=1)  # vado a fine mese scorso
                data_start = data_end.replace(day=1)  # vado a inizio del mese precedente
            elif get_mese_fatture == 'prevprev':  # due mesi fa
                data_end = (oggi.replace(day=1) - datetime.timedelta(days=1)).replace(
                    day=1) - datetime.timedelta(
                    days=1)  # vado a inizio mese scorso
                data_start = data_end.replace(day=1)  # vado a inizio di due mesi fa
            else:
                raise Exception("Unexpected get mese fatture %s" % get_mese_fatture)
        else:
            data_start = parse_datestring(  # dal primo del mese scorso
                (self.request.GET.get("data_start") or
                 self.request.session.get('{}data_start'.format(self.session_prefix))),
                default=(
                    tamdates.ita_today().replace(
                        day=1) - datetime.timedelta(days=1)).replace(day=1)
            )
            data_end = parse_datestring(  # a oggi
                (self.request.GET.get("data_end") or
                 self.request.session.get('{}data_end'.format(self.session_prefix))),
                default=tamdates.ita_today()
            )
        context.update(locals())
        context.update({
            "dontHilightFirst": True,
            "mediabundleJS": ('tamUI',),
            "mediabundleCSS": ('tamUI',),
        })
        return context
コード例 #7
0
 class ArchiveForm(forms.Form):
     """ Form che chiede una data non successiva a 30 giorni fa """
     end_date_suggested = (
         tamdates.ita_today() -
         datetime.timedelta(days=archiveNotBefore_days)).replace(
             month=1, day=1).strftime('%d/%m/%Y')
     end_date = forms.DateField(label="Data finale",
                                input_formats=[_('%d/%m/%Y')],
                                initial=end_date_suggested)
コード例 #8
0
ファイル: archiveViews.py プロジェクト: dariosky/tam
def action(request, template_name="archive/action.html"):
    """ Archivia le corse, mantenendo le classifiche inalterate """
    if not request.user.has_perm('tamArchive.archive'):
        messages.error(request, "Devi avere accesso all'archiviazione.")
        return HttpResponseRedirect(reverse("tamArchiveUtil"))

    end_date_string = request.POST.get("end_date")
    try:
        timetuple = time.strptime(end_date_string, '%d/%m/%Y')
        end_date = tamdates.tz_italy.localize(
            datetime.datetime(timetuple.tm_year, timetuple.tm_mon,
                              timetuple.tm_mday))
    except:
        end_date = None
    if end_date is None:
        messages.error(request,
                       "Devi specificare una data valida per archiviare.")
        return HttpResponseRedirect(reverse("tamArchiveUtil"))
    max_date = tamdates.ita_today() - datetime.timedelta(
        days=archiveNotBefore_days)
    if end_date > max_date:
        messages.error(request,
                       "La data che hai scelto è troppo recente. Deve essere al massimo il %s." % max_date)
        return HttpResponseRedirect(reverse("tamArchiveUtil"))

    # non archivio le non confermate

    total_count = Viaggio.objects.count()
    count = Viaggio.objects.filter(data__lt=end_date,
                                   conducente__isnull=False).count()

    log_total = ActionLog.objects.count()
    log_count = ActionLog.objects.filter(data__lt=end_date).count()
    archive_needed = count or log_count

    if "archive" in request.POST:
        from tamArchive.tasks import do_archiviazioneTask

        do_archiviazioneTask(request.user, end_date)
        messages.info(request, "Archiviazione iniziata.")

        return HttpResponseRedirect(reverse("tamArchiveUtil"))

    return render(request,
                  template_name,
                  {"archiveCount": count,
                   "archiveTotalCount": total_count,
                   "logCount": log_count,
                   "logTotalCount": log_total,
                   "archive_needed": archive_needed,
                   "end_date": end_date,
                   "end_date_string": end_date_string,
                   },
                  )
コード例 #9
0
def onPageListino(canvas, doc):
    width, height = canvas._doctemplate.pagesize
    canvas.saveState()
    anno = tamdates.ita_today().year
    setPdfProperties(canvas, 'Listino %d' % anno)

    # in alto a sinistra
    y1 = height - doc.topMargin
    x = doc.leftMargin

    logo_height = 2.5 * cm
    y1 -= logo_height
    if not test: canvas.drawImage(logoImage_path, x=x, y=y1, width=7 * cm, height=logo_height)

    # in alto a destra
    y2 = height - doc.topMargin
    x = width - 8 * cm - doc.rightMargin

    consorzio = Paragraph(
        '<font size="8"><b>%s</b></font>' % settings.DATI_CONSORZIO.strip().replace('\n', '<br/>'),
        normal_right_style)
    consorzio.wrapOn(canvas, 8 * cm, y2)
    consorzio.drawOn(canvas, x=x, y=y2 - consorzio.height)
    y2 -= consorzio.height + 10

    descrittore = Paragraph('<font size="14"><b>Listino %s</b></font>' % doc.listino.nome,
                            normal_right_style)
    descrittore.wrapOn(canvas, 8 * cm, y2)
    descrittore.drawOn(canvas, x=x, y=y2 - descrittore.height)
    y2 -= descrittore.height + 10

    x = doc.leftMargin

    y = min(y1, y2)

    doc.pageTemplate.frames = [
        Frame(doc.leftMargin, doc.bottomMargin,
              width - (doc.leftMargin + doc.rightMargin), y - doc.bottomMargin,
              showBoundary=test),  # x,y, width, height
    ]
    canvas.restoreState()
コード例 #10
0
ファイル: visualizzazione.py プロジェクト: AdhlanFauzan/tam
def view_fatture(request, template_name="5_lista-fatture.html"):
    get_mese_fatture = request.GET.get('mese', None)
    oggi = tamdates.ita_today()
    quick_month_names = [
        MONTH_NAMES[(oggi.month - 3) % 12], MONTH_NAMES[(oggi.month - 2) % 12],
        MONTH_NAMES[(oggi.month - 1) % 12]
    ]  # current month
    quick_month_names.reverse()

    if get_mese_fatture:
        if get_mese_fatture == "cur":
            data_start = oggi.replace(day=1)
            data_end = (data_start + datetime.timedelta(days=32)).replace(
                day=1) - datetime.timedelta(days=1)
        elif get_mese_fatture == 'prev':
            data_end = oggi.replace(day=1) - datetime.timedelta(
                days=1)  # vado a fine mese scorso
            data_start = data_end.replace(
                day=1)  # vado a inizio del mese precedente
        elif get_mese_fatture == 'prevprev':  # due mesi fa
            data_end = (oggi.replace(day=1) - datetime.timedelta(days=1)
                        ).replace(day=1) - datetime.timedelta(
                            days=1)  # vado a inizio mese scorso
            data_start = data_end.replace(
                day=1)  # vado a inizio di due mesi fa
        else:
            raise Exception("Unexpected get mese fatture %s" %
                            get_mese_fatture)
    else:
        data_start = parse_datestring(  # dal primo del mese scorso
            request.GET.get("data_start"),
            default=(tamdates.ita_today().replace(day=1) -
                     datetime.timedelta(days=1)).replace(day=1))
        data_end = parse_datestring(  # a oggi
            request.GET.get("data_end"),
            default=tamdates.ita_today())

    gruppo_fatture = []
    for fatturazione in DEFINIZIONE_FATTURE:
        selezione = Fattura.objects.filter(tipo=fatturazione.codice,
                                           data__gte=data_start,
                                           data__lte=data_end)
        order_on_view = getattr(fatturazione, 'order_on_view',
                                ['emessa_da', 'data', 'emessa_a'])
        selezione = selezione.order_by(
            *order_on_view)  # ordinamento delle fatture in visualizzazione
        dictFatturazione = {
            "d": fatturazione,  # la definizione della fatturazione
            "lista": selezione,
        }
        gruppo_fatture.append(dictFatturazione)

    # lista_consorzio = Fattura.objects.filter(tipo='1', data__gte=data_start, data__lte=data_end)
    # lista_consorzio = lista_consorzio.annotate(valore=Sum(F('righe__prezzo')*(1+F('righe__iva')/100)))
    # TODO: (Django 1.4) dovrei annotare prezzo*1+iva/100, non si può fare attualmente
    # lista_conducente = Fattura.objects.filter(tipo='2', data__gte=data_start, data__lte=data_end)
    # 	lista_ricevute = Fattura.objects.filter(tipo='3', data__gte=data_start, data__lte=data_end)

    return render(
        request,
        template_name,
        {
            "data_start": data_start.date(),
            "data_end": data_end.date(),
            "dontHilightFirst": True,
            "mediabundleJS": ('tamUI', ),
            "mediabundleCSS": ('tamUI', ),
            "gruppo_fatture": gruppo_fatture,
            "quick_month_names": quick_month_names,
        },
    )
コード例 #11
0
ファイル: generazione.py プロジェクト: dariosky/tam
def lista_fatture_generabili(request, template_name="1_scelta_fatture.html"):
    get_mese_fatture = request.GET.get('mese', None)
    oggi = tamdates.ita_today()
    quick_month_names = [MONTH_NAMES[(oggi.month - 3) % 12],
                         MONTH_NAMES[(oggi.month - 2) % 12],
                         MONTH_NAMES[(oggi.month - 1) % 12]]  # current month
    quick_month_names.reverse()
    if get_mese_fatture:
        if get_mese_fatture == "cur":
            data_start = oggi.replace(day=1)
            data_end = (data_start + datetime.timedelta(days=32)).replace(
                day=1) - datetime.timedelta(days=1)
        elif get_mese_fatture == 'prev':
            data_end = oggi.replace(day=1) - datetime.timedelta(days=1)  # vado a fine mese scorso
            data_start = data_end.replace(day=1)  # vado a inizio del mese precedente
        elif get_mese_fatture == 'prevprev':  # due mesi fa
            data_end = (oggi.replace(day=1) - datetime.timedelta(days=1)).replace(
                day=1) - datetime.timedelta(
                days=1)  # vado a inizio mese scorso
            data_start = data_end.replace(day=1)  # vado a inizio di due mesi fa
        else:
            raise Exception("Unexpected get mese fatture %s" % get_mese_fatture)
    else:
        data_start = parse_datestring(  # dal primo del mese scorso
            request.GET.get("data_start"),
            default=(tamdates.ita_today().replace(
                day=1) - datetime.timedelta(
                days=1)).replace(day=1)
        )
        data_end = parse_datestring(  # all'ultimo del mese scorso
            request.GET.get("data_end"),
            default=tamdates.ita_today().replace(
                day=1) - datetime.timedelta(days=1)
        )

    # prendo i viaggi da fatturare
    # dalla mezzanotte del primo giorno alla mezzanotte esclusa del giorno dopo l'ultimo
    gruppo_fatture = []

    for fatturazione in DEFINIZIONE_FATTURE:
        if not fatturazione.generabile: continue
        selezione = fatturazione.origine.objects
        selezione = selezione.filter(fatturazione.filtro)

        if fatturazione.origine == Viaggio:
            #			selezione = selezione.filter(id=81833)	#DEBUG:
            selezione = selezione.filter(data__gte=data_start,
                                         data__lt=data_end + datetime.timedelta(
                                             days=1))

            selezione = selezione.select_related("da", "a", "cliente",
                                                 "conducente", "passeggero",
                                                 "padre")
        if fatturazione.origine == RigaFattura:
            selezione = selezione.filter(viaggio__data__gte=data_start,
                                         viaggio__data__lte=data_end + datetime.timedelta(
                                             days=1))
            selezione = selezione.select_related("viaggio__da", "viaggio__a",
                                                 "viaggio__cliente",
                                                 "viaggio__conducente",
                                                 "viaggio__passeggero",
                                                 'fattura', 'conducente')
        selezione = selezione.order_by(*fatturazione.order_by)

        dictFatturazione = {"d": fatturazione,
                            # la definizione della fatturazione
                            "lista": selezione,
                            }
        if hasattr(fatturazione, "update_context"):
            dictFatturazione["parametri"] = fatturazione.update_context(
                data_start, data_end) if hasattr(fatturazione,
                                                 "update_context") else {}
        else:
            dictFatturazione["parametri"] = {}
        gruppo_fatture.append(dictFatturazione)
    oggi = tamdates.ita_today()

    profile = ProfiloUtente.objects.get(user=request.user)
    luogoRiferimento = profile.luogo
    return render(
        request,
        template_name,
        {
            "today": oggi,
            "luogoRiferimento": luogoRiferimento,
            "data_start": data_start,
            "data_end": data_end,
            "dontHilightFirst": True,
            "mediabundleJS": ('tamUI',),
            "mediabundleCSS": ('tamUI',),

            "gruppo_fatture": gruppo_fatture,
            'PREZZO_VIAGGIO_NETTO': PREZZO_VIAGGIO_NETTO,
            "quick_month_names": quick_month_names,
        },
    )
コード例 #12
0
ファイル: views.py プロジェクト: dariosky/tam
def actionLog(request, template_name="actionLog.html"):
    logAndCleanExpiredSessions()
    from_a_superuser = request.user.is_superuser
    utenti = User.objects.all().order_by('username')
    if not from_a_superuser:
        utenti = utenti.exclude(is_superuser=True)  # normal users don't see superusers
    filterUtente = request.GET.get('user', '')
    filterType = request.GET.get('type', '')
    filterId = request.GET.get('id', '')
    filterAction = request.GET.get('action', '')
    filterPreInsert = 'preInsert' in request.GET.keys()  # se ho preinsert cerco tutte le inserite postume
    content_type = None
    viaggioType = ContentType.objects.get(app_label="tam", model='viaggio')
    if filterType:
        if filterType == 'fattura':
            content_type = ContentType.objects.get(app_label="fatturazione", model='fattura')
        else:
            try:
                content_type = ContentType.objects.get(app_label="tam", model=filterType)
            except ContentType.DoesNotExist:
                messages.error(request, "Tipo di oggetto da loggare non valido %s." % filterType)

    actions = ActionLog.objects.all()
    if filterUtente:  # rendo filterUtente un intero
        try:
            filterUtente = int(filterUtente)
        except:
            messages.error(request, "Utente %s non valido." % filterUtente)
            filterUtente = ""
    if filterId and content_type:  # rendo filterUtente un intero
        try:
            filterId = int(filterId)
        except:
            messages.error(request, "ID %s non valido." % filterId)
            filterId = ""
    if filterUtente:
        logging.debug("Filtro per utente %s" % filterUtente)
        actions = actions.filter(user_id=filterUtente)
    if content_type:
        logging.debug("Filtro per tipo oggetto %s" % content_type.model)
        actions = actions.filter(modelName=content_type.model)
    if filterId:
        logging.debug("Filtro per id %s" % filterId)
        actions = actions.filter(instance_id=filterId)
    if filterAction:
        actions = actions.filter(action_type=filterAction)
    if filterPreInsert:
        actions = actions.filter(modelName='viaggio')
        actions = actions.filter(action_type__in=('A', 'M'))
        actions = actions.filter(hilight=True)
    if not from_a_superuser:
        superuser_ids = User.objects.filter(is_superuser=True).values_list('id', flat=True)
        actions = actions.exclude(user_id__in=superuser_ids)  # hide superactions to normal

    # inserimento postumo se la data della corsa è precedente alla mezzanotte del
    # giorno di inserimento

    paginator = Paginator(actions, 60, orphans=3)  # pagine
    page = request.GET.get("page", 1)
    try:
        page = int(page)
    except:
        page = 1

    s = SmartPager(page, paginator.num_pages)
    paginator.smart_page_range = s.results

    try:
        thisPage = paginator.page(page)
        actions = thisPage.object_list
    # for action in actions:		# evidenzio tutti i viaggio "preInsert"
    #			if action.modelName == 'viaggio':
    #				action.preInsert = False
    #				if action.action_type in ('A', 'M'):
    #					viaggio = Viaggio.objects.get(id=action.instance_id)
    #					action.preInsert = viaggio.data < action.data.replace(hour=0, minute=0)
    except Exception:
        messages.warning(request, "La pagina %d è vuota." % page)
        thisPage = None
        actions = []

    return render(request,
                  template_name,
                  {
                      "actions": actions,
                      "today": tamdates.ita_today(),
                      "thisPage": thisPage,
                      "paginator": paginator,
                      "utenti": utenti,
                      'filterAction': filterAction,
                      "filterUtente": filterUtente,
                      "filterPreInsert": filterPreInsert,
                      "viaggioType": viaggioType
                  },
                  )
コード例 #13
0
ファイル: fixAction.py プロジェクト: AdhlanFauzan/tam
def fixAction(request, template_name="utils/fixAction.html"):
    if not request.user.is_superuser:
        messages.error(request, "Devi avere i superpoteri per eseguire le azioni correttive.")
        return HttpResponseRedirect(reverse("tamUtil"))

    messageLines = []
    error = ""
    #	messageLines.append("Nessuna azione correttiva impostata. Meglio tenere tutto fermo di default.")
    if request.POST.get('toV2'):
        # ===========================================================================
        # Azione di aggiornamento alla 2.0
        # Aggiungo lo speciale ai luoghi in base al nome
        # Effettuo il vacuum del DB
        from tamArchive.tasks import vacuum_db

        messageLines.append('Imposto gli speciali sui luoghi con stazione/aer* nel nome.')
        stazioni = Luogo.objects.filter(nome__icontains='stazione').exclude(speciale='S')
        if len(stazioni):
            messageLines.append('%d stazioni trovate:' % len(stazioni))
        for stazione in stazioni:
            stazione.speciale = 'S'
            stazione.save()
            messageLines.append(stazione.nome)
        aeroporti = Luogo.objects.filter(nome__icontains=' aer').exclude(speciale='A')
        if len(aeroporti):
            messageLines.append('%d aeroporti trovati:' % len(aeroporti))
        for aeroporto in aeroporti:
            aeroporto.speciale = 'A'
            aeroporto.save()
            messageLines.append(aeroporto.nome)

        gruppo_potenti = Group.objects.get(name='Potente')
        permessiDaAggiungere = ('get_backup', 'can_backup', 'archive', 'flat')
        for nomePermesso in permessiDaAggiungere:
            p = Permission.objects.get(codename=nomePermesso)
            gruppo_potenti.permissions.add(p)
            messageLines.append('Do agli utenti potenti: %s' % nomePermesso)
        messageLines.append('Vacuum DB.')
        vacuum_db()
        # ===========================================================================

    if "Aggiorno i prezzi di Padova e Venezia delle corse degli ultimi 2 mesi" == False:
        corseCambiate = corse = 0

        corseDaSistemare = Viaggio.objects.filter(
            data__gt=datetime.date.today() - datetime.timedelta(days=60),
            padre__isnull=True)
        # corseDaSistemare = Viaggio.objects.filter(pk=44068, padre__isnull=True)
        for corsa in corseDaSistemare:
            oldDPadova = corsa.prezzoDoppioPadova
            oldVenezia = corsa.prezzoVenezia
            corsa.updatePrecomp(forceDontSave=True)
            if oldDPadova != corsa.prezzoDoppioPadova or oldVenezia != corsa.prezzoVenezia:
                messageLines.append("%s\n   DPD: %d->%d VE: %d->%d" % (
                    corsa, oldDPadova, corsa.prezzoDoppioPadova, oldVenezia, corsa.prezzoVenezia))
                corseCambiate += 1
            corse += 1
        messageLines.append("Corse aggiornate %d/%d" % (corseCambiate, corse))

    if False:
        messageLines.append("Conguaglio completamente la corsa 35562")
        messageLines.append("e tolgo il conguaglio alle 38740 e 38887")

        def status():
            corsa = Viaggio.objects.filter(pk=35562)[0]
            messageLines.append("la prima del %s è conguagliata di %d km su %d punti. Andrebbe 360."
                                % (corsa.date_start, corsa.km_conguagliati, corsa.punti_abbinata))

            corsa = Viaggio.objects.filter(pk=38740)[0]
            messageLines.append("la seconda del %s è conguagliata di %d km su %d punti. Andrebbe 0."
                                % (corsa.date_start, corsa.km_conguagliati, corsa.punti_abbinata))

            corsa = Viaggio.objects.filter(pk=38887)[0]
            messageLines.append("la terza del %s è conguagliata di %d km su %d punti. Andrebbe 0."
                                % (corsa.date_start, corsa.km_conguagliati, corsa.punti_abbinata))

        status()

        messageLines.append("EFFETTUO LE AZIONI!")
        corsa = Viaggio.objects.filter(pk=35562)[0]
        corsa.km_conguagliati = 360
        corsa.save()
        corsa.updatePrecomp()  # salvo perché mi toglierà i punti

        corsa = Viaggio.objects.filter(pk=38740)[0]
        corsa.km_conguagliati = 0
        corsa.save()
        corsa.updatePrecomp()  # salvo perché mi toglierà i punti

        corsa = Viaggio.objects.filter(pk=38887)[0]
        corsa.km_conguagliati = 0
        corsa.save()
        corsa.updatePrecomp()  # salvo perché mi toglierà i punti

        status()

    if request.POST.get('fixDisturbi'):
        # Per le corse abbinate, dove l'ultimo fratello è un aereoporto ricalcolo i distrubi
        print("Refixo")
        viaggi = Viaggio.objects.filter(is_abbinata__in=('P', 'S'),
                                        date_start__gt=datetime.datetime(2012, 3, 1),
                                        padre=None)
        sistemati = 0
        for viaggio in viaggi:
            ultimaCorsa = viaggio.lastfratello()
            if ultimaCorsa.da.speciale == 'A':

                disturbiGiusti = trovaDisturbi(viaggio.date_start,
                                               viaggio.get_date_end(recurse=True),
                                               metodo=fasce_semilineari)
                notturniGiusti = disturbiGiusti.get('night', 0)
                diurniGiusti = disturbiGiusti.get('morning', 0)
                if diurniGiusti != viaggio.punti_diurni or notturniGiusti != viaggio.punti_notturni:
                    messageLines.append(viaggio)
                    messageLines.append(ultimaCorsa)
                    messageLines.append(
                        "prima %s/%s" % (viaggio.punti_diurni, viaggio.punti_notturni))
                    messageLines.append("dopo %s/%s" % (diurniGiusti, notturniGiusti))
                    messageLines.append(" ")
                    viaggio.punti_diurni = diurniGiusti
                    viaggio.punti_notturni = notturniGiusti
                    viaggio.save()
                    sistemati += 1

        messageLines.append("Errati (e corretti) %d/%d" % (sistemati, len(viaggi)))
    if request.POST.get("spostaILog"):
        from tam.tasks import moveLogs

        moveLogs()
        messages.info(request, "Spostamento dei log iniziato.")

    if request.POST.get("permessiStandard"):
        import tam.views.actions.set_default_permissions as setperm

        setperm.delete_all_permissions()
        setperm.create_missing_permissions()
        setperm.create_missing_groups()
        setperm.set_default_permissions()

    if request.POST.get("deleteAllCorse"):
        messageLines.append("CANCELLO TUTTE LE PRENOTAZIONI e le CORSE")
        Prenotazione.objects.all().delete()
        Viaggio.objects.all().delete()

    if request.POST.get("renewTragitto"):
        messageLines.append("Aggiorno il tragitto precalcolato, senza toccare nient'altro.")
        # passaggio da mediagenerator a django-pipeline...
        #  gli asset precalcolati li lascio senza timestamp
        query_asset_sub = r"""
        -- night
                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/static/img/(night[\d]*)\.[a-z0-9]*\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/static/img%' AND html_tragitto LIKE '%night%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/media/(night[\d]*)\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/media/%' AND html_tragitto LIKE '%night%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/mediaprod/(night[\d]*)-[a-z0-9]*\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/mediaprod/%' AND html_tragitto LIKE '%night%';
        -- morning
                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/static/img/(morning[\d]*)\.[a-z0-9]*\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/static/img%' AND html_tragitto LIKE '%morning%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/media/(morning[\d]*)\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/media/%' AND html_tragitto LIKE '%morning%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/mediaprod/(morning[\d]*)-[a-z0-9]*\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/mediaprod/%' AND html_tragitto LIKE '%morning%';
        --arrow
                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/static/img/(arrow_right)\.[a-z0-9]*\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/static/img%' AND html_tragitto LIKE '%arrow_right%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/media/(arrow_right[\d]*)\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/media/%' AND html_tragitto LIKE '%arrow_right%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/mediaprod/(arrow_right[\d]*)\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/mediaprod/%' AND html_tragitto LIKE '%arrow_right%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/mediaprod/(arrow_right[\d]*)-[a-z0-9]*\.png', '/static/img/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/mediaprod/%' AND html_tragitto LIKE '%arrow_right%';
        --airport
                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/static/(flag/luogo-airport)\.[a-z0-9]*\.png', '/static/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/static/%' AND html_tragitto LIKE '%flag/luogo-airport%';

                            UPDATE tam_viaggio
                            SET html_tragitto = regexp_replace(html_tragitto, '/mediaprod/(flag/luogo-airport[\d]*)-[a-z0-9]*\.png', '/static/\1.png', 'g')
                            WHERE html_tragitto LIKE '%/mediaprod/flag/%' AND html_tragitto LIKE '%luogo-airport%';

                          """.replace("%", "%%")
        from django.db import connection

        cursor = connection.cursor()
        cursor.execute(query_asset_sub)
        connection.commit()
        prossimiviaggi = Viaggio.objects.filter(
            data__gt=tamdates.ita_today() - datetime.timedelta(days=15))
        messageLines.append("Ricalcolo completamente i prossimi viaggi: %s." % len(prossimiviaggi))
        for viaggio in prossimiviaggi:
            viaggio.html_tragitto = viaggio.get_html_tragitto()
            viaggio.save()

    if request.POST.get("setEndDates"):
        # add end dates to latest viaggio (I suppose we don't need it the old ones)
        viaggi = Viaggio.objects.filter(date_end=None, padre_id=None,
                                        data__gt=tamdates.ita_today() - datetime.timedelta(days=15))
        messageLines.append("Imposto la data di fine a %d corse." % len(viaggi))
        for viaggio in viaggi:
            viaggio.date_end = viaggio.get_date_end(recurse=True)
            viaggio.save(updateViaggi=False)

    if request.POST.get('setCustomPermissions'):
        stats_non_model, created = ContentType.objects.get_or_create(
            app_label='stats', model='unused'
        )

        can_see_stats, created = Permission.objects.get_or_create(
            name='can see stats', content_type=stats_non_model,
            codename='can_see_stats')
        messageLines.append(
            "Stats permissions where already there" if not created else "Stats permissions created")

    if request.POST.get('consolidateLog'):
        messageLines.append("Starting moving log files from SQLITE to the default connection")
        sourceLogs = ActionLog.objects.using('modellog').all()
        if len(sourceLogs) > 0:
            existing = ActionLog.objects.all()
            messageLines.append("Deleting the existing logs form the default: %d" % len(existing))
            existing.delete()
            messageLines.append("%d log records to move" % len(sourceLogs))
            ActionLog.objects.bulk_create(sourceLogs, batch_size=1000)
            sourceLogs.delete()
        else:
            messageLines.append("No records to move in SQLITE")
        cursor = db.connection.cursor()
        messageLines.append("Resetting log sequence")
        cursor.execute("""
        BEGIN;
          SELECT setval(pg_get_serial_sequence('"modellog_actionlog"','id'), coalesce(max("id"), 1), max("id") IS NOT NULL) FROM "modellog_actionlog";
        COMMIT;
        """)

    return render(request, template_name, {"messageLines": messageLines, "error": error})
コード例 #14
0
ファイル: views.py プロジェクト: AdhlanFauzan/tam
def actionLog(request, template_name="actionLog.html"):
    logAndCleanExpiredSessions()
    from_a_superuser = request.user.is_superuser
    utenti = User.objects.all().order_by('username')
    if not from_a_superuser:
        utenti = utenti.exclude(
            is_superuser=True)  # normal users don't see superusers
    filterUtente = request.GET.get('user', '')
    filterType = request.GET.get('type', '')
    filterId = request.GET.get('id', '')
    filterAction = request.GET.get('action', '')
    filterPreInsert = 'preInsert' in request.GET.keys(
    )  # se ho preinsert cerco tutte le inserite postume
    content_type = None
    viaggioType = ContentType.objects.get(app_label="tam", model='viaggio')
    if filterType:
        if filterType == 'fattura':
            content_type = ContentType.objects.get(app_label="fatturazione",
                                                   model='fattura')
        else:
            try:
                content_type = ContentType.objects.get(app_label="tam",
                                                       model=filterType)
            except ContentType.DoesNotExist:
                messages.error(
                    request,
                    "Tipo di oggetto da loggare non valido %s." % filterType)

    actions = ActionLog.objects.all()
    if filterUtente:  # rendo filterUtente un intero
        try:
            filterUtente = int(filterUtente)
        except:
            messages.error(request, "Utente %s non valido." % filterUtente)
            filterUtente = ""
    if filterId and content_type:  # rendo filterUtente un intero
        try:
            filterId = int(filterId)
        except:
            messages.error(request, "ID %s non valido." % filterId)
            filterId = ""
    if filterUtente:
        logging.debug("Filtro per utente %s" % filterUtente)
        actions = actions.filter(user_id=filterUtente)
    if content_type:
        logging.debug("Filtro per tipo oggetto %s" % content_type.model)
        actions = actions.filter(modelName=content_type.model)
    if filterId:
        logging.debug("Filtro per id %s" % filterId)
        actions = actions.filter(instance_id=filterId)
    if filterAction:
        actions = actions.filter(action_type=filterAction)
    if filterPreInsert:
        actions = actions.filter(modelName='viaggio')
        actions = actions.filter(action_type__in=('A', 'M'))
        actions = actions.filter(hilight=True)
    if not from_a_superuser:
        superuser_ids = User.objects.filter(is_superuser=True).values_list(
            'id', flat=True)
        actions = actions.exclude(
            user_id__in=superuser_ids)  # hide superactions to normal

    # inserimento postumo se la data della corsa è precedente alla mezzanotte del
    # giorno di inserimento

    paginator = Paginator(actions, 60, orphans=3)  # pagine
    page = request.GET.get("page", 1)
    try:
        page = int(page)
    except:
        page = 1

    s = SmartPager(page, paginator.num_pages)
    paginator.smart_page_range = s.results

    try:
        thisPage = paginator.page(page)
        actions = thisPage.object_list
    # for action in actions:		# evidenzio tutti i viaggio "preInsert"
    #			if action.modelName == 'viaggio':
    #				action.preInsert = False
    #				if action.action_type in ('A', 'M'):
    #					viaggio = Viaggio.objects.get(id=action.instance_id)
    #					action.preInsert = viaggio.data < action.data.replace(hour=0, minute=0)
    except Exception:
        messages.warning(request, "La pagina %d è vuota." % page)
        thisPage = None
        actions = []

    return render(
        request,
        template_name,
        {
            "actions": actions,
            "today": tamdates.ita_today(),
            "thisPage": thisPage,
            "paginator": paginator,
            "utenti": utenti,
            'filterAction': filterAction,
            "filterUtente": filterUtente,
            "filterPreInsert": filterPreInsert,
            "viaggioType": viaggioType
        },
    )
コード例 #15
0
ファイル: generazione.py プロジェクト: AdhlanFauzan/tam
def lista_fatture_generabili(request, template_name="1_scelta_fatture.html"):
    get_mese_fatture = request.GET.get('mese', None)
    oggi = tamdates.ita_today()
    quick_month_names = [
        MONTH_NAMES[(oggi.month - 3) % 12], MONTH_NAMES[(oggi.month - 2) % 12],
        MONTH_NAMES[(oggi.month - 1) % 12]
    ]  # current month
    quick_month_names.reverse()
    if get_mese_fatture:
        if get_mese_fatture == "cur":
            data_start = oggi.replace(day=1)
            data_end = (data_start + datetime.timedelta(days=32)).replace(
                day=1) - datetime.timedelta(days=1)
        elif get_mese_fatture == 'prev':
            data_end = oggi.replace(day=1) - datetime.timedelta(
                days=1)  # vado a fine mese scorso
            data_start = data_end.replace(
                day=1)  # vado a inizio del mese precedente
        elif get_mese_fatture == 'prevprev':  # due mesi fa
            data_end = (oggi.replace(day=1) - datetime.timedelta(days=1)
                        ).replace(day=1) - datetime.timedelta(
                            days=1)  # vado a inizio mese scorso
            data_start = data_end.replace(
                day=1)  # vado a inizio di due mesi fa
        else:
            raise Exception("Unexpected get mese fatture %s" %
                            get_mese_fatture)
    else:
        data_start = parse_datestring(  # dal primo del mese scorso
            request.GET.get("data_start"),
            default=(tamdates.ita_today().replace(day=1) -
                     datetime.timedelta(days=1)).replace(day=1))
        data_end = parse_datestring(  # all'ultimo del mese scorso
            request.GET.get("data_end"),
            default=tamdates.ita_today().replace(day=1) -
            datetime.timedelta(days=1))

    # prendo i viaggi da fatturare
    # dalla mezzanotte del primo giorno alla mezzanotte esclusa del giorno dopo l'ultimo
    gruppo_fatture = []

    for fatturazione in DEFINIZIONE_FATTURE:
        if not fatturazione.generabile: continue
        selezione = fatturazione.origine.objects
        selezione = selezione.filter(fatturazione.filtro)

        if fatturazione.origine == Viaggio:
            #			selezione = selezione.filter(id=81833)	#DEBUG:
            selezione = selezione.filter(data__gte=data_start,
                                         data__lt=data_end +
                                         datetime.timedelta(days=1))

            selezione = selezione.select_related("da", "a", "cliente",
                                                 "conducente", "passeggero",
                                                 "padre")
        if fatturazione.origine == RigaFattura:
            selezione = selezione.filter(viaggio__data__gte=data_start,
                                         viaggio__data__lte=data_end +
                                         datetime.timedelta(days=1))
            selezione = selezione.select_related("viaggio__da", "viaggio__a",
                                                 "viaggio__cliente",
                                                 "viaggio__conducente",
                                                 "viaggio__passeggero",
                                                 'fattura', 'conducente')
        selezione = selezione.order_by(*fatturazione.order_by)

        dictFatturazione = {
            "d": fatturazione,
            # la definizione della fatturazione
            "lista": selezione,
        }
        if hasattr(fatturazione, "update_context"):
            dictFatturazione["parametri"] = fatturazione.update_context(
                data_start, data_end) if hasattr(fatturazione,
                                                 "update_context") else {}
        else:
            dictFatturazione["parametri"] = {}
        gruppo_fatture.append(dictFatturazione)
    oggi = tamdates.ita_today()

    profile = ProfiloUtente.objects.get(user=request.user)
    luogoRiferimento = profile.luogo
    return render(
        request,
        template_name,
        {
            "today": oggi,
            "luogoRiferimento": luogoRiferimento,
            "data_start": data_start,
            "data_end": data_end,
            "dontHilightFirst": True,
            "mediabundleJS": ('tamUI', ),
            "mediabundleCSS": ('tamUI', ),
            "gruppo_fatture": gruppo_fatture,
            'PREZZO_VIAGGIO_NETTO': PREZZO_VIAGGIO_NETTO,
            "quick_month_names": quick_month_names,
        },
    )