Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TRA 15352] Remonter le VHU en situation irrégulière (sans émetteur TD) dans l'onglet À collecter #3792

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ et le projet suit un schéma de versionning inspiré de [Calendar Versioning](ht
#### :nail_care: Améliorations

- Permettre au transporteur étranger d'avoir les mêmes droits qu'un transporteur FR concernant la révision sur une Annexe 1 [PR 3770](https://github.com/MTES-MCT/trackdechets/pull/3770)
- Remonter le VHU en situation irrégulière (sans émetteur TD) dans l'onglet À collecter du transporteur [PR 3792](https://github.com/MTES-MCT/trackdechets/pull/3792)

#### :bug: Corrections de bugs

Expand Down
1 change: 1 addition & 0 deletions back/src/bsds/resolvers/mutations/utils/clone.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,7 @@ export const cloneBsvhu = async (user: Express.User, id: string) => {
emitterEmissionSignatureDate: bsvhu.emitterEmissionSignatureDate,
emitterIrregularSituation: bsvhu.emitterIrregularSituation,
emitterNoSiret: bsvhu.emitterNoSiret,
emitterNotOnTD: bsvhu.emitterNotOnTD,
identificationNumbers: bsvhu.identificationNumbers,
identificationType: bsvhu.identificationType,
intermediaries: bsvhu.intermediaries.length
Expand Down
8 changes: 8 additions & 0 deletions back/src/bsvhu/elastic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,14 @@ export function getWhere(bsvhu: BsvhuForElastic): Pick<BsdElastic, WhereKeys> {
for (const fieldName of siretsFilters.keys()) {
setTab(siretsFilters, fieldName, "isDraftFor");
}
} else if (bsvhu.emitterNotOnTD) {
// even though the emitter is not on TD, we still add the SIRET to the index
// so if the account is created after the BSVHU, it will still appear in the
// emitter's dashboard.
setTab(siretsFilters, "emitterCompanySiret", "isForActionFor");
setTab(siretsFilters, "transporterCompanySiret", "isToCollectFor");
} else if (bsvhu.emitterNoSiret) {
setTab(siretsFilters, "transporterCompanySiret", "isToCollectFor");
} else {
setTab(siretsFilters, "emitterCompanySiret", "isForActionFor");
setTab(siretsFilters, "transporterCompanySiret", "isFollowFor");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ describe("mutaion.duplicateBsvhu", () => {
opt: {
emitterIrregularSituation: false,
emitterNoSiret: false,
emitterNotOnTD: false,
emitterCompanySiret: emitter.company.siret,
emitterCompanyName: emitter.company.name,
emitterCompanyAddress: emitter.company.address,
Expand Down Expand Up @@ -185,6 +186,14 @@ describe("mutaion.duplicateBsvhu", () => {
traderRecepisseValidityLimit: traderReceipt.validityLimit
}
});

const searchResults = {
[emitter.company.siret!]: emitter.company
};

(searchCompany as jest.Mock).mockImplementation((clue: string) => {
return Promise.resolve(searchResults[clue]);
});
const { mutate } = makeClient(emitter.user);

const { errors, data } = await mutate<Pick<Mutation, "duplicateBsvhu">>(
Expand All @@ -202,6 +211,7 @@ describe("mutaion.duplicateBsvhu", () => {
const {
emitterIrregularSituation,
emitterNoSiret,
emitterNotOnTD,
emitterAgrementNumber,
emitterCompanyName,
emitterCompanySiret,
Expand Down Expand Up @@ -313,6 +323,7 @@ describe("mutaion.duplicateBsvhu", () => {
expect(duplicatedBsvhu).toMatchObject({
emitterIrregularSituation,
emitterNoSiret,
emitterNotOnTD,
emitterAgrementNumber,
emitterCompanyName,
emitterCompanySiret,
Expand Down
1 change: 1 addition & 0 deletions back/src/bsvhu/validation/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export type BsvhuEditableFields = Required<
| "isDraft"
| "isDeleted"
| "emitterCustomInfo"
| "emitterNotOnTD"
| "destinationCustomInfo"
| "transporterCustomInfo"
| "transporterTransportPlates"
Expand Down
4 changes: 4 additions & 0 deletions back/src/bsvhu/validation/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ const rawBsvhuSchema = z.object({
.boolean()
.nullish()
.transform(v => Boolean(v)),
emitterNotOnTD: z.coerce
.boolean()
.nullish()
.transform(v => Boolean(v)),
emitterCompanyName: z.string().nullish(),
emitterCompanySiret: siretSchema(CompanyRole.Emitter).nullish(),
emitterCompanyAddress: z.string().nullish(),
Expand Down
3 changes: 3 additions & 0 deletions back/src/bsvhu/validation/sirenify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ const sirenifyBsvhuAccessors = (
{
siret: bsvhu?.emitterCompanySiret,
skip: sealedFields.includes("emitterCompanySiret") || bsvhu.emitterNoSiret,
setterIfNotFound: input => {
input.emitterNotOnTD = true;
},
setter: (input, companyInput) => {
input.emitterCompanyName = companyInput.name;
input.emitterCompanyAddress = companyInput.address;
Expand Down
6 changes: 5 additions & 1 deletion back/src/companies/sirenify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ export default function buildSirenify<T>(
export type NextCompanyInputAccessor<T> = {
siret: string | null | undefined;
skip: boolean;
setterIfNotFound?: (input: T) => void;
setter: (
input: T,
data: {
Expand Down Expand Up @@ -152,8 +153,11 @@ export function nextBuildSirenify<T>(
const sirenifiedInput = { ...input };

for (const [idx, companySearchResult] of companySearchResults.entries()) {
const { setter } = accessors[idx];
const { setter, setterIfNotFound } = accessors[idx];
if (!companySearchResult) {
if (setterIfNotFound) {
setterIfNotFound(sirenifiedInput);
}
continue;
}
const company = companySearchResult as CompanySearchResult;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Bsvhu" ADD COLUMN "emitterNotOnTD" BOOLEAN DEFAULT false;
1 change: 1 addition & 0 deletions libs/back/prisma/src/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,7 @@ model Bsvhu {

emitterIrregularSituation Boolean? @default(false)
emitterNoSiret Boolean? @default(false)
emitterNotOnTD Boolean? @default(false)
emitterAgrementNumber String? @db.VarChar(100)
emitterCompanyName String?
emitterCompanySiret String? @db.VarChar(17)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { Bsvhu, BsvhuStatus } from "@prisma/client";
import { prisma } from "@td/prisma";
import { logger } from "@td/logger";
import Queue, { JobOptions } from "bull";
import { searchCompanyFailFast } from "back/src/companies/sirenify";

const { REDIS_URL, NODE_ENV } = process.env;

const INDEX_QUEUE_NAME = `queue_index_elastic_${NODE_ENV}`;
const indexQueue = new Queue<string>(INDEX_QUEUE_NAME, REDIS_URL!, {
defaultJobOptions: {
attempts: 3,
backoff: { type: "fixed", delay: 100 },
removeOnComplete: 10_000,
timeout: 10000
}
});

async function enqueueUpdatedBsdToIndex(
bsdId: string,
options?: JobOptions
): Promise<void> {
logger.info(`Enqueuing BSD ${bsdId} for indexation`);
await indexQueue.add("index_updated", bsdId, options);
}

export async function run() {
logger.info("starting BSVHU emitter not on TD script");
let finished = false;
let lastId: string | null = null;

while (!finished) {
let bsvhus: Bsvhu[] = [];
try {
bsvhus = await prisma.bsvhu.findMany({
take: 10,
...(lastId
? {
cursor: {
id: lastId
},
skip: 1 // Skip the cursor
}
: {}),
where: {
AND: [
{
isDraft: false
},
{
emitterIrregularSituation: true
},
{
status: BsvhuStatus.INITIAL
},
{
NOT: {
isDeleted: true
}
},
{
NOT: {
emitterNoSiret: true
}
}
]
},
orderBy: {
id: "asc"
}
});
} catch (error) {
logger.error(`failed to fetch bsvhus from cursor ${lastId}`);
logger.error(error);
break;
}
logger.info(`got BSVHUs ${bsvhus.map(bsvhu => bsvhu.id).join(", ")}`);
if (bsvhus.length < 10) {
finished = true;
}
if (bsvhus.length === 0) {
break;
}
lastId = bsvhus[bsvhus.length - 1].id;
for (const bsvhu of bsvhus) {
logger.info(`handling ${bsvhu.id}`);
if (bsvhu.emitterCompanySiret) {
const emitterCompany = await searchCompanyFailFast(
bsvhu.emitterCompanySiret
);
if (!emitterCompany) {
logger.info(`updating ${bsvhu.id}`);
await prisma.bsvhu.update({
where: { id: bsvhu.id },
data: {
emitterNotOnTD: true
},
select: {
id: true
}
});
enqueueUpdatedBsdToIndex(bsvhu.id);
}
logger.info(`handled ${bsvhu.id}`);
}
}
}
}