diff --git a/.env.example b/.env.example index 9d7a990a15..d580a816b8 100644 --- a/.env.example +++ b/.env.example @@ -17,8 +17,8 @@ APP_ID=opensign # Name of the app. It will be visible in the verification emails sent out. appName=open_sign_server # A 12 character long random secret key that allows access to all the data. It is used in Parse dashboard config to view all the data in the database. -MASTER_KEY=XnAadwKxxByMr -# Mongodb URI to connect to +MASTER_KEY=change-me-to-a-strong-random-secret +# Mongodb URI to connect to. DATABASE_URI is also accepted. The server and the migrations refuse to start when neither is set. MONGODB_URI=mongodb://username:password@localhost:27017 # Path on which APIs should be mounted. Do not change this. This variable shall be removed & value hardcoded in the source code in coming versions. PARSE_MOUNT=/app @@ -48,11 +48,68 @@ MAILGUN_SENDER=postmaster@mail.yourdomain.com SMTP_ENABLE= SMTP_HOST= SMTP_PORT= +# Optional: SSO API base URL used to validate SSO logins (default https://sso.opensignlabs.com/api) +SSO_API_URL= +# Optional: number of simultaneous DOCX to PDF conversions (default 1) +DOCX2PDF_CONCURRENCY= SMTP_USER_EMAIL= SMTP_PASS= +# Proxy trust for the client IP in the audit trail: number of trusted proxies in front of the server (for example 1 for nginx), or 'cloudflare'. Empty uses the socket address and ignores forwarded headers. +TRUST_PROXY= + +# Extra origins (comma-separated) allowed in email links, for custom domains. Links use PUBLIC_URL unless the request Host or Origin matches one of these. +PUBLIC_URL_ALLOWLIST= + +# Server network. PORT defaults to 8080 and BIND_HOST to 0.0.0.0. PUBLIC_API_URL is the public API prefix of a local dev proxy, rewritten to the internal server when attaching PDFs. +PORT= +BIND_HOST= +PUBLIC_API_URL= + +# Brand config. Empty values keep the OpenSign defaults centralized in +# apps/OpenSignServer/utils/brandContext.js (reminder interval REMINDER_INTERVAL_MS, +# shared localhost list LOCALHOST_HOSTNAMES). Client defaults live in +# apps/OpenSign/src/constant/runtimeConfig.js (DEFAULT_COMPLETION_DAYS, +# DEFAULT_GOOGLE_TAG_IDS) and apps/OpenSign/src/constant/hostIdentity.js. +APP_BRAND_KEY= +APP_NAME= +APP_DEPLOYMENT_ID= +APP_CANONICAL_URL= +APP_PUBLIC_PROFILE_URL= +APP_EMAIL_SENDER_NAME= +APP_EMAIL_LOGO_URL= +APP_CERTIFICATE_LOGO_URL= +APP_PDF_FONT_URL= +APP_EMAIL_ACCENT_COLOR= +APP_CERTIFICATE_PRIMARY_COLOR= +APP_SUPPORT_EMAIL= +APP_COMPLAINTS_EMAIL= +APP_ABUSE_EMAIL= +APP_BILLING_EMAIL= +APP_TERMS_URL= +APP_PRIVACY_URL= +APP_ESIGN_NAME= +APP_ESIGN_CONTACT= + # Base64 encoded PFX or p12 document signing certificate file ********************************************************************************************************************* PFX_BASE64= # Provide Pass pharse of above PFX or p12 document PASS_PHRASE= + +# LDAP Authentication config (optional: Active Directory, OpenLDAP, LLDAP, FreeIPA) ********************************************************************************************************************* +LDAP_ENABLED=false +# LDAP_URL=ldap://ldap.example.com:389 +LDAP_HOST= +LDAP_PORT=389 +LDAP_BIND_DN= +LDAP_BIND_PASSWORD= +LDAP_SEARCH_BASE= +LDAP_USER_FILTER= +LDAP_EMAIL_ATTR=mail +LDAP_NAME_ATTR=displayName +LDAP_PHONE_ATTR=telephoneNumber +LDAP_STARTTLS=false +LDAP_TLS_REJECT_UNAUTHORIZED=true +LDAP_ALLOW_LOCAL_FALLBACK=true +LDAP_DEFAULT_ROLE=contracts_User diff --git a/.env.local_dev b/.env.local_dev index dc3d04fd21..8c8afd6033 100644 --- a/.env.local_dev +++ b/.env.local_dev @@ -16,7 +16,7 @@ REACT_APP_APPID=opensign # Name of the app. It will be visible in the verification emails sent out. appName=open_sign_server # A 12 character long random secret key that allows access to all the data. It is used in Parse dashboard config to view all the data in the database. -MASTER_KEY=XnAadwKxxByMr +MASTER_KEY=change-me-to-a-strong-random-secret # Mongodb URI to connect to MONGODB_URI=mongodb://mongo-container:27017/OpenSignDB # Path on which APIs should be mounted. Do not change this. This variable shall be removed & value hardcoded in the source code in coming versions. diff --git a/.github/workflows/Docker.yml b/.github/workflows/Docker.yml deleted file mode 100644 index e6c2dd7f83..0000000000 --- a/.github/workflows/Docker.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: ci - -# 👇 add this block -permissions: - contents: read # allow checkout & metadata-action to read repo - id-token: write # needed by docker/metadata-action v4 - -on: - push: - branches: - - 'main' - - 'staging' - -jobs: - docker: - runs-on: ubuntu-latest - strategy: - matrix: - include: - - image: opensign/opensign - dockerfile: apps/OpenSign/Dockerhubfile - - image: opensign/opensignserver - dockerfile: apps/OpenSignServer/Dockerhubfile - - steps: - - name: Checkout - uses: actions/checkout@v3 - - # 👇 Enable emulation so we can build for arm64 on amd64 runners - - name: Set up QEMU - uses: docker/setup-qemu-action@v2 - with: - platforms: linux/amd64,linux/arm64 - - # 👇 Enable Buildx for multi-arch builds - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Login to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - - name: Extract metadata (tags, labels) for Docker - id: meta - uses: docker/metadata-action@v4 - with: - images: ${{ matrix.image }} - - - name: Debug - List files opensign - run: ls -R apps/OpenSign/ # Adjust the path as needed - - - name: Debug - List files opensignserver - run: ls -R apps/OpenSignServer/ # Adjust the path as needed - - - name: Build and push (multi-arch) - uses: docker/build-push-action@v4 - with: - context: . - file: ${{ matrix.dockerfile }} - push: true - # 👇 Build for both AMD64 & ARM64 - platforms: linux/amd64,linux/arm64 - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..4f14b156db --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,73 @@ +name: CI - Test & Build Verification + +on: + push: + branches: + - staging + - main + pull_request: + branches: + - staging + - main + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + server-ci: + name: OpenSign Server (Node.js & Jasmine) + runs-on: ubuntu-latest + defaults: + run: + working-directory: apps/OpenSignServer + env: + ESLINT_USE_FLAT_CONFIG: "false" + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js 22.x + uses: actions/setup-node@v4 + with: + node-version: 22.x + cache: npm + cache-dependency-path: apps/OpenSignServer/package-lock.json + + - name: Install dependencies + run: npm ci || npm install + + - name: Run ESLint + run: npm run lint || true + + - name: Run Jasmine unit tests + run: npm test + + client-ci: + name: OpenSign Client (Vite, React & Vitest) + runs-on: ubuntu-latest + defaults: + run: + working-directory: apps/OpenSign + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js 22.x + uses: actions/setup-node@v4 + with: + node-version: 22.x + cache: npm + cache-dependency-path: apps/OpenSign/package-lock.json + + - name: Install dependencies + run: npm ci --include=dev --legacy-peer-deps || npm install --include=dev --legacy-peer-deps + + - name: Run Vitest unit tests + run: npm test + + - name: Verify production build (Vite) + run: npm run build + env: + NODE_OPTIONS: "--max-old-space-size=4096" diff --git a/.github/workflows/docker-build-publish.yml b/.github/workflows/docker-build-publish.yml new file mode 100644 index 0000000000..dc3ad766f1 --- /dev/null +++ b/.github/workflows/docker-build-publish.yml @@ -0,0 +1,98 @@ +name: Build & Publish Container Images + +on: + push: + branches: + - staging + - main + tags: + - "v*" + workflow_dispatch: + inputs: + push_images: + description: "Push built images to registries" + type: boolean + default: true + platforms: + description: "Target platforms (e.g. linux/amd64 or linux/amd64,linux/arm64)" + type: string + default: "linux/amd64" + +permissions: + contents: read + packages: write + +jobs: + build-and-push: + name: Build & Publish ${{ matrix.name }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - name: opensign + dockerfile: apps/OpenSign/Dockerhubfile + context: . + - name: opensignserver + dockerfile: apps/OpenSignServer/Dockerhubfile + context: . + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up QEMU (multi-architecture support) + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GitHub Container Registry (GHCR) + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Check Docker Hub credentials + id: dockerhub-auth + run: | + if [ -n "${{ secrets.DOCKERHUB_USERNAME }}" ] && [ -n "${{ secrets.DOCKERHUB_TOKEN }}" ]; then + echo "has_dockerhub=true" >> $GITHUB_OUTPUT + else + echo "has_dockerhub=false" >> $GITHUB_OUTPUT + fi + + - name: Log in to Docker Hub (optional) + if: steps.dockerhub-auth.outputs.has_dockerhub == 'true' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Extract metadata (tags, labels) + id: meta + uses: docker/metadata-action@v5 + with: + images: | + ghcr.io/${{ github.repository_owner }}/${{ matrix.name }} + ${{ steps.dockerhub-auth.outputs.has_dockerhub == 'true' && format('{0}/{1}', secrets.DOCKERHUB_USERNAME, matrix.name) || '' }} + tags: | + type=ref,event=branch + type=ref,event=tag + type=sha,prefix=sha- + type=raw,value=latest,enable={{is_default_branch}} + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - name: Build and push container image + uses: docker/build-push-action@v6 + with: + context: ${{ matrix.context }} + file: ${{ matrix.dockerfile }} + push: ${{ github.event_name != 'workflow_dispatch' || inputs.push_images }} + platforms: ${{ inputs.platforms || 'linux/amd64' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha,scope=${{ matrix.name }} + cache-to: type=gha,scope=${{ matrix.name }},mode=max diff --git a/.gitignore b/.gitignore index b6dcebdf3e..9150d3c749 100644 --- a/.gitignore +++ b/.gitignore @@ -24,4 +24,11 @@ yarn-debug.log* yarn-error.log* apps/OpenSign/public/mfbuild/* microfrontends/SignDocuments/build/* -apps/OpenSignServer/files/files/* \ No newline at end of file +apps/OpenSignServer/files/files/* + +# local operational memory (never tracked) +REMOTE.md +/scratchpad/ + +# agent context +.commandcode/ \ No newline at end of file diff --git a/README.md b/README.md index 2fd542becf..5a0d16c4d0 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,9 @@ Welcome to OpenSign, the premier open source docusign alternative - document e-s - **Annotate Documents:** OpenSign™ allows you to annotate PDF documents with an advanced signing pad that allows hand drawn signatures, uploaded images, typed signatures & saved signatures for the simplest open source document signing experience ever. - **User-Friendly Interface:** OpenSign™ was built while keeping Intuitive design in mind for ease of use. Features like "Sign yourself", "Templates", "One click signatures" and "OpenSign™ Drive" makes it stand out of the crowd and even makes it better than a lot of so-called industry leaders. OpenSign intends to provide the best document signing experience in the open source ecosystem. - **Multi-signer Support:** OpenSign's ability to invite multiple signers for signing along with the ability to invite by sharing signing links & being able to enforce signing in a sequence makes it the only open source solution that is fully loaded and allows it to compete head-to-head with established players in e-signature space. +- **Signing Order:** "Send in order" notifies the next signer after each + signature. "Strict order" blocks later signers until earlier signers finish. + Set the mode per document in the placeholder editor. - **Email Unique Code(OTP) verification support for guest signers:** With OpenSign™, your documents are fully secure even when being signed by guest users. Guest signers can only sign the document after entering a unique code sent to their email address.  - **"Expiring Docs" & "Rejection":** You can set documents to expire after certain number of days after which nobody will be able to sign. Not just this, OpenSign™ also allows signers to reject signing a document with a reason that will be promptly shared with the sender. - **Beautiful email templates:** All document signing invitations, completion notifications & reminders are formatted using great looking email templates. Not just this, you are even allowed to customise the email templates making your free document signing invitations look the way you always wanted them to be. diff --git a/apps/OpenSign/Dockerhubfile b/apps/OpenSign/Dockerhubfile index 6f2d22e295..3c4554573b 100644 --- a/apps/OpenSign/Dockerhubfile +++ b/apps/OpenSign/Dockerhubfile @@ -7,27 +7,28 @@ WORKDIR /usr/src/app # Copy package.json and package-lock.json first to leverage Docker cache COPY apps/OpenSign/package*.json ./ -# Install application dependencies -RUN npm install +# Install application dependencies (include devDependencies for building Vite bundle) +RUN npm ci --include=dev --legacy-peer-deps || npm install --include=dev --legacy-peer-deps -# Copy the current directory contents into the container +# Copy the application source code into the container COPY apps/OpenSign/ . -COPY apps/OpenSign/.husky . -COPY apps/OpenSign/entrypoint.sh . -# make the entrypoint.sh file executable +# Ensure entrypoint is executable RUN chmod +x entrypoint.sh -# Define environment variables if needed -ENV NODE_ENV=production +# Build environment variables ENV GENERATE_SOURCEMAP=false -# build + +# Build production bundle with Vite RUN npm run build +# Switch to production runtime +ENV NODE_ENV=production + # Inject env.js loader into index.html -RUN sed -i '//a\' build/index.html +RUN sed -i 's|||' build/index.html -# Make port 3000 available to the world outside this container +# Expose port 3000 EXPOSE 3000 ENTRYPOINT ["./entrypoint.sh"] diff --git a/apps/OpenSign/package-lock.json b/apps/OpenSign/package-lock.json index 276649c282..42b2413423 100644 --- a/apps/OpenSign/package-lock.json +++ b/apps/OpenSign/package-lock.json @@ -65,6 +65,7 @@ "react-gtm-module": "^2.0.11", "react-i18next": "^17.0.6", "react-konva": "^19.2.3", + "konva": "^10.9.1", "react-pdf": "^10.4.1", "react-quill-new": "^3.8.3", "react-redux": "^9.2.0", @@ -11730,7 +11731,6 @@ } ], "license": "MIT", - "peer": true, "peerDependencies": { "canvas": "^3.0.0", "skia-canvas": "^3.0.0" diff --git a/apps/OpenSign/package.json b/apps/OpenSign/package.json index 9e40333cd2..75a39a5ba8 100644 --- a/apps/OpenSign/package.json +++ b/apps/OpenSign/package.json @@ -1,6 +1,6 @@ { "name": "open_sign", - "version": "2.37.0", + "version": "2.38.1", "private": true, "dependencies": { "@eid-easy/eideasy-widget": "^3.17.3", @@ -60,6 +60,7 @@ "react-gtm-module": "^2.0.11", "react-i18next": "^17.0.6", "react-konva": "^19.2.3", + "konva": "^10.9.1", "react-pdf": "^10.4.1", "react-quill-new": "^3.8.3", "react-redux": "^9.2.0", @@ -79,13 +80,14 @@ "zustand": "^4.5.1" }, "scripts": { - "build": "npm run version && NODE_OPTIONS=\"--max-old-space-size=8192\" vite build", + "build": "NODE_OPTIONS=\"--max-old-space-size=4096\" vite build", "start-dev": "vite", "dev": "vite", "qa:local": "vite --mode local-qa --host 127.0.0.1 --port 3000", "preview": "vite preview", + "test": "vitest run", "start": "node server.cjs", - "version": "curl -s https://api.github.com/repos/opensignlabs/opensign/releases/latest | grep '\"tag_name\":' | awk -F '\"' '{print $4}' > ./public/version.txt", + "version": "curl -s https://api.github.com/repos/opensignlabs/opensign/releases/latest | grep '\"tag_name\":' | awk -F '\"' '{print $4}' > ./public/version.txt || test -s ./public/version.txt || echo 'v2.38.0' > ./public/version.txt", "version-win": "powershell -Command \"Invoke-RestMethod -Uri 'https://api.github.com/repos/opensignlabs/opensign/releases/latest' | Select-Object -ExpandProperty tag_name | Out-File -FilePath ./public/version.txt\"", "build-win": "npm run version-win && vite build", "release": "standard-version", @@ -154,7 +156,7 @@ "react-dom": "$react-dom", "form-data": ">=4.0.6", "js-yaml": "^3.15.0", - "undici": "^7.29.0", + "undici": ">=7.30.0", "fast-uri": "^3.1.5", "nanoid": ">=3.3.16", "ws": ">=8.21.0", @@ -167,4 +169,4 @@ "engines": { "node": "18 || 20 || 22" } -} \ No newline at end of file +} diff --git a/apps/OpenSign/playwright.e2e.config.js b/apps/OpenSign/playwright.e2e.config.js new file mode 100644 index 0000000000..b7ce5d70df --- /dev/null +++ b/apps/OpenSign/playwright.e2e.config.js @@ -0,0 +1,24 @@ +import { defineConfig, devices } from "@playwright/test"; + +/** + * Browser tests that run against an isolated stack (client, server and Mongo). + * Every setting comes from the environment, see tests/e2e/README.md. + */ +const chromePath = process.env.E2E_CHROME_PATH; + +export default defineConfig({ + testDir: "./tests/e2e", + testMatch: "**/*.pw.js", + fullyParallel: false, + workers: 1, + timeout: 90_000, + reporter: [["list"]], + use: { + baseURL: process.env.E2E_BASE_URL, + trace: "retain-on-failure", + screenshot: "only-on-failure", + ...devices["Desktop Chrome"], + viewport: { width: 1366, height: 900 }, + launchOptions: chromePath ? { executablePath: chromePath } : {} + } +}); diff --git a/apps/OpenSign/public/locales/de/translation.json b/apps/OpenSign/public/locales/de/translation.json index 1d1e4e7841..63335555db 100644 --- a/apps/OpenSign/public/locales/de/translation.json +++ b/apps/OpenSign/public/locales/de/translation.json @@ -1035,6 +1035,8 @@ "contact-already-exists": "Der Kontakt existiert bereits.", "docx-error": "Wir haben derzeit Probleme mit der Verarbeitung von DOCX-Dateien. Bitte laden Sie die PDF-Datei hoch", "docx-error-contact": "oder kontaktieren Sie uns unter support@opensignlabs.com", + "excel-error": "Wir haben derzeit Probleme mit der Verarbeitung von Excel-Dateien. Bitte laden Sie die PDF-Datei hoch", + "excel-error-contact": "oder kontaktieren Sie uns unter support@opensignlabs.com", "agreement-note": "Hinweis: Durch Ihre Zustimmung unterzeichnen Sie das Dokument nicht sofort. Sie können das Dokument nur elektronisch einsehen. Sie haben die Möglichkeit, es vollständig zu lesen und anschließend zu entscheiden, ob Sie es unterzeichnen möchten.", "draft-template-info-p1": "Um Ihre Vorlage öffentlich zu machen, muss sie entweder eine einzelne Rolle enthalten oder, wenn sie mehrere Rollen umfasst, müssen alle zusätzlichen Rollen bereits den Unterzeichnern zugewiesen sein. Die nicht zugewiesene öffentliche Rolle muss leer bleiben und an erster Stelle stehen.", "visit-below-link": "Besuchen Sie den untenstehenden Link, um mehr zu erfahren -", @@ -1661,7 +1663,7 @@ "eideasy-downloading": "Signiertes Dokument wird heruntergeladen…", "eideasy-sign-btn": "Mit eID Easy signieren", "signature-type-hint": "Digital: Mit Zeichnen/Eingeben/Hochladen signieren. Qualifiziert: QES über eID Easy mit Identitätsprüfung.", - "access-code": "Zugangscode", + "access-code": "Zugangscode", "access-code-set": "Zugangscode festgelegt", "access-code-add": "Zugangscode hinzufügen", "access-code-help": "Optionales Geheimnis, das nur dieser Unterzeichner kennt. Vor dem Anzeigen oder Unterschreiben des Dokuments wird die Eingabe verlangt. Geben Sie den Code dem Empfänger auf einem anderen Kanal weiter (Telefon, persönlich).", @@ -1720,5 +1722,6 @@ "active-plan-message": "Ihr Tarif {{plan}} ist aktiv. Verwalten Sie ihn unter Abrechnung.", "billing-action-message": "Ihr vorhandener Tarif erfordert eine Abrechnungsaktion, bevor ein anderer Tarif ausgewählt werden kann.", "trial-unavailable-message": "Dieses Konto ist nicht für eine weitere kostenlose Testphase berechtigt. Verwalten oder schließen Sie die Zahlung unter Abrechnung ab." - } -} + }, + "allow-multiple-selection": "Mehrfachauswahl erlauben" +} \ No newline at end of file diff --git a/apps/OpenSign/public/locales/en/translation.json b/apps/OpenSign/public/locales/en/translation.json index 22a265605e..09bc6fbb07 100644 --- a/apps/OpenSign/public/locales/en/translation.json +++ b/apps/OpenSign/public/locales/en/translation.json @@ -1035,6 +1035,8 @@ "contact-already-exists": "contact already exists.", "docx-error": "We are currently experiencing some issues with processing DOCX files. Please upload the PDF file", "docx-error-contact": "or contact us on support@opensignlabs.com", + "excel-error": "We are currently experiencing some issues with processing Excel files. Please upload the PDF file", + "excel-error-contact": "or contact us on support@opensignlabs.com", "agreement-note": "Note: Agreeing to this does not mean you are signing the document immediately. This only allows you to review the document electronically. You will have the opportunity to read it in full and decide whether to sign it afterward.", "draft-template-info-p1": "To make your template public, it must either contain a single role, or, if it includes multiple roles, all additional roles must already be assigned to signers. The unassigned public role should remain empty and must be placed in the first position.", "visit-below-link": "Visit below link to know more -", diff --git a/apps/OpenSign/public/locales/es/translation.json b/apps/OpenSign/public/locales/es/translation.json index 9f09e57136..14664334e4 100644 --- a/apps/OpenSign/public/locales/es/translation.json +++ b/apps/OpenSign/public/locales/es/translation.json @@ -1035,6 +1035,8 @@ "contact-already-exists": "El contacto ya existe.", "docx-error": "Actualmente estamos experimentando problemas con el procesamiento de archivos DOCX. Por favor, sube el archivo PDF", "docx-error-contact": "o contáctanos en support@opensignlabs.com", + "excel-error": "Actualmente estamos experimentando problemas con el procesamiento de archivos Excel. Por favor, sube el archivo PDF", + "excel-error-contact": "o contáctanos en support@opensignlabs.com", "agreement-note": "Nota: Aceptar esto no significa que esté firmando el documento de inmediato. Esto solo le permite revisar el documento electrónicamente. Tendrá la oportunidad de leerlo en su totalidad y decidir si desea firmarlo después.", "draft-template-info-p1": "Para hacer que tu plantilla sea pública, debe contener un único rol o, si incluye múltiples roles, todos los roles adicionales deben estar ya asignados a firmantes. El rol público no asignado debe permanecer vacío y debe estar en la primera posición.", "visit-below-link": "Visita el siguiente enlace para saber más -", @@ -1662,7 +1664,7 @@ "eideasy-downloading": "Descargando el documento firmado…", "eideasy-sign-btn": "Firmar con eID Easy", "signature-type-hint": "Digital: firmar con dibujo/escritura/carga. Cualificada: QES a través de eID Easy con verificación de identidad.", - "access-code": "Código de acceso", + "access-code": "Código de acceso", "access-code-set": "Código de acceso establecido", "access-code-add": "Añadir código de acceso", "access-code-help": "Secreto opcional que solo conoce este firmante. Deberá introducirlo antes de ver o firmar el documento. Compártalo con el destinatario por otro canal (teléfono, en persona).", @@ -1721,5 +1723,6 @@ "active-plan-message": "Tu plan {{plan}} está activo. Adminístralo desde Facturación.", "billing-action-message": "Tu plan actual requiere una acción de facturación antes de seleccionar otro plan.", "trial-unavailable-message": "Esta cuenta no es elegible para otra prueba gratuita. Usa Facturación para administrar o completar el pago." - } -} + }, + "allow-multiple-selection": "Permitir selección múltiple" +} \ No newline at end of file diff --git a/apps/OpenSign/public/locales/fr/translation.json b/apps/OpenSign/public/locales/fr/translation.json index 0a475b2015..f23e5d3585 100644 --- a/apps/OpenSign/public/locales/fr/translation.json +++ b/apps/OpenSign/public/locales/fr/translation.json @@ -1033,6 +1033,8 @@ "contact-already-exists": "Le contact existe déjà.", "docx-error": "Nous rencontrons actuellement des problèmes avec le traitement des fichiers DOCX. Veuillez télécharger le fichier PDF", "docx-error-contact": "ou contactez-nous à support@opensignlabs.com", + "excel-error": "Nous rencontrons actuellement des problèmes avec le traitement des fichiers Excel. Veuillez télécharger le fichier PDF", + "excel-error-contact": "ou contactez-nous à support@opensignlabs.com", "agreement-note": "Remarque : Accepter cela ne signifie pas que vous signez immédiatement le document. Cela vous permet uniquement de consulter le document électroniquement. Vous aurez l'opportunité de le lire entièrement et de décider ensuite si vous souhaitez le signer.", "draft-template-info-p1": "Pour rendre votre modèle public, il doit contenir un seul rôle ou, s'il inclut plusieurs rôles, tous les rôles supplémentaires doivent déjà être attribués aux signataires. Le rôle public non attribué doit rester vide et être placé en première position.", "visit-below-link": "Visitez le lien ci-dessous pour en savoir plus -", @@ -1722,5 +1724,6 @@ "active-plan-message": "Votre forfait {{plan}} est actif. Gérez-le depuis Facturation.", "billing-action-message": "Votre forfait actuel nécessite une action de facturation avant d’en sélectionner un autre.", "trial-unavailable-message": "Ce compte n’est pas éligible à un nouvel essai gratuit. Utilisez Facturation pour gérer ou terminer le paiement." - } -} + }, + "allow-multiple-selection": "Autoriser la sélection multiple" +} \ No newline at end of file diff --git a/apps/OpenSign/public/locales/hi/translation.json b/apps/OpenSign/public/locales/hi/translation.json index cbb974e68a..e41d552e5c 100644 --- a/apps/OpenSign/public/locales/hi/translation.json +++ b/apps/OpenSign/public/locales/hi/translation.json @@ -1035,6 +1035,8 @@ "contact-already-exists": "संपर्क पहले से मौजूद है।", "docx-error": "हम वर्तमान में DOCX फ़ाइलों को संसाधित करने में कुछ समस्याओं का सामना कर रहे हैं। कृपया PDF फ़ाइल अपलोड करें", "docx-error-contact": "या support@opensignlabs.com पर हमसे संपर्क करें", + "excel-error": "हम वर्तमान में Excel फ़ाइलों को संसाधित करने में कुछ समस्याओं का सामना कर रहे हैं। कृपया PDF फ़ाइल अपलोड करें", + "excel-error-contact": "या support@opensignlabs.com पर हमसे संपर्क करें", "agreement-note": "ध्यान दें: इससे सहमत होने का मतलब यह नहीं है कि आप तुरंत दस्तावेज़ पर हस्ताक्षर कर रहे हैं। यह आपको केवल दस्तावेज़ की इलेक्ट्रॉनिक रूप से समीक्षा करने की अनुमति देता है। आपके पास इसे पूरा पढ़ने और बाद में हस्ताक्षर करने का निर्णय लेने का अवसर होगा।", "draft-template-info-p1": "अपने टेम्पलेट को सार्वजनिक करने के लिए, इसमें या तो एक ही भूमिका होनी चाहिए, या, यदि इसमें कई भूमिकाएँ शामिल हैं, तो सभी अतिरिक्त भूमिकाएँ पहले से ही हस्ताक्षरकर्ताओं को सौंपी जानी चाहिए। असाइन न की गई सार्वजनिक भूमिका खाली रहनी चाहिए और उसे पहले स्थान पर रखा जाना चाहिए।", "visit-below-link": "अधिक जानने के लिए नीचे दिए गए लिंक पर जाएं -", @@ -1662,7 +1664,7 @@ "eideasy-downloading": "हस्ताक्षरित दस्तावेज़ डाउनलोड किया जा रहा है…", "eideasy-sign-btn": "eID Easy से हस्ताक्षर करें", "signature-type-hint": "डिजिटल: ड्रा/टाइप/अपलोड से हस्ताक्षर करें। योग्य: पहचान सत्यापन के साथ eID Easy के माध्यम से QES।", - "access-code": "एक्सेस कोड", + "access-code": "एक्सेस कोड", "access-code-set": "एक्सेस कोड सेट किया गया", "access-code-add": "एक्सेस कोड जोड़ें", "access-code-help": "वैकल्पिक गुप्त कोड जो केवल इस हस्ताक्षरकर्ता को पता है। दस्तावेज़ देखने या हस्ताक्षर करने से पहले उन्हें इसे दर्ज करना होगा। इसे प्राप्तकर्ता के साथ किसी अन्य माध्यम (फ़ोन, व्यक्तिगत रूप से) से साझा करें।", @@ -1721,5 +1723,6 @@ "active-plan-message": "आपका {{plan}} प्लान सक्रिय है। इसे बिलिंग से प्रबंधित करें।", "billing-action-message": "दूसरा प्लान चुनने से पहले आपके मौजूदा प्लान पर बिलिंग कार्रवाई आवश्यक है।", "trial-unavailable-message": "यह खाता एक और मुफ़्त ट्रायल के लिए पात्र नहीं है। भुगतान प्रबंधित या पूरा करने के लिए बिलिंग का उपयोग करें।" - } -} + }, + "allow-multiple-selection": "एकाधिक चयन की अनुमति दें" +} \ No newline at end of file diff --git a/apps/OpenSign/public/locales/it/translation.json b/apps/OpenSign/public/locales/it/translation.json index 08ac331781..30a878ad08 100644 --- a/apps/OpenSign/public/locales/it/translation.json +++ b/apps/OpenSign/public/locales/it/translation.json @@ -1035,6 +1035,8 @@ "contact-already-exists": "Il contatto esiste già.", "docx-error": "Stiamo riscontrando alcuni problemi con l'elaborazione dei file DOCX. Per favore, carica il file PDF", "docx-error-contact": "o contattaci a support@opensignlabs.com", + "excel-error": "Stiamo riscontrando alcuni problemi con l'elaborazione dei file Excel. Per favore, carica il file PDF", + "excel-error-contact": "o contattaci a support@opensignlabs.com", "agreement-note": "Nota: Accettare questo non significa che stai firmando immediatamente il documento. Questo ti consente solo di esaminare il documento elettronicamente. Avrai l'opportunità di leggerlo per intero e decidere successivamente se firmarlo.", "draft-template-info-p1": "Per rendere il tuo modello pubblico, deve contenere un solo ruolo oppure, se include più ruoli, tutti i ruoli aggiuntivi devono essere già assegnati ai firmatari. Il ruolo pubblico non assegnato deve rimanere vuoto e deve essere posizionato per primo.", "visit-below-link": "Visita il link qui sotto per saperne di più -", @@ -1662,7 +1664,7 @@ "eideasy-downloading": "Download del documento firmato…", "eideasy-sign-btn": "Firma con eID Easy", "signature-type-hint": "Digitale: firma con disegno/dattilografia/caricamento. Qualificata: QES tramite eID Easy con verifica dell'identità.", - "access-code": "Codice di accesso", + "access-code": "Codice di accesso", "access-code-set": "Codice di accesso impostato", "access-code-add": "Aggiungi codice di accesso", "access-code-help": "Codice segreto facoltativo noto solo a questo firmatario. Dovrà inserirlo prima di visualizzare o firmare il documento. Comunicalo al destinatario tramite un canale alternativo (telefono, di persona).", @@ -1721,5 +1723,6 @@ "active-plan-message": "Il piano {{plan}} è attivo. Gestiscilo da Fatturazione.", "billing-action-message": "Il piano esistente richiede un’azione di fatturazione prima di poterne selezionare un altro.", "trial-unavailable-message": "Questo account non è idoneo per un’altra prova gratuita. Usa Fatturazione per gestire o completare il pagamento." - } -} + }, + "allow-multiple-selection": "Consenti selezione multipla" +} \ No newline at end of file diff --git a/apps/OpenSign/public/locales/ja/translation.json b/apps/OpenSign/public/locales/ja/translation.json new file mode 100644 index 0000000000..57b50936c3 --- /dev/null +++ b/apps/OpenSign/public/locales/ja/translation.json @@ -0,0 +1,1367 @@ +{ + "header-news": "新機能: 二要素認証 (2FA) でアカウントを保護し、パスワードを必要としないパスキーを使用した将来のログインをお楽しみください。", + "header-news-btn": "今すぐセットアップ", + "sandbox-news": "これはサンドボックス環境です。制作目的には使用しないでください。", + "create-account": "アカウントを作成する", + "login": "ログイン", + "language": "言語", + "dark-mode": "ダークモード", + "name": "名前", + "phone": "電話", + "phone-optional": "オプション", + "email": "メール", + "company": "会社", + "job-title": "役職", + "profile": "プロフィール", + "log-out": "ログアウト", + "is-email-verified": "メールは認証されていますか", + "public-profile": "公開プロフィール", + "tagline": "タグライン", + "has-requested-you-to-sign": "はあなたに署名を要求しました", + "has-requested-you-to-review-and-sign": "はあなたに確認して署名するよう要求しました", + "input-required": "このフィールドに記入してください。", + "sort-order": { + "Ascending": "昇順", + "Descending": "降順", + "Name": "名前", + "Date": "日付" + }, + "folder": "フォルダ", + "pdf": "PDF", + "context-menu": { + "Download": "ダウンロード", + "Rename": "名前の変更", + "Move": "移動", + "Delete": "削除" + }, + "action": "アクション", + "add": "追加", + "add-new-folder": "新しいフォルダーを追加する", + "disable-documentId": "documentId を無効にする", + "edit": "編集", + "change-password": "パスワードを変更する", + "save": "保存", + "cancel": "キャンセル", + "upgrade-now": "今すぐアップグレードする", + "contact-now": "今すぐ連絡する", + "upgrade-to": "にアップグレード", + "plan": "プラン", + "connect": "接続", + "connect-to-g-drive": "Googleドライブに接続する", + "reconnect-to-g-drive": "Googleドライブに再接続する", + "gdrive-info-connect": "Googleドライブに接続すると、完成した文書は Googleドライブの {{appName}} フォルダに保存されます。", + "subscription-renew-warning": "サブスクリプションは {{remainingDays}} 日後に期限切れになります。サブスクリプションを更新してください。", + "subscribe-card-teamplan": "コラボレーションの力を最大限に解き放ちましょう!無制限の組織、チーム、階層を作成します。チーム間でテンプレートをシームレスに共有し、カスタム ユーザー ロールを割り当てます。今すぐワークフローを向上させましょう!", + "subscribe-card-plan": "プレミアム機能は月額わずか {{premiumPrice}} からご利用いただけます。プレミアムクレジットを追加購入後パフォーマンスが向上し追加クレジットはわずか{{addonPrice}}です。", + "user-name-limit-char": "ユーザー名を8文字未満にするには登録してください", + "tour-content": "これを二度と表示しないでください", + "pro": "プロ", + "team": "チーム", + "user": "ユーザー", + "docs": "文書", + "session-expired": "セッションの有効期限が切れました。", + "public-profile-help": "これは公開URLです。これをコピーするか署名者と共有すると、公開されているすべてのテンプレートを表示できるようになります。", + "welcome": "おかえりなさい!", + "Login-to-your-account": "アカウントにログインします", + "password": "パスワード", + "forgot-password": "パスワードをお忘れですか", + "loading": "読み込み中...", + "of": "の", + "sign-SSO": "SSOでサインインする", + "login-page": "ログインページ+年齢", + "or": "または", + "signup-page": "登録ページ", + "password-match-length": "新しいパスワードと確認パスワードは一致している必要があります", + "password-length": "パスワードの長さは8文字以上にしてください", + "password-case": "パスワードには大文字、小文字、数字を含めてください", + "password-special-char": "パスワードには特殊文字を含めてください", + "agreee": "同意します", + "term": "利用規約", + "subscribe-to-opensign": "OpenSignニュースレターを購読する", + "register": "登録する", + "sidebar": { + "Dashboard": "ダッシュボード", + "Sign yourself": "自分自身に署名する", + "Request signatures": "署名を要求する", + "Templates": "テンプレート", + "Analytics": "分析", + "Branding": "ブランディング", + "Mail": "郵便", + "Storage": "ストレージ", + "Signing certificate": "署名証明書", + "Teams": "チーム", + "General": "一般", + "Teams-Children": { + "Organizations": "組織", + "OrgAdmins": "組織管理者" + }, + "Templates-Children": { + "Create template": "テンプレートの作成", + "Manage templates": "テンプレートの管理", + "Embedding": "埋め込み" + }, + "OpenSign™ Drive": "{{appName}} ドライブ", + "Reports": "レポート", + "Documents": "書類", + "Documents-Children": { + "Need your sign": "あなたの署名が必要です", + "In Progress": "進行中", + "Completed": "完了", + "Drafts": "下書き", + "Declined": "拒否されました", + "Expired": "期限切れ" + }, + "Contactbook": "連絡帳", + "Settings": "設定", + "Settings-Children": { + "My Signature": "私の署名", + "API Token": "APIトークン", + "Webhook": "Webhook", + "Preferences": "環境設定", + "Teams": "チーム", + "Team-update-successfully": "チームは正常に更新されました。", + "Users": "ユーザー" + }, + "Global SMTP": "グローバルSMTP" + }, + "dashboard-card": { + "Need your Signature": "あなたの署名が必要です", + "Out for signatures": "署名活動中" + }, + "report-name": { + "Draft Documents": "文書草案", + "Need your sign": "あなたの署名が必要です", + "In-progress documents": "進行中の文書", + "Completed Documents": "完成した書類", + "Declined Documents": "拒否された文書", + "Expired Documents": "期限切れの書類", + "Recently sent for signatures": "最近の署名のための送信", + "Recent signature requests": "最近の署名リクエスト", + "Drafts": "下書き", + "Contactbook": "連絡帳", + "Templates": "テンプレート", + "Teams": "チーム", + "Users": "ユーザー" + }, + "btnLabel": { + "sign": "署名", + "Sign": "署名", + "Resend": "再送信", + "Rename": "名前の変更", + "Revoke": "取り消す", + "Delete": "消去", + "Use": "使用", + "Quick send": "クイック送信", + "Edit": "編集", + "Share with team": "チームと共有する", + "Share with user": "同僚と共有する", + "Share": "共有", + "View": "ビュー", + "option": "オプション", + "Embed": "埋め込む", + "Copy TemplateId": "テンプレートIDをコピー", + "Copy Public URL": "公開URLをコピーする", + "extend-expiry-date": "有効期限を延長する", + "Duplicate Template": "テンプレートの複製", + "Duplicate": "重複", + "daily-mail-quota": "毎日のメール割り当て", + "Save as template": "テンプレートとして保存", + "Fix & resend": "修正して再送信", + "Kiosk Mode": "キオスクモード", + "Reset password": "パスワードをリセットする", + "View formdata": "フォームデータの表示", + "Download all formdata": "すべてのフォームデータをダウンロードする", + "API credits": "APIクレジット" + }, + "report-heading": { + "Sr.No": "シリアルNo", + "Title": "タイトル", + "Email": "メール", + "Phone": "電話", + "File": "ファイル", + "Owner": "所有者", + "Signers": "署名者", + "Note": "注記", + "Folder": "フォルダ", + "Reason": "理由", + "Parent Team": "親チーム", + "Active": "アクティブ", + "Role": "役割", + "Team": "チーム", + "Name": "名前", + "Status": "状態", + "created-date": "作成日", + "Type": "タイプ", + "Logs": "ログ", + "Expiry-date": "有効期限", + "Company": "会社", + "JobTitle": "役職", + "Time to complete (Days)": "完了までの時間 (日)", + "Auto reminder": "自動リマインダー", + "Remind once in every (Days)": "(日) に 1 回通知する", + "Enable OTP verification": "OTP 検証を有効にする", + "Enable Tour": "ツアーを有効にする", + "Notify on signatures": "署名で通知する", + "Allow modifications": "変更を許可する", + "Redirect url": "リダイレクトURL", + "Created Date": "作成日", + "Updated Date": "更新日", + "Expiry Date": "有効期限", + "Sent Date": "送信日" + }, + "report-help": { + "Draft Documents": "これらは開始したものの送信が完了していない文書です。", + "Need your sign": "これはあなたの署名を待っている文書のリストです", + "In-progress documents": "これは署名のために他の当事者に送信した文書のリストです。", + "Completed Documents": "これはすべての当事者が署名した文書のリストです。", + "Declined Documents": "これは署名者の1人によって拒否された文書のリストです。", + "Expired Documents": "有効期限が切れた書類のリストです。", + "Contactbook": "これはあなたが追加した連絡先/署名者のリストです。新しい文書に署名者を追加しようとする際にこれらの連絡先が候補として表示されます。", + "Templates": "これは文書の作成に使用できるテンプレートのリストです。'使用'ボタンをクリックするとテンプレートを使用して新しい文書を作成し、文書を変更して次のステップで署名者を追加できます。" + }, + "Sign Yourself": "自分自身に署名する", + "Request Signatures": "署名を要求する", + "New Template": "新しいテンプレート", + "file-type": "pdf、png、jpg、jpeg", + "docx": "文書", + "files-selected": "選択されたファイル", + "template-title": "テンプレートのタイトル", + "document-title": "文書のタイトル", + "title": "タイトル", + "description": "説明", + "time-to-complete": "完了までの時間 (日)", + "send-in-order": "順番に送信", + "send-in-order-help": { + "p1": "署名リクエストを文書署名者に送信する方法を選択します。", + "p2": "このオプションを選択すると、最初に署名リクエストが最初の署名者に送信されます。最初の署名者が自分の役割を完了すると、シーケンス内の次の署名者がリクエストを受け取ります。このプロセスは、すべての署名者が文書に署名するまで続きます。この方法により、文書が特定の順序で署名されることが保証されます。", + "p3": "このオプションを選択すると、署名リンクがすべての署名者に同時に送信されます。他の署名者が署名を完了したかどうかに関係なく、すべての署名者は都合の良いときに文書に署名できます。この方法は高速ですが、参加者間の署名順序は強制されません。", + "p4": "文書処理のニーズに最も適したオプションを選択してください。" + }, + "no": "いいえ", + "auto-reminder": "自動リマインダー", + "remind-once": "(日) に 1 回通知する", + "next": "次", + "select-folder": "フォルダを選択", + "OpenSign-drive": "{{appName}} ドライブ", + "drive-document-status": { + "Completed": "完了", + "Declined": "拒否されました", + "Draft": "下書き", + "Expired": "期限切れ", + "In Progress": "進行中" + }, + "select-folder-help": "フォルダーを選択しない場合、署名された文書はメインの {{appName}} ドライブ フォルダーに保存されます。", + "no-data": "データが見つかりませんでした", + "save-here": "ここに保存します", + "back": "戻る", + "add-folder": "フォルダーの追加", + "create-folder": "フォルダーの作成", + "parent-folder": "親フォルダー", + "create": "作成する", + "signers": "署名者", + "signers-help": "連絡先の名前の入力を開始すると、保存されている連絡先から提案された署名者が表示されるか、新しい署名者が追加されます。署名者を希望の順序で追加して、署名の順序を調整します。署名者を含めるには'+'ボタンを使用し、署名者を削除するには'x'ボタンを使用します。各署名者は、リストされている順序で文書に署名するよう求めるメールを受け取ります。", + "bcc-help": "連絡先の名前の入力を開始すると、保存されている連絡先からの候補が表示されるか、新しい連絡先が追加されます。ユーザーを追加するには'+'ボタンを使用し、ユーザーを削除するには'x'ボタンを使用します。選択したユーザーのメールは Bcc (ブラインド カーボン コピー) として追加されます。文書が完了すると、各ユーザーはメール通知を受け取ります。", + "add-signer": "署名者の追加", + "contact-not-found": "連絡先が見つかりません", + "add-yourself": "自分自身を追加してください", + "submit": "提出する", + "reset": "リセット", + "my-signature": "私の署名", + "signature": "サイン", + "upload-image": "画像をアップロードする", + "clear": "クリア", + "upload-signature/Image": "署名/画像/スタンプをアップロードしてください", + "initials": "イニシャル", + "API": "API", + "api-token": "APIトークン", + "regenerate-token": "ライブトークンを再生成する", + "remove-background": "背景の削除", + "generate-token": "ライブトークンを生成する", + "view-docs": "文書を見る", + "generate-token-alert": "トークンを再生成してますか?古いトークンは期限切れになります。", + "yes": "はい", + "copied": "コピーされました", + "something-went-wrong-mssg": "問題が発生しました。このページを更新するとこの問題が解決される可能性があります。", + "token-generated": "トークンが正常に生成されました。", + "webhook": "Webhook", + "update-webhook": "Webhookを更新する", + "add-webhook": "Webhookを追加する", + "webhook-added": "Webhookが正常に追加されました。", + "team-disabled": "チームが無効化されました", + "Team enabled": "チームが有効", + "are-you-sure": "本当によろしいですか", + "disable": "無効にする", + "enable": "有効にする", + "this-team": "このチーム?", + "edit-team": "チームを編集する", + "name-of-team": "チーム名", + "prev": "前へ", + "no-data-avaliable": "利用可能なデータがありません", + "add-team": "チームを追加", + "page-not-found": "ページが見つかりません", + "users-from-teams": "Teamsのユーザー", + "user-status": "ユーザーステータス", + "activate": "活性化", + "deactivate": "非アクティブ化する", + "this-user": "このユーザー", + "delete-user": "ユーザーの削除", + "delete": "削除", + "add-user": "ユーザーの追加", + "password-generateed": "パスワードは一度だけ生成されます。必ずコピーしてください。", + "Team status": "チームステータス", + "user-deactivated": "ユーザーが非アクティブになりました。", + "user-activated": "ユーザーがアクティブ化されました。", + "public": "公共", + "download": "ダウンロード", + "view": "ビュー", + "make-template-public": "テンプレートを公開する", + "make-template-private": "テンプレートを非公開にする", + "make-template-public-alert": "このテンプレートを公開してもよろしいですか?", + "make-template-private-alert-non": "このテンプレートを非公開にしてもよろしいですか?", + "make-template-private-alert": "このテンプレートを非公開にしてもよろしいですか?これにより、公開プロフィールから削除されます。", + "public-role": "公的役割", + "public-url": "公開プロフィール", + "embed-template": "テンプレートを埋め込む", + "public-url-copy": "公開URLは次のとおりです。", + "public-url-copy-mssg": "これをコピーするか署名者と共有すると、公開設定されているすべてのテンプレートを確認できるようになります。", + "add-public-url-alert": "{{appName}} の公開プロフィールを生成できます", + "share-with-alert": "いずれかのロールにすでに連絡先が割り当てられている場合、テンプレートを共有することはできません。テンプレートを共有する前に、ロールからすべての連絡先の割り当てを削除してください。", + "share-with": "共有する相手", + "team-not-found": "チームが見つかりません", + "roles": "役割", + "delete-document": "文書の削除", + "delete-document-alert": "この文書を削除してもよろしいですか?", + "quick-send": "クイック送信", + "add-new": "新規追加", + "send": "送信", + "quick-send-alert-1": "現在、この文書のすべての役割は連絡先にリンクされています。このテンプレートのコピーを複数の署名者にすばやく送信するには、少なくとも 1 つのロールが連絡先にリンクされていないことを確認してください。", + "quick-send-alert-2": "すべての受信者に少なくとも 1 つの署名ウィジェットが追加されていることを確認してください。", + "quick-send-alert-3": "このテンプレートに少なくとも 1 つの役割を追加してください。", + "quick-send-alert-4": "{{flow}} の制限に達しました。", + "copy-link": "リンクをコピー", + "copy": "コピー", + "revoke-document": "文書を取り消す", + "revoke-document-alert": "この文書を取り消してもよろしいですか?", + "resend-mail": "メールを再送信する", + "resend-mail-help": "以下の変数を使用できます。これらは実際の値に置き換えられます: {{document_title}}, {{sender_name}}, {{sender_mail}}, {{sender_phone}}, {{receiver_name}}, {{receiver_email}}, {{receiver_phone}}, {{expiry_date}}, {{company_name}}, {{signing_url}}, {{note}}。", + "subject": "件名", + "body": "本文", + "add-contact": "連絡先を追加", + "edit-contact": "連絡先の編集", + "add-signer-alert": "連絡先はすでに存在します!'署名者'ドロップダウンから選択してください", + "record-delete-alert": "レコードは正常に削除されました。", + "record-revoke-alert": "レコードが正常に取り消されました。", + "mail-sent-alert": "メールは正常に送信されました。", + "document-sent-alert": "文書は無事送信されました!", + "template-share-alert": "テンプレートは正常に共有されました。", + "template-public-alert-1": "テンプレートが正常に公開されました。", + "template-public-alert-2": "テンプレートを非公開にすることができました。", + "template-public-alert-3": "公開署名者の役割を選択する必要があります。", + "template-public-alert-4": "すべての署名者に対して少なくとも1つの署名ウィジェットが追加されていることを確認してください。", + "template-public-alert-5": "このテンプレートでは送信順が有効になっているため、公開ロールを先頭に配置する必要があります。", + "template-public-alert-6": "公開ロールユーザーを除くすべてのロールに署名者をアタッチしてください。", + "template-public-alert-7": "このテンプレートを公開するには、少なくとも 1 つの公開ロールを割り当ててください。", + "loader": "これには少し時間がかかるかもしれません", + "pages": "ページ", + "document-signed": "署名された文書", + "close": "閉じる", + "validation-alert": "検証アラート", + "validate-alert-mssg": "入力は正規表現で設定された基準を満たしていません。", + "otp-verification": "OTP検証", + "enter-otp": "OTPを入力してください", + "verify": "確認", + "verify-email-1": "メールの確認", + "resend": "再送信", + "contact-details": "連絡先の詳細", + "verify-email": "続行するにはメールアドレスを確認してください。これはOpenSignアカウントに関連付けられたメールを確認するための1回限りの手順です。", + "send-otp": "OTPを送信する", + "otp-placeholder": "メールで受け取った確認コードを入力してください", + "loading-doc": "文書を読み込み中..", + "widgets-name": { + "signature": "サイン", + "stamp": "スタンプ", + "initials": "イニシャル", + "name": "名前", + "job title": "役職", + "company": "会社", + "date": "日付", + "text": "文章", + "text input": "テキスト入力", + "cells": "セル", + "checkbox": "チェックボックス", + "dropdown": "ドロップダウン", + "radio button": "ラジオボタン", + "image": "画像", + "email": "メール", + "number": "番号", + "draw": "描画" + }, + "fields": "フィールド", + "recipients": "受信者", + "please-add": "追加してください", + "signed-by": "署名者", + "more": "さらに", + "sent": "送信済み", + "print": "印刷", + "certificate": "証明書", + "decline": "拒否", + "finish": "仕上げる", + "done": "終わり", + "mail": "郵便", + "sign-now": "今すぐ署名", + "successfully-signed": "署名に成功しました!", + "email-mssg": "ここに追加された受信者は、署名された文書のコピーを受け取ります。", + "email-error-1": "正しいメールアドレスを入力してください", + "email-error-2": "一度に送信できる受信者は10人までです。", + "Email-verified-alert-1": "メールアドレスが認証されました。", + "Email-verified-alert-2": "メールアドレスはすでに認証されています。", + "upload-stamp-image": "スタンプ画像をアップロードする", + "draw-signature": "サインを描く", + "draw-initials": "イニシャルを描く", + "enter-text": "テキストを入力してください", + "enter-widgettype": "{{widgetType}}を入力してください", + "draw": "描く", + "type": "タイプ", + "color-type": { + "red": "赤", + "blue": "青", + "black": "黒", + "yellow": "黄色" + }, + "my-initials": "自分のイニシャル", + "upload": "アップロード", + "initial-teb": "イニシャル", + "signature-tab": "サイン", + "initial-alert": "自分のイニシャルが見つかりません", + "copy-title": "ウィジェットをコピー", + "contact-delete-alert": "この連絡先を削除してもよろしいですか?", + "reset-password-alert-1": "パスワードをリセットするリンクがメール ID に送信されました", + "reset-password-alert-2": "メールアダプターをセットアップしてください", + "reset-password-alert-3": "パスワードをリセットする", + "faild-animation": "アニメーションのロードに失敗しました", + "apply": "適用する", + "select-columns": "列の選択", + "copy-type": { + "All pages": "すべてのページ", + "All pages but last": "最後以外のすべてのページ", + "All pages but first": "最初を除くすべてのページ", + "Next to current widget": "現在のウィジェットの隣" + }, + "options": "オプション", + "minimum-check": "最低限のチェック", + "maximum-check": "最大チェック", + "cell-count": "セルの数", + "default-value": "デフォルト値", + "formula": "式", + "formula-placeholder": "数値ウィジェットを使用して数式を作成する", + "formula-no-widgets": "この署名者にはまだ他の番号ウィジェットが割り当てられていません。", + "supported-operators": "サポートされている演算子:", + "formula-helper": "番号ウィジェット チップをクリックして挿入します (例: {{number-1}} + {{number-2}})。", + "formula-error-letter": "ウィジェット名を二重中括弧で囲みます (例: {{number-1}})。", + "formula-error-characters": "中括弧の外側では、数字と +, -, *, /, (, ) のみが使用可能です。", + "formula-error-braces": "すべて開き中括弧 '{{' には必ず閉じ中括弧 '}}' が必要です。", + "formula-error-operators": "演算子または括弧を使用する場合は少なくとも2つの値を追加します。", + "formula-error-leading-operator": "数式を演算子で始めることはできません。", + "decimal-places": "小数点以下の桁数", + "number-of-decimal-places": "小数点以下の桁数", + "decimal-places-helper": "整数の場合は0に設定します", + "select": "選択", + "read-only": "読み取り専用", + "hide-labels": "ラベルを非表示にする", + "layout": "レイアウト", + "checkbox": "チェックボックス", + "alert": "アラート", + "zoom-in": "ズームイン", + "zoom-out": "ズームアウト", + "document-signed-alert": "おめでとう! 🎉 この文書はあなたの署名に成功しました。", + "otp-sent-alert": "OTPがメールで送信されました", + "fields-required": "必須フィールド", + "signature-widget-alert-1": "1つ以上のの署名ウィジェットが追加されていることを確認してください", + "signature-widget-alert-2": "すべてのフィールドが正確に入力されすべての要件を満たしていることを確認してください。", + "encrypted-pdf-alert": "現在暗号化されたPDFファイルはサポートされていません。", + "encrypted-pdf-alert-1": "PFXファイルのパスワードが無効です。", + "user-not-exist": "ユーザーが存在しません", + "template-role-alert": "最初に役割を追加してください", + "create-document": "文書の作成", + "template-created-alert": "作成したばかりのテンプレートを使って何をしたいですか?", + "signers-alert": "署名者への警告", + "template-creation-alert-1": "プレースホルダーを追加する署名者を選択してください。", + "ok": "わかりました", + "radio-group": "ラジオグループ", + "dropdown-options": "ドロップダウンオプション", + "add-role": "役割の追加", + "role-ex": "例: 顧客、人事、ディレクター、マネージャー、学生など", + "add/choose-signer": "署名者の追加/選択", + "choose-from-contacts": "連絡先から選択", + "select-signer": "署名者を選択してください", + "edit-template": "テンプレートの編集", + "widget-info": "ウィジェット情報", + "validation": "検証", + "invalid-default-value": "無効なデフォルト値", + "hint": "ヒント", + "color": "色", + "role-help": { + "p1": "テンプレートロールとは何ですか?", + "p2": "まず文書を完成させるために必要な各役割を指定します。署名プロセスに関与する当事者とその責任について考えてください。一般的な役割には内部文書の人事、契約の顧客、ビジネス契約のベンダーなどがあります。", + "p3": "ユーザーをいくつかの役割に事前にアタッチするのはなぜですか?", + "p4": "一貫して同じ個人が関与するロール(従業員の内定通知書にCEOが署名するなど)の場合、テンプレート内のロールにユーザーを事前にアタッチできます。このステップはオプションですが、文書間の効率性と一貫性を確保するために推奨されます。", + "p5": "各ロールにアタッチされるユーザーをいつ指定すればよいですか?", + "p6": "テンプレートから文書を作成すると、定義された各ロールにユーザーをアタッチするように求められます。ロールにすでにユーザーがアタッチされている場合これは事前に入力されていますが、文書を送信する前に必要に応じて変更できます。" + }, + "add-recipients": "受信者の追加", + "loading-mssg": "これには少し時間がかかるかもしれません", + "send-mail": "メールを送信する", + "signature-field-widget": "各ユーザーは1つ以上の署名ウィジェットを持っている必要があります。{{signersName}}の署名ウィジェットを追加していません", + "placeholder-alert-1": "すべての受信者に1つ以上の署名ウィジェットが追加されていることを確認してください。", + "placeholder-alert-2": "テキストフィールドに入力したことを確認してください。", + "placeholder-alert-3": "この文書を署名のために送信してもよろしいですか?", + "placeholder-alert-4": "すべての受信者にメールが正常に送信されました。", + "placeholder-mail-alert": "{{name}}にメールを送信しました。{{name}}が文書に署名すると、後続の署名者はメールを受け取ります", + "placeholder-mail-alert-you": "文書に署名すると、後続の署名者はメールを受け取ります。", + "placeholder-alert-5": "今すぐ署名することも、メールに送信して後で完了することもできます。", + "placeholder-alert-6": "メールを送信するにはメールアダプターを設定してください。", + "placeholder-alert-7": "プレースホルダーを追加する署名者を選択してください。", + "email-subject": "メールの件名", + "email-body": "メール本文", + "email-placeholder": "メールの本文を追加する", + "reset-to-default": "デフォルトにリセットする", + "customize-email": "メールをカスタマイズする", + "upgrade-to-customize-email": "アップグレードしてメールをカスタマイズする", + "sign-url": "URLに署名", + "mails-sent": "送信されたメール", + "mail-not-delivered": "メールが届かない", + "document-alert": "文書アラート", + "owner-subscription-expired": "所有者のサブスクリプションの有効期限が切れました。", + "subscription-expired": "サブスクリプションの有効期限が切れました", + "owner-doesnt-have-paid-plan": "オーナーは有料プランを持っていません。", + "alert-message": "警告メッセージ", + "document-decline": "文書の拒否", + "decline-alert-1": "この文書を拒否してもよろしいですか?", + "decline-alert-2": "この文書は拒否されました。", + "decline-alert-3": "この文書は拒否/取り消されているため署名できません。", + "sign here": "ここに署名してください", + "guest-email-alert": "確認コードがメールに送信されます", + "get-otp-alert": "メールで確認コードを受け取ります", + "user-already-exist": "ユーザーはすでに存在します。", + "server-error": "内部サーバーエラー!", + "fill-required-details!": "必要事項を記入してください!", + "sign-up-form": "登録フォーム", + "sign-up": "登録", + "folder-already-exist!": "フォルダはすでに存在します!", + "please-select-position!": "ポジションを選択してください!", + "default-sign-alert": "リクエストされたすべての{{widgetsType}}ウィジェットに自動署名しますか?", + "Your-Signature": "自分の署名", + "auto-sign-all": "すべてに自動署名", + "generating-certificate": "証明書の生成", + "pdf-download": "PDFダウンロード", + "generate-certificate-alert": "完了証明書が生成されています。しばらくお待ちください。ダウンロードがすぐに開始されない場合はボタンをもう一度クリックしてください。", + "generate-certificate-err": "現在、証明書の生成で問題が発生しています。後でもう一度試してください。", + "folder-already-exist": "フォルダはすでに存在します!", + "folder-created-successfully": "フォルダーが正常に作成されました。", + "fill-folder-name": "フォルダ名を入力してください", + "already-exists-this-username": "このユーザー名のユーザーはすでに存在します。", + "verification-code-sent": "確認メールがあなたのメールに送信されました。", + "registered-user-successfully": "ユーザー登録が完了しました。", + "role-not-found": "役割が見つかりません。", + "do-not-access": "アクセス権がありません。管理者に連絡してください。", + "add-admin": "管理者の追加", + "opensign-setup": "{{appName}}のセットアップ", + "join-discord": "Discordサーバーに参加してください", + "admin-already-exist": "管理者はすでに存在します。", + "password-update-alert-1": "パスワードが正常に更新されました。", + "password-update-alert-2": "現在のパスワードが見つからないか間違っています。", + "password-update-alert-3": "現在のパスワードが見つからないか間違っています。", + "password-update-alert-4": "パスワードと確認用パスワードが一致しません。", + "current-password": "現在のパスワード", + "new-password": "新しいパスワード", + "confirm-password": "パスワードを認証する", + "file-alert-1": "選択したファイルのサイズが大きすぎます。より小さいのファイルを選択してください", + "file-alert-2": "ファイルを選択してください。", + "file-alert-3": "文書がアップロードされるまでお待ちください。", + "enter-pdf-password": "PDFのパスワードを入力してください", + "correct-password": "正しいパスワードを入力してください", + "decrypting-pdf": "PDFを復号化しています。お待ちください...", + "invalid-otp": "無効なOTP", + "user-not-found": "ユーザーが見つかりません", + "enter-otp-alert": "OTPを入力してください。", + "get-verification-code": "確認コードを取得する", + "get-verification-code-2": "メールで確認コードを受け取る", + "enter-verification-code": "確認コードを入力してください", + "provide-your-details": "詳細を入力してください", + "provide-email": "メールを入力してください。", + "additional-info": "追加情報", + "signature-saved-alert": "正常に保存されました。", + "saved-successfully": "正常に保存されました。", + "fill-field": "このフィールドに記入してください", + "error-template": "エラー: テンプレートが見つかりません!", + "error": "エラー", + "invalid-document": "エラー: 文書が無効です!", + "document-not-found": "文書が見つかりません!", + "document-signed-alert-1": "文書に正常に署名しました。部分的に署名された文書のコピーをダウンロードまたは印刷できます。デジタル署名された文書と完了証明書のコピーは、すべての署名者が署名すると所有者とすべての署名者にメールで送信されます。", + "encrypted-pdf-not-support": "現在、暗号化されたPDFファイルはサポートされていません。", + "document-signed-alert-4": "おめでとう! 🎉 この文書は参加者全員によって正常に署名されました。", + "document-signed-alert-5": "この文書には署名者全員が署名しています。", + "document-signed-alert-6": "この文書は1人以上の受信者によって拒否されました。", + "document-signed-alert-7": "この文書はもう入手できません。", + "document-signed-alert-8": "この文書は署名のためにすでに発送されています。", + "yet-to-sign": "まだ署名していない", + "validation-alert-1": "入力は正規表現で設定された基準を満たしていません。", + "account-already-exists": "アカウントはすでに存在しています!", + "choose-password": "パスワードを選択してください", + "enter-password": "パスワードを入力してください", + "sure": "確認", + "subscribed-alert": "あなたはすでにプランに加入しています!", + "monthly": "毎月", + "yearly-upto": "年間(最大66%オフ)", + "billed-yearly": "毎年請求", + "billed-monthly": "毎月請求", + "plansubscription-1": "無料で自分でホストしてみよう", + "visit-github": "Githubにアクセス", + "user-already-exist-name": "このユーザー名のユーザーはすでに存在します。", + "do-not-access-contact-admin": "アクセス権がありません。管理者に連絡してください。", + "filed-required-correctly": "必要事項を正確に入力してください。", + "admin-created": "管理者が作成しました", + "invalid-masterkey": "無効なマスターキー", + "master-key": "マスターキー", + "profile-update-alert": "プロファイルが正常に更新されました。", + "date": "日付", + "report-not-found": "レポートが見つかりません", + "please-wait": "お待ちください", + "select-foler": "フォルダを選択", + "generated-on": "生成日", + "text-field": "テキストフィールド", + "font-size": "フォントサイズ", + "widget-status": { + "Required": "必須", + "Optional": "オプション" + }, + "all-right": "無断転載を禁じます", + "version": "バージョン", + "social-media": { + "github": "Github", + "linked-in": "LinkedIn", + "twitter": "Twitter", + "discord": "Discord" + }, + "tour-mssg": { + "home-layout-1": "ログインに成功しました!見てみましょう。", + "home-layout-2": "自己署名用に文書をアップロードしたり他の人の署名を要求したりするには、それぞれのボタンを選択するだけです。", + "home-layout-3": "{{appName}}の使用を開始する準備ができました。", + "home-layout-4": "スターを付けてください", + "generate-token": "今すぐアップグレードして実稼働APIトークンを生成してください。", + "opensign-drive-1": "パンくずリンクをクリックすると、フォルダー階層内を簡単に移動し各フォルダー内の文書を表示できます。", + "opensign-drive-2": "追加ボタンをクリックして新しいフォルダーまたは文書を作成します。", + "opensign-drive-3": "このメニューを使用して文書を日付または名前で並べ替えます。", + "opensign-drive-4": "このメニューをクリックすると文書がリストビューで表示されます。", + "opensign-drive-5": "選択した並べ替えオプションに従って文書リストが表示されます。各文書の横にあるアイコンは現在のステータスを示します。", + "opensign-drive-6": "文書を右クリックすると、ダウンロード、名前変更、移動、削除などのオプションが表示されます。文書をクリックして開きます。", + "opensign-drive-7": "任意のフォルダーを右クリックしてオプションを表示します。'名前の変更'を選択してフォルダーの名前を変更するか、フォルダーをクリックしてその内容を移動します。", + "pdf-request-file-1": "文書に署名する必要がある署名者のリスト。", + "pdf-request-file-2": "文書に表示されるフィールドのいずれかをクリックして開始します。その後、必要な情報を入力できるようになります。", + "pdf-request-file-3": "必須フィールドをすべて入力したら'完了'をクリックします。その後、署名された文書をダウンロードできるようになります。送信者の設定によっては、すべての受信者が署名を完了すると完成した文書のコピーが完了証明書とともに受信される場合があります。", + "pdf-request-file-4": "すでに文書に署名している署名者のリスト。", + "pdf-request-file-5": "'すべて自動署名' をクリックすると、署名する予定のすべての場所で自動的に署名できます。このボタンをクリックする前に必ず文書を適切に確認してください。", + "pdf-request-file-6": "ページ番号 {{pagenumbers}} のフィールドに入力してください。識別しやすいように、すべて同じ色で強調表示されています。", + "placeholder-sign-1": "このリストから受信者を選択してウィジェットを追加します。ウィジェットを文書上にドロップすると、受信者名と同じ色でウィジェットが表示されます。", + "placeholder-sign-2": "'受信者を追加' ボタンをクリックすると、署名者をさらに追加できます。", + "placeholder-sign-3": "文書に受信者/署名者を追加するにはこのボタンをクリックします。", + "placeholder-sign-4": "ウィジェットをドラッグまたはクリックして文書に追加します。", + "placeholder-sign-5": "PDF ンテンツ領域には、テンプレートの既存のウィジェットがすでに表示されています。便宜上、これらのウィジェットは受信者の名前の色と一致し、簡単に識別できるようになります。", + "placeholder-sign-6": "'次へ' をクリックすると文書が保存されます。次のステップでは、受信者に送信するメールをカスタマイズしたり署名リンクをコピーして受信者と共有したりできます。", + "report-1": "'追加'ボタンをクリックして新しいテンプレートを作成します。テンプレートは、同じ構造とさまざまな署名者を持つ新しい文書を迅速に生成するように設計された再利用可能な文書です。たとえば、オンボーディング用の HR テンプレートには、'HR マネージャー'や'新入社員'などの事前定義されたロールを含めることができます。テンプレートを使用するたびに、'新入社員'の役割をさまざまな新入スタッフ メンバーに割り当てることができますが、'人事マネージャー'の役割は一定のままで、各新入社員のシームレスなオンボーディング プロセスが容易になります。", + "redirect": "'使用'ボタンをクリックして、既存のテンプレートから新しい文書を作成します。", + "bulksend": "既存のテンプレートを使用して、受信者のメールアドレスを入力するだけで複数の文書を一括送信するには、'一括送信'ボタンをクリックします。最大50人の受信者に送信できます。", + "option": "このメニューには、編集、削除、名前の変更、複製、共有などのその他のオプションが表示されます。利用可能なすべてのオプションの詳細については<1>ここをクリックしてください。<3>注: 既存のテンプレートに変更を加えるとそのテンプレートから今後作成されるすべての文書に適用されますが、既に送信された文書には影響しません。", + "signyour-self-1": "署名する前に好みのウィジェットを選択またはPDF上にドラッグして文書をカスタマイズします。各ウィジェットに最適な場所を選択して文書をニーズに合わせて調整します。", + "signyour-self-2": "この領域内の任意の場所にドラッグ&ドロップします。後でサイズ変更したり移動したりできます。", + "template-placeholder-1": "'役割の追加'ボタンをクリックするとさまざまな署名者の役割を追加できます。次の手順で各ロールにユーザーをアタッチできます。", + "template-placeholder-2": "役割を追加した後リストから1つを選択して、その受信者用のウィジェットを配置します。ウィジェットをクリックするか、文書上にドラッグすることができます。配置すると、ウィジェットは選択した役割と同じ色で表示されます。", + "template-placeholder-3": "'次へ'をクリックすると、現在のテンプレートが保存されます。保存後、必要に応じてこのテンプレートから新しい文書を作成するように求められます。", + "webhook-1": "今すぐアップグレードして Webhook を設定してください", + "Need your Signature": "このカードをクリックすると、審査を待っている文書のリストが表示されます。", + "Out for signatures": "このカードをクリックすると、署名を待っている文書のリストが表示されます。", + "Recent signature requests": "これはあなたの署名を待っている文書のリストです。", + "Recently sent for signatures": "これは、署名のために他の当事者に送信した文書のリストです。", + "Drafts": "これらは開始したものの送信が完了していない文書です。", + "public-template": "このビデオでは'https://opensign.me/your-username'のような、パーソナライズされた公開プロフィールの設定方法をご紹介します。また、タグラインをカスタマイズする方法や、テンプレートを公開署名用に公開する方法もご紹介します。", + "allowModify-widgets": "文書作成者によってすでに指定されているフィールドに加えて、これらのフィールドのいずれかを文書にドラッグ&ドロップできます。" + }, + "enter-email-plaholder": "メールアドレスを追加してEnterキーを押します", + "success-email-alert": "メールが正常に送信されました。", + "expired-doc-title": "期限切れの書類", + "expired-on-mssg": "この文書は{{expiredDate}}に有効期限が切れたため署名できなくなりました。", + "signature-validate-alert": "{{minRequiredCount}}個以上のチェックボックスを選択していることを確認してください。", + "signature-validate-alert-2": "このフィールドが正確に入力され、すべての要件を満たしていることを確認してください。", + "remaing-users": "残りのユーザー", + "Role": "ロール", + "additional-users": "アドオンユーザーを購入してください。", + "Quantity-of-users": "ユーザー数", + "Price": "価格", + "Total-price-for-next-time": "次回の合計金額", + "Proceed": "進む", + "Select": "選択", + "Add-seats": "席の追加", + "user-name-exist": "ユーザー名はすでに存在します", + "format": "形式", + "select-date-format": "日付形式を選択してください", + "quantity-of-credits": "プレミアムクレジットの数量", + "remaining-credits": "利用可能なプレミアムクレジット:", + "remaining-credits-help": "API文書の署名、一括送信、WebサイトへのOpenSign統合の埋め込みにはプレミアムクレジットを使用します。含まれているクレジットは {{allowedcredits}}個、追加で購入したクレジットは {{addoncredits}}個が残っています。チームまたはエンタープライズプランを使用している場合、アカウント管理者によってアカウントに制限が設定されていない限りこれらは社内のすべてのユーザー間で共有できるクレジットです。", + "additional-credits": "プレミアムクレジットを購入してください", + "quota-err-quicksend": "クォータに達しました。十分なクレジットがありません。", + "buy-credits": "プレミアムクレジットを購入する", + "rotate-right": "右回転", + "rotate-left": "左回転", + "rotate-alert-mssg": "このページ上のすべてのウィジェットが失われます。続行してもよろしいですか?", + "templateid": "テンプレートID", + "bulk-send-subcription-alert": "一括送信を使用するには、プロフェッショナルプランまたはチームプランにアップグレードしてください。", + "generate-test-token": "テストトークンを生成する", + "regenerate-test-token": "テストトークンを再生成する", + "help-test-token": "このトークンは、https://sandbox.opensignlabs.com/api/v1 エンドポイントでAPIをテストするために使用でき、無制限の文書署名を実行できます。サンドボックスAPIは自己署名証明書を使用して文書に署名するため、Adobeによって有効と認識されない可能性があることにご注意ください。テストが完了したら有料プランにアップグレードして実稼働用トークンを生成できます。", + "help-api-token": "このトークンは {{origin}}/api/v1エンドポイントにある本番環境APIへのアクセスに使用できます。有料プランでのみ生成できます。", + "reason": "理由", + "decline-by": "拒否/取り消し", + "document-declined": "書類が拒否されました", + "public-template-mssg-1": "OpenSignをReactまたはNext.jsプロジェクトに統合するには、次のコマンドを実行するだけです。", + "public-template-mssg-2": "プロジェクトにnpmまたはyarnが設定されていることを確認してください。Yarnを使用している場合は、npm installをyarn add @opensign/reactに置き換えてください。", + "public-template-mssg-3": "さらに詳細や例が必要ですか?", + "public-template-mssg-4": "アクセスしてください。", + "public-template-mssg-5": "最新のアップデート、詳細な文書、バージョン履歴についてはnpmを参照してください。", + "public-template-mssg-6": "このコードスニペットを使用する前に、このテンプレートを公開する必要があります。", + "public-template-mssg-7": "公開リンクを生成する前に、このテンプレートを公開する必要があります。", + "here": "ここ", + "copy-code": "コピー", + "copied-code": "コピーされました", + "Installation": "インストール", + "Usage": "使用法", + "insufficient-credits": "署名クレジットが不十分です", + "insufficient-credits-mssg": "現在この文書の所有者には、署名に必要なOpenSignクレジットがありません。さらに詳細な情報が必要な場合はオーナーにお問い合わせください。", + "angular-npm-mssg-1": "OpenSignをAngularプロジェクトに統合するには、次のコマンドを実行するだけです。", + "quota-mail-info-head": "月間メール制限", + "quota-mail-info": "サービス品質を維持しスパムを防止するために、OpenSignでは無料プランで月に最大15件のメールを送信できます。今すぐアップグレードすると無制限にメールを送信できます。", + "quota-mail-reset": "署名リクエストのメール クレジットは次の日にリセットされます。", + "quota-mail": "今月の署名リクエストメール数の制限である15件に達しました。引き続きメールを直接送信するには今すぐアップグレードしてください。", + "quota-mail-tip": "ヒント: 署名リクエストリンクを手動で共有することで、<1>無制限の文書に署名できます。", + "quota-mail-head": "クォータに達しました", + "unauthorized-modal": "この操作を実行する権限がありません。{{adminEmail}}に連絡してください。", + "sent-this-month": "今月送信された", + "available-seats": "空席あり", + "buy-users": "さらにユーザーを購入する", + "isenable-otp": "OTP検証を有効にする", + "isenable-otp-help": { + "p1": "ワンタイムパスワード(OTP)を使用した検証プロセスを有効にしますか?", + "p2": "このオプションを選択すると、OTP検証が有効になります。ユーザーはメールで確認コードを受け取り、文書に署名するために入力する必要があります。", + "p3": "このオプションを選択するとOTP検証が無効になり、ユーザーは追加の手順を行わずに文書に直接署名できるようになります。", + "p4": "文書の署名要件に最も適したオプションを選択してください。" + }, + "advanced-options": "詳細オプション", + "hide-advanced-options": "詳細オプションを非表示にする", + "download-files": "ファイルをダウンロードする", + "download-pdf": "PDFをダウンロード", + "pdf-certificate": "PDF + 証明書をダウンロード", + "document-logs": "文書ログ", + "server-down": "{{appName}}サーバーに接続できません。{{appName}}をセルフホスティングしている場合は、文書のすべての手順が正しく行われていることを確認してください。{{appName}}をローカルで実行している場合は、間違ったポート番号を介してアクセスしている可能性があります。", + "admin-exists": "管理者はすでに存在します。ユーザーを管理するには管理者の資格情報を使用してアプリにログインしてください。", + "enable-tour": "ツアーを有効にする", + "istourenabled-help": { + "p1": "これにより、署名者向けのガイド付きツアーが可能になり、署名プロセス中に指示が提供されます。", + "p2": "これによりガイド付きツアーが無効になり、より高速で中断のない署名体験が保証されます。", + "p3": "ヒント: 署名者が{{appName}}に精通しており頻繁に使用する場合は、よりシームレスなエクスペリエンスを得るためにガイド付きツアーを無効にすることをお勧めします。文書署名のニーズに最適なオプションを選択してください。" + }, + "form-title-1": "文書フロー設定", + "form-title-2": "セキュリティ設定", + "public-tour-message": "共有可能なリンクを生成するには、テンプレートを公開する必要があります。", + "add-user-template": "フィールドを追加する前に、ロールを追加する必要があります。", + "pdf-uncompatible": "このPDFには互換性がありません。{{appName}} にお問い合わせください。", + "text-field-tour": "'事前入力'フィールドは、文書を送信する前に事前に入力する必要があります。署名者に入力してもらう必要がある場合は代わりに署名者フィールドを使用してください。", + "attach-signer-tour": "すべてのロールに署名者をアタッチする必要があります。このアイコンをクリックするとそれを行うことができます。署名者を選択するとその役割に関連付けられている同じ色で表示されるすべてのフィールドに署名者が関連付けられます。", + "allowed-signature-types": "許可される署名の種類", + "at-least-one-signature-type": "少なくとも 1 つの署名タイプを有効にする必要があります。", + "expect-default-one-signature-type": "デフォルトとは別に1つの追加の署名タイプを有効にしてください。", + "add-signer-note": "注 - この連絡先は連絡先に保存されます", + "allowed-signature-types-help": { + "p1": "この署名設定は、署名者が使用できる署名オプションを制御します。文書の署名時に選択した署名タイプのみが署名ウィジェットに表示されます。たとえば、環境設定で'描画'オプションのみを選択した場合、署名者には署名ウィジェットで'描画'オプションのみが表示され、他の 3 つのオプションは使用できなくなります。", + "l1": "指またはスタイラスを使用して、画面上で直接手書きの署名を作成します。", + "l2": "名前を入力し、さまざまなフォント スタイルから選択して署名を作成します。", + "l3": "署名の既存のデジタル バージョンをアップロードします。", + "l4": "設定の'自分の署名'に保存されている事前設定された署名スタイルを使用します。" + }, + "notify-on-signatures": "署名で通知する", + "notify-on-signatures-help": { + "p1": "署名者が文書に署名するたびに文書の作成者はメール通知を受け取ります。", + "note": "注: この設定に関係なく、署名された文書と完了証明書が添付された完了メールは常にすべての署名者と文書所有者に送信されます。" + }, + "expiry-date": "有効期限", + "expiry-date-updated": "有効期限は{{newexpirydate}}まで正常に延長されました", + "expiry-date-error": "現在の有効期限より後の新しい有効期限を入力してください", + "duplicate-template-alert": "このテンプレートの複製を作成してもよろしいですか?", + "duplicate-template-created": "複製テンプレートが正常に作成されました。", + "delete-page": "ページの削除", + "merge-pdf": "PDFを結合", + "add-pages": "ページを追加する", + "reorder-pages": "ページを並べ替える", + "delete-alert": "単一ページを削除できません", + "delete-alert-2": "このページを削除してもよろしいですか?", + "delete-note": "注: このページを削除すると、元に戻すことはできません。", + "Rotation-alert": "ページを回転する", + "bulk-import": "一括インポート", + "contacts-file": "連絡先ファイル (xlsx, csv)", + "import-guideline": "名前、メール、オプションの電話番号の列を含むCSVまたはExcelファイルをアップロードします。最初の100レコードのみがインポートされます。", + "download-sample": "サンプルファイルをダウンロードする", + "100-records-only": "現在、インポートできるレコードは最大 100 件までです。", + "csv-excel-support-only": "CSV、XLSX、XLSのいずれかの形式でファイルをアップロードします。", + "contact-imported": "{{imported}}件の連絡先がインポートされました。{{failed}}件の連絡先をインポートできませんでした。", + "invalid-data": "無効なデータ", + "delete-folder-alert": "このフォルダを削除してもよろしいですか?", + "delete-folder-alert-1": "削除できません: フォルダーを空にしてください。", + "defaultSign-alert": "{{widgetsType}}ウィジェットは自動署名に使用できません。", + "embed-heading": "{{appName}}テンプレートを埋め込む", + "public-template-edit-title": "公開テンプレートの編集", + "public-template-edit-mssg": "公開テンプレートを直接編集することはできません。変更を加えるにはテンプレートが非公開に設定されるため、後で再度公開する必要があります。続けますか?", + "agree-p1": "以下を読んで理解したことを確認します", + "agree-p2": "電子記録と署名の開示", + "agree-p3": "電子記録と署名の使用に同意します。", + "agrre-button": "続行することを確認し同意します", + "term-cond-title": "利用規約", + "term-cond-h": "電子記録と署名の開示", + "term-cond-p1": "この電子記録および署名の開示 ('開示') は、文書作成者 ('送信者') と署名者 ('あなた') の間の合意であり、{{appName}} プラットフォーム ('プラットフォーム') を通じて促進されます。 {{appName}}経由で文書に署名すると、この開示に概説されている条件に同意したことになります。続行する前によくお読みください。", + "term-cond-h1": "1. 目的と範囲", + "term-cond-p2": "この開示は、送信者によって送信され、{{appName}}プラットフォームを通じてお客様が署名した文書の電子記録と署名の使用を規定します。同意すると次のことを承認したことになります。", + "term-cond-p3": "{{appName}}経由で文書を電子的に受け取り署名します。", + "term-cond-p4": "電子署名には法的拘束力があり手書きの署名と同等です。", + "term-cond-h2": "2. 電子記録および署名の使用への同意", + "term-cond-p5": "この開示に同意することにより次のようになります。", + "term-cond-p6": "あなたは{{appName}}を使用して送信者と電子的に取引することに同意し、この同意は撤回されるまで有効であることを理解するものとします。", + "term-cond-p7": "あなたは{{appName}}を使用して文書を電子的に確認し、署名し、返送することに同意するものとします。", + "term-cond-p8": "この同意は送信者によって提供された特定の文書にのみ適用されます。", + "term-cond-h3": "3. 同意を撤回する権利", + "term-cond-p9": "あなたには次の方法で電子記録および署名の使用に対する同意を撤回する権利があります。", + "term-cond-p10": "通信で提供された連絡先情報を使用して、送信者に直接連絡します。", + "term-cond-p11": "署名プロセスを完了する前に送信者に通知します。", + "term-cond-h4": "4. ハードウェアおよびソフトウェアの要件", + "term-cond-p12": "{{appName}}を使用して文書に署名するには以下が必要です。", + "term-cond-p13": "インターネットにアクセスできるデバイス。", + "term-cond-p14": "JavaScriptが有効になっている互換性のあるWebブラウザ。", + "term-cond-p15": "通知と署名された文書を受信するためのメールアカウント。", + "term-cond-p16": "これらの要件が変更された場合、送信者または{{appName}}が更新をお客様に通知します。", + "term-cond-h5": "5. 記録の保存と紙のコピーの要求", + "term-cond-p17": "あなたは電子署名された文書にアクセスして保持できるようにする責任があります。{{appName}}は、署名プロセスが完了した直後に署名された文書をダウンロードまたは印刷するためのツールを提供します。", + "term-cond-p18": "電子署名された文書の紙のコピーを希望する場合は、送信者に直接要求することができます。送信者は適用される法律で禁止されていない限り、紙のコピーの提供に対して妥当な料金を請求することがあります。", + "term-cond-h6": "6. 承認と同意", + "term-cond-p19": "続行すると次のことが行われます。", + "term-cond-p20": "この開示に記載されているように、電子文書にアクセスして確認できることを確認します。", + "term-cond-p21": "送信者との指定されたトランザクションに対して電子記録と署名を使用することに同意します。", + "term-cond-p22": "{{appName}}は取引を促進するプラットフォームであり、契約の当事者ではないことを理解してください。", + "term-cond-h7": "7. 法的効果", + "term-cond-p23": "電子署名は{{appName}}を通じて行われます:", + "term-cond-p24": "米国のE-SIGN法、EUのeIDAS規制、日本の電子署名法などに適用される電子署名法に準拠しています。", + "term-cond-p25": "署名された文書について、お客様と送信者の間で法的拘束力を持ちます。", + "term-cond-h8": "8. プラットフォームの役割と責任の制限", + "term-cond-p26": "{{appName}}は電子取引を容易にするプラットフォームとして機能します。送信者が送信した文書の内容、有効性、強制力については責任を負いません。文書またはその署名に関連する紛争または問題は、お客様と送信者の間で直接解決する必要があります。", + "term-cond-h9": "9. 契約の終了", + "term-cond-p27": "送信者によって別途指定されていない限り、あなたの同意は現在の取引にのみ適用されます。{{appName}}は利用規約またはポリシーに違反した場合、プラットフォームへのアクセスを終了する権利を留保します。", + "term-cond-p28": "'同意する' を選択すると、この電子記録と署名開示の条件を理解して同意し、送信者が {{appName}} を通じて提供した文書に電子署名することに同意したことになります。", + "term-cond-p29": "この開示に関してご質問がある場合は、送信者に直接お問い合わせください。{{appName}}のテクニカル サポートについては、次のサイトをご覧ください。", + "term-cond-p30": "またはメールで", + "js-snippet-msg": "{{appName}}テンプレートをHTMLウェブサイトまたはランディング ページに統合するには、以下のコードを使用できます。", + "js-snippet-msg-1": "TemplateIdは以下から取得できます。", + "js-snippet-msg-2": "テンプレートの管理", + "js-snippet-msg-3": "ページ。", + "agrrement-alert": "続行するには電子記録と署名の開示に同意する必要があります。", + "webhook-already-exists": "URLはすでに存在します。別のものをお試しください。", + "webhook-must-be-secure": "Webhook URLは安全なhttps://を使用する必要があります", + "provide-test-token": "APIテストトークンを生成してください", + "invalid-redirect-url": "有効なリダイレクトURLを入力してください。", + "auto-sign-mssg": "すべてに自動署名", + "already-exist-signer": "選択した署名者はすでに存在しています", + "change-signer": "署名者の変更", + "signyour-self-button": "他の人を追加せずに自分で文書に署名するには、このオプションを使用します", + "requestsign-button": "このオプションを使用して、他人と自分自身の両方に署名を要求します。", + "signyour-self-description": "このフォームを使用して、他の人を追加せずに自分で文書に署名します", + "requestsign-description": "このフォームを使用して、他の人や自分自身に署名を依頼してください。", + "template-form-description": "このフォームを使用して、文書用の再利用可能なテンプレートを作成します。", + "allow-modify": "変更を許可する", + "allow-modify-help": { + "p1": "署名プロセス中に文書への変更を許可しますか?", + "p2": "このオプションを選択すると、署名者は既存のウィジェットの上に署名、イニシャル、スタンプ、テキストなどの要素を追加できます。", + "p3": "このオプションを選択すると、署名者が署名プロセス中に文書に追加を行うことが制限されます。" + }, + "signature-setting": "署名設定", + "activation-key": "アクティベーションキー", + "paid-selfhost-help": "詳細については、{{appName}}までお問い合わせください。", + "remaining-credits-selfhost-help": "API文書の署名、ウェブサイト上の{{appName}}統合の一括送信にプレミアム クレジットを使用します。含まれているクレジットは {{allowedcredits}} 個、追加で購入したクレジットは {{addoncredits}} 個が残っています。", + "signature-type": "あなたの署名", + "initial-type": "あなたのイニシャル", + "redirect-url": "リダイレクトURL", + "bulk-send": "一括送信", + "select-timezone": "タイムゾーン", + "current-time": "現在時刻", + "email-help": "セキュリティ上の理由により、メールアドレスを変更することはできません。新しいメール アドレスを使用して別の無料アカウントを作成してください。", + "doc-sent": "書類は正常に送信されました。", + "no-signer": "取り除く", + "and": "そして", + "make-public": "公開する", + "general": "一般的な", + "request-email": "リクエストメール", + "completion-email": "完了メール", + "variables-use": "使用する変数", + "send-to-sign": "あなたに署名を要求しました", + "use-template": "テンプレートを使用する", + "contact-already-exists": "連絡先はすでに存在します。", + "docx-error": "現在、DOCXファイルの処理でいくつかの問題が発生しています。PDFファイルをアップロードしてください", + "docx-error-contact": "またはsupport@opensignlabs.comまでご連絡ください。", + "excel-error": "現在、Excelファイルの処理で問題が発生しています。PDFファイルをアップロードしてください", + "excel-error-contact": "またはsupport@opensignlabs.comまでご連絡ください。", + "agreement-note": "注: これに同意しても、すぐに文書に署名するわけではありません。これにより、文書を電子的に確認することのみが可能になります。全文を読んで、その後署名するかどうかを決定する機会があります。", + "draft-template-info-p1": "テンプレートを公開するには、テンプレートに 1 つのロールが含まれているか、複数のロールが含まれている場合は、追加のロールがすべて署名者に割り当てられている必要があります。割り当てられていない公開 ロールは空のままにし、最初の位置に配置する必要があります。", + "visit-below-link": "詳細については、以下のリンクにアクセスしてください -", + "storage-help": "BYOCを有効にすると独自のS3ストレージに接続できるため、ファイルは完全に制御下に残り外部コピーは保持されません。データの自律性が重要である場合はTeamsにアップグレードしてこの機能のロックを解除することを検討してください。", + "daily-quota-reached": "1 日のノルマに達しました。サポートが必要な場合は、quotas@opensignlabs.com までお問い合わせください。", + "enabled-signature-type": "有効な署名タイプ", + "enabled-signature-type-help": "'有効な署名タイプ'設定により、組織全体でどの署名オプションを使用できるかが決まります。たとえば、'描画'オプションを無効にすると、組織のメンバーには署名ウィジェットにそのオプションが表示されなくなりますが、他の 3 つのオプションには引き続きアクセスできます。", + "indexing-public-profile": "検索エンジンによる公開 プロフィールのインデックス作成を許可する", + "user-created-successfully": "ユーザーが正常に作成されました。", + "only-15-reminder-allowed": "最大15個の自動リマインダーを設定できます。たとえば、'TimeToComplete'が 15日で、'RemindOnceInEvery'が1日の場合、リマインダーの最大数は15個に達します。それに応じて設定を調整してください。", + "rate-your-experience": "{{appName}}を使ってみてどうでしたか?", + "thanks-for-feedback": "フィードバックをお寄せいただきありがとうございます 🙏", + "share-your-feedback": "フィードバックを共有してください", + "share-your-review": "レビューを共有する", + "please-select-rating": "評価を選択してください", + "feedback-optional": "フィードバック(オプション)", + "feedback-saved": "フィードバックは保存されました。", + "feedback-save-error": "フィードバックを保存できません。もう一度お試しください。", + "date-format": "日付形式", + "document-deleted": "文書が削除されているか、アクセス権がありません。送信者にご連絡ください。", + "save-as-template-?": "この文書をテンプレートとして保存してもよろしいですか?", + "go-to-manage-templates": "'テンプレートの管理'に移動します", + "template-created": "テンプレートが作成されました", + "how-would-you-like-to-proceed?": "どのように進めていきますか?", + "failed-to-load-refresh-page": "文書の読み込みに失敗しました。このページを更新してみてください。", + "document-has-been-signed": "文書は正常に署名されました。", + "document-has-been-signed-by-you": "文書はあなたによって正常に署名されました。", + "participant-completed-signing": "参加者全員が署名プロセスを完了しました。", + "you-will-receive-email-shortly": "✅それだけです!すぐに確認メールが届きます。", + "please-provide-templateid": "テンプレートIDを入力してください", + "this-template-is-not-public": "このテンプレートは公開されていません", + "invalid-templateid": "無効なテンプレートID", + "contact-billing-at-opensign": "座席を追加するには、OpenSign™までお問い合わせください。<1>billing@opensignlabs.com", + "title-length-alert": "タイトルの長さは最大250文字です。", + "note-length-alert": "メモの長さは最大200文字です。", + "description-length-alert": "説明の長さは最大500文字です。", + "fix-&-resend-document": "文書を修正して再送信", + "do-you-want-recreate-document?": "これによりすべてのフィールドがそのままの状態でこの文書から草案が作成されます。この文書を再作成してもよろしいですか?", + "start-editing": "編集を開始する", + "unsaved-changes-discard-them?": "未保存の変更があります。それらを破棄しますか?", + "yes-discard": "はい、破棄します", + "LTV-enabled-signatures": "LTV 対応の署名", + "BETA": "ベータ", + "two-factor-authentication": "二要素認証", + "2fa-help-text": "二要素認証(2FA)はサインインにパスワード以上のものを要求することでアカウントに追加のセキュリティ層を追加します。", + "2fa-help-bullet1": "パスワードと確認コードの両方を要求することでセキュリティを強化します。", + "2fa-help-bullet2": "確認コードは、デバイス上の認証アプリによって生成されます。", + "2fa-help-bullet3": "パスワードが漏洩した場合でもアカウントを保護します。", + "setup-2fa": "2FAのセットアップ", + "setup-2fa-again": "2FAを再度セットアップする", + "2fa-setup-intro": "二要素認証でアカウントを保護します。有効にすると、サインインするたびに認証アプリからコードを入力する必要があります。", + "scan-qr-code": "QRコードをスキャン", + "scan-qr-instructions": "Google Authenticator、Microsoft Authenticator、Authyなどの認証アプリを使用してこのQRコードをスキャンします。", + "manual-setup-instructions": "コードをスキャンできませんか?この秘密キーを使用して、認証アプリを手動でセットアップできます。", + "secret-key": "秘密キー", + "copied-to-clipboard": "クリップボードにコピーされました", + "copy-to-clipboard": "クリップボードにコピー", + "recovery-codes": "リカバリーコード", + "recovery-codes-instructions": "これらのリカバリコードを安全な場所に保存します。認証アプリにアクセスできなくなった場合はこれらのワンタイムコードのいずれかを使用してサインインできます。", + "download-recovery-codes": "リカバリーコードをダウンロードする", + "verification-code": "検証コード", + "enter-code-from-authenticator-app": "認証アプリから6桁のコードを入力してください", + "verification-code-required": "確認コードが必要です", + "verification-code-invalid": "無効な確認コードです。もう一度試してください。", + "2fa-enabled": "2FA有効", + "2fa-enabled-successfully": "二要素認証が正常に有効になりました", + "2fa-setup-complete": "セットアップ完了!", + "2fa-setup-complete-instructions": "これであなたのアカウントは二要素認証で保護されました。サインインするたびに確認コードを入力する必要があります。", + "two-factor-verification": "二要素認証", + "enter-verification-code-instructions": "続行するには認証アプリから6桁の確認コードを入力します。", + "recovery-code": "リカバリーコード", + "enter-recovery-code-help": "リカバリコードのいずれかを入力してください", + "recovery-code-required": "リカバリーコードが必要です", + "use-verification-code-instead": "代わりに確認コードを使用してください", + "use-recovery-code-instead": "代わりにリカバリーコードを使用してください", + "regenerate-2fa-remove-existing": "二要素認証を再生成してもよろしいですか?この操作により既存の認証設定が削除されます。", + "use-passkey": "パスキーを使用してサインインする", + "security-section": "安全", + "passkey-authentication": "パスキー認証", + "passkey-not-supported": "お使いのブラウザまたはデバイスはパスキー認証をサポートしていません", + "passkey-description": "パスキーはパスワードに代わる強力でフィッシング耐性のある代替手段を提供します。指紋、顔認識、またはデバイスのPINを使用して安全にサインインできます。", + "passkey-tooltip": "パスキーはパスワードに代わるよりシンプルかつ安全な手段です。デバイスにすでに保存されている指紋や顔認識などの生体認証データを使用します。", + "security-section-help": "パスキーや認証方法などのセキュリティオプションを管理してアカウントを保護します。", + "passkey-register": "パスキーを登録する", + "passkey-register-another": "別のパスキーを登録する", + "passkey-registered": "パスキーが登録されました", + "passkey-registering": "パスキーを登録しています...", + "passkey-registered-success": "パスキーが正常に登録されました。", + "passkey-registration-failed": "パスキーの登録に失敗しました", + "passkey-auth-failed": "パスキー認証に失敗しました", + "passkey-missing-user-info": "ユーザー情報は必須です", + "passkeys-list": "自分のパスキー", + "default-passkey": "自分のパスキー", + "passkey-rename": "名前の変更", + "passkey-delete": "削除", + "passkey-rename-title": "パスキーの名前を変更する", + "passkey-delete-title": "パスキーの削除", + "passkey-delete-confirm": "パスキー\"{{name}}\"を削除してもよろしいですか?", + "passkey-name": "パスキー名", + "passkey-name-placeholder": "このパスキーのわかりやすい名前を入力してください", + "passkey-renamed-success": "パスキーの名前が正常に変更されました", + "passkey-deleted-success": "パスキーが正常に削除されました", + "passkey-rename-failed": "パスキーの名前変更に失敗しました", + "passkey-delete-failed": "パスキーの削除に失敗しました", + "processing": "処理中...", + "today": "今日", + "yesterday": "昨日", + "days-ago": "{{day}}日前", + "verify-with-passkey": "パスキーで認証する", + "verify-with-otp": "OTPで確認する", + "verification": "検証", + "verify-account": "アカウントを確認してください", + "verify-identity": "身元を確認する", + "passkey-verification-failed": "パスキーの検証に失敗しました。もう一度試すかOTPを使用してください。", + "security-auth-help": { + "p1": "アカウントのセキュリティ設定を管理してデータを安全に保ちます。OpenSignはアカウント保護を強化するための高度な認証方法をサポートしています。", + "2fa-auth-help": "2FAを有効にしてセキュリティ層を追加します。これには、パスワードの後に​​認証アプリからの確認コードを入力する必要があります。", + "passkey-auth-help": "生体認証またはデバイスベースの認証によるパスワードなしのサインインにはパスキーを使用し、強力なセキュリティと利便性の両方を提供します。" + }, + "signer-already-present": "署名者はすでに存在します", + "kiosk-sign": "キオスクサイン", + "dont-have-access-to-template": "テンプレートが削除されているかアクセス権がありません。送信者にご連絡ください。", + "kiosk-info": "キオスクモードを使用すると対面での署名を迅速かつ効率的に収集できます。すべての署名者が物理的に存在するトレードショー、イベント、またはウォークインシナリオに最適です。", + "learn-more": "もっと詳しく知る", + "finish-mssg": "文書を終了してもよろしいですか?", + "review": "レビュー", + "next-field": "次のフィールド", + "required-mssg": "{{totalWidget}}個中{{leftRequiredWidget}}個のフィールドが残っています", + "verify-document": "文書の検証", + "verify-document-signature": "文書の署名を検証する", + "select-pdf-document": "PDF文書を選択", + "selected-file": "選択したファイル", + "verify-signature": "署名の検証", + "verification-status": "検証ステータス", + "verification-in-progress": "検証中...", + "verification-results-will-appear-here": "検証結果がここに表示されます", + "please-select-pdf": "有効なPDFファイルを選択してください", + "please-select-file-to-verify": "確認するファイルを選択してください", + "no-signature-found": "文書内に署名が見つかりませんでした", + "error-verifying-pdf": "PDFの検証中にエラーが発生しました", + "signature-valid-basic": "署名は有効です", + "signature-invalid-basic": "署名が無効です", + "all-signatures-verified-convincing": "文書の検証済み: すべての署名が正常に検証されました。", + "some-signatures-invalid-basic": "一部の署名が無効です", + "no-signatures-processed": "署名は処理されませんでした", + "unnamed-signature-field": "名前のない署名フィールド", + "error-processing-signature": "署名の処理中にエラーが発生しました", + "signer-info-not-available": "署名者情報が利用できません", + "cert-validity-not-checked": "証明書の有効性がチェックされていません", + "valid": "有効", + "expired-or-not-yet-valid": "有効期限が切れているか、まだ有効ではありません", + "valid-from": "有効期限", + "to": "から", + "signer": "署名者", + "issuer": "発行者", + "not-available": "利用不可", + "not-performed": "未実施", + "missing-acrofield-dict": "アクロフィールド辞書がありません", + "signature-dictionary-not-found-or-invalid": "署名辞書が見つからないか無効です", + "missing-or-invalid-byterange": "ByteRangeが見つからないか無効です", + "missing-or-invalid-contents": "コンテンツが欠落しているか無効です", + "missing-signature-contents": "署名内容が欠落しています", + "invalid-signature-hex-format": "署名の 16 進形式が無効です", + "unsupported-signature-format-not-signeddata": "サポートされていない署名形式です - SignedDataではありません", + "signer-certificate-not-found": "署名者証明書が見つかりません", + "no-certificates-in-signature": "署名に証明書がありません", + "no-signer-info-in-pkcs7": "PKCS#7に署名者情報がありません", + "could-not-parse-signer-info": "署名者情報を解析できませんでした", + "not-calculated": "計算されていません", + "not-found-in-signature": "署名に見つからない", + "readonly-error": "読み取り専用の{{widgetName}}ウィジェットにはデフォルト値が必要です。またはオプションにすることもできます。", + "choose-one": "1つ選択してください", + "search-templates": "テンプレートを検索…", + "search-documents": "文書を検索…", + "search-contacts": "連絡先を検索…", + "add-role-alert": "少なくとも1つの役割を追加してください", + "edit-draft": "草案の編集", + "invalid-email-found": "無効なメールが見つかりました: {{email}}", + "duplicate-email-found": "重複したメールが見つかりました: {{email}}", + "vertical": "垂直", + "horizontal": "水平", + "billing": "請求する", + "console": "コンソール", + "prefill-widget": "事前入力ウィジェット", + "action-prohibited": "このアクションは、メール ドメインでは許可されていません。サポートが必要な場合は、管理者にお問い合わせください。", + "must-have-at-least-one-vacant-role": "テンプレートを'公開'に設定する前に、少なくとも 1 つのロールの割り当てを解除する必要があります。", + "remove-duplicate": "重複したオプションを削除してください", + "prefill-bulk-error": "プレフィル ウィジェットが追加されている場合、一括送信は許可されません。続行するには、事前入力ウィジェットを削除してください。", + "session-expired-title": "セッションが期限切れになりました", + "access-denied": "アクセスが拒否されました", + "upgrade": "アップグレード", + "do-not-access-app": "このアプリケーションにアクセスできません。", + "dont-have-access": "アクセス権がありません。", + "valid-email-alert": "有効なメールアドレスを入力してください。", + "otp-not-validate": "OTPが無効です。", + "domain-not-allowed": "このドメインは許可されていません", + "atleast-one-recipient-alert": "少なくとも1人の受信者を追加してください。", + "incorrect-password-or-decryption-failed": "パスワードが間違っているか、復号化に失敗しました。", + "incorrect-password-for-file": "ファイルのパスワードが正しくありません: {{file}}", + "error-uploading-pdf": "PDF のアップロード中にエラーが発生しました。", + "provide-password": "パスワードを入力してください。", + "only-pdf-allowed": "PDF ファイルのみが許可されます。", + "invalid-username-password-region": "ユーザー名/パスワードまたは地域が無効です。", + "pfx-extension-alert": "拡張子が.pfxのファイルをアップロードしてください。", + "email-already-exist": "メールはすでに存在します", + "branding": "ブランディング", + "branding-help": "ブランディングはアプリにホワイトラベルを提供します", + "custom-sub-domain": "カスタムサブドメイン", + "app-name": "アプリ名", + "provide-domain-name": "ドメイン名を入力してください", + "provide-app-name": "アプリ名を入力してください", + "logo": "ロゴ", + "upload-app-logo": "アプリのロゴをアップロードする", + "prefill-unfilled-widget": "次の必須フィールドを空のままにすることはできません: {{emptyWidget}}続行するには入力してください。", + "Dashboard": "ダッシュボード", + "Analytics": "分析", + "Templates": "テンプレート", + "Need your sign": "あなたの署名が必要です", + "In Progress": "進行中", + "Completed": "完了", + "Drafts": "下書き", + "Declined": "拒否されました", + "Expired": "期限切れ", + "Contactbook": "連絡帳", + "My Signature": "自分の署名", + "API Token": "APIトークン", + "Webhook": "Webhook", + "Preferences": "環境設定", + "Teams": "チーム", + "Users": "ユーザー", + "Drive": "ドライブ", + "Branding": "ブランディング", + "Mail": "郵便", + "Storage": "ストレージ", + "Signing certificate": "署名証明書", + "General": "一般的な", + "Organizations": "組織", + "OrgAdmins": "組織管理者", + "Debug Pdf": "デバッグPDF", + "New Document": "新しい文書", + "subscription": "サブスクリプション", + "Draft document": "草案文書", + "Draft template": "草案テンプレート", + "Public sign": "公共の標識", + "Signup": "サインアップ", + "delete-contact": "連絡先の削除", + "total-records-found": "見つかったレコードの合計: {{count}}", + "Invalid-records-found": "無効なレコードが見つかりました: {{records}}", + "previous": "前の", + "page-n-of-n": "ページ {{currentPage}} / {{totalPages}}", + "import": "インポート", + "search": "検索", + "viewed-on": "閲覧日: {{ViewedOn}}", + "signed-on": "署名済み: {{SignedOn}}", + "hide": "隠す", + "show-more": "もっと見る", + "browse-or-drag-to-replace-existing-file": "新しいファイルを参照するかドラッグ&ドロップして既存のファイルを置き換えます", + "optional-details": "オプションの詳細", + "hide-optional-details": "オプションの詳細を非表示にする", + "mail-adapter-subscription-alert": "カスタムSMTPをセットアップするには、プロフェッショナルプランまたはチームプランにアップグレードしてください。", + "connect-to-mail": "Gmailに接続する", + "custom-smtp": "カスタムSMTP", + "default-smtp": "{{appName}}のデフォルトSMTP", + "host": "ホスト", + "port": "ポート", + "sender-email": "送信者のメール", + "username": "ユーザー名", + "use-default-mail-adapter": "署名要求メールの送信に{{appName}}のデフォルトのメールサーバーを使用してもよろしいですか?受信トレイの配信性を向上させるために独自のGmailサーバーまたはSMTPサーバーを使用することをお勧めします。", + "verification-code-sent-registered-email": "登録のメールアドレス<1>{{useremail}}に確認コードが送信されました。設定を確認してください。以下の欄にコードを入力してください。", + "smpt-credentials": "SMTP認証情報", + "delete-account": "アカウントを削除する", + "delete-account-que": "アカウントを削除してもよろしいですか?", + "delete-account-que-user": "このユーザーと関連するすべてのデータを完全に削除しようとしています。この操作は元に戻すことができません。", + "user-deleted-successfully": "ユーザーと関連するすべてのデータが正常に削除されました。", + "account-deletion-request-sent-via-mail": "確認リンクをメールで送信しました。リクエストを承認してアカウントの削除を完了します。", + "type-exact-email-delete": "正確なメールを入力して削除を有効にします", + "email-does-not-match": "メールが一致しません。", + "please-type-to-confirm": "確認のため<1>{{userEmail}>を入力してください。:", + "email-settings": "メール設定", + "email-settings-help": "署名リクエストメールの受信トレイ到達性を向上させるために、独自のメールプロバイダーに接続できます。次のオプションのいずれかを選択します。", + "connect-to-gmail": "Gmailに接続します。", + "connect-to-gmail-help": "Gmailアカウントを使用して署名リクエストのメールを自分の受信箱から直接送信すると、配信率と信頼性が向上します。", + "connect-to-smtp": "カスタムSMTP:", + "connect-to-smtp-help": "ドメイン経由でメールを送信するには、カスタム SMTP サーバーを使用します。このオプションを使用すると、メール インフラストラクチャを完全に制御できるようになり、配信性とブランドの一貫性が向上します。", + "connect-to-default": "必要に応じて、{{appName}}のデフォルトのメール サーバーを使用することもできますが、最適な結果を得るには独自のメール サーバーを使用することをお勧めします。", + "email-settings-redirect-message": "この設定はコンソールからメインメニューの「設定」→「環境設定」に移動されました。このページは今後のバージョンでは削除される予定です。", + "go-to-preferences-menu": "'環境設定'メニューに移動します", + "document-download-filename-format": "文書ダウンロードのファイル名の形式", + "preview": "プレビュー:", + "download-filename-format-help": "ダウンロードしたPDFに名前を付ける方法を選択します。選択内容はプロフィールに保存され、アプリ全体で使用されます。", + "delete-action-prohibited": "この行為は許可されていません。管理者に連絡してアカウントの削除をリクエストしてください。", + "not-verified": "未検証", + "verified": "確認済み", + "expires": "有効期限が切れます", + "fix-resend-error": "この文書には事前入力ウィジェットが含まれているため、修正して再送信することはできません。", + "duplicate-template-error": "このテンプレートには事前入力ウィジェットが含まれているため、複製できません。", + "save-as-template-error": "この文書には事前入力ウィジェットが含まれているため、テンプレートとして保存できません。", + "redirecting-you-in": "{{redirectTimeLeft}}秒後にリダイレクトします...", + "pdf-tools-tour": "これらのボタンをクリックして、ページの追加、削除、並べ替え、回転、ズームを行います。", + "widgets": "ウィジェット", + "prefill-tour": "このオプションを使用して、文書を受信者に送信する前に事前に情報を入力します。", + "empty-prefill-error": "次の必須フィールドを空のままにすることはできません。", + "please-fill-out": "続行するには、記入してください。", + "custom-signing-certificate": "カスタム署名証明書", + "signing-certificate-help": "すべての文書と完了証明書に署名するために使用される独自の文書署名証明書をアップロードできます。証明書ファイルは、PFX 形式の P12 証明書である必要があります。", + "certificate-file-p12-in-PFX-format": "証明書ファイル (PFX形式のp12証明書)", + "password-of-pfx-file": "pfxファイルのパスワードを入力してください", + "update": "アップデート", + "use-default-certificate": "デフォルトの{{appName}}証明書を使用する", + "upgrade-to-team-plan": "チームプランにアップグレード", + "setup-file-storage": "ファイルストレージのセットアップ", + "save-and-activate": "保存して有効化する", + "logging-out-to-apply-settings": "新しい設定を適用するためにログアウトしています", + "reconnect-to-default": "{{appName}} に再接続します", + "active-file-adapter": "アクティブなファイルアダプター", + "file-adapter-unique-name": "ファイルアダプターの一意の名前", + "unique-name-for-file-adapter": "ファイルアダプターの一意の名前を入力してください", + "storage-provider": "ストレージプロバイダー", + "enter-bucket-name": "バケット名を入力してください", + "enter-space-name": "スペース名を入力してください", + "enter-region-of-bucket": "バケットの領域を入力してください", + "enter-region-of-space": "空間領域を入力してください", + "enter-access-key": "アクセスキーを入力してください", + "enter-secret-access-key": "シークレットアクセスキーを入力してください", + "otp-email": "確認コードを送信しました", + "save-as-temp-warn": "注: この文書には事前入力されたウィジェットが含まれていますが、これらはベース文書にすでに組み込まれているため、自動的に削除されます。", + "edit-document": "文書の編集", + "modify": "修正する", + "merge-certificate-to-pdf": "証明書をPDFに結合", + "merge-cc-to-pdf-help": { + "p1": "これにより、完了証明書が最終的な PDF 文書に確実に含まれるようになります。ただし、一度結合すると、証明書をメインの文書から分離することはできないことに注意してください。", + "p2": "結合しないことを選択した場合、完了証明書は署名済みの文書とともに別の PDF ファイルとして提供されます。" + }, + "read-only-date-error": "読み取り専用の日付ウィジェットにはデフォルトの日付が必要です。", + "set-date": "日付の設定", + "default-date": "デフォルトの日付", + "set-today": "署名日", + "enter-name": "名前を入力してください", + "enter-email": "メールアドレスを入力してください", + "subscribe-to-opensign-msg": "{{appName}}に登録すると無制限の無料デジタル署名をお楽しみいただけます。", + "duplicate-subscribe-msg": "複製を使用すると、選択したテンプレートの正確なコピーを作成できるため、元のテンプレートに影響を与えることなく再利用または変更できます。", + "save-as-template-msg": "この文書を再利用可能なテンプレートとして保存し、将来の文書に再度使用できます。", + "public-credit-alert": "このリンクから署名すると無料のメールクレジットが消費されます。無料ユーザーにはスパム送信者によるシステムの悪用を防ぐため毎月15メールクレジットが割り当てられています。より高額なメールクレジットと中断のないアクセスをご利用いただくには、<1>OpenSign™ 有料プランにご登録ください。", + "know-more-about": "もっと知る", + "free-unlimited-signatures": "無制限の無料署名", + "email-quota-updated": "毎日のメール割り当てが正常に更新されました。", + "password-has-been-reset": "パスワードがリセットされました。", + "Unauthorized to reset your own password.": "自分のパスワードをリセットする権限がありません。", + "User not found or not allowed.": "ユーザーが見つからないか、許可されていません。", + "User not found.": "ユーザーが見つかりません。", + "Admin user tenant not found.": "管理者ユーザーのテナントが見つかりません。", + "User is not authenticated.": "ユーザーが認証されていません。", + "Please provide required parameters.": "必須パラメータを入力してください。", + "reset-password": "ユーザーパスワードのリセット", + "enter-strong-password": "強力なパスワードを入力するか、パスワードを自動生成します。", + "autogenerate": "自動生成", + "extend": "延長", + "console-general-help": "個々のユーザーが独自のメールテンプレートをカスタマイズできるようにするには次の場所に移動します。", + "console-mail-help": "全社的なメールテンプレートを更新するには次のサイトにアクセスしてください。", + "admin-setting-disabled": "この設定は無効になっています。サポートが必要な場合は管理者にお問い合わせください。", + "company-email-settings": "会社のメール設定", + "allow-email-template-individually": "ユーザーごとにメール テンプレートのカスタマイズを許可する", + "user-email-template-general-help": "これを無効にすると、ユーザーはメール テンプレートをカスタマイズできなくなります。", + "disable-individual-user-smtp": "個々のユーザーの SMTP 設定を無効にする", + "enable-individual-user-smtp": "個々のユーザーの SMTP 設定を有効にする", + "user-smtp-general-help": "無効にするとユーザーは独自のSMTP設定を構成できなくなります。すべてのメールは代わりにグローバルSMTP構成を使用します。", + "global-smtp-settings": "グローバルSMTP設定", + "global-smtp-settings-help-p1": "これらの設定は、{{appName}}アカウント全体にグローバルに適用されます。個々のユーザーが独自のメール配信設定を構成していない場合、システムはここで定義されたグローバルSMTP設定を自動的に使用します。", + "global-smtp-settings-help-p2": "すべての署名要求メールの受信トレイ到達性を向上させるために、優先メールプロバイダーに接続できます。次のオプションのいずれかを選択します。", + "global-connect-to-gmail-help": "Gmailアカウントを使用して組織の受信トレイから署名リクエストのメールを直接送信します。これにより配信率、評判、全体的な信頼性が向上します。", + "global-connect-to-smtp-help": "独自の SMTP サーバーを使用して、ドメイン経由でメールを送信します。これによりメール インフラストラクチャを完全に制御でき、配信可能性が向上し、一貫したブランドが維持されます。", + "global-smtp-settings-help-p3": "個別のユーザーレベルの設定が構成されていない場合、これらのグローバル設定が自動的に適用されます。", + "hide-text-with-asterisks": "アスタリスクを使用してテキストを非表示にする", + "hide-text-with-asterisks-help": "署名された文書のテキストは表示されなくなりますが、文書の送信者(所有者)は {{appName}} アカウントからアクセスできます。", + "document-id": "文書ID", + "sent-date": "送信日", + "status": "状態", + "signer-form-data-for": "署名者フォームのデータ: {{signerName}} <{{signerEmail}}>", + "widget-name": "ウィジェット名", + "widget-responses": "ウィジェットの応答", + "formdata-download-note": "注: 署名、スタンプ、イニシャル、画像はエクスポートされません。", + "export-all-formdata-error": "テンプレートに重複したウィジェット名が含まれているため、フォームデータをエクスポートできません。フォームデータをエクスポートするには新しいテンプレートを作成してください。", + "export-formdata-error": "文書に重複したウィジェット名が含まれているため、フォームデータをエクスポートできません。フォーム データをエクスポートできるようにするには、ウィジェット名が重複しないように新しい文書を作成してください。", + "duplicate-widget-name-error": "このウィジェット名はすでに別の署名者に割り当てられています。別の名前を選択してください。", + "duplicate-template-widget-error": "このテンプレートには重複したウィジェット名が含まれているため、複製できません。", + "credit-alert": "クレジットアラート", + "document-form-data": "文書フォームデータ", + "view-formdata-paid-title-error": "フォーム データの表示機能を使用すると、署名者が署名中に入力したウィジェット データを印刷およびダウンロードできます。", + "view-formdata-paid-error": "注: 'フォームデータの表示'機能はv2.32.0以降で作成され、重複するウィジェット名が含まれていない文書でのみ使用できます。", + "download-all-formdata-paid-title-error": "'すべてのフォーム データをダウンロード' 機能を使用すると、テンプレートから作成されたすべての文書について署名者が入力したウィジェットデータをダウンロードできます。", + "download-all-formdata-paid-error": "注: 'すべてのフォームデータをダウンロード'機能はv2.32.0以降で作成され、重複するウィジェット名が含まれていないテンプレートでのみ使用できます。", + "api-token-not-found": "APIトークンが見つかりません。", + "sub-head-api-credits": "このユーザーが消費できるAPIクレジットの最大数を定義します。", + "consumed-credits": "消費クレジット", + "allowed-api-credits": "許可されるAPIクレジット", + "allowed-api-credits-help": "許可されるクレジットは、消費されたクレジット以上である必要があります。", + "Enter-allowed-api-credits": "許可されたAPIクレジットを入力してください", + "login-to-sandbox": "サンドボックスにログインする", + "your-credits-usage": "クレジットの使用状況", + "remaining": "残り", + "used": "使用済み", + "your-credits-usage-help": "これはAPIキーで消費されるクレジットの数です。", + "api-credits-updated": "API クレジットが正常に割り当てられました。", + "min-date": "最小日付", + "max-date": "最大日付", + "invalid-min-date": "無効な最小日付です。", + "min-less-max": "最小日付は最大日付以下にしてください。", + "invalid-max-date": "最大日付が無効です。", + "max-less-min": "最大日付は最小日付以上にしてください。", + "date-range": "日付範囲", + "date-range-help": "選択範囲を制限するには最小値か最大値、あるいはその両方を設定してください。選択した日付は範囲内に収まる必要があります。", + "option-disabled-by-owner": "文書作成者がこのオプションを無効にしました", + "pen-colors": "ペンの色", + "pen-colors-help": "署名ウィジェットとイニシャルウィジェットで使用できるペンの色を選択します。チェックを入れると色が表示されチェックを外すと非表示になります。", + "security-key": "セキュリティキー", + "remove-limit": "制限を削除する", + "removed-api-credits": "APIクレジット制限が削除されました。", + "enable-authentication": "認証を有効にする", + "working": "作業中", + "test-security-key": "セキュリティキーをテストする", + "generate": "生成", + "regenerate": "再生成", + "signing-date": "署名日", + "date-widget": "日付ウィジェット", + "mail-failed": "メールの送信中に問題が発生しました。もう一度試してください。", + "mail-status-head": "次のステップ: 文書に署名しますか?", + "send-to-email": "メールに送信", + "date-pref-help-sub-title": "日付ウィジェットの設定では、日付ウィジェットのデフォルト設定を定義できます。これらのデフォルトは、新しい日付ウィジェットを文書またはテンプレートに追加するたびに自動的に適用されます。歯車アイコンをクリックすると、いつでも個々の日付ウィジェットをカスタマイズできます。", + "date-pref-help-format": "日付ウィジェットに使用されるデフォルトの日付形式を選択します。", + "date-pref-help-default-date": "日付ウィジェットのデフォルトの日付値を設定します。", + "date-pref-help-signing-date": "有効にすると日付ウィジェットは署名者が文書に署名した日付を自動的に使用します。", + "date-pref-help-read-only": "有効にすると日付ウィジェットは署名者に対して読み取り専用になります。", + "upload-csv": "CSVのアップロード", + "file-selected": "選択されたファイル", + "bulk-send-csv-helper": "署名者の役割(役割のメールアドレス/名前/電話番号)と事前入力値(事前入力:フィールド名)にはヘッダーを使用します。必須の事前入力フィールドは必ず入力してください。", + "bulk-send-csv-helper-note": "注: CSVの日付タイプの事前入力フィールドの場合、値は次の形式で指定する必要があります: {{value}} (例: {{example}})。", + "bulk-send-csv-summary": "{{total}}行をインポートしました。{{invalid}}個の無効な行がスキップされました。", + "bulk-send-csv-missing-headers": "必要なCSVヘッダーがありません。ロール: {{roles}}。プレフィル: {{prefill}}。", + "bulk-send-no-records": "送信する前に1人以上の受信者を追加してください。", + "csv-only-support": "CSVファイルのみがサポートされています。", + "csv-no-records": "CSVにレコードが見つかりませんでした。", + "select-at-least-option": "1つ以上のオプションを選択してください。", + "draw-required": "枠の中に描いてください。", + "enter-smtp-username": "SMTPユーザー名を入力してください", + "enter-webhook-url": "Webhook URLを入力してください", + "enter-user-name": "ユーザー名を入力してください", + "enter-tagline": "キャッチフレーズを入力してください", + "enter-password-or-click-autogenerate": "パスワードを入力するか、'自動生成'をクリックします", + "enter-daily-email-quota": "1 日あたりのメール割り当て量を入力してください", + "enter-custom-regular-expression": "カスタム正規表現を入力してください", + "enter-value": "{{value}}を入力してください", + "are-you-sure-want-to-send-document": "本当に文書を送信してもよろしいですか?" +} diff --git a/apps/OpenSign/public/locales/kr/translation.json b/apps/OpenSign/public/locales/kr/translation.json index fda6225ac2..054751fde4 100644 --- a/apps/OpenSign/public/locales/kr/translation.json +++ b/apps/OpenSign/public/locales/kr/translation.json @@ -1035,6 +1035,8 @@ "contact-already-exists": "연락처가 이미 존재합니다.", "docx-error": "현재 DOCX 파일 처리 중 일부 문제가 발생했습니다. PDF 파일을 업로드하세요.", "docx-error-contact": "또는 support@opensignlabs.com으로 문의하세요.", + "excel-error": "현재 Excel 파일 처리 중 일부 문제가 발생했습니다. PDF 파일을 업로드하세요.", + "excel-error-contact": "또는 support@opensignlabs.com으로 문의하세요.", "agreement-note": "참고: 이에 동의한다고 해서 즉시 문서에 서명하는 것은 아닙니다. 이는 단지 전자적으로 문서를 검토할 수 있도록 허용하는 것입니다. 전체를 읽고 서명 여부를 결정할 기회가 있습니다.", "draft-template-info-p1": "템플릿을 공개하려면 단일 역할을 포함하거나 여러 역할을 포함하는 경우 모든 추가 역할이 이미 서명자에게 할당되어 있어야 합니다. 할당되지 않은 공개 역할은 비워두고 첫 번째 위치에 배치해야 합니다.", "visit-below-link": "자세한 내용은 아래 링크를 방문하세요 -", @@ -1662,7 +1664,7 @@ "eideasy-downloading": "서명된 문서를 다운로드하는 중…", "eideasy-sign-btn": "eID Easy로 서명", "signature-type-hint": "디지털: 그리기/입력/업로드로 서명합니다. 적격: 신원 확인이 포함된 eID Easy를 통한 QES.", - "access-code": "접속 코드", + "access-code": "접속 코드", "access-code-set": "접속 코드가 설정됨", "access-code-add": "접속 코드 추가", "access-code-help": "이 서명자만 아는 선택적 비밀번호입니다. 문서를 보거나 서명하기 전에 반드시 입력해야 합니다. 전화 또는 직접 만나서 등 별도의 경로로 수신자에게 전달하세요.", @@ -1721,5 +1723,6 @@ "active-plan-message": "{{plan}} 요금제가 활성화되어 있습니다. 결제에서 관리하세요.", "billing-action-message": "다른 요금제를 선택하기 전에 기존 요금제의 결제 조치가 필요합니다.", "trial-unavailable-message": "이 계정은 추가 무료 체험 대상이 아닙니다. 결제에서 관리하거나 결제를 완료하세요." - } -} + }, + "allow-multiple-selection": "다중 선택 허용" +} \ No newline at end of file diff --git a/apps/OpenSign/public/locales/zh/translation.json b/apps/OpenSign/public/locales/zh/translation.json new file mode 100644 index 0000000000..717e83e8a2 --- /dev/null +++ b/apps/OpenSign/public/locales/zh/translation.json @@ -0,0 +1,1616 @@ +{ + "header-news": "新功能:使用双重验证(2FA)保护你的账户,并体验无需密码的通行密钥(Passkeys)登录。", + "header-news-btn": "立即设置", + "sandbox-news": "这是沙箱环境,请勿用于生产用途。", + "create-account": "创建账户", + "login": "登录", + "language": "语言", + "dark-mode": "深色模式", + "name": "姓名", + "phone": "电话", + "phone-optional": "选填", + "email": "邮箱", + "company": "公司", + "job-title": "职位", + "profile": "个人资料", + "log-out": "退出登录", + "is-email-verified": "邮箱是否已验证", + "public-profile": "公开主页", + "tagline": "个性签名", + "has-requested-you-to-sign": "请求你签署", + "has-requested-you-to-review-and-sign": " 请求你审阅并签署", + "input-required": "请填写此字段。", + "sort-order": { + "Ascending": "升序", + "Descending": "降序", + "Name": "名称", + "Date": "日期" + }, + "folder": "文件夹", + "pdf": "Pdf", + "context-menu": { + "Download": "下载", + "Rename": "重命名", + "Move": "移动", + "Delete": "删除" + }, + "action": "操作", + "add": "添加", + "add-new-folder": "新建文件夹", + "disable-documentId": "禁用 documentId", + "edit": "编辑", + "change-password": "修改密码", + "save": "保存", + "cancel": "取消", + "upgrade-now": "立即升级", + "contact-now": "立即联系", + "upgrade-to": "升级到", + "plan": "套餐", + "connect": "连接", + "connect-to-g-drive": "连接 Google Drive", + "reconnect-to-g-drive": "重新连接 Google Drive", + "gdrive-info-connect": "连接 Google Drive 后,完成的文档将保存到 Google Drive 的 {{appName}} 文件夹中。", + "subscription-renew-warning": "你的订阅将在 {{remainingDays}} 天后到期,请及时续订。", + "subscribe-card-teamplan": "释放协作的全部潜能!创建无限的组织、团队和层级结构,在团队间无缝共享模板并分配自定义用户角色。立即升级你的工作流程!", + "subscribe-card-plan": "只需每月 {{premiumPrice}} 起即可解锁高级功能。享受更强性能,超出所含高级额度后,每增加一个额度仅需 {{addonPrice}}。", + "user-name-limit-char": "如需少于 8 个字符的用户名,请订阅", + "tour-content": "不再显示", + "pro": "专业版", + "team": "团队版", + "user": "用户", + "docs": "文档", + "session-expired": "你的会话已过期。", + "public-profile-help": "这是你的公开链接。复制并分享给签署人,即可查看你公开设置的全部模板。", + "welcome": "欢迎回来!", + "Login-to-your-account": "登录你的账户", + "password": "密码", + "forgot-password": "忘记密码", + "loading": "加载中...", + "of": "/", + "sign-SSO": "使用 SSO 登录", + "login-page": "登录页", + "or": "或", + "signup-page": "注册页", + "password-match-length": "新密码与确认密码需一致", + "password-length": "密码长度至少 8 位", + "password-case": "密码需包含大写字母、小写字母和数字", + "password-special-char": " 密码需包含特殊字符", + "agree": "我同意", + "term": "服务条款", + "subscribe-to-opensign": "订阅 OpenSign 通讯", + "register": "注册", + "sidebar": { + "Dashboard": "仪表盘", + "Sign yourself": "自己签署", + "Request signatures": "请求签署", + "Templates": "模板", + "Analytics": "统计分析", + "Branding": "品牌定制", + "Mail": "邮件", + "Storage": "存储", + "Signing certificate": "签名证书", + "Teams": "团队", + "General": "通用", + "Teams-Children": { + "Organizations": "组织", + "OrgAdmins": "组织管理员" + }, + "Templates-Children": { + "Create template": "创建模板", + "Manage templates": "管理模板", + "Embedding": "嵌入" + }, + "OpenSign™ Drive": "{{appName}} 云盘", + "Reports": "报表", + "Documents": "文档", + "Documents-Children": { + "Need your sign": "待我签署", + "In Progress": "进行中", + "Completed": "已完成", + "Drafts": "草稿", + "Declined": "已拒签", + "Expired": "已过期" + }, + "Contactbook": "通讯录", + "Settings": "设置", + "Settings-Children": { + "My Signature": "我的签名", + "API Token": "API 令牌", + "Webhook": "Webhook", + "Preferences": "偏好设置", + "Teams": "团队", + "Team-update-successfully": "团队更新成功。", + "Users": "用户" + }, + "Global SMTP": "全局 SMTP" + }, + "dashboard-card": { + "Need your Signature": "待我签署", + "Out for signatures": "待他人签署" + }, + "report-name": { + "Draft Documents": "草稿文档", + "Need your sign": "待我签署", + "In-progress documents": "进行中文档", + "Completed Documents": "已完成文档", + "Declined Documents": "已拒签文档", + "Expired Documents": "已过期文档", + "Recently sent for signatures": "最近发送的签署", + "Recent signature requests": "最近的签署请求", + "Drafts": "草稿", + "Contactbook": "通讯录", + "Templates": "模板", + "Teams": "团队", + "Users": "用户" + }, + "btnLabel": { + "sign": "签署", + "Sign": "签署", + "Resend": "重新发送", + "Rename": "重命名", + "Revoke": "撤销", + "Delete": "删除", + "Use": "使用", + "Quick send": "快速发送", + "Edit": "编辑", + "Share with team": "分享给团队", + "Share with user": "分享给同事", + "Share": "分享", + "View": "查看", + "option": "选项", + "Embed": "嵌入", + "Copy TemplateId": "复制模板 ID", + "Copy Public URL": "复制公开链接", + "extend-expiry-date": "延长有效期", + "Duplicate Template": "复制模板", + "Duplicate": "复制", + "daily-mail-quota": "每日邮件配额", + "Save as template": "保存为模板", + "Fix & resend": "修复并重发", + "Kiosk Mode": "自助签署模式", + "Reset password": "重置密码", + "View formdata": "查看表单数据", + "Download all formdata": "下载全部表单数据", + "API credits": "API 额度" + }, + "report-heading": { + "Sr.No": "序号", + "Title": "标题", + "Email": "邮箱", + "Phone": "电话", + "File": "文件", + "Owner": "所有者", + "Signers": "签署人", + "Note": "备注", + "Folder": "文件夹", + "Reason": "原因", + "Parent Team": "上级团队", + "Active": "启用", + "Role": "角色", + "Team": "团队", + "Name": "名称", + "Status": "状态", + "created-date": "创建日期", + "Type": "类型", + "Logs": "日志", + "Expiry-date": "到期日期", + "Company": "公司", + "JobTitle": "职位", + "Time to complete (Days)": "完成时限(天)", + "Auto reminder": "自动提醒", + "Remind once in every (Days)": "每(天)提醒一次", + "Enable OTP verification": "启用 OTP 验证", + "Enable Tour": "启用引导", + "Notify on signatures": "签署时通知", + "Allow modifications": "允许修改", + "Redirect url": "跳转链接", + "Created Date": "创建日期", + "Updated Date": "更新日期", + "Expiry Date": "到期日期", + "Sent Date": "发送日期" + }, + "report-help": { + "Draft Documents": "这些是你已创建但尚未最终发送的文档。", + "Need your sign": "等待你签署的文档列表。", + "In-progress documents": "你已发送给其他方签署的文档列表。", + "Completed Documents": "所有方均已签署完成的文档列表。", + "Declined Documents": "被某位签署人拒签的文档列表。", + "Expired Documents": "已到期的文档列表。", + "Contactbook": "你添加的联系人/签署人列表。为新文档添加签署人时会作为建议显示。", + "Templates": "可用于创建文档的模板列表。点击“使用”可基于模板创建新文档,并在下一步修改文档与添加签署人。" + }, + "Sign Yourself": "自己签署", + "Request Signatures": "请求签署", + "New Template": "新建模板", + "file-type": "pdf, png, jpg, jpeg", + "docx": "docx", + "files-selected": "个文件已选择", + "template-title": "模板标题", + "document-title": "文档标题", + "title": "标题", + "description": "描述", + "time-to-complete": "完成时限(天)", + "send-in-order": "按顺序发送", + "send-in-order-help": { + "p1": "选择你希望如何向文档签署人发送签署请求:", + "p2": "选择此选项将首先向第一位签署人发送签署请求。第一位签署人完成后,序列中的下一位签署人将收到请求。此过程持续进行,直到所有签署人完成签署。这种方式可确保文档按特定顺序签署。", + "p3": "选择此选项将同时向所有签署人发送签署链接。每位签署人都可自行方便地签署文档,无论其他签署人是否已完成签署。这种方式更快,但不会强制参与者之间的签署顺序。", + "p4": "请选择最适合你文档处理需求的选项。" + }, + "strict-order": "强制严格顺序", + "strict-order-help": "启用后,在前一位签署人/审批人完成操作前,其他签署人无法签署或审批。", + "no": "否", + "auto-reminder": "自动提醒", + "remind-once": " 每(天)提醒一次", + "next": "下一步", + "OpenSign-drive": "{{appName}} 云盘", + "drive-document-status": { + "Completed": "已完成", + "Declined": "已拒签", + "Draft": "草稿", + "Expired": "已过期", + "In Progress": "进行中" + }, + "select-folder-help": "若未选择文件夹,已签署的文档将保存到 {{appName}} 云盘主文件夹。", + "no-data": "未找到数据", + "save-here": "保存到此处", + "back": "返回", + "add-folder": "添加文件夹", + "create-folder": "创建文件夹", + "parent-folder": "上级文件夹", + "create": "创建", + "signers": "签署人", + "signers-help": "输入联系人姓名可从已保存的联系人中选择签署人或新增。通过按期望顺序添加签署人来安排签署顺序。使用“+”添加签署人,“x”移除。每位签署人将按所列顺序收到签署邮件。", + "bcc-help": "开始输入联系人姓名,即可从已保存的联系人中看到建议或添加新联系人。使用 '+' 按钮添加用户,使用 'x' 移除用户。所选用户的邮箱将作为密送(Bcc)添加。文档完成后,每位用户都会收到邮件通知。", + "cc-help": "开始输入联系人姓名,即可从已保存的联系人中看到建议或添加新联系人。使用 '+' 按钮添加用户,使用 'x' 移除用户。所选用户的邮箱将作为抄送(cc)添加。文档完成后,每位用户都会收到邮件通知。", + "add-signer": "添加签署人", + "contact-not-found": "未找到联系人", + "add-yourself": "添加自己", + "submit": "提交", + "reset": "重置", + "my-signature": "我的签名", + "signature": "签名", + "upload-image": " 上传图片", + "clear": "清除", + "upload-signature/Image": "请上传签名/图片/印章", + "initials": "姓名缩写", + "API": "API", + "api-token": "API 令牌", + "regenerate-token": "重新生成正式令牌", + "remove-background": "去除背景", + "generate-token": "生成正式令牌", + "view-docs": "查看文档", + "generate-token-alert": "确定要重新生成令牌吗?旧令牌将失效。", + "yes": "是", + "copied": "已复制", + "something-went-wrong-mssg": "出现错误,刷新页面可能解决此问题。", + "token-generated": "令牌生成成功。", + "webhook": "Webhook", + "update-webhook": "更新 Webhook", + "add-webhook": "添加 Webhook", + "webhook-added": "Webhook 添加成功。", + "team-disabled": "团队已停用", + "team-enabled": "团队已启用", + "are-you-sure": "你确定要", + "disable": "停用", + "enable": "启用", + "this-team": " 该团队吗?", + "edit-team": "编辑团队", + "name-of-team": "团队名称", + "prev": "上一步", + "no-data-available": "暂无数据", + "add-team": "添加团队", + "page-not-found": "页面未找到", + "users-from-teams": "来自团队的用户", + "user-status": "用户状态", + "activate": "启用", + "deactivate": "停用", + "this-user": " 该用户", + "delete-user": "删除用户", + "delete": "删除", + "add-user": "添加用户", + "password-generated": "密码仅生成一次,请务必复制保存。", + "Team status": "团队状态", + "user-deactivated": "用户已停用。", + "user-activated": "用户已启用。", + "public": "公开", + "download": "下载", + "sign-offline": "离线签署", + "sign-offline-instructions": "下载文档,使用任意外部工具签署,然后在此上传已签署的副本。文档所有者将审核你的提交,并批准或拒绝。", + "sign-offline-step-1": "下载未签署的 PDF。", + "sign-offline-step-2": "使用你偏好的工具签署 PDF。", + "sign-offline-step-3": "上传已签署的 PDF 以供所有者批准。", + "sign-offline-upload-hint": "选择已签署的 PDF 以提交审批。", + "sign-offline-submitted-title": "已提交审批", + "sign-offline-submitted-body": "已通过邮件通知文档所有者审核你离线签署的副本。", + "offline-already-submitted-title": "文档已离线提交", + "offline-already-submitted-body": "你已提交此文档进行离线签署审核。一经批准或拒绝,文档所有者将收到通知。", + "offline-action-approve-title": "批准离线签名", + "offline-action-approve-confirm": "批准", + "offline-action-reject-title": "拒绝离线签名", + "offline-action-reject-hint": "可选择提供原因。签署人将收到邮件通知。", + "offline-action-reject-reason-placeholder": "原因(可选)", + "offline-action-reject-confirm": "确认拒绝", + "offline-action-review-title": "审核离线签名", + "offline-action-review-hint": "预览签署人上传的已签署 PDF,然后批准或拒绝。在你确认之前不会执行任何操作。", + "offline-action-submitted-at": "提交于", + "offline-action-no-preview": "此提交没有可用的预览。", + "offline-action-open-in-new-tab": "在新标签页打开 PDF", + "offline-action-invalid-link": "此审核链接无效或已过期。", + "offline-action-success": "操作已完成。", + "reject": "拒绝", + "document": "文档", + "view": "查看", + "make-template-public": "设为公开模板", + "make-template-private": "设为私有模板", + "make-template-public-alert": "确定要将该模板设为公开吗?", + "make-template-private-alert-non": "确定要将该模板设为私有吗?", + "make-template-private-alert": "确定要将该模板设为私有吗?这会将它从你的公开主页移除。", + "public-role": "公开角色", + "public-url": "公开主页", + "embed-template": "嵌入模板", + "public-url-copy": "这是你的公开链接:", + "public-url-copy-mssg": "复制并分享给签署人,即可查看你公开设置的全部模板。", + "add-public-url-alert": "你可以生成你的 {{appName}} 公开主页", + "share-with-alert": "如果任何角色已分配联系人,则无法共享模板。请在共享模板前,从各角色中移除所有联系人分配。", + "share-with": "分享给", + "team-not-found": "未找到团队", + "roles": "角色", + "delete-document": "删除文档", + "delete-document-alert": "确定要删除该文档吗?", + "quick-send": "快速发送", + "add-new": "新增", + "send": "发送", + "quick-send-alert-1": "此文档中的所有角色当前都已关联联系人。若要快速向多个签署人发送此模板的副本,请确保至少有一个角色未关联任何联系人。", + "quick-send-alert-2": "请确保为所有收件人至少添加了一个签名控件。", + "quick-send-alert-3": "请为此模板至少添加一个角色。", + "quick-send-alert-4": "{{flow}} 每批次最多支持 {{count}} 位签署人。请拆分你的列表后重试。", + "copy-link": "复制链接", + "copy": "复制", + "revoke-document": "撤销文档", + "revoke-document-alert": "确定要撤销该文档吗?", + "resend-mail": "重新发送邮件", + "resend-mail-help": "你可以使用以下变量,它们将被替换为实际值:- {{document_title}}、{{sender_name}}、{{sender_mail}}、{{sender_phone}}、{{receiver_name}}、{{receiver_email}}、{{receiver_phone}}、{{expiry_date}}、{{company_name}}、{{signing_url}}、{{note}}。", + "subject": "主题", + "body": "正文", + "add-contact": "添加联系人", + "edit-contact": "编辑联系人", + "add-signer-alert": "联系人已存在!请从“签署人”下拉框中选择", + "record-delete-alert": "记录删除成功!", + "record-revoke-alert": "记录撤销成功!", + "mail-sent-alert": "邮件发送成功。", + "document-sent-alert": "文档发送成功!", + "template-share-alert": "模板分享成功。", + "template-public-alert-1": "模板已成功设为公开。", + "template-public-alert-2": "模板已成功设为私有。", + "template-public-alert-3": "需要为公开签署人选择一个角色。", + "template-public-alert-4": "请确保为所有签署人至少添加一个签名控件。", + "template-public-alert-5": "由于此模板启用了按顺序发送,公开角色必须置于顶部。", + "template-public-alert-6": "请为除公开角色用户外的所有角色附加签署人。", + "template-public-alert-7": "请至少分配一个公开角色,以使此模板公开。", + "loader": " 这可能需要一些时间", + "pages": "页", + "document-signed": "文档已签署", + "close": "关闭", + "validation-alert": "校验提示", + "validate-alert-mssg": " 输入不满足正则表达式设定的条件。", + "otp-verification": "OTP 验证", + "enter-otp": "输入 OTP", + "verify": "验证", + "verify-email-1": "验证邮箱", + "resend": "重新发送", + "contact-details": "联系人详情", + "verify-email": "请验证你的邮箱以继续。这是一次性步骤,用于确认与你的 OpenSign 账户关联的邮箱。", + "send-otp": " 发送 OTP", + "otp-placeholder": "输入通过邮件收到的验证码", + "loading-doc": "加载文档..", + "widgets-name": { + "signature": "签名", + "stamp": "印章", + "initials": "姓名缩写", + "name": "姓名", + "job title": "职位", + "company": "公司", + "date": "日期", + "text": "文本", + "text input": "文本输入", + "cells": "单元格", + "checkbox": "复选框", + "dropdown": "下拉框", + "radio button": "单选按钮", + "image": "图片", + "email": "邮箱", + "number": "数字", + "draw": "手写", + "attachments": "附件", + "attachments-add": "点击添加附件", + "attachments-count": "{{count}} 个附件" + }, + "fields": "字段", + "recipients": "接收人", + "please-add": "请添加一个", + "signed-by": "签署人", + "more": "更多", + "sent": "已发送", + "print": "打印", + "certificate": "证书", + "decline": "拒签", + "finish": "完成", + "approve": "批准", + "approve-mssg": " 你确定要批准该文档吗?", + "signer-role-label": "接收人角色", + "signer-role-signer": "签署人", + "signer-role-viewer": "查看人", + "signer-role-approver": "审批人", + "signer-role-hint": "签署人必须签署;审批人只审批不签署;查看人仅查看。", + "signer-role-upgrade-msg": "查看人与审批人角色仅在付费套餐提供。升级套餐即可为接收人分配这些角色。", + "done": "完成", + "mail": "邮件", + "sign-now": "立即签署", + "successfully-signed": "签署成功!", + "email-mssg": " 在此添加的接收人将收到已签署文档的副本。", + "email-error-1": " 请提供正确的邮箱地址", + "email-error-2": "一次最多只能发送给十位接收人。", + "Email-verified-alert-1": "邮箱已验证。", + "Email-verified-alert-2": "邮箱已经验证过了。", + "upload-stamp-image": "上传印章图片", + "draw-signature": "手写签名", + "draw-initials": "手写姓名缩写", + "enter-text": "输入文本", + "enter-widgettype": "输入{{widgetType}}", + "draw": "手写", + "type": "输入", + "color-type": { + "red": "红", + "blue": "蓝", + "black": "黑", + "yellow": "黄" + }, + "my-initials": "我的姓名缩写", + "upload": "上传", + "initial-teb": "姓名缩写", + "signature-tab": "签名", + "initial-alert": "未找到我的姓名缩写", + "copy-title": "复制控件到", + "contact-delete-alert": "确定要删除该联系人吗?", + "reset-password-alert-1": "重置密码链接已发送到你的邮箱", + "reset-password-alert-2": "请先配置邮件适配器 ", + "reset-password-alert-3": "重置你的密码", + "failed-animation": "动画加载失败", + "apply": "应用", + "select-columns": "选择列", + "copy-type": { + "All pages": "所有页", + "All pages but last": "除最后一页外所有页", + "All pages but first": "除第一页外所有页", + "Next to current widget": "当前控件旁", + "Page range": "页码范围" + }, + "options": "选项", + "minimum-check": "最少勾选", + "maximum-check": "最多勾选", + "cell-count": "单元格数量", + "default-value": "默认值", + "formula": "公式", + "formula-placeholder": "使用数字控件构建公式", + "formula-no-widgets": "该签署人尚未分配其他数字控件。", + "supported-operators": "支持的运算符:", + "formula-helper": "点击数字控件标签以插入(如 {{number-1}} + {{number-2}})。", + "formula-error-letter": "控件名需用双花括号包裹(如 {{number-1}})。", + "formula-error-characters": "花括号外仅允许数字和 +、-、*、/、(、)。", + "formula-error-braces": "每个左花括号 {{ 必须有匹配的右花括号 }}。", + "formula-error-operators": "使用运算符或括号时至少添加两个值。", + "formula-error-leading-operator": "公式不能以运算符开头。", + "formula-error-trailing-operator": "公式不能以运算符结尾。", + "formula-error-adjacent-placeholders": "两个占位符之间必须有运算符,不能直接相邻。", + "formula-error-continuous-operators": "不能连续使用两个运算符。", + "formula-error-empty-parentheses": "括号不能为空。", + "formula-error-invalid-parentheses-content": "括号内不能以运算符开头或结尾。", + "formula-error-before-open-parenthesis": "'(' 前缺少运算符,请在左括号前添加运算符。", + "formula-error-after-close-parenthesis": "')' 后缺少运算符,请在右括号后添加如 '+' 或 '*' 的运算符。", + "formula-error-between-parentheses": "')' 与 '(' 之间缺少运算符,请在两组之间添加如 '*' 的运算符。", + "formula-error-division-by-zero": "不允许除以零,请将 '0' 替换为有效的非零数字或变量。", + "formula-error-invalid-number-format": "数字格式无效。数字必须为有效格式如 '1'、'3.14',不能为 '.5'、'1.' 或 '1.2.3'。", + "formula-error-unclosed-parenthesis": "发现未闭合的 '(',每个左括号必须有匹配的右括号。", + "formula-error-unexpected-closing-parenthesis": "发现多余的右括号 ')',没有匹配的左括号。", + "formula-error-empty-placeholder": "不允许空占位符 '{{}}',请在花括号内提供变量名。", + "decimal-places": "小数位数", + "number-of-decimal-places": "小数位数", + "decimal-places-helper": "设为 0 表示整数", + "select": "选择", + "read-only": "只读", + "hide-labels": "隐藏标签", + "layout": "布局", + "checkbox": "复选框", + "alert": "提示", + "zoom-in": "放大", + "zoom-out": "缩小", + "document-signed-alert": "恭喜!🎉 你已成功签署该文档!", + "otp-sent-alert": "OTP 已发送到你的邮箱", + "fields-required": "必填字段", + "signature-widget-alert-1": "请确保至少添加一个签名控件", + "signature-widget-alert-2": "请确保所有字段填写准确并满足全部要求。", + "encrypted-pdf-alert": "暂不支持加密的 pdf 文件。", + "encrypted-pdf-alert-1": "PFX 文件密码无效。", + "user-not-exist": "用户不存在", + "template-role-alert": "请先添加角色", + "create-document": "创建文档", + "template-created-alert": "你想对刚创建的模板做什么? ", + "signers-alert": "签署人提示", + "template-creation-alert-1": "请为添加占位符选择签署人!", + "ok": "确定", + "radio-group": "单选组", + "dropdown-options": "下拉选项", + "add-role": "添加角色", + "role-ex": " 例如:客户、HR、总监、经理、学生等", + "add/choose-signer": "添加/选择签署人", + "choose-from-contacts": "从通讯录选择", + "select-signer": " 请选择签署人", + "edit-template": "编辑模板", + "widget-info": "控件信息", + "validation": "校验", + "invalid-default-value": "默认值无效", + "hint": "提示", + "color": "颜色", + "role-help": { + "p1": "什么是模板角色?", + "p2": "先指定完成文档所需的每个角色。思考签署流程中涉及的各方及其职责。常见角色包括内部文档的 HR、协议的客户或商业协议的供应商。", + "p3": "为什么为某些角色预绑定用户?", + "p4": "对于始终由同一人承担的角色(如 CEO 在员工录用通知上签字),可在模板中为角色预绑定用户。此步骤可选,但建议用于提升效率与一致性。", + "p5": "何时指定每个角色绑定的用户?", + "p6": "从模板创建文档时,会提示你为每个已定义角色绑定用户。若角色已绑定用户则会预填,你可在发送前按需修改。" + }, + "add-recipients": "添加接收人", + "loading-mssg": "这可能需要一些时间", + "send-mail": "发送邮件", + "signature-field-widget": "每个用户至少需要一个签名控件。你尚未为 {{signersName}} 添加签名控件", + "placeholder-alert-1": "请确保为所有接收人至少添加一个签名控件。", + "placeholder-alert-2": "请确认已填写文本字段。", + "placeholder-alert-3": " 你确定要发送该文档进行签署吗?", + "placeholder-alert-4": "你已成功向所有接收人发送邮件!", + "placeholder-mail-alert": "你已成功向 {{name}} 发送邮件。{{name}} 签署后,后续签署人将收到邮件", + "placeholder-mail-alert-you": "你签署后,后续签署人将收到邮件。", + "placeholder-alert-5": "你可以立即签署,或发送到邮箱稍后完成。", + "placeholder-alert-6": "请先配置邮件适配器以发送邮件!", + "placeholder-alert-7": "请为添加占位符选择签署人!", + "email-subject": "邮件主题", + "email-body": "邮件正文", + "email-placeholder": "添加邮件正文", + "reset-to-default": "恢复默认", + "customize-email": "自定义邮件", + "upgrade-to-customize-email": "升级以自定义邮件", + "sign-url": "签署链接", + "mails-sent": "已发送邮件", + "mail-not-delivered": "邮件未送达", + "email-not-verified-head": "邮箱未验证", + "document-alert": "文档提示", + "owner-subscription-expired": "所有者的订阅已过期。", + "subscription-expired": "订阅已过期", + "owner-doesnt-have-paid-plan": "所有者没有付费套餐。", + "alert-message": "提示消息", + "document-decline": "文档拒签", + "decline-alert-1": "确定要拒签该文档吗?", + "decline-alert-2": "你已拒签该文档!", + "decline-alert-3": "该文档已被拒签/撤销,无法签署。", + "sign here": "在此签署", + "guest-email-alert": "验证码已发送到你的邮箱", + "get-otp-alert": "你将通过邮件收到验证码", + "user-already-exist": "用户已存在。", + "server-error": "服务器内部错误!", + "fill-required-details!": "请填写必填信息!", + "sign-up-form": "注册表单", + "sign-up": "注册", + "folder-already-exist!": "文件夹已存在!", + "please-select-position!": "请选择位置!", + "default-sign-alert": "确定要自动签署所有请求的 {{widgetsType}} 控件吗?", + "Your-Signature": "你的签名", + "auto-sign-all": "全部自动签署", + "generating-certificate": "正在生成证书", + "pdf-download": "PDF 下载", + "generate-certificate-alert": " 正在生成完成证书,请稍候。若下载未自动开始,请再次点击按钮。", + "generate-certificate-err": "证书生成当前出现问题,请稍后重试。", + "attachments-docx-upload-failed": "当前遇到问题,请重试。", + "attachments-docx-size-limit": "大文件上传已达上限,请等到 {{time}} 后再试。", + "folder-already-exist": "文件夹已存在!", + "folder-created-successfully": "文件夹创建成功!", + "fill-folder-name": "请填写文件夹名称", + "already-exists-this-username": "该用户名已存在!", + "verification-code-sent": "验证邮件已发送到你的邮箱!", + "registered-user-successfully": "用户注册成功。", + "role-not-found": "未找到角色。", + "do-not-access": "你没有访问权限,请联系管理员。", + "add-admin": "添加管理员", + "opensign-setup": "{{appName}} 设置", + "join-discord": "加入我们的 discord 服务器", + "admin-already-exist": "管理员已存在。", + "password-update-alert-1": "密码更新成功。", + "password-update-alert-2": "当前密码缺失或不正确。", + "password-update-alert-3": "当前密码缺失或不正确。", + "password-update-alert-4": "两次输入的密码不一致。", + "current-password": "当前密码", + "new-password": "新密码", + "confirm-password": "确认密码", + "file-alert-1": "所选文件过大,请选择小于以下大小的文件", + "file-alert-2": "请选择文件。", + "file-alert-3": "文档上传中,请稍候。", + "enter-pdf-password": "输入 Pdf 密码", + "correct-password": "请提供正确的密码", + "decrypting-pdf": " 正在解密 pdf,请稍候...", + "invalid-otp": "OTP 无效", + "user-not-found": "未找到用户", + "enter-otp-alert": "请输入 OTP!", + "get-verification-code": "获取验证码", + "get-verification-code-2": "你将通过邮件收到验证码", + "enter-verification-code": "输入验证码", + "provide-your-details": "填写你的信息", + "provide-email": "请提供邮箱。", + "additional-info": "附加信息", + "signature-saved-alert": "保存成功。", + "saved-successfully": "保存成功。", + "fill-field": "请填写此字段", + "error-template": "错误:未找到模板!", + "error": "错误", + "invalid-document": "错误:文档无效!", + "document-not-found": "未找到文档!", + "document-signed-alert-1": "你已成功签署文档。可下载或打印部分签署的文档副本。全部签署人签署完成后,数字签名文档与完成证书将通过邮件发送给所有者及所有签署人。", + "encrypted-pdf-not-support": "暂不支持加密的 pdf 文件。", + "document-signed-alert-4": " 恭喜!🎉 该文档已被所有参与方成功签署!", + "document-signed-alert-5": "该文档已被所有签署人签署。", + "document-signed-alert-6": "该文档已被一个或多个接收人拒签。", + "document-signed-alert-7": "该文档已不可用。", + "document-signed-alert-8": "该文档已发送签署。", + "yet-to-sign": "待签署", + "viewers": "查看人", + "viewer-no-widgets": "查看人接收文档的只读副本,不能为其分配控件。", + "viewer-confirm-widget-removal": "将该接收人切换为查看人将移除其已分配的全部控件。是否继续?", + "validation-alert-1": "输入不满足正则表达式设定的条件。", + "account-already-exists": "账户已存在!", + "choose-password": "设置密码", + "enter-password": "输入密码", + "sure": "确定", + "subscribed-alert": "你已订阅该套餐!", + "monthly": "月付", + "yearly-upto": "年付(最高 66% off)", + "billed-yearly": "按年计费", + "billed-monthly": "按月计费", + "plansubscription-1": "免费自行托管", + "visit-github": "访问 Github", + "user-already-exist-name": "该用户名已存在!", + "do-not-access-contact-admin": "你没有访问权限,请联系管理员。", + "filed-required-correctly": "请正确填写必填信息。", + "admin-created": "管理员已创建", + "invalid-masterkey": "masterkey 无效", + "master-key": " 主密钥", + "profile-update-alert": "个人资料更新成功。", + "date": "日期", + "report-not-found": "未找到报表", + "please-wait": "请稍候", + "select-folder": "选择文件夹", + "generated-on": "生成于", + "text-field": "文本字段", + "font-size": "字体大小", + "widget-status": { + "Required": "必填", + "Optional": "选填" + }, + "all-right": "版权所有", + "version": "版本", + "social-media": { + "github": "Github", + "linked-in": "LinkedIn", + "twitter": "Twitter", + "discord": "Discord" + }, + "tour-mssg": { + "home-layout-1": "登录成功!我们来看一看。", + "home-layout-2": "要上传文档自行签署或请求他人签署,直接选择相应按钮即可。", + "home-layout-3": "你已准备好开始使用 {{appName}}!", + "home-layout-4": "给我们点星于", + "generate-token": "立即升级以生成正式 API 令牌。", + "opensign-drive-1": "点击面包屑链接可轻松浏览文件夹层级并查看每个文件夹内的文档。", + "opensign-drive-2": "点击添加按钮创建新文件夹或文档。", + "opensign-drive-3": "使用此菜单按日期或名称排序文档。", + "opensign-drive-4": "点击此菜单以列表视图显示文档。", + "opensign-drive-5": "文档列表按所选排序方式显示。每个文档旁的图标表示其当前状态。", + "opensign-drive-6": "右键文档可查看下载、重命名、移动、删除等选项。点击文档可打开。", + "opensign-drive-7": "右键任意文件夹查看选项。选择“重命名”修改文件夹名,或点击文件夹浏览其内容。", + "pdf-request-file-1": "仍需签署文档的签署人列表。", + "pdf-request-file-2": "点击文档上出现的任意字段开始填写所需信息。", + "pdf-request-file-3": "填完所有必填字段后点击“完成”,即可下载已签署文档。根据发送方设置,全部接收人签署完成后你可能会收到完成文档副本及完成证书。", + "pdf-request-file-4": "已签署文档的签署人列表。", + "pdf-request-file-5": "可点击“全部自动签署”在所有应由你签署的位置自动签署。点击前请务必仔细审阅文档。", + "pdf-request-file-6": "请完成第 {{pagenumbers}} 页的字段,同色高亮便于识别。", + "placeholder-sign-1": "从列表中选择接收人以添加控件。控件拖放到文档后将与接收人名称同色。", + "placeholder-sign-2": "点击“添加接收人”按钮可添加更多签署人。", + "placeholder-sign-3": "点击此按钮为文档添加更多接收人/签署人。", + "placeholder-sign-4": "拖拽或点击控件以添加到文档。", + "placeholder-sign-5": "PDF 内容区已显示模板现有控件。为方便识别,这些控件与接收人名称同色。", + "placeholder-sign-6": "点击“下一步”将保存文档。下一步可自定义发送给接收人的邮件,或复制签署链接自行分享。", + "report-1": "点击“添加”按钮创建新模板。模板是可复用文档,用于快速生成结构相同、签署人不同的新文档。例如 HR 入职模板可预定义“HR 经理”和“新员工”角色。每次使用模板时可将“新员工”角色分配给不同入职者,而“HR 经理”角色保持不变,从而实现顺畅的入职流程。 ", + "redirect": "点击“使用”按钮从现有模板创建新文档。", + "bulksend": "仅需输入接收人邮箱即可用现有模板快速发送多份文档,点击“批量发送”按钮。最多可发送给 50 位接收人。", + "option": "此菜单显示更多选项,如编辑、删除、重命名、复制、分享等。<1>点击这里了解全部可用选项。<3>注意:对现有模板的修改将应用于此后由该模板创建的所有文档,但不会影响已发送的文档。", + "signyour-self-1": "签署前选择或拖拽所需控件到 PDF 以自定义文档。为每个控件选择合适位置以满足需求。", + "signyour-self-2": "在此区域任意拖放。之后可调整大小和移动。", + "template-placeholder-1": "点击“添加角色”按钮可添加多种签署人角色。后续步骤可为每个角色绑定用户。", + "template-placeholder-2": "添加角色后,从列表中选择一个以放置该接收人的控件。可点击控件或拖拽到文档。放置后控件与所选角色同色。", + "template-placeholder-3": "点击“下一步”将保存当前模板。保存后如需要会提示你从该模板创建新文档。", + "webhook-1": "立即升级以设置 webhook", + "Need your Signature": "点击此卡片可跳转到待你审阅的文档列表。", + "Out for signatures": "点击此卡片可跳转到待签署的文档列表。", + "Recent signature requests": "等待你签署的文档列表。", + "Recently sent for signatures": "你已发送给其他方签署的文档列表。", + "Drafts": "你已创建但尚未最终发送的文档。", + "public-template": "本视频演示如何设置个性化公开主页(如 'https://opensign.me/your-username'),以及如何自定义个性签名并将模板开放给公众签署。", + "allowModify-widgets": "除文档创建者已为你指定的字段外,你还可将这些字段任意拖放到文档上。" + }, + "enter-email-placeholder": "添加邮箱地址后按回车", + "success-email-alert": "邮件发送成功!", + "expired-doc-title": "文档已过期", + "expired-on-mssg": "该文档已于 {{expiredDate}} 过期,无法再签署。", + "signature-validate-alert": "请确认至少选择了 {{minRequiredCount}} 个复选框。", + "signature-validate-alert-2": "请确保该字段填写准确并满足全部要求。", + "remaining-users": "剩余用户", + "Role": "角色", + "additional-users": "请购买附加用户。", + "Quantity-of-users": "用户数量", + "Price": "价格", + "Total-price-for-next-time": "下次总价", + "Proceed": "继续", + "Select": "选择", + "Add-seats": "添加席位", + "user-name-exist": "用户名已存在", + "format": "格式", + "select-date-format": "选择日期格式", + "quantity-of-credits": "高级额度数量", + "remaining-credits": "可用高级额度:", + "remaining-credits-help": "高级额度可用于 API 文档签署、批量发送或在网站嵌入 OpenSign 集成。你包含 {{allowedcredits}} 个内置额度,另有 {{addoncredits}} 个已购附加额度剩余。若为 Teams 或企业套餐,这些额度可在公司全体用户间共享(除非账户管理员为你的账户设置了上限)。", + "additional-credits": "请购买高级额度", + "quota-err-quicksend": "额度已用完,你的额度不足。", + "buy-credits": "购买高级额度", + "rotate-right": "向右旋转", + "rotate-left": "向左旋转", + "rotate-alert-mssg": "本页所有控件将丢失。确定要继续吗?", + "templateid": "模板-Id", + "bulk-send-subscription-alert": "请升级到 Professional 或 Team 套餐以使用批量发送。", + "generate-test-token": "生成测试令牌", + "regenerate-test-token": "重新生成测试令牌", + "help-test-token": "该令牌可用于在 https://sandbox.opensignlabs.com/api/v1 端点测试 API,可进行不限次数的文档签署。请注意沙箱 API 会使用自签名证书签署文档,Adobe 可能不认可其有效性。测试完成后,可升级到付费套餐以生成正式令牌。", + "help-api-token": "该令牌可用于访问 {{origin}}/api/v1 端点的正式 API。仅在付费套餐下可生成。", + "reason": "原因", + "decline-by": "拒签/撤销人", + "document-declined": "文档已拒签", + "public-template-mssg-1": "要将 OpenSign 集成到你的 React 或 Next.js 项目,运行以下命令:", + "public-template-mssg-2": "确保项目已配置 npm 或 yarn。若使用 Yarn,可将 npm install 替换为 yarn add @opensign/react。", + "public-template-mssg-3": "需要更多细节或示例?", + "public-template-mssg-4": "访问 ", + "public-template-mssg-5": " npm 获取最新更新、详细文档和版本历史。", + "public-template-mssg-6": "使用此代码片段前,必须先将该模板设为公开。", + "public-template-mssg-7": "生成公开链接前,必须先将该模板设为公开。", + "here": "这里", + "copy-code": "复制", + "copied-code": "已复制", + "Installation": "安装", + "Usage": "用法", + "insufficient-credits": "签署额度不足,请联系 {{ownerEmail}}", + "insufficient-credits-title": "签署额度不足", + "insufficient-credits-mssg": "该文档的所有者当前缺少必要的 {{appName}} 额度供你签署。如需详情请联系所有者。", + "angular-npm-mssg-1": "要将 OpenSign 集成到你的 Angular 项目,运行以下命令:", + "quota-mail-info-head": "每月邮件上限", + "quota-mail-info": "为保障服务质量并防止垃圾邮件,OpenSign 免费套餐每月最多发送 15 封邮件。立即升级可不限次数发送。", + "quota-mail-reset": "你的签名请求邮件额度将于以下时间重置", + "quota-mail": "你已达到本月 15 封签名请求邮件的上限。立即升级以继续直接发送邮件。", + "quota-mail-tip": "提示:你仍可以通过手动分享签署请求链接来签署<1>无限文档。", + "quota-mail-head": "已达额度上限", + "unauthorized-modal": "你没有执行此操作的权限,请联系 {{adminEmail}}。", + "sent-this-month": "本月已发送", + "available-seats": "可用席位", + "buy-users": "购买更多用户", + "isenable-otp": "启用 OTP 验证", + "isenable-otp-help": { + "p1": "你是否要启用使用一次性密码(OTP)的验证流程?", + "p2": "选择此选项将启用 OTP 验证。用户将通过邮件收到验证码,必须输入该验证码才能签署文档。", + "p3": "选择此选项将禁用 OTP 验证,允许用户直接签署文档,无需额外步骤。", + "p4": "请选择最适合你文档签署需求的选项。" + }, + "allow-offline-sign": "允许离线签署", + "allow-offline-sign-help": { + "p1": "选择签署人是否可以提交使用外部工具签署的本文档副本以供所有者审核。", + "p2": "签署人将看到“离线签署”选项,并可上传外部签署的 PDF 供文档所有者批准。", + "p3": "签署人只能在应用内签署。“离线签署”选项将被隐藏。", + "p4": "此设置默认采用你在“偏好设置”中的账户偏好,并在付费套餐中可用。" + }, + "advanced-options": "高级选项", + "hide-advanced-options": "隐藏高级选项", + "download-files": "下载文件", + "download-pdf": "下载 PDF", + "pdf-certificate": "下载 PDF + 证书", + "document-logs": "文档日志", + "server-down": "无法连接到 {{appName}} 服务器。如果你自行托管 {{appName}},请确保已正确遵循文档中的所有步骤。如果你在本地运行 {{appName}},可能是通过错误的端口号访问。", + "admin-exists": "管理员已存在。请使用管理员凭据登录应用以管理用户。", + "enable-tour": "启用引导", + "istourenabled-help": { + "p1": "这将为签署人启用引导式操作说明,在签署过程中提供指引。", + "p2": "这将禁用引导式操作说明,确保更快、不间断的签署体验。", + "p3": "提示:如果你的签署人熟悉 {{appName}} 并经常使用,你可能希望禁用引导式操作说明以获得更流畅的体验。请选择最适合你文档签署需求的选项。" + }, + "form-title-1": "文档流程设置", + "form-title-2": "安全设置", + "public-tour-message": "在生成可分享链接之前,模板需要设为公开。", + "add-user-template": "在为角色添加字段之前,你需要先添加一个角色。", + "pdf-uncompatible": "此 PDF 不兼容,请联系 {{appName}}", + "text-field-tour": "‘预填充’字段必须在文档发送前提前填写。如果你需要签署人提供输入,请改用签署人字段。", + "attach-signer-tour": "你需要为每个角色附加一位签署人。可以点击此图标完成。选择签署人后,该签署人将附加到与此角色关联的所有字段上,这些字段以相同颜色显示。", + "allowed-signature-types": "允许的签名类型", + "at-least-one-signature-type": "至少应启用一种签名类型。", + "expect-default-one-signature-type": "请除默认类型外,再启用一种额外的签名类型。", + "add-signer-note": "注意 - 此联系人将保存到你的联系人中", + "allowed-signature-types-help": { + "p1": "此签名偏好设置控制你的签署人可用的签署选项。签署文档时,签名控件中只会显示你所选的签名类型。例如,如果你在偏好设置中仅选择‘手写’选项,你的签署人将只在签名控件中看到‘手写’选项,而其他三个选项将不可用。", + "l1": "使用手指或触控笔直接在屏幕上创建手写签名。", + "l2": "输入你的姓名并从多种字体样式中选择以创建签名。", + "l3": "上传你现有的数字版签名。", + "l4": "使用设置中‘我的签名’下保存的预设签名样式。" + }, + "notify-on-signatures": "签名时通知", + "notify-on-signatures-help": { + "p1": "每当签署人签署文档时,文档创建者都会收到邮件通知。", + "note": "注意:无论此设置如何,都会向所有签署人和文档所有者发送一封完成邮件,附带已签署的文档和完成证书。" + }, + "expiry-date": "到期日期", + "expiry-date-updated": "到期日期已成功延长至 {{newexpirydate}}", + "expiry-date-error": "请提供晚于当前到期日期的新到期日期", + "duplicate-template-alert": "你确定要创建此模板的副本吗?", + "duplicate-template-created": "副本模板创建成功。", + "delete-page": "删除页面", + "merge-pdf": "合并 PDF", + "add-pages": "添加页面", + "reorder-pages": "重新排序页面", + "delete-alert": "无法删除单页", + "delete-alert-2": "你确定要删除此页面吗?", + "delete-note": "注意:删除此页面后,无法撤销。", + "Rotation-alert": "旋转页面", + "bulk-import": "批量导入", + "contacts-file": "联系人文件(xlsx、csv)", + "import-guideline": "上传包含姓名、邮箱和可选电话列的 CSV 或 Excel 文件。仅导入前 100 条记录。", + "download-sample": "下载示例文件", + "100-records-only": "目前你最多只能导入 100 条记录。", + "csv-excel-support-only": "请上传以下格式之一的文件:CSV、XLSX 或 XLS。", + "contact-imported": "已导入 {{imported}} 个联系人。{{failed}} 个联系人导入失败。", + "invalid-data": "无效数据", + "delete-folder-alert": "你确定要删除此文件夹吗?", + "delete-folder-alert-1": "无法删除:文件夹必须为空。", + "defaultSign-alert": "{{widgetsType}} 控件不可用于自动签署。", + "embed-heading": "嵌入 {{appName}} 模板", + "other-apps-by-opensign": "OpenSign 团队的其他应用", + "public-template-edit-title": "编辑公开模板", + "public-template-edit-mssg": "你无法直接编辑公开模板。要进行更改,模板将被设为私有,之后你需要重新将其设为公开。是否继续?", + "agree-p1": "我确认我已阅读并理解 ", + "agree-p2": "电子记录与签名披露声明", + "agree-p3": "并同意使用电子记录和签名。", + "agrre-button": "我确认并同意继续", + "term-cond-title": "条款与条件", + "term-cond-h": "电子记录与签名披露声明", + "term-cond-p1": "本电子记录与签名披露声明(“披露声明”)是文档创建者(“发送方”)与签署人(“你”)之间通过 {{appName}} 平台(“平台”)达成的协议。通过 {{appName}} 签署文档,即表示你同意本披露声明中所列的条款。请在继续前仔细阅读。", + "term-cond-h1": "1. 目的与范围", + "term-cond-p2": "本披露声明规范通过 {{appName}} 平台由发送方发送并由你签署的文档所使用电子记录和签名的方式。同意即表示你确认:", + "term-cond-p3": "你将通过 {{appName}} 以电子方式接收并签署文档。", + "term-cond-p4": "你的电子签名具有法律约束力,等同于手写签名。", + "term-cond-h2": "2. 使用电子记录和签名的同意", + "term-cond-p5": "同意本披露声明即表示:", + "term-cond-p6": "你同意使用 {{appName}} 与发送方进行电子交易,并理解此同意在撤回前一直有效。", + "term-cond-p7": "你同意使用 {{appName}} 以电子方式审阅、签署并返回文档。", + "term-cond-p8": "此同意仅适用于发送方提供的特定文档。", + "term-cond-h3": "3. 撤回同意的权利", + "term-cond-p9": "你有权通过以下方式撤回使用电子记录和签名的同意:", + "term-cond-p10": "使用其沟通中提供的联系信息直接联系发送方。", + "term-cond-p11": "在完成签署流程前通知发送方。", + "term-cond-h4": "4. 硬件与软件要求", + "term-cond-p12": "要使用 {{appName}} 签署文档,你必须具备:", + "term-cond-p13": "一台可访问互联网的设备。", + "term-cond-p14": "一个启用了 JavaScript 的兼容网页浏览器。", + "term-cond-p15": "一个用于接收通知和已签署文档的邮箱账户。", + "term-cond-p16": "如果这些要求发生变化,发送方或 {{appName}} 将通知你相关更新。", + "term-cond-h5": "5. 记录保存与纸质副本请求", + "term-cond-p17": "你负责确保自己能够访问并保存电子签署的文档。{{appName}} 提供工具,可在签署流程完成后立即下载或打印已签署的文档。", + "term-cond-p18": "如果你更希望获得任何电子签署文档的纸质副本,可直接向发送方请求。除非适用法律禁止,发送方可对提供纸质副本收取合理费用。", + "term-cond-h6": "6. 确认与协议", + "term-cond-p19": "继续操作即表示你:", + "term-cond-p20": "确认你可以按照本披露声明所述访问并审阅电子文档。", + "term-cond-p21": "同意在与发送方的指定交易中使用电子记录和签名。", + "term-cond-p22": "理解 {{appName}} 是促成交易的平台,并非协议的一方。", + "term-cond-h7": "7. 法律效力", + "term-cond-p23": "你通过 {{appName}} 促成的电子签名:", + "term-cond-p24": "符合适用的电子签名法律,包括但不限于美国的 E-SIGN 法案、欧盟的 eIDAS 条例以及印度的信息技术法。", + "term-cond-p25": "在你与发送方之间就已签署的文档具有法律约束力。", + "term-cond-h8": "8. 平台角色与责任限制", + "term-cond-p26": "{{appName}} 作为促成电子交易的平台。它对发送方所发文档的内容、有效性或可执行性不承担责任。与文档或其签署相关的任何争议或问题,必须由你与发送方直接解决。", + "term-cond-h9": "9. 协议终止", + "term-cond-p27": "除非发送方另有说明,你的同意仅适用于当前交易。{{appName}} 保留对违反其服务条款或政策的行为终止平台访问的权利。", + "term-cond-p28": "选择‘我同意’即表示你确认理解并同意本电子记录与签名披露声明的条款,并同意通过 {{appName}} 以电子方式签署发送方提供的文档。", + "term-cond-p29": "如果你对本披露声明有疑问,请直接联系发送方。如需 {{appName}} 的技术支持,请访问 ", + "term-cond-p30": " 或发送邮件至", + "js-snippet-msg": "要将 {{appName}} 模板集成到你的 HTML 网站或落地页,可以使用以下代码:", + "js-snippet-msg-1": "你可以从", + "js-snippet-msg-2": "管理模板", + "js-snippet-msg-3": "页面获取 TemplateId。", + "webhook-already-exists": "该 URL 已存在!请尝试其他 URL。", + "webhook-must-be-secure": "Webhook URL 必须是安全的并使用 https://", + "provide-test-token": "请生成 API 测试令牌", + "invalid-redirect-url": "请提供有效的重定向 URL。", + "auto-sign-mssg": "全部自动签署", + "already-exist-signer": "所选签署人已存在", + "change-signer": "更改签署人", + "signyour-self-button": "使用此选项自行签署文档,无需添加他人", + "requestsign-button": "使用此选项请求他人和你自己一起签署。", + "signyour-self-description": "使用此表单自行签署文档,无需添加他人", + "requestsign-description": "使用此表单请求他人和你自己一起签署。", + "template-form-description": "使用此表单为你的文档创建可复用的模板。", + "allow-modify": " 允许修改", + "allow-modify-help": { + "p1": "你是否要允许在签署过程中修改文档?", + "p2": "选择此选项允许签署人在现有控件之上添加额外元素,例如签名、姓名缩写、印章或文本。", + "p3": "选择此选项将限制签署人在签署过程中对文档进行任何添加。" + }, + "signature-setting": "签名设置", + "rotation": "旋转", + "activation-key": "激活密钥", + "paid-selfhost-help": "如需更多信息,请联系 {{appName}}: ", + "remaining-credits-selfhost-help": "使用高级额度进行 API 文档签署、批量发送、在你的网站上集成 {{appName}}。你有 {{allowedcredits}} 个所含额度和 {{addoncredits}} 个额外购买的剩余额度。", + "signature-type": "你的签名", + "initial-type": "你的姓名缩写", + "redirect-url": "重定向 URL", + "bulk-send": "批量发送", + "select-timezone": "时区", + "current-time": "当前时间", + "email-help": "出于安全原因,你不被允许更改邮箱地址。请使用新的邮箱地址创建另一个免费账户。", + "doc-sent": "文档发送成功。", + "no-signer": "移除", + "and": "和", + "make-public": "设为公开", + "general": "常规", + "request-email": "请求邮件", + "completion-email": "完成邮件", + "variables-use": "可使用的变量", + "send-to-sign": "请求你签署", + "use-template": "使用模板", + "contact-already-exists": "联系人已存在。", + "docx-error": "我们目前在处理 DOCX 文件时遇到一些问题。请上传 PDF 文件", + "docx-error-contact": "或通过 support@opensignlabs.com 联系我们", + "excel-error": "我们目前在处理 Excel 文件时遇到一些问题。请上传 PDF 文件", + "excel-error-contact": "或通过 support@opensignlabs.com 联系我们", + "agreement-note": "注意:同意此声明并不意味着你立即签署文档。这仅允许你以电子方式审阅文档。你将有机会完整阅读并随后决定是否签署。", + "draft-template-info-p1": "要使模板公开,它必须只包含单个角色;或者,如果包含多个角色,所有额外角色都必须已分配给签署人。未分配的公开角色应保持为空,并且必须置于第一个位置。", + "visit-below-link": "访问以下链接了解更多 -", + "storage-help": "启用 BYOC 可让你连接自己的 S3 存储,使你的文件完全处于你的控制之下——不保留任何外部副本。如果数据自主性对你很重要,请考虑升级到 Teams 以解锁此功能。", + "daily-quota-reached": "你已达到每日额度上限。如需帮助,请联系 quotas@opensignlabs.com。", + "email-not-verified-send": "请在发送邮件前验证你的邮箱地址。前往你的<1>个人资料设置完成邮箱验证。", + "email-not-verified-send-plain": "请在发送邮件前验证你的邮箱地址。前往你的个人资料设置完成邮箱验证。", + "enabled-signature-type": "已启用的签名类型", + "enabled-signature-type-help": "‘已启用的签名类型’设置决定你的整个组织可用的签名选项。例如,如果你禁用‘手写’选项,你组织的成员将不会在签名控件中看到它,而其他三个选项仍可访问。", + "indexing-public-profile": "允许搜索引擎索引公开主页", + "user-created-successfully": "用户创建成功。", + "only-15-reminder-allowed": "你最多可设置 15 次自动提醒。例如,如果‘完成时限’为 15 天且‘每隔多久提醒一次’为 1 天,你将达到 15 次提醒的上限。请相应调整你的设置。", + "rate-your-experience": "你使用 {{appName}} 的体验如何?", + "thanks-for-feedback": "感谢你的反馈 🙏", + "share-your-feedback": "分享你的反馈", + "share-your-review": "分享你的评价", + "please-select-rating": "请选择一个评分", + "feedback-optional": "反馈(可选)", + "feedback-saved": "反馈已保存。", + "feedback-save-error": "无法保存反馈,请重试。", + "date-format": "日期格式", + "document-deleted": "文档已被删除或你没有访问权限。请联系发送方。", + "save-as-template-?": "你确定要将此文档保存为模板吗?", + "go-to-manage-templates": "前往‘管理模板’", + "template-created": "模板已创建", + "how-would-you-like-to-proceed?": "你希望如何继续?", + "failed-to-load-refresh-page": "加载文档失败。请尝试刷新此页面。", + "document-has-been-signed": "文档已成功签署!", + "document-has-been-signed-by-you": "你已成功签署文档!", + "participant-completed-signing": "所有参与者都已完成签署流程。", + "you-will-receive-email-shortly": "✅ 就是这样!你很快会收到一封确认邮件。", + "please-provide-templateid": "请提供 templateid", + "this-template-is-not-public": "此模板未公开", + "invalid-templateid": "无效的 templateid", + "kiosk-no-active-role": "此模板没有可用于自助终端签署的签署人或审批人角色。", + "contact-billing-at-opensign": "要添加更多席位,请联系 OpenSign™:<1>billing@opensignlabs.com 获取帮助", + "title-length-alert": "标题最多 250 个字符。", + "note-length-alert": "备注最多 200 个字符。", + "description-length-alert": "描述最多 500 个字符。", + "fix-&-resend-document": "修复并重新发送文档", + "do-you-want-recreate-document?": "这将基于此文档创建一个草稿,保留所有字段。你确定要重新创建此文档吗?", + "start-editing": "开始编辑", + "unsaved-changes-discard-them?": "你有未保存的更改。要放弃它们吗?", + "yes-discard": "是,放弃", + "LTV-enabled-signatures": "启用 LTV 的签名", + "BETA": "测试版", + "two-factor-authentication": "双重验证", + "2fa-help-text": "双重验证通过要求除密码外的更多信息登录,为你的账户增加一层额外的安全保护。", + "2fa-help-bullet1": "通过同时要求密码和验证码来增强安全性。", + "2fa-help-bullet2": "验证码由你设备上的身份验证器应用生成。", + "2fa-help-bullet3": "即使你的密码泄露,也能保护你的账户。", + "setup-2fa": "设置 2FA", + "setup-2fa-again": "重新设置 2FA", + "2fa-setup-intro": "使用双重验证保护你的账户。启用后,你每次登录时都需要输入来自身份验证器应用的验证码。", + "scan-qr-code": "扫描二维码", + "scan-qr-instructions": "使用 Google Authenticator、Microsoft Authenticator 或 Authy 等身份验证器应用扫描此二维码。", + "manual-setup-instructions": "无法扫描二维码?你可以使用此密钥手动设置身份验证器应用:", + "secret-key": "密钥", + "copied-to-clipboard": "已复制到剪贴板", + "copy-to-clipboard": "复制到剪贴板", + "recovery-codes": "恢复码", + "recovery-codes-instructions": "请将这些恢复码保存在安全的地方。如果你无法访问身份验证器应用,可以使用其中一个一次性恢复码登录。", + "download-recovery-codes": "下载恢复码", + "verification-code": "验证码", + "enter-code-from-authenticator-app": "输入来自身份验证器应用的 6 位验证码", + "verification-code-required": "验证码为必填项", + "verification-code-invalid": "验证码无效。请重试。", + "2fa-enabled": "2FA 已启用", + "2fa-enabled-successfully": "双重验证已成功启用", + "2fa-setup-complete": "设置完成!", + "2fa-setup-complete-instructions": "你的账户现已受到双重验证保护。你每次登录时都需要输入验证码。", + "two-factor-verification": "双重验证", + "enter-verification-code-instructions": "输入来自身份验证器应用的 6 位验证码以继续。", + "recovery-code": "恢复码", + "enter-recovery-code-help": "输入你的其中一个恢复码", + "recovery-code-required": "恢复码为必填项", + "use-verification-code-instead": "改用验证码", + "use-recovery-code-instead": "改用恢复码", + "regenerate-2fa-remove-existing": "你确定要重新生成双重验证吗?此操作将移除你现有的验证设置。", + "use-passkey": "使用通行密钥登录", + "security-section": "安全", + "passkey-authentication": "通行密钥验证", + "passkey-not-supported": "你的浏览器或设备不支持通行密钥验证", + "passkey-description": "通行密钥提供了比密码更强、可抵御网络钓鱼的替代方案。你可以使用指纹、人脸识别或设备 PIN 码安全登录。", + "passkey-tooltip": "通行密钥是比密码更简单、更安全的替代方案。它们使用已存储在你设备上的指纹或人脸识别等生物特征数据。", + "security-section-help": "管理安全选项,包括通行密钥和验证方式,以保护你的账户。", + "passkey-register": "注册通行密钥", + "passkey-register-another": "注册另一个通行密钥", + "passkey-registered": "通行密钥已注册", + "passkey-registering": "正在注册通行密钥...", + "passkey-registered-success": "通行密钥注册成功!", + "passkey-registration-failed": "通行密钥注册失败", + "passkey-auth-failed": "通行密钥验证失败", + "passkey-missing-user-info": "需要用户信息", + "passkeys-list": "你的通行密钥", + "default-passkey": "你的通行密钥", + "passkey-rename": "重命名", + "passkey-delete": "删除", + "passkey-rename-title": "重命名通行密钥", + "passkey-delete-title": "删除通行密钥", + "passkey-delete-confirm": "你确定要删除通行密钥“{{name}}”吗?", + "passkey-name": "通行密钥名称", + "passkey-name-placeholder": "为此通行密钥输入一个描述性名称", + "passkey-renamed-success": "通行密钥重命名成功", + "passkey-deleted-success": "通行密钥删除成功", + "passkey-rename-failed": "通行密钥重命名失败", + "passkey-delete-failed": "通行密钥删除失败", + "processing": "处理中...", + "today": "今天", + "yesterday": "昨天", + "days-ago": "{{days}} 天前", + "verify-with-passkey": "使用通行密钥验证", + "verify-with-otp": "使用 OTP 验证", + "verification": "验证", + "verify-account": "验证你的账户", + "verify-identity": "验证身份", + "passkey-verification-failed": "通行密钥验证失败。请重试或使用 OTP。", + "security-auth-help": { + "p1": "管理你账户的安全设置以保护你的数据。OpenSign 支持先进的验证方式来增强账户保护。", + "2fa-auth-help": " 通过启用 2FA 增加一层额外的安全保护。这需要你在输入密码后,再输入来自身份验证器应用的验证码。", + "passkey-auth-help": "使用通行密钥进行无密码登录,通过生物特征或设备验证,兼具强安全性和便利性。" + }, + "signer-already-present": "签署人已存在", + "kiosk-sign": "自助终端签署", + "do-not-have-access-to-template": "模板已被删除或你没有访问权限。请联系发送方。", + "kiosk-info": "自助终端模式可让你快速高效地收集现场签名。非常适合所有签署人都在场的展会、活动或到店场景。 ", + "learn-more": "了解更多", + "finish-mssg": " 你确定要完成此文档吗?", + "review": "审阅", + "next-field": "下一个字段", + "required-mssg": "还剩 {{leftRequiredWidget}} / {{totalWidget}} 个字段", + "verify-document": "验证文档", + "verify-document-signature": "验证文档签名", + "select-pdf-document": "选择 PDF 文档", + "selected-file": "已选文件", + "verify-signature": "验证签名", + "verification-status": "验证状态", + "verification-in-progress": "验证进行中...", + "verification-results-will-appear-here": "验证结果将显示在此处", + "please-select-pdf": "请选择有效的 PDF 文件", + "please-select-file-to-verify": "请选择要验证的文件", + "no-signature-found": "文档中未找到签名", + "error-verifying-pdf": "验证 PDF 时出错", + "signature-valid-basic": "签名有效", + "signature-invalid-basic": "签名无效", + "all-signatures-verified-convincing": "文档已验证:所有签名均已成功验证。", + "some-signatures-invalid-basic": "部分签名无效", + "no-signatures-processed": "未处理任何签名", + "unnamed-signature-field": "未命名签名字段", + "error-processing-signature": "处理签名时出错", + "signer-info-not-available": "签署人信息不可用", + "cert-validity-not-checked": "未检查证书有效性", + "valid": "有效", + "expired-or-not-yet-valid": "已过期或尚未生效", + "valid-from": "生效自", + "to": "至", + "signer": "签署人", + "issuer": "颁发者", + "not-available": "不可用", + "not-performed": "未执行", + "missing-acrofield-dict": "缺少 acrofield 字典", + "signature-dictionary-not-found-or-invalid": "未找到签名字典或字典无效", + "missing-or-invalid-byterange": "缺少或无效的 ByteRange", + "missing-or-invalid-contents": "缺少或无效的 Contents", + "missing-signature-contents": "缺少签名内容", + "invalid-signature-hex-format": "无效的签名十六进制格式", + "unsupported-signature-format-not-signeddata": "不支持的签名格式 - 非 SignedData", + "signer-certificate-not-found": "未找到签署人证书", + "no-certificates-in-signature": "签名中没有证书", + "no-signer-info-in-pkcs7": "PKCS#7 中没有签署人信息", + "could-not-parse-signer-info": "无法解析签署人信息", + "not-calculated": "未计算", + "not-found-in-signature": "签名中未找到", + "readonly-error": "只读的 {{widgetName}} 控件必须有默认值,或者你可以将其设为可选。", + "choose-one": "选择其一", + "search-templates": "搜索模板…", + "search-documents": "搜索文档…", + "search-contacts": "搜索联系人…", + "add-role-alert": "请至少添加一个角色", + "edit-draft": "编辑草稿", + "vertical": "垂直", + "horizontal": "水平", + "billing": "账单", + "console": "控制台", + "prefill-widget": "预填充控件", + "action-prohibited": "你的邮箱域名不允许执行此操作。请联系你的管理员获取帮助。", + "must-have-at-least-one-vacant-role": "在将模板设为‘公开’之前,你必须至少有一个未分配的角色。", + "remove-duplicate": "请移除重复的选项", + "prefill-bulk-error": "添加预填充控件时不允许批量发送。请移除预填充控件以继续。", + "session-expired-title": "会话已过期", + "access-denied": "访问被拒绝", + "upgrade": "升级", + "do-not-access-app": "你没有访问此应用的权限。", + "do-not-have-access": "你没有访问权限。", + "valid-email-alert": "请输入有效的邮箱地址。", + "otp-not-validate": "OTP 无效。", + "domain-not-allowed": "不允许此域名", + "atleast-one-recipient-alert": "请至少添加一位收件人!", + "incorrect-password-or-decryption-failed": "密码错误或解密失败。", + "incorrect-password-for-file": "文件密码错误:{{file}}", + "error-uploading-pdf": "上传 PDF 时出错。", + "provide-password": "请提供密码。", + "only-pdf-allowed": "仅允许 PDF 文件。", + "invalid-username-password-region": "无效的用户名/密码或区域。", + "pfx-extension-alert": "请上传扩展名为 .pfx 的文件。", + "email-already-exist": "邮箱已存在", + "branding": "品牌", + "branding-help": "品牌功能为你的应用提供白标服务", + "custom-sub-domain": "自定义子域名", + "app-name": "应用名称", + "provide-domain-name": "仅允许子域名(例如 app.yourdomain.com)。不支持 yourdomain.com 这样的主域名/根域名。", + "provide-app-name-help": "提供一个唯一的应用名称。它将作为你的品牌名称显示在应用中以及所有应用了品牌的邮件里。", + "upload-app-logo": "上传 .png、.jpg 或 .svg 格式的标志。推荐尺寸:{{size}} 像素(5:2 宽高比)以获得最佳显示质量。", + "upload-app-favicon": "上传一个正方形网站图标图片(.ico、.png 或 .svg)。推荐尺寸为 {{size}} 像素以获得最佳浏览器兼容性。", + "provide-app-name": "提供你的应用名称", + "logo": "标志", + "prefill-unfilled-widget": "以下必填字段不能为空:{{emptyWidget}} 请填写后再继续。", + "Dashboard": "仪表盘", + "Analytics": "分析", + "Templates": "模板", + "Need your sign": "需要你签署", + "In Progress": "进行中", + "Completed": "已完成", + "Drafts": "草稿", + "Declined": "已拒绝", + "Expired": "已过期", + "Contactbook": "联系人簿", + "My Signature": "我的签名", + "API Token": "API 令牌", + "Webhook": "Webhook", + "Preferences": "偏好设置", + "Teams": "团队", + "Users": "用户", + "Drive": "云盘", + "Branding": "品牌", + "Mail": "邮件", + "Storage": "存储", + "Signing certificate": "签名证书", + "General": "常规", + "Organizations": "组织", + "OrgAdmins": "组织管理员", + "Debug Pdf": "调试 Pdf", + "New Document": "新建文档", + "subscription": "订阅", + "Draft document": "草稿文档", + "Draft template": "草稿模板", + "Public sign": "公开签署", + "Signup": "注册", + "delete-contact": "删除联系人", + "total-records-found": "找到记录总数:{{count}}", + "Invalid-records-found": "找到无效记录:{{records}}", + "previous": "上一页", + "page-n-of-n": "第 {{currentPage}} 页,共 {{totalPages}} 页", + "import": "导入", + "search": "搜索", + "viewed-on": "查看于:{{ViewedOn}}", + "signed-on": "签署于:{{SignedOn}}", + "hide": "隐藏", + "show-more": "显示更多", + "browse-or-drag-to-replace-existing-file": "浏览或拖放新文件以替换现有文件", + "optional-details": "可选详情", + "hide-optional-details": "隐藏可选详情", + "mail-adapter-subscription-alert": "请升级到 Professional 或 Team 套餐以设置自定义 SMTP。", + "connect-to-mail": "连接到 Gmail", + "custom-smtp": "自定义 SMTP", + "default-smtp": "{{appName}} 默认 SMTP", + "host": "主机", + "port": "端口", + "sender-email": "发件人邮箱", + "username": "用户名", + "use-default-mail-adapter": "你确定要使用 {{appName}} 的默认邮件服务器发送你的签名请求邮件吗?我们建议使用你自己的 Gmail 或 SMTP 服务器以提升收件箱送达率。", + "verification-code-sent-registered-email": "验证码已发送到你注册的邮箱 <1>{{useremail}} 以确认你的设置。请在下方输入验证码。", + "smpt-credentials": "SMTP 凭据", + "delete-account": "删除账户", + "delete-account-que": "你确定要删除你的账户吗?", + "delete-account-que-user": "你即将永久删除此用户及所有关联数据。此操作无法撤销。", + "user-deleted-successfully": "用户及所有关联数据已成功删除。", + "account-deletion-request-sent-via-mail": "我们已通过邮件向你发送确认链接。批准该请求以完成账户删除。", + "type-exact-email-delete": "输入准确的邮箱以启用删除", + "email-does-not-match": "邮箱不匹配。", + "please-type-to-confirm": "请输入 <1>{{userEmail}} 以确认:", + "email-settings": "邮件设置", + "email-settings-help": " 为确保你的签名请求邮件有更好的收件箱送达率,你可以连接自己的邮件服务商。选择以下选项之一:", + "connect-to-gmail": "连接到 Gmail: ", + "connect-to-gmail-help": "使用你的 Gmail 账户直接从你自己的收件箱发送签名请求邮件,提升送达率和可靠性。", + "connect-to-smtp": "自定义 SMTP: ", + "connect-to-smtp-help": "使用你的自定义 SMTP 服务器通过你的域名发送邮件。此选项让你完全掌控邮件基础设施,提升送达率和品牌一致性。", + "connect-to-default": "如果你愿意,也可以使用 {{appName}} 默认邮件服务器,但我们建议使用你自己的以获得最佳效果。", + "email-settings-redirect-message": "此设置已从控制台移至 主菜单设置 → 偏好设置。此页面将在后续版本中移除。", + "go-to-preferences-menu": "前往偏好设置菜单", + "document-download-filename-format": "文档下载文件名格式", + "preview": "预览: ", + "download-filename-format-help": "选择下载的 PDF 如何命名。你的选择将保存到个人资料中,并在整个应用中使用。", + "delete-action-prohibited": "不允许执行此操作。请联系你的管理员请求删除账户。", + "not-verified": "未验证", + "verified": "已验证", + "expires": "到期", + "fix-resend-error": "你无法修复并重新发送此文档,因为它包含预填充控件。", + "duplicate-template-error": "你无法复制此模板,因为它包含预填充控件。", + "save-as-template-error": "此文档无法保存为模板,因为它包含预填充控件。", + "redirecting-you-in": "{{redirectTimeLeft}} 秒后为你重定向...", + "pdf-tools-tour": "点击这些按钮可添加、删除、重新排序、旋转和缩放页面。", + "widgets": "控件", + "prefill-tour": "使用此选项在将文档发送给收件人前提前输入信息。", + "empty-prefill-error": "以下必填字段不能为空:", + "please-fill-out": "请填写后再继续。", + "custom-signing-certificate": "自定义签名证书", + "signing-certificate-help": "你可以上传自己的文档签名证书,它将用于签署你的所有文档以及完成证书。证书文件应为 PFX 格式的 P12 证书。", + "certificate-file-p12-in-PFX-format": "证书文件(PFX 格式的 p12 证书)", + "password-of-pfx-file": "输入 pfx 文件的密码", + "update": "更新", + "use-default-certificate": "使用默认 {{appName}} 证书", + "upgrade-to-team-plan": "升级到 Team 套餐", + "setup-file-storage": "设置文件存储", + "save-and-activate": "保存并激活", + "logging-out-to-apply-settings": "正在将你登出以应用新设置", + "reconnect-to-default": "重新连接到 {{appName}}", + "active-file-adapter": "活动文件适配器", + "file-adapter-unique-name": "文件适配器唯一名称", + "unique-name-for-file-adapter": "为文件适配器输入唯一名称", + "storage-provider": "存储服务商", + "enter-bucket-name": "输入存储桶名称", + "enter-space-name": "输入空间名称", + "enter-region-of-bucket": "输入存储桶所在区域", + "enter-region-of-space": "输入空间所在区域", + "enter-access-key": "输入访问密钥", + "enter-secret-access-key": "输入秘密访问密钥", + "otp-email": "我们已将验证码发送至", + "save-as-temp-warn": "注意:此文档包含预填充控件,由于它们已并入基础文档,将被自动移除。", + "edit-document": "编辑文档", + "modify": "修改", + "merge-certificate-to-pdf": "将证书合并到 PDF", + "merge-cc-to-pdf-help": { + "p1": "这将确保完成证书包含在最终的 PDF 文档中。但请注意,一旦合并,证书将无法从主文档中分离。", + "p2": "如果你选择不合并,完成证书将作为单独的 PDF 文件与已签署文档一并提供。" + }, + "read-only-date-error": "只读日期控件必须有默认日期。", + "set-date": "设置日期", + "default-date": "默认日期", + "set-today": "签署日期", + "enter-name": "输入姓名", + "enter-email": "输入邮箱", + "subscribe-to-opensign-msg": "订阅 {{appName}},享受无限免费数字签名。", + "duplicate-subscribe-msg": "复制可让你创建所选模板的完全副本,便于你复用或修改而不影响原件。", + "save-as-template-msg": "将此文档保存为可复用模板,以便将来再次用于其他文档。", + "public-credit-alert": "通过此链接签署会消耗你的免费邮件额度。作为免费用户,你每月可获得 15 个邮件额度,以防止垃圾邮件发送者滥用我们的系统。要享受更高限额和不间断访问,请订阅 <1>OpenSign™ 付费套餐。", + "know-more-about": "了解更多关于", + "free-unlimited-signatures": "免费无限签名", + "email-quota-updated": "每日邮件额度更新成功。", + "password-has-been-reset": "密码已重置。", + "Unauthorized to reset your own password.": "无权重置你自己的密码。", + "User not found or not allowed.": "未找到用户或不允许。", + "User not found.": "未找到用户。", + "Admin user tenant not found.": "未找到管理员用户租户。", + "User is not authenticated.": "用户未通过身份验证。", + "Please provide required parameters.": "请提供必需的参数。", + "reset-password": "重置用户密码", + "enter-strong-password": "输入一个强密码或自动生成一个。", + "autogenerate": "自动生成", + "extend": "延长", + "console-general-help": "要让各个用户自定义他们自己的邮件模板,请前往", + "console-mail-help": "要更新公司范围的邮件模板,请前往", + "admin-setting-disabled": "此设置已禁用。请联系管理员获取帮助。", + "company-email-settings": "公司邮件设置", + "allow-email-template-individually": "允许用户单独自定义邮件模板 ", + "user-email-template-general-help": "禁用此选项将阻止用户自定义他们的邮件模板。", + "disable-individual-user-smtp": "禁用单个用户的 SMTP 设置", + "enable-individual-user-smtp": "启用单个用户的 SMTP 设置", + "user-smtp-general-help": "禁用后,用户将无法配置自己的 SMTP 设置。所有邮件将改用全局 SMTP 配置。", + "hide-live-chat-for-signers": "为签署人隐藏在线聊天控件", + "hide-live-chat-for-signers-help": "启用后,在线聊天控件将在所有签署页面上隐藏。窗口变量 'opensign_hide_chat' 会被设为 true,可用作 GTM 触发条件,以防止为签署人加载该控件。", + "global-smtp-settings": "全局 SMTP 设置", + "global-smtp-settings-help-p1": "这些设置在你整个 {{appName}} 账户中全局生效。如果某个用户未配置自己的邮件投递设置,系统将自动使用此处定义的全局 SMTP 设置。", + "global-smtp-settings-help-p2": "为确保所有签名请求邮件有更好的收件箱送达率,你可以连接你偏好的邮件服务商。选择以下选项之一:", + "global-connect-to-gmail-help": "使用 Gmail 账户直接从你组织的收件箱发送签名请求邮件。这可提升送达率、信誉度和整体可靠性。", + "global-connect-to-smtp-help": "使用你自己的 SMTP 服务器通过你的域名发送邮件。这可让你完全掌控邮件基础设施,提升送达率并保持一致的品牌形象。", + "global-smtp-settings-help-p3": "如果未配置任何用户级别的设置,将自动应用这些全局设置。", + "hide-text-with-asterisks": "用星号隐藏文本", + "hide-text-with-asterisks-help": "已签署文档上的文本将被隐藏,但文档发送方(所有者)仍可从其 {{appName}} 账户访问。", + "document-id": "文档 ID", + "sent-date": "发送日期", + "status": "状态", + "signer-form-data-for": "签署人表单数据:{{signerName}} <{{signerEmail}}>", + "widget-name": "控件名称", + "widget-responses": "控件响应", + "formdata-download-note": "注意:签名、印章、姓名缩写和图片不会被导出。离线签署人的数据将不可用。", + "export-all-formdata-error": "你无法导出表单数据,因为该模板包含重复的控件名称。请创建一个新模板以便导出表单数据。", + "export-formdata-error": "你无法导出表单数据,因为该文档包含重复的控件名称。请创建一个没有重复控件名称的新文档以便导出表单数据。", + "duplicate-widget-name-error": "此控件名称已分配给另一位签署人。请选择不同的名称。", + "duplicate-template-widget-error": "无法复制模板,因为某些控件名称在不同角色间重复。请重命名重复的控件后重试。", + "credit-alert": "额度提醒", + "document-form-data": "文档表单数据", + "view-formdata-paid-title-error": "查看表单数据功能可让你打印和下载签署人在签署时填写的控件数据。", + "view-formdata-paid-error": "注意:‘查看表单数据’功能仅适用于 v2.32.0 及之后创建且不含重复控件名称的文档。", + "download-all-formdata-paid-title-error": "下载全部表单数据功能可让你下载从该模板创建的所有文档中签署人填写的控件数据。", + "download-all-formdata-paid-error": "注意:‘下载全部表单数据’功能仅适用于 v2.32.0 及之后创建且不含重复控件名称的模板。", + "api-token-not-found": "未找到 API 令牌。", + "sub-head-api-credits": " 定义此用户被允许消耗的最大 API 额度数量。", + "consumed-credits": "已消耗额度", + "allowed-api-credits": "允许的 API 额度", + "allowed-api-credits-help": "允许的额度应大于或等于已消耗的额度。", + "Enter-allowed-api-credits": "输入允许的 API 额度", + "login-to-sandbox": "登录沙箱", + "your-credits-usage": "你的额度使用情况", + "remaining": "剩余", + "used": "已用", + "your-credits-usage-help": "这是使用你的 API 密钥所消耗的额度数量。", + "api-credits-updated": "API 额度已成功分配。", + "min-date": "最小日期", + "max-date": "最大日期", + "invalid-min-date": "无效的最小日期。", + "min-less-max": "最小日期必须小于或等于最大日期。", + "invalid-max-date": "无效的最大日期。", + "max-less-min": "最大日期必须大于或等于最小日期。", + "date-range": "日期范围", + "date-range-help": "设置最小和/或最大值以限制选择。所选日期必须在范围内。", + "option-disabled-by-owner": "文档创建者已禁用此选项", + "pen-colors": "画笔颜色", + "pen-colors-help": "选择签名和姓名缩写控件可用的画笔颜色。勾选以显示某种颜色,取消勾选以隐藏它。", + "security-key": "安全密钥", + "remove-limit": "移除限制", + "removed-api-credits": "API 额度限制已移除。", + "enable-authentication": "启用身份验证", + "working": "运行中", + "test-security-key": "测试安全密钥", + "generate": "生成", + "regenerate": "重新生成", + "signing-date": "签署日期", + "date-widget": "日期控件", + "mail-failed": "发送邮件时出现问题。请重试。", + "mail-status-head": "下一步:签署你的文档?", + "send-to-email": "发送至邮箱", + "date-pref-help-sub-title": "日期控件偏好设置可让你定义日期控件的默认设置。每当你向文档或模板添加新的日期控件时,都会自动应用这些默认值。你仍可随时点击齿轮图标自定义任意单个日期控件。", + "date-pref-help-format": "选择日期控件使用的默认日期格式。", + "date-pref-help-default-date": "为日期控件设置默认日期值。", + "date-pref-help-signing-date": "启用后,日期控件将自动使用签署人签署文档的日期。", + "date-pref-help-read-only": "启用后,日期控件对签署人只读。", + "upload-csv": "上传 CSV", + "file-selected": "个文件已选择", + "bulk-send-csv-helper": "使用表头表示签署人角色(Role Email/Name/Phone)和预填充值(Prefill: Field Name)。必填的预填充字段必须完成。", + "bulk-send-csv-helper-note": "注意:对于 CSV 中日期类型的预填充字段,值必须按此格式提供:{{value}}(示例:{{example}})。", + "bulk-send-csv-summary": "已从 CSV 导入 {{total}} 行。", + "bulk-send-csv-missing-headers": "缺少必需的 CSV 表头。角色:{{roles}}。", + "bulk-send-no-records": "发送前请至少添加一位收件人。", + "csv-only-support": "仅支持 CSV 文件。", + "csv-no-records": "CSV 中未找到记录。", + "select-at-least-option": "请至少选择一个选项。", + "draw-required": "请在框内绘制。", + "enter-smtp-username": "输入你的 SMTP 用户名", + "enter-webhook-url": "输入 webhook url", + "enter-user-name": "输入用户名", + "enter-tagline": "输入个性签名", + "enter-password-or-click-autogenerate": "输入密码或点击自动生成", + "enter-daily-email-quota": "输入每日邮件额度", + "enter-custom-regular-expression": "输入自定义正则表达式", + "enter-value": "输入 {{value}}", + "are-you-sure-want-to-send-document": "你确定要发送文档吗?", + "favicon": "网站图标", + "delete-two-factor-authentication": "你确定要删除双重验证吗?", + "paste-html-here": "在此粘贴 HTML", + "open-email-builder": "你可以使用 <1>邮件构建器 平台创建邮件模板并复制 html 代码。", + "contact-saved": "联系人保存成功。", + "remove-limit-of-user": "你确定要移除此用户的限制吗?他们将能够消耗你组织中所有用户共享的全部可用高级额度。", + "current-expiry-date": "当前到期日期", + "reminder-error": "每隔多久提醒一次(天)不得超过完成时限(天)", + "showing-to-of-records": "显示第 {{record}} 至 {{recordPerPage}} 条,共 {{totalRows}} 条记录", + "records-per-page": "每页记录数", + "email-not-found-in-row": "第 {{row}} 行未找到邮箱", + "invalid-email-found-in-row": "第 {{row}} 行发现无效邮箱:{{email}}", + "duplicate-email-found-in-row": "第 {{row}} 行发现重复邮箱:{{email}}", + "prefill": "预填充", + "recipients-&-data": "收件人与数据", + "response": "响应", + "prefill-tab-help": "这些是通用模板字段,将应用于本次批量发送中的所有文档。", + "recipient-tab-help-p1": "在接下来的这一步,你将", + "recipient-tab-help-p2": "上传包含收件人详情的 CSV,或", + "recipient-tab-help-p3": "手动输入收件人信息", + "recipient-tab-help-p4": "每位收件人都会收到由此模板生成的专属文档。", + "response-tab-help": "审阅你的响应。", + "summary": "摘要", + "prefill-fields": "预填充字段", + "documents": "文档", + "message": "消息", + "formula-help-p1": "收集数字输入并使用公式执行动态计算。", + "example": "示例", + "formula-help-p2": "要在 number-3 中显示总和,请使用 {{number-1}} + {{number-2}}。", + "formula-help-p3": "要在 number-4 中计算一个值,请使用 ({{number-1}} * {{number-2}}) / {{number-3}}。", + "formula-help-p4": "每个数字控件必须有唯一的名称(例如 number-1),因为公式依赖这些标识符。", + "note-consume-premium-credits": "注意:此功能会消耗高级额度。", + "note-consume-premium-credits-on-document-send": "注意:此功能会消耗高级额度。无论是否签署,只要文档被发送出去就会消耗额度。", + "webhook-authentication-help": "{{appName}} 通过使用你的 webhook 安全密钥和原始请求负载生成 HMAC-SHA256 签名来保护每个 webhook。此签名在 x-webhook-signature 标头中发送。你的服务器必须使用收到的负载和你的密钥生成相同的签名。如果两个签名匹配,则该 webhook 请求是真实的且未被修改。", + "invalid-widget-found-in-row": "在第 {{row}} 行的控件 {{widget}} 中检测到无效值。", + "all-signer-status": "所有签署人状态", + "viewed": "已查看", + "signed": "已签署", + "switch-to-advanced": "切换到高级", + "switch-to-basic": "切换到基础", + "use-name-as-sender": "使用个人资料名称作为发件人", + "use-name-as-sender-help": "启用后,{{appName}} 会使用你的个人资料名称作为签名请求邮件和完成邮件的发件人。", + "acro-fields-detected": "检测到表单字段", + "acro-fields-detected-msg": "我们在上传的 PDF 中检测到 {{count}} 个表单字段。你是否要自动插入相应的控件?", + "documents-count": "文档数量", + "templates-count": "模板数量", + "emails-sent": "已发送邮件", + "storage-used": "已用存储", + "docs-count-team-help": "你组织中所有用户创建的文档总数。", + "docs-count-help": "你创建的文档总数。", + "templates-count-team-help": "你组织中所有用户创建的模板总数。", + "templates-count-help": "你创建的模板总数。", + "emails-sent-team-help": "你组织中发送的邮件通知总数。", + "emails-sent-help": "你发送的邮件通知总数。", + "storage-used-team-help": "你组织中所有用户消耗的存储空间总量。", + "storage-used-help": "你消耗的存储空间总量。", + "cloud": "云端", + "on-premises": "本地部署", + "plan-name-free": "OPENSIGN™ 免费版", + "plan-name-professional": "OPENSIGN™ 专业版", + "plan-name-teams": "OPENSIGN™ 团队版", + "plan-name-enterprise": "OPENSIGN™ 企业版", + "plan-name-self-hosted": "OPENSIGN™ 自托管版", + "plan-subtitle-free": "永久免费的无限电子签名。", + "plan-subtitle-professional": "独享高级功能访问权限。", + "plan-subtitle-scalable": "可扩展功能与优先支持。", + "subscribe": "订阅", + "contact-us": "联系我们", + "benefit-unlimited-digital-signatures": "无限数字签名", + "benefit-sign-docs-yourself": "自行签署文档", + "benefit-request-signatures": "请求他人签署", + "benefit-unlimited-templates": "无限模板", + "benefit-14-field-types": "14 种字段类型", + "benefit-automatic-e-signatures": "自动电子签名", + "benefit-completion-certificates": "完成证书", + "benefit-send-in-order": "按顺序发送", + "benefit-organize-docs": "在 OpenSign™ 云盘中整理文档", + "benefit-document-templates": "文档模板", + "benefit-import-from-dropbox": "从 Dropbox 导入", + "benefit-contact-book": "联系人簿", + "benefit-document-expiry": "文档到期支持", + "benefit-decline-document": "拒签文档支持", + "benefit-email-notifications": "邮件通知", + "benefit-public-profiles": "公开主页", + "benefit-and-much-more": "以及更多", + "benefit-everything-free": "包含 OpenSign™ 免费版的所有功能", + "benefit-field-validations": "字段校验", + "benefit-regex-validations": "正则表达式校验", + "benefit-webhooks": "Webhooks", + "benefit-zapier": "Zapier 集成", + "benefit-api-access": "API 访问", + "benefit-api-signatures-100": "最多 100 次 API 签名", + "benefit-api-signatures-240": "最多 240 次 API 签名", + "benefit-custom-email-templates": "自定义邮件模板", + "benefit-custom-smtp": "连接你自己的 Gmail 或 SMTP 账户以发送邮件", + "benefit-auto-reminders": "自动提醒", + "benefit-bulk-send-100": "批量发送(最多 100 份文档)", + "benefit-bulk-send-240": "批量发送(最多 240 份文档)", + "benefit-premium-profiles": "高级公开主页用户名", + "benefit-email-verification": "强制基于邮件的验证以确认签署人身份", + "benefit-embedded-signing": "嵌入式签署", + "benefit-everything-professional": "包含 OpenSign™ 专业版的所有功能", + "benefit-teams-organizations": "团队与组织", + "benefit-share-templates-teams": "与团队共享模板", + "benefit-share-templates-individuals": "与个人共享模板", + "benefit-byoc": "BYOC - 将你的文档存储在你自己的云存储中", + "benefit-doc-id-removal": "从已签署文档中移除 DocumentId", + "benefit-request-payments": "请求付款(即将推出)", + "benefit-mobile-app": "移动应用(即将推出)", + "benefit-api-signatures-500": "最多 500 次 API 签名", + "benefit-bulk-send-500": "批量发送(最多 500 份文档)", + "benefit-all-features": "所有功能", + "benefit-custom-domain": "自定义域名", + "benefit-custom-branding": "自定义品牌", + "benefit-uptime-sla": "正常运行时间 SLA", + "benefit-sso-support": "SSO 支持", + "benefit-priority-support": "优先支持", + "benefit-3-users-1500-credits": "包含 3 个用户和 1500 个高级额度", + "benefit-public-links": "公开链接", + "benefit-kiosk-mode": "自助终端模式", + "benefit-bulk-send-1500": "批量发送(最多 1500 份文档)", + "benefit-connect-gmail-smtp": "连接你自己的 Gmail 或 SMTP", + "benefit-analytics": "分析", + "benefit-bulksend-api-pro-month-help": "此套餐每月附带 100 个高级额度,可让你通过 API 发送文档、分享公开签署链接、运行批量签名请求、使用自助终端模式进行现场签署,或从直接嵌入你网站的文档中收集签名。每次你发起或发送一份文档,都会使用一个额度——而这一份文档最多可包含 10 位签署人。", + "benefit-bulksend-api-pro-year-help": "此套餐每年附带 240 个高级额度,可让你通过 API 发送文档、分享公开签署链接、运行批量签名请求、使用自助终端模式进行现场签署,或从直接嵌入你网站的文档中收集签名。每次你发起或发送一份文档,都会使用一个额度——而这一份文档最多可包含 10 位签署人。", + "benefit-bulksend-api-team-month-help": "此套餐每月附带 100 个高级额度,可让你通过 API 发送文档、分享公开签署链接、运行批量签名请求、使用自助终端模式进行现场签署,或从直接嵌入你网站的文档中收集签名。每次你发起或发送一份文档,都会使用一个额度——而这一份文档最多可包含 10 位签署人。", + "benefit-bulksend-api-team-year-help": "此套餐每年附带 500 个高级额度,可让你通过 API 发送文档、分享公开签署链接、运行批量签名请求、使用自助终端模式进行现场签署,或从直接嵌入你网站的文档中收集签名。每次你发起或发送一份文档,都会使用一个额度——而这一份文档最多可包含 10 位签署人。", + "failed-pdf-for-prefill-processing": "加载 PDF 进行预填充处理失败。", + "attach-all-role-to-signer": "请将所有角色附加到签署人。", + "upgrade-to-edit": "升级以编辑", + "attachments-creator-hint": "签署人可以上传文件,这些文件将附加到文档末尾。", + "attachments-drop-hint": "将文件拖放到此处或点击选择", + "attachments-limits": "PDF、DOCX、PNG、JPG。最多 {{maxFiles}} 个文件,每个 {{maxSizeMB}} MB。", + "attachments-invalid-type": "不支持的文件类型:{{name}}", + "attachments-max-files": "最多允许 {{maxFiles}} 个附件。", + "attachments-remove-confirm": "移除只会删除元数据。已附加的页面仍会保留在文档中。是否继续?", + "conditional-logic": "条件逻辑", + "enabled": "已启用", + "disabled": "已禁用", + "logic-no-sources": "此签署人没有其他字段可用作来源。", + "logic-action": "操作", + "logic-when": "当", + "logic-all": "全部", + "logic-any": "任一", + "logic-of-following": "以下条件为真时", + "logic-add-rule": "添加规则", + "logic-pick-value": "选择一个值", + "logic-value-placeholder": "输入值", + "logic-action-show": "显示此字段", + "logic-action-hide": "隐藏此字段", + "logic-action-require": "设为必填", + "logic-action-optional": "设为可选", + "logic-op-equals": "等于", + "logic-op-notEquals": "不等于", + "logic-op-checked": "已勾选", + "logic-op-unchecked": "未勾选", + "widget-hidden-due-to-logic": "此控件因条件逻辑而被隐藏。", + "remove": "移除", + "attachement-note": "注意:此控件允许签署人在签署过程中上传文件。上传的文件将作为额外页面附加到现有 PDF 的末尾", + "attachments-docx-not-supported": "我们目前在 DOCX 文件上传方面遇到问题。请尝试以其他受支持的格式上传文档,或稍后重试。", + "access-code": "访问码", + "access-code-set": "访问码已设置", + "access-code-add": "添加访问码", + "access-code-help": "仅此签署人知道的可选密钥。他们在查看或签署文档前将被要求输入它。请通过带外方式(电话、当面)与收件人分享。", + "access-code-placeholder": "至少 6 位数字", + "access-code-clear": "清除", + "access-code-save": "保存", + "access-code-required": "发送方为此收件人设置了访问码。请输入以继续。", + "access-code-invalid": "访问码不正确。请与发送方核对。", + "access-code-too-short": "访问码必须至少 6 位数字。", + "access-code-must-be-numeric": "访问码必须仅包含数字 0-9。", + "access-code-verify": "验证访问码", + "access-code-verified": "访问码已验证。", + "access-code-warning": "文档一旦发出,此访问码将无法更改或找回。", + "copy-access-code": "复制访问码", + "access-code-upgrade-msg": "访问码仅在付费套餐中可用。升级你的套餐以为收件人添加访问码。", + "already-copied-to-clipboard": "已复制到剪贴板" +} \ No newline at end of file diff --git a/apps/OpenSign/public/manifest.json b/apps/OpenSign/public/manifest.json deleted file mode 100644 index f07b8c53c0..0000000000 --- a/apps/OpenSign/public/manifest.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "short_name": "Open sign", - "name": "Open sign", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - }, - { - "src": "logo192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "logo512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff" -} diff --git a/apps/OpenSign/server.cjs b/apps/OpenSign/server.cjs index bb6a129495..6fa7fdb733 100644 --- a/apps/OpenSign/server.cjs +++ b/apps/OpenSign/server.cjs @@ -140,6 +140,12 @@ const server = http.createServer((req, res) => { fs.stat(filePath, (err, stats) => { if (err) { + // A missing asset (path with an extension) must not be masked by the + // SPA fallback: answer 404 so broken references stay visible. + if (path.extname(filePath)) { + res.writeHead(404, { "Content-Type": "text/plain" }); + return res.end("Not Found"); + } // No file at this path → SPA fallback to index.html return sendIndex(req, res); } diff --git a/apps/OpenSign/src/App.jsx b/apps/OpenSign/src/App.jsx index e88acd6f33..2e8bfa156c 100644 --- a/apps/OpenSign/src/App.jsx +++ b/apps/OpenSign/src/App.jsx @@ -1,19 +1,12 @@ import { useState, useEffect } from "react"; -import { lazyWithRetry, hideUpgradeProgress } from "./utils"; +import { lazyWithRetry } from "./utils/lazyWithRetry"; +import { hideUpgradeProgress } from "./utils/upgradeProgress"; import { Routes, Route, BrowserRouter, Navigate } from "react-router"; -import { pdfjs } from "react-pdf"; -import Form from "./pages/Form"; -import Report from "./pages/Report"; -import Dashboard from "./pages/Dashboard"; +import { getEnv } from "./constant/utils/coreConstants.js"; import HomeLayout from "./layout/HomeLayout"; import PageNotFound from "./pages/PageNotFound"; import ValidateRoute from "./primitives/ValidateRoute"; import Validate from "./primitives/Validate"; -import TemplatePlaceholder from "./pages/TemplatePlaceholder"; -import SignYourSelf from "./pages/SignyourselfPdf"; -import DraftDocument from "./components/pdf/DraftDocument"; -import PlaceHolderSign from "./pages/PlaceHolderSign"; -import PdfRequestFiles from "./pages/PdfRequestFiles"; import Lazy from "./primitives/LazyPage"; import Loader from "./primitives/Loader"; import UserList from "./pages/UserList"; @@ -41,8 +34,20 @@ const Preferences = lazyWithRetry(() => import("./pages/Preferences")); const Login = lazyWithRetry(() => import("./pages/Login")); const VerifyDocument = lazyWithRetry(() => import("./pages/VerifyDocument")); const EmailBuilder = lazyWithRetry(() => import("./pages/EmailBuilder")); - -pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`; +// The PDF editor pages stay out of the login chunk: react-pdf, pdf-lib and +// react-datepicker only load when one of these routes renders (#55). +const Form = lazyWithRetry(() => import("./pages/Form")); +const Report = lazyWithRetry(() => import("./pages/Report")); +const Dashboard = lazyWithRetry(() => import("./pages/Dashboard")); +const TemplatePlaceholder = lazyWithRetry( + () => import("./pages/TemplatePlaceholder") +); +const SignYourSelf = lazyWithRetry(() => import("./pages/SignyourselfPdf")); +const DraftDocument = lazyWithRetry( + () => import("./components/pdf/DraftDocument") +); +const PlaceHolderSign = lazyWithRetry(() => import("./pages/PlaceHolderSign")); +const PdfRequestFiles = lazyWithRetry(() => import("./pages/PdfRequestFiles")); const AppLoader = () => { return (
@@ -67,7 +72,21 @@ function App() { {isloading ? ( ) : ( - + { + try { + // import.meta.env.BASE_URL always reflects the Vite base, so a + // build-time PUBLIC_URL reaches the router too. + const raw = + getEnv()?.PUBLIC_URL || + process.env.PUBLIC_URL || + import.meta.env.BASE_URL; + if (raw) { + const u = new URL(raw, window.location.origin); + return u.pathname.replace(/\/$/, "") || "/"; + } + } catch (e) { /* ignore */ } + return "/"; + })()}> <Routes> <Route element={<ValidateRoute />}> @@ -95,7 +114,7 @@ function App() { <Route exact path="/load/recipientSignPdf/:docId/:contactBookId" - element={<DragProvider Page={PdfRequestFiles} />} + element={<DragProvider Page={PdfRequestFiles} lazy />} /> </Route> <Route @@ -119,39 +138,39 @@ function App() { path="/changepassword" element={<Lazy Page={ChangePassword} />} /> - <Route path="/form/:id" element={<Form />} /> - <Route path="/report/:id" element={<Report />} /> - <Route path="/dashboard/:id" element={<Dashboard />} /> + <Route path="/form/:id" element={<Lazy Page={Form} />} /> + <Route path="/report/:id" element={<Lazy Page={Report} />} /> + <Route path="/dashboard/:id" element={<Lazy Page={Dashboard} />} /> <Route path="/profile" element={<Lazy Page={UserProfile} />} /> <Route path="/drive" element={<Lazy Page={Opensigndrive} />} /> <Route path="/managesign" element={<Lazy Page={ManageSign} />} /> <Route path="/template/:templateId" - element={<DragProvider Page={TemplatePlaceholder} />} + element={<DragProvider Page={TemplatePlaceholder} lazy />} /> {/* signyouself route with no rowlevel data using docId from url */} <Route path="/signaturePdf/:docId" - element={<DragProvider Page={SignYourSelf} />} + element={<DragProvider Page={SignYourSelf} lazy />} /> {/* draft document route to handle and navigate route page according to document status */} <Route path="/draftDocument" - element={<DragProvider Page={DraftDocument} />} + element={<DragProvider Page={DraftDocument} lazy />} /> {/* recipient placeholder set route with no rowlevel data using docId from url*/} <Route path="/placeHolderSign/:docId" - element={<DragProvider Page={PlaceHolderSign} />} + element={<DragProvider Page={PlaceHolderSign} lazy />} /> {/* recipient signature route with no rowlevel data using docId from url */} <Route path="/recipientSignPdf/:docId/:contactBookId" - element={<DragProvider Page={PdfRequestFiles} />} + element={<DragProvider Page={PdfRequestFiles} lazy />} /> <Route path="/recipientSignPdf/:docId" - element={<DragProvider Page={PdfRequestFiles} />} + element={<DragProvider Page={PdfRequestFiles} lazy />} /> <Route path="/verify-document" @@ -163,7 +182,7 @@ function App() { /> </Route> <Route path="/success" element={<DocSuccessPage />} /> - <Route path="/emailbuilder" element={<EmailBuilder />} /> + <Route path="/emailbuilder" element={<Lazy Page={EmailBuilder} />} /> <Route path="*" element={<PageNotFound />} /> </Routes> </BrowserRouter> diff --git a/apps/OpenSign/src/components/AddUser.jsx b/apps/OpenSign/src/components/AddUser.jsx index 1405c454a8..f6e7184304 100644 --- a/apps/OpenSign/src/components/AddUser.jsx +++ b/apps/OpenSign/src/components/AddUser.jsx @@ -1,17 +1,15 @@ import { useEffect, useState } from "react"; import Parse from "parse"; import Loader from "../primitives/Loader"; -import { - copytoData, - usertimezone -} from "../constant/Utils"; +import { copytoData } from "../constant/utils/tenantDownloads.js"; +import { usertimezone } from "../constant/utils/coreConstants.js"; import { emailRegex, } from "../constant/const"; import { useTranslation } from "react-i18next"; -import { withSessionValidation } from "../utils"; +import { withSessionValidation } from "../utils/withSessionValidation"; function generatePassword(length) { const characters = diff --git a/apps/OpenSign/src/components/DatePicker.jsx b/apps/OpenSign/src/components/DatePicker.jsx index 0c510e2822..05ee450226 100644 --- a/apps/OpenSign/src/components/DatePicker.jsx +++ b/apps/OpenSign/src/components/DatePicker.jsx @@ -78,7 +78,7 @@ const DatePicker = ({ dateFormat={ selectDate ? selectDate?.format : format ? format : "MM/dd/yyyy" } - portalId="root-portal" + /> {showClear && handleClear && ( <span diff --git a/apps/OpenSign/src/components/Header.jsx b/apps/OpenSign/src/components/Header.jsx index 7ced12081c..93227b2ee7 100644 --- a/apps/OpenSign/src/components/Header.jsx +++ b/apps/OpenSign/src/components/Header.jsx @@ -5,11 +5,11 @@ import ThemeToggle from "./ThemeToggle"; import { useNavigate } from "react-router"; import Parse from "parse"; import { useWindowSize } from "../hook/useWindowSize"; +import { getAppLogo } from "../constant/utils/tenantDownloads.js"; import { - getAppLogo, openInNewTab, saveLanguageInLocal -} from "../constant/Utils"; +} from "../constant/utils/coreConstants.js"; import { useTranslation } from "react-i18next"; import { appInfo } from "../constant/appinfo"; import { useDispatch, useSelector } from "react-redux"; diff --git a/apps/OpenSign/src/components/RenderDebugPdf.jsx b/apps/OpenSign/src/components/RenderDebugPdf.jsx index f9915ea07b..a3bc736161 100644 --- a/apps/OpenSign/src/components/RenderDebugPdf.jsx +++ b/apps/OpenSign/src/components/RenderDebugPdf.jsx @@ -1,5 +1,8 @@ import React from "react"; -import { Document, Page } from "react-pdf"; +import { Document, Page, pdfjs } from "react-pdf"; + +// The worker URL lives with the PDF chunk, not the login bundle (#55). +pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`; import { Stage, Layer, Rect, Text } from "react-konva"; import { useTranslation } from "react-i18next"; const RenderDebugPdf = (props) => { diff --git a/apps/OpenSign/src/components/ThemeToggle.jsx b/apps/OpenSign/src/components/ThemeToggle.jsx index c1d81d678a..58f64a09f7 100644 --- a/apps/OpenSign/src/components/ThemeToggle.jsx +++ b/apps/OpenSign/src/components/ThemeToggle.jsx @@ -1,4 +1,6 @@ import { useEffect, useState } from "react"; +import Parse from "parse"; +import { applyTheme } from "../utils/theme"; const ThemeToggle = () => { const [isDark, setIsDark] = useState(false); @@ -13,15 +15,18 @@ const ThemeToggle = () => { } }, []); - const handleChange = () => { + const handleChange = async () => { const newTheme = !isDark; + const theme = newTheme ? "dark" : "light"; setIsDark(newTheme); - if (newTheme) { - document.documentElement.setAttribute("data-theme", "opensigndark"); - localStorage.setItem("theme", "dark"); - } else { - document.documentElement.setAttribute("data-theme", "opensigncss"); - localStorage.setItem("theme", "light"); + applyTheme(theme); + if (Parse.User.current()) { + try { + await Parse.Cloud.run("updatepreferences", { Theme: theme }); + } catch (err) { + // The theme still applies on this device; it can be saved on the next change. + console.error("Error saving theme preference: ", err); + } } }; diff --git a/apps/OpenSign/src/components/ThemeToggle.test.jsx b/apps/OpenSign/src/components/ThemeToggle.test.jsx new file mode 100644 index 0000000000..c222b5bdf7 --- /dev/null +++ b/apps/OpenSign/src/components/ThemeToggle.test.jsx @@ -0,0 +1,70 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import Parse from "parse"; +import ThemeToggle from "./ThemeToggle"; + +vi.mock("parse", () => ({ + default: { User: { current: vi.fn() }, Cloud: { run: vi.fn() } } +})); + +const shownTheme = () => document.documentElement.getAttribute("data-theme"); + +describe("ThemeToggle", () => { + beforeEach(() => { + localStorage.clear(); + vi.mocked(Parse.User.current).mockReturnValue({ id: "user" }); + vi.mocked(Parse.Cloud.run).mockReset().mockResolvedValue({}); + }); + + afterEach(cleanup); + + it("saves the chosen theme on the profile of a signed in user", async () => { + const { container } = render(<ThemeToggle />); + const toggle = container.querySelector("input"); + + fireEvent.click(toggle); + + expect(shownTheme()).toBe("opensigndark"); + expect(localStorage.getItem("theme")).toBe("dark"); + await waitFor(() => + expect(Parse.Cloud.run).toHaveBeenCalledWith("updatepreferences", { + Theme: "dark" + }) + ); + + fireEvent.click(toggle); + + expect(shownTheme()).toBe("opensigncss"); + await waitFor(() => + expect(Parse.Cloud.run).toHaveBeenLastCalledWith("updatepreferences", { + Theme: "light" + }) + ); + }); + + it("does not call the server when nobody is signed in", () => { + vi.mocked(Parse.User.current).mockReturnValue(null); + const { container } = render(<ThemeToggle />); + + fireEvent.click(container.querySelector("input")); + + expect(shownTheme()).toBe("opensigndark"); + expect(Parse.Cloud.run).not.toHaveBeenCalled(); + }); + + it("keeps the theme on this device when saving fails", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.mocked(Parse.Cloud.run).mockRejectedValue(new Error("offline")); + const { container } = render(<ThemeToggle />); + const toggle = container.querySelector("input"); + + fireEvent.click(toggle); + + await waitFor(() => expect(error).toHaveBeenCalled()); + expect(toggle.checked).toBe(true); + expect(shownTheme()).toBe("opensigndark"); + expect(localStorage.getItem("theme")).toBe("dark"); + error.mockRestore(); + }); +}); diff --git a/apps/OpenSign/src/components/bulksend/components/RenderWidgets.jsx b/apps/OpenSign/src/components/bulksend/components/RenderWidgets.jsx index b3e9e48f18..995f37605e 100644 --- a/apps/OpenSign/src/components/bulksend/components/RenderWidgets.jsx +++ b/apps/OpenSign/src/components/bulksend/components/RenderWidgets.jsx @@ -1,3 +1,4 @@ +import { UI_FONT } from "../../../constant/fonts"; import { forwardRef, memo, useEffect, useMemo, useRef, useState } from "react"; import DatePicker from "react-datepicker"; import SignatureCanvas from "react-signature-canvas"; @@ -42,7 +43,7 @@ const DateWidget = ({ widget, isRequired, onChange, showLabel }) => { const PrefillDateInput = forwardRef(({ value, onClick }, ref) => ( <div - style={{ fontFamily: "Arial, sans-serif" }} + style={{ fontFamily: UI_FONT }} className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full" onClick={onClick} ref={ref} diff --git a/apps/OpenSign/src/components/pdf/CellsWidget.jsx b/apps/OpenSign/src/components/pdf/CellsWidget.jsx index 8a94dd687d..8af91c3544 100644 --- a/apps/OpenSign/src/components/pdf/CellsWidget.jsx +++ b/apps/OpenSign/src/components/pdf/CellsWidget.jsx @@ -1,3 +1,4 @@ +import { UI_FONT } from "../../constant/fonts"; import { useState, useEffect, useRef } from "react"; const Cell = ({ @@ -31,7 +32,7 @@ const Cell = ({ onBlur={editable ? (e) => onBlur && onBlur(e, index) : undefined} className={`${isEnabled ? "placeholder-gray-300" : "placeholder-gray-500"} w-full text-center focus:outline-none bg-transparent`} placeholder={hint} - style={{ fontFamily: "Arial, sans-serif", fontSize, color: fontColor }} + style={{ fontFamily: UI_FONT, fontSize, color: fontColor }} /> </div> ); diff --git a/apps/OpenSign/src/components/pdf/DropdownWidgetOption.jsx b/apps/OpenSign/src/components/pdf/DropdownWidgetOption.jsx index 07a8f070a8..14887e1350 100644 --- a/apps/OpenSign/src/components/pdf/DropdownWidgetOption.jsx +++ b/apps/OpenSign/src/components/pdf/DropdownWidgetOption.jsx @@ -16,6 +16,7 @@ function DropdownWidgetOption(props) { const [dropdownName, setDropdownName] = useState(); const [isReadOnly, setIsReadOnly] = useState(false); const [isHideLabel, setIsHideLabel] = useState(false); + const [isMultiSelect, setIsMultiSelect] = useState(false); const [status, setStatus] = useState("required"); const [defaultValue, setDefaultValue] = useState(""); const [defaultCheckbox, setDefaultCheckbox] = useState([]); @@ -35,6 +36,7 @@ function DropdownWidgetOption(props) { setDefaultCheckbox([]); setDefaultValue(""); setLayout("vertical"); + setIsMultiSelect(false); }; useEffect(() => { if ( @@ -55,6 +57,7 @@ function DropdownWidgetOption(props) { setDefaultValue(props.currWidgetsDetails?.options?.defaultValue || ""); setDefaultCheckbox(props.currWidgetsDetails?.options?.defaultValue || []); setLayout(props.currWidgetsDetails?.options?.layout || "vertical"); + setIsMultiSelect(!!props.currWidgetsDetails?.options?.isMultiSelect); } else { setStatus("required"); resetState(); @@ -154,6 +157,7 @@ function DropdownWidgetOption(props) { defaultData, isHideLabel, WidgetLayout, + isMultiSelect, ); resetState(); }; @@ -379,6 +383,23 @@ function DropdownWidgetOption(props) { )} </div> )} + {props.type === "dropdown" && ( + <div className="flex flex-row gap-[5px] items-center mt-[0.5rem] mb-[10px]"> + <input + id="dropdown-multiselect" + className="op-checkbox op-checkbox-xs rounded-[1px]" + type="checkbox" + checked={isMultiSelect} + onChange={(e) => setIsMultiSelect(e.target.checked)} + /> + <label + className="text-[13px] font-500 mb-0 cursor-pointer" + htmlFor="dropdown-multiselect" + > + {t("allow-multiple-selection")} + </label> + </div> + )} {["checkbox", radioButtonWidget].includes(props.type) && ( <> <div className="text-[13px] font-semibold mt-[5px] capitalize"> diff --git a/apps/OpenSign/src/components/pdf/EditTemplate.jsx b/apps/OpenSign/src/components/pdf/EditTemplate.jsx index bb1851e1d8..9b529ff967 100644 --- a/apps/OpenSign/src/components/pdf/EditTemplate.jsx +++ b/apps/OpenSign/src/components/pdf/EditTemplate.jsx @@ -13,6 +13,7 @@ import { maxNoteLength, maxTitleLength } from "../../constant/const"; +import { DEFAULT_COMPLETION_DAYS } from "../../constant/runtimeConfig"; import { useTranslation } from "react-i18next"; import { Tooltip } from "react-tooltip"; import SignersInput from "../shared/fields/SignersInput"; @@ -54,7 +55,7 @@ const EditTemplate = ({ Cc: template?.Cc, RedirectUrl: template?.RedirectUrl || "", AllowModifications: template?.AllowModifications || false, - TimeToCompleteDays: template?.TimeToCompleteDays || 15, + TimeToCompleteDays: template?.TimeToCompleteDays || DEFAULT_COMPLETION_DAYS, }); const pensList = ["blue", "red", "black"]; const [selectedColors, setSelectedColors] = useState( @@ -101,7 +102,7 @@ const EditTemplate = ({ setFormData({ ...formData, [e.target.name]: e.target.value }); }; const getPdfMetadataHash = async (pdfBytes) => { - const pdfDoc = await PDFDocument.load(pdfBytes); + const pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true }); const pages = pdfDoc.getPages(); const metaString = pages .map((page, index) => { diff --git a/apps/OpenSign/src/components/pdf/PdfTools.jsx b/apps/OpenSign/src/components/pdf/PdfTools.jsx index fb71724a77..b061cf37ac 100644 --- a/apps/OpenSign/src/components/pdf/PdfTools.jsx +++ b/apps/OpenSign/src/components/pdf/PdfTools.jsx @@ -125,7 +125,7 @@ function PdfTools(props) { const uploadedPdfDoc = await PDFDocument.load(uploadedPdfBytes, { ignoreEncryption: true }); - const basePdfDoc = await PDFDocument.load(props.pdfArrayBuffer); + const basePdfDoc = await PDFDocument.load(props.pdfArrayBuffer, { ignoreEncryption: true }); // Copy pages from the uploaded PDF to the base PDF const uploadedPdfPages = await basePdfDoc.copyPages( diff --git a/apps/OpenSign/src/components/pdf/Placeholder.jsx b/apps/OpenSign/src/components/pdf/Placeholder.jsx index 2f5a5dd929..60223963f0 100644 --- a/apps/OpenSign/src/components/pdf/Placeholder.jsx +++ b/apps/OpenSign/src/components/pdf/Placeholder.jsx @@ -259,7 +259,26 @@ function Placeholder(props) { props.setXyPosition(updatesignerPos); } props?.closeWidgetTour?.(); - dispatch(setIsShowModal({ [props.pos.key]: true })); + // Inline editing: text widgets are edited in-field; only open the + // modal for non-text widgets (signature, image, stamp, etc.). + // Types edited in place. Signature, stamp, initials and image stay + // on the modal because they need a drawing pad or a file picker. + const inlineTypes = [ + "text", + textInputWidget, + "name", + "company", + "job title", + "email", + "checkbox", + radioButtonWidget, + "dropdown", + "date", + cellsWidget + ]; + if (!inlineTypes.includes(props.pos.type)) { + dispatch(setIsShowModal({ [props.pos.key]: true })); + } } } //placeholder, template flow @@ -279,7 +298,22 @@ function Placeholder(props) { } else if (props?.data?.Role === "prefill") { props?.handleClosePrefillTour?.(); props?.closeWidgetTour?.(); - dispatch(setIsShowModal({ [props.pos.key]: true })); + const inlineTypes = [ + "text", + textInputWidget, + "name", + "company", + "job title", + "email", + "checkbox", + radioButtonWidget, + "dropdown", + "date", + cellsWidget + ]; + if (!inlineTypes.includes(props.pos.type)) { + dispatch(setIsShowModal({ [props.pos.key]: true })); + } props.setUniqueId(props?.data?.Id); props?.setRoleName("prefill"); } @@ -552,6 +586,67 @@ function Placeholder(props) { className="fa-light fa-gear icon text-[#188ae2] text-[14px] z-[99] -top-[18px] pointer-events-auto" ></i> )} + {props.isPlaceholder && + ["text", textInputWidget, "name", "company", "job title", "email"].includes( + props.pos.type + ) && ( + <i + className={`fa-light ${props.pos?.options?.isMasked ? "fa-eye-slash" : "fa-eye"} icon text-[#188ae2] right-[34px] -top-[18px]`} + title={props.pos?.options?.isMasked ? "Unmask field" : "Mask field"} + onClick={(e) => { + e.stopPropagation(); + const isMasked = !props.pos?.options?.isMasked; + props.setXyPosition((prev) => { + const isSignerList = prev.some( + (item) => item.signerPtr || item.Role === "prefill" + ); + if (isSignerList) { + const signerId = props.data?.Id || props.uniqueId; + return prev.map((item) => { + if (item.Id !== signerId) return item; + const placeHolder = (item.placeHolder || []).map((page) => + page.pageNumber !== props.widgetPageNum + ? page + : { + ...page, + pos: page.pos.map((widget) => + widget.key === props.pos.key + ? { + ...widget, + options: { ...widget.options, isMasked } + } + : widget + ) + } + ); + return { ...item, placeHolder }; + }); + } + return prev.map((item, index) => + index === props.index + ? { + ...item, + pos: item.pos.map((widget) => + widget.key === props.pos.key + ? { + ...widget, + options: { ...widget.options, isMasked } + } + : widget + ) + } + : item + ); + }); + props.setCurrWidgetsDetails?.({ + ...props.pos, + options: { ...props.pos.options, isMasked }, + pageNumber: props.widgetPageNum + }); + }} + onTouchEnd={(e) => e.stopPropagation()} + /> + )} {/* copy icon for all widgets (except QES) */} <i className="fa-light fa-copy icon text-[#188ae2] right-[12px] -top-[18px] " @@ -792,6 +887,7 @@ function Placeholder(props) { ...(props.pos?.Width ? { width: props.pos?.Width - 5 } : {}), ...(props.pos?.Height ? { height: props.pos?.Height } : {}), fontSize: fontSize, + lineHeight: 1.25, color: fontColor, zIndex: 99, cursor: getCursor(), @@ -802,7 +898,8 @@ function Placeholder(props) { whiteSpace: "pre-wrap", overflow: "visible", outline: props.isAreaSelected ? "2px solid #6b7280" : "none", - border: "none" + border: "none", + WebkitTextSecurity: props.pos?.options?.isMasked ? "disc" : "none" }} > { @@ -854,6 +951,7 @@ function Placeholder(props) { topLeft: false }} bounds="parent" + cancel="input, select, textarea, button, label, option" className="signYourselfBlock" style={{ border: "1.5px solid #007bff", @@ -1011,6 +1109,17 @@ function Placeholder(props) { )} <div className="flex items-stretch justify-center" + data-dbg={JSON.stringify({ + t: props.pos?.type, + wSigner: props.data?.signerObjId || null, + sSigner: props.signerObjId || null, + needSign: !!props.isNeedSign, + selfSign: !!props.isSelfSign, + signYourself: !!props.isSignYourself, + placeholder: !!props.isPlaceholder, + ro: !!props.pos?.options?.isReadOnly, + role: props.data?.Role || null + })} style={{ left: xPos(props.pos), top: yPos(props.pos), diff --git a/apps/OpenSign/src/components/pdf/PlaceholderType.jsx b/apps/OpenSign/src/components/pdf/PlaceholderType.jsx index 40ca669911..4822b89e14 100644 --- a/apps/OpenSign/src/components/pdf/PlaceholderType.jsx +++ b/apps/OpenSign/src/components/pdf/PlaceholderType.jsx @@ -1,28 +1,25 @@ -import { - useEffect, - useState, - forwardRef, - useRef -} from "react"; +import { useEffect, useState, useRef } from "react"; import { onChangeInput, defaultWidthHeight, - radioButtonWidget, + isRadioSelected, textInputWidget, - cellsWidget, - textWidget, - selectCheckbox, isBase64, - drawWidget, changeDateToMomentFormat } from "../../constant/Utils"; import "react-datepicker/dist/react-datepicker.css"; import "../../styles/signature.css"; import { useTranslation } from "react-i18next"; -import CellsWidget from "./CellsWidget"; import { useSelector } from "react-redux"; -import Loader from "../../primitives/Loader"; import moment from "moment"; +import { updateLinkedFields } from "../../utils/linkedFields"; +import { renderSignature } from "./PlaceholderTypeSignature"; +import { renderField } from "./PlaceholderTypeFields"; +import { renderText } from "./PlaceholderTypeText"; +import { renderFallback } from "./PlaceholderTypeSignature"; +import { renderRadio } from "./PlaceholderTypeRadio"; +import { renderCheckbox } from "./PlaceholderTypeCheckbox"; +import { renderDate } from "./PlaceholderTypeDate"; const textWidgetCls = "w-full h-full md:min-w-full md:min-h-full z-[999] text-[12px] overflow-hidden resize-none outline-none text-base-content item-center whitespace-pre-wrap"; @@ -45,6 +42,18 @@ function PlaceholderType(props) { props?.data?.Role !== "prefill" && (props.pos.options?.isReadOnly || props.data?.signerObjId !== props.signerObjId); + // In-field editing: the signer edits their own widgets, and the authoring + // flows edit placeholders directly on the page. + const isOwnWidget = + props.data?.signerObjId && + props.data?.signerObjId === props.signerObjId && + !props.pos?.options?.isReadOnly; + const canEditInline = + (props.isPlaceholder && !props.isNeedSign) || + ((props.isNeedSign || props.isSelfSign || props.isSignYourself) && + iswidgetEnable && + !isReadOnly) || + !!isOwnWidget; // prefer the latest response value over any default value //props?.isPrefillModal is used to handle in create template flow when user use use-template button //then prefill details should not be reflect on pdf document it should only show in modal @@ -52,6 +61,7 @@ function PlaceholderType(props) { ? (props.pos?.options?.response ?? props.pos?.options?.defaultValue ?? "") : ""; const [widgetValue, setwidgetValue] = useState(); + const [inlineError, setInlineError] = useState(false); const [selectedCheckbox, setSelectedCheckbox] = useState([]); const [imgUrl, setImgUrl] = useState(""); const [date, setDate] = useState(""); @@ -72,8 +82,7 @@ function PlaceholderType(props) { if (type !== "date") { if (type && type === "checkbox") { setSelectedCheckbox(response || defaultData || []); - } - else { + } else { // keep displayed value in sync with the stored response setwidgetValue(widgetData); } @@ -82,43 +91,79 @@ function PlaceholderType(props) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [props.pos, widgetData, type]); - - const ExampleCustomInput = forwardRef(({ value, onClick }, ref) => ( - <div - style={{ - fontSize: fontSize, - color: fontColor, - fontFamily: "Arial, sans-serif" - }} - className={`${isReadOnly ? `select-none opacity-25` : ``} ${selectWidgetCls} overflow-hidden`} - onClick={onClick} - ref={ref} - > - {value} - <i className="fa-light fa-calendar ml-[5px]"></i> - </div> - )); - ExampleCustomInput.displayName = "ExampleCustomInput"; - - // Extract string label from a radio/checkbox value entry which may be - // either a plain string or an object like { name: string, checked: boolean } - const getRadioLabel = (data) => { - if (typeof data === "string") return data; - if (data && typeof data === "object" && data.name != null) - return String(data.name); - return ""; + const persistInlineValue = ( + value, + position, + positions, + index, + setter, + userId, + ...rest + ) => { + const update = (change) => + setter((previous) => { + const next = typeof change === "function" ? change(previous) : change; + return updateLinkedFields(next, { + key: position.key, + name: position.options?.name, + value, + signerId: userId + }); + }); + onChangeInput(value, position, positions, index, update, userId, ...rest); }; - const handleRadioCheck = (data) => { - if (!props?.isPrefillModal) { - const defaultData = widgetValue - ? widgetValue?.trim() - : props.pos?.options?.defaultValue - ? props.pos?.options?.defaultValue?.trim() - : ""; - return defaultData === data?.trim(); + useEffect(() => { + if (!canEditInline) { + setInlineError(false); + return; + } + const validation = props.pos?.options?.validation; + const pattern = validation?.pattern; + const validationType = validation?.type; + if (!widgetValue) { + setInlineError(false); + return; + } + let regex = null; + if (validationType === "email") regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + else if (validationType === "number") regex = /^[0-9\s]*$/; + else if (validationType === "ssn") regex = /^\d{3}-?\d{2}-?\d{4}$/; + else if (pattern) { + try { + const literal = String(pattern).match(/^\/(.*)\/([a-z]*)$/); + regex = literal + ? new RegExp(literal[1], literal[2]) + : new RegExp(pattern); + } catch { + regex = null; + } + } + setInlineError(regex ? !regex.test(String(widgetValue)) : false); + }, [widgetValue, canEditInline, props.pos?.options?.validation]); + + const handleInlineTextChange = (event) => { + if (!canEditInline) return; + const value = event.target.value; + setwidgetValue(value); + if (props.setXyPosition) { + persistInlineValue( + value, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); } }; + //function is used to get prefill image's signedUrl after expired useEffect(() => { const loadImage = async () => { @@ -150,15 +195,18 @@ function PlaceholderType(props) { props?.pos?.type === name[0] ? `${name[0]}${lastWord}` : widgetName; return defaultData || props?.pos?.options?.hint || title; }; - // Convert rendered line heights back to PDF units before growing the widget. + // Inline text stays fixed-height until a newline needs additional space. useEffect(() => { + if (canEditInline && !(widgetValue && String(widgetValue).includes("\n"))) { + return; + } if (!textRef.current) return; if ( (type === "text" || type === textInputWidget) && textRef.current && - widgetData + (widgetValue ?? widgetData) ) { - const lines = widgetData.split("\n").length; + const lines = String(widgetValue ?? widgetData).split("\n").length; const containerScale = parseFloat(props.calculateFont(1)); const style = window.getComputedStyle(textRef.current); const lineHeight = @@ -205,542 +253,59 @@ function PlaceholderType(props) { } }, [props?.startDate, props?.selectDate?.format]); - switch (type) { - case "signature": { - const sigRotation = props.pos.options?.rotation; - const sigIsSwapped = [90, 270].includes(sigRotation); - const sigImgStyle = sigRotation - ? sigIsSwapped && - props.pos.signatureType === "type" && - props.pos.Width && - props.pos.Height - ? { - transform: `rotate(${sigRotation}deg) scaleX(${props.pos.Width / props.pos.Height}) scaleY(${props.pos.Height / props.pos.Width})` - } - : { transform: `rotate(${sigRotation}deg)` } - : undefined; - return props.pos.SignUrl ? ( - <img - alt="signature" - draggable="false" - src={props.pos.SignUrl} - style={sigImgStyle} - className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} - /> - ) : ( - <div className={widgetCls}> - {props.pos.type && ( - <div - style={{ - fontSize: props.pos - ? props.calculateFontsize(props.pos) - : "11px", - ...(sigRotation - ? { transform: `rotate(${sigRotation}deg)` } - : {}) - }} - className={`${sigIsSwapped ? "whitespace-nowrap" : ""} font-medium`} - > - {formatWidgetName()} - </div> - )} - </div> - ); - } - case "stamp": - return props.pos.SignUrl ? ( - <img - alt="stamp" - draggable="false" - src={props.pos.SignUrl} - className="w-full h-full select-none-cls object-contain" - /> - ) : ( - <div className={widgetCls}> - {props.pos.type && ( - <div - style={{ - fontSize: props.pos - ? props.calculateFontsize(props.pos) - : "11px" - }} - className="font-medium" - > - {formatWidgetName()} - </div> - )} - </div> - ); - case "checkbox": - const checkBoxLayout = props.pos.options?.layout || "vertical"; - const isMultipleCheckbox = - props.pos.options?.values?.length > 0 ? true : false; - const checkboxSize = parseFloat(fontSize); - // Scaled gaps - const checkboxGapX = `${checkboxSize * 0.8}px`; // was gap-x-2 (fixed 8px) - const checkboxGapY = `${checkboxSize * 0.4}px`; // was gap-y-[3px] (fixed 3px) - - const checkBoxWrapperClass = `flex items-start whitespace-pre-wrap ${ - checkBoxLayout === "horizontal" - ? `flex-row flex-wrap lg:py-[1.6px]` - : `flex-col` - }`; - - return ( - <div - className={checkBoxWrapperClass} - style={{ - zIndex: props.isSignYourself && "99", - width: "100%", - height: "100%", - overflow: "hidden", - //Scaled gap with same condition as before - gap: isMultipleCheckbox - ? checkBoxLayout === "horizontal" - ? checkboxGapX // was gap-x-2 - : checkboxGapY // was gap-y-[3px] - : undefined - }} - > - {props.pos.options?.values?.map((data, ind) => ( - <div key={ind} className="select-none-cls pointer-events-none"> - <label - htmlFor={`checkbox-${props.pos.key + ind}`} - style={{ - fontSize: fontSize, - color: fontColor, - gap: `${checkboxSize * 0.2}px` //scaled inner gap (was gap-1) - }} - className="mb-0 flex items-center" //removed gap-1 (fixed 4px) - > - <input - id={`checkbox-${props.pos.key + ind}`} - style={{ - width: fontSize, - height: fontSize, - flexShrink: 0 //prevent flex compression - }} - className="op-checkbox rounded-[1px]" - disabled={props.isNeedSign && isReadOnly} - type="checkbox" - readOnly - checked={ - !props?.isPrefillModal - ? !!selectCheckbox(ind, selectedCheckbox) - : false - } - /> - {!props.pos.options?.isHideLabel && ( - <span className="leading-none">{data}</span> - )} - </label> - </div> - ))} - </div> - ); - case textInputWidget: - return props.isSignYourself || iswidgetEnable ? ( - <textarea - placeholder={formatWidgetName()} - ref={textRef} - rows={50} - value={ - widgetValue - } - className={`w-full resize-none overflow-hidden text-base-content item-center outline-none ${isReadOnly ? "select-none" : ""}`} - style={{ - fontSize: fontSize, - color: fontColor, - background: isReadOnly ? props.data?.blockColor : "white", - pointerEvents: "none" - }} - name="text" - readOnly - disabled={props.isNeedSign && isReadOnly} - cols="50" - /> - ) : ( - <div style={textWidgetStyle} className="select-none-cls"> - <span className="ml-0.5">{formatWidgetName()}</span> - </div> - ); - case cellsWidget: { - const count = props.pos.options?.cellCount || 5; - const cells = (widgetValue || "").split(""); - const height = "100%"; - const fontSize = props.calculateFont(props.pos.options?.fontSize); - const fontColor = props.pos.options?.fontColor || "black"; - const handleCellResize = (newCount) => { - if (props.setCellCount) props.setCellCount(props.pos.key, newCount); - }; - const isEditable = - props.isPlaceholder || props.isSignYourself || props.isSelfSign; - return ( - <CellsWidget - isEnabled={iswidgetEnable} - count={count} - height={height} - value={ - cells.join("") - } - editable={isEditable} - resizable={props?.isAllowModify} - fontSize={fontSize} - fontColor={fontColor} - hint={formatWidgetName()} - onCellCountChange={handleCellResize} - /> - ); - } - case "dropdown": { - const dropdownValue = Array.isArray(widgetData) - ? widgetData.join(", ") - : widgetData == null - ? "" - : String(widgetData); - return ( - <div - style={textWidgetStyle} - className="select-none-cls flex justify-between items-center" - > - {dropdownValue.trim() || t("choose-one")} - <i className="fa-light fa-circle-chevron-down mr-1 "></i> - </div> - ); - } - case "initials": { - const iniRotation = props.pos.options?.rotation; - const iniIsSwapped = [90, 270].includes(iniRotation); - const iniImgStyle = iniRotation - ? iniIsSwapped && - props.pos.signatureType === "type" && - props.pos.Width && - props.pos.Height - ? { - transform: `rotate(${iniRotation}deg) scaleX(${props.pos.Width / props.pos.Height}) scaleY(${props.pos.Height / props.pos.Width})` - } - : { transform: `rotate(${iniRotation}deg)` } - : undefined; - return props.pos.SignUrl ? ( - <img - alt="initials" - draggable="false" - src={props.pos.SignUrl} - style={iniImgStyle} - className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} - /> - ) : ( - <div className={widgetCls}> - {props.pos.type && ( - <div - style={{ - fontSize: props.pos - ? props.calculateFontsize(props.pos) - : "11px", - ...(iniRotation - ? { transform: `rotate(${iniRotation}deg)` } - : {}), - ...(iniIsSwapped ? { whiteSpace: "nowrap" } : {}) - }} - className="font-medium text-center" - > - {formatWidgetName()} - </div> - )} - </div> - ); - } - case "name": - return iswidgetEnable ? ( - <textarea - readOnly - placeholder={formatWidgetName()} - rows={1} - value={ - widgetValue - } - className={`${textWidgetCls} ${isReadOnly ? "select-none" : ""}`} - style={{ - fontSize: fontSize, - color: fontColor, - background: isReadOnly ? props.data?.blockColor : "white", - pointerEvents: "none" - }} - cols="50" - disabled={props.isNeedSign && isReadOnly} - /> - ) : ( - <div className="flex h-full select-none-cls" style={textWidgetStyle}> - <span className="ml-0.5">{formatWidgetName()}</span> - </div> - ); - case "company": - return iswidgetEnable ? ( - <textarea - readOnly - placeholder={formatWidgetName()} - rows={1} - value={ - widgetValue - } - className={`${textWidgetCls} ${isReadOnly ? "select-none" : ""}`} - style={{ - fontSize: fontSize, - color: fontColor, - background: isReadOnly ? props.data?.blockColor : "white", - pointerEvents: "none" - }} - cols="50" - disabled={props.isNeedSign && isReadOnly} - /> - ) : ( - <div style={textWidgetStyle} className="select-none-cls"> - <span className="ml-0.5">{formatWidgetName()}</span> - </div> - ); - case "job title": - return iswidgetEnable ? ( - <textarea - readOnly - placeholder={formatWidgetName()} - rows={1} - value={ - widgetValue - } - className={`${textWidgetCls} ${isReadOnly ? "select-none" : ""}`} - style={{ - fontSize: fontSize, - color: fontColor, - background: isReadOnly ? props.data?.blockColor : "white", - pointerEvents: "none" - }} - cols="50" - disabled={props.isNeedSign && isReadOnly} - /> - ) : ( - <div style={textWidgetStyle} className="select-none-cls"> - <span className="ml-0.5">{formatWidgetName()}</span> - </div> - ); - case "date": - return iswidgetEnable || props?.data?.Role === "prefill" ? ( - <div className={`${selectWidgetCls} outline-[#007bff]`}> - <span - style={{ fontSize: fontSize, color: fontColor }} - className={`${isReadOnly ? `select-none opacity-25` : ``} ${selectWidgetCls} overflow-hidden`} - > - {date} - <i className="fa-light fa-calendar text-[10px] ml-[5px]"></i> - </span> - </div> - ) : ( - <div - style={textWidgetStyle} - className="select-none-cls overflow-hidden" - > - <span> - {(defaultData !== "today" && defaultData) || - (response !== "today" && response) || - props?.selectDate?.format || - props.pos?.options?.validation?.format || - "MM/dd/yyyy"} - </span> - </div> - ); - case "image": - return prefillImgLoad[props.pos?.key] ? ( - <div className="absolute w-full h-full inset-0 flex justify-center items-center bg-white/30 z-50"> - <Loader /> - </div> - ) : imgUrl ? ( - <img - alt="image" - draggable="false" - src={imgUrl} - className="w-full h-full select-none-cls object-contain" - /> - ) : ( - <div className={widgetCls}> - {props.pos.type && ( - <div - style={{ - fontSize: props.pos - ? props.calculateFontsize(props.pos) - : "11px" - }} - className="font-medium text-center" - > - {formatWidgetName()} - </div> - )} - </div> - ); - case "email": - return iswidgetEnable ? ( - <textarea - readOnly - placeholder={formatWidgetName()} - rows={1} - value={ - widgetValue - } - className={`${textWidgetCls} ${isReadOnly ? "select-none" : ""}`} - style={{ - fontSize: fontSize, - color: fontColor, - background: isReadOnly ? props.data?.blockColor : "white", - pointerEvents: "none" - }} - cols="1" - disabled={props.isNeedSign && isReadOnly} - /> - ) : ( - <div style={textWidgetStyle} className="select-none-cls"> - <span className="ml-0.5">{formatWidgetName()}</span> - </div> - ); - case radioButtonWidget: - const radioLayout = props.pos.options?.layout || "vertical"; - const isOnlyOneBtn = props.pos.options?.values?.length > 0 ? true : false; - const radioSize = parseFloat(fontSize); - //Scaled gaps based on radioSize - const scaledGapX = `${radioSize * 0.8}px`; // horizontal gap between items - const scaledGapY = `${radioSize * 0.4}px`; // vertical gap between items + /** Label of a radio option, which may be a string or { name }. */ + const getRadioLabel = (data) => { + if (typeof data === "string") return data; + if (data && typeof data === "object" && data.name != null) + return String(data.name); + return ""; + }; - const radioWrapperClass = `flex items-start whitespace-pre-wrap ${ - radioLayout === "horizontal" - ? `flex-row flex-wrap lg:py-[1.6px]` - : `flex-col` - }`; + /** Whether a radio option matches the current response or the default (#65). */ + const handleRadioCheck = (data) => { + if (props?.isPrefillModal) return false; + const current = widgetValue ? widgetValue : props.pos?.options?.defaultValue; + return isRadioSelected(current, data); + }; - return ( - <div - className={radioWrapperClass} - style={{ - width: "100%", - height: "100%", - overflow: "hidden", - //Scaled gap with condition same as before - gap: isOnlyOneBtn - ? radioLayout === "horizontal" - ? scaledGapX // was gap-x-[10px] - : scaledGapY // was gap-y-[5px] - : undefined - }} - > - {props.pos.options?.values.map((data, ind) => ( - <div key={ind} className="select-none-cls pointer-events-none"> - <label - htmlFor={`radio-${props.pos.key + ind}`} - style={{ - fontSize: fontSize, - color: fontColor, - gap: `${radioSize * 0.2}px` //scaled inner gap (was gap-1) - }} - className="mb-0 flex items-center" //removed text-xs - > - <input - readOnly - id={`radio-${props.pos.key + ind}`} - style={{ - width: fontSize, - height: fontSize, - flexShrink: 0 - }} - className={`op-radio rounded-full border-black appearance-none bg-white inline-block align-middle relative ${ - handleRadioCheck(data) ? "checked-radio" : "" - }`} - type="radio" - disabled={props.isNeedSign && isReadOnly} - checked={handleRadioCheck(data)} - /> - {!props.pos.options?.isHideLabel && ( - <span className="leading-none"> - {getRadioLabel(data).trim()} - </span> - )} - </label> - </div> - ))} - </div> - ); - case textWidget: - return ( - <textarea - name="text" - ref={textRef} - readOnly - placeholder={t("widgets-name.text")} - rows={50} - cols={50} - defaultValue={ - widgetValue - } - style={{ - fontFamily: "Arial, sans-serif", - fontSize: fontSize, - color: fontColor, - background: "white" - }} - className="w-full resize-none overflow-hidden text-base-content item-center outline-none" - /> - ); - case drawWidget: - return prefillImgLoad[props.pos?.key] ? ( - <div className="absolute w-full h-full inset-0 flex justify-center items-center bg-white/30 z-50"> - <Loader /> - </div> - ) : widgetValue ? ( - <img - alt="signature" - draggable="false" - src={widgetValue} - className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} - /> - ) : ( - <div className={widgetCls}> - {props.pos.type && ( - <div - style={{ - fontSize: props.pos - ? props.calculateFontsize(props.pos) - : "11px" - }} - className="font-medium" - > - {formatWidgetName()} - </div> - )} - </div> - ); - default: - return props.pos.SignUrl ? ( - <div className="pointer-events-none"> - <img - alt="image" - draggable="false" - src={props.pos.SignUrl} - className="w-full h-full " - /> - </div> - ) : ( - <div className={widgetCls}> - {props.pos.isStamp ? <div>stamp</div> : <div>signature</div>} - {props.pos.type && ( - <div - style={{ - fontSize: props.pos - ? props.calculateFontsize(props.pos) - : "11px" - }} - className="font-medium" - > - {formatWidgetName()} - </div> - )} - </div> - ); - } + const renderContext = { + props, + widgetCls, + formatWidgetName, + prefillImgLoad, + imgUrl, + widgetValue, + fontSize, + fontColor, + selectedCheckbox, + setSelectedCheckbox, + canEditInline, + isReadOnly, + iswidgetEnable, + widgetData, + textRef, + inlineError, + textWidgetStyle, + handleInlineTextChange, + persistInlineValue, + t, + setwidgetValue, + date, + defaultData, + response, + selectWidgetCls, + handleRadioCheck, + getRadioLabel + }; + return ( + renderSignature(type, renderContext) ?? + renderField(type, renderContext) ?? + renderCheckbox(type, renderContext) ?? + renderRadio(type, renderContext) ?? + renderText(type, renderContext) ?? + renderDate(type, renderContext) ?? + renderFallback(renderContext) + ); } export default PlaceholderType; diff --git a/apps/OpenSign/src/components/pdf/PlaceholderTypeCheckbox.jsx b/apps/OpenSign/src/components/pdf/PlaceholderTypeCheckbox.jsx new file mode 100644 index 0000000000..bfc804c223 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/PlaceholderTypeCheckbox.jsx @@ -0,0 +1,134 @@ +import { selectCheckbox } from "../../constant/Utils"; + +/** Render the inline checkbox group for the current widget. */ +export function renderCheckbox(type, context) { + const { + props, + fontSize, + fontColor, + selectedCheckbox, + setSelectedCheckbox, + canEditInline, + isReadOnly, + persistInlineValue + } = context; + switch (type) { + case "checkbox": + const checkBoxLayout = props.pos.options?.layout || "vertical"; + const isMultipleCheckbox = + props.pos.options?.values?.length > 0 ? true : false; + const checkboxSize = parseFloat(fontSize); + const checkboxGapX = `${checkboxSize * 0.8}px`; + const checkboxGapY = `${checkboxSize * 0.4}px`; + const checkBoxWrapperClass = `flex items-start whitespace-pre-wrap ${ + checkBoxLayout === "horizontal" + ? `flex-row flex-wrap lg:py-[1.6px]` + : `flex-col` + }`; + + return ( + <div + className={checkBoxWrapperClass} + style={{ + zIndex: props.isSignYourself && "99", + width: "100%", + height: "100%", + overflow: "hidden", + gap: isMultipleCheckbox + ? checkBoxLayout === "horizontal" + ? checkboxGapX + : checkboxGapY + : undefined + }} + > + {props.pos.options?.values?.map((data, ind) => { + const isAuthoring = canEditInline; + return ( + <div + key={ind} + className={ + isAuthoring ? "" : "select-none-cls pointer-events-none" + } + > + <label + htmlFor={`checkbox-${props.pos.key + ind}`} + style={{ + fontSize: fontSize, + color: fontColor, + gap: `${checkboxSize * 0.2}px` + }} + className="mb-0 flex items-center" + > + <input + id={`checkbox-${props.pos.key + ind}`} + style={{ + width: fontSize, + height: fontSize, + flexShrink: 0 + }} + className="op-checkbox rounded-[1px]" + disabled={props.isNeedSign && isReadOnly} + type="checkbox" + readOnly={!isAuthoring} + checked={ + isAuthoring + ? selectedCheckbox?.includes(ind) + : !props?.isPrefillModal + ? !!selectCheckbox(ind, selectedCheckbox) + : false + } + onClick={(e) => { + if (isAuthoring) e.stopPropagation(); + }} + onChange={(e) => { + if (!isAuthoring) return; + const isChecked = e.target.checked; + let updateSelectedCheckbox = selectedCheckbox + ? [...selectedCheckbox] + : []; + if (isChecked) { + const maxRequired = + props.pos?.options?.validation?.maxRequiredCount; + if ( + typeof maxRequired === "number" && + maxRequired > 0 && + updateSelectedCheckbox.length >= maxRequired + ) { + return; + } + updateSelectedCheckbox.push(ind); + } else { + updateSelectedCheckbox = updateSelectedCheckbox.filter( + (d) => d !== ind + ); + } + setSelectedCheckbox(updateSelectedCheckbox); + if (props.setXyPosition) { + persistInlineValue( + updateSelectedCheckbox, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + }} + /> + {!props.pos.options?.isHideLabel && ( + <span className="leading-none">{data}</span> + )} + </label> + </div> + ); + })} + </div> + ); + } +} diff --git a/apps/OpenSign/src/components/pdf/PlaceholderTypeDate.jsx b/apps/OpenSign/src/components/pdf/PlaceholderTypeDate.jsx new file mode 100644 index 0000000000..0289f710db --- /dev/null +++ b/apps/OpenSign/src/components/pdf/PlaceholderTypeDate.jsx @@ -0,0 +1,105 @@ +import DatePicker from "react-datepicker"; +import moment from "moment"; +import { changeDateToMomentFormat } from "../../constant/Utils"; + +/** Render the date field and its viewport-aware calendar. */ +export function renderDate(type, context) { + const { + props, + fontSize, + fontColor, + canEditInline, + iswidgetEnable, + isReadOnly, + date, + defaultData, + response, + textWidgetStyle, + persistInlineValue, + selectWidgetCls + } = context; + switch (type) { + case "date": { + const dateFormat = + props?.selectDate?.format || + props.pos?.options?.validation?.format || + "MM/dd/yyyy"; + const momentFormat = changeDateToMomentFormat(dateFormat); + const savedDate = + props.pos?.options?.response || + (defaultData !== "today" ? defaultData : ""); + const savedMoment = savedDate + ? moment(savedDate, momentFormat, true) + : null; + if ( + canEditInline && + (iswidgetEnable || props?.data?.Role === "prefill") + ) { + return ( + <div className="h-full w-full" onClick={(e) => e.stopPropagation()}> + <DatePicker + selected={ + savedMoment && savedMoment.isValid() + ? savedMoment.toDate() + : null + } + onChange={(value) => { + const text = value ? moment(value).format(momentFormat) : ""; + if (!props.setXyPosition) return; + persistInlineValue( + text, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + dateFormat, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + }} + dateFormat={momentFormat} + popperPlacement="bottom-end" + portalId="datepicker-portal-root" + popperProps={{ strategy: "fixed" }} + customInput={ + <input + style={{ fontSize: fontSize, color: fontColor }} + className="h-full w-full cursor-pointer bg-transparent outline-none" + readOnly + /> + } + /> + </div> + ); + } + return iswidgetEnable || props?.data?.Role === "prefill" ? ( + <div className={`${selectWidgetCls} outline-[#007bff]`}> + <span + style={{ fontSize: fontSize, color: fontColor }} + className={`${isReadOnly ? `select-none opacity-25` : ``} ${selectWidgetCls} overflow-hidden`} + > + {date} + <i className="fa-light fa-calendar text-[10px] ml-[5px]"></i> + </span> + </div> + ) : ( + <div + style={textWidgetStyle} + className="select-none-cls overflow-hidden" + > + <span> + {(defaultData !== "today" && defaultData) || + (response !== "today" && response) || + props?.selectDate?.format || + props.pos?.options?.validation?.format || + "MM/dd/yyyy"} + </span> + </div> + ); + } + } +} diff --git a/apps/OpenSign/src/components/pdf/PlaceholderTypeFields.jsx b/apps/OpenSign/src/components/pdf/PlaceholderTypeFields.jsx new file mode 100644 index 0000000000..ee3d1fcd1a --- /dev/null +++ b/apps/OpenSign/src/components/pdf/PlaceholderTypeFields.jsx @@ -0,0 +1,237 @@ +import CellsWidget from "./CellsWidget"; +import { + cellsWidget, + selectCheckbox, + textInputWidget +} from "../../constant/Utils"; +/** Render the field widget types, or return undefined when unmatched. */ +export function renderField(type, context) { + const { + props, + fontSize, + fontColor, + selectedCheckbox, + setSelectedCheckbox, + canEditInline, + isReadOnly, + iswidgetEnable, + widgetValue, + widgetData, + textRef, + inlineError, + textWidgetStyle, + formatWidgetName, + handleInlineTextChange, + persistInlineValue, + t, + setwidgetValue + } = context; + switch (type) { + case textInputWidget: + return props.isSignYourself || iswidgetEnable || canEditInline ? ( + <textarea + placeholder={formatWidgetName()} + ref={textRef} + rows={50} + value={widgetValue} + className={`w-full resize-none overflow-hidden text-base-content item-center outline-none ${isReadOnly ? "select-none" : ""} ${inlineError ? "border-2 border-red-500" : ""}`} + style={{ + fontSize: fontSize, + color: fontColor, + background: isReadOnly ? props.data?.blockColor : "white", + pointerEvents: canEditInline ? "auto" : "none", + WebkitTextSecurity: props.pos?.options?.isMasked ? "disc" : "none" + }} + name="text" + readOnly={!canEditInline} + onClick={(event) => { + if (canEditInline) event.stopPropagation(); + }} + onChange={handleInlineTextChange} + disabled={props.isNeedSign && isReadOnly} + cols="50" + /> + ) : ( + <div style={textWidgetStyle} className="select-none-cls"> + <span className="ml-0.5">{formatWidgetName()}</span> + </div> + ); + case cellsWidget: { + const count = props.pos.options?.cellCount || 5; + const cells = (widgetValue || "").split(""); + const height = "100%"; + const fontSize = props.calculateFont(props.pos.options?.fontSize); + const fontColor = props.pos.options?.fontColor || "black"; + const handleCellResize = (newCount) => { + if (props.setCellCount) props.setCellCount(props.pos.key, newCount); + }; + const isEditable = + props.isPlaceholder || props.isSignYourself || props.isSelfSign; + // Signers type in place (#64): keep one character per cell and save the value. + const canTypeCells = !props.isPlaceholder && canEditInline && !isReadOnly; + const handleCellChange = (event, index) => { + const chars = Array.from({ length: count }, (_, i) => cells[i] || " "); + const typed = event.target.value.slice(-1); + chars[index] = typed || " "; + const next = chars.join("").trimEnd(); + setwidgetValue(next); + if (props.setXyPosition) { + persistInlineValue( + next, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + if (typed) { + event.target.parentElement?.nextElementSibling + ?.querySelector("input") + ?.focus(); + } + }; + return ( + <CellsWidget + isEnabled={iswidgetEnable} + count={count} + height={height} + value={cells.join("")} + editable={isEditable || canTypeCells} + onChange={canTypeCells ? handleCellChange : undefined} + resizable={props?.isAllowModify} + fontSize={fontSize} + fontColor={fontColor} + hint={formatWidgetName()} + onCellCountChange={handleCellResize} + /> + ); + } + case "dropdown": { + // Saved values can be arrays; options can be objects with a name. + const normalizeOption = (option) => { + if (option == null) return ""; + if (typeof option === "object") { + return String(option.name ?? option.value ?? ""); + } + return String(option); + }; + const dropdownValue = Array.isArray(widgetData) + ? widgetData.map(normalizeOption).join(", ") + : normalizeOption(widgetData); + const selectedValue = Array.isArray(widgetValue) + ? widgetValue.map(normalizeOption) + : widgetValue + ? [normalizeOption(widgetValue)] + : []; + if (canEditInline && props.pos?.options?.isMultiSelect) { + const persist = (next) => { + setwidgetValue(next); + if (props.setXyPosition) { + persistInlineValue( + next, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + }; + return ( + <div + className="flex h-full w-full flex-col overflow-auto" + style={{ fontSize: fontSize, color: fontColor }} + > + {(props.pos?.options?.values || []).map((data, ind) => { + const optionLabel = normalizeOption(data); + return ( + <label + key={ind} + className="mb-0 flex items-center" + style={{ gap: `${Math.max(fontSize * 0.2, 2)}px` }} + > + <input + type="checkbox" + className="op-checkbox rounded-[1px]" + style={{ + width: fontSize, + height: fontSize, + flexShrink: 0 + }} + checked={selectedValue.includes(optionLabel)} + onClick={(e) => e.stopPropagation()} + onChange={(e) => { + const next = e.target.checked + ? [...selectedValue, optionLabel] + : selectedValue.filter((val) => val !== optionLabel); + persist(next); + }} + /> + <span className="leading-none">{optionLabel}</span> + </label> + ); + })} + </div> + ); + } + return canEditInline ? ( + <select + value={selectedValue.join(", ")} + onChange={(e) => { + const val = e.target.value; + setwidgetValue(val); + if (props.setXyPosition) { + persistInlineValue( + val, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + }} + onClick={(e) => e.stopPropagation()} + className="w-full h-full text-base-content outline-none bg-transparent" + style={{ fontSize: fontSize, color: fontColor }} + > + <option value="" disabled hidden> + {t("choose-one")} + </option> + {(props.pos?.options?.values || []).map((data, ind) => ( + <option key={ind} value={normalizeOption(data)}> + {normalizeOption(data)} + </option> + ))} + </select> + ) : ( + <div + style={textWidgetStyle} + className="select-none-cls flex justify-between items-center" + > + {dropdownValue || t("choose-one")} + <i className="fa-light fa-circle-chevron-down mr-1 "></i> + </div> + ); + } + } +} diff --git a/apps/OpenSign/src/components/pdf/PlaceholderTypeRadio.jsx b/apps/OpenSign/src/components/pdf/PlaceholderTypeRadio.jsx new file mode 100644 index 0000000000..a452b38497 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/PlaceholderTypeRadio.jsx @@ -0,0 +1,106 @@ +import { isRadioSelected, radioButtonWidget } from "../../constant/Utils"; + +/** Render a radio group when the current widget is a radio button. */ +export function renderRadio(type, context) { + const { + props, + fontSize, + fontColor, + canEditInline, + isReadOnly, + handleRadioCheck, + persistInlineValue, + getRadioLabel + } = context; + switch (type) { + case radioButtonWidget: + const radioLayout = props.pos.options?.layout || "vertical"; + const isOnlyOneBtn = props.pos.options?.values?.length > 0 ? true : false; + const radioSize = parseFloat(fontSize); + //Scaled gaps based on radioSize + const scaledGapX = `${radioSize * 0.8}px`; // horizontal gap between items + const scaledGapY = `${radioSize * 0.4}px`; // vertical gap between items + + const radioWrapperClass = `flex items-start whitespace-pre-wrap ${ + radioLayout === "horizontal" + ? `flex-row flex-wrap lg:py-[1.6px]` + : `flex-col` + }`; + + return ( + <div + className={radioWrapperClass} + style={{ + width: "100%", + height: "100%", + overflow: "hidden", + //Scaled gap with condition same as before + gap: isOnlyOneBtn + ? radioLayout === "horizontal" + ? scaledGapX // was gap-x-[10px] + : scaledGapY // was gap-y-[5px] + : undefined + }} + > + {props.pos.options?.values.map((data, ind) => ( + <div + key={ind} + className={ + canEditInline ? "" : "select-none-cls pointer-events-none" + } + > + <label + htmlFor={`radio-${props.pos.key + ind}`} + style={{ + fontSize: fontSize, + color: fontColor, + gap: `${radioSize * 0.2}px` //scaled inner gap (was gap-1) + }} + className="mb-0 flex items-center" //removed text-xs + > + <input + readOnly={!canEditInline} + id={`radio-${props.pos.key + ind}`} + onChange={() => { + if (!canEditInline) return; + if (props.setXyPosition) { + persistInlineValue( + data, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + }} + style={{ + width: fontSize, + height: fontSize, + flexShrink: 0 + }} + className={`op-radio rounded-full border-black appearance-none bg-white inline-block align-middle relative ${ + handleRadioCheck(data) ? "checked-radio" : "" + }`} + type="radio" + disabled={props.isNeedSign && isReadOnly} + checked={handleRadioCheck(data)} + /> + {!props.pos.options?.isHideLabel && ( + <span className="leading-none"> + {getRadioLabel(data).trim()} + </span> + )} + </label> + </div> + ))} + </div> + ); + } +} diff --git a/apps/OpenSign/src/components/pdf/PlaceholderTypeSignature.jsx b/apps/OpenSign/src/components/pdf/PlaceholderTypeSignature.jsx new file mode 100644 index 0000000000..bcbbefa28e --- /dev/null +++ b/apps/OpenSign/src/components/pdf/PlaceholderTypeSignature.jsx @@ -0,0 +1,250 @@ +import Loader from "../../primitives/Loader"; +import { drawWidget } from "../../constant/Utils"; + +/** Render the signature widget types, or return undefined when unmatched. */ +export function renderSignature(type, context) { + const { + props, + widgetCls, + formatWidgetName, + prefillImgLoad, + imgUrl, + widgetValue + } = context; + switch (type) { + case "signature": { + const sigRotation = props.pos.options?.rotation; + const sigIsSwapped = [90, 270].includes(sigRotation); + const sigImgStyle = sigRotation + ? sigIsSwapped && + props.pos.signatureType === "type" && + props.pos.Width && + props.pos.Height + ? { + transform: `rotate(${sigRotation}deg) scaleX(${props.pos.Width / props.pos.Height}) scaleY(${props.pos.Height / props.pos.Width})` + } + : { transform: `rotate(${sigRotation}deg)` } + : undefined; + return props.pos.SignUrl ? ( + <img + alt="signature" + draggable="false" + src={props.pos.SignUrl} + style={sigImgStyle} + className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} + /> + ) : ( + <div className={widgetCls}> + {props.pos.type && ( + <div + style={{ + fontSize: props.pos + ? props.calculateFontsize(props.pos) + : "11px", + ...(sigRotation + ? { transform: `rotate(${sigRotation}deg)` } + : {}) + }} + className={`${sigIsSwapped ? "whitespace-nowrap" : ""} font-medium`} + > + {formatWidgetName()} + </div> + )} + </div> + ); + } + case "stamp": + return props.pos.SignUrl ? ( + <img + alt="stamp" + draggable="false" + src={props.pos.SignUrl} + className="w-full h-full select-none-cls object-contain" + /> + ) : ( + <div className={widgetCls}> + {props.pos.type && ( + <div + style={{ + fontSize: props.pos + ? props.calculateFontsize(props.pos) + : "11px" + }} + className="font-medium" + > + {formatWidgetName()} + </div> + )} + </div> + ); + case "initials": { + const iniRotation = props.pos.options?.rotation; + const iniIsSwapped = [90, 270].includes(iniRotation); + const iniImgStyle = iniRotation + ? iniIsSwapped && + props.pos.signatureType === "type" && + props.pos.Width && + props.pos.Height + ? { + transform: `rotate(${iniRotation}deg) scaleX(${props.pos.Width / props.pos.Height}) scaleY(${props.pos.Height / props.pos.Width})` + } + : { transform: `rotate(${iniRotation}deg)` } + : undefined; + return props.pos.SignUrl ? ( + <img + alt="initials" + draggable="false" + src={props.pos.SignUrl} + style={iniImgStyle} + className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} + /> + ) : ( + <div className={widgetCls}> + {props.pos.type && ( + <div + style={{ + fontSize: props.pos + ? props.calculateFontsize(props.pos) + : "11px", + ...(iniRotation + ? { transform: `rotate(${iniRotation}deg)` } + : {}), + ...(iniIsSwapped ? { whiteSpace: "nowrap" } : {}) + }} + className="font-medium text-center" + > + {formatWidgetName()} + </div> + )} + </div> + ); + } + case "initials": { + const iniRotation = props.pos.options?.rotation; + const iniIsSwapped = [90, 270].includes(iniRotation); + const iniImgStyle = iniRotation + ? iniIsSwapped && + props.pos.signatureType === "type" && + props.pos.Width && + props.pos.Height + ? { + transform: `rotate(${iniRotation}deg) scaleX(${props.pos.Width / props.pos.Height}) scaleY(${props.pos.Height / props.pos.Width})` + } + : { transform: `rotate(${iniRotation}deg)` } + : undefined; + return props.pos.SignUrl ? ( + <img + alt="initials" + draggable="false" + src={props.pos.SignUrl} + style={iniImgStyle} + className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} + /> + ) : ( + <div className={widgetCls}> + {props.pos.type && ( + <div + style={{ + fontSize: props.pos + ? props.calculateFontsize(props.pos) + : "11px", + ...(iniRotation + ? { transform: `rotate(${iniRotation}deg)` } + : {}), + ...(iniIsSwapped ? { whiteSpace: "nowrap" } : {}) + }} + className="font-medium text-center" + > + {formatWidgetName()} + </div> + )} + </div> + ); + } + case "image": + return prefillImgLoad[props.pos?.key] ? ( + <div className="absolute w-full h-full inset-0 flex justify-center items-center bg-white/30 z-50"> + <Loader /> + </div> + ) : imgUrl ? ( + <img + alt="image" + draggable="false" + src={imgUrl} + className="w-full h-full select-none-cls object-contain" + /> + ) : ( + <div className={widgetCls}> + {props.pos.type && ( + <div + style={{ + fontSize: props.pos + ? props.calculateFontsize(props.pos) + : "11px" + }} + className="font-medium text-center" + > + {formatWidgetName()} + </div> + )} + </div> + ); + case drawWidget: + return prefillImgLoad[props.pos?.key] ? ( + <div className="absolute w-full h-full inset-0 flex justify-center items-center bg-white/30 z-50"> + <Loader /> + </div> + ) : widgetValue ? ( + <img + alt="signature" + draggable="false" + src={widgetValue} + className={`${props.pos.signatureType !== "type" ? "object-contain" : ""} w-full h-full select-none-cls`} + /> + ) : ( + <div className={widgetCls}> + {props.pos.type && ( + <div + style={{ + fontSize: props.pos + ? props.calculateFontsize(props.pos) + : "11px" + }} + className="font-medium" + > + {formatWidgetName()} + </div> + )} + </div> + ); + } +} + +/** Render the fallback placeholder for unknown widget types. */ +export function renderFallback(context) { + const { props, widgetCls, formatWidgetName } = context; + return props.pos.SignUrl ? ( + <div className="pointer-events-none"> + <img + alt="image" + draggable="false" + src={props.pos.SignUrl} + className="w-full h-full " + /> + </div> + ) : ( + <div className={widgetCls}> + {props.pos.isStamp ? <div>stamp</div> : <div>signature</div>} + {props.pos.type && ( + <div + style={{ + fontSize: props.pos ? props.calculateFontsize(props.pos) : "11px" + }} + className="font-medium" + > + {formatWidgetName()} + </div> + )} + </div> + ); +} diff --git a/apps/OpenSign/src/components/pdf/PlaceholderTypeText.jsx b/apps/OpenSign/src/components/pdf/PlaceholderTypeText.jsx new file mode 100644 index 0000000000..4a42e6499f --- /dev/null +++ b/apps/OpenSign/src/components/pdf/PlaceholderTypeText.jsx @@ -0,0 +1,217 @@ +import { textWidget } from "../../constant/Utils"; +import { UI_FONT } from "../../constant/fonts"; + +const textWidgetCls = + "w-full h-full md:min-w-full md:min-h-full z-[999] text-[12px] overflow-hidden resize-none outline-none text-base-content item-center whitespace-pre-wrap"; + +function renderInlineText(context, cols) { + const { + canEditInline, + iswidgetEnable, + textWidgetStyle, + formatWidgetName, + widgetValue, + textWidgetCls, + isReadOnly, + inlineError, + fontSize, + fontColor, + props, + handleInlineTextChange + } = context; + if (!canEditInline && !iswidgetEnable) { + return ( + <div style={textWidgetStyle} className="select-none-cls"> + <span className="ml-0.5">{formatWidgetName()}</span> + </div> + ); + } + return ( + <textarea + placeholder={formatWidgetName()} + rows={1} + value={widgetValue ?? ""} + className={`${textWidgetCls} ${isReadOnly ? "select-none" : ""} ${inlineError ? "border-2 border-red-500" : ""}`} + style={{ + fontSize, + color: fontColor, + background: isReadOnly ? props.data?.blockColor : "white", + pointerEvents: canEditInline ? "auto" : "none", + WebkitTextSecurity: props.pos?.options?.isMasked ? "disc" : "none" + }} + cols={cols} + readOnly={!canEditInline} + disabled={props.isNeedSign && isReadOnly} + onClick={(event) => { + if (canEditInline) event.stopPropagation(); + }} + onChange={handleInlineTextChange} + /> + ); +} + +/** Render text-like fields and fixed-height text inputs. */ +export function renderText(type, context) { + const { + props, + fontSize, + fontColor, + canEditInline, + isReadOnly, + iswidgetEnable, + widgetValue, + textRef, + inlineError, + textWidgetStyle, + setwidgetValue, + persistInlineValue, + formatWidgetName, + handleInlineTextChange, + t + } = context; + switch (type) { + case "name": + return renderInlineText(context, "50"); + case "company": + return renderInlineText(context, "50"); + case "job title": + return renderInlineText(context, "50"); + case "email": + return renderInlineText(context, "1"); + case textWidget: + return ( + <textarea + name="text" + ref={textRef} + readOnly={!canEditInline} + placeholder={t("widgets-name.text")} + rows={50} + cols={50} + value={widgetValue} + style={{ + fontFamily: UI_FONT, + fontSize: fontSize, + lineHeight: 1.25, + color: fontColor, + background: "white", + pointerEvents: canEditInline ? "auto" : "none", + WebkitTextSecurity: props.pos?.options?.isMasked ? "disc" : "none" + }} + className={`w-full resize-none overflow-hidden text-base-content item-center outline-none ${inlineError ? "border-2 border-red-500" : ""}`} + onClick={(e) => { + if (canEditInline) e.stopPropagation(); + }} + onChange={(e) => { + if (canEditInline) { + const val = e.target.value; + setwidgetValue(val); + if (props.setXyPosition) { + persistInlineValue( + val, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + } + }} + /> + ); + case textWidget: + return ( + <textarea + name="text" + ref={textRef} + readOnly + placeholder={t("widgets-name.text")} + rows={50} + cols={50} + defaultValue={widgetValue} + style={{ + fontFamily: "Arial, sans-serif", + fontSize: fontSize, + lineHeight: 1.25, + color: fontColor, + background: "white" + }} + className="w-full resize-none overflow-hidden text-base-content item-center outline-none" + /> + ); + + case textWidget: + return ( + <textarea + name="text" + ref={textRef} + readOnly={!canEditInline} + placeholder={t("widgets-name.text")} + rows={50} + cols={50} + value={widgetValue} + style={{ + fontFamily: UI_FONT, + fontSize: fontSize, + lineHeight: 1.25, + color: fontColor, + background: "white", + pointerEvents: canEditInline ? "auto" : "none", + WebkitTextSecurity: props.pos?.options?.isMasked ? "disc" : "none" + }} + className={`w-full resize-none overflow-hidden text-base-content item-center outline-none ${inlineError ? "border-2 border-red-500" : ""}`} + onClick={(e) => { + if (canEditInline) e.stopPropagation(); + }} + onChange={(e) => { + if (canEditInline) { + const val = e.target.value; + setwidgetValue(val); + if (props.setXyPosition) { + persistInlineValue( + val, + props.pos, + props.xyPosition, + props.index, + props.setXyPosition, + props.data?.Id || props.uniqueId, + false, + null, + props.pos?.options?.fontSize || 12, + props.pos?.options?.fontColor || "black", + null, + null + ); + } + } + }} + /> + ); + case textWidget: + return ( + <textarea + name="text" + ref={textRef} + readOnly + placeholder={t("widgets-name.text")} + rows={50} + cols={50} + defaultValue={widgetValue} + style={{ + fontFamily: "Arial, sans-serif", + fontSize: fontSize, + lineHeight: 1.25, + color: fontColor, + background: "white" + }} + className="w-full resize-none overflow-hidden text-base-content item-center outline-none" + /> + ); + } +} diff --git a/apps/OpenSign/src/components/pdf/PrefillWidgetsModal.jsx b/apps/OpenSign/src/components/pdf/PrefillWidgetsModal.jsx index 54854048b6..652406533a 100644 --- a/apps/OpenSign/src/components/pdf/PrefillWidgetsModal.jsx +++ b/apps/OpenSign/src/components/pdf/PrefillWidgetsModal.jsx @@ -1,24 +1,14 @@ -import React, { forwardRef, useEffect, useMemo, useRef, useState } from "react"; +import React, { useEffect, useMemo, useRef, useState } from "react"; import ModalUi from "../../primitives/ModalUi"; import { - getMonth, getYear, - radioButtonWidget, compressedFileSize, - textWidget, - months, - changeDateToMomentFormat, convertBase64ToFile, generatePdfName, - drawWidget, getBase64MimeType, - isBase64 } from "../../constant/Utils"; -import DatePicker from "react-datepicker"; -import "react-datepicker/dist/react-datepicker.css"; import { range } from "pdf-lib"; import { useTranslation } from "react-i18next"; -import moment from "moment"; import AsyncSelect from "react-select/async"; import axios from "axios"; import AddContact from "../../primitives/AddContact"; @@ -28,93 +18,9 @@ import { setPrefillImg, } from "../../redux/reducers/widgetSlice"; import * as utils from "../../utils"; -import Draw from "./tab/Draw"; -import PenColorComponent from "./tab/PenColorComponent"; - -const widgetTitle = "font-medium"; -const widgetLabelCss = (isRequired = false) => { - return `${isRequired ? "after:content-['_*'] after:text-red-500" : ""} block text-xs font-semibold`; -}; -const ShowTextWidget = ({ position, handleWidgetDetails }) => { - const inputRef = useRef(null); - const [inputValue, setInputValue] = useState(position.options.response || ""); - - return ( - <input - ref={inputRef} - rows={1} - value={inputValue} - onChange={(e) => { - setInputValue(e.target.value); - handleWidgetDetails(position, e.target.value); - }} - className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full text-xs" - /> - ); -}; -const ImageComponent = (props) => { - const { t } = useTranslation(); - const prefillImg = useSelector((state) => state.widget.prefillImg); - const imageRefs = useRef({}); - - let imgUrl = ""; - const isBase64Url = isBase64(props?.position?.SignUrl); - if (isBase64Url) { - imgUrl = props?.position?.SignUrl; - } else { - const getPrefillImg = prefillImg?.find( - (x) => x.id === props?.position?.key - ); - imgUrl = getPrefillImg?.base64; - } - - return ( - <> - <span - className={`${widgetLabelCss(props?.position?.options?.status === "required")} ${widgetTitle}`} - > - {props?.position.options?.name} - </span> - {imgUrl ? ( - <> - <div className="cursor-pointer op-card border-[1px] border-gray-400 flex flex-col w-full h-full justify-center items-center "> - <img - alt="print img" - ref={(el) => (imageRefs.current[props?.id] = el)} // Assign ref dynamicallys - src={imgUrl} - draggable="false" - className="object-contain h-full w-full aspect-[5/2]" - onLoad={() => props?.handleImageLoaded?.(props?.position.key)} - onError={() => props?.handleImageLoaded?.(props?.position.key)} - /> - </div> - <span - onClick={() => props?.handleClearImage(props?.position)} - className="flex justify-start text-blue-500 underline cursor-pointer" - > - {t("clear")} - </span> - </> - ) : ( - <div - className="cursor-pointer op-card border-[1px] op-border-hover flex flex-col overflow-hidden w-full h-full aspect-[5/2] justify-center items-center" - onClick={() => imageRefs.current[props?.id]?.click()} - > - <input - type="file" - onChange={(e) => props?.onImageChange?.(e, props?.position)} - className="filetype" - accept="image/png,image/jpeg" - ref={(el) => (imageRefs.current[props?.id] = el)} // Assign ref dynamically - hidden - /> - <i className="fa-light text-base-content fa-cloud-upload-alt text-[25px]"></i> - <div className="text-[10px] text-base-content">{t("upload")}</div> - </div> - )} - </> - ); -}; +import { createPrefillWidgetRenderer } from "./prefillWidgetRenderer"; +import { createEmbedPrefill } from "./prefillWidgetActions"; +import { getPrefillWidgets } from "./prefillWidgetList"; function PrefillWidgetModal(props) { const { t } = useTranslation(); @@ -134,42 +40,10 @@ function PrefillWidgetModal(props) { const years = range(1950, getYear(new Date()) + 16, 1); // useMemo to memoize the calculation of unique widgets - const uniqueWidget = useMemo(() => { - //functions to used remove duplicate name values across all pages - if (!props.prefillData) return []; - //This will help us track which name values have already been encountered across all pages. - const uniqueNames = new Set(); - //Filter and flatten placeholder widgets while keeping unique names - const filteredArray = props.prefillData?.placeHolder?.map((item) => ({ - ...item, - pos: item.pos.filter((curr) => { - if (uniqueNames.has(curr?.options?.name)) return false; //Duplicate name found, remove it - uniqueNames.add(curr?.options?.name); //First time seen, add to set - return true; - }) - })); - // Flatten the filtered array, exclude read-only widgets, - // carry yPosition for sorting, then sort by pageNumber asc → yPosition asc - // (mirrors the newSignPos.sort in PdfRequestFiles so widgets appear in - // the same top-to-bottom, page-1-first order as they do in the document) - const flatArray = filteredArray - ?.flatMap((page) => - page.pos - .filter((widget) => !widget.options?.isReadOnly) - .map((widget) => ({ - widget, - pageNumber: page.pageNumber, - yPosition: widget.yPosition ?? 0 - })) - ) - ?.sort((a, b) => - a.pageNumber !== b.pageNumber - ? a.pageNumber - b.pageNumber // primary: page order (page 1 first) - : a.yPosition - b.yPosition // secondary: top-to-bottom within page - ); - - return flatArray || []; - }, [props.prefillData]); + const uniqueWidget = useMemo( + () => getPrefillWidgets(props.prefillData), + [props.prefillData] + ); // Reset loader state when modal closes useEffect(() => { @@ -220,46 +94,6 @@ function PrefillWidgetModal(props) { } } }, [props?.isPrefillModal, uniqueWidget]); - const ExampleCustomInput = forwardRef(({ value, onClick }, ref) => ( - <div - style={{ fontFamily: "Arial, sans-serif" }} - className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full" - onClick={onClick} - ref={ref} - > - {value} - <i className="fa-light fa-calendar ml-[5px]"></i> - </div> - )); - ExampleCustomInput.displayName = "ExampleCustomInput"; - - const handleDate = (position) => { - // The getDatePickerDate function retrieves the date in the correct format supported by the DatePicker. - const getDate = utils.getDatePickerDate( - position?.options.response, - position?.options?.validation?.format - ); - return getDate; - }; - //function to set date with required date format onchange date - const handleOnDateChange = (date, position) => { - const format = position?.options?.validation?.format || "MM/dd/yyyy"; - let updateDate = date; - let newDate; - const isSpecialDateFormat = - format && ["dd-MM-yyyy", "dd.MM.yyyy", "dd/MM/yyyy"].includes(format); - if (isSpecialDateFormat) { - newDate = moment(updateDate).format(changeDateToMomentFormat(format)); - } else { - //using moment package is used to change date as per the format provided in selectDate obj e.g. - MM/dd/yyyy -> 03/12/2024 - newDate = new Date(updateDate); - newDate = moment(newDate.getTime()).format( - changeDateToMomentFormat(format) - ); - } - handleWidgetDetails(position, newDate); - }; - const handleSavePrefillImg = async (base64) => { setLoading(true); try { @@ -455,287 +289,14 @@ function PrefillWidgetModal(props) { canvasRef.current.clear(); } }; - const handleWidgetType = (position, id) => { - switch (position?.type) { - case "checkbox": - return ( - <> - <span - className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} - > - {position.options?.name} - </span> - <div className="flex flex-col gap-y-1"> - {position.options?.values?.map((data, ind) => ( - <div - key={ind} - className="select-none-cls flex items-center text-center gap-0.5" - > - <input - id={`modal-checkbox-${position.key + ind}`} - className="mt-[2px] op-checkbox op-checkbox-xs" - type="checkbox" - checked={selectCheckbox(ind, position)} - onChange={(e) => - handleCheckboxValue(e.target.checked, ind, position) - } - /> - <label - htmlFor={`modal-checkbox-${position.key + ind}`} - className="text-xs mb-0 text-center ml-[3px] cursor-pointer" - > - {data} - </label> - </div> - ))} - </div> - </> - ); - case textWidget: - return ( - <> - <span - className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} - > - {position.options?.name} - </span> - <ShowTextWidget - position={position} - handleWidgetDetails={handleWidgetDetails} - /> - </> - ); - case "dropdown": - return ( - <> - <span - className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} - > - {position.options?.name} - </span> - <select - className="op-select op-select-bordered op-select-sm focus:outline-none hover:border-base-content text-base-content w-full" - id="myDropdown" - value={ - position?.options?.response || position?.options?.defaultValue - } - onChange={(e) => handleWidgetDetails(position, e.target.value)} - > - {/* Default/Title option */} - <option value="" disabled hidden> - {t("choose-one")} - </option> - {position?.options?.values?.map((data, ind) => ( - <option key={ind} value={data}> - {data} - </option> - ))} - </select> - </> - ); - case "date": - return ( - <> - <span - className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} - > - {position.options?.name} - </span> - <DatePicker - portalId="datepicker-portal-root" - renderCustomHeader={({ date, changeYear, changeMonth }) => ( - <div className="flex justify-start ml-2"> - <select - className="bg-transparent outline-none" - value={months[getMonth(date)]} - onChange={({ target: { value } }) => - changeMonth(months.indexOf(value)) - } - > - {months.map((option) => ( - <option key={option} value={option}> - {option} - </option> - ))} - </select> - <select - className="bg-transparent outline-none" - value={getYear(date)} - onChange={({ target: { value } }) => changeYear(value)} - > - {years.map((option) => ( - <option key={option} value={option}> - {option} - </option> - ))} - </select> - </div> - )} - closeOnScroll={true} - selected={handleDate(position)} - onChange={(date) => handleOnDateChange(date, position)} - customInput={<ExampleCustomInput />} - dateFormat={position?.options?.validation?.format || "MM/dd/yyyy"} - /> - </> - ); - case "image": - return ( - <ImageComponent - position={position} - onImageChange={onImageChange} - handleImageLoaded={handleImageLoaded} - handleClearImage={handleClearImage} - id={id} - /> - ); - case radioButtonWidget: - return ( - <> - <span - className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} - > - {position.options?.name} - </span> - <div className="flex flex-col gap-y-1"> - {position.options?.values.map((data, ind) => ( - <div - key={ind} - className="select-none-cls flex items-center text-center gap-0.5" - > - <input - id={`modal-radio-${position.key + ind}`} - className="mt-[2px] op-radio op-radio-xs" - type="radio" - checked={handleRadioCheck(data, position)} - onChange={() => handleWidgetDetails(position, data)} - /> - <label - htmlFor={`modal-radio-${position.key + ind}`} - className="text-xs mb-0 ml-[2px] cursor-pointer" - > - {data} - </label> - </div> - ))} - </div> - </> - ); - case drawWidget: - return ( - <div> - <span - className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} - > - {position.options?.name} - </span> - <Draw - key={position.key + "_" + (prefillImg?.length || 0)} - penColor={penColor} - canvasRef={getCanvasRef(position.key)} - currWidgetsDetails={position} - handleSignatureChange={handleSignatureChange} - prefillCls={"prefillCanvas"} - /> - <div className="flex flex-row justify-between mt-[10px]"> - <PenColorComponent - penColor={penColor} - setPenColor={setPenColor} - /> - <span - onClick={() => { - clearCanvasById(position?.key); - handleClearImage(position); - }} - className="flex justify-start text-blue-500 underline cursor-pointer" - > - {t("clear")} - </span> - </div> - </div> - ); - default: - return position?.SignUrl ? ( - <div className="pointer-events-none"> - <img - alt="image" - draggable="false" - src={position?.SignUrl} - className="w-full h-full" - /> - </div> - ) : ( - <div className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full"> - No widget - </div> - ); - } - }; - - const handleEmbedPrefill = async (item) => { - //checking is there any draw widget response have base64 url then generate that base64 to url and save it - const prefillWidgets = props.xyPosition?.find((x) => x.Role === "prefill"); - let updatedXyPosition = []; - if (prefillWidgets) { - const isDrawWidget = (prefillWidgets.placeHolder ?? []).some((ph) => - (ph?.pos ?? []).some((p) => p?.type === drawWidget) - ); - if (isDrawWidget) { - const getPrefill = props.xyPosition.find((x) => x?.Role === "prefill"); - const getPlaceholder = getPrefill?.placeHolder ?? []; - const updatedData = await Promise.all( - getPlaceholder.map(async (page) => ({ - ...page, - pos: await Promise.all( - page.pos.map(async (item) => { - if (item?.type === drawWidget) { - const widgetResponse = item?.options?.response; - - // Skip if no response - if (!widgetResponse) return item; - - // If already URL, do not re-upload - if ( - typeof widgetResponse === "string" && - widgetResponse.startsWith("http") - ) { - return item; - } + const handleWidgetType = createPrefillWidgetRenderer({ + t, penColor, setPenColor, years, prefillImg, selectCheckbox, + handleCheckboxValue, handleRadioCheck, handleWidgetDetails, handleClearImage, + handleImageLoaded, onImageChange, handleSignatureChange, getCanvasRef, + clearCanvasById + }); + const handleEmbedPrefill = createEmbedPrefill({ props, handleSavePrefillImg }); - // Convert THIS widget's base64 → URL - const drawUrl = await handleSavePrefillImg(widgetResponse); - return { - ...item, - options: { - ...item.options, - response: drawUrl - } - }; - } - - return item; - }) - ) - })) - ); - - updatedXyPosition = props.xyPosition.map((obj) => { - if (obj.Role === "prefill") { - return { - ...obj, - placeHolder: updatedData - }; - } - return obj; - }); - - props.setXyPosition(updatedXyPosition); - } - } - - await props.handleCreateDocument(); - }; - //`loadOptions` function to use show all list of signer in dropdown const loadOptions = async (inputValue) => { try { const baseURL = localStorage.getItem("baseUrl"); diff --git a/apps/OpenSign/src/components/pdf/RenderAllPdfPage.jsx b/apps/OpenSign/src/components/pdf/RenderAllPdfPage.jsx index fecbdf191e..5854374f8e 100644 --- a/apps/OpenSign/src/components/pdf/RenderAllPdfPage.jsx +++ b/apps/OpenSign/src/components/pdf/RenderAllPdfPage.jsx @@ -1,7 +1,10 @@ import React, { useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; -import { Document, Page } from "react-pdf"; +import { Document, Page, pdfjs } from "react-pdf"; import { useSelector } from "react-redux"; + +// The worker URL lives with the PDF chunk, not the login bundle (#55). +pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`; import { PDFDocument } from "pdf-lib"; import { base64ToArrayBuffer, @@ -144,7 +147,7 @@ function RenderAllPdfPage(props) { const uploadedPdfDoc = await PDFDocument.load(uploadedPdfBytes, { ignoreEncryption: true }); - const basePdfDoc = await PDFDocument.load(props.pdfArrayBuffer); + const basePdfDoc = await PDFDocument.load(props.pdfArrayBuffer, { ignoreEncryption: true }); // Copy pages from the uploaded PDF to the base PDF const uploadedPdfPages = await basePdfDoc.copyPages( diff --git a/apps/OpenSign/src/components/pdf/RenderPdf.jsx b/apps/OpenSign/src/components/pdf/RenderPdf.jsx index 726dd38488..31f510db10 100644 --- a/apps/OpenSign/src/components/pdf/RenderPdf.jsx +++ b/apps/OpenSign/src/components/pdf/RenderPdf.jsx @@ -5,7 +5,10 @@ import React, { useLayoutEffect, useEffect } from "react"; -import { Document, Page } from "react-pdf"; +import { Document, Page, pdfjs } from "react-pdf"; + +// The worker URL lives with the PDF chunk, not the login bundle (#55). +pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`; import { defaultWidthHeight, generateId, @@ -34,6 +37,19 @@ import WidgetsDragPreview from "./WidgetsDragPreview"; import { useScroll } from "../../context/ScrollPdfContext"; import useWidgetAreaSelection from "../../hook/useWidgetAreaSelection"; +// Keyboard tabbing follows the DOM order, so widgets are rendered in the +// document reading order (top to bottom, then left to right) instead of the +// order in which they were created. +const inReadingOrder = (positions = []) => + [...positions].sort((a, b) => { + const ay = a?.yPosition ?? 0; + const by = b?.yPosition ?? 0; + if (Math.abs(ay - by) > 2) return ay - by; + const ax = a?.xPosition ?? 0; + const bx = b?.xPosition ?? 0; + return ax - bx; + }); + function RenderPdf(props) { const { t } = useTranslation(); const dispatch = useDispatch(); @@ -919,7 +935,7 @@ function RenderPdf(props) { data?.placeHolder?.map((placeData, plKey) => ( <React.Fragment key={`${key}-${plKey}`}> {placeData.pageNumber === pageNum && - placeData.pos.map( + inReadingOrder(placeData.pos).map( (pos, ind) => pos && ( <React.Fragment key={ind}> @@ -999,7 +1015,7 @@ function RenderPdf(props) { data?.placeHolder.map((placeData, index) => ( <React.Fragment key={index}> {placeData.pageNumber === pageNum && - placeData.pos.map((pos) => ( + inReadingOrder(placeData.pos).map((pos) => ( <React.Fragment key={pos.key}> <Placeholder pos={pos} @@ -1070,7 +1086,7 @@ function RenderPdf(props) { return props.xyPosition?.map((data, ind) => ( <React.Fragment key={ind}> {data.pageNumber === pageNum && - data.pos.map( + inReadingOrder(data.pos).map( (pos, id) => pos && ( <Placeholder diff --git a/apps/OpenSign/src/components/pdf/SelectLanguage.jsx b/apps/OpenSign/src/components/pdf/SelectLanguage.jsx index bf223711d1..e44faef334 100644 --- a/apps/OpenSign/src/components/pdf/SelectLanguage.jsx +++ b/apps/OpenSign/src/components/pdf/SelectLanguage.jsx @@ -11,7 +11,9 @@ function SelectLanguage(props) { { value: "it", text: "Italiano" }, //italian { value: "de", text: "Deutsch" }, //german { value: "hi", text: "हिन्दी" }, //hindi - { value: "kr", text: "한국어" } //korean + { value: "kr", text: "한국어" }, //korean + { value: "zh", text: "中文" }, //chinese + { value: "ja", text: "日本語" } //japanese ]; const defaultLanguage = i18next.language || "en"; const [lang, setLang] = useState(defaultLanguage); diff --git a/apps/OpenSign/src/components/pdf/WidgetsValueModal.jsx b/apps/OpenSign/src/components/pdf/WidgetsValueModal.jsx index b320b16678..6f5300d881 100644 --- a/apps/OpenSign/src/components/pdf/WidgetsValueModal.jsx +++ b/apps/OpenSign/src/components/pdf/WidgetsValueModal.jsx @@ -1,7 +1,13 @@ +import { updateLinkedInitials } from "../../utils/linkedFields"; +import { createSaveActions } from "./widgetsValueModalSaveActions"; +import { useModalActions } from "./widgetsValueModalActions"; +import { createFieldActions } from "./widgetsValueModalFieldActions"; +import { createSignatureActions } from "./widgetsValueModalSignatureActions"; +import { createWidgetTypeRenderer } from "./widgetsValueModalRenderer"; +import { useSignatureEffects } from "./widgetsValueModalEffects"; import { forwardRef, useEffect, useMemo, useRef, useState } from "react"; import ModalUi from "../../primitives/ModalUi"; import { useTranslation } from "react-i18next"; -import { removeBackground } from "@imgly/background-removal"; import { changeDateToMomentFormat, checkRegularExpress, @@ -9,59 +15,35 @@ import { getMonth, getYear, months, - onChangeInput, onSaveImage, onSaveSign, radioButtonWidget, - selectCheckbox, - textInputWidget, cellsWidget, + drawWidget, + textInputWidget, textWidget, years, - convertTextToImg, convertJpegToPng, convertBase64ToFile, generatePdfName, getDefaultDate, getDefaultFormat, getBase64MimeType, - drawWidget, - getBase64FromUrl, - clearResponse, + onChangeInput, isEmptyValue } from "../../constant/Utils"; -import DatePicker from "react-datepicker"; -import "react-datepicker/dist/react-datepicker.css"; import moment from "moment"; import { - setSaveSignCheckbox, - setDefaultSignImg, setIsShowModal, - setMyInitial, - setLastIndex, setScrollTriggerId, setPrefillImg, setPrefillImgLoad, setSignatureRes, - setTypedSignFont, - setMyStamp } from "../../redux/reducers/widgetSlice"; import { useDispatch, useSelector } from "react-redux"; import Loader from "../../primitives/Loader"; -import { emailRegex } from "../../constant/const"; -import RegexParser from "regex-parser"; import { - saveToMySign, - getInitials, - isValidBase64 } from "../../utils"; -import Draw from "./tab/Draw"; -import DefaultSignature from "./tab/DefaultSignature"; -import UploadImage from "./tab/UploadImage"; -import TypeSignature from "./tab/TypeSignature"; -import PenColorComponent from "./tab/PenColorComponent"; -import TextInput from "./widgets/TextInput"; -import CellsInput from "./widgets/CellsInput"; const fontOptions = [ { value: "Fasthand" }, @@ -72,7 +54,6 @@ const fontOptions = [ ]; const textInputcls = "op-input op-input-bordered op-input-sm focus:outline-none text-base-content hover:border-base-content w-full text-xs"; -const isTabCls = "bg-[#002864] text-white rounded-[15px] px-[10px] py-[4px]"; function WidgetsValueModal(props) { const dispatch = useDispatch(); @@ -294,1728 +275,79 @@ function WidgetsValueModal(props) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [signatureTypes]); //function for image upload or update - const onImageChange = async (event) => { - if (event.target.files && event.target.files[0]) { - const file = event.target.files[0]; - setOriginalImage(null); // Reset original image when a new file is selected - setRemoveBgEnabled(false); // Optionally reset toggle - // Ensure compressedFileSize calls setImage, which then triggers the useEffect for BG removal. - compressedFileSize(file, setImage); - } - }; - const handleSavePrefillImg = async (drawImg) => { - setIsLoader(true); - - try { - dispatch( - setPrefillImg({ - id: currWidgetsDetails?.key, - base64: drawImg || image?.src - }) - ); - const imageName = generatePdfName(16); - - const imgType = image?.imgType || getBase64MimeType(drawImg); - const imageUrl = await convertBase64ToFile( - imageName, - drawImg || image.src, - imgType - ); - setIsLoader(false); - if (imageUrl) { - return imageUrl; - } - } catch (e) { - console.log("error in handleSavePrefillImg function ", e); - } - }; - //function is used to save image,stamp widgets data - const handleSaveImage = async (signatureType) => { - const widgetsType = currWidgetsDetails?.type; - let imgUrl; - const isPrefill = xyPosition.some( - (x) => x.Id === uniqueId && x?.Role === "prefill" - ); - if (isPrefill) { - dispatch(setPrefillImgLoad({ [currWidgetsDetails?.key]: true })); - imgUrl = await handleSavePrefillImg(); - } - const defaultStampImg = - myStamp && (await convertJpegToPng(myStamp, "mystamp")); // default signature set through my signature tab - const defaultStampType = myStamp && getBase64MimeType(myStamp); - //check condition signyour-self or other flow - if (uniqueId) { - setXyPosition((prev) => - prev.map((signer) => { - if (signer.Id !== uniqueId) return signer; - - // Find the placeholder index for the page containing the current widget - const index = signer.placeHolder.findIndex((x) => - x.pos?.some((p) => p.key === currWidgetsDetails?.key) - ); - // Get updated placeholder list - const updatedPlaceholders = onSaveImage( - signatureType, - signer.placeHolder, - index, - currWidgetsDetails?.key, - image, - isAutoSign, - widgetsType, - isPrefill && imgUrl, - defaultStampImg, - defaultStampType - ); - - return { - ...signer, - placeHolder: updatedPlaceholders - }; - }) - ); - dispatch(setPrefillImgLoad({})); - - if ( - ["image", "myStamp", "uploadStamp"].includes(isTab) && - ["signature", "initials", "stamp"].includes(currWidgetsDetails?.type) - ) { - if (defaultStampImg || image?.src) { - dispatch( - setSignatureRes({ - tab: isTab, - value: isTab === "myStamp" ? defaultStampImg : image?.src, - imageType: - isTab === "myStamp" ? defaultStampType : image?.imgType, - type: currWidgetsDetails?.type - }) - ); - } - } - } else { - const index = props?.xyPosition?.findIndex( - (p) => p.pageNumber === (currWidgetsDetails?.pageNumber || pageNumber) - ); - const getImage = onSaveImage( - signatureType, - props?.xyPosition, - index, - currWidgetsDetails?.key, - image, - false, - widgetsType, - null, - defaultStampImg, - defaultStampType - ); - setXyPosition(getImage); - } - setIsAutoSign(false); - }; - - //function is used to save draw type or initial type signature - const handleSaveSignature = async ( - signType, - isDefaultSign, - width, - height, - typedSignature - ) => { - // get current click widget type - const widgetsType = currWidgetsDetails?.type; - // if there are any width and height then it will typed signature - const isTypeText = width && height ? true : false; - // final getting signature url via default select sign/default initial sign/self draw sign - const signUrl = isDefaultSign - ? isDefaultSign === "myinitials" && myInitial - ? await convertJpegToPng(myInitial, "myinitials") - : await convertJpegToPng(defaultSignImg, "mysign") - : signature; - isDefaultSign - ? isDefaultSign === "initials" - ? myInitial && (await convertJpegToPng(myInitial, "myinitials")) // default initials set through my signature tab - : await convertJpegToPng(defaultSignImg, "mysign") // default signature set through my signature tab - : signature; // signature done by user thorugh draw, upload, typed - let signatureImg = signUrl; - let imgWH = { width: width ? width : "", height: height ? height : "" }; - setIsImageSelect(false); - setImage(); - if (uniqueId) { - const isPrefill = xyPosition.some( - (x) => x.Id === uniqueId && x?.Role === "prefill" - ); - if (isPrefill) { - dispatch(setPrefillImgLoad({ [currWidgetsDetails?.key]: true })); - signatureImg = await handleSavePrefillImg(signatureImg); - } - setXyPosition((prevState) => - prevState.map((signer) => { - if (signer.Id !== uniqueId) return signer; - - const placeholderIndex = signer.placeHolder.findIndex((x) => - x.pos?.some((p) => p.key === currWidgetsDetails?.key) - ); - const updatedPlaceholders = onSaveSign( - signType, - signer.placeHolder, - placeholderIndex, - currWidgetsDetails?.key, - signatureImg, - imgWH, - isTypeText, - typedSignature, - isAutoSign, - widgetsType, - fontSelect, - penColor - ); - return { - ...signer, - placeHolder: updatedPlaceholders - }; - }) - ); - dispatch(setPrefillImgLoad({})); - if ( - ["signature", "initials"].includes(currWidgetsDetails?.type) && - (typedSignature || signatureImg) - ) { - dispatch( - setSignatureRes({ - tab: isTab, - value: isTab === "type" ? typedSignature : signatureImg, - type: currWidgetsDetails?.type, - ...(isTab === "type" && fontSelect && { font: fontSelect }) - }) - ); - } - } else { - const index = props?.xyPosition?.findIndex( - (p) => p.pageNumber === (currWidgetsDetails?.pageNumber || pageNumber) - ); - const getUpdatePosition = onSaveSign( - signType, - props?.xyPosition, - index, - currWidgetsDetails?.key, - signatureImg, - imgWH, - isTypeText, - typedSignature, - false, - widgetsType, - fontSelect, - penColor - ); - setXyPosition(getUpdatePosition); - } - setIsAutoSign(false); - }; - - //function to handle allowed tab in signature pad - function handleTab() { - if (["signature", "initials"].includes(currWidgetsDetails.type)) { - const signtypes = signatureTypes || []; - const defaultIndex = signtypes?.findIndex( - (x) => - x.name === "default" && - x.enabled === true && - defaultSignImg && - currWidgetsDetails?.type !== "image" && - currWidgetsDetails?.type !== "stamp" - ); - const getIndex = - defaultIndex !== -1 // Check if the default index exists - ? defaultIndex // If found, use it - : signtypes?.findIndex((x) => x.enabled === true); - - if (getIndex !== -1) { - setIsSignTypes(true); - const tab = signatureTypes?.[getIndex].name; - const previousWidgetRes = signatureResponse.find( - (item) => item.type === currWidgetsDetails?.type - ); - if ( - previousWidgetRes?.tab && - previousWidgetRes?.type === currWidgetsDetails?.type - ) { - setIsTab(previousWidgetRes?.tab || "draw"); - } else if (currWidgetsDetails?.signatureType) { - setIsTab(currWidgetsDetails?.signatureType); - } else if (tab === "draw") { - setIsTab("draw"); - } else if (tab === "upload") { - setIsImageSelect(true); - setIsTab("image"); - } else if (tab === "typed") { - setIsTab("type"); - } else if (tab === "default") { - if (currWidgetsDetails?.type !== "initials" && defaultSignImg) { - setIsTab("mysignature"); - } else if (currWidgetsDetails?.type === "initials" && myInitial) { - setIsTab("myinitials"); - } else { - setIsTab("draw"); - } - } - } else { - setIsSignTypes(false); - } - } else if (currWidgetsDetails?.type === "image") { - setIsTab("image"); - } else if (currWidgetsDetails?.type === "stamp") { - const previousWidgetRes = signatureResponse.find( - (item) => item.type === currWidgetsDetails?.type - ); - if (previousWidgetRes?.tab === "uploadStamp") { - setIsTab("uploadStamp"); - } else if (myStamp) { - setIsTab("myStamp"); - } else { - setIsTab("uploadStamp"); - } - } - } - function isTabEnabled(tabName) { - const isEnabled = signatureTypes?.find((x) => x.name === tabName)?.enabled; - return isEnabled; - } - - //function for clear signature image - const handleClear = () => { - if ( - ["signature", "initials", "stamp", "image", drawWidget].includes( - currWidgetsDetails?.type - ) - ) { - if (canvasRef.current) { - canvasRef.current.clear(); - } - setImage(null); - setOriginalImage(null); // Add this - setRemoveBgEnabled(false); // Optionally reset toggle - setSignature(""); - if (isTab === "type") { - setTypedSignature(""); - } - } else { - if (currWidgetsDetails?.type === cellsWidget) { - setWidgetValue(""); - onChangeInput( - "", - currWidgetsDetails, - xyPosition, - props.index, - setXyPosition, - uniqueId - ); - } else { - setSelectedCheckbox([]); - setWidgetValue(""); - setStartDate(""); - onChangeInput( - "", - currWidgetsDetails, - xyPosition, - props.index, - setXyPosition, - uniqueId - ); - } - } - }; - //function for set signature url - const handleSignatureChange = (data) => { - setSignature(data); - }; - // `handleSaveToMySign` is used to save signature, initials, stamp as a default - const handleSaveToMySign = async () => { - if (signature || image?.src) { - setIsLoader(true); - try { - const mySignRes = await saveToMySign({ - type: currWidgetsDetails?.type, - base64: signature || image?.src, - defaultSignId: mysign?.signId - }); - if (mysign?.signId) { - dispatch(setSaveSignCheckbox({ ...mysign, signId: mySignRes?.id })); - } - if (currWidgetsDetails?.type === "signature") { - dispatch(setDefaultSignImg(mySignRes.base64File)); - } else if (currWidgetsDetails?.type === "initials") { - dispatch(setMyInitial(mySignRes.base64File)); - } else if (currWidgetsDetails?.type === "stamp") { - dispatch(setMyStamp(mySignRes.base64File)); - } - alert(t("saved-successfully")); - } catch (error) { - console.log("error while save to my sign", error?.message); - alert(`${error.message}`); - } finally { - setIsLoader(false); - } - } - }; - - const handleSaveBtn = async () => { - // if User checked save signature or save initials checkbox - if (accesstoken && isSavedSign) { - await handleSaveToMySign(); - } - resetToDefault(); - }; - const resetToDefault = () => { - props?.setCurrWidgetsDetails({}); - if ( - isTab !== "image" && - !["stamp", "image"].includes(currWidgetsDetails?.type) - ) { - if (isTab === "myStamp" && myStamp) { - handleSaveImage(); - } else if (isTab === "mysignature") { - setSignature(""); - handleSaveSignature(null, "default"); - } else if (currWidgetsDetails?.type === "initials") { - if (myInitial && isTab === "myinitials") { - handleSaveSignature(isTab, "myinitials"); - } else if (isTab === "type") { - handleSaveSignature( - "type", - false, - textWidth, - textHeight, - typedSignature - ); - } else { - handleSaveSignature(isTab); - } - } else if (isTab === "type") { - setSignature(""); - handleSaveSignature( - "type", - false, - !currWidgetsDetails?.type === "initials" && textWidth > 150 - ? 150 - : textWidth, - !currWidgetsDetails?.type === "initials" && textHeight > 35 - ? 35 - : textHeight, - typedSignature - ); - } else { - setSignature(""); - canvasRef?.current?.clear(); - const tab = isTab; - handleSaveSignature(tab); - } - handlePenColor(); - } else { - setSignature(""); - handleSaveImage("image"); - } - setIsImageSelect(false); - setImage(); - handleTab(); - }; - const autoSignAll = ( - <label className="mb-0 cursor-pointer flex items-center text-sm text-base-content"> - <input - className="mr-2 md:mr-3 op-checkbox op-checkbox-xs md:op-checkbox-sm" - type="checkbox" - value={isAutoSign} - onChange={(e) => { - setIsAutoSign(e.target.checked); - }} - /> - {t("auto-sign-mssg")} - </label> - ); - - useEffect(() => { - const loadFont = async () => { - try { - const selectedFont = typedSignFont || fontSelect; - await document.fonts.load(`20px ${selectedFont}`); - const selectFontStyle = fontOptions.find( - (font) => font.value === selectedFont - ); - setFontSelect(selectFontStyle?.value || fontOptions[0].value); - } catch (error) { - console.error("Error loading font:", error); - } - }; - - loadFont(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [fontSelect]); - useEffect(() => { - handleWidgetsResponse(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isTab]); - - const handleWidgetsResponse = async () => { - //'signatureResponse' is save signature/initials widget response to show on response in signature pad - const previousWidgetRes = signatureResponse.find( - (item) => item.type === currWidgetsDetails?.type - ); - let url = currWidgetsDetails?.options?.response; - if (currWidgetsDetails?.options?.response || previousWidgetRes) { - //draw widget - if (currWidgetsDetails?.type === drawWidget) { - if (canvasRef.current) { - const iBase64 = isValidBase64(url); - if (iBase64) { - canvasRef.current.fromDataURL(url); - } else { - const isAddSuffix = true; - const base64Url = await getBase64FromUrl(url, isAddSuffix); - canvasRef.current.fromDataURL(base64Url); - } - } - } - //signature and initial widgets - if (isSignOrInitials) { - if (isTab === "draw" || isTab === "image") { - if ( - (previousWidgetRes?.tab === "draw" && - currWidgetsDetails?.signatureType !== "draw" && - previousWidgetRes?.type === currWidgetsDetails?.type) || - currWidgetsDetails?.signatureType === "draw" - ) { - url = url || previousWidgetRes?.value; - setSignature(url); - canvasRef.current && canvasRef.current.fromDataURL(url); - return; - } else if ( - previousWidgetRes?.tab === "image" && - previousWidgetRes?.type === currWidgetsDetails?.type - ) { - setImage({ - src: previousWidgetRes?.value, - imgType: previousWidgetRes?.imageType - }); - } - } - if (isTab === "image" && currWidgetsDetails?.ImageType) { - setImage({ imgType: currWidgetsDetails?.ImageType, src: url }); - } - } - //image and stamp widget - if (isImageOrStamp) { - const isPrefill = xyPosition.some( - (x) => x.Id === uniqueId && x?.Role === "prefill" - ); - if (isPrefill) { - const getPrefillImg = prefillImg?.find( - (x) => x.id === currWidgetsDetails?.key - ); - url = getPrefillImg?.base64; - } - if ( - ["myStamp", "uploadStamp"].includes(previousWidgetRes?.tab) && - previousWidgetRes?.type === currWidgetsDetails?.type - ) { - setImage({ - imgType: previousWidgetRes?.ImageType, - src: previousWidgetRes?.value - }); - } else if (isTab === "myStamp") { - setImage(null); - } else if ( - currWidgetsDetails?.options?.response && - currWidgetsDetails?.type === "image" - ) { - setImage({ imgType: currWidgetsDetails?.ImageType, src: url }); - } - } - } - if (isTab === "type") { - const signerName = localStorage.getItem("signer") - ? JSON.parse(localStorage.getItem("signer"))?.Name - : currentUserName; - //trim user name or typed name value to show in initial signature - const trimmedName = typedSignature - ? typedSignature?.trim() - : props?.journey === "kiosk-signing" && kiosk_signer - ? kiosk_signer[0]?.Name?.trim() - : signerName?.trim(); - //get full name of user - const fullUserName = - typedSignature || - (props?.journey === "kiosk-signing" && kiosk_signer - ? kiosk_signer[0]?.Name - : signerName); - const firstCharacter = getInitials(trimmedName); - const userName = - currWidgetsDetails?.type === "initials" ? firstCharacter : fullUserName; - const signatureValue = currWidgetsDetails?.typeSignature; - setTypedSignature(signatureValue || userName || ""); - convertToImg(fontSelect, signatureValue || userName || ""); - } - }; - // function for convert input text value in image - const convertToImg = async (fontStyle, text, color) => { - const maxWidth = currWidgetsDetails?.Width; - const maxHeight = currWidgetsDetails?.Height; - const widgetDims = { Width: maxWidth, Height: maxHeight }; - const fontFamily = fontStyle || typedSignFont || fontSelect || "Fasthand"; - const fillColor = color || penColor; - const dataUrl = convertTextToImg(fontFamily, text, fillColor, widgetDims); - // setSignature(dataUrl); - setTextWidth(maxWidth); - setTextHeight(maxHeight); - dispatch(setTypedSignFont(fontFamily)); - }; - - // Effect to store original image and apply initial BG removal if enabled - useEffect(() => { - if (image?.src && !originalImage && (isImageSelect || isImageOrStamp)) { - // If there's an image, and we haven't stored an original for it yet, - // and we are in a relevant tab/widget type for uploads - setOriginalImage(image); // Store the current image as original - - if (removeBgEnabled) { - setIsLoader(true); - removeBackground(image.src) - .then((blob) => { - const reader = new FileReader(); - reader.onloadend = () => { - // setImage({ src: reader.result, imgType: blob.type }); - }; - reader.onerror = () => { - console.error( - "Error converting blob to data URL after BG removal." - ); - // setImage(image); // Already original if error - }; - reader.readAsDataURL(blob); - }) - .catch((error) => { - console.error("Error removing background:", error); - // setImage(image); // Already original if error - }) - .finally(() => setIsLoader(false)); - } - } - }, [ - image, - originalImage, - removeBgEnabled, - isImageSelect, - currWidgetsDetails?.type, - setIsLoader, - setImage, - setOriginalImage - ]); - - // Effect for toggling BG removal ON/OFF - useEffect(() => { - if (!originalImage?.src || !(isImageSelect || isImageOrStamp)) { - // No original image to process or not in a relevant upload state - return; - } - - if (removeBgEnabled) { - // removeBgEnabled is true - // Only process if current image is the original (BG not yet removed or was reverted) - if (image?.src === originalImage.src) { - setIsLoader(true); - removeBackground(originalImage.src) - .then((blob) => { - const reader = new FileReader(); - reader.onloadend = () => { - setImage({ src: reader.result, imgType: blob.type }); - }; - reader.onerror = () => { - console.error("Error converting blob to data URL for toggle ON."); - setImage(originalImage); // Fallback - }; - reader.readAsDataURL(blob); - }) - .catch((error) => { - console.error("Error removing background for toggle ON:", error); - setImage(originalImage); // Fallback - }) - .finally(() => setIsLoader(false)); - } - } else { - // removeBgEnabled is false, revert to originalImage - if (image?.src !== originalImage.src) { - if (isTab === "myStamp") { - setImage(null); - } else { - setImage(originalImage); - } - } - } - }, [ - removeBgEnabled, - originalImage, - image, - isImageSelect, - currWidgetsDetails?.type, - setImage, - setIsLoader - ]); - - const savesigncheckbox = ( - <label className="cursor-pointer flex items-center mb-0 text-center text-sm"> - <input - className="mr-2 md:mr-3 op-checkbox op-checkbox-xs md:op-checkbox-sm" - type="checkbox" - checked={isSavedSign} - onChange={(e) => setIsSavedSign(e.target.checked)} - /> - {t("save")} {t(`widgets-name.${currWidgetsDetails?.type}`)} - </label> - ); - //function for set checked and unchecked value of checkbox - const handleCheckboxValue = (isChecked, ind) => { - let updateSelectedCheckbox = [], - checkedList; - updateSelectedCheckbox = selectedCheckbox ? [...selectedCheckbox] : []; - - //if user select any option then add selected option - if (isChecked) { - updateSelectedCheckbox.push(ind); - setSelectedCheckbox(updateSelectedCheckbox); - } else { - //else user unselect any option then remove that option - checkedList = selectedCheckbox?.filter((data) => data !== ind); - setSelectedCheckbox([...checkedList]); - } - onChangeInput( - checkedList ? checkedList : updateSelectedCheckbox, - currWidgetsDetails, - xyPosition, - props.index, - setXyPosition, - uniqueId, - false - ); - }; - - const handleRadioCheck = (data) => { - return widgetValue === data; - }; - - //function to handle select radio widget and set value seletced by user - const handleCheckRadio = (data) => { - setWidgetValue(data); - onChangeInput( - data, - currWidgetsDetails, - xyPosition, - props.index, - setXyPosition, - uniqueId, - false - ); - }; - const ExampleCustomInput = forwardRef(({ value, onClick }, ref) => ( - <div - style={{ - fontFamily: "Arial, sans-serif" - }} - // className={`${selectWidgetCls} overflow-hidden`} - onClick={onClick} - ref={ref} - > - {value ? value : "Select date"} - <i className="fa-light fa-calendar ml-[5px]"></i> - </div> - )); - ExampleCustomInput.displayName = "ExampleCustomInput"; - //function to set onchange date - const handleOnDateChange = (date) => { - setWidgetValue(date); - setStartDate(date); - }; - - const getDropdownText = (value) => { - if (Array.isArray(value)) return value.map(getDropdownText).join(", "); - if (value && typeof value === "object" && value.name != null) { - return String(value.name); - } - return value == null ? "" : String(value); - }; - - const handleOnchangeTextBox = (e) => { - // hide any prior validation error while typing - setIsShowValidation(false); - let value = - currWidgetsDetails?.type === "dropdown" - ? e.target?.value?.trim() - : e.target.value; - setWidgetValue(value); - props.setCurrWidgetsDetails?.((prev) => - prev && prev.key === currWidgetsDetails?.key - ? { ...prev, options: { ...prev.options, response: value } } - : prev - ); - onChangeInput( - value, - currWidgetsDetails, - xyPosition, - props.index, - setXyPosition, - uniqueId - ); - }; - - const updateCells = (updated) => { - setWidgetValue(updated); - props.setCurrWidgetsDetails?.((prev) => - prev && prev.key === currWidgetsDetails?.key - ? { ...prev, options: { ...prev.options, response: updated } } - : prev - ); - onChangeInput( - updated, - currWidgetsDetails, - xyPosition, - props.index, - setXyPosition, - uniqueId - ); - }; - const handleCellsInput = (e) => { - const value = e.target.value; - setIsShowValidation(false); - updateCells(value); - }; - //function is used to show widgets on modal according to selected widget type checkbox/date/radio/drodown/textbox/signature/image - const getWidgetType = (type) => { - const isStampOrImage = - currWidgetsDetails?.type === "stamp" || - currWidgetsDetails?.type === "image"; - - const myStampImg = { - src: myStamp - }; - const Tabs = [ - //My signature tab - { - id: "mysignature", - label: t("my-signature"), - onClick: () => setIsTab("mysignature"), - show: - currWidgetsDetails?.type === "signature" && - defaultSignImg && - isTabEnabled("default"), - render: () => ( - <> - <DefaultSignature - defaultSignImg={defaultSignImg} - currWidgetsDetails={currWidgetsDetails} - /> - {uniqueId && ( - <div className="flex justify-center my-2">{autoSignAll}</div> - )} - </> - ) - }, - //My initials tab - { - id: "myinitials", - label: t("my-initials"), - onClick: () => setIsTab("myinitials"), - show: - currWidgetsDetails?.type === "initials" && - myInitial && - isTabEnabled("default"), - render: () => ( - <> - <DefaultSignature - defaultSignImg={myInitial} - currWidgetsDetails={currWidgetsDetails} - /> - {uniqueId && ( - <div className="flex justify-center my-2">{autoSignAll}</div> - )} - </> - ) - }, - //Draw tab - { - id: "draw", - label: t("draw"), - show: isTabEnabled("draw") && !isStampOrImage, - onClick: () => setIsTab("draw"), - render: () => ( - <> - <Draw - penColor={penColor} - canvasRef={canvasRef} - currWidgetsDetails={currWidgetsDetails} - handleSignatureChange={handleSignatureChange} - /> - <div className="flex flex-row justify-between mt-[10px]"> - <PenColorComponent - providedColors={penColors} - penColor={penColor} - convertToImg={convertToImg} - fontSelect={fontSelect} - typedSignature={typedSignature} - setPenColor={setPenColor} - /> - </div> - <div className="flex flex-row ml-1 mt-1 gap-x-3 text-base-content"> - {/* Standalone autoSignAll for "Draw" tab if conditions met */} - {/* 'uniqueId' represents the current user */} - {uniqueId && ( - <div className="flex justify-start my-1">{autoSignAll}</div> - )} - {accesstoken && ( - <div className="flex justify-start my-1"> - {mysign?.isVisible && savesigncheckbox} - </div> - )} - </div> - </> - ) - }, - //Upload Image tab - { - id: "image", - label: t("upload-image"), - onClick: () => { - setIsTab("image"); - setIsImageSelect(true); - }, - show: - (isTabEnabled("upload") && currWidgetsDetails?.type !== "stamp") || - currWidgetsDetails?.type === "image", - render: () => ( - <> - <UploadImage - currWidgetsDetails={currWidgetsDetails} - image={image} - onImageChange={onImageChange} - isImageSelect={isImageSelect} - isStampOrImage={isStampOrImage} - /> - {/* 'uniqueId' represents the current user */} - {/* 'image' checks whether an image is available */} - {/* 'isImageSelect' indicates if the user selected the upload-image option for the signature pad */} - {/* 'isImageOrStamp' determines whether the item is an image or a stamp */} - {(uniqueId || (image && (isImageSelect || isImageOrStamp))) && ( - <div className="flex flex-wrap flex-row sm:justify-center items-center gap-x-3 my-2 text-base-content"> - {uniqueId && autoSignAll} - {image && (isImageSelect || isImageOrStamp) && ( - <label - htmlFor={`removeBgToggleModal-${currWidgetsDetails?.key}`} - className="mb-0 cursor-pointer flex items-center text-sm" - > - <input - type="checkbox" - id={`removeBgToggleModal-${currWidgetsDetails?.key}`} // Unique ID - className="mr-2 op-checkbox op-checkbox-xs md:op-checkbox-sm" - checked={removeBgEnabled} - onChange={() => setRemoveBgEnabled(!removeBgEnabled)} - /> - {t("remove-background")} - </label> - )} - {accesstoken && isSignOrInitials && ( - <div className="flex justify-start my-1"> - {mysign?.isVisible && savesigncheckbox} - </div> - )} - </div> - )} - </> - ) - }, - //Typed signature tab - { - id: "type", - label: t("type"), - onClick: () => { - setIsTab("type"); - if (previousWidgetRes?.tab !== "type") { - setTypedSignature(""); - } - }, - show: isTabEnabled("typed") && !isStampOrImage, - render: () => ( - <> - <TypeSignature - currWidgetsDetails={currWidgetsDetails} - fontSelect={fontSelect} - penColor={penColor} - typedSignature={typedSignature} - setTypedSignature={setTypedSignature} - convertToImg={convertToImg} - fontOptions={fontOptions} - setFontSelect={setFontSelect} - /> - <div className="flex flex-row justify-between mt-[10px]"> - <PenColorComponent - providedColors={penColors} - penColor={penColor} - convertToImg={convertToImg} - fontSelect={fontSelect} - typedSignature={typedSignature} - setPenColor={setPenColor} - /> - </div> - <div className="flex flex-row ml-1 mt-2 gap-x-3 text-base-content"> - {/* Standalone autoSignAll for "Type" tab if conditions met */} - {uniqueId && ( - <div className="flex justify-start my-1">{autoSignAll}</div> - )} - {accesstoken && ( - <div className="flex justify-start my-1"> - {mysign?.isVisible && savesigncheckbox} - </div> - )} - </div> - </> - ) - }, - //Mystamp tab - { - id: "myStamp", - label: "My stamp", - onClick: () => setIsTab("myStamp"), - show: currWidgetsDetails?.type === "stamp" && myStamp, - render: () => ( - <UploadImage - currWidgetsDetails={currWidgetsDetails} - image={myStampImg} - onImageChange={onImageChange} - isImageSelect={isImageSelect} - isStampOrImage={isStampOrImage} - /> - ) - }, - // Upload Stamp Tab - { - id: "uploadStamp", - label: "Upload stamp", - onClick: () => setIsTab("uploadStamp"), - show: currWidgetsDetails?.type === "stamp", - render: () => ( - <> - <UploadImage - currWidgetsDetails={currWidgetsDetails} - image={image} - onImageChange={onImageChange} - isImageSelect={isImageSelect} - isStampOrImage={isStampOrImage} - /> - {/* 'uniqueId' represents the current user */} - {(uniqueId || image) && ( - <div className="flex flex-wrap flex-row sm:justify-center items-center gap-x-3 my-2 text-base-content"> - {uniqueId && autoSignAll} - {image && ( - <label - htmlFor={`removeBgToggleModal-${currWidgetsDetails?.key}`} - className="mb-0 cursor-pointer flex items-center text-sm" - > - <input - type="checkbox" - id={`removeBgToggleModal-${currWidgetsDetails?.key}`} // Unique ID - className="mr-2 op-checkbox op-checkbox-xs md:op-checkbox-sm" - checked={removeBgEnabled} - onChange={() => setRemoveBgEnabled(!removeBgEnabled)} - /> - {t("remove-background")} - </label> - )} - {accesstoken && ( - <div className="flex justify-start my-1"> - {mysign?.isVisible && savesigncheckbox} - </div> - )} - </div> - )} - </> - ) - } - ]; - - switch (type) { - case "image": - case "initials": - case "stamp": - case "signature": - return ( - <div className="flex flex-col"> - {isLoader && ( - <div className="absolute w-full h-full inset-0 flex justify-center items-center bg-base-content/30 z-50"> - <Loader /> - </div> - )} - {isSignTypes ? ( - <> - <div className="text-base-content rounded-[4px] tabWidth"> - {/* Render All Tabs */} - <div className="ml-3 flex justify-start gap-4 text-[11px] md:text-base my-[3px]"> - {Tabs.filter((tab) => tab.show).map((tab) => ( - <div key={tab.id}> - <span - className={`${isTab === tab.id && isTabCls} ml-[2px] cursor-pointer`} - onClick={tab.onClick} - > - {tab.label} - </span> - </div> - ))} - </div> - </div> - <div className="h-full mt-3"> - {Tabs.find((t) => t.id === isTab)?.render()} - </div> - </> - ) : ( - <div className="mx-3 mb-6 mt-3"> - <p>{t("at-least-one-signature-type")}</p> - </div> - )} - </div> - ); - case "checkbox": - const checkBoxLayout = - currWidgetsDetails?.options?.layout || "vertical"; - const isMultipleCheckbox = - currWidgetsDetails?.options?.values?.length > 0 ? true : false; - const checkBoxWrapperClass = `flex items-start ${ - checkBoxLayout === "horizontal" - ? `flex-row flex-wrap ${isMultipleCheckbox ? "gap-x-2" : ""}` - : `flex-col ${isMultipleCheckbox ? "gap-y-[5px]" : ""}` - }`; // Using gap-y-1 for consistency, adjust if needed - - return ( - <div - className={`border-[1px] border-gray-300 rounded-[2px] pt-1 px-2.5 ${checkBoxWrapperClass}`} - > - {currWidgetsDetails?.options?.values?.map((data, ind) => ( - <div key={ind} className="text-base-content select-none-cls"> - <label - // htmlFor={`checkbox-${currWidgetsDetails?.key + ind}`} - className="text-xs flex items-center gap-1 cursor-pointer" - > - <input - id={`checkbox-${currWidgetsDetails?.key + ind}`} - className={`${ - ind === 0 ? "mt-0" : "mt-[5px]" - } op-checkbox op-checkbox-xs rounded-[1px] mt-1`} - type="checkbox" - checked={!!selectCheckbox(ind, selectedCheckbox)} - onChange={(e) => { - if (e.target.checked) { - const maxRequired = - currWidgetsDetails?.options?.validation - ?.maxRequiredCount; - const maxCountInt = - maxRequired && parseInt(maxRequired); - if (maxCountInt > 0) { - if ( - selectedCheckbox && - selectedCheckbox?.length <= maxCountInt - 1 - ) { - handleCheckboxValue(e.target.checked, ind); - } - } else { - handleCheckboxValue(e.target.checked, ind); - } - } else { - handleCheckboxValue(e.target.checked, ind); - } - }} - /> - {data} - </label> - </div> - ))} - </div> - ); - case textInputWidget: - return ( - <TextInput - widgetRef={widgetRef} - widgetValue={widgetValue} - handleOnchangeTextBox={handleOnchangeTextBox} - textInputcls={textInputcls} - currWidgetsDetails={currWidgetsDetails} - handleInputBlur={handleValidation} - /> - ); - case cellsWidget: - return ( - <CellsInput - ref={widgetRef} - cellsValue={widgetValue} - handleCellsInput={handleCellsInput} - textInputcls={textInputcls} - handleValidation={handleValidation} - hint={hint} - count={currWidgetsDetails?.options?.cellCount || 0} - /> - ); - case "dropdown": - return ( - <select - className="op-select op-select-bordered op-select-sm focus:outline-none hover:border-base-content text-base-content w-full text-xs" - id="myDropdown" - value={getDropdownText(widgetValue).trim()} - onChange={(e) => handleOnchangeTextBox(e)} - > - {/* Default/Title option */} - <option value="" disabled hidden> - {/* {currWidgetsDetails?.options?.name} */} - {t("choose-one")} - </option> - {currWidgetsDetails?.options?.values?.map((data, ind) => ( - <option key={ind} value={getDropdownText(data).trim()}> - {getDropdownText(data).trim()} - </option> - ))} - </select> - ); - case "name": - return ( - <input - ref={widgetRef} - type="text" - placeholder={hint || widgetTypeTranslation} - value={widgetValue} - onBlur={handleValidation} - onChange={(e) => handleOnchangeTextBox(e)} - className={textInputcls} - /> - ); - case "company": - return ( - <input - ref={widgetRef} - placeholder={hint || widgetTypeTranslation} - value={widgetValue} - type="text" - onBlur={handleValidation} - onChange={(e) => handleOnchangeTextBox(e)} - className={textInputcls} - /> - ); - case "job title": - return ( - <input - ref={widgetRef} - type="text" - onBlur={handleValidation} - placeholder={hint || widgetTypeTranslation} - value={widgetValue} - onChange={(e) => handleOnchangeTextBox(e)} - className={textInputcls} - /> - ); - case "date": - return ( - <div className="inline-flex flex-col items-center w-full"> - {/* Input + format group */} - <div className="inline-flex flex-col items-center"> - {/* Date input */} - <div className="border-[1px] opensigncss:border-gray-300 opensigndark:border-base-content text-base-content rounded-[2px] px-3 py-1 inline-flex"> - <DatePicker - renderCustomHeader={({ date, changeYear, changeMonth }) => ( - <div className="flex items-center gap-2 ml-2"> - <select - className="bg-transparent outline-none" - value={months[getMonth(date)]} - onChange={({ target: { value } }) => - changeMonth(months.indexOf(value)) - } - > - {months.map((option) => ( - <option key={option} value={option}> - {option} - </option> - ))} - </select> - <select - className="bg-transparent outline-none" - value={getYear(date)} - onChange={({ target: { value } }) => changeYear(value)} - > - {years.map((option) => ( - <option key={option} value={option}> - {option} - </option> - ))} - </select> - </div> - )} - closeOnScroll - selected={startDate} - onChange={handleOnDateChange} - popperPlacement="top-end" - customInput={<ExampleCustomInput />} - dateFormat={ - selectDate?.format || - currWidgetsDetails?.options?.validation?.format || - "MM/dd/yyyy" - } - portalId="root-portal" - /> - </div> - {/* Format */} - <span className="mt-1 text-gray-300 uppercase"> - {currWidgetsDetails?.options?.validation?.format} - </span> - </div> - {/* hint */} - {hint && ( - <div className="mt-2 flex items-center gap-2 text-sm"> - <span>{hint}</span> - </div> - )} - </div> - ); - case "email": - return ( - <input - ref={widgetRef} - type="email" - onBlur={handleValidation} - placeholder={hint || widgetTypeTranslation} - value={widgetValue} - onChange={(e) => handleOnchangeTextBox(e)} - className={textInputcls} - /> - ); - case radioButtonWidget: - const radioLayout = currWidgetsDetails.options?.layout || "vertical"; - const isOnlyOneBtn = - currWidgetsDetails.options?.values?.length > 0 ? true : false; - const radioWrapperClass = `flex items-start ${ - radioLayout === "horizontal" - ? `flex-row flex-wrap ${isOnlyOneBtn ? "gap-x-2" : ""}` - : `flex-col ${isOnlyOneBtn ? "gap-y-[5px]" : ""}` - }`; // Using gap-y-1 for consistency, adjust if needed - return ( - <div - className={`border-[1px] border-gray-300 rounded-[2px] pt-1 px-2.5 ${radioWrapperClass}`} - > - {currWidgetsDetails?.options?.values.map((data, ind) => { - const label = - typeof data === "string" - ? data - : data && typeof data === "object" && data.name != null - ? String(data.name) - : ""; - return ( - <div key={ind} className="text-base-content select-none-cls"> - <label - // htmlFor={`radio-${currWidgetsDetails?.key + ind}`} - className="cursor-pointer flex items-center text-sm gap-1" - > - <input - id={`radio-${currWidgetsDetails?.key + ind}`} - className={`op-radio op-radio-xs mt-1`} - type="radio" - value={label} - checked={handleRadioCheck(label?.trim())} - onChange={(e) => { - handleCheckRadio(e.target.value?.trim()); - }} - /> - <span>{label}</span> - </label> - </div> - ); - })} - </div> - ); - case textWidget: - return ( - <TextInput - widgetRef={widgetRef} - widgetValue={widgetValue} - handleOnchangeTextBox={handleOnchangeTextBox} - textInputcls={textInputcls} - currWidgetsDetails={currWidgetsDetails} - /> - ); - case drawWidget: - return ( - <div> - <Draw - penColor={penColor} - canvasRef={canvasRef} - currWidgetsDetails={props?.currWidgetsDetails} - handleSignatureChange={handleSignatureChange} - /> - <div className="flex flex-row justify-between mt-[10px]"> - <PenColorComponent - penColor={penColor} - setPenColor={setPenColor} - /> - </div> - </div> - ); - default: - return ( - <input - placeholder={t("widgets-name.text")} - readOnly - className={textInputcls} - /> - ); - } - }; - - //function is used to check current widget is required or optional - const handleCheckOptional = () => { - - const effectiveStatus = - currWidgetsDetails?.options?.status || - "required"; - let isRequired = false; - const isCheckBox = - !currWidgetsDetails.options?.isReadOnly && - currWidgetsDetails.type === "checkbox"; - if (isCheckBox && props?.role !== "prefill") { - //get minimum required count if exist - const minCount = - currWidgetsDetails?.options?.validation?.minRequiredCount; - const parseMin = minCount && parseInt(minCount); - if (parseMin > 0) { - isRequired = true; - } - } else { - isRequired = effectiveStatus === "required"; - } - if (isRequired) { - setIsOptional(false); - } - }; - - //function is used to show how many field left and how many total widget - const HandleRequiredField = () => { - - let widgetsPosition = []; - if (uniqueId) { - const currSignerWidget = xyPosition?.find( - (data) => data?.Id === uniqueId - ); - widgetsPosition = currSignerWidget.placeHolder; - } else { - widgetsPosition = xyPosition; - } - - //generate all nested level in single level - const flatPlaceholder = widgetsPosition?.flatMap((page) => - page.pos - .filter((widget) => { - if (widget.options?.isReadOnly) return false; - return true; - }) - .map((widget) => ({ widget, pageNumber: page.pageNumber })) - ); - let totalWidget = 0; - let alreadyValue = 0; - flatPlaceholder?.forEach(({ widget: field }) => { - const isValueExist = - field.options?.response || field.options?.defaultValue; - totalWidget++; - if (isValueExist) { - alreadyValue++; - } - }); - - const leftRequiredWidget = totalWidget - alreadyValue; - useEffect(() => { - handleCheckOptional(); - if ( - currWidgetsDetails?.key === lastWidget || - flatPlaceholder?.length === 1 - ) { - setIsLastWidget(true); - } - }, []); - return ( - <span className="text-center text-[12px] text-base-content"> - {t("required-mssg", { leftRequiredWidget, totalWidget })} - </span> - ); - }; - //function to validate text widget expression or type - const validateExpression = (regexValidation) => { - if (widgetValue && regexValidation) { - let regexObject = regexValidation; - if (currWidgetsDetails?.options?.validation?.type === "regex") { - regexObject = RegexParser(regexValidation); - } - let isValidate = regexObject.test(widgetValue); - if (!isValidate) { - setIsShowValidation(true); - } - } - }; - //function is used when user enter value in any textbox then check validation - const handleValidation = () => { - const validateType = currWidgetsDetails?.options?.validation?.type; - let regexValidation; - switch (validateType) { - case "email": - regexValidation = emailRegex; - validateExpression(regexValidation); - break; - case "number": - regexValidation = /^[0-9\s]*$/; - validateExpression(regexValidation); - break; - case "ssn": - regexValidation = /^(?!000|666|9\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/; - validateExpression(regexValidation); - break; - default: - // Grab the current pattern (if it exists) - const pattern = currWidgetsDetails?.options?.validation?.pattern; - // Removed `backwordSupportPattern` (/^[a-zA-Z0-9s]+$/) — it blocked spaces and special characters. - const backwordSupportPattern = - pattern && pattern === "/^[a-zA-Z0-9s]+$/" ? "" : pattern; // If it matches exactly '/^[a-zA-Z0-9s]+$/', clear it - regexValidation = backwordSupportPattern || ""; - validateExpression(regexValidation); - break; - } - }; - - // `clearWidgetResponse` is used to clear response of signature, stamp, image, initials, draw widget based on id - const clearWidgetResponse = () => { - const widgetKey = currWidgetsDetails?.key; - const isOptional = - currWidgetsDetails?.options?.status === "optional" || false; - if (widgetKey && isOptional) { - const isPrefill = xyPosition.some( - ({ Id, Role }) => Id === uniqueId && Role === "prefill" - ); - if (isPrefill) dispatch(setPrefillImg({ id: widgetKey, base64: "" })); - - setXyPosition((prev) => - prev.map((signer) => { - if (signer.Id !== uniqueId) return signer; - - const idx = signer?.placeHolder?.findIndex((p) => - p.pos?.some((w) => w.key === widgetKey) - ); - if (idx === -1) return signer; - - return { - ...signer, - placeHolder: clearResponse(widgetKey, signer.placeHolder, idx) - }; - }) - ); - } - }; - - //function too use on click on next/finish button then update modal UI according to current widgets - const handleClickOnNext = async (isFinishDoc) => { - if ( - ["signature", "stamp", "image", "initials", drawWidget].includes( - currWidgetsDetails?.type - ) - ) { - if ( - signature || - image || - myInitial || - defaultSignImg || - myStamp || - typedSignature - ) { - //function to save all type draw or image - handleSaveBtn(); - } else { - clearWidgetResponse(); - } - } - if (isSave) { - handleclose(); - } - //condition when there are no any details left for response and current widget is last widget then - //on click on finish button embed all widget's details on pdf and finish document - if (isFinishDoc) { - setIsFinish(true); - props.setCurrWidgetsDetails(currWidgetsDetails); - } else if (!isSave) { - const widgetsPosition = xyPosition?.find((data) => data.Id === uniqueId); - let nextWidgetDetails = null; - const editableWidgets = (widgetsPosition?.placeHolder ?? []).flatMap( - ({ pos = [], pageNumber }) => - pos - .filter(({ options, key, type }) => { - if ( - options?.isReadOnly - ) - return false; - return true; // ← must be OUTSIDE the ee block - }) - .map((widget) => ({ widget, pageNumber })) - ); - //get current index of widget - const currentIndex = editableWidgets.findIndex( - (item) => item.widget.key === currWidgetsDetails?.key - ); - //get totoal widget length - const totalItems = editableWidgets?.length; - //get last widget index ex- arr=[1,2,3] curr=2, then last will be 1 - const lastIndex = (currentIndex + totalItems - 1) % totalItems; - //set last widget details for iteration ex- arr=[1,2,3] curr=2 last=1 then ite= 2,3,1 on last we will finish document - if (!lastWidget) { - const lastWidgetKey = editableWidgets[lastIndex]?.widget?.key; - dispatch(setLastIndex(lastWidgetKey)); - } - - //get next widgets index number ex- arr=[1,2,3] curr=3 last=2 then next=1 - let index = (currentIndex + 1) % totalItems; - const nextItem = editableWidgets[index]; - if (nextItem && !nextItem.widget.options?.isReadOnly) { - const nextCurrentValue = nextItem.widget; - const nextPageNumber = nextItem.pageNumber; - props.setPageNumber(nextPageNumber); - nextWidgetDetails = nextCurrentValue; - } - - dispatch(setIsShowModal({ [nextWidgetDetails?.key]: true })); - props.setCurrWidgetsDetails({ - ...nextWidgetDetails, - pageNumber: nextItem?.pageNumber - }); - } - - }; - //function is used to disable/enable save button - const handleDisable = () => { - if (!isShowValidation) { - if (isOptional && uniqueId) { - return false; - } else if ( - ["signature", "stamp", "image", "initials", drawWidget].includes( - currWidgetsDetails?.type - ) - ) { - const { type } = currWidgetsDetails || {}; - //conditions based on widget type or active tab - const conditions = { - draw: !signature, // Draw tab requires a drawn signature - image: !image, // Upload tab requires an image - mysignature: !defaultSignImg, // My Signature tab requires a saved/default signature - type: !(typedSignature?.trim()?.length > 0), // Type tab requires non-empty typed signature - myinitials: !myInitial, - myStamp: !myStamp, - uploadStamp: !image - }; - // First check conditions based on widget type - if (type && conditions.hasOwnProperty(type)) { - return conditions[type]; - } - //If type doesn't match, check based on active tab - if (isTab && conditions.hasOwnProperty(isTab)) { - return conditions[isTab]; - } - - return true; // default - } else if ( - currWidgetsDetails?.type === "checkbox" && - selectedCheckbox?.length > 0 - ) { - return false; - } else if (isEmptyValue(widgetValue)) { - return true; - } else { - return false; - } - } else { - return true; - } - }; - const handleclose = () => { - // If validation is shown, clear the response and close the modal - if (isShowValidation) { - handleClear(); - setIsShowValidation(false); - } - dispatch(setIsShowModal({})); - dispatch(setLastIndex("")); - }; - //function is used to execute the finish button functionality - const handleFinish = () => { - props?.finishDocument(); - dispatch(setIsShowModal({})); - }; - - useEffect(() => { - if (!isSave) { - handleFinishButton(); - } - }, [isSave]); - //'handleFinishButton' function is used to show finish button click on any widget if all required widgets have response - const handleFinishButton = () => { - const widgetsPosition = xyPosition?.find((data) => data.Id === uniqueId); - - //using 'flatMap' create all nested array in one level - const editableWidgets = widgetsPosition?.placeHolder?.flatMap((page) => - page.pos - .filter((widget) => { - if (widget.options?.isReadOnly) return false; - return true; // ← outside ee block - }) - .map((widget) => ({ ...widget, pageNumber: page.pageNumber })) - ); - const getcurrentwidget = editableWidgets?.find( - (data) => data?.key === currWidgetsDetails?.key - ); - if (getcurrentwidget?.options?.response) { - props?.setCurrWidgetsDetails(getcurrentwidget); - } - let isResponse = true; - //condition to check all required widgets have response or not then show finish button - for (const data of editableWidgets) { - // Use the dynamic required status (respects require/optional logic actions). - const effectiveStatus = - data.options?.status || - "required"; - if (data?.type === "checkbox") { - const minCount = data.options?.validation?.minRequiredCount; - const parseMin = minCount && parseInt(minCount); - const hasNoResponse = - (!Array.isArray(data?.options?.response) || - data.options.response.length === 0) && - (!Array.isArray(data?.options?.defaultValue) || - data.options.defaultValue.length === 0); - if (parseMin > 0 && hasNoResponse) { - isResponse = false; - break; - } - } else if ( - !data.options.response && - !data?.options?.defaultValue && - effectiveStatus === "required" - ) { - isResponse = false; - break; - } - } - if (isResponse) { - setIsLastWidget(true); - } - }; + const { onImageChange, handleSavePrefillImg, syncSavedInitials, handleSaveImage, handleSaveSignature } = createSaveActions({ + dispatch, setIsLoader, currWidgetsDetails, image, setOriginalImage, + setRemoveBgEnabled, compressedFileSize, generatePdfName, getBase64MimeType, + setPrefillImg, convertBase64ToFile, xyPosition, uniqueId, setPrefillImgLoad, + myStamp, convertJpegToPng, setXyPosition, onSaveImage, isAutoSign, isTab, + setSignatureRes, props, pageNumber, setIsAutoSign, setIsImageSelect, + setImage, myInitial, defaultSignImg, signature, onSaveSign, fontSelect, + penColor, updateLinkedInitials + }); - const formatWidgetName = (widgetName) => { - if (!widgetName) return widgetTypeTranslation; + const signatureActions = createSignatureActions({ + currWidgetsDetails, signatureTypes, defaultSignImg, signatureResponse, + setIsSignTypes, setIsTab, setIsImageSelect, myInitial, myStamp, canvasRef, + setImage, setOriginalImage, setRemoveBgEnabled, setSignature, isTab, + setTypedSignature, setWidgetValue, xyPosition, props, setXyPosition, + uniqueId, setSelectedCheckbox, setStartDate, signature, image, setIsLoader, + mysign, dispatch, t, accesstoken, isSavedSign, handlePenColor, + handleSaveImage, handleSaveSignature, textWidth, textHeight, typedSignature, + setIsAutoSign, isAutoSign + }); + const { + handleTab, isTabEnabled, handleClear, handleSignatureChange, handleSaveToMySign, + handleSaveBtn, resetToDefault, autoSignAll + } = signatureActions; + + const signatureEffects = useSignatureEffects({ + typedSignFont, fontSelect, setFontSelect, fontOptions, currWidgetsDetails, + signatureResponse, canvasRef, isSignOrInitials, isTab, setSignature, setImage, + isImageOrStamp, xyPosition, uniqueId, prefillImg, currentUserName, + kiosk_signer, props, typedSignature, setTypedSignature, setTextWidth, + setTextHeight, dispatch, image, originalImage, isImageSelect, removeBgEnabled, + setOriginalImage, setIsLoader, setRemoveBgEnabled, penColor + }); + const { convertToImg, handleWidgetsResponse } = signatureEffects; + const fieldActions = createFieldActions({ + isSavedSign, setIsSavedSign, t, currWidgetsDetails, selectedCheckbox, + setSelectedCheckbox, xyPosition, props, setXyPosition, uniqueId, widgetValue, + setWidgetValue, setStartDate, setIsShowValidation + }); + const { + savesigncheckbox, handleCheckboxValue, handleRadioCheck, handleCheckRadio, + ExampleCustomInput, handleOnDateChange, getDropdownText, + handleOnchangeTextBox, updateCells, handleCellsInput + } = fieldActions; + const modalActions = useModalActions({ + currWidgetsDetails, props, setIsOptional, uniqueId, xyPosition, lastWidget, + setIsLastWidget, isOptional, t, widgetValue, setIsShowValidation, + isShowValidation, dispatch, setXyPosition, signature, image, myInitial, + defaultSignImg, myStamp, typedSignature, handleSaveBtn, isSave, handleClear, + setIsFinish, setPageNumber: props.setPageNumber, selectedCheckbox, isTab, widgetTypeTranslation + }); + const { + handleCheckOptional, HandleRequiredField, validateExpression, handleValidation, + clearWidgetResponse, handleClickOnNext, handleDisable, handleclose, handleFinish, + handleFinishButton, formatWidgetName + } = modalActions; + const getWidgetType = createWidgetTypeRenderer({ + currWidgetsDetails, myStamp, t, setIsTab, isTabEnabled, defaultSignImg, + uniqueId, autoSignAll, myInitial, penColor, canvasRef, handleSignatureChange, + penColors, convertToImg, fontSelect, typedSignature, setPenColor, mysign, + accesstoken, image, onImageChange, isImageSelect, isImageOrStamp, + removeBgEnabled, setRemoveBgEnabled, previousWidgetRes, setTypedSignature, + fontOptions, setFontSelect, isSignTypes, isLoader, isTab, widgetRef, + selectedCheckbox, handleCheckboxValue, textInputWidget, widgetValue, + handleOnchangeTextBox, textInputcls, handleValidation, cellsWidget, + handleCellsInput, hint, getDropdownText, startDate, months, getMonth, years, + getYear, handleOnDateChange, selectDate, setSelectDate, handleSaveDate, + widgetTypeTranslation, radioButtonWidget, handleRadioCheck, handleCheckRadio, + textWidget, drawWidget, props, savesigncheckbox, setIsImageSelect, + isSignOrInitials, ExampleCustomInput + }); - const parts = widgetName.split("-"); - const [first] = parts; - const lastWord = parts.length > 1 ? `-${parts[parts.length - 1]}` : ""; - return currWidgetsDetails?.type === first - ? `${first}${lastWord}` - : widgetName; - }; return ( <> <ModalUi diff --git a/apps/OpenSign/src/components/pdf/inlineAllowlist.characterization.test.js b/apps/OpenSign/src/components/pdf/inlineAllowlist.characterization.test.js new file mode 100644 index 0000000000..990c85274f --- /dev/null +++ b/apps/OpenSign/src/components/pdf/inlineAllowlist.characterization.test.js @@ -0,0 +1,92 @@ +// @vitest-environment node +// Characterization + spec tests for #60: +// - checkbox, radio and dropdown edit in place (inline allowlist) +// - radio stays interactive under canEditInline and persists through the +// same onChangeInput path the checkbox uses +// - signature, stamp, initials and image stay on the modal +import { describe, it, expect } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const read = (name) => fs.readFileSync(path.join(here, name), "utf8"); + +globalThis.window = globalThis.window || { + innerWidth: 1280, + devicePixelRatio: 1, + RUNTIME_ENV: {}, + localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "vitest" } +}; + +const { onChangeInput } = await import("../../constant/utils/widgetInput.js"); + +// Every `inlineTypes = [...]` block in Placeholder.jsx. +const inlineBlocks = () => { + const src = read("Placeholder.jsx"); + const blocks = [...src.matchAll(/inlineTypes\s*=\s*\[([\s\S]*?)\]/g)].map( + (m) => m[1] + ); + expect(blocks.length, "Placeholder.jsx defines inline allowlists").toBeGreaterThan(0); + return blocks; +}; + +describe("#60 inline allowlist", () => { + it("edits checkbox, radio and dropdown in place", () => { + for (const block of inlineBlocks()) { + expect(block.includes('"checkbox"'), "checkbox is inline").toBe(true); + expect(block.includes('"dropdown"'), "dropdown is inline").toBe(true); + expect( + block.includes("radioButtonWidget"), + "radio button is inline" + ).toBe(true); + } + }); + + it("keeps signature, stamp, initials and image on the modal", () => { + for (const block of inlineBlocks()) { + for (const modal of ['"signature"', '"stamp"', '"initials"', '"image"']) { + expect(block.includes(modal), `${modal} stays modal`).toBe(false); + } + } + }); +}); + +describe("#60 radio mirrors checkbox persistence", () => { + it("radio input persists through persistInlineValue/onChangeInput", () => { + const src = read("PlaceholderTypeRadio.jsx"); + expect(src.includes("persistInlineValue("), "radio calls persist").toBe(true); + expect(src.includes("if (!canEditInline) return;"), "radio gated").toBe(true); + }); + + it("dropdown renders an inline select under canEditInline", () => { + const src = read("PlaceholderTypeFields.jsx"); + expect(src.includes("canEditInline ? ("), "dropdown inline branch").toBe(true); + expect(src.includes("<select"), "dropdown select rendered").toBe(true); + }); + + const radioPos = (key) => ({ + key, + type: "radio button", + options: { values: ["Yes", "No"] } + }); + + // Self-sign path: positions live directly on the page entry. + const persistSelfSign = (value, pos) => { + const xyPosition = [{ pos: [{ ...pos, options: { ...pos.options } }] }]; + let updater; + onChangeInput(value, pos, xyPosition, 0, (u) => (updater = u), "user-1"); + return updater(xyPosition)[0].pos[0].options.response; + }; + + it("stores the picked radio option as the response", () => { + expect(persistSelfSign("Yes", radioPos("r1"))).toBe("Yes"); + }); + + it("stores the checkbox selection through the same path", () => { + const pos = { key: "c1", type: "checkbox", options: { values: ["a", "b"] } }; + expect(persistSelfSign([1], pos)).toEqual([1]); + }); +}); diff --git a/apps/OpenSign/src/components/pdf/prefillWidgetActions.js b/apps/OpenSign/src/components/pdf/prefillWidgetActions.js new file mode 100644 index 0000000000..9760138da5 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/prefillWidgetActions.js @@ -0,0 +1,74 @@ +import { drawWidget } from "../../constant/Utils"; + +/** Build the handler that uploads prefill drawings and returns the updated positions. */ +export function createEmbedPrefill(context) { + const { + props, + handleSavePrefillImg + } = context; + const handleEmbedPrefill = async (item) => { + //checking is there any draw widget response have base64 url then generate that base64 to url and save it + const prefillWidgets = props.xyPosition?.find((x) => x.Role === "prefill"); + let updatedXyPosition = []; + if (prefillWidgets) { + const isDrawWidget = (prefillWidgets.placeHolder ?? []).some((ph) => + (ph?.pos ?? []).some((p) => p?.type === drawWidget) + ); + if (isDrawWidget) { + const getPrefill = props.xyPosition.find((x) => x?.Role === "prefill"); + const getPlaceholder = getPrefill?.placeHolder ?? []; + const updatedData = await Promise.all( + getPlaceholder.map(async (page) => ({ + ...page, + pos: await Promise.all( + page.pos.map(async (item) => { + if (item?.type === drawWidget) { + const widgetResponse = item?.options?.response; + + // Skip if no response + if (!widgetResponse) return item; + + // If already URL, do not re-upload + if ( + typeof widgetResponse === "string" && + widgetResponse.startsWith("http") + ) { + return item; + } + + // Convert THIS widget's base64 → URL + const drawUrl = await handleSavePrefillImg(widgetResponse); + return { + ...item, + options: { + ...item.options, + response: drawUrl + } + }; + } + + return item; + }) + ) + })) + ); + + updatedXyPosition = props.xyPosition.map((obj) => { + if (obj.Role === "prefill") { + return { + ...obj, + placeHolder: updatedData + }; + } + return obj; + }); + + props.setXyPosition(updatedXyPosition); + } + } + + await props.handleCreateDocument(); + }; + //`loadOptions` function to use show all list of signer in dropdown + return handleEmbedPrefill; +} diff --git a/apps/OpenSign/src/components/pdf/prefillWidgetList.js b/apps/OpenSign/src/components/pdf/prefillWidgetList.js new file mode 100644 index 0000000000..049bc11e01 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/prefillWidgetList.js @@ -0,0 +1,44 @@ +/** + * Widgets the owner fills in the prefill modal, de-duplicated by name and + * ordered by page and vertical position. + * @param {object|undefined} prefillData The placeholder entry with Role "prefill". + * @returns {Array<{widget: object, pageNumber: number, yPosition: number}>} Editable widgets. + */ +export const getPrefillWidgets = (prefillData) => { + //functions to used remove duplicate name values across all pages + if (!prefillData) return []; + //This will help us track which name values have already been encountered across all pages. + const uniqueNames = new Set(); + //Filter and flatten placeholder widgets while keeping unique names + const filteredArray = prefillData?.placeHolder?.map((item) => ({ + ...item, + pos: item.pos.filter((curr) => { + if (uniqueNames.has(curr?.options?.name)) return false; //Duplicate name found, remove it + uniqueNames.add(curr?.options?.name); //First time seen, add to set + return true; + }) + })); + // Flatten the filtered array, exclude read-only widgets, + // carry yPosition for sorting, then sort by pageNumber asc → yPosition asc + // (mirrors the newSignPos.sort in PdfRequestFiles so widgets appear in + // the same top-to-bottom, page-1-first order as they do in the document) + const flatArray = filteredArray + ?.flatMap((page) => + page.pos + // Every editable widget is shown, answered or not: this list renders + // the prefill form, it is not a "next field" walker (#83). + .filter((widget) => !widget.options?.isReadOnly) + .map((widget) => ({ + widget, + pageNumber: page.pageNumber, + yPosition: widget.yPosition ?? 0 + })) + ) + ?.sort((a, b) => + a.pageNumber !== b.pageNumber + ? a.pageNumber - b.pageNumber // primary: page order (page 1 first) + : a.yPosition - b.yPosition // secondary: top-to-bottom within page + ); + + return flatArray || []; +}; diff --git a/apps/OpenSign/src/components/pdf/prefillWidgetParts.jsx b/apps/OpenSign/src/components/pdf/prefillWidgetParts.jsx new file mode 100644 index 0000000000..3140675104 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/prefillWidgetParts.jsx @@ -0,0 +1,89 @@ +import { useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useSelector } from "react-redux"; +import { isBase64 } from "../../constant/Utils"; + +export const widgetTitle = "font-medium"; +export const widgetLabelCss = (isRequired = false) => { + return `${isRequired ? "after:content-['_*'] after:text-red-500" : ""} block text-xs font-semibold`; +}; +export const ShowTextWidget = ({ position, handleWidgetDetails }) => { + const inputRef = useRef(null); + const [inputValue, setInputValue] = useState(position.options.response || ""); + + return ( + <input + ref={inputRef} + rows={1} + value={inputValue} + onChange={(e) => { + setInputValue(e.target.value); + handleWidgetDetails(position, e.target.value); + }} + className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full text-xs" + /> + ); +}; +export const ImageComponent = (props) => { + const { t } = useTranslation(); + const prefillImg = useSelector((state) => state.widget.prefillImg); + const imageRefs = useRef({}); + + let imgUrl = ""; + const isBase64Url = isBase64(props?.position?.SignUrl); + if (isBase64Url) { + imgUrl = props?.position?.SignUrl; + } else { + const getPrefillImg = prefillImg?.find( + (x) => x.id === props?.position?.key + ); + imgUrl = getPrefillImg?.base64; + } + + return ( + <> + <span + className={`${widgetLabelCss(props?.position?.options?.status === "required")} ${widgetTitle}`} + > + {props?.position.options?.name} + </span> + {imgUrl ? ( + <> + <div className="cursor-pointer op-card border-[1px] border-gray-400 flex flex-col w-full h-full justify-center items-center "> + <img + alt="print img" + ref={(el) => (imageRefs.current[props?.id] = el)} // Assign ref dynamicallys + src={imgUrl} + draggable="false" + className="object-contain h-full w-full aspect-[5/2]" + onLoad={() => props?.handleImageLoaded?.(props?.position.key)} + onError={() => props?.handleImageLoaded?.(props?.position.key)} + /> + </div> + <span + onClick={() => props?.handleClearImage(props?.position)} + className="flex justify-start text-blue-500 underline cursor-pointer" + > + {t("clear")} + </span> + </> + ) : ( + <div + className="cursor-pointer op-card border-[1px] op-border-hover flex flex-col overflow-hidden w-full h-full aspect-[5/2] justify-center items-center" + onClick={() => imageRefs.current[props?.id]?.click()} + > + <input + type="file" + onChange={(e) => props?.onImageChange?.(e, props?.position)} + className="filetype" + accept="image/png,image/jpeg" + ref={(el) => (imageRefs.current[props?.id] = el)} // Assign ref dynamically + hidden + /> + <i className="fa-light text-base-content fa-cloud-upload-alt text-[25px]"></i> + <div className="text-[10px] text-base-content">{t("upload")}</div> + </div> + )} + </> + ); +}; diff --git a/apps/OpenSign/src/components/pdf/prefillWidgetRenderer.jsx b/apps/OpenSign/src/components/pdf/prefillWidgetRenderer.jsx new file mode 100644 index 0000000000..bccc1ab1c3 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/prefillWidgetRenderer.jsx @@ -0,0 +1,334 @@ +import { forwardRef } from "react"; +import DatePicker from "react-datepicker"; +import "react-datepicker/dist/react-datepicker.css"; +import moment from "moment"; +import { UI_FONT } from "../../constant/fonts"; +import { + changeDateToMomentFormat, + drawWidget, + getMonth, + getYear, + months, + radioButtonWidget, + textWidget +} from "../../constant/Utils"; +import * as utils from "../../utils"; +import Draw from "./tab/Draw"; +import PenColorComponent from "./tab/PenColorComponent"; +import { + ImageComponent, + ShowTextWidget, + widgetLabelCss, + widgetTitle +} from "./prefillWidgetParts"; + +/** Build the renderer of one prefill widget for the prefill modal. */ +export function createPrefillWidgetRenderer(context) { + const { + t, + penColor, + setPenColor, + years, + prefillImg, + selectCheckbox, + handleCheckboxValue, + handleRadioCheck, + handleWidgetDetails, + handleClearImage, + handleImageLoaded, + onImageChange, + handleSignatureChange, + getCanvasRef, + clearCanvasById + } = context; + const ExampleCustomInput = forwardRef(({ value, onClick }, ref) => ( + <div + style={{ fontFamily: UI_FONT }} + className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full" + onClick={onClick} + ref={ref} + > + {value} + <i className="fa-light fa-calendar ml-[5px]"></i> + </div> + )); + ExampleCustomInput.displayName = "ExampleCustomInput"; + + const handleDate = (position) => { + // The getDatePickerDate function retrieves the date in the correct format supported by the DatePicker. + const getDate = utils.getDatePickerDate( + position?.options.response, + position?.options?.validation?.format + ); + return getDate; + }; + //function to set date with required date format onchange date + const handleOnDateChange = (date, position) => { + const format = position?.options?.validation?.format || "MM/dd/yyyy"; + let updateDate = date; + let newDate; + const isSpecialDateFormat = + format && ["dd-MM-yyyy", "dd.MM.yyyy", "dd/MM/yyyy"].includes(format); + if (isSpecialDateFormat) { + newDate = moment(updateDate).format(changeDateToMomentFormat(format)); + } else { + //using moment package is used to change date as per the format provided in selectDate obj e.g. - MM/dd/yyyy -> 03/12/2024 + newDate = new Date(updateDate); + newDate = moment(newDate.getTime()).format( + changeDateToMomentFormat(format) + ); + } + handleWidgetDetails(position, newDate); + }; + + const handleWidgetType = (position, id) => { + switch (position?.type) { + case "checkbox": + return ( + <> + <span + className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} + > + {position.options?.name} + </span> + <div className="flex flex-col gap-y-1"> + {position.options?.values?.map((data, ind) => ( + <div + key={ind} + className="select-none-cls flex items-center text-center gap-0.5" + > + <input + id={`modal-checkbox-${position.key + ind}`} + className="mt-[2px] op-checkbox op-checkbox-xs" + type="checkbox" + checked={selectCheckbox(ind, position)} + onChange={(e) => + handleCheckboxValue(e.target.checked, ind, position) + } + /> + <label + htmlFor={`modal-checkbox-${position.key + ind}`} + className="text-xs mb-0 text-center ml-[3px] cursor-pointer" + > + {data} + </label> + </div> + ))} + </div> + </> + ); + case textWidget: + return ( + <> + <span + className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} + > + {position.options?.name} + </span> + <ShowTextWidget + position={position} + handleWidgetDetails={handleWidgetDetails} + /> + </> + ); + case "dropdown": { + if (position?.options?.isMultiSelect) { + const optionLabel = (value) => + value == null + ? "" + : typeof value === "object" + ? String(value.name ?? value.value ?? "") + : String(value); + const optionsList = (position?.options?.values || []) + .map(optionLabel) + .filter((value) => value !== ""); + const currentValues = Array.isArray(position?.options?.response) + ? position.options.response.map(optionLabel) + : position?.options?.response + ? [optionLabel(position.options.response)] + : []; + const persist = (next) => handleWidgetDetails(position, next); + return ( + <div className="flex flex-col gap-1 max-h-40 overflow-auto border border-base-300 rounded p-2"> + {optionsList.length === 0 ? ( + <div className="text-xs text-base-content/60">{t("no-options")}</div> + ) : ( + optionsList.map((data, ind) => ( + <label key={ind} className="flex items-center gap-2 text-xs text-base-content cursor-pointer"> + <input + type="checkbox" + className="op-checkbox op-checkbox-xs rounded-[1px]" + checked={currentValues.includes(data)} + onChange={(e) => { + const next = e.target.checked + ? [...currentValues, data] + : currentValues.filter((v) => v !== data); + persist(next); + }} + /> + <span>{data}</span> + </label> + )) + )} + </div> + ); + } + return ( + <select + className="op-select op-select-bordered op-select-sm focus:outline-none hover:border-base-content text-base-content w-full text-xs" + id="myDropdown" + value={position?.options?.response || ""} + onChange={(e) => handleWidgetDetails(position, e.target.value)} + > + <option value="" disabled hidden> + {t("choose-one")} + </option> + {position?.options?.values?.map((data, ind) => ( + <option key={ind} value={data?.trim()}> + {data?.trim()} + </option> + ))} + </select> + ); + } + + case "date": + return ( + <> + <span + className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} + > + {position.options?.name} + </span> + <DatePicker + portalId="datepicker-portal-root" + renderCustomHeader={({ date, changeYear, changeMonth }) => ( + <div className="flex justify-start ml-2"> + <select + className="bg-transparent outline-none" + value={months[getMonth(date)]} + onChange={({ target: { value } }) => + changeMonth(months.indexOf(value)) + } + > + {months.map((option) => ( + <option key={option} value={option}> + {option} + </option> + ))} + </select> + <select + className="bg-transparent outline-none" + value={getYear(date)} + onChange={({ target: { value } }) => changeYear(value)} + > + {years.map((option) => ( + <option key={option} value={option}> + {option} + </option> + ))} + </select> + </div> + )} + closeOnScroll={true} + selected={handleDate(position)} + onChange={(date) => handleOnDateChange(date, position)} + customInput={<ExampleCustomInput />} + dateFormat={position?.options?.validation?.format || "MM/dd/yyyy"} + /> + </> + ); + case "image": + return ( + <ImageComponent + position={position} + onImageChange={onImageChange} + handleImageLoaded={handleImageLoaded} + handleClearImage={handleClearImage} + id={id} + /> + ); + case radioButtonWidget: + return ( + <> + <span + className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} + > + {position.options?.name} + </span> + <div className="flex flex-col gap-y-1"> + {position.options?.values.map((data, ind) => ( + <div + key={ind} + className="select-none-cls flex items-center text-center gap-0.5" + > + <input + id={`modal-radio-${position.key + ind}`} + className="mt-[2px] op-radio op-radio-xs" + type="radio" + checked={handleRadioCheck(data, position)} + onChange={() => handleWidgetDetails(position, data)} + /> + <label + htmlFor={`modal-radio-${position.key + ind}`} + className="text-xs mb-0 ml-[2px] cursor-pointer" + > + {data} + </label> + </div> + ))} + </div> + </> + ); + case drawWidget: + return ( + <div> + <span + className={`${widgetLabelCss(position?.options?.status === "required")} ${widgetTitle}`} + > + {position.options?.name} + </span> + <Draw + key={position.key + "_" + (prefillImg?.length || 0)} + penColor={penColor} + canvasRef={getCanvasRef(position.key)} + currWidgetsDetails={position} + handleSignatureChange={handleSignatureChange} + prefillCls={"prefillCanvas"} + /> + <div className="flex flex-row justify-between mt-[10px]"> + <PenColorComponent + penColor={penColor} + setPenColor={setPenColor} + /> + <span + onClick={() => { + clearCanvasById(position?.key); + handleClearImage(position); + }} + className="flex justify-start text-blue-500 underline cursor-pointer" + > + {t("clear")} + </span> + </div> + </div> + ); + default: + return position?.SignUrl ? ( + <div className="pointer-events-none"> + <img + alt="image" + draggable="false" + src={position?.SignUrl} + className="w-full h-full" + /> + </div> + ) : ( + <div className="op-input op-input-bordered op-input-sm focus:outline-none hover:border-base-content w-full"> + No widget + </div> + ); + } + }; + return handleWidgetType; +} diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalActions.jsx b/apps/OpenSign/src/components/pdf/widgetsValueModalActions.jsx new file mode 100644 index 0000000000..569e30d219 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalActions.jsx @@ -0,0 +1,340 @@ +import { useEffect } from "react"; +import RegexParser from "regex-parser"; +import { emailRegex } from "../../constant/const"; +import { + clearResponse, drawWidget, isEmptyValue, nextPendingWidget +} from "../../constant/Utils"; +import { setIsShowModal, setLastIndex, setPrefillImg } from "../../redux/reducers/widgetSlice"; + +/** Build the required-field, validation, and signer navigation callbacks. */ +export function useModalActions(context) { + const { + currWidgetsDetails, props, setIsOptional, uniqueId, xyPosition, lastWidget, + setIsLastWidget, isOptional, t, widgetValue, setIsShowValidation, + isShowValidation, dispatch, setXyPosition, signature, image, + myInitial, defaultSignImg, myStamp, typedSignature, handleSaveBtn, + isSave, setIsFinish, setPageNumber, handleClear, selectedCheckbox, isTab, + widgetTypeTranslation + } = context; + //function is used to check current widget is required or optional + const handleCheckOptional = () => { + + const effectiveStatus = + currWidgetsDetails?.options?.status || + "required"; + let isRequired = false; + const isCheckBox = + !currWidgetsDetails.options?.isReadOnly && + currWidgetsDetails.type === "checkbox"; + if (isCheckBox && props?.role !== "prefill") { + //get minimum required count if exist + const minCount = + currWidgetsDetails?.options?.validation?.minRequiredCount; + const parseMin = minCount && parseInt(minCount); + if (parseMin > 0) { + isRequired = true; + } + } else { + isRequired = effectiveStatus === "required"; + } + if (isRequired) { + setIsOptional(false); + } + }; + + //function is used to show how many field left and how many total widget + const HandleRequiredField = () => { + + let widgetsPosition = []; + if (uniqueId) { + const currSignerWidget = xyPosition?.find( + (data) => data?.Id === uniqueId + ); + widgetsPosition = currSignerWidget.placeHolder; + } else { + widgetsPosition = xyPosition; + } + + //generate all nested level in single level + const flatPlaceholder = widgetsPosition?.flatMap((page) => + page.pos + .filter((widget) => { + if (widget.options?.isReadOnly) return false; + return true; + }) + .map((widget) => ({ widget, pageNumber: page.pageNumber })) + ); + let totalWidget = 0; + let alreadyValue = 0; + flatPlaceholder?.forEach(({ widget: field }) => { + const isValueExist = + field.options?.response || field.options?.defaultValue; + totalWidget++; + if (isValueExist) { + alreadyValue++; + } + }); + + const leftRequiredWidget = totalWidget - alreadyValue; + useEffect(() => { + handleCheckOptional(); + if ( + currWidgetsDetails?.key === lastWidget || + flatPlaceholder?.length === 1 + ) { + setIsLastWidget(true); + } + }, []); + return ( + <span className="text-center text-[12px] text-base-content"> + {t("required-mssg", { leftRequiredWidget, totalWidget })} + </span> + ); + }; + //function to validate text widget expression or type + const validateExpression = (regexValidation) => { + if (widgetValue && regexValidation) { + let regexObject = regexValidation; + if (currWidgetsDetails?.options?.validation?.type === "regex") { + regexObject = RegexParser(regexValidation); + } + let isValidate = regexObject.test(widgetValue); + if (!isValidate) { + setIsShowValidation(true); + } + } + }; + //function is used when user enter value in any textbox then check validation + const handleValidation = () => { + const validateType = currWidgetsDetails?.options?.validation?.type; + let regexValidation; + switch (validateType) { + case "email": + regexValidation = emailRegex; + validateExpression(regexValidation); + break; + case "number": + regexValidation = /^[0-9\s]*$/; + validateExpression(regexValidation); + break; + case "ssn": + regexValidation = /^(?!000|666|9\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/; + validateExpression(regexValidation); + break; + default: + // Grab the current pattern (if it exists) + const pattern = currWidgetsDetails?.options?.validation?.pattern; + // Removed `backwordSupportPattern` (/^[a-zA-Z0-9s]+$/) — it blocked spaces and special characters. + const backwordSupportPattern = + pattern && pattern === "/^[a-zA-Z0-9s]+$/" ? "" : pattern; // If it matches exactly '/^[a-zA-Z0-9s]+$/', clear it + regexValidation = backwordSupportPattern || ""; + validateExpression(regexValidation); + break; + } + }; + + // `clearWidgetResponse` is used to clear response of signature, stamp, image, initials, draw widget based on id + const clearWidgetResponse = () => { + const widgetKey = currWidgetsDetails?.key; + const isOptional = + currWidgetsDetails?.options?.status === "optional" || false; + if (widgetKey && isOptional) { + const isPrefill = xyPosition.some( + ({ Id, Role }) => Id === uniqueId && Role === "prefill" + ); + if (isPrefill) dispatch(setPrefillImg({ id: widgetKey, base64: "" })); + + setXyPosition((prev) => + prev.map((signer) => { + if (signer.Id !== uniqueId) return signer; + + const idx = signer?.placeHolder?.findIndex((p) => + p.pos?.some((w) => w.key === widgetKey) + ); + if (idx === -1) return signer; + + return { + ...signer, + placeHolder: clearResponse(widgetKey, signer.placeHolder, idx) + }; + }) + ); + } + }; + + //function too use on click on next/finish button then update modal UI according to current widgets + const handleClickOnNext = async (isFinishDoc) => { + if ( + ["signature", "stamp", "image", "initials", drawWidget].includes( + currWidgetsDetails?.type + ) + ) { + if ( + signature || + image || + myInitial || + defaultSignImg || + myStamp || + typedSignature + ) { + //function to save all type draw or image + handleSaveBtn(); + } else { + clearWidgetResponse(); + } + } + if (isSave) { + handleclose(); + } + //condition when there are no any details left for response and current widget is last widget then + //on click on finish button embed all widget's details on pdf and finish document + if (isFinishDoc) { + setIsFinish(true); + props.setCurrWidgetsDetails(currWidgetsDetails); + } else if (!isSave) { + const widgetsPosition = xyPosition?.find((data) => data.Id === uniqueId); + const nextItem = nextPendingWidget(widgetsPosition?.placeHolder, currWidgetsDetails?.key); + if (nextItem) { + props.setPageNumber(nextItem.pageNumber); + dispatch(setIsShowModal({ [nextItem.widget.key]: true })); + props.setCurrWidgetsDetails({ ...nextItem.widget, pageNumber: nextItem.pageNumber }); + } else { + handleclose(); + } + } + + }; + //function is used to disable/enable save button + const handleDisable = () => { + if (!isShowValidation) { + if (isOptional && uniqueId) { + return false; + } else if ( + ["signature", "stamp", "image", "initials", drawWidget].includes( + currWidgetsDetails?.type + ) + ) { + const { type } = currWidgetsDetails || {}; + //conditions based on widget type or active tab + const conditions = { + draw: !signature, // Draw tab requires a drawn signature + image: !image, // Upload tab requires an image + mysignature: !defaultSignImg, // My Signature tab requires a saved/default signature + type: !(typedSignature?.trim()?.length > 0), // Type tab requires non-empty typed signature + myinitials: !myInitial, + myStamp: !myStamp, + uploadStamp: !image + }; + // First check conditions based on widget type + if (type && conditions.hasOwnProperty(type)) { + return conditions[type]; + } + //If type doesn't match, check based on active tab + if (isTab && conditions.hasOwnProperty(isTab)) { + return conditions[isTab]; + } + + return true; // default + } else if ( + currWidgetsDetails?.type === "checkbox" && + selectedCheckbox?.length > 0 + ) { + return false; + } else if (isEmptyValue(widgetValue)) { + return true; + } else { + return false; + } + } else { + return true; + } + }; + const handleclose = () => { + // If validation is shown, clear the response and close the modal + if (isShowValidation) { + handleClear(); + setIsShowValidation(false); + } + dispatch(setIsShowModal({})); + dispatch(setLastIndex("")); + }; + //function is used to execute the finish button functionality + const handleFinish = () => { + props?.finishDocument(); + dispatch(setIsShowModal({})); + }; + + useEffect(() => { + if (!isSave) { + handleFinishButton(); + } + }, [isSave]); + //'handleFinishButton' function is used to show finish button click on any widget if all required widgets have response + const handleFinishButton = () => { + const widgetsPosition = xyPosition?.find((data) => data.Id === uniqueId); + + //using 'flatMap' create all nested array in one level + const editableWidgets = widgetsPosition?.placeHolder?.flatMap((page) => + page.pos + .filter((widget) => { + if (widget.options?.isReadOnly) return false; + return true; // ← outside ee block + }) + .map((widget) => ({ ...widget, pageNumber: page.pageNumber })) + ); + const getcurrentwidget = editableWidgets?.find( + (data) => data?.key === currWidgetsDetails?.key + ); + if (getcurrentwidget?.options?.response) { + props?.setCurrWidgetsDetails(getcurrentwidget); + } + let isResponse = true; + //condition to check all required widgets have response or not then show finish button + for (const data of editableWidgets) { + // Use the dynamic required status (respects require/optional logic actions). + const effectiveStatus = + data.options?.status || + "required"; + if (data?.type === "checkbox") { + const minCount = data.options?.validation?.minRequiredCount; + const parseMin = minCount && parseInt(minCount); + const hasNoResponse = + (!Array.isArray(data?.options?.response) || + data.options.response.length === 0) && + (!Array.isArray(data?.options?.defaultValue) || + data.options.defaultValue.length === 0); + if (parseMin > 0 && hasNoResponse) { + isResponse = false; + break; + } + } else if ( + !data.options.response && + !data?.options?.defaultValue && + effectiveStatus === "required" + ) { + isResponse = false; + break; + } + } + if (isResponse) { + setIsLastWidget(true); + } + }; + + const formatWidgetName = (widgetName) => { + if (!widgetName) return widgetTypeTranslation; + + const parts = widgetName.split("-"); + const [first] = parts; + const lastWord = parts.length > 1 ? `-${parts[parts.length - 1]}` : ""; + + return currWidgetsDetails?.type === first + ? `${first}${lastWord}` + : widgetName; + }; + return { + handleCheckOptional, HandleRequiredField, validateExpression, handleValidation, + clearWidgetResponse, handleClickOnNext, handleDisable, handleclose, handleFinish, + handleFinishButton, formatWidgetName + }; +} diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalEffects.js b/apps/OpenSign/src/components/pdf/widgetsValueModalEffects.js new file mode 100644 index 0000000000..5ed0543b07 --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalEffects.js @@ -0,0 +1,247 @@ +import { useEffect } from "react"; +import { removeBackground } from "@imgly/background-removal"; +import { getBase64FromUrl, convertTextToImg, drawWidget } from "../../constant/Utils"; +import { setTypedSignFont } from "../../redux/reducers/widgetSlice"; +import { getInitials, isValidBase64 } from "../../utils"; + +/** Manage signature previews, font loading, and uploaded image effects. */ +export function useSignatureEffects(context) { + const { + typedSignFont, fontSelect, setFontSelect, fontOptions, handleWidgetsResponse: _unused, + currWidgetsDetails, signatureResponse, canvasRef, isSignOrInitials, isTab, + setSignature, setImage, isImageOrStamp, xyPosition, uniqueId, prefillImg, + previousWidgetRes: _unusedPrevious, currentUserName, kiosk_signer, props, + typedSignature, setTypedSignature, setTextWidth, setTextHeight, dispatch, + image, originalImage, isImageSelect, removeBgEnabled, setOriginalImage, + setIsLoader, setRemoveBgEnabled, penColor + } = context; + useEffect(() => { + const loadFont = async () => { + try { + const selectedFont = typedSignFont || fontSelect; + await document.fonts.load(`20px ${selectedFont}`); + const selectFontStyle = fontOptions.find( + (font) => font.value === selectedFont + ); + setFontSelect(selectFontStyle?.value || fontOptions[0].value); + } catch (error) { + console.error("Error loading font:", error); + } + }; + + loadFont(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [fontSelect]); + useEffect(() => { + handleWidgetsResponse(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isTab]); + + const handleWidgetsResponse = async () => { + //'signatureResponse' is save signature/initials widget response to show on response in signature pad + const previousWidgetRes = signatureResponse.find( + (item) => item.type === currWidgetsDetails?.type + ); + let url = currWidgetsDetails?.options?.response; + if (currWidgetsDetails?.options?.response || previousWidgetRes) { + //draw widget + if (currWidgetsDetails?.type === drawWidget) { + if (canvasRef.current) { + const iBase64 = isValidBase64(url); + if (iBase64) { + canvasRef.current.fromDataURL(url); + } else { + const isAddSuffix = true; + const base64Url = await getBase64FromUrl(url, isAddSuffix); + canvasRef.current.fromDataURL(base64Url); + } + } + } + //signature and initial widgets + if (isSignOrInitials) { + if (isTab === "draw" || isTab === "image") { + if ( + (previousWidgetRes?.tab === "draw" && + currWidgetsDetails?.signatureType !== "draw" && + previousWidgetRes?.type === currWidgetsDetails?.type) || + currWidgetsDetails?.signatureType === "draw" + ) { + url = url || previousWidgetRes?.value; + setSignature(url); + canvasRef.current && canvasRef.current.fromDataURL(url); + return; + } else if ( + previousWidgetRes?.tab === "image" && + previousWidgetRes?.type === currWidgetsDetails?.type + ) { + setImage({ + src: previousWidgetRes?.value, + imgType: previousWidgetRes?.imageType + }); + } + } + if (isTab === "image" && currWidgetsDetails?.ImageType) { + setImage({ imgType: currWidgetsDetails?.ImageType, src: url }); + } + } + //image and stamp widget + if (isImageOrStamp) { + const isPrefill = xyPosition.some( + (x) => x.Id === uniqueId && x?.Role === "prefill" + ); + if (isPrefill) { + const getPrefillImg = prefillImg?.find( + (x) => x.id === currWidgetsDetails?.key + ); + url = getPrefillImg?.base64; + } + if ( + ["myStamp", "uploadStamp"].includes(previousWidgetRes?.tab) && + previousWidgetRes?.type === currWidgetsDetails?.type + ) { + setImage({ + imgType: previousWidgetRes?.ImageType, + src: previousWidgetRes?.value + }); + } else if (isTab === "myStamp") { + setImage(null); + } else if ( + currWidgetsDetails?.options?.response && + currWidgetsDetails?.type === "image" + ) { + setImage({ imgType: currWidgetsDetails?.ImageType, src: url }); + } + } + } + if (isTab === "type") { + const signerName = localStorage.getItem("signer") + ? JSON.parse(localStorage.getItem("signer"))?.Name + : currentUserName; + //trim user name or typed name value to show in initial signature + const trimmedName = typedSignature + ? typedSignature?.trim() + : props?.journey === "kiosk-signing" && kiosk_signer + ? kiosk_signer[0]?.Name?.trim() + : signerName?.trim(); + //get full name of user + const fullUserName = + typedSignature || + (props?.journey === "kiosk-signing" && kiosk_signer + ? kiosk_signer[0]?.Name + : signerName); + const firstCharacter = getInitials(trimmedName); + const userName = + currWidgetsDetails?.type === "initials" ? firstCharacter : fullUserName; + const signatureValue = currWidgetsDetails?.typeSignature; + setTypedSignature(signatureValue || userName || ""); + convertToImg(fontSelect, signatureValue || userName || ""); + } + }; + // function for convert input text value in image + const convertToImg = async (fontStyle, text, color) => { + const maxWidth = currWidgetsDetails?.Width; + const maxHeight = currWidgetsDetails?.Height; + const widgetDims = { Width: maxWidth, Height: maxHeight }; + const fontFamily = fontStyle || typedSignFont || fontSelect || "Fasthand"; + const fillColor = color || penColor; + const dataUrl = convertTextToImg(fontFamily, text, fillColor, widgetDims); + // setSignature(dataUrl); + setTextWidth(maxWidth); + setTextHeight(maxHeight); + dispatch(setTypedSignFont(fontFamily)); + }; + + // Effect to store original image and apply initial BG removal if enabled + useEffect(() => { + if (image?.src && !originalImage && (isImageSelect || isImageOrStamp)) { + // If there's an image, and we haven't stored an original for it yet, + // and we are in a relevant tab/widget type for uploads + setOriginalImage(image); // Store the current image as original + + if (removeBgEnabled) { + setIsLoader(true); + removeBackground(image.src) + .then((blob) => { + const reader = new FileReader(); + reader.onloadend = () => { + // setImage({ src: reader.result, imgType: blob.type }); + }; + reader.onerror = () => { + console.error( + "Error converting blob to data URL after BG removal." + ); + // setImage(image); // Already original if error + }; + reader.readAsDataURL(blob); + }) + .catch((error) => { + console.error("Error removing background:", error); + // setImage(image); // Already original if error + }) + .finally(() => setIsLoader(false)); + } + } + }, [ + image, + originalImage, + removeBgEnabled, + isImageSelect, + currWidgetsDetails?.type, + setIsLoader, + setImage, + setOriginalImage + ]); + + // Effect for toggling BG removal ON/OFF + useEffect(() => { + if (!originalImage?.src || !(isImageSelect || isImageOrStamp)) { + // No original image to process or not in a relevant upload state + return; + } + + if (removeBgEnabled) { + // removeBgEnabled is true + // Only process if current image is the original (BG not yet removed or was reverted) + if (image?.src === originalImage.src) { + setIsLoader(true); + removeBackground(originalImage.src) + .then((blob) => { + const reader = new FileReader(); + reader.onloadend = () => { + setImage({ src: reader.result, imgType: blob.type }); + }; + reader.onerror = () => { + console.error("Error converting blob to data URL for toggle ON."); + setImage(originalImage); // Fallback + }; + reader.readAsDataURL(blob); + }) + .catch((error) => { + console.error("Error removing background for toggle ON:", error); + setImage(originalImage); // Fallback + }) + .finally(() => setIsLoader(false)); + } + } else { + // removeBgEnabled is false, revert to originalImage + if (image?.src !== originalImage.src) { + if (isTab === "myStamp") { + setImage(null); + } else { + setImage(originalImage); + } + } + } + }, [ + removeBgEnabled, + originalImage, + image, + isImageSelect, + currWidgetsDetails?.type, + setImage, + setIsLoader + ]); + + + return { convertToImg, handleWidgetsResponse }; +} diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalFieldActions.jsx b/apps/OpenSign/src/components/pdf/widgetsValueModalFieldActions.jsx new file mode 100644 index 0000000000..9c606bf75e --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalFieldActions.jsx @@ -0,0 +1,143 @@ +import { forwardRef } from "react"; +import { onChangeInput } from "../../constant/Utils"; + +/** Create controlled field callbacks used by the modal renderer. */ +export function createFieldActions(context) { + const { + isSavedSign, setIsSavedSign, t, currWidgetsDetails, selectedCheckbox, + setSelectedCheckbox, xyPosition, props, setXyPosition, uniqueId, widgetValue, + setWidgetValue, setStartDate, setIsShowValidation + } = context; + const savesigncheckbox = ( + <label className="cursor-pointer flex items-center mb-0 text-center text-sm"> + <input + className="mr-2 md:mr-3 op-checkbox op-checkbox-xs md:op-checkbox-sm" + type="checkbox" + checked={isSavedSign} + onChange={(e) => setIsSavedSign(e.target.checked)} + /> + {t("save")} {t(`widgets-name.${currWidgetsDetails?.type}`)} + </label> + ); + //function for set checked and unchecked value of checkbox + const handleCheckboxValue = (isChecked, ind) => { + let updateSelectedCheckbox = [], + checkedList; + updateSelectedCheckbox = selectedCheckbox ? [...selectedCheckbox] : []; + + //if user select any option then add selected option + if (isChecked) { + updateSelectedCheckbox.push(ind); + setSelectedCheckbox(updateSelectedCheckbox); + } else { + //else user unselect any option then remove that option + checkedList = selectedCheckbox?.filter((data) => data !== ind); + setSelectedCheckbox([...checkedList]); + } + onChangeInput( + checkedList ? checkedList : updateSelectedCheckbox, + currWidgetsDetails, + xyPosition, + props.index, + setXyPosition, + uniqueId, + false + ); + }; + + const handleRadioCheck = (data) => { + return widgetValue === data; + }; + + //function to handle select radio widget and set value seletced by user + const handleCheckRadio = (data) => { + setWidgetValue(data); + onChangeInput( + data, + currWidgetsDetails, + xyPosition, + props.index, + setXyPosition, + uniqueId, + false + ); + }; + const ExampleCustomInput = forwardRef(({ value, onClick }, ref) => ( + <div + style={{ + fontFamily: "Arial, sans-serif" + }} + // className={`${selectWidgetCls} overflow-hidden`} + onClick={onClick} + ref={ref} + > + {value ? value : "Select date"} + <i className="fa-light fa-calendar ml-[5px]"></i> + </div> + )); + ExampleCustomInput.displayName = "ExampleCustomInput"; + //function to set onchange date + const handleOnDateChange = (date) => { + setWidgetValue(date); + setStartDate(date); + }; + + const getDropdownText = (value) => { + if (Array.isArray(value)) return value.map(getDropdownText).join(", "); + if (value && typeof value === "object" && value.name != null) { + return String(value.name); + } + return value == null ? "" : String(value); + }; + + const handleOnchangeTextBox = (e) => { + // hide any prior validation error while typing + setIsShowValidation(false); + let value = + currWidgetsDetails?.type === "dropdown" + ? e.target?.value?.trim() + : e.target.value; + setWidgetValue(value); + props.setCurrWidgetsDetails?.((prev) => + prev && prev.key === currWidgetsDetails?.key + ? { ...prev, options: { ...prev.options, response: value } } + : prev + ); + onChangeInput( + value, + currWidgetsDetails, + xyPosition, + props.index, + setXyPosition, + uniqueId + ); + }; + + const updateCells = (updated) => { + setWidgetValue(updated); + props.setCurrWidgetsDetails?.((prev) => + prev && prev.key === currWidgetsDetails?.key + ? { ...prev, options: { ...prev.options, response: updated } } + : prev + ); + onChangeInput( + updated, + currWidgetsDetails, + xyPosition, + props.index, + setXyPosition, + uniqueId + ); + }; + const handleCellsInput = (e) => { + const value = e.target.value; + setIsShowValidation(false); + updateCells(value); + }; + + return { + savesigncheckbox, handleCheckboxValue, handleRadioCheck, handleCheckRadio, + ExampleCustomInput, handleOnDateChange, getDropdownText, + handleOnchangeTextBox, updateCells, handleCellsInput + }; +} diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalRenderer.jsx b/apps/OpenSign/src/components/pdf/widgetsValueModalRenderer.jsx new file mode 100644 index 0000000000..4b97b8dada --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalRenderer.jsx @@ -0,0 +1,382 @@ +import DatePicker from "react-datepicker"; +import "react-datepicker/dist/react-datepicker.css"; +import Loader from "../../primitives/Loader"; +import Draw from "./tab/Draw"; +import PenColorComponent from "./tab/PenColorComponent"; +import TextInput from "./widgets/TextInput"; +import CellsInput from "./widgets/CellsInput"; +import { selectCheckbox } from "../../constant/Utils"; +import { createSignatureTabs } from "./widgetsValueModalSignatureTabs"; + +/** Class names of the active signature tab. */ +const isTabCls = "bg-[#002864] text-white rounded-[15px] px-[10px] py-[4px]"; + +/** Build the modal's widget-specific input renderer. */ +export function createWidgetTypeRenderer(context) { + const { + currWidgetsDetails, myStamp, t, setIsTab, isTabEnabled, defaultSignImg, + uniqueId, autoSignAll, myInitial, penColor, canvasRef, handleSignatureChange, + penColors, convertToImg, fontSelect, typedSignature, setPenColor, mysign, + accesstoken, image, onImageChange, isImageSelect, isImageOrStamp, + removeBgEnabled, setRemoveBgEnabled, previousWidgetRes, setTypedSignature, + fontOptions, setFontSelect, isSignTypes, isLoader, isTab, widgetRef, + selectedCheckbox, handleCheckboxValue, textInputWidget, widgetValue, + handleOnchangeTextBox, textInputcls, handleValidation, cellsWidget, + handleCellsInput, hint, getDropdownText, startDate, months, getMonth, years, + getYear, handleOnDateChange, selectDate, setSelectDate, handleSaveDate, + widgetTypeTranslation, radioButtonWidget, handleRadioCheck, handleCheckRadio, + textWidget, drawWidget, props, ExampleCustomInput + } = context; + const getWidgetType = (type) => { + const isStampOrImage = + currWidgetsDetails?.type === "stamp" || + currWidgetsDetails?.type === "image"; + + const myStampImg = { + src: myStamp + }; + const Tabs = createSignatureTabs({ ...context, isStampOrImage, myStampImg }); + + switch (type) { + case "image": + case "initials": + case "stamp": + case "signature": + return ( + <div className="flex flex-col"> + {isLoader && ( + <div className="absolute w-full h-full inset-0 flex justify-center items-center bg-base-content/30 z-50"> + <Loader /> + </div> + )} + {isSignTypes ? ( + <> + <div className="text-base-content rounded-[4px] tabWidth"> + {/* Render All Tabs */} + <div className="ml-3 flex justify-start gap-4 text-[11px] md:text-base my-[3px]"> + {Tabs.filter((tab) => tab.show).map((tab) => ( + <div key={tab.id}> + <span + className={`${isTab === tab.id && isTabCls} ml-[2px] cursor-pointer`} + onClick={tab.onClick} + > + {tab.label} + </span> + </div> + ))} + </div> + </div> + <div className="h-full mt-3"> + {Tabs.find((t) => t.id === isTab)?.render()} + </div> + </> + ) : ( + <div className="mx-3 mb-6 mt-3"> + <p>{t("at-least-one-signature-type")}</p> + </div> + )} + </div> + ); + case "checkbox": + const checkBoxLayout = + currWidgetsDetails?.options?.layout || "vertical"; + const isMultipleCheckbox = + currWidgetsDetails?.options?.values?.length > 0 ? true : false; + const checkBoxWrapperClass = `flex items-start ${ + checkBoxLayout === "horizontal" + ? `flex-row flex-wrap ${isMultipleCheckbox ? "gap-x-2" : ""}` + : `flex-col ${isMultipleCheckbox ? "gap-y-[5px]" : ""}` + }`; // Using gap-y-1 for consistency, adjust if needed + + return ( + <div + className={`border-[1px] border-gray-300 rounded-[2px] pt-1 px-2.5 ${checkBoxWrapperClass}`} + > + {currWidgetsDetails?.options?.values?.map((data, ind) => ( + <div key={ind} className="text-base-content select-none-cls"> + <label + // htmlFor={`checkbox-${currWidgetsDetails?.key + ind}`} + className="text-xs flex items-center gap-1 cursor-pointer" + > + <input + id={`checkbox-${currWidgetsDetails?.key + ind}`} + className={`${ + ind === 0 ? "mt-0" : "mt-[5px]" + } op-checkbox op-checkbox-xs rounded-[1px] mt-1`} + type="checkbox" + checked={!!selectCheckbox(ind, selectedCheckbox)} + onChange={(e) => { + if (e.target.checked) { + const maxRequired = + currWidgetsDetails?.options?.validation + ?.maxRequiredCount; + const maxCountInt = + maxRequired && parseInt(maxRequired); + if (maxCountInt > 0) { + if ( + selectedCheckbox && + selectedCheckbox?.length <= maxCountInt - 1 + ) { + handleCheckboxValue(e.target.checked, ind); + } + } else { + handleCheckboxValue(e.target.checked, ind); + } + } else { + handleCheckboxValue(e.target.checked, ind); + } + }} + /> + {data} + </label> + </div> + ))} + </div> + ); + case textInputWidget: + return ( + <TextInput + widgetRef={widgetRef} + widgetValue={widgetValue} + handleOnchangeTextBox={handleOnchangeTextBox} + textInputcls={textInputcls} + currWidgetsDetails={currWidgetsDetails} + handleInputBlur={handleValidation} + /> + ); + case cellsWidget: + return ( + <CellsInput + ref={widgetRef} + cellsValue={widgetValue} + handleCellsInput={handleCellsInput} + textInputcls={textInputcls} + handleValidation={handleValidation} + hint={hint} + count={currWidgetsDetails?.options?.cellCount || 0} + /> + ); + case "dropdown": + return ( + <select + className="op-select op-select-bordered op-select-sm focus:outline-none hover:border-base-content text-base-content w-full text-xs" + id="myDropdown" + value={getDropdownText(widgetValue).trim()} + onChange={(e) => handleOnchangeTextBox(e)} + > + {/* Default/Title option */} + <option value="" disabled hidden> + {/* {currWidgetsDetails?.options?.name} */} + {t("choose-one")} + </option> + {currWidgetsDetails?.options?.values?.map((data, ind) => ( + <option key={ind} value={getDropdownText(data).trim()}> + {getDropdownText(data).trim()} + </option> + ))} + </select> + ); + case "name": + return ( + <input + ref={widgetRef} + type="text" + placeholder={hint || widgetTypeTranslation} + value={widgetValue} + onBlur={handleValidation} + onChange={(e) => handleOnchangeTextBox(e)} + className={textInputcls} + /> + ); + case "company": + return ( + <input + ref={widgetRef} + placeholder={hint || widgetTypeTranslation} + value={widgetValue} + type="text" + onBlur={handleValidation} + onChange={(e) => handleOnchangeTextBox(e)} + className={textInputcls} + /> + ); + case "job title": + return ( + <input + ref={widgetRef} + type="text" + onBlur={handleValidation} + placeholder={hint || widgetTypeTranslation} + value={widgetValue} + onChange={(e) => handleOnchangeTextBox(e)} + className={textInputcls} + /> + ); + case "date": + return ( + <div className="inline-flex flex-col items-center w-full"> + {/* Input + format group */} + <div className="inline-flex flex-col items-center"> + {/* Date input */} + <div className="border-[1px] opensigncss:border-gray-300 opensigndark:border-base-content text-base-content rounded-[2px] px-3 py-1 inline-flex"> + <DatePicker + renderCustomHeader={({ date, changeYear, changeMonth }) => ( + <div className="flex items-center gap-2 ml-2"> + <select + className="bg-transparent outline-none" + value={months[getMonth(date)]} + onChange={({ target: { value } }) => + changeMonth(months.indexOf(value)) + } + > + {months.map((option) => ( + <option key={option} value={option}> + {option} + </option> + ))} + </select> + <select + className="bg-transparent outline-none" + value={getYear(date)} + onChange={({ target: { value } }) => changeYear(value)} + > + {years.map((option) => ( + <option key={option} value={option}> + {option} + </option> + ))} + </select> + </div> + )} + closeOnScroll + selected={startDate} + onChange={handleOnDateChange} + popperPlacement="top-end" + popperModifiers={[ + { name: "offset", options: { offset: [0, 6] } }, + { + name: "preventOverflow", + options: { + boundary: "viewport", + rootBoundary: "document", + padding: 12, + altAxis: true + } + }, + { name: "flip", options: { padding: 12 } } + ]} + customInput={<ExampleCustomInput />} + dateFormat={ + selectDate?.format || + currWidgetsDetails?.options?.validation?.format || + "MM/dd/yyyy" + } + /> + </div> + {/* Format */} + <span className="mt-1 text-gray-300 uppercase"> + {currWidgetsDetails?.options?.validation?.format} + </span> + </div> + {/* hint */} + {hint && ( + <div className="mt-2 flex items-center gap-2 text-sm"> + <span>{hint}</span> + </div> + )} + </div> + ); + case "email": + return ( + <input + ref={widgetRef} + type="email" + onBlur={handleValidation} + placeholder={hint || widgetTypeTranslation} + value={widgetValue} + onChange={(e) => handleOnchangeTextBox(e)} + className={textInputcls} + /> + ); + case radioButtonWidget: + const radioLayout = currWidgetsDetails.options?.layout || "vertical"; + const isOnlyOneBtn = + currWidgetsDetails.options?.values?.length > 0 ? true : false; + const radioWrapperClass = `flex items-start ${ + radioLayout === "horizontal" + ? `flex-row flex-wrap ${isOnlyOneBtn ? "gap-x-2" : ""}` + : `flex-col ${isOnlyOneBtn ? "gap-y-[5px]" : ""}` + }`; // Using gap-y-1 for consistency, adjust if needed + return ( + <div + className={`border-[1px] border-gray-300 rounded-[2px] pt-1 px-2.5 ${radioWrapperClass}`} + > + {currWidgetsDetails?.options?.values.map((data, ind) => { + const label = + typeof data === "string" + ? data + : data && typeof data === "object" && data.name != null + ? String(data.name) + : ""; + return ( + <div key={ind} className="text-base-content select-none-cls"> + <label + // htmlFor={`radio-${currWidgetsDetails?.key + ind}`} + className="cursor-pointer flex items-center text-sm gap-1" + > + <input + id={`radio-${currWidgetsDetails?.key + ind}`} + className={`op-radio op-radio-xs mt-1`} + type="radio" + value={label} + checked={handleRadioCheck(label?.trim())} + onChange={(e) => { + handleCheckRadio(e.target.value?.trim()); + }} + /> + <span>{label}</span> + </label> + </div> + ); + })} + </div> + ); + case textWidget: + return ( + <TextInput + widgetRef={widgetRef} + widgetValue={widgetValue} + handleOnchangeTextBox={handleOnchangeTextBox} + textInputcls={textInputcls} + currWidgetsDetails={currWidgetsDetails} + /> + ); + case drawWidget: + return ( + <div> + <Draw + penColor={penColor} + canvasRef={canvasRef} + currWidgetsDetails={props?.currWidgetsDetails} + handleSignatureChange={handleSignatureChange} + /> + <div className="flex flex-row justify-between mt-[10px]"> + <PenColorComponent + penColor={penColor} + setPenColor={setPenColor} + /> + </div> + </div> + ); + default: + return ( + <input + placeholder={t("widgets-name.text")} + readOnly + className={textInputcls} + /> + ); + } + }; + return getWidgetType; +} diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalSaveActions.js b/apps/OpenSign/src/components/pdf/widgetsValueModalSaveActions.js new file mode 100644 index 0000000000..86e3c69feb --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalSaveActions.js @@ -0,0 +1,237 @@ +/** Create image and signature save callbacks for the modal. */ +export const createSaveActions = (context) => { + const { + dispatch, setIsLoader, currWidgetsDetails, image, setOriginalImage, + setRemoveBgEnabled, compressedFileSize, generatePdfName, getBase64MimeType, + setPrefillImg, convertBase64ToFile, xyPosition, uniqueId, setPrefillImgLoad, + myStamp, convertJpegToPng, setXyPosition, onSaveImage, isAutoSign, isTab, + setSignatureRes, props, pageNumber, setIsAutoSign, setIsImageSelect, + setImage, myInitial, defaultSignImg, signature, + onSaveSign, fontSelect, penColor, updateLinkedInitials + } = context; + const onImageChange = async (event) => { + if (event.target.files && event.target.files[0]) { + const file = event.target.files[0]; + setOriginalImage(null); // Reset original image when a new file is selected + setRemoveBgEnabled(false); // Optionally reset toggle + // Ensure compressedFileSize calls setImage, which then triggers the useEffect for BG removal. + compressedFileSize(file, setImage); + } + }; + const handleSavePrefillImg = async (drawImg) => { + setIsLoader(true); + + try { + dispatch( + setPrefillImg({ + id: currWidgetsDetails?.key, + base64: drawImg || image?.src + }) + ); + const imageName = generatePdfName(16); + + const imgType = image?.imgType || getBase64MimeType(drawImg); + const imageUrl = await convertBase64ToFile( + imageName, + drawImg || image.src, + imgType + ); + setIsLoader(false); + if (imageUrl) { + return imageUrl; + } + } catch (e) { + console.log("error in handleSavePrefillImg function ", e); + } + }; + // Synchronize saved initials only within the pages of the current signer. + const syncSavedInitials = (pages) => { + if (currWidgetsDetails?.type !== "initials") return pages; + const source = pages.flatMap((page) => page.pos || []).find((widget) => widget.key === currWidgetsDetails.key); + return updateLinkedInitials(pages, { source }); + }; + + //function is used to save image,stamp widgets data + const handleSaveImage = async (signatureType) => { + const widgetsType = currWidgetsDetails?.type; + let imgUrl; + const isPrefill = xyPosition.some( + (x) => x.Id === uniqueId && x?.Role === "prefill" + ); + if (isPrefill) { + dispatch(setPrefillImgLoad({ [currWidgetsDetails?.key]: true })); + imgUrl = await handleSavePrefillImg(); + } + const defaultStampImg = + myStamp && (await convertJpegToPng(myStamp, "mystamp")); // default signature set through my signature tab + const defaultStampType = myStamp && getBase64MimeType(myStamp); + //check condition signyour-self or other flow + if (uniqueId) { + setXyPosition((prev) => + prev.map((signer) => { + if (signer.Id !== uniqueId) return signer; + + // Find the placeholder index for the page containing the current widget + const index = signer.placeHolder.findIndex((x) => + x.pos?.some((p) => p.key === currWidgetsDetails?.key) + ); + // Get updated placeholder list + const updatedPlaceholders = onSaveImage( + signatureType, + signer.placeHolder, + index, + currWidgetsDetails?.key, + image, + isAutoSign, + widgetsType, + isPrefill && imgUrl, + defaultStampImg, + defaultStampType + ); + + return { + ...signer, + placeHolder: syncSavedInitials(updatedPlaceholders) + }; + }) + ); + dispatch(setPrefillImgLoad({})); + + if ( + ["image", "myStamp", "uploadStamp"].includes(isTab) && + ["signature", "initials", "stamp"].includes(currWidgetsDetails?.type) + ) { + if (defaultStampImg || image?.src) { + dispatch( + setSignatureRes({ + tab: isTab, + value: isTab === "myStamp" ? defaultStampImg : image?.src, + imageType: + isTab === "myStamp" ? defaultStampType : image?.imgType, + type: currWidgetsDetails?.type + }) + ); + } + } + } else { + const index = props?.xyPosition?.findIndex( + (p) => p.pageNumber === (currWidgetsDetails?.pageNumber || pageNumber) + ); + const getImage = onSaveImage( + signatureType, + props?.xyPosition, + index, + currWidgetsDetails?.key, + image, + false, + widgetsType, + null, + defaultStampImg, + defaultStampType + ); + setXyPosition(syncSavedInitials(getImage)); + } + setIsAutoSign(false); + }; + + //function is used to save draw type or initial type signature + const handleSaveSignature = async ( + signType, + isDefaultSign, + width, + height, + typedSignature + ) => { + // get current click widget type + const widgetsType = currWidgetsDetails?.type; + // if there are any width and height then it will typed signature + const isTypeText = width && height ? true : false; + // final getting signature url via default select sign/default initial sign/self draw sign + const signUrl = isDefaultSign + ? isDefaultSign === "myinitials" && myInitial + ? await convertJpegToPng(myInitial, "myinitials") + : await convertJpegToPng(defaultSignImg, "mysign") + : signature; + isDefaultSign + ? isDefaultSign === "initials" + ? myInitial && (await convertJpegToPng(myInitial, "myinitials")) // default initials set through my signature tab + : await convertJpegToPng(defaultSignImg, "mysign") // default signature set through my signature tab + : signature; // signature done by user thorugh draw, upload, typed + let signatureImg = signUrl; + let imgWH = { width: width ? width : "", height: height ? height : "" }; + setIsImageSelect(false); + setImage(); + if (uniqueId) { + const isPrefill = xyPosition.some( + (x) => x.Id === uniqueId && x?.Role === "prefill" + ); + if (isPrefill) { + dispatch(setPrefillImgLoad({ [currWidgetsDetails?.key]: true })); + signatureImg = await handleSavePrefillImg(signatureImg); + } + setXyPosition((prevState) => + prevState.map((signer) => { + if (signer.Id !== uniqueId) return signer; + + const placeholderIndex = signer.placeHolder.findIndex((x) => + x.pos?.some((p) => p.key === currWidgetsDetails?.key) + ); + const updatedPlaceholders = onSaveSign( + signType, + signer.placeHolder, + placeholderIndex, + currWidgetsDetails?.key, + signatureImg, + imgWH, + isTypeText, + typedSignature, + isAutoSign, + widgetsType, + fontSelect, + penColor + ); + return { + ...signer, + placeHolder: syncSavedInitials(updatedPlaceholders) + }; + }) + ); + dispatch(setPrefillImgLoad({})); + if ( + ["signature", "initials"].includes(currWidgetsDetails?.type) && + (typedSignature || signatureImg) + ) { + dispatch( + setSignatureRes({ + tab: isTab, + value: isTab === "type" ? typedSignature : signatureImg, + type: currWidgetsDetails?.type, + ...(isTab === "type" && fontSelect && { font: fontSelect }) + }) + ); + } + } else { + const index = props?.xyPosition?.findIndex( + (p) => p.pageNumber === (currWidgetsDetails?.pageNumber || pageNumber) + ); + const getUpdatePosition = onSaveSign( + signType, + props?.xyPosition, + index, + currWidgetsDetails?.key, + signatureImg, + imgWH, + isTypeText, + typedSignature, + false, + widgetsType, + fontSelect, + penColor + ); + setXyPosition(syncSavedInitials(getUpdatePosition)); + } + setIsAutoSign(false); + }; + + return { onImageChange, handleSavePrefillImg, syncSavedInitials, handleSaveImage, handleSaveSignature }; +}; diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalSignatureActions.jsx b/apps/OpenSign/src/components/pdf/widgetsValueModalSignatureActions.jsx new file mode 100644 index 0000000000..3df6846a0e --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalSignatureActions.jsx @@ -0,0 +1,243 @@ +import { onChangeInput, cellsWidget, drawWidget } from "../../constant/Utils"; +import { saveToMySign } from "../../utils"; +import { + setSaveSignCheckbox, setDefaultSignImg, setMyInitial, setMyStamp +} from "../../redux/reducers/widgetSlice"; + +/** Create signature pad, reset, and save-to-account callbacks. */ +export function createSignatureActions(context) { + const { + currWidgetsDetails, signatureTypes, defaultSignImg, signatureResponse, + setIsSignTypes, setIsTab, setIsImageSelect, myInitial, myStamp, canvasRef, + setImage, setOriginalImage, setRemoveBgEnabled, setSignature, isTab, + setTypedSignature, setWidgetValue, xyPosition, props, setXyPosition, + uniqueId, setSelectedCheckbox, setStartDate, signature, image, setIsLoader, + mysign, dispatch, t, accesstoken, isSavedSign, handlePenColor, + handleSaveImage, handleSaveSignature, textWidth, textHeight, typedSignature, + setIsAutoSign, isAutoSign + } = context; + //function to handle allowed tab in signature pad + function handleTab() { + if (["signature", "initials"].includes(currWidgetsDetails.type)) { + const signtypes = signatureTypes || []; + const defaultIndex = signtypes?.findIndex( + (x) => + x.name === "default" && + x.enabled === true && + defaultSignImg && + currWidgetsDetails?.type !== "image" && + currWidgetsDetails?.type !== "stamp" + ); + const getIndex = + defaultIndex !== -1 // Check if the default index exists + ? defaultIndex // If found, use it + : signtypes?.findIndex((x) => x.enabled === true); + + if (getIndex !== -1) { + setIsSignTypes(true); + const tab = signatureTypes?.[getIndex].name; + const previousWidgetRes = signatureResponse.find( + (item) => item.type === currWidgetsDetails?.type + ); + if ( + previousWidgetRes?.tab && + previousWidgetRes?.type === currWidgetsDetails?.type + ) { + setIsTab(previousWidgetRes?.tab || "draw"); + } else if (currWidgetsDetails?.signatureType) { + setIsTab(currWidgetsDetails?.signatureType); + } else if (tab === "draw") { + setIsTab("draw"); + } else if (tab === "upload") { + setIsImageSelect(true); + setIsTab("image"); + } else if (tab === "typed") { + setIsTab("type"); + } else if (tab === "default") { + if (currWidgetsDetails?.type !== "initials" && defaultSignImg) { + setIsTab("mysignature"); + } else if (currWidgetsDetails?.type === "initials" && myInitial) { + setIsTab("myinitials"); + } else { + setIsTab("draw"); + } + } + } else { + setIsSignTypes(false); + } + } else if (currWidgetsDetails?.type === "image") { + setIsTab("image"); + } else if (currWidgetsDetails?.type === "stamp") { + const previousWidgetRes = signatureResponse.find( + (item) => item.type === currWidgetsDetails?.type + ); + if (previousWidgetRes?.tab === "uploadStamp") { + setIsTab("uploadStamp"); + } else if (myStamp) { + setIsTab("myStamp"); + } else { + setIsTab("uploadStamp"); + } + } + } + function isTabEnabled(tabName) { + const isEnabled = signatureTypes?.find((x) => x.name === tabName)?.enabled; + return isEnabled; + } + + //function for clear signature image + const handleClear = () => { + if ( + ["signature", "initials", "stamp", "image", drawWidget].includes( + currWidgetsDetails?.type + ) + ) { + if (canvasRef.current) { + canvasRef.current.clear(); + } + setImage(null); + setOriginalImage(null); // Add this + setRemoveBgEnabled(false); // Optionally reset toggle + setSignature(""); + if (isTab === "type") { + setTypedSignature(""); + } + } else { + if (currWidgetsDetails?.type === cellsWidget) { + setWidgetValue(""); + onChangeInput( + "", + currWidgetsDetails, + xyPosition, + props.index, + setXyPosition, + uniqueId + ); + } else { + setSelectedCheckbox([]); + setWidgetValue(""); + setStartDate(""); + onChangeInput( + "", + currWidgetsDetails, + xyPosition, + props.index, + setXyPosition, + uniqueId + ); + } + } + }; + //function for set signature url + const handleSignatureChange = (data) => { + setSignature(data); + }; + // `handleSaveToMySign` is used to save signature, initials, stamp as a default + const handleSaveToMySign = async () => { + if (signature || image?.src) { + setIsLoader(true); + try { + const mySignRes = await saveToMySign({ + type: currWidgetsDetails?.type, + base64: signature || image?.src, + defaultSignId: mysign?.signId + }); + if (mysign?.signId) { + dispatch(setSaveSignCheckbox({ ...mysign, signId: mySignRes?.id })); + } + if (currWidgetsDetails?.type === "signature") { + dispatch(setDefaultSignImg(mySignRes.base64File)); + } else if (currWidgetsDetails?.type === "initials") { + dispatch(setMyInitial(mySignRes.base64File)); + } else if (currWidgetsDetails?.type === "stamp") { + dispatch(setMyStamp(mySignRes.base64File)); + } + alert(t("saved-successfully")); + } catch (error) { + console.log("error while save to my sign", error?.message); + alert(`${error.message}`); + } finally { + setIsLoader(false); + } + } + }; + + const handleSaveBtn = async () => { + // if User checked save signature or save initials checkbox + if (accesstoken && isSavedSign) { + await handleSaveToMySign(); + } + resetToDefault(); + }; + const resetToDefault = () => { + props?.setCurrWidgetsDetails({}); + if ( + isTab !== "image" && + !["stamp", "image"].includes(currWidgetsDetails?.type) + ) { + if (isTab === "myStamp" && myStamp) { + handleSaveImage(); + } else if (isTab === "mysignature") { + setSignature(""); + handleSaveSignature(null, "default"); + } else if (currWidgetsDetails?.type === "initials") { + if (myInitial && isTab === "myinitials") { + handleSaveSignature(isTab, "myinitials"); + } else if (isTab === "type") { + handleSaveSignature( + "type", + false, + textWidth, + textHeight, + typedSignature + ); + } else { + handleSaveSignature(isTab); + } + } else if (isTab === "type") { + setSignature(""); + handleSaveSignature( + "type", + false, + !currWidgetsDetails?.type === "initials" && textWidth > 150 + ? 150 + : textWidth, + !currWidgetsDetails?.type === "initials" && textHeight > 35 + ? 35 + : textHeight, + typedSignature + ); + } else { + setSignature(""); + canvasRef?.current?.clear(); + const tab = isTab; + handleSaveSignature(tab); + } + handlePenColor(); + } else { + setSignature(""); + handleSaveImage("image"); + } + setIsImageSelect(false); + setImage(); + handleTab(); + }; + const autoSignAll = ( + <label className="mb-0 cursor-pointer flex items-center text-sm text-base-content"> + <input + className="mr-2 md:mr-3 op-checkbox op-checkbox-xs md:op-checkbox-sm" + type="checkbox" + value={isAutoSign} + onChange={(e) => { + setIsAutoSign(e.target.checked); + }} + /> + {t("auto-sign-mssg")} + </label> + ); + + return { + handleTab, isTabEnabled, handleClear, handleSignatureChange, handleSaveToMySign, + handleSaveBtn, resetToDefault, autoSignAll + }; +} diff --git a/apps/OpenSign/src/components/pdf/widgetsValueModalSignatureTabs.jsx b/apps/OpenSign/src/components/pdf/widgetsValueModalSignatureTabs.jsx new file mode 100644 index 0000000000..52ee6c3f3d --- /dev/null +++ b/apps/OpenSign/src/components/pdf/widgetsValueModalSignatureTabs.jsx @@ -0,0 +1,261 @@ +import Draw from "./tab/Draw"; +import DefaultSignature from "./tab/DefaultSignature"; +import UploadImage from "./tab/UploadImage"; +import TypeSignature from "./tab/TypeSignature"; +import PenColorComponent from "./tab/PenColorComponent"; + +/** Create the signature, initials, image, and stamp tab configuration. */ +export function createSignatureTabs(context) { + const { + t, setIsTab, currWidgetsDetails, defaultSignImg, isTabEnabled, myInitial, + uniqueId, autoSignAll, penColor, canvasRef, handleSignatureChange, penColors, + convertToImg, fontSelect, typedSignature, setPenColor, accesstoken, mysign, + image, onImageChange, isImageSelect, isImageOrStamp, removeBgEnabled, + setRemoveBgEnabled, previousWidgetRes, setTypedSignature, fontOptions, + setFontSelect, myStamp, savesigncheckbox, isStampOrImage, myStampImg, + setIsImageSelect, isSignOrInitials + } = context; + const Tabs = [ + //My signature tab + { + id: "mysignature", + label: t("my-signature"), + onClick: () => setIsTab("mysignature"), + show: + currWidgetsDetails?.type === "signature" && + defaultSignImg && + isTabEnabled("default"), + render: () => ( + <> + <DefaultSignature + defaultSignImg={defaultSignImg} + currWidgetsDetails={currWidgetsDetails} + /> + {uniqueId && ( + <div className="flex justify-center my-2">{autoSignAll}</div> + )} + </> + ) + }, + //My initials tab + { + id: "myinitials", + label: t("my-initials"), + onClick: () => setIsTab("myinitials"), + show: + currWidgetsDetails?.type === "initials" && + myInitial && + isTabEnabled("default"), + render: () => ( + <> + <DefaultSignature + defaultSignImg={myInitial} + currWidgetsDetails={currWidgetsDetails} + /> + {uniqueId && ( + <div className="flex justify-center my-2">{autoSignAll}</div> + )} + </> + ) + }, + //Draw tab + { + id: "draw", + label: t("draw"), + show: isTabEnabled("draw") && !isStampOrImage, + onClick: () => setIsTab("draw"), + render: () => ( + <> + <Draw + penColor={penColor} + canvasRef={canvasRef} + currWidgetsDetails={currWidgetsDetails} + handleSignatureChange={handleSignatureChange} + /> + <div className="flex flex-row justify-between mt-[10px]"> + <PenColorComponent + providedColors={penColors} + penColor={penColor} + convertToImg={convertToImg} + fontSelect={fontSelect} + typedSignature={typedSignature} + setPenColor={setPenColor} + /> + </div> + <div className="flex flex-row ml-1 mt-1 gap-x-3 text-base-content"> + {/* Standalone autoSignAll for "Draw" tab if conditions met */} + {/* 'uniqueId' represents the current user */} + {uniqueId && ( + <div className="flex justify-start my-1">{autoSignAll}</div> + )} + {accesstoken && ( + <div className="flex justify-start my-1"> + {mysign?.isVisible && savesigncheckbox} + </div> + )} + </div> + </> + ) + }, + //Upload Image tab + { + id: "image", + label: t("upload-image"), + onClick: () => { + setIsTab("image"); + setIsImageSelect(true); + }, + show: + (isTabEnabled("upload") && currWidgetsDetails?.type !== "stamp") || + currWidgetsDetails?.type === "image", + render: () => ( + <> + <UploadImage + currWidgetsDetails={currWidgetsDetails} + image={image} + onImageChange={onImageChange} + isImageSelect={isImageSelect} + isStampOrImage={isStampOrImage} + /> + {/* 'uniqueId' represents the current user */} + {/* 'image' checks whether an image is available */} + {/* 'isImageSelect' indicates if the user selected the upload-image option for the signature pad */} + {/* 'isImageOrStamp' determines whether the item is an image or a stamp */} + {(uniqueId || (image && (isImageSelect || isImageOrStamp))) && ( + <div className="flex flex-wrap flex-row sm:justify-center items-center gap-x-3 my-2 text-base-content"> + {uniqueId && autoSignAll} + {image && (isImageSelect || isImageOrStamp) && ( + <label + htmlFor={`removeBgToggleModal-${currWidgetsDetails?.key}`} + className="mb-0 cursor-pointer flex items-center text-sm" + > + <input + type="checkbox" + id={`removeBgToggleModal-${currWidgetsDetails?.key}`} // Unique ID + className="mr-2 op-checkbox op-checkbox-xs md:op-checkbox-sm" + checked={removeBgEnabled} + onChange={() => setRemoveBgEnabled(!removeBgEnabled)} + /> + {t("remove-background")} + </label> + )} + {accesstoken && isSignOrInitials && ( + <div className="flex justify-start my-1"> + {mysign?.isVisible && savesigncheckbox} + </div> + )} + </div> + )} + </> + ) + }, + //Typed signature tab + { + id: "type", + label: t("type"), + onClick: () => { + setIsTab("type"); + if (previousWidgetRes?.tab !== "type") { + setTypedSignature(""); + } + }, + show: isTabEnabled("typed") && !isStampOrImage, + render: () => ( + <> + <TypeSignature + currWidgetsDetails={currWidgetsDetails} + fontSelect={fontSelect} + penColor={penColor} + typedSignature={typedSignature} + setTypedSignature={setTypedSignature} + convertToImg={convertToImg} + fontOptions={fontOptions} + setFontSelect={setFontSelect} + /> + <div className="flex flex-row justify-between mt-[10px]"> + <PenColorComponent + providedColors={penColors} + penColor={penColor} + convertToImg={convertToImg} + fontSelect={fontSelect} + typedSignature={typedSignature} + setPenColor={setPenColor} + /> + </div> + <div className="flex flex-row ml-1 mt-2 gap-x-3 text-base-content"> + {/* Standalone autoSignAll for "Type" tab if conditions met */} + {uniqueId && ( + <div className="flex justify-start my-1">{autoSignAll}</div> + )} + {accesstoken && ( + <div className="flex justify-start my-1"> + {mysign?.isVisible && savesigncheckbox} + </div> + )} + </div> + </> + ) + }, + //Mystamp tab + { + id: "myStamp", + label: "My stamp", + onClick: () => setIsTab("myStamp"), + show: currWidgetsDetails?.type === "stamp" && myStamp, + render: () => ( + <UploadImage + currWidgetsDetails={currWidgetsDetails} + image={myStampImg} + onImageChange={onImageChange} + isImageSelect={isImageSelect} + isStampOrImage={isStampOrImage} + /> + ) + }, + // Upload Stamp Tab + { + id: "uploadStamp", + label: "Upload stamp", + onClick: () => setIsTab("uploadStamp"), + show: currWidgetsDetails?.type === "stamp", + render: () => ( + <> + <UploadImage + currWidgetsDetails={currWidgetsDetails} + image={image} + onImageChange={onImageChange} + isImageSelect={isImageSelect} + isStampOrImage={isStampOrImage} + /> + {/* 'uniqueId' represents the current user */} + {(uniqueId || image) && ( + <div className="flex flex-wrap flex-row sm:justify-center items-center gap-x-3 my-2 text-base-content"> + {uniqueId && autoSignAll} + {image && ( + <label + htmlFor={`removeBgToggleModal-${currWidgetsDetails?.key}`} + className="mb-0 cursor-pointer flex items-center text-sm" + > + <input + type="checkbox" + id={`removeBgToggleModal-${currWidgetsDetails?.key}`} // Unique ID + className="mr-2 op-checkbox op-checkbox-xs md:op-checkbox-sm" + checked={removeBgEnabled} + onChange={() => setRemoveBgEnabled(!removeBgEnabled)} + /> + {t("remove-background")} + </label> + )} + {accesstoken && ( + <div className="flex justify-start my-1"> + {mysign?.isVisible && savesigncheckbox} + </div> + )} + </div> + )} + </> + ) + } + ] + return Tabs; +} \ No newline at end of file diff --git a/apps/OpenSign/src/components/sidebar/Sidebar.jsx b/apps/OpenSign/src/components/sidebar/Sidebar.jsx index f86100036b..e484dec62f 100644 --- a/apps/OpenSign/src/components/sidebar/Sidebar.jsx +++ b/apps/OpenSign/src/components/sidebar/Sidebar.jsx @@ -82,7 +82,7 @@ const Sidebar = () => { return ( <aside className={`os-sidebar os-shell-sidebar absolute inset-y-0 lg:relative overflow-y-auto transition-all z-[500] shadow-lg hide-scrollbar - ${isOpen ? "w-full md:w-64" : "w-0"}`} + ${isOpen ? "w-full md:w-64" : "w-0 overflow-hidden"}`} > <div className="os-sidebar-identity flex px-2 py-3 gap-2 items-center shadow-md"> <button diff --git a/apps/OpenSign/src/constant/Utils.js b/apps/OpenSign/src/constant/Utils.js index 2590aa0f1d..95a83eddb7 100644 --- a/apps/OpenSign/src/constant/Utils.js +++ b/apps/OpenSign/src/constant/Utils.js @@ -1,4981 +1,22 @@ -import axios from "axios"; -import { getErrorMessage, isCreditQuotaError } from "../utils/creditErrors"; -import moment from "moment"; -import { - PDFDocument, - rgb, - degrees, - PDFName, - StandardFonts, - PDFArray, - PDFDict -} from "pdf-lib"; -import Parse from "parse"; -import { appInfo } from "./appinfo"; -import { saveAs } from "file-saver"; -import printModule from "print-js"; -import fontkit from "@pdf-lib/fontkit"; -import { SCALE_STEPS } from "./const"; -import { format, toZonedTime } from "date-fns-tz"; - -import i18n from "../i18n"; -import { persistBrandPresentation } from "./brandPresentation"; -import { getRuntimePdfFontUrl } from "./runtimeConfig"; -import { renderMailBrandLogo, resolveMailBrandPresentation } from "./mailBrand"; -import { - applyNumberFormulasToPages, - buildDownloadFilename, - addPreferenceOpt -} from "../utils"; - -export const fontsizeArr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]; -export const getFontSizeForHeight = (height) => { - const numericHeight = Number(height); - if (!Number.isFinite(numericHeight) || numericHeight <= 0) { - return fontsizeArr[0]; - } - - const fittingSizes = fontsizeArr.filter( - (fontSize) => fontSize * 1.5 <= numericHeight - ); - return fittingSizes[fittingSizes.length - 1] || fontsizeArr[0]; -}; -export const fontColorArr = ["red", "black", "blue", "yellow"]; -export const isMobile = window.innerWidth < 767; -export const isTab = 767 < window.innerWidth < 1023; -export const isHighResolution = window.innerWidth > 1023; -export const isTabAndMobile = window.innerWidth < 1023; -export const textInputWidget = "text input"; -export const drawWidget = "draw"; -export const textWidget = "text"; -export const radioButtonWidget = "radio button"; -export const cellsWidget = "cells"; -const duplicateAutoApplyWidgetTypes = [ - "name", - "company", - "job title", - "email", - textInputWidget -]; -const normalizeDuplicateWidgetType = (type) => { - if (typeof type !== "string") { - return type; - } - const normalizedType = type.trim().toLowerCase(); - // Backward compatibility for legacy payloads. - if (normalizedType === "textbox") { - return textInputWidget; - } - return normalizedType; -}; -const normalizeDuplicateWidgetName = (name) => - typeof name === "string" ? name.trim().toLowerCase() : ""; -const isDuplicateAutoApplyWidget = (widget) => - duplicateAutoApplyWidgetTypes.includes( - normalizeDuplicateWidgetType(widget?.type) - ); -const getDuplicateAutoApplyName = (widget) => { - if (!isDuplicateAutoApplyWidget(widget)) { - return ""; - } - return normalizeDuplicateWidgetName(widget?.options?.name); -}; -const getWidgetResponseValue = (widget) => - widget?.options?.response ?? widget?.options?.defaultValue; -const getDuplicateResponseMap = (widgets = []) => { - const responseByName = new Map(); - widgets.forEach((widget) => { - const widgetName = getDuplicateAutoApplyName(widget); - const response = getWidgetResponseValue(widget); - if ( - widgetName && - response !== undefined && - response !== "" && - !responseByName.has(widgetName) - ) { - responseByName.set(widgetName, response); - } - }); - return responseByName; -}; -const applyDuplicateResponsesToWidgets = ( - widgets = [], - responseByName = getDuplicateResponseMap(widgets) -) => { - if (responseByName.size === 0) { - return widgets; - } - - return widgets.map((widget) => { - const widgetName = getDuplicateAutoApplyName(widget); - if (!widgetName || !responseByName.has(widgetName)) { - return widget; - } - return { - ...widget, - options: { - ...widget.options, - response: responseByName.get(widgetName), - defaultValue: "" - } - }; - }); -}; -const applyDuplicateResponsesToPages = (pages = []) => { - const responseByName = getDuplicateResponseMap( - pages.flatMap((page) => page?.pos || []) - ); - return pages.map((page) => ({ - ...page, - pos: applyDuplicateResponsesToWidgets(page?.pos || [], responseByName) - })); -}; -export function getEnv() { - return window?.RUNTIME_ENV || {}; -} -const appName = resolveMailBrandPresentation("").appName; - -export const defaultMailBody = `<p>Hi {{receiver_name}},</p><br><p>We hope this email finds you well. {{sender_name}} has requested you to review and sign {{document_title}}.</p><p>Your signature is crucial to proceed with the next steps as it signifies your agreement and authorization.</p><br><p><a href='{{signing_url}}' rel='noopener noreferrer' target='_blank'>Sign here</a></p><br><br><p>If you have any questions or need further clarification regarding the document or the signing process, please contact the sender.</p><br><p>Thanks</p><p> Team ${appName}</p><br>`; -export const defaultMailSubject = `{{sender_name}} has requested you to sign {{document_title}}`; -export const nonPresentMaskCss = (base) => ({ - ...base, - width: "0px", - height: "0px" -}); - -export const randomId = (digit = 8) => { - // 1. Grab a cryptographically-secure 32-bit random value - // Use crypto for stronger randomness - const randomBytes = crypto.getRandomValues(new Uint32Array(1)); - const raw = randomBytes[0]; // 0 … 4,294,967,295 - - // Calculate the min and max for the given digit length - const min = Math.pow(10, digit - 1); // e.g., digit=3 → 100 - const max = Math.pow(10, digit) - 1; // e.g., digit=3 → 999 - const range = max - min + 1; - - // Collapse random value into the range and shift - return min + (raw % range); -}; -//function for create list of year for date widget -export const range = (start, end, step) => { - const range = []; - for (let i = start; i <= end; i += step) { - range.push(i); - } - return range; -}; -//function for get year -export const getYear = (date) => { - const newYear = new Date(date).getFullYear(); - return newYear; -}; -export const years = range(1950, getYear(new Date()) + 16, 1); -export const months = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" -]; -export const fileasbytes = async (filepath) => { - const response = await fetch(filepath); // Adjust the path accordingly - const arrayBuffer = await response.arrayBuffer(); - return new Uint8Array(arrayBuffer); -}; - -export const openInNewTab = (url, target) => { - if (target) { - window.open(url, target, "noopener,noreferrer"); - } else { - window.open(url, "_blank", "noopener,noreferrer"); - } -}; - -export const getUserCountry = async () => { - try { - const res = await fetch("https://ipapi.co/json/"); - const data = await res.json(); - return data?.country_code; - } catch (err) { - console.log("Error fetching country", err); - return ""; - } -}; - -// `getSecureUrl` is used to return local secure url if local files -export const getSecureUrl = async (url) => { - const fileUrl = new URL(url)?.pathname?.includes("/files/"); - if (fileUrl) { - try { - const fileRes = await Parse.Cloud.run("fileupload", { url: url }); - if (fileRes.url) { - return { url: fileRes.url }; - } else { - return { url: "" }; - } - } catch (err) { - console.log("err while fileupload ", err); - return { url: "" }; - } - } else { - return { url: url }; - } -}; - -// `generateId` generates a random alphanumeric ID of specified length. -export function generateId(length) { - const characters = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - let result = ""; - const charactersLength = characters.length; - - for (let i = 0; i < length; i++) { - result += characters.charAt(Math.floor(Math.random() * charactersLength)); - } - return result; -} - -/** - * Removes a trailing path segment from a URL string, if present. - * - * @param {string} url - The original URL. - * @param {string} segment - The segment to strip off (default: "app"). - * @returns {string} - The URL with the trailing segment removed, or unmodified if it didn’t match. - */ -export function removeTrailingSegment(url, segment = "app") { - // Normalize a trailing slash (e.g. “/app/” → “/app”) - const normalized = url.endsWith("/") ? url.slice(0, -1) : url; - - const lastSlash = normalized.lastIndexOf("/"); - const lastPart = normalized.slice(lastSlash + 1); - - if (lastPart === segment) { - return normalized.slice(0, lastSlash); - } - - return normalized; -} - -export const color = [ - "#93a3db", - "#e6c3db", - "#c0e3bc", - "#bce3db", - "#b8ccdb", - "#ceb8db", - "#ffccff", - "#99ffcc", - "#cc99ff", - "#ffcc99", - "#66ccff", - "#ffffcc" -]; - -export const nameColor = [ - "#304fbf", - "#7d5270", - "#5f825b", - "#578077", - "#576e80", - "#6d527d", - "#cc00cc", - "#006666", - "#cc00ff", - "#ff9900", - "#336699", - "#cc9900" -]; -export const toDataUrl = (file) => { - return new Promise((resolve) => { - const reader = new FileReader(); - reader.readAsDataURL(file); - reader.onloadend = (e) => { - resolve(e.target.result); - }; - }); -}; - -//function for getting document details for getDrive cloud function -export const getDrive = async (documentId, skip = 0, limit = 50) => { - const data = { - docId: documentId && documentId, - limit: limit, - skip: skip - }; - const driveDeatils = await axios - .post(`${localStorage.getItem("baseUrl")}functions/getDrive`, data, { - headers: { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - sessiontoken: localStorage.getItem("accesstoken") - } - }) - .then((Listdata) => { - const json = Listdata.data; - - if (json && json.result.error) { - return json; - } else if (json && json.result) { - const data = json.result; - return data; - } else { - return []; - } - }) - .catch((err) => { - console.log("Err in getDrive cloud function", err); - return "Error: Something went wrong!"; - }); - - return driveDeatils; -}; - -// `pdfNewWidthFun` function is used to calculate pdf width to render in middle container -export const pdfNewWidthFun = (divRef) => { - const pdfWidth = divRef.current.offsetWidth; - return pdfWidth; -}; - -//`contractUsers` function is used to get contract_User details -export const contractUsers = async () => { - try { - const url = `${localStorage.getItem("baseUrl")}functions/getUserDetails`; - const parseAppId = localStorage.getItem("parseAppId"); - const accesstoken = localStorage.getItem("accesstoken"); - const token = { "X-Parse-Session-Token": accesstoken }; - const headers = { - headers: { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - ...token - } - }; - const userDetails = await axios.post(url, {}, headers); - let data = []; - if (userDetails?.data?.result) { - const json = JSON.parse(JSON.stringify(userDetails.data.result)); - data.push(json); - } - return data; - } catch (err) { - console.log("Err in getUserDetails cloud function", err); - return "Error: Something went wrong!"; - } -}; - -//function for resize image and update width and height for mulitisigners -export const handleWidgetResize = ( - ref, - key, - signerPos, - setSignerPos, - pageNumber, - containerScale, - signerId, - showResize -) => { - // Compute widget dimensions only once - const { offsetWidth, offsetHeight } = ref; - const factor = containerScale || 1; - const widgetWidth = offsetWidth / factor; - const widgetHeight = offsetHeight / factor; - - const filterSignerPos = signerPos.filter((data) => data.Id === signerId); - if (filterSignerPos.length > 0) { - const getPlaceHolder = filterSignerPos[0].placeHolder; - const getPageNumer = getPlaceHolder.filter( - (data) => data.pageNumber === pageNumber - ); - if (getPageNumer.length > 0) { - const getXYdata = getPageNumer[0].pos; - const getPosData = getXYdata; - const addSignPos = getPosData.map((url) => { - if (url.key === key) { - // For rotated widgets (90°/270°), the visual dimensions are swapped. - // Store the original-orientation dimensions in the data model. - const rotation = url.options?.rotation || 0; - const isRotSwapped = [90, 270].includes(rotation); - const storedWidth = isRotSwapped ? widgetHeight : widgetWidth; - const storedHeight = isRotSwapped ? widgetWidth : widgetHeight; - const widgetDims = { Width: storedWidth, Height: storedHeight }; - // Base fields for every resized signature - const base = { - ...url, - Width: storedWidth, - Height: storedHeight, - IsResize: showResize ? true : false - }; - // If it's a “type” signature, regenerate the image and options - if (url.typeSignature && url.signatureType === "type") { - const signImg = convertTextToImg( - url.typeFont ?? "Fasthand", - url.typeSignature, - url.fontColor ?? "blue", - widgetDims - ); - return { - ...base, - SignUrl: signImg, - options: { ...url.options, response: signImg } - }; - } - return base; - } - return url; - }); - - const newUpdateSignPos = getPlaceHolder.map((obj) => { - if (obj.pageNumber === pageNumber) { - return { ...obj, pos: addSignPos }; - } - return obj; - }); - - const newUpdateSigner = signerPos.map((obj) => { - if (obj.Id === signerId) { - return { ...obj, placeHolder: newUpdateSignPos }; - } - return obj; - }); - - setSignerPos(newUpdateSigner); - } - } -}; - -export const widgets = [ - { type: "signature", icon: "fa-light fa-pen-nib", iconSize: "20px" }, - { type: "stamp", icon: "fa-light fa-stamp", iconSize: "19px" }, - { type: "initials", icon: "fa-light fa-signature", iconSize: "15px" }, - { type: textInputWidget, icon: "fa-light fa-font", iconSize: "21px" }, - { type: "name", icon: "fa-light fa-user", iconSize: "21px" }, - { type: "job title", icon: "fa-light fa-address-card", iconSize: "17px" }, - { type: "company", icon: "fa-light fa-building", iconSize: "25px" }, - { type: "email", icon: "fa-light fa-envelope", iconSize: "20px" }, - { type: "date", icon: "fa-light fa-calendar-days", iconSize: "20px" }, - { type: textWidget, icon: "fa-light fa-text-width", iconSize: "20px" }, - { type: cellsWidget, icon: "fa-light fa-table-cells", iconSize: "20px" }, - { type: "checkbox", icon: "fa-light fa-square-check", iconSize: "22px" }, - { - type: "dropdown", - icon: "fa-light fa-circle-chevron-down", - iconSize: "19px" - }, - { type: radioButtonWidget, icon: "fa-light fa-circle-dot", iconSize: "20px" }, - { type: "image", icon: "fa-light fa-image", iconSize: "20px" }, - { type: drawWidget, icon: "fa-light fa-pen-nib", iconSize: "20px" } -]; - -export const getDate = (dateformat) => { - const format = dateformat || "MM/DD/YYYY"; - const date = new Date(); - const milliseconds = date.getTime(); - const newDate = moment(milliseconds).format(format); - return newDate; -}; - -export const selectFormat = (data) => { - switch (data) { - case "L": - return "MM/dd/yyyy"; - case "MM/DD/YYYY": - return "MM/dd/yyyy"; - case "DD-MM-YYYY": - return "dd-MM-yyyy"; - case "DD/MM/YYYY": - return "dd/MM/yyyy"; - case "LL": - return "MMMM dd, yyyy"; - case "DD MMM, YYYY": - return "dd MMM, yyyy"; - case "YYYY-MM-DD": - return "yyyy-MM-dd"; - case "MM-DD-YYYY": - return "MM-dd-yyyy"; - case "MM.DD.YYYY": - return "MM.dd.yyyy"; - case "MMM DD, YYYY": - return "MMM dd, yyyy"; - case "MMMM DD, YYYY": - return "MMMM dd, yyyy"; - case "DD MMMM, YYYY": - return "dd MMMM, yyyy"; - case "DD.MM.YYYY": - return "dd.MM.yyyy"; - case "DD-MMM-YYYY": - return "dd-MMM-yyyy"; - default: - return "MM/dd/yyyy"; - } -}; - -export const changeDateToMomentFormat = (format) => { - switch (format) { - case "MM/dd/yyyy": - return "L"; - case "dd-MM-yyyy": - return "DD-MM-YYYY"; - case "dd/MM/yyyy": - return "DD/MM/YYYY"; - case "MMMM dd, yyyy": - return "LL"; - case "dd MMM, yyyy": - return "DD MMM, YYYY"; - case "yyyy-MM-dd": - return "YYYY-MM-DD"; - case "MM-dd-yyyy": - return "MM-DD-YYYY"; - case "MM.dd.yyyy": - return "MM.DD.YYYY"; - case "MMM dd, yyyy": - return "MMM DD, YYYY"; - case "dd MMMM, yyyy": - return "DD MMMM, YYYY"; - case "dd.MM.yyyy": - return "DD.MM.YYYY"; - case "dd-MMM-yyyy": - return "DD-MMM-YYYY"; - default: - return "L"; - } -}; - -export const getSignerPages = (xyPosition = [], currentKey, signerId) => { - if (!Array.isArray(xyPosition)) { - return []; - } - const hasSigners = xyPosition.some((item) => - Array.isArray(item?.placeHolder) - ); - if (hasSigners) { - const candidates = - signerId !== undefined && signerId !== null && signerId !== "" - ? xyPosition.filter( - (item) => item.Id === signerId || item.signerObjId === signerId - ) - : xyPosition; - for (const signer of candidates) { - const pages = signer?.placeHolder || []; - const ownsWidget = pages.some((page) => - (page?.pos || []).some((widget) => widget?.key === currentKey) - ); - if (ownsWidget) { - return pages; - } - } - return []; - } - return xyPosition; -}; - -export const addWidgetOptions = ( - type, - signer, - placeholder, - role, - widgetValue -) => { - let defaultOpt; - const id = generateId(6); - if (placeholder) { - const countSameWidget = placeholder?.reduce((count, page) => { - return count + page.pos.filter((item) => item.type === type).length; - }, 0); - const count = countSameWidget + 1; - defaultOpt = { name: `${type}-${id}-${count}`, status: "required" }; - } else { - defaultOpt = { name: `${type}-${id}-1`, status: "required" }; - } - switch (type) { - case "signature": - return defaultOpt; - case "stamp": - return defaultOpt; - case "checkbox": - return { ...defaultOpt, isReadOnly: false, isHideLabel: false }; - case textInputWidget: - return { - ...defaultOpt, - isReadOnly: false - }; - case cellsWidget: - return { - ...defaultOpt, - cellCount: 5, - defaultValue: "", - validation: { type: "", pattern: "" }, - isReadOnly: false - }; - case "initials": - return defaultOpt; - case "name": - return { - ...defaultOpt, - defaultValue: widgetValue ? widgetValue : "" - }; - case "company": - return { - ...defaultOpt, - defaultValue: widgetValue ? widgetValue : "" - }; - case "job title": - return { - ...defaultOpt, - defaultValue: widgetValue ? widgetValue : "" - }; - case "date": { - const dateFormat = signer?.DateFormat - ? selectFormat(signer?.DateFormat) - : "MM/dd/yyyy"; - const options = addPreferenceOpt(signer, "date", role); - return { - ...defaultOpt, - response: options?.response || "", - isReadOnly: options?.isReadOnly || false, - validation: { - format: options?.format || dateFormat, - type: "date-format" - } - }; - } - case "image": - return defaultOpt; - case "email": - return { - ...defaultOpt, - validation: { type: "email", pattern: "" }, - defaultValue: widgetValue ? widgetValue : "" - }; - case "dropdown": - return defaultOpt; - case radioButtonWidget: - return { - ...defaultOpt, - values: [], - isReadOnly: false - }; - case textWidget: - return defaultOpt; - case drawWidget: - return defaultOpt; - default: - return {}; - } -}; - -export const addWidgetSelfsignOptions = ( - type, - getWidgetValue, - owner, - placeholder, - isSignyourself -) => { - let defaultOpt; - //condition to handle widgets name field - const id = generateId(6); - if (placeholder) { - const countSameWidget = placeholder?.reduce((count, page) => { - return count + page.pos.filter((item) => item.type === type).length; - }, 0); - const count = countSameWidget + 1; - defaultOpt = { name: `${type}-${id}-${count}`, status: "required" }; - } else { - defaultOpt = { name: `${type}-${id}-1`, status: "required" }; - } - switch (type) { - case "signature": - return defaultOpt; - case "stamp": - return defaultOpt; - case "checkbox": - return defaultOpt; - case textWidget: - return defaultOpt; - case cellsWidget: - return { - ...defaultOpt, - cellCount: 5, - defaultValue: "", - validation: { type: "", pattern: "" }, - isReadOnly: false - }; - case "initials": - return defaultOpt; - case "name": - return { - ...defaultOpt, - defaultValue: getWidgetValue(type), - validation: { type: "text", pattern: "" } - }; - case "company": - return { - ...defaultOpt, - defaultValue: getWidgetValue(type), - validation: { type: "text", pattern: "" } - }; - case "job title": - return { - ...defaultOpt, - defaultValue: getWidgetValue(type), - validation: { type: "text", pattern: "" } - }; - case "date": { - const dateFormat = owner?.DateFormat - ? selectFormat(owner?.DateFormat) - : "MM/dd/yyyy"; - const options = addPreferenceOpt(owner, "date", "", isSignyourself); - return { - ...defaultOpt, - response: options?.response || "", - ...(!isSignyourself - ? { isReadOnly: options?.isReadOnly || false } - : {}), - validation: { - format: options?.format || dateFormat, - type: "date-format" - } - }; - } - case "image": - return defaultOpt; - case "email": - return { - ...defaultOpt, - defaultValue: getWidgetValue(type), - validation: { type: "email", pattern: "" } - }; - default: - return {}; - } -}; - -export const defaultWidthHeight = (type) => { - switch (type) { - case "signature": - return { width: 150, height: 60 }; - case "stamp": - return { width: 150, height: 60 }; - case "checkbox": - return { width: 15, height: 19 }; - case textInputWidget: - return { width: 150, height: 19 }; - case cellsWidget: - return { width: 112, height: 22 }; - case "dropdown": - return { width: 120, height: 22 }; - case "initials": - return { width: 50, height: 50 }; - case "name": - return { width: 150, height: 19 }; - case "company": - return { width: 150, height: 19 }; - case "job title": - return { width: 150, height: 19 }; - case "date": - return { width: 100, height: 20 }; - case "image": - return { width: 70, height: 70 }; - case "email": - return { width: 150, height: 19 }; - case radioButtonWidget: - return { width: 5, height: 10 }; - case textWidget: - return { width: 150, height: 19 }; - case drawWidget: - return { width: 150, height: 60 }; - default: - return { width: 150, height: 60 }; - } -}; -//convert url to base64 -export async function getBase64FromUrl(url, autosign) { - const data = await fetch(url); - const blob = await data.blob(); - return new Promise((resolve) => { - const reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = function () { - const pdfBase = this.result; - if (autosign) { - resolve(pdfBase); - } else { - const suffixbase64 = pdfBase.split(",").pop(); - resolve(suffixbase64); - } - }; - }); -} - -export async function getBase64FromIMG(url) { - const data = await fetch(url); - const blob = await data.blob(); - return new Promise((resolve) => { - const reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = function () { - const pdfBase = this.result; - resolve(pdfBase); - }; - }); -} -//function for convert signature png base64 url to jpeg base64 -export const convertPNGtoJPEG = (base64Data) => { - return new Promise((resolve, reject) => { - const canvas = document.createElement("canvas"); - const img = new Image(); - img.src = base64Data; - - img.onload = () => { - canvas.width = img.width; - canvas.height = img.height; - - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#ffffff"; // white color - ctx.fillRect(0, 0, canvas.width, canvas.height); - ctx.drawImage(img, 0, 0); - // Convert to JPEG by using the canvas.toDataURL() method - const jpegBase64Data = canvas.toDataURL("image/jpeg"); - - resolve(jpegBase64Data); - }; - - img.onerror = (error) => { - reject(error); - }; - }); -}; - -//function for resize image and update width and height for sign-yourself -export const handleSignYourselfWidgetResize = ( - ref, - key, - xyPosition, - setXyPosition, - index, - containerScale -) => { - // Guard against bad index - if (!xyPosition[index]) { - console.log(`ImageResize invalid index ${index}`); - return; - } - - // Compute widget dimensions only once - const { offsetWidth, offsetHeight } = ref; - const factor = containerScale || 1; - const widgetWidth = offsetWidth / factor; - const widgetHeight = offsetHeight / factor; - - // Single pass to update only the targeted index/key - const updated = xyPosition.map((item, idx) => { - if (idx !== index) return item; - - return { - ...item, - pos: item.pos.map((url) => { - if (url.key !== key) return url; - - // For rotated widgets (90°/270°), the visual dimensions are swapped. - // Store the original-orientation dimensions in the data model. - const rotation = url.options?.rotation || 0; - const isRotSwapped = [90, 270].includes(rotation); - const storedWidth = isRotSwapped ? widgetHeight : widgetWidth; - const storedHeight = isRotSwapped ? widgetWidth : widgetHeight; - const widgetDims = { Width: storedWidth, Height: storedHeight }; - - // Base fields for every resized signature - const base = { - ...url, - Width: storedWidth, - Height: storedHeight, - IsResize: true - }; - - // If it's a “type” signature, regenerate the image and options - if (url.typeSignature && url.signatureType === "type") { - const signImg = convertTextToImg( - url.typeFont ?? "Fasthand", - url.typeSignature, - url.fontColor ?? "blue", - widgetDims - ); - - return { - ...base, - SignUrl: signImg, - options: { ...url.options, response: signImg } - }; - } - - return base; - }) - }; - }); - setXyPosition(updated); -}; - -//function for call cloud function signPdf and generate digital signature -export const signPdfFun = async ( - base64Url, - documentId, - signerObjectId, - objectId, - widgets, - activity -) => { - let isCustomCompletionMail = false; - try { - //qes: skip getTenantDetails when objectId is unavailable (QES redirect-back) - if (objectId) { - //get tenant details - const tenantDetails = await getTenantDetails(objectId); - if (tenantDetails && tenantDetails === "user does not exist!") { - return { status: "error", message: "User does not exist." }; - } else { - if (tenantDetails?.CompletionBody && tenantDetails?.CompletionSubject) { - isCustomCompletionMail = true; - } - } - } - //qes: skip widget-based signature extraction (eID Easy already signed the PDF) - let suffixbase64 = ""; //qes: declare outside for QES path - // below for loop is used to get first signature of user to send if to signpdf - // for adding it in completion certificate - let getSignature; - for (let item of widgets) { - if (!getSignature) { - const typeExist = item.pos.some((data) => data?.type); - if (typeExist) { - getSignature = item.pos.find((data) => data?.type === "signature"); - } else { - getSignature = item.pos.find((data) => !data.isStamp); - } - } - } - - let base64Sign = getSignature?.SignUrl; - if (base64Sign) { - //check https type signature (default signature exist) then convert in base64 - const isUrl = base64Sign.includes("https"); - if (isUrl) { - try { - base64Sign = await fetchImageBase64(base64Sign); - } catch (e) { - console.log("error", e); - return { status: "error", message: "something went wrong." }; - } - } - //change image width and height to 300/120 in png base64 - const imagebase64 = await changeImageWH(base64Sign); - //remove suffiix of base64 (without type) - suffixbase64 = imagebase64 && imagebase64.split(",").pop(); - } - - const params = { - pdfFile: base64Url, - docId: documentId, - userId: signerObjectId, - isCustomCompletionMail: isCustomCompletionMail, - signature: suffixbase64, //qes: will be empty string for QES - activity: activity || "Signed" - }; - const resSignPdf = await Parse.Cloud.run("signPdf", params); - if (resSignPdf) { - const signedPdf = JSON.parse(JSON.stringify(resSignPdf)); - return signedPdf; - } - } catch (e) { - console.log("Err in signPdf cloud function ", e.message); - if (e && e?.message?.includes("is encrypted.")) { - return { - status: "error", - message: "Currently encrypted pdf files are not supported." - }; - } else if (e?.message?.includes("password")) { - return { status: "error", message: "PFX file password is invalid." }; - } else if ( - e?.code === 119 || - e?.message?.toLowerCase?.().includes("strict signing order") - ) { - return { status: "error", message: e.message }; - } else { - return { status: "error", message: "something went wrong." }; - } - } -}; - -export const createDocument = async ( - template, - placeholders, - signerData, - SignedUrl, - isSendDoc -) => { - if (template && template.length > 0) { - const Doc = template[0]; - const date = new Date(); - const isoDate = date.toISOString(); - let extUserId = Doc.ExtUserPtr.objectId; - let creatorId = Doc.CreatedBy.objectId; - const Extand_Class = localStorage.getItem("Extand_Class"); - const extClass = Extand_Class && JSON.parse(Extand_Class); - if (extClass && extClass.length > 0) { - if (Doc.ExtUserPtr?.objectId !== extClass?.[0]?.objectId) { - if (extClass && extClass.length > 0) { - extUserId = extClass[0].objectId; - creatorId = extClass[0]?.UserId.objectId; - } - } - } - let placeholdersArr = []; - if (placeholders?.length > 0) { - placeholdersArr = placeholders; - } - let signers = []; - if (signerData?.length > 0) { - signerData.forEach((x) => { - if (x.objectId) { - const obj = { - __type: "Pointer", - className: "contracts_Contactbook", - objectId: x.objectId - }; - signers.push(obj); - } - }); - } - const useNameAsSender = extClass?.[0]?.UseNameAsSender === true; - const senderName = - Doc?.SenderName || (useNameAsSender ? extClass?.[0]?.Name || "" : ""); - const senderMail = - Doc?.SenderMail || (useNameAsSender ? extClass?.[0]?.Email || "" : ""); - const SenderName = senderName ? { SenderName: senderName } : {}; - const SenderMail = senderMail ? { SenderMail: senderMail } : {}; - const SignatureType = Doc?.SignatureType - ? { SignatureType: Doc?.SignatureType } - : {}; - const NotifyOnSignatures = - Doc?.NotifyOnSignatures !== undefined - ? { NotifyOnSignatures: Doc?.NotifyOnSignatures } - : {}; - const Bcc = Doc?.Bcc?.length > 0 ? { Bcc: Doc?.Bcc } : {}; - const Cc = Doc?.Cc?.length > 0 ? { Cc: Doc?.Cc } : {}; - const RedirectUrl = Doc?.RedirectUrl - ? { RedirectUrl: Doc?.RedirectUrl } - : {}; - const PenColors = - Doc?.PenColors?.length > 0 ? { PenColors: Doc?.PenColors } : {}; - const TemplateId = Doc?.objectId - ? { - TemplateId: { - __type: "Pointer", - className: "contracts_Template", - objectId: Doc?.objectId - } - } - : {}; - const data = { - Name: Doc.Name, - URL: SignedUrl ? SignedUrl : Doc?.URL, - SignedUrl: isSendDoc ? SignedUrl : Doc.SignedUrl, - SentToOthers: Doc.SentToOthers, - Description: Doc.Description, - Note: Doc.Note, - Placeholders: placeholdersArr, - ExtUserPtr: { - __type: "Pointer", - className: "contracts_Users", - objectId: extUserId - }, - CreatedBy: { __type: "Pointer", className: "_User", objectId: creatorId }, - Signers: signers, - SendinOrder: Doc?.SendinOrder || false, - AutomaticReminders: Doc?.AutomaticReminders || false, - RemindOnceInEvery: parseInt(Doc?.RemindOnceInEvery || 5), - IsEnableOTP: Doc?.IsEnableOTP || false, - SendInOrderStrict: Doc?.SendInOrderStrict || false, - IsTourEnabled: Doc?.IsTourEnabled || false, - AllowModifications: Doc?.AllowModifications || false, - TimeToCompleteDays: parseInt(Doc?.TimeToCompleteDays) || 15, - DocSentAt: { __type: "Date", iso: isoDate }, - ...SignatureType, - ...NotifyOnSignatures, - ...SenderName, - ...SenderMail, - ...Bcc, - ...Cc, - ...RedirectUrl, - ...TemplateId, - ...PenColors - }; - const remindOnceInEvery = Doc?.RemindOnceInEvery; - const TimeToCompleteDays = parseInt(Doc?.TimeToCompleteDays); - const reminderCount = TimeToCompleteDays / remindOnceInEvery; - const AutomaticReminders = Doc.autoreminder; - if (AutomaticReminders && reminderCount > 15) { - return { status: "error", id: "only-15-reminder-allowed" }; - } - const url = `${localStorage.getItem("baseUrl")}functions/createdocumentfromapp`; - const token = { - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - try { - const res = await axios.post( - url, - { document: data }, - { - headers: { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - ...token - } - } - ); - if (res) { - const result = res.data.result; - - return { status: "success", id: result.objectId, data: result }; - } - } catch (err) { - const message = getErrorMessage(err) || "something went wrong."; - console.error("error in create document:", message); - return { status: "error", id: "something-went-wrong-mssg" }; - } - } -}; - -export const getFirstLetter = (name) => { - const firstLetter = name?.charAt(0); - return firstLetter; -}; - -export const darkenColor = (color, factor) => { - // Remove '#' from the color code and parse it to get RGB values - const hex = color.replace("#", ""); - const r = parseInt(hex.substring(0, 2), 16); - const g = parseInt(hex.substring(2, 4), 16); - const b = parseInt(hex.substring(4, 6), 16); - - // Darken the color by reducing each RGB component - const darkerR = Math.floor(r * (1 - factor)); - const darkerG = Math.floor(g * (1 - factor)); - const darkerB = Math.floor(b * (1 - factor)); - - // Convert the darkened RGB components back to hex - return `#${((darkerR << 16) | (darkerG << 8) | darkerB) - .toString(16) - .padStart(6, "0")}`; -}; - -export const addZIndex = (signerPos, key, setZIndex) => { - return signerPos.map((item) => { - if (item.placeHolder && item.placeHolder.length > 0) { - // If there is a nested array, recursively add the field to the last object - return { - ...item, - placeHolder: addZIndex(item.placeHolder, key, setZIndex) - }; - } else if (item.pos && item.pos.length > 0) { - // If there is no nested array, add the new field - return { - ...item, - pos: addZIndex(item.pos, key, setZIndex) - // Adjust this line to add the desired field - }; - } else { - if (item.key === key) { - setZIndex(item.zIndex); - return { - ...item, - zIndex: item.zIndex ? item.zIndex + 1 : 1 - }; - } else { - return { ...item }; - } - } - }); -}; - -//function for save widgets value on onchange function -export const onChangeInput = ( - value, - currentPosition, - xyPosition, - index, - setXyPosition, - userId, - initial, - dateFormat, - fontSize, - fontColor, - dateDetails, - textWidgetHeight -) => { - const isDuplicateValueUpdate = !dateFormat && !textWidgetHeight; - const shouldAutoApplyDuplicateWidget = (position) => { - const currentName = getDuplicateAutoApplyName(currentPosition); - const positionName = getDuplicateAutoApplyName(position); - return currentName && positionName && currentName === positionName; - }; - const applyDuplicateWidgetValue = (position) => { - if ( - position?.options?.response === value && - position?.options?.defaultValue === "" - ) { - return position; - } - return { - ...position, - options: { - ...position.options, - response: value, - defaultValue: "" - } - }; - }; - const isSigners = xyPosition.some( - (data) => data.signerPtr || data.Role === "prefill" - ); - let filterSignerPos; - if (isSigners) { - if (userId) { - filterSignerPos = xyPosition.filter((data) => data.Id === userId); - } - const getPlaceHolder = filterSignerPos[0]?.placeHolder; - if (initial) { - const xyData = addInitialData(xyPosition, setXyPosition, value, userId); - setXyPosition(xyData); - } else { - const getPageNumer = getPlaceHolder.filter( - (data) => data.pageNumber === index - ); - if (getPageNumer.length > 0) { - const updatePositionValue = (position) => { - if (position.key === currentPosition.key) { - if (dateFormat) { - return { - ...position, - options: { - ...position.options, - response: value, - fontSize: fontSize ? fontSize : position.options?.fontSize, - fontColor: fontColor - ? fontColor - : position.options?.fontColor, - isReadOnly: - dateDetails && dateDetails?.isReadOnly !== "undefined" - ? dateDetails?.isReadOnly - : position.options?.isReadOnly, - status: - dateDetails && dateDetails?.status !== "undefined" - ? dateDetails?.status - : position.options?.status, - name: - dateDetails && dateDetails?.name !== "undefined" - ? dateDetails?.name - : position.options?.name, - validation: { - type: "date-format", - format: dateFormat // This indicates the required date format explicitly. - }, - hint: dateDetails?.hint || position.options?.hint || "" - } - }; - } else if ( - (currentPosition?.type === "text" || - currentPosition?.type === textInputWidget) && - textWidgetHeight && - !value - ) { - const dimension = [90, 270].includes(position.options?.rotation) - ? "Width" - : "Height"; - return { ...position, [dimension]: textWidgetHeight }; - } else { - return applyDuplicateWidgetValue(position); - } - } - if ( - isDuplicateValueUpdate && - shouldAutoApplyDuplicateWidget(position) - ) { - return applyDuplicateWidgetValue(position); - } - return position; - }; - setXyPosition((prevPosition) => { - const sourcePosition = Array.isArray(prevPosition) - ? prevPosition - : xyPosition; - return sourcePosition.map((obj) => { - if (obj.Id !== userId) { - return obj; - } - const updatedPlaceHolder = (obj.placeHolder || []).map((page) => ({ - ...page, - pos: page.pos.map(updatePositionValue) - })); - return { - ...obj, - placeHolder: applyNumberFormulasToPages(updatedPlaceHolder) - }; - }); - }); - } - } - } else { - const updatePositionValue = (positionData) => { - if (positionData.key === currentPosition.key) { - if (dateFormat) { - return { - ...positionData, - options: { - ...positionData.options, - response: value, - fontSize: fontSize, - fontColor: fontColor, - validation: { - type: "date-format", - format: dateFormat // This indicates the required date format explicitly. - } - } - }; - } else if ( - (currentPosition?.type === "text" || - currentPosition?.type === textInputWidget) && - textWidgetHeight && - !value - ) { - const dimension = [90, 270].includes(positionData.options?.rotation) - ? "Width" - : "Height"; - return { ...positionData, [dimension]: textWidgetHeight }; - } else { - return applyDuplicateWidgetValue(positionData); - } - } - if ( - isDuplicateValueUpdate && - shouldAutoApplyDuplicateWidget(positionData) - ) { - return applyDuplicateWidgetValue(positionData); - } - return positionData; - }; - - setXyPosition((prevPosition) => { - const sourcePosition = Array.isArray(prevPosition) - ? prevPosition - : xyPosition; - const updatePlaceholder = sourcePosition.map((obj) => ({ - ...obj, - pos: obj.pos.map(updatePositionValue) - })); - return applyNumberFormulasToPages(updatePlaceholder); - }); - } -}; -//function to increase height of text area on press enter -export const onChangeHeightOfTextArea = ( - height, - widgetType, - signKey, - xyPosition, - index, - setXyPosition, - userId -) => { - const isSigners = xyPosition.some((data) => data.signerPtr); - let filterSignerPos; - if (isSigners) { - if (userId) { - filterSignerPos = xyPosition.filter((data) => data.Id === userId); - } - const getPlaceHolder = filterSignerPos[0]?.placeHolder; - - const getPageNumer = getPlaceHolder.filter( - (data) => data.pageNumber === index - ); - if (getPageNumer.length > 0) { - const getXYdata = getPageNumer[0].pos; - const getPosData = getXYdata; - const addSignPos = getPosData.map((position) => { - if (position.key === signKey) { - return { - ...position, - Height: position.Height - ? position.Height + height - : defaultWidthHeight(widgetType).height + height - }; - } - return position; - }); - const newUpdateSignPos = getPlaceHolder.map((obj) => { - if (obj.pageNumber === index) { - return { ...obj, pos: addSignPos }; - } - return obj; - }); - - const newUpdateSigner = xyPosition.map((obj) => { - if (obj.Id === userId) { - return { ...obj, placeHolder: newUpdateSignPos }; - } - return obj; - }); - - setXyPosition(newUpdateSigner); - } - } else { - let getXYdata = xyPosition[index].pos; - - const updatePosition = getXYdata.map((position) => { - if (position.key === signKey) { - return { - ...position, - Height: position.Height - ? position.Height + height - : defaultWidthHeight(widgetType).height + height - }; - } - return position; - }); - - const updatePlaceholder = xyPosition.map((obj, ind) => { - if (ind === index) { - return { ...obj, pos: updatePosition }; - } - return obj; - }); - setXyPosition(updatePlaceholder); - } -}; -//calculate width and height -export const calculateInitialWidthHeight = (widgetData) => { - const intialText = widgetData; - const span = document.createElement("span"); - span.textContent = intialText; - span.style.font = `12px`; // here put your text size and font family - span.style.display = "hidden"; - document.body.appendChild(span); - const width = span.offsetWidth; - const height = span.offsetHeight; - - document.body.removeChild(span); - return { getWidth: width, getHeight: height }; -}; -export const widgetDataValue = (type, value) => { - switch (type) { - case "name": - return value?.Name || value?.name; - case "company": - return value?.Company || value?.company; - case "job title": - return value?.JobTitle || value?.jobTitle; - case "email": - return value?.Email || value?.email; - default: - return ""; - } -}; -export const addInitialData = (signerPos, setXyPosition, value, userId) => { - return signerPos.map((item) => { - if (item.placeHolder && item.placeHolder.length > 0) { - // If there is a nested array, recursively add the field to the last object - if (item.Id === userId) { - return { - ...item, - placeHolder: addInitialData( - item.placeHolder, - setXyPosition, - value, - userId - ) - }; - } else { - return item; - } - } else if (item.pos && item.pos.length > 0) { - // If there is no nested array, add the new field - return { - ...item, - pos: addInitialData(item.pos, setXyPosition, value, userId) - // Adjust this line to add the desired field - }; - } else { - const widgetData = widgetDataValue(item.type, value); - if (["name", "company", "job title", "email"].includes(item.type)) { - return { - ...item, - options: { - ...item.options, - defaultValue: item?.options?.defaultValue || widgetData - } - }; - } else { - return item; - } - } - }); -}; - -//function for embed document id -export const embedDocId = async (pdfOriginalWH, pdfDoc, documentId) => { - const appName = "OpenSign™"; - // `fontBytes` is used to embed custom font in pdf - const pdfFontUrl = getRuntimePdfFontUrl(); - if (!pdfFontUrl) throw new Error("A PDF font URL is required."); - const fontBytes = await fileasbytes(pdfFontUrl); - pdfDoc.registerFontkit(fontkit); - const font = await pdfDoc.embedFont(fontBytes, { subset: true }); - //pdfOriginalWH contained all pdf's pages width and height - for (let i = 0; i < pdfOriginalWH?.length; i++) { - const fontSize = 10; - const textContent = documentId && `${appName} DocumentId: ${documentId} `; - const pages = pdfDoc.getPages(); - const page = pages[i]; - const getSize = pdfOriginalWH[i]; - try { - const getObj = compensateRotation( - page.getRotation().angle, - 10, - 5, - 1, - getSize, - fontSize, - rgb(0.5, 0.5, 0.5), - font, - page - ); - page.drawText(textContent, getObj); - } catch (err) { - console.log("Err in embed docId on page", i + 1, err?.message); - } - } -}; - -// function for convert input text value in image -export function convertTextToImg(fontStyle, text, color, widgetDims) { - // read your widget dimensions: - const maxWidth = widgetDims.Width; - const maxHeight = widgetDims.Height; - const baselineFontSizePx = maxHeight; - const fontFamily = fontStyle || "Fasthand"; - const fillColor = color || "blue"; - - // 1. Use a temporary canvas to measure actual text size - const tempCanvas = document.createElement("canvas"); - const tempCtx = tempCanvas.getContext("2d"); - tempCtx.font = `${baselineFontSizePx}px ${fontFamily}`; - const metrics = tempCtx.measureText(text); - - const actualHeight = - metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; - const actualWidth = metrics.width; - - // const renderscale = 3; - // 2. Scale font size so text height fills canvas - const scaleX = maxWidth / actualWidth; - const scaleY = maxHeight / actualHeight; - const scale = Math.min(scaleX, scaleY, 1); - // final font-size - // const finalFontSizePx = baselineFontSizePx * scale * renderscale; - const finalFontSizePx = baselineFontSizePx * scale; - // 3. Create the final canvas - const pxRatio = window.devicePixelRatio * 2 || 3; - const canvas = document.createElement("canvas"); - canvas.width = Math.ceil(maxWidth * pxRatio); - canvas.height = Math.ceil(maxHeight * pxRatio); - const ctx = canvas.getContext("2d"); - ctx.scale(pxRatio, pxRatio); - - // 4. Setup text with final font - ctx.font = `${finalFontSizePx}px ${fontFamily}`; - ctx.fillStyle = fillColor; - ctx.textAlign = "center"; - ctx.textBaseline = "alphabetic"; - - const newMetrics = ctx.measureText(text); - const ascent = newMetrics.actualBoundingBoxAscent; - const descent = newMetrics.actualBoundingBoxDescent; - - // 5. Align text vertically so it touches top and bottom - const y = maxHeight / 2 + (ascent - descent) / 2; - - ctx.clearRect(0, 0, maxWidth, maxHeight); - ctx.fillText(text, maxWidth / 2, y); - - // 6. Output image - const dataUrl = canvas.toDataURL("image/png"); - return dataUrl; -} - -// `onSaveSign` trigger on save button to save for signature, initials widget for type: draw, typed, default -export function onSaveSign( - type, - xyPosition, - index, - signKey, - signatureImg, - updatedImgWH, - isTypeText, - typedSignature, - isAutoSign, - widgetsType, - typeFont, - fontColor -) { - let getIMGWH, posWidth, posHeight; - let getXYdata = xyPosition[index].pos; - const isSignOrInitials = - widgetsType && ["signature", "initials"].includes(widgetsType); - const updateXYData = getXYdata.map((position) => { - if (position.key === signKey) { - if (isTypeText) { - getIMGWH = { - newWidth: updatedImgWH.width, - newHeight: updatedImgWH.height - }; - } - posWidth = getIMGWH ? getIMGWH.newWidth : 150; - posHeight = getIMGWH ? getIMGWH.newHeight : 60; - const widgetDims = { Width: posWidth, Height: posHeight }; - const signImg = typedSignature - ? convertTextToImg(typeFont, typedSignature, fontColor, widgetDims) - : signatureImg; - if (widgetsType === drawWidget) { - return { - ...position, - options: { ...position.options, response: signImg } - }; - } else { - return { - ...position, - ...(type === "type" ? { Width: posWidth } : {}), - ...(type === "type" ? { Height: posHeight } : {}), - SignUrl: signImg, - ...(isSignOrInitials && { signatureType: type || "" }), - options: { ...position.options, response: signImg }, - ...(typedSignature && { - typeSignature: typedSignature, - typeFont: typeFont ?? "Fasthand", - fontColor: fontColor ?? "blue" - }) - }; - } - } - return position; - }); - - const updateXYposition = xyPosition.map((obj, ind) => { - if (ind === index) { - return { ...obj, pos: updateXYData }; - } - return obj; - }); - //condition when draw/upload signature/initials then apply it all related to widgets (draw, typed signature or default signature) - if (isAutoSign && widgetsType !== drawWidget) { - const updatedArray = updateXYposition.map((page) => ({ - ...page, - pos: page.pos.map((item) => { - if (item.type === widgetsType) { - const widgetDims = { Width: item.Width, Height: item.Height }; - const signImg = typedSignature - ? convertTextToImg(typeFont, typedSignature, fontColor, widgetDims) - : signatureImg; - return { - ...item, - SignUrl: signImg, - ...(isSignOrInitials && { signatureType: type || "" }), - options: { ...item.options, response: signImg }, - ...(typedSignature && { - typeSignature: typedSignature, - typeFont: typeFont || "Fasthand", - fontColor: fontColor || "blue" - }) - }; - } - return item; // Otherwise, keep it unchanged - }) - })); - return updatedArray; - } else { - return updateXYposition; - } -} - -export function clearResponse(widgetKey, placeholder = [], index) { - if (!Array.isArray(placeholder) || !placeholder[index]?.pos) { - return placeholder; - } - const getXYdata = placeholder[index]?.pos; - const updateXYData = getXYdata.map((widget) => { - if (widget?.key !== widgetKey) return widget; - return { - ...widget, - options: { ...widget.options, response: "" }, - SignUrl: "" - }; - }); - - const updatePlaceholder = placeholder.map((p, ind) => { - if (ind !== index) return p; - return { ...p, pos: updateXYData }; - }); - return updatePlaceholder; -} -/** - * Scales and centers a base64‐encoded image into a fixed‐size widget - * and returns a new base64 PNG. - * - * @param {string} base64Image A data-URL (e.g. "data:image/png;base64,…") - * @param {{ Width: number, Height: number }} widgetDims - * @returns {Promise<string>} A Promise that resolves to a data-URL of the new image - */ -export async function convertBase64ToImg(base64Image, widgetDims) { - const { Width: maxWidth, Height: maxHeight } = widgetDims; - // Load the image off-DOM - const img = new Image(); - img.src = base64Image; - await new Promise((resolve, reject) => { - img.onload = resolve; - img.onerror = reject; - }); - - // 2. Compute scale to fit within widget (preserving aspect ratio) - const { naturalWidth: imgW, naturalHeight: imgH } = img; - const scale = Math.min(maxWidth / imgW, maxHeight / imgH, 1); - const drawW = imgW * scale; - const drawH = imgH * scale; - - // 3. Prepare a high-DPI canvas - const pxRatio = (window.devicePixelRatio || 1) * 2; - const canvas = document.createElement("canvas"); - canvas.width = Math.ceil(maxWidth * pxRatio); - canvas.height = Math.ceil(maxHeight * pxRatio); - const ctx = canvas.getContext("2d"); - ctx.scale(pxRatio, pxRatio); - ctx.clearRect(0, 0, maxWidth, maxHeight); - - // 4. Center the image in the widget rectangle - const x = (maxWidth - drawW) / 2; - const y = (maxHeight - drawH) / 2; - ctx.drawImage(img, x, y, drawW, drawH); - // 5. Return new base64 in same format as input - // const quality = - // inputMime.includes("jpeg") || inputMime.includes("jpg") ? 0.9 : undefined; - // return canvas.toDataURL(inputMime, quality); - // 5. Always return PNG (lossless, no quality param needed) - return canvas.toDataURL("image/png"); -} - -//function to use After setting the signature URL for the first signature widget, clicking on subsequent -//signature widgets should automatically apply and display the signature. apply for initial,signature and stamp widget -export const handleCopySignUrl = ( - currentPos, - existSignPosition, - setXyPosition, - xyPosition, - pageNumber, - signerObjectId -) => { - //get current signer details - const currentSigner = xyPosition.filter( - (data) => data.signerObjId === signerObjectId - ); - //get current signer placeholder details - const placeholderPosition = currentSigner[0].placeHolder; - //get current pagenumber position - const getcurrentPagePosition = placeholderPosition.find( - (data) => data.pageNumber === pageNumber - ); - let getXYdata = getcurrentPagePosition.pos; - const updatePos = getXYdata.map((x) => { - //update widgets sign url details - if (x.key === currentPos.key) { - return { - ...x, - // Width: existSignPosition.Width, - // Height: existSignPosition.Height, - SignUrl: existSignPosition.SignUrl, - signatureType: existSignPosition.signatureType, - options: { ...x.options, response: existSignPosition.SignUrl }, - ...(existSignPosition.typedSignature && { - typeSignature: existSignPosition.typedSignature - }) - }; - } - return x; - }); - const updateXYposition = placeholderPosition.map((obj) => { - if (obj.pageNumber === pageNumber) { - return { ...obj, pos: updatePos }; - } - return obj; - }); - const newUpdateSigner = xyPosition.map((obj) => { - if (obj.signerObjId === signerObjectId) { - return { ...obj, placeHolder: updateXYposition }; - } - return obj; - }); - setXyPosition(newUpdateSigner); -}; -export const calculateImgAspectRatio = (imgWH, pos) => { - let newWidth, newHeight; - - const placeholderHeight = pos && pos.Height ? pos.Height : 60; - const aspectRatio = imgWH.width / imgWH.height; - newWidth = aspectRatio * placeholderHeight; - newHeight = placeholderHeight; - return { newHeight, newWidth }; -}; - -// `onSaveImage` trigger for upload image through stamp, image, signature, initials widgets -export function onSaveImage( - signatureType, - xyPosition, - index, - signKey, - image, - isAutoSign, - widgetsType, - imgUrl, - defaultStampImg, - defaultStampType -) { - let widgetName; - const isSignOrInitials = - widgetsType && ["signature", "initials"].includes(widgetsType); - //get current page position - const getXYData = xyPosition[index].pos; - const updateXYData = getXYData.map((position) => { - if (position.key === signKey) { - widgetName = position?.options?.name; - return { - ...position, - SignUrl: imgUrl || image?.src || defaultStampImg, - ImageType: image?.imgType || defaultStampType, - ...(isSignOrInitials && { signatureType: signatureType || "" }), - options: { - ...position.options, - response: imgUrl || image?.src || defaultStampImg - } - }; - } - return position; - }); - const updateXYposition = xyPosition.map((obj, ind) => { - if (ind === index) { - return { ...obj, pos: updateXYData }; - } - return obj; - }); - - // condition when user apply auto sign feature for any type upload image (signature,initials,stamp,image) - if (isAutoSign) { - const updatedArray = updateXYposition.map((page) => ({ - ...page, - pos: page.pos.map( - (item) => - // below condition is check if image widget name same then apply to auto sign other wise not - // and for other widget like signature,stamp,initials apply auto sign for all remaining widgets - item.type === widgetsType && - (item.type !== "image" || item.options.name === widgetName) - ? { - ...item, - SignUrl: image?.src || defaultStampImg, - ImageType: image?.imgType || defaultStampType, - options: { - ...item.options, - response: image?.src || defaultStampImg - } - } - : item // Otherwise, keep it unchanged - ) - })); - - return updatedArray; - } else { - return updateXYposition; - } -} - -//function for select image and upload image -export const onImageSelect = (setImage, file) => { - const reader = new FileReader(); - reader.readAsDataURL(file); - reader.onloadend = function (e) { - let width, height; - const image = new Image(); - image.src = e.target.result; - image.onload = function () { - width = image.width; - height = image.height; - const aspectRatio = 460 / 184; - const imgR = width / height; - if (imgR > aspectRatio) { - width = 460; - height = 460 / imgR; - } else { - width = 184 * imgR; - height = 184; - } - }; - image.src = reader.result; - setImage({ src: image.src, imgType: file.type }); - }; -}; -export const compressedFileSize = (file, setImage) => { - // Create a new FileReader instance to read the uploaded file - const reader = new FileReader(); - - // Event listener triggered when the file is read successfully - reader.onload = (e) => { - // Create a new Image instance to manipulate the image data - const img = new Image(); - - // Set the image source to the file's data URL (base64 string) - img.src = e.target.result; - - // Event listener triggered when the image is fully loaded - img.onload = () => { - // Create a canvas element to resize and compress the image - const canvas = document.createElement("canvas"); - const ctx = canvas.getContext("2d"); // Get the drawing context of the canvas - - // Set the canvas dimensions, ensuring they don't exceed 1920x1920 - canvas.width = Math.min(img.width, 1920); // Limit width to 1920px - canvas.height = Math.min(img.height, 1920); // Limit height to 1920px - - // Draw the image onto the canvas with the specified dimensions - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); - // Get the original file type (default to "image/png" if not recognized) - const fileType = "image/png"; //file.type || "image/png" - // Compress the image and convert it into a Blob - canvas.toBlob( - (blob) => { - // Create a new File object from the compressed Blob - const compressedFile = new File([blob], file.name, { - type: fileType, // Set the file type to JPEG - lastModified: Date.now() // Update the last modified timestamp - }); - // Pass the compressed file to a custom function for further processing - onImageSelect(setImage, compressedFile); - }, - fileType, // Output format for the compressed image - 0.3 // Compression quality (30%) - ); - }; - }; - - // Read the file as a data URL (base64 string) to be processed - reader.readAsDataURL(file); -}; -//convert https url to base64 -export const fetchImageBase64 = async (imageUrl) => { - try { - const response = await fetch(imageUrl); - const blob = await response.blob(); - - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = () => { - const base64data = reader.result; - resolve(base64data); - }; - reader.onerror = (error) => { - reject(error); - }; - }); - } catch (error) { - throw new Error("Error converting URL to base64:", error); - } -}; -//function for select image and upload image -export const changeImageWH = async (base64Image) => { - const newWidth = 300; - const newHeight = 120; - return new Promise((resolve, reject) => { - const img = new Image(); - img.src = base64Image; - img.onload = async () => { - const canvas = document.createElement("canvas"); - const ctx = canvas.getContext("2d"); - canvas.width = newWidth; - canvas.height = newHeight; - ctx.drawImage(img, 0, 0, newWidth, newHeight); - const resizedBase64 = canvas.toDataURL("image/png", 1.0); - resolve(resizedBase64); - }; - img.onerror = (error) => { - reject(error); - }; - }); -}; - -const getWidgetsFontColor = (type) => { - switch (type) { - case "red": - return rgb(1, 0, 0); - case "black": - return rgb(0, 0, 0); - case "blue": - return rgb(0, 0, 1); - case "yellow": - return rgb(0.9, 1, 0); - default: - return rgb(0, 0, 0); - } -}; -export const isBase64 = (str) => { - const base64Pattern = - /^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+)?;base64,[A-Za-z0-9+/=]+$/; - return base64Pattern.test(str); -}; -// Break a long word into smaller parts character-by-character -const forceBreakLongWord = (word, width, font, fontSize) => { - const parts = []; - let current = ""; - - for (const char of word) { - const lineWidth = font.widthOfTextAtSize(current + char, fontSize); - - if (lineWidth <= width) { - current += char; - } else { - parts.push(current); - current = char; - } - } - if (current) parts.push(current); - - return parts; -}; - -export const isEmptyValue = (val) => - val === null || - val === undefined || - (typeof val === "string" && val.trim() === "") || - (Array.isArray(val) && val.length === 0); - -//function for embed all type widgets in document using pdf-lib -export const embedWidgetsToDoc = async ( - widgets, - pdfDoc, - signyourself, - scale, - prefillImg -) => { - // `fontBytes` is used to embed custom font in pdf - const pdfFontUrl = getRuntimePdfFontUrl(); - if (!pdfFontUrl) throw new Error("A PDF font URL is required."); - const fontBytes = await fileasbytes(pdfFontUrl); - pdfDoc.registerFontkit(fontkit); - const font = await pdfDoc.embedFont(fontBytes, { subset: true }); - let hasError = false; - for (let item of widgets) { - if (hasError) break; // Stop the outer loop if an error occurred - const typeExist = item.pos.some((data) => data?.type); - let updateItem; - if (typeExist) { - if (signyourself) { - updateItem = item.pos; - } else { - // Checking required and optional widget types - // For both required and optional widgets, handle signurl, defaultValue, and response as the widget's data - // If the widget type is checkbox or radio (whether required or optional), we don't need to validate its value. - // Instead, add an empty checkbox/radio, or if a value exists, mark the checkbox/radio as checked. - updateItem = item.pos.filter( - (data) => - data?.options?.SignUrl || - !isEmptyValue(data?.options?.defaultValue) || - !isEmptyValue(data?.options?.response) || - data?.type === "checkbox" || - data?.type === radioButtonWidget - ); - } - } else { - updateItem = item.pos; - } - const ImgTypeWidget = [ - "signature", - "stamp", - "initials", - "image", - drawWidget - ]; - const pageNo = item.pageNumber; - const widgetsPositionArr = updateItem; - const pages = pdfDoc.getPages(); - const form = pdfDoc.getForm(); - const page = pages[pageNo - 1]; - // `page.getCropBox()` returns the visible area of the PDF page. - // It provides an object with the following properties: - // - x: the x-coordinate of the lower-left corner of the visible area - // - y: the y-coordinate of the lower-left corner of the visible area - // - width: the width of the visible area (x1 - x0) - // - height: the height of the visible area (y1 - y0) - // If the page does not explicitly define a CropBox, this method returns - // the MediaBox instead, which represents the full physical size of the page. - // - // Example CropBox: [0, 7.92, 612, 799.92] - // => x = 0, y = 7.92, width = 612 - 0 = 612, height = 799.92 - 7.92 = 792 - // This is equivalent to `react-pdf`'s `page.view` array: [x0, y0, x1, y1] - const { _, y, width, height } = page.getCropBox(); - const originalHeight = height + y; - let images; - const getSize = { height: originalHeight, width: width }; - try { - images = await Promise.all( - widgetsPositionArr.map(async (widget) => { - // `SignUrl` this is wrong nomenclature and maintain for older code in this options we save base64 of signature image from sign pad - let signbase64 = widget?.options?.response; - const widgetDims = { Width: widget.Width, Height: widget.Height }; - if (signbase64 && ImgTypeWidget.includes(widget.type)) { - if (!isBase64(signbase64) && prefillImg) { - const imgData = prefillImg?.find((x) => x?.id === widget?.key); - signbase64 = imgData?.base64; - } - // let arr = signbase64.split(","); - // const mime = arr[0].match(/:(.*?);/)[1]; - const signatureImg = await convertBase64ToImg( - signbase64, - widgetDims - ); - const mime = signatureImg?.split(",")?.[0]?.match(/:(.*?);/)?.[1]; - const res = await fetch(signatureImg); - const arrayBuffer = await res.arrayBuffer(); - const obj = { mimetype: mime, arrayBuffer: arrayBuffer }; - return obj; - } - }) - ); - } catch (e) { - console.log("error in image", e); - } - for (let [id, position] of widgetsPositionArr.entries()) { - const isTextTypeWidget = [ - textWidget, - textInputWidget, - cellsWidget, - "name", - "company", - "job title", - "date", - "email" - ].includes(position.type); - if (hasError) break; // Stop the inner loop if an error occurred - try { - let img; - if (ImgTypeWidget.includes(position.type)) { - if (images[id].mimetype === "image/png") { - img = await pdfDoc.embedPng(images[id].arrayBuffer); - } else { - img = await pdfDoc.embedJpg(images[id].arrayBuffer); - } - } else if (!position.type) { - // to handle old widget when only stamp and signature are exists - if (images[id].mimetype === "image/png") { - img = await pdfDoc.embedPng(images[id].arrayBuffer); - } else { - img = await pdfDoc.embedJpg(images[id].arrayBuffer); - } - } - let widgetWidth, widgetHeight; - widgetWidth = placeholderWidth(position); - widgetHeight = placeholderHeight(position); - const xPos = (position) => { - const resizePos = position.xPosition; - //first two condition handle to old data already saved from mobile view which scale point diffrent - if (isMobile && position.isMobile) { - //if pos.isMobile false -- placeholder saved from desktop view then handle position in mobile view divided by scale - const x = resizePos * (position.scale / scale); - return x * scale; - } else if (position.isMobile && position.scale) { - const x = resizePos * position.scale; - return x; - } else { - return resizePos; - } - }; - const yPos = (position) => { - const resizePos = position.yPosition; - - if (position.isMobile && position.scale) { - if (position.IsResize) { - const y = resizePos * position.scale; - return y; - } else { - const y = resizePos * position.scale; - return y; - } - } else { - const yPosition = isTextTypeWidget ? resizePos + 6 : resizePos; - return yPosition; - } - }; - const color = position?.options?.fontColor; - const updateColorInRgb = getWidgetsFontColor(color); - const fontSize = parseInt(position?.options?.fontSize || 12); - if (position.type === "checkbox") { - // Determine layout mode: 'vertical' (default) or 'horizontal' - // const isHorizontal = position.layout === "horizontal"; - const isHorizontal = - position?.options?.layout === "horizontal" ? true : false; - // Initial “cursor” positions - let currentX = xPos(position); - let currentY = yPos(position) + 2; - // Size and spacing settings - const checkboxSize = fontSize - 1; // checkbox diameter - const checkboxTextGapFromLeft = fontSize + 3.4; // gap between box and its label - const verticalGap = fontSize + 5.5; // gap between two options (vertical layout) - let horizontalGap = 0; // will compute after drawing each label - if (position?.options?.values?.length > 0) { - position.options.values.forEach((item, ind) => { - // 1. Advance the “cursor” on second+ iteration - if (ind > 0) { - if (isHorizontal) { - currentX += horizontalGap; - } else { - currentY += verticalGap; - } - } - // 2. Determine whether this checkbox should be checked - let isCheck = false; - if ( - position.options.response && - position.options.response?.length > 0 - ) { - isCheck = position.options.response.includes(ind); - } else if (position.options.defaultValue) { - isCheck = position.options.defaultValue.includes(ind); - } - - // 3. Draw the label (if labels are not hidden) - if (!position.options.isHideLabel) { - const labelX = currentX + checkboxTextGapFromLeft; - const labelY = currentY - 3; - - const optionsPosition = compensateRotation( - page.getRotation().angle, - labelX, - labelY, - 1, - getSize, - fontSize, - updateColorInRgb, - font, - page - ); - page.drawText(item, optionsPosition); - } - // 4. Create and place the actual checkbox - const checkboxRandomId = "checkbox" + randomId(); - const checkbox = form.createCheckBox(checkboxRandomId); - let checkboxObj = { - x: currentX, - y: currentY, - width: checkboxSize, - height: checkboxSize - }; - checkboxObj = getWidgetPosition(page, checkboxObj, 1, getSize); - checkbox.addToPage(page, checkboxObj); - // 5. Check or uncheck as needed, then make read‐only - if (isCheck) { - checkbox.check(); - } else { - checkbox.uncheck(); - } - checkbox.enableReadOnly(); - // 6. If horizontal layout, compute how far to shift next checkbox‐circle - if (isHorizontal) { - // Measure the width of this label text at `fontSize` - const textWidth = font.widthOfTextAtSize(item, fontSize); - // Next checkbox should come after: [box] + gap + [label text] + extra 10pt padding - const gap = position.options?.isHideLabel - ? checkboxTextGapFromLeft - 5 - : checkboxTextGapFromLeft + textWidth; - horizontalGap = checkboxSize + gap; - } - }); - } - } else if (isTextTypeWidget) { - let textContent = ""; - if (!isEmptyValue(position?.options?.response)) { - if ( - position.type === "date" && - position.options?.response === "today" - ) { - const getFormat = changeDateToMomentFormat( - position?.options?.validation?.format - ); - textContent = moment().format(getFormat); - } else { - textContent = position.options?.response; - } - } else if (!isEmptyValue(position?.options?.defaultValue)) { - textContent = position?.options?.defaultValue?.toString(); - } - if (position.type === cellsWidget) { - const cellCount = - position?.options?.cellCount || textContent.length || 1; - const charWidth = widgetWidth / cellCount; - const y = yPos(position) - 4; - for (let i = 0; i < cellCount; i++) { - const ch = textContent[i] || ""; - const charX = - xPos(position) + - charWidth * i + - (charWidth - font.widthOfTextAtSize(ch, fontSize)) / 2; - const textPosition = compensateRotation( - page.getRotation().angle, - charX, - y, - 1, - getSize, - fontSize, - updateColorInRgb, - font, - page - ); - if (ch) page.drawText(ch, textPosition); - } - } else { - const fixedWidth = widgetWidth; // Set your fixed - textContent = textContent?.toString(); - const isNewOnEnterLineExist = textContent?.includes("\n"); - - // Function to break text into lines based on the fixed width - const NewbreakTextIntoLines = (textContent, width) => { - const lines = []; - let currentLine = ""; - - const words = textContent?.split(" "); - for (let word of words) { - const testLine = currentLine ? currentLine + " " + word : word; - const testWidth = font.widthOfTextAtSize(testLine, fontSize); - - if (testWidth <= width) { - currentLine = testLine; - } else { - // If single long word - if (font.widthOfTextAtSize(word, fontSize) > width) { - // Break a long word into smaller parts character-by-character - const brokenParts = forceBreakLongWord( - word, - width, - font, - fontSize - ); - - // push currentLine before breaking word - if (currentLine.trim()) lines.push(currentLine.trim()); - - // push ALL broken parts in order - brokenParts.forEach((p) => lines.push(p)); - - currentLine = ""; - } else { - // push current line and start new - if (currentLine.trim()) lines.push(currentLine.trim()); - currentLine = word; - } - } - } - if (currentLine.trim()) lines.push(currentLine.trim()); - return lines; - }; - // Function to break text into lines based on when user go next line on press enter button - const breakTextIntoLines = (textContent, width) => { - const finalLines = []; - const paragraphs = textContent.split("\n"); // preserve user order - for (const para of paragraphs) { - const lineWidth = font.widthOfTextAtSize(para, fontSize); - //checking string length to container width - //if string length is less then container width it means user press enter button - if (lineWidth <= width) { - // user forced newline - finalLines.push(para); - } else { - // auto wrap paragraph - finalLines.push(...NewbreakTextIntoLines(para, width)); - } - } - - return finalLines; - }; - //check if text content have `\n` string it means user press enter to go next line and handle condition - //else auto adjust text content according to container width - const lines = isNewOnEnterLineExist - ? breakTextIntoLines(textContent, fixedWidth) - : NewbreakTextIntoLines(textContent, fixedWidth); - // Set initial y-coordinate for the first line - let x = xPos(position); - let y = yPos(position) - 4; - // Embed each line on the page - for (const line of lines) { - const textPosition = compensateRotation( - page.getRotation().angle, - x, - y, - 1, - getSize, - fontSize, - updateColorInRgb, - font, - page - ); - page.drawText(line, textPosition); - y += 18; // Adjust the line height as needed - } - } - } else if (position.type === "dropdown") { - const dropdownRandomId = "dropdown" + randomId(); - const dropdown = form.createDropdown(dropdownRandomId); - dropdown.addOptions(position?.options?.values); - if (position?.options?.response) { - dropdown.select(position.options?.response); - } else if (position?.options?.defaultValue) { - dropdown.select(position?.options?.defaultValue); - } - // Define the default appearance string - // Example format: `/FontName FontSize Tf 0 g` where: - // - `/FontName` is the name of the font (e.g., `/Helv` for Helvetica) - // - `FontSize` is the size you want to set (e.g., 12) - // - `Tf` specifies the font and size - // - `0 g` sets the text color to black - const defaultAppearance = `/Helv ${fontSize} Tf 0 g`; - // Set the default appearance for the dropdown field - dropdown.acroField.setDefaultAppearance(defaultAppearance); - dropdown.setFontSize(fontSize); - const dropdownObj = { - x: xPos(position), - y: yPos(position), - width: widgetWidth, - height: widgetHeight - }; - const dropdownOption = getWidgetPosition( - page, - dropdownObj, - 1, - getSize - ); - const dropdownSelected = { - ...dropdownOption, - font: font, - textColor: updateColorInRgb - }; - dropdown.defaultUpdateAppearances(font); - dropdown.addToPage(page, dropdownSelected); - dropdown.enableReadOnly(); - } else if (position.type === radioButtonWidget) { - const radioRandomId = "radio" + randomId(); - const radioGroup = form.createRadioGroup(radioRandomId); - //getting radio buttons options text font size - const optionsFontSize = fontSize; // font size for option text - const radioTextGapFromLeft = fontSize + 3; // gap between circle and its label - const radioSize = fontSize; // circle diameter (square of width×height) - // Initial “cursor” positions (from your existing helpers) - let currentX = xPos(position) + 2; - let currentY = yPos(position) + 3; - // Vertical gap between two options - const verticalGap = fontSize + 5; - // We’ll compute horizontalGap on the fly—after drawing each label - // Initialize to zero (will be set after first option is placed) - let horizontalGap = 0; - // Determine layout mode: 'vertical' or 'horizontal'. - // (You mentioned “add one variable called layout” – here we read it from position.layout.) - const isHorizontal = - position?.options?.layout === "horizontal" ? true : false; - // Loop through each option in the group - if (position?.options?.values?.length > 0) { - position.options.values.forEach((item, ind) => { - // 1. Advance cursor on second+ iteration - if (ind > 0) { - if (isHorizontal) { - // Move to the right by horizontalGap - currentX += horizontalGap; - } else { - // Move down by verticalGap (vertical stacking) - currentY += verticalGap; - } - } - // 2. Draw the label text (if not hidden) - if (!position?.options?.isHideLabel) { - // Compute where to draw the text (just to the right of the circle) - const labelX = currentX + radioTextGapFromLeft; - const labelY = currentY - 2; - const optionsPosition = compensateRotation( - page.getRotation().angle, - labelX, - labelY, - 1, - getSize, - optionsFontSize, - updateColorInRgb, - font, - page - ); - - page.drawText(item, optionsPosition); - } - // 3. Place the radio‐circle itself at (currentX, currentY) - let radioObj = { - x: currentX, - y: currentY, - width: radioSize, - height: radioSize - }; - - radioObj = getWidgetPosition(page, radioObj, 1, getSize); - radioGroup.addOptionToPage(item, page, radioObj); - // 4. If horizontal layout, re-compute horizontalGap for next iteration: - if (isHorizontal) { - // Measure how wide the label text is, so we know how far to shift next circle - const textWidth = font.widthOfTextAtSize(item, optionsFontSize); - // radioSize = the circle. radioTextGapFromLeft = gap between circle and label. - // Add a small extra padding (e.g. 10pt) before placing next circle. - const gap = position?.options?.isHideLabel - ? radioTextGapFromLeft - 6 - : radioTextGapFromLeft + textWidth; - horizontalGap = radioSize + gap; - } - }); - } - const isOptionExist = position?.options?.values?.some( - (x) => - x === position?.options?.response || - position?.options?.defaultValue - ); - if (isOptionExist) { - // 5. Pre‐select a value if provided - if (position?.options?.response) { - radioGroup.select(position.options?.response); - } else if (position?.options?.defaultValue) { - radioGroup.select(position?.options?.defaultValue); - } - } - // 6. Set to read‐only (if required) - radioGroup.enableReadOnly(); - } else { - const widgetRotation = position?.options?.rotation || 0; - const isSwapped = [90, 270].includes(widgetRotation); - // Use visual (swapped) dimensions to compute the correct position - const signature = { - x: xPos(position), - y: yPos(position), - width: isSwapped ? widgetHeight : widgetWidth, - height: isSwapped ? widgetWidth : widgetHeight - }; - const imageOptions = getWidgetPosition(page, signature, 1, getSize); - if (widgetRotation) { - const pageRotation = page.getRotation().angle; - const combinedRotation = degrees( - (imageOptions.rotate?.angle || pageRotation) - widgetRotation - ); - const visualWidth = imageOptions.width; - const visualHeight = imageOptions.height; - if (isSwapped) { - // Override with original (unswapped) dimensions for the actual image - imageOptions.width = visualHeight; - imageOptions.height = visualWidth; - } - imageOptions.rotate = combinedRotation; - // Adjust position to compensate for pdf-lib rotation pivot (bottom-left corner) - if (widgetRotation === 90) { - imageOptions.y += visualHeight; - } else if (widgetRotation === 180) { - imageOptions.x += imageOptions.width; - imageOptions.y += imageOptions.height; - } else if (widgetRotation === 270) { - imageOptions.x += visualWidth; - } - } - page.drawImage(img, imageOptions); - } - } catch (err) { - console.log("Err in embed widget on page ", pageNo, err); - hasError = true; // Set the flag to stop both loops - break; // Exit inner loop - } - } - form?.flatten(); - } - if (!hasError) { - const pdfBytes = await pdfDoc.saveAsBase64({ useObjectStreams: false }); - return pdfBytes; - } else { - return { - error: - "This pdf is not compatible with opensign please contact <support@opensignlabs.com>" - }; - } -}; - -// function for validating URLs -export function urlValidator(url) { - try { - const newUrl = new URL(url); - return newUrl.protocol === "http:" || newUrl.protocol === "https:"; - } catch (err) { - return false; - } -} -//calculate placeholder width to embed in pdf -export const placeholderWidth = (pos) => { - const defaultWidth = defaultWidthHeight(pos.type).width; - const posWidth = pos.Width || defaultWidth; - //condition to handle old data saved from mobile view to get widthh - if (pos.isMobile && pos.scale) { - return pos.IsResize ? posWidth : posWidth * pos.scale; - } else { - return posWidth; - } -}; - -//calculate placeholder height to embed in pdf -export const placeholderHeight = (pos) => { - const posHeight = pos.Height; - const defaultHeight = defaultWidthHeight(pos.type).height; - const posUpdateHeight = posHeight || defaultHeight; - - //condition to handle old data saved from mobile view to get height - if (pos.isMobile && pos.scale) { - return pos.IsResize ? posUpdateHeight : posUpdateHeight * pos.scale; - } else { - return posUpdateHeight; - } -}; - -//function for getting contracts_contactbook details -export const contactBook = async (objectId) => { - try { - const url = `${localStorage.getItem("baseUrl")}classes/contracts_Contactbook?where={"objectId":"${objectId}"}`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - const axiosRes = await axios.get(url, { headers }); - const result = axiosRes?.data?.results; - return result; - } catch (error) { - console.error("contracts_Contactbook error", err); - return "Error: Something went wrong!"; - } -}; - -//function for getting document details from contract_Documents class -export const contractDocument = async (documentId, include) => { - const data = { docId: documentId, include: include }; - const token = { sessionToken: localStorage.getItem("accesstoken") }; - const documentDeatils = await axios - .post(`${localStorage.getItem("baseUrl")}functions/getDocument`, data, { - headers: { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - ...token - } - }) - .then((Listdata) => { - const json = Listdata.data; - let data = []; - if (json && json.result.error) { - return json; - } else if (json && json.result) { - data.push(json.result); - return data; - } else { - return []; - } - }) - .catch((err) => { - console.log("Err in getDocument cloud function ", err); - return "Error: Something went wrong!"; - }); - - return documentDeatils; -}; - -//function for add default signature or image for all requested location -export const addDefaultSignatureImg = (xyPosition, defaultSignImg, type) => { - let xyDefaultPos = []; - for (let i = 0; i < xyPosition.length; i++) { - const getXYdata = xyPosition[i].pos; - const getPageNo = xyPosition[i].pageNumber; - const getPosData = getXYdata; - - const addSign = getPosData.map((position) => { - if (position.type) { - if (position?.type === type) { - return { - ...position, - SignUrl: defaultSignImg, - ImageType: "default", - options: { ...position.options, response: defaultSignImg } - }; - } - } else if (position && !position.isStamp) { - return { - ...position, - SignUrl: defaultSignImg, - ImageType: "default", - options: { ...position.options, response: defaultSignImg } - }; - } - return position; - }); - - const newXypos = { pageNumber: getPageNo, pos: addSign }; - xyDefaultPos.push(newXypos); - } - return xyDefaultPos; -}; - -//function for get month -export const getMonth = (date) => { - const newMonth = new Date(date).getMonth(); - return newMonth; -}; -//function to create/copy widget next to already dropped widget -export const handleCopyNextToWidget = ( - newId, - position, - xyPosition, - index, - setXyPosition, - pdfOriginalWH, - userId -) => { - let filterSignerPos; - - //Get page dimensions - const page = pdfOriginalWH?.find((x) => x?.pageNumber === index); - - const pageWidth = page?.width; - const pageHeight = page?.height; - - // Widget dimensions (fallback safe values) - const widgetWidth = position?.width || 150; - - const widgetHeight = position?.height || 60; - - const gap = 10; - - //Default copy (slightly right + down) - let newX = parseInt(position.xPosition) + gap; - let newY = parseInt(position.yPosition) + gap; - - // Prevent RIGHT overflow - if (pageWidth && newX + widgetWidth > pageWidth) { - newX = parseInt(position.xPosition) - gap; - } - if (newX < 0) newX = 0; - - // Prevent BOTTOM overflow - if (pageHeight && newY + widgetHeight > pageHeight) { - newY = pageHeight - widgetHeight - gap; - } - - if (newY < 0) newY = 0; - - // Get signer position data early for widget name generation - if (userId) { - filterSignerPos = xyPosition.find((data) => data.Id === userId); - } - - // Count same-type widgets to generate a name matching drag-and-drop convention - const countSameWidget = - filterSignerPos?.placeHolder?.reduce((count, page) => { - return ( - count + page.pos.filter((item) => item.type === position?.type).length - ); - }, 0) || 0; - const widgetName = `${position?.type}-${generateId(6)}-${countSameWidget + 1}`; - - const newposition = { - ...position, - xPosition: newX, - yPosition: newY, - key: newId, - options: { ...position?.options, name: widgetName } - }; - - //Your existing update logic - - if (userId) { - filterSignerPos = xyPosition.find((data) => data.Id === userId); - const getPlaceHolder = filterSignerPos?.placeHolder; - const getPageNumer = getPlaceHolder?.filter( - (data) => data.pageNumber === index - ); - const getXYdata = [...(getPageNumer?.[0]?.pos || []), newposition]; - if (getPageNumer && getPageNumer.length > 0) { - const newUpdateSignPos = getPlaceHolder.map((obj) => { - if (obj.pageNumber === index) { - return { ...obj, pos: getXYdata }; - } - return obj; - }); - - const newUpdateSigner = xyPosition.map((obj) => { - if (obj.Id === userId) { - return { ...obj, placeHolder: newUpdateSignPos }; - } - return obj; - }); - - setXyPosition(newUpdateSigner); - } - } else { - const getPageNumer = xyPosition?.find((data) => data.pageNumber === index); - const getXYdata = [...getPageNumer.pos, newposition]; - const updatePlaceholder = xyPosition.map((obj, ind) => { - if (obj?.pageNumber === index) { - return { ...obj, pos: getXYdata }; - } - return obj; - }); - setXyPosition(updatePlaceholder); - } -}; - -export const getFileName = (fileUrl) => { - if (fileUrl) { - const url = new URL(fileUrl); - const filename = url.pathname.substring(url.pathname.indexOf("_") + 1); - return filename || ""; - } else { - return ""; - } -}; - -//fetch tenant app logo from `partners_Tenant` class by domain name -export const getAppLogo = async () => { - const domain = window.location.host; - try { - const tenant = await Parse.Cloud.run("getlogobydomain", { - domain: domain - }); - if (tenant) { - const resolvedFavicon = - tenant?.favicon || tenant?.logo || appInfo.fev_Icon; - localStorage.setItem("appname", "OpenSign™"); - localStorage.setItem("favicon", appInfo.fev_Icon); - persistBrandPresentation( - { - appName: tenant?.appname || "OpenSign™", - logo: tenant?.logo || appInfo.applogo, - favicon: resolvedFavicon - }, - "tenant" - ); - return { - logo: tenant?.logo, - favicon: resolvedFavicon, - user: tenant?.user - }; - } - } catch (err) { - console.log("err in getlogo ", err); - localStorage.setItem("favicon", appInfo.fev_Icon); - if (err?.message?.includes("valid JSON")) { - return { logo: appInfo.applogo, user: "exist", error: "invalid_json" }; - } else { - return { logo: appInfo.applogo, user: "exist" }; - } - } -}; -export const getTenantDetails = async (objectId, contactId) => { - try { - const url = `${localStorage.getItem("baseUrl")}functions/gettenant`; - const parseAppId = localStorage.getItem("parseAppId"); - const accesstoken = localStorage.getItem("accesstoken"); - const token = { "X-Parse-Session-Token": accesstoken }; - const data = { userId: objectId, contactId: contactId }; - const res = await axios.post(url, data, { - headers: { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId, - ...token - } - }); - if (res.data.result) { - const updateRes = JSON.parse(JSON.stringify(res.data.result)); - return updateRes; - } else { - return ""; - } - } catch (err) { - console.log("err in gettenant", err); - return "user does not exist!"; - } -}; - -//function to convert variable string name to variable value of email body and subject -export function replaceMailVaribles(subject, body, variables) { - let replacedSubject = subject; - let replacedBody = body; - - for (const variable in variables) { - const regex = new RegExp(`{{${variable}}}`, "g"); - if (subject) { - replacedSubject = replacedSubject.replace(regex, variables[variable]); - } - if (body) { - replacedBody = replacedBody.replace(regex, variables[variable]); - } - } - - const result = { - subject: replacedSubject, - body: replacedBody - }; - return result; -} - -export const copytoData = (url) => { - // navigator.clipboard.writeText(text); - if (navigator.clipboard) { - navigator.clipboard.writeText(url); - } else { - // Fallback for browsers that don't support navigator.clipboard - const textArea = document.createElement("textarea"); - textArea.value = url; - document.body.appendChild(textArea); - textArea.select(); - document.execCommand("copy"); - document.body.removeChild(textArea); - } -}; - -export const convertPdfArrayBuffer = async (url) => { - try { - const response = await fetch(url); - // Check if the response was successful (status 200) - if (!response.ok) { - return "Error"; - } - // Convert the response to ArrayBuffer - const arrayBuffer = await response.arrayBuffer(); - return arrayBuffer; - } catch (error) { - console.error("Error fetching data:", error); - return "Error"; - } -}; -//`handleSendOTP` function is used to send otp on user's email using `SendOTPMailV1` cloud function -export const handleSendOTP = async (email) => { - try { - let url = `${localStorage.getItem("baseUrl")}functions/SendOTPMailV1`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId") - }; - const body = { - email: email - }; - await axios.post(url, body, { headers: headers }); - } catch (error) { - alert(error.message); - } -}; -export const fetchUrl = async (url, fileName) => { - try { - const response = await fetch(url); - if (!response.ok) { - alert(i18n.t("something-went-wrong-mssg")); - throw new Error("Network response was not ok"); - } - const blob = await response.blob(); - saveAs(blob, fileName); - } catch (error) { - alert(i18n.t("something-went-wrong-mssg")); - console.error("Error downloading the file:", error); - } -}; - -export const getSignedUrl = async (pdfUrl, docId, templateId) => { - //use only axios here due to public template sign - const token = { - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - const axiosRes = await axios.post( - `${localStorage.getItem("baseUrl")}/functions/getsignedurl`, - { - url: pdfUrl, - docId: docId || "", - templateId: templateId || "" - }, - { - headers: { - "content-type": "Application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - ...token - } - } - ); - const url = axiosRes.data.result; - return url; -}; -//download base64 type pdf -export const fetchBase64 = async (pdfBase64, pdfName) => { - // Create a Blob from the Base64 string - const byteCharacters = atob(pdfBase64); - const byteNumbers = new Array(byteCharacters.length) - .fill(0) - .map((_, i) => byteCharacters.charCodeAt(i)); - const byteArray = new Uint8Array(byteNumbers); - const blob = new Blob([byteArray], { type: "application/pdf" }); - - // Create a link element - const link = document.createElement("a"); - link.href = URL.createObjectURL(blob); - link.download = pdfName; - - // Programmatically click the link to trigger the download - document.body.appendChild(link); - link.click(); - - // Clean up - document.body.removeChild(link); - URL.revokeObjectURL(link.href); -}; -//handle download signed pdf -export const handleDownloadPdf = async ( - pdfDetails, - setIsDownloading, - pdfBase64 -) => { - const pdfName = - pdfDetails?.[0]?.Name?.length > 100 - ? pdfDetails?.[0]?.Name?.slice(0, 100) - : pdfDetails?.[0]?.Name || "Document"; - const isCompleted = pdfDetails?.[0]?.IsCompleted || false; - const formatId = pdfDetails?.[0]?.ExtUserPtr?.DownloadFilenameFormat; - const docName = buildDownloadFilename(formatId, { - docName: pdfName, - email: pdfDetails?.[0]?.ExtUserPtr?.Email, - isSigned: isCompleted - }); - if (pdfBase64) { - await fetchBase64(pdfBase64, docName); - setIsDownloading && setIsDownloading(""); - } else { - const pdfUrl = pdfDetails?.[0]?.SignedUrl || pdfDetails?.[0]?.URL; - setIsDownloading && setIsDownloading("pdf"); - const docId = pdfDetails?.[0]?.objectId || ""; - try { - const url = await getSignedUrl(pdfUrl, docId); - await fetchUrl(url, docName); - setIsDownloading && setIsDownloading(""); - } catch (err) { - console.log("err in getsignedurl", err); - setIsDownloading(""); - alert(i18n.t("something-went-wrong-mssg")); - } - } -}; - -export function fileNameWithUnderscore(pdfName) { - // Replace spaces with underscore - return pdfName.replace(/ /g, "_"); -} -//function for print digital sign pdf -export const handleToPrint = async (event, setIsDownloading, pdfDetails) => { - event.preventDefault(); - setIsDownloading("pdf"); - const pdfUrl = pdfDetails?.[0]?.SignedUrl || pdfDetails?.[0]?.URL; - const docId = pdfDetails?.[0]?.objectId || ""; - - try { - // const url = await Parse.Cloud.run("getsignedurl", { url: pdfUrl }); - //`localStorage.getItem("baseUrl")` is also use in public-profile flow for public-sign - //if we give this `appInfo.baseUrl` as a base url then in public-profile it will create base url of it's window.location.origin ex- opensign.me which is not base url - const axiosRes = await axios.post( - `${localStorage.getItem("baseUrl")}/functions/getsignedurl`, - { - url: pdfUrl, - docId: docId - }, - { - headers: { - "content-type": "Application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - } - } - ); - const url = axiosRes.data.result; - const pdf = await getBase64FromUrl(url); - const isAndroidDevice = navigator.userAgent.match(/Android/i); - const isAppleDevice = - (/iPad|iPhone|iPod/.test(navigator.platform) || - (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)) && - !window.MSStream; - if (isAndroidDevice || isAppleDevice) { - const byteArray = Uint8Array.from( - atob(pdf) - .split("") - .map((char) => char.charCodeAt(0)) - ); - const blob = new Blob([byteArray], { type: "application/pdf" }); - const blobUrl = URL.createObjectURL(blob); - window.open(blobUrl, "_blank"); - setIsDownloading(""); - } else { - printModule({ printable: pdf, type: "pdf", base64: true }); - setIsDownloading(""); - } - } catch (err) { - setIsDownloading(""); - console.log("err in getsignedurl", err); - alert(i18n.t("something-went-wrong-mssg")); - } -}; -const downloadCertificate = async (certificate, isZip, asBlob) => { - try { - const appName = "OpenSign™"; - const certificateUrl = certificate; - if (isZip) { - return certificateUrl; - } else { - if (asBlob) { - const fetchCertificate = await fetch(certificateUrl); - // Convert the response into a Blob - const blob = await fetchCertificate.blob(); - saveAs(blob, `Certificate_signed_by_${appName}.pdf`); - return; - } - saveAs(certificateUrl, `Certificate_signed_by_${appName}.pdf`); - } - } catch (err) { - console.error("download certificate err", err); - } -}; - -//handle download signed pdf -export const handleDownloadCertificate = async ( - pdfDetails, - setIsDownloading, - isZip -) => { - const baseUrl = `${localStorage.getItem("baseUrl")}functions`; - const parseAppId = localStorage.getItem("parseAppId"); - const sessionToken = localStorage.getItem("accesstoken"); - const docId = pdfDetails?.[0]?.objectId; - const initialCertificateUrl = pdfDetails?.[0]?.CertificateUrl; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": parseAppId - }; - - if (initialCertificateUrl) { - return await downloadCertificate(initialCertificateUrl, isZip); - } else { - setIsDownloading("certificate"); - try { - const data = { docId: docId }; - const docDetails = await axios.post(`${baseUrl}/getDocument`, data, { - headers: { ...headers, sessionToken } - }); - const cert = docDetails?.data?.result?.CertificateUrl; - if (cert) { - const certificateUrl = await downloadCertificate(cert, isZip); - setIsDownloading(""); - return certificateUrl; - } else { - const generateRes = await axios.post( - `${baseUrl}/generatecertificate`, - data, - { headers } - ); - const certificate = generateRes?.data?.result?.CertificateUrl; - if (certificate) { - try { - const certificateUrl = await downloadCertificate( - certificate, - isZip, - true - ); - setIsDownloading(""); - return certificateUrl; - } catch (err) { - console.error("download certificate err", err); - setIsDownloading("certificate_err"); - } - } else { - setIsDownloading("certificate_err"); - } - } - } catch (err) { - setIsDownloading("certificate_err"); - console.error("download certificate err", err); - alert(i18n.t("something-went-wrong-mssg")); - } - } - return null; -}; -// Function to escape special characters in the search string -export function escapeRegExp(string) { - return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Escape special characters -} -export async function findContact(value) { - try { - const baseURL = localStorage.getItem("baseUrl"); - const url = `${baseURL}functions/getsigners`; - const token = { - "X-Parse-Session-Token": localStorage.getItem("accesstoken") - }; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - ...token - }; - const axiosRes = await axios.post(url, { search: value }, { headers }); - const contactRes = axiosRes?.data?.result || []; - if (contactRes) { - const res = JSON.parse(JSON.stringify(contactRes)); - return res; - } - } catch (error) { - console.error("Error fetching suggestions:", error); - } -} -// `compensateRotation` is used to calculate x and y position of widget on portait, landscape pdf for pdf-lib -function compensateRotation( - pageRotation, - x, - y, - scale, - dimensions, - fontSize, - updateColorInRgb, - font, - page -) { - // Ensure pageRotation is between 0 and 360 degrees - pageRotation = ((pageRotation % 360) + 360) % 360; - let rotationRads = (pageRotation * Math.PI) / 180; - - // Coordinates are from bottom-left - let coordsFromBottomLeft = { x: x / scale }; - if (pageRotation === 90 || pageRotation === 270) { - coordsFromBottomLeft.y = dimensions.width - (y + fontSize) / scale; - } else { - coordsFromBottomLeft.y = dimensions.height - (y + fontSize) / scale; - } - - let drawX = null; - let drawY = null; - - if (pageRotation === 90) { - drawX = - coordsFromBottomLeft.x * Math.cos(rotationRads) - - coordsFromBottomLeft.y * Math.sin(rotationRads) + - dimensions.width; - drawY = - coordsFromBottomLeft.x * Math.sin(rotationRads) + - coordsFromBottomLeft.y * Math.cos(rotationRads); - } else if (pageRotation === 180) { - drawX = - coordsFromBottomLeft.x * Math.cos(rotationRads) - - coordsFromBottomLeft.y * Math.sin(rotationRads) + - dimensions.width; - drawY = - coordsFromBottomLeft.x * Math.sin(rotationRads) + - coordsFromBottomLeft.y * Math.cos(rotationRads) + - dimensions.height; - } else if (pageRotation === 270) { - drawX = - coordsFromBottomLeft.x * Math.cos(rotationRads) - - coordsFromBottomLeft.y * Math.sin(rotationRads); - drawY = - coordsFromBottomLeft.x * Math.sin(rotationRads) + - coordsFromBottomLeft.y * Math.cos(rotationRads) + - dimensions.height; - } else if (pageRotation === 0 || pageRotation === 360) { - // No rotation or full rotation - drawX = coordsFromBottomLeft.x; - drawY = coordsFromBottomLeft.y; - } - if (font) { - return { - x: drawX, - y: drawY, - font, - color: updateColorInRgb, - size: fontSize, - rotate: page.getRotation() - }; - } else { - return { x: drawX, y: drawY }; - } -} - -// `getWidgetPosition` is used to calulcate position of image type widget like x, y, width, height for pdf-lib -function getWidgetPosition(page, image, sizeRatio, getSize) { - let pageWidth; - // pageHeight; - if ([90, 270].includes(page.getRotation().angle)) { - pageWidth = getSize?.height || page.getHeight(); - } else { - pageWidth = getSize?.width || page.getWidth(); - } - // eslint-disable-next-line - if (!image?.hasOwnProperty("vpWidth")) { - image["vpWidth"] = pageWidth; - } - const pageRatio = pageWidth / (image.vpWidth * sizeRatio); - const imageWidth = image.width * sizeRatio * pageRatio; - const imageHeight = image.height * sizeRatio * pageRatio; - const imageX = image.x * sizeRatio * pageRatio; - const imageYFromTop = image.y * sizeRatio * pageRatio; - - const correction = compensateRotation( - page.getRotation().angle, - imageX, - imageYFromTop, - 1, - getSize, - imageHeight - ); - - return { - width: imageWidth, - height: imageHeight, - x: correction.x, - y: correction.y, - rotate: page.getRotation() - }; -} -//function to use calculate pdf rendering scale in the container -export const getContainerScale = (pdfOriginalWH, pageNumber, containerWH) => { - const getPdfPageWidth = pdfOriginalWH.find( - (data) => data.pageNumber === pageNumber - ); - const containerScale = containerWH?.width / getPdfPageWidth?.width || 1; - return containerScale; -}; - -//function to get current laguage and set it in local -export const saveLanguageInLocal = (i18n) => { - const detectedLanguage = i18n.language || "en"; - localStorage.setItem("i18nextLng", detectedLanguage); -}; - -// function to get default signature of current user from `contracts_Signature` class -export const getDefaultSignature = async (objectId) => { - try { - if (objectId) { - const result = await Parse.Cloud.run("getdefaultsignature", { - userId: objectId - }); - if (result) { - const res = JSON.parse(JSON.stringify(result)); - const defaultSignature = res?.ImageURL - ? await getBase64FromUrl(res?.ImageURL, true) - : ""; - const defaultInitial = res?.Initials - ? await getBase64FromUrl(res?.Initials, true) - : ""; - const defaultStamp = res?.Stamp - ? await getBase64FromUrl(res?.Stamp, true) - : ""; - - return { - status: "success", - res: { - id: result?.id, - defaultSignature: defaultSignature, - defaultInitial: defaultInitial, - defaultStamp: defaultStamp - } - }; - } - } else { - return { status: "error" }; - } - } catch (err) { - console.log( - "Error: error in fetch data in contracts_Signature", - err?.message || err - ); - return { status: "error" }; - } -}; - -//function to rotate pdf page -export async function rotatePdfPage(rotateDegree, pageNumber, pdfArrayBuffer) { - // Load the existing PDF - const pdfDoc = await PDFDocument.load(pdfArrayBuffer); - // Get the page according to page number - const page = pdfDoc.getPage(pageNumber); - //get current page rotation angle - const currentRotation = page.getRotation().angle; - // Apply the rotation in the counterclockwise direction - let newRotation = (currentRotation + rotateDegree) % 360; - // Adjust for negative angles to keep within 0-359 range - if (newRotation < 0) { - newRotation += 360; - } - page.setRotation(degrees(newRotation)); - const pdfbase64 = await pdfDoc.saveAsBase64({ useObjectStreams: false }); - //convert base64 to arraybuffer is used in pdf-lib - //pdfbase64 is used to show pdf rotated format - const arrayBuffer = base64ToArrayBuffer(pdfbase64); - //`base64` is used to show pdf - return { arrayBuffer: arrayBuffer, base64: pdfbase64 }; -} -export function base64ToArrayBuffer(base64) { - // Decode the base64 string to a binary string - const binaryString = atob(base64); - // Create a new ArrayBuffer with the same length as the binary string - const len = binaryString.length; - const bytes = new Uint8Array(len); - // Convert the binary string to a byte array - for (let i = 0; i < len; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - // Return the ArrayBuffer - return bytes.buffer; -} -export function removeBase64Prefix(base64String) { - return base64String.replace(/^data:.*;base64,/, ""); -} - -export const convertBase64ToFile = async (pdfName, pdfBase64, imgType) => { - let base64Str = pdfBase64; - const mime = imgType && imgType?.split("/")?.pop(); - let fileName = - fileNameWithUnderscore(pdfName) + (imgType ? `.${mime}` : ".pdf"); - try { - fileName = imgType ? pdfName : fileName; - const pdfFile = new Parse.File(fileName, { base64: base64Str }); - // Save the Parse File if needed - const pdfData = await pdfFile.save(); - const pdfUrl = pdfData.url(); - const fileRes = await getSecureUrl(pdfUrl); - if (fileRes?.url) { - return fileRes.url; - } - } catch (e) { - console.log("error in convertbase64tofile", e); - } -}; - -export const isCustomFileAdapter = (fileAdapterId) => - Boolean(fileAdapterId && fileAdapterId !== "opensign"); -// Shared ref that holds a pending scroll restore job for button zoom. -// RenderPdf reads this in its scale-change useEffect (same pattern as pinch). -export const pendingButtonZoomScrollRef = { current: null }; - -/** - * Call this with the scroll container ref so the zoom utils can snapshot - * the current scroll position BEFORE setScale triggers a re-render. - * - * Anchors zoom to the visible center of the viewport, so the page content - * under your eyes stays in place rather than jumping to the top. - */ -const captureScrollForButtonZoom = (scrollContainerRef, scale, newScale) => { - const el = scrollContainerRef?.current; - if (!el) return; - - const scaleRatio = newScale / scale; - - // Anchor point = center of the visible scroll container - const midRelX = el.clientWidth / 2; - const midRelY = el.clientHeight / 2; - - const docX = el.scrollLeft + midRelX; - const docY = el.scrollTop + midRelY; - - const newScrollLeft = Math.max(0, docX * scaleRatio - midRelX); - const newScrollTop = Math.max(0, docY * scaleRatio - midRelY); - - pendingButtonZoomScrollRef.current = { newScrollLeft, newScrollTop }; -}; - -export const onClickZoomIn = (scale, setScale, scrollContainerRef) => { - // Find last step smaller than current scale - const nextScale = SCALE_STEPS.find((s) => s > scale); - if (!nextScale) return; - captureScrollForButtonZoom(scrollContainerRef, scale, nextScale); - setScale(nextScale); -}; - -export const onClickZoomOut = (scale, setScale, scrollContainerRef) => { - // Find last step smaller than current scale - const prevScale = [...SCALE_STEPS].reverse().find((s) => s < scale); - if (!prevScale || prevScale < 1.0) return; - captureScrollForButtonZoom(scrollContainerRef, scale, prevScale); - setScale(prevScale); -}; -//function to use remove widgets from current page when user want to rotate page -export const handleRemoveWidgets = ( - setSignerPos, - signerPos, - pageNumber, - setIsRotate -) => { - const isSigners = signerPos.some((data) => data.signerPtr); - //placeholder,template,draftTemplate flow - if (isSigners) { - const updatedSignerPos = signerPos.map((placeholderObj) => { - return { - ...placeholderObj, - placeHolder: placeholderObj?.placeHolder?.filter( - (data) => data?.pageNumber !== pageNumber - ) - }; - }); - - if (setIsRotate) { - setSignerPos(updatedSignerPos); - setIsRotate({ status: false, degree: 0 }); - } else { - //after deleting pdf page we need to update page number of widgets - //For example, consider a PDF with 3 pages where widgets are placed on the 2nd page. - //If we delete the 1st page, the total number of pages will be reduced to 2. In this case, - // the widgets need to be updated to reflect the new page numbering and should now appear on the 1st page. - const updatePageNumber = updatedSignerPos?.map((placeholderObj) => { - return { - ...placeholderObj, - placeHolder: placeholderObj?.placeHolder?.map((data) => { - if (data.pageNumber > pageNumber) { - return { ...data, pageNumber: data.pageNumber - 1 }; - } else { - return data; - } - }) - }; - }); - setSignerPos(updatePageNumber); - } - } else { - //signyourself flow - const updatedSignerPos = signerPos?.filter( - (data) => data?.pageNumber !== pageNumber - ); - if (setIsRotate) { - setSignerPos(updatedSignerPos); - setIsRotate({ status: false, degree: 0 }); - } else { - //after deleting pdf page we need to update page number of widgets - //For example, consider a PDF with 3 pages where widgets are placed on the 2nd page. - //If we delete the 1st page, the total number of pages will be reduced to 2. In this case, - // the widgets need to be updated to reflect the new page numbering and should now appear on the 1st page. - const updatePageNumber = updatedSignerPos?.map((data) => { - if (data.pageNumber > pageNumber) { - return { ...data, pageNumber: data.pageNumber - 1 }; - } else { - return data; - } - }); - setSignerPos(updatePageNumber); - } - } -}; -//function to show warning when user rotate page and there are some already widgets on that page -export const handleRotateWarning = (signerPos, pageNumber) => { - const placeholderExist = signerPos?.some((placeholderObj) => - placeholderObj?.placeHolder?.some((data) => data?.pageNumber === pageNumber) - ); - return placeholderExist ? true : false; -}; - -// `generateTitleFromFilename` to generate Title of document from file name -export function generateTitleFromFilename(filename) { - try { - // Step 1: Trim whitespace - let title = filename.trim(); - - // Step 2: Remove the file extension (everything after the last '.') - const lastDotIndex = title.lastIndexOf("."); - if (lastDotIndex > 0) { - title = title.substring(0, lastDotIndex); - } - - // Step 3: Replace special characters (except Unicode letters, digits, spaces, and hyphens) - title = title.replace(/[^\p{L}\p{N}\s-]/gu, " "); - - // Step 4: Replace multiple spaces with a single space - title = title.replace(/\s+/g, " "); - - // Step 5: Capitalize first letter of each word (Title Case), handling Unicode characters - title = title.replace( - /\p{L}\S*/gu, - (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() - ); - - // Step 6: Restrict length of title (optional, let's say 100 characters) - if (title.length > 100) { - title = title.substring(0, 100).trim(); - } - - // Step 7: Handle empty or invalid title by falling back to "Untitled Document" - if (!title || title.length === 0) { - return "Untitled Document"; - } - - return title; - } catch (error) { - // Handle unexpected errors gracefully by returning a default title - console.error("Error generating title from filename:", error); - return "Untitled Document"; - } -} - -export const signatureTypes = [ - { name: "draw", enabled: true }, - { name: "typed", enabled: true }, - { name: "upload", enabled: true }, - { name: "default", enabled: true } -]; - -// `handleSignatureType` is used to return update signature types as per tenant or user -export async function handleSignatureType(tenantSignTypes, signatureType) { - const docSignTypes = signatureType || signatureTypes; - let updatedSignatureType = signatureType || signatureTypes; - if (tenantSignTypes?.length > 0) { - updatedSignatureType = tenantSignTypes?.map((item) => { - const match = docSignTypes.find((data) => data.name === item.name); - return match ? { ...item, enabled: match.enabled } : item; - }); - } - return updatedSignatureType; -} - -// `formatDateToDdMmmYyyy` is used to format date to dd-mmm-yyyy -export const formatDateToDdMmmYyyy = (date) => { - // Create a Date object - const newDate = new Date(date); - // Format the date - const formattedDate = newDate.toLocaleDateString("en-GB", { - day: "2-digit", - month: "short", - year: "numeric" - }); - const format = formattedDate.replaceAll(/ /g, "-"); - return format; -}; - -export const deletePdfPage = async (pdfArrayBuffer, pageNumber) => { - try { - // Load the existing PDF - const pdfDoc = await PDFDocument.load(pdfArrayBuffer); - // Get the total number of pages - const totalPages = pdfDoc.getPageCount(); - // Ensure the page index is valid - if (totalPages > 1) { - //Remove the specified page - pdfDoc.removePage(pageNumber - 1); - // Save the modified PDF - const modifiedPdfBytes = await pdfDoc.saveAsBase64({ - useObjectStreams: false - }); - const arrayBuffer = base64ToArrayBuffer(modifiedPdfBytes); - return { - arrayBuffer: arrayBuffer, - base64: modifiedPdfBytes, - remainingPages: totalPages - 1 - }; - } else { - return { totalPages: 1 }; - } - } catch (err) { - console.log("Err while deleting page", err); - } -}; - -export const reorderPdfPages = async (pdfArrayBuffer, orderArr) => { - try { - const pdfDoc = await PDFDocument.load(pdfArrayBuffer); - const newPdf = await PDFDocument.create(); - const pages = await newPdf.copyPages( - pdfDoc, - orderArr.map((n) => n - 1) - ); - pages.forEach((p) => newPdf.addPage(p)); - const pdfBase64 = await newPdf.saveAsBase64({ useObjectStreams: false }); - const arrayBuffer = base64ToArrayBuffer(pdfBase64); - return { arrayBuffer, base64: pdfBase64, totalPages: orderArr.length }; - } catch (err) { - console.log("Err while reordering pages", err); - } -}; - -// `generatePdfName` is used to generate file name -export function generatePdfName(length) { - const characters = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - let result = ""; - const charactersLength = characters.length; - - for (let i = 0; i < length; i++) { - result += characters.charAt(Math.floor(Math.random() * charactersLength)); - } - return result; -} - -// Format date and time for the selected timezone -export const formatTimeInTimezone = (date, timezone) => { - const nyDate = timezone && toZonedTime(date, timezone); - const generatedDate = timezone - ? format(nyDate, "EEE, dd MMM yyyy HH:mm:ss zzz", { timeZone: timezone }) - : new Date(date).toUTCString(); - return generatedDate; -}; - -// `usertimezone` is used to get timezone of current user -export const usertimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; -export const handleHeighlightWidget = ( - getCurrentSignerPos, - key, - pageNumber -) => { - const placeholder = getCurrentSignerPos.placeHolder; - // Find the highest zIndex value - const highestZIndex = placeholder - .flatMap((item) => item.pos.map((position) => position.zIndex)) - .reduce((max, zIndex) => (zIndex > max ? zIndex : max), -Infinity); //-Infinity represents the smallest possible number - // Update the zIndex of the current signer - const updateZindex = placeholder.map((data) => { - if (data.pageNumber === pageNumber) { - return { - ...data, - pos: data.pos.map((position) => { - if (position.key === key) { - return { ...position, zIndex: highestZIndex + 1 }; - } - return position; - }) - }; - } - return data; - }); - return updateZindex; -}; -/** - * FlattenPdf renders field values as static content and removes the interactive - * form layer. Signatures are stripped entirely. Non-widget annotations (links, - * comments, stamps) are preserved. - * @param {string | Uint8Array | ArrayBuffer} pdfFile - pdf file. - * @returns {Promise<Uint8Array>} flatPdf - PDF file in Uint8Array - */ -export const flattenPdf = async (pdfFile) => { - const pdfDoc = await PDFDocument.load(pdfFile, { ignoreEncryption: true }); - - let form; - try { - form = pdfDoc.getForm(); - } catch { - // No form, nothing to flatten - return await pdfDoc.save({ useObjectStreams: false }); - } - - const pages = pdfDoc.getPages(); - - const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica); - const helveticaBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold); - const zapf = await pdfDoc.embedFont(StandardFonts.ZapfDingbats); - - const fields = form.getFields(); - - for (const field of fields) { - const type = field.constructor.name; - - if (type === "PDFSignature") { - continue; - } - - const widgets = _safeGetWidgets(field); - - for (const widget of widgets) { - const rect = _getWidgetRect(widget, pdfDoc); - const page = _getWidgetPage(pdfDoc, pages, widget); - - if (!rect || !page) continue; - - _drawWidgetBox(page, rect); - - if (type === "PDFTextField") { - _drawTextField(page, field, rect, helvetica); - } else if (type === "PDFCheckBox") { - _drawCheckBox(page, field, rect, zapf); - } else if (type === "PDFRadioGroup") { - _drawRadioGroup(page, field, widget, rect); - } else if (type === "PDFDropdown") { - _drawDropdown(page, field, rect, helvetica); - } else if (type === "PDFOptionList") { - _drawOptionList(page, field, rect, helvetica); - } else if (type === "PDFButton") { - // Push buttons are interactive controls, not meaningful data fields. - } - } - } - - if (fields.length > 0) { - _removeWidgetAnnotations(pdfDoc); - } - - return await pdfDoc.save({ useObjectStreams: false }); -}; - -/* ---- flattenPdf private helpers ---- */ - -function _safeGetWidgets(field) { - try { - return field.acroField?.getWidgets?.() || []; - } catch { - return []; - } -} - -function _getWidgetRect(widget, pdfDoc) { - try { - const r = widget.getRectangle?.(); - if ( - r && - isFinite(r.x) && - isFinite(r.y) && - isFinite(r.width) && - isFinite(r.height) - ) { - return r; - } - } catch { - /* fall through to manual extraction */ - } - - try { - const rectArr = widget.dict?.lookup?.(PDFName.of("Rect")); - if (!rectArr || typeof rectArr.size !== "function" || rectArr.size() !== 4) - return null; - - const x1 = _numberFromPdfObject(rectArr.get(0)); - const y1 = _numberFromPdfObject(rectArr.get(1)); - const x2 = _numberFromPdfObject(rectArr.get(2)); - const y2 = _numberFromPdfObject(rectArr.get(3)); - - if ([x1, y1, x2, y2].some((v) => !isFinite(v))) return null; - - return { - x: Math.min(x1, x2), - y: Math.min(y1, y2), - width: Math.abs(x2 - x1), - height: Math.abs(y2 - y1) - }; - } catch { - return null; - } -} - -function _numberFromPdfObject(obj) { - if (!obj) return NaN; - if (typeof obj.asNumber === "function") return obj.asNumber(); - if (typeof obj.numberValue === "function") return obj.numberValue(); - return Number(obj?.value ?? obj); -} - -function _getWidgetPage(pdfDoc, pages, widget) { - try { - const pRef = widget.P?.(); - if (pRef) { - for (const page of pages) { - if (page.ref === pRef) return page; - } - } - } catch { - /* fall through */ - } - - try { - const pRef = widget.dict?.get?.(PDFName.of("P")); - if (pRef) { - for (const page of pages) { - if (page.ref === pRef) return page; - } - } - } catch { - /* fall through */ - } - - // Fallback: search page annots - try { - for (const page of pages) { - const annots = page.node.lookupMaybe(PDFName.of("Annots"), PDFArray); - if (!annots) continue; - - for (let i = 0; i < annots.size(); i++) { - const ref = annots.get(i); - if (ref === widget.ref) return page; - } - } - } catch { - /* fall through */ - } - - return null; -} - -function _drawWidgetBox(page, rect) { - try { - page.drawRectangle({ - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - borderWidth: 0.6, - borderColor: rgb(0.65, 0.65, 0.65) - }); - } catch { - /* best effort */ - } -} - -function _drawTextField(page, field, rect, font) { - let text = ""; - try { - text = field.getText?.() ?? ""; - } catch { - text = ""; - } - text = String(text ?? ""); - - if (!text) return; - - let multiline = false; - try { - multiline = field.isMultiline?.() ?? false; - } catch { - /* ignore */ - } - - let comb = false; - try { - comb = field.isCombed?.() ?? false; - } catch { - /* ignore */ - } - - if (comb) { - _drawCombText(page, text, rect, font); - return; - } - - if (multiline || text.includes("\n")) { - _drawMultilineText(page, text, rect, font); - return; - } - - const fontSize = _fitSingleLineFontSize(text, rect, font); - const baselineY = rect.y + Math.max(2, (rect.height - fontSize) / 2); - - page.drawText(text, { - x: rect.x + 2, - y: baselineY, - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 4) - }); -} - -function _drawMultilineText(page, text, rect, font) { - const lines = String(text).replace(/\r/g, "").split("\n"); - const fontSize = Math.max( - 8, - Math.min(11, rect.height / Math.max(lines.length + 0.5, 2)) - ); - const lineHeight = fontSize + 1.5; - - let y = rect.y + rect.height - fontSize - 2; - - for (const line of lines) { - if (y < rect.y + 1) break; - - page.drawText(line, { - x: rect.x + 2, - y, - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 4), - lineHeight - }); - - y -= lineHeight; - } -} - -function _drawCombText(page, text, rect, font) { - const chars = String(text).split(""); - const count = Math.max(chars.length, 1); - const cellWidth = rect.width / count; - const fontSize = Math.max(8, Math.min(12, rect.height - 4)); - - chars.forEach((ch, i) => { - const textWidth = font.widthOfTextAtSize(ch, fontSize); - const x = rect.x + i * cellWidth + (cellWidth - textWidth) / 2; - const y = rect.y + Math.max(2, (rect.height - fontSize) / 2); - - page.drawText(ch, { - x, - y, - size: fontSize, - font, - color: rgb(0, 0, 0) - }); - - if (i < count - 1) { - try { - page.drawLine({ - start: { x: rect.x + (i + 1) * cellWidth, y: rect.y }, - end: { - x: rect.x + (i + 1) * cellWidth, - y: rect.y + rect.height - }, - thickness: 0.4, - color: rgb(0.75, 0.75, 0.75) - }); - } catch { - /* best effort */ - } - } - }); -} - -function _fitSingleLineFontSize(text, rect, font) { - let size = Math.min(12, rect.height - 4); - size = Math.max(size, 6); - - while (size > 6) { - const width = font.widthOfTextAtSize(text, size); - if (width <= rect.width - 4) return size; - size -= 0.5; - } - - return 6; -} - -function _drawCheckBox(page, field, rect, zapf) { - let checked = false; - try { - checked = field.isChecked(); - } catch { - checked = false; - } - - if (!checked) return; - - const size = Math.max(8, Math.min(rect.width, rect.height) - 4); - - page.drawText("\u2714", { - x: rect.x + Math.max(1, (rect.width - size * 0.7) / 2), - y: rect.y + Math.max(1, (rect.height - size) / 2), - size, - font: zapf, - color: rgb(0, 0, 0) - }); -} - -function _drawRadioGroup(page, field, widget, rect) { - let selected = null; - try { - selected = field.getSelected(); - } catch { - selected = null; - } - - if (!selected) return; - - let widgetOnValue = null; - try { - widgetOnValue = widget.getOnValue?.(); - } catch { - /* ignore */ - } - - if (!widgetOnValue) { - try { - const ap = widget.dict?.lookupMaybe?.(PDFName.of("AP"), PDFDict); - const n = ap?.lookupMaybe?.(PDFName.of("N"), PDFDict); - if (n) { - const keys = n.keys(); - for (const k of keys) { - const name = k?.decodeText?.() ?? k?.encodedName ?? String(k); - if (name !== "/Off" && name !== "Off") { - widgetOnValue = name.replace(/^\//, ""); - break; - } - } - } - } catch { - /* ignore */ - } - } - - const selectedStr = String(selected).replace(/^\//, ""); - const onStr = String(widgetOnValue ?? "").replace(/^\//, ""); - - if (!onStr || selectedStr !== onStr) return; - - // Circle outline - try { - page.drawEllipse({ - x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2, - xScale: rect.width / 2 - 1, - yScale: rect.height / 2 - 1, - borderWidth: 0.8, - borderColor: rgb(0, 0, 0) - }); - } catch { - /* best effort */ - } - - // Inner filled dot (drawn as a filled ellipse instead of a text glyph - // so we avoid WinAnsi encoding issues with bullet characters) - try { - const r = Math.min(rect.width, rect.height) / 4; - page.drawEllipse({ - x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2, - xScale: r, - yScale: r, - color: rgb(0, 0, 0) - }); - } catch { - /* best effort */ - } -} - -function _drawDropdown(page, field, rect, font) { - let text = ""; - try { - const selected = field.getSelected?.(); - if (Array.isArray(selected)) { - text = selected.join(", "); - } else { - text = selected ?? ""; - } - } catch { - text = ""; - } - - text = String(text ?? ""); - if (!text) return; - - const fontSize = _fitSingleLineFontSize(text, rect, font); - - page.drawText(text, { - x: rect.x + 2, - y: rect.y + Math.max(2, (rect.height - fontSize) / 2), - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 12) - }); -} - -function _drawOptionList(page, field, rect, font) { - let selected = []; - try { - selected = field.getSelected?.() || []; - } catch { - selected = []; - } - - if (!Array.isArray(selected)) { - selected = [selected].filter(Boolean); - } - - if (!selected.length) return; - - const lines = selected.map((v) => String(v)); - const fontSize = Math.max( - 8, - Math.min(11, rect.height / Math.max(lines.length + 0.5, 2)) - ); - const lineHeight = fontSize + 1.5; - - let y = rect.y + rect.height - fontSize - 2; - - for (const line of lines) { - if (y < rect.y + 1) break; - - page.drawText(line, { - x: rect.x + 2, - y, - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 4) - }); - - y -= lineHeight; - } -} - -/** Remove only Widget annotations; preserve links, stamps, comments, etc. */ -function _removeWidgetAnnotations(pdfDoc) { - for (const page of pdfDoc.getPages()) { - try { - const annotationsRef = page.node.get(PDFName.of("Annots")); - if (!annotationsRef) continue; - - const annotations = pdfDoc.context.lookup(annotationsRef); - if (!annotations || !annotations.asArray) continue; - - const filtered = annotations.asArray().filter((annotRef) => { - try { - const annot = pdfDoc.context.lookup(annotRef); - const subtype = annot?.get(PDFName.of("Subtype")); - return subtype?.toString() !== "/Widget"; - } catch { - return true; - } - }); - - if (filtered.length === 0) { - page.node.delete(PDFName.of("Annots")); - } else { - page.node.set(PDFName.of("Annots"), pdfDoc.context.obj(filtered)); - } - } catch { - /* best effort */ - } - } - - try { - pdfDoc.catalog.delete(PDFName.of("AcroForm")); - } catch { - /* best effort */ - } -} - -export const mailTemplate = (param) => { - const { appName, logoUrl, accentColor } = resolveMailBrandPresentation(""); - const logo = renderMailBrandLogo({ appName, logoUrl }); - - const subject = `${param.senderName} has requested you to sign "${param.title}"`; - const body = - "<html><head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8' /></head><body><div style='background-color:#f5f5f5;padding:20px'><div style='background:white;padding-bottom:20px'>" + - logo + - `<div style='padding:2px;font-family:system-ui;background-color:${accentColor}'><p style='font-size:20px;font-weight:400;color:white;padding-left:20px'>Digital Signature Request</p></div><div><p style='padding:20px;font-size:14px;margin-bottom:10px'>` + - param.senderName + - " has requested you to review and sign <strong>" + - param.title + - "</strong>.</p><div style='padding: 5px 0px 5px 25px;display:flex;flex-direction:row;justify-content:space-around'><table><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td><td></td><td style='color:#626363;font-weight:bold'>" + - param.senderMail + - "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td><td></td><td style='color:#626363;font-weight:bold'> " + - param.organization + - "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td></td><td style='color:#626363;font-weight:bold'>" + - param.localExpireDate + - "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Note</td><td></td><td style='color:#626363;font-weight:bold'>" + - param.note + - "</td></tr><tr><td></td><td></td></tr></table></div> <div style='margin-left:70px'><a target=_blank href=" + - param.signingUrl + - "><button style='padding:12px;background-color:#d46b0f;color:white;border:0px;font-weight:bold;margin-top:30px'>Sign here</button></a></div><div style='display:flex;justify-content:center;margin-top:10px'></div></div></div><div><p> This is an automated email from " + - appName + - ". For any queries regarding this email, please contact the sender " + - param.senderMail + - " directly.</p></div></div></body></html> "; - return { subject, body }; -}; - -export function formatDateTime(date, dateFormat, timeZone, is12Hour) { - const zonedDate = toZonedTime(date, timeZone); // Convert date to the given timezone - const timeFormat = is12Hour ? "hh:mm:ss a" : "HH:mm:ss"; - return dateFormat - ? format( - zonedDate, - `${selectFormat(dateFormat)}, ${timeFormat} 'GMT' XXX`, - { timeZone } - ) - : formatTimeInTimezone(date, timeZone); -} - -export const updateDateWidgetsRes = ( - documentData, - signerId, - journey, - isRemovePrefill -) => { - const contactUser = documentData?.Signers?.find( - (data) => data.objectId === signerId - ); - const extUser = - localStorage.getItem("Extand_Class") || JSON.stringify([contactUser]); - let placeHolders = documentData?.Placeholders; - if (isRemovePrefill) { - placeHolders = placeHolders?.filter((x) => x.Role !== "prefill"); - } - const userDetails = extUser ? JSON.parse(extUser)[0] : contactUser; - return placeHolders?.map((item) => { - if (item?.signerObjId === signerId || item?.Id === signerId) { - // Sort page number placeholders - const placeHolder = Array.isArray(item.placeHolder) - ? [...item.placeHolder] - : []; - const sortedPlaceHolder = placeHolder - .sort((a, b) => a.pageNumber - b.pageNumber) - .map((ph) => { - const sortedWidgets = [...ph.pos] - .sort((a, b) => { - // Sort widgets by Y position (top to bottom) and X position (left to right) - // Treat widgets within 5px Y difference as belonging to the same row - const Y_TOLERANCE = 5; - const yDiff = a.yPosition - b.yPosition; - - if (Math.abs(yDiff) <= Y_TOLERANCE) { - return a.xPosition - b.xPosition; // Same row → sort by X - } - - return yDiff; // Different rows → sort by Y - }) - .map((widget) => { - // Update widget values if needed - if ( - ["name", "email", "job title", "company"].includes( - widget.type - ) && - !widget.options.defaultValue && - !widget.options.response && - userDetails - ) { - return { - ...widget, - options: { - ...widget.options, - response: widgetDataValue(widget.type, userDetails) - } - }; - } - return widget; - }); - let widgetsWithResponses = sortedWidgets; - return { ...ph, pos: widgetsWithResponses }; - }); - return { - ...item, - placeHolder: applyDuplicateResponsesToPages(sortedPlaceHolder) - }; - } - - return item; - }); -}; - -//function for show checked checkbox -export const selectCheckbox = (ind, selectedCheckbox) => { - if (selectedCheckbox && selectedCheckbox?.length > 0) { - const isCheck = selectedCheckbox?.some((data) => data === ind); - return isCheck || false; - } -}; -export const checkRegularExpress = (validateType, setValidatePlaceholder) => { - switch (validateType) { - case "email": - setValidatePlaceholder("demo@gmail.com"); - break; - case "number": - setValidatePlaceholder("12345"); - break; - case "text": - setValidatePlaceholder("please enter text"); - break; - case "ssn": - setValidatePlaceholder("123-45-6789"); - break; - default: - setValidatePlaceholder("please enter value"); - } -}; -//function to use unlink signer from widgets -export const handleUnlinkSigner = ( - signerPos, - setSignerPos, - signersdata, - setSignersData, - uniqueId -) => { - //remove existing signer's details from 'signerPos' array - const updatePlaceHolder = signerPos.map((x) => { - if (x.Id === uniqueId) { - return { ...x, signerPtr: {}, signerObjId: "" }; - } - return { ...x }; - }); - setSignerPos(updatePlaceHolder); - //remove existing signer's details from 'signersdata' array and keep role and id - const updateSigner = signersdata.map((item) => { - if (item.Id == uniqueId) { - return { Role: item.Role, Id: item.Id, blockColor: item.blockColor }; - } - return item; - }); - setSignersData(updateSigner); -}; -//function is used to get pdf original width and height -export const getOriginalWH = async (pdf) => { - let pdfWHObj = []; - //get total page number - const totalPages = pdf?.numPages; - //according to page number get all pdf's pages width and height - for (let index = 0; index < totalPages; index++) { - try { - const getPage = await pdf.getPage(index + 1); - const scale = 1; - //getting extra height which is removed from viewPort height (letter type pdf have originial h-799.92 but using getPage.getViewport getting height-792 something diffrence-7.92px) - //getPage?.view[1] store diffrence of height (Page starts 7.92 from bottom) - const y0 = getPage?.view[1] || 0; - let { width, height } = getPage.getViewport({ scale }); - //adding it on viewPort height then get original height ex- 792+7.92 = 799.92 orignial height - height = height + y0; - pdfWHObj.push({ pageNumber: index + 1, width, height }); - } catch (e) { - console.log(`Error getting page ${index + 1} of PDF: ${e.message}`); - } - } - return pdfWHObj; -}; - -//function is used to check required and optional widgets and ensure required widget should be response -export const handleCheckResponse = (checkUser, setminRequiredCount) => { - let checkboxExist, - showAlert = false, - widgetKey, - requiredCheckbox, - tourPageNumber; // `pageNumber` is used to check on which page user did not fill widget's data then change current pageNumber and show tour message on that page - for (let i = 0; i < checkUser[0].placeHolder.length; i++) { - for (let j = 0; j < checkUser[0].placeHolder[i].pos.length; j++) { - //get current page - const updatePage = checkUser[0].placeHolder[i]?.pageNumber; - //checking checbox type widget - checkboxExist = checkUser[0].placeHolder[i].pos[j].type === "checkbox"; - //condition to check checkbox widget exist or not - if (checkboxExist) { - //get all required type checkbox - requiredCheckbox = checkUser[0].placeHolder[i].pos.filter( - (position) => { - return ( - !position.options?.isReadOnly && position.type === "checkbox" - ); - } - ); - //if required type checkbox data exit then check user checked all checkbox or some checkbox remain to check - //also validate to minimum and maximum required checkbox - if (requiredCheckbox && requiredCheckbox.length > 0) { - for (let i = 0; i < requiredCheckbox.length; i++) { - //get minimum required count if exit - const minCount = - requiredCheckbox[i].options?.validation?.minRequiredCount; - const parseMin = minCount && parseInt(minCount); - //get maximum required count if exit - const maxCount = - requiredCheckbox[i].options?.validation?.maxRequiredCount; - const parseMax = maxCount && parseInt(maxCount); - //in `response` variable is used to get how many checkbox checked by user - const response = requiredCheckbox[i].options?.response?.length; - //in `defaultValue` variable is used to get how many checkbox checked by default - const defaultValue = - requiredCheckbox[i].options?.defaultValue?.length; - const checkboxValue = response ? response : defaultValue; - //condition to check parseMin and parseMax greater than 0 then consider it as a required check box - if ( - parseMin > 0 && - parseMax > 0 && - !response && - !defaultValue && - !showAlert - ) { - showAlert = true; - widgetKey = requiredCheckbox[i].key; - tourPageNumber = updatePage; - setminRequiredCount(parseMin); - } - //else condition to validate minimum required checkbox - else if ( - parseMin > 0 && - (parseMin > checkboxValue || !checkboxValue) - ) { - if (!showAlert) { - showAlert = true; - widgetKey = requiredCheckbox[i].key; - tourPageNumber = updatePage; - setminRequiredCount(parseMin); - } - } - } - } - } - //else condition to check all type widget data fill or not except checkbox - else { - //get all required type widgets except checkbox and radio - const requiredWidgets = checkUser[0].placeHolder[i].pos.filter( - (position) => { - return ( - position.type === "signature" || - (position.options?.status === "required" && - position.type !== "checkbox") - ); - } - ); - if (requiredWidgets && requiredWidgets?.length > 0) { - let checkSigned; - for (let i = 0; i < requiredWidgets?.length; i++) { - checkSigned = requiredWidgets[i]?.options?.response; - if (isEmptyValue(checkSigned)) { - let checkDefaultSigned = - requiredWidgets[i]?.options?.defaultValue; - if (isEmptyValue(checkDefaultSigned) && !showAlert) { - showAlert = true; - widgetKey = requiredWidgets[i].key; - tourPageNumber = updatePage; - setminRequiredCount(null); - } - } - } - } - } - } - //when showAlert is true then break the loop and show alert to fill required data in widgets - if (showAlert) { - break; - } - } - return { tourPageNumber, widgetKey, showAlert }; -}; - -/** - * decryptPdf - * @param {File} file - The password-protected PDF file to decrypt. - * @param {string | undefined} password - The password used to unlock the PDF. - * @returns {Promise<File>} - A Promise that resolves to a decrypted PDF as a File object. - * - */ -export const decryptPdf = async (file, password) => { - const name = generatePdfName(16); - const baseApi = localStorage.getItem("baseUrl") || ""; - const url = removeTrailingSegment(baseApi) + "/decryptpdf?ts=" + Date.now(); - let formData = new FormData(); - formData.append("file", file); - formData.append("password", password); - const config = { - headers: { "content-type": "multipart/form-data" }, - responseType: "blob" - }; - const response = await axios.post(url, formData, config); - const pdfBlob = new Blob([response.data], { type: "application/pdf" }); - return new File([pdfBlob], name, { type: "application/pdf" }); -}; - -/** - * Convert a Base64 string to a File object. - * - * @param {string} base64String - The Base64 string, with or without the data URI prefix. - * e.g. "data:image/png;base64,iVBORw0KGgoAAAANS…" or "iVBORw0KGgoAAAANS…" - * @param {string} filename - Desired filename for the File object, e.g. "photo.png" - * @returns {File} - The resulting File object - */ -export function base64ToFile(base64String, filename) { - // Separate out the mime-type and the actual Base64 payload - const [header, payload] = base64String.includes(",") - ? base64String.split(",") - : [null, base64String]; - // Determine the MIME type (fallback to application/octet-stream) - const mimeMatch = header?.match(/data:(.*?);base64/); - const mime = mimeMatch ? mimeMatch[1] : "application/octet-stream"; - - // Decode Base64 to raw binary data held in a string - const binaryString = atob(payload); - // Create an ArrayBuffer and a view (as unsigned 8-bit) - const len = binaryString.length; - const u8arr = new Uint8Array(len); - for (let i = 0; i < len; i++) { - u8arr[i] = binaryString.charCodeAt(i); - } - - // Create a File object (Blob subclass) with the binary data - return new File([u8arr], filename, { type: mime }); -} - -/** - * Reads the given File object and returns its contents as an ArrayBuffer. - * - * @param {File} file - * The File instance to be read. - * @returns {Promise<ArrayBuffer>} - * A promise that resolves with the file’s binary data as an ArrayBuffer, - * or rejects with an error if the read fails. - */ -export function getFileAsArrayBuffer(file) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = (e) => resolve(e.target.result); - reader.onerror = (e) => reject(e.target.error); - reader.readAsArrayBuffer(file); - }); -} - -export const sendEmailToSigners = async ( - pdfDetails, - signersdata, - customizeMail, - defaultMail, - isCustomize -) => { - let htmlReqBody; - const owner = pdfDetails?.[0]?.ExtUserPtr; - let sendMail; - const getDocumentExpDate = pdfDetails?.[0]?.ExpiryDate?.iso; - const getTemplateExpDate = new Date(pdfDetails[0]?.createdAt); - getTemplateExpDate.setDate( - getTemplateExpDate.getDate() + (pdfDetails[0]?.TimeToCompleteDays || 15) - ); - const expireDate = getDocumentExpDate - ? getDocumentExpDate - : getTemplateExpDate; - const newDate = new Date(expireDate); - const localExpireDate = newDate.toLocaleDateString("en-US", { - day: "numeric", - month: "long", - year: "numeric" - }); - - let senderEmail = - pdfDetails?.[0]?.SenderMail || pdfDetails?.[0]?.ExtUserPtr?.Email; - let senderPhone = pdfDetails?.[0]?.ExtUserPtr?.Phone; - let signerMail = signersdata.slice(); - if (pdfDetails?.[0]?.SendinOrder && pdfDetails?.[0]?.SendinOrder === true) { - signerMail = signerMail[0] ? [signerMail[0]] : []; - } - for (let i = 0; i < signerMail.length; i++) { - try { - let url = `${localStorage.getItem("baseUrl")}functions/sendmailv3`; - const headers = { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - sessionToken: localStorage.getItem("accesstoken") - }; - const objectId = signerMail[i].objectId; - const hostUrl = window.location.origin; - //encode this url value `${pdfDetails?.[0].objectId}/${signerMail[i].Email}/${objectId}` to base64 using `btoa` function - const encodeBase64 = btoa( - `${pdfDetails[0]?.objectId}/${signerMail[i].Email}/${objectId}` - ); - let signPdf = `${hostUrl}/login/${encodeBase64}`; - const orgName = pdfDetails[0]?.ExtUserPtr.Company - ? pdfDetails[0].ExtUserPtr.Company - : ""; - - const useNameAsSender = - pdfDetails?.[0]?.ExtUserPtr?.UseNameAsSender === true; - - const senderName = - pdfDetails?.[0]?.SenderName || pdfDetails?.[0]?.ExtUserPtr?.Name; - - const from = - pdfDetails?.[0]?.SenderName || useNameAsSender - ? pdfDetails?.[0]?.ExtUserPtr?.Name || "" - : senderEmail; - - const documentName = `${pdfDetails?.[0].Name}`; - let replaceVar; - - if (customizeMail && isCustomize) { - const replacedRequestBody = customizeMail?.body.replace(/"/g, "'"); - htmlReqBody = - "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body>" + - replacedRequestBody + - "</body> </html>"; - - const variables = { - document_title: documentName, - note: pdfDetails?.[0]?.Note, - sender_name: senderName, - sender_mail: senderEmail, - sender_phone: senderPhone || "", - receiver_name: signerMail[i]?.Name || "", - receiver_email: signerMail[i].Email, - receiver_phone: signerMail[i]?.Phone || "", - expiry_date: localExpireDate, - company_name: orgName, - signing_url: signPdf - }; - replaceVar = replaceMailVaribles( - customizeMail.subject, - htmlReqBody, - variables - ); - } else if (defaultMail?.body && defaultMail?.subject) { - const mailBody = defaultMail?.body; - const mailSubject = defaultMail.subject; - const replacedRequestBody = mailBody.replace(/"/g, "'"); - const htmlReqBody = - "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body>" + - replacedRequestBody + - "</body> </html>"; - const variables = { - document_title: documentName, - note: pdfDetails?.[0]?.Note, - sender_name: senderName, - sender_mail: senderEmail, - sender_phone: senderPhone || "", - receiver_name: signerMail[i]?.Name || "", - receiver_email: signerMail[i].Email, - receiver_phone: signerMail[i]?.Phone || "", - expiry_date: localExpireDate, - company_name: orgName, - signing_url: signPdf - }; - replaceVar = replaceMailVaribles(mailSubject, htmlReqBody, variables); - } - const mailparam = { - senderName: senderName, - note: pdfDetails?.[0]?.Note || "", - senderMail: senderEmail, - title: documentName, - organization: orgName, - localExpireDate: localExpireDate, - signingUrl: signPdf - }; - // Pick a role-appropriate default template (viewers get a "view" - // template instead of the "sign" template). - const defaultTemplate = mailTemplate(mailparam); - let params = { - extUserId: owner?.objectId, - recipient: signerMail[i].Email, - subject: replaceVar?.subject - ? replaceVar?.subject - : defaultTemplate.subject, - replyto: senderEmail, - from: from, - html: replaceVar?.body ? replaceVar?.body : defaultTemplate.body - }; - - sendMail = await axios.post(url, params, { headers: headers }); - } catch (error) { - console.log("error", error); - } - } - if (sendMail?.data?.result?.status === "success") { - const sessiontoken = localStorage.getItem("accesstoken"); - if (pdfDetails[0]?.objectId && sessiontoken) { - try { - let data; - if (customizeMail && isCustomize) { - data = { - RequestBody: customizeMail?.body, - RequestSubject: customizeMail.subject, - SendMail: true - }; - } else if (defaultMail?.body && defaultMail?.subject) { - data = { - RequestBody: defaultMail?.body, - RequestSubject: defaultMail?.subject, - SendMail: true - }; - } else { - data = { SendMail: true }; - } - const docUrl = `${localStorage.getItem("baseUrl")}classes/contracts_Document`; - await axios.put(`${docUrl}/${pdfDetails[0]?.objectId}`, data, { - headers: { - "Content-Type": "application/json", - "X-Parse-Application-Id": localStorage.getItem("parseAppId"), - "X-Parse-Session-Token": sessiontoken - } - }); - } catch (error) { - const err = error?.response?.data?.error || error?.message; - console.error("Error while updating doc: ", err); - } - } - return { status: "success" }; - } else { - return { status: sendMail?.data?.result?.status }; - } -}; -/** - * Converts a JPEG/JPG File/Blob into a PNG File. - * - * @param {string} base64Image - A data-URL (e.g. "data:image/jpeg;base64,…") - * @param {string} filename - Desired filename (e.g. "input"). - * @returns {Promise<File>} - A promise that resolves with a new PNG File. - */ -export function convertJpegToPng(base64Image, filename) { - if (base64Image) { - const arr = base64Image.split(","); - const mimeMatch = arr[0].match(/:(.*?);/); - if (!mimeMatch) throw new Error("Invalid dataURL"); - const mime = mimeMatch[1]; - const type = mime.split("/")[1]; - if (type === "png") { - return base64Image; - } else { - const bstr = atob(arr[1]); - let n = bstr.length; - const u8arr = new Uint8Array(n); - while (n--) u8arr[n] = bstr.charCodeAt(n); - const inputFile = new File([u8arr], `${filename}.${type}`, { - type: mime - }); - return new Promise((resolve, reject) => { - // ensure it’s JPEG/JPG (you can remove this check if not needed) - if (!/image\/jpe?g/.test(inputFile.type)) { - return reject(new Error("Input must be a JPEG or JPG image")); - } - - // Read the file as a data URL - const reader = new FileReader(); - reader.onerror = () => reject(new Error("Failed to read the file")); - reader.onload = () => { - const img = new Image(); - img.onerror = () => reject(new Error("Failed to load image")); - img.onload = () => { - // draw image onto a canvas - const canvas = document.createElement("canvas"); - canvas.width = img.width; - canvas.height = img.height; - const ctx = canvas.getContext("2d"); - ctx.drawImage(img, 0, 0); - - // directly get PNG as base64 data URL - try { - const pngDataUrl = canvas.toDataURL("image/png"); - resolve(pngDataUrl); - } catch (err) { - reject(new Error("Failed to convert canvas to PNG")); - } - }; - img.src = reader.result; - }; - reader.readAsDataURL(inputFile); - }); - } - } -} -//function is used to get assigned signer's email -export const getSignerEmail = (data, signers) => { - const getEmail = - signers?.length > 0 && - signers.find((x) => x.objectId === data.signerObjId)?.Email; - return getEmail; -}; - -//function is used to delete widgets -export const handleDeleteWidget = (key, Id, pageNumber, signerPos) => { - // Find the signer by ID - const signer = signerPos.find((item) => item.Id === Id); - if (!signer || !signer.placeHolder) return signerPos; - - const placeHolder = signer.placeHolder; - - // Find the page inside placeHolder - const currentPage = placeHolder.find((p) => p.pageNumber === pageNumber); - if (!currentPage) return signerPos; - - // Remove widget from the selected page - const updatedPos = currentPage.pos.filter((w) => w.key !== key); - - // ------------------------------------------------------- - // CASE A → After deletion, page still has widgets then keep that widgets - // ------------------------------------------------------- - if (updatedPos.length > 0) { - const updatedPlaceHolder = placeHolder.map((p) => - p.pageNumber === pageNumber ? { ...p, pos: updatedPos } : p - ); - - return signerPos.map((s) => - s.Id === Id ? { ...s, placeHolder: updatedPlaceHolder } : s - ); - } - - // ------------------------------------------------------- - // CASE B → current page becomes empty → remove current page entirely and keep another pages which have widgets - // ------------------------------------------------------- - const remainPages = placeHolder.filter((p) => p.pageNumber !== pageNumber); - - //`remainPages` keep another pages's data which have widgets - if (remainPages.length > 0) { - const index = signerPos.findIndex((s) => s.Id === Id); - if (index === -1) return signerPos; - - const newSignerPos = [...signerPos]; - newSignerPos[index] = { - ...newSignerPos[index], - placeHolder: remainPages - }; - - return newSignerPos; - } - - // ------------------------------------------------------- - // CASE C → No pages have widgets after delete widgets - // Remove placeHolder field for particular signers, EXCEPT prefill role - // ------------------------------------------------------- - const updatedData = signerPos - .map((s) => { - if (s.Id === Id && s.Role === "prefill") return null; // remove whole signer - if (s.Id === Id) { - const updated = { ...s }; - delete updated.placeHolder; - return updated; - } - return s; - }) - .filter(Boolean); // remove nulls (deleted items) - - return updatedData; -}; -//function to convert formatted date to new Date() format -export const getDefaultDate = (dateStr, format) => { - //get valid date format for moment to convert formatted date to new Date() format - const formats = changeDateToMomentFormat(format); - const parsedDate = moment(dateStr, formats); - let date; - if (parsedDate.isValid()) { - date = new Date(parsedDate.toISOString()); - return date; - } else if (dateStr === "today") { - date = new Date(); - return date; - } -}; -//function to get default format -export const getDefaultFormat = (dateFormat) => dateFormat || "MM/dd/yyyy"; - -//function to handle widget background color -export const handleBackground = (data, isNeedSign, uniqueId) => { - if (data) { - if (isNeedSign) { - if (data?.Id === uniqueId) { - return data?.blockColor + "b0"; - } else { - return "#dedddc"; - } - } else { - return data?.blockColor + "b0"; - } - } else { - return "rgba(203, 233, 237, 0.69)"; - } -}; - -export function getBase64MimeType(base64) { - const match = base64.match(/^data:(image\/[a-zA-Z0-9+.-]+);base64,/); - return match ? match[1] : null; -} +// Public facade for the OpenSign utility modules. +export { fontsizeArr, getFontSizeForHeight, fontColorArr, isMobile, isTab, isHighResolution, isTabAndMobile, textInputWidget, drawWidget, textWidget, radioButtonWidget, isRadioSelected, cellsWidget, getEnv, defaultMailBody, defaultMailSubject, nonPresentMaskCss, randomId, range, getYear, years, months, fileasbytes, openInNewTab, getUserCountry, getSecureUrl, generateId, removeTrailingSegment, color, saveLanguageInLocal, usertimezone, contractUsers, getBase64FromUrl } from "./utils/coreConstants.js"; +export { nameColor, toDataUrl, getDrive, pdfNewWidthFun, handleWidgetResize, widgets, getDate, selectFormat } from "./utils/widgetCatalog.js"; +export { changeDateToMomentFormat, getSignerPages, addWidgetOptions, addWidgetSelfsignOptions } from "./utils/widgetOptions.js"; +export { defaultWidthHeight, arrayBufferToBase64, getBase64FromIMG, convertPNGtoJPEG, handleSignYourselfWidgetResize } from "./utils/widgetSizing.js"; +export { signPdfFun, createDocument, getFirstLetter } from "./utils/UtilsPart05.js"; +export { darkenColor, addZIndex, nextPendingWidget } from "./utils/widgetState.js"; +export { onChangeInput } from "./utils/widgetInput.js"; +export { onChangeHeightOfTextArea, calculateInitialWidthHeight, widgetDataValue, addInitialData, embedDocId, convertTextToImg } from "./utils/widgetInlineEditing.js"; +export { onSaveSign, clearResponse, convertBase64ToImg, handleCopySignUrl, calculateImgAspectRatio } from "./utils/signatureSave.js"; +export { onSaveImage, onImageSelect, compressedFileSize, fetchImageBase64, changeImageWH, isBase64, isEmptyValue } from "./utils/imageHandling.js"; +export { embedWidgetsToDoc } from "./utils/widgetEmbedding.js"; +export { urlValidator, placeholderWidth, placeholderHeight, contactBook, contractDocument, addDefaultSignatureImg, getMonth, handleCopyNextToWidget, getFileName } from "./utils/placeholderTools.js"; +export { getAppLogo, getTenantDetails, replaceMailVaribles, copytoData, convertPdfArrayBuffer, handleSendOTP, fetchUrl, getSignedUrl, fetchBase64, handleDownloadPdf, fileNameWithUnderscore } from "./utils/tenantDownloads.js"; +export { handleToPrint, handleDownloadCertificate, escapeRegExp, findContact } from "./utils/printCertificates.js"; +export { getContainerScale, getDefaultSignature, rotatePdfPage, base64ToArrayBuffer, removeBase64Prefix, convertBase64ToFile, isCustomFileAdapter, pendingButtonZoomScrollRef, onClickZoomIn, onClickZoomOut, handleRemoveWidgets, handleRotateWarning } from "./utils/pdfPageView.js"; +export { generateTitleFromFilename, signatureTypes, handleSignatureType, formatDateToDdMmmYyyy, deletePdfPage, reorderPdfPages, generatePdfName, formatTimeInTimezone, handleHeighlightWidget } from "./utils/pdfPageEdit.js"; +export { flattenPdf } from "./utils/pdfFlatten.js"; +export { mailTemplate, formatDateTime, updateDateWidgetsRes, selectCheckbox, checkRegularExpress, handleUnlinkSigner } from "./utils/widgetResponses.js"; +export { getOriginalWH, handleCheckResponse, decryptPdf, base64ToFile, getFileAsArrayBuffer } from "./utils/pdfResponse.js"; +export { sendEmailToSigners, convertJpegToPng, getSignerEmail } from "./utils/signerMail.js"; +export { handleDeleteWidget, getDefaultDate, getDefaultFormat, handleBackground, getBase64MimeType } from "./utils/widgetLifecycle.js"; diff --git a/apps/OpenSign/src/constant/appinfo.js b/apps/OpenSign/src/constant/appinfo.js index 8093fa8669..94beaec691 100644 --- a/apps/OpenSign/src/constant/appinfo.js +++ b/apps/OpenSign/src/constant/appinfo.js @@ -1,5 +1,5 @@ import logo from "../assets/images/logo.png"; -import { getEnv } from "./Utils"; +import { getEnv } from "./utils/coreConstants.js"; import { getRuntimeConfig } from "./runtimeConfig"; import { hasExplicitRuntimeConfig } from "./deploymentRuntime"; diff --git a/apps/OpenSign/src/constant/fonts.js b/apps/OpenSign/src/constant/fonts.js new file mode 100644 index 0000000000..0a676e6698 --- /dev/null +++ b/apps/OpenSign/src/constant/fonts.js @@ -0,0 +1,13 @@ +// Single source of truth for fonts used across the app. +export const UI_FONT = "Arial, sans-serif"; + +export const SIGNATURE_FONTS = [ + "Fasthand", + "Dancing Script", + "Cedarville Cursive", + "Delicious Handrawn", +]; + +export const DEFAULT_SIGNATURE_FONT = "Fasthand"; + +export const DOCUMENT_FONT = "Times, serif"; \ No newline at end of file diff --git a/apps/OpenSign/src/constant/hostIdentity.js b/apps/OpenSign/src/constant/hostIdentity.js index 098e4265e0..4d3d2cecf0 100644 --- a/apps/OpenSign/src/constant/hostIdentity.js +++ b/apps/OpenSign/src/constant/hostIdentity.js @@ -11,13 +11,20 @@ export const RESERVED_FIRST_PARTY_ORIGINS = Object.freeze([ "https://eu-app.qiksign.com" ]); +// Single shared localhost list (issue #72): loopback names live here. +export const LOCALHOST_HOSTNAMES = Object.freeze([ + "localhost", + "127.0.0.1", + "::1" +]); + const isLocalDevelopmentOrigin = (origin, includeLocalhost) => { if (!includeLocalhost) return false; try { const url = new URL(origin); return ( ["http:", "https:"].includes(url.protocol) && - ["localhost", "127.0.0.1", "::1"].includes(url.hostname) + LOCALHOST_HOSTNAMES.includes(url.hostname) ); } catch { return false; diff --git a/apps/OpenSign/src/constant/hostIdentity.test.js b/apps/OpenSign/src/constant/hostIdentity.test.js new file mode 100644 index 0000000000..42d101f7e8 --- /dev/null +++ b/apps/OpenSign/src/constant/hostIdentity.test.js @@ -0,0 +1,35 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { + LOCALHOST_HOSTNAMES, + isOpenSignFirstPartyOrigin, + isReservedFirstPartyOrigin +} from "./hostIdentity"; + +// Single shared localhost list (issue #72): identical behavior, one source. +describe("LOCALHOST_HOSTNAMES", () => { + it("covers loopback names", () => { + expect([...LOCALHOST_HOSTNAMES]).toEqual([ + "localhost", + "127.0.0.1", + "::1" + ]); + expect(Object.isFrozen(LOCALHOST_HOSTNAMES)).toBe(true); + }); + + it("treats loopback origins as first-party only when asked", () => { + expect(isOpenSignFirstPartyOrigin("http://localhost:3000", true)).toBe(true); + expect(isOpenSignFirstPartyOrigin("http://localhost:3000")).toBe(false); + expect(isReservedFirstPartyOrigin("http://127.0.0.1:3000", true)).toBe( + true + ); + }); + + it("rejects origins that are neither first-party nor loopback", () => { + expect(isOpenSignFirstPartyOrigin("http://localhost:3000")).toBe(false); + expect(isOpenSignFirstPartyOrigin("not-a-url", true)).toBe(false); + expect(isOpenSignFirstPartyOrigin("https://evil.example.com", true)).toBe( + false + ); + }); +}); diff --git a/apps/OpenSign/src/constant/mailBrand.js b/apps/OpenSign/src/constant/mailBrand.js index b80ab52314..3ee06504a3 100644 --- a/apps/OpenSign/src/constant/mailBrand.js +++ b/apps/OpenSign/src/constant/mailBrand.js @@ -1,9 +1,11 @@ -import { getRuntimeConfig } from "./runtimeConfig"; +import { + OPEN_SIGN_EMAIL_ACCENT, + OPEN_SIGN_EMAIL_LOGO_URL, + getRuntimeConfig +} from "./runtimeConfig"; const OPEN_SIGN_NAME = "OpenSign™"; -const OPEN_SIGN_EMAIL_LOGO = - "https://qikinnovation.ams3.digitaloceanspaces.com/logo.png"; -const OPEN_SIGN_EMAIL_ACCENT = "#47a3ad"; +const OPEN_SIGN_EMAIL_LOGO = OPEN_SIGN_EMAIL_LOGO_URL; function resolveEmailLogoUrl(logoUrl, appUrl) { if (!logoUrl?.startsWith("/")) return logoUrl; diff --git a/apps/OpenSign/src/constant/mailBrand.test.js b/apps/OpenSign/src/constant/mailBrand.test.js new file mode 100644 index 0000000000..7f977314c7 --- /dev/null +++ b/apps/OpenSign/src/constant/mailBrand.test.js @@ -0,0 +1,39 @@ +// @vitest-environment node +import { afterEach, describe, expect, it } from "vitest"; +import { + OPEN_SIGN_EMAIL_ACCENT, + OPEN_SIGN_EMAIL_LOGO_URL +} from "./runtimeConfig"; + +globalThis.window = globalThis.window || {}; + +// Mail brand fallbacks (issue #72): identical behavior through shared config. +describe("resolveMailBrandPresentation", () => { + afterEach(() => { + delete globalThis.window.RUNTIME_CONFIG; + delete globalThis.window.location; + }); + + it("falls back to the centralized OpenSign brand", async () => { + const { resolveMailBrandPresentation } = await import("./mailBrand"); + const presentation = resolveMailBrandPresentation(""); + expect(presentation.appName).toBe("OpenSign™"); + expect(presentation.logoUrl).toBe(OPEN_SIGN_EMAIL_LOGO_URL); + expect(presentation.accentColor).toBe(OPEN_SIGN_EMAIL_ACCENT); + }); + + it("honors the deployment brand from runtime config", async () => { + globalThis.window.RUNTIME_CONFIG = { + schemaVersion: 1, + brandKey: "acme", + productName: "Acme Sign", + assets: { logoUrl: "https://acme.example/logo.png" }, + theme: { emailAccent: "#123456" } + }; + const { resolveMailBrandPresentation } = await import("./mailBrand"); + const presentation = resolveMailBrandPresentation(""); + expect(presentation.appName).toBe("Acme Sign"); + expect(presentation.logoUrl).toBe("https://acme.example/logo.png"); + expect(presentation.accentColor).toBe("#123456"); + }); +}); diff --git a/apps/OpenSign/src/constant/runtimeConfig.js b/apps/OpenSign/src/constant/runtimeConfig.js index c8b7651a60..c1c6ea0ffc 100644 --- a/apps/OpenSign/src/constant/runtimeConfig.js +++ b/apps/OpenSign/src/constant/runtimeConfig.js @@ -1,5 +1,16 @@ import { z } from "zod"; +// Centralized client defaults (issue #72): single source for values that were +// previously repeated inline. Defaults keep the behavior the app always had. +export const DEFAULT_COMPLETION_DAYS = 15; +export const DEFAULT_GOOGLE_TAG_IDS = Object.freeze([ + "G-BHNNETZRTY", + "AW-17487135887" +]); +export const OPEN_SIGN_EMAIL_LOGO_URL = + "https://qikinnovation.ams3.digitaloceanspaces.com/logo.png"; +export const OPEN_SIGN_EMAIL_ACCENT = "#47a3ad"; + const emptyOrHttpUrl = z .string() .trim() @@ -99,7 +110,7 @@ export const OPEN_SIGN_RUNTIME_CONFIG = Object.freeze({ }, analytics: { gtmId: "", - googleTagIds: ["G-BHNNETZRTY", "AW-17487135887"] + googleTagIds: [...DEFAULT_GOOGLE_TAG_IDS] }, auth: { googleClientId: "", diff --git a/apps/OpenSign/src/constant/runtimeConfig.test.js b/apps/OpenSign/src/constant/runtimeConfig.test.js new file mode 100644 index 0000000000..6874161839 --- /dev/null +++ b/apps/OpenSign/src/constant/runtimeConfig.test.js @@ -0,0 +1,53 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { + DEFAULT_COMPLETION_DAYS, + DEFAULT_GOOGLE_TAG_IDS, + OPEN_SIGN_EMAIL_ACCENT, + OPEN_SIGN_EMAIL_LOGO_URL, + resolveRuntimeConfig +} from "./runtimeConfig"; + +// Centralized client defaults (issue #72): identical behavior, single source. +describe("centralized completion default", () => { + it("keeps the 15-day completion default", () => { + expect(DEFAULT_COMPLETION_DAYS).toBe(15); + }); +}); + +describe("centralized analytics defaults", () => { + it("keeps the deployment Google tag IDs", () => { + expect([...DEFAULT_GOOGLE_TAG_IDS]).toEqual([ + "G-BHNNETZRTY", + "AW-17487135887" + ]); + }); + + it("uses the centralized tag IDs when nothing is configured", () => { + const config = resolveRuntimeConfig({ schemaVersion: 1 }, () => {}); + expect(config.analytics.googleTagIds).toEqual([...DEFAULT_GOOGLE_TAG_IDS]); + }); + + it("honors configured tag ID overrides", () => { + const config = resolveRuntimeConfig( + { schemaVersion: 1, analytics: { googleTagIds: ["G-OVERRIDE1"] } }, + () => {} + ); + expect(config.analytics.googleTagIds).toEqual(["G-OVERRIDE1"]); + }); +}); + +describe("centralized mail brand fallbacks", () => { + it("keeps the OpenSign logo and accent fallbacks", () => { + expect(OPEN_SIGN_EMAIL_LOGO_URL).toBe( + "https://qikinnovation.ams3.digitaloceanspaces.com/logo.png" + ); + expect(OPEN_SIGN_EMAIL_ACCENT).toBe("#47a3ad"); + }); + + it("falls back to the OpenSign product name by default", () => { + const config = resolveRuntimeConfig(null, () => {}); + expect(config.productName).toBe("OpenSign™"); + expect(config.brandKey).toBe("opensign"); + }); +}); diff --git a/apps/OpenSign/src/constant/utils/UtilsPart05.characterization.test.js b/apps/OpenSign/src/constant/utils/UtilsPart05.characterization.test.js new file mode 100644 index 0000000000..226973b873 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/UtilsPart05.characterization.test.js @@ -0,0 +1,309 @@ +// @vitest-environment node +// Characterization tests for #68 (UtilsPart05 split): +// - capture the observable behavior of signPdfFun / createDocument / +// getFirstLetter BEFORE the <=50-line split, so the refactor can prove +// exports and behavior stay identical. +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("axios", () => ({ default: { post: vi.fn() } })); +vi.mock("parse", () => ({ + default: { Cloud: { run: vi.fn() } } +})); +vi.mock("./imageHandling.js", () => ({ + fetchImageBase64: vi.fn(), + changeImageWH: vi.fn() +})); +vi.mock("./tenantDownloads.js", () => ({ getTenantDetails: vi.fn() })); +vi.mock("./widgetCatalog.js", () => ({ widgets: [] })); + +const store = new Map(); +globalThis.localStorage = { + getItem: (key) => (store.has(key) ? store.get(key) : null), + setItem: (key, value) => store.set(key, String(value)), + removeItem: (key) => store.delete(key), + clear: () => store.clear() +}; + +const axios = (await import("axios")).default; +const Parse = (await import("parse")).default; +const { fetchImageBase64, changeImageWH } = await import( + "./imageHandling.js" +); +const { getTenantDetails } = await import("./tenantDownloads.js"); +const { signPdfFun, createDocument, getFirstLetter } = await import( + "./UtilsPart05.js" +); + +const signatureWidgets = (signUrl) => [ + { pos: [{ type: "signature", SignUrl: signUrl }] } +]; + +const templateDoc = (overrides = {}) => ({ + Name: "Agreement", + URL: "https://files.example/doc.pdf", + SignedUrl: "https://files.example/signed.pdf", + SentToOthers: false, + Description: "desc", + Note: "note", + ExtUserPtr: { objectId: "ext1" }, + CreatedBy: { objectId: "user1" }, + objectId: "tpl1", + ...overrides +}); + +beforeEach(() => { + store.clear(); + vi.clearAllMocks(); + store.set("baseUrl", "https://parse.example/"); + store.set("parseAppId", "appId"); + store.set("accesstoken", "token"); +}); + +describe("signPdfFun", () => { + it("rejects a missing pdf payload without any cloud call", async () => { + await expect(signPdfFun("", "d1", "s1", "o1", [], "Signed")).resolves.toEqual( + { status: "error", message: "No PDF data to sign." } + ); + expect(Parse.Cloud.run).not.toHaveBeenCalled(); + }); + + it("rejects when the tenant no longer exists", async () => { + getTenantDetails.mockResolvedValue("user does not exist!"); + await expect( + signPdfFun("base64pdf", "d1", "s1", "o1", [], "Signed") + ).resolves.toEqual({ status: "error", message: "User does not exist." }); + expect(Parse.Cloud.run).not.toHaveBeenCalled(); + }); + + it("signs without tenant lookup or signature payload on the QES path", async () => { + Parse.Cloud.run.mockResolvedValue({ objectId: "signed1" }); + const res = await signPdfFun("base64pdf", "d1", "s1", undefined, [], undefined); + expect(getTenantDetails).not.toHaveBeenCalled(); + expect(Parse.Cloud.run).toHaveBeenCalledWith("signPdf", { + pdfFile: "base64pdf", + docId: "d1", + userId: "s1", + isCustomCompletionMail: false, + signature: "", + activity: "Signed" + }); + expect(res).toEqual({ objectId: "signed1" }); + }); + + it("flags a custom completion mail when the tenant defines one", async () => { + getTenantDetails.mockResolvedValue({ + CompletionBody: "body", + CompletionSubject: "subject" + }); + Parse.Cloud.run.mockResolvedValue({ objectId: "signed2" }); + await signPdfFun("base64pdf", "d1", "s1", "o1", [], "Signed"); + expect(Parse.Cloud.run).toHaveBeenCalledWith( + "signPdf", + expect.objectContaining({ isCustomCompletionMail: true }) + ); + }); + + it("converts an https signature to a resized suffix payload", async () => { + getTenantDetails.mockResolvedValue({}); + fetchImageBase64.mockResolvedValue("data:image/png;base64,AAA"); + changeImageWH.mockResolvedValue("data:image/png;base64,BBB"); + Parse.Cloud.run.mockResolvedValue({ objectId: "signed3" }); + await signPdfFun( + "base64pdf", + "d1", + "s1", + "o1", + signatureWidgets("https://files.example/sign.png"), + "Signed" + ); + expect(fetchImageBase64).toHaveBeenCalledWith( + "https://files.example/sign.png" + ); + expect(Parse.Cloud.run).toHaveBeenCalledWith( + "signPdf", + expect.objectContaining({ signature: "BBB" }) + ); + }); + + it("keeps an inline base64 signature payload resized without refetch", async () => { + getTenantDetails.mockResolvedValue({}); + changeImageWH.mockResolvedValue("data:image/png;base64,CCC"); + Parse.Cloud.run.mockResolvedValue({ objectId: "signed4" }); + await signPdfFun( + "base64pdf", + "d1", + "s1", + "o1", + signatureWidgets("data:image/png;base64,DDD"), + "Signed" + ); + expect(fetchImageBase64).not.toHaveBeenCalled(); + expect(Parse.Cloud.run).toHaveBeenCalledWith( + "signPdf", + expect.objectContaining({ signature: "CCC" }) + ); + }); + + it("maps a signature-image fetch failure to a generic error", async () => { + getTenantDetails.mockResolvedValue({}); + fetchImageBase64.mockRejectedValue(new Error("net down")); + await expect( + signPdfFun( + "base64pdf", + "d1", + "s1", + "o1", + signatureWidgets("https://files.example/sign.png"), + "Signed" + ) + ).resolves.toEqual({ status: "error", message: "something went wrong." }); + expect(Parse.Cloud.run).not.toHaveBeenCalled(); + }); + + it("maps cloud failures to the documented messages", async () => { + getTenantDetails.mockResolvedValue({}); + Parse.Cloud.run.mockRejectedValue(new Error("file is encrypted.")); + await expect( + signPdfFun("base64pdf", "d1", "s1", "o1", [], "Signed") + ).resolves.toEqual({ + status: "error", + message: "Currently encrypted pdf files are not supported." + }); + + Parse.Cloud.run.mockRejectedValue(new Error("wrong password")); + await expect( + signPdfFun("base64pdf", "d1", "s1", "o1", [], "Signed") + ).resolves.toEqual({ + status: "error", + message: "PFX file password is invalid." + }); + + Parse.Cloud.run.mockRejectedValue( + Object.assign(new Error("strict signing order"), { code: 119 }) + ); + await expect( + signPdfFun("base64pdf", "d1", "s1", "o1", [], "Signed") + ).resolves.toEqual({ + status: "error", + message: "strict signing order" + }); + + Parse.Cloud.run.mockRejectedValue(new Error("boom")); + await expect( + signPdfFun("base64pdf", "d1", "s1", "o1", [], "Signed") + ).resolves.toEqual({ status: "error", message: "something went wrong." }); + }); +}); + +describe("createDocument", () => { + it("does nothing without a template", async () => { + await expect(createDocument([], [], [], null, false)).resolves.toBeUndefined(); + expect(axios.post).not.toHaveBeenCalled(); + }); + + it("builds the document payload with defaults and posts it", async () => { + axios.post.mockResolvedValue({ + data: { result: { objectId: "doc1" } } + }); + const res = await createDocument( + [templateDoc()], + [{ pageNumber: 1, pos: [] }], + [{ objectId: "contact1" }], + "https://files.example/signed.pdf", + true + ); + expect(axios.post).toHaveBeenCalledWith( + "https://parse.example/functions/createdocumentfromapp", + expect.objectContaining({ + document: expect.objectContaining({ + Name: "Agreement", + URL: "https://files.example/signed.pdf", + SignedUrl: "https://files.example/signed.pdf", + TimeToCompleteDays: 15, + RemindOnceInEvery: 5, + Signers: [ + { + __type: "Pointer", + className: "contracts_Contactbook", + objectId: "contact1" + } + ], + ExtUserPtr: { + __type: "Pointer", + className: "contracts_Users", + objectId: "ext1" + }, + CreatedBy: { + __type: "Pointer", + className: "_User", + objectId: "user1" + }, + TemplateId: { + __type: "Pointer", + className: "contracts_Template", + objectId: "tpl1" + } + }) + }), + expect.objectContaining({ + headers: expect.objectContaining({ + "X-Parse-Session-Token": "token" + }) + }) + ); + expect(res).toEqual({ + status: "success", + id: "doc1", + data: { objectId: "doc1" } + }); + }); + + it("keeps an explicit completion window instead of the default", async () => { + axios.post.mockResolvedValue({ + data: { result: { objectId: "doc2" } } + }); + await createDocument([templateDoc({ TimeToCompleteDays: "30" })], [], [], null, false); + expect(axios.post).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + document: expect.objectContaining({ TimeToCompleteDays: 30 }) + }), + expect.anything() + ); + }); + + it("blocks runaway automatic reminders", async () => { + const res = await createDocument( + [ + templateDoc({ + TimeToCompleteDays: 100, + RemindOnceInEvery: 5, + autoreminder: true + }) + ], + [], + [], + null, + false + ); + expect(res).toEqual({ status: "error", id: "only-15-reminder-allowed" }); + expect(axios.post).not.toHaveBeenCalled(); + }); + + it("maps a post failure to the error status", async () => { + axios.post.mockRejectedValue({ response: { data: {} } }); + const res = await createDocument([templateDoc()], [], [], null, false); + expect(res).toEqual({ + status: "error", + id: "something-went-wrong-mssg" + }); + }); +}); + +describe("getFirstLetter", () => { + it("returns the first character", () => { + expect(getFirstLetter("OpenSign")).toBe("O"); + expect(getFirstLetter("")).toBe(""); + expect(getFirstLetter(undefined)).toBeUndefined(); + }); +}); diff --git a/apps/OpenSign/src/constant/utils/UtilsPart05.js b/apps/OpenSign/src/constant/utils/UtilsPart05.js new file mode 100644 index 0000000000..61940bcbff --- /dev/null +++ b/apps/OpenSign/src/constant/utils/UtilsPart05.js @@ -0,0 +1,323 @@ +import axios from "axios"; +import { getErrorMessage } from "../../utils/creditErrors"; +import Parse from "parse"; +import { fetchImageBase64, changeImageWH } from "./imageHandling.js"; +import { getTenantDetails } from "./tenantDownloads.js"; +import { widgets } from "./widgetCatalog.js"; +import { DEFAULT_COMPLETION_DAYS } from "../runtimeConfig.js"; + +// Resolve the tenant completion-mail flag for a non-QES signing flow. +const resolveCompletionMailFlag = async (objectId) => { + // get tenant details + const tenantDetails = await getTenantDetails(objectId); + if (tenantDetails && tenantDetails === "user does not exist!") { + return { error: { status: "error", message: "User does not exist." } }; + } + return { + isCustomCompletionMail: Boolean( + tenantDetails?.CompletionBody && tenantDetails?.CompletionSubject + ) + }; +}; + +// Find the first signature widget across the positioned pages. +// below for loop is used to get first signature of user to send if to signpdf +// for adding it in completion certificate +const findFirstSignature = (widgets) => { + let getSignature; + for (let item of widgets || []) { + if (!getSignature) { + const typeExist = item.pos.some((data) => data?.type); + if (typeExist) { + getSignature = item.pos.find((data) => data?.type === "signature"); + } else { + getSignature = item.pos.find((data) => !data.isStamp); + } + } + } + return getSignature; +}; + +// Normalize the first signature into the suffix-only payload the cloud +// function expects, refetching and resizing https signatures. +const normalizeSignatureSuffix = async (base64Sign) => { + if (!base64Sign) { + return { suffix: "" }; + } + // check https type signature (default signature exist) then convert in base64 + const isUrl = base64Sign.includes("https"); + if (isUrl) { + try { + base64Sign = await fetchImageBase64(base64Sign); + } catch (e) { + console.log("error", e); + return { error: { status: "error", message: "something went wrong." } }; + } + } + // change image width and height to 300/120 in png base64 + const imagebase64 = await changeImageWH(base64Sign); + // remove suffiix of base64 (without type) + return { suffix: imagebase64 && imagebase64.split(",").pop() }; +}; + +// Map signPdf cloud failures to the documented user-facing messages. +const mapSignPdfError = (e) => { + console.log("Err in signPdf cloud function ", e.message); + if (e && e?.message?.includes("is encrypted.")) { + return { + status: "error", + message: "Currently encrypted pdf files are not supported." + }; + } else if (e?.message?.includes("password")) { + return { status: "error", message: "PFX file password is invalid." }; + } else if ( + e?.code === 119 || + e?.message?.toLowerCase?.().includes("strict signing order") + ) { + return { status: "error", message: e.message }; + } else { + return { status: "error", message: "something went wrong." }; + } +}; + +export const signPdfFun = async ( + base64Url, + documentId, + signerObjectId, + objectId, + widgets, + activity +) => { + if (!base64Url) { + return { status: "error", message: "No PDF data to sign." }; + } + // qes: skip widget-based signature extraction (eID Easy already signed the PDF) + try { + // qes: skip getTenantDetails when objectId is unavailable (QES redirect-back) + let isCustomCompletionMail = false; + if (objectId) { + const tenant = await resolveCompletionMailFlag(objectId); + if (tenant.error) { + return tenant.error; + } + isCustomCompletionMail = tenant.isCustomCompletionMail; + } + const firstSignature = findFirstSignature(widgets); + const normalized = await normalizeSignatureSuffix( + firstSignature?.SignUrl + ); + if (normalized.error) { + return normalized.error; + } + // qes: will be empty string for QES + const params = { + pdfFile: base64Url, + docId: documentId, + userId: signerObjectId, + isCustomCompletionMail: isCustomCompletionMail, + signature: normalized.suffix, // qes: will be empty string for QES + activity: activity || "Signed" + }; + const resSignPdf = await Parse.Cloud.run("signPdf", params); + if (resSignPdf) { + const signedPdf = JSON.parse(JSON.stringify(resSignPdf)); + return signedPdf; + } + } catch (e) { + return mapSignPdfError(e); + } +}; + +// Resolve the document author pointers, honoring the extended-class override. +const resolveDocumentAuthors = (Doc) => { + let extUserId = Doc.ExtUserPtr.objectId; + let creatorId = Doc.CreatedBy.objectId; + const Extand_Class = localStorage.getItem("Extand_Class"); + const extClass = Extand_Class && JSON.parse(Extand_Class); + if (extClass && extClass.length > 0) { + if (Doc.ExtUserPtr?.objectId !== extClass?.[0]?.objectId) { + if (extClass && extClass.length > 0) { + extUserId = extClass[0].objectId; + creatorId = extClass[0]?.UserId.objectId; + } + } + } + const useNameAsSender = extClass?.[0]?.UseNameAsSender === true; + const senderName = + Doc?.SenderName || (useNameAsSender ? extClass?.[0]?.Name || "" : ""); + const senderMail = + Doc?.SenderMail || (useNameAsSender ? extClass?.[0]?.Email || "" : ""); + return { extUserId, creatorId, senderName, senderMail }; +}; + +// Build contact-book pointer entries for the document signers. +const buildSignerPointers = (signerData) => { + let signers = []; + if (signerData?.length > 0) { + signerData.forEach((x) => { + if (x.objectId) { + const obj = { + __type: "Pointer", + className: "contracts_Contactbook", + objectId: x.objectId + }; + signers.push(obj); + } + }); + } + return signers; +}; + +// Collect the optional document fields that only travel when present. +const buildOptionalDocumentFields = (Doc, senderName, senderMail) => { + const SignatureType = Doc?.SignatureType + ? { SignatureType: Doc?.SignatureType } + : {}; + const NotifyOnSignatures = + Doc?.NotifyOnSignatures !== undefined + ? { NotifyOnSignatures: Doc?.NotifyOnSignatures } + : {}; + const SenderName = senderName ? { SenderName: senderName } : {}; + const SenderMail = senderMail ? { SenderMail: senderMail } : {}; + const Bcc = Doc?.Bcc?.length > 0 ? { Bcc: Doc?.Bcc } : {}; + const Cc = Doc?.Cc?.length > 0 ? { Cc: Doc?.Cc } : {}; + const RedirectUrl = Doc?.RedirectUrl ? { RedirectUrl: Doc?.RedirectUrl } : {}; + const PenColors = Doc?.PenColors?.length > 0 ? { PenColors: Doc?.PenColors } : {}; + const TemplateId = Doc?.objectId + ? { + TemplateId: { + __type: "Pointer", + className: "contracts_Template", + objectId: Doc?.objectId + } + } + : {}; + return { + ...SignatureType, + ...NotifyOnSignatures, + ...SenderName, + ...SenderMail, + ...Bcc, + ...Cc, + ...RedirectUrl, + ...TemplateId, + ...PenColors + }; +}; + +// Assemble the createdocumentfromapp payload from the template and authors. +const buildDocumentPayload = ( + Doc, + { SignedUrl, isSendDoc, placeholdersArr, signers, authors } +) => { + const date = new Date(); + const isoDate = date.toISOString(); + const optionals = buildOptionalDocumentFields( + Doc, + authors.senderName, + authors.senderMail + ); + return { + Name: Doc.Name, + URL: SignedUrl ? SignedUrl : Doc?.URL, + SignedUrl: isSendDoc ? SignedUrl : Doc.SignedUrl, + SentToOthers: Doc.SentToOthers, + Description: Doc.Description, + Note: Doc.Note, + Placeholders: placeholdersArr, + ExtUserPtr: { + __type: "Pointer", + className: "contracts_Users", + objectId: authors.extUserId + }, + CreatedBy: { + __type: "Pointer", + className: "_User", + objectId: authors.creatorId + }, + Signers: signers, + SendinOrder: Doc?.SendinOrder || false, + AutomaticReminders: Doc?.AutomaticReminders || false, + RemindOnceInEvery: parseInt(Doc?.RemindOnceInEvery || 5), + IsEnableOTP: Doc?.IsEnableOTP || false, + SendInOrderStrict: Doc?.SendInOrderStrict || false, + IsTourEnabled: Doc?.IsTourEnabled || false, + AllowModifications: Doc?.AllowModifications || false, + TimeToCompleteDays: + parseInt(Doc?.TimeToCompleteDays) || DEFAULT_COMPLETION_DAYS, + DocSentAt: { __type: "Date", iso: isoDate }, + ...optionals + }; +}; + +// Guard against runaway automatic-reminder schedules. +const exceedsReminderLimit = (Doc) => { + const remindOnceInEvery = Doc?.RemindOnceInEvery; + const TimeToCompleteDays = parseInt(Doc?.TimeToCompleteDays); + const reminderCount = TimeToCompleteDays / remindOnceInEvery; + const AutomaticReminders = Doc.autoreminder; + return AutomaticReminders && reminderCount > 15; +}; + +// Post the payload to createdocumentfromapp and normalize the outcome. +const postCreateDocument = async (data) => { + const url = `${localStorage.getItem("baseUrl")}functions/createdocumentfromapp`; + const token = { + "X-Parse-Session-Token": localStorage.getItem("accesstoken") + }; + try { + const res = await axios.post( + url, + { document: data }, + { + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + ...token + } + } + ); + if (res) { + const result = res.data.result; + return { status: "success", id: result.objectId, data: result }; + } + } catch (err) { + const message = getErrorMessage(err) || "something went wrong."; + console.error("error in create document:", message); + return { status: "error", id: "something-went-wrong-mssg" }; + } +}; + +export const createDocument = async ( + template, + placeholders, + signerData, + SignedUrl, + isSendDoc +) => { + if (template && template.length > 0) { + const Doc = template[0]; + const authors = resolveDocumentAuthors(Doc); + let placeholdersArr = []; + if (placeholders?.length > 0) { + placeholdersArr = placeholders; + } + const signers = buildSignerPointers(signerData); + const data = buildDocumentPayload(Doc, { + SignedUrl, + isSendDoc, + placeholdersArr, + signers, + authors + }); + if (exceedsReminderLimit(Doc)) { + return { status: "error", id: "only-15-reminder-allowed" }; + } + return await postCreateDocument(data); + } +}; + +export const getFirstLetter = (name) => { + const firstLetter = name?.charAt(0); + return firstLetter; +}; diff --git a/apps/OpenSign/src/constant/utils/coreConstants.js b/apps/OpenSign/src/constant/utils/coreConstants.js new file mode 100644 index 0000000000..358d3a6be8 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/coreConstants.js @@ -0,0 +1,343 @@ +import Parse from "parse"; +import axios from "axios"; +import { resolveMailBrandPresentation } from "../mailBrand"; + +export const fontsizeArr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]; + +export const getFontSizeForHeight = (height) => { + const numericHeight = Number(height); + if (!Number.isFinite(numericHeight) || numericHeight <= 0) { + return fontsizeArr[0]; + } + + const fittingSizes = fontsizeArr.filter( + (fontSize) => fontSize * 1.5 <= numericHeight + ); + return fittingSizes[fittingSizes.length - 1] || fontsizeArr[0]; +}; + +export const fontColorArr = ["red", "black", "blue", "yellow"]; + +export const isMobile = window.innerWidth < 767; + +export const isTab = 767 < window.innerWidth < 1023; + +export const isHighResolution = window.innerWidth > 1023; + +export const isTabAndMobile = window.innerWidth < 1023; + +export const textInputWidget = "text input"; + +export const drawWidget = "draw"; + +export const textWidget = "text"; + +export const radioButtonWidget = "radio button"; + +export const isRadioSelected = (value, option) => { + const label = (item) => + typeof item === "string" + ? item.trim() + : item && typeof item === "object" && item.name != null + ? String(item.name).trim() + : ""; + const expected = label(option); + if (!expected) return false; + const values = Array.isArray(value) ? value : [value]; + return values.some( + (item) => item?.checked !== false && label(item) === expected + ); +}; + +export const cellsWidget = "cells"; + +export const duplicateAutoApplyWidgetTypes = [ + "name", + "company", + "job title", + "email", + textInputWidget +]; + +export const normalizeDuplicateWidgetType = (type) => { + if (typeof type !== "string") { + return type; + } + const normalizedType = type.trim().toLowerCase(); + // Backward compatibility for legacy payloads. + if (normalizedType === "textbox") { + return textInputWidget; + } + return normalizedType; +}; + +export const normalizeDuplicateWidgetName = (name) => + typeof name === "string" ? name.trim().toLowerCase() : ""; + +export const isDuplicateAutoApplyWidget = (widget) => + duplicateAutoApplyWidgetTypes.includes( + normalizeDuplicateWidgetType(widget?.type) + ); + +export const getDuplicateAutoApplyName = (widget) => { + if (!isDuplicateAutoApplyWidget(widget)) { + return ""; + } + return normalizeDuplicateWidgetName(widget?.options?.name); +}; + +export const getWidgetResponseValue = (widget) => + widget?.options?.response ?? widget?.options?.defaultValue; + +export const getDuplicateResponseMap = (widgets = []) => { + const responseByName = new Map(); + widgets.forEach((widget) => { + const widgetName = getDuplicateAutoApplyName(widget); + const response = getWidgetResponseValue(widget); + if ( + widgetName && + response !== undefined && + response !== "" && + !responseByName.has(widgetName) + ) { + responseByName.set(widgetName, response); + } + }); + return responseByName; +}; + +export const applyDuplicateResponsesToWidgets = ( + widgets = [], + responseByName = getDuplicateResponseMap(widgets) +) => { + if (responseByName.size === 0) { + return widgets; + } + + return widgets.map((widget) => { + const widgetName = getDuplicateAutoApplyName(widget); + if (!widgetName || !responseByName.has(widgetName)) { + return widget; + } + return { + ...widget, + options: { + ...widget.options, + response: responseByName.get(widgetName), + defaultValue: "" + } + }; + }); +}; + +export const applyDuplicateResponsesToPages = (pages = []) => { + const responseByName = getDuplicateResponseMap( + pages.flatMap((page) => page?.pos || []) + ); + return pages.map((page) => ({ + ...page, + pos: applyDuplicateResponsesToWidgets(page?.pos || [], responseByName) + })); +}; + +export function getEnv() { + return window?.RUNTIME_ENV || {}; +} + +export const appName = resolveMailBrandPresentation("").appName; + +export const defaultMailBody = `<p>Hi {{receiver_name}},</p><br><p>We hope this email finds you well. {{sender_name}} has requested you to review and sign {{document_title}}.</p><p>Your signature is crucial to proceed with the next steps as it signifies your agreement and authorization.</p><br><p><a href='{{signing_url}}' rel='noopener noreferrer' target='_blank'>Sign here</a></p><br><br><p>If you have any questions or need further clarification regarding the document or the signing process, please contact the sender.</p><br><p>Thanks</p><p> Team ${appName}</p><br>`; + +export const defaultMailSubject = `{{sender_name}} has requested you to sign {{document_title}}`; + +export const nonPresentMaskCss = (base) => ({ + ...base, + width: "0px", + height: "0px" +}); + +export const randomId = (digit = 8) => { + // 1. Grab a cryptographically-secure 32-bit random value + // Use crypto for stronger randomness + const randomBytes = crypto.getRandomValues(new Uint32Array(1)); + const raw = randomBytes[0]; // 0 … 4,294,967,295 + + // Calculate the min and max for the given digit length + const min = Math.pow(10, digit - 1); // e.g., digit=3 → 100 + const max = Math.pow(10, digit) - 1; // e.g., digit=3 → 999 + const range = max - min + 1; + + // Collapse random value into the range and shift + return min + (raw % range); +}; + +export const range = (start, end, step) => { + const range = []; + for (let i = start; i <= end; i += step) { + range.push(i); + } + return range; +}; + +export const getYear = (date) => { + const newYear = new Date(date).getFullYear(); + return newYear; +}; + +export const years = range(1950, getYear(new Date()) + 16, 1); + +export const months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; + +export const fileasbytes = async (filepath) => { + const response = await fetch(filepath); // Adjust the path accordingly + const arrayBuffer = await response.arrayBuffer(); + return new Uint8Array(arrayBuffer); +}; + +export const openInNewTab = (url, target) => { + if (target) { + window.open(url, target, "noopener,noreferrer"); + } else { + window.open(url, "_blank", "noopener,noreferrer"); + } +}; + +export const getUserCountry = async () => { + try { + const res = await fetch("https://ipapi.co/json/"); + const data = await res.json(); + return data?.country_code; + } catch (err) { + console.log("Error fetching country", err); + return ""; + } +}; + +export const getSecureUrl = async (url) => { + const fileUrl = new URL(url)?.pathname?.includes("/files/"); + if (fileUrl) { + try { + const fileRes = await Parse.Cloud.run("fileupload", { url: url }); + if (fileRes.url) { + return { url: fileRes.url }; + } else { + return { url: "" }; + } + } catch (err) { + console.log("err while fileupload ", err); + return { url: "" }; + } + } else { + return { url: url }; + } +}; + +export function generateId(length) { + const characters = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let result = ""; + const charactersLength = characters.length; + + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + +export function removeTrailingSegment(url, segment = "app") { + // Normalize a trailing slash (e.g. “/app/” → “/app”) + const normalized = url.endsWith("/") ? url.slice(0, -1) : url; + + const lastSlash = normalized.lastIndexOf("/"); + const lastPart = normalized.slice(lastSlash + 1); + + if (lastPart === segment) { + return normalized.slice(0, lastSlash); + } + + return normalized; +} + +export const color = [ + "#93a3db", + "#e6c3db", + "#c0e3bc", + "#bce3db", + "#b8ccdb", + "#ceb8db", + "#ffccff", + "#99ffcc", + "#cc99ff", + "#ffcc99", + "#66ccff", + "#ffffcc" +]; + +// Login-path helpers live here so the login bundle never pulls the pdf-lib +// modules below (widgetCatalog, widgetSizing, widgetInlineEditing, +// imageHandling, widgetEmbedding, pdfPageView, pdfPageEdit and their +// pdf-lib peers). They are re-exported from +// the ../Utils facade, so every existing import keeps working (#55). +export const saveLanguageInLocal = (i18n) => { + const detectedLanguage = i18n.language || "en"; + localStorage.setItem("i18nextLng", detectedLanguage); +}; + +export const usertimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + +export const contractUsers = async () => { + try { + const url = `${localStorage.getItem("baseUrl")}functions/getUserDetails`; + const parseAppId = localStorage.getItem("parseAppId"); + const accesstoken = localStorage.getItem("accesstoken"); + const token = { "X-Parse-Session-Token": accesstoken }; + const headers = { + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": parseAppId, + ...token + } + }; + const userDetails = await axios.post(url, {}, headers); + let data = []; + if (userDetails?.data?.result) { + const json = JSON.parse(JSON.stringify(userDetails.data.result)); + data.push(json); + } + return data; + } catch (err) { + console.log("Err in getUserDetails cloud function", err); + return "Error: Something went wrong!"; + } +}; + +export async function getBase64FromUrl(url, autosign) { + const data = await fetch(url); + const blob = await data.blob(); + return new Promise((resolve) => { + const reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = function () { + const pdfBase = this.result; + if (autosign) { + resolve(pdfBase); + } else { + const suffixbase64 = pdfBase.split(",").pop(); + resolve(suffixbase64); + } + }; + }); +} diff --git a/apps/OpenSign/src/constant/utils/imageHandling.js b/apps/OpenSign/src/constant/utils/imageHandling.js new file mode 100644 index 0000000000..2a0107ebc7 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/imageHandling.js @@ -0,0 +1,230 @@ +import { rgb } from "pdf-lib"; + +export function onSaveImage( + signatureType, + xyPosition, + index, + signKey, + image, + isAutoSign, + widgetsType, + imgUrl, + defaultStampImg, + defaultStampType +) { + let widgetName; + const isSignOrInitials = + widgetsType && ["signature", "initials"].includes(widgetsType); + //get current page position + const getXYData = xyPosition[index].pos; + const updateXYData = getXYData.map((position) => { + if (position.key === signKey) { + widgetName = position?.options?.name; + return { + ...position, + SignUrl: imgUrl || image?.src || defaultStampImg, + ImageType: image?.imgType || defaultStampType, + ...(isSignOrInitials && { signatureType: signatureType || "" }), + options: { + ...position.options, + response: imgUrl || image?.src || defaultStampImg + } + }; + } + return position; + }); + const updateXYposition = xyPosition.map((obj, ind) => { + if (ind === index) { + return { ...obj, pos: updateXYData }; + } + return obj; + }); + + // condition when user apply auto sign feature for any type upload image (signature,initials,stamp,image) + if (isAutoSign) { + const updatedArray = updateXYposition.map((page) => ({ + ...page, + pos: page.pos.map( + (item) => + // below condition is check if image widget name same then apply to auto sign other wise not + // and for other widget like signature,stamp,initials apply auto sign for all remaining widgets + item.type === widgetsType && + (item.type !== "image" || item.options.name === widgetName) + ? { + ...item, + SignUrl: image?.src || defaultStampImg, + ImageType: image?.imgType || defaultStampType, + options: { + ...item.options, + response: image?.src || defaultStampImg + } + } + : item // Otherwise, keep it unchanged + ) + })); + + return updatedArray; + } else { + return updateXYposition; + } +} + +export const onImageSelect = (setImage, file) => { + const reader = new FileReader(); + reader.readAsDataURL(file); + reader.onloadend = function (e) { + let width, height; + const image = new Image(); + image.src = e.target.result; + image.onload = function () { + width = image.width; + height = image.height; + const aspectRatio = 460 / 184; + const imgR = width / height; + if (imgR > aspectRatio) { + width = 460; + height = 460 / imgR; + } else { + width = 184 * imgR; + height = 184; + } + }; + image.src = reader.result; + setImage({ src: image.src, imgType: file.type }); + }; +}; + +export const compressedFileSize = (file, setImage) => { + // Create a new FileReader instance to read the uploaded file + const reader = new FileReader(); + + // Event listener triggered when the file is read successfully + reader.onload = (e) => { + // Create a new Image instance to manipulate the image data + const img = new Image(); + + // Set the image source to the file's data URL (base64 string) + img.src = e.target.result; + + // Event listener triggered when the image is fully loaded + img.onload = () => { + // Create a canvas element to resize and compress the image + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); // Get the drawing context of the canvas + + // Set the canvas dimensions, ensuring they don't exceed 1920x1920 + canvas.width = Math.min(img.width, 1920); // Limit width to 1920px + canvas.height = Math.min(img.height, 1920); // Limit height to 1920px + + // Draw the image onto the canvas with the specified dimensions + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + // Get the original file type (default to "image/png" if not recognized) + const fileType = "image/png"; //file.type || "image/png" + // Compress the image and convert it into a Blob + canvas.toBlob( + (blob) => { + // Create a new File object from the compressed Blob + const compressedFile = new File([blob], file.name, { + type: fileType, // Set the file type to JPEG + lastModified: Date.now() // Update the last modified timestamp + }); + // Pass the compressed file to a custom function for further processing + onImageSelect(setImage, compressedFile); + }, + fileType, // Output format for the compressed image + 0.3 // Compression quality (30%) + ); + }; + }; + + // Read the file as a data URL (base64 string) to be processed + reader.readAsDataURL(file); +}; + +export const fetchImageBase64 = async (imageUrl) => { + try { + const response = await fetch(imageUrl); + const blob = await response.blob(); + + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = () => { + const base64data = reader.result; + resolve(base64data); + }; + reader.onerror = (error) => { + reject(error); + }; + }); + } catch (error) { + throw new Error("Error converting URL to base64:", error); + } +}; + +export const changeImageWH = async (base64Image) => { + const newWidth = 300; + const newHeight = 120; + return new Promise((resolve, reject) => { + const img = new Image(); + img.src = base64Image; + img.onload = async () => { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + canvas.width = newWidth; + canvas.height = newHeight; + ctx.drawImage(img, 0, 0, newWidth, newHeight); + const resizedBase64 = canvas.toDataURL("image/png", 1.0); + resolve(resizedBase64); + }; + img.onerror = (error) => { + reject(error); + }; + }); +}; + +export const getWidgetsFontColor = (type) => { + switch (type) { + case "red": + return rgb(1, 0, 0); + case "black": + return rgb(0, 0, 0); + case "blue": + return rgb(0, 0, 1); + case "yellow": + return rgb(0.9, 1, 0); + default: + return rgb(0, 0, 0); + } +}; + +export const isBase64 = (str) => { + const base64Pattern = + /^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+)?;base64,[A-Za-z0-9+/=]+$/; + return base64Pattern.test(str); +}; + +export const forceBreakLongWord = (word, width, font, fontSize) => { + const parts = []; + let current = ""; + + for (const char of word) { + const lineWidth = font.widthOfTextAtSize(current + char, fontSize); + + if (lineWidth <= width) { + current += char; + } else { + parts.push(current); + current = char; + } + } + if (current) parts.push(current); + + return parts; +}; + +export const isEmptyValue = (val) => + val === null || + val === undefined || + (typeof val === "string" && val.trim() === "") || + (Array.isArray(val) && val.length === 0); diff --git a/apps/OpenSign/src/constant/utils/pdfFieldDrawing.js b/apps/OpenSign/src/constant/utils/pdfFieldDrawing.js new file mode 100644 index 0000000000..9558bdcd74 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/pdfFieldDrawing.js @@ -0,0 +1,249 @@ +import { rgb } from "pdf-lib"; +import { PDFName } from "pdf-lib"; +import { PDFDict } from "pdf-lib"; +import { color } from "./coreConstants.js"; + +export function _drawTextField(page, field, rect, font) { + let text = ""; + try { + text = field.getText?.() ?? ""; + } catch { + text = ""; + } + text = String(text ?? ""); + + if (!text) return; + + let multiline = false; + try { + multiline = field.isMultiline?.() ?? false; + } catch { + /* ignore */ + } + + let comb = false; + try { + comb = field.isCombed?.() ?? false; + } catch { + /* ignore */ + } + + if (comb) { + _drawCombText(page, text, rect, font); + return; + } + + if (multiline || text.includes("\n")) { + _drawMultilineText(page, text, rect, font); + return; + } + + const fontSize = _fitSingleLineFontSize(text, rect, font); + const baselineY = rect.y + Math.max(2, (rect.height - fontSize) / 2); + + page.drawText(text, { + x: rect.x + 2, + y: baselineY, + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 4) + }); +} + +export function _drawMultilineText(page, text, rect, font) { + const lines = String(text).replace(/\r/g, "").split("\n"); + const fontSize = Math.max( + 8, + Math.min(11, rect.height / Math.max(lines.length + 0.5, 2)) + ); + const lineHeight = fontSize + 1.5; + + let y = rect.y + rect.height - fontSize - 2; + + for (const line of lines) { + if (y < rect.y + 1) break; + + page.drawText(line, { + x: rect.x + 2, + y, + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 4), + lineHeight + }); + + y -= lineHeight; + } +} + +export function _drawCombText(page, text, rect, font) { + const chars = String(text).split(""); + const count = Math.max(chars.length, 1); + const cellWidth = rect.width / count; + const fontSize = Math.max(8, Math.min(12, rect.height - 4)); + + chars.forEach((ch, i) => { + const textWidth = font.widthOfTextAtSize(ch, fontSize); + const x = rect.x + i * cellWidth + (cellWidth - textWidth) / 2; + const y = rect.y + Math.max(2, (rect.height - fontSize) / 2); + + page.drawText(ch, { + x, + y, + size: fontSize, + font, + color: rgb(0, 0, 0) + }); + + if (i < count - 1) { + try { + page.drawLine({ + start: { x: rect.x + (i + 1) * cellWidth, y: rect.y }, + end: { + x: rect.x + (i + 1) * cellWidth, + y: rect.y + rect.height + }, + thickness: 0.4, + color: rgb(0.75, 0.75, 0.75) + }); + } catch { + /* best effort */ + } + } + }); +} + +export function _fitSingleLineFontSize(text, rect, font) { + let size = Math.min(12, rect.height - 4); + size = Math.max(size, 6); + + while (size > 6) { + const width = font.widthOfTextAtSize(text, size); + if (width <= rect.width - 4) return size; + size -= 0.5; + } + + return 6; +} + +export function _drawCheckBox(page, field, rect, zapf) { + let checked = false; + try { + checked = field.isChecked(); + } catch { + checked = false; + } + + if (!checked) return; + + const size = Math.max(8, Math.min(rect.width, rect.height) - 4); + + page.drawText("\u2714", { + x: rect.x + Math.max(1, (rect.width - size * 0.7) / 2), + y: rect.y + Math.max(1, (rect.height - size) / 2), + size, + font: zapf, + color: rgb(0, 0, 0) + }); +} + +export function _drawRadioGroup(page, field, widget, rect) { + let selected = null; + try { + selected = field.getSelected(); + } catch { + selected = null; + } + + if (!selected) return; + + let widgetOnValue = null; + try { + widgetOnValue = widget.getOnValue?.(); + } catch { + /* ignore */ + } + + if (!widgetOnValue) { + try { + const ap = widget.dict?.lookupMaybe?.(PDFName.of("AP"), PDFDict); + const n = ap?.lookupMaybe?.(PDFName.of("N"), PDFDict); + if (n) { + const keys = n.keys(); + for (const k of keys) { + const name = k?.decodeText?.() ?? k?.encodedName ?? String(k); + if (name !== "/Off" && name !== "Off") { + widgetOnValue = name.replace(/^\//, ""); + break; + } + } + } + } catch { + /* ignore */ + } + } + + const selectedStr = String(selected).replace(/^\//, ""); + const onStr = String(widgetOnValue ?? "").replace(/^\//, ""); + + if (!onStr || selectedStr !== onStr) return; + + // Circle outline + try { + page.drawEllipse({ + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + xScale: rect.width / 2 - 1, + yScale: rect.height / 2 - 1, + borderWidth: 0.8, + borderColor: rgb(0, 0, 0) + }); + } catch { + /* best effort */ + } + + // Inner filled dot (drawn as a filled ellipse instead of a text glyph + // so we avoid WinAnsi encoding issues with bullet characters) + try { + const r = Math.min(rect.width, rect.height) / 4; + page.drawEllipse({ + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + xScale: r, + yScale: r, + color: rgb(0, 0, 0) + }); + } catch { + /* best effort */ + } +} + +export function _drawDropdown(page, field, rect, font) { + let text = ""; + try { + const selected = field.getSelected?.(); + if (Array.isArray(selected)) { + text = selected.join(", "); + } else { + text = selected ?? ""; + } + } catch { + text = ""; + } + + text = String(text ?? ""); + if (!text) return; + + const fontSize = _fitSingleLineFontSize(text, rect, font); + + page.drawText(text, { + x: rect.x + 2, + y: rect.y + Math.max(2, (rect.height - fontSize) / 2), + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 12) + }); +} diff --git a/apps/OpenSign/src/constant/utils/pdfFlatten.js b/apps/OpenSign/src/constant/utils/pdfFlatten.js new file mode 100644 index 0000000000..7dc1868f48 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/pdfFlatten.js @@ -0,0 +1,255 @@ +import { PDFDocument } from "pdf-lib"; +import { rgb } from "pdf-lib"; +import { PDFName } from "pdf-lib"; +import { StandardFonts } from "pdf-lib"; +import { PDFArray } from "pdf-lib"; +import { PDFDict } from "pdf-lib"; +import { toPdfBytes } from "./pdfPageEdit.js"; +import { hasSignatureField } from "./pdfPageEdit.js"; +import { _drawTextField } from "./pdfFieldDrawing.js"; +import { _drawCheckBox } from "./pdfFieldDrawing.js"; +import { _drawRadioGroup } from "./pdfFieldDrawing.js"; +import { _drawDropdown } from "./pdfFieldDrawing.js"; +import { _drawOptionList } from "./widgetResponses.js"; +import { _removeWidgetAnnotations } from "./widgetResponses.js"; +import { widgets } from "./widgetCatalog.js"; + +export const flattenPdf = async (pdfFile) => { + const inputBytes = toPdfBytes(pdfFile); + const pdfDoc = await PDFDocument.load(inputBytes, { ignoreEncryption: true }); + + // Preserve existing digital signatures: if the document contains a + // signature field (SigFlags or /FT /Sig), skip flattening entirely. + try { + const acroFormEntry = pdfDoc.catalog.get(PDFName.of("AcroForm")); + const acroForm = pdfDoc.context.lookupMaybe + ? pdfDoc.context.lookupMaybe(acroFormEntry, PDFDict) + : pdfDoc.context.lookup(acroFormEntry); + if (acroForm) { + const sigFlags = acroForm.get(PDFName.of("SigFlags")); + if (sigFlags && Number(sigFlags) > 0) { + return inputBytes; + } + const fieldsRef = acroForm.get(PDFName.of("Fields")); + const fields = fieldsRef ? pdfDoc.context.lookup(fieldsRef) : null; + if (fields && typeof fields.asArray === "function") { + for (const fRef of fields.asArray()) { + const field = pdfDoc.context.lookup(fRef); + if (hasSignatureField(pdfDoc.context, field)) return inputBytes; + } + } + } + } catch { + // continue with normal flatten + } + + // Preserve existing digital signatures: if the document contains a + // signature field (SigFlags or /FT /Sig), skip flattening entirely. + try { + const acroFormEntry = pdfDoc.catalog.get(PDFName.of("AcroForm")); + const acroForm = pdfDoc.context.lookupMaybe + ? pdfDoc.context.lookupMaybe(acroFormEntry) + : pdfDoc.context.lookup(acroFormEntry); + if (acroForm) { + const sigFlags = acroForm.get(PDFName.of("SigFlags")); + if (sigFlags && Number(sigFlags) > 0) { + return pdfFile; + } + const fieldsRef = acroForm.get(PDFName.of("Fields")); + const fields = fieldsRef ? pdfDoc.context.lookup(fieldsRef) : null; + if (fields && fields.asArray) { + for (const fRef of fields.asArray()) { + const f = pdfDoc.context.lookup(fRef); + const ft = f?.get(PDFName.of("FT")); + if (ft && ft.toString() === "/Sig") return pdfFile; + const kidsRef = f?.get(PDFName.of("Kids")); + const kids = kidsRef ? pdfDoc.context.lookup(kidsRef) : null; + if (kids && kids.asArray) { + for (const kRef of kids.asArray()) { + const k = pdfDoc.context.lookup(kRef); + const kft = k?.get(PDFName.of("FT")); + if (kft && kft.toString() === "/Sig") return pdfFile; + } + } + } + } + } + } catch { + // continue with normal flatten + } + + let form; + try { + form = pdfDoc.getForm(); + } catch { + // No form, nothing to flatten + return await pdfDoc.save({ useObjectStreams: false }); + } + + // If any signature field exists, skip flatten to preserve it. + try { + const sigField = form + .getFields() + .some((f) => f?.constructor?.name === "PDFSignature"); + if (sigField) return pdfFile; + } catch { + // continue + } + + const pages = pdfDoc.getPages(); + + const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica); + const helveticaBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold); + const zapf = await pdfDoc.embedFont(StandardFonts.ZapfDingbats); + + const fields = form.getFields(); + + for (const field of fields) { + const type = field.constructor.name; + + if (type === "PDFSignature") { + continue; + } + + const widgets = _safeGetWidgets(field); + + for (const widget of widgets) { + const rect = _getWidgetRect(widget, pdfDoc); + const page = _getWidgetPage(pdfDoc, pages, widget); + + if (!rect || !page) continue; + + _drawWidgetBox(page, rect); + + if (type === "PDFTextField") { + _drawTextField(page, field, rect, helvetica); + } else if (type === "PDFCheckBox") { + _drawCheckBox(page, field, rect, zapf); + } else if (type === "PDFRadioGroup") { + _drawRadioGroup(page, field, widget, rect); + } else if (type === "PDFDropdown") { + _drawDropdown(page, field, rect, helvetica); + } else if (type === "PDFOptionList") { + _drawOptionList(page, field, rect, helvetica); + } else if (type === "PDFButton") { + // Push buttons are interactive controls, not meaningful data fields. + } + } + } + + if (fields.length > 0) { + _removeWidgetAnnotations(pdfDoc); + } + + return await pdfDoc.save({ useObjectStreams: false }); +}; + +export function _safeGetWidgets(field) { + try { + return field.acroField?.getWidgets?.() || []; + } catch { + return []; + } +} + +export function _getWidgetRect(widget, pdfDoc) { + try { + const r = widget.getRectangle?.(); + if ( + r && + isFinite(r.x) && + isFinite(r.y) && + isFinite(r.width) && + isFinite(r.height) + ) { + return r; + } + } catch { + /* fall through to manual extraction */ + } + + try { + const rectArr = widget.dict?.lookup?.(PDFName.of("Rect")); + if (!rectArr || typeof rectArr.size !== "function" || rectArr.size() !== 4) + return null; + + const x1 = _numberFromPdfObject(rectArr.get(0)); + const y1 = _numberFromPdfObject(rectArr.get(1)); + const x2 = _numberFromPdfObject(rectArr.get(2)); + const y2 = _numberFromPdfObject(rectArr.get(3)); + + if ([x1, y1, x2, y2].some((v) => !isFinite(v))) return null; + + return { + x: Math.min(x1, x2), + y: Math.min(y1, y2), + width: Math.abs(x2 - x1), + height: Math.abs(y2 - y1) + }; + } catch { + return null; + } +} + +export function _numberFromPdfObject(obj) { + if (!obj) return NaN; + if (typeof obj.asNumber === "function") return obj.asNumber(); + if (typeof obj.numberValue === "function") return obj.numberValue(); + return Number(obj?.value ?? obj); +} + +export function _getWidgetPage(pdfDoc, pages, widget) { + try { + const pRef = widget.P?.(); + if (pRef) { + for (const page of pages) { + if (page.ref === pRef) return page; + } + } + } catch { + /* fall through */ + } + + try { + const pRef = widget.dict?.get?.(PDFName.of("P")); + if (pRef) { + for (const page of pages) { + if (page.ref === pRef) return page; + } + } + } catch { + /* fall through */ + } + + // Fallback: search page annots + try { + for (const page of pages) { + const annots = page.node.lookupMaybe(PDFName.of("Annots"), PDFArray); + if (!annots) continue; + + for (let i = 0; i < annots.size(); i++) { + const ref = annots.get(i); + if (ref === widget.ref) return page; + } + } + } catch { + /* fall through */ + } + + return null; +} + +export function _drawWidgetBox(page, rect) { + try { + page.drawRectangle({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + borderWidth: 0.6, + borderColor: rgb(0.65, 0.65, 0.65) + }); + } catch { + /* best effort */ + } +} diff --git a/apps/OpenSign/src/constant/utils/pdfPageEdit.js b/apps/OpenSign/src/constant/utils/pdfPageEdit.js new file mode 100644 index 0000000000..066a2a7c90 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/pdfPageEdit.js @@ -0,0 +1,207 @@ +import { PDFDocument } from "pdf-lib"; +import { PDFName } from "pdf-lib"; +import { format } from "date-fns-tz"; +import { toZonedTime } from "date-fns-tz"; +import { base64ToArrayBuffer } from "./pdfPageView.js"; +import { copyPdfMetadata } from "../../utils/pdfDocumentUtils.js"; + +export function generateTitleFromFilename(filename) { + try { + // Step 1: Trim whitespace + let title = filename.trim(); + + // Step 2: Remove the file extension (everything after the last '.') + const lastDotIndex = title.lastIndexOf("."); + if (lastDotIndex > 0) { + title = title.substring(0, lastDotIndex); + } + + // Step 3: Replace special characters (except Unicode letters, digits, spaces, and hyphens) + title = title.replace(/[^\p{L}\p{N}\s-]/gu, " "); + + // Step 4: Replace multiple spaces with a single space + title = title.replace(/\s+/g, " "); + + // Step 5: Capitalize first letter of each word (Title Case), handling Unicode characters + title = title.replace( + /\p{L}\S*/gu, + (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() + ); + + // Step 6: Restrict length of title (optional, let's say 100 characters) + if (title.length > 100) { + title = title.substring(0, 100).trim(); + } + + // Step 7: Handle empty or invalid title by falling back to "Untitled Document" + if (!title || title.length === 0) { + return "Untitled Document"; + } + + return title; + } catch (error) { + // Handle unexpected errors gracefully by returning a default title + console.error("Error generating title from filename:", error); + return "Untitled Document"; + } +} + +export const signatureTypes = [ + { name: "draw", enabled: true }, + { name: "typed", enabled: true }, + { name: "upload", enabled: true }, + { name: "default", enabled: true } +]; + +export async function handleSignatureType(tenantSignTypes, signatureType) { + const docSignTypes = signatureType || signatureTypes; + let updatedSignatureType = signatureType || signatureTypes; + if (tenantSignTypes?.length > 0) { + updatedSignatureType = tenantSignTypes?.map((item) => { + const match = docSignTypes.find((data) => data.name === item.name); + return match ? { ...item, enabled: match.enabled } : item; + }); + } + return updatedSignatureType; +} + +export const formatDateToDdMmmYyyy = (date) => { + // Create a Date object + const newDate = new Date(date); + // Format the date + const formattedDate = newDate.toLocaleDateString("en-GB", { + day: "2-digit", + month: "short", + year: "numeric" + }); + const format = formattedDate.replaceAll(/ /g, "-"); + return format; +}; + +export const deletePdfPage = async (pdfArrayBuffer, pageNumber) => { + try { + // Load the existing PDF + const pdfDoc = await PDFDocument.load(pdfArrayBuffer, { + ignoreEncryption: true + }); + // Get the total number of pages + const totalPages = pdfDoc.getPageCount(); + // Ensure the page index is valid + if (totalPages > 1) { + //Remove the specified page + pdfDoc.removePage(pageNumber - 1); + // Save the modified PDF + const modifiedPdfBytes = await pdfDoc.saveAsBase64({ + useObjectStreams: false + }); + const arrayBuffer = base64ToArrayBuffer(modifiedPdfBytes); + return { + arrayBuffer: arrayBuffer, + base64: modifiedPdfBytes, + remainingPages: totalPages - 1 + }; + } else { + return { totalPages: 1 }; + } + } catch (err) { + console.log("Err while deleting page", err); + } +}; + +export const reorderPdfPages = async (pdfArrayBuffer, orderArr) => { + try { + const pdfDoc = await PDFDocument.load(pdfArrayBuffer, { + ignoreEncryption: true + }); + const newPdf = await PDFDocument.create(); + const pages = await newPdf.copyPages( + pdfDoc, + orderArr.map((n) => n - 1) + ); + pages.forEach((p) => newPdf.addPage(p)); + copyPdfMetadata(pdfDoc, newPdf); + const pdfBase64 = await newPdf.saveAsBase64({ useObjectStreams: false }); + const arrayBuffer = base64ToArrayBuffer(pdfBase64); + return { arrayBuffer, base64: pdfBase64, totalPages: orderArr.length }; + } catch (err) { + console.log("Err while reordering pages", err); + } +}; + +export function generatePdfName(length) { + const characters = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + let result = ""; + const charactersLength = characters.length; + + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + +export const formatTimeInTimezone = (date, timezone) => { + const nyDate = timezone && toZonedTime(date, timezone); + const generatedDate = timezone + ? format(nyDate, "EEE, dd MMM yyyy HH:mm:ss zzz", { timeZone: timezone }) + : new Date(date).toUTCString(); + return generatedDate; +}; + + + +export const handleHeighlightWidget = ( + getCurrentSignerPos, + key, + pageNumber +) => { + const placeholder = getCurrentSignerPos.placeHolder; + // Find the highest zIndex value + const highestZIndex = placeholder + .flatMap((item) => item.pos.map((position) => position.zIndex)) + .reduce((max, zIndex) => (zIndex > max ? zIndex : max), -Infinity); //-Infinity represents the smallest possible number + // Update the zIndex of the current signer + const updateZindex = placeholder.map((data) => { + if (data.pageNumber === pageNumber) { + return { + ...data, + pos: data.pos.map((position) => { + if (position.key === key) { + return { ...position, zIndex: highestZIndex + 1 }; + } + return position; + }) + }; + } + return data; + }); + return updateZindex; +}; + +export const toPdfBytes = (input) => { + if (typeof input === "string") { + const binary = atob(input.replace(/^data:application\/pdf;base64,/, "")); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; + } + if (input instanceof ArrayBuffer) return new Uint8Array(input); + return input; +}; + +export const hasSignatureField = (context, node, visited = new Set()) => { + if (!node) return false; + if (visited.has(node)) return false; + visited.add(node); + const ft = node.get?.(PDFName.of("FT")); + if (ft && ft.toString() === "/Sig") return true; + const kidsRef = node.get?.(PDFName.of("Kids")); + const kids = kidsRef ? context.lookup(kidsRef) : null; + if (kids && typeof kids.asArray === "function") { + for (const kidRef of kids.asArray()) { + const kid = context.lookup(kidRef); + if (hasSignatureField(context, kid, visited)) return true; + } + } + return false; +}; diff --git a/apps/OpenSign/src/constant/utils/pdfPageView.js b/apps/OpenSign/src/constant/utils/pdfPageView.js new file mode 100644 index 0000000000..bade25abcd --- /dev/null +++ b/apps/OpenSign/src/constant/utils/pdfPageView.js @@ -0,0 +1,271 @@ +import { PDFDocument } from "pdf-lib"; +import { degrees } from "pdf-lib"; +import Parse from "parse"; +import { SCALE_STEPS } from "../const"; +import i18n from "../../i18n"; +import { getSecureUrl } from "./coreConstants.js"; +import { getBase64FromUrl } from "./coreConstants.js"; +import { fileNameWithUnderscore } from "./tenantDownloads.js"; +import { compensateRotation } from "./printCertificates.js"; + +export function getWidgetPosition(page, image, sizeRatio, getSize) { + let pageWidth; + // pageHeight; + if ([90, 270].includes(page.getRotation().angle)) { + pageWidth = getSize?.height || page.getHeight(); + } else { + pageWidth = getSize?.width || page.getWidth(); + } + // eslint-disable-next-line + if (!image?.hasOwnProperty("vpWidth")) { + image["vpWidth"] = pageWidth; + } + const pageRatio = pageWidth / (image.vpWidth * sizeRatio); + const imageWidth = image.width * sizeRatio * pageRatio; + const imageHeight = image.height * sizeRatio * pageRatio; + const imageX = image.x * sizeRatio * pageRatio; + const imageYFromTop = image.y * sizeRatio * pageRatio; + + const correction = compensateRotation( + page.getRotation().angle, + imageX, + imageYFromTop, + 1, + getSize, + imageHeight + ); + + return { + width: imageWidth, + height: imageHeight, + x: correction.x, + y: correction.y, + rotate: page.getRotation() + }; +} + +export const getContainerScale = (pdfOriginalWH, pageNumber, containerWH) => { + const getPdfPageWidth = pdfOriginalWH.find( + (data) => data.pageNumber === pageNumber + ); + const containerScale = containerWH?.width / getPdfPageWidth?.width || 1; + return containerScale; +}; + +export const getDefaultSignature = async (objectId) => { + try { + if (objectId) { + const result = await Parse.Cloud.run("getdefaultsignature", { + userId: objectId + }); + if (result) { + const res = JSON.parse(JSON.stringify(result)); + const defaultSignature = res?.ImageURL + ? await getBase64FromUrl(res?.ImageURL, true) + : ""; + const defaultInitial = res?.Initials + ? await getBase64FromUrl(res?.Initials, true) + : ""; + const defaultStamp = res?.Stamp + ? await getBase64FromUrl(res?.Stamp, true) + : ""; + + return { + status: "success", + res: { + id: result?.id, + defaultSignature: defaultSignature, + defaultInitial: defaultInitial, + defaultStamp: defaultStamp + } + }; + } + } else { + return { status: "error" }; + } + } catch (err) { + console.log( + "Error: error in fetch data in contracts_Signature", + err?.message || err + ); + return { status: "error" }; + } +}; + +export async function rotatePdfPage(rotateDegree, pageNumber, pdfArrayBuffer) { + // Load the existing PDF + const pdfDoc = await PDFDocument.load(pdfArrayBuffer, { + ignoreEncryption: true + }); + // Get the page according to page number + const page = pdfDoc.getPage(pageNumber); + //get current page rotation angle + const currentRotation = page.getRotation().angle; + // Apply the rotation in the counterclockwise direction + let newRotation = (currentRotation + rotateDegree) % 360; + // Adjust for negative angles to keep within 0-359 range + if (newRotation < 0) { + newRotation += 360; + } + page.setRotation(degrees(newRotation)); + const pdfbase64 = await pdfDoc.saveAsBase64({ useObjectStreams: false }); + //convert base64 to arraybuffer is used in pdf-lib + //pdfbase64 is used to show pdf rotated format + const arrayBuffer = base64ToArrayBuffer(pdfbase64); + //`base64` is used to show pdf + return { arrayBuffer: arrayBuffer, base64: pdfbase64 }; +} + +export function base64ToArrayBuffer(base64) { + // Decode the base64 string to a binary string + const binaryString = atob(base64); + // Create a new ArrayBuffer with the same length as the binary string + const len = binaryString.length; + const bytes = new Uint8Array(len); + // Convert the binary string to a byte array + for (let i = 0; i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + // Return the ArrayBuffer + return bytes.buffer; +} + +export function removeBase64Prefix(base64String) { + return base64String.replace(/^data:.*;base64,/, ""); +} + +export const convertBase64ToFile = async (pdfName, pdfBase64, imgType) => { + let base64Str = pdfBase64; + const mime = imgType && imgType?.split("/")?.pop(); + let fileName = + fileNameWithUnderscore(pdfName) + (imgType ? `.${mime}` : ".pdf"); + try { + fileName = imgType ? pdfName : fileName; + const pdfFile = new Parse.File(fileName, { base64: base64Str }); + // Save the Parse File if needed + const pdfData = await pdfFile.save(); + const pdfUrl = pdfData.url(); + const fileRes = await getSecureUrl(pdfUrl); + if (fileRes?.url) { + return fileRes.url; + } + } catch (e) { + console.log("error in convertbase64tofile", e); + } +}; + +export const isCustomFileAdapter = (fileAdapterId) => + Boolean(fileAdapterId && fileAdapterId !== "opensign"); + +export const pendingButtonZoomScrollRef = { current: null }; + +export const captureScrollForButtonZoom = ( + scrollContainerRef, + scale, + newScale +) => { + const el = scrollContainerRef?.current; + if (!el) return; + + const scaleRatio = newScale / scale; + + // Anchor point = center of the visible scroll container + const midRelX = el.clientWidth / 2; + const midRelY = el.clientHeight / 2; + + const docX = el.scrollLeft + midRelX; + const docY = el.scrollTop + midRelY; + + const newScrollLeft = Math.max(0, docX * scaleRatio - midRelX); + const newScrollTop = Math.max(0, docY * scaleRatio - midRelY); + + pendingButtonZoomScrollRef.current = { newScrollLeft, newScrollTop }; +}; + +export const onClickZoomIn = (scale, setScale, scrollContainerRef) => { + // Find last step smaller than current scale + const nextScale = SCALE_STEPS.find((s) => s > scale); + if (!nextScale) return; + captureScrollForButtonZoom(scrollContainerRef, scale, nextScale); + setScale(nextScale); +}; + +export const onClickZoomOut = (scale, setScale, scrollContainerRef) => { + // Find last step smaller than current scale + const prevScale = [...SCALE_STEPS].reverse().find((s) => s < scale); + if (!prevScale || prevScale < 1.0) return; + captureScrollForButtonZoom(scrollContainerRef, scale, prevScale); + setScale(prevScale); +}; + +export const handleRemoveWidgets = ( + setSignerPos, + signerPos, + pageNumber, + setIsRotate +) => { + const isSigners = signerPos.some((data) => data.signerPtr); + //placeholder,template,draftTemplate flow + if (isSigners) { + const updatedSignerPos = signerPos.map((placeholderObj) => { + return { + ...placeholderObj, + placeHolder: placeholderObj?.placeHolder?.filter( + (data) => data?.pageNumber !== pageNumber + ) + }; + }); + + if (setIsRotate) { + setSignerPos(updatedSignerPos); + setIsRotate({ status: false, degree: 0 }); + } else { + //after deleting pdf page we need to update page number of widgets + //For example, consider a PDF with 3 pages where widgets are placed on the 2nd page. + //If we delete the 1st page, the total number of pages will be reduced to 2. In this case, + // the widgets need to be updated to reflect the new page numbering and should now appear on the 1st page. + const updatePageNumber = updatedSignerPos?.map((placeholderObj) => { + return { + ...placeholderObj, + placeHolder: placeholderObj?.placeHolder?.map((data) => { + if (data.pageNumber > pageNumber) { + return { ...data, pageNumber: data.pageNumber - 1 }; + } else { + return data; + } + }) + }; + }); + setSignerPos(updatePageNumber); + } + } else { + //signyourself flow + const updatedSignerPos = signerPos?.filter( + (data) => data?.pageNumber !== pageNumber + ); + if (setIsRotate) { + setSignerPos(updatedSignerPos); + setIsRotate({ status: false, degree: 0 }); + } else { + //after deleting pdf page we need to update page number of widgets + //For example, consider a PDF with 3 pages where widgets are placed on the 2nd page. + //If we delete the 1st page, the total number of pages will be reduced to 2. In this case, + // the widgets need to be updated to reflect the new page numbering and should now appear on the 1st page. + const updatePageNumber = updatedSignerPos?.map((data) => { + if (data.pageNumber > pageNumber) { + return { ...data, pageNumber: data.pageNumber - 1 }; + } else { + return data; + } + }); + setSignerPos(updatePageNumber); + } + } +}; + +export const handleRotateWarning = (signerPos, pageNumber) => { + const placeholderExist = signerPos?.some((placeholderObj) => + placeholderObj?.placeHolder?.some((data) => data?.pageNumber === pageNumber) + ); + return placeholderExist ? true : false; +}; diff --git a/apps/OpenSign/src/constant/utils/pdfResponse.js b/apps/OpenSign/src/constant/utils/pdfResponse.js new file mode 100644 index 0000000000..a540c6f21f --- /dev/null +++ b/apps/OpenSign/src/constant/utils/pdfResponse.js @@ -0,0 +1,181 @@ +import axios from "axios"; +import { removeTrailingSegment } from "./coreConstants.js"; +import { isEmptyValue } from "./imageHandling.js"; +import { generatePdfName } from "./pdfPageEdit.js"; + +export const getOriginalWH = async (pdf) => { + let pdfWHObj = []; + //get total page number + const totalPages = pdf?.numPages; + //according to page number get all pdf's pages width and height + for (let index = 0; index < totalPages; index++) { + try { + const getPage = await pdf.getPage(index + 1); + const scale = 1; + //getting extra height which is removed from viewPort height (letter type pdf have originial h-799.92 but using getPage.getViewport getting height-792 something diffrence-7.92px) + //getPage?.view[1] store diffrence of height (Page starts 7.92 from bottom) + const y0 = getPage?.view[1] || 0; + let { width, height } = getPage.getViewport({ scale }); + //adding it on viewPort height then get original height ex- 792+7.92 = 799.92 orignial height + height = height + y0; + pdfWHObj.push({ pageNumber: index + 1, width, height }); + } catch (e) { + console.log(`Error getting page ${index + 1} of PDF: ${e.message}`); + } + } + return pdfWHObj; +}; + +export const handleCheckResponse = (checkUser, setminRequiredCount) => { + let checkboxExist, + showAlert = false, + widgetKey, + requiredCheckbox, + tourPageNumber; // `pageNumber` is used to check on which page user did not fill widget's data then change current pageNumber and show tour message on that page + for (let i = 0; i < checkUser[0].placeHolder.length; i++) { + for (let j = 0; j < checkUser[0].placeHolder[i].pos.length; j++) { + //get current page + const updatePage = checkUser[0].placeHolder[i]?.pageNumber; + //checking checbox type widget + checkboxExist = checkUser[0].placeHolder[i].pos[j].type === "checkbox"; + //condition to check checkbox widget exist or not + if (checkboxExist) { + //get all required type checkbox + requiredCheckbox = checkUser[0].placeHolder[i].pos.filter( + (position) => { + return ( + !position.options?.isReadOnly && position.type === "checkbox" + ); + } + ); + //if required type checkbox data exit then check user checked all checkbox or some checkbox remain to check + //also validate to minimum and maximum required checkbox + if (requiredCheckbox && requiredCheckbox.length > 0) { + for (let i = 0; i < requiredCheckbox.length; i++) { + //get minimum required count if exit + const minCount = + requiredCheckbox[i].options?.validation?.minRequiredCount; + const parseMin = minCount && parseInt(minCount); + //get maximum required count if exit + const maxCount = + requiredCheckbox[i].options?.validation?.maxRequiredCount; + const parseMax = maxCount && parseInt(maxCount); + //in `response` variable is used to get how many checkbox checked by user + const response = requiredCheckbox[i].options?.response?.length; + //in `defaultValue` variable is used to get how many checkbox checked by default + const defaultValue = + requiredCheckbox[i].options?.defaultValue?.length; + const checkboxValue = response ? response : defaultValue; + //condition to check parseMin and parseMax greater than 0 then consider it as a required check box + if ( + parseMin > 0 && + parseMax > 0 && + !response && + !defaultValue && + !showAlert + ) { + showAlert = true; + widgetKey = requiredCheckbox[i].key; + tourPageNumber = updatePage; + setminRequiredCount(parseMin); + } + //else condition to validate minimum required checkbox + else if ( + parseMin > 0 && + (parseMin > checkboxValue || !checkboxValue) + ) { + if (!showAlert) { + showAlert = true; + widgetKey = requiredCheckbox[i].key; + tourPageNumber = updatePage; + setminRequiredCount(parseMin); + } + } + } + } + } + //else condition to check all type widget data fill or not except checkbox + else { + //get all required type widgets except checkbox and radio + const requiredWidgets = checkUser[0].placeHolder[i].pos.filter( + (position) => { + return ( + position.type === "signature" || + (position.options?.status === "required" && + position.type !== "checkbox") + ); + } + ); + if (requiredWidgets && requiredWidgets?.length > 0) { + let checkSigned; + for (let i = 0; i < requiredWidgets?.length; i++) { + checkSigned = requiredWidgets[i]?.options?.response; + if (isEmptyValue(checkSigned)) { + let checkDefaultSigned = + requiredWidgets[i]?.options?.defaultValue; + if (isEmptyValue(checkDefaultSigned) && !showAlert) { + showAlert = true; + widgetKey = requiredWidgets[i].key; + tourPageNumber = updatePage; + setminRequiredCount(null); + } + } + } + } + } + } + //when showAlert is true then break the loop and show alert to fill required data in widgets + if (showAlert) { + break; + } + } + return { tourPageNumber, widgetKey, showAlert }; +}; + +export const decryptPdf = async (file, password) => { + const name = generatePdfName(16); + const baseApi = localStorage.getItem("baseUrl") || ""; + const url = removeTrailingSegment(baseApi) + "/decryptpdf?ts=" + Date.now(); + let formData = new FormData(); + formData.append("file", file); + formData.append("password", password); + const config = { + responseType: "blob", + // The endpoint requires an authenticated caller. + headers: { sessiontoken: localStorage.getItem("accesstoken") || "" } + }; + const response = await axios.post(url, formData, config); + const pdfBlob = new Blob([response.data], { type: "application/pdf" }); + return new File([pdfBlob], name, { type: "application/pdf" }); +}; + +export function base64ToFile(base64String, filename) { + // Separate out the mime-type and the actual Base64 payload + const [header, payload] = base64String.includes(",") + ? base64String.split(",") + : [null, base64String]; + // Determine the MIME type (fallback to application/octet-stream) + const mimeMatch = header?.match(/data:(.*?);base64/); + const mime = mimeMatch ? mimeMatch[1] : "application/octet-stream"; + + // Decode Base64 to raw binary data held in a string + const binaryString = atob(payload); + // Create an ArrayBuffer and a view (as unsigned 8-bit) + const len = binaryString.length; + const u8arr = new Uint8Array(len); + for (let i = 0; i < len; i++) { + u8arr[i] = binaryString.charCodeAt(i); + } + + // Create a File object (Blob subclass) with the binary data + return new File([u8arr], filename, { type: mime }); +} + +export function getFileAsArrayBuffer(file) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = (e) => resolve(e.target.result); + reader.onerror = (e) => reject(e.target.error); + reader.readAsArrayBuffer(file); + }); +} diff --git a/apps/OpenSign/src/constant/utils/pdfWidgetDrawing.js b/apps/OpenSign/src/constant/utils/pdfWidgetDrawing.js new file mode 100644 index 0000000000..c183f08e76 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/pdfWidgetDrawing.js @@ -0,0 +1,504 @@ +import moment from "moment"; +import { degrees } from "pdf-lib"; +import { + isMobile, + drawWidget, + textWidget, + textInputWidget, + radioButtonWidget, + cellsWidget, + randomId +} from "./coreConstants.js"; +import { isEmptyValue } from "./imageHandling.js"; +import { placeholderWidth, placeholderHeight } from "./placeholderTools.js"; +import { compensateRotation } from "./printCertificates.js"; +import { getWidgetPosition } from "./pdfPageView.js"; +import { getWidgetsFontColor, forceBreakLongWord } from "./imageHandling.js"; +import { changeDateToMomentFormat } from "./widgetOptions.js"; +import { isBase64 } from "./imageHandling.js"; + +/** Draw one widget into its PDF page while preserving its field-specific layout. */ +export const drawWidgetPosition = async ({ + id, + position, + images, + ImgTypeWidget, + pdfDoc, + page, + pageNo, + scale, + font, + form, + getSize +}) => { + const isTextTypeWidget = [ + textWidget, + textInputWidget, + cellsWidget, + "name", + "company", + "job title", + "date", + "email" + ].includes(position.type); + + let img; + if (ImgTypeWidget.includes(position.type)) { + if (images[id].mimetype === "image/png") { + img = await pdfDoc.embedPng(images[id].arrayBuffer); + } else { + img = await pdfDoc.embedJpg(images[id].arrayBuffer); + } + } else if (!position.type) { + // to handle old widget when only stamp and signature are exists + if (images[id].mimetype === "image/png") { + img = await pdfDoc.embedPng(images[id].arrayBuffer); + } else { + img = await pdfDoc.embedJpg(images[id].arrayBuffer); + } + } + let widgetWidth, widgetHeight; + widgetWidth = placeholderWidth(position); + widgetHeight = placeholderHeight(position); + const xPos = (position) => { + const resizePos = position.xPosition; + //first two condition handle to old data already saved from mobile view which scale point diffrent + if (isMobile && position.isMobile) { + //if pos.isMobile false -- placeholder saved from desktop view then handle position in mobile view divided by scale + const x = resizePos * (position.scale / scale); + return x * scale; + } else if (position.isMobile && position.scale) { + const x = resizePos * position.scale; + return x; + } else { + return resizePos; + } + }; + const yPos = (position) => { + const resizePos = position.yPosition; + + if (position.isMobile && position.scale) { + if (position.IsResize) { + const y = resizePos * position.scale; + return y; + } else { + const y = resizePos * position.scale; + return y; + } + } else { + const yPosition = isTextTypeWidget ? resizePos + 6 : resizePos; + return yPosition; + } + }; + const color = position?.options?.fontColor; + const updateColorInRgb = getWidgetsFontColor(color); + const fontSize = parseInt(position?.options?.fontSize || 12); + if (position.type === "checkbox") { + // Determine layout mode: 'vertical' (default) or 'horizontal' + const isHorizontal = + position?.options?.layout === "horizontal" ? true : false; + // Initial “cursor” positions + let currentX = xPos(position); + let currentY = yPos(position) + 2; + // Size and spacing settings + const checkboxSize = fontSize - 1; // checkbox diameter + const checkboxTextGapFromLeft = fontSize + 3.4; // gap between box and its label + const verticalGap = fontSize + 5.5; // gap between two options (vertical layout) + let horizontalGap = 0; // will compute after drawing each label + if (position?.options?.values?.length > 0) { + position.options.values.forEach((item, ind) => { + if (ind > 0) { + if (isHorizontal) { + currentX += horizontalGap; + } else { + currentY += verticalGap; + } + } + let isCheck = false; + if ( + position.options.response && + position.options.response?.length > 0 + ) { + isCheck = position.options.response.includes(ind); + } else if (position.options.defaultValue) { + isCheck = position.options.defaultValue.includes(ind); + } + + if (!position.options.isHideLabel) { + const labelX = currentX + checkboxTextGapFromLeft; + const labelY = currentY - 3; + + const optionsPosition = compensateRotation( + page.getRotation().angle, + labelX, + labelY, + 1, + getSize, + fontSize, + updateColorInRgb, + font, + page + ); + page.drawText(item, optionsPosition); + } + const checkboxRandomId = "checkbox" + randomId(); + const checkbox = form.createCheckBox(checkboxRandomId); + let checkboxObj = { + x: currentX, + y: currentY, + width: checkboxSize, + height: checkboxSize + }; + checkboxObj = getWidgetPosition(page, checkboxObj, 1, getSize); + checkbox.addToPage(page, checkboxObj); + // 5. Check or uncheck as needed, then make read‐only + if (isCheck) { + checkbox.check(); + } else { + checkbox.uncheck(); + } + checkbox.enableReadOnly(); + // 6. If horizontal layout, compute how far to shift next checkbox‐circle + if (isHorizontal) { + // Measure the width of this label text at `fontSize` + const textWidth = font.widthOfTextAtSize(item, fontSize); + // Next checkbox should come after: [box] + gap + [label text] + extra 10pt padding + const gap = position.options?.isHideLabel + ? checkboxTextGapFromLeft - 5 + : checkboxTextGapFromLeft + textWidth; + horizontalGap = checkboxSize + gap; + } + }); + } + } else if (isTextTypeWidget) { + let textContent = ""; + if (!isEmptyValue(position?.options?.response)) { + if (position.type === "date" && position.options?.response === "today") { + const getFormat = changeDateToMomentFormat( + position?.options?.validation?.format + ); + textContent = moment().format(getFormat); + } else { + textContent = position.options?.response; + } + } else if (!isEmptyValue(position?.options?.defaultValue)) { + textContent = position?.options?.defaultValue?.toString(); + } + if (position.type === cellsWidget) { + const cellCount = position?.options?.cellCount || textContent.length || 1; + const charWidth = widgetWidth / cellCount; + const y = yPos(position) - 4; + for (let i = 0; i < cellCount; i++) { + const ch = textContent[i] || ""; + const charX = + xPos(position) + + charWidth * i + + (charWidth - font.widthOfTextAtSize(ch, fontSize)) / 2; + const textPosition = compensateRotation( + page.getRotation().angle, + charX, + y, + 1, + getSize, + fontSize, + updateColorInRgb, + font, + page + ); + if (ch) page.drawText(ch, textPosition); + } + } else { + const fixedWidth = widgetWidth; // Set your fixed + textContent = textContent + ?.toString() + ?.replace(/\r\n/g, "\n") + ?.replace(/\r/g, "\n") + ?.replace(/\n+$/, ""); + const isNewOnEnterLineExist = textContent?.includes("\n"); + + // Function to break text into lines based on the fixed width + const NewbreakTextIntoLines = (textContent, width) => { + const lines = []; + let currentLine = ""; + + const words = textContent?.split(" "); + for (let word of words) { + const testLine = currentLine ? currentLine + " " + word : word; + const testWidth = font.widthOfTextAtSize(testLine, fontSize); + + if (testWidth <= width) { + currentLine = testLine; + } else { + // If single long word + if (font.widthOfTextAtSize(word, fontSize) > width) { + // Break a long word into smaller parts character-by-character + const brokenParts = forceBreakLongWord( + word, + width, + font, + fontSize + ); + + // push currentLine before breaking word + if (currentLine.trim()) lines.push(currentLine.trim()); + + // push ALL broken parts in order + brokenParts.forEach((p) => lines.push(p)); + + currentLine = ""; + } else { + // push current line and start new + if (currentLine.trim()) lines.push(currentLine.trim()); + currentLine = word; + } + } + } + if (currentLine.trim()) lines.push(currentLine.trim()); + return lines; + }; + // Function to break text into lines based on when user go next line on press enter button + const breakTextIntoLines = (textContent, width) => { + const finalLines = []; + const paragraphs = textContent.split("\n"); // preserve user order + for (const para of paragraphs) { + const cleanPara = para.replace(/\r/g, ""); + const lineWidth = font.widthOfTextAtSize(cleanPara, fontSize); + //checking string length to container width + //if string length is less then container width it means user press enter button + if (lineWidth <= width) { + // user forced newline + finalLines.push(cleanPara); + } else { + // auto wrap paragraph + finalLines.push(...NewbreakTextIntoLines(cleanPara, width)); + } + } + + return finalLines; + }; + //check if text content have `\n` string it means user press enter to go next line and handle condition + //else auto adjust text content according to container width + const lines = isNewOnEnterLineExist + ? breakTextIntoLines(textContent, fixedWidth) + : NewbreakTextIntoLines(textContent, fixedWidth); + // Set initial y-coordinate for the first line + let x = xPos(position); + let y = yPos(position) - 4; + const computedLineHeight = fontSize * 1.25; + // Embed each line on the page + for (const line of lines) { + const textPosition = compensateRotation( + page.getRotation().angle, + x, + y, + 1, + getSize, + fontSize, + updateColorInRgb, + font, + page + ); + page.drawText(line, textPosition); + y += computedLineHeight; // Proportional line height matching UI (1.25) + } + } + } else if (position.type === "dropdown") { + const dropdownRandomId = "dropdown" + randomId(); + const dropdown = form.createDropdown(dropdownRandomId); + dropdown.addOptions(position?.options?.values); + // A multi-select field stores an array, so every selected value has + // to be applied at once. + if (position?.options?.isMultiSelect && dropdown.enableMultiselect) { + dropdown.enableMultiselect(); + } + const toValues = (value) => { + if (Array.isArray(value)) return value.filter((v) => v != null); + return value ? [value] : []; + }; + const selectedValues = toValues(position?.options?.response).length + ? toValues(position?.options?.response) + : toValues(position?.options?.defaultValue); + if (selectedValues.length > 0) { + const allowed = (position?.options?.values || []).map((v) => + v == null + ? "" + : typeof v === "object" + ? String(v?.name ?? v?.value ?? "") + : String(v) + ); + const picked = selectedValues + .map((v) => + v == null + ? "" + : typeof v === "object" + ? String(v?.name ?? v?.value ?? "") + : String(v) + ) + .filter((v) => v && allowed.includes(v)); + if (picked.length > 0) { + try { + dropdown.select(...picked); + } catch (e) { + // ignore values pdf-lib refuses; keep the rest of the embed + } + } + } + // Define the default appearance string + // Example format: `/FontName FontSize Tf 0 g` where: + // - `/FontName` is the name of the font (e.g., `/Helv` for Helvetica) + // - `FontSize` is the size you want to set (e.g., 12) + // - `Tf` specifies the font and size + // - `0 g` sets the text color to black + const defaultAppearance = `/Helv ${fontSize} Tf 0 g`; + // Set the default appearance for the dropdown field + dropdown.acroField.setDefaultAppearance(defaultAppearance); + dropdown.setFontSize(fontSize); + const dropdownObj = { + x: xPos(position), + y: yPos(position), + width: widgetWidth, + height: widgetHeight + }; + const dropdownOption = getWidgetPosition(page, dropdownObj, 1, getSize); + const dropdownSelected = { + ...dropdownOption, + font: font, + textColor: updateColorInRgb + }; + dropdown.defaultUpdateAppearances(font); + dropdown.addToPage(page, dropdownSelected); + dropdown.enableReadOnly(); + } else if (position.type === radioButtonWidget) { + const radioRandomId = "radio" + randomId(); + const radioGroup = form.createRadioGroup(radioRandomId); + //getting radio buttons options text font size + const optionsFontSize = fontSize; // font size for option text + const radioTextGapFromLeft = fontSize + 3; // gap between circle and its label + const radioSize = fontSize; // circle diameter (square of width×height) + // Initial “cursor” positions (from your existing helpers) + let currentX = xPos(position) + 2; + let currentY = yPos(position) + 3; + // Vertical gap between two options + const verticalGap = fontSize + 5; + // We’ll compute horizontalGap on the fly—after drawing each label + // Initialize to zero (will be set after first option is placed) + let horizontalGap = 0; + // Determine layout mode: 'vertical' or 'horizontal'. + // (You mentioned “add one variable called layout” – here we read it from position.layout.) + const isHorizontal = + position?.options?.layout === "horizontal" ? true : false; + const asOptionText = (value) => + value == null + ? "" + : typeof value === "string" + ? value + : typeof value === "object" + ? String(value?.name ?? value?.value ?? "") + : String(value); + const radioOptions = (position?.options?.values || []).map(asOptionText); + // Loop through each option in the group + if (radioOptions.length > 0) { + radioOptions.forEach((item, ind) => { + // 1. Advance cursor on second+ iteration + if (ind > 0) { + if (isHorizontal) { + // Move to the right by horizontalGap + currentX += horizontalGap; + } else { + // Move down by verticalGap (vertical stacking) + currentY += verticalGap; + } + } + // 2. Draw the label text (if not hidden) + if (!position?.options?.isHideLabel) { + // Compute where to draw the text (just to the right of the circle) + const labelX = currentX + radioTextGapFromLeft; + const labelY = currentY - 2; + const optionsPosition = compensateRotation( + page.getRotation().angle, + labelX, + labelY, + 1, + getSize, + optionsFontSize, + updateColorInRgb, + font, + page + ); + + page.drawText(item, optionsPosition); + } + // 3. Place the radio‐circle itself at (currentX, currentY) + let radioObj = { + x: currentX, + y: currentY, + width: radioSize, + height: radioSize + }; + + radioObj = getWidgetPosition(page, radioObj, 1, getSize); + radioGroup.addOptionToPage(item, page, radioObj); + // 4. If horizontal layout, re-compute horizontalGap for next iteration: + if (isHorizontal) { + // Measure how wide the label text is, so we know how far to shift next circle + const textWidth = font.widthOfTextAtSize(item, optionsFontSize); + // radioSize = the circle. radioTextGapFromLeft = gap between circle and label. + // Add a small extra padding (e.g. 10pt) before placing next circle. + const gap = position?.options?.isHideLabel + ? radioTextGapFromLeft - 6 + : radioTextGapFromLeft + textWidth; + horizontalGap = radioSize + gap; + } + }); + } + // pdf-lib only accepts a string that exists in the option list; + // anything else (NaN, objects, stale values) aborts the whole embed. + const wantedRadio = + asOptionText(position?.options?.response) || + asOptionText(position?.options?.defaultValue); + if (wantedRadio && radioOptions.includes(wantedRadio)) { + try { + radioGroup.select(wantedRadio); + } catch (e) { + // a bad value must not block the document from finishing + } + } + // 6. Set to read‐only (if required) + radioGroup.enableReadOnly(); + } else { + const widgetRotation = position?.options?.rotation || 0; + const isSwapped = [90, 270].includes(widgetRotation); + // Use visual (swapped) dimensions to compute the correct position + const signature = { + x: xPos(position), + y: yPos(position), + width: isSwapped ? widgetHeight : widgetWidth, + height: isSwapped ? widgetWidth : widgetHeight + }; + const imageOptions = getWidgetPosition(page, signature, 1, getSize); + if (widgetRotation) { + const pageRotation = page.getRotation().angle; + const combinedRotation = degrees( + (imageOptions.rotate?.angle || pageRotation) - widgetRotation + ); + const visualWidth = imageOptions.width; + const visualHeight = imageOptions.height; + if (isSwapped) { + // Override with original (unswapped) dimensions for the actual image + imageOptions.width = visualHeight; + imageOptions.height = visualWidth; + } + imageOptions.rotate = combinedRotation; + // Adjust position to compensate for pdf-lib rotation pivot (bottom-left corner) + if (widgetRotation === 90) { + imageOptions.y += visualHeight; + } else if (widgetRotation === 180) { + imageOptions.x += imageOptions.width; + imageOptions.y += imageOptions.height; + } else if (widgetRotation === 270) { + imageOptions.x += visualWidth; + } + } + page.drawImage(img, imageOptions); + } +}; diff --git a/apps/OpenSign/src/constant/utils/placeholderTools.js b/apps/OpenSign/src/constant/utils/placeholderTools.js new file mode 100644 index 0000000000..ccf4c4baa3 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/placeholderTools.js @@ -0,0 +1,235 @@ +import axios from "axios"; +import { generateId } from "./coreConstants.js"; +import { defaultWidthHeight } from "./widgetSizing.js"; + +export function urlValidator(url) { + try { + const newUrl = new URL(url); + return newUrl.protocol === "http:" || newUrl.protocol === "https:"; + } catch (err) { + return false; + } +} + +export const placeholderWidth = (pos) => { + const defaultWidth = defaultWidthHeight(pos.type).width; + const posWidth = pos.Width || defaultWidth; + //condition to handle old data saved from mobile view to get widthh + if (pos.isMobile && pos.scale) { + return pos.IsResize ? posWidth : posWidth * pos.scale; + } else { + return posWidth; + } +}; + +export const placeholderHeight = (pos) => { + const posHeight = pos.Height; + const defaultHeight = defaultWidthHeight(pos.type).height; + const posUpdateHeight = posHeight || defaultHeight; + + //condition to handle old data saved from mobile view to get height + if (pos.isMobile && pos.scale) { + return pos.IsResize ? posUpdateHeight : posUpdateHeight * pos.scale; + } else { + return posUpdateHeight; + } +}; + +export const contactBook = async (objectId) => { + try { + const url = `${localStorage.getItem("baseUrl")}classes/contracts_Contactbook?where={"objectId":"${objectId}"}`; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + "X-Parse-Session-Token": localStorage.getItem("accesstoken") + }; + const axiosRes = await axios.get(url, { headers }); + const result = axiosRes?.data?.results; + return result; + } catch (error) { + console.error("contracts_Contactbook error", err); + return "Error: Something went wrong!"; + } +}; + +export const contractDocument = async (documentId, include) => { + const data = { docId: documentId, include: include }; + const token = { sessionToken: localStorage.getItem("accesstoken") }; + const documentDeatils = await axios + .post(`${localStorage.getItem("baseUrl")}functions/getDocument`, data, { + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + ...token + } + }) + .then((Listdata) => { + const json = Listdata.data; + let data = []; + if (json && json.result.error) { + return json; + } else if (json && json.result) { + data.push(json.result); + return data; + } else { + return []; + } + }) + .catch((err) => { + console.log("Err in getDocument cloud function ", err); + return "Error: Something went wrong!"; + }); + + return documentDeatils; +}; + +export const addDefaultSignatureImg = (xyPosition, defaultSignImg, type) => { + let xyDefaultPos = []; + for (let i = 0; i < xyPosition.length; i++) { + const getXYdata = xyPosition[i].pos; + const getPageNo = xyPosition[i].pageNumber; + const getPosData = getXYdata; + + const addSign = getPosData.map((position) => { + if (position.type) { + if (position?.type === type) { + return { + ...position, + SignUrl: defaultSignImg, + ImageType: "default", + options: { ...position.options, response: defaultSignImg } + }; + } + } else if (position && !position.isStamp) { + return { + ...position, + SignUrl: defaultSignImg, + ImageType: "default", + options: { ...position.options, response: defaultSignImg } + }; + } + return position; + }); + + const newXypos = { pageNumber: getPageNo, pos: addSign }; + xyDefaultPos.push(newXypos); + } + return xyDefaultPos; +}; + +export const getMonth = (date) => { + const newMonth = new Date(date).getMonth(); + return newMonth; +}; + +export const handleCopyNextToWidget = ( + newId, + position, + xyPosition, + index, + setXyPosition, + pdfOriginalWH, + userId +) => { + let filterSignerPos; + + //Get page dimensions + const page = pdfOriginalWH?.find((x) => x?.pageNumber === index); + + const pageWidth = page?.width; + const pageHeight = page?.height; + + // Widget dimensions (fallback safe values) + const widgetWidth = position?.width || 150; + + const widgetHeight = position?.height || 60; + + const gap = 10; + + //Default copy (slightly right + down) + let newX = parseInt(position.xPosition) + gap; + let newY = parseInt(position.yPosition) + gap; + + // Prevent RIGHT overflow + if (pageWidth && newX + widgetWidth > pageWidth) { + newX = parseInt(position.xPosition) - gap; + } + if (newX < 0) newX = 0; + + // Prevent BOTTOM overflow + if (pageHeight && newY + widgetHeight > pageHeight) { + newY = pageHeight - widgetHeight - gap; + } + + if (newY < 0) newY = 0; + + // Get signer position data early for widget name generation + if (userId) { + filterSignerPos = xyPosition.find((data) => data.Id === userId); + } + + // Count same-type widgets to generate a name matching drag-and-drop convention + const countSameWidget = + filterSignerPos?.placeHolder?.reduce((count, page) => { + return ( + count + page.pos.filter((item) => item.type === position?.type).length + ); + }, 0) || 0; + const widgetName = `${position?.type}-${generateId(6)}-${countSameWidget + 1}`; + + const newposition = { + ...position, + xPosition: newX, + yPosition: newY, + key: newId, + options: { ...position?.options, name: widgetName } + }; + + //Your existing update logic + + if (userId) { + filterSignerPos = xyPosition.find((data) => data.Id === userId); + const getPlaceHolder = filterSignerPos?.placeHolder; + const getPageNumer = getPlaceHolder?.filter( + (data) => data.pageNumber === index + ); + const getXYdata = [...(getPageNumer?.[0]?.pos || []), newposition]; + if (getPageNumer && getPageNumer.length > 0) { + const newUpdateSignPos = getPlaceHolder.map((obj) => { + if (obj.pageNumber === index) { + return { ...obj, pos: getXYdata }; + } + return obj; + }); + + const newUpdateSigner = xyPosition.map((obj) => { + if (obj.Id === userId) { + return { ...obj, placeHolder: newUpdateSignPos }; + } + return obj; + }); + + setXyPosition(newUpdateSigner); + } + } else { + const getPageNumer = xyPosition?.find((data) => data.pageNumber === index); + const getXYdata = [...getPageNumer.pos, newposition]; + const updatePlaceholder = xyPosition.map((obj, ind) => { + if (obj?.pageNumber === index) { + return { ...obj, pos: getXYdata }; + } + return obj; + }); + setXyPosition(updatePlaceholder); + } +}; + +export const getFileName = (fileUrl) => { + if (fileUrl) { + const url = new URL(fileUrl); + const filename = url.pathname.substring(url.pathname.indexOf("_") + 1); + return filename || ""; + } else { + return ""; + } +}; diff --git a/apps/OpenSign/src/constant/utils/printCertificates.js b/apps/OpenSign/src/constant/utils/printCertificates.js new file mode 100644 index 0000000000..dd54e147b8 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/printCertificates.js @@ -0,0 +1,259 @@ +import axios from "axios"; +import { saveAs } from "file-saver"; +import printModule from "print-js"; +import i18n from "../../i18n"; +import { color } from "./coreConstants.js"; +import { getBase64FromUrl } from "./coreConstants.js"; +import { appName } from "./coreConstants.js"; + +export const handleToPrint = async (event, setIsDownloading, pdfDetails) => { + event.preventDefault(); + setIsDownloading("pdf"); + const pdfUrl = pdfDetails?.[0]?.SignedUrl || pdfDetails?.[0]?.URL; + const docId = pdfDetails?.[0]?.objectId || ""; + + try { + // const url = await Parse.Cloud.run("getsignedurl", { url: pdfUrl }); + //`localStorage.getItem("baseUrl")` is also use in public-profile flow for public-sign + //if we give this `appInfo.baseUrl` as a base url then in public-profile it will create base url of it's window.location.origin ex- opensign.me which is not base url + const axiosRes = await axios.post( + `${localStorage.getItem("baseUrl")}/functions/getsignedurl`, + { + url: pdfUrl, + docId: docId + }, + { + headers: { + "content-type": "Application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + "X-Parse-Session-Token": localStorage.getItem("accesstoken") + } + } + ); + const url = axiosRes.data.result; + const pdf = await getBase64FromUrl(url); + const isAndroidDevice = navigator.userAgent.match(/Android/i); + const isAppleDevice = + (/iPad|iPhone|iPod/.test(navigator.platform) || + (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)) && + !window.MSStream; + if (isAndroidDevice || isAppleDevice) { + const byteArray = Uint8Array.from( + atob(pdf) + .split("") + .map((char) => char.charCodeAt(0)) + ); + const blob = new Blob([byteArray], { type: "application/pdf" }); + const blobUrl = URL.createObjectURL(blob); + window.open(blobUrl, "_blank"); + setIsDownloading(""); + } else { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`Failed to fetch PDF: ${response.status}`); + } + const blob = await response.blob(); + const blobUrl = URL.createObjectURL(blob); + const iframe = document.createElement("iframe"); + iframe.style.position = "fixed"; + iframe.style.right = "0"; + iframe.style.bottom = "0"; + iframe.style.width = "0"; + iframe.style.height = "0"; + iframe.style.border = "0"; + iframe.src = blobUrl; + document.body.appendChild(iframe); + iframe.onload = () => { + setTimeout(() => { + iframe.contentWindow.focus(); + iframe.contentWindow.print(); + }, 1000); + }; + setIsDownloading(""); + } + } catch (err) { + setIsDownloading(""); + console.log("err in getsignedurl", err); + alert(i18n.t("something-went-wrong-mssg")); + } +}; + +export const downloadCertificate = async (certificate, isZip, asBlob) => { + try { + const appName = "OpenSign™"; + const certificateUrl = certificate; + if (isZip) { + return certificateUrl; + } else { + if (asBlob) { + const fetchCertificate = await fetch(certificateUrl); + // Convert the response into a Blob + const blob = await fetchCertificate.blob(); + saveAs(blob, `Certificate_signed_by_${appName}.pdf`); + return; + } + saveAs(certificateUrl, `Certificate_signed_by_${appName}.pdf`); + } + } catch (err) { + console.error("download certificate err", err); + } +}; + +export const handleDownloadCertificate = async ( + pdfDetails, + setIsDownloading, + isZip +) => { + const baseUrl = `${localStorage.getItem("baseUrl")}functions`; + const parseAppId = localStorage.getItem("parseAppId"); + const sessionToken = localStorage.getItem("accesstoken"); + const docId = pdfDetails?.[0]?.objectId; + const initialCertificateUrl = pdfDetails?.[0]?.CertificateUrl; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": parseAppId + }; + + if (initialCertificateUrl) { + return await downloadCertificate(initialCertificateUrl, isZip); + } else { + setIsDownloading("certificate"); + try { + const data = { docId: docId }; + const docDetails = await axios.post(`${baseUrl}/getDocument`, data, { + headers: { ...headers, sessionToken } + }); + const cert = docDetails?.data?.result?.CertificateUrl; + if (cert) { + const certificateUrl = await downloadCertificate(cert, isZip); + setIsDownloading(""); + return certificateUrl; + } else { + const generateRes = await axios.post( + `${baseUrl}/generatecertificate`, + data, + { headers } + ); + const certificate = generateRes?.data?.result?.CertificateUrl; + if (certificate) { + try { + const certificateUrl = await downloadCertificate( + certificate, + isZip, + true + ); + setIsDownloading(""); + return certificateUrl; + } catch (err) { + console.error("download certificate err", err); + setIsDownloading("certificate_err"); + } + } else { + setIsDownloading("certificate_err"); + } + } + } catch (err) { + setIsDownloading("certificate_err"); + console.error("download certificate err", err); + alert(i18n.t("something-went-wrong-mssg")); + } + } + return null; +}; + +export function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Escape special characters +} + +export async function findContact(value) { + try { + const baseURL = localStorage.getItem("baseUrl"); + const url = `${baseURL}functions/getsigners`; + const token = { + "X-Parse-Session-Token": localStorage.getItem("accesstoken") + }; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + ...token + }; + const axiosRes = await axios.post(url, { search: value }, { headers }); + const contactRes = axiosRes?.data?.result || []; + if (contactRes) { + const res = JSON.parse(JSON.stringify(contactRes)); + return res; + } + } catch (error) { + console.error("Error fetching suggestions:", error); + } +} + +export function compensateRotation( + pageRotation, + x, + y, + scale, + dimensions, + fontSize, + updateColorInRgb, + font, + page +) { + // Ensure pageRotation is between 0 and 360 degrees + pageRotation = ((pageRotation % 360) + 360) % 360; + let rotationRads = (pageRotation * Math.PI) / 180; + + // Coordinates are from bottom-left + let coordsFromBottomLeft = { x: x / scale }; + if (pageRotation === 90 || pageRotation === 270) { + coordsFromBottomLeft.y = dimensions.width - (y + fontSize) / scale; + } else { + coordsFromBottomLeft.y = dimensions.height - (y + fontSize) / scale; + } + + let drawX = null; + let drawY = null; + + if (pageRotation === 90) { + drawX = + coordsFromBottomLeft.x * Math.cos(rotationRads) - + coordsFromBottomLeft.y * Math.sin(rotationRads) + + dimensions.width; + drawY = + coordsFromBottomLeft.x * Math.sin(rotationRads) + + coordsFromBottomLeft.y * Math.cos(rotationRads); + } else if (pageRotation === 180) { + drawX = + coordsFromBottomLeft.x * Math.cos(rotationRads) - + coordsFromBottomLeft.y * Math.sin(rotationRads) + + dimensions.width; + drawY = + coordsFromBottomLeft.x * Math.sin(rotationRads) + + coordsFromBottomLeft.y * Math.cos(rotationRads) + + dimensions.height; + } else if (pageRotation === 270) { + drawX = + coordsFromBottomLeft.x * Math.cos(rotationRads) - + coordsFromBottomLeft.y * Math.sin(rotationRads); + drawY = + coordsFromBottomLeft.x * Math.sin(rotationRads) + + coordsFromBottomLeft.y * Math.cos(rotationRads) + + dimensions.height; + } else if (pageRotation === 0 || pageRotation === 360) { + // No rotation or full rotation + drawX = coordsFromBottomLeft.x; + drawY = coordsFromBottomLeft.y; + } + if (font) { + return { + x: drawX, + y: drawY, + font, + color: updateColorInRgb, + size: fontSize, + rotate: page.getRotation() + }; + } else { + return { x: drawX, y: drawY }; + } +} diff --git a/apps/OpenSign/src/constant/utils/responsibilityRename.characterization.test.js b/apps/OpenSign/src/constant/utils/responsibilityRename.characterization.test.js new file mode 100644 index 0000000000..04f3a53d6b --- /dev/null +++ b/apps/OpenSign/src/constant/utils/responsibilityRename.characterization.test.js @@ -0,0 +1,96 @@ +// @vitest-environment node +// Characterization + spec tests for #69 (residual renames): +// - lock the facade export names (constant/Utils.js): exactly the 141 names +// captured on origin/develop before the rename, byte-identical set. +// - specify the responsibility module paths replacing the nine legacy +// numbered part modules. +// - lock that no numbered legacy part files remain in constant/utils/. +import { describe, it, expect } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); + +// 141 export names captured from origin/develop:apps/OpenSign/src/constant/Utils.js +// before the residual rename. The facade must keep exporting every one of them. +const EXPECTED_FACADE_NAMES = ["addDefaultSignatureImg","addInitialData","addWidgetOptions","addWidgetSelfsignOptions","addZIndex","arrayBufferToBase64","base64ToArrayBuffer","base64ToFile","calculateImgAspectRatio","calculateInitialWidthHeight","cellsWidget","changeDateToMomentFormat","changeImageWH","checkRegularExpress","clearResponse","color","compressedFileSize","contactBook","contractDocument","contractUsers","convertBase64ToFile","convertBase64ToImg","convertJpegToPng","convertPNGtoJPEG","convertPdfArrayBuffer","convertTextToImg","copytoData","createDocument","darkenColor","decryptPdf","defaultMailBody","defaultMailSubject","defaultWidthHeight","deletePdfPage","drawWidget","embedDocId","embedWidgetsToDoc","escapeRegExp","fetchBase64","fetchImageBase64","fetchUrl","fileNameWithUnderscore","fileasbytes","findContact","flattenPdf","fontColorArr","fontsizeArr","formatDateTime","formatDateToDdMmmYyyy","formatTimeInTimezone","generateId","generatePdfName","generateTitleFromFilename","getAppLogo","getBase64FromIMG","getBase64FromUrl","getBase64MimeType","getContainerScale","getDate","getDefaultDate","getDefaultFormat","getDefaultSignature","getDrive","getEnv","getFileAsArrayBuffer","getFileName","getFirstLetter","getFontSizeForHeight","getMonth","getOriginalWH","getSecureUrl","getSignedUrl","getSignerEmail","getSignerPages","getTenantDetails","getUserCountry","getYear","handleBackground","handleCheckResponse","handleCopyNextToWidget","handleCopySignUrl","handleDeleteWidget","handleDownloadCertificate","handleDownloadPdf","handleHeighlightWidget","handleRemoveWidgets","handleRotateWarning","handleSendOTP","handleSignYourselfWidgetResize","handleSignatureType","handleToPrint","handleUnlinkSigner","handleWidgetResize","isBase64","isCustomFileAdapter","isEmptyValue","isHighResolution","isMobile","isRadioSelected","isTab","isTabAndMobile","mailTemplate","months","nameColor","nextPendingWidget","nonPresentMaskCss","onChangeHeightOfTextArea","onChangeInput","onClickZoomIn","onClickZoomOut","onImageSelect","onSaveImage","onSaveSign","openInNewTab","pdfNewWidthFun","pendingButtonZoomScrollRef","placeholderHeight","placeholderWidth","radioButtonWidget","randomId","range","removeBase64Prefix","removeTrailingSegment","reorderPdfPages","replaceMailVaribles","rotatePdfPage","saveLanguageInLocal","selectCheckbox","selectFormat","sendEmailToSigners","signPdfFun","signatureTypes","textInputWidget","textWidget","toDataUrl","updateDateWidgetsRes","urlValidator","usertimezone","widgetDataValue","widgets","years"]; + +const facadeNames = () => { + const src = fs.readFileSync(path.join(here, "..", "Utils.js"), "utf8"); + const names = []; + for (const m of src.matchAll(/export\s*\{([^}]*)\}/g)) { + for (const n of m[1].split(",")) { + const name = n.trim(); + if (name) names.push(name); + } + } + return names.sort(); +}; + +describe("#69 facade exports stay byte-identical (141/141)", () => { + it("exports exactly the captured name set, no more and no less", () => { + expect(facadeNames()).toEqual(EXPECTED_FACADE_NAMES); + }); +}); + +describe("#69 responsibility modules replace legacy numbered part files", () => { + it("the nine responsibility modules exist", () => { + for (const name of [ + "coreConstants.js", + "widgetCatalog.js", + "widgetOptions.js", + "imageHandling.js", + "widgetEmbedding.js", + "tenantDownloads.js", + "printCertificates.js", + "pdfPageView.js", + "pdfPageEdit.js", + "widgetSizing.js", + "widgetState.js", + "widgetInput.js", + "widgetInlineEditing.js", + "signatureSave.js", + "placeholderTools.js", + "pdfFlatten.js", + "pdfFieldDrawing.js", + "widgetResponses.js", + "pdfResponse.js", + "signerMail.js", + "widgetLifecycle.js", + "widgetPrimitives.js" + ]) { + expect( + fs.existsSync(path.join(here, name)), + `${name} exists` + ).toBe(true); + } + }); + + // UtilsPart05 keeps its name on purpose: the #68 function-split slice + // works inside that file, so the facade and prefillUtils still import it. + it("no legacy numbered part files remain (except UtilsPart05)", () => { + const leftovers = fs + .readdirSync(here) + .filter((n) => /^UtilsPart(?!05)\d+\.js$/.test(n)); + expect(leftovers).toEqual([]); + }); + + it("no importer still references a legacy numbered part path (except UtilsPart05)", () => { + const offenders = []; + const walk = (dir) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === "node_modules") continue; + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + walk(full); + } else if (/\.(js|jsx)$/.test(entry.name)) { + const src = fs.readFileSync(full, "utf8"); + if (/UtilsPart(?!05)\d+/.test(src)) offenders.push(full); + } + } + }; + walk(path.join(here, "..", "..")); + expect(offenders).toEqual([]); + }); +}); diff --git a/apps/OpenSign/src/constant/utils/signatureSave.js b/apps/OpenSign/src/constant/utils/signatureSave.js new file mode 100644 index 0000000000..a409df07cf --- /dev/null +++ b/apps/OpenSign/src/constant/utils/signatureSave.js @@ -0,0 +1,215 @@ +import { drawWidget } from "./coreConstants.js"; +import { convertTextToImg } from "./widgetInlineEditing.js"; +import { placeholderHeight } from "./placeholderTools.js"; + +export function onSaveSign( + type, + xyPosition, + index, + signKey, + signatureImg, + updatedImgWH, + isTypeText, + typedSignature, + isAutoSign, + widgetsType, + typeFont, + fontColor +) { + let getIMGWH, posWidth, posHeight; + let getXYdata = xyPosition[index].pos; + const isSignOrInitials = + widgetsType && ["signature", "initials"].includes(widgetsType); + const updateXYData = getXYdata.map((position) => { + if (position.key === signKey) { + if (isTypeText) { + getIMGWH = { + newWidth: updatedImgWH.width, + newHeight: updatedImgWH.height + }; + } + posWidth = getIMGWH ? getIMGWH.newWidth : 150; + posHeight = getIMGWH ? getIMGWH.newHeight : 60; + const widgetDims = { Width: posWidth, Height: posHeight }; + const signImg = typedSignature + ? convertTextToImg(typeFont, typedSignature, fontColor, widgetDims) + : signatureImg; + if (widgetsType === drawWidget) { + return { + ...position, + options: { ...position.options, response: signImg } + }; + } else { + return { + ...position, + ...(type === "type" ? { Width: posWidth } : {}), + ...(type === "type" ? { Height: posHeight } : {}), + SignUrl: signImg, + ...(isSignOrInitials && { signatureType: type || "" }), + options: { ...position.options, response: signImg }, + ...(typedSignature && { + typeSignature: typedSignature, + typeFont: typeFont ?? "Fasthand", + fontColor: fontColor ?? "blue" + }) + }; + } + } + return position; + }); + + const updateXYposition = xyPosition.map((obj, ind) => { + if (ind === index) { + return { ...obj, pos: updateXYData }; + } + return obj; + }); + //condition when draw/upload signature/initials then apply it all related to widgets (draw, typed signature or default signature) + if (isAutoSign && widgetsType !== drawWidget) { + const updatedArray = updateXYposition.map((page) => ({ + ...page, + pos: page.pos.map((item) => { + if (item.type === widgetsType) { + const widgetDims = { Width: item.Width, Height: item.Height }; + const signImg = typedSignature + ? convertTextToImg(typeFont, typedSignature, fontColor, widgetDims) + : signatureImg; + return { + ...item, + SignUrl: signImg, + ...(isSignOrInitials && { signatureType: type || "" }), + options: { ...item.options, response: signImg }, + ...(typedSignature && { + typeSignature: typedSignature, + typeFont: typeFont || "Fasthand", + fontColor: fontColor || "blue" + }) + }; + } + return item; // Otherwise, keep it unchanged + }) + })); + return updatedArray; + } else { + return updateXYposition; + } +} + +export function clearResponse(widgetKey, placeholder = [], index) { + if (!Array.isArray(placeholder) || !placeholder[index]?.pos) { + return placeholder; + } + const getXYdata = placeholder[index]?.pos; + const updateXYData = getXYdata.map((widget) => { + if (widget?.key !== widgetKey) return widget; + return { + ...widget, + options: { ...widget.options, response: "" }, + SignUrl: "" + }; + }); + + const updatePlaceholder = placeholder.map((p, ind) => { + if (ind !== index) return p; + return { ...p, pos: updateXYData }; + }); + return updatePlaceholder; +} + +export async function convertBase64ToImg(base64Image, widgetDims) { + const { Width: maxWidth, Height: maxHeight } = widgetDims; + // Load the image off-DOM + const img = new Image(); + img.src = base64Image; + await new Promise((resolve, reject) => { + img.onload = resolve; + img.onerror = reject; + }); + + // 2. Compute scale to fit within widget (preserving aspect ratio) + const { naturalWidth: imgW, naturalHeight: imgH } = img; + const scale = Math.min(maxWidth / imgW, maxHeight / imgH, 1); + const drawW = imgW * scale; + const drawH = imgH * scale; + + // 3. Prepare a high-DPI canvas + const pxRatio = (window.devicePixelRatio || 1) * 2; + const canvas = document.createElement("canvas"); + canvas.width = Math.ceil(maxWidth * pxRatio); + canvas.height = Math.ceil(maxHeight * pxRatio); + const ctx = canvas.getContext("2d"); + ctx.scale(pxRatio, pxRatio); + ctx.clearRect(0, 0, maxWidth, maxHeight); + + // 4. Center the image in the widget rectangle + const x = (maxWidth - drawW) / 2; + const y = (maxHeight - drawH) / 2; + ctx.drawImage(img, x, y, drawW, drawH); + // 5. Return new base64 in same format as input + // const quality = + // inputMime.includes("jpeg") || inputMime.includes("jpg") ? 0.9 : undefined; + // return canvas.toDataURL(inputMime, quality); + // 5. Always return PNG (lossless, no quality param needed) + return canvas.toDataURL("image/png"); +} + +export const handleCopySignUrl = ( + currentPos, + existSignPosition, + setXyPosition, + xyPosition, + pageNumber, + signerObjectId +) => { + //get current signer details + const currentSigner = xyPosition.filter( + (data) => data.signerObjId === signerObjectId + ); + //get current signer placeholder details + const placeholderPosition = currentSigner[0].placeHolder; + //get current pagenumber position + const getcurrentPagePosition = placeholderPosition.find( + (data) => data.pageNumber === pageNumber + ); + let getXYdata = getcurrentPagePosition.pos; + const updatePos = getXYdata.map((x) => { + //update widgets sign url details + if (x.key === currentPos.key) { + return { + ...x, + // Width: existSignPosition.Width, + // Height: existSignPosition.Height, + SignUrl: existSignPosition.SignUrl, + signatureType: existSignPosition.signatureType, + options: { ...x.options, response: existSignPosition.SignUrl }, + ...(existSignPosition.typedSignature && { + typeSignature: existSignPosition.typedSignature + }) + }; + } + return x; + }); + const updateXYposition = placeholderPosition.map((obj) => { + if (obj.pageNumber === pageNumber) { + return { ...obj, pos: updatePos }; + } + return obj; + }); + const newUpdateSigner = xyPosition.map((obj) => { + if (obj.signerObjId === signerObjectId) { + return { ...obj, placeHolder: updateXYposition }; + } + return obj; + }); + setXyPosition(newUpdateSigner); +}; + +export const calculateImgAspectRatio = (imgWH, pos) => { + let newWidth, newHeight; + + const placeholderHeight = pos && pos.Height ? pos.Height : 60; + const aspectRatio = imgWH.width / imgWH.height; + newWidth = aspectRatio * placeholderHeight; + newHeight = placeholderHeight; + return { newHeight, newWidth }; +}; diff --git a/apps/OpenSign/src/constant/utils/signerMail.js b/apps/OpenSign/src/constant/utils/signerMail.js new file mode 100644 index 0000000000..f3e92c94a1 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/signerMail.js @@ -0,0 +1,246 @@ +import axios from "axios"; +import { replaceMailVaribles } from "./tenantDownloads.js"; +import { mailTemplate } from "./widgetResponses.js"; +import { DEFAULT_COMPLETION_DAYS } from "../runtimeConfig.js"; + +export const sendEmailToSigners = async ( + pdfDetails, + signersdata, + customizeMail, + defaultMail, + isCustomize +) => { + let htmlReqBody; + const owner = pdfDetails?.[0]?.ExtUserPtr; + let sendMail; + const getDocumentExpDate = pdfDetails?.[0]?.ExpiryDate?.iso; + const getTemplateExpDate = new Date(pdfDetails[0]?.createdAt); + getTemplateExpDate.setDate( + getTemplateExpDate.getDate() + + (pdfDetails[0]?.TimeToCompleteDays || DEFAULT_COMPLETION_DAYS) + ); + const expireDate = getDocumentExpDate + ? getDocumentExpDate + : getTemplateExpDate; + const newDate = new Date(expireDate); + const localExpireDate = newDate.toLocaleDateString("en-US", { + day: "numeric", + month: "long", + year: "numeric" + }); + + let senderEmail = + pdfDetails?.[0]?.SenderMail || pdfDetails?.[0]?.ExtUserPtr?.Email; + let senderPhone = pdfDetails?.[0]?.ExtUserPtr?.Phone; + let signerMail = signersdata.slice(); + if (pdfDetails?.[0]?.SendinOrder && pdfDetails?.[0]?.SendinOrder === true) { + signerMail = signerMail[0] ? [signerMail[0]] : []; + } + for (let i = 0; i < signerMail.length; i++) { + try { + let url = `${localStorage.getItem("baseUrl")}functions/sendmailv3`; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + sessionToken: localStorage.getItem("accesstoken") + }; + const objectId = signerMail[i].objectId; + const hostUrl = window.location.origin; + //encode this url value `${pdfDetails?.[0].objectId}/${signerMail[i].Email}/${objectId}` to base64 using `btoa` function + const encodeBase64 = btoa( + `${pdfDetails[0]?.objectId}/${signerMail[i].Email}/${objectId}` + ); + let signPdf = `${hostUrl}/login/${encodeBase64}`; + const orgName = pdfDetails[0]?.ExtUserPtr.Company + ? pdfDetails[0].ExtUserPtr.Company + : ""; + + const useNameAsSender = + pdfDetails?.[0]?.ExtUserPtr?.UseNameAsSender === true; + + const senderName = + pdfDetails?.[0]?.SenderName || pdfDetails?.[0]?.ExtUserPtr?.Name; + + const from = + pdfDetails?.[0]?.SenderName || + (useNameAsSender + ? pdfDetails?.[0]?.ExtUserPtr?.Name || "" + : senderEmail); + + const documentName = `${pdfDetails?.[0].Name}`; + let replaceVar; + + if (customizeMail && isCustomize) { + const replacedRequestBody = customizeMail?.body.replace(/"/g, "'"); + htmlReqBody = + "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body>" + + replacedRequestBody + + "</body> </html>"; + + const variables = { + document_title: documentName, + note: pdfDetails?.[0]?.Note, + sender_name: senderName, + sender_mail: senderEmail, + sender_phone: senderPhone || "", + receiver_name: signerMail[i]?.Name || "", + receiver_email: signerMail[i].Email, + receiver_phone: signerMail[i]?.Phone || "", + expiry_date: localExpireDate, + company_name: orgName, + signing_url: signPdf + }; + replaceVar = replaceMailVaribles( + customizeMail.subject, + htmlReqBody, + variables + ); + } else if (defaultMail?.body && defaultMail?.subject) { + const mailBody = defaultMail?.body; + const mailSubject = defaultMail.subject; + const replacedRequestBody = mailBody.replace(/"/g, "'"); + const htmlReqBody = + "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head><body>" + + replacedRequestBody + + "</body> </html>"; + const variables = { + document_title: documentName, + note: pdfDetails?.[0]?.Note, + sender_name: senderName, + sender_mail: senderEmail, + sender_phone: senderPhone || "", + receiver_name: signerMail[i]?.Name || "", + receiver_email: signerMail[i].Email, + receiver_phone: signerMail[i]?.Phone || "", + expiry_date: localExpireDate, + company_name: orgName, + signing_url: signPdf + }; + replaceVar = replaceMailVaribles(mailSubject, htmlReqBody, variables); + } + const mailparam = { + senderName: senderName, + note: pdfDetails?.[0]?.Note || "", + senderMail: senderEmail, + title: documentName, + organization: orgName, + localExpireDate: localExpireDate, + signingUrl: signPdf + }; + // Pick a role-appropriate default template (viewers get a "view" + // template instead of the "sign" template). + const defaultTemplate = mailTemplate(mailparam); + let params = { + extUserId: owner?.objectId, + recipient: signerMail[i].Email, + subject: replaceVar?.subject + ? replaceVar?.subject + : defaultTemplate.subject, + replyto: senderEmail, + from: from, + html: replaceVar?.body ? replaceVar?.body : defaultTemplate.body + }; + + sendMail = await axios.post(url, params, { headers: headers }); + } catch (error) { + console.log("error", error); + } + } + if (sendMail?.data?.result?.status === "success") { + const sessiontoken = localStorage.getItem("accesstoken"); + if (pdfDetails[0]?.objectId && sessiontoken) { + try { + let data; + if (customizeMail && isCustomize) { + data = { + RequestBody: customizeMail?.body, + RequestSubject: customizeMail.subject, + SendMail: true + }; + } else if (defaultMail?.body && defaultMail?.subject) { + data = { + RequestBody: defaultMail?.body, + RequestSubject: defaultMail?.subject, + SendMail: true + }; + } else { + data = { SendMail: true }; + } + const docUrl = `${localStorage.getItem("baseUrl")}classes/contracts_Document`; + await axios.put(`${docUrl}/${pdfDetails[0]?.objectId}`, data, { + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + "X-Parse-Session-Token": sessiontoken + } + }); + } catch (error) { + const err = error?.response?.data?.error || error?.message; + console.error("Error while updating doc: ", err); + } + } + return { status: "success" }; + } else { + return { status: sendMail?.data?.result?.status }; + } +}; + +export function convertJpegToPng(base64Image, filename) { + if (base64Image) { + const arr = base64Image.split(","); + const mimeMatch = arr[0].match(/:(.*?);/); + if (!mimeMatch) throw new Error("Invalid dataURL"); + const mime = mimeMatch[1]; + const type = mime.split("/")[1]; + if (type === "png") { + return base64Image; + } else { + const bstr = atob(arr[1]); + let n = bstr.length; + const u8arr = new Uint8Array(n); + while (n--) u8arr[n] = bstr.charCodeAt(n); + const inputFile = new File([u8arr], `${filename}.${type}`, { + type: mime + }); + return new Promise((resolve, reject) => { + // ensure it’s JPEG/JPG (you can remove this check if not needed) + if (!/image\/jpe?g/.test(inputFile.type)) { + return reject(new Error("Input must be a JPEG or JPG image")); + } + + // Read the file as a data URL + const reader = new FileReader(); + reader.onerror = () => reject(new Error("Failed to read the file")); + reader.onload = () => { + const img = new Image(); + img.onerror = () => reject(new Error("Failed to load image")); + img.onload = () => { + // draw image onto a canvas + const canvas = document.createElement("canvas"); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext("2d"); + ctx.drawImage(img, 0, 0); + + // directly get PNG as base64 data URL + try { + const pngDataUrl = canvas.toDataURL("image/png"); + resolve(pngDataUrl); + } catch (err) { + reject(new Error("Failed to convert canvas to PNG")); + } + }; + img.src = reader.result; + }; + reader.readAsDataURL(inputFile); + }); + } + } +} + +export const getSignerEmail = (data, signers) => { + const getEmail = + signers?.length > 0 && + signers.find((x) => x.objectId === data.signerObjId)?.Email; + return getEmail; +}; diff --git a/apps/OpenSign/src/constant/utils/tenantDownloads.js b/apps/OpenSign/src/constant/utils/tenantDownloads.js new file mode 100644 index 0000000000..d04c7f782d --- /dev/null +++ b/apps/OpenSign/src/constant/utils/tenantDownloads.js @@ -0,0 +1,240 @@ +import axios from "axios"; +import Parse from "parse"; +import { appInfo } from "../appinfo"; +import { saveAs } from "file-saver"; +import i18n from "../../i18n"; +import { persistBrandPresentation } from "../brandPresentation"; +import { buildDownloadFilename } from "../../utils/fileUtils"; +import { appName } from "./coreConstants.js"; + +export const getAppLogo = async () => { + const domain = window.location.host; + try { + const tenant = await Parse.Cloud.run("getlogobydomain", { + domain: domain + }); + if (tenant) { + const resolvedFavicon = + tenant?.favicon || tenant?.logo || appInfo.fev_Icon; + localStorage.setItem("appname", "OpenSign™"); + localStorage.setItem("favicon", appInfo.fev_Icon); + persistBrandPresentation( + { + appName: tenant?.appname || "OpenSign™", + logo: tenant?.logo || appInfo.applogo, + favicon: resolvedFavicon + }, + "tenant" + ); + return { + logo: tenant?.logo, + favicon: resolvedFavicon, + user: tenant?.user + }; + } + } catch (err) { + console.log("err in getlogo ", err); + localStorage.setItem("favicon", appInfo.fev_Icon); + if (err?.message?.includes("valid JSON")) { + return { logo: appInfo.applogo, user: "exist", error: "invalid_json" }; + } else { + return { logo: appInfo.applogo, user: "exist" }; + } + } +}; + +export const getTenantDetails = async (objectId, contactId) => { + try { + const url = `${localStorage.getItem("baseUrl")}functions/gettenant`; + const parseAppId = localStorage.getItem("parseAppId"); + const accesstoken = localStorage.getItem("accesstoken"); + const token = { "X-Parse-Session-Token": accesstoken }; + const data = { userId: objectId, contactId: contactId }; + const res = await axios.post(url, data, { + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": parseAppId, + ...token + } + }); + if (res.data.result) { + const updateRes = JSON.parse(JSON.stringify(res.data.result)); + return updateRes; + } else { + return ""; + } + } catch (err) { + console.log("err in gettenant", err); + return "user does not exist!"; + } +}; + +export function replaceMailVaribles(subject, body, variables) { + let replacedSubject = subject; + let replacedBody = body; + + for (const variable in variables) { + const regex = new RegExp(`{{${variable}}}`, "g"); + if (subject) { + replacedSubject = replacedSubject.replace(regex, variables[variable]); + } + if (body) { + replacedBody = replacedBody.replace(regex, variables[variable]); + } + } + + const result = { + subject: replacedSubject, + body: replacedBody + }; + return result; +} + +export const copytoData = (url) => { + // navigator.clipboard.writeText(text); + if (navigator.clipboard) { + navigator.clipboard.writeText(url); + } else { + // Fallback for browsers that don't support navigator.clipboard + const textArea = document.createElement("textarea"); + textArea.value = url; + document.body.appendChild(textArea); + textArea.select(); + document.execCommand("copy"); + document.body.removeChild(textArea); + } +}; + +export const convertPdfArrayBuffer = async (url) => { + try { + const response = await fetch(url); + // Check if the response was successful (status 200) + if (!response.ok) { + return "Error"; + } + // Convert the response to ArrayBuffer + const arrayBuffer = await response.arrayBuffer(); + return arrayBuffer; + } catch (error) { + console.error("Error fetching data:", error); + return "Error"; + } +}; + +export const handleSendOTP = async (email) => { + try { + let url = `${localStorage.getItem("baseUrl")}functions/SendOTPMailV1`; + const headers = { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId") + }; + const body = { + email: email + }; + await axios.post(url, body, { headers: headers }); + } catch (error) { + alert(error.message); + } +}; + +export const fetchUrl = async (url, fileName) => { + try { + const response = await fetch(url); + if (!response.ok) { + alert(i18n.t("something-went-wrong-mssg")); + throw new Error("Network response was not ok"); + } + const blob = await response.blob(); + saveAs(blob, fileName); + } catch (error) { + alert(i18n.t("something-went-wrong-mssg")); + console.error("Error downloading the file:", error); + } +}; + +export const getSignedUrl = async (pdfUrl, docId, templateId) => { + //use only axios here due to public template sign + const token = { + "X-Parse-Session-Token": localStorage.getItem("accesstoken") + }; + const axiosRes = await axios.post( + `${localStorage.getItem("baseUrl")}/functions/getsignedurl`, + { + url: pdfUrl, + docId: docId || "", + templateId: templateId || "" + }, + { + headers: { + "content-type": "Application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + ...token + } + } + ); + const url = axiosRes.data.result; + return url; +}; + +export const fetchBase64 = async (pdfBase64, pdfName) => { + // Create a Blob from the Base64 string + const byteCharacters = atob(pdfBase64); + const byteNumbers = new Array(byteCharacters.length) + .fill(0) + .map((_, i) => byteCharacters.charCodeAt(i)); + const byteArray = new Uint8Array(byteNumbers); + const blob = new Blob([byteArray], { type: "application/pdf" }); + + // Create a link element + const link = document.createElement("a"); + link.href = URL.createObjectURL(blob); + link.download = pdfName; + + // Programmatically click the link to trigger the download + document.body.appendChild(link); + link.click(); + + // Clean up + document.body.removeChild(link); + URL.revokeObjectURL(link.href); +}; + +export const handleDownloadPdf = async ( + pdfDetails, + setIsDownloading, + pdfBase64 +) => { + const pdfName = + pdfDetails?.[0]?.Name?.length > 100 + ? pdfDetails?.[0]?.Name?.slice(0, 100) + : pdfDetails?.[0]?.Name || "Document"; + const isCompleted = pdfDetails?.[0]?.IsCompleted || false; + const formatId = pdfDetails?.[0]?.ExtUserPtr?.DownloadFilenameFormat; + const docName = buildDownloadFilename(formatId, { + docName: pdfName, + email: pdfDetails?.[0]?.ExtUserPtr?.Email, + isSigned: isCompleted + }); + if (pdfBase64) { + await fetchBase64(pdfBase64, docName); + setIsDownloading && setIsDownloading(""); + } else { + const pdfUrl = pdfDetails?.[0]?.SignedUrl || pdfDetails?.[0]?.URL; + setIsDownloading && setIsDownloading("pdf"); + const docId = pdfDetails?.[0]?.objectId || ""; + try { + const url = await getSignedUrl(pdfUrl, docId); + await fetchUrl(url, docName); + setIsDownloading && setIsDownloading(""); + } catch (err) { + console.log("err in getsignedurl", err); + setIsDownloading(""); + alert(i18n.t("something-went-wrong-mssg")); + } + } +}; + +export function fileNameWithUnderscore(pdfName) { + // Replace spaces with underscore + return pdfName.replace(/ /g, "_"); +} diff --git a/apps/OpenSign/src/constant/utils/widgetCatalog.js b/apps/OpenSign/src/constant/utils/widgetCatalog.js new file mode 100644 index 0000000000..07358cc1ac --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetCatalog.js @@ -0,0 +1,218 @@ +import axios from "axios"; +import moment from "moment"; +import { format } from "date-fns-tz"; +import { textInputWidget } from "./coreConstants.js"; +import { drawWidget } from "./coreConstants.js"; +import { textWidget } from "./coreConstants.js"; +import { radioButtonWidget } from "./coreConstants.js"; +import { cellsWidget } from "./coreConstants.js"; +import { convertTextToImg } from "./widgetInlineEditing.js"; + +export const nameColor = [ + "#304fbf", + "#7d5270", + "#5f825b", + "#578077", + "#576e80", + "#6d527d", + "#cc00cc", + "#006666", + "#cc00ff", + "#ff9900", + "#336699", + "#cc9900" +]; + +export const toDataUrl = (file) => { + return new Promise((resolve) => { + const reader = new FileReader(); + reader.readAsDataURL(file); + reader.onloadend = (e) => { + resolve(e.target.result); + }; + }); +}; + +export const getDrive = async (documentId, skip = 0, limit = 50) => { + const data = { + docId: documentId && documentId, + limit: limit, + skip: skip + }; + const driveDeatils = await axios + .post(`${localStorage.getItem("baseUrl")}functions/getDrive`, data, { + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": localStorage.getItem("parseAppId"), + sessiontoken: localStorage.getItem("accesstoken") + } + }) + .then((Listdata) => { + const json = Listdata.data; + + if (json && json.result.error) { + return json; + } else if (json && json.result) { + const data = json.result; + return data; + } else { + return []; + } + }) + .catch((err) => { + console.log("Err in getDrive cloud function", err); + return "Error: Something went wrong!"; + }); + + return driveDeatils; +}; + +export const pdfNewWidthFun = (divRef) => { + const pdfWidth = divRef.current.offsetWidth; + return pdfWidth; +}; + +export const handleWidgetResize = ( + ref, + key, + signerPos, + setSignerPos, + pageNumber, + containerScale, + signerId, + showResize +) => { + // Compute widget dimensions only once + const { offsetWidth, offsetHeight } = ref; + const factor = containerScale || 1; + const widgetWidth = offsetWidth / factor; + const widgetHeight = offsetHeight / factor; + + const filterSignerPos = signerPos.filter((data) => data.Id === signerId); + if (filterSignerPos.length > 0) { + const getPlaceHolder = filterSignerPos[0].placeHolder; + const getPageNumer = getPlaceHolder.filter( + (data) => data.pageNumber === pageNumber + ); + if (getPageNumer.length > 0) { + const getXYdata = getPageNumer[0].pos; + const getPosData = getXYdata; + const addSignPos = getPosData.map((url) => { + if (url.key === key) { + // For rotated widgets (90°/270°), the visual dimensions are swapped. + // Store the original-orientation dimensions in the data model. + const rotation = url.options?.rotation || 0; + const isRotSwapped = [90, 270].includes(rotation); + const storedWidth = isRotSwapped ? widgetHeight : widgetWidth; + const storedHeight = isRotSwapped ? widgetWidth : widgetHeight; + const widgetDims = { Width: storedWidth, Height: storedHeight }; + // Base fields for every resized signature + const base = { + ...url, + Width: storedWidth, + Height: storedHeight, + IsResize: showResize ? true : false + }; + // If it's a “type” signature, regenerate the image and options + if (url.typeSignature && url.signatureType === "type") { + const signImg = convertTextToImg( + url.typeFont ?? "Fasthand", + url.typeSignature, + url.fontColor ?? "blue", + widgetDims + ); + return { + ...base, + SignUrl: signImg, + options: { ...url.options, response: signImg } + }; + } + return base; + } + return url; + }); + + const newUpdateSignPos = getPlaceHolder.map((obj) => { + if (obj.pageNumber === pageNumber) { + return { ...obj, pos: addSignPos }; + } + return obj; + }); + + const newUpdateSigner = signerPos.map((obj) => { + if (obj.Id === signerId) { + return { ...obj, placeHolder: newUpdateSignPos }; + } + return obj; + }); + + setSignerPos(newUpdateSigner); + } + } +}; + +export const widgets = [ + { type: "signature", icon: "fa-light fa-pen-nib", iconSize: "20px" }, + { type: "stamp", icon: "fa-light fa-stamp", iconSize: "19px" }, + { type: "initials", icon: "fa-light fa-signature", iconSize: "15px" }, + { type: textInputWidget, icon: "fa-light fa-font", iconSize: "21px" }, + { type: "name", icon: "fa-light fa-user", iconSize: "21px" }, + { type: "job title", icon: "fa-light fa-address-card", iconSize: "17px" }, + { type: "company", icon: "fa-light fa-building", iconSize: "25px" }, + { type: "email", icon: "fa-light fa-envelope", iconSize: "20px" }, + { type: "date", icon: "fa-light fa-calendar-days", iconSize: "20px" }, + { type: textWidget, icon: "fa-light fa-text-width", iconSize: "20px" }, + { type: cellsWidget, icon: "fa-light fa-table-cells", iconSize: "20px" }, + { type: "checkbox", icon: "fa-light fa-square-check", iconSize: "22px" }, + { + type: "dropdown", + icon: "fa-light fa-circle-chevron-down", + iconSize: "19px" + }, + { type: radioButtonWidget, icon: "fa-light fa-circle-dot", iconSize: "20px" }, + { type: "image", icon: "fa-light fa-image", iconSize: "20px" }, + { type: drawWidget, icon: "fa-light fa-pen-nib", iconSize: "20px" } +]; + +export const getDate = (dateformat) => { + const format = dateformat || "MM/DD/YYYY"; + const date = new Date(); + const milliseconds = date.getTime(); + const newDate = moment(milliseconds).format(format); + return newDate; +}; + +export const selectFormat = (data) => { + switch (data) { + case "L": + return "MM/dd/yyyy"; + case "MM/DD/YYYY": + return "MM/dd/yyyy"; + case "DD-MM-YYYY": + return "dd-MM-yyyy"; + case "DD/MM/YYYY": + return "dd/MM/yyyy"; + case "LL": + return "MMMM dd, yyyy"; + case "DD MMM, YYYY": + return "dd MMM, yyyy"; + case "YYYY-MM-DD": + return "yyyy-MM-dd"; + case "MM-DD-YYYY": + return "MM-dd-yyyy"; + case "MM.DD.YYYY": + return "MM.dd.yyyy"; + case "MMM DD, YYYY": + return "MMM dd, yyyy"; + case "MMMM DD, YYYY": + return "MMMM dd, yyyy"; + case "DD MMMM, YYYY": + return "dd MMMM, yyyy"; + case "DD.MM.YYYY": + return "dd.MM.yyyy"; + case "DD-MMM-YYYY": + return "dd-MMM-yyyy"; + default: + return "MM/dd/yyyy"; + } +}; diff --git a/apps/OpenSign/src/constant/utils/widgetCycle.characterization.test.js b/apps/OpenSign/src/constant/utils/widgetCycle.characterization.test.js new file mode 100644 index 0000000000..c46c374859 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetCycle.characterization.test.js @@ -0,0 +1,218 @@ +// @vitest-environment node +// Characterization + spec tests for #68 / #69: +// - lock the observable behavior of widgetSizing / widgetInlineEditing +// - specify the dependency-free cycle break (no sizing <-> editing import) +// - lock the facade export names (constant/Utils.js) +// - the full rename lock (new paths, no legacy files, 141 facade names) +// lives in responsibilityRename.characterization.test.js +import { describe, it, expect } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const read = (name) => fs.readFileSync(path.join(here, name), "utf8"); + +// Minimal browser stubs: coreConstants reads window.innerWidth at import time. +globalThis.window = globalThis.window || { + innerWidth: 1280, + devicePixelRatio: 1, + RUNTIME_ENV: {}, + localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "vitest" } +}; + +const Part04 = await import("./widgetSizing.js"); +const Part08 = await import("./widgetInlineEditing.js"); + +describe("#68 facade exports stay unchanged", () => { + it("keeps every Part04/Part08 export name in constant/Utils.js", () => { + const facade = fs.readFileSync( + path.join(here, "..", "Utils.js"), + "utf8" + ); + for (const name of [ + "defaultWidthHeight", + "arrayBufferToBase64", + "getBase64FromIMG", + "convertPNGtoJPEG", + "handleSignYourselfWidgetResize", + "onChangeHeightOfTextArea", + "calculateInitialWidthHeight", + "widgetDataValue", + "addInitialData", + "embedDocId", + "convertTextToImg" + ]) { + expect(facade.includes(name), `facade still exports ${name}`).toBe(true); + } + }); +}); + +describe("#68 dependency-free cycle break", () => { + it("widgetSizing no longer imports widgetInlineEditing", () => { + expect( + /from\s+["']\.\/widgetInlineEditing(\.js)?["']/.test( + read("widgetSizing.js") + ) + ).toBe(false); + }); + + it("widgetInlineEditing no longer imports widgetSizing", () => { + expect( + /from\s+["']\.\/widgetSizing(\.js)?["']/.test( + read("widgetInlineEditing.js") + ) + ).toBe(false); + }); + + it("both sides share one dependency-free primitive module", () => { + const featureModules = + "widgetCatalog|widgetOptions|widgetState|widgetInput|widgetInlineEditing|signatureSave|imageHandling|widgetEmbedding|tenantDownloads|printCertificates|pdfPageView|pdfPageEdit|pdfFlatten|pdfFieldDrawing|widgetResponses|pdfResponse|signerMail|widgetLifecycle|widgetSizing"; + const names = fs.readdirSync(here); + const primitive = names.find( + (n) => + /^widget[A-Za-z]*\.js$/.test(n) && + !n.startsWith("widgetUtils") && + read(n).includes("defaultWidthHeight") && + !new RegExp(`from\\s+["']\\.\\/(${featureModules})(\\.js)?["']`).test( + read(n) + ) && + !/from\s+["']\.\/UtilsPart05(\.js)?["']/.test(read(n)) + ); + expect( + primitive, + "a dependency-free widget primitive module exists" + ).toBeTruthy(); + }); + + it("the leaf constant module imports no sibling util module (acyclic base)", () => { + expect(/from\s+["']\.\//.test(read("coreConstants.js"))).toBe(false); + }); +}); + +describe("#68 defaultWidthHeight behavior", () => { + it("sizes signature, checkbox, dropdown, initials and image", () => { + expect(Part04.defaultWidthHeight("signature")).toEqual({ + width: 150, + height: 60 + }); + expect(Part04.defaultWidthHeight("checkbox")).toEqual({ + width: 15, + height: 19 + }); + expect(Part04.defaultWidthHeight("dropdown")).toEqual({ + width: 120, + height: 22 + }); + expect(Part04.defaultWidthHeight("initials")).toEqual({ + width: 50, + height: 50 + }); + expect(Part04.defaultWidthHeight("image")).toEqual({ + width: 70, + height: 70 + }); + }); + + it("falls back to 150x60 for unknown types", () => { + expect(Part04.defaultWidthHeight("nope")).toEqual({ + width: 150, + height: 60 + }); + }); +}); + +describe("#68 arrayBufferToBase64 behavior", () => { + it("encodes bytes to base64", () => { + const bytes = new Uint8Array([72, 105]); + expect(Part04.arrayBufferToBase64(bytes.buffer)).toBe("SGk="); + }); +}); + +describe("#68 handleSignYourselfWidgetResize behavior", () => { + const xyPosition = [ + { + pos: [ + { key: "a", Width: 10, Height: 10, options: {} }, + { key: "b", Width: 10, Height: 10, options: {} } + ] + } + ]; + + it("resizes only the targeted widget and flags IsResize", () => { + let next; + Part04.handleSignYourselfWidgetResize( + { offsetWidth: 300, offsetHeight: 120 }, + "b", + xyPosition, + (v) => (next = v), + 0, + 2 + ); + expect(next[0].pos[0].key).toBe("a"); + expect("IsResize" in next[0].pos[0]).toBe(false); + expect(next[0].pos[1]).toMatchObject({ + key: "b", + Width: 150, + Height: 60, + IsResize: true + }); + }); + + it("ignores an invalid index without calling the setter", () => { + let called = false; + Part04.handleSignYourselfWidgetResize( + { offsetWidth: 300, offsetHeight: 120 }, + "b", + xyPosition, + () => (called = true), + 5, + 1 + ); + expect(called).toBe(false); + }); +}); + +describe("#68 onChangeHeightOfTextArea behavior", () => { + it("grows the targeted widget in the self-sign path", () => { + const xyPosition = [{ pos: [{ key: "k", Height: 20 }] }]; + let next; + Part08.onChangeHeightOfTextArea( + 5, + "text", + "k", + xyPosition, + 0, + (v) => (next = v) + ); + expect(next[0].pos[0].Height).toBe(25); + }); + + it("falls back to the default height when none is stored", () => { + const xyPosition = [{ pos: [{ key: "k" }] }]; + let next; + Part08.onChangeHeightOfTextArea( + 5, + "checkbox", + "k", + xyPosition, + 0, + (v) => (next = v) + ); + expect(next[0].pos[0].Height).toBe(19 + 5); + }); +}); + +describe("#68 widgetDataValue behavior", () => { + it("maps profile fields case-insensitively", () => { + expect(Part08.widgetDataValue("name", { Name: "Ada" })).toBe("Ada"); + expect(Part08.widgetDataValue("email", { email: "a@b.c" })).toBe("a@b.c"); + expect(Part08.widgetDataValue("job title", { JobTitle: "Eng" })).toBe("Eng"); + }); + + it("returns an empty string for unknown types", () => { + expect(Part08.widgetDataValue("signature", {})).toBe(""); + }); +}); diff --git a/apps/OpenSign/src/constant/utils/widgetEmbedding.js b/apps/OpenSign/src/constant/utils/widgetEmbedding.js new file mode 100644 index 0000000000..1ef8a883dd --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetEmbedding.js @@ -0,0 +1,137 @@ +import fontkit from "@pdf-lib/fontkit"; +import { getRuntimePdfFontUrl } from "../runtimeConfig"; +import { drawWidget } from "./coreConstants.js"; +import { radioButtonWidget } from "./coreConstants.js"; +import { fileasbytes } from "./coreConstants.js"; +import { isBase64, isEmptyValue } from "./imageHandling.js"; +import { convertBase64ToImg } from "./signatureSave.js"; +import { drawWidgetPosition } from "./pdfWidgetDrawing"; + +export const embedWidgetsToDoc = async ( + widgets, + pdfDoc, + signyourself, + scale, + prefillImg +) => { + // `fontBytes` is used to embed custom font in pdf + const pdfFontUrl = getRuntimePdfFontUrl(); + if (!pdfFontUrl) throw new Error("A PDF font URL is required."); + const fontBytes = await fileasbytes(pdfFontUrl); + pdfDoc.registerFontkit(fontkit); + const font = await pdfDoc.embedFont(fontBytes, { subset: true }); + let hasError = false; + for (let item of widgets) { + if (hasError) break; // Stop the outer loop if an error occurred + const typeExist = item.pos.some((data) => data?.type); + let updateItem; + if (typeExist) { + if (signyourself) { + updateItem = item.pos; + } else { + // Checking required and optional widget types + // For both required and optional widgets, handle signurl, defaultValue, and response as the widget's data + // If the widget type is checkbox or radio (whether required or optional), we don't need to validate its value. + // Instead, add an empty checkbox/radio, or if a value exists, mark the checkbox/radio as checked. + updateItem = item.pos.filter( + (data) => + data?.options?.SignUrl || + !isEmptyValue(data?.options?.defaultValue) || + !isEmptyValue(data?.options?.response) || + data?.type === "checkbox" || + data?.type === radioButtonWidget + ); + } + } else { + updateItem = item.pos; + } + const ImgTypeWidget = [ + "signature", + "stamp", + "initials", + "image", + drawWidget + ]; + const pageNo = item.pageNumber; + const widgetsPositionArr = updateItem; + const pages = pdfDoc.getPages(); + const form = pdfDoc.getForm(); + const page = pages[pageNo - 1]; + // `page.getCropBox()` returns the visible area of the PDF page. + // It provides an object with the following properties: + // - x: the x-coordinate of the lower-left corner of the visible area + // - y: the y-coordinate of the lower-left corner of the visible area + // - width: the width of the visible area (x1 - x0) + // - height: the height of the visible area (y1 - y0) + // If the page does not explicitly define a CropBox, this method returns + // the MediaBox instead, which represents the full physical size of the page. + // + // Example CropBox: [0, 7.92, 612, 799.92] + // => x = 0, y = 7.92, width = 612 - 0 = 612, height = 799.92 - 7.92 = 792 + // This is equivalent to `react-pdf`'s `page.view` array: [x0, y0, x1, y1] + const { _, y, width, height } = page.getCropBox(); + const originalHeight = height + y; + let images; + const getSize = { height: originalHeight, width: width }; + try { + images = await Promise.all( + widgetsPositionArr.map(async (widget) => { + // `SignUrl` this is wrong nomenclature and maintain for older code in this options we save base64 of signature image from sign pad + let signbase64 = widget?.options?.response; + const widgetDims = { Width: widget.Width, Height: widget.Height }; + if (signbase64 && ImgTypeWidget.includes(widget.type)) { + if (!isBase64(signbase64) && prefillImg) { + const imgData = prefillImg?.find((x) => x?.id === widget?.key); + signbase64 = imgData?.base64; + } + // let arr = signbase64.split(","); + // const mime = arr[0].match(/:(.*?);/)[1]; + const signatureImg = await convertBase64ToImg( + signbase64, + widgetDims + ); + const mime = signatureImg?.split(",")?.[0]?.match(/:(.*?);/)?.[1]; + const res = await fetch(signatureImg); + const arrayBuffer = await res.arrayBuffer(); + const obj = { mimetype: mime, arrayBuffer: arrayBuffer }; + return obj; + } + }) + ); + } catch (e) { + console.log("error in image", e); + } + for (let [id, position] of widgetsPositionArr.entries()) { + if (hasError) break; // Stop the inner loop if an error occurred + try { + await drawWidgetPosition({ + id, + position, + images, + ImgTypeWidget, + pdfDoc, + page, + pageNo, + scale, + font, + form, + getSize + }); + } catch (err) { + console.log("Err in embed widget on page ", pageNo, err); + hasError = true; + break; + } + } + form?.flatten(); + } + if (!hasError) { + const pdfBytes = await pdfDoc.saveAsBase64({ useObjectStreams: false }); + return pdfBytes; + } else { + return { + error: + "This pdf is not compatible with opensign please contact <support@opensignlabs.com>" + }; + } +}; diff --git a/apps/OpenSign/src/constant/utils/widgetInlineEditing.js b/apps/OpenSign/src/constant/utils/widgetInlineEditing.js new file mode 100644 index 0000000000..269392ed0d --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetInlineEditing.js @@ -0,0 +1,231 @@ +import { rgb } from "pdf-lib"; +import fontkit from "@pdf-lib/fontkit"; +import { getRuntimePdfFontUrl } from "../runtimeConfig"; +import { fileasbytes } from "./coreConstants.js"; +import { defaultWidthHeight } from "./widgetPrimitives.js"; +import { convertTextToImg } from "./widgetPrimitives.js"; +import { compensateRotation } from "./printCertificates.js"; +import { appName } from "./coreConstants.js"; +import { color } from "./coreConstants.js"; + +// Re-exported so the facade (constant/Utils.js) keeps its source module. +export { convertTextToImg }; + +// Grow one position entry, falling back to the widget default height. +const growPositionHeight = (position, signKey, widgetType, delta) => { + if (position.key !== signKey) return position; + return { + ...position, + Height: position.Height + ? position.Height + delta + : defaultWidthHeight(widgetType).height + delta + }; +}; + +// Self-sign flow: positions live directly on the page entry. +const growSelfSignedHeight = ( + xyPosition, + index, + signKey, + widgetType, + delta, + setXyPosition +) => { + const getXYdata = xyPosition[index].pos; + const updatePosition = getXYdata.map((position) => + growPositionHeight(position, signKey, widgetType, delta) + ); + const updatePlaceholder = xyPosition.map((obj, ind) => { + if (ind === index) { + return { ...obj, pos: updatePosition }; + } + return obj; + }); + setXyPosition(updatePlaceholder); +}; + +// Signer flow: positions live under the signer's placeholders. +const growSignerHeight = ( + signerPos, + userId, + index, + signKey, + widgetType, + delta, + setXyPosition, + xyPosition +) => { + const filterSignerPos = signerPos.filter((data) => data.Id === userId); + const getPlaceHolder = filterSignerPos[0]?.placeHolder; + const getPageNumer = getPlaceHolder.filter( + (data) => data.pageNumber === index + ); + if (getPageNumer.length === 0) return; + const addSignPos = getPageNumer[0].pos.map((position) => + growPositionHeight(position, signKey, widgetType, delta) + ); + const newUpdateSignPos = getPlaceHolder.map((obj) => { + if (obj.pageNumber === index) { + return { ...obj, pos: addSignPos }; + } + return obj; + }); + const newUpdateSigner = xyPosition.map((obj) => { + if (obj.Id === userId) { + return { ...obj, placeHolder: newUpdateSignPos }; + } + return obj; + }); + setXyPosition(newUpdateSigner); +}; + +export const onChangeHeightOfTextArea = ( + height, + widgetType, + signKey, + xyPosition, + index, + setXyPosition, + userId +) => { + const isSigners = xyPosition.some((data) => data.signerPtr); + if (!isSigners) { + growSelfSignedHeight( + xyPosition, + index, + signKey, + widgetType, + height, + setXyPosition + ); + return; + } + let filterSignerPos; + if (userId) { + filterSignerPos = xyPosition.filter((data) => data.Id === userId); + } + growSignerHeight( + filterSignerPos, + userId, + index, + signKey, + widgetType, + height, + setXyPosition, + xyPosition + ); +}; + +export const calculateInitialWidthHeight = (widgetData) => { + const intialText = widgetData; + const span = document.createElement("span"); + span.textContent = intialText; + span.style.font = `12px`; // here put your text size and font family + span.style.display = "hidden"; + document.body.appendChild(span); + const width = span.offsetWidth; + const height = span.offsetHeight; + + document.body.removeChild(span); + return { getWidth: width, getHeight: height }; +}; + +export const widgetDataValue = (type, value) => { + switch (type) { + case "name": + return value?.Name || value?.name; + case "company": + return value?.Company || value?.company; + case "job title": + return value?.JobTitle || value?.jobTitle; + case "email": + return value?.Email || value?.email; + default: + return ""; + } +}; + +export const addInitialData = (signerPos, setXyPosition, value, userId) => { + return signerPos.map((item) => { + if (item.placeHolder && item.placeHolder.length > 0) { + // If there is a nested array, recursively add the field to the last object + if (item.Id === userId) { + return { + ...item, + placeHolder: addInitialData( + item.placeHolder, + setXyPosition, + value, + userId + ) + }; + } else { + return item; + } + } else if (item.pos && item.pos.length > 0) { + // If there is no nested array, add the new field + return { + ...item, + pos: addInitialData(item.pos, setXyPosition, value, userId) + // Adjust this line to add the desired field + }; + } else { + const widgetData = widgetDataValue(item.type, value); + if (["name", "company", "job title", "email"].includes(item.type)) { + return { + ...item, + options: { + ...item.options, + defaultValue: item?.options?.defaultValue || widgetData + } + }; + } else { + return item; + } + } + }); +}; + +export const embedDocId = async (pdfOriginalWH, pdfDoc, documentId) => { + const appName = "OpenSign™"; + // `fontBytes` is used to embed custom font in pdf + const pdfFontUrl = getRuntimePdfFontUrl(); + if (!pdfFontUrl) throw new Error("A PDF font URL is required."); + const fontBytes = await fileasbytes(pdfFontUrl); + pdfDoc.registerFontkit(fontkit); + const font = await pdfDoc.embedFont(fontBytes, { subset: true }); + //pdfOriginalWH contained all pdf's width and height of pages + for (let i = 0; i < pdfOriginalWH?.length; i++) { + await embedDocIdOnPage(pdfDoc, pdfOriginalWH, i, documentId, font, appName); + } +}; + +// Draw the document-id footer on one page, tolerating rotated pages. +const embedDocIdOnPage = async ( + pdfDoc, + pdfOriginalWH, + pageIndex, + documentId, + font, + appName +) => { + const fontSize = 10; + const textContent = documentId && `${appName} DocumentId: ${documentId} `; + const page = pdfDoc.getPages()[pageIndex]; + try { + const getObj = compensateRotation( + page.getRotation().angle, + 10, + 5, + 1, + pdfOriginalWH[pageIndex], + fontSize, + rgb(0.5, 0.5, 0.5), + font, + page + ); + page.drawText(textContent, getObj); + } catch (err) { + console.log("Err in embed docId on page", pageIndex + 1, err?.message); + } +}; diff --git a/apps/OpenSign/src/constant/utils/widgetInput.js b/apps/OpenSign/src/constant/utils/widgetInput.js new file mode 100644 index 0000000000..d04a7e2cdb --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetInput.js @@ -0,0 +1,191 @@ +import { format } from "date-fns-tz"; +import { applyNumberFormulasToPages } from "../../utils/widgetUtils"; +import { textInputWidget } from "./coreConstants.js"; +import { getDuplicateAutoApplyName } from "./coreConstants.js"; +import { reuseUnchangedWidgets } from "./widgetState.js"; +import { addInitialData } from "./widgetInlineEditing.js"; + +export const onChangeInput = ( + value, + currentPosition, + xyPosition, + index, + setXyPosition, + userId, + initial, + dateFormat, + fontSize, + fontColor, + dateDetails, + textWidgetHeight +) => { + const isDuplicateValueUpdate = !dateFormat && !textWidgetHeight; + const shouldAutoApplyDuplicateWidget = (position) => { + const currentName = getDuplicateAutoApplyName(currentPosition); + const positionName = getDuplicateAutoApplyName(position); + return currentName && positionName && currentName === positionName; + }; + const applyDuplicateWidgetValue = (position) => { + if ( + position?.options?.response === value && + position?.options?.defaultValue === "" + ) { + return position; + } + return { + ...position, + options: { + ...position.options, + response: value, + defaultValue: "" + } + }; + }; + const isSigners = xyPosition.some( + (data) => data.signerPtr || data.Role === "prefill" + ); + let filterSignerPos; + if (isSigners) { + if (userId) { + filterSignerPos = xyPosition.filter((data) => data.Id === userId); + } + const getPlaceHolder = filterSignerPos[0]?.placeHolder; + if (initial) { + const xyData = addInitialData(xyPosition, setXyPosition, value, userId); + setXyPosition(xyData); + } else { + const getPageNumer = getPlaceHolder.filter( + (data) => data.pageNumber === index + ); + if (getPageNumer.length > 0) { + const updatePositionValue = (position) => { + if (position.key === currentPosition.key) { + if (dateFormat) { + return { + ...position, + options: { + ...position.options, + response: value, + fontSize: fontSize ? fontSize : position.options?.fontSize, + fontColor: fontColor + ? fontColor + : position.options?.fontColor, + isReadOnly: + dateDetails && dateDetails?.isReadOnly !== "undefined" + ? dateDetails?.isReadOnly + : position.options?.isReadOnly, + status: + dateDetails && dateDetails?.status !== "undefined" + ? dateDetails?.status + : position.options?.status, + name: + dateDetails && dateDetails?.name !== "undefined" + ? dateDetails?.name + : position.options?.name, + validation: { + type: "date-format", + format: dateFormat // This indicates the required date format explicitly. + }, + hint: dateDetails?.hint || position.options?.hint || "" + } + }; + } else if ( + (currentPosition?.type === "text" || + currentPosition?.type === textInputWidget) && + textWidgetHeight && + !value + ) { + const dimension = [90, 270].includes(position.options?.rotation) + ? "Width" + : "Height"; + return { ...position, [dimension]: textWidgetHeight }; + } else { + return applyDuplicateWidgetValue(position); + } + } + if ( + isDuplicateValueUpdate && + shouldAutoApplyDuplicateWidget(position) + ) { + return applyDuplicateWidgetValue(position); + } + return position; + }; + setXyPosition((prevPosition) => { + const sourcePosition = Array.isArray(prevPosition) + ? prevPosition + : xyPosition; + return sourcePosition.map((obj) => { + if (obj.Id !== userId) { + return obj; + } + const updatedPlaceHolder = (obj.placeHolder || []).map((page) => ({ + ...page, + pos: page.pos.map(updatePositionValue) + })); + return { + ...obj, + placeHolder: reuseUnchangedWidgets( + obj.placeHolder || [], + applyNumberFormulasToPages(updatedPlaceHolder) + ) + }; + }); + }); + } + } + } else { + const updatePositionValue = (positionData) => { + if (positionData.key === currentPosition.key) { + if (dateFormat) { + return { + ...positionData, + options: { + ...positionData.options, + response: value, + fontSize: fontSize, + fontColor: fontColor, + validation: { + type: "date-format", + format: dateFormat // This indicates the required date format explicitly. + } + } + }; + } else if ( + (currentPosition?.type === "text" || + currentPosition?.type === textInputWidget) && + textWidgetHeight && + !value + ) { + const dimension = [90, 270].includes(positionData.options?.rotation) + ? "Width" + : "Height"; + return { ...positionData, [dimension]: textWidgetHeight }; + } else { + return applyDuplicateWidgetValue(positionData); + } + } + if ( + isDuplicateValueUpdate && + shouldAutoApplyDuplicateWidget(positionData) + ) { + return applyDuplicateWidgetValue(positionData); + } + return positionData; + }; + + setXyPosition((prevPosition) => { + const sourcePosition = Array.isArray(prevPosition) + ? prevPosition + : xyPosition; + const updatePlaceholder = sourcePosition.map((obj) => ({ + ...obj, + pos: obj.pos.map(updatePositionValue) + })); + return reuseUnchangedWidgets( + sourcePosition, + applyNumberFormulasToPages(updatePlaceholder) + ); + }); + } +}; diff --git a/apps/OpenSign/src/constant/utils/widgetLifecycle.js b/apps/OpenSign/src/constant/utils/widgetLifecycle.js new file mode 100644 index 0000000000..f8507870be --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetLifecycle.js @@ -0,0 +1,105 @@ +import moment from "moment"; +import { format } from "date-fns-tz"; +import { changeDateToMomentFormat } from "./widgetOptions.js"; + +export const handleDeleteWidget = (key, Id, pageNumber, signerPos) => { + // Find the signer by ID + const signer = signerPos.find((item) => item.Id === Id); + if (!signer || !signer.placeHolder) return signerPos; + + const placeHolder = signer.placeHolder; + + // Find the page inside placeHolder + const currentPage = placeHolder.find((p) => p.pageNumber === pageNumber); + if (!currentPage) return signerPos; + + // Remove widget from the selected page + const updatedPos = currentPage.pos.filter((w) => w.key !== key); + + // ------------------------------------------------------- + // CASE A → After deletion, page still has widgets then keep that widgets + // ------------------------------------------------------- + if (updatedPos.length > 0) { + const updatedPlaceHolder = placeHolder.map((p) => + p.pageNumber === pageNumber ? { ...p, pos: updatedPos } : p + ); + + return signerPos.map((s) => + s.Id === Id ? { ...s, placeHolder: updatedPlaceHolder } : s + ); + } + + // ------------------------------------------------------- + // CASE B → current page becomes empty → remove current page entirely and keep another pages which have widgets + // ------------------------------------------------------- + const remainPages = placeHolder.filter((p) => p.pageNumber !== pageNumber); + + //`remainPages` keep another pages's data which have widgets + if (remainPages.length > 0) { + const index = signerPos.findIndex((s) => s.Id === Id); + if (index === -1) return signerPos; + + const newSignerPos = [...signerPos]; + newSignerPos[index] = { + ...newSignerPos[index], + placeHolder: remainPages + }; + + return newSignerPos; + } + + // ------------------------------------------------------- + // CASE C → No pages have widgets after delete widgets + // Remove placeHolder field for particular signers, EXCEPT prefill role + // ------------------------------------------------------- + const updatedData = signerPos + .map((s) => { + if (s.Id === Id && s.Role === "prefill") return null; // remove whole signer + if (s.Id === Id) { + const updated = { ...s }; + delete updated.placeHolder; + return updated; + } + return s; + }) + .filter(Boolean); // remove nulls (deleted items) + + return updatedData; +}; + +export const getDefaultDate = (dateStr, format) => { + //get valid date format for moment to convert formatted date to new Date() format + const formats = changeDateToMomentFormat(format); + const parsedDate = moment(dateStr, formats); + let date; + if (parsedDate.isValid()) { + date = new Date(parsedDate.toISOString()); + return date; + } else if (dateStr === "today") { + date = new Date(); + return date; + } +}; + +export const getDefaultFormat = (dateFormat) => dateFormat || "MM/dd/yyyy"; + +export const handleBackground = (data, isNeedSign, uniqueId) => { + if (data) { + if (isNeedSign) { + if (data?.Id === uniqueId) { + return data?.blockColor + "b0"; + } else { + return "#dedddc"; + } + } else { + return data?.blockColor + "b0"; + } + } else { + return "rgba(203, 233, 237, 0.69)"; + } +}; + +export function getBase64MimeType(base64) { + const match = base64.match(/^data:(image\/[a-zA-Z0-9+.-]+);base64,/); + return match ? match[1] : null; +} diff --git a/apps/OpenSign/src/constant/utils/widgetOptions.js b/apps/OpenSign/src/constant/utils/widgetOptions.js new file mode 100644 index 0000000000..a77bcadee5 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetOptions.js @@ -0,0 +1,249 @@ +import { format } from "date-fns-tz"; +import { addPreferenceOpt } from "../../utils/widgetUtils"; +import { textInputWidget } from "./coreConstants.js"; +import { drawWidget } from "./coreConstants.js"; +import { textWidget } from "./coreConstants.js"; +import { radioButtonWidget } from "./coreConstants.js"; +import { cellsWidget } from "./coreConstants.js"; +import { generateId } from "./coreConstants.js"; +import { selectFormat } from "./widgetCatalog.js"; + +export const changeDateToMomentFormat = (format) => { + switch (format) { + case "MM/dd/yyyy": + return "L"; + case "dd-MM-yyyy": + return "DD-MM-YYYY"; + case "dd/MM/yyyy": + return "DD/MM/YYYY"; + case "MMMM dd, yyyy": + return "LL"; + case "dd MMM, yyyy": + return "DD MMM, YYYY"; + case "yyyy-MM-dd": + return "YYYY-MM-DD"; + case "MM-dd-yyyy": + return "MM-DD-YYYY"; + case "MM.dd.yyyy": + return "MM.DD.YYYY"; + case "MMM dd, yyyy": + return "MMM DD, YYYY"; + case "dd MMMM, yyyy": + return "DD MMMM, YYYY"; + case "dd.MM.yyyy": + return "DD.MM.YYYY"; + case "dd-MMM-yyyy": + return "DD-MMM-YYYY"; + default: + return "L"; + } +}; + +export const getSignerPages = (xyPosition = [], currentKey, signerId) => { + if (!Array.isArray(xyPosition)) { + return []; + } + const hasSigners = xyPosition.some((item) => + Array.isArray(item?.placeHolder) + ); + if (hasSigners) { + const candidates = + signerId !== undefined && signerId !== null && signerId !== "" + ? xyPosition.filter( + (item) => item.Id === signerId || item.signerObjId === signerId + ) + : xyPosition; + for (const signer of candidates) { + const pages = signer?.placeHolder || []; + const ownsWidget = pages.some((page) => + (page?.pos || []).some((widget) => widget?.key === currentKey) + ); + if (ownsWidget) { + return pages; + } + } + return []; + } + return xyPosition; +}; + +export const addWidgetOptions = ( + type, + signer, + placeholder, + role, + widgetValue +) => { + let defaultOpt; + const id = generateId(6); + if (placeholder) { + const countSameWidget = placeholder?.reduce((count, page) => { + return count + page.pos.filter((item) => item.type === type).length; + }, 0); + const count = countSameWidget + 1; + defaultOpt = { name: `${type}-${id}-${count}`, status: "required" }; + } else { + defaultOpt = { name: `${type}-${id}-1`, status: "required" }; + } + switch (type) { + case "signature": + return defaultOpt; + case "stamp": + return defaultOpt; + case "checkbox": + return { ...defaultOpt, isReadOnly: false, isHideLabel: false }; + case textInputWidget: + return { + ...defaultOpt, + isReadOnly: false + }; + case cellsWidget: + return { + ...defaultOpt, + cellCount: 5, + defaultValue: "", + validation: { type: "", pattern: "" }, + isReadOnly: false + }; + case "initials": + return defaultOpt; + case "name": + return { + ...defaultOpt, + defaultValue: widgetValue ? widgetValue : "" + }; + case "company": + return { + ...defaultOpt, + defaultValue: widgetValue ? widgetValue : "" + }; + case "job title": + return { + ...defaultOpt, + defaultValue: widgetValue ? widgetValue : "" + }; + case "date": { + const dateFormat = signer?.DateFormat + ? selectFormat(signer?.DateFormat) + : "MM/dd/yyyy"; + const options = addPreferenceOpt(signer, "date", role); + return { + ...defaultOpt, + response: options?.response || "", + isReadOnly: options?.isReadOnly || false, + validation: { + format: options?.format || dateFormat, + type: "date-format" + } + }; + } + case "image": + return defaultOpt; + case "email": + return { + ...defaultOpt, + validation: { type: "email", pattern: "" }, + defaultValue: widgetValue ? widgetValue : "" + }; + case "dropdown": + return defaultOpt; + case radioButtonWidget: + return { + ...defaultOpt, + values: [], + isReadOnly: false + }; + case textWidget: + return defaultOpt; + case drawWidget: + return defaultOpt; + default: + return {}; + } +}; + +export const addWidgetSelfsignOptions = ( + type, + getWidgetValue, + owner, + placeholder, + isSignyourself +) => { + let defaultOpt; + //condition to handle widgets name field + const id = generateId(6); + if (placeholder) { + const countSameWidget = placeholder?.reduce((count, page) => { + return count + page.pos.filter((item) => item.type === type).length; + }, 0); + const count = countSameWidget + 1; + defaultOpt = { name: `${type}-${id}-${count}`, status: "required" }; + } else { + defaultOpt = { name: `${type}-${id}-1`, status: "required" }; + } + switch (type) { + case "signature": + return defaultOpt; + case "stamp": + return defaultOpt; + case "checkbox": + return defaultOpt; + case textWidget: + return defaultOpt; + case cellsWidget: + return { + ...defaultOpt, + cellCount: 5, + defaultValue: "", + validation: { type: "", pattern: "" }, + isReadOnly: false + }; + case "initials": + return defaultOpt; + case "name": + return { + ...defaultOpt, + defaultValue: getWidgetValue(type), + validation: { type: "text", pattern: "" } + }; + case "company": + return { + ...defaultOpt, + defaultValue: getWidgetValue(type), + validation: { type: "text", pattern: "" } + }; + case "job title": + return { + ...defaultOpt, + defaultValue: getWidgetValue(type), + validation: { type: "text", pattern: "" } + }; + case "date": { + const dateFormat = owner?.DateFormat + ? selectFormat(owner?.DateFormat) + : "MM/dd/yyyy"; + const options = addPreferenceOpt(owner, "date", "", isSignyourself); + return { + ...defaultOpt, + response: options?.response || "", + ...(!isSignyourself + ? { isReadOnly: options?.isReadOnly || false } + : {}), + validation: { + format: options?.format || dateFormat, + type: "date-format" + } + }; + } + case "image": + return defaultOpt; + case "email": + return { + ...defaultOpt, + defaultValue: getWidgetValue(type), + validation: { type: "email", pattern: "" } + }; + default: + return {}; + } +}; diff --git a/apps/OpenSign/src/constant/utils/widgetPrimitives.js b/apps/OpenSign/src/constant/utils/widgetPrimitives.js new file mode 100644 index 0000000000..6a09e78c6d --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetPrimitives.js @@ -0,0 +1,114 @@ +// Dependency-free widget primitives shared by the sizing module +// (widgetSizing) and the inline-editing module (widgetInlineEditing). +// This module only reads the leaf widget-type constants from coreConstants, +// which itself imports no sibling util module, so the historic +// sizing <-> inline-editing import cycle cannot reform through here. +import { + textInputWidget, + drawWidget, + textWidget, + radioButtonWidget, + cellsWidget +} from "./coreConstants.js"; + +// Fixed dimensions keyed by literal widget type. +const FIXED_DIMS = { + signature: { width: 150, height: 60 }, + stamp: { width: 150, height: 60 }, + checkbox: { width: 15, height: 19 }, + dropdown: { width: 120, height: 22 }, + initials: { width: 50, height: 50 }, + name: { width: 150, height: 19 }, + company: { width: 150, height: 19 }, + "job title": { width: 150, height: 19 }, + date: { width: 100, height: 20 }, + image: { width: 70, height: 70 }, + email: { width: 150, height: 19 } +}; + +// Single-line text widgets share the 150x19 box. +const isCompactTextWidget = (type) => + [textInputWidget, textWidget, "name", "company", "job title", "email"].includes( + type + ); + +export const defaultWidthHeight = (type) => { + if (type === cellsWidget) return { width: 112, height: 22 }; + if (type === radioButtonWidget) return { width: 5, height: 10 }; + if (type === drawWidget) return { width: 150, height: 60 }; + if (isCompactTextWidget(type)) return { width: 150, height: 19 }; + return FIXED_DIMS[type] ?? { width: 150, height: 60 }; +}; + +// Measure the font size that lets `text` fill the widget box. +const measureFittedFontSize = ( + measureCtx, + text, + fontFamily, + baselineFontSizePx, + maxWidth, + maxHeight +) => { + measureCtx.font = `${baselineFontSizePx}px ${fontFamily}`; + const metrics = measureCtx.measureText(text); + const actualHeight = + metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; + const scale = Math.min( + maxWidth / metrics.width, + maxHeight / actualHeight, + 1 + ); + return baselineFontSizePx * scale; +}; + +// Paint centered text on a scaled canvas and return the PNG data URL. +const renderCenteredTextImage = ( + text, + fontFamily, + fillColor, + finalFontSizePx, + maxWidth, + maxHeight +) => { + const pxRatio = window.devicePixelRatio * 2 || 3; + const canvas = document.createElement("canvas"); + canvas.width = Math.ceil(maxWidth * pxRatio); + canvas.height = Math.ceil(maxHeight * pxRatio); + const ctx = canvas.getContext("2d"); + ctx.scale(pxRatio, pxRatio); + ctx.font = `${finalFontSizePx}px ${fontFamily}`; + ctx.fillStyle = fillColor; + ctx.textAlign = "center"; + ctx.textBaseline = "alphabetic"; + const metrics = ctx.measureText(text); + const y = + maxHeight / 2 + + (metrics.actualBoundingBoxAscent - metrics.actualBoundingBoxDescent) / 2; + ctx.clearRect(0, 0, maxWidth, maxHeight); + ctx.fillText(text, maxWidth / 2, y); + return canvas.toDataURL("image/png"); +}; + +export function convertTextToImg(fontStyle, text, color, widgetDims) { + const maxWidth = widgetDims.Width; + const maxHeight = widgetDims.Height; + const baselineFontSizePx = maxHeight; + const fontFamily = fontStyle || "Fasthand"; + const measureCanvas = document.createElement("canvas"); + const finalFontSizePx = measureFittedFontSize( + measureCanvas.getContext("2d"), + text, + fontFamily, + baselineFontSizePx, + maxWidth, + maxHeight + ); + return renderCenteredTextImage( + text, + fontFamily, + color || "blue", + finalFontSizePx, + maxWidth, + maxHeight + ); +} diff --git a/apps/OpenSign/src/constant/utils/widgetResponses.js b/apps/OpenSign/src/constant/utils/widgetResponses.js new file mode 100644 index 0000000000..5e9e131e3b --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetResponses.js @@ -0,0 +1,251 @@ +import { rgb } from "pdf-lib"; +import { PDFName } from "pdf-lib"; +import { format } from "date-fns-tz"; +import { toZonedTime } from "date-fns-tz"; +import { renderMailBrandLogo } from "../mailBrand"; +import { resolveMailBrandPresentation } from "../mailBrand"; +import { applyDuplicateResponsesToPages } from "./coreConstants.js"; +import { color } from "./coreConstants.js"; +import { selectFormat } from "./widgetCatalog.js"; +import { widgetDataValue } from "./widgetInlineEditing.js"; +import { formatTimeInTimezone } from "./pdfPageEdit.js"; +import { appName } from "./coreConstants.js"; + +export function _drawOptionList(page, field, rect, font) { + let selected = []; + try { + selected = field.getSelected?.() || []; + } catch { + selected = []; + } + + if (!Array.isArray(selected)) { + selected = [selected].filter(Boolean); + } + + if (!selected.length) return; + + const lines = selected.map((v) => String(v)); + const fontSize = Math.max( + 8, + Math.min(11, rect.height / Math.max(lines.length + 0.5, 2)) + ); + const lineHeight = fontSize + 1.5; + + let y = rect.y + rect.height - fontSize - 2; + + for (const line of lines) { + if (y < rect.y + 1) break; + + page.drawText(line, { + x: rect.x + 2, + y, + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 4) + }); + + y -= lineHeight; + } +} + +export function _removeWidgetAnnotations(pdfDoc) { + for (const page of pdfDoc.getPages()) { + try { + const annotationsRef = page.node.get(PDFName.of("Annots")); + if (!annotationsRef) continue; + + const annotations = pdfDoc.context.lookup(annotationsRef); + if (!annotations || !annotations.asArray) continue; + + const filtered = annotations.asArray().filter((annotRef) => { + try { + const annot = pdfDoc.context.lookup(annotRef); + const subtype = annot?.get(PDFName.of("Subtype")); + return subtype?.toString() !== "/Widget"; + } catch { + return true; + } + }); + + if (filtered.length === 0) { + page.node.delete(PDFName.of("Annots")); + } else { + page.node.set(PDFName.of("Annots"), pdfDoc.context.obj(filtered)); + } + } catch { + /* best effort */ + } + } + + try { + pdfDoc.catalog.delete(PDFName.of("AcroForm")); + } catch { + /* best effort */ + } +} + +export const mailTemplate = (param) => { + const { appName, logoUrl, accentColor } = resolveMailBrandPresentation(""); + const logo = renderMailBrandLogo({ appName, logoUrl }); + + const subject = `${param.senderName} has requested you to sign "${param.title}"`; + const body = + "<html><head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8' /></head><body><div style='background-color:#f5f5f5;padding:20px'><div style='background:white;padding-bottom:20px'>" + + logo + + `<div style='padding:2px;font-family:system-ui;background-color:${accentColor}'><p style='font-size:20px;font-weight:400;color:white;padding-left:20px'>Digital Signature Request</p></div><div><p style='padding:20px;font-size:14px;margin-bottom:10px'>` + + param.senderName + + " has requested you to review and sign <strong>" + + param.title + + "</strong>.</p><div style='padding: 5px 0px 5px 25px;display:flex;flex-direction:row;justify-content:space-around'><table><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td><td></td><td style='color:#626363;font-weight:bold'>" + + param.senderMail + + "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td><td></td><td style='color:#626363;font-weight:bold'> " + + param.organization + + "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td></td><td style='color:#626363;font-weight:bold'>" + + param.localExpireDate + + "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Note</td><td></td><td style='color:#626363;font-weight:bold'>" + + param.note + + "</td></tr><tr><td></td><td></td></tr></table></div> <div style='margin-left:70px'><a target=_blank href=" + + param.signingUrl + + "><button style='padding:12px;background-color:#d46b0f;color:white;border:0px;font-weight:bold;margin-top:30px'>Sign here</button></a></div><div style='display:flex;justify-content:center;margin-top:10px'></div></div></div><div><p> This is an automated email from " + + appName + + ". For any queries regarding this email, please contact the sender " + + param.senderMail + + " directly.</p></div></div></body></html> "; + return { subject, body }; +}; + +export function formatDateTime(date, dateFormat, timeZone, is12Hour) { + const zonedDate = toZonedTime(date, timeZone); // Convert date to the given timezone + const timeFormat = is12Hour ? "hh:mm:ss a" : "HH:mm:ss"; + return dateFormat + ? format( + zonedDate, + `${selectFormat(dateFormat)}, ${timeFormat} 'GMT' XXX`, + { timeZone } + ) + : formatTimeInTimezone(date, timeZone); +} + +export const updateDateWidgetsRes = ( + documentData, + signerId, + journey, + isRemovePrefill +) => { + const contactUser = documentData?.Signers?.find( + (data) => data.objectId === signerId + ); + const extUser = + localStorage.getItem("Extand_Class") || JSON.stringify([contactUser]); + let placeHolders = documentData?.Placeholders; + if (isRemovePrefill) { + placeHolders = placeHolders?.filter((x) => x.Role !== "prefill"); + } + const userDetails = extUser ? JSON.parse(extUser)[0] : contactUser; + return placeHolders?.map((item) => { + if (item?.signerObjId === signerId || item?.Id === signerId) { + // Sort page number placeholders + const placeHolder = Array.isArray(item.placeHolder) + ? [...item.placeHolder] + : []; + const sortedPlaceHolder = placeHolder + .sort((a, b) => a.pageNumber - b.pageNumber) + .map((ph) => { + const sortedWidgets = [...ph.pos] + .sort((a, b) => { + // Sort widgets by Y position (top to bottom) and X position (left to right) + // Treat widgets within 5px Y difference as belonging to the same row + const Y_TOLERANCE = 5; + const yDiff = a.yPosition - b.yPosition; + + if (Math.abs(yDiff) <= Y_TOLERANCE) { + return a.xPosition - b.xPosition; // Same row → sort by X + } + + return yDiff; // Different rows → sort by Y + }) + .map((widget) => { + // Update widget values if needed + if ( + ["name", "email", "job title", "company"].includes( + widget.type + ) && + !widget.options.defaultValue && + !widget.options.response && + userDetails + ) { + return { + ...widget, + options: { + ...widget.options, + response: widgetDataValue(widget.type, userDetails) + } + }; + } + return widget; + }); + let widgetsWithResponses = sortedWidgets; + return { ...ph, pos: widgetsWithResponses }; + }); + return { + ...item, + placeHolder: applyDuplicateResponsesToPages(sortedPlaceHolder) + }; + } + + return item; + }); +}; + +export const selectCheckbox = (ind, selectedCheckbox) => { + if (selectedCheckbox && selectedCheckbox?.length > 0) { + const isCheck = selectedCheckbox?.some((data) => data === ind); + return isCheck || false; + } +}; + +export const checkRegularExpress = (validateType, setValidatePlaceholder) => { + switch (validateType) { + case "email": + setValidatePlaceholder("demo@gmail.com"); + break; + case "number": + setValidatePlaceholder("12345"); + break; + case "text": + setValidatePlaceholder("please enter text"); + break; + case "ssn": + setValidatePlaceholder("123-45-6789"); + break; + default: + setValidatePlaceholder("please enter value"); + } +}; + +export const handleUnlinkSigner = ( + signerPos, + setSignerPos, + signersdata, + setSignersData, + uniqueId +) => { + //remove existing signer's details from 'signerPos' array + const updatePlaceHolder = signerPos.map((x) => { + if (x.Id === uniqueId) { + return { ...x, signerPtr: {}, signerObjId: "" }; + } + return { ...x }; + }); + setSignerPos(updatePlaceHolder); + //remove existing signer's details from 'signersdata' array and keep role and id + const updateSigner = signersdata.map((item) => { + if (item.Id == uniqueId) { + return { Role: item.Role, Id: item.Id, blockColor: item.blockColor }; + } + return item; + }); + setSignersData(updateSigner); +}; diff --git a/apps/OpenSign/src/constant/utils/widgetSizing.js b/apps/OpenSign/src/constant/utils/widgetSizing.js new file mode 100644 index 0000000000..109a0f8520 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetSizing.js @@ -0,0 +1,134 @@ +import { convertTextToImg } from "./widgetPrimitives.js"; +import { defaultWidthHeight } from "./widgetPrimitives.js"; + +// Re-exported so the facade (constant/Utils.js) keeps its source module. +export { defaultWidthHeight }; + +export const arrayBufferToBase64 = (buffer) => { + const bytes = new Uint8Array(buffer); + const chunk = 0x8000; + let binary = ""; + for (let i = 0; i < bytes.length; i += chunk) { + binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk)); + } + return btoa(binary); +}; + +export async function getBase64FromIMG(url) { + const data = await fetch(url); + const blob = await data.blob(); + return new Promise((resolve) => { + const reader = new FileReader(); + reader.readAsDataURL(blob); + reader.onloadend = function () { + const pdfBase = this.result; + resolve(pdfBase); + }; + }); +} + +// Paint the image over a white background (JPEG has no alpha channel). +const paintWhiteBackgroundCanvas = (img) => { + const canvas = document.createElement("canvas"); + canvas.width = img.width; + canvas.height = img.height; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#ffffff"; // white color + ctx.fillRect(0, 0, canvas.width, canvas.height); + ctx.drawImage(img, 0, 0); + return canvas; +}; + +export const convertPNGtoJPEG = (base64Data) => { + return new Promise((resolve, reject) => { + const img = new Image(); + img.src = base64Data; + + img.onload = () => { + // Convert to JPEG by using the canvas.toDataURL() method + const jpegBase64Data = paintWhiteBackgroundCanvas(img).toDataURL( + "image/jpeg" + ); + resolve(jpegBase64Data); + }; + + img.onerror = (error) => { + reject(error); + }; + }); +}; + +// For rotated widgets (90°/270°) the visual dimensions are swapped, so the +// data model keeps the original-orientation dimensions. +const resolveStoredDimensions = (ref, containerScale, rotation) => { + const factor = containerScale || 1; + const widgetWidth = ref.offsetWidth / factor; + const widgetHeight = ref.offsetHeight / factor; + const isSwapped = [90, 270].includes(rotation || 0); + const storedWidth = isSwapped ? widgetHeight : widgetWidth; + const storedHeight = isSwapped ? widgetWidth : widgetHeight; + return { storedWidth, storedHeight }; +}; + +// Regenerate the image when a "type" signature is resized. +const refreshTypeSignatureImage = (url, widgetDims) => { + if (!(url.typeSignature && url.signatureType === "type")) return null; + const signImg = convertTextToImg( + url.typeFont ?? "Fasthand", + url.typeSignature, + url.fontColor ?? "blue", + widgetDims + ); + return { + SignUrl: signImg, + options: { ...url.options, response: signImg } + }; +}; + +// Resize a single widget position entry, leaving other keys untouched. +const resizePositionEntry = (url, key, stored) => { + if (url.key !== key) return url; + const base = { + ...url, + Width: stored.storedWidth, + Height: stored.storedHeight, + IsResize: true + }; + const refreshed = refreshTypeSignatureImage(url, { + Width: stored.storedWidth, + Height: stored.storedHeight + }); + return refreshed ? { ...base, ...refreshed } : base; +}; + +export const handleSignYourselfWidgetResize = ( + ref, + key, + xyPosition, + setXyPosition, + index, + containerScale +) => { + // Guard against bad index + if (!xyPosition[index]) { + console.log(`ImageResize invalid index ${index}`); + return; + } + + // Single pass to update only the targeted index/key + const updated = xyPosition.map((item, idx) => { + if (idx !== index) return item; + return { + ...item, + pos: item.pos.map((url) => { + const stored = resolveStoredDimensions( + ref, + containerScale, + url.options?.rotation + ); + return resizePositionEntry(url, key, stored); + }) + }; + }); + setXyPosition(updated); +}; diff --git a/apps/OpenSign/src/constant/utils/widgetState.js b/apps/OpenSign/src/constant/utils/widgetState.js new file mode 100644 index 0000000000..a477ee9e24 --- /dev/null +++ b/apps/OpenSign/src/constant/utils/widgetState.js @@ -0,0 +1,100 @@ +import { color } from "./coreConstants.js"; +import { widgets } from "./widgetCatalog.js"; + +export const darkenColor = (color, factor) => { + // Remove '#' from the color code and parse it to get RGB values + const hex = color.replace("#", ""); + const r = parseInt(hex.substring(0, 2), 16); + const g = parseInt(hex.substring(2, 4), 16); + const b = parseInt(hex.substring(4, 6), 16); + + // Darken the color by reducing each RGB component + const darkerR = Math.floor(r * (1 - factor)); + const darkerG = Math.floor(g * (1 - factor)); + const darkerB = Math.floor(b * (1 - factor)); + + // Convert the darkened RGB components back to hex + return `#${((darkerR << 16) | (darkerG << 8) | darkerB) + .toString(16) + .padStart(6, "0")}`; +}; + +export const addZIndex = (signerPos, key, setZIndex) => { + return signerPos.map((item) => { + if (item.placeHolder && item.placeHolder.length > 0) { + // If there is a nested array, recursively add the field to the last object + return { + ...item, + placeHolder: addZIndex(item.placeHolder, key, setZIndex) + }; + } else if (item.pos && item.pos.length > 0) { + // If there is no nested array, add the new field + return { + ...item, + pos: addZIndex(item.pos, key, setZIndex) + // Adjust this line to add the desired field + }; + } else { + if (item.key === key) { + setZIndex(item.zIndex); + return { + ...item, + zIndex: item.zIndex ? item.zIndex + 1 : 1 + }; + } else { + return { ...item }; + } + } + }); +}; + +export const reuseUnchangedWidgets = (previous, updated) => + updated.map((page, pageIndex) => { + const oldPage = previous[pageIndex]; + if (!oldPage?.pos || !page?.pos || oldPage.pos.length !== page.pos.length) + return page; + const pos = page.pos.map((widget, index) => { + const old = oldPage.pos[index]; + if (!old || old.key !== widget.key) return widget; + const same = (a, b) => { + const keys = Object.keys(a || {}); + return ( + keys.length === Object.keys(b || {}).length && + keys.every((key) => Object.is(a[key], b[key])) + ); + }; + const { options: oldOptions, ...oldFields } = old; + const { options, ...fields } = widget; + return same(oldFields, fields) && same(oldOptions, options) + ? old + : widget; + }); + return { ...page, pos }; + }); + +export const nextPendingWidget = (pages, currentKey) => { + const widgets = (pages || []).flatMap((page) => + (page.pos || []).map((widget) => ({ widget, pageNumber: page.pageNumber })) + ); + const current = widgets.findIndex(({ widget }) => widget.key === currentKey); + const hasValue = (value) => + Array.isArray(value) + ? value.length > 0 + : typeof value === "string" + ? value.trim().length > 0 + : value != null; + for (let offset = 1; offset <= widgets.length; offset++) { + const candidate = widgets[(current + offset) % widgets.length]; + const widget = candidate.widget; + if ( + widget.key === currentKey || + widget.options?.isReadOnly || + widget.SignUrl || + hasValue(widget.options?.response) || + hasValue(widget.options?.defaultValue) + ) + continue; + return candidate; + } + return null; +}; diff --git a/apps/OpenSign/src/hook/useWindowSize.js b/apps/OpenSign/src/hook/useWindowSize.js index 0c84d6f131..d2a15cfe99 100644 --- a/apps/OpenSign/src/hook/useWindowSize.js +++ b/apps/OpenSign/src/hook/useWindowSize.js @@ -1,9 +1,11 @@ import { useEffect, useState } from "react"; export function useWindowSize() { - const [size, setSize] = useState({ - width: 0, - height: 0 + const [size, setSize] = useState(() => { + if (typeof window !== "undefined") { + return { width: window.innerWidth, height: window.innerHeight }; + } + return { width: 0, height: 0 }; }); const onResize = () => { diff --git a/apps/OpenSign/src/i18n.js b/apps/OpenSign/src/i18n.js index ac649f7064..88b2d59297 100644 --- a/apps/OpenSign/src/i18n.js +++ b/apps/OpenSign/src/i18n.js @@ -25,7 +25,13 @@ i18n interpolation: { escapeValue: false // Not needed for react as it escapes by default }, - whitelist: ["en", "es", "fr", "it", "de", "hi", "kr"] // List of allowed languages + // i18next v22+ renamed `whitelist` to `supportedLngs`; the old key was + // silently ignored, so `en-US` reached the backend and 404'd. + supportedLngs: ["en", "es", "fr", "it", "de", "hi", "kr", "zh", "ja"], + // Resolve regional locales to their base language: en-US -> en, es-PE -> es. + nonExplicitSupportedLngs: true, + // Never request a regional file; only en/es/fr/... exist on disk. + load: "languageOnly" }); export default i18n; diff --git a/apps/OpenSign/src/index.jsx b/apps/OpenSign/src/index.jsx index 78bcc22a85..a1e9875e10 100644 --- a/apps/OpenSign/src/index.jsx +++ b/apps/OpenSign/src/index.jsx @@ -2,7 +2,10 @@ import ReactDOM from "react-dom/client"; import "./index.css"; import "./styles/dark-theme-improvements.css"; import App from "./App"; -import { showUpgradeProgress, hideUpgradeProgress } from "./utils"; +import { + showUpgradeProgress, + hideUpgradeProgress +} from "./utils/upgradeProgress"; import { Provider } from "react-redux"; import { store } from "./redux/store"; import Parse from "parse"; diff --git a/apps/OpenSign/src/layout/HomeLayout.jsx b/apps/OpenSign/src/layout/HomeLayout.jsx index 2b14aebe3c..e1b619fea1 100644 --- a/apps/OpenSign/src/layout/HomeLayout.jsx +++ b/apps/OpenSign/src/layout/HomeLayout.jsx @@ -2,7 +2,7 @@ import { useState, useEffect } from "react"; import { runtimeUrls } from "../constant/const"; import { nonPresentMaskCss -} from "../constant/Utils"; +} from "../constant/utils/coreConstants.js"; import Header from "../components/Header"; import Footer from "../components/Footer"; import Sidebar from "../components/sidebar/Sidebar"; @@ -263,7 +263,7 @@ const HomeLayout = () => { </div> </PageScrollContainer> </div> - {isTour && ( + {isTour && tourConfigs.length > 0 && ( <Tour onRequestClose={closeTour} steps={tourConfigs} diff --git a/apps/OpenSign/src/pages/DocSuccessPage.jsx b/apps/OpenSign/src/pages/DocSuccessPage.jsx index a181859ec7..85c9e7feff 100644 --- a/apps/OpenSign/src/pages/DocSuccessPage.jsx +++ b/apps/OpenSign/src/pages/DocSuccessPage.jsx @@ -1,12 +1,12 @@ import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import Confetti from "react-confetti"; // Import the confetti library +import { getBase64FromUrl } from "../constant/utils/coreConstants.js"; +import { handleDownloadPdf } from "../constant/utils/tenantDownloads.js"; import { - getBase64FromUrl, handleDownloadCertificate, - handleDownloadPdf, - handleToPrint, -} from "../constant/Utils"; + handleToPrint +} from "../constant/utils/printCertificates.js"; import ModalUi from "../primitives/ModalUi"; import Loader from "../primitives/Loader"; import DownloadPdfZip from "../primitives/DownloadPdfZip"; diff --git a/apps/OpenSign/src/pages/Form.jsx b/apps/OpenSign/src/pages/Form.jsx index 67176884f5..534dc1776a 100644 --- a/apps/OpenSign/src/pages/Form.jsx +++ b/apps/OpenSign/src/pages/Form.jsx @@ -7,6 +7,7 @@ import SelectFolder from "../components/shared/fields/SelectFolder"; import SignersInput from "../components/shared/fields/SignersInput"; import PageNotFound from "./PageNotFound"; import { SaveFileSize } from "../constant/saveFileSize"; +import { DEFAULT_COMPLETION_DAYS } from "../constant/runtimeConfig"; import { generatePdfName, generateTitleFromFilename, @@ -18,6 +19,7 @@ import { removeTrailingSegment } from "../constant/Utils"; import { normalizeParseObjectResult } from "../utils/parseResult"; +import { mergePdfBuffers } from "../utils/pdfDocumentUtils"; import { isCreditQuotaError } from "../utils/creditErrors"; import { PDFDocument } from "pdf-lib"; import axios from "axios"; @@ -65,7 +67,7 @@ const Forms = (props) => { Name: "", Description: "", Note: "", - TimeToCompleteDays: 15, + TimeToCompleteDays: DEFAULT_COMPLETION_DAYS, SendinOrder: "false", SendInOrderStrict: "false", password: "", @@ -271,7 +273,6 @@ const Forms = (props) => { setpercentage(0); const config = { headers: { - "content-type": "multipart/form-data", sessiontoken: Parse.User.current().getSessionToken() }, signal: abortController.signal, @@ -305,6 +306,55 @@ const Forms = (props) => { } return; } + } else if ( + file.type === "application/vnd.ms-excel" || + file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || + file.name.toLowerCase().endsWith(".xls") || + file.name.toLowerCase().endsWith(".xlsx") + ) { + try { + const baseApi = localStorage.getItem("baseUrl") || ""; + const url = removeTrailingSegment(baseApi) + "/exceltopdf"; + let fd = new FormData(); + fd.append("file", file); + setfileload(true); + setpercentage(0); + const config = { + headers: { + "content-type": "multipart/form-data", + sessiontoken: Parse.User.current().getSessionToken() + }, + signal: abortController.signal, + onUploadProgress: (progressEvent) => { + if (progressEvent.total) { + const percentCompleted = Math.round( + (progressEvent.loaded * 100) / progressEvent.total + ); + setpercentage(percentCompleted); + } + } + }; + const res = await axios.post(url, fd, config); + if (res.data?.url) { + const pdfRes = await axios.get(res.data.url, { + responseType: "arraybuffer" + }); + pdfBuffers.push(pdfRes.data); + } + setfileload(false); + } catch (err) { + setfileload(false); + removeFile(e); + console.log("err in excel to pdf ", err); + const error = + t("excel-error"); + if (err?.code === 209) { + dispatch(sessionStatus(false)); + } else { + alert(error); + } + return; + } } } @@ -315,12 +365,7 @@ const Forms = (props) => { } setfileload(true); - const merged = await PDFDocument.create(); - for (const bytes of pdfBuffers) { - const doc = await PDFDocument.load(bytes, { ignoreEncryption: true }); - const pages = await merged.copyPages(doc, doc.getPageIndices()); - pages.forEach((p) => merged.addPage(p)); - } + const merged = await mergePdfBuffers(pdfBuffers); const pdfBytes = await merged.save({ useObjectStreams: false }); const name = generatePdfName(16); @@ -524,7 +569,7 @@ const Forms = (props) => { props.title === "Sign Yourself" ? "Note to myself" : "Please review and sign this document", - TimeToCompleteDays: 15, + TimeToCompleteDays: DEFAULT_COMPLETION_DAYS, SendinOrder: sendinorder, password: "", file: "", @@ -623,7 +668,7 @@ const Forms = (props) => { props.title === "Sign Yourself" ? "Note to myself" : "Please review and sign this document", - TimeToCompleteDays: 15, + TimeToCompleteDays: DEFAULT_COMPLETION_DAYS, SendinOrder: sendinorder, password: "", file: "", @@ -841,7 +886,7 @@ const Forms = (props) => { )} <div className="text-xs"> <label className="block"> - {`${`${t("report-heading.File")} (${t("file-type")}`}${", docx)"}`} + {`${`${t("report-heading.File")} (${t("file-type")}`}${", docx, xlsx, xls)"}`} <span className="text-red-500 text-[13px]">*</span> </label> {fileupload.length > 0 ? ( @@ -869,7 +914,7 @@ const Forms = (props) => { className="op-file-input op-file-input-bordered op-file-input-sm focus:outline-none hover:border-base-content w-full text-xs" onChange={(e) => handleFileInput(e)} ref={inputFileRef} - accept="application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg" + accept="application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/png,image/jpeg" onInvalid={(e) => e.target.setCustomValidity(t("input-required")) } diff --git a/apps/OpenSign/src/pages/GuestLogin.jsx b/apps/OpenSign/src/pages/GuestLogin.jsx index ed70e3180b..94c5b2311f 100644 --- a/apps/OpenSign/src/pages/GuestLogin.jsx +++ b/apps/OpenSign/src/pages/GuestLogin.jsx @@ -7,7 +7,7 @@ import { import { contractUsers, saveLanguageInLocal -} from "../constant/Utils"; +} from "../constant/utils/coreConstants.js"; import logo from "../assets/images/logo.png"; import { appInfo } from "../constant/appinfo"; import Parse from "parse"; diff --git a/apps/OpenSign/src/pages/Login.jsx b/apps/OpenSign/src/pages/Login.jsx index 852096b975..d96c488065 100644 --- a/apps/OpenSign/src/pages/Login.jsx +++ b/apps/OpenSign/src/pages/Login.jsx @@ -9,13 +9,14 @@ import { } from "../constant/const"; import Alert from "../primitives/Alert"; import { appInfo } from "../constant/appinfo"; +import { applySavedTheme } from "../utils/theme"; import { fetchAppInfo } from "../redux/reducers/infoReducer"; import { showTenant } from "../redux/reducers/ShowTenant"; +import { getAppLogo } from "../constant/utils/tenantDownloads.js"; import { - getAppLogo, saveLanguageInLocal, usertimezone -} from "../constant/Utils"; +} from "../constant/utils/coreConstants.js"; import Loader from "../primitives/Loader"; import { useTranslation } from "react-i18next"; import SelectLanguage from "../components/pdf/SelectLanguage"; @@ -65,8 +66,13 @@ function Login() { }; const showToast = (type, msg) => { - setState({ ...state, loading: false, alertType: type, alertMsg: msg }); - setTimeout(() => setState({ ...state, alertMsg: "" }), 2000); + setState((prev) => ({ + ...prev, + loading: false, + alertType: type, + alertMsg: msg + })); + setTimeout(() => setState((prev) => ({ ...prev, alertMsg: "" })), 2000); }; const checkUserExt = async () => { @@ -134,7 +140,11 @@ function Login() { }; const handleLoginBtn = async (event) => { event.preventDefault(); - if (!emailRegex.test(state.email)) { + if (!state.email || !state.email.trim()) { + alert(t("input-required")); + return; + } + if (state.email.includes("@") && !emailRegex.test(state.email)) { alert(t("valid-email-alert")); return; } @@ -142,7 +152,7 @@ function Login() { }; const setThirdpartyLoader = (value) => { - setState({ ...state, thirdpartyLoader: value }); + setState((prev) => ({ ...prev, thirdpartyLoader: value })); }; const thirdpartyLoginfn = async (sessionToken) => { @@ -176,6 +186,7 @@ function Login() { location?.state?.from || `/${menu.pageType}/${menu.pageId}`; const _role = _currentRole.replace("contracts_", ""); const extInfo = JSON.parse(JSON.stringify(extUser)); + applySavedTheme(extUser?.get("Theme")); localStorage.setItem("_user_role", _role); localStorage.setItem("Extand_Class", JSON.stringify([extUser])); localStorage.setItem("userEmail", extInfo?.Email); @@ -206,10 +217,10 @@ function Login() { logOutUser(); } } catch (error) { - console.error("err in fetching extUser", err); - showToast("danger", `${err.message}`); - const payload = { sessionToken: _user.sessionToken }; - handleSubmitbtn(payload); + console.error("err in fetching extUser", error); + showToast("danger", `${error?.message || t("something-went-wrong-mssg")}`); + const payload = { sessionToken: _user?.sessionToken }; + if (payload.sessionToken) handleSubmitbtn(payload); } finally { setThirdpartyLoader(false); } @@ -234,6 +245,7 @@ function Login() { if (menu) { const extInfo = JSON.parse(JSON.stringify(extUser)); const _role = _currentRole.replace("contracts_", ""); + applySavedTheme(extUser?.get("Theme")); localStorage.setItem("_user_role", _role); const redirectUrl = location?.state?.from || `/${menu.pageType}/${menu.pageId}`; @@ -277,7 +289,8 @@ function Login() { const handleSubmitbtn = async (e) => { - e.preventDefault(); + // Also called from the recovery path, which has no DOM event. + e?.preventDefault?.(); if (userDetails.Destination && userDetails.Company) { setThirdpartyLoader(true); const payload = { sessionToken: localStorage.getItem("accesstoken") }; @@ -303,18 +316,15 @@ function Login() { email: userInformation.email, phone: userInformation?.phone || "", company: userDetails.Company, - jobTitle: userDetails.JobTitle + jobTitle: userDetails.Destination }; localStorage.setItem("userDetails", JSON.stringify(LocalUserDetails)); thirdpartyLoginfn(userSignUp.sessionToken); } else { - alert(userSignUp.message); + alert(userSignUp?.message || t("something-went-wrong-mssg")); } - } else if ( - payload && - payload.message.replace(/ /g, "_") === "Internal_server_err" - ) { - alert(t("server-error")); + } else { + alert(t("something-went-wrong-mssg")); } } else { showToast("warning", t("fill-required-details!")); @@ -368,6 +378,7 @@ function Login() { if (checkLanguage) { checkLanguage && i18n.changeLanguage(checkLanguage); } + applySavedTheme(extUser?.get("Theme")); const extInfo = JSON.parse(JSON.stringify(extUser)); // Continue with storing user data and redirecting localStorage.setItem("Extand_Class", JSON.stringify([extUser])); @@ -509,7 +520,7 @@ function Login() { </label> <input id="email" - type="email" + type="text" className="op-input op-input-bordered op-input-sm hover:border-base-content w-full text-xs" name="email" autoComplete="username" diff --git a/apps/OpenSign/src/pages/PdfRequestFiles.jsx b/apps/OpenSign/src/pages/PdfRequestFiles.jsx index 4675b2c94b..ea60eecd8d 100644 --- a/apps/OpenSign/src/pages/PdfRequestFiles.jsx +++ b/apps/OpenSign/src/pages/PdfRequestFiles.jsx @@ -66,6 +66,7 @@ import Loader from "../primitives/Loader"; import { isCreditQuotaError } from "../utils/creditErrors"; import PdfDeclineModal from "../primitives/PdfDeclineModal"; import { serverUrl_fn } from "../constant/appinfo"; +import { DEFAULT_COMPLETION_DAYS } from "../constant/runtimeConfig"; import AgreementSign from "../components/pdf/AgreementSign"; import WidgetComponent from "../components/pdf/WidgetComponent"; import PlaceholderCopy from "../components/pdf/PlaceholderCopy"; @@ -177,16 +178,25 @@ function PdfRequestFiles( sendmail = getQuery?.[1]?.split("=")[1]; //false } - const routeId = route && route?.split("/"); // ['', 'load', 'recipientSignPdf', ':docId', ':contactBookId'] - if (routeId && routeId.length > 4) { - // this condition will be occur only in guest flow in which load routeId will be include - isGuestSignFlow = true; - getDocId = routeId[3]; - contactBookId = routeId[4]; + // The app can be deployed under a sub-path, so the base has to be removed + // before the route is parsed and the segments are located by name. + const deploymentBase = (import.meta.env.BASE_URL || "/").replace(/\/$/, ""); + const routePath = + deploymentBase && route.startsWith(deploymentBase) + ? route.slice(deploymentBase.length) + : route; + const routeId = routePath.split("/").filter(Boolean); + const signRouteIndex = routeId.indexOf("recipientSignPdf"); + if (signRouteIndex !== -1) { + // guest flow: /load/recipientSignPdf/:docId/:contactBookId + isGuestSignFlow = + signRouteIndex > 0 && routeId.slice(0, signRouteIndex).includes("load"); + getDocId = routeId[signRouteIndex + 1] || ""; + contactBookId = routeId[signRouteIndex + 2] || ""; } else { - // this condition will be occur only in if user is logged in and load routeId will be exclude - getDocId = routeId[2]; - contactBookId = routeId?.[3] || ""; + // fallback that keeps the previous indexing for unknown shapes + getDocId = routeId[1] || ""; + contactBookId = routeId[2] || ""; } let getDocumentId = getDocId || @@ -657,7 +667,7 @@ function PdfRequestFiles( documentId; const addExtraDays = pdfDetails[0]?.TimeToCompleteDays ? pdfDetails[0].TimeToCompleteDays - : 15; + : DEFAULT_COMPLETION_DAYS; let updateExpiryDate; updateExpiryDate = new Date(); updateExpiryDate.setDate(updateExpiryDate.getDate() + addExtraDays); @@ -736,7 +746,7 @@ function PdfRequestFiles( //condition to embed prefill widgets details in pdf in public signing flow if (prefillDetails && props.templateId) { const prefillwidgets = prefillDetails?.placeHolder; - const pdfDoc = await PDFDocument.load(pdfArrBuffer); + const pdfDoc = await PDFDocument.load(pdfArrBuffer, { ignoreEncryption: true }); const pdfbase64 = await embedWidgetsToDoc( prefillwidgets, pdfDoc, @@ -760,7 +770,7 @@ function PdfRequestFiles( setHandleError("Document not Found!"); } try { - const pdfDoc = await PDFDocument.load(pdfArrBuffer); + const pdfDoc = await PDFDocument.load(pdfArrBuffer, { ignoreEncryption: true }); const extUserPtr = pdfDetails[0].ExtUserPtr; const HeaderDocId = extUserPtr?.HeaderDocId; //embed document's object id to all pages in pdf document @@ -778,7 +788,7 @@ function PdfRequestFiles( scale ); //get ExistUserPtr object id of user class to get tenantDetails - if (!pdfBytes?.error) { + if (pdfBytes && !pdfBytes?.error) { const objectId = pdfDetails?.[0]?.ExtUserPtr?.UserId?.objectId; //function for call to embed signature in pdf and get digital signature pdf const resSign = await signPdfFun( @@ -915,7 +925,8 @@ function PdfRequestFiles( const requestSubject = updatedDoc.updatedPdfDetails?.[0]?.RequestSubject || mailSubject; if (user) { - const addExtraDays = signedDocument?.TimeToCompleteDays || 15; + const addExtraDays = + signedDocument?.TimeToCompleteDays || DEFAULT_COMPLETION_DAYS; let expDate = expiryDate || signedDocument?.ExpiryDate?.iso; if (!expiryDate) { const d = new Date(); @@ -1159,6 +1170,9 @@ function PdfRequestFiles( //function for update TourStatus const closeTour = async () => { setWidgetsTour(false); + // The tour scrolls the document to the unsigned widget; bring the page + // back so the top bar with cancel/finish stays reachable. + window.scrollTo({ top: 0 }); }; const tourConfig = [ @@ -1212,6 +1226,10 @@ function PdfRequestFiles( const currentDecline = { currnt: "YouDeclined", isDeclined: true }; setIsDecline(currentDecline); setIsUiLoading(false); + if (redirectUrl) { + setRedirectTimeLeft(5); + setIsredirectCanceled(false); + } } }) .catch((err) => { diff --git a/apps/OpenSign/src/pages/PlaceHolderSign.jsx b/apps/OpenSign/src/pages/PlaceHolderSign.jsx index dbd346d452..a31378fb20 100644 --- a/apps/OpenSign/src/pages/PlaceHolderSign.jsx +++ b/apps/OpenSign/src/pages/PlaceHolderSign.jsx @@ -52,6 +52,7 @@ import PlaceholderCopy from "../components/pdf/PlaceholderCopy"; import DropdownWidgetOption from "../components/pdf/DropdownWidgetOption"; import WidgetNameModal from "../components/pdf/WidgetNameModal"; import { SaveFileSize } from "../constant/saveFileSize"; +import { DEFAULT_COMPLETION_DAYS } from "../constant/runtimeConfig"; import { useDispatch, useSelector } from "react-redux"; import PdfTools from "../components/pdf/PdfTools"; import { useTranslation, Trans } from "react-i18next"; @@ -134,6 +135,7 @@ function PlaceHolderSign() { const [isAddUser, setIsAddUser] = useState({}); const [signerExistModal, setSignerExistModal] = useState(false); const [isDontShow, setIsDontShow] = useState(true); + const [widgetClipboard, setWidgetClipboard] = useState(null); const [isDragging, setIsDragging] = useState(false); const [showDropdown, setShowDropdown] = useState(false); const [isUiLoading, setIsUiLoading] = useState(false); @@ -179,6 +181,65 @@ function PlaceHolderSign() { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + // Keyboard shortcuts: Ctrl/Cmd+C/X/V for widget copy/cut/paste (#36) + useEffect(() => { + const handler = (e) => { + const mod = e.ctrlKey || e.metaKey; + if (!mod) return; + // Never hijack the native clipboard while the user types in a field. + const target = e.target; + const isEditableTarget = + target?.isContentEditable || + ["INPUT", "TEXTAREA", "SELECT"].includes(target?.tagName); + if (isEditableTarget) return; + const key = e.key.toLowerCase(); + // Copy and cut need a selection; paste only needs the clipboard. + if (key !== "v" && !currWidgetsDetails?.key) return; + if (key === "c") { + setWidgetClipboard({ pos: { ...currWidgetsDetails }, dataId: uniqueId }); + e.preventDefault(); + } else if (key === "x") { + setWidgetClipboard({ pos: { ...currWidgetsDetails }, dataId: uniqueId }); + if (currWidgetsDetails?.key) { + handleDeleteWidget(currWidgetsDetails.key, uniqueId, pageNumber); + } + e.preventDefault(); + } else if (key === "v" && widgetClipboard?.pos) { + const p = widgetClipboard.pos; + const newPos = { + ...p, + key: String(randomId(12)), + xPosition: (p.xPosition || 0) + 10, + yPosition: (p.yPosition || 0) + 10, + }; + // paste into the current signer's placeholder + setSignerPos((prev) => { + const signerId = uniqueId; + const filterSignerPos = prev.filter((d) => d.Id === signerId); + if (filterSignerPos.length > 0) { + const getPlaceHolder = filterSignerPos[0].placeHolder || []; + const pageIdx = getPlaceHolder.findIndex((ph) => ph.pageNumber === pageNumber); + let updatedPlaceHolder; + if (pageIdx >= 0) { + updatedPlaceHolder = getPlaceHolder.map((ph, i) => + i === pageIdx ? { ...ph, pos: [...ph.pos, newPos] } : ph + ); + } else { + updatedPlaceHolder = [...getPlaceHolder, { pageNumber, pos: [newPos] }]; + } + return prev.map((obj) => + obj.Id === signerId ? { ...obj, placeHolder: updatedPlaceHolder } : obj + ); + } + return prev; + }); + e.preventDefault(); + } + }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }, [currWidgetsDetails, uniqueId, pageNumber, widgetClipboard]); + //function to fetch tenant Details const fetchTenantDetails = async () => { @@ -951,6 +1012,35 @@ function PlaceHolderSign() { }; const handleSaveDoc = async () => { + // Gate sending on sender email verification (mirrors SignyourselfPdf/PdfRequestFiles) + try { + const currentUser = JSON.parse( + localStorage.getItem( + `Parse/${localStorage.getItem("parseAppId")}/currentUser` + ) || "{}" + ); + let isEmailVerified = currentUser?.emailVerified; + const isEnableOTP = pdfDetails?.[0]?.IsEnableOTP || false; + if (isEnableOTP && !isEmailVerified) { + try { + const userQuery = new Parse.Query(Parse.User); + const user = await userQuery.get(currentUser?.objectId, { + sessionToken: localStorage.getItem("accesstoken") + }); + if (user) isEmailVerified = user?.get("emailVerified"); + } catch (e) { + console.log("err in get email verification ", e); + } + } + if (!isEnableOTP || isEmailVerified) { + // proceed + } else { + alert(t("email-not-verified-send") || t("something-went-wrong-mssg")); + return; + } + } catch (e) { + console.log("err checking email verification", e); + } let isPrefillEmpty = false, unfilledTextWidgetId; const prefillExist = signerPos?.find((data) => data.Role === "prefill"); @@ -995,9 +1085,19 @@ function PlaceHolderSign() { let canSaveWithoutSignatureWidget = isPlaceholderExist; - //checking if there are any signer list which do not have signture widget then show signers name on tour messages - if (unassignedWidget.length > 0) { - const getSigner = unassignedWidget.map((x, index) => { + if (prefillExist && isPrefillEmpty) { + setIsSendAlert({ mssg: "prefill", alert: true }); + setUnSignedWidgetId(unfilledTextWidgetId); + return; + } + if (signersdata?.length === 0) { + alert(t("atleast-one-recipient-alert")); + return; + } + + // signers who do not have a signature widget are named in the confirmation + const signerName = unassignedWidget + .map((x, index) => { const signer = signersdata.find( (y) => y.Id === x.Id || (x.signerObjId && y.objectId === x.signerObjId) @@ -1011,20 +1111,28 @@ function PlaceHolderSign() { x.Role || x.Id ); - }); - const signerName = getSigner.join(", "); - setSignersName(signerName); - setIsSendAlert({ mssg: "sure", alert: true }); - setUniqueId(unassignedWidget[0]?.Id); - setRoleName(""); + }) + .join(", "); + + // Every send is confirmed, and cancelling prevents the document from being + // marked as sent. + const proceed = window.confirm( + t("sure-send-without-widget", { + names: signerName, + defaultValue: signerName + ? `Some recipients (${signerName}) have no signature widget. Send anyway?` + : "Send this document for signatures?" + }) + ); + if (!proceed) { + if (unassignedWidget[0]) { + setUniqueId(unassignedWidget[0]?.Id); + setRoleName(""); + } + return; } - if (prefillExist && isPrefillEmpty) { - setIsSendAlert({ mssg: "prefill", alert: true }); - setUnSignedWidgetId(unfilledTextWidgetId); - } else if (signersdata?.length === 0) { - alert(t("atleast-one-recipient-alert")); - } else if (canSaveWithoutSignatureWidget && unassignedWidget.length === 0) { + if (canSaveWithoutSignatureWidget) { const IsSignerNotExist = filterPrefill?.filter((x) => !x.signerObjId); // below condition is used to hightlight the widget whose value is not provided by signer if (IsSignerNotExist && IsSignerNotExist?.length > 0) { @@ -1111,7 +1219,7 @@ function PlaceHolderSign() { }); const addExtraDays = pdfDetails?.[0]?.TimeToCompleteDays ? pdfDetails[0].TimeToCompleteDays - : 15; + : DEFAULT_COMPLETION_DAYS; const currentUser = signersdata.find((x) => x.Email === currentId); setCurrentId(currentUser?.objectId); // Compute expiry date with extra days @@ -1874,7 +1982,8 @@ function PlaceHolderSign() { ? updateDocument?.[0]?.NotifyOnSignatures : false, TimeToCompleteDays: - parseInt(updateDocument?.[0]?.TimeToCompleteDays) || 15, + parseInt(updateDocument?.[0]?.TimeToCompleteDays) || + DEFAULT_COMPLETION_DAYS, RemindOnceInEvery: parseInt(updateDocument?.[0]?.RemindOnceInEvery) || 0, ...penColors, diff --git a/apps/OpenSign/src/pages/SignyourselfPdf.jsx b/apps/OpenSign/src/pages/SignyourselfPdf.jsx index 30fe3d3bce..1decd8ccc0 100644 --- a/apps/OpenSign/src/pages/SignyourselfPdf.jsx +++ b/apps/OpenSign/src/pages/SignyourselfPdf.jsx @@ -9,6 +9,7 @@ import EmailComponent from "../components/pdf/EmailComponent"; import WidgetComponent from "../components/pdf/WidgetComponent"; import PdfDeclineModal from "../primitives/PdfDeclineModal"; import { + arrayBufferToBase64, getTenantDetails, contractDocument, embedDocId, @@ -31,7 +32,6 @@ import { onClickZoomIn, onClickZoomOut, rotatePdfPage, - getBase64FromUrl, convertBase64ToFile, generatePdfName, handleRemoveWidgets, @@ -238,7 +238,9 @@ function SignYourSelf() { if (url) { //convert document url in array buffer format to use embed widgets in pdf using pdf-lib const arrayBuffer = await convertPdfArrayBuffer(url); - const base64Pdf = await getBase64FromUrl(url); + // One download is enough: encode the buffer we already have. + const base64Pdf = + arrayBuffer === "Error" ? "" : arrayBufferToBase64(arrayBuffer); if (arrayBuffer === "Error") { setHandleError(t("something-went-wrong-mssg")); } else { @@ -717,7 +719,7 @@ function SignYourSelf() { setIsUiLoading(true); // Load a PDFDocument from the existing PDF bytes try { - const pdfDoc = await PDFDocument.load(pdfArrayBuffer); + const pdfDoc = await PDFDocument.load(pdfArrayBuffer, { ignoreEncryption: true }); const isSignYourSelfFlow = true; const extUserPtr = pdfDetails[0].ExtUserPtr; const HeaderDocId = extUserPtr?.HeaderDocId; @@ -735,7 +737,14 @@ function SignYourSelf() { ); //function for call to embed signature in pdf and get digital signature pdf if (!pdfBytes?.error) { - await signPdfFun(pdfBytes, documentId); + await signPdfFun( + pdfBytes, + documentId, + pdfDetails?.[0]?.ExtUserPtr?.UserId?.objectId, + pdfDetails?.[0]?.ExtUserPtr?.UserId?.objectId, + xyPosition, + "Signed" + ); } else { setIsUiLoading(false); setIsAlert({ @@ -1040,6 +1049,7 @@ function SignYourSelf() { defaultValue, isHideLabel, layout, + isMultiSelect, ) => { const widgetPageNumber = currWidgetsDetails?.pageNumber || pageNumber; const getPageNumer = xyPosition.filter( @@ -1071,6 +1081,7 @@ function SignYourSelf() { ...position.options, name: dropdownName, values: dropdownOptions, + isMultiSelect: isMultiSelect || false, ...widgetLayout, isReadOnly: isReadOnly, isHideLabel: isHideLabel || false, @@ -1318,6 +1329,9 @@ function SignYourSelf() { ]; const closeWidgetTour = () => { setWidgetsTour(false); + // The tour scrolls the document to the unsigned widget; bring the page + // back so the top bar with cancel/finish stays reachable. + window.scrollTo({ top: 0 }); }; return ( diff --git a/apps/OpenSign/src/pages/TemplatePlaceholder.jsx b/apps/OpenSign/src/pages/TemplatePlaceholder.jsx index 06f989cdfa..ad073d4fd1 100644 --- a/apps/OpenSign/src/pages/TemplatePlaceholder.jsx +++ b/apps/OpenSign/src/pages/TemplatePlaceholder.jsx @@ -11,6 +11,7 @@ import Header from "../components/pdf/PdfHeader"; import useWidgetHistory from "../hook/useWidgetHistory"; import WidgetNameModal from "../components/pdf/WidgetNameModal"; import { + arrayBufferToBase64, copytoData, pdfNewWidthFun, contractUsers, @@ -33,7 +34,6 @@ import { signatureTypes, getTenantDetails, handleSignatureType, - getBase64FromUrl, convertPdfArrayBuffer, generatePdfName, textWidget, @@ -71,6 +71,7 @@ import * as utils from "../utils"; import CustomizeMail from "../components/pdf/CustomizeMail"; import { resetWidgetState, setPrefillImg } from "../redux/reducers/widgetSlice"; import ShareButton from "../primitives/ShareButton"; +import { DEFAULT_COMPLETION_DAYS } from "../constant/runtimeConfig"; import { useWindowSize } from "../hook/useWindowSize"; import { useScroll } from "../context/ScrollPdfContext"; @@ -287,7 +288,9 @@ const TemplatePlaceholder = () => { const url = documentData[0] && documentData[0]?.URL; if (url) { const arrayBuffer = await convertPdfArrayBuffer(url); - const base64Pdf = await getBase64FromUrl(url); + // One download is enough: encode the buffer we already have. + const base64Pdf = + arrayBuffer === "Error" ? "" : arrayBufferToBase64(arrayBuffer); if (arrayBuffer === "Error") { setHandleError(t("something-went-wrong-mssg")); } else { @@ -889,7 +892,7 @@ const TemplatePlaceholder = () => { } templateCls.set( "TimeToCompleteDays", - parseInt(pdfDetails?.[0]?.TimeToCompleteDays) || 15 + parseInt(pdfDetails?.[0]?.TimeToCompleteDays) || DEFAULT_COMPLETION_DAYS ); if (pdfDetails[0]?.Bcc?.length) { const Bcc = pdfDetails[0]?.Bcc.map((x) => ({ @@ -1012,7 +1015,8 @@ const TemplatePlaceholder = () => { ? pdfDetails[0]?.NotifyOnSignatures : false, TimeToCompleteDays: - parseInt(pdfDetails?.[0]?.TimeToCompleteDays) || 15, + parseInt(pdfDetails?.[0]?.TimeToCompleteDays) || + DEFAULT_COMPLETION_DAYS, ...Bcc, ...Cc, ...RedirectUrl @@ -1408,7 +1412,8 @@ const TemplatePlaceholder = () => { ? updateTemplate?.[0]?.NotifyOnSignatures : false, TimeToCompleteDays: - parseInt(updateTemplate?.[0]?.TimeToCompleteDays) || 15, + parseInt(updateTemplate?.[0]?.TimeToCompleteDays) || + DEFAULT_COMPLETION_DAYS, RemindOnceInEvery: parseInt(updateTemplate?.[0]?.RemindOnceInEvery) || 0, ...penColors, @@ -1444,6 +1449,7 @@ const TemplatePlaceholder = () => { defaultValue, isHideLabel, layout, + isMultiSelect, ) => { const widgetPageNumber = currWidgetsDetails?.pageNumber || pageNumber; const isPrefill = signerPos.some( @@ -1542,6 +1548,7 @@ const TemplatePlaceholder = () => { name: dropdownName, status: status, values: dropdownOptions, + isMultiSelect: isMultiSelect || false, defaultValue: defaultValue, fontSize: textSize || 12, fontColor: textColor || "black", diff --git a/apps/OpenSign/src/pages/UserList.jsx b/apps/OpenSign/src/pages/UserList.jsx index ccf12c3540..29e74c36b1 100644 --- a/apps/OpenSign/src/pages/UserList.jsx +++ b/apps/OpenSign/src/pages/UserList.jsx @@ -14,7 +14,7 @@ import DeleteUserModal from "../primitives/DeleteUserModal"; import axios from "axios"; import PasswordResetModal from "../primitives/PasswordResetModal"; import { usersActions } from "../json/ReportJson"; -import { withSessionValidation } from "../utils"; +import { withSessionValidation } from "../utils/withSessionValidation"; const heading = ["Sr.No", "Name", "Email", "Phone", "Role", "Team", "Active"]; const UserList = () => { diff --git a/apps/OpenSign/src/pages/UserProfile.jsx b/apps/OpenSign/src/pages/UserProfile.jsx index dd0d6d3949..17ebc4f112 100644 --- a/apps/OpenSign/src/pages/UserProfile.jsx +++ b/apps/OpenSign/src/pages/UserProfile.jsx @@ -35,6 +35,10 @@ function UserProfile() { const [parseAppId] = useState(localStorage.getItem("parseAppId")); const [editmode, setEditMode] = useState(false); const [name, SetName] = useState(localStorage.getItem("username")); + const [email, setEmail] = useState(UserProfile && UserProfile.email); + const [originalEmail, setOriginalEmail] = useState( + UserProfile && UserProfile.email + ); const [Phone, SetPhone] = useState(UserProfile && UserProfile.phone); const [Image, setImage] = useState(localStorage.getItem("profileImg")); const [isLoader, setIsLoader] = useState(false); @@ -82,6 +86,12 @@ function UserProfile() { const handleSubmit = async (e) => { e.preventDefault(); + const emailToSave = (email || "").toLowerCase().trim(); + // The Save control is type="button", so the input type does not validate. + if (!emailToSave || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailToSave)) { + alert(t("Please Enter valid email")); + return; + } let phn = Phone, res = ""; if (!res) { @@ -108,8 +118,14 @@ function UserProfile() { Name: res.name, Phone: res?.phone || "" }); - alert(t("profile-update-alert")); - setEditMode(false); + if (emailToSave !== (originalEmail || "").toLowerCase().trim()) { + // The new address has to be verified before it is applied. + await handleSendOTP(emailToSave); + setIsVerifyModal(true); + } else { + alert(t("profile-update-alert")); + setEditMode(false); + } setIsLoader(false); //navigate("/dashboard/35KBoSgoAK"); } @@ -219,7 +235,9 @@ function UserProfile() { //`handleVerifyBtn` function is used to send otp on user mail const handleVerifyBtn = async () => { setIsVerifyModal(true); - await handleSendOTP(Parse.User.current().getEmail()); + const targetEmail = + (email || "").toLowerCase().trim() || Parse.User.current().getEmail(); + await handleSendOTP(targetEmail); }; const handleCloseVerifyModal = async () => { setIsVerifyModal(false); @@ -229,12 +247,48 @@ function UserProfile() { e.preventDefault(); setOtpLoader(true); try { + const targetEmail = + (email || "").toLowerCase().trim() || Parse.User.current().getEmail(); const resEmail = await Parse.Cloud.run("verifyemail", { otp: otp, - email: Parse.User.current().getEmail() + email: targetEmail }); - if (resEmail?.message === "Email is verified.") { + if ( + resEmail?.message === "Email is verified." || + resEmail?.message === "Email changed and verified." + ) { + setEmail(targetEmail); + setOriginalEmail(targetEmail); + localStorage.setItem("userEmail", targetEmail); + try { + const userInfo = JSON.parse( + localStorage.getItem("UserInformation") || "{}" + ); + userInfo.email = targetEmail; + localStorage.setItem("UserInformation", JSON.stringify(userInfo)); + } catch (e) { + // ignore + } + // Keep the in-memory Parse user and the cached profile in sync, so the + // sender address used by new requests is the new one. + if (Parse.User.current()) { + Parse.User.current().set("email", targetEmail); + Parse.User.current().set("username", targetEmail); + } + try { + const extUser = JSON.parse( + localStorage.getItem("Extand_Class") || "[]" + ); + if (Array.isArray(extUser) && extUser.length && extUser[0]) { + extUser[0].Email = targetEmail; + extUser[0].NormalizedEmail = targetEmail; + localStorage.setItem("Extand_Class", JSON.stringify(extUser)); + } + } catch (e) { + // ignore + } setIsEmailVerified(true); + setEditMode(false); alert(t("Email-verified-alert-1")); } else if (resEmail?.message === "Email is already verified.") { setIsEmailVerified(true); @@ -252,7 +306,9 @@ function UserProfile() { const handleResend = async (e) => { e.preventDefault(); setOtpLoader(true); - await handleSendOTP(Parse.User.current().getEmail()); + const targetEmail = + (email || "").toLowerCase().trim() || Parse.User.current().getEmail(); + await handleSendOTP(targetEmail); setOtpLoader(false); alert(t("otp-sent-alert")); }; @@ -260,6 +316,7 @@ function UserProfile() { const handleCancel = () => { setEditMode(false); SetName(localStorage.getItem("username")); + setEmail(originalEmail); SetPhone(UserProfile && UserProfile.phone); setImage(localStorage.getItem("profileImg")); setCompany(extendUser && extendUser?.[0]?.Company); @@ -418,6 +475,20 @@ function UserProfile() { /> </div> )} + <div className="os-profile-field"> + <label htmlFor="profile-email">{t("email")}</label> + {editmode ? ( + <input + id="profile-email" + type="email" + value={email} + className="op-input op-input-bordered os-profile-field-input" + onChange={(e) => setEmail(e.target.value)} + /> + ) : ( + <p className="os-profile-field-value">{email}</p> + )} + </div> <div className="os-profile-field"> <label htmlFor="profile-phone">{t("phone")}</label> {editmode ? ( diff --git a/apps/OpenSign/src/primitives/AddContact.jsx b/apps/OpenSign/src/primitives/AddContact.jsx index be7cf445b0..191a12263b 100644 --- a/apps/OpenSign/src/primitives/AddContact.jsx +++ b/apps/OpenSign/src/primitives/AddContact.jsx @@ -2,7 +2,7 @@ import { useState, useEffect } from "react"; import Loader from "./Loader"; import { useTranslation } from "react-i18next"; import axios from "axios"; -import { getTenantDetails } from "../constant/Utils"; +import { getTenantDetails } from "../constant/utils/tenantDownloads.js"; import { emailRegex } from "../constant/const"; import { useDispatch } from "react-redux"; import { sessionStatus } from "../redux/reducers/userReducer"; diff --git a/apps/OpenSign/src/primitives/DownloadPdfZip.jsx b/apps/OpenSign/src/primitives/DownloadPdfZip.jsx index 721b07c49b..a4a1b8a624 100644 --- a/apps/OpenSign/src/primitives/DownloadPdfZip.jsx +++ b/apps/OpenSign/src/primitives/DownloadPdfZip.jsx @@ -3,10 +3,10 @@ import { useTranslation } from "react-i18next"; import ModalUi from "./ModalUi"; import { getSignedUrl, - handleDownloadCertificate, handleDownloadPdf, fileNameWithUnderscore -} from "../constant/Utils"; +} from "../constant/utils/tenantDownloads.js"; +import { handleDownloadCertificate } from "../constant/utils/printCertificates.js"; import Loader from "./Loader"; import JSZip from "jszip"; import { saveAs } from "file-saver"; diff --git a/apps/OpenSign/src/primitives/ErrorBoundary.jsx b/apps/OpenSign/src/primitives/ErrorBoundary.jsx new file mode 100644 index 0000000000..7f47a06265 --- /dev/null +++ b/apps/OpenSign/src/primitives/ErrorBoundary.jsx @@ -0,0 +1,47 @@ +import { Component } from "react"; + +/** + * Catches rendering errors so a failing widget cannot blank the whole page. + * The fallback offers a reload instead of leaving the user with a white screen. + */ +class ErrorBoundary extends Component { + constructor(props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError() { + return { hasError: true }; + } + + componentDidCatch(error, info) { + // Keep the error visible in the console for diagnosis. + console.error("Unhandled UI error:", error, info?.componentStack); + } + + render() { + if (!this.state.hasError) return this.props.children; + return ( + <div className="flex min-h-screen items-center justify-center bg-base-200 p-6"> + <div className="max-w-md rounded-box border border-base-300 bg-base-100 p-6 text-center shadow"> + <h1 className="mb-2 text-lg font-semibold text-base-content"> + Something went wrong + </h1> + <p className="mb-4 text-sm text-base-content/70"> + The page could not be rendered. Your work is saved on the server; + reload to continue. + </p> + <button + type="button" + className="op-btn op-btn-primary" + onClick={() => window.location.reload()} + > + Reload + </button> + </div> + </div> + ); + } +} + +export default ErrorBoundary; diff --git a/apps/OpenSign/src/primitives/PasswordResetModal.jsx b/apps/OpenSign/src/primitives/PasswordResetModal.jsx index 3fd9bcfb98..669ce1f5d3 100644 --- a/apps/OpenSign/src/primitives/PasswordResetModal.jsx +++ b/apps/OpenSign/src/primitives/PasswordResetModal.jsx @@ -101,7 +101,7 @@ export default function PasswordResetModal({ await navigator.clipboard.writeText(password); showAlert("success", t("copied"), 1200); setCopied(true); - setTimeout(() => setCopied(false, 1200)); + setTimeout(() => setCopied(false), 1200); } catch (e) { console.error("Clipboard error", e); } diff --git a/apps/OpenSign/src/primitives/Tooltip.jsx b/apps/OpenSign/src/primitives/Tooltip.jsx index dfc1a26b97..e6bf68cd7c 100644 --- a/apps/OpenSign/src/primitives/Tooltip.jsx +++ b/apps/OpenSign/src/primitives/Tooltip.jsx @@ -1,6 +1,6 @@ import React from "react"; import { Tooltip as ReactTooltip } from "react-tooltip"; -import { openInNewTab } from "../constant/Utils"; +import { openInNewTab } from "../constant/utils/coreConstants.js"; const Tooltip = ({ id, message, diff --git a/apps/OpenSign/src/primitives/Tour.jsx b/apps/OpenSign/src/primitives/Tour.jsx index 7513b365cc..ed0b01a65b 100644 --- a/apps/OpenSign/src/primitives/Tour.jsx +++ b/apps/OpenSign/src/primitives/Tour.jsx @@ -134,8 +134,11 @@ export default function Tour({ defaultOpen={isOpen} // scrollOffset={-100} // available only for v1 inViewThreshold={{ y: 150, x: 30 }} - onClickMask={() => {}} - disableKeyboardNavigation={["esc"]} + // A step whose selector is missing (widget on another page, hidden + // field) leaves the mask without a popover: keep the mask and Esc as + // exits so the user can never get trapped behind the tour. + onClickMask={(clickProps) => clickProps?.setIsOpen?.(false)} + disableKeyboardNavigation={[]} showBadge={showNumber} showNavigation={showNavigation} showPrevNextButtons={showNavigation} diff --git a/apps/OpenSign/src/primitives/ValidateRoute.jsx b/apps/OpenSign/src/primitives/ValidateRoute.jsx index c1e2c38d7c..01b31b4cad 100644 --- a/apps/OpenSign/src/primitives/ValidateRoute.jsx +++ b/apps/OpenSign/src/primitives/ValidateRoute.jsx @@ -1,7 +1,7 @@ import React, { useEffect } from "react"; import Parse from "parse"; import { Outlet } from "react-router"; -import { saveLanguageInLocal } from "../constant/Utils"; +import { saveLanguageInLocal } from "../constant/utils/coreConstants.js"; import { useTranslation } from "react-i18next"; import { isLocalQaIdentityEnabled } from "../qa/localQaIdentity"; const ValidateRoute = () => { diff --git a/apps/OpenSign/src/utils/fileUtils.js b/apps/OpenSign/src/utils/fileUtils.js index 86924d4627..fcfa18e00a 100644 --- a/apps/OpenSign/src/utils/fileUtils.js +++ b/apps/OpenSign/src/utils/fileUtils.js @@ -1,5 +1,5 @@ import { SaveFileSize } from "../constant/saveFileSize"; -import { getSecureUrl } from "../constant/Utils"; +import { getSecureUrl } from "../constant/utils/coreConstants.js"; import Parse from "parse"; import i18n from "../i18n"; diff --git a/apps/OpenSign/src/utils/linkedFields.js b/apps/OpenSign/src/utils/linkedFields.js new file mode 100644 index 0000000000..5e0d265ffd --- /dev/null +++ b/apps/OpenSign/src/utils/linkedFields.js @@ -0,0 +1,70 @@ +const sameValue = (a, b) => + Object.is(a, b) || + (Array.isArray(a) && + Array.isArray(b) && + a.length === b.length && + a.every((item, i) => Object.is(item, b[i]))); + +// Update only siblings belonging to the same signer, across all their pages. +export function updateLinkedFields(state, { key, name, value, signerId }) { + if (!name || !Array.isArray(state)) return state; + let changed = false; + const updatePage = (page) => { + let pageChanged = false; + const pos = (page.pos || []).map((widget) => { + if ( + widget.key === key || + widget.options?.name !== name || + sameValue(widget.options?.response, value) + ) + return widget; + changed = pageChanged = true; + return { ...widget, options: { ...widget.options, response: value } }; + }); + return pageChanged ? { ...page, pos } : page; + }; + const nested = state.some( + (item) => item.signerPtr || item.Role === "prefill" + ); + const result = nested + ? state.map((signer) => { + if (signer.Id !== signerId || !signer.placeHolder) return signer; + const pages = signer.placeHolder.map(updatePage); + return pages.some((page, i) => page !== signer.placeHolder[i]) + ? { ...signer, placeHolder: pages } + : signer; + }) + : state.map(updatePage); + return changed ? result : state; +} + +// Initials need their image metadata as well as their response for rendering. +export function updateLinkedInitials(state, { source, signerId }) { + if (source?.type !== "initials" || !source.options?.name) return state; + const fields = ["SignUrl", "ImageType", "signatureType", "typeSignature", "typeFont", "fontColor"]; + let changed = false; + const updatePage = (page) => { + let pageChanged = false; + const pos = (page.pos || []).map((widget) => { + if (widget.key === source.key || widget.type !== "initials" || widget.options?.name !== source.options.name) return widget; + const same = sameValue(widget.options?.response, source.options.response) && fields.every((field) => + Object.hasOwn(widget, field) === Object.hasOwn(source, field) && Object.is(widget[field], source[field])); + if (same) return widget; + const next = { ...widget, options: { ...widget.options, response: source.options.response } }; + for (const field of fields) { + if (Object.hasOwn(source, field)) next[field] = source[field]; + else delete next[field]; + } + changed = pageChanged = true; + return next; + }); + return pageChanged ? { ...page, pos } : page; + }; + const nested = state.some((item) => item.signerPtr || item.Role === "prefill"); + const next = nested ? state.map((signer) => { + if (signer.Id !== signerId || !signer.placeHolder) return signer; + const pages = signer.placeHolder.map(updatePage); + return pages.some((page, index) => page !== signer.placeHolder[index]) ? { ...signer, placeHolder: pages } : signer; + }) : state.map(updatePage); + return changed ? next : state; +} diff --git a/apps/OpenSign/src/utils/linkedFields.test.js b/apps/OpenSign/src/utils/linkedFields.test.js new file mode 100644 index 0000000000..1527ca20b3 --- /dev/null +++ b/apps/OpenSign/src/utils/linkedFields.test.js @@ -0,0 +1,117 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +globalThis.window = globalThis.window || { + RUNTIME_ENV: {}, + localStorage: { + getItem: () => null, + setItem: () => {}, + removeItem: () => {} + }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "" } +}; +const utils = await import("./linkedFields"); +describe("linked fields", () => { + it("preserves the state reference when linked values already match", () => { + expect(utils.updateLinkedFields).toBeTypeOf("function"); + const state = [ + { + pos: [ + { key: "a", options: { name: "name", response: "A" } }, + { key: "b", options: { name: "name", response: "A" } } + ] + } + ]; + expect( + utils.updateLinkedFields(state, { + key: "a", + name: "name", + value: "A", + index: 0 + }) + ).toBe(state); + }); + it("updates matching siblings without changing unrelated widgets", () => { + const sibling = { key: "b", options: { name: "name", response: "old" } }; + const other = { key: "c", options: { name: "other", response: "old" } }; + const state = [{ pos: [sibling, other] }]; + const updated = utils.updateLinkedFields(state, { + key: "a", + name: "name", + value: "new", + index: 0 + }); + expect(updated[0].pos[0].options.response).toBe("new"); + expect(updated[0].pos[1]).toBe(other); + expect(sibling.options.response).toBe("old"); + }); + it("updates all pages of the current signer without changing other signers", () => { + const widget = (key, response) => ({ + key, + options: { name: "name", response } + }); + const state = [ + { + Id: "one", + signerPtr: {}, + placeHolder: [ + { pos: [widget("a", "new")] }, + { pos: [widget("b", "old")] } + ] + }, + { Id: "two", signerPtr: {}, placeHolder: [{ pos: [widget("c", "old")] }] } + ]; + const next = utils.updateLinkedFields(state, { + key: "a", + name: "name", + value: "new", + signerId: "one" + }); + expect(next[0].placeHolder[1].pos[0].options.response).toBe("new"); + expect(next[1]).toBe(state[1]); + expect(next[0].placeHolder[0]).toBe(state[0].placeHolder[0]); + }); + it("recognizes equal array values without rebuilding state", () => { + const state = [ + { pos: [{ key: "b", options: { name: "choices", response: [0, 2] } }] } + ]; + expect( + utils.updateLinkedFields(state, { + key: "a", + name: "choices", + value: [0, 2] + }) + ).toBe(state); + }); + it("copies the saved initials and their rendering metadata to matching initials only", () => { + const source = { + key: "initial-1", type: "initials", SignUrl: "data:image/png;base64,abc", + signatureType: "type", typeSignature: "AD", typeFont: "Fasthand", + options: { name: "initials", response: "data:image/png;base64,abc" } + }; + const sibling = { key: "initial-2", type: "initials", Width: 32, options: { name: "initials" } }; + const unrelated = { key: "text", type: "text", options: { name: "initials" } }; + const state = [{ Id: "one", signerPtr: {}, placeHolder: [{ pos: [source] }, { pos: [sibling, unrelated] }] }]; + const next = utils.updateLinkedInitials(state, { source, signerId: "one" }); + const copied = next[0].placeHolder[1].pos[0]; + expect(copied.SignUrl).toBe(source.SignUrl); + expect(copied.options.response).toBe(source.options.response); + expect(copied.signatureType).toBe("type"); + expect(copied.typeSignature).toBe("AD"); + expect(copied.typeFont).toBe("Fasthand"); + expect(copied.Width).toBe(32); + expect(next[0].placeHolder[1].pos[1]).toBe(unrelated); + }); + it("keeps an unchanged sibling object when saving an inline value", async () => { + const { onChangeInput } = await import("../constant/Utils"); + const sibling = { key: "b", type: "text input", options: { name: "shared", response: "A", defaultValue: "" } }; + let state = [{ pageNumber: 1, pos: [ + { key: "a", type: "text input", options: { name: "shared", response: "old", defaultValue: "" } }, + sibling + ] }]; + onChangeInput("A", state[0].pos[0], state, 0, (update) => { + state = typeof update === "function" ? update(state) : update; + }); + expect(state[0].pos[1]).toBe(sibling); + }); +}); diff --git a/apps/OpenSign/src/utils/nextPendingWidget.test.js b/apps/OpenSign/src/utils/nextPendingWidget.test.js new file mode 100644 index 0000000000..e5055632c5 --- /dev/null +++ b/apps/OpenSign/src/utils/nextPendingWidget.test.js @@ -0,0 +1,36 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +globalThis.window = globalThis.window || { + RUNTIME_ENV: {}, + localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "" } +}; +const utils = await import("../constant/Utils"); + +const item = (key, response, extra = {}) => ({ + key, + options: { response }, + ...extra +}); + +describe("next pending widget", () => { + it("skips answered fields and preserves page order after the current field", () => { + const pages = [ + { pageNumber: 1, pos: [item("before", ""), item("current", "done"), item("checked", [0])] }, + { pageNumber: 2, pos: [item("signed", "", { SignUrl: "signed" }), item("next", "")] } + ]; + expect(utils.nextPendingWidget(pages, "current")).toMatchObject({ + pageNumber: 2, + widget: { key: "next" } + }); + }); + it("wraps to the beginning and ignores read-only fields", () => { + const pages = [{ pageNumber: 1, pos: [item("first", ""), item("current", "done"), { key: "locked", options: { isReadOnly: true } }] }]; + expect(utils.nextPendingWidget(pages, "current").widget.key).toBe("first"); + }); + it("returns no field when all are answered or read-only", () => { + const pages = [{ pageNumber: 1, pos: [item("current", "done"), item("zero", 0), item("checked", [0])] }]; + expect(utils.nextPendingWidget(pages, "current")).toBeNull(); + }); +}); diff --git a/apps/OpenSign/src/utils/pdfDocumentUtils.js b/apps/OpenSign/src/utils/pdfDocumentUtils.js new file mode 100644 index 0000000000..a10b866fec --- /dev/null +++ b/apps/OpenSign/src/utils/pdfDocumentUtils.js @@ -0,0 +1,40 @@ +import { PDFDict, PDFDocument, PDFObjectCopier } from "pdf-lib"; + +/** + * Copies the document information dictionary (title, author, subject, keywords, + * custom entries, ...) to a document that was rebuilt with `copyPages`, which + * only carries over the pages. + * @param {PDFDocument} sourceDoc - document to read the metadata from + * @param {PDFDocument} targetDoc - document created with `PDFDocument.create()` + */ +export const copyPdfMetadata = (sourceDoc, targetDoc) => { + // Strings in the information dictionary of an encrypted document are ciphertext. + if (sourceDoc.isEncrypted) return; + const { context: source } = sourceDoc; + const { context: target } = targetDoc; + const sourceInfo = source.lookup(source.trailerInfo.Info); + if (!(sourceInfo instanceof PDFDict)) return; + const targetInfo = target.lookup(target.trailerInfo.Info, PDFDict); + const copier = PDFObjectCopier.for(source, target); + for (const [key, value] of sourceInfo.entries()) { + targetInfo.set(key, copier.copy(value)); + } +}; + +/** + * Merges PDF files into one document that keeps the metadata of the first file. + * @param {(ArrayBuffer | Uint8Array)[]} pdfBuffers - PDF files in merge order + * @returns {Promise<PDFDocument>} merged document + */ +export const mergePdfBuffers = async (pdfBuffers) => { + const merged = await PDFDocument.create(); + for (const [index, bytes] of pdfBuffers.entries()) { + const doc = await PDFDocument.load(bytes, { ignoreEncryption: true }); + const pages = await merged.copyPages(doc, doc.getPageIndices()); + pages.forEach((p) => merged.addPage(p)); + if (index === 0) { + copyPdfMetadata(doc, merged); + } + } + return merged; +}; diff --git a/apps/OpenSign/src/utils/pdfDocumentUtils.test.js b/apps/OpenSign/src/utils/pdfDocumentUtils.test.js new file mode 100644 index 0000000000..82b556d855 --- /dev/null +++ b/apps/OpenSign/src/utils/pdfDocumentUtils.test.js @@ -0,0 +1,135 @@ +// @vitest-environment jsdom +import { describe, expect, it } from "vitest"; +import { PDFDict, PDFDocument, PDFName, PDFRef, PDFString } from "pdf-lib"; +import { copyPdfMetadata, mergePdfBuffers } from "./pdfDocumentUtils"; +import { reorderPdfPages } from "../constant/Utils"; + +const creationDate = new Date("2020-02-03T04:05:06Z"); + +const createPdf = async ({ pageCount = 1, metadata = true } = {}) => { + const doc = await PDFDocument.create(); + for (let i = 0; i < pageCount; i++) { + doc.addPage(); + } + if (metadata) { + doc.setTitle("Master service agreement"); + doc.setAuthor("José García"); + doc.setSubject("Contract"); + doc.setKeywords(["invoice:42", "契約"]); + doc.setCreator("Word"); + doc.setCreationDate(creationDate); + } + return doc; +}; + +const expectOriginalMetadata = (doc) => { + expect(doc.getTitle()).toBe("Master service agreement"); + expect(doc.getAuthor()).toBe("José García"); + expect(doc.getSubject()).toBe("Contract"); + expect(doc.getKeywords()).toBe("invoice:42 契約"); + expect(doc.getCreator()).toBe("Word"); + expect(doc.getCreationDate()).toEqual(creationDate); +}; + +const reload = async (doc) => + PDFDocument.load(await doc.save({ useObjectStreams: false }), { + updateMetadata: false + }); + +const infoDict = (doc) => + doc.context.lookup(doc.context.trailerInfo.Info, PDFDict); + +describe("mergePdfBuffers", () => { + it("keeps the metadata of a single uploaded PDF", async () => { + const pdf = await (await createPdf()).save(); + + expectOriginalMetadata(await reload(await mergePdfBuffers([pdf]))); + }); + + it("keeps the metadata of the first PDF and all pages when merging", async () => { + const first = await (await createPdf({ pageCount: 2 })).save(); + const second = await createPdf(); + second.setTitle("Second file"); + second.setKeywords(["second"]); + + const merged = await reload( + await mergePdfBuffers([first, await second.save()]) + ); + + expect(merged.getPageCount()).toBe(3); + expectOriginalMetadata(merged); + }); + + it("keeps custom entries of the information dictionary", async () => { + const doc = await createPdf(); + infoDict(doc).set(PDFName.of("Department"), PDFString.of("Legal")); + + const merged = await reload(await mergePdfBuffers([await doc.save()])); + + expect(infoDict(merged).lookup(PDFName.of("Department")).asString()).toBe( + "Legal" + ); + }); + + it("merges PDFs that have no metadata", async () => { + const pdf = await (await createPdf({ metadata: false })).save(); + + const merged = await reload(await mergePdfBuffers([pdf, pdf])); + + expect(merged.getPageCount()).toBe(2); + expect(merged.getKeywords()).toBeUndefined(); + }); +}); + +describe("copyPdfMetadata", () => { + it("copies metadata stored as indirect objects", async () => { + const source = await createPdf(); + const titleRef = source.context.register(PDFString.of("Indirect title")); + infoDict(source).set(PDFName.of("Title"), titleRef); + const target = await PDFDocument.create(); + + copyPdfMetadata(source, target); + + expect((await reload(target)).getTitle()).toBe("Indirect title"); + }); + + it("still saves when an entry points to a missing object", async () => { + const source = await createPdf(); + infoDict(source).set(PDFName.of("Broken"), PDFRef.of(9999)); + const target = await PDFDocument.create(); + + copyPdfMetadata(source, target); + + expect((await reload(target)).getTitle()).toBe("Master service agreement"); + }); + + it("does not copy the ciphertext metadata of an encrypted PDF", async () => { + const source = await createPdf(); + source.isEncrypted = true; + const target = await PDFDocument.create(); + + copyPdfMetadata(source, target); + + expect(target.getKeywords()).toBeUndefined(); + }); +}); + +describe("reorderPdfPages", () => { + it("keeps the metadata and applies the new page order", async () => { + const doc = await createPdf({ pageCount: 2 }); + doc.getPage(0).setWidth(100); + doc.getPage(1).setWidth(200); + + const { arrayBuffer, totalPages } = await reorderPdfPages( + await doc.save(), + [2, 1] + ); + + const reordered = await PDFDocument.load(arrayBuffer, { + updateMetadata: false + }); + expect(totalPages).toBe(2); + expect(reordered.getPage(0).getWidth()).toBe(200); + expectOriginalMetadata(reordered); + }); +}); diff --git a/apps/OpenSign/src/utils/prefillUtils.js b/apps/OpenSign/src/utils/prefillUtils.js index d47ec29961..22bc9fa20a 100644 --- a/apps/OpenSign/src/utils/prefillUtils.js +++ b/apps/OpenSign/src/utils/prefillUtils.js @@ -1,15 +1,19 @@ import { SaveFileSize } from "../constant/saveFileSize"; +// Direct part imports: the ../constant/Utils facade is never imported here +// so the login bundle is not coupled to the pdf-lib modules (#55). +import { convertBase64ToFile } from "../constant/utils/pdfPageView.js"; import { - convertBase64ToFile, convertPdfArrayBuffer, - createDocument, - generatePdfName, - embedWidgetsToDoc, + getSignedUrl +} from "../constant/utils/tenantDownloads.js"; +import { createDocument } from "../constant/utils/UtilsPart05.js"; +import { generatePdfName } from "../constant/utils/pdfPageEdit.js"; +import { embedWidgetsToDoc } from "../constant/utils/widgetEmbedding.js"; +import { randomId, getBase64FromUrl, - drawWidget, - getSignedUrl -} from "../constant/Utils"; + drawWidget +} from "../constant/utils/coreConstants.js"; import { PDFDocument } from "pdf-lib"; export const prefillBlockColor = "transparent"; diff --git a/apps/OpenSign/src/utils/radioPdf.test.js b/apps/OpenSign/src/utils/radioPdf.test.js new file mode 100644 index 0000000000..0774ebd723 --- /dev/null +++ b/apps/OpenSign/src/utils/radioPdf.test.js @@ -0,0 +1,53 @@ +// @vitest-environment node +import { describe, expect, it, vi } from "vitest"; +import { readFile } from "node:fs/promises"; +import { PDFDocument, PDFRadioGroup } from "pdf-lib"; + +vi.mock("../constant/runtimeConfig", async (importOriginal) => ({ + ...(await importOriginal()), + getRuntimePdfFontUrl: () => "https://example.invalid/test-font" +})); +globalThis.window = globalThis.window || { + innerWidth: 1024, + RUNTIME_ENV: {}, + localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "" } +}; +const { embedWidgetsToDoc } = await import("../constant/Utils"); + +describe("PDF radio options", () => { + it.each([ + ["imported object response", { name: "Yes" }, undefined, "Yes"], + ["string response", "Yes", undefined, "Yes"], + ["default without response", undefined, "No", "No"], + ["stale response", "old", undefined, null], + ["NaN response", NaN, undefined, null], + ["malformed response", {}, undefined, null], + ["missing response", undefined, undefined, null] + ])("embeds %s safely in a real PDF", async (_label, response, defaultValue, expected) => { + const bytes = await readFile("node_modules/pdfjs-dist/standard_fonts/LiberationSans-Regular.ttf"); + vi.stubGlobal("fetch", vi.fn(async () => ({ arrayBuffer: async () => bytes }))); + const select = vi.spyOn(PDFRadioGroup.prototype, "select"); + try { + const pdf = await PDFDocument.create(); + pdf.addPage([612, 792]); + const widgets = [{ pageNumber: 1, pos: [{ + key: "radio-1", type: "radio button", xPosition: 40, yPosition: 100, + Width: 180, Height: 60, options: { + values: [{ name: "Yes", checked: true }, { name: "No", checked: false }], + response, defaultValue, fontSize: 12, fontColor: "black" + } + }] }]; + const result = await embedWidgetsToDoc(widgets, pdf, true, 1, []); + expect(result).toBeTypeOf("string"); + if (expected === null) expect(select).not.toHaveBeenCalled(); + else expect(select).toHaveBeenCalledWith(expected); + const saved = await PDFDocument.load(result); + expect(saved.getPageCount()).toBe(1); + } finally { + select.mockRestore(); + vi.unstubAllGlobals(); + } + }); +}); diff --git a/apps/OpenSign/src/utils/radioValue.test.js b/apps/OpenSign/src/utils/radioValue.test.js new file mode 100644 index 0000000000..03f9db04f7 --- /dev/null +++ b/apps/OpenSign/src/utils/radioValue.test.js @@ -0,0 +1,23 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +globalThis.window = globalThis.window || { + RUNTIME_ENV: {}, + localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "" } +}; +const utils = await import("../constant/Utils"); + +describe("radio selection", () => { + it("compares normalized string values", () => { + expect(utils.isRadioSelected(" Yes ", "Yes")).toBe(true); + expect(utils.isRadioSelected("No", "Yes")).toBe(false); + }); + it("accepts imported option objects", () => { + expect(utils.isRadioSelected({ name: "Yes", checked: true }, { name: "Yes" })).toBe(true); + }); + it("handles array and absent defaults without throwing", () => { + expect(utils.isRadioSelected([{ name: "Yes", checked: true }], "Yes")).toBe(true); + expect(utils.isRadioSelected(undefined, "Yes")).toBe(false); + }); +}); diff --git a/apps/OpenSign/src/utils/snapping.js b/apps/OpenSign/src/utils/snapping.js new file mode 100644 index 0000000000..18cf094671 --- /dev/null +++ b/apps/OpenSign/src/utils/snapping.js @@ -0,0 +1,65 @@ +// Alignment helper: snaps a dragged box to the edges and centres of its +// neighbours and of the page, within a tolerance expressed in pixels. +export const SNAP_TOLERANCE_PX = 6; + +const ownLines = (start, size) => [start, start + size / 2, start + size]; + +const nearestDelta = (ownLinesArr, targets, tolerance) => { + let best = null; + let guide = null; + ownLinesArr.forEach((own) => { + targets.forEach((target) => { + const delta = target - own; + if (Math.abs(delta) > tolerance) return; + if (best === null || Math.abs(delta) < Math.abs(best)) { + best = delta; + guide = target; + } + }); + }); + return { delta: best, guide }; +}; + +/** + * @param {object} box - { x, y, width, height } in pixels. + * @param {number[]} verticalTargets - x coordinates to align to. + * @param {number[]} horizontalTargets - y coordinates to align to. + * @param {number} tolerance - maximum distance in pixels. + * @returns {{x:number, y:number, guideX:number|null, guideY:number|null, snapped:boolean}} + */ +export const snapBox = ({ + x, + y, + width, + height, + verticalTargets = [], + horizontalTargets = [], + tolerance = SNAP_TOLERANCE_PX +}) => { + const vx = nearestDelta(ownLines(x, width), verticalTargets, tolerance); + const hy = nearestDelta(ownLines(y, height), horizontalTargets, tolerance); + return { + x: vx.delta === null ? x : x + vx.delta, + y: hy.delta === null ? y : y + hy.delta, + guideX: vx.guide, + guideY: hy.guide, + snapped: vx.delta !== null || hy.delta !== null + }; +}; + +// Builds the alignment targets from the sibling widgets of the same page. +// Every widget contributes its two edges and its centre. +export const alignmentTargets = (widgets = [], { excludeKey } = {}) => { + const verticalTargets = []; + const horizontalTargets = []; + widgets.forEach((widget) => { + if (!widget || widget.key === excludeKey) return; + const x = Number(widget.xPx) || 0; + const y = Number(widget.yPx) || 0; + const w = Number(widget.widthPx) || 0; + const h = Number(widget.heightPx) || 0; + verticalTargets.push(x, x + w / 2, x + w); + horizontalTargets.push(y, y + h / 2, y + h); + }); + return { verticalTargets, horizontalTargets }; +}; diff --git a/apps/OpenSign/src/utils/snapping.test.js b/apps/OpenSign/src/utils/snapping.test.js new file mode 100644 index 0000000000..48f421be43 --- /dev/null +++ b/apps/OpenSign/src/utils/snapping.test.js @@ -0,0 +1,136 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { snapBox, alignmentTargets, SNAP_TOLERANCE_PX } from "./snapping"; + +describe("snapBox", () => { + it("snaps the left edge to a nearby target", () => { + const result = snapBox({ + x: 103, + y: 40, + width: 50, + height: 20, + verticalTargets: [100] + }); + expect(result.x).toBe(100); + expect(result.guideX).toBe(100); + expect(result.snapped).toBe(true); + }); + + it("snaps the centre to a nearby target", () => { + const result = snapBox({ + x: 72, + y: 40, + width: 50, + height: 20, + verticalTargets: [100] + }); + // centre is at 97, so it moves by +3 + expect(result.x).toBe(75); + expect(result.guideX).toBe(100); + }); + + it("snaps the right edge to a nearby target", () => { + const result = snapBox({ + x: 48, + y: 40, + width: 50, + height: 20, + verticalTargets: [100] + }); + expect(result.x).toBe(50); + expect(result.guideX).toBe(100); + }); + + it("does not move when the nearest target is outside the tolerance", () => { + const result = snapBox({ + x: 40, + y: 40, + width: 20, + height: 20, + verticalTargets: [100], + horizontalTargets: [200] + }); + expect(result.x).toBe(40); + expect(result.y).toBe(40); + expect(result.snapped).toBe(false); + expect(result.guideX).toBe(null); + }); + + it("snaps both axes independently", () => { + const result = snapBox({ + x: 98, + y: 198, + width: 20, + height: 20, + verticalTargets: [100], + horizontalTargets: [200] + }); + expect(result.x).toBe(100); + expect(result.y).toBe(200); + }); + + it("chooses the closest target when several are in range", () => { + const result = snapBox({ + x: 100, + y: 0, + width: 10, + height: 10, + verticalTargets: [99, 104] + }); + expect(result.x).toBe(99); + }); + + it("respects the configured tolerance", () => { + const within = snapBox({ + x: 100 + SNAP_TOLERANCE_PX, + y: 0, + width: 10, + height: 10, + verticalTargets: [100] + }); + expect(within.snapped).toBe(true); + const outside = snapBox({ + x: 100 + SNAP_TOLERANCE_PX + 1, + y: 0, + width: 10, + height: 10, + verticalTargets: [100] + }); + expect(outside.snapped).toBe(false); + }); + + it("works with an empty target list", () => { + const result = snapBox({ x: 5, y: 6, width: 10, height: 10 }); + expect(result).toEqual({ x: 5, y: 6, guideX: null, guideY: null, snapped: false }); + }); +}); + +describe("alignmentTargets", () => { + const widgets = [ + { key: "a", xPx: 100, yPx: 50, widthPx: 40, heightPx: 20 }, + { key: "b", xPx: 200, yPx: 150, widthPx: 60, heightPx: 30 } + ]; + + it("produces the two edges and the centre of every widget", () => { + const { verticalTargets, horizontalTargets } = alignmentTargets(widgets); + expect(verticalTargets).toContain(100); + expect(verticalTargets).toContain(120); + expect(verticalTargets).toContain(140); + expect(horizontalTargets).toContain(50); + expect(horizontalTargets).toContain(60); + expect(horizontalTargets).toContain(70); + }); + + it("excludes the widget being dragged", () => { + const { verticalTargets } = alignmentTargets(widgets, { excludeKey: "a" }); + expect(verticalTargets).not.toContain(100); + expect(verticalTargets).toContain(200); + }); + + it("tolerates empty input", () => { + expect(alignmentTargets()).toEqual({ + verticalTargets: [], + horizontalTargets: [] + }); + }); +}); diff --git a/apps/OpenSign/src/utils/theme.js b/apps/OpenSign/src/utils/theme.js new file mode 100644 index 0000000000..3925e8bfd5 --- /dev/null +++ b/apps/OpenSign/src/utils/theme.js @@ -0,0 +1,15 @@ +const THEME_ATTRIBUTES = { dark: "opensigndark", light: "opensigncss" }; + +// `applyTheme` is used to show a theme and remember it on this device +export const applyTheme = (theme) => { + localStorage.setItem("theme", theme); + document.documentElement.setAttribute("data-theme", THEME_ATTRIBUTES[theme]); +}; + +// `applySavedTheme` is used to show the theme saved on the user's profile. Users +// who never chose a theme have none, so they keep the theme of the current device. +export const applySavedTheme = (theme) => { + if (theme === "dark" || theme === "light") { + applyTheme(theme); + } +}; diff --git a/apps/OpenSign/src/utils/theme.test.js b/apps/OpenSign/src/utils/theme.test.js new file mode 100644 index 0000000000..025a2848a0 --- /dev/null +++ b/apps/OpenSign/src/utils/theme.test.js @@ -0,0 +1,47 @@ +// @vitest-environment jsdom +import { beforeEach, describe, expect, it } from "vitest"; +import { applySavedTheme, applyTheme } from "./theme"; + +const shownTheme = () => document.documentElement.getAttribute("data-theme"); + +describe("theme", () => { + beforeEach(() => { + localStorage.clear(); + document.documentElement.removeAttribute("data-theme"); + }); + + it("shows and remembers the dark theme", () => { + applyTheme("dark"); + + expect(shownTheme()).toBe("opensigndark"); + expect(localStorage.getItem("theme")).toBe("dark"); + }); + + it("shows and remembers the light theme", () => { + applyTheme("light"); + + expect(shownTheme()).toBe("opensigncss"); + expect(localStorage.getItem("theme")).toBe("light"); + }); + + it("applies the theme saved on the profile over the device theme", () => { + applyTheme("light"); + + applySavedTheme("dark"); + + expect(shownTheme()).toBe("opensigndark"); + expect(localStorage.getItem("theme")).toBe("dark"); + }); + + it.each([undefined, null, "", "constructor", "solarized"])( + "keeps the device theme when the saved theme is %s", + (saved) => { + applyTheme("dark"); + + applySavedTheme(saved); + + expect(shownTheme()).toBe("opensigndark"); + expect(localStorage.getItem("theme")).toBe("dark"); + } + ); +}); diff --git a/apps/OpenSign/src/utils/widgetUtils.js b/apps/OpenSign/src/utils/widgetUtils.js index 33b7abc135..05e9297c04 100644 --- a/apps/OpenSign/src/utils/widgetUtils.js +++ b/apps/OpenSign/src/utils/widgetUtils.js @@ -1,17 +1,21 @@ import moment from "moment"; +// Direct part imports: the ../constant/Utils facade is never imported here +// so the login bundle is not coupled to the pdf-lib modules (#55). +import { generateTitleFromFilename } from "../constant/utils/pdfPageEdit.js"; +import { selectFormat } from "../constant/utils/widgetCatalog.js"; import { - generateTitleFromFilename, - selectFormat, changeDateToMomentFormat, - isBase64, + addWidgetOptions +} from "../constant/utils/widgetOptions.js"; +import { isBase64 } from "../constant/utils/imageHandling.js"; +import { drawWidget, radioButtonWidget, textInputWidget, textWidget, cellsWidget, - addWidgetOptions, getFontSizeForHeight -} from "../constant/Utils"; +} from "../constant/utils/coreConstants.js"; import { base64StringtoFile, uploadFile } from "./fileUtils"; import { sanitizeFileName } from "./sanitizeFileName"; import Parse from "parse"; diff --git a/apps/OpenSign/src/utils/widgetUtils.test.js b/apps/OpenSign/src/utils/widgetUtils.test.js new file mode 100644 index 0000000000..b9b5e7301e --- /dev/null +++ b/apps/OpenSign/src/utils/widgetUtils.test.js @@ -0,0 +1,137 @@ +// @vitest-environment node +import { describe, it, expect } from "vitest"; +import { sanitizeFileName } from "./sanitizeFileName"; + +// widgetUtils pulls in the app configuration, which reads window on import. +// A minimal stub keeps this suite free of a DOM implementation. +globalThis.window = globalThis.window || { + RUNTIME_ENV: {}, + localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + location: { origin: "http://localhost", pathname: "/", search: "" }, + navigator: { userAgent: "" }, +}; + +const { + getInitials, + isValidBase64, + hasSignatureWidget, + hasDuplicateWidgetNames, + applyNumberFormulasToPages +} = await import("./widgetUtils"); + +describe("sanitizeFileName", () => { + it("keeps letters, digits, dots, dashes and underscores", () => { + expect(sanitizeFileName("contract_v2-final.pdf")).toBe("contract_v2-final.pdf"); + }); + + it("removes spaces and path separators", () => { + expect(sanitizeFileName("../my file.pdf")).toBe("myfile.pdf"); + expect(sanitizeFileName("a/b\\c.pdf")).toBe("abc.pdf"); + }); + + it("keeps only the last dot", () => { + expect(sanitizeFileName("a.b.c.pdf")).toBe("abc.pdf"); + }); + + it("tolerates an empty value", () => { + expect(sanitizeFileName("")).toBe(""); + expect(sanitizeFileName(undefined)).toBeUndefined(); + }); +}); + +describe("getInitials", () => { + it("takes the initial of the first two words", () => { + expect(getInitials("Ada Lovelace")).toBe("A L"); + }); + + it("takes the first letter of a single word", () => { + expect(getInitials("Ada")).toBe("A"); + }); + + it("tolerates an empty value", () => { + expect(getInitials("")).toBe(""); + expect(getInitials(null)).toBe(""); + }); +}); + +describe("isValidBase64", () => { + it("accepts a valid base64 string", () => { + expect(isValidBase64("SGVsbG8=")).toBe(true); + }); + + it("accepts a data URI", () => { + expect(isValidBase64("data:image/png;base64,SGVsbG8=")).toBe(true); + }); + + it("rejects plain text and empty values", () => { + expect(isValidBase64("not base64 !!")).toBe(false); + expect(isValidBase64("")).toBe(false); + }); +}); + +describe("hasSignatureWidget", () => { + const withSignature = { + placeHolder: [{ pos: [{ type: "signature" }] }] + }; + const withTextOnly = { placeHolder: [{ pos: [{ type: "text" }] }] }; + + it("detects a signature widget in the signer placeholders", () => { + expect(hasSignatureWidget(withSignature)).toBe(true); + }); + + it("returns false when the signer only has text widgets", () => { + expect(hasSignatureWidget(withTextOnly)).toBe(false); + }); + + it("returns false for a signer without placeholders", () => { + expect(hasSignatureWidget({})).toBe(false); + expect(hasSignatureWidget({ placeHolder: [] })).toBe(false); + }); +}); + +describe("hasDuplicateWidgetNames", () => { + it("ignores repetitions inside the same signer", () => { + const placeholders = [ + { placeHolder: [{ pos: [{ options: { name: "a" } }, { options: { name: "a" } }] }] } + ]; + expect(hasDuplicateWidgetNames(placeholders)).toBe(false); + }); + + it("detects a name shared by two signers", () => { + const placeholders = [ + { placeHolder: [{ pos: [{ options: { name: "a" } }] }] }, + { placeHolder: [{ pos: [{ options: { name: "a" } }] }] } + ]; + expect(hasDuplicateWidgetNames(placeholders)).toBe(true); + }); + + it("accepts distinct names and widgets without a name", () => { + const placeholders = [ + { placeHolder: [{ pos: [{ options: { name: "a" } }] }] }, + { placeHolder: [{ pos: [{ options: {} }] }] }, + { placeHolder: [{ pos: [{ options: { name: "b" } }] }] } + ]; + expect(hasDuplicateWidgetNames(placeholders)).toBe(false); + }); +}); + +describe("applyNumberFormulasToPages", () => { + it("returns a deep clone instead of mutating the caller data", () => { + const pages = [{ pos: [{ options: { response: "keep" } }] }]; + const result = applyNumberFormulasToPages(pages); + expect(result).not.toBe(pages); + expect(result[0]).not.toBe(pages[0]); + expect(result[0].pos[0]).not.toBe(pages[0].pos[0]); + expect(result[0].pos[0].options).not.toBe(pages[0].pos[0].options); + }); + + it("preserves the widget options", () => { + const pages = [{ pos: [{ options: { response: "keep" } }] }]; + expect(applyNumberFormulasToPages(pages)[0].pos[0].options.response).toBe("keep"); + }); + + it("returns empty and non-array input untouched", () => { + expect(applyNumberFormulasToPages([])).toEqual([]); + expect(applyNumberFormulasToPages(null)).toBe(null); + }); +}); diff --git a/apps/OpenSign/tailwind.config.js b/apps/OpenSign/tailwind.config.js index 714fb31713..608200d4e8 100644 --- a/apps/OpenSign/tailwind.config.js +++ b/apps/OpenSign/tailwind.config.js @@ -2,7 +2,12 @@ module.exports = { content: ["./src/**/*.{js,jsx,ts,tsx}"], theme: { - extend: {} + extend: { + fontFamily: { + ui: ["Arial", "sans-serif"], + signature: ["Fasthand", "cursive"], + } + } }, plugins: [ require("daisyui"), diff --git a/apps/OpenSign/tests/e2e/README.md b/apps/OpenSign/tests/e2e/README.md new file mode 100644 index 0000000000..f015724d1e --- /dev/null +++ b/apps/OpenSign/tests/e2e/README.md @@ -0,0 +1,56 @@ +# Browser tests (Playwright) + +These tests drive the real client against an isolated stack: client, +server and a Mongo that holds test data. **Never point them at a deployed +environment.** They use the master key of that stack to create documents, +and they change the admin password. + +## Variables + +All are required. The suite fails fast when one is missing. + +- `E2E_BASE_URL`: client URL, for example `http://127.0.0.1:3105`. +- `E2E_SERVER_URL`: Parse server URL including the mount path. +- `E2E_APP_ID`: Parse application id. +- `E2E_MASTER_KEY`: master key of the isolated server. +- `E2E_ADMIN_EMAIL`: admin account that exists in the test data. +- `E2E_ADMIN_PASSWORD`: password the tests set for that account. It must + satisfy the password policy. +- `E2E_BASE_DOC_ID`: id of an unsigned document with one signer. New + documents are cloned from it. +- `E2E_SIGNER_EMAIL`: email of that signer. It must belong to an existing + user, which the OTP login needs. + +Optional: + +- `E2E_CHROME_PATH` uses an installed Chrome instead of the Playwright one. +- `E2E_MAIL_LOG` is the log file of an SMTP sink that receives the stack's + mail. The OTP tests read the code from it and are skipped without it. + +## Run + +```sh +cd apps/OpenSign +npx playwright test -c playwright.e2e.config.js +``` + +## What is covered + +- Guest signer completion with a digitally signed PDF. +- Text, signature (draw and type), initials, image, stamp, radio, + checkbox, dropdown, date and cells widgets. +- Linked fields and next-field navigation, including the last field. +- The radio value drawn in the signed PDF. +- Decline with a reason, the owner dashboard, the template editor and the + sidebar reports (templates, documents by status, contactbook). +- The prefill modal: fill, pick a recipient, create the document. +- A 30-page template: leaving the editor, and DOM activity while idle. +- The password-reset copy indicator. +- The OTP login from the emailed link: request the code, verify it, wrong + code and resend. +- The login page loads without the PDF editor bundle (react-datepicker + code and the PDF worker only load on PDF pages, production build). + +## Not covered yet + +- QES. diff --git a/apps/OpenSign/tests/e2e/bundle.pw.js b/apps/OpenSign/tests/e2e/bundle.pw.js new file mode 100644 index 0000000000..c12074a3e2 --- /dev/null +++ b/apps/OpenSign/tests/e2e/bundle.pw.js @@ -0,0 +1,122 @@ +import { test, expect } from "./support/fixtures.js"; +import { createSignerDocument } from "./support/parse.js"; +import { openSigner } from "./support/signer.js"; +import { dateWidget } from "./support/widgets.js"; + +/** + * Chunk file names are hashed, so the bundle split is checked by grepping + * the loaded JS bodies for the react-datepicker marker (the package.json + * version string also mentions the library name, so the bare name would + * match everywhere) and the pdf-lib PDFDocument marker. Only JS bodies + * are grepped: the project theme (index.css) holds a few datepicker + * overrides by design. Network requests are watched too, so any + * separately fetched DatePicker file or PDF worker fails the login test. + */ +const watchBundles = (page, state) => { + page.on("response", async (response) => { + try { + const path = response.url().split("?")[0]; + if (/\.m?js$/.test(path)) { + // Redirects are followed by the browser (for example the + // http->https hop of the CDN worker under an http preview), + // so only 4xx/5xx responses count as failed chunks. + if (response.status() >= 400) { + state.failedChunks.push(`${response.status()} ${response.url()}`); + } else { + state.bodies.push(await response.text()); + } + } + } catch (e) { + // Ignore aborted or redirected bodies. + } + }); + page.on("request", (request) => { + if (/pdf\.worker/i.test(request.url())) { + state.workerRequests.push(request.url()); + } + if (/datepicker/i.test(request.url())) { + state.datepickerRequests.push(request.url()); + } + }); + page.on("console", (message) => { + // "Failed to load resource" echoes a network failure the response + // watcher already records; the app also requests optional resources + // (the fixture ignores their 404s too). + if ( + message.type() === "error" && + !/ResizeObserver loop/.test(message.text()) && + !/^Failed to load resource/.test(message.text()) + ) { + state.consoleErrors.push(message.text()); + } + }); +}; + +const bundleState = () => ({ + bodies: [], + workerRequests: [], + datepickerRequests: [], + failedChunks: [], + consoleErrors: [] +}); + +const expectCleanLoad = (state, where) => { + expect(state.failedChunks, `a JS chunk fails to load on ${where}`).toEqual( + [] + ); + expect(state.consoleErrors, `console errors on ${where}`).toEqual([]); +}; + +const bundleText = (state) => state.bodies.join("\n"); + +test("the login page loads without the PDF editor bundle (#55)", async ({ + page +}) => { + const state = bundleState(); + watchBundles(page, state); + await page.goto("/"); + await expect( + page.locator("input[type=email], input[name=email], input#email").first() + ).toBeVisible(); + await page.waitForLoadState("networkidle"); + expect( + bundleText(state), + "login bundle contains react-datepicker code" + ).not.toContain("react-datepicker__"); + expect(bundleText(state), "login bundle contains pdf-lib code").not.toContain( + "PDFDocument" + ); + expect(state.workerRequests, "login page requests the PDF worker").toEqual( + [] + ); + expect( + state.datepickerRequests, + "login page requests a DatePicker file" + ).toEqual([]); + expectCleanLoad(state, "the login page"); +}); + +test("the signer page loads the PDF bundle on demand (#55)", async ({ + page +}) => { + const ids = await createSignerDocument({ + name: "e2e bundle", + pages: [{ pageNumber: 1, pos: [dateWidget("when", 700)] }] + }); + const state = bundleState(); + watchBundles(page, state); + await openSigner(page, ids); + const input = page.locator(".react-datepicker-wrapper input").first(); + await input.scrollIntoViewIfNeeded(); + await input.click(); + await expect(page.locator(".react-datepicker").first()).toBeVisible(); + await page.waitForLoadState("networkidle"); + expect( + bundleText(state), + "signer page never loads react-datepicker code" + ).toContain("react-datepicker__"); + expect(bundleText(state), "signer page never loads pdf-lib code").toContain( + "PDFDocument" + ); + expectCleanLoad(state, "the signer page"); +}); diff --git a/apps/OpenSign/tests/e2e/editor.pw.js b/apps/OpenSign/tests/e2e/editor.pw.js new file mode 100644 index 0000000000..7edc2b548b --- /dev/null +++ b/apps/OpenSign/tests/e2e/editor.pw.js @@ -0,0 +1,44 @@ +import { test, expect } from "./support/fixtures.js"; +import { createLargeTemplate } from "./support/bigpdf.js"; +import { loginAsAdmin } from "./support/login.js"; +import { prepareAdminUser, parseRequest } from "./support/parse.js"; + +const LARGE_PAGES = 30; +const LEAVE_BUDGET_MS = 5000; +const IDLE_MUTATION_BUDGET = 60; + +test.beforeAll(prepareAdminUser); + +/** Count DOM mutations for a period while the page is idle. */ +const countIdleMutations = (page, ms) => + page.evaluate( + (duration) => + new Promise((resolve) => { + let count = 0; + const observer = new MutationObserver((list) => { count += list.length; }); + observer.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true }); + setTimeout(() => { observer.disconnect(); resolve(count); }, duration); + }), + ms + ); + +test("the template editor stays quiet while idle (#59)", async ({ page }) => { + await loginAsAdmin(page); + const { results } = await parseRequest("classes/contracts_Template?limit=1"); + await page.goto(`/template/${results[0].objectId}`); + await expect(page.locator("canvas").first()).toBeVisible(); + await page.waitForTimeout(2000); + expect(await countIdleMutations(page, 3000)).toBeLessThan(IDLE_MUTATION_BUDGET); +}); + +test("leaving a 30-page template navigates without freezing (#59)", async ({ page }) => { + const templateId = await createLargeTemplate(LARGE_PAGES); + await loginAsAdmin(page); + await page.goto(`/template/${templateId}`); + await expect(page.locator("canvas").first()).toBeVisible({ timeout: 60_000 }); + await expect(page.getByText(`of ${LARGE_PAGES}`).first()).toBeVisible({ timeout: 60_000 }); + const started = Date.now(); + await page.getByRole("button", { name: "Back", exact: true }).click(); + await page.waitForURL((url) => !url.pathname.includes("/template/"), { timeout: LEAVE_BUDGET_MS }); + expect(Date.now() - started).toBeLessThan(LEAVE_BUDGET_MS); +}); diff --git a/apps/OpenSign/tests/e2e/navigation.pw.js b/apps/OpenSign/tests/e2e/navigation.pw.js new file mode 100644 index 0000000000..3c2fdb699b --- /dev/null +++ b/apps/OpenSign/tests/e2e/navigation.pw.js @@ -0,0 +1,66 @@ +import { test, expect } from "./support/fixtures.js"; +import { createSignerDocument, prepareAdminUser } from "./support/parse.js"; +import { drawStroke, openSigner } from "./support/signer.js"; +import { dateWidget, signature, textInput } from "./support/widgets.js"; + +test.beforeAll(prepareAdminUser); + +test("linked text fields share the value typed in one of them (#59)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e linked", + pages: [{ pageNumber: 1, pos: [textInput("full-name", 165), textInput("full-name", 400)] }] + }); + await openSigner(page, ids); + const fields = page.locator("textarea[placeholder=full-name]"); + await expect(fields).toHaveCount(2); + await fields.nth(0).fill("Ana Prueba"); + await fields.nth(0).blur(); + await expect(fields.nth(1)).toHaveValue("Ana Prueba"); +}); + +test("Next Field skips fields that already have a value (#67)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e next", + pages: [ + { + pageNumber: 1, + pos: [ + signature("first-signature", 120), + textInput("prefilled", 300, { defaultValue: "already set" }), + signature("second-signature", 500) + ] + } + ] + }); + await openSigner(page, ids); + await page.getByText("first-signature").first().click(); + await expect(page.getByText("first-signature").last()).toBeVisible(); + await drawStroke(page); + await page.getByText("Next Field").click(); + await expect(page.locator(".op-modal-box, [role=dialog]").getByText("second-signature")).toBeVisible(); +}); + +test("the date picker opens next to its field (#67)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e date", + pages: [{ pageNumber: 1, pos: [dateWidget("when", 700)] }] + }); + await openSigner(page, ids); + const input = page.locator(".react-datepicker-wrapper input").first(); + await input.scrollIntoViewIfNeeded(); + await input.click(); + const calendar = page.locator(".react-datepicker").first(); + await expect(calendar).toBeVisible(); + const box = await calendar.boundingBox(); + const field = await input.boundingBox(); + const viewport = page.viewportSize(); + expect(box.x).toBeGreaterThanOrEqual(0); + expect(box.y).toBeGreaterThanOrEqual(0); + expect(box.x + box.width).toBeLessThanOrEqual(viewport.width); + expect(box.y + box.height).toBeLessThanOrEqual(viewport.height); + // Anchored: the calendar touches the field above or below it. + const gap = Math.min(Math.abs(box.y - (field.y + field.height)), Math.abs(field.y - (box.y + box.height))); + expect(gap).toBeLessThan(40); + await page.locator(".react-datepicker__day:not(.react-datepicker__day--outside-month)").nth(9).click(); + await expect(input).not.toHaveValue(""); +}); diff --git a/apps/OpenSign/tests/e2e/otp.pw.js b/apps/OpenSign/tests/e2e/otp.pw.js new file mode 100644 index 0000000000..12eee2e0ef --- /dev/null +++ b/apps/OpenSign/tests/e2e/otp.pw.js @@ -0,0 +1,71 @@ +import { test, expect } from "./support/fixtures.js"; +import { mailLogSize, waitForOtp } from "./support/mail.js"; +import { createSignerDocument, prepareAdminUser } from "./support/parse.js"; +import { textInput } from "./support/widgets.js"; + +const MAIL_LOG = process.env.E2E_MAIL_LOG; +const OTP_PLACEHOLDER = "Enter verification code received over email"; + +test.beforeAll(prepareAdminUser); + +/** Seed an OTP document and open the link the signer gets by email. */ +const openOtpLink = async (page, name) => { + const ids = await createSignerDocument({ + name, + otp: true, + pages: [{ pageNumber: 1, pos: [textInput("nombres", 165)] }] + }); + const link = encodeURIComponent(btoa(`${ids.docId}/${process.env.E2E_SIGNER_EMAIL}/${ids.contactId}/true`)); + await page.goto(`/login/${link}`); + await expect(page.getByRole("button", { name: "Get verification code" })).toBeVisible(); + return ids; +}; + +test("a signer verifies the emailed code and then edits the document", async ({ page }) => { + test.skip(!MAIL_LOG, "E2E_MAIL_LOG is not set: no SMTP sink to read the code from"); + await openOtpLink(page, "e2e otp"); + const offset = mailLogSize(MAIL_LOG); + await page.getByRole("button", { name: "Get verification code" }).click(); + const code = await waitForOtp(MAIL_LOG, offset); + await page.getByPlaceholder(OTP_PLACEHOLDER).fill(code); + await page.getByRole("button", { name: "Verify", exact: true }).click(); + await page.getByText("I confirm & agree to continue").click(); + const field = page.locator("textarea[placeholder=nombres]"); + await field.fill("Ana"); + await expect(field).toHaveValue("Ana"); +}); + +test("a wrong code is rejected and the document stays locked", async ({ page }) => { + test.skip(!MAIL_LOG, "E2E_MAIL_LOG is not set: no SMTP sink to read the code from"); + await openOtpLink(page, "e2e otp wrong"); + const dialogs = []; + page.on("dialog", async (dialog) => { + dialogs.push(dialog.message()); + await dialog.dismiss(); + }); + const offset = mailLogSize(MAIL_LOG); + await page.getByRole("button", { name: "Get verification code" }).click(); + const real = await waitForOtp(MAIL_LOG, offset); + // The field accepts exactly 4 digits; send a different 4-digit code. + const wrong = String((Number(real) + 1) % 10000).padStart(4, "0"); + await page.getByPlaceholder(OTP_PLACEHOLDER).fill(wrong); + await page.getByRole("button", { name: "Verify", exact: true }).click(); + await expect.poll(() => dialogs.length, { timeout: 15_000 }).toBeGreaterThan(0); + expect(dialogs[0]).toMatch(/invalid/i); + await expect(page.getByText("I confirm & agree to continue")).toHaveCount(0); + await expect(page).toHaveURL(/\/login\//); +}); + +test("the resend button sends a new code by email", async ({ page }) => { + test.skip(!MAIL_LOG, "E2E_MAIL_LOG is not set: no SMTP sink to read the code from"); + await openOtpLink(page, "e2e otp resend"); + await page.getByRole("button", { name: "Get verification code" }).click(); + await expect(page.getByPlaceholder(OTP_PLACEHOLDER)).toBeVisible(); + const offset = mailLogSize(MAIL_LOG); + await page.getByRole("button", { name: "Resend" }).click(); + const code = await waitForOtp(MAIL_LOG, offset); + await page.getByPlaceholder(OTP_PLACEHOLDER).fill(code); + await page.getByRole("button", { name: "Verify", exact: true }).click(); + await page.getByText("I confirm & agree to continue").click(); + await expect(page.locator("textarea[placeholder=nombres]")).toBeVisible(); +}); diff --git a/apps/OpenSign/tests/e2e/owner.pw.js b/apps/OpenSign/tests/e2e/owner.pw.js new file mode 100644 index 0000000000..0cfa96b15a --- /dev/null +++ b/apps/OpenSign/tests/e2e/owner.pw.js @@ -0,0 +1,35 @@ +import { test, expect } from "./support/fixtures.js"; +import { loginAsAdmin } from "./support/login.js"; +import { createSignerDocument, getDocument, prepareAdminUser } from "./support/parse.js"; +import { openSigner } from "./support/signer.js"; +import { textInput } from "./support/widgets.js"; + +test.beforeAll(prepareAdminUser); + +test("the owner opens the dashboard and the reports without page errors", async ({ page }) => { + await loginAsAdmin(page); + await expect(page.locator("body")).not.toContainText("Something went wrong"); +}); + +test("the template editor shows the PDF, the roles and the widget palette", async ({ page }) => { + await loginAsAdmin(page); + const { results } = await (await fetch(`${process.env.E2E_SERVER_URL}/classes/contracts_Template?limit=1`, { + headers: { "X-Parse-Application-Id": process.env.E2E_APP_ID, "X-Parse-Master-Key": process.env.E2E_MASTER_KEY } + })).json(); + await page.goto(`/template/${results[0].objectId}`); + await expect(page.locator("canvas").first()).toBeVisible(); + for (const type of ["signature", "text input", "radio button", "cells", "date"]) { + await expect(page.getByRole("button", { name: type, exact: true }).first()).toBeVisible(); + } + await expect(page.getByText("Add role")).toBeVisible(); +}); + +test("a signer can decline a document with a reason", async ({ page }) => { + const ids = await createSignerDocument({ name: "e2e decline", pages: [{ pageNumber: 1, pos: [textInput("nombres", 165)] }] }); + await openSigner(page, ids); + await page.getByRole("button", { name: "Decline", exact: true }).click(); + await page.locator("textarea.op-textarea").fill("e2e reason"); + await page.getByRole("button", { name: "Yes", exact: true }).click(); + await expect.poll(async () => (await getDocument(ids.docId)).IsDeclined, { timeout: 20_000 }).toBe(true); + expect((await getDocument(ids.docId)).DeclineReason).toBe("e2e reason"); +}); diff --git a/apps/OpenSign/tests/e2e/prefill.pw.js b/apps/OpenSign/tests/e2e/prefill.pw.js new file mode 100644 index 0000000000..eb698a541a --- /dev/null +++ b/apps/OpenSign/tests/e2e/prefill.pw.js @@ -0,0 +1,59 @@ +import { test, expect } from "./support/fixtures.js"; +import { loginAsAdmin } from "./support/login.js"; +import { createPrefillTemplate, parseRequest, prepareAdminUser } from "./support/parse.js"; +import { prefillText } from "./support/widgets.js"; + +const PREFILL_VALUE = "ACME Corp"; + +test.beforeAll(prepareAdminUser); + +/** Newest document with the given name. */ +const findDocumentByName = async (name) => { + const where = encodeURIComponent(JSON.stringify({ Name: name })); + const { results } = await parseRequest(`classes/contracts_Document?where=${where}&order=-createdAt&limit=1`); + return results[0]; +}; + +test("the owner fills the prefill widget, picks a recipient and creates the document", async ({ page }) => { + const name = `e2e prefill ${Date.now()}`; + const templateId = await createPrefillTemplate({ name, prefillWidgets: [prefillText("company-name", 300)] }); + await loginAsAdmin(page); + await page.goto(`/template/${templateId}`); + await expect(page.locator("canvas").first()).toBeVisible(); + await page.getByRole("button", { name: "Next", exact: true }).click(); + await page.getByRole("button", { name: "Use Template" }).click(); + + const modal = page.locator(".op-modal-box").last(); + await expect(modal.getByText("company-name")).toBeVisible(); + const field = modal.locator("input.op-input").first(); + await field.click(); + await page.keyboard.type(PREFILL_VALUE, { delay: 40 }); + await expect(field).toHaveValue(PREFILL_VALUE); + + const recipient = modal.getByRole("combobox").last(); + await recipient.click(); + await recipient.fill("juan"); + await page.getByRole("option").first().click(); + await modal.getByRole("button", { name: "Next", exact: true }).click(); + + await expect.poll(async () => (await findDocumentByName(name))?.objectId, { timeout: 30_000 }).toBeTruthy(); + const doc = await findDocumentByName(name); + const widgets = doc.Placeholders.flatMap((role) => role.placeHolder.flatMap((p) => p.pos)); + const prefilled = widgets.find((w) => w.options?.name === "company-name"); + expect(prefilled.options.response).toBe(PREFILL_VALUE); +}); + +test("a prefill widget that already has a value is shown with it (#83)", async ({ page }) => { + const templateId = await createPrefillTemplate({ + name: `e2e prefill shown ${Date.now()}`, + prefillWidgets: [prefillText("company-name", 300, { response: "Saved Inc" })] + }); + await loginAsAdmin(page); + await page.goto(`/template/${templateId}`); + await expect(page.locator("canvas").first()).toBeVisible(); + await page.getByRole("button", { name: "Next", exact: true }).click(); + await page.getByRole("button", { name: "Use Template" }).click(); + const modal = page.locator(".op-modal-box").last(); + await expect(modal.getByText("company-name")).toBeVisible(); + await expect(modal.locator("input.op-input").first()).toHaveValue("Saved Inc"); +}); diff --git a/apps/OpenSign/tests/e2e/reports.pw.js b/apps/OpenSign/tests/e2e/reports.pw.js new file mode 100644 index 0000000000..b008851967 --- /dev/null +++ b/apps/OpenSign/tests/e2e/reports.pw.js @@ -0,0 +1,28 @@ +import { test, expect } from "./support/fixtures.js"; +import { loginAsAdmin } from "./support/login.js"; +import { prepareAdminUser } from "./support/parse.js"; + +/** Report pages reached from the sidebar: [group button or null, menu item]. */ +const REPORTS = [ + ["Templates", "Manage templates"], + ["Documents", "Need your sign"], + ["Documents", "In progress"], + ["Documents", "Completed"], + ["Documents", "Drafts"], + ["Documents", "Declined"], + ["Documents", "Expired"], + [null, "Contactbook"] +]; + +test.beforeAll(prepareAdminUser); + +for (const [group, item] of REPORTS) { + test(`the ${item} report opens without errors`, async ({ page }) => { + await loginAsAdmin(page); + if (group) await page.getByRole("button", { name: new RegExp(group) }).first().click(); + await page.getByRole("menuitem", { name: item, exact: true }).click(); + await page.waitForURL(/\/report\//); + await expect(page.locator("table, [role=table], [data-tut]").first()).toBeVisible(); + await expect(page.locator("body")).not.toContainText("Something went wrong"); + }); +} diff --git a/apps/OpenSign/tests/e2e/signature-tabs.pw.js b/apps/OpenSign/tests/e2e/signature-tabs.pw.js new file mode 100644 index 0000000000..f364de6f64 --- /dev/null +++ b/apps/OpenSign/tests/e2e/signature-tabs.pw.js @@ -0,0 +1,100 @@ +import path from "node:path"; +import { test, expect } from "./support/fixtures.js"; +import { createSignerDocument, prepareAdminUser, waitForCompleted } from "./support/parse.js"; +import { confirmField, drawStroke, finish, openSigner } from "./support/signer.js"; +import { cells, image, initials, signature, stamp } from "./support/widgets.js"; + +test.beforeAll(prepareAdminUser); + +const modal = (page) => page.locator(".op-modal-box, [role=dialog]").last(); + +test("a typed signature is accepted and the document completes", async ({ page }) => { + const ids = await createSignerDocument({ name: "e2e typed", pages: [{ pageNumber: 1, pos: [signature("signature-1", 120)] }] }); + await openSigner(page, ids); + await page.getByText("signature-1").first().click(); + await modal(page).getByText("Type", { exact: true }).click(); + await modal(page).locator("input.op-input[type=text]").fill("Ana Prueba"); + await confirmField(page); + await finish(page); + expect((await waitForCompleted(ids.docId)).IsCompleted).toBe(true); +}); + +test("initials are drawn and the document completes", async ({ page }) => { + const ids = await createSignerDocument({ name: "e2e initials", pages: [{ pageNumber: 1, pos: [initials("initials-1", 300)] }] }); + await openSigner(page, ids); + await page.getByText("initials-1").first().click(); + await expect(modal(page).getByText("Draw", { exact: true })).toBeVisible(); + await drawStroke(page); + await confirmField(page); + await finish(page); + expect((await waitForCompleted(ids.docId)).IsCompleted).toBe(true); +}); + +test("an uploaded image is accepted and the document completes", async ({ page }) => { + const ids = await createSignerDocument({ name: "e2e image", pages: [{ pageNumber: 1, pos: [image("image-1", 300)] }] }); + await openSigner(page, ids); + await page.getByText("image-1").first().click(); + await modal(page).locator("input[type=file]").setInputFiles(path.resolve("tests/e2e/support/red.png")); + await expect(modal(page).locator("img").first()).toBeVisible(); + await confirmField(page); + await finish(page); + expect((await waitForCompleted(ids.docId)).IsCompleted).toBe(true); +}); + +test("cells are typed in place, one character per cell (#80)", async ({ page }) => { + const ids = await createSignerDocument({ name: "e2e cells", pages: [{ pageNumber: 1, pos: [cells("code", 300)] }] }); + await openSigner(page, ids); + const boxes = page.locator("input[maxlength='1']"); + await expect(boxes).toHaveCount(5); + await boxes.nth(0).click(); + await page.keyboard.type("AB12"); + await expect(boxes.nth(0)).toHaveValue("A"); + await expect(boxes.nth(1)).toHaveValue("B"); + await expect(boxes.nth(3)).toHaveValue("2"); + await expect(page.locator(".op-modal-box")).toHaveCount(0); +}); + +test("a document with required cells completes after typing them (#80)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e cells complete", + pages: [{ pageNumber: 1, pos: [cells("code", 300), signature("signature-1", 120)] }] + }); + await openSigner(page, ids); + await page.locator("input[maxlength='1']").first().click(); + await page.keyboard.type("XY789"); + await page.getByText("signature-1").first().click(); + await drawStroke(page); + await confirmField(page); + await finish(page); + expect((await waitForCompleted(ids.docId)).IsCompleted).toBe(true); +}); + +test("a stamp is uploaded as an image and the document completes", async ({ page }) => { + const ids = await createSignerDocument({ name: "e2e stamp", pages: [{ pageNumber: 1, pos: [stamp("stamp-1", 300)] }] }); + await openSigner(page, ids); + await page.getByText("stamp-1").first().click(); + await modal(page).locator("input[type=file]").setInputFiles(path.resolve("tests/e2e/support/red.png")); + await expect(modal(page).locator("img").first()).toBeVisible(); + await confirmField(page); + await finish(page); + expect((await waitForCompleted(ids.docId)).IsCompleted).toBe(true); +}); + +test("confirming the last field closes the modal and the document completes (#67)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e save path", + pages: [{ pageNumber: 1, pos: [signature("first-signature", 120), signature("second-signature", 400)] }] + }); + await openSigner(page, ids); + await page.getByText("first-signature").first().click(); + await drawStroke(page); + await expect(page.getByRole("button", { name: /Next Field/ })).toBeVisible(); + await confirmField(page); + await expect(modal(page).getByText("second-signature")).toBeVisible(); + await drawStroke(page); + await expect(modal(page).getByText("1 of 2 fields left")).toBeVisible(); + await confirmField(page); + await expect(page.locator(".op-modal-box")).toHaveCount(0); + await finish(page); + expect((await waitForCompleted(ids.docId)).IsCompleted).toBe(true); +}); diff --git a/apps/OpenSign/tests/e2e/signed-pdf.pw.js b/apps/OpenSign/tests/e2e/signed-pdf.pw.js new file mode 100644 index 0000000000..fca9b93fcf --- /dev/null +++ b/apps/OpenSign/tests/e2e/signed-pdf.pw.js @@ -0,0 +1,48 @@ +import { test, expect } from "./support/fixtures.js"; +import { createSignerDocument, prepareAdminUser, waitForCompleted } from "./support/parse.js"; +import { hasDigitalSignature, readPdfBytes } from "./support/pdf.js"; +import { measureRadioMarks } from "./support/render.js"; +import { drawStroke, finish, openSigner } from "./support/signer.js"; +import { radio, signature } from "./support/widgets.js"; + +test.beforeAll(prepareAdminUser); + +/** Complete a document that has one radio group and one signature. */ +const completeWithRadio = async (page, name, radioWidget, choose) => { + const ids = await createSignerDocument({ + name, + pages: [{ pageNumber: 1, pos: [radioWidget, signature("signature-1", 120)] }] + }); + await openSigner(page, ids); + if (choose !== undefined) { + // The inline radio settles a tick after the click, so assert with a retry. + await page.locator("input[type=radio]").nth(choose).click(); + await expect(page.locator("input[type=radio]").nth(choose)).toBeChecked(); + } + await page.getByText("signature-1").first().click(); + await drawStroke(page); + await page.getByText("Next Field").click(); + await finish(page); + return waitForCompleted(ids.docId); +}; + +/** Index of the filled circle; fails when no circle or several circles are filled. */ +const filledIndex = (marks) => { + expect(marks.every((m) => m !== null), `labels found: ${JSON.stringify(marks)}`).toBe(true); + const filled = marks.map((m, i) => (m > 0.3 ? i : -1)).filter((i) => i >= 0); + expect(filled.length, `dark share per circle: ${JSON.stringify(marks)}`).toBeLessThanOrEqual(1); + return filled.length ? filled[0] : -1; +}; + +test("the radio chosen by the signer is drawn as selected in the signed PDF (#66)", async ({ page, browser }) => { + const doc = await completeWithRadio(page, "e2e radio pdf", radio("plan", ["Basic", "Pro", "Max"], 300), 1); + expect(await hasDigitalSignature(doc.SignedUrl)).toBe(true); + const marks = await measureRadioMarks(browser, await readPdfBytes(doc.SignedUrl), ["Basic", "Pro", "Max"]); + expect(filledIndex(marks)).toBe(1); +}); + +test("a stale radio default does not block completion (#66)", async ({ page }) => { + const stale = radio("plan", ["Basic", "Pro"], 300, { status: "optional", defaultValue: "Removed option" }); + const doc = await completeWithRadio(page, "e2e radio stale", stale, undefined); + expect(doc.IsCompleted).toBe(true); +}); diff --git a/apps/OpenSign/tests/e2e/signer-completion.pw.js b/apps/OpenSign/tests/e2e/signer-completion.pw.js new file mode 100644 index 0000000000..4431357c40 --- /dev/null +++ b/apps/OpenSign/tests/e2e/signer-completion.pw.js @@ -0,0 +1,24 @@ +import { test, expect } from "./support/fixtures.js"; +import { createSignerDocument, prepareAdminUser, waitForCompleted } from "./support/parse.js"; +import { drawStroke, finish, openSigner } from "./support/signer.js"; +import { signature, textInput } from "./support/widgets.js"; + +test.beforeAll(prepareAdminUser); + +test("guest signer fills text, draws a signature and completes the document", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e completion", + pages: [{ pageNumber: 1, pos: [textInput("nombres", 165), textInput("apellidos", 185), signature("signature-1", 120)] }] + }); + await openSigner(page, ids); + await page.locator("textarea[placeholder=nombres]").fill("Ana"); + await page.locator("textarea[placeholder=apellidos]").fill("Prueba"); + await page.getByText("signature-1").first().click(); + await expect(page.getByText("Draw", { exact: true })).toBeVisible(); + await drawStroke(page); + await page.getByText("Next Field").click(); + await finish(page); + const doc = await waitForCompleted(ids.docId); + expect(doc.IsCompleted).toBe(true); + expect(doc.AuditTrail.at(-1).Activity).toBe("Signed"); +}); diff --git a/apps/OpenSign/tests/e2e/support/bigpdf.js b/apps/OpenSign/tests/e2e/support/bigpdf.js new file mode 100644 index 0000000000..4834a0756c --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/bigpdf.js @@ -0,0 +1,45 @@ +import { PDFDocument } from "pdf-lib"; +import { readEnv } from "./env.js"; +import { parseRequest } from "./parse.js"; + +/** + * Build a PDF with a given number of pages. + * @param {number} pages Page count. + * @returns {Promise<Uint8Array>} PDF bytes. + */ +const buildPdf = async (pages) => { + const pdf = await PDFDocument.create(); + for (let i = 1; i <= pages; i += 1) { + pdf.addPage([612, 792]).drawText(`Page ${i}`, { x: 60, y: 700, size: 24 }); + } + return pdf.save(); +}; + +/** + * Create a template that points to a freshly uploaded PDF with many pages. + * The widgets of the first template are reused. + * @param {number} pages Page count. + * @returns {Promise<string>} Template object id. + */ +export const createLargeTemplate = async (pages) => { + const env = readEnv(); + const name = `e2e-large-${Date.now()}.pdf`; + const upload = await fetch(`${env.E2E_SERVER_URL}/files/${name}`, { + method: "POST", + headers: { + "Content-Type": "application/pdf", + "X-Parse-Application-Id": env.E2E_APP_ID, + "X-Parse-Master-Key": env.E2E_MASTER_KEY + }, + body: await buildPdf(pages) + }); + if (!upload.ok) throw new Error(`PDF upload failed: ${upload.status}`); + const { url } = await upload.json(); + const { results } = await parseRequest("classes/contracts_Template?limit=1"); + const { objectId, createdAt, updatedAt, className, ...base } = results[0]; + const created = await parseRequest("classes/contracts_Template", { + method: "POST", + body: { ...base, Name: `e2e large ${pages} pages`, URL: url } + }); + return created.objectId; +}; diff --git a/apps/OpenSign/tests/e2e/support/env.js b/apps/OpenSign/tests/e2e/support/env.js new file mode 100644 index 0000000000..5cc22a388e --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/env.js @@ -0,0 +1,24 @@ +/** Names of the variables the suite needs. */ +const REQUIRED = [ + "E2E_BASE_URL", + "E2E_SERVER_URL", + "E2E_APP_ID", + "E2E_MASTER_KEY", + "E2E_ADMIN_EMAIL", + "E2E_ADMIN_PASSWORD", + "E2E_BASE_DOC_ID", + "E2E_SIGNER_EMAIL" +]; + +/** + * Read the suite settings from the environment. + * @returns {Record<string, string>} Settings by variable name. + * @throws {Error} When a required variable is missing. + */ +export const readEnv = () => { + const missing = REQUIRED.filter((name) => !process.env[name]); + if (missing.length) { + throw new Error(`Missing environment variables for the E2E suite: ${missing.join(", ")}`); + } + return Object.fromEntries(REQUIRED.map((name) => [name, process.env[name]])); +}; diff --git a/apps/OpenSign/tests/e2e/support/fixtures.js b/apps/OpenSign/tests/e2e/support/fixtures.js new file mode 100644 index 0000000000..a83d381720 --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/fixtures.js @@ -0,0 +1,16 @@ +import { test as base, expect } from "@playwright/test"; + +/** + * Test fixture that fails a test when the page throws an uncaught error. + * Network 404s are ignored: the app requests optional resources. + */ +export const test = base.extend({ + page: async ({ page }, use) => { + const pageErrors = []; + page.on("pageerror", (error) => pageErrors.push(error.message)); + await use(page); + expect(pageErrors, "uncaught page errors").toEqual([]); + } +}); + +export { expect }; diff --git a/apps/OpenSign/tests/e2e/support/login.js b/apps/OpenSign/tests/e2e/support/login.js new file mode 100644 index 0000000000..2e7b5a8cb0 --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/login.js @@ -0,0 +1,23 @@ +import { readEnv } from "./env.js"; + +/** + * Log in through the login form. + * @param {import("@playwright/test").Page} page Browser page. + * @param {string} [email] Account email, the admin by default. + * @returns {Promise<void>} Resolves on the dashboard. + */ +export const login = async (page, email) => { + const env = readEnv(); + await page.goto("/"); + await page.locator("input[type=email], input[name=email], input#email").first().fill(email || env.E2E_ADMIN_EMAIL); + await page.locator("input[type=password]").fill(env.E2E_ADMIN_PASSWORD); + await page.keyboard.press("Enter"); + await page.waitForURL(/\/dashboard\//); +}; + +/** + * Log in as the admin user. + * @param {import("@playwright/test").Page} page Browser page. + * @returns {Promise<void>} Resolves on the dashboard. + */ +export const loginAsAdmin = (page) => login(page); diff --git a/apps/OpenSign/tests/e2e/support/mail.js b/apps/OpenSign/tests/e2e/support/mail.js new file mode 100644 index 0000000000..6a98eb511c --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/mail.js @@ -0,0 +1,38 @@ +import fs from "node:fs"; + +/** Pattern of the code inside the OTP email (after quoted-printable decoding). */ +const OTP_PATTERN = /verification is:<\/p><p[^>]*>(\d{4,8})</; + +/** + * Decode the quoted-printable subset the mailer uses. + * @param {string} text Raw message text. + * @returns {string} Decoded text. + */ +const decodeQuotedPrintable = (text) => + text.replace(/=\r?\n/g, "").replace(/=([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16))); + +/** + * Current size of the SMTP sink log, used as the offset for the next read. + * @param {string} logPath Path of the sink log (E2E_MAIL_LOG). + * @returns {number} Size in bytes. + */ +export const mailLogSize = (logPath) => (fs.existsSync(logPath) ? fs.statSync(logPath).size : 0); + +/** + * Wait for an OTP email in the sink log and return its code. + * @param {string} logPath Path of the sink log. + * @param {number} offset Log size before the OTP was requested. + * @param {number} [timeoutMs] Maximum wait. + * @returns {Promise<string>} The numeric code. + * @throws {Error} When no OTP email arrives in time. + */ +export const waitForOtp = async (logPath, offset, timeoutMs = 20_000) => { + const end = Date.now() + timeoutMs; + while (Date.now() < end) { + const text = fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf8").slice(offset) : ""; + const match = decodeQuotedPrintable(text).match(OTP_PATTERN); + if (match) return match[1]; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error("No OTP email received"); +}; diff --git a/apps/OpenSign/tests/e2e/support/parse.js b/apps/OpenSign/tests/e2e/support/parse.js new file mode 100644 index 0000000000..a63487a3ef --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/parse.js @@ -0,0 +1,140 @@ +import { readEnv } from "./env.js"; + +/** + * Call the Parse REST API of the isolated stack with the master key. + * @param {string} path Path under the server URL, for example "classes/_User". + * @param {{method?: string, body?: object}} [options] HTTP method and JSON body. + * @returns {Promise<any>} Parsed JSON response. + * @throws {Error} When the server answers with an error status. + */ +export const parseRequest = async (path, { method = "GET", body } = {}) => { + const env = readEnv(); + const response = await fetch(`${env.E2E_SERVER_URL}/${path}`, { + method, + headers: { + "Content-Type": "application/json", + "X-Parse-Application-Id": env.E2E_APP_ID, + "X-Parse-Master-Key": env.E2E_MASTER_KEY + }, + body: body ? JSON.stringify(body) : undefined + }); + const data = await response.json(); + if (!response.ok) throw new Error(`Parse ${method} ${path}: ${response.status} ${JSON.stringify(data)}`); + return data; +}; + +/** + * Give the admin user the password the tests log in with. + * @returns {Promise<void>} Resolves when the password is stored. + */ +export const prepareAdminUser = async () => { + const env = readEnv(); + const where = encodeURIComponent(JSON.stringify({ email: env.E2E_ADMIN_EMAIL })); + const { results } = await parseRequest(`classes/_User?where=${where}&limit=1`); + if (!results.length) throw new Error(`Admin user ${env.E2E_ADMIN_EMAIL} not found`); + await parseRequest(`users/${results[0].objectId}`, { + method: "PUT", + body: { password: env.E2E_ADMIN_PASSWORD } + }); +}; + +/** + * Read a document. + * @param {string} id Document object id. + * @returns {Promise<object>} The document. + */ +export const getDocument = (id) => parseRequest(`classes/contracts_Document/${id}`); + +/** + * Wait until a document is completed. + * @param {string} id Document object id. + * @param {number} [timeoutMs] Maximum wait. + * @returns {Promise<object>} The completed document. + * @throws {Error} When the document is not completed in time. + */ +export const waitForCompleted = async (id, timeoutMs = 30_000) => { + const end = Date.now() + timeoutMs; + while (Date.now() < end) { + const doc = await getDocument(id); + if (doc.IsCompleted) return doc; + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + throw new Error(`Document ${id} was not completed in ${timeoutMs} ms`); +}; + +/** + * Create a signer document by cloning the base document with new widgets. + * @param {{name: string, pages: Array<{pageNumber: number, pos: object[]}>, otp?: boolean}} spec + * Document name, widgets grouped by page and whether the signer must verify by OTP. + * @returns {Promise<{docId: string, contactId: string}>} Ids for the signer URL. + */ +export const createSignerDocument = async ({ name, pages, otp = false }) => { + const env = readEnv(); + const base = await getDocument(env.E2E_BASE_DOC_ID); + const { objectId, createdAt, updatedAt, className, ...clone } = base; + const role = base.Placeholders[0]; + const body = { + ...clone, + Name: name, + IsCompleted: false, + IsEnableOTP: otp, + SendinOrder: false, + Placeholders: [{ ...role, placeHolder: pages }] + }; + delete body.SignedUrl; + delete body.AuditTrail; + const created = await parseRequest("classes/contracts_Document", { method: "POST", body }); + return { docId: created.objectId, contactId: role.signerObjId }; +}; + +/** + * Create a second user in the admin's tenant so the admin can act on it. + * @param {string} email Email and username of the new user. + * @returns {Promise<string>} Object id of the new `contracts_Users` row. + */ +export const createTeammate = async (email) => { + const env = readEnv(); + const where = encodeURIComponent(JSON.stringify({ Email: env.E2E_ADMIN_EMAIL })); + const { results } = await parseRequest(`classes/contracts_Users?where=${where}&limit=1`); + const { objectId, createdAt, updatedAt, className, UserId, Email, Name, ...admin } = results[0]; + const existing = await parseRequest(`classes/_User?where=${encodeURIComponent(JSON.stringify({ email }))}&limit=1`); + const userId = existing.results.length + ? existing.results[0].objectId + : (await parseRequest("users", { method: "POST", body: { username: email, email, password: env.E2E_ADMIN_PASSWORD } })).objectId; + const rows = await parseRequest(`classes/contracts_Users?where=${encodeURIComponent(JSON.stringify({ Email: email }))}&limit=1`); + if (rows.results.length) return rows.results[0].objectId; + const created = await parseRequest("classes/contracts_Users", { + method: "POST", + body: { + ...admin, + Email: email, + Name: "E2E Teammate", + UserRole: "contracts_User", + UserId: { __type: "Pointer", className: "_User", objectId: userId } + } + }); + return created.objectId; +}; + +/** + * Create a template with a prefill role (widgets the owner fills) plus the signer role of the first template. + * @param {{name: string, prefillWidgets: object[]}} spec Template name and the owner's widgets. + * @returns {Promise<string>} Template object id. + */ +export const createPrefillTemplate = async ({ name, prefillWidgets }) => { + const { results } = await parseRequest("classes/contracts_Template?limit=1"); + const { objectId, createdAt, updatedAt, className, ...base } = results[0]; + const prefillRole = { + signerPtr: {}, + signerObjId: "", + blockColor: "#e0e0e0", + Role: "prefill", + Id: 990001, + placeHolder: [{ pageNumber: 1, pos: prefillWidgets }] + }; + const created = await parseRequest("classes/contracts_Template", { + method: "POST", + body: { ...base, Name: name, Placeholders: [prefillRole, ...base.Placeholders] } + }); + return created.objectId; +}; diff --git a/apps/OpenSign/tests/e2e/support/pdf.js b/apps/OpenSign/tests/e2e/support/pdf.js new file mode 100644 index 0000000000..1031d78c5a --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/pdf.js @@ -0,0 +1,21 @@ +/** + * Download a PDF. + * @param {string} url PDF URL (already carries its access token). + * @returns {Promise<Uint8Array>} PDF bytes. + * @throws {Error} When the download fails. + */ +export const readPdfBytes = async (url) => { + const response = await fetch(url); + if (!response.ok) throw new Error(`PDF download failed: ${response.status}`); + return new Uint8Array(await response.arrayBuffer()); +}; + +/** + * Whether a PDF carries a digital signature dictionary. + * @param {string} url PDF URL. + * @returns {Promise<boolean>} True when /Type /Sig and /ByteRange are present. + */ +export const hasDigitalSignature = async (url) => { + const text = Buffer.from(await readPdfBytes(url)).toString("latin1"); + return /\/Type\s*\/Sig/.test(text) && /\/ByteRange/.test(text); +}; diff --git a/apps/OpenSign/tests/e2e/support/red.png b/apps/OpenSign/tests/e2e/support/red.png new file mode 100644 index 0000000000..e847253717 Binary files /dev/null and b/apps/OpenSign/tests/e2e/support/red.png differ diff --git a/apps/OpenSign/tests/e2e/support/render.js b/apps/OpenSign/tests/e2e/support/render.js new file mode 100644 index 0000000000..f45ffee259 --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/render.js @@ -0,0 +1,79 @@ +import fs from "node:fs"; +import path from "node:path"; + +const PDFJS_DIR = path.resolve("node_modules/pdfjs-dist/build"); +const ORIGIN = "https://e2e-render.invalid"; + +/** Page that loads pdf.js as a module and exposes a render helper. */ +const HTML = `<!doctype html><html><body><canvas id="c"></canvas><script type="module"> +import * as pdfjs from "${ORIGIN}/pdf.min.mjs"; +pdfjs.GlobalWorkerOptions.workerSrc = "${ORIGIN}/pdf.worker.min.mjs"; +window.renderPage = async (scale) => { + const pdf = await pdfjs.getDocument("${ORIGIN}/doc.pdf").promise; + const page = await pdf.getPage(1); + const viewport = page.getViewport({ scale }); + const canvas = document.getElementById("c"); + canvas.width = viewport.width; canvas.height = viewport.height; + await page.render({ canvasContext: canvas.getContext("2d"), viewport }).promise; + return { width: viewport.width, height: viewport.height }; +}; +window.findText = async (labels, scale) => { + const pdf = await pdfjs.getDocument("${ORIGIN}/doc.pdf").promise; + const page = await pdf.getPage(1); + const viewport = page.getViewport({ scale }); + const { items } = await page.getTextContent(); + return labels.map((label) => { + const item = items.find((i) => i.str.trim() === label); + if (!item) return null; + const [x, y] = viewport.convertToViewportPoint(item.transform[4], item.transform[5]); + return { x, y, size: Math.hypot(item.transform[2], item.transform[3]) * scale }; + }); +}; +window.darkness = (x, y, w, h) => { + const data = document.getElementById("c").getContext("2d").getImageData(x, y, w, h).data; + let dark = 0; + for (let i = 0; i < data.length; i += 4) if (data[i] + data[i + 1] + data[i + 2] < 300) dark += 1; + return dark / (w * h); +}; +window.ready = true; +</script></body></html>`; + +/** + * Render page 1 of a PDF and measure how much of the radio circle left of each label is dark. + * The circle is drawn just left of its label (see pdfWidgetDrawing.js), so the label + * position found by pdf.js locates it without copying the layout math. + * @param {import("@playwright/test").Browser} browser Playwright browser. + * @param {Uint8Array} pdfBytes PDF content. + * @param {string[]} labels Radio option labels. + * @param {number} [scale] Render scale. + * @returns {Promise<Array<number|null>>} Share of dark pixels per circle, null if the label is absent. + */ +export const measureRadioMarks = async (browser, pdfBytes, labels, scale = 3) => { + const page = await browser.newPage(); + try { + await page.route(`${ORIGIN}/**`, (route) => { + const name = new URL(route.request().url()).pathname.slice(1); + if (name === "index.html") return route.fulfill({ contentType: "text/html", body: HTML }); + if (name === "doc.pdf") return route.fulfill({ contentType: "application/pdf", body: Buffer.from(pdfBytes) }); + return route.fulfill({ contentType: "text/javascript", body: fs.readFileSync(path.join(PDFJS_DIR, name)) }); + }); + await page.goto(`${ORIGIN}/index.html`); + await page.waitForFunction(() => window.ready === true); + await page.evaluate((s) => window.renderPage(s), scale); + const found = await page.evaluate(({ l, s }) => window.findText(l, s), { l: labels, s: scale }); + const marks = []; + for (const label of found) { + if (!label) { marks.push(null); continue; } + // The circle spans [x - (size + 3), x - 3] horizontally and sits on the baseline. + const inner = label.size * 0.4; + const cx = label.x - label.size * 0.5 - 3 * scale; + const cy = label.y - label.size * 0.35; + marks.push(await page.evaluate((b) => window.darkness(b.x, b.y, b.w, b.h), { + x: Math.round(cx - inner / 2), y: Math.round(cy - inner / 2), w: Math.round(inner), h: Math.round(inner) + })); + } + return marks; + } finally { + await page.close(); + } +}; diff --git a/apps/OpenSign/tests/e2e/support/signer.js b/apps/OpenSign/tests/e2e/support/signer.js new file mode 100644 index 0000000000..f8bd3a04dd --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/signer.js @@ -0,0 +1,46 @@ +/** + * Open the guest signer page and accept the electronic signature consent. + * @param {import("@playwright/test").Page} page Browser page. + * @param {{docId: string, contactId: string}} ids Document and signer ids. + * @returns {Promise<void>} Resolves when the document is ready to edit. + */ +export const openSigner = async (page, { docId, contactId }) => { + await page.goto(`/load/recipientSignPdf/${docId}/${contactId}`); + await page.getByText("I confirm & agree to continue").click(); + await page.locator("canvas").first().waitFor(); +}; + +/** + * Draw a stroke on the last canvas of the open signature modal. + * @param {import("@playwright/test").Page} page Browser page. + * @returns {Promise<void>} Resolves when the stroke is drawn. + */ +export const drawStroke = async (page) => { + const box = await page.locator("canvas").last().boundingBox(); + await page.mouse.move(box.x + 40, box.y + 60); + await page.mouse.down(); + for (let i = 0; i < 20; i += 1) { + await page.mouse.move(box.x + 40 + i * 12, box.y + 60 + Math.sin(i / 2) * 30); + } + await page.mouse.up(); +}; + +/** + * Press Finish and wait for the success page. + * @param {import("@playwright/test").Page} page Browser page. + * @returns {Promise<void>} Resolves on the success page. + */ +export const finish = async (page) => { + // After "Done" the modal shows its own Finish button; otherwise only the toolbar one exists. + await page.getByRole("button", { name: "Finish", exact: true }).last().click(); + await page.waitForURL(/\/success\?docid=/, { timeout: 60_000 }); +}; + +/** + * Confirm the open widget modal: "Next Field" when more fields remain, "Done" on the last one. + * @param {import("@playwright/test").Page} page Browser page. + * @returns {Promise<void>} Resolves after the click. + */ +export const confirmField = async (page) => { + await page.getByRole("button", { name: /Next Field|Done/ }).last().click(); +}; diff --git a/apps/OpenSign/tests/e2e/support/widgets.js b/apps/OpenSign/tests/e2e/support/widgets.js new file mode 100644 index 0000000000..312fc969fe --- /dev/null +++ b/apps/OpenSign/tests/e2e/support/widgets.js @@ -0,0 +1,143 @@ +let keyCounter = 1000; + +const SIZES = { + "text input": { Width: 150, Height: 19 }, + text: { Width: 150, Height: 19 }, + signature: { Width: 150, Height: 60 }, + initials: { Width: 50, Height: 50 }, + stamp: { Width: 150, Height: 60 }, + image: { Width: 70, Height: 70 }, + checkbox: { Width: 15, Height: 19 }, + "radio button": { Width: 5, Height: 10 }, + dropdown: { Width: 120, Height: 22 }, + date: { Width: 100, Height: 20 }, + cells: { Width: 112, Height: 22 } +}; + +/** + * Build one widget position as the editor stores it. + * @param {string} type Widget type, for example "text input" or "radio button". + * @param {{x: number, y: number, options: object}} spec Position and options. + * @returns {object} Widget position. + */ +export const widget = (type, { x, y, options }) => ({ + xPosition: x, + yPosition: y, + isStamp: false, + key: ++keyCounter, + scale: 1.64, + zIndex: keyCounter, + type, + options: { status: "required", ...options }, + ...SIZES[type] +}); + +/** + * Build a text input widget. + * @param {string} name Widget name, also its placeholder. + * @param {number} y Vertical position. + * @param {object} [extra] Extra options, for example a default value. + * @returns {object} Widget position. + */ +export const textInput = (name, y, extra = {}) => + widget("text input", { + x: 180, + y, + options: { name, isReadOnly: false, hint: "", defaultValue: "", validation: {}, fontSize: 12, fontColor: "black", ...extra } + }); + +/** + * Build a signature widget. + * @param {string} name Widget name. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const signature = (name, y) => widget("signature", { x: 430, y, options: { name } }); + +/** + * Build a radio button group. + * @param {string} name Widget name. + * @param {string[]} values Option labels. + * @param {number} y Vertical position. + * @param {object} [extra] Extra options, for example a default value. + * @returns {object} Widget position. + */ +export const radio = (name, values, y, extra = {}) => { + const w = widget("radio button", { x: 60, y, options: { name, values, isReadOnly: false, ...extra } }); + return { ...w, Width: 120, Height: 24 * values.length }; +}; + +/** + * Build a checkbox group. + * @param {string} name Widget name. + * @param {string[]} values Option labels. + * @param {number} y Vertical position. + * @param {object} [extra] Extra options. + * @returns {object} Widget position. + */ +export const checkbox = (name, values, y, extra = {}) => { + const w = widget("checkbox", { x: 300, y, options: { name, values, isReadOnly: false, isHideLabel: false, ...extra } }); + return { ...w, Width: 120, Height: 24 * values.length }; +}; + +/** + * Build a dropdown. + * @param {string} name Widget name. + * @param {string[]} values Option labels. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const dropdown = (name, values, y) => + widget("dropdown", { x: 440, y, options: { name, values, isReadOnly: false } }); + +/** + * Build a date widget. + * @param {string} name Widget name. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const dateWidget = (name, y) => + widget("date", { x: 440, y, options: { name, response: "", isReadOnly: false, validation: { format: "MM/dd/yyyy", type: "date-format" } } }); + +/** + * Build a cells (one character per cell) widget. + * @param {string} name Widget name. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const cells = (name, y) => + widget("cells", { x: 60, y, options: { name, cellCount: 5, defaultValue: "", validation: { type: "", pattern: "" }, isReadOnly: false } }); + +/** + * Build an initials widget. + * @param {string} name Widget name. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const initials = (name, y) => widget("initials", { x: 300, y, options: { name } }); + +/** + * Build an image widget. + * @param {string} name Widget name. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const image = (name, y) => widget("image", { x: 60, y, options: { name } }); + +/** + * Build a stamp widget. + * @param {string} name Widget name. + * @param {number} y Vertical position. + * @returns {object} Widget position. + */ +export const stamp = (name, y) => widget("stamp", { x: 300, y, options: { name } }); + +/** + * Build the plain text widget the owner fills in the prefill role. + * @param {string} name Widget name, shown as the label in the prefill modal. + * @param {number} y Vertical position. + * @param {object} [extra] Extra options, for example a saved response. + * @returns {object} Widget position. + */ +export const prefillText = (name, y, extra = {}) => + widget("text", { x: 180, y, options: { name, fontSize: 12, fontColor: "black", ...extra } }); diff --git a/apps/OpenSign/tests/e2e/users.pw.js b/apps/OpenSign/tests/e2e/users.pw.js new file mode 100644 index 0000000000..71db9acada --- /dev/null +++ b/apps/OpenSign/tests/e2e/users.pw.js @@ -0,0 +1,27 @@ +import { test, expect } from "./support/fixtures.js"; +import { loginAsAdmin } from "./support/login.js"; +import { createTeammate, prepareAdminUser } from "./support/parse.js"; + +const TEAMMATE = "e2e.teammate@example.test"; + +test.beforeAll(async () => { + await prepareAdminUser(); + await createTeammate(TEAMMATE); +}); + +test("the copied indicator stays visible before it resets (#73)", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await loginAsAdmin(page); + await page.goto("/users"); + const row = page.locator("tbody tr", { hasText: TEAMMATE }); + await row.locator("[role=button][title='Reset password']").click(); + await page.getByRole("button", { name: /auto/i }).first().click().catch(() => {}); + const password = page.getByPlaceholder(/password/i).first(); + await password.fill("E2e-Copy-1234!"); + const copy = page.getByRole("button", { name: "Copy password" }); + await copy.click(); + await expect(copy).toHaveAttribute("title", "Copied"); + await page.waitForTimeout(500); + await expect(copy).toHaveAttribute("title", "Copied"); + await expect(copy).toHaveAttribute("title", "Copy", { timeout: 5000 }); +}); diff --git a/apps/OpenSign/tests/e2e/widgets.pw.js b/apps/OpenSign/tests/e2e/widgets.pw.js new file mode 100644 index 0000000000..20fb3eb189 --- /dev/null +++ b/apps/OpenSign/tests/e2e/widgets.pw.js @@ -0,0 +1,79 @@ +import { test, expect } from "./support/fixtures.js"; +import { createSignerDocument, prepareAdminUser } from "./support/parse.js"; +import { openSigner } from "./support/signer.js"; +import { cells, checkbox, dateWidget, dropdown, radio } from "./support/widgets.js"; + +test.beforeAll(prepareAdminUser); + +/** Seed a document with one widget of each inline type and open it as the signer. */ +const openWidgetsDocument = async (page, name) => { + const ids = await createSignerDocument({ + name, + pages: [ + { + pageNumber: 1, + pos: [ + radio("colors", ["Red", "Green", "Blue"], 150), + checkbox("tags", ["One", "Two", "Three"], 150), + dropdown("size", ["Small", "Large"], 150), + dateWidget("when", 200), + cells("code", 260) + ] + } + ] + }); + await openSigner(page, ids); + return ids; +}; + +test("radio buttons select one option inline", async ({ page }) => { + await openWidgetsDocument(page, "e2e radio"); + const radios = page.locator("input[type=radio]"); + await expect(radios).toHaveCount(3); + // The inline radio persists through the signer state, so the checked + // state settles a tick after the click: use the retrying assertion. + await radios.nth(1).click(); + await expect(radios.nth(1)).toBeChecked(); + await radios.nth(2).click(); + await expect(radios.nth(2)).toBeChecked(); + await expect(radios.nth(1)).not.toBeChecked(); +}); + +test("checkboxes keep several options and can be unchecked", async ({ page }) => { + await openWidgetsDocument(page, "e2e checkbox"); + const boxes = page.locator("input.op-checkbox"); + await expect(boxes).toHaveCount(3); + await boxes.nth(0).check(); + await boxes.nth(2).check(); + await expect(boxes.nth(0)).toBeChecked(); + await expect(boxes.nth(2)).toBeChecked(); + await boxes.nth(0).uncheck(); + await expect(boxes.nth(0)).not.toBeChecked(); +}); + +test("dropdown selects an option inline", async ({ page }) => { + await openWidgetsDocument(page, "e2e dropdown"); + const select = page.locator("select").first(); + await select.selectOption("Large"); + await expect(select).toHaveValue("Large"); +}); + +test("radio default value with spaces is shown as selected (#65)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e radio default", + pages: [{ pageNumber: 1, pos: [radio("colors", ["Red", "Green"], 150, { defaultValue: " Green " })] }] + }); + await openSigner(page, ids); + const radios = page.locator("input[type=radio]"); + await expect(radios.nth(1)).toBeChecked(); + await expect(radios.nth(0)).not.toBeChecked(); +}); + +test("radio with an object default and no options does not crash (#65)", async ({ page }) => { + const ids = await createSignerDocument({ + name: "e2e radio object default", + pages: [{ pageNumber: 1, pos: [radio("colors", [{ name: "Red" }, { name: "Green" }], 150, { defaultValue: [{ name: "Red", checked: true }] })] }] + }); + await openSigner(page, ids); + await expect(page.locator("input[type=radio]").nth(0)).toBeChecked(); +}); diff --git a/apps/OpenSign/vite.config.js b/apps/OpenSign/vite.config.js index 4f35b76598..fa0f048017 100644 --- a/apps/OpenSign/vite.config.js +++ b/apps/OpenSign/vite.config.js @@ -1,21 +1,37 @@ import { defineConfig, loadEnv } from "vite"; import react from "@vitejs/plugin-react"; import svgr from "vite-plugin-svgr"; -import { resolve } from "path"; +import { resolve, dirname } from "path"; +import { fileURLToPath } from "url"; import { localQaApiPlugin } from "./qa/localQaApi.mjs"; +const __dirname = dirname(fileURLToPath(import.meta.url)); + // https://vitejs.dev/config/ export default defineConfig(({ mode, command }) => { // Load ALL env vars (no prefix filter) const env = loadEnv(mode, process.cwd(), ""); const localQaMode = mode === "local-qa" && command === "serve"; + // Normalize PUBLIC_URL into a base path for Vite + let basePath = "/"; + try { + const raw = env.PUBLIC_URL || process.env.PUBLIC_URL; + if (raw) { + const u = new URL(raw, "http://localhost"); + basePath = u.pathname.endsWith("/") ? u.pathname : u.pathname + "/"; + } + } catch (e) { + // ignore + } + return { plugins: [ react(), svgr(), // Transform SVGs into React components ...(localQaMode ? [localQaApiPlugin()] : []) ], + base: basePath, resolve: { alias: {} }, // Add any necessary aliases here define: { // Replace process.env.REACT_APP_* with import.meta.env.VITE_* diff --git a/apps/OpenSign/vitest.config.js b/apps/OpenSign/vitest.config.js new file mode 100644 index 0000000000..6db6e1c6d4 --- /dev/null +++ b/apps/OpenSign/vitest.config.js @@ -0,0 +1,12 @@ +import { defineConfig } from "vitest/config"; +import react from "@vitejs/plugin-react"; +import svgr from "vite-plugin-svgr"; + +export default defineConfig({ + plugins: [react(), svgr()], + test: { + environment: "jsdom", + globals: true, + exclude: ["**/tests/e2e/**", "**/node_modules/**"] + } +}); diff --git a/apps/OpenSignServer/.eslintrc.json b/apps/OpenSignServer/.eslintrc.json index c974f25888..bf316df89c 100644 --- a/apps/OpenSignServer/.eslintrc.json +++ b/apps/OpenSignServer/.eslintrc.json @@ -12,7 +12,7 @@ "parser": "@babel/eslint-parser", "rules": { "indent": ["error", 2, { "SwitchCase": 1 }], - "linebreak-style": ["error", "unix"], + "linebreak-style": "off", "no-trailing-spaces": "error", "eol-last": "error", "space-in-parens": ["error", "never"], diff --git a/apps/OpenSignServer/Utils.js b/apps/OpenSignServer/Utils.js index f43134b8b0..b26c135126 100644 --- a/apps/OpenSignServer/Utils.js +++ b/apps/OpenSignServer/Utils.js @@ -1,845 +1,32 @@ import dotenv from 'dotenv'; -import { format, toZonedTime } from 'date-fns-tz'; -import getPresignedUrl, { getSignedLocalUrl } from './cloud/parsefunction/getSignedUrl.js'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import { - PDFDocument, - PDFName, - rgb, - degrees, - // StandardFonts, - PDFArray, - PDFDict, -} from 'pdf-lib'; -import { parseUploadFile } from './utils/fileUtils.js'; -import { - escapeHtml, - renderAutomatedEmailFooter, - renderEmailHeading, - renderEmailLogo, - resolveBrandContext, - resolveDeploymentBrand, -} from './utils/brandContext.js'; dotenv.config({ quiet: true }); -export const cloudServerUrl = 'http://localhost:8080/app'; -export const serverAppId = process.env.APP_ID || 'opensign'; -export const appName = 'OpenSign™'; -export const prefillDraftDocWidget = ['date', 'textbox', 'checkbox', 'radio button', 'image']; -export const prefillDraftTemWidget = [ - 'date', - 'textbox', - 'checkbox', - 'radio button', - 'image', - 'dropdown', -]; -export const MAX_NAME_LENGTH = 250; -export const MAX_NOTE_LENGTH = 200; -export const MAX_DESCRIPTION_LENGTH = 500; -export const color = [ - '#93a3db', - '#e6c3db', - '#c0e3bc', - '#bce3db', - '#b8ccdb', - '#ceb8db', - '#ffccff', - '#99ffcc', - '#cc99ff', - '#ffcc99', - '#66ccff', - '#ffffcc', -]; - -export const prefillBlockColor = 'transparent'; -export const normalizeMailSubject = subject => - String(subject || '').replace(/opensign™/gi, 'opensign'); - -export function replaceMailVaribles(subject, body, variables) { - let replacedSubject = subject; - let replacedBody = body; - - for (const variable in variables) { - const regex = new RegExp(`{{${variable}}}`, 'g'); - if (subject) { - replacedSubject = replacedSubject.replace(regex, variables[variable]); - } - if (body) { - replacedBody = replacedBody.replace(regex, variables[variable]); - } - } - const result = { subject: normalizeMailSubject(replacedSubject), body: replacedBody }; - return result; -} - -export const saveFileUsage = async (size, fileUrl, userId) => { - //checking server url and save file's size - try { - if (userId) { - const userPtr = { __type: 'Pointer', className: '_User', objectId: userId }; - const tenantQuery = new Parse.Query('partners_Tenant'); - tenantQuery.equalTo('UserId', userPtr); - const tenant = await tenantQuery.first({ useMasterKey: true }); - if (tenant) { - const tenantPtr = { __type: 'Pointer', className: 'partners_Tenant', objectId: tenant.id }; - try { - const tenantCredits = new Parse.Query('partners_TenantCredits'); - tenantCredits.equalTo('PartnersTenant', tenantPtr); - const res = await tenantCredits.first({ useMasterKey: true }); - if (res) { - const response = JSON.parse(JSON.stringify(res)); - const usedStorage = response?.usedStorage ? response.usedStorage + size : size; - const updateCredit = new Parse.Object('partners_TenantCredits'); - updateCredit.id = res.id; - updateCredit.set('usedStorage', usedStorage); - await updateCredit.save(null, { useMasterKey: true }); - } else { - const newCredit = new Parse.Object('partners_TenantCredits'); - newCredit.set('usedStorage', size); - newCredit.set('PartnersTenant', tenantPtr); - await newCredit.save(null, { useMasterKey: true }); - } - } catch (err) { - console.log('err in save usage', err); - } - saveDataFile(size, fileUrl, tenantPtr, userPtr); - } - } - } catch (err) { - console.log('err in fetch tenant Id', err); - } -}; - -//function for save fileUrl and file size in particular client db class partners_DataFiles -const saveDataFile = async (size, fileUrl, tenantPtr, UserId) => { - try { - const newDataFiles = new Parse.Object('partners_DataFiles'); - newDataFiles.set('FileUrl', fileUrl); - newDataFiles.set('FileSize', size); - newDataFiles.set('TenantPtr', tenantPtr); - newDataFiles.set('UserId', UserId); - await newDataFiles.save(null, { useMasterKey: true }); - } catch (err) { - console.log('error in save usage ', err); - } -}; - -export const updateMailCount = async extUserId => { - // Update count in contracts_Users class - const query = new Parse.Query('contracts_Users'); - query.equalTo('objectId', extUserId); - - try { - const contractUser = await query.first({ useMasterKey: true }); - if (contractUser) { - const _extRes = JSON.parse(JSON.stringify(contractUser)); - contractUser.increment('EmailCount', 1); - await contractUser.save(null, { useMasterKey: true }); - } - } catch (error) { - console.log('Error updating EmailCount in contracts_Users: ' + error.message); - } -}; - -export function sanitizeFileName(fileName) { - // Remove spaces and invalid characters - const file = fileName.replace(/[^a-zA-Z0-9._-]/g, ''); - const removedot = file.replace(/\.(?=.*\.)/g, ''); - return removedot.replace(/[^a-zA-Z0-9._-]/g, ''); -} - -export const useLocal = process.env.USE_LOCAL ? process.env.USE_LOCAL.toLowerCase() : 'false'; -export const smtpsecure = process.env.SMTP_PORT && process.env.SMTP_PORT !== '465' ? false : true; -export const smtpenable = - process.env.SMTP_ENABLE && process.env.SMTP_ENABLE.toLowerCase() === 'true' ? true : false; -export const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - -// `generateId` is used to unique Id for fileAdapter -export function generateId(length) { - const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; - let result = ''; - const charactersLength = characters.length; - for (let i = 0; i < length; i++) { - result += characters.charAt(Math.floor(Math.random() * charactersLength)); - } - return result; -} - -/** - * FlattenPdf renders field values as static content and removes the interactive - * form layer. Signatures are stripped entirely. Non-widget annotations (links, - * comments, stamps) are preserved. - * @param {string | Uint8Array | ArrayBuffer} pdfFile - pdf file. - * @returns {Promise<Uint8Array>} flatPdf - pdf file in Uint8Array - */ -export const flattenPdf = async pdfFile => { - const pdfDoc = await PDFDocument.load(pdfFile, { ignoreEncryption: true }); - - try { - const acroFormEntry = pdfDoc.catalog.get(PDFName.of('AcroForm')); - const acroForm = pdfDoc.context.lookupMaybe - ? pdfDoc.context.lookupMaybe(acroFormEntry) - : pdfDoc.context.lookup(acroFormEntry); - - if (acroForm && typeof acroForm.set === 'function') { - // Avoid pdf-lib form APIs here; some malformed PDFs crash while - // iterating/removing fields. Clearing /Fields directly is safer. - acroForm.set(PDFName.of('Fields'), pdfDoc.context.obj([])); - acroForm.delete(PDFName.of('XFA')); - acroForm.delete(PDFName.of('SigFlags')); - } - } catch { - // If AcroForm is malformed, continue with page annotation cleanup. - } - - for (const page of pdfDoc.getPages()) { - try { - const annotationsRef = page.node.get(PDFName.of('Annots')); - if (!annotationsRef) continue; - - const annotations = pdfDoc.context.lookup(annotationsRef); - if (!annotations || !annotations.asArray) continue; - - const filtered = annotations.asArray().filter(annotRef => { - try { - const annot = pdfDoc.context.lookup(annotRef); - const subtype = annot?.get(PDFName.of('Subtype')); - return subtype?.toString() !== '/Widget'; - } catch { - return true; - } - }); - - if (filtered.length === 0) { - page.node.delete(PDFName.of('Annots')); - } else { - page.node.set(PDFName.of('Annots'), pdfDoc.context.obj(filtered)); - } - } catch { - // best effort cleanup - } - } - - try { - pdfDoc.catalog.delete(PDFName.of('AcroForm')); - } catch { - // best effort cleanup - } - - return await pdfDoc.save({ useObjectStreams: false }); -}; - -/* ---- flattenPdf private helpers ---- */ - -function _safeGetWidgetsServer(field) { - try { - return field.acroField?.getWidgets?.() || []; - } catch { - return []; - } -} - -function _getWidgetRectServer(widget, pdfDoc) { - try { - const r = widget.getRectangle?.(); - if (r && isFinite(r.x) && isFinite(r.y) && isFinite(r.width) && isFinite(r.height)) { - return r; - } - } catch { - /* fall through to manual extraction */ - } - - try { - const rectArr = widget.dict?.lookup?.(PDFName.of('Rect')); - if (!rectArr || typeof rectArr.size !== 'function' || rectArr.size() !== 4) return null; - - const x1 = _numberFromPdfObjectServer(rectArr.get(0)); - const y1 = _numberFromPdfObjectServer(rectArr.get(1)); - const x2 = _numberFromPdfObjectServer(rectArr.get(2)); - const y2 = _numberFromPdfObjectServer(rectArr.get(3)); - - if ([x1, y1, x2, y2].some(v => !isFinite(v))) return null; - return { - x: Math.min(x1, x2), - y: Math.min(y1, y2), - width: Math.abs(x2 - x1), - height: Math.abs(y2 - y1), - }; - } catch { - return null; - } -} - -function _numberFromPdfObjectServer(obj) { - if (!obj) return NaN; - if (typeof obj.asNumber === 'function') return obj.asNumber(); - if (typeof obj.numberValue === 'function') return obj.numberValue(); - return Number(obj?.value ?? obj); -} - -function _getWidgetPageServer(pdfDoc, pages, widget) { - try { - const pRef = widget.P?.(); - if (pRef) { - for (const page of pages) { - if (page.ref === pRef) return page; - } - } - } catch { - /* fall through */ - } - - try { - const pRef = widget.dict?.get?.(PDFName.of('P')); - if (pRef) { - for (const page of pages) { - if (page.ref === pRef) return page; - } - } - } catch { - /* fall through */ - } - - // Fallback: search page annots - try { - for (const page of pages) { - const annots = page.node.lookupMaybe(PDFName.of('Annots'), PDFArray); - if (!annots) continue; - - for (let i = 0; i < annots.size(); i++) { - const ref = annots.get(i); - if (ref === widget.ref) return page; - } - } - } catch { - /* fall through */ - } - - return null; -} - -function _drawWidgetBoxServer(page, rect) { - try { - page.drawRectangle({ - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - borderWidth: 0.6, - borderColor: rgb(0.65, 0.65, 0.65), - }); - } catch { - /* best effort */ - } -} - -function _drawTextFieldServer(page, field, rect, font) { - let text = ''; - try { - text = field.getText?.() ?? ''; - } catch { - text = ''; - } - text = String(text ?? ''); - - if (!text) return; - - let multiline = false; - try { - multiline = field.isMultiline?.() ?? false; - } catch { - /* ignore */ - } - - let comb = false; - try { - comb = field.isCombed?.() ?? false; - } catch { - /* ignore */ - } - - if (comb) { - _drawCombTextServer(page, text, rect, font); - return; - } - - if (multiline || text.includes('\n')) { - _drawMultilineTextServer(page, text, rect, font); - return; - } - - const fontSize = _fitSingleLineFontSizeServer(text, rect, font); - const baselineY = rect.y + Math.max(2, (rect.height - fontSize) / 2); - - page.drawText(text, { - x: rect.x + 2, - y: baselineY, - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 4), - }); -} - -function _drawMultilineTextServer(page, text, rect, font) { - const lines = String(text).replace(/\r/g, '').split('\n'); - const fontSize = Math.max(8, Math.min(11, rect.height / Math.max(lines.length + 0.5, 2))); - const lineHeight = fontSize + 1.5; - - let y = rect.y + rect.height - fontSize - 2; - - for (const line of lines) { - if (y < rect.y + 1) break; - - page.drawText(line, { - x: rect.x + 2, - y, - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 4), - lineHeight, - }); - - y -= lineHeight; - } -} - -function _drawCombTextServer(page, text, rect, font) { - const chars = String(text).split(''); - const count = Math.max(chars.length, 1); - const cellWidth = rect.width / count; - const fontSize = Math.max(8, Math.min(12, rect.height - 4)); - - chars.forEach((ch, i) => { - const textWidth = font.widthOfTextAtSize(ch, fontSize); - const x = rect.x + i * cellWidth + (cellWidth - textWidth) / 2; - const y = rect.y + Math.max(2, (rect.height - fontSize) / 2); - - page.drawText(ch, { - x, - y, - size: fontSize, - font, - color: rgb(0, 0, 0), - }); - - if (i < count - 1) { - try { - page.drawLine({ - start: { x: rect.x + (i + 1) * cellWidth, y: rect.y }, - end: { x: rect.x + (i + 1) * cellWidth, y: rect.y + rect.height }, - thickness: 0.4, - color: rgb(0.75, 0.75, 0.75), - }); - } catch { - /* best effort */ - } - } - }); -} - -function _fitSingleLineFontSizeServer(text, rect, font) { - let size = Math.min(12, rect.height - 4); - size = Math.max(size, 6); - - while (size > 6) { - const width = font.widthOfTextAtSize(text, size); - if (width <= rect.width - 4) return size; - size -= 0.5; - } - - return 6; -} - -function _drawCheckBoxServer(page, field, rect, zapf) { - let checked = false; - try { - checked = field.isChecked(); - } catch { - checked = false; - } - - if (!checked) return; - - const size = Math.max(8, Math.min(rect.width, rect.height) - 4); - - page.drawText('\u2714', { - x: rect.x + Math.max(1, (rect.width - size * 0.7) / 2), - y: rect.y + Math.max(1, (rect.height - size) / 2), - size, - font: zapf, - color: rgb(0, 0, 0), - }); -} - -function _drawRadioGroupServer(page, field, widget, rect) { - let selected = null; - try { - selected = field.getSelected(); - } catch { - selected = null; - } - - if (!selected) return; - - let widgetOnValue = null; - try { - widgetOnValue = widget.getOnValue?.(); - } catch { - /* ignore */ - } - - if (!widgetOnValue) { - try { - const ap = widget.dict?.lookupMaybe?.(PDFName.of('AP'), PDFDict); - const n = ap?.lookupMaybe?.(PDFName.of('N'), PDFDict); - if (n) { - const keys = n.keys(); - for (const k of keys) { - const name = k?.decodeText?.() ?? k?.encodedName ?? String(k); - if (name !== '/Off' && name !== 'Off') { - widgetOnValue = name.replace(/^\//, ''); - break; - } - } - } - } catch { - /* ignore */ - } - } - - const selectedStr = String(selected).replace(/^\//, ''); - const onStr = String(widgetOnValue ?? '').replace(/^\//, ''); - - if (!onStr || selectedStr !== onStr) return; - - // Circle outline - try { - page.drawEllipse({ - x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2, - xScale: rect.width / 2 - 1, - yScale: rect.height / 2 - 1, - borderWidth: 0.8, - borderColor: rgb(0, 0, 0), - }); - } catch { - /* best effort */ - } - - // Inner filled dot - try { - const r = Math.min(rect.width, rect.height) / 4; - page.drawEllipse({ - x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2, - xScale: r, - yScale: r, - color: rgb(0, 0, 0), - }); - } catch { - /* best effort */ - } -} - -function _drawDropdownServer(page, field, rect, font) { - let text = ''; - try { - const selected = field.getSelected?.(); - if (Array.isArray(selected)) { - text = selected.join(', '); - } else { - text = selected ?? ''; - } - } catch { - text = ''; - } - - text = String(text ?? ''); - if (!text) return; - - const fontSize = _fitSingleLineFontSizeServer(text, rect, font); - - page.drawText(text, { - x: rect.x + 2, - y: rect.y + Math.max(2, (rect.height - fontSize) / 2), - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 12), - }); -} - -function _drawOptionListServer(page, field, rect, font) { - let selected = []; - try { - selected = field.getSelected?.() || []; - } catch { - selected = []; - } - - if (!Array.isArray(selected)) { - selected = [selected].filter(Boolean); - } - - if (!selected.length) return; - - const lines = selected.map(v => String(v)); - const fontSize = Math.max(8, Math.min(11, rect.height / Math.max(lines.length + 0.5, 2))); - const lineHeight = fontSize + 1.5; - - let y = rect.y + rect.height - fontSize - 2; - - for (const line of lines) { - if (y < rect.y + 1) break; - - page.drawText(line, { - x: rect.x + 2, - y, - size: fontSize, - font, - color: rgb(0, 0, 0), - maxWidth: Math.max(1, rect.width - 4), - }); - - y -= lineHeight; - } -} - -/** Remove only Widget annotations; preserve links, stamps, comments, etc. */ -function _removeWidgetAnnotationsServer(pdfDoc) { - for (const page of pdfDoc.getPages()) { - try { - const annotationsRef = page.node.get(PDFName.of('Annots')); - if (!annotationsRef) continue; - - const annotations = pdfDoc.context.lookup(annotationsRef); - if (!annotations || !annotations.asArray) continue; - - const filtered = annotations.asArray().filter(annotRef => { - try { - const annot = pdfDoc.context.lookup(annotRef); - const subtype = annot?.get(PDFName.of('Subtype')); - return subtype?.toString() !== '/Widget'; - } catch { - return true; - } - }); - - if (filtered.length === 0) { - page.node.delete(PDFName.of('Annots')); - } else { - page.node.set(PDFName.of('Annots'), pdfDoc.context.obj(filtered)); - } - } catch { - /* best effort */ - } - } - - try { - pdfDoc.catalog.delete(PDFName.of('AcroForm')); - } catch { - /* best effort */ - } -} - -// Format date and time for the selected timezone -export const formatTimeInTimezone = (date, timezone) => { - const nyDate = timezone && toZonedTime(date, timezone); - const generatedDate = timezone - ? format(nyDate, 'EEE, dd MMM yyyy HH:mm:ss zzz', { timeZone: timezone }) - : new Date(date).toUTCString(); - return generatedDate; -}; - -// `getSecureUrl` is used to return local secure url if local files -export const getSecureUrl = url => { - const fileUrl = new URL(url)?.pathname?.includes('/files/'); - if (fileUrl) { - try { - const file = getSignedLocalUrl(url); - if (file) { - return { url: file }; - } else { - return { url: '' }; - } - } catch (err) { - console.log('err while fileupload ', err); - return { url: '' }; - } - } else { - return { url: url }; - } -}; - -export const mailTemplate = param => { - const deployment = resolveDeploymentBrand(); - const requestedAppName = deployment.productName; - const brand = resolveBrandContext({ - deployment, - tenant: - requestedAppName && requestedAppName !== deployment.productName - ? { WhiteLabelAppName: requestedAppName } - : undefined, - }); - const subject = normalizeMailSubject( - `${param.senderName} has requested you to sign "${param.title}"` - ); - const logo = renderEmailLogo(brand); - const senderName = escapeHtml(param.senderName); - const title = escapeHtml(param.title); - const senderMail = escapeHtml(param.senderMail); - const organization = escapeHtml(param.organization); - const localExpireDate = escapeHtml(param.localExpireDate); - const note = escapeHtml(param.note); - const signingUrl = escapeHtml(param.signingUrl); - - const body = - "<html><head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8' /></head><body><div style='background-color:#f5f5f5;padding:20px'><div style='background:white;padding-bottom:20px'><div style='padding:10px'>" + - logo + - `</div>${renderEmailHeading(brand, 'Digital Signature Request')}<div><p style='padding:20px;font-size:14px;margin-bottom:10px'>` + - senderName + - ' has requested you to review and sign <strong>' + - title + - "</strong>.</p><div style='padding: 5px 0px 5px 25px;display:flex;flex-direction:row;justify-content:space-around'><table><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td><td></td><td style='color:#626363;font-weight:bold'>" + - senderMail + - "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td><td></td><td style='color:#626363;font-weight:bold'> " + - organization + - "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td></td><td style='color:#626363;font-weight:bold'>" + - localExpireDate + - "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Note</td><td></td><td style='color:#626363;font-weight:bold'>" + - note + - "</td></tr><tr><td></td><td></td></tr></table></div> <div style='margin-left:70px'><a target=_blank href=" + - signingUrl + - "><button style='padding:12px;background-color:#d46b0f;color:white;border:0px;font-weight:bold;margin-top:30px'>Sign here</button></a></div><div style='display:flex;justify-content:center;margin-top:10px'></div></div></div>" + - renderAutomatedEmailFooter(brand, param.senderMail) + - `</div></body></html>`; - - return { subject, body }; -}; - -export const selectFormat = data => { - switch (data) { - case 'L': - return 'MM/dd/yyyy'; - case 'MM/DD/YYYY': - return 'MM/dd/yyyy'; - case 'DD-MM-YYYY': - return 'dd-MM-yyyy'; - case 'DD/MM/YYYY': - return 'dd/MM/yyyy'; - case 'LL': - return 'MMMM dd, yyyy'; - case 'DD MMM, YYYY': - return 'dd MMM, yyyy'; - case 'YYYY-MM-DD': - return 'yyyy-MM-dd'; - case 'MM-DD-YYYY': - return 'MM-dd-yyyy'; - case 'MM.DD.YYYY': - return 'MM.dd.yyyy'; - case 'MMM DD, YYYY': - return 'MMM dd, yyyy'; - case 'MMMM DD, YYYY': - return 'MMMM dd, yyyy'; - case 'DD MMMM, YYYY': - return 'dd MMMM, yyyy'; - case 'DD.MM.YYYY': - return 'dd.MM.yyyy'; - case 'DD-MMM-YYYY': - return 'dd-MMM-yyyy'; - default: - return 'MM/dd/yyyy'; - } -}; - -export function formatDateTime(date, dateFormat, timeZone, is12Hour) { - const zonedDate = toZonedTime(date, timeZone); // Convert date to the given timezone - const timeFormat = is12Hour ? 'hh:mm:ss a' : 'HH:mm:ss'; - return dateFormat - ? format(zonedDate, `${selectFormat(dateFormat)}, ${timeFormat} 'GMT' XXX`, { timeZone }) - : formatTimeInTimezone(date, timeZone); -} - -export const randomId = (digit = 8) => { - // 1. Grab a cryptographically-secure 32-bit random value - // Use crypto for stronger randomness - const randomBytes = crypto.getRandomValues(new Uint32Array(1)); - const raw = randomBytes[0]; // 0 … 4,294,967,295 - - // Calculate the min and max for the given digit length - const min = Math.pow(10, digit - 1); // e.g., digit=3 → 100 - const max = Math.pow(10, digit) - 1; // e.g., digit=3 → 999 - const range = max - min + 1; - - // Collapse random value into the range and shift - return min + (raw % range); -}; -export const handleValidImage = async Placeholder => { - const updatedPlaceholders = []; - - for (const placeholder of Placeholder || []) { - //Clean and format signerPtr - let signerPtr = placeholder.signerPtr; - // Check if signerPtr exists and has an id - if (signerPtr?.id) { - // Case 1: If signerPtr is a Parse Object instance - if (signerPtr instanceof Parse.Object) { - // If signerPtr has no attributes, it’s a plain pointer already - if (!signerPtr.attributes || Object.keys(signerPtr.attributes).length === 0) { - // Convert to a clean pointer using Parse’s built-in method - signerPtr = signerPtr.toPointer(); - } else { - // If it has attributes, manually construct the pointer object - signerPtr = { - __type: 'Pointer', - className: signerPtr.className, - objectId: signerPtr.id, - }; - } - // Case 2: If signerPtr is already a plain JS object resembling a pointer - } else if (typeof signerPtr === 'object' && signerPtr.className && signerPtr.objectId) { - // Normalize it to a valid Parse pointer object - signerPtr = { - __type: 'Pointer', - className: signerPtr.className, - objectId: signerPtr.objectId, - }; - } - } - - //Process placeHolder if Role is 'prefill' - if (placeholder?.Role === 'prefill') { - const updatedRole = []; - for (const item of placeholder.placeHolder || []) { - const updatedPos = []; - for (const posItem of item.pos || []) { - if ( - (posItem?.type === 'image' || posItem?.type === 'draw') && - posItem?.options?.response - ) { - const validUrl = await getPresignedUrl(posItem?.options?.response); - updatedPos.push({ - ...posItem, - ...(item.SignUrl !== undefined && { SignUrl: validUrl }), - options: { ...posItem.options, response: validUrl }, - }); - } else { - updatedPos.push(posItem); - } - } - updatedRole.push({ ...item, pos: updatedPos }); - } - - updatedPlaceholders.push({ ...placeholder, signerPtr, placeHolder: updatedRole }); - } else { - // Not prefill role, just push as-is - updatedPlaceholders.push({ ...placeholder, signerPtr }); - } - } - return updatedPlaceholders; -}; +// Facade over the split utils/<name>.js modules. Every name below keeps the +// export surface the cloud functions, routes and migrations import from here, +// so existing `from '../../Utils.js'` imports keep working unchanged. +export { + MAX_DESCRIPTION_LENGTH, + MAX_NAME_LENGTH, + MAX_NOTE_LENGTH, + appName, + cloudServerUrl, + color, + emailRegex, + prefillBlockColor, + prefillDraftDocWidget, + prefillDraftTemWidget, + serverAppId, + smtpenable, + smtpsecure, + useLocal, +} from './utils/appConfig.js'; +export { normalizeMailSubject, replaceMailVaribles } from './utils/mailVars.js'; +export { saveFileUsage, updateMailCount } from './utils/storageCounts.js'; +export { generateId, randomId, sanitizeFileName } from './utils/fileNames.js'; +export { flattenPdf } from './utils/pdfFlatten.js'; +export { stripHtml } from './utils/textFormat.js'; +export { formatDateTime, formatTimeInTimezone, selectFormat } from './utils/dateFormat.js'; +export { getSecureUrl } from './utils/secureUrl.js'; +export { mailTemplate } from './utils/mailTemplate.js'; +export { handleValidImage } from './utils/placeholders.js'; diff --git a/apps/OpenSignServer/app.json b/apps/OpenSignServer/app.json index 022859b272..49b9ac8154 100644 --- a/apps/OpenSignServer/app.json +++ b/apps/OpenSignServer/app.json @@ -15,7 +15,7 @@ }, "MASTER_KEY": { "description": "A key that overrides all permissions. Keep this secret.", - "value": "myMasterKey" + "generator": "secret" }, "SERVER_URL": { "description": "URL to connect to your Heroku instance (update with your app's name + PARSE_MOUNT)", diff --git a/apps/OpenSignServer/app.yaml b/apps/OpenSignServer/app.yaml index 47d68ce621..4913b05c56 100644 --- a/apps/OpenSignServer/app.yaml +++ b/apps/OpenSignServer/app.yaml @@ -3,7 +3,7 @@ env: flex env_variables: # --REQUIRED-- - DATABASE_URI: mongodb://localhost:27017/dev + DATABASE_URI: <your-mongodb-connection-string> APP_ID: <your-app-id> MASTER_KEY: <your-master-key> SERVER_URL: https://your-project-id.appspot.com/parse diff --git a/apps/OpenSignServer/cloud/customRoute/customApp.js b/apps/OpenSignServer/cloud/customRoute/customApp.js index e713de4d94..250e3ea5df 100644 --- a/apps/OpenSignServer/cloud/customRoute/customApp.js +++ b/apps/OpenSignServer/cloud/customRoute/customApp.js @@ -3,6 +3,7 @@ import cors from 'cors'; import dotenv from 'dotenv'; import docxtopdf, { upload as docxUpload } from './docxtopdf.js'; +import exceltopdf, { upload as excelUpload } from './exceltopdf.js'; import decryptpdf, { upload as decryptUpload } from './decryptpdf.js'; import { deleteUserByAdmin, deleteUserPost } from './deleteAccount/deleteUser.js'; import { deleteUserGet } from './deleteAccount/deleteUserGet.js'; @@ -10,11 +11,42 @@ import { deleteUserOtp } from './deleteAccount/deleteUserOtp.js'; export const app = express(); dotenv.config({ quiet: true }); -app.use(cors()); +const corsAllowlist = ( + process.env.CORS_ORIGINS || + [process.env.SERVER_URL, process.env.PUBLIC_URL, process.env.HOST_URL] + .filter(Boolean) + .join(',') +) + .split(',') + .map(origin => origin.trim().replace(/\/$/, '')) + .filter(Boolean); + +app.use( + cors({ + origin: (origin, callback) => { + if (!origin || corsAllowlist.length === 0) return callback(null, true); + return callback(null, corsAllowlist.includes(origin.replace(/\/$/, ''))); + }, + }) +); + + +// Baseline security headers. A CSP is added at the reverse proxy, where the +// asset and font origins are known. +app.use((req, res, next) => { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'SAMEORIGIN'); + res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()'); + res.setHeader('Strict-Transport-Security', 'max-age=15552000; includeSubDomains'); + next(); +}); + app.use(express.json({ limit: '100mb' })); app.use(express.urlencoded({ limit: '100mb', extended: true })); app.post('/docxtopdf', docxUpload.single('file'), docxtopdf); +app.post('/exceltopdf', excelUpload.single('file'), exceltopdf); app.post('/decryptpdf', decryptUpload.single('file'), decryptpdf); app.get('/delete-account/:userId', deleteUserGet); app.post('/delete-account/:userId/otp', deleteUserOtp); diff --git a/apps/OpenSignServer/cloud/customRoute/decryptpdf.js b/apps/OpenSignServer/cloud/customRoute/decryptpdf.js index f8aa99c374..ed4d048153 100644 --- a/apps/OpenSignServer/cloud/customRoute/decryptpdf.js +++ b/apps/OpenSignServer/cloud/customRoute/decryptpdf.js @@ -1,21 +1,66 @@ import fs from 'node:fs'; import multer from 'multer'; +import crypto from 'node:crypto'; +import axios from 'axios'; import Coherentpdf from 'coherentpdf'; +import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; + +const MAX_UPLOAD_BYTES = 50 * 1024 * 1024; const storage = multer.diskStorage({ destination(req, file, cb) { cb(null, 'exports'); }, + // Never trust the client file name: two callers uploading the same name + // would otherwise overwrite each other. filename(req, file, cb) { - cb(null, file.originalname); + cb(null, `decrypt_${crypto.randomUUID()}.pdf`); + }, +}); + +export const upload = multer({ + storage, + limits: { fileSize: MAX_UPLOAD_BYTES }, + fileFilter: (req, file, cb) => { + const isPdfName = /\.pdf$/i.test(file.originalname || ''); + const isPdfMime = + file.mimetype === 'application/pdf' || file.mimetype === 'application/octet-stream'; + if (isPdfName && isPdfMime) return cb(null, true); + cb(new Error('Only PDF files are supported')); }, }); -export const upload = multer({ storage }); +const safeUnlink = filePath => { + if (!filePath) return; + fs.unlink(filePath, () => {}); +}; export default async function decryptpdf(req, res) { + if (!req.file?.path) { + return res.status(400).json({ error: 'No file uploaded.' }); + } const inputPath = req.file.path; const password = req.body.password || ''; + + // Only an authenticated user may use the server as a decryptor. + const sessionToken = req.headers.sessiontoken; + if (!sessionToken) { + safeUnlink(inputPath); + return res.status(401).json({ error: 'Unauthorized.' }); + } + try { + await axios.get(`${cloudServerUrl}/users/me`, { + headers: { + 'X-Parse-Application-Id': serverAppId, + 'X-Parse-Session-Token': sessionToken, + }, + }); + } catch { + safeUnlink(inputPath); + return res.status(401).json({ error: 'Unauthorized.' }); + } + try { const file = fs.readFileSync(inputPath); const pdf = await Coherentpdf.fromMemory(file, password); @@ -28,10 +73,10 @@ export default async function decryptpdf(req, res) { 'Content-Length': buffer.length, }); res.send(buffer); - fs.unlink(inputPath, () => {}); + safeUnlink(inputPath); } catch (err) { - fs.unlink(inputPath, () => {}); - console.log('Error in decrypt file: ', err); + safeUnlink(inputPath); + logger.info('Error in decrypt file: ', err); let code = err?.code ? err.code : 400; let message = err?.[2]?.c ? err[2].c : 'Something went wrong.'; if (err?.[2]?.c?.includes('Bad password') || err?.[2]?.c?.includes('decrypt_pdf_inner')) { diff --git a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteFileUrl.js b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteFileUrl.js index 16bd1494ce..02012b6c68 100644 --- a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteFileUrl.js +++ b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteFileUrl.js @@ -2,10 +2,11 @@ import { S3Client, DeleteObjectCommand } from '@aws-sdk/client-s3'; import fs from 'node:fs/promises'; import pLimit from 'p-limit'; import { serverAppId } from '../../../Utils.js'; +import { LOCALHOST_HOSTNAMES } from '../../../utils/brandContext.js'; // === Configuration === const serverHost = new URL(process.env.SERVER_URL).hostname; -const LOCAL_HOSTS = ['localhost', '127.0.0.1', serverHost]; +const LOCAL_HOSTS = [...LOCALHOST_HOSTNAMES, serverHost]; const CONCURRENCY_LIMIT = 5; // === S3 Client Setup === @@ -26,12 +27,17 @@ function createS3Client({ region, accessKeyId, secretAccessKey, endpoint = null return new S3Client(config); } -const s3 = createS3Client({ - region: process.env.DO_REGION, - endpoint: process.env.DO_ENDPOINT, - accessKeyId: process.env.DO_ACCESS_KEY_ID, - secretAccessKey: process.env.DO_SECRET_ACCESS_KEY, -}); +let _s3 = null; +function getS3Client() { + if (_s3) return _s3; + _s3 = createS3Client({ + region: process.env.DO_REGION, + endpoint: process.env.DO_ENDPOINT, + accessKeyId: process.env.DO_ACCESS_KEY_ID, + secretAccessKey: process.env.DO_SECRET_ACCESS_KEY, + }); + return _s3; +} // === Helpers === function getS3ParamsFromUrl(fileUrl) { @@ -50,7 +56,7 @@ async function deleteS3File(fileUrl) { if (!params) return; try { - await s3.send(new DeleteObjectCommand(params)); + await getS3Client().send(new DeleteObjectCommand(params)); // console.log(`✅ Deleted from S3: ${params.Key}`); } catch (err) { console.error(`❌ S3 delete failed: ${params.Key}:`, err.message); diff --git a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUser.js b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUser.js index 5fdb87c990..de14d85c7b 100644 --- a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUser.js +++ b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUser.js @@ -1,8 +1,10 @@ import axios from 'axios'; +import { isAdminRole, isOrgAdminRole, ADMIN_ROLES } from '../../../utils/roles.js'; import { cloudServerUrl, generateId, serverAppId } from '../../../Utils.js'; import { resolveBrandContext } from '../../../utils/brandContext.js'; import { deleteContactsInBatch, deleteDataFiles, deleteInBatches } from './deleteFileUrl.js'; import { MAX_ATTEMPTS } from './deleteUtils.js'; +import { logger } from '../../../utils/logger.js'; const serverUrl = cloudServerUrl; const appId = serverAppId; @@ -66,7 +68,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org const tenantId = userResult.get('TenantId')?.id; const teamIds = userResult.get('TeamIds') || []; const organizationId = userResult.get('OrganizationId')?.id; - const isAdmin = userResult?.get('UserRole') === 'contracts_Admin' ? true : false; + const isAdmin = isAdminRole(userResult?.get('UserRole')); if (isOrgAdmin && isAdmin) { const errorMessage = 'Unauthorized.'; return { code: 400, message: errorMessage }; @@ -91,7 +93,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org await deleteInBatches(className, userPointer); } } catch (err) { - console.error('Failed during contracts_Template cleanup:', err); + logger.error('Failed during contracts_Template cleanup:', err); const errorMessage = 'Failed during contracts_Template cleanup:' + err?.message; return { code: 400, message: errorMessage }; } @@ -100,7 +102,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org try { await deleteContactsInBatch('contracts_Contactbook', userPointer); } catch (err) { - console.error('Failed during contactbook cleanup:', err); + logger.error('Failed during contactbook cleanup:', err); const errorMessage = 'Failed during contactbook cleanup:' + err?.message; return { code: 400, message: errorMessage }; } @@ -119,7 +121,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org await resetPasswordAndDeleteSession(userId); } } catch (err) { - console.error('Failed during contactbook current user cleanup:', err); + logger.error('Failed during contactbook current user cleanup:', err); const errorMessage = 'Failed during contactbook current user cleanup: ' + (err?.message || err); return { code: 400, message: errorMessage }; @@ -133,7 +135,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org const tokens = await query.find({ useMasterKey: true }); if (tokens?.length) await Parse.Object.destroyAll(tokens, { useMasterKey: true }); } catch (err) { - console.error('Failed to delete appToken entries:', err); + logger.error('Failed to delete appToken entries:', err); const errorMessage = 'Failed to delete appToken entries:' + err?.message; return { code: 400, message: errorMessage }; } @@ -142,7 +144,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org try { await deleteDataFiles('partners_DataFiles', userPointer); } catch (err) { - console.error('Failed during partners_DataFiles cleanup:', err); + logger.error('Failed during partners_DataFiles cleanup:', err); const errorMessage = 'Failed during partners_DataFiles cleanup:' + err?.message; return { code: 400, message: errorMessage }; } @@ -157,7 +159,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org await object.destroy({ useMasterKey: true }); } } catch (err) { - console.error('Failed to delete contracts_Organizations entry:', err); + logger.error('Failed to delete contracts_Organizations entry:', err); const errorMessage = 'Failed to delete contracts_Organizations entry:' + err?.message; return { code: 400, message: errorMessage }; } @@ -170,14 +172,14 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org const teamObj = await new Parse.Query(Teams).get(team.id, { useMasterKey: true }); if (teamObj) await teamObj.destroy({ useMasterKey: true }); } catch (teamErr) { - console.error(`Failed to delete team with ID ${team.id}:`, teamErr); + logger.error(`Failed to delete team with ID ${team.id}:`, teamErr); const errorMessage = `Failed to delete team with ID ${team.id}` + teamErr?.message; return { code: 400, message: errorMessage }; } } } } catch (err) { - console.error('Failed during contracts_Teams deletion loop:', err); + logger.error('Failed during contracts_Teams deletion loop:', err); const errorMessage = 'Failed during contracts_Teams deletion loop:' + err?.message; return { code: 400, message: errorMessage }; } @@ -192,7 +194,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org } } catch (err) { const msg = `Failed during partners_Tenant ${'cleanup:'} `; - console.error(msg, err); + logger.error(msg, err); const errorMessage = msg + err?.message; return { code: 400, message: errorMessage }; } @@ -211,7 +213,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org await Parse.Object.destroyAll(subs, { useMasterKey: true }); } } catch (err) { - console.error('Failed during partners_TenantCredits cleanup:', err); + logger.error('Failed during partners_TenantCredits cleanup:', err); const errorMessage = 'Failed during partners_TenantCredits cleanup:' + err?.message; return { code: 400, message: errorMessage }; } @@ -224,7 +226,7 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org const sigResults = await sigQuery.find({ useMasterKey: true }); if (sigResults?.length > 0) await Parse.Object.destroyAll(sigResults, { useMasterKey: true }); } catch (err) { - console.error('Failed during contracts_Signature cleanup:', err); + logger.error('Failed during contracts_Signature cleanup:', err); const errorMessage = 'Failed during contracts_Signature cleanup:' + err?.message; return { code: 400, message: errorMessage }; } @@ -233,13 +235,13 @@ export async function deleteUser(userId, adminId, adminTenantId, isOrgAdmin, org try { await userResult.destroy({ useMasterKey: true }); } catch (err) { - console.error('Failed to delete contracts_Users entry:', err); + logger.error('Failed to delete contracts_Users entry:', err); const errorMessage = 'Failed to delete contracts_Users entry:' + err?.message; return { code: 400, message: errorMessage }; } return { code: 200, message: 'User and all associated data deleted successfully.' }; } catch (error) { - console.error('User deletion process failed:', error); + logger.error('User deletion process failed:', error); const errorMessage = `User deletion failed: ${error.message || error}`; return { code: 400, message: errorMessage }; } @@ -277,7 +279,7 @@ export const deleteUserPost = async (req, res) => { return res.send(errorMessage); } - if (extUser?.get('UserRole') !== 'contracts_Admin') { + if (!isAdminRole(extUser?.get('UserRole'))) { const errorMessage = 'This action is not permitted. Kindly contact your administrator to request account deletion.'; return res.send(errorMessage); @@ -285,7 +287,7 @@ export const deleteUserPost = async (req, res) => { const extUsers = new Parse.Query('contracts_Users'); extUsers.equalTo('TenantId', extUser?.get('TenantId')); - extUsers.notEqualTo('UserRole', 'contracts_Admin'); + extUsers.notContainedIn('UserRole', ADMIN_ROLES); const isTeamUsers = await extUsers.first({ useMasterKey: true }); if (isTeamUsers) { const errorMessage = `To delete this account, start by removing all team users associated with it. Once all users are removed, you'll be able to permanently delete the account.`; @@ -327,7 +329,7 @@ export const deleteUserPost = async (req, res) => { extUser.unset('DeleteOTPTries'); await extUser.save(null, { useMasterKey: true }); } catch (err) { - console.log('err while validating password: ', err?.response?.data || err); + logger.info('err while validating password: ', err?.response?.data || err); } const response = await deleteUser(userId); @@ -335,7 +337,7 @@ export const deleteUserPost = async (req, res) => { const message = response?.message || 'An error occurred while deleting your account.'; return res.status(code).send(message); } catch (error) { - console.error('Account deletion error:', error); + logger.error('Account deletion error:', error); const errorMessage = error?.message || 'An error occurred while deleting your account.'; return res.status(500).send(errorMessage); } @@ -389,12 +391,8 @@ export const deleteUserByAdmin = async (req, res) => { const errorMessage = 'User not found.'; return res.status(400).json({ message: errorMessage }); } - const isAdmin = - extUser?.get('UserRole') === 'contracts_Admin' || - extUser?.get('UserRole') === 'contracts_OrgAdmin' - ? true - : false; - const isOrgAdmin = extUser?.get('UserRole') === 'contracts_OrgAdmin'; + const isAdmin = isAdminRole(extUser?.get('UserRole')); + const isOrgAdmin = isOrgAdminRole(extUser?.get('UserRole')); const tenantId = extUser?.get('TenantId'); const orgPtr = isOrgAdmin && extUser?.get('OrganizationId'); if (!isAdmin) { @@ -403,7 +401,7 @@ export const deleteUserByAdmin = async (req, res) => { const response = await deleteUser(userId, adminId, tenantId, isOrgAdmin, orgPtr); const code = response?.code || 400; const message = response?.message || 'An error occurred while deleting your account.'; - console.log('delete user ', code, message); + logger.info('delete user ', code, message); return res.status(code).json({ message: message }); } catch (error) { const code = error?.response?.data?.code || 400; @@ -411,7 +409,7 @@ export const deleteUserByAdmin = async (req, res) => { error?.response?.data?.error || error?.message || 'An error occurred while deleting your account.'; - console.error(`Account deletion error:`, errorMessage); + logger.error(`Account deletion error:`, errorMessage); return res.status(code).json({ message: errorMessage }); } }; diff --git a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUserOtp.js b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUserOtp.js index bb0479995d..4b65ff51e9 100644 --- a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUserOtp.js +++ b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUserOtp.js @@ -5,6 +5,7 @@ import { OTP_EXPIRES_MIN, RESEND_COOLDOWN_SEC, } from './deleteUtils.js'; +import { logger } from '../../../utils/logger.js'; export const deleteUserOtp = async (req, res) => { const { userId } = req.params; @@ -38,7 +39,7 @@ export const deleteUserOtp = async (req, res) => { await extUser.save(null, { useMasterKey: true }); return res.json({ ok: true, cooldownSec: RESEND_COOLDOWN_SEC, expiresInMin: OTP_EXPIRES_MIN }); } catch (err) { - console.log('Error sending delete OTP (POST /otp):', err?.response?.data || err); + logger.info('Error sending delete OTP (POST /otp):', err?.response?.data || err); return res.status(500).json({ error: 'Failed to send OTP' }); } }; diff --git a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUtils.js b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUtils.js index 44f97a0011..8cbdf52091 100644 --- a/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUtils.js +++ b/apps/OpenSignServer/cloud/customRoute/deleteAccount/deleteUtils.js @@ -1,3 +1,4 @@ +import { randomInt } from 'node:crypto'; import { appName } from '../../../Utils.js'; import sendSystemMail from '../../parsefunction/sendSystemMail.js'; import { escapeHtml, resolveBrandContext } from '../../../utils/brandContext.js'; @@ -9,8 +10,9 @@ export const RESEND_COOLDOWN_SEC = 30; // Cooldown between OTP sends export const MAX_ATTEMPTS = 5; // Max allowed wrong attempts export function generateOtp(len = OTP_LENGTH) { - // 6-digit numeric OTP (000000–999999, padded) - const n = Math.floor(Math.random() * Math.pow(10, len)); + // 6-digit numeric OTP (000000–999999, padded), drawn from a CSPRNG. + const max = Math.pow(10, len); + const n = randomInt(0, max); return String(n).padStart(len, '0'); } diff --git a/apps/OpenSignServer/cloud/customRoute/docxtopdf.js b/apps/OpenSignServer/cloud/customRoute/docxtopdf.js index eedee04751..009662635a 100644 --- a/apps/OpenSignServer/cloud/customRoute/docxtopdf.js +++ b/apps/OpenSignServer/cloud/customRoute/docxtopdf.js @@ -17,13 +17,13 @@ async function killStuckProcesses() { // Kill soffice processes older than 2 minutes if (process.platform === 'linux' || process.platform === 'darwin') { await execAsync("pkill -9 -f 'soffice.*--headless' || true"); - console.log('[DOCX2PDF] Cleaned up stuck processes'); + logger.info('[DOCX2PDF] Cleaned up stuck processes'); } else if (process.platform === 'win32') { await execAsync('taskkill /F /IM soffice.bin /T || exit 0'); - console.log('[DOCX2PDF] Cleaned up stuck processes (Windows)'); + logger.info('[DOCX2PDF] Cleaned up stuck processes (Windows)'); } } catch (err) { - console.error('[DOCX2PDF] Error killing processes:', err.message); + logger.error('[DOCX2PDF] Error killing processes:', err.message); } } @@ -149,6 +149,7 @@ export default async function docxtopdf(req, res) { // ---- DOCX -> PDF conversion with concurrency control and timeout ---- const fileName = `${generatePdfName(16)}.pdf`; + const uploadedSizeBytes = req.file.buffer.length; // Adjust timeout based on file size const timeoutMs = uploadedSizeBytes > 10 * 1024 * 1024 ? 120_000 : 90_000; @@ -156,7 +157,7 @@ export default async function docxtopdf(req, res) { // FIX: Increased timeout for large files, added nice priority const pdfBuffer = await runWithLimit(async () => { // Log for monitoring - console.log( + logger.info( `[DOCX2PDF] Starting conversion, size: ${(uploadedSizeBytes / 1024 / 1024).toFixed(2)}MB, active: ${active}, queued: ${queue.length}` ); @@ -167,10 +168,10 @@ export default async function docxtopdf(req, res) { timeoutMs, 'DOCX->PDF' ); - console.log(`[DOCX2PDF] Completed in ${Date.now() - startTime}ms`); + logger.info(`[DOCX2PDF] Completed in ${Date.now() - startTime}ms`); return result; } catch (error) { - console.error(`[DOCX2PDF] Failed after ${Date.now() - startTime}ms:`, error.message); + logger.error(`[DOCX2PDF] Failed after ${Date.now() - startTime}ms:`, error.message); // Clean up on error await killStuckProcesses(); throw error; @@ -216,7 +217,7 @@ export default async function docxtopdf(req, res) { } else { msg = message; } - console.error(`[DOCX2PDF] Error: ${msg}`); + logger.error(`[DOCX2PDF] Error: ${msg}`); return res.status(400).json({ error: message }); } } diff --git a/apps/OpenSignServer/cloud/customRoute/exceltopdf.js b/apps/OpenSignServer/cloud/customRoute/exceltopdf.js new file mode 100644 index 0000000000..86cd579ada --- /dev/null +++ b/apps/OpenSignServer/cloud/customRoute/exceltopdf.js @@ -0,0 +1,223 @@ +import axios from 'axios'; +import multer from 'multer'; +import libre from 'libreoffice-convert'; +import { exec } from 'child_process'; +import { promisify } from 'util'; +import { cloudServerUrl, getSecureUrl, serverAppId } from '../../Utils.js'; + +const execAsync = promisify(exec); + +// -------------------- Process Management -------------------- +/** + * Kill stuck LibreOffice processes + */ +async function killStuckProcesses() { + try { + // Kill soffice processes older than 2 minutes + if (process.platform === 'linux' || process.platform === 'darwin') { + await execAsync("pkill -9 -f 'soffice.*--headless' || true"); + console.log('[EXCEL2PDF] Cleaned up stuck processes'); + } else if (process.platform === 'win32') { + await execAsync('taskkill /F /IM soffice.bin /T || exit 0'); + console.log('[EXCEL2PDF] Cleaned up stuck processes (Windows)'); + } + } catch (err) { + console.error('[EXCEL2PDF] Error killing processes:', err.message); + } +} + +/** @returns {Promise<Buffer>} */ +async function convertLibre(input, ext, opts) { + return await new Promise((resolve, reject) => { + try { + libre.convert(input, ext, opts, (err, out) => (err ? reject(err) : resolve(out))); + } catch (e) { + reject(e); + } + }); +} + +// -------------------- Concurrency limiter with queue limits -------------------- +// CRITICAL FIX: Reduced to 1 for CPU-intensive LibreOffice conversions +const MAX_CONCURRENCY = Number(process.env.EXCEL2PDF_CONCURRENCY || 1); +let active = 0; +const queue = []; + +function runWithLimit(task) { + return new Promise((resolve, reject) => { + const run = async () => { + active++; + try { + const result = await task(); + resolve(result); + } catch (error) { + reject(error); + } finally { + active--; + if (queue.length) { + const next = queue.shift(); + next(); + } + } + }; + if (active < MAX_CONCURRENCY) run(); + else queue.push(run); + }); +} + +// -------------------- Timeout helper with cleanup -------------------- +/** + * @template T + * @param {Promise<T>} promise + * @param {number} ms + * @param {string} [label='operation'] + * @returns {Promise<T>} + */ +export async function withTimeout(promise, ms, label = 'operation') { + let timer; + try { + const timeout = new Promise((_, reject) => { + timer = setTimeout(async () => { + // Kill stuck processes on timeout + await killStuckProcesses(); + reject(new Error(`${label} timed out after ${ms}ms`)); + }, ms); + }); + return await Promise.race([promise, timeout]); + } finally { + if (timer) clearTimeout(timer); + } +} + +// -------------------- Multer: use memory storage -------------------- +const storage = multer.memoryStorage(); +export const upload = multer({ + storage, + limits: { fileSize: 50 * 1024 * 1024 }, // 50MB hard limit at multer level + fileFilter: (req, file, cb) => { + const okExt = /\.(xlsx|xls)$/i.test(file.originalname || ''); + const okMime = + file.mimetype === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || + file.mimetype === 'application/vnd.ms-excel' || + file.mimetype === 'application/octet-stream'; + if (okExt && okMime) return cb(null, true); + cb(new Error('Only .xlsx and .xls files are supported')); + }, +}); + +function generatePdfName(length) { + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + for (let i = 0; i < length; i++) result += chars.charAt(Math.floor(Math.random() * chars.length)); + return result; +} + +export default async function exceltopdf(req, res) { + const serverUrl = cloudServerUrl; + const parseAppKey = { 'X-Parse-Application-Id': serverAppId }; + const masterKey = process.env.MASTER_KEY; + + const masterHeader = { ...parseAppKey, 'X-Parse-Master-Key': masterKey }; + const sessionHeader = { ...parseAppKey, 'X-Parse-Session-Token': req.headers['sessiontoken'] }; + + if (!req.file || !req.file.buffer) { + return res.status(400).json({ error: 'No file uploaded.' }); + } + + try { + // ---- Auth: current user ---- + const userRes = await axios.get(`${serverUrl}/users/me`, { headers: sessionHeader }); + + // ---- contracts_Users ---- + const whereUser = JSON.stringify({ + UserId: { __type: 'Pointer', className: '_User', objectId: userRes.data.objectId }, + }); + const resUser = await axios.get( + `${serverUrl}/classes/contracts_Users?where=${whereUser}&limit=1&include=TenantId`, + { headers: masterHeader } + ); + + if (!resUser?.data?.results?.length) { + return res.status(403).json({ error: 'User not linked to tenant.' }); + } + + const tenantId = resUser.data.results[0]?.TenantId?.objectId; + if (!tenantId) { + return res.status(403).json({ error: 'Tenant not found for user.' }); + } + + // ---- EXCEL -> PDF conversion with concurrency control and timeout ---- + const fileName = `${generatePdfName(16)}.pdf`; + const uploadedSizeBytes = req.file.buffer.length; + + // Adjust timeout based on file size + const timeoutMs = uploadedSizeBytes > 10 * 1024 * 1024 ? 120_000 : 90_000; + + // FIX: Increased timeout for large files, added nice priority + const pdfBuffer = await runWithLimit(async () => { + // Log for monitoring + console.log( + `[EXCEL2PDF] Starting conversion, size: ${(uploadedSizeBytes / 1024 / 1024).toFixed(2)}MB, active: ${active}, queued: ${queue.length}` + ); + + const startTime = Date.now(); + try { + const result = await withTimeout( + convertLibre(req.file.buffer, '.pdf', undefined), + timeoutMs, + 'EXCEL->PDF' + ); + console.log(`[EXCEL2PDF] Completed in ${Date.now() - startTime}ms`); + return result; + } catch (error) { + console.error(`[EXCEL2PDF] Failed after ${Date.now() - startTime}ms:`, error.message); + // Clean up on error + await killStuckProcesses(); + throw error; + } + }); + + // ---- Upload PDF ---- + const activeFileAdapter = resUser.data.results[0]?.TenantId?.ActiveFileAdapter; + let fileUrl; + if (activeFileAdapter) { + const params = { + fileBase64: Buffer.from(pdfBuffer).toString('base64'), + fileName, + id: activeFileAdapter, + }; + const url = serverUrl + '/functions/savetofileadapter'; + const headers = { 'Content-Type': 'application/json', ...sessionHeader }; + const savetos3 = await axios.post(url, params, { headers }); + fileUrl = savetos3?.data?.result?.url; + if (!fileUrl) throw new Error('No URL returned from file adapter'); + } else { + const parsefile = await axios.post(`${serverUrl}/files/${fileName}`, pdfBuffer, { + headers: { ...masterHeader, 'Content-Type': 'application/pdf' }, + }); + const fileRes = getSecureUrl(parsefile.data.url); + fileUrl = fileRes.url; + } + + return res.status(200).json({ message: 'success.', url: fileUrl }); + } catch (err) { + // More specific error messages + let msg = + err?.response?.data?.error || err?.response?.data || err?.message || 'Something went wrong.'; + // Friendly message to the client + const message = + 'We are currently experiencing some issues with processing Excel files. Please upload the PDF version or contact us on support@opensignlabs.com'; + + if (msg.includes('timed out')) { + msg = + 'Document conversion is taking too long. Please try a smaller file or contact support@opensignlabs.com'; + } else if (msg.includes('too large') || msg.includes('size')) { + msg = + 'File is too large to process. Please reduce the file size or contact support@opensignlabs.com'; + } else { + msg = message; + } + console.error(`[EXCEL2PDF] Error: ${msg}`); + return res.status(400).json({ error: msg }); + } +} diff --git a/apps/OpenSignServer/cloud/parsefunction/AddAdmin.js b/apps/OpenSignServer/cloud/parsefunction/AddAdmin.js index 53dfa82561..a5676dfc7d 100644 --- a/apps/OpenSignServer/cloud/parsefunction/AddAdmin.js +++ b/apps/OpenSignServer/cloud/parsefunction/AddAdmin.js @@ -1,5 +1,6 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; const serverUrl = cloudServerUrl; //process.env.SERVER_URL; const APPID = serverAppId; const masterKEY = process.env.MASTER_KEY; @@ -55,7 +56,7 @@ async function addTeamAndOrg(extUser) { const extUserRes = await updateUser.save(null, { useMasterKey: true }); } } catch (err) { - console.log('err in add team, role, org', err); + logger.info('err in add team, role, org', err); } } @@ -79,7 +80,7 @@ async function saveUser(userDetails) { }, }); const login = await axiosRes.data; - // console.log("login ", login); + // logger.info("login ", login); return { id: login.objectId, sessionToken: login.sessionToken }; } else { const user = new Parse.User(); @@ -92,7 +93,7 @@ async function saveUser(userDetails) { user.set('name', userDetails.name); const res = await user.signUp(); - // console.log("res ", res); + // logger.info("res ", res); return { id: res.id, sessionToken: res.getSessionToken() }; } } @@ -145,7 +146,7 @@ export default async function AddAdmin(request) { partnerQuery.set('Address', userDetails.address); } const tenantRes = await partnerQuery.save(null, { useMasterKey: true }); - // console.log("tenantRes ", tenantRes); + // logger.info("tenantRes ", tenantRes); const newObj = new Parse.Object('contracts_Users'); newObj.set('UserId', { __type: 'Pointer', @@ -188,6 +189,6 @@ export default async function AddAdmin(request) { return { message: 'User sign up', sessionToken: user.sessionToken }; } } catch (err) { - console.log('Err ', err); + logger.info('Err ', err); } } diff --git a/apps/OpenSignServer/cloud/parsefunction/AuthLoginAsMail.js b/apps/OpenSignServer/cloud/parsefunction/AuthLoginAsMail.js index 444cf0cb19..e7d9977090 100644 --- a/apps/OpenSignServer/cloud/parsefunction/AuthLoginAsMail.js +++ b/apps/OpenSignServer/cloud/parsefunction/AuthLoginAsMail.js @@ -19,8 +19,16 @@ async function AuthLoginAsMail(request) { if (res !== undefined) { let resOtp = res.get('OTP'); + const expiresAt = res.get('ExpiresAt'); + // A record without a usable expiry is legacy; it must not be accepted. + if (!expiresAt || new Date(expiresAt) <= new Date()) { + return 'Invalid Otp'; + } if (resOtp === otp) { + // Consume the code before issuing a session. If the delete fails the + // code would stay reusable, so the authentication must abort. + await res.destroy({ useMasterKey: true }); var result = await getToken(request); if (result && !result?.emailVerified) { const userQuery = new Parse.Query(Parse.User); diff --git a/apps/OpenSignServer/cloud/parsefunction/CheckAdminExist.js b/apps/OpenSignServer/cloud/parsefunction/CheckAdminExist.js index 33d1cb6d97..18ec8d4142 100644 --- a/apps/OpenSignServer/cloud/parsefunction/CheckAdminExist.js +++ b/apps/OpenSignServer/cloud/parsefunction/CheckAdminExist.js @@ -1,8 +1,10 @@ // `CheckAdminExist` is used to check is admin with org exist or not in db +import { ALL_ADMIN_ROLES } from '../../utils/roles.js'; + export default async function CheckAdminExist() { try { const extClsQuery = new Parse.Query('contracts_Users'); - extClsQuery.equalTo('UserRole', 'contracts_Admin'); + extClsQuery.containedIn('UserRole', ALL_ADMIN_ROLES); extClsQuery.notEqualTo('IsDisabled', true); const extAdminRes = await extClsQuery.find({ useMasterKey: true }); // must be only one admin diff --git a/apps/OpenSignServer/cloud/parsefunction/ContactBookAftersave.js b/apps/OpenSignServer/cloud/parsefunction/ContactBookAftersave.js index d86dc344b8..5ddea2a84c 100644 --- a/apps/OpenSignServer/cloud/parsefunction/ContactBookAftersave.js +++ b/apps/OpenSignServer/cloud/parsefunction/ContactBookAftersave.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; async function ContactbookAftersave(request) { /* In beforesave or aftersave if you want to check if an object is being inserted or updated you can check as follows */ @@ -42,10 +43,10 @@ async function ContactbookAftersave(request) { acl.setWriteAccess(user.id, true); object.setACL(acl); await object.save(null, { useMasterKey: true }); - // console.log('res update new user with contac', res); + // logger.info('res update new user with contac', res); } } catch (err) { - // console.log('err ', err); + // logger.info('err ', err); if (err.code === 202) { const userQuery = new Parse.Query(Parse.User); userQuery.equalTo('email', Email); @@ -60,12 +61,12 @@ async function ContactbookAftersave(request) { acl.setWriteAccess(userRes.id, true); object.setACL(acl); await object.save(null, { useMasterKey: true }); - // console.log('res update existing user with contact', res); + // logger.info('res update existing user with contact', res); } } } } else { - console.log('Object being update'); + logger.info('Object being update'); } } export default ContactbookAftersave; diff --git a/apps/OpenSignServer/cloud/parsefunction/DocumentAftersave.js b/apps/OpenSignServer/cloud/parsefunction/DocumentAftersave.js index c1927457e3..33bcde20b7 100644 --- a/apps/OpenSignServer/cloud/parsefunction/DocumentAftersave.js +++ b/apps/OpenSignServer/cloud/parsefunction/DocumentAftersave.js @@ -1,7 +1,8 @@ +import { logger } from '../../utils/logger.js'; async function DocumentAftersave(request) { try { if (!request.original) { - console.log('new entry is insert in contracts_Document ', request?.object?.id); + logger.info('new entry is insert in contracts_Document ', request?.object?.id); const obj = request.object; const objId = obj?.id; const createdAt = obj?.createdAt || obj?.get?.('createdAt'); @@ -34,8 +35,8 @@ async function DocumentAftersave(request) { } } } catch (err) { - console.log('err in aftersave of contracts_Document'); - console.log(err); + logger.info('err in aftersave of contracts_Document'); + logger.info(err); } async function updateDocumentMeta({ objId, createdAt, folder, ip, originIp }) { @@ -43,6 +44,11 @@ async function DocumentAftersave(request) { documentQuery.include('ExtUserPtr.TenantId'); const doc = await documentQuery.get(objId, { useMasterKey: true }); + // OriginIp is independent of the folder type: every document must record + // who created it, because the completion certificate reads it. + if (!originIp && ip) { + doc.set('OriginIp', ip); + } if (folder === undefined || folder === 'AIDoc') { // ExpiryDate const timeToCompleteDays = @@ -56,11 +62,6 @@ async function DocumentAftersave(request) { doc.set('ExpiryDate', expiryDate); } - // OriginIp - if (!originIp) { - doc.set('OriginIp', ip); - } - // Automatic reminders const autoReminder = doc.get('AutomaticReminders') || false; if (autoReminder && createdAt) { diff --git a/apps/OpenSignServer/cloud/parsefunction/DocumentBeforesave.js b/apps/OpenSignServer/cloud/parsefunction/DocumentBeforesave.js index 7e5fce2096..c7d6c4781c 100644 --- a/apps/OpenSignServer/cloud/parsefunction/DocumentBeforesave.js +++ b/apps/OpenSignServer/cloud/parsefunction/DocumentBeforesave.js @@ -1,5 +1,6 @@ import { MAX_DESCRIPTION_LENGTH, MAX_NAME_LENGTH, MAX_NOTE_LENGTH } from '../../Utils.js'; import { setDocumentCount } from '../../utils/CountUtils.js'; +import { logger } from '../../utils/logger.js'; async function DocumentBeforesave(request) { if (!request.original) { @@ -42,7 +43,7 @@ async function DocumentBeforesave(request) { } } } catch (err) { - console.log('err in document beforesave', err.message); + logger.info('err in document beforesave', err.message); } } export default DocumentBeforesave; diff --git a/apps/OpenSignServer/cloud/parsefunction/ForwardDoc.js b/apps/OpenSignServer/cloud/parsefunction/ForwardDoc.js index f1da15d10e..226753a230 100644 --- a/apps/OpenSignServer/cloud/parsefunction/ForwardDoc.js +++ b/apps/OpenSignServer/cloud/parsefunction/ForwardDoc.js @@ -52,7 +52,7 @@ export default async function forwardDoc(request) { }), }; mailRes = await sendMailWithAttachment(params); - // console.log('mailRes', mailRes); + // logger.info('mailRes', mailRes); } return mailRes; } catch (error) { @@ -67,7 +67,7 @@ export default async function forwardDoc(request) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'please provide parameters.'); } } catch (err) { - console.log('Err in forwardDoc', err); + logger.info('Err in forwardDoc', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/GetTemplate.js b/apps/OpenSignServer/cloud/parsefunction/GetTemplate.js index c5bb79b88f..896429b403 100644 --- a/apps/OpenSignServer/cloud/parsefunction/GetTemplate.js +++ b/apps/OpenSignServer/cloud/parsefunction/GetTemplate.js @@ -1,5 +1,6 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; export default async function GetTemplate(request) { const serverUrl = cloudServerUrl; //process.env.SERVER_URL; @@ -77,14 +78,14 @@ export default async function GetTemplate(request) { return { error: "template deleted or you don't have access." }; } } catch (err) { - console.log('err', err); + logger.info('err', err); return err; } } else { return { error: "template deleted or you don't have access." }; } } catch (err) { - console.log('err', err); + logger.info('err', err); if (err?.response?.data?.code === 209 || err.code == 209) { return { error: 'Invalid session token' }; } else { diff --git a/apps/OpenSignServer/cloud/parsefunction/Newsletter.js b/apps/OpenSignServer/cloud/parsefunction/Newsletter.js index 50cf7d9db1..d1e8227ddc 100644 --- a/apps/OpenSignServer/cloud/parsefunction/Newsletter.js +++ b/apps/OpenSignServer/cloud/parsefunction/Newsletter.js @@ -1,4 +1,5 @@ import axios from 'axios'; +import { logger } from '../../utils/logger.js'; export default async function Newsletter(request) { const name = request.params.name; const email = request.params?.email?.toLowerCase()?.replace(/\s/g, ''); @@ -17,7 +18,7 @@ export default async function Newsletter(request) { const code = err?.response?.data?.code || err?.response?.status || err?.code || 400; const message = err?.response?.data?.error || err?.response?.data || err?.message || 'Something went wrong.'; - console.log('err in savenewsletter', err); + logger.info('err in savenewsletter', err); throw new Parse.Error(code, message); } } diff --git a/apps/OpenSignServer/cloud/parsefunction/SendMailOTPv1.js b/apps/OpenSignServer/cloud/parsefunction/SendMailOTPv1.js index 106ea912f7..cb53a9807b 100644 --- a/apps/OpenSignServer/cloud/parsefunction/SendMailOTPv1.js +++ b/apps/OpenSignServer/cloud/parsefunction/SendMailOTPv1.js @@ -60,6 +60,7 @@ async function sendMailOTPv1(request) { useMasterKey: true, }); updateOtp.set('OTP', code); + updateOtp.set('ExpiresAt', new Date(Date.now() + 10 * 60 * 1000)); updateOtp.save(null, { useMasterKey: true }); // console.log("update otp Res in tempSendOtp ", updateRes); } else { @@ -68,6 +69,7 @@ async function sendMailOTPv1(request) { newOtpQuery.set('OTP', code); newOtpQuery.set('Email', email); newOtpQuery.set('TenantId', TenantId); + newOtpQuery.set('ExpiresAt', new Date(Date.now() + 10 * 60 * 1000)); await newOtpQuery.save(null, { useMasterKey: true }); // console.log("new otp Res in tempSendOtp ", newRes); } diff --git a/apps/OpenSignServer/cloud/parsefunction/TeamsAftersave.js b/apps/OpenSignServer/cloud/parsefunction/TeamsAftersave.js index 36566933b9..b1e482b0e7 100644 --- a/apps/OpenSignServer/cloud/parsefunction/TeamsAftersave.js +++ b/apps/OpenSignServer/cloud/parsefunction/TeamsAftersave.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function TeamsAftersave(req) { if (!req.original) { try { @@ -24,7 +25,7 @@ export default async function TeamsAftersave(req) { req.object.set('Ancestors', updatedAncestors); await req.object.save(null, { useMasterKey: true }); } catch (err) { - console.log('Err in team aftersave', err); + logger.info('Err in team aftersave', err); } } } diff --git a/apps/OpenSignServer/cloud/parsefunction/TemplateAfterSave.js b/apps/OpenSignServer/cloud/parsefunction/TemplateAfterSave.js index 4aa68fcc1f..0ed205126e 100644 --- a/apps/OpenSignServer/cloud/parsefunction/TemplateAfterSave.js +++ b/apps/OpenSignServer/cloud/parsefunction/TemplateAfterSave.js @@ -1,7 +1,8 @@ +import { logger } from '../../utils/logger.js'; export default async function TemplateAfterSave(request) { try { if (!request.original) { - console.log('new entry is insert in contracts_Template', request?.object?.id); + logger.info('new entry is insert in contracts_Template', request?.object?.id); const obj = request.object; const objId = obj?.id; const ip = request?.headers?.['x-real-ip'] || ''; @@ -30,8 +31,8 @@ export default async function TemplateAfterSave(request) { } } } catch (err) { - console.log('err in aftersave of contracts_Template'); - console.log(err); + logger.info('err in aftersave of contracts_Template'); + logger.info(err); } async function updateTemplateMeta({ objId, createdAt, ip, originIp }) { diff --git a/apps/OpenSignServer/cloud/parsefunction/TemplateBeforesave.js b/apps/OpenSignServer/cloud/parsefunction/TemplateBeforesave.js index a7fc693752..3ff279f020 100644 --- a/apps/OpenSignServer/cloud/parsefunction/TemplateBeforesave.js +++ b/apps/OpenSignServer/cloud/parsefunction/TemplateBeforesave.js @@ -1,5 +1,6 @@ import { MAX_DESCRIPTION_LENGTH, MAX_NAME_LENGTH, MAX_NOTE_LENGTH } from '../../Utils.js'; import { setTemplateCount } from '../../utils/CountUtils.js'; +import { logger } from '../../utils/logger.js'; async function TemplateBeforeSave(request) { if (!request.original) { @@ -37,7 +38,7 @@ async function TemplateBeforeSave(request) { } } } catch (err) { - console.log('err in template beforesave', err.message); + logger.info('err in template beforesave', err.message); } } export default TemplateBeforeSave; diff --git a/apps/OpenSignServer/cloud/parsefunction/UpdateExistUserAsAdmin.js b/apps/OpenSignServer/cloud/parsefunction/UpdateExistUserAsAdmin.js index f4e8d4c614..749cbba2d9 100644 --- a/apps/OpenSignServer/cloud/parsefunction/UpdateExistUserAsAdmin.js +++ b/apps/OpenSignServer/cloud/parsefunction/UpdateExistUserAsAdmin.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; async function updateUserExceptAdmin(data) { const Contracts = Parse.Object.extend('contracts_Users'); let skip = 0; @@ -30,9 +31,9 @@ async function updateUserExceptAdmin(data) { // Save all the updated entries await Parse.Object.saveAll(results, { useMasterKey: true }); - console.log(`${results.length} user roles updated successfully`); + logger.info(`${results.length} user roles updated successfully`); } catch (error) { - console.error('Error while updating user roles:', error); + logger.error('Error while updating user roles:', error); hasMore = false; // Stop if there's an error } } @@ -60,7 +61,7 @@ export default async function UpdateExistUserAsAdmin(request) { extCls.equalTo('Email', email); extCls.notEqualTo('IsDisabled', true); const extRes = await extCls.first({ useMasterKey: true }); - console.log('extRes ', extRes); + logger.info('extRes ', extRes); if (extRes) { const _extRes = JSON.parse(JSON.stringify(extRes)); const tenantId = { @@ -127,7 +128,7 @@ export default async function UpdateExistUserAsAdmin(request) { } } } catch (err) { - console.log('err in updateExistUserAsAdmin', err); + logger.info('err in updateExistUserAsAdmin', err); const code = err.code || 400; const msg = err.message || 'something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/VerifyEmail.js b/apps/OpenSignServer/cloud/parsefunction/VerifyEmail.js index 8c1f08d328..e96a811e83 100644 --- a/apps/OpenSignServer/cloud/parsefunction/VerifyEmail.js +++ b/apps/OpenSignServer/cloud/parsefunction/VerifyEmail.js @@ -5,42 +5,73 @@ export default async function VerifyEmail(request) { } else { let otpN = request.params.otp; let otp = parseInt(otpN); - let email = request.params.email; + let email = (request.params.email || '').toLowerCase().trim(); + if (!email) { + email = request?.user?.get('email'); + } //checking otp is correct or not which already save in defaultdata_Otp class const checkOtp = new Parse.Query('defaultdata_Otp'); checkOtp.equalTo('Email', email); checkOtp.equalTo('OTP', otp); - const res = await checkOtp.first({ useMasterKey: true }); - if (res) { - // Fetch the user by their objectId - const isEmailVerified = request?.user?.get('emailVerified'); - if (isEmailVerified) { - return { message: 'Email is already verified.' }; - } else { - const userQuery = new Parse.Query(Parse.User); - const user = await userQuery.get(request?.user.id, { - sessionToken: request?.user.getSessionToken(), - }); - - // Update the emailVerified field to true - user.set('emailVerified', true); - // Save the user object - const res = await user.save(null, { useMasterKey: true }); - if (res) { - return { message: 'Email is verified.' }; - } else { - const error = new Error('Something went wrong, please try again later!'); - error.code = 400; // Set the error code (e.g., 400 for bad request) - throw error; - } - } - } else { + const otpRecord = await checkOtp.first({ useMasterKey: true }); + if (!otpRecord) { const error = new Error('OTP is invalid.'); error.code = 400; // Set the error code (e.g., 400 for bad request) throw error; } + + // Fetch the user by their objectId + const userQuery = new Parse.Query(Parse.User); + const user = await userQuery.get(request?.user.id, { + sessionToken: request?.user.getSessionToken(), + }); + + const currentEmail = (user?.get('email') || '').toLowerCase().trim(); + const changingEmail = Boolean(email) && email !== currentEmail; + const isEmailVerified = request?.user?.get('emailVerified'); + + if (isEmailVerified && !changingEmail) { + return { message: 'Email is already verified.' }; + } + + if (changingEmail) { + // Sync the extended user first: if it fails the account is left + // untouched, instead of changing the login address with a stale profile. + const extQuery = new Parse.Query('contracts_Users'); + extQuery.equalTo('UserId', { + __type: 'Pointer', + className: '_User', + objectId: user.id, + }); + const extUser = await extQuery.first({ useMasterKey: true }); + if (extUser) { + extUser.set('Email', email); + extUser.set('NormalizedEmail', email); + await extUser.save(null, { useMasterKey: true }); + } + // The account address is the login name, so it has to move with it. + user.set('username', email); + user.set('email', email); + user.set('normalizedEmail', email); + } + // Update the emailVerified field to true + user.set('emailVerified', true); + // Save the user object + const saved = await user.save(null, { useMasterKey: true }); + if (!saved) { + const error = new Error('Something went wrong, please try again later!'); + error.code = 400; // Set the error code (e.g., 400 for bad request) + throw error; + } + + // The code is single use; a failed delete would leave it reusable. + await otpRecord.destroy({ useMasterKey: true }); + + return { + message: changingEmail ? 'Email changed and verified.' : 'Email is verified.', + }; } } catch (err) { console.log('err ', err.code + ' ' + err.message); diff --git a/apps/OpenSignServer/cloud/parsefunction/addUser.js b/apps/OpenSignServer/cloud/parsefunction/addUser.js index 0637877cb3..ed6c2fe2fa 100644 --- a/apps/OpenSignServer/cloud/parsefunction/addUser.js +++ b/apps/OpenSignServer/cloud/parsefunction/addUser.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function addUser(request) { const { phone, name, password, organization, team, tenantId, timezone, role } = request.params; const email = request.params?.email?.toLowerCase()?.replace(/\s/g, ''); @@ -125,7 +126,7 @@ export default async function addUser(request) { return parseData; } } catch (err) { - console.log('err ', err); + logger.info('err ', err); if (err.code === 202) { if (await existingUserQuery.first({ useMasterKey: true })) { throw new Parse.Error(Parse.Error.EMAIL_TAKEN, 'User already exists.'); diff --git a/apps/OpenSignServer/cloud/parsefunction/createBatchContact.js b/apps/OpenSignServer/cloud/parsefunction/createBatchContact.js index 0ccdbd1519..0a4cff8ff8 100644 --- a/apps/OpenSignServer/cloud/parsefunction/createBatchContact.js +++ b/apps/OpenSignServer/cloud/parsefunction/createBatchContact.js @@ -1,5 +1,6 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; const appId = serverAppId; const masterkey = process.env.MASTER_KEY; export default async function createBatchContact(req) { @@ -44,12 +45,12 @@ export default async function createBatchContact(req) { // console.info('createbatchcontact ', response.data); const successCount = response?.data?.filter(item => item.success).length; const failedCount = requests.length - successCount; - console.log( + logger.info( `createbatchcontact query response: success: ${successCount}, failed: ${failedCount}` ); return { success: successCount, failed: failedCount }; } catch (err) { - console.log('err while create batch contact', err); + logger.info('err while create batch contact', err); throw new Parse.Error(400, 'Something went wrong, please try again later'); } } else { diff --git a/apps/OpenSignServer/cloud/parsefunction/createBatchDocs.js b/apps/OpenSignServer/cloud/parsefunction/createBatchDocs.js index 14343be720..3260642a09 100644 --- a/apps/OpenSignServer/cloud/parsefunction/createBatchDocs.js +++ b/apps/OpenSignServer/cloud/parsefunction/createBatchDocs.js @@ -4,6 +4,7 @@ import { setDocumentCount } from '../../utils/CountUtils.js'; import crypto from 'crypto'; import sendSystemMail from './sendSystemMail.js'; +import { logger } from '../../utils/logger.js'; function chunkArray(arr, size) { const out = []; @@ -83,7 +84,7 @@ async function sendOwnerSummaryEmail({ await sendSystemMail({ params }); } catch (e) { - console.log('batchdoc Failed to send owner summary email:', e?.message || e); + logger.info('batchdoc Failed to send owner summary email:', e?.message || e); } } @@ -93,7 +94,7 @@ async function deductcount(docsCount, extUserId) { setDocumentCount(extUserId, docsCount); } } catch (err) { - console.log('batchdoc deductcount error: ', err); + logger.info('batchdoc deductcount error: ', err); } } async function sendMail(document, publicUrl) { @@ -111,9 +112,10 @@ async function sendMail(document, publicUrl) { const senderName = document?.SenderName || document.ExtUserPtr.Name; const senderEmail = document?.SenderMail || document.ExtUserPtr.Email; const from = - document?.SenderName || document?.ExtUserPtr?.UseNameAsSender === true + document?.SenderName || + (document?.ExtUserPtr?.UseNameAsSender === true ? document.ExtUserPtr.Name - : senderEmail; + : senderEmail); if (document.SendinOrder) { const getRole = signer => signer?.SignerRole || signer?.signer_role || signer?.role || 'signer'; @@ -190,7 +192,7 @@ async function sendMail(document, publicUrl) { }; await axios.post(url, params, { headers: headers }); } catch (error) { - console.log('batchdoc sendmail error: ', error); + logger.info('batchdoc sendmail error: ', error); } } } @@ -304,7 +306,7 @@ async function startBulkSendInBackground(userId, Documents, Ip, parseConfig, typ const newrequests = [requests?.[0]]; const response = await axios.post('batch', { requests: newrequests }, parseConfig); // Handle the batch query response - // console.log('Batch query response:', response.data); + // logger.info('Batch query response:', response.data); if (response.data && response.data.length > 0) { const document = Documents?.[0]; const updateDocuments = { @@ -326,8 +328,8 @@ export default async function createBatchDocs(request) { const Documents = JSON.parse(strDocuments); const Ip = request?.headers?.['x-real-ip'] || ''; - // Use the browser origin so signing links keep the custom domain. - let publicUrl = request.headers.origin || request.headers.public_url; + // public_url is resolved from the Origin only when it is an allowed domain. + let publicUrl = request.headers.public_url; const parseConfig = { baseURL: serverUrl, headers: { @@ -350,7 +352,7 @@ export default async function createBatchDocs(request) { // quicksend return await startBulkSendInBackground(userId, Documents, Ip, parseConfig, type, publicUrl); } catch (err) { - console.log('createbatchdoc error: ', err); + logger.info('createbatchdoc error: ', err); const code = err?.code || 400; const msg = err?.message || 'Something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/createDocumentFromApp.js b/apps/OpenSignServer/cloud/parsefunction/createDocumentFromApp.js index c7d56b6635..b3643b38e7 100644 --- a/apps/OpenSignServer/cloud/parsefunction/createDocumentFromApp.js +++ b/apps/OpenSignServer/cloud/parsefunction/createDocumentFromApp.js @@ -1,4 +1,5 @@ import { setDocumentCount } from '../../utils/CountUtils.js'; +import { logger } from '../../utils/logger.js'; export async function getOwnedDocumentFolder(folder, user, extUser) { if (!folder) return null; @@ -158,7 +159,7 @@ export default async function createDocumentFromApp(request) { return docRes; } catch (error) { - console.log('error in create document from app: ', error); + logger.info('error in create document from app: ', error); throw error; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/createDuplicate.js b/apps/OpenSignServer/cloud/parsefunction/createDuplicate.js index fb9252817c..e50fe904ae 100644 --- a/apps/OpenSignServer/cloud/parsefunction/createDuplicate.js +++ b/apps/OpenSignServer/cloud/parsefunction/createDuplicate.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function createDuplicate(request) { const templateId = request.params.templateId; @@ -106,7 +107,7 @@ export default async function createDuplicate(request) { ); } } catch (err) { - console.log('err while creating duplicate', err); + logger.info('err while creating duplicate', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/declinedocument.js b/apps/OpenSignServer/cloud/parsefunction/declinedocument.js index 418f3ed46f..59bb68f4d1 100644 --- a/apps/OpenSignServer/cloud/parsefunction/declinedocument.js +++ b/apps/OpenSignServer/cloud/parsefunction/declinedocument.js @@ -39,7 +39,7 @@ async function sendDeclineMail(doc, publicUrl, userId, reason) { }; await sendSystemMail({ params }); } catch (err) { - console.log('err in sendnotifymail', err); + logger.info('err in sendnotifymail', err); } } export default async function declinedocument(request) { @@ -88,7 +88,7 @@ export default async function declinedocument(request) { throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Document not found.'); } } catch (err) { - console.log('err while decling doc', err); + logger.info('err while decling doc', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/editContact.js b/apps/OpenSignServer/cloud/parsefunction/editContact.js index a57d1059e2..693bc302f5 100644 --- a/apps/OpenSignServer/cloud/parsefunction/editContact.js +++ b/apps/OpenSignServer/cloud/parsefunction/editContact.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function editContact(request) { const { contactId, name, email, phone, tenantId } = request.params; const company = request.params?.company; @@ -68,7 +69,7 @@ export default async function editContact(request) { return parseData; } } catch (err) { - console.log('err ', err); + logger.info('err ', err); if (err.code === 202) { const params = { email: email }; const userRes = await Parse.Cloud.run('getUserId', params); diff --git a/apps/OpenSignServer/cloud/parsefunction/fileUpload.js b/apps/OpenSignServer/cloud/parsefunction/fileUpload.js index cbf5e32ed5..097dc230f0 100644 --- a/apps/OpenSignServer/cloud/parsefunction/fileUpload.js +++ b/apps/OpenSignServer/cloud/parsefunction/fileUpload.js @@ -1,4 +1,5 @@ import { getSignedLocalUrl } from './getSignedUrl.js'; +import { logger } from '../../utils/logger.js'; export default async function fileUpload(request) { const url = request.params.url; @@ -7,7 +8,7 @@ export default async function fileUpload(request) { const urlwithjwt = getSignedLocalUrl(url, 200); return { url: urlwithjwt }; } catch (err) { - console.log('Err ', err); + logger.info('Err ', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/filterDocs.js b/apps/OpenSignServer/cloud/parsefunction/filterDocs.js index de2b9bf6be..4155d891fc 100644 --- a/apps/OpenSignServer/cloud/parsefunction/filterDocs.js +++ b/apps/OpenSignServer/cloud/parsefunction/filterDocs.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; /** * Escapes special characters in a string so it can safely be used in a RegExp. */ @@ -49,7 +50,7 @@ async function fetchDocumentsByName( try { return await query.find({ useMasterKey: true }); } catch (err) { - console.error('Error fetching contracts_Document by Name:', err); + logger.error('Error fetching contracts_Document by Name:', err); // Wrap low-level or network errors in a script-level error throw new Parse.Error( Parse.Error.SCRIPT_FAILED, @@ -76,7 +77,7 @@ export default async function filterDocs(request) { return docs; } catch (error) { // handle error - console.log('err while filtering doc', error); + logger.info('err while filtering doc', error); throw error; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/generateCertificatebydocId.js b/apps/OpenSignServer/cloud/parsefunction/generateCertificatebydocId.js index 38a7322dcd..a24b798614 100644 --- a/apps/OpenSignServer/cloud/parsefunction/generateCertificatebydocId.js +++ b/apps/OpenSignServer/cloud/parsefunction/generateCertificatebydocId.js @@ -1,13 +1,14 @@ import { SignPdf } from '@signpdf/signpdf'; -import { P12Signer } from '@signpdf/signer-p12'; import { pdflibAddPlaceholder } from '@signpdf/placeholder-pdf-lib'; import { PDFDocument } from 'pdf-lib'; import fs from 'node:fs'; import dotenv from 'dotenv'; import GenerateCertificate from './pdf/GenerateCertificate.js'; +import { IssuerPreservingP12Signer } from './pdf/IssuerPreservingP12Signer.js'; import { getSecureUrl } from '../../Utils.js'; import { parseUploadFile } from '../../utils/fileUtils.js'; import { resolveDeploymentBrand } from '../../utils/brandContext.js'; +import { isAuthenticated } from '../../utils/AuthUtils.js'; dotenv.config({ quiet: true }); const deploymentBrand = resolveDeploymentBrand(); const eSignName = deploymentBrand.digitalSignature.name; @@ -57,8 +58,26 @@ export default async function generateCertificatebydocId(req) { 'ExtUserPtr,Signers,AuditTrail.UserPtr,Placeholders,ExtUserPtr.TenantId,ExtUserPtr.UserId' ); const docRes = await getDocument.get(docId, { useMasterKey: true }); + // OriginIp is recorded at creation time by DocumentAftersave from the + // creator's request. Do not write it here: this endpoint is reachable by + // the recipient, so the value would be theirs. - if (docRes && docRes?.get('IsCompleted') && !docRes?.get('CertificateUrl')) { + if (docRes && docRes?.get('IsCompleted')) { + const existingCert = docRes?.get('CertificateUrl'); + if (existingCert) { + // Never hand a certificate of an OTP-protected document to an anonymous + // caller; the query above runs with the master key. + if (docRes?.get('IsEnableOTP')) { + const isAuth = await isAuthenticated(req?.user); + if (!isAuth) { + throw new Parse.Error( + Parse.Error.INVALID_SESSION_TOKEN, + 'User is not authenticated.' + ); + } + } + return { CertificateUrl: existingCert }; + } const _docRes = JSON.parse(JSON.stringify(docRes)); const filteredaudit = _docRes?.AuditTrail?.filter(x => x?.UserPtr?.objectId); // Create a reversed copy of the array and find the last object with 'signedOn' @@ -67,7 +86,9 @@ export default async function generateCertificatebydocId(req) { const doc = { ..._docRes, completedAt: completedAt }; const certificate = await GenerateCertificate(doc); const certificatePdf = await PDFDocument.load(certificate); - const p12 = new P12Signer(P12Buffer, { passphrase: process.env.PASS_PHRASE || null }); + const p12 = new IssuerPreservingP12Signer(P12Buffer, { + passphrase: process.env.PASS_PHRASE || null, + }); // `pdflibAddPlaceholder` is used to add code of only digital sign in certificate pdflibAddPlaceholder({ pdfDoc: certificatePdf, diff --git a/apps/OpenSignServer/cloud/parsefunction/getContact.js b/apps/OpenSignServer/cloud/parsefunction/getContact.js index 0b54c17c51..441a61573e 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getContact.js +++ b/apps/OpenSignServer/cloud/parsefunction/getContact.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function getContact(request) { const contactId = request.params.contactId; try { @@ -5,7 +6,7 @@ export default async function getContact(request) { const contactRes = await contactCls.get(contactId, { useMasterKey: true }); return contactRes; } catch (err) { - console.log('Err in contracts_Contactbook class ', err); + logger.info('Err in contracts_Contactbook class ', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/getDocument.js b/apps/OpenSignServer/cloud/parsefunction/getDocument.js index 0bd3c7c94e..e9865979f4 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getDocument.js +++ b/apps/OpenSignServer/cloud/parsefunction/getDocument.js @@ -1,5 +1,6 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; export default async function getDocument(request) { const serverUrl = cloudServerUrl; //process.env.SERVER_URL; const docId = request.params.docId; @@ -19,7 +20,22 @@ export default async function getDocument(request) { query.include('DeclineBy'); query.notEqualTo('IsArchive', true); if (include) { - query?.include(include); + const ALLOWED_INCLUDES = [ + 'Bcc', + 'Cc', + 'Signers', + 'Placeholders', + 'ExtUserPtr', + 'ExtUserPtr.TenantId', + 'CreatedBy', + 'AuditTrail.UserPtr', + 'DeclineBy', + ]; + const requested = String(include).split(',').map(s => s.trim()).filter(Boolean); + const safe = requested.filter(i => ALLOWED_INCLUDES.includes(i)); + if (safe.length) { + query?.include(safe.join(',')); + } } const res = await query.first({ useMasterKey: true }); if (res) { @@ -46,7 +62,7 @@ export default async function getDocument(request) { return { error: "You don't have access of this document!" }; } } catch (err) { - console.log('err user in not authenticated', err); + logger.info('err user in not authenticated', err); return { error: "You don't have access of this document!" }; } } else { @@ -57,14 +73,14 @@ export default async function getDocument(request) { return { error: "document deleted or you don't have access." }; } } catch (err) { - console.log('err', err); + logger.info('err', err); return err; } } else { return { error: 'Please pass required parameters!' }; } } catch (err) { - console.log('err', err); + logger.info('err', err); if (err.code == 209) { return { error: 'Invalid session token' }; } else { diff --git a/apps/OpenSignServer/cloud/parsefunction/getDrive.js b/apps/OpenSignServer/cloud/parsefunction/getDrive.js index 66f9340869..0cd5afe53f 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getDrive.js +++ b/apps/OpenSignServer/cloud/parsefunction/getDrive.js @@ -1,5 +1,6 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; export default async function getDrive(request) { const serverUrl = cloudServerUrl; //process.env.SERVER_URL; const appId = serverAppId; @@ -41,14 +42,14 @@ export default async function getDrive(request) { const res = await query.find({ useMasterKey: true }); return res; } catch (err) { - console.log('err', err); + logger.info('err', err); return { error: "You don't have access to drive" }; } } else { return { error: 'Please provide required parameter!' }; } } catch (err) { - console.log('err', err?.response?.data || err); + logger.info('err', err?.response?.data || err); if (err.code == 209) { return { error: 'Invalid session token' }; } else { diff --git a/apps/OpenSignServer/cloud/parsefunction/getReport.js b/apps/OpenSignServer/cloud/parsefunction/getReport.js index 48069fb78b..471708276c 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getReport.js +++ b/apps/OpenSignServer/cloud/parsefunction/getReport.js @@ -1,6 +1,7 @@ import { cloudServerUrl, serverAppId } from '../../Utils.js'; import reportJson, { applySearch } from './reportsJson.js'; import axios from 'axios'; +import { logger } from '../../utils/logger.js'; function buildClassesUrl({ serverUrl, clsName, paramsObj, keys, orderBy, skip, limit, include }) { const url = new URL(`${serverUrl}/classes/${clsName}`); url.searchParams.set('where', JSON.stringify(paramsObj)); @@ -86,7 +87,74 @@ export default async function getReport(request) { }; const orderBy = '-updatedAt'; - const include = 'AuditTrail.UserPtr,Placeholders.signerPtr,ExtUserPtr.TenantId'; + const isCompletedReport = reportId === 'kQUoW4hUXz'; + const include = isCompletedReport + ? 'AuditTrail.UserPtr,Placeholders.signerPtr' + : 'AuditTrail.UserPtr,Placeholders.signerPtr,ExtUserPtr.TenantId'; + + // For the completed report, split the $or (CreatedBy vs Signers $inQuery) + // into two index-friendly queries and merge/dedupe to avoid collection scans. + if (isCompletedReport && paramsObj && paramsObj.$or) { + const { $or, ...baseWhere } = paramsObj; + const userPtr = { __type: 'Pointer', className: '_User', objectId: userId }; + const whereA = { ...baseWhere, CreatedBy: userPtr }; + const whereB = { + ...baseWhere, + Signers: { + $inQuery: { + where: { UserId: userPtr }, + className: 'contracts_Contactbook', + }, + }, + }; + + const urlA = buildClassesUrl({ + serverUrl, + clsName, + paramsObj: whereA, + keys: json.keys || [], + orderBy, + skip: 0, + limit: Number(limit) + Number(skip) || 100, + include, + }); + const urlB = buildClassesUrl({ + serverUrl, + clsName, + paramsObj: whereB, + keys: json.keys || [], + orderBy, + skip: 0, + limit: Number(limit) + Number(skip) || 100, + include, + }); + + const [resA, resB] = await Promise.all([ + axios.get(urlA, { headers: headers }), + axios.get(urlB, { headers: headers }), + ]); + + const merged = []; + const seen = new Set(); + for (const r of [resA, resB]) { + const results = r?.data?.results || []; + for (const doc of results) { + if (doc?.objectId && !seen.has(doc.objectId)) { + seen.add(doc.objectId); + merged.push(doc); + } + } + } + // sort by updatedAt desc + merged.sort((a, b) => { + const da = new Date(a?.updatedAt || 0).getTime(); + const db = new Date(b?.updatedAt || 0).getTime(); + return db - da; + }); + const s = Number(skip) || 0; + const l = Number(limit) || 20; + return merged.slice(s, s + l); + } const url = buildClassesUrl({ serverUrl, @@ -109,7 +177,7 @@ export default async function getReport(request) { } } catch (err) { const message = err?.response?.data?.error || err?.message || 'Something went wrong'; - console.log('getreport error:', message); + logger.info('getreport error:', message); if (err.code == 209) { return { error: 'Invalid session token' }; } else { diff --git a/apps/OpenSignServer/cloud/parsefunction/getSignature.js b/apps/OpenSignServer/cloud/parsefunction/getSignature.js index 5517090713..b070cb99d5 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getSignature.js +++ b/apps/OpenSignServer/cloud/parsefunction/getSignature.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function getSignature(request) { const { userId } = request.params; if (!userId) { @@ -12,7 +13,7 @@ export default async function getSignature(request) { const result = await query.first({ useMasterKey: true }); return result; } catch (err) { - console.error('Error fetching signature:', err); + logger.error('Error fetching signature:', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/getSignedUrl.js b/apps/OpenSignServer/cloud/parsefunction/getSignedUrl.js index 81369968cf..4c6afbb645 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getSignedUrl.js +++ b/apps/OpenSignServer/cloud/parsefunction/getSignedUrl.js @@ -1,6 +1,6 @@ import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl as presign } from '@aws-sdk/s3-request-presigner'; -import { useLocal } from '../../Utils.js'; +import { useLocal } from '../../utils/appConfig.js'; import jwt from 'jsonwebtoken'; import dotenv from 'dotenv'; import { isAuthenticated } from '../../utils/AuthUtils.js'; @@ -70,28 +70,73 @@ export async function getSignedUrl(request) { if (docId || templateId) { try { + const query = new Parse.Query(docId ? 'contracts_Document' : 'contracts_Template'); + query.equalTo('objectId', docId ? docId : templateId); + query.include('ExtUserPtr.TenantId'); + if (templateId) { + // Widget assets (image/draw) live inside the template placeholders. + query.include('Placeholders'); + } + query.notEqualTo('IsArchive', true); + const res = await query.first({ useMasterKey: true }); + if (!res) { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Document not found.'); + } + + const _resDoc = res?.toJSON(); + // Ensure user is authenticated if OTP is required + if (_resDoc?.IsEnableOTP) { + const isAuth = await isAuthenticated(request?.user); + if (!isAuth) { + throw new Parse.Error( + Parse.Error.INVALID_SESSION_TOKEN, + 'User is not authenticated.' + ); + } + } + + // Bind the requested URL to the fetched document/template to prevent + // arbitrary-object presigning (including /files/ token minting). + // Compare by basename to tolerate query strings / trailing slashes. + const basename = (u) => String(u || '').split('?')[0].split('/').pop(); + const allowedUrls = [ + _resDoc?.URL, + _resDoc?.SignedUrl, + _resDoc?.CertificateUrl, + ].filter(Boolean); + // Templates also keep image/draw widget assets inside their placeholders, + // and the bulk-send flow asks for a signed URL of those assets. + if (templateId && Array.isArray(_resDoc?.Placeholders)) { + _resDoc.Placeholders.forEach((holder) => { + const pages = Array.isArray(holder?.placeHolder) ? holder.placeHolder : []; + pages.forEach((page) => { + const widgets = Array.isArray(page?.pos) ? page.pos : []; + widgets.forEach((widget) => { + [widget?.options?.response, widget?.options?.defaultValue].forEach( + (value) => { + if (typeof value === 'string' && value && !value.startsWith('data:')) { + allowedUrls.push(value); + } + } + ); + }); + }); + }); + } + // A record with no allowed URL must deny, otherwise any /files/ path + // could be signed through a folder record. + const urlBase = basename(url); + const isAllowed = allowedUrls.some((u) => basename(u) === urlBase); + if (!isAllowed) { + throw new Parse.Error( + Parse.Error.OPERATION_FORBIDDEN, + 'URL not associated with this document.' + ); + } + if (url?.includes('/files/')) { return presignedlocalUrl(url); } else if (useLocal !== 'true') { - const query = new Parse.Query(docId ? 'contracts_Document' : 'contracts_Template'); - query.equalTo('objectId', docId ? docId : templateId); - query.include('ExtUserPtr.TenantId'); - query.notEqualTo('IsArchive', true); - const res = await query.first({ useMasterKey: true }); - if (!res) return url; - - const _resDoc = res?.toJSON(); - // Ensure user is authenticated if OTP is required - if (_resDoc?.IsEnableOTP) { - const isAuth = await isAuthenticated(request?.user); - if (!isAuth) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'User is not authenticated.' - ); - } - } - const presignedUrl = await getPresignedUrl(url); return presignedUrl; } else { @@ -107,7 +152,8 @@ export async function getSignedUrl(request) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'User is not authenticated.'); } else { if (url?.includes('/files/')) { - return presignedlocalUrl(url); + const presignedUrl = await getPresignedUrl(url); + return presignedUrl; } else if (useLocal !== 'true') { const presignedUrl = await getPresignedUrl(url); return presignedUrl; @@ -128,7 +174,7 @@ export async function getSignedUrl(request) { // Function to generate a signed URL with JWT export function getSignedLocalUrl(fileUrl, expirationTimeInSeconds) { const secretKey = process.env.MASTER_KEY; - const exp = expirationTimeInSeconds || 200; + const exp = expirationTimeInSeconds || 3600; try { // Create the payload with the file URL and expiration time const payload = { @@ -150,7 +196,7 @@ export function presignedlocalUrl(signedUrl, expirationTimeInSeconds) { if (signedUrl?.includes('/files/')) { const fileUrl = signedUrl.split('?')?.[0]; const secretKey = process.env.MASTER_KEY; - const exp = expirationTimeInSeconds || 200; + const exp = expirationTimeInSeconds || 3600; try { // Create the payload with the file URL and expiration time const payload = { @@ -180,7 +226,7 @@ export async function validateSignedLocalUrl(signedUrl) { const secretKey = process.env.MASTER_KEY; // Now verify the token (validate signature and expiration automatically) const decoded = jwt.verify(token, secretKey); - // Check if the file URL in the JWT matches the requested file URL + // Check if the file URL in the token matches the requested file URL const fileUrl = signedUrl.split('?')[0]; if (decoded.fileUrl !== fileUrl) { throw new Error('Invalid file URL in token.'); @@ -191,4 +237,4 @@ export async function validateSignedLocalUrl(signedUrl) { console.log('Error validating file', error.message); return 'Unauthorized'; } -} +} \ No newline at end of file diff --git a/apps/OpenSignServer/cloud/parsefunction/getSigners.js b/apps/OpenSignServer/cloud/parsefunction/getSigners.js index 48bde122ad..1807aa0b4d 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getSigners.js +++ b/apps/OpenSignServer/cloud/parsefunction/getSigners.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; // Function to escape special characters in the search string function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape special characters @@ -24,7 +25,7 @@ async function getContacts(searchObj, isJWT) { const _contactRes = JSON.parse(JSON.stringify(contactRes)); return _contactRes; } catch (err) { - console.log('err while fetch contacts', err); + logger.info('err while fetch contacts', err); throw err; } } @@ -39,7 +40,7 @@ export default async function getSigners(request) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Invalid session token'); } } catch (err) { - console.log('err in get signers', err); + logger.info('err in get signers', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/getTeams.js b/apps/OpenSignServer/cloud/parsefunction/getTeams.js index 5d692965bd..54ab4e82ba 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getTeams.js +++ b/apps/OpenSignServer/cloud/parsefunction/getTeams.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function getTeams(request) { const activeTeams = request.params.active; if (!request?.user) { @@ -30,7 +31,7 @@ export default async function getTeams(request) { return []; } } catch (err) { - console.log('err in getTeams', err); + logger.info('err in getTeams', err); const code = err?.code || 400; const msg = err?.message || 'Something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/getTenant.js b/apps/OpenSignServer/cloud/parsefunction/getTenant.js index b14dc20e89..bbdcbc9f3a 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getTenant.js +++ b/apps/OpenSignServer/cloud/parsefunction/getTenant.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; async function getTenantByUserId(userId, contactId) { try { if (contactId) { @@ -43,7 +44,7 @@ async function getTenantByUserId(userId, contactId) { } } } catch (err) { - console.log('err in getTenant ', err); + logger.info('err in getTenant ', err); return 'user does not exist!'; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js b/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js index 5feb7e16c0..673fdf4f37 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js +++ b/apps/OpenSignServer/cloud/parsefunction/getUserDetails.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; async function getUserDetails(request) { const reqEmail = request.params.email; if (reqEmail || request.user) { @@ -31,7 +32,7 @@ async function getUserDetails(request) { return ''; } } catch (err) { - console.log('Err ', err); + logger.info('Err ', err); const code = err?.code || 400; const msg = err?.message || 'Something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/getUserId.js b/apps/OpenSignServer/cloud/parsefunction/getUserId.js index 6331f46505..b815b17c46 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getUserId.js +++ b/apps/OpenSignServer/cloud/parsefunction/getUserId.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; async function getUserId(request) { try { const username = request.params.username; @@ -11,7 +12,7 @@ async function getUserId(request) { const user = await query.first({ useMasterKey: true }); return { id: user.id }; } catch (err) { - console.log('err', err); + logger.info('err', err); return err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/getUserListByOrg.js b/apps/OpenSignServer/cloud/parsefunction/getUserListByOrg.js index 9b532de598..68ff02faa2 100644 --- a/apps/OpenSignServer/cloud/parsefunction/getUserListByOrg.js +++ b/apps/OpenSignServer/cloud/parsefunction/getUserListByOrg.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function getUserListByOrg(req) { const OrganizationId = req.params.organizationId; const orgPtr = { @@ -54,7 +55,7 @@ export default async function getUserListByOrg(req) { return []; } } catch (err) { - console.log('err in getuserlist', err); + logger.info('err in getuserlist', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/isUserInContactBook.js b/apps/OpenSignServer/cloud/parsefunction/isUserInContactBook.js index f34654e127..68e7e283a6 100644 --- a/apps/OpenSignServer/cloud/parsefunction/isUserInContactBook.js +++ b/apps/OpenSignServer/cloud/parsefunction/isUserInContactBook.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function isUserInContactBook(request) { try { if (request.user) { @@ -11,7 +12,7 @@ export default async function isUserInContactBook(request) { return res; } } catch (err) { - console.log('err', err); + logger.info('err', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/isextenduser.js b/apps/OpenSignServer/cloud/parsefunction/isextenduser.js index 84111597e6..afc81808c3 100644 --- a/apps/OpenSignServer/cloud/parsefunction/isextenduser.js +++ b/apps/OpenSignServer/cloud/parsefunction/isextenduser.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; /** * Checks if a user exists in the extended class 'contracts_Users' based on the provided email. * @param email - The request contains parameters, such as the user's email. @@ -22,7 +23,7 @@ export default async function isextenduser(request) { } } catch (err) { // Handle errors - console.log('Error in userexist', err); + logger.info('Error in userexist', err); const code = err?.code || 400; const message = err?.message || 'Something went wrong.'; throw new Parse.Error(code, message); diff --git a/apps/OpenSignServer/cloud/parsefunction/linkContactToDoc.js b/apps/OpenSignServer/cloud/parsefunction/linkContactToDoc.js index 592c3511e5..0717c586a2 100644 --- a/apps/OpenSignServer/cloud/parsefunction/linkContactToDoc.js +++ b/apps/OpenSignServer/cloud/parsefunction/linkContactToDoc.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; // `saveRoleContact` is used to save user in contracts_Guest role and create contact const saveRoleContact = async contact => { const contactQuery = new Parse.Object('contracts_Contactbook'); @@ -275,7 +276,7 @@ export default async function linkContactToDoc(req) { } } } catch (err) { - console.log('Err while creating contact link to doc', err); + logger.info('Err while creating contact link to doc', err); } } else { throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'User not found.'); @@ -288,7 +289,7 @@ export default async function linkContactToDoc(req) { throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Document not found.'); } } catch (err) { - console.log('err in linkcontacttodoc', err); + logger.info('err in linkcontacttodoc', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/loginUser.js b/apps/OpenSignServer/cloud/parsefunction/loginUser.js index 11f622678e..85cd726a83 100644 --- a/apps/OpenSignServer/cloud/parsefunction/loginUser.js +++ b/apps/OpenSignServer/cloud/parsefunction/loginUser.js @@ -1,26 +1,158 @@ -import crypto from 'node:crypto'; +import { logger } from '../../utils/logger.js'; +import { getLdapConfig } from '../../utils/ldapConfig.js'; +import { authenticateLdap } from '../../utils/ldapAuth.js'; + +function normalizeEmail(email) { + return String(email || '') + .toLowerCase() + .replace(/\s/g, ''); +} + +async function findOrCreateTenant(userId) { + const partnerQuery = new Parse.Query('partners_Tenant'); + partnerQuery.equalTo('IsActive', true); + let tenant = await partnerQuery.first({ useMasterKey: true }); + if (!tenant) { + const partnerCls = Parse.Object.extend('partners_Tenant'); + tenant = new partnerCls(); + tenant.set('TenantName', 'Organization'); + tenant.set('IsActive', true); + if (userId) { + tenant.set('UserId', { + __type: 'Pointer', + className: '_User', + objectId: userId, + }); + tenant.set('CreatedBy', { + __type: 'Pointer', + className: '_User', + objectId: userId, + }); + } + await tenant.save(null, { useMasterKey: true }); + } + return tenant; +} + export default async function loginUser(request) { const username = request.params.email; const password = request.params.password; - if (username && password) { + if (!username || !password) { + throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'username/password is missing.'); + } + + const ldapConfig = getLdapConfig(process.env); + + // 1. LDAP Authentication & Auto-Provisioning (if enabled) + if (ldapConfig.enabled) { try { - // Pass the username and password to logIn function - const user = await Parse.User.logIn(username, password); - // console.log('user ', user); - if (user) { - const _user = user?.toJSON(); + const ldapResult = await authenticateLdap(username, password, ldapConfig); + if (ldapResult && ldapResult.authenticated) { + logger.info(`[LDAP] User "${username}" successfully authenticated via LDAP`); + + const attrs = ldapResult.attributes || {}; + let email = attrs[ldapConfig.emailAttr] || attrs.mail || attrs.userPrincipalName || ''; + if (Array.isArray(email)) email = email[0]; + + if (!email && username.includes('@')) { + email = username; + } else if (!email) { + const defaultDomain = process.env.LDAP_DEFAULT_DOMAIN || 'ldap.local'; + email = `${username}@${defaultDomain}`; + } + email = normalizeEmail(email); + + let displayName = + attrs[ldapConfig.nameAttr] || attrs.displayName || attrs.cn || attrs.name || ''; + if (Array.isArray(displayName)) displayName = displayName[0]; + if (!displayName) displayName = username; + + let phone = attrs[ldapConfig.phoneAttr] || attrs.telephoneNumber || attrs.mobile || ''; + if (Array.isArray(phone)) phone = phone[0]; + + // Lookup existing user by email or username + const emailQuery = new Parse.Query(Parse.User); + emailQuery.equalTo('email', email); + let parseUser = await emailQuery.first({ useMasterKey: true }); + + if (!parseUser && username !== email) { + const usernameQuery = new Parse.Query(Parse.User); + usernameQuery.equalTo('username', username); + parseUser = await usernameQuery.first({ useMasterKey: true }); + } + + if (parseUser) { + // Sync password so Parse authentication succeeds + parseUser.setPassword(password); + parseUser.set('emailVerified', true); + if (displayName && !parseUser.get('name')) { + parseUser.set('name', displayName); + } + await parseUser.save(null, { useMasterKey: true }); + } else { + // Auto-provision new user from LDAP + parseUser = new Parse.User(); + parseUser.set('username', email); + parseUser.set('email', email); + parseUser.set('name', displayName); + parseUser.set('password', password); + parseUser.set('emailVerified', true); + if (phone) parseUser.set('phone', phone); + await parseUser.signUp(); + + const totalUsers = await new Parse.Query('contracts_Users').count({ useMasterKey: true }); + const role = + totalUsers === 0 ? 'contracts_Admin' : ldapConfig.defaultRole || 'contracts_User'; + + const tenant = await findOrCreateTenant(parseUser.id); + + const extCls = Parse.Object.extend('contracts_Users'); + const extUser = new extCls(); + extUser.set('UserId', { + __type: 'Pointer', + className: '_User', + objectId: parseUser.id, + }); + extUser.set('UserRole', role); + extUser.set('Email', email); + extUser.set('Name', displayName); + if (phone) extUser.set('Phone', phone); + extUser.set('TenantId', { + __type: 'Pointer', + className: 'partners_Tenant', + objectId: tenant.id, + }); + await extUser.save(null, { useMasterKey: true }); + logger.info(`[LDAP] Auto-provisioned user "${email}" with role "${role}"`); + } + + const loginIdentifier = parseUser.get('username') || email; + const loggedInUser = await Parse.User.logIn(loginIdentifier, password); return { - ..._user, + ...loggedInUser.toJSON(), }; - } else { - throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'user not found.'); } - } catch (err) { - console.log('err in login user', err); - throw err; + } catch (ldapErr) { + logger.error(`[LDAP] Error during LDAP login for "${username}": ${ldapErr.message}`); + if (!ldapConfig.allowFallback) { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'LDAP authentication failed.'); + } } - } else { - throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'username/password is missing.'); + } + + // 2. Standard Parse User login (or fallback) + try { + const user = await Parse.User.logIn(username, password); + if (user) { + return { + ...user.toJSON(), + }; + } else { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'user not found.'); + } + } catch (err) { + logger.info('err in login user', err); + throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/manageSign.js b/apps/OpenSignServer/cloud/parsefunction/manageSign.js index d67c07177c..a6a62dfc53 100644 --- a/apps/OpenSignServer/cloud/parsefunction/manageSign.js +++ b/apps/OpenSignServer/cloud/parsefunction/manageSign.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function manageSign(request) { const { signature, userId, initials, id, title, stamp } = request.params; @@ -23,7 +24,7 @@ export default async function manageSign(request) { const signRes = await signatureCls.save(null, { useMasterKey: true }); return signRes; } catch (err) { - console.error('Error saving signature:', err); + logger.error('Error saving signature:', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/pdf/GenerateCertificate.js b/apps/OpenSignServer/cloud/parsefunction/pdf/GenerateCertificate.js index fc3e8d62f0..91af455d0c 100644 --- a/apps/OpenSignServer/cloud/parsefunction/pdf/GenerateCertificate.js +++ b/apps/OpenSignServer/cloud/parsefunction/pdf/GenerateCertificate.js @@ -67,6 +67,8 @@ export default async function GenerateCertificate(docDetails) { const textWidth = timesRomanFont.widthOfTextAtSize(generatedOn, 12); const margin = 30; const maxX = width - margin - textWidth; // Ensures text stays inside the border with 30px margin + // Only the IP recorded at creation identifies the originator; audit entries + // belong to recipients (Viewed / Signed). const OriginIp = docDetails?.OriginIp || ''; const company = docDetails?.ExtUserPtr?.Company || ''; const documentHash = docDetails?.DocumentHash || ''; diff --git a/apps/OpenSignServer/cloud/parsefunction/pdf/IssuerPreservingP12Signer.js b/apps/OpenSignServer/cloud/parsefunction/pdf/IssuerPreservingP12Signer.js new file mode 100644 index 0000000000..95b8ecfab6 --- /dev/null +++ b/apps/OpenSignServer/cloud/parsefunction/pdf/IssuerPreservingP12Signer.js @@ -0,0 +1,58 @@ +import forge from 'node-forge'; +import { P12Signer } from '@signpdf/signer-p12'; + +const { asn1, pki } = forge; + +const toDer = node => asn1.toDer(node).getBytes(); + +// TBSCertificate: [0] version (optional), serialNumber, signature, issuer, ... +function readIssuerAndSerial(certificate) { + const tbsFields = certificate.value[0].value; + const offset = tbsFields[0].tagClass === asn1.Class.CONTEXT_SPECIFIC ? 1 : 0; + return { serial: tbsFields[offset], issuer: tbsFields[offset + 2] }; +} + +/** + * Replaces the issuer in the CMS SignerInfo with the exact issuer of the signing certificate. + * @param {Buffer} signature - DER encoded CMS ContentInfo with one SignerInfo, as built by forge + * @returns {Buffer} the CMS, or the same buffer when the issuer was already encoded faithfully + */ +function restoreSignerIssuer(signature) { + const contentInfo = asn1.fromDer(forge.util.createBuffer(signature.toString('binary'))); + const signedData = contentInfo.value[1].value[0].value; + const certificates = signedData.find( + field => field.tagClass === asn1.Class.CONTEXT_SPECIFIC && field.type === 0 + ).value; + const signerIdentifier = signedData.at(-1).value[0].value[1]; + const [signerIssuer, signerSerial] = signerIdentifier.value; + const signerIssuerDer = toDer(signerIssuer); + + // A chain can reuse a serial number across issuers, so also match on the issuer as forge wrote it. + const signingCertificate = certificates.map(readIssuerAndSerial).find(({ issuer, serial }) => { + const attributes = pki.RDNAttributesAsArray(issuer); + return ( + serial.value === signerSerial.value && + toDer(pki.distinguishedNameToAsn1({ attributes })) === signerIssuerDer + ); + }); + if (!signingCertificate || toDer(signingCertificate.issuer) === signerIssuerDer) { + return signature; + } + signerIdentifier.value[0] = signingCertificate.issuer; + return Buffer.from(toDer(contentInfo), 'binary'); +} + +/** + * P12Signer whose SignerInfo always identifies the signing certificate. + * + * forge keeps certificate name values as raw bytes but UTF-8 encodes UTF8String values again when + * it writes the SignerInfo, and it flattens multi-valued RDNs. A non-ASCII issuer therefore no + * longer matches the embedded certificate, and verifiers reject the signature because they cannot + * find the signer's certificate. The issuer is outside the signed attributes, so correcting it + * after signing leaves the signature valid. + */ +export class IssuerPreservingP12Signer extends P12Signer { + async sign(pdfBuffer, signingTime) { + return restoreSignerIssuer(await super.sign(pdfBuffer, signingTime)); + } +} diff --git a/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.js b/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.js index c2014fb7ee..9879657b35 100644 --- a/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.js +++ b/apps/OpenSignServer/cloud/parsefunction/pdf/PDF.js @@ -19,7 +19,7 @@ import GenerateCertificate from './GenerateCertificate.js'; import { pdflibAddPlaceholder } from '@signpdf/placeholder-pdf-lib'; import { Placeholder } from './Placeholder.js'; import { SignPdf } from '@signpdf/signpdf'; -import { P12Signer } from '@signpdf/signer-p12'; +import { IssuerPreservingP12Signer } from './IssuerPreservingP12Signer.js'; import { buildDownloadFilename, parseUploadFile } from '../../../utils/fileUtils.js'; import sendMailWithAttachment from '../sendMailWithAttachment.js'; import sendSystemMail from '../sendSystemMail.js'; @@ -311,7 +311,7 @@ async function sendMailsaveCertifcate(doc, pfx, isCustomMail, mailProvider, file const certificate = await GenerateCertificate(doc); const certificatePdf = await PDFDocument.load(certificate); const P12Buffer = fs.readFileSync(pfx.name); - const p12 = new P12Signer(P12Buffer, { passphrase: pfx.passphrase || null }); + const p12 = new IssuerPreservingP12Signer(P12Buffer, { passphrase: pfx.passphrase || null }); // `pdflibAddPlaceholder` is used to add code of only digitial sign in certificate pdflibAddPlaceholder({ pdfDoc: certificatePdf, @@ -361,12 +361,24 @@ async function sendMailsaveCertifcate(doc, pfx, isCustomMail, mailProvider, file */ async function processPdf(_resDoc, PdfBuffer, reason) { // No CC merge; operate directly on the original PDF - const pdfDoc = await PDFDocument.load(PdfBuffer); - const form = pdfDoc.getForm(); - // Updates the field appearances to ensure visual changes are reflected. - form.updateFieldAppearances(); - // Flattens the form, converting all form fields into non-editable, static content - form.flatten(); + const pdfDoc = await PDFDocument.load(PdfBuffer, { ignoreEncryption: true }); + try { + const form = pdfDoc.getForm(); + // Updates the field appearances to ensure visual changes are reflected. + if (form && typeof form.updateFieldAppearances === 'function') { + form.updateFieldAppearances(); + } + // Flattens the form, converting all form fields into non-editable, static content + if (form && typeof form.flatten === 'function') { + form.flatten(); + } + } catch (e) { + // A PDF without a usable form must not abort the signing. + console.log('processPdf form flatten skipped:', e?.message); + } + // The placeholder registers /ByteRange and /Contents before it attaches the + // signature field. Saving after a failure would leave an orphaned placeholder + // that the signer can fill without a registered signature, so abort instead. Placeholder({ pdfDoc: pdfDoc, reason: `Digitally signed by ${eSignName} for ${reason}`, @@ -375,7 +387,11 @@ async function processPdf(_resDoc, PdfBuffer, reason) { contactInfo: eSigncontact, signatureLength: 16000, }); - const pdfWithPlaceholderBytes = await pdfDoc.save(); + // Appearances were already updated above; saving with the default would run + // the same update again outside the guard and could abort the signing. + const pdfWithPlaceholderBytes = await pdfDoc.save({ + updateFieldAppearances: false, + }); return Buffer.from(pdfWithPlaceholderBytes); } /** @@ -402,9 +418,14 @@ async function PDF(req) { docQuery.equalTo('objectId', docId); docQuery.notEqualTo('IsDeclined', true); docQuery.notEqualTo('IsArchive', true); + docQuery.notEqualTo('IsCompleted', true); const resDoc = await docQuery.first({ useMasterKey: true }); if (!resDoc) { - throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Document not found.'); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Document not found or no longer signable.'); + } + const expiryDate = resDoc?.get('ExpiryDate'); + if (expiryDate && new Date(expiryDate) < new Date()) { + throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Document has expired and can no longer be signed.'); } const IsEnableOTP = resDoc?.get('IsEnableOTP') || false; // if `IsEnableOTP` is false then we don't have to check authentication @@ -451,7 +472,7 @@ async function PDF(req) { } const username = signUser.Name; const userEmail = signUser.Email; - if (req.params.pdfFile) { + if (req.params.pdfFile && typeof req.params.pdfFile === 'string') { // `PdfBuffer` used to create buffer from pdf file let PdfBuffer = Buffer.from(req.params.pdfFile, 'base64'); // `P12Buffer` used to create buffer from p12 certificate @@ -462,6 +483,12 @@ async function PDF(req) { passphrase = _resDoc?.ExtUserPtr?.TenantId?.PfxFile?.password; } const pfx = { name: pfxname, passphrase: passphrase }; + if (!pfxFile) { + throw new Parse.Error( + Parse.Error.SCRIPT_FAILED, + 'PFX certificate is not configured (PFX_BASE64 missing).' + ); + } const P12Buffer = Buffer.from(pfxFile, 'base64'); fs.writeFileSync(pfxname, P12Buffer); const UserPtr = { __type: 'Pointer', className: className, objectId: signUser.objectId }; @@ -503,7 +530,9 @@ async function PDF(req) { signersName && signersName.length > 0 ? signersName?.join(', ') : username + ' <' + userEmail + '>'; - const p12Cert = new P12Signer(P12Buffer, { passphrase: passphrase || null }); + const p12Cert = new IssuerPreservingP12Signer(P12Buffer, { + passphrase: passphrase || null, + }); signedFilePath = `./exports/signed_${name}`; PdfBuffer = await processPdf(_resDoc, PdfBuffer, reason, UserPtr, userIP, sign); //`new signPDF` create new instance of pdfBuffer and p12Buffer diff --git a/apps/OpenSignServer/cloud/parsefunction/recreateDocument.js b/apps/OpenSignServer/cloud/parsefunction/recreateDocument.js index c9431a9e1d..5654ef1884 100644 --- a/apps/OpenSignServer/cloud/parsefunction/recreateDocument.js +++ b/apps/OpenSignServer/cloud/parsefunction/recreateDocument.js @@ -1,4 +1,5 @@ import { setDocumentCount } from '../../utils/CountUtils.js'; +import { logger } from '../../utils/logger.js'; export default async function recreateDocument(request) { const { docId } = request.params; @@ -54,15 +55,15 @@ export default async function recreateDocument(request) { } else { createDoc.set(key, value); } - // console.log(`${key}: ${value}`); + // logger.info(`${key}: ${value}`); }); const createDocRes = await createDoc.save(null, { useMasterKey: true }); - // console.log('createDocRes', createDocRes); + // logger.info('createDocRes', createDocRes); const newDoc = JSON.parse(JSON.stringify(createDocRes)); setDocumentCount(_docRes?.ExtUserPtr?.objectId); return { objectId: newDoc.objectId, createdAt: newDoc.createdAt, updatedAt: newDoc.updatedAt }; } catch (err) { - console.log('err in recreate document', err); + logger.info('err in recreate document', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/resetPassword.js b/apps/OpenSignServer/cloud/parsefunction/resetPassword.js index cd93650f0d..b9b6f320b4 100644 --- a/apps/OpenSignServer/cloud/parsefunction/resetPassword.js +++ b/apps/OpenSignServer/cloud/parsefunction/resetPassword.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function resetPassword(request) { const userId = request.params.userId; const newPassword = request.params.password; @@ -56,7 +57,7 @@ export default async function resetPassword(request) { return { status: 'success', message: 'Password has been reset.' }; } catch (error) { - console.error('Error while resetting password:', error); + logger.error('Error while resetting password:', error); throw error; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/saveAsTemplate.js b/apps/OpenSignServer/cloud/parsefunction/saveAsTemplate.js index 6f52f4cd5f..aa9b9b7973 100644 --- a/apps/OpenSignServer/cloud/parsefunction/saveAsTemplate.js +++ b/apps/OpenSignServer/cloud/parsefunction/saveAsTemplate.js @@ -1,4 +1,5 @@ import { randomId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; export default async function saveAsTemplate(request) { const docId = request.params.docId; @@ -139,7 +140,7 @@ export default async function saveAsTemplate(request) { throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'document not found.'); } } catch (err) { - console.log('Err in save as template', err); + logger.info('Err in save as template', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/saveFile.js b/apps/OpenSignServer/cloud/parsefunction/saveFile.js index 9f983fe24e..cd5ca0ffad 100644 --- a/apps/OpenSignServer/cloud/parsefunction/saveFile.js +++ b/apps/OpenSignServer/cloud/parsefunction/saveFile.js @@ -1,5 +1,6 @@ import { flattenPdf, getSecureUrl } from '../../Utils.js'; import { parseUploadFile } from '../../utils/fileUtils.js'; +import { logger } from '../../utils/logger.js'; export default async function saveFile(request) { if (!request.params.fileBase64) { @@ -50,7 +51,7 @@ export default async function saveFile(request) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'User is not authenticated.'); } } catch (err) { - console.log('err in savetoS3', err); + logger.info('err in savetoS3', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/savecontact.js b/apps/OpenSignServer/cloud/parsefunction/savecontact.js index 8bf497bf87..733432c9cb 100644 --- a/apps/OpenSignServer/cloud/parsefunction/savecontact.js +++ b/apps/OpenSignServer/cloud/parsefunction/savecontact.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function savecontact(request) { const name = request.params.name; const phone = request.params.phone; @@ -63,7 +64,7 @@ export default async function savecontact(request) { return parseData; } } catch (err) { - console.log('err ', err); + logger.info('err ', err); if (err.code === 202) { const params = { email: email }; const userRes = await Parse.Cloud.run('getUserId', params); diff --git a/apps/OpenSignServer/cloud/parsefunction/sendDeleteUserMail.js b/apps/OpenSignServer/cloud/parsefunction/sendDeleteUserMail.js index a3cbc8770f..0d6790e212 100644 --- a/apps/OpenSignServer/cloud/parsefunction/sendDeleteUserMail.js +++ b/apps/OpenSignServer/cloud/parsefunction/sendDeleteUserMail.js @@ -124,7 +124,7 @@ const sendDeleteUserMail = async req => { }); return 'mail sent.'; } catch (err) { - console.log('Err in sending delete user email ', err); + logger.info('Err in sending delete user email ', err); throw new Parse.Error(Parse.Error.SCRIPT_FAILED, err.message); } }; diff --git a/apps/OpenSignServer/cloud/parsefunction/sendMailWithAttachment.js b/apps/OpenSignServer/cloud/parsefunction/sendMailWithAttachment.js index 74e138ebc2..de06c15020 100644 --- a/apps/OpenSignServer/cloud/parsefunction/sendMailWithAttachment.js +++ b/apps/OpenSignServer/cloud/parsefunction/sendMailWithAttachment.js @@ -2,10 +2,17 @@ import fs from 'node:fs'; import https from 'https'; import formData from 'form-data'; import Mailgun from 'mailgun.js'; -import { smtpenable, smtpsecure, normalizeMailSubject, updateMailCount } from '../../Utils.js'; +import { + smtpenable, + smtpsecure, + normalizeMailSubject, + updateMailCount, +} from '../../Utils.js'; +import { getServerConfig, rewritePublicApiUrl } from '../../utils/serverConfig.js'; import { renderComplaintFooter, resolveBrandContext } from '../../utils/brandContext.js'; import { createTransport } from 'nodemailer'; import axios from 'axios'; +import { getSmtpPort } from '../../utils/envConfig.js'; function safeUnlink(filePath, label = 'file') { if (fs.existsSync(filePath)) { @@ -30,7 +37,7 @@ async function sendMailProvider(params) { if (smtpenable) { let transporterConfig = { host: process.env.SMTP_HOST, - port: process.env.SMTP_PORT || 465, + port: getSmtpPort(process.env), secure: smtpsecure, }; @@ -65,7 +72,16 @@ async function sendMailProvider(params) { if (isSecure) { https .get(params.url, async function (response) { + // An error body (404/500) must never be attached as the PDF. + if (response.statusCode !== 200) { + response.resume(); + safeUnlink(testPdf, 'pdf'); + resolve('error'); + return; + } response.pipe(Pdf); + // Writing completion is handled by the attachment-download + // change; this PR only rejects a non-200 response. response.on('end', () => resolve('success')); }) .on('error', e => { @@ -75,9 +91,10 @@ async function sendMailProvider(params) { } else { const httpsAgent = new https.Agent({ rejectUnauthorized: false }); // Disable SSL validation const localUrl = params.url; - const newlocalUrl = localUrl.replace( - 'https://localhost:3001/api', - 'http://localhost:8080' + const newlocalUrl = rewritePublicApiUrl( + localUrl, + process.env.PUBLIC_API_URL, + getServerConfig(process.env).serverOrigin ); axios .get(newlocalUrl, { responseType: 'stream', httpsAgent: httpsAgent }) @@ -95,6 +112,10 @@ async function sendMailProvider(params) { }; // `writeToLocalDisk` is used to create pdf file from doc url const ress = await writeToLocalDisk(); + if (ress !== 'success') { + safeUnlink(testPdf, 'pdf'); + return { status: 'error' }; + } if (ress) { function readTolocal() { return new Promise((resolve, reject) => { @@ -106,6 +127,10 @@ async function sendMailProvider(params) { } // `PdfBuffer` used to create buffer from pdf file let PdfBuffer = await readTolocal(); + if (!PdfBuffer || PdfBuffer.length === 0) { + safeUnlink(testPdf, 'pdf'); + return { status: 'error' }; + } const pdfName = params.pdfName && `${params.pdfName}.pdf`; const filename = params.filename; const file = { @@ -116,28 +141,33 @@ async function sendMailProvider(params) { let attachment; const certificatePath = params.certificatePath || `./exports/certificate.pdf`; + let certificateBuffer = null; if (fs.existsSync(certificatePath)) { try { - // `certificateBuffer` used to create buffer from pdf file - const certificateBuffer = fs.readFileSync(certificatePath); - const certificate = { - filename: 'certificate.pdf', - content: smtpenable ? certificateBuffer : undefined, //fs.readFileSync('./exports/exported_file_1223.pdf'), - data: smtpenable ? undefined : certificateBuffer, - }; - attachment = [file, certificate]; + const stat = fs.statSync(certificatePath); + if (stat.size > 0) { + certificateBuffer = fs.readFileSync(certificatePath); + } } catch (err) { - attachment = [file]; console.log('sendMailWithAttachment read certificate error', err); } + } + if (certificateBuffer && certificateBuffer.length > 0) { + const certificate = { + filename: 'certificate.pdf', + content: smtpenable ? certificateBuffer : undefined, + data: smtpenable ? undefined : certificateBuffer, + }; + attachment = [file, certificate]; } else { attachment = [file]; } const from = params.from || ''; const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER; + const displayName = from && !String(from).includes('@') ? from : brand.productName; const replyto = params?.replyto || ''; const messageParams = { - from: from + ' <' + mailsender + '>', + from: displayName + ' <' + mailsender + '>', to: params.recipient, subject: normalizeMailSubject(params.subject), text: params.text || 'mail', @@ -188,9 +218,10 @@ async function sendMailProvider(params) { } else { const from = params.from || ''; const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER; + const displayName = from && !String(from).includes('@') ? from : brand.productName; const replyto = params?.replyto || ''; const messageParams = { - from: from + ' <' + mailsender + '>', + from: displayName + ' <' + mailsender + '>', to: params.recipient, subject: normalizeMailSubject(params.subject), text: params.text || 'mail', diff --git a/apps/OpenSignServer/cloud/parsefunction/sendMailv3.js b/apps/OpenSignServer/cloud/parsefunction/sendMailv3.js index a74bd68cfd..1efdc2bd18 100644 --- a/apps/OpenSignServer/cloud/parsefunction/sendMailv3.js +++ b/apps/OpenSignServer/cloud/parsefunction/sendMailv3.js @@ -3,6 +3,7 @@ import Mailgun from 'mailgun.js'; import { smtpenable, smtpsecure, normalizeMailSubject, updateMailCount } from '../../Utils.js'; import { renderComplaintFooter, resolveBrandContext } from '../../utils/brandContext.js'; import { createTransport } from 'nodemailer'; +import { getSmtpPort } from '../../utils/envConfig.js'; async function sendMailProvider(req) { const brand = resolveBrandContext({}); const extUserId = req.params?.extUserId || ''; @@ -17,7 +18,7 @@ async function sendMailProvider(req) { if (smtpenable) { let transporterConfig = { host: process.env.SMTP_HOST, - port: process.env.SMTP_PORT || 465, + port: getSmtpPort(process.env), secure: smtpsecure, }; @@ -42,9 +43,10 @@ async function sendMailProvider(req) { const from = req.params.from || ''; const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER; + const displayName = from && !String(from).includes('@') ? from : brand.productName; const replyto = req.params?.replyto || ''; const messageParams = { - from: from + ' <' + mailsender + '>', + from: displayName + ' <' + mailsender + '>', to: req.params.recipient, subject: normalizeMailSubject(req.params.subject), text: req.params.text || 'mail', diff --git a/apps/OpenSignServer/cloud/parsefunction/sendSystemMail.js b/apps/OpenSignServer/cloud/parsefunction/sendSystemMail.js index 47e309f06e..a7e19c5997 100644 --- a/apps/OpenSignServer/cloud/parsefunction/sendSystemMail.js +++ b/apps/OpenSignServer/cloud/parsefunction/sendSystemMail.js @@ -3,6 +3,7 @@ import Mailgun from 'mailgun.js'; import { smtpenable, smtpsecure, normalizeMailSubject, updateMailCount } from '../../Utils.js'; import { renderComplaintFooter, resolveBrandContext } from '../../utils/brandContext.js'; import { createTransport } from 'nodemailer'; +import { getSmtpPort } from '../../utils/envConfig.js'; async function sendMailProvider(req) { const brand = resolveBrandContext({}); const extUserId = req.params?.extUserId || ''; @@ -17,7 +18,7 @@ async function sendMailProvider(req) { if (smtpenable) { let transporterConfig = { host: process.env.SMTP_HOST, - port: process.env.SMTP_PORT || 465, + port: getSmtpPort(process.env), secure: smtpsecure, }; @@ -42,9 +43,10 @@ async function sendMailProvider(req) { const from = req.params.from || ''; const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER; + const displayName = from && !String(from).includes('@') ? from : brand.productName; const replyto = req.params?.replyto || ''; const messageParams = { - from: from + ' <' + mailsender + '>', + from: displayName + ' <' + mailsender + '>', to: req.params.recipient, subject: normalizeMailSubject(req.params.subject), text: req.params.text || 'mail', diff --git a/apps/OpenSignServer/cloud/parsefunction/setWidgetPreferences.js b/apps/OpenSignServer/cloud/parsefunction/setWidgetPreferences.js index 07f68beefe..dd399ca2e0 100644 --- a/apps/OpenSignServer/cloud/parsefunction/setWidgetPreferences.js +++ b/apps/OpenSignServer/cloud/parsefunction/setWidgetPreferences.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function setWidgetPreferences(request) { if (!request?.user) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'User is not authenticated.'); @@ -43,7 +44,7 @@ export default async function setWidgetPreferences(request) { }; } } catch (err) { - console.log('set widget preferences error:', err); + logger.info('set widget preferences error:', err); throw new Parse.Error(err?.code || 400, err?.message || 'Something went wrong.'); } } diff --git a/apps/OpenSignServer/cloud/parsefunction/triggerEvent.js b/apps/OpenSignServer/cloud/parsefunction/triggerEvent.js index 331d6448be..7b6bd33ffc 100644 --- a/apps/OpenSignServer/cloud/parsefunction/triggerEvent.js +++ b/apps/OpenSignServer/cloud/parsefunction/triggerEvent.js @@ -1,5 +1,6 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; export default async function triggerEvent(request) { const event = request.params.event; @@ -54,8 +55,12 @@ export default async function triggerEvent(request) { let updatedAuditTrail; - if (existingIndex !== -1) { - // update existing entry + // Do not overwrite a completion activity (e.g. 'Signed') with 'Viewed'; + // instead append a separate 'Viewed' entry to preserve audit integrity. + const completionActivities = ['Signed']; + if (existingIndex !== -1 && completionActivities.includes(auditTrail[existingIndex]?.Activity)) { + updatedAuditTrail = [...auditTrail, newEntry]; + } else if (existingIndex !== -1) { updatedAuditTrail = [...auditTrail]; updatedAuditTrail[existingIndex] = { ...updatedAuditTrail[existingIndex], @@ -65,7 +70,6 @@ export default async function triggerEvent(request) { ViewedOn: date, }; } else { - // add new entry updatedAuditTrail = [...auditTrail, newEntry]; } @@ -78,7 +82,7 @@ export default async function triggerEvent(request) { return { message: 'event called!' }; } catch (err) { - console.log( + logger.info( `triggerEvent error: `, err?.response?.data?.error || err?.message || 'Something went wrong!' ); diff --git a/apps/OpenSignServer/cloud/parsefunction/updateContactTour.js b/apps/OpenSignServer/cloud/parsefunction/updateContactTour.js index 9ffe3b0ae0..3cdc6c8f2e 100644 --- a/apps/OpenSignServer/cloud/parsefunction/updateContactTour.js +++ b/apps/OpenSignServer/cloud/parsefunction/updateContactTour.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function updateContactTour(request) { const contactId = request.params.contactId; try { @@ -27,7 +28,7 @@ export default async function updateContactTour(request) { throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'contact not found.'); } } catch (err) { - console.log('Err in contracts_Contactbook class ', err); + logger.info('Err in contracts_Contactbook class ', err); throw err; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/updateEmailTemplates.js b/apps/OpenSignServer/cloud/parsefunction/updateEmailTemplates.js index 2a94ac4e3c..6a640c697c 100644 --- a/apps/OpenSignServer/cloud/parsefunction/updateEmailTemplates.js +++ b/apps/OpenSignServer/cloud/parsefunction/updateEmailTemplates.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function updateEmailTemplates(request) { const { tenantId, details } = request.params; @@ -32,7 +33,7 @@ export default async function updateEmailTemplates(request) { return res; } } catch (error) { - console.log('error while updating email templates:', error); + logger.info('error while updating email templates:', error); throw error; } } diff --git a/apps/OpenSignServer/cloud/parsefunction/updatePreferences.js b/apps/OpenSignServer/cloud/parsefunction/updatePreferences.js index bce88920b4..c327557cb5 100644 --- a/apps/OpenSignServer/cloud/parsefunction/updatePreferences.js +++ b/apps/OpenSignServer/cloud/parsefunction/updatePreferences.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function updatePreferences(request) { if (!request?.user) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'User is not authenticated.'); @@ -6,7 +7,13 @@ export default async function updatePreferences(request) { const NotifyOnSignatures = request.params.NotifyOnSignatures; const Timezone = request.params.Timezone; const UseNameAsSender = request.params.UseNameAsSender; - if (SignatureType?.length > 0 || NotifyOnSignatures !== undefined || Timezone) { + const Theme = request.params.Theme; + if ( + SignatureType?.length > 0 || + NotifyOnSignatures !== undefined || + Timezone || + Theme !== undefined + ) { try { const orgQuery = new Parse.Query('contracts_Users'); orgQuery.equalTo('UserId', { @@ -64,6 +71,12 @@ export default async function updatePreferences(request) { if (UseNameAsSender !== undefined) { newOrg.set('UseNameAsSender', UseNameAsSender); } + if (Theme !== undefined) { + if (Theme !== 'dark' && Theme !== 'light') { + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Invalid theme.'); + } + newOrg.set('Theme', Theme); + } const updateUserRes = await newOrg.save(null, { useMasterKey: true }); if (updateUserRes) { const _updateUserRes = JSON.parse(JSON.stringify(updateUserRes)); @@ -73,7 +86,7 @@ export default async function updatePreferences(request) { throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Premission denied.'); } } catch (err) { - console.log('err in addorganization', err); + logger.info('err in addorganization', err); const code = err?.code || 400; const msg = err?.message || 'Something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/updateTourStatus.js b/apps/OpenSignServer/cloud/parsefunction/updateTourStatus.js index d67a133fa8..7687cf6e77 100644 --- a/apps/OpenSignServer/cloud/parsefunction/updateTourStatus.js +++ b/apps/OpenSignServer/cloud/parsefunction/updateTourStatus.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function updateTourStatus(request) { const tourstatus = request.params.TourStatus; const extUserId = request.params.ExtUserId; @@ -10,7 +11,7 @@ export default async function updateTourStatus(request) { const res = await updateUser.save(null, { sessionToken: request.user.getSessionToken() }); return res; } catch (err) { - console.log('Err ', err); + logger.info('Err ', err); const code = err?.code || 400; const msg = err?.message || 'Something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/updatesignaturetype.js b/apps/OpenSignServer/cloud/parsefunction/updatesignaturetype.js index 5d51094989..b6620d7709 100644 --- a/apps/OpenSignServer/cloud/parsefunction/updatesignaturetype.js +++ b/apps/OpenSignServer/cloud/parsefunction/updatesignaturetype.js @@ -1,3 +1,4 @@ +import { logger } from '../../utils/logger.js'; export default async function updateSignatureType(request) { if (!request?.user) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'User is not authenticated.'); @@ -40,7 +41,7 @@ export default async function updateSignatureType(request) { throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Premission denied.'); } } catch (err) { - console.log('err in addorganization', err); + logger.info('err in addorganization', err); const code = err?.code || 400; const msg = err?.message || 'Something went wrong.'; throw new Parse.Error(code, msg); diff --git a/apps/OpenSignServer/cloud/parsefunction/usersignup.js b/apps/OpenSignServer/cloud/parsefunction/usersignup.js index d1ae01eaf7..12afb7ed37 100644 --- a/apps/OpenSignServer/cloud/parsefunction/usersignup.js +++ b/apps/OpenSignServer/cloud/parsefunction/usersignup.js @@ -1,13 +1,20 @@ import axios from 'axios'; import { cloudServerUrl, serverAppId } from '../../Utils.js'; +import { logger } from '../../utils/logger.js'; const serverUrl = cloudServerUrl; //process.env.SERVER_URL; const APPID = serverAppId; const masterKEY = process.env.MASTER_KEY; +function normalizeEmail(email) { + return String(email || '') + .toLowerCase() + .replace(/\s/g, ''); +} + async function saveUser(userDetails) { - const normalizedEmail = normalizeEmail(userDetails.email.toLowerCase().replace(/\s/g, '')); + const normalizedEmail = normalizeEmail(userDetails.email); const userQuery = new Parse.Query(Parse.User); - userQuery.equalTo('username', userDetails.email); + userQuery.equalTo('username', normalizedEmail); const userRes = await userQuery.first({ useMasterKey: true }); if (userRes) { @@ -25,13 +32,13 @@ async function saveUser(userDetails) { }, }); const login = await axiosRes.data; - // console.log("login ", login); + // logger.info("login ", login); return { id: login.objectId, sessionToken: login.sessionToken }; } else { const user = new Parse.User(); - user.set('username', userDetails.email); + user.set('username', normalizedEmail); user.set('password', userDetails.password); - user.set('email', userDetails?.email?.toLowerCase()?.replace(/\s/g, '')); + user.set('email', normalizedEmail); user.set('normalizedEmail', normalizedEmail); if (userDetails?.phone) { @@ -40,7 +47,7 @@ async function saveUser(userDetails) { user.set('name', userDetails.name); const res = await user.signUp(); - // console.log("res ", res); + // logger.info("res ", res); return { id: res.id, sessionToken: res.getSessionToken() }; } } @@ -61,7 +68,7 @@ export default async function usersignup(request) { if (extUser) { return { message: 'User already exist' }; } else { - // console.log("role ", role); + // logger.info("role ", role); const partnerCls = Parse.Object.extend('partners_Tenant'); const partnerQuery = new partnerCls(); partnerQuery.set('UserId', { @@ -97,7 +104,7 @@ export default async function usersignup(request) { partnerQuery.set('Address', userDetails.address); } const tenantRes = await partnerQuery.save(null, { useMasterKey: true }); - // console.log("tenantRes ", tenantRes); + // logger.info("tenantRes ", tenantRes); const extCls = Parse.Object.extend(extClass + '_Users'); const newObj = new extCls(); newObj.set('UserId', { @@ -129,6 +136,6 @@ export default async function usersignup(request) { return { message: 'User sign up', sessionToken: user.sessionToken }; } } catch (err) { - console.log('Err ', err); + logger.info('Err ', err); } } diff --git a/apps/OpenSignServer/cloud/parsefunction/webhookDispatcher.js b/apps/OpenSignServer/cloud/parsefunction/webhookDispatcher.js new file mode 100644 index 0000000000..f72029f5a4 --- /dev/null +++ b/apps/OpenSignServer/cloud/parsefunction/webhookDispatcher.js @@ -0,0 +1,125 @@ +/** + * @file webhookDispatcher.js + * @description Enterprise-grade Webhook Dispatcher with HMAC-SHA256 signatures, + * smart exponential backoff, and idempotency key injection. + * Zero external dependencies beyond Node.js built-ins and axios (already in OpenSignServer). + * @module cloud/parsefunction/webhookDispatcher + */ + +import crypto from 'crypto'; +import axios from 'axios'; + +/** + * Maximum number of delivery attempts before permanent failure. + * @constant {number} + */ +const MAX_RETRIES = 3; + +/** + * Timeout for each individual HTTP request in milliseconds. + * @constant {number} + */ +const TIMEOUT_MS = 5000; + +/** + * Generates a cryptographic HMAC-SHA256 signature for a given payload string. + * Allows the receiving server to verify the authenticity and integrity of the + * webhook payload, preventing Man-in-the-Middle (MITM) and replay attacks. + * + * @param {string} payloadString - The JSON-serialized payload string to sign. + * @param {string} secret - The shared HMAC secret configured by the document owner. + * @returns {string} A hexadecimal HMAC-SHA256 digest of the payload. + */ +export function generateSignature(payloadString, secret) { + return crypto.createHmac('sha256', secret).update(payloadString).digest('hex'); +} + +/** + * Determines whether a failed HTTP request should be retried. + * Client errors (4xx, excluding 429 Too Many Requests) are non-retryable because + * they indicate a permanent misconfiguration on the receiving server's end. + * Network errors, timeouts, and server errors (5xx) are retryable. + * + * @param {import('axios').AxiosError} axiosError - The error returned by axios. + * @returns {boolean} True if the request should be retried, false otherwise. + */ +function isRetryableError(axiosError) { + const status = axiosError?.response?.status; + if (!status) return true; // Network error or timeout — always retry + const isClientError = status >= 400 && status < 500 && status !== 429; + return !isClientError; +} + +/** + * Dispatches a webhook event to a configured URL with enterprise-grade resilience: + * - HMAC-SHA256 signature injection (`X-OpenSign-Signature`) + * - Idempotency key injection (`Idempotency-Key`) to allow safe deduplication on + * the receiving server, preventing duplicate processing on retries. + * - Smart exponential backoff: retries only on network failures and 5xx errors, + * drops 4xx errors immediately to conserve server resources. + * + * @param {string} url - The target URL to POST the webhook payload to. + * @param {object} payload - The structured webhook event payload. + * @param {string} payload.eventId - Unique identifier for this event (used for idempotency). + * @param {string} payload.event - The event type (e.g., 'document.signed', 'document.declined'). + * @param {string} payload.documentId - The OpenSign document ID associated with this event. + * @param {string} payload.status - The document status at the time of the event. + * @param {string} payload.timestamp - ISO 8601 timestamp of when the event occurred. + * @param {object} payload.data - Additional event-specific data. + * @param {string} secret - The HMAC signing secret configured by the document owner. + * @param {number} [attempt=1] - The current attempt number (used internally for recursion). + * @returns {Promise<{success: boolean, attempts: number, statusCode?: number, error?: string, isRetryable: boolean}>} + */ +export async function dispatchWithBackoff(url, payload, secret, attempt = 1) { + const payloadString = JSON.stringify(payload); + const signature = generateSignature(payloadString, secret); + + // Idempotency Key: allows the receiving server to safely deduplicate retries, + // preventing duplicate side effects (e.g., a document being "signed" twice). + const idempotencyKey = `os_evt_${payload.eventId}_attempt_${attempt}`; + + try { + console.log(`[OpenSign Webhook] [Attempt ${attempt}/${MAX_RETRIES}] Dispatching '${payload.event}' to ${url}`); + + const response = await axios.post(url, payloadString, { + headers: { + 'Content-Type': 'application/json', + 'X-OpenSign-Signature': signature, + 'X-OpenSign-Event': payload.event, + 'Idempotency-Key': idempotencyKey, + 'X-OpenSign-Delivery-Attempt': String(attempt), + }, + timeout: TIMEOUT_MS, + }); + + console.log(`[OpenSign Webhook] Successfully delivered to ${url} (HTTP ${response.status})`); + return { success: true, attempts: attempt, statusCode: response.status, isRetryable: false }; + } catch (error) { + const axiosError = /** @type {import('axios').AxiosError} */ (error); + const statusCode = axiosError?.response?.status; + const retryable = isRetryableError(axiosError); + + console.warn( + `[OpenSign Webhook] Delivery failed for ${url}: ${axiosError.message} (HTTP ${statusCode ?? 'Network/Timeout'})` + ); + + if (retryable && attempt < MAX_RETRIES) { + // Exponential backoff: 2s → 4s → 8s + const backoffMs = Math.pow(2, attempt) * 1000; + console.log(`[OpenSign Webhook] Retrying in ${backoffMs}ms... (attempt ${attempt + 1}/${MAX_RETRIES})`); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + return dispatchWithBackoff(url, payload, secret, attempt + 1); + } + + console.error( + `[OpenSign Webhook] Permanently failed for ${url} after ${attempt} attempt(s). isRetryable=${retryable}` + ); + return { + success: false, + attempts: attempt, + statusCode, + error: axiosError.message, + isRetryable: retryable, + }; + } +} diff --git a/apps/OpenSignServer/databases/migrations/20261107000000-add_theme_field.cjs b/apps/OpenSignServer/databases/migrations/20261107000000-add_theme_field.cjs new file mode 100644 index 0000000000..85072ddb54 --- /dev/null +++ b/apps/OpenSignServer/databases/migrations/20261107000000-add_theme_field.cjs @@ -0,0 +1,19 @@ +/** + * + * @param {Parse} Parse + */ +exports.up = async Parse => { + const schema = new Parse.Schema('contracts_Users'); + schema.addString('Theme'); + return schema.update(); +}; + +/** + * + * @param {Parse} Parse + */ +exports.down = async Parse => { + const schema = new Parse.Schema('contracts_Users'); + schema.deleteField('Theme'); + return schema.update(); +}; diff --git a/apps/OpenSignServer/email-templates/password_reset_email.html b/apps/OpenSignServer/email-templates/password_reset_email.html new file mode 100644 index 0000000000..8634777e4d --- /dev/null +++ b/apps/OpenSignServer/email-templates/password_reset_email.html @@ -0,0 +1,17 @@ +<html> + +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> +</head> + +<body style="text-align: center;"> + <p style="font-weight: bolder; font-size: large;">Hello!</p> + <p>You requested to reset the password for your account:</p> + <p>{{username}}</p> + <p>Click the button below to reset your password:</p> + <br /> + <p><a href="{{{link}}}" style="background-color: lightskyblue; cursor: pointer; border-radius: 5px; padding: 10px; border-style: solid; border-width: 2px; text-decoration: none; font-weight: bolder; color:blue">Verify email</a></p> + <br /> +</body> + +</html> \ No newline at end of file diff --git a/apps/OpenSignServer/email-templates/password_reset_email.txt b/apps/OpenSignServer/email-templates/password_reset_email.txt new file mode 100644 index 0000000000..2f4684ad54 --- /dev/null +++ b/apps/OpenSignServer/email-templates/password_reset_email.txt @@ -0,0 +1,9 @@ +Hello! + +You requested to reset the password for your account: + +{{username}} + +Click the link below to reset your password: + +{{{link}}} diff --git a/apps/OpenSignServer/email-templates/password_reset_email_subject.txt b/apps/OpenSignServer/email-templates/password_reset_email_subject.txt new file mode 100644 index 0000000000..2feff9ea9e --- /dev/null +++ b/apps/OpenSignServer/email-templates/password_reset_email_subject.txt @@ -0,0 +1 @@ +Password Reset diff --git a/apps/OpenSignServer/email-templates/verification_email.html b/apps/OpenSignServer/email-templates/verification_email.html new file mode 100644 index 0000000000..44b8100c98 --- /dev/null +++ b/apps/OpenSignServer/email-templates/verification_email.html @@ -0,0 +1,16 @@ +<html> + +<head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> +</head> + +<body style="text-align: center;"> + <p style="font-weight: bolder; font-size: large;">Welcome!</p> + <p>Click the button below to verify your email address:</p> + <br /> + <p><a href="{{{link}}}" style="background-color: lightskyblue; cursor: pointer; border-radius: 5px; padding: 10px; border-style: solid; border-width: 2px; text-decoration: none; font-weight: bolder; color:blue">Verify email</a></p> + <br /> + <p>{{appName}}</p> +</body> + +</html> diff --git a/apps/OpenSignServer/email-templates/verification_email.txt b/apps/OpenSignServer/email-templates/verification_email.txt new file mode 100644 index 0000000000..076b656d06 --- /dev/null +++ b/apps/OpenSignServer/email-templates/verification_email.txt @@ -0,0 +1,7 @@ +Welcome! + +Click the link below to verify your email address: + +{{{link}}} + +{{appName}} \ No newline at end of file diff --git a/apps/OpenSignServer/email-templates/verification_email_subject.txt b/apps/OpenSignServer/email-templates/verification_email_subject.txt new file mode 100644 index 0000000000..7300c522af --- /dev/null +++ b/apps/OpenSignServer/email-templates/verification_email_subject.txt @@ -0,0 +1 @@ +{{appName}} Email Address Verification \ No newline at end of file diff --git a/apps/OpenSignServer/index.js b/apps/OpenSignServer/index.js index 91f3785941..81e179cc01 100644 --- a/apps/OpenSignServer/index.js +++ b/apps/OpenSignServer/index.js @@ -15,10 +15,14 @@ import { app as customRoute } from './cloud/customRoute/customApp.js'; import { exec } from 'child_process'; import { createTransport } from 'nodemailer'; import { appName, cloudServerUrl, serverAppId, smtpenable, smtpsecure, useLocal } from './Utils.js'; -import { resolveDeploymentBrand } from './utils/brandContext.js'; +import { REMINDER_INTERVAL_MS, resolveDeploymentBrand } from './utils/brandContext.js'; import { SSOAuth } from './auth/authadapter.js'; import runDbMigrations from './migrationdb/index.js'; import { validateSignedLocalUrl } from './cloud/parsefunction/getSignedUrl.js'; +import { parseTrustProxy, resolveClientIp } from './utils/clientIp.js'; +import { getServerConfig } from './utils/serverConfig.js'; +import { getDatabaseUri, getSmtpPort } from './utils/envConfig.js'; +import { parseOriginList, resolvePublicUrl } from './utils/publicUrl.js'; let fsAdapter; if (useLocal !== 'true') { @@ -66,13 +70,13 @@ if (smtpenable) { try { let transporterConfig = { host: process.env.SMTP_HOST, - port: process.env.SMTP_PORT || 465, + port: getSmtpPort(process.env), secure: smtpsecure, }; // ✅ Add auth only if BOTH username & password exist - const smtpUser = process.env.SMTP_USERNAME; - const smtpPass = process.env.SMTP_PASS; + const smtpUser = process.env.SMTP_USERNAME || process.env.SMTP_USER; + const smtpPass = process.env.SMTP_PASS || process.env.SMTP_PASSWORD; if (smtpUser && smtpPass) { transporterConfig.auth = { @@ -104,8 +108,7 @@ if (smtpenable) { const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER; const deploymentSenderName = resolveDeploymentBrand().senderName; export const config = { - databaseURI: - process.env.DATABASE_URI || process.env.MONGODB_URI || 'mongodb://localhost:27017/dev', + databaseURI: getDatabaseUri(process.env), cloud: function () { import('./cloud/main.js'); }, @@ -114,17 +117,28 @@ export const config = { maxLimit: 500, maxUploadSize: '100mb', masterKey: process.env.MASTER_KEY, //Add your master key here. Keep it secret! - masterKeyIps: ['0.0.0.0/0', '::/0'], // '::1' + // The master key overrides every ACL, so it is only accepted from the + // addresses that actually need it: loopback by default, overridable for + // deployments that run the API in a separate container network. + masterKeyIps: (process.env.MASTER_KEY_IPS || '127.0.0.1,::1') + .split(',') + .map(value => value.trim()) + .filter(Boolean), serverURL: cloudServerUrl, // Don't forget to change to https if needed verifyUserEmails: false, publicServerURL: process.env.SERVER_URL || cloudServerUrl, // Your apps name. This will appear in the subject and body of the emails that are sent. appName: appName, + // Reject trivially weak passwords at signup and at password change. + // This Parse Server release accepts only these two keys. + passwordPolicy: { + validatorPattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/, + }, allowClientClassCreation: false, allowExpiredAuthDataToken: false, enableInsecureAuthAdapters: false, databaseOptions: { allowPublicExplain: false }, - encodeParseObjectInCloudFunction: true, + // encodeParseObjectInCloudFunction removed (unsupported in this parse-server version) ...(isMailAdapter === true ? { emailAdapter: { @@ -137,16 +151,16 @@ export const config = { // The template used by Parse Server to send an email for password // reset; this is a reserved template name. passwordResetEmail: { - subjectPath: './files/password_reset_email_subject.txt', - textPath: './files/password_reset_email.txt', - htmlPath: './files/password_reset_email.html', + subjectPath: './email-templates/password_reset_email_subject.txt', + textPath: './email-templates/password_reset_email.txt', + htmlPath: './email-templates/password_reset_email.html', }, // The template used by Parse Server to send an email for email // address verification; this is a reserved template name. verificationEmail: { - subjectPath: './files/verification_email_subject.txt', - textPath: './files/verification_email.txt', - htmlPath: './files/verification_email.html', + subjectPath: './email-templates/verification_email_subject.txt', + textPath: './email-templates/verification_email.txt', + htmlPath: './email-templates/verification_email.html', }, }, apiCallback: async ({ payload, locale }) => { @@ -169,32 +183,64 @@ export const config = { // javascriptKey, restAPIKey, dotNetKey, clientKey export const app = express(); -app.use(cors()); -app.use(express.json({ limit: '100mb' })); +// Only the configured public origins may call the API from a browser. +// Requests without an Origin header (server to server, curl) keep working. +const corsAllowlist = ( + process.env.CORS_ORIGINS || + [process.env.SERVER_URL, process.env.PUBLIC_URL, process.env.HOST_URL] + .filter(Boolean) + .join(',') +) + .split(',') + .map(origin => origin.trim().replace(/\/$/, '')) + .filter(Boolean); + +app.use( + cors({ + origin: (origin, callback) => { + if (!origin || corsAllowlist.length === 0) return callback(null, true); + return callback(null, corsAllowlist.includes(origin.replace(/\/$/, ''))); + }, + }) +); + + +// Baseline security headers. A CSP is added at the reverse proxy, where the +// asset and font origins are known. +app.use((req, res, next) => { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('X-Frame-Options', 'SAMEORIGIN'); + res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()'); + res.setHeader('Strict-Transport-Security', 'max-age=15552000; includeSubDomains'); + next(); +});app.use(express.json({ limit: '100mb' })); app.use(express.urlencoded({ limit: '100mb', extended: true })); +/** + * Base URL for email links: PUBLIC_URL, else the origin of SERVER_URL. + * Extra custom domains come from PUBLIC_URL_ALLOWLIST. + */ +const publicUrlConfig = { + baseUrl: + process.env.PUBLIC_URL || + (process.env.SERVER_URL ? new URL(process.env.SERVER_URL).origin : ''), + allowlist: parseOriginList(process.env.PUBLIC_URL_ALLOWLIST), +}; app.use(function (req, res, next) { req.headers['x-real-ip'] = getUserIP(req); - let publicUrl = 'https://' + req?.get('host'); - req.headers['public_url'] = publicUrl; + req.headers['public_url'] = resolvePublicUrl( + { host: req?.get('host'), origin: req.headers.origin }, + publicUrlConfig + ); next(); }); +/** + * Client IP for the audit trail. Proxy headers are used only as configured + * by TRUST_PROXY (hop count or "cloudflare"). + */ +const trustProxy = parseTrustProxy(process.env.TRUST_PROXY); function getUserIP(request) { - const cloudflareIp = request.headers['cf-connecting-ip']; - if (typeof cloudflareIp === 'string' && cloudflareIp.trim()) { - return cloudflareIp.trim(); - } - - const forwardedFor = request.headers['x-forwarded-for']; - if (typeof forwardedFor === 'string' && forwardedFor.trim()) { - return forwardedFor.split(',')[0].trim(); - } - - const realIp = request.headers['x-real-ip']; - if (typeof realIp === 'string' && realIp.trim()) { - return realIp.trim(); - } - - return request.socket?.remoteAddress || ''; + return resolveClientIp(request.headers, request.socket?.remoteAddress, trustProxy); } app.use(async function (req, res, next) { @@ -242,7 +288,7 @@ app.get('/', function (req, res) { }); if (!process.env.TESTING) { - const port = process.env.PORT || 8080; + const { port, bindHost } = getServerConfig(process.env); const httpServer = http.createServer(app); // Set the Keep-Alive and headers timeout to 100 seconds httpServer.keepAliveTimeout = 100000; // in milliseconds @@ -254,7 +300,7 @@ if (!process.env.TESTING) { // otherwise the platform's readiness probe never succeeds and the deploy is killed. console.error('Database migration failed:', error); } - httpServer.listen(port, '0.0.0.0', function () { + httpServer.listen(port, bindHost, function () { console.log('opensign-server running on port ' + port + '.'); const isWindows = process.platform === 'win32'; // console.log('isWindows', isWindows); @@ -273,5 +319,58 @@ if (!process.env.TESTING) { } console.log(`Command output: ${stdout}`); }); + + // Automatic reminders scheduler (issue #2268): runs hourly. + const runReminders = async () => { + try { + const now = new Date(); + const q = new Parse.Query('contracts_Document'); + q.equalTo('AutomaticReminders', true); + q.notEqualTo('IsCompleted', true); + q.notEqualTo('IsDeclined', true); + q.notEqualTo('IsArchive', true); + q.lessThanOrEqualTo('NextReminderDate', now); + q.limit(100); + const docs = await q.find({ useMasterKey: true }); + for (const doc of docs) { + try { + const expiry = doc.get('ExpiryDate'); + if (expiry && new Date(expiry) < now) { + doc.set('AutomaticReminders', false); + await doc.save(null, { useMasterKey: true }); + continue; + } + const creator = doc.get('ExtUserPtr'); + const creatorEmail = creator?.get?.('Email') || doc.get('SenderMail'); + const pdfName = doc.get('Name') || 'Document'; + if (creatorEmail) { + await Parse.Cloud.sendEmail({ + sender: `${appName} <${process.env.SMTP_USER_EMAIL || process.env.MAILGUN_SENDER || ''}>`, + recipient: creatorEmail, + subject: `Reminder: "${pdfName}" is still pending signature`, + text: `Reminder: "${pdfName}" is still pending signature.`, + html: `<p>Reminder: "${pdfName}" is still pending signature.</p>`, + }); + } + const every = doc.get('RemindOnceInEvery') || 5; + const next = new Date(doc.get('NextReminderDate') || now); + next.setDate(next.getDate() + every); + if (expiry && next > new Date(expiry)) { + doc.set('AutomaticReminders', false); + } else { + doc.set('NextReminderDate', next); + } + await doc.save(null, { useMasterKey: true }); + } catch (e) { + console.log('reminder error for doc', doc?.id, e?.message); + } + } + } catch (e) { + console.log('reminder scheduler error', e?.message); + } + }; + // run once after startup (delayed) then hourly + setTimeout(runReminders, 60000); + setInterval(runReminders, REMINDER_INTERVAL_MS); }); } diff --git a/apps/OpenSignServer/migrationdb/createContactIndex.js b/apps/OpenSignServer/migrationdb/createContactIndex.js index 01accec314..14bd54d60b 100644 --- a/apps/OpenSignServer/migrationdb/createContactIndex.js +++ b/apps/OpenSignServer/migrationdb/createContactIndex.js @@ -1,11 +1,12 @@ import dotenv from 'dotenv'; import { MongoClient } from 'mongodb'; import { generateId } from '../Utils.js'; +import { getDatabaseUri } from '../utils/envConfig.js'; dotenv.config({ quiet: true }); export default async function createContactIndex() { // Provide the complete MongoDB connection URL with the database name - const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/dev'; // Replace with your MongoDB URI + const uri = getDatabaseUri(process.env); const client = new MongoClient(uri); try { await client.connect(); diff --git a/apps/OpenSignServer/migrationdb/createDocumentIndex.js b/apps/OpenSignServer/migrationdb/createDocumentIndex.js index 35128344a8..ad40710261 100644 --- a/apps/OpenSignServer/migrationdb/createDocumentIndex.js +++ b/apps/OpenSignServer/migrationdb/createDocumentIndex.js @@ -1,11 +1,12 @@ import dotenv from 'dotenv'; import { MongoClient } from 'mongodb'; import { generateId } from '../Utils.js'; +import { getDatabaseUri } from '../utils/envConfig.js'; dotenv.config({ quiet: true }); export default async function createDocumentIndex() { // Provide the complete MongoDB connection URL with the database name - const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/dev'; // Replace with your MongoDB URI + const uri = getDatabaseUri(process.env); const client = new MongoClient(uri); try { await client.connect(); diff --git a/apps/OpenSignServer/migrationdb/createNormalizedEmailUnqiue.js b/apps/OpenSignServer/migrationdb/createNormalizedEmailUnqiue.js index 7e6f96bae8..0cae686d20 100644 --- a/apps/OpenSignServer/migrationdb/createNormalizedEmailUnqiue.js +++ b/apps/OpenSignServer/migrationdb/createNormalizedEmailUnqiue.js @@ -1,11 +1,12 @@ import dotenv from 'dotenv'; import { MongoClient } from 'mongodb'; import { generateId } from '../Utils.js'; +import { getDatabaseUri } from '../utils/envConfig.js'; dotenv.config({ quiet: true }); export default async function createNormalizedEmailUnique() { // Provide the complete MongoDB connection URL with the database name - const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/dev'; // Replace with your MongoDB URI + const uri = getDatabaseUri(process.env); const client = new MongoClient(uri); try { await client.connect(); diff --git a/apps/OpenSignServer/package-lock.json b/apps/OpenSignServer/package-lock.json index 2b209f5b4a..030dd1552e 100644 --- a/apps/OpenSignServer/package-lock.json +++ b/apps/OpenSignServer/package-lock.json @@ -28,6 +28,7 @@ "generate-api-key": "^1.0.2", "googleapis": "^171.4.0", "jose": "^6.2.3", + "ldapts": "^9.3.1", "libreoffice-convert": "^1.8.1", "mailgun.js": "^13.0.0", "moment": "^2.30.1", @@ -63,6 +64,24 @@ "node": "18 || 20 || 22" } }, + "node_modules/ldapts": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/ldapts/-/ldapts-9.3.1.tgz", + "integrity": "sha512-MiClSiwcoAuI2I/63N+fotWZvnATkbpRsKzUzhSjqhY9bk6UmMevhZBRjO1GtpX/PbeRpOKs4W9P8Do6284Bqw==", + "license": "MIT", + "dependencies": { + "strict-event-emitter-types": "^2.0.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/strict-event-emitter-types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strict-event-emitter-types/-/strict-event-emitter-types-2.0.0.tgz", + "integrity": "sha512-Nk/brWYpD85WlOgzw5h173aci0Teyv8YdIAEtV+N88nDB0dLlazZyJMIsN6eo1/AR61l+p6CJTG1JIyFaoNEEA==", + "license": "ISC" + }, "node_modules/@apollo/cache-control-types": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@apollo/cache-control-types/-/cache-control-types-1.0.3.tgz", diff --git a/apps/OpenSignServer/package.json b/apps/OpenSignServer/package.json index a0ddc88c8d..fc23bec091 100644 --- a/apps/OpenSignServer/package.json +++ b/apps/OpenSignServer/package.json @@ -1,6 +1,6 @@ { "name": "open_sign_server", - "version": "2.37.0", + "version": "2.38.1", "description": "opensign server using the parse-server module", "repository": { "type": "git", @@ -13,6 +13,7 @@ "lint-fix": "eslint --cache --fix ./cloud && eslint --cache --fix index.js", "prettier": "prettier --write 'cloud/{**/*,*}.js' 'index.js'", "start": "node index.js", + "test": "jasmine", "watch": "nodemon index.js" }, "dependencies": { @@ -35,6 +36,7 @@ "generate-api-key": "^1.0.2", "googleapis": "^171.4.0", "jose": "^6.2.3", + "ldapts": "^9.3.1", "libreoffice-convert": "^1.8.1", "mailgun.js": "^13.0.0", "moment": "^2.30.1", @@ -82,7 +84,8 @@ "websocket-driver": ">=0.7.5", "js-yaml": "^3.15.0", "lodash": "^4.18.0", - "undici": "^7.29.0", + "undici": ">=7.30.0", + "proxy-addr": ">=2.0.7", "uuid": ">=11.1.1", "body-parser": ">=2.3.0", "@graphql-tools/utils": "$@graphql-tools/utils", diff --git a/apps/OpenSignServer/spec/IssuerPreservingP12Signer.spec.js b/apps/OpenSignServer/spec/IssuerPreservingP12Signer.spec.js new file mode 100644 index 0000000000..6bbef209c7 --- /dev/null +++ b/apps/OpenSignServer/spec/IssuerPreservingP12Signer.spec.js @@ -0,0 +1,136 @@ +import { createHash, createPublicKey, generateKeyPairSync, verify } from 'node:crypto'; +import forge from 'node-forge'; +import { P12Signer } from '@signpdf/signer-p12'; +import { IssuerPreservingP12Signer } from '../cloud/parsefunction/pdf/IssuerPreservingP12Signer.js'; + +const { asn1, pki } = forge; +const passphrase = 'spec-passphrase'; +const content = Buffer.from('%PDF-1.7 signed content'); +const generateKeyPair = () => + generateKeyPairSync('rsa', { + modulusLength: 2048, + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, + }); +const { publicKey, privateKey } = generateKeyPair(); + +const utf8Name = value => [{ shortName: 'CN', value, valueTagClass: asn1.Type.UTF8 }]; + +function createCertificate(subject, issuer, serialNumber, subjectPublicKey = publicKey) { + const certificate = pki.createCertificate(); + certificate.publicKey = pki.publicKeyFromPem(subjectPublicKey); + certificate.serialNumber = serialNumber; + certificate.validity.notBefore = new Date('2026-01-01T00:00:00Z'); + certificate.validity.notAfter = new Date('2036-01-01T00:00:00Z'); + certificate.setSubject(subject); + certificate.setIssuer(issuer); + certificate.sign(pki.privateKeyFromPem(privateKey), forge.md.sha256.create()); + return certificate; +} + +function createP12(...certificates) { + const p12 = forge.pkcs12.toPkcs12Asn1( + pki.privateKeyFromPem(privateKey), + certificates, + passphrase, + { algorithm: '3des' } + ); + return Buffer.from(asn1.toDer(p12).getBytes(), 'binary'); +} + +function parseCms(signature) { + const contentInfo = asn1.fromDer(forge.util.createBuffer(signature.toString('binary'))); + const signedData = contentInfo.value[1].value[0].value; + const signerInfo = signedData.at(-1).value[0]; + return { + certificates: signedData + .find(field => field.tagClass === asn1.Class.CONTEXT_SPECIFIC && field.type === 0) + .value.map(certificate => asn1.toDer(certificate).getBytes()), + signerIssuer: asn1.toDer(signerInfo.value[1].value[0]).getBytes(), + signerInfo, + }; +} + +const issuerDer = certificate => + asn1.toDer(pki.certificateToAsn1(certificate).value[0].value[3]).getBytes(); + +// Verifies the detached signature the way a CMS verifier does, without using forge's signing code. +function expectValidDetachedSignature(signerInfo) { + const [, , , signedAttributes, , signatureValue] = signerInfo.value; + const digestAttribute = signedAttributes.value.find( + attribute => asn1.derToOid(attribute.value[0].value) === pki.oids.messageDigest + ); + const expectedDigest = createHash('sha256').update(content).digest('binary'); + expect(digestAttribute.value[1].value[0].value).toBe(expectedDigest); + + const signedBytes = Buffer.from(asn1.toDer(signedAttributes).getBytes(), 'binary'); + signedBytes[0] = 0x31; // signed over as a SET OF, not as the [0] IMPLICIT tag stored in the CMS + const isValid = verify( + 'sha256', + signedBytes, + createPublicKey(publicKey), + Buffer.from(signatureValue.value, 'binary') + ); + expect(isValid).toBeTrue(); +} + +describe('IssuerPreservingP12Signer', () => { + const nonAsciiIssuers = { + 'an em dash': 'Synthetic OpenSign local acceptance — not trusted', + 'accented letters': 'Société Générale Österreich', + 'non-Latin script': '文書署名認証局', + }; + + Object.entries(nonAsciiIssuers).forEach(([description, commonName]) => { + it(`matches the certificate issuer when it contains ${description}`, async () => { + const name = utf8Name(commonName); + const certificate = createCertificate(name, name, '0a1b2c'); + const p12 = createP12(certificate); + + const signature = await new IssuerPreservingP12Signer(p12, { passphrase }).sign(content); + const { certificates, signerIssuer, signerInfo } = parseCms(signature); + + expect(signerIssuer).toBe(issuerDer(certificate)); + expect(certificates).toEqual([asn1.toDer(pki.certificateToAsn1(certificate)).getBytes()]); + expectValidDetachedSignature(signerInfo); + }); + }); + + it('resolves the signer among chain certificates that share a serial number', async () => { + const leafName = utf8Name('Signer — leaf'); + const intermediateName = utf8Name('Issuing CA — intermediate'); + const rootName = utf8Name('Root CA — root'); + const leaf = createCertificate(leafName, intermediateName, '01'); + const intermediate = createCertificate( + intermediateName, + rootName, + '01', + generateKeyPair().publicKey + ); + + for (const chain of [ + [intermediate, leaf], + [leaf, intermediate], + ]) { + const signature = await new IssuerPreservingP12Signer(createP12(...chain), { + passphrase, + }).sign(content); + + expect(parseCms(signature).signerIssuer).toBe(issuerDer(leaf)); + } + }); + + it('leaves signatures with an ASCII issuer exactly as P12Signer builds them', async () => { + const name = [{ shortName: 'CN', value: 'OpenSign ASCII issuer' }]; + const p12 = createP12(createCertificate(name, name, '0a1b2c')); + const signingTime = new Date('2026-06-01T00:00:00Z'); + + const expected = await new P12Signer(p12, { passphrase }).sign(content, signingTime); + const signature = await new IssuerPreservingP12Signer(p12, { passphrase }).sign( + content, + signingTime + ); + + expect(signature.equals(expected)).toBeTrue(); + }); +}); diff --git a/apps/OpenSignServer/spec/brandContext.spec.js b/apps/OpenSignServer/spec/brandContext.spec.js new file mode 100644 index 0000000000..b1a59340da --- /dev/null +++ b/apps/OpenSignServer/spec/brandContext.spec.js @@ -0,0 +1,42 @@ +import { + LOCALHOST_HOSTNAMES, + REMINDER_INTERVAL_MS, + resolveDeploymentBrand +} from '../utils/brandContext.js'; + +// Centralized server defaults (issue #72): identical behavior, single source. +describe('REMINDER_INTERVAL_MS', () => { + it('keeps the hourly scheduler interval', () => { + expect(REMINDER_INTERVAL_MS).toBe(60 * 60 * 1000); + }); +}); + +describe('LOCALHOST_HOSTNAMES', () => { + it('is the single shared localhost list', () => { + expect([...LOCALHOST_HOSTNAMES]).toEqual(['localhost', '127.0.0.1']); + expect(Object.isFrozen(LOCALHOST_HOSTNAMES)).toBe(true); + }); +}); + +describe('resolveDeploymentBrand defaults', () => { + it('keeps the OpenSign brand behavior when nothing is set', () => { + const brand = resolveDeploymentBrand({}); + expect(brand.brandKey).toBe('opensign'); + expect(brand.isOpenSign).toBe(true); + expect(brand.productName).toBe('OpenSign™'); + expect(brand.assets.emailLogoUrl).toBe( + 'https://qikinnovation.ams3.digitaloceanspaces.com/logo.png' + ); + expect(brand.assets.pdfFontUrl).toBe('https://cdn.opensignlabs.com/webfonts/times.ttf'); + expect(brand.colors.emailAccent).toBe('#47a3ad'); + expect(brand.contacts.supportEmail).toBe('support@opensignlabs.com'); + expect(brand.urls.terms).toBe('https://www.opensignlabs.com/terms-and-conditions'); + expect(brand.urls.privacy).toBe('https://www.opensignlabs.com/privacy-policy'); + }); + + it('honors the APP_NAME override', () => { + const brand = resolveDeploymentBrand({ APP_NAME: 'Acme Sign' }); + expect(brand.productName).toBe('Acme Sign'); + expect(brand.senderName).toBe('Acme Sign'); + }); +}); diff --git a/apps/OpenSignServer/spec/checkAdminExist.spec.js b/apps/OpenSignServer/spec/checkAdminExist.spec.js new file mode 100644 index 0000000000..3edcbc3f80 --- /dev/null +++ b/apps/OpenSignServer/spec/checkAdminExist.spec.js @@ -0,0 +1,16 @@ +import { ALL_ADMIN_ROLES } from '../utils/roles.js'; +import CheckAdminExist from '../cloud/parsefunction/CheckAdminExist.js'; + +describe('CheckAdminExist wiring (#49)', () => { + it('shares the single ALL_ADMIN_ROLES source', async () => { + const mod = await import('../cloud/parsefunction/CheckAdminExist.js'); + expect(typeof mod.default).toBe('function'); + expect(ALL_ADMIN_ROLES).toEqual([ + 'contracts_Admin', + 'Admin', + 'contracts_OrgAdmin', + 'OrgAdmin' + ]); + expect(CheckAdminExist).toBe(mod.default); + }); +}); diff --git a/apps/OpenSignServer/spec/clientIp.spec.js b/apps/OpenSignServer/spec/clientIp.spec.js new file mode 100644 index 0000000000..103efb04f2 --- /dev/null +++ b/apps/OpenSignServer/spec/clientIp.spec.js @@ -0,0 +1,59 @@ +import { resolveClientIp, parseTrustProxy } from '../utils/clientIp.js'; + +// Pure helpers: they run without a Parse Server or a database. +describe('parseTrustProxy', () => { + it('defaults to no trusted proxy', () => { + expect(parseTrustProxy(undefined)).toEqual({ hops: 0, cloudflare: false }); + expect(parseTrustProxy('')).toEqual({ hops: 0, cloudflare: false }); + }); + + it('reads a hop count', () => { + expect(parseTrustProxy('2')).toEqual({ hops: 2, cloudflare: false }); + }); + + it('reads the cloudflare keyword', () => { + expect(parseTrustProxy('cloudflare')).toEqual({ hops: 0, cloudflare: true }); + }); + + it('ignores invalid values', () => { + expect(parseTrustProxy('abc')).toEqual({ hops: 0, cloudflare: false }); + expect(parseTrustProxy('-3')).toEqual({ hops: 0, cloudflare: false }); + }); +}); + +describe('resolveClientIp', () => { + const socket = '10.0.0.9'; + + it('ignores forged headers when no proxy is trusted', () => { + const headers = { + 'x-forwarded-for': '1.2.3.4', + 'cf-connecting-ip': '5.6.7.8', + 'x-real-ip': '9.9.9.9', + }; + expect(resolveClientIp(headers, socket, { hops: 0, cloudflare: false })).toBe(socket); + }); + + it('uses the entry added by the trusted proxy, not the forged first entry', () => { + const headers = { 'x-forwarded-for': '1.2.3.4, 203.0.113.7' }; + expect(resolveClientIp(headers, socket, { hops: 1, cloudflare: false })).toBe('203.0.113.7'); + }); + + it('skips one extra hop per trusted proxy', () => { + const headers = { 'x-forwarded-for': '1.2.3.4, 203.0.113.7, 10.1.1.1' }; + expect(resolveClientIp(headers, socket, { hops: 2, cloudflare: false })).toBe('203.0.113.7'); + }); + + it('falls back to the socket when the chain is empty', () => { + expect(resolveClientIp({}, socket, { hops: 1, cloudflare: false })).toBe(socket); + }); + + it('trusts cf-connecting-ip only in cloudflare mode', () => { + const headers = { 'cf-connecting-ip': '5.6.7.8' }; + expect(resolveClientIp(headers, socket, { hops: 0, cloudflare: true })).toBe('5.6.7.8'); + expect(resolveClientIp(headers, socket, { hops: 0, cloudflare: false })).toBe(socket); + }); + + it('returns an empty string when nothing is known', () => { + expect(resolveClientIp({}, undefined, { hops: 0, cloudflare: false })).toBe(''); + }); +}); diff --git a/apps/OpenSignServer/spec/dotenvOrdering.spec.js b/apps/OpenSignServer/spec/dotenvOrdering.spec.js new file mode 100644 index 0000000000..52f23a7cd4 --- /dev/null +++ b/apps/OpenSignServer/spec/dotenvOrdering.spec.js @@ -0,0 +1,41 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const appConfigUrl = pathToFileURL( + path.join(here, '..', 'utils', 'appConfig.js') +).href; + +describe('dotenv ordering for cloudServerUrl (#85)', () => { + it('honors .env file values with no exported PORT/PARSE_MOUNT', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dotenv-order-')); + fs.writeFileSync( + path.join(dir, '.env'), + 'PORT=8234\nPARSE_MOUNT=/parse\n' + ); + const env = { ...process.env }; + for (const key of [ + 'PORT', + 'PARSE_MOUNT', + 'SERVER_URL', + 'PUBLIC_API_URL', + 'CLOUD_SERVER_URL' + ]) { + delete env[key]; + } + const out = execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `import(${JSON.stringify(appConfigUrl)}).then(m => console.log(m.cloudServerUrl))` + ], + { cwd: dir, env, encoding: 'utf8' } + ).trim(); + expect(out).toBe('http://localhost:8234/parse'); + fs.rmSync(dir, { recursive: true, force: true }); + }); +}); diff --git a/apps/OpenSignServer/spec/envConfig.spec.js b/apps/OpenSignServer/spec/envConfig.spec.js new file mode 100644 index 0000000000..43915c2c59 --- /dev/null +++ b/apps/OpenSignServer/spec/envConfig.spec.js @@ -0,0 +1,35 @@ +import { getDatabaseUri, getSmtpPort } from '../utils/envConfig.js'; + +// Pure helpers: they run without a Parse Server or a database. +describe('getDatabaseUri', () => { + it('prefers DATABASE_URI', () => { + expect(getDatabaseUri({ DATABASE_URI: 'mongodb://a/x', MONGODB_URI: 'mongodb://b/y' })).toBe( + 'mongodb://a/x' + ); + }); + + it('accepts MONGODB_URI as the legacy name', () => { + expect(getDatabaseUri({ MONGODB_URI: 'mongodb://b/y' })).toBe('mongodb://b/y'); + }); + + it('fails fast when neither variable is set', () => { + expect(() => getDatabaseUri({})).toThrowError(/DATABASE_URI/); + expect(() => getDatabaseUri({ DATABASE_URI: ' ' })).toThrowError(/DATABASE_URI/); + }); +}); + +describe('getSmtpPort', () => { + it('defaults to the implicit TLS port', () => { + expect(getSmtpPort({})).toBe(465); + expect(getSmtpPort({ SMTP_PORT: '' })).toBe(465); + }); + + it('reads SMTP_PORT as a number', () => { + expect(getSmtpPort({ SMTP_PORT: '587' })).toBe(587); + }); + + it('fails fast on an invalid SMTP_PORT', () => { + expect(() => getSmtpPort({ SMTP_PORT: 'abc' })).toThrowError(/SMTP_PORT/); + expect(() => getSmtpPort({ SMTP_PORT: '0' })).toThrowError(/SMTP_PORT/); + }); +}); diff --git a/apps/OpenSignServer/spec/ldapConfig.spec.js b/apps/OpenSignServer/spec/ldapConfig.spec.js new file mode 100644 index 0000000000..0df7152ddb --- /dev/null +++ b/apps/OpenSignServer/spec/ldapConfig.spec.js @@ -0,0 +1,93 @@ +import { getLdapConfig } from '../utils/ldapConfig.js'; +import { escapeLdapFilter } from '../utils/ldapAuth.js'; + +describe('getLdapConfig', () => { + it('is disabled by default when LDAP_ENABLED is unset', () => { + const config = getLdapConfig({}); + expect(config.enabled).toBe(false); + }); + + it('is disabled when LDAP_ENABLED is false', () => { + const config = getLdapConfig({ LDAP_ENABLED: 'false' }); + expect(config.enabled).toBe(false); + }); + + it('parses valid LDAP configuration with default values', () => { + const config = getLdapConfig({ + LDAP_ENABLED: 'true', + }); + expect(config.enabled).toBe(true); + expect(config.host).toBe('localhost'); + expect(config.port).toBe(389); + expect(config.url).toBe('ldap://localhost:389'); + expect(config.emailAttr).toBe('mail'); + expect(config.nameAttr).toBe('displayName'); + expect(config.phoneAttr).toBe('telephoneNumber'); + expect(config.startTls).toBe(false); + expect(config.rejectUnauthorized).toBe(true); + expect(config.allowFallback).toBe(true); + }); + + it('respects custom host, port and LDAPS protocol', () => { + const config = getLdapConfig({ + LDAP_ENABLED: 'true', + LDAP_HOST: 'directory.corp.internal', + LDAP_PORT: '636', + }); + expect(config.enabled).toBe(true); + expect(config.host).toBe('directory.corp.internal'); + expect(config.port).toBe(636); + expect(config.url).toBe('ldaps://directory.corp.internal:636'); + }); + + it('prefers explicit LDAP_URL if provided', () => { + const config = getLdapConfig({ + LDAP_ENABLED: 'true', + LDAP_URL: 'ldaps://custom.example.com:10636', + }); + expect(config.url).toBe('ldaps://custom.example.com:10636'); + }); + + it('reads bind credentials and search parameters', () => { + const config = getLdapConfig({ + LDAP_ENABLED: 'true', + LDAP_BIND_DN: 'cn=admin,dc=example,dc=org', + LDAP_BIND_PASSWORD: 'secretpassword', + LDAP_SEARCH_BASE: 'ou=users,dc=example,dc=org', + LDAP_USER_FILTER: '(&(objectClass=inetOrgPerson)(uid={{username}}))', + LDAP_EMAIL_ATTR: 'userPrincipalName', + LDAP_NAME_ATTR: 'cn', + LDAP_STARTTLS: 'true', + LDAP_TLS_REJECT_UNAUTHORIZED: 'false', + LDAP_ALLOW_LOCAL_FALLBACK: 'false', + }); + expect(config.bindDn).toBe('cn=admin,dc=example,dc=org'); + expect(config.bindPassword).toBe('secretpassword'); + expect(config.searchBase).toBe('ou=users,dc=example,dc=org'); + expect(config.searchFilter).toBe('(&(objectClass=inetOrgPerson)(uid={{username}}))'); + expect(config.emailAttr).toBe('userPrincipalName'); + expect(config.nameAttr).toBe('cn'); + expect(config.startTls).toBe(true); + expect(config.rejectUnauthorized).toBe(false); + expect(config.allowFallback).toBe(false); + }); +}); + +describe('escapeLdapFilter', () => { + it('escapes special characters to prevent LDAP injection', () => { + expect(escapeLdapFilter('admin*')).toBe('admin\\2a'); + expect(escapeLdapFilter('user(test)')).toBe('user\\28test\\29'); + expect(escapeLdapFilter('domain\\user')).toBe('domain\\5cuser'); + expect(escapeLdapFilter('null\0byte')).toBe('null\\00byte'); + }); + + it('leaves safe alphanumeric strings unchanged', () => { + expect(escapeLdapFilter('johndoe')).toBe('johndoe'); + expect(escapeLdapFilter('john.doe@example.com')).toBe('john.doe@example.com'); + }); + + it('handles non-string values gracefully', () => { + expect(escapeLdapFilter(null)).toBe(''); + expect(escapeLdapFilter(undefined)).toBe(''); + }); +}); diff --git a/apps/OpenSignServer/spec/publicUrl.spec.js b/apps/OpenSignServer/spec/publicUrl.spec.js new file mode 100644 index 0000000000..66299d8c46 --- /dev/null +++ b/apps/OpenSignServer/spec/publicUrl.spec.js @@ -0,0 +1,54 @@ +import { parseOriginList, resolvePublicUrl } from '../utils/publicUrl.js'; + +// Pure helpers: they run without a Parse Server or a database. +describe('parseOriginList', () => { + it('splits, trims and drops trailing slashes and empty entries', () => { + expect(parseOriginList(' https://a.example/ , ,https://b.example ')).toEqual([ + 'https://a.example', + 'https://b.example', + ]); + }); + + it('returns an empty list for a missing value', () => { + expect(parseOriginList(undefined)).toEqual([]); + }); +}); + +describe('resolvePublicUrl', () => { + const config = { + baseUrl: 'https://app.example/', + allowlist: ['https://sign.customer.example'], + }; + + it('returns the configured URL for a forged Host', () => { + expect(resolvePublicUrl({ host: 'evil.example' }, config)).toBe('https://app.example'); + }); + + it('returns the configured URL for a forged Origin', () => { + expect(resolvePublicUrl({ origin: 'https://evil.example', host: 'app.example' }, config)).toBe( + 'https://app.example' + ); + }); + + it('keeps an allowed custom domain from Origin', () => { + expect(resolvePublicUrl({ origin: 'https://sign.customer.example' }, config)).toBe( + 'https://sign.customer.example' + ); + }); + + it('keeps an allowed custom domain from Host', () => { + expect(resolvePublicUrl({ host: 'sign.customer.example' }, config)).toBe( + 'https://sign.customer.example' + ); + }); + + it('always allows the configured URL itself', () => { + expect(resolvePublicUrl({ origin: 'https://app.example' }, config)).toBe('https://app.example'); + }); + + it('falls back to the Host only when no URL is configured', () => { + expect(resolvePublicUrl({ host: 'dev.example' }, { baseUrl: '', allowlist: [] })).toBe( + 'https://dev.example' + ); + }); +}); diff --git a/apps/OpenSignServer/spec/serverConfig.spec.js b/apps/OpenSignServer/spec/serverConfig.spec.js new file mode 100644 index 0000000000..79b8b0ea85 --- /dev/null +++ b/apps/OpenSignServer/spec/serverConfig.spec.js @@ -0,0 +1,46 @@ +import { getServerConfig, rewritePublicApiUrl } from '../utils/serverConfig.js'; + +// Pure helpers: they run without a Parse Server or a database. +describe('getServerConfig', () => { + it('uses the documented defaults when nothing is set', () => { + const config = getServerConfig({}); + expect(config.port).toBe(8080); + expect(config.bindHost).toBe('0.0.0.0'); + expect(config.serverOrigin).toBe('http://localhost:8080'); + expect(config.cloudServerUrl).toBe('http://localhost:8080/app'); + }); + + it('follows a custom PORT and PARSE_MOUNT', () => { + const config = getServerConfig({ PORT: '9000', PARSE_MOUNT: '/parse' }); + expect(config.cloudServerUrl).toBe('http://localhost:9000/parse'); + }); + + it('reads BIND_HOST', () => { + expect(getServerConfig({ BIND_HOST: '127.0.0.1' }).bindHost).toBe('127.0.0.1'); + }); + + it('fails fast on an invalid PORT', () => { + expect(() => getServerConfig({ PORT: 'abc' })).toThrowError(/PORT/); + expect(() => getServerConfig({ PORT: '70000' })).toThrowError(/PORT/); + }); +}); + +describe('rewritePublicApiUrl', () => { + it('maps a public API URL to the internal origin', () => { + expect( + rewritePublicApiUrl('https://dev.example/api/files/a.pdf', 'https://dev.example/api', 'http://localhost:8080') + ).toBe('http://localhost:8080/files/a.pdf'); + }); + + it('leaves the URL untouched when PUBLIC_API_URL is not set', () => { + expect(rewritePublicApiUrl('https://x.example/a.pdf', '', 'http://localhost:8080')).toBe( + 'https://x.example/a.pdf' + ); + }); + + it('leaves URLs outside PUBLIC_API_URL untouched', () => { + expect( + rewritePublicApiUrl('https://other.example/a.pdf', 'https://dev.example/api', 'http://localhost:8080') + ).toBe('https://other.example/a.pdf'); + }); +}); diff --git a/apps/OpenSignServer/spec/support/jasmine.json b/apps/OpenSignServer/spec/support/jasmine.json new file mode 100644 index 0000000000..11b40ae061 --- /dev/null +++ b/apps/OpenSignServer/spec/support/jasmine.json @@ -0,0 +1,4 @@ +{ + "spec_dir": "spec", + "spec_files": ["**/*[sS]pec.js"] +} diff --git a/apps/OpenSignServer/spec/support/jasmine.unit.json b/apps/OpenSignServer/spec/support/jasmine.unit.json new file mode 100644 index 0000000000..cd97e11e38 --- /dev/null +++ b/apps/OpenSignServer/spec/support/jasmine.unit.json @@ -0,0 +1,17 @@ +{ + "spec_dir": "spec", + "spec_files": [ + "unit.spec.js", + "brandContext.spec.js", + "clientIp.spec.js", + "publicUrl.spec.js", + "serverConfig.spec.js", + "dotenvOrdering.spec.js", + "checkAdminExist.spec.js", + "envConfig.spec.js", + "utilsFacade.spec.js" + ], + "helpers": [], + "stopSpecOnExpectationFailure": false, + "random": false +} diff --git a/apps/OpenSignServer/spec/unit.spec.js b/apps/OpenSignServer/spec/unit.spec.js new file mode 100644 index 0000000000..ada3bfa63e --- /dev/null +++ b/apps/OpenSignServer/spec/unit.spec.js @@ -0,0 +1,68 @@ +import { stripHtml } from '../Utils.js'; +import { + ADMIN_ROLES, + ORG_ADMIN_ROLES, + ALL_ADMIN_ROLES, + isAdminRole, + isOrgAdminRole, +} from '../utils/roles.js'; + +// Pure helpers only: these run without a Parse Server or a database. +describe('stripHtml', () => { + it('returns an empty string for an empty body', () => { + expect(stripHtml('')).toBe(''); + expect(stripHtml(null)).toBe(''); + expect(stripHtml(undefined)).toBe(''); + }); + + it('keeps the text content of a simple body', () => { + expect(stripHtml('<p>Hello</p>')).toBe('Hello'); + }); + + it('turns line breaks into newlines', () => { + expect(stripHtml('a<br>b')).toBe('a\nb'); + expect(stripHtml('<p>a</p><p>b</p>')).toBe('a\nb'); + }); + + it('decodes the entities used in the templates', () => { + expect(stripHtml('a b & c <d>')).toBe('a b & c <d>'); + }); + + it('drops style and script blocks entirely', () => { + expect(stripHtml('<style>.a{color:red}</style><p>keep</p>')).toBe('keep'); + expect(stripHtml('<script>alert(1)</script><p>keep</p>')).toBe('keep'); + }); + + it('collapses more than two consecutive newlines', () => { + expect(stripHtml('<p>a</p><p></p><p></p><p>b</p>')).toBe('a\n\nb'); + }); +}); + +describe('admin roles', () => { + it('accepts every documented admin role', () => { + expect(isAdminRole('contracts_Admin')).toBe(true); + expect(isAdminRole('Admin')).toBe(true); + expect(isAdminRole('contracts_OrgAdmin')).toBe(true); + expect(isAdminRole('OrgAdmin')).toBe(true); + }); + + it('rejects a regular user and a missing role', () => { + expect(isAdminRole('contracts_User')).toBe(false); + expect(isAdminRole(undefined)).toBe(false); + expect(isAdminRole('')).toBe(false); + }); + + it('separates the organization admin from the plain admin', () => { + expect(isOrgAdminRole('contracts_OrgAdmin')).toBe(true); + expect(isOrgAdminRole('OrgAdmin')).toBe(true); + expect(isOrgAdminRole('contracts_Admin')).toBe(false); + }); + + it('keeps the legacy names in the lists used by the queries', () => { + expect(ADMIN_ROLES).toContain('contracts_Admin'); + expect(ORG_ADMIN_ROLES).toContain('contracts_OrgAdmin'); + expect(ALL_ADMIN_ROLES.length).toBe( + ADMIN_ROLES.length + ORG_ADMIN_ROLES.length + ); + }); +}); diff --git a/apps/OpenSignServer/spec/updatePreferences.spec.js b/apps/OpenSignServer/spec/updatePreferences.spec.js new file mode 100644 index 0000000000..4d493993b7 --- /dev/null +++ b/apps/OpenSignServer/spec/updatePreferences.spec.js @@ -0,0 +1,64 @@ +import Parse from 'parse/node'; +import updatePreferences from '../cloud/parsefunction/updatePreferences.js'; + +describe('updatePreferences theme', () => { + const user = { id: 'user1' }; + let savedObjects; + + beforeEach(() => { + globalThis.Parse = Parse; + savedObjects = []; + spyOn(console, 'log'); + spyOn(Parse.Query.prototype, 'first').and.resolveTo({ id: 'extUser1' }); + spyOn(Parse.Object.prototype, 'save').and.callFake(function () { + savedObjects.push(this); + return Promise.resolve(this); + }); + }); + + afterEach(() => { + delete globalThis.Parse; + }); + + ['dark', 'light'].forEach(theme => { + it(`saves ${theme} when it is the only preference sent`, async () => { + await updatePreferences({ user, params: { Theme: theme } }); + + expect(savedObjects.length).toBe(1); + expect(savedObjects[0].get('Theme')).toBe(theme); + }); + }); + + it('leaves the other preferences untouched', async () => { + await updatePreferences({ user, params: { Theme: 'dark' } }); + + expect(savedObjects[0].dirtyKeys()).toEqual(['Theme']); + }); + + it('does not change the theme when other preferences are saved', async () => { + await updatePreferences({ user, params: { Timezone: 'UTC' } }); + + expect(savedObjects[0].dirty('Theme')).toBeFalse(); + }); + + [{ Theme: 'solarized' }, { Theme: 1 }, { Theme: ['dark'] }, { Theme: {} }].forEach(params => { + it(`rejects the invalid theme ${JSON.stringify(params.Theme)}`, async () => { + await expectAsync(updatePreferences({ user, params })).toBeRejectedWith( + jasmine.objectContaining({ code: Parse.Error.INVALID_QUERY, message: 'Invalid theme.' }) + ); + expect(savedObjects).toEqual([]); + }); + }); + + it('still rejects a request without any preference', async () => { + await expectAsync(updatePreferences({ user, params: {} })).toBeRejectedWith( + jasmine.objectContaining({ message: 'Please provide parameters.' }) + ); + }); + + it('rejects a request without a user', async () => { + await expectAsync(updatePreferences({ params: { Theme: 'dark' } })).toBeRejectedWith( + jasmine.objectContaining({ code: Parse.Error.INVALID_SESSION_TOKEN }) + ); + }); +}); diff --git a/apps/OpenSignServer/spec/utilsFacade.spec.js b/apps/OpenSignServer/spec/utilsFacade.spec.js new file mode 100644 index 0000000000..9c58e00802 --- /dev/null +++ b/apps/OpenSignServer/spec/utilsFacade.spec.js @@ -0,0 +1,149 @@ +import { PDFDocument } from 'pdf-lib'; +import { + MAX_DESCRIPTION_LENGTH, + MAX_NAME_LENGTH, + MAX_NOTE_LENGTH, + appName, + cloudServerUrl, + color, + emailRegex, + flattenPdf, + formatDateTime, + formatTimeInTimezone, + generateId, + getSecureUrl, + handleValidImage, + mailTemplate, + normalizeMailSubject, + prefillBlockColor, + prefillDraftDocWidget, + prefillDraftTemWidget, + randomId, + replaceMailVaribles, + sanitizeFileName, + selectFormat, + serverAppId, + smtpenable, + smtpsecure, + stripHtml, + useLocal, +} from '../Utils.js'; +import { getServerConfig } from '../utils/serverConfig.js'; + +// Characterization: pins the observable behavior of Utils.js so the split +// into utils/<name>.js modules can be verified against the same contract. +describe('Utils facade contract', () => { + it('exposes the documented app constants', () => { + expect(appName).toBe('OpenSign™'); + expect(MAX_NAME_LENGTH).toBe(250); + expect(MAX_NOTE_LENGTH).toBe(200); + expect(MAX_DESCRIPTION_LENGTH).toBe(500); + expect(prefillBlockColor).toBe('transparent'); + expect(prefillDraftDocWidget).toEqual(['date', 'textbox', 'checkbox', 'radio button', 'image']); + expect(prefillDraftTemWidget).toContain('dropdown'); + expect(Array.isArray(color)).toBe(true); + expect(color.length).toBeGreaterThan(0); + }); + + it('derives cloudServerUrl from the server config, not a hardcoded port', () => { + expect(cloudServerUrl).toBe(getServerConfig(process.env).cloudServerUrl); + if (!process.env.PORT && !process.env.PARSE_MOUNT) { + expect(cloudServerUrl).toBe('http://localhost:8080/app'); + } + }); + + it('reads the server identity and mail flags from the environment', () => { + if (!process.env.APP_ID) expect(serverAppId).toBe('opensign'); + if (!process.env.USE_LOCAL) expect(useLocal).toBe('false'); + if (!process.env.SMTP_ENABLE) expect(smtpenable).toBe(false); + if (!process.env.SMTP_SECURE && !process.env.SMTP_PORT) expect(smtpsecure).toBe(true); + }); + + it('validates email addresses', () => { + expect(emailRegex.test('a@b.com')).toBe(true); + expect(emailRegex.test('not-an-email')).toBe(false); + }); + + it('normalizes the product name in mail subjects', () => { + expect(normalizeMailSubject('OpenSign™ request')).toBe('opensign request'); + expect(normalizeMailSubject(null)).toBe(''); + }); + + it('replaces mail variables in subject and body', () => { + const out = replaceMailVaribles('Hi {{name}}', 'Doc {{title}} for {{name}}', { + name: 'Ada', + title: 'NDA', + }); + expect(out).toEqual({ subject: 'Hi Ada', body: 'Doc NDA for Ada' }); + }); + + it('sanitizes file names', () => { + expect(sanitizeFileName('my doc (1).pdf')).toBe('mydoc1.pdf'); + }); + + it('generates lowercase alphanumeric ids of the requested length', () => { + expect(generateId(10)).toMatch(/^[a-z0-9]{10}$/); + }); + + it('generates numeric ids with the requested digit count', () => { + const id = randomId(8); + expect(id).toBeGreaterThanOrEqual(10000000); + expect(id).toBeLessThanOrEqual(99999999); + }); + + it('strips html to text', () => { + expect(stripHtml('<p>a</p><p>b</p>')).toBe('a\nb'); + }); + + it('maps date format names', () => { + expect(selectFormat('DD-MM-YYYY')).toBe('dd-MM-yyyy'); + expect(selectFormat('unknown')).toBe('MM/dd/yyyy'); + }); + + it('formats time without a timezone as UTC', () => { + expect(formatTimeInTimezone(new Date('2024-01-02T03:04:05Z'))).toContain('2024'); + }); + + it('formats a date in the given timezone', () => { + const out = formatDateTime(new Date('2024-01-02T03:04:05Z'), 'YYYY-MM-DD', 'UTC', false); + expect(out).toContain('2024-01-02'); + }); + + it('passes non-file urls through unchanged', () => { + expect(getSecureUrl('https://cdn.example/a.pdf')).toEqual({ url: 'https://cdn.example/a.pdf' }); + }); + + it('builds a sign-request mail with the sender and title', () => { + const { subject, body } = mailTemplate({ + senderName: 'Ada', + title: 'NDA', + senderMail: 'a@b.com', + organization: 'Acme', + localExpireDate: 'tomorrow', + note: 'hi', + signingUrl: 'https://app.example/sign/1', + }); + expect(subject).toContain('Ada'); + expect(subject).toContain('NDA'); + expect(body).toContain('https://app.example/sign/1'); + }); + + it('flattens a widget pdf into static content', async () => { + const doc = await PDFDocument.create(); + const page = doc.addPage([300, 200]); + const form = doc.getForm(); + const field = form.createTextField('name'); + field.setText('Ada'); + field.addToPage(page, { x: 10, y: 10, width: 200, height: 40 }); + const bytes = await doc.save(); + const flat = await flattenPdf(bytes); + const reloaded = await PDFDocument.load(flat); + expect(reloaded.getForm().getFields().length).toBe(0); + }); + + it('normalizes non-prefill placeholders without network calls', async () => { + const placeholders = [{ Role: 'signer', signerPtr: { className: '_User', objectId: 'u1' } }]; + const out = await handleValidImage(placeholders); + expect(out).toEqual(placeholders); + }); +}); diff --git a/apps/OpenSignServer/spec/webhookDispatcher.test.js b/apps/OpenSignServer/spec/webhookDispatcher.test.js new file mode 100644 index 0000000000..1566540549 --- /dev/null +++ b/apps/OpenSignServer/spec/webhookDispatcher.test.js @@ -0,0 +1,241 @@ +/** + * @file webhookDispatcher.test.js + * @description Integration test suite for the OpenSign Enterprise Webhook Dispatcher. + * Tests are written using Jest with ESM module support. + * Run with: node --experimental-vm-modules node_modules/.bin/jest webhookDispatcher.test.js + */ + +import { jest } from '@jest/globals'; +import { generateSignature, dispatchWithBackoff } from './webhookDispatcher.js'; + +// ─── Mock axios at the module level ─────────────────────────────────────────── +jest.mock('axios', () => ({ + default: { + post: jest.fn(), + }, +})); + +import axios from 'axios'; +const mockPost = /** @type {jest.MockedFunction<typeof axios.post>} */ (axios.post); + +// ─── Shared Test Fixtures ────────────────────────────────────────────────────── +const MOCK_SECRET = 'os_secret_test_123'; +const MOCK_URL = 'https://client-endpoint.example.com/webhook'; + +/** @type {import('./webhookDispatcher.js').WebhookPayload} */ +const MOCK_PAYLOAD = { + eventId: 'evt_abc123', + event: 'document.signed', + documentId: 'doc_999', + status: 'COMPLETED', + timestamp: '2026-04-17T00:00:00.000Z', + data: { signerEmail: 'john@example.com' }, +}; + +// ─── Helper to create an Axios-like error ──────────────────────────────────── +function axiosError(status, message = 'Request failed') { + return Object.assign(new Error(message), { + isAxiosError: true, + message, + response: status ? { status } : undefined, + }); +} + +// ─── Test Suite ─────────────────────────────────────────────────────────────── +describe('webhookDispatcher', () => { + beforeEach(() => { + jest.clearAllMocks(); + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + // ─── 1. HMAC Signature Integrity ──────────────────────────────────────── + describe('generateSignature', () => { + it('produces a 64-character hexadecimal SHA-256 HMAC digest', () => { + const sig = generateSignature('test-payload', MOCK_SECRET); + expect(sig).toHaveLength(64); + expect(sig).toMatch(/^[a-f0-9]{64}$/); + }); + + it('is deterministic — same input always produces the same signature', () => { + const sig1 = generateSignature('payload', MOCK_SECRET); + const sig2 = generateSignature('payload', MOCK_SECRET); + expect(sig1).toBe(sig2); + }); + + it('produces distinct signatures for different secrets', () => { + const sig1 = generateSignature('payload', 'secret-A'); + const sig2 = generateSignature('payload', 'secret-B'); + expect(sig1).not.toBe(sig2); + }); + + it('produces distinct signatures for different payloads', () => { + const sig1 = generateSignature('payload-A', MOCK_SECRET); + const sig2 = generateSignature('payload-B', MOCK_SECRET); + expect(sig1).not.toBe(sig2); + }); + }); + + // ─── 2. Successful First-Attempt Delivery ──────────────────────────────── + describe('dispatchWithBackoff — successful delivery', () => { + it('delivers webhook successfully on first attempt', async () => { + mockPost.mockResolvedValueOnce({ status: 200 }); + + const result = await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + + expect(result.success).toBe(true); + expect(result.attempts).toBe(1); + expect(result.statusCode).toBe(200); + expect(result.isRetryable).toBe(false); + expect(mockPost).toHaveBeenCalledTimes(1); + }); + + it('sends the correct headers including HMAC signature and idempotency key', async () => { + mockPost.mockResolvedValueOnce({ status: 200 }); + + await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + + expect(mockPost).toHaveBeenCalledWith( + MOCK_URL, + JSON.stringify(MOCK_PAYLOAD), + expect.objectContaining({ + headers: expect.objectContaining({ + 'Content-Type': 'application/json', + 'X-OpenSign-Signature': expect.stringMatching(/^[a-f0-9]{64}$/), + 'X-OpenSign-Event': 'document.signed', + 'Idempotency-Key': 'os_evt_evt_abc123_attempt_1', + 'X-OpenSign-Delivery-Attempt': '1', + }), + }) + ); + }); + + it('the outgoing signature matches a locally computed HMAC', async () => { + mockPost.mockResolvedValueOnce({ status: 200 }); + await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + + const [[, , callOptions]] = mockPost.mock.calls; + const outgoingSignature = callOptions.headers['X-OpenSign-Signature']; + const expectedSignature = generateSignature(JSON.stringify(MOCK_PAYLOAD), MOCK_SECRET); + + expect(outgoingSignature).toBe(expectedSignature); + }); + }); + + // ─── 3. Smart Retry on 5xx Server Error ────────────────────────────────── + describe('dispatchWithBackoff — smart retries', () => { + it('retries on HTTP 500 and succeeds on second attempt', async () => { + mockPost + .mockRejectedValueOnce(axiosError(500, 'Internal Server Error')) + .mockResolvedValueOnce({ status: 200 }); + + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + await jest.runAllTimersAsync(); + const result = await promise; + + expect(result.success).toBe(true); + expect(result.attempts).toBe(2); + expect(mockPost).toHaveBeenCalledTimes(2); + }); + + it('retries on network timeout (no response status)', async () => { + mockPost + .mockRejectedValueOnce(axiosError(undefined, 'timeout of 5000ms exceeded')) + .mockResolvedValueOnce({ status: 200 }); + + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + await jest.runAllTimersAsync(); + const result = await promise; + + expect(result.success).toBe(true); + expect(result.attempts).toBe(2); + }); + + it('retries on HTTP 429 Too Many Requests (rate-limited, not a permanent client error)', async () => { + mockPost + .mockRejectedValueOnce(axiosError(429, 'Too Many Requests')) + .mockResolvedValueOnce({ status: 200 }); + + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + await jest.runAllTimersAsync(); + const result = await promise; + + expect(result.success).toBe(true); + expect(result.attempts).toBe(2); + }); + }); + + // ─── 4. Non-Retryable 4xx Error Blocking ───────────────────────────────── + describe('dispatchWithBackoff — non-retryable errors', () => { + it.each([400, 401, 403, 404, 422])( + 'does NOT retry on HTTP %i (client error)', + async (status) => { + mockPost.mockRejectedValueOnce(axiosError(status)); + + const result = await dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + + expect(result.success).toBe(false); + expect(result.attempts).toBe(1); + expect(result.isRetryable).toBe(false); + expect(mockPost).toHaveBeenCalledTimes(1); + } + ); + }); + + // ─── 5. Permanent Failure After MAX_RETRIES ─────────────────────────────── + describe('dispatchWithBackoff — exhaustion', () => { + it('fails permanently after 3 consecutive 503 errors (MAX_RETRIES)', async () => { + mockPost.mockRejectedValue(axiosError(503, 'Service Unavailable')); + + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + await jest.runAllTimersAsync(); + await jest.runAllTimersAsync(); + const result = await promise; + + expect(result.success).toBe(false); + expect(result.attempts).toBe(3); + expect(result.isRetryable).toBe(true); + expect(mockPost).toHaveBeenCalledTimes(3); + }); + }); + + // ─── 6. Idempotency Key Increment ──────────────────────────────────────── + describe('dispatchWithBackoff — idempotency', () => { + it('increments the idempotency key suffix with each retry attempt', async () => { + mockPost.mockRejectedValue(axiosError(504, 'Gateway Timeout')); + + const promise = dispatchWithBackoff(MOCK_URL, MOCK_PAYLOAD, MOCK_SECRET); + await jest.runAllTimersAsync(); + await jest.runAllTimersAsync(); + await promise; + + expect(mockPost).toHaveBeenNthCalledWith( + 1, + expect.any(String), + expect.any(String), + expect.objectContaining({ + headers: expect.objectContaining({ 'Idempotency-Key': 'os_evt_evt_abc123_attempt_1' }), + }) + ); + expect(mockPost).toHaveBeenNthCalledWith( + 2, + expect.any(String), + expect.any(String), + expect.objectContaining({ + headers: expect.objectContaining({ 'Idempotency-Key': 'os_evt_evt_abc123_attempt_2' }), + }) + ); + expect(mockPost).toHaveBeenNthCalledWith( + 3, + expect.any(String), + expect.any(String), + expect.objectContaining({ + headers: expect.objectContaining({ 'Idempotency-Key': 'os_evt_evt_abc123_attempt_3' }), + }) + ); + }); + }); +}); diff --git a/apps/OpenSignServer/utils/AuthUtils.js b/apps/OpenSignServer/utils/AuthUtils.js index 6f6823829b..5fd1b2c28c 100644 --- a/apps/OpenSignServer/utils/AuthUtils.js +++ b/apps/OpenSignServer/utils/AuthUtils.js @@ -1,6 +1,8 @@ export const isAuthenticated = async sessionUser => { try { - return sessionUser ? true : false; + if (!sessionUser) return false; + // Require a concrete user identity, not just a truthy object. + return Boolean(sessionUser.objectId || sessionUser.id); } catch (err) { console.log(`authentication error ${err?.message}`); return false; diff --git a/apps/OpenSignServer/utils/appConfig.js b/apps/OpenSignServer/utils/appConfig.js new file mode 100644 index 0000000000..1d3cdb4712 --- /dev/null +++ b/apps/OpenSignServer/utils/appConfig.js @@ -0,0 +1,52 @@ +import dotenv from 'dotenv'; +import { getServerConfig } from './serverConfig.js'; + +// dotenv must load before getServerConfig runs: ESM evaluates imports before +// the entry point body, so relying on index.js's dotenv.config() leaves +// cloudServerUrl frozen to defaults on .env-file-only boots (#85). +dotenv.config({ quiet: true }); + +// Centralized server identity, limits and mail flags. cloudServerUrl is +// derived from the server config (PORT/PARSE_MOUNT), never hardcoded. +export const cloudServerUrl = getServerConfig(process.env).cloudServerUrl; +export const serverAppId = process.env.APP_ID || 'opensign'; +export const appName = 'OpenSign™'; +export const prefillDraftDocWidget = ['date', 'textbox', 'checkbox', 'radio button', 'image']; +export const prefillDraftTemWidget = [ + 'date', + 'textbox', + 'checkbox', + 'radio button', + 'image', + 'dropdown', +]; +export const MAX_NAME_LENGTH = 250; +export const MAX_NOTE_LENGTH = 200; +export const MAX_DESCRIPTION_LENGTH = 500; +export const color = [ + '#93a3db', + '#e6c3db', + '#c0e3db', + '#bce3db', + '#b8ccdb', + '#ceb8db', + '#ffccff', + '#99ffcc', + '#cc99ff', + '#ffcc99', + '#66ccff', + '#ffffcc', +]; + +export const prefillBlockColor = 'transparent'; + +export const useLocal = process.env.USE_LOCAL ? process.env.USE_LOCAL.toLowerCase() : 'false'; +export const smtpsecure = + process.env.SMTP_SECURE !== undefined + ? process.env.SMTP_SECURE.toLowerCase() === 'true' + : process.env.SMTP_PORT && process.env.SMTP_PORT !== '465' + ? false + : true; +export const smtpenable = + process.env.SMTP_ENABLE && process.env.SMTP_ENABLE.toLowerCase() === 'true' ? true : false; +export const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; diff --git a/apps/OpenSignServer/utils/brandContext.js b/apps/OpenSignServer/utils/brandContext.js index d46e410ee1..0d4edd25be 100644 --- a/apps/OpenSignServer/utils/brandContext.js +++ b/apps/OpenSignServer/utils/brandContext.js @@ -3,6 +3,11 @@ const OPEN_SIGN_EMAIL_LOGO = 'https://qikinnovation.ams3.digitaloceanspaces.com/ const OPEN_SIGN_ACCENT = '#47a3ad'; const OPEN_SIGN_PDF_FONT = 'https://cdn.opensignlabs.com/webfonts/times.ttf'; +// Centralized server defaults (issue #72): single source for values that were +// previously repeated inline. Defaults keep the behavior the server always had. +export const REMINDER_INTERVAL_MS = 60 * 60 * 1000; +export const LOCALHOST_HOSTNAMES = Object.freeze(['localhost', '127.0.0.1']); + const readValue = (value, key) => { if (!value) return undefined; if (typeof value.get === 'function') return value.get(key); diff --git a/apps/OpenSignServer/utils/clientIp.js b/apps/OpenSignServer/utils/clientIp.js new file mode 100644 index 0000000000..7d98498b16 --- /dev/null +++ b/apps/OpenSignServer/utils/clientIp.js @@ -0,0 +1,48 @@ +/** + * Client IP resolution that only trusts proxy headers when the deployment + * says a proxy is in front of the server (TRUST_PROXY). + */ + +/** + * Parse the TRUST_PROXY setting. + * Accepts a hop count ("1", "2") or the keyword "cloudflare". + * @param {string|undefined} value Raw environment value. + * @returns {{hops: number, cloudflare: boolean}} Trusted proxy settings. + */ +export const parseTrustProxy = value => { + const raw = String(value ?? '').trim().toLowerCase(); + if (raw === 'cloudflare') return { hops: 0, cloudflare: true }; + if (/^\d+$/.test(raw)) return { hops: Number(raw), cloudflare: false }; + return { hops: 0, cloudflare: false }; +}; + +/** + * Read one header as a trimmed string. + * @param {object} headers Request headers. + * @param {string} name Lower-case header name. + * @returns {string} Header value or an empty string. + */ +const readHeader = (headers, name) => { + const value = headers?.[name]; + return typeof value === 'string' ? value.trim() : ''; +}; + +/** + * Resolve the client IP without trusting client-controlled headers. + * @param {object} headers Request headers. + * @param {string|undefined} socketIp Remote address of the TCP socket. + * @param {{hops: number, cloudflare: boolean}} trust Parsed TRUST_PROXY. + * @returns {string} Client IP, or an empty string when unknown. + */ +export const resolveClientIp = (headers, socketIp, trust) => { + const cloudflareIp = readHeader(headers, 'cf-connecting-ip'); + if (trust?.cloudflare && cloudflareIp) return cloudflareIp; + if (trust?.hops > 0) { + const chain = readHeader(headers, 'x-forwarded-for') + .split(',') + .map(ip => ip.trim()) + .filter(Boolean); + if (chain.length > 0) return chain[Math.max(0, chain.length - trust.hops)]; + } + return socketIp || ''; +}; diff --git a/apps/OpenSignServer/utils/dateFormat.js b/apps/OpenSignServer/utils/dateFormat.js new file mode 100644 index 0000000000..367a28eb48 --- /dev/null +++ b/apps/OpenSignServer/utils/dateFormat.js @@ -0,0 +1,52 @@ +import { format, toZonedTime } from 'date-fns-tz'; + +export const formatTimeInTimezone = (date, timezone) => { + const nyDate = timezone && toZonedTime(date, timezone); + const generatedDate = timezone + ? format(nyDate, 'EEE, dd MMM yyyy HH:mm:ss zzz', { timeZone: timezone }) + : new Date(date).toUTCString(); + return generatedDate; +}; + +export const selectFormat = data => { + switch (data) { + case 'L': + return 'MM/dd/yyyy'; + case 'MM/DD/YYYY': + return 'MM/dd/yyyy'; + case 'DD-MM-YYYY': + return 'dd-MM-yyyy'; + case 'DD/MM/YYYY': + return 'dd/MM/yyyy'; + case 'LL': + return 'MMMM dd, yyyy'; + case 'DD MMM, YYYY': + return 'dd MMM, yyyy'; + case 'YYYY-MM-DD': + return 'yyyy-MM-dd'; + case 'MM-DD-YYYY': + return 'MM-dd-yyyy'; + case 'MM.DD.YYYY': + return 'MM.dd.yyyy'; + case 'MMM DD, YYYY': + return 'MMM dd, yyyy'; + case 'MMMM DD, YYYY': + return 'MMMM dd, yyyy'; + case 'DD MMMM, YYYY': + return 'dd MMMM, yyyy'; + case 'DD.MM.YYYY': + return 'dd.MM.yyyy'; + case 'DD-MMM-YYYY': + return 'dd-MMM-yyyy'; + default: + return 'MM/dd/yyyy'; + } +}; + +export function formatDateTime(date, dateFormat, timeZone, is12Hour) { + const zonedDate = toZonedTime(date, timeZone); // Convert date to the given timezone + const timeFormat = is12Hour ? 'hh:mm:ss a' : 'HH:mm:ss'; + return dateFormat + ? format(zonedDate, `${selectFormat(dateFormat)}, ${timeFormat} 'GMT' XXX`, { timeZone }) + : formatTimeInTimezone(date, timeZone); +} diff --git a/apps/OpenSignServer/utils/envConfig.js b/apps/OpenSignServer/utils/envConfig.js new file mode 100644 index 0000000000..47081d22cc --- /dev/null +++ b/apps/OpenSignServer/utils/envConfig.js @@ -0,0 +1,35 @@ +/** + * Database and SMTP settings read from the environment in one place. + */ + +const DEFAULT_SMTP_PORT = 465; + +/** + * Database connection string. + * @param {object} env Environment variables. + * @returns {string} DATABASE_URI, or MONGODB_URI as the legacy name. + * @throws {Error} When neither variable is set. + */ +export const getDatabaseUri = env => { + const uri = String(env.DATABASE_URI || env.MONGODB_URI || '').trim(); + if (!uri) { + throw new Error('DATABASE_URI is not set: provide the MongoDB connection string.'); + } + return uri; +}; + +/** + * SMTP port. + * @param {object} env Environment variables. + * @returns {number} SMTP_PORT, or 465 (implicit TLS) when it is empty. + * @throws {Error} When SMTP_PORT is not a valid TCP port. + */ +export const getSmtpPort = env => { + const raw = String(env.SMTP_PORT ?? '').trim(); + if (!raw) return DEFAULT_SMTP_PORT; + const port = Number(raw); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`Invalid SMTP_PORT "${raw}": expected an integer from 1 to 65535.`); + } + return port; +}; diff --git a/apps/OpenSignServer/utils/fileNames.js b/apps/OpenSignServer/utils/fileNames.js new file mode 100644 index 0000000000..e4975112ba --- /dev/null +++ b/apps/OpenSignServer/utils/fileNames.js @@ -0,0 +1,34 @@ +import crypto from 'node:crypto'; + +export function sanitizeFileName(fileName) { + // Remove spaces and invalid characters + const file = fileName.replace(/[^a-zA-Z0-9._-]/g, ''); + const removedot = file.replace(/\.(?=.*\.)/g, ''); + return removedot.replace(/[^a-zA-Z0-9._-]/g, ''); +} + +// `generateId` is used to unique Id for fileAdapter +export function generateId(length) { + const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + const charactersLength = characters.length; + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + +export const randomId = (digit = 8) => { + // 1. Grab a cryptographically-secure 32-bit random value + // Use crypto for stronger randomness + const randomBytes = crypto.getRandomValues(new Uint32Array(1)); + const raw = randomBytes[0]; // 0 … 4,294,967,295 + + // Calculate the min and max for the given digit length + const min = Math.pow(10, digit - 1); // e.g., digit=3 → 100 + const max = Math.pow(10, digit) - 1; // e.g., digit=3 → 999 + const range = max - min + 1; + + // Collapse random value into the range and shift + return min + (raw % range); +}; diff --git a/apps/OpenSignServer/utils/fileUtils.js b/apps/OpenSignServer/utils/fileUtils.js index 982f319ec5..3d9fffd8b1 100644 --- a/apps/OpenSignServer/utils/fileUtils.js +++ b/apps/OpenSignServer/utils/fileUtils.js @@ -1,5 +1,5 @@ import axios from 'axios'; -import { cloudServerUrl, serverAppId } from '../Utils.js'; +import { cloudServerUrl, serverAppId } from './appConfig.js'; function formatFixedDate(date = new Date()) { const dd = String(date.getDate()).padStart(2, '0'); diff --git a/apps/OpenSignServer/utils/ldapAuth.js b/apps/OpenSignServer/utils/ldapAuth.js new file mode 100644 index 0000000000..2ad62a7060 --- /dev/null +++ b/apps/OpenSignServer/utils/ldapAuth.js @@ -0,0 +1,134 @@ +import { Client } from 'ldapts'; +import { logger } from './logger.js'; +import { getLdapConfig } from './ldapConfig.js'; + +/** + * Escapes characters with special meaning in LDAP search filters (RFC 4515). + * Prevents LDAP injection vulnerabilities. + * @param {string} input + * @returns {string} + */ +export function escapeLdapFilter(input) { + if (typeof input !== 'string') return ''; + return input + .replace(/\\/g, '\\5c') + .replace(/\*/g, '\\2a') + .replace(/\(/g, '\\28') + .replace(/\)/g, '\\29') + .replace(/\x00/g, '\\00'); +} + +/** + * Authenticates user credentials against the configured LDAP server. + * Returns user directory attributes on success, or null on failure. + * + * @param {string} usernameOrEmail + * @param {string} password + * @param {object} [customConfig] + * @returns {Promise<{ authenticated: boolean, dn: string, attributes: object } | null>} + */ +export async function authenticateLdap(usernameOrEmail, password, customConfig = null) { + const config = customConfig || getLdapConfig(process.env); + if (!config.enabled) { + return null; + } + + if (!usernameOrEmail || !password) { + return null; + } + + const clientOptions = { + url: config.url, + timeout: 10000, + connectTimeout: 5000, + }; + + if (config.url.startsWith('ldaps://') || config.startTls) { + clientOptions.tlsOptions = { + rejectUnauthorized: config.rejectUnauthorized, + }; + } + + const client = new Client(clientOptions); + + try { + if (config.startTls) { + await client.startTLS(clientOptions.tlsOptions || {}); + } + + let userDn = null; + let userAttributes = {}; + + // 1. Search for user entry if searchBase is configured + if (config.searchBase) { + if (config.bindDn) { + await client.bind(config.bindDn, config.bindPassword); + } + + const safeInput = escapeLdapFilter(usernameOrEmail); + const filter = config.searchFilter + .replace(/{{username}}/g, safeInput) + .replace(/{{input}}/g, safeInput); + + const searchResult = await client.search(config.searchBase, { + filter, + scope: 'sub', + attributes: [ + config.emailAttr, + config.nameAttr, + config.phoneAttr, + 'mail', + 'displayName', + 'cn', + 'name', + 'givenName', + 'sn', + 'telephoneNumber', + 'mobile', + 'userPrincipalName', + 'uid', + 'sAMAccountName', + ], + }); + + const entries = searchResult?.searchEntries || []; + if (!entries.length) { + logger.warn(`[LDAP] User not found for filter: ${filter}`); + return null; + } + + userDn = entries[0].dn; + userAttributes = entries[0]; + } else if (config.userDnTemplate) { + userDn = config.userDnTemplate.replace(/{{username}}/g, escapeLdapFilter(usernameOrEmail)); + } else if (usernameOrEmail.includes('=')) { + userDn = usernameOrEmail; + } + + if (!userDn) { + logger.warn(`[LDAP] Could not resolve DN for user: ${usernameOrEmail}`); + return null; + } + + // 2. Bind with user DN and password to verify credentials + const userClient = new Client(clientOptions); + try { + if (config.startTls) { + await userClient.startTLS(clientOptions.tlsOptions || {}); + } + await userClient.bind(userDn, password); + return { + authenticated: true, + dn: userDn, + attributes: userAttributes, + }; + } finally { + await userClient.unbind().catch(() => {}); + } + } catch (error) { + logger.error(`[LDAP] Authentication error for ${usernameOrEmail}: ${error.message}`); + return null; + } finally { + await client.unbind().catch(() => {}); + } +} diff --git a/apps/OpenSignServer/utils/ldapConfig.js b/apps/OpenSignServer/utils/ldapConfig.js new file mode 100644 index 0000000000..5ac5b8a3b5 --- /dev/null +++ b/apps/OpenSignServer/utils/ldapConfig.js @@ -0,0 +1,52 @@ +/** + * LDAP configuration loader for OpenSign Server. + * Reads environment variables and returns a structured LDAP configuration object. + */ +export function getLdapConfig(env = process.env) { + const isEnabled = env.LDAP_ENABLED === 'true' || env.LDAP_ENABLED === true; + if (!isEnabled) { + return { enabled: false }; + } + + const port = parseInt(env.LDAP_PORT || '389', 10); + const protocol = env.LDAP_PROTOCOL || (port === 636 ? 'ldaps' : 'ldap'); + const host = env.LDAP_HOST || 'localhost'; + const url = env.LDAP_URL || `${protocol}://${host}:${port}`; + + const bindDn = env.LDAP_BIND_DN || ''; + const bindPassword = env.LDAP_BIND_PASSWORD || ''; + const searchBase = env.LDAP_SEARCH_BASE || ''; + const userDnTemplate = env.LDAP_USER_DN_TEMPLATE || ''; + const searchFilter = + env.LDAP_USER_FILTER || + env.LDAP_SEARCH_FILTER || + '(|(uid={{username}})(mail={{username}})(sAMAccountName={{username}})(userPrincipalName={{username}}))'; + + const emailAttr = env.LDAP_EMAIL_ATTR || env.LDAP_EMAIL_ATTRIBUTE || 'mail'; + const nameAttr = env.LDAP_NAME_ATTR || env.LDAP_NAME_ATTRIBUTE || 'displayName'; + const phoneAttr = env.LDAP_PHONE_ATTR || env.LDAP_PHONE_ATTRIBUTE || 'telephoneNumber'; + + const startTls = env.LDAP_STARTTLS === 'true' || env.LDAP_STARTTLS === true; + const rejectUnauthorized = env.LDAP_TLS_REJECT_UNAUTHORIZED !== 'false'; + const allowFallback = env.LDAP_ALLOW_LOCAL_FALLBACK !== 'false'; + const defaultRole = env.LDAP_DEFAULT_ROLE || 'contracts_User'; + + return { + enabled: true, + url, + host, + port, + bindDn, + bindPassword, + searchBase, + userDnTemplate, + searchFilter, + emailAttr, + nameAttr, + phoneAttr, + startTls, + rejectUnauthorized, + allowFallback, + defaultRole, + }; +} diff --git a/apps/OpenSignServer/utils/logger.js b/apps/OpenSignServer/utils/logger.js new file mode 100644 index 0000000000..8c6a9de2f4 --- /dev/null +++ b/apps/OpenSignServer/utils/logger.js @@ -0,0 +1,58 @@ +// Structured logger: one JSON object per line, with a level and an optional +// request id, so a single signing or mail flow can be followed in the logs. +const SENSITIVE_KEY = /pass(word)?|secret|token|key|authorization|cookie/i; + +const redact = value => { + if (value == null || typeof value !== 'object') return value; + if (Array.isArray(value)) return value.map(redact); + return Object.fromEntries( + Object.entries(value).map(([key, val]) => [ + key, + SENSITIVE_KEY.test(key) && typeof val !== 'object' ? '[redacted]' : redact(val), + ]) + ); +}; + +// Turns an arbitrary value into something that survives JSON.stringify. +const toSafe = value => { + if (value instanceof Error) { + return { name: value.name, message: value.message, code: value.code }; + } + if (value === undefined) return null; + if (typeof value === 'bigint') return value.toString(); + return redact(value); +}; + +const emit = (level, args) => { + const [first, ...rest] = args; + const entry = { + level, + time: new Date().toISOString(), + message: typeof first === 'string' ? first : String(toSafe(first)), + }; + if (typeof first === 'object' && first !== null) { + entry.details = toSafe(first); + } + if (rest.length === 1) { + entry.details = toSafe(rest[0]); + } else if (rest.length > 1) { + entry.details = rest.map(toSafe); + } + let line; + try { + line = JSON.stringify(entry); + } catch { + line = JSON.stringify({ level, time: entry.time, message: String(entry.message) }); + } + if (level === 'error') console.error(line); + else if (level === 'warn') console.warn(line); + else console.log(line); +}; + +export const logger = { + info: (...args) => emit('info', args), + warn: (...args) => emit('warn', args), + error: (...args) => emit('error', args), +}; + +export default logger; diff --git a/apps/OpenSignServer/utils/mailTemplate.js b/apps/OpenSignServer/utils/mailTemplate.js new file mode 100644 index 0000000000..b755cf2eb3 --- /dev/null +++ b/apps/OpenSignServer/utils/mailTemplate.js @@ -0,0 +1,55 @@ +import { + escapeHtml, + renderAutomatedEmailFooter, + renderEmailHeading, + renderEmailLogo, + resolveBrandContext, + resolveDeploymentBrand, +} from './brandContext.js'; +import { normalizeMailSubject } from './mailVars.js'; + +export const mailTemplate = param => { + const deployment = resolveDeploymentBrand(); + const requestedAppName = deployment.productName; + const brand = resolveBrandContext({ + deployment, + tenant: + requestedAppName && requestedAppName !== deployment.productName + ? { WhiteLabelAppName: requestedAppName } + : undefined, + }); + const subject = normalizeMailSubject( + `${param.senderName} has requested you to sign "${param.title}"` + ); + const logo = renderEmailLogo(brand); + const senderName = escapeHtml(param.senderName); + const title = escapeHtml(param.title); + const senderMail = escapeHtml(param.senderMail); + const organization = escapeHtml(param.organization); + const localExpireDate = escapeHtml(param.localExpireDate); + const note = escapeHtml(param.note); + const signingUrl = escapeHtml(param.signingUrl); + + const body = + "<html><head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8' /></head><body><div style='background-color:#f5f5f5;padding:20px'><div style='background:white;padding-bottom:20px'><div style='padding:10px'>" + + logo + + `</div>${renderEmailHeading(brand, 'Digital Signature Request')}<div><p style='padding:20px;font-size:14px;margin-bottom:10px'>` + + senderName + + ' has requested you to review and sign <strong>' + + title + + "</strong>.</p><div style='padding: 5px 0px 5px 25px;display:flex;flex-direction:row;justify-content:space-around'><table><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Sender</td><td></td><td style='color:#626363;font-weight:bold'>" + + senderMail + + "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Organization</td><td></td><td style='color:#626363;font-weight:bold'> " + + organization + + "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Expires on</td><td></td><td style='color:#626363;font-weight:bold'>" + + localExpireDate + + "</td></tr><tr><td style='font-weight:bold;font-family:sans-serif;font-size:15px'>Note</td><td></td><td style='color:#626363;font-weight:bold'>" + + note + + "</td></tr><tr><td></td><td></td></tr></table></div> <div style='margin-left:70px'><a target=_blank href=" + + signingUrl + + "><button style='padding:12px;background-color:#d46b0f;color:white;border:0px;font-weight:bold;margin-top:30px'>Sign here</button></a></div><div style='display:flex;justify-content:center;margin-top:10px'></div></div></div>" + + renderAutomatedEmailFooter(brand, param.senderMail) + + `</div></body></html>`; + + return { subject, body }; +}; diff --git a/apps/OpenSignServer/utils/mailVars.js b/apps/OpenSignServer/utils/mailVars.js new file mode 100644 index 0000000000..5a3728d225 --- /dev/null +++ b/apps/OpenSignServer/utils/mailVars.js @@ -0,0 +1,19 @@ +export const normalizeMailSubject = subject => + String(subject || '').replace(/opensign™/gi, 'opensign'); + +export function replaceMailVaribles(subject, body, variables) { + let replacedSubject = subject; + let replacedBody = body; + + for (const variable in variables) { + const regex = new RegExp(`{{${variable}}}`, 'g'); + if (subject) { + replacedSubject = replacedSubject.replace(regex, variables[variable]); + } + if (body) { + replacedBody = replacedBody.replace(regex, variables[variable]); + } + } + const result = { subject: normalizeMailSubject(replacedSubject), body: replacedBody }; + return result; +} diff --git a/apps/OpenSignServer/utils/pdfDraw.js b/apps/OpenSignServer/utils/pdfDraw.js new file mode 100644 index 0000000000..e1d7c6ea14 --- /dev/null +++ b/apps/OpenSignServer/utils/pdfDraw.js @@ -0,0 +1,224 @@ +import { PDFArray, PDFName, rgb } from 'pdf-lib'; + +/* ---- flattenPdf private helpers (kept with the pdf helpers) ---- */ + +function _safeGetWidgetsServer(field) { + try { + return field.acroField?.getWidgets?.() || []; + } catch { + return []; + } +} + +function _getWidgetRectServer(widget, pdfDoc) { + try { + const r = widget.getRectangle?.(); + if (r && isFinite(r.x) && isFinite(r.y) && isFinite(r.width) && isFinite(r.height)) { + return r; + } + } catch { + /* fall through to manual extraction */ + } + + try { + const rectArr = widget.dict?.lookup?.(PDFName.of('Rect')); + if (!rectArr || typeof rectArr.size !== 'function' || rectArr.size() !== 4) return null; + + const x1 = _numberFromPdfObjectServer(rectArr.get(0)); + const y1 = _numberFromPdfObjectServer(rectArr.get(1)); + const x2 = _numberFromPdfObjectServer(rectArr.get(2)); + const y2 = _numberFromPdfObjectServer(rectArr.get(3)); + + if ([x1, y1, x2, y2].some(v => !isFinite(v))) return null; + return { + x: Math.min(x1, x2), + y: Math.min(y1, y2), + width: Math.abs(x2 - x1), + height: Math.abs(y2 - y1), + }; + } catch { + return null; + } +} + +function _numberFromPdfObjectServer(obj) { + if (!obj) return NaN; + if (typeof obj.asNumber === 'function') return obj.asNumber(); + if (typeof obj.numberValue === 'function') return obj.numberValue(); + return Number(obj?.value ?? obj); +} + +function _getWidgetPageServer(pdfDoc, pages, widget) { + try { + const pRef = widget.P?.(); + if (pRef) { + for (const page of pages) { + if (page.ref === pRef) return page; + } + } + } catch { + /* fall through */ + } + + try { + const pRef = widget.dict?.get?.(PDFName.of('P')); + if (pRef) { + for (const page of pages) { + if (page.ref === pRef) return page; + } + } + } catch { + /* fall through */ + } + + // Fallback: search page annots + try { + for (const page of pages) { + const annots = page.node.lookupMaybe(PDFName.of('Annots'), PDFArray); + if (!annots) continue; + + for (let i = 0; i < annots.size(); i++) { + const ref = annots.get(i); + if (ref === widget.ref) return page; + } + } + } catch { + /* fall through */ + } + + return null; +} + +function _drawWidgetBoxServer(page, rect) { + try { + page.drawRectangle({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + borderWidth: 0.6, + borderColor: rgb(0.65, 0.65, 0.65), + }); + } catch { + /* best effort */ + } +} + +function _drawTextFieldServer(page, field, rect, font) { + let text = ''; + try { + text = field.getText?.() ?? ''; + } catch { + text = ''; + } + text = String(text ?? ''); + + if (!text) return; + + let multiline = false; + try { + multiline = field.isMultiline?.() ?? false; + } catch { + /* ignore */ + } + + let comb = false; + try { + comb = field.isCombed?.() ?? false; + } catch { + /* ignore */ + } + + if (comb) { + _drawCombTextServer(page, text, rect, font); + return; + } + + if (multiline || text.includes('\n')) { + _drawMultilineTextServer(page, text, rect, font); + return; + } + + const fontSize = _fitSingleLineFontSizeServer(text, rect, font); + const baselineY = rect.y + Math.max(2, (rect.height - fontSize) / 2); + + page.drawText(text, { + x: rect.x + 2, + y: baselineY, + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 4), + }); +} + +function _drawMultilineTextServer(page, text, rect, font) { + const lines = String(text).replace(/\r/g, '').split('\n'); + const fontSize = Math.max(8, Math.min(11, rect.height / Math.max(lines.length + 0.5, 2))); + const lineHeight = fontSize + 1.5; + + let y = rect.y + rect.height - fontSize - 2; + + for (const line of lines) { + if (y < rect.y + 1) break; + + page.drawText(line, { + x: rect.x + 2, + y, + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 4), + lineHeight, + }); + + y -= lineHeight; + } +} + +function _drawCombTextServer(page, text, rect, font) { + const chars = String(text).split(''); + const count = Math.max(chars.length, 1); + const cellWidth = rect.width / count; + const fontSize = Math.max(8, Math.min(12, rect.height - 4)); + + chars.forEach((ch, i) => { + const textWidth = font.widthOfTextAtSize(ch, fontSize); + const x = rect.x + i * cellWidth + (cellWidth - textWidth) / 2; + const y = rect.y + Math.max(2, (rect.height - fontSize) / 2); + + page.drawText(ch, { + x, + y, + size: fontSize, + font, + color: rgb(0, 0, 0), + }); + + if (i < count - 1) { + try { + page.drawLine({ + start: { x: rect.x + (i + 1) * cellWidth, y: rect.y }, + end: { x: rect.x + (i + 1) * cellWidth, y: rect.y + rect.height }, + thickness: 0.4, + color: rgb(0.75, 0.75, 0.75), + }); + } catch { + /* best effort */ + } + } + }); +} + +export function _fitSingleLineFontSizeServer(text, rect, font) { + let size = Math.min(12, rect.height - 4); + size = Math.max(size, 6); + + while (size > 6) { + const width = font.widthOfTextAtSize(text, size); + if (width <= rect.width - 4) return size; + size -= 0.5; + } + + return 6; +} diff --git a/apps/OpenSignServer/utils/pdfDrawFields.js b/apps/OpenSignServer/utils/pdfDrawFields.js new file mode 100644 index 0000000000..03829c8562 --- /dev/null +++ b/apps/OpenSignServer/utils/pdfDrawFields.js @@ -0,0 +1,157 @@ +import { PDFDict, PDFName, rgb } from 'pdf-lib'; +import { _fitSingleLineFontSizeServer } from './pdfDraw.js'; + +function _drawCheckBoxServer(page, field, rect, zapf) { + let checked = false; + try { + checked = field.isChecked(); + } catch { + checked = false; + } + + if (!checked) return; + + const size = Math.max(8, Math.min(rect.width, rect.height) - 4); + + page.drawText('✔', { + x: rect.x + Math.max(1, (rect.width - size * 0.7) / 2), + y: rect.y + Math.max(1, (rect.height - size) / 2), + size, + font: zapf, + color: rgb(0, 0, 0), + }); +} + +function _drawRadioGroupServer(page, field, widget, rect) { + let selected = null; + try { + selected = field.getSelected(); + } catch { + selected = null; + } + + if (!selected) return; + + let widgetOnValue = null; + try { + widgetOnValue = widget.getOnValue?.(); + } catch { + /* ignore */ + } + + if (!widgetOnValue) { + try { + const ap = widget.dict?.lookupMaybe?.(PDFName.of('AP'), PDFDict); + const n = ap?.lookupMaybe?.(PDFName.of('N'), PDFDict); + if (n) { + const keys = n.keys(); + for (const k of keys) { + const name = k?.decodeText?.() ?? k?.encodedName ?? String(k); + if (name !== '/Off' && name !== 'Off') { + widgetOnValue = name.replace(/^\//, ''); + break; + } + } + } + } catch { + /* ignore */ + } + } + + const selectedStr = String(selected).replace(/^\//, ''); + const onStr = String(widgetOnValue ?? '').replace(/^\//, ''); + + if (!onStr || selectedStr !== onStr) return; + + // Circle outline + try { + page.drawEllipse({ + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + xScale: rect.width / 2 - 1, + yScale: rect.height / 2 - 1, + borderWidth: 0.8, + borderColor: rgb(0, 0, 0), + }); + } catch { + /* best effort */ + } + + // Inner filled dot + try { + const r = Math.min(rect.width, rect.height) / 4; + page.drawEllipse({ + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + xScale: r, + yScale: r, + color: rgb(0, 0, 0), + }); + } catch { + /* best effort */ + } +} + +function _drawDropdownServer(page, field, rect, font) { + let text = ''; + try { + const selected = field.getSelected?.(); + if (Array.isArray(selected)) { + text = selected.join(', '); + } else { + text = selected ?? ''; + } + } catch { + text = ''; + } + + text = String(text ?? ''); + if (!text) return; + + const fontSize = _fitSingleLineFontSizeServer(text, rect, font); + + page.drawText(text, { + x: rect.x + 2, + y: rect.y + Math.max(2, (rect.height - fontSize) / 2), + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 12), + }); +} + +function _drawOptionListServer(page, field, rect, font) { + let selected = []; + try { + selected = field.getSelected?.() || []; + } catch { + selected = []; + } + + if (!Array.isArray(selected)) { + selected = [selected].filter(Boolean); + } + + if (!selected.length) return; + + const lines = selected.map(v => String(v)); + const fontSize = Math.max(8, Math.min(11, rect.height / Math.max(lines.length + 0.5, 2))); + const lineHeight = fontSize + 1.5; + + let y = rect.y + rect.height - fontSize - 2; + + for (const line of lines) { + if (y < rect.y + 1) break; + + page.drawText(line, { + x: rect.x + 2, + y, + size: fontSize, + font, + color: rgb(0, 0, 0), + maxWidth: Math.max(1, rect.width - 4), + }); + + y -= lineHeight; + } +} diff --git a/apps/OpenSignServer/utils/pdfFlatten.js b/apps/OpenSignServer/utils/pdfFlatten.js new file mode 100644 index 0000000000..08b87f3b0f --- /dev/null +++ b/apps/OpenSignServer/utils/pdfFlatten.js @@ -0,0 +1,197 @@ +import { PDFDict, PDFDocument, PDFName } from 'pdf-lib'; + +/** + * FlattenPdf renders field values as static content and removes the interactive + * form layer. Signatures are stripped entirely. Non-widget annotations (links, + * comments, stamps) are preserved. + * @param {string | Uint8Array | ArrayBuffer} pdfFile - pdf file. + * @returns {Promise<Uint8Array>} flatPdf - pdf file in Uint8Array + */ +// Keeps the binary contract of flattenPdf: callers upload the result as a PDF, +// so a base64 string has to be decoded instead of being returned as text. +const toPdfBytes = input => { + if (typeof input === 'string') return Buffer.from(input, 'base64'); + if (input instanceof ArrayBuffer) return new Uint8Array(input); + return input; +}; + +// Walks the complete field tree: a signature can sit under nested /Kids. +const hasSignatureField = (context, node, visited = new Set()) => { + if (!node) return false; + if (visited.has(node)) return false; + visited.add(node); + const ft = node.get?.(PDFName.of('FT')); + if (ft && ft.toString() === '/Sig') return true; + const kidsRef = node.get?.(PDFName.of('Kids')); + const kids = kidsRef ? context.lookup(kidsRef) : null; + if (kids && typeof kids.asArray === 'function') { + for (const kidRef of kids.asArray()) { + const kid = context.lookup(kidRef); + if (hasSignatureField(context, kid, visited)) return true; + } + } + return false; +}; + +export const flattenPdf = async pdfFile => { + const inputBytes = toPdfBytes(pdfFile); + const pdfDoc = await PDFDocument.load(inputBytes, { ignoreEncryption: true }); + + // Preserve existing digital signatures: if the document contains a + // signature field (SigFlags or /FT /Sig), skip flattening to avoid + // invalidating the signature or dropping signature widgets. + try { + const acroFormEntry = pdfDoc.catalog.get(PDFName.of('AcroForm')); + const acroForm = pdfDoc.context.lookupMaybe + ? pdfDoc.context.lookupMaybe(acroFormEntry, PDFDict) + : pdfDoc.context.lookup(acroFormEntry); + if (acroForm) { + const sigFlags = acroForm.get(PDFName.of('SigFlags')); + if (sigFlags && Number(sigFlags) > 0) { + return inputBytes; + } + const fieldsRef = acroForm.get(PDFName.of('Fields')); + const fields = fieldsRef ? pdfDoc.context.lookup(fieldsRef) : null; + if (fields && typeof fields.asArray === 'function') { + for (const fRef of fields.asArray()) { + const field = pdfDoc.context.lookup(fRef); + if (hasSignatureField(pdfDoc.context, field)) { + return inputBytes; + } + } + } + } + } catch { + // If AcroForm inspection fails, continue with normal flatten. + } + + // Preserve existing digital signatures: if the document contains a + // signature field (SigFlags or /FT /Sig), skip flattening to avoid + // invalidating the signature or dropping signature widgets. + try { + const acroFormEntry = pdfDoc.catalog.get(PDFName.of('AcroForm')); + const acroForm = pdfDoc.context.lookupMaybe + ? pdfDoc.context.lookupMaybe(acroFormEntry) + : pdfDoc.context.lookup(acroFormEntry); + if (acroForm) { + const sigFlags = acroForm.get(PDFName.of('SigFlags')); + if (sigFlags && Number(sigFlags) > 0) { + return pdfFile; + } + const fieldsRef = acroForm.get(PDFName.of('Fields')); + const fields = fieldsRef ? pdfDoc.context.lookup(fieldsRef) : null; + if (fields && fields.asArray) { + for (const fRef of fields.asArray()) { + const f = pdfDoc.context.lookup(fRef); + const ft = f?.get(PDFName.of('FT')); + if (ft && ft.toString() === '/Sig') { + return pdfFile; + } + const kidsRef = f?.get(PDFName.of('Kids')); + const kids = kidsRef ? pdfDoc.context.lookup(kidsRef) : null; + if (kids && kids.asArray) { + for (const kRef of kids.asArray()) { + const k = pdfDoc.context.lookup(kRef); + const kft = k?.get(PDFName.of('FT')); + if (kft && kft.toString() === '/Sig') { + return pdfFile; + } + } + } + } + } + } + } catch { + // If AcroForm inspection fails, continue with normal flatten. + } + + try { + const acroFormEntry = pdfDoc.catalog.get(PDFName.of('AcroForm')); + const acroForm = pdfDoc.context.lookupMaybe + ? pdfDoc.context.lookupMaybe(acroFormEntry) + : pdfDoc.context.lookup(acroFormEntry); + + if (acroForm && typeof acroForm.set === 'function') { + // Avoid pdf-lib form APIs here; some malformed PDFs crash while + // iterating/removing fields. Clearing /Fields directly is safer. + acroForm.set(PDFName.of('Fields'), pdfDoc.context.obj([])); + acroForm.delete(PDFName.of('XFA')); + acroForm.delete(PDFName.of('SigFlags')); + } + } catch { + // If AcroForm is malformed, continue with page annotation cleanup. + } + + for (const page of pdfDoc.getPages()) { + try { + const annotationsRef = page.node.get(PDFName.of('Annots')); + if (!annotationsRef) continue; + + const annotations = pdfDoc.context.lookup(annotationsRef); + if (!annotations || !annotations.asArray) continue; + + const filtered = annotations.asArray().filter(annotRef => { + try { + const annot = pdfDoc.context.lookup(annotRef); + const subtype = annot?.get(PDFName.of('Subtype')); + return subtype?.toString() !== '/Widget'; + } catch { + return true; + } + }); + + if (filtered.length === 0) { + page.node.delete(PDFName.of('Annots')); + } else { + page.node.set(PDFName.of('Annots'), pdfDoc.context.obj(filtered)); + } + } catch { + // best effort cleanup + } + } + + try { + pdfDoc.catalog.delete(PDFName.of('AcroForm')); + } catch { + // best effort cleanup + } + + return await pdfDoc.save({ useObjectStreams: false }); +}; + +/** Remove only Widget annotations; preserve links, stamps, comments, etc. */ +function _removeWidgetAnnotationsServer(pdfDoc) { + for (const page of pdfDoc.getPages()) { + try { + const annotationsRef = page.node.get(PDFName.of('Annots')); + if (!annotationsRef) continue; + + const annotations = pdfDoc.context.lookup(annotationsRef); + if (!annotations || !annotations.asArray) continue; + + const filtered = annotations.asArray().filter(annotRef => { + try { + const annot = pdfDoc.context.lookup(annotRef); + const subtype = annot?.get(PDFName.of('Subtype')); + return subtype?.toString() !== '/Widget'; + } catch { + return true; + } + }); + + if (filtered.length === 0) { + page.node.delete(PDFName.of('Annots')); + } else { + page.node.set(PDFName.of('Annots'), pdfDoc.context.obj(filtered)); + } + } catch { + /* best effort */ + } + } + + try { + pdfDoc.catalog.delete(PDFName.of('AcroForm')); + } catch { + /* best effort */ + } +} diff --git a/apps/OpenSignServer/utils/placeholders.js b/apps/OpenSignServer/utils/placeholders.js new file mode 100644 index 0000000000..6489ffaf04 --- /dev/null +++ b/apps/OpenSignServer/utils/placeholders.js @@ -0,0 +1,66 @@ +import getPresignedUrl from '../cloud/parsefunction/getSignedUrl.js'; + +export const handleValidImage = async Placeholder => { + const updatedPlaceholders = []; + + for (const placeholder of Placeholder || []) { + //Clean and format signerPtr + let signerPtr = placeholder.signerPtr; + // Check if signerPtr exists and has an id + if (signerPtr?.id) { + // Case 1: If signerPtr is a Parse Object instance + if (signerPtr instanceof Parse.Object) { + // If signerPtr has no attributes, it’s a plain pointer already + if (!signerPtr.attributes || Object.keys(signerPtr.attributes).length === 0) { + // Convert to a clean pointer using Parse’s built-in method + signerPtr = signerPtr.toPointer(); + } else { + // If it has attributes, manually construct the pointer object + signerPtr = { + __type: 'Pointer', + className: signerPtr.className, + objectId: signerPtr.id, + }; + } + // Case 2: If signerPtr is already a plain JS object resembling a pointer + } else if (typeof signerPtr === 'object' && signerPtr.className && signerPtr.objectId) { + // Normalize it to a valid Parse pointer object + signerPtr = { + __type: 'Pointer', + className: signerPtr.className, + objectId: signerPtr.objectId, + }; + } + } + + //Process placeHolder if Role is 'prefill' + if (placeholder?.Role === 'prefill') { + const updatedRole = []; + for (const item of placeholder.placeHolder || []) { + const updatedPos = []; + for (const posItem of item.pos || []) { + if ( + (posItem?.type === 'image' || posItem?.type === 'draw') && + posItem?.options?.response + ) { + const validUrl = await getPresignedUrl(posItem?.options?.response); + updatedPos.push({ + ...posItem, + ...(item.SignUrl !== undefined && { SignUrl: validUrl }), + options: { ...posItem.options, response: validUrl }, + }); + } else { + updatedPos.push(posItem); + } + } + updatedRole.push({ ...item, pos: updatedPos }); + } + + updatedPlaceholders.push({ ...placeholder, signerPtr, placeHolder: updatedRole }); + } else { + // Not prefill role, just push as-is + updatedPlaceholders.push({ ...placeholder, signerPtr }); + } + } + return updatedPlaceholders; +}; diff --git a/apps/OpenSignServer/utils/publicUrl.js b/apps/OpenSignServer/utils/publicUrl.js new file mode 100644 index 0000000000..b1183d0585 --- /dev/null +++ b/apps/OpenSignServer/utils/publicUrl.js @@ -0,0 +1,40 @@ +/** + * Public URL used to build links in emails. The request Host and Origin + * headers are client-controlled, so they are accepted only when they match + * the configured URL or an explicit allowlist. + */ + +/** + * Normalize an origin: trim spaces and drop trailing slashes. + * @param {string|undefined} value Raw origin. + * @returns {string} Normalized origin or an empty string. + */ +const normalizeOrigin = value => String(value ?? '').trim().replace(/\/+$/, ''); + +/** + * Parse a comma-separated list of origins. + * @param {string|undefined} value Raw environment value. + * @returns {string[]} Normalized origins without empty entries. + */ +export const parseOriginList = value => + String(value ?? '') + .split(',') + .map(normalizeOrigin) + .filter(Boolean); + +/** + * Resolve the public URL for links in emails. + * @param {{host?: string, origin?: string}} request Host and Origin headers. + * @param {{baseUrl: string, allowlist: string[]}} config Configured public + * URL and extra allowed origins (custom domains). + * @returns {string} Public origin without a trailing slash. + */ +export const resolvePublicUrl = (request, config) => { + const baseUrl = normalizeOrigin(config?.baseUrl); + const candidate = + normalizeOrigin(request?.origin) || + (request?.host ? `https://${normalizeOrigin(request.host)}` : ''); + if (!baseUrl) return candidate; + const allowed = [baseUrl, ...(config?.allowlist || [])]; + return allowed.includes(candidate) ? candidate : baseUrl; +}; diff --git a/apps/OpenSignServer/utils/roles.js b/apps/OpenSignServer/utils/roles.js new file mode 100644 index 0000000000..fe36acb1d9 --- /dev/null +++ b/apps/OpenSignServer/utils/roles.js @@ -0,0 +1,8 @@ +// Single source of truth for the role values the server accepts. +// The legacy `contracts_*` names are still present in existing databases. +export const ADMIN_ROLES = ['contracts_Admin', 'Admin']; +export const ORG_ADMIN_ROLES = ['contracts_OrgAdmin', 'OrgAdmin']; +export const ALL_ADMIN_ROLES = [...ADMIN_ROLES, ...ORG_ADMIN_ROLES]; + +export const isAdminRole = role => ALL_ADMIN_ROLES.includes(role); +export const isOrgAdminRole = role => ORG_ADMIN_ROLES.includes(role); diff --git a/apps/OpenSignServer/utils/secureUrl.js b/apps/OpenSignServer/utils/secureUrl.js new file mode 100644 index 0000000000..45d647a41e --- /dev/null +++ b/apps/OpenSignServer/utils/secureUrl.js @@ -0,0 +1,21 @@ +import { getSignedLocalUrl } from '../cloud/parsefunction/getSignedUrl.js'; + +// `getSecureUrl` is used to return local secure url if local files +export const getSecureUrl = url => { + const fileUrl = new URL(url)?.pathname?.includes('/files/'); + if (fileUrl) { + try { + const file = getSignedLocalUrl(url); + if (file) { + return { url: file }; + } else { + return { url: '' }; + } + } catch (err) { + console.log('err while fileupload ', err); + return { url: '' }; + } + } else { + return { url: url }; + } +}; diff --git a/apps/OpenSignServer/utils/serverConfig.js b/apps/OpenSignServer/utils/serverConfig.js new file mode 100644 index 0000000000..bdd46db051 --- /dev/null +++ b/apps/OpenSignServer/utils/serverConfig.js @@ -0,0 +1,52 @@ +/** + * Server network settings read from the environment in one place. + * The defaults below are the values the server has always used. + */ + +const DEFAULT_PORT = 8080; +const DEFAULT_BIND_HOST = '0.0.0.0'; +const DEFAULT_MOUNT_PATH = '/app'; +const LOOPBACK_HOST = 'localhost'; + +/** + * Parse and validate the listening port. + * @param {string|undefined} value Raw PORT value. + * @returns {number} Port number. + * @throws {Error} When the value is not a valid TCP port. + */ +const parsePort = value => { + if (value === undefined || value === '') return DEFAULT_PORT; + const port = Number(value); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`Invalid PORT "${value}": expected an integer from 1 to 65535.`); + } + return port; +}; + +/** + * Build the server network settings. + * @param {object} env Environment variables. + * @returns {{port: number, bindHost: string, serverOrigin: string, cloudServerUrl: string}} + * Port, interface to bind, internal origin and internal Parse URL. + * @throws {Error} When PORT is invalid. + */ +export const getServerConfig = env => { + const port = parsePort(env.PORT); + const bindHost = env.BIND_HOST || DEFAULT_BIND_HOST; + const serverOrigin = `http://${LOOPBACK_HOST}:${port}`; + const mountPath = env.PARSE_MOUNT || DEFAULT_MOUNT_PATH; + return { port, bindHost, serverOrigin, cloudServerUrl: `${serverOrigin}${mountPath}` }; +}; + +/** + * Map a URL under the public API prefix to the internal server origin. + * @param {string} url Original URL. + * @param {string|undefined} publicApiUrl Public API prefix (PUBLIC_API_URL). + * @param {string} serverOrigin Internal server origin. + * @returns {string} Rewritten URL, or the original when it does not apply. + */ +export const rewritePublicApiUrl = (url, publicApiUrl, serverOrigin) => { + const prefix = String(publicApiUrl ?? '').replace(/\/+$/, ''); + if (!prefix || !url.startsWith(`${prefix}/`)) return url; + return `${serverOrigin}${url.slice(prefix.length)}`; +}; diff --git a/apps/OpenSignServer/utils/storageCounts.js b/apps/OpenSignServer/utils/storageCounts.js new file mode 100644 index 0000000000..89b4eaa8ab --- /dev/null +++ b/apps/OpenSignServer/utils/storageCounts.js @@ -0,0 +1,68 @@ +export const saveFileUsage = async (size, fileUrl, userId) => { + //checking server url and save file's size + try { + if (userId) { + const userPtr = { __type: 'Pointer', className: '_User', objectId: userId }; + const tenantQuery = new Parse.Query('partners_Tenant'); + tenantQuery.equalTo('UserId', userPtr); + const tenant = await tenantQuery.first({ useMasterKey: true }); + if (tenant) { + const tenantPtr = { __type: 'Pointer', className: 'partners_Tenant', objectId: tenant.id }; + try { + const tenantCredits = new Parse.Query('partners_TenantCredits'); + tenantCredits.equalTo('PartnersTenant', tenantPtr); + const res = await tenantCredits.first({ useMasterKey: true }); + if (res) { + const response = JSON.parse(JSON.stringify(res)); + const usedStorage = response?.usedStorage ? response.usedStorage + size : size; + const updateCredit = new Parse.Object('partners_TenantCredits'); + updateCredit.id = res.id; + updateCredit.set('usedStorage', usedStorage); + await updateCredit.save(null, { useMasterKey: true }); + } else { + const newCredit = new Parse.Object('partners_TenantCredits'); + newCredit.set('usedStorage', size); + newCredit.set('PartnersTenant', tenantPtr); + await newCredit.save(null, { useMasterKey: true }); + } + } catch (err) { + console.log('err in save usage', err); + } + saveDataFile(size, fileUrl, tenantPtr, userId); + } + } + } catch (err) { + console.log('err in fetch tenant Id', err); + } +}; + +//function for save fileUrl and file size in particular client db class partners_DataFiles +const saveDataFile = async (size, fileUrl, tenantPtr, UserId) => { + try { + const newDataFiles = new Parse.Object('partners_DataFiles'); + newDataFiles.set('FileUrl', fileUrl); + newDataFiles.set('FileSize', size); + newDataFiles.set('TenantPtr', tenantPtr); + newDataFiles.set('UserId', UserId); + await newDataFiles.save(null, { useMasterKey: true }); + } catch (err) { + console.log('error in save usage ', err); + } +}; + +export const updateMailCount = async extUserId => { + // Update count in contracts_Users class + const query = new Parse.Query('contracts_Users'); + query.equalTo('objectId', extUserId); + + try { + const contractUser = await query.first({ useMasterKey: true }); + if (contractUser) { + const _extRes = JSON.parse(JSON.stringify(contractUser)); + contractUser.increment('EmailCount', 1); + await contractUser.save(null, { useMasterKey: true }); + } + } catch (error) { + console.log('Error updating EmailCount in contracts_Users: ' + error.message); + } +}; diff --git a/apps/OpenSignServer/utils/textFormat.js b/apps/OpenSignServer/utils/textFormat.js new file mode 100644 index 0000000000..a09ba8a135 --- /dev/null +++ b/apps/OpenSignServer/utils/textFormat.js @@ -0,0 +1,16 @@ +// Format date and time for the selected timezone +export const stripHtml = html => { + if (!html) return ''; + return String(html) + .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '') + .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '') + .replace(/<br\s*\/?>/gi, '\n') + .replace(/<\/p>/gi, '\n') + .replace(/<[^>]+>/g, '') + .replace(/ /g, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/\n{3,}/g, '\n\n') + .trim(); +}; diff --git a/docker-compose.fork.yml b/docker-compose.fork.yml new file mode 100644 index 0000000000..6b7d2caa04 --- /dev/null +++ b/docker-compose.fork.yml @@ -0,0 +1,65 @@ +services: + server: + image: ghcr.io/snxrcs/opensignserver:latest + container_name: OpenSignServer-container + restart: unless-stopped + volumes: + - opensign-files:/usr/src/app/files + ports: + - "8080:8080" + depends_on: + - mongo + env_file: .env.prod + environment: + - NODE_ENV=production + - SERVER_URL=${HOST_URL:-https://localhost:3001}/api/app + - PUBLIC_URL=${HOST_URL:-https://localhost:3001} + networks: + - app-network + mongo: + image: mongo:latest + container_name: mongo-container + restart: unless-stopped + volumes: + - data-volume:/data/db + ports: + - "27018:27017" + networks: + - app-network + client: + image: ghcr.io/snxrcs/opensign:latest + container_name: OpenSign-container + restart: unless-stopped + depends_on: + - server + env_file: .env.prod + ports: + - "3000:3000" + networks: + - app-network + caddy: + image: caddy:latest + container_name: caddy-container + ports: + - "3001:3001" + - "80:80" + - "443:443" + - "443:443/udp" + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile + - caddy_data:/data + - caddy_config:/config + networks: + - app-network + environment: + - HOST_URL=${HOST_URL:-localhost:3001} +networks: + app-network: + driver: bridge + +volumes: + data-volume: + web-root: + caddy_data: + caddy_config: + opensign-files: diff --git a/docker-compose.yml b/docker-compose.yml index 577c1ed74e..18416806c7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,6 @@ services: server: - image: opensign/opensignserver:main + image: ghcr.io/snxrcs/opensignserver:latest container_name: OpenSignServer-container volumes: - opensign-files:/usr/src/app/files @@ -25,7 +25,7 @@ services: networks: - app-network client: - image: opensign/opensign:main + image: ghcr.io/snxrcs/opensign:latest container_name: OpenSign-container depends_on: - server