Compare commits
27 Commits
89bb9689e9
...
cursor/omn
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed2573d8e4 | ||
|
|
9121200bfa | ||
|
|
31cd1783a1 | ||
|
|
4fdccfb805 | ||
|
|
1b933d9042 | ||
|
|
97130034dd | ||
|
|
653d569149 | ||
|
|
757781f7a0 | ||
|
|
0d6c215fa7 | ||
|
|
48d9356d10 | ||
|
|
6d27bceb14 | ||
|
|
f2150f9243 | ||
|
|
95cc827a0a | ||
| 1d18dbd7c4 | |||
|
|
b013181d35 | ||
|
|
94791dcd67 | ||
| 1cad94b8d5 | |||
| f1d9693966 | |||
| 7c50480324 | |||
| f04ca3fe72 | |||
| 31dd69c2aa | |||
| 95e0acbe71 | |||
| a39cccb0dc | |||
| 5d827ae70d | |||
|
|
8ee6cebea3 | ||
| a07d3b46dc | |||
|
|
78d1a0a5fc |
75
.github/workflows/bump-version.yml
vendored
Normal file
75
.github/workflows/bump-version.yml
vendored
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
# Manually bump package version and open a PR to main.
|
||||||
|
# Actions → Bump version → Run workflow → choose patch / minor / major.
|
||||||
|
name: Bump version
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
part:
|
||||||
|
description: Version part to bump
|
||||||
|
required: true
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- patch
|
||||||
|
- minor
|
||||||
|
- major
|
||||||
|
default: patch
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: bump-version
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
bump:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout main
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: main
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Install uv
|
||||||
|
uses: astral-sh/setup-uv@v5
|
||||||
|
|
||||||
|
- name: Bump version
|
||||||
|
id: bump
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
OLD=$(uvx --from bump-my-version bump-my-version show current_version)
|
||||||
|
uvx --from bump-my-version bump-my-version bump "${{ inputs.part }}" --no-commit --no-tag
|
||||||
|
NEW=$(uvx --from bump-my-version bump-my-version show current_version)
|
||||||
|
echo "old=${OLD}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "new=${NEW}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "Bumped ${OLD} → ${NEW} (${{ inputs.part }})"
|
||||||
|
|
||||||
|
- name: Create pull request
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
OLD="${{ steps.bump.outputs.old }}"
|
||||||
|
NEW="${{ steps.bump.outputs.new }}"
|
||||||
|
BRANCH="chore/bump-version-${NEW}"
|
||||||
|
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
|
|
||||||
|
git checkout -b "$BRANCH"
|
||||||
|
git add pyproject.toml
|
||||||
|
git commit -m "Bump version: ${OLD} → ${NEW}"
|
||||||
|
git push -u origin "$BRANCH"
|
||||||
|
|
||||||
|
gh pr create \
|
||||||
|
--base main \
|
||||||
|
--head "$BRANCH" \
|
||||||
|
--title "Bump version to ${NEW}" \
|
||||||
|
--body "## Summary
|
||||||
|
|
||||||
|
Automated \`${{ inputs.part }}\` bump: \`${OLD}\` → \`${NEW}\`.
|
||||||
|
|
||||||
|
Source: \`[project].version\` in \`pyproject.toml\` (via bump-my-version)."
|
||||||
49
AGENTS.md
49
AGENTS.md
@@ -4,7 +4,7 @@
|
|||||||
configured directory, clearing/resetting specific cells. Interfaces:
|
configured directory, clearing/resetting specific cells. Interfaces:
|
||||||
|
|
||||||
- CLI: `src/xlsx_clean/clean_cells.py` (`beaupy`)
|
- CLI: `src/xlsx_clean/clean_cells.py` (`beaupy`)
|
||||||
- Web UI: `src/xlsx_clean/web_app.py` (NiceGUI; default **native** single window via pywebview)
|
- GUI: `src/xlsx_clean/gui_app.py` (PyWebView cross-platform desktop window with a local HTML/CSS/JS frontend)
|
||||||
|
|
||||||
## Backends
|
## Backends
|
||||||
|
|
||||||
@@ -15,40 +15,33 @@ configured directory, clearing/resetting specific cells. Interfaces:
|
|||||||
only). Preserves non-worksheet parts (styles, connections/Power Query definitions,
|
only). Preserves non-worksheet parts (styles, connections/Power Query definitions,
|
||||||
drawings, etc.). Does not calculate formulas or refresh queries.
|
drawings, etc.). Does not calculate formulas or refresh queries.
|
||||||
|
|
||||||
Select with `--backend com|ooxml` (CLI) or the Backend dropdown (web UI).
|
Select with `--backend com|ooxml` (CLI) or `config.toml`.
|
||||||
|
|
||||||
## Cursor Cloud specific instructions
|
## Cursor Cloud Specific Instructions
|
||||||
|
|
||||||
### Platform notes
|
### Platform Notes
|
||||||
- `pywin32` has no Linux wheels and is declared as Windows-only
|
- `pywin32` has no Linux wheels and is declared as Windows-only
|
||||||
(`pywin32>=312; sys_platform == 'win32'`). It is intentionally **not** installed here.
|
(`pywin32>=312; sys_platform == 'win32'`). It is intentionally **not** installed here.
|
||||||
- End-to-end COM automation needs Windows + desktop Excel and does not run on this VM.
|
- End-to-end COM automation needs Windows + desktop Excel and does not run on this VM.
|
||||||
- On Linux, the **ooxml** backend can clear/set cells and write a new workbook when
|
- On Linux, the **ooxml** backend can clear/set cells and write a new workbook when
|
||||||
sample files and `XLSX_CLEAN_ROOT` point at a real tree. Without those data files,
|
sample files and `XLSX_CLEAN_ROOT` point at a real tree. Without those data files,
|
||||||
interactive selection still works for config loading, but globbing finds no templates.
|
interactive selection still works for config loading, but globbing finds no templates.
|
||||||
- NiceGUI defaults to a native window (`pywebview`). On Linux that needs **system**
|
- PyWebView supports Windows (Edge WebView2), Linux (WebKitGTK), and macOS (WKWebView).
|
||||||
GTK/WebKit packages (`python3-gi`, `gir1.2-gtk-3.0`, `gir1.2-webkit2-4.1` via apt) —
|
Windows needs the separately-installed Microsoft Edge WebView2 Runtime; `pythonnet`
|
||||||
not installable with `uv`. Prefer `./desktop/setup_linux.sh`, which recreates
|
does not install it. Linux needs `python3-gi`, GTK, and WebKitGTK typelibs; use the
|
||||||
`.venv` with **OS** `/usr/bin/python3` (`--no-managed-python --system-site-packages`).
|
system Python with `--system-site-packages` so apt-provided `gi` remains importable.
|
||||||
A uv-managed CPython (e.g. from `~/.local/share/uv/python`) cannot load apt
|
- On headless machines without a display server the GUI cannot open a native window.
|
||||||
`_gi` even with system-site-packages. `setup_linux.sh` always uses
|
|
||||||
`/usr/bin/python3`, not PATH `python3`. `.python-version` is `3.12` (minor pin)
|
|
||||||
so sync can use the OS interpreter. On this headless/cloud VM native mode is
|
|
||||||
often unavailable; the app falls back to the browser, or use `--no-browser`
|
|
||||||
/ `--browser`.
|
|
||||||
|
|
||||||
### Environment
|
### Environment
|
||||||
- Prefer **uv** for all installs (`uv` in `~/.local/bin`, on PATH via `~/.bashrc`).
|
- Prefer **uv** for all installs (`uv` in `~/.local/bin`, on PATH via `~/.bashrc`).
|
||||||
- Rye is **not** used (`requirements.lock` removed). Use `uv.lock` + `uv sync`.
|
- Rye is **not** used (`requirements.lock` removed). Use `uv.lock` + `uv sync`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Linux desktop (native window + Desktop shortcut):
|
# Linux desktop (system WebKitGTK deps + venv + Desktop shortcut):
|
||||||
./desktop/setup_linux.sh
|
./desktop/setup_linux.sh
|
||||||
|
|
||||||
# Deps only (any OS). For Linux native window use OS python3, not managed:
|
# Dependencies and test tooling (any OS):
|
||||||
uv sync
|
uv sync
|
||||||
# or:
|
|
||||||
uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages && uv sync
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- Run Python via the venv interpreter: `.venv/bin/python`.
|
- Run Python via the venv interpreter: `.venv/bin/python`.
|
||||||
@@ -56,19 +49,17 @@ Select with `--backend com|ooxml` (CLI) or the Backend dropdown (web UI).
|
|||||||
- Note: the `uv`-created `.venv` does not include `pip`; use `uv pip ...` / `uv sync`
|
- Note: the `uv`-created `.venv` does not include `pip`; use `uv pip ...` / `uv sync`
|
||||||
for package operations.
|
for package operations.
|
||||||
|
|
||||||
### Lint / test / build
|
### Lint / Test / Build
|
||||||
- There is **no lint config, no test suite, and no build step** in this repo (no ruff/flake8,
|
- Tests use `pytest`; run `uv run pytest -q`.
|
||||||
no pytest, no CI). Don't invent one unless asked.
|
- `pyproject.toml` uses `hatchling` as the build backend; build a wheel with `uv build`.
|
||||||
- `pyproject.toml` uses `hatchling` as the build backend; there is nothing to "build" for dev.
|
|
||||||
|
|
||||||
### Running / verifying
|
### Running / Verifying
|
||||||
- CLI: `.venv/bin/python -m xlsx_clean.clean_cells` (defaults to `ooxml` on Linux).
|
- CLI: `.venv/bin/python -m xlsx_clean.clean_cells` (defaults to `ooxml` on Linux).
|
||||||
- Web UI: `.venv/bin/python -m xlsx_clean.web_app` (native window) or
|
- GUI: `.venv/bin/python -m xlsx_clean.gui_app [--width 800 --height 600]`.
|
||||||
`--no-browser` / `--browser` on headless / for default browser.
|
- Linux setup: `./desktop/setup_linux.sh` (GTK/WebKitGTK check, uv sync).
|
||||||
- Linux setup: `./desktop/setup_linux.sh` (apt + OS Python venv + shortcut).
|
- Windows shop-floor: double-click `desktop/Setup.bat` (uv sync), or build
|
||||||
- Desktop shortcut (Linux): `.venv/bin/python desktop/install_desktop_shortcut.py`
|
|
||||||
- Windows shop-floor: double-click `desktop/Setup.bat` (uv sync + shortcut), or build
|
|
||||||
an exe with `desktop/build_windows_exe.bat` **on a Windows PC** (cannot build Windows
|
an exe with `desktop/build_windows_exe.bat` **on a Windows PC** (cannot build Windows
|
||||||
exe here).
|
exe here).
|
||||||
|
- Operators create their own shortcut to the GUI launcher (no installer script).
|
||||||
- Sanity-check imports:
|
- Sanity-check imports:
|
||||||
`.venv/bin/python -c "import pandas, beaupy, nicegui; from xlsx_clean import hello; from xlsx_clean.ooxml_backend import expand_a1_range; print(hello(), expand_a1_range('A1:B2'))"`.
|
`.venv/bin/python -c "import webview, beaupy; from xlsx_clean import hello; from xlsx_clean.core import load_config, list_sets; from xlsx_clean.ooxml_backend import expand_a1_range; print(webview, hello(), expand_a1_range('A1:B2'))"`.
|
||||||
|
|||||||
114
README.md
114
README.md
@@ -5,31 +5,26 @@ Operator-facing name: **New QC Sheet**.
|
|||||||
Create a new QC datasheet from the latest matching workbook: clear configured cells,
|
Create a new QC datasheet from the latest matching workbook: clear configured cells,
|
||||||
blank notes, write the batch serial, and save under a new `[SERIAL]` name.
|
blank notes, write the batch serial, and save under a new `[SERIAL]` name.
|
||||||
|
|
||||||
Everyday use is a **Desktop icon** that opens a **single app window**
|
Everyday use opens a **single app window** (Set -> Ink -> Serial -> Create).
|
||||||
(Set → Ink → Serial → Create) — not your full browser with all tabs.
|
|
||||||
No terminal commands are required for operators.
|
No terminal commands are required for operators.
|
||||||
|
|
||||||
## Quick start (Windows operators)
|
## Quick start (Windows operators)
|
||||||
|
|
||||||
1. One-time setup (IT / first install): install [uv](https://docs.astral.sh/uv/getting-started/installation/), clone/copy this project, then double-click
|
1. One-time setup (IT / first install): install [uv](https://docs.astral.sh/uv/getting-started/installation/), clone/copy this project, then double-click
|
||||||
**`desktop\Setup.bat`**
|
**`desktop\Setup.bat`**
|
||||||
2. Every day: double-click the **New QC Sheet** icon on the Desktop
|
2. Every day: launch the app via the **New QC Sheet** shortcut
|
||||||
3. In the app window: choose **Set**, **Ink color**, enter **Serial**, click **Create datasheet**
|
3. In the app window: choose **Set**, **Ink color**, enter **Serial**, click **Create datasheet**
|
||||||
|
|
||||||
`Setup.bat` creates `.venv` with uv, installs the package, and adds the Desktop shortcut
|
`Setup.bat` creates `.venv` with uv and installs the package. Operators create their own
|
||||||
(using the modern icon in `desktop\xlsx-clean.ico`).
|
shortcut to `desktop\XlsxClean.vbs` (uses the modern icon in `desktop\xlsx-clean.ico`).
|
||||||
The shortcut runs `desktop\XlsxClean.vbs` and opens one dedicated window (via pywebview).
|
On Windows, install the Microsoft Edge WebView2 Runtime separately before opening the
|
||||||
Closing that window stops the app.
|
PyWebView GUI; `pythonnet` does not install it. The shortcut runs `desktop\XlsxClean.vbs`
|
||||||
|
which launches the GUI window. Closing that window stops the app.
|
||||||
|
|
||||||
When you **Create** with the **com** backend, Excel is maximized and brought to the front
|
When you **Create** with the **com** backend, Excel is maximized and brought to the front
|
||||||
after the new workbook is saved.
|
after the new workbook is saved.
|
||||||
|
|
||||||
If something fails, use **`desktop\XlsxClean.bat`** instead — it shows a console with errors.
|
If something fails, use **`desktop\XlsxClean.bat`** instead - it shows a console with errors.
|
||||||
To force the old “open in default browser” behavior for debugging:
|
|
||||||
|
|
||||||
```bat
|
|
||||||
.venv\Scripts\python.exe -m xlsx_clean.web_app --browser
|
|
||||||
```
|
|
||||||
|
|
||||||
## Standalone Windows exe (optional)
|
## Standalone Windows exe (optional)
|
||||||
|
|
||||||
@@ -37,7 +32,7 @@ To put a self-contained app on other PCs (build **on Windows**):
|
|||||||
|
|
||||||
1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/) if needed
|
1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/) if needed
|
||||||
2. Double-click **`desktop\build_windows_exe.bat`**
|
2. Double-click **`desktop\build_windows_exe.bat`**
|
||||||
3. It creates `dist\New QC Sheet\New QC Sheet.exe` and a Desktop shortcut
|
3. It creates `dist\New QC Sheet\New QC Sheet.exe`
|
||||||
4. Copy the whole **`dist\New QC Sheet\`** folder when moving to another machine (keep files together)
|
4. Copy the whole **`dist\New QC Sheet\`** folder when moving to another machine (keep files together)
|
||||||
|
|
||||||
## What the app does
|
## What the app does
|
||||||
@@ -56,7 +51,7 @@ To put a self-contained app on other PCs (build **on Windows**):
|
|||||||
| Windows | `com` | Uses Microsoft Excel + add-ins from `strings.txt`; leaves Excel open |
|
| Windows | `com` | Uses Microsoft Excel + add-ins from `strings.txt`; leaves Excel open |
|
||||||
| Linux / macOS | `ooxml` | Surgical `.xlsx` edit; keeps formulas, formatting, and queries on disk |
|
| Linux / macOS | `ooxml` | Surgical `.xlsx` edit; keeps formulas, formatting, and queries on disk |
|
||||||
|
|
||||||
Choose the backend in the web UI dropdown, or with CLI `--backend com\|ooxml`.
|
Choose the backend in the `config.toml` file, or override with CLI `--backend com|ooxml`.
|
||||||
|
|
||||||
**Limits of `ooxml`:** does not refresh Power Query, calculate formulas, or load `.xlam`/`.xla`
|
**Limits of `ooxml`:** does not refresh Power Query, calculate formulas, or load `.xlam`/`.xla`
|
||||||
add-ins. Open the file in Excel afterward for refresh/calc. Prefer **`com` on Windows** when
|
add-ins. Open the file in Excel afterward for refresh/calc. Prefer **`com` on Windows** when
|
||||||
@@ -76,51 +71,35 @@ chmod +x desktop/setup_linux.sh
|
|||||||
./desktop/setup_linux.sh
|
./desktop/setup_linux.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
That installs apt GTK/WebKit packages if needed, recreates `.venv` with
|
That installs the required GTK/WebKitGTK packages, creates a venv that can import the
|
||||||
**`/usr/bin/python3`** (`--no-managed-python --system-site-packages` so apt
|
apt-provided `gi` bindings, and runs `uv sync`. It uses WebKit2 4.1 when available and
|
||||||
`python3-gi` / `_gi` loads), runs `uv sync`, and creates a Desktop shortcut.
|
supports distro packages that provide WebKit2 4.0. Operators create their own shortcut
|
||||||
It ignores PATH `python3` when that points at a uv-managed build under
|
to `.venv/bin/python -m xlsx_clean.gui_app`.
|
||||||
`~/.local/share/uv/python/` (common with an activated `.venv`).
|
|
||||||
|
|
||||||
**Manual / macOS** (deps only; on Linux this alone is not enough for a native window):
|
**Manual / macOS:**
|
||||||
|
|
||||||
|
The macOS backend defaults to **`ooxml`** (no Excel/COM on macOS). WKWebView is built into
|
||||||
|
macOS, so no extra system packages are needed beyond Python 3.12+ and `uv`.
|
||||||
|
|
||||||
|
From the project root:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv sync
|
uv sync
|
||||||
```
|
```
|
||||||
|
|
||||||
That creates `.venv` and installs locked deps from `uv.lock`.
|
That creates `.venv` and installs locked deps from `uv.lock` (including the `pyobjc`
|
||||||
|
bindings used by PyWebView).
|
||||||
|
|
||||||
### Linux single app window (native mode)
|
To create a double-clickable Finder launcher that runs the GUI:
|
||||||
|
|
||||||
Prefer **`./desktop/setup_linux.sh`** (above). Native mode uses **pywebview**,
|
|
||||||
which needs **system** GTK/WebKit packages (`uv sync` cannot install these).
|
|
||||||
|
|
||||||
Manual equivalent:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Ubuntu / Debian (names may vary by release: webkit2-4.0 vs 4.1)
|
chmod +x desktop/XlsxClean.command
|
||||||
sudo apt install python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1
|
|
||||||
|
|
||||||
rm -rf .venv
|
|
||||||
# Must be OS python3 — `uv venv --python python3` may pick a managed build
|
|
||||||
# that cannot load apt _gi.
|
|
||||||
uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages
|
|
||||||
uv sync
|
|
||||||
|
|
||||||
.venv/bin/python -m xlsx_clean.web_app
|
|
||||||
```
|
```
|
||||||
|
|
||||||
If you already have a normal isolated `.venv`, the app will still try to load
|
Then double-click **`desktop/XlsxClean.command`** in Finder. The first launch may require
|
||||||
system `python3-gi` from `/usr/lib/python3/dist-packages` when those apt packages
|
right-click → Open (Gatekeeper) once. The script opens the app window in a new Terminal
|
||||||
are installed. Without GTK/WebKit (or on a headless machine with no display), it
|
window; closing that window stops the app. Operators create their own shortcut to this
|
||||||
falls back to opening the default browser, or you can force:
|
executable.
|
||||||
|
|
||||||
```bash
|
|
||||||
.venv/bin/python -m xlsx_clean.web_app --browser
|
|
||||||
.venv/bin/python -m xlsx_clean.web_app --no-browser
|
|
||||||
```
|
|
||||||
|
|
||||||
**Windows** native mode uses Edge/WebView2 and does **not** need the apt packages above.
|
|
||||||
|
|
||||||
Before building the standalone exe:
|
Before building the standalone exe:
|
||||||
|
|
||||||
@@ -128,27 +107,17 @@ Before building the standalone exe:
|
|||||||
uv sync --extra desktop
|
uv sync --extra desktop
|
||||||
```
|
```
|
||||||
|
|
||||||
Then create the Desktop shortcut (if you did not use `Setup.bat`):
|
Optional: Edit `~/.xlsx-clean/config.toml` (created automatically on first run) if workbooks are not under the default `D:\\OpenCloud` paths.
|
||||||
|
|
||||||
- **Windows:** double-click `desktop\Install-DesktopShortcut.bat`
|
|
||||||
- **Linux:** `./desktop/setup_linux.sh` (preferred), or
|
|
||||||
`.venv/bin/python desktop/install_desktop_shortcut.py`
|
|
||||||
|
|
||||||
Optional: set `XLSX_CLEAN_ROOT` if workbooks are not under `D:\OpenCloud`
|
|
||||||
(e.g. `set XLSX_CLEAN_ROOT=D:\OpenCloud` or `export XLSX_CLEAN_ROOT=/mnt/opencloud`).
|
|
||||||
|
|
||||||
## Developer interfaces
|
## Developer interfaces
|
||||||
|
|
||||||
These are optional; operators should use the Desktop icon.
|
These are optional; operators use the shortcut to the app executable.
|
||||||
|
|
||||||
**App window (default: native single window)**
|
**GUI (desktop window)**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
.venv/bin/python -m xlsx_clean.web_app
|
.venv/bin/python -m xlsx_clean.gui_app --width 800 --height 600
|
||||||
# Windows: .venv\Scripts\python.exe -m xlsx_clean.web_app
|
# Windows: .venv\Scripts\python.exe -m xlsx_clean.gui_app --width 800 --height 600
|
||||||
|
|
||||||
# Optional: open in the default browser instead
|
|
||||||
.venv/bin/python -m xlsx_clean.web_app --browser
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**CLI**
|
**CLI**
|
||||||
@@ -163,20 +132,19 @@ Windows CLI helper: `src\xlsx_clean\new_xslx.bat`
|
|||||||
|
|
||||||
| File | Purpose |
|
| File | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `src/xlsx_clean/file_data.csv` | Product folders, filename patterns, cells to clear/set |
|
| `config.toml` | Backend choice and root directory path for each set (auto-generated in `~/.xlsx-clean/` on first run) |
|
||||||
|
| `src/xlsx_clean/file_data.csv` | Relative product folders, filename patterns, cells to clear/set |
|
||||||
| `src/xlsx_clean/strings.txt` | UI prompts + Windows Excel add-in paths (`com` only) |
|
| `src/xlsx_clean/strings.txt` | UI prompts + Windows Excel add-in paths (`com` only) |
|
||||||
| `XLSX_CLEAN_ROOT` (env) | Replaces the `D:\OpenCloud\...` root in CSV paths |
|
|
||||||
|
|
||||||
## Project layout (launchers)
|
## Project layout (launchers)
|
||||||
|
|
||||||
| Path | Purpose |
|
| Path | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `desktop/xlsx-clean.ico` | Modern Windows Desktop / exe icon |
|
| `desktop/xlsx-clean.ico` | Modern Windows Desktop / exe icon |
|
||||||
| `desktop/Setup.bat` | Windows one-time setup via uv + Desktop shortcut |
|
| `desktop/Setup.bat` | Windows one-time setup via uv |
|
||||||
| `desktop/setup_linux.sh` | Linux one-time setup (apt + OS Python venv + shortcut) |
|
| `desktop/setup_linux.sh` | Linux one-time setup (uv sync) |
|
||||||
| `desktop/Install-DesktopShortcut.bat` | Create Desktop icon only (Windows) |
|
| `desktop/XlsxClean.command` | macOS double-click launcher (opens GUI in Terminal) |
|
||||||
| `desktop/XlsxClean.vbs` | Silent double-click launcher |
|
| `desktop/XlsxClean.vbs` | Silent Windows double-click launcher |
|
||||||
| `desktop/XlsxClean.bat` | Launcher with visible console |
|
| `desktop/XlsxClean.bat` | Windows launcher with visible console |
|
||||||
| `desktop/build_windows_exe.bat` | Build standalone `New QC Sheet.exe` with uv |
|
| `desktop/build_windows_exe.bat` | Build standalone `New QC Sheet.exe` with uv |
|
||||||
| `desktop/install_desktop_shortcut.py` | Create Desktop shortcut (Linux) |
|
|
||||||
| `packaging/xlsx_clean.spec` | PyInstaller spec |
|
| `packaging/xlsx_clean.spec` | PyInstaller spec |
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
@echo off
|
|
||||||
REM Create a Desktop shortcut that points at desktop\XlsxClean.vbs
|
|
||||||
setlocal
|
|
||||||
cd /d "%~dp0\.."
|
|
||||||
|
|
||||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-DesktopShortcut.ps1"
|
|
||||||
if errorlevel 1 (
|
|
||||||
echo Failed to create desktop shortcut.
|
|
||||||
pause
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
echo Desktop shortcut created: New QC Sheet
|
|
||||||
pause
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
# Creates %USERPROFILE%\Desktop\New QC Sheet.lnk -> desktop\XlsxClean.vbs
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
|
||||||
$target = Join-Path $PSScriptRoot "XlsxClean.vbs"
|
|
||||||
$desktop = [Environment]::GetFolderPath("Desktop")
|
|
||||||
$shortcutPath = Join-Path $desktop "New QC Sheet.lnk"
|
|
||||||
|
|
||||||
if (-not (Test-Path $target)) {
|
|
||||||
throw "Launcher not found: $target"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Remove older shortcut name if present
|
|
||||||
$legacy = Join-Path $desktop "XlsxClean.lnk"
|
|
||||||
if (Test-Path $legacy) {
|
|
||||||
Remove-Item $legacy -Force
|
|
||||||
}
|
|
||||||
|
|
||||||
$wsh = New-Object -ComObject WScript.Shell
|
|
||||||
$shortcut = $wsh.CreateShortcut($shortcutPath)
|
|
||||||
$shortcut.TargetPath = $target
|
|
||||||
$shortcut.WorkingDirectory = $repoRoot
|
|
||||||
$shortcut.WindowStyle = 7
|
|
||||||
$shortcut.Description = "Open New QC Sheet"
|
|
||||||
$iconCandidate = Join-Path $PSScriptRoot "xlsx-clean.ico"
|
|
||||||
if (Test-Path $iconCandidate) {
|
|
||||||
$shortcut.IconLocation = "$iconCandidate,0"
|
|
||||||
}
|
|
||||||
$shortcut.Save()
|
|
||||||
Write-Host "Created $shortcutPath"
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
@echo off
|
@echo off
|
||||||
REM One-time Windows setup with uv: sync deps from uv.lock, Desktop shortcut.
|
REM One-time Windows setup with uv: sync deps from uv.lock.
|
||||||
setlocal
|
setlocal
|
||||||
cd /d "%~dp0\.."
|
cd /d "%~dp0\.."
|
||||||
|
|
||||||
@@ -20,14 +20,6 @@ if errorlevel 1 (
|
|||||||
exit /b 1
|
exit /b 1
|
||||||
)
|
)
|
||||||
|
|
||||||
echo Creating Desktop shortcut...
|
|
||||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0Install-DesktopShortcut.ps1"
|
|
||||||
if errorlevel 1 (
|
|
||||||
echo Desktop shortcut step failed.
|
|
||||||
pause
|
|
||||||
exit /b 1
|
|
||||||
)
|
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo Setup complete. Double-click the New QC Sheet icon on your Desktop.
|
echo Setup complete. Create your own shortcut to desktop\XlsxClean.vbs.
|
||||||
pause
|
pause
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
@echo off
|
@echo off
|
||||||
REM Double-click launcher with visible console (useful for troubleshooting).
|
REM Double-click launcher with visible console (useful for troubleshooting).
|
||||||
REM Default: single native app window. To use the browser instead, add --browser
|
|
||||||
setlocal
|
setlocal
|
||||||
cd /d "%~dp0\.."
|
cd /d "%~dp0\.."
|
||||||
set PORT=8080
|
|
||||||
|
|
||||||
if exist ".venv\Scripts\python.exe" (
|
if exist ".venv\Scripts\python.exe" (
|
||||||
".venv\Scripts\python.exe" -m xlsx_clean.web_app --host 127.0.0.1 --port %PORT% %*
|
".venv\Scripts\python.exe" -m xlsx_clean.gui_app %*
|
||||||
) else (
|
) else (
|
||||||
py -3 -m xlsx_clean.web_app --host 127.0.0.1 --port %PORT% %*
|
py -3 -m xlsx_clean.gui_app %*
|
||||||
)
|
)
|
||||||
|
|||||||
14
desktop/XlsxClean.command
Executable file
14
desktop/XlsxClean.command
Executable file
@@ -0,0 +1,14 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Operator launcher for New QC Sheet on macOS.
|
||||||
|
# Double-click in Finder (or run from Terminal). Opens the GUI in a new Terminal window.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
if [[ ! -x .venv/bin/python ]]; then
|
||||||
|
echo "Virtual environment not found. Run 'uv sync' first, or use desktop/setup_macos.sh." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
exec ./.venv/bin/python -m xlsx_clean.gui_app
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
' XlsxClean.vbs — double-click launcher (no console window)
|
' XlsxClean.vbs - double-click launcher (no console window)
|
||||||
' Resolves repo root from this script's folder (desktop\ -> repo root).
|
' Resolves repo root from this script's folder (desktop\ -> repo root).
|
||||||
Option Explicit
|
Option Explicit
|
||||||
|
|
||||||
Dim fso, sh, scriptDir, root, pythonExe, cmd, port
|
Dim fso, sh, scriptDir, root, pythonExe, cmd
|
||||||
Set fso = CreateObject("Scripting.FileSystemObject")
|
Set fso = CreateObject("Scripting.FileSystemObject")
|
||||||
Set sh = CreateObject("WScript.Shell")
|
Set sh = CreateObject("WScript.Shell")
|
||||||
|
|
||||||
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
|
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
|
||||||
root = fso.GetParentFolderName(scriptDir)
|
root = fso.GetParentFolderName(scriptDir)
|
||||||
port = "8080"
|
|
||||||
|
|
||||||
' Prefer project venv, then py launcher, then python on PATH.
|
' Prefer project venv, then py launcher, then python on PATH.
|
||||||
pythonExe = root & "\.venv\Scripts\pythonw.exe"
|
pythonExe = root & "\.venv\Scripts\pythonw.exe"
|
||||||
@@ -20,10 +19,10 @@ If Not fso.FileExists(pythonExe) Then
|
|||||||
End If
|
End If
|
||||||
|
|
||||||
sh.CurrentDirectory = root
|
sh.CurrentDirectory = root
|
||||||
' Window style 0 = hidden. Opens browser via NiceGUI show=True.
|
' Window style 0 = hidden.
|
||||||
cmd = """" & pythonExe & """ -m xlsx_clean.web_app --host 127.0.0.1 --port " & port
|
cmd = """" & pythonExe & """ -m xlsx_clean.gui_app"
|
||||||
If pythonExe = "py" Then
|
If pythonExe = "py" Then
|
||||||
cmd = "py -3 -m xlsx_clean.web_app --host 127.0.0.1 --port " & port
|
cmd = "py -3 -m xlsx_clean.gui_app"
|
||||||
End If
|
End If
|
||||||
|
|
||||||
sh.Run cmd, 0, False
|
sh.Run cmd, 0, False
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
"""Install a Desktop shortcut that launches New QC Sheet."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
||||||
DESKTOP_DIR = Path(__file__).resolve().parent
|
|
||||||
APP_DISPLAY_NAME = "New QC Sheet"
|
|
||||||
|
|
||||||
|
|
||||||
def _user_desktop() -> Path:
|
|
||||||
if sys.platform == "win32":
|
|
||||||
return Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Desktop"
|
|
||||||
# Linux / macOS
|
|
||||||
xdg = os.environ.get("XDG_DESKTOP_DIR")
|
|
||||||
if xdg:
|
|
||||||
return Path(xdg)
|
|
||||||
return Path.home() / "Desktop"
|
|
||||||
|
|
||||||
|
|
||||||
def install_windows() -> Path:
|
|
||||||
ps1 = DESKTOP_DIR / "Install-DesktopShortcut.ps1"
|
|
||||||
subprocess.run(
|
|
||||||
[
|
|
||||||
"powershell",
|
|
||||||
"-NoProfile",
|
|
||||||
"-ExecutionPolicy",
|
|
||||||
"Bypass",
|
|
||||||
"-File",
|
|
||||||
str(ps1),
|
|
||||||
],
|
|
||||||
check=True,
|
|
||||||
)
|
|
||||||
return _user_desktop() / f"{APP_DISPLAY_NAME}.lnk"
|
|
||||||
|
|
||||||
|
|
||||||
def install_linux() -> Path:
|
|
||||||
desktop = _user_desktop()
|
|
||||||
desktop.mkdir(parents=True, exist_ok=True)
|
|
||||||
python = REPO_ROOT / ".venv" / "bin" / "python"
|
|
||||||
if not python.is_file():
|
|
||||||
python = Path(sys.executable)
|
|
||||||
out = desktop / f"{APP_DISPLAY_NAME}.desktop"
|
|
||||||
legacy = desktop / "XlsxClean.desktop"
|
|
||||||
if legacy.is_file():
|
|
||||||
legacy.unlink()
|
|
||||||
exec_line = (
|
|
||||||
f"{python} -m xlsx_clean.web_app --host 127.0.0.1 --port 8080"
|
|
||||||
)
|
|
||||||
icon_png = DESKTOP_DIR / "xlsx-clean.png"
|
|
||||||
icon_line = str(icon_png) if icon_png.is_file() else "applications-office"
|
|
||||||
content = f"""[Desktop Entry]
|
|
||||||
Type=Application
|
|
||||||
Version=1.0
|
|
||||||
Name={APP_DISPLAY_NAME}
|
|
||||||
Comment=Create a new QC datasheet
|
|
||||||
Exec={exec_line}
|
|
||||||
Path={REPO_ROOT}
|
|
||||||
Icon={icon_line}
|
|
||||||
Terminal=false
|
|
||||||
Categories=Office;
|
|
||||||
StartupNotify=true
|
|
||||||
"""
|
|
||||||
out.write_text(content, encoding="utf-8")
|
|
||||||
out.chmod(out.stat().st_mode | 0o111)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
if sys.platform == "win32":
|
|
||||||
path = install_windows()
|
|
||||||
else:
|
|
||||||
path = install_linux()
|
|
||||||
print(f"Desktop shortcut created: {path}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,131 +1,107 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Operator setup for New QC Sheet on Ubuntu/Debian desktops.
|
# Operator setup for New QC Sheet on Debian/Ubuntu Linux desktops.
|
||||||
# Installs system GTK/WebKit bindings, creates a uv venv that uses the OS
|
|
||||||
# Python (so apt python3-gi/_gi loads), syncs deps, and installs a Desktop shortcut.
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
|
|
||||||
APT_PACKAGES=(python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1)
|
SYS_PY=/usr/bin/python3
|
||||||
|
|
||||||
need_apt=()
|
|
||||||
for pkg in "${APT_PACKAGES[@]}"; do
|
|
||||||
if ! dpkg -s "$pkg" >/dev/null 2>&1; then
|
|
||||||
need_apt+=("$pkg")
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if ((${#need_apt[@]})); then
|
|
||||||
echo "Missing system packages for the native window: ${need_apt[*]}"
|
|
||||||
echo "Installing with apt (sudo)..."
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y "${need_apt[@]}"
|
|
||||||
else
|
|
||||||
echo "System GTK/WebKit packages already installed."
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ! command -v uv >/dev/null 2>&1; then
|
if ! command -v uv >/dev/null 2>&1; then
|
||||||
echo "uv not found on PATH. Install uv first: https://docs.astral.sh/uv/" >&2
|
echo "uv not found on PATH. Install uv first: https://docs.astral.sh/uv/" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Must use the OS interpreter that apt's python3-gi/_gi was built for.
|
if ! command -v apt-get >/dev/null 2>&1; then
|
||||||
# Never use `command -v python3`: with an activated .venv or uv on PATH it often
|
echo "This setup script requires apt-get (Debian/Ubuntu). Install python3-gi,"
|
||||||
# resolves to ~/.local/share/uv/python/... which cannot import apt gi.
|
echo "gir1.2-gtk-3.0, and gir1.2-webkit2-4.1 (or WebKit2 4.0) manually." >&2
|
||||||
resolve_os_python() {
|
|
||||||
local candidate resolved
|
|
||||||
for candidate in /usr/bin/python3 /usr/local/bin/python3; do
|
|
||||||
if [[ -x "$candidate" ]]; then
|
|
||||||
resolved="$(readlink -f "$candidate")"
|
|
||||||
# Reject uv-managed installs even if somehow symlinked here.
|
|
||||||
if [[ "$resolved" == *"/uv/python/"* ]] || [[ "$resolved" == *".local/share/uv/"* ]]; then
|
|
||||||
continue
|
|
||||||
fi
|
|
||||||
printf '%s\n' "$resolved"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
if ! SYSTEM_PYTHON="$(resolve_os_python)"; then
|
|
||||||
echo "OS Python not found at /usr/bin/python3." >&2
|
|
||||||
echo "Install python3 from apt, then re-run. Do not rely on uv-managed Python." >&2
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
SYSTEM_VERSION="$("$SYSTEM_PYTHON" -c 'import sys; print(sys.version.split()[0])')"
|
if [[ ! -x "$SYS_PY" ]]; then
|
||||||
echo "Using OS Python: ${SYSTEM_PYTHON} (${SYSTEM_VERSION})"
|
echo "System Python not found at $SYS_PY" >&2
|
||||||
if PATH_PYTHON="$(command -v python3 2>/dev/null || true)"; then
|
exit 1
|
||||||
PATH_PYTHON_RESOLVED="$(readlink -f "$PATH_PYTHON" 2>/dev/null || true)"
|
|
||||||
if [[ -n "$PATH_PYTHON_RESOLVED" && "$PATH_PYTHON_RESOLVED" != "$SYSTEM_PYTHON" ]]; then
|
|
||||||
echo "Note: PATH python3 is ${PATH_PYTHON_RESOLVED} (ignored; apt gi needs OS Python)."
|
|
||||||
fi
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Preflight: system Python must import Gtk/WebKit..."
|
packages=(python3-gi gir1.2-gtk-3.0)
|
||||||
if ! "$SYSTEM_PYTHON" - <<'PY'
|
if apt-cache show gir1.2-webkit2-4.1 >/dev/null 2>&1; then
|
||||||
import gi
|
packages+=(gir1.2-webkit2-4.1)
|
||||||
|
elif apt-cache show gir1.2-webkit2-4.0 >/dev/null 2>&1; then
|
||||||
|
packages+=(gir1.2-webkit2-4.0)
|
||||||
|
else
|
||||||
|
echo "Neither gir1.2-webkit2-4.1 nor gir1.2-webkit2-4.0 is available." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
missing=()
|
||||||
|
for package in "${packages[@]}"; do
|
||||||
|
if ! dpkg-query -W -f='${db:Status-Status}' "$package" 2>/dev/null | grep -qx installed; then
|
||||||
|
missing+=("$package")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if ((${#missing[@]})); then
|
||||||
|
echo "Installing GTK/WebKitGTK requirements: ${missing[*]}"
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y "${missing[@]}"
|
||||||
|
else
|
||||||
|
echo "GTK/WebKitGTK requirements already installed."
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! "$SYS_PY" -c 'import gi' >/dev/null 2>&1; then
|
||||||
|
echo "System $SYS_PY cannot import gi. Install python3-gi." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
enable_system_site_packages() {
|
||||||
|
local cfg=.venv/pyvenv.cfg
|
||||||
|
if [[ ! -f "$cfg" ]]; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if grep -q '^include-system-site-packages' "$cfg"; then
|
||||||
|
sed -i 's/^include-system-site-packages = .*/include-system-site-packages = true/' "$cfg"
|
||||||
|
else
|
||||||
|
printf '\ninclude-system-site-packages = true\n' >> "$cfg"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ ! -x .venv/bin/python ]] || ! .venv/bin/python -c 'import gi' >/dev/null 2>&1; then
|
||||||
|
echo "Creating venv with the system Python and system site packages..."
|
||||||
|
rm -rf .venv
|
||||||
|
uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Syncing dependencies..."
|
||||||
|
# Pin the same interpreter so uv does not honor .python-version (3.12) and
|
||||||
|
# recreate a managed venv without apt gi (python3-gi).
|
||||||
|
uv sync --python /usr/bin/python3 --no-managed-python
|
||||||
|
|
||||||
|
if ! .venv/bin/python -c 'import gi' >/dev/null 2>&1; then
|
||||||
|
echo "Restoring system site packages on .venv so apt gi is importable..."
|
||||||
|
enable_system_site_packages
|
||||||
|
fi
|
||||||
|
|
||||||
|
venv_ver="$(.venv/bin/python -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
|
||||||
|
sys_ver="$("$SYS_PY" -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
|
||||||
|
if [[ "$venv_ver" != "$sys_ver" ]]; then
|
||||||
|
echo "venv Python $venv_ver does not match system Python $sys_ver at $SYS_PY." >&2
|
||||||
|
echo "uv likely honored .python-version instead of the system interpreter." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Verifying GTK and WebKit2 bindings..."
|
||||||
|
.venv/bin/python -c '
|
||||||
|
import gi
|
||||||
gi.require_version("Gtk", "3.0")
|
gi.require_version("Gtk", "3.0")
|
||||||
gi.require_version("Gdk", "3.0")
|
|
||||||
try:
|
try:
|
||||||
gi.require_version("WebKit2", "4.1")
|
gi.require_version("WebKit2", "4.1")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
gi.require_version("WebKit2", "4.0")
|
gi.require_version("WebKit2", "4.0")
|
||||||
from gi.repository import Gtk, WebKit2 # noqa: F401
|
from gi.repository import Gtk, WebKit2
|
||||||
|
print("GTK/WebKit2 bindings available")
|
||||||
print("System gi OK")
|
'
|
||||||
PY
|
|
||||||
then
|
|
||||||
echo "System Python cannot import Gtk/WebKit. Install:" >&2
|
|
||||||
echo " sudo apt install ${APT_PACKAGES[*]}" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Creating .venv with system-site-packages (OS Python only)..."
|
|
||||||
rm -rf .venv
|
|
||||||
# --no-managed-python: refuse uv-managed builds that break apt _gi.
|
|
||||||
# Also pass it to sync — otherwise uv may recreate .venv from a managed
|
|
||||||
# download (see .python-version) and undo the system interpreter.
|
|
||||||
uv venv --python "$SYSTEM_PYTHON" --no-managed-python --system-site-packages
|
|
||||||
uv sync --python "$SYSTEM_PYTHON" --no-managed-python
|
|
||||||
|
|
||||||
echo "Checking native-window bindings in .venv..."
|
|
||||||
if ! .venv/bin/python - <<'PY'
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.insert(0, "src")
|
|
||||||
from xlsx_clean.web_app import (
|
|
||||||
_linux_has_display,
|
|
||||||
_linux_webview_libs_available,
|
|
||||||
_NATIVE_DIAG,
|
|
||||||
)
|
|
||||||
|
|
||||||
ok_libs = _linux_webview_libs_available()
|
|
||||||
ok_display = _linux_has_display()
|
|
||||||
print(f"Python: {sys.version.split()[0]} ({sys.executable})")
|
|
||||||
print(f"GTK/WebKit usable: {ok_libs}")
|
|
||||||
print(f"Display available: {ok_display}")
|
|
||||||
if not ok_libs:
|
|
||||||
if _NATIVE_DIAG:
|
|
||||||
print(f"Detail: {_NATIVE_DIAG}", file=sys.stderr)
|
|
||||||
sys.exit(2)
|
|
||||||
PY
|
|
||||||
then
|
|
||||||
echo "ERROR: GTK/WebKit still not usable from .venv." >&2
|
|
||||||
echo "The venv Python must be the same build as apt python3-gi." >&2
|
|
||||||
echo "Retry: rm -rf .venv && uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages && uv sync" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Native window libraries look OK."
|
|
||||||
|
|
||||||
echo "Installing Desktop shortcut..."
|
|
||||||
.venv/bin/python desktop/install_desktop_shortcut.py
|
|
||||||
|
|
||||||
echo
|
echo
|
||||||
echo "Done. Launch with:"
|
echo "Done. Launch with:"
|
||||||
echo " .venv/bin/python -m xlsx_clean.web_app"
|
echo " .venv/bin/python -m xlsx_clean.gui_app"
|
||||||
echo "or use the Desktop shortcut."
|
echo "Create your own shortcut to that command."
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
[Desktop Entry]
|
|
||||||
Type=Application
|
|
||||||
Version=1.0
|
|
||||||
Name=New QC Sheet
|
|
||||||
Comment=Create a new QC datasheet
|
|
||||||
# Exec is filled by install_desktop_shortcut.py; placeholder for manual edits:
|
|
||||||
Exec=bash -lc 'cd "$(dirname "%k")/.." && (.venv/bin/python -m xlsx_clean.web_app --host 127.0.0.1 --port 8080)'
|
|
||||||
Path=
|
|
||||||
Icon=applications-office
|
|
||||||
Terminal=false
|
|
||||||
Categories=Office;
|
|
||||||
StartupNotify=true
|
|
||||||
@@ -8,37 +8,47 @@ Or manually:
|
|||||||
pyinstaller packaging/xlsx_clean.spec
|
pyinstaller packaging/xlsx_clean.spec
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
from PyInstaller.utils.hooks import collect_all
|
from PyInstaller.utils.hooks import collect_all
|
||||||
|
|
||||||
block_cipher = None
|
block_cipher = None
|
||||||
|
|
||||||
|
# SPECPATH is set by PyInstaller to the folder containing this spec file
|
||||||
|
ROOT_DIR = os.path.abspath(os.path.join(SPECPATH, ".."))
|
||||||
|
|
||||||
datas = [
|
datas = [
|
||||||
("src/xlsx_clean/file_data.csv", "xlsx_clean"),
|
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "file_data.csv"), "xlsx_clean"),
|
||||||
("src/xlsx_clean/strings.txt", "xlsx_clean"),
|
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "strings.txt"), "xlsx_clean"),
|
||||||
|
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "fonts"), "xlsx_clean/fonts"),
|
||||||
|
(os.path.join(ROOT_DIR, "src", "xlsx_clean", "ui"), "xlsx_clean/ui"),
|
||||||
]
|
]
|
||||||
binaries = []
|
binaries = []
|
||||||
hiddenimports = [
|
hiddenimports = [
|
||||||
"xlsx_clean",
|
"xlsx_clean",
|
||||||
"xlsx_clean.web_app",
|
"xlsx_clean.core",
|
||||||
|
"xlsx_clean.gui_app",
|
||||||
"xlsx_clean.clean_cells",
|
"xlsx_clean.clean_cells",
|
||||||
"xlsx_clean.ooxml_backend",
|
"xlsx_clean.ooxml_backend",
|
||||||
"xlsx_clean.com_backend",
|
"xlsx_clean.com_backend",
|
||||||
"xlsx_clean.paths",
|
"xlsx_clean.paths",
|
||||||
]
|
]
|
||||||
|
|
||||||
tmp_ret = collect_all("nicegui")
|
webview_ret = collect_all("webview")
|
||||||
datas += tmp_ret[0]
|
datas += webview_ret[0]
|
||||||
binaries += tmp_ret[1]
|
binaries += webview_ret[1]
|
||||||
hiddenimports += tmp_ret[2]
|
hiddenimports += webview_ret[2]
|
||||||
|
|
||||||
tmp_ret = collect_all("webview")
|
if sys.platform == "win32":
|
||||||
datas += tmp_ret[0]
|
clr_ret = collect_all("clr_loader")
|
||||||
binaries += tmp_ret[1]
|
datas += clr_ret[0]
|
||||||
hiddenimports += tmp_ret[2]
|
binaries += clr_ret[1]
|
||||||
|
hiddenimports += clr_ret[2]
|
||||||
|
hiddenimports += ["clr", "clr_loader", "pythonnet"]
|
||||||
|
|
||||||
a = Analysis(
|
a = Analysis(
|
||||||
["src/xlsx_clean/web_app.py"],
|
[os.path.join(ROOT_DIR, "src", "xlsx_clean", "gui_app.py")],
|
||||||
pathex=["."],
|
pathex=[ROOT_DIR],
|
||||||
binaries=binaries,
|
binaries=binaries,
|
||||||
datas=datas,
|
datas=datas,
|
||||||
hiddenimports=hiddenimports,
|
hiddenimports=hiddenimports,
|
||||||
@@ -54,7 +64,6 @@ a = Analysis(
|
|||||||
|
|
||||||
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
||||||
|
|
||||||
# onedir is more reliable than onefile for NiceGUI assets
|
|
||||||
exe = EXE(
|
exe = EXE(
|
||||||
pyz,
|
pyz,
|
||||||
a.scripts,
|
a.scripts,
|
||||||
@@ -65,13 +74,13 @@ exe = EXE(
|
|||||||
bootloader_ignore_signals=False,
|
bootloader_ignore_signals=False,
|
||||||
strip=False,
|
strip=False,
|
||||||
upx=True,
|
upx=True,
|
||||||
console=False, # no black console window
|
console=False,
|
||||||
disable_windowed_traceback=False,
|
disable_windowed_traceback=False,
|
||||||
argv_emulation=False,
|
argv_emulation=False,
|
||||||
target_arch=None,
|
target_arch=None,
|
||||||
codesign_identity=None,
|
codesign_identity=None,
|
||||||
entitlements_file=None,
|
entitlements_file=None,
|
||||||
icon="desktop/xlsx-clean.ico",
|
icon=os.path.join(ROOT_DIR, "desktop", "xlsx-clean.ico"),
|
||||||
)
|
)
|
||||||
|
|
||||||
coll = COLLECT(
|
coll = COLLECT(
|
||||||
|
|||||||
@@ -1,15 +1,13 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "xlsx-clean"
|
name = "xlsx-clean"
|
||||||
version = "0.1.0"
|
version = "1.0.0"
|
||||||
description = "Create a new QC datasheet from the latest matching workbook"
|
description = "Create a new QC datasheet from the latest matching workbook"
|
||||||
authors = [
|
authors = [
|
||||||
{ name = "Diaco Soltanpour", email = "dyaco8464@yahoo.com" }
|
{ name = "Diaco Soltanpour", email = "dyaco8464@yahoo.com" }
|
||||||
]
|
]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"beaupy>=3.12.0",
|
"beaupy>=3.12.0",
|
||||||
"nicegui>=3.14.0",
|
"pywebview>=5.0",
|
||||||
"pandas>=3.0.3",
|
|
||||||
"pywebview>=6.2.1",
|
|
||||||
"pywin32>=312; sys_platform == 'win32'",
|
"pywin32>=312; sys_platform == 'win32'",
|
||||||
]
|
]
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@@ -17,7 +15,7 @@ requires-python = ">=3.12"
|
|||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
xlsx-clean = "xlsx_clean.clean_cells:main"
|
xlsx-clean = "xlsx_clean.clean_cells:main"
|
||||||
xlsx-clean-web = "xlsx_clean.web_app:main"
|
xlsx-clean-gui = "xlsx_clean.gui_app:main"
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
desktop = [
|
desktop = [
|
||||||
@@ -39,5 +37,30 @@ packages = ["src/xlsx_clean"]
|
|||||||
"src/xlsx_clean/strings.txt" = "xlsx_clean/strings.txt"
|
"src/xlsx_clean/strings.txt" = "xlsx_clean/strings.txt"
|
||||||
"src/xlsx_clean/new_xslx.bat" = "xlsx_clean/new_xslx.bat"
|
"src/xlsx_clean/new_xslx.bat" = "xlsx_clean/new_xslx.bat"
|
||||||
|
|
||||||
|
[dependency-groups]
|
||||||
|
test = [
|
||||||
|
"pytest>=8.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
|
||||||
[tool.uv]
|
[tool.uv]
|
||||||
package = true
|
package = true
|
||||||
|
default-groups = ["test"]
|
||||||
|
|
||||||
|
# Version bumps: `uvx bump-my-version bump patch|minor|major`
|
||||||
|
# current_version falls back to [project].version above.
|
||||||
|
[tool.bumpversion]
|
||||||
|
commit = false
|
||||||
|
tag = false
|
||||||
|
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
|
||||||
|
serialize = ["{major}.{minor}.{patch}"]
|
||||||
|
message = "Bump version: {current_version} → {new_version}"
|
||||||
|
tag_name = "v{new_version}"
|
||||||
|
tag_message = "Bump version: {current_version} → {new_version}"
|
||||||
|
|
||||||
|
[[tool.bumpversion.files]]
|
||||||
|
filename = "pyproject.toml"
|
||||||
|
search = 'version = "{current_version}"'
|
||||||
|
replace = 'version = "{new_version}"'
|
||||||
|
|||||||
@@ -1,239 +1,19 @@
|
|||||||
"""Interactive CLI: copy latest QC workbook, clear cells, stamp serial."""
|
"""Interactive CLI: select set/ink/serial, create a cleaned QC workbook."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import shutil
|
|
||||||
import tempfile
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from datetime import datetime
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pandas
|
|
||||||
from beaupy import prompt, select
|
from beaupy import prompt, select
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
|
||||||
from xlsx_clean.app_logging import get_logger
|
from xlsx_clean.core import (
|
||||||
from xlsx_clean.paths import (
|
create_datasheet,
|
||||||
default_backend,
|
list_ink_colors,
|
||||||
get_opencloud_root,
|
list_sets,
|
||||||
package_file,
|
load_config,
|
||||||
remap_opencloud_path,
|
|
||||||
resolve_backend,
|
|
||||||
)
|
)
|
||||||
|
from xlsx_clean.paths import default_backend, resolve_backend
|
||||||
NEW_VALUE = ""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class CreateResult:
|
|
||||||
ok: bool
|
|
||||||
message: str
|
|
||||||
template: Path | None = None
|
|
||||||
destination: Path | None = None
|
|
||||||
backend: str | None = None
|
|
||||||
skipped: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
def find_last_workbook(files: list[str]) -> str:
|
|
||||||
return sorted(files)[-1]
|
|
||||||
|
|
||||||
|
|
||||||
def get_workbook_names(
|
|
||||||
files: list[str],
|
|
||||||
batch_serial: str,
|
|
||||||
source_dir: Path,
|
|
||||||
pattern: str,
|
|
||||||
) -> tuple[str, Path]:
|
|
||||||
last_workbook = find_last_workbook(files)
|
|
||||||
path_of_the_year = Path(str(source_dir).replace("2025", str(datetime.now().year)))
|
|
||||||
return last_workbook, path_of_the_year / pattern.replace(
|
|
||||||
"[SERIAL]", batch_serial.split("/")[0]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def load_config() -> tuple[list[str], pandas.DataFrame]:
|
|
||||||
strings_path = package_file("strings.txt")
|
|
||||||
with open(strings_path, encoding="utf-8") as f:
|
|
||||||
content = [line.strip() for line in f.readlines()]
|
|
||||||
|
|
||||||
path_df = pandas.read_csv(package_file("file_data.csv"))
|
|
||||||
root = get_opencloud_root()
|
|
||||||
path_df["dir"] = [
|
|
||||||
str(remap_opencloud_path(path, root)) for path in path_df["dir"]
|
|
||||||
]
|
|
||||||
return content, path_df
|
|
||||||
|
|
||||||
|
|
||||||
def list_sets(path_df: pandas.DataFrame) -> list[str]:
|
|
||||||
return list(
|
|
||||||
path_df.drop_duplicates(subset=["set_name"], keep="first")["set_name"]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def list_ink_colors(path_df: pandas.DataFrame, selected_set: str) -> list[str]:
|
|
||||||
return [
|
|
||||||
Path(path).stem
|
|
||||||
for path in list(path_df[path_df["set_name"] == selected_set]["dir"])
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def create_datasheet(
|
|
||||||
selected_set: str,
|
|
||||||
selected_dir: str,
|
|
||||||
batch_serial: str,
|
|
||||||
backend: str | None = None,
|
|
||||||
path_df: pandas.DataFrame | None = None,
|
|
||||||
addin_paths: list[str] | None = None,
|
|
||||||
) -> CreateResult:
|
|
||||||
"""Create a cleaned QC workbook for the given selection.
|
|
||||||
|
|
||||||
Shared by the CLI and the NiceGUI web UI.
|
|
||||||
"""
|
|
||||||
log = get_logger()
|
|
||||||
ctx = f"set={selected_set!r} ink={selected_dir!r} serial={batch_serial!r}"
|
|
||||||
|
|
||||||
if not selected_set:
|
|
||||||
message = "Select a set."
|
|
||||||
log.error("Create failed: %s (%s)", message, ctx)
|
|
||||||
return CreateResult(ok=False, message=message)
|
|
||||||
if not selected_dir:
|
|
||||||
message = "Select an ink color."
|
|
||||||
log.error("Create failed: %s (%s)", message, ctx)
|
|
||||||
return CreateResult(ok=False, message=message)
|
|
||||||
if not batch_serial or not str(batch_serial).strip():
|
|
||||||
message = "Enter a serial."
|
|
||||||
log.error("Create failed: %s (%s)", message, ctx)
|
|
||||||
return CreateResult(ok=False, message=message)
|
|
||||||
|
|
||||||
batch_serial = str(batch_serial).strip()
|
|
||||||
ctx = f"set={selected_set!r} ink={selected_dir!r} serial={batch_serial!r}"
|
|
||||||
try:
|
|
||||||
resolved_backend = resolve_backend(backend)
|
|
||||||
except (ValueError, RuntimeError) as exc:
|
|
||||||
log.error("Create failed: %s (%s)", exc, ctx)
|
|
||||||
return CreateResult(ok=False, message=str(exc))
|
|
||||||
|
|
||||||
ctx = f"{ctx} backend={resolved_backend}"
|
|
||||||
|
|
||||||
if path_df is None or addin_paths is None:
|
|
||||||
content, loaded_df = load_config()
|
|
||||||
if path_df is None:
|
|
||||||
path_df = loaded_df
|
|
||||||
if addin_paths is None:
|
|
||||||
addin_paths = content[3:5] if len(content) >= 5 else []
|
|
||||||
|
|
||||||
matches = path_df[
|
|
||||||
(path_df["set_name"] == selected_set)
|
|
||||||
& (path_df["dir"].str.endswith(selected_dir))
|
|
||||||
]
|
|
||||||
if matches.empty:
|
|
||||||
message = f"No config row for set={selected_set!r} ink={selected_dir!r}."
|
|
||||||
log.error("Create failed: %s (%s)", message, ctx)
|
|
||||||
return CreateResult(ok=False, message=message)
|
|
||||||
|
|
||||||
row = matches.iloc[0]
|
|
||||||
path_ = Path(row["dir"])
|
|
||||||
pattern = row["pattern"]
|
|
||||||
search_pattern = pattern.replace("[SERIAL]", "*")
|
|
||||||
files = [str(x) for x in path_.glob(search_pattern) if x.is_file()]
|
|
||||||
if not files:
|
|
||||||
message = f"No workbooks matching {search_pattern!r} in {path_}"
|
|
||||||
log.error("Create failed: %s (%s)", message, ctx)
|
|
||||||
return CreateResult(
|
|
||||||
ok=False,
|
|
||||||
message=message,
|
|
||||||
backend=resolved_backend,
|
|
||||||
)
|
|
||||||
|
|
||||||
ref_workbook_name, new_workbook_name = get_workbook_names(
|
|
||||||
files, batch_serial, path_, pattern
|
|
||||||
)
|
|
||||||
template = Path(ref_workbook_name)
|
|
||||||
|
|
||||||
if new_workbook_name.is_file():
|
|
||||||
message = f"Destination already exists, skipped: {new_workbook_name}"
|
|
||||||
log.info(
|
|
||||||
"Create skipped: %s (template=%s destination=%s %s)",
|
|
||||||
message,
|
|
||||||
template,
|
|
||||||
new_workbook_name,
|
|
||||||
ctx,
|
|
||||||
)
|
|
||||||
return CreateResult(
|
|
||||||
ok=True,
|
|
||||||
skipped=True,
|
|
||||||
message=message,
|
|
||||||
template=template,
|
|
||||||
destination=new_workbook_name,
|
|
||||||
backend=resolved_backend,
|
|
||||||
)
|
|
||||||
|
|
||||||
cells_to_clear = row["cells_to_clear"]
|
|
||||||
notes_cell = row["notes_cell"]
|
|
||||||
serial_cell = row["serial_cell"]
|
|
||||||
|
|
||||||
try:
|
|
||||||
if resolved_backend == "com":
|
|
||||||
from xlsx_clean.com_backend import clean_workbook_com
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory(prefix="xlsx_clean_") as tmp:
|
|
||||||
temp_workbook = Path(tmp) / "temp_workbook.xlsx"
|
|
||||||
shutil.copyfile(ref_workbook_name, temp_workbook)
|
|
||||||
clean_workbook_com(
|
|
||||||
source=temp_workbook,
|
|
||||||
destination=new_workbook_name,
|
|
||||||
cells_to_clear=cells_to_clear,
|
|
||||||
notes_cell=notes_cell,
|
|
||||||
serial_cell=serial_cell,
|
|
||||||
batch_serial=batch_serial,
|
|
||||||
addin_paths=addin_paths or [],
|
|
||||||
notes_value=NEW_VALUE,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
from xlsx_clean.ooxml_backend import clean_workbook_ooxml
|
|
||||||
|
|
||||||
clean_workbook_ooxml(
|
|
||||||
source=ref_workbook_name,
|
|
||||||
destination=new_workbook_name,
|
|
||||||
cells_to_clear=cells_to_clear,
|
|
||||||
notes_cell=notes_cell,
|
|
||||||
serial_cell=serial_cell,
|
|
||||||
batch_serial=batch_serial,
|
|
||||||
notes_value=NEW_VALUE,
|
|
||||||
)
|
|
||||||
except Exception as exc: # noqa: BLE001 - surface to CLI/UI
|
|
||||||
message = f"Failed to create workbook: {exc}"
|
|
||||||
log.exception(
|
|
||||||
"Create failed: %s (template=%s destination=%s %s)",
|
|
||||||
message,
|
|
||||||
template,
|
|
||||||
new_workbook_name,
|
|
||||||
ctx,
|
|
||||||
)
|
|
||||||
return CreateResult(
|
|
||||||
ok=False,
|
|
||||||
message=message,
|
|
||||||
template=template,
|
|
||||||
destination=new_workbook_name,
|
|
||||||
backend=resolved_backend,
|
|
||||||
)
|
|
||||||
|
|
||||||
message = f"Wrote {new_workbook_name}"
|
|
||||||
log.info(
|
|
||||||
"Create succeeded: %s (template=%s destination=%s %s)",
|
|
||||||
message,
|
|
||||||
template,
|
|
||||||
new_workbook_name,
|
|
||||||
ctx,
|
|
||||||
)
|
|
||||||
return CreateResult(
|
|
||||||
ok=True,
|
|
||||||
message=message,
|
|
||||||
template=template,
|
|
||||||
destination=new_workbook_name,
|
|
||||||
backend=resolved_backend,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||||
@@ -249,41 +29,58 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|||||||
default=None,
|
default=None,
|
||||||
help=(
|
help=(
|
||||||
"Excel edit backend: 'com' (Windows Excel + add-ins) or "
|
"Excel edit backend: 'com' (Windows Excel + add-ins) or "
|
||||||
f"'ooxml' (surgical zip edit). Default: {default_backend()}."
|
f"'ooxml' (surgical zip edit). Default: {default_backend()} (Overrides config.toml)."
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--root",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Override the root directory for the selected set.",
|
||||||
|
)
|
||||||
return parser.parse_args(argv)
|
return parser.parse_args(argv)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def run(argv: list[str] | None = None) -> int:
|
def run(argv: list[str] | None = None) -> int:
|
||||||
|
from pathlib import Path
|
||||||
args = parse_args(argv)
|
args = parse_args(argv)
|
||||||
|
|
||||||
|
content, rows, config = load_config()
|
||||||
|
|
||||||
# Validate early so CLI fails fast on unsupported COM.
|
# Validate early so CLI fails fast on unsupported COM.
|
||||||
try:
|
try:
|
||||||
backend = resolve_backend(args.backend)
|
backend = resolve_backend(args.backend, config.get("backend"))
|
||||||
except (ValueError, RuntimeError) as exc:
|
except (ValueError, RuntimeError) as exc:
|
||||||
Console().print(f"[red]{exc}[/red]")
|
Console().print(f"[red]{exc}[/red]")
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
content, path_df = load_config()
|
|
||||||
q1, q2, q3 = content[0], content[1], content[2]
|
q1, q2, q3 = content[0], content[1], content[2]
|
||||||
addin_paths = content[3:5] if len(content) >= 5 else []
|
addin_paths = content[3:5] if len(content) >= 5 else []
|
||||||
|
|
||||||
console = Console()
|
console = Console()
|
||||||
console.print(q1)
|
console.print(q1)
|
||||||
selected_set = select(list_sets(path_df), cursor_style="cyan")
|
selected_set = select(list_sets(rows), cursor_style="cyan")
|
||||||
|
|
||||||
console.print(q2)
|
console.print(q2)
|
||||||
selected_dir = select(list_ink_colors(path_df, selected_set))
|
selected_dir = select(list_ink_colors(rows, selected_set))
|
||||||
console.print(f"Selected: {selected_dir}")
|
console.print(f"Selected: {selected_dir}")
|
||||||
|
|
||||||
|
if args.root:
|
||||||
|
for r in rows:
|
||||||
|
if r["set_name"] == selected_set:
|
||||||
|
r["dir"] = str(Path(args.root) / r["rel_dir"])
|
||||||
|
|
||||||
batch_serial = prompt(q3, target_type=str)
|
batch_serial = prompt(q3, target_type=str)
|
||||||
result = create_datasheet(
|
result = create_datasheet(
|
||||||
selected_set=selected_set,
|
selected_set=selected_set,
|
||||||
selected_dir=selected_dir,
|
selected_dir=selected_dir,
|
||||||
batch_serial=batch_serial,
|
batch_serial=batch_serial,
|
||||||
backend=backend,
|
backend=backend,
|
||||||
path_df=path_df,
|
rows=rows,
|
||||||
addin_paths=addin_paths,
|
addin_paths=addin_paths,
|
||||||
|
config=config,
|
||||||
)
|
)
|
||||||
|
|
||||||
if result.template is not None:
|
if result.template is not None:
|
||||||
|
|||||||
263
src/xlsx_clean/core.py
Normal file
263
src/xlsx_clean/core.py
Normal file
@@ -0,0 +1,263 @@
|
|||||||
|
"""Core business logic for xlsx_clean."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
from xlsx_clean.app_logging import get_logger
|
||||||
|
from xlsx_clean.paths import (
|
||||||
|
default_config_path,
|
||||||
|
package_file,
|
||||||
|
resolve_backend,
|
||||||
|
)
|
||||||
|
|
||||||
|
DEFAULT_CONFIG_CONTENT = """\
|
||||||
|
# Configuration for xlsx_clean
|
||||||
|
|
||||||
|
# backend options:
|
||||||
|
# - "com": Use Microsoft Excel COM (Windows only, keeps Excel visible)
|
||||||
|
# - "ooxml": Surgical zip edit (Cross-platform, very fast, preserves non-worksheet data)
|
||||||
|
backend = "com"
|
||||||
|
|
||||||
|
[sets]
|
||||||
|
"Kimia Razi" = "D:\\\\OpenCloud\\\\Kimia Razi"
|
||||||
|
"inco" = "D:\\\\OpenCloud\\\\inco"
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
NEW_VALUE = ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CreateResult:
|
||||||
|
ok: bool
|
||||||
|
message: str
|
||||||
|
template: Path | None = None
|
||||||
|
destination: Path | None = None
|
||||||
|
backend: str | None = None
|
||||||
|
skipped: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def find_last_workbook(files: list[str]) -> str:
|
||||||
|
return sorted(files)[-1]
|
||||||
|
|
||||||
|
|
||||||
|
def get_workbook_names(
|
||||||
|
files: list[str],
|
||||||
|
batch_serial: str,
|
||||||
|
source_dir: Path,
|
||||||
|
pattern: str,
|
||||||
|
) -> tuple[str, Path]:
|
||||||
|
last_workbook = find_last_workbook(files)
|
||||||
|
path_of_the_year = Path(str(source_dir).replace("2025", str(datetime.now().year)))
|
||||||
|
return last_workbook, path_of_the_year / pattern.replace(
|
||||||
|
"[SERIAL]", batch_serial.split("/")[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config() -> tuple[list[str], list[dict], dict]:
|
||||||
|
config_path = default_config_path()
|
||||||
|
if not config_path.exists():
|
||||||
|
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
config_path.write_text(DEFAULT_CONFIG_CONTENT, encoding="utf-8")
|
||||||
|
|
||||||
|
with open(config_path, "rb") as f:
|
||||||
|
config = tomllib.load(f)
|
||||||
|
|
||||||
|
strings_path = package_file("strings.txt")
|
||||||
|
with open(strings_path, encoding="utf-8") as f:
|
||||||
|
content = [line.strip() for line in f.readlines()]
|
||||||
|
|
||||||
|
csv_path = package_file("file_data.csv")
|
||||||
|
rows = []
|
||||||
|
set_roots = config.get("sets", {})
|
||||||
|
with open(csv_path, encoding="utf-8") as f:
|
||||||
|
reader = csv.DictReader(f)
|
||||||
|
for row in reader:
|
||||||
|
set_name = row["set_name"]
|
||||||
|
rel_dir = row["dir"].replace("\\", "/")
|
||||||
|
row["rel_dir"] = rel_dir
|
||||||
|
root_str = set_roots.get(set_name, "")
|
||||||
|
if root_str:
|
||||||
|
row["dir"] = str(Path(root_str) / rel_dir)
|
||||||
|
else:
|
||||||
|
row["dir"] = str(Path(rel_dir))
|
||||||
|
rows.append(row)
|
||||||
|
|
||||||
|
return content, rows, config
|
||||||
|
|
||||||
|
|
||||||
|
def list_sets(rows: list[dict]) -> list[str]:
|
||||||
|
return list(dict.fromkeys(r["set_name"] for r in rows))
|
||||||
|
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
def _sort_key(name: str):
|
||||||
|
match = re.search(r'\d+', name)
|
||||||
|
num = int(match.group()) if match else 0
|
||||||
|
return (num, name)
|
||||||
|
|
||||||
|
def list_ink_colors(rows: list[dict], selected_set: str) -> list[str]:
|
||||||
|
inks = (Path(r["dir"]).stem for r in rows if r["set_name"] == selected_set)
|
||||||
|
return sorted(inks, key=_sort_key)
|
||||||
|
|
||||||
|
|
||||||
|
def create_datasheet(
|
||||||
|
selected_set: str,
|
||||||
|
selected_dir: str,
|
||||||
|
batch_serial: str,
|
||||||
|
backend: str | None = None,
|
||||||
|
rows: list[dict] | None = None,
|
||||||
|
addin_paths: list[str] | None = None,
|
||||||
|
config: dict | None = None,
|
||||||
|
) -> CreateResult:
|
||||||
|
log = get_logger()
|
||||||
|
ctx = f"set={selected_set!r} ink={selected_dir!r} serial={batch_serial!r}"
|
||||||
|
|
||||||
|
if not selected_set:
|
||||||
|
message = "Select a set."
|
||||||
|
log.error("Create failed: %s (%s)", message, ctx)
|
||||||
|
return CreateResult(ok=False, message=message)
|
||||||
|
if not selected_dir:
|
||||||
|
message = "Select an ink color."
|
||||||
|
log.error("Create failed: %s (%s)", message, ctx)
|
||||||
|
return CreateResult(ok=False, message=message)
|
||||||
|
if not batch_serial or not str(batch_serial).strip():
|
||||||
|
message = "Enter a serial."
|
||||||
|
log.error("Create failed: %s (%s)", message, ctx)
|
||||||
|
return CreateResult(ok=False, message=message)
|
||||||
|
|
||||||
|
batch_serial = str(batch_serial).strip()
|
||||||
|
ctx = f"set={selected_set!r} ink={selected_dir!r} serial={batch_serial!r}"
|
||||||
|
if config is None:
|
||||||
|
content, loaded_rows, config = load_config()
|
||||||
|
if rows is None:
|
||||||
|
rows = loaded_rows
|
||||||
|
if addin_paths is None:
|
||||||
|
addin_paths = content[3:5] if len(content) >= 5 else []
|
||||||
|
|
||||||
|
try:
|
||||||
|
resolved_backend = resolve_backend(backend, config.get("backend"))
|
||||||
|
except (ValueError, RuntimeError) as exc:
|
||||||
|
log.error("Create failed: %s (%s)", exc, ctx)
|
||||||
|
return CreateResult(ok=False, message=str(exc))
|
||||||
|
|
||||||
|
ctx = f"{ctx} backend={resolved_backend}"
|
||||||
|
|
||||||
|
matches = [r for r in rows if r["set_name"] == selected_set and r["dir"].endswith(selected_dir)]
|
||||||
|
if not matches:
|
||||||
|
message = f"No config row for set={selected_set!r} ink={selected_dir!r}."
|
||||||
|
log.error("Create failed: %s (%s)", message, ctx)
|
||||||
|
return CreateResult(ok=False, message=message)
|
||||||
|
|
||||||
|
row = matches[0]
|
||||||
|
path_ = Path(row["dir"])
|
||||||
|
pattern = row["pattern"]
|
||||||
|
search_pattern = pattern.replace("[SERIAL]", "*")
|
||||||
|
files = [str(x) for x in path_.glob(search_pattern) if x.is_file()]
|
||||||
|
|
||||||
|
if not files:
|
||||||
|
message = f"No workbooks matching {search_pattern!r} in {path_}"
|
||||||
|
log.error("Create failed: %s (%s)", message, ctx)
|
||||||
|
return CreateResult(
|
||||||
|
ok=False,
|
||||||
|
message=message,
|
||||||
|
backend=resolved_backend,
|
||||||
|
)
|
||||||
|
|
||||||
|
ref_workbook_name, new_workbook_name = get_workbook_names(
|
||||||
|
files, batch_serial, path_, pattern
|
||||||
|
)
|
||||||
|
template = Path(ref_workbook_name)
|
||||||
|
|
||||||
|
if new_workbook_name.is_file():
|
||||||
|
message = f"Destination already exists, skipped: {new_workbook_name}"
|
||||||
|
log.info(
|
||||||
|
"Create skipped: %s (template=%s destination=%s %s)",
|
||||||
|
message,
|
||||||
|
template,
|
||||||
|
new_workbook_name,
|
||||||
|
ctx,
|
||||||
|
)
|
||||||
|
return CreateResult(
|
||||||
|
ok=True,
|
||||||
|
skipped=True,
|
||||||
|
message=message,
|
||||||
|
template=template,
|
||||||
|
destination=new_workbook_name,
|
||||||
|
backend=resolved_backend,
|
||||||
|
)
|
||||||
|
|
||||||
|
cells_to_clear = row["cells_to_clear"]
|
||||||
|
notes_cell = row["notes_cell"]
|
||||||
|
serial_cell = row["serial_cell"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
if resolved_backend == "com":
|
||||||
|
from xlsx_clean.com_backend import clean_workbook_com
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory(prefix="xlsx_clean_") as tmp:
|
||||||
|
temp_workbook = Path(tmp) / "temp_workbook.xlsx"
|
||||||
|
shutil.copyfile(ref_workbook_name, temp_workbook)
|
||||||
|
clean_workbook_com(
|
||||||
|
source=temp_workbook,
|
||||||
|
destination=new_workbook_name,
|
||||||
|
cells_to_clear=cells_to_clear,
|
||||||
|
notes_cell=notes_cell,
|
||||||
|
serial_cell=serial_cell,
|
||||||
|
batch_serial=batch_serial,
|
||||||
|
addin_paths=addin_paths or [],
|
||||||
|
notes_value=NEW_VALUE,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
from xlsx_clean.ooxml_backend import clean_workbook_ooxml
|
||||||
|
|
||||||
|
clean_workbook_ooxml(
|
||||||
|
source=ref_workbook_name,
|
||||||
|
destination=new_workbook_name,
|
||||||
|
cells_to_clear=cells_to_clear,
|
||||||
|
notes_cell=notes_cell,
|
||||||
|
serial_cell=serial_cell,
|
||||||
|
batch_serial=batch_serial,
|
||||||
|
notes_value=NEW_VALUE,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 - surface to CLI/UI
|
||||||
|
message = f"Failed to create workbook: {exc}"
|
||||||
|
log.exception(
|
||||||
|
"Create failed: %s (template=%s destination=%s %s)",
|
||||||
|
message,
|
||||||
|
template,
|
||||||
|
new_workbook_name,
|
||||||
|
ctx,
|
||||||
|
)
|
||||||
|
return CreateResult(
|
||||||
|
ok=False,
|
||||||
|
message=message,
|
||||||
|
template=template,
|
||||||
|
destination=new_workbook_name,
|
||||||
|
backend=resolved_backend,
|
||||||
|
)
|
||||||
|
|
||||||
|
message = f"Wrote {new_workbook_name}"
|
||||||
|
log.info(
|
||||||
|
"Create succeeded: %s (template=%s destination=%s %s)",
|
||||||
|
message,
|
||||||
|
template,
|
||||||
|
new_workbook_name,
|
||||||
|
ctx,
|
||||||
|
)
|
||||||
|
return CreateResult(
|
||||||
|
ok=True,
|
||||||
|
message=message,
|
||||||
|
template=template,
|
||||||
|
destination=new_workbook_name,
|
||||||
|
backend=resolved_backend,
|
||||||
|
)
|
||||||
@@ -1,25 +1,25 @@
|
|||||||
dir,pattern,set_name,cells_to_clear,serial_cell,notes_cell
|
dir,pattern,set_name,cells_to_clear,serial_cell,notes_cell
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRCY1100T Blue","KRCY1100T Blue [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRCY1100T Blue,KRCY1100T Blue [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBK1300T Black","KRBK1300T Black [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRBK1300T Black,KRBK1300T Black [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBK1314T Black","KRBK1314T Black [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12:I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRBK1314T Black,KRBK1314T Black [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12:I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBR1200T Brown","KRBR1200T Brown [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRBR1200T Brown,KRBR1200T Brown [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBR1201T Brown","KRBR1201T Brown [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRBR1201T Brown,KRBR1201T Brown [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRYL1400T Yellow","KRYL1400T Yellow [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRYL1400T Yellow,KRYL1400T Yellow [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRYL1401T Yellow","KRYL1401T Yellow [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRYL1401T Yellow,KRYL1401T Yellow [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!E12:G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRBG1600T Beige","KRBG1600T Beige [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRBG1600T Beige,KRBG1600T Beige [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRPK1500T Pink","KRPK1500T Pink [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRPK1500T Pink,KRPK1500T Pink [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\Kimia Razi\Production\QC Datasheet\1403\KRHN1700T Honey","KRHN1700T Honey [SERIAL].xlsx","Kimia Razi","Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11","Batch!D3","Batch!D25"
|
Production\QC Datasheet\1403\KRHN1700T Honey,KRHN1700T Honey [SERIAL].xlsx,Kimia Razi,"Batch!F2:F3,Batch!G12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D7:D8,Milling!D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ108 Beige","ICJ_108 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2025\ICJ108 Beige,ICJ_108 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ610 Black","ICJ_610 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2026\ICJ610 Black,ICJ_610 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ308 Blue","ICJ_308 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2026\ICJ308 Blue,ICJ_308 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJEH680 Black","ICJ_EH680 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2026\ICJEH680 Black,ICJ_EH680 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJEH630 Black","ICJ_EH630 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2026\ICJEH630 Black,ICJ_EH630 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJEH600 Black","ICJ_EH600 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2025\ICJEH600 Black,ICJ_EH600 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ407 Brown","ICJ_407 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D24"
|
Quality control data sheet\2025\ICJ407 Brown,ICJ_407 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D24
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ408 Brown","ICJ_408 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D24"
|
Quality control data sheet\2025\ICJ408 Brown,ICJ_408 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D24
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ435 Beige","ICJ_435 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D24"
|
Quality control data sheet\2026\ICJ435 Beige,ICJ_435 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D24
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ107 Yellow","ICJ_107 yellow op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2025\ICJ107 Yellow,ICJ_107 yellow op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ703 Pink","ICJ_703 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2025\ICJ703 Pink,ICJ_703 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2024\ICJ309 Cyan","ICJ_309 cyan op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2024\ICJ309 Cyan,ICJ_309 cyan op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D19:J22,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2025\ICJ109 Golden Yellow","ICJ_109 op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2025\ICJ109 Golden Yellow,ICJ_109 op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!E12:F12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
"D:\OpenCloud\inco\Quality control data sheet\2026\ICJ152 Yellow","ICJ_152 yellow op. [SERIAL].xlsx","inco","Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11","Batch!D3","Batch!D25"
|
Quality control data sheet\2026\ICJ152 Yellow,ICJ_152 yellow op. [SERIAL].xlsx,inco,"Batch!F2:F3,Batch!I12,Batch!O9:Q10,Batch!O12:Q12,Batch!N10,Batch!N13,Batch!D20:J23,'KW'!C3:C4,Milling!G5:K8,Milling!G11:K11,Milling!D6:D8,Milling!D11,Mix!B3:D11",Batch!D3,Batch!D25
|
||||||
|
|||||||
|
BIN
src/xlsx_clean/fonts/Inter-Bold.ttf
Normal file
BIN
src/xlsx_clean/fonts/Inter-Bold.ttf
Normal file
Binary file not shown.
BIN
src/xlsx_clean/fonts/Inter-Regular.ttf
Normal file
BIN
src/xlsx_clean/fonts/Inter-Regular.ttf
Normal file
Binary file not shown.
139
src/xlsx_clean/gui_app.py
Normal file
139
src/xlsx_clean/gui_app.py
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
"""PyWebView desktop GUI for New QC Sheet."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from importlib.metadata import PackageNotFoundError, version as package_version
|
||||||
|
|
||||||
|
import webview
|
||||||
|
|
||||||
|
from xlsx_clean.core import create_datasheet, list_ink_colors, list_sets, load_config
|
||||||
|
from xlsx_clean.app_logging import get_logger
|
||||||
|
from xlsx_clean.paths import package_file
|
||||||
|
|
||||||
|
try:
|
||||||
|
_VERSION = package_version("xlsx-clean")
|
||||||
|
except PackageNotFoundError:
|
||||||
|
_VERSION = "dev"
|
||||||
|
|
||||||
|
|
||||||
|
class Api:
|
||||||
|
"""Python functions exposed to JavaScript via ``window.pywebview.api``."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.rows: list[dict] = []
|
||||||
|
self.addin_paths: list[str] = []
|
||||||
|
self.config: dict = {}
|
||||||
|
self._initial_data: dict | None = None
|
||||||
|
self._initialization_error: Exception | None = None
|
||||||
|
|
||||||
|
def initialize(self) -> None:
|
||||||
|
"""Load configuration before the local frontend is opened."""
|
||||||
|
if self._initial_data is not None or self._initialization_error is not None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
content, self.rows, self.config = load_config()
|
||||||
|
sets = list_sets(self.rows)
|
||||||
|
self.addin_paths = content[3:5] if len(content) >= 5 else []
|
||||||
|
self._initial_data = {
|
||||||
|
"sets": sets,
|
||||||
|
"inks": list_ink_colors(self.rows, sets[0]) if sets else [],
|
||||||
|
"labels": {
|
||||||
|
"set": content[0] if len(content) > 0 else "Select Set",
|
||||||
|
"ink": content[1] if len(content) > 1 else "Select Ink Color",
|
||||||
|
"serial": content[2] if len(content) > 2 else "Serial:",
|
||||||
|
},
|
||||||
|
"version": _VERSION,
|
||||||
|
}
|
||||||
|
except Exception as exc: # noqa: BLE001 - serialize bridge failures to JS
|
||||||
|
self._initialization_error = exc
|
||||||
|
|
||||||
|
def get_initial_data(self) -> dict:
|
||||||
|
"""Return configuration-derived values for the initial page render."""
|
||||||
|
self.initialize()
|
||||||
|
if self._initialization_error is not None:
|
||||||
|
raise self._initialization_error
|
||||||
|
assert self._initial_data is not None
|
||||||
|
return self._initial_data
|
||||||
|
|
||||||
|
def get_inks(self, selected_set: str) -> list[str]:
|
||||||
|
"""Return ink colors for a selected set."""
|
||||||
|
return list_ink_colors(self.rows, selected_set)
|
||||||
|
|
||||||
|
def create(
|
||||||
|
self, selected_set: str, selected_dir: str, batch_serial: str
|
||||||
|
) -> dict:
|
||||||
|
"""Create a datasheet and return a JSON-safe result.
|
||||||
|
|
||||||
|
Unexpected exceptions are serialized into the result contract so the
|
||||||
|
frontend always sees the same shape, regardless of platform-specific
|
||||||
|
bridge behavior.
|
||||||
|
"""
|
||||||
|
log = get_logger()
|
||||||
|
try:
|
||||||
|
result = create_datasheet(
|
||||||
|
selected_set=selected_set,
|
||||||
|
selected_dir=selected_dir,
|
||||||
|
batch_serial=batch_serial,
|
||||||
|
backend=None,
|
||||||
|
rows=self.rows,
|
||||||
|
addin_paths=self.addin_paths,
|
||||||
|
config=self.config,
|
||||||
|
)
|
||||||
|
except Exception as exc: # noqa: BLE001 - serialize bridge failures to JS
|
||||||
|
log.exception(
|
||||||
|
"Unexpected error in Api.create(set=%r, dir=%r, serial=%r)",
|
||||||
|
selected_set,
|
||||||
|
selected_dir,
|
||||||
|
batch_serial,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"skipped": False,
|
||||||
|
"message": f"Unexpected error: {exc}",
|
||||||
|
"template": None,
|
||||||
|
"destination": None,
|
||||||
|
"backend": None,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"ok": result.ok,
|
||||||
|
"skipped": result.skipped,
|
||||||
|
"message": result.message,
|
||||||
|
"template": str(result.template) if result.template is not None else None,
|
||||||
|
"destination": (
|
||||||
|
str(result.destination) if result.destination is not None else None
|
||||||
|
),
|
||||||
|
"backend": result.backend,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||||
|
"""Parse GUI dimensions without changing process-global arguments."""
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Start the New QC Sheet PyWebView interface."
|
||||||
|
)
|
||||||
|
parser.add_argument("--width", type=int, default=800, help="Window width")
|
||||||
|
parser.add_argument("--height", type=int, default=600, help="Window height")
|
||||||
|
return parser.parse_args(argv)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> None:
|
||||||
|
"""Open the native PyWebView window."""
|
||||||
|
args = parse_args(argv)
|
||||||
|
api = Api()
|
||||||
|
api.initialize()
|
||||||
|
index_html = package_file("ui/index.html")
|
||||||
|
webview.create_window(
|
||||||
|
title=f"New QC Sheet · v{_VERSION}",
|
||||||
|
url=index_html.as_uri(),
|
||||||
|
js_api=api,
|
||||||
|
width=args.width,
|
||||||
|
height=args.height,
|
||||||
|
min_size=(450, 400),
|
||||||
|
background_color="#0b0e14",
|
||||||
|
)
|
||||||
|
webview.start()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -19,52 +19,29 @@ def _package_dir() -> Path:
|
|||||||
|
|
||||||
PACKAGE_DIR = _package_dir()
|
PACKAGE_DIR = _package_dir()
|
||||||
|
|
||||||
# Historical Windows root used in file_data.csv
|
|
||||||
DEFAULT_OPENCLOUD_ROOT = Path(r"D:\OpenCloud")
|
|
||||||
OPENCLOUD_MARKER = "OpenCloud"
|
|
||||||
|
|
||||||
|
|
||||||
def package_file(name: str) -> Path:
|
def package_file(name: str) -> Path:
|
||||||
return PACKAGE_DIR / name
|
return PACKAGE_DIR / name
|
||||||
|
|
||||||
|
def default_config_path() -> Path:
|
||||||
def get_opencloud_root() -> Path:
|
"""Resolve the default location for the TOML configuration file."""
|
||||||
"""Workbook tree root from XLSX_CLEAN_ROOT, else D:\\OpenCloud on Windows."""
|
if getattr(sys, "frozen", False):
|
||||||
env = os.environ.get("XLSX_CLEAN_ROOT")
|
return Path(sys.executable).resolve().parent / "config.toml"
|
||||||
if env:
|
return Path.home() / ".xlsx-clean" / "config.toml"
|
||||||
return Path(env)
|
|
||||||
return DEFAULT_OPENCLOUD_ROOT
|
|
||||||
|
|
||||||
|
|
||||||
def remap_opencloud_path(path_str: str, root: Path | None = None) -> Path:
|
|
||||||
"""Map a CSV path under OpenCloud onto the configured root.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
D:\\OpenCloud\\inco\\... + root=/data -> /data/inco/...
|
|
||||||
Relative paths without OpenCloud are returned as-is (Path).
|
|
||||||
"""
|
|
||||||
if root is None:
|
|
||||||
root = get_opencloud_root()
|
|
||||||
|
|
||||||
normalized = path_str.replace("\\", "/")
|
|
||||||
# Case-insensitive marker search
|
|
||||||
lower = normalized.lower()
|
|
||||||
marker = f"{OPENCLOUD_MARKER.lower()}/"
|
|
||||||
idx = lower.find(marker)
|
|
||||||
if idx != -1:
|
|
||||||
rel = normalized[idx + len(marker) :]
|
|
||||||
return root / rel
|
|
||||||
|
|
||||||
# Already relative to root-style path without drive
|
|
||||||
return Path(path_str)
|
|
||||||
|
|
||||||
|
|
||||||
def default_backend() -> str:
|
def default_backend() -> str:
|
||||||
return "com" if sys.platform == "win32" else "ooxml"
|
return "com" if sys.platform == "win32" else "ooxml"
|
||||||
|
|
||||||
|
|
||||||
def resolve_backend(requested: str | None) -> str:
|
def resolve_backend(requested: str | None, config_backend: str | None = None) -> str:
|
||||||
backend = (requested or default_backend()).lower()
|
"""Resolve backend using explicitly requested, config file, or system default."""
|
||||||
|
if requested:
|
||||||
|
backend = requested.lower()
|
||||||
|
elif config_backend:
|
||||||
|
backend = config_backend.lower()
|
||||||
|
else:
|
||||||
|
backend = default_backend().lower()
|
||||||
|
|
||||||
if backend not in {"com", "ooxml"}:
|
if backend not in {"com", "ooxml"}:
|
||||||
raise ValueError(f"Unknown backend {backend!r}; use 'com' or 'ooxml'")
|
raise ValueError(f"Unknown backend {backend!r}; use 'com' or 'ooxml'")
|
||||||
if backend == "com" and sys.platform != "win32":
|
if backend == "com" and sys.platform != "win32":
|
||||||
|
|||||||
758
src/xlsx_clean/ui/index.html
Normal file
758
src/xlsx_clean/ui/index.html
Normal file
@@ -0,0 +1,758 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>New QC Sheet</title>
|
||||||
|
<script>
|
||||||
|
try {
|
||||||
|
if (localStorage.getItem("xlsx-clean-theme") === "light") {
|
||||||
|
document.documentElement.setAttribute("data-theme", "light");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
/* localStorage may be unavailable in some WebView embeds */
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<style>
|
||||||
|
@font-face {
|
||||||
|
font-family: "Inter";
|
||||||
|
src: url("../fonts/Inter-Regular.ttf") format("truetype");
|
||||||
|
font-weight: 400;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: "Inter";
|
||||||
|
src: url("../fonts/Inter-Bold.ttf") format("truetype");
|
||||||
|
font-weight: 700;
|
||||||
|
font-style: normal;
|
||||||
|
font-display: swap;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--primary: #e54d5e;
|
||||||
|
--primary-hover: #c93d4e;
|
||||||
|
--accent: #6366f1;
|
||||||
|
--accent-2: #8b5cf6;
|
||||||
|
--accent-3: #a855f7;
|
||||||
|
--success: #22c55e;
|
||||||
|
--warning: #f59e0b;
|
||||||
|
--error: #ef4444;
|
||||||
|
--bg: #0b0e14;
|
||||||
|
--bg-alt: #111520;
|
||||||
|
--surface: #161b22;
|
||||||
|
--surface-2: #1c2230;
|
||||||
|
--border: rgba(255, 255, 255, 0.08);
|
||||||
|
--border-strong: rgba(255, 255, 255, 0.14);
|
||||||
|
--grid-line: rgba(255, 255, 255, 0.06);
|
||||||
|
--grid-size: 32px;
|
||||||
|
--text: #e6e6ef;
|
||||||
|
--text-muted: #8b8b9e;
|
||||||
|
--text-dim: #5a5a6e;
|
||||||
|
--grad-brand: linear-gradient(135deg, var(--primary), var(--accent-3));
|
||||||
|
--grad-soft: linear-gradient(135deg, rgba(229, 77, 94, 0.12), rgba(168, 85, 247, 0.12));
|
||||||
|
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||||
|
--font-mono: ui-monospace, "JetBrains Mono", "Fira Code", "SF Mono", monospace;
|
||||||
|
--radius: 14px;
|
||||||
|
--radius-sm: 9px;
|
||||||
|
--ease: cubic-bezier(0.22, 1, 0.36, 1);
|
||||||
|
--status-ready: transparent;
|
||||||
|
--status-success: rgba(34, 197, 94, 0.12);
|
||||||
|
--status-skipped: rgba(245, 158, 11, 0.12);
|
||||||
|
--status-error: rgba(239, 68, 68, 0.12);
|
||||||
|
--label-bg: rgba(11, 14, 20, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme="light"] {
|
||||||
|
--bg: #f9f9fb;
|
||||||
|
--bg-alt: #f0f0f5;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--surface-2: #f5f5fa;
|
||||||
|
--border: rgba(0, 0, 0, 0.08);
|
||||||
|
--border-strong: rgba(0, 0, 0, 0.14);
|
||||||
|
--grid-line: rgba(0, 0, 0, 0.07);
|
||||||
|
--text: #1a1a2e;
|
||||||
|
--text-muted: #71717a;
|
||||||
|
--text-dim: #9a9aa5;
|
||||||
|
--grad-soft: linear-gradient(135deg, rgba(229, 77, 94, 0.08), rgba(168, 85, 247, 0.08));
|
||||||
|
--status-success: rgba(34, 197, 94, 0.1);
|
||||||
|
--status-skipped: rgba(245, 158, 11, 0.12);
|
||||||
|
--status-error: rgba(239, 68, 68, 0.1);
|
||||||
|
--label-bg: rgba(249, 249, 251, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
min-height: 100vh;
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.5;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
body::before {
|
||||||
|
content: "";
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: -1;
|
||||||
|
pointer-events: none;
|
||||||
|
background-image:
|
||||||
|
linear-gradient(to right, var(--grid-line) 1px, transparent 1px),
|
||||||
|
linear-gradient(to bottom, var(--grid-line) 1px, transparent 1px);
|
||||||
|
background-size: var(--grid-size) var(--grid-size);
|
||||||
|
}
|
||||||
|
|
||||||
|
.page {
|
||||||
|
display: flex;
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: min(100%, 36rem);
|
||||||
|
margin: auto;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heading-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-toggle {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-width: 52px;
|
||||||
|
height: 28px;
|
||||||
|
margin-top: 2px;
|
||||||
|
padding: 0 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--surface-2);
|
||||||
|
color: var(--text);
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-toggle:hover {
|
||||||
|
background: var(--bg-alt);
|
||||||
|
border-color: var(--border-strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-toggle:focus-visible {
|
||||||
|
outline: 2px solid var(--accent-3);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.eyebrow {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
color: var(--primary);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 1.875rem;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.15;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.subtitle {
|
||||||
|
margin: 8px 0 22px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fields { display: grid; gap: 18px; }
|
||||||
|
|
||||||
|
.field {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-label {
|
||||||
|
z-index: 1;
|
||||||
|
margin-left: 4px;
|
||||||
|
padding: 0 4px;
|
||||||
|
background: var(--label-bg);
|
||||||
|
color: var(--primary);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.2;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
select, input {
|
||||||
|
width: 100%;
|
||||||
|
align-self: stretch;
|
||||||
|
min-height: 54px;
|
||||||
|
padding: 16px 12px;
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
outline: none;
|
||||||
|
background: var(--surface-2);
|
||||||
|
color: var(--text);
|
||||||
|
font: inherit;
|
||||||
|
transition: border-color 150ms var(--ease), box-shadow 150ms var(--ease);
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox-input {
|
||||||
|
padding-right: 36px;
|
||||||
|
cursor: text;
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox { position: relative; }
|
||||||
|
|
||||||
|
.combobox > select {
|
||||||
|
position: absolute;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
padding: 0;
|
||||||
|
margin: -1px;
|
||||||
|
overflow: hidden;
|
||||||
|
clip: rect(0 0 0 0);
|
||||||
|
white-space: nowrap;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox-caret {
|
||||||
|
position: absolute;
|
||||||
|
right: 12px;
|
||||||
|
bottom: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 54px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
pointer-events: none;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox-panel {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 4px);
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
z-index: 5;
|
||||||
|
max-height: 220px;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 4px 0;
|
||||||
|
background: var(--surface-2);
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: 0 12px 32px rgb(0 0 0 / 35%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox-panel[hidden] { display: none; }
|
||||||
|
|
||||||
|
.combobox-option {
|
||||||
|
padding: 8px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text);
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox-option[aria-selected="true"],
|
||||||
|
.combobox-option:hover {
|
||||||
|
background: var(--grad-soft);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.combobox-option[hidden] { display: none; }
|
||||||
|
|
||||||
|
.combobox-empty {
|
||||||
|
padding: 8px 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
select:focus, input:focus,
|
||||||
|
.combobox-input:focus {
|
||||||
|
border-color: var(--accent);
|
||||||
|
box-shadow: 0 0 0 3px rgb(99 102 241 / 28%);
|
||||||
|
}
|
||||||
|
|
||||||
|
select:disabled, input:disabled,
|
||||||
|
.combobox-input:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
background: var(--bg-alt);
|
||||||
|
color: var(--text-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.divider {
|
||||||
|
height: 1px;
|
||||||
|
margin: 22px 0;
|
||||||
|
background: var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
#create-button {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 44px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
background: var(--grad-brand);
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
box-shadow: 0 8px 22px -10px var(--primary);
|
||||||
|
transition: transform 150ms var(--ease), box-shadow 150ms var(--ease), filter 150ms var(--ease);
|
||||||
|
}
|
||||||
|
|
||||||
|
#create-button:hover:not(:disabled) {
|
||||||
|
filter: brightness(1.06);
|
||||||
|
box-shadow: 0 10px 26px -8px var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
#create-button:focus-visible {
|
||||||
|
outline: 2px solid var(--accent-3);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#create-button:disabled { cursor: not-allowed; opacity: 0.65; }
|
||||||
|
|
||||||
|
.status {
|
||||||
|
min-height: 48px;
|
||||||
|
margin-top: 16px;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1.45;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status::before {
|
||||||
|
content: "$ ";
|
||||||
|
color: var(--primary);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-ready { background: var(--status-ready); }
|
||||||
|
.status-success { background: var(--status-success); color: var(--success); }
|
||||||
|
.status-skipped { background: var(--status-skipped); color: var(--warning); }
|
||||||
|
.status-error { background: var(--status-error); color: var(--error); }
|
||||||
|
|
||||||
|
.version {
|
||||||
|
margin-top: 16px;
|
||||||
|
color: var(--text-dim);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.page { padding: 14px; }
|
||||||
|
h1 { font-size: 1.5rem; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="page">
|
||||||
|
<section class="panel" aria-labelledby="heading">
|
||||||
|
<div class="heading-row">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">QC datasheet</p>
|
||||||
|
<h1 id="heading">New QC Sheet</h1>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
id="theme-toggle"
|
||||||
|
class="theme-toggle"
|
||||||
|
type="button"
|
||||||
|
aria-label="Switch to light theme"
|
||||||
|
title="Switch theme">
|
||||||
|
Aa
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="subtitle">Create a new QC datasheet from the latest matching workbook.</p>
|
||||||
|
|
||||||
|
<div class="fields">
|
||||||
|
<label class="field combobox" for="set-dropdown-input">
|
||||||
|
<span id="set-label" class="field-label">Select Set</span>
|
||||||
|
<input
|
||||||
|
id="set-dropdown-input"
|
||||||
|
class="combobox-input"
|
||||||
|
type="text"
|
||||||
|
autocomplete="off"
|
||||||
|
spellcheck="false"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded="false"
|
||||||
|
aria-controls="set-dropdown-panel"
|
||||||
|
aria-autocomplete="list"
|
||||||
|
aria-labelledby="set-label"
|
||||||
|
placeholder=" ">
|
||||||
|
<select id="set-dropdown" aria-labelledby="set-label" tabindex="-1"></select>
|
||||||
|
<span class="combobox-caret" aria-hidden="true">▾</span>
|
||||||
|
<div id="set-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="set-label" hidden></div>
|
||||||
|
</label>
|
||||||
|
<label class="field combobox" for="ink-dropdown-input">
|
||||||
|
<span id="ink-label" class="field-label">Select Ink Color</span>
|
||||||
|
<input
|
||||||
|
id="ink-dropdown-input"
|
||||||
|
class="combobox-input"
|
||||||
|
type="text"
|
||||||
|
autocomplete="off"
|
||||||
|
spellcheck="false"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded="false"
|
||||||
|
aria-controls="ink-dropdown-panel"
|
||||||
|
aria-autocomplete="list"
|
||||||
|
aria-labelledby="ink-label"
|
||||||
|
placeholder=" ">
|
||||||
|
<select id="ink-dropdown" aria-labelledby="ink-label" tabindex="-1"></select>
|
||||||
|
<span class="combobox-caret" aria-hidden="true">▾</span>
|
||||||
|
<div id="ink-dropdown-panel" class="combobox-panel" role="listbox" aria-labelledby="ink-label" hidden></div>
|
||||||
|
</label>
|
||||||
|
<label class="field" for="serial-input">
|
||||||
|
<span id="serial-label" class="field-label">Serial:</span>
|
||||||
|
<input id="serial-input" type="text" placeholder="e.g. 1234/A" aria-labelledby="serial-label">
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="divider"></div>
|
||||||
|
<button id="create-button" type="button">Create datasheet</button>
|
||||||
|
<div id="status" class="status status-ready" role="status">Loading configuration...</div>
|
||||||
|
<p id="version" class="version"></p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const setDropdown = document.getElementById("set-dropdown");
|
||||||
|
const inkDropdown = document.getElementById("ink-dropdown");
|
||||||
|
const setInput = document.getElementById("set-dropdown-input");
|
||||||
|
const inkInput = document.getElementById("ink-dropdown-input");
|
||||||
|
const setPanel = document.getElementById("set-dropdown-panel");
|
||||||
|
const inkPanel = document.getElementById("ink-dropdown-panel");
|
||||||
|
const serialInput = document.getElementById("serial-input");
|
||||||
|
const createBtn = document.getElementById("create-button");
|
||||||
|
const status = document.getElementById("status");
|
||||||
|
const themeToggle = document.getElementById("theme-toggle");
|
||||||
|
|
||||||
|
function isLightTheme() {
|
||||||
|
return document.documentElement.getAttribute("data-theme") === "light";
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncThemeToggle() {
|
||||||
|
const light = isLightTheme();
|
||||||
|
themeToggle.setAttribute(
|
||||||
|
"aria-label",
|
||||||
|
light ? "Switch to dark theme" : "Switch to light theme"
|
||||||
|
);
|
||||||
|
themeToggle.textContent = light ? "Dark" : "Light";
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyTheme(theme) {
|
||||||
|
if (theme === "light") {
|
||||||
|
document.documentElement.setAttribute("data-theme", "light");
|
||||||
|
} else {
|
||||||
|
document.documentElement.removeAttribute("data-theme");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
localStorage.setItem("xlsx-clean-theme", theme);
|
||||||
|
} catch (error) {
|
||||||
|
/* ignore quota / privacy mode */
|
||||||
|
}
|
||||||
|
syncThemeToggle();
|
||||||
|
}
|
||||||
|
|
||||||
|
themeToggle.addEventListener("click", () => {
|
||||||
|
applyTheme(isLightTheme() ? "dark" : "light");
|
||||||
|
});
|
||||||
|
syncThemeToggle();
|
||||||
|
|
||||||
|
// Builds a searchable combobox. The underlying <select> stays as the
|
||||||
|
// semantic source of truth; the visible widget is a text <input> plus a
|
||||||
|
// listbox panel that filters options as the user types.
|
||||||
|
function createCombobox(selectEl, inputEl, panelEl) {
|
||||||
|
let openState = false;
|
||||||
|
let inputDirty = false;
|
||||||
|
|
||||||
|
const visibleOptions = () =>
|
||||||
|
Array.from(panelEl.querySelectorAll(".combobox-option")).filter(
|
||||||
|
(node) => !node.hidden
|
||||||
|
);
|
||||||
|
|
||||||
|
const open = () => {
|
||||||
|
if (openState || inputEl.disabled) return;
|
||||||
|
openState = true;
|
||||||
|
panelEl.hidden = false;
|
||||||
|
inputEl.setAttribute("aria-expanded", "true");
|
||||||
|
filter();
|
||||||
|
};
|
||||||
|
|
||||||
|
const close = () => {
|
||||||
|
if (!openState) return;
|
||||||
|
openState = false;
|
||||||
|
panelEl.hidden = true;
|
||||||
|
inputEl.setAttribute("aria-expanded", "false");
|
||||||
|
inputEl.removeAttribute("aria-activedescendant");
|
||||||
|
for (const node of panelEl.querySelectorAll(".combobox-option")) {
|
||||||
|
node.setAttribute("aria-selected", "false");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setActive = (idx) => {
|
||||||
|
const options = visibleOptions();
|
||||||
|
for (const node of panelEl.querySelectorAll(".combobox-option")) {
|
||||||
|
node.setAttribute("aria-selected", "false");
|
||||||
|
}
|
||||||
|
if (idx < 0 || idx >= options.length) {
|
||||||
|
inputEl.removeAttribute("aria-activedescendant");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const node = options[idx];
|
||||||
|
node.setAttribute("aria-selected", "true");
|
||||||
|
node.scrollIntoView({ block: "nearest" });
|
||||||
|
inputEl.setAttribute("aria-activedescendant", node.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const filter = () => {
|
||||||
|
const needle = inputDirty ? inputEl.value.trim().toLowerCase() : "";
|
||||||
|
let firstVisible = -1;
|
||||||
|
let count = 0;
|
||||||
|
for (const node of panelEl.querySelectorAll(".combobox-option")) {
|
||||||
|
const value = (node.dataset.value || "").toLowerCase();
|
||||||
|
const match = !needle || value.includes(needle);
|
||||||
|
node.hidden = !match;
|
||||||
|
if (match) {
|
||||||
|
if (firstVisible === -1) firstVisible = count;
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const empty = panelEl.querySelector(".combobox-empty");
|
||||||
|
if (empty) empty.hidden = count > 0;
|
||||||
|
setActive(firstVisible === -1 ? -1 : 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectValue = (value) => {
|
||||||
|
if (selectEl.value !== value) {
|
||||||
|
selectEl.value = value;
|
||||||
|
selectEl.dispatchEvent(new Event("change", { bubbles: true }));
|
||||||
|
}
|
||||||
|
inputEl.value = value;
|
||||||
|
inputDirty = false;
|
||||||
|
close();
|
||||||
|
inputEl.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncDisabled = () => {
|
||||||
|
inputEl.disabled = selectEl.disabled;
|
||||||
|
if (selectEl.disabled) close();
|
||||||
|
};
|
||||||
|
|
||||||
|
const rebuild = () => {
|
||||||
|
panelEl.replaceChildren();
|
||||||
|
const values = Array.from(selectEl.options).map((o) => o.value);
|
||||||
|
for (const value of values) {
|
||||||
|
const node = document.createElement("div");
|
||||||
|
node.className = "combobox-option";
|
||||||
|
node.id = `${selectEl.id}-opt-${CSS.escape(value)}`;
|
||||||
|
node.setAttribute("role", "option");
|
||||||
|
node.setAttribute("aria-selected", "false");
|
||||||
|
node.dataset.value = value;
|
||||||
|
node.textContent = value;
|
||||||
|
node.addEventListener("mousedown", (event) => {
|
||||||
|
// mousedown (not click) so we beat the input's blur handler.
|
||||||
|
event.preventDefault();
|
||||||
|
selectValue(value);
|
||||||
|
});
|
||||||
|
panelEl.append(node);
|
||||||
|
}
|
||||||
|
const empty = document.createElement("div");
|
||||||
|
empty.className = "combobox-empty";
|
||||||
|
empty.textContent = "No matches";
|
||||||
|
empty.hidden = true;
|
||||||
|
panelEl.append(empty);
|
||||||
|
inputEl.value = selectEl.value || "";
|
||||||
|
inputDirty = false;
|
||||||
|
syncDisabled();
|
||||||
|
};
|
||||||
|
|
||||||
|
inputEl.addEventListener("focus", open);
|
||||||
|
inputEl.addEventListener("mousedown", () => {
|
||||||
|
open();
|
||||||
|
});
|
||||||
|
inputEl.addEventListener("input", () => {
|
||||||
|
inputDirty = true;
|
||||||
|
if (!openState) open();
|
||||||
|
filter();
|
||||||
|
});
|
||||||
|
inputEl.addEventListener("blur", () => {
|
||||||
|
// Defer close so a mousedown on a panel option can fire first.
|
||||||
|
setTimeout(() => {
|
||||||
|
if (inputEl.value !== selectEl.value) {
|
||||||
|
inputEl.value = selectEl.value || "";
|
||||||
|
inputDirty = false;
|
||||||
|
}
|
||||||
|
close();
|
||||||
|
}, 0);
|
||||||
|
});
|
||||||
|
inputEl.addEventListener("keydown", (event) => {
|
||||||
|
const options = visibleOptions();
|
||||||
|
if (event.key === "ArrowDown") {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!openState) open();
|
||||||
|
const idx = options.findIndex(
|
||||||
|
(n) => n.getAttribute("aria-selected") === "true"
|
||||||
|
);
|
||||||
|
setActive(Math.min(idx + 1, options.length - 1));
|
||||||
|
} else if (event.key === "ArrowUp") {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!openState) open();
|
||||||
|
const idx = options.findIndex(
|
||||||
|
(n) => n.getAttribute("aria-selected") === "true"
|
||||||
|
);
|
||||||
|
setActive(Math.max(idx - 1, 0));
|
||||||
|
} else if (event.key === "Home") {
|
||||||
|
if (openState) {
|
||||||
|
event.preventDefault();
|
||||||
|
setActive(0);
|
||||||
|
}
|
||||||
|
} else if (event.key === "End") {
|
||||||
|
if (openState) {
|
||||||
|
event.preventDefault();
|
||||||
|
setActive(options.length - 1);
|
||||||
|
}
|
||||||
|
} else if (event.key === "Enter") {
|
||||||
|
if (openState) {
|
||||||
|
event.preventDefault();
|
||||||
|
const node = panelEl.querySelector(
|
||||||
|
'.combobox-option[aria-selected="true"]'
|
||||||
|
);
|
||||||
|
if (node) selectValue(node.dataset.value);
|
||||||
|
}
|
||||||
|
} else if (event.key === "Escape") {
|
||||||
|
if (openState) {
|
||||||
|
event.preventDefault();
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Click outside closes the panel.
|
||||||
|
document.addEventListener("mousedown", (event) => {
|
||||||
|
if (!openState) return;
|
||||||
|
if (!inputEl.parentElement.contains(event.target)) close();
|
||||||
|
});
|
||||||
|
|
||||||
|
return { rebuild, syncDisabled };
|
||||||
|
}
|
||||||
|
|
||||||
|
const setCombobox = createCombobox(setDropdown, setInput, setPanel);
|
||||||
|
const inkCombobox = createCombobox(inkDropdown, inkInput, inkPanel);
|
||||||
|
|
||||||
|
function populateDropdown(dropdown, combobox, values) {
|
||||||
|
dropdown.replaceChildren();
|
||||||
|
for (const value of values) {
|
||||||
|
const option = document.createElement("option");
|
||||||
|
option.value = value;
|
||||||
|
option.textContent = value;
|
||||||
|
dropdown.append(option);
|
||||||
|
}
|
||||||
|
dropdown.disabled = values.length === 0;
|
||||||
|
combobox.rebuild();
|
||||||
|
}
|
||||||
|
|
||||||
|
function populateDropdowns(sets, inks) {
|
||||||
|
populateDropdown(setDropdown, setCombobox, sets);
|
||||||
|
populateDropdown(inkDropdown, inkCombobox, inks);
|
||||||
|
}
|
||||||
|
|
||||||
|
function populateInkDropdown(inks) {
|
||||||
|
populateDropdown(inkDropdown, inkCombobox, inks);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLabels(labels) {
|
||||||
|
document.getElementById("set-label").textContent = labels.set;
|
||||||
|
document.getElementById("ink-label").textContent = labels.ink;
|
||||||
|
document.getElementById("serial-label").textContent = labels.serial;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setVersion(version) {
|
||||||
|
document.getElementById("version").textContent = `v${version}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showStatus(result) {
|
||||||
|
const details = [result.message];
|
||||||
|
if (result.template) details.push(`Template: ${result.template}`);
|
||||||
|
if (result.destination) details.push(`Output: ${result.destination}`);
|
||||||
|
if (result.backend) details.push(`Backend: ${result.backend}`);
|
||||||
|
status.textContent = details.join("\n");
|
||||||
|
status.className = "status";
|
||||||
|
if (result.skipped) {
|
||||||
|
status.classList.add("status-skipped");
|
||||||
|
} else if (result.ok) {
|
||||||
|
status.classList.add("status-success");
|
||||||
|
} else {
|
||||||
|
status.classList.add("status-error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function initialize() {
|
||||||
|
try {
|
||||||
|
const data = await window.pywebview.api.get_initial_data();
|
||||||
|
populateDropdowns(data.sets, data.inks);
|
||||||
|
setLabels(data.labels);
|
||||||
|
setVersion(data.version);
|
||||||
|
showStatus({ message: "Ready.", ok: true, skipped: false });
|
||||||
|
} catch (error) {
|
||||||
|
showStatus({ message: `Failed to load configuration: ${error}`, ok: false, skipped: false });
|
||||||
|
createBtn.disabled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setDropdown.addEventListener("change", async () => {
|
||||||
|
try {
|
||||||
|
const inks = await window.pywebview.api.get_inks(setDropdown.value);
|
||||||
|
populateInkDropdown(inks);
|
||||||
|
} catch (error) {
|
||||||
|
showStatus({ message: `Failed to load ink colors: ${error}`, ok: false, skipped: false });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
createBtn.addEventListener("click", async () => {
|
||||||
|
createBtn.disabled = true;
|
||||||
|
try {
|
||||||
|
const result = await window.pywebview.api.create(
|
||||||
|
setDropdown.value, inkDropdown.value, serialInput.value
|
||||||
|
);
|
||||||
|
showStatus(result);
|
||||||
|
} catch (error) {
|
||||||
|
showStatus({ message: `Failed to create datasheet: ${error}`, ok: false, skipped: false });
|
||||||
|
} finally {
|
||||||
|
createBtn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener("pywebviewready", initialize);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,335 +0,0 @@
|
|||||||
"""NiceGUI web UI for selecting set / ink / serial and creating a datasheet."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from importlib.metadata import PackageNotFoundError, version as package_version
|
|
||||||
|
|
||||||
from nicegui import ui
|
|
||||||
|
|
||||||
from xlsx_clean.clean_cells import (
|
|
||||||
create_datasheet,
|
|
||||||
list_ink_colors,
|
|
||||||
list_sets,
|
|
||||||
load_config,
|
|
||||||
)
|
|
||||||
from xlsx_clean.paths import default_backend
|
|
||||||
|
|
||||||
APP_DISPLAY_NAME = "New QC Sheet"
|
|
||||||
_PACKAGE_NAME = "xlsx-clean"
|
|
||||||
|
|
||||||
|
|
||||||
def _app_version() -> str:
|
|
||||||
"""Installed package version from metadata (pyproject.toml)."""
|
|
||||||
try:
|
|
||||||
return package_version(_PACKAGE_NAME)
|
|
||||||
except PackageNotFoundError:
|
|
||||||
return "0.1.0"
|
|
||||||
|
|
||||||
|
|
||||||
def _app_title(version: str | None = None) -> str:
|
|
||||||
ver = version if version is not None else _app_version()
|
|
||||||
return f"{APP_DISPLAY_NAME} · {ver}"
|
|
||||||
|
|
||||||
|
|
||||||
# Last native-check diagnostic (Python version + import/typelib error).
|
|
||||||
_NATIVE_DIAG: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def _linux_native_hint(detail: str | None = None) -> str:
|
|
||||||
lines = [
|
|
||||||
"Linux native window needs system GTK/WebKit packages "
|
|
||||||
"(uv cannot install them), e.g.:",
|
|
||||||
" sudo apt install python3-gi gir1.2-gtk-3.0 gir1.2-webkit2-4.1",
|
|
||||||
"Recommended one-shot setup:",
|
|
||||||
" ./desktop/setup_linux.sh",
|
|
||||||
"Recreate the venv with the OS Python (not a uv-managed build):",
|
|
||||||
" rm -rf .venv && uv venv --python /usr/bin/python3 "
|
|
||||||
"--no-managed-python --system-site-packages && uv sync",
|
|
||||||
]
|
|
||||||
if detail:
|
|
||||||
lines.append(f"Detail: {detail}")
|
|
||||||
detail_l = detail.lower()
|
|
||||||
if "_gi" in detail_l or "partially initialized" in detail_l:
|
|
||||||
lines.append(
|
|
||||||
"This usually means the venv Python does not match apt "
|
|
||||||
"python3-gi (uv-managed CPython on PATH, e.g. "
|
|
||||||
"~/.local/share/uv/python/...). Re-run ./desktop/setup_linux.sh "
|
|
||||||
"so .venv uses /usr/bin/python3 (not PATH python3)."
|
|
||||||
)
|
|
||||||
lines.append(
|
|
||||||
"Falling back to the default browser. "
|
|
||||||
"Use --no-browser for server-only."
|
|
||||||
)
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def _linux_has_display() -> bool:
|
|
||||||
return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
|
|
||||||
|
|
||||||
|
|
||||||
def _linux_system_dist_packages() -> list[str]:
|
|
||||||
"""Debian/Ubuntu (and similar) PyGObject install locations."""
|
|
||||||
major, minor = sys.version_info[:2]
|
|
||||||
return [
|
|
||||||
"/usr/lib/python3/dist-packages",
|
|
||||||
f"/usr/lib/python{major}.{minor}/dist-packages",
|
|
||||||
f"/usr/local/lib/python{major}.{minor}/dist-packages",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _ensure_linux_system_gi_path() -> None:
|
|
||||||
"""Make system python3-gi visible inside an isolated uv/venv.
|
|
||||||
|
|
||||||
apt installs PyGObject into dist-packages; plain `uv sync` venvs do not
|
|
||||||
include system site-packages, so `import gi` fails and NiceGUI falls back
|
|
||||||
to the browser. Exposing dist-packages is enough when typelibs are installed.
|
|
||||||
"""
|
|
||||||
if not sys.platform.startswith("linux"):
|
|
||||||
return
|
|
||||||
for path in _linux_system_dist_packages():
|
|
||||||
if os.path.isdir(path) and path not in sys.path:
|
|
||||||
sys.path.append(path)
|
|
||||||
|
|
||||||
|
|
||||||
def _gi_gtk_webkit_probe() -> str | None:
|
|
||||||
"""Return None if pywebview's GTK backend is usable, else an error detail."""
|
|
||||||
try:
|
|
||||||
import gi
|
|
||||||
except ImportError as exc:
|
|
||||||
return f"import gi failed ({exc})"
|
|
||||||
try:
|
|
||||||
gi.require_version("Gtk", "3.0")
|
|
||||||
gi.require_version("Gdk", "3.0")
|
|
||||||
except (ValueError, AttributeError) as exc:
|
|
||||||
return f"Gtk/Gdk typelib unavailable ({exc})"
|
|
||||||
try:
|
|
||||||
gi.require_version("WebKit2", "4.1")
|
|
||||||
except ValueError:
|
|
||||||
try:
|
|
||||||
gi.require_version("WebKit2", "4.0")
|
|
||||||
except ValueError as exc:
|
|
||||||
return f"WebKit2 typelib unavailable ({exc})"
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _linux_webview_libs_available() -> bool:
|
|
||||||
"""True if GTK (gi) or Qt (qtpy) Python bindings are usable for pywebview."""
|
|
||||||
global _NATIVE_DIAG
|
|
||||||
_ensure_linux_system_gi_path()
|
|
||||||
gi_err = _gi_gtk_webkit_probe()
|
|
||||||
if gi_err is None:
|
|
||||||
_NATIVE_DIAG = None
|
|
||||||
return True
|
|
||||||
try:
|
|
||||||
import qtpy # noqa: F401
|
|
||||||
|
|
||||||
_NATIVE_DIAG = None
|
|
||||||
return True
|
|
||||||
except ImportError as qt_exc:
|
|
||||||
_NATIVE_DIAG = (
|
|
||||||
f"Python {sys.version.split()[0]}; {gi_err}; "
|
|
||||||
f"qtpy also unavailable ({qt_exc})"
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _native_mode_available() -> bool:
|
|
||||||
"""Whether pywebview is likely able to open a native window."""
|
|
||||||
global _NATIVE_DIAG
|
|
||||||
if sys.platform == "win32" or sys.platform == "darwin":
|
|
||||||
_NATIVE_DIAG = None
|
|
||||||
return True
|
|
||||||
if sys.platform.startswith("linux"):
|
|
||||||
if not _linux_has_display():
|
|
||||||
_NATIVE_DIAG = (
|
|
||||||
f"Python {sys.version.split()[0]}; "
|
|
||||||
"no DISPLAY/WAYLAND_DISPLAY (headless?)"
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
return _linux_webview_libs_available()
|
|
||||||
return _linux_webview_libs_available()
|
|
||||||
|
|
||||||
|
|
||||||
def _build_page() -> None:
|
|
||||||
content, path_df = load_config()
|
|
||||||
q1, q2, q3 = content[0], content[1], content[2]
|
|
||||||
sets = list_sets(path_df)
|
|
||||||
initial_set = sets[0] if sets else None
|
|
||||||
initial_inks = list_ink_colors(path_df, initial_set) if initial_set else []
|
|
||||||
app_version = _app_version()
|
|
||||||
|
|
||||||
ui.page_title(_app_title(app_version))
|
|
||||||
ui.colors(primary="#0f766e", secondary="#115e59", accent="#14b8a6")
|
|
||||||
|
|
||||||
with ui.column().classes("w-full max-w-xl mx-auto p-6 gap-4"):
|
|
||||||
ui.label(APP_DISPLAY_NAME).classes("text-3xl font-bold text-teal-800")
|
|
||||||
ui.label(
|
|
||||||
"Create a new QC datasheet from the latest matching workbook."
|
|
||||||
).classes("text-gray-600")
|
|
||||||
|
|
||||||
ink_ref: dict = {}
|
|
||||||
|
|
||||||
def on_set_change(e) -> None:
|
|
||||||
selected = e.value
|
|
||||||
inks = list_ink_colors(path_df, selected) if selected else []
|
|
||||||
ink = ink_ref["select"]
|
|
||||||
ink.options = inks
|
|
||||||
ink.value = inks[0] if inks else None
|
|
||||||
ink.update()
|
|
||||||
|
|
||||||
set_select = ui.select(
|
|
||||||
options=sets,
|
|
||||||
value=initial_set,
|
|
||||||
label=q1,
|
|
||||||
with_input=True,
|
|
||||||
on_change=on_set_change,
|
|
||||||
).classes("w-full")
|
|
||||||
|
|
||||||
ink_select = ui.select(
|
|
||||||
options=initial_inks,
|
|
||||||
value=initial_inks[0] if initial_inks else None,
|
|
||||||
label=q2,
|
|
||||||
with_input=True,
|
|
||||||
).classes("w-full")
|
|
||||||
ink_ref["select"] = ink_select
|
|
||||||
|
|
||||||
serial_input = ui.input(label=q3, placeholder="e.g. 1234/A").classes("w-full")
|
|
||||||
|
|
||||||
backend_select = ui.select(
|
|
||||||
options=["ooxml", "com"],
|
|
||||||
value=default_backend(),
|
|
||||||
label="Backend",
|
|
||||||
).classes("w-full")
|
|
||||||
if sys.platform != "win32":
|
|
||||||
ui.label(
|
|
||||||
"COM backend requires Windows with Microsoft Excel; use ooxml here."
|
|
||||||
).classes("text-sm text-amber-700")
|
|
||||||
|
|
||||||
status = ui.markdown("Ready.").classes("w-full p-3 rounded bg-gray-50")
|
|
||||||
|
|
||||||
def on_create() -> None:
|
|
||||||
result = create_datasheet(
|
|
||||||
selected_set=set_select.value or "",
|
|
||||||
selected_dir=ink_select.value or "",
|
|
||||||
batch_serial=serial_input.value or "",
|
|
||||||
backend=backend_select.value,
|
|
||||||
path_df=path_df,
|
|
||||||
addin_paths=content[3:5] if len(content) >= 5 else [],
|
|
||||||
)
|
|
||||||
lines = [result.message]
|
|
||||||
if result.template is not None:
|
|
||||||
lines.append(f"**Template:** `{result.template.name}`")
|
|
||||||
if result.destination is not None:
|
|
||||||
lines.append(f"**Output:** `{result.destination}`")
|
|
||||||
if result.backend is not None:
|
|
||||||
lines.append(f"**Backend:** `{result.backend}`")
|
|
||||||
status.set_content("\n\n".join(lines))
|
|
||||||
if result.ok and not result.skipped:
|
|
||||||
status.classes(replace="w-full p-3 rounded bg-teal-50")
|
|
||||||
elif result.skipped:
|
|
||||||
status.classes(replace="w-full p-3 rounded bg-amber-50")
|
|
||||||
else:
|
|
||||||
status.classes(replace="w-full p-3 rounded bg-red-50")
|
|
||||||
|
|
||||||
ui.button("Create datasheet", on_click=on_create).props("unelevated").classes(
|
|
||||||
"w-full"
|
|
||||||
)
|
|
||||||
ui.label(f"v{app_version}").classes(
|
|
||||||
"w-full text-right text-xs text-gray-400"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description=f"Start the {APP_DISPLAY_NAME} NiceGUI interface."
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--host",
|
|
||||||
default="127.0.0.1",
|
|
||||||
help="Bind address (default: 127.0.0.1).",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--port",
|
|
||||||
type=int,
|
|
||||||
default=8080,
|
|
||||||
help="Port (default: 8080; native mode may pick a free port).",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--reload",
|
|
||||||
action="store_true",
|
|
||||||
help="Enable NiceGUI auto-reload (dev only; ignored in native mode).",
|
|
||||||
)
|
|
||||||
mode = parser.add_mutually_exclusive_group()
|
|
||||||
mode.add_argument(
|
|
||||||
"--browser",
|
|
||||||
action="store_true",
|
|
||||||
help="Open in the default web browser instead of a native app window.",
|
|
||||||
)
|
|
||||||
mode.add_argument(
|
|
||||||
"--no-browser",
|
|
||||||
action="store_true",
|
|
||||||
help="Run the server only; do not open a window or browser.",
|
|
||||||
)
|
|
||||||
return parser.parse_args(argv)
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> None:
|
|
||||||
args = parse_args(argv)
|
|
||||||
_build_page()
|
|
||||||
|
|
||||||
frozen = getattr(sys, "frozen", False)
|
|
||||||
use_native = not args.browser and not args.no_browser
|
|
||||||
if use_native and not _native_mode_available():
|
|
||||||
if os.environ.get("XLSX_CLEAN_NATIVE_FALLBACK") != "1":
|
|
||||||
print(_linux_native_hint(_NATIVE_DIAG), file=sys.stderr)
|
|
||||||
os.environ["XLSX_CLEAN_NATIVE_FALLBACK"] = "1"
|
|
||||||
use_native = False
|
|
||||||
args.browser = True
|
|
||||||
|
|
||||||
run_kwargs: dict = {
|
|
||||||
"host": args.host,
|
|
||||||
"port": args.port,
|
|
||||||
"reload": False if frozen or use_native else args.reload,
|
|
||||||
"title": _app_title(),
|
|
||||||
}
|
|
||||||
if args.no_browser:
|
|
||||||
run_kwargs["show"] = False
|
|
||||||
run_kwargs["native"] = False
|
|
||||||
elif use_native:
|
|
||||||
# Single dedicated window (pywebview), not the default browser with tabs.
|
|
||||||
run_kwargs["native"] = True
|
|
||||||
run_kwargs["window_size"] = (900, 700)
|
|
||||||
run_kwargs["show"] = False
|
|
||||||
else:
|
|
||||||
run_kwargs["show"] = True
|
|
||||||
run_kwargs["native"] = False
|
|
||||||
|
|
||||||
try:
|
|
||||||
ui.run(**run_kwargs)
|
|
||||||
except Exception as exc:
|
|
||||||
# Native mode can still fail at runtime (e.g. missing WebKit gir).
|
|
||||||
msg = str(exc).lower()
|
|
||||||
if run_kwargs.get("native") and (
|
|
||||||
"gtk" in msg or "qt" in msg or "webview" in msg or "gi" in msg
|
|
||||||
):
|
|
||||||
print(
|
|
||||||
_linux_native_hint(
|
|
||||||
f"Python {sys.version.split()[0]}; native start failed: {exc}"
|
|
||||||
),
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
run_kwargs["native"] = False
|
|
||||||
run_kwargs.pop("window_size", None)
|
|
||||||
run_kwargs["show"] = True
|
|
||||||
run_kwargs["reload"] = False if frozen else args.reload
|
|
||||||
ui.run(**run_kwargs)
|
|
||||||
else:
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ in {"__main__", "__mp_main__"}:
|
|
||||||
# NiceGUI may re-import as __mp_main__ when reload is enabled.
|
|
||||||
main()
|
|
||||||
127
tests/test_gui_app.py
Normal file
127
tests/test_gui_app.py
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from xlsx_clean.gui_app import Api
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_data_stores_state_and_uses_first_set_inks():
|
||||||
|
rows = [{"set_name": "Set A"}]
|
||||||
|
config = {"backend": "ooxml"}
|
||||||
|
with patch(
|
||||||
|
"xlsx_clean.gui_app.load_config",
|
||||||
|
return_value=(["Set", "Ink", "Serial", "addin-a", "addin-b"], rows, config),
|
||||||
|
), patch("xlsx_clean.gui_app.list_sets", return_value=["Set A"]), patch(
|
||||||
|
"xlsx_clean.gui_app.list_ink_colors", return_value=["Blue"]
|
||||||
|
) as inks:
|
||||||
|
api = Api()
|
||||||
|
data = api.get_initial_data()
|
||||||
|
|
||||||
|
assert data["sets"] == ["Set A"]
|
||||||
|
assert data["inks"] == ["Blue"]
|
||||||
|
assert data["labels"] == {"set": "Set", "ink": "Ink", "serial": "Serial"}
|
||||||
|
assert api.rows == rows
|
||||||
|
assert api.addin_paths == ["addin-a", "addin-b"]
|
||||||
|
assert api.config == config
|
||||||
|
inks.assert_called_once_with(rows, "Set A")
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_data_uses_safe_label_fallbacks_and_empty_inks():
|
||||||
|
with (
|
||||||
|
patch("xlsx_clean.gui_app.load_config", return_value=([], [], {})),
|
||||||
|
patch("xlsx_clean.gui_app.list_sets", return_value=[]),
|
||||||
|
patch("xlsx_clean.gui_app.list_ink_colors") as inks,
|
||||||
|
):
|
||||||
|
data = Api().get_initial_data()
|
||||||
|
|
||||||
|
assert data["labels"] == {
|
||||||
|
"set": "Select Set",
|
||||||
|
"ink": "Select Ink Color",
|
||||||
|
"serial": "Serial:",
|
||||||
|
}
|
||||||
|
assert data["inks"] == []
|
||||||
|
inks.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_inks_uses_initialized_rows():
|
||||||
|
api = Api()
|
||||||
|
api.rows = [{"set_name": "Set A"}]
|
||||||
|
with patch("xlsx_clean.gui_app.list_ink_colors", return_value=["Blue"]) as inks:
|
||||||
|
assert api.get_inks("Set A") == ["Blue"]
|
||||||
|
|
||||||
|
inks.assert_called_once_with(api.rows, "Set A")
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_passes_core_arguments_and_serializes_paths():
|
||||||
|
api = Api()
|
||||||
|
api.rows = [{"set_name": "Set A"}]
|
||||||
|
api.addin_paths = ["addin-a"]
|
||||||
|
api.config = {"backend": "ooxml"}
|
||||||
|
result = SimpleNamespace(
|
||||||
|
ok=True,
|
||||||
|
skipped=False,
|
||||||
|
message="Wrote workbook",
|
||||||
|
template=Path("template.xlsx"),
|
||||||
|
destination=Path("output.xlsx"),
|
||||||
|
backend="ooxml",
|
||||||
|
)
|
||||||
|
with patch("xlsx_clean.gui_app.create_datasheet", return_value=result) as create:
|
||||||
|
response = api.create("Set A", "Blue", "1234/A")
|
||||||
|
|
||||||
|
create.assert_called_once_with(
|
||||||
|
selected_set="Set A",
|
||||||
|
selected_dir="Blue",
|
||||||
|
batch_serial="1234/A",
|
||||||
|
backend=None,
|
||||||
|
rows=api.rows,
|
||||||
|
addin_paths=api.addin_paths,
|
||||||
|
config=api.config,
|
||||||
|
)
|
||||||
|
assert response == {
|
||||||
|
"ok": True,
|
||||||
|
"skipped": False,
|
||||||
|
"message": "Wrote workbook",
|
||||||
|
"template": "template.xlsx",
|
||||||
|
"destination": "output.xlsx",
|
||||||
|
"backend": "ooxml",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_serializes_missing_paths_for_error_or_skipped_result():
|
||||||
|
api = Api()
|
||||||
|
result = SimpleNamespace(
|
||||||
|
ok=False,
|
||||||
|
skipped=False,
|
||||||
|
message="Select a set.",
|
||||||
|
template=None,
|
||||||
|
destination=None,
|
||||||
|
backend=None,
|
||||||
|
)
|
||||||
|
with patch("xlsx_clean.gui_app.create_datasheet", return_value=result):
|
||||||
|
response = api.create("", "", "")
|
||||||
|
|
||||||
|
assert response["template"] is None
|
||||||
|
assert response["destination"] is None
|
||||||
|
assert response["ok"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_serializes_unexpected_exceptions_into_result_contract():
|
||||||
|
api = Api()
|
||||||
|
api.rows = [{"set_name": "Set A"}]
|
||||||
|
api.addin_paths = []
|
||||||
|
api.config = {"backend": "ooxml"}
|
||||||
|
|
||||||
|
def boom(**kwargs):
|
||||||
|
raise RuntimeError("backend exploded")
|
||||||
|
|
||||||
|
with patch("xlsx_clean.gui_app.create_datasheet", side_effect=boom):
|
||||||
|
response = api.create("Set A", "Blue", "1234/A")
|
||||||
|
|
||||||
|
assert response == {
|
||||||
|
"ok": False,
|
||||||
|
"skipped": False,
|
||||||
|
"message": "Unexpected error: backend exploded",
|
||||||
|
"template": None,
|
||||||
|
"destination": None,
|
||||||
|
"backend": None,
|
||||||
|
}
|
||||||
44
tests/test_gui_entrypoint.py
Normal file
44
tests/test_gui_entrypoint.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from xlsx_clean import gui_app
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_args_uses_default_dimensions():
|
||||||
|
args = gui_app.parse_args([])
|
||||||
|
assert (args.width, args.height) == (800, 600)
|
||||||
|
|
||||||
|
|
||||||
|
def test_main_initializes_api_before_opening_window():
|
||||||
|
index_html = Path("/tmp/index.html")
|
||||||
|
events = []
|
||||||
|
api = MagicMock()
|
||||||
|
|
||||||
|
def create_window(**kwargs):
|
||||||
|
events.append(("create_window", kwargs))
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch("xlsx_clean.gui_app.Api", return_value=api),
|
||||||
|
patch("xlsx_clean.gui_app.package_file", return_value=index_html) as package_file,
|
||||||
|
patch("xlsx_clean.gui_app.webview.create_window", side_effect=create_window),
|
||||||
|
patch("xlsx_clean.gui_app.webview.start", side_effect=lambda: events.append(("start",))),
|
||||||
|
):
|
||||||
|
gui_app.main(["--width", "900", "--height", "700"])
|
||||||
|
|
||||||
|
package_file.assert_called_once_with("ui/index.html")
|
||||||
|
api.initialize.assert_called_once_with()
|
||||||
|
assert events == [
|
||||||
|
(
|
||||||
|
"create_window",
|
||||||
|
{
|
||||||
|
"title": f"New QC Sheet · v{gui_app._VERSION}",
|
||||||
|
"url": index_html.as_uri(),
|
||||||
|
"js_api": api,
|
||||||
|
"width": 900,
|
||||||
|
"height": 700,
|
||||||
|
"min_size": (450, 400),
|
||||||
|
"background_color": "#0b0e14",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
("start",),
|
||||||
|
]
|
||||||
14
tests/test_packaging.py
Normal file
14
tests/test_packaging.py
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def test_pyinstaller_spec_collects_webview_and_local_assets():
|
||||||
|
spec = Path("packaging/xlsx_clean.spec").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
assert 'collect_all("webview")' in spec
|
||||||
|
assert 'collect_all("dearpygui")' not in spec
|
||||||
|
assert '"ui"), "xlsx_clean/ui")' in spec
|
||||||
|
assert '"fonts"), "xlsx_clean/fonts")' in spec
|
||||||
|
assert 'if sys.platform == "win32":' in spec
|
||||||
|
assert 'collect_all("clr_loader")' in spec
|
||||||
|
for hidden_import in ('"clr"', '"clr_loader"', '"pythonnet"'):
|
||||||
|
assert hidden_import in spec
|
||||||
19
tests/test_setup_linux.py
Normal file
19
tests/test_setup_linux.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_linux_pins_system_python_for_uv_sync():
|
||||||
|
script = Path("desktop/setup_linux.sh").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
assert "uv venv --python /usr/bin/python3 --no-managed-python --system-site-packages" in script
|
||||||
|
|
||||||
|
sync_lines = [
|
||||||
|
line.strip()
|
||||||
|
for line in script.splitlines()
|
||||||
|
if line.strip().startswith("uv sync")
|
||||||
|
]
|
||||||
|
assert sync_lines == [
|
||||||
|
"uv sync --python /usr/bin/python3 --no-managed-python"
|
||||||
|
]
|
||||||
|
assert "--python-preference" not in script
|
||||||
|
assert "uv sync --active" not in script
|
||||||
|
assert "include-system-site-packages = true" in script
|
||||||
63
tests/test_ui_assets.py
Normal file
63
tests/test_ui_assets.py
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import re
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from xlsx_clean.paths import package_file
|
||||||
|
|
||||||
|
|
||||||
|
class StrictHtmlParser(HTMLParser):
|
||||||
|
def error(self, message):
|
||||||
|
raise AssertionError(message)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ui_asset_exists_and_has_required_bridge_content():
|
||||||
|
html_path = package_file("ui/index.html")
|
||||||
|
assert html_path.is_file()
|
||||||
|
content = html_path.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
for expected in (
|
||||||
|
"New QC Sheet",
|
||||||
|
"Create a new QC datasheet from the latest matching workbook.",
|
||||||
|
'id="set-label"',
|
||||||
|
'id="ink-label"',
|
||||||
|
'id="serial-label"',
|
||||||
|
"Create datasheet",
|
||||||
|
"status-ready",
|
||||||
|
"status-success",
|
||||||
|
"status-skipped",
|
||||||
|
"status-error",
|
||||||
|
'id="version"',
|
||||||
|
"pywebviewready",
|
||||||
|
"get_initial_data()",
|
||||||
|
"get_inks(setDropdown.value)",
|
||||||
|
"api.create(",
|
||||||
|
"finally",
|
||||||
|
'inputEl.value = selectEl.value || ""',
|
||||||
|
'inputEl.addEventListener("mousedown", () => {\n open();\n });',
|
||||||
|
):
|
||||||
|
assert expected in content
|
||||||
|
|
||||||
|
assert "tailwind" not in content.lower()
|
||||||
|
assert "quasar" not in content.lower()
|
||||||
|
assert "cdn" not in content.lower()
|
||||||
|
assert not re.search(r"https?://", content)
|
||||||
|
assert "#0b0e14" in content
|
||||||
|
assert "#e54d5e" in content
|
||||||
|
assert "background-size: var(--grid-size) var(--grid-size)" in content
|
||||||
|
assert "background: transparent" in content
|
||||||
|
assert "tl-red" not in content
|
||||||
|
assert 'class="chrome"' not in content
|
||||||
|
StrictHtmlParser().feed(content)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ui_font_sources_are_bundled_locally():
|
||||||
|
content = package_file("ui/index.html").read_text(encoding="utf-8")
|
||||||
|
font_urls = re.findall(r'url\("([^\"]+\.ttf)"\)', content)
|
||||||
|
|
||||||
|
assert font_urls == ["../fonts/Inter-Regular.ttf", "../fonts/Inter-Bold.ttf"]
|
||||||
|
for font_url in font_urls:
|
||||||
|
assert (package_file("ui") / font_url).resolve().is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_demo_html_is_not_shipped():
|
||||||
|
assert not Path("desktop/demo.html").exists()
|
||||||
Reference in New Issue
Block a user