def collate_excel_weekreport_data(day):
        r_iface = ReportInterface('')
        w_iface = WeekInterface('')
        project = day.project

        report_data = {}
        _, totals_prod, totals_time, totals_rcvr, totals_hse = r_iface.calc_totals(
            day)
        report_data['df'] = r_iface.create_proj_df()
        days, weeks = w_iface.collate_weekdata(day, report_data['df'])

        report_data['report_date'] = day.production_date.strftime('%#d %b %Y')
        report_data['month_days'] = day.production_date.day
        if project.start_report:
            report_data['proj_days'] = (day.production_date -
                                        project.planned_start_date).days + 1

        else:
            report_data['proj_days'] = 1

        # CSR author and comment
        if _week := day.project.weeklies.filter(
                week_report_date=day.production_date):
            week = _week.first()
            try:
                author = week.author.name
            except AttributeError:
                author = ''
            report_data['author_table'] = {'CSR': author}
            report_data['comment_table'] = {'Comments': week.csr_week_comment}
示例#2
0
def mpr_excel_report(request, daily_id):
    rprt_iface = ReportInterface('')

    try:
        # get daily report from id
        day = Daily.objects.get(id=daily_id)
        project = day.project
        day, _ = rprt_iface.load_report_db(project, day.production_date)

    except Daily.DoesNotExist:
        return redirect('daily_page', 0)

    mpr_report = ExcelMprReport(day)

    # note FileResponse will close the file/ buffer - do not use with block
    f_excel = mpr_report.create_mprreport()

    return FileResponse(f_excel, as_attachment=True, filename='mpr_report.xlsx')
示例#3
0
def csr_excel_report(request, daily_id):

    r_iface = ReportInterface('')

    try:
        # get daily report from id
        day = Daily.objects.get(id=daily_id)
        project = day.project
        day, _ = r_iface.load_report_db(project, day.production_date)

    except Daily.DoesNotExist:
        return redirect('daily_page', 0)

    csr_report = ExcelDayReport(day, settings.MEDIA_ROOT, settings.STATIC_ROOT)

    #TODO save excel: improve file handling, name sheet, set to A4, fit to page print
    # note FileResponse will close the file/ buffer - do not use with block
    f_excel = csr_report.create_dailyreport()

    return FileResponse(f_excel,
                        as_attachment=True,
                        filename='csr_report.xlsx')
示例#4
0
    def collate_excel_dailyreport_data(day):
        r_iface = ReportInterface('')
        (
            _,
            totals_production,
            totals_time,
            totals_receiver,
            totals_hse,
        ) = r_iface.calc_totals(day)
        # no need to call create_daily_graphs as this has been done in DailyView

        project = day.project

        report_data = {}
        report_data['report_date'] = day.production_date.strftime('%#d %b %Y')

        if project.start_report:
            ops_days = (day.production_date - project.start_report).days + 1

        else:
            ops_days = NO_DATE_STR

        if project.planned_start_date:
            proj_start_str = project.planned_start_date.strftime('%#d %b %Y')

        else:
            proj_start_str = NO_DATE_STR

        report_data['project_table'] = {
            'Project': project.project_name,
            'Project VPs': project.planned_vp,
            f'Area (km{SS_2})': project.planned_area,
            'Acq. start': proj_start_str,
            'Crew': project.crew_name,
        }
        report_data['daily_table'] = {
            'Oper Day': ops_days,
            'Total VPs': totals_production['day_total'],
            'Target VPs': totals_production['day_ctm'],
            '% Target': totals_production['day_appctm'],
            'Recording Hrs': totals_time['day_rec_time'],
            'Ops Hrs': totals_time['day_ops_time'],
            'Standby Hrs': totals_time['day_standby'],
            'Downtime Hrs': totals_time['day_downtime'],
            'Skip VPs': totals_production['day_skips'],
        }
        report_data['receiver_table'] = {
            'Layout': totals_receiver['day_layout'],
            'Pickup': totals_receiver['day_pickup'],
            'Node download': totals_receiver['day_node_download'],
            'Node failure': totals_receiver['day_node_failure'],
            'HyperQ QC': totals_receiver['day_qc_field']
        }
        # cst table XGO first then CSR
        xgo_staff = {
            f'{p.department}_{i:02}': p.name
            for i, p in enumerate(
                day.staff.filter(
                    department__startswith='X').order_by('department', 'name'))
        }
        csr_staff = {
            f'{p.department}_{i:02}': p.name
            for i, p in enumerate(
                day.staff.filter(department__startswith='C').order_by('name'))
        }
        report_data['csr_table'] = {**xgo_staff, **csr_staff}

        # proj_stats
        proj_total = totals_production['proj_total']
        proj_skips = totals_production['proj_skips']
        if project.planned_vp > 0:
            proj_complete = (proj_total + proj_skips) / project.planned_vp

        else:
            proj_complete = 0

        # block_stats and project area
        report_data['block_stats_table'] = {}
        (report_data['block_stats_table']['Block'],
         report_data['block_stats_table'][f'Area (km{SS_2})'],
         report_data['block_stats_table']['% Complete'],
         report_data['block_stats_table']['Est. Complete'],
         _proj_area_) = r_iface.get_block_totals(day)

        report_data['proj_stats_table'] = {
            'Recorded VPs':
            proj_total,
            f'Area (km{SS_2})':
            _proj_area_,
            'Skip VPs':
            proj_skips,
            '% Complete':
            proj_complete,
            'Est. Complete':
            r_iface.calc_est_completion_date(day, AVG_PERIOD,
                                             project.planned_vp,
                                             proj_complete),
        }

        report_data['hse_stats_table'] = {
            'LTI': totals_hse['day_lti'],
            'RWC': totals_hse['day_rwc'],
            'MTC': totals_hse['day_mtc'],
            'FAC': totals_hse['day_fac'],
            'Incident/ NM': totals_hse['day_incident_nm'],
            'LSR': totals_hse['day_lsr_violations'],
            'Observations': totals_hse['day_stop'],
            'Drills': totals_hse['day_drills'],
            'Insp./ Audits': totals_hse['day_audits'],
            'Medevac': totals_hse['day_medevac'],
            'Headcount': totals_hse['day_headcount'],
            'Exposure': totals_hse['day_exposure_hours'],
        }
        report_data['resources_table'] = {
            'Active sources': totals_production['day_avg_sources'],
            'QC/ TS teams': totals_receiver['day_qc_teams'],
            'FC teams': totals_receiver['day_fc_teams'],
            'BC teams': totals_receiver['day_bc_teams'],
        }
        report_data['csr_comment_table'] = {'Comment': day.csr_comment}

        return report_data
示例#5
0
class WeekInterface:

    rprt_iface = ReportInterface('')

    def __init__(self, media_dir):
        self.media_dir = media_dir

    @staticmethod
    def get_week_values(day):
        if not day:
            return {}

        start_week = day.production_date - timedelta(WEEKDAYS - 1)
        end_week = day.production_date

        try:
            week = day.project.weeklies.get(
                week_report_date=day.production_date)
            initial_week_form = {
                'week_start_date': start_week,
                'week_report_date': week.week_report_date,
                'proj_name': week.project.project_name,
                'proj_vps': day.project.planned_vp,
                'proj_area': day.project.planned_area,
                'proj_start': day.project.planned_start_date,
                'proj_crew': day.project.crew_name,
                'author': [week.author.id],
                'csr_week_comment': week.csr_week_comment,
            }

        except (AttributeError, ObjectDoesNotExist):
            initial_week_form = {
                'week_start_date': start_week,
                'week_report_date': end_week,
                'proj_name': day.project.project_name,
                'proj_vps': day.project.planned_vp,
                'proj_area': day.project.planned_area,
                'proj_start': day.project.planned_start_date,
                'proj_crew': day.project.crew_name,
                'author': [],
                'csr_week_comment': '',
            }

        return initial_week_form

    @staticmethod
    def update_week_report(day, week_comment, author_id):
        try:
            week = Weekly.objects.get(project=day.project,
                                      week_report_date=day.production_date)

        except Weekly.DoesNotExist:
            week = Weekly.objects.create(project=day.project,
                                         week_report_date=day.production_date)

        week.csr_week_comment = week_comment
        try:
            week.author = Person.objects.get(id=author_id)

        except (ValueError, Person.DoesNotExist):
            pass

        week.save()

    @staticmethod
    def select_week_report(day, choice=WeekSelection.none):
        week_report_dates = sorted(
            [w.week_report_date for w in day.project.weeklies.all()])
        if choice == WeekSelection.none or not week_report_dates:
            return day

        elif choice == WeekSelection.first:
            return day.project.dailies.get(
                production_date=week_report_dates[0]).id

        elif choice == WeekSelection.previous:
            for wd in reversed(week_report_dates):
                if wd < day.production_date:
                    return day.project.dailies.get(production_date=wd)

                else:
                    continue

            return day

        elif choice == WeekSelection.next:
            for wd in week_report_dates:
                if wd > day.production_date:
                    return day.project.dailies.get(production_date=wd)

                else:
                    continue

            return day

        elif choice == WeekSelection.last:
            return day.project.dailies.get(
                production_date=week_report_dates[-1])

    @staticmethod
    def delete_week_report(day):
        try:
            week = Weekly.objects.get(project=day.project,
                                      week_report_date=day.production_date)

        except Weekly.DoesNotExist:
            return

        week.delete()

    @timed(logger, print_log=True)
    def collate_weekdata(self, report_day, proj_df):
        times_schema = time_breakdown_schema + ['ops', 'standby', 'downtime']

        # get the daily production figures for the days in the week
        days = {}
        start_date = report_day.production_date - timedelta(days=WEEKDAYS - 1)
        for day_in_week in reversed(range(0, WEEKDAYS)):
            report_date = start_date + timedelta(days=day_in_week)
            days[day_in_week] = {}
            days[day_in_week]['date'] = report_date
            day_df = proj_df[proj_df['date'].between(
                report_date.strftime('%Y-%m-%d'),
                report_date.strftime('%Y-%m-%d'))]
            for time_cat in times_schema:
                days[day_in_week][time_cat] = day_df[time_cat].sum()

            for rcvr_cat in receiver_prod_schema:
                days[day_in_week][rcvr_cat] = day_df[rcvr_cat].sum()

            days[day_in_week]['total_sp'] = day_df['total_sp'].sum()
            days[day_in_week]['skips'] = day_df['skips'].sum()

            try:
                days[day_in_week]['vp_hour'] = (round(
                    days[day_in_week]['total_sp'] /
                    days[day_in_week]['rec_hours']))
            except (ValueError, KeyError, ZeroDivisionError):
                days[day_in_week]['vp_hour'] = np.nan

        # get the weekly production figures for the 6 weeks before
        weeks = {}
        start_date = report_day.production_date - timedelta(days=(WEEKS - 1) *
                                                            WEEKDAYS)
        for week_no in range(0, WEEKS):
            week_end_date = start_date + timedelta(days=WEEKDAYS * week_no)
            week_start_date = week_end_date - timedelta(days=(WEEKDAYS - 1))
            weeks[week_no] = {}
            week_df = proj_df[proj_df['date'].between(
                week_start_date.strftime('%Y-%m-%d'),
                week_end_date.strftime('%Y-%m-%d'))]
            weeks[week_no]['dates'] = (week_start_date, week_end_date)

            for time_cat in times_schema:
                weeks[week_no][time_cat] = week_df[time_cat].sum()

            for rcvr_cat in receiver_prod_schema[0:7]:
                weeks[week_no][rcvr_cat] = week_df[rcvr_cat].sum()

            for rcvr_cat in receiver_prod_schema[7:11]:
                weeks[week_no][rcvr_cat] = week_df[rcvr_cat].mean()

            weeks[week_no]['total_sp'] = week_df['total_sp'].sum()
            weeks[week_no]['skips'] = week_df['skips'].sum()

            try:
                weeks[week_no]['vp_hour'] = (round(
                    weeks[week_no]['total_sp'] / weeks[week_no]['rec_hours']))
            except (ValueError, KeyError, ZeroDivisionError):
                weeks[week_no]['vp_hour'] = np.nan

        return days, weeks
示例#6
0
class WeeklyView(View):

    form_week = WeeklyForm
    template_weekly_page = 'daily_report/weekly_page.html'
    r_iface = ReportInterface(settings.MEDIA_ROOT)
    w_iface = WeekInterface(settings.MEDIA_ROOT)
    arrow_symbols = {'right': RIGHT_ARROW, 'left': LEFT_ARROW}

    def get(self, request, daily_id):
        try:
            # get daily report from id
            day = Daily.objects.get(id=daily_id)

        except Daily.DoesNotExist:
            return redirect('daily_page', daily_id)

        week_initial = self.w_iface.get_week_values(day)
        (_, totals_prod, totals_time, totals_rcvr,
         totals_hse) = self.r_iface.calc_totals(day)
        days, weeks = self.w_iface.collate_weekdata(
            day, self.r_iface.create_proj_df())

        proj_complete = (
            (totals_prod['proj_total'] + totals_prod['proj_skips']) /
            planned_ if (planned_ := day.project.planned_vp) > 0 else 0)
        est_complete = self.r_iface.calc_est_completion_date(
            day, AVG_PERIOD, day.project.planned_vp, proj_complete)

        *_, totals_prod['proj_area'] = self.r_iface.get_block_totals(day)
        totals_prod['proj_complete'] = proj_complete
        totals_prod['est_complete'] = est_complete

        context = {
            'daily_id': daily_id,
            'SS_2': SS_2,
            'arrow_symbols': self.arrow_symbols,
            'totals_prod': totals_prod,
            'totals_rcvr': totals_rcvr,
            'totals_time': totals_time,
            'totals_hse': totals_hse,
            'days': days,
            'weeks': weeks,
            'form_week': self.form_week(initial=week_initial),
        }

        return render(request, self.template_weekly_page, context)

    def post(self, request, daily_id):
        day = None
        try:
            day = Daily.objects.get(id=daily_id)

        except day.DoesNotExist:
            redirect('daily_page', 0)

        if request.method == 'POST':
            ip_address = get_client_ip(request)
            user = request.user
            button_pressed = request.POST.get('button_pressed', '')

            if button_pressed == 'save_csr_weekly':
                week_form = self.form_week(request.POST)
                if week_form.is_valid():
                    week_comment = week_form.cleaned_data.get(
                        'csr_week_comment', '')
                    author = week_form.cleaned_data.get('author', '')
                    self.w_iface.update_week_report(day, week_comment, author)
                    logger.info(
                        f'user {user.username} (ip: {ip_address}) made comment '
                        f'in week report {day.production_date} '
                        f'for {day.project.project_name}')

            elif button_pressed == 'delete':
                self.w_iface.delete_week_report(day)
                logger.info(f'user {user.username} (ip: {ip_address}) deleted '
                            f'week report {day.production_date} '
                            f'for {day.project.project_name}')

            elif button_pressed == self.arrow_symbols['right']:
                day = self.w_iface.select_week_report(
                    day, choice=WeekSelection.next)

            elif button_pressed == self.arrow_symbols['left']:
                day = self.w_iface.select_week_report(
                    day, choice=WeekSelection.previous)

        if (new_daily_id := day.id) and new_daily_id != daily_id:
            daily_id = new_daily_id
            request.session['selected_project'] = day.project.project_name
            request.session['report_date'] = date_to_string(
                day.production_date)

        return redirect('weekly_page', daily_id)
示例#7
0
class ProjectView(View):

    form_project_control = ProjectControlForm
    form_block_control = BlockControlForm
    form_sourcetype_control = SourceTypeControlForm
    form_receivertype_control = ReceiverTypeControlForm
    form_project = ProjectForm
    form_block = BlockForm
    form_sourcetype = SourceTypeForm
    form_receivertype = ReceiverTypeForm
    template_project_page = 'daily_report/project_page.html'
    ri = ReportInterface('')
    pi = ProjectInterface()
    new_project_name = ''

    def get(self, request):
        selected_project = request.session.get('selected_project', '')
        selected_block = request.session.get('selected_block', '')
        selected_sourcetype = request.session.get('selected_sourcetype', '')
        selected_receivertype = request.session.get('selected_receivertype',
                                                    '')

        selected_project, project, initial_project_form = (
            self.pi.get_project_values(selected_project))
        daily_id, report_date = self.ri.get_latest_report_id(selected_project)
        request.session['report_date'] = date_to_string(report_date)

        selected_block, block, initial_block_form = (self.pi.get_block_values(
            project, selected_block))

        selected_sourcetype, _, initial_sourcetype_form = (
            self.pi.get_sourcetype_values(project, selected_sourcetype))

        selected_receivertype, _, initial_receivertype_form = (
            self.pi.get_receivertype_values(project, selected_receivertype))

        form_project = self.form_project(initial=initial_project_form)
        form_block = self.form_block(initial=initial_block_form,
                                     instance=block)
        form_sourcetype = self.form_sourcetype(initial=initial_sourcetype_form)
        form_receivertype = self.form_receivertype(
            initial=initial_receivertype_form)

        form_project_control = self.form_project_control(
            initial={
                'projects': selected_project,
                'new_project_name': '',
                'daily_id': daily_id,
            })
        form_block_control = self.form_block_control(project=project,
                                                     initial={
                                                         'blocks':
                                                         selected_block,
                                                         'new_block_name': '',
                                                     })
        form_sourcetype_control = self.form_sourcetype_control(
            project=project,
            initial={
                'sourcetypes': selected_sourcetype,
                'new_sourcetype_name': '',
            })
        form_receivertype_control = self.form_receivertype_control(
            project=project,
            initial={
                'receivertypes': selected_receivertype,
                'new_receivertype_name': '',
            })

        context = {
            'form_project': form_project,
            'form_block': form_block,
            'form_sourcetype': form_sourcetype,
            'form_receivertype': form_receivertype,
            'form_project_control': form_project_control,
            'form_block_control': form_block_control,
            'form_sourcetype_control': form_sourcetype_control,
            'form_receivertype_control': form_receivertype_control,
        }

        return render(request, self.template_project_page, context)

    def post(self, request):
        form_project_control = self.form_project_control(request.POST)
        if form_project_control.is_valid():
            # get project controls
            self.selected_project = form_project_control.cleaned_data.get(
                'projects', '')
            self.new_project_name = form_project_control.cleaned_data.get(
                'new_project_name', '')[:NAME_LENGTH]
            self.button_pressed = form_project_control.cleaned_data.get(
                'button_pressed', '')

            #get project object
            _, self.project, _ = self.pi.get_project_values(
                self.selected_project)

            # Get the pdf_workorder_file from request and store in project
            try:
                self.pi.store_workorder(self.project,
                                        request.FILES['pdf_workorder_file'])

            except MultiValueDictKeyError:
                pass

            # get block controls
            form_block_control = self.form_block_control(request.POST,
                                                         project=self.project)
            if form_block_control.is_valid():
                self.selected_block = form_block_control.cleaned_data.get(
                    'blocks', '')
                self.new_block_name = form_block_control.cleaned_data.get(
                    'new_block_name', '')[:NAME_LENGTH]

            else:
                self.selected_block = ''
                self.new_block_name = ''

            # get sourcetype controls
            form_sourcetype_control = self.form_sourcetype_control(
                request.POST, project=self.project)
            if form_sourcetype_control.is_valid():
                self.selected_sourcetype = form_sourcetype_control.cleaned_data.get(
                    'sourcetypes', '')
                self.new_sourcetype_name = form_sourcetype_control.cleaned_data.get(
                    'new_sourcetype_name', '')[:NAME_LENGTH]

            else:
                self.selected_sourcetype = ''
                self.new_sourcetype_name = ''

            # get receivertype controls
            form_receivertype_control = self.form_receivertype_control(
                request.POST, project=self.project)
            if form_receivertype_control.is_valid():
                self.selected_receivertype = form_receivertype_control.cleaned_data.get(
                    'receivertypes', '')
                self.new_receivertype_name = form_receivertype_control.cleaned_data.get(
                    'new_receivertype_name', '')[:NAME_LENGTH]

            else:
                self.selected_receivertype = ''
                self.new_receivertype_name = ''

            # get block and source, receiver type objects
            _, self.block, _ = self.pi.get_block_values(
                self.project, self.selected_block)
            _, self.sourcetype, _ = self.pi.get_sourcetype_values(
                self.project, self.selected_sourcetype)
            _, self.receivertype, _ = self.pi.get_receivertype_values(
                self.project, self.selected_receivertype)

            # action for project submit button
            if self.button_pressed == 'submit_project':
                form_project = ProjectForm(request.POST, instance=self.project)

                if form_project.is_valid():
                    form_project.save(commit=True)
                    # in case the name of the project has been changed
                    self.selected_project = form_project.cleaned_data.get(
                        'project_name')
                    # disable button pressed
                    self.button_pressed = ''

            # action for block submit button
            if self.button_pressed == 'submit_block':
                form_block = BlockForm(request.POST, instance=self.block)

                if form_block.is_valid():
                    form_block.save(commit=True)
                    # in case the name of the block has been changed
                    self.selected_block = form_block.cleaned_data.get(
                        'block_name')[:NAME_LENGTH]
                    self.button_pressed = ''

            # action for sourcetype submit button
            if self.button_pressed == 'submit_sourcetype':
                form_sourcetype = SourceTypeForm(request.POST,
                                                 instance=self.sourcetype)

                if form_sourcetype.is_valid():
                    form_sourcetype.save(commit=True)
                    # in case the name of the sourcetype has been changed
                    self.selected_sourcetype = form_sourcetype.cleaned_data.get(
                        'sourcetype_name')[:NAME_LENGTH]
                    self.button_pressed = ''

            # action for receivertype submit button
            if self.button_pressed == 'submit_receivertype':
                form_receivertype = ReceiverTypeForm(
                    request.POST, instance=self.receivertype)

                if form_receivertype.is_valid():
                    form_receivertype.save(commit=True)
                    # in case the name of the receivertype has been changed
                    self.selected_receivertype = form_receivertype.cleaned_data.get(
                        'receivertype_name')[:NAME_LENGTH]
                    self.button_pressed = ''

            # actions for new or delete buttons are pressed
            if self.button_pressed in ['new_project', 'delete_project']:
                self.create_or_delete_project()

            if self.button_pressed in ['new_block', 'delete_block']:
                self.create_or_delete_block()

            if self.button_pressed in ['new_sourcetype', 'delete_sourcetype']:
                self.create_or_delete_sourcetype()

            if self.button_pressed in [
                    'new_receivertype', 'delete_receivertype'
            ]:
                self.create_or_delete_receivertype()

            #get latest values after changes
            self.selected_project, _, initial_project_form = (
                self.pi.get_project_values(self.selected_project))
            daily_id, report_date = self.ri.get_latest_report_id(
                self.selected_project)
            request.session['report_date'] = date_to_string(report_date)

            self.selected_block, _, initial_block_form = (
                self.pi.get_block_values(self.project, self.selected_block))

            self.selected_sourcetype, _, initial_sourcetype_form = (
                self.pi.get_sourcetype_values(self.project,
                                              self.selected_sourcetype))

            self.selected_receivertype, _, initial_receivertype_form = (
                self.pi.get_receivertype_values(self.project,
                                                self.selected_receivertype))

            form_project = self.form_project(initial=initial_project_form)
            form_block = self.form_block(initial=initial_block_form,
                                         instance=self.block)
            form_sourcetype = self.form_sourcetype(
                initial=initial_sourcetype_form)
            form_receivertype = self.form_receivertype(
                initial=initial_receivertype_form)

            form_project_control = self.form_project_control(
                initial={
                    'projects': self.selected_project,
                    'new_project_name': '',
                    'daily_id': daily_id,
                })
            form_block_control = self.form_block_control(
                project=self.project,
                initial={
                    'blocks': self.selected_block,
                    'new_block_name': '',
                })
            form_sourcetype_control = self.form_sourcetype_control(
                project=self.project,
                initial={
                    'sourcetypes': self.selected_sourcetype,
                    'new_sourcetype_name': '',
                })
            form_receivertype_control = self.form_receivertype_control(
                project=self.project,
                initial={
                    'receivertypes': self.selected_receivertype,
                    'new_receivertype_name': '',
                })

            request.session['selected_project'] = self.selected_project
            request.session['selected_block'] = self.selected_block
            request.session['selected_sourcetype'] = self.selected_sourcetype
            request.session[
                'selected_receivertype'] = self.selected_receivertype

            logger.info(
                f'user {request.user.username} (ip: {get_client_ip(request)}) '
                f'made changes in project: {self.selected_project}')

        else:
            form_project = self.form_project()
            form_block = self.form_block()
            form_sourcetype = self.form_sourcetype()
            form_project_control = self.form_project_control(
                initial={
                    'projects': '',
                    'new_project_name': '',
                    'daily_id': 0,
                })
            form_block_control = self.form_block_control(initial={
                'blocks': '',
                'new_block_name': '',
            })
            form_sourcetype_control = self.form_sourcetype_control(
                initial={
                    'sourcetypes': '',
                    'new_sourcetype_name': '',
                })
            form_receivertype_control = self.form_receivertype_control(
                initial={
                    'receivertypes': '',
                    'new_receivertype_name': '',
                })

        context = {
            'form_project': form_project,
            'form_block': form_block,
            'form_sourcetype': form_sourcetype,
            'form_receivertype': form_receivertype,
            'form_project_control': form_project_control,
            'form_block_control': form_block_control,
            'form_sourcetype_control': form_sourcetype_control,
            'form_receivertype_control': form_receivertype_control,
        }

        return render(request, self.template_project_page, context)

    def create_or_delete_project(self):
        if self.button_pressed == 'new_project':
            self.project, self.selected_project = self.pi.create_project(
                self.new_project_name)

        elif self.button_pressed == 'delete_project':
            self.project, self.selected_project = self.pi.delete_project(
                self.project)

        self.new_project_name = ''
        self.button_pressed = ''

    def create_or_delete_block(self):
        if self.button_pressed == 'new_block':
            self.block, self.selected_block = self.pi.create_block(
                self.project, self.new_block_name)

        elif self.button_pressed == 'delete_block':
            self.block, self.selected_bklock = self.pi.delete_block(self.block)

        self.new_block_name = ''
        self.button_pressed = ''

    def create_or_delete_sourcetype(self):
        if self.button_pressed == 'new_sourcetype':
            self.sourcetype, self.selected_sourcetype = self.pi.create_sourcetype(
                self.project, self.new_sourcetype_name)

        elif self.button_pressed == 'delete_sourcetype':
            self.sourcetype, self.selected_sourcetype = self.pi.delete_sourcetype(
                self.sourcetype)

        self.new_sourcetype_name = ''
        self.button_pressed = ''

    def create_or_delete_receivertype(self):
        if self.button_pressed == 'new_receivertype':
            self.receivertype, self.selected_receivertype = self.pi.create_receivertype(
                self.project, self.new_receivertype_name)

        elif self.button_pressed == 'delete_receivertype':
            self.receivertype, self.selected_receivertype = self.pi.delete_receivertype(
                self.receivertype)

        self.new_receivertype_name = ''
        self.button_pressed = ''
示例#8
0
class ServiceView(View):

    template_services_page = 'daily_report/services_page.html'
    ri = ReportInterface('')

    def get(self, request, project_name):
        services = Service.objects.filter(
            project__project_name=project_name).order_by('service_contract')
        daily_id, report_date = self.ri.get_latest_report_id(project_name)
        try:
            year = report_date.year
            month = report_date.month

        except AttributeError:
            year = None
            month = None

        context = {
            'services': services,
            'project_name': project_name,
            'daily_id': daily_id,
            'year': year,
            'month': month,
        }
        return render(request, self.template_services_page, context)

    def post(self, request, project_name):
        new_service_name = request.POST.get('new_service_name', '')[:NAME_LENGTH]
        new_service_description = request.POST.get('new_service_description', '')[:DESCR_LENGTH]  #pylint: disable=line-too-long
        edit_service = request.POST.get('edit_service', '')[:NAME_LENGTH]
        new_task_name = request.POST.get('new_task_name', '')[:NAME_LENGTH]
        new_task_description = request.POST.get('new_task_description', '')[:DESCR_LENGTH]
        new_task_unit = request.POST.get('new_task_unit', '')[:NAME_LENGTH]
        edit_task = request.POST.get('edit_task', '')[:NAME_LENGTH]
        service_name = request.POST.get('service_name', '')[:NAME_LENGTH]
        delete_service = request.POST.get('delete_service', '')[:NAME_LENGTH]
        delete_task = request.POST.get('delete_task', '')
        if delete_task:
            service_name, delete_task = [v.strip()[:NAME_LENGTH]
                                         for v in delete_task.split(',')]
        project = Project.objects.get(project_name=project_name)
        daily_id, report_date = self.ri.get_latest_report_id(project_name)
        try:
            year = report_date.year
            month = report_date.month

        except AttributeError:
            year = None
            month = None

        self.create_edit_delete_service(
            project, new_service_name, new_service_description,
            edit_service, delete_service,
        )
        self.create_edit_delete_task(
            project, service_name, new_task_name, new_task_description, new_task_unit,
            edit_task, delete_task,
        )
        services = Service.objects.filter(project=project).order_by('service_contract')
        context = {
            'services': services,
            'project_name': project_name,
            'daily_id': daily_id,
            'year': year,
            'month': month,
        }

        logger.info(
            f'user {request.user.username} (ip: {get_client_ip(request)}) '
            f'made changes in services for {project_name}'
        )

        return render(request, self.template_services_page, context)

    @staticmethod
    def create_edit_delete_service(
            project, service_name, service_description, edit_service, delete_service,
        ):

        if not (delete_service or edit_service or service_name):
            return

        # delete service
        if delete_service:
            try:
                service = Service.objects.get(
                    project=project, service_contract=delete_service)
                service.delete()
                return

            except Service.DoesNotExist:
                return

         # edit an existing service
        if edit_service and service_name:
            try:
                service = Service.objects.get(
                    project=project, service_contract=edit_service)
                service.service_contract = service_name
                service.description = service_description
                service.save()
                return

            except (Service.DoesNotExist, IntegrityError):
                return

        # create a new service
        if not edit_service and service_name:
            try:
                Service.objects.create(
                    project=project,
                    service_contract=service_name,
                    description=service_description,
                )

            except IntegrityError:
                pass

        return

    @staticmethod
    def create_edit_delete_task(
            project, service_name, task_name, task_description, task_unit,
            edit_task, delete_task,
        ):

        if not (delete_task or edit_task or task_name):
            return

        try:
            service = Service.objects.get(
                project=project,
                service_contract=service_name,
            )

        except Service.DoesNotExist:
            return

        # delete task
        if delete_task:
            try:
                task = ServiceTask.objects.get(
                    service=service, task_name=delete_task)
                task.delete()
                return

            except ServiceTask.DoesNotExist:
                return

        # edit an existing task
        if edit_task and task_name:
            try:
                task = ServiceTask.objects.get(
                    service=service, task_name=edit_task)
                task.task_name = task_name
                task.task_description = task_description
                task.task_unit = task_unit
                task.save()
                return

            except (ServiceTask.DoesNotExist, IntegrityError):
                return

        # create a new task
        if not edit_task:
            try:
                ServiceTask.objects.create(
                    service=service,
                    task_name=task_name,
                    task_description=task_description,
                    task_unit=task_unit,
                )

            except IntegrityError:
                pass

        return
示例#9
0
class DailyView(View):

    form_daily = DailyForm
    form_project_control = ProjectControlForm
    template_daily_page = 'daily_report/daily_page.html'
    rprt_iface = ReportInterface(settings.MEDIA_ROOT)
    arrow_symbols = {'right': RIGHT_ARROW, 'left': LEFT_ARROW}

    def get(self, request, daily_id):
        report_date_str = ''
        project_name = ''

        try:
            # get daily report from id
            day = Daily.objects.get(id=daily_id)
            day, day_initial = self.rprt_iface.load_report_db(
                day.project, day.production_date)

        except Daily.DoesNotExist:
            # get daily report from session project_name and report_date
            project_name = request.session.get('selected_project', '')
            project = self.rprt_iface.get_project(project_name)
            report_date = string_to_date(request.session.get(
                'report_date', ''))
            day, day_initial = self.rprt_iface.load_report_db(
                project, report_date)

        if day:
            form_project_control = self.form_project_control(
                initial={
                    'projects': day.project.project_name,
                    'report_date': day.production_date.strftime('%#d %b %Y'),
                })
            (_, totals_production, totals_time, totals_receiver,
             totals_hse) = self.rprt_iface.calc_totals(day)

            self.rprt_iface.create_daily_graphs()
            context = {
                'form_daily': self.form_daily(initial=day_initial),
                'totals_production': totals_production,
                'totals_receiver': totals_receiver,
                'totals_time': totals_time,
                'totals_hse': totals_hse,
                'arrow_symbols': self.arrow_symbols,
                'form_project_control': form_project_control,
            }

        else:
            # if there is a date format for display in template
            if report_date:
                report_date_str = report_date.strftime('%#d %b %Y')

            form_project_control = self.form_project_control(
                initial={
                    'projects': project_name,
                    'report_date': report_date_str,
                })

            context = {
                'arrow_symbols': self.arrow_symbols,
                'form_project_control': form_project_control,
            }

        return render(request, self.template_daily_page, context)

    def post(self, request, daily_id):
        day = None
        if request.method == 'POST':
            ip_address = get_client_ip(request)
            user = request.user
            form_project_control = self.form_project_control(request.POST)

            if form_project_control.is_valid():
                new_project_name = form_project_control.cleaned_data.get(
                    'projects', '')
                if new_project_name:
                    project_name = new_project_name
                else:
                    project_name = request.session.get('selected_project', '')

            project = self.rprt_iface.get_project(project_name)

            button_pressed = request.POST.get('button_pressed', '')
            new_report_date = request.POST.get('report_date', '')
            if new_report_date:
                report_date = new_report_date

            else:
                report_date = request.session.get('report_date', '')

            report_date = string_to_date(report_date)

            if button_pressed == self.arrow_symbols['right']:
                report_date += timedelta(days=1)

            elif button_pressed == self.arrow_symbols['left']:
                report_date -= timedelta(days=1)

            csr_comment = ''
            staff_selected = []
            if button_pressed == 'save_csr':
                daily_form = self.form_daily(request.POST)
                if daily_form.is_valid():
                    csr_comment = daily_form.cleaned_data.get(
                        'csr_comment', '')
                    staff_selected = daily_form.cleaned_data.get('staff')

            try:
                # Get the report_file from request and store it in the database
                report_file = request.FILES['daily_report_file']
                report_date = self.rprt_iface.save_report_file(
                    project, report_file)
                if report_date:
                    logger.info(f'user {user.username} (ip: {ip_address}) '
                                f'uploaded {report_file} for {report_date} '
                                f'for {project.project_name}')
            except MultiValueDictKeyError:
                pass

            day, _ = self.rprt_iface.load_report_db(project, report_date)
            if day and button_pressed == 'delete':
                logger.info(f'user {user.username} (ip: {ip_address}) '
                            f'deleted report {day.production_date} '
                            f'for {day.project.project_name}')
                day.delete()
                day = None
                report_date = string_to_date('1900-01-01')

            else:
                if day and button_pressed == "save_csr":
                    day.csr_comment = csr_comment
                    day.staff.set(staff_selected)
                    day.save()
                    logger.info(
                        f'user {user.username} (ip: {ip_address}) made comment '
                        f'in report {day.production_date} '
                        f'for {day.project.project_name}')

            request.session['selected_project'] = project_name
            request.session['report_date'] = date_to_string(report_date)

        day_id = day.id if day else 0
        return redirect('daily_page', day_id)
示例#10
0
class SourcetypeView(View):

    form_daily = DailyForm
    form_project_control = ProjectControlForm
    template_sourcetype_page = 'daily_report/sourcetype_page.html'
    rprt_iface = ReportInterface(settings.MEDIA_ROOT)
    arrow_symbols = {'right': RIGHT_ARROW, 'left': LEFT_ARROW}

    def get(self, request, daily_id):
        day = None
        try:
            day = Daily.objects.get(id=daily_id)
            day, day_initial = self.rprt_iface.load_report_db(
                day.project, day.production_date)

        except Daily.DoesNotExist:
            pass

        if day:
            form_project_control = self.form_project_control(
                initial={
                    'projects': day.project.project_name,
                    'report_date': day.production_date.strftime('%#d %b %Y'),
                })
            (
                totals_production_by_type,
                totals_production,
                _,
                _,
                _,
            ) = self.rprt_iface.calc_totals(day)

            context = {
                'daily_id': daily_id,
                'form_daily': self.form_daily(initial=day_initial),
                'form_project_control': form_project_control,
                'totals_production_by_type': totals_production_by_type,
                'totals_production': totals_production,
                'arrow_symbols': self.arrow_symbols,
            }

        else:
            project_name = request.session.get('selected_project', '')
            report_date = string_to_date(request.session.get(
                'report_date', ''))
            if report_date:
                report_date_str = report_date.strftime('%#d %b %Y')
            else:
                report_date_str = ''

            form_project_control = self.form_project_control(
                initial={
                    'projects': project_name,
                    'report_date': report_date_str,
                })
            context = {
                'daily_id': daily_id,
                'form_project_control': form_project_control,
                'arrow_symbols': self.arrow_symbols,
            }

        return render(request, self.template_sourcetype_page, context)

    def post(self, request, daily_id):
        day = None
        if request.method == 'POST':
            report_date = request.session.get('report_date', '')
            project_name = request.session.get('selected_project', '')
            project = self.rprt_iface.get_project(project_name)

            button_pressed = request.POST.get('button_pressed', '')

            new_report_date = request.POST.get('report_date', '')
            if new_report_date:
                report_date = new_report_date

            report_date = string_to_date(report_date)

            if button_pressed == self.arrow_symbols['right']:
                report_date += timedelta(days=1)

            elif button_pressed == self.arrow_symbols['left']:
                report_date -= timedelta(days=1)

            request.session['report_date'] = date_to_string(report_date)

            day, _ = self.rprt_iface.load_report_db(project, report_date)

        day_id = day.id if day else 0
        return redirect('sourcetype_page', day_id)