diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e78007 --- /dev/null +++ b/.gitignore @@ -0,0 +1,231 @@ +# Created by https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode +# Edit at https://www.toptal.com/developers/gitignore?templates=macos,python,visualstudiocode + +# File generated by test server +test.* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# End of https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6c76296 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Sergal.engineering + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..68daf74 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# inventree-phomemo-plugin + +TBD diff --git a/empty.html b/empty.html new file mode 100644 index 0000000..2af6927 --- /dev/null +++ b/empty.html @@ -0,0 +1,9 @@ +{% extends "label/label_base.html" %} + +{% block style %} + +{% endblock %} + +{% block content %} + +{% endblock %} \ No newline at end of file diff --git a/inventree_phomemo/__init__.py b/inventree_phomemo/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/inventree_phomemo/phomemo_label.py b/inventree_phomemo/phomemo_label.py new file mode 100644 index 0000000..17fbfcf --- /dev/null +++ b/inventree_phomemo/phomemo_label.py @@ -0,0 +1,133 @@ +# django +from django.utils.translation import gettext_lazy as _ +from django.core.validators import MinValueValidator +from django.core.validators import MaxValueValidator +from django.http import JsonResponse + +# printer support +import requests + +# barcode helpers +from InvenTree.helpers_model import getModelsWithMixin +from InvenTree.models import InvenTreeBarcodeMixin + +# InvenTree plugin libs +from plugin import InvenTreePlugin +from plugin.mixins import LabelPrintingMixin, SettingsMixin, BarcodeMixin +from label.models import LabelTemplate + +from inventree_phomemo.version import PHOMEMO_PLUGIN_VERSION + +class PhomemoLabelPlugin(LabelPrintingMixin, BarcodeMixin, SettingsMixin, InvenTreePlugin): + AUTHOR = "Sergal.engineering" + DESCRIPTION = "Label printing plugin for Phomemo printers" + VERSION = PHOMEMO_PLUGIN_VERSION + NAME = "Phomemo" + SLUG = "phomemo" + TITLE = "Phomemo Label Printer" + + SETTINGS = { + 'URL': { + 'name': _('URL'), + 'description': _('URL of the print endpoint'), + 'default': 'http://localhost:8080/print', + }, + } + + def get_fields(self, label_instance): + object_to_print = label_instance.object_to_print + + match label_instance.SUBDIR: + case 'part': + tpart = object_to_print + barcode = '1' + str(object_to_print.pk) + case 'stockitem': + tpart = object_to_print.part + barcode = '2' + str(object_to_print.pk) + case 'stocklocation': + tpart = object_to_print + barcode = '3' + str(object_to_print.pk) + case 'build': + tpart = object_to_print + barcode = '4' + str(object_to_print.pk) + case _: + tpart = object_to_print + barcode = '0' + str(object_to_print.pk) + print(f"!! Unsupported item type: {label_instance.SUBDIR}") + + fields = { + 'name': tpart.name, + 'description': tpart.description, + 'pk': tpart.pk, + 'params': tpart.parameters_map() if hasattr(tpart, 'parameters_map') else None, + 'category': tpart.category.name if hasattr(tpart, 'category') else None, + 'category_path': tpart.category.pathstring if hasattr(tpart, 'category') else None, + 'barcode': barcode, + 'type': label_instance.SUBDIR, + 'width': label_instance.width, + 'height': label_instance.height + } + + return fields + + def print_labels(self, label: LabelTemplate, items: list, request, **kwargs): + outputs = [] + + # Get label content for every label + for item in items: + label.object_to_print = item + outputs.append(self.get_fields(label)) + + # Read settings + url = self.get_setting('URL') + + # Send the label to the printer + r = requests.post(url, json=outputs) + r.raise_for_status() + + return JsonResponse({ + 'success': True, + 'message': f'{len(items)} labels printed', + }) + + + @staticmethod + def get_supported_barcode_models(): + """Returns a list of database models which support barcode functionality.""" + return getModelsWithMixin(InvenTreeBarcodeMixin) + + def format_matched_response(self, label, model, instance): + """Format a response for the scanned data.""" + return {label: instance.format_matched_response()} + + def scan(self, barcode_data): + # Our barcode should be a string + if type(barcode_data) is not str: + barcode_data = str(barcode_data) + + # Our barcodes are at least two symbols long + if len(barcode_data) < 2: + return + + match barcode_data[0]: + case '1': + model_type = 'part' + case '2': + model_type = 'stockitem' + case '3': + model_type = 'stocklocation' + case '4': + model_type = 'build' + + supported_models = self.get_supported_barcode_models() + + for model in supported_models: + label = model.barcode_model_type() + + if label == model_type: + try: + pk = int(barcode_data[1:]) + instance = model.objects.get(pk=pk) + return self.format_matched_response(label, model, instance) + except (ValueError, model.DoesNotExist): + pass \ No newline at end of file diff --git a/inventree_phomemo/server.py b/inventree_phomemo/server.py new file mode 100644 index 0000000..6e889a8 --- /dev/null +++ b/inventree_phomemo/server.py @@ -0,0 +1,22 @@ +# server.py +# simple listener to an IP port to test the phomemo plugin + +import socket + +PORT = 9100 # Port to listen on + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +s.bind(('', PORT)) +s.listen(1) +while True: + conn, addr = s.accept() + print(addr) + printer = open('test.json', 'wb') + while True: + data = conn.recv(91000) + print('data received') + print('Sending to printer...') + printer.write(data) + if not data: + break + printer.close() \ No newline at end of file diff --git a/inventree_phomemo/version.py b/inventree_phomemo/version.py new file mode 100644 index 0000000..aa88b61 --- /dev/null +++ b/inventree_phomemo/version.py @@ -0,0 +1 @@ +PHOMEMO_PLUGIN_VERSION = "0.0.0" \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..24097d7 --- /dev/null +++ b/setup.py @@ -0,0 +1,28 @@ +from setuptools import setup, find_packages + +from inventree_phomemo.version import PHOMEMO_PLUGIN_VERSION + +with open('README.md', encoding='utf-8') as f: + long_description = f.read() + +setup( + name = "inventree-phomemo-plugin", + version = PHOMEMO_PLUGIN_VERSION, + author = "Sergal.engineering", + author_email = "zener@theserg.al", + license = "MIT", + description = "Phomemo label plugin for InvenTree", + long_description = long_description, + long_description_content_type = 'text/markdown', + keywords = "inventree phomemo label plugin", + url = "https://git.merp.digital/sergal-engineering/inventree-phomemo-plugin/", + + packages = find_packages(), + scripts = [], + + install_requires = ['requests'], + + entry_points = { + 'inventree_plugins': [ 'PhomemoLabelPlugin = inventree_phomemo.phomemo_label:PhomemoLabelPlugin' ] + } +)