mirror of
https://github.com/rickbarrette/redmine_qbo_labels.git
synced 2026-11-17 17:50:36 -05:00
New plugin: print part labels on a Brother QL printer
Print label in the top-right actions of issues, estimates and invoices prints the customer's last name and the PO number (W/E/I + number) in big bold letters on a 62mm continuous roll, with a preview of the label and its status until it's printed. A print agent on the printer's network (redmine_qbo_label_agent) asks Redmine for labels every couple of seconds with its printer's token, so labels print from anywhere. Administration » Label printers: printers, agent tokens and status, recent labels. Settings: label lengths, capitals, poll interval, how long a label waits for an offline agent, and logging the agents' requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
3e29f14f76
41 files changed
+2194
No files matched your search
@@ -0,0 +1,5 @@
|
||||
.bundle
|
||||
.config
|
||||
.dockerrc
|
||||
.vscode
|
||||
Gemfile.lock
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2026 Rick Barrette
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,80 @@
|
||||
# Redmine QBO Labels
|
||||
|
||||
Prints part labels on a Brother QL label printer from Redmine: the customer's last name and the PO number parts are ordered with, in big bold letters that can be read from across the shop.
|
||||
|
||||
```
|
||||
┌──────────────────────┐
|
||||
│ SMITH │
|
||||
│ E1234 │
|
||||
└──────────────────────┘
|
||||
```
|
||||
|
||||
* **Where**: **Print label** in the top-right actions of an issue, an estimate or an invoice ([redmine_qbo](https://github.com/rickbarrette/redmine_qbo)).
|
||||
* **What**: the customer's last name (their family name in QuickBooks; a business's whole name) and the PO number: **E** + estimate number, **I** + invoice number, **W** + work order (issue) number. Both can be changed before printing, with a preview of the label as it will print, and up to 10 copies.
|
||||
* **Size**: labels run along a 62mm (2.4in) continuous roll (e.g. DK-2205) and are only as long as their text needs, up to 4in (both lengths can be changed). Each line gets the biggest letters that fit; a long name gets smaller letters, and the PO number stays big.
|
||||
* **From anywhere**: Redmine never talks to the printer. A small **print agent** on the printer's network ([redmine_qbo_label_agent](https://github.com/rickbarrette/redmine_qbo_label_agent)) asks Redmine for labels every 2 seconds and prints them, so labels print from a phone or from home, without knowing the printer's address. The agent finds the printer on its network by itself.
|
||||
|
||||
The print dialog follows the label until it's printed, or says why it wasn't (no labels in the printer, cover open, printer not found). A label the agent doesn't pick up within 10 minutes (it's offline) is dropped, so it doesn't print hours later.
|
||||
|
||||
## Requirements
|
||||
|
||||
* Redmine 7
|
||||
* redmine_qbo 2026.11.0 or later (2026.11.19 or later for **Print label** on invoices)
|
||||
* A Brother QL printer on the network (made for the QL-820NWB) and a computer on the same network that runs Docker, for the print agent
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
cd /path/to/redmine/plugins
|
||||
git clone https://github.com/rickbarrette/redmine_qbo_labels.git
|
||||
cd ..
|
||||
bundle exec rake redmine:plugins:migrate
|
||||
```
|
||||
|
||||
Restart Redmine, then:
|
||||
|
||||
1. **Administration » Label printers » New label printer**: give it a name (e.g. *Parts room*). The next page shows the print agent's token, once, and a Docker Compose file with it filled in.
|
||||
2. Run the print agent on a computer on the printer's network with that file (see the agent's README). Within a few seconds the printer shows as **Online** on the Label printers page, with the printer the agent found.
|
||||
3. **Administration » Roles and permissions**: give the roles that print labels **Print labels**. Estimates and invoices also need redmine_qbo's **View customers** (or **Write estimates** / **Write invoices**); issues need to be visible to the user.
|
||||
|
||||
With more than one printer, the print dialog asks which one.
|
||||
|
||||
## Settings
|
||||
|
||||
**Administration » Plugins » Redmine QBO Labels plugin » Configure**:
|
||||
|
||||
* **Label length**: the shortest and longest label, in inches (default 1 to 4).
|
||||
* **Capital letters**: print the lines in capitals (default on).
|
||||
* **Check for labels every**: how often the agents ask Redmine for labels (default 2 seconds; they pick up a change within a poll).
|
||||
* **Give up on a label after**: how long a label waits for an offline agent (default 10 minutes).
|
||||
* **Log label printer requests**: the agents' polls and the print dialog's status checks are left out of the Redmine log, since they come every couple of seconds. Turn this on to see them (and what each poll handed out) while debugging, and off when done. Warnings (such as an agent with a wrong token) and errors are always logged.
|
||||
|
||||
## How it works
|
||||
|
||||
* `LabelJob`: a label waiting for its printer (*queued*), taken by the agent (*printing*), then *printed*, *failed* (with the printer's error) or *not printed* (expired). Labels are kept 30 days; the latest 50 are on the Label printers page.
|
||||
* `LabelPrinter`: a printer and its agent's token (only a SHA-256 digest is stored), and what the agent last said about itself and the printer.
|
||||
* The agent's API (`LabelAgentController`), with the token as `Authorization: Bearer <token>`:
|
||||
* `POST /label_agent/poll` `{ "agent": { "version", "printer_model", "printer_address", "printer_status" } }` (agent optional) returns `{ "job": { "id", "lines", "copies", "min_length_mm", "max_length_mm" } | null, "poll_seconds" }`
|
||||
* `POST /label_agent/jobs/:id/result` `{ "status": "printed" | "failed", "error": "..." }`
|
||||
* The label is drawn by the agent; the print dialog draws its preview the same way, with the same font (`assets/javascripts/qbo_labels.js` and the agent's `label_agent/label.py`; keep them in step).
|
||||
|
||||
The label font is DejaVu Sans Bold, cut down to Latin letters (see `assets/fonts/LICENSE`).
|
||||
|
||||
## Hooks
|
||||
|
||||
Hook|Context|Use
|
||||
---|---|---
|
||||
`:view_qbo_estimate_contextual`, `:view_qbo_invoice_contextual` (redmine_qbo)|estimate/invoice id|**Print label** on estimates and invoices
|
||||
`:view_issues_show_details_bottom`|issue|**Print label** on issues (moved into the issue's actions by script, as Redmine has no hook there)
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
bundle exec rake redmine:plugins:test NAME=redmine_qbo_labels
|
||||
```
|
||||
|
||||
The tests need redmine_qbo installed, and so a MySQL database.
|
||||
|
||||
## License
|
||||
|
||||
MIT, see LICENSE.
|
||||
@@ -0,0 +1,61 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# The print agent's API (redmine-qbo-label-agent). The agent runs on the printer's network, so Redmine never
|
||||
# needs to reach the printer: the agent signs in with its printer's token (Authorization: Bearer <token>),
|
||||
# asks for the next label every couple of seconds, prints it, and reports back.
|
||||
#
|
||||
# POST /label_agent/poll { "agent": { "version", "printer_model", "printer_address",
|
||||
# "printer_status" } } (agent is optional)
|
||||
# => { "job": { "id", "lines", "copies", "max_length_mm", "min_length_mm" } | null, "poll_seconds" }
|
||||
# POST /label_agent/jobs/:id/result { "status": "printed" | "failed", "error": "..." }
|
||||
# => { "ok": true }
|
||||
class LabelAgentController < ActionController::API
|
||||
before_action :authenticate_agent
|
||||
|
||||
def poll
|
||||
@printer.seen!(ip: request.remote_ip, agent: agent_params)
|
||||
job = LabelJob.claim_next(@printer)
|
||||
log_request(job ? "sent job #{job.id}" : 'no job')
|
||||
render json: { job: job&.to_agent_json, poll_seconds: RedmineQboLabels::Settings.poll_seconds }
|
||||
end
|
||||
|
||||
def result
|
||||
job = @printer.label_jobs.find_by(id: params[:id])
|
||||
return render(json: { error: 'not found' }, status: :not_found) unless job
|
||||
|
||||
# A repeated report (the agent retrying after a dropped connection) changes nothing
|
||||
job.finish!(printed: params[:status] == 'printed', error: params[:error]) unless job.finished?
|
||||
log_request("job #{job.id} #{job.status}#{" (#{job.error})" if job.error.present?}")
|
||||
render json: { ok: true, status: job.status }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def authenticate_agent
|
||||
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/, 1]
|
||||
@printer = LabelPrinter.authenticate(token)
|
||||
return if @printer
|
||||
|
||||
Rails.logger.warn "[redmine_qbo_labels] Print agent from #{request.remote_ip} has an unknown token"
|
||||
render json: { error: 'unauthorized' }, status: :unauthorized
|
||||
end
|
||||
|
||||
def agent_params
|
||||
agent = params[:agent]
|
||||
agent.respond_to?(:permit) ? agent.permit(:version, :printer_model, :printer_address, :printer_status).to_h : nil
|
||||
end
|
||||
|
||||
def log_request(message)
|
||||
return unless RedmineQboLabels::Settings.log_requests?
|
||||
|
||||
Rails.logger.info "[redmine_qbo_labels] #{@printer.name} agent (#{request.remote_ip}): #{message}"
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,59 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# The Print label dialog: opened from an issue, estimate or invoice (new), sends the label to a printer's
|
||||
# queue (create), and follows it until it's printed (show, polled by the dialog). The dialog asks for show's
|
||||
# JSON with an Accept header, not a .json URL: Redmine treats .json as the REST API, without the session.
|
||||
class LabelJobsController < ApplicationController
|
||||
before_action :authorize_global
|
||||
before_action :find_source, only: [:new, :create]
|
||||
before_action :find_printers, only: [:new, :create]
|
||||
|
||||
def new
|
||||
@lines = @source.lines
|
||||
@copies = 1
|
||||
respond_to { |format| format.js }
|
||||
end
|
||||
|
||||
def create
|
||||
@lines = Array(params[:lines]).first(LabelJob::MAX_LINES)
|
||||
@copies = params[:copies].to_i.clamp(1, LabelJob::MAX_COPIES)
|
||||
printer = @printers.find { |p| p.id == params[:printer_id].to_i } || @printers.first
|
||||
@job = LabelJob.new(label_printer: printer, user: User.current, lines: @lines, copies: @copies,
|
||||
source_type: @source.type, source_id: @source.id.to_s)
|
||||
@job.save if printer
|
||||
respond_to { |format| format.js }
|
||||
end
|
||||
|
||||
def show
|
||||
@job = LabelJob.find_by(id: params[:id])
|
||||
return render_404 unless @job && (@job.user_id == User.current.id || User.current.admin?)
|
||||
|
||||
LabelJob.expire_lapsed unless @job.finished?
|
||||
@job.reload
|
||||
respond_to do |format|
|
||||
format.json do
|
||||
render json: { id: @job.id, status: @job.status, status_label: @job.status_label, error: @job.error,
|
||||
finished: @job.finished?, printer_online: @job.label_printer.online? }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_source
|
||||
@source = RedmineQboLabels::LabelSource.find(params[:source_type], params[:source_id])
|
||||
render_404 unless @source
|
||||
end
|
||||
|
||||
def find_printers
|
||||
@printers = LabelPrinter.active.sorted.to_a
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,82 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# Administration » Label printers: the printers (one print agent each), their agents' tokens and status, and
|
||||
# the labels printed lately
|
||||
class LabelPrintersController < ApplicationController
|
||||
layout 'admin'
|
||||
self.main_menu = false
|
||||
menu_item :label_printers
|
||||
|
||||
before_action :require_admin
|
||||
before_action :find_printer, only: [:edit, :update, :destroy, :regenerate_token]
|
||||
|
||||
def index
|
||||
@printers = LabelPrinter.sorted.to_a
|
||||
LabelJob.expire_lapsed
|
||||
@jobs = LabelJob.recent.includes(:label_printer, :user).limit(50)
|
||||
end
|
||||
|
||||
def new
|
||||
@printer = LabelPrinter.new
|
||||
end
|
||||
|
||||
def create
|
||||
@printer = LabelPrinter.new(printer_params)
|
||||
@printer.generate_token
|
||||
if @printer.save
|
||||
render_token
|
||||
else
|
||||
render action: 'new'
|
||||
end
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
if @printer.update(printer_params)
|
||||
flash[:notice] = l(:notice_successful_update)
|
||||
redirect_to label_printers_path
|
||||
else
|
||||
render action: 'edit'
|
||||
end
|
||||
end
|
||||
|
||||
# A new token for the printer's agent; the old one stops working right away
|
||||
def regenerate_token
|
||||
@printer.generate_token
|
||||
@printer.save!
|
||||
render_token
|
||||
end
|
||||
|
||||
def destroy
|
||||
@printer.destroy
|
||||
flash[:notice] = l(:notice_successful_delete)
|
||||
redirect_to label_printers_path
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_printer
|
||||
@printer = LabelPrinter.find(params[:id])
|
||||
rescue ActiveRecord::RecordNotFound
|
||||
render_404
|
||||
end
|
||||
|
||||
def printer_params
|
||||
params.require(:label_printer).permit(:name, :active)
|
||||
end
|
||||
|
||||
# The token is only ever shown here, right after it's made
|
||||
def render_token
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
render action: 'token'
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,102 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# A label sent to a label printer. Queued until the printer's agent picks it up (printing), then printed or
|
||||
# failed; one its agent never picks up expires (RedmineQboLabels::Settings.job_expiry), so a label doesn't
|
||||
# print long after it was asked for.
|
||||
class LabelJob < ApplicationRecord
|
||||
STATUSES = %w[queued printing printed failed expired].freeze
|
||||
FINISHED = %w[printed failed expired].freeze
|
||||
MAX_LINES = 4
|
||||
MAX_LINE_LENGTH = 40
|
||||
MAX_COPIES = 10
|
||||
# A label the agent took but never reported on
|
||||
PRINTING_TIMEOUT = 2.minutes
|
||||
# Finished jobs are kept this long
|
||||
KEEP_FOR = 30.days
|
||||
|
||||
belongs_to :label_printer
|
||||
belongs_to :user, optional: true
|
||||
|
||||
serialize :lines, coder: JSON, type: Array
|
||||
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
validates :copies, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: MAX_COPIES }
|
||||
validate :validate_lines
|
||||
|
||||
before_validation :normalize_lines, on: :create
|
||||
|
||||
scope :recent, -> { order(created_at: :desc, id: :desc) }
|
||||
|
||||
def finished?
|
||||
FINISHED.include?(status)
|
||||
end
|
||||
|
||||
# The next queued label for a printer, marked as printing, or nil. Lapsed jobs are expired first.
|
||||
def self.claim_next(printer)
|
||||
expire_lapsed
|
||||
transaction do
|
||||
job = printer.label_jobs.where(status: 'queued').order(:id).lock.first
|
||||
job&.update!(status: 'printing', claimed_at: Time.current)
|
||||
job
|
||||
end
|
||||
end
|
||||
|
||||
# Queued jobs past their expiry, and printing jobs the agent never reported on; old finished jobs go
|
||||
def self.expire_lapsed
|
||||
now = Time.current
|
||||
where(status: 'queued').where(created_at: ...RedmineQboLabels::Settings.job_expiry.ago)
|
||||
.update_all(status: 'expired', finished_at: now, updated_at: now,
|
||||
error: I18n.t(:text_qbo_labels_job_expired))
|
||||
where(status: 'printing').where(claimed_at: ...PRINTING_TIMEOUT.ago)
|
||||
.update_all(status: 'failed', finished_at: now, updated_at: now,
|
||||
error: I18n.t(:text_qbo_labels_job_unconfirmed))
|
||||
where(created_at: ...KEEP_FOR.ago).delete_all
|
||||
end
|
||||
|
||||
# The agent's report: printed, or failed with why
|
||||
def finish!(printed:, error: nil)
|
||||
update!(status: printed ? 'printed' : 'failed', finished_at: Time.current,
|
||||
error: printed ? nil : error.to_s.truncate(1000).presence || I18n.t(:text_qbo_labels_job_failed))
|
||||
end
|
||||
|
||||
# What the agent needs to print it
|
||||
def to_agent_json
|
||||
{
|
||||
id: id, lines: lines, copies: copies,
|
||||
max_length_mm: RedmineQboLabels::Settings.max_length_mm,
|
||||
min_length_mm: RedmineQboLabels::Settings.min_length_mm
|
||||
}
|
||||
end
|
||||
|
||||
def status_label
|
||||
I18n.t("label_qbo_labels_status_#{status}")
|
||||
end
|
||||
|
||||
def source
|
||||
RedmineQboLabels::LabelSource.find(source_type, source_id) if source_type.present?
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def normalize_lines
|
||||
self.lines = Array(lines).map { |line| line.to_s.squish }
|
||||
self.lines = lines.map(&:upcase) if RedmineQboLabels::Settings.uppercase?
|
||||
self.lines = lines.reject(&:blank?)
|
||||
end
|
||||
|
||||
def validate_lines
|
||||
if lines.blank?
|
||||
errors.add(:base, :qbo_labels_no_text)
|
||||
elsif lines.size > MAX_LINES || lines.any? { |line| line.length > MAX_LINE_LENGTH }
|
||||
errors.add(:base, :qbo_labels_text_too_long, count: MAX_LINE_LENGTH)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# A label printer, reached through the print agent on its network. The agent signs in with a token and asks
|
||||
# for labels every couple of seconds (LabelAgentController).
|
||||
class LabelPrinter < ApplicationRecord
|
||||
TOKEN_PREFIX = 'qbl_'
|
||||
# The agent counts as online when it asked for labels within this time
|
||||
ONLINE_WITHIN = 30.seconds
|
||||
# How often an agent's polls update last_seen_at (saves a write every 2 seconds)
|
||||
SEEN_RESOLUTION = 15.seconds
|
||||
|
||||
has_many :label_jobs, dependent: :delete_all
|
||||
|
||||
validates :name, presence: true, length: { maximum: 60 }, uniqueness: { case_sensitive: false }
|
||||
validates :token_digest, presence: true
|
||||
|
||||
scope :active, -> { where(active: true) }
|
||||
scope :sorted, -> { order(:name) }
|
||||
|
||||
attr_reader :token
|
||||
|
||||
def self.digest(token)
|
||||
Digest::SHA256.hexdigest(token.to_s)
|
||||
end
|
||||
|
||||
# The active printer whose agent has this token, or nil
|
||||
def self.authenticate(token)
|
||||
return nil unless token.to_s.start_with?(TOKEN_PREFIX)
|
||||
|
||||
active.find_by(token_digest: digest(token))
|
||||
end
|
||||
|
||||
# Makes a new token (kept in #token until the record is reloaded) and returns it
|
||||
def generate_token
|
||||
@token = "#{TOKEN_PREFIX}#{SecureRandom.base58(32)}"
|
||||
self.token_digest = self.class.digest(@token)
|
||||
@token
|
||||
end
|
||||
|
||||
def online?
|
||||
last_seen_at.present? && last_seen_at > ONLINE_WITHIN.ago
|
||||
end
|
||||
|
||||
# Records an agent's poll, and what it says about the printer when it says anything
|
||||
def seen!(ip:, agent: nil)
|
||||
changes = {}
|
||||
changes[:last_seen_at] = Time.current if last_seen_at.nil? || last_seen_at < SEEN_RESOLUTION.ago
|
||||
changes[:last_ip] = ip if ip.present? && ip != last_ip
|
||||
if agent.is_a?(Hash)
|
||||
{ agent_version: 'version', printer_model: 'printer_model', printer_address: 'printer_address',
|
||||
printer_status: 'printer_status' }.each do |column, key|
|
||||
next unless agent.key?(key)
|
||||
|
||||
value = agent[key].to_s.truncate(250).presence
|
||||
changes[column] = value if value != self[column]
|
||||
end
|
||||
end
|
||||
update_columns(changes.merge(updated_at: Time.current)) if changes.any?
|
||||
end
|
||||
|
||||
def to_s
|
||||
name
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
<%# Print label on an issue's page: Redmine's issue actions have no hook, so the link goes there from here %>
|
||||
<template id="qbo-label-issue-link"><%= render partial: 'label_hooks/print_link', locals: { source_type: 'issue', source_id: issue.id } %></template>
|
||||
<%= javascript_tag do %>
|
||||
$(function() { QboLabels.placeIssueLink('#qbo-label-issue-link'); });
|
||||
<% end %>
|
||||
@@ -0,0 +1,4 @@
|
||||
<%# Print label, in the top-right actions of an issue, estimate or invoice; opens the print dialog %>
|
||||
<%= link_to sprite_icon('qbo-label-print', l(:button_qbo_labels_print), plugin: 'redmine_qbo_labels'),
|
||||
new_label_job_path(source_type: source_type, source_id: source_id),
|
||||
remote: true, class: 'icon icon-qbo-label-print', title: l(:button_qbo_labels_print) %>
|
||||
@@ -0,0 +1,69 @@
|
||||
<%# The Print label dialog: the label's lines (filled from the issue, estimate or invoice), a preview drawn
|
||||
the way the print agent draws it (assets/javascripts/qbo_labels.js), copies and printer %>
|
||||
<div id="qbo-label-dialog"
|
||||
data-max-length-mm="<%= RedmineQboLabels::Settings.max_length_mm %>"
|
||||
data-min-length-mm="<%= RedmineQboLabels::Settings.min_length_mm %>"
|
||||
data-uppercase="<%= RedmineQboLabels::Settings.uppercase? %>"
|
||||
data-text-printing="<%= l(:text_qbo_labels_printing) %>"
|
||||
data-text-waiting="<%= l(:text_qbo_labels_waiting) %>"
|
||||
data-text-offline="<%= l(:text_qbo_labels_offline) %>"
|
||||
data-text-lost="<%= l(:text_qbo_labels_lost_contact) %>">
|
||||
<% if @printers.empty? %>
|
||||
<p class="nodata"><%= l(:text_qbo_labels_no_printers) %></p>
|
||||
<% else %>
|
||||
<%= form_tag label_jobs_path, remote: true, id: 'qbo-label-form' do %>
|
||||
<%= hidden_field_tag :source_type, @source.type %>
|
||||
<%= hidden_field_tag :source_id, @source.id %>
|
||||
<% if @job&.errors&.any? %>
|
||||
<div id="errorExplanation"><ul><% @job.errors.full_messages.each do |message| %><li><%= message %></li><% end %></ul></div>
|
||||
<% end %>
|
||||
|
||||
<div class="qbo-label-preview-wrap">
|
||||
<canvas class="qbo-label-preview" width="1" height="1" aria-label="<%= l(:label_qbo_labels_preview) %>"></canvas>
|
||||
<div class="qbo-label-size"></div>
|
||||
</div>
|
||||
|
||||
<div class="tabular">
|
||||
<p>
|
||||
<label for="qbo_label_line_0"><%= l(:field_qbo_labels_name) %></label>
|
||||
<%= text_field_tag 'lines[]', @lines[0], id: 'qbo_label_line_0', class: 'qbo-label-line',
|
||||
maxlength: LabelJob::MAX_LINE_LENGTH, autocomplete: 'off' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_label_line_1"><%= l(:field_qbo_labels_po_number) %></label>
|
||||
<%= text_field_tag 'lines[]', @lines[1], id: 'qbo_label_line_1', class: 'qbo-label-line',
|
||||
maxlength: LabelJob::MAX_LINE_LENGTH, autocomplete: 'off' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_label_copies"><%= l(:field_qbo_labels_copies) %></label>
|
||||
<%= number_field_tag :copies, @copies, id: 'qbo_label_copies', min: 1, max: LabelJob::MAX_COPIES,
|
||||
class: 'qbo-label-copies' %>
|
||||
</p>
|
||||
<% if @printers.size > 1 %>
|
||||
<p>
|
||||
<label for="qbo_label_printer"><%= l(:field_qbo_labels_printer) %></label>
|
||||
<%= select_tag :printer_id,
|
||||
options_for_select(@printers.map { |p| ["#{p.name}#{" (#{l(:label_qbo_labels_offline)})" unless p.online?}", p.id] },
|
||||
params[:printer_id] || @printers.find(&:online?)&.id),
|
||||
id: 'qbo_label_printer' %>
|
||||
</p>
|
||||
<% elsif !@printers.first.online? %>
|
||||
<p class="qbo-label-warning"><%= l(:text_qbo_labels_printer_offline, name: @printers.first.name) %></p>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<p class="buttons">
|
||||
<%= submit_tag l(:button_qbo_labels_print), class: 'qbo-label-submit', data: { disable_with: l(:button_qbo_labels_print) } %>
|
||||
<%= link_to_function l(:button_cancel), 'hideModal(this);' %>
|
||||
</p>
|
||||
<% end %>
|
||||
|
||||
<div class="qbo-label-status" hidden>
|
||||
<p class="qbo-label-status-text"></p>
|
||||
<p class="buttons">
|
||||
<%= button_tag l(:button_qbo_labels_print_another), type: 'button', onclick: 'QboLabels.again();', class: 'qbo-label-again' %>
|
||||
<%= button_tag l(:button_close), type: 'button', onclick: 'hideModal(this);' %>
|
||||
</p>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -0,0 +1,7 @@
|
||||
<% if @job.persisted? %>
|
||||
QboLabels.follow(<%= raw({ url: label_job_path(@job), printer: @job.label_printer.name,
|
||||
printer_online: @job.label_printer.online? }.to_json) %>);
|
||||
<% else %>
|
||||
$('#ajax-modal').html('<%= escape_javascript(render partial: 'label_jobs/dialog') %>');
|
||||
QboLabels.initDialog();
|
||||
<% end %>
|
||||
@@ -0,0 +1,3 @@
|
||||
$('#ajax-modal').html('<%= escape_javascript(render partial: 'label_jobs/dialog') %>');
|
||||
showModal('ajax-modal', '480px', '<%= escape_javascript(l(:label_qbo_labels_print_title)) %>');
|
||||
QboLabels.initDialog();
|
||||
@@ -0,0 +1,11 @@
|
||||
<%= error_messages_for 'printer' %>
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<%= f.text_field :name, size: 30, maxlength: 60, required: true %>
|
||||
<em class="info"><%= l(:text_qbo_labels_printer_name) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<%= f.check_box :active %>
|
||||
<em class="info"><%= l(:text_qbo_labels_printer_active) %></em>
|
||||
</p>
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
<h2><%= link_to l(:label_label_printer_plural), label_printers_path %> » <%= @printer.name %></h2>
|
||||
|
||||
<%= labelled_form_for :label_printer, @printer, url: label_printer_path(@printer), html: { method: :patch } do |f| %>
|
||||
<%= render partial: 'label_printers/form', locals: { f: f } %>
|
||||
<%= submit_tag l(:button_save) %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,98 @@
|
||||
<%# Administration » Label printers %>
|
||||
<div class="contextual">
|
||||
<%= link_to sprite_icon('add', l(:label_qbo_labels_new_printer)), new_label_printer_path, class: 'icon icon-add' %>
|
||||
<%= link_to sprite_icon('settings', l(:label_settings)), plugin_settings_path('redmine_qbo_labels'), class: 'icon icon-settings' %>
|
||||
</div>
|
||||
|
||||
<h2><%= l(:label_label_printer_plural) %></h2>
|
||||
|
||||
<% if @printers.empty? %>
|
||||
<p class="nodata"><%= l(:text_qbo_labels_no_printers_admin) %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list label-printers">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:field_name) %></th>
|
||||
<th><%= l(:field_qbo_labels_agent) %></th>
|
||||
<th><%= l(:field_qbo_labels_printer) %></th>
|
||||
<th><%= l(:field_qbo_labels_last_seen) %></th>
|
||||
<th><%= l(:field_active) %></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @printers.each do |printer| %>
|
||||
<tr>
|
||||
<td class="name"><%= printer.name %></td>
|
||||
<td>
|
||||
<% if printer.online? %>
|
||||
<span class="status-online"><%= l(:label_qbo_labels_online) %></span>
|
||||
<% else %>
|
||||
<span class="status-offline"><%= l(:label_qbo_labels_offline) %></span>
|
||||
<% end %>
|
||||
<% if printer.agent_version.present? %><br><small><%= l(:label_qbo_labels_agent_version, version: printer.agent_version) %></small><% end %>
|
||||
</td>
|
||||
<td>
|
||||
<% if printer.printer_model.present? || printer.printer_address.present? %>
|
||||
<%= [printer.printer_model, printer.printer_address].compact_blank.join(' @ ') %>
|
||||
<% else %>
|
||||
<span class="qbo-label-muted"><%= l(:label_qbo_labels_printer_not_found) %></span>
|
||||
<% end %>
|
||||
<% if printer.printer_status.present? %><br><small><%= printer.printer_status %></small><% end %>
|
||||
</td>
|
||||
<td>
|
||||
<%= printer.last_seen_at ? format_time(printer.last_seen_at) : '-' %>
|
||||
<% if printer.last_ip.present? %><br><small><%= printer.last_ip %></small><% end %>
|
||||
</td>
|
||||
<td><%= checked_image printer.active? %></td>
|
||||
<td class="buttons">
|
||||
<%= link_to sprite_icon('edit', l(:button_edit)), edit_label_printer_path(printer), class: 'icon icon-edit' %>
|
||||
<%= link_to sprite_icon('key', l(:button_qbo_labels_new_token)), regenerate_token_label_printer_path(printer),
|
||||
method: :post, class: 'icon icon-key', data: { confirm: l(:text_qbo_labels_new_token_confirm) } %>
|
||||
<%= link_to sprite_icon('del', l(:button_delete)), label_printer_path(printer), method: :delete,
|
||||
class: 'icon icon-del', data: { confirm: l(:text_are_you_sure) } %>
|
||||
</td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<h3><%= l(:label_qbo_labels_recent_jobs) %></h3>
|
||||
<% if @jobs.empty? %>
|
||||
<p class="nodata"><%= l(:label_no_data) %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list label-jobs">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:field_created_on) %></th>
|
||||
<th><%= l(:field_qbo_labels_label) %></th>
|
||||
<th><%= l(:field_qbo_labels_copies) %></th>
|
||||
<th><%= l(:field_qbo_labels_for) %></th>
|
||||
<th><%= l(:field_user) %></th>
|
||||
<th><%= l(:field_qbo_labels_printer) %></th>
|
||||
<th><%= l(:field_status) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @jobs.each do |job| %>
|
||||
<tr>
|
||||
<td><%= format_time(job.created_at) %></td>
|
||||
<td class="lines"><%= safe_join(job.lines.map { |line| h(line) }, tag.br) %></td>
|
||||
<td><%= job.copies %></td>
|
||||
<td><%= job.source_type.present? ? l("label_qbo_labels_source_#{job.source_type}") + " #{job.source_id}" : '-' %></td>
|
||||
<td><%= job.user ? link_to_user(job.user) : '-' %></td>
|
||||
<td><%= job.label_printer&.name %></td>
|
||||
<td class="status-<%= job.status %>">
|
||||
<%= job.status_label %>
|
||||
<% if job.error.present? %><br><small><%= job.error %></small><% end %>
|
||||
</td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -0,0 +1,6 @@
|
||||
<h2><%= link_to l(:label_label_printer_plural), label_printers_path %> » <%= l(:label_qbo_labels_new_printer) %></h2>
|
||||
|
||||
<%= labelled_form_for :label_printer, @printer, url: label_printers_path, html: { method: :post } do |f| %>
|
||||
<%= render partial: 'label_printers/form', locals: { f: f } %>
|
||||
<%= submit_tag l(:button_create) %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,30 @@
|
||||
<%# Shown once, right after a printer is added or gets a new token: the agent's token and how to run the agent %>
|
||||
<% redmine_url = "#{Setting.protocol}://#{Setting.host_name}".chomp('/') %>
|
||||
<h2><%= link_to l(:label_label_printer_plural), label_printers_path %> » <%= @printer.name %></h2>
|
||||
|
||||
<div class="flash warning"><%= l(:text_qbo_labels_token_once) %></div>
|
||||
|
||||
<div class="box">
|
||||
<p><strong><%= l(:field_qbo_labels_token) %></strong></p>
|
||||
<pre class="qbo-label-token"><%= @printer.token %></pre>
|
||||
|
||||
<p><%= l(:text_qbo_labels_compose_intro) %></p>
|
||||
<pre class="qbo-label-token">services:
|
||||
label-agent:
|
||||
build: https://github.com/rickbarrette/redmine_qbo_label_agent.git
|
||||
restart: always
|
||||
# Host networking lets the agent find the printer on the local network (Bonjour/mDNS)
|
||||
network_mode: host
|
||||
environment:
|
||||
REDMINE_URL: <%= redmine_url %>
|
||||
AGENT_TOKEN: <%= @printer.token %>
|
||||
PRINTER_MODEL: QL-820NWB
|
||||
# Optional: skip the network search and use this printer
|
||||
# PRINTER: tcp://192.168.0.100
|
||||
# DEBUG, INFO or WARNING
|
||||
LOG_LEVEL: INFO
|
||||
</pre>
|
||||
<p><em class="info"><%= l(:text_qbo_labels_compose_after) %></em></p>
|
||||
</div>
|
||||
|
||||
<p><%= link_to l(:button_back), label_printers_path %></p>
|
||||
@@ -0,0 +1,42 @@
|
||||
<%# Settings for redmine_qbo_labels (Administration » Plugins » Configure) %>
|
||||
<% s = RedmineQboLabels::Settings %>
|
||||
<% field = ->(key) { "settings[#{key}]" } %>
|
||||
|
||||
<p><%= link_to sprite_icon('document', l(:label_label_printer_plural)), label_printers_path, class: 'icon icon-document' %></p>
|
||||
|
||||
<fieldset class="box tabular">
|
||||
<legend><%= l(:label_qbo_labels_label_settings) %></legend>
|
||||
<p>
|
||||
<label for="qbo_labels_min_length"><%= l(:field_qbo_labels_length) %></label>
|
||||
<%= number_field_tag field.call('min_length_in'), s.min_length_in, id: 'qbo_labels_min_length', min: 0.5, max: 12, step: 0.1, style: 'width: 5em' %>
|
||||
–
|
||||
<%= number_field_tag field.call('max_length_in'), s.max_length_in, id: 'qbo_labels_max_length', min: 1, max: 12, step: 0.1, style: 'width: 5em' %>
|
||||
<%= l(:label_qbo_labels_inches) %>
|
||||
<em class="info"><%= l(:text_qbo_labels_length) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_labels_uppercase"><%= l(:field_qbo_labels_uppercase) %></label>
|
||||
<%= hidden_field_tag field.call('uppercase'), '0', id: nil %>
|
||||
<%= check_box_tag field.call('uppercase'), '1', s.uppercase?, id: 'qbo_labels_uppercase' %>
|
||||
</p>
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="box tabular">
|
||||
<legend><%= l(:label_qbo_labels_agent_settings) %></legend>
|
||||
<p>
|
||||
<label for="qbo_labels_poll"><%= l(:field_qbo_labels_poll_seconds) %></label>
|
||||
<%= number_field_tag field.call('poll_seconds'), s.poll_seconds, id: 'qbo_labels_poll', min: 1, max: 60, style: 'width: 5em' %>
|
||||
<em class="info"><%= l(:text_qbo_labels_poll_seconds) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_labels_expiry"><%= l(:field_qbo_labels_job_expiry) %></label>
|
||||
<%= number_field_tag field.call('job_expiry_minutes'), s.job_expiry.in_minutes.round, id: 'qbo_labels_expiry', min: 1, max: 1440, style: 'width: 5em' %>
|
||||
<em class="info"><%= l(:text_qbo_labels_job_expiry) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_labels_log"><%= l(:field_qbo_labels_log_requests) %></label>
|
||||
<%= hidden_field_tag field.call('log_requests'), '0', id: nil %>
|
||||
<%= check_box_tag field.call('log_requests'), '1', s.log_requests?, id: 'qbo_labels_log' %>
|
||||
<em class="info"><%= l(:text_qbo_labels_log_requests) %></em>
|
||||
</p>
|
||||
</fieldset>
|
||||
@@ -0,0 +1,49 @@
|
||||
qbo-label-bold.ttf is DejaVu Sans Bold (https://dejavu-fonts.github.io/), cut down to Latin
|
||||
letters (Basic Latin, Latin-1, Latin Extended-A) without kerning or hinting, so the print
|
||||
dialog's preview and the print agent's labels come out the same.
|
||||
|
||||
Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.
|
||||
Bitstream Vera is a trademark of Bitstream, Inc.
|
||||
DejaVu changes are in public domain.
|
||||
License: bitstream-vera
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of the fonts accompanying this license ("Fonts") and associated
|
||||
documentation files (the "Font Software"), to reproduce and distribute the
|
||||
Font Software, including without limitation the rights to use, copy, merge,
|
||||
publish, distribute, and/or sell copies of the Font Software, and to permit
|
||||
persons to whom the Font Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice shall
|
||||
be included in all copies of one or more of the Font Software typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in particular
|
||||
the designs of glyphs or characters in the Fonts may be modified and
|
||||
additional glyphs or characters may be added to the Fonts, only if the fonts
|
||||
are renamed to names not containing either the words "Bitstream" or the word
|
||||
"Vera".
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts or Font
|
||||
Software that has been modified and is distributed under the "Bitstream
|
||||
Vera" names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but no
|
||||
copy of one or more of the Font Software typefaces may be sold by itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
|
||||
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
|
||||
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
|
||||
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
|
||||
FONT SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the names of Gnome, the Gnome
|
||||
Foundation, and Bitstream Inc., shall not be used in advertising or
|
||||
otherwise to promote the sale, use or other dealings in this Font Software
|
||||
without prior written authorization from the Gnome Foundation or Bitstream
|
||||
Inc., respectively. For further information, contact: fonts at gnome dot
|
||||
org.
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<!-- Label printing icons (Tabler outline icons, MIT), in the layout of Redmine's own sprite -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon--sprite">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-label-print">
|
||||
<path d="M17 17h2a2 2 0 0 0 2 -2v-4a2 2 0 0 0 -2 -2h-14a2 2 0 0 0 -2 2v4a2 2 0 0 0 2 2h2"/>
|
||||
<path d="M17 9v-4a2 2 0 0 0 -2 -2h-6a2 2 0 0 0 -2 2v4"/>
|
||||
<path d="M7 15a2 2 0 0 1 2 -2h6a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-6a2 2 0 0 1 -2 -2z"/>
|
||||
</symbol>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 581 B |
@@ -0,0 +1,238 @@
|
||||
/*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2026 rick barrette
|
||||
*
|
||||
* Print label dialog (redmine_qbo_labels): draws a preview of the label the way the print agent draws it,
|
||||
* then follows the print job until it's printed.
|
||||
*
|
||||
* Label layout (keep in step with the agent's label.py): the label runs along a 62mm continuous roll at
|
||||
* 300 dpi, so it's 696 dots tall and as long as its text needs, between the minimum and maximum length.
|
||||
* The lines are stacked, left aligned, each in the largest bold letters that fit.
|
||||
*/
|
||||
var QboLabels = (function($) {
|
||||
'use strict';
|
||||
|
||||
var LAYOUT = {
|
||||
dpi: 300,
|
||||
height: 696, // printable dots across a 62mm roll
|
||||
marginX: 36, // ~3mm at each end
|
||||
marginY: 24, // ~2mm top and bottom
|
||||
gapRatio: 0.12, // space between lines, as a share of the (smallest) font size
|
||||
minSize: 8,
|
||||
maxSize: 700,
|
||||
sameSizeWithin: 1.25, // lines whose biggest sizes are this close are drawn the same size
|
||||
font: 'QboLabel'
|
||||
};
|
||||
|
||||
var pollTimer = null;
|
||||
var following = null;
|
||||
|
||||
function mmToDots(mm) {
|
||||
return Math.round(mm / 25.4 * LAYOUT.dpi);
|
||||
}
|
||||
|
||||
function fontAt(size) {
|
||||
return '700 ' + size + 'px ' + LAYOUT.font + ', "DejaVu Sans", Arial, sans-serif';
|
||||
}
|
||||
|
||||
// A line's ink at a font size: { left, right, ascent, descent, width, height }
|
||||
function box(ctx, text, size) {
|
||||
ctx.font = fontAt(size);
|
||||
var m = ctx.measureText(text);
|
||||
var left = m.actualBoundingBoxLeft || 0, right = m.actualBoundingBoxRight || m.width;
|
||||
var ascent = m.actualBoundingBoxAscent || size * 0.73, descent = m.actualBoundingBoxDescent || 0;
|
||||
return { left: left, right: right, ascent: ascent, descent: descent,
|
||||
width: left + right, height: ascent + descent };
|
||||
}
|
||||
|
||||
// The largest font size from minSize to maxSize that passes the test (minSize if none does)
|
||||
function largest(test) {
|
||||
var lo = LAYOUT.minSize, hi = LAYOUT.maxSize;
|
||||
while (lo < hi) {
|
||||
var mid = Math.floor((lo + hi + 1) / 2);
|
||||
if (test(mid)) { lo = mid; } else { hi = mid - 1; }
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
function gapFor(sizes) {
|
||||
return Math.round(Math.min.apply(null, sizes) * LAYOUT.gapRatio);
|
||||
}
|
||||
|
||||
function totalHeight(ctx, lines, sizes) {
|
||||
return lines.reduce(function(sum, text, i) { return sum + box(ctx, text, sizes[i]).height; }, 0) +
|
||||
gapFor(sizes) * (lines.length - 1);
|
||||
}
|
||||
|
||||
// Each line's font size and box, and the label's length in dots. Every line is as big as it can be: no
|
||||
// wider than the longest label allows, and together no taller than the roll. Lines that would come out
|
||||
// about the same size are made the same size; when one is held back by its length (a long name), the
|
||||
// others still grow to fill the height.
|
||||
function layout(ctx, lines, minLengthMm, maxLengthMm) {
|
||||
var maxLength = mmToDots(maxLengthMm), minLength = mmToDots(minLengthMm);
|
||||
var maxWidth = maxLength - 2 * LAYOUT.marginX, maxHeight = LAYOUT.height - 2 * LAYOUT.marginY;
|
||||
|
||||
var limits = lines.map(function(text) {
|
||||
return largest(function(size) {
|
||||
var b = box(ctx, text, size);
|
||||
return b.width <= maxWidth && b.height <= maxHeight;
|
||||
});
|
||||
});
|
||||
function sizesAt(cap) { return limits.map(function(limit) { return Math.min(cap, limit); }); }
|
||||
|
||||
var cap = largest(function(c) { return totalHeight(ctx, lines, sizesAt(c)) <= maxHeight; });
|
||||
var sizes = sizesAt(cap);
|
||||
var smallest = Math.min.apply(null, sizes);
|
||||
if (Math.max.apply(null, sizes) < smallest * LAYOUT.sameSizeWithin) {
|
||||
sizes = sizes.map(function() { return smallest; });
|
||||
}
|
||||
|
||||
var boxes = lines.map(function(text, i) { return box(ctx, text, sizes[i]); });
|
||||
var width = Math.max.apply(null, boxes.map(function(b) { return b.width; }));
|
||||
var length = Math.min(maxLength, Math.max(minLength, Math.ceil(width + 2 * LAYOUT.marginX)));
|
||||
return { sizes: sizes, boxes: boxes, length: length };
|
||||
}
|
||||
|
||||
function draw(canvas, lines, opts) {
|
||||
var ctx = canvas.getContext('2d');
|
||||
if (!lines.length) {
|
||||
canvas.width = mmToDots(opts.minLengthMm); canvas.height = LAYOUT.height;
|
||||
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
return null;
|
||||
}
|
||||
var result = layout(ctx, lines, opts.minLengthMm, opts.maxLengthMm);
|
||||
canvas.width = result.length;
|
||||
canvas.height = LAYOUT.height;
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.textBaseline = 'alphabetic';
|
||||
|
||||
var gap = gapFor(result.sizes);
|
||||
var total = result.boxes.reduce(function(sum, b) { return sum + b.height; }, 0) + gap * (lines.length - 1);
|
||||
var y = Math.round((LAYOUT.height - total) / 2);
|
||||
lines.forEach(function(text, i) {
|
||||
var b = result.boxes[i];
|
||||
ctx.font = fontAt(result.sizes[i]);
|
||||
ctx.fillText(text, LAYOUT.marginX + b.left, y + b.ascent);
|
||||
y += b.height + gap;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
function dialog() { return $('#qbo-label-dialog'); }
|
||||
|
||||
function currentLines($dialog) {
|
||||
var upper = $dialog.data('uppercase') === true || $dialog.data('uppercase') === 'true';
|
||||
return $dialog.find('.qbo-label-line').map(function() {
|
||||
var text = $.trim($(this).val()).replace(/\s+/g, ' ');
|
||||
return upper ? text.toUpperCase() : text;
|
||||
}).get().filter(function(text) { return text.length > 0; });
|
||||
}
|
||||
|
||||
function redraw() {
|
||||
var $dialog = dialog();
|
||||
var canvas = $dialog.find('canvas.qbo-label-preview')[0];
|
||||
if (!canvas) { return; }
|
||||
var lines = currentLines($dialog);
|
||||
var result = draw(canvas, lines, {
|
||||
minLengthMm: parseFloat($dialog.data('min-length-mm')),
|
||||
maxLengthMm: parseFloat($dialog.data('max-length-mm'))
|
||||
});
|
||||
var inches = (canvas.width / LAYOUT.dpi).toFixed(1);
|
||||
$dialog.find('.qbo-label-size').text(result ? '2.4 × ' + inches + ' in' : '');
|
||||
$dialog.find('.qbo-label-submit').prop('disabled', !result);
|
||||
}
|
||||
|
||||
function initDialog() {
|
||||
var $dialog = dialog();
|
||||
stopFollowing();
|
||||
$dialog.on('input change', '.qbo-label-line', redraw);
|
||||
redraw();
|
||||
// Redraw once the label font has loaded (the first draw may use a fallback font)
|
||||
if (document.fonts && document.fonts.load) {
|
||||
document.fonts.load(fontAt(100), 'A').then(function() { redraw(); }, function() {});
|
||||
}
|
||||
$dialog.find('.qbo-label-line').first().trigger('focus');
|
||||
// Stop following the job when the dialog is closed
|
||||
$('#ajax-modal').off('dialogclose.qboLabels').on('dialogclose.qboLabels', stopFollowing);
|
||||
}
|
||||
|
||||
function setStatus(text, state) {
|
||||
var $status = dialog().find('.qbo-label-status');
|
||||
$status.prop('hidden', false).attr('data-state', state || 'working');
|
||||
$status.find('.qbo-label-status-text').text(text);
|
||||
$status.find('.qbo-label-again').toggle(state === 'printed' || state === 'failed');
|
||||
}
|
||||
|
||||
function stopFollowing() {
|
||||
if (pollTimer) { clearTimeout(pollTimer); }
|
||||
pollTimer = null;
|
||||
following = null;
|
||||
}
|
||||
|
||||
// Follows a print job until it's printed, failed or expired
|
||||
function follow(job) {
|
||||
var $dialog = dialog();
|
||||
stopFollowing();
|
||||
following = { url: job.url, errors: 0 };
|
||||
// .hide(): Redmine's styles show forms whatever their hidden attribute says
|
||||
$dialog.find('#qbo-label-form').hide();
|
||||
setStatus(job.printer_online ? $dialog.data('text-printing') : $dialog.data('text-offline'));
|
||||
poll(following);
|
||||
}
|
||||
|
||||
function poll(state) {
|
||||
if (following !== state) { return; }
|
||||
$.ajax({ url: state.url, dataType: 'json', cache: false }).done(function(data) {
|
||||
if (following !== state) { return; }
|
||||
state.errors = 0;
|
||||
if (data.finished) {
|
||||
var text = data.status_label + (data.error ? ': ' + data.error : '');
|
||||
setStatus(text, data.status === 'printed' ? 'printed' : 'failed');
|
||||
stopFollowing();
|
||||
return;
|
||||
}
|
||||
var $dialog = dialog();
|
||||
if (data.status === 'printing') {
|
||||
setStatus($dialog.data('text-printing'));
|
||||
} else {
|
||||
setStatus(data.printer_online ? $dialog.data('text-waiting') : $dialog.data('text-offline'));
|
||||
}
|
||||
pollTimer = setTimeout(function() { poll(state); }, 1000);
|
||||
}).fail(function() {
|
||||
if (following !== state) { return; }
|
||||
state.errors += 1;
|
||||
if (state.errors >= 5) {
|
||||
setStatus(dialog().data('text-lost'), 'failed');
|
||||
stopFollowing();
|
||||
} else {
|
||||
pollTimer = setTimeout(function() { poll(state); }, 2000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Back to the form, to print the label again or another one
|
||||
function again() {
|
||||
var $dialog = dialog();
|
||||
stopFollowing();
|
||||
$dialog.find('.qbo-label-status').prop('hidden', true);
|
||||
$dialog.find('#qbo-label-form').show().find('.qbo-label-submit').prop('disabled', false);
|
||||
redraw();
|
||||
}
|
||||
|
||||
// Moves the issue's Print label link into its top-right actions, before the "..." menu
|
||||
function placeIssueLink(selector) {
|
||||
var template = $(selector)[0];
|
||||
if (!template) { return; }
|
||||
var $menu = $('#content > .contextual').not('.next-prev-links').first();
|
||||
if (!$menu.length) { return; }
|
||||
var $link = $(document.importNode(template.content, true));
|
||||
var $drdn = $menu.children('.drdn');
|
||||
if ($drdn.length) { $drdn.first().before($link); } else { $menu.append($link); }
|
||||
}
|
||||
|
||||
return { initDialog: initDialog, follow: follow, again: again, placeIssueLink: placeIssueLink,
|
||||
layout: layout, LAYOUT: LAYOUT };
|
||||
})(jQuery);
|
||||
@@ -0,0 +1,102 @@
|
||||
/* Print label dialog (redmine_qbo_labels) */
|
||||
|
||||
/* The label font, also used by the print agent (DejaVu Sans Bold, Latin subset; see assets/fonts/LICENSE) */
|
||||
@font-face {
|
||||
font-family: 'QboLabel';
|
||||
src: url('../fonts/qbo-label-bold.ttf') format('truetype');
|
||||
font-weight: 700;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .qbo-label-preview-wrap {
|
||||
margin: 0 0 1em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* The label as it comes off the roll, scaled to the dialog */
|
||||
#qbo-label-dialog canvas.qbo-label-preview {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
max-width: 100%;
|
||||
max-height: 160px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
background: #fff;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, .15);
|
||||
}
|
||||
|
||||
#qbo-label-dialog .qbo-label-size {
|
||||
margin-top: .3em;
|
||||
color: #888;
|
||||
font-size: .9em;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .tabular p {
|
||||
padding-left: 130px;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .tabular label {
|
||||
width: 120px;
|
||||
margin-left: -130px;
|
||||
}
|
||||
|
||||
#qbo-label-dialog input.qbo-label-line {
|
||||
width: 95%;
|
||||
font-weight: bold;
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
#qbo-label-dialog input.qbo-label-copies {
|
||||
width: 5em;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .qbo-label-warning,
|
||||
#qbo-label-dialog .qbo-label-status[data-state="failed"] .qbo-label-status-text {
|
||||
color: #c22;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .qbo-label-status-text {
|
||||
font-size: 1.2em;
|
||||
text-align: center;
|
||||
padding: .5em 0;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .qbo-label-status[data-state="printed"] .qbo-label-status-text {
|
||||
color: #1a7f37;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#qbo-label-dialog .qbo-label-status[data-state="working"] .qbo-label-status-text::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: .8em;
|
||||
height: .8em;
|
||||
margin-right: .5em;
|
||||
border: 2px solid currentColor;
|
||||
border-right-color: transparent;
|
||||
border-radius: 50%;
|
||||
vertical-align: -1px;
|
||||
animation: qbo-label-spin .8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes qbo-label-spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Administration » Label printers */
|
||||
table.label-printers .status-online { color: #1a7f37; font-weight: bold; }
|
||||
table.label-printers .status-offline { color: #c22; }
|
||||
table.label-printers .qbo-label-muted { color: #888; font-style: italic; }
|
||||
table.label-jobs td.lines { font-weight: bold; white-space: nowrap; }
|
||||
table.label-jobs td.status-failed,
|
||||
table.label-jobs td.status-expired { color: #c22; }
|
||||
table.label-jobs td.status-printed { color: #1a7f37; }
|
||||
pre.qbo-label-token { white-space: pre-wrap; word-break: break-all; }
|
||||
|
||||
@media screen and (max-width: 899px) {
|
||||
#qbo-label-dialog .tabular p { padding-left: 0; }
|
||||
#qbo-label-dialog .tabular label { width: auto; margin-left: 0; display: block; text-align: left; float: none; }
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# English strings go here for Rails i18n
|
||||
en:
|
||||
# Permission (Roles and permissions)
|
||||
permission_print_labels: "Print labels"
|
||||
|
||||
label_label_printer_plural: "Label printers"
|
||||
label_qbo_labels_new_printer: "New label printer"
|
||||
label_qbo_labels_print_title: "Print label"
|
||||
label_qbo_labels_preview: "Label preview"
|
||||
label_qbo_labels_online: "Online"
|
||||
label_qbo_labels_offline: "offline"
|
||||
label_qbo_labels_agent_version: "Agent %{version}"
|
||||
label_qbo_labels_printer_not_found: "No printer found yet"
|
||||
label_qbo_labels_recent_jobs: "Recent labels"
|
||||
label_qbo_labels_label_settings: "Labels"
|
||||
label_qbo_labels_agent_settings: "Print agents"
|
||||
label_qbo_labels_inches: "inches"
|
||||
label_qbo_labels_source_issue: "Work order"
|
||||
label_qbo_labels_source_estimate: "Estimate"
|
||||
label_qbo_labels_source_invoice: "Invoice"
|
||||
label_qbo_labels_status_queued: "Waiting for the printer"
|
||||
label_qbo_labels_status_printing: "Printing"
|
||||
label_qbo_labels_status_printed: "Printed"
|
||||
label_qbo_labels_status_failed: "Failed"
|
||||
label_qbo_labels_status_expired: "Not printed"
|
||||
|
||||
field_qbo_labels_name: "Name"
|
||||
field_qbo_labels_po_number: "PO number"
|
||||
field_qbo_labels_copies: "Copies"
|
||||
field_qbo_labels_printer: "Printer"
|
||||
field_qbo_labels_agent: "Print agent"
|
||||
field_qbo_labels_last_seen: "Last seen"
|
||||
field_qbo_labels_label: "Label"
|
||||
field_qbo_labels_for: "For"
|
||||
field_qbo_labels_token: "Agent token"
|
||||
field_qbo_labels_length: "Label length"
|
||||
field_qbo_labels_uppercase: "Capital letters"
|
||||
field_qbo_labels_poll_seconds: "Check for labels every"
|
||||
field_qbo_labels_job_expiry: "Give up on a label after"
|
||||
field_qbo_labels_log_requests: "Log label printer requests"
|
||||
|
||||
button_qbo_labels_print: "Print label"
|
||||
button_qbo_labels_print_another: "Print again"
|
||||
button_qbo_labels_new_token: "New token"
|
||||
|
||||
text_qbo_labels_printing: "Printing…"
|
||||
text_qbo_labels_waiting: "Sent, waiting for the printer…"
|
||||
text_qbo_labels_offline: "The printer's agent is offline. The label will print if it comes back within a few minutes…"
|
||||
text_qbo_labels_lost_contact: "Lost contact with Redmine. Check the printer before printing again."
|
||||
text_qbo_labels_no_printers: "There's no label printer set up yet (Administration » Label printers)."
|
||||
text_qbo_labels_no_printers_admin: "No label printers yet. Add one, then run the print agent on the printer's network with its token."
|
||||
text_qbo_labels_printer_offline: "%{name}'s print agent is offline: the label will wait a few minutes for it."
|
||||
text_qbo_labels_printer_name: "Shown in the print dialog when there's more than one printer, e.g. Parts room"
|
||||
text_qbo_labels_printer_active: "Inactive printers aren't offered for printing, and their agent can't sign in"
|
||||
text_qbo_labels_new_token_confirm: "The print agent stops working until it's given the new token. Continue?"
|
||||
text_qbo_labels_token_once: "Copy the token now: it isn't shown again. If it's lost, make a new one."
|
||||
text_qbo_labels_compose_intro: "Run the print agent on a computer on the printer's network, for example with Docker Compose:"
|
||||
text_qbo_labels_compose_after: "Once it's running, the printer shows as Online on the Label printers page, with the printer the agent found."
|
||||
text_qbo_labels_length: "Labels are as long as their text needs, from the shorter length up to the longer; long names get smaller letters to fit"
|
||||
text_qbo_labels_poll_seconds: "seconds (the agent picks this up within a poll)"
|
||||
text_qbo_labels_job_expiry: "minutes, when the printer's agent is offline, so labels don't print long after they were asked for"
|
||||
text_qbo_labels_log_requests: "Writes the print agents' polls and the print dialog's status checks to the Redmine log. Turn on to debug, off when done (they come every couple of seconds)."
|
||||
text_qbo_labels_job_expired: "The printer's agent didn't pick it up in time"
|
||||
text_qbo_labels_job_unconfirmed: "The printer's agent didn't say whether it printed"
|
||||
text_qbo_labels_job_failed: "The printer reported an error"
|
||||
|
||||
activerecord:
|
||||
errors:
|
||||
messages:
|
||||
qbo_labels_no_text: "The label has no text"
|
||||
qbo_labels_text_too_long: "The label can have up to 4 lines of %{count} characters"
|
||||
@@ -0,0 +1,27 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
RedmineApp::Application.routes.draw do
|
||||
|
||||
# Print label dialog
|
||||
resources :label_jobs, only: [:new, :create, :show]
|
||||
|
||||
# Administration » Label printers
|
||||
resources :label_printers, except: [:show] do
|
||||
member do
|
||||
post :regenerate_token
|
||||
end
|
||||
end
|
||||
|
||||
# Print agent API (token authenticated, see LabelAgentController)
|
||||
post 'label_agent/poll', to: 'label_agent#poll', as: :label_agent_poll
|
||||
post 'label_agent/jobs/:id/result', to: 'label_agent#result', as: :label_agent_result
|
||||
|
||||
end
|
||||
@@ -0,0 +1,30 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
class CreateLabelPrinters < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A label printer and the print agent on its network that prints its labels
|
||||
create_table :label_printers do |t|
|
||||
t.string :name, null: false
|
||||
t.boolean :active, null: false, default: true
|
||||
# SHA-256 of the agent's token (the token itself is only shown once)
|
||||
t.string :token_digest, null: false
|
||||
# What the agent last reported
|
||||
t.datetime :last_seen_at
|
||||
t.string :last_ip
|
||||
t.string :agent_version
|
||||
t.string :printer_model
|
||||
t.string :printer_address
|
||||
t.string :printer_status
|
||||
t.timestamps
|
||||
end
|
||||
add_index :label_printers, :token_digest, unique: true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
class CreateLabelJobs < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A label sent to a printer: queued until its agent picks it up, then printed or failed
|
||||
create_table :label_jobs do |t|
|
||||
t.references :label_printer, null: false
|
||||
t.references :user
|
||||
t.text :lines, null: false
|
||||
t.integer :copies, null: false, default: 1
|
||||
t.string :status, null: false, default: 'queued'
|
||||
t.text :error
|
||||
# The issue, estimate or invoice it's for
|
||||
t.string :source_type
|
||||
t.string :source_id
|
||||
t.datetime :claimed_at
|
||||
t.datetime :finished_at
|
||||
t.timestamps
|
||||
end
|
||||
add_index :label_jobs, [:label_printer_id, :status]
|
||||
add_index :label_jobs, :created_at
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,29 @@
|
||||
Redmine::Plugin.register :redmine_qbo_labels do
|
||||
|
||||
# About
|
||||
name 'Redmine QBO Labels plugin'
|
||||
author 'Rick Barrette'
|
||||
description 'Prints part labels (customer last name and document number) for issues, estimates and invoices on a Brother QL label printer, through a small print agent on the printer\'s network'
|
||||
version '2026.11.0'
|
||||
url 'https://github.com/rickbarrette/redmine_qbo_labels'
|
||||
author_url 'https://barrettefabrication.com'
|
||||
requires_redmine version_or_higher: '7.0.0'
|
||||
|
||||
# Customers, estimates and invoices live in redmine_qbo
|
||||
begin
|
||||
requires_redmine_plugin :redmine_qbo, version_or_higher: '2026.11.0'
|
||||
rescue Redmine::PluginNotFound
|
||||
raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)'
|
||||
end
|
||||
|
||||
settings default: RedmineQboLabels::Settings::DEFAULTS.dup, partial: 'settings/qbo_labels'
|
||||
|
||||
# Print label dialog, sending the label and following its print job
|
||||
permission :print_labels, { label_jobs: [:new, :create, :show] }, global: true
|
||||
|
||||
# Label printers (print agents) and their recent jobs
|
||||
menu :admin_menu, :label_printers, { controller: 'label_printers', action: 'index' },
|
||||
caption: :label_label_printer_plural, html: { class: 'icon icon-document' }
|
||||
end
|
||||
|
||||
RedmineQboLabels.setup
|
||||
@@ -0,0 +1,30 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
module RedmineQboLabels
|
||||
|
||||
def self.setup
|
||||
# Keep the print agent's 2-second polls (and the print dialog's status checks) out of the log unless
|
||||
# "Log label printer requests" is on
|
||||
Rails::Rack::Logger.prepend(RedmineQboLabels::RequestSilencer)
|
||||
|
||||
# Hooks
|
||||
RedmineQboLabels::Hooks::ViewHookListener
|
||||
|
||||
Rails.configuration.to_prepare do
|
||||
ApplicationController.prepend_view_path(File.expand_path('../app/views', __dir__))
|
||||
end
|
||||
end
|
||||
|
||||
# Whether the current user may print labels and there's a printer to print on
|
||||
def self.printing_available?
|
||||
User.current.allowed_to?(:print_labels, nil, global: true) && LabelPrinter.active.exists?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,52 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
module RedmineQboLabels
|
||||
module Hooks
|
||||
# "Print label" in the top-right actions of issues, estimates and invoices
|
||||
class ViewHookListener < Redmine::Hook::ViewListener
|
||||
|
||||
# The print dialog's script and styles
|
||||
def view_layouts_base_html_head(context = {})
|
||||
return '' unless User.current.logged?
|
||||
|
||||
stylesheet_link_tag('qbo_labels', plugin: 'redmine_qbo_labels') +
|
||||
javascript_include_tag('qbo_labels', plugin: 'redmine_qbo_labels')
|
||||
end
|
||||
|
||||
# An estimate's page (redmine_qbo's :view_qbo_estimate_contextual)
|
||||
def view_qbo_estimate_contextual(context = {})
|
||||
print_link(context, 'estimate', context[:estimate_id])
|
||||
end
|
||||
|
||||
# An invoice's page (redmine_qbo's :view_qbo_invoice_contextual)
|
||||
def view_qbo_invoice_contextual(context = {})
|
||||
print_link(context, 'invoice', context[:invoice_id])
|
||||
end
|
||||
|
||||
# An issue's page: Redmine has no hook in the issue's actions, so the link is moved there by script
|
||||
def view_issues_show_details_bottom(context = {})
|
||||
issue = context[:issue]
|
||||
return '' unless issue&.persisted? && RedmineQboLabels.printing_available?
|
||||
|
||||
context[:hook_caller].render(partial: 'label_hooks/issue_print_link', locals: { issue: issue })
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def print_link(context, source_type, source_id)
|
||||
return '' if source_id.blank? || !RedmineQboLabels.printing_available?
|
||||
|
||||
context[:hook_caller].render(partial: 'label_hooks/print_link',
|
||||
locals: { source_type: source_type, source_id: source_id })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,98 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
module RedmineQboLabels
|
||||
# What goes on a part label for an issue, estimate or invoice: the customer's last name and the PO number
|
||||
# parts are ordered with (Sales SOP): E + estimate number, I + invoice number, W + work order (issue) number
|
||||
class LabelSource
|
||||
TYPES = %w[issue estimate invoice].freeze
|
||||
PREFIXES = { 'issue' => 'W', 'estimate' => 'E', 'invoice' => 'I' }.freeze
|
||||
NAME_SUFFIXES = /\A(jr|sr|ii|iii|iv|v|esq)\.?\z/i
|
||||
|
||||
attr_reader :type, :record
|
||||
|
||||
# The issue, estimate or invoice the current user may see, or nil
|
||||
def self.find(type, id)
|
||||
type = type.to_s
|
||||
return nil unless TYPES.include?(type)
|
||||
|
||||
record = case type
|
||||
when 'issue' then Issue.visible.find_by(id: id)
|
||||
when 'estimate' then Estimate.find_by(id: id) if billing_visible?(:write_estimates)
|
||||
when 'invoice' then Invoice.find_by(id: id) if billing_visible?(:write_invoices)
|
||||
end
|
||||
record && new(type, record)
|
||||
end
|
||||
|
||||
# Estimates and invoices are seen by those who view customers or write them (redmine_qbo's permissions)
|
||||
def self.billing_visible?(write_permission, user = User.current)
|
||||
[:view_customers, write_permission].any? { |permission| user.allowed_to?(permission, nil, global: true) }
|
||||
end
|
||||
private_class_method :billing_visible?
|
||||
|
||||
def initialize(type, record)
|
||||
@type = type
|
||||
@record = record
|
||||
end
|
||||
|
||||
def id
|
||||
record.id
|
||||
end
|
||||
|
||||
def customer
|
||||
record.respond_to?(:customer) ? record.customer : nil
|
||||
end
|
||||
|
||||
# E1234, I1234 or W1234
|
||||
def po_number
|
||||
number = type == 'issue' ? record.id : record.doc_number
|
||||
"#{PREFIXES[type]}#{number}"
|
||||
end
|
||||
|
||||
def last_name
|
||||
self.class.last_name(customer)
|
||||
end
|
||||
|
||||
# The label's lines, as they are printed unless changed in the print dialog
|
||||
def lines
|
||||
[last_name, po_number]
|
||||
end
|
||||
|
||||
# Shown in the job list: "Estimate #1234"
|
||||
def title
|
||||
number = type == 'issue' ? record.id : record.doc_number
|
||||
"#{I18n.t("label_qbo_labels_source_#{type}")} ##{number}"
|
||||
end
|
||||
|
||||
# The customer's last name: their family name in QuickBooks, or for a business their full name, or else
|
||||
# the last word of their name (skipping Jr., III, ...)
|
||||
def self.last_name(customer)
|
||||
return '' unless customer
|
||||
|
||||
details = qbo_details(customer)
|
||||
family = details&.family_name.to_s.strip
|
||||
return family if family.present?
|
||||
return customer.name.to_s if details&.company_name.present?
|
||||
|
||||
words = customer.name.to_s.split
|
||||
words.pop while words.size > 1 && words.last.match?(NAME_SUFFIXES)
|
||||
words.last.to_s
|
||||
end
|
||||
|
||||
# QuickBooks' copy of the customer (cached by redmine_qbo); nil when QuickBooks can't be reached
|
||||
def self.qbo_details(customer)
|
||||
customer.details
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "[redmine_qbo_labels] QuickBooks details for customer #{customer.id}: #{e.message}"
|
||||
nil
|
||||
end
|
||||
private_class_method :qbo_details
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
module RedmineQboLabels
|
||||
# Prepended to Rails::Rack::Logger: the print agent asks for labels every couple of seconds, and the print
|
||||
# dialog checks on its label every second, which would fill the log. Those requests are only logged (and
|
||||
# their SQL) when "Log label printer requests" is on; warnings (e.g. an agent with a wrong token) and errors
|
||||
# are always logged.
|
||||
module RequestSilencer
|
||||
QUIET_PATHS = %r{\A/(label_agent/|label_jobs/\d+(\.json)?\z)}
|
||||
|
||||
def call(env)
|
||||
return super unless quiet?(env)
|
||||
|
||||
logger.silence(::Logger::WARN) { super }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def quiet?(env)
|
||||
env['PATH_INFO'].to_s.match?(QUIET_PATHS) && !RedmineQboLabels::Settings.log_requests?
|
||||
rescue StandardError
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
module RedmineQboLabels
|
||||
# The plugin's settings (Administration » Plugins » Redmine QBO Labels plugin » Configure)
|
||||
module Settings
|
||||
DEFAULTS = {
|
||||
# Labels run along a 62mm (2.4in) continuous roll; their length fits the text, between these (inches)
|
||||
'max_length_in' => '4',
|
||||
'min_length_in' => '1',
|
||||
'uppercase' => '1',
|
||||
# A label still waiting this long (the agent is offline) is dropped, so it doesn't print hours later
|
||||
'job_expiry_minutes' => '10',
|
||||
# How often the print agent asks for labels (seconds)
|
||||
'poll_seconds' => '2',
|
||||
# Write the agent's polls and the print dialog's status checks to the Redmine log (for debugging)
|
||||
'log_requests' => '0'
|
||||
}.freeze
|
||||
|
||||
MM_PER_INCH = 25.4
|
||||
|
||||
def self.values
|
||||
DEFAULTS.merge((Setting.plugin_redmine_qbo_labels.presence || {}).to_h.stringify_keys)
|
||||
end
|
||||
|
||||
def self.max_length_in
|
||||
clamp(values['max_length_in'], DEFAULTS['max_length_in'], 1.0, 12.0)
|
||||
end
|
||||
|
||||
def self.min_length_in
|
||||
[clamp(values['min_length_in'], DEFAULTS['min_length_in'], 0.5, 12.0), max_length_in].min
|
||||
end
|
||||
|
||||
def self.max_length_mm
|
||||
(max_length_in * MM_PER_INCH).round(1)
|
||||
end
|
||||
|
||||
def self.min_length_mm
|
||||
(min_length_in * MM_PER_INCH).round(1)
|
||||
end
|
||||
|
||||
def self.uppercase?
|
||||
values['uppercase'].to_s == '1'
|
||||
end
|
||||
|
||||
def self.job_expiry
|
||||
clamp(values['job_expiry_minutes'], DEFAULTS['job_expiry_minutes'], 1, 1440).minutes
|
||||
end
|
||||
|
||||
def self.poll_seconds
|
||||
clamp(values['poll_seconds'], DEFAULTS['poll_seconds'], 1, 60)
|
||||
end
|
||||
|
||||
def self.log_requests?
|
||||
values['log_requests'].to_s == '1'
|
||||
end
|
||||
|
||||
def self.clamp(value, default, min, max)
|
||||
number = Float(value.to_s, exception: false) || Float(default)
|
||||
number = number.clamp(min, max)
|
||||
min.is_a?(Integer) ? number.round : number
|
||||
end
|
||||
private_class_method :clamp
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,110 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class LabelAgentApiTest < Redmine::IntegrationTest
|
||||
include QboLabelsTestHelper
|
||||
fixtures :users
|
||||
|
||||
def setup
|
||||
@printer, @token = create_printer
|
||||
end
|
||||
|
||||
def headers(token = @token)
|
||||
{ 'Authorization' => "Bearer #{token}", 'CONTENT_TYPE' => 'application/json' }
|
||||
end
|
||||
|
||||
def test_unknown_token_is_refused
|
||||
post '/label_agent/poll', params: '{}', headers: headers('qbl_wrong')
|
||||
assert_response :unauthorized
|
||||
post '/label_agent/poll', params: '{}'
|
||||
assert_response :unauthorized
|
||||
end
|
||||
|
||||
def test_poll_without_labels
|
||||
post '/label_agent/poll', params: '{}', headers: headers
|
||||
assert_response :success
|
||||
json = response.parsed_body
|
||||
assert_nil json['job']
|
||||
assert_equal 2, json['poll_seconds']
|
||||
assert @printer.reload.online?
|
||||
end
|
||||
|
||||
def test_poll_hands_out_the_next_label
|
||||
job = create_job(@printer, copies: 2)
|
||||
post '/label_agent/poll', params: '{}', headers: headers
|
||||
assert_response :success
|
||||
json = response.parsed_body['job']
|
||||
assert_equal job.id, json['id']
|
||||
assert_equal %w[SMITH E1234], json['lines']
|
||||
assert_equal 2, json['copies']
|
||||
assert_equal 'printing', job.reload.status
|
||||
|
||||
post '/label_agent/poll', params: '{}', headers: headers
|
||||
assert_nil response.parsed_body['job']
|
||||
end
|
||||
|
||||
def test_poll_records_what_the_agent_says
|
||||
post '/label_agent/poll', headers: headers,
|
||||
params: { agent: { version: '2026.11.0', printer_model: 'QL-820NWB', printer_address: '192.168.0.100:9100',
|
||||
printer_status: 'Ready, 62mm continuous', other: 'x' } }.to_json
|
||||
assert_response :success
|
||||
@printer.reload
|
||||
assert_equal '2026.11.0', @printer.agent_version
|
||||
assert_equal 'QL-820NWB', @printer.printer_model
|
||||
assert_equal 'Ready, 62mm continuous', @printer.printer_status
|
||||
end
|
||||
|
||||
def test_result_marks_the_label_printed_or_failed
|
||||
job = create_job(@printer)
|
||||
LabelJob.claim_next(@printer)
|
||||
post "/label_agent/jobs/#{job.id}/result", params: { status: 'printed' }.to_json, headers: headers
|
||||
assert_response :success
|
||||
assert_equal 'printed', job.reload.status
|
||||
|
||||
# A repeated report changes nothing
|
||||
post "/label_agent/jobs/#{job.id}/result", params: { status: 'failed', error: 'x' }.to_json, headers: headers
|
||||
assert_response :success
|
||||
assert_equal 'printed', job.reload.status
|
||||
|
||||
job = create_job(@printer)
|
||||
post "/label_agent/jobs/#{job.id}/result", params: { status: 'failed', error: 'Error: No media' }.to_json,
|
||||
headers: headers
|
||||
assert_equal 'failed', job.reload.status
|
||||
assert_equal 'Error: No media', job.error
|
||||
end
|
||||
|
||||
def test_an_agent_only_reports_on_its_own_printers_labels
|
||||
other, = create_printer(name: 'Shop')
|
||||
job = create_job(other)
|
||||
post "/label_agent/jobs/#{job.id}/result", params: { status: 'printed' }.to_json, headers: headers
|
||||
assert_response :not_found
|
||||
assert_equal 'queued', job.reload.status
|
||||
end
|
||||
|
||||
def test_polls_stay_out_of_the_log_unless_turned_on
|
||||
io = StringIO.new
|
||||
logger = ActiveSupport::Logger.new(io)
|
||||
previous = Rails.logger
|
||||
Rails.logger = ActiveSupport::BroadcastLogger.new(logger)
|
||||
begin
|
||||
post '/label_agent/poll', params: '{}', headers: headers
|
||||
assert_not_includes io.string, '/label_agent/poll'
|
||||
|
||||
with_label_settings('log_requests' => '1') do
|
||||
post '/label_agent/poll', params: '{}', headers: headers
|
||||
end
|
||||
assert_includes io.string, 'Parts room agent'
|
||||
ensure
|
||||
Rails.logger = previous
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,92 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class LabelJobsTest < Redmine::IntegrationTest
|
||||
include QboLabelsTestHelper
|
||||
fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
|
||||
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows
|
||||
|
||||
def setup
|
||||
@printer, = create_printer
|
||||
Role.find(1).add_permission!(:print_labels)
|
||||
end
|
||||
|
||||
def test_print_dialog_for_an_issue
|
||||
log_user('jsmith', 'jsmith')
|
||||
get '/label_jobs/new', params: { source_type: 'issue', source_id: 1 }, xhr: true
|
||||
assert_response :success
|
||||
assert_includes response.body, 'W1'
|
||||
assert_includes response.body, 'qbo-label-preview'
|
||||
end
|
||||
|
||||
def test_printing_needs_the_permission
|
||||
log_user('dlopper', 'foo') # Developer: no Print labels
|
||||
get '/label_jobs/new', params: { source_type: 'issue', source_id: 1 }, xhr: true
|
||||
assert_response :forbidden
|
||||
end
|
||||
|
||||
def test_print_dialog_for_something_unseen
|
||||
log_user('jsmith', 'jsmith')
|
||||
get '/label_jobs/new', params: { source_type: 'issue', source_id: 999 }, xhr: true
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_print_queues_the_label
|
||||
log_user('jsmith', 'jsmith')
|
||||
assert_difference 'LabelJob.count', 1 do
|
||||
post '/label_jobs', params: { source_type: 'issue', source_id: 1, lines: ['Smith', 'w1'], copies: '2' }, xhr: true
|
||||
end
|
||||
assert_response :success
|
||||
job = LabelJob.last
|
||||
assert_equal %w[SMITH W1], job.lines
|
||||
assert_equal 2, job.copies
|
||||
assert_equal @printer, job.label_printer
|
||||
assert_equal 'issue', job.source_type
|
||||
assert_equal '1', job.source_id
|
||||
assert_includes response.body, "QboLabels.follow"
|
||||
|
||||
get "/label_jobs/#{job.id}", headers: { "Accept" => "application/json" }
|
||||
assert_response :success
|
||||
assert_equal 'queued', response.parsed_body['status']
|
||||
assert_equal false, response.parsed_body['finished']
|
||||
end
|
||||
|
||||
def test_an_empty_label_shows_the_dialog_again
|
||||
log_user('jsmith', 'jsmith')
|
||||
assert_no_difference 'LabelJob.count' do
|
||||
post '/label_jobs', params: { source_type: 'issue', source_id: 1, lines: ['', ' '] }, xhr: true
|
||||
end
|
||||
assert_response :success
|
||||
assert_includes response.body, 'errorExplanation'
|
||||
end
|
||||
|
||||
def test_only_your_own_labels_can_be_followed
|
||||
job = create_job(@printer, user: User.find(3))
|
||||
log_user('jsmith', 'jsmith')
|
||||
get "/label_jobs/#{job.id}", headers: { "Accept" => "application/json" }
|
||||
assert_response :not_found
|
||||
end
|
||||
|
||||
def test_issue_page_has_the_print_label_link
|
||||
log_user('jsmith', 'jsmith')
|
||||
get '/issues/1'
|
||||
assert_response :success
|
||||
assert_select 'template#qbo-label-issue-link a.icon-qbo-label-print[data-remote=true]'
|
||||
end
|
||||
|
||||
def test_no_link_without_an_active_printer
|
||||
@printer.update!(active: false)
|
||||
log_user('jsmith', 'jsmith')
|
||||
get '/issues/1'
|
||||
assert_select 'template#qbo-label-issue-link', 0
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,48 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class LabelPrintersTest < Redmine::IntegrationTest
|
||||
include QboLabelsTestHelper
|
||||
fixtures :users, :email_addresses
|
||||
|
||||
def test_admins_add_a_printer_and_see_its_token_once
|
||||
log_user('admin', 'admin')
|
||||
get '/label_printers'
|
||||
assert_response :success
|
||||
|
||||
assert_difference 'LabelPrinter.count', 1 do
|
||||
post '/label_printers', params: { label_printer: { name: 'Parts room', active: '1' } }
|
||||
end
|
||||
assert_response :success
|
||||
token = css_select('pre.qbo-label-token').first.text.strip
|
||||
assert LabelPrinter.authenticate(token)
|
||||
assert_includes response.body, 'AGENT_TOKEN'
|
||||
assert_equal 'no-store', response.headers['Cache-Control']
|
||||
|
||||
get '/label_printers'
|
||||
assert_not_includes response.body, token
|
||||
end
|
||||
|
||||
def test_new_token
|
||||
printer, token = create_printer
|
||||
log_user('admin', 'admin')
|
||||
post "/label_printers/#{printer.id}/regenerate_token"
|
||||
assert_response :success
|
||||
assert_nil LabelPrinter.authenticate(token)
|
||||
end
|
||||
|
||||
def test_admins_only
|
||||
log_user('jsmith', 'jsmith')
|
||||
get '/label_printers'
|
||||
assert_response :forbidden
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,41 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
# Load the Redmine helper
|
||||
require File.expand_path('../../../test/test_helper', __dir__)
|
||||
|
||||
module QboLabelsTestHelper
|
||||
# Start from no printers or labels (inside the test's transaction)
|
||||
def self.included(base)
|
||||
base.setup do
|
||||
LabelJob.delete_all
|
||||
LabelPrinter.delete_all
|
||||
end
|
||||
end
|
||||
|
||||
def create_printer(name: 'Parts room', active: true)
|
||||
printer = LabelPrinter.new(name: name, active: active)
|
||||
token = printer.generate_token
|
||||
printer.save!
|
||||
[printer, token]
|
||||
end
|
||||
|
||||
def create_job(printer, lines: %w[SMITH E1234], status: 'queued', user: User.find(2), **attributes)
|
||||
LabelJob.create!({ label_printer: printer, user: user, lines: lines, status: status }.merge(attributes))
|
||||
end
|
||||
|
||||
def with_label_settings(values)
|
||||
saved = Setting.plugin_redmine_qbo_labels
|
||||
Setting.plugin_redmine_qbo_labels = RedmineQboLabels::Settings::DEFAULTS.merge(values)
|
||||
yield
|
||||
ensure
|
||||
Setting.plugin_redmine_qbo_labels = saved
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,111 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class LabelJobTest < ActiveSupport::TestCase
|
||||
include QboLabelsTestHelper
|
||||
fixtures :users
|
||||
|
||||
def setup
|
||||
@printer, = create_printer
|
||||
end
|
||||
|
||||
def test_lines_are_tidied_and_capitalized
|
||||
job = create_job(@printer, lines: [' Smith ', '', 'e1234'])
|
||||
assert_equal %w[SMITH E1234], job.lines
|
||||
assert_equal %w[SMITH E1234], job.reload.lines
|
||||
end
|
||||
|
||||
def test_capitals_can_be_turned_off
|
||||
with_label_settings('uppercase' => '0') do
|
||||
assert_equal %w[Smith E1234], create_job(@printer, lines: %w[Smith E1234]).lines
|
||||
end
|
||||
end
|
||||
|
||||
def test_a_label_needs_text_that_fits
|
||||
assert_not LabelJob.new(label_printer: @printer, lines: ['', ' ']).valid?
|
||||
assert_not LabelJob.new(label_printer: @printer, lines: ['X' * 41]).valid?
|
||||
assert_not LabelJob.new(label_printer: @printer, lines: %w[A B C D E]).valid?
|
||||
assert_not LabelJob.new(label_printer: @printer, lines: %w[A], copies: 11).valid?
|
||||
assert LabelJob.new(label_printer: @printer, lines: %w[A], copies: 10).valid?
|
||||
end
|
||||
|
||||
def test_claim_next_takes_the_oldest_queued_label_of_the_printer
|
||||
other, = create_printer(name: 'Shop')
|
||||
first = create_job(@printer)
|
||||
second = create_job(@printer)
|
||||
create_job(other)
|
||||
|
||||
assert_equal first, LabelJob.claim_next(@printer)
|
||||
assert_equal 'printing', first.reload.status
|
||||
assert_not_nil first.claimed_at
|
||||
assert_equal second, LabelJob.claim_next(@printer)
|
||||
assert_nil LabelJob.claim_next(@printer)
|
||||
end
|
||||
|
||||
def test_labels_not_picked_up_in_time_expire
|
||||
job = create_job(@printer)
|
||||
travel 11.minutes do
|
||||
assert_nil LabelJob.claim_next(@printer)
|
||||
job.reload
|
||||
assert_equal 'expired', job.status
|
||||
assert job.finished?
|
||||
assert_not_nil job.error
|
||||
end
|
||||
end
|
||||
|
||||
def test_expiry_follows_the_setting
|
||||
job = create_job(@printer)
|
||||
with_label_settings('job_expiry_minutes' => '30') do
|
||||
travel 11.minutes do
|
||||
assert_equal job, LabelJob.claim_next(@printer)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def test_labels_the_agent_never_reports_on_fail
|
||||
job = create_job(@printer)
|
||||
LabelJob.claim_next(@printer)
|
||||
travel 3.minutes do
|
||||
LabelJob.expire_lapsed
|
||||
assert_equal 'failed', job.reload.status
|
||||
end
|
||||
end
|
||||
|
||||
def test_old_labels_are_removed
|
||||
job = create_job(@printer, status: 'printed')
|
||||
travel 31.days do
|
||||
LabelJob.expire_lapsed
|
||||
assert_not LabelJob.exists?(job.id)
|
||||
end
|
||||
end
|
||||
|
||||
def test_finish
|
||||
job = create_job(@printer)
|
||||
job.finish!(printed: true)
|
||||
assert_equal 'printed', job.reload.status
|
||||
assert_nil job.error
|
||||
|
||||
job = create_job(@printer)
|
||||
job.finish!(printed: false, error: 'Error: No media')
|
||||
assert_equal 'failed', job.reload.status
|
||||
assert_equal 'Error: No media', job.error
|
||||
end
|
||||
|
||||
def test_agent_json_has_the_label_and_its_lengths
|
||||
job = create_job(@printer, copies: 2)
|
||||
json = job.to_agent_json
|
||||
assert_equal %w[SMITH E1234], json[:lines]
|
||||
assert_equal 2, json[:copies]
|
||||
assert_equal 101.6, json[:max_length_mm]
|
||||
assert_equal 25.4, json[:min_length_mm]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,74 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class LabelPrinterTest < ActiveSupport::TestCase
|
||||
include QboLabelsTestHelper
|
||||
|
||||
def test_token_signs_the_agent_in_and_only_its_digest_is_kept
|
||||
printer, token = create_printer
|
||||
assert token.start_with?('qbl_')
|
||||
assert_not_equal token, printer.reload.token_digest
|
||||
assert_equal printer, LabelPrinter.authenticate(token)
|
||||
assert_nil LabelPrinter.authenticate('qbl_wrong')
|
||||
assert_nil LabelPrinter.authenticate('')
|
||||
end
|
||||
|
||||
def test_inactive_printers_cannot_sign_in
|
||||
printer, token = create_printer(active: false)
|
||||
assert_nil LabelPrinter.authenticate(token)
|
||||
printer.update!(active: true)
|
||||
assert_equal printer, LabelPrinter.authenticate(token)
|
||||
end
|
||||
|
||||
def test_new_token_replaces_the_old_one
|
||||
printer, token = create_printer
|
||||
new_token = printer.generate_token
|
||||
printer.save!
|
||||
assert_nil LabelPrinter.authenticate(token)
|
||||
assert_equal printer, LabelPrinter.authenticate(new_token)
|
||||
end
|
||||
|
||||
def test_seen_records_the_agent_and_its_printer
|
||||
printer, = create_printer
|
||||
assert_not printer.online?
|
||||
printer.seen!(ip: '10.0.0.5', agent: { 'version' => '2026.11.0', 'printer_model' => 'QL-820NWB',
|
||||
'printer_address' => '192.168.0.100:9100',
|
||||
'printer_status' => 'Ready, 62mm continuous' })
|
||||
printer.reload
|
||||
assert printer.online?
|
||||
assert_equal '10.0.0.5', printer.last_ip
|
||||
assert_equal 'QL-820NWB', printer.printer_model
|
||||
assert_equal '192.168.0.100:9100', printer.printer_address
|
||||
assert_equal 'Ready, 62mm continuous', printer.printer_status
|
||||
end
|
||||
|
||||
def test_seen_writes_last_seen_only_every_few_seconds
|
||||
printer, = create_printer
|
||||
printer.seen!(ip: '10.0.0.5')
|
||||
first = printer.reload.last_seen_at
|
||||
travel 5.seconds do
|
||||
printer.seen!(ip: '10.0.0.5')
|
||||
assert_equal first, printer.reload.last_seen_at
|
||||
end
|
||||
travel 20.seconds do
|
||||
printer.seen!(ip: '10.0.0.5')
|
||||
assert_operator printer.reload.last_seen_at, :>, first
|
||||
end
|
||||
end
|
||||
|
||||
def test_names_are_unique
|
||||
create_printer(name: 'Parts room')
|
||||
printer = LabelPrinter.new(name: 'parts ROOM')
|
||||
printer.generate_token
|
||||
assert_not printer.valid?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#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.
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class LabelSourceTest < ActiveSupport::TestCase
|
||||
include QboLabelsTestHelper
|
||||
fixtures :projects, :users, :members, :member_roles, :roles, :issues, :trackers, :projects_trackers,
|
||||
:issue_statuses, :enabled_modules, :enumerations
|
||||
|
||||
Details = Struct.new(:family_name, :company_name)
|
||||
FakeCustomer = Struct.new(:id, :name, :details)
|
||||
Document = Struct.new(:id, :doc_number, :customer)
|
||||
|
||||
def customer(name, family_name: nil, company_name: nil)
|
||||
FakeCustomer.new(1, name, Details.new(family_name, company_name))
|
||||
end
|
||||
|
||||
def test_po_numbers_follow_the_sales_sop
|
||||
assert_equal 'E1234', RedmineQboLabels::LabelSource.new('estimate', Document.new(99, '1234', nil)).po_number
|
||||
assert_equal 'I1234', RedmineQboLabels::LabelSource.new('invoice', Document.new(98, '1234', nil)).po_number
|
||||
assert_equal 'W3', RedmineQboLabels::LabelSource.new('issue', Issue.find(3)).po_number
|
||||
end
|
||||
|
||||
def test_last_name_is_the_quickbooks_family_name
|
||||
assert_equal 'Smith', RedmineQboLabels::LabelSource.last_name(customer('Jane A. Smith-Jones', family_name: 'Smith'))
|
||||
end
|
||||
|
||||
def test_last_name_falls_back_to_the_last_word_of_the_name
|
||||
assert_equal 'Smith', RedmineQboLabels::LabelSource.last_name(customer('Jane Smith'))
|
||||
assert_equal 'Smith', RedmineQboLabels::LabelSource.last_name(customer('John Smith Jr.'))
|
||||
assert_equal 'Smith', RedmineQboLabels::LabelSource.last_name(customer('John Smith III'))
|
||||
assert_equal 'Smith', RedmineQboLabels::LabelSource.last_name(customer('Smith'))
|
||||
end
|
||||
|
||||
def test_a_business_uses_its_whole_name
|
||||
assert_equal 'Acme Offroad LLC',
|
||||
RedmineQboLabels::LabelSource.last_name(customer('Acme Offroad LLC', company_name: 'Acme Offroad LLC'))
|
||||
end
|
||||
|
||||
def test_last_name_without_quickbooks
|
||||
broken = FakeCustomer.new(1, 'Jane Smith', nil)
|
||||
def broken.details = raise('QuickBooks is down')
|
||||
assert_equal 'Smith', RedmineQboLabels::LabelSource.last_name(broken)
|
||||
assert_equal '', RedmineQboLabels::LabelSource.last_name(nil)
|
||||
end
|
||||
|
||||
def test_issues_must_be_visible
|
||||
User.current = User.find(2)
|
||||
assert RedmineQboLabels::LabelSource.find('issue', 1)
|
||||
User.current = User.anonymous
|
||||
assert_nil RedmineQboLabels::LabelSource.find('issue', 4) # private project
|
||||
assert_nil RedmineQboLabels::LabelSource.find('project', 1)
|
||||
ensure
|
||||
User.current = nil
|
||||
end
|
||||
|
||||
def test_estimates_and_invoices_need_redmine_qbos_permissions
|
||||
User.current = User.find(7) # no global permissions
|
||||
assert_nil RedmineQboLabels::LabelSource.find('estimate', 1)
|
||||
assert_nil RedmineQboLabels::LabelSource.find('invoice', 1)
|
||||
ensure
|
||||
User.current = nil
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user