from django.shortcuts import render, redirect, get_object_or_404 from django.core.paginator import Paginator from django.contrib import messages from core.models import Report from core.forms import ReportForm from core.utils import ConfigurableCRUDView, queryFromMaster from .filters import ReportFilter from .forms import ExportOptionsForm from pprint import pprint from .gen_report import gen_xlsx from django.core.files.base import File from pathlib import Path from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponseBadRequest import json from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from legacy.models import Data def index(request): reports = Report.objects.all() report_filter = ReportFilter(request.GET, queryset=reports) # Paginate the filtered queryset paginator = Paginator(report_filter.qs, 10) # Show 10 reports per page page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'filter': report_filter, 'page_obj': page_obj, } return render(request, 'report/index.html', context) def report_create_view(request): if request.method == "POST": form = ReportForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Report created successfully!") return redirect("report:report_index") # Adjust with your report list view name else: form = ReportForm() return render(request, "report/create.html", {"form": form}) class ReportCRUDView(ConfigurableCRUDView): model = Report list_template_name = 'legacy/datacrud_list.html' detail_template_name = 'legacy/datacrud_detail.html' form_template_name = 'report/report_form.html' confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html' filterset_class = ReportFilter page_title = "Reports" # URL name mappings list_url_name = 'report:report-list' create_url_name = 'report:report-create' update_url_name = 'report:report-update' delete_url_name = 'report:report-delete' config_fields = ["name", "file", "created_by", "created_at"] config_field_orders = ["id", "name", "created_by"] # config_readonly_fields = ["lot_no"] # config_edit_fields = ["lot_no", "code"] ordering = ["-created_at", "-id",] def convert_sheet_data(sheet_data): """ Convert sheet_data to the required form with prefixed keys. :param sheet_data: Dictionary with sheet names as keys and their data as values. :return: Dictionary in the required key-value format. """ converted_data = {} for sheet_name, data in sheet_data.items(): for key, value in data.items(): # Prefix each key with the sheet name converted_key = f"{sheet_name}.{key}" converted_data[converted_key] = value return converted_data def generate_hardness_out_values(lot_no): """ Generate a dictionary of placeholder values for a given lot_no. :param lot_no: The lot number to query data for. :return: A dictionary with placeholders (e.g., v1_1, v1_2, ...) as keys and their respective values. """ # Query the Data model for records matching the given lot_no records = Data.objects.filter(lot_no=lot_no).order_by('row_no') print(f"records {lot_no} = {records.values()}") # Initialize an empty dictionary to store placeholder values placeholders = {} # Iterate over the records to populate placeholder values for record_idx, record in enumerate(records, start=1): placeholders[f'v{record_idx}_1'] = record.p1 # Checkpoint 1 value placeholders[f'v{record_idx}_2'] = record.p2 # Checkpoint 2 value placeholders[f'v{record_idx}_3'] = record.p3 # Checkpoint 3 value placeholders[f'v{record_idx}_4'] = record.avg # Average value placeholders[f'v{record_idx}_5'] = record.rgrade # Judgment value return placeholders def merge_sheet_data_with_data(sheet_data, data): """ Merge `sheet_data` with `data`. :param sheet_data: Dictionary containing the sheet-specific data. :param data: Dictionary containing general data. :return: A merged dictionary combining both `sheet_data` and `data`. """ # Merge dictionaries using unpacking merged_data = {**data, **sheet_data} return merged_data def create_coi_file(lot_no, sheets, user, md): pprint("---- create_coi_file ---") pprint(md) qa1 = User.objects.get(pk=md['qa1']) qa2 = User.objects.get(pk=md['qa2']) pprint(qa1) pprint(qa2) sheet_data = {} for sheet_name in sheets: if sheet_name == 'hardness_out': sheet_data[sheet_name] = generate_hardness_out_values(lot_no) converted_data = convert_sheet_data(sheet_data) print(f"sheet_data \n {sheet_data}") print(f"converted_data \n {converted_data}") data = { "customer": "Tum Coder", "inspect_date": "2025-01-15", "lot_no": "12345", "staff_name": "Tum 8888", "man_name": "Tum 999", "size": "Large", "pcs": "10 pcs", "spec": "Spec-A", "hardness_out.acc": True, # Hide rows 24 to 28 if the prefix is "0" "hardness_out.spe_acc": False, # Hide rows 24 to 28 if the prefix is "0" "acc": True, # Hide rows 24 to 28 if the prefix is "0" "spe_acc": True, # Hide rows 24 to 28 if the prefix is "0" # "hardness_out.qa1": f"{qa1.first_name} {qa1.last_name}", # "hardness_out.qa2": f"{qa2.first_name} {qa2.last_name}", "qa1": f"{qa1.first_name} {qa1.last_name}", "qa2": f"{qa2.first_name} {qa2.last_name}", "dimension_app.d1_act": "33", "dimension_app.d2_act": "0[26:32]", # Hide rows 24 to 28 if the prefix is "0" "dimension_app.acc": True, # Hide rows 24 to 28 if the prefix is "0" "dimension_app.spe_acc": True, # Hide rows 24 to 28 if the prefix is "0" "sign1": qa1.profile.signed_picture, "sign2": qa2.profile.signed_picture, "pos1": qa1.profile.get_position_display(), "pos2": qa2.profile.get_position_display() } merged_data = merge_sheet_data_with_data(converted_data, data) pprint(f"---- merged_data ---") pprint(merged_data) output_file = gen_xlsx( template_file="/app/report/coi_templates.xlsx", selected_sheets=sheets, # Replace with your actual sheet names prefix_filename="/app/media/coi", data=merged_data ) report = Report.objects.create( name=lot_no, created_by=user, file=None # Leave this as None or assign a file if required ) output_file_path = Path(output_file) # Convert to a Path object for convenience with open(output_file_path, "rb") as f: report.file.save(output_file_path.name, File(f), save=True) pprint(f"outputfile = {output_file}") return report SHEET_NAMES = { 'hardness_out': 'Hardness Out', 'hardness_out_in': 'Hardness Out/In', 'hardness_both_size': 'Hardness Both Size', 'dimension': 'Dimension', 'dimension_app': 'Dimension Appearance', 'dimension_bal_weight': 'Dimension Balance/Weight', 'dim_bal_app_hard': 'Dimension Balance/Appearance/Hardness', 'dim_bal_app_rot_hard': 'Dimension Balance/Appearance/Rotation/Hardness', 'thickness_8_point': 'Thickness 8 Points', 'centering': 'Centering', } def coi_view(request): pprint(f"xxxx method = xxx {request.method}") users = User.objects.all() if request.method == "POST": pprint(request.POST) exports = request.POST.getlist("exports") # Retrieve the list of selected values pprint(f"Selected Export Options: {exports}") if 'export' in request.POST: data = { "customer": "Tum Coder", "inspect_date": "2025-01-15", "lot_no": "12345", "staff_name": "Tum 8888", "man_name": "Tum 999", "size": "Large", "lot_size": "10 pcs", "spec": "Spec-A", "hardness_out.d1_act": "10", "hardness_out.d2_act": "0[24:28]", # Hide rows 24 to 28 if the prefix is "0" "hardness_out.acc": True, # Hide rows 24 to 28 if the prefix is "0" "hardness_out.spe_acc": False, # Hide rows 24 to 28 if the prefix is "0" "dimension_app.d1_act": "33", "dimension_app.d2_act": "0[26:32]", # Hide rows 24 to 28 if the prefix is "0" "dimension_app.acc": True, # Hide rows 24 to 28 if the prefix is "0" "dimension_app.spe_acc": True, # Hide rows 24 to 28 if the prefix is "0" } output_file = gen_xlsx( template_file="/app/report/coi_templates.xlsx", selected_sheets=exports, # Replace with your actual sheet names prefix_filename="/app/media/coi", data=data ) report = Report.objects.create( name=request.POST.get('lot_no','Untitled'), created_by=request.user, file=None # Leave this as None or assign a file if required ) output_file_path = Path(output_file) # Convert to a Path object for convenience with open(output_file_path, "rb") as f: report.file.save(output_file_path.name, File(f), save=True) pprint(f"outputfile = {output_file}") if 'search_lot' in request.POST: lot_no = request.POST.get('lot_no', None) if lot_no: results = queryFromMaster(lot_no) first_result = results[0] if results else None try: pcs = int(first_result.PRO5) - int(first_result.PRO27) except: pcs = 0 size_str = f"{first_result.PRO10}x{first_result.PRO11}x{first_result.PRO12}"; spec = f"{first_result.PRO13} {first_result.PRO14} {first_result.PRO15} {first_result.PRO16} {first_result.PRO17} {first_result.PRO18}" return render(request, 'report/coi.html', {'result': first_result, 'pcs':pcs, 'size_str': size_str, 'spec': spec}) messages.success(request, "Request Sent") return redirect(request.path_info) return render(request, 'report/coi.html', {'SHEET_NAMES': SHEET_NAMES, 'users': users}) @csrf_exempt # Disable CSRF for API requests (ensure this is secure in production) @login_required def gen_report_view(request): if request.method == "POST": try: # Parse JSON data from the request body data = json.loads(request.body) lot_no = data.get("lot_no").strip() exports = data.get("exports") qa1 = data.get('qa1') qa2 = data.get('qa2') print(f"data = {data}") if not lot_no: return HttpResponseBadRequest("Missing 'lot_no' in request data") # Call the `create_coi_file` function with the provided lot_no report = create_coi_file(lot_no, exports, request.user, {'qa1': qa1, 'qa2': qa2}) # Return a success response with the report details return JsonResponse({ "message": "Report generated successfully", "report_id": report.id, "file_url": report.file.url if report.file else None, }) except json.JSONDecodeError: return HttpResponseBadRequest("Invalid JSON data") except Exception as e: pprint(e) return JsonResponse({"error": str(e)}, status=500) else: return HttpResponseBadRequest("Only POST requests are allowed")