Compare commits
65 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
97e86308ce | ||
b7f725bcfd | |||
649f930a1b | |||
1a397a8a5d | |||
eeec82437a | |||
21d2d7b94d | |||
c8f6d625f8 | |||
09a2c85119 | |||
ed4b797230 | |||
f48240bea3 | |||
d1af444ed1 | |||
02091bf433 | |||
4d11a9b7ef | |||
6edde3781b | |||
dc54ec1a9b | |||
863533be33 | |||
4b7a08534d | |||
c5bf332242 | |||
![]() |
1c3afac679 | ||
![]() |
63fc45927f | ||
![]() |
5b3f432c3a | ||
![]() |
758a32a4d6 | ||
![]() |
6f6d3e8de5 | ||
![]() |
c87ad8fed5 | ||
![]() |
56fe4fbcd3 | ||
![]() |
d94fd9e017 | ||
![]() |
4f76d43f38 | ||
![]() |
7bfe3bcad2 | ||
![]() |
c178b60d51 | ||
![]() |
a450d80600 | ||
![]() |
095c4efba2 | ||
![]() |
723322cc0a | ||
![]() |
d17f4aa8d9 | ||
![]() |
7a137dbe2f | ||
![]() |
a351c1814c | ||
![]() |
4e8dbcbf17 | ||
![]() |
2e54e77aee | ||
96ed1e50fa | |||
e4c440d6df | |||
d3e13bd801 | |||
ca5a59c51a | |||
![]() |
76650e3068 | ||
![]() |
5667f07b51 | ||
![]() |
19f517a946 | ||
![]() |
01d56c864a | ||
![]() |
e8d7c5777f | ||
c939065562 | |||
![]() |
fd4a9d32b7 | ||
![]() |
eb4e47a73e | ||
![]() |
5620084a35 | ||
![]() |
5b3fcc1eaf | ||
![]() |
cc4da39f74 | ||
![]() |
e98b9ff6d7 | ||
![]() |
393bdae782 | ||
![]() |
82ee58dd25 | ||
![]() |
7fa33cbdbc | ||
![]() |
bd5d50cf97 | ||
6ed6682824 | |||
39c14ff490 | |||
f9abdd31cd | |||
d7e27bbb9a | |||
ccc0a1620c | |||
5ad6465b74 | |||
7435a33fe0 | |||
65f67993ba |
43
.github/workflows/cicd.yml
vendored
Normal file
43
.github/workflows/cicd.yml
vendored
Normal file
@ -0,0 +1,43 @@
|
||||
name: Build and Push to Registry
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ cicd ]
|
||||
|
||||
env:
|
||||
REGISTRY: git.4nkweb.com
|
||||
IMAGE_NAME: 4nk/lecoffre-front
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up SSH agent
|
||||
uses: webfactory/ssh-agent@v0.9.1
|
||||
with:
|
||||
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ secrets.USER }}
|
||||
password: ${{ secrets.TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
ssh: default
|
||||
build-args: |
|
||||
ENV_VARS=${{ secrets.ENV_VARS }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ gitea.sha }}
|
78
.github/workflows/ppd.yml
vendored
78
.github/workflows/ppd.yml
vendored
@ -1,78 +0,0 @@
|
||||
name: Preprod - Build & Deploy to Scaleway
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [preprod]
|
||||
|
||||
env:
|
||||
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
|
||||
NAMESPACE_ID_LECOFFRE: e975f056-967e-43fe-b237-84bfa8032e64
|
||||
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffreppdmp73pool
|
||||
|
||||
IMAGE_NAME: front
|
||||
CONTAINER_NAME: front
|
||||
|
||||
jobs:
|
||||
build-and-push-image-lecoffre:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
- name: Copy SSH
|
||||
run: cp ~/.ssh/id_rsa id_rsa
|
||||
- name: Login to Scaleway Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: nologin
|
||||
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
|
||||
- name: Get Git Commit SHA
|
||||
id: vars
|
||||
run: echo "COMMIT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
- name: Build the Docker Image
|
||||
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
|
||||
- name: Push the Docker Image to Scaleway Container Registry
|
||||
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
|
||||
deploy-to-scaleway-lecoffre:
|
||||
needs: build-and-push-image-lecoffre
|
||||
runs-on: ubuntu-latest
|
||||
environment: preprod
|
||||
steps:
|
||||
- name: Install CLI
|
||||
uses: scaleway/action-scw@v0
|
||||
- name: Get container ID
|
||||
run: |
|
||||
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
|
||||
env:
|
||||
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
|
||||
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
|
||||
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
|
||||
- name: Deploy the container based on the new image
|
||||
run: |
|
||||
env_string=""
|
||||
while IFS= read -r line; do
|
||||
if [[ "$line" == *"="* ]]; then
|
||||
key=$(echo "$line" | cut -d '=' -f 1)
|
||||
value=$(echo "$line" | cut -d '=' -f 2-)
|
||||
if [[ -n "$key" ]]; then
|
||||
env_string+="environment-variables.$key=$value "
|
||||
fi
|
||||
fi
|
||||
done <<< "$ENV_VARS"
|
||||
env_string=$(echo $env_string | sed 's/ $//')
|
||||
scw container container update ${{ env.CONTAINER_ID }} $env_string
|
||||
env:
|
||||
ENV_VARS: ${{ secrets.ENV }}
|
||||
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
|
||||
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
|
||||
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
|
||||
|
79
.github/workflows/prd.yml
vendored
79
.github/workflows/prd.yml
vendored
@ -1,79 +0,0 @@
|
||||
name: Prod - Build & Deploy to Scaleway
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
|
||||
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
|
||||
NAMESPACE_ID_LECOFFRE: 8fbbce9d-31d1-4368-94c4-445e79f10834
|
||||
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffreprdjulp9mam
|
||||
|
||||
IMAGE_NAME: front
|
||||
CONTAINER_NAME: front
|
||||
|
||||
jobs:
|
||||
build-and-push-image-lecoffre:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
- name: Copy SSH
|
||||
run: cp ~/.ssh/id_rsa id_rsa
|
||||
- name: Login to Scaleway Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: nologin
|
||||
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
|
||||
- name: Get Git Commit SHA
|
||||
id: vars
|
||||
run: echo "COMMIT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||
- name: Build the Docker Image
|
||||
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
|
||||
- name: Push the Docker Image to Scaleway Container Registry
|
||||
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
|
||||
deploy-to-scaleway-lecoffre:
|
||||
needs: build-and-push-image-lecoffre
|
||||
runs-on: ubuntu-latest
|
||||
environment: prod
|
||||
steps:
|
||||
- name: Install CLI
|
||||
uses: scaleway/action-scw@v0
|
||||
- name: Get container ID
|
||||
run: |
|
||||
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
|
||||
env:
|
||||
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
|
||||
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
|
||||
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
|
||||
- name: Deploy the container based on the new image
|
||||
run: |
|
||||
env_string=""
|
||||
while IFS= read -r line; do
|
||||
if [[ "$line" == *"="* ]]; then
|
||||
key=$(echo "$line" | cut -d '=' -f 1)
|
||||
value=$(echo "$line" | cut -d '=' -f 2-)
|
||||
if [[ -n "$key" ]]; then
|
||||
env_string+="environment-variables.$key=$value "
|
||||
fi
|
||||
fi
|
||||
done <<< "$ENV_VARS"
|
||||
env_string=$(echo $env_string | sed 's/ $//')
|
||||
scw container container update ${{ env.CONTAINER_ID }} $env_string
|
||||
env:
|
||||
ENV_VARS: ${{ secrets.ENV }}
|
||||
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
|
||||
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
|
||||
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
|
||||
|
74
.github/workflows/stg.yml
vendored
74
.github/workflows/stg.yml
vendored
@ -1,74 +0,0 @@
|
||||
name: Staging - Build & Deploy to Scaleway
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [staging]
|
||||
|
||||
env:
|
||||
PROJECT_ID_LECOFFRE: 72d08499-37c2-412b-877e-f8af0471654a
|
||||
NAMESPACE_ID_LECOFFRE: f8137e85-47ad-46a5-9e2e-18af5de829c5
|
||||
CONTAINER_REGISTRY_ENDPOINT_LECOFFRE: rg.fr-par.scw.cloud/funcscwlecoffrestgbqbfhtv6
|
||||
|
||||
IMAGE_NAME: front
|
||||
CONTAINER_NAME: front
|
||||
|
||||
jobs:
|
||||
build-and-push-image-lecoffre:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
|
||||
chmod 600 ~/.ssh/id_rsa
|
||||
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
- name: Copy SSH
|
||||
run: cp ~/.ssh/id_rsa id_rsa
|
||||
- name: Login to Scaleway Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: nologin
|
||||
password: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
registry: ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}
|
||||
- name: Build the Docker Image
|
||||
run: docker build . -t ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
|
||||
- name: Push the Docker Image to Scaleway Container Registry
|
||||
run: docker push ${{ env.CONTAINER_REGISTRY_ENDPOINT_LECOFFRE }}/${{ env.IMAGE_NAME }}
|
||||
deploy-to-scaleway-lecoffre:
|
||||
needs: build-and-push-image-lecoffre
|
||||
runs-on: ubuntu-latest
|
||||
environment: staging
|
||||
steps:
|
||||
- name: Install CLI
|
||||
uses: scaleway/action-scw@v0
|
||||
- name: Get container ID
|
||||
run: |
|
||||
echo "CONTAINER_ID=$(scw container container list namespace-id=${{env.NAMESPACE_ID_LECOFFRE}} -o json | jq -r '.[] | select(.name == "${{ env.CONTAINER_NAME }}") | .id')" >> $GITHUB_ENV
|
||||
env:
|
||||
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
|
||||
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
|
||||
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
|
||||
- name: Deploy the container based on the new image
|
||||
run: |
|
||||
env_string=""
|
||||
while IFS= read -r line; do
|
||||
if [[ "$line" == *"="* ]]; then
|
||||
key=$(echo "$line" | cut -d '=' -f 1)
|
||||
value=$(echo "$line" | cut -d '=' -f 2-)
|
||||
if [[ -n "$key" ]]; then
|
||||
env_string+="environment-variables.$key=$value "
|
||||
fi
|
||||
fi
|
||||
done <<< "$ENV_VARS"
|
||||
env_string=$(echo $env_string | sed 's/ $//')
|
||||
scw container container update ${{ env.CONTAINER_ID }} $env_string
|
||||
env:
|
||||
ENV_VARS: ${{ secrets.ENV }}
|
||||
SCW_ACCESS_KEY: ${{ secrets.SCW_ACCESS_KEY_LECOFFRE }}
|
||||
SCW_SECRET_KEY: ${{ secrets.SCW_SECRET_KEY_LECOFFRE }}
|
||||
SCW_DEFAULT_PROJECT_ID: ${{ env.PROJECT_ID_LECOFFRE }}
|
||||
SCW_DEFAULT_ORGANIZATION_ID: ${{ secrets.SCW_ORGANIZATION_ID_LECOFFRE }}
|
4
.vscode/settings.json
vendored
4
.vscode/settings.json
vendored
@ -1,7 +1,7 @@
|
||||
{
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
"editor.defaultFormatter": "vscode.typescript-language-features"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
@ -32,6 +32,6 @@
|
||||
"rust-client.disableRustup": true,
|
||||
"rust-client.autoStartRls": false,
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
"editor.defaultFormatter": "vscode.typescript-language-features"
|
||||
}
|
||||
}
|
51
Dockerfile
51
Dockerfile
@ -1,46 +1,33 @@
|
||||
# Install dependencies only when needed
|
||||
# syntax=docker/dockerfile:1.4
|
||||
FROM node:19-alpine AS deps
|
||||
|
||||
WORKDIR leCoffre-front
|
||||
WORKDIR /leCoffre-front
|
||||
|
||||
COPY package.json ./
|
||||
|
||||
RUN apk update && apk add openssh-client git
|
||||
ARG ENV_VARS
|
||||
RUN echo "${ENV_VARS}" > .env
|
||||
|
||||
COPY id_rsa /root/.ssh/id_rsa
|
||||
RUN chmod 600 ~/.ssh/id_rsa
|
||||
RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa
|
||||
RUN ssh-keyscan github.com smart-chain-fr/leCoffre-resources.git >> /root/.ssh/known_hosts
|
||||
RUN apk update && apk add --no-cache openssh-client git
|
||||
|
||||
RUN npm install --frozen-lockfile
|
||||
# Forward SSH agent via BuildKit (clé jamais écrite dans l'image)
|
||||
RUN --mount=type=ssh \
|
||||
mkdir -p /root/.ssh && \
|
||||
ssh-keyscan git.4nkweb.com >> /root/.ssh/known_hosts && \
|
||||
npm install --frozen-lockfile
|
||||
|
||||
# Rebuild the source code only when needed
|
||||
FROM node:19-alpine AS builder
|
||||
# Configuration pour le développement
|
||||
FROM node:19-alpine AS development
|
||||
WORKDIR /leCoffre-front
|
||||
|
||||
WORKDIR leCoffre-front
|
||||
|
||||
COPY --from=deps leCoffre-front/node_modules ./node_modules
|
||||
COPY --from=deps leCoffre-front/package.json package.json
|
||||
COPY tsconfig.json tsconfig.json
|
||||
COPY next.config.js next.config.js
|
||||
COPY src src
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# Production image, copy all the files and run next
|
||||
FROM node:19-alpine AS production
|
||||
|
||||
WORKDIR leCoffre-front
|
||||
COPY --from=deps /leCoffre-front/node_modules ./node_modules
|
||||
COPY --from=deps /leCoffre-front/package.json ./package.json
|
||||
COPY --from=deps /leCoffre-front/.env ./.env
|
||||
COPY . .
|
||||
|
||||
# Création de l'utilisateur non-root
|
||||
RUN adduser -D lecoffreuser --uid 10000 && chown -R lecoffreuser .
|
||||
|
||||
COPY public ./public
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/node_modules ./node_modules
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/.next ./.next
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/next.config.js ./next.config.js
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/package.json ./package.json
|
||||
|
||||
USER lecoffreuser
|
||||
|
||||
CMD ["npm", "run", "start"]
|
||||
CMD ["npm", "run", "dev"]
|
||||
EXPOSE 3000
|
@ -1,44 +0,0 @@
|
||||
# Install dependencies only when needed
|
||||
FROM node:19-alpine AS deps
|
||||
|
||||
WORKDIR leCoffre-front
|
||||
|
||||
COPY package.json ./
|
||||
|
||||
RUN apk update && apk add openssh-client git
|
||||
|
||||
COPY id_rsa /root/.ssh/id_rsa
|
||||
RUN chmod 600 ~/.ssh/id_rsa
|
||||
RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa
|
||||
RUN ssh-keyscan github.com smart-chain-fr/leCoffre-resources.git >> /root/.ssh/known_hosts
|
||||
|
||||
RUN npm install --frozen-lockfile
|
||||
|
||||
# Rebuild the source code only when needed
|
||||
FROM node:19-alpine AS builder
|
||||
|
||||
WORKDIR leCoffre-front
|
||||
|
||||
COPY --from=deps leCoffre-front/node_modules ./node_modules
|
||||
COPY --from=deps leCoffre-front/package.json package.json
|
||||
COPY tsconfig.json tsconfig.json
|
||||
COPY src src
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# Production image, copy all the files and run next
|
||||
FROM node:19-alpine AS production
|
||||
|
||||
WORKDIR leCoffre-front
|
||||
|
||||
RUN adduser -D lecoffreuser --uid 10000 && chown -R lecoffreuser .
|
||||
|
||||
COPY public ./public
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/node_modules ./node_modules
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/.next ./.next
|
||||
COPY --from=builder --chown=lecoffreuser leCoffre-front/package.json ./package.json
|
||||
|
||||
USER lecoffreuser
|
||||
|
||||
CMD ["npm", "run", "start"]
|
||||
EXPOSE 3000
|
@ -2,6 +2,9 @@
|
||||
|
||||
const nextConfig = {
|
||||
reactStrictMode: false,
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
publicRuntimeConfig: {
|
||||
// Will be available on both server and client
|
||||
NEXT_PUBLIC_BACK_API_PROTOCOL: process.env.NEXT_PUBLIC_BACK_API_PROTOCOL,
|
||||
@ -16,6 +19,7 @@ const nextConfig = {
|
||||
NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL,
|
||||
NEXT_PUBLIC_HOTJAR_SITE_ID: process.env.NEXT_PUBLIC_HOTJAR_SITE_ID,
|
||||
NEXT_PUBLIC_HOTJAR_VERSION: process.env.NEXT_PUBLIC_HOTJAR_VERSION,
|
||||
NEXT_PUBLIC_4NK_URL: process.env.NEXT_PUBLIC_4NK_URL,
|
||||
},
|
||||
|
||||
serverRuntimeConfig: {
|
||||
@ -31,6 +35,7 @@ const nextConfig = {
|
||||
NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL,
|
||||
NEXT_PUBLIC_HOTJAR_SITE_ID: process.env.NEXT_PUBLIC_HOTJAR_SITE_ID,
|
||||
NEXT_PUBLIC_HOTJAR_VERSION: process.env.NEXT_PUBLIC_HOTJAR_VERSION,
|
||||
NEXT_PUBLIC_4NK_URL: process.env.NEXT_PUBLIC_4NK_URL,
|
||||
},
|
||||
|
||||
env: {
|
||||
@ -46,6 +51,7 @@ const nextConfig = {
|
||||
NEXT_PUBLIC_DOCAPOSTE_API_URL: process.env.NEXT_PUBLIC_DOCAPOSTE_API_URL,
|
||||
NEXT_PUBLIC_HOTJAR_SITE_ID: process.env.NEXT_PUBLIC_HOTJAR_SITE_ID,
|
||||
NEXT_PUBLIC_HOTJAR_VERSION: process.env.NEXT_PUBLIC_HOTJAR_VERSION,
|
||||
NEXT_PUBLIC_4NK_URL: process.env.NEXT_PUBLIC_4NK_URL,
|
||||
},
|
||||
|
||||
// webpack: config => {
|
||||
|
4376
package-lock.json
generated
4376
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -4,7 +4,7 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"build": "NEXT_TELEMETRY_DISABLED=1 next build --no-lint",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"format": "prettier --write src"
|
||||
@ -30,8 +30,9 @@
|
||||
"heroicons": "^2.1.5",
|
||||
"jszip": "^3.10.1",
|
||||
"jwt-decode": "^3.1.2",
|
||||
"le-coffre-resources": "git@github.com:smart-chain-fr/leCoffre-resources.git#v2.167",
|
||||
"le-coffre-resources": "git+ssh://git@git.4nkweb.com/4nk/lecoffre-ressources.git#v2.167",
|
||||
"next": "^14.2.3",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"prettier": "^2.8.7",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
|
75
src/common/Api/LeCoffreApi/sdk/AbstractService.ts
Normal file
75
src/common/Api/LeCoffreApi/sdk/AbstractService.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import MessageBus from 'src/sdk/MessageBus';
|
||||
|
||||
export default abstract class AbstractService {
|
||||
|
||||
protected static readonly messageBus: MessageBus = MessageBus.getInstance();
|
||||
|
||||
private static readonly CACHE_TTL = 45 * 60 * 1000; // 45 minutes cache TTL
|
||||
|
||||
protected constructor() { }
|
||||
|
||||
protected static setItem(key: string, process: any): void {
|
||||
const list: any[] = JSON.parse(sessionStorage.getItem(key) || '[]');
|
||||
|
||||
const index: number = list.findIndex((item: any) => item.process.processData.uid === process.processData.uid);
|
||||
if (index !== -1) {
|
||||
list[index] = {
|
||||
process: process,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
} else {
|
||||
list.push({
|
||||
process: process,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
sessionStorage.setItem(key, JSON.stringify(list));
|
||||
}
|
||||
|
||||
protected static getItem(key: string, uid: string): any {
|
||||
const list: any[] = JSON.parse(sessionStorage.getItem(key) || '[]');
|
||||
if (list.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const item: any = list.find((item: any) => item.process.processData.uid === uid);
|
||||
if (!item) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
if ((now - item.timestamp) < this.CACHE_TTL) {
|
||||
return item.process;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected static getItems(key: string): any[] {
|
||||
const list: any[] = JSON.parse(sessionStorage.getItem(key) || '[]');
|
||||
const now = Date.now();
|
||||
|
||||
const items: any[] = [];
|
||||
for (const item of list) {
|
||||
if (now - item.timestamp < this.CACHE_TTL) {
|
||||
items.push(item.process);
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
protected static removeItem(key: string, uid: string): void {
|
||||
const list: any[] = JSON.parse(sessionStorage.getItem(key) || '[]');
|
||||
|
||||
const index: number = list.findIndex((item: any) => item.process.processData.uid === uid);
|
||||
if (index !== -1) {
|
||||
list.splice(index, 1);
|
||||
}
|
||||
|
||||
sessionStorage.setItem(key, JSON.stringify(list));
|
||||
}
|
||||
}
|
152
src/common/Api/LeCoffreApi/sdk/CollaboratorService.ts
Normal file
152
src/common/Api/LeCoffreApi/sdk/CollaboratorService.ts
Normal file
@ -0,0 +1,152 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
|
||||
export default class CollaboratorService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static createCollaborator(collaboratorData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'collaborator',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...collaboratorData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getCollaboratorByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getCollaborators(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = this.getItems('_collaborators_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'collaborator' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (const process of processes) {
|
||||
// Update cache
|
||||
this.setItem('_collaborators_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getCollaboratorByUid(uid: string): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_collaborators_', uid);
|
||||
if (item) {
|
||||
return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['uid'] === uid &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'collaborator' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false'
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
|
||||
// Update cache
|
||||
this.setItem('_collaborators_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateCollaborator(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const collaboratorUid: string = process.processData.uid;
|
||||
this.removeItem('_collaborators_', collaboratorUid);
|
||||
|
||||
this.getCollaboratorByUid(collaboratorUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
152
src/common/Api/LeCoffreApi/sdk/CustomerService.ts
Normal file
152
src/common/Api/LeCoffreApi/sdk/CustomerService.ts
Normal file
@ -0,0 +1,152 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
|
||||
export default class CustomerService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static createCustomer(customerData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'customer',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...customerData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getCustomerByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getCustomers(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = [];//this.getItems('_customers_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'customer' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (const process of processes) {
|
||||
// Update cache
|
||||
this.setItem('_customers_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getCustomerByUid(uid: string): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_customers_', uid);
|
||||
if (item) {
|
||||
//return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['uid'] === uid &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'customer' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false'
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
|
||||
// Update cache
|
||||
this.setItem('_customers_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateCustomer(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const customerUid: string = process.processData.uid;
|
||||
this.removeItem('_customers_', customerUid);
|
||||
|
||||
this.getCustomerByUid(customerUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
165
src/common/Api/LeCoffreApi/sdk/DeedTypeService.ts
Normal file
165
src/common/Api/LeCoffreApi/sdk/DeedTypeService.ts
Normal file
@ -0,0 +1,165 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
import DocumentTypeService from './DocumentTypeService';
|
||||
|
||||
export default class DeedTypeService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static createDeedType(deedTypeData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'deedType',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...deedTypeData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getDeedTypeByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getDeedTypes(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = this.getItems('_deed_types_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'deedType' &&
|
||||
publicValues['isDeleted'] && publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then(async (processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (let process of processes) {
|
||||
process = await this.completeDeedType(process);
|
||||
|
||||
// Update cache
|
||||
this.setItem('_deed_types_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getDeedTypeByUid(uid: string, includeDocumentTypes: boolean = true): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_deed_types_', uid);
|
||||
if (item) {
|
||||
return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'deedType' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false').then(async (processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
let process: any = processes[0];
|
||||
process = await this.completeDeedType(process);
|
||||
|
||||
// Update cache
|
||||
this.setItem('_deed_types_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateDeedType(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const deedTypeUid: string = process.processData.uid;
|
||||
this.removeItem('_deed_types_', deedTypeUid);
|
||||
|
||||
this.getDeedTypeByUid(deedTypeUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
private static async completeDeedType(process: any): Promise<any> {
|
||||
if (process.processData.document_types && process.processData.document_types.length > 0) {
|
||||
process.processData.document_types = await new Promise<any[]>(async (resolve: (document_types: any[]) => void) => {
|
||||
let document_types: any[] = [];
|
||||
for (const document_type of process.processData.document_types) {
|
||||
document_types.push((await DocumentTypeService.getDocumentTypeByUid(document_type.uid)).processData);
|
||||
}
|
||||
|
||||
// Remove duplicates
|
||||
document_types = document_types.filter((item: any, index: number) => document_types.findIndex((t: any) => t.uid === item.uid) === index);
|
||||
resolve(document_types);
|
||||
});
|
||||
}
|
||||
|
||||
return process
|
||||
}
|
||||
}
|
152
src/common/Api/LeCoffreApi/sdk/DocumentService.ts
Normal file
152
src/common/Api/LeCoffreApi/sdk/DocumentService.ts
Normal file
@ -0,0 +1,152 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
|
||||
export default class DocumentService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static createDocument(documentData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'document',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...documentData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getDocumentByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getDocuments(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = [];//this.getItems('_documents_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'document' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (const process of processes) {
|
||||
// Update cache
|
||||
this.setItem('_documents_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getDocumentByUid(uid: string): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_documents_', uid);
|
||||
if (item) {
|
||||
//return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['uid'] === uid &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'document' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false'
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
|
||||
// Update cache
|
||||
this.setItem('_documents_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateDocument(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const documentUid: string = process.processData.uid;
|
||||
this.removeItem('_documents_', documentUid);
|
||||
|
||||
this.getDocumentByUid(documentUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
145
src/common/Api/LeCoffreApi/sdk/DocumentTypeService.ts
Normal file
145
src/common/Api/LeCoffreApi/sdk/DocumentTypeService.ts
Normal file
@ -0,0 +1,145 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
|
||||
export default class DocumentTypeService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static createDocumentType(documentTypeData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'documentType',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...documentTypeData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getDocumentTypeByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getDocumentTypes(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = this.getItems('_document_types_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'documentType' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then(async (processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (const process of processes) {
|
||||
// Update cache
|
||||
this.setItem('_document_types_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getDocumentTypeByUid(uid: string): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_document_types_', uid);
|
||||
if (item) {
|
||||
return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'documentType' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false').then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
|
||||
// Update cache
|
||||
this.setItem('_document_types_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateDocumentType(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const documentTypeUid: string = process.processData.uid;
|
||||
this.removeItem('_document_types_', documentTypeUid);
|
||||
|
||||
this.getDocumentTypeByUid(documentTypeUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
97
src/common/Api/LeCoffreApi/sdk/FileService.ts
Normal file
97
src/common/Api/LeCoffreApi/sdk/FileService.ts
Normal file
@ -0,0 +1,97 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import MessageBus from 'src/sdk/MessageBus';
|
||||
import User from 'src/sdk/User';
|
||||
import { FileData } from '../../../../front/Api/Entities/types';
|
||||
|
||||
export default class FileService {
|
||||
|
||||
private static readonly messageBus: MessageBus = MessageBus.getInstance();
|
||||
|
||||
private constructor() { }
|
||||
|
||||
public static createFile(fileData: FileData, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'file',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...fileData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
resolve(processCreated);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getFileByUid(uid: string): Promise<any> {
|
||||
return this.messageBus.getFileByUid(uid);
|
||||
}
|
||||
|
||||
public static updateFile(process: any, newData: Partial<FileData> & { isDeleted?: string }): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
222
src/common/Api/LeCoffreApi/sdk/FolderService.ts
Normal file
222
src/common/Api/LeCoffreApi/sdk/FolderService.ts
Normal file
@ -0,0 +1,222 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
import CustomerService from './CustomerService';
|
||||
import DeedTypeService from './DeedTypeService';
|
||||
import DocumentTypeService from './DocumentTypeService';
|
||||
import DocumentService from './DocumentService';
|
||||
import FileService from './FileService';
|
||||
import NoteService from './NoteService';
|
||||
|
||||
export default class FolderService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static invalidateCache(uid: string): void {
|
||||
this.removeItem('_folders_', uid);
|
||||
}
|
||||
|
||||
public static createFolder(folderData: any, stakeholdersId: string[], customersId: string[]): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'folder',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...folderData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
stakeholders: {
|
||||
members: stakeholdersId,
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['documents', 'motes'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
customers: {
|
||||
members: customersId,
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: privateFields,
|
||||
min_sig_member: 0.0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getFolderByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getFolders(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = [];//this.getItems('_folders_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'folder' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then(async (processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (let process of processes) {
|
||||
process = await this.completeFolder(process);
|
||||
|
||||
// Update cache
|
||||
//this.setItem('_folders_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getFolderByUid(uid: string): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_folders_', uid);
|
||||
if (item) {
|
||||
//return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['uid'] === uid &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'folder' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false'
|
||||
).then(async (processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
let process: any = processes[0];
|
||||
process = await this.completeFolder(process);
|
||||
|
||||
// Update cache
|
||||
//this.setItem('_folders_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateFolder(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const folderUid: string = process.processData.uid;
|
||||
//this.removeItem('_folders_', folderUid);
|
||||
|
||||
//this.getFolderByUid(folderUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
private static async completeFolder(process: any): Promise<any> {
|
||||
if (process.processData.customers && process.processData.customers.length > 0) {
|
||||
process.processData.customers = await new Promise<any[]>(async (resolve: (customers: any[]) => void) => {
|
||||
const customers: any[] = [];
|
||||
for (const customer of process.processData.customers) {
|
||||
customers.push((await CustomerService.getCustomerByUid(customer.uid)).processData);
|
||||
}
|
||||
resolve(customers);
|
||||
});
|
||||
|
||||
if (process.processData.customers && process.processData.customers.length > 0) {
|
||||
const documents: any[] = (await DocumentService.getDocuments()).map((process: any) => process.processData);
|
||||
for (const customer of process.processData.customers) {
|
||||
customer.documents = documents.filter((document: any) => (document.depositor && document.depositor.uid === customer.uid) || (document.customer && document.customer.uid === customer.uid));
|
||||
|
||||
for (const document of customer.documents) {
|
||||
if (document.document_type) {
|
||||
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
|
||||
}
|
||||
|
||||
if (document.files && document.files.length > 0) {
|
||||
const files: any[] = [];
|
||||
for (const file of document.files) {
|
||||
const p: any = await FileService.getFileByUid(file.uid);
|
||||
files.push({ uid: p.processData.uid, file_name: p.processData.file_name });
|
||||
}
|
||||
document.files = files;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (process.processData.deed && process.processData.deed.deed_type) {
|
||||
const deed_type: any = (await DeedTypeService.getDeedTypeByUid(process.processData.deed.deed_type.uid)).processData;
|
||||
process.processData.deed.deed_type = deed_type;
|
||||
|
||||
if (deed_type.document_types && deed_type.document_types.length > 0) {
|
||||
// Remove duplicates
|
||||
process.processData.deed.document_types = deed_type.document_types.filter((item: any, index: number) => deed_type.document_types.findIndex((t: any) => t.uid === item.uid) === index);
|
||||
}
|
||||
}
|
||||
|
||||
const notes: any[] = (await NoteService.getNotes()).map((process: any) => process.processData);
|
||||
if (notes.length > 0) {
|
||||
process.processData.notes = notes.filter((note: any) => note.folder.uid === process.processData.uid);
|
||||
}
|
||||
|
||||
return process;
|
||||
}
|
||||
}
|
45
src/common/Api/LeCoffreApi/sdk/Loader/LoaderService.ts
Normal file
45
src/common/Api/LeCoffreApi/sdk/Loader/LoaderService.ts
Normal file
@ -0,0 +1,45 @@
|
||||
class LoaderService {
|
||||
private static instance: LoaderService;
|
||||
private _isVisible: boolean = false;
|
||||
private _callbacks: Array<(isVisible: boolean) => void> = [];
|
||||
|
||||
private constructor() { }
|
||||
|
||||
public static getInstance(): LoaderService {
|
||||
if (!LoaderService.instance) {
|
||||
LoaderService.instance = new LoaderService();
|
||||
}
|
||||
return LoaderService.instance;
|
||||
}
|
||||
|
||||
public show(): void {
|
||||
this._isVisible = true;
|
||||
this._notifySubscribers();
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
this._isVisible = false;
|
||||
this._notifySubscribers();
|
||||
}
|
||||
|
||||
public get isVisible(): boolean {
|
||||
return this._isVisible;
|
||||
}
|
||||
|
||||
public subscribe(callback: (isVisible: boolean) => void): () => void {
|
||||
this._callbacks.push(callback);
|
||||
|
||||
// Return unsubscribe function
|
||||
return () => {
|
||||
this._callbacks = this._callbacks.filter(cb => cb !== callback);
|
||||
};
|
||||
}
|
||||
|
||||
private _notifySubscribers(): void {
|
||||
this._callbacks.forEach(callback => {
|
||||
callback(this._isVisible);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default LoaderService;
|
38
src/common/Api/LeCoffreApi/sdk/Loader/classes.module.scss
Normal file
38
src/common/Api/LeCoffreApi/sdk/Loader/classes.module.scss
Normal file
@ -0,0 +1,38 @@
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(1turn);
|
||||
}
|
||||
}
|
||||
|
||||
.loader-container {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(255, 255, 255, 0.7);
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.loader {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background-color: white;
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-top: 1rem;
|
||||
font-size: 1rem;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
animation: spin 1s infinite linear;
|
||||
}
|
37
src/common/Api/LeCoffreApi/sdk/Loader/index.tsx
Normal file
37
src/common/Api/LeCoffreApi/sdk/Loader/index.tsx
Normal file
@ -0,0 +1,37 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import { ArrowPathIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
import LoaderService from "./LoaderService";
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
// Composant fusionné qui gère à la fois l'abonnement au service et l'affichage
|
||||
const Loader: React.FC = () => {
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// S'abonner aux changements d'état du loader
|
||||
const unsubscribe = LoaderService.getInstance().subscribe((visible) => {
|
||||
setIsVisible(visible);
|
||||
});
|
||||
|
||||
// Nettoyage de l'abonnement
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Ne rien afficher si le loader n'est pas visible
|
||||
if (!isVisible) return null;
|
||||
|
||||
// Affichage du loader avec overlay
|
||||
return (
|
||||
<div className={classes["loader-container"]}>
|
||||
<div className={classes["loader"]}>
|
||||
<ArrowPathIcon className={classes["spinner"]} width={40} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Loader;
|
109
src/common/Api/LeCoffreApi/sdk/NoteService.ts
Normal file
109
src/common/Api/LeCoffreApi/sdk/NoteService.ts
Normal file
@ -0,0 +1,109 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import MessageBus from 'src/sdk/MessageBus';
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
export default class NoteService {
|
||||
|
||||
private static readonly messageBus: MessageBus = MessageBus.getInstance();
|
||||
|
||||
private constructor() { }
|
||||
|
||||
public static createNote(noteData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'note',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...noteData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
resolve(processCreated);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getNotes(): Promise<any[]> {
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'note' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false');
|
||||
}
|
||||
|
||||
public static getNoteByUid(uid: string): Promise<any> {
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'note' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false').then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateNote(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
152
src/common/Api/LeCoffreApi/sdk/OfficeService.ts
Normal file
152
src/common/Api/LeCoffreApi/sdk/OfficeService.ts
Normal file
@ -0,0 +1,152 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
import AbstractService from './AbstractService';
|
||||
|
||||
export default class OfficeService extends AbstractService {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public static createOffice(officeData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'office',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...officeData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
this.getOfficeByUid(processCreated.processData.uid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getOffices(): Promise<any[]> {
|
||||
// Check if we have valid cache
|
||||
const items: any[] = this.getItems('_offices_');
|
||||
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'office' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false' &&
|
||||
!items.map((item: any) => item.processData.uid).includes(publicValues['uid'])
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
return items;
|
||||
} else {
|
||||
for (const process of processes) {
|
||||
// Update cache
|
||||
this.setItem('_offices_', process);
|
||||
|
||||
items.push(process);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static getOfficeByUid(uid: string): Promise<any> {
|
||||
// Check if we have valid cache
|
||||
const item: any = this.getItem('_offices_', uid);
|
||||
if (item) {
|
||||
return Promise.resolve(item);
|
||||
}
|
||||
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) =>
|
||||
publicValues['uid'] &&
|
||||
publicValues['uid'] === uid &&
|
||||
publicValues['utype'] &&
|
||||
publicValues['utype'] === 'office' &&
|
||||
publicValues['isDeleted'] &&
|
||||
publicValues['isDeleted'] === 'false'
|
||||
).then((processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
|
||||
// Update cache
|
||||
this.setItem('_offices_', process);
|
||||
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateDocument(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
const officeUid: string = process.processData.uid;
|
||||
this.removeItem('_offices_', officeUid);
|
||||
|
||||
this.getOfficeByUid(officeUid).then(resolve).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
109
src/common/Api/LeCoffreApi/sdk/RoleService.ts
Normal file
109
src/common/Api/LeCoffreApi/sdk/RoleService.ts
Normal file
@ -0,0 +1,109 @@
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import MessageBus from 'src/sdk/MessageBus';
|
||||
import User from 'src/sdk/User';
|
||||
|
||||
export default class RoleService {
|
||||
|
||||
private static readonly messageBus: MessageBus = MessageBus.getInstance();
|
||||
|
||||
private constructor() { }
|
||||
|
||||
public static createRole(roleData: any, validatorId: string): Promise<any> {
|
||||
const ownerId = User.getInstance().getPairingId()!;
|
||||
|
||||
const processData: any = {
|
||||
uid: uuidv4(),
|
||||
utype: 'role',
|
||||
isDeleted: 'false',
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
...roleData,
|
||||
};
|
||||
|
||||
const privateFields: string[] = Object.keys(processData);
|
||||
privateFields.splice(privateFields.indexOf('uid'), 1);
|
||||
privateFields.splice(privateFields.indexOf('utype'), 1);
|
||||
privateFields.splice(privateFields.indexOf('isDeleted'), 1);
|
||||
|
||||
const roles: any = {
|
||||
demiurge: {
|
||||
members: [...[ownerId], validatorId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
},
|
||||
owner: {
|
||||
members: [ownerId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: [...privateFields, 'roles', 'uid', 'utype'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
validator: {
|
||||
members: [validatorId],
|
||||
validation_rules: [
|
||||
{
|
||||
quorum: 0.5,
|
||||
fields: ['idCertified', 'roles'],
|
||||
min_sig_member: 1,
|
||||
},
|
||||
{
|
||||
quorum: 0.0,
|
||||
fields: [...privateFields],
|
||||
min_sig_member: 0,
|
||||
},
|
||||
],
|
||||
storages: []
|
||||
},
|
||||
apophis: {
|
||||
members: [ownerId],
|
||||
validation_rules: [],
|
||||
storages: []
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<any>((resolve: (processCreated: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.createProcess(processData, privateFields, roles).then((processCreated: any) => {
|
||||
this.messageBus.notifyUpdate(processCreated.processId, processCreated.process.states[0].state_id).then(() => {
|
||||
this.messageBus.validateState(processCreated.processId, processCreated.process.states[0].state_id).then((_stateValidated: any) => {
|
||||
resolve(processCreated);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static getRoles(): Promise<any[]> {
|
||||
return this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['utype'] && publicValues['utype'] === 'role' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false');
|
||||
}
|
||||
|
||||
public static getRoleByUid(uid: string): Promise<any> {
|
||||
return new Promise<any>((resolve: (process: any) => void, reject: (error: string) => void) => {
|
||||
this.messageBus.getProcessesDecoded((publicValues: any) => publicValues['uid'] && publicValues['uid'] === uid && publicValues['utype'] && publicValues['utype'] === 'role' && publicValues['isDeleted'] && publicValues['isDeleted'] === 'false').then(async (processes: any[]) => {
|
||||
if (processes.length === 0) {
|
||||
resolve(null);
|
||||
} else {
|
||||
const process: any = processes[0];
|
||||
resolve(process);
|
||||
}
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
public static updateRole(process: any, newData: any): Promise<void> {
|
||||
return new Promise<void>((resolve: () => void, reject: (error: string) => void) => {
|
||||
this.messageBus.updateProcess(process.processId, { updated_at: new Date().toISOString(), ...newData }, [], null).then((processUpdated: any) => {
|
||||
const newStateId: string = processUpdated.diffs[0]?.state_id;
|
||||
this.messageBus.notifyUpdate(process.processId, newStateId).then(() => {
|
||||
this.messageBus.validateState(process.processId, newStateId).then((_stateValidated) => {
|
||||
resolve();
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
}).catch(reject);
|
||||
});
|
||||
}
|
||||
}
|
@ -40,12 +40,15 @@ export default class Auth extends BaseApiService {
|
||||
}
|
||||
}
|
||||
|
||||
public async getIdnotJwt(autorizationCode: string | string[]): Promise<{ accessToken: string; refreshToken: string }> {
|
||||
const variables = FrontendVariables.getInstance();
|
||||
const baseBackUrl = variables.BACK_API_PROTOCOL + variables.BACK_API_HOST;
|
||||
public async getIdNotUser(autorizationCode: string | string[]): Promise<{ idNotUser: any }> {
|
||||
// const variables = FrontendVariables.getInstance();
|
||||
|
||||
// TODO: review
|
||||
const baseBackUrl = 'http://localhost:8080';//variables.BACK_API_PROTOCOL + variables.BACK_API_HOST;
|
||||
|
||||
const url = new URL(`${baseBackUrl}/api/v1/idnot/user/${autorizationCode}`);
|
||||
try {
|
||||
return await this.postRequest<{ accessToken: string; refreshToken: string }>(url);
|
||||
return await this.postRequest<{ idNotUser: any }>(url);
|
||||
} catch (err) {
|
||||
this.onError(err);
|
||||
return Promise.reject(err);
|
||||
|
2
src/front/Api/Entities/index.ts
Normal file
2
src/front/Api/Entities/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export * from './types';
|
||||
export * from './rule';
|
21
src/front/Api/Entities/types.ts
Normal file
21
src/front/Api/Entities/types.ts
Normal file
@ -0,0 +1,21 @@
|
||||
/**
|
||||
* FileBlob interface representing a file's binary data and metadata
|
||||
* Used for file transmission and storage in the application
|
||||
*/
|
||||
export interface FileBlob {
|
||||
/** MIME type of the file (e.g., "application/pdf", "image/jpeg") */
|
||||
type: string;
|
||||
/** Binary data of the file as Uint8Array */
|
||||
data: Uint8Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* FileData interface representing a complete file object with blob and metadata
|
||||
* Used when creating or updating files in the system
|
||||
*/
|
||||
export interface FileData {
|
||||
/** The file blob containing type and binary data */
|
||||
file_blob: FileBlob;
|
||||
/** The name of the file */
|
||||
file_name: string;
|
||||
}
|
@ -14,10 +14,13 @@ import classNames from "classnames";
|
||||
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "../Button";
|
||||
import Confirm from "../OldModal/Confirm";
|
||||
import Documents from "@Front/Api/LeCoffreApi/Customer/Documents/Documents";
|
||||
import Files from "@Front/Api/LeCoffreApi/Customer/Files/Files";
|
||||
import Alert from "../OldModal/Alert";
|
||||
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
|
||||
|
||||
type IProps = {
|
||||
onChange?: (files: File[]) => void;
|
||||
open: boolean;
|
||||
@ -206,35 +209,91 @@ export default class DepositOtherDocument extends React.Component<IProps, IState
|
||||
this.setState({
|
||||
isLoading: true,
|
||||
});
|
||||
const filesArray = this.state.currentFiles;
|
||||
|
||||
const filesArray = this.state.currentFiles;
|
||||
if (!filesArray) return;
|
||||
let documentCreated: Document = {} as Document;
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
let documentCreated: any;
|
||||
try {
|
||||
documentCreated = await Documents.getInstance().post({
|
||||
documentCreated = await new Promise<any>((resolve: (document: any) => void) => {
|
||||
const documentTypeData: any = {
|
||||
folder: {
|
||||
uid: this.props.folder_uid,
|
||||
},
|
||||
depositor: {
|
||||
uid: this.props.customer_uid,
|
||||
},
|
||||
}
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
DocumentService.createDocument(documentTypeData, validatorId).then((processCreated: any) => {
|
||||
if (processCreated) {
|
||||
const document: any = processCreated.processData;
|
||||
resolve(document);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
this.setState({ showFailedDocument: "Le dossier est vérifié aucune modification n'est acceptée", isLoading: false });
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < filesArray.length; i++) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", filesArray[i]!.file, filesArray[i]!.fileName);
|
||||
const query = JSON.stringify({ document: { uid: documentCreated.uid } });
|
||||
formData.append("q", query);
|
||||
try {
|
||||
await Files.getInstance().post(formData);
|
||||
} catch (e) {
|
||||
this.setState({ showFailedUploaded: "Le fichier ne correspond pas aux critères demandés", isLoading: false });
|
||||
return;
|
||||
const customer: any = await new Promise<void>((resolve: (customer: any) => void) => {
|
||||
CustomerService.getCustomerByUid(this.props.customer_uid).then((process: any) => {
|
||||
if (process) {
|
||||
const customer: any = process.processData;
|
||||
resolve(customer);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
for (let i = 0; i < filesArray.length; i++) {
|
||||
const file = filesArray[i]!.file;
|
||||
await new Promise<void>((resolve: () => void) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
if (event.target?.result) {
|
||||
const date: Date = new Date();
|
||||
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;
|
||||
|
||||
const fileName: string = `${file.name.split('.')[0]}-${strDate}.${file.name.split('.').pop()}`;
|
||||
|
||||
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
|
||||
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
const fileBlob: any = {
|
||||
type: file.type,
|
||||
data: uint8Array
|
||||
};
|
||||
|
||||
const fileData: any = {
|
||||
file_blob: fileBlob,
|
||||
file_name: fileName
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||
const fileUid: string = processCreated.processData.uid;
|
||||
|
||||
DocumentService.getDocumentByUid(documentCreated.uid).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
|
||||
let files: any[] = document.files;
|
||||
if (!files) {
|
||||
files = [];
|
||||
}
|
||||
files.push({ uid: fileUid });
|
||||
|
||||
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
this.setState({
|
||||
|
@ -213,9 +213,9 @@ export default function DragAndDrop(props: IProps) {
|
||||
</div>
|
||||
{documentFiles.length > 0 && (
|
||||
<div className={classes["documents"]}>
|
||||
{documentFiles.map((documentFile) => (
|
||||
{documentFiles.map((documentFile, index) => (
|
||||
<DocumentFileElement
|
||||
key={documentFile.id}
|
||||
key={documentFile.uid || `${documentFile.id}-${index}`}
|
||||
isLoading={documentFile.isLoading}
|
||||
file={documentFile.file}
|
||||
onRemove={() => handleRemove(documentFile)}
|
||||
|
@ -1,6 +1,4 @@
|
||||
import { AppRuleActions, AppRuleNames } from "@Front/Api/Entities/rule";
|
||||
import Notifications from "@Front/Api/LeCoffreApi/Notary/Notifications/Notifications";
|
||||
import OfficeFolderAnchors from "@Front/Api/LeCoffreApi/Notary/OfficeFolderAnchors/OfficeFolderAnchors";
|
||||
import Rules, { RulesMode } from "@Front/Components/Elements/Rules";
|
||||
import Module from "@Front/Config/Module";
|
||||
import Toasts from "@Front/Stores/Toasts";
|
||||
@ -17,6 +15,7 @@ export default function Navigation() {
|
||||
const pathname = usePathname();
|
||||
|
||||
const getAnchoringStatus = useCallback(async () => {
|
||||
/* TODO: review
|
||||
const anchors = await OfficeFolderAnchors.getInstance().get({
|
||||
where: {
|
||||
status: {
|
||||
@ -27,7 +26,10 @@ export default function Navigation() {
|
||||
folder: true,
|
||||
},
|
||||
});
|
||||
*/
|
||||
// const anchors = [] as any[];
|
||||
|
||||
/* TODO: review
|
||||
try {
|
||||
for (const anchor of anchors) {
|
||||
await OfficeFolderAnchors.getInstance().getByUid(anchor.folder?.uid as string);
|
||||
@ -35,10 +37,13 @@ export default function Navigation() {
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
*/
|
||||
}, []);
|
||||
|
||||
const getNotifications = useCallback(async () => {
|
||||
//await getAnchoringStatus();
|
||||
|
||||
/* TODO: review
|
||||
const notifications = await Notifications.getInstance().get({
|
||||
where: {
|
||||
read: false,
|
||||
@ -50,6 +55,9 @@ export default function Navigation() {
|
||||
notification: { created_at: "desc" },
|
||||
},
|
||||
});
|
||||
*/
|
||||
const notifications = [] as any[];
|
||||
|
||||
notifications.forEach((notification) => {
|
||||
Toasts.getInstance().open({
|
||||
title: notification.notification.message,
|
||||
|
@ -8,6 +8,7 @@ import MenuItem from "@Front/Components/DesignSystem/Menu/MenuItem";
|
||||
type IProps = {
|
||||
isOpen: boolean;
|
||||
closeModal: () => void;
|
||||
isCustomer?: boolean;
|
||||
};
|
||||
type IState = {};
|
||||
|
||||
@ -19,29 +20,31 @@ export default class ProfileModal extends React.Component<IProps, IState> {
|
||||
<>
|
||||
<div className={classes["background"]} onClick={this.props.closeModal} />
|
||||
<div className={classes["root"]}>
|
||||
<MenuItem
|
||||
{!this.props.isCustomer && <MenuItem
|
||||
item={{
|
||||
text: "Mon compte",
|
||||
link: Module.getInstance().get().modules.pages.MyAccount.props.path,
|
||||
}}
|
||||
/>
|
||||
/>}
|
||||
|
||||
<MenuItem
|
||||
{!this.props.isCustomer && <MenuItem
|
||||
item={{
|
||||
text: "Guide de Prise en Main",
|
||||
link: "https://ressources.lecoffre.io/",
|
||||
target: "_blank",
|
||||
}}
|
||||
/>
|
||||
/>}
|
||||
|
||||
<MenuItem
|
||||
|
||||
{!this.props.isCustomer && <MenuItem
|
||||
item={{
|
||||
text: "CGU",
|
||||
link: "/CGU_LeCoffre_io.pdf",
|
||||
hasSeparator: true,
|
||||
}}
|
||||
/>
|
||||
<LogOutButton />
|
||||
/>}
|
||||
|
||||
<LogOutButton isCustomer={this.props.isCustomer} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
@ -9,7 +9,7 @@ import ProfileModal from "./ProfileModal";
|
||||
|
||||
const headerBreakpoint = 1023;
|
||||
|
||||
export default function Profile() {
|
||||
export default function Profile(props: { isCustomer?: boolean }) {
|
||||
const { isOpen, toggle, close } = useOpenable();
|
||||
|
||||
useEffect(() => {
|
||||
@ -27,7 +27,7 @@ export default function Profile() {
|
||||
return (
|
||||
<div className={classes["root"]}>
|
||||
<IconButton icon={<UserIcon />} onClick={toggle} />
|
||||
<ProfileModal isOpen={isOpen} closeModal={close} />
|
||||
<ProfileModal isOpen={isOpen} closeModal={close} isCustomer={props.isCustomer} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
@ -1,17 +1,16 @@
|
||||
import LogoIcon from "@Assets/logo_standard_neutral.svg";
|
||||
import Stripe from "@Front/Api/LeCoffreApi/Admin/Stripe/Stripe";
|
||||
import Subscriptions from "@Front/Api/LeCoffreApi/Admin/Subscriptions/Subscriptions";
|
||||
// import Stripe from "@Front/Api/LeCoffreApi/Admin/Stripe/Stripe";
|
||||
// import Subscriptions from "@Front/Api/LeCoffreApi/Admin/Subscriptions/Subscriptions";
|
||||
import Module from "@Front/Config/Module";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import { InformationCircleIcon, LifebuoyIcon } from "@heroicons/react/24/outline";
|
||||
// import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import { LifebuoyIcon } from "@heroicons/react/24/outline";
|
||||
import Head from "next/head";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import React, { useCallback, useEffect } from "react";
|
||||
|
||||
import IconButton from "../IconButton";
|
||||
import Typography, { ETypo, ETypoColor } from "../Typography";
|
||||
import BurgerMenu from "./BurgerMenu";
|
||||
import classes from "./classes.module.scss";
|
||||
import LogoCielNatureIcon from "./logo-ciel-notaires.jpeg";
|
||||
@ -21,20 +20,22 @@ import Profile from "./Profile";
|
||||
|
||||
type IProps = {
|
||||
isUserConnected: boolean;
|
||||
isCustomer?: boolean;
|
||||
};
|
||||
|
||||
const headerHeight = 75;
|
||||
|
||||
export default function Header(props: IProps) {
|
||||
const { isUserConnected } = props;
|
||||
const { isUserConnected, isCustomer } = props;
|
||||
|
||||
const router = useRouter();
|
||||
const { pathname } = router;
|
||||
const isOnCustomerLoginPage = Module.getInstance().get().modules.pages.CustomersLogin.props.path === pathname;
|
||||
|
||||
const [cancelAt, setCancelAt] = useState<Date | null>(null);
|
||||
// const [cancelAt, setCancelAt] = useState<Date | null>(null);
|
||||
|
||||
const loadSubscription = useCallback(async () => {
|
||||
/* TODO: review
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
const subscription = await Subscriptions.getInstance().get({ where: { office: { uid: jwt?.office_Id } } });
|
||||
if (subscription[0]) {
|
||||
@ -43,6 +44,7 @@ export default function Header(props: IProps) {
|
||||
setCancelAt(new Date(stripeSubscription.cancel_at! * 1000));
|
||||
}
|
||||
}
|
||||
*/
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@ -61,7 +63,7 @@ export default function Header(props: IProps) {
|
||||
<Image src={LogoIcon} alt="logo" className={classes["logo"]} />
|
||||
</Link>
|
||||
</div>
|
||||
{isUserConnected && (
|
||||
{isUserConnected && !isCustomer && (
|
||||
<>
|
||||
<div className={classes["desktop"]}>
|
||||
<Navigation />
|
||||
@ -82,9 +84,14 @@ export default function Header(props: IProps) {
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{isCustomer && (
|
||||
<div className={classes["desktop"]}>
|
||||
<Profile isCustomer={isCustomer} />
|
||||
</div>
|
||||
)}
|
||||
{isOnCustomerLoginPage && <Image width={70} height={70} alt="ciel-nature" src={LogoCielNatureIcon}></Image>}
|
||||
</div>
|
||||
{cancelAt && (
|
||||
{/* {cancelAt && (
|
||||
<div className={classes["subscription-line"]}>
|
||||
<InformationCircleIcon height="24" />
|
||||
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_GENERIC_BLACK}>
|
||||
@ -92,7 +99,7 @@ export default function Header(props: IProps) {
|
||||
{cancelAt.toLocaleDateString()}.
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
)} */}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
@ -6,14 +6,19 @@ import React, { useCallback } from "react";
|
||||
|
||||
import MenuItem from "../Menu/MenuItem";
|
||||
|
||||
export default function LogOut() {
|
||||
export default function LogOut(props: { isCustomer?: boolean }) {
|
||||
const router = useRouter();
|
||||
const variables = FrontendVariables.getInstance();
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
if (!props.isCustomer) {
|
||||
UserStore.instance
|
||||
.disconnect()
|
||||
.then(() => router.push(`https://qual-connexion.idnot.fr/user/auth/logout?sourceURL=${variables.FRONT_APP_HOST}`));
|
||||
} else {
|
||||
sessionStorage.setItem("customerIsConnected", "false");
|
||||
router.push("/");
|
||||
}
|
||||
}, [router, variables.FRONT_APP_HOST]);
|
||||
|
||||
return <MenuItem item={{ text: "Déconnexion", icon: <PowerIcon />, onClick: disconnect }} />;
|
||||
|
@ -20,7 +20,7 @@ export default function Rules(props: IProps) {
|
||||
const router = useRouter();
|
||||
|
||||
const [isShowing, setIsShowing] = React.useState(false);
|
||||
const [hasJwt, setHasJwt] = React.useState(false);
|
||||
// const [hasJwt, setHasJwt] = React.useState(false);
|
||||
|
||||
const getShowValue = useCallback(() => {
|
||||
if (props.mode === RulesMode.NECESSARY) {
|
||||
@ -30,8 +30,9 @@ export default function Rules(props: IProps) {
|
||||
}, [props.mode, props.rules]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!JwtService.getInstance().decodeJwt()) return;
|
||||
setHasJwt(true);
|
||||
// TODO: review
|
||||
//if (!JwtService.getInstance().decodeJwt()) return;
|
||||
// setHasJwt(true);
|
||||
setIsShowing(getShowValue());
|
||||
}, [getShowValue, isShowing]);
|
||||
|
||||
@ -40,7 +41,8 @@ export default function Rules(props: IProps) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!hasJwt || !isShowing) return null;
|
||||
// TODO: review
|
||||
//if (!hasJwt || !isShowing) return null;
|
||||
|
||||
return props.children;
|
||||
}
|
||||
|
@ -57,6 +57,13 @@ export default function Tabs<T>({ onSelect, tabs: propsTabs }: IProps<T>) {
|
||||
|
||||
useEffect(() => {
|
||||
tabs.current = propsTabs;
|
||||
|
||||
if (tabs.current && tabs.current.length > 0 && tabs.current[0]) {
|
||||
setSelectedTab(tabs.current[0].value);
|
||||
onSelect(tabs.current[0].value);
|
||||
|
||||
setTimeout(() => calculateVisibleElements(), 100);
|
||||
}
|
||||
}, [propsTabs]);
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -2,11 +2,12 @@ import React, { useEffect } from "react";
|
||||
|
||||
import { useRouter } from "next/router";
|
||||
import Module from "@Front/Config/Module";
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
import User from "le-coffre-resources/dist/Notary";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import Users, { IGetUsersparams } from "@Front/Api/LeCoffreApi/Admin/Users/Users";
|
||||
|
||||
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService";
|
||||
|
||||
type IProps = IPropsDashboardWithList;
|
||||
|
||||
@ -15,6 +16,7 @@ export default function DefaultCollaboratorDashboard(props: IProps) {
|
||||
const router = useRouter();
|
||||
const { collaboratorUid } = router.query;
|
||||
useEffect(() => {
|
||||
/* TODO: review
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
if (!jwt) return;
|
||||
const query: IGetUsersparams = {
|
||||
@ -28,10 +30,24 @@ export default function DefaultCollaboratorDashboard(props: IProps) {
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Users.getInstance()
|
||||
.get(query)
|
||||
.then((users) => setCollaborators(users));
|
||||
*/
|
||||
|
||||
const user: any = UserStore.instance.getUser();
|
||||
const officeId: string = user.office.uid;
|
||||
|
||||
CollaboratorService.getCollaborators().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let collaborators: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy office.uid
|
||||
collaborators = collaborators.filter((collaborator: any) => collaborator.office.uid === officeId);
|
||||
|
||||
setCollaborators(collaborators);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
|
@ -1,4 +1,3 @@
|
||||
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import Module from "@Front/Config/Module";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
@ -8,17 +7,22 @@ import React, { useEffect, useState } from "react";
|
||||
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
|
||||
type IProps = IPropsDashboardWithList & {};
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
type IProps = IPropsDashboardWithList & {
|
||||
isReady: boolean;
|
||||
};
|
||||
|
||||
export default function DefaultCustomerDashboard(props: IProps) {
|
||||
const router = useRouter();
|
||||
const { folderUid } = router.query;
|
||||
const { folderUid, profileUid } = router.query;
|
||||
const [folders, setFolders] = useState<OfficeFolder[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const jwt = JwtService.getInstance().decodeCustomerJwt();
|
||||
if (!jwt) return;
|
||||
|
||||
/*
|
||||
Folders.getInstance()
|
||||
.get({
|
||||
q: {
|
||||
@ -42,7 +46,21 @@ export default function DefaultCustomerDashboard(props: IProps) {
|
||||
},
|
||||
})
|
||||
.then((folders) => setFolders(folders));
|
||||
}, []);
|
||||
*/
|
||||
|
||||
if (props.isReady) {
|
||||
FolderService.getFolders().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let folders: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// Filter By customer.uid
|
||||
folders = folders.filter((folder: any) => folder.customers.some((customer: any) => customer.uid === profileUid));
|
||||
|
||||
setFolders(folders);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [props.isReady]);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
const folder = folders.find((folder) => folder.uid === block.id);
|
||||
@ -50,10 +68,12 @@ export default function DefaultCustomerDashboard(props: IProps) {
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.ClientDashboard.props.path.replace("[folderUid]", folder.uid ?? ""),
|
||||
.modules.pages.ClientDashboard.props.path
|
||||
.replace("[folderUid]", folder.uid ?? "")
|
||||
.replace("[profileUid]", profileUid as string ?? ""),
|
||||
);
|
||||
};
|
||||
return <DefaultDashboardWithList {...props} onSelectedBlock={onSelectedBlock} blocks={getBlocks(folders)} headerConnected={false}/>;
|
||||
return <DefaultDashboardWithList {...props} onSelectedBlock={onSelectedBlock} blocks={getBlocks(folders)} headerConnected={false} isCustomer={true} />;
|
||||
|
||||
function getBlocks(folders: OfficeFolder[]): IBlock[] {
|
||||
return folders.map((folder) => {
|
||||
|
@ -15,6 +15,7 @@ export type IPropsDashboardWithList = {
|
||||
mobileBackText?: string;
|
||||
headerConnected?: boolean;
|
||||
noPadding?: boolean;
|
||||
isCustomer?: boolean;
|
||||
};
|
||||
|
||||
type IProps = IPropsDashboardWithList & ISearchBlockListProps;
|
||||
@ -29,11 +30,12 @@ export default function DefaultDashboardWithList(props: IProps) {
|
||||
headerConnected = true,
|
||||
bottomButton,
|
||||
noPadding = false,
|
||||
isCustomer = false,
|
||||
} = props;
|
||||
|
||||
return (
|
||||
<div className={classes["root"]}>
|
||||
<Header isUserConnected={headerConnected} />
|
||||
<Header isUserConnected={headerConnected} isCustomer={isCustomer} />
|
||||
<div className={classes["content"]}>
|
||||
<SearchBlockList blocks={blocks} onSelectedBlock={onSelectedBlock} bottomButton={bottomButton} />
|
||||
<div className={classes["right-side"]} data-no-padding={noPadding}>
|
||||
|
@ -5,7 +5,8 @@ import Module from "@Front/Config/Module";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
import { DeedType } from "le-coffre-resources/dist/Notary";
|
||||
import DeedTypes, { IGetDeedTypesParams } from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
|
||||
|
||||
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||
|
||||
type IProps = IPropsDashboardWithList;
|
||||
|
||||
@ -13,19 +14,19 @@ export default function DefaultDeedTypeDashboard(props: IProps) {
|
||||
const [deedTypes, setDeedTypes] = React.useState<DeedType[] | null>(null);
|
||||
const router = useRouter();
|
||||
const { deedTypeUid } = router.query;
|
||||
useEffect(() => {
|
||||
const query: IGetDeedTypesParams = {
|
||||
where: {
|
||||
archived_at: null,
|
||||
},
|
||||
orderBy: {
|
||||
name: "asc",
|
||||
},
|
||||
};
|
||||
|
||||
DeedTypes.getInstance()
|
||||
.get(query)
|
||||
.then((deedTypes) => setDeedTypes(deedTypes));
|
||||
useEffect(() => {
|
||||
DeedTypeService.getDeedTypes().then((processes: any) => {
|
||||
let deedTypes = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy archived_at = null or not defined
|
||||
deedTypes = deedTypes.filter((deedType: any) => !deedType.archived_at);
|
||||
|
||||
// OrderBy name asc
|
||||
deedTypes.sort((a: any, b: any) => a.name.localeCompare(b.name));
|
||||
|
||||
setDeedTypes(deedTypes);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
|
@ -1,13 +1,14 @@
|
||||
import React, { useEffect } from "react";
|
||||
|
||||
import { useRouter } from "next/router";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
||||
import { DocumentType } from "le-coffre-resources/dist/Notary";
|
||||
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
|
||||
type IProps = IPropsDashboardWithList;
|
||||
|
||||
export default function DefaultDocumentTypeDashboard(props: IProps) {
|
||||
@ -15,18 +16,22 @@ export default function DefaultDocumentTypeDashboard(props: IProps) {
|
||||
const router = useRouter();
|
||||
const { documentTypeUid } = router.query;
|
||||
useEffect(() => {
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
if (!jwt) return;
|
||||
DocumentTypes.getInstance()
|
||||
.get({
|
||||
where: {
|
||||
office_uid: jwt.office_Id,
|
||||
},
|
||||
orderBy: {
|
||||
name: "asc",
|
||||
},
|
||||
})
|
||||
.then((documentTypes) => setDocumentTypes(documentTypes));
|
||||
const user: any = UserStore.instance.getUser();
|
||||
const officeId: string = user.office.uid;
|
||||
|
||||
DocumentTypeService.getDocumentTypes().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy office.uid
|
||||
documents = documents.filter((document: any) => document.office.uid === officeId);
|
||||
|
||||
// OrderBy name asc
|
||||
documents = documents.sort((a: any, b: any) => a.name.localeCompare(b.name));
|
||||
|
||||
setDocumentTypes(documents);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
|
@ -1,4 +1,3 @@
|
||||
import Folders, { IGetFoldersParams } from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import EFolderStatus from "le-coffre-resources/dist/Customer/EFolderStatus";
|
||||
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import React, { useCallback, useEffect } from "react";
|
||||
@ -9,6 +8,8 @@ import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList
|
||||
import { useRouter } from "next/router";
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
type IProps = IPropsDashboardWithList & {
|
||||
isArchived?: boolean;
|
||||
};
|
||||
@ -76,6 +77,8 @@ export default function DefaultNotaryDashboard(props: IProps) {
|
||||
useEffect(() => {
|
||||
let targetedStatus: EFolderStatus = EFolderStatus["LIVE" as keyof typeof EFolderStatus];
|
||||
if (isArchived) targetedStatus = EFolderStatus.ARCHIVED;
|
||||
|
||||
/* TODO: review
|
||||
const query: IGetFoldersParams = {
|
||||
q: {
|
||||
where: { status: targetedStatus },
|
||||
@ -110,6 +113,18 @@ export default function DefaultNotaryDashboard(props: IProps) {
|
||||
Folders.getInstance()
|
||||
.get(query)
|
||||
.then((folders) => setFolders(folders));
|
||||
*/
|
||||
|
||||
FolderService.getFolders().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let folders: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy status
|
||||
folders = folders.filter((folder: any) => folder.status === targetedStatus);
|
||||
|
||||
setFolders(folders);
|
||||
}
|
||||
});
|
||||
}, [isArchived]);
|
||||
|
||||
return (
|
||||
|
@ -5,7 +5,7 @@ import { useRouter } from "next/router";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
import Offices from "@Front/Api/LeCoffreApi/SuperAdmin/Offices/Offices";
|
||||
// import Offices from "@Front/Api/LeCoffreApi/SuperAdmin/Offices/Offices";
|
||||
|
||||
type IProps = IPropsDashboardWithList;
|
||||
|
||||
@ -14,9 +14,12 @@ export default function DefaultOfficeDashboard(props: IProps) {
|
||||
const router = useRouter();
|
||||
const { officeUid } = router.query;
|
||||
useEffect(() => {
|
||||
/* TODO: review
|
||||
Offices.getInstance()
|
||||
.get()
|
||||
.then((offices) => setOffices(offices));
|
||||
*/
|
||||
setOffices([]);
|
||||
}, []);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
|
@ -4,16 +4,19 @@ import { useRouter } from "next/router";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import DefaultDashboardWithList, { IPropsDashboardWithList } from "../DefaultDashboardWithList";
|
||||
import { OfficeRole } from "le-coffre-resources/dist/Notary";
|
||||
import OfficeRoles, { IGetRolesParams } from "@Front/Api/LeCoffreApi/Admin/OfficeRoles/OfficeRoles";
|
||||
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
|
||||
|
||||
type IProps = IPropsDashboardWithList;
|
||||
|
||||
export default function DefaultRoleDashboard(props: IProps) {
|
||||
const [roles, setRoles] = React.useState<OfficeRole[] | null>(null);
|
||||
const [roles, setRoles] = React.useState<any[] | null>(null);
|
||||
const router = useRouter();
|
||||
const { roleUid } = router.query;
|
||||
useEffect(() => {
|
||||
/* TODO: review
|
||||
const query: IGetRolesParams = {
|
||||
include: { rules: true },
|
||||
};
|
||||
@ -21,6 +24,102 @@ export default function DefaultRoleDashboard(props: IProps) {
|
||||
OfficeRoles.getInstance()
|
||||
.get(query)
|
||||
.then((roles) => setRoles(roles));
|
||||
*/
|
||||
|
||||
const roles: any[] = [
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: 'Notaire',
|
||||
office: {
|
||||
name: '',
|
||||
crpcen: '',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
rules: [
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: "Gestion de l'abonnement",
|
||||
label: "Gestion de l'abonnement",
|
||||
namespace: "Gestion de l'abonnement",
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: "Gestion des matrices d'actes et des documents",
|
||||
label: "Gestion des matrices d'actes et des documents",
|
||||
namespace: "Gestion des matrices d'actes et des documents",
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: "Intégration du RIB",
|
||||
label: "Intégration du RIB",
|
||||
namespace: "Intégration du RIB",
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
}
|
||||
],
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
},
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: 'Collaborateur',
|
||||
office: {
|
||||
name: '',
|
||||
crpcen: '',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
rules: [
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: "Gestion de l'abonnement",
|
||||
label: "Gestion de l'abonnement",
|
||||
namespace: "Gestion de l'abonnement",
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: "Gestion des matrices d'actes et des documents",
|
||||
label: "Gestion des matrices d'actes et des documents",
|
||||
namespace: "Gestion des matrices d'actes et des documents",
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
},
|
||||
{
|
||||
uid: uuidv4(),
|
||||
name: "Intégration du RIB",
|
||||
label: "Intégration du RIB",
|
||||
namespace: "Intégration du RIB",
|
||||
created_at: new Date(),
|
||||
updated_at: new Date()
|
||||
}
|
||||
],
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}
|
||||
];
|
||||
|
||||
RoleService.getRoles().then(async (processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
const roles: any[] = processes.map((process: any) => process.processData);
|
||||
setRoles(roles);
|
||||
} else {
|
||||
/*
|
||||
for (let role of roles) {
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
await RoleService.createRole(role, validatorId);
|
||||
}
|
||||
setRoles(roles);
|
||||
*/
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
@ -35,7 +134,7 @@ export default function DefaultRoleDashboard(props: IProps) {
|
||||
roles
|
||||
? roles.map((role) => ({
|
||||
id: role.uid!,
|
||||
primaryText: role.name,
|
||||
primaryText: role.label,
|
||||
isActive: role.uid === roleUid,
|
||||
}))
|
||||
: []
|
||||
|
@ -1,4 +1,4 @@
|
||||
import Users, { IGetUsersparams } from "@Front/Api/LeCoffreApi/SuperAdmin/Users/Users";
|
||||
// import Users, { IGetUsersparams } from "@Front/Api/LeCoffreApi/SuperAdmin/Users/Users";
|
||||
import User from "le-coffre-resources/dist/SuperAdmin";
|
||||
import React, { useEffect } from "react";
|
||||
|
||||
@ -14,13 +14,15 @@ export default function DefaultUserDashboard(props: IProps) {
|
||||
const router = useRouter();
|
||||
const { userUid } = router.query;
|
||||
useEffect(() => {
|
||||
/* TODO: review
|
||||
const query: IGetUsersparams = {
|
||||
include: { contact: true, office_membership: true },
|
||||
};
|
||||
|
||||
Users.getInstance()
|
||||
.get(query)
|
||||
.then((users) => setUsers(users));
|
||||
*/
|
||||
setUsers([]);
|
||||
}, []);
|
||||
|
||||
const onSelectedBlock = (block: IBlock) => {
|
||||
|
@ -3,10 +3,10 @@ import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Ty
|
||||
import { ArrowDownTrayIcon } from "@heroicons/react/24/outline";
|
||||
import Customer from "le-coffre-resources/dist/Customer";
|
||||
import { OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Notary";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
import OfficeRib from "@Front/Api/LeCoffreApi/Customer/OfficeRib/OfficeRib";
|
||||
// import OfficeRib from "@Front/Api/LeCoffreApi/Customer/OfficeRib/OfficeRib";
|
||||
|
||||
type IProps = {
|
||||
folder: OfficeFolderNotary;
|
||||
@ -16,12 +16,23 @@ type IProps = {
|
||||
export default function ContactBox(props: IProps) {
|
||||
const { folder, customer } = props;
|
||||
|
||||
const [ribUrl, setRibUrl] = useState<string | null>(null);
|
||||
// const [ribUrl, setRibUrl] = useState<string | null>(null);
|
||||
const ribUrl = null;
|
||||
|
||||
// TODO: review
|
||||
const stakeholder = {
|
||||
cell_phone_number: "0606060606",
|
||||
phone_number: "0606060606",
|
||||
email: "test@lecoffre.fr",
|
||||
};
|
||||
|
||||
const notaryContact = useMemo(
|
||||
() =>
|
||||
folder?.stakeholders!.find((stakeholder) => stakeholder.office_role?.name === "Notaire")?.contact ??
|
||||
folder?.stakeholders![0]!.contact,
|
||||
/*folder?.stakeholders!.find((stakeholder) => stakeholder.office_role?.name === "Notaire")?.contact ??
|
||||
folder?.stakeholders![0]!.contact*/
|
||||
|
||||
// TODO: review
|
||||
stakeholder,
|
||||
[folder],
|
||||
);
|
||||
|
||||
@ -37,9 +48,11 @@ export default function ContactBox(props: IProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!folder?.office?.uid) return;
|
||||
/* TODO: review
|
||||
OfficeRib.getInstance()
|
||||
.getRibStream(folder.office.uid)
|
||||
.then((blob) => setRibUrl(URL.createObjectURL(blob)));
|
||||
*/
|
||||
}, [folder]);
|
||||
|
||||
const downloadRib = useCallback(async () => {
|
||||
|
@ -1,52 +1,174 @@
|
||||
import DragAndDrop, { IDocumentFileWithUid } from "@Front/Components/DesignSystem/DragAndDrop";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import { Document } from "le-coffre-resources/dist/Customer";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
import Files from "@Front/Api/LeCoffreApi/Customer/Files/Files";
|
||||
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
|
||||
import { FileBlob, FileData } from "@Front/Api/Entities/types";
|
||||
import WatermarkService from "@Front/Services/WatermarkService";
|
||||
|
||||
type IProps = {
|
||||
document: Document;
|
||||
document: any;
|
||||
customer: any;
|
||||
onChange: () => void;
|
||||
};
|
||||
|
||||
export default function DepositDocumentComponent(props: IProps) {
|
||||
const { document, onChange } = props;
|
||||
const { document, customer, onChange } = props;
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [refused_reason, setRefusedReason] = useState<string | null>(null);
|
||||
|
||||
const defaultFiles: IDocumentFileWithUid[] = useMemo(() => {
|
||||
const filesNotArchived = document.files?.filter((file) => !file.archived_at) ?? [];
|
||||
return filesNotArchived.map((file) => ({
|
||||
const filesNotArchived = document.files?.filter((file: any) => !file.archived_at) ?? [];
|
||||
return filesNotArchived.map((file: any) => ({
|
||||
id: file.uid!,
|
||||
file: new File([""], file.file_name!, { type: file.mimetype }),
|
||||
file: new File([""], file.file_name!, { type: file.file_blob.type }),
|
||||
uid: file.uid!,
|
||||
}));
|
||||
}, [document.files]);
|
||||
|
||||
const addFile = useCallback(
|
||||
(file: File) => {
|
||||
const formData = new FormData();
|
||||
const safeFileName = file.name.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||||
formData.append("file", file, safeFileName);
|
||||
const query = JSON.stringify({ document: { uid: document.uid } });
|
||||
formData.append("q", query);
|
||||
return Files.getInstance()
|
||||
.post(formData)
|
||||
async (file: File) => {
|
||||
try {
|
||||
// Add watermark to the file before processing
|
||||
const watermarkedFile = await WatermarkService.getInstance().addWatermark(file);
|
||||
|
||||
return new Promise<void>(
|
||||
(resolve: () => void) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
if (event.target?.result) {
|
||||
const date: Date = new Date();
|
||||
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;
|
||||
|
||||
const fileName: string = `${document.document_type.name}-${customer.contact.last_name}-${strDate}.${file.name.split('.').pop()}`;
|
||||
|
||||
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
|
||||
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
const fileBlob: FileBlob = {
|
||||
type: watermarkedFile.type,
|
||||
data: uint8Array
|
||||
};
|
||||
|
||||
const fileData: FileData = {
|
||||
file_blob: fileBlob,
|
||||
file_name: fileName
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||
const fileUid: string = processCreated.processData.uid;
|
||||
|
||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
FolderService.invalidateCache(document.folder.uid);
|
||||
|
||||
let files: any[] = document.files;
|
||||
if (!files) {
|
||||
files = [];
|
||||
}
|
||||
files.push({ uid: fileUid });
|
||||
|
||||
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(watermarkedFile);
|
||||
})
|
||||
.then(onChange)
|
||||
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
|
||||
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
|
||||
} catch (error) {
|
||||
console.error('Error processing file with watermark:', error);
|
||||
// If watermarking fails, proceed with original file
|
||||
return new Promise<void>(
|
||||
(resolve: () => void) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
if (event.target?.result) {
|
||||
const date: Date = new Date();
|
||||
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;
|
||||
|
||||
const fileName: string = `${document.document_type.name}-${customer.contact.last_name}-${strDate}.${file.name.split('.').pop()}`;
|
||||
|
||||
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
|
||||
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
const fileBlob: FileBlob = {
|
||||
type: file.type,
|
||||
data: uint8Array
|
||||
};
|
||||
|
||||
const fileData: FileData = {
|
||||
file_blob: fileBlob,
|
||||
file_name: fileName
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||
const fileUid: string = processCreated.processData.uid;
|
||||
|
||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
|
||||
let files: any[] = document.files;
|
||||
if (!files) {
|
||||
files = [];
|
||||
}
|
||||
files.push({ uid: fileUid });
|
||||
|
||||
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.DEPOSITED }).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(file);
|
||||
})
|
||||
.then(onChange)
|
||||
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier uploadé avec succès!" }))
|
||||
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
|
||||
}
|
||||
},
|
||||
[document.uid, onChange],
|
||||
);
|
||||
|
||||
const deleteFile = useCallback(
|
||||
(filedUid: string) => {
|
||||
return Files.getInstance()
|
||||
.delete(filedUid)
|
||||
(fileUid: string) => {
|
||||
return new Promise<void>(
|
||||
(resolve: () => void) => {
|
||||
FileService.getFileByUid(fileUid).then((res: any) => {
|
||||
if (res) {
|
||||
FileService.updateFile(res.processId, { isDeleted: 'true' }).then(() => {
|
||||
DocumentService.getDocumentByUid(document.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
|
||||
let files: any[] = document.files;
|
||||
if (!files) {
|
||||
files = [];
|
||||
}
|
||||
files = files.filter((file: any) => file.uid !== fileUid);
|
||||
|
||||
DocumentService.updateDocument(process, { files: files, document_status: EDocumentStatus.ASKED }).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
.then(onChange)
|
||||
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Fichier supprimé avec succès!" }))
|
||||
.catch((error) => ToasterService.getInstance().error({ title: "Erreur !", description: error.message }));
|
||||
@ -55,7 +177,8 @@ export default function DepositDocumentComponent(props: IProps) {
|
||||
);
|
||||
|
||||
const onOpenModal = useCallback(async () => {
|
||||
const refused_reason = document.document_history?.find((history) => history.document_status === "REFUSED")?.refused_reason;
|
||||
if (document.document_status !== "REFUSED") return;
|
||||
const refused_reason = document.refused_reason;
|
||||
if (!refused_reason) return;
|
||||
setRefusedReason(refused_reason);
|
||||
setIsModalOpen(true);
|
||||
|
@ -1,5 +1,3 @@
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
|
||||
import FilesNotary from "@Front/Api/LeCoffreApi/Customer/FilesNotary/Files";
|
||||
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import IconButton from "@Front/Components/DesignSystem/IconButton";
|
||||
import Table from "@Front/Components/DesignSystem/Table";
|
||||
@ -8,7 +6,7 @@ import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Ty
|
||||
import BackArrow from "@Front/Components/Elements/BackArrow";
|
||||
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
|
||||
import Module from "@Front/Config/Module";
|
||||
import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService";
|
||||
// import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService";
|
||||
import { ArrowDownTrayIcon, EyeIcon } from "@heroicons/react/24/outline";
|
||||
import { saveAs } from "file-saver";
|
||||
import JSZip from "jszip";
|
||||
@ -16,10 +14,14 @@ import { useRouter } from "next/router";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import classes from "./classes.module.scss";
|
||||
import Link from "next/link";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
|
||||
import Customer from "le-coffre-resources/dist/Customer";
|
||||
import { DocumentNotary } from "le-coffre-resources/dist/Notary";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
const header: readonly IHead[] = [
|
||||
{
|
||||
key: "name",
|
||||
@ -42,11 +44,31 @@ export default function ReceivedDocuments() {
|
||||
const [customer, setCustomer] = useState<Customer | null>(null);
|
||||
|
||||
const fetchFolderAndCustomer = useCallback(async () => {
|
||||
let jwt: ICustomerJwtPayload | undefined;
|
||||
if (typeof document !== "undefined") {
|
||||
jwt = JwtService.getInstance().decodeCustomerJwt();
|
||||
}
|
||||
// let jwt: ICustomerJwtPayload | undefined;
|
||||
// if (typeof document !== "undefined") {
|
||||
// jwt = JwtService.getInstance().decodeCustomerJwt();
|
||||
// }
|
||||
|
||||
// TODO: review
|
||||
LoaderService.getInstance().show();
|
||||
const folder: any = await new Promise<any>((resolve: (folder: any) => void) => {
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
resolve(folder);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
//const customer = folder?.customers?.find((customer) => customer.contact?.email === jwt?.email);
|
||||
const customer = folder?.customers?.[0];
|
||||
if (!customer) throw new Error("Customer not found");
|
||||
|
||||
setCustomer(customer);
|
||||
|
||||
return { folder, customer };
|
||||
|
||||
/*
|
||||
const folder = await Folders.getInstance().getByUid(folderUid as string, {
|
||||
q: {
|
||||
office: true,
|
||||
@ -76,32 +98,58 @@ export default function ReceivedDocuments() {
|
||||
setCustomer(customer);
|
||||
|
||||
return { folder, customer };
|
||||
*/
|
||||
}, [folderUid]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchFolderAndCustomer();
|
||||
}, [folderUid]); // Ne dépend que de folderUid
|
||||
|
||||
// Effet séparé pour charger les documents lorsque customer change
|
||||
useEffect(() => {
|
||||
const customerUid = customer?.uid;
|
||||
if (!folderUid || !customerUid) return;
|
||||
DocumentsNotary.getInstance()
|
||||
.get({ where: { folder: { uid: folderUid }, customer: { uid: customerUid } }, include: { files: true } })
|
||||
.then((documentsNotary) => setDocumentsNotary(documentsNotary));
|
||||
}, [folderUid, customer, fetchFolderAndCustomer]);
|
||||
|
||||
const onDownload = useCallback((doc: DocumentNotary) => {
|
||||
DocumentService.getDocuments().then(async (processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy folder.uid & customer.uid
|
||||
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.customer /*&& document.customer.uid === customerUid*/);
|
||||
|
||||
for (const document of documents) {
|
||||
if (document.files && document.files.length > 0) {
|
||||
const files: any[] = [];
|
||||
for (const file of document.files) {
|
||||
files.push((await FileService.getFileByUid(file.uid)).processData);
|
||||
}
|
||||
document.files = files;
|
||||
}
|
||||
}
|
||||
|
||||
setDocumentsNotary(documents);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
}, [folderUid, customer]);
|
||||
|
||||
const onDownload = useCallback((doc: any) => {
|
||||
const file = doc.files?.[0];
|
||||
if (!file || !file?.uid || !doc.uid) return;
|
||||
if (!file) return;
|
||||
|
||||
return FilesNotary.getInstance()
|
||||
.download(file.uid, doc.uid)
|
||||
.then((blob) => {
|
||||
return new Promise<void>((resolve: () => void) => {
|
||||
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = file.file_name ?? "file";
|
||||
a.download = file.file_name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch((e) => console.warn(e));
|
||||
|
||||
resolve();
|
||||
}).catch((e) => console.warn(e));
|
||||
}, []);
|
||||
|
||||
const onDownloadAll = useCallback(async () => {
|
||||
@ -110,16 +158,14 @@ export default function ReceivedDocuments() {
|
||||
const zip = new JSZip();
|
||||
const folder = zip.folder("documents") || zip;
|
||||
|
||||
const downloadPromises = documentsNotary.map(async (doc) => {
|
||||
documentsNotary.map((doc: any) => {
|
||||
const file = doc.files?.[0];
|
||||
if (file && file.uid && doc.uid) {
|
||||
const blob = await FilesNotary.getInstance().download(file.uid, doc.uid);
|
||||
if (file) {
|
||||
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
|
||||
folder.file(file.file_name ?? "file", blob);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(downloadPromises);
|
||||
|
||||
zip.generateAsync({ type: "blob" })
|
||||
.then((blob: any) => {
|
||||
saveAs(blob, "documents.zip");
|
||||
@ -160,12 +206,9 @@ function buildRows(
|
||||
folderUid: string | string[],
|
||||
onDownloadFileNotary: (doc: DocumentNotary) => void,
|
||||
): IRowProps[] {
|
||||
console.log(documentsNotary);
|
||||
console.log(folderUid);
|
||||
|
||||
return documentsNotary.map((documentNotary) => ({
|
||||
key: documentNotary.uid ?? "",
|
||||
name: formatName(documentNotary.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_",
|
||||
name: documentNotary.files?.[0]?.file_name?.split(".")?.[0] || "_",
|
||||
sentAt: new Date(documentNotary.created_at!).toLocaleDateString(),
|
||||
// actions: <IconButton onClick={() => onDownloadFileNotary(documentNotary)} icon={<ArrowDownTrayIcon />} />,
|
||||
actions: {
|
||||
@ -185,7 +228,3 @@ function buildRows(
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
function formatName(text: string): string {
|
||||
return text.replace(/[^a-zA-Z0-9 ]/g, "");
|
||||
}
|
||||
|
@ -3,16 +3,20 @@ import RightArrowIcon from "@Assets/Icons/right-arrow.svg";
|
||||
import Button from "@Front/Components/DesignSystem/Button";
|
||||
import FilePreview from "@Front/Components/DesignSystem/FilePreview";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import { DocumentNotary, File } from "le-coffre-resources/dist/Notary";
|
||||
import { DocumentNotary } from "le-coffre-resources/dist/Notary";
|
||||
import Image from "next/image";
|
||||
import { NextRouter, useRouter } from "next/router";
|
||||
import React from "react";
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
|
||||
import BasePage from "../../Base";
|
||||
import classes from "./classes.module.scss";
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
|
||||
|
||||
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
|
||||
import FilesNotary from "@Front/Api/LeCoffreApi/Customer/FilesNotary/Files";
|
||||
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {};
|
||||
type IPropsClass = {
|
||||
@ -25,8 +29,8 @@ type IState = {
|
||||
isValidateModalVisible: boolean;
|
||||
refuseText: string;
|
||||
selectedFileIndex: number;
|
||||
selectedFile: File | null;
|
||||
documentNotary: DocumentNotary | null;
|
||||
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null;
|
||||
documentNotary: any | null;
|
||||
fileBlob: Blob | null;
|
||||
isLoading: boolean;
|
||||
};
|
||||
@ -71,10 +75,10 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
|
||||
</div>
|
||||
)}
|
||||
<div className={classes["file-container"]}>
|
||||
{this.state.selectedFile.mimetype === "application/pdf" ||
|
||||
this.state.selectedFile.mimetype === "image/jpeg" ||
|
||||
this.state.selectedFile.mimetype === "image/png" ||
|
||||
this.state.selectedFile.mimetype === "image/jpg" ? (
|
||||
{this.state.selectedFile.file_blob.type === "application/pdf" ||
|
||||
this.state.selectedFile.file_blob.type === "image/jpeg" ||
|
||||
this.state.selectedFile.file_blob.type === "image/png" ||
|
||||
this.state.selectedFile.file_blob.type === "image/jpg" ? (
|
||||
<FilePreview
|
||||
href={this.state.fileBlob ? URL.createObjectURL(this.state.fileBlob) : ""}
|
||||
fileName={this.state.selectedFile.file_name}
|
||||
@ -123,16 +127,31 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
override async componentDidMount() {
|
||||
try {
|
||||
const documentNotary = await DocumentsNotary.getInstance().getByUid(this.props.documentUid, {
|
||||
files: true,
|
||||
folder: true,
|
||||
depositor: true,
|
||||
LoaderService.getInstance().show();
|
||||
const documentNotary: any = await new Promise<any>((resolve: (document: any) => void) => {
|
||||
DocumentService.getDocumentByUid(this.props.documentUid).then(async (process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
|
||||
if (document.files && document.files.length > 0) {
|
||||
const files: any[] = [];
|
||||
for (const file of document.files) {
|
||||
files.push((await FileService.getFileByUid(file.uid)).processData);
|
||||
}
|
||||
document.files = files;
|
||||
}
|
||||
|
||||
resolve(document);
|
||||
}
|
||||
});
|
||||
});
|
||||
LoaderService.getInstance().hide();
|
||||
|
||||
this.setState(
|
||||
{
|
||||
documentNotary,
|
||||
selectedFileIndex: 0,
|
||||
selectedFile: documentNotary.files![0]!,
|
||||
selectedFile: documentNotary.files![0] as any,
|
||||
isLoading: false,
|
||||
},
|
||||
() => {
|
||||
@ -149,8 +168,7 @@ class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
private async getFilePreview(): Promise<void> {
|
||||
try {
|
||||
const fileBlob: Blob = await FilesNotary.getInstance().download(this.state.selectedFile?.uid as string, this.props.documentUid);
|
||||
|
||||
const fileBlob: Blob = new Blob([this.state.selectedFile!.file_blob.data], { type: this.state.selectedFile!.file_blob.type });
|
||||
this.setState({
|
||||
fileBlob,
|
||||
});
|
||||
|
@ -1,16 +1,14 @@
|
||||
"use client";
|
||||
import Documents, { IGetDocumentsparams } from "@Front/Api/LeCoffreApi/Customer/Documents/Documents";
|
||||
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
|
||||
import Customer, { Document, DocumentType } from "le-coffre-resources/dist/Customer";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { DocumentNotary, type OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Notary";
|
||||
import { DocumentNotary, OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Notary";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
import { useRouter } from "next/router";
|
||||
import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
|
||||
|
||||
import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag";
|
||||
import DefaultCustomerDashboard from "@Front/Components/LayoutTemplates/DefaultCustomerDashboard";
|
||||
@ -21,28 +19,91 @@ import Module from "@Front/Config/Module";
|
||||
import Separator, { ESeperatorColor, ESeperatorDirection } from "@Front/Components/DesignSystem/Separator";
|
||||
import NotificationBox from "@Front/Components/DesignSystem/NotificationBox";
|
||||
import ContactBox from "./ContactBox";
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
|
||||
import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
|
||||
import DepositOtherDocument from "@Front/Components/DesignSystem/DepositOtherDocument";
|
||||
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
|
||||
import AuthModal from "src/sdk/AuthModal";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {};
|
||||
|
||||
export default function ClientDashboard(props: IProps) {
|
||||
const router = useRouter();
|
||||
let { folderUid } = router.query;
|
||||
let { folderUid, profileUid } = router.query;
|
||||
const [documents, setDocuments] = useState<Document[] | null>(null);
|
||||
|
||||
const [customer, setCustomer] = useState<Customer | null>(null);
|
||||
const [folder, setFolder] = useState<OfficeFolderNotary | null>(null);
|
||||
|
||||
const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
|
||||
const [isAddDocumentModalVisible, setIsAddDocumentModalVisible] = useState<boolean>(false);
|
||||
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
|
||||
const [isSmsModalOpen, setIsSmsModalOpen] = useState(true);
|
||||
const [smsCode, setSmsCode] = useState("");
|
||||
const [smsError, setSmsError] = useState("");
|
||||
|
||||
const verifySmsCode = useCallback(() => {
|
||||
if (smsCode === "1234") {
|
||||
setIsSmsModalOpen(false);
|
||||
setIsAuthModalOpen(true);
|
||||
} else {
|
||||
setSmsError("Code incorrect. Le code valide est 1234.");
|
||||
}
|
||||
}, [smsCode]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyPress = (e: KeyboardEvent) => {
|
||||
if (e.key === "Enter" && isSmsModalOpen) {
|
||||
verifySmsCode();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keypress", handleKeyPress);
|
||||
return () => {
|
||||
window.removeEventListener("keypress", handleKeyPress);
|
||||
};
|
||||
}, [isSmsModalOpen, smsCode, verifySmsCode]);
|
||||
|
||||
const fetchFolderAndCustomer = useCallback(async () => {
|
||||
let jwt: ICustomerJwtPayload | undefined;
|
||||
if (typeof document !== "undefined") {
|
||||
jwt = JwtService.getInstance().decodeCustomerJwt();
|
||||
}
|
||||
|
||||
// TODO: review
|
||||
LoaderService.getInstance().show();
|
||||
const { folder, customer } = await new Promise<any>((resolve) => {
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
|
||||
const customers: any[] = folder.customers;
|
||||
const customer: any = customers.find((customer: any) => customer.uid === profileUid as string);
|
||||
if (customer) {
|
||||
resolve({ folder: folder, customer });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setCustomer(customer);
|
||||
setFolder(folder);
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
|
||||
return { folder, customer };
|
||||
|
||||
/*
|
||||
const folder = await Folders.getInstance().getByUid(folderUid as string, {
|
||||
q: {
|
||||
office: true,
|
||||
@ -73,46 +134,77 @@ export default function ClientDashboard(props: IProps) {
|
||||
setCustomer(customer);
|
||||
|
||||
return { folder, customer };
|
||||
*/
|
||||
}, [folderUid]);
|
||||
|
||||
const fetchDocuments = useCallback(
|
||||
(customerUid: string | undefined) => {
|
||||
const query: IGetDocumentsparams = {
|
||||
where: { depositor: { uid: customerUid }, folder_uid: folderUid as string },
|
||||
include: {
|
||||
files: true,
|
||||
document_history: true,
|
||||
document_type: true,
|
||||
depositor: true,
|
||||
folder: {
|
||||
include: {
|
||||
customers: {
|
||||
include: {
|
||||
contact: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
async (customerUid: string | undefined) => {
|
||||
setDocuments([]);
|
||||
LoaderService.getInstance().show();
|
||||
return new Promise<void>((resolve: () => void) => {
|
||||
DocumentService.getDocuments().then(async (processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
return Documents.getInstance()
|
||||
.get(query)
|
||||
.then((documents) => setDocuments(documents));
|
||||
// FilterBy folder.uid & depositor.uid
|
||||
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.depositor && document.depositor.uid === customerUid);
|
||||
|
||||
for (const document of documents) {
|
||||
if (document.document_type) {
|
||||
document.document_type = (await DocumentTypeService.getDocumentTypeByUid(document.document_type.uid)).processData;
|
||||
}
|
||||
|
||||
if (document.files && document.files.length > 0) {
|
||||
const files: any[] = [];
|
||||
for (const file of document.files) {
|
||||
files.push((await FileService.getFileByUid(file.uid)).processData);
|
||||
}
|
||||
document.files = files;
|
||||
}
|
||||
}
|
||||
|
||||
setDocuments(documents);
|
||||
}
|
||||
LoaderService.getInstance().hide();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
},
|
||||
[folderUid],
|
||||
);
|
||||
|
||||
/*
|
||||
useEffect(() => {
|
||||
fetchFolderAndCustomer().then(({ customer }) => fetchDocuments(customer.uid));
|
||||
}, [fetchDocuments, fetchFolderAndCustomer]);
|
||||
*/
|
||||
|
||||
useEffect(() => {
|
||||
setDocumentsNotary([]);
|
||||
const customerUid = customer?.uid;
|
||||
if (!folderUid || !customerUid) return;
|
||||
DocumentsNotary.getInstance()
|
||||
.get({ where: { folder: { uid: folderUid }, customer: { uid: customerUid } }, include: { files: true } })
|
||||
.then((documentsNotary) => setDocumentsNotary(documentsNotary));
|
||||
LoaderService.getInstance().show();
|
||||
DocumentService.getDocuments().then(async (processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy folder.uid & customer.uid
|
||||
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.customer && document.customer.uid === customerUid);
|
||||
|
||||
for (const document of documents) {
|
||||
if (document.files && document.files.length > 0) {
|
||||
const files: any[] = [];
|
||||
for (const file of document.files) {
|
||||
files.push((await FileService.getFileByUid(file.uid)).processData);
|
||||
}
|
||||
document.files = files;
|
||||
}
|
||||
}
|
||||
|
||||
setDocumentsNotary(documents);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
}, [folderUid, customer?.uid]);
|
||||
|
||||
const documentsNotaryNotRead = useMemo(
|
||||
@ -147,8 +239,8 @@ export default function ClientDashboard(props: IProps) {
|
||||
}, [customer, folderUid, isAddDocumentModalVisible, onCloseModalAddDocument, folder]);
|
||||
|
||||
return (
|
||||
<DefaultCustomerDashboard>
|
||||
<div className={classes["root"]}>
|
||||
<DefaultCustomerDashboard isReady={isReady}>
|
||||
{isReady && (<div className={classes["root"]}>
|
||||
<div className={classes["top"]}>
|
||||
<div className={classes["folder-info-container"]}>
|
||||
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_SECONDARY}>
|
||||
@ -227,6 +319,7 @@ export default function ClientDashboard(props: IProps) {
|
||||
<DepositDocumentComponent
|
||||
key={document.uid}
|
||||
document={document}
|
||||
customer={customer}
|
||||
onChange={() => fetchDocuments(customer?.uid)}
|
||||
/>
|
||||
))}
|
||||
@ -244,7 +337,61 @@ export default function ClientDashboard(props: IProps) {
|
||||
Ajouter d'autres documents
|
||||
</Button>
|
||||
{isAddDocumentModalVisible && renderBox()}
|
||||
</div>)}
|
||||
|
||||
{isAuthModalOpen && <AuthModal
|
||||
isOpen={isAuthModalOpen}
|
||||
onClose={() => {
|
||||
setIsReady(true);
|
||||
setIsAuthModalOpen(false);
|
||||
fetchFolderAndCustomer().then(({ customer }) => fetchDocuments(customer.uid));
|
||||
|
||||
sessionStorage.setItem("customerIsConnected", "true");
|
||||
}}
|
||||
/>}
|
||||
|
||||
{isSmsModalOpen && (
|
||||
<Modal
|
||||
isOpen={isSmsModalOpen}
|
||||
onClose={() => setIsSmsModalOpen(false)}
|
||||
title="Vérification SMS"
|
||||
>
|
||||
<div className={classes["sms-modal-content"]}>
|
||||
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_PRIMARY}>
|
||||
Veuillez saisir le code à 4 chiffres que vous avez reçu par SMS
|
||||
</Typography>
|
||||
|
||||
<TextField
|
||||
name="smsCode"
|
||||
placeholder="Code SMS à 4 chiffres"
|
||||
value={smsCode}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
// Only allow digits
|
||||
if (value === "" || /^\d+$/.test(value)) {
|
||||
setSmsCode(value);
|
||||
setSmsError("");
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{smsError && (
|
||||
<Typography typo={ETypo.TEXT_SM_REGULAR} color={ETypoColor.TEXT_ACCENT}>
|
||||
{smsError}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<div style={{ marginTop: "20px" }}>
|
||||
<Button
|
||||
variant={EButtonVariant.PRIMARY}
|
||||
onClick={verifySmsCode}
|
||||
>
|
||||
Vérifier
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</DefaultCustomerDashboard>
|
||||
);
|
||||
}
|
||||
|
@ -18,6 +18,9 @@ import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/Dr
|
||||
import { getLabel } from "@Front/Components/DesignSystem/Dropdown";
|
||||
import SelectField from "@Front/Components/DesignSystem/Form/SelectField";
|
||||
|
||||
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService";
|
||||
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
|
||||
|
||||
type IProps = {};
|
||||
export default function CollaboratorInformations(props: IProps) {
|
||||
const router = useRouter();
|
||||
@ -120,6 +123,30 @@ export default function CollaboratorInformations(props: IProps) {
|
||||
useEffect(() => {
|
||||
async function getUser() {
|
||||
if (!collaboratorUid) return;
|
||||
|
||||
CollaboratorService.getCollaboratorByUid(collaboratorUid as string).then(async (process: any) => {
|
||||
if (process) {
|
||||
const collaborator: any = process.processData;
|
||||
|
||||
const roles: any[] = await new Promise<any[]>((resolve: (roles: any[]) => void) => {
|
||||
RoleService.getRoles().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
const roles: any[] = processes.map((process: any) => process.processData);
|
||||
resolve(roles);
|
||||
}
|
||||
});
|
||||
});
|
||||
setAvailableRoles(roles.map((role) => ({ id: role.uid ?? "", label: role.label })));
|
||||
|
||||
setUserSelected(collaborator);
|
||||
setSelectedOption({
|
||||
id: (collaborator?.office_role ? collaborator?.office_role?.uid : collaborator?.role?.uid) ?? "",
|
||||
label: collaborator?.office_role ? collaborator?.office_role?.label : "Utilisateur restreint",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
const user = await Users.getInstance().getByUid(collaboratorUid as string, {
|
||||
q: {
|
||||
contact: true,
|
||||
@ -142,6 +169,7 @@ export default function CollaboratorInformations(props: IProps) {
|
||||
id: (user?.office_role ? user?.office_role?.uid : user?.role?.uid) ?? "",
|
||||
label: user?.office_role ? user?.office_role?.name : "Utilisateur restreint",
|
||||
});
|
||||
*/
|
||||
}
|
||||
|
||||
getUser();
|
||||
|
@ -1,4 +1,3 @@
|
||||
import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
@ -6,6 +5,7 @@ import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import DefaultDeedTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDeedTypeDashboard";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import Module from "@Front/Config/Module";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import { DeedType, Office } from "le-coffre-resources/dist/Admin";
|
||||
@ -15,6 +15,9 @@ import { useCallback, useState } from "react";
|
||||
import classes from "./classes.module.scss";
|
||||
import { validateOrReject, ValidationError } from "class-validator";
|
||||
|
||||
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {};
|
||||
export default function DeedTypesCreate(props: IProps) {
|
||||
const [hasChanged, setHasChanged] = useState<boolean>(false);
|
||||
@ -25,12 +28,14 @@ export default function DeedTypesCreate(props: IProps) {
|
||||
const onSubmitHandler = useCallback(
|
||||
async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
|
||||
try {
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
// TODO: review
|
||||
const officeId = 'demo_notary_office_id'; //JwtService.getInstance().decodeJwt()?.office_Id;
|
||||
|
||||
const deedType = DeedType.hydrate<DeedType>({
|
||||
name: values["name"],
|
||||
description: values["description"],
|
||||
office: Office.hydrate<Office>({
|
||||
uid: jwt?.office_Id,
|
||||
uid: officeId,
|
||||
}),
|
||||
});
|
||||
try {
|
||||
@ -40,21 +45,28 @@ export default function DeedTypesCreate(props: IProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deedTypeCreated = await DeedTypes.getInstance().post(
|
||||
DeedType.hydrate<DeedType>({
|
||||
const deedTypeData: any = {
|
||||
name: values["name"],
|
||||
description: values["description"],
|
||||
office: Office.hydrate<Office>({
|
||||
uid: jwt?.office_Id,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
office: {
|
||||
uid: officeId,
|
||||
}
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
DeedTypeService.createDeedType(deedTypeData, validatorId).then((processCreated: any) => {
|
||||
ToasterService.getInstance().success({
|
||||
title: "Succès !",
|
||||
description: "Type d'acte créé avec succès"
|
||||
});
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeCreated.uid!),
|
||||
.modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", processCreated.processData.uid),
|
||||
);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
} catch (validationErrors: Array<ValidationError> | any) {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
|
@ -14,6 +14,9 @@ import { ValidationError } from "class-validator";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
export default function DeedTypesEdit() {
|
||||
const router = useRouter();
|
||||
let { deedTypeUid } = router.query;
|
||||
@ -27,13 +30,15 @@ export default function DeedTypesEdit() {
|
||||
setHasChanged(false);
|
||||
async function getDeedType() {
|
||||
if (!deedTypeUid) return;
|
||||
const deedType = await DeedTypes.getInstance().getByUid(deedTypeUid as string, {
|
||||
q: {
|
||||
document_types: true,
|
||||
},
|
||||
});
|
||||
LoaderService.getInstance().show();
|
||||
DeedTypeService.getDeedTypeByUid(deedTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const deedType: any = process.processData;
|
||||
setDeedTypeSelected(deedType);
|
||||
}
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
|
||||
getDeedType();
|
||||
}, [deedTypeUid]);
|
||||
@ -57,19 +62,19 @@ export default function DeedTypesEdit() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await DeedTypes.getInstance().put(
|
||||
deedTypeUid as string,
|
||||
DeedType.hydrate<DeedType>({
|
||||
uid: deedTypeUid as string,
|
||||
name: values["name"],
|
||||
description: values["description"],
|
||||
}),
|
||||
);
|
||||
LoaderService.getInstance().show();
|
||||
DeedTypeService.getDeedTypeByUid(deedTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
DeedTypeService.updateDeedType(process, { name: values["name"], description: values["description"] }).then(() => {
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.DeedTypes.pages.DeedTypesInformations.props.path.replace("[uid]", deedTypeUid as string),
|
||||
);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (validationErrors) {
|
||||
if (!Array.isArray(validationErrors)) return;
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
|
@ -1,7 +1,5 @@
|
||||
import ChevronIcon from "@Assets/Icons/chevron.svg";
|
||||
import PenICon from "@Assets/Icons/pen.svg";
|
||||
import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
|
||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
@ -20,6 +18,10 @@ import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {};
|
||||
export default function DeedTypesInformations(props: IProps) {
|
||||
const router = useRouter();
|
||||
@ -49,42 +51,48 @@ export default function DeedTypesInformations(props: IProps) {
|
||||
}, []);
|
||||
|
||||
const deleteDeedType = useCallback(async () => {
|
||||
await DeedTypes.getInstance().put(
|
||||
deedTypeUid as string,
|
||||
DeedType.hydrate<DeedType>({
|
||||
uid: deedTypeUid as string,
|
||||
archived_at: new Date(),
|
||||
}),
|
||||
);
|
||||
LoaderService.getInstance().show();
|
||||
DeedTypeService.getDeedTypeByUid(deedTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
DeedTypeService.updateDeedType(process, { archived_at: new Date().toISOString() }).then(() => {
|
||||
router.push(Module.getInstance().get().modules.pages.DeedTypes.props.path);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [deedTypeUid, router]);
|
||||
|
||||
useEffect(() => {
|
||||
async function getDeedType() {
|
||||
if (!deedTypeUid) return;
|
||||
const deedType = await DeedTypes.getInstance().getByUid(deedTypeUid as string, {
|
||||
q: {
|
||||
document_types: true,
|
||||
},
|
||||
});
|
||||
|
||||
DeedTypeService.getDeedTypeByUid(deedTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const deedType: any = process.processData;
|
||||
setDeedTypeSelected(deedType);
|
||||
|
||||
if (!deedType.document_types) return;
|
||||
const documentsOptions: IOption[] = deedType.document_types
|
||||
?.map((documentType) => {
|
||||
?.map((documentType: any) => {
|
||||
return {
|
||||
label: documentType.name,
|
||||
id: documentType.uid ?? "",
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
.sort((a: any, b: any) => a.label.localeCompare(b.label));
|
||||
setSelectedDocuments(documentsOptions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function getDocuments() {
|
||||
const documents = await DocumentTypes.getInstance().get({});
|
||||
DocumentTypeService.getDocumentTypes().then((processes: any[]) => {
|
||||
if (processes.length) {
|
||||
const documents: any[] = processes.map((process: any) => process.processData);
|
||||
setAvailableDocuments(documents);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getDocuments();
|
||||
getDeedType();
|
||||
@ -97,12 +105,25 @@ export default function DeedTypesInformations(props: IProps) {
|
||||
[openSaveModal],
|
||||
);
|
||||
|
||||
const saveDocumentTypes = useCallback(async () => {
|
||||
await DeedTypes.getInstance().put(deedTypeUid as string, {
|
||||
uid: deedTypeUid as string,
|
||||
document_types: selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
|
||||
});
|
||||
const saveDocumentTypes = useCallback(() => {
|
||||
LoaderService.getInstance().show();
|
||||
DeedTypeService.getDeedTypeByUid(deedTypeUid as string, false).then((process: any) => {
|
||||
if (process) {
|
||||
const deedType: any = process.processData;
|
||||
|
||||
let document_types: any[] = deedType.document_types;
|
||||
if (!document_types) {
|
||||
document_types = [];
|
||||
}
|
||||
selectedDocuments.map((selectedDocument: any) => ({ uid: selectedDocument.id as string }))
|
||||
.forEach((selectedDocument: any) => document_types.push(selectedDocument));
|
||||
|
||||
DeedTypeService.updateDeedType(process, { document_types: document_types }).then(() => {
|
||||
LoaderService.getInstance().hide();
|
||||
closeSaveModal();
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [closeSaveModal, deedTypeUid, selectedDocuments]);
|
||||
|
||||
const onDocumentChangeHandler = useCallback((options: IOption[] | null) => {
|
||||
|
@ -1,10 +1,10 @@
|
||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import Module from "@Front/Config/Module";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import { validateOrReject, ValidationError } from "class-validator";
|
||||
@ -14,6 +14,10 @@ import { useCallback, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
|
||||
type IProps = {};
|
||||
export default function DocumentTypesCreate(props: IProps) {
|
||||
const [validationError, setValidationError] = useState<ValidationError[]>([]);
|
||||
@ -22,23 +26,38 @@ export default function DocumentTypesCreate(props: IProps) {
|
||||
const onSubmitHandler = useCallback(
|
||||
async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
|
||||
try {
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
if (!jwt) return;
|
||||
const office = Office.hydrate<Office>({
|
||||
uid: jwt.office_Id,
|
||||
});
|
||||
const documentToCreate = DocumentType.hydrate<DocumentType>({
|
||||
...values,
|
||||
office: office,
|
||||
});
|
||||
await validateOrReject(documentToCreate, { groups: ["createDocumentType"] });
|
||||
const documentTypeCreated = await DocumentTypes.getInstance().post(documentToCreate);
|
||||
const user: any = UserStore.instance.getUser();
|
||||
const officeId: string = user.office.uid;
|
||||
|
||||
const documentFormModel = DocumentType.hydrate<DocumentType>({
|
||||
...values,
|
||||
office: Office.hydrate<Office>({
|
||||
uid: officeId,
|
||||
})
|
||||
});
|
||||
await validateOrReject(documentFormModel, { groups: ["createDocumentType"] });
|
||||
|
||||
const documentTypeData: any = {
|
||||
...values,
|
||||
office: {
|
||||
uid: officeId,
|
||||
}
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
DocumentTypeService.createDocumentType(documentTypeData, validatorId).then((processCreated: any) => {
|
||||
ToasterService.getInstance().success({
|
||||
title: "Succès !",
|
||||
description: "Type de document créé avec succès"
|
||||
});
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", documentTypeCreated.uid!),
|
||||
.modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace("[uid]", processCreated.processData.uid),
|
||||
);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof Array) {
|
||||
setValidationError(e);
|
||||
|
@ -1,4 +1,3 @@
|
||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
@ -13,6 +12,9 @@ import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
export default function DocumentTypesEdit() {
|
||||
const router = useRouter();
|
||||
let { documentTypeUid } = router.query;
|
||||
@ -23,11 +25,15 @@ export default function DocumentTypesEdit() {
|
||||
useEffect(() => {
|
||||
async function getDocumentType() {
|
||||
if (!documentTypeUid) return;
|
||||
const documentType = await DocumentTypes.getInstance().getByUid(documentTypeUid as string, {
|
||||
_count: true,
|
||||
});
|
||||
LoaderService.getInstance().show();
|
||||
DocumentTypeService.getDocumentTypeByUid(documentTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const documentType: any = process.processData;
|
||||
setDocumentTypeSelected(documentType);
|
||||
}
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
|
||||
getDocumentType();
|
||||
}, [documentTypeUid]);
|
||||
@ -46,16 +52,22 @@ export default function DocumentTypesEdit() {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
|
||||
const documentTypeUpdated = await DocumentTypes.getInstance().put(documentTypeUid as string, documentToUpdate);
|
||||
LoaderService.getInstance().show();
|
||||
DocumentTypeService.getDocumentTypeByUid(documentTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
DocumentTypeService.updateDocumentType(process, values).then(() => {
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.DocumentTypes.pages.DocumentTypesInformations.props.path.replace(
|
||||
"[uid]",
|
||||
documentTypeUpdated.uid ?? "",
|
||||
),
|
||||
documentTypeUid as string ?? "",
|
||||
)
|
||||
);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (validationErrors: Array<ValidationError> | any) {
|
||||
if (!Array.isArray(validationErrors)) return;
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
|
@ -1,6 +1,5 @@
|
||||
import ChevronIcon from "@Assets/Icons/chevron.svg";
|
||||
import PenICon from "@Assets/Icons/pen.svg";
|
||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import DefaultDocumentTypesDashboard from "@Front/Components/LayoutTemplates/DefaultDocumentTypesDashboard";
|
||||
import Module from "@Front/Config/Module";
|
||||
@ -13,6 +12,8 @@ import { useEffect, useState } from "react";
|
||||
import classes from "./classes.module.scss";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
|
||||
export default function DocumentTypesInformations() {
|
||||
const router = useRouter();
|
||||
let { documentTypeUid } = router.query;
|
||||
@ -22,12 +23,14 @@ export default function DocumentTypesInformations() {
|
||||
useEffect(() => {
|
||||
async function getDocument() {
|
||||
if (!documentTypeUid) return;
|
||||
const document = await DocumentTypes.getInstance().getByUid(documentTypeUid as string, {
|
||||
_count: true,
|
||||
});
|
||||
if (!document) return;
|
||||
|
||||
DocumentTypeService.getDocumentTypeByUid(documentTypeUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
setDocumentSelected(document);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getDocument();
|
||||
}, [documentTypeUid]);
|
||||
|
@ -1,5 +1,3 @@
|
||||
import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import AutocompleteMultiSelect from "@Front/Components/DesignSystem/AutocompleteMultiSelect";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
|
||||
@ -9,9 +7,10 @@ import RadioBox from "@Front/Components/DesignSystem/RadioBox";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import BackArrow from "@Front/Components/Elements/BackArrow";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import { ValidationError } from "class-validator";
|
||||
import { ECivility } from "le-coffre-resources/dist/Customer/Contact";
|
||||
import { Contact, Customer, OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import { Contact, Customer } from "le-coffre-resources/dist/Notary";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
@ -19,6 +18,10 @@ import classes from "./classes.module.scss";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
|
||||
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
enum ESelectedOption {
|
||||
EXISTING_CUSTOMER = "existing_customer",
|
||||
NEW_CUSTOMER = "new_customer",
|
||||
@ -63,34 +66,65 @@ export default function AddClientToFolder(props: IProps) {
|
||||
values["cell_phone_number"] = "+33" + values["cell_phone_number"].substring(1);
|
||||
}
|
||||
}
|
||||
const contactToCreate = Contact.hydrate<Customer>(values);
|
||||
await contactToCreate.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
|
||||
const contactFormModel = Contact.hydrate<Customer>(values);
|
||||
await contactFormModel.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
|
||||
} catch (validationErrors) {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const customer: Customer = await Customers.getInstance().post({
|
||||
contact: values,
|
||||
// TODO: review
|
||||
const customerData: any = {
|
||||
contact: values
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
CustomerService.createCustomer(customerData, validatorId).then((processCreated: any) => {
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const customers: any[] = [];
|
||||
for (const customerUid of process.processData.customers.map((customer: any) => customer.uid)) {
|
||||
customers.push({ uid: customerUid });
|
||||
}
|
||||
customers.push({ uid: processCreated.processData.uid });
|
||||
|
||||
FolderService.updateFolder(process, { customers: customers }).then(() => {
|
||||
ToasterService.getInstance().success({
|
||||
title: "Succès !",
|
||||
description: "Client ajouté avec succès au dossier"
|
||||
});
|
||||
router.push(`/folders/${folderUid}`);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
if (!customer.uid) return;
|
||||
customersToLink?.push({ uid: customer.uid } as Partial<Customer>);
|
||||
} catch (backError) {
|
||||
if (!Array.isArray(backError)) return;
|
||||
setValidationError(backError as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const customers: any[] = [];
|
||||
for (const customerUid of customersToLink.map((customer: any) => customer.uid)) {
|
||||
customers.push({ uid: customerUid });
|
||||
}
|
||||
|
||||
if (customersToLink) {
|
||||
const body = OfficeFolder.hydrate<OfficeFolder>({
|
||||
customers: customersToLink.map((customer) => {
|
||||
return Customer.hydrate<Customer>(customer);
|
||||
}),
|
||||
FolderService.updateFolder(process, { customers: customers }).then(() => {
|
||||
ToasterService.getInstance().success({
|
||||
title: "Succès !",
|
||||
description: selectedCustomers.length > 1 ? "Clients associés avec succès au dossier" : "Client associé avec succès au dossier"
|
||||
});
|
||||
await Folders.getInstance().put(folderUid as string, body);
|
||||
router.push(`/folders/${folderUid}`);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
[existingCustomers, folderUid, router, selectedCustomers, selectedOption],
|
||||
@ -98,24 +132,23 @@ export default function AddClientToFolder(props: IProps) {
|
||||
|
||||
const getFolderPreSelectedCustomers = useCallback(
|
||||
async (folderUid: string): Promise<IOption[] | undefined> => {
|
||||
const query = {
|
||||
q: {
|
||||
customers: {
|
||||
include: {
|
||||
contact: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
let preExistingCustomers: IOption[] = [];
|
||||
try {
|
||||
const folder = await Folders.getInstance().getByUid(folderUid, query);
|
||||
preExistingCustomers = folder.customers!.map((customer) => {
|
||||
preExistingCustomers = await new Promise(resolve => {
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
const preExistingCustomers: IOption[] = folder.customers
|
||||
.map((customer: any) => {
|
||||
return {
|
||||
label: customer.contact?.first_name + " " + customer.contact?.last_name,
|
||||
id: customer.uid ?? "",
|
||||
};
|
||||
});
|
||||
resolve(preExistingCustomers);
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
router.push(Module.getInstance().get().modules.pages["404"].props.path);
|
||||
return;
|
||||
@ -126,11 +159,13 @@ export default function AddClientToFolder(props: IProps) {
|
||||
);
|
||||
|
||||
const loadCustomers = useCallback(async () => {
|
||||
const query = {};
|
||||
const availableCustomers = await Customers.getInstance().get(query);
|
||||
let preExistingCustomers: IOption[] | undefined = await getFolderPreSelectedCustomers(folderUid as string);
|
||||
const existingCustomers = preExistingCustomers ?? [];
|
||||
LoaderService.getInstance().show();
|
||||
CustomerService.getCustomers().then(async (processes: any[]) => {
|
||||
const availableCustomers: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
const preExistingCustomers: IOption[] | undefined = await getFolderPreSelectedCustomers(folderUid as string);
|
||||
|
||||
const existingCustomers = preExistingCustomers ?? [];
|
||||
existingCustomers.forEach((customer) => {
|
||||
const index = availableCustomers.findIndex((availableCustomer) => availableCustomer.uid === customer.id);
|
||||
if (index !== -1) availableCustomers.splice(index, 1);
|
||||
@ -145,6 +180,9 @@ export default function AddClientToFolder(props: IProps) {
|
||||
setExistingCustomers(existingCustomers);
|
||||
setIsLoaded(true);
|
||||
setSelectedOption(selectedOption);
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}, [folderUid, getFolderPreSelectedCustomers]);
|
||||
|
||||
const getSelectedOptions = useCallback((): IOption[] => {
|
||||
|
@ -1,5 +1,3 @@
|
||||
import Deeds from "@Front/Api/LeCoffreApi/Notary/Deeds/Deeds";
|
||||
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
|
||||
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
|
||||
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
|
||||
import { IOption as IFormOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
|
||||
@ -7,11 +5,15 @@ import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import RadioBox from "@Front/Components/DesignSystem/RadioBox";
|
||||
import { DocumentType, OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import { ChangeEvent, useCallback, useEffect, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
|
||||
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {
|
||||
isCreateDocumentModalVisible: boolean;
|
||||
closeModal: () => void;
|
||||
@ -29,7 +31,9 @@ export default function ParameterDocuments(props: IProps) {
|
||||
const [formattedOptions, setFormattedOptions] = useState<IOption[]>([]);
|
||||
|
||||
const getAvailableDocuments = useCallback(async () => {
|
||||
const documents = await DocumentTypes.getInstance().get({});
|
||||
DocumentTypeService.getDocumentTypes().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
const documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
const formattedOptions: IOption[] = documents
|
||||
.filter((document) => {
|
||||
@ -41,8 +45,11 @@ export default function ParameterDocuments(props: IProps) {
|
||||
id: document.uid ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1));
|
||||
setFormattedOptions(formattedOptions);
|
||||
}
|
||||
});
|
||||
}, [props.folder.deed?.document_types]);
|
||||
|
||||
const onVisibleDescriptionChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||
@ -68,18 +75,38 @@ export default function ParameterDocuments(props: IProps) {
|
||||
const addDocument = useCallback(async () => {
|
||||
if (addOrEditDocument === "add") {
|
||||
try {
|
||||
const documentType = await DocumentTypes.getInstance().post({
|
||||
LoaderService.getInstance().show();
|
||||
|
||||
const documentTypeData: any = {
|
||||
name: documentName,
|
||||
private_description: visibleDescription,
|
||||
office: {
|
||||
uid: props.folder.office!.uid!,
|
||||
},
|
||||
public_description: visibleDescription,
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
|
||||
DocumentTypeService.createDocumentType(documentTypeData, validatorId).then((processCreated: any) => {
|
||||
const documentType: any = processCreated.processData;
|
||||
resolve(documentType);
|
||||
});
|
||||
});
|
||||
|
||||
const oldDocumentsType = props.folder.deed?.document_types!;
|
||||
await Deeds.getInstance().put(props.folder.deed?.uid!, {
|
||||
document_types: [...oldDocumentsType, documentType],
|
||||
|
||||
await new Promise<void>((resolve: () => void) => {
|
||||
DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
DeedTypeService.updateDeedType(process, {
|
||||
document_types: [
|
||||
...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
|
||||
{ uid: documentType.uid }
|
||||
]
|
||||
}).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Create a new document type in the format expected by the parent component
|
||||
@ -93,28 +120,44 @@ export default function ParameterDocuments(props: IProps) {
|
||||
props.onDocumentsUpdated([newDocumentType]);
|
||||
}
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
handleClose();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
LoaderService.getInstance().show();
|
||||
|
||||
const oldDocumentsType = props.folder.deed?.document_types!;
|
||||
await Deeds.getInstance().put(props.folder.deed?.uid!, {
|
||||
await new Promise<void>((resolve: () => void) => {
|
||||
DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
DeedTypeService.updateDeedType(process, {
|
||||
document_types: [
|
||||
...oldDocumentsType,
|
||||
...selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
|
||||
],
|
||||
...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
|
||||
...selectedDocuments.map((document: any) => ({ uid: document.id as string }))
|
||||
]
|
||||
}).then(() => resolve());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Get the full document details for the selected documents
|
||||
const documentsById = await Promise.all(
|
||||
selectedDocuments.map(async (doc) => {
|
||||
const fullDoc = await DocumentTypes.getInstance().getByUid(doc.id as string);
|
||||
const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
|
||||
DocumentTypeService.getDocumentTypeByUid(doc.id as string).then((process: any) => {
|
||||
if (process) {
|
||||
const documentType: any = process.processData;
|
||||
resolve(documentType);
|
||||
}
|
||||
});
|
||||
});
|
||||
return {
|
||||
label: fullDoc.name!,
|
||||
value: fullDoc.uid!,
|
||||
description: fullDoc.private_description!,
|
||||
label: documentType.name!,
|
||||
value: documentType.uid!,
|
||||
description: documentType.private_description!,
|
||||
} as IFormOption;
|
||||
})
|
||||
);
|
||||
@ -123,6 +166,7 @@ export default function ParameterDocuments(props: IProps) {
|
||||
props.onDocumentsUpdated(documentsById);
|
||||
}
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
handleClose();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
|
@ -1,5 +1,3 @@
|
||||
import Documents from "@Front/Api/LeCoffreApi/Notary/Documents/Documents";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import CheckBox from "@Front/Components/DesignSystem/CheckBox";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
@ -8,6 +6,7 @@ import BackArrow from "@Front/Components/Elements/BackArrow";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { PlusIcon } from "@heroicons/react/24/outline";
|
||||
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useCallback, useEffect, useState, useRef } from "react";
|
||||
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
|
||||
@ -16,6 +15,10 @@ import ParameterDocuments from "./ParameterDocuments";
|
||||
import { IOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
export default function AskDocuments() {
|
||||
const router = useRouter();
|
||||
let { folderUid, customerUid } = router.query;
|
||||
@ -55,21 +58,30 @@ export default function AskDocuments() {
|
||||
},
|
||||
) => {
|
||||
try {
|
||||
// TODO: review
|
||||
LoaderService.getInstance().show();
|
||||
const documentAsked: [] = values["document_types"] as [];
|
||||
for (let i = 0; i < documentAsked.length; i++) {
|
||||
await Documents.getInstance().post({
|
||||
const documentTypeUid = documentAsked[i];
|
||||
if (!documentTypeUid) continue;
|
||||
|
||||
const documentData: any = {
|
||||
folder: {
|
||||
uid: folderUid,
|
||||
uid: folderUid as string,
|
||||
},
|
||||
depositor: {
|
||||
uid: customerUid,
|
||||
uid: customerUid as string,
|
||||
},
|
||||
document_type: {
|
||||
uid: documentAsked[i],
|
||||
uid: documentTypeUid
|
||||
},
|
||||
});
|
||||
}
|
||||
document_status: EDocumentStatus.ASKED,
|
||||
file_uid: null,
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
await DocumentService.createDocument(documentData, validatorId);
|
||||
}
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
@ -93,7 +105,7 @@ export default function AskDocuments() {
|
||||
|
||||
// If those UIDs are already asked, filter them to not show them in the list and only
|
||||
// show the documents that are not asked yet
|
||||
const documentTypes = folder.deed!.document_types!.filter((documentType) => {
|
||||
const documentTypes = folder.deed?.document_types?.filter((documentType) => {
|
||||
if (userDocumentTypesUids.includes(documentType!.uid!)) return false;
|
||||
return true;
|
||||
});
|
||||
@ -119,25 +131,15 @@ export default function AskDocuments() {
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
const folder = await Folders.getInstance().getByUid(folderUid as string, {
|
||||
q: {
|
||||
deed: {
|
||||
include: {
|
||||
document_types: true,
|
||||
},
|
||||
},
|
||||
office: true,
|
||||
documents: {
|
||||
include: {
|
||||
depositor: true,
|
||||
document_type: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!folder) return;
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folderUid as string).then(async (process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
setFolder(folder);
|
||||
setDocumentTypes(await getAvailableDocuments(folder));
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
@ -13,9 +13,11 @@ import BasePage from "../../Base";
|
||||
import classes from "./classes.module.scss";
|
||||
import Customer from "le-coffre-resources/dist/Customer";
|
||||
import Note from "le-coffre-resources/dist/Customer/Note";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
|
||||
import Notes from "@Front/Api/LeCoffreApi/Customer/Notes/Notes";
|
||||
import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
|
||||
import NoteService from "src/common/Api/LeCoffreApi/sdk/NoteService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {};
|
||||
|
||||
@ -76,9 +78,29 @@ class CreateCustomerNoteClass extends BasePage<IPropsClass, IState> {
|
||||
}
|
||||
|
||||
public override async componentDidMount() {
|
||||
/* TODO: review
|
||||
// const note = await Notes.getInstance().getByUid(this.props.noteUid, query);
|
||||
const folder = await Folders.getInstance().getByUid(this.props.folderUid, { note: true });
|
||||
const customer = await Customers.getInstance().getByUid(this.props.customerUid);
|
||||
*/
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
|
||||
const folder: any = await FolderService.getFolderByUid(this.props.folderUid).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
return folder;
|
||||
}
|
||||
});
|
||||
|
||||
const customer: any = await CustomerService.getCustomerByUid(this.props.customerUid).then((process: any) => {
|
||||
if (process) {
|
||||
const customer: any = process.processData;
|
||||
return customer;
|
||||
}
|
||||
});
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
|
||||
//get the note of the folder that has customer_uid = this.props.customer.uid
|
||||
// const folderNote = folder.notes?.find((note) => note.customer?.uid === this.props.customerUid);
|
||||
@ -91,14 +113,23 @@ class CreateCustomerNoteClass extends BasePage<IPropsClass, IState> {
|
||||
if (!this.state.folder || !this.state.customer) {
|
||||
throw new Error("Folder or customer not found");
|
||||
}
|
||||
const note = {
|
||||
content: values["content"],
|
||||
folder: this.state.folder,
|
||||
customer: this.state.customer,
|
||||
};
|
||||
|
||||
await Notes.getInstance().post(note);
|
||||
// TODO: review
|
||||
const noteData: any = {
|
||||
content: values["content"],
|
||||
folder: {
|
||||
uid: this.state.folder.uid
|
||||
},
|
||||
customer: {
|
||||
uid: this.state.customer.uid
|
||||
}
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
NoteService.createNote(noteData, validatorId).then(() => {
|
||||
this.props.router.push(this.backwardPath);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
@ -1,7 +1,4 @@
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
import DeedTypes from "@Front/Api/LeCoffreApi/Notary/DeedTypes/DeedTypes";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import Users from "@Front/Api/LeCoffreApi/Notary/Users/Users";
|
||||
import Button from "@Front/Components/DesignSystem/Button";
|
||||
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
@ -11,18 +8,23 @@ import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
import RadioBox from "@Front/Components/DesignSystem/RadioBox";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import BackArrow from "@Front/Components/Elements/BackArrow";
|
||||
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import { ValidationError } from "class-validator/types/validation/ValidationError";
|
||||
import { Deed, Office, OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import User from "le-coffre-resources/dist/Notary";
|
||||
import EFolderStatus from "le-coffre-resources/dist/Customer/EFolderStatus";
|
||||
import { DeedType } from "le-coffre-resources/dist/Notary";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
export default function CreateFolder(): JSX.Element {
|
||||
/**
|
||||
* State
|
||||
@ -48,9 +50,11 @@ export default function CreateFolder(): JSX.Element {
|
||||
[key: string]: any;
|
||||
},
|
||||
) => {
|
||||
const officeId = JwtService.getInstance().decodeJwt()?.office_Id;
|
||||
// TODO: review
|
||||
console.log(JwtService.getInstance().decodeJwt());
|
||||
const officeId = 'demo_notary_office_id'; //JwtService.getInstance().decodeJwt()?.office_Id;
|
||||
|
||||
const officeFolderForm = OfficeFolder.hydrate<OfficeFolder>({
|
||||
const officeFolderModel = OfficeFolder.hydrate<OfficeFolder>({
|
||||
folder_number: values["folder_number"],
|
||||
name: values["name"],
|
||||
description: values["description"],
|
||||
@ -67,16 +71,42 @@ export default function CreateFolder(): JSX.Element {
|
||||
});
|
||||
|
||||
try {
|
||||
await officeFolderForm.validateOrReject?.({ groups: ["createFolder"], forbidUnknownValues: true });
|
||||
await officeFolderModel.validateOrReject?.({ groups: ["createFolder"], forbidUnknownValues: true });
|
||||
} catch (validationErrors) {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newOfficeFolder = await Folders.getInstance().post(officeFolderForm);
|
||||
if (!newOfficeFolder) return;
|
||||
router.push(`/folders/${newOfficeFolder.uid}`);
|
||||
const folderData: any = {
|
||||
folder_number: values["folder_number"],
|
||||
name: values["name"],
|
||||
deed: {
|
||||
deed_type: {
|
||||
uid: values["deed"],
|
||||
}
|
||||
},
|
||||
description: values["description"],
|
||||
office: {
|
||||
uid: officeId
|
||||
},
|
||||
customers: [],
|
||||
documents: [],
|
||||
notes: [],
|
||||
stakeholders: folderAccessType === "whole_office" ? availableCollaborators : selectedCollaborators,
|
||||
status: EFolderStatus.LIVE
|
||||
};
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.createFolder(folderData, [], []).then((processCreated: any) => {
|
||||
ToasterService.getInstance().success({
|
||||
title: "Succès !",
|
||||
description: "Dossier créé avec succès"
|
||||
});
|
||||
const folderUid: string = processCreated.processData.uid;
|
||||
router.push(`/folders/${folderUid}`);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
} catch (backError) {
|
||||
if (!Array.isArray(backError)) return;
|
||||
setValidationError(backError as ValidationError[]);
|
||||
@ -100,9 +130,18 @@ export default function CreateFolder(): JSX.Element {
|
||||
* UseEffect
|
||||
*/
|
||||
useEffect(() => {
|
||||
DeedTypes.getInstance()
|
||||
.get({ where: { archived_at: null } })
|
||||
.then((deedTypes) => setAvailableDeedTypes(deedTypes));
|
||||
DeedTypeService.getDeedTypes().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let deedTypes: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy archived_at = null or not defined
|
||||
deedTypes = deedTypes.filter((deedType: any) => !deedType.archived_at);
|
||||
|
||||
setAvailableDeedTypes(deedTypes);
|
||||
}
|
||||
});
|
||||
|
||||
/* TODO: review
|
||||
// no need to pass query 'where' param here, default query for notaries include only users which are in the same office as the caller
|
||||
Users.getInstance()
|
||||
.get({
|
||||
@ -110,12 +149,15 @@ export default function CreateFolder(): JSX.Element {
|
||||
})
|
||||
.then((users) => {
|
||||
setAvailableCollaborators(users);
|
||||
/ *
|
||||
// set default selected collaborators to the connected user
|
||||
const currentUser = users.find((user) => user.uid === JwtService.getInstance().decodeJwt()?.userId);
|
||||
if (currentUser) {
|
||||
setSelectedCollaborators([currentUser]);
|
||||
}
|
||||
* /
|
||||
});
|
||||
*/
|
||||
}, []);
|
||||
|
||||
/**
|
||||
|
@ -0,0 +1,171 @@
|
||||
@import "@Themes/constants.scss";
|
||||
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-2xl, 40px);
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: var(--spacing-xl, 32px);
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-md, 16px);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-2xl, 40px);
|
||||
|
||||
.drag-drop-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-xl, 32px);
|
||||
|
||||
@media (min-width: $screen-m) {
|
||||
flex-direction: row;
|
||||
gap: var(--spacing-lg, 24px);
|
||||
}
|
||||
|
||||
.drag-drop-box {
|
||||
flex: 1;
|
||||
min-height: 200px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-sm, 8px);
|
||||
|
||||
// Force the DragAndDrop component to take full width and height
|
||||
> div {
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
min-height: 200px !important;
|
||||
display: flex !important;
|
||||
flex-direction: column !important;
|
||||
|
||||
// Override the fit-content width from DragAndDrop
|
||||
&.root {
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
min-height: 200px !important;
|
||||
}
|
||||
}
|
||||
|
||||
.file-info {
|
||||
padding: var(--spacing-sm, 8px) var(--spacing-md, 16px);
|
||||
background-color: var(--color-success-50, #f0f9ff);
|
||||
border: 1px solid var(--color-success-200, #bae6fd);
|
||||
border-radius: var(--radius-md, 8px);
|
||||
margin-top: var(--spacing-sm, 8px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.warning {
|
||||
text-align: center;
|
||||
padding: var(--spacing-md, 16px);
|
||||
background-color: var(--color-warning-50, #fffbeb);
|
||||
border: 1px solid var(--color-warning-200, #fde68a);
|
||||
border-radius: var(--radius-md, 8px);
|
||||
}
|
||||
|
||||
.verification-result {
|
||||
text-align: center;
|
||||
padding: var(--spacing-lg, 24px);
|
||||
border-radius: var(--radius-md, 8px);
|
||||
border: 2px solid;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-md, 16px);
|
||||
|
||||
&.success {
|
||||
background-color: var(--color-success-50, #f0fdf4);
|
||||
border-color: var(--color-success-200, #bbf7d0);
|
||||
}
|
||||
|
||||
&.error {
|
||||
background-color: var(--color-error-50, #fef2f2);
|
||||
border-color: var(--color-error-200, #fecaca);
|
||||
}
|
||||
|
||||
.verification-details {
|
||||
background-color: rgba(0, 0, 0, 0.05);
|
||||
padding: var(--spacing-md, 16px);
|
||||
border-radius: var(--radius-sm, 4px);
|
||||
font-family: monospace;
|
||||
white-space: pre-line;
|
||||
text-align: left;
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.merkle-proof-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--spacing-md, 16px);
|
||||
padding: var(--spacing-lg, 24px);
|
||||
background-color: rgba(0, 0, 0, 0.02);
|
||||
border-radius: var(--radius-md, 8px);
|
||||
border: 1px solid rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--spacing-sm, 8px);
|
||||
|
||||
.qr-code {
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
border: 2px solid var(--color-neutral-200, #e5e7eb);
|
||||
border-radius: var(--radius-sm, 4px);
|
||||
padding: var(--spacing-sm, 8px);
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
.qr-description {
|
||||
text-align: center;
|
||||
max-width: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
.qr-loading {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
border: 2px dashed var(--color-neutral-300, #d1d5db);
|
||||
border-radius: var(--radius-sm, 4px);
|
||||
background-color: var(--color-neutral-50, #f9fafb);
|
||||
}
|
||||
|
||||
.qr-error {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 150px;
|
||||
height: 150px;
|
||||
border: 2px solid var(--color-error-200, #fecaca);
|
||||
border-radius: var(--radius-sm, 4px);
|
||||
background-color: var(--color-error-50, #fef2f2);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--spacing-lg, 24px);
|
||||
|
||||
@media (max-width: $screen-s) {
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-md, 16px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,260 @@
|
||||
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import DragAndDrop from "@Front/Components/DesignSystem/DragAndDrop";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import Module from "@Front/Config/Module";
|
||||
import PdfService from "@Front/Services/PdfService";
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
import { ShieldCheckIcon } from "@heroicons/react/24/outline";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useState } from "react";
|
||||
import MessageBus from "src/sdk/MessageBus";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
|
||||
type IProps = {
|
||||
folderUid: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert a File object to FileBlob
|
||||
* @param file - The File object to convert
|
||||
* @returns Promise<FileBlob> - The converted FileBlob
|
||||
*/
|
||||
const convertFileToFileBlob = async (file: File): Promise<FileBlob> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const arrayBuffer = reader.result as ArrayBuffer;
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
resolve({
|
||||
type: file.type,
|
||||
data: uint8Array
|
||||
});
|
||||
};
|
||||
reader.onerror = () => reject(new Error('Failed to read file'));
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
|
||||
export default function DocumentVerification(props: IProps) {
|
||||
const { folderUid } = props;
|
||||
const router = useRouter();
|
||||
|
||||
const [documentToVerify, setDocumentToVerify] = useState<File | null>(null);
|
||||
const [validationCertificate, setValidationCertificate] = useState<File | null>(null);
|
||||
const [isVerifying, setIsVerifying] = useState(false);
|
||||
const [verificationResult, setVerificationResult] = useState<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
details?: string;
|
||||
merkleProof?: string;
|
||||
} | null>(null);
|
||||
|
||||
const handleDocumentToVerifyChange = (files: File[]) => {
|
||||
if (files.length > 0 && files[0]) {
|
||||
setDocumentToVerify(files[0]);
|
||||
} else {
|
||||
setDocumentToVerify(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleValidationCertificateChange = (files: File[]) => {
|
||||
if (files.length > 0 && files[0]) {
|
||||
setValidationCertificate(files[0]);
|
||||
} else {
|
||||
setValidationCertificate(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerifyDocuments = async () => {
|
||||
if (!documentToVerify || !validationCertificate) {
|
||||
console.error("Both documents are required for verification");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsVerifying(true);
|
||||
setVerificationResult(null);
|
||||
|
||||
const messageBus = MessageBus.getInstance();
|
||||
|
||||
try {
|
||||
// Here the things we need to verify:
|
||||
// - we can produce the same hash from the document provided than what is in the validation certificate
|
||||
// - the merkle proof is valid with that hash
|
||||
// - the root of the merkle tree is a state id from a commited state in the process
|
||||
// - that process is a file process linked to the right folder
|
||||
// Step 1: Parse the validation certificate
|
||||
const validationData = await PdfService.getInstance().parseCertificate(validationCertificate);
|
||||
|
||||
// Step 2: Convert File to FileBlob and hash the document using MessageBus
|
||||
const fileBlob = await convertFileToFileBlob(documentToVerify);
|
||||
|
||||
await messageBus.isReady();
|
||||
const documentHash = await messageBus.hashDocument(fileBlob, validationData.commitmentId);
|
||||
|
||||
// Step 3: Compare hashes
|
||||
const hashesMatch = documentHash.toLowerCase() === validationData.documentHash.toLowerCase();
|
||||
|
||||
if (!hashesMatch) {
|
||||
throw new Error('Hash du document invalide, le document fourni n\'est pas celui qui a été certifié');
|
||||
}
|
||||
|
||||
// Step 4: Verify the merkle proof
|
||||
const merkleProof = validationData.merkleProof;
|
||||
const merkleProofValid = await messageBus.verifyMerkleProof(merkleProof, documentHash);
|
||||
|
||||
if (!merkleProofValid) {
|
||||
throw new Error('Preuve de Merkle invalide, le document n\'a pas été certifié là où le certificat le prétend');
|
||||
}
|
||||
|
||||
// Step 5: Verify that this file process depends on the right folder process
|
||||
// First pin all the validated documents related to the folder
|
||||
const documentProcesses = await DocumentService.getDocuments();
|
||||
|
||||
const documents = documentProcesses.filter((process: any) =>
|
||||
process.processData.document_status === "VALIDATED" &&
|
||||
process.processData.folder.uid === folderUid
|
||||
);
|
||||
|
||||
if (!documents || documents.length === 0) {
|
||||
throw new Error(`Aucune demande de document trouvé pour le dossier ${folderUid}`);
|
||||
}
|
||||
|
||||
// Step 6: verify that the merkle proof match the last commited state for the file process
|
||||
const stateId = JSON.parse(validationData.merkleProof)['root'];
|
||||
|
||||
let stateIdExists = false;
|
||||
for (const doc of documents) {
|
||||
const processData = doc.processData;
|
||||
|
||||
for (const file of processData.files) {
|
||||
const fileUid = file.uid;
|
||||
const fileProcess = await FileService.getFileByUid(fileUid);
|
||||
const lastUpdatedStateId = fileProcess.lastUpdatedFileState.state_id;
|
||||
|
||||
stateIdExists = lastUpdatedStateId === stateId; // we assume that last state is the validated document, that seems reasonable
|
||||
if (stateIdExists) break;
|
||||
}
|
||||
|
||||
if (stateIdExists) break;
|
||||
}
|
||||
|
||||
if (!stateIdExists) {
|
||||
throw new Error('La preuve fournie ne correspond à aucun document demandé pour ce dossier.');
|
||||
}
|
||||
|
||||
setVerificationResult({
|
||||
success: true,
|
||||
message: "✅ Vérification réussie ! Le document est authentique et intègre.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Verification failed:", error);
|
||||
setVerificationResult({
|
||||
success: false,
|
||||
message: `❌ Erreur lors de la vérification: ${error}`,
|
||||
});
|
||||
} finally {
|
||||
setIsVerifying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBackToFolder = () => {
|
||||
const folderPath = Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid);
|
||||
router.push(folderPath);
|
||||
};
|
||||
|
||||
const bothDocumentsPresent = documentToVerify && validationCertificate;
|
||||
|
||||
return (
|
||||
<div className={classes["root"]}>
|
||||
<div className={classes["header"]}>
|
||||
<Typography typo={ETypo.TITLE_H2} color={ETypoColor.TEXT_PRIMARY}>
|
||||
Vérification de Documents
|
||||
</Typography>
|
||||
<Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.TEXT_SECONDARY}>
|
||||
Vérifiez l'intégrité et l'authenticité de vos documents
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className={classes["content"]}>
|
||||
<div className={classes["drag-drop-container"]}>
|
||||
<div className={classes["drag-drop-box"]}>
|
||||
<DragAndDrop
|
||||
title="Document à valider"
|
||||
description="Glissez-déposez ou cliquez pour sélectionner le document que vous souhaitez vérifier"
|
||||
onChange={handleDocumentToVerifyChange}
|
||||
/>
|
||||
{documentToVerify && (
|
||||
<div className={classes["file-info"]}>
|
||||
<Typography typo={ETypo.TEXT_SM_REGULAR} color={ETypoColor.COLOR_SUCCESS_500}>
|
||||
✓ {documentToVerify.name}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={classes["drag-drop-box"]}>
|
||||
<DragAndDrop
|
||||
title="Certificat de validation"
|
||||
description="Glissez-déposez ou cliquez pour sélectionner le certificat de validation correspondant"
|
||||
onChange={handleValidationCertificateChange}
|
||||
/>
|
||||
{validationCertificate && (
|
||||
<div className={classes["file-info"]}>
|
||||
<Typography typo={ETypo.TEXT_SM_REGULAR} color={ETypoColor.COLOR_SUCCESS_500}>
|
||||
✓ {validationCertificate.name}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!bothDocumentsPresent && (
|
||||
<div className={classes["warning"]}>
|
||||
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_WARNING_500}>
|
||||
⚠️ Veuillez sélectionner les deux documents pour procéder à la vérification
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{verificationResult && (
|
||||
<div className={`${classes["verification-result"]} ${classes[verificationResult.success ? "success" : "error"]}`}>
|
||||
<Typography typo={ETypo.TEXT_LG_REGULAR} color={verificationResult.success ? ETypoColor.COLOR_SUCCESS_500 : ETypoColor.COLOR_ERROR_500}>
|
||||
{verificationResult.message}
|
||||
</Typography>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={classes["actions"]}>
|
||||
<Button
|
||||
variant={EButtonVariant.SECONDARY}
|
||||
styletype={EButtonstyletype.TEXT}
|
||||
size={EButtonSize.LG}
|
||||
onClick={handleBackToFolder}
|
||||
disabled={isVerifying}
|
||||
>
|
||||
Retour au dossier
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant={EButtonVariant.PRIMARY}
|
||||
styletype={EButtonstyletype.CONTAINED}
|
||||
size={EButtonSize.LG}
|
||||
onClick={handleVerifyDocuments}
|
||||
rightIcon={<ShieldCheckIcon />}
|
||||
disabled={!bothDocumentsPresent || isVerifying}
|
||||
isLoading={isVerifying}
|
||||
>
|
||||
{isVerifying ? "Vérification en cours..." : "Vérifier les documents"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -12,7 +12,9 @@ import { useCallback } from "react";
|
||||
import { AnchorStatus } from "../..";
|
||||
import classes from "./classes.module.scss";
|
||||
import DeleteCustomerModal from "./DeleteCustomerModal";
|
||||
import Documents from "@Front/Api/LeCoffreApi/Notary/Documents/Documents";
|
||||
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {
|
||||
customer: Customer;
|
||||
@ -28,18 +30,33 @@ export default function ClientBox(props: IProps) {
|
||||
const { isOpen: isDeleteModalOpen, open: openDeleteModal, close: closeDeleteModal } = useOpenable();
|
||||
const { isOpen: isErrorModalOpen, open: openErrorModal, close: closeErrorModal } = useOpenable();
|
||||
|
||||
// TODO: review
|
||||
const handleOpenConnectionLink = useCallback(() => {
|
||||
const url = `http://localhost:3000/client-dashboard/${folderUid}/profile/${customer.uid}`;
|
||||
alert(url);
|
||||
}, [customer.uid, folderUid]);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (customerUid: string) => {
|
||||
console.log(customer);
|
||||
const documents = await Documents.getInstance().get({ where: { depositor_uid: customerUid, folder_uid: folderUid } });
|
||||
console.log(documents);
|
||||
(customerUid: string) => {
|
||||
LoaderService.getInstance().show();
|
||||
DocumentService.getDocuments().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let documents: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy folder.uid & depositor.uid
|
||||
documents = documents.filter((document: any) => document.folder.uid === folderUid && document.depositor && document.depositor.uid === customerUid);
|
||||
|
||||
if (documents && documents.length > 0) {
|
||||
closeDeleteModal();
|
||||
openErrorModal();
|
||||
return;
|
||||
}
|
||||
|
||||
props.onDelete(customerUid);
|
||||
} else {
|
||||
props.onDelete(customerUid);
|
||||
}
|
||||
});
|
||||
},
|
||||
[closeDeleteModal, customer.documents, openErrorModal, props, customer, folderUid],
|
||||
);
|
||||
@ -83,6 +100,15 @@ export default function ClientBox(props: IProps) {
|
||||
</Menu>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
size={EButtonSize.SM}
|
||||
variant={EButtonVariant.WARNING}
|
||||
styletype={EButtonstyletype.TEXT}
|
||||
onClick={handleOpenConnectionLink}>
|
||||
Lien de connexion
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_NEUTRAL_700}>
|
||||
Numéro de téléphone
|
||||
|
@ -1,9 +1,11 @@
|
||||
import Documents from "@Front/Api/LeCoffreApi/Notary/Documents/Documents";
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import React, { useCallback } from "react";
|
||||
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {
|
||||
documentUid: string;
|
||||
isOpen: boolean;
|
||||
@ -15,13 +17,22 @@ export default function DeleteAskedDocumentModal(props: IProps) {
|
||||
const { isOpen, onClose, documentUid, onDeleteSuccess } = props;
|
||||
|
||||
const onDelete = useCallback(
|
||||
() =>
|
||||
Documents.getInstance()
|
||||
.delete(documentUid)
|
||||
() => {
|
||||
LoaderService.getInstance().show();
|
||||
new Promise<void>(
|
||||
(resolve: () => void) => {
|
||||
DocumentService.getDocumentByUid(documentUid).then((process: any) => {
|
||||
if (process) {
|
||||
DocumentService.updateDocument(process, { isDeleted: 'true' }).then(() => resolve());
|
||||
}
|
||||
});
|
||||
})
|
||||
.then(() => onDeleteSuccess(documentUid))
|
||||
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Le document a été supprimé avec succès." }))
|
||||
.then(() => LoaderService.getInstance().hide())
|
||||
.then(onClose)
|
||||
.catch((error) => console.warn(error)),
|
||||
.catch((error) => console.warn(error));
|
||||
},
|
||||
[documentUid, onClose, onDeleteSuccess],
|
||||
);
|
||||
|
||||
|
@ -1,9 +1,11 @@
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Notary/DocumentsNotary/DocumentsNotary";
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import React, { useCallback } from "react";
|
||||
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {
|
||||
documentUid: string;
|
||||
isOpen: boolean;
|
||||
@ -15,13 +17,18 @@ export default function DeleteSentDocumentModal(props: IProps) {
|
||||
const { isOpen, onClose, documentUid, onDeleteSuccess } = props;
|
||||
|
||||
const onDelete = useCallback(
|
||||
() =>
|
||||
DocumentsNotary.getInstance()
|
||||
.delete(documentUid)
|
||||
() => {
|
||||
LoaderService.getInstance().show();
|
||||
DocumentService.getDocumentByUid(documentUid).then((process: any) => {
|
||||
if (process) {
|
||||
DocumentService.updateDocument(process, { isDeleted: 'true' })
|
||||
.then(() => onDeleteSuccess(documentUid))
|
||||
.then(() => ToasterService.getInstance().success({ title: "Succès !", description: "Le document a été supprimé avec succès." }))
|
||||
.then(onClose)
|
||||
.catch((error) => console.warn(error)),
|
||||
.then(() => LoaderService.getInstance().hide())
|
||||
.then(onClose);
|
||||
}
|
||||
});
|
||||
},
|
||||
[documentUid, onClose, onDeleteSuccess],
|
||||
);
|
||||
|
||||
|
@ -1,9 +1,12 @@
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import { File } from "le-coffre-resources/dist/Customer";
|
||||
import React from "react";
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
|
||||
type IProps = {
|
||||
file: File;
|
||||
file: {
|
||||
uid: string;
|
||||
file_blob: FileBlob;
|
||||
};
|
||||
url: string;
|
||||
isOpen: boolean;
|
||||
onClose?: () => void;
|
||||
@ -14,7 +17,7 @@ export default function FilePreviewModal(props: IProps) {
|
||||
|
||||
return (
|
||||
<Modal key={file.uid} isOpen={isOpen} onClose={onClose} fullscreen>
|
||||
<object data={url} type={file.mimetype} width="100%" height="800px" />
|
||||
<object data={url} type={file.file_blob.type} width="100%" height="800px" />
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
@ -1,7 +1,3 @@
|
||||
import Documents from "@Front/Api/LeCoffreApi/Notary/Documents/Documents";
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Notary/DocumentsNotary/DocumentsNotary";
|
||||
import Files from "@Front/Api/LeCoffreApi/Notary/Files/Files";
|
||||
import FilesNotary from "@Front/Api/LeCoffreApi/Notary/FilesNotary/Files";
|
||||
import CircleProgress from "@Front/Components/DesignSystem/CircleProgress";
|
||||
import IconButton from "@Front/Components/DesignSystem/IconButton";
|
||||
import Table from "@Front/Components/DesignSystem/Table";
|
||||
@ -10,9 +6,8 @@ import Tag, { ETagColor, ETagVariant } from "@Front/Components/DesignSystem/Tag"
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import Module from "@Front/Config/Module";
|
||||
import useOpenable from "@Front/Hooks/useOpenable";
|
||||
import { ArrowDownTrayIcon, EyeIcon, TrashIcon } from "@heroicons/react/24/outline";
|
||||
import { ArrowDownTrayIcon, EyeIcon, TrashIcon, DocumentTextIcon } from "@heroicons/react/24/outline";
|
||||
import { useMediaQuery } from "@mui/material";
|
||||
import { Document } from "le-coffre-resources/dist/Customer";
|
||||
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
|
||||
import DocumentNotary, { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
|
||||
import Link from "next/link";
|
||||
@ -23,6 +18,13 @@ import classes from "./classes.module.scss";
|
||||
import DeleteAskedDocumentModal from "./DeleteAskedDocumentModal";
|
||||
import DeleteSentDocumentModal from "./DeleteSentDocumentModal";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
|
||||
import PdfService, { CertificateData, Metadata } from "@Front/Services/PdfService";
|
||||
import MessageBus from "src/sdk/MessageBus";
|
||||
|
||||
type IProps = {
|
||||
customerUid: string;
|
||||
folderUid: string;
|
||||
@ -42,7 +44,7 @@ const tradDocumentsNotaryStatus: Record<EDocumentNotaryStatus, string> = {
|
||||
|
||||
export default function DocumentTables(props: IProps) {
|
||||
const { folderUid, customerUid } = props;
|
||||
const [documents, setDocuments] = useState<Document[]>([]);
|
||||
const [documents, setDocuments] = useState<any[]>([]);
|
||||
const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
|
||||
const [focusedDocumentUid, setFocusedDocumentUid] = useState<string | null>(null);
|
||||
|
||||
@ -52,23 +54,44 @@ export default function DocumentTables(props: IProps) {
|
||||
const deleteSentDocumentModal = useOpenable();
|
||||
|
||||
const fetchDocuments = useCallback(
|
||||
() =>
|
||||
Documents.getInstance()
|
||||
.get({
|
||||
where: { folder: { uid: folderUid }, depositor: { uid: customerUid } },
|
||||
include: { files: true, document_type: true },
|
||||
})
|
||||
.then(setDocuments)
|
||||
.catch(console.warn),
|
||||
() => {
|
||||
setDocuments([]);
|
||||
FolderService.getFolderByUid(folderUid).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
const customer: any = folder.customers.find((customer: any) => customer.uid === customerUid);
|
||||
if (customer && customer.documents) {
|
||||
const documents: any[] = customer.documents.filter((document: any) => document.depositor);
|
||||
setDocuments(documents);
|
||||
} else {
|
||||
setDocuments([]);
|
||||
}
|
||||
} else {
|
||||
setDocuments([]);
|
||||
}
|
||||
});
|
||||
},
|
||||
[customerUid, folderUid],
|
||||
);
|
||||
|
||||
const fetchDocumentsNotary = useCallback(
|
||||
() =>
|
||||
DocumentsNotary.getInstance()
|
||||
.get({ where: { folder: { uid: folderUid }, customer: { uid: customerUid } }, include: { files: true } })
|
||||
.then(setDocumentsNotary)
|
||||
.catch(console.warn),
|
||||
() => {
|
||||
setDocumentsNotary([]);
|
||||
FolderService.getFolderByUid(folderUid).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
const customer: any = folder.customers.find((customer: any) => customer.uid === customerUid);
|
||||
if (customer && customer.documents) {
|
||||
const documents: any[] = customer.documents.filter((document: any) => document.customer);
|
||||
setDocumentsNotary(documents);
|
||||
} else {
|
||||
setDocumentsNotary([]);
|
||||
}
|
||||
} else {
|
||||
setDocumentsNotary([]);
|
||||
}
|
||||
});
|
||||
},
|
||||
[customerUid, folderUid],
|
||||
);
|
||||
|
||||
@ -95,40 +118,104 @@ export default function DocumentTables(props: IProps) {
|
||||
[deleteSentDocumentModal],
|
||||
);
|
||||
|
||||
const onDownload = useCallback((doc: Document) => {
|
||||
const onDownload = useCallback((doc: any) => {
|
||||
const file = doc.files?.[0];
|
||||
if (!file || !file?.uid) return;
|
||||
if (!file) return;
|
||||
|
||||
return Files.getInstance()
|
||||
.download(file.uid)
|
||||
.then((blob) => {
|
||||
return new Promise<void>((resolve: () => void) => {
|
||||
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = file.file_name ?? "file";
|
||||
a.download = file.file_name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch((e) => console.warn(e));
|
||||
|
||||
resolve();
|
||||
}).catch((e) => console.warn(e));
|
||||
}, []);
|
||||
|
||||
const onDownloadFileNotary = useCallback((doc: DocumentNotary) => {
|
||||
const onDownloadFileNotary = useCallback((doc: any) => {
|
||||
const file = doc.files?.[0];
|
||||
if (!file || !file?.uid) return;
|
||||
if (!file) return;
|
||||
|
||||
return FilesNotary.getInstance()
|
||||
.download(file.uid)
|
||||
.then((blob) => {
|
||||
return new Promise<void>((resolve: () => void) => {
|
||||
const blob = new Blob([file.file_blob.data], { type: file.file_blob.type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = file.file_name ?? "file";
|
||||
a.download = file.file_name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch((e) => console.warn(e));
|
||||
|
||||
resolve();
|
||||
}).catch((e) => console.warn(e));
|
||||
}, []);
|
||||
|
||||
const onDownloadCertificate = useCallback(async (doc: any) => {
|
||||
try {
|
||||
const certificateData: CertificateData = {
|
||||
customer: {
|
||||
firstName: doc.depositor.first_name || doc.depositor.firstName || "N/A",
|
||||
lastName: doc.depositor.last_name || doc.depositor.lastName || "N/A",
|
||||
postalAddress: doc.depositor.postal_address || doc.depositor.address || doc.depositor.postalAddress || "N/A",
|
||||
email: doc.depositor.email || "N/A"
|
||||
},
|
||||
notary: {
|
||||
name: "N/A"
|
||||
},
|
||||
folderUid: folderUid,
|
||||
documentHash: "N/A",
|
||||
metadata: {
|
||||
fileName: "N/A",
|
||||
isDeleted: false,
|
||||
updatedAt: new Date(),
|
||||
commitmentId: "N/A",
|
||||
createdAt: new Date(),
|
||||
documentUid: "N/A",
|
||||
documentType: "N/A",
|
||||
merkleProof: "N/A"
|
||||
}
|
||||
};
|
||||
|
||||
// Get the specific document that was clicked
|
||||
const documentProcess = await DocumentService.getDocumentByUid(doc.uid);
|
||||
if (!documentProcess) {
|
||||
throw new Error('Document not found');
|
||||
}
|
||||
|
||||
// Process only the files for this specific document
|
||||
for (const file of documentProcess.processData.files) {
|
||||
const fileProcess = await FileService.getFileByUid(file.uid);
|
||||
|
||||
const hash = fileProcess.lastUpdatedFileState.pcd_commitment.file_blob;
|
||||
certificateData.documentHash = hash;
|
||||
|
||||
const proof = await MessageBus.getInstance().generateMerkleProof(fileProcess.lastUpdatedFileState, 'file_blob');
|
||||
|
||||
const metadata: Metadata = {
|
||||
fileName: fileProcess.processData.file_name,
|
||||
isDeleted: false,
|
||||
updatedAt: new Date(fileProcess.processData.updated_at),
|
||||
commitmentId: fileProcess.lastUpdatedFileState.commited_in,
|
||||
createdAt: new Date(fileProcess.processData.created_at),
|
||||
documentUid: doc.uid,
|
||||
documentType: doc.document_type.name,
|
||||
merkleProof: proof
|
||||
};
|
||||
certificateData.metadata = metadata;
|
||||
}
|
||||
|
||||
await PdfService.getInstance().downloadCertificate(certificateData);
|
||||
} catch (error) {
|
||||
console.error('Error downloading certificate:', error);
|
||||
}
|
||||
}, [folderUid, customerUid]);
|
||||
|
||||
const askedDocuments: IRowProps[] = useMemo(
|
||||
() =>
|
||||
documents
|
||||
@ -136,21 +223,25 @@ export default function DocumentTables(props: IProps) {
|
||||
if (document.document_status !== EDocumentStatus.ASKED) return null;
|
||||
return {
|
||||
key: document.uid,
|
||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
||||
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||
document_status: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.INFO}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.created_at ? new Date(document.created_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -172,21 +263,25 @@ export default function DocumentTables(props: IProps) {
|
||||
if (document.document_status !== EDocumentStatus.DEPOSITED) return null;
|
||||
return {
|
||||
key: document.uid,
|
||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
||||
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||
document_status: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.WARNING}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name?.split(".")?.[0] ?? "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -208,27 +303,31 @@ export default function DocumentTables(props: IProps) {
|
||||
);
|
||||
|
||||
const validatedDocuments: IRowProps[] = useMemo(
|
||||
() =>
|
||||
documents
|
||||
() => {
|
||||
const validated = documents
|
||||
.map((document) => {
|
||||
if (document.document_status !== EDocumentStatus.VALIDATED) return null;
|
||||
return {
|
||||
key: document.uid,
|
||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
||||
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||
document_status: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.SUCCESS}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name?.split(".")?.[0] ?? "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -241,13 +340,17 @@ export default function DocumentTables(props: IProps) {
|
||||
<IconButton icon={<EyeIcon />} />
|
||||
</Link>
|
||||
<IconButton onClick={() => onDownload(document)} icon={<ArrowDownTrayIcon />} />
|
||||
<IconButton onClick={() => onDownloadCertificate(document)} icon={<DocumentTextIcon />} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
};
|
||||
})
|
||||
.filter((document) => document !== null) as IRowProps[],
|
||||
[documents, folderUid, onDownload],
|
||||
.filter((document) => document !== null) as IRowProps[];
|
||||
|
||||
return validated;
|
||||
},
|
||||
[documents, folderUid, onDownload, onDownloadCertificate],
|
||||
);
|
||||
|
||||
const refusedDocuments: IRowProps[] = useMemo(
|
||||
@ -257,21 +360,25 @@ export default function DocumentTables(props: IProps) {
|
||||
if (document.document_status !== EDocumentStatus.REFUSED) return null;
|
||||
return {
|
||||
key: document.uid,
|
||||
document_type: { sx: { width: 400 }, content: document.document_type?.name ?? "_" },
|
||||
document_type: { sx: { width: 300 }, content: document.document_type?.name ?? "_" },
|
||||
document_status: {
|
||||
sx: { width: 107 },
|
||||
content: (
|
||||
<Tag
|
||||
color={ETagColor.ERROR}
|
||||
variant={ETagVariant.SEMI_BOLD}
|
||||
label={tradDocumentStatus[document.document_status].toUpperCase()}
|
||||
label={tradDocumentStatus[document.document_status as EDocumentStatus].toUpperCase()}
|
||||
/>
|
||||
),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name?.split(".")?.[0] ?? "_",
|
||||
},
|
||||
actions: { sx: { width: 76 }, content: "" },
|
||||
};
|
||||
})
|
||||
@ -286,17 +393,21 @@ export default function DocumentTables(props: IProps) {
|
||||
return {
|
||||
key: document.uid,
|
||||
document_type: {
|
||||
sx: { width: 400 },
|
||||
content: formatName(document.files?.[0]?.file_name?.split(".")?.[0] ?? "") || "_",
|
||||
sx: { width: 300 },
|
||||
content: "Autre document",
|
||||
},
|
||||
document_status: {
|
||||
sx: { width: 107 },
|
||||
content: getTagForSentDocument(document.document_status as EDocumentNotaryStatus),
|
||||
},
|
||||
date: {
|
||||
sx: { width: 107 },
|
||||
sx: { width: 120 },
|
||||
content: document.updated_at ? new Date(document.updated_at).toLocaleDateString() : "_",
|
||||
},
|
||||
file: {
|
||||
sx: { width: 120 },
|
||||
content: document.files?.[0]?.file_name?.split(".")?.[0] ?? "_",
|
||||
},
|
||||
actions: {
|
||||
sx: { width: 76 },
|
||||
content: (
|
||||
@ -383,6 +494,10 @@ function getHeader(dateColumnTitle: string, isMobile: boolean): IHead[] {
|
||||
key: "date",
|
||||
title: dateColumnTitle,
|
||||
},
|
||||
{
|
||||
key: "file",
|
||||
title: "Fichier",
|
||||
},
|
||||
{
|
||||
key: "actions",
|
||||
title: "Action",
|
||||
@ -390,10 +505,6 @@ function getHeader(dateColumnTitle: string, isMobile: boolean): IHead[] {
|
||||
];
|
||||
}
|
||||
|
||||
function formatName(text: string): string {
|
||||
return text.replace(/[^a-zA-Z0-9 ]/g, "");
|
||||
}
|
||||
|
||||
function getTagForSentDocument(status: EDocumentNotaryStatus) {
|
||||
if (status === EDocumentNotaryStatus.SENT) {
|
||||
return (
|
||||
|
@ -41,7 +41,9 @@ export default function EmailReminder(props: IProps) {
|
||||
}, [customer.uid, folderUid]);
|
||||
|
||||
useEffect(() => {
|
||||
/* TODO: review
|
||||
fetchReminders();
|
||||
*/
|
||||
}, [fetchReminders]);
|
||||
|
||||
const remindersLength = useMemo(() => {
|
||||
|
@ -14,7 +14,9 @@ import classes from "./classes.module.scss";
|
||||
import ClientBox from "./ClientBox";
|
||||
import DocumentTables from "./DocumentTables";
|
||||
import EmailReminder from "./EmailReminder";
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Notary/DocumentsNotary/DocumentsNotary";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {
|
||||
folder: OfficeFolder;
|
||||
@ -27,18 +29,19 @@ export default function ClientView(props: IProps) {
|
||||
const { folder, anchorStatus } = props;
|
||||
|
||||
const customers: ICustomer[] = useMemo(
|
||||
() =>
|
||||
folder?.customers
|
||||
?.map((customer) => ({
|
||||
id: customer.uid ?? "",
|
||||
() => {
|
||||
return folder?.customers
|
||||
?.map((customer: any) => ({
|
||||
id: customer.uid ?? '',
|
||||
...customer,
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
.sort((a: any, b: any) => {
|
||||
return a.documents &&
|
||||
a.documents.filter((document) => document.document_status === EDocumentStatus.DEPOSITED).length > 0
|
||||
a.documents.filter((document: any) => document.document_status === EDocumentStatus.DEPOSITED).length > 0
|
||||
? -1
|
||||
: 1;
|
||||
}) ?? [],
|
||||
}) ?? []
|
||||
},
|
||||
[folder],
|
||||
);
|
||||
|
||||
@ -58,27 +61,22 @@ export default function ClientView(props: IProps) {
|
||||
);
|
||||
|
||||
const handleClientDelete = useCallback(
|
||||
async (customerUid: string) => {
|
||||
(customerUid: string) => {
|
||||
if (!folder.uid) return;
|
||||
const documentsNotary = await DocumentsNotary.getInstance().get({
|
||||
where: { customer: { uid: customerUid }, folder: { uid: folder.uid } },
|
||||
});
|
||||
console.log(documentsNotary);
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folder.uid).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
|
||||
if (documentsNotary.length > 0) {
|
||||
documentsNotary.forEach(async (doc) => {
|
||||
await DocumentsNotary.getInstance().delete(doc.uid!);
|
||||
// FilterBy customerUid
|
||||
const customers = folder.customers.filter((uid: string) => uid !== customerUid);
|
||||
|
||||
FolderService.updateFolder(process, { customers: customers }).then(() => {
|
||||
LoaderService.getInstance().hide();
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
Folders.getInstance().put(
|
||||
folder.uid,
|
||||
OfficeFolder.hydrate<OfficeFolder>({
|
||||
...folder,
|
||||
customers: folder.customers?.filter((customer) => customer.uid !== customerUid),
|
||||
}),
|
||||
);
|
||||
window.location.reload();
|
||||
});
|
||||
},
|
||||
[folder],
|
||||
);
|
||||
@ -110,7 +108,7 @@ export default function ClientView(props: IProps) {
|
||||
anchorStatus={anchorStatus}
|
||||
folderUid={folder.uid}
|
||||
onDelete={handleClientDelete}
|
||||
customerNote={folder.notes!.find((value) => value.customer?.uid === customer.uid) ?? null}
|
||||
customerNote={folder.notes!.find((value: any) => value.customer?.uid === customer.uid) ?? null}
|
||||
/>
|
||||
<div className={classes["button-container"]}>
|
||||
{anchorStatus === AnchorStatus.NOT_ANCHORED && (
|
||||
|
@ -5,11 +5,12 @@ import { IItem } from "@Front/Components/DesignSystem/Menu/MenuItem";
|
||||
import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { ArchiveBoxIcon, EllipsisHorizontalIcon, PaperAirplaneIcon, PencilSquareIcon, UsersIcon } from "@heroicons/react/24/outline";
|
||||
import { ArchiveBoxIcon, EllipsisHorizontalIcon, PaperAirplaneIcon, PencilSquareIcon, ShieldCheckIcon, UsersIcon } from "@heroicons/react/24/outline";
|
||||
import classNames from "classnames";
|
||||
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import Link from "next/link";
|
||||
import { useMemo } from "react";
|
||||
import { useRouter } from "next/router";
|
||||
|
||||
import { AnchorStatus } from "..";
|
||||
import classes from "./classes.module.scss";
|
||||
@ -24,6 +25,7 @@ type IProps = {
|
||||
|
||||
export default function InformationSection(props: IProps) {
|
||||
const { folder, progress, onArchive, anchorStatus, isArchived } = props;
|
||||
const router = useRouter();
|
||||
|
||||
const menuItemsDekstop = useMemo(() => {
|
||||
let elements: IItem[] = [];
|
||||
@ -43,6 +45,17 @@ export default function InformationSection(props: IProps) {
|
||||
link: Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.EditInformations.props.path.replace("[folderUid]", folder?.uid ?? ""),
|
||||
hasSeparator: true,
|
||||
};
|
||||
const verifyDocumentElement = {
|
||||
icon: <ShieldCheckIcon />,
|
||||
text: "Vérifier le document",
|
||||
onClick: () => {
|
||||
const verifyPath = Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.VerifyDocuments.props.path.replace("[folderUid]", folder?.uid ?? "");
|
||||
router.push(verifyPath);
|
||||
},
|
||||
hasSeparator: false,
|
||||
};
|
||||
|
||||
@ -52,8 +65,11 @@ export default function InformationSection(props: IProps) {
|
||||
elements.push(modifyInformationsElement);
|
||||
}
|
||||
|
||||
// Add verify document option
|
||||
elements.push(verifyDocumentElement);
|
||||
|
||||
return elements;
|
||||
}, [anchorStatus, folder?.uid]);
|
||||
}, [anchorStatus, folder?.uid, router]);
|
||||
|
||||
const menuItemsMobile = useMemo(() => {
|
||||
let elements: IItem[] = [];
|
||||
@ -75,6 +91,17 @@ export default function InformationSection(props: IProps) {
|
||||
.modules.pages.Folder.pages.EditInformations.props.path.replace("[folderUid]", folder?.uid ?? ""),
|
||||
hasSeparator: true,
|
||||
};
|
||||
const verifyDocumentElement = {
|
||||
icon: <ShieldCheckIcon />,
|
||||
text: "Vérifier le document",
|
||||
onClick: () => {
|
||||
const verifyPath = Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.VerifyDocuments.props.path.replace("[folderUid]", folder?.uid ?? "");
|
||||
router.push(verifyPath);
|
||||
},
|
||||
hasSeparator: true,
|
||||
};
|
||||
|
||||
// If the folder is not anchored, we can modify the collaborators and the informations
|
||||
if (anchorStatus === AnchorStatus.NOT_ANCHORED) {
|
||||
@ -82,6 +109,9 @@ export default function InformationSection(props: IProps) {
|
||||
elements.push(modifyInformationsElement);
|
||||
}
|
||||
|
||||
// Add verify document option
|
||||
elements.push(verifyDocumentElement);
|
||||
|
||||
elements.push({
|
||||
icon: <PaperAirplaneIcon />,
|
||||
text: "Envoyer des documents",
|
||||
@ -101,7 +131,7 @@ export default function InformationSection(props: IProps) {
|
||||
}
|
||||
|
||||
return elements;
|
||||
}, [anchorStatus, folder?.uid, isArchived, onArchive]);
|
||||
}, [anchorStatus, folder?.uid, isArchived, onArchive, router]);
|
||||
return (
|
||||
<section className={classes["root"]}>
|
||||
<div className={classes["info-box1"]}>
|
||||
|
@ -1,4 +1,3 @@
|
||||
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import Modal from "@Front/Components/DesignSystem/Modal";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import Module from "@Front/Config/Module";
|
||||
@ -6,6 +5,9 @@ import { OfficeFolder } from "le-coffre-resources/dist/Notary";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useCallback } from "react";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {
|
||||
isOpen: boolean;
|
||||
onClose?: () => void;
|
||||
@ -21,8 +23,18 @@ export default function DeleteFolderModal(props: IProps) {
|
||||
if ((folder?.customers?.length ?? 0) > 0 || (folder?.documents?.length ?? 0) > 0)
|
||||
return console.warn("Cannot delete folder with customers or documents");
|
||||
|
||||
return Folders.getInstance()
|
||||
.delete(folder.uid)
|
||||
return new Promise<void>(
|
||||
(resolve: () => void) => {
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folder.uid!).then((process: any) => {
|
||||
if (process) {
|
||||
FolderService.updateFolder(process, { isDeleted: 'true' }).then(() => {
|
||||
LoaderService.getInstance().hide();
|
||||
resolve();
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
.then(() => router.push(Module.getInstance().get().modules.pages.Folder.props.path))
|
||||
.then(onClose);
|
||||
}, [folder, router, onClose]);
|
||||
|
@ -7,6 +7,8 @@ import React, { useCallback, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
type IProps = {
|
||||
isOpen: boolean;
|
||||
onClose?: () => void;
|
||||
@ -19,11 +21,29 @@ export default function AnchoringModal(props: IProps) {
|
||||
const [isAnchoring, setIsAnchoring] = useState(false);
|
||||
|
||||
const anchor = useCallback(() => {
|
||||
setIsAnchoring(true);
|
||||
|
||||
// TODO: review
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
FolderService.updateFolder(process, { status: '' }).then(() => {
|
||||
setIsAnchoring(false);
|
||||
|
||||
onAnchorSuccess();
|
||||
if (onClose) {
|
||||
onClose();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
const timeoutDelay = 9800;
|
||||
const timeoutPromise = new Promise((resolve) => {
|
||||
setTimeout(resolve, timeoutDelay);
|
||||
});
|
||||
setIsAnchoring(true);
|
||||
|
||||
return OfficeFolderAnchors.getInstance()
|
||||
.post(folderUid)
|
||||
.then(() => timeoutPromise)
|
||||
@ -34,6 +54,7 @@ export default function AnchoringModal(props: IProps) {
|
||||
console.warn(e);
|
||||
setIsAnchoring(false);
|
||||
});
|
||||
*/
|
||||
}, [folderUid, onAnchorSuccess, onClose]);
|
||||
|
||||
return (
|
||||
|
@ -1,4 +1,3 @@
|
||||
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import OfficeFolderAnchors from "@Front/Api/LeCoffreApi/Notary/OfficeFolderAnchors/OfficeFolderAnchors";
|
||||
import Loader from "@Front/Components/DesignSystem/Loader";
|
||||
import DefaultNotaryDashboard from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
|
||||
@ -21,6 +20,8 @@ import InformationSection from "./InformationSection";
|
||||
import NoClientView from "./NoClientView";
|
||||
import AnchoringProcessingInfo from "./elements/AnchoringProcessingInfo";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
export enum AnchorStatus {
|
||||
"VERIFIED_ON_CHAIN" = "VERIFIED_ON_CHAIN",
|
||||
"ANCHORING" = "ANCHORING",
|
||||
@ -59,6 +60,8 @@ export default function FolderInformation(props: IProps) {
|
||||
|
||||
const fetchFolder = useCallback(async () => {
|
||||
if (!folderUid) return;
|
||||
|
||||
/*
|
||||
const query = {
|
||||
q: {
|
||||
deed: { include: { deed_type: true, document_types: true } },
|
||||
@ -99,6 +102,15 @@ export default function FolderInformation(props: IProps) {
|
||||
return Folders.getInstance()
|
||||
.getByUid(folderUid, query)
|
||||
.then((folder) => setFolder(folder));
|
||||
*/
|
||||
|
||||
// TODO: review
|
||||
return FolderService.getFolderByUid(folderUid).then(async (process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
setFolder(folder);
|
||||
}
|
||||
});
|
||||
}, [folderUid]);
|
||||
|
||||
const fetchAnchorStatus = useCallback(() => {
|
||||
@ -113,7 +125,10 @@ export default function FolderInformation(props: IProps) {
|
||||
const fetchData = useCallback(() => {
|
||||
setIsLoading(true);
|
||||
return fetchFolder()
|
||||
.then(() => fetchAnchorStatus())
|
||||
.then(() => {
|
||||
// TODO: review
|
||||
//return fetchAnchorStatus()
|
||||
})
|
||||
.catch((e) => console.error(e))
|
||||
.finally(() => setIsLoading(false));
|
||||
}, [fetchAnchorStatus, fetchFolder]);
|
||||
|
@ -1,6 +1,5 @@
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
import DocumentsNotary from "@Front/Api/LeCoffreApi/Notary/DocumentsNotary/DocumentsNotary";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
|
||||
import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import DragAndDrop from "@Front/Components/DesignSystem/DragAndDrop";
|
||||
import Form from "@Front/Components/DesignSystem/Form";
|
||||
@ -19,6 +18,12 @@ import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
|
||||
|
||||
enum EClientSelection {
|
||||
ALL_CLIENTS = "all_clients",
|
||||
SELECTED_CLIENTS = "selected_clients",
|
||||
@ -59,6 +64,78 @@ export default function SendDocuments() {
|
||||
throw new Error("No clients selected");
|
||||
}
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
for (const selectedClient of selectedClients) {
|
||||
const customer: any = await new Promise<void>((resolve: (customer: any) => void) => {
|
||||
CustomerService.getCustomerByUid(selectedClient as string).then((process: any) => {
|
||||
if (process) {
|
||||
const customer: any = process.processData;
|
||||
resolve(customer);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
await new Promise<void>((resolve: () => void) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
if (event.target?.result) {
|
||||
const date: Date = new Date();
|
||||
const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;
|
||||
|
||||
const fileName: string = `${customer.contact.last_name}-${strDate}.${file.name.split('.').pop()}`;
|
||||
|
||||
const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
|
||||
const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
const fileBlob: any = {
|
||||
type: file.type,
|
||||
data: uint8Array
|
||||
};
|
||||
|
||||
const fileData: any = {
|
||||
file_blob: fileBlob,
|
||||
file_name: fileName
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
FileService.createFile(fileData, validatorId).then((processCreated: any) => {
|
||||
const fileUid: string = processCreated.processData.uid;
|
||||
|
||||
const documentData: any = {
|
||||
folder: {
|
||||
uid: folderUid as string
|
||||
},
|
||||
customer: {
|
||||
uid: selectedClient as string
|
||||
},
|
||||
files: [
|
||||
{
|
||||
uid: fileUid
|
||||
}
|
||||
],
|
||||
document_status: EDocumentNotaryStatus.SENT
|
||||
};
|
||||
|
||||
DocumentService.createDocument(documentData, validatorId).then(() => resolve());
|
||||
});
|
||||
}
|
||||
};
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
}
|
||||
LoaderService.getInstance().hide();
|
||||
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string),
|
||||
);
|
||||
setIsSending(false);
|
||||
ToasterService.getInstance().success({ title: "Succès !", description: "Votre document a été envoyée avec succès." });
|
||||
|
||||
/*
|
||||
await Promise.all(
|
||||
selectedClients.map(async (customer) => {
|
||||
const promises = files.map(async (file) => {
|
||||
@ -83,6 +160,7 @@ export default function SendDocuments() {
|
||||
);
|
||||
setIsSending(false);
|
||||
ToasterService.getInstance().success({ title: "Succès !", description: "Votre document a été envoyée avec succès." });
|
||||
*/
|
||||
} catch (error) {
|
||||
setIsSending(false);
|
||||
console.warn("Error while sending files: ", error);
|
||||
@ -92,18 +170,14 @@ export default function SendDocuments() {
|
||||
);
|
||||
|
||||
const fetchFolder = useCallback(async () => {
|
||||
Folders.getInstance()
|
||||
.getByUid(folderUid as string, {
|
||||
q: {
|
||||
customers: {
|
||||
include: {
|
||||
contact: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
.then((folder) => setFolder(folder))
|
||||
.catch((e) => console.warn(e));
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folderUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
setFolder(folder);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
}, [folderUid]);
|
||||
|
||||
const onClientSelectionChange = useCallback(
|
||||
|
@ -1,5 +1,4 @@
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import Form, { IBaseField } from "@Front/Components/DesignSystem/Form";
|
||||
import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
@ -15,9 +14,11 @@ import { Contact, Customer } from "le-coffre-resources/dist/Notary";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
export default function UpdateClient() {
|
||||
const router = useRouter();
|
||||
const { folderUid, customerUid } = router.query;
|
||||
@ -35,16 +36,14 @@ export default function UpdateClient() {
|
||||
useEffect(() => {
|
||||
const fetchCustomer = async () => {
|
||||
try {
|
||||
const customerData = await Customers.getInstance().getByUid(customerUid as string, {
|
||||
contact: {
|
||||
include: {
|
||||
address: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (customerData) {
|
||||
setCustomer(customerData);
|
||||
LoaderService.getInstance().show();
|
||||
CustomerService.getCustomerByUid(customerUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const customer: any = process.processData;
|
||||
setCustomer(customer);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch customer", error);
|
||||
}
|
||||
@ -72,8 +71,17 @@ export default function UpdateClient() {
|
||||
|
||||
try {
|
||||
await contact.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
|
||||
await Customers.getInstance().put(customerUid as string, { contact });
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
CustomerService.getCustomerByUid(customerUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
// TODO: review - address
|
||||
CustomerService.updateCustomer(process, { contact: contact }).then(() => {
|
||||
router.push(backwardPath);
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (validationErrors) {
|
||||
if (Array.isArray(validationErrors)) {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
|
@ -11,7 +11,9 @@ import { NextRouter, useRouter } from "next/router";
|
||||
import BasePage from "../../Base";
|
||||
import classes from "./classes.module.scss";
|
||||
import Note from "le-coffre-resources/dist/Customer/Note";
|
||||
import Notes from "@Front/Api/LeCoffreApi/Customer/Notes/Notes";
|
||||
|
||||
import NoteService from "src/common/Api/LeCoffreApi/sdk/NoteService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type IProps = {};
|
||||
|
||||
@ -66,13 +68,11 @@ class UpdateCustomerNoteClass extends BasePage<IPropsClass, IState> {
|
||||
}
|
||||
|
||||
public override async componentDidMount() {
|
||||
const query = {
|
||||
q: {
|
||||
customer: "true",
|
||||
folder: "true",
|
||||
},
|
||||
};
|
||||
const note = await Notes.getInstance().getByUid(this.props.noteUid, query);
|
||||
LoaderService.getInstance().show();
|
||||
NoteService.getNoteByUid(this.props.noteUid).then((process: any) => {
|
||||
if (process) {
|
||||
const note: any = process.processData;
|
||||
|
||||
// const folder = await Folders.getInstance().getByUid(this.props.folderUid, { note: true });
|
||||
//get the note of the folder that has customer_uid = this.props.customer.uid
|
||||
// const folderNote = folder.notes?.find((note) => note.customer?.uid === this.props.customerUid);
|
||||
@ -82,19 +82,22 @@ class UpdateCustomerNoteClass extends BasePage<IPropsClass, IState> {
|
||||
.get()
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", note.folder?.uid!),
|
||||
});
|
||||
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async onFormSubmit(e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) {
|
||||
try {
|
||||
const note = {
|
||||
content: values["content"],
|
||||
};
|
||||
|
||||
await Notes.getInstance().put(this.props.noteUid, note);
|
||||
LoaderService.getInstance().show();
|
||||
NoteService.getNoteByUid(this.props.noteUid).then((process: any) => {
|
||||
if (process) {
|
||||
NoteService.updateNote(process, { content: values["content"] }).then(() => {
|
||||
this.props.router.push(this.state.backwardPath);
|
||||
|
||||
// await Folders.getInstance().put(this.props.folderUid, values);
|
||||
// this.props.router.push(this.backwardPath);
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
|
@ -18,6 +18,9 @@ import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoub
|
||||
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
import { isArray } from "class-validator";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
export default function UpdateFolderMetadata() {
|
||||
const router = useRouter();
|
||||
|
||||
@ -46,14 +49,18 @@ export default function UpdateFolderMetadata() {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await Folders.getInstance().put(folderUid, newValues);
|
||||
const url = Module.getInstance()
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folderUid).then((process: any) => {
|
||||
if (process) {
|
||||
FolderService.updateFolder(process, { ...values, deed: { uid: values["deed"] } }).then(() => {
|
||||
router.push(Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid);
|
||||
|
||||
router.push(url);
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid));
|
||||
LoaderService.getInstance().hide();
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (backError) {
|
||||
if (!Array.isArray(backError)) return;
|
||||
setValidationError(backError);
|
||||
@ -63,16 +70,14 @@ export default function UpdateFolderMetadata() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderUid || isArray(folderUid)) return;
|
||||
const query = {
|
||||
q: {
|
||||
deed: { include: { deed_type: true } },
|
||||
office: true,
|
||||
customers: { include: { contact: true } },
|
||||
},
|
||||
};
|
||||
Folders.getInstance()
|
||||
.getByUid(folderUid, query)
|
||||
.then((folder) => setSelectedFolder(folder));
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolderByUid(folderUid).then((process: any) => {
|
||||
if (process) {
|
||||
const folder: any = process.processData;
|
||||
setSelectedFolder(folder);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
}, [folderUid]);
|
||||
|
||||
const backwardPath = Module.getInstance()
|
||||
|
@ -1,13 +1,12 @@
|
||||
import LeftArrowIcon from "@Assets/Icons/left-arrow.svg";
|
||||
import RightArrowIcon from "@Assets/Icons/right-arrow.svg";
|
||||
import Documents from "@Front/Api/LeCoffreApi/Notary/Documents/Documents";
|
||||
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
|
||||
import FilePreview from "@Front/Components/DesignSystem/FilePreview";
|
||||
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import DefaultNotaryDashboard from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { Document, File } from "le-coffre-resources/dist/Notary";
|
||||
import { Document } from "le-coffre-resources/dist/Notary";
|
||||
import { EDocumentStatus } from "le-coffre-resources/dist/Notary/Document";
|
||||
import Image from "next/image";
|
||||
import { NextRouter, useRouter } from "next/router";
|
||||
@ -15,10 +14,14 @@ import React from "react";
|
||||
|
||||
import BasePage from "../../Base";
|
||||
import classes from "./classes.module.scss";
|
||||
import Files from "@Front/Api/LeCoffreApi/Notary/Files/Files";
|
||||
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
|
||||
import MessageBox from "@Front/Components/Elements/MessageBox";
|
||||
|
||||
import { FileBlob } from "@Front/Api/Entities/types";
|
||||
|
||||
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
|
||||
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
|
||||
|
||||
type IProps = {};
|
||||
type IPropsClass = {
|
||||
documentUid: string;
|
||||
@ -31,9 +34,9 @@ type IState = {
|
||||
isValidateModalVisible: boolean;
|
||||
refuseText: string;
|
||||
selectedFileIndex: number;
|
||||
selectedFile: File | null;
|
||||
selectedFile: { uid: string; file_name: string; file_blob: FileBlob } | null;
|
||||
validatedPercentage: number;
|
||||
document: Document | null;
|
||||
document: any | null;
|
||||
fileBlob: Blob | null;
|
||||
isLoading: boolean;
|
||||
};
|
||||
@ -89,10 +92,10 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
</div>
|
||||
)}
|
||||
<div className={classes["file-container"]}>
|
||||
{this.state.selectedFile.mimetype === "application/pdf" ||
|
||||
this.state.selectedFile.mimetype === "image/jpeg" ||
|
||||
this.state.selectedFile.mimetype === "image/png" ||
|
||||
this.state.selectedFile.mimetype === "image/jpg" ? (
|
||||
{this.state.selectedFile.file_blob.type === "application/pdf" ||
|
||||
this.state.selectedFile.file_blob.type === "image/jpeg" ||
|
||||
this.state.selectedFile.file_blob.type === "image/png" ||
|
||||
this.state.selectedFile.file_blob.type === "image/jpg" ? (
|
||||
<FilePreview
|
||||
href={this.state.fileBlob ? URL.createObjectURL(this.state.fileBlob) : ""}
|
||||
fileName={this.state.selectedFile.file_name}
|
||||
@ -197,14 +200,24 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
override async componentDidMount() {
|
||||
try {
|
||||
const document = await Documents.getInstance().getByUid(this.props.documentUid, {
|
||||
files: {
|
||||
where: { archived_at: null },
|
||||
},
|
||||
document_type: true,
|
||||
folder: true,
|
||||
depositor: true,
|
||||
const document: any = await new Promise((resolve: (document: any) => void) => {
|
||||
DocumentService.getDocumentByUid(this.props.documentUid).then(async (process: any) => {
|
||||
if (process) {
|
||||
const document: any = process.processData;
|
||||
|
||||
if (document.files && document.files.length > 0) {
|
||||
const files: any[] = [];
|
||||
for (const file of document.files) {
|
||||
files.push((await FileService.getFileByUid(file.uid)).processData);
|
||||
}
|
||||
document.files = files;
|
||||
}
|
||||
|
||||
resolve(document);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
this.setState(
|
||||
{
|
||||
document,
|
||||
@ -226,8 +239,9 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
private async getFilePreview(): Promise<void> {
|
||||
try {
|
||||
const fileBlob: Blob = await Files.getInstance().download(this.state.selectedFile?.uid as string);
|
||||
if (!this.state.selectedFile) return;
|
||||
|
||||
const fileBlob: Blob = new Blob([this.state.selectedFile.file_blob.data], { type: this.state.selectedFile.file_blob.type });
|
||||
this.setState({
|
||||
fileBlob,
|
||||
});
|
||||
@ -237,16 +251,16 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
}
|
||||
|
||||
private downloadFile() {
|
||||
if (!this.state.fileBlob) return;
|
||||
const url = window.URL.createObjectURL(this.state.fileBlob);
|
||||
const a = document.createElement("a");
|
||||
a.style.display = "none";
|
||||
if (!this.state.fileBlob || !this.state.selectedFile) return;
|
||||
|
||||
const url = URL.createObjectURL(this.state.fileBlob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
// the filename you want
|
||||
a.download = this.state.selectedFile?.file_name as string;
|
||||
a.download = this.state.selectedFile.file_name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
private getRandomPercentageForOcr() {
|
||||
@ -309,8 +323,9 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
private async refuseDocument() {
|
||||
try {
|
||||
await Documents.getInstance().refuse(this.props.documentUid, this.state.refuseText);
|
||||
|
||||
DocumentService.getDocumentByUid(this.props.documentUid).then((process: any) => {
|
||||
if (process) {
|
||||
DocumentService.updateDocument(process, { document_status: EDocumentStatus.REFUSED, refused_reason: this.state.refuseText }).then(() => {
|
||||
this.props.router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
@ -318,6 +333,9 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
"?customerUid=" +
|
||||
this.state.document?.depositor?.uid,
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
@ -325,10 +343,24 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
|
||||
private async validateDocument() {
|
||||
try {
|
||||
await Documents.getInstance().put(this.props.documentUid, {
|
||||
document_status: EDocumentStatus.VALIDATED,
|
||||
DocumentService.getDocumentByUid(this.props.documentUid).then(async (process: any) => {
|
||||
if (process) {
|
||||
await new Promise<void>((resolve: () => void) => {
|
||||
FileService.getFileByUid(process.processData.files[0].uid).then((p) => {
|
||||
if (p) {
|
||||
alert(`aplc-${p.processData.file_name}`)
|
||||
FileService.updateFile(p, { file_name: `aplc-${p.processData.file_name}` }).then(resolve);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
FileService.getFileByUid(process.processData.files[0].uid).then((process) => {
|
||||
if (process) {
|
||||
console.log(process.processData);
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
this.props.router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
@ -336,6 +368,21 @@ class ViewDocumentsClass extends BasePage<IPropsClass, IState> {
|
||||
"?customerUid=" +
|
||||
this.state.document?.depositor?.uid,
|
||||
);
|
||||
*/
|
||||
|
||||
/*
|
||||
DocumentService.updateDocument(process, { document_status: EDocumentStatus.VALIDATED }).then(() => {
|
||||
this.props.router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", this.props.folderUid) +
|
||||
"?customerUid=" +
|
||||
this.state.document?.depositor?.uid,
|
||||
);
|
||||
});
|
||||
*/
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
@ -13,9 +13,10 @@ import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
export default function Folder() {
|
||||
const [_isArchivedModalOpen, _setIsArchivedModalOpen] = useState(true);
|
||||
const router = useRouter();
|
||||
@ -23,6 +24,25 @@ export default function Folder() {
|
||||
const { user: activeUser } = useUser();
|
||||
|
||||
useEffect(() => {
|
||||
// TODO: review
|
||||
FolderService.getFolders().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let folders: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy status
|
||||
folders = folders.filter((folder: any) => folder.status === EFolderStatus.LIVE);
|
||||
|
||||
if (folders.length > 0) {
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folders[0].uid)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
Folders.getInstance()
|
||||
.get({
|
||||
q: {
|
||||
@ -38,6 +58,7 @@ export default function Folder() {
|
||||
.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folders[0]?.uid ?? ""),
|
||||
);
|
||||
});
|
||||
*/
|
||||
}, [router]);
|
||||
return (
|
||||
<DefaultNotaryDashboard title={"Dossier"} mobileBackText={"Liste des dossiers"}>
|
||||
|
@ -25,6 +25,7 @@ type IProps = {
|
||||
export default function StepEmail(props: IProps) {
|
||||
const { onSubmit, validationErrors } = props;
|
||||
const [isErrorModalOpen, setIsErrorModalOpen] = useState(0);
|
||||
|
||||
/* const router = useRouter();
|
||||
const redirectCustomerOnConnection = useCallback(() => {
|
||||
async function getCustomer() {
|
||||
@ -41,12 +42,17 @@ export default function StepEmail(props: IProps) {
|
||||
const router = useRouter();
|
||||
const error = router.query["error"];
|
||||
const redirectUserOnConnection = useCallback(() => {
|
||||
/* TODO: review
|
||||
const variables = FrontendVariables.getInstance();
|
||||
router.push(
|
||||
`${variables.IDNOT_BASE_URL + variables.IDNOT_AUTHORIZE_ENDPOINT}?client_id=${variables.IDNOT_CLIENT_ID}&redirect_uri=${
|
||||
variables.FRONT_APP_HOST
|
||||
}/authorized-client&scope=openid,profile&response_type=code`,
|
||||
);
|
||||
*/
|
||||
router.push(
|
||||
`https://qual-connexion.idnot.fr/user/IdPOAuth2/authorize/idnot_idp_v1?client_id=B3CE56353EDB15A9&redirect_uri=http://local.lecoffreio.4nkweb:3000/authorized-client&scope=openid,profile&response_type=code`,
|
||||
);
|
||||
}, [router]);
|
||||
|
||||
const openErrorModal = useCallback((index: number) => {
|
||||
@ -94,12 +100,14 @@ export default function StepEmail(props: IProps) {
|
||||
Pour les clients :
|
||||
</Typography>
|
||||
<Form className={classes["form"]} onSubmit={onSubmit}>
|
||||
{
|
||||
<TextField
|
||||
placeholder="Renseigner votre email"
|
||||
label="E-mail"
|
||||
name="email"
|
||||
validationError={validationErrors.find((err) => err.property === "email")}
|
||||
/>
|
||||
}
|
||||
<Button type="submit">Se connecter</Button>
|
||||
</Form>
|
||||
</div>
|
||||
|
@ -16,6 +16,12 @@ import Module from "@Front/Config/Module";
|
||||
import { TotpCodesReasons } from "le-coffre-resources/dist/Customer/TotpCodes";
|
||||
import PasswordForgotten from "./PasswordForgotten";
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
|
||||
import AuthModal from "src/sdk/AuthModal";
|
||||
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
|
||||
|
||||
export enum LoginStep {
|
||||
EMAIL,
|
||||
TOTP,
|
||||
@ -23,6 +29,7 @@ export enum LoginStep {
|
||||
NEW_PASSWORD,
|
||||
PASSWORD_FORGOTTEN,
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
const router = useRouter();
|
||||
// const error = router.query["error"];
|
||||
@ -35,6 +42,7 @@ export default function Login() {
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [partialPhoneNumber, setPartialPhoneNumber] = useState<string>("");
|
||||
const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
|
||||
const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
|
||||
|
||||
// const openErrorModal = useCallback(() => {
|
||||
// setIsErrorModalOpen(true);
|
||||
@ -52,9 +60,13 @@ export default function Login() {
|
||||
try {
|
||||
if (!values["email"]) return;
|
||||
setEmail(values["email"]);
|
||||
|
||||
/* TODO: review
|
||||
const res = await Auth.getInstance().mailVerifySms({ email: values["email"] });
|
||||
setPartialPhoneNumber(res.partialPhoneNumber);
|
||||
setTotpCodeUid(res.totpCodeUid);
|
||||
*/
|
||||
|
||||
setStep(LoginStep.TOTP);
|
||||
setValidationErrors([]);
|
||||
} catch (error: any) {
|
||||
@ -73,19 +85,34 @@ export default function Login() {
|
||||
const onSmsCodeSubmit = useCallback(
|
||||
async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
|
||||
try {
|
||||
console.log(values);
|
||||
console.log(email);
|
||||
|
||||
if (!values["totpCode"]) return;
|
||||
/*
|
||||
const res = await Auth.getInstance().verifyTotpCode({ totpCode: values["totpCode"], email });
|
||||
|
||||
// If the code is valid setting it in state
|
||||
if (res.validCode) setTotpCode(values["totpCode"]);
|
||||
if (res.validCode) {
|
||||
setTotpCode(values["totpCode"]);
|
||||
}
|
||||
*/
|
||||
if ('1234' === values["totpCode"]) {
|
||||
setTotpCode(values["totpCode"]);
|
||||
}
|
||||
|
||||
setValidationErrors([]);
|
||||
|
||||
/*
|
||||
// If it's first connection, show the form for first connection
|
||||
if (res.reason === TotpCodesReasons.FIRST_LOGIN) setStep(LoginStep.NEW_PASSWORD);
|
||||
// If it's password forgotten, show the form for password forgotten
|
||||
else if (res.reason === TotpCodesReasons.RESET_PASSWORD) setStep(LoginStep.PASSWORD_FORGOTTEN);
|
||||
// Else just login normally
|
||||
else setStep(LoginStep.PASSWORD);
|
||||
*/
|
||||
|
||||
setIsAuthModalOpen(true);
|
||||
} catch (error: any) {
|
||||
setValidationErrors([
|
||||
{
|
||||
@ -130,7 +157,10 @@ export default function Login() {
|
||||
return;
|
||||
}
|
||||
const token = await Auth.getInstance().setPassword({ totpCode, email, password: values["password"] });
|
||||
CustomerStore.instance.connect(token.accessToken, token.refreshToken);
|
||||
|
||||
// TODO: review
|
||||
//CustomerStore.instance.connect(token.accessToken, token.refreshToken);
|
||||
|
||||
setValidationErrors([]);
|
||||
router.push(Module.getInstance().get().modules.pages.Folder.pages.Select.props.path);
|
||||
// If set password worked, setting the token and redirecting
|
||||
@ -154,7 +184,10 @@ export default function Login() {
|
||||
try {
|
||||
if (!values["password"]) return;
|
||||
const token = await Auth.getInstance().login({ totpCode, email, password: values["password"] });
|
||||
CustomerStore.instance.connect(token.accessToken, token.refreshToken);
|
||||
|
||||
// TODO: review
|
||||
//CustomerStore.instance.connect(token.accessToken, token.refreshToken);
|
||||
|
||||
setValidationErrors([]);
|
||||
router.push(Module.getInstance().get().modules.pages.Folder.pages.Select.props.path);
|
||||
} catch (error: any) {
|
||||
@ -231,6 +264,23 @@ export default function Login() {
|
||||
{step === LoginStep.PASSWORD_FORGOTTEN && (
|
||||
<PasswordForgotten onSubmit={onNewPasswordSubmit} validationErrors={validationErrors} />
|
||||
)}
|
||||
|
||||
{isAuthModalOpen && <AuthModal
|
||||
isOpen={isAuthModalOpen}
|
||||
onClose={() => {
|
||||
CustomerService.getCustomers().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
const customers: any[] = processes.map((process: any) => process.processData);
|
||||
const customer: any = customers.find((customer: any) => customer.contact.email === email);
|
||||
if (customer) {
|
||||
UserStore.instance.connect(customer);
|
||||
router.push(Module.getInstance().get().modules.pages.Folder.pages.Select.props.path);
|
||||
}
|
||||
}
|
||||
setIsAuthModalOpen(false);
|
||||
});
|
||||
}}
|
||||
/>}
|
||||
</div>
|
||||
{/* <Confirm
|
||||
isOpen={isErrorModalOpen}
|
||||
|
@ -6,32 +6,135 @@ import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Ty
|
||||
import HelpBox from "@Front/Components/Elements/HelpBox";
|
||||
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
|
||||
import Module from "@Front/Config/Module";
|
||||
import CookieService from "@Front/Services/CookieService/CookieService";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
import Image from "next/image";
|
||||
import { useRouter } from "next/router";
|
||||
import React, { useEffect } from "react";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import classes from "./classes.module.scss";
|
||||
|
||||
import AuthModal from "src/sdk/AuthModal";
|
||||
|
||||
import MessageBus from "src/sdk/MessageBus";
|
||||
import Iframe from "src/sdk/Iframe";
|
||||
|
||||
import OfficeService from "src/common/Api/LeCoffreApi/sdk/OfficeService";
|
||||
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
|
||||
import CollaboratorService from "src/common/Api/LeCoffreApi/sdk/CollaboratorService";
|
||||
|
||||
export default function LoginCallBack() {
|
||||
const router = useRouter();
|
||||
const [idNotUser, setIdNotUser] = useState<any>(null);
|
||||
const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
|
||||
const getOffice = async (idNotUser: any) => {
|
||||
return await new Promise<any>((resolve: (office: any) => void) => {
|
||||
OfficeService.getOffices().then((processes: any[]) => {
|
||||
const officeFound: any = processes.length > 0 ? processes.map((process: any) => process.processData).find((office: any) => office.idNot === idNotUser.office.idNot) : null;
|
||||
if (officeFound) {
|
||||
resolve(officeFound);
|
||||
} else {
|
||||
const officeData: any = {
|
||||
idNot: idNotUser.office.idNot,
|
||||
name: idNotUser.office.name,
|
||||
crpcen: idNotUser.office.crpcen,
|
||||
address: {
|
||||
create: {
|
||||
address: idNotUser.office.address.address,
|
||||
zip_code: idNotUser.office.address.zip_code,
|
||||
city: idNotUser.office.address.city,
|
||||
},
|
||||
},
|
||||
office_status: 'ACTIVATED'
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
OfficeService.createOffice(officeData, validatorId).then((process: any) => {
|
||||
if (process) {
|
||||
const office: any = process.processData;
|
||||
resolve(office);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const getRole = async (idNotUser: any) => {
|
||||
return await new Promise<any>((resolve: (role: any) => void) => {
|
||||
RoleService.getRoles().then((processes: any[]) => {
|
||||
const roleFound: any = processes.length > 0 ? processes.map((process: any) => process.processData).find((role: any) => role.name === idNotUser.role.name) : null;
|
||||
if (roleFound) {
|
||||
resolve(roleFound);
|
||||
} else {
|
||||
const roleData: any = {
|
||||
name: idNotUser.role!.name,
|
||||
label: idNotUser.role!.label
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
RoleService.createRole(roleData, validatorId).then((process: any) => {
|
||||
if (process) {
|
||||
const role: any = process.processData;
|
||||
resolve(role);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const getCollaborator = async (collaboratorData: any) => {
|
||||
return await new Promise<any>((resolve: (role: any) => void) => {
|
||||
CollaboratorService.getCollaborators().then((processes: any[]) => {
|
||||
const collaboratorFound: any = processes.length > 0 ? processes.map((process: any) => process.processData).find((collaborator: any) => collaborator.idNot === idNotUser.idNot) : null;
|
||||
if (collaboratorFound) {
|
||||
resolve(collaboratorFound);
|
||||
} else {
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
CollaboratorService.createCollaborator(collaboratorData, validatorId).then((process: any) => {
|
||||
if (process) {
|
||||
const collaborator: any = process.processData;
|
||||
resolve(collaborator);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
async function getUser() {
|
||||
UserStore.instance.disconnect();
|
||||
|
||||
// TODO: review
|
||||
// HACK: If start with http://local.lecoffreio.4nkweb:3000/authorized-client
|
||||
// Replace with http://localhost:3000/authorized-client
|
||||
if (window.location.href.startsWith('http://local.lecoffreio.4nkweb:3000/authorized-client')) {
|
||||
window.location.href = window.location.href.replace('http://local.lecoffreio.4nkweb:3000/authorized-client', 'http://localhost:3000/authorized-client');
|
||||
return;
|
||||
}
|
||||
|
||||
const code = router.query["code"];
|
||||
if (code) {
|
||||
try {
|
||||
const token = await Auth.getInstance().getIdnotJwt(code as string);
|
||||
const idNotUser: any = await Auth.getInstance().getIdNotUser(code as string);
|
||||
setIdNotUser(idNotUser);
|
||||
setIsAuthModalOpen(true);
|
||||
/*
|
||||
const token: any = null;
|
||||
if (!token) return router.push(Module.getInstance().get().modules.pages.Login.props.path);
|
||||
await UserStore.instance.connect(token.accessToken, token.refreshToken);
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
if (!jwt) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
|
||||
if (!jwt.rules.includes("GET folders")) {
|
||||
if (jwt.rules && !jwt.rules.includes("GET folders")) {
|
||||
return router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
|
||||
}
|
||||
return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
|
||||
setIsAuthModalOpen(true);
|
||||
//return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
|
||||
*/
|
||||
return;
|
||||
} catch (e: any) {
|
||||
if (e.http_status === 401 && e.message === "Email not found") {
|
||||
return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=3");
|
||||
@ -42,6 +145,7 @@ export default function LoginCallBack() {
|
||||
return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
|
||||
}
|
||||
}
|
||||
/*
|
||||
const refreshToken = CookieService.getInstance().getCookie("leCoffreRefreshToken");
|
||||
if (!refreshToken) return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=1");
|
||||
const isTokenRefreshed = await JwtService.getInstance().refreshToken(refreshToken);
|
||||
@ -51,13 +155,15 @@ export default function LoginCallBack() {
|
||||
return router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
|
||||
}
|
||||
if (isTokenRefreshed) {
|
||||
return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
|
||||
//setIsAuthModalOpen(true);
|
||||
//return router.push(Module.getInstance().get().modules.pages.Folder.props.path);
|
||||
return;
|
||||
}
|
||||
*/
|
||||
return router.push(Module.getInstance().get().modules.pages.Login.props.path + "?error=2");
|
||||
}
|
||||
getUser();
|
||||
}),
|
||||
[router];
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<DefaultDoubleSidePage title={"Login"} image={backgroundImage}>
|
||||
@ -76,6 +182,44 @@ export default function LoginCallBack() {
|
||||
description="Notre équipe de support est là pour vous aider."
|
||||
button={{ text: "Contacter l'administrateur", link: "mailto:support@lecoffre.io" }}
|
||||
/>
|
||||
{isAuthModalOpen && <AuthModal
|
||||
isOpen={isAuthModalOpen}
|
||||
onClose={() => {
|
||||
setIsAuthModalOpen(false);
|
||||
setIsConnected(true);
|
||||
setTimeout(() => {
|
||||
MessageBus.getInstance().initMessageListener();
|
||||
MessageBus.getInstance().isReady().then(async () => {
|
||||
const office: any = await getOffice(idNotUser);
|
||||
const role: any = await getRole(idNotUser);
|
||||
|
||||
const collaboratorData: any = {
|
||||
idNot: idNotUser.idNot,
|
||||
contact: idNotUser.contact,
|
||||
office: {
|
||||
uid: office.uid
|
||||
},
|
||||
role: {
|
||||
uid: role.uid
|
||||
}
|
||||
};
|
||||
const collaborator: any = await getCollaborator(collaboratorData);
|
||||
collaborator.office = office;
|
||||
collaborator.role = role;
|
||||
UserStore.instance.connect(collaborator);
|
||||
|
||||
MessageBus.getInstance().destroyMessageListener();
|
||||
/*
|
||||
if (jwt.rules && !jwt.rules.includes("GET folders")) {
|
||||
router.push(Module.getInstance().get().modules.pages.Subscription.pages.New.props.path);
|
||||
}
|
||||
*/
|
||||
router.push(Module.getInstance().get().modules.pages.Folder.props.path);
|
||||
});
|
||||
}, 100);
|
||||
}}
|
||||
/>}
|
||||
{isConnected && <Iframe />}
|
||||
</div>
|
||||
</DefaultDoubleSidePage>
|
||||
);
|
||||
|
@ -5,6 +5,7 @@ import TextField from "@Front/Components/DesignSystem/Form/TextField";
|
||||
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
|
||||
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
|
||||
import DefaultRolesDashboard from "@Front/Components/LayoutTemplates/DefaultRoleDashboard";
|
||||
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
|
||||
import Module from "@Front/Config/Module";
|
||||
import { Office, OfficeRole } from "le-coffre-resources/dist/Admin";
|
||||
import { useRouter } from "next/router";
|
||||
@ -16,6 +17,10 @@ import Rules, { RulesMode } from "@Front/Components/Elements/Rules";
|
||||
import { AppRuleActions, AppRuleNames } from "@Front/Api/Entities/rule";
|
||||
import { ValidationError } from "class-validator";
|
||||
|
||||
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
|
||||
type IProps = {};
|
||||
export default function RolesCreate(props: IProps) {
|
||||
const [hasChanged, setHasChanged] = useState<boolean>(false);
|
||||
@ -25,13 +30,16 @@ export default function RolesCreate(props: IProps) {
|
||||
const router = useRouter();
|
||||
const onSubmitHandler = useCallback(
|
||||
async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
|
||||
const jwt = JwtService.getInstance().decodeJwt();
|
||||
const user: any = UserStore.instance.getUser();
|
||||
const officeId: string = user.office.uid;
|
||||
|
||||
const officeRole = OfficeRole.hydrate<OfficeRole>({
|
||||
name: values["name"],
|
||||
office: Office.hydrate<Office>({
|
||||
uid: jwt?.office_Id,
|
||||
uid: officeId,
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await officeRole.validateOrReject?.({ groups: ["createOfficeRole"], forbidUnknownValues: true });
|
||||
} catch (validationErrors: Array<ValidationError> | any) {
|
||||
@ -39,6 +47,29 @@ export default function RolesCreate(props: IProps) {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
|
||||
const roleData: any = {
|
||||
name: values["name"],
|
||||
office: {
|
||||
uid: officeId,
|
||||
}
|
||||
};
|
||||
const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
RoleService.createRole(roleData, validatorId).then((processCreated: any) => {
|
||||
if (processCreated) {
|
||||
ToasterService.getInstance().success({
|
||||
title: "Succès !",
|
||||
description: "Rôle créé avec succès"
|
||||
});
|
||||
const role: any = processCreated.processData;
|
||||
router.push(Module.getInstance().get().modules.pages.Roles.pages.RolesInformations.props.path.replace("[uid]", role.uid!));
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
try {
|
||||
const role = await OfficeRoles.getInstance().post(
|
||||
OfficeRole.hydrate<OfficeRole>({
|
||||
@ -55,6 +86,7 @@ export default function RolesCreate(props: IProps) {
|
||||
setValidationError(validationErrors as ValidationError[]);
|
||||
return;
|
||||
}
|
||||
*/
|
||||
},
|
||||
[router],
|
||||
);
|
||||
|
@ -13,6 +13,9 @@ import React from "react";
|
||||
import classes from "./classes.module.scss";
|
||||
import RulesGroups from "@Front/Api/LeCoffreApi/Admin/RulesGroups/RulesGroups";
|
||||
|
||||
import RoleService from "src/common/Api/LeCoffreApi/sdk/RoleService";
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
|
||||
type RuleGroupsCheckbox = RulesGroup & {
|
||||
checked: boolean;
|
||||
};
|
||||
@ -21,7 +24,7 @@ export default function RolesInformations() {
|
||||
const router = useRouter();
|
||||
let { roleUid } = router.query;
|
||||
|
||||
const [roleSelected, setRoleSelected] = useState<OfficeRole | null>(null);
|
||||
const [roleSelected, setRoleSelected] = useState<any | null>(null);
|
||||
const [rulesGroupsCheckboxes, setRulesGroupsCheckboxes] = useState<RuleGroupsCheckbox[]>([]);
|
||||
const [selectAll, setSelectAll] = useState<boolean>(false);
|
||||
|
||||
@ -39,24 +42,64 @@ export default function RolesInformations() {
|
||||
setSelectAll(false);
|
||||
async function getUser() {
|
||||
if (!roleUid) return;
|
||||
|
||||
/*
|
||||
const role = await OfficeRoles.getInstance().getByUid(roleUid as string, {
|
||||
q: {
|
||||
rules: true,
|
||||
},
|
||||
});
|
||||
*/
|
||||
|
||||
LoaderService.getInstance().show();
|
||||
const role: any = await new Promise<any>((resolve: (role: any) => void) => {
|
||||
RoleService.getRoleByUid(roleUid as string).then((process: any) => {
|
||||
if (process) {
|
||||
const role: any = process.processData;
|
||||
resolve(role);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
/* TODO: review
|
||||
const rulesGroups = await RulesGroups.getInstance().get({
|
||||
include: {
|
||||
rules: true,
|
||||
},
|
||||
});
|
||||
*/
|
||||
|
||||
/*
|
||||
const rulesGroups: RulesGroup[] = [
|
||||
{
|
||||
uid: 'toto',
|
||||
name: 'toto',
|
||||
rules: [
|
||||
{
|
||||
uid: 'toto',
|
||||
name: 'toto',
|
||||
label: 'toto',
|
||||
namespace: 'toto',
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}
|
||||
],
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}
|
||||
];
|
||||
*/
|
||||
|
||||
if (!role) return;
|
||||
setRoleSelected(role);
|
||||
|
||||
// TODO: review
|
||||
if (!role.rules) return;
|
||||
/*
|
||||
const rulesCheckboxes = rulesGroups
|
||||
.map((ruleGroup) => {
|
||||
if (ruleGroup.rules?.every((rule) => role.rules?.find((r) => r.uid === rule.uid))) {
|
||||
if (ruleGroup.rules?.every((rule) => role.rules?.find((r: any) => r.uid === rule.uid))) {
|
||||
return { ...ruleGroup, checked: true };
|
||||
}
|
||||
return { ...ruleGroup, checked: false };
|
||||
@ -67,6 +110,8 @@ export default function RolesInformations() {
|
||||
const selectAll = rulesCheckboxes.every((rule) => rule.checked);
|
||||
setSelectAll(selectAll);
|
||||
setRulesGroupsCheckboxes(rulesCheckboxes);
|
||||
*/
|
||||
setRulesGroupsCheckboxes(role.rules);
|
||||
}
|
||||
|
||||
getUser();
|
||||
@ -124,7 +169,7 @@ export default function RolesInformations() {
|
||||
<Typography typo={ETypo.TITLE_H1}>Gestion des rôles</Typography>
|
||||
</div>
|
||||
<div className={classes["subtitle"]}>
|
||||
<Typography typo={ETypo.TITLE_H5}>{roleSelected?.name}</Typography>
|
||||
<Typography typo={ETypo.TITLE_H5}>{roleSelected?.label}</Typography>
|
||||
</div>
|
||||
<div className={classes["rights-container"]}>
|
||||
<div className={classes["rights-header"]}>
|
||||
|
@ -1,11 +1,9 @@
|
||||
import backgroundImage from "@Assets/images/background_refonte.svg";
|
||||
import LogoIcon from "@Assets/logo_small_blue.svg";
|
||||
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";
|
||||
import SearchBlockList from "@Front/Components/DesignSystem/SearchBlockList";
|
||||
import { IBlock } from "@Front/Components/DesignSystem/SearchBlockList/BlockList/Block";
|
||||
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
|
||||
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
import { OfficeFolder } from "le-coffre-resources/dist/Customer";
|
||||
import Image from "next/image";
|
||||
import { useRouter } from "next/router";
|
||||
@ -14,37 +12,38 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import classes from "./classes.module.scss";
|
||||
import Module from "@Front/Config/Module";
|
||||
|
||||
import UserStore from "@Front/Stores/UserStore";
|
||||
|
||||
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
|
||||
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
|
||||
|
||||
export default function SelectFolder() {
|
||||
const router = useRouter();
|
||||
const [customer, setCustomer] = useState<any>(null);
|
||||
const [folders, setFolders] = useState<OfficeFolder[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const jwt = JwtService.getInstance().decodeCustomerJwt();
|
||||
if (!jwt) return;
|
||||
const customer: any = UserStore.instance.getUser();
|
||||
if (!customer) {
|
||||
return;
|
||||
}
|
||||
setCustomer(customer);
|
||||
|
||||
Folders.getInstance()
|
||||
.get({
|
||||
q: {
|
||||
where: {
|
||||
customers: {
|
||||
some: {
|
||||
contact: {
|
||||
email: jwt.email,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
created_at: "desc",
|
||||
},
|
||||
],
|
||||
include: {
|
||||
customers: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
.then((folders) => setFolders(folders));
|
||||
LoaderService.getInstance().show();
|
||||
FolderService.getFolders().then((processes: any[]) => {
|
||||
if (processes.length > 0) {
|
||||
let folders: any[] = processes.map((process: any) => process.processData);
|
||||
|
||||
// FilterBy customer.uid
|
||||
folders = folders.filter((folder: any) => folder.customers && folder.customers.length > 0 && folder.customers.some((customer: any) => customer.uid === customer.uid));
|
||||
|
||||
// OrderBy created_at desc
|
||||
folders = folders.sort((a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
||||
|
||||
setFolders(folders);
|
||||
LoaderService.getInstance().hide();
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSelectBlock = useCallback(
|
||||
@ -52,7 +51,7 @@ export default function SelectFolder() {
|
||||
router.push(
|
||||
Module.getInstance()
|
||||
.get()
|
||||
.modules.pages.ClientDashboard.props.path.replace("[folderUid]", folder.id ?? ""),
|
||||
.modules.pages.ClientDashboard.props.path.replace("[folderUid]", folder.id ?? "").replace("[profileUid]", customer.uid ?? ""),
|
||||
);
|
||||
},
|
||||
[router],
|
||||
|
@ -34,7 +34,7 @@
|
||||
"ClientDashboard": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/client-dashboard/[folderUid]",
|
||||
"path": "/client-dashboard/[folderUid]/profile/[profileUid]",
|
||||
"labelKey": "client-dashboard"
|
||||
},
|
||||
"pages": {
|
||||
@ -160,6 +160,13 @@
|
||||
"path": "/folders/select",
|
||||
"labelKey": "select_folder"
|
||||
}
|
||||
},
|
||||
"VerifyDocuments": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/folders/[folderUid]/verify-documents",
|
||||
"labelKey": "verify_documents"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
@ -34,7 +34,7 @@
|
||||
"ClientDashboard": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/client-dashboard/[folderUid]",
|
||||
"path": "/client-dashboard/[folderUid]/profile/[profileUid]",
|
||||
"labelKey": "client-dashboard"
|
||||
},
|
||||
"pages": {
|
||||
@ -160,6 +160,13 @@
|
||||
"path": "/folders/select",
|
||||
"labelKey": "select_folder"
|
||||
}
|
||||
},
|
||||
"VerifyDocuments": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/folders/[folderUid]/verify-documents",
|
||||
"labelKey": "verify_documents"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
@ -34,7 +34,7 @@
|
||||
"ClientDashboard": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/client-dashboard/[folderUid]",
|
||||
"path": "/client-dashboard/[folderUid]/profile/[profileUid]",
|
||||
"labelKey": "client-dashboard"
|
||||
},
|
||||
"pages": {
|
||||
@ -160,6 +160,13 @@
|
||||
"path": "/folders/select",
|
||||
"labelKey": "select_folder"
|
||||
}
|
||||
},
|
||||
"VerifyDocuments": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/folders/[folderUid]/verify-documents",
|
||||
"labelKey": "verify_documents"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
@ -34,7 +34,7 @@
|
||||
"ClientDashboard": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/client-dashboard/[folderUid]",
|
||||
"path": "/client-dashboard/[folderUid]/profile/[profileUid]",
|
||||
"labelKey": "client-dashboard"
|
||||
},
|
||||
"pages": {
|
||||
@ -160,6 +160,13 @@
|
||||
"path": "/folders/select",
|
||||
"labelKey": "select_folder"
|
||||
}
|
||||
},
|
||||
"VerifyDocuments": {
|
||||
"enabled": true,
|
||||
"props": {
|
||||
"path": "/folders/[folderUid]/verify-documents",
|
||||
"labelKey": "verify_documents"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
@ -27,7 +27,9 @@ export class FrontendVariables {
|
||||
|
||||
public HOTJAR_SITE_ID!: number;
|
||||
|
||||
public HOJAR_VERSION!: number;
|
||||
public HOTJAR_VERSION!: number;
|
||||
|
||||
public _4NK_URL!: string;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
|
@ -7,6 +7,7 @@ export default function useUser() {
|
||||
const [user, setUser] = useState<User | null>();
|
||||
|
||||
useEffect(() => {
|
||||
/* TODO: review
|
||||
const decodedJwt = JwtService.getInstance().decodeJwt();
|
||||
if (!decodedJwt) return;
|
||||
Users.getInstance()
|
||||
@ -18,6 +19,7 @@ export default function useUser() {
|
||||
.then((user) => {
|
||||
setUser(user);
|
||||
});
|
||||
*/
|
||||
}, []);
|
||||
|
||||
return {
|
||||
|
@ -38,25 +38,25 @@ export default class JwtService {
|
||||
public getUserJwtPayload(): IUserJwtPayload | undefined {
|
||||
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
|
||||
if (!accessToken) return;
|
||||
return jwt_decode(accessToken);
|
||||
return undefined; //jwt_decode(accessToken);
|
||||
}
|
||||
|
||||
public getCustomerJwtPayload(): ICustomerJwtPayload | undefined {
|
||||
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
|
||||
if (!accessToken) return;
|
||||
return jwt_decode(accessToken);
|
||||
return undefined; //jwt_decode(accessToken);
|
||||
}
|
||||
|
||||
public decodeJwt(): IUserJwtPayload | undefined {
|
||||
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
|
||||
if (!accessToken) return;
|
||||
return jwt_decode(accessToken);
|
||||
return undefined; //jwt_decode(accessToken);
|
||||
}
|
||||
|
||||
public decodeCustomerJwt(): ICustomerJwtPayload | undefined {
|
||||
const accessToken = CookieService.getInstance().getCookie("leCoffreAccessToken");
|
||||
if (!accessToken) return;
|
||||
return jwt_decode(accessToken);
|
||||
return undefined; //jwt_decode(accessToken);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -74,8 +74,7 @@ export default class JwtService {
|
||||
const headers = new Headers();
|
||||
headers.append("Authorization", `Bearer ${refreshToken}`);
|
||||
const response = await fetch(
|
||||
`${
|
||||
variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
`${variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
}/idnot/user/auth/refresh-token`,
|
||||
{ method: "POST", headers: headers },
|
||||
);
|
||||
@ -93,8 +92,7 @@ export default class JwtService {
|
||||
const headers = new Headers();
|
||||
headers.append("Authorization", `Bearer ${refreshToken}`);
|
||||
const response = await fetch(
|
||||
`${
|
||||
variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
`${variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
}/id360/customers/refresh-token`,
|
||||
{ method: "POST", headers: headers },
|
||||
);
|
||||
@ -122,8 +120,7 @@ export default class JwtService {
|
||||
const headers = new Headers();
|
||||
headers.append("Authorization", `Bearer ${refreshToken}`);
|
||||
const response = await fetch(
|
||||
`${
|
||||
variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
`${variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
}/idnot/user/auth/refresh-token`,
|
||||
{ method: "POST", headers: headers },
|
||||
);
|
||||
@ -141,8 +138,7 @@ export default class JwtService {
|
||||
const headers = new Headers();
|
||||
headers.append("Authorization", `Bearer ${refreshToken}`);
|
||||
const response = await fetch(
|
||||
`${
|
||||
variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
`${variables.BACK_API_PROTOCOL + variables.BACK_API_HOST + variables.BACK_API_ROOT_URL + variables.BACK_API_VERSION
|
||||
}/id360/customers/refresh-token`,
|
||||
{ method: "POST", headers: headers },
|
||||
);
|
||||
|
338
src/front/Services/PdfService/index.ts
Normal file
338
src/front/Services/PdfService/index.ts
Normal file
@ -0,0 +1,338 @@
|
||||
import { saveAs } from 'file-saver';
|
||||
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
||||
|
||||
const separator = '\x1f';
|
||||
|
||||
export interface CustomerInfo {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
postalAddress: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface NotaryInfo {
|
||||
name: string;
|
||||
// Add more notary fields as needed
|
||||
}
|
||||
|
||||
export interface Metadata {
|
||||
fileName: string,
|
||||
createdAt: Date,
|
||||
isDeleted: boolean,
|
||||
updatedAt: Date,
|
||||
commitmentId: string,
|
||||
documentUid: string;
|
||||
documentType: string;
|
||||
merkleProof: string;
|
||||
}
|
||||
|
||||
export interface CertificateData {
|
||||
customer: CustomerInfo;
|
||||
notary: NotaryInfo;
|
||||
folderUid: string;
|
||||
documentHash: string;
|
||||
metadata: Metadata;
|
||||
}
|
||||
|
||||
export default class PdfService {
|
||||
private static instance: PdfService;
|
||||
|
||||
public static getInstance(): PdfService {
|
||||
if (!PdfService.instance) {
|
||||
PdfService.instance = new PdfService();
|
||||
}
|
||||
return PdfService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a certificate PDF for a document
|
||||
* @param certificateData - Data needed for the certificate
|
||||
* @returns Promise<Blob> - The generated PDF as a blob
|
||||
*/
|
||||
public async generateCertificate(certificateData: CertificateData): Promise<Blob> {
|
||||
try {
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
const page = pdfDoc.addPage([595, 842]); // A4 size
|
||||
const { width, height } = page.getSize();
|
||||
|
||||
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||
const helveticaObliqueFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||
|
||||
let y = height - 40; // Start 40pt from the top
|
||||
const leftMargin = 20;
|
||||
const rightSectionX = 320;
|
||||
const lineSpacing = 16;
|
||||
|
||||
// Notary Information Section (Top Left)
|
||||
page.drawText('Notaire Validateur:', {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaBoldFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
page.drawText(certificateData.notary.name, {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
|
||||
// Customer Information Section (Top Right)
|
||||
let yRight = height - 40;
|
||||
page.drawText('Fournisseur de Document:', {
|
||||
x: rightSectionX,
|
||||
y: yRight,
|
||||
size: 12,
|
||||
font: helveticaBoldFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
yRight -= lineSpacing;
|
||||
page.drawText(`${certificateData.customer.firstName} ${certificateData.customer.lastName}`, {
|
||||
x: rightSectionX,
|
||||
y: yRight,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
yRight -= lineSpacing;
|
||||
page.drawText(certificateData.customer.email, {
|
||||
x: rightSectionX,
|
||||
y: yRight,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
yRight -= lineSpacing;
|
||||
page.drawText(certificateData.customer.postalAddress, {
|
||||
x: rightSectionX,
|
||||
y: yRight,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
|
||||
// Centered Title
|
||||
y -= 4 * lineSpacing; // Add more space between header and title
|
||||
const titleText = 'Certificat de Validation de Document';
|
||||
const titleWidth = helveticaBoldFont.widthOfTextAtSize(titleText, 20);
|
||||
page.drawText(titleText, {
|
||||
x: (width - titleWidth) / 2,
|
||||
y: y,
|
||||
size: 20,
|
||||
font: helveticaBoldFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
|
||||
// Add a line separator
|
||||
page.drawLine({
|
||||
start: { x: leftMargin, y: y },
|
||||
end: { x: width - leftMargin, y: y },
|
||||
thickness: 0.5,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
|
||||
// Document Information Section
|
||||
page.drawText('Informations du Document', {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaBoldFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
page.drawText(`UID du Dossier: ${certificateData.folderUid}`, {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
page.drawText(`Type de Document: ${certificateData.metadata.documentType}`, {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
page.drawText(`Nom du fichier: ${certificateData.metadata.fileName}`, {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
page.drawText(`Créé le: ${certificateData.metadata.createdAt.toLocaleDateString('fr-FR')}`, {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
page.drawText(`Dernière modification: ${certificateData.metadata.updatedAt.toLocaleDateString('fr-FR')}`, {
|
||||
x: leftMargin,
|
||||
y: y,
|
||||
size: 12,
|
||||
font: helveticaFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
y -= lineSpacing;
|
||||
|
||||
const keywords = [
|
||||
certificateData.documentHash,
|
||||
certificateData.metadata.commitmentId,
|
||||
JSON.stringify(certificateData.metadata.merkleProof)
|
||||
];
|
||||
pdfDoc.setKeywords([keywords.join(separator)]);
|
||||
|
||||
// Add explanatory text about certificate usage
|
||||
const explanatoryText = "Ce certificat doit être utilisé avec le document qu'il certifie pour être vérifié sur la page dédiée. Le document correspondant à ce certificat doit être téléchargé depuis LeCoffre et peut être conservé avec le certificat tant qu'il n'est pas modifié.";
|
||||
const explanatoryLines = this.splitTextToFit(helveticaObliqueFont, explanatoryText, width - (2 * leftMargin), 11);
|
||||
y -= (explanatoryLines.length * 12) + 40; // Space after verification data
|
||||
explanatoryLines.forEach((line, index) => {
|
||||
page.drawText(line, {
|
||||
x: leftMargin,
|
||||
y: y - (index * 14), // Slightly more spacing for readability
|
||||
size: 11,
|
||||
font: helveticaObliqueFont,
|
||||
color: rgb(0.3, 0.3, 0.3) // Slightly grayed out to distinguish from main content
|
||||
});
|
||||
});
|
||||
|
||||
// Footer
|
||||
const footerText1 = `Page 1 sur 1`;
|
||||
const footerText2 = `Généré le ${new Date().toLocaleString('fr-FR')}`;
|
||||
const footerWidth1 = helveticaObliqueFont.widthOfTextAtSize(footerText1, 10);
|
||||
const footerWidth2 = helveticaObliqueFont.widthOfTextAtSize(footerText2, 10);
|
||||
page.drawText(footerText1, {
|
||||
x: (width - footerWidth1) / 2,
|
||||
y: 35,
|
||||
size: 10,
|
||||
font: helveticaObliqueFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
page.drawText(footerText2, {
|
||||
x: (width - footerWidth2) / 2,
|
||||
y: 25,
|
||||
size: 10,
|
||||
font: helveticaObliqueFont,
|
||||
color: rgb(0, 0, 0)
|
||||
});
|
||||
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
return new Blob([pdfBytes], { type: 'application/pdf' });
|
||||
} catch (error) {
|
||||
console.error('Error generating certificate:', error);
|
||||
throw new Error('Failed to generate certificate');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split text to fit within a specified width
|
||||
* @param font - PDF font instance
|
||||
* @param text - Text to split
|
||||
* @param maxWidth - Maximum width in points
|
||||
* @param fontSize - Font size
|
||||
* @returns Array of text lines
|
||||
*/
|
||||
private splitTextToFit(font: any, text: string, maxWidth: number, fontSize: number): string[] {
|
||||
const lines: string[] = [];
|
||||
let currentLine = '';
|
||||
|
||||
// Split by characters (pdf-lib doesn't have word-level text measurement)
|
||||
const chars = text.split('');
|
||||
|
||||
for (const char of chars) {
|
||||
const testLine = currentLine + char;
|
||||
const testWidth = font.widthOfTextAtSize(testLine, fontSize);
|
||||
|
||||
if (testWidth <= maxWidth) {
|
||||
currentLine = testLine;
|
||||
} else {
|
||||
if (currentLine) {
|
||||
lines.push(currentLine);
|
||||
currentLine = char;
|
||||
} else {
|
||||
// If even a single character is too wide, force a break
|
||||
lines.push(char);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLine) {
|
||||
lines.push(currentLine);
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a certificate PDF
|
||||
* @param certificateData - Data needed for the certificate
|
||||
* @param filename - Optional filename for the download
|
||||
*/
|
||||
public async downloadCertificate(certificateData: CertificateData, filename?: string): Promise<void> {
|
||||
try {
|
||||
const pdfBlob = await this.generateCertificate(certificateData);
|
||||
const defaultFilename = `certificate_${certificateData.metadata.documentUid}_${new Date().toISOString().split('T')[0]}.pdf`;
|
||||
saveAs(pdfBlob, filename || defaultFilename);
|
||||
} catch (error) {
|
||||
console.error('Error downloading certificate:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a PDF certificate and extract document information
|
||||
* @param pdfBlob - The PDF file as a blob
|
||||
* @returns Promise<{documentHash: string, documentUid: string, commitmentId: string, merkleProof?: string}> - Extracted information
|
||||
*/
|
||||
public async parseCertificate(certificateFile: File): Promise<{ documentHash: string, commitmentId: string, merkleProof: any }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fileReader = new FileReader();
|
||||
|
||||
fileReader.onload = async () => {
|
||||
try {
|
||||
// Read the metadata and get the validation data from the keywords
|
||||
const pdfDoc = await PDFDocument.load(await certificateFile.arrayBuffer());
|
||||
const keywords = pdfDoc.getKeywords()?.split(separator);
|
||||
|
||||
if (!keywords) {
|
||||
throw new Error("No keywords found in certificate");
|
||||
}
|
||||
|
||||
if (keywords.length !== 3) {
|
||||
throw new Error("Invalid keywords found in certificate");
|
||||
}
|
||||
|
||||
const documentHash = keywords[0];
|
||||
const commitmentId = keywords[1];
|
||||
const merkleProof = keywords[2];
|
||||
|
||||
if (!documentHash || !commitmentId || !merkleProof) {
|
||||
throw new Error("Invalid keywords found in certificate");
|
||||
}
|
||||
|
||||
resolve({ documentHash, commitmentId, merkleProof });
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
fileReader.onerror = () => {
|
||||
reject(new Error('Failed to read PDF file'));
|
||||
};
|
||||
|
||||
fileReader.readAsArrayBuffer(certificateFile);
|
||||
});
|
||||
}
|
||||
}
|
211
src/front/Services/WatermarkService/index.ts
Normal file
211
src/front/Services/WatermarkService/index.ts
Normal file
@ -0,0 +1,211 @@
|
||||
export default class WatermarkService {
|
||||
private static instance: WatermarkService;
|
||||
|
||||
public static getInstance(): WatermarkService {
|
||||
if (!WatermarkService.instance) {
|
||||
WatermarkService.instance = new WatermarkService();
|
||||
}
|
||||
return WatermarkService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a watermark to a file based on its type
|
||||
* @param file - The original file
|
||||
* @returns Promise<File> - The file with watermark added
|
||||
*/
|
||||
public async addWatermark(file: File): Promise<File> {
|
||||
const fileType = file.type;
|
||||
|
||||
try {
|
||||
if (fileType.startsWith('image/')) {
|
||||
return await this.addWatermarkToImage(file);
|
||||
} else if (fileType === 'application/pdf') {
|
||||
return await this.addWatermarkToPdf(file);
|
||||
} else {
|
||||
// For other file types, return the original file
|
||||
console.warn(`Watermark not supported for file type: ${fileType}`);
|
||||
return file;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error adding watermark:', error);
|
||||
// Return original file if watermarking fails
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add watermark to image files
|
||||
* @param file - Image file
|
||||
* @returns Promise<File> - Image with watermark
|
||||
*/
|
||||
private async addWatermarkToImage(file: File): Promise<File> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
try {
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
try {
|
||||
// Create canvas
|
||||
const canvas = document.createElement('canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
if (!ctx) {
|
||||
reject(new Error('Could not get canvas context'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Set canvas size to image size
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
|
||||
// Draw original image
|
||||
ctx.drawImage(img, 0, 0);
|
||||
|
||||
// Add watermark
|
||||
this.addImageWatermark(ctx, img.width, img.height);
|
||||
|
||||
// Convert to blob
|
||||
canvas.toBlob((blob) => {
|
||||
if (blob) {
|
||||
const watermarkedFile = new File([blob], file.name, { type: file.type });
|
||||
resolve(watermarkedFile);
|
||||
} else {
|
||||
reject(new Error('Could not create blob from canvas'));
|
||||
}
|
||||
}, file.type);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
img.onerror = reject;
|
||||
img.src = event.target?.result as string;
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add watermark to PDF files
|
||||
* @param file - PDF file
|
||||
* @returns Promise<File> - PDF with watermark
|
||||
*/
|
||||
private async addWatermarkToPdf(file: File): Promise<File> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (event) => {
|
||||
try {
|
||||
const arrayBuffer = event.target?.result as ArrayBuffer;
|
||||
|
||||
// Import pdf-lib dynamically to avoid SSR issues
|
||||
const { PDFDocument, rgb } = await import('pdf-lib');
|
||||
|
||||
// Load the existing PDF
|
||||
const pdfDoc = await PDFDocument.load(arrayBuffer);
|
||||
|
||||
// Get all pages
|
||||
const pages = pdfDoc.getPages();
|
||||
|
||||
// Add watermark to each page
|
||||
for (const page of pages) {
|
||||
this.addPdfWatermark(page, rgb(0.8, 0.2, 0.2)); // Pale red color
|
||||
}
|
||||
|
||||
// Save the modified PDF
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
const watermarkedFile = new File([pdfBytes], file.name, { type: file.type });
|
||||
resolve(watermarkedFile);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error adding watermark to PDF:', error);
|
||||
// If PDF watermarking fails, return original file
|
||||
resolve(file);
|
||||
}
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add watermark to image using Canvas
|
||||
* @param ctx - Canvas 2D context
|
||||
* @param width - Image width
|
||||
* @param height - Image height
|
||||
*/
|
||||
private addImageWatermark(ctx: CanvasRenderingContext2D, width: number, height: number): void {
|
||||
// Save current state
|
||||
ctx.save();
|
||||
|
||||
// Set watermark properties
|
||||
ctx.fillStyle = 'rgba(128, 128, 128, 0.7)'; // Semi-transparent gray
|
||||
ctx.font = '12px Arial';
|
||||
ctx.textAlign = 'right';
|
||||
ctx.textBaseline = 'bottom';
|
||||
|
||||
// Position watermark in bottom-right corner
|
||||
const text = 'Processed by LeCoffre';
|
||||
const x = width - 10; // 10 pixels from right edge
|
||||
const y = height - 10; // 10 pixels from bottom
|
||||
|
||||
// Add watermark text
|
||||
ctx.fillText(text, x, y);
|
||||
|
||||
// Restore state
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add watermark to PDF using pdf-lib
|
||||
* @param page - PDF page from pdf-lib
|
||||
* @param color - Color for the watermark
|
||||
*/
|
||||
private addPdfWatermark(page: any, color: any): void {
|
||||
const { width, height } = page.getSize();
|
||||
|
||||
// Calculate watermark position (bottom-right corner)
|
||||
const text = 'Processed by LeCoffre';
|
||||
const dateTime = new Date().toLocaleString('fr-FR', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
|
||||
const fontSize = 10;
|
||||
const lineHeight = 12; // Space between lines
|
||||
|
||||
// Calculate text widths (approximate - pdf-lib doesn't have a direct method for this)
|
||||
// Using a conservative estimate: ~6 points per character for 10pt font
|
||||
const estimatedTextWidth1 = text.length * 6;
|
||||
const estimatedTextWidth2 = dateTime.length * 6;
|
||||
const maxTextWidth = Math.max(estimatedTextWidth1, estimatedTextWidth2);
|
||||
|
||||
// Position watermark with proper margins (20 points from edges)
|
||||
const x = width - maxTextWidth - 20; // 20 points from right edge
|
||||
const y = 20; // 20 points from bottom
|
||||
|
||||
// Add watermark text with transparency (first line)
|
||||
page.drawText(text, {
|
||||
x: x,
|
||||
y: y + lineHeight, // Second line (top)
|
||||
size: fontSize,
|
||||
color: color,
|
||||
opacity: 0.7
|
||||
});
|
||||
|
||||
// Add date/time with transparency (second line)
|
||||
page.drawText(dateTime, {
|
||||
x: x,
|
||||
y: y, // First line (bottom)
|
||||
size: fontSize,
|
||||
color: color,
|
||||
opacity: 0.7
|
||||
});
|
||||
}
|
||||
}
|
@ -4,30 +4,23 @@ import CookieService from "@Front/Services/CookieService/CookieService";
|
||||
import EventEmitter from "@Front/Services/EventEmitter";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
|
||||
import User from "src/sdk/User";
|
||||
|
||||
export default class UserStore {
|
||||
public static readonly instance = new this();
|
||||
protected readonly event = new EventEmitter();
|
||||
public accessToken: string | null = null;
|
||||
public refreshToken: string | null = null;
|
||||
|
||||
private constructor() { }
|
||||
|
||||
public isConnected(): boolean {
|
||||
return !!this.accessToken;
|
||||
return !!CookieService.getInstance().getCookie("leCoffreAccessToken");
|
||||
}
|
||||
|
||||
public getRole(): string | undefined {
|
||||
const decodedPayload = JwtService.getInstance().decodeJwt();
|
||||
return decodedPayload?.role;
|
||||
}
|
||||
|
||||
public async connect(accessToken: string, refreshToken: string) {
|
||||
public async connect(user: any) {
|
||||
try {
|
||||
//Save tokens in cookies
|
||||
CookieService.getInstance().setCookie("leCoffreAccessToken", accessToken);
|
||||
CookieService.getInstance().setCookie("leCoffreRefreshToken", refreshToken);
|
||||
|
||||
this.event.emit("connection", this.accessToken);
|
||||
CookieService.getInstance().setCookie("leCoffreAccessToken", JSON.stringify(user));
|
||||
this.event.emit("connection", CookieService.getInstance().getCookie("leCoffreAccessToken"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
@ -37,11 +30,11 @@ export default class UserStore {
|
||||
|
||||
public async disconnect() {
|
||||
try {
|
||||
User.getInstance().clear();
|
||||
|
||||
//Remove tokens from cookies
|
||||
CookieService.getInstance().deleteCookie("leCoffreAccessToken");
|
||||
CookieService.getInstance().deleteCookie("leCoffreRefreshToken");
|
||||
|
||||
this.event.emit("disconnection", this.accessToken);
|
||||
this.event.emit("disconnection", CookieService.getInstance().getCookie("leCoffreAccessToken"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
@ -56,4 +49,8 @@ export default class UserStore {
|
||||
this.event.on("connection", callback);
|
||||
return () => this.event.off("connection", callback);
|
||||
}
|
||||
|
||||
public getUser(): any {
|
||||
return JSON.parse(CookieService.getInstance().getCookie("leCoffreAccessToken") || "");
|
||||
}
|
||||
}
|
||||
|
@ -2,32 +2,24 @@
|
||||
|
||||
import CookieService from "@Front/Services/CookieService/CookieService";
|
||||
import EventEmitter from "@Front/Services/EventEmitter";
|
||||
import JwtService from "@Front/Services/JwtService/JwtService";
|
||||
|
||||
import User from "src/sdk/User";
|
||||
|
||||
export default class UserStore {
|
||||
public static readonly instance = new this();
|
||||
protected readonly event = new EventEmitter();
|
||||
public accessToken: string | null = null;
|
||||
public refreshToken: string | null = null;
|
||||
|
||||
private constructor() { }
|
||||
|
||||
public isConnected(): boolean {
|
||||
return !!this.accessToken;
|
||||
return !!CookieService.getInstance().getCookie("leCoffreAccessToken");
|
||||
}
|
||||
|
||||
public getRole(): string | undefined {
|
||||
const decodedPayload = JwtService.getInstance().decodeJwt();
|
||||
return decodedPayload?.role;
|
||||
}
|
||||
|
||||
public async connect(accessToken: string, refreshToken: string) {
|
||||
public async connect(user: any) {
|
||||
try {
|
||||
//Save tokens in cookies
|
||||
CookieService.getInstance().setCookie("leCoffreAccessToken", accessToken);
|
||||
CookieService.getInstance().setCookie("leCoffreRefreshToken", refreshToken);
|
||||
|
||||
this.event.emit("connection", this.accessToken);
|
||||
CookieService.getInstance().setCookie("leCoffreAccessToken", JSON.stringify(user));
|
||||
this.event.emit("connection", CookieService.getInstance().getCookie("leCoffreAccessToken"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
@ -37,11 +29,11 @@ export default class UserStore {
|
||||
|
||||
public async disconnect() {
|
||||
try {
|
||||
User.getInstance().clear();
|
||||
|
||||
//Remove tokens from cookies
|
||||
CookieService.getInstance().deleteCookie("leCoffreAccessToken");
|
||||
CookieService.getInstance().deleteCookie("leCoffreRefreshToken");
|
||||
|
||||
this.event.emit("disconnection", this.accessToken);
|
||||
this.event.emit("disconnection", CookieService.getInstance().getCookie("leCoffreAccessToken"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
@ -56,4 +48,8 @@ export default class UserStore {
|
||||
this.event.on("connection", callback);
|
||||
return () => this.event.off("connection", callback);
|
||||
}
|
||||
|
||||
public getUser(): any {
|
||||
return JSON.parse(CookieService.getInstance().getCookie("leCoffreAccessToken") || "");
|
||||
}
|
||||
}
|
||||
|
@ -8,6 +8,7 @@ export async function middleware(request: NextRequest) {
|
||||
const cookies = request.cookies.get("leCoffreAccessToken");
|
||||
if (!cookies) return NextResponse.redirect(new URL("/", request.url));
|
||||
|
||||
/*
|
||||
// Decode it
|
||||
const userDecodedToken = jwt_decode(cookies.value) as IUserJwtPayload;
|
||||
const customerDecodedToken = jwt_decode(cookies.value) as ICustomerJwtPayload;
|
||||
@ -23,6 +24,7 @@ export async function middleware(request: NextRequest) {
|
||||
if (customerDecodedToken.customerId && customerDecodedToken.exp < now) {
|
||||
return NextResponse.redirect(new URL("/id360/customer-callback", request.url));
|
||||
}
|
||||
*/
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
@ -3,11 +3,18 @@ import { DefaultLayout } from "@Front/Components/LayoutTemplates/DefaultLayout";
|
||||
import { FrontendVariables } from "@Front/Config/VariablesFront";
|
||||
import type { NextPage } from "next";
|
||||
import type { AppType, AppProps } from "next/app";
|
||||
import { useEffect, type ReactElement, type ReactNode } from "react";
|
||||
import { useEffect, useState, type ReactElement, type ReactNode } from "react";
|
||||
import getConfig from "next/config";
|
||||
import { GoogleTagManager } from "@next/third-parties/google";
|
||||
import { hotjar } from "react-hotjar";
|
||||
|
||||
import Loader from "src/common/Api/LeCoffreApi/sdk/Loader";
|
||||
|
||||
import IframeReference from "src/sdk/IframeReference";
|
||||
import Iframe from "src/sdk/Iframe";
|
||||
import MessageBus from "src/sdk/MessageBus";
|
||||
import User from "src/sdk/User";
|
||||
|
||||
export type NextPageWithLayout<TProps = Record<string, unknown>, TInitialProps = TProps> = NextPage<TProps, TInitialProps> & {
|
||||
getLayout?: (page: ReactElement) => ReactNode;
|
||||
};
|
||||
@ -28,6 +35,7 @@ type AppPropsWithLayout = AppProps & {
|
||||
docaposteApiUrl: string;
|
||||
hotjarSiteId: number;
|
||||
hotjarVersion: number;
|
||||
_4nkUrl: string;
|
||||
};
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
@ -48,6 +56,7 @@ const MyApp = (({
|
||||
docaposteApiUrl,
|
||||
hotjarSiteId,
|
||||
hotjarVersion,
|
||||
_4nkUrl,
|
||||
}: AppPropsWithLayout) => {
|
||||
const getLayout = Component.getLayout ?? ((page) => <DefaultLayout children={page}></DefaultLayout>);
|
||||
|
||||
@ -64,7 +73,30 @@ const MyApp = (({
|
||||
instance.FC_CLIENT_ID = fcClientId;
|
||||
instance.DOCAPOST_API_URL = docaposteApiUrl;
|
||||
instance.HOTJAR_SITE_ID = hotjarSiteId;
|
||||
instance.HOJAR_VERSION = hotjarVersion;
|
||||
instance.HOTJAR_VERSION = hotjarVersion;
|
||||
instance._4NK_URL = _4nkUrl;
|
||||
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
|
||||
IframeReference.setTargetOrigin(_4nkUrl);
|
||||
|
||||
useEffect(() => {
|
||||
const isAuthenticated = User.getInstance().isAuthenticated();
|
||||
setIsConnected(isAuthenticated);
|
||||
|
||||
if (isAuthenticated) {
|
||||
MessageBus.getInstance().initMessageListener();
|
||||
MessageBus.getInstance().isReady().then(() => setIsReady(true));
|
||||
|
||||
return () => {
|
||||
MessageBus.getInstance().destroyMessageListener();
|
||||
};
|
||||
}
|
||||
|
||||
return () => { };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hotjarSiteId || !hotjarVersion) {
|
||||
console.warn("No hotjar site id or version provided");
|
||||
@ -78,9 +110,15 @@ const MyApp = (({
|
||||
}, [hotjarSiteId, hotjarVersion]);
|
||||
|
||||
return getLayout(
|
||||
<>
|
||||
{((isConnected && isReady) || !isConnected) &&
|
||||
<Component {...pageProps}>
|
||||
<GoogleTagManager gtmId="GTM-5GLJN86P" />
|
||||
</Component>,
|
||||
</Component>
|
||||
}
|
||||
{isConnected && <Iframe />}
|
||||
<Loader />
|
||||
</>
|
||||
);
|
||||
}) as AppType;
|
||||
|
||||
@ -100,6 +138,7 @@ MyApp.getInitialProps = async () => {
|
||||
docaposteApiUrl: publicRuntimeConfig.NEXT_PUBLIC_DOCAPOST_API_URL,
|
||||
hotjarSiteId: publicRuntimeConfig.NEXT_PUBLIC_HOTJAR_SITE_ID,
|
||||
hotjarVersion: publicRuntimeConfig.NEXT_PUBLIC_HOTJAR_VERSION,
|
||||
_4nkUrl: publicRuntimeConfig.NEXT_PUBLIC_4NK_URL,
|
||||
};
|
||||
};
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user