Exemplo n.º 1
0
    def render_faults(self, visit, index, unit_report_data):
        """Рассчитывает большие промежутки в сообщениях, ДУТ, завязанный на моточасы"""
        # первая геозона до включения массы
        if index == 0 and len(visit.odometers) < 3:
            return 'OK'

        faults = []
        # если топливо не меняется в течение геозоны, но при этом есть минимум 1км пробега:
        fuel_start, fuel_end = getattr(visit, 'start_fuel_level'), getattr(
            visit, 'end_fuel_level')
        odometer_start = getattr(visit, 'start_odometer')
        odometer_end = getattr(visit, 'end_odometer')

        if fuel_start is not None and fuel_end is not None and fuel_end - fuel_start == .0:
            if odometer_start is not None and odometer_end is not None \
                    and odometer_end - odometer_start > 1:
                faults.append([visit.dt_from, visit.dt_to, 'ДУТ'])

        prev_odometer = None
        for odometer in visit.odometers:
            if prev_odometer:
                if (odometer.dt - prev_odometer.dt
                    ).total_seconds() > self.module_fault_timeout:
                    # если период неисправности продолжается, то есть текущий диапазон тоже
                    # большой, как и предыдущий, тогда склеиваем 2 возможные неисправности
                    if faults and faults[-1][1] == prev_odometer.dt:
                        faults[-1][1] = odometer.dt
                    else:
                        faults.append(
                            [prev_odometer.dt, odometer.dt, 'бортовой блок'])

            prev_odometer = odometer

        for fault in faults:
            fault.append(
                format_timedelta((fault[1] - fault[0]).total_seconds()))
            fault[0] = date_format(
                utc_to_local_time(fault[0], self.user.timezone), 'H:i')
            fault[1] = date_format(
                utc_to_local_time(fault[1], self.user.timezone), 'H:i')

        if faults:
            return '\n'.join([
                '%s - %s (%s), %s' % (x[0], x[1], x[3], x[2]) for x in faults
            ])

        return 'OK'
Exemplo n.º 2
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(VchmTaxiingView,
                          self).write_xls_data(worksheet, context)

        self.styles.update({
            'border_bold_left_style':
            xlwt.easyxf(
                'font: bold 1, height 200;'
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz left'),
            'border_bold_right_style':
            xlwt.easyxf(
                'font: bold 1, height 200;'
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz right')
        })

        worksheet.col(0).width = 3600
        worksheet.col(1).width = 5500
        worksheet.col(2).width = 5500
        worksheet.col(3).width = 5500
        worksheet.col(4).width = 3000
        worksheet.col(5).width = 3000
        worksheet.col(6).width = 3150
        worksheet.col(7).width = 3150
        worksheet.col(8).width = 3200
        worksheet.col(9).width = 3200
        worksheet.col(10).width = 3800
        worksheet.col(11).width = 3300
        worksheet.col(12).width = 4500
        worksheet.col(13).width = 3300
        worksheet.col(14).width = 3300
        worksheet.col(15).width = 3300
        worksheet.col(16).width = 3300
        worksheet.col(17).width = 3300
        worksheet.col(18).width = 3300
        worksheet.col(19).width = 7000

        # header
        x = 0
        if context.get('heading_data'):
            for key, value in context['heading_data'].items():
                x += 1
                worksheet.write(x,
                                0,
                                key + ' ',
                                style=self.styles['right_center_style'])
                worksheet.write_merge(x,
                                      x,
                                      1,
                                      self.xls_heading_merge - 1,
                                      value,
                                      style=self.styles['left_center_style'])
            x += 1
            worksheet.write_merge(x, x, 0, self.xls_heading_merge, '')

        headings = ('Гос № ТС', 'ФИО водителя', 'Наименование маршрута',
                    'Наименование\nгеозоны', 'Время\nвхода в\nгеозону',
                    'Время\nвыхода из\nгеозоны',
                    'Время\nнахождения\nв геозоне,\nчч:мм',
                    'Время\nв движении\nв рамках\nгеозоны,\nчч:мм',
                    'Время\nпростоя\nв рамках\nгеозоны,\nчч:мм',
                    'Время\nпростоя\nна холостом\nходу, чч:мм',
                    'Время\nпростоя\nс выключенным\nдвигателем,\nчч:мм',
                    'Время\nпростоя\nво время\nработы КМУ,\nчч:мм',
                    'Количество\nпростоев с\nдлительностью\n> 3 минут',
                    'Пробег\nв рамках\nгеозоны,\nкм',
                    'Расход\nтоплива\nв рамках\nгеозоны,\nл',
                    'Заправка\nв рамках\nгеозоны,\nл',
                    'Слив в\nрамках\nгеозоны,\nл',
                    'Перепробег\nпо маршрутам,\nкм',
                    'Перепростой\nпо маршрутам,\nч',
                    'Исправность оборудования')

        x += 1
        for y, heading in enumerate(headings):

            worksheet.write(x,
                            y,
                            heading,
                            style=self.styles['border_center_style'])

        worksheet.row(x).height = 1200

        stats = context.get('stats')
        if stats:
            x += 1
            worksheet.write_merge(x,
                                  x,
                                  0,
                                  3,
                                  'ИТОГО за смену',
                                  style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            4,
                            date_format(
                                utc_to_local_time(stats['dt_from_min'],
                                                  self.user.timezone), 'H:i'),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            5,
                            date_format(
                                utc_to_local_time(stats['dt_to_max'],
                                                  self.user.timezone), 'H:i'),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            6,
                            format_timedelta(stats['total_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            7,
                            format_timedelta(stats['moving_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            8,
                            format_timedelta(stats['parking_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            9,
                            format_timedelta(stats['idle_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            10,
                            format_timedelta(stats['idle_off_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            11,
                            format_timedelta(stats['angle_sensor_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x,
                            12,
                            stats['over_3min_parkings_count'],
                            style=self.styles['border_bold_right_style'])
            worksheet.write(x,
                            13,
                            floatcomma(stats['odometer'], -2),
                            style=self.styles['border_bold_right_style'])
            worksheet.write(x,
                            14,
                            floatcomma(stats['fuel_level_delta'], -2),
                            style=self.styles['border_bold_right_style'])
            worksheet.write(x,
                            15,
                            floatcomma(stats['refills_delta'], -2),
                            style=self.styles['border_bold_right_style'])
            worksheet.write(x,
                            16,
                            floatcomma(stats['discharge_delta'], -2),
                            style=self.styles['border_bold_right_style'])
            worksheet.write(x,
                            17,
                            floatcomma(stats['overstatement_mileage'], -2),
                            style=self.styles['border_bold_right_style'])
            worksheet.write(x,
                            18,
                            format_timedelta(stats['overstatement_time']),
                            style=self.styles['border_bold_left_style'])
            worksheet.write(x, 19, '', style=self.styles['border_left_style'])
            worksheet.row(x).height = 360

        for row in context['report_data']:
            x += 1
            worksheet.write(x,
                            0,
                            row['car_number'],
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            1,
                            row['driver_fio'],
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            2,
                            row['route_name'],
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            3,
                            row['point_name'],
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            4,
                            date_format(
                                utc_to_local_time(row['dt_from'],
                                                  self.user.timezone), 'H:i'),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            5,
                            date_format(
                                utc_to_local_time(row['dt_to'],
                                                  self.user.timezone), 'H:i'),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            6,
                            format_timedelta(row['total_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            7,
                            format_timedelta(row['moving_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            8,
                            format_timedelta(row['parking_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            9,
                            format_timedelta(row['idle_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            10,
                            format_timedelta(row['idle_off_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            11,
                            format_timedelta(row['angle_sensor_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            12,
                            row['over_3min_parkings_count'],
                            style=self.styles['border_right_style'])
            worksheet.write(x,
                            13,
                            floatcomma(row['odometer'], -2),
                            style=self.styles['border_right_style'])
            worksheet.write(x,
                            14,
                            floatcomma(row['fuel_level_delta'], -2),
                            style=self.styles['border_right_style'])
            worksheet.write(x,
                            15,
                            floatcomma(row['refills_delta'], -2),
                            style=self.styles['border_right_style'])
            worksheet.write(x,
                            16,
                            floatcomma(row['discharge_delta'], -2),
                            style=self.styles['border_right_style'])
            worksheet.write(x,
                            17,
                            floatcomma(row['overstatement_mileage'], -2),
                            style=self.styles['border_right_style'])
            worksheet.write(x,
                            18,
                            format_timedelta(row['overstatement_time']),
                            style=self.styles['border_left_style'])
            worksheet.write(x,
                            19,
                            row['faults'],
                            style=self.styles['border_left_style'])
            worksheet.row(x).height = 720

        return worksheet
Exemplo n.º 3
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(FaultsView, self).write_xls_data(worksheet, context)
        worksheet.set_portrait(False)
        worksheet.set_print_scaling(80)

        for col in range(4):
            worksheet.col(col).width = 6000
        worksheet.col(1).width = 10000
        worksheet.col(2).width = 4800
        worksheet.col(4).width = 4200
        worksheet.col(5).width = 10000

        # header
        worksheet.write_merge(
            1,
            1,
            0,
            3,
            'На дату: %s' %
            date_format(context['cleaned_data']['dt'], 'd.m.Y'),
        )

        worksheet.write_merge(2,
                              2,
                              0,
                              1,
                              'ФИО ответственного за устранение неполадок:',
                              style=self.styles['left_center_style'])

        worksheet.write_merge(2,
                              2,
                              2,
                              5,
                              '',
                              style=self.styles['bottom_border_style'])

        worksheet.write_merge(
            3,
            3,
            0,
            5,
            'Всего оборудованных транспортных объектов ССМТ: %s' %
            context['stats']['total'],
            style=self.styles['right_center_style'])

        worksheet.write_merge(
            4,
            4,
            0,
            5,
            'Из них*: исправных %s\nВозможно неисправных %s' % (
                context['stats']['total'] - context['stats']['broken'],
                context['stats']['broken'],
            ),
            style=self.styles['right_center_style'])

        # head
        worksheet.write_merge(5,
                              6,
                              0,
                              0,
                              ' Гос№ ТС',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              5,
                              1,
                              2,
                              ' Последняя полученная информация',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              3,
                              3,
                              ' ФИО водителя',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              4,
                              4,
                              ' Суммарное\nнеисправное\nрабочее время, ч',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(
            5,
            6,
            5,
            5,
            ' Наименование возможно\nнеисправного оборудования (ДУТ, ...)',
            style=self.styles['border_center_style'])
        worksheet.write(6,
                        1,
                        ' Место/геозона',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        2,
                        ' Время',
                        style=self.styles['border_center_style'])

        for i in range(6):
            worksheet.write(7,
                            i,
                            str(i + 1),
                            style=self.styles['border_center_style'])

        for i in range(1, 8):
            worksheet.row(i).height = REPORT_ROW_HEIGHT
        worksheet.row(5).height = REPORT_ROW_HEIGHT + 100
        worksheet.row(6).height = REPORT_ROW_HEIGHT + 100
        worksheet.row(4).height = REPORT_ROW_HEIGHT * 2

        # body
        i = 8
        for row in context['report_data']:
            worksheet.write(i,
                            0,
                            row['unit_name'],
                            style=self.styles['border_left_style'])
            worksheet.write(i,
                            1,
                            row['place'],
                            style=self.styles['border_left_style'])
            worksheet.write(i,
                            2,
                            date_format(row['dt'], 'Y-m-d H:i:s'),
                            style=self.styles['border_left_style'])
            worksheet.write(i,
                            3,
                            row['driver_name'],
                            style=self.styles['border_left_style'])
            worksheet.write(i,
                            4,
                            row['sum_broken_work_time'],
                            style=self.styles['border_right_style'])
            worksheet.write(i,
                            5,
                            row['fault'],
                            style=self.styles['border_left_style'])
            worksheet.row(i).height = 780
            worksheet.row(i).height_mismatch = True
            i += 1

        worksheet.write_merge(i,
                              i,
                              0,
                              5,
                              '''
*Состояния:
- исправное - передача данных с датчиков и блока (трекера) осуществляется без затруднений;
- неисправное - отсутствует передача данных с блока (трекера) или датчиков (веса, ДУТ, ...)
в течение смены.
''',
                              style=self.styles['left_center_style'])
        worksheet.row(i).height = 520 * 3

        return worksheet
Exemplo n.º 4
0
    def get_context_data(self, **kwargs):
        sess_id = self.request.session.get('sid')
        if not sess_id:
            raise ReportException(WIALON_NOT_LOGINED)

        try:
            units_list = get_units(sess_id, extra_fields=True)
        except WialonException as e:
            raise ReportException(str(e))

        self.default_unit = units_list[0]['id']
        kwargs = super(VchmTaxiingView, self).get_context_data(**kwargs)
        form = kwargs['form']
        kwargs['units'] = units_list

        if not self.request.POST:
            return kwargs

        if form.is_valid():
            report_data = []
            stats = {
                'dt_from_min': None,
                'dt_to_max': None,
                'total_time': .0,
                'moving_time': .0,
                'parking_time': .0,
                'idle_time': .0,
                'idle_off_time': .0,
                'angle_sensor_time': .0,
                'over_3min_parkings_count': 0,
                'odometer': .0,
                'fuel_level_delta': .0,
                'refills_delta': .0,
                'discharge_delta': .0,
                'overstatement_mileage': .0,
                'overstatement_time': .0
            }
            kwargs.update(report_data=report_data, stats=stats)

            self.user = User.objects.filter(is_active=True) \
                .filter(wialon_username=self.request.session.get('user')).first()
            if not self.user:
                raise ReportException(WIALON_USER_NOT_FOUND)

            local_dt_from = datetime.datetime.combine(form.cleaned_data['dt'],
                                                      datetime.time(0, 0, 0))
            local_dt_to = datetime.datetime.combine(form.cleaned_data['dt'],
                                                    datetime.time(23, 59, 59))

            unit_id = form.cleaned_data.get('unit')
            self.units_dict = OrderedDict([(x['name'], x) for x in units_list
                                           if x['id'] == unit_id])
            unit = list(self.units_dict.values())[0]

            routes = {
                x['id']: x
                for x in get_routes(sess_id, with_points=True)
            }
            standard_job_templates = StandardJobTemplate.objects \
                .filter(wialon_id__in=[str(x) for x in routes.keys()]) \
                .prefetch_related(
                    Prefetch(
                        'points',
                        StandardPoint.objects.filter(
                            Q(total_time_standard__isnull=False) |
                            Q(parking_time_standard__isnull=False)
                        ),
                        'points_cache'
                    )
                )

            standards = {
                int(x.wialon_id): {
                    'space_overstatements_standard':
                    x.space_overstatements_standard
                    if x.space_overstatements_standard is not None else None,
                    'points': {
                        p.title: {
                            'total_time_standard':
                            p.total_time_standard
                            if p.total_time_standard is not None else None,
                            'parking_time_standard':
                            p.parking_time_standard
                            if p.parking_time_standard is not None else None
                        }
                        for p in x.points_cache
                    }
                }
                for x in standard_job_templates if
                x.space_overstatements_standard is not None or x.points_cache
            }

            service = MovingService(self.user,
                                    local_dt_from,
                                    local_dt_to,
                                    sess_id,
                                    object_id=unit_id,
                                    units_dict=self.units_dict,
                                    last_visit_allowance=60 * 10,
                                    devide_last_parking_by_motohours=True)
            service.exec_report()
            service.analyze()

            ura_user = self.user.ura_user if self.user.ura_user_id else self.user
            jobs = Job.objects.filter(
                user=ura_user,
                date_begin__gte=local_to_utc_time(local_dt_from,
                                                  ura_user.timezone),
                date_end__lte=local_to_utc_time(local_dt_to,
                                                ura_user.timezone))
            jobs_cache = {int(j.unit_id): j for j in jobs}

            normal_ratio = 1 + (form.cleaned_data.get(
                'overstatement_param', DEFAULT_OVERSTATEMENT_NORMAL_PERCENTAGE)
                                / 100.0)

            unit_report_data = service.report_data.get(unit['name'])
            if not unit_report_data:
                return kwargs

            kwargs.update(heading_data=OrderedDict((
                ('Марка, модель', self.get_car_model(unit['name'])),
                ('Гос.номер', self.get_car_number(unit['name'])),
                ('VIN', self.get_car_vin(unit['name'])),
                ('Тип ТС', self.get_car_type(unit['name'])),
                ('Дата', date_format(form.cleaned_data['dt'], 'd.m.Y')))))

            job = jobs_cache.get(unit['id'])
            standard = None
            if job:
                standard = standards.get(int(job.route_id))

            for i, visit in enumerate(unit_report_data.geozones.target):
                try:
                    next_visit = unit_report_data.geozones.target[i + 1]
                except IndexError:
                    next_visit = None

                point_standard = None
                if standard:
                    point_standard = standard.get('points', {}).get(
                        visit.geozone_full, {})
                    if not point_standard:
                        point_standard = standard.get('points', {}).get(
                            visit.geozone, {})

                total_standart = parking_standard = None
                if point_standard:
                    total_standart = point_standard['total_time_standard'] * 60
                    parking_standard = point_standard[
                        'parking_time_standard'] * 60

                total_delta = (visit.dt_to - visit.dt_from).total_seconds()
                moving_delta = getattr(visit, 'trips_delta', .0)
                # переделал пока под расчет разницы между периодом нахождения и временем в
                # движении, так как в расчет стоянок иногда не принимаются концевые участки
                # длиной несколько минут
                # parking_delta = getattr(visit, 'parkings_delta', .0)
                parking_delta = max(.0, total_delta - moving_delta)

                motohours_delta = getattr(visit, 'motohours_delta', .0)
                idle_delta = getattr(visit, 'idle_delta', .0)
                off_delta = max(.0, total_delta - motohours_delta)
                angle_sensor_delta = getattr(visit, 'angle_sensor_delta', .0)
                refillings_volume = getattr(visit, 'refillings_volume', .0)
                discharges_volume = getattr(visit, 'discharges_volume', .0)

                overstatement_time = .0
                if total_standart is not None \
                        and total_delta / total_standart > normal_ratio:
                    overstatement_time += total_delta - total_standart

                elif parking_standard is not None \
                        and parking_delta / parking_standard > normal_ratio:
                    overstatement_time += parking_delta - parking_standard

                point_name = self.get_point_name(visit.geozone)
                if not point_name:
                    # если первая строка, и зона неизвестна, то это зона, где машина
                    # находилась до включения блока (допущение, предложенное заказчиком)
                    if i == 0 and next_visit:
                        point_name = self.get_point_name(next_visit.geozone)
                    else:
                        point_name = 'Неизвестная'

                over_3min_parkings_count = 0
                if point_name == 'Неизвестная':
                    over_3min_parkings_count = len([
                        True for x in getattr(visit, 'parkings', [])
                        if (x.dt_to - x.dt_from).total_seconds() > 3 * 60
                    ])

                report_row = {
                    'car_number': self.get_car_number(unit['name']),
                    'driver_fio': job.driver_fio
                    if job and job.driver_fio else 'Неизвестный',
                    'route_name': job.route_title
                    if job and job.route_title else 'Неизвестный маршрут',
                    'point_name': point_name,
                    'dt_from': visit.dt_from,
                    'dt_to': visit.dt_to,
                    'total_time': total_delta,
                    'moving_time': moving_delta,
                    'parking_time': parking_delta,
                    'idle_time': idle_delta,
                    'idle_off_time': off_delta,
                    'angle_sensor_time': angle_sensor_delta,
                    'over_3min_parkings_count': over_3min_parkings_count,
                    'odometer': self.get_odometer(unit, visit),
                    'fuel_level_delta': self.get_fuel_delta(unit, visit),
                    'refills_delta': refillings_volume,
                    'discharge_delta': discharges_volume,
                    'overstatement_mileage': .0,
                    'overstatement_time': overstatement_time,
                    'faults': self.render_faults(visit, i, unit_report_data)
                }
                report_data.append(report_row)

                if stats['dt_from_min'] is None:
                    stats['dt_from_min'] = visit.dt_from
                else:
                    stats['dt_from_min'] = min(stats['dt_from_min'],
                                               visit.dt_from)

                if stats['dt_to_max'] is None:
                    stats['dt_to_max'] = visit.dt_to
                else:
                    stats['dt_to_max'] = max(stats['dt_to_max'], visit.dt_to)

                stats['total_time'] += total_delta
                stats['moving_time'] += moving_delta
                stats['parking_time'] += parking_delta
                stats['idle_time'] += idle_delta
                stats['idle_off_time'] += off_delta
                stats['angle_sensor_time'] += angle_sensor_delta
                stats['over_3min_parkings_count'] += over_3min_parkings_count
                stats['odometer'] += self.get_odometer(unit, visit)
                stats['fuel_level_delta'] += self.get_fuel_delta(unit, visit)
                stats['refills_delta'] += refillings_volume
                stats['discharge_delta'] += discharges_volume
                stats['overstatement_mileage'] += .0
                stats['overstatement_time'] += overstatement_time

        return kwargs
Exemplo n.º 5
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(VchmIdleTimesView, self).write_xls_data(worksheet, context)

        worksheet.col(0).width = 5500
        worksheet.col(1).width = 3000
        worksheet.col(2).width = 5000
        worksheet.col(3).width = 5000
        worksheet.col(4).width = 6000
        worksheet.col(5).width = 7000
        worksheet.col(6).width = 3150
        worksheet.col(7).width = 3150
        worksheet.col(8).width = 3700
        worksheet.col(9).width = 3700
        worksheet.col(10).width = 3300
        worksheet.col(11).width = 7000
        worksheet.col(12).width = 3600

        headings = (
            'Водитель',
            'Гос №',
            'VIN',
            'Тип ТС',
            'Название маршрута',
            'Название геозоны',
            'Время\nнахождения,\nчч:мм',
            'Время\nостановки,\nчч:мм',
            'Время\nс выключенным\nдвигателем, чч:мм',
            'Время на\nхолостом ходу\n(без работы), чч:мм',
            'Время работы\nГПМ,\nчч:мм',
            'Место остановки\n(адрес или км трассы)',
            'Время простоя\nсверх норматива*,\nчч:мм'
        )

        # header
        worksheet.write_merge(
            1, 1, 0, self.xls_heading_merge, 'За период: %s - %s' % (
                date_format(context['cleaned_data']['dt_from'], 'd.m.Y'),
                date_format(context['cleaned_data']['dt_to'], 'd.m.Y')
            )
        )

        x = 2
        for y, heading in enumerate(headings):
            worksheet.write(
                x, y, heading, style=self.styles['border_center_style']
            )

        worksheet.row(x).height = 900

        for row in context['report_data']:
            x += 1
            worksheet.write(
                x, 0, row['driver_fio'],
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 1, row['car_number'],
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 2, row['car_vin'],
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 3, row['car_type'],
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 4, row['route_name'],
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 5, row['point_name'],
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 6, format_timedelta(row['total_time']),
                style=self.styles['border_right_style']
            )
            worksheet.write(
                x, 7, format_timedelta(row['parking_time']),
                style=self.styles['border_right_style']
            )
            worksheet.write(
                x, 8, format_timedelta(row['off_motor_time']),
                style=self.styles['border_right_style']
            )
            worksheet.write(
                x, 9, format_timedelta(row['idle_time']),
                style=self.styles['border_right_style']
            )
            worksheet.write(
                x, 10, format_timedelta(row['gpm_time']),
                style=self.styles['border_right_style']
            )
            worksheet.write(
                x, 11, self.render_parking(row['parkings']),
                style=self.styles['border_left_style']
            )
            worksheet.write(
                x, 12, format_timedelta(row['overstatement']),
                style=self.styles['border_right_style']
            )
            worksheet.row(x).height = 720

        x += 1
        worksheet.write_merge(
            x, x, 0, self.xls_heading_merge,
            '*В случае превышения фактического простоя над нормативным более чем на %s%%' %
            context['cleaned_data'].get(
                'overstatement_param', DEFAULT_OVERSTATEMENT_NORMAL_PERCENTAGE
            ),
            style=self.styles['left_center_style']
        )
        worksheet.row(x).height = 520

        return worksheet
Exemplo n.º 6
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(DischargeView,
                          self).write_xls_data(worksheet, context)
        worksheet.set_portrait(False)

        worksheet.col(0).width = 5000
        worksheet.col(1).width = 8000
        worksheet.col(2).width = 4000
        worksheet.col(3).width = 4500
        worksheet.col(4).width = 5000
        worksheet.col(5).width = 3000
        worksheet.col(6).width = 4000
        worksheet.col(7).width = 5500
        worksheet.col(8).width = 4000
        worksheet.col(9).width = 4000
        worksheet.col(10).width = 6000
        worksheet.col(11).width = 9000
        worksheet.col(12).width = 2200
        worksheet.col(13).width = 3000
        worksheet.col(14).width = 4000
        worksheet.col(15).width = 4000
        worksheet.col(16).width = 2700
        worksheet.col(17).width = 3200

        # header
        worksheet.write_merge(
            1, 1, 0, 17, 'За период: %s - %s' %
            (date_format(context['cleaned_data']['dt_from'], 'd.m.Y H:i'),
             date_format(context['cleaned_data']['dt_to'], 'd.m.Y H:i')))
        worksheet.write_merge(
            2,
            2,
            0,
            17,
            'Итого перерасход, л: %s' % floatformat(
                context.get('stats', {}).get('overspanding_total', 0) or 0,
                -2),
            style=self.styles['left_center_style'])
        worksheet.write_merge(
            3,
            3,
            0,
            17,
            'Итого слив, л: %s' % floatformat(
                context.get('stats', {}).get('discharge_total', 0) or 0, -2),
            style=self.styles['left_center_style'])
        worksheet.write_merge(
            4,
            4,
            0,
            17,
            'Зафиксировано случаев слива: %s' %
            context.get('stats', {}).get('overspanding_count', 0) or 0,
            style=self.styles['left_center_style'])
        worksheet.write_merge(5,
                              5,
                              0,
                              17,
                              'Список случаев перерасхода топлива на дату:',
                              style=self.styles['right_center_style'])

        # head
        worksheet.write_merge(6,
                              7,
                              0,
                              0,
                              ' Время',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              7,
                              1,
                              1,
                              ' Наименование',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              7,
                              2,
                              2,
                              ' Гос.номер ТС',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              7,
                              3,
                              3,
                              ' Тип ТС',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(
            6,
            7,
            4,
            4,
            ' Плановый график\nработы водителя\n(время с - время по)',
            style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              6,
                              5,
                              9,
                              ' Фактическая наработка за запрашиваемый период',
                              style=self.styles['border_center_style'])
        worksheet.write(7,
                        5,
                        ' Пробег, км',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        6,
                        ' Время работы\nна ХХ***,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        7,
                        ' Время работы\nдоп.оборудования****,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        8,
                        ' Время\nв движении,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        9,
                        ' Время работы\nдвигателя,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              7,
                              10,
                              10,
                              ' ФИО водителя',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              6,
                              11,
                              12,
                              ' Событие слив',
                              style=self.styles['border_center_style'])
        worksheet.write(7,
                        11,
                        ' Место/\nгеозона',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        12,
                        ' Объем',
                        style=self.styles['border_center_style'])
        worksheet.write_merge(
            6,
            6,
            13,
            16,
            ' Израсходовано топлива за запрашиваемый период, л',
            style=self.styles['border_center_style'])
        worksheet.write(7,
                        13,
                        ' По норме\nот пробега**',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        14,
                        ' По норме\nот времени\nработы на ХХ***',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        15,
                        ' По норме\nот работы доп.\nоборудования****',
                        style=self.styles['border_center_style'])
        worksheet.write(7,
                        16,
                        ' По факту\nс ДУТ',
                        style=self.styles['border_center_style'])
        worksheet.write_merge(6,
                              7,
                              17,
                              17,
                              ' Перерасход,\nл*',
                              style=self.styles['border_center_style'])

        for i in range(18):
            worksheet.write(8,
                            i,
                            str(i + 1),
                            style=self.styles['border_center_style'])

        for i in range(1, 9):
            worksheet.row(i).height = REPORT_ROW_HEIGHT
            worksheet.row(i).level = 1
        worksheet.row(7).height = 800

        # body
        i = 8
        for row in context['report_data'].values():
            for period in row['periods']:
                i += 1
                worksheet.row(i).level = 1

                worksheet.write(i,
                                0,
                                '%s - %s' %
                                (date(period['dt_from'], 'Y-m-d H:i:s'),
                                 date(period['dt_to'], 'Y-m-d H:i:s')),
                                style=self.styles['border_left_style'])

                worksheet.write(i,
                                1,
                                row['unit_name'],
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                2,
                                row['unit_number'],
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                3,
                                row['vehicle_type'],
                                style=self.styles['border_left_style'])

                job_period = ''
                if period.get('job'):
                    job_period = '%s - %s' % (date(
                        period['dt_from'],
                        'Y-m-d H:i:s'), date(period['dt_to'], 'Y-m-d H:i:s'))
                worksheet.write(i,
                                4,
                                job_period,
                                style=self.styles['border_left_style'])

                worksheet.write(i,
                                5,
                                floatformat(period['mileage'], 2) or '',
                                style=self.styles['border_right_style'])
                worksheet.write(
                    i,
                    6,
                    render_timedelta(period['idle_hours'], '0:00:00')
                    if period['idle_hours'] else '',
                    style=self.styles['border_left_style'])
                worksheet.write(
                    i,
                    7,
                    render_timedelta(period['extra_device_hours'], '0:00:00')
                    if period['extra_device_hours'] else '',
                    style=self.styles['border_left_style'])
                worksheet.write(
                    i,
                    8,
                    render_timedelta(period['move_hours'], '0:00:00')
                    if period['move_hours'] else '',
                    style=self.styles['border_left_style'])
                worksheet.write(
                    i,
                    9,
                    render_timedelta(period['moto_hours'], '0:00:00')
                    if period['moto_hours'] else '',
                    style=self.styles['border_left_style'])

                worksheet.write(
                    i,
                    10,
                    period['job'].driver_fio if period.get('job') else '',
                    style=self.styles['border_left_style'])
                worksheet.write(i,
                                11,
                                period['discharge']['place'],
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                12,
                                floatformat(period['discharge']['volume'], 2)
                                or '',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                13,
                                floatformat(period['fact_mileage'], 2) or '',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                14,
                                floatformat(period['fact_motohours'], 2) or '',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                15,
                                floatformat(period['fact_extra_device'], 2)
                                or '',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                16,
                                floatformat(period['fact_dut'], 2) or '',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                17,
                                floatformat(period['overspanding'], 2) or '',
                                style=self.styles['border_right_style'])
                worksheet.row(i).height = 520

                for detail in period['details']:
                    i += 1
                    worksheet.row(i).level = 2

                    worksheet.write(i,
                                    0,
                                    date(detail['dt'], 'Y-m-d H:i:s') or '',
                                    style=self.styles['border_left_style'])

                    worksheet.write(i,
                                    1,
                                    row['unit_name'],
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    2,
                                    row['unit_number'],
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    3,
                                    row['vehicle_type'],
                                    style=self.styles['border_left_style'])

                    job_period = ''
                    if period.get('job'):
                        job_period = '%s - %s' % (
                            date(period['dt_from'], 'Y-m-d H:i:s'),
                            date(period['dt_to'], 'Y-m-d H:i:s'))
                    worksheet.write(i,
                                    4,
                                    job_period,
                                    style=self.styles['border_left_style'])

                    worksheet.write(i,
                                    5,
                                    floatformat(period['mileage'], 2) or '',
                                    style=self.styles['border_right_style'])
                    worksheet.write(
                        i,
                        6,
                        render_timedelta(period['idle_hours'], '0:00:00')
                        if period['idle_hours'] else '',
                        style=self.styles['border_left_style'])
                    worksheet.write(
                        i,
                        7,
                        render_timedelta(period['extra_device_hours'],
                                         '0:00:00')
                        if period['extra_device_hours'] else '',
                        style=self.styles['border_left_style'])
                    worksheet.write(
                        i,
                        8,
                        render_timedelta(period['move_hours'], '0:00:00')
                        if period['move_hours'] else '',
                        style=self.styles['border_left_style'])
                    worksheet.write(
                        i,
                        9,
                        render_timedelta(period['moto_hours'], '0:00:00')
                        if period['moto_hours'] else '',
                        style=self.styles['border_left_style'])

                    worksheet.write(
                        i,
                        10,
                        period['job'].driver_fio if period.get('job') else '',
                        style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    11,
                                    detail['place'] or '',
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    12,
                                    floatformat(detail['volume'], 2) or '',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    13,
                                    '',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    14,
                                    '',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    15,
                                    '',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    16,
                                    '',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    17,
                                    '',
                                    style=self.styles['border_right_style'])
                    worksheet.row(i).height = 520

        worksheet.write_merge(
            i + 1,
            i + 1,
            0,
            17,
            '''* В случае превышения фактического расхода топлива на нормативы более чем на %s%%
** исходя из нормативов л/100км, с добавочным коэффициентом на работу оборудования
*** исходя из нормативов л/час при заведенном двигателе на холостых оборотах,
с добавочным коэффициентом на работу оборудования
''' % context['cleaned_data'].get('overspanding_percentage',
                                  DEFAULT_OVERSPANDING_NORMAL_PERCENTAGE),
            style=self.styles['left_center_style'])
        worksheet.row(i + 1).height = 520 * 4

        return worksheet
Exemplo n.º 7
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(VchmDrivingStyleView, self).write_xls_data(worksheet, context)

        self.styles = {
            'heading_style': xlwt.easyxf('font: bold 1, height 340'),
            'bottom_border_style': xlwt.easyxf('borders: bottom thin'),
            'left_center_style': xlwt.easyxf('align: vert centre, horiz left'),
            'right_center_style': xlwt.easyxf('align: wrap on, vert centre, horiz right'),
            'border_left_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz left'
            ),
            'border_left_style_bold': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz left; font: bold 1, height 200'
            ),
            'border_center_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz centre'
            ),
            'border_right_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz right'
            ),
            'border_right_style_bold': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: wrap on, vert centre, horiz right; font: bold 1, height 200'
            ),
            'border_right_0_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right'
            ),
            'border_right_25_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right'
            ),
            'border_right_50_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right'
            ),
            'border_right_75_style': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right'
            ),
            'border_right_0_style_bold': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right; font: bold 1, height 200'
            ),
            'border_right_25_style_bold': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right; font: bold 1, height 200'
            ),
            'border_right_50_style_bold': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right; font: bold 1, height 200'
            ),
            'border_right_75_style_bold': xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right; font: bold 1, height 200'
            )
        }

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['light_green']
        self.styles['border_right_0_style'].pattern = pattern
        self.styles['border_right_0_style_bold'].pattern = pattern

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['red']
        self.styles['border_right_25_style'].pattern = pattern
        self.styles['border_right_25_style_bold'].pattern = pattern

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['gold']
        self.styles['border_right_50_style'].pattern = pattern
        self.styles['border_right_50_style_bold'].pattern = pattern

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['light_yellow']
        self.styles['border_right_75_style'].pattern = pattern
        self.styles['border_right_75_style_bold'].pattern = pattern

        worksheet.set_portrait(False)
        widths = [
            5500, 2900, 2130, 4700, 4700, 4700, 4700, 4700, 4700, 2400, 2400, 2500, 2300, 2450,
            2300, 3000, 2750, 2750, 2330, 3000, 3000
        ]

        if self.is_total:
            widths.insert(0, 5500)

        for y, width in enumerate(widths):
            worksheet.col(y).width = width

        headings = [
            'Водитель',
            'Гос №',
            'Пробег,\nкм',
            'Превышение\nдопустимой\nскорости',
            'Превышение\nкритической\nскорости',
            'Движение\nбез ремня\nбезопасности',
            'Движение\nбез фар',
            'Движение\nс поднятой КМУ\n(кузовом)',
            'Резкие\nтормож.,\nшт. на\n100 км',
            'Резкие\nускор-я,\nшт. на\n100 км',
            'Резкие\nповороты,\nшт. на\n100 км',
            'Собл.\nскор.\nреж.',
            'Ремень\nбезопас.',
            'Фары',
            'Торможения',
            'Ускорения',
            'Повороты',
            'КМУ\n*(кузов)',
            'Взвеш.\nоценка\nкачества\nвождения',
            'Оценка\nкритических\nпараметров'
        ]

        if self.is_total:
            headings.insert(0, 'Компания')

        # header
        worksheet.write_merge(
            1, 1, 0, 17 if self.is_total else 16, 'За период: %s - %s' % (
                date_format(context['cleaned_data']['dt_from'], 'd.m.Y'),
                date_format(context['cleaned_data']['dt_to'], 'd.m.Y')
            )
        )

        x = 2
        for y, heading in enumerate(headings):
            worksheet.write(x, y, heading, style=self.styles['border_center_style'])

        worksheet.row(2).height = 900

        def write_row(x, group, row, total=False):
            y = 0
            boldness = '_bold' if total else ''

            if self.is_total:
                worksheet.write(
                    x, y, group['company_name'],
                    style=self.styles['border_left_style' + boldness]
                )
                y += 1

            worksheet.write(
                x, y, group['driver_fio'],
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, row['unit_number'],
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, row['total_mileage'],
                style=self.styles['border_right_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, self.render_measure(row, 'avg_overspeed'),
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, self.render_measure(row, 'critical_overspeed'),
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, self.render_measure(row, 'belt'),
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, self.render_measure(row, 'lights'),
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, self.render_measure(row, 'jib'),
                style=self.styles['border_left_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, floatcomma(row['per_100km_count']['brakings']['count'], -2),
                style=self.styles['border_right_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, floatcomma(row['per_100km_count']['accelerations']['count'], -2),
                style=self.styles['border_right_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, floatcomma(row['per_100km_count']['turns']['count'], -2),
                style=self.styles['border_right_style' + boldness]
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['overspeed']),
                style=self.render_background(row['rating']['overspeed'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['belt']),
                style=self.render_background(row['rating']['belt'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['lights']),
                style=self.render_background(row['rating']['lights'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['brakings']),
                style=self.render_background(row['rating']['brakings'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['accelerations']),
                style=self.render_background(row['rating']['accelerations'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['turns']),
                style=self.render_background(row['rating']['turns'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating']['jib']),
                style=self.render_background(row['rating']['jib'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating_total']['avg']),
                style=self.render_background(row['rating_total']['avg'], total=total)
            )
            y += 1
            worksheet.write(
                x, y, self.render_rating(row['rating_total']['critical_avg']),
                style=self.render_background(row['rating_total']['critical_avg'], total=total)
            )
            y += 1

        for group in context['report_data']:
            if len(group['rows']) > 1 \
                    and (
                        not group['driver_fio']
                        or group['driver_fio'].strip().lower() != 'неизвестный'
                    ):
                x += 1
                write_row(x, group, group['stats'], total=True)
                worksheet.row(x).level = 1
                # worksheet.row(x).collapse = 1

            for row in group['rows']:
                x += 1
                write_row(x, group, row)
                worksheet.row(x).level = 2 if len(group['rows']) > 1 else 1
                worksheet.row(x).collapse = 1 if len(group['rows']) > 1 else 0

        return worksheet
Exemplo n.º 8
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(FinishedJobsView,
                          self).write_xls_data(worksheet, context)

        for col in range(5):
            worksheet.col(col).width = 5000
        worksheet.col(1).width = 12000

        # header
        worksheet.write_merge(
            1, 1, 0, 4, 'За период: %s - %s' %
            (date_format(context['cleaned_data']['dt_from'], 'd.m.Y H:i'),
             date_format(context['cleaned_data']['dt_to'], 'd.m.Y H:i')))

        worksheet.write_merge(2,
                              2,
                              0,
                              1,
                              'ФИО ответственного за корректировку:',
                              style=self.styles['left_center_style'])

        worksheet.write_merge(2,
                              2,
                              2,
                              4,
                              '',
                              style=self.styles['bottom_border_style'])

        worksheet.write_merge(3,
                              3,
                              0,
                              4,
                              'Всего шаблонов заданий в базе ССМТ: %s' %
                              context['stats']['total'],
                              style=self.styles['right_center_style'])

        worksheet.write_merge(4,
                              4,
                              0,
                              4,
                              'Из них неактуальных заданий: %s' %
                              context['stats']['non_actual'],
                              style=self.styles['right_center_style'])

        # head
        worksheet.write_merge(5,
                              6,
                              0,
                              0,
                              ' № шаблона задания\nиз ССМТ',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              1,
                              1,
                              ' Наименование шаблона задания',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              5,
                              2,
                              3,
                              ' Кол-во путевых листов',
                              style=self.styles['border_center_style'])
        worksheet.write(6,
                        2,
                        ' Заявлено',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        3,
                        ' Исполнялось*',
                        style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              4,
                              4,
                              ' Актуальность, %',
                              style=self.styles['border_center_style'])

        for i in range(5):
            worksheet.write(7,
                            i,
                            str(i + 1),
                            style=self.styles['border_center_style'])

        for i in range(1, 8):
            worksheet.row(i).height = REPORT_ROW_HEIGHT

        # body
        i = 8
        for row in context['report_data'].values():
            worksheet.write(i,
                            0,
                            row['key'],
                            style=self.styles['border_left_style'])
            worksheet.write(i,
                            1,
                            row['name'],
                            style=self.styles['border_left_style'])
            worksheet.write(i,
                            2,
                            row['plan'],
                            style=self.styles['border_right_style'])
            worksheet.write(i,
                            3,
                            row['finished'],
                            style=self.styles['border_right_style'])
            worksheet.write(i,
                            4,
                            row['ratio'],
                            style=self.styles['border_right_style'])
            worksheet.row(i).height = REPORT_ROW_HEIGHT
            i += 1

        worksheet.write_merge(i + 1,
                              i + 1,
                              0,
                              4,
                              '''
* Исполненое задание - по факту работы транспорта в рамках одного путевого листа было
зафиксировано посещение заданных заданием геозон, хотя бы однократно.
Условие неактуальности шаблона задания: более %s%% неисполненных заданий
''' % context['cleaned_data'].get('non_actual_param', 20),
                              style=self.styles['left_center_style'])
        worksheet.row(i + 1).height = 520 * 2

        return worksheet
Exemplo n.º 9
0
    def write_xls_data(self, worksheet, context):
        worksheet = super(DrivingStyleView,
                          self).write_xls_data(worksheet, context)
        cleaned_data = context['cleaned_data']

        self.styles.update({
            'border_right_green_style':
            xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right'),
            'border_right_yellow_style':
            xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right'),
            'border_right_red_style':
            xlwt.easyxf(
                'borders: bottom thin, left thin, right thin, top thin;'
                'align: vert centre, horiz right')
        })

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['light_green']
        self.styles['border_right_green_style'].pattern = pattern

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['light_yellow']
        self.styles['border_right_yellow_style'].pattern = pattern

        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map['coral']
        self.styles['border_right_red_style'].pattern = pattern

        worksheet.set_portrait(False)
        worksheet.col(0).width = 5000
        worksheet.col(1).width = 6000
        worksheet.col(2).width = 8000
        worksheet.col(3).width = 4000
        worksheet.col(4).width = 4000
        worksheet.col(5).width = 3000
        worksheet.col(6).width = 3000
        worksheet.col(7).width = 3000
        worksheet.col(8).width = 3000
        worksheet.col(9).width = 3000
        worksheet.col(10).width = 3000
        worksheet.col(11).width = 3000
        worksheet.col(12).width = 3000
        worksheet.col(13).width = 3000
        worksheet.col(14).width = 3000
        worksheet.col(15).width = 3000
        worksheet.col(16).width = 3300
        worksheet.col(17).width = 3000

        # header
        worksheet.write_merge(
            1, 1, 0, 16, 'За период: %s - %s' %
            (date_format(context['cleaned_data']['dt_from'], 'd.m.Y H:i'),
             date_format(context['cleaned_data']['dt_to'], 'd.m.Y H:i')))

        worksheet.write_merge(2,
                              2,
                              0,
                              2,
                              'ФИО ответственного за разбор событий:',
                              style=self.styles['left_center_style'])
        worksheet.write_merge(2,
                              2,
                              3,
                              9,
                              '',
                              style=self.styles['bottom_border_style'])

        worksheet.write_merge(
            3,
            3,
            0,
            17,
            'Детализация нарушений ПДД и инструкции по эксплуатации техники:',
            style=self.styles['right_center_style'])

        # head
        worksheet.write_merge(4,
                              6,
                              0,
                              0,
                              ' Время',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(4,
                              6,
                              1,
                              1,
                              ' ФИО',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(4,
                              6,
                              2,
                              2,
                              ' Наименование ТС',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(4,
                              6,
                              3,
                              3,
                              ' Гос.номер ТС',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(
            4,
            6,
            4,
            4,
            ' Суммарное время\nв движении\nза период, чч:мм:сс',
            style=self.styles['border_center_style'])

        worksheet.write_merge(4,
                              4,
                              5,
                              12,
                              ' Нарушения',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              5,
                              5,
                              6,
                              ' Превышение скоростного\nрежима',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              5,
                              7,
                              8,
                              ' Выключенный свет фар\nпри движении',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(
            5,
            5,
            9,
            10,
            ' Непристегнутый ремень\nбезопасности при движении',
            style=self.styles['border_center_style'])
        worksheet.write_merge(
            5,
            5,
            11,
            12,
            ' Не транспортное\nположение оборудования\nпри движении',
            style=self.styles['border_center_style'])
        worksheet.write(6,
                        5,
                        ' Кол-во\nслучаев',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        6,
                        ' Часов\nнарушения,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        7,
                        ' Кол-во\nслучаев',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        8,
                        ' Часов\nнарушения,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        9,
                        ' Кол-во\nслучаев',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        10,
                        ' Часов\nнарушения,\nчч:мм:сс',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        11,
                        ' Кол-во\nслучаев',
                        style=self.styles['border_center_style'])
        worksheet.write(6,
                        12,
                        ' Часов\nнарушения,\nчч:мм:сс',
                        style=self.styles['border_center_style'])

        worksheet.write_merge(4,
                              4,
                              13,
                              16,
                              ' % нарушений',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              13,
                              13,
                              ' Скоростной\nрежим',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              14,
                              14,
                              ' Свет',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              15,
                              15,
                              ' Ремень',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(5,
                              6,
                              16,
                              16,
                              ' Доп.\nоборудование',
                              style=self.styles['border_center_style'])
        worksheet.write_merge(4,
                              6,
                              17,
                              17,
                              ' Оценка\nвождения, %',
                              style=self.styles['border_center_style'])

        for i in range(18):
            worksheet.write(7,
                            i,
                            str(i + 1),
                            style=self.styles['border_center_style'])

        for i in range(1, 8):
            worksheet.row(i).height = REPORT_ROW_HEIGHT

        worksheet.row(5).height = 680
        worksheet.row(6).height = 680

        # body
        i = 7
        for row in context['report_data'].values():
            for period in row['periods']:
                i += 1
                worksheet.row(i).level = 1
                # worksheet.row(i).collapse = 2

                worksheet.write(i,
                                0,
                                '%s -\n%s' %
                                (date(period['dt_from'], 'Y-m-d H:i:s'),
                                 date(period['dt_to'], 'Y-m-d H:i:s')),
                                style=self.styles['border_left_style'])

                worksheet.write(
                    i,
                    1,
                    period['job'].driver_fio if period.get('job') else '',
                    style=self.styles['border_left_style'])

                worksheet.write(i,
                                2,
                                row['unit_name'],
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                3,
                                row['unit_number'],
                                style=self.styles['border_left_style'])

                worksheet.write(i,
                                4,
                                render_timedelta(period['total_time']),
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                5,
                                period['facts']['speed']['count']
                                if period['facts']['speed']['count'] else '0',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                6,
                                render_timedelta(
                                    period['facts']['speed']['seconds'],
                                    '0:00:00'),
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                7,
                                period['facts']['lights']['count']
                                if period['facts']['lights']['count'] else '0',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                8,
                                render_timedelta(
                                    period['facts']['lights']['seconds'],
                                    '0:00:00'),
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                9,
                                period['facts']['belt']['count']
                                if period['facts']['belt']['count'] else '0',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                10,
                                render_timedelta(
                                    period['facts']['belt']['seconds'],
                                    '0:00:00'),
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                11,
                                period['facts']['devices']['count'] if
                                period['facts']['devices']['count'] else '0',
                                style=self.styles['border_right_style'])
                worksheet.write(i,
                                12,
                                render_timedelta(
                                    period['facts']['devices']['seconds'],
                                    '0:00:00'),
                                style=self.styles['border_left_style'])
                worksheet.write(i,
                                13,
                                floatcomma(period['percentage']['speed'], -2)
                                if period['percentage']['speed'] else '0',
                                style=self.render_background(
                                    period['percentage']['speed'],
                                    style=True,
                                    cleaned_data=cleaned_data))
                worksheet.write(i,
                                14,
                                floatcomma(period['percentage']['lights'], -2)
                                if period['percentage']['lights'] else '0',
                                style=self.render_background(
                                    period['percentage']['lights'],
                                    style=True,
                                    cleaned_data=cleaned_data))
                worksheet.write(i,
                                15,
                                floatcomma(period['percentage']['belt'], -2)
                                if period['percentage']['belt'] else '0',
                                style=self.render_background(
                                    period['percentage']['belt'],
                                    style=True,
                                    cleaned_data=cleaned_data))
                worksheet.write(i,
                                16,
                                floatcomma(period['percentage']['devices'], -2)
                                if period['percentage']['devices'] else '0',
                                style=self.render_background(
                                    period['percentage']['devices'],
                                    style=True,
                                    cleaned_data=cleaned_data))
                worksheet.write(i,
                                17,
                                floatcomma(period['rating'], -2),
                                style=self.styles['border_right_style'])

                worksheet.row(i).height = 520

                for detail in period['details']:
                    i += 1
                    worksheet.row(i).level = 2
                    # worksheet.row(i).collapse = 2

                    worksheet.write(i,
                                    0,
                                    '%s -\n%s' %
                                    (date(detail['dt_from'], 'Y-m-d H:i:s'),
                                     date(detail['dt_to'], 'Y-m-d H:i:s')),
                                    style=self.styles['border_left_style'])

                    worksheet.write(
                        i,
                        1,
                        period['job'].driver_fio if period.get('job') else '',
                        style=self.styles['border_left_style'])

                    worksheet.write(i,
                                    2,
                                    row['unit_name'],
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    3,
                                    row['unit_number'],
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    4,
                                    '',
                                    style=self.styles['border_left_style'])

                    worksheet.write(i,
                                    5,
                                    detail['speed']['count']
                                    if detail['speed']['count'] else '0',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    6,
                                    render_timedelta(
                                        detail['speed']['seconds'], '0:00:00'),
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    7,
                                    detail['lights']['count']
                                    if detail['lights']['count'] else '0',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    8,
                                    render_timedelta(
                                        detail['lights']['seconds'],
                                        '0:00:00'),
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    9,
                                    detail['belt']['count']
                                    if detail['belt']['count'] else '0',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    10,
                                    render_timedelta(detail['belt']['seconds'],
                                                     '0:00:00'),
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    11,
                                    detail['devices']['count']
                                    if detail['devices']['count'] else '0',
                                    style=self.styles['border_right_style'])
                    worksheet.write(i,
                                    12,
                                    render_timedelta(
                                        detail['devices']['seconds'],
                                        '0:00:00'),
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    13,
                                    '',
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    14,
                                    '',
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    15,
                                    '',
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    16,
                                    '',
                                    style=self.styles['border_left_style'])
                    worksheet.write(i,
                                    17,
                                    '',
                                    style=self.styles['border_left_style'])

                    worksheet.row(i).height = 520

        worksheet.write_merge(
            i + 1,
            i + 1,
            0,
            17,
            '''Условия форматирования ячеек:
до %s%% нарушений - норма
от %s%% до %s%% нарушений - требуется профилактическая беседа
от %s%% до 100%% нарушений - требуется профилактическая беседа с возможным лишением части премии
''' % (
                context['cleaned_data'].get('normal_rating', 10),
                context['cleaned_data'].get('normal_rating', 10),
                context['cleaned_data'].get('bad_rating', 30),
                context['cleaned_data'].get('bad_rating', 30),
            ),
            style=self.styles['left_center_style'])
        worksheet.row(i + 1).height = 520 * 4

        return worksheet