Esempio n. 1
0
def date_parameters_dictionary(request):
	if request.GET.get('start_date') and request.GET.get('end_date'):
		start_date, end_date = parse_start_and_end_date(request.GET.get('start_date'), request.GET.get('end_date'))
	else:
		start_date, end_date = get_month_timeframe()
	kind = request.GET.get("type")
	identifier = request.GET.get("id")
	customer = request.GET.get("customer")
	tool = request.GET.get("tool")
	dictionary = {
		'month_list': month_list(),
		'start_date': start_date,
		'end_date': end_date,
		'kind': kind,
		'identifier': identifier,
		'tab_url': get_url_for_other_tab(request),
		'customer': None,
		'tool': None,
		'billing_service': get_billing_service().get('available', False),
	}
	if request.user.is_staff:
		dictionary['users'] = User.objects.all()
		dictionary['tools'] = Tool.objects.all()
	try:
		if customer:
			dictionary['customer'] = User.objects.get(id=customer)
		if tool:
			dictionary['tool'] = Tool.objects.get(id=tool)
	except:
		pass
	return dictionary, start_date, end_date, kind, identifier
Esempio n. 2
0
def date_parameters_dictionary(request):
    if request.GET.get('start_date') and request.GET.get('end_date'):
        start_date, end_date = parse_start_and_end_date(
            request.GET.get('start_date'), request.GET.get('end_date'))
    else:
        start_date, end_date = get_month_timeframe()
    kind = request.GET.get("type")
    identifier = request.GET.get("id")
    dictionary = {
        'month_list':
        month_list(),
        'start_date':
        start_date,
        'end_date':
        end_date,
        'kind':
        kind,
        'identifier':
        identifier,
        'tab_url':
        get_url_for_other_tab(request),
        'billing_service':
        False if not hasattr(settings, 'BILLING_SERVICE')
        or not settings.BILLING_SERVICE['available'] else True,
    }
    return dictionary, start_date, end_date, kind, identifier
Esempio n. 3
0
def usage(request):
    first_of_the_month, last_of_the_month = get_month_timeframe(
        request.GET.get('timeframe'))
    dictionary = {
        'area_access':
        AreaAccessRecord.objects.filter(customer=request.user,
                                        end__gt=first_of_the_month,
                                        end__lte=last_of_the_month,
                                        active_flag=True),
        'consumables':
        ConsumableWithdraw.objects.filter(customer=request.user,
                                          date__gt=first_of_the_month,
                                          date__lte=last_of_the_month,
                                          active_flag=True),
        'missed_reservations':
        Reservation.objects.filter(user=request.user,
                                   missed=True,
                                   end__gt=first_of_the_month,
                                   end__lte=last_of_the_month),
        'staff_charges':
        StaffCharge.objects.filter(customer=request.user,
                                   end__gt=first_of_the_month,
                                   end__lte=last_of_the_month,
                                   active_flag=True),
        'training_sessions':
        TrainingSession.objects.filter(trainee=request.user,
                                       date__gt=first_of_the_month,
                                       date__lte=last_of_the_month),
        'usage_events':
        UsageEvent.objects.filter(user=request.user,
                                  end__gt=first_of_the_month,
                                  end__lte=last_of_the_month,
                                  active_flag=True),
        'month_list':
        month_list(),
        'timeframe':
        request.GET.get('timeframe') or first_of_the_month.strftime('%B, %Y'),
        'billing_active_by_default':
        True if hasattr(settings, 'BILLING_SERVICE')
        and settings.BILLING_SERVICE['available'] else False
    }
    dictionary['no_charges'] = not (
        dictionary['area_access'] or dictionary['consumables']
        or dictionary['missed_reservations'] or dictionary['staff_charges']
        or dictionary['training_sessions'] or dictionary['usage_events'])
    return render(request, 'usage/usage.html', dictionary)
Esempio n. 4
0
def date_parameters_dictionary(request):
	if request.GET.get('start_date') and request.GET.get('end_date'):
		start_date, end_date = parse_start_and_end_date(request.GET.get('start_date'), request.GET.get('end_date'))
	else:
		start_date, end_date = get_month_timeframe()
	kind = request.GET.get("type")
	identifier = request.GET.get("id")
	dictionary = {
		'month_list': month_list(),
		'start_date': start_date,
		'end_date': end_date,
		'kind': kind,
		'identifier': identifier,
		'tab_url': get_url_for_other_tab(request),
		'billing_service': get_billing_service().get('available', False),
	}
	return dictionary, start_date, end_date, kind, identifier
Esempio n. 5
0
def date_parameters_dictionary(request):
    dates = False
    if request.GET.get('start_date') and request.GET.get('end_date'):
        start_date, end_date = parse_start_and_end_date(
            request.GET.get('start_date'), request.GET.get('end_date'))
        dates = True
    else:
        start_date, end_date = get_month_timeframe(
            request.GET.get('timeframe'))
    dictionary = {
        'month_list': month_list(),
        'timeframe': request.GET.get('timeframe')
        or start_date.strftime('%B, %Y'),
        'start_date': start_date,
        'end_date': end_date,
        'dates': dates,
        'tab_url': get_url_for_other_tab(request)
    }
    return dictionary, start_date, end_date
Esempio n. 6
0
def nanofab_usage(request):
    first_of_the_month, last_of_the_month = get_month_timeframe(
        request.GET.get('timeframe'))
    dictionary = {
        'area_access':
        AreaAccessRecord.objects.filter(customer=request.user,
                                        end__gt=first_of_the_month,
                                        end__lte=last_of_the_month),
        'consumables':
        ConsumableWithdraw.objects.filter(customer=request.user,
                                          date__gt=first_of_the_month,
                                          date__lte=last_of_the_month),
        'missed_reservations':
        Reservation.objects.filter(user=request.user,
                                   missed=True,
                                   end__gt=first_of_the_month,
                                   end__lte=last_of_the_month),
        'staff_charges':
        StaffCharge.objects.filter(customer=request.user,
                                   end__gt=first_of_the_month,
                                   end__lte=last_of_the_month),
        'training_sessions':
        TrainingSession.objects.filter(trainee=request.user,
                                       date__gt=first_of_the_month,
                                       date__lte=last_of_the_month),
        'usage_events':
        UsageEvent.objects.filter(user=request.user,
                                  end__gt=first_of_the_month,
                                  end__lte=last_of_the_month),
        'month_list':
        month_list(),
        'timeframe':
        request.GET.get('timeframe') or first_of_the_month.strftime('%B, %Y'),
    }
    dictionary['no_charges'] = not (
        dictionary['area_access'] or dictionary['consumables']
        or dictionary['missed_reservations'] or dictionary['staff_charges']
        or dictionary['training_sessions'] or dictionary['usage_events'])
    return render(request, 'nanofab_usage.html', dictionary)
Esempio n. 7
0
def remote_work(request):
	first_of_the_month, last_of_the_month = get_month_timeframe(request.GET.get('date'))
	operator = request.GET.get('operator')
	if operator:
		if operator == "all staff":
			operator = None
		else:
			operator = get_object_or_404(User, id=operator)
	else:
		operator = request.user
	usage_events = UsageEvent.objects.filter(operator__is_staff=True, start__gte=first_of_the_month, start__lte=last_of_the_month).exclude(operator=F('user'))
	staff_charges = StaffCharge.objects.filter(start__gte=first_of_the_month, start__lte=last_of_the_month)
	if operator:
		usage_events = usage_events.exclude(~Q(operator_id=operator.id))
		staff_charges = staff_charges.exclude(~Q(staff_member_id=operator.id))
	dictionary = {
		'usage': usage_events,
		'staff_charges': staff_charges,
		'staff_list': User.objects.filter(is_staff=True),
		'month_list': month_list(),
		'selected_staff': operator.id if operator else "all staff",
		'selected_month': request.GET.get('date'),
	}
	return render(request, 'remote_work.html', dictionary)
Esempio n. 8
0
def billing_information(request, timeframe=''):
    dictionary = {}
    if not hasattr(
            settings,
            'BILLING_SERVICE') or not settings.BILLING_SERVICE['available']:
        return HttpResponse()
    try:
        cost_activity_url = settings.BILLING_SERVICE['cost_activity_url']
        project_lead_url = settings.BILLING_SERVICE['project_lead_url']
        keyword_arguments = settings.BILLING_SERVICE['keyword_arguments']

        first_of_the_month, last_of_the_month = get_month_timeframe(timeframe)
        formatted_projects = ','.join(
            map(
                str,
                set(request.user.active_projects().values_list(
                    'project_number', 'name', 'simba_cost_center',
                    flat=True))))
        cost_activity_params = {
            'created_date_gte': f"'{first_of_the_month.strftime('%m/%d/%Y')}'",
            'created_date_lt': f"'{last_of_the_month.strftime('%m/%d/%Y')}'",
            'application_names': f"'{formatted_projects}'",
            '$format': 'json'
        }
        cost_activity_response = get(cost_activity_url,
                                     params=cost_activity_params,
                                     **keyword_arguments)
        cost_activity_data = cost_activity_response.json()['d']

        latest_pis_params = {'$format': 'json'}
        latest_pis_response = get(project_lead_url,
                                  params=latest_pis_params,
                                  **keyword_arguments)
        latest_pis_data = latest_pis_response.json()['d']

        project_totals = {}
        application_totals = {}
        user_pi_applications = list()
        # Construct a tree of account, application, project, and member total spending
        cost_activities_tree = {}
        for activity in cost_activity_data:
            project_totals.setdefault(activity['project_id'], 0)
            application_totals.setdefault(activity['application_id'], 0)
            account_key = (activity['account_id'], activity['account_name'])
            application_key = (activity['application_id'],
                               activity['application_name'])
            project_key = (activity['project_id'], activity['project_name'])
            user_key = (activity['member_id'],
                        User.objects.get(id=activity['member_id']))
            user_is_pi = is_user_pi(
                request.user,
                next(
                    (x for x in latest_pis_data
                     if x['application_name'] == activity['application_name']),
                    None))
            if user_is_pi:
                user_pi_applications.append(activity['application_id'])
            if user_is_pi or str(request.user.id) == activity['member_id']:
                cost_activities_tree.setdefault(
                    (activity['account_id'], activity['account_name']), {})
                cost_activities_tree[account_key].setdefault(
                    application_key, {})
                cost_activities_tree[account_key][application_key].setdefault(
                    project_key, {})
                cost_activities_tree[account_key][application_key][
                    project_key].setdefault(user_key, 0)
                cost = -activity['cost'] if activity[
                    'activity_type'] == 'refund_activity' else activity['cost']
                cost_activities_tree[account_key][application_key][
                    project_key][user_key] = cost_activities_tree[account_key][
                        application_key][project_key][user_key] + cost
                project_totals[activity['project_id']] = project_totals[
                    activity['project_id']] + cost
                application_totals[
                    activity['application_id']] = application_totals[
                        activity['application_id']] + cost
        dictionary['spending'] = {
            'activities': cost_activities_tree,
            'project_totals': project_totals,
            'application_totals': application_totals,
            'user_pi_applications': user_pi_applications
        } if cost_activities_tree else {}
        return render(request, 'usage/billing.html', dictionary)
    except Exception as e:
        return HttpResponse(str(e))
Esempio n. 9
0
def email_daily_passdown(request):
    # Make list of all events that belong in the daily passdown email"
    #New shutdowns, New problems, Overnight access, Access and usage in the last day, Upcoming reservations, Upcoming configuration requests,
    #Low stock items, Ongoing issues, Safety reports, lab usage numbers
    passdown = {}
    now = timezone.now()
    yesterday = now - timedelta(hours=24)
    tomorrow = now + timedelta(hours=24)
    #Daily information
    passdown['new_shutdowns'] = Task.objects.filter(
        creation_time__gt=yesterday, force_shutdown=True)
    passdown['new_problems'] = Task.objects.filter(creation_time__gt=yesterday,
                                                   force_shutdown=False)
    passdown['area_accesses'] = AreaAccessRecord.objects.filter(
        start__gt=yesterday)
    passdown['tool_enables'] = UsageEvent.objects.filter(start__gt=yesterday)
    overnight_access = AreaAccessRecord.objects.filter(start__gt=now -
                                                       timedelta(hours=12),
                                                       start__lte=now)
    overnight_usage = []
    for access in overnight_access:
        if access.end == None:
            end = now
        else:
            end = access.end
        usage = UsageEvent.objects.filter(start__gt=access.start,
                                          start__lte=end,
                                          user=access.customer)
        tools = Tool.objects.filter(
            id__in=usage.values_list('tool', flat=True))
        overnight_usage.append({
            'user': access.customer,
            'area': access.area,
            'start': access.start,
            'end': access.end,
            'tools': tools
        })
    passdown['overnight_usage'] = overnight_usage
    passdown['upcoming_reservations'] = Reservation.objects.filter(
        start__gt=now,
        start__lte=tomorrow,
        cancelled=False,
        missed=False,
        shortened=False).order_by('start')
    tools = Tool.objects.exclude(configuration__isnull=True).exclude(
        configuration__exclude_from_configuration_agenda=True).values_list(
            'id', flat=True)
    reservations = Reservation.objects.filter(
        start__gt=now,
        start__lt=tomorrow,
        tool__id__in=tools,
        self_configuration=False,
        cancelled=False,
        missed=False,
        shortened=False).exclude(additional_information='').order_by('start')
    passdown['configuration_requests'] = Tool.objects.filter(
        id__in=reservations.values_list('tool', flat=True))
    stock = StockroomItem.objects.all()
    low_stock = []
    low_consumable = []
    for i in stock:
        if i.quantity <= i.reminder_threshold:
            low_stock.append(i)
    consumable = Consumable.objects.all()
    for i in consumable:
        if i.quantity <= i.reminder_threshold:
            low_consumable.append(i)
    passdown['low_stock'] = low_stock
    passdown['low_consumable'] = low_consumable

    #Ongoing issues
    passdown['all_shutdowns'] = Task.objects.filter(force_shutdown=True,
                                                    cancelled=False,
                                                    resolved=False)
    passdown['all_problems'] = Task.objects.filter(force_shutdown=False,
                                                   cancelled=False,
                                                   resolved=False)
    passdown['safety_issues'] = SafetyIssue.objects.filter(resolved=False)

    # Statistics
    u = AreaAccessRecord.objects.filter(
        start__gt=now - timedelta(days=90),
        start__lt=now).exclude(customer__is_staff=True)
    areadf = DataFrame.from_records(u.values('start', 'area__name',
                                             'customer'))
    startdate = [x.date() for x in areadf.loc[:, ('start')]]
    areadf['start_date'] = startdate
    areacount = dict(
        areadf.groupby(['start_date', 'area__name'
                        ]).nunique()['customer'].unstack().sum().astype(int))
    area_unique_count = []
    for i in range(0, len(areacount)):
        area_unique_count.append({
            'area': list(areacount.keys())[i],
            'entrances': list(areacount.values())[i]
        })
    passdown['area_access_stats'] = area_unique_count
    #startmonth, endmonth = get_month_timeframe((now.date()+relativedelta.relativedelta(months=-1)).strftime('%m/%d/%Y'))
    billingstart, billingend = get_month_timeframe(
        (now.date() +
         relativedelta.relativedelta(months=-1)).strftime('%m/%d/%Y'))
    #billing_summary = get_billing_data(billingstart, billingend)
    billingdf = DataFrame(get_billing_data(billingstart, billingend))
    billingnumeric = to_numeric(billingdf['billable_days'], errors='coerce')
    billingdf['billable_days'] = billingnumeric
    billing_dict = dict(billingdf.groupby('user_type').sum()['billable_days'])
    billing_summary = []
    for i in range(0, len(billing_dict)):
        billing_summary.append({
            'type': list(billing_dict.keys())[i],
            'billable_days': list(billing_dict.values())[i]
        })
    passdown['billing_summary'] = billing_summary

    # main_cr_usage=len(cr)
    # usage_data['main_cr'] = main_cr_usage
    # pack = AreaAccessRecord.objects.filter(start__gt=now-timedelta(days=90),start__lt=now, area=8, customer.is_staff=False)
    # pack_usage = len(pack)
    # usage_data['packaging'] = pack_usage
    # soft = AreaAccessRecord.objects.filter(start__gt=now-timedelta(days=90),start__lt=now, area__id__exact=3, customer.is_staff=False)
    # smp_usage = len(soft)
    # usage_data['smp'] = smp_usage

    user_office_email = get_customization('user_office_email_address')
    passdown_email = get_customization('daily_passdown_email_address')

    message = get_media_file_contents('daily_passdown_email.html')
    if message:
        subject = "PRISM Cleanroom Daily Passdown"
        rendered_message = Template(message).render(
            Context({'passdown': passdown}))
        send_mail(subject,
                  '',
                  user_office_email, [passdown_email],
                  html_message=rendered_message)
    return HttpResponse()
Esempio n. 10
0
def remote_work(request):
    if request.GET.get("start_date") and request.GET.get("end_date"):
        start_date, end_date = parse_start_and_end_date(
            request.GET.get("start_date"), request.GET.get("end_date"))
    else:
        start_date, end_date = get_month_timeframe()

    operator = request.GET.get("operator")
    if operator:
        if operator == "all staff":
            operator = None
        else:
            operator = get_object_or_404(User, id=operator)
    else:
        operator = request.user

    project = request.GET.get("project")
    if project and project != "all projects":
        project = get_object_or_404(Project, id=project)
    else:
        project = None
    usage_events = UsageEvent.objects.filter(
        operator__is_staff=True, start__gte=start_date,
        start__lte=end_date).exclude(operator=F("user"))
    staff_charges = StaffCharge.objects.filter(start__gte=start_date,
                                               start__lte=end_date)
    if operator:
        usage_events = usage_events.exclude(~Q(operator_id=operator.id))
        staff_charges = staff_charges.exclude(~Q(staff_member_id=operator.id))
    if project:
        usage_events = usage_events.filter(project=project)
        staff_charges = staff_charges.filter(project=project)

    csv_export = bool(request.GET.get("csv", False))
    if csv_export:
        table_result = BasicDisplayTable()
        TYPE, ID, ITEM, STAFF, CUSTOMER, PROJECT, START, END = (
            "item_type",
            "item_id",
            "item",
            "staff_member",
            "customer",
            "project",
            "start_date",
            "end_date",
        )
        table_result.headers = [
            (TYPE, "Item Type"),
            (ID, "Item Id"),
            (ITEM, "Item"),
            (STAFF, "Staff"),
            (CUSTOMER, "Customer"),
            (PROJECT, "Project"),
            (START, "Start"),
            (END, "End"),
        ]
        for usage in usage_events:
            table_result.add_row({
                ID:
                usage.tool.id,
                TYPE:
                "Tool Usage",
                ITEM:
                usage.tool,
                STAFF:
                usage.operator,
                CUSTOMER:
                usage.user,
                START:
                usage.start.astimezone(
                    timezone.get_current_timezone()).strftime(
                        "%m/%d/%Y @ %I:%M %p"),
                END:
                usage.end.astimezone(timezone.get_current_timezone()).strftime(
                    "%m/%d/%Y @ %I:%M %p") if usage.end else "",
                PROJECT:
                usage.project,
            })
        for staff_charge in staff_charges:
            for access in staff_charge.areaaccessrecord_set.all():
                table_result.add_row({
                    ID:
                    access.area.id,
                    TYPE:
                    "Area Access",
                    ITEM:
                    access.area,
                    STAFF:
                    staff_charge.staff_member,
                    CUSTOMER:
                    access.customer,
                    START:
                    access.start.astimezone(
                        timezone.get_current_timezone()).strftime(
                            "%m/%d/%Y @ %I:%M %p"),
                    END:
                    access.end.astimezone(timezone.get_current_timezone()).
                    strftime("%m/%d/%Y @ %I:%M %p") if access.end else "",
                    PROJECT:
                    access.project,
                })
            table_result.add_row({
                ID:
                staff_charge.id,
                TYPE:
                "Staff Charge",
                ITEM:
                "Staff Charge",
                STAFF:
                staff_charge.staff_member,
                CUSTOMER:
                staff_charge.customer,
                START:
                staff_charge.start.astimezone(
                    timezone.get_current_timezone()).strftime(
                        "%m/%d/%Y @ %I:%M %p"),
                END:
                staff_charge.end.astimezone(timezone.get_current_timezone()).
                strftime("%m/%d/%Y @ %I:%M %p") if staff_charge.end else "",
                PROJECT:
                staff_charge.project,
            })
        response = table_result.to_csv()
        filename = f"remote_work_{start_date.strftime('%m_%d_%Y')}_to_{end_date.strftime('%m_%d_%Y')}.csv"
        response["Content-Disposition"] = f'attachment; filename="{filename}"'
        return response
    dictionary = {
        "usage": usage_events,
        "staff_charges": staff_charges,
        "staff_list": User.objects.filter(is_staff=True),
        "project_list": Project.objects.filter(active=True),
        "start_date": start_date,
        "end_date": end_date,
        "month_list": month_list(),
        "selected_staff": operator.id if operator else "all staff",
        "selected_project": project.id if project else "all projects",
    }
    return render(request, "remote_work.html", dictionary)