Merge branch 'master' into new-logo
This commit is contained in:
commit
4d5e5f3bca
|
|
@ -39,14 +39,14 @@ runs:
|
|||
using: 'composite'
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # pin@v4.2.2
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
# Python installs
|
||||
- name: Set up Python ${{ env.python_version }}
|
||||
if: ${{ inputs.python == 'true' && env.python_version != '3.14' }}
|
||||
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # pin@v5.0.0
|
||||
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||
with:
|
||||
python-version: ${{ env.python_version }}
|
||||
cache: pip
|
||||
|
|
@ -57,7 +57,7 @@ runs:
|
|||
contrib/dev_reqs/requirements.txt
|
||||
- name: Setup Python 3.14
|
||||
if: ${{ inputs.python == 'true' && env.python_version == '3.14' }}
|
||||
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # pin@v5.0.0
|
||||
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||
with:
|
||||
python-version: ${{ env.python_version }}
|
||||
- name: Install Base Python Dependencies
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ jobs:
|
|||
)
|
||||
steps:
|
||||
- name: Backport Action
|
||||
uses: sqren/backport-github-action@ad888e978060bc1b2798690dd9d03c4036560947 # pin@v9.2.2
|
||||
uses: sorenlouv/backport-github-action@8a6c0381851f43f9f1fddc7303f0e9015eb57b62 # v12.0.4
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
auto_backport_label_prefix: backport-to-
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ jobs:
|
|||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # pin@v4.0.1
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
|
|
@ -167,7 +167,7 @@ jobs:
|
|||
with:
|
||||
persist-credentials: false
|
||||
- name: Set Up Python ${{ env.python_version }}
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # pin@v6.2.0
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
||||
with:
|
||||
python-version: ${{ env.python_version }}
|
||||
- name: Version Check
|
||||
|
|
@ -178,13 +178,13 @@ jobs:
|
|||
echo "git_commit_date=$(git show -s --format=%ci)" >> $GITHUB_ENV
|
||||
- name: Set up QEMU
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # pin@v4.1.0
|
||||
uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # v4.1.0
|
||||
- name: Set up Docker Buildx
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # pin@v4.1.0
|
||||
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
|
||||
- name: Set up cosign
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # pin@v4.1.2
|
||||
uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2
|
||||
- name: Check if Dockerhub login is required
|
||||
id: docker_login
|
||||
run: |
|
||||
|
|
@ -195,14 +195,14 @@ jobs:
|
|||
fi
|
||||
- name: Login to Dockerhub
|
||||
if: github.event_name != 'pull_request' && steps.docker_login.outputs.skip_dockerhub_login != 'true'
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # pin@v4.2.0
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Log into registry ghcr.io
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # pin@v4.2.0
|
||||
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
|
|
@ -211,16 +211,16 @@ jobs:
|
|||
- name: Extract Docker metadata
|
||||
if: github.event_name != 'pull_request'
|
||||
id: meta
|
||||
uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # pin@v6.1.0
|
||||
uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0
|
||||
with:
|
||||
images: |
|
||||
inventree/inventree
|
||||
ghcr.io/${{ github.repository }}
|
||||
- uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # pin@v1
|
||||
- uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1
|
||||
- name: Push Docker Images
|
||||
id: push-docker
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: depot/build-push-action@98e78adca7817480b8185f474a400b451d74e287 # pin@v1
|
||||
uses: depot/build-push-action@98e78adca7817480b8185f474a400b451d74e287 # v1
|
||||
with:
|
||||
project: jczzbjkk68
|
||||
context: .
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ name: Frontend
|
|||
|
||||
on:
|
||||
push:
|
||||
branches-ignore: ["l10*", "dependabot/*", "backport/*"]
|
||||
branches-ignore: ["l10*", "dependabot/**", "backport/**"]
|
||||
pull_request:
|
||||
branches-ignore: ["l10*"]
|
||||
|
||||
|
|
@ -49,7 +49,7 @@ jobs:
|
|||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # pin@v4.0.1
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
|
|
@ -86,7 +86,7 @@ jobs:
|
|||
run: |
|
||||
cd src/backend/InvenTree/web/static
|
||||
zip -r frontend-build.zip web/ web/.vite
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: frontend-build
|
||||
path: src/backend/InvenTree/web/static/web
|
||||
|
|
@ -141,7 +141,7 @@ jobs:
|
|||
- name: Install dependencies
|
||||
run: invoke int.frontend-compile --extract
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # pin@v5.0.5
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
|
|
@ -165,7 +165,7 @@ jobs:
|
|||
cp ./tests/fixtures/playwright_custom_splash.png ../backend/InvenTree/InvenTree/static/img/playwright_custom_splash.png
|
||||
invoke static
|
||||
env INVENTREE_CUSTOM_SPLASH="img/playwright_custom_splash.png" INVENTREE_CUSTOM_LOGO="img/playwright_custom_logo.png" PLAYWRIGHT_BASE_URL=http://localhost:8000 npx playwright test --project=firefox --shard=${{ matrix.shard }}/2
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
if: ${{ !cancelled() && steps.tests.outcome == 'failure' }}
|
||||
with:
|
||||
name: playwright-report-firefox-${{ matrix.shard }}
|
||||
|
|
@ -223,7 +223,7 @@ jobs:
|
|||
- name: Install dependencies
|
||||
run: invoke int.frontend-compile --extract
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # pin@v5.0.5
|
||||
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
|
|
@ -245,7 +245,7 @@ jobs:
|
|||
cd src/frontend
|
||||
npx nyc playwright test --project=chromium --shard=${{ matrix.shard }}/4
|
||||
- name: Playwright Report [${{ matrix.shard }} / 4]
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
if: ${{ !cancelled() && steps.tests.outcome == 'failure' }}
|
||||
with:
|
||||
name: playwright-report-chromium-${{ matrix.shard }}
|
||||
|
|
@ -253,7 +253,7 @@ jobs:
|
|||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
- name: Upload Coverage Artifact [${{ matrix.shard }} / 4]
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
id: coverage-upload
|
||||
if: ${{ !cancelled() && steps.tests.outcome != 'failure' }}
|
||||
with:
|
||||
|
|
@ -285,7 +285,7 @@ jobs:
|
|||
update: false
|
||||
|
||||
- name: Download Coverage Artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # pin@v8.0.1
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: coverage-*
|
||||
path: all-coverage/
|
||||
|
|
@ -304,7 +304,7 @@ jobs:
|
|||
|
||||
- name: Upload coverage reports to Codecov
|
||||
if: ${{ !cancelled() && github.ref == 'refs/heads/master' }}
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # pin@v7.0.0
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
slug: inventree/InvenTree
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ name: Import / Export
|
|||
|
||||
on:
|
||||
push:
|
||||
branches-ignore: ["l10*", "dependabot/*", "backport/*"]
|
||||
branches-ignore: ["l10*", "dependabot/**", "backport/**"]
|
||||
pull_request:
|
||||
branches-ignore: ["l10*"]
|
||||
|
||||
|
|
@ -51,7 +51,7 @@ jobs:
|
|||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # pin@v4.0.1
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ name: QC
|
|||
|
||||
on:
|
||||
push:
|
||||
branches-ignore: ["l10*", "dependabot/*", "backport/*"]
|
||||
branches-ignore: ["l10*", "dependabot/**", "backport/**"]
|
||||
pull_request:
|
||||
branches-ignore: ["l10*"]
|
||||
|
||||
|
|
@ -47,7 +47,7 @@ jobs:
|
|||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # pin@v4.0.1
|
||||
- uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
|
|
@ -112,12 +112,12 @@ jobs:
|
|||
with:
|
||||
persist-credentials: false
|
||||
- name: Set up Python ${{ env.python_version }}
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # pin@v6.2.0
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
||||
with:
|
||||
python-version: ${{ env.python_version }}
|
||||
cache: "pip"
|
||||
- name: Run pre commit hook Checks
|
||||
uses: j178/prek-action@bdca6f102f98e2b4c7029491a53dfd366469e33d # pin@v2
|
||||
uses: j178/prek-action@e98a699c41eb69ab013a45817a0406469a748f8d # v2.0.5
|
||||
- name: Check Version
|
||||
run: |
|
||||
pip install --require-hashes -r contrib/dev_reqs/requirements.txt
|
||||
|
|
@ -156,7 +156,7 @@ jobs:
|
|||
with:
|
||||
persist-credentials: false
|
||||
- name: Set up Python ${{ env.python_version }}
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # pin@v6.2.0
|
||||
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
||||
with:
|
||||
python-version: ${{ env.python_version }}
|
||||
- name: Check Config
|
||||
|
|
@ -165,7 +165,7 @@ jobs:
|
|||
pip install --require-hashes -r docs/requirements.txt
|
||||
python docs/ci/check_mkdocs_config.py
|
||||
- name: Check Links
|
||||
uses: tcort/github-action-markdown-link-check@e7c7a18363c842693fadde5d41a3bd3573a7a225 # pin@v1
|
||||
uses: tcort/github-action-markdown-link-check@e7c7a18363c842693fadde5d41a3bd3573a7a225 # v1
|
||||
with:
|
||||
folder-path: docs
|
||||
config-file: docs/mlc_config.json
|
||||
|
|
@ -202,7 +202,7 @@ jobs:
|
|||
- name: Export API Documentation
|
||||
run: invoke dev.schema --ignore-warnings --filename src/backend/InvenTree/schema.yml
|
||||
- name: Upload schema
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: schema.yml
|
||||
path: src/backend/InvenTree/schema.yml
|
||||
|
|
@ -251,17 +251,17 @@ jobs:
|
|||
- name: Extract settings / tags
|
||||
run: invoke int.export-definitions --basedir docs
|
||||
- name: Upload settings
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: inventree_settings.json
|
||||
path: docs/generated/inventree_settings.json
|
||||
- name: Upload tags
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: inventree_tags.yml
|
||||
path: docs/generated/inventree_tags.yml
|
||||
- name: Upload filters
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: inventree_filters.yml
|
||||
path: docs/generated/inventree_filters.yml
|
||||
|
|
@ -284,7 +284,7 @@ jobs:
|
|||
- name: Create artifact directory
|
||||
run: mkdir -p artifact
|
||||
- name: Download schema artifact
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # pin@v8.0.1
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
path: artifact
|
||||
merge-multiple: true
|
||||
|
|
@ -301,7 +301,7 @@ jobs:
|
|||
echo "after move"
|
||||
ls -la artifact
|
||||
rm -rf artifact
|
||||
- uses: stefanzweifel/git-auto-commit-action@04702edda442b2e678b25b537cec683a1493fcb9 # pin@v7.1.0
|
||||
- uses: stefanzweifel/git-auto-commit-action@04702edda442b2e678b25b537cec683a1493fcb9 # v7.1.0
|
||||
name: Commit schema changes
|
||||
with:
|
||||
commit_message: "Update API schema for ${{ env.version }} / ${{ github.sha }}"
|
||||
|
|
@ -409,13 +409,13 @@ jobs:
|
|||
- name: Coverage Tests
|
||||
run: invoke dev.test --check --coverage --translations
|
||||
- name: Upload raw coverage to artifacts
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: coverage
|
||||
path: .coverage
|
||||
retention-days: 14
|
||||
- name: Upload coverage reports to Codecov
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # pin@v7.0.0
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
|
||||
if: always()
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
|
@ -597,7 +597,7 @@ jobs:
|
|||
- name: Run Tests
|
||||
run: invoke dev.test --check --migrations --report --coverage --translations
|
||||
- name: Upload coverage reports to Codecov
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # pin@v7.0.0
|
||||
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
|
||||
if: always()
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ jobs:
|
|||
pip install --require-hashes -r contrib/dev_reqs/requirements.txt
|
||||
python3 .github/scripts/version_check.py
|
||||
- name: Push to Stable Branch
|
||||
uses: ad-m/github-push-action@881a6320fdb16eb5318c5054f31c218aec2b324c # pin@v1.3.0
|
||||
uses: ad-m/github-push-action@881a6320fdb16eb5318c5054f31c218aec2b324c # v1.3.0
|
||||
if: env.stable_release == 'true'
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
|
@ -57,7 +57,7 @@ jobs:
|
|||
- name: Build frontend
|
||||
run: cd src/frontend && npm run compile && npm run build
|
||||
- name: Create SBOM for frontend
|
||||
uses: anchore/sbom-action@e22c389904149dbc22b58101806040fa8d37a610 # pin@v0
|
||||
uses: anchore/sbom-action@e22c389904149dbc22b58101806040fa8d37a610 # v0
|
||||
with:
|
||||
artifact-name: frontend-build.spdx
|
||||
path: src/frontend
|
||||
|
|
@ -75,7 +75,7 @@ jobs:
|
|||
zip -r ../frontend-build.zip * .vite
|
||||
- name: Attest Build Provenance
|
||||
id: attest
|
||||
uses: actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26 # pin@v4
|
||||
uses: actions/attest@a1948c3f048ba23858d222213b7c278aabede763 # v4.1.1
|
||||
with:
|
||||
subject-path: "${{ github.workspace }}/src/backend/InvenTree/web/static/frontend-build.zip"
|
||||
|
||||
|
|
@ -85,7 +85,7 @@ jobs:
|
|||
REF: ${{ github.ref_name }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Upload frontend to artifacts
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # pin@v7.0.1
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: frontend-build
|
||||
path: src/backend/InvenTree/web/static/frontend-build.zip
|
||||
|
|
@ -161,7 +161,7 @@ jobs:
|
|||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Get frontend artifact
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # pin@v8.0.1
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: frontend-build
|
||||
- name: Setup
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ jobs:
|
|||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- uses: actions/stale@eb5cf3af3ac0a1aa4c9c45633dd1ae542a27a899 # pin@v10.3.0
|
||||
- uses: actions/stale@eb5cf3af3ac0a1aa4c9c45633dd1ae542a27a899 # v10.3.0
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: "This issue seems stale. Please react to show this is still important."
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ jobs:
|
|||
echo "Resetting to HEAD~"
|
||||
git reset HEAD~ || true
|
||||
- name: crowdin action
|
||||
uses: crowdin/github-action@52aa776766211d83d975df51f3b9c53c2f8ba35f # pin@v2
|
||||
uses: crowdin/github-action@52aa776766211d83d975df51f3b9c53c2f8ba35f # v2
|
||||
with:
|
||||
upload_sources: true
|
||||
upload_translations: false
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ jobs:
|
|||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # pin@v4.2.2
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Setup
|
||||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
run: pip-compile --output-file=requirements.txt requirements.in -U
|
||||
- name: Update requirements-dev.txt
|
||||
run: pip-compile --generate-hashes --output-file=requirements-dev.txt requirements-dev.in -U
|
||||
- uses: stefanzweifel/git-auto-commit-action@fd157da78fa13d9383e5580d1fd1184d89554b51 # pin@v4.15.1
|
||||
- uses: stefanzweifel/git-auto-commit-action@fd157da78fa13d9383e5580d1fd1184d89554b51 # v4.15.1
|
||||
with:
|
||||
commit_message: "[Bot] Updated dependency"
|
||||
branch: dep-update
|
||||
|
|
|
|||
|
|
@ -4,15 +4,57 @@ title: Report Mixin
|
|||
|
||||
## ReportMixin
|
||||
|
||||
The `ReportMixin` class provides a plugin with the ability to extend the functionality of custom [report templates](../../report/report.md). A plugin which implements the ReportMixin mixin class can add custom context data to a report template for rendering.
|
||||
The `ReportMixin` class provides a plugin with the ability to extend the functionality of custom [report templates](../../report/report.md). A plugin which implements the ReportMixin mixin class can add custom context data to a report template for rendering, and can also receive a callback when a report is generated.
|
||||
|
||||
### Add Report Context
|
||||
|
||||
A plugin which implements the ReportMixin mixin can define the `add_report_context` method, allowing custom context data to be added to a report template at time of printing.
|
||||
|
||||
This method is called each time a report is generated, and is passed the following arguments:
|
||||
|
||||
| Argument | Description |
|
||||
| --- | --- |
|
||||
| `report_instance` | The report template instance which is being rendered |
|
||||
| `model_instance` | The model instance against which the report is being generated |
|
||||
| `user` | The user who initiated the report generation |
|
||||
| `context` | The context dictionary, which can be modified in-place |
|
||||
|
||||
Any data added to the provided `context` dictionary is made available to the report template, and can be rendered using standard django template syntax:
|
||||
|
||||
```python
|
||||
def add_report_context(self, report_instance, model_instance, user, context):
|
||||
"""Add extra context data to the report template."""
|
||||
context['my_custom_data'] = self.calculate_custom_data(model_instance)
|
||||
```
|
||||
|
||||
### Add Label Context
|
||||
|
||||
Additionally the `add_label_context` method, allowing custom context data to be added to a label template at time of printing.
|
||||
Similarly, the `add_label_context` method allows custom context data to be added to a label template at time of printing:
|
||||
|
||||
| Argument | Description |
|
||||
| --- | --- |
|
||||
| `label_instance` | The label template instance which is being rendered |
|
||||
| `model_instance` | The model instance against which the label is being generated |
|
||||
| `user` | The user who initiated the label generation |
|
||||
| `context` | The context dictionary, which can be modified in-place |
|
||||
|
||||
### Report Callback
|
||||
|
||||
The `report_callback` method is called after a report has been generated, and allows the plugin to perform custom actions with the generated report - for example, forwarding the report to an external system, or performing custom post-processing.
|
||||
|
||||
| Argument | Description |
|
||||
| --- | --- |
|
||||
| `template` | The report template instance which was used to generate the report |
|
||||
| `instance` | The model instance against which the report was generated |
|
||||
| `report` | The generated report (PDF file data) |
|
||||
| `user` | The user who initiated the report generation |
|
||||
|
||||
```python
|
||||
def report_callback(self, template, instance, report, user, **kwargs):
|
||||
"""Custom callback function - called after a report is generated."""
|
||||
# For example, forward the generated report to an external service
|
||||
self.upload_to_external_service(report)
|
||||
```
|
||||
|
||||
### Sample Plugin
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,45 @@
|
|||
---
|
||||
title: Report Assets
|
||||
---
|
||||
|
||||
## Report Assets
|
||||
|
||||
Users can upload asset files (e.g. images) which can be used when generating reports. For example, you may wish to generate a report with your company logo in the header.
|
||||
|
||||
Asset files are managed from the [Admin Center](../settings/admin.md#admin-center), via the *Report Assets* panel. Staff users can upload new asset files, and remove assets which are no longer required.
|
||||
|
||||
Asset files can be rendered directly into the template as follows
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
<!-- Need to include the report template tags at the start of the template file -->
|
||||
{% load report %}
|
||||
|
||||
<!-- Simple stylesheet -->
|
||||
<head>
|
||||
<style>
|
||||
.company-logo {
|
||||
height: 50px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- Report template code here -->
|
||||
|
||||
<!-- Render an uploaded asset image -->
|
||||
<img src="{% asset 'company_image.png' %}" class="company-logo">
|
||||
|
||||
<!-- ... -->
|
||||
</body>
|
||||
|
||||
{% endraw %}
|
||||
```
|
||||
|
||||
!!! warning "Asset Naming"
|
||||
If the requested asset name does not match the name of an uploaded asset, the template will continue without loading the image.
|
||||
|
||||
!!! info "Assets location"
|
||||
Upload new assets via the *Report Assets* panel in the [Admin Center](../settings/admin.md#admin-center) to ensure they are uploaded to the correct location on the server.
|
||||
|
||||
There are various [helper functions](./helpers.md#report-assets) available to assist with embedding assets into templates.
|
||||
|
|
@ -69,12 +69,14 @@ Templates (whether for generating [reports](./report.md) or [labels](./labels.md
|
|||
|
||||
| Model Type | Description |
|
||||
| --- | --- |
|
||||
| company | A Company instance |
|
||||
| [company](#company) | A Company instance |
|
||||
| [build](#build-order) | A [Build Order](../manufacturing/build.md) instance |
|
||||
| [buildline](#build-line) | A [Build Order Line Item](../manufacturing/build.md) instance |
|
||||
| [salesorder](#sales-order) | A [Sales Order](../sales/sales_order.md) instance |
|
||||
| [salesordershipment](#sales-order-shipment) | A [Sales Order Shipment](../sales/sales_order.md#sales-order-shipments) instance |
|
||||
| [returnorder](#return-order) | A [Return Order](../sales/return_order.md) instance |
|
||||
| [purchaseorder](#purchase-order) | A [Purchase Order](../purchasing/purchase_order.md) instance |
|
||||
| [transferorder](#transfer-order) | A [Transfer Order](../stock/transfer_order.md) instance |
|
||||
| [stockitem](#stock-item) | A [StockItem](../stock/index.md#stock-item) instance |
|
||||
| [stocklocation](#stock-location) | A [StockLocation](../stock/index.md#stock-location) instance |
|
||||
| [part](#part) | A [Part](../part/index.md) instance |
|
||||
|
|
@ -141,6 +143,16 @@ When printing a report or label against a [PurchaseOrder](../purchasing/purchase
|
|||
|
||||
{{ report_context("models", "purchaseorder") }}
|
||||
|
||||
### Transfer Order
|
||||
|
||||
When printing a report or label against a [TransferOrder](../stock/transfer_order.md) object, the following context variables are available:
|
||||
|
||||
{{ report_context("models", "transferorder") }}
|
||||
|
||||
::: order.models.TransferOrder.report_context
|
||||
options:
|
||||
show_source: True
|
||||
|
||||
### Stock Item
|
||||
|
||||
When printing a report or label against a [StockItem](../stock/index.md#stock-item) object, the following context variables are available:
|
||||
|
|
@ -173,7 +185,7 @@ When printing a report or label against a [Part](../part/index.md) object, the f
|
|||
|
||||
## Model Variables
|
||||
|
||||
Additional to the context variables provided directly to each template, each model type has a number of attributes and methods which can be accessedd via the template.
|
||||
Additional to the context variables provided directly to each template, each model type has a number of attributes and methods which can be accessed via the template.
|
||||
|
||||
For each model type, a subset of the most commonly used attributes are listed below. For a full list of attributes and methods, refer to the source code for the particular model type.
|
||||
|
||||
|
|
@ -187,7 +199,6 @@ Each part object has access to a lot of context variables about the part. The fo
|
|||
|----------|-------------|
|
||||
| name | Brief name for this part |
|
||||
| full_name | Full name for this part (including IPN, if not null and including variant, if not null) |
|
||||
| variant | Optional variant number for this part - Must be unique for the part name
|
||||
| category | The [PartCategory](#part-category) object to which this part belongs
|
||||
| description | Longer form description of the part
|
||||
| keywords | Optional keywords for improving part search results
|
||||
|
|
@ -244,7 +255,6 @@ Each part object has access to a lot of context variables about the part. The fo
|
|||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| parent | Link to another [StockItem](#stock-item) from which this StockItem was created |
|
||||
| uid | Field containing a unique-id which is mapped to a third-party identifier (e.g. a barcode) |
|
||||
| part | Link to the master abstract [Part](#part) that this [StockItem](#stock-item) is an instance of |
|
||||
| supplier_part | Link to a specific [SupplierPart](#supplierpart) (optional) |
|
||||
| location | The [StockLocation](#stock-location) Where this [StockItem](#stock-item) is located |
|
||||
|
|
@ -263,7 +273,6 @@ Each part object has access to a lot of context variables about the part. The fo
|
|||
| build | Link to a Build (if this stock item was created from a build) |
|
||||
| is_building | Boolean field indicating if this stock item is currently being built (or is "in production") |
|
||||
| purchase_order | Link to a [PurchaseOrder](#purchase-order) (if this stock item was created from a PurchaseOrder) |
|
||||
| infinite | If True this [StockItem](#stock-item) can never be exhausted |
|
||||
| sales_order | Link to a [SalesOrder](#sales-order) object (if the StockItem has been assigned to a SalesOrder) |
|
||||
| purchase_price | The unit purchase price for this [StockItem](#stock-item) - this is the unit price at time of purchase (if this item was purchased from an external supplier) |
|
||||
| packaging | Description of how the StockItem is packaged (e.g. "reel", "loose", "tape" etc) |
|
||||
|
|
@ -353,7 +362,7 @@ Each part object has access to a lot of context variables about the part. The fo
|
|||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| username | the username of the user |
|
||||
| fist_name | The first name of the user |
|
||||
| first_name | The first name of the user |
|
||||
| last_name | The last name of the user |
|
||||
| email | The email address of the user |
|
||||
| pk | The primary key of the user |
|
||||
|
|
|
|||
|
|
@ -907,7 +907,7 @@ If you have a custom logo, but explicitly wish to load the InvenTree logo itself
|
|||
|
||||
## Report Assets
|
||||
|
||||
[Report Assets](./index.md#report-assets) are files specifically uploaded by the user for inclusion in generated reports and labels.
|
||||
[Report Assets](./assets.md) are files specifically uploaded by the user for inclusion in generated reports and labels.
|
||||
|
||||
You can add asset images to the reports and labels by using the `{% raw %}{% asset ... %}{% endraw %}` template tag:
|
||||
|
||||
|
|
|
|||
|
|
@ -53,29 +53,43 @@ To read more about the capabilities of the report templating engine, and how to
|
|||
|
||||
## Creating Templates
|
||||
|
||||
Report and label templates can be created (and edited) via the [admin interface](../settings/admin.md), under the *Report* section.
|
||||
Report and label templates are managed from the [Admin Center](../settings/admin.md#admin-center), which provides dedicated panels (under the *Reporting* group) for each template type:
|
||||
|
||||
Select the type of template you are wanting to create (a *Report Template* or *Label Template*) and press the *Add* button in the top right corner:
|
||||
- **Label Templates** - Create and edit [label templates](./labels.md)
|
||||
- **Report Templates** - Create and edit [report templates](./report.md)
|
||||
- **Report Snippets** - Manage reusable [snippet](#report-snippets) files
|
||||
- **Report Assets** - Manage uploaded [asset](#report-assets) files
|
||||
|
||||
{{ image("report/report_template_admin.png", "Report template admin") }}
|
||||
Label and report templates are created and edited using the built-in [template editor](./template_editor.md), which allows templates to be written directly within the browser, with a live preview of the rendered output.
|
||||
|
||||
!!! tip "Staff Access Only"
|
||||
Only users with staff access can upload or edit report template files.
|
||||
Only users with staff access can create, upload or edit templates, snippets and assets.
|
||||
|
||||
!!! info "Editing Reports"
|
||||
Existing reports can be edited from the admin interface, in the same location as described above. To change the contents of the template, re-upload a template file, to override the existing template data.
|
||||
|
||||
!!! tip "Template Editor"
|
||||
InvenTree also provides a powerful [template editor](./template_editor.md) which allows for the creation and editing of report templates directly within the browser.
|
||||
!!! info "Backend Admin Interface"
|
||||
Templates can also be managed at a lower level via the [backend admin interface](../settings/admin.md#backend-admin-interface), under the *Report* section. This is recommended for advanced users only.
|
||||
|
||||
### Name and Description
|
||||
|
||||
Each report template requires a name and description, which identify and describe the report template.
|
||||
|
||||
### Revision
|
||||
|
||||
Each template has a revision number, which is automatically incremented each time the template is updated. This provides a simple mechanism for tracking changes to a template over time. The revision number is read-only, and cannot be edited directly.
|
||||
|
||||
!!! info "Template Revision Context"
|
||||
The revision number of the template is made available when rendering, via the `template_revision` [context variable](./context_variables.md#global-context).
|
||||
|
||||
### Enabled Status
|
||||
|
||||
Boolean field which determines if the specific report template is enabled, and available for use. Reports can be disabled to remove them from the list of available templates, but without deleting them from the database.
|
||||
|
||||
### Attach to Model
|
||||
|
||||
If the *Attach to Model on Print* option is enabled, a copy of the generated report is automatically saved as a file attachment against the item (model instance) for which it was generated, each time the template is printed.
|
||||
|
||||
!!! warning "Attachment Support"
|
||||
The report output is only attached if the target model type supports file attachments.
|
||||
|
||||
### Filename Pattern
|
||||
|
||||
The filename pattern used to generate the output `.pdf` file. Defaults to "report.pdf".
|
||||
|
|
@ -147,89 +161,15 @@ Setting the *Debug Mode* option renders the template as raw HTML instead of PDF,
|
|||
|
||||
## Report Assets
|
||||
|
||||
User can upload asset files (e.g. images) which can be used when generating reports. For example, you may wish to generate a report with your company logo in the header. Asset files are uploaded via the admin interface.
|
||||
|
||||
Asset files can be rendered directly into the template as follows
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
<!-- Need to include the report template tags at the start of the template file -->
|
||||
{% load report %}
|
||||
|
||||
<!-- Simple stylesheet -->
|
||||
<head>
|
||||
<style>
|
||||
.company-logo {
|
||||
height: 50px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- Report template code here -->
|
||||
|
||||
<!-- Render an uploaded asset image -->
|
||||
<img src="{% asset 'company_image.png' %}" class="company-logo">
|
||||
|
||||
<!-- ... -->
|
||||
</body>
|
||||
|
||||
{% endraw %}
|
||||
```
|
||||
|
||||
!!! warning "Asset Naming"
|
||||
If the requested asset name does not match the name of an uploaded asset, the template will continue without loading the image.
|
||||
|
||||
!!! info "Assets location"
|
||||
Upload new assets via the [admin interface](../settings/admin.md) to ensure they are uploaded to the correct location on the server.
|
||||
User can upload asset files (e.g. images) which can be used when generating reports. For example, you may wish to generate a report with your company logo in the header.
|
||||
|
||||
Refer to the [report assets](./assets.md) documentation for further information.
|
||||
|
||||
## Report Snippets
|
||||
|
||||
A powerful feature provided by the django / WeasyPrint templating framework is the ability to include external template files. This allows commonly used template features to be broken out into separate files and reused across multiple templates.
|
||||
InvenTree provides report "snippets" - reusable template files which cannot be rendered by themselves, but can be included in other templates.
|
||||
|
||||
To support this, InvenTree provides report "snippets" - short (or not so short) template files which cannot be rendered by themselves, but can be called from other templates.
|
||||
|
||||
Similar to assets files, snippet template files are uploaded via the admin interface.
|
||||
|
||||
Snippets are included in a template as follows:
|
||||
|
||||
```
|
||||
{% raw %}{% include 'snippets/<snippet_name.html>' %}{% endraw %}
|
||||
```
|
||||
|
||||
For example, consider a custom stocktake report for a particular stock location, where we wish to render a table with a row for each item in that location.
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
|
||||
<table class='stock-table'>
|
||||
<thead>
|
||||
<!-- table header data -->
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in location.stock_items %}
|
||||
{% include 'snippets/stock_row.html' with item=item %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
{% endraw %}
|
||||
```
|
||||
|
||||
!!! info "Snippet Arguments"
|
||||
Note above that named argument variables can be passed through to the snippet!
|
||||
|
||||
And the snippet file `stock_row.html` may be written as follows:
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
<!-- stock_row snippet -->
|
||||
<tr>
|
||||
<td>{{ item.part.full_name }}</td>
|
||||
<td>{{ item.quantity }}</td>
|
||||
</tr>
|
||||
{% endraw %}
|
||||
```
|
||||
Refer to the [report snippets](./snippets.md) documentation for further information.
|
||||
|
||||
## Security
|
||||
|
||||
|
|
@ -243,7 +183,7 @@ When WeasyPrint renders a template to PDF it can make outbound requests to load
|
|||
|---|---|
|
||||
| `data:` URIs | Always permitted — self-contained, no network access |
|
||||
| `file://` | Always blocked — assets and images must be inlined as `data:` URIs before reaching WeasyPrint |
|
||||
| `http` / `https` | Disabled by default, but can be blocked - see *Remote URL Fetching* below |
|
||||
| `http` / `https` | Disabled by default, but can be enabled - see *Remote URL Fetching* below |
|
||||
| Any other scheme | Always blocked |
|
||||
|
||||
HTTP redirects are also disabled: a URL that passes validation cannot redirect to an internal address.
|
||||
|
|
@ -259,6 +199,6 @@ When enabled, URLs are still validated against private, loopback, link-local, an
|
|||
|
||||
### Asset Files
|
||||
|
||||
Asset files uploaded through the admin interface are embedded directly into the rendered PDF as base64 `data:` URIs — they are read via the Django storage API and never loaded through WeasyPrint's URL fetcher. This means assets work correctly regardless of whether remote URL fetching is enabled, and also work with remote storage backends such as S3.
|
||||
[Asset files](./assets.md) uploaded through the admin interface are embedded directly into the rendered PDF as base64 `data:` URIs — they are read via the Django storage API and never loaded through WeasyPrint's URL fetcher. This means assets work correctly regardless of whether remote URL fetching is enabled, and also work with remote storage backends such as S3.
|
||||
|
||||
There are various [helper functions](./helpers.md#report-assets) available to assist with embedding assets into templates.
|
||||
|
|
|
|||
|
|
@ -128,6 +128,25 @@ As an example, consider a label template for a StockItem. A user may wish to def
|
|||
|
||||
To restrict the label accordingly, we could set the *filters* value to `part__IPN=IPN123`.
|
||||
|
||||
## Printing Labels
|
||||
|
||||
Labels are printed directly from the web interface, from the pages where the target items are displayed. To print labels against one or more items:
|
||||
|
||||
1. Select the items to print - either from a table (using the row checkboxes), or by viewing the detail page of a single item
|
||||
2. Select the *Print* action, and choose the *Print Label* option
|
||||
3. Select the desired label template - only *enabled* templates which match the selected model type (and pass any template filters) are available for selection
|
||||
4. Select the *printer* (plugin) to use for printing the labels
|
||||
|
||||
### Label Printing Plugins
|
||||
|
||||
The actual printing of labels is handled by a [label printing plugin](../plugins/mixins/label.md). InvenTree provides a number of built-in printing plugins:
|
||||
|
||||
- The default [InvenTree Label Printer](../plugins/builtin/inventree_label.md) plugin generates a PDF file, which is then made available for download.
|
||||
- The [Label Sheet](../plugins/builtin/inventree_label_sheet.md) plugin arranges multiple labels onto a single sheet for printing.
|
||||
- The [Label Machine](../plugins/builtin/inventree_label_machine.md) plugin sends the label to an external [label printer machine](../plugins/machines/label_printer.md).
|
||||
|
||||
Custom label printing plugins (e.g. for driving a specific hardware printer) can be installed to extend this list - refer to the [label mixin documentation](../plugins/mixins/label.md) for further information.
|
||||
|
||||
## Built-In Templates
|
||||
|
||||
The InvenTree installation provides a number of simple *default* templates which can be used as a starting point for creating custom labels. These built-in templates can be disabled if they are not required.
|
||||
|
|
|
|||
|
|
@ -1,53 +1,51 @@
|
|||
---
|
||||
title: Report and Label Generation
|
||||
title: Report Templates
|
||||
---
|
||||
|
||||
## Custom Reports
|
||||
## Report Templates
|
||||
|
||||
InvenTree supports a customizable reporting ecosystem, allowing the user to develop document templates that meet their particular needs.
|
||||
Report templates are used to generate formal PDF documents - such as order reports, packing lists, or test reports - rendered against a particular database item (or list of items).
|
||||
|
||||
PDF files are generated from custom HTML template files which are written by the user.
|
||||
Like all InvenTree templates, report templates are written using a mixture of HTML / CSS and the django template language, and are rendered to a PDF file using the WeasyPrint engine:
|
||||
|
||||
Templates can be used to generate *reports* or *labels* which can be used in a variety of situations to format data in a friendly format for printing, distribution, conformance and testing.
|
||||
- Refer to the [template overview](./index.md) for information on creating and managing templates.
|
||||
- Refer to the [template rendering documentation](./weasyprint.md) for information on the WeasyPrint engine and the django template language.
|
||||
- Refer to the [context variables documentation](./context_variables.md) for the variables available when rendering a template.
|
||||
|
||||
In addition to providing the ability for end-users to provide their own reporting templates, some report types offer "built-in" report templates ready for use.
|
||||
## Report Options
|
||||
|
||||
### WeasyPrint Templates
|
||||
In addition to the [options common to all templates](./index.md#creating-templates), each report template provides the following options:
|
||||
|
||||
InvenTree report templates utilize the powerful [WeasyPrint](https://weasyprint.org/) PDF generation engine.
|
||||
### Page Size
|
||||
|
||||
!!! info "WeasyPrint"
|
||||
WeasyPrint is an extremely powerful and flexible reporting library. Refer to the [WeasyPrint docs](https://doc.courtbouillon.org/weasyprint/stable/) for further information.
|
||||
The page size (e.g. `A4` or `Letter`) used when rendering the report to a PDF file. When a new report template is created, this value defaults to the [default page size](./index.md#default-page-size) specified in the global settings.
|
||||
|
||||
### Stylesheets
|
||||
### Landscape
|
||||
|
||||
Templates are rendered using standard HTML / CSS - if you are familiar with web page layout, you're ready to go!
|
||||
If enabled, the report is rendered in landscape orientation, rather than the default portrait orientation.
|
||||
|
||||
### Template Language
|
||||
### Merge
|
||||
|
||||
Uploaded report template files are passed through the [django template rendering framework]({% include "django.html" %}/topics/templates/), and as such accept the same variable template strings as any other django template file. Different variables are passed to the report template (based on the context of the report) and can be used to customize the contents of the generated PDF.
|
||||
If enabled, a single report document is generated for all selected items, rather than a separate document for each item. Refer to the [merging reports](#merging-reports) section below for further information.
|
||||
|
||||
### Variables
|
||||
!!! info "Context Variables"
|
||||
The `page_size`, `landscape` and `merge` values are also made available to the template as [context variables](./context_variables.md#report-context).
|
||||
|
||||
Each report template is provided a set of *context variables* which can be used when rendering the template.
|
||||
## Generating Reports
|
||||
|
||||
For example, rendering the name of a part (which is available in the particular template context as `part`) is as follows:
|
||||
Reports are generated directly from the web interface, from the pages where the target items are displayed. To generate a report against one or more items:
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
1. Select the items to print - either from a table (using the row checkboxes), or by viewing the detail page of a single item
|
||||
2. Select the *Print* action, and choose the *Print Report* option
|
||||
3. Select the desired report template - only *enabled* templates which match the selected model type (and pass any [template filters](./index.md#template-filters)) are available for selection
|
||||
4. The report is generated by the server, and the resulting PDF file is made available for download
|
||||
|
||||
<!-- Template variables use {{ double_curly_braces }} -->
|
||||
<h2>Part: {{ part.name }}</h3>
|
||||
<p><i>
|
||||
Description:<br>
|
||||
{{ part.description }}
|
||||
</p></i>
|
||||
{% endraw %}
|
||||
```
|
||||
!!! info "Enable Reports"
|
||||
Report generation must be [enabled in the global settings](./index.md#enable-reports) before reports can be generated.
|
||||
|
||||
## Merging Reports
|
||||
|
||||
When rendering reports for multiple items, the default behaviour is that each item is rendered as a separate report. The chosen templeate is rendered multiple times, once for each item selected, and expects a single item in the context variable.
|
||||
When rendering reports for multiple items, the default behaviour is that each item is rendered as a separate report. The chosen template is rendered multiple times, once for each item selected, and expects a single item in the context variable.
|
||||
|
||||
However, it is possible to merge multiple items into a single report document. This is achieved by enabling the `merge` attribute of the report template:
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ The following report templates are provided "out of the box" and can be used as
|
|||
| [Sales Order Shipment](#sales-order-shipment) | [SalesOrderShipment](../sales/sales_order.md) | Sales Order Shipment report |
|
||||
| [Stock Location](#stock-location) | [StockLocation](../stock/index.md#stock-location) | Stock Location report |
|
||||
| [Test Report](#test-report) | [StockItem](../stock/index.md#stock-item) | Test Report |
|
||||
| [Transfer Order](#transfer-order) | [TransferOrder](../stock/transfer_order.md) | Transfer Order report |
|
||||
| [Selected Stock Items Report](#selected-stock-items-report) | [StockItem](../stock/index.md#stock-item) | Selected Stock Items report |
|
||||
|
||||
|
||||
|
|
@ -57,6 +58,10 @@ The following report templates are provided "out of the box" and can be used as
|
|||
|
||||
{{ templatefile("report/inventree_test_report.html") }}
|
||||
|
||||
### Transfer Order
|
||||
|
||||
{{ templatefile("report/inventree_transfer_order_report.html") }}
|
||||
|
||||
### Selected Stock Items Report
|
||||
|
||||
{{ templatefile("report/inventree_stock_report_merge.html") }}
|
||||
|
|
@ -68,9 +73,11 @@ The following label templates are provided "out of the box" and can be used as a
|
|||
| Template | Model Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [Build Line](#build-line-label) | [Build line item](../manufacturing/build.md) | Build Line label |
|
||||
| [Part](#part-label) | [Part](../part/index.md) | Part label |
|
||||
| [Part](#part-label) | [Part](../part/index.md) | Part label (QR code and part name) |
|
||||
| [Part (Code128)](#part-label-code128) | [Part](../part/index.md) | Part label (Code128 barcode) |
|
||||
| [Stock Item](#stock-item-label) | [StockItem](../stock/index.md#stock-item) | Stock Item label |
|
||||
| [Stock Location](#stock-location-label) | [StockLocation](../stock/index.md#stock-location) | Stock Location label |
|
||||
| [Stock Location](#stock-location-label) | [StockLocation](../stock/index.md#stock-location) | Stock Location label (QR code) |
|
||||
| [Stock Location (with text)](#stock-location-label-with-text) | [StockLocation](../stock/index.md#stock-location) | Stock Location label (QR code and location details) |
|
||||
|
||||
### Build Line Label
|
||||
|
||||
|
|
@ -78,6 +85,10 @@ The following label templates are provided "out of the box" and can be used as a
|
|||
|
||||
### Part Label
|
||||
|
||||
{{ templatefile("label/part_label.html") }}
|
||||
|
||||
### Part Label (Code128)
|
||||
|
||||
{{ templatefile("label/part_label_code128.html") }}
|
||||
|
||||
### Stock Item Label
|
||||
|
|
@ -86,4 +97,8 @@ The following label templates are provided "out of the box" and can be used as a
|
|||
|
||||
### Stock Location Label
|
||||
|
||||
{{ templatefile("label/stocklocation_qr.html") }}
|
||||
|
||||
### Stock Location Label (with text)
|
||||
|
||||
{{ templatefile("label/stocklocation_qr_and_text.html") }}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
---
|
||||
title: Report Snippets
|
||||
---
|
||||
|
||||
## Report Snippets
|
||||
|
||||
A powerful feature provided by the django / WeasyPrint templating framework is the ability to include external template files. This allows commonly used template features to be broken out into separate files and reused across multiple templates.
|
||||
|
||||
To support this, InvenTree provides report "snippets" - short (or not so short) template files which cannot be rendered by themselves, but can be called from other templates.
|
||||
|
||||
Snippet files are managed from the [Admin Center](../settings/admin.md#admin-center), via the *Report Snippets* panel. Staff users can upload new snippet files, and edit or remove existing snippets.
|
||||
|
||||
Additionally, the content of an existing snippet can be modified directly within the browser - simply select a snippet from the table to open it in the built-in [template editor](./template_editor.md#editing-snippets).
|
||||
|
||||
Snippets are included in a template as follows:
|
||||
|
||||
```
|
||||
{% raw %}{% include 'snippets/<snippet_name.html>' %}{% endraw %}
|
||||
```
|
||||
|
||||
For example, consider a custom stocktake report for a particular stock location, where we wish to render a table with a row for each item in that location.
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
|
||||
<table class='stock-table'>
|
||||
<thead>
|
||||
<!-- table header data -->
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for item in location.stock_items %}
|
||||
{% include 'snippets/stock_row.html' with item=item %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
|
||||
{% endraw %}
|
||||
```
|
||||
|
||||
!!! info "Snippet Arguments"
|
||||
Note above that named argument variables can be passed through to the snippet!
|
||||
|
||||
And the snippet file `stock_row.html` may be written as follows:
|
||||
|
||||
```html
|
||||
{% raw %}
|
||||
<!-- stock_row snippet -->
|
||||
<tr>
|
||||
<td>{{ item.part.full_name }}</td>
|
||||
<td>{{ item.quantity }}</td>
|
||||
</tr>
|
||||
{% endraw %}
|
||||
```
|
||||
|
|
@ -4,11 +4,11 @@ title: Template editor
|
|||
|
||||
## Template editor
|
||||
|
||||
The Template Editor is integrated into the [Admin Center](../settings//admin.md#admin-center) of the Web UI. It allows users to create and edit label and report templates directly with a side by side preview for a more productive workflow.
|
||||
The Template Editor is integrated into the [Admin Center](../settings/admin.md#admin-center) of the Web UI. It allows users to create and edit label and report templates directly with a side by side preview for a more productive workflow.
|
||||
|
||||

|
||||
|
||||
On the left side (1) are all possible possible template types for labels and reports listed. With the "+" button (2), above the template table (3), new templates for the selected type can be created. To switch to the template editor click on a template.
|
||||
On the left side (1) are all possible template types for labels and reports listed. With the "+" button (2), above the template table (3), new templates for the selected type can be created. To switch to the template editor click on a template.
|
||||
|
||||
### Editing Templates
|
||||
|
||||
|
|
@ -31,3 +31,10 @@ If you don't want to override the template, but just render a preview for a temp
|
|||
#### Edit template metadata
|
||||
|
||||
Editing metadata such as name, description, filters and even width/height for labels and orientation/page size for reports can be done from the edit modal accessible when clicking on the three dots (4) and select "Edit" in the dropdown menu.
|
||||
|
||||
### Editing Snippets
|
||||
|
||||
[Report snippets](./index.md#report-snippets) can also be edited directly within the browser, from the *Report Snippets* panel in the Admin Center. Selecting a snippet from the table opens it in the same code editor as used for report and label templates.
|
||||
|
||||
!!! info "No Preview"
|
||||
As snippets cannot be rendered by themselves (they must be included in a report or label template), no preview area is available when editing a snippet.
|
||||
|
|
|
|||
|
|
@ -174,6 +174,8 @@ nav:
|
|||
- Template Editor: report/template_editor.md
|
||||
- Reports: report/report.md
|
||||
- Labels: report/labels.md
|
||||
- Report Assets: report/assets.md
|
||||
- Report Snippets: report/snippets.md
|
||||
- Context Variables: report/context_variables.md
|
||||
- Helper Functions: report/helpers.md
|
||||
- Barcodes: report/barcodes.md
|
||||
|
|
|
|||
|
|
@ -1,11 +1,16 @@
|
|||
"""InvenTree API version information."""
|
||||
|
||||
# InvenTree API version
|
||||
INVENTREE_API_VERSION = 513
|
||||
INVENTREE_API_VERSION = 514
|
||||
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
|
||||
|
||||
INVENTREE_API_TEXT = """
|
||||
|
||||
v514 -> 2026-07-02 : https://github.com/inventree/InvenTree/pull/12294
|
||||
- Adds "duplicate" field to the BuildOrder, Company, ManufacturerPart, SupplierPart and SalesOrderShipment API endpoints
|
||||
- Order duplication options: renames "order_id" field to "original", which now performs primary-key validation
|
||||
- Part duplication options: renames "part" field to "original"
|
||||
|
||||
v513 -> 2026-06-25 : https://github.com/inventree/InvenTree/pull/12250
|
||||
- Adds "active" field to the ProjectCode model and API endpoints
|
||||
|
||||
|
|
|
|||
|
|
@ -600,7 +600,7 @@ class InvenTreeModelSerializer(serializers.ModelSerializer):
|
|||
|
||||
Default implementation returns an empty list
|
||||
"""
|
||||
return []
|
||||
return getattr(self, 'SKIP_CREATE_FIELDS', [])
|
||||
|
||||
def save(self, **kwargs):
|
||||
"""Catch any django ValidationError thrown at the moment `save` is called, and re-throw as a DRF ValidationError."""
|
||||
|
|
@ -921,3 +921,104 @@ class ContentTypeField(serializers.ChoiceField):
|
|||
)
|
||||
|
||||
return content_type
|
||||
|
||||
|
||||
class DuplicateOptionsSerializer(serializers.Serializer):
|
||||
"""Generic serializer for specifying copy options when duplicating a model instance.
|
||||
|
||||
Builds its fields dynamically at instantiation time so the same class can be
|
||||
reused for any model without subclassing.
|
||||
"""
|
||||
|
||||
# Special 'shortcut' fields which are used for multiple models
|
||||
DEFAULT_FIELDS = [
|
||||
(
|
||||
'copy_parameters',
|
||||
_('Copy Parameters'),
|
||||
_('Copy parameters from the original item'),
|
||||
False,
|
||||
),
|
||||
(
|
||||
'copy_lines',
|
||||
_('Copy Lines'),
|
||||
_('Copy line items from the original order'),
|
||||
False,
|
||||
),
|
||||
(
|
||||
'copy_extra_lines',
|
||||
_('Copy Extra Lines'),
|
||||
_('Copy extra line items from the original order'),
|
||||
False,
|
||||
),
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
queryset: QuerySet,
|
||||
*args,
|
||||
copy_fields: Optional[list[dict]] = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""Initialise the serializer and dynamically attach fields.
|
||||
|
||||
Arguments:
|
||||
queryset: Queryset used for the `original` PrimaryKeyRelatedField.
|
||||
copy_fields: Optional list of dicts, each describing one boolean copy toggle.
|
||||
Keys:
|
||||
name: (str, required)
|
||||
label: (str, optional)
|
||||
help_text: (str, optional)
|
||||
default: (bool, optional, default True)
|
||||
"""
|
||||
# Enforce certain properties onto this serializer
|
||||
kwargs['label'] = kwargs.get('label', _('Duplication Options'))
|
||||
kwargs['help_text'] = kwargs.get(
|
||||
'help_text', _('Specify options for duplicating this item')
|
||||
)
|
||||
kwargs['required'] = False
|
||||
kwargs['write_only'] = True
|
||||
|
||||
copy_fields = copy_fields or []
|
||||
copy_field_names = [spec['name'] for spec in copy_fields]
|
||||
|
||||
# Apply "default" fields
|
||||
for name, label, help_text, default_value in self.DEFAULT_FIELDS:
|
||||
popped_value = kwargs.pop(name, default_value)
|
||||
|
||||
if name in copy_field_names:
|
||||
# Manually supplied field, continue
|
||||
continue
|
||||
|
||||
if popped_value:
|
||||
copy_fields.append({
|
||||
'name': name,
|
||||
'label': label,
|
||||
'help_text': help_text,
|
||||
'default': True,
|
||||
})
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Re-class the instance with a model-specific subclass,
|
||||
# so that each model generates a unique schema component name
|
||||
if self.__class__ is DuplicateOptionsSerializer:
|
||||
self.__class__ = type(
|
||||
f'{queryset.model.__name__}DuplicateOptionsSerializer',
|
||||
(DuplicateOptionsSerializer,),
|
||||
{},
|
||||
)
|
||||
|
||||
self.fields['original'] = serializers.PrimaryKeyRelatedField(
|
||||
queryset=queryset,
|
||||
required=True,
|
||||
label=_('Original'),
|
||||
help_text=_('Select instance to duplicate'),
|
||||
)
|
||||
|
||||
for spec in copy_fields or []:
|
||||
self.fields[spec['name']] = serializers.BooleanField(
|
||||
required=False,
|
||||
default=spec.get('default', True),
|
||||
label=spec.get('label', spec['name']),
|
||||
help_text=spec.get('help_text', ''),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -37,10 +37,7 @@ from build.validators import (
|
|||
validate_build_order_reference,
|
||||
)
|
||||
from common.models import ProjectCode
|
||||
from common.settings import (
|
||||
get_global_setting,
|
||||
prevent_build_output_complete_on_incompleted_tests,
|
||||
)
|
||||
from common.settings import get_global_setting
|
||||
from generic.enums import StringEnum
|
||||
from generic.states import StateTransitionMixin, StatusCodeMixin
|
||||
from plugin.events import trigger_event
|
||||
|
|
@ -1093,6 +1090,61 @@ class Build(
|
|||
},
|
||||
)
|
||||
|
||||
def can_complete_output(
|
||||
self,
|
||||
output: stock.models.StockItem,
|
||||
quantity: Optional[decimal.Decimal] = None,
|
||||
required_tests=None,
|
||||
) -> bool:
|
||||
"""Determine if the given build output can be completed.
|
||||
|
||||
Arguments:
|
||||
output: The StockItem instance (build output) to check
|
||||
quantity: The quantity to complete (defaults to entire output quantity)
|
||||
required_tests: Optional list of required tests to check against (defaults to the part's required tests)
|
||||
|
||||
Returns:
|
||||
True if the build output can be completed, False otherwise
|
||||
|
||||
Raises:
|
||||
ValidationError: If the build output cannot be completed, with an appropriate message
|
||||
"""
|
||||
prevent_incomplete = get_global_setting(
|
||||
'PREVENT_BUILD_COMPLETION_HAVING_INCOMPLETED_TESTS'
|
||||
)
|
||||
|
||||
if prevent_incomplete and not output.passedAllRequiredTests(
|
||||
required_tests=required_tests
|
||||
):
|
||||
raise ValidationError(_('Build output has not passed all required tests'))
|
||||
|
||||
# Ensure that none of the allocated items are themselves still "in production"
|
||||
allocated_items = output.items_to_install.all().filter(
|
||||
stock_item__is_building=True
|
||||
)
|
||||
|
||||
if allocated_items.exists():
|
||||
raise ValidationError(_('Allocated stock items are still in production'))
|
||||
|
||||
if quantity is not None and quantity != output.quantity:
|
||||
# Cannot split a build output with allocated items
|
||||
if output.items_to_install.exists():
|
||||
raise ValidationError({
|
||||
'quantity': _(
|
||||
'Cannot partially complete a build output with allocated items'
|
||||
)
|
||||
})
|
||||
|
||||
if quantity <= 0:
|
||||
raise ValidationError({
|
||||
'quantity': _('Quantity must be greater than zero')
|
||||
})
|
||||
|
||||
if quantity > output.quantity:
|
||||
raise ValidationError({
|
||||
'quantity': _('Quantity cannot be greater than the output quantity')
|
||||
})
|
||||
|
||||
@transaction.atomic
|
||||
def complete_build_output(
|
||||
self,
|
||||
|
|
@ -1118,52 +1170,20 @@ class Build(
|
|||
notes = kwargs.get('notes', '')
|
||||
|
||||
required_tests = kwargs.get('required_tests', output.part.getRequiredTests())
|
||||
prevent_on_incomplete = kwargs.get(
|
||||
'prevent_on_incomplete',
|
||||
prevent_build_output_complete_on_incompleted_tests(),
|
||||
|
||||
self.can_complete_output(
|
||||
output, quantity=quantity, required_tests=required_tests
|
||||
)
|
||||
|
||||
if prevent_on_incomplete and not output.passedAllRequiredTests(
|
||||
required_tests=required_tests
|
||||
):
|
||||
msg = _('Build output has not passed all required tests')
|
||||
|
||||
if serial := output.serial:
|
||||
msg = _(f'Build output {serial} has not passed all required tests')
|
||||
|
||||
raise ValidationError(msg)
|
||||
|
||||
# List the allocated BuildItem objects for the given output
|
||||
allocated_items = output.items_to_install.all()
|
||||
|
||||
# Ensure that none of the allocated items are themselves still "in production"
|
||||
for build_item in allocated_items:
|
||||
if build_item.stock_item.is_building:
|
||||
raise ValidationError(
|
||||
_('Allocated stock items are still in production')
|
||||
)
|
||||
|
||||
# If a partial quantity is provided, split the stock output
|
||||
if quantity is not None and quantity != output.quantity:
|
||||
# Cannot split a build output with allocated items
|
||||
if allocated_items.count() > 0:
|
||||
raise ValidationError(
|
||||
_('Cannot partially complete a build output with allocated items')
|
||||
)
|
||||
|
||||
if quantity <= 0:
|
||||
raise ValidationError({
|
||||
'quantity': _('Quantity must be greater than zero')
|
||||
})
|
||||
|
||||
if quantity > output.quantity:
|
||||
raise ValidationError({
|
||||
'quantity': _('Quantity cannot be greater than the output quantity')
|
||||
})
|
||||
|
||||
# Split the stock item
|
||||
output = output.splitStock(quantity, user=user, allow_production=True)
|
||||
|
||||
allocated_items = output.items_to_install.all().select_related(
|
||||
'stock_item', 'stock_item__part'
|
||||
)
|
||||
|
||||
for build_item in allocated_items:
|
||||
# Complete the allocation of stock for that item
|
||||
build_item.complete_allocation(user=user)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
"""JSON serializers for Build API."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||
from django.db import models, transaction
|
||||
|
|
@ -22,7 +24,6 @@ from rest_framework import serializers
|
|||
from rest_framework.serializers import ValidationError
|
||||
|
||||
import common.filters
|
||||
import common.settings
|
||||
import company.serializers
|
||||
import InvenTree.helpers
|
||||
import part.filters
|
||||
|
|
@ -33,6 +34,7 @@ from generic.states.fields import InvenTreeCustomStatusSerializerMixin
|
|||
from InvenTree.mixins import DataImportExportSerializerMixin
|
||||
from InvenTree.serializers import (
|
||||
CustomStatusSerializerMixin,
|
||||
DuplicateOptionsSerializer,
|
||||
FilterableSerializerMixin,
|
||||
InvenTreeDecimalField,
|
||||
InvenTreeModelSerializer,
|
||||
|
|
@ -52,6 +54,7 @@ from users.serializers import OwnerSerializer, UserSerializer
|
|||
|
||||
from .models import Build, BuildItem, BuildLine
|
||||
from .status_codes import BuildStatus
|
||||
from .validators import check_build_output
|
||||
|
||||
|
||||
class BuildSerializer(
|
||||
|
|
@ -65,6 +68,8 @@ class BuildSerializer(
|
|||
):
|
||||
"""Serializes a Build object."""
|
||||
|
||||
SKIP_CREATE_FIELDS = ['duplicate']
|
||||
|
||||
class Meta:
|
||||
"""Serializer metaclass."""
|
||||
|
||||
|
|
@ -78,6 +83,7 @@ class BuildSerializer(
|
|||
'completed',
|
||||
'completion_date',
|
||||
'destination',
|
||||
'duplicate',
|
||||
'external',
|
||||
'parent',
|
||||
'part',
|
||||
|
|
@ -188,12 +194,29 @@ class BuildSerializer(
|
|||
|
||||
return queryset
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(Build.objects.all(), copy_parameters=True)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Determine if extra serializer fields are required."""
|
||||
kwargs.pop('create', False)
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@transaction.atomic
|
||||
def create(self, validated_data):
|
||||
"""Create a new Build instance, optionally copying data from an existing build."""
|
||||
duplicate = validated_data.pop('duplicate', None)
|
||||
|
||||
instance = super().create(validated_data)
|
||||
|
||||
if duplicate:
|
||||
original = duplicate['original']
|
||||
|
||||
if duplicate.get('copy_parameters', True):
|
||||
instance.copy_parameters_from(original)
|
||||
|
||||
return instance
|
||||
|
||||
def validate_reference(self, reference):
|
||||
"""Custom validation for the Build reference field."""
|
||||
# Ensure the reference matches the required pattern
|
||||
|
|
@ -260,11 +283,19 @@ class BuildOutputSerializer(serializers.Serializer):
|
|||
class BuildOutputQuantitySerializer(BuildOutputSerializer):
|
||||
"""Build output with quantity field."""
|
||||
|
||||
# Optional callable to validate the output field, if required
|
||||
output_validator: Optional[Callable] = None
|
||||
|
||||
class Meta:
|
||||
"""Serializer metaclass."""
|
||||
|
||||
fields = [*BuildOutputSerializer.Meta.fields, 'quantity']
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize the serializer."""
|
||||
self.output_validator = kwargs.pop('output_validator', None)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
quantity = serializers.DecimalField(
|
||||
max_digits=15,
|
||||
decimal_places=5,
|
||||
|
|
@ -292,6 +323,10 @@ class BuildOutputQuantitySerializer(BuildOutputSerializer):
|
|||
'quantity': _('Quantity cannot be greater than the output quantity')
|
||||
})
|
||||
|
||||
if self.output_validator:
|
||||
# Call the parent serializer's output validator, if provided
|
||||
self.output_validator(output, quantity=quantity)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
|
|
@ -527,7 +562,9 @@ class BuildOutputCompleteSerializer(serializers.Serializer):
|
|||
'notes',
|
||||
]
|
||||
|
||||
outputs = BuildOutputQuantitySerializer(many=True, required=True)
|
||||
outputs = BuildOutputQuantitySerializer(
|
||||
many=True, required=True, output_validator=check_build_output
|
||||
)
|
||||
|
||||
location = serializers.PrimaryKeyRelatedField(
|
||||
queryset=StockLocation.objects.all(),
|
||||
|
|
@ -554,30 +591,6 @@ class BuildOutputCompleteSerializer(serializers.Serializer):
|
|||
|
||||
outputs = data.get('outputs', [])
|
||||
|
||||
if common.settings.prevent_build_output_complete_on_incompleted_tests():
|
||||
errors = []
|
||||
for output in outputs:
|
||||
stock_item = output['output']
|
||||
if (
|
||||
stock_item.hasRequiredTests()
|
||||
and not stock_item.passedAllRequiredTests()
|
||||
):
|
||||
serial = stock_item.serial
|
||||
|
||||
if serial:
|
||||
errors.append(
|
||||
_(
|
||||
f'Build output {serial} has not passed all required tests'
|
||||
)
|
||||
)
|
||||
else:
|
||||
errors.append(
|
||||
_('Build output has not passed all required tests')
|
||||
)
|
||||
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
if len(outputs) == 0:
|
||||
raise ValidationError(_('A list of build outputs must be provided'))
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ from build.models import Build, BuildItem, BuildLine
|
|||
from build.status_codes import BuildStatus
|
||||
from common.settings import set_global_setting
|
||||
from InvenTree.unit_test import InvenTreeAPITestCase
|
||||
from part.models import BomItem, BomItemSubstitute, Part
|
||||
from part.models import BomItem, BomItemSubstitute, Part, PartTestTemplate
|
||||
from stock.models import StockItem, StockLocation, StockSortOrder
|
||||
from stock.status_codes import StockStatus
|
||||
|
||||
|
|
@ -1531,10 +1531,15 @@ class BuildOutputScrapTest(BuildAPITest):
|
|||
'notes': 'Partial complete',
|
||||
}
|
||||
|
||||
# Ensure that an invalid quantity raises an error
|
||||
for q in [-4, 0, 999]:
|
||||
# Ensure that an invalid quantity raises an error, with the expected message
|
||||
for q, expected_message in [
|
||||
(-4, 'Ensure this value is greater than or equal to 0'),
|
||||
(0, 'Quantity must be greater than zero'),
|
||||
(999, 'Quantity cannot be greater than the output quantity'),
|
||||
]:
|
||||
data['outputs'][0]['quantity'] = q
|
||||
self.post(url, data, expected_code=400)
|
||||
response = self.post(url, data, expected_code=400)
|
||||
self.assertIn(expected_message, str(response.data))
|
||||
|
||||
# Partially complete the output (with a valid quantity)
|
||||
data['outputs'][0]['quantity'] = 4
|
||||
|
|
@ -1552,6 +1557,94 @@ class BuildOutputScrapTest(BuildAPITest):
|
|||
self.assertEqual(completed_output.status, StockStatus.OK)
|
||||
self.assertFalse(completed_output.is_building)
|
||||
|
||||
def test_complete_with_required_tests(self):
|
||||
"""Test that build output completion is blocked if required tests have not passed."""
|
||||
build = Build.objects.get(pk=1)
|
||||
output = build.create_build_output(1).first()
|
||||
|
||||
template = PartTestTemplate.objects.create(
|
||||
part=build.part, test_name='Required test', required=True
|
||||
)
|
||||
|
||||
set_global_setting(
|
||||
'PREVENT_BUILD_COMPLETION_HAVING_INCOMPLETED_TESTS', True, change_user=None
|
||||
)
|
||||
|
||||
url = reverse('api-build-output-complete', kwargs={'pk': build.pk})
|
||||
|
||||
data = {'outputs': [{'output': output.pk}], 'location': 1}
|
||||
|
||||
response = self.post(url, data, expected_code=400)
|
||||
|
||||
self.assertIn(
|
||||
'Build output has not passed all required tests', str(response.data)
|
||||
)
|
||||
|
||||
# Add a passing test result - the output should now be able to be completed
|
||||
output.add_test_result(template=template, result=True)
|
||||
|
||||
self.post(url, data, expected_code=200)
|
||||
|
||||
def test_complete_still_in_production(self):
|
||||
"""Test that build output completion is blocked if an allocated item is still in production."""
|
||||
build = Build.objects.get(pk=1)
|
||||
output = build.create_build_output(1).first()
|
||||
|
||||
build.create_build_line_items()
|
||||
line = build.build_lines.first()
|
||||
|
||||
sub_build = Build.objects.create(
|
||||
part=line.bom_item.sub_part,
|
||||
quantity=1,
|
||||
title='Sub-build',
|
||||
reference='BO-9998',
|
||||
)
|
||||
|
||||
in_production = StockItem.objects.create(
|
||||
part=line.bom_item.sub_part, quantity=1, is_building=True, build=sub_build
|
||||
)
|
||||
|
||||
BuildItem.objects.create(
|
||||
build_line=line, stock_item=in_production, quantity=1, install_into=output
|
||||
)
|
||||
|
||||
url = reverse('api-build-output-complete', kwargs={'pk': build.pk})
|
||||
|
||||
response = self.post(
|
||||
url, {'outputs': [{'output': output.pk}], 'location': 1}, expected_code=400
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
'Allocated stock items are still in production', str(response.data)
|
||||
)
|
||||
|
||||
def test_partial_complete_with_allocated_items(self):
|
||||
"""Test that a build output with allocated items cannot be partially completed."""
|
||||
build = Build.objects.get(pk=1)
|
||||
output = build.create_build_output(10).first()
|
||||
|
||||
build.create_build_line_items()
|
||||
line = build.build_lines.first()
|
||||
|
||||
stock_item = StockItem.objects.create(part=line.bom_item.sub_part, quantity=10)
|
||||
|
||||
BuildItem.objects.create(
|
||||
build_line=line, stock_item=stock_item, quantity=1, install_into=output
|
||||
)
|
||||
|
||||
url = reverse('api-build-output-complete', kwargs={'pk': build.pk})
|
||||
|
||||
response = self.post(
|
||||
url,
|
||||
{'outputs': [{'output': output.pk, 'quantity': 4}], 'location': 1},
|
||||
expected_code=400,
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
'Cannot partially complete a build output with allocated items',
|
||||
str(response.data),
|
||||
)
|
||||
|
||||
|
||||
class BuildOutputCancelTest(BuildAPITest):
|
||||
"""Test cancellation of build outputs."""
|
||||
|
|
|
|||
|
|
@ -650,11 +650,15 @@ class BuildTest(BuildTestBase):
|
|||
'PREVENT_BUILD_COMPLETION_HAVING_INCOMPLETED_TESTS', True, change_user=None
|
||||
)
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
with self.assertRaises(ValidationError) as exc:
|
||||
self.build_w_tests_trackable.complete_build_output(
|
||||
self.stockitem_with_required_test, None
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
'Build output has not passed all required tests', str(exc.exception)
|
||||
)
|
||||
|
||||
# let's complete the required test and see if it could be saved
|
||||
StockItemTestResult.objects.create(
|
||||
stock_item=self.stockitem_with_required_test,
|
||||
|
|
@ -671,6 +675,59 @@ class BuildTest(BuildTestBase):
|
|||
self.stockitem_wo_required_test, None
|
||||
)
|
||||
|
||||
def test_complete_output_still_in_production(self):
|
||||
"""Test that a build output cannot be completed if allocated stock is still in production."""
|
||||
# Create a stock item of the tracked sub-part, which is itself still "in production"
|
||||
sub_build = Build.objects.create(
|
||||
reference=generate_next_build_reference(),
|
||||
title='Building a sub-part',
|
||||
part=self.sub_part_3,
|
||||
quantity=2,
|
||||
issued_by=get_user_model().objects.get(pk=1),
|
||||
)
|
||||
|
||||
in_production = StockItem.objects.create(
|
||||
part=self.sub_part_3, quantity=2, is_building=True, build=sub_build
|
||||
)
|
||||
|
||||
self.allocate_stock(self.output_1, {in_production: 2})
|
||||
|
||||
with self.assertRaises(ValidationError) as exc:
|
||||
self.build.complete_build_output(self.output_1, None)
|
||||
|
||||
self.assertIn(
|
||||
'Allocated stock items are still in production', str(exc.exception)
|
||||
)
|
||||
|
||||
def test_partial_complete_with_allocated_items(self):
|
||||
"""Test that a build output with tracked allocations cannot be partially completed."""
|
||||
# Allocate tracked stock against output_1 (quantity=3)
|
||||
self.allocate_stock(self.output_1, {self.stock_3_1: 6})
|
||||
|
||||
with self.assertRaises(ValidationError) as exc:
|
||||
self.build.complete_build_output(self.output_1, None, quantity=1)
|
||||
|
||||
self.assertIn(
|
||||
'Cannot partially complete a build output with allocated items',
|
||||
str(exc.exception),
|
||||
)
|
||||
|
||||
def test_complete_output_invalid_quantity(self):
|
||||
"""Test that invalid quantities are rejected when completing a build output directly."""
|
||||
with self.assertRaises(ValidationError) as exc:
|
||||
self.build.complete_build_output(self.output_1, None, quantity=0)
|
||||
|
||||
self.assertIn('Quantity must be greater than zero', str(exc.exception))
|
||||
|
||||
with self.assertRaises(ValidationError) as exc:
|
||||
self.build.complete_build_output(
|
||||
self.output_1, None, quantity=self.output_1.quantity + 1
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
'Quantity cannot be greater than the output quantity', str(exc.exception)
|
||||
)
|
||||
|
||||
def test_overdue_notification(self):
|
||||
"""Test sending of notifications when a build order is overdue."""
|
||||
self.ensurePluginsLoaded()
|
||||
|
|
|
|||
|
|
@ -21,3 +21,13 @@ def validate_build_order_reference(value):
|
|||
|
||||
# If we get to here, run the "default" validation routine
|
||||
Build.validate_reference_field(value)
|
||||
|
||||
|
||||
def check_build_output(output, quantity=None):
|
||||
"""Run a validation check against each output before accepting it for completion.
|
||||
|
||||
Arguments:
|
||||
output (StockItem): The build output to check
|
||||
quantity (Decimal, optional): The quantity to complete. If None, the full output quantity is assumed.
|
||||
"""
|
||||
output.build.can_complete_output(output, quantity=quantity)
|
||||
|
|
|
|||
|
|
@ -142,12 +142,3 @@ def stock_expiry_enabled():
|
|||
from common.models import InvenTreeSetting
|
||||
|
||||
return InvenTreeSetting.get_setting('STOCK_ENABLE_EXPIRY', False, create=False)
|
||||
|
||||
|
||||
def prevent_build_output_complete_on_incompleted_tests():
|
||||
"""Returns True if the completion of the build outputs is disabled until the required tests are passed."""
|
||||
from common.models import InvenTreeSetting
|
||||
|
||||
return InvenTreeSetting.get_setting(
|
||||
'PREVENT_BUILD_COMPLETION_HAVING_INCOMPLETED_TESTS', False, create=False
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
"""JSON serializers for Company app."""
|
||||
|
||||
from django.db import transaction
|
||||
from django.db.models import Prefetch
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
|
@ -14,6 +15,7 @@ from importer.registry import register_importer
|
|||
from InvenTree.mixins import DataImportExportSerializerMixin
|
||||
from InvenTree.ready import isGeneratingSchema
|
||||
from InvenTree.serializers import (
|
||||
DuplicateOptionsSerializer,
|
||||
FilterableSerializerMixin,
|
||||
InvenTreeCurrencySerializer,
|
||||
InvenTreeDecimalField,
|
||||
|
|
@ -118,6 +120,8 @@ class CompanySerializer(
|
|||
|
||||
import_exclude_fields = ['image']
|
||||
|
||||
SKIP_CREATE_FIELDS = ['duplicate']
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
|
|
@ -132,6 +136,7 @@ class CompanySerializer(
|
|||
'email',
|
||||
'currency',
|
||||
'contact',
|
||||
'duplicate',
|
||||
'link',
|
||||
'image',
|
||||
'active',
|
||||
|
|
@ -191,6 +196,23 @@ class CompanySerializer(
|
|||
|
||||
parameters = common.filters.enable_parameters_filter()
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(Company.objects.all(), copy_parameters=True)
|
||||
|
||||
@transaction.atomic
|
||||
def create(self, validated_data):
|
||||
"""Create a new Company instance, optionally copying data from an existing company."""
|
||||
duplicate = validated_data.pop('duplicate', None)
|
||||
|
||||
instance = super().create(validated_data)
|
||||
|
||||
if duplicate:
|
||||
original = duplicate['original']
|
||||
|
||||
if duplicate.get('copy_parameters', True):
|
||||
instance.copy_parameters_from(original)
|
||||
|
||||
return instance
|
||||
|
||||
|
||||
@register_importer()
|
||||
class ContactSerializer(DataImportExportSerializerMixin, InvenTreeModelSerializer):
|
||||
|
|
@ -217,6 +239,8 @@ class ManufacturerPartSerializer(
|
|||
):
|
||||
"""Serializer for ManufacturerPart object."""
|
||||
|
||||
SKIP_CREATE_FIELDS = ['duplicate']
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
|
|
@ -229,6 +253,7 @@ class ManufacturerPartSerializer(
|
|||
'manufacturer',
|
||||
'manufacturer_detail',
|
||||
'description',
|
||||
'duplicate',
|
||||
'MPN',
|
||||
'link',
|
||||
'barcode_hash',
|
||||
|
|
@ -241,6 +266,25 @@ class ManufacturerPartSerializer(
|
|||
|
||||
parameters = common.filters.enable_parameters_filter()
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
ManufacturerPart.objects.all(), copy_parameters=True
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
def create(self, validated_data):
|
||||
"""Create a new ManufacturerPart instance, optionally copying data from an existing instance."""
|
||||
duplicate = validated_data.pop('duplicate', None)
|
||||
|
||||
instance = super().create(validated_data)
|
||||
|
||||
if duplicate:
|
||||
original = duplicate['original']
|
||||
|
||||
if duplicate.get('copy_parameters', True):
|
||||
instance.copy_parameters_from(original)
|
||||
|
||||
return instance
|
||||
|
||||
part_detail = OptionalField(
|
||||
serializer_class=part_serializers.PartBriefSerializer,
|
||||
serializer_kwargs={
|
||||
|
|
@ -323,6 +367,8 @@ class SupplierPartSerializer(
|
|||
|
||||
export_exclude_fields = ['tags']
|
||||
|
||||
SKIP_CREATE_FIELDS = ['duplicate']
|
||||
|
||||
export_child_fields = [
|
||||
'part_detail.name',
|
||||
'part_detail.description',
|
||||
|
|
@ -339,6 +385,7 @@ class SupplierPartSerializer(
|
|||
'available',
|
||||
'availability_updated',
|
||||
'description',
|
||||
'duplicate',
|
||||
'in_stock',
|
||||
'on_order',
|
||||
'link',
|
||||
|
|
@ -494,6 +541,10 @@ class SupplierPartSerializer(
|
|||
# Date fields
|
||||
updated = serializers.DateTimeField(allow_null=True, read_only=True)
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
SupplierPart.objects.all(), copy_parameters=True
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def annotate_queryset(queryset):
|
||||
"""Annotate the SupplierPart queryset with extra fields.
|
||||
|
|
@ -522,8 +573,11 @@ class SupplierPartSerializer(
|
|||
|
||||
return response
|
||||
|
||||
@transaction.atomic
|
||||
def create(self, validated_data):
|
||||
"""Extract manufacturer data and process ManufacturerPart."""
|
||||
duplicate = validated_data.pop('duplicate', None)
|
||||
|
||||
# Extract 'available' quantity from the serializer
|
||||
available = validated_data.pop('available', None)
|
||||
|
||||
|
|
@ -541,6 +595,12 @@ class SupplierPartSerializer(
|
|||
kwargs = {'manufacturer': manufacturer, 'MPN': MPN}
|
||||
supplier_part.save(**kwargs)
|
||||
|
||||
if duplicate:
|
||||
original = duplicate['original']
|
||||
|
||||
if duplicate.get('copy_parameters', True):
|
||||
supplier_part.copy_parameters_from(original)
|
||||
|
||||
return supplier_part
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ from taggit.serializers import TagListSerializerField
|
|||
import data_exporter.serializers
|
||||
import data_exporter.tasks
|
||||
import InvenTree.exceptions
|
||||
import InvenTree.serializers
|
||||
from common.models import DataOutput
|
||||
from InvenTree.helpers import str2bool
|
||||
from InvenTree.tasks import offload_task
|
||||
|
|
@ -64,6 +65,14 @@ class DataExportSerializerMixin:
|
|||
# Exclude fields which are not required for data export
|
||||
for field in self.get_export_exclude_fields(**kwargs):
|
||||
self.fields.pop(field, None)
|
||||
|
||||
# Duplication options are never used for data export
|
||||
for field in [
|
||||
name
|
||||
for name, field in self.fields.items()
|
||||
if isinstance(field, InvenTree.serializers.DuplicateOptionsSerializer)
|
||||
]:
|
||||
self.fields.pop(field, None)
|
||||
else:
|
||||
# Exclude fields which are only used for data export
|
||||
for field in self.get_export_only_fields(**kwargs):
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
from rest_framework import fields, serializers
|
||||
from taggit.serializers import TagListSerializerField
|
||||
|
||||
import InvenTree.serializers
|
||||
|
||||
|
||||
class DataImportSerializerMixin:
|
||||
"""Mixin class for adding data import functionality to a DRF serializer."""
|
||||
|
|
@ -41,6 +43,14 @@ class DataImportSerializerMixin:
|
|||
for field in self.get_import_exclude_fields(**kwargs):
|
||||
self.fields.pop(field, None)
|
||||
|
||||
# Duplication options are never used for data import
|
||||
for field in [
|
||||
name
|
||||
for name, field in self.fields.items()
|
||||
if isinstance(field, InvenTree.serializers.DuplicateOptionsSerializer)
|
||||
]:
|
||||
self.fields.pop(field, None)
|
||||
|
||||
else:
|
||||
# Exclude fields which are only used for data import
|
||||
for field in self.get_import_only_fields(**kwargs):
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -32,6 +32,7 @@ from InvenTree.helpers import extract_serial_numbers, hash_barcode, normalize, s
|
|||
from InvenTree.mixins import DataImportExportSerializerMixin
|
||||
from InvenTree.serializers import (
|
||||
CustomStatusSerializerMixin,
|
||||
DuplicateOptionsSerializer,
|
||||
FilterableSerializerMixin,
|
||||
InvenTreeCurrencySerializer,
|
||||
InvenTreeDecimalField,
|
||||
|
|
@ -67,40 +68,6 @@ class TotalPriceMixin(serializers.Serializer):
|
|||
)
|
||||
|
||||
|
||||
class DuplicateOrderSerializer(serializers.Serializer):
|
||||
"""Serializer for specifying options when duplicating an order."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
fields = ['order_id', 'copy_lines', 'copy_extra_lines', 'copy_parameters']
|
||||
|
||||
order_id = serializers.IntegerField(
|
||||
required=True, label=_('Order ID'), help_text=_('ID of the order to duplicate')
|
||||
)
|
||||
|
||||
copy_lines = serializers.BooleanField(
|
||||
required=False,
|
||||
default=True,
|
||||
label=_('Copy Lines'),
|
||||
help_text=_('Copy line items from the original order'),
|
||||
)
|
||||
|
||||
copy_extra_lines = serializers.BooleanField(
|
||||
required=False,
|
||||
default=True,
|
||||
label=_('Copy Extra Lines'),
|
||||
help_text=_('Copy extra line items from the original order'),
|
||||
)
|
||||
|
||||
copy_parameters = serializers.BooleanField(
|
||||
required=False,
|
||||
default=True,
|
||||
label=_('Copy Parameters'),
|
||||
help_text=_('Copy order parameters from the original order'),
|
||||
)
|
||||
|
||||
|
||||
class AbstractOrderSerializer(
|
||||
CustomStatusSerializerMixin,
|
||||
DataImportExportSerializerMixin,
|
||||
|
|
@ -110,9 +77,9 @@ class AbstractOrderSerializer(
|
|||
):
|
||||
"""Abstract serializer class which provides fields common to all order types."""
|
||||
|
||||
export_exclude_fields = ['notes', 'duplicate']
|
||||
export_exclude_fields = ['notes']
|
||||
|
||||
import_exclude_fields = ['notes', 'duplicate']
|
||||
import_exclude_fields = ['notes']
|
||||
|
||||
# Number of line items in this order
|
||||
line_items = serializers.IntegerField(
|
||||
|
|
@ -195,12 +162,8 @@ class AbstractOrderSerializer(
|
|||
|
||||
created_by = UserSerializer(read_only=True)
|
||||
|
||||
duplicate = DuplicateOrderSerializer(
|
||||
label=_('Duplicate Order'),
|
||||
help_text=_('Specify options for duplicating this order'),
|
||||
required=False,
|
||||
write_only=True,
|
||||
)
|
||||
# Note: The 'duplicate' field must be defined by each concrete serializer class,
|
||||
# as it requires a queryset specific to the order model type
|
||||
|
||||
def validate_reference(self, reference):
|
||||
"""Custom validation for the reference field."""
|
||||
|
|
@ -293,30 +256,21 @@ class AbstractOrderSerializer(
|
|||
instance = super().create(validated_data)
|
||||
|
||||
if duplicate:
|
||||
order_id = duplicate.get('order_id', None)
|
||||
copy_lines = duplicate.get('copy_lines', True)
|
||||
copy_extra_lines = duplicate.get('copy_extra_lines', True)
|
||||
copy_parameters = duplicate.get('copy_parameters', True)
|
||||
original = duplicate['original']
|
||||
|
||||
try:
|
||||
copy_from = instance.__class__.objects.get(pk=order_id)
|
||||
except Exception:
|
||||
# If the order ID is invalid, raise a validation error
|
||||
raise ValidationError(_('Invalid order ID'))
|
||||
|
||||
if copy_lines:
|
||||
for line in copy_from.lines.all():
|
||||
if duplicate.get('copy_lines', False):
|
||||
for line in original.lines.all():
|
||||
instance.clean_line_item(line)
|
||||
line.save()
|
||||
|
||||
if copy_extra_lines:
|
||||
for line in copy_from.extra_lines.all():
|
||||
if duplicate.get('copy_extra_lines', False):
|
||||
for line in original.extra_lines.all():
|
||||
line.pk = None
|
||||
line.order = instance
|
||||
line.save()
|
||||
|
||||
if copy_parameters:
|
||||
instance.copy_parameters_from(copy_from)
|
||||
if duplicate.get('copy_parameters', False):
|
||||
instance.copy_parameters_from(original)
|
||||
|
||||
return instance
|
||||
|
||||
|
|
@ -452,6 +406,13 @@ class PurchaseOrderSerializer(
|
|||
|
||||
return [*fields, 'duplicate']
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
order.models.PurchaseOrder.objects.all(),
|
||||
copy_lines=True,
|
||||
copy_extra_lines=True,
|
||||
copy_parameters=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def annotate_queryset(queryset):
|
||||
"""Add extra information to the queryset.
|
||||
|
|
@ -1134,6 +1095,13 @@ class SalesOrderSerializer(
|
|||
|
||||
return [*fields, 'duplicate']
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
order.models.SalesOrder.objects.all(),
|
||||
copy_lines=True,
|
||||
copy_extra_lines=True,
|
||||
copy_parameters=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def annotate_queryset(queryset):
|
||||
"""Add extra information to the queryset.
|
||||
|
|
@ -1411,6 +1379,8 @@ class SalesOrderShipmentSerializer(
|
|||
):
|
||||
"""Serializer for the SalesOrderShipment class."""
|
||||
|
||||
SKIP_CREATE_FIELDS = ['duplicate']
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
|
|
@ -1423,6 +1393,7 @@ class SalesOrderShipmentSerializer(
|
|||
'shipment_address',
|
||||
'delivery_date',
|
||||
'checked_by',
|
||||
'duplicate',
|
||||
'reference',
|
||||
'tracking_number',
|
||||
'invoice_number',
|
||||
|
|
@ -1507,6 +1478,25 @@ class SalesOrderShipmentSerializer(
|
|||
|
||||
tags = common.filters.enable_tags_filter()
|
||||
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
order.models.SalesOrderShipment.objects.all(), copy_parameters=True
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
def create(self, validated_data):
|
||||
"""Create a new SalesOrderShipment instance, optionally copying data from an existing shipment."""
|
||||
duplicate = validated_data.pop('duplicate', None)
|
||||
|
||||
instance = super().create(validated_data)
|
||||
|
||||
if duplicate:
|
||||
original = duplicate['original']
|
||||
|
||||
if duplicate.get('copy_parameters', True):
|
||||
instance.copy_parameters_from(original)
|
||||
|
||||
return instance
|
||||
|
||||
|
||||
class SalesOrderAllocationSerializer(
|
||||
FilterableSerializerMixin, InvenTreeModelSerializer
|
||||
|
|
@ -2198,6 +2188,14 @@ class ReturnOrderSerializer(
|
|||
|
||||
return [*fields, 'duplicate']
|
||||
|
||||
# Note: line items cannot be duplicated from a ReturnOrder,
|
||||
# as they are linked to specific stock items
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
order.models.ReturnOrder.objects.all(),
|
||||
copy_extra_lines=True,
|
||||
copy_parameters=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def annotate_queryset(queryset):
|
||||
"""Custom annotation for the serializer queryset."""
|
||||
|
|
@ -2485,6 +2483,11 @@ class TransferOrderSerializer(
|
|||
|
||||
return [*fields, 'duplicate']
|
||||
|
||||
# Note: TransferOrder does not have "extra" line items
|
||||
duplicate = DuplicateOptionsSerializer(
|
||||
order.models.TransferOrder.objects.all(), copy_lines=True, copy_parameters=True
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def annotate_queryset(queryset):
|
||||
"""Add extra information to the queryset.
|
||||
|
|
|
|||
|
|
@ -573,7 +573,7 @@ class PurchaseOrderTest(OrderTest):
|
|||
|
||||
# Duplicate with non-existent PK to provoke error
|
||||
data['duplicate'] = {
|
||||
'order_id': 10000001,
|
||||
'original': 10000001,
|
||||
'copy_lines': True,
|
||||
'copy_extra_lines': False,
|
||||
}
|
||||
|
|
@ -584,7 +584,7 @@ class PurchaseOrderTest(OrderTest):
|
|||
response = self.post(reverse('api-po-list'), data, expected_code=400)
|
||||
|
||||
data['duplicate'] = {
|
||||
'order_id': 1,
|
||||
'original': 1,
|
||||
'copy_lines': True,
|
||||
'copy_extra_lines': False,
|
||||
}
|
||||
|
|
@ -605,7 +605,7 @@ class PurchaseOrderTest(OrderTest):
|
|||
data['reference'] = 'PO-9998'
|
||||
|
||||
data['duplicate'] = {
|
||||
'order_id': 1,
|
||||
'original': 1,
|
||||
'copy_lines': False,
|
||||
'copy_extra_lines': True,
|
||||
}
|
||||
|
|
@ -1792,7 +1792,7 @@ class SalesOrderTest(OrderTest):
|
|||
{
|
||||
'reference': 'SO-12345',
|
||||
'customer': so.customer.pk,
|
||||
'duplicate': {'order_id': so.pk, 'copy_parameters': False},
|
||||
'duplicate': {'original': so.pk, 'copy_parameters': False},
|
||||
},
|
||||
)
|
||||
|
||||
|
|
@ -1809,7 +1809,7 @@ class SalesOrderTest(OrderTest):
|
|||
{
|
||||
'reference': 'SO-12346',
|
||||
'customer': so.customer.pk,
|
||||
'duplicate': {'order_id': so.pk},
|
||||
'duplicate': {'original': so.pk},
|
||||
},
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -407,67 +407,6 @@ class PartBriefSerializer(
|
|||
)
|
||||
|
||||
|
||||
class DuplicatePartSerializer(serializers.Serializer):
|
||||
"""Serializer for specifying options when duplicating a Part.
|
||||
|
||||
The fields in this serializer control how the Part is duplicated.
|
||||
"""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
fields = [
|
||||
'part',
|
||||
'copy_image',
|
||||
'copy_bom',
|
||||
'copy_parameters',
|
||||
'copy_notes',
|
||||
'copy_tests',
|
||||
]
|
||||
|
||||
part = serializers.PrimaryKeyRelatedField(
|
||||
queryset=Part.objects.all(),
|
||||
label=_('Original Part'),
|
||||
help_text=_('Select original part to duplicate'),
|
||||
required=True,
|
||||
)
|
||||
|
||||
copy_image = serializers.BooleanField(
|
||||
label=_('Copy Image'),
|
||||
help_text=_('Copy image from original part'),
|
||||
required=False,
|
||||
default=False,
|
||||
)
|
||||
|
||||
copy_bom = serializers.BooleanField(
|
||||
label=_('Copy BOM'),
|
||||
help_text=_('Copy bill of materials from original part'),
|
||||
required=False,
|
||||
default=False,
|
||||
)
|
||||
|
||||
copy_parameters = serializers.BooleanField(
|
||||
label=_('Copy Parameters'),
|
||||
help_text=_('Copy parameter data from original part'),
|
||||
required=False,
|
||||
default=False,
|
||||
)
|
||||
|
||||
copy_notes = serializers.BooleanField(
|
||||
label=_('Copy Notes'),
|
||||
help_text=_('Copy notes from original part'),
|
||||
required=False,
|
||||
default=True,
|
||||
)
|
||||
|
||||
copy_tests = serializers.BooleanField(
|
||||
label=_('Copy Tests'),
|
||||
help_text=_('Copy test templates from original part'),
|
||||
required=False,
|
||||
default=False,
|
||||
)
|
||||
|
||||
|
||||
class InitialStockSerializer(serializers.Serializer):
|
||||
"""Serializer for creating initial stock quantity."""
|
||||
|
||||
|
|
@ -601,7 +540,7 @@ class PartSerializer(
|
|||
Used when displaying all details of a single component.
|
||||
"""
|
||||
|
||||
import_exclude_fields = ['creation_date', 'creation_user', 'duplicate']
|
||||
import_exclude_fields = ['creation_date', 'creation_user']
|
||||
|
||||
class Meta:
|
||||
"""Metaclass defining serializer fields."""
|
||||
|
|
@ -1007,11 +946,37 @@ class PartSerializer(
|
|||
)
|
||||
|
||||
# Extra fields used only for creation of a new Part instance
|
||||
duplicate = DuplicatePartSerializer(
|
||||
duplicate = InvenTree.serializers.DuplicateOptionsSerializer(
|
||||
Part.objects.all(),
|
||||
label=_('Duplicate Part'),
|
||||
help_text=_('Copy initial data from another Part'),
|
||||
write_only=True,
|
||||
required=False,
|
||||
copy_parameters=True,
|
||||
copy_fields=[
|
||||
{
|
||||
'name': 'copy_image',
|
||||
'label': _('Copy Image'),
|
||||
'help_text': _('Copy image from original part'),
|
||||
'default': False,
|
||||
},
|
||||
{
|
||||
'name': 'copy_bom',
|
||||
'label': _('Copy BOM'),
|
||||
'help_text': _('Copy bill of materials from original part'),
|
||||
'default': False,
|
||||
},
|
||||
{
|
||||
'name': 'copy_notes',
|
||||
'label': _('Copy Notes'),
|
||||
'help_text': _('Copy notes from original part'),
|
||||
'default': True,
|
||||
},
|
||||
{
|
||||
'name': 'copy_tests',
|
||||
'label': _('Copy Tests'),
|
||||
'help_text': _('Copy test templates from original part'),
|
||||
'default': False,
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
initial_stock = InitialStockSerializer(
|
||||
|
|
@ -1077,7 +1042,7 @@ class PartSerializer(
|
|||
|
||||
# Copy data from original Part
|
||||
if duplicate:
|
||||
original = duplicate['part']
|
||||
original = duplicate['original']
|
||||
|
||||
if duplicate.get('copy_bom', False):
|
||||
instance.copy_bom_from(original)
|
||||
|
|
|
|||
|
|
@ -1649,7 +1649,7 @@ class PartCreationTests(PartAPITestBase):
|
|||
'testable': do_copy,
|
||||
'assembly': do_copy,
|
||||
'duplicate': {
|
||||
'part': 100,
|
||||
'original': 100,
|
||||
'copy_bom': do_copy,
|
||||
'copy_notes': do_copy,
|
||||
'copy_image': do_copy,
|
||||
|
|
|
|||
|
|
@ -1770,7 +1770,7 @@ class StockCountSerializer(StockAdjustmentSerializer):
|
|||
fields = ['items', 'notes', 'location']
|
||||
|
||||
location = serializers.PrimaryKeyRelatedField(
|
||||
queryset=StockLocation.objects.filter(structural=False),
|
||||
queryset=StockLocation.objects.filter(),
|
||||
many=False,
|
||||
required=False,
|
||||
allow_null=True,
|
||||
|
|
@ -1778,6 +1778,15 @@ class StockCountSerializer(StockAdjustmentSerializer):
|
|||
help_text=_('Set stock location for counted items (optional)'),
|
||||
)
|
||||
|
||||
def validate_location(self, location):
|
||||
"""Validate the provided location."""
|
||||
if location and location.structural:
|
||||
raise ValidationError(
|
||||
_('Structural locations cannot be assigned stock items')
|
||||
)
|
||||
|
||||
return location
|
||||
|
||||
def save(self):
|
||||
"""Count stock."""
|
||||
request = self.context['request']
|
||||
|
|
@ -1874,7 +1883,7 @@ class StockTransferSerializer(StockAdjustmentSerializer):
|
|||
items = StockAdjustmentItemSerializer(many=True, require_non_zero=True)
|
||||
|
||||
location = serializers.PrimaryKeyRelatedField(
|
||||
queryset=StockLocation.objects.filter(structural=False),
|
||||
queryset=StockLocation.objects.filter(),
|
||||
many=False,
|
||||
required=True,
|
||||
allow_null=False,
|
||||
|
|
@ -1882,6 +1891,15 @@ class StockTransferSerializer(StockAdjustmentSerializer):
|
|||
help_text=_('Destination stock location'),
|
||||
)
|
||||
|
||||
def validate_location(self, location):
|
||||
"""Validate the provided location."""
|
||||
if location and location.structural:
|
||||
raise ValidationError(
|
||||
_('Structural locations cannot be assigned stock items')
|
||||
)
|
||||
|
||||
return location
|
||||
|
||||
def save(self):
|
||||
"""Transfer stock."""
|
||||
request = self.context['request']
|
||||
|
|
@ -1965,7 +1983,7 @@ class StockReturnSerializer(StockAdjustmentSerializer):
|
|||
)
|
||||
|
||||
location = serializers.PrimaryKeyRelatedField(
|
||||
queryset=StockLocation.objects.filter(structural=False),
|
||||
queryset=StockLocation.objects.filter(),
|
||||
many=False,
|
||||
required=True,
|
||||
allow_null=False,
|
||||
|
|
@ -1973,6 +1991,15 @@ class StockReturnSerializer(StockAdjustmentSerializer):
|
|||
help_text=_('Destination stock location'),
|
||||
)
|
||||
|
||||
def validate_location(self, location):
|
||||
"""Validate the provided location."""
|
||||
if location and location.structural:
|
||||
raise ValidationError(
|
||||
_('Structural locations cannot be assigned stock items')
|
||||
)
|
||||
|
||||
return location
|
||||
|
||||
merge = serializers.BooleanField(
|
||||
default=False,
|
||||
required=False,
|
||||
|
|
|
|||
|
|
@ -2435,7 +2435,10 @@ class StocktakeTest(StockAPITestCase):
|
|||
{'items': [{'pk': item_a.pk, 'quantity': 1}], 'location': structural.pk},
|
||||
expected_code=400,
|
||||
)
|
||||
self.assertIn('does not exist', str(response.data['location']))
|
||||
self.assertIn(
|
||||
'Structural locations cannot be assigned stock items',
|
||||
str(response.data['location']),
|
||||
)
|
||||
|
||||
|
||||
class StockTransferMergeTest(StockAPITestCase):
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ class TemplateTagTest(InvenTreeTestCase):
|
|||
|
||||
shipped_js = resp.split('<script type="module" src="')[1:]
|
||||
self.assertGreater(len(shipped_js), 0)
|
||||
self.assertGreater(len(shipped_js), 3)
|
||||
self.assertGreater(len(shipped_js), 2)
|
||||
|
||||
manifest_file = Path(__file__).parent.joinpath('static/web/.vite/manifest.json')
|
||||
# Try with removed manifest file
|
||||
|
|
|
|||
|
|
@ -57,4 +57,5 @@ export interface SettingsStateProps {
|
|||
pathParams?: PathParams;
|
||||
getSetting: (key: string, default_value?: string) => string; // Return a raw setting value
|
||||
isSet: (key: string, default_value?: boolean) => boolean; // Check a "boolean" setting
|
||||
getSettingLength: () => number;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -108,10 +108,10 @@
|
|||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.29.7",
|
||||
"@babel/preset-react": "^7.29.7",
|
||||
"@babel/preset-typescript": "^7.29.7",
|
||||
"@babel/runtime": "^7.29.7",
|
||||
"@babel/core": "^8.0.1",
|
||||
"@babel/preset-react": "^8.0.1",
|
||||
"@babel/preset-typescript": "^8.0.1",
|
||||
"@babel/runtime": "^8.0.0",
|
||||
"@codecov/vite-plugin": "^2.0.1",
|
||||
"@flakiness/playwright": "^1.13.0",
|
||||
"@lingui/babel-plugin-lingui-macro": "^5.9.5",
|
||||
|
|
@ -126,7 +126,7 @@
|
|||
"@types/react-router-dom": "^5.3.3",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"@vanilla-extract/vite-plugin": "^5.2.2",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"@vitejs/plugin-react": "^5",
|
||||
"babel-plugin-macros": "^3.1.0",
|
||||
"nyc": "^18.0.0",
|
||||
"otpauth": "^9.5.1",
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ export default defineConfig({
|
|||
INVENTREE_FRONTEND_API_HOST: 'http://localhost:8000',
|
||||
INVENTREE_CORS_ORIGIN_ALLOW_ALL: 'True',
|
||||
INVENTREE_COOKIE_SAMESITE: 'False',
|
||||
INVENTREE_LOGIN_ATTEMPTS: '100',
|
||||
INVENTREE_LOGIN_ATTEMPTS: '3',
|
||||
INVENTREE_PLUGINS_MANDATORY: 'samplelocate',
|
||||
INVENTREE_CUSTOM_SPLASH: 'img/playwright_custom_splash.png',
|
||||
INVENTREE_CUSTOM_LOGO: 'img/playwright_custom_logo.png'
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export const PdfPreviewComponent: PreviewAreaComponent = forwardRef(
|
|||
}
|
||||
|
||||
let preview = await api.post(
|
||||
printingUrl,
|
||||
printingUrl!,
|
||||
{
|
||||
items: [previewItem],
|
||||
template: template.pk
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import { Boundary } from '@lib/components/Boundary';
|
||||
import { ModelInformationDict } from '@lib/enums/ModelInformation';
|
||||
import { ModelType } from '@lib/enums/ModelType';
|
||||
import { apiUrl } from '@lib/functions/Api';
|
||||
import { t } from '@lingui/core/macro';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
CloseButton,
|
||||
Group,
|
||||
List,
|
||||
|
|
@ -24,11 +29,6 @@ import {
|
|||
import Split from '@uiw/react-split';
|
||||
import type React from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { Boundary } from '@lib/components/Boundary';
|
||||
import { ModelInformationDict } from '@lib/enums/ModelInformation';
|
||||
import { ModelType } from '@lib/enums/ModelType';
|
||||
import { apiUrl } from '@lib/functions/Api';
|
||||
import { api } from '../../../App';
|
||||
import type { TemplateI } from '../../../tables/settings/TemplateTable';
|
||||
import { SplitButton } from '../../buttons/SplitButton';
|
||||
|
|
@ -78,26 +78,38 @@ export type PreviewArea = {
|
|||
|
||||
export type TemplateEditorProps = {
|
||||
templateUrl: string;
|
||||
printingUrl: string;
|
||||
printingUrl?: string;
|
||||
editors: Editor[];
|
||||
previewAreas: PreviewArea[];
|
||||
template: TemplateI;
|
||||
// Name of the file field on the template model (e.g. 'template' or 'snippet')
|
||||
fileField?: string;
|
||||
};
|
||||
|
||||
export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
||||
const { templateUrl, editors, previewAreas, template } = props;
|
||||
const {
|
||||
templateUrl,
|
||||
editors,
|
||||
previewAreas,
|
||||
template,
|
||||
fileField = 'template'
|
||||
} = props;
|
||||
const editorRef = useRef<EditorRef | null>(null);
|
||||
const previewRef = useRef<PreviewAreaRef | null>(null);
|
||||
|
||||
// If no preview areas are provided, the template is saved directly
|
||||
const hasPreview = previewAreas.length > 0;
|
||||
|
||||
const [hasSaveConfirmed, setHasSaveConfirmed] = useState(false);
|
||||
|
||||
const [previewItem, setPreviewItem] = useState<string>('');
|
||||
const [renderingErrors, setRenderingErrors] = useState<string[] | null>(null);
|
||||
const [isPreviewLoading, setIsPreviewLoading] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
const [editorValue, setEditorValue] = useState<null | string>(editors[0].key);
|
||||
const [previewValue, setPreviewValue] = useState<null | string>(
|
||||
previewAreas[0].key
|
||||
previewAreas[0]?.key ?? null
|
||||
);
|
||||
|
||||
const codeRef = useRef<string | undefined>(undefined);
|
||||
|
|
@ -131,12 +143,12 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
if (!templateUrl) return;
|
||||
|
||||
api.get(templateUrl).then((response: any) => {
|
||||
if (response.data?.template) {
|
||||
if (response.data?.[fileField]) {
|
||||
// Fetch the raw template file from the server
|
||||
// Request that it is provided without any caching,
|
||||
// to ensure that we always get the latest version
|
||||
api
|
||||
.get(response.data.template, {
|
||||
.get(response.data[fileField], {
|
||||
headers: {
|
||||
'Cache-Control': 'no-cache',
|
||||
Pragma: 'no-cache',
|
||||
|
|
@ -149,7 +161,7 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
})
|
||||
.catch(() => {
|
||||
console.error(
|
||||
`ERR: Could not load template from ${response.data.template}`
|
||||
`ERR: Could not load template from ${response.data[fileField]}`
|
||||
);
|
||||
codeRef.current = undefined;
|
||||
hideNotification('template-load-error');
|
||||
|
|
@ -244,6 +256,45 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
[previewItem]
|
||||
);
|
||||
|
||||
// Save the template file directly to the server, without any preview
|
||||
const saveTemplate = useCallback(async () => {
|
||||
const code = await getCodeFromEditor();
|
||||
|
||||
if (code === undefined) return;
|
||||
|
||||
const filename =
|
||||
(template as any)[fileField]?.split('/').pop() ?? 'template.html';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append(fileField, new File([code], filename));
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
api
|
||||
.patch(templateUrl, formData)
|
||||
.then(() => {
|
||||
hideNotification('template-save');
|
||||
showNotification({
|
||||
id: 'template-save',
|
||||
title: t`Saved`,
|
||||
message: t`Template file has been updated`,
|
||||
color: 'green'
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
hideNotification('template-save');
|
||||
showNotification({
|
||||
id: 'template-save',
|
||||
title: t`Error`,
|
||||
message: t`Could not save the template to the server.`,
|
||||
color: 'red'
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
setIsSaving(false);
|
||||
});
|
||||
}, [getCodeFromEditor, template, templateUrl, fileField]);
|
||||
|
||||
const previewApiUrl = useMemo(
|
||||
() =>
|
||||
ModelInformationDict[template.model_type ?? ModelType.stockitem]
|
||||
|
|
@ -261,18 +312,20 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
}, [template]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasPreview) return;
|
||||
|
||||
api
|
||||
.get(apiUrl(previewApiUrl), { params: { limit: 1, ...templateFilters } })
|
||||
.then((res) => {
|
||||
if (res.data.results.length === 0) return;
|
||||
setPreviewItem(res.data.results[0].pk);
|
||||
});
|
||||
}, [previewApiUrl, templateFilters]);
|
||||
}, [hasPreview, previewApiUrl, templateFilters]);
|
||||
|
||||
return (
|
||||
<Boundary label='TemplateEditor'>
|
||||
<Stack style={{ height: '100%', flex: '1' }}>
|
||||
<Split visible style={{ flex: 1 }}>
|
||||
<Split visible={hasPreview} style={{ flex: 1 }}>
|
||||
<Tabs
|
||||
value={editorValue}
|
||||
onChange={async (v) => {
|
||||
|
|
@ -282,7 +335,7 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
keepMounted={false}
|
||||
style={{
|
||||
minWidth: '300px',
|
||||
width: '50%',
|
||||
width: hasPreview ? '50%' : '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}}
|
||||
|
|
@ -301,29 +354,39 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
})}
|
||||
|
||||
<Group justify='right' style={{ flex: '1' }} wrap='nowrap'>
|
||||
<SplitButton
|
||||
loading={isPreviewLoading}
|
||||
defaultSelected='preview_save'
|
||||
name='preview-options'
|
||||
options={[
|
||||
{
|
||||
key: 'preview',
|
||||
name: t`Reload preview`,
|
||||
tooltip: t`Use the currently stored template from the server`,
|
||||
icon: IconRefresh,
|
||||
onClick: () => updatePreview(true, false),
|
||||
disabled: !previewItem || isPreviewLoading
|
||||
},
|
||||
{
|
||||
key: 'preview_save',
|
||||
name: t`Save & Reload Preview`,
|
||||
tooltip: t`Save the current template and reload the preview`,
|
||||
icon: IconDeviceFloppy,
|
||||
onClick: () => updatePreview(hasSaveConfirmed),
|
||||
disabled: !previewItem || isPreviewLoading
|
||||
}
|
||||
]}
|
||||
/>
|
||||
{hasPreview ? (
|
||||
<SplitButton
|
||||
loading={isPreviewLoading}
|
||||
defaultSelected='preview_save'
|
||||
name='preview-options'
|
||||
options={[
|
||||
{
|
||||
key: 'preview',
|
||||
name: t`Reload preview`,
|
||||
tooltip: t`Use the currently stored template from the server`,
|
||||
icon: IconRefresh,
|
||||
onClick: () => updatePreview(true, false),
|
||||
disabled: !previewItem || isPreviewLoading
|
||||
},
|
||||
{
|
||||
key: 'preview_save',
|
||||
name: t`Save & Reload Preview`,
|
||||
tooltip: t`Save the current template and reload the preview`,
|
||||
icon: IconDeviceFloppy,
|
||||
onClick: () => updatePreview(hasSaveConfirmed),
|
||||
disabled: !previewItem || isPreviewLoading
|
||||
}
|
||||
]}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
leftSection={<IconDeviceFloppy size={18} />}
|
||||
loading={isSaving}
|
||||
onClick={() => saveTemplate()}
|
||||
>
|
||||
{t`Save`}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Tabs.List>
|
||||
|
||||
|
|
@ -342,100 +405,102 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
|||
))}
|
||||
</Tabs>
|
||||
|
||||
<Tabs
|
||||
value={previewValue}
|
||||
onChange={setPreviewValue}
|
||||
keepMounted={false}
|
||||
style={{
|
||||
minWidth: '200px',
|
||||
width: '50%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}}
|
||||
>
|
||||
<Tabs.List>
|
||||
{previewAreas.map((PreviewArea) => (
|
||||
<Tabs.Tab
|
||||
key={PreviewArea.key}
|
||||
value={PreviewArea.key}
|
||||
leftSection={PreviewArea.icon}
|
||||
>
|
||||
{PreviewArea.name}
|
||||
</Tabs.Tab>
|
||||
))}
|
||||
</Tabs.List>
|
||||
|
||||
<div
|
||||
{hasPreview && (
|
||||
<Tabs
|
||||
value={previewValue}
|
||||
onChange={setPreviewValue}
|
||||
keepMounted={false}
|
||||
style={{
|
||||
minWidth: '100%',
|
||||
paddingBottom: '10px',
|
||||
paddingTop: '10px'
|
||||
minWidth: '200px',
|
||||
width: '50%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}}
|
||||
>
|
||||
<StandaloneField
|
||||
fieldDefinition={{
|
||||
field_type: 'related field',
|
||||
api_url: apiUrl(previewApiUrl),
|
||||
description: '',
|
||||
label: t`Select instance to preview`,
|
||||
model: template.model_type,
|
||||
value: previewItem,
|
||||
filters: templateFilters,
|
||||
onValueChange: (value) => setPreviewItem(value)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Tabs.List>
|
||||
{previewAreas.map((PreviewArea) => (
|
||||
<Tabs.Tab
|
||||
key={PreviewArea.key}
|
||||
value={PreviewArea.key}
|
||||
leftSection={PreviewArea.icon}
|
||||
>
|
||||
{PreviewArea.name}
|
||||
</Tabs.Tab>
|
||||
))}
|
||||
</Tabs.List>
|
||||
|
||||
{previewAreas.map((PreviewArea) => (
|
||||
<Tabs.Panel
|
||||
key={PreviewArea.key}
|
||||
value={PreviewArea.key}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flex: previewValue === PreviewArea.key ? 1 : 0
|
||||
minWidth: '100%',
|
||||
paddingBottom: '10px',
|
||||
paddingTop: '10px'
|
||||
}}
|
||||
>
|
||||
<div
|
||||
<StandaloneField
|
||||
fieldDefinition={{
|
||||
field_type: 'related field',
|
||||
api_url: apiUrl(previewApiUrl),
|
||||
description: '',
|
||||
label: t`Select instance to preview`,
|
||||
model: template.model_type,
|
||||
value: previewItem,
|
||||
filters: templateFilters,
|
||||
onValueChange: (value) => setPreviewItem(value)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{previewAreas.map((PreviewArea) => (
|
||||
<Tabs.Panel
|
||||
key={PreviewArea.key}
|
||||
value={PreviewArea.key}
|
||||
style={{
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flex: '1'
|
||||
flex: previewValue === PreviewArea.key ? 1 : 0
|
||||
}}
|
||||
>
|
||||
{/* @ts-ignore-next-line */}
|
||||
<PreviewArea.component ref={previewRef} />
|
||||
<div
|
||||
style={{
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flex: '1'
|
||||
}}
|
||||
>
|
||||
{/* @ts-ignore-next-line */}
|
||||
<PreviewArea.component ref={previewRef} />
|
||||
|
||||
{renderingErrors && (
|
||||
<Overlay color='red' center blur={0.2}>
|
||||
<CloseButton
|
||||
onClick={() => setRenderingErrors(null)}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '10px',
|
||||
right: '10px',
|
||||
color: '#fff'
|
||||
}}
|
||||
variant='filled'
|
||||
/>
|
||||
<Alert
|
||||
color='red'
|
||||
icon={<IconExclamationCircle />}
|
||||
title={t`Error rendering template`}
|
||||
mx='10px'
|
||||
>
|
||||
<List>
|
||||
{renderingErrors.map((error, index) => (
|
||||
<ListItem key={index}>{error}</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</Alert>
|
||||
</Overlay>
|
||||
)}
|
||||
</div>
|
||||
</Tabs.Panel>
|
||||
))}
|
||||
</Tabs>
|
||||
{renderingErrors && (
|
||||
<Overlay color='red' center blur={0.2}>
|
||||
<CloseButton
|
||||
onClick={() => setRenderingErrors(null)}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '10px',
|
||||
right: '10px',
|
||||
color: '#fff'
|
||||
}}
|
||||
variant='filled'
|
||||
/>
|
||||
<Alert
|
||||
color='red'
|
||||
icon={<IconExclamationCircle />}
|
||||
title={t`Error rendering template`}
|
||||
mx='10px'
|
||||
>
|
||||
<List>
|
||||
{renderingErrors.map((error, index) => (
|
||||
<ListItem key={index}>{error}</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</Alert>
|
||||
</Overlay>
|
||||
)}
|
||||
</div>
|
||||
</Tabs.Panel>
|
||||
))}
|
||||
</Tabs>
|
||||
)}
|
||||
</Split>
|
||||
</Stack>
|
||||
</Boundary>
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ import { useId } from '@mantine/hooks';
|
|||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
import { type Control, type FieldValues, useController } from 'react-hook-form';
|
||||
|
||||
import { ApiEndpoints } from '@lib/enums/ApiEndpoints';
|
||||
import { ModelType } from '@lib/enums/ModelType';
|
||||
import { apiUrl } from '@lib/functions/Api';
|
||||
import type { ApiFormFieldSet, ApiFormFieldType } from '@lib/types/Forms';
|
||||
import { IconFileUpload } from '@tabler/icons-react';
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
|
|
@ -19,6 +22,7 @@ import { RelatedModelField } from './RelatedModelField';
|
|||
import { TableField } from './TableField';
|
||||
import TagsField from './TagsField';
|
||||
import TextField from './TextField';
|
||||
import { TreeField } from './TreeField';
|
||||
|
||||
/**
|
||||
* Render an individual form field
|
||||
|
|
@ -121,14 +125,48 @@ export function ApiFormField({
|
|||
const fieldInstance = useMemo(() => {
|
||||
switch (fieldDefinition.field_type) {
|
||||
case 'related field':
|
||||
return (
|
||||
<RelatedModelField
|
||||
definition={fieldDefinition}
|
||||
controller={controller}
|
||||
fieldName={fieldName}
|
||||
navigate={navigate}
|
||||
/>
|
||||
);
|
||||
if (
|
||||
fieldDefinition.api_url === apiUrl(ApiEndpoints.stock_location_list)
|
||||
) {
|
||||
// Redirect location fields to the appropriate tree field
|
||||
return (
|
||||
<TreeField
|
||||
controller={controller}
|
||||
definition={fieldDefinition}
|
||||
fieldName={fieldName}
|
||||
endpoint={ApiEndpoints.stock_location_tree}
|
||||
childIdentifier='sublocations'
|
||||
genericPlaceholder={t`Select location`}
|
||||
model={ModelType.stocklocation}
|
||||
navigate={navigate}
|
||||
/>
|
||||
);
|
||||
} else if (
|
||||
fieldDefinition.api_url === apiUrl(ApiEndpoints.category_list)
|
||||
) {
|
||||
// Redirect category fields to the appropriate tree field
|
||||
return (
|
||||
<TreeField
|
||||
controller={controller}
|
||||
definition={fieldDefinition}
|
||||
fieldName={fieldName}
|
||||
endpoint={ApiEndpoints.category_tree}
|
||||
childIdentifier='subcategories'
|
||||
genericPlaceholder={t`Select category`}
|
||||
model={ModelType.partcategory}
|
||||
navigate={navigate}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<RelatedModelField
|
||||
definition={fieldDefinition}
|
||||
controller={controller}
|
||||
fieldName={fieldName}
|
||||
navigate={navigate}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case 'email':
|
||||
case 'url':
|
||||
case 'string':
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { t } from '@lingui/core/macro';
|
||||
import { Trans } from '@lingui/react/macro';
|
||||
import {
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Container,
|
||||
Group,
|
||||
|
|
@ -9,7 +10,10 @@ import {
|
|||
Table,
|
||||
Text
|
||||
} from '@mantine/core';
|
||||
import { IconExclamationCircle } from '@tabler/icons-react';
|
||||
import {
|
||||
IconCornerDownRight,
|
||||
IconExclamationCircle
|
||||
} from '@tabler/icons-react';
|
||||
import {
|
||||
type ReactNode,
|
||||
memo,
|
||||
|
|
@ -63,13 +67,33 @@ function TableFieldRow({
|
|||
);
|
||||
}
|
||||
|
||||
return modelRenderer({
|
||||
item: item,
|
||||
rowId: rowId,
|
||||
rowErrors: rowErrors,
|
||||
changeFn: changeFn,
|
||||
removeFn: removeFn
|
||||
});
|
||||
const nonFieldErrors = rowErrors?.non_field_errors;
|
||||
|
||||
return (
|
||||
<>
|
||||
{modelRenderer({
|
||||
item: item,
|
||||
rowId: rowId,
|
||||
rowErrors: rowErrors,
|
||||
changeFn: changeFn,
|
||||
removeFn: removeFn
|
||||
})}
|
||||
{nonFieldErrors && (
|
||||
<Table.Tr key={`table-row-${rowId}-non-field-errors`}>
|
||||
<Table.Td colSpan={columnCount}>
|
||||
<Group gap='xs'>
|
||||
<ActionIcon size='sm' variant='transparent' c='red'>
|
||||
<IconCornerDownRight />
|
||||
</ActionIcon>
|
||||
<Text size='xs' c='red'>
|
||||
{nonFieldErrors.message ?? nonFieldErrors}
|
||||
</Text>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Memoize each table field row, so that we don't re-render the entire table when a single row is updated
|
||||
|
|
|
|||
|
|
@ -0,0 +1,499 @@
|
|||
import { t } from '@lingui/core/macro';
|
||||
import {
|
||||
ActionIcon,
|
||||
Group,
|
||||
Input,
|
||||
Text,
|
||||
type TreeNodeData,
|
||||
TreeSelect
|
||||
} from '@mantine/core';
|
||||
import { useDebouncedValue, useId } from '@mantine/hooks';
|
||||
import {
|
||||
IconChevronDown,
|
||||
IconChevronRight,
|
||||
IconLink,
|
||||
IconX
|
||||
} from '@tabler/icons-react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { FieldValues, UseControllerReturn } from 'react-hook-form';
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
|
||||
import type { ApiEndpoints } from '@lib/enums/ApiEndpoints';
|
||||
import { ModelInformationDict } from '@lib/enums/ModelInformation';
|
||||
import type { ModelType } from '@lib/enums/ModelType';
|
||||
import { apiUrl } from '@lib/functions/Api';
|
||||
import { cancelEvent } from '@lib/functions/Events';
|
||||
import { getDetailUrl, navigateToLink } from '@lib/functions/Navigation';
|
||||
import type { ApiFormFieldType } from '@lib/types/Forms';
|
||||
import { useApi } from '../../../contexts/ApiContext';
|
||||
import {
|
||||
useGlobalSettingsState,
|
||||
useUserSettingsState
|
||||
} from '../../../states/SettingsStates';
|
||||
import { ScanButton } from '../../buttons/ScanButton';
|
||||
import { ApiIcon } from '../../items/ApiIcon';
|
||||
import Expand from '../../items/Expand';
|
||||
import { ModelHoverCard } from '../../render/ModelHoverCard';
|
||||
|
||||
/**
|
||||
* A form field that renders a hierarchical tree selector backed by a tree API
|
||||
* endpoint. Supports server-side search, lazy child loading, and (when a model
|
||||
* type is provided) barcode scanning and a hover-card navigate link.
|
||||
*/
|
||||
export function TreeField({
|
||||
controller,
|
||||
definition,
|
||||
fieldName,
|
||||
endpoint,
|
||||
childIdentifier,
|
||||
genericPlaceholder,
|
||||
model,
|
||||
navigate
|
||||
}: Readonly<{
|
||||
controller: UseControllerReturn<FieldValues, any>;
|
||||
definition: ApiFormFieldType;
|
||||
fieldName: string;
|
||||
endpoint: ApiEndpoints;
|
||||
childIdentifier: string;
|
||||
genericPlaceholder?: string;
|
||||
model?: ModelType;
|
||||
navigate?: NavigateFunction | null;
|
||||
}>) {
|
||||
const api = useApi();
|
||||
const inputId = useId();
|
||||
const globalSettings = useGlobalSettingsState();
|
||||
const userSettings = useUserSettingsState();
|
||||
|
||||
const {
|
||||
field,
|
||||
fieldState: { error }
|
||||
} = controller;
|
||||
|
||||
// Keep the selected pk in sync with form state so we can always request
|
||||
// the selected node (and its ancestors) for label hydration.
|
||||
const selectedValue = useMemo(
|
||||
() => (field.value != null ? Number(field.value) : null),
|
||||
[field.value]
|
||||
);
|
||||
|
||||
// Track dropdown state to separate server-side search text from the
|
||||
// read-only display label shown when the field is closed.
|
||||
const dropdownOpen = useRef(false);
|
||||
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
||||
|
||||
// Track the pk whose ancestor path was last auto-expanded.
|
||||
const expandedForValue = useRef<number | null>(null);
|
||||
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const [debouncedSearch] = useDebouncedValue(searchValue, 300);
|
||||
const [expandedValues, setExpandedValues] = useState<string[]>([]);
|
||||
const [nodes, setNodes] = useState<any[]>([]);
|
||||
|
||||
const query = useQuery({
|
||||
enabled:
|
||||
!definition.disabled &&
|
||||
!definition.hidden &&
|
||||
(isDropdownOpen || selectedValue != null),
|
||||
queryKey: [
|
||||
'tree-field',
|
||||
fieldName,
|
||||
endpoint,
|
||||
isDropdownOpen,
|
||||
debouncedSearch,
|
||||
selectedValue
|
||||
],
|
||||
queryFn: () =>
|
||||
api
|
||||
.get(apiUrl(endpoint), {
|
||||
params: {
|
||||
...definition.filters,
|
||||
ordering: 'level',
|
||||
search: debouncedSearch || undefined,
|
||||
// Include the selected node and its ancestors in the initial response
|
||||
// so the node label is available before the user interacts with the field.
|
||||
max_level: debouncedSearch ? undefined : 0,
|
||||
expand_to: debouncedSearch
|
||||
? undefined
|
||||
: (selectedValue ?? undefined)
|
||||
}
|
||||
})
|
||||
.then((res) => res.data ?? [])
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setNodes(query.data ?? []);
|
||||
}, [query.data]);
|
||||
|
||||
// O(1) lookup for raw node data inside renderNode
|
||||
const nodeMap = useMemo(() => {
|
||||
const map: Record<string, any> = {};
|
||||
for (const n of nodes) map[n.pk.toString()] = n;
|
||||
return map;
|
||||
}, [nodes]);
|
||||
|
||||
// Expand all returned nodes when a search is active so users can see all matches.
|
||||
// On the first browse-mode load, expand the ancestors of the initial value so
|
||||
// the tree shows the path to the currently-selected node.
|
||||
useEffect(() => {
|
||||
if (debouncedSearch) {
|
||||
setExpandedValues(nodes.map((n: any) => n.pk.toString()));
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
selectedValue != null &&
|
||||
expandedForValue.current !== selectedValue &&
|
||||
nodes.length > 0
|
||||
) {
|
||||
expandedForValue.current = selectedValue;
|
||||
const map: Record<number, any> = {};
|
||||
for (const n of nodes) map[n.pk] = n;
|
||||
const toExpand: string[] = [];
|
||||
let cur = map[selectedValue];
|
||||
while (cur?.parent) {
|
||||
toExpand.push(String(cur.parent));
|
||||
cur = map[cur.parent];
|
||||
}
|
||||
setExpandedValues(toExpand);
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedValue == null) {
|
||||
expandedForValue.current = null;
|
||||
}
|
||||
}, [debouncedSearch, nodes, selectedValue]);
|
||||
|
||||
// Convert the flat API response (sorted by level) into the nested TreeNodeData structure.
|
||||
// `children` is intentionally left undefined on leaf nodes: Mantine's flatten logic uses
|
||||
// Array.isArray(node.children) to detect loaded children, so an empty [] would make every
|
||||
// node look like a parent. Instead we set node.hasChildren from the server-side count field
|
||||
// (childIdentifier) and only attach a children array when a child is actually encountered.
|
||||
const treeData: TreeNodeData[] = useMemo(() => {
|
||||
const map: Record<number, any> = {};
|
||||
const tree: TreeNodeData[] = [];
|
||||
|
||||
const sorted = [...nodes].sort((a, b) => a.level - b.level);
|
||||
|
||||
for (const raw of sorted) {
|
||||
const node: any = {
|
||||
value: raw.pk.toString(),
|
||||
label: raw.name as string,
|
||||
hasChildren: (raw[childIdentifier] ?? 0) > 0
|
||||
};
|
||||
|
||||
map[raw.pk] = node;
|
||||
|
||||
if (!raw.parent) {
|
||||
tree.push(node);
|
||||
} else if (map[raw.parent]) {
|
||||
if (!map[raw.parent].children) {
|
||||
map[raw.parent].children = [];
|
||||
}
|
||||
map[raw.parent].children.push(node);
|
||||
} else {
|
||||
// Keep orphaned nodes visible so selected labels can still resolve
|
||||
// if the API response omits an ancestor.
|
||||
tree.push(node);
|
||||
}
|
||||
}
|
||||
return tree;
|
||||
}, [nodes, childIdentifier]);
|
||||
|
||||
const onChange = useCallback(
|
||||
(val: string | null) => {
|
||||
const pk = val ? Number.parseInt(val, 10) : null;
|
||||
const raw = val ? (nodeMap[val] ?? {}) : {};
|
||||
field.onChange(pk);
|
||||
definition.onValueChange?.(pk, raw);
|
||||
},
|
||||
[field, definition, nodeMap]
|
||||
);
|
||||
|
||||
const selectValue = useMemo(
|
||||
() => (field.value != null ? field.value.toString() : null),
|
||||
[field.value]
|
||||
);
|
||||
|
||||
const selectedLabel = useMemo(() => {
|
||||
if (selectValue == null) return '';
|
||||
const node = nodeMap[selectValue];
|
||||
return node?.pathstring ?? node?.name ?? selectValue;
|
||||
}, [nodeMap, selectValue]);
|
||||
|
||||
const inputSearchValue = isDropdownOpen ? searchValue : selectedLabel;
|
||||
|
||||
const refreshChildren = useCallback(
|
||||
async (nodeValue: string) => {
|
||||
const pk = Number.parseInt(nodeValue, 10);
|
||||
if (Number.isNaN(pk)) return;
|
||||
|
||||
const node = nodeMap[nodeValue];
|
||||
if (!node) return;
|
||||
|
||||
const response = await api.get(apiUrl(endpoint), {
|
||||
params: {
|
||||
...definition.filters,
|
||||
ordering: 'level',
|
||||
parent: pk,
|
||||
max_level: (node.level ?? 0) + 1
|
||||
}
|
||||
});
|
||||
|
||||
const children: any[] = response.data ?? [];
|
||||
|
||||
setNodes((prev) => {
|
||||
const base = prev.filter((n) => n.parent !== pk);
|
||||
const byPk = new Map<number, any>();
|
||||
|
||||
for (const n of base) {
|
||||
byPk.set(n.pk, n);
|
||||
}
|
||||
|
||||
for (const child of children) {
|
||||
byPk.set(child.pk, child);
|
||||
}
|
||||
|
||||
if (children.length === 0) {
|
||||
const parentNode = byPk.get(pk);
|
||||
if (parentNode) {
|
||||
byPk.set(pk, { ...parentNode, [childIdentifier]: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(byPk.values());
|
||||
});
|
||||
},
|
||||
[api, endpoint, nodeMap, childIdentifier]
|
||||
);
|
||||
|
||||
const toggleExpanded = useCallback(
|
||||
(nodeValue: string) => {
|
||||
setExpandedValues((prev) => {
|
||||
const isExpanded = prev.includes(nodeValue);
|
||||
|
||||
if (!isExpanded) {
|
||||
void refreshChildren(nodeValue);
|
||||
return [...prev, nodeValue];
|
||||
}
|
||||
|
||||
return prev.filter((v) => v !== nodeValue);
|
||||
});
|
||||
},
|
||||
[refreshChildren]
|
||||
);
|
||||
|
||||
// --- Navigate / hovercard ---
|
||||
|
||||
const detailUrl = useMemo(() => {
|
||||
if (!model || !selectedValue) return '';
|
||||
return getDetailUrl(model, selectedValue, true);
|
||||
}, [model, selectedValue]);
|
||||
|
||||
const handleNavigate = useCallback(
|
||||
(e: any) => {
|
||||
if (navigate && detailUrl) navigateToLink(detailUrl, navigate, e);
|
||||
},
|
||||
[navigate, detailUrl]
|
||||
);
|
||||
|
||||
// When a navigate model is present and a value is selected, swap out
|
||||
// Mantine's built-in clear button for a custom right section that holds
|
||||
// both a clear button and a link to the model detail page (with tooltip).
|
||||
const showNavigateSection = Boolean(model && selectedValue);
|
||||
|
||||
const navigateRightSection = showNavigateSection ? (
|
||||
<Group gap={2} wrap='nowrap' style={{ paddingRight: 4 }}>
|
||||
{!definition.required && selectValue && (
|
||||
<ActionIcon
|
||||
variant='transparent'
|
||||
size='xs'
|
||||
color='dimmed'
|
||||
aria-label={t`Clear`}
|
||||
onClick={(e: any) => {
|
||||
cancelEvent(e);
|
||||
onChange(null);
|
||||
}}
|
||||
>
|
||||
<IconX size={12} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
<ModelHoverCard model={model} pk={selectedValue} navigate={navigate}>
|
||||
<ActionIcon
|
||||
variant='transparent'
|
||||
size='xs'
|
||||
component='a'
|
||||
href={detailUrl || '#'}
|
||||
target='_blank'
|
||||
aria-label={t`View details`}
|
||||
onClick={handleNavigate}
|
||||
>
|
||||
<IconLink size={12} />
|
||||
</ActionIcon>
|
||||
</ModelHoverCard>
|
||||
</Group>
|
||||
) : undefined;
|
||||
|
||||
// --- Barcode scanning ---
|
||||
|
||||
const modelInfo = useMemo(
|
||||
() => (model ? ModelInformationDict[model] : null),
|
||||
[model]
|
||||
);
|
||||
|
||||
const addBarcodeField = useMemo(() => {
|
||||
if (!modelInfo?.supports_barcode) return false;
|
||||
if (!globalSettings.isSet('BARCODE_ENABLE')) return false;
|
||||
if (!userSettings.isSet('BARCODE_IN_FORM_FIELDS')) return false;
|
||||
return true;
|
||||
}, [modelInfo, globalSettings, userSettings]);
|
||||
|
||||
const onBarcodeScan = useCallback(
|
||||
(_barcode: string, response: any) => {
|
||||
if (!model) return;
|
||||
const modelData = response?.[model] ?? null;
|
||||
if (modelData?.pk) {
|
||||
field.onChange(modelData.pk);
|
||||
definition.onValueChange?.(modelData.pk, modelData);
|
||||
}
|
||||
},
|
||||
[model, field, definition]
|
||||
);
|
||||
|
||||
// --- Render ---
|
||||
|
||||
return (
|
||||
<Input.Wrapper
|
||||
label={definition.label}
|
||||
description={definition.description}
|
||||
required={definition.required}
|
||||
error={definition.error ?? error?.message}
|
||||
id={inputId}
|
||||
>
|
||||
<Group wrap='nowrap' gap={3}>
|
||||
<Expand>
|
||||
<TreeSelect
|
||||
id={inputId}
|
||||
data={treeData}
|
||||
aria-label={`tree-field-${fieldName}`}
|
||||
value={selectValue}
|
||||
searchValue={inputSearchValue}
|
||||
onChange={onChange}
|
||||
onSearchChange={(val) => {
|
||||
if (dropdownOpen.current) setSearchValue(val);
|
||||
}}
|
||||
searchable
|
||||
filter={() => true}
|
||||
clearable={showNavigateSection ? false : !definition.required}
|
||||
rightSection={navigateRightSection}
|
||||
rightSectionPointerEvents={showNavigateSection ? 'all' : undefined}
|
||||
rightSectionWidth={
|
||||
showNavigateSection ? (definition.required ? 28 : 52) : undefined
|
||||
}
|
||||
expandedValues={expandedValues}
|
||||
onExpandedChange={setExpandedValues}
|
||||
onDropdownOpen={() => {
|
||||
dropdownOpen.current = true;
|
||||
setIsDropdownOpen(true);
|
||||
}}
|
||||
onDropdownClose={() => {
|
||||
dropdownOpen.current = false;
|
||||
setIsDropdownOpen(false);
|
||||
setSearchValue('');
|
||||
}}
|
||||
placeholder={
|
||||
isDropdownOpen && selectedLabel
|
||||
? selectedLabel
|
||||
: (definition.placeholder ?? genericPlaceholder ?? t`Select...`)
|
||||
}
|
||||
disabled={definition.disabled}
|
||||
comboboxProps={{ withinPortal: true }}
|
||||
maxDropdownHeight={300}
|
||||
nothingFoundMessage={
|
||||
query.isFetching ? t`Loading...` : t`No results found`
|
||||
}
|
||||
renderNode={({ node, expanded, hasChildren, selected }) => {
|
||||
const raw = nodeMap[node.value];
|
||||
return (
|
||||
<Group
|
||||
justify='space-between'
|
||||
gap='xs'
|
||||
wrap='nowrap'
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<Group gap={4} wrap='nowrap'>
|
||||
{/* Chevron rendered manually so renderNode can coexist with
|
||||
expand behavior. stopPropagation prevents the
|
||||
Combobox.Option from selecting the node when the user
|
||||
clicks the expand toggle. */}
|
||||
<span
|
||||
role={hasChildren ? 'button' : undefined}
|
||||
tabIndex={hasChildren ? 0 : undefined}
|
||||
style={{
|
||||
display: 'inline-flex',
|
||||
width: 16,
|
||||
alignItems: 'center',
|
||||
flexShrink: 0,
|
||||
cursor: hasChildren ? 'pointer' : 'default'
|
||||
}}
|
||||
aria-label={expanded ? t`Collapse` : t`Expand`}
|
||||
onClick={
|
||||
hasChildren
|
||||
? (event: any) => {
|
||||
cancelEvent(event);
|
||||
toggleExpanded(node.value);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onKeyDown={
|
||||
hasChildren
|
||||
? (event: any) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
cancelEvent(event);
|
||||
toggleExpanded(node.value);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{hasChildren &&
|
||||
(expanded ? (
|
||||
<IconChevronDown size={14} />
|
||||
) : (
|
||||
<IconChevronRight size={14} />
|
||||
))}
|
||||
</span>
|
||||
{raw?.icon && <ApiIcon name={raw.icon} size={14} />}
|
||||
<Text
|
||||
size='sm'
|
||||
fw={selected ? 600 : undefined}
|
||||
fs={raw?.structural ? 'italic' : undefined}
|
||||
c={raw?.structural ? 'dimmed' : undefined}
|
||||
>
|
||||
{raw?.name ?? String(node.label)}
|
||||
</Text>
|
||||
</Group>
|
||||
{raw?.description && (
|
||||
<Text
|
||||
size='xs'
|
||||
c='dimmed'
|
||||
ta='right'
|
||||
truncate
|
||||
flex={1}
|
||||
maw='50%'
|
||||
>
|
||||
{raw.description}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Expand>
|
||||
{addBarcodeField && (
|
||||
<ScanButton modelType={model} onScanSuccess={onBarcodeScan} />
|
||||
)}
|
||||
</Group>
|
||||
</Input.Wrapper>
|
||||
);
|
||||
}
|
||||
|
|
@ -65,8 +65,8 @@ const AboutContent = ({
|
|||
function fillTable(lookup: AboutLookupRef[], data: any, alwaysLink = false) {
|
||||
return lookup
|
||||
.filter((entry: AboutLookupRef) => !!data[entry.ref])
|
||||
.map((entry: AboutLookupRef, idx) => (
|
||||
<Table.Tr key={idx}>
|
||||
.map((entry: AboutLookupRef) => (
|
||||
<Table.Tr key={entry.ref}>
|
||||
<Table.Td>{entry.title}</Table.Td>
|
||||
<Table.Td>
|
||||
<Group justify='space-between' gap='xs'>
|
||||
|
|
|
|||
|
|
@ -564,9 +564,9 @@ export function SearchDrawer({
|
|||
multiple
|
||||
defaultValue={searchQueries.map((q) => q.model)}
|
||||
>
|
||||
{queryResults.map((query, idx) => (
|
||||
{queryResults.map((query) => (
|
||||
<QueryResultGroup
|
||||
key={idx}
|
||||
key={query.model}
|
||||
searchText={searchText}
|
||||
query={query}
|
||||
navigate={navigate}
|
||||
|
|
|
|||
|
|
@ -31,9 +31,9 @@ export type { InstanceRenderInterface } from '@lib/types/Rendering';
|
|||
import {
|
||||
getBaseUrl,
|
||||
getDetailUrl,
|
||||
navigateToLink,
|
||||
shortenString
|
||||
} from '@lib/index';
|
||||
navigateToLink
|
||||
} from '@lib/functions/Navigation';
|
||||
import { shortenString } from '@lib/functions/String';
|
||||
import { IconLink } from '@tabler/icons-react';
|
||||
import { useApi } from '../../contexts/ApiContext';
|
||||
import { usePluginState } from '../../states/PluginState';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,81 @@
|
|||
import { t } from '@lingui/core/macro';
|
||||
import {
|
||||
ActionIcon,
|
||||
Anchor,
|
||||
Group,
|
||||
HoverCard,
|
||||
Stack,
|
||||
Text
|
||||
} from '@mantine/core';
|
||||
import type { ReactNode } from 'react';
|
||||
import type { NavigateFunction } from 'react-router-dom';
|
||||
|
||||
import { ModelInformationDict } from '@lib/enums/ModelInformation';
|
||||
import type { ModelType } from '@lib/enums/ModelType';
|
||||
import { getDetailUrl, navigateToLink } from '@lib/functions/Navigation';
|
||||
import { IconLink } from '@tabler/icons-react';
|
||||
|
||||
/**
|
||||
* Wraps children in a HoverCard showing the model label, pk, and a "View
|
||||
* details" link for the given instance. Renders children directly (no card)
|
||||
* when model or pk is absent.
|
||||
*/
|
||||
export function ModelHoverCard({
|
||||
children,
|
||||
model,
|
||||
pk,
|
||||
navigate
|
||||
}: {
|
||||
children: ReactNode;
|
||||
model: ModelType | undefined;
|
||||
pk: number | null | undefined;
|
||||
navigate?: NavigateFunction | null;
|
||||
}) {
|
||||
const modelInfo = model ? ModelInformationDict[model] : undefined;
|
||||
|
||||
if (!modelInfo || !pk) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
const detailUrl = getDetailUrl(model!, pk, true);
|
||||
|
||||
return (
|
||||
<HoverCard
|
||||
position='top-end'
|
||||
withinPortal
|
||||
openDelay={500}
|
||||
closeDelay={100}
|
||||
zIndex={99999}
|
||||
>
|
||||
<HoverCard.Target>
|
||||
<span>{children}</span>
|
||||
</HoverCard.Target>
|
||||
<HoverCard.Dropdown>
|
||||
<Stack gap='xs'>
|
||||
<Group justify='space-between'>
|
||||
<Text size='sm' fw='bold'>
|
||||
{modelInfo.label()}
|
||||
</Text>
|
||||
<Text size='xs'>{`[${t`ID`}: ${pk}]`}</Text>
|
||||
</Group>
|
||||
{detailUrl && (
|
||||
<Anchor
|
||||
href={detailUrl}
|
||||
target='_blank'
|
||||
onClick={(event) => {
|
||||
if (navigate) navigateToLink(detailUrl, navigate, event);
|
||||
}}
|
||||
>
|
||||
<Group gap='xs' wrap='nowrap'>
|
||||
<ActionIcon variant='transparent' size='xs'>
|
||||
<IconLink />
|
||||
</ActionIcon>
|
||||
<Text size='sm'>{t`View details`}</Text>
|
||||
</Group>
|
||||
</Anchor>
|
||||
)}
|
||||
</Stack>
|
||||
</HoverCard.Dropdown>
|
||||
</HoverCard>
|
||||
);
|
||||
}
|
||||
|
|
@ -128,12 +128,7 @@ export function RenderPartCategory(
|
|||
<RenderInlineModel
|
||||
{...props}
|
||||
tooltip={instance.pathstring}
|
||||
prefix={
|
||||
<>
|
||||
{instance.level > 0 && `${'- '.repeat(instance.level)}`}
|
||||
{instance.icon && <ApiIcon name={instance.icon} />}
|
||||
</>
|
||||
}
|
||||
prefix={instance.icon && <ApiIcon name={instance.icon} />}
|
||||
primary={category}
|
||||
suffix={suffix}
|
||||
url={
|
||||
|
|
|
|||
|
|
@ -48,12 +48,7 @@ export function RenderStockLocation(
|
|||
<RenderInlineModel
|
||||
{...props}
|
||||
tooltip={instance.pathstring}
|
||||
prefix={
|
||||
<>
|
||||
{instance.level > 0 && `${'- '.repeat(instance.level)}`}
|
||||
{instance.icon && <ApiIcon name={instance.icon} />}
|
||||
</>
|
||||
}
|
||||
prefix={instance.icon && <ApiIcon name={instance.icon} />}
|
||||
primary={location}
|
||||
suffix={suffix}
|
||||
url={
|
||||
|
|
|
|||
|
|
@ -28,21 +28,34 @@ export function SettingList({
|
|||
settingsState,
|
||||
keys,
|
||||
onChange,
|
||||
onLoaded
|
||||
onLoaded,
|
||||
doGet
|
||||
}: Readonly<{
|
||||
heading?: string;
|
||||
settingsState: SettingsStateProps;
|
||||
keys?: string[];
|
||||
onChange?: () => void;
|
||||
onLoaded?: (settings: SettingsStateProps) => void;
|
||||
doGet?: boolean;
|
||||
}>) {
|
||||
useEffect(() => {
|
||||
if (settingsState.loaded) {
|
||||
if (settingsState.loaded === true) {
|
||||
// Call the onLoaded callback if provided
|
||||
onLoaded?.(settingsState);
|
||||
}
|
||||
}, [settingsState.loaded, settingsState.settings]);
|
||||
|
||||
// get data if doGet is true to break memos leading to hidden group panels
|
||||
useMemo(() => {
|
||||
if (doGet && !settingsState.loaded) {
|
||||
settingsState.fetchSettings().then((success) => {
|
||||
if (success) {
|
||||
onLoaded?.(settingsState);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [doGet, settingsState]);
|
||||
|
||||
const api = useApi();
|
||||
|
||||
const allKeys = useMemo(
|
||||
|
|
@ -226,9 +239,11 @@ export function GlobalSettingList({
|
|||
|
||||
export function PluginSettingList({
|
||||
pluginKey,
|
||||
doGet,
|
||||
onLoaded
|
||||
}: Readonly<{
|
||||
pluginKey: string;
|
||||
doGet?: boolean;
|
||||
onLoaded?: (settings: SettingsStateProps) => void;
|
||||
}>) {
|
||||
const store = useMemo(
|
||||
|
|
@ -246,14 +261,22 @@ export function PluginSettingList({
|
|||
pluginSettings.fetchSettings();
|
||||
}, [pluginSettings.fetchSettings]);
|
||||
|
||||
return <SettingList settingsState={pluginSettings} onLoaded={onLoaded} />;
|
||||
return (
|
||||
<SettingList
|
||||
settingsState={pluginSettings}
|
||||
onLoaded={onLoaded}
|
||||
doGet={doGet}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function PluginUserSettingList({
|
||||
pluginKey,
|
||||
doGet,
|
||||
onLoaded
|
||||
}: Readonly<{
|
||||
pluginKey: string;
|
||||
doGet?: boolean;
|
||||
onLoaded?: (settings: SettingsStateProps) => void;
|
||||
}>) {
|
||||
const store = useMemo(
|
||||
|
|
@ -271,7 +294,13 @@ export function PluginUserSettingList({
|
|||
pluginUserSettings.fetchSettings();
|
||||
}, [pluginUserSettings.fetchSettings]);
|
||||
|
||||
return <SettingList settingsState={pluginUserSettings} onLoaded={onLoaded} />;
|
||||
return (
|
||||
<SettingList
|
||||
settingsState={pluginUserSettings}
|
||||
onLoaded={onLoaded}
|
||||
doGet={doGet}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function MachineSettingList({
|
||||
|
|
|
|||
|
|
@ -36,16 +36,18 @@ import {
|
|||
} from '../hooks/UseGenerator';
|
||||
import { useGlobalSettingsState } from '../states/SettingsStates';
|
||||
import { RenderPartColumn } from '../tables/ColumnRenderers';
|
||||
import { ProjectCodeField, TagsField } from './CommonFields';
|
||||
import { DuplicateField, ProjectCodeField, TagsField } from './CommonFields';
|
||||
|
||||
/**
|
||||
* Field set for BuildOrder forms
|
||||
*/
|
||||
export function useBuildOrderFields({
|
||||
create,
|
||||
duplicateBuildId,
|
||||
modalId
|
||||
}: {
|
||||
create: boolean;
|
||||
duplicateBuildId?: number | null;
|
||||
modalId: string;
|
||||
}): ApiFormFieldSet {
|
||||
const [destination, setDestination] = useState<number | null | undefined>(
|
||||
|
|
@ -133,7 +135,13 @@ export function useBuildOrderFields({
|
|||
is_active: true
|
||||
}
|
||||
},
|
||||
external: {}
|
||||
external: {},
|
||||
duplicate: DuplicateField({
|
||||
originalId: duplicateBuildId,
|
||||
extraFields: {
|
||||
copy_parameters: {}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
if (!globalSettings.isSet('PROJECT_CODES_ENABLED', true)) {
|
||||
|
|
@ -144,8 +152,19 @@ export function useBuildOrderFields({
|
|||
delete fields.external;
|
||||
}
|
||||
|
||||
if (!duplicateBuildId) {
|
||||
delete fields.duplicate;
|
||||
}
|
||||
|
||||
return fields;
|
||||
}, [create, destination, batchCode, batchGenerator.result, globalSettings]);
|
||||
}, [
|
||||
create,
|
||||
destination,
|
||||
batchCode,
|
||||
batchGenerator.result,
|
||||
globalSettings,
|
||||
duplicateBuildId
|
||||
]);
|
||||
}
|
||||
|
||||
export function useBuildOrderOutputFields({
|
||||
|
|
|
|||
|
|
@ -2,6 +2,26 @@ import type { ApiFormFieldType } from '@lib/types/Forms';
|
|||
import { t } from '@lingui/core/macro';
|
||||
import { IconList } from '@tabler/icons-react';
|
||||
|
||||
// Generic field for implementing a "duplication options" form field
|
||||
export function DuplicateField({
|
||||
originalId,
|
||||
extraFields
|
||||
}: Readonly<{
|
||||
originalId?: number | null;
|
||||
extraFields?: Record<string, any>;
|
||||
}>): ApiFormFieldType {
|
||||
return {
|
||||
children: {
|
||||
original: {
|
||||
value: originalId,
|
||||
hidden: true
|
||||
},
|
||||
...extraFields
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Generic field for rendering a list of tags within a form
|
||||
export function TagsField({
|
||||
label,
|
||||
description,
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
IconPhone
|
||||
} from '@tabler/icons-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { TagsField } from './CommonFields';
|
||||
import { DuplicateField, TagsField } from './CommonFields';
|
||||
|
||||
/**
|
||||
* Field set for SupplierPart instance
|
||||
|
|
@ -21,11 +21,13 @@ import { TagsField } from './CommonFields';
|
|||
export function useSupplierPartFields({
|
||||
manufacturerId,
|
||||
manufacturerPartId,
|
||||
partId
|
||||
partId,
|
||||
duplicateSupplierPartId
|
||||
}: {
|
||||
manufacturerId?: number;
|
||||
manufacturerPartId?: number;
|
||||
partId?: number;
|
||||
duplicateSupplierPartId?: number | null;
|
||||
}) {
|
||||
const [part, setPart] = useState<any>({});
|
||||
|
||||
|
|
@ -95,14 +97,34 @@ export function useSupplierPartFields({
|
|||
icon: <IconPackage />
|
||||
},
|
||||
primary: {},
|
||||
active: {}
|
||||
active: {},
|
||||
duplicate: DuplicateField({
|
||||
originalId: duplicateSupplierPartId,
|
||||
extraFields: {
|
||||
copy_parameters: {}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
if (!duplicateSupplierPartId) {
|
||||
delete fields.duplicate;
|
||||
}
|
||||
|
||||
return fields;
|
||||
}, [manufacturerId, manufacturerPartId, partId, part]);
|
||||
}, [
|
||||
manufacturerId,
|
||||
manufacturerPartId,
|
||||
partId,
|
||||
part,
|
||||
duplicateSupplierPartId
|
||||
]);
|
||||
}
|
||||
|
||||
export function useManufacturerPartFields() {
|
||||
export function useManufacturerPartFields({
|
||||
duplicateManufacturerPartId
|
||||
}: {
|
||||
duplicateManufacturerPartId?: number | null;
|
||||
} = {}) {
|
||||
return useMemo(() => {
|
||||
const fields: ApiFormFieldSet = {
|
||||
part: {},
|
||||
|
|
@ -120,18 +142,32 @@ export function useManufacturerPartFields() {
|
|||
MPN: {},
|
||||
description: {},
|
||||
tags: TagsField({}),
|
||||
link: {}
|
||||
link: {},
|
||||
duplicate: DuplicateField({
|
||||
originalId: duplicateManufacturerPartId,
|
||||
extraFields: {
|
||||
copy_parameters: {}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
if (!duplicateManufacturerPartId) {
|
||||
delete fields.duplicate;
|
||||
}
|
||||
|
||||
return fields;
|
||||
}, []);
|
||||
}, [duplicateManufacturerPartId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Field set for editing a company instance
|
||||
*/
|
||||
export function companyFields(): ApiFormFieldSet {
|
||||
return {
|
||||
export function companyFields({
|
||||
duplicateCompanyId
|
||||
}: {
|
||||
duplicateCompanyId?: number | null;
|
||||
} = {}): ApiFormFieldSet {
|
||||
const fields: ApiFormFieldSet = {
|
||||
name: {},
|
||||
description: {},
|
||||
website: {
|
||||
|
|
@ -151,6 +187,18 @@ export function companyFields(): ApiFormFieldSet {
|
|||
is_supplier: {},
|
||||
is_manufacturer: {},
|
||||
is_customer: {},
|
||||
active: {}
|
||||
active: {},
|
||||
duplicate: DuplicateField({
|
||||
originalId: duplicateCompanyId,
|
||||
extraFields: {
|
||||
copy_parameters: {}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
if (!duplicateCompanyId) {
|
||||
delete fields.duplicate;
|
||||
}
|
||||
|
||||
return fields;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,7 +156,7 @@ export function usePartFields({
|
|||
fields.duplicate = {
|
||||
icon: <IconCopy />,
|
||||
children: {
|
||||
part: {
|
||||
original: {
|
||||
value: duplicatePartInstance?.pk,
|
||||
hidden: true
|
||||
},
|
||||
|
|
|
|||
|
|
@ -316,7 +316,7 @@ export function usePurchaseOrderFields({
|
|||
if (!!duplicateOrderId) {
|
||||
fields.duplicate = {
|
||||
children: {
|
||||
order_id: {
|
||||
original: {
|
||||
hidden: true,
|
||||
value: duplicateOrderId
|
||||
},
|
||||
|
|
|
|||
|
|
@ -84,15 +84,10 @@ export function useReturnOrderFields({
|
|||
if (!!duplicateOrderId) {
|
||||
fields.duplicate = {
|
||||
children: {
|
||||
order_id: {
|
||||
original: {
|
||||
hidden: true,
|
||||
value: duplicateOrderId
|
||||
},
|
||||
copy_lines: {
|
||||
// Cannot duplicate lines from a return order!
|
||||
value: false,
|
||||
hidden: true
|
||||
},
|
||||
copy_extra_lines: {},
|
||||
copy_parameters: {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ export function useSalesOrderFields({
|
|||
if (!!duplicateOrderId) {
|
||||
fields.duplicate = {
|
||||
children: {
|
||||
order_id: {
|
||||
original: {
|
||||
hidden: true,
|
||||
value: duplicateOrderId
|
||||
},
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue