diff --git a/manufacturing_utilities/fixtures/custom_field.json b/manufacturing_utilities/fixtures/custom_field.json new file mode 100644 index 0000000..eaca020 --- /dev/null +++ b/manufacturing_utilities/fixtures/custom_field.json @@ -0,0 +1,188 @@ +[ + { + "alignment": "", + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "button_color": "", + "collapsible": 0, + "collapsible_depends_on": null, + "columns": 0, + "default": null, + "depends_on": null, + "description": null, + "docstatus": 0, + "doctype": "Custom Field", + "dt": "Network Printer Settings", + "fetch_from": null, + "fetch_if_empty": 0, + "fieldname": "custom_label_composer", + "fieldtype": "Section Break", + "hidden": 0, + "hide_border": 0, + "hide_days": 0, + "hide_seconds": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_global_search": 0, + "in_list_view": 0, + "in_preview": 0, + "in_standard_filter": 0, + "insert_after": "printer_name", + "is_system_generated": 0, + "is_virtual": 0, + "label": "Label Composer", + "length": 0, + "link_filters": null, + "mandatory_depends_on": null, + "mask": 0, + "modified": "2026-10-25 14:29:20.007352", + "module": null, + "name": "Network Printer Settings-custom_label_composer", + "no_copy": 0, + "non_negative": 0, + "options": null, + "permlevel": 0, + "placeholder": null, + "precision": "", + "print_hide": 0, + "print_hide_if_no_value": 0, + "print_width": null, + "read_only": 0, + "read_only_depends_on": null, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "show_dashboard": 0, + "sort_options": 0, + "translatable": 0, + "unique": 0, + "width": null + }, + { + "alignment": "", + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "button_color": "", + "collapsible": 0, + "collapsible_depends_on": null, + "columns": 0, + "default": null, + "depends_on": null, + "description": null, + "docstatus": 0, + "doctype": "Custom Field", + "dt": "Network Printer Settings", + "fetch_from": null, + "fetch_if_empty": 0, + "fieldname": "custom_paper_width_mm", + "fieldtype": "Float", + "hidden": 0, + "hide_border": 0, + "hide_days": 0, + "hide_seconds": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_global_search": 0, + "in_list_view": 0, + "in_preview": 0, + "in_standard_filter": 0, + "insert_after": "custom_label_composer", + "is_system_generated": 0, + "is_virtual": 0, + "label": "Paper Width (mm)", + "length": 0, + "link_filters": null, + "mandatory_depends_on": null, + "mask": 0, + "modified": "2026-10-25 14:29:20.138647", + "module": null, + "name": "Network Printer Settings-custom_paper_width_mm", + "no_copy": 0, + "non_negative": 0, + "options": null, + "permlevel": 0, + "placeholder": null, + "precision": "1", + "print_hide": 0, + "print_hide_if_no_value": 0, + "print_width": null, + "read_only": 0, + "read_only_depends_on": null, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "show_dashboard": 0, + "sort_options": 0, + "translatable": 0, + "unique": 0, + "width": null + }, + { + "alignment": "", + "allow_bulk_edit": 0, + "allow_in_quick_entry": 0, + "allow_on_submit": 0, + "bold": 0, + "button_color": "", + "collapsible": 0, + "collapsible_depends_on": null, + "columns": 0, + "default": null, + "depends_on": null, + "description": null, + "docstatus": 0, + "doctype": "Custom Field", + "dt": "Network Printer Settings", + "fetch_from": null, + "fetch_if_empty": 0, + "fieldname": "custom_paper_height_mm", + "fieldtype": "Float", + "hidden": 0, + "hide_border": 0, + "hide_days": 0, + "hide_seconds": 0, + "ignore_user_permissions": 0, + "ignore_xss_filter": 0, + "in_global_search": 0, + "in_list_view": 0, + "in_preview": 0, + "in_standard_filter": 0, + "insert_after": "custom_column_break_pcoln", + "is_system_generated": 0, + "is_virtual": 0, + "label": "Paper Height (mm)", + "length": 0, + "link_filters": null, + "mandatory_depends_on": null, + "mask": 0, + "modified": "2026-10-25 14:29:20.230068", + "module": null, + "name": "Network Printer Settings-custom_paper_height_mm", + "no_copy": 0, + "non_negative": 0, + "options": null, + "permlevel": 0, + "placeholder": null, + "precision": "1", + "print_hide": 0, + "print_hide_if_no_value": 0, + "print_width": null, + "read_only": 0, + "read_only_depends_on": null, + "report_hide": 0, + "reqd": 0, + "search_index": 0, + "set_only_once": 0, + "show_dashboard": 0, + "sort_options": 0, + "translatable": 0, + "unique": 0, + "width": null + } +] \ No newline at end of file diff --git a/manufacturing_utilities/hooks.py b/manufacturing_utilities/hooks.py index 99a9b8a..0f894c9 100644 --- a/manufacturing_utilities/hooks.py +++ b/manufacturing_utilities/hooks.py @@ -37,6 +37,14 @@ app_license = "gpl-3.0" # app_include_css = "/assets/manufacturing_utilities/css/manufacturing_utilities.css" # app_include_js = "/assets/manufacturing_utilities/js/manufacturing_utilities.js" +app_include_js = [ + "/assets/manufacturing_utilities/js/label_composer.js", +] + +app_include_css = [ + "/assets/manufacturing_utilities/css/label_composer.css", +] + # include js, css files in header of web template # web_include_css = "/assets/manufacturing_utilities/css/manufacturing_utilities.css" # web_include_js = "/assets/manufacturing_utilities/js/manufacturing_utilities.js" @@ -298,5 +306,16 @@ fixtures = [ "filters": [ ["name", "=", "Manufacturing Overview"] ] + }, + { + "dt": "Custom Field", + "filters": [ + ["dt", "=", "Network Printer Settings"], + ["fieldname", "in", [ + "custom_label_composer", + "custom_paper_width_mm", + "custom_paper_height_mm" + ]] + ] } ] \ No newline at end of file diff --git a/manufacturing_utilities/manufacturing_utilities/__init__.py b/manufacturing_utilities/label_composer/__init__.py similarity index 100% rename from manufacturing_utilities/manufacturing_utilities/__init__.py rename to manufacturing_utilities/label_composer/__init__.py diff --git a/manufacturing_utilities/label_composer/api.py b/manufacturing_utilities/label_composer/api.py new file mode 100644 index 0000000..e8a2576 --- /dev/null +++ b/manufacturing_utilities/label_composer/api.py @@ -0,0 +1,672 @@ + +"""Label Composer for Frappe / ERPNext v16. + +- Live HTML/Jinja preview in the requested print language +- PDF generation at the configured physical label size +- CUPS submission with group-specific copy counts +- No individual label documents are created or saved +""" + +import base64 +import math +import os +import tempfile +from io import BytesIO + +import frappe +from frappe import _ +from frappe.translate import print_language +from frappe.utils import cint, flt, getdate +from frappe.utils.html_utils import sanitize_html +from frappe.www.printview import get_print_style, get_rendered_template +from pypdf import PdfReader + + +TEMPLATE_DOCTYPE = "Label Composer Template" + +MAX_GROUPS = 30 +MAX_COPIES_PER_GROUP = 500 +MAX_TOTAL_LABELS = 1000 + +LABEL_FIELDS = { + "Customer Label": ( + "customer", + "item_code", + "item_name", + "quantity", + "delivery_date", + ), + "Warehouse Label": ( + "customer", + "item_code", + "item_name", + ), + "Supplier Label": ( + "supplier", + "item_code", + "item_name", + "quantity", + "delivery_date", + ), + "Generic Label": ( + "free_text", + ), +} + + +def _require_login(): + if frappe.session.user == "Guest": + frappe.throw(_("Login required"), frappe.PermissionError) + + +def _parse_values(values): + parsed = frappe.parse_json(values) if values else {} + + if not isinstance(parsed, dict): + frappe.throw(_("Label values must be an object")) + + if len(parsed) > 20: + frappe.throw(_("Too many label fields")) + + return parsed + + +def _get_print_language(values): + """Validate the selected Frappe Language without changing user settings.""" + + language = values.get("language") or frappe.local.lang or "en" + + if not isinstance(language, str): + frappe.throw(_("Invalid print language")) + + language = language.strip() + + if len(language) > 20: + frappe.throw(_("Invalid print language")) + + if not frappe.db.exists( + "Language", + {"name": language, "enabled": 1}, + ): + frappe.throw( + _("Print language {0} is not enabled").format(language) + ) + + return language + + +def _get_configuration(label_type): + if label_type not in LABEL_FIELDS: + frappe.throw(_("Unknown label type")) + + if not frappe.db.exists(TEMPLATE_DOCTYPE, label_type): + return None, _("No Label Composer Template configured") + + template = frappe.get_doc(TEMPLATE_DOCTYPE, label_type) + template.check_permission("read") + + if not template.enabled: + return None, _("This label template is disabled") + + if not template.print_format: + return None, _("No Print Format configured") + + if not template.default_printer: + return None, _("No default printer configured") + + if not frappe.db.exists("Print Format", template.print_format): + return None, _("Configured Print Format not found") + + print_format = frappe.get_doc( + "Print Format", + template.print_format, + ) + + if print_format.doc_type != TEMPLATE_DOCTYPE: + frappe.throw( + _("The Print Format belongs to a different DocType") + ) + + if print_format.disabled: + return None, _("The selected Print Format is disabled") + + printer = frappe.get_doc( + "Network Printer Settings", + template.default_printer, + ) + printer.check_permission("read") + + width = flt(printer.custom_paper_width_mm) + height = flt(printer.custom_paper_height_mm) + + if not (10 <= width <= 600 and 10 <= height <= 600): + return None, _("Invalid paper dimensions in printer settings") + + return { + "template": template, + "print_format": print_format, + "printer": printer, + "width": width, + "height": height, + }, None + + +def _prepare_document(template, label_type, values): + """Fill an existing configuration document in memory only.""" + + doc = frappe.get_doc(TEMPLATE_DOCTYPE, template.name) + doc.check_permission("read") + + for fieldname in LABEL_FIELDS[label_type]: + value = values.get(fieldname) + + if fieldname == "quantity": + if ( + isinstance(value, bool) + or not str( + value if value is not None else "" + ).strip() + ): + frappe.throw( + _("Label quantity must be greater than zero") + ) + + try: + quantity = float(value) + except (TypeError, ValueError): + frappe.throw(_("Invalid label quantity")) + + if not math.isfinite(quantity) or quantity <= 0: + frappe.throw( + _("Label quantity must be greater than zero") + ) + + # No check against the ordered quantity. + # Overproduction and partial packaging are allowed. + doc.set(fieldname, quantity) + continue + + if value is None: + value = "" + + if not isinstance(value, str): + frappe.throw( + _("Invalid value for {0}").format(fieldname) + ) + + if fieldname == "delivery_date": + doc.set( + fieldname, + getdate(value) if value else None, + ) + continue + + if fieldname == "free_text": + if len(value) > 10000: + frappe.throw(_("Free text is too long")) + + doc.set(fieldname, sanitize_html(value)) + continue + + if len(value) > 500: + frappe.throw( + _("Text value is too long for {0}").format( + fieldname + ) + ) + + doc.set(fieldname, value) + + return doc + + +def _page_settings(config): + return { + "pdf_page_size": "Custom", + "pdf_page_width": config["width"], + "pdf_page_height": config["height"], + } + + +@frappe.whitelist() +def preview_html(label_type, values=None): + """Render translated HTML for the composer without Chromium.""" + + _require_login() + + values = _parse_values(values) + language = _get_print_language(values) + + config, error = _get_configuration(label_type) + + if error: + return {"ready": False, "message": error} + + print_format = config["print_format"] + + if not print_format.custom_format: + return { + "ready": False, + "message": _( + "Live HTML preview requires an HTML/Jinja Print Format" + ), + } + + doc = _prepare_document( + config["template"], + label_type, + values, + ) + + settings = _page_settings(config) + + with print_language(language): + html = get_rendered_template( + doc, + print_format=print_format, + no_letterhead=True, + settings=settings, + ) + + css = get_print_style( + print_format=print_format, + overrides=settings, + ) + + return { + "ready": True, + "html": html, + "css": css, + "language": language, + "printer": config["printer"].name, + "print_format": print_format.name, + "width_mm": config["width"], + "height_mm": config["height"], + } + + +def _render_pdf(label_type, values, config=None): + """Render the print PDF in the same language as the HTML preview.""" + + values = _parse_values(values) + language = _get_print_language(values) + + if config is None: + config, error = _get_configuration(label_type) + + if error: + return None, config, error + + doc = _prepare_document( + config["template"], + label_type, + values, + ) + + width = config["width"] + height = config["height"] + + with print_language(language): + pdf = frappe.get_print( + doctype=TEMPLATE_DOCTYPE, + name=config["template"].name, + print_format=config["print_format"].name, + doc=doc, + as_pdf=True, + no_letterhead=1, + pdf_generator="chrome", + settings=_page_settings(config), + pdf_options={ + "page-size": "Custom", + "page-width": f"{width}mm", + "page-height": f"{height}mm", + "margin-top": "0mm", + "margin-bottom": "0mm", + "margin-left": "0mm", + "margin-right": "0mm", + }, + ) + + if not isinstance(pdf, bytes) or not pdf: + frappe.throw(_("PDF rendering returned no data")) + + return pdf, config, None + + +@frappe.whitelist() +def preview_label(label_type, values=None): + """Optional PDF diagnostic endpoint.""" + + _require_login() + + pdf, config, error = _render_pdf(label_type, values) + + if error: + return {"ready": False, "message": error} + + reader = PdfReader(BytesIO(pdf)) + + if not reader.pages: + frappe.throw(_("The PDF contains no pages")) + + page = reader.pages[0] + + actual_width = float(page.mediabox.width) * 25.4 / 72 + actual_height = float(page.mediabox.height) * 25.4 / 72 + + return { + "ready": True, + "pdf_base64": base64.b64encode(pdf).decode("ascii"), + "page_count": len(reader.pages), + "printer": config["printer"].name, + "print_format": config["print_format"].name, + "width_mm": config["width"], + "height_mm": config["height"], + "rendered_width_mm": round(actual_width, 2), + "rendered_height_mm": round(actual_height, 2), + } + + +# ============================================================= +# CUPS printing +# ============================================================= + +def _validate_print_jobs(jobs): + jobs = frappe.parse_json(jobs) + + if not isinstance(jobs, list) or not jobs: + frappe.throw(_("The print job is empty")) + + if len(jobs) > MAX_GROUPS: + frappe.throw( + _("Too many print groups (maximum {0})").format( + MAX_GROUPS + ) + ) + + validated = [] + total_labels = 0 + + for index, job in enumerate(jobs, start=1): + if not isinstance(job, dict): + frappe.throw( + _("Invalid print group {0}").format(index) + ) + + label_type = job.get("label_type") + + if label_type not in LABEL_FIELDS: + frappe.throw( + _("Invalid label type in group {0}").format(index) + ) + + values = job.get("values") + + if not isinstance(values, dict): + frappe.throw( + _("Invalid label values in group {0}").format(index) + ) + + # This validates the language before any CUPS submission. + _get_print_language(values) + + copies = job.get("copies") + + if ( + isinstance(copies, bool) + or not isinstance(copies, int) + or not 1 <= copies <= MAX_COPIES_PER_GROUP + ): + frappe.throw( + _("Invalid copy count in group {0}").format(index) + ) + + total_labels += copies + + if total_labels > MAX_TOTAL_LABELS: + frappe.throw( + _("Too many labels (maximum {0})").format( + MAX_TOTAL_LABELS + ) + ) + + validated.append({ + "label_type": label_type, + "values": values, + "copies": copies, + }) + + return validated, total_labels + + +def _cups_connection(cups, printer, connections): + """Resolve the configured CUPS server and printer queue.""" + + host = str(printer.server_ip or "").strip() + + if not host: + frappe.throw( + _("CUPS server address is missing for printer {0}").format( + printer.name + ) + ) + + try: + port = int(printer.port or 631) + except (TypeError, ValueError): + frappe.throw(_("Invalid CUPS port")) + + if not 1 <= port <= 65535: + frappe.throw(_("Invalid CUPS port")) + + queue = str(printer.printer_name or "").strip() + + if not queue: + frappe.throw( + _("CUPS queue name is missing for printer {0}").format( + printer.name + ) + ) + + key = (host, port) + + if key not in connections: + try: + connection = cups.Connection(host=host, port=port) + available = connection.getPrinters() + except (cups.IPPError, OSError) as exc: + frappe.throw( + _("Cannot connect to CUPS server for {0}: {1}").format( + printer.name, + str(exc), + ) + ) + + connections[key] = { + "connection": connection, + "printers": available, + } + + entry = connections[key] + + if queue not in entry["printers"]: + frappe.throw( + _("CUPS printer queue {0} was not found").format(queue) + ) + + attributes = entry["printers"][queue] + + if attributes.get("printer-is-accepting-jobs") is False: + frappe.throw( + _("CUPS printer {0} is not accepting jobs").format(queue) + ) + + return entry["connection"], queue + + +@frappe.whitelist() +def print_labels(jobs, allow_multipage=0): + """Preflight all groups, then submit them to CUPS. + + A successful response confirms queue acceptance, not completed + physical printing. Multiple CUPS submissions are not atomic. + """ + + _require_login() + + validated_jobs, total_labels = _validate_print_jobs(jobs) + + try: + import cups + except ImportError: + frappe.throw( + _("pycups is not installed on the Frappe server") + ) + + connections = {} + prepared = [] + + # Stage 1: Validate all configurations and destinations. + for index, job in enumerate(validated_jobs, start=1): + config, error = _get_configuration(job["label_type"]) + + if error: + frappe.throw( + _("Group {0}: {1}").format(index, error) + ) + + connection, queue = _cups_connection( + cups, + config["printer"], + connections, + ) + + prepared.append({ + "index": index, + "job": job, + "config": config, + "connection": connection, + "queue": queue, + }) + + # Stage 2: Render and inspect all PDFs before printing. + multipage_groups = [] + + for entry in prepared: + job = entry["job"] + + pdf, _, error = _render_pdf( + job["label_type"], + job["values"], + config=entry["config"], + ) + + if error: + frappe.throw( + _("Group {0}: {1}").format( + entry["index"], + error, + ) + ) + + pages = len(PdfReader(BytesIO(pdf)).pages) + + if pages < 1: + frappe.throw( + _("Group {0} generated an empty PDF").format( + entry["index"] + ) + ) + + entry["pdf"] = pdf + entry["pages"] = pages + + if pages > 1: + multipage_groups.append({ + "group": entry["index"], + "label_type": job["label_type"], + "printer": entry["config"]["printer"].name, + "copies": job["copies"], + "pages_per_copy": pages, + }) + + if multipage_groups and not cint(allow_multipage): + return { + "status": "multipage_warning", + "total_labels": total_labels, + "multipage_groups": multipage_groups, + } + + # Stage 3: Submit all prepared PDFs in group order. + submitted = [] + + for entry in prepared: + path = None + + try: + with tempfile.NamedTemporaryFile( + mode="wb", + prefix="label-composer-", + suffix=".pdf", + delete=False, + ) as file: + file.write(entry["pdf"]) + path = file.name + + job = entry["job"] + + options = { + "copies": str(job["copies"]), + "job-sheets": "none", + "sides": "one-sided", + } + + title = ( + f"Label Composer - {job['label_type']} " + f"- Group {entry['index']}" + ) + + cups_job_id = entry["connection"].printFile( + entry["queue"], + path, + title, + options, + ) + + submitted.append({ + "group": entry["index"], + "label_type": job["label_type"], + "printer": entry["config"]["printer"].name, + "queue": entry["queue"], + "cups_job_id": cups_job_id, + "copies": job["copies"], + "pages_per_copy": entry["pages"], + }) + + except (cups.IPPError, OSError) as exc: + frappe.log_error( + title="Label Composer CUPS submission failed", + message=frappe.get_traceback(), + ) + + return { + "status": "partial_failure", + "submitted": submitted, + "failed_group": entry["index"], + "message": str(exc), + "retry_warning": _( + "Check the CUPS queue before trying again. " + "Some labels may already have been submitted." + ), + } + + finally: + if path and os.path.exists(path): + os.unlink(path) + + return { + "status": "submitted", + "submitted": submitted, + "total_groups": len(submitted), + "total_labels": total_labels, + } diff --git a/manufacturing_utilities/manufacturing_utilities/.frappe b/manufacturing_utilities/label_composer/doctype/__init__.py similarity index 100% rename from manufacturing_utilities/manufacturing_utilities/.frappe rename to manufacturing_utilities/label_composer/doctype/__init__.py diff --git a/manufacturing_utilities/label_composer/doctype/label_composer_template/__init__.py b/manufacturing_utilities/label_composer/doctype/label_composer_template/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.js b/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.js new file mode 100644 index 0000000..d7f8011 --- /dev/null +++ b/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.js @@ -0,0 +1,8 @@ +// Copyright (c) 2026, CAnetzberger Design and contributors +// For license information, please see license.txt + +// frappe.ui.form.on("Label Composer Template", { +// refresh(frm) { + +// }, +// }); diff --git a/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.json b/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.json new file mode 100644 index 0000000..e0774ce --- /dev/null +++ b/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.json @@ -0,0 +1,144 @@ +{ + "actions": [], + "allow_bulk_edit": 1, + "allow_rename": 1, + "autoname": "field:template_name", + "creation": "2026-10-25 17:08:31.393480", + "doctype": "DocType", + "engine": "InnoDB", + "field_order": [ + "generic_section", + "template_name", + "label_type", + "enabled", + "column_break_mcpv", + "default_printer", + "print_format", + "preview_data_section", + "delivery_date_column", + "customer", + "supplier", + "item_code", + "item_name", + "quantity", + "delivery_date", + "free_text" + ], + "fields": [ + { + "fieldname": "generic_section", + "fieldtype": "Section Break", + "label": "Generic" + }, + { + "fieldname": "label_type", + "fieldtype": "Select", + "label": "Label Type", + "options": "Customer Label\nWarehouse Label\nSupplier Label\nGeneric Label" + }, + { + "default": "1", + "fieldname": "enabled", + "fieldtype": "Check", + "label": "Enabled" + }, + { + "fieldname": "column_break_mcpv", + "fieldtype": "Column Break" + }, + { + "fieldname": "default_printer", + "fieldtype": "Link", + "label": "Default Printer", + "options": "Network Printer Settings" + }, + { + "fieldname": "print_format", + "fieldtype": "Link", + "label": "Print Format", + "options": "Print Format" + }, + { + "fieldname": "preview_data_section", + "fieldtype": "Section Break", + "label": "Preview Data" + }, + { + "fieldname": "delivery_date_column", + "fieldtype": "Column Break", + "label": "Delivery Date" + }, + { + "fieldname": "customer", + "fieldtype": "Data", + "label": "Customer" + }, + { + "fieldname": "supplier", + "fieldtype": "Data", + "label": "Supplier" + }, + { + "fieldname": "item_code", + "fieldtype": "Data", + "label": "Item Code" + }, + { + "fieldname": "item_name", + "fieldtype": "Data", + "label": "Item Name" + }, + { + "fieldname": "quantity", + "fieldtype": "Float", + "label": "Quantity", + "precision": "0" + }, + { + "fieldname": "delivery_date", + "fieldtype": "Date", + "label": "Delivery Date" + }, + { + "fieldname": "free_text", + "fieldtype": "Text Editor", + "label": "Free Text" + }, + { + "fieldname": "template_name", + "fieldtype": "Data", + "in_list_view": 1, + "label": "Template Name", + "reqd": 1, + "unique": 1 + } + ], + "grid_page_length": 50, + "index_web_pages_for_search": 1, + "links": [], + "modified": "2026-10-25 17:28:48.739473", + "modified_by": "Administrator", + "module": "Label Composer", + "name": "Label Composer Template", + "naming_rule": "By fieldname", + "owner": "Administrator", + "permissions": [ + { + "create": 1, + "delete": 1, + "email": 1, + "export": 1, + "print": 1, + "read": 1, + "report": 1, + "role": "System Manager", + "share": 1, + "write": 1 + } + ], + "row_format": "Dynamic", + "rows_threshold_for_grid_search": 20, + "sort_field": "creation", + "sort_order": "DESC", + "states": [] +} diff --git a/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.py b/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.py new file mode 100644 index 0000000..f9af41e --- /dev/null +++ b/manufacturing_utilities/label_composer/doctype/label_composer_template/label_composer_template.py @@ -0,0 +1,9 @@ +# Copyright (c) 2026, CAnetzberger Design and contributors +# For license information, please see license.txt + +# import frappe +from frappe.model.document import Document + + +class LabelComposerTemplate(Document): + pass diff --git a/manufacturing_utilities/label_composer/doctype/label_composer_template/test_label_composer_template.py b/manufacturing_utilities/label_composer/doctype/label_composer_template/test_label_composer_template.py new file mode 100644 index 0000000..0038682 --- /dev/null +++ b/manufacturing_utilities/label_composer/doctype/label_composer_template/test_label_composer_template.py @@ -0,0 +1,22 @@ +# Copyright (c) 2026, CAnetzberger Design and Contributors +# See license.txt + +# import frappe +from frappe.tests import IntegrationTestCase + + +# On IntegrationTestCase, the doctype test records and all +# link-field test record dependencies are recursively loaded +# Use these module variables to add/remove to/from that list +EXTRA_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"] +IGNORE_TEST_RECORD_DEPENDENCIES = [] # eg. ["User"] + + + +class IntegrationTestLabelComposerTemplate(IntegrationTestCase): + """ + Integration tests for LabelComposerTemplate. + Use this class for testing interactions between multiple components. + """ + + pass diff --git a/manufacturing_utilities/modules.txt b/manufacturing_utilities/modules.txt index 93c0cc4..02b568d 100644 --- a/manufacturing_utilities/modules.txt +++ b/manufacturing_utilities/modules.txt @@ -1 +1,2 @@ -Manufacturing Overview \ No newline at end of file +Manufacturing Overview +Label Composer \ No newline at end of file diff --git a/manufacturing_utilities/public/css/label_composer.css b/manufacturing_utilities/public/css/label_composer.css new file mode 100644 index 0000000..7dab45a --- /dev/null +++ b/manufacturing_utilities/public/css/label_composer.css @@ -0,0 +1,502 @@ +/* ========================================================= + Manufacturing Utilities — Label Composer + ========================================================= */ + +/* --------------------------------------------------------- + Native Dock Utility + --------------------------------------------------------- */ + +.dock-utilities .lc-dock-utility { + cursor: pointer; +} + +.dock-utilities .lc-dock-utility .dock-item-icon { + display: flex; + align-items: center; + justify-content: center; +} + +/* --------------------------------------------------------- + Floating Desktop Fallback + --------------------------------------------------------- */ + +.lc-launcher--floating { + position: fixed; + right: 24px; + bottom: 24px; + z-index: 1020; + + display: inline-flex; + align-items: center; + justify-content: center; + gap: 9px; + + min-height: 42px; + padding: 11px 17px; + + border: 1px solid var(--border-color); + border-radius: 12px; + + background: var(--card-bg); + color: var(--text-color); + + font-size: 13px; + font-weight: 600; + cursor: pointer; + box-shadow: var(--shadow-lg); + + transition: + background 0.15s ease, + transform 0.15s ease; +} + +.lc-launcher--floating:hover { + background: var(--control-bg); + transform: translateY(-2px); +} + +.lc-launcher--floating:focus-visible { + outline: 2px solid var(--primary); + outline-offset: 3px; +} + +.lc-launcher-icon { + display: flex; + align-items: center; + justify-content: center; +} + +.lc-launcher-icon svg { + width: 18px; + height: 18px; +} + +body:has(#desk-dock.dock-owns-utilities:not(.hidden)[aria-hidden="false"]) .lc-launcher--floating { + display: none; +} + +/* --------------------------------------------------------- + Modal Sizing + --------------------------------------------------------- */ + +.label-composer-dialog .modal-dialog { + width: min(1180px, calc(100vw - 48px)); + max-width: 1180px; + margin: 24px auto; +} + +.label-composer-dialog .modal-content { + max-height: calc(100dvh - 48px); + overflow: hidden; + border-radius: 14px; +} + +.label-composer-dialog .modal-header { + flex-shrink: 0; + padding: 16px 22px; +} + +.label-composer-dialog .modal-body { + min-height: 0; + overflow-y: auto; + padding: 20px 24px 22px; +} + +.label-composer-dialog .modal-footer { + flex-shrink: 0; + padding: 12px 22px; +} + +/* --------------------------------------------------------- + Native Two-Column Frappe Section + --------------------------------------------------------- */ + +.label-composer-dialog .lc-composer-section > .section-body { + display: grid; + grid-template-columns: + minmax(0, 0.95fr) + minmax(0, 1.05fr); + align-items: start; + gap: 28px; +} + +.label-composer-dialog .lc-composer-section > .section-body > .form-column { + float: none !important; + width: auto !important; + max-width: none !important; + min-width: 0; + padding: 0 !important; +} + +.label-composer-dialog .lc-fields-column { + padding-right: 8px !important; +} + +.label-composer-dialog .lc-preview-column { + align-self: start; + position: sticky; + top: 0; +} + +.label-composer-dialog .lc-fields-column .frappe-control { + margin-bottom: 10px; +} + +.label-composer-dialog .lc-fields-column .form-group { + margin-bottom: 8px; +} + +.label-composer-dialog .lc-fields-column .control-label { + font-size: 12px; +} + +.label-composer-dialog .lc-fields-column .form-control { + min-height: 34px; +} + +.label-composer-dialog .lc-fields-column .checkbox { + margin-top: 6px; + margin-bottom: 8px; +} + +/* --------------------------------------------------------- + Document Context + --------------------------------------------------------- */ + +.lc-source-info { + display: flex; + flex-wrap: wrap; + gap: 5px 8px; + align-items: baseline; + + margin-bottom: 12px; + padding-bottom: 10px; + + border-bottom: 1px solid var(--border-color); + + color: var(--text-muted); + font-size: 12px; +} + +.lc-source-info strong { + color: var(--text-color); + font-weight: 600; +} + +/* --------------------------------------------------------- + Compact Packaging Quantity Editor + --------------------------------------------------------- */ + +.lc-quantity-editor { + margin: 8px 0 10px; +} + +.lc-qty-headings, +.lc-qty-row { + display: grid; + grid-template-columns: + minmax(0, 1.5fr) + minmax(0, 0.9fr) + 34px; + align-items: center; + gap: 8px; +} + +.lc-qty-headings { + margin-bottom: 6px; + color: var(--text-muted); + font-size: 11px; +} + +.lc-qty-row { + margin-bottom: 7px; +} + +.lc-qty-row .form-control { + width: 100%; + min-width: 0; + min-height: 34px; +} + +.lc-remove-group { + width: 34px; + height: 34px; + padding: 6px; +} + +.lc-add-group { + margin-top: 3px; +} + +.lc-quantity-summary { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 16px; + + margin-top: 11px; + padding: 10px 12px; + + border: 1px solid var(--border-color); + border-radius: 8px; + background: var(--control-bg); + + font-size: 12px; +} + +.lc-total-parts, +.lc-total-labels { + font-weight: 600; +} + +.lc-reference-status { + flex-basis: 100%; + font-size: 11px; + color: var(--text-muted); +} + +.lc-status-success { + color: var(--green-600, #16803c); +} + +.lc-status-warning { + color: var(--orange-600, #a96500); +} + +/* --------------------------------------------------------- + Right Preview Panel + --------------------------------------------------------- */ + +.lc-preview { + overflow: hidden; + + border: 1px solid var(--border-color); + border-radius: 12px; + + background: var(--card-bg); +} + +.lc-preview-heading { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + + padding: 16px 18px; + + border-bottom: 1px solid var(--border-color); +} + +.lc-preview-eyebrow { + margin-bottom: 4px; + + color: var(--text-muted); + font-size: 10px; + font-weight: 600; + letter-spacing: 1px; +} + +.lc-selected-type { + font-size: 16px; + font-weight: 600; + color: var(--text-color); +} + +.lc-preview-mode { + padding: 4px 8px; + + border: 1px solid var(--border-color); + border-radius: 6px; + + color: var(--text-muted); + font-size: 11px; +} + +/* --------------------------------------------------------- + Preview Group Selector + --------------------------------------------------------- */ + +.lc-preview-jobs { + display: flex; + flex-wrap: wrap; + gap: 7px; + + padding: 14px 18px 4px; +} + +.lc-preview-job { + border-radius: 8px; + font-size: 11px; + line-height: 1.4; + + white-space: normal; + text-align: left; +} + +.lc-preview-job-active { + background: var(--primary); + border: 1px solid var(--primary); + color: #ffffff; +} + +.lc-preview-job-active:hover { + color: #ffffff; +} + +/* --------------------------------------------------------- + Physical Label Preview + --------------------------------------------------------- */ + +.lc-preview-canvas { + display: flex; + align-items: center; + justify-content: center; + + width: 100%; + min-height: 245px; + + margin: 12px 0 0; + padding: 24px 14px; + + background: var(--control-bg); +} + +.lc-preview-sheet { + position: relative; + display: none; + flex-shrink: 0; + + overflow: hidden; + + border: 1px solid #d8d8d8; + border-radius: 2px; + + background: #ffffff; + box-shadow: + 0 2px 5px rgba(0, 0, 0, 0.07), + 0 12px 26px rgba(0, 0, 0, 0.09); +} + +.lc-html-frame { + position: absolute; + top: 0; + left: 0; + + display: none; + border: 0; + padding: 0; + margin: 0; + + background: #ffffff; + + /* The preview is visual only. */ + pointer-events: none; +} + +.lc-preview-message { + padding: 11px 18px 3px; + + min-height: 32px; + color: var(--text-muted); + + font-size: 12px; + line-height: 1.5; +} + +.lc-preview-warning { + color: var(--orange-600, #a96500); +} + +.lc-preview-error { + color: var(--red-600, #c53030); +} + +.lc-preview-details { + padding: 0 18px 14px; + + color: var(--text-muted); + font-size: 11px; + line-height: 1.5; +} + +/* --------------------------------------------------------- + Print Job Summary + --------------------------------------------------------- */ + +.lc-preview-bottom { + display: flex; + justify-content: space-between; + align-items: center; + flex-wrap: wrap; + gap: 8px; + + padding: 13px 18px; + + border-top: 1px solid var(--border-color); + + font-size: 12px; + color: var(--text-muted); +} + +.lc-job-summary { + color: var(--text-color); + font-size: 12px; + font-weight: 600; +} + +/* --------------------------------------------------------- + Responsive + --------------------------------------------------------- */ + +@media (max-width: 900px) { + .label-composer-dialog .modal-dialog { + width: calc(100vw - 24px); + margin: 12px auto; + } + + .label-composer-dialog .modal-content { + max-height: calc(100dvh - 24px); + } + + .label-composer-dialog .lc-composer-section > .section-body { + grid-template-columns: minmax(0, 1fr); + gap: 18px; + } + + .label-composer-dialog .lc-preview-column { + position: static; + } + + .label-composer-dialog .modal-body { + padding: 16px; + } + + .lc-preview-canvas { + min-height: 200px; + } +} + +@media (max-width: 600px) { + .lc-launcher--floating { + right: 16px; + bottom: 16px; + padding: 11px 13px; + } + + .lc-launcher--floating .lc-launcher-label { + display: none; + } + + .lc-preview-heading { + padding: 12px 14px; + } + + .lc-preview-jobs { + padding: 12px 14px 4px; + } + + .lc-preview-canvas { + min-height: 175px; + padding: 14px 8px; + } +} diff --git a/manufacturing_utilities/public/js/label_composer.js b/manufacturing_utilities/public/js/label_composer.js new file mode 100644 index 0000000..e3fffac --- /dev/null +++ b/manufacturing_utilities/public/js/label_composer.js @@ -0,0 +1,2051 @@ + +(() => { + "use strict"; + + frappe.provide("manufacturing_utilities.label_composer"); + + const composer = window.manufacturing_utilities.label_composer; + if (composer.initialized) return; + composer.initialized = true; + + const PREVIEW_API = + "manufacturing_utilities.label_composer.api.preview_html"; + + const PRINT_API = + "manufacturing_utilities.label_composer.api.print_labels"; + + const LABEL_TYPES = [ + "Customer Label", + "Warehouse Label", + "Supplier Label", + "Generic Label" + ]; + + const QUANTITY_TYPES = [ + "Customer Label", + "Supplier Label" + ]; + + const DEFAULT_LANGUAGE = + frappe.boot?.lang || + frappe.boot?.sysdefaults?.language || + frappe.boot?.sysdefaults?.lang || + "en"; + + const PREVIEW_DELAY = 300; + const PIXELS_PER_MM = 96 / 25.4; + + let activeDialog = null; + + + // ========================================================= + // Helpers + // ========================================================= + + function escapeHTML(value) { + return frappe.utils.escape_html(String(value ?? "")); + } + + function getResponse(response) { + return response?.message || response || {}; + } + + function formatNumber(value) { + return Number(value).toLocaleString(undefined, { + maximumFractionDigits: 6 + }); + } + + function validQuantity(value) { + const number = Number(value); + + return ( + String(value ?? "").trim() !== "" && + Number.isFinite(number) && + number > 0 + ); + } + + function validCount(value) { + const number = Number(value); + + return ( + String(value ?? "").trim() !== "" && + Number.isSafeInteger(number) && + number > 0 + ); + } + + function showPrintSuccess() { + frappe.show_alert({ + message: __("Printing successful"), + indicator: "green" + }, 5); + } + + function showPrintFailure(message = __("Label printing failed")) { + frappe.show_alert({ + message, + indicator: "red" + }, 6); + } + + function getCurrentForm() { + const route = frappe.get_route(); + const frm = window.cur_frm; + + if (!route || route[0] !== "Form") return null; + if (!frm?.doc || frm.doctype !== route[1]) return null; + + if (route[2]) { + let name = route[2]; + + try { + name = decodeURIComponent(name); + } catch (error) { + // Keep original name. + } + + if (frm.doc.name !== name) return null; + } + + return frm; + } + + + // ========================================================= + // Name, Language and Item Lookups + // ========================================================= + + async function getPreferredName(doctype, name, fallback = "") { + if (!name) return fallback || ""; + + const nameField = + doctype === "Customer" + ? "customer_name" + : "supplier_name"; + + try { + const response = await frappe.db.get_value( + doctype, + name, + ["alias", nameField] + ); + + const record = getResponse(response); + + return ( + record.alias?.trim() || + record[nameField] || + fallback || + name + ); + } catch (error) { + console.warn( + `[Label Composer] ${doctype} lookup failed:`, + error + ); + + return fallback || name; + } + } + + async function getPartyLanguage(doctype, name) { + if (!name) return ""; + + try { + const response = await frappe.db.get_value( + doctype, + name, + "language" + ); + + return getResponse(response).language || ""; + } catch (error) { + console.warn( + `[Label Composer] ${doctype} language lookup failed:`, + error + ); + + return ""; + } + } + + async function getItemName(itemCode) { + if (!itemCode) return ""; + + try { + const response = await frappe.db.get_value( + "Item", + itemCode, + "item_name" + ); + + return getResponse(response).item_name || itemCode; + } catch (error) { + console.warn( + "[Label Composer] Item lookup failed:", + error + ); + + return itemCode; + } + } + + + // ========================================================= + // Document Context + // ========================================================= + + function getDocumentItems(doc, doctype) { + const rows = Array.isArray(doc.items) ? doc.items : []; + + return rows.map((row, index) => { + const isFinishedGood = + doctype === "Purchase Order" && + Boolean(doc.is_subcontracted) && + Boolean(row.fg_item); + + const itemCode = isFinishedGood + ? row.fg_item + : row.item_code; + + const itemName = + isFinishedGood && + row.fg_item !== row.item_code + ? row.fg_item + : row.item_name || itemCode; + + const quantity = + isFinishedGood && + Number(row.fg_item_qty) > 0 + ? row.fg_item_qty + : row.qty; + + const deliveryDate = + row.schedule_date || + row.expected_delivery_date || + ( + doctype !== "Stock Entry" + ? doc.schedule_date + : "" + ) || + ""; + + return { + index, + item_code: itemCode || "", + item_name: itemName || "", + quantity: quantity ?? "", + delivery_date: deliveryDate, + lookup_item_name: + isFinishedGood && + row.fg_item !== row.item_code + }; + }).filter(row => Boolean(row.item_code)); + } + + function getContext() { + const frm = getCurrentForm(); + + const context = { + doctype: null, + name: null, + doc: null, + label_type: "Generic Label", + items: [], + values: { + customer: "", + supplier: "", + item_code: "", + item_name: "", + quantity: "", + delivery_date: "", + language: DEFAULT_LANGUAGE + }, + customer_link: "", + supplier_link: "" + }; + + if (!frm) return context; + + const doc = frm.doc; + + context.doctype = frm.doctype; + context.name = doc.name; + context.doc = doc; + context.values.language = + doc.language || DEFAULT_LANGUAGE; + + switch (frm.doctype) { + case "Work Order": + context.label_type = "Customer Label"; + + context.values.item_code = + doc.production_item || ""; + + context.values.item_name = + doc.item_name || ""; + + context.values.quantity = + doc.qty ?? ""; + + context.values.delivery_date = + doc.expected_delivery_date || ""; + + context.values.customer = + doc.customer_name || + doc.customer || + ""; + + context.customer_link = doc.customer || ""; + break; + + case "Item": { + context.label_type = "Warehouse Label"; + + context.values.item_code = + doc.item_code || doc.name || ""; + + context.values.item_name = + doc.item_name || ""; + + const customers = [ + ...new Set( + (doc.customer_items || []) + .map(row => row.customer_name) + .filter(Boolean) + ) + ]; + + if (customers.length === 1) { + context.customer_link = customers[0]; + context.values.customer = customers[0]; + } + + break; + } + + case "Purchase Order": + case "Subcontracting Order": + context.label_type = "Supplier Label"; + + context.supplier_link = doc.supplier || ""; + + context.values.supplier = + doc.supplier_name || + doc.supplier || + ""; + + context.items = getDocumentItems( + doc, + frm.doctype + ); + break; + + case "Stock Entry": { + const isSubcontracting = Boolean( + doc.subcontracting_order || + doc.supplier || + doc.purchase_order || + /subcontract/i.test(String(doc.purpose || "")) + ); + + if (!isSubcontracting) break; + + context.label_type = "Supplier Label"; + + context.supplier_link = doc.supplier || ""; + + context.values.supplier = + doc.supplier_name || + doc.supplier || + ""; + + context.items = getDocumentItems( + doc, + frm.doctype + ); + break; + } + } + + if (context.items.length) { + const item = context.items[0]; + + context.values.item_code = item.item_code; + context.values.item_name = item.item_name; + context.values.quantity = item.quantity; + context.values.delivery_date = item.delivery_date; + } + + return context; + } + + function setIfUnchanged(dialog, fieldname, previous, value) { + if (activeDialog !== dialog) return false; + if (!value || value === previous) return false; + if (dialog.get_value(fieldname) !== previous) return false; + + dialog.set_value(fieldname, value); + return true; + } + + + // ========================================================= + // Composer Dialog + // ========================================================= + + function openComposer() { + if (activeDialog) { + activeDialog.show(); + return; + } + + const context = getContext(); + + let dialog; + let selectionVersion = 0; + let nextGroupId = 1; + + let referenceQuantity = context.values.quantity; + + let quantityGroups = [{ + id: nextGroupId++, + quantity: validQuantity(referenceQuantity) + ? String(referenceQuantity) + : "", + copies: "1" + }]; + + let previewTimer = null; + let previewVersion = 0; + let selectedPreviewJob = 0; + let currentPreviewSize = null; + let previewResizeObserver = null; + + // Printing state. + let printing = false; + let printLocked = false; + + // Language state. + let languageTouched = false; + let applyingAutomaticLanguage = false; + + + // ----------------------------------------------------- + // Automatic Print Language + // ----------------------------------------------------- + + async function applyPartyLanguage(doctype, name, fallback = "") { + const language = + (await getPartyLanguage(doctype, name)) || + fallback; + + if ( + !language || + languageTouched || + activeDialog !== dialog + ) { + return; + } + + if (dialog.get_value("language") === language) { + return; + } + + applyingAutomaticLanguage = true; + + try { + await dialog.set_value("language", language); + } finally { + applyingAutomaticLanguage = false; + } + } + + + // ----------------------------------------------------- + // Context Enrichment + // ----------------------------------------------------- + + async function enrichContext() { + const doc = context.doc; + if (!doc) return; + + const initialCustomer = context.values.customer; + const initialSupplier = context.values.supplier; + + if (context.doctype === "Work Order") { + let customer = context.customer_link; + let fallback = initialCustomer; + let deliveryDate = context.values.delivery_date; + let orderLanguage = ""; + + if (doc.sales_order) { + try { + const response = await frappe.db.get_value( + "Sales Order", + doc.sales_order, + [ + "customer", + "customer_name", + "delivery_date", + "language" + ] + ); + + const order = getResponse(response); + + customer = order.customer || customer; + + fallback = + order.customer_name || + fallback || + customer; + + deliveryDate = + deliveryDate || + order.delivery_date || + ""; + + orderLanguage = order.language || ""; + } catch (error) { + console.warn( + "[Label Composer] Sales Order lookup failed:", + error + ); + } + } + + if (customer) { + const displayName = await getPreferredName( + "Customer", + customer, + fallback + ); + + setIfUnchanged( + dialog, + "customer", + initialCustomer, + displayName + ); + + await applyPartyLanguage( + "Customer", + customer, + orderLanguage + ); + } else if (orderLanguage) { + if ( + !languageTouched && + activeDialog === dialog + ) { + applyingAutomaticLanguage = true; + + try { + await dialog.set_value( + "language", + orderLanguage + ); + } finally { + applyingAutomaticLanguage = false; + } + } + } + + if (!context.values.delivery_date && deliveryDate) { + setIfUnchanged( + dialog, + "delivery_date", + "", + deliveryDate + ); + } + } + + if ( + context.doctype === "Item" && + context.customer_link + ) { + const displayName = await getPreferredName( + "Customer", + context.customer_link, + initialCustomer + ); + + setIfUnchanged( + dialog, + "customer", + initialCustomer, + displayName + ); + + await applyPartyLanguage( + "Customer", + context.customer_link + ); + } + + if ( + [ + "Purchase Order", + "Subcontracting Order", + "Stock Entry" + ].includes(context.doctype) && + context.label_type === "Supplier Label" + ) { + let supplier = context.supplier_link; + let fallback = initialSupplier; + + if ( + context.doctype === "Stock Entry" && + !supplier + ) { + const referenceDoctype = + doc.subcontracting_order + ? "Subcontracting Order" + : doc.purchase_order + ? "Purchase Order" + : null; + + const referenceName = + doc.subcontracting_order || + doc.purchase_order; + + if (referenceDoctype && referenceName) { + try { + const response = await frappe.db.get_value( + referenceDoctype, + referenceName, + [ + "supplier", + "supplier_name", + "language" + ] + ); + + const reference = getResponse(response); + + supplier = reference.supplier || ""; + + fallback = + reference.supplier_name || + fallback || + supplier; + } catch (error) { + console.warn( + "[Label Composer] Supplier lookup failed:", + error + ); + } + } + } + + if (supplier) { + const displayName = await getPreferredName( + "Supplier", + supplier, + fallback + ); + + setIfUnchanged( + dialog, + "supplier", + initialSupplier, + displayName + ); + + await applyPartyLanguage( + "Supplier", + supplier, + doc.language || "" + ); + } + } + } + + + // ----------------------------------------------------- + // Quantity Groups + // ----------------------------------------------------- + + function getQuantityTotals() { + let totalParts = 0; + let totalLabels = 0; + let valid = quantityGroups.length > 0; + + for (const group of quantityGroups) { + if ( + !validQuantity(group.quantity) || + !validCount(group.copies) + ) { + valid = false; + continue; + } + + totalParts += + Number(group.quantity) * + Number(group.copies); + + totalLabels += Number(group.copies); + } + + return { totalParts, totalLabels, valid }; + } + + function renderQuantityRows() { + const $wrapper = + dialog.fields_dict.quantity_groups.$wrapper; + + const rows = quantityGroups.map(group => ` +
+ + + +
+ `).join(""); + + $wrapper.html(` +
+
+ ${escapeHTML(__("Quantity per Label"))} + ${escapeHTML(__("Labels"))} + +
+ +
${rows}
+ + + +
+ + +
+
+
+ `); + + updateQuantitySummary(); + } + + function updateQuantitySummary() { + if (!dialog) return; + + const totals = getQuantityTotals(); + const $wrapper = + dialog.fields_dict.quantity_groups.$wrapper; + + $wrapper.find(".lc-total-parts").text( + __("Parts") + ": " + + formatNumber(totals.totalParts) + ); + + $wrapper.find(".lc-total-labels").text( + __("Labels") + ": " + + formatNumber(totals.totalLabels) + ); + + const $status = + $wrapper.find(".lc-reference-status"); + + $status.removeClass( + "lc-status-success lc-status-warning" + ); + + if (!totals.valid) { + $status.text( + __("Enter valid quantities and label counts.") + ); + } else if (validQuantity(referenceQuantity)) { + const expected = Number(referenceQuantity); + const difference = totals.totalParts - expected; + + if (Math.abs(difference) < 0.000001) { + $status + .text(__("Matches document quantity")) + .addClass("lc-status-success"); + } else if (difference < 0) { + $status.text( + __("Partial quantity") + + ": " + + formatNumber(totals.totalParts) + + " / " + + formatNumber(expected) + ); + } else { + // Overproduction is informational only. + $status + .text( + __("Exceeds document quantity") + + ": " + + formatNumber(totals.totalParts) + + " / " + + formatNumber(expected) + + " — " + + __("Printing allowed") + ) + .addClass("lc-status-warning"); + } + } else { + $status.text(""); + } + + refreshPreview(); + } + + function resetQuantityGroups(quantity) { + referenceQuantity = quantity; + + quantityGroups = [{ + id: nextGroupId++, + quantity: validQuantity(quantity) + ? String(quantity) + : "", + copies: "1" + }]; + + selectedPreviewJob = 0; + renderQuantityRows(); + } + + + // ----------------------------------------------------- + // Draft Print Job + // ----------------------------------------------------- + + function getDraftPrintJob() { + if (!dialog) return null; + + const labelType = + dialog.get_value("label_type") || + LABEL_TYPES[0]; + + const values = { + customer: dialog.get_value("customer") || "", + supplier: dialog.get_value("supplier") || "", + item_code: dialog.get_value("item_code") || "", + item_name: dialog.get_value("item_name") || "", + delivery_date: + dialog.get_value("delivery_date") || "", + free_text: dialog.get_value("free_text") || "", + language: + dialog.get_value("language") || + DEFAULT_LANGUAGE + }; + + const jobs = []; + const errors = []; + + if (QUANTITY_TYPES.includes(labelType)) { + for (const group of quantityGroups) { + if ( + !validQuantity(group.quantity) || + !validCount(group.copies) + ) { + errors.push( + __("Invalid packaging quantity or label count") + ); + continue; + } + + jobs.push({ + label_type: labelType, + values: { + ...values, + quantity: Number(group.quantity) + }, + copies: Number(group.copies) + }); + } + + if ( + labelType === "Customer Label" && + dialog.get_value("include_warehouse") + ) { + const count = + dialog.get_value("warehouse_count"); + + if (validCount(count)) { + jobs.push({ + label_type: "Warehouse Label", + values: { ...values }, + copies: Number(count) + }); + } else { + errors.push( + __("Invalid warehouse label count") + ); + } + } + } else { + const count = dialog.get_value("label_count"); + + if (validCount(count)) { + jobs.push({ + label_type: labelType, + values: { ...values }, + copies: Number(count) + }); + } else { + errors.push(__("Invalid label count")); + } + } + + return { + source: context.doctype + ? { + doctype: context.doctype, + name: context.name + } + : null, + jobs, + errors, + valid: errors.length === 0 && jobs.length > 0 + }; + } + + + // ----------------------------------------------------- + // HTML Preview + // ----------------------------------------------------- + + function getPreviewElements() { + const $root = + dialog.fields_dict.preview.$wrapper; + + return { + $root, + $frame: $root.find(".lc-html-frame"), + $sheet: $root.find(".lc-preview-sheet"), + $canvas: $root.find(".lc-preview-canvas"), + $message: $root.find(".lc-preview-message"), + $details: $root.find(".lc-preview-details") + }; + } + + function setPreviewMessage(message, state = "") { + if (!dialog) return; + + const { $message } = getPreviewElements(); + + $message + .removeClass( + "lc-preview-error lc-preview-warning" + ) + .toggleClass( + "lc-preview-error", + state === "error" + ) + .toggleClass( + "lc-preview-warning", + state === "warning" + ) + .text(message); + } + + function clearPreview() { + currentPreviewSize = null; + + const { + $frame, + $sheet, + $details + } = getPreviewElements(); + + $frame + .off("load.lc") + .removeAttr("srcdoc") + .hide(); + + $sheet.hide(); + $details.empty(); + } + + function resizePreview() { + if (!dialog || !currentPreviewSize) return; + + const { + $frame, + $sheet, + $canvas + } = getPreviewElements(); + + const width = currentPreviewSize.width; + const height = currentPreviewSize.height; + + const availableWidth = Math.max( + 100, + $canvas.width() - 24 + ); + + const scale = Math.min( + 1.5, + availableWidth / width + ); + + $sheet.css({ + width: `${width * scale}px`, + height: `${height * scale}px` + }); + + $frame.css({ + width: `${width}px`, + height: `${height}px`, + transform: `scale(${scale})`, + transformOrigin: "top left" + }); + } + + function buildPreviewDocument(result) { + const base = escapeHTML( + `${window.location.origin}/` + ); + + return ` + + + + + + + + + + + + + +`; + } + + function displayPreview(result) { + const { + $frame, + $sheet, + $details + } = getPreviewElements(); + + const widthMm = Number(result.width_mm); + const heightMm = Number(result.height_mm); + + if ( + !Number.isFinite(widthMm) || + !Number.isFinite(heightMm) || + widthMm <= 0 || + heightMm <= 0 + ) { + clearPreview(); + setPreviewMessage( + __("Invalid printer paper size."), + "error" + ); + return; + } + + currentPreviewSize = { + width: widthMm * PIXELS_PER_MM, + height: heightMm * PIXELS_PER_MM + }; + + $details.text( + `${result.printer} · ` + + `${formatNumber(widthMm)} × ` + + `${formatNumber(heightMm)} mm · ` + + `${result.print_format} · ` + + `${result.language || DEFAULT_LANGUAGE}` + ); + + $sheet.show(); + $frame.show(); + + resizePreview(); + + const iframe = $frame.get(0); + + $frame.off("load.lc").on("load.lc", () => { + if (!dialog || activeDialog !== dialog) { + return; + } + + setPreviewMessage(__("Preview ready")); + + try { + const document = iframe.contentDocument; + if (!document || !currentPreviewSize) { + return; + } + + const content = document.documentElement; + + const overflows = + content.scrollWidth > + currentPreviewSize.width + 4 || + content.scrollHeight > + currentPreviewSize.height + 4; + + if (overflows) { + setPreviewMessage( + __("Content extends beyond the label area. Check the Print Format before printing."), + "warning" + ); + } + } catch (error) { + // Browser sandbox may restrict inspection. + } + }); + + iframe.srcdoc = buildPreviewDocument(result); + } + + function renderPreviewJobSelector(draft) { + const $container = + getPreviewElements().$root + .find(".lc-preview-jobs"); + + if (selectedPreviewJob >= draft.jobs.length) { + selectedPreviewJob = 0; + } + + $container.html( + draft.jobs.map((job, index) => { + const quantity = job.values.quantity + ? ` · ${formatNumber(job.values.quantity)}` + : ""; + + return ` + + `; + }).join("") + ); + } + + function scheduleHTMLPreview(draft) { + if (previewTimer) { + clearTimeout(previewTimer); + previewTimer = null; + } + + const version = ++previewVersion; + + if (!draft.valid) { + clearPreview(); + setPreviewMessage( + __("Complete the quantities to see a preview.") + ); + return; + } + + const job = draft.jobs[selectedPreviewJob]; + if (!job) return; + + setPreviewMessage(__("Updating preview...")); + + previewTimer = setTimeout(async () => { + previewTimer = null; + + try { + const response = await frappe.call({ + method: PREVIEW_API, + args: { + label_type: job.label_type, + values: JSON.stringify(job.values) + } + }); + + if ( + activeDialog !== dialog || + version !== previewVersion + ) { + return; + } + + const result = getResponse(response); + + if (!result.ready) { + clearPreview(); + setPreviewMessage( + result.message || + __("This label is not configured yet.") + ); + return; + } + + displayPreview(result); + } catch (error) { + if ( + activeDialog !== dialog || + version !== previewVersion + ) { + return; + } + + clearPreview(); + + setPreviewMessage( + __("HTML preview failed. Check the server error log."), + "error" + ); + + console.error( + "[Label Composer] HTML preview failed:", + error + ); + } + }, PREVIEW_DELAY); + } + + function refreshPreview() { + if (!dialog || activeDialog !== dialog) return; + + const draft = getDraftPrintJob(); + if (!draft) return; + + const $root = getPreviewElements().$root; + + $root.find(".lc-selected-type").text( + dialog.get_value("label_type") || + LABEL_TYPES[0] + ); + + const totalLabels = draft.jobs.reduce( + (total, job) => total + job.copies, + 0 + ); + + if (draft.valid) { + $root.find(".lc-job-summary").text( + formatNumber(totalLabels) + + " " + + __("labels") + + " · " + + formatNumber(draft.jobs.length) + + " " + + __("groups") + ); + } else { + $root.find(".lc-job-summary").text( + [...new Set(draft.errors)].join(", ") + ); + } + + renderPreviewJobSelector(draft); + scheduleHTMLPreview(draft); + } + + + // ----------------------------------------------------- + // Silent Print Submission + // ----------------------------------------------------- + + async function requestPrint(jobs) { + // Use a dedicated HTTP request for printing. + // + // frappe.call() may display a global error modal for + // HTTP failures, even if our own code only uses toasts. + // + // This request leaves error presentation entirely + // under Label Composer's control. + + const response = await fetch( + `/api/method/${PRINT_API}`, + { + method: "POST", + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "Accept": "application/json", + "X-Frappe-CSRF-Token": frappe.csrf_token + }, + body: JSON.stringify({ + jobs: JSON.stringify(jobs), + + // Never bypass the multi-page protection. + allow_multipage: 0 + }) + } + ); + + const payload = await response.json().catch(() => null); + + if (!response.ok) { + const error = new Error( + `Print request failed (HTTP ${response.status})` + ); + error.response = payload; + throw error; + } + + return getResponse(payload); + } + + async function submitPrintJob() { + if ( + printing || + printLocked || + activeDialog !== dialog + ) { + return; + } + + const draft = getDraftPrintJob(); + + if (!draft?.valid) { + console.warn( + "[Label Composer] Invalid print job:", + draft?.errors + ); + + showPrintFailure(); + return; + } + + // Snapshot all fields and quantities at the time + // the operator clicks Print. + const jobs = JSON.parse( + JSON.stringify(draft.jobs) + ); + + printing = true; + dialog.disable_primary_action(); + + try { + const result = await requestPrint(jobs); + + if (result.status === "submitted") { + printLocked = true; + + console.info( + "[Label Composer] Jobs accepted by CUPS:", + result.submitted + ); + + // Close the composer and show only a toast. + dialog.hide(); + showPrintSuccess(); + return; + } + + if (result.status === "multipage_warning") { + // Nothing has been submitted. + // Keep the dialog editable so the operator + // can correct the Print Format. + + console.warn( + "[Label Composer] Printing blocked: " + + "multi-page label detected.", + result.multipage_groups + ); + + showPrintFailure( + __("Label printing failed: label spans multiple pages") + ); + return; + } + + if (result.status === "partial_failure") { + // Some jobs may already have reached CUPS. + // Prevent accidental duplicate submission. + printLocked = true; + + console.error( + "[Label Composer] Partial CUPS submission:", + result + ); + + showPrintFailure(); + return; + } + + // Unknown response: treat submission status + // as ambiguous, so do not allow automatic retries. + printLocked = true; + + console.error( + "[Label Composer] Unexpected print response:", + result + ); + + showPrintFailure(); + + } catch (error) { + // On a network or server error, it may be unclear + // whether CUPS already accepted some of the jobs. + // Keep the button disabled to avoid duplicate labels. + + printLocked = true; + + console.error( + "[Label Composer] Printing failed. " + + "Check CUPS before retrying.", + error + ); + + showPrintFailure(); + + } finally { + printing = false; + + if ( + activeDialog === dialog && + !printLocked + ) { + dialog.enable_primary_action(); + } + } + } + + + // ----------------------------------------------------- + // Source Item Selection + // ----------------------------------------------------- + + async function resolveSelectedItemName(item, version) { + if (!item.lookup_item_name) return; + + const resolved = await getItemName(item.item_code); + + if ( + activeDialog !== dialog || + selectionVersion !== version + ) { + return; + } + + setIfUnchanged( + dialog, + "item_name", + item.item_name, + resolved + ); + } + + async function changeSelectedItem() { + const index = Number( + dialog.get_value("source_item") + ); + + const item = context.items[index]; + if (!item) return; + + const version = ++selectionVersion; + + await dialog.set_values({ + item_code: item.item_code, + item_name: item.item_name, + delivery_date: item.delivery_date + }); + + if ( + activeDialog !== dialog || + selectionVersion !== version + ) { + return; + } + + resetQuantityGroups(item.quantity); + resolveSelectedItemName(item, version); + } + + const itemOptions = context.items.map( + (item, index) => ({ + value: String(index), + label: + `${index + 1}. ` + + item.item_code + + " — " + + item.item_name + }) + ); + + + // ----------------------------------------------------- + // Dialog Fields + // ----------------------------------------------------- + + const fields = [ + { + fieldtype: "Section Break", + fieldname: "lc_workspace", + css_class: "lc-composer-section", + hide_border: 1 + }, + { + fieldname: "context_info", + fieldtype: "HTML" + }, + { + fieldname: "label_type", + fieldtype: "Select", + label: __("Label Type"), + options: LABEL_TYPES.join("\n"), + default: context.label_type, + onchange() { + if (!dialog) return; + dialog.refresh_dependency(); + selectedPreviewJob = 0; + refreshPreview(); + } + }, + { + fieldname: "language", + fieldtype: "Link", + options: "Language", + label: __("Print Language"), + default: context.values.language, + reqd: 1, + get_query() { + return { + filters: { + enabled: 1 + } + }; + }, + onchange() { + if (!applyingAutomaticLanguage) { + languageTouched = true; + } + refreshPreview(); + } + }, + { + fieldname: "source_item", + fieldtype: "Select", + label: __("Source Item"), + options: itemOptions, + default: "0", + hidden: context.items.length <= 1, + depends_on: + "eval:doc.label_type == 'Supplier Label'", + onchange() { + changeSelectedItem(); + } + }, + { + fieldname: "customer", + fieldtype: "Data", + label: __("Customer"), + default: context.values.customer, + depends_on: + "eval:doc.label_type == 'Customer Label' || doc.label_type == 'Warehouse Label'", + onchange: refreshPreview + }, + { + fieldname: "supplier", + fieldtype: "Data", + label: __("Supplier"), + default: context.values.supplier, + depends_on: + "eval:doc.label_type == 'Supplier Label'", + onchange: refreshPreview + }, + { + fieldname: "item_code", + fieldtype: "Data", + label: __("Item Code"), + default: context.values.item_code, + depends_on: + "eval:doc.label_type != 'Generic Label'", + onchange: refreshPreview + }, + { + fieldname: "item_name", + fieldtype: "Data", + label: __("Item Name"), + default: context.values.item_name, + depends_on: + "eval:doc.label_type != 'Generic Label'", + onchange: refreshPreview + }, + { + fieldname: "delivery_date", + fieldtype: "Date", + label: __("Delivery Date"), + default: context.values.delivery_date, + depends_on: + "eval:doc.label_type == 'Customer Label' || doc.label_type == 'Supplier Label'", + onchange: refreshPreview + }, + { + fieldname: "quantity_groups", + fieldtype: "HTML", + depends_on: + "eval:doc.label_type == 'Customer Label' || doc.label_type == 'Supplier Label'" + }, + { + fieldname: "label_count", + fieldtype: "Int", + label: __("Number of Labels"), + default: 1, + depends_on: + "eval:doc.label_type == 'Warehouse Label' || doc.label_type == 'Generic Label'", + onchange: refreshPreview + }, + { + fieldname: "include_warehouse", + fieldtype: "Check", + label: __("Also Print Warehouse Labels"), + depends_on: + "eval:doc.label_type == 'Customer Label'", + onchange() { + if (!dialog) return; + dialog.refresh_dependency(); + refreshPreview(); + } + }, + { + fieldname: "warehouse_count", + fieldtype: "Int", + label: __("Warehouse Label Count"), + default: 1, + depends_on: + "eval:doc.label_type == 'Customer Label' && doc.include_warehouse", + onchange: refreshPreview + }, + { + fieldname: "free_text", + fieldtype: "Text Editor", + label: __("Text"), + depends_on: + "eval:doc.label_type == 'Generic Label'", + onchange: refreshPreview + }, + { + fieldtype: "Column Break", + fieldname: "lc_preview_column" + }, + { + fieldname: "preview", + fieldtype: "HTML" + } + ]; + + + // ----------------------------------------------------- + // Build Dialog + // ----------------------------------------------------- + + dialog = new frappe.ui.Dialog({ + title: __("Label Composer"), + size: "extra-large", + fields, + primary_action_label: __("Print"), + primary_action() { + // No confirmation modal. + // Printing begins immediately. + submitPrintJob(); + } + }); + + activeDialog = dialog; + + dialog.$wrapper.addClass("label-composer-dialog"); + + dialog.fields_dict.context_info.$wrapper.html( + context.doctype + ? `
+ ${escapeHTML(__("Source"))} + ${escapeHTML(context.doctype)} + ${escapeHTML(context.name)} +
` + : `
+ ${escapeHTML(__("No document selected"))} +
` + ); + + dialog.fields_dict.preview.$wrapper.html(` +
+
+
+
+ ${escapeHTML(__("LIVE PREVIEW"))} +
+
+
+ + ${escapeHTML(__("HTML"))} + +
+ +
+ +
+
+ +
+
+ +
+ ${escapeHTML(__("Preparing preview..."))} +
+ +
+ +
+ ${escapeHTML(__("Print Job"))} + +
+
+ `); + + dialog.fields_dict.label_type.$wrapper + .closest(".form-column") + .addClass("lc-fields-column"); + + dialog.fields_dict.preview.$wrapper + .closest(".form-column") + .addClass("lc-preview-column"); + + + // ----------------------------------------------------- + // Quantity Editor Events + // ----------------------------------------------------- + + const $quantityWrapper = + dialog.fields_dict.quantity_groups.$wrapper; + + $quantityWrapper.on( + "input change", + ".lc-qty-input", + function () { + const $row = $(this).closest(".lc-qty-row"); + const id = Number($row.attr("data-group-id")); + const property = $(this).attr("data-property"); + + const group = quantityGroups.find( + group => group.id === id + ); + + if ( + !group || + !["quantity", "copies"].includes(property) + ) { + return; + } + + group[property] = this.value; + updateQuantitySummary(); + } + ); + + $quantityWrapper.on("click", ".lc-add-group", () => { + quantityGroups.push({ + id: nextGroupId++, + quantity: "", + copies: "1" + }); + + renderQuantityRows(); + + $quantityWrapper.find( + ".lc-qty-row:last .lc-qty-input:first" + ).trigger("focus"); + }); + + $quantityWrapper.on( + "click", + ".lc-remove-group", + function () { + const id = Number( + $(this) + .closest(".lc-qty-row") + .attr("data-group-id") + ); + + if (quantityGroups.length <= 1) return; + + quantityGroups = quantityGroups.filter( + group => group.id !== id + ); + + renderQuantityRows(); + } + ); + + dialog.fields_dict.preview.$wrapper.on( + "click", + ".lc-preview-job", + function () { + const index = Number( + $(this).attr("data-job-index") + ); + + if (!Number.isSafeInteger(index)) return; + + selectedPreviewJob = index; + refreshPreview(); + } + ); + + + // ----------------------------------------------------- + // Lifecycle + // ----------------------------------------------------- + + dialog.$wrapper.one("hidden.bs.modal", () => { + if (previewTimer) { + clearTimeout(previewTimer); + previewTimer = null; + } + + previewVersion++; + selectionVersion++; + + previewResizeObserver?.disconnect(); + + if (activeDialog === dialog) { + activeDialog = null; + } + + dialog.$wrapper.remove(); + }); + + renderQuantityRows(); + + dialog.show(); + dialog.refresh_dependency(); + + const canvas = + dialog.fields_dict.preview.$wrapper + .find(".lc-preview-canvas")[0]; + + if (window.ResizeObserver && canvas) { + previewResizeObserver = new ResizeObserver( + resizePreview + ); + previewResizeObserver.observe(canvas); + } + + refreshPreview(); + enrichContext(); + + if (context.items.length) { + resolveSelectedItemName( + context.items[0], + selectionVersion + ); + } + + dialog.get_label_print_job = getDraftPrintJob; + } + + + // ========================================================= + // Native Dock Integration + // ========================================================= + + function addDockUtility(dock) { + if (!dock || !dock.$dock) return; + if (frappe.session.user === "Guest") return; + + const $utilities = + dock.$dock.find(".dock-utilities"); + + if (!$utilities.length) return; + + if ($utilities.find(".lc-dock-utility").length) { + return; + } + + if (typeof dock.make_utility !== "function") { + return; + } + + const $button = dock.make_utility({ + label: __("Label Composer"), + icon: "printer", + css_class: "lc-dock-utility" + }); + + $button.attr("type", "button"); + + $button.on("click.label_composer", event => { + event.preventDefault(); + event.stopPropagation(); + openComposer(); + }); + + $utilities.append($button); + } + + function installDockExtension() { + const Dock = frappe.ui?.Dock; + if (!Dock?.prototype) return false; + + if ( + typeof Dock.prototype.render_utilities !== "function" || + typeof Dock.prototype.make_utility !== "function" + ) { + return false; + } + + if (!Dock.prototype._label_composer_extended) { + const originalRender = + Dock.prototype.render_utilities; + + Dock.prototype.render_utilities = function (...args) { + const result = originalRender.apply(this, args); + addDockUtility(this); + return result; + }; + + Dock.prototype._label_composer_extended = true; + } + + const dock = frappe.app?.sidebar?.dock; + if (dock) addDockUtility(dock); + + return true; + } + + + // ========================================================= + // Desktop Fallback + // ========================================================= + + function createFallbackLauncher() { + if (!document.body) return; + + if ( + document.getElementById( + "label-composer-fallback" + ) + ) { + return; + } + + const button = document.createElement("button"); + + button.id = "label-composer-fallback"; + button.type = "button"; + + button.className = + "lc-launcher lc-launcher--floating"; + + button.setAttribute( + "aria-label", + __("Open Label Composer") + ); + + button.title = __("Open Label Composer"); + + button.innerHTML = ` + + ${frappe.utils.icon("printer", "sm")} + + + ${escapeHTML(__("Print Labels"))} + + `; + + button.addEventListener("click", openComposer); + document.body.appendChild(button); + } + + + // ========================================================= + // Initialization / Public API + // ========================================================= + + function initialize() { + createFallbackLauncher(); + installDockExtension(); + + $(document).on( + "page-change.label_composer " + + "toolbar_setup.label_composer", + installDockExtension + ); + + window.setTimeout(installDockExtension, 1000); + } + + composer.open = openComposer; + + composer.getDraftPrintJob = function () { + if (!activeDialog?.get_label_print_job) { + return null; + } + + return activeDialog.get_label_print_job(); + }; + + if (document.readyState === "loading") { + document.addEventListener( + "DOMContentLoaded", + initialize, + { once: true } + ); + } else { + initialize(); + } +})();