@7365admin1/core 3.96.1-staging.369 → 3.96.1-staging.370

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ ---
2
+ "@7365admin1/core": minor
3
+ ---
4
+
5
+ Service-provider invitations can no longer read "Accepted" without the site on the provider's Sites list. Opening the email link (`PATCH /auth/verification/status`), the old `POST /service-providers/id/:id` route and creating an organisation from the invitation no longer mark it complete; only Accept does, and Accept adds the site in the same transaction. New `PUT /service-provider-invitations/:id/link-site` (`linkSite`) adds the site for an already-accepted invitation whose site never arrived (invited account, company administrator, accepted and not deleted, never for an invitation accepted for another company; idempotent). The received list reports `needsSiteLink`; `onThisOrg` is read from the Sites list itself.
package/dist/index.d.ts CHANGED
@@ -5960,6 +5960,7 @@ declare function useCustomerSiteRepo(): {
5960
5960
  org: string | ObjectId;
5961
5961
  }) => Promise<TCustomerSite[]>;
5962
5962
  countActiveByOrgAndSite: (org: string | ObjectId, site: string | ObjectId) => Promise<number>;
5963
+ countAnyByOrgAndSite: (org: string | ObjectId, site: string | ObjectId, session?: ClientSession) => Promise<number>;
5963
5964
  getBySiteAsServiceProvider: (site: string | ObjectId) => Promise<{} | undefined>;
5964
5965
  getById: (id: string | ObjectId) => Promise<mongodb.WithId<bson.Document>>;
5965
5966
  updateCustomerSiteById: (id: string | ObjectId, payload: Partial<TCustomerSite>, session?: ClientSession) => Promise<mongodb.WithId<bson.Document>>;
@@ -5982,6 +5983,13 @@ declare function useCustomerSiteService(): {
5982
5983
  providerOrgId: string;
5983
5984
  providerOrgName: string;
5984
5985
  }>;
5986
+ linkAcceptedInvite: (invite: string, actor: {
5987
+ id?: string;
5988
+ name?: string;
5989
+ }, forOrgId: string) => Promise<{
5990
+ linked: boolean;
5991
+ message: string;
5992
+ }>;
5985
5993
  updateCusSiteById: (customerSiteId: string, payload: Partial<TCustomerSite>) => Promise<mongodb.WithId<bson.Document>>;
5986
5994
  };
5987
5995
 
@@ -14948,12 +14956,14 @@ declare function useVerificationRepoV2(): {
14948
14956
  createTextIndex: () => Promise<void>;
14949
14957
  add: (value: TVerificationV2, session?: ClientSession) => Promise<ObjectId>;
14950
14958
  getServiceProviderInviteById: (id: string | ObjectId) => Promise<TVerificationV2 | null>;
14951
- transitionServiceProviderInvite: ({ id, from, to, event, set, session, }: {
14959
+ transitionServiceProviderInvite: ({ id, from, to, event, set, where, session, }: {
14952
14960
  id: string | ObjectId;
14953
14961
  from: string[];
14954
14962
  to?: string | undefined;
14955
14963
  event: TVerificationEvent;
14956
14964
  set?: Record<string, any> | undefined;
14965
+ /** Extra conditions the row must still meet for the write to happen. */
14966
+ where?: Record<string, any> | undefined;
14957
14967
  session?: ClientSession | undefined;
14958
14968
  }) => Promise<any>;
14959
14969
  getServiceProviderInvites: ({ statuses, orgIds, email, search, includeDeleted, page, limit, }: {
@@ -15237,6 +15247,7 @@ declare function useServiceProviderInviteController(): {
15237
15247
  remove: (req: Request, res: Response, next: NextFunction) => Promise<void>;
15238
15248
  decline: (req: Request, res: Response, next: NextFunction) => Promise<void>;
15239
15249
  accept: (req: Request, res: Response, next: NextFunction) => Promise<void>;
15250
+ linkSite: (req: Request, res: Response, next: NextFunction) => Promise<void>;
15240
15251
  received: (req: Request, res: Response, next: NextFunction) => Promise<void>;
15241
15252
  getOne: (req: Request, res: Response, next: NextFunction) => Promise<void>;
15242
15253
  };
@@ -15332,6 +15343,13 @@ declare function useServiceProviderInviteService(): {
15332
15343
  }) => Promise<{
15333
15344
  message: string;
15334
15345
  }>;
15346
+ linkSite: ({ id, userId, org, }: {
15347
+ id: string;
15348
+ userId?: string | undefined;
15349
+ org?: string | undefined;
15350
+ }) => Promise<{
15351
+ message: string;
15352
+ }>;
15335
15353
  listReceived: ({ userId, org, status, }: {
15336
15354
  userId?: string | undefined;
15337
15355
  org?: string | undefined;
@@ -15352,6 +15370,7 @@ declare function useServiceProviderInviteService(): {
15352
15370
  providerOrgId: any;
15353
15371
  providerOrgName: string;
15354
15372
  onThisOrg: boolean;
15373
+ needsSiteLink: boolean;
15355
15374
  }[];
15356
15375
  counts: Record<string, number>;
15357
15376
  }>;
@@ -15375,6 +15394,7 @@ declare function useServiceProviderInviteService(): {
15375
15394
  providerOrgId: any;
15376
15395
  providerOrgName: string;
15377
15396
  onThisOrg: boolean;
15397
+ needsSiteLink: boolean;
15378
15398
  }>;
15379
15399
  notifyProvider: (invite: TVerificationV2) => Promise<void>;
15380
15400
  };
package/dist/index.js CHANGED
@@ -8359,6 +8359,7 @@ function useVerificationRepoV2() {
8359
8359
  to,
8360
8360
  event,
8361
8361
  set = {},
8362
+ where = {},
8362
8363
  session
8363
8364
  }) {
8364
8365
  let _id;
@@ -8373,7 +8374,7 @@ function useVerificationRepoV2() {
8373
8374
  };
8374
8375
  if (to)
8375
8376
  $set.status = to;
8376
- const filter = { _id };
8377
+ const filter = { ...where, _id };
8377
8378
  if (from.length > 0)
8378
8379
  filter.status = { $in: from };
8379
8380
  try {
@@ -8828,6 +8829,15 @@ function useCustomerSiteRepo() {
8828
8829
  }
8829
8830
  return await collection.countDocuments({ org, site, status: "active" });
8830
8831
  }
8832
+ async function countAnyByOrgAndSite(org, site, session) {
8833
+ try {
8834
+ org = new import_mongodb24.ObjectId(org);
8835
+ site = new import_mongodb24.ObjectId(site);
8836
+ } catch {
8837
+ throw new import_node_server_utils26.BadRequestError("Invalid ID.");
8838
+ }
8839
+ return await collection.countDocuments({ org, site }, { session });
8840
+ }
8831
8841
  async function getById(id) {
8832
8842
  try {
8833
8843
  id = new import_mongodb24.ObjectId(id);
@@ -8910,6 +8920,7 @@ function useCustomerSiteRepo() {
8910
8920
  getAll,
8911
8921
  getByName,
8912
8922
  countActiveByOrgAndSite,
8923
+ countAnyByOrgAndSite,
8913
8924
  getBySiteAsServiceProvider,
8914
8925
  getById,
8915
8926
  updateCustomerSiteById,
@@ -12784,7 +12795,8 @@ function useCustomerSiteService() {
12784
12795
  add: _add,
12785
12796
  updateCustomerSiteById,
12786
12797
  getById: _getById,
12787
- countActiveByOrgAndSite: _countActiveByOrgAndSite
12798
+ countActiveByOrgAndSite: _countActiveByOrgAndSite,
12799
+ countAnyByOrgAndSite: _countAnyByOrgAndSite
12788
12800
  } = useCustomerSiteRepo();
12789
12801
  const {
12790
12802
  getByName: getSiteByName,
@@ -12994,6 +13006,99 @@ function useCustomerSiteService() {
12994
13006
  session?.endSession();
12995
13007
  }
12996
13008
  }
13009
+ async function linkAcceptedInvite(invite, actor, forOrgId) {
13010
+ const session = import_node_server_utils40.useAtlas.getClient()?.startSession();
13011
+ session?.startTransaction();
13012
+ try {
13013
+ const verification = await _getInviteFresh(invite);
13014
+ if (!verification)
13015
+ throw new import_node_server_utils40.NotFoundError("Invitation not found.");
13016
+ if (verification.status !== "complete" || verification.deletedAt) {
13017
+ throw new import_node_server_utils40.BadRequestError(
13018
+ "Only an accepted invitation can be added to your Sites."
13019
+ );
13020
+ }
13021
+ const siteId = verification.metadata?.siteId?.toString() ?? "";
13022
+ const orgId = verification.metadata?.org?.toString() ?? "";
13023
+ if (!siteId || !orgId) {
13024
+ throw new import_node_server_utils40.BadRequestError("Invalid invite, missing site or organization.");
13025
+ }
13026
+ const [org, site, provider] = await Promise.all([
13027
+ _getByOrgId(orgId),
13028
+ getSiteById(siteId),
13029
+ _getByOrgId(forOrgId)
13030
+ ]);
13031
+ if (!org || !provider)
13032
+ throw new import_node_server_utils40.NotFoundError("Organization not found.");
13033
+ if (!site)
13034
+ throw new import_node_server_utils40.NotFoundError("Site not found.");
13035
+ if (await _countActiveByOrgAndSite(forOrgId, siteId) > 0) {
13036
+ await session?.commitTransaction();
13037
+ return { linked: false, message: "This site is already on your Sites list." };
13038
+ }
13039
+ if (await _countAnyByOrgAndSite(forOrgId, siteId, session) > 0) {
13040
+ throw new import_node_server_utils40.BadRequestError(
13041
+ "This site was removed from your Sites list. Ask the client to invite you again."
13042
+ );
13043
+ }
13044
+ const marked = await _transitionInvite({
13045
+ id: invite,
13046
+ from: ["complete"],
13047
+ event: {
13048
+ action: "site-linked",
13049
+ at: (/* @__PURE__ */ new Date()).toISOString(),
13050
+ by: actor?.id ? new import_mongodb36.ObjectId(actor.id) : null,
13051
+ byName: actor?.name ?? ""
13052
+ },
13053
+ set: {
13054
+ "metadata.providerOrg": forOrgId,
13055
+ "metadata.providerOrgName": provider.name ?? "",
13056
+ "metadata.siteLinkedAt": (/* @__PURE__ */ new Date()).toISOString()
13057
+ },
13058
+ // Once only, and only for the company it belongs to: a second repair
13059
+ // (at the same moment or later, for this or another company) no
13060
+ // longer matches and writes nothing.
13061
+ where: {
13062
+ "metadata.siteLinkedAt": { $exists: false },
13063
+ $or: [
13064
+ { "metadata.providerOrg": { $exists: false } },
13065
+ { "metadata.providerOrg": null },
13066
+ { "metadata.providerOrg": "" },
13067
+ { "metadata.providerOrg": forOrgId }
13068
+ ]
13069
+ },
13070
+ session
13071
+ });
13072
+ if (!marked) {
13073
+ throw new import_node_server_utils40.BadRequestError(
13074
+ "This invitation's site has already been added to a Sites list."
13075
+ );
13076
+ }
13077
+ if (!provider.defaultSite) {
13078
+ await _updateFieldById(
13079
+ { _id: forOrgId, field: "defaultSite", value: siteId },
13080
+ session
13081
+ );
13082
+ }
13083
+ await _add(
13084
+ {
13085
+ name: site.name,
13086
+ site: siteId,
13087
+ siteOrg: orgId,
13088
+ siteOrgName: org.name,
13089
+ org: forOrgId
13090
+ },
13091
+ session
13092
+ );
13093
+ await session?.commitTransaction();
13094
+ return { linked: true, message: `${site.name} is now on your Sites list.` };
13095
+ } catch (error) {
13096
+ await session?.abortTransaction();
13097
+ throw error;
13098
+ } finally {
13099
+ session?.endSession();
13100
+ }
13101
+ }
12997
13102
  async function updateCusSiteById(customerSiteId, payload) {
12998
13103
  const session = import_node_server_utils40.useAtlas.getClient()?.startSession();
12999
13104
  session?.startTransaction();
@@ -13046,6 +13151,7 @@ function useCustomerSiteService() {
13046
13151
  return {
13047
13152
  add,
13048
13153
  addViaInvite,
13154
+ linkAcceptedInvite,
13049
13155
  updateCusSiteById
13050
13156
  };
13051
13157
  }
@@ -13752,16 +13858,7 @@ function useServiceProviderInviteService() {
13752
13858
  const siteId = metadata.siteId?.toString?.() ?? "";
13753
13859
  const history = invite.history ?? [];
13754
13860
  const answer = [...history].reverse().find((h) => ["accepted", "declined", "cancelled"].includes(h?.action));
13755
- let providerOrgId = metadata.providerOrg?.toString?.() ?? "";
13756
- let providerOrgName = String(metadata.providerOrgName ?? "");
13757
- if (status === "complete" && !providerOrgId) {
13758
- const byEmail = await getOrgByEmail(
13759
- String(invite.email ?? "").trim().toLowerCase()
13760
- ).catch(() => null);
13761
- providerOrgId = byEmail?._id?.toString() ?? "";
13762
- providerOrgName = byEmail?.name ?? "";
13763
- }
13764
- const onThisOrg = status === "complete" && forOrg && siteId ? await useCustomerSiteRepo().countActiveByOrgAndSite(forOrg, siteId).catch(() => 0) > 0 : false;
13861
+ const { providerOrgId, providerOrgName, onThisOrg, needsSiteLink } = await siteLinkState(invite, forOrg);
13765
13862
  return {
13766
13863
  _id: invite._id,
13767
13864
  orgName,
@@ -13776,9 +13873,85 @@ function useServiceProviderInviteService() {
13776
13873
  statusLabel: RECEIVED_INVITE_LABELS[status] ?? serviceProviderInviteLabel(status),
13777
13874
  providerOrgId,
13778
13875
  providerOrgName,
13779
- onThisOrg
13876
+ onThisOrg,
13877
+ needsSiteLink
13878
+ };
13879
+ }
13880
+ async function siteLinkState(invite, forOrg) {
13881
+ const status = serviceProviderInviteViewStatus(invite);
13882
+ const metadata = invite.metadata ?? {};
13883
+ const siteId = metadata.siteId?.toString?.() ?? "";
13884
+ const recorded = metadata.providerOrg?.toString?.() ?? "";
13885
+ let providerOrgId = recorded;
13886
+ let providerOrgName = String(metadata.providerOrgName ?? "");
13887
+ const complete = status === "complete" && !invite.deletedAt;
13888
+ if (!complete || !siteId) {
13889
+ return { providerOrgId, providerOrgName, onThisOrg: false, needsSiteLink: false };
13890
+ }
13891
+ if (!providerOrgId) {
13892
+ const byEmail = await getOrgByEmail(
13893
+ String(invite.email ?? "").trim().toLowerCase()
13894
+ ).catch(() => null);
13895
+ providerOrgId = byEmail?._id?.toString() ?? "";
13896
+ providerOrgName = byEmail?.name ?? "";
13897
+ }
13898
+ const linked = (org) => org ? useCustomerSiteRepo().countActiveByOrgAndSite(org, siteId).then((n) => n > 0).catch(() => false) : Promise.resolve(false);
13899
+ const onThisOrg = forOrg ? await linked(forOrg) : false;
13900
+ const everLinked = Boolean(metadata.siteLinkedAt) || (forOrg && !onThisOrg ? await useCustomerSiteRepo().countAnyByOrgAndSite(forOrg, siteId).catch(() => 0) > 0 : false);
13901
+ const elsewhere = providerOrgId && providerOrgId !== forOrg ? recorded ? true : await linked(providerOrgId) : false;
13902
+ return {
13903
+ providerOrgId,
13904
+ providerOrgName,
13905
+ onThisOrg,
13906
+ needsSiteLink: Boolean(forOrg) && !onThisOrg && !elsewhere && !everLinked
13780
13907
  };
13781
13908
  }
13909
+ async function linkSite({
13910
+ id,
13911
+ userId,
13912
+ org
13913
+ }) {
13914
+ const actor = await actorFor(userId);
13915
+ const invite = await load(id);
13916
+ await assertInvitedParty(actor.id, invite);
13917
+ const forOrg = memberOrg(actor, org);
13918
+ if (!forOrg) {
13919
+ throw new import_node_server_utils43.BadRequestError("Choose the company to add the site to.");
13920
+ }
13921
+ if (![SERVICE_PROVIDER_SIGN_IN_TYPE, SERVICE_PROVIDER_SIGN_UP_TYPE].includes(
13922
+ String(invite.type ?? "")
13923
+ ) || invite.status === "awaiting-approval" /* AWAITING_APPROVAL */) {
13924
+ throw new import_node_server_utils43.NotFoundError("Invitation not found.");
13925
+ }
13926
+ if (invite.status !== "complete" /* COMPLETE */ || invite.deletedAt) {
13927
+ throw new import_node_server_utils43.BadRequestError(
13928
+ "Only an accepted invitation can be added to your Sites."
13929
+ );
13930
+ }
13931
+ const state = await siteLinkState(invite, forOrg);
13932
+ if (state.onThisOrg) {
13933
+ return { message: "This site is already on your Sites list." };
13934
+ }
13935
+ if (!state.needsSiteLink) {
13936
+ throw new import_node_server_utils43.BadRequestError(
13937
+ state.providerOrgId && state.providerOrgId !== forOrg ? `This invitation was accepted for ${state.providerOrgName || "another company"}. The site is on that company's Sites list.` : "This site was removed from your Sites list. Ask the client to invite you again."
13938
+ );
13939
+ }
13940
+ try {
13941
+ const result = await useCustomerSiteService().linkAcceptedInvite(
13942
+ id,
13943
+ { id: actor.id, name: actor.name },
13944
+ forOrg
13945
+ );
13946
+ return { message: result.message };
13947
+ } catch (error) {
13948
+ const siteId = String(invite.metadata?.siteId ?? "");
13949
+ const added = await useCustomerSiteRepo().countActiveByOrgAndSite(forOrg, siteId).catch(() => 0);
13950
+ if (added > 0)
13951
+ return { message: "This site is already on your Sites list." };
13952
+ throw error;
13953
+ }
13954
+ }
13782
13955
  async function getForProvider({
13783
13956
  id,
13784
13957
  userId,
@@ -13804,6 +13977,7 @@ function useServiceProviderInviteService() {
13804
13977
  softDelete,
13805
13978
  decline,
13806
13979
  accept,
13980
+ linkSite,
13807
13981
  listReceived,
13808
13982
  getForProvider,
13809
13983
  notifyProvider
@@ -27320,6 +27494,14 @@ function useVerificationController() {
27320
27494
  next(new import_node_server_utils70.BadRequestError("Verification not found."));
27321
27495
  return;
27322
27496
  }
27497
+ if ([SERVICE_PROVIDER_SIGN_IN_TYPE, SERVICE_PROVIDER_SIGN_UP_TYPE].includes(
27498
+ String(verification.type ?? "")
27499
+ )) {
27500
+ res.json({
27501
+ message: "Sign in and accept this invitation to add the site to your Sites."
27502
+ });
27503
+ return;
27504
+ }
27323
27505
  if (verification.status === "complete") {
27324
27506
  res.json({ message: "Successfully updated verification status." });
27325
27507
  return;
@@ -28804,6 +28986,7 @@ function useOrgController() {
28804
28986
  let invitedFrom = null;
28805
28987
  let invitedRole = null;
28806
28988
  let inviteAlreadyComplete = false;
28989
+ let invitedServiceProvider = false;
28807
28990
  let invitedModules = null;
28808
28991
  let self = null;
28809
28992
  if (inviteId) {
@@ -28817,6 +29000,10 @@ function useOrgController() {
28817
29000
  invitedFrom = String(invite._id);
28818
29001
  invitedRole = invite.metadata?.role ? String(invite.metadata.role) : null;
28819
29002
  inviteAlreadyComplete = invite.status === "complete" /* COMPLETE */;
29003
+ invitedServiceProvider = [
29004
+ SERVICE_PROVIDER_SIGN_IN_TYPE,
29005
+ SERVICE_PROVIDER_SIGN_UP_TYPE
29006
+ ].includes(String(invite.type ?? ""));
28820
29007
  const chosen = normaliseModules(invite.metadata?.modules);
28821
29008
  const invitedBy = invite.metadata?.invitedBy;
28822
29009
  if (chosen.length && invitedBy && invite.metadata?.app === body.nature) {
@@ -28873,7 +29060,7 @@ function useOrgController() {
28873
29060
  })
28874
29061
  });
28875
29062
  }
28876
- if (invitedFrom && !inviteAlreadyComplete) {
29063
+ if (invitedFrom && !inviteAlreadyComplete && !invitedServiceProvider) {
28877
29064
  try {
28878
29065
  await useVerificationRepoV2().updateStatusById(
28879
29066
  invitedFrom,
@@ -33756,6 +33943,13 @@ function useServiceProviderService() {
33756
33943
  "You have already accepted the service provider invite using this link."
33757
33944
  );
33758
33945
  }
33946
+ if ([SERVICE_PROVIDER_SIGN_IN_TYPE, SERVICE_PROVIDER_SIGN_UP_TYPE].includes(
33947
+ String(invite.type ?? "")
33948
+ )) {
33949
+ throw new import_node_server_utils102.BadRequestError(
33950
+ "Accept this invitation from Client invitations in the Organization app."
33951
+ );
33952
+ }
33759
33953
  const expired = new Date(invite.expireAt) < /* @__PURE__ */ new Date();
33760
33954
  if (invite.status === "expired" || expired) {
33761
33955
  throw new import_node_server_utils102.BadRequestError("Service provider invitation link expired.");
@@ -93868,6 +94062,7 @@ function useServiceProviderInviteController() {
93868
94062
  softDelete: _softDelete,
93869
94063
  decline: _decline,
93870
94064
  accept: _accept,
94065
+ linkSite: _linkSite,
93871
94066
  listReceived: _listReceived,
93872
94067
  getForProvider: _getForProvider
93873
94068
  } = useServiceProviderInviteService();
@@ -94034,6 +94229,19 @@ function useServiceProviderInviteController() {
94034
94229
  next(error);
94035
94230
  }
94036
94231
  }
94232
+ async function linkSite(req, res, next) {
94233
+ try {
94234
+ res.json(
94235
+ await _linkSite({
94236
+ id: inviteId(req),
94237
+ userId: callerId5(req),
94238
+ org: optionalOrg(req.body?.org)
94239
+ })
94240
+ );
94241
+ } catch (error) {
94242
+ next(error);
94243
+ }
94244
+ }
94037
94245
  async function received(req, res, next) {
94038
94246
  try {
94039
94247
  res.json(
@@ -94071,6 +94279,7 @@ function useServiceProviderInviteController() {
94071
94279
  remove,
94072
94280
  decline,
94073
94281
  accept,
94282
+ linkSite,
94074
94283
  received,
94075
94284
  getOne
94076
94285
  };