Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ZPL Utils #136

Merged
merged 6 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion beam/beam/barcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def formatted_zpl_barcode(barcode_text: str) -> str:
@frappe.whitelist()
@frappe.read_only()
def formatted_zpl_label(
width: str, length: str, dpi: str = 203, print_speed: int = 2, copies: int = 1
width: str, length: str, dpi: int = 203, print_speed: int = 2, copies: int = 1
) -> str:
l = frappe._dict({})
# ^XA Start format
Expand Down
292 changes: 145 additions & 147 deletions beam/beam/printing.py
Original file line number Diff line number Diff line change
@@ -1,147 +1,145 @@
import base64
import datetime
import json
import os
from pathlib import Path

import frappe
import requests
from frappe.utils import get_bench_path, get_files_path, random_string
from frappe.utils.jinja import get_jinja_hooks
from frappe.utils.safe_exec import get_safe_globals
from jinja2 import DebugUndefined, Environment
from PyPDF2 import PdfFileWriter

try:
import cups
except Exception as e:
frappe.log_error(e, "CUPS is not installed on this server")


@frappe.whitelist()
def print_by_server(
doctype,
name,
printer_setting,
print_format=None,
doc=None,
no_letterhead=0,
file_path=None,
):
print_settings = frappe.get_doc("Network Printer Settings", printer_setting)
if isinstance(doc, str):
doc = frappe._dict(json.loads(doc))
if not print_format:
print_format = frappe.get_meta(doctype).get("default_print_format")
print_format = frappe.get_doc("Print Format", print_format)
try:
cups.setServer(print_settings.server_ip)
cups.setPort(print_settings.port)
conn = cups.Connection()
if print_format.raw_printing == 1:
output = ""
# using a custom jinja environment so we don't have to use frappe's formatting
methods, filters = get_jinja_hooks()
e = Environment(undefined=DebugUndefined)
e.globals.update(get_safe_globals())
e.filters.update(
{
"json": frappe.as_json,
"len": len,
"int": frappe.utils.data.cint,
"str": frappe.utils.data.cstr,
"flt": frappe.utils.data.flt,
}
)
if methods:
e.globals.update(methods)
template = e.from_string(print_format.raw_commands)
output = template.render(doc=doc)
if not file_path:
# use this path for testing, it will be available from the public server with the file name
# file_path = f"{get_bench_path()}/sites{get_files_path()[1:]}/{name}{random_string(10).upper()}.txt"
# use this technique for production
file_path = os.path.join("/", "tmp", f"frappe-zpl-{frappe.generate_hash()}.txt")
Path(file_path).write_text(output)
else:
output = PdfFileWriter()
output = frappe.get_print(
doctype,
name,
print_format.name,
doc=doc,
no_letterhead=no_letterhead,
as_pdf=True,
output=output,
)
if not file_path:
file_path = os.path.join("/", "tmp", f"frappe-pdf-{frappe.generate_hash()}.pdf")
output.write(open(file_path, "wb"))
conn.printFile(print_settings.printer_name, file_path, name, {})
frappe.msgprint(
f"{name } printing on {print_settings.printer_name}", alert=True, indicator="green"
)
except OSError as e:
if (
"ContentNotFoundError" in e.message
or "ContentOperationNotPermittedError" in e.message
or "UnknownContentError" in e.message
or "RemoteHostClosedError" in e.message
):
frappe.throw(frappe._("PDF generation failed"))
except cups.IPPError:
frappe.throw(frappe._("Printing failed"))


@frappe.whitelist()
def print_handling_units(
doctype=None, name=None, printer_setting=None, print_format=None, doc=None
):
if isinstance(doc, str):
doc = frappe._dict(json.loads(doc))

for row in doc.get("items"):
if not row.get("handling_unit"):
continue
# only print output / scrap items from Stock Entry
if doctype == "Stock Entry" and not row.get("t_warehouse"):
continue
# if one of the transfer types, use the 'to_handling_unit' field instead
if doctype == "Stock Entry" and doc.get("purpose") in (
"Material Transfer",
"Send to Subcontractor",
"Material Transfer for Manufacture",
):
handling_unit = frappe.get_doc("Handling Unit", row.get("to_handling_unit"))
else:
handling_unit = frappe.get_doc("Handling Unit", row.get("handling_unit"))
print_by_server(
handling_unit.doctype,
handling_unit.name,
printer_setting,
print_format,
handling_unit,
)


"""
<img src="data:image/png;base64,{{ labelary_api(doc, 'Handling Unit 6x4 ZPL Format', {}) }}" />
"""


def labelary_api(doc, print_format, settings):
print_format = frappe.get_doc("Print Format", print_format)
if print_format.raw_printing != 1:
frappe.throw("This is a not a RAW print format")
output = ""
# using a custom jinja environment so we don't have to use frappe's formatting
methods, filters = get_jinja_hooks()
e = Environment(undefined=DebugUndefined)
e.globals.update(get_safe_globals())
if methods:
e.globals.update(methods)
template = e.from_string(print_format.raw_commands)
output = template.render(doc=doc)
url = "http://api.labelary.com/v1/printers/8dpmm/labels/6x4/0/"
r = requests.post(url, files={"file": output})
return base64.b64encode(r.content).decode("ascii")
import base64
import json
import os
from pathlib import Path

import frappe
import requests
from frappe.utils.jinja import get_jinja_hooks
from frappe.utils.safe_exec import get_safe_globals
from jinja2 import DebugUndefined, Environment
from PyPDF2 import PdfFileWriter

try:
import cups
except Exception as e:
frappe.log_error(e, "CUPS is not installed on this server")


@frappe.whitelist()
def print_by_server(
doctype,
name,
printer_setting,
print_format=None,
doc=None,
no_letterhead=0,
file_path=None,
):
print_settings = frappe.get_doc("Network Printer Settings", printer_setting)
if isinstance(doc, str):
doc = frappe._dict(json.loads(doc))
if not print_format:
print_format = frappe.get_meta(doctype).get("default_print_format")
print_format = frappe.get_doc("Print Format", print_format)
try:
cups.setServer(print_settings.server_ip)
cups.setPort(print_settings.port)
conn = cups.Connection()
if print_format.raw_printing == 1:
output = ""
# using a custom jinja environment so we don't have to use frappe's formatting
methods, filters = get_jinja_hooks()
e = Environment(undefined=DebugUndefined)
e.globals.update(get_safe_globals())
e.filters.update(
{
"json": frappe.as_json,
"len": len,
"int": frappe.utils.data.cint,
"str": frappe.utils.data.cstr,
"flt": frappe.utils.data.flt,
}
)
if methods:
e.globals.update(methods)
template = e.from_string(print_format.raw_commands)
output = template.render(doc=doc)
if not file_path:
# use this path for testing, it will be available from the public server with the file name
# file_path = f"{get_bench_path()}/sites{get_files_path()[1:]}/{name}{random_string(10).upper()}.txt"
# use this technique for production
file_path = os.path.join("/", "tmp", f"frappe-zpl-{frappe.generate_hash()}.txt")
Path(file_path).write_text(output)
else:
output = PdfFileWriter()
output = frappe.get_print(
doctype,
name,
print_format.name,
doc=doc,
no_letterhead=no_letterhead,
as_pdf=True,
output=output,
)
if not file_path:
file_path = os.path.join("/", "tmp", f"frappe-pdf-{frappe.generate_hash()}.pdf")
output.write(open(file_path, "wb"))
conn.printFile(print_settings.printer_name, file_path, name, {})
frappe.msgprint(
f"{name } printing on {print_settings.printer_name}", alert=True, indicator="green"
)
except OSError as e:
if (
"ContentNotFoundError" in e.message
or "ContentOperationNotPermittedError" in e.message
or "UnknownContentError" in e.message
or "RemoteHostClosedError" in e.message
):
frappe.throw(frappe._("PDF generation failed"))
except cups.IPPError:
frappe.throw(frappe._("Printing failed"))


@frappe.whitelist()
def print_handling_units(
doctype=None, name=None, printer_setting=None, print_format=None, doc=None
):
if isinstance(doc, str):
doc = frappe._dict(json.loads(doc))

for row in doc.get("items"):
if not row.get("handling_unit"):
continue
# only print output / scrap items from Stock Entry
if doctype == "Stock Entry" and not row.get("t_warehouse"):
continue
# if one of the transfer types, use the 'to_handling_unit' field instead
if doctype == "Stock Entry" and doc.get("purpose") in (
"Material Transfer",
"Send to Subcontractor",
"Material Transfer for Manufacture",
):
handling_unit = frappe.get_doc("Handling Unit", row.get("to_handling_unit"))
else:
handling_unit = frappe.get_doc("Handling Unit", row.get("handling_unit"))
print_by_server(
handling_unit.doctype,
handling_unit.name,
printer_setting,
print_format,
handling_unit,
)


"""
<img src="data:image/png;base64,{{ labelary_api(doc, 'Handling Unit 6x4 ZPL Format', {}) }}" />
"""


def labelary_api(doc, print_format, settings):
print_format = frappe.get_doc("Print Format", print_format)
if print_format.raw_printing != 1:
frappe.throw("This is a not a RAW print format")
output = ""
# using a custom jinja environment so we don't have to use frappe's formatting
methods, filters = get_jinja_hooks()
e = Environment(undefined=DebugUndefined)
e.globals.update(get_safe_globals())
if methods:
e.globals.update(methods)
template = e.from_string(print_format.raw_commands)
output = template.render(doc=doc)
url = "http://api.labelary.com/v1/printers/8dpmm/labels/6x4/0/"
r = requests.post(url, files={"file": output})
return base64.b64encode(r.content).decode("ascii")
8 changes: 4 additions & 4 deletions beam/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,16 @@

jinja = {
"methods": [
"beam.beam.scan.get_handling_unit",
"beam.beam.barcodes.add_to_label",
"beam.beam.barcodes.barcode128",
"beam.beam.barcodes.formatted_zpl_barcode",
"beam.beam.barcodes.zebra_zpl_barcode",
"beam.beam.barcodes.formatted_zpl_label",
"beam.beam.barcodes.zebra_zpl_label",
"beam.beam.barcodes.formatted_zpl_text",
"beam.beam.barcodes.zebra_zpl_barcode",
"beam.beam.barcodes.zebra_zpl_label",
"beam.beam.barcodes.zebra_zpl_text",
"beam.beam.barcodes.add_to_label",
"beam.beam.printing.labelary_api",
"beam.beam.scan.get_handling_unit",
],
}

Expand Down
49 changes: 1 addition & 48 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ dependencies = [
"python-barcode",
"pytest",
"pytest-order",
"py-zebra-zpl"
"zebra-zpl @ git+https://github.com/mtking2/py-zebra-zpl.git"
]

[build-system]
Expand All @@ -31,57 +31,10 @@ ensure_newline_before_comments = true
indent = "\t"

[tool.semantic_release]
assets = []
commit_message = "{version}\n\nAutomatically generated by python-semantic-release"
commit_parser = "angular"
logging_use_named_masks = false
major_on_zero = true
tag_format = "v{version}"
version_variables = [
"beam/__init__.py:__version__",
"pyproject.toml:version"
]

[tool.semantic_release.branches.version]
match = "version-14"
prerelease = false

[tool.semantic_release.changelog]
template_dir = "templates"
changelog_file = "CHANGELOG.md"
exclude_commit_patterns = []

[tool.semantic_release.changelog.environment]
block_start_string = "{%"
block_end_string = "%}"
variable_start_string = "{{"
variable_end_string = "}}"
comment_start_string = "{#"
comment_end_string = "#}"
trim_blocks = false
lstrip_blocks = false
newline_sequence = "\n"
keep_trailing_newline = false
extensions = []
autoescape = true

[tool.semantic_release.commit_author]
env = "GIT_COMMIT_AUTHOR"
default = "semantic-release <semantic-release>"

[tool.semantic_release.commit_parser_options]
allowed_tags = ["build", "chore", "ci", "docs", "feat", "fix", "perf", "style", "refactor", "test"]
minor_tags = ["feat"]
patch_tags = ["fix", "perf"]

[tool.semantic_release.remote]
name = "origin"
type = "github"
ignore_token_for_push = false

[tool.semantic_release.remote.token]
env = "GH_TOKEN"

[tool.semantic_release.publish]
dist_glob_patterns = ["dist/*"]
upload_to_vcs_release = true
Loading