diff --git a/XSLPrintDot/.github/workflows/release.yml b/XSLPrintDot/.github/workflows/release.yml new file mode 100644 index 0000000..6267291 --- /dev/null +++ b/XSLPrintDot/.github/workflows/release.yml @@ -0,0 +1,154 @@ +name: release + +on: + push: + tags: + - "v*" + +permissions: + contents: write + +jobs: + build: + name: build-${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + platform: windows/amd64 + package: windows + - os: macos-latest + platform: darwin/universal + package: macos-universal + - os: ubuntu-22.04 + platform: linux/amd64 + package: linux + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version: "1.22.x" + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "20.x" + cache: "npm" + cache-dependency-path: frontend/package-lock.json + + - name: Install Wails + run: go install github.com/wailsapp/wails/v2/cmd/wails@latest + + - name: Install Linux build dependencies + if: matrix.os == 'ubuntu-22.04' + run: | + sudo apt-get update + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev pkg-config + + - name: Build + if: matrix.os != 'windows-latest' + run: wails build -clean -platform ${{ matrix.platform }} + + - name: Build (Windows installer) + if: matrix.os == 'windows-latest' + shell: pwsh + run: | + choco install nsis -y + $env:Path = "C:\Program Files (x86)\NSIS;" + $env:Path + if (-not (Get-Command makensis -ErrorAction SilentlyContinue)) { + Write-Error "makensis not found after NSIS install" + } + wails build -clean -nsis -platform windows/amd64 + + - name: Package (Windows) + if: matrix.os == 'windows-latest' + shell: pwsh + run: | + Write-Host "Listing build/bin contents:" + Get-ChildItem -Path build/bin -Recurse | Select-Object FullName | Format-Table -AutoSize + + $installer = Get-ChildItem -Path build/bin -Recurse -File -Filter "*.exe" | + Where-Object { $_.Name -match "installer|setup" } | + Select-Object -First 1 + + if (-not $installer) { + $installer = Get-ChildItem -Path build/bin -Recurse -File -Filter "*.msi" | Select-Object -First 1 + } + + if (-not $installer) { + Write-Error "No Windows installer found in build/bin" + } + $renamed = Join-Path $installer.DirectoryName "XSL-PrintDot-setup-windows.exe" + Copy-Item -Path $installer.FullName -Destination $renamed -Force + Compress-Archive -Path $renamed -DestinationPath build/XSL-PrintDot-windows.zip + + - name: Package (macOS) + if: matrix.os == 'macos-latest' + run: | + APP_PATH=$(find build/bin -maxdepth 2 -type d -name "*.app" | head -n 1) + if [ -z "$APP_PATH" ]; then + echo "No .app found in build/bin" >&2 + exit 1 + fi + if [ ! -d "$APP_PATH/Contents" ]; then + echo "Invalid .app bundle: $APP_PATH" >&2 + exit 1 + fi + echo "Packaging $APP_PATH" + + APP_NAME=$(basename "$APP_PATH" .app) + BIN_PATH="$APP_PATH/Contents/MacOS/$APP_NAME" + if [ ! -f "$BIN_PATH" ]; then + echo "Binary not found: $BIN_PATH" >&2 + exit 1 + fi + + ARM_APP="build/bin/${APP_NAME}-arm64.app" + AMD_APP="build/bin/${APP_NAME}-amd64.app" + + rm -rf "$ARM_APP" "$AMD_APP" + cp -R "$APP_PATH" "$ARM_APP" + cp -R "$APP_PATH" "$AMD_APP" + + lipo -thin arm64 "$BIN_PATH" -output "$ARM_APP/Contents/MacOS/$APP_NAME" + lipo -thin x86_64 "$BIN_PATH" -output "$AMD_APP/Contents/MacOS/$APP_NAME" + + ditto -c -k --sequesterRsrc --keepParent "$ARM_APP" build/XSL-PrintDot-macos-arm64.zip + ditto -c -k --sequesterRsrc --keepParent "$AMD_APP" build/XSL-PrintDot-macos-amd64.zip + + - name: Package (Linux) + if: matrix.os == 'ubuntu-22.04' + run: | + if [ ! -d "build/bin" ]; then + echo "build/bin not found" >&2 + exit 1 + fi + tar -czf build/XSL-PrintDot-linux.tar.gz -C build/bin . + + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: XSL-PrintDot-${{ matrix.os }} + path: build/XSL-PrintDot-* + + release: + name: create-release + runs-on: ubuntu-latest + needs: build + + steps: + - name: Download Artifacts + uses: actions/download-artifact@v4 + with: + path: artifacts + + - name: Publish Release + uses: softprops/action-gh-release@v2 + with: + files: artifacts/**/* diff --git a/XSLPrintDot/.gitignore b/XSLPrintDot/.gitignore new file mode 100644 index 0000000..f7e496f --- /dev/null +++ b/XSLPrintDot/.gitignore @@ -0,0 +1,13 @@ +build/bin +node_modules +frontend/dist +frontend/components.d.ts +frontend/wailsjs/ + +# Build-time artifacts +build/windows/installer/resources/*.zip +build/windows/installer/resources/sumatra_tmp/ +build/windows/installer/tmp/ +build/windows/installer/wails_tools.nsh +frontend/package.json.md5 + diff --git a/XSLPrintDot/LICENSE b/XSLPrintDot/LICENSE new file mode 100644 index 0000000..e3d3562 --- /dev/null +++ b/XSLPrintDot/LICENSE @@ -0,0 +1,649 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains +free software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, +and giving a relevant date. + +b) The work must carry prominent notices stating that it is released +under this License and any conditions added under section 7. This +requirement modifies the requirement in section 4 to "keep intact all +notices". + +c) You must license the entire work, as a whole, under this License +to anyone who comes into possession of a copy. This License will +therefore apply, along with any applicable section 7 additional terms, +to the whole of the work, and all its parts, regardless of how they are +packaged. This License gives no permission to license the work in any +other way, but it does not invalidate such permission if you have +separately received it. + +d) If the work has interactive user interfaces, each must display +Appropriate Legal Notices; however, if the Program has interactive +interfaces that do not display Appropriate Legal Notices, your work +need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + +a) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by the +Corresponding Source fixed on a durable physical medium customarily +used for software interchange. + +b) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by a written +offer, valid for at least three years and valid for as long as you +offer spare parts or customer support for that product model, to give +anyone who possesses the object code either (1) a copy of the +Corresponding Source for all the software in the product that is +covered by this License, on a durable physical medium customarily +used for software interchange, for a price no more than your +reasonable cost of physically performing this conveying of source, or +(2) access to copy the Corresponding Source from a network server at +no charge. + +c) Convey individual copies of the object code with a copy of the +written offer to provide the Corresponding Source. This alternative +is allowed only occasionally and noncommercially, and only if you +received the object code with such an offer, in accord with +subsection 6b. + +d) Convey the object code by offering access from a designated place +(gratis or for a charge), and offer equivalent access to the +Corresponding Source in the same way through the same place at no +further charge. You need not require recipients to copy the +Corresponding Source along with the object code. If the place to copy +the object code is a network server, the Corresponding Source may be +on a different server (operated by you or a third party) that supports +equivalent copying facilities, provided you maintain clear directions +next to the object code saying where to find the Corresponding Source. +Regardless of what server hosts the Corresponding Source, you remain +obligated to ensure that it is available for as long as needed to +satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided +you inform other peers where the object code and Corresponding Source +of the work are being offered to the general public at no charge under +subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, that product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part +of a transaction in which the right of possession and use of the User +Product is transferred to the recipient in perpetuity or for a fixed term +(regardless of how the transaction is characterized), the Corresponding +Source conveyed under this section must be accompanied by the +Installation Information. But this requirement does not apply if neither +you nor any third party retains the ability to install modified object +code on the User Product (for example, the work has been installed in +ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in source +code form), and must require no special password or key for unpacking, +reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own removal +in certain cases when you modify the work.) You may place additional +permissions on material, added by you to a covered work, for which you +have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the +terms of sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or +author attributions in that material or in the Appropriate Legal +Notices displayed by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or +requiring that modified versions of such material be marked in +reasonable ways as different from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or +authors of the material; or + +e) Declining to grant rights under trademark law for use of some +trade names, trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that +material by anyone who conveys the material (or modified versions of +it) with contractual assumptions of liability to the recipient, for +any liability that these contractual assumptions directly impose on +those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this License does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. + +For purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your +version supports such interaction) an opportunity to receive the +Corresponding Source of your version by providing access to the +Corresponding Source from a network server at no charge, through some +standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any +work covered by version 3 of the GNU General Public License that is +incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever +published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING +ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF +THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO +LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU +OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . diff --git a/XSLPrintDot/README.md b/XSLPrintDot/README.md new file mode 100644 index 0000000..e560213 --- /dev/null +++ b/XSLPrintDot/README.md @@ -0,0 +1,120 @@ +
+ +# PrintDot Client + +**中文** | [English](README_EN.md) + +PrintDot Client Logo + +
+ +## 简介 + +PrintDot Client 是一款基于 Wails 与 Vue 的桌面打印助手,主打“稳定、快速、好上手”。它将设备发现、连接管理与转发能力打包到一个轻量客户端里,让你用更少的配置成本,获得更高的打印链路稳定性与可用性。本项目是 [Vue Print Designer](https://github.com/0ldFive/Vue-Print-Designer) 的配套客户端。 +## 界面预览 + + + + + + +
+ 主界面
+ 主界面 - 设备状态与连接管理 +
+ 设置页面
+ 设置页面 - 偏好与配置选项 +
+ +## 优势 + +- 秒级启动与响应,日常操作几乎零等待 +- 稳定可靠的发现与转发链路,长时间运行也很安心 +- 跨平台一致体验,减少环境差异带来的折腾 +- 轻量架构、低资源占用,老机器也能顺滑跑 +- 细节打磨的设置与多语言体验,新手上手更快 +- 现代化界面与清晰信息层级,关键状态一眼可见 + +## 支持平台 + +- Windows +- macOS +- Linux + +## 功能概览 + +- 自动发现与识别本地/网络设备 +- 稳定的连接维护与转发队列 +- 简洁的可视化状态与告警提示 +- 多语言界面与基础偏好设置 +- 适合长期后台运行的轻量模式 + +## 架构与模块 + +- 前端:Vue 3 + Vite + Tailwind,负责界面与交互 +- 桌面容器:Wails,提供跨平台窗口与系统能力 +- 后端:Go 服务层,负责发现、连接、转发与配置 + +## 安装与运行 + +### 开发模式 + +1. 安装 Wails 与 Node.js 依赖 +2. 运行开发命令 + +```bash +wails dev +``` + +### 生产构建 + +```bash +wails build +``` + +#### Windows + +```bash +wails build -clean -nsis +``` + +#### macOS + +```bash +wails build -clean -platform darwin/amd64 +wails build -clean -platform darwin/arm64 +``` + +#### Linux + +```bash +wails build -clean -platform linux/amd64 +``` + +## 配置说明 + +- 配置文件由应用自动生成并维护 +- 可在设置页中调整设备与转发相关选项 +- 修改配置后即时生效,无需重启 + +## 常见问题 + +**Q: 设备没有出现或连接不稳定怎么办?** + +- 请检查同一网络与防火墙放行 +- 重启客户端后重新发现 +- 若仍异常,请参考使用手册排查 + +**Q: 是否支持后台常驻?** + +- 支持,应用优化了低资源占用与持续转发 + +## 贡献与开发 + +- 欢迎提交 Issue 与 Pull Request +- 建议先阅读使用手册与配置说明,保持一致的行为与体验 + +## 使用手册 + +- 中文: [docs/usage_guide_zh.md](docs/usage_guide_zh.md) +- English: [docs/usage_guide_en.md](docs/usage_guide_en.md) diff --git a/XSLPrintDot/README_EN.md b/XSLPrintDot/README_EN.md new file mode 100644 index 0000000..f8db0d2 --- /dev/null +++ b/XSLPrintDot/README_EN.md @@ -0,0 +1,121 @@ +
+ +# PrintDot Client + +[中文](README.md) | **English** + +PrintDot Client Logo + +
+ +## Introduction + +PrintDot Client is a desktop printing assistant built with Wails and Vue, focusing on "stability, speed, and ease of use". It packages device discovery, connection management, and forwarding capabilities into a lightweight client, allowing you to achieve higher printing stability and availability with less configuration effort. This project is the companion client for [Vue Print Designer](https://github.com/0ldFive/Vue-Print-Designer). + +## Screenshots + + + + + + +
+ Main Interface
+ Main Interface - Device Status & Connection Management +
+ Settings Page
+ Settings Page - Preferences & Configuration +
+ +## Advantages + +- Instant startup and response, virtually zero wait for daily operations +- Stable and reliable discovery and forwarding, worry-free for long-term running +- Consistent cross-platform experience, less hassle from environment differences +- Lightweight architecture with low resource usage, runs smoothly even on older machines +- Polished settings and multilingual experience, easier for beginners +- Modern interface with clear information hierarchy, key status visible at a glance + +## Supported Platforms + +- Windows +- macOS +- Linux + +## Features + +- Auto-discovery and identification of local/network devices +- Stable connection maintenance and forwarding queue +- Clean visual status and alert notifications +- Multilingual interface and basic preferences +- Lightweight mode suitable for long-term background running + +## Architecture & Modules + +- Frontend: Vue 3 + Vite + Tailwind for UI and interactions +- Desktop Container: Wails for cross-platform windowing and system capabilities +- Backend: Go service layer for discovery, connection, forwarding, and configuration + +## Installation & Usage + +### Development Mode + +1. Install Wails and Node.js dependencies +2. Run the development command + +```bash +wails dev +``` + +### Production Build + +```bash +wails build +``` + +#### Windows + +```bash +wails build -clean -nsis +``` + +#### macOS + +```bash +wails build -clean -platform darwin/amd64 +wails build -clean -platform darwin/arm64 +``` + +#### Linux + +```bash +wails build -clean -platform linux/amd64 +``` + +## Configuration + +- Configuration files are automatically generated and maintained by the application +- Device and forwarding options can be adjusted in the settings page +- Changes take effect immediately without restart + +## FAQ + +**Q: What if the device doesn't appear or the connection is unstable?** + +- Check if devices are on the same network and firewall is properly configured +- Restart the client and rediscover +- If issues persist, refer to the user manual for troubleshooting + +**Q: Does it support running in background?** + +- Yes, the application is optimized for low resource usage and continuous forwarding + +## Contributing + +- Issues and Pull Requests are welcome +- Please read the user manual and configuration guide first to maintain consistent behavior and experience + +## User Manual + +- 中文: [docs/usage_guide_zh.md](docs/usage_guide_zh.md) +- English: [docs/usage_guide_en.md](docs/usage_guide_en.md) diff --git a/XSLPrintDot/app.go b/XSLPrintDot/app.go new file mode 100644 index 0000000..f9a6304 --- /dev/null +++ b/XSLPrintDot/app.go @@ -0,0 +1,280 @@ +package main + +import ( + "context" + "embed" + "fmt" + "os" + "os/exec" + "strconv" + "sync" + + "github.com/wailsapp/wails/v2/pkg/menu" + "github.com/wailsapp/wails/v2/pkg/menu/keys" + "github.com/wailsapp/wails/v2/pkg/runtime" +) + +//go:embed docs +var usageGuides embed.FS + +// App struct +type App struct { + ctx context.Context + AppMode string + LogPort int + bridge *Bridge + settings *SettingsManager + isQuitting bool + + logsMu sync.Mutex + settingsCmd *exec.Cmd + logsCmd *exec.Cmd + helpCmd *exec.Cmd +} + +// NewApp creates a new App application struct +func NewApp(mode string, logPort int) *App { + return &App{ + AppMode: mode, + LogPort: logPort, + bridge: NewBridge(), + settings: NewSettingsManager(), + } +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + a.ctx = ctx + + // Bind logger + a.bridge.SetLogger(func(msg string) { + runtime.EventsEmit(ctx, "log", msg) + }) + + // Bind client count + a.bridge.SetCountCallback(func(count int) { + runtime.EventsEmit(ctx, "client_count", count) + }) + + // Bind reload callback + a.bridge.SetReloadCallback(func() { + a.Reload() + }) + + a.bridge.SetForwarderStatusProvider(func() RemoteForwarderStatus { + status := a.bridge.GetRemoteForwarderStatus() + status.AutoReconnect = a.settings.Get().RemoteAutoConnect + return status + }) + a.bridge.SetForwarderConnectHandler(func() { + a.bridge.StartRemoteForwarderWithSettings(a.settings.Get(), true) + }) + a.bridge.SetForwarderDisconnectHandler(func() { + a.bridge.StopRemoteForwarder() + }) + + // Bind client connect + a.bridge.SetClientConnectCallback(func(clientInfo string) { + runtime.EventsEmit(ctx, "client_connected", clientInfo) + }) + + if a.AppMode == "main" { + // Start Log Server + if err := a.bridge.StartLogServer(); err != nil { + fmt.Printf("Failed to start log server: %v\n", err) + } else { + a.LogPort = a.bridge.logPort + a.bridge.Log(fmt.Sprintf("Log server started on port %d", a.LogPort)) + } + + a.bridge.ConfigureRemoteForwarder(a.settings.Get()) + } +} + +func (a *App) domReady(ctx context.Context) { + // Add any dom ready logic +} + +func (a *App) beforeClose(ctx context.Context) (prevent bool) { + return false +} + +func (a *App) shutdown(ctx context.Context) { + a.Cleanup() +} + +func (a *App) Cleanup() { + if a.AppMode == "main" { + a.bridge.StopServer() + a.bridge.StopLogServer() + a.bridge.StopRemoteForwarder() + + // Kill child windows + if a.settingsCmd != nil && a.settingsCmd.Process != nil { + a.settingsCmd.Process.Kill() + } + if a.logsCmd != nil && a.logsCmd.Process != nil { + a.logsCmd.Process.Kill() + } + if a.helpCmd != nil && a.helpCmd.Process != nil { + a.helpCmd.Process.Kill() + } + } +} + +func (a *App) Quit() { + a.isQuitting = true + if a.ctx != nil { + runtime.Quit(a.ctx) + } else { + os.Exit(0) + } +} + +// Wails Methods + +func (a *App) GetUsageGuide() string { + lang := a.settings.Get().Language + filename := "docs/usage_guide_en.md" + if lang == "zh-CN" { + filename = "docs/usage_guide_zh.md" + } + + content, err := usageGuides.ReadFile(filename) + if err != nil { + return "# Error\n\nFailed to load usage guide: " + err.Error() + } + return string(content) +} + +func (a *App) GetSettings() AppSettings { + return a.settings.Get() +} + +func (a *App) SaveSettings(s AppSettings) error { + return a.settings.Save(s) +} + +func (a *App) GetPrinters() ([]PrinterInfo, error) { + return a.bridge.GetPrinters() +} + +// PrintCurrentView uses the CDP hack to silent print the current WebView content +func (a *App) StartServer(port, key string) error { + return a.bridge.StartServer(port, key) +} + +func (a *App) StopServer() error { + return a.bridge.StopServer() +} + +func (a *App) GetAppMode() string { + return a.AppMode +} + +func (a *App) Restart() { + runtime.Quit(a.ctx) +} + +func (a *App) ShowHelp() { + a.logsMu.Lock() + defer a.logsMu.Unlock() + a.spawnWindow("help", &a.helpCmd) +} + +func (a *App) ShowLogs() { + a.logsMu.Lock() + defer a.logsMu.Unlock() + a.spawnWindow("logs", &a.logsCmd) +} + +func (a *App) ShowSettings() { + a.logsMu.Lock() + defer a.logsMu.Unlock() + a.spawnWindow("settings", &a.settingsCmd) +} + +func (a *App) spawnWindow(mode string, cmdStore **exec.Cmd) { + exe, err := os.Executable() + if err != nil { + a.bridge.Log(fmt.Sprintf("Failed to get executable: %v", err)) + return + } + + cmd := exec.Command(exe, mode, strconv.Itoa(a.LogPort)) + cmd.Start() + *cmdStore = cmd +} + +func (a *App) GetLogPort() int { + return a.LogPort +} + +func (a *App) GetRemoteForwarderStatus() RemoteForwarderStatus { + return a.bridge.GetRemoteForwarderStatus() +} + +func (a *App) DisconnectRemoteForwarder() { + a.bridge.StopRemoteForwarder() +} + +func (a *App) ConnectRemoteForwarder() { + a.bridge.StartRemoteForwarderWithSettings(a.settings.Get(), true) +} + +func (a *App) CreateMenu(lang string) *menu.Menu { + // Ensure locales are loaded + LoadLocales(lang) + appMenu := menu.NewMenu() + + // Main App Configuration + menuTitle := T("menu.title") + settingsTitle := T("menu.settings") + logsTitle := T("menu.logs") + helpTitle := T("menu.help") + quitTitle := T("menu.quit") + + // Menu (菜单) + MenuMenu := appMenu.AddSubmenu(menuTitle) + MenuMenu.AddText(logsTitle, keys.CmdOrCtrl("l"), func(_ *menu.CallbackData) { + a.ShowLogs() + }) + MenuMenu.AddSeparator() + MenuMenu.AddText(quitTitle, keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + a.Quit() + }) + + // Help (帮助) + HelpMenu := appMenu.AddSubmenu(helpTitle) + HelpMenu.AddText(helpTitle, keys.CmdOrCtrl("h"), func(_ *menu.CallbackData) { + a.ShowHelp() + }) + + // Settings (设置) + SettingsMenu := appMenu.AddSubmenu(settingsTitle) + SettingsMenu.AddText(settingsTitle, keys.CmdOrCtrl("i"), func(_ *menu.CallbackData) { + a.ShowSettings() + }) + + return appMenu +} + +func (a *App) UpdateUI(lang string) { + if a.ctx != nil && a.AppMode == "main" { + runtime.MenuSetApplicationMenu(a.ctx, a.CreateMenu(lang)) + // Emit event for frontend updates + runtime.EventsEmit(a.ctx, "reload_settings") + } +} + +func (a *App) Reload() { + // Reload settings from disk + a.settings.Load() + // Reload locale + LoadLocales(a.settings.Get().Language) + // Update menu and UI + a.UpdateUI(a.settings.Get().Language) + a.bridge.ConfigureRemoteForwarder(a.settings.Get()) + a.bridge.Log("Settings reloaded") +} diff --git a/XSLPrintDot/autostart_other.go b/XSLPrintDot/autostart_other.go new file mode 100644 index 0000000..405f60b --- /dev/null +++ b/XSLPrintDot/autostart_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package main + +func setAutoStart(enabled bool) { + _ = enabled +} diff --git a/XSLPrintDot/autostart_windows.go b/XSLPrintDot/autostart_windows.go new file mode 100644 index 0000000..930d1db --- /dev/null +++ b/XSLPrintDot/autostart_windows.go @@ -0,0 +1,27 @@ +//go:build windows + +package main + +import ( + "os" + "os/exec" + "syscall" +) + +func setAutoStart(enabled bool) { + exe, err := os.Executable() + if err != nil { + return + } + + if enabled { + cmd := exec.Command("reg", "add", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "/v", "PrintDotClient", "/t", "REG_SZ", "/d", exe, "/f") + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + _ = cmd.Run() + return + } + + cmd := exec.Command("reg", "delete", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "/v", "PrintDotClient", "/f") + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + _ = cmd.Run() +} diff --git a/XSLPrintDot/backend.go b/XSLPrintDot/backend.go new file mode 100644 index 0000000..fb87bec --- /dev/null +++ b/XSLPrintDot/backend.go @@ -0,0 +1,950 @@ +package main + +import ( + "bufio" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "html/template" + "io/ioutil" + "log" + "math" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +type Bridge struct { + server *http.Server + port string + key string + mu sync.Mutex + log func(string) // Callback to log to frontend + + // Log related + logFileMu sync.Mutex + logServer *http.Server + logPort int + + // Connection tracking + clientCount int + countMu sync.Mutex + onCountChange func(int) // Callback to update frontend + conns map[*websocket.Conn]bool + + // Restart callback + onRestart func() + onReload func() + onClientConnect func(string) + + // Remote forwarding + remoteMu sync.Mutex + remoteStop chan struct{} + remoteWg sync.WaitGroup + remoteCfg RemoteConfig + remoteConn *websocket.Conn + remoteStatus RemoteForwarderStatus + forwarderStatusProvider func() RemoteForwarderStatus + forwarderConnect func() + forwarderDisconnect func() +} + +func NewBridge() *Bridge { + b := &Bridge{ + port: "1122", + key: "", + conns: make(map[*websocket.Conn]bool), + } + b.ensureLogDir() + return b +} + +func (b *Bridge) SetLogger(logger func(string)) { + b.log = logger +} + +func (b *Bridge) SetCountCallback(cb func(int)) { + b.onCountChange = cb +} + +func (b *Bridge) SetRestartCallback(cb func()) { + b.onRestart = cb +} + +func (b *Bridge) SetReloadCallback(cb func()) { + b.onReload = cb +} + +func (b *Bridge) SetClientConnectCallback(cb func(string)) { + b.onClientConnect = cb +} + +func (b *Bridge) SetForwarderStatusProvider(cb func() RemoteForwarderStatus) { + b.forwarderStatusProvider = cb +} + +func (b *Bridge) SetForwarderConnectHandler(cb func()) { + b.forwarderConnect = cb +} + +func (b *Bridge) SetForwarderDisconnectHandler(cb func()) { + b.forwarderDisconnect = cb +} + +func (b *Bridge) updateClientCount(delta int) { + b.countMu.Lock() + b.clientCount += delta + count := b.clientCount + b.countMu.Unlock() + + if b.onCountChange != nil { + b.onCountChange(count) + } +} + +func (b *Bridge) Log(msg string) { + timestamp := time.Now().Format("15:04:05") + entry := fmt.Sprintf("[%s] %s", timestamp, msg) + if err := b.appendLogLine(entry); err != nil { + log.Println(entry) + } else if b.log != nil { + b.log(msg) + } +} + +func (b *Bridge) GetPrinters() ([]PrinterInfo, error) { + return b.getPrintersPlatform() +} + +type PrinterInfo struct { + Name string `json:"name"` + IsDefault bool `json:"isDefault"` +} + +func (b *Bridge) GetPrinterCapabilities(printerName string) (map[string]interface{}, error) { + return b.getPrinterCapabilitiesPlatform(printerName) +} + +func (b *Bridge) StartServer(port string, key string) error { + b.mu.Lock() + defer b.mu.Unlock() + + if b.server != nil { + return fmt.Errorf("server already running") + } + + b.port = port + b.key = key + + mux := http.NewServeMux() + mux.HandleFunc("/ws", b.handleWebSocket) + + b.server = &http.Server{ + Addr: ":" + port, + Handler: mux, + } + + go func() { + b.Log(fmt.Sprintf("Starting server on port %s...", port)) + if err := b.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + b.Log(fmt.Sprintf("Server error: %v", err)) + } + b.Log("Server stopped") + }() + + return nil +} + +func (b *Bridge) StopServer() error { + b.mu.Lock() + defer b.mu.Unlock() + + if b.server == nil { + return nil + } + + // Close all active connections first + b.countMu.Lock() + for conn := range b.conns { + conn.Close() + } + // Clear the map + b.conns = make(map[*websocket.Conn]bool) + b.countMu.Unlock() + + if err := b.server.Shutdown(context.Background()); err != nil { + return err + } + b.server = nil + return nil +} + +var upgrader = websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { + return true // Allow all origins + }, +} + +type PrintRequest struct { + Printer string `json:"printer"` + Content string `json:"content"` // Base64 encoded PDF + Key string `json:"key"` + + Job struct { + Name string `json:"name"` + Copies int `json:"copies"` + IntervalMs int `json:"intervalMs"` + } `json:"job"` + Pages struct { + Range string `json:"range"` + Set string `json:"set"` + } `json:"pages"` + Layout struct { + Scale string `json:"scale"` + Orientation string `json:"orientation"` + } `json:"layout"` + Color struct { + Mode string `json:"mode"` + } `json:"color"` + Sides struct { + Mode string `json:"mode"` + } `json:"sides"` + Paper PaperSpec `json:"paper"` + Tray struct { + Bin string `json:"bin"` + } `json:"tray"` +} + +type PaperSpec struct { + Size string `json:"size"` +} + +type PrintOptions struct { + PageRange string + PageSet string + Duplex string + ColorMode string + Paper string + Scale string + Orientation string + TrayBin string + Copies int +} + +type Response struct { + Status string `json:"status"` + Message string `json:"message"` +} + +func (b *Bridge) handleWebSocket(w http.ResponseWriter, r *http.Request) { + // Authentication check + if b.key != "" { + pass := r.URL.Query().Get("key") + if pass == "" { + pass = r.URL.Query().Get("password") + } + + if pass != b.key { + b.Log(fmt.Sprintf("Authentication failed for %s", r.RemoteAddr)) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + } + + c, err := upgrader.Upgrade(w, r, nil) + if err != nil { + b.Log(fmt.Sprintf("Upgrade error: %v", err)) + return + } + defer c.Close() + + b.countMu.Lock() + b.conns[c] = true + b.countMu.Unlock() + b.updateClientCount(1) + defer func() { + b.countMu.Lock() + delete(b.conns, c) + b.countMu.Unlock() + b.updateClientCount(-1) + }() + + b.Log(fmt.Sprintf("Client connected from %s", c.RemoteAddr())) + + if b.onClientConnect != nil { + b.onClientConnect(c.RemoteAddr().String()) + } + + // Send printer list immediately upon connection + printers, err := b.GetPrinters() + if err == nil { + msg := map[string]interface{}{ + "type": "printer_list", + "data": printers, + } + if jsonBytes, err := json.Marshal(msg); err == nil { + b.Log(fmt.Sprintf("Sent WS message: %s", string(jsonBytes))) + } + c.WriteJSON(msg) + } else { + b.Log(fmt.Sprintf("Failed to get printers on connect: %v", err)) + errMsg := fmt.Sprintf("Failed to get printer list: %v", err) + c.WriteJSON(Response{Status: "error", Message: errMsg}) + } + + for { + // Read message as raw JSON map first to check type + var rawMsg map[string]interface{} + err := c.ReadJSON(&rawMsg) + if err != nil { + if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { + b.Log(fmt.Sprintf("Client disconnected: %v", err)) + } else { + // Normal closure or other error + } + break + } + + if jsonBytes, err := json.Marshal(rawMsg); err == nil { + b.Log(fmt.Sprintf("Received WS message: %s", string(jsonBytes))) + } + + // Check message type + if msgType, ok := rawMsg["type"].(string); ok && msgType == "get_printers" { + printers, err := b.GetPrinters() + if err == nil { + msg := map[string]interface{}{ + "type": "printer_list", + "data": printers, + } + if jsonBytes, err := json.Marshal(msg); err == nil { + b.Log(fmt.Sprintf("Sent WS message: %s", string(jsonBytes))) + } + c.WriteJSON(msg) + } else { + resp := Response{Status: "error", Message: fmt.Sprintf("Failed to get printer list: %v", err)} + if jsonBytes, err := json.Marshal(resp); err == nil { + b.Log(fmt.Sprintf("Sent WS message: %s", string(jsonBytes))) + } + c.WriteJSON(resp) + } + continue + } + + if msgType, ok := rawMsg["type"].(string); ok && msgType == "get_printer_caps" { + printer, _ := rawMsg["printer"].(string) + printer = strings.TrimSpace(printer) + if printer == "" { + resp := Response{Status: "error", Message: "printer is required"} + c.WriteJSON(resp) + continue + } + + caps, err := b.GetPrinterCapabilities(printer) + if err != nil { + b.Log(fmt.Sprintf("Failed to get printer capabilities for '%s': %v", printer, err)) + resp := Response{Status: "error", Message: err.Error()} + c.WriteJSON(resp) + continue + } + + msg := map[string]interface{}{ + "type": "printer_caps", + "printer": printer, + "data": caps, + } + c.WriteJSON(msg) + continue + } + + // Handle as PrintRequest (default) + jsonBody, _ := json.Marshal(rawMsg) + var req PrintRequest + if err := json.Unmarshal(jsonBody, &req); err != nil { + b.Log(fmt.Sprintf("Invalid print request: %v", err)) + resp := Response{Status: "error", Message: "Invalid request format"} + c.WriteJSON(resp) + continue + } + + msg, err := b.processPrintRequest(req) + if err == nil { + resp := Response{Status: "success", Message: msg} + c.WriteJSON(resp) + } else { + c.WriteJSON(Response{Status: "error", Message: msg}) + } + } +} + +func (b *Bridge) processPrintRequest(req PrintRequest) (string, error) { + jobName := strings.TrimSpace(req.Job.Name) + + copies := req.Job.Copies + if copies <= 0 { + copies = 1 + } + + intervalMs := req.Job.IntervalMs + + contentToDecode := req.Content + if strings.HasPrefix(contentToDecode, "data:") { + if idx := strings.Index(contentToDecode, ","); idx != -1 { + contentToDecode = contentToDecode[idx+1:] + } + } + decoded, err := base64.StdEncoding.DecodeString(contentToDecode) + if err != nil { + b.Log("Error decoding Base64 content") + return "Invalid Base64 content", fmt.Errorf("invalid base64 content") + } + + if len(decoded) < 4 || string(decoded[0:4]) != "%PDF" { + b.Log("Content is not a valid PDF (missing %PDF header)") + return "Content must be a PDF file", fmt.Errorf("invalid pdf") + } + + autoPaper := "" + if strings.TrimSpace(req.Paper.Size) == "" { + if name, ok := detectPaperFromPDF(decoded); ok { + autoPaper = name + b.Log(fmt.Sprintf("Auto paper size detected: %s", name)) + } + } + + options := PrintOptions{ + PageRange: strings.TrimSpace(req.Pages.Range), + PageSet: strings.TrimSpace(req.Pages.Set), + Duplex: strings.TrimSpace(req.Sides.Mode), + ColorMode: strings.TrimSpace(req.Color.Mode), + Paper: strings.TrimSpace(firstNonEmpty(req.Paper.Size, autoPaper)), + Scale: strings.TrimSpace(req.Layout.Scale), + Orientation: strings.TrimSpace(req.Layout.Orientation), + TrayBin: strings.TrimSpace(req.Tray.Bin), + } + + runCount := 1 + perRunCopies := copies + if intervalMs > 0 { + runCount = copies + perRunCopies = 1 + } + options.Copies = perRunCopies + + successCount := 0 + var lastErr error + + for i := 0; i < runCount; i++ { + if i > 0 && intervalMs > 0 { + time.Sleep(time.Duration(intervalMs) * time.Millisecond) + } + + err = b.printPDF(req.Printer, jobName, decoded, options) + if err != nil { + lastErr = err + b.Log(fmt.Sprintf("Print error (copy %d): %v", i+1, err)) + break + } else { + successCount += perRunCopies + } + } + + if successCount == copies { + b.Log("Print success") + return "Printed successfully", nil + } + + msg := fmt.Sprintf("Printed %d/%d copies. Error: %v", successCount, copies, lastErr) + b.Log(msg) + return msg, fmt.Errorf("print failed") +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} + +var ( + mediaBoxRegex = regexp.MustCompile(`/MediaBox\s*\[\s*([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s*\]`) + cropBoxRegex = regexp.MustCompile(`/CropBox\s*\[\s*([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s*\]`) +) + +func detectPaperFromPDF(pdfData []byte) (string, bool) { + limit := len(pdfData) + if limit > 5*1024*1024 { + limit = 5 * 1024 * 1024 + } + chunk := string(pdfData[:limit]) + match := cropBoxRegex.FindStringSubmatch(chunk) + if len(match) != 5 { + match = mediaBoxRegex.FindStringSubmatch(chunk) + } + if len(match) != 5 { + return "", false + } + + llx, err1 := strconv.ParseFloat(match[1], 64) + lly, err2 := strconv.ParseFloat(match[2], 64) + urx, err3 := strconv.ParseFloat(match[3], 64) + ury, err4 := strconv.ParseFloat(match[4], 64) + if err1 != nil || err2 != nil || err3 != nil || err4 != nil { + return "", false + } + + widthPt := math.Abs(urx - llx) + heightPt := math.Abs(ury - lly) + return matchStandardPaper(widthPt, heightPt) +} + +type paperSize struct { + Name string + Wmm float64 + Hmm float64 +} + +func matchStandardPaper(widthPt, heightPt float64) (string, bool) { + mmPerPt := 25.4 / 72.0 + widthMm := widthPt * mmPerPt + heightMm := heightPt * mmPerPt + + if widthMm <= 0 || heightMm <= 0 { + return "", false + } + + if widthMm > heightMm { + widthMm, heightMm = heightMm, widthMm + } + + standard := []paperSize{ + {Name: "A2", Wmm: 420, Hmm: 594}, + {Name: "A3", Wmm: 297, Hmm: 420}, + {Name: "A4", Wmm: 210, Hmm: 297}, + {Name: "A5", Wmm: 148, Hmm: 210}, + {Name: "A6", Wmm: 105, Hmm: 148}, + {Name: "letter", Wmm: 216, Hmm: 279}, + {Name: "legal", Wmm: 216, Hmm: 356}, + {Name: "tabloid", Wmm: 279, Hmm: 432}, + {Name: "statement", Wmm: 140, Hmm: 216}, + } + + const tolerance = 2.0 + for _, size := range standard { + if math.Abs(widthMm-size.Wmm) <= tolerance && math.Abs(heightMm-size.Hmm) <= tolerance { + return size.Name, true + } + } + + return "", false +} + +func (b *Bridge) printPDF(printerName string, jobName string, pdfData []byte, options PrintOptions) error { + // 1. Write to temp file + tmpFile, err := ioutil.TempFile("", "print-dot-*.pdf") + if err != nil { + return fmt.Errorf("create temp file failed: %v", err) + } + defer os.Remove(tmpFile.Name()) // Clean up on exit + + if _, err := tmpFile.Write(pdfData); err != nil { + tmpFile.Close() + return fmt.Errorf("write temp file failed: %v", err) + } + tmpFile.Close() + absPath, _ := filepath.Abs(tmpFile.Name()) + + if jobName != "" { + b.Log(fmt.Sprintf("Printing job '%s': %s to %s", jobName, absPath, printerName)) + } else { + b.Log(fmt.Sprintf("Printing PDF file: %s to %s", absPath, printerName)) + } + + return b.printPDFPlatform(printerName, absPath, options) +} + +func (b *Bridge) StartLogServer() error { + b.ensureLogDir() + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + return err + } + b.logPort = listener.Addr().(*net.TCPAddr).Port + + mux := http.NewServeMux() + mux.HandleFunc("/logs", b.handleLogs) + mux.HandleFunc("/api/logs", b.handleLogsJSON) + mux.HandleFunc("/api/logs/clear", b.handleClearLogs) + mux.HandleFunc("/api/restart", b.handleRestartRequest) + mux.HandleFunc("/api/reload", b.handleReloadRequest) + mux.HandleFunc("/api/forwarder/status", b.handleForwarderStatus) + mux.HandleFunc("/api/forwarder/connect", b.handleForwarderConnect) + mux.HandleFunc("/api/forwarder/disconnect", b.handleForwarderDisconnect) + mux.HandleFunc("/api/forwarder/stream", b.handleForwarderStream) + + b.logServer = &http.Server{ + Handler: mux, + } + + go func() { + if err := b.logServer.Serve(listener); err != nil && err != http.ErrServerClosed { + b.Log(fmt.Sprintf("Log server error: %v", err)) + } + }() + + return nil +} + +func (b *Bridge) ensureLogDir() { + logDir, err := b.logDirPath() + if err != nil { + return + } + _ = os.MkdirAll(logDir, 0755) + path := filepath.Join(logDir, time.Now().Format("20060102")+".txt") + if f, err := os.OpenFile(path, os.O_CREATE, 0644); err == nil { + f.Close() + } +} + +func (b *Bridge) StopLogServer() error { + if b.logServer == nil { + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if err := b.logServer.Shutdown(ctx); err != nil { + _ = b.logServer.Close() + return err + } + b.logServer = nil + return nil +} + +func (b *Bridge) handleLogs(w http.ResponseWriter, r *http.Request) { + currentLogs, _ := b.readLogLines() + + html := ` + + + System Logs - XSL-PrintDot Client + + + + +

System Logs

+
Auto-refreshing every 2 seconds
+
+ {{range .}} +
{{.}}
+ {{else}} +
No logs available.
+ {{end}} +
+ +` + + t, err := template.New("logs").Parse(html) + if err != nil { + http.Error(w, "Template error", http.StatusInternalServerError) + return + } + t.Execute(w, currentLogs) +} + +func (b *Bridge) handleLogsJSON(w http.ResponseWriter, r *http.Request) { + currentLogs, _ := b.readLogLines() + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Access-Control-Allow-Origin", "*") // Allow child process to fetch + json.NewEncoder(w).Encode(currentLogs) +} + +func (b *Bridge) handleClearLogs(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + b.clearLogFile() + + w.WriteHeader(http.StatusOK) +} + +func (b *Bridge) logFilePath() (string, error) { + logDir, err := b.logDirPath() + if err != nil { + return "", err + } + fileName := time.Now().Format("20060102") + ".txt" + return filepath.Join(logDir, fileName), nil +} + +func (b *Bridge) logDirPath() (string, error) { + baseDir, err := dataDirPath() + if err != nil { + return "", err + } + return filepath.Join(baseDir, "logs"), nil +} + +func dataDirPath() (string, error) { + if programData := strings.TrimSpace(os.Getenv("ProgramData")); programData != "" { + return filepath.Join(programData, "PrintDot"), nil + } + if runtime.GOOS == "darwin" { + if home, err := os.UserHomeDir(); err == nil { + return filepath.Join(home, "Library", "Application Support", "PrintDot"), nil + } + } + if runtime.GOOS == "linux" { + if dataHome := strings.TrimSpace(os.Getenv("XDG_DATA_HOME")); dataHome != "" { + return filepath.Join(dataHome, "PrintDot"), nil + } + if home, err := os.UserHomeDir(); err == nil { + return filepath.Join(home, ".local", "share", "PrintDot"), nil + } + } + if wd, err := os.Getwd(); err == nil { + return filepath.Join(wd, "PrintDot"), nil + } + return "", fmt.Errorf("failed to resolve data directory") +} + +func (b *Bridge) appendLogLine(line string) error { + b.ensureLogDir() + path, err := b.logFilePath() + if err != nil { + return err + } + if !strings.HasSuffix(line, "\n") { + line += "\n" + } + + b.logFileMu.Lock() + defer b.logFileMu.Unlock() + + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) + if err != nil { + return err + } + defer f.Close() + + _, err = f.WriteString(line) + return err +} + +func (b *Bridge) readLogLines() ([]string, error) { + b.ensureLogDir() + path, err := b.logFilePath() + if err != nil { + return nil, err + } + + b.logFileMu.Lock() + defer b.logFileMu.Unlock() + + f, err := os.Open(path) + if err != nil { + if os.IsNotExist(err) { + return []string{}, nil + } + return nil, err + } + defer f.Close() + + lines := []string{} + scanner := bufio.NewScanner(f) + for scanner.Scan() { + text := strings.TrimSpace(scanner.Text()) + if text == "" { + continue + } + lines = append(lines, text) + } + + if err := scanner.Err(); err != nil { + return lines, err + } + + // Reverse logs for display (newest top) + for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 { + lines[i], lines[j] = lines[j], lines[i] + } + return lines, nil +} + +func (b *Bridge) clearLogFile() { + path, err := b.logFilePath() + if err != nil { + return + } + + b.logFileMu.Lock() + defer b.logFileMu.Unlock() + _ = os.Remove(path) +} + +func (b *Bridge) handleReloadRequest(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + w.WriteHeader(http.StatusOK) + w.Write([]byte("Reload initiated")) + + // Trigger reload on main thread + if b.onReload != nil { + go func() { + time.Sleep(100 * time.Millisecond) + b.onReload() + }() + } +} + +func (b *Bridge) handleForwarderStatus(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + if r.Method != http.MethodGet { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + status := RemoteForwarderStatus{} + if b.forwarderStatusProvider != nil { + status = b.forwarderStatusProvider() + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(status) +} + +func (b *Bridge) handleForwarderConnect(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + if b.forwarderConnect != nil { + b.forwarderConnect() + } + w.WriteHeader(http.StatusOK) +} + +func (b *Bridge) handleForwarderDisconnect(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + if b.forwarderDisconnect != nil { + b.forwarderDisconnect() + } + w.WriteHeader(http.StatusOK) +} + +func (b *Bridge) handleForwarderStream(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + + flusher, ok := w.(http.Flusher) + if !ok { + http.Error(w, "streaming unsupported", http.StatusInternalServerError) + return + } + + status := RemoteForwarderStatus{} + if b.forwarderStatusProvider != nil { + status = b.forwarderStatusProvider() + } + if data, err := json.Marshal(status); err == nil { + fmt.Fprintf(w, "data: %s\n\n", data) + flusher.Flush() + } + + last := status + ctx := r.Context() + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + current := RemoteForwarderStatus{} + if b.forwarderStatusProvider != nil { + current = b.forwarderStatusProvider() + } + if current != last { + if data, err := json.Marshal(current); err == nil { + fmt.Fprintf(w, "data: %s\n\n", data) + flusher.Flush() + last = current + } + } + } + } +} diff --git a/XSLPrintDot/backend_restart.go b/XSLPrintDot/backend_restart.go new file mode 100644 index 0000000..767e27c --- /dev/null +++ b/XSLPrintDot/backend_restart.go @@ -0,0 +1,24 @@ +package main + +import ( + "net/http" + "time" +) + +func (b *Bridge) handleRestartRequest(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + w.WriteHeader(http.StatusOK) + w.Write([]byte("Restart initiated")) + + // Trigger restart on main thread + if b.onRestart != nil { + go func() { + time.Sleep(500 * time.Millisecond) // Give time for response to be sent + b.onRestart() + }() + } +} diff --git a/XSLPrintDot/backend_unix.go b/XSLPrintDot/backend_unix.go new file mode 100644 index 0000000..493fa9e --- /dev/null +++ b/XSLPrintDot/backend_unix.go @@ -0,0 +1,157 @@ +//go:build !windows + +package main + +import ( + "fmt" + "os/exec" + "strings" +) + +func (b *Bridge) getPrintersPlatform() ([]PrinterInfo, error) { + defaultName := "" + if out, err := exec.Command("lpstat", "-d").Output(); err == nil { + line := strings.TrimSpace(string(out)) + if idx := strings.LastIndex(line, ":"); idx >= 0 { + defaultName = strings.TrimSpace(line[idx+1:]) + } + } + + cmd := exec.Command("sh", "-c", "lpstat -a | cut -d ' ' -f 1") + output, err := cmd.Output() + if err != nil { + return nil, err + } + + lines := strings.Split(string(output), "\n") + var printers []PrinterInfo + for _, line := range lines { + trimmed := strings.TrimSpace(line) + if trimmed != "" { + printers = append(printers, PrinterInfo{Name: trimmed, IsDefault: trimmed == defaultName}) + } + } + return printers, nil +} + +func (b *Bridge) getPrinterCapabilitiesPlatform(printerName string) (map[string]interface{}, error) { + printerName = strings.TrimSpace(printerName) + if printerName == "" { + return nil, fmt.Errorf("printer name is empty") + } + + cmd := exec.Command("lpoptions", "-p", printerName, "-l") + output, err := cmd.CombinedOutput() + if err != nil { + return nil, fmt.Errorf("lpoptions error: %v, output: %s", err, string(output)) + } + + options := map[string]map[string]interface{}{} + lines := strings.Split(string(output), "\n") + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + parts := strings.SplitN(line, ":", 2) + if len(parts) != 2 { + continue + } + left := strings.TrimSpace(parts[0]) + right := strings.TrimSpace(parts[1]) + optName := left + if idx := strings.Index(left, "/"); idx >= 0 { + optName = strings.TrimSpace(left[:idx]) + } + + values := []string{} + defaultValue := "" + for _, token := range strings.Fields(right) { + if strings.HasPrefix(token, "*") { + clean := strings.TrimPrefix(token, "*") + defaultValue = clean + values = append(values, clean) + continue + } + values = append(values, token) + } + + options[optName] = map[string]interface{}{ + "values": values, + "default": defaultValue, + "raw": right, + } + } + + return map[string]interface{}{ + "printer": printerName, + "options": options, + }, nil +} + +func (b *Bridge) printPDFPlatform(printerName, filePath string, options PrintOptions) error { + args := []string{"-d", printerName} + + if options.Copies > 1 { + args = append(args, "-n", fmt.Sprintf("%d", options.Copies)) + } + + if options.PageRange != "" { + args = append(args, "-P", options.PageRange) + } + + switch strings.ToLower(strings.TrimSpace(options.PageSet)) { + case "even": + args = append(args, "-o", "page-set=even") + case "odd": + args = append(args, "-o", "page-set=odd") + } + + switch strings.ToLower(strings.TrimSpace(options.Duplex)) { + case "long-edge", "long", "duplex", "duplexlong": + args = append(args, "-o", "sides=two-sided-long-edge") + case "short-edge", "short", "duplexshort": + args = append(args, "-o", "sides=two-sided-short-edge") + case "simplex", "one-sided": + args = append(args, "-o", "sides=one-sided") + } + + switch strings.ToLower(strings.TrimSpace(options.ColorMode)) { + case "color": + args = append(args, "-o", "ColorModel=RGB") + case "mono", "monochrome", "grayscale", "gray": + args = append(args, "-o", "ColorModel=Gray") + } + + if options.Paper != "" { + args = append(args, "-o", fmt.Sprintf("media=%s", options.Paper)) + } + + switch strings.ToLower(strings.TrimSpace(options.Scale)) { + case "noscale", "none", "actual": + args = append(args, "-o", "scaling=100") + case "shrink": + // Default CUPS behavior already shrinks to fit if needed + case "fit": + args = append(args, "-o", "fit-to-page") + } + + switch strings.ToLower(strings.TrimSpace(options.Orientation)) { + case "portrait": + args = append(args, "-o", "orientation-requested=3") + case "landscape": + args = append(args, "-o", "orientation-requested=4") + } + + if options.TrayBin != "" { + args = append(args, "-o", fmt.Sprintf("InputSlot=%s", options.TrayBin)) + } + + args = append(args, filePath) + + cmd := exec.Command("lp", args...) + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("lp error: %v, output: %s", err, string(out)) + } + return nil +} diff --git a/XSLPrintDot/backend_windows.go b/XSLPrintDot/backend_windows.go new file mode 100644 index 0000000..df39c97 --- /dev/null +++ b/XSLPrintDot/backend_windows.go @@ -0,0 +1,498 @@ +//go:build windows + +package main + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "time" + "unsafe" +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procMultiByteToWideChar = kernel32.NewProc("MultiByteToWideChar") +) + +// ansiToUtf8 converts ANSI (CP_ACP) bytes to UTF-8 string +func ansiToUtf8(b []byte) (string, error) { + if len(b) == 0 { + return "", nil + } + + // CP_ACP = 0 + // 1. Get required length + ret, _, _ := procMultiByteToWideChar.Call( + 0, // CP_ACP + 0, + uintptr(unsafe.Pointer(&b[0])), + uintptr(len(b)), + 0, + 0, + ) + if ret == 0 { + return "", fmt.Errorf("MultiByteToWideChar failed") + } + + // 2. Allocate buffer + utf16buf := make([]uint16, ret) + + // 3. Convert + ret, _, _ = procMultiByteToWideChar.Call( + 0, + 0, + uintptr(unsafe.Pointer(&b[0])), + uintptr(len(b)), + uintptr(unsafe.Pointer(&utf16buf[0])), + ret, + ) + if ret == 0 { + return "", fmt.Errorf("MultiByteToWideChar failed") + } + + return syscall.UTF16ToString(utf16buf), nil +} + +// decodeCmdOutput handles WMIC encoding quirks (UTF-16LE BOM or ANSI) +func decodeCmdOutput(output []byte) (string, error) { + if len(output) >= 2 && output[0] == 0xFF && output[1] == 0xFE { + // UTF-16LE BOM detected + // Skip BOM + raw16 := output[2:] + // Make sure even number of bytes + if len(raw16)%2 != 0 { + raw16 = append(raw16, 0) + } + u16s := make([]uint16, len(raw16)/2) + for i := 0; i < len(u16s); i++ { + u16s[i] = uint16(raw16[i*2]) | uint16(raw16[i*2+1])<<8 + } + return syscall.UTF16ToString(u16s), nil + } + + // Assume ANSI (e.g. GBK on Chinese Windows) + return ansiToUtf8(output) +} + +func (b *Bridge) getPrintersPlatform() ([]PrinterInfo, error) { + // Use WMIC to get printer names and default flags in CSV format + cmd := exec.Command("wmic", "printer", "get", "name,default", "/format:csv") + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + + output, err := cmd.Output() + if err != nil { + return getPrintersViaPowerShell() + } + + decodedStr, err := decodeCmdOutput(output) + if err != nil { + // Fallback + decodedStr = string(output) + } + + reader := csv.NewReader(strings.NewReader(decodedStr)) + reader.FieldsPerRecord = -1 + reader.LazyQuotes = true + records, err := reader.ReadAll() + if err != nil { + return getPrintersViaPowerShell() + } + + var printers []PrinterInfo + for _, record := range records { + if len(record) < 3 { + continue + } + if strings.EqualFold(record[1], "Default") && strings.EqualFold(record[2], "Name") { + continue + } + name := strings.TrimSpace(record[len(record)-1]) + if name == "" { + continue + } + if strings.EqualFold(name, "Name") { + continue + } + isDefault := strings.EqualFold(strings.TrimSpace(record[1]), "TRUE") + printers = append(printers, PrinterInfo{Name: name, IsDefault: isDefault}) + } + if len(printers) == 0 { + return getPrintersViaPowerShell() + } + return printers, nil +} + +func getPrintersViaPowerShell() ([]PrinterInfo, error) { + ps := `Get-Printer | Select-Object Name,Default | ConvertTo-Json -Depth 3` + cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", ps) + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + output, err := cmd.Output() + if err != nil { + return nil, err + } + + decoded, err := decodeCmdOutput(output) + if err != nil { + decoded = string(output) + } + + var list []struct { + Name string `json:"Name"` + Default bool `json:"Default"` + } + if err := json.Unmarshal([]byte(decoded), &list); err == nil { + printers := make([]PrinterInfo, 0, len(list)) + for _, item := range list { + name := strings.TrimSpace(item.Name) + if name == "" { + continue + } + printers = append(printers, PrinterInfo{Name: name, IsDefault: item.Default}) + } + return printers, nil + } + + var single struct { + Name string `json:"Name"` + Default bool `json:"Default"` + } + if err := json.Unmarshal([]byte(decoded), &single); err != nil { + return nil, err + } + name := strings.TrimSpace(single.Name) + if name == "" { + return nil, fmt.Errorf("no printers found") + } + return []PrinterInfo{{Name: name, IsDefault: single.Default}}, nil +} + +func (b *Bridge) getPrinterCapabilitiesPlatform(printerName string) (map[string]interface{}, error) { + printerName = strings.TrimSpace(printerName) + if printerName == "" { + return nil, fmt.Errorf("printer name is empty") + } + + escaped := strings.ReplaceAll(printerName, "'", "''") + ps := fmt.Sprintf(`$p = Get-CimInstance Win32_Printer -Filter "Name='%s'"; `+ + `$c = Get-CimInstance Win32_PrinterConfiguration -Filter "Name='%s'"; `+ + `if ($null -eq $p) { throw "Printer not found" }; `+ + `[pscustomobject]@{ `+ + `name = $p.Name; `+ + `defaultPaperSize = $p.DefaultPaperSize; `+ + `printerPaperNames = $p.PrinterPaperNames; `+ + `paperSizes = $p.PaperSizes; `+ + `colorSupported = $p.ColorSupported; `+ + `duplexSupported = $p.DuplexSupported; `+ + `driverName = $p.DriverName; `+ + `portName = $p.PortName; `+ + `printProcessor = $p.PrintProcessor; `+ + `deviceId = $p.DeviceID; `+ + `config = @{ `+ + `paperSize = $c.PaperSize; `+ + `orientation = $c.Orientation; `+ + `color = $c.Color; `+ + `duplex = $c.Duplex; `+ + `copies = $c.Copies `+ + `} `+ + `} | ConvertTo-Json -Depth 4`, escaped, escaped) + + cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", ps) + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + output, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("get printer capabilities failed: %v", err) + } + + decoded, err := decodeCmdOutput(output) + if err != nil { + decoded = string(output) + } + + var caps map[string]interface{} + if err := json.Unmarshal([]byte(decoded), &caps); err != nil { + return nil, fmt.Errorf("parse printer capabilities failed: %v", err) + } + + return caps, nil +} + +func (b *Bridge) printPDFPlatform(printerName, filePath string, options PrintOptions) error { + sumatraPath, err := findSumatraPDF() + if err != nil { + return err + } + + settings := buildSumatraPrintSettings(options) + + args := []string{"-print-to", printerName} + if settings != "" { + args = append(args, "-print-settings", settings) + } + args = append(args, filePath) + + cmd := exec.Command(sumatraPath, args...) + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + + queueSnapshot, _ := getPrintJobIDs(printerName) + if err := cmd.Start(); err != nil { + return fmt.Errorf("sumatra print failed to start: %v", err) + } + + cmdDone := make(chan error, 1) + go func() { + cmdDone <- cmd.Wait() + }() + + if err := waitForWindowsPrintCompletion(printerName, queueSnapshot, cmdDone); err != nil { + return err + } + + return nil +} + +type windowsPrintJob struct { + Id int `json:"Id"` + JobStatus interface{} `json:"JobStatus"` + DocumentName string `json:"DocumentName"` +} + +const ( + printQueuePollInterval = 500 * time.Millisecond + printQueueAppearTimeout = 120 * time.Second + printQueueCompleteTimeout = 5 * time.Minute +) + +func getPrintJobs(printerName string) ([]windowsPrintJob, error) { + printerName = strings.TrimSpace(printerName) + if printerName == "" { + return nil, fmt.Errorf("printer name is empty") + } + + escaped := strings.ReplaceAll(printerName, "'", "''") + ps := fmt.Sprintf(`Get-PrintJob -PrinterName '%s' | Select-Object Id,JobStatus,DocumentName | ConvertTo-Json -Depth 3`, escaped) + cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", ps) + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + output, err := cmd.Output() + if err != nil { + return nil, err + } + + decoded, err := decodeCmdOutput(output) + if err != nil { + decoded = string(output) + } + decoded = strings.TrimSpace(decoded) + if decoded == "" || decoded == "null" { + return nil, nil + } + + var list []windowsPrintJob + if err := json.Unmarshal([]byte(decoded), &list); err == nil { + return list, nil + } + + var single windowsPrintJob + if err := json.Unmarshal([]byte(decoded), &single); err != nil { + return nil, err + } + return []windowsPrintJob{single}, nil +} + +func getPrintJobIDs(printerName string) (map[int]bool, error) { + jobs, err := getPrintJobs(printerName) + if err != nil { + return nil, err + } + ids := make(map[int]bool, len(jobs)) + for _, job := range jobs { + if job.Id > 0 { + ids[job.Id] = true + } + } + return ids, nil +} + +func waitForWindowsPrintCompletion(printerName string, existingIDs map[int]bool, cmdDone <-chan error) error { + appearDeadline := time.Now().Add(printQueueAppearTimeout) + completeDeadline := time.Now().Add(printQueueCompleteTimeout) + + queued := false + jobID := 0 + + for { + select { + case err := <-cmdDone: + if err != nil && !queued { + return fmt.Errorf("sumatra print failed: %v", err) + } + default: + } + + now := time.Now() + if !queued && now.After(appearDeadline) { + return fmt.Errorf("print job not queued within %s", printQueueAppearTimeout) + } + if queued && now.After(completeDeadline) { + return fmt.Errorf("print job not completed within %s", printQueueCompleteTimeout) + } + + jobs, err := getPrintJobs(printerName) + if err == nil { + if !queued { + for _, job := range jobs { + if !existingIDs[job.Id] { + jobID = job.Id + queued = true + break + } + } + } else { + found := false + var statusList []string + for _, job := range jobs { + if job.Id == jobID { + found = true + statusList = normalizeJobStatus(job.JobStatus) + break + } + } + if !found { + return nil + } + if isWindowsJobFailed(statusList) { + return fmt.Errorf("print job failed: %s", strings.Join(statusList, ", ")) + } + } + } + + time.Sleep(printQueuePollInterval) + } +} + +func normalizeJobStatus(status interface{}) []string { + switch v := status.(type) { + case string: + if strings.TrimSpace(v) == "" { + return nil + } + return []string{strings.TrimSpace(v)} + case []interface{}: + out := make([]string, 0, len(v)) + for _, item := range v { + if s, ok := item.(string); ok { + if strings.TrimSpace(s) != "" { + out = append(out, strings.TrimSpace(s)) + } + } + } + return out + default: + return nil + } +} + +func isWindowsJobFailed(statuses []string) bool { + for _, status := range statuses { + value := strings.ToLower(status) + if strings.Contains(value, "error") || strings.Contains(value, "offline") || strings.Contains(value, "paused") { + return true + } + } + return false +} + +func findSumatraPDF() (string, error) { + if envPath := strings.TrimSpace(os.Getenv("SUMATRAPDF_PATH")); envPath != "" { + if fileExists(envPath) { + return envPath, nil + } + } + + if exe, err := os.Executable(); err == nil { + candidate := filepath.Join(filepath.Dir(exe), "SumatraPDF.exe") + if fileExists(candidate) { + return candidate, nil + } + } + + if path, err := exec.LookPath("SumatraPDF.exe"); err == nil { + return path, nil + } + if path, err := exec.LookPath("SumatraPDF"); err == nil { + return path, nil + } + + return "", fmt.Errorf("SumatraPDF.exe not found. Place it next to the app, add it to PATH, or set SUMATRAPDF_PATH") +} + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + +func buildSumatraPrintSettings(options PrintOptions) string { + var settings []string + + if options.PageRange != "" { + settings = append(settings, options.PageRange) + } + + switch strings.ToLower(strings.TrimSpace(options.PageSet)) { + case "even": + settings = append(settings, "even") + case "odd": + settings = append(settings, "odd") + } + + switch strings.ToLower(strings.TrimSpace(options.Scale)) { + case "fit": + settings = append(settings, "fit") + case "shrink": + settings = append(settings, "shrink") + case "none", "actual", "noscale": + settings = append(settings, "noscale") + } + + switch strings.ToLower(strings.TrimSpace(options.Orientation)) { + case "portrait": + settings = append(settings, "portrait") + case "landscape": + settings = append(settings, "landscape") + } + + switch strings.ToLower(strings.TrimSpace(options.Duplex)) { + case "simplex", "one-sided": + settings = append(settings, "simplex") + case "long-edge", "long", "duplex", "duplexlong": + settings = append(settings, "duplex") + case "short-edge", "short", "duplexshort": + settings = append(settings, "duplexshort") + } + + switch strings.ToLower(strings.TrimSpace(options.ColorMode)) { + case "color": + settings = append(settings, "color") + case "mono", "monochrome", "grayscale", "gray": + settings = append(settings, "monochrome") + } + + if options.Paper != "" { + settings = append(settings, fmt.Sprintf("paper=%s", options.Paper)) + } + + if options.TrayBin != "" { + settings = append(settings, fmt.Sprintf("bin=%s", options.TrayBin)) + } + + if options.Copies > 1 { + settings = append(settings, fmt.Sprintf("%dx", options.Copies)) + } + + return strings.Join(settings, ",") +} diff --git a/XSLPrintDot/build/README.md b/XSLPrintDot/build/README.md new file mode 100644 index 0000000..1ae2f67 --- /dev/null +++ b/XSLPrintDot/build/README.md @@ -0,0 +1,35 @@ +# Build Directory + +The build directory is used to house all the build files and assets for your application. + +The structure is: + +* bin - Output directory +* darwin - macOS specific files +* windows - Windows specific files + +## Mac + +The `darwin` directory holds files specific to Mac builds. +These may be customised and used as part of the build. To return these files to the default state, simply delete them +and +build with `wails build`. + +The directory contains the following files: + +- `Info.plist` - the main plist file used for Mac builds. It is used when building using `wails build`. +- `Info.dev.plist` - same as the main plist file but used when building using `wails dev`. + +## Windows + +The `windows` directory contains the manifest and rc files used when building with `wails build`. +These may be customised for your application. To return these files to the default state, simply delete them and +build with `wails build`. + +- `icon.ico` - The icon used for the application. This is used when building using `wails build`. If you wish to + use a different icon, simply replace this file with your own. If it is missing, a new `icon.ico` file + will be created using the `appicon.png` file in the build directory. +- `installer/*` - The files used to create the Windows installer. These are used when building using `wails build`. +- `info.json` - Application details used for Windows builds. The data here will be used by the Windows installer, + as well as the application itself (right click the exe -> properties -> details) +- `wails.exe.manifest` - The main application manifest file. \ No newline at end of file diff --git a/XSLPrintDot/build/appicon.png b/XSLPrintDot/build/appicon.png new file mode 100644 index 0000000..3e0bc8b Binary files /dev/null and b/XSLPrintDot/build/appicon.png differ diff --git a/XSLPrintDot/build/darwin/Info.dev.plist b/XSLPrintDot/build/darwin/Info.dev.plist new file mode 100644 index 0000000..14121ef --- /dev/null +++ b/XSLPrintDot/build/darwin/Info.dev.plist @@ -0,0 +1,68 @@ + + + + CFBundlePackageType + APPL + CFBundleName + {{.Info.ProductName}} + CFBundleExecutable + {{.OutputFilename}} + CFBundleIdentifier + com.wails.{{.Name}} + CFBundleVersion + {{.Info.ProductVersion}} + CFBundleGetInfoString + {{.Info.Comments}} + CFBundleShortVersionString + {{.Info.ProductVersion}} + CFBundleIconFile + iconfile + LSMinimumSystemVersion + 10.13.0 + NSHighResolutionCapable + true + NSHumanReadableCopyright + {{.Info.Copyright}} + {{if .Info.FileAssociations}} + CFBundleDocumentTypes + + {{range .Info.FileAssociations}} + + CFBundleTypeExtensions + + {{.Ext}} + + CFBundleTypeName + {{.Name}} + CFBundleTypeRole + {{.Role}} + CFBundleTypeIconFile + {{.IconName}} + + {{end}} + + {{end}} + {{if .Info.Protocols}} + CFBundleURLTypes + + {{range .Info.Protocols}} + + CFBundleURLName + com.wails.{{.Scheme}} + CFBundleURLSchemes + + {{.Scheme}} + + CFBundleTypeRole + {{.Role}} + + {{end}} + + {{end}} + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + + diff --git a/XSLPrintDot/build/darwin/Info.plist b/XSLPrintDot/build/darwin/Info.plist new file mode 100644 index 0000000..d17a747 --- /dev/null +++ b/XSLPrintDot/build/darwin/Info.plist @@ -0,0 +1,63 @@ + + + + CFBundlePackageType + APPL + CFBundleName + {{.Info.ProductName}} + CFBundleExecutable + {{.OutputFilename}} + CFBundleIdentifier + com.wails.{{.Name}} + CFBundleVersion + {{.Info.ProductVersion}} + CFBundleGetInfoString + {{.Info.Comments}} + CFBundleShortVersionString + {{.Info.ProductVersion}} + CFBundleIconFile + iconfile + LSMinimumSystemVersion + 10.13.0 + NSHighResolutionCapable + true + NSHumanReadableCopyright + {{.Info.Copyright}} + {{if .Info.FileAssociations}} + CFBundleDocumentTypes + + {{range .Info.FileAssociations}} + + CFBundleTypeExtensions + + {{.Ext}} + + CFBundleTypeName + {{.Name}} + CFBundleTypeRole + {{.Role}} + CFBundleTypeIconFile + {{.IconName}} + + {{end}} + + {{end}} + {{if .Info.Protocols}} + CFBundleURLTypes + + {{range .Info.Protocols}} + + CFBundleURLName + com.wails.{{.Scheme}} + CFBundleURLSchemes + + {{.Scheme}} + + CFBundleTypeRole + {{.Role}} + + {{end}} + + {{end}} + + diff --git a/XSLPrintDot/build/windows/icon.ico b/XSLPrintDot/build/windows/icon.ico new file mode 100644 index 0000000..c5ac729 Binary files /dev/null and b/XSLPrintDot/build/windows/icon.ico differ diff --git a/XSLPrintDot/build/windows/info.json b/XSLPrintDot/build/windows/info.json new file mode 100644 index 0000000..9727946 --- /dev/null +++ b/XSLPrintDot/build/windows/info.json @@ -0,0 +1,15 @@ +{ + "fixed": { + "file_version": "{{.Info.ProductVersion}}" + }, + "info": { + "0000": { + "ProductVersion": "{{.Info.ProductVersion}}", + "CompanyName": "{{.Info.CompanyName}}", + "FileDescription": "{{.Info.ProductName}}", + "LegalCopyright": "{{.Info.Copyright}}", + "ProductName": "{{.Info.ProductName}}", + "Comments": "{{.Info.Comments}}" + } + } +} \ No newline at end of file diff --git a/XSLPrintDot/build/windows/installer/project.nsi b/XSLPrintDot/build/windows/installer/project.nsi new file mode 100644 index 0000000..f43ab8a --- /dev/null +++ b/XSLPrintDot/build/windows/installer/project.nsi @@ -0,0 +1,120 @@ +Unicode true + +#### +## Please note: Template replacements don't work in this file. They are provided with default defines like +## mentioned underneath. +## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo. +## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually +## from outside of Wails for debugging and development of the installer. +## +## For development first make a wails nsis build to populate the "wails_tools.nsh": +## > wails build --target windows/amd64 --nsis +## Then you can call makensis on this file with specifying the path to your binary: +## For a AMD64 only installer: +## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app.exe +## For a ARM64 only installer: +## > makensis -DARG_WAILS_ARM64_BINARY=..\..\bin\app.exe +## For a installer with both architectures: +## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe +#### +## The following information is taken from the ProjectInfo file, but they can be overwritten here. +#### +## !define INFO_PROJECTNAME "MyProject" # Default "{{.Name}}" +## !define INFO_COMPANYNAME "MyCompany" # Default "{{.Info.CompanyName}}" +## !define INFO_PRODUCTNAME "MyProduct" # Default "{{.Info.ProductName}}" +## !define INFO_PRODUCTVERSION "1.0.0" # Default "{{.Info.ProductVersion}}" +## !define INFO_COPYRIGHT "Copyright" # Default "{{.Info.Copyright}}" +### +## !define PRODUCT_EXECUTABLE "Application.exe" # Default "${INFO_PROJECTNAME}.exe" +## !define UNINST_KEY_NAME "UninstKeyInRegistry" # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}" +#### +## !define REQUEST_EXECUTION_LEVEL "admin" # Default "admin" see also https://nsis.sourceforge.io/Docs/Chapter4.html +#### +## Include the wails tools +#### +!include "wails_tools.nsh" + +# The version information for this two must consist of 4 parts +VIProductVersion "${INFO_PRODUCTVERSION}.0" +VIFileVersion "${INFO_PRODUCTVERSION}.0" + +VIAddVersionKey "CompanyName" "${INFO_COMPANYNAME}" +VIAddVersionKey "FileDescription" "${INFO_PRODUCTNAME} Installer" +VIAddVersionKey "ProductVersion" "${INFO_PRODUCTVERSION}" +VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}" +VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}" +VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}" + +# Enable HiDPI support. https://nsis.sourceforge.io/Reference/ManifestDPIAware +ManifestDPIAware true + +!include "MUI.nsh" + +!define MUI_ICON "..\icon.ico" +!define MUI_UNICON "..\icon.ico" +# !define MUI_WELCOMEFINISHPAGE_BITMAP "resources\leftimage.bmp" #Include this to add a bitmap on the left side of the Welcome Page. Must be a size of 164x314 +!define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps +!define MUI_ABORTWARNING # This will warn the user if they exit from the installer. + +!insertmacro MUI_PAGE_WELCOME # Welcome to the installer page. +# !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer +!insertmacro MUI_PAGE_DIRECTORY # In which folder install page. +!insertmacro MUI_PAGE_INSTFILES # Installing page. +!insertmacro MUI_PAGE_FINISH # Finished installation page. + +!insertmacro MUI_UNPAGE_INSTFILES # Uinstalling page + +!insertmacro MUI_LANGUAGE "English" # Set the Language of the installer + +## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1 +#!uninstfinalize 'signtool --file "%1"' +#!finalize 'signtool --file "%1"' + +Name "${INFO_PRODUCTNAME}" +OutFile "..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file. +InstallDir "$PROGRAMFILES64\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder). +ShowInstDetails show # This will always show the installation details. + +Function .onInit + !insertmacro wails.checkArchitecture +FunctionEnd + +Section + !insertmacro wails.setShellContext + + !insertmacro wails.webview2runtime + + SetOutPath $INSTDIR + + !insertmacro wails.files + + File "resources\SumatraPDF.exe" + + CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}" + CreateShortCut "$DESKTOP\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}" + + !insertmacro wails.associateFiles + !insertmacro wails.associateCustomProtocols + + !insertmacro wails.writeUninstaller +SectionEnd + +Section "uninstall" + !insertmacro wails.setShellContext + + RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath + + RMDir /r "$ProgramData\PrintDot" + + Delete "$INSTDIR\SumatraPDF.exe" + + RMDir /r $INSTDIR + + Delete "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" + Delete "$DESKTOP\${INFO_PRODUCTNAME}.lnk" + + !insertmacro wails.unassociateFiles + !insertmacro wails.unassociateCustomProtocols + + !insertmacro wails.deleteUninstaller +SectionEnd diff --git a/XSLPrintDot/build/windows/installer/resources/SumatraPDF-settings.txt b/XSLPrintDot/build/windows/installer/resources/SumatraPDF-settings.txt new file mode 100644 index 0000000..d216e33 --- /dev/null +++ b/XSLPrintDot/build/windows/installer/resources/SumatraPDF-settings.txt @@ -0,0 +1,94 @@ +# For documentation, see https://www.sumatrapdfreader.org/settings/settings3-5-1.html +Theme = Light +FixedPageUI [ + TextColor = #000000 + BackgroundColor = #ffffff + SelectionColor = #f5fc0c + WindowMargin = 2 4 2 4 + PageSpacing = 4 4 + InvertColors = false + HideScrollbars = false +] +ComicBookUI [ + WindowMargin = 0 0 0 0 + PageSpacing = 4 4 + CbxMangaMode = false +] +ChmUI [ + UseFixedPageUI = false +] + +SelectionHandlers [ +] +ExternalViewers [ +] + +ZoomLevels = 8.33 12.5 18 25 33.33 50 66.67 75 100 125 150 200 300 400 600 800 1000 1200 1600 2000 2400 3200 4800 6400 +ZoomIncrement = 0 + +PrinterDefaults [ + PrintScale = shrink +] +ForwardSearch [ + HighlightOffset = 0 + HighlightWidth = 15 + HighlightColor = #6581ff + HighlightPermanent = false +] +Annotations [ + HighlightColor = #ffff00 + UnderlineColor = #00ff00 + SquigglyColor = #ff00ff + StrikeOutColor = #ff0000 + FreeTextColor = + FreeTextSize = 12 + FreeTextBorderWidth = 1 + TextIconColor = + TextIconType = + DefaultAuthor = +] + +RememberOpenedFiles = true +RememberStatePerDocument = true +RestoreSession = true +UiLanguage = cn +EnableTeXEnhancements = false +DefaultDisplayMode = automatic +DefaultZoom = fit page +Shortcuts [ +] +EscToExit = false +ReuseInstance = false +ReloadModifiedDocuments = true + +MainWindowBackground = #80fff200 +FullPathInTitle = false +ShowMenubar = true +ShowToolbar = true +ShowFavorites = false +ShowToc = true +NoHomeTab = false +TocDy = 0 +SidebarDx = 0 +ToolbarSize = 18 +TabWidth = 300 +TreeFontSize = 0 +TreeFontWeightOffset = 0 +TreeFontName = automatic +SmoothScroll = false +ShowStartPage = true +CheckForUpdates = true +WindowState = 1 +WindowPos = 520 0 880 1140 +UseTabs = true +UseSysColors = false +CustomScreenDPI = 0 + +FileStates [ +] +SessionData [ +] +TimeOfLastUpdateCheck = 0 0 +OpenCountWeek = 798 + +# Settings below are not recognized by the current version diff --git a/XSLPrintDot/build/windows/installer/resources/SumatraPDF.exe b/XSLPrintDot/build/windows/installer/resources/SumatraPDF.exe new file mode 100644 index 0000000..f034e5e Binary files /dev/null and b/XSLPrintDot/build/windows/installer/resources/SumatraPDF.exe differ diff --git a/XSLPrintDot/build/windows/wails.exe.manifest b/XSLPrintDot/build/windows/wails.exe.manifest new file mode 100644 index 0000000..17e1a23 --- /dev/null +++ b/XSLPrintDot/build/windows/wails.exe.manifest @@ -0,0 +1,15 @@ + + + + + + + + + + + true/pm + permonitorv2,permonitor + + + \ No newline at end of file diff --git a/XSLPrintDot/device_id.go b/XSLPrintDot/device_id.go new file mode 100644 index 0000000..99b622b --- /dev/null +++ b/XSLPrintDot/device_id.go @@ -0,0 +1,30 @@ +package main + +import "strings" + +func getNormalizedDeviceID() string { + id, err := getDeviceID() + if err != nil { + return "" + } + id = strings.TrimSpace(id) + if id == "" { + return "" + } + + if strings.HasPrefix(id, "{") && strings.HasSuffix(id, "}") { + id = strings.TrimSpace(id[1 : len(id)-1]) + } + + clean := strings.ReplaceAll(id, "-", "") + clean = strings.ReplaceAll(clean, " ", "") + clean = strings.ReplaceAll(clean, "\t", "") + clean = strings.ReplaceAll(clean, "\n", "") + clean = strings.ReplaceAll(clean, "\r", "") + + if len(clean) == 32 { + id = clean[0:8] + "-" + clean[8:12] + "-" + clean[12:16] + "-" + clean[16:20] + "-" + clean[20:32] + } + + return strings.ToUpper(id) +} diff --git a/XSLPrintDot/device_id_darwin.go b/XSLPrintDot/device_id_darwin.go new file mode 100644 index 0000000..607924c --- /dev/null +++ b/XSLPrintDot/device_id_darwin.go @@ -0,0 +1,33 @@ +//go:build darwin + +package main + +import ( + "bytes" + "os/exec" + "strings" +) + +func getDeviceID() (string, error) { + out, err := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output() + if err != nil { + return "", err + } + + lines := bytes.Split(out, []byte("\n")) + for _, line := range lines { + text := strings.TrimSpace(string(line)) + if !strings.Contains(text, "IOPlatformUUID") { + continue + } + if idx := strings.Index(text, "="); idx >= 0 { + value := strings.TrimSpace(text[idx+1:]) + value = strings.Trim(value, "\"") + if value != "" { + return value, nil + } + } + } + + return "", nil +} diff --git a/XSLPrintDot/device_id_linux.go b/XSLPrintDot/device_id_linux.go new file mode 100644 index 0000000..b8da775 --- /dev/null +++ b/XSLPrintDot/device_id_linux.go @@ -0,0 +1,28 @@ +//go:build linux + +package main + +import ( + "os" + "strings" +) + +func getDeviceID() (string, error) { + paths := []string{ + "/etc/machine-id", + "/var/lib/dbus/machine-id", + } + + for _, path := range paths { + data, err := os.ReadFile(path) + if err != nil { + continue + } + value := strings.TrimSpace(string(data)) + if value != "" { + return value, nil + } + } + + return "", nil +} diff --git a/XSLPrintDot/device_id_other.go b/XSLPrintDot/device_id_other.go new file mode 100644 index 0000000..4fcafa9 --- /dev/null +++ b/XSLPrintDot/device_id_other.go @@ -0,0 +1,9 @@ +//go:build !windows && !darwin && !linux + +package main + +import "os" + +func getDeviceID() (string, error) { + return os.Hostname() +} diff --git a/XSLPrintDot/device_id_windows.go b/XSLPrintDot/device_id_windows.go new file mode 100644 index 0000000..6ebd987 --- /dev/null +++ b/XSLPrintDot/device_id_windows.go @@ -0,0 +1,19 @@ +//go:build windows + +package main + +import "golang.org/x/sys/windows/registry" + +func getDeviceID() (string, error) { + key, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE) + if err != nil { + return "", err + } + defer key.Close() + + id, _, err := key.GetStringValue("MachineGuid") + if err != nil { + return "", err + } + return id, nil +} diff --git a/XSLPrintDot/docs/images/1.png b/XSLPrintDot/docs/images/1.png new file mode 100644 index 0000000..19d46b0 Binary files /dev/null and b/XSLPrintDot/docs/images/1.png differ diff --git a/XSLPrintDot/docs/images/2.png b/XSLPrintDot/docs/images/2.png new file mode 100644 index 0000000..55d60c0 Binary files /dev/null and b/XSLPrintDot/docs/images/2.png differ diff --git a/XSLPrintDot/docs/usage_guide_en.md b/XSLPrintDot/docs/usage_guide_en.md new file mode 100644 index 0000000..3c11688 --- /dev/null +++ b/XSLPrintDot/docs/usage_guide_en.md @@ -0,0 +1,257 @@ +# XSL-PrintDot Client Usage Guide + +## 1. Introduction + +**XSL-PrintDot Client** is a local printing middleware developed based on Wails (Go + Vue 3). It acts as a bridge between browsers (or other clients) and the operating system's printers, receiving print instructions via the WebSocket protocol and invoking the system printer for printing. + +Key Features: +- Automatically retrieves the list of installed printers in the operating system. +- Starts a WebSocket service to listen for print requests (default port 1122). +- Supports custom service ports and security keys (Secret Key). +- **Print Content Requirement**: Accepts Base64 encoded PDF content and invokes system printing commands. +- Supports advanced print parameters: copies, interval between copies, and more print settings. +- Provides a visual management interface to view logs and printer status in real-time. +- **Real-time Log Monitoring**: View system logs in real time. + +--- + +## 2. Startup and Configuration + +### 2.1 Starting the Application +You can run the compiled executable file (e.g., `XSL-PrintDot.exe`) directly. + +**Note**: The program automatically starts the WebSocket service (default port 1122) upon startup. + +**Windows printing note**: +- Ensure the Windows printing backend is available and accessible by the app. + +### 2.2 Interface Configuration +After startup, the interface provides the following configuration options: +- **Port**: WebSocket service listening port (default `1122`). +- **Secret Key**: Security key (optional). If a key is set, clients must authenticate when connecting or sending requests. +- **Start/Stop Server**: Click the button to start or stop the WebSocket service. +- **Connection URL**: After the service starts, the interface displays the full connection address (e.g., `ws://localhost:1122/ws?key=...`). + +**Operation Instructions**: +- **Exit Program**: Use the menu bar `Menu` -> `Quit` (Ctrl+Q) or the tray menu `Quit` to completely exit the program. +- **Run in Background**: Clicking the main window close button (X) will not exit the program but minimize it to the system tray. An icon appears in the system tray area, which can be used to quickly recall the window or exit. +- **Tray Menu**: Right-click the system tray icon to select `Show Main Window` or `Quit`. +- **Open Settings**: Use the menu bar `Menu` -> `Settings` (Ctrl+I) to open the settings window. +- **View Logs**: Use the menu bar `Menu` -> `System Logs` (Ctrl+L) to view logs in real time. + +--- + +## 3. WebSocket Interface Specification + +### 3.1 Connection Information +- **Protocol**: WebSocket (`ws://`) +- **Address**: `ws://localhost:/ws` +- **Authentication**: + - If a `Secret Key` is set, it is recommended to carry it in the connection URL: `ws://localhost:1122/ws?key=YOUR_PASSWORD` + - If the key is not carried during connection, it can also be included in the message body sent (but not recommended, as the connection might be rejected). + +### 3.2 Message Types + +#### 3.2.1 Connection Success Response (Server -> Client) +After the connection is established, the server immediately sends the current printer list: +```json +{ + "type": "printer_list", + "data": [ + {"name": "Microsoft Print to PDF", "isDefault": true}, + {"name": "ZDesigner GK888t", "isDefault": false} + ] +} +``` + +#### 3.2.2 Get Printer List (Client -> Server) +The client can actively request the latest printer list at any time by sending the following JSON message: +```json +{ + "type": "get_printers" +} +``` +The server will reply with a `printer_list` message in the same format as **3.2.1**. + +#### 3.2.3 Get Printer Capabilities (Client -> Server) +Request capabilities for a specific printer: +```json +{ + "type": "get_printer_caps", + "printer": "Microsoft Print to PDF" +} +``` +Example response: +```json +{ + "type": "printer_caps", + "printer": "Microsoft Print to PDF", + "data": { + "paperSizes": ["A4", "Letter"], + "printerPaperNames": ["A4", "Letter"], + "duplexSupported": false, + "colorSupported": true + } +} +``` +> Note: fields vary by platform. Windows returns Win32_Printer/Win32_PrinterConfiguration info; Linux/macOS returns parsed lpoptions data. + +#### 3.2.4 Send Print Job (Client -> Server) +The JSON payload is grouped by feature: + +```json +{ + "printer": "Microsoft Print to PDF", // [Required] Target printer name + "content": "data:application/pdf;base64,JVBERi...", // [Required] Base64 encoded PDF content (Supports Data URI prefix or raw Base64) + "key": "123456", // [Optional] Auth key (can be omitted if verified during connection) + "job": { + "name": "My Print Job 001", // [Optional] Job name (for logging only) + "copies": 2, // [Optional] Number of copies, default 1 + "intervalMs": 1000 // [Optional] Delay between copies (ms) + }, + "pages": { + "range": "1-3,5", // [Optional] Page range (N / N-M / N,M / reverse ranges) + "set": "odd" // [Optional] odd | even + }, + "layout": { + "scale": "fit", // [Optional] noscale | shrink | fit + "orientation": "portrait" // [Optional] portrait | landscape + }, + "color": { + "mode": "color" // [Optional] color | monochrome + }, + "sides": { + "mode": "duplex" // [Optional] simplex | duplex | duplexshort | duplexlong + }, + "paper": { + "size": "A4" // [Optional] A4 | letter | legal | tabloid | statement | A2 | A3 | A5 | A6 + }, + "tray": { + "bin": "2" // [Optional] Tray number or name, e.g. 2 / Manual + } +} +``` + +> **Note**: +> 1. The `content` field must be a **Base64 encoded string of a PDF file**. +> - Supports standard Data URI format: `data:application/pdf;base64,JVBERi...` +> - Also supports raw Base64 string: `JVBERi...` +> - The server automatically strips the `data:` prefix (if present) and validates that the decoded content starts with `%PDF`. + +| Field | Type | Description | +| :--- | :--- | :--- | +| `printer` | String | Target printer name. | +| `content` | String | **Base64 encoded PDF content**. | +| `job.name` | String | Print job name. | +| `job.copies` | Integer | **Number of copies**. If `intervalMs` is 0, handled by the system command. | +| `job.intervalMs` | Integer | **Interval (ms)**. When > 0, the server prints one copy per run. | +| `pages.range` | String | **Page range**: `N` / `N-M` / `N,M` / reverse ranges. | +| `pages.set` | String | **Odd/Even**: `odd` / `even`. | +| `layout.scale` | String | **Scaling**: `noscale` / `shrink` / `fit`. | +| `layout.orientation` | String | **Orientation**: `portrait` / `landscape`. | +| `color.mode` | String | **Color mode**: `color` / `monochrome`. | +| `sides.mode` | String | **Duplex**: `simplex` / `duplex` / `duplexshort` / `duplexlong`. | +| `paper.size` | String | **Paper size**: e.g. `A4`, `letter`, `legal`. If omitted, we try to auto-detect common sizes from PDF MediaBox. | +| `tray.bin` | String | **Tray**: number or name. | + +#### 3.2.3.1 Platform Support +**Windows** +- `pages.range` / `pages.set` / `layout.scale` / `layout.orientation` / `color.mode` / `sides.mode` / `paper.size` / `tray.bin` / `job.copies` are converted to Windows print options. + +**Linux/macOS (lp/CUPS)** +- `pages.range` -> `-P`. +- `pages.set` -> `-o page-set=odd|even`. +- `layout.scale` -> `fit-to-page` / `scaling=100` (`shrink` uses default behavior). +- `layout.orientation` -> `-o orientation-requested=3|4` (may be ignored by drivers). +- `color.mode` -> `-o ColorModel=Gray` / `-o ColorModel=RGB` (may be ignored by drivers). +- `sides.mode` -> `-o sides=...`. +- `paper.size` -> `-o media=...`. +- `tray.bin` -> `-o InputSlot=...` (depends on driver support). + +#### 3.2.4 Server Response (Server -> Client) +The server returns the result of each print: + +**Success Response:** +```json +{ + "status": "success", + "message": "Printed successfully" +} +``` + +**Failure Response:** +```json +{ + "status": "error", + "message": "Content must be a PDF file" +} +``` + +**Windows queue tracking note:** +On Windows, the server waits for the print job to appear in the printer queue and complete before returning `success`. +If the job does not appear within 120 seconds, or does not complete within 5 minutes, it returns `error` with a timeout message. + +### 3.3 Client Code Example + +```javascript +const socket = new WebSocket('ws://localhost:1122/ws?key=123456'); + +socket.onopen = () => { + console.log('Connected'); +}; + +socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + if (msg.type === 'printer_list') { + console.log('Available printers:', msg.data); + + const targetPrinter = msg.data.find(p => p.isDefault) || msg.data[0]; + + // Example: Actively refresh printer list + // socket.send(JSON.stringify({ type: 'get_printers' })); + + // Fetch printer capabilities (paper/duplex/color, etc.) + socket.send(JSON.stringify({ + type: 'get_printer_caps', + printer: targetPrinter?.name + })); + } else if (msg.type === 'printer_caps') { + const caps = msg.data || {}; + const sizes = caps.printerPaperNames || caps.paperSizes || []; + const paperSize = sizes[0] || 'A4'; + + // Send print job (grouped by feature) + socket.send(JSON.stringify({ + printer: msg.printer, + content: "JVBERi0xLjQKJ...", // Base64 PDF Data + job: { + name: "Test Job", + copies: 2, + intervalMs: 0 + }, + pages: { + range: "1-3,5", + set: "odd" + }, + layout: { + scale: "fit", + orientation: "portrait" + }, + color: { + mode: "color" + }, + sides: { + mode: "duplex" + }, + paper: { + size: paperSize + }, + tray: { + bin: "2" + } + })); + } else { + console.log('Response:', msg); + } +}; +``` diff --git a/XSLPrintDot/docs/usage_guide_zh.md b/XSLPrintDot/docs/usage_guide_zh.md new file mode 100644 index 0000000..ec81c39 --- /dev/null +++ b/XSLPrintDot/docs/usage_guide_zh.md @@ -0,0 +1,263 @@ +# XSL-PrintDot Client 使用指南与规范 + +## 1. 项目简介 + +**XSL-PrintDot Client** 是一个基于 Wails (Go + Vue 3) 开发的本地打印中间件。它充当浏览器(或其他客户端)与操作系统打印机之间的桥梁,通过 WebSocket 协议接收打印指令,并调用系统打印机进行打印。 + +主要功能: +- 自动获取操作系统已安装的打印机列表。 +- 启动 WebSocket 服务监听打印请求(默认端口 1122)。 +- 支持自定义服务端口和安全密钥(Secret Key)。 +- **打印内容要求**:接收 Base64 编码的 PDF 文件内容,并调用系统打印命令进行打印。 +- 支持高级打印参数:打印份数、份数间隔,以及更多打印设置。 +- 提供可视化的管理界面,实时查看日志和打印机状态。 +- **日志实时监控**:支持实时查看系统日志。 + +--- + +## 2. 启动与配置 + +### 2.1 启动应用 +可以直接运行编译后的可执行文件(如 `XSL-PrintDot.exe`),或在开发环境中使用: + +```bash +wails dev +``` + +**注意**: 程序启动时会自动开启 WebSocket 服务(默认端口 1122)。 + +**Windows 打印说明**: +- 请确保 Windows 打印后端可用且程序有权限访问。 + +### 2.2 界面配置 +启动后,界面提供以下配置项: +- **Port**: WebSocket 服务监听端口(默认 `1122`)。 +- **Secret Key**: 安全密钥(可选)。如果设置了密钥,客户端在连接或发送请求时必须通过鉴权。 +- **Start/Stop Server**: 点击按钮即可启动或停止 WebSocket 服务。 +- **Connection URL**: 服务启动后,界面会显示完整的连接地址(如 `ws://localhost:1122/ws?key=...`)。 + +**操作说明**: +- **退出程序**: 使用菜单栏 `Menu` -> `Quit` (Ctrl+Q),或使用托盘菜单的 `Quit` 可完全退出程序。 +- **后台运行**: 点击主窗口关闭按钮 (X) 不会退出程序,而是将程序最小化到系统托盘区。程序启动后会在系统托盘区显示图标,可用于快速唤起窗口或退出。 +- **托盘菜单**: 在系统托盘图标上右键单击,可选择 `Show Main Window` 显示主窗口或 `Quit` 退出程序。 +- **打开设置**: 使用菜单栏 `Menu` -> `Settings` (Ctrl+I) 可打开设置窗口。 +- **查看日志**: 使用菜单栏 `Menu` -> `System Logs` (Ctrl+L) 可查看实时日志. + +--- + +## 3. WebSocket 接口规范 + +### 3.1 连接信息 +- **协议**: WebSocket (`ws://`) +- **地址**: `ws://localhost:/ws` +- **鉴权**: + - 如果设置了 `Secret Key`,建议在连接 URL 中携带:`ws://localhost:1122/ws?key=YOUR_PASSWORD` + - 如果连接时未携带 key,也可以在发送的消息体中包含 `key` 字段(但不推荐,连接可能被拒绝)。 + +### 3.2 消息类型 + +#### 3.2.1 连接成功响应 (Server -> Client) +连接建立后,服务端会立即发送当前的打印机列表: +```json +{ + "type": "printer_list", + "data": [ + {"name": "Microsoft Print to PDF", "isDefault": true}, + {"name": "ZDesigner GK888t", "isDefault": false} + ] +} +``` + +#### 3.2.2 获取打印机列表 (Client -> Server) +客户端可以随时发送以下 JSON 消息主动获取最新的打印机列表: +```json +{ + "type": "get_printers" +} +``` +服务端将回复与 **3.2.1** 相同格式的 `printer_list` 消息。 + +#### 3.2.3 获取打印机能力 (Client -> Server) +客户端可以请求指定打印机的可用参数: +```json +{ + "type": "get_printer_caps", + "printer": "Microsoft Print to PDF" +} +``` +服务端响应示例: +```json +{ + "type": "printer_caps", + "printer": "Microsoft Print to PDF", + "data": { + "paperSizes": ["A4", "Letter"], + "printerPaperNames": ["A4", "Letter"], + "duplexSupported": false, + "colorSupported": true + } +} +``` +> 说明:不同系统返回字段会有差异,Windows 返回 Win32_Printer/Win32_PrinterConfiguration 信息;Linux/macOS 返回 lpoptions 解析结果。 + +#### 3.2.4 发送打印任务 (Client -> Server) +客户端发送的 JSON 数据包结构如下(按功能分类): + +```json +{ + "printer": "Microsoft Print to PDF", // [必填] 目标打印机名称 + "content": "data:application/pdf;base64,JVBERi...", // [必填] Base64 编码的 PDF 内容 (支持带前缀或纯 Base64) + "key": "123456", // [选填] 鉴权密钥 (若连接时已验证可省略) + "job": { + "name": "My Print Job 001", // [选填] 任务名称 (仅用于日志记录) + "copies": 2, // [选填] 打印份数,默认 1 + "intervalMs": 1000 // [选填] 份数间延迟(毫秒),用于手动隔张打印 + }, + "pages": { + "range": "1-3,5", // [选填] 页码范围 (支持 N / N-M / N,M / 反向区间) + "set": "odd" // [选填] odd | even + }, + "layout": { + "scale": "fit", // [选填] noscale | shrink | fit + "orientation": "portrait" // [选填] portrait | landscape + }, + "color": { + "mode": "color" // [选填] color | monochrome + }, + "sides": { + "mode": "duplex" // [选填] simplex | duplex | duplexshort | duplexlong + }, + "paper": { + "size": "A4" // [选填] A4 | letter | legal | tabloid | statement | A2 | A3 | A5 | A6 + }, + "tray": { + "bin": "2" // [选填] 纸盒编号或名称,例如 2 / Manual + } +} +``` + +> **注意**: +> 1. `content` 字段必须是 **PDF 文件的 Base64 编码字符串**。 +> - 支持标准 Data URI 格式:`data:application/pdf;base64,JVBERi...` +> - 也支持纯 Base64 字符串:`JVBERi...` +> - 服务端会自动去除 `data:` 前缀(如果有)并校验解码后的内容是否以 `%PDF` 开头。 + +| 字段 | 类型 | 说明 | +| :--- | :--- | :--- | +| `printer` | String | 目标打印机名称。 | +| `content` | String | **Base64 编码的 PDF 内容**。 | +| `job.name` | String | 打印任务名称。 | +| `job.copies` | Integer | **打印份数**。`intervalMs` 为 0 时由系统命令一次性处理。 | +| `job.intervalMs` | Integer | **隔张间隔 (ms)**。大于 0 时服务端逐份打印。 | +| `pages.range` | String | **页码范围**:`N` / `N-M` / `N,M` / 反向区间。 | +| `pages.set` | String | **奇偶页**:`odd` / `even`。 | +| `layout.scale` | String | **缩放**:`noscale` / `shrink` / `fit`。 | +| `layout.orientation` | String | **方向**:`portrait` / `landscape`。 | +| `color.mode` | String | **颜色模式**:`color` / `monochrome`。 | +| `sides.mode` | String | **单双面**:`simplex` / `duplex` / `duplexshort` / `duplexlong`。 | +| `paper.size` | String | **纸张**:如 `A4`、`letter`、`legal`。未提供时会尝试从 PDF 的 MediaBox 自动识别常见尺寸。 | +| `tray.bin` | String | **纸盒**:编号或名称。 | + +#### 3.2.3.1 平台支持说明 +**Windows** +- `pages.range` / `pages.set` / `layout.scale` / `layout.orientation` / `color.mode` / `sides.mode` / `paper.size` / `tray.bin` / `job.copies` 会被转换为 Windows 打印选项。 + +**Linux/macOS (lp/CUPS)** +- `pages.range` -> `-P`。 +- `pages.set` -> `-o page-set=odd|even`。 +- `layout.scale` -> `fit-to-page` / `scaling=100`(`shrink` 使用默认行为)。 +- `layout.orientation` -> `-o orientation-requested=3|4`(驱动可能忽略)。 +- `color.mode` -> `-o ColorModel=Gray` / `-o ColorModel=RGB`(部分驱动可能忽略)。 +- `sides.mode` -> `-o sides=...`。 +- `paper.size` -> `-o media=...`。 +- `tray.bin` -> `-o InputSlot=...`(依赖驱动支持)。 + +#### 3.2.4 服务端响应 (Server -> Client) +服务端会返回每次打印的结果: + +**成功响应:** +```json +{ + "status": "success", + "message": "Printed successfully" +} +``` + +**失败响应:** +```json +{ + "status": "error", + "message": "Content must be a PDF file" +} +``` + +**Windows 队列跟踪说明:** +Windows 下服务端会等待打印任务进入打印队列并完成后才返回 `success`。 +若 120 秒内未入队或 5 分钟内未完成,将返回 `error` 并给出超时提示。 + +--- + +## 4. 调用示例 (JavaScript) + +```javascript +const socket = new WebSocket('ws://localhost:1122/ws?key=123456'); + +socket.onopen = () => { + console.log('已连接'); +}; + +socket.onmessage = (event) => { + const msg = JSON.parse(event.data); + if (msg.type === 'printer_list') { + console.log('可用打印机:', msg.data); + + const targetPrinter = msg.data.find(p => p.isDefault) || msg.data[0]; + + // 示例:主动刷新打印机列表 + // socket.send(JSON.stringify({ type: 'get_printers' })); + + // 获取打印机能力(纸张/单双面/彩色等) + socket.send(JSON.stringify({ + type: 'get_printer_caps', + printer: targetPrinter?.name + })); + } else if (msg.type === 'printer_caps') { + const caps = msg.data || {}; + const sizes = caps.printerPaperNames || caps.paperSizes || []; + const paperSize = sizes[0] || 'A4'; + + // 发送打印任务(按功能分组) + socket.send(JSON.stringify({ + printer: msg.printer, + content: "JVBERi0xLjQKJ...", // Base64 PDF Data + job: { + name: "Test Job", + copies: 2, + intervalMs: 0 + }, + pages: { + range: "1-3,5", + set: "odd" + }, + layout: { + scale: "fit", + orientation: "portrait" + }, + color: { + mode: "color" + }, + sides: { + mode: "duplex" + }, + paper: { + size: paperSize + }, + tray: { + bin: "2" + } + })); + } else { + console.log('收到回复:', msg); + } +}; +``` diff --git a/XSLPrintDot/forwarder.go b/XSLPrintDot/forwarder.go new file mode 100644 index 0000000..ce4c153 --- /dev/null +++ b/XSLPrintDot/forwarder.go @@ -0,0 +1,513 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/gorilla/websocket" +) + +const ( + remotePingInterval = 20 * time.Second + remoteReportInterval = 10 * time.Second + remotePongWait = 70 * time.Second + remoteWriteWait = 5 * time.Second +) + +type RemoteConfig struct { + Server string + AuthURL string + WsURL string + ClientID string + SecretKey string + ClientName string +} + +type RemoteForwarderStatus struct { + Connected bool `json:"connected"` + LastError string `json:"lastError"` + LastChange int64 `json:"lastChange"` + AutoReconnect bool `json:"autoReconnect"` +} + +type remoteLoginResponse struct { + Token string `json:"token"` +} + +type remotePrintTask struct { + Cmd string `json:"cmd"` + TaskID string `json:"task_id"` + PrintRequest +} + +func (b *Bridge) ConfigureRemoteForwarder(s AppSettings) { + b.StartRemoteForwarderWithSettings(s, false) +} + +func (b *Bridge) StartRemoteForwarderWithSettings(s AppSettings, force bool) { + cfg := RemoteConfig{ + Server: strings.TrimSpace(s.RemoteServer), + AuthURL: strings.TrimSpace(s.RemoteAuthURL), + WsURL: strings.TrimSpace(s.RemoteWsURL), + ClientID: strings.TrimSpace(firstNonEmpty(s.RemoteClientID, s.RemoteUser)), + SecretKey: strings.TrimSpace(firstNonEmpty(s.RemoteSecretKey, s.RemotePassword)), + ClientName: strings.TrimSpace(s.RemoteClientName), + } + + if !force && !s.RemoteAutoConnect { + b.StopRemoteForwarder() + return + } + + if (cfg.AuthURL == "" && cfg.Server == "") || + (cfg.WsURL == "" && cfg.Server == "") || + cfg.ClientID == "" || cfg.SecretKey == "" { + b.StopRemoteForwarder() + return + } + + b.remoteMu.Lock() + same := cfg == b.remoteCfg && b.remoteStop != nil + b.remoteMu.Unlock() + if same { + return + } + + b.StopRemoteForwarder() + + b.remoteMu.Lock() + b.remoteCfg = cfg + b.remoteStop = make(chan struct{}) + stop := b.remoteStop + b.remoteMu.Unlock() + + b.remoteWg.Add(1) + go b.runRemoteForwarder(cfg, stop) +} + +func (b *Bridge) StopRemoteForwarder() { + b.remoteMu.Lock() + stop := b.remoteStop + conn := b.remoteConn + b.remoteStop = nil + b.remoteMu.Unlock() + + if stop != nil { + close(stop) + } + if conn != nil { + _ = conn.Close() + } + b.setRemoteConnected(false) + b.remoteWg.Wait() +} + +func (b *Bridge) runRemoteForwarder(cfg RemoteConfig, stop <-chan struct{}) { + defer b.remoteWg.Done() + + for { + if err := b.connectAndServeForwarder(cfg, stop); err != nil { + b.setRemoteError(err) + b.Log(fmt.Sprintf("Remote forwarder error: %v", err)) + } + + select { + case <-stop: + return + case <-time.After(3 * time.Second): + } + } +} + +func (b *Bridge) connectAndServeForwarder(cfg RemoteConfig, stop <-chan struct{}) error { + loginURL, wsURL, err := buildRemoteURLsFromConfig(cfg) + if err != nil { + return err + } + + token, err := b.remoteLogin(loginURL, cfg) + if err != nil { + return err + } + + headers := http.Header{} + headers.Set("Authorization", "Bearer "+token) + headers.Set("X-Client-Id", cfg.ClientID) + if cfg.ClientName != "" { + headers.Set("X-Client-Name", cfg.ClientName) + } + + conn, _, err := websocket.DefaultDialer.Dial(wsURL.String(), headers) + if err != nil { + return fmt.Errorf("ws connect failed: %v", err) + } + defer conn.Close() + + conn.SetReadLimit(8 * 1024 * 1024) + _ = conn.SetReadDeadline(time.Now().Add(remotePongWait)) + conn.SetPongHandler(func(string) error { + return conn.SetReadDeadline(time.Now().Add(remotePongWait)) + }) + + b.setRemoteConn(conn) + b.setRemoteConnected(true) + defer func() { + b.clearRemoteConn(conn) + b.setRemoteConnected(false) + }() + + b.Log(fmt.Sprintf("Remote forwarder connected: %s", wsURL.String())) + + if err := b.reportPrinters(conn); err != nil { + b.Log(fmt.Sprintf("Report printers failed: %v", err)) + } + + pingStop := make(chan struct{}) + go b.pingLoop(conn, pingStop) + go b.reportLoop(conn, pingStop) + defer close(pingStop) + + for { + select { + case <-stop: + return nil + default: + } + + _ = conn.SetReadDeadline(time.Now().Add(remotePongWait)) + var rawMsg map[string]interface{} + if err := conn.ReadJSON(&rawMsg); err != nil { + return err + } + + cmd, _ := rawMsg["cmd"].(string) + switch strings.ToLower(strings.TrimSpace(cmd)) { + case "print_task": + jsonBody, _ := json.Marshal(rawMsg) + var task remotePrintTask + if err := json.Unmarshal(jsonBody, &task); err != nil { + b.Log(fmt.Sprintf("Invalid print task: %v", err)) + continue + } + + message, err := b.processPrintRequest(task.PrintRequest) + status := "success" + if err != nil { + status = "failed" + } + + resp := map[string]interface{}{ + "cmd": "report_result", + "task_id": task.TaskID, + "status": status, + "message": message, + } + if err := writeJSONWithDeadline(conn, resp); err != nil { + b.Log(fmt.Sprintf("Report result failed: %v", err)) + } + case "get_printers": + if err := b.reportPrinters(conn); err != nil { + b.Log(fmt.Sprintf("Report printers failed: %v", err)) + } + case "auth_resp": + b.Log("Remote forwarder auth ok") + } + } +} + +func (b *Bridge) remoteLogin(loginURL *url.URL, cfg RemoteConfig) (string, error) { + payload := map[string]string{ + "client_id": cfg.ClientID, + "secret_key": cfg.SecretKey, + } + if cfg.ClientName != "" { + payload["client_name"] = cfg.ClientName + } + + body, err := json.Marshal(payload) + if err != nil { + return "", err + } + + req, err := http.NewRequest("POST", loginURL.String(), bytes.NewReader(body)) + if err != nil { + return "", err + } + req.Header.Set("Content-Type", "application/json") + + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return "", fmt.Errorf("login failed: status %d", resp.StatusCode) + } + + var loginResp remoteLoginResponse + if err := json.NewDecoder(resp.Body).Decode(&loginResp); err != nil { + return "", err + } + if strings.TrimSpace(loginResp.Token) == "" { + return "", fmt.Errorf("login failed: empty token") + } + return loginResp.Token, nil +} + +func (b *Bridge) reportPrinters(conn *websocket.Conn) error { + printers, err := b.GetPrinters() + if err != nil { + return err + } + + list := make([]map[string]interface{}, 0, len(printers)) + for _, p := range printers { + caps, capsErr := b.GetPrinterCapabilities(p.Name) + if capsErr != nil { + b.Log(fmt.Sprintf("Get printer capabilities failed: %s: %v", p.Name, capsErr)) + caps = map[string]interface{}{} + } + list = append(list, map[string]interface{}{ + "printer_name": p.Name, + "printer_type": "system", + "paper_spec": "", + "is_ready": true, + "supported_format": "pdf", + "capabilities": caps, + }) + } + + payload := map[string]interface{}{ + "cmd": "report_printers", + "printers": list, + } + return writeJSONWithDeadline(conn, payload) +} + +func (b *Bridge) pingLoop(conn *websocket.Conn, stop <-chan struct{}) { + ticker := time.NewTicker(remotePingInterval) + defer ticker.Stop() + + for { + select { + case <-stop: + return + case <-ticker.C: + deadline := time.Now().Add(remoteWriteWait) + _ = conn.WriteControl(websocket.PingMessage, []byte("ping"), deadline) + } + } +} + +func (b *Bridge) reportLoop(conn *websocket.Conn, stop <-chan struct{}) { + ticker := time.NewTicker(remoteReportInterval) + defer ticker.Stop() + + for { + select { + case <-stop: + return + case <-ticker.C: + if err := b.reportPrinters(conn); err != nil { + b.Log(fmt.Sprintf("Report printers failed: %v", err)) + } + } + } +} + +func writeJSONWithDeadline(conn *websocket.Conn, payload interface{}) error { + _ = conn.SetWriteDeadline(time.Now().Add(remoteWriteWait)) + return conn.WriteJSON(payload) +} + +func buildRemoteURLs(raw string) (*url.URL, *url.URL, error) { + baseURL, err := normalizeRemoteBaseURL(raw) + if err != nil { + return nil, nil, err + } + + loginBase := *baseURL + switch loginBase.Scheme { + case "ws": + loginBase.Scheme = "http" + case "wss": + loginBase.Scheme = "https" + } + + wsBase := *baseURL + switch wsBase.Scheme { + case "http": + wsBase.Scheme = "ws" + case "https": + wsBase.Scheme = "wss" + } + + loginURL := loginBase.ResolveReference(&url.URL{Path: "/api/client/login"}) + wsURL := wsBase.ResolveReference(&url.URL{Path: "/ws/client"}) + return loginURL, wsURL, nil +} + +func buildRemoteURLsFromConfig(cfg RemoteConfig) (*url.URL, *url.URL, error) { + var loginURL *url.URL + var wsURL *url.URL + + if cfg.AuthURL != "" { + parsed, err := normalizeAuthURL(cfg.AuthURL) + if err != nil { + return nil, nil, err + } + loginURL = parsed + } + + if cfg.WsURL != "" { + parsed, err := normalizeWsURL(cfg.WsURL) + if err != nil { + return nil, nil, err + } + wsURL = parsed + } + + if (loginURL == nil || wsURL == nil) && cfg.Server != "" { + baseLoginURL, baseWsURL, err := buildRemoteURLs(cfg.Server) + if err != nil { + return nil, nil, err + } + if loginURL == nil { + loginURL = baseLoginURL + } + if wsURL == nil { + wsURL = baseWsURL + } + } + + if loginURL == nil || wsURL == nil { + return nil, nil, fmt.Errorf("auth or ws address is missing") + } + + return loginURL, wsURL, nil +} + +func normalizeAuthURL(raw string) (*url.URL, error) { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return nil, fmt.Errorf("auth address is empty") + } + if !strings.Contains(trimmed, "://") { + trimmed = "http://" + trimmed + } + parsed, err := url.Parse(trimmed) + if err != nil { + return nil, err + } + if parsed.Host == "" { + return nil, fmt.Errorf("invalid auth address") + } + if parsed.Path == "" || parsed.Path == "/" { + parsed.Path = "/api/client/login" + } + switch parsed.Scheme { + case "ws": + parsed.Scheme = "http" + case "wss": + parsed.Scheme = "https" + } + return parsed, nil +} + +func normalizeWsURL(raw string) (*url.URL, error) { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return nil, fmt.Errorf("ws address is empty") + } + if !strings.Contains(trimmed, "://") { + trimmed = "ws://" + trimmed + } + parsed, err := url.Parse(trimmed) + if err != nil { + return nil, err + } + if parsed.Host == "" { + return nil, fmt.Errorf("invalid ws address") + } + if parsed.Path == "" || parsed.Path == "/" { + parsed.Path = "/ws/client" + } + switch parsed.Scheme { + case "http": + parsed.Scheme = "ws" + case "https": + parsed.Scheme = "wss" + } + return parsed, nil +} + +func normalizeRemoteBaseURL(raw string) (*url.URL, error) { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return nil, fmt.Errorf("remote server is empty") + } + + if !strings.Contains(trimmed, "://") { + trimmed = "http://" + trimmed + } + + parsed, err := url.Parse(trimmed) + if err != nil { + return nil, err + } + if parsed.Host == "" { + return nil, fmt.Errorf("invalid remote server address") + } + parsed.Path = strings.TrimRight(parsed.Path, "/") + parsed.RawQuery = "" + parsed.Fragment = "" + + return parsed, nil +} + +func (b *Bridge) setRemoteConn(conn *websocket.Conn) { + b.remoteMu.Lock() + b.remoteConn = conn + b.remoteMu.Unlock() +} + +func (b *Bridge) clearRemoteConn(conn *websocket.Conn) { + b.remoteMu.Lock() + if b.remoteConn == conn { + b.remoteConn = nil + } + b.remoteMu.Unlock() +} + +func (b *Bridge) setRemoteConnected(connected bool) { + b.remoteMu.Lock() + b.remoteStatus.Connected = connected + if connected { + b.remoteStatus.LastError = "" + } + b.remoteStatus.LastChange = time.Now().Unix() + b.remoteMu.Unlock() +} + +func (b *Bridge) setRemoteError(err error) { + if err == nil { + return + } + b.remoteMu.Lock() + b.remoteStatus.LastError = err.Error() + b.remoteStatus.LastChange = time.Now().Unix() + b.remoteMu.Unlock() +} + +func (b *Bridge) GetRemoteForwarderStatus() RemoteForwarderStatus { + b.remoteMu.Lock() + defer b.remoteMu.Unlock() + return b.remoteStatus +} diff --git a/XSLPrintDot/frontend/README.md b/XSLPrintDot/frontend/README.md new file mode 100644 index 0000000..98f4a52 --- /dev/null +++ b/XSLPrintDot/frontend/README.md @@ -0,0 +1,23 @@ +# Vue 3 + TypeScript + Vite + +This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue +3 ` + + + diff --git a/XSLPrintDot/frontend/package-lock.json b/XSLPrintDot/frontend/package-lock.json new file mode 100644 index 0000000..2b5c723 --- /dev/null +++ b/XSLPrintDot/frontend/package-lock.json @@ -0,0 +1,2419 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.0.0", + "dependencies": { + "marked": "^17.0.1", + "vue": "^3.2.37", + "vue-i18n": "^9.14.5" + }, + "devDependencies": { + "@babel/types": "^7.18.10", + "@iconify-json/material-symbols": "^1.2.53", + "@tailwindcss/postcss": "^4.1.18", + "@vitejs/plugin-vue": "^3.0.3", + "autoprefixer": "^10.4.24", + "postcss": "^8.5.6", + "tailwindcss": "^4.1.18", + "typescript": "^4.6.4", + "unplugin-icons": "^23.0.1", + "unplugin-vue-components": "^31.0.0", + "vite": "^3.0.7", + "vue-tsc": "^1.8.27" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@antfu/install-pkg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz", + "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "package-manager-detector": "^1.3.0", + "tinyexec": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz", + "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.18.tgz", + "integrity": "sha512-5GT+kcs2WVGjVs7+boataCkO5Fg0y4kCjzkB5bAip7H4jfnOS3dA6KPiww9W1OEKTKeAcUVhdZGvgI65OXmUnw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.18.tgz", + "integrity": "sha512-L4jVKS82XVhw2nvzLg/19ClLWg0y27ulRwuP7lcyL6AbUWB5aPglXY3M21mauDQMDfRLs8cQmeT03r/+X3cZYQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@iconify-json/material-symbols": { + "version": "1.2.53", + "resolved": "https://registry.npmjs.org/@iconify-json/material-symbols/-/material-symbols-1.2.53.tgz", + "integrity": "sha512-2jXBKFdNzL9zy6chnJqubykL9WZno7rEP6/isSzpp6fKJJMXXhRtVkaGw1Clle0RlXGWzVkd/eiYUH8f9/ILrQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@iconify/types": "*" + } + }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@iconify/utils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.0.tgz", + "integrity": "sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@antfu/install-pkg": "^1.1.0", + "@iconify/types": "^2.0.0", + "mlly": "^1.8.0" + } + }, + "node_modules/@intlify/core-base": { + "version": "9.14.5", + "resolved": "https://registry.npmjs.org/@intlify/core-base/-/core-base-9.14.5.tgz", + "integrity": "sha512-5ah5FqZG4pOoHjkvs8mjtv+gPKYU0zCISaYNjBNNqYiaITxW8ZtVih3GS/oTOqN8d9/mDLyrjD46GBApNxmlsA==", + "license": "MIT", + "dependencies": { + "@intlify/message-compiler": "9.14.5", + "@intlify/shared": "9.14.5" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/kazupon" + } + }, + "node_modules/@intlify/message-compiler": { + "version": "9.14.5", + "resolved": "https://registry.npmjs.org/@intlify/message-compiler/-/message-compiler-9.14.5.tgz", + "integrity": "sha512-IHzgEu61/YIpQV5Pc3aRWScDcnFKWvQA9kigcINcCBXN8mbW+vk9SK+lDxA6STzKQsVJxUPg9ACC52pKKo3SVQ==", + "license": "MIT", + "dependencies": { + "@intlify/shared": "9.14.5", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/kazupon" + } + }, + "node_modules/@intlify/shared": { + "version": "9.14.5", + "resolved": "https://registry.npmjs.org/@intlify/shared/-/shared-9.14.5.tgz", + "integrity": "sha512-9gB+E53BYuAEMhbCAxVgG38EZrk59sxBtv3jSizNL2hEWlgjBjAw1AwpLHtNaeda12pe6W20OGEa0TwuMSRbyQ==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/kazupon" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz", + "integrity": "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "enhanced-resolve": "^5.18.3", + "jiti": "^2.6.1", + "lightningcss": "1.30.2", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.1.18" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.1.18.tgz", + "integrity": "sha512-EgCR5tTS5bUSKQgzeMClT6iCY3ToqE1y+ZB0AKldj809QXk1Y+3jB0upOYZrn9aGIzPtUsP7sX4QQ4XtjBB95A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.1.18", + "@tailwindcss/oxide-darwin-arm64": "4.1.18", + "@tailwindcss/oxide-darwin-x64": "4.1.18", + "@tailwindcss/oxide-freebsd-x64": "4.1.18", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.18", + "@tailwindcss/oxide-linux-arm64-gnu": "4.1.18", + "@tailwindcss/oxide-linux-arm64-musl": "4.1.18", + "@tailwindcss/oxide-linux-x64-gnu": "4.1.18", + "@tailwindcss/oxide-linux-x64-musl": "4.1.18", + "@tailwindcss/oxide-wasm32-wasi": "4.1.18", + "@tailwindcss/oxide-win32-arm64-msvc": "4.1.18", + "@tailwindcss/oxide-win32-x64-msvc": "4.1.18" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.1.18.tgz", + "integrity": "sha512-dJHz7+Ugr9U/diKJA0W6N/6/cjI+ZTAoxPf9Iz9BFRF2GzEX8IvXxFIi/dZBloVJX/MZGvRuFA9rqwdiIEZQ0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.1.18.tgz", + "integrity": "sha512-Gc2q4Qhs660bhjyBSKgq6BYvwDz4G+BuyJ5H1xfhmDR3D8HnHCmT/BSkvSL0vQLy/nkMLY20PQ2OoYMO15Jd0A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.1.18.tgz", + "integrity": "sha512-FL5oxr2xQsFrc3X9o1fjHKBYBMD1QZNyc1Xzw/h5Qu4XnEBi3dZn96HcHm41c/euGV+GRiXFfh2hUCyKi/e+yw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.1.18.tgz", + "integrity": "sha512-Fj+RHgu5bDodmV1dM9yAxlfJwkkWvLiRjbhuO2LEtwtlYlBgiAT4x/j5wQr1tC3SANAgD+0YcmWVrj8R9trVMA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.1.18.tgz", + "integrity": "sha512-Fp+Wzk/Ws4dZn+LV2Nqx3IilnhH51YZoRaYHQsVq3RQvEl+71VGKFpkfHrLM/Li+kt5c0DJe/bHXK1eHgDmdiA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.1.18.tgz", + "integrity": "sha512-S0n3jboLysNbh55Vrt7pk9wgpyTTPD0fdQeh7wQfMqLPM/Hrxi+dVsLsPrycQjGKEQk85Kgbx+6+QnYNiHalnw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.1.18.tgz", + "integrity": "sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.18.tgz", + "integrity": "sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.1.18.tgz", + "integrity": "sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.1.18.tgz", + "integrity": "sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@emnapi/wasi-threads": "^1.1.0", + "@napi-rs/wasm-runtime": "^1.1.0", + "@tybys/wasm-util": "^0.10.1", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.7.1", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.1.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.7.1", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.1.0", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.0", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@tybys/wasm-util": "^0.10.1" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.18.tgz", + "integrity": "sha512-HjSA7mr9HmC8fu6bdsZvZ+dhjyGCLdotjVOgLA2vEqxEBZaQo9YTX4kwgEvPCpRh8o4uWc4J/wEoFzhEmjvPbA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.1.18.tgz", + "integrity": "sha512-bJWbyYpUlqamC8dpR7pfjA0I7vdF6t5VpUGMWRkXVE3AXgIZjYUYAK7II1GNaxR8J1SSrSrppRar8G++JekE3Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/postcss": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.1.18.tgz", + "integrity": "sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "@tailwindcss/node": "4.1.18", + "@tailwindcss/oxide": "4.1.18", + "postcss": "^8.4.41", + "tailwindcss": "4.1.18" + } + }, + "node_modules/@vitejs/plugin-vue": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-3.2.0.tgz", + "integrity": "sha512-E0tnaL4fr+qkdCNxJ+Xd0yM31UwMkQje76fsDVBBUCoGOUPexu2VDUYHL8P4CwV+zMvWw6nlRw19OnRKmYAJpw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^3.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@volar/language-core": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-1.11.1.tgz", + "integrity": "sha512-dOcNn3i9GgZAcJt43wuaEykSluAuOkQgzni1cuxLxTV0nJKanQztp7FxyswdRILaKH+P2XZMPRp2S4MV/pElCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "1.11.1" + } + }, + "node_modules/@volar/source-map": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-1.11.1.tgz", + "integrity": "sha512-hJnOnwZ4+WT5iupLRnuzbULZ42L7BWWPMmruzwtLhJfpDVoZLjNBxHDi2sY2bgZXCKlpU5XcsMFoYrsQmPhfZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "muggle-string": "^0.3.1" + } + }, + "node_modules/@volar/typescript": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-1.11.1.tgz", + "integrity": "sha512-iU+t2mas/4lYierSnoFOeRFQUhAEMgsFuQxoxvwn5EdQopw43j+J27a4lt9LMInx1gLJBC6qL14WYGlgymaSMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "1.11.1", + "path-browserify": "^1.0.1" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.27.tgz", + "integrity": "sha512-gnSBQjZA+//qDZen+6a2EdHqJ68Z7uybrMf3SPjEGgG4dicklwDVmMC1AeIHxtLVPT7sn6sH1KOO+tS6gwOUeQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@vue/shared": "3.5.27", + "entities": "^7.0.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.27.tgz", + "integrity": "sha512-oAFea8dZgCtVVVTEC7fv3T5CbZW9BxpFzGGxC79xakTr6ooeEqmRuvQydIiDAkglZEAd09LgVf1RoDnL54fu5w==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.27", + "@vue/shared": "3.5.27" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.27.tgz", + "integrity": "sha512-sHZu9QyDPeDmN/MRoshhggVOWE5WlGFStKFwu8G52swATgSny27hJRWteKDSUUzUH+wp+bmeNbhJnEAel/auUQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@vue/compiler-core": "3.5.27", + "@vue/compiler-dom": "3.5.27", + "@vue/compiler-ssr": "3.5.27", + "@vue/shared": "3.5.27", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.6", + "source-map-js": "^1.2.1" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.27.tgz", + "integrity": "sha512-Sj7h+JHt512fV1cTxKlYhg7qxBvack+BGncSpH+8vnN+KN95iPIcqB5rsbblX40XorP+ilO7VIKlkuu3Xq2vjw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.27", + "@vue/shared": "3.5.27" + } + }, + "node_modules/@vue/devtools-api": { + "version": "6.6.4", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz", + "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "1.8.27", + "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-1.8.27.tgz", + "integrity": "sha512-L8Kc27VdQserNaCUNiSFdDl9LWT24ly8Hpwf1ECy3aFb9m6bDhBGQYOujDm21N7EW3moKIOKEanQwe1q5BK+mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "~1.11.1", + "@volar/source-map": "~1.11.1", + "@vue/compiler-dom": "^3.3.0", + "@vue/shared": "^3.3.0", + "computeds": "^0.0.1", + "minimatch": "^9.0.3", + "muggle-string": "^0.3.1", + "path-browserify": "^1.0.1", + "vue-template-compiler": "^2.7.14" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.27.tgz", + "integrity": "sha512-vvorxn2KXfJ0nBEnj4GYshSgsyMNFnIQah/wczXlsNXt+ijhugmW+PpJ2cNPe4V6jpnBcs0MhCODKllWG+nvoQ==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.27" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.27.tgz", + "integrity": "sha512-fxVuX/fzgzeMPn/CLQecWeDIFNt3gQVhxM0rW02Tvp/YmZfXQgcTXlakq7IMutuZ/+Ogbn+K0oct9J3JZfyk3A==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.27", + "@vue/shared": "3.5.27" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.27.tgz", + "integrity": "sha512-/QnLslQgYqSJ5aUmb5F0z0caZPGHRB8LEAQ1s81vHFM5CBfnun63rxhvE/scVb/j3TbBuoZwkJyiLCkBluMpeg==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.27", + "@vue/runtime-core": "3.5.27", + "@vue/shared": "3.5.27", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.27.tgz", + "integrity": "sha512-qOz/5thjeP1vAFc4+BY3Nr6wxyLhpeQgAE/8dDtKo6a6xdk+L4W46HDZgNmLOBUDEkFXV3G7pRiUqxjX0/2zWA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.27", + "@vue/shared": "3.5.27" + }, + "peerDependencies": { + "vue": "3.5.27" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.27.tgz", + "integrity": "sha512-dXr/3CgqXsJkZ0n9F3I4elY8wM9jMJpP3pvRG52r6m0tu/MsAFIe6JpXVGeNMd/D9F4hQynWT8Rfuj0bdm9kFQ==", + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/autoprefixer": { + "version": "10.4.24", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.24.tgz", + "integrity": "sha512-uHZg7N9ULTVbutaIsDRoUkoS8/h3bdsmVJYZ5l3wv8Cp/6UIIoRDm90hZ+BwxUj/hGBEzLxdHNSKuFpn8WOyZw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.1", + "caniuse-lite": "^1.0.30001766", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.9.19", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.19.tgz", + "integrity": "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001766", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001766.tgz", + "integrity": "sha512-4C0lfJ0/YPjJQHagaE9x2Elb69CIqEPZeG0anQt9SIvIoOH4a4uaRl73IavyO+0qZh6MDLH//DrXThEYKHkmYA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/computeds": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/computeds/-/computeds-0.0.1.tgz", + "integrity": "sha512-7CEBgcMjVmitjYo5q8JTJVra6X5mQ20uTThdK+0kR7UEaDrAWEQcRiBtWJzga4eRpP6afNwwLsX2SET2JhVB1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.2.tgz", + "integrity": "sha512-1NB+BKqhtNipMsov4xI/NnhCKp9XG9NamYp5PVm9klAT0fsrNPjaFICsCFhNhwZJKNh7zB/3q8qXz0E9oaMNtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/de-indent": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/de-indent/-/de-indent-1.0.2.tgz", + "integrity": "sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.283", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.283.tgz", + "integrity": "sha512-3vifjt1HgrGW/h76UEeny+adYApveS9dH2h3p57JYzBSXJIKUJAvtmIytDKjcSCt9xHfrNCFJ7gts6vkhuq++w==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.18.4", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz", + "integrity": "sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.18.tgz", + "integrity": "sha512-x/R72SmW3sSFRm5zrrIjAhCeQSAWoni3CmHEqfQrZIQTM3lVCdehdwuIqaOtfC2slvpdlLa62GYoN8SxT23m6Q==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.15.18", + "@esbuild/linux-loong64": "0.15.18", + "esbuild-android-64": "0.15.18", + "esbuild-android-arm64": "0.15.18", + "esbuild-darwin-64": "0.15.18", + "esbuild-darwin-arm64": "0.15.18", + "esbuild-freebsd-64": "0.15.18", + "esbuild-freebsd-arm64": "0.15.18", + "esbuild-linux-32": "0.15.18", + "esbuild-linux-64": "0.15.18", + "esbuild-linux-arm": "0.15.18", + "esbuild-linux-arm64": "0.15.18", + "esbuild-linux-mips64le": "0.15.18", + "esbuild-linux-ppc64le": "0.15.18", + "esbuild-linux-riscv64": "0.15.18", + "esbuild-linux-s390x": "0.15.18", + "esbuild-netbsd-64": "0.15.18", + "esbuild-openbsd-64": "0.15.18", + "esbuild-sunos-64": "0.15.18", + "esbuild-windows-32": "0.15.18", + "esbuild-windows-64": "0.15.18", + "esbuild-windows-arm64": "0.15.18" + } + }, + "node_modules/esbuild-android-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.18.tgz", + "integrity": "sha512-wnpt3OXRhcjfIDSZu9bnzT4/TNTDsOUvip0foZOUBG7QbSt//w3QV4FInVJxNhKc/ErhUxc5z4QjHtMi7/TbgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-android-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.18.tgz", + "integrity": "sha512-G4xu89B8FCzav9XU8EjsXacCKSG2FT7wW9J6hOc18soEHJdtWu03L3TQDGf0geNxfLTtxENKBzMSq9LlbjS8OQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-darwin-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.18.tgz", + "integrity": "sha512-2WAvs95uPnVJPuYKP0Eqx+Dl/jaYseZEUUT1sjg97TJa4oBtbAKnPnl3b5M9l51/nbx7+QAEtuummJZW0sBEmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-darwin-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.18.tgz", + "integrity": "sha512-tKPSxcTJ5OmNb1btVikATJ8NftlyNlc8BVNtyT/UAr62JFOhwHlnoPrhYWz09akBLHI9nElFVfWSTSRsrZiDUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-freebsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.18.tgz", + "integrity": "sha512-TT3uBUxkteAjR1QbsmvSsjpKjOX6UkCstr8nMr+q7zi3NuZ1oIpa8U41Y8I8dJH2fJgdC3Dj3CXO5biLQpfdZA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-freebsd-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.18.tgz", + "integrity": "sha512-R/oVr+X3Tkh+S0+tL41wRMbdWtpWB8hEAMsOXDumSSa6qJR89U0S/PpLXrGF7Wk/JykfpWNokERUpCeHDl47wA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-32": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.18.tgz", + "integrity": "sha512-lphF3HiCSYtaa9p1DtXndiQEeQDKPl9eN/XNoBf2amEghugNuqXNZA/ZovthNE2aa4EN43WroO0B85xVSjYkbg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.18.tgz", + "integrity": "sha512-hNSeP97IviD7oxLKFuii5sDPJ+QHeiFTFLoLm7NZQligur8poNOWGIgpQ7Qf8Balb69hptMZzyOBIPtY09GZYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-arm": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.18.tgz", + "integrity": "sha512-UH779gstRblS4aoS2qpMl3wjg7U0j+ygu3GjIeTonCcN79ZvpPee12Qun3vcdxX+37O5LFxz39XeW2I9bybMVA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.18.tgz", + "integrity": "sha512-54qr8kg/6ilcxd+0V3h9rjT4qmjc0CccMVWrjOEM/pEcUzt8X62HfBSeZfT2ECpM7104mk4yfQXkosY8Quptug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-mips64le": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.18.tgz", + "integrity": "sha512-Mk6Ppwzzz3YbMl/ZZL2P0q1tnYqh/trYZ1VfNP47C31yT0K8t9s7Z077QrDA/guU60tGNp2GOwCQnp+DYv7bxQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-ppc64le": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.18.tgz", + "integrity": "sha512-b0XkN4pL9WUulPTa/VKHx2wLCgvIAbgwABGnKMY19WhKZPT+8BxhZdqz6EgkqCLld7X5qiCY2F/bfpUUlnFZ9w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-riscv64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.18.tgz", + "integrity": "sha512-ba2COaoF5wL6VLZWn04k+ACZjZ6NYniMSQStodFKH/Pu6RxzQqzsmjR1t9QC89VYJxBeyVPTaHuBMCejl3O/xg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-linux-s390x": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.18.tgz", + "integrity": "sha512-VbpGuXEl5FCs1wDVp93O8UIzl3ZrglgnSQ+Hu79g7hZu6te6/YHgVJxCM2SqfIila0J3k0csfnf8VD2W7u2kzQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-netbsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.18.tgz", + "integrity": "sha512-98ukeCdvdX7wr1vUYQzKo4kQ0N2p27H7I11maINv73fVEXt2kyh4K4m9f35U1K43Xc2QGXlzAw0K9yoU7JUjOg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-openbsd-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.18.tgz", + "integrity": "sha512-yK5NCcH31Uae076AyQAXeJzt/vxIo9+omZRKj1pauhk3ITuADzuOx5N2fdHrAKPxN+zH3w96uFKlY7yIn490xQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-sunos-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.18.tgz", + "integrity": "sha512-On22LLFlBeLNj/YF3FT+cXcyKPEI263nflYlAhz5crxtp3yRG1Ugfr7ITyxmCmjm4vbN/dGrb/B7w7U8yJR9yw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-32": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.18.tgz", + "integrity": "sha512-o+eyLu2MjVny/nt+E0uPnBxYuJHBvho8vWsC2lV61A7wwTWC3jkN2w36jtA+yv1UgYkHRihPuQsL23hsCYGcOQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.18.tgz", + "integrity": "sha512-qinug1iTTaIIrCorAUjR0fcBk24fjzEedFYhhispP8Oc7SFvs+XeW3YpAKiKp8dRpizl4YYAhxMjlftAMJiaUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-windows-arm64": { + "version": "0.15.18", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.18.tgz", + "integrity": "sha512-q9bsYzegpZcLziq0zgUi5KqGVtfhjxGbnksaBFYmWLxeV/S1fK4OLdq2DFYnXcLMjlZw2L0jLsk1eGoB522WXQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/exsolve": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", + "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz", + "integrity": "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.30.2", + "lightningcss-darwin-arm64": "1.30.2", + "lightningcss-darwin-x64": "1.30.2", + "lightningcss-freebsd-x64": "1.30.2", + "lightningcss-linux-arm-gnueabihf": "1.30.2", + "lightningcss-linux-arm64-gnu": "1.30.2", + "lightningcss-linux-arm64-musl": "1.30.2", + "lightningcss-linux-x64-gnu": "1.30.2", + "lightningcss-linux-x64-musl": "1.30.2", + "lightningcss-win32-arm64-msvc": "1.30.2", + "lightningcss-win32-x64-msvc": "1.30.2" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.30.2.tgz", + "integrity": "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.30.2.tgz", + "integrity": "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.30.2.tgz", + "integrity": "sha512-oBZgKchomuDYxr7ilwLcyms6BCyLn0z8J0+ZZmfpjwg9fRVZIR5/GMXd7r9RH94iDhld3UmSjBM6nXWM2TfZTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.30.2.tgz", + "integrity": "sha512-c2bH6xTrf4BDpK8MoGG4Bd6zAMZDAXS569UxCAGcA7IKbHNMlhGQ89eRmvpIUGfKWNVdbhSbkQaWhEoMGmGslA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.30.2.tgz", + "integrity": "sha512-eVdpxh4wYcm0PofJIZVuYuLiqBIakQ9uFZmipf6LF/HRj5Bgm0eb3qL/mr1smyXIS1twwOxNWndd8z0E374hiA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.30.2.tgz", + "integrity": "sha512-UK65WJAbwIJbiBFXpxrbTNArtfuznvxAJw4Q2ZGlU8kPeDIWEX1dg3rn2veBVUylA2Ezg89ktszWbaQnxD/e3A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.30.2.tgz", + "integrity": "sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.30.2.tgz", + "integrity": "sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.30.2.tgz", + "integrity": "sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.30.2.tgz", + "integrity": "sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.30.2.tgz", + "integrity": "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/local-pkg": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.1.2.tgz", + "integrity": "sha512-arhlxbFRmoQHl33a0Zkle/YWlmNwoyt6QNZEIJcqNbdrsix5Lvc4HyyI3EnwxTYlZYc32EbYrQ8SzEZ7dqgg9A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.3.0", + "quansync": "^0.2.11" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/marked": { + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/marked/-/marked-17.0.1.tgz", + "integrity": "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mlly": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz", + "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.15.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.1" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/muggle-string": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.3.1.tgz", + "integrity": "sha512-ckmWDJjphvd/FvZawgygcUeQCxzvohjFO5RxTjj4eq8kw359gFF3E1brjfI+viLMxss5JrHTDRHZvu2/tuy0Qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/package-manager-detector": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz", + "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg-types": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", + "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.2.2", + "exsolve": "^1.0.7", + "pathe": "^2.0.3" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/quansync": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", + "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz", + "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rollup": { + "version": "2.79.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz", + "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", + "dev": true, + "license": "MIT", + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz", + "integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz", + "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", + "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/ufo": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz", + "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/unplugin": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.3.11.tgz", + "integrity": "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "acorn": "^8.15.0", + "picomatch": "^4.0.3", + "webpack-virtual-modules": "^0.6.2" + }, + "engines": { + "node": ">=18.12.0" + } + }, + "node_modules/unplugin-icons": { + "version": "23.0.1", + "resolved": "https://registry.npmjs.org/unplugin-icons/-/unplugin-icons-23.0.1.tgz", + "integrity": "sha512-rv0XEJepajKzDLvRUWASM8K+8+/CCfZn2jtogXqg6RIp7kpatRc/aFrVJn8ANQA09e++lPEEv9yX8cC9enc+QQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@antfu/install-pkg": "^1.1.0", + "@iconify/utils": "^3.1.0", + "local-pkg": "^1.1.2", + "obug": "^2.1.1", + "unplugin": "^2.3.11" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@svgr/core": ">=7.0.0", + "@svgx/core": "^1.0.1", + "@vue/compiler-sfc": "^3.0.2", + "svelte": "^3.0.0 || ^4.0.0 || ^5.0.0" + }, + "peerDependenciesMeta": { + "@svgr/core": { + "optional": true + }, + "@svgx/core": { + "optional": true + }, + "@vue/compiler-sfc": { + "optional": true + }, + "svelte": { + "optional": true + } + } + }, + "node_modules/unplugin-utils": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/unplugin-utils/-/unplugin-utils-0.3.1.tgz", + "integrity": "sha512-5lWVjgi6vuHhJ526bI4nlCOmkCIF3nnfXkCMDeMJrtdvxTs6ZFCM8oNufGTsDbKv/tJ/xj8RpvXjRuPBZJuJog==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/unplugin-vue-components": { + "version": "31.0.0", + "resolved": "https://registry.npmjs.org/unplugin-vue-components/-/unplugin-vue-components-31.0.0.tgz", + "integrity": "sha512-4ULwfTZTLuWJ7+S9P7TrcStYLsSRkk6vy2jt/WTfgUEUb0nW9//xxmrfhyHUEVpZ2UKRRwfRb8Yy15PDbVZf+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "local-pkg": "^1.1.2", + "magic-string": "^0.30.21", + "mlly": "^1.8.0", + "obug": "^2.1.1", + "picomatch": "^4.0.3", + "tinyglobby": "^0.2.15", + "unplugin": "^2.3.11", + "unplugin-utils": "^0.3.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "@nuxt/kit": "^3.2.2 || ^4.0.0", + "vue": "^3.0.0" + }, + "peerDependenciesMeta": { + "@nuxt/kit": { + "optional": true + } + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "3.2.11", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.11.tgz", + "integrity": "sha512-K/jGKL/PgbIgKCiJo5QbASQhFiV02X9Jh+Qq0AKCRCRKZtOTVi4t6wh75FDpGf2N9rYOnzH87OEFQNaFy6pdxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.15.9", + "postcss": "^8.4.18", + "resolve": "^1.22.1", + "rollup": "^2.79.1" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + }, + "peerDependencies": { + "@types/node": ">= 14", + "less": "*", + "sass": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/vue": { + "version": "3.5.27", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.27.tgz", + "integrity": "sha512-aJ/UtoEyFySPBGarREmN4z6qNKpbEguYHMmXSiOGk69czc+zhs0NF6tEFrY8TZKAl8N/LYAkd4JHVd5E/AsSmw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.27", + "@vue/compiler-sfc": "3.5.27", + "@vue/runtime-dom": "3.5.27", + "@vue/server-renderer": "3.5.27", + "@vue/shared": "3.5.27" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-i18n": { + "version": "9.14.5", + "resolved": "https://registry.npmjs.org/vue-i18n/-/vue-i18n-9.14.5.tgz", + "integrity": "sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==", + "deprecated": "v9 and v10 no longer supported. please migrate to v11. about maintenance status, see https://vue-i18n.intlify.dev/guide/maintenance.html", + "license": "MIT", + "dependencies": { + "@intlify/core-base": "9.14.5", + "@intlify/shared": "9.14.5", + "@vue/devtools-api": "^6.5.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/kazupon" + }, + "peerDependencies": { + "vue": "^3.0.0" + } + }, + "node_modules/vue-template-compiler": { + "version": "2.7.16", + "resolved": "https://registry.npmjs.org/vue-template-compiler/-/vue-template-compiler-2.7.16.tgz", + "integrity": "sha512-AYbUWAJHLGGQM7+cNTELw+KsOG9nl2CnSv467WobS5Cv9uk3wFcnr1Etsz2sEIHEZvw1U+o9mRlEO6QbZvUPGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "de-indent": "^1.0.2", + "he": "^1.2.0" + } + }, + "node_modules/vue-tsc": { + "version": "1.8.27", + "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-1.8.27.tgz", + "integrity": "sha512-WesKCAZCRAbmmhuGl3+VrdWItEvfoFIPXOvUJkjULi+x+6G/Dy69yO3TBRJDr9eUlmsNAwVmxsNZxvHKzbkKdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "~1.11.1", + "@vue/language-core": "1.8.27", + "semver": "^7.5.4" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": "*" + } + }, + "node_modules/webpack-virtual-modules": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", + "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/XSLPrintDot/frontend/package.json b/XSLPrintDot/frontend/package.json new file mode 100644 index 0000000..8fc6332 --- /dev/null +++ b/XSLPrintDot/frontend/package.json @@ -0,0 +1,30 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vue-tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "marked": "^17.0.1", + "vue": "^3.2.37", + "vue-i18n": "^9.14.5" + }, + "devDependencies": { + "@babel/types": "^7.18.10", + "@iconify-json/material-symbols": "^1.2.53", + "@tailwindcss/postcss": "^4.1.18", + "@vitejs/plugin-vue": "^3.0.3", + "autoprefixer": "^10.4.24", + "postcss": "^8.5.6", + "tailwindcss": "^4.1.18", + "typescript": "^4.6.4", + "unplugin-icons": "^23.0.1", + "unplugin-vue-components": "^31.0.0", + "vite": "^3.0.7", + "vue-tsc": "^1.8.27" + } +} diff --git a/XSLPrintDot/frontend/postcss.config.js b/XSLPrintDot/frontend/postcss.config.js new file mode 100644 index 0000000..1c87846 --- /dev/null +++ b/XSLPrintDot/frontend/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + '@tailwindcss/postcss': {}, + autoprefixer: {}, + }, +} diff --git a/XSLPrintDot/frontend/src/App.vue b/XSLPrintDot/frontend/src/App.vue new file mode 100644 index 0000000..56f45cb --- /dev/null +++ b/XSLPrintDot/frontend/src/App.vue @@ -0,0 +1,454 @@ + + + + + diff --git a/XSLPrintDot/frontend/src/assets/fonts/OFL.txt b/XSLPrintDot/frontend/src/assets/fonts/OFL.txt new file mode 100644 index 0000000..9cac04c --- /dev/null +++ b/XSLPrintDot/frontend/src/assets/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Nunito Project Authors (contact@sansoxygen.com), + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/XSLPrintDot/frontend/src/assets/fonts/nunito-v16-latin-regular.woff2 b/XSLPrintDot/frontend/src/assets/fonts/nunito-v16-latin-regular.woff2 new file mode 100644 index 0000000..2f9cc59 Binary files /dev/null and b/XSLPrintDot/frontend/src/assets/fonts/nunito-v16-latin-regular.woff2 differ diff --git a/XSLPrintDot/frontend/src/assets/images/logo-universal.png b/XSLPrintDot/frontend/src/assets/images/logo-universal.png new file mode 100644 index 0000000..d63303b Binary files /dev/null and b/XSLPrintDot/frontend/src/assets/images/logo-universal.png differ diff --git a/XSLPrintDot/frontend/src/components/Help.vue b/XSLPrintDot/frontend/src/components/Help.vue new file mode 100644 index 0000000..c3ce47b --- /dev/null +++ b/XSLPrintDot/frontend/src/components/Help.vue @@ -0,0 +1,70 @@ + + + + + \ No newline at end of file diff --git a/XSLPrintDot/frontend/src/components/Settings.vue b/XSLPrintDot/frontend/src/components/Settings.vue new file mode 100644 index 0000000..82f9840 --- /dev/null +++ b/XSLPrintDot/frontend/src/components/Settings.vue @@ -0,0 +1,338 @@ + + + \ No newline at end of file diff --git a/XSLPrintDot/frontend/src/i18n.ts b/XSLPrintDot/frontend/src/i18n.ts new file mode 100644 index 0000000..f16b2c1 --- /dev/null +++ b/XSLPrintDot/frontend/src/i18n.ts @@ -0,0 +1,15 @@ +import { createI18n } from 'vue-i18n' +import en from './locales/en.json' +import zh from './locales/zh.json' + +const i18n = createI18n({ + legacy: false, + locale: 'zh-CN', // default locale + fallbackLocale: 'en', + messages: { + 'en': en, + 'zh-CN': zh + } +}) + +export default i18n \ No newline at end of file diff --git a/XSLPrintDot/frontend/src/locales/en.json b/XSLPrintDot/frontend/src/locales/en.json new file mode 100644 index 0000000..218d610 --- /dev/null +++ b/XSLPrintDot/frontend/src/locales/en.json @@ -0,0 +1,58 @@ +{ + "settings": { + "title": "Settings", + "language": "Language", + "autoStart": "Start on Boot", + "remotePrint": "Remote Print Server", + "forwarding": "Cloud Print Forwarder", + "serverAddress": "Server Address", + "authAddress": "Auth Address", + "wsAddress": "WS Address", + "autoConnect": "Auto Reconnect", + "username": "Username", + "password": "Password", + "clientId": "Client ID", + "secretKey": "Secret Key", + "clientName": "Client Name (Optional)", + "deviceIdReadonly": "Device ID is auto-detected and cannot be edited", + "forwarderStatus": "Connection Status", + "connected": "Connected", + "disconnected": "Disconnected", + "connect": "Connect", + "connecting": "Connecting...", + "disconnect": "Disconnect", + "disconnecting": "Disconnecting...", + "lastError": "Last Error", + "save": "Save Settings", + "saving": "Saving...", + "saved": "Saved", + "restart": "Restart Now", + "confirmRestart": "Restart Required", + "confirmRestartMessage": "Applying these settings requires a restart. Do you want to restart now?", + "cancel": "Cancel" + }, + "main": { + "title": "XSL-PrintDot", + "subtitle": "WebSocket Printer Bridge", + "clients": "connections", + "serverControl": "Server Control", + "port": "Port", + "secretKey": "Secret Key (Optional)", + "placeholderKey": "Leave empty for no auth", + "startServer": "Start Server", + "stopServer": "Stop Server", + "connectionUrl": "Connection URL", + "availablePrinters": "Available Printers", + "defaultPrinter": "Default", + "refresh": "Refresh", + "loading": "Loading...", + "noPrinters": "No printers found.", + "clientConnected": "Client Connected" + }, + "logs": { + "title": "System Logs", + "subtitle": "Live system events", + "clearAll": "Clear All", + "empty": "No logs available yet..." + } +} \ No newline at end of file diff --git a/XSLPrintDot/frontend/src/locales/zh.json b/XSLPrintDot/frontend/src/locales/zh.json new file mode 100644 index 0000000..b7120b0 --- /dev/null +++ b/XSLPrintDot/frontend/src/locales/zh.json @@ -0,0 +1,58 @@ +{ + "settings": { + "title": "设置", + "language": "语言", + "autoStart": "开机自启动", + "remotePrint": "远程打印服务器", + "forwarding": "云打印中转服务", + "serverAddress": "服务器地址", + "authAddress": "鉴权地址", + "wsAddress": "WS地址", + "autoConnect": "自动重连", + "username": "用户名", + "password": "密码", + "clientId": "客户端ID", + "secretKey": "密钥", + "clientName": "客户端名称(可选)", + "deviceIdReadonly": "设备ID自动获取,无法修改", + "forwarderStatus": "连接状态", + "connected": "已连接", + "disconnected": "未连接", + "connect": "连接", + "connecting": "连接中...", + "disconnect": "断开", + "disconnecting": "断开中...", + "lastError": "最近错误", + "save": "保存", + "saving": "保存中...", + "saved": "已保存", + "restart": "立即重启", + "confirmRestart": "需要重启", + "confirmRestartMessage": "应用这些设置需要重启程序。是否立即重启?", + "cancel": "取消" + }, + "main": { + "title": "XSL-PrintDot", + "subtitle": "WebSocket 打印桥接器", + "clients": "个连接", + "serverControl": "服务控制", + "port": "端口", + "secretKey": "密钥 (可选)", + "placeholderKey": "留空则无需认证", + "startServer": "启动服务", + "stopServer": "停止服务", + "connectionUrl": "连接地址", + "availablePrinters": "可用打印机", + "defaultPrinter": "默认", + "refresh": "刷新", + "loading": "加载中...", + "noPrinters": "未找到打印机", + "clientConnected": "客户端已连接" + }, + "logs": { + "title": "系统日志", + "subtitle": "实时系统事件", + "clearAll": "清除所有", + "empty": "暂无日志..." + } +} \ No newline at end of file diff --git a/XSLPrintDot/frontend/src/main.ts b/XSLPrintDot/frontend/src/main.ts new file mode 100644 index 0000000..288cf9d --- /dev/null +++ b/XSLPrintDot/frontend/src/main.ts @@ -0,0 +1,6 @@ +import {createApp} from 'vue' +import App from './App.vue' +import './style.css'; +import i18n from './i18n' + +createApp(App).use(i18n).mount('#app') diff --git a/XSLPrintDot/frontend/src/style.css b/XSLPrintDot/frontend/src/style.css new file mode 100644 index 0000000..d11fd09 --- /dev/null +++ b/XSLPrintDot/frontend/src/style.css @@ -0,0 +1,42 @@ +@import "tailwindcss"; + + +html { + background-color: white; + /* text-align: center; Removed to fix left alignment issues */ + color: #1a202c; + overflow: hidden; /* Prevent window scrollbar */ +} + +body { + margin: 0; + color: #1a202c; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", + "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", + sans-serif; + overflow: hidden; /* Prevent body scrollbar */ +} + +/* Hide scrollbar for Chrome, Safari and Opera */ +::-webkit-scrollbar { + display: none; +} + +/* Hide scrollbar for IE, Edge and Firefox */ +html, body, #app { + -ms-overflow-style: none; /* IE and Edge */ + scrollbar-width: none; /* Firefox */ +} + +@font-face { + font-family: "Nunito"; + font-style: normal; + font-weight: 400; + src: local(""), + url("assets/fonts/nunito-v16-latin-regular.woff2") format("woff2"); +} + +#app { + height: 100vh; + /* text-align: center; Removed to fix left alignment issues */ +} diff --git a/XSLPrintDot/frontend/src/vite-env.d.ts b/XSLPrintDot/frontend/src/vite-env.d.ts new file mode 100644 index 0000000..dcfaef4 --- /dev/null +++ b/XSLPrintDot/frontend/src/vite-env.d.ts @@ -0,0 +1,7 @@ +/// + +declare module '*.vue' { + import type {DefineComponent} from 'vue' + const component: DefineComponent<{}, {}, any> + export default component +} diff --git a/XSLPrintDot/frontend/tailwind.config.js b/XSLPrintDot/frontend/tailwind.config.js new file mode 100644 index 0000000..bd3eb14 --- /dev/null +++ b/XSLPrintDot/frontend/tailwind.config.js @@ -0,0 +1,11 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: [ + "./index.html", + "./src/**/*.{vue,js,ts,jsx,tsx}", + ], + theme: { + extend: {}, + }, + plugins: [], +} diff --git a/XSLPrintDot/frontend/tsconfig.json b/XSLPrintDot/frontend/tsconfig.json new file mode 100644 index 0000000..3cc844d --- /dev/null +++ b/XSLPrintDot/frontend/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ESNext", + "useDefineForClassFields": true, + "module": "ESNext", + "moduleResolution": "Node", + "strict": true, + "jsx": "preserve", + "sourceMap": true, + "resolveJsonModule": true, + "isolatedModules": true, + "esModuleInterop": true, + "lib": [ + "ESNext", + "DOM" + ], + "skipLibCheck": true + }, + "include": [ + "src/**/*.ts", + "src/**/*.d.ts", + "src/**/*.tsx", + "src/**/*.vue" + ], + "references": [ + { + "path": "./tsconfig.node.json" + } + ] +} diff --git a/XSLPrintDot/frontend/tsconfig.node.json b/XSLPrintDot/frontend/tsconfig.node.json new file mode 100644 index 0000000..b8afcc8 --- /dev/null +++ b/XSLPrintDot/frontend/tsconfig.node.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "composite": true, + "module": "ESNext", + "moduleResolution": "Node", + "allowSyntheticDefaultImports": true + }, + "include": [ + "vite.config.ts" + ] +} diff --git a/XSLPrintDot/frontend/vite.config.ts b/XSLPrintDot/frontend/vite.config.ts new file mode 100644 index 0000000..3c792fb --- /dev/null +++ b/XSLPrintDot/frontend/vite.config.ts @@ -0,0 +1,23 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import Icons from 'unplugin-icons/vite' +import Components from 'unplugin-vue-components/vite' +import IconsResolver from 'unplugin-icons/resolver' + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [ + vue(), + Components({ + resolvers: [ + IconsResolver({ + prefix: 'i', // Prefix for components, e.g. + enabledCollections: ['material-symbols'] + }) + ] + }), + Icons({ + autoInstall: true + }) + ] +}) diff --git a/XSLPrintDot/go.mod b/XSLPrintDot/go.mod new file mode 100644 index 0000000..d83f937 --- /dev/null +++ b/XSLPrintDot/go.mod @@ -0,0 +1,44 @@ +module print-dot-client + +go 1.24.0 + +require ( + github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 + github.com/energye/systray v1.0.3 + github.com/gorilla/websocket v1.5.3 + github.com/wailsapp/wails/v2 v2.12.0 + golang.org/x/sys v0.40.0 +) + +require ( + git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect + github.com/bep/debounce v1.2.1 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect + github.com/labstack/echo/v4 v4.13.3 // indirect + github.com/labstack/gommon v0.4.2 // indirect + github.com/leaanthony/go-ansi-parser v1.6.1 // indirect + github.com/leaanthony/gosod v1.0.4 // indirect + github.com/leaanthony/slicer v1.6.0 // indirect + github.com/leaanthony/u v1.1.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.39.1 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/samber/lo v1.49.1 // indirect + github.com/tkrajina/go-reflector v0.5.8 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + github.com/wailsapp/go-webview2 v1.0.22 // indirect + github.com/wailsapp/mimetype v1.4.1 // indirect + golang.org/x/crypto v0.47.0 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/text v0.33.0 // indirect +) + +// replace github.com/wailsapp/wails/v2 v2.11.0 => C:\Users\admin\go\pkg\mod diff --git a/XSLPrintDot/go.sum b/XSLPrintDot/go.sum new file mode 100644 index 0000000..e5009a9 --- /dev/null +++ b/XSLPrintDot/go.sum @@ -0,0 +1,164 @@ +git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA= +git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc= +github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY= +github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0= +github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21 h1:tuijfIjZyjZaHq9xDUh0tNitwXshJpbLkqMOJv4H3do= +github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21/go.mod h1:po7NpZ/QiTKzBKyrsEAxwnTamCoh8uDk/egRpQ7siIc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/energye/systray v1.0.3 h1:XnyjJCeRU5z00bpNOic2fGTKz/7yHZMZjWiGIVXDS+4= +github.com/energye/systray v1.0.3/go.mod h1:HelKhC3PXwv3ryDxbuQqV+7kAxAYNzE5cfdrerGOZTc= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck= +github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs= +github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY= +github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g= +github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0= +github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU= +github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc= +github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA= +github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A= +github.com/leaanthony/go-ansi-parser v1.6.1/go.mod h1:+vva/2y4alzVmmIEpk9QDhA7vLC5zKDTRwfZGOp3IWU= +github.com/leaanthony/gosod v1.0.4 h1:YLAbVyd591MRffDgxUOU1NwLhT9T1/YiwjKZpkNFeaI= +github.com/leaanthony/gosod v1.0.4/go.mod h1:GKuIL0zzPj3O1SdWQOdgURSuhkF+Urizzxh26t9f1cw= +github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/Js= +github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8= +github.com/leaanthony/u v1.1.1 h1:TUFjwDGlNX+WuwVEzDqQwC2lOv0P4uhTQw7CMFdiK7M= +github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI= +github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= +github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= +github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= +github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew= +github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ= +github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/wailsapp/go-webview2 v1.0.22 h1:YT61F5lj+GGaat5OB96Aa3b4QA+mybD0Ggq6NZijQ58= +github.com/wailsapp/go-webview2 v1.0.22/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc= +github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs= +github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o= +github.com/wailsapp/wails/v2 v2.12.0 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c= +github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/XSLPrintDot/i18n.go b/XSLPrintDot/i18n.go new file mode 100644 index 0000000..1c6de0f --- /dev/null +++ b/XSLPrintDot/i18n.go @@ -0,0 +1,84 @@ +package main + +import ( + "embed" + "encoding/json" + "fmt" + "strings" + "sync" +) + +//go:embed locales/*.json +var localeFS embed.FS + +var ( + translations map[string]interface{} + i18nMu sync.RWMutex +) + +// LoadLocales loads the locale file based on the language code +func LoadLocales(lang string) error { + i18nMu.Lock() + defer i18nMu.Unlock() + + // Map generic codes to file names + filename := "locales/en.json" + if lang == "zh-CN" || lang == "zh" { + filename = "locales/zh.json" + } + + content, err := localeFS.ReadFile(filename) + if err != nil { + // Fallback to en if specific locale fails + if filename != "locales/en.json" { + content, err = localeFS.ReadFile("locales/en.json") + if err != nil { + return err + } + } else { + return err + } + } + + var data map[string]interface{} + if err := json.Unmarshal(content, &data); err != nil { + return err + } + + translations = data + return nil +} + +// T translates a key. Nested keys can be accessed with dot notation (e.g., "menu.title") +func T(key string, args ...interface{}) string { + i18nMu.RLock() + defer i18nMu.RUnlock() + + if translations == nil { + return key + } + + keys := strings.Split(key, ".") + var val interface{} = translations + + for _, k := range keys { + if m, ok := val.(map[string]interface{}); ok { + if v, exists := m[k]; exists { + val = v + } else { + return key + } + } else { + return key + } + } + + if str, ok := val.(string); ok { + if len(args) > 0 { + return fmt.Sprintf(str, args...) + } + return str + } + + return key +} diff --git a/XSLPrintDot/locales/en.json b/XSLPrintDot/locales/en.json new file mode 100644 index 0000000..45f9433 --- /dev/null +++ b/XSLPrintDot/locales/en.json @@ -0,0 +1,25 @@ +{ + "menu": { + "title": "Menu", + "settings": "Settings", + "logs": "System Logs", + "help": "Help", + "quit": "Quit" + }, + "tray": { + "show": "Show Main Window", + "quit": "Quit", + "title": "XSL-PrintDot", + "tooltip": "XSL-PrintDot" + }, + "window": { + "logs": "System Logs", + "help": "Help - Usage Guide", + "settings": "Settings", + "main": "XSL-PrintDot" + }, + "notification": { + "title": "XSL-PrintDot", + "connected": "Client connected: %s" + } +} diff --git a/XSLPrintDot/locales/zh.json b/XSLPrintDot/locales/zh.json new file mode 100644 index 0000000..35fb499 --- /dev/null +++ b/XSLPrintDot/locales/zh.json @@ -0,0 +1,25 @@ +{ + "menu": { + "title": "菜单", + "settings": "设置", + "logs": "系统日志", + "help": "帮助", + "quit": "退出" + }, + "tray": { + "show": "显示主窗口", + "quit": "退出", + "title": "XSL-PrintDot", + "tooltip": "XSL-PrintDot" + }, + "window": { + "logs": "系统日志", + "help": "帮助 - 使用指南", + "settings": "设置", + "main": "XSL-PrintDot" + }, + "notification": { + "title": "XSL-PrintDot", + "connected": "客户端已连接: %s" + } +} diff --git a/XSLPrintDot/main.go b/XSLPrintDot/main.go new file mode 100644 index 0000000..73a883b --- /dev/null +++ b/XSLPrintDot/main.go @@ -0,0 +1,230 @@ +package main + +import ( + "context" + "embed" + sys_runtime "runtime" + + "os" + "strconv" + + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/menu" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/mac" + "github.com/wailsapp/wails/v2/pkg/options/windows" + "github.com/wailsapp/wails/v2/pkg/runtime" + + "github.com/energye/systray" +) + +//go:embed all:frontend/dist +var assets embed.FS + +//go:embed build/appicon.png +var icon []byte + +//go:embed build/windows/icon.ico +var iconIco []byte + +func main() { + // Check command line args + mode := "main" + logPort := 0 + + if len(os.Args) > 1 { + switch os.Args[1] { + case "logs": + mode = "logs" + if len(os.Args) > 2 { + if p, err := strconv.Atoi(os.Args[2]); err == nil { + logPort = p + } + } + case "help": + mode = "help" + case "settings": + mode = "settings" + if len(os.Args) > 2 { + if p, err := strconv.Atoi(os.Args[2]); err == nil { + logPort = p + } + } + } + } + + // Create an instance of the app structure + app := NewApp(mode, logPort) + + // Load settings to determine menu language + sm := NewSettingsManager() + currentLang := sm.Get().Language + LoadLocales(currentLang) + + // Configure based on mode + title := T("window.main") + width := 380 + height := 660 + minWidth := 380 + minHeight := 600 + var onBeforeClose func(ctx context.Context) bool + + var appMenu *menu.Menu + + if mode == "main" { + appMenu = app.CreateMenu(currentLang) + + onBeforeClose = func(ctx context.Context) bool { + if app.isQuitting { + app.Cleanup() + return false + } + runtime.WindowHide(ctx) + return true + } + + // Start system tray + go func() { + sys_runtime.LockOSThread() + systray.Run(func() { + if sys_runtime.GOOS == "windows" { + systray.SetIcon(iconIco) + } else { + systray.SetIcon(icon) + } + systray.SetTitle(T("tray.title")) + systray.SetTooltip(T("tray.tooltip")) + + systray.SetOnClick(func(menu systray.IMenu) { + go func() { + if app.ctx != nil { + runtime.WindowShow(app.ctx) + } + }() + }) + systray.SetOnRClick(func(menu systray.IMenu) { + menu.ShowMenu() + }) + + mShow := systray.AddMenuItem(T("tray.show"), T("tray.show")) + mHelp := systray.AddMenuItem(T("menu.help"), T("menu.help")) + mSettings := systray.AddMenuItem(T("menu.settings"), T("menu.settings")) + systray.AddSeparator() + mQuit := systray.AddMenuItem(T("tray.quit"), T("tray.quit")) + + mShow.Click(func() { + go func() { + if app.ctx != nil { + runtime.WindowShow(app.ctx) + } + }() + }) + mHelp.Click(func() { + go app.ShowHelp() + }) + mSettings.Click(func() { + go app.ShowSettings() + }) + mQuit.Click(func() { + go app.Quit() + }) + }, func() { + // Cleanup if needed + }) + }() + } else if mode == "logs" { + // Logs Window Configuration + title = T("window.logs") + width = 700 + height = 500 + // No special menu or close behavior for logs window (it just closes) + } else if mode == "help" { + title = T("window.help") + width = 800 + height = 600 + minWidth = 600 + minHeight = 400 + } else if mode == "settings" { + title = T("window.settings") + } + + // Create application with options + appOptions := &options.App{ + Title: title, + Width: width, + Height: height, + MinWidth: minWidth, + MinHeight: minHeight, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 1}, + OnStartup: func(ctx context.Context) { + app.startup(ctx) + // Restore position if valid + if mode == "main" { + s := sm.Get() + if s.WindowX != 0 || s.WindowY != 0 { + runtime.WindowSetPosition(ctx, s.WindowX, s.WindowY) + } + if s.Maximized { + runtime.WindowMaximise(ctx) + } + } + }, + OnBeforeClose: onBeforeClose, + Menu: appMenu, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewIsTransparent: false, + WindowIsTranslucent: false, + BackdropType: windows.Mica, + }, + Mac: &mac.Options{ + TitleBar: mac.TitleBarHiddenInset(), + }, + } + + if mode == "main" { + appOptions.SingleInstanceLock = &options.SingleInstanceLock{ + UniqueId: "56006c0a-0498-4228-a320-c2409044a14e", + OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) { + runtime.WindowShow(app.ctx) + }, + } + } else if mode == "logs" { + appOptions.SingleInstanceLock = &options.SingleInstanceLock{ + UniqueId: "56006c0a-0498-4228-a320-c2409044a14e-logs", + OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) { + runtime.WindowShow(app.ctx) + }, + } + } else if mode == "help" { + appOptions.SingleInstanceLock = &options.SingleInstanceLock{ + UniqueId: "56006c0a-0498-4228-a320-c2409044a14e-help", + OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) { + runtime.WindowShow(app.ctx) + }, + } + } else if mode == "settings" { + appOptions.SingleInstanceLock = &options.SingleInstanceLock{ + UniqueId: "56006c0a-0498-4228-a320-c2409044a14e-settings", + OnSecondInstanceLaunch: func(secondInstanceData options.SecondInstanceData) { + runtime.WindowShow(app.ctx) + }, + } + } + + err := wails.Run(appOptions) + + if mode == "main" { + systray.Quit() + } + + if err != nil { + println("Error:", err.Error()) + } +} diff --git a/XSLPrintDot/npx-out.txt b/XSLPrintDot/npx-out.txt new file mode 100644 index 0000000..80f568d Binary files /dev/null and b/XSLPrintDot/npx-out.txt differ diff --git a/XSLPrintDot/scripts/uninstall.sh b/XSLPrintDot/scripts/uninstall.sh new file mode 100644 index 0000000..0d12084 --- /dev/null +++ b/XSLPrintDot/scripts/uninstall.sh @@ -0,0 +1,37 @@ +#!/bin/sh +set -e + +remove_data_linux() { + if [ -n "${XDG_DATA_HOME:-}" ]; then + BASE_DIR="$XDG_DATA_HOME/PrintDot" + elif [ -n "${HOME:-}" ]; then + BASE_DIR="$HOME/.local/share/PrintDot" + else + BASE_DIR="" + fi + + if [ -n "$BASE_DIR" ]; then + rm -rf "$BASE_DIR" + fi +} + +remove_data_macos() { + if [ -n "${HOME:-}" ]; then + rm -rf "$HOME/Library/Application Support/PrintDot" + fi +} + +case "$(uname -s)" in + Darwin) + remove_data_macos + ;; + Linux) + remove_data_linux + ;; + *) + echo "Unsupported OS: $(uname -s)" + exit 1 + ;; +esac + +echo "PrintDot data removed." diff --git a/XSLPrintDot/settings.go b/XSLPrintDot/settings.go new file mode 100644 index 0000000..de78523 --- /dev/null +++ b/XSLPrintDot/settings.go @@ -0,0 +1,181 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "sync" + + "github.com/cloudfoundry/jibber_jabber" +) + +type AppSettings struct { + Language string `json:"language"` + AutoStart bool `json:"autoStart"` + RemoteAutoConnect bool `json:"remoteAutoConnect"` + ServerPort string `json:"serverPort"` + ServerKey string `json:"serverKey"` + RemoteServer string `json:"remoteServer"` + RemoteAuthURL string `json:"remoteAuthUrl"` + RemoteWsURL string `json:"remoteWsUrl"` + RemoteUser string `json:"remoteUser"` + RemotePassword string `json:"remotePassword"` + RemoteClientID string `json:"remoteClientId"` + RemoteSecretKey string `json:"remoteSecretKey"` + RemoteClientName string `json:"remoteClientName"` + // Window State + WindowWidth int `json:"windowWidth"` + WindowHeight int `json:"windowHeight"` + WindowX int `json:"windowX"` + WindowY int `json:"windowY"` + Maximized bool `json:"maximized"` +} + +type SettingsManager struct { + settings AppSettings + mu sync.Mutex + filePath string +} + +func NewSettingsManager() *SettingsManager { + appConfigDir, err := dataDirPath() + if err != nil { + configDir, _ := os.UserConfigDir() + appConfigDir = filepath.Join(configDir, "PrintDot") + } + os.MkdirAll(appConfigDir, 0755) + + // Detect language + defaultLang := "en-US" + userLang, err := jibber_jabber.DetectLanguage() + if err == nil && strings.ToLower(userLang) == "zh" { + defaultLang = "zh-CN" + } + + sm := &SettingsManager{ + filePath: filepath.Join(appConfigDir, "settings.json"), + settings: AppSettings{ + Language: defaultLang, + AutoStart: false, + RemoteAutoConnect: true, + ServerPort: "1122", + }, + } + sm.Load() + return sm +} + +func (sm *SettingsManager) Load() { + sm.mu.Lock() + defer sm.mu.Unlock() + + data, err := os.ReadFile(sm.filePath) + if err == nil { + json.Unmarshal(data, &sm.settings) + var raw map[string]interface{} + if json.Unmarshal(data, &raw) == nil { + if _, ok := raw["remoteAutoConnect"]; !ok { + sm.settings.RemoteAutoConnect = true + } + } + } + + if sm.settings.RemoteClientID == "" && sm.settings.RemoteUser != "" { + sm.settings.RemoteClientID = sm.settings.RemoteUser + } + if sm.settings.RemoteSecretKey == "" && sm.settings.RemotePassword != "" { + sm.settings.RemoteSecretKey = sm.settings.RemotePassword + } + + if sm.settings.RemoteAuthURL == "" && sm.settings.RemoteWsURL == "" && sm.settings.RemoteServer != "" { + if loginURL, wsURL, err := buildRemoteURLs(sm.settings.RemoteServer); err == nil { + sm.settings.RemoteAuthURL = loginURL.String() + sm.settings.RemoteWsURL = wsURL.String() + } + } + + if strings.TrimSpace(sm.settings.ServerPort) == "" { + sm.settings.ServerPort = "1122" + } + + applyDefaultClientIdentity(&sm.settings) +} + +func (sm *SettingsManager) Save(settings AppSettings) error { + sm.mu.Lock() + defer sm.mu.Unlock() + + if settings.RemoteClientID == "" && settings.RemoteUser != "" { + settings.RemoteClientID = settings.RemoteUser + } + if settings.RemoteUser == "" && settings.RemoteClientID != "" { + settings.RemoteUser = settings.RemoteClientID + } + if settings.RemoteSecretKey == "" && settings.RemotePassword != "" { + settings.RemoteSecretKey = settings.RemotePassword + } + if settings.RemotePassword == "" && settings.RemoteSecretKey != "" { + settings.RemotePassword = settings.RemoteSecretKey + } + + if settings.RemoteAuthURL == "" && settings.RemoteWsURL == "" && settings.RemoteServer != "" { + if loginURL, wsURL, err := buildRemoteURLs(settings.RemoteServer); err == nil { + settings.RemoteAuthURL = loginURL.String() + settings.RemoteWsURL = wsURL.String() + } + } + + applyDefaultClientIdentity(&settings) + + sm.settings = settings + data, err := json.MarshalIndent(settings, "", " ") + if err != nil { + return err + } + + // Handle AutoStart + if settings.AutoStart != sm.settings.AutoStart { + setAutoStart(settings.AutoStart) + } + + return os.WriteFile(sm.filePath, data, 0644) +} + +func (sm *SettingsManager) Get() AppSettings { + sm.mu.Lock() + defer sm.mu.Unlock() + return sm.settings +} + +func applyDefaultClientIdentity(settings *AppSettings) { + id, name := defaultClientIdentity() + if id != "" { + settings.RemoteClientID = id + } + if settings.RemoteClientName == "" { + settings.RemoteClientName = name + } +} + +func defaultClientIdentity() (string, string) { + name := strings.TrimSpace(os.Getenv("COMPUTERNAME")) + if name == "" { + if host, err := os.Hostname(); err == nil { + name = strings.TrimSpace(host) + } + } + if name == "" { + name = "XSL-PrintDot" + } + + id := getNormalizedDeviceID() + if id == "" { + id = strings.ToLower(name) + id = strings.ReplaceAll(id, " ", "-") + id = strings.ReplaceAll(id, "_", "-") + id = strings.ReplaceAll(id, "/", "-") + } + + return id, name +} diff --git a/XSLPrintDot/tmp_test.ico b/XSLPrintDot/tmp_test.ico new file mode 100644 index 0000000..395dee2 Binary files /dev/null and b/XSLPrintDot/tmp_test.ico differ diff --git a/XSLPrintDot/wails.json b/XSLPrintDot/wails.json new file mode 100644 index 0000000..f2638ae --- /dev/null +++ b/XSLPrintDot/wails.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://wails.io/schemas/config.v2.json", + "name": "XSL-PrintDot", + "outputfilename": "XSL-PrintDot", + "frontend:install": "npm install", + "frontend:build": "npm run build", + "frontend:dev:watcher": "npm run dev", + "frontend:dev:serverUrl": "auto", + "author": { + "name": "Jonny", + "email": "1515188277@qq.com" + }, + "info": { + "productVersion": "1.1.1" + } +} diff --git a/jeecg-boot/db/mes-xsl-biz-entity-field-detail-alter-slot-columns.sql b/jeecg-boot/db/mes-xsl-biz-entity-field-detail-alter-slot-columns.sql new file mode 100644 index 0000000..7d716f7 --- /dev/null +++ b/jeecg-boot/db/mes-xsl-biz-entity-field-detail-alter-slot-columns.sql @@ -0,0 +1,28 @@ +-- 升级脚本:仅为缺失的列执行 ADD,可重复执行(不会因「列已存在」报错) +-- 适用:旧库 mes_xsl_biz_entity_field_detail 缺少 detail_property_name / detail_slot_kind + +SET NAMES utf8mb4; + +SELECT COUNT(*) INTO @jeecg_chk_dpn FROM information_schema.COLUMNS +WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'mes_xsl_biz_entity_field_detail' + AND COLUMN_NAME = 'detail_property_name'; + +SET @jeecg_sql_dpn := IF(@jeecg_chk_dpn = 0, + 'ALTER TABLE mes_xsl_biz_entity_field_detail ADD COLUMN detail_property_name varchar(128) DEFAULT NULL COMMENT ''主实体明细属性名(与打印绑定 detailProperty 一致)'' AFTER profile_id', + 'SELECT ''detail_property_name 已存在,跳过'' AS msg'); +PREPARE jeecg_stmt_dpn FROM @jeecg_sql_dpn; +EXECUTE jeecg_stmt_dpn; +DEALLOCATE PREPARE jeecg_stmt_dpn; + +SELECT COUNT(*) INTO @jeecg_chk_dsk FROM information_schema.COLUMNS +WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'mes_xsl_biz_entity_field_detail' + AND COLUMN_NAME = 'detail_slot_kind'; + +SET @jeecg_sql_dsk := IF(@jeecg_chk_dsk = 0, + 'ALTER TABLE mes_xsl_biz_entity_field_detail ADD COLUMN detail_slot_kind varchar(16) DEFAULT NULL COMMENT ''LIST 或 OBJECT'' AFTER detail_property_name', + 'SELECT ''detail_slot_kind 已存在,跳过'' AS msg'); +PREPARE jeecg_stmt_dsk FROM @jeecg_sql_dsk; +EXECUTE jeecg_stmt_dsk; +DEALLOCATE PREPARE jeecg_stmt_dsk; diff --git a/jeecg-boot/db/mes-xsl-biz-entity-field-profile.sql b/jeecg-boot/db/mes-xsl-biz-entity-field-profile.sql new file mode 100644 index 0000000..816960d --- /dev/null +++ b/jeecg-boot/db/mes-xsl-biz-entity-field-profile.sql @@ -0,0 +1,38 @@ +-- 业务实体字段配置(主表 + 明细:每条明细对应一类「明细表」及其字段列表) +SET NAMES utf8mb4; + +CREATE TABLE IF NOT EXISTS `mes_xsl_biz_entity_field_profile` ( + `id` varchar(32) NOT NULL COMMENT '主键', + `business_name` varchar(200) NOT NULL COMMENT '业务名称', + `business_code` varchar(64) NOT NULL COMMENT '业务编码(菜单 permission id,与打印 biz_code 一致,唯一)', + `entity_class_name` varchar(512) DEFAULT NULL COMMENT '主实体 Java 全限定类名', + `main_fields_json` text COMMENT '主表实体字段列表(JSON 数组,元素可为字符串字段名或含 name/comment/javaType 的对象)', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `tenant_id` int DEFAULT NULL COMMENT '租户ID', + `create_by` varchar(32) DEFAULT NULL COMMENT '创建人', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + `update_by` varchar(32) DEFAULT NULL COMMENT '更新人', + `update_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_mxbefp_bcode` (`business_code`), + KEY `idx_mxbefp_tenant` (`tenant_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES业务实体字段配置-主表'; + +CREATE TABLE IF NOT EXISTS `mes_xsl_biz_entity_field_detail` ( + `id` varchar(32) NOT NULL COMMENT '主键', + `profile_id` varchar(32) NOT NULL COMMENT '主表ID', + `detail_property_name` varchar(128) DEFAULT NULL COMMENT '主实体明细属性名(与打印绑定 detailProperty 一致)', + `detail_slot_kind` varchar(16) DEFAULT NULL COMMENT 'LIST 或 OBJECT', + `detail_name` varchar(200) DEFAULT NULL COMMENT '明细展示名称', + `detail_entity_class_name` varchar(512) DEFAULT NULL COMMENT '明细实体 Java 全限定类名', + `detail_fields_json` text COMMENT '明细表字段列表(JSON 数组,规则同 main_fields_json)', + `sort_no` int DEFAULT NULL COMMENT '排序号', + `create_by` varchar(32) DEFAULT NULL COMMENT '创建人', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + `update_by` varchar(32) DEFAULT NULL COMMENT '更新人', + `update_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + KEY `idx_mxbefd_profile` (`profile_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES业务实体字段配置-明细表字段清单'; + +-- ─── 旧表缺列时执行(见 db/mes-xsl-biz-entity-field-detail-alter-slot-columns.sql 或 Flyway V3.9.2_55)─── diff --git a/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/ShiroConfig.java b/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/ShiroConfig.java index ff49bd1..ace9fb2 100644 --- a/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/ShiroConfig.java +++ b/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/config/shiro/ShiroConfig.java @@ -213,6 +213,9 @@ public class ShiroConfig { filterChainDefinitionMap.put("/xslmes/mesXslWarehouseArea/anon/**", "anon"); // MES密炼物料管理免密接口(供桌面端调用) filterChainDefinitionMap.put("/mes/material/mixerMaterial/anon/**", "anon"); + // 打印模板免密接口(供桌面端调用) + filterChainDefinitionMap.put("/print/template/anon/**", "anon"); + filterChainDefinitionMap.put("/print/bizTemplateBind/anon/**", "anon"); // 系统分类字典免密接口(供桌面端调用) filterChainDefinitionMap.put("/sys/category/anon/**", "anon"); // 桌面端用户反同步批量上报(Outbox -> /sys/sync/batch) diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-print/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-print/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java index 1f72634..0181d8f 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-print/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-print/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java @@ -198,6 +198,36 @@ public class PrintTemplateController extends JeecgController anonQueryByCode(@RequestParam(name = "code") String code) { + PrintTemplate t = service.getByCode(code); + if (t == null) { + return Result.error("未找到模板: " + code); + } + return Result.OK(t); + } + + /** + * 免密-分页列表(供 WPF 桌面端匿名调用,用于打印设置页选择模板) + */ + @Operation(summary = "打印模板-免密分页列表(桌面端)") + @GetMapping(value = "/anon/list") + public Result> anonList(PrintTemplate query, + @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, + @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, + HttpServletRequest req) { + QueryWrapper qw = QueryGenerator.initQueryWrapper(query, req.getParameterMap()); + qw.orderByAsc("template_code"); + Page page = new Page<>(pageNo, pageSize); + return Result.OK(service.page(page, qw)); + } + @AutoLog(value = "打印模板-图片分析生成原生JSON") @Operation(summary = "打印模板-上传图片分析为原生模板JSON(前端传 imageBase64;可接 OpenAI 兼容视觉模型)") @PostMapping(value = "/analyzeImageForNative") diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/pom.xml b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/pom.xml index 19b8ebd..23cc3e1 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/pom.xml +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/pom.xml @@ -18,5 +18,11 @@ org.jeecgframework.boot3 jeecg-boot-base-core + + + org.jeecgframework.boot3 + jeecg-system-biz + ${jeecgboot.version} + diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/bootstrap/BizEntityFieldCatalogSyncRunner.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/bootstrap/BizEntityFieldCatalogSyncRunner.java new file mode 100644 index 0000000..f11b61a --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/bootstrap/BizEntityFieldCatalogSyncRunner.java @@ -0,0 +1,164 @@ +package org.jeecg.modules.xslmes.bootstrap; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.Resource; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.entity.PrintBizPermEntity; +import org.jeecg.modules.print.service.IPrintBizPermEntityService; +import org.jeecg.modules.print.util.PrintBizDetailPropertyScanner; +import org.jeecg.modules.print.util.PrintBizEntityFieldIntrospector; +import org.jeecg.modules.print.vo.PrintBizDetailSlotVO; +import org.jeecg.modules.print.vo.PrintBizFieldItemVO; +import org.jeecg.modules.system.entity.SysPermission; +import org.jeecg.modules.system.service.ISysPermissionService; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail; +import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * 启动后异步:遍历 {@code print_biz_perm_entity} 中已配置实体类的业务,反射主表与明细槽位字段并写入 {@code mes_xsl_biz_entity_field_*}, + * 供「业务打印绑定」弹窗读取(避免运行时频繁反射)。 + * + *

关闭:{@code jeecg.print.biz-entity-field-catalog-sync=false} + * + *

建议在 {@link org.jeecg.modules.print.bootstrap.PrintBizPermEntityWarmupRunner}(Order 2000)之后执行。 + */ +@Slf4j +@Component +@Order(2100) +public class BizEntityFieldCatalogSyncRunner implements ApplicationRunner { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @Resource + private IPrintBizPermEntityService printBizPermEntityService; + + @Resource + private IMesXslBizEntityFieldProfileService bizEntityFieldProfileService; + + @Resource + private ISysPermissionService sysPermissionService; + + @Value("${jeecg.print.biz-entity-field-catalog-sync:true}") + private boolean syncEnabled; + + /** 延迟执行秒数,便于晚于「打印菜单实体映射预热」写完 print_biz_perm_entity */ + @Value("${jeecg.print.biz-entity-field-catalog-sync-delay-seconds:10}") + private int catalogSyncDelaySeconds; + + @Override + public void run(ApplicationArguments args) { + if (!syncEnabled) { + log.info("业务实体字段缓存同步已关闭(jeecg.print.biz-entity-field-catalog-sync=false)"); + return; + } + log.info( + "业务实体字段缓存:将在 {} 秒后异步同步(来源 print_biz_perm_entity → mes_xsl_biz_entity_field_*)", + Math.max(0, catalogSyncDelaySeconds)); + CompletableFuture.runAsync( + this::doSync, + CompletableFuture.delayedExecutor( + Math.max(0, catalogSyncDelaySeconds), + TimeUnit.SECONDS, + ForkJoinPool.commonPool())); + } + + private void doSync() { + try { + log.info("业务实体字段缓存:开始异步同步(来源 print_biz_perm_entity)"); + List rows = printBizPermEntityService.list(); + if (rows == null || rows.isEmpty()) { + log.info("业务实体字段缓存:print_biz_perm_entity 无数据,跳过"); + return; + } + int ok = 0; + int skip = 0; + for (PrintBizPermEntity row : rows) { + if (row == null || StringUtils.isBlank(row.getPermId())) { + skip++; + continue; + } + String permId = row.getPermId().trim(); + String entityFqn = StringUtils.trimToNull(row.getEntityClass()); + if (entityFqn == null) { + skip++; + continue; + } + Class clazz = PrintBizEntityFieldIntrospector.tryLoadClass(entityFqn); + if (clazz == null) { + skip++; + continue; + } + try { + syncOne(permId, clazz, entityFqn); + ok++; + } catch (Exception ex) { + log.warn("业务实体字段缓存同步失败 permId={} entity={}", permId, entityFqn, ex); + skip++; + } + } + log.info("业务实体字段缓存同步完成:成功 {} 条,跳过 {} 条", ok, skip); + } catch (Exception e) { + log.warn("业务实体字段缓存同步异常(不影响系统启动)", e); + } + } + + private void syncOne(String permId, Class clazz, String entityFqn) throws Exception { + List mainFields = PrintBizEntityFieldIntrospector.listFields(clazz); + String mainJson = OBJECT_MAPPER.writeValueAsString(mainFields); + + List slots = PrintBizDetailPropertyScanner.listSlots(clazz); + List detailRows = new ArrayList<>(); + int sort = 0; + Date now = new Date(); + for (PrintBizDetailSlotVO slot : slots) { + Class itemClazz = + PrintBizDetailPropertyScanner.resolveItemClassForSlot( + clazz, slot.getPropertyName(), slot.getSlotKind()); + if (itemClazz == null) { + continue; + } + List itemFields = PrintBizEntityFieldIntrospector.listFields(itemClazz); + MesXslBizEntityFieldDetail d = new MesXslBizEntityFieldDetail(); + d.setDetailPropertyName(slot.getPropertyName()); + d.setDetailSlotKind(slot.getSlotKind()); + d.setDetailName(slot.getLabel()); + d.setDetailEntityClassName(fqn(itemClazz)); + d.setDetailFieldsJson(OBJECT_MAPPER.writeValueAsString(itemFields)); + d.setSortNo(sort++); + d.setCreateTime(now); + d.setUpdateTime(now); + detailRows.add(d); + } + + String bizName = resolveMenuName(permId); + bizEntityFieldProfileService.upsertScannedProfile(permId, bizName, entityFqn, mainJson, detailRows); + } + + private static String fqn(Class c) { + if (c == null) { + return null; + } + String cn = c.getCanonicalName(); + return cn != null ? cn : c.getName(); + } + + private String resolveMenuName(String permId) { + SysPermission p = sysPermissionService.getById(permId); + if (p != null && StringUtils.isNotBlank(p.getName())) { + return p.getName().trim(); + } + return permId; + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/WarehouseAreaActualCapacityContribution.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/WarehouseAreaActualCapacityContribution.java new file mode 100644 index 0000000..87fc11a --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/WarehouseAreaActualCapacityContribution.java @@ -0,0 +1,16 @@ +package org.jeecg.modules.xslmes.capacity; + +import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; + +import java.util.List; + +/** + * 库区展示用「实际存放量」数据源贡献者(可多实现并按 Spring Order 编排) + */ +public interface WarehouseAreaActualCapacityContribution { + + /** + * @param areas 通常为列表/分页的一段记录(内存回填,不写库) + */ + void contribute(List areas); +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/WarehouseAreaDisplayedActualCapacityMediator.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/WarehouseAreaDisplayedActualCapacityMediator.java new file mode 100644 index 0000000..4519d26 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/WarehouseAreaDisplayedActualCapacityMediator.java @@ -0,0 +1,31 @@ +package org.jeecg.modules.xslmes.capacity; + +import lombok.RequiredArgsConstructor; +import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; +import org.springframework.core.annotation.AnnotationAwareOrderComparator; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * 编排库区「实际存放量」展示回填(可多 {@link WarehouseAreaActualCapacityContribution} 扩展)。 + */ +@Component +@RequiredArgsConstructor +public class WarehouseAreaDisplayedActualCapacityMediator { + + private final List contributions; + + public void apply(Collection areas) { + if (areas == null || areas.isEmpty()) { + return; + } + List list = new ArrayList<>(areas); + List ordered = contributions.stream().sorted(AnnotationAwareOrderComparator.INSTANCE).toList(); + for (WarehouseAreaActualCapacityContribution c : ordered) { + c.contribute(list); + } + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/impl/RawMaterialCardRemainQtyCapacityContribution.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/impl/RawMaterialCardRemainQtyCapacityContribution.java new file mode 100644 index 0000000..7e113f3 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/capacity/impl/RawMaterialCardRemainQtyCapacityContribution.java @@ -0,0 +1,134 @@ +package org.jeecg.modules.xslmes.capacity.impl; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.xslmes.capacity.WarehouseAreaActualCapacityContribution; +import org.jeecg.modules.xslmes.config.XslMesWarehouseAreaCapacityProperties; +import org.jeecg.modules.xslmes.dto.MesXslAreaRemainQtySumDTO; +import org.jeecg.modules.system.service.ISysCategoryService; +import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; +import org.jeecg.modules.xslmes.mapper.MesXslRawMaterialCardMapper; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 用「原材料卡片」按库区(trim)汇总 remaining_quantity,回填展示字段 actual_capacity(不写库)。 + */ +@Slf4j +@Component +@Order(100) +@RequiredArgsConstructor +public class RawMaterialCardRemainQtyCapacityContribution implements WarehouseAreaActualCapacityContribution { + + private final XslMesWarehouseAreaCapacityProperties properties; + private final MesXslRawMaterialCardMapper mesXslRawMaterialCardMapper; + private final ISysCategoryService sysCategoryService; + + @Override + public void contribute(List areas) { + if (areas == null || areas.isEmpty()) { + return; + } + if (!properties.isEnabled()) { + return; + } + Set allowedCategories = resolveAllowedWarehouseCategoryIds(); + if (allowedCategories.isEmpty()) { + log.debug("[WarehouseAreaActualCapacity] 原材料库分类编码/ID 均未解析到有效 warehouse_category,跳过 RawMaterialCard 策略"); + return; + } + + List targets = + areas.stream().filter(a -> a != null && allowedCategories.contains(normId(a.getWarehouseCategory())) && StringUtils.isNotBlank(a.getAreaCode())) + .collect(Collectors.toList()); + if (targets.isEmpty()) { + return; + } + + Collection codes = + targets.stream().map(MesXslWarehouseArea::getAreaCode).map(String::trim).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList()); + + Map sumMap = loadSumMap(codes); + for (MesXslWarehouseArea a : targets) { + String ck = trimKey(a.getAreaCode()); + long sum = sumMap.getOrDefault(ck, 0L); + int display; + try { + display = Math.toIntExact(Math.min(sum, Integer.MAX_VALUE)); + } catch (ArithmeticException ex) { + display = Integer.MAX_VALUE; + } + a.setActualCapacity(display); + } + } + + private Map loadSumMap(Collection codes) { + if (codes.isEmpty()) { + return Collections.emptyMap(); + } + List rows = mesXslRawMaterialCardMapper.sumRemainingQtyByTrimmedWarehouseArea(codes); + if (rows == null || rows.isEmpty()) { + return Collections.emptyMap(); + } + Map map = new HashMap<>(Math.max(16, rows.size() * 2)); + for (MesXslAreaRemainQtySumDTO row : rows) { + if (row == null || row.getAreaCode() == null) { + continue; + } + String k = row.getAreaCode().trim(); + if (StringUtils.isBlank(k)) { + continue; + } + long v = row.getQtySum() == null ? 0L : row.getQtySum(); + map.put(k, v); + } + return map; + } + + private static String trimKey(String code) { + return code == null ? "" : code.trim(); + } + + private static String normId(String id) { + return StringUtils.trimToEmpty(id); + } + + private static Set normalizeIdSet(Collection raw) { + if (raw == null) { + return Collections.emptySet(); + } + return raw.stream().filter(StringUtils::isNotBlank).map(String::trim).collect(Collectors.toSet()); + } + + /** 配置的 id + 配置的 code 解析出的 id 合并 */ + private Set resolveAllowedWarehouseCategoryIds() { + Set set = new HashSet<>(normalizeIdSet(properties.getRawMaterialWarehouseCategoryIds())); + Collection codes = properties.getRawMaterialWarehouseCategoryCodes(); + if (codes != null) { + for (String c : codes) { + if (StringUtils.isBlank(c)) { + continue; + } + try { + String id = sysCategoryService.queryIdByCode(c.trim()); + if (StringUtils.isNotBlank(id)) { + set.add(id.trim()); + } + } catch (Exception ex) { + log.warn("[WarehouseAreaActualCapacity] 解析原材料库分类编码失败 code={}: {}", c, ex.getMessage()); + } + } + } + return set; + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/config/XslMesWarehouseAreaCapacityProperties.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/config/XslMesWarehouseAreaCapacityProperties.java new file mode 100644 index 0000000..d5c3715 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/config/XslMesWarehouseAreaCapacityProperties.java @@ -0,0 +1,43 @@ +package org.jeecg.modules.xslmes.config; + +import lombok.Data; +import org.jeecg.modules.xslmes.constant.MesXslWarehouseCategory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +/** + * 库区列表「实际存放量」展示口径配置(不写库) + *

+ * 推荐使用 {@link #rawMaterialWarehouseCategoryCodes},启动时解析为 sys_category.id, + * 避免在配置里维护易变的雪花 id;也可用 {@link #rawMaterialWarehouseCategoryIds} 直接指定 id。 + */ +@Data +@Component +@ConfigurationProperties(prefix = "xslmes.warehouse-area.display-actual-capacity") +public class XslMesWarehouseAreaCapacityProperties { + + /** + * 是否启用展示层回填「实际存放量」 + */ + private boolean enabled = true; + + /** + * 原材料库分类编码列表(resolve 成 id 后与 warehouse_category 匹配)。 + * 默认兼容 {@link MesXslWarehouseCategory#RAW_MATERIAL_CATEGORY_CODES}。 + */ + private List rawMaterialWarehouseCategoryCodes = defaultRawCodes(); + + /** + * 直接指定 warehouse_category=sys_category.id(与 codes 解析结果合并)。 + * 可为空。 + */ + private List rawMaterialWarehouseCategoryIds = new ArrayList<>(); + + private static List defaultRawCodes() { + return new ArrayList<>(MesXslWarehouseCategory.RAW_MATERIAL_CATEGORY_CODES); + } +} + \ No newline at end of file diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslPrintConstants.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslPrintConstants.java new file mode 100644 index 0000000..4dc5c3a --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslPrintConstants.java @@ -0,0 +1,15 @@ +package org.jeecg.modules.xslmes.constant; + +/** + * 打印业务绑定 biz_code 使用菜单 permission id;与 print_biz_perm_entity、Flyway 中原材料卡片菜单一致。 + */ +public final class MesXslPrintConstants { + + /** 原材料卡片页面菜单(sys_permission.id) */ + public static final String RAW_MATERIAL_CARD_PERM_ID = "1900000000000000540"; + + /** 原料入场记录页面菜单(sys_permission.id,与 Flyway 中 parent 菜单一致) */ + public static final String RAW_MATERIAL_ENTRY_PERM_ID = "1900000000000000530"; + + private MesXslPrintConstants() {} +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslWarehouseCategory.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslWarehouseCategory.java index 63bd508..db79d45 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslWarehouseCategory.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/constant/MesXslWarehouseCategory.java @@ -1,7 +1,19 @@ package org.jeecg.modules.xslmes.constant; +import org.apache.commons.lang3.StringUtils; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** * MES 仓库分类(分类字典 sys_category,根编码 {@link #ROOT_CODE}) + * + *

说明:历史版本曾在编码上使用 F1/F2 后缀;当前业务树已不再按楼层区分, + * 「F1」「F2」仅可能作为编码后缀保留,请以 {@link #RAW_MATERIAL_CATEGORY_CODES}、 + * 客户/供应商库编码集合为准做兼容。

*/ public final class MesXslWarehouseCategory { @@ -10,8 +22,37 @@ public final class MesXslWarehouseCategory { /** 根节点编码,与 JCategorySelect 的 pcode 一致 */ public static final String ROOT_CODE = "XSLMES_WH"; - /** 客户库(二楼):须关联客户 */ - public static final String CUSTOMER_CATEGORY_CODE = "XSLMES_WH_F2_KH"; - /** 供应商库(二楼):须关联供应商 */ - public static final String SUPPLIER_CATEGORY_CODE = "XSLMES_WH_F2_GYS"; + /** 兼容历史:原材料库在库中可能出现的分类编码(新环境多为 F1,老数据可能仍为 F2) */ + public static final List RAW_MATERIAL_CATEGORY_CODES = + Collections.unmodifiableList(Arrays.asList("XSLMES_WH_F1_YCL", "XSLMES_WH_F2_YCL")); + + /** 兼容历史编号的「客户库」分类编码集合 */ + private static final Set CUSTOMER_CATEGORY_CODES = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList("XSLMES_WH_F1_KH", "XSLMES_WH_F2_KH"))); + + /** 兼容历史编号的「供应商库」分类编码集合 */ + private static final Set SUPPLIER_CATEGORY_CODES = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList("XSLMES_WH_F1_GYS", "XSLMES_WH_F2_GYS"))); + + /** + * @deprecated 请改用 {@link #isCustomerWarehouseCategoryCode(String)} + */ + @Deprecated + public static final String CUSTOMER_CATEGORY_CODE = "XSLMES_WH_F1_KH"; + + /** + * @deprecated 请改用 {@link #isSupplierWarehouseCategoryCode(String)} + */ + @Deprecated + public static final String SUPPLIER_CATEGORY_CODE = "XSLMES_WH_F1_GYS"; + + /** 是否为「客户库」分类编码(兼容 XSLMES_WH_F1_KH / XSLMES_WH_F2_KH) */ + public static boolean isCustomerWarehouseCategoryCode(String code) { + return CUSTOMER_CATEGORY_CODES.contains(StringUtils.trimToEmpty(code)); + } + + /** 是否为「供应商库」分类编码(兼容 XSLMES_WH_F1_GYS / XSLMES_WH_F2_GYS) */ + public static boolean isSupplierWarehouseCategoryCode(String code) { + return SUPPLIER_CATEGORY_CODES.contains(StringUtils.trimToEmpty(code)); + } } diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslBizEntityFieldProfileController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslBizEntityFieldProfileController.java new file mode 100644 index 0000000..4fbed79 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslBizEntityFieldProfileController.java @@ -0,0 +1,128 @@ +package org.jeecg.modules.xslmes.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.jeecg.common.api.vo.Result; +import org.jeecg.common.aspect.annotation.AutoLog; +import org.jeecg.common.system.base.controller.JeecgController; +import org.jeecg.common.system.query.QueryGenerator; +import org.jeecg.common.util.oConvertUtils; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile; +import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +/** + * 业务实体字段配置:主表存业务名称与主实体字段 JSON;子表存各明细表的字段 JSON。 + */ +@Tag(name = "业务实体字段配置") +@RestController +@RequestMapping("/xslmes/mesXslBizEntityFieldProfile") +@Slf4j +public class MesXslBizEntityFieldProfileController extends JeecgController { + + @Autowired + private IMesXslBizEntityFieldProfileService bizEntityFieldProfileService; + + @Operation(summary = "分页列表(不含明细,减轻负载)") + @GetMapping(value = "/list") + public Result> queryPageList( + MesXslBizEntityFieldProfile query, + @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, + @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, + HttpServletRequest req) { + QueryWrapper qw = QueryGenerator.initQueryWrapper(query, req.getParameterMap()); + Page page = new Page<>(pageNo, pageSize); + IPage pageList = bizEntityFieldProfileService.page(page, qw); + return Result.OK(pageList); + } + + @AutoLog(value = "业务实体字段配置-添加") + @Operation(summary = "添加(请求体可含 detailList)") + @RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:add") + @PostMapping(value = "/add") + public Result add(@RequestBody MesXslBizEntityFieldProfile entity) { + if (oConvertUtils.isEmpty(entity.getBusinessName())) { + return Result.error("业务名称不能为空"); + } + if (oConvertUtils.isEmpty(entity.getBusinessCode())) { + return Result.error("业务编码不能为空(建议填写菜单 permission id)"); + } + bizEntityFieldProfileService.saveWithDetails(entity); + return Result.OK("添加成功"); + } + + @AutoLog(value = "业务实体字段配置-编辑") + @Operation(summary = "编辑(明细全量替换)") + @RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:edit") + @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST}) + public Result edit(@RequestBody MesXslBizEntityFieldProfile entity) { + if (oConvertUtils.isEmpty(entity.getId())) { + return Result.error("主键不能为空"); + } + if (oConvertUtils.isEmpty(entity.getBusinessName())) { + return Result.error("业务名称不能为空"); + } + if (oConvertUtils.isEmpty(entity.getBusinessCode())) { + return Result.error("业务编码不能为空(建议填写菜单 permission id)"); + } + bizEntityFieldProfileService.updateWithDetails(entity); + return Result.OK("编辑成功"); + } + + @AutoLog(value = "业务实体字段配置-删除") + @Operation(summary = "删除") + @RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:delete") + @DeleteMapping(value = "/delete") + public Result delete(@RequestParam(name = "id", required = true) String id) { + bizEntityFieldProfileService.removeWithDetails(id); + return Result.OK("删除成功"); + } + + @AutoLog(value = "业务实体字段配置-批量删除") + @Operation(summary = "批量删除") + @RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:deleteBatch") + @DeleteMapping(value = "/deleteBatch") + public Result deleteBatch(@RequestParam(name = "ids", required = true) String ids) { + bizEntityFieldProfileService.removeBatchWithDetails(Arrays.asList(ids.split(","))); + return Result.OK("批量删除成功"); + } + + @Operation(summary = "按 id 查询(含 detailList)") + @GetMapping(value = "/queryById") + public Result queryById(@RequestParam(name = "id", required = true) String id) { + MesXslBizEntityFieldProfile entity = bizEntityFieldProfileService.getByIdWithDetails(id); + if (entity == null) { + return Result.error("未找到对应数据"); + } + return Result.OK(entity); + } + + @RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:exportXls") + @RequestMapping(value = "/exportXls") + public ModelAndView exportXls(HttpServletRequest request, MesXslBizEntityFieldProfile query) { + return super.exportXls(request, query, MesXslBizEntityFieldProfile.class, "业务实体字段配置"); + } + + @RequiresPermissions("xslmes:mes_xsl_biz_entity_field_profile:importExcel") + @RequestMapping(value = "/importExcel", method = RequestMethod.POST) + public Result importExcel(HttpServletRequest request, HttpServletResponse response) { + return super.importExcel(request, response, MesXslBizEntityFieldProfile.class); + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslDesktopAnonController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslDesktopAnonController.java index c4f5c7e..76f5f84 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslDesktopAnonController.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslDesktopAnonController.java @@ -9,10 +9,20 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.jeecg.common.api.vo.Result; import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.util.oConvertUtils; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; +import org.jeecg.modules.print.entity.PrintTemplate; +import org.jeecg.modules.print.service.IPrintBizTemplateBindService; +import org.jeecg.modules.print.service.IPrintTemplateService; +import org.jeecg.modules.print.util.PrintBizDataMappingUtil; import org.jeecg.modules.xslmes.constant.MesXslCustomerBizStatus; +import org.jeecg.modules.xslmes.constant.MesXslPrintConstants; import org.jeecg.modules.xslmes.entity.MesXslCustomer; import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard; import org.jeecg.modules.xslmes.entity.MesXslRawMaterialEntry; @@ -33,6 +43,9 @@ import org.jeecg.modules.xslmes.service.MesXslStompNotifyService; import org.springframework.web.bind.annotation.*; import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import java.util.Objects; import org.apache.commons.lang3.StringUtils; @@ -59,6 +72,9 @@ public class MesXslDesktopAnonController { private final IMesXslWarehouseService warehouseService; private final IMesXslWarehouseAreaService warehouseAreaService; private final MesXslStompNotifyService stompNotify; + private final IPrintBizTemplateBindService printBizTemplateBindService; + private final IPrintTemplateService printTemplateService; + private final ObjectMapper objectMapper; // ═══════════════════════════ 车辆管理 ═══════════════════════════ @@ -606,6 +622,61 @@ public class MesXslDesktopAnonController { return Result.OK((int) count); } + + @Operation(summary = "原材料卡片-免密准备原生打印数据(桌面端用)") + @GetMapping("/xslmes/mesXslRawMaterialCard/anon/prepareNativePrint") + public Result> rawMaterialCardAnonPrepareNativePrint(@RequestParam(name = "id") String id) { + try { + MesXslRawMaterialCard card = rawMaterialCardService.getById(id); + if (card == null) return Result.error("未找到原材料卡片"); + PrintBizTemplateBind bind = + printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_CARD_PERM_ID); + if (bind == null) return Result.error("请先在「业务打印绑定」中配置原材料卡片与打印模板"); + PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId()); + if (tpl == null) return Result.error("绑定的打印模板不存在"); + ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson()); + JsonNode bizRoot = objectMapper.valueToTree(card); + ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping); + PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson()); + Map out = new HashMap<>(8); + out.put("cardId", card.getId()); + out.put("templateCode", bind.getTemplateCode()); + out.put("templateJson", tpl.getTemplateJson()); + out.put("printData", objectMapper.convertValue(printData, Map.class)); + return Result.OK(out); + } catch (Exception e) { + log.error("原材料卡片-免密准备打印数据失败 id={}", id, e); + return Result.error("准备打印数据失败: " + e.getMessage()); + } + } + + @Operation(summary = "原料入场记录-免密准备原生打印数据(桌面端用)") + @GetMapping("/xslmes/mesXslRawMaterialEntry/anon/prepareNativePrint") + public Result> rawMaterialEntryAnonPrepareNativePrint(@RequestParam(name = "id") String id) { + try { + MesXslRawMaterialEntry entry = rawMaterialEntryService.getById(id); + if (entry == null) return Result.error("未找到原料入场记录"); + PrintBizTemplateBind bind = + printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_ENTRY_PERM_ID); + if (bind == null) return Result.error("请先在「业务打印绑定」中配置原料入场记录与打印模板"); + PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId()); + if (tpl == null) return Result.error("绑定的打印模板不存在"); + ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson()); + JsonNode bizRoot = objectMapper.valueToTree(entry); + ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping); + PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson()); + Map out = new HashMap<>(8); + out.put("entryId", entry.getId()); + out.put("templateCode", bind.getTemplateCode()); + out.put("templateJson", tpl.getTemplateJson()); + out.put("printData", objectMapper.convertValue(printData, Map.class)); + return Result.OK(out); + } catch (Exception e) { + log.error("原料入场记录-免密准备打印数据失败 id={}", id, e); + return Result.error("准备打印数据失败: " + e.getMessage()); + } + } + // ═══════════════════════════ 仓库管理(只读,供桌面端下拉选取) ═══════════════════════════ @Operation(summary = "仓库-免密分页列表查询(供桌面端筛选使用)") @@ -632,6 +703,7 @@ public class MesXslDesktopAnonController { HttpServletRequest req) { QueryWrapper qw = QueryGenerator.initQueryWrapper(mesXslWarehouseArea, req.getParameterMap()); IPage page = warehouseAreaService.page(new Page<>(pageNo, pageSize), qw); + warehouseAreaService.enrichDisplayedActualCapacity(page.getRecords()); return Result.OK(page); } @@ -639,7 +711,11 @@ public class MesXslDesktopAnonController { @GetMapping("/xslmes/mesXslWarehouseArea/anon/queryById") public Result warehouseAreaAnonQueryById(@RequestParam(name = "id") String id) { MesXslWarehouseArea entity = warehouseAreaService.getById(id); - return entity != null ? Result.OK(entity) : Result.error("未找到对应数据"); + if (entity == null) { + return Result.error("未找到对应数据"); + } + warehouseAreaService.enrichDisplayedActualCapacity(Collections.singletonList(entity)); + return Result.OK(entity); } @Operation(summary = "库区-免密添加") diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialCardController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialCardController.java index 144d131..902e33a 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialCardController.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialCardController.java @@ -1,27 +1,50 @@ package org.jeecg.modules.xslmes.controller; -import java.util.Arrays; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import org.jeecg.common.api.vo.Result; -import org.jeecg.common.system.query.QueryGenerator; -import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard; -import org.jeecg.modules.xslmes.service.IMesXslRawMaterialCardService; -import org.jeecg.modules.xslmes.service.MesXslStompNotifyService; - import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import lombok.extern.slf4j.Slf4j; - -import org.jeecg.common.system.base.controller.JeecgController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; -import io.swagger.v3.oas.annotations.tags.Tag; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.v3.oas.annotations.Operation; -import org.jeecg.common.aspect.annotation.AutoLog; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.common.util.oConvertUtils; +import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.jeecg.common.api.vo.Result; +import org.jeecg.common.aspect.annotation.AutoLog; +import org.jeecg.common.system.base.controller.JeecgController; +import org.jeecg.common.system.query.QueryGenerator; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; +import org.jeecg.modules.print.entity.PrintTemplate; +import org.jeecg.modules.print.service.IPrintBizTemplateBindService; +import org.jeecg.modules.print.service.IPrintTemplateService; +import org.jeecg.modules.print.support.PrintServerEnvironmentService; +import org.jeecg.modules.print.support.PrintServerPdfJobService; +import org.jeecg.modules.print.util.PrintBizDataMappingUtil; +import org.jeecg.modules.xslmes.constant.MesXslPrintConstants; +import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard; +import org.jeecg.modules.xslmes.service.IMesXslRawMaterialCardService; +import org.jeecg.modules.xslmes.service.MesXslStompNotifyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; /** * @Description: 原材料卡片 @@ -34,10 +57,21 @@ import org.apache.shiro.authz.annotation.RequiresPermissions; @RequestMapping("/xslmes/mesXslRawMaterialCard") @Slf4j public class MesXslRawMaterialCardController extends JeecgController { + @Autowired private IMesXslRawMaterialCardService mesXslRawMaterialCardService; @Autowired private MesXslStompNotifyService stompNotify; + @Autowired + private PrintServerEnvironmentService printServerEnvironmentService; + @Autowired + private PrintServerPdfJobService printServerPdfJobService; + @Autowired + private IPrintBizTemplateBindService printBizTemplateBindService; + @Autowired + private IPrintTemplateService printTemplateService; + @Autowired + private ObjectMapper objectMapper; /** * 分页列表查询 @@ -48,7 +82,36 @@ public class MesXslRawMaterialCardController extends JeecgController queryWrapper = QueryGenerator.initQueryWrapper(mesXslRawMaterialCard, req.getParameterMap()); + if (filterByWarehouseArea) { + queryWrapper.apply("TRIM(COALESCE(warehouse_area,'')) = {0}", areaEq); + } + // 看板等扩展查询:remaining_quantity「有剩余 / 无剩余」(非实体字段,单独拼条件) + String remainQtyFilter = req.getParameter("remainQtyFilter"); + if ("has".equals(remainQtyFilter)) { + queryWrapper.gt("remaining_quantity", 0); + } else if ("none".equals(remainQtyFilter)) { + queryWrapper.and(w -> w.isNull("remaining_quantity").or().le("remaining_quantity", 0)); + } + String mixKw = req.getParameter("mixKeyword"); + if (StringUtils.isNotBlank(mixKw)) { + final String kw = mixKw.trim(); + queryWrapper.and( + w -> w.like("barcode", kw) + .or() + .like("batch_no", kw) + .or() + .like("material_name", kw) + .or() + .like("material_id", kw)); + } Page page = new Page<>(pageNo, pageSize); IPage pageList = mesXslRawMaterialCardService.page(page, queryWrapper); return Result.OK(pageList); @@ -122,6 +185,88 @@ public class MesXslRawMaterialCardController extends JeecgController> queryPrinters() { + return Result.OK(printServerEnvironmentService.buildPrinterQueryResult()); + } + + /** + * 根据业务打印绑定生成模板 JSON + 映射后的 printData,供前端生成 PDF 后调用 printPdf + */ + @Operation(summary = "原材料卡片-准备原生打印数据") + @GetMapping(value = "/prepareNativePrint") + /** 与 printPdf 一致:准备模板与打印数据属于「打印」动作,使用 edit 权限 */ + @RequiresPermissions("xslmes:mes_xsl_raw_material_card:edit") + public Result> prepareNativePrint(@RequestParam(name = "id") String id) { + try { + MesXslRawMaterialCard card = mesXslRawMaterialCardService.getById(id); + if (card == null) { + return Result.error("未找到原材料卡片"); + } + PrintBizTemplateBind bind = + printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_CARD_PERM_ID); + if (bind == null) { + return Result.error("请先在「业务打印绑定」中配置原材料卡片与打印模板"); + } + PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId()); + if (tpl == null) { + return Result.error("绑定的打印模板不存在"); + } + ArrayNode mapping = + PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson()); + JsonNode bizRoot = objectMapper.valueToTree(card); + ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping); + PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson()); + Map out = new HashMap<>(8); + out.put("cardId", card.getId()); + out.put("templateCode", bind.getTemplateCode()); + out.put("templateJson", tpl.getTemplateJson()); + out.put("paperWidthMm", tpl.getPaperWidthMm()); + out.put("paperHeightMm", tpl.getPaperHeightMm()); + out.put("paperOrientation", tpl.getPaperOrientation()); + out.put("printData", objectMapper.convertValue(printData, Map.class)); + return Result.OK(out); + } catch (Exception e) { + log.error("原材料卡片准备打印数据失败 id={}", id, e); + return Result.error("准备打印数据失败: " + e.getMessage()); + } + } + + /** + * 将前端生成的 PDF Base64 提交到服务器打印机(与 /print/template/directPrintPdf 一致) + */ + @AutoLog(value = "原材料卡片-PDF后端打印") + @Operation(summary = "原材料卡片-PDF后端打印") + @PostMapping(value = "/printPdf") + @RequiresPermissions("xslmes:mes_xsl_raw_material_card:edit") + public Result printPdf(@RequestBody Map body) { + String id = String.valueOf(body.getOrDefault("id", "")).trim(); + String printerName = String.valueOf(body.getOrDefault("printerName", "")).trim(); + String pdfBase64 = String.valueOf(body.getOrDefault("pdfBase64", "")).trim(); + String fileName = String.valueOf(body.getOrDefault("fileName", "")).trim(); + if (StringUtils.isBlank(id)) { + return Result.error("id 不能为空"); + } + MesXslRawMaterialCard card = mesXslRawMaterialCardService.getById(id); + if (card == null) { + return Result.error("未找到原材料卡片"); + } + String prefix = + StringUtils.isNotBlank(card.getBarcode()) ? card.getBarcode() : card.getId(); + String fn = + StringUtils.isNotBlank(fileName) ? fileName : ("原材料卡片-" + prefix + ".pdf"); + return printServerPdfJobService.submitPdfBase64( + printerName, pdfBase64, fn, "RAW_CARD_" + prefix); + } + /** * 通过id查询 */ diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialEntryController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialEntryController.java index ab1fc0d..df44d4e 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialEntryController.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialEntryController.java @@ -1,28 +1,50 @@ package org.jeecg.modules.xslmes.controller; -import java.util.Arrays; -import java.util.List; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import org.jeecg.common.api.vo.Result; -import org.jeecg.common.system.query.QueryGenerator; -import org.jeecg.modules.xslmes.entity.MesXslRawMaterialEntry; -import org.jeecg.modules.xslmes.service.IMesXslRawMaterialEntryService; -import org.jeecg.modules.xslmes.service.MesXslStompNotifyService; - import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import lombok.extern.slf4j.Slf4j; - -import org.jeecg.common.system.base.controller.JeecgController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; -import io.swagger.v3.oas.annotations.tags.Tag; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.v3.oas.annotations.Operation; -import org.jeecg.common.aspect.annotation.AutoLog; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.jeecg.common.api.vo.Result; +import org.jeecg.common.aspect.annotation.AutoLog; +import org.jeecg.common.system.base.controller.JeecgController; +import org.jeecg.common.system.query.QueryGenerator; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; +import org.jeecg.modules.print.entity.PrintTemplate; +import org.jeecg.modules.print.service.IPrintBizTemplateBindService; +import org.jeecg.modules.print.service.IPrintTemplateService; +import org.jeecg.modules.print.support.PrintServerEnvironmentService; +import org.jeecg.modules.print.support.PrintServerPdfJobService; +import org.jeecg.modules.print.util.PrintBizDataMappingUtil; +import org.jeecg.modules.xslmes.constant.MesXslPrintConstants; +import org.jeecg.modules.xslmes.entity.MesXslRawMaterialEntry; +import org.jeecg.modules.xslmes.service.IMesXslRawMaterialEntryService; +import org.jeecg.modules.xslmes.service.MesXslStompNotifyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; /** * @Description: 原料入场记录 @@ -40,6 +62,16 @@ public class MesXslRawMaterialEntryController extends JeecgController> queryPrinters() { + return Result.OK(printServerEnvironmentService.buildPrinterQueryResult()); + } + + /** + * 根据业务打印绑定生成模板 JSON + 映射后的 printData,供前端生成 PDF 后调用 printPdf + */ + @Operation(summary = "原料入场记录-准备原生打印数据") + @GetMapping(value = "/prepareNativePrint") + @RequiresPermissions("xslmes:mes_xsl_raw_material_entry:edit") + public Result> prepareNativePrint(@RequestParam(name = "id") String id) { + try { + MesXslRawMaterialEntry entry = mesXslRawMaterialEntryService.getById(id); + if (entry == null) { + return Result.error("未找到原料入场记录"); + } + PrintBizTemplateBind bind = + printBizTemplateBindService.getByBizCode(MesXslPrintConstants.RAW_MATERIAL_ENTRY_PERM_ID); + if (bind == null) { + return Result.error("请先在「业务打印绑定」中配置原料入场记录与打印模板"); + } + PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId()); + if (tpl == null) { + return Result.error("绑定的打印模板不存在"); + } + ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson()); + JsonNode bizRoot = objectMapper.valueToTree(entry); + ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping); + PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson()); + Map out = new HashMap<>(8); + out.put("entryId", entry.getId()); + out.put("templateCode", bind.getTemplateCode()); + out.put("templateJson", tpl.getTemplateJson()); + out.put("paperWidthMm", tpl.getPaperWidthMm()); + out.put("paperHeightMm", tpl.getPaperHeightMm()); + out.put("paperOrientation", tpl.getPaperOrientation()); + out.put("printData", objectMapper.convertValue(printData, Map.class)); + return Result.OK(out); + } catch (Exception e) { + log.error("原料入场记录准备打印数据失败 id={}", id, e); + return Result.error("准备打印数据失败: " + e.getMessage()); + } + } + + @AutoLog(value = "原料入场记录-PDF后端打印") + @Operation(summary = "原料入场记录-PDF后端打印") + @PostMapping(value = "/printPdf") + @RequiresPermissions("xslmes:mes_xsl_raw_material_entry:edit") + public Result printPdf(@RequestBody Map body) { + String id = String.valueOf(body.getOrDefault("id", "")).trim(); + String printerName = String.valueOf(body.getOrDefault("printerName", "")).trim(); + String pdfBase64 = String.valueOf(body.getOrDefault("pdfBase64", "")).trim(); + String fileName = String.valueOf(body.getOrDefault("fileName", "")).trim(); + if (StringUtils.isBlank(id)) { + return Result.error("id 不能为空"); + } + MesXslRawMaterialEntry entry = mesXslRawMaterialEntryService.getById(id); + if (entry == null) { + return Result.error("未找到原料入场记录"); + } + String prefix = + StringUtils.isNotBlank(entry.getBarcode()) ? entry.getBarcode() : entry.getId(); + String fn = + StringUtils.isNotBlank(fileName) ? fileName : ("原料入场记录-" + prefix + ".pdf"); + return printServerPdfJobService.submitPdfBase64( + printerName, pdfBase64, fn, "RAW_ENTRY_" + prefix); + } + @RequiresPermissions("xslmes:mes_xsl_raw_material_entry:exportXls") @RequestMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, MesXslRawMaterialEntry mesXslRawMaterialEntry) { diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialWarehouseBoardController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialWarehouseBoardController.java new file mode 100644 index 0000000..3b9c975 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslRawMaterialWarehouseBoardController.java @@ -0,0 +1,38 @@ +package org.jeecg.modules.xslmes.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.jeecg.common.api.vo.Result; +import org.jeecg.modules.xslmes.service.IMesXslRawMaterialWarehouseBoardService; +import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * 原材料库区看板:库区主数据 + 原材料卡片聚合 + */ +@Tag(name = "原材料库区看板") +@RestController +@RequestMapping("/xslmes/mesXslRawMaterialWarehouseBoard") +@Slf4j +public class MesXslRawMaterialWarehouseBoardController { + + @Autowired + private IMesXslRawMaterialWarehouseBoardService mesXslRawMaterialWarehouseBoardService; + + @Operation(summary = "原材料库区看板-汇总数据") + @RequiresPermissions("xslmes:mes_xsl_raw_material_warehouse_board:list") + @GetMapping(value = "/board") + public Result board( + @RequestParam(name = "warehouseId", required = false) String warehouseId, + @RequestParam(name = "keyword", required = false) String keyword, + @RequestParam(name = "measureType", required = false) String measureType) { + MesXslRawMaterialWarehouseBoardVO data = mesXslRawMaterialWarehouseBoardService.queryBoard(warehouseId, keyword, measureType); + return Result.OK(data); + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslWarehouseAreaController.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslWarehouseAreaController.java index 8f75448..933337f 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslWarehouseAreaController.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/controller/MesXslWarehouseAreaController.java @@ -3,6 +3,7 @@ package org.jeecg.modules.xslmes.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.shiro.SecurityUtils; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; @@ -13,15 +14,22 @@ import org.jeecg.common.api.vo.Result; import org.jeecg.common.aspect.annotation.AutoLog; import org.jeecg.common.system.base.controller.JeecgController; import org.jeecg.common.system.query.QueryGenerator; +import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.util.oConvertUtils; +import org.jeecg.config.JeecgBaseConfig; import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; import org.jeecg.modules.xslmes.service.IMesXslWarehouseAreaService; import org.jeecg.modules.xslmes.service.MesXslStompNotifyService; +import org.jeecgframework.poi.excel.def.NormalExcelConstants; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.entity.enmus.ExcelType; +import org.jeecgframework.poi.excel.view.JeecgEntityExcelView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.Arrays; +import java.util.Collections; import java.util.List; /** @@ -36,6 +44,9 @@ public class MesXslWarehouseAreaController extends JeecgController queryWrapper = QueryGenerator.initQueryWrapper(mesXslWarehouseArea, req.getParameterMap()); Page page = new Page<>(pageNo, pageSize); IPage pageList = mesXslWarehouseAreaService.page(page, queryWrapper); + mesXslWarehouseAreaService.enrichDisplayedActualCapacity(pageList.getRecords()); return Result.OK(pageList); } @@ -166,13 +178,33 @@ public class MesXslWarehouseAreaController extends JeecgController queryWrapper = QueryGenerator.initQueryWrapper(mesXslWarehouseArea, request.getParameterMap()); + LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); + String selections = request.getParameter("selections"); + if (oConvertUtils.isNotEmpty(selections)) { + queryWrapper.in("id", Arrays.asList(selections.split(","))); + } + List exportList = mesXslWarehouseAreaService.list(queryWrapper); + mesXslWarehouseAreaService.enrichDisplayedActualCapacity(exportList); + ModelAndView mv = new ModelAndView(new JeecgEntityExcelView()); + mv.addObject(NormalExcelConstants.FILE_NAME, "MES库区管理"); + mv.addObject(NormalExcelConstants.CLASS, MesXslWarehouseArea.class); + ExportParams exportParams = new ExportParams("MES库区管理报表", "导出人:" + sysUser.getRealname(), "MES库区管理", ExcelType.XSSF); + exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload()); + mv.addObject(NormalExcelConstants.PARAMS, exportParams); + mv.addObject(NormalExcelConstants.DATA_LIST, exportList); + String exportFields = request.getParameter(NormalExcelConstants.EXPORT_FIELDS); + if (oConvertUtils.isNotEmpty(exportFields)) { + mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields); + } + return mv; } @RequiresPermissions("xslmes:mes_xsl_warehouse_area:importExcel") diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/dto/MesXslAreaRemainQtySumDTO.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/dto/MesXslAreaRemainQtySumDTO.java new file mode 100644 index 0000000..98bb31c --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/dto/MesXslAreaRemainQtySumDTO.java @@ -0,0 +1,20 @@ +package org.jeecg.modules.xslmes.dto; + +import lombok.Data; + +import java.io.Serializable; + +/** + * 按库区(trim 后编码)聚合剩余数量汇总 + */ +@Data +public class MesXslAreaRemainQtySumDTO implements Serializable { + + private static final long serialVersionUID = 1L; + + /** 库区编码(已 trim) */ + private String areaCode; + + /** 剩余数量合计 */ + private Long qtySum; +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/entity/MesXslBizEntityFieldDetail.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/entity/MesXslBizEntityFieldDetail.java new file mode 100644 index 0000000..2c70743 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/entity/MesXslBizEntityFieldDetail.java @@ -0,0 +1,68 @@ +package org.jeecg.modules.xslmes.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import java.util.Date; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.springframework.format.annotation.DateTimeFormat; + +/** + * 业务实体字段配置子表:一类明细表对应一行,字段清单存 JSON。 + */ +@Data +@TableName("mes_xsl_biz_entity_field_detail") +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Schema(description = "业务实体字段配置-明细表字段清单") +public class MesXslBizEntityFieldDetail implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private String id; + + @Schema(description = "主表ID") + private String profileId; + + @Schema(description = "主实体上明细属性名(与打印绑定 detailProperty 一致,如 lines)") + private String detailPropertyName; + + @Schema(description = "槽位类型:LIST 或 OBJECT") + private String detailSlotKind; + + @Schema(description = "明细展示名称") + private String detailName; + + @Schema(description = "明细实体 Java 全限定类名") + private String detailEntityClassName; + + /** 明细表字段列表 JSON */ + @Schema(description = "明细表字段列表(JSON 数组)") + private String detailFieldsJson; + + @Schema(description = "排序号") + private Integer sortNo; + + @Schema(description = "创建人") + private String createBy; + + @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @Schema(description = "创建时间") + private Date createTime; + + @Schema(description = "更新人") + private String updateBy; + + @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @Schema(description = "更新时间") + private Date updateTime; +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/entity/MesXslBizEntityFieldProfile.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/entity/MesXslBizEntityFieldProfile.java new file mode 100644 index 0000000..c3bf52c --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/entity/MesXslBizEntityFieldProfile.java @@ -0,0 +1,72 @@ +package org.jeecg.modules.xslmes.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import java.util.Date; +import java.util.List; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.springframework.format.annotation.DateTimeFormat; + +/** + * 业务实体字段配置主表:业务名称、主实体类名、主表字段 JSON;明细通过 detailList 关联子表。 + */ +@Data +@TableName("mes_xsl_biz_entity_field_profile") +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +@Schema(description = "业务实体字段配置主表") +public class MesXslBizEntityFieldProfile implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private String id; + + @Schema(description = "业务名称") + private String businessName; + + @Schema(description = "业务编码(菜单 permission id,与业务打印绑定 biz_code、print_biz_perm_entity.perm_id 一致)") + private String businessCode; + + @Schema(description = "主实体 Java 全限定类名") + private String entityClassName; + + /** 主表实体字段列表 JSON */ + @Schema(description = "主表实体字段列表(JSON 数组)") + private String mainFieldsJson; + + @Schema(description = "备注") + private String remark; + + @Schema(description = "租户ID") + private Integer tenantId; + + @Schema(description = "创建人") + private String createBy; + + @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @Schema(description = "创建时间") + private Date createTime; + + @Schema(description = "更新人") + private String updateBy; + + @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @Schema(description = "更新时间") + private Date updateTime; + + /** 各明细表对应的字段清单(不落主表) */ + @TableField(exist = false) + @Schema(description = "明细表字段配置列表") + private List detailList; +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslBizEntityFieldDetailMapper.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslBizEntityFieldDetailMapper.java new file mode 100644 index 0000000..e05176e --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslBizEntityFieldDetailMapper.java @@ -0,0 +1,8 @@ +package org.jeecg.modules.xslmes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail; + +@Mapper +public interface MesXslBizEntityFieldDetailMapper extends BaseMapper {} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslBizEntityFieldProfileMapper.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslBizEntityFieldProfileMapper.java new file mode 100644 index 0000000..d1a7309 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslBizEntityFieldProfileMapper.java @@ -0,0 +1,8 @@ +package org.jeecg.modules.xslmes.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile; + +@Mapper +public interface MesXslBizEntityFieldProfileMapper extends BaseMapper {} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslRawMaterialCardMapper.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslRawMaterialCardMapper.java index 7110eeb..74142e5 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslRawMaterialCardMapper.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/MesXslRawMaterialCardMapper.java @@ -1,7 +1,12 @@ package org.jeecg.modules.xslmes.mapper; -import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.jeecg.modules.xslmes.dto.MesXslAreaRemainQtySumDTO; +import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard; + +import java.util.Collection; +import java.util.List; /** * @Description: 原材料卡片 @@ -10,4 +15,9 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; * @Version: V1.0 */ public interface MesXslRawMaterialCardMapper extends BaseMapper { + + /** + * 按 trim 后的库区编码汇总原材料卡片剩余数量(当前租户由拦截器补齐) + */ + List sumRemainingQtyByTrimmedWarehouseArea(@Param("areaCodes") Collection areaCodes); } diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/xml/MesXslRawMaterialCardMapper.xml b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/xml/MesXslRawMaterialCardMapper.xml index f240dd2..d99a26b 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/xml/MesXslRawMaterialCardMapper.xml +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/mapper/xml/MesXslRawMaterialCardMapper.xml @@ -1,4 +1,18 @@ + + diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/print/catalog/PrintBizEntityFieldCatalogProviderImpl.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/print/catalog/PrintBizEntityFieldCatalogProviderImpl.java new file mode 100644 index 0000000..994e395 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/print/catalog/PrintBizEntityFieldCatalogProviderImpl.java @@ -0,0 +1,226 @@ +package org.jeecg.modules.xslmes.print.catalog; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.annotation.Resource; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.catalog.IPrintBizEntityFieldCatalogProvider; +import org.jeecg.modules.print.vo.PrintBizDetailSlotVO; +import org.jeecg.modules.print.vo.PrintBizFieldItemVO; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile; +import org.jeecg.modules.xslmes.mapper.MesXslBizEntityFieldDetailMapper; +import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService; +import org.springframework.stereotype.Component; + +/** + * 将 mes_xsl_biz_entity_field_* 中的缓存提供给打印绑定接口(SPI 实现)。 + * + *

bizCode = {@code print_biz_perm_entity.perm_id}。 + * + *

「新增绑定」下拉组装时对每条业务若单独查库会产生严重 N+1;{@link #beginBulkLookup(Collection)} 在同一请求线程内改为单次 IN 查询。 + */ +@Slf4j +@Component +public class PrintBizEntityFieldCatalogProviderImpl implements IPrintBizEntityFieldCatalogProvider { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** null=非批量模式;非 null=批量模式(可能为空 Map) */ + private static final ThreadLocal> BULK_PROFILE_BY_CODE = + new ThreadLocal<>(); + + @Resource + private IMesXslBizEntityFieldProfileService bizEntityFieldProfileService; + + @Resource + private MesXslBizEntityFieldDetailMapper detailMapper; + + @Override + public void beginBulkLookup(Collection bizCodes) { + endBulkLookup(); + if (bizCodes == null || bizCodes.isEmpty()) { + BULK_PROFILE_BY_CODE.set(Collections.emptyMap()); + return; + } + List ids = + bizCodes.stream() + .filter(StringUtils::isNotBlank) + .map(String::trim) + .distinct() + .collect(Collectors.toList()); + if (ids.isEmpty()) { + BULK_PROFILE_BY_CODE.set(Collections.emptyMap()); + return; + } + List list = + bizEntityFieldProfileService + .lambdaQuery() + .in(MesXslBizEntityFieldProfile::getBusinessCode, ids) + .list(); + Map map = new HashMap<>(Math.max(16, list.size() * 2)); + for (MesXslBizEntityFieldProfile p : list) { + if (p != null && StringUtils.isNotBlank(p.getBusinessCode())) { + map.put(p.getBusinessCode().trim(), p); + } + } + BULK_PROFILE_BY_CODE.set(map); + } + + @Override + public void endBulkLookup() { + BULK_PROFILE_BY_CODE.remove(); + } + + /** 批量模式下读线程 Map;否则单次按编码查询 */ + private MesXslBizEntityFieldProfile resolveProfile(String bizCode) { + if (StringUtils.isBlank(bizCode)) { + return null; + } + Map bulk = BULK_PROFILE_BY_CODE.get(); + if (bulk != null) { + return bulk.get(bizCode.trim()); + } + return bizEntityFieldProfileService.getByBusinessCode(bizCode); + } + + @Override + public String getEntityClassFqn(String bizCode) { + MesXslBizEntityFieldProfile p = resolveProfile(bizCode); + return p != null ? StringUtils.trimToNull(p.getEntityClassName()) : null; + } + + @Override + public boolean hasCatalogForBiz(String bizCode) { + return resolveProfile(bizCode) != null; + } + + @Override + public List listMainFields(String bizCode) { + MesXslBizEntityFieldProfile p = resolveProfile(bizCode); + if (p == null) { + return Collections.emptyList(); + } + return parseFieldItems(p.getMainFieldsJson()); + } + + @Override + public List listDetailSlots(String bizCode) { + MesXslBizEntityFieldProfile p = resolveProfile(bizCode); + if (p == null || StringUtils.isBlank(p.getId())) { + return Collections.emptyList(); + } + List lines = + detailMapper.selectList( + new LambdaQueryWrapper() + .eq(MesXslBizEntityFieldDetail::getProfileId, p.getId()) + .orderByAsc(MesXslBizEntityFieldDetail::getSortNo) + .orderByAsc(MesXslBizEntityFieldDetail::getId)); + List out = new ArrayList<>(); + for (MesXslBizEntityFieldDetail line : lines) { + if (StringUtils.isBlank(line.getDetailPropertyName())) { + continue; + } + out.add( + new PrintBizDetailSlotVO( + line.getDetailPropertyName(), + StringUtils.defaultString(line.getDetailEntityClassName()), + StringUtils.defaultIfBlank(line.getDetailSlotKind(), "LIST"), + StringUtils.defaultIfBlank(line.getDetailName(), line.getDetailPropertyName()))); + } + return out; + } + + @Override + public List listPrefixedDetailFields(String bizCode, String detailProperty, String slotKind) { + if (StringUtils.isAnyBlank(bizCode, detailProperty)) { + return Collections.emptyList(); + } + MesXslBizEntityFieldProfile p = resolveProfile(bizCode); + if (p == null || StringUtils.isBlank(p.getId())) { + return Collections.emptyList(); + } + String prop = detailProperty.trim(); + String reqKind = StringUtils.trimToEmpty(slotKind); + List lines = + detailMapper.selectList( + new LambdaQueryWrapper() + .eq(MesXslBizEntityFieldDetail::getProfileId, p.getId())); + MesXslBizEntityFieldDetail hit = null; + for (MesXslBizEntityFieldDetail line : lines) { + if (!prop.equals(line.getDetailPropertyName())) { + continue; + } + if (!slotKindMatch(reqKind, line.getDetailSlotKind())) { + continue; + } + hit = line; + break; + } + if (hit == null) { + return Collections.emptyList(); + } + List raw = parseFieldItems(hit.getDetailFieldsJson()); + List out = new ArrayList<>(raw.size()); + for (PrintBizFieldItemVO x : raw) { + String path = prop + "." + x.getFieldKey(); + String label = "明细「" + prop + "」→ " + x.getLabel(); + out.add(PrintBizFieldItemVO.copyWithPrefixedPath(x, path, label)); + } + return out; + } + + private static boolean slotKindMatch(String requested, String stored) { + String r = StringUtils.trimToEmpty(requested); + String s = StringUtils.trimToEmpty(stored); + if (StringUtils.isBlank(s)) { + return true; + } + if (StringUtils.isBlank(r)) { + return true; + } + return r.equalsIgnoreCase(s); + } + + /** 解析 JSON 数组:支持 VO 对象元素或纯字符串字段名 */ + private List parseFieldItems(String json) { + if (StringUtils.isBlank(json)) { + return Collections.emptyList(); + } + try { + JsonNode root = OBJECT_MAPPER.readTree(json); + if (!root.isArray()) { + return Collections.emptyList(); + } + List out = new ArrayList<>(); + for (JsonNode n : root) { + if (n.isTextual()) { + String k = n.asText(); + if (StringUtils.isNotBlank(k)) { + out.add(PrintBizFieldItemVO.plainStringField(k)); + } + continue; + } + if (n.isObject()) { + PrintBizFieldItemVO vo = OBJECT_MAPPER.treeToValue(n, PrintBizFieldItemVO.class); + if (vo != null && StringUtils.isNotBlank(vo.getFieldKey())) { + out.add(vo); + } + } + } + return out; + } catch (Exception e) { + log.warn("解析业务实体字段缓存 JSON 失败: {}", e.getMessage()); + return Collections.emptyList(); + } + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslBizEntityFieldProfileService.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslBizEntityFieldProfileService.java new file mode 100644 index 0000000..2d8065a --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslBizEntityFieldProfileService.java @@ -0,0 +1,40 @@ +package org.jeecg.modules.xslmes.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import java.util.List; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile; + +/** 业务实体字段配置(主子表) */ +public interface IMesXslBizEntityFieldProfileService extends IService { + + /** 按业务编码(菜单 permission id)查询主表,不含 detailList */ + MesXslBizEntityFieldProfile getByBusinessCode(String businessCode); + + /** + * 按业务编码 upsert(用于启动扫描写入);明细全量替换。 + * + * @param businessCode 与 print_biz_perm_entity.perm_id、biz_code 一致 + */ + void upsertScannedProfile( + String businessCode, + String businessName, + String entityFqn, + String mainFieldsJson, + List detailRows); + + /** 新增主表并保存明细 */ + void saveWithDetails(MesXslBizEntityFieldProfile profile); + + /** 更新主表并重写明细 */ + void updateWithDetails(MesXslBizEntityFieldProfile profile); + + /** 按主键删除主表及明细 */ + void removeWithDetails(String id); + + /** 批量删除主表及明细 */ + void removeBatchWithDetails(java.util.Collection ids); + + /** 查询主表并填充 detailList */ + MesXslBizEntityFieldProfile getByIdWithDetails(String id); +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslRawMaterialWarehouseBoardService.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslRawMaterialWarehouseBoardService.java new file mode 100644 index 0000000..5c5f869 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslRawMaterialWarehouseBoardService.java @@ -0,0 +1,18 @@ +package org.jeecg.modules.xslmes.service; + +import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO; + +/** + * 原材料库区看板(库区 + 原材料卡片聚合) + */ +public interface IMesXslRawMaterialWarehouseBoardService { + + /** + * 聚合看板数据 + * + * @param warehouseId 所属仓库ID,可空表示全部启用库区 + * @param keyword 物料名称/条码/批次模糊筛选(可空);非空时仅展示仍有匹配卡片的库区 + * @param measureType quantity=占用率按剩余数量与 maxCapacity 对齐;weight=按剩余重量 + */ + MesXslRawMaterialWarehouseBoardVO queryBoard(String warehouseId, String keyword, String measureType); +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslWarehouseAreaService.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslWarehouseAreaService.java index 1046865..273fa17 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslWarehouseAreaService.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/IMesXslWarehouseAreaService.java @@ -3,6 +3,8 @@ package org.jeecg.modules.xslmes.service; import com.baomidou.mybatisplus.extension.service.IService; import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; +import java.util.Collection; + /** * MES 库区管理 */ @@ -12,4 +14,9 @@ public interface IMesXslWarehouseAreaService extends IService areas); } diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/MesXslStompNotifyService.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/MesXslStompNotifyService.java index 2ec033d..d55282c 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/MesXslStompNotifyService.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/MesXslStompNotifyService.java @@ -70,6 +70,11 @@ public class MesXslStompNotifyService { publish("/topic/sync/mes-warehouse-areas", "MES_WAREHOUSE_AREA_CHANGED", "warehouseAreaId", warehouseAreaId, action); } + /** 广播打印模板变更事件到 /topic/sync/print-templates */ + public void publishPrintTemplateChanged(String action, String templateId) { + publish("/topic/sync/print-templates", "PRINT_TEMPLATE_CHANGED", "templateId", templateId, action); + } + // ─────────────────────────── 私有辅助 ──────────────────────────── private void publish(String topic, String cmd, String idKey, String idValue, String action) { diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslBizEntityFieldProfileServiceImpl.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslBizEntityFieldProfileServiceImpl.java new file mode 100644 index 0000000..06387d2 --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslBizEntityFieldProfileServiceImpl.java @@ -0,0 +1,164 @@ +package org.jeecg.modules.xslmes.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import jakarta.annotation.Resource; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldDetail; +import org.jeecg.modules.xslmes.entity.MesXslBizEntityFieldProfile; +import org.jeecg.modules.xslmes.mapper.MesXslBizEntityFieldDetailMapper; +import org.jeecg.modules.xslmes.mapper.MesXslBizEntityFieldProfileMapper; +import org.jeecg.modules.xslmes.service.IMesXslBizEntityFieldProfileService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class MesXslBizEntityFieldProfileServiceImpl extends ServiceImpl + implements IMesXslBizEntityFieldProfileService { + + /** 标记为启动任务根据 print_biz_perm_entity 写入,便于区分手工维护数据 */ + private static final String REMARK_PRINT_PERM_SCAN = "print_biz_perm_entity 启动异步扫描"; + + @Resource + private MesXslBizEntityFieldDetailMapper detailMapper; + + @Override + public MesXslBizEntityFieldProfile getByBusinessCode(String businessCode) { + if (StringUtils.isBlank(businessCode)) { + return null; + } + return this.lambdaQuery() + .eq(MesXslBizEntityFieldProfile::getBusinessCode, businessCode.trim()) + .last("LIMIT 1") + .one(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void upsertScannedProfile( + String businessCode, + String businessName, + String entityFqn, + String mainFieldsJson, + List detailRows) { + if (StringUtils.isBlank(businessCode)) { + return; + } + String code = businessCode.trim(); + Date now = new Date(); + MesXslBizEntityFieldProfile existing = getByBusinessCode(code); + if (existing == null) { + MesXslBizEntityFieldProfile p = new MesXslBizEntityFieldProfile(); + p.setBusinessCode(code); + p.setBusinessName(StringUtils.defaultIfBlank(businessName, code)); + p.setEntityClassName(entityFqn); + p.setMainFieldsJson(mainFieldsJson); + p.setRemark(REMARK_PRINT_PERM_SCAN); + p.setCreateTime(now); + p.setUpdateTime(now); + p.setDetailList(detailRows != null ? detailRows : List.of()); + saveWithDetails(p); + return; + } + existing.setBusinessName(StringUtils.defaultIfBlank(businessName, existing.getBusinessName())); + existing.setEntityClassName(entityFqn); + existing.setMainFieldsJson(mainFieldsJson); + existing.setRemark(REMARK_PRINT_PERM_SCAN); + existing.setUpdateTime(now); + existing.setDetailList(detailRows != null ? detailRows : List.of()); + updateWithDetails(existing); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void saveWithDetails(MesXslBizEntityFieldProfile profile) { + this.save(profile); + insertDetailRows(profile); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateWithDetails(MesXslBizEntityFieldProfile profile) { + this.updateById(profile); + detailMapper.delete(new LambdaQueryWrapper().eq(MesXslBizEntityFieldDetail::getProfileId, profile.getId())); + insertDetailRows(profile); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void removeWithDetails(String id) { + if (StringUtils.isBlank(id)) { + return; + } + detailMapper.delete(new LambdaQueryWrapper().eq(MesXslBizEntityFieldDetail::getProfileId, id)); + this.removeById(id); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void removeBatchWithDetails(Collection ids) { + if (ids == null || ids.isEmpty()) { + return; + } + List trimmed = new ArrayList<>(); + for (String id : ids) { + if (StringUtils.isNotBlank(id)) { + String t = id.trim(); + trimmed.add(t); + detailMapper.delete(new LambdaQueryWrapper().eq(MesXslBizEntityFieldDetail::getProfileId, t)); + } + } + if (!trimmed.isEmpty()) { + this.removeByIds(trimmed); + } + } + + @Override + public MesXslBizEntityFieldProfile getByIdWithDetails(String id) { + MesXslBizEntityFieldProfile profile = this.getById(id); + if (profile == null) { + return null; + } + List lines = + detailMapper.selectList( + new LambdaQueryWrapper() + .eq(MesXslBizEntityFieldDetail::getProfileId, id) + .orderByAsc(MesXslBizEntityFieldDetail::getSortNo) + .orderByAsc(MesXslBizEntityFieldDetail::getId)); + profile.setDetailList(lines); + return profile; + } + + /** 写入子表(编辑时已清空旧数据) */ + private void insertDetailRows(MesXslBizEntityFieldProfile profile) { + if (profile.getDetailList() == null || profile.getDetailList().isEmpty()) { + return; + } + Date now = new Date(); + int seq = 0; + for (MesXslBizEntityFieldDetail row : profile.getDetailList()) { + row.setId(null); + row.setProfileId(profile.getId()); + if (row.getSortNo() == null) { + row.setSortNo(seq++); + } + if (row.getCreateTime() == null) { + row.setCreateTime(now); + } + if (row.getUpdateTime() == null) { + row.setUpdateTime(now); + } + if (StringUtils.isBlank(row.getCreateBy())) { + row.setCreateBy(profile.getCreateBy()); + } + if (StringUtils.isBlank(row.getUpdateBy())) { + row.setUpdateBy(profile.getUpdateBy()); + } + detailMapper.insert(row); + } + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslRawMaterialWarehouseBoardServiceImpl.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslRawMaterialWarehouseBoardServiceImpl.java new file mode 100644 index 0000000..e6155fc --- /dev/null +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslRawMaterialWarehouseBoardServiceImpl.java @@ -0,0 +1,248 @@ +package org.jeecg.modules.xslmes.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard; +import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; +import org.jeecg.modules.xslmes.service.IMesXslRawMaterialCardService; +import org.jeecg.modules.xslmes.service.IMesXslRawMaterialWarehouseBoardService; +import org.jeecg.modules.xslmes.service.IMesXslWarehouseAreaService; +import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO; +import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO.BoardAreaCardVO; +import org.jeecg.modules.xslmes.vo.MesXslRawMaterialWarehouseBoardVO.BoardBandVO; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * 原材料库区看板 + */ +@Service +@RequiredArgsConstructor +public class MesXslRawMaterialWarehouseBoardServiceImpl implements IMesXslRawMaterialWarehouseBoardService { + + private static final String MEASURE_WEIGHT = "weight"; + /** 库区编码首段形如 1F、2P、03A 等,仅作看板分组带标题(与仓库分类层级无「楼层」对应关系) */ + private static final Pattern BAND_FIRST_SEGMENT = Pattern.compile("^\\d+[A-Za-z]+$"); + + private final IMesXslWarehouseAreaService mesXslWarehouseAreaService; + private final IMesXslRawMaterialCardService mesXslRawMaterialCardService; + + @Override + public MesXslRawMaterialWarehouseBoardVO queryBoard(String warehouseId, String keyword, String measureType) { + String mt = StringUtils.defaultIfBlank(measureType, "quantity").toLowerCase(Locale.ROOT).trim(); + if (!MEASURE_WEIGHT.equals(mt)) { + mt = "quantity"; + } + MesXslRawMaterialWarehouseBoardVO vo = new MesXslRawMaterialWarehouseBoardVO(); + vo.setMeasureType(mt); + + QueryWrapper areaQw = new QueryWrapper<>(); + areaQw.eq("status", "0"); + if (StringUtils.isNotBlank(warehouseId)) { + areaQw.eq("warehouse_id", warehouseId.trim()); + } + areaQw.orderByAsc("area_code"); + List areas = mesXslWarehouseAreaService.list(areaQw); + if (areas.isEmpty()) { + return vo; + } + mesXslWarehouseAreaService.enrichDisplayedActualCapacity(areas); + + List areaCodes = areas.stream().map(MesXslWarehouseArea::getAreaCode).filter(StringUtils::isNotBlank).map(String::trim).distinct().collect(Collectors.toList()); + + QueryWrapper cardQw = new QueryWrapper<>(); + cardQw.in("warehouse_area", areaCodes); + cardQw.apply("(COALESCE(remaining_quantity,0) > 0 OR COALESCE(remaining_weight,0) > 0)"); + String kw = StringUtils.trimToNull(keyword); + if (kw != null) { + cardQw.and(w -> + w.like("material_name", kw).or().like("barcode", kw).or().like("batch_no", kw)); + } + List cards = mesXslRawMaterialCardService.list(cardQw); + + Map> byArea = + cards.stream().filter(c -> StringUtils.isNotBlank(c.getWarehouseArea())).collect(Collectors.groupingBy(c -> c.getWarehouseArea().trim(), Collectors.toList())); + + boolean filterByKeyword = kw != null; + Map bandMap = new LinkedHashMap<>(); + + for (MesXslWarehouseArea area : areas) { + String code = StringUtils.trimToEmpty(area.getAreaCode()); + if (code.isEmpty()) { + continue; + } + List list = byArea.getOrDefault(code, new ArrayList<>()); + if (filterByKeyword && list.isEmpty()) { + continue; + } + BoardAreaCardVO cardVo = aggregateArea(area, list, mt); + BandKey bk = resolveBand(area.getAreaCode()); + BoardBandVO band = bandMap.computeIfAbsent(bk.key, k -> { + BoardBandVO b = new BoardBandVO(); + b.setBandKey(bk.key); + b.setBandLabel(bk.label); + b.setBandSort(bk.sort); + return b; + }); + band.getAreas().add(cardVo); + } + + List bands = + bandMap.values().stream().sorted(Comparator.comparing(BoardBandVO::getBandSort, Comparator.nullsLast(Integer::compareTo)).thenComparing(BoardBandVO::getBandKey, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList()); + + for (BoardBandVO band : bands) { + band.getAreas().sort(Comparator.comparing(BoardAreaCardVO::getAreaCode, Comparator.nullsLast(String::compareTo))); + } + vo.setBands(bands); + return vo; + } + + private BoardAreaCardVO aggregateArea(MesXslWarehouseArea area, List list, String measureType) { + BoardAreaCardVO vo = new BoardAreaCardVO(); + vo.setAreaId(area.getId()); + vo.setAreaCode(area.getAreaCode()); + vo.setAreaName(area.getAreaName()); + vo.setWarehouseId(area.getWarehouseId()); + vo.setWarehouseName(area.getWarehouseName()); + vo.setMaxCapacity(area.getMaxCapacity()); + vo.setActualCapacity(area.getActualCapacity()); + vo.setCardCount(list.size()); + + int sumQty = 0; + BigDecimal sumW = BigDecimal.ZERO; + LinkedHashSet materialNames = new LinkedHashSet<>(); + for (MesXslRawMaterialCard c : list) { + if (c.getRemainingQuantity() != null) { + sumQty += c.getRemainingQuantity(); + } + if (c.getRemainingWeight() != null) { + sumW = sumW.add(c.getRemainingWeight()); + } + if (StringUtils.isNotBlank(c.getMaterialName())) { + materialNames.add(c.getMaterialName().trim()); + } + } + vo.setCurrentQuantity(sumQty); + vo.setCurrentWeight(sumW.setScale(3, RoundingMode.HALF_UP)); + vo.setMaterialKindCount(materialNames.size()); + vo.setTopMaterialNames(materialNames.stream().limit(8).collect(Collectors.toList())); + + Double usage = null; + Integer maxCap = area.getMaxCapacity(); + if (maxCap != null && maxCap > 0) { + if (MEASURE_WEIGHT.equals(measureType)) { + usage = sumW.multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(maxCap), 1, RoundingMode.HALF_UP).doubleValue(); + } else { + usage = BigDecimal.valueOf(sumQty).multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(maxCap), 1, RoundingMode.HALF_UP).doubleValue(); + } + if (usage > 100) { + usage = 100d; + } + if (usage < 0) { + usage = 0d; + } + } + vo.setUsagePercent(usage); + vo.setAlertLevel(resolveAlert(usage, list.isEmpty())); + return vo; + } + + private static String resolveAlert(Double usagePercent, boolean emptyCards) { + if (emptyCards) { + return "empty"; + } + if (usagePercent == null) { + return "unknown"; + } + if (usagePercent <= 0) { + return "empty"; + } + if (usagePercent < 30) { + return "low"; + } + if (usagePercent < 90) { + return "normal"; + } + if (usagePercent < 100) { + return "high"; + } + return "full"; + } + + private BandKey resolveBand(String areaCode) { + if (StringUtils.isBlank(areaCode)) { + return new BandKey("zzz_other", "其它", 999_000); + } + String trimmed = areaCode.trim(); + String head = trimmed.contains("-") ? trimmed.substring(0, trimmed.indexOf('-')) : trimmed; + if (BAND_FIRST_SEGMENT.matcher(head).matches()) { + String normalized = normalizeBandToken(head); + int sort = bandSort(normalized); + return new BandKey(normalized.toLowerCase(Locale.ROOT), normalized, sort); + } + String label = StringUtils.left(head, 16); + if (label.isEmpty()) { + label = trimmed.length() > 16 ? trimmed.substring(0, 16) : trimmed; + } + return new BandKey("z_" + label.toLowerCase(Locale.ROOT), label, 888_000 + Math.abs(label.hashCode() % 1000)); + } + + private static String normalizeBandToken(String raw) { + if (raw == null) { + return "其它"; + } + String s = raw.toUpperCase(Locale.ROOT); + s = s.replace('F', 'F').replace('P', 'P'); + return s; + } + + /** + * 简单排序:按前缀中的数字升序(1F<2F<10F),末尾字母次之 + */ + private static int bandSort(String label) { + String digits = ""; + String tail = ""; + for (int i = 0; i < label.length(); i++) { + char ch = label.charAt(i); + if (Character.isDigit(ch)) { + digits += ch; + } else { + tail = label.substring(i); + break; + } + } + int num = 0; + try { + if (!digits.isEmpty()) { + num = Integer.parseInt(digits); + } + } catch (NumberFormatException ignored) { + num = 0; + } + return num * 100 + Math.min(Math.abs(tail.hashCode() % 99), 99); + } + + private static final class BandKey { + final String key; + final String label; + final int sort; + + BandKey(String key, String label, int sort) { + this.key = key; + this.label = label; + this.sort = sort; + } + } +} diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseAreaServiceImpl.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseAreaServiceImpl.java index d4a2908..b2db810 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseAreaServiceImpl.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseAreaServiceImpl.java @@ -1,18 +1,25 @@ package org.jeecg.modules.xslmes.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.xslmes.capacity.WarehouseAreaDisplayedActualCapacityMediator; import org.jeecg.modules.xslmes.entity.MesXslWarehouseArea; import org.jeecg.modules.xslmes.mapper.MesXslWarehouseAreaMapper; import org.jeecg.modules.xslmes.service.IMesXslWarehouseAreaService; import org.springframework.stereotype.Service; +import java.util.Collection; + /** * MES 库区管理 */ @Service +@RequiredArgsConstructor public class MesXslWarehouseAreaServiceImpl extends ServiceImpl implements IMesXslWarehouseAreaService { + private final WarehouseAreaDisplayedActualCapacityMediator displayedActualCapacityMediator; + @Override public boolean existsSameAreaCode(String areaCode, String excludeId) { if (StringUtils.isBlank(areaCode)) { @@ -24,4 +31,9 @@ public class MesXslWarehouseAreaServiceImpl extends ServiceImpl 0L; } + + @Override + public void enrichDisplayedActualCapacity(Collection areas) { + displayedActualCapacityMediator.apply(areas); + } } diff --git a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseServiceImpl.java b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseServiceImpl.java index 3333a35..f05ab9c 100644 --- a/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseServiceImpl.java +++ b/jeecg-boot/jeecg-boot-module/jeecg-module-xslmes/src/main/java/org/jeecg/modules/xslmes/service/impl/MesXslWarehouseServiceImpl.java @@ -41,11 +41,11 @@ public class MesXslWarehouseServiceImpl extends ServiceImpl bands = new ArrayList<>(); + + @Data + @Schema(description = "看板分组带(如 1F、2F)") + public static class BoardBandVO implements Serializable { + private static final long serialVersionUID = 1L; + + @Schema(description = "分组键(排序用)") + private String bandKey; + + @Schema(description = "分组标题") + private String bandLabel; + + @Schema(description = "排序号,越小越靠前") + private Integer bandSort; + + @Schema(description = "该组下的库区卡片") + private List areas = new ArrayList<>(); + } + + @Data + @Schema(description = "单个库区卡片数据") + public static class BoardAreaCardVO implements Serializable { + private static final long serialVersionUID = 1L; + + @Schema(description = "库区主键") + private String areaId; + + @Schema(description = "库区编码") + private String areaCode; + + @Schema(description = "库区名称") + private String areaName; + + @Schema(description = "所属仓库ID") + private String warehouseId; + + @Schema(description = "所属仓库名称") + private String warehouseName; + + @Schema(description = "最大存放量(库区主数据)") + private Integer maxCapacity; + + @Schema(description = "实际存放量(库区主数据快照)") + private Integer actualCapacity; + + @Schema(description = "在库卡片张数(有剩余量)") + private Integer cardCount; + + @Schema(description = "物料种类数(去重物料名称)") + private Integer materialKindCount; + + @Schema(description = "剩余数量合计") + private Integer currentQuantity; + + @Schema(description = "剩余重量合计") + private BigDecimal currentWeight; + + @Schema(description = "物料名称摘要(前若干种)") + private List topMaterialNames = new ArrayList<>(); + + @Schema(description = "占用率 0~100,无上限或上限为0时为 null") + private Double usagePercent; + + @Schema(description = "告警级别:empty/low/normal/high/full/unknown") + private String alertLevel; + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/bootstrap/PrintBizPermEntityWarmupRunner.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/bootstrap/PrintBizPermEntityWarmupRunner.java new file mode 100644 index 0000000..beee855 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/bootstrap/PrintBizPermEntityWarmupRunner.java @@ -0,0 +1,43 @@ +package org.jeecg.modules.print.bootstrap; + +import java.util.concurrent.CompletableFuture; +import lombok.extern.slf4j.Slf4j; +import org.jeecg.modules.print.service.IPrintBizPermEntityService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * 项目启动后异步从数据库 {@code sys_permission} 读取真实 component / component_name,预热 + * {@code print_biz_perm_entity},不依赖人工白名单操作。关闭:{@code jeecg.print.biz-perm-warmup=false} + */ +@Slf4j +@Component +@Order(2000) +public class PrintBizPermEntityWarmupRunner implements ApplicationRunner { + + @Autowired private IPrintBizPermEntityService printBizPermEntityService; + + @Value("${jeecg.print.biz-perm-warmup:true}") + private boolean warmupEnabled; + + @Override + public void run(ApplicationArguments args) { + if (!warmupEnabled) { + log.info("打印菜单-实体映射预热已关闭(jeecg.print.biz-perm-warmup=false)"); + return; + } + CompletableFuture.runAsync( + () -> { + try { + log.info("打印菜单-实体映射:开始异步预热(来源 sys_permission 表)"); + printBizPermEntityService.warmupMappingsFromSysPermissionTable(); + } catch (Exception e) { + log.warn("打印菜单-实体映射预热失败(不影响系统启动)", e); + } + }); + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/catalog/IPrintBizEntityFieldCatalogProvider.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/catalog/IPrintBizEntityFieldCatalogProvider.java new file mode 100644 index 0000000..20166d7 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/catalog/IPrintBizEntityFieldCatalogProvider.java @@ -0,0 +1,41 @@ +package org.jeecg.modules.print.catalog; + +import java.util.Collection; +import java.util.List; +import org.jeecg.modules.print.vo.PrintBizDetailSlotVO; +import org.jeecg.modules.print.vo.PrintBizFieldItemVO; + +/** + * 业务实体字段缓存(mes_xsl_biz_entity_field_*)供打印绑定使用;实现类位于 jeecg-module-xslmes,避免 system-biz 依赖业务模块。 + * + *

bizCode 与 {@code print_biz_perm_entity.perm_id}、打印绑定 {@code biz_code} 一致。 + */ +public interface IPrintBizEntityFieldCatalogProvider { + + /** + * 在一次接口内批量组装多个业务的 VO 前调用,将mes_xsl_biz_entity_field_profile 一次查出放入线程缓存,避免按业务 N + * 次查询;必须与 {@link #endBulkLookup()} 成对(建议 finally)。 + */ + default void beginBulkLookup(Collection bizCodes) {} + + /** 结束批量查找,清理线程缓存 */ + default void endBulkLookup() {} + + /** 缓存中的主实体全限定名(无记录返回 null) */ + String getEntityClassFqn(String bizCode); + + /** 是否已有缓存记录(存在即优先走缓存,即使字段为空) */ + boolean hasCatalogForBiz(String bizCode); + + /** 主实体可选字段(与反射接口字段结构一致) */ + List listMainFields(String bizCode); + + /** 明细数据来源槽位 */ + List listDetailSlots(String bizCode); + + /** + * 明细槽位对应字段,fieldKey 已带「属性名.」前缀(与 {@link org.jeecg.modules.print.util.PrintBizDetailPropertyScanner#listPrefixedDetailFields} + * 一致)。 + */ + List listPrefixedDetailFields(String bizCode, String detailProperty, String slotKind); +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintBizTemplateBindController.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintBizTemplateBindController.java new file mode 100644 index 0000000..5d886f8 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintBizTemplateBindController.java @@ -0,0 +1,376 @@ +package org.jeecg.modules.print.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import com.alibaba.fastjson.JSON; +import jakarta.servlet.http.HttpServletRequest; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.jeecg.common.api.vo.Result; +import org.jeecg.common.aspect.annotation.AutoLog; +import org.jeecg.common.system.base.controller.JeecgController; +import org.jeecg.common.system.query.QueryGenerator; +import org.jeecg.modules.print.catalog.IPrintBizEntityFieldCatalogProvider; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; +import org.jeecg.modules.print.entity.PrintTemplate; +import org.jeecg.modules.print.service.IPrintBizBindPermWhitelistService; +import org.jeecg.modules.print.service.IPrintBizPermEntityService; +import org.jeecg.modules.print.service.IPrintBizTemplateBindService; +import org.jeecg.modules.print.service.IPrintTemplateService; +import org.jeecg.modules.print.util.PrintBizDataMappingUtil; +import org.jeecg.modules.print.util.PrintBizDetailPropertyScanner; +import org.jeecg.modules.print.util.PrintBizEntityFieldIntrospector; +import org.jeecg.modules.print.util.PrintNativeTemplateFieldExtractor; +import org.jeecg.modules.print.vo.PrintBizDetailSlotVO; +import org.jeecg.modules.print.vo.PrintBizFieldItemVO; +import org.jeecg.modules.print.vo.PrintBizTypeVO; +import org.jeecg.modules.print.vo.PrintTemplateFieldItemVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.web.bind.annotation.*; + +/** + * 业务与打印模板绑定:可视化配置字段映射 + */ +@Slf4j +@Tag(name = "业务打印绑定") +@RestController +@RequestMapping("/print/bizTemplateBind") +public class PrintBizTemplateBindController extends JeecgController { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + @Autowired private IPrintTemplateService printTemplateService; + @Autowired private IPrintBizBindPermWhitelistService printBizBindPermWhitelistService; + @Autowired private IPrintBizPermEntityService printBizPermEntityService; + @Autowired private SimpMessagingTemplate messagingTemplate; + + @Autowired(required = false) + private IPrintBizEntityFieldCatalogProvider fieldCatalogProvider; + + @Operation(summary = "业务打印绑定-分页列表") + @GetMapping("/list") + @RequiresPermissions("print:bizBind:list") + public Result> list( + PrintBizTemplateBind query, + @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, + @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, + HttpServletRequest req) { + QueryWrapper qw = + QueryGenerator.initQueryWrapper(query, req.getParameterMap()); + qw.orderByDesc("create_time"); + Page page = new Page<>(pageNo, pageSize); + return Result.OK(service.page(page, qw)); + } + + @AutoLog(value = "业务打印绑定-添加") + @Operation(summary = "业务打印绑定-添加") + @PostMapping("/add") + @RequiresPermissions("print:bizBind:add") + public Result add(@RequestBody PrintBizTemplateBind entity) { + String err = validateAndFillTemplate(entity); + if (err != null) { + return Result.error(err); + } + if (service.getByBizCode(entity.getBizCode()) != null) { + return Result.error("该业务编码已存在绑定,请编辑原记录或先删除"); + } + normalizeMappingJson(entity); + service.save(entity); + publishPrintBizTemplateBindChanged("add", entity.getId()); + return Result.OK("添加成功"); + } + + @AutoLog(value = "业务打印绑定-编辑") + @Operation(summary = "业务打印绑定-编辑") + @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST}) + @RequiresPermissions("print:bizBind:edit") + public Result edit(@RequestBody PrintBizTemplateBind entity) { + PrintBizTemplateBind db = service.getById(entity.getId()); + if (db == null) { + return Result.error("记录不存在"); + } + String err = validateAndFillTemplate(entity); + if (err != null) { + return Result.error(err); + } + PrintBizTemplateBind other = service.getByBizCode(entity.getBizCode()); + if (other != null && !other.getId().equals(entity.getId())) { + return Result.error("业务编码与其他记录冲突"); + } + normalizeMappingJson(entity); + service.updateById(entity); + publishPrintBizTemplateBindChanged("edit", entity.getId()); + return Result.OK("编辑成功"); + } + + @AutoLog(value = "业务打印绑定-删除") + @Operation(summary = "业务打印绑定-删除") + @DeleteMapping("/delete") + @RequiresPermissions("print:bizBind:delete") + public Result delete(@RequestParam(name = "id") String id) { + if (service.removeById(id)) { + publishPrintBizTemplateBindChanged("delete", id); + } + return Result.OK("删除成功"); + } + + @Operation(summary = "已配置的菜单-实体映射及反射字段(完整目录;biz_code 为菜单 id)") + @GetMapping("/bizTypes") + @RequiresPermissions("print:bizBind:list") + public Result> bizTypes() { + return Result.OK(printBizPermEntityService.listAllBizTypeVOs()); + } + + /** + * 「新增/编辑业务打印绑定」业务下拉:print_biz_perm_entity 中的映射,并按「打印业务白名单」过滤。 + * 白名单为空表示不过滤;非空则仅保留菜单 id 在白名单内的项。 + */ + @Operation(summary = "可选业务类型(白名单过滤后)") + @GetMapping("/bizTypesForBinding") + @RequiresPermissions("print:bizBind:list") + public Result> bizTypesForBinding() { + return Result.OK(printBizBindPermWhitelistService.listBizTypesForBinding()); + } + + @Operation(summary = "打印业务白名单:当前勾选的菜单 id(catalog 恒为空,避免全库反射超时)") + @GetMapping("/permWhitelist") + @RequiresPermissions("print:bizBind:whitelist") + public Result getPermWhitelist() { + PrintBizPermWhitelistVO vo = new PrintBizPermWhitelistVO(); + vo.setPermIds(printBizBindPermWhitelistService.listPermIds()); + vo.setCatalog(Collections.emptyList()); + return Result.OK(vo); + } + + @AutoLog(value = "业务打印绑定-保存打印业务白名单") + @Operation(summary = "保存打印业务白名单(按菜单 permission id)") + @PostMapping("/permWhitelist") + @RequiresPermissions("print:bizBind:whitelist") + public Result savePermWhitelist(@RequestBody PermWhitelistBody body) { + printBizBindPermWhitelistService.replacePermIds(body == null ? null : body.getPermIds()); + return Result.OK("保存成功"); + } + + @Operation(summary = "解析原生模板中的占位字段(bindField)") + @GetMapping("/parseTemplateFields") + @RequiresPermissions("print:bizBind:list") + public Result> parseTemplateFields( + @RequestParam(name = "templateId") String templateId) { + if (StringUtils.isBlank(templateId)) { + return Result.error("templateId 不能为空"); + } + PrintTemplate tpl = printTemplateService.getById(templateId); + if (tpl == null) { + return Result.error("模板不存在"); + } + List fields = + PrintNativeTemplateFieldExtractor.extract(tpl.getTemplateJson()); + return Result.OK(fields); + } + + @Operation(summary = "主实体上的明细槽位(List<明细实体> / 明细数组 / 嵌套对象),用于先选明细再反射明细字段") + @GetMapping("/detailSlots") + @RequiresPermissions("print:bizBind:list") + public Result> detailSlots(@RequestParam(name = "bizCode") String bizCode) { + if (StringUtils.isBlank(bizCode)) { + return Result.error("bizCode 不能为空"); + } + String code = bizCode.trim(); + if (fieldCatalogProvider != null && fieldCatalogProvider.hasCatalogForBiz(code)) { + return Result.OK(fieldCatalogProvider.listDetailSlots(code)); + } + PrintBizTypeVO bizVo = printBizPermEntityService.resolveBizTypeVo(code); + if (bizVo == null || StringUtils.isBlank(bizVo.getDescription())) { + return Result.OK(Collections.emptyList()); + } + Class main = PrintBizEntityFieldIntrospector.tryLoadClass(bizVo.getDescription().trim()); + if (main == null) { + return Result.OK(Collections.emptyList()); + } + return Result.OK(PrintBizDetailPropertyScanner.listSlots(main)); + } + + @Operation(summary = "反射指定明细槽位元素类的字段(fieldKey 带「属性名.」前缀,用于与模板明细占位绑定)") + @GetMapping("/bizFieldsForDetailSlot") + @RequiresPermissions("print:bizBind:list") + public Result> bizFieldsForDetailSlot( + @RequestParam(name = "bizCode") String bizCode, + @RequestParam(name = "detailProperty") String detailProperty, + @RequestParam(name = "slotKind", defaultValue = "LIST") String slotKind) { + if (StringUtils.isAnyBlank(bizCode, detailProperty)) { + return Result.error("bizCode 与 detailProperty 不能为空"); + } + String code = bizCode.trim(); + if (fieldCatalogProvider != null && fieldCatalogProvider.hasCatalogForBiz(code)) { + return Result.OK( + fieldCatalogProvider.listPrefixedDetailFields(code, detailProperty.trim(), slotKind.trim())); + } + PrintBizTypeVO bizVo = printBizPermEntityService.resolveBizTypeVo(code); + if (bizVo == null || StringUtils.isBlank(bizVo.getDescription())) { + return Result.OK(Collections.emptyList()); + } + Class main = PrintBizEntityFieldIntrospector.tryLoadClass(bizVo.getDescription().trim()); + if (main == null) { + return Result.OK(Collections.emptyList()); + } + return Result.OK( + PrintBizDetailPropertyScanner.listPrefixedDetailFields( + main, detailProperty.trim(), slotKind.trim())); + } + + @Operation(summary = "按业务编码查询绑定(供打印调用)") + @GetMapping("/queryByBizCode") + @RequiresPermissions("print:bizBind:list") + public Result queryByBizCode(@RequestParam(name = "bizCode") String bizCode) { + if (StringUtils.isBlank(bizCode)) { + return Result.error("bizCode 不能为空"); + } + PrintBizTemplateBind row = service.getByBizCode(bizCode.trim()); + if (row == null) { + return Result.error("未配置该业务的打印绑定"); + } + return Result.OK(row); + } + + @Operation(summary = "预览:业务数据按映射转为模板打印 JSON") + @PostMapping("/previewMappedData") + @RequiresPermissions("print:bizBind:list") + public Result> previewMappedData(@RequestBody PreviewMappedBody body) { + if (body == null || StringUtils.isBlank(body.getBizCode())) { + return Result.error("bizCode 不能为空"); + } + PrintBizTemplateBind bind = service.getByBizCode(body.getBizCode().trim()); + if (bind == null) { + return Result.error("未配置该业务的打印绑定"); + } + try { + ArrayNode mapping = PrintBizDataMappingUtil.parseMappingArray(bind.getFieldMappingJson()); + JsonNode bizRoot = PrintBizDataMappingUtil.parseBizJson(body.getBizDataJson()); + ObjectNode printData = PrintBizDataMappingUtil.mapBizToPrintData(bizRoot, mapping); + PrintTemplate tpl = printTemplateService.getById(bind.getTemplateId()); + if (tpl != null && StringUtils.isNotBlank(tpl.getTemplateJson())) { + PrintBizDataMappingUtil.fillMissingDataBindingParamKeys(printData, tpl.getTemplateJson()); + } + Map res = new HashMap<>(4); + res.put("templateCode", bind.getTemplateCode()); + res.put("templateId", bind.getTemplateId()); + res.put("printData", OBJECT_MAPPER.convertValue(printData, Map.class)); + return Result.OK(res); + } catch (Exception e) { + return Result.error("预览失败:" + e.getMessage()); + } + } + + /** @return 错误信息;null 表示校验通过 */ + private String validateAndFillTemplate(PrintBizTemplateBind entity) { + if (entity == null || StringUtils.isBlank(entity.getBizCode())) { + return "业务编码不能为空"; + } + if (StringUtils.isBlank(entity.getTemplateId())) { + return "请选择打印模板"; + } + PrintTemplate tpl = printTemplateService.getById(entity.getTemplateId()); + if (tpl == null) { + return "打印模板不存在"; + } + entity.setTemplateCode(tpl.getTemplateCode()); + PrintBizTypeVO bizVo = printBizPermEntityService.resolveBizTypeVo(entity.getBizCode()); + if (bizVo == null) { + return "无效的业务:该菜单无法解析到实体类(需菜单 component 为如 xslmes/xxx/XxxList,或在 print_biz_perm_entity 中配置 entity_class;biz_code 为菜单 id)"; + } + if (StringUtils.isBlank(entity.getBizName())) { + entity.setBizName(bizVo.getBizName()); + } + return null; + } + + /** 确保 mapping JSON 为数组字符串 */ + private void normalizeMappingJson(PrintBizTemplateBind entity) { + String raw = entity.getFieldMappingJson(); + if (StringUtils.isBlank(raw)) { + entity.setFieldMappingJson("[]"); + return; + } + try { + JsonNode n = OBJECT_MAPPER.readTree(raw); + if (!n.isArray()) { + entity.setFieldMappingJson("[]"); + } + } catch (Exception e) { + entity.setFieldMappingJson("[]"); + } + } + + @Data + public static class PreviewMappedBody { + private String bizCode; + /** 业务对象 JSON(对象或可解析字符串) */ + private Object bizDataJson; + } + + @Data + public static class PrintBizPermWhitelistVO { + /** 已勾选的 sys_permission.id;空集合表示未配置(不限制可选业务) */ + private java.util.List permIds; + /** 完整打印业务目录(含 linkedPermissionId,便于对照菜单) */ + private java.util.List catalog; + } + + @Data + public static class PermWhitelistBody { + private java.util.List permIds; + } + + // ═══════════════════════════ 桌面端免密只读 ═══════════════════════════ + + @Operation(summary = "业务打印绑定-免密分页列表(桌面端缓存同步)") + @GetMapping("/anon/list") + public Result> anonList( + PrintBizTemplateBind query, + @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, + @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, + HttpServletRequest req) { + QueryWrapper qw = + QueryGenerator.initQueryWrapper(query, req.getParameterMap()); + qw.orderByDesc("create_time"); + Page page = new Page<>(pageNo, pageSize); + return Result.OK(service.page(page, qw)); + } + + @Operation(summary = "业务打印绑定-免密按 id 查询(桌面端)") + @GetMapping("/anon/queryById") + public Result anonQueryById(@RequestParam(name = "id") String id) { + PrintBizTemplateBind row = service.getById(id); + return row != null ? Result.OK(row) : Result.error("未找到记录"); + } + + /** + * 广播到 /topic/sync/print-biz-binds,与桌面端 PrintBizTemplateBindSyncCoordinator 对应。 + */ + private void publishPrintBizTemplateBindChanged(String action, String bindId) { + try { + Map event = new HashMap<>(); + event.put("cmd", "PRINT_BIZ_TEMPLATE_BIND_CHANGED"); + event.put("action", action); + event.put("bindId", bindId); + event.put("timestamp", System.currentTimeMillis()); + messagingTemplate.convertAndSend("/topic/sync/print-biz-binds", JSON.toJSONString(event)); + } catch (Exception e) { + log.debug("广播 STOMP 事件失败 [PRINT_BIZ_TEMPLATE_BIND_CHANGED]: {}", e.getMessage()); + } + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java index 3029843..4e904fa 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/controller/PrintTemplateController.java @@ -6,36 +6,19 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; -import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Locale; import java.util.Map; -import java.util.stream.Collectors; -import javax.print.Doc; -import javax.print.DocFlavor; -import javax.print.DocPrintJob; -import javax.print.PrintException; import javax.print.PrintService; -import javax.print.PrintServiceLookup; -import javax.print.SimpleDoc; -import javax.print.attribute.HashPrintRequestAttributeSet; -import javax.print.attribute.standard.JobName; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; -import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Printable; -import java.awt.print.PrinterAbortException; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; -import java.io.ByteArrayInputStream; import lombok.extern.slf4j.Slf4j; -import org.apache.pdfbox.pdmodel.PDDocument; -import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.jeecg.common.api.vo.Result; @@ -44,10 +27,13 @@ import org.jeecg.common.system.base.controller.JeecgController; import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.modules.print.entity.PrintTemplate; import org.jeecg.modules.print.service.IPrintTemplateService; +import org.jeecg.modules.print.support.PrintServerEnvironmentService; +import org.jeecg.modules.print.support.PrintServerPdfJobService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import org.jeecg.modules.print.ai.INativePrintTemplateImageAnalyzeService; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import com.alibaba.fastjson.JSON; /** * 打印模板维护(Hiprint) @@ -57,12 +43,22 @@ import org.jeecg.modules.print.ai.INativePrintTemplateImageAnalyzeService; @RestController @RequestMapping("/print/template") public class PrintTemplateController extends JeecgController { - @Value("${print.network-printers:}") - private String networkPrinters; + @Autowired private PrintServerEnvironmentService printServerEnvironmentService; + @Autowired private PrintServerPdfJobService printServerPdfJobService; @Autowired private INativePrintTemplateImageAnalyzeService nativePrintTemplateImageAnalyzeService; + /** + * STOMP 实时通知:广播打印模板变更到 /topic/sync/print-templates。 + * 直接用 SimpMessagingTemplate 内联推送,避免 jeecg-system-biz(核心模块) + * 反向依赖 jeecg-module-xslmes(业务模块)造成的循环依赖。 + * 消息体格式与 MesXslStompNotifyService.publishPrintTemplateChanged 完全一致, + * 桌面端订阅方无需任何改动。 + */ + @Autowired + private SimpMessagingTemplate messagingTemplate; + @Operation(summary = "打印模板-分页列表") @GetMapping(value = "/list") @RequiresPermissions("print:template:list") @@ -92,6 +88,7 @@ public class PrintTemplateController extends JeecgController delete(@RequestParam(name = "id") String id) { service.removeById(id); + publishPrintTemplateChanged("delete", id); return Result.OK("删除成功"); } @@ -153,7 +152,9 @@ public class PrintTemplateController extends JeecgController idList = java.util.Arrays.asList(ids.split(",")); + service.removeByIds(idList); + idList.forEach(id -> publishPrintTemplateChanged("delete", id.trim())); return Result.OK("批量删除成功"); } @@ -208,45 +209,7 @@ public class PrintTemplateController extends JeecgController> queryPrinters() { - Map res = new HashMap<>(8); - List serverPrinters = new ArrayList<>(); - String serverDefaultPrinter = ""; - try { - PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); - if (services != null) { - for (PrintService service : services) { - if (service != null && StringUtils.isNotBlank(service.getName())) { - serverPrinters.add(service.getName().trim()); - } - } - } - PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); - if (defaultService != null && StringUtils.isNotBlank(defaultService.getName())) { - serverDefaultPrinter = defaultService.getName().trim(); - } - } catch (Exception e) { - log.warn("查询服务器打印机失败: {}", e.getMessage()); - } - List networkPrinterList = - StringUtils.isBlank(networkPrinters) - ? new ArrayList<>() - : java.util.Arrays.stream(networkPrinters.split(",")) - .map(String::trim) - .filter(StringUtils::isNotBlank) - .distinct() - .collect(Collectors.toList()); - - Map capability = new LinkedHashMap<>(4); - capability.put("localSupported", false); - capability.put("localReason", "浏览器环境无法直接枚举客户端本地打印机,需要本地组件或客户端程序配合。"); - capability.put("serverSupported", true); - capability.put("networkSupported", true); - - res.put("capability", capability); - res.put("serverPrinters", serverPrinters); - res.put("serverDefaultPrinter", serverDefaultPrinter); - res.put("networkPrinters", networkPrinterList); - return Result.OK(res); + return Result.OK(printServerEnvironmentService.buildPrinterQueryResult()); } @AutoLog(value = "打印模板-服务端直打") @@ -269,23 +232,12 @@ public class PrintTemplateController extends JeecgController 0) { - base64Body = pdfBase64.substring(commaIdx + 1); - } - byte[] pdfBytes = Base64.getDecoder().decode(base64Body); - String printJobName = StringUtils.isNotBlank(fileName) ? fileName : ("QH-MES-" + templateCode + ".pdf"); - // 优先直送 PDF 字节,避免走 RasterPrinterJob(虚拟打印机/无界面会话下易触发 PrinterAbortException) - if (tryPrintPdfBytesWithDocFlavor(target, pdfBytes, printJobName)) { - return Result.OK("已提交PDF到服务器打印机: " + resolvedPrinterLabel); - } - try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes))) { - PDFRenderer renderer = new PDFRenderer(document); - PrinterJob job = PrinterJob.getPrinterJob(); - job.setPrintService(target); - job.setJobName(printJobName); - job.setPrintable( - (graphics, pageFormat, pageIndex) -> { - if (pageIndex >= document.getNumberOfPages()) { - return Printable.NO_SUCH_PAGE; - } - BufferedImage image; - try { - image = renderer.renderImageWithDPI(pageIndex, 150); - } catch (Exception ex) { - throw new PrinterException("PDF页面渲染失败: " + ex.getMessage()); - } - Graphics2D g2 = (Graphics2D) graphics; - double imageableX = pageFormat.getImageableX(); - double imageableY = pageFormat.getImageableY(); - double imageableWidth = pageFormat.getImageableWidth(); - double imageableHeight = pageFormat.getImageableHeight(); - double scale = - Math.min(imageableWidth / image.getWidth(), imageableHeight / image.getHeight()); - int drawWidth = (int) Math.round(image.getWidth() * scale); - int drawHeight = (int) Math.round(image.getHeight() * scale); - int drawX = (int) Math.round(imageableX + (imageableWidth - drawWidth) / 2); - int drawY = (int) Math.round(imageableY + (imageableHeight - drawHeight) / 2); - g2.drawImage(image, drawX, drawY, drawWidth, drawHeight, null); - return Printable.PAGE_EXISTS; - }); - HashPrintRequestAttributeSet patts = new HashPrintRequestAttributeSet(); - patts.add(new JobName(printJobName, Locale.getDefault())); - job.print(patts); - } - return Result.OK("已提交PDF到服务器打印机: " + resolvedPrinterLabel); - } catch (PrinterAbortException e) { - log.error("PDF后端打印失败(PrinterAbortException)", e); - return Result.error(buildPdfPrinterAbortHint(printerName, lastResolvedPrinterLabel)); - } catch (Exception e) { - log.error("PDF后端打印失败", e); - return Result.error("PDF后端打印失败: " + e.getMessage()); + return printServerPdfJobService.submitPdfBase64(printerName, pdfBase64, fileName, templateCode); + } + + // ═══════════════════════════ 桌面端免密接口 ═══════════════════════════ + + @Operation(summary = "打印模板-免密通过编码查询(桌面端)") + @GetMapping(value = "/anon/queryByCode") + public Result anonQueryByCode(@RequestParam(name = "code") String code) { + PrintTemplate t = service.getByCode(code); + if (t == null) { + return Result.error("未找到模板: " + code); } + return Result.OK(t); + } + + @Operation(summary = "打印模板-免密分页列表(桌面端)") + @GetMapping(value = "/anon/list") + public Result> anonList(PrintTemplate query, + @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, + @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, + HttpServletRequest req) { + QueryWrapper qw = QueryGenerator.initQueryWrapper(query, req.getParameterMap()); + qw.orderByAsc("template_code"); + Page page = new Page<>(pageNo, pageSize); + return Result.OK(service.page(page, qw)); } /** - * 若打印机声明支持 application/pdf,则通过 DocPrintJob 提交,通常比 AWT 栅格化更稳定。 + * 广播打印模板变更事件到 /topic/sync/print-templates,桌面端订阅同步刷新本地缓存。 + * 消息体格式 = MesXslStompNotifyService.publishPrintTemplateChanged 的输出, + * 内联实现避免反向依赖业务模块。 */ - private boolean tryPrintPdfBytesWithDocFlavor(PrintService printService, byte[] pdfBytes, String jobName) { - DocFlavor flavor = new DocFlavor.INPUT_STREAM("application/pdf"); - if (!printService.isDocFlavorSupported(flavor)) { - return false; - } + private void publishPrintTemplateChanged(String action, String templateId) { try { - DocPrintJob docJob = printService.createPrintJob(); - ByteArrayInputStream in = new ByteArrayInputStream(pdfBytes); - Doc doc = new SimpleDoc(in, flavor, null); - HashPrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(); - if (StringUtils.isNotBlank(jobName)) { - attrs.add(new JobName(jobName, Locale.getDefault())); - } - docJob.print(doc, attrs); - return true; - } catch (PrintException e) { - log.warn("PDF DocFlavor 直送失败,将回退为位图渲染: {} - {}", printService.getName(), e.getMessage()); - return false; + Map event = new HashMap<>(); + event.put("cmd", "PRINT_TEMPLATE_CHANGED"); + event.put("action", action); + event.put("templateId", templateId); + event.put("timestamp", System.currentTimeMillis()); + messagingTemplate.convertAndSend("/topic/sync/print-templates", JSON.toJSONString(event)); + } catch (Exception e) { + log.debug("广播 STOMP 事件失败 [PRINT_TEMPLATE_CHANGED]: {}", e.getMessage()); } } - - private static String buildPdfPrinterAbortHint(String requestedPrinterName, String resolvedPrintQueueName) { - StringBuilder sb = new StringBuilder(); - sb.append("打印任务被系统取消(PrinterAbortException)。常见原因:"); - sb.append("1) 默认或所选为「Microsoft Print to PDF」等虚拟打印机,在 Tomcat 等服务进程无交互桌面时无法弹出保存对话框,作业会被中止——请安装实体打印机并在前端指定 printerName;"); - sb.append("2) 打印机离线、队列暂停、缺纸或驱动报错;"); - sb.append("3) 运行服务的 Windows 账户无权访问打印队列。"); - if (StringUtils.isNotBlank(resolvedPrintQueueName)) { - sb.append(" 当前实际使用的打印队列: ").append(resolvedPrintQueueName.trim()).append("。"); - } - if (StringUtils.isNotBlank(requestedPrinterName) && !"__system_default__".equalsIgnoreCase(requestedPrinterName.trim())) { - sb.append(" 请求参数 printerName: ").append(requestedPrinterName.trim()).append("。"); - } - return sb.toString(); - } - - private PrintService resolvePrintService(String printerName) { - PrintService target = null; - if (StringUtils.isNotBlank(printerName) && !"__system_default__".equals(printerName)) { - PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); - if (services != null) { - for (PrintService serviceItem : services) { - if (serviceItem != null - && printerName.equalsIgnoreCase(String.valueOf(serviceItem.getName()).trim())) { - target = serviceItem; - break; - } - } - } - } - if (target == null) { - target = PrintServiceLookup.lookupDefaultPrintService(); - } - return target; - } } diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizBindPermWhitelist.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizBindPermWhitelist.java new file mode 100644 index 0000000..d8e6371 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizBindPermWhitelist.java @@ -0,0 +1,16 @@ +package org.jeecg.modules.print.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; +import lombok.Data; + +/** 业务打印绑定可选范围:白名单(sys_permission.id) */ +@Data +@TableName("print_biz_bind_perm_whitelist") +public class PrintBizBindPermWhitelist implements Serializable { + + @TableId(type = IdType.INPUT) + private String permId; +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizPermEntity.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizPermEntity.java new file mode 100644 index 0000000..aad2917 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizPermEntity.java @@ -0,0 +1,24 @@ +package org.jeecg.modules.print.entity; + +import com.baomidou.mybatisplus.annotation.FieldStrategy; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import java.io.Serializable; +import lombok.Data; + +/** 打印业务:菜单权限与实体类映射(biz_code 使用 perm_id) */ +@Data +@TableName("print_biz_perm_entity") +public class PrintBizPermEntity implements Serializable { + + @TableId(value = "perm_id", type = IdType.INPUT) + private String permId; + + /** + * 实体类全限定名;为空表示占位。ALWAYS 保证 update 时带上 entity_class(含置 null),避免仅主键导致无 SET 子句。 + */ + @TableField(updateStrategy = FieldStrategy.ALWAYS) + private String entityClass; +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizTemplateBind.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizTemplateBind.java new file mode 100644 index 0000000..e77a763 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/entity/PrintBizTemplateBind.java @@ -0,0 +1,47 @@ +package org.jeecg.modules.print.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +import org.jeecg.common.system.base.entity.JeecgEntity; + +/** + * 业务与打印模板绑定(字段映射) + */ +@Data +@EqualsAndHashCode(callSuper = true) +@Accessors(chain = true) +@JsonIgnoreProperties(ignoreUnknown = true) +@Schema(description = "业务打印模板绑定") +@TableName("print_biz_template_bind") +public class PrintBizTemplateBind extends JeecgEntity implements Serializable { + + @Schema(description = "业务编码") + @TableField("biz_code") + private String bizCode; + + @Schema(description = "业务名称") + @TableField("biz_name") + private String bizName; + + @Schema(description = "打印模板主键") + @TableField("template_id") + private String templateId; + + @Schema(description = "打印模板编码") + @TableField("template_code") + private String templateCode; + + @Schema(description = "字段映射 JSON:[{templateField,bizField}]") + @TableField("field_mapping_json") + private String fieldMappingJson; + + @Schema(description = "备注") + @TableField("remark") + private String remark; +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizBindPermWhitelistMapper.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizBindPermWhitelistMapper.java new file mode 100644 index 0000000..e0a7fec --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizBindPermWhitelistMapper.java @@ -0,0 +1,7 @@ +package org.jeecg.modules.print.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.jeecg.modules.print.entity.PrintBizBindPermWhitelist; + +/** 打印业务菜单白名单 */ +public interface PrintBizBindPermWhitelistMapper extends BaseMapper {} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizPermEntityMapper.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizPermEntityMapper.java new file mode 100644 index 0000000..eff3f4a --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizPermEntityMapper.java @@ -0,0 +1,7 @@ +package org.jeecg.modules.print.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.jeecg.modules.print.entity.PrintBizPermEntity; + +/** 菜单-实体映射 */ +public interface PrintBizPermEntityMapper extends BaseMapper {} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizTemplateBindMapper.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizTemplateBindMapper.java new file mode 100644 index 0000000..e85ce2e --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/mapper/PrintBizTemplateBindMapper.java @@ -0,0 +1,7 @@ +package org.jeecg.modules.print.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; + +/** 业务打印模板绑定 Mapper */ +public interface PrintBizTemplateBindMapper extends BaseMapper {} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizBindPermWhitelistService.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizBindPermWhitelistService.java new file mode 100644 index 0000000..d985977 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizBindPermWhitelistService.java @@ -0,0 +1,19 @@ +package org.jeecg.modules.print.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import java.util.List; +import org.jeecg.modules.print.entity.PrintBizBindPermWhitelist; +import org.jeecg.modules.print.vo.PrintBizTypeVO; + +/** 打印业务与系统菜单白名单 */ +public interface IPrintBizBindPermWhitelistService extends IService { + + /** 当前白名单中的菜单 id(空集合表示未配置,放行全部目录中的打印业务) */ + List listPermIds(); + + /** 全量替换白名单 */ + void replacePermIds(List permIds); + + /** 「新增业务打印绑定」下拉里可用的业务类型(print_biz_perm_entity + 反射字段,受白名单过滤) */ + List listBizTypesForBinding(); +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizPermEntityService.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizPermEntityService.java new file mode 100644 index 0000000..27e3ac5 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizPermEntityService.java @@ -0,0 +1,36 @@ +package org.jeecg.modules.print.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import java.util.List; +import org.jeecg.modules.print.entity.PrintBizPermEntity; +import org.jeecg.modules.print.vo.PrintBizTypeVO; + +/** 菜单与实体映射 + 反射生成业务类型 VO */ +public interface IPrintBizPermEntityService extends IService { + + PrintBizPermEntity getByPermId(String permId); + + /** 全部映射对应的业务类型(含反射字段);用于目录展示与白名单弹窗 catalog */ + List listAllBizTypeVOs(); + + /** + * 按白名单过滤:permIds 为空表示不过滤(返回全部映射);非空则仅保留 perm_id 在集合内的项。 + */ + List listBizTypeVOsFiltered(List whitelistPermIds); + + /** + * 解析单个菜单对应的业务类型:优先 print_biz_perm_entity,否则按菜单 component 推断实体类并反射字段。 + */ + PrintBizTypeVO resolveBizTypeVo(String permId); + + /** + * 将白名单勾选的菜单写入/补全 print_biz_perm_entity:已有可加载的 entity_class 不覆盖;否则按菜单 component 推断并插入或更新。 + */ + void upsertMappingsForWhitelist(List permIds); + + /** + * 启动预热:扫描数据库 sys_permission(menu_type=1 且 component 非空),用表中真实的 component / component_name 推断实体类并写入 + * print_biz_perm_entity(不覆盖已有可加载的 entity_class)。 + */ + void warmupMappingsFromSysPermissionTable(); +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizTemplateBindService.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizTemplateBindService.java new file mode 100644 index 0000000..dbfed8a --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/IPrintBizTemplateBindService.java @@ -0,0 +1,10 @@ +package org.jeecg.modules.print.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; + +/** 业务打印模板绑定 */ +public interface IPrintBizTemplateBindService extends IService { + + PrintBizTemplateBind getByBizCode(String bizCode); +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizBindPermWhitelistServiceImpl.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizBindPermWhitelistServiceImpl.java new file mode 100644 index 0000000..86e0c8f --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizBindPermWhitelistServiceImpl.java @@ -0,0 +1,67 @@ +package org.jeecg.modules.print.service.impl; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.entity.PrintBizBindPermWhitelist; +import org.jeecg.modules.print.mapper.PrintBizBindPermWhitelistMapper; +import org.jeecg.modules.print.service.IPrintBizBindPermWhitelistService; +import org.jeecg.modules.print.service.IPrintBizPermEntityService; +import org.jeecg.modules.print.vo.PrintBizTypeVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class PrintBizBindPermWhitelistServiceImpl + extends ServiceImpl + implements IPrintBizBindPermWhitelistService { + + @Autowired private IPrintBizPermEntityService printBizPermEntityService; + + @Override + public List listPermIds() { + return list().stream().map(PrintBizBindPermWhitelist::getPermId).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void replacePermIds(List permIds) { + remove( + Wrappers.lambdaQuery() + .isNotNull(PrintBizBindPermWhitelist::getPermId)); + if (permIds == null || permIds.isEmpty()) { + return; + } + Set seen = new HashSet<>(); + List batch = new ArrayList<>(); + for (String raw : permIds) { + String id = StringUtils.trimToEmpty(raw); + if (id.isEmpty() || seen.contains(id)) { + continue; + } + seen.add(id); + PrintBizBindPermWhitelist row = new PrintBizBindPermWhitelist(); + row.setPermId(id); + batch.add(row); + } + if (!batch.isEmpty()) { + // 分段写入,避免单次 SQL 包过大 + saveBatch(batch, 500); + List savedIds = + batch.stream().map(PrintBizBindPermWhitelist::getPermId).collect(Collectors.toList()); + printBizPermEntityService.upsertMappingsForWhitelist(savedIds); + } + } + + @Override + public List listBizTypesForBinding() { + List whitelist = listPermIds(); + return printBizPermEntityService.listBizTypeVOsFiltered(whitelist); + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizPermEntityServiceImpl.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizPermEntityServiceImpl.java new file mode 100644 index 0000000..9a781c9 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizPermEntityServiceImpl.java @@ -0,0 +1,341 @@ +package org.jeecg.modules.print.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.entity.PrintBizPermEntity; +import org.jeecg.modules.print.catalog.IPrintBizEntityFieldCatalogProvider; +import org.jeecg.modules.print.mapper.PrintBizPermEntityMapper; +import org.jeecg.modules.print.service.IPrintBizPermEntityService; +import org.jeecg.modules.print.util.PrintBizEntityFieldIntrospector; +import org.jeecg.modules.print.util.PrintBizMenuEntityInference; +import org.jeecg.modules.print.vo.PrintBizTypeVO; +import org.jeecg.modules.system.entity.SysPermission; +import org.jeecg.modules.system.service.ISysPermissionService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@Service +public class PrintBizPermEntityServiceImpl + extends ServiceImpl + implements IPrintBizPermEntityService { + + @Autowired private ISysPermissionService sysPermissionService; + + @Autowired(required = false) + private IPrintBizEntityFieldCatalogProvider fieldCatalogProvider; + + @Override + public PrintBizPermEntity getByPermId(String permId) { + if (StringUtils.isBlank(permId)) { + return null; + } + return getById(permId.trim()); + } + + @Override + public List listAllBizTypeVOs() { + List rows = list(); + if (rows == null || rows.isEmpty()) { + return new ArrayList<>(); + } + List permIds = new ArrayList<>(rows.size()); + for (PrintBizPermEntity row : rows) { + if (row != null && StringUtils.isNotBlank(row.getPermId())) { + permIds.add(row.getPermId().trim()); + } + } + Map permMap = loadPermissionMap(permIds); + List out = new ArrayList<>(); + try { + if (fieldCatalogProvider != null) { + fieldCatalogProvider.beginBulkLookup(permIds); + } + for (PrintBizPermEntity row : rows) { + if (row == null || StringUtils.isBlank(row.getPermId())) { + continue; + } + PrintBizTypeVO vo = buildVoForPermId(row.getPermId().trim(), row, permMap); + if (vo != null) { + out.add(vo); + } + } + } finally { + if (fieldCatalogProvider != null) { + fieldCatalogProvider.endBulkLookup(); + } + } + return out; + } + + @Override + public List listBizTypeVOsFiltered(List whitelistPermIds) { + if (whitelistPermIds == null || whitelistPermIds.isEmpty()) { + return listAllBizTypeVOs(); + } + List ids = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String raw : whitelistPermIds) { + String id = StringUtils.trimToEmpty(raw); + if (id.isEmpty() || seen.contains(id)) { + continue; + } + seen.add(id); + ids.add(id); + } + if (ids.isEmpty()) { + return new ArrayList<>(); + } + Map permMap = loadPermissionMap(ids); + Map entityMap = new HashMap<>(ids.size()); + for (PrintBizPermEntity e : listByIds(ids)) { + if (e != null && StringUtils.isNotBlank(e.getPermId())) { + entityMap.put(e.getPermId().trim(), e); + } + } + List out = new ArrayList<>(); + try { + if (fieldCatalogProvider != null) { + fieldCatalogProvider.beginBulkLookup(ids); + } + for (String id : ids) { + PrintBizTypeVO vo = buildVoForPermId(id, entityMap.get(id), permMap); + if (vo != null) { + out.add(vo); + } + } + } finally { + if (fieldCatalogProvider != null) { + fieldCatalogProvider.endBulkLookup(); + } + } + return out; + } + + @Override + public PrintBizTypeVO resolveBizTypeVo(String permId) { + return buildVoForPermId(permId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void upsertMappingsForWhitelist(List permIds) { + if (permIds == null || permIds.isEmpty()) { + return; + } + List ids = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String raw : permIds) { + String id = StringUtils.trimToEmpty(raw); + if (id.isEmpty() || seen.contains(id)) { + continue; + } + seen.add(id); + ids.add(id); + } + if (ids.isEmpty()) { + return; + } + // 批量查询,避免勾选数百条时 N 次 getById 导致超时 + Map existingMap = new HashMap<>(ids.size()); + for (PrintBizPermEntity e : listByIds(ids)) { + if (e != null && StringUtils.isNotBlank(e.getPermId())) { + existingMap.put(e.getPermId(), e); + } + } + Map permMap = new HashMap<>(ids.size()); + for (SysPermission p : sysPermissionService.listByIds(ids)) { + if (p != null && StringUtils.isNotBlank(p.getId())) { + permMap.put(p.getId(), p); + } + } + List toSave = new ArrayList<>(); + for (String id : ids) { + PrintBizPermEntity existing = existingMap.get(id); + // 已有可加载的实体类配置则保留,不再覆盖 + if (existing != null && StringUtils.isNotBlank(existing.getEntityClass())) { + Class loaded = + PrintBizEntityFieldIntrospector.tryLoadClass(existing.getEntityClass().trim()); + if (loaded != null) { + continue; + } + } + SysPermission p = permMap.get(id); + String inferred = PrintBizMenuEntityInference.inferEntityClassFqn(p); + PrintBizPermEntity row = existing != null ? existing : new PrintBizPermEntity(); + row.setPermId(id); + if (StringUtils.isNotBlank(inferred) + && PrintBizEntityFieldIntrospector.tryLoadClass(inferred) != null) { + row.setEntityClass(inferred); + } else { + // 勾选即落库(与勾选数量一致);无法推断或类不在 classpath 时占位 NULL,可手工 UPDATE + row.setEntityClass(null); + } + toSave.add(row); + } + if (!toSave.isEmpty()) { + saveOrUpdateBatch(toSave, 500); + } + } + + @Override + public void warmupMappingsFromSysPermissionTable() { + List menus = + sysPermissionService + .lambdaQuery() + .eq(SysPermission::getMenuType, 1) + .isNotNull(SysPermission::getComponent) + .list(); + if (menus == null || menus.isEmpty()) { + log.info("打印菜单-实体映射预热:无子菜单数据"); + return; + } + List ids = + menus.stream() + .map(SysPermission::getId) + .filter(StringUtils::isNotBlank) + .distinct() + .collect(Collectors.toList()); + Map existingMap = new HashMap<>(ids.size()); + for (PrintBizPermEntity e : listByIds(ids)) { + if (e != null && StringUtils.isNotBlank(e.getPermId())) { + existingMap.put(e.getPermId(), e); + } + } + List toSave = new ArrayList<>(); + for (SysPermission p : menus) { + if (p == null || StringUtils.isBlank(p.getId())) { + continue; + } + String comp = p.getComponent(); + if (StringUtils.isBlank(comp) + || comp.contains("layouts") + || comp.contains("RouteView") + || comp.contains("ParentView")) { + continue; + } + PrintBizPermEntity existing = existingMap.get(p.getId()); + if (existing != null && StringUtils.isNotBlank(existing.getEntityClass())) { + if (PrintBizEntityFieldIntrospector.tryLoadClass(existing.getEntityClass().trim()) != null) { + continue; + } + } + String inferred = PrintBizMenuEntityInference.inferEntityClassFqn(p); + if (StringUtils.isBlank(inferred) + || PrintBizEntityFieldIntrospector.tryLoadClass(inferred) == null) { + continue; + } + PrintBizPermEntity row = existing != null ? existing : new PrintBizPermEntity(); + row.setPermId(p.getId()); + row.setEntityClass(inferred); + toSave.add(row); + } + if (toSave.isEmpty()) { + log.info("打印菜单-实体映射预热:无新增可解析项"); + return; + } + saveOrUpdateBatch(toSave, 500); + log.info("打印菜单-实体映射预热完成,本次写入/更新 {} 条(数据来自 sys_permission 表中的 component/component_name)", toSave.size()); + } + + /** + * 显式表优先;否则按 SysPermission.component 推断实体类名并加载字段。 + */ + private Map loadPermissionMap(List permIds) { + if (permIds == null || permIds.isEmpty()) { + return Collections.emptyMap(); + } + List plist = sysPermissionService.listByIds(permIds); + Map map = new HashMap<>(Math.max(16, plist.size() * 2)); + for (SysPermission p : plist) { + if (p != null && StringUtils.isNotBlank(p.getId())) { + map.put(p.getId().trim(), p); + } + } + return map; + } + + private PrintBizTypeVO buildVoForPermId(String permId) { + if (StringUtils.isBlank(permId)) { + return null; + } + String id = permId.trim(); + return buildVoForPermId(id, getById(id), null); + } + + private PrintBizTypeVO buildVoForPermId( + String permId, PrintBizPermEntity row, Map permCache) { + if (StringUtils.isBlank(permId)) { + return null; + } + String id = permId.trim(); + PrintBizPermEntity rowEff = row != null ? row : getById(id); + String entityFqn = null; + if (rowEff != null && StringUtils.isNotBlank(rowEff.getEntityClass())) { + entityFqn = rowEff.getEntityClass().trim(); + } else { + SysPermission p = permCache != null ? permCache.get(id) : sysPermissionService.getById(id); + entityFqn = PrintBizMenuEntityInference.inferEntityClassFqn(p); + } + boolean catalogOk = + fieldCatalogProvider != null && fieldCatalogProvider.hasCatalogForBiz(id); + if (StringUtils.isBlank(entityFqn)) { + if (!catalogOk) { + return null; + } + entityFqn = StringUtils.trimToEmpty(fieldCatalogProvider.getEntityClassFqn(id)); + } + Class clazz = null; + if (!catalogOk) { + clazz = PrintBizEntityFieldIntrospector.tryLoadClass(entityFqn); + if (clazz == null) { + // 类不在 classpath(模块未引入)时不生成下拉项,避免空字段误导 + return null; + } + } + PrintBizTypeVO vo = new PrintBizTypeVO(); + vo.setBizCode(id); + vo.setLinkedPermissionId(id); + vo.setBizName(resolveMenuName(id, permCache)); + String desc = StringUtils.isNotBlank(entityFqn) ? entityFqn : ""; + if (StringUtils.isBlank(desc) && fieldCatalogProvider != null) { + desc = StringUtils.defaultString(fieldCatalogProvider.getEntityClassFqn(id)); + } + vo.setDescription(desc); + if (catalogOk) { + vo.setFields(fieldCatalogProvider.listMainFields(id)); + } else { + vo.setFields(PrintBizEntityFieldIntrospector.listFields(clazz)); + } + return vo; + } + + private String resolveMenuName(String permId, Map permCache) { + if (permCache != null) { + SysPermission p = permCache.get(permId); + if (p != null && StringUtils.isNotBlank(p.getName())) { + return p.getName().trim(); + } + return permId; + } + return resolveMenuName(permId); + } + + private String resolveMenuName(String permId) { + SysPermission p = sysPermissionService.getById(permId); + if (p != null && StringUtils.isNotBlank(p.getName())) { + return p.getName(); + } + return permId; + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizTemplateBindServiceImpl.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizTemplateBindServiceImpl.java new file mode 100644 index 0000000..68dd6ee --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/service/impl/PrintBizTemplateBindServiceImpl.java @@ -0,0 +1,24 @@ +package org.jeecg.modules.print.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.jeecg.modules.print.entity.PrintBizTemplateBind; +import org.jeecg.modules.print.mapper.PrintBizTemplateBindMapper; +import org.jeecg.modules.print.service.IPrintBizTemplateBindService; +import org.springframework.stereotype.Service; + +@Service +public class PrintBizTemplateBindServiceImpl extends ServiceImpl + implements IPrintBizTemplateBindService { + + @Override + public PrintBizTemplateBind getByBizCode(String bizCode) { + if (bizCode == null || bizCode.isBlank()) { + return null; + } + LambdaQueryWrapper q = new LambdaQueryWrapper<>(); + q.eq(PrintBizTemplateBind::getBizCode, bizCode.trim()); + q.last("LIMIT 1"); + return getOne(q); + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/support/PrintServerEnvironmentService.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/support/PrintServerEnvironmentService.java new file mode 100644 index 0000000..6f34893 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/support/PrintServerEnvironmentService.java @@ -0,0 +1,69 @@ +package org.jeecg.modules.print.support; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.print.PrintService; +import javax.print.PrintServiceLookup; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * 服务端打印机枚举能力(与 {@link org.jeecg.modules.print.controller.PrintTemplateController#queryPrinters} 一致)。 + */ +@Slf4j +@Service +public class PrintServerEnvironmentService { + + @Value("${print.network-printers:}") + private String networkPrinters; + + /** 与打印模板页 /print/template/queryPrinters 返回结构完全一致 */ + public Map buildPrinterQueryResult() { + Map res = new HashMap<>(8); + List serverPrinters = new ArrayList<>(); + String serverDefaultPrinter = ""; + try { + PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); + if (services != null) { + for (PrintService service : services) { + if (service != null && StringUtils.isNotBlank(service.getName())) { + serverPrinters.add(service.getName().trim()); + } + } + } + PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); + if (defaultService != null && StringUtils.isNotBlank(defaultService.getName())) { + serverDefaultPrinter = defaultService.getName().trim(); + } + } catch (Exception e) { + log.warn("查询服务器打印机失败: {}", e.getMessage()); + } + List networkPrinterList = + StringUtils.isBlank(networkPrinters) + ? new ArrayList<>() + : java.util.Arrays.stream(networkPrinters.split(",")) + .map(String::trim) + .filter(StringUtils::isNotBlank) + .distinct() + .collect(Collectors.toList()); + + Map capability = new LinkedHashMap<>(4); + capability.put("localSupported", false); + capability.put( + "localReason", "浏览器环境无法直接枚举客户端本地打印机,需要本地组件或客户端程序配合。"); + capability.put("serverSupported", true); + capability.put("networkSupported", true); + + res.put("capability", capability); + res.put("serverPrinters", serverPrinters); + res.put("serverDefaultPrinter", serverDefaultPrinter); + res.put("networkPrinters", networkPrinterList); + return res; + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/support/PrintServerPdfJobService.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/support/PrintServerPdfJobService.java new file mode 100644 index 0000000..6d173c7 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/support/PrintServerPdfJobService.java @@ -0,0 +1,170 @@ +package org.jeecg.modules.print.support; + +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterAbortException; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import java.io.ByteArrayInputStream; +import java.util.Base64; +import java.util.Locale; +import javax.print.Doc; +import javax.print.DocFlavor; +import javax.print.DocPrintJob; +import javax.print.PrintException; +import javax.print.PrintService; +import javax.print.PrintServiceLookup; +import javax.print.SimpleDoc; +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.print.attribute.standard.JobName; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.PDFRenderer; +import org.jeecg.common.api.vo.Result; +import org.springframework.stereotype.Service; + +/** + * 服务端将 PDF Base64 提交至打印队列(与打印模板 {@code /print/template/directPrintPdf} 逻辑一致)。 + */ +@Slf4j +@Service +public class PrintServerPdfJobService { + + /** + * @param templateCodeOrPrefix 用于默认作业名:{@code QH-MES-{code}.pdf} + */ + public Result submitPdfBase64( + String printerName, String pdfBase64, String fileName, String templateCodeOrPrefix) { + if (StringUtils.isBlank(pdfBase64)) { + return Result.error("pdfBase64 不能为空"); + } + String lastResolvedPrinterLabel = null; + try { + PrintService target = resolvePrintService(printerName); + if (target == null) { + return Result.error("未找到可用打印机,请检查服务器打印机配置"); + } + final String resolvedPrinterLabel = target.getName(); + lastResolvedPrinterLabel = resolvedPrinterLabel; + String base64Body = pdfBase64; + int commaIdx = pdfBase64.indexOf(","); + if (pdfBase64.startsWith("data:") && commaIdx > 0) { + base64Body = pdfBase64.substring(commaIdx + 1); + } + byte[] pdfBytes = Base64.getDecoder().decode(base64Body); + String prefix = StringUtils.isNotBlank(templateCodeOrPrefix) ? templateCodeOrPrefix.trim() : "MES"; + String printJobName = + StringUtils.isNotBlank(fileName) ? fileName : ("QH-MES-" + prefix + ".pdf"); + if (tryPrintPdfBytesWithDocFlavor(target, pdfBytes, printJobName)) { + return Result.OK("已提交PDF到服务器打印机: " + resolvedPrinterLabel); + } + try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes))) { + PDFRenderer renderer = new PDFRenderer(document); + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintService(target); + job.setJobName(printJobName); + job.setPrintable( + (graphics, pageFormat, pageIndex) -> { + if (pageIndex >= document.getNumberOfPages()) { + return Printable.NO_SUCH_PAGE; + } + BufferedImage image; + try { + image = renderer.renderImageWithDPI(pageIndex, 150); + } catch (Exception ex) { + throw new PrinterException("PDF页面渲染失败: " + ex.getMessage()); + } + Graphics2D g2 = (Graphics2D) graphics; + double imageableX = pageFormat.getImageableX(); + double imageableY = pageFormat.getImageableY(); + double imageableWidth = pageFormat.getImageableWidth(); + double imageableHeight = pageFormat.getImageableHeight(); + double scale = + Math.min(imageableWidth / image.getWidth(), imageableHeight / image.getHeight()); + int drawWidth = (int) Math.round(image.getWidth() * scale); + int drawHeight = (int) Math.round(image.getHeight() * scale); + int drawX = (int) Math.round(imageableX + (imageableWidth - drawWidth) / 2); + int drawY = (int) Math.round(imageableY + (imageableHeight - drawHeight) / 2); + g2.drawImage(image, drawX, drawY, drawWidth, drawHeight, null); + return Printable.PAGE_EXISTS; + }); + HashPrintRequestAttributeSet patts = new HashPrintRequestAttributeSet(); + patts.add(new JobName(printJobName, Locale.getDefault())); + job.print(patts); + } + return Result.OK("已提交PDF到服务器打印机: " + resolvedPrinterLabel); + } catch (PrinterAbortException e) { + log.error("PDF后端打印失败(PrinterAbortException)", e); + return Result.error(buildPdfPrinterAbortHint(printerName, lastResolvedPrinterLabel)); + } catch (Exception e) { + log.error("PDF后端打印失败", e); + return Result.error("PDF后端打印失败: " + e.getMessage()); + } + } + + public PrintService resolvePrintService(String printerName) { + PrintService target = null; + if (StringUtils.isNotBlank(printerName) && !"__system_default__".equals(printerName)) { + PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); + if (services != null) { + for (PrintService serviceItem : services) { + if (serviceItem != null + && printerName.equalsIgnoreCase(String.valueOf(serviceItem.getName()).trim())) { + target = serviceItem; + break; + } + } + } + } + if (target == null) { + target = PrintServiceLookup.lookupDefaultPrintService(); + } + return target; + } + + private boolean tryPrintPdfBytesWithDocFlavor( + PrintService printService, byte[] pdfBytes, String jobName) { + DocFlavor flavor = new DocFlavor.INPUT_STREAM("application/pdf"); + if (!printService.isDocFlavorSupported(flavor)) { + return false; + } + try { + DocPrintJob docJob = printService.createPrintJob(); + ByteArrayInputStream in = new ByteArrayInputStream(pdfBytes); + Doc doc = new SimpleDoc(in, flavor, null); + HashPrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(); + if (StringUtils.isNotBlank(jobName)) { + attrs.add(new JobName(jobName, Locale.getDefault())); + } + docJob.print(doc, attrs); + return true; + } catch (PrintException e) { + log.warn( + "PDF DocFlavor 直送失败,将回退为位图渲染: {} - {}", + printService.getName(), + e.getMessage()); + return false; + } + } + + private static String buildPdfPrinterAbortHint( + String requestedPrinterName, String resolvedPrintQueueName) { + StringBuilder sb = new StringBuilder(); + sb.append("打印任务被系统取消(PrinterAbortException)。常见原因:"); + sb.append( + "1) 默认或所选为「Microsoft Print to PDF」等虚拟打印机,在 Tomcat 等服务进程无交互桌面时无法弹出保存对话框,作业会被中止——请安装实体打印机并在前端指定 printerName;"); + sb.append("2) 打印机离线、队列暂停、缺纸或驱动报错;"); + sb.append("3) 运行服务的 Windows 账户无权访问打印队列。"); + if (StringUtils.isNotBlank(resolvedPrintQueueName)) { + sb.append(" 当前实际使用的打印队列: ").append(resolvedPrintQueueName.trim()).append("。"); + } + if (StringUtils.isNotBlank(requestedPrinterName) + && !"__system_default__".equalsIgnoreCase(requestedPrinterName.trim())) { + sb.append(" 请求参数 printerName: ").append(requestedPrinterName.trim()).append("。"); + } + return sb.toString(); + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizDataMappingUtil.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizDataMappingUtil.java new file mode 100644 index 0000000..b1a320f --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizDataMappingUtil.java @@ -0,0 +1,213 @@ +package org.jeecg.modules.print.util; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.vo.PrintTemplateFieldItemVO; + +/** 按映射规则把业务 JSON 转为模板打印数据(键为模板 bindField) */ +public final class PrintBizDataMappingUtil { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private PrintBizDataMappingUtil() {} + + public static ObjectNode mapBizToPrintData(JsonNode bizRoot, ArrayNode mappingRules) { + ObjectNode printData = MAPPER.createObjectNode(); + if (bizRoot == null || mappingRules == null) { + return printData; + } + for (JsonNode rule : mappingRules) { + if (rule == null || !rule.isObject()) { + continue; + } + String templateField = text(rule, "templateField"); + String bizField = text(rule, "bizField"); + // 仅要求模板字段名;业务字段为空表示「不参与取数」,仍向 printData 写入空字符串,避免模板占位符缺键 + if (StringUtils.isBlank(templateField)) { + continue; + } + JsonNode val; + if (StringUtils.isBlank(bizField)) { + val = MAPPER.getNodeFactory().textNode(""); + } else { + val = resolvePath(bizRoot, bizField); + } + setPath(printData, templateField, val); + } + return printData; + } + + /** + * 按模板中已声明的绑定路径({@code dataBinding.params}、画布/表格等元素的 {@code bindField},与 + * {@link PrintNativeTemplateFieldExtractor} 一致),向 printData 补齐缺失路径(空字符串)。 + * + *

避免字段映射未包含某键时 API 缺键,桌面端渲染把「设计稿占位 text」当成数据显示。 + */ + public static ObjectNode fillMissingDataBindingParamKeys(ObjectNode printData, String templateJson) { + if (printData == null) { + printData = MAPPER.createObjectNode(); + } + if (StringUtils.isBlank(templateJson)) { + return printData; + } + try { + List fields = PrintNativeTemplateFieldExtractor.extract(templateJson); + for (PrintTemplateFieldItemVO item : fields) { + if (item == null || StringUtils.isBlank(item.getBindField())) { + continue; + } + String bf = item.getBindField().trim(); + if (!hasPath(printData, bf)) { + setPath(printData, bf, MAPPER.getNodeFactory().textNode("")); + } + } + } catch (Exception ignored) { + // 模板解析异常时不阻断打印 + } + return printData; + } + + /** 判断 printData 上是否存在该点分路径(含嵌套对象) */ + private static boolean hasPath(ObjectNode root, String path) { + if (StringUtils.isBlank(path)) { + return false; + } + String[] parts = path.split("\\."); + JsonNode cur = root; + for (int i = 0; i < parts.length; i++) { + if (cur == null || !cur.isObject()) { + return false; + } + ObjectNode obj = (ObjectNode) cur; + String p = parts[i]; + if (p.isEmpty() || !obj.has(p)) { + return false; + } + if (i == parts.length - 1) { + return true; + } + cur = obj.get(p); + } + return false; + } + + private static JsonNode resolvePath(JsonNode root, String path) { + if (root == null || StringUtils.isBlank(path)) { + return null; + } + String[] parts = path.split("\\."); + JsonNode cur = root; + for (String p : parts) { + if (cur == null || p.isEmpty()) { + return null; + } + if (cur.isArray()) { + if (isNonNegativeIntString(p)) { + cur = cur.get(Integer.parseInt(p)); + } else { + JsonNode first = cur.size() > 0 ? cur.get(0) : null; + cur = first != null ? first.get(p) : null; + } + } else { + cur = cur.get(p); + } + } + return cur; + } + + /** 全数字段按数组下标解析,否则在 JSON 数组上取首行再取属性(如 lines.qty 表示第一行明细的 qty) */ + private static boolean isNonNegativeIntString(String p) { + if (p == null || p.isEmpty()) { + return false; + } + for (int i = 0; i < p.length(); i++) { + if (!Character.isDigit(p.charAt(i))) { + return false; + } + } + return true; + } + + private static void setPath(ObjectNode target, String path, JsonNode value) { + if (target == null || StringUtils.isBlank(path)) { + return; + } + String[] parts = path.split("\\."); + if (parts.length == 1) { + putLeaf(target, parts[0], value); + return; + } + ObjectNode cur = target; + for (int i = 0; i < parts.length - 1; i++) { + String p = parts[i]; + JsonNode next = cur.get(p); + if (next == null || !next.isObject()) { + ObjectNode created = MAPPER.createObjectNode(); + cur.set(p, created); + cur = created; + } else { + cur = (ObjectNode) next; + } + } + String leaf = parts[parts.length - 1]; + putLeaf(cur, leaf, value); + } + + private static void putLeaf(ObjectNode node, String key, JsonNode value) { + if (value == null || value.isNull()) { + node.putNull(key); + } else if (value.isObject() || value.isArray()) { + node.set(key, value); + } else if (value.isTextual()) { + node.put(key, value.asText()); + } else if (value.isBoolean()) { + node.put(key, value.booleanValue()); + } else if (value.isNumber()) { + node.put(key, value.doubleValue()); + } else { + node.set(key, value); + } + } + + private static String text(JsonNode n, String key) { + if (n == null || !n.isObject()) { + return ""; + } + JsonNode v = n.get(key); + return v == null || v.isNull() ? "" : v.asText(""); + } + + /** 将任意 JsonNode 转为可序列化的 JSON 树(复制) */ + public static JsonNode parseBizJson(Object bizDataJson) throws Exception { + if (bizDataJson == null) { + return MAPPER.createObjectNode(); + } + if (bizDataJson instanceof String s) { + if (StringUtils.isBlank(s)) { + return MAPPER.createObjectNode(); + } + return MAPPER.readTree(s); + } + return MAPPER.valueToTree(bizDataJson); + } + + /** 规范化映射列表:解析字符串或数组 */ + public static ArrayNode parseMappingArray(String fieldMappingJson) throws Exception { + if (StringUtils.isBlank(fieldMappingJson)) { + return MAPPER.createArrayNode(); + } + JsonNode n = MAPPER.readTree(fieldMappingJson); + if (n.isArray()) { + return (ArrayNode) n; + } + return MAPPER.createArrayNode(); + } + + public static String mappingArrayToJson(ArrayNode arr) throws Exception { + return MAPPER.writeValueAsString(arr); + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizDetailPropertyScanner.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizDetailPropertyScanner.java new file mode 100644 index 0000000..dad9c8e --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizDetailPropertyScanner.java @@ -0,0 +1,185 @@ +package org.jeecg.modules.print.util; + +import io.swagger.v3.oas.annotations.media.Schema; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.jeecgframework.poi.excel.annotation.Excel; +import org.jeecg.modules.print.vo.PrintBizDetailSlotVO; +import org.jeecg.modules.print.vo.PrintBizFieldItemVO; + +/** + * 扫描主实体类上可作为「明细」的来源属性:{@code List<Entity>} / {@code Set<Entity>} / 数组 / 嵌套业务对象。 + */ +public final class PrintBizDetailPropertyScanner { + + private PrintBizDetailPropertyScanner() {} + + /** + * 根据已选明细槽位解析元素类型:LIST 取集合元素类或数组组件类型;OBJECT 取嵌套属性类型。 + * + * @param slotKind LIST 或 OBJECT(与 {@link PrintBizDetailSlotVO#getSlotKind()} 一致) + */ + public static Class resolveItemClassForSlot( + Class mainClazz, String propertyName, String slotKind) { + if (mainClazz == null || StringUtils.isBlank(propertyName)) { + return null; + } + Field f = findDeclaredField(mainClazz, propertyName.trim()); + if (f == null) { + return null; + } + if ("OBJECT".equalsIgnoreCase(StringUtils.trimToEmpty(slotKind))) { + Class t = f.getType(); + return isLikelyBizBean(t) ? t : null; + } + Class elem = resolveCollectionElementClass(f); + if (elem != null) { + return elem; + } + if (f.getType().isArray()) { + Class comp = f.getType().getComponentType(); + return isSimpleOrJdkValueType(comp) ? null : comp; + } + return null; + } + + private static Field findDeclaredField(Class start, String name) { + Class c = start; + while (c != null && c != Object.class) { + try { + return c.getDeclaredField(name); + } catch (NoSuchFieldException ignored) { + c = c.getSuperclass(); + } + } + return null; + } + + /** 明细元素类型反射字段,fieldKey 已带「属性名.」前缀,便于与模板明细占位映射 */ + public static List listPrefixedDetailFields( + Class mainClazz, String propertyName, String slotKind) { + Class item = resolveItemClassForSlot(mainClazz, propertyName, slotKind); + if (item == null) { + return Collections.emptyList(); + } + List raw = PrintBizEntityFieldIntrospector.listFields(item); + String prefix = propertyName.trim(); + List out = new ArrayList<>(raw.size()); + for (PrintBizFieldItemVO x : raw) { + String path = prefix + "." + x.getFieldKey(); + String label = "明细「" + prefix + "」→ " + x.getLabel(); + out.add(PrintBizFieldItemVO.copyWithPrefixedPath(x, path, label)); + } + return out; + } + + public static List listSlots(Class mainClazz) { + Map ordered = new LinkedHashMap<>(); + Class c = mainClazz; + while (c != null && c != Object.class) { + for (Field f : c.getDeclaredFields()) { + int mod = f.getModifiers(); + if (Modifier.isStatic(mod) || f.isSynthetic()) { + continue; + } + String name = f.getName(); + if ("serialVersionUID".equals(name)) { + continue; + } + Class elem = resolveCollectionElementClass(f); + if (elem != null && isLikelyBizBean(elem)) { + ordered.putIfAbsent( + name, + new PrintBizDetailSlotVO(name, elem.getName(), "LIST", resolveFieldLabel(f))); + continue; + } + Class ft = f.getType(); + if (ft.isArray() && !isSimpleOrJdkValueType(ft.getComponentType())) { + Class comp = ft.getComponentType(); + ordered.putIfAbsent( + name, new PrintBizDetailSlotVO(name, comp.getName(), "LIST", resolveFieldLabel(f))); + continue; + } + if (!ft.isPrimitive() + && !ft.getName().startsWith("java.lang") + && !Number.class.isAssignableFrom(ft) + && !java.util.Date.class.isAssignableFrom(ft) + && !ft.getName().startsWith("java.time") + && !Map.class.isAssignableFrom(ft) + && !Collection.class.isAssignableFrom(ft) + && isLikelyBizBean(ft)) { + ordered.putIfAbsent( + name, new PrintBizDetailSlotVO(name, ft.getName(), "OBJECT", resolveFieldLabel(f))); + } + } + c = c.getSuperclass(); + } + return new ArrayList<>(ordered.values()); + } + + /** 解析 List<T> / Set<T> 的元素类型 T */ + private static Class resolveCollectionElementClass(Field f) { + Type gt = f.getGenericType(); + if (!(gt instanceof ParameterizedType)) { + return null; + } + ParameterizedType pt = (ParameterizedType) gt; + Type raw = pt.getRawType(); + if (!(raw instanceof Class rc) || !Collection.class.isAssignableFrom(rc)) { + return null; + } + Type[] args = pt.getActualTypeArguments(); + if (args.length != 1) { + return null; + } + Type arg0 = args[0]; + if (arg0 instanceof Class) { + Class ac = (Class) arg0; + return isSimpleOrJdkValueType(ac) ? null : ac; + } + return null; + } + + private static boolean isSimpleOrJdkValueType(Class cl) { + if (cl == null || cl.isPrimitive()) { + return true; + } + if (cl.isEnum()) { + return true; + } + String n = cl.getName(); + if (n.startsWith("java.lang") || n.startsWith("java.time")) { + return true; + } + if (Number.class.isAssignableFrom(cl) || java.util.Date.class.isAssignableFrom(cl)) { + return true; + } + return false; + } + + /** 非 JDK 简单值、非集合/Map 的自定义类型视为可映射明细实体 */ + private static boolean isLikelyBizBean(Class cl) { + return cl != null && !cl.isEnum() && !isSimpleOrJdkValueType(cl) && !Map.class.isAssignableFrom(cl); + } + + private static String resolveFieldLabel(Field f) { + Schema schema = f.getAnnotation(Schema.class); + if (schema != null && StringUtils.isNotBlank(schema.description())) { + return schema.description().trim(); + } + Excel excel = f.getAnnotation(Excel.class); + if (excel != null && StringUtils.isNotBlank(excel.name())) { + return excel.name().trim(); + } + return f.getName(); + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizEntityFieldIntrospector.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizEntityFieldIntrospector.java new file mode 100644 index 0000000..4911b65 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizEntityFieldIntrospector.java @@ -0,0 +1,237 @@ +package org.jeecg.modules.print.util; + +import io.swagger.v3.oas.annotations.media.Schema; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.vo.PrintBizFieldItemVO; +import org.jeecgframework.poi.excel.annotation.Excel; + +/** + * 从实体类反射可映射字段(供打印业务绑定下拉与映射);子类字段优先于父类同名字段。 + * + *

写入缓存 JSON 时附带 {@code javaType}、{@code jdbcType}、{@code simpleKind}。 + */ +public final class PrintBizEntityFieldIntrospector { + + private PrintBizEntityFieldIntrospector() {} + + public static List listFields(Class clazz) { + Map ordered = new LinkedHashMap<>(); + Class c = clazz; + while (c != null && c != Object.class) { + for (Field f : c.getDeclaredFields()) { + int mod = f.getModifiers(); + if (Modifier.isStatic(mod) || f.isSynthetic()) { + continue; + } + String name = f.getName(); + if ("serialVersionUID".equals(name)) { + continue; + } + PrintBizFieldItemVO vo = + new PrintBizFieldItemVO(name, resolveLabel(f), ""); + fillJavaJdbcSimple(vo, f.getType()); + ordered.putIfAbsent(name, vo); + } + c = c.getSuperclass(); + } + return new ArrayList<>(ordered.values()); + } + + /** 将反射得到的 Java 类型写成 VO 上的三类提示字段 */ + public static void fillJavaJdbcSimple(PrintBizFieldItemVO vo, Class declaredType) { + if (vo == null || declaredType == null) { + return; + } + vo.setJavaType(resolveJavaTypeFqn(declaredType)); + vo.setSimpleKind(resolveSimpleKind(declaredType)); + vo.setJdbcType(resolveJdbcTypeName(declaredType)); + } + + private static String resolveJavaTypeFqn(Class t) { + String cn = t.getCanonicalName(); + return cn != null ? cn : t.getName(); + } + + /** + * STRING / BOOLEAN / INTEGER / LONG / DECIMAL / DATE / TIME / DATETIME / ENUM / BINARY / JAVA_OBJECT / + * OTHER + */ + private static String resolveSimpleKind(Class t) { + if (t.isPrimitive()) { + if (t == boolean.class) { + return "BOOLEAN"; + } + if (t == byte.class || t == short.class || t == int.class || t == char.class) { + return "INTEGER"; + } + if (t == long.class) { + return "LONG"; + } + if (t == float.class || t == double.class) { + return "DECIMAL"; + } + return "OTHER"; + } + if (t == Boolean.class) { + return "BOOLEAN"; + } + if (t.isEnum()) { + return "ENUM"; + } + if (CharSequence.class.isAssignableFrom(t)) { + return "STRING"; + } + if (Number.class.isAssignableFrom(t)) { + if (BigDecimal.class.isAssignableFrom(t) + || Float.class.isAssignableFrom(t) + || Double.class.isAssignableFrom(t)) { + return "DECIMAL"; + } + if (BigInteger.class.isAssignableFrom(t) || Long.class.isAssignableFrom(t)) { + return "LONG"; + } + return "INTEGER"; + } + if (UUID.class.isAssignableFrom(t)) { + return "STRING"; + } + if (Date.class.isAssignableFrom(t)) { + return "DATETIME"; + } + if (LocalDate.class.isAssignableFrom(t)) { + return "DATE"; + } + if (LocalTime.class.isAssignableFrom(t)) { + return "TIME"; + } + if (LocalDateTime.class.isAssignableFrom(t) + || Instant.class.isAssignableFrom(t) + || ZonedDateTime.class.isAssignableFrom(t) + || OffsetDateTime.class.isAssignableFrom(t)) { + return "DATETIME"; + } + if (byte[].class == t) { + return "BINARY"; + } + if (t.getName().startsWith("java.") || t.getName().startsWith("javax.")) { + return "JAVA_OBJECT"; + } + return "JAVA_OBJECT"; + } + + /** + * 粗粒度 JDBC 名称(非穷尽);自定义 Bean 等返回 JAVA_OBJECT。 + */ + private static String resolveJdbcTypeName(Class t) { + if (t.isPrimitive()) { + if (t == boolean.class) { + return "BOOLEAN"; + } + if (t == byte.class) { + return "TINYINT"; + } + if (t == short.class) { + return "SMALLINT"; + } + if (t == int.class) { + return "INTEGER"; + } + if (t == long.class) { + return "BIGINT"; + } + if (t == float.class) { + return "FLOAT"; + } + if (t == double.class) { + return "DOUBLE"; + } + if (t == char.class) { + return "CHAR"; + } + return "OTHER"; + } + if (t == Boolean.class) { + return "BOOLEAN"; + } + if (t.isEnum()) { + return "VARCHAR"; + } + if (String.class == t || CharSequence.class.isAssignableFrom(t)) { + return "VARCHAR"; + } + if (UUID.class.isAssignableFrom(t)) { + return "CHAR"; + } + if (Integer.class == t || Short.class == t || Byte.class == t) { + return "INTEGER"; + } + if (Long.class == t || BigInteger.class.isAssignableFrom(t)) { + return "BIGINT"; + } + if (BigDecimal.class.isAssignableFrom(t)) { + return "DECIMAL"; + } + if (Float.class == t || Double.class == t) { + return "DOUBLE"; + } + if (Date.class.isAssignableFrom(t)) { + return "TIMESTAMP"; + } + if (LocalDate.class.isAssignableFrom(t)) { + return "DATE"; + } + if (LocalTime.class.isAssignableFrom(t)) { + return "TIME"; + } + if (LocalDateTime.class.isAssignableFrom(t) + || Instant.class.isAssignableFrom(t) + || ZonedDateTime.class.isAssignableFrom(t) + || OffsetDateTime.class.isAssignableFrom(t)) { + return "TIMESTAMP"; + } + if (byte[].class == t) { + return "BLOB"; + } + return "JAVA_OBJECT"; + } + + private static String resolveLabel(Field f) { + Schema schema = f.getAnnotation(Schema.class); + if (schema != null && StringUtils.isNotBlank(schema.description())) { + return schema.description().trim(); + } + Excel excel = f.getAnnotation(Excel.class); + if (excel != null && StringUtils.isNotBlank(excel.name())) { + return excel.name().trim(); + } + return f.getName(); + } + + /** 按全限定类名加载 Class,失败返回 null */ + public static Class tryLoadClass(String entityClassFqn) { + if (StringUtils.isBlank(entityClassFqn)) { + return null; + } + try { + return Class.forName(entityClassFqn.trim()); + } catch (Throwable e) { + return null; + } + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizMenuEntityInference.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizMenuEntityInference.java new file mode 100644 index 0000000..52d2e63 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintBizMenuEntityInference.java @@ -0,0 +1,94 @@ +package org.jeecg.modules.print.util; + +import java.util.Objects; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.system.entity.SysPermission; + +/** + * 根据菜单 component / componentName 推断实体类全名。
+ * 典型:
+ * - xslmes/mesXslWarehouseArea/MesXslWarehouseAreaList
+ * - mes/materialinfo/index + componentName=MesMaterialList → org.jeecg.modules.mes.material.entity.MesMaterial + */ +public final class PrintBizMenuEntityInference { + + /** MES 物料等菜单实体默认落在该包下(与工程 mes.material.entity 一致) */ + private static final String MES_MATERIAL_ENTITY_PKG = "org.jeecg.modules.mes.material.entity."; + + private PrintBizMenuEntityInference() {} + + /** + * @return 实体类全限定名;无法推断时返回 null(按钮、目录等) + */ + public static String inferEntityClassFqn(SysPermission permission) { + if (permission == null) { + return null; + } + if (Objects.equals(permission.getMenuType(), 2)) { + return null; + } + String comp = permission.getComponent(); + if (StringUtils.isBlank(comp)) { + return null; + } + String c = comp.trim(); + if (c.contains("layouts") + || c.contains("RouteView") + || c.contains("ParentView") + || c.startsWith("http")) { + return null; + } + + // Jeecg Vue:component 常为 mes/xxx/index,实体类名在 component_name(如 MesMaterialList) + if (c.startsWith("mes/") && c.endsWith("/index")) { + String fromMesIndex = + tryInferMesMaterialModuleFromComponentName(permission.getComponentName()); + if (StringUtils.isNotBlank(fromMesIndex)) { + return fromMesIndex; + } + } + + String[] segs = c.split("/"); + if (segs.length < 2) { + return null; + } + String last = segs[segs.length - 1]; + if (StringUtils.isBlank(last)) { + return null; + } + String simple = + last.endsWith("List") ? last.substring(0, last.length() - 4) : last; + if (simple.isEmpty()) { + return null; + } + String module = segs[0]; + if (StringUtils.isBlank(module)) { + return null; + } + String trial = "org.jeecg.modules." + module + ".entity." + simple; + if (PrintBizEntityFieldIntrospector.tryLoadClass(trial) != null) { + return trial; + } + return null; + } + + /** mes 模块下 index 路由:用 componentName(MesXxxList)推断 mes.material.entity.MesXxx */ + private static String tryInferMesMaterialModuleFromComponentName(String componentName) { + if (StringUtils.isBlank(componentName)) { + return null; + } + String cn = componentName.trim(); + if (!cn.endsWith("List")) { + return null; + } + String simple = cn.substring(0, cn.length() - 4); + if (simple.isEmpty()) { + return null; + } + String trial = MES_MATERIAL_ENTITY_PKG + simple; + if (PrintBizEntityFieldIntrospector.tryLoadClass(trial) != null) { + return trial; + } + return null; + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintNativeTemplateFieldExtractor.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintNativeTemplateFieldExtractor.java new file mode 100644 index 0000000..3ff9035 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/util/PrintNativeTemplateFieldExtractor.java @@ -0,0 +1,141 @@ +package org.jeecg.modules.print.util; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.apache.commons.lang3.StringUtils; +import org.jeecg.modules.print.vo.PrintTemplateFieldItemVO; + +/** + * 从原生打印模板 JSON 中收集所有 bindField / 表格列 field,供业务字段映射使用。 + * + *

原生设计器在 {@code dataBinding.params} 中维护「参数」列表(如 Parameter1~Parameter10),画布元素通过 + * bindField 引用这些 key;仅扫描 elements 会漏掉未拖放到画布上的参数,故必须先合并 dataBinding。 + */ +public final class PrintNativeTemplateFieldExtractor { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private PrintNativeTemplateFieldExtractor() {} + + public static List extract(String templateJson) { + List list = new ArrayList<>(); + if (StringUtils.isBlank(templateJson)) { + return list; + } + Set seen = new LinkedHashSet<>(); + try { + JsonNode root = MAPPER.readTree(templateJson); + // 优先收录设计器「参数/明细字段」目录,保证显示名与组件库一致,且不被后续元素扫描覆盖 + collectDataBinding(root, seen, list); + JsonNode elements = root.get("elements"); + if (elements != null && elements.isArray()) { + for (JsonNode el : elements) { + collectFromElement(el, seen, list); + } + } + } catch (Exception ignored) { + return list; + } + return list; + } + + /** 解析 schema.dataBinding:params(参数键)、detailTables(明细字段) */ + private static void collectDataBinding(JsonNode root, Set seen, List list) { + JsonNode db = root.get("dataBinding"); + if (db == null || !db.isObject()) { + return; + } + JsonNode params = db.get("params"); + if (params != null && params.isArray()) { + for (JsonNode p : params) { + if (p == null || !p.isObject()) { + continue; + } + String key = text(p, "key").trim(); + if (StringUtils.isBlank(key) || !seen.add(key)) { + continue; + } + list.add(new PrintTemplateFieldItemVO(key, "param", text(p, "label"))); + } + } + JsonNode detailTables = db.get("detailTables"); + if (detailTables != null && detailTables.isArray()) { + for (JsonNode t : detailTables) { + if (t == null || !t.isObject()) { + continue; + } + String tableKey = text(t, "tableKey").trim(); + JsonNode fields = t.get("fields"); + if (fields == null || !fields.isArray()) { + continue; + } + for (JsonNode f : fields) { + if (f == null || !f.isObject()) { + continue; + } + String fk = text(f, "key").trim(); + if (StringUtils.isBlank(fk)) { + continue; + } + // 与画布列 bindField 一致时多为短 key;多表明细同字段再加 tableKey 前缀消歧 + String bindKey = fk; + if (seen.contains(bindKey) && StringUtils.isNotBlank(tableKey)) { + bindKey = tableKey + "." + fk; + } + if (seen.contains(bindKey) || !seen.add(bindKey)) { + continue; + } + list.add(new PrintTemplateFieldItemVO(bindKey, "detailField", text(f, "label"))); + } + } + } + } + + private static void collectFromElement(JsonNode el, Set seen, List list) { + if (el == null || !el.isObject()) { + return; + } + String bindField = text(el, "bindField"); + if (StringUtils.isNotBlank(bindField) && seen.add(bindField.trim())) { + list.add( + new PrintTemplateFieldItemVO( + bindField.trim(), + text(el, "type"), + firstNonBlank(text(el, "title"), text(el, "text")))); + } + JsonNode cols = el.get("columns"); + if (cols != null && cols.isArray()) { + for (JsonNode c : cols) { + String field = firstNonBlank(text(c, "bindField"), text(c, "field")); + if (StringUtils.isNotBlank(field) && seen.add(field.trim())) { + list.add(new PrintTemplateFieldItemVO(field.trim(), "column", text(c, "title"))); + } + } + } + JsonNode nested = el.get("elements"); + if (nested != null && nested.isArray()) { + for (JsonNode child : nested) { + collectFromElement(child, seen, list); + } + } + } + + private static String text(JsonNode n, String key) { + if (n == null || !n.isObject()) { + return ""; + } + JsonNode v = n.get(key); + return v == null || v.isNull() ? "" : v.asText(""); + } + + private static String firstNonBlank(String a, String b) { + if (StringUtils.isNotBlank(a)) { + return a; + } + return StringUtils.isNotBlank(b) ? b : ""; + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizDetailSlotVO.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizDetailSlotVO.java new file mode 100644 index 0000000..8de95ab --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizDetailSlotVO.java @@ -0,0 +1,27 @@ +package org.jeecg.modules.print.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** 主实体上可作为「明细数据来源」的属性(集合元素类型或嵌套对象类型) */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Schema(description = "业务实体明细槽位") +public class PrintBizDetailSlotVO implements Serializable { + + @Schema(description = "Java 属性名(JSON 路径前缀,如 lines、headerExt)") + private String propertyName; + + @Schema(description = "明细元素类型全限定名") + private String itemEntityClassFqn; + + @Schema(description = "LIST=集合明细一行映射;OBJECT=嵌套对象字段映射") + private String slotKind; + + @Schema(description = "展示名") + private String label; +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizFieldItemVO.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizFieldItemVO.java new file mode 100644 index 0000000..c7db51e --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizFieldItemVO.java @@ -0,0 +1,68 @@ +package org.jeecg.modules.print.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@Schema(description = "业务实体可选字段") +public class PrintBizFieldItemVO implements Serializable { + + @Schema(description = "字段路径(支持 a.b,与 JSON 一致)") + private String fieldKey; + + @Schema(description = "展示名称") + private String label; + + @Schema(description = "说明") + private String description; + + /** 声明类型全限定名(如 java.lang.String、java.time.LocalDateTime) */ + @Schema(description = "Java 声明类型全限定名") + private String javaType; + + /** + * 与 JDBC 习惯对齐的类型名(如 VARCHAR、BIGINT、DECIMAL、TIMESTAMP);非 JDBC 标量填 JAVA_OBJECT。 + */ + @Schema(description = "粗粒度 JDBC 风格类型名") + private String jdbcType; + + /** + * 粗分类:STRING、BOOLEAN、INTEGER、LONG、DECIMAL、DATE、TIME、DATETIME、ENUM、BINARY、OTHER、JAVA_OBJECT + */ + @Schema(description = "简化种类,便于前端格式化") + private String simpleKind; + + /** 兼容旧三参构造(类型字段为空) */ + public PrintBizFieldItemVO(String fieldKey, String label, String description) { + this.fieldKey = fieldKey; + this.label = label; + this.description = description == null ? "" : description; + } + + /** 复制前缀明细字段时保留类型元数据 */ + public static PrintBizFieldItemVO copyWithPrefixedPath( + PrintBizFieldItemVO src, String prefixedFieldKey, String prefixedLabel) { + PrintBizFieldItemVO o = new PrintBizFieldItemVO(); + o.setFieldKey(prefixedFieldKey); + o.setLabel(prefixedLabel); + o.setDescription(src != null ? src.getDescription() : ""); + if (src != null) { + o.setJavaType(src.getJavaType()); + o.setJdbcType(src.getJdbcType()); + o.setSimpleKind(src.getSimpleKind()); + } + return o; + } + + /** 仅占位字符串数组解析出来的单项(视为字符串) */ + public static PrintBizFieldItemVO plainStringField(String fieldKey) { + PrintBizFieldItemVO o = new PrintBizFieldItemVO(fieldKey, fieldKey, ""); + o.setJavaType(String.class.getName()); + o.setJdbcType("VARCHAR"); + o.setSimpleKind("STRING"); + return o; + } +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizTypeVO.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizTypeVO.java new file mode 100644 index 0000000..9804e3c --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintBizTypeVO.java @@ -0,0 +1,29 @@ +package org.jeecg.modules.print.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import java.util.List; +import lombok.Data; + +@Data +@Schema(description = "可配置的业务类型") +public class PrintBizTypeVO implements Serializable { + @Schema(description = "业务编码(与菜单权限 id、绑定表 biz_code 一致)") + private String bizCode; + + @Schema(description = "业务名称") + private String bizName; + + @Schema(description = "说明") + private String description; + + /** + * 与「系统菜单」中的菜单主键(sys_permission.id)对应;用于「打印业务白名单」按菜单勾选。 + * 未设置表示未挂菜单,白名单生效时仍可出现于下拉(避免仅后端注册、尚未配菜单的业务被误过滤)。 + */ + @Schema(description = "关联菜单权限ID(sys_permission.id)") + private String linkedPermissionId; + + @Schema(description = "业务侧可用字段目录") + private List fields; +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintTemplateFieldItemVO.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintTemplateFieldItemVO.java new file mode 100644 index 0000000..8f14291 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/print/vo/PrintTemplateFieldItemVO.java @@ -0,0 +1,22 @@ +package org.jeecg.modules.print.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Schema(description = "模板中的数据占位字段") +public class PrintTemplateFieldItemVO implements Serializable { + @Schema(description = "模板 bindField 路径") + private String bindField; + + @Schema(description = "元素类型") + private String elementType; + + @Schema(description = "元素标题/提示") + private String titleHint; +} diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysCategoryController.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysCategoryController.java index c93e5b2..5961764 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysCategoryController.java +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/controller/SysCategoryController.java @@ -416,13 +416,7 @@ public class SysCategoryController { * 递归求子节点 同步加载用到 */ private void loadAllCategoryChildren(List ls) { - for (TreeSelectModel tsm : ls) { - List temp = this.sysCategoryService.queryListByPid(tsm.getKey()); - if(temp!=null && temp.size()>0) { - tsm.setChildren(temp); - loadAllCategoryChildren(temp); - } - } + this.sysCategoryService.fillCategoryChildrenBatch(ls); } /** diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/SysCategoryMapper.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/SysCategoryMapper.java index 208ba7e..c676b39 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/SysCategoryMapper.java +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/SysCategoryMapper.java @@ -28,6 +28,11 @@ public interface SysCategoryMapper extends BaseMapper { */ public List queryListByPid(@Param("pid") String pid,@Param("query") Map query); + /** + * 批量按父 id 查询子节点(树同步加载按层拉取,避免 N+1) + */ + List queryListByPidIn(@Param("pids") List pids, @Param("query") Map query); + /** * 通过code查询分类字典表 * @param code diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/xml/SysCategoryMapper.xml b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/xml/SysCategoryMapper.xml index 741670c..6c32069 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/xml/SysCategoryMapper.xml +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/mapper/xml/SysCategoryMapper.xml @@ -33,5 +33,36 @@ + + diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/ISysCategoryService.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/ISysCategoryService.java index 607d2c5..652f672 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/ISysCategoryService.java +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/ISysCategoryService.java @@ -98,4 +98,11 @@ public interface ISysCategoryService extends IService { */ List loadDictItemByNames(String names, boolean delNotExist); + /** + * 按层批量补全子节点(替代逐节点递归 queryListByPid,显著减少数据库往返) + * + * @param nodes 首层节点列表(通常来自 {@link #queryListByCode}) + */ + void fillCategoryChildrenBatch(List nodes); + } diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysCategoryServiceImpl.java b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysCategoryServiceImpl.java index cff09f8..5410273 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysCategoryServiceImpl.java +++ b/jeecg-boot/jeecg-module-system/jeecg-system-biz/src/main/java/org/jeecg/modules/system/service/impl/SysCategoryServiceImpl.java @@ -126,6 +126,37 @@ public class SysCategoryServiceImpl extends ServiceImpl nodes) { + if (nodes == null || nodes.isEmpty()) { + return; + } + List frontier = new ArrayList<>(nodes); + while (!frontier.isEmpty()) { + List pids = frontier.stream().map(TreeSelectModel::getKey).filter(Objects::nonNull).collect(Collectors.toList()); + if (pids.isEmpty()) { + break; + } + List allChildren = baseMapper.queryListByPidIn(pids, null); + if (allChildren == null || allChildren.isEmpty()) { + break; + } + Map> byParent = allChildren.stream().collect(Collectors.groupingBy(TreeSelectModel::getParentId)); + List nextFrontier = new ArrayList<>(); + for (TreeSelectModel parent : frontier) { + List ch = byParent.get(parent.getKey()); + if (ch != null && !ch.isEmpty()) { + parent.setChildren(ch); + nextFrontier.addAll(ch); + } + } + if (nextFrontier.isEmpty()) { + break; + } + frontier = nextFrontier; + } + } + @Override public String queryIdByCode(String code) { return baseMapper.queryIdByCode(code); diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/JeecgSystemApplication.java b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/JeecgSystemApplication.java index 2d70dab..fa5e6a5 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/JeecgSystemApplication.java +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/JeecgSystemApplication.java @@ -48,6 +48,7 @@ public class JeecgSystemApplication extends SpringBootServletInitializer { String port = env.getProperty("server.port"); String path = oConvertUtils.getString(env.getProperty("server.servlet.context-path")); log.info("\n----------------------------------------------------------\n\t" + + "Application Jeecg-Boot is running! Access URLs:\n\t" + "Local: \t\thttp://localhost:" + port + path + "\n\t" + "External: \thttp://" + ip + ":" + port + path + "/doc.html\n\t" + diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application.yml b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application.yml index 92b9835..ffd8030 100644 --- a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application.yml +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application.yml @@ -2,6 +2,8 @@ spring: application: name: jeecg-system config: - import: optional:classpath:config/application-liteflow.yml + import: + - optional:classpath:config/application-liteflow.yml + - optional:classpath:config/application-xslmes-warehouse-area.yml profiles: active: '@profile.name@' \ No newline at end of file diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/config/application-xslmes-warehouse-area.yml b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/config/application-xslmes-warehouse-area.yml new file mode 100644 index 0000000..cfc9656 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/config/application-xslmes-warehouse-area.yml @@ -0,0 +1,11 @@ +# MES XSL — 库区「实际存放量」展示回填(不写库,可覆盖) +xslmes: + warehouse-area: + display-actual-capacity: + enabled: true + # 按「原材料库」分类编码解析 sys_category.id(推荐;业务树已无楼层语义,编码中 F1/F2 后缀若变化请改此处) + raw-material-warehouse-category-codes: + - XSLMES_WH_F1_YCL + - XSLMES_WH_F2_YCL + # 可选:直接写 warehouse_category=id,与上面的编码解析结果合并 + raw-material-warehouse-category-ids: [] diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_50__print_biz_template_bind.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_50__print_biz_template_bind.sql new file mode 100644 index 0000000..793bc49 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_50__print_biz_template_bind.sql @@ -0,0 +1,43 @@ +-- 业务与打印模板绑定(字段映射可视化配置) +CREATE TABLE IF NOT EXISTS `print_biz_template_bind` ( + `id` varchar(36) NOT NULL COMMENT '主键', + `biz_code` varchar(64) NOT NULL COMMENT '业务编码(如 MES_RAW_MATERIAL_CARD)', + `biz_name` varchar(128) DEFAULT NULL COMMENT '业务名称(冗余展示)', + `template_id` varchar(36) NOT NULL COMMENT '打印模板主键', + `template_code` varchar(64) NOT NULL COMMENT '打印模板编码(冗余,便于调用方查询)', + `field_mapping_json` longtext COMMENT '字段映射 JSON:[{templateField,bizField}],templateField 对应模板 bindField', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `create_by` varchar(50) DEFAULT NULL COMMENT '创建人', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + `update_by` varchar(50) DEFAULT NULL COMMENT '更新人', + `update_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_print_biz_template_bind_biz` (`biz_code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='业务打印模板绑定'; + +-- 菜单:打印管理下「业务打印绑定」 +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000120', '1900000000000000100', '业务打印绑定', '/print/bizTemplateBind', 'print/bizTemplateBind/index', 1, 'PrintBizTemplateBind', NULL, 1, NULL, '0', 3.00, 0, 'ant-design:link-outlined', 1, 1, 0, 0, '业务与打印模板、字段映射配置', 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000120'); + +-- 按钮权限 +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000121', '1900000000000000120', '业务打印绑定-查询', NULL, NULL, 0, NULL, NULL, 2, 'print:bizBind:list', '1', 1.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000121'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000122', '1900000000000000120', '业务打印绑定-添加', NULL, NULL, 0, NULL, NULL, 2, 'print:bizBind:add', '1', 2.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000122'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000123', '1900000000000000120', '业务打印绑定-编辑', NULL, NULL, 0, NULL, NULL, 2, 'print:bizBind:edit', '1', 3.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000123'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000124', '1900000000000000120', '业务打印绑定-删除', NULL, NULL, 0, NULL, NULL, 2, 'print:bizBind:delete', '1', 4.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000124'); diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_51__print_biz_bind_perm_whitelist.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_51__print_biz_bind_perm_whitelist.sql new file mode 100644 index 0000000..1e7c40e --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_51__print_biz_bind_perm_whitelist.sql @@ -0,0 +1,11 @@ +-- 打印业务可选范围:白名单(勾选 sys_permission.id,对应 PrintBizTypeCatalog 中 linkedPermissionId) +CREATE TABLE IF NOT EXISTS `print_biz_bind_perm_whitelist` ( + `perm_id` varchar(36) NOT NULL COMMENT 'sys_permission 主键(菜单/功能)', + PRIMARY KEY (`perm_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='业务打印绑定-可选业务白名单(权限菜单)'; + +-- 按钮:打印业务白名单 +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000125', '1900000000000000120', '打印业务白名单', NULL, NULL, 0, NULL, NULL, 2, 'print:bizBind:whitelist', '1', 5.00, 0, NULL, 1, 0, 0, 0, '配置哪些菜单关联的打印业务可出现在「新增业务打印绑定」中', 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000125'); diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_52__print_biz_perm_entity.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_52__print_biz_perm_entity.sql new file mode 100644 index 0000000..649e40d --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_52__print_biz_perm_entity.sql @@ -0,0 +1,17 @@ +-- 菜单权限与打印业务实体类映射(biz_code / 绑定表业务编码 = perm_id) +CREATE TABLE IF NOT EXISTS `print_biz_perm_entity` ( + `perm_id` varchar(36) NOT NULL COMMENT 'sys_permission.id', + `entity_class` varchar(512) NOT NULL COMMENT '实体类全限定名(用于反射字段)', + PRIMARY KEY (`perm_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='打印业务-菜单与实体映射'; + +-- 原材料卡片菜单 -> MesXslRawMaterialCard +INSERT INTO `print_biz_perm_entity` (`perm_id`, `entity_class`) +SELECT '1900000000000000540', 'org.jeecg.modules.xslmes.entity.MesXslRawMaterialCard' +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM `print_biz_perm_entity` WHERE `perm_id` = '1900000000000000540'); + +-- 历史绑定:业务编码由语义码改为菜单 id(与白名单、映射表一致) +UPDATE `print_biz_template_bind` +SET `biz_code` = '1900000000000000540' +WHERE `biz_code` = 'MES_RAW_MATERIAL_CARD'; diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_53__print_biz_perm_entity_nullable_entity.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_53__print_biz_perm_entity_nullable_entity.sql new file mode 100644 index 0000000..ef93f7c --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_53__print_biz_perm_entity_nullable_entity.sql @@ -0,0 +1,3 @@ +-- 允许 entity_class 为空:白名单勾选的菜单优先落库占位,无法按 component 推断时再手工补全 +ALTER TABLE `print_biz_perm_entity` + MODIFY COLUMN `entity_class` varchar(512) NULL COMMENT '实体类全限定名;为空表示仅勾选占位,需手工配置或菜单不符合推断规则'; diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_54__mes_xsl_biz_entity_field_catalog.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_54__mes_xsl_biz_entity_field_catalog.sql new file mode 100644 index 0000000..02c8a06 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_54__mes_xsl_biz_entity_field_catalog.sql @@ -0,0 +1,35 @@ +-- 业务实体字段缓存表:供「业务打印绑定」下拉读取;数据由启动任务根据 print_biz_perm_entity 异步扫描写入 + +CREATE TABLE IF NOT EXISTS `mes_xsl_biz_entity_field_profile` ( + `id` varchar(32) NOT NULL COMMENT '主键', + `business_name` varchar(200) NOT NULL COMMENT '业务名称', + `business_code` varchar(64) NOT NULL COMMENT '业务编码(菜单 permission id,与 print 绑定 biz_code 一致)', + `entity_class_name` varchar(512) DEFAULT NULL COMMENT '主实体 Java 全限定类名', + `main_fields_json` text COMMENT '主表字段列表 JSON(PrintBizFieldItemVO 数组)', + `remark` varchar(500) DEFAULT NULL COMMENT '备注', + `tenant_id` int DEFAULT NULL COMMENT '租户ID', + `create_by` varchar(32) DEFAULT NULL COMMENT '创建人', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + `update_by` varchar(32) DEFAULT NULL COMMENT '更新人', + `update_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_mxbefp_bcode` (`business_code`), + KEY `idx_mxbefp_tenant` (`tenant_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES业务实体字段配置-主表'; + +CREATE TABLE IF NOT EXISTS `mes_xsl_biz_entity_field_detail` ( + `id` varchar(32) NOT NULL COMMENT '主键', + `profile_id` varchar(32) NOT NULL COMMENT '主表ID', + `detail_property_name` varchar(128) DEFAULT NULL COMMENT '主实体明细属性名(如 lines,与打印绑定 detailProperty 一致)', + `detail_slot_kind` varchar(16) DEFAULT NULL COMMENT 'LIST 或 OBJECT', + `detail_name` varchar(200) DEFAULT NULL COMMENT '明细展示名称', + `detail_entity_class_name` varchar(512) DEFAULT NULL COMMENT '明细元素类型全限定名', + `detail_fields_json` text COMMENT '明细元素类字段列表 JSON(无前缀,PrintBizFieldItemVO 数组)', + `sort_no` int DEFAULT NULL COMMENT '排序号', + `create_by` varchar(32) DEFAULT NULL COMMENT '创建人', + `create_time` datetime DEFAULT NULL COMMENT '创建时间', + `update_by` varchar(32) DEFAULT NULL COMMENT '更新人', + `update_time` datetime DEFAULT NULL COMMENT '更新时间', + PRIMARY KEY (`id`), + KEY `idx_mxbefd_profile` (`profile_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES业务实体字段配置-明细槽位字段清单'; diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_55__mes_xsl_biz_entity_field_detail_slot_columns.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_55__mes_xsl_biz_entity_field_detail_slot_columns.sql new file mode 100644 index 0000000..50a06e0 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_55__mes_xsl_biz_entity_field_detail_slot_columns.sql @@ -0,0 +1,25 @@ +-- 旧库升级:明细表若早于完整脚本创建,可能缺少 detail_property_name / detail_slot_kind(兼容 MySQL 5.7+) + +SELECT COUNT(*) INTO @jeecg_chk_dpn FROM information_schema.COLUMNS +WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'mes_xsl_biz_entity_field_detail' + AND COLUMN_NAME = 'detail_property_name'; + +SET @jeecg_sql_dpn := IF(@jeecg_chk_dpn = 0, + 'ALTER TABLE mes_xsl_biz_entity_field_detail ADD COLUMN detail_property_name varchar(128) DEFAULT NULL COMMENT ''主实体明细属性名(与打印绑定 detailProperty 一致)'' AFTER profile_id', + 'SELECT 1'); +PREPARE jeecg_stmt_dpn FROM @jeecg_sql_dpn; +EXECUTE jeecg_stmt_dpn; +DEALLOCATE PREPARE jeecg_stmt_dpn; + +SELECT COUNT(*) INTO @jeecg_chk_dsk FROM information_schema.COLUMNS +WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'mes_xsl_biz_entity_field_detail' + AND COLUMN_NAME = 'detail_slot_kind'; + +SET @jeecg_sql_dsk := IF(@jeecg_chk_dsk = 0, + 'ALTER TABLE mes_xsl_biz_entity_field_detail ADD COLUMN detail_slot_kind varchar(16) DEFAULT NULL COMMENT ''LIST 或 OBJECT'' AFTER detail_property_name', + 'SELECT 1'); +PREPARE jeecg_stmt_dsk FROM @jeecg_sql_dsk; +EXECUTE jeecg_stmt_dsk; +DEALLOCATE PREPARE jeecg_stmt_dsk; diff --git a/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_56__mes_xsl_raw_material_warehouse_board.sql b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_56__mes_xsl_raw_material_warehouse_board.sql new file mode 100644 index 0000000..8f226b9 --- /dev/null +++ b/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/flyway/sql/mysql/V3.9.2_56__mes_xsl_raw_material_warehouse_board.sql @@ -0,0 +1,19 @@ +-- 原材料库区看板:菜单与查询权限(父菜单 MES XSL 1900000000000000300) + +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000580', '1900000000000000300', '原材料库区看板', '/xslmes/mesXslRawMaterialWarehouseBoard', 'xslmes/mesXslRawMaterialWarehouseBoard/MesXslRawMaterialWarehouseBoard', 1, NULL, NULL, 1, NULL, '0', 12.50, 0, 'ant-design:layout-outlined', 0, 1, 0, 0, '按库区聚合展示原材料卡片库存', 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000580'); + +INSERT INTO `sys_permission` (`id`, `parent_id`, `name`, `url`, `component`, `is_route`, `component_name`, `redirect`, `menu_type`, `perms`, `perms_type`, `sort_no`, `always_show`, `icon`, `is_leaf`, `keep_alive`, `hidden`, `hide_tab`, `description`, `create_by`, `create_time`, `update_by`, `update_time`, `del_flag`, `rule_flag`, `status`, `internal_or_external`) +SELECT '1900000000000000581', '1900000000000000580', '查询', NULL, NULL, 0, NULL, NULL, 2, 'xslmes:mes_xsl_raw_material_warehouse_board:list', '1', 1.00, 0, NULL, 1, 0, 0, 0, NULL, 'admin', NOW(), 'admin', NOW(), 0, 0, '1', 0 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = '1900000000000000581'); + +INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`) +SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000580', NULL, NOW(), '127.0.0.1' +FROM `sys_role` r WHERE r.`role_code` = 'admin' + AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000580'); + +INSERT INTO `sys_role_permission` (`id`, `role_id`, `permission_id`, `data_rule_ids`, `operate_date`, `operate_ip`) +SELECT REPLACE(UUID(), '-', ''), r.id, '1900000000000000581', NULL, NOW(), '127.0.0.1' +FROM `sys_role` r WHERE r.`role_code` = 'admin' + AND NOT EXISTS (SELECT 1 FROM `sys_role_permission` rp WHERE rp.`role_id` = r.id AND rp.`permission_id` = '1900000000000000581'); diff --git a/jeecgboot-vue3/src/views/mes/material/MesMixerMaterialList.vue b/jeecgboot-vue3/src/views/mes/material/MesMixerMaterialList.vue index 26edd29..06bb3b0 100644 --- a/jeecgboot-vue3/src/views/mes/material/MesMixerMaterialList.vue +++ b/jeecgboot-vue3/src/views/mes/material/MesMixerMaterialList.vue @@ -114,6 +114,8 @@ const { tableContext, onExportXls, onImportXls } = useListPage({ title: '密炼物料信息', api: list, columns, + // 避免:表格默认 immediate 请求一次 + onMounted 末尾 reload 再请求一次(进入页列表闪两次) + immediate: false, canResize: true, formConfig: { labelWidth: 120, schemas: searchFormSchema, autoSubmitOnEnter: true, showAdvancedButton: true }, actionColumn: { width: 120 }, @@ -227,9 +229,8 @@ function findNodeByKey(nodes: Recordable[], key: string): Recordable | null { async function loadCategoryTree() { treeLoading.value = true; try { - const root = await fetchMaterialCategoryRoot(); + const [root, res] = await Promise.all([fetchMaterialCategoryRoot(), loadCategoryTreeRoot({ async: false, pcode: 'XSLMES_MATERIAL' })]); materialCategoryRootId.value = root?.id != null ? String(root.id) : ''; - const res = await loadCategoryTreeRoot({ async: false, pcode: 'XSLMES_MATERIAL' }); rawCategoryTree.value = Array.isArray(res) ? res : []; if (!materialCategoryRootId.value || !rawCategoryTree.value.length) { createMessage.warning('未加载到物料分类树,请确认分类字典根编码 XSLMES_MATERIAL 已存在。'); diff --git a/jeecgboot-vue3/src/views/print/bizTemplateBind/bizTemplateBind.api.ts b/jeecgboot-vue3/src/views/print/bizTemplateBind/bizTemplateBind.api.ts new file mode 100644 index 0000000..e05227c --- /dev/null +++ b/jeecgboot-vue3/src/views/print/bizTemplateBind/bizTemplateBind.api.ts @@ -0,0 +1,59 @@ +import { defHttp } from '/@/utils/http/axios'; + +enum Api { + list = '/print/bizTemplateBind/list', + add = '/print/bizTemplateBind/add', + edit = '/print/bizTemplateBind/edit', + deleteOne = '/print/bizTemplateBind/delete', + bizTypes = '/print/bizTemplateBind/bizTypes', + bizTypesForBinding = '/print/bizTemplateBind/bizTypesForBinding', + permWhitelist = '/print/bizTemplateBind/permWhitelist', + parseTemplateFields = '/print/bizTemplateBind/parseTemplateFields', + previewMappedData = '/print/bizTemplateBind/previewMappedData', + detailSlots = '/print/bizTemplateBind/detailSlots', + bizFieldsForDetailSlot = '/print/bizTemplateBind/bizFieldsForDetailSlot', +} + +export const list = (params) => defHttp.get({ url: Api.list, params }); +// 与系统其它模块一致:body 走 params 键 +export const add = (params) => defHttp.post({ url: Api.add, params }); +export const edit = (params) => defHttp.put({ url: Api.edit, params }); +export const deleteOne = (params, handleSuccess?) => + defHttp.delete({ url: Api.deleteOne, params }, { joinParamsToUrl: true }).then(() => handleSuccess?.()); + +export const bizTypes = () => defHttp.get({ url: Api.bizTypes }); +/** 新增/编辑绑定时可选业务(受打印业务白名单过滤);后端批量查缓存与菜单,数据多时延长超时 */ +export const bizTypesForBinding = () => + defHttp.get({ url: Api.bizTypesForBinding, timeout: 120000 }); +/** 白名单:已勾选菜单 id + 完整业务目录 */ +export const getPermWhitelist = () => defHttp.get({ url: Api.permWhitelist }); +/** 勾选菜单多时后端需批量 upsert,默认 10s 易超时 */ +export const savePermWhitelist = (data: { permIds: string[] }) => + defHttp.post({ url: Api.permWhitelist, data, timeout: 3 * 60 * 1000 }); +export const parseTemplateFields = (templateId: string) => + defHttp.get({ + url: Api.parseTemplateFields, + params: { templateId, _t: Date.now() }, + }); + +/** 预览映射后的打印数据 */ +export const previewMappedData = (data: { bizCode: string; bizDataJson: Record }) => + defHttp.post({ url: Api.previewMappedData, data }); + +/** 主实体上可作为明细的数据属性(List/数组/嵌套对象) */ +export const detailSlots = (bizCode: string) => + defHttp.get<{ propertyName: string; itemEntityClassFqn: string; slotKind: string; label: string }[]>({ + url: Api.detailSlots, + params: { bizCode }, + }); + +/** 反射明细元素类字段,fieldKey 已带「属性名.」前缀 */ +export const bizFieldsForDetailSlot = (params: { + bizCode: string; + detailProperty: string; + slotKind?: string; +}) => + defHttp.get<{ fieldKey: string; label: string; description?: string }[]>({ + url: Api.bizFieldsForDetailSlot, + params, + }); diff --git a/jeecgboot-vue3/src/views/print/bizTemplateBind/bizTemplateBind.data.ts b/jeecgboot-vue3/src/views/print/bizTemplateBind/bizTemplateBind.data.ts new file mode 100644 index 0000000..d18ed58 --- /dev/null +++ b/jeecgboot-vue3/src/views/print/bizTemplateBind/bizTemplateBind.data.ts @@ -0,0 +1,8 @@ +import type { BasicColumn } from '/@/components/Table'; + +export const columns: BasicColumn[] = [ + { title: '业务编码', dataIndex: 'bizCode', width: 200 }, + { title: '业务名称', dataIndex: 'bizName', width: 140 }, + { title: '模板编码', dataIndex: 'templateCode', width: 180 }, + { title: '备注', dataIndex: 'remark', ellipsis: true }, +]; diff --git a/jeecgboot-vue3/src/views/print/bizTemplateBind/index.vue b/jeecgboot-vue3/src/views/print/bizTemplateBind/index.vue new file mode 100644 index 0000000..237682a --- /dev/null +++ b/jeecgboot-vue3/src/views/print/bizTemplateBind/index.vue @@ -0,0 +1,892 @@ + + + + + diff --git a/jeecgboot-vue3/src/views/print/template/native/NativePrintDesigner.vue b/jeecgboot-vue3/src/views/print/template/native/NativePrintDesigner.vue index 6783f55..53fab09 100644 --- a/jeecgboot-vue3/src/views/print/template/native/NativePrintDesigner.vue +++ b/jeecgboot-vue3/src/views/print/template/native/NativePrintDesigner.vue @@ -1059,6 +1059,13 @@ } if (type === 'qrcode' || type === 'barcode') { base.value = payload.value || ''; + if (type === 'barcode') { + // 默认 Code128(自动),与 jsbarcode 默认一致;displayValue 默认显示底部文字 + base.format = payload.format || 'CODE128'; + base.displayValue = payload.displayValue !== false; + // 条码下文字对齐:center / left / right / justify(两端对齐),默认居中 + base.textAlign = payload.textAlign || 'center'; + } return base as NativeElement; } if (type === 'reportHeader' || type === 'reportFooter') { diff --git a/jeecgboot-vue3/src/views/print/template/native/components/PropertiesPanel.vue b/jeecgboot-vue3/src/views/print/template/native/components/PropertiesPanel.vue index 0ad3585..a8f5caa 100644 --- a/jeecgboot-vue3/src/views/print/template/native/components/PropertiesPanel.vue +++ b/jeecgboot-vue3/src/views/print/template/native/components/PropertiesPanel.vue @@ -86,6 +86,47 @@