# Our own C#-based print service

<div style="text-align: justify;">

VeloxFactory does not talk to printers directly. Instead, a lightweight companion application — the **Background Printing Service** — runs on any Windows machine that has the target printers installed. It receives print tasks from VeloxFactory, renders the PDF to the printer, and reports the result back. The two components communicate exclusively over the VeloxFactory API and WebSocket; there is no shared database or filesystem.

---

<h3 id="how-it-works" style="color: #203671; margin-top: 2.2em;">How it works</h3>

The service starts as a regular Windows console process and works through two sequential phases.

<h4 style="color: #203671; margin-top: 1.4em;">Phase 1 — Initial pull</h4>

On startup the service immediately calls `GET /api/v1/report-print-task?status=pending` and processes all tasks it finds. It repeats this in a loop — waiting two seconds between rounds — until the queue comes back empty *and* no jobs are still running. This ensures that any tasks queued while the service was offline are handled before switching to real-time mode.

<h4 style="color: #203671; margin-top: 1.4em;">Phase 2 — WebSocket listener</h4>

Once the initial queue is drained, the service connects to VeloxFactory's WebSocket endpoint (Laravel Reverb) and subscribes to the private channel `private-report-print-tasks`. From this point on, it reacts to incoming events in real time. If the WebSocket connection drops for any reason, the service waits five seconds and reconnects automatically — no manual restart required.

<div style="border-left: 4px solid #5fc75d; background: #f6fdf6; padding: 10px 16px; margin: 16px 0; border-radius: 0 4px 4px 0;">
ℹ️ <strong>The WebSocket uses the Pusher protocol.</strong> When a connection is established, the service authenticates with VeloxFactory via <code>POST /api/v1/broadcasting/auth</code> and subscribes to the private channel using the configured API token.
</div>

---

<h3 id="processing" style="color: #203671; margin-top: 2.2em;">Processing a print task</h3>

Whether a task arrives via the initial pull or via a WebSocket event, the processing steps are identical:

1. **Fetch** — The service calls `GET /api/v1/report-print-task/{id}` to retrieve the full task record, including the PDF as a Base64 string.
2. **Write temp file** — The PDF is decoded and written to a temporary file in `reportPdfFileTempPath` (e.g. `C:\VeloxFactory\temp\42_delivery_note.pdf`).
3. **Print** — PdfiumViewer opens the PDF and sends it to the printer specified in `printerName`. The print is repeated `numberOfCopies` times.
4. **Report back** — On success, the service calls `PATCH /api/v1/report-print-task/{id}/set-printed`, which sets the status to `printed`. On failure, it calls `PATCH /api/v1/report-print-task/{id}/set-status` with `{"status": "error", "errorMessage": "..."}`.
5. **Cleanup** — The temporary file is deleted regardless of the outcome.

<div style="border-left: 4px solid #203671; background: #f0f3fb; padding: 10px 16px; margin: 16px 0; border-radius: 0 4px 4px 0;">
⚠️ <strong>The WebSocket event only carries the task ID and <code>broadcastId</code> — not the PDF.</strong> The service always fetches the full task from the API as a second step. This means the printer machine needs HTTP access to VeloxFactory, not just WebSocket access.
</div>

---

<h3 id="broadcast-id-filtering" style="color: #203671; margin-top: 2.2em;">Broadcast ID filtering</h3>

`listeningBroadcastIds` is a list of broadcast channel identifiers the service will accept. Any `report-print-task.created` event whose `broadcastId` is not in this list is silently ignored.

This makes it straightforward to run multiple service instances in parallel — for example one per location or printer group — each configured to respond only to its own `broadcastId`. The initial pull is not filtered this way: it always processes all pending tasks returned by the API, regardless of `broadcastId`.

---

<h3 id="configuration" style="color: #203671; margin-top: 2.2em;">Configuration</h3>

All settings live in `App.config` in the `applicationSettings` section. Edit the file in a text editor and restart the service for changes to take effect.

<table style="width: 100%; border-collapse: collapse;">
  <thead>
    <tr style="border-top: 1px solid #e6e8ef; border-bottom: 1px solid #e6e8ef;">
      <th style="text-align: left; padding: 6px 10px; white-space: nowrap;">Setting</th>
      <th style="text-align: left; padding: 6px 10px;">Description</th>
      <th style="text-align: left; padding: 6px 10px;">Example</th>
    </tr>
  </thead>
  <tbody>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>apiToken</code></td>
      <td style="padding: 6px 10px;">Bearer token used for all API requests. Must belong to a user with <code>report-print-task:read</code>, <code>:update</code>, and <code>:delete</code> permissions.</td>
      <td style="padding: 6px 10px;"><code>4|abc123...</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>websocketUrl</code></td>
      <td style="padding: 6px 10px;">WebSocket endpoint of Laravel Reverb.</td>
      <td style="padding: 6px 10px;"><code>ws://10.0.0.10:8080/app/veloxfactory</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>websocketAuthUrl</code></td>
      <td style="padding: 6px 10px;">VeloxFactory broadcasting auth endpoint.</td>
      <td style="padding: 6px 10px;"><code>http://10.0.0.10:8088/api/v1/broadcasting/auth</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>reportPrintTask_index</code></td>
      <td style="padding: 6px 10px;">URL for the initial pull — must include <code>?status=pending</code>.</td>
      <td style="padding: 6px 10px;"><code>http://10.0.0.10:8088/api/v1/report-print-task?status=pending</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>reportPrintTask_get</code></td>
      <td style="padding: 6px 10px;">URL template for fetching a single task. <code>{0}</code> is replaced with the task ID.</td>
      <td style="padding: 6px 10px;"><code>http://10.0.0.10:8088/api/v1/report-print-task/{0}</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>reportPrintTask_setPrinted</code></td>
      <td style="padding: 6px 10px;">URL template for marking a task as printed. <code>{0}</code> is replaced with the task ID.</td>
      <td style="padding: 6px 10px;"><code>http://10.0.0.10:8088/api/v1/report-print-task/{0}/set-printed</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>reportPrintTask_setError</code></td>
      <td style="padding: 6px 10px;">URL template for reporting a failed task. <code>{0}</code> is replaced with the task ID.</td>
      <td style="padding: 6px 10px;"><code>http://10.0.0.10:8088/api/v1/report-print-task/{0}/set-status</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>listeningBroadcastIds</code></td>
      <td style="padding: 6px 10px;">List of broadcast IDs this instance will accept. Add one <code>&lt;string&gt;</code> entry per ID.</td>
      <td style="padding: 6px 10px;"><code>Standard</code>, <code>Warehouse</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>maxParallelPrintJobs</code></td>
      <td style="padding: 6px 10px;">Maximum number of tasks processed concurrently. Default: <code>10</code>.</td>
      <td style="padding: 6px 10px;"><code>10</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>reportPdfFileTempPath</code></td>
      <td style="padding: 6px 10px;">Directory for temporary PDF files. Created automatically on startup if it does not exist.</td>
      <td style="padding: 6px 10px;"><code>C:\VeloxFactory\temp</code></td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>logFile</code></td>
      <td style="padding: 6px 10px;">Path to the log file. Relative paths are resolved from the executable directory.</td>
      <td style="padding: 6px 10px;"><code>.\Log.log</code></td>
    </tr>
    <tr>
      <td style="padding: 6px 10px; white-space: nowrap;"><code>laconicLogging</code></td>
      <td style="padding: 6px 10px;">If <code>True</code>, only errors are logged. If <code>False</code>, all informational messages are logged as well.</td>
      <td style="padding: 6px 10px;"><code>False</code></td>
    </tr>
  </tbody>
</table>

---

<h3 id="concurrency" style="color: #203671; margin-top: 2.2em;">Concurrency</h3>

The service uses two layers of concurrency control to avoid overloading printers.

A global semaphore limits the total number of tasks being processed at the same time to `maxParallelPrintJobs`. In addition, a per-printer semaphore ensures that only one print job runs on a given printer at a time — jobs targeting different printers can execute in parallel, but two jobs targeting the same printer are always serialised. This prevents the spooler from receiving multiple jobs simultaneously from the service.

---

<h3 id="logging" style="color: #203671; margin-top: 2.2em;">Logging</h3>

The service uses **Serilog** and writes to both the console and a rolling log file. Log files are capped at 100 MB each; up to 10 rotated files are retained before the oldest is deleted.

Set `laconicLogging` to `True` in `App.config` to suppress informational messages and log only errors — useful in production once the service is confirmed working.

---

<h3 id="dependencies" style="color: #203671; margin-top: 2.2em;">Dependencies</h3>

<table style="width: 100%; border-collapse: collapse;">
  <thead>
    <tr style="border-top: 1px solid #e6e8ef; border-bottom: 1px solid #e6e8ef;">
      <th style="text-align: left; padding: 6px 10px; white-space: nowrap;">Package</th>
      <th style="text-align: left; padding: 6px 10px;">Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>PdfiumViewer</code></td>
      <td style="padding: 6px 10px;">PDF rendering and printing. Wraps the native PDFium library (bundled via <code>PdfiumViewer.Native.x86_64.v8-xfa</code>) — no separate PDF reader installation required on the target machine.</td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>RestSharp</code></td>
      <td style="padding: 6px 10px;">HTTP client for all API calls to VeloxFactory.</td>
    </tr>
    <tr style="border-bottom: 1px solid #e6e8ef;">
      <td style="padding: 6px 10px; white-space: nowrap;"><code>Newtonsoft.Json</code></td>
      <td style="padding: 6px 10px;">JSON serialisation and deserialisation (API responses, WebSocket messages).</td>
    </tr>
    <tr>
      <td style="padding: 6px 10px; white-space: nowrap;"><code>Serilog</code></td>
      <td style="padding: 6px 10px;">Structured logging to console and rolling file.</td>
    </tr>
  </tbody>
</table>

<div style="border-left: 4px solid #5fc75d; background: #f6fdf6; padding: 10px 16px; margin: 16px 0; border-radius: 0 4px 4px 0;">
ℹ️ <strong>The service targets .NET Framework 4.7.2 and runs on Windows only.</strong> The PDFium native binary is bundled with the build output — no additional runtime installation is needed beyond .NET Framework 4.7.2, which ships with Windows 10 and Windows Server 2016 and later.
</div>

</div>