@greatapps/common 1.1.477 → 1.1.479

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.
Files changed (76) hide show
  1. package/dist/components/account/hooks/useDisableTwoFactorAuthForm.mjs +3 -1
  2. package/dist/components/account/hooks/useDisableTwoFactorAuthForm.mjs.map +1 -1
  3. package/dist/hooks/useAuthQueryKey.mjs +23 -0
  4. package/dist/hooks/useAuthQueryKey.mjs.map +1 -0
  5. package/dist/index.mjs +17 -2
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/modules/accounts/hooks/current-account.hook.mjs +5 -2
  8. package/dist/modules/accounts/hooks/current-account.hook.mjs.map +1 -1
  9. package/dist/modules/accounts/hooks/useAccountManagement.mjs +19 -9
  10. package/dist/modules/accounts/hooks/useAccountManagement.mjs.map +1 -1
  11. package/dist/modules/accounts/hooks/useCurrencies.mjs +3 -1
  12. package/dist/modules/accounts/hooks/useCurrencies.mjs.map +1 -1
  13. package/dist/modules/accounts/hooks/useTimezones.mjs +3 -1
  14. package/dist/modules/accounts/hooks/useTimezones.mjs.map +1 -1
  15. package/dist/modules/auth/hooks/useUserQuery.mjs +15 -6
  16. package/dist/modules/auth/hooks/useUserQuery.mjs.map +1 -1
  17. package/dist/modules/cards/hooks/cards.hook.mjs +3 -1
  18. package/dist/modules/cards/hooks/cards.hook.mjs.map +1 -1
  19. package/dist/modules/cards/hooks/create-card.hook.mjs +3 -1
  20. package/dist/modules/cards/hooks/create-card.hook.mjs.map +1 -1
  21. package/dist/modules/ia-credits/hooks/ia-credits.hook.mjs +3 -1
  22. package/dist/modules/ia-credits/hooks/ia-credits.hook.mjs.map +1 -1
  23. package/dist/modules/plans/hooks/list-plans.hook.mjs +3 -1
  24. package/dist/modules/plans/hooks/list-plans.hook.mjs.map +1 -1
  25. package/dist/modules/plans/hooks/use-plan-by-id.hook.mjs +4 -2
  26. package/dist/modules/plans/hooks/use-plan-by-id.hook.mjs.map +1 -1
  27. package/dist/modules/plans/services/plans.service.mjs +4 -2
  28. package/dist/modules/plans/services/plans.service.mjs.map +1 -1
  29. package/dist/modules/projects/hooks/add-project-user.hook.mjs +15 -12
  30. package/dist/modules/projects/hooks/add-project-user.hook.mjs.map +1 -1
  31. package/dist/modules/projects/hooks/list-all-account-users.hook.mjs +3 -1
  32. package/dist/modules/projects/hooks/list-all-account-users.hook.mjs.map +1 -1
  33. package/dist/modules/projects/hooks/list-available-users.hook.mjs +3 -1
  34. package/dist/modules/projects/hooks/list-available-users.hook.mjs.map +1 -1
  35. package/dist/modules/projects/hooks/list-project-users.hook.mjs +3 -1
  36. package/dist/modules/projects/hooks/list-project-users.hook.mjs.map +1 -1
  37. package/dist/modules/projects/hooks/remove-project-user.hook.mjs +15 -12
  38. package/dist/modules/projects/hooks/remove-project-user.hook.mjs.map +1 -1
  39. package/dist/modules/subscriptions/constants/query-keys.constants.mjs +2 -0
  40. package/dist/modules/subscriptions/constants/query-keys.constants.mjs.map +1 -1
  41. package/dist/modules/subscriptions/hooks/find-active-subscription.hook.mjs +3 -1
  42. package/dist/modules/subscriptions/hooks/find-active-subscription.hook.mjs.map +1 -1
  43. package/dist/modules/subscriptions/hooks/list-subscriptions.hook.mjs +3 -1
  44. package/dist/modules/subscriptions/hooks/list-subscriptions.hook.mjs.map +1 -1
  45. package/dist/modules/subscriptions/hooks/update-subscription-plan.hook.mjs +6 -3
  46. package/dist/modules/subscriptions/hooks/update-subscription-plan.hook.mjs.map +1 -1
  47. package/dist/modules/users/hooks/messages.hook.mjs +9 -4
  48. package/dist/modules/users/hooks/messages.hook.mjs.map +1 -1
  49. package/dist/providers/auth.provider.mjs +6 -4
  50. package/dist/providers/auth.provider.mjs.map +1 -1
  51. package/package.json +1 -1
  52. package/src/components/account/hooks/useDisableTwoFactorAuthForm.tsx +3 -1
  53. package/src/hooks/useAuthQueryKey.ts +32 -0
  54. package/src/index.ts +10 -1
  55. package/src/modules/accounts/hooks/current-account.hook.tsx +7 -3
  56. package/src/modules/accounts/hooks/useAccountManagement.ts +20 -11
  57. package/src/modules/accounts/hooks/useCurrencies.ts +5 -2
  58. package/src/modules/accounts/hooks/useTimezones.ts +5 -2
  59. package/src/modules/auth/hooks/useUserQuery.ts +75 -65
  60. package/src/modules/cards/hooks/cards.hook.ts +5 -2
  61. package/src/modules/cards/hooks/create-card.hook.ts +3 -1
  62. package/src/modules/ia-credits/hooks/ia-credits.hook.ts +99 -97
  63. package/src/modules/plans/hooks/list-plans.hook.ts +5 -2
  64. package/src/modules/plans/hooks/use-plan-by-id.hook.ts +4 -2
  65. package/src/modules/plans/services/plans.service.ts +4 -2
  66. package/src/modules/projects/hooks/add-project-user.hook.ts +16 -13
  67. package/src/modules/projects/hooks/list-all-account-users.hook.ts +8 -3
  68. package/src/modules/projects/hooks/list-available-users.hook.ts +8 -3
  69. package/src/modules/projects/hooks/list-project-users.hook.ts +8 -3
  70. package/src/modules/projects/hooks/remove-project-user.hook.ts +16 -13
  71. package/src/modules/subscriptions/constants/query-keys.constants.ts +3 -1
  72. package/src/modules/subscriptions/hooks/find-active-subscription.hook.ts +4 -1
  73. package/src/modules/subscriptions/hooks/list-subscriptions.hook.ts +4 -1
  74. package/src/modules/subscriptions/hooks/update-subscription-plan.hook.ts +6 -3
  75. package/src/modules/users/hooks/messages.hook.ts +12 -5
  76. package/src/providers/auth.provider.tsx +162 -160
@@ -1,97 +1,99 @@
1
- 'use client';
2
-
3
- import { useMemo } from 'react';
4
- import { useQuery } from '@tanstack/react-query';
5
- import { listIaCreditsAction } from '../actions/list-ia-credits.action';
6
- import type { IaCreditOperation, IaCreditsSummary } from '../types';
7
- import { useActiveSubscription } from '../../subscriptions/hooks/find-active-subscription.hook';
8
- import { withAction } from '../../../utils/withAction';
9
-
10
- function calculateSummary(operations: IaCreditOperation[]): IaCreditsSummary {
11
- const today = new Date();
12
- const todayDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
13
-
14
- const adds = operations.filter((op) => op.operation === 'add');
15
- const subtracts = operations.filter((op) => op.operation === 'subtract');
16
-
17
- let totalCredits = 0;
18
- let usedCredits = 0;
19
- let nextExpirationInDays: number | null = null;
20
- let nextExpiringCredits: number | null = null;
21
-
22
- for (const add of adds) {
23
- const expirationRaw = add.expiration_time;
24
- if (!expirationRaw) continue;
25
-
26
- const expiration = new Date(expirationRaw);
27
- const expirationDate = new Date(
28
- expiration.getFullYear(),
29
- expiration.getMonth(),
30
- expiration.getDate()
31
- );
32
-
33
- const expiredByDate = expirationDate.getTime() < todayDate.getTime();
34
- const hasExpired = add.has_expired || expiredByDate;
35
-
36
- if (hasExpired) continue;
37
-
38
- const addedCredits = add.operation_value;
39
-
40
- const consumedForAdd = subtracts
41
- .filter((sub) => String(sub.consumed_from_add_id) === String(add.id))
42
- .reduce((sum, sub) => sum + sub.operation_value, 0);
43
-
44
- const remainingForAdd = Math.max(0, addedCredits - consumedForAdd);
45
-
46
- totalCredits += addedCredits;
47
- usedCredits += consumedForAdd;
48
-
49
- const diffMs = expirationDate.getTime() - todayDate.getTime();
50
- const days = Math.max(0, Math.ceil(diffMs / (1000 * 60 * 60 * 24)));
51
-
52
- if (remainingForAdd > 0) {
53
- if (nextExpirationInDays === null || days < nextExpirationInDays) {
54
- nextExpirationInDays = days;
55
- nextExpiringCredits = remainingForAdd;
56
- }
57
- }
58
- }
59
-
60
- const availableCredits = Math.max(0, totalCredits - usedCredits);
61
-
62
- return {
63
- totalCredits,
64
- usedCredits,
65
- availableCredits,
66
- nextExpiringCredits,
67
- nextExpirationInDays,
68
- };
69
- }
70
-
71
- export function useIaCredits() {
72
- const { data: subscriptionData, isPending: isSubscriptionLoading } = useActiveSubscription();
73
- const subscription = subscriptionData?.data?.[0] ?? null;
74
- const subscriptionId = subscription?.id;
75
-
76
- const query = useQuery({
77
- queryKey: ['ia-credits', subscriptionId],
78
- queryFn: withAction(() => listIaCreditsAction(subscriptionId!)),
79
- enabled: subscriptionId != null,
80
- });
81
-
82
- const operations = query.data?.data ?? [];
83
-
84
- // eslint-disable-next-line react-hooks/exhaustive-deps
85
- const summary = useMemo(() => calculateSummary(operations), [operations]);
86
-
87
- return {
88
- subscription,
89
- operations,
90
- summary,
91
- isLoading: isSubscriptionLoading || query.isPending,
92
- isSubscriptionLoading,
93
- isCreditsLoading: query.isPending,
94
- isError: query.isError,
95
- error: query.error,
96
- };
97
- }
1
+ 'use client';
2
+
3
+ import { useMemo } from 'react';
4
+ import { useQuery } from '@tanstack/react-query';
5
+ import { listIaCreditsAction } from '../actions/list-ia-credits.action';
6
+ import type { IaCreditOperation, IaCreditsSummary } from '../types';
7
+ import { useActiveSubscription } from '../../subscriptions/hooks/find-active-subscription.hook';
8
+ import { withAction } from '../../../utils/withAction';
9
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
10
+
11
+ function calculateSummary(operations: IaCreditOperation[]): IaCreditsSummary {
12
+ const today = new Date();
13
+ const todayDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
14
+
15
+ const adds = operations.filter((op) => op.operation === 'add');
16
+ const subtracts = operations.filter((op) => op.operation === 'subtract');
17
+
18
+ let totalCredits = 0;
19
+ let usedCredits = 0;
20
+ let nextExpirationInDays: number | null = null;
21
+ let nextExpiringCredits: number | null = null;
22
+
23
+ for (const add of adds) {
24
+ const expirationRaw = add.expiration_time;
25
+ if (!expirationRaw) continue;
26
+
27
+ const expiration = new Date(expirationRaw);
28
+ const expirationDate = new Date(
29
+ expiration.getFullYear(),
30
+ expiration.getMonth(),
31
+ expiration.getDate()
32
+ );
33
+
34
+ const expiredByDate = expirationDate.getTime() < todayDate.getTime();
35
+ const hasExpired = add.has_expired || expiredByDate;
36
+
37
+ if (hasExpired) continue;
38
+
39
+ const addedCredits = add.operation_value;
40
+
41
+ const consumedForAdd = subtracts
42
+ .filter((sub) => String(sub.consumed_from_add_id) === String(add.id))
43
+ .reduce((sum, sub) => sum + sub.operation_value, 0);
44
+
45
+ const remainingForAdd = Math.max(0, addedCredits - consumedForAdd);
46
+
47
+ totalCredits += addedCredits;
48
+ usedCredits += consumedForAdd;
49
+
50
+ const diffMs = expirationDate.getTime() - todayDate.getTime();
51
+ const days = Math.max(0, Math.ceil(diffMs / (1000 * 60 * 60 * 24)));
52
+
53
+ if (remainingForAdd > 0) {
54
+ if (nextExpirationInDays === null || days < nextExpirationInDays) {
55
+ nextExpirationInDays = days;
56
+ nextExpiringCredits = remainingForAdd;
57
+ }
58
+ }
59
+ }
60
+
61
+ const availableCredits = Math.max(0, totalCredits - usedCredits);
62
+
63
+ return {
64
+ totalCredits,
65
+ usedCredits,
66
+ availableCredits,
67
+ nextExpiringCredits,
68
+ nextExpirationInDays,
69
+ };
70
+ }
71
+
72
+ export function useIaCredits() {
73
+ const { data: subscriptionData, isPending: isSubscriptionLoading } = useActiveSubscription();
74
+ const subscription = subscriptionData?.data?.[0] ?? null;
75
+ const subscriptionId = subscription?.id;
76
+ const queryKey = useAuthQueryKey(['ia-credits', subscriptionId]);
77
+
78
+ const query = useQuery({
79
+ queryKey,
80
+ queryFn: withAction(() => listIaCreditsAction(subscriptionId!)),
81
+ enabled: subscriptionId != null,
82
+ });
83
+
84
+ const operations = query.data?.data ?? [];
85
+
86
+ // eslint-disable-next-line react-hooks/exhaustive-deps
87
+ const summary = useMemo(() => calculateSummary(operations), [operations]);
88
+
89
+ return {
90
+ subscription,
91
+ operations,
92
+ summary,
93
+ isLoading: isSubscriptionLoading || query.isPending,
94
+ isSubscriptionLoading,
95
+ isCreditsLoading: query.isPending,
96
+ isError: query.isError,
97
+ error: query.error,
98
+ };
99
+ }
@@ -4,12 +4,15 @@ import { useQuery } from '@tanstack/react-query';
4
4
  import { withAction } from '@greatapps/common';
5
5
  import { listPlansAction } from '../actions/list-plans.action';
6
6
  import type { Plan } from '../types/plan.type';
7
+ import { useWlQueryKey } from '../../../hooks/useAuthQueryKey';
7
8
 
8
- export const PLANS_QUERY_KEY = ['plans'];
9
+ export const PLANS_QUERY_KEY = ['plans'] as const;
9
10
 
10
11
  export function usePlans() {
12
+ const queryKey = useWlQueryKey([...PLANS_QUERY_KEY]);
13
+
11
14
  return useQuery<Plan[]>({
12
- queryKey: [...PLANS_QUERY_KEY],
15
+ queryKey,
13
16
  queryFn: withAction(listPlansAction),
14
17
  staleTime: Infinity,
15
18
  gcTime: Infinity,
@@ -5,16 +5,18 @@ import { withAction } from "../../../utils/withAction";
5
5
  import { findPlanByIdAction } from "../actions/find-plan-by-id.action";
6
6
  import type { Plan } from "../types/plan.type";
7
7
  import { PLANS_QUERY_KEY } from "./list-plans.hook";
8
+ import { useWlQueryKey } from "../../../hooks/useAuthQueryKey";
8
9
 
9
10
  export function usePlanById(idPlan: number | string | undefined) {
10
11
  const queryClient = useQueryClient();
12
+ const plansKey = useWlQueryKey([...PLANS_QUERY_KEY]);
11
13
 
12
14
  return useQuery({
13
- queryKey: [...PLANS_QUERY_KEY, idPlan],
15
+ queryKey: [...plansKey, idPlan],
14
16
  queryFn: withAction(() => findPlanByIdAction(idPlan!)),
15
17
  initialData: () => {
16
18
  const queries = queryClient.getQueriesData<Plan[]>({
17
- queryKey: [...PLANS_QUERY_KEY],
19
+ queryKey: plansKey,
18
20
  });
19
21
 
20
22
  for (const [, data] of queries) {
@@ -41,9 +41,10 @@ class PlansService {
41
41
  async listPlans(
42
42
  params?: ListPlansParams,
43
43
  ): Promise<PaginatedSuccessResult<Plan>> {
44
- const { id_account } = await getUserContext();
44
+ const { id_wl, id_account } = await getUserContext();
45
45
  const cacheKey = this.buildCacheKey("plans", {
46
46
  ...params,
47
+ id_wl,
47
48
  id_account,
48
49
  });
49
50
 
@@ -87,8 +88,9 @@ class PlansService {
87
88
  }
88
89
 
89
90
  async findById(idPlan: number | string): Promise<SuccessResult<Plan>> {
90
- const { id_account } = await getUserContext();
91
+ const { id_wl, id_account } = await getUserContext();
91
92
  const cacheKey = this.buildCacheKey(`plan-${idPlan}`, {
93
+ id_wl,
92
94
  id_account: String(id_account),
93
95
  });
94
96
 
@@ -5,27 +5,30 @@ import { addProjectUserAction } from '../actions/add-project-user.action';
5
5
  import { LIST_PROJECT_USERS_BASE_KEY } from './list-project-users.hook';
6
6
  import { LIST_ALL_ACCOUNT_USERS_BASE_KEY } from './list-all-account-users.hook';
7
7
  import type { UsersPage, AccountUser, ProjectUser } from '../types';
8
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
8
9
 
9
10
  export function useAddProjectUser(projectId: number) {
10
11
  const queryClient = useQueryClient();
12
+ const allAccountUsersKey = useAuthQueryKey([...LIST_ALL_ACCOUNT_USERS_BASE_KEY()]);
13
+ const projectUsersKey = useAuthQueryKey([...LIST_PROJECT_USERS_BASE_KEY(projectId)]);
11
14
 
12
15
  return useMutation({
13
- mutationFn: (userId: number) =>
14
- addProjectUserAction({ projectId, users: [userId] }),
16
+ mutationFn: (targetUserId: number) =>
17
+ addProjectUserAction({ projectId, users: [targetUserId] }),
15
18
 
16
- onMutate: async (userId) => {
17
- await queryClient.cancelQueries({ queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY() });
18
- await queryClient.cancelQueries({ queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId) });
19
+ onMutate: async (targetUserId) => {
20
+ await queryClient.cancelQueries({ queryKey: allAccountUsersKey });
21
+ await queryClient.cancelQueries({ queryKey: projectUsersKey });
19
22
 
20
23
  const prevAccountUsers = queryClient.getQueriesData<InfiniteData<UsersPage<AccountUser>>>({
21
- queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY(),
24
+ queryKey: allAccountUsersKey,
22
25
  });
23
26
  const prevProjectUsers = queryClient.getQueriesData<InfiniteData<UsersPage<ProjectUser>>>({
24
- queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId),
27
+ queryKey: projectUsersKey,
25
28
  });
26
29
 
27
30
  queryClient.setQueriesData<InfiniteData<UsersPage<AccountUser>>>(
28
- { queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY(), exact: false },
31
+ { queryKey: allAccountUsersKey, exact: false },
29
32
  (old) => {
30
33
  if (!old) return old;
31
34
  return {
@@ -33,7 +36,7 @@ export function useAddProjectUser(projectId: number) {
33
36
  pages: old.pages.map((page) => ({
34
37
  ...page,
35
38
  data: page.data.map((u) =>
36
- u.id === userId ? { ...u, in_project: true } : u
39
+ u.id === targetUserId ? { ...u, in_project: true } : u
37
40
  ),
38
41
  })),
39
42
  };
@@ -41,7 +44,7 @@ export function useAddProjectUser(projectId: number) {
41
44
  );
42
45
 
43
46
  queryClient.setQueriesData<InfiniteData<UsersPage<ProjectUser>>>(
44
- { queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId), exact: false },
47
+ { queryKey: projectUsersKey, exact: false },
45
48
  (old) => {
46
49
  if (!old?.pages.length) return old;
47
50
  return {
@@ -56,14 +59,14 @@ export function useAddProjectUser(projectId: number) {
56
59
  return { prevAccountUsers, prevProjectUsers };
57
60
  },
58
61
 
59
- onError: (_err, _userId, ctx) => {
62
+ onError: (_err, _targetUserId, ctx) => {
60
63
  ctx?.prevAccountUsers.forEach(([key, data]) => queryClient.setQueryData(key, data));
61
64
  ctx?.prevProjectUsers.forEach(([key, data]) => queryClient.setQueryData(key, data));
62
65
  },
63
66
 
64
67
  onSettled: () => {
65
- queryClient.invalidateQueries({ queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId) });
66
- queryClient.invalidateQueries({ queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY() });
68
+ queryClient.invalidateQueries({ queryKey: projectUsersKey });
69
+ queryClient.invalidateQueries({ queryKey: allAccountUsersKey });
67
70
  },
68
71
  });
69
72
  }
@@ -3,19 +3,24 @@
3
3
  import { useInfiniteQuery } from '@tanstack/react-query';
4
4
  import { listAllAccountUsersAction } from '../actions/list-all-account-users.action';
5
5
  import { withAction } from '../../../utils/withAction';
6
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
6
7
 
7
8
  const PAGE_SIZE = 20;
8
9
 
9
- export const LIST_ALL_ACCOUNT_USERS_BASE_KEY = () => ['account-users', 'all'];
10
+ export const LIST_ALL_ACCOUNT_USERS_BASE_KEY = () =>
11
+ ['account-users', 'all'] as const;
12
+
10
13
  export const LIST_ALL_ACCOUNT_USERS_QUERY_KEY = (search: string = '', projectId?: number) => [
11
14
  ...LIST_ALL_ACCOUNT_USERS_BASE_KEY(),
12
15
  search,
13
16
  projectId,
14
- ];
17
+ ] as const;
15
18
 
16
19
  export function useListAllAccountUsers(search: string = '', projectId?: number) {
20
+ const queryKey = useAuthQueryKey([...LIST_ALL_ACCOUNT_USERS_QUERY_KEY(search, projectId)]);
21
+
17
22
  return useInfiniteQuery({
18
- queryKey: LIST_ALL_ACCOUNT_USERS_QUERY_KEY(search, projectId),
23
+ queryKey,
19
24
  queryFn: ({ pageParam }) =>
20
25
  withAction(() =>
21
26
  listAllAccountUsersAction({
@@ -3,18 +3,23 @@
3
3
  import { useInfiniteQuery } from '@tanstack/react-query';
4
4
  import { listAvailableUsersAction } from '../actions/list-available-users.action';
5
5
  import { withAction } from '../../../utils/withAction';
6
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
6
7
 
7
8
  const PAGE_SIZE = 20;
8
9
 
9
- export const LIST_AVAILABLE_USERS_BASE_KEY = (projectId: number) => ['project-users', projectId, 'out'];
10
+ export const LIST_AVAILABLE_USERS_BASE_KEY = (projectId: number) =>
11
+ ['project-users', projectId, 'out'] as const;
12
+
10
13
  export const LIST_AVAILABLE_USERS_QUERY_KEY = (projectId: number, search: string = '') => [
11
14
  ...LIST_AVAILABLE_USERS_BASE_KEY(projectId),
12
15
  search,
13
- ];
16
+ ] as const;
14
17
 
15
18
  export function useListAvailableUsers(projectId: number, search: string = '') {
19
+ const queryKey = useAuthQueryKey([...LIST_AVAILABLE_USERS_QUERY_KEY(projectId, search)]);
20
+
16
21
  return useInfiniteQuery({
17
- queryKey: LIST_AVAILABLE_USERS_QUERY_KEY(projectId, search),
22
+ queryKey,
18
23
  queryFn: ({ pageParam }) =>
19
24
  withAction(() =>
20
25
  listAvailableUsersAction(projectId, {
@@ -3,18 +3,23 @@
3
3
  import { useInfiniteQuery } from '@tanstack/react-query';
4
4
  import { listProjectUsersAction } from '../actions/list-project-users.action';
5
5
  import { withAction } from '../../../utils/withAction';
6
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
6
7
 
7
8
  const PAGE_SIZE = 20;
8
9
 
9
- export const LIST_PROJECT_USERS_BASE_KEY = (projectId: number) => ['project-users', projectId, 'in'];
10
+ export const LIST_PROJECT_USERS_BASE_KEY = (projectId: number) =>
11
+ ['project-users', projectId, 'in'] as const;
12
+
10
13
  export const LIST_PROJECT_USERS_QUERY_KEY = (projectId: number, search: string = '') => [
11
14
  ...LIST_PROJECT_USERS_BASE_KEY(projectId),
12
15
  search,
13
- ];
16
+ ] as const;
14
17
 
15
18
  export function useListProjectUsers(projectId: number, search: string = '') {
19
+ const queryKey = useAuthQueryKey([...LIST_PROJECT_USERS_QUERY_KEY(projectId, search)]);
20
+
16
21
  return useInfiniteQuery({
17
- queryKey: LIST_PROJECT_USERS_QUERY_KEY(projectId, search),
22
+ queryKey,
18
23
  queryFn: ({ pageParam }) =>
19
24
  withAction(() =>
20
25
  listProjectUsersAction(projectId, {
@@ -5,27 +5,30 @@ import { removeProjectUserAction } from '../actions/remove-project-user.action';
5
5
  import { LIST_PROJECT_USERS_BASE_KEY } from './list-project-users.hook';
6
6
  import { LIST_ALL_ACCOUNT_USERS_BASE_KEY } from './list-all-account-users.hook';
7
7
  import type { UsersPage, AccountUser, ProjectUser } from '../types';
8
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
8
9
 
9
10
  export function useRemoveProjectUser(projectId: number) {
10
11
  const queryClient = useQueryClient();
12
+ const allAccountUsersKey = useAuthQueryKey([...LIST_ALL_ACCOUNT_USERS_BASE_KEY()]);
13
+ const projectUsersKey = useAuthQueryKey([...LIST_PROJECT_USERS_BASE_KEY(projectId)]);
11
14
 
12
15
  return useMutation({
13
- mutationFn: (userId: number) =>
14
- removeProjectUserAction({ projectId, users: [userId] }),
16
+ mutationFn: (targetUserId: number) =>
17
+ removeProjectUserAction({ projectId, users: [targetUserId] }),
15
18
 
16
- onMutate: async (userId) => {
17
- await queryClient.cancelQueries({ queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY() });
18
- await queryClient.cancelQueries({ queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId) });
19
+ onMutate: async (targetUserId) => {
20
+ await queryClient.cancelQueries({ queryKey: allAccountUsersKey });
21
+ await queryClient.cancelQueries({ queryKey: projectUsersKey });
19
22
 
20
23
  const prevAccountUsers = queryClient.getQueriesData<InfiniteData<UsersPage<AccountUser>>>({
21
- queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY(),
24
+ queryKey: allAccountUsersKey,
22
25
  });
23
26
  const prevProjectUsers = queryClient.getQueriesData<InfiniteData<UsersPage<ProjectUser>>>({
24
- queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId),
27
+ queryKey: projectUsersKey,
25
28
  });
26
29
 
27
30
  queryClient.setQueriesData<InfiniteData<UsersPage<AccountUser>>>(
28
- { queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY(), exact: false },
31
+ { queryKey: allAccountUsersKey, exact: false },
29
32
  (old) => {
30
33
  if (!old) return old;
31
34
  return {
@@ -33,7 +36,7 @@ export function useRemoveProjectUser(projectId: number) {
33
36
  pages: old.pages.map((page) => ({
34
37
  ...page,
35
38
  data: page.data.map((u) =>
36
- u.id === userId ? { ...u, in_project: false } : u
39
+ u.id === targetUserId ? { ...u, in_project: false } : u
37
40
  ),
38
41
  })),
39
42
  };
@@ -41,7 +44,7 @@ export function useRemoveProjectUser(projectId: number) {
41
44
  );
42
45
 
43
46
  queryClient.setQueriesData<InfiniteData<UsersPage<ProjectUser>>>(
44
- { queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId), exact: false },
47
+ { queryKey: projectUsersKey, exact: false },
45
48
  (old) => {
46
49
  if (!old?.pages.length) return old;
47
50
  return {
@@ -56,14 +59,14 @@ export function useRemoveProjectUser(projectId: number) {
56
59
  return { prevAccountUsers, prevProjectUsers };
57
60
  },
58
61
 
59
- onError: (_err, _userId, ctx) => {
62
+ onError: (_err, _targetUserId, ctx) => {
60
63
  ctx?.prevAccountUsers.forEach(([key, data]) => queryClient.setQueryData(key, data));
61
64
  ctx?.prevProjectUsers.forEach(([key, data]) => queryClient.setQueryData(key, data));
62
65
  },
63
66
 
64
67
  onSettled: () => {
65
- queryClient.invalidateQueries({ queryKey: LIST_PROJECT_USERS_BASE_KEY(projectId) });
66
- queryClient.invalidateQueries({ queryKey: LIST_ALL_ACCOUNT_USERS_BASE_KEY() });
68
+ queryClient.invalidateQueries({ queryKey: projectUsersKey });
69
+ queryClient.invalidateQueries({ queryKey: allAccountUsersKey });
67
70
  },
68
71
  });
69
72
  }
@@ -1 +1,3 @@
1
- export const SUBSCRIPTIONS_QUERY_KEY = ['subscriptions'];
1
+ export const SUBSCRIPTIONS_QUERY_KEY = ['subscriptions'] as const;
2
+
3
+ export const CHARGES_QUERY_KEY = ['charges'] as const;
@@ -4,10 +4,13 @@ import { useQuery } from "@tanstack/react-query";
4
4
  import { listSubscriptionsAction } from "../actions/list-subscriptions.action";
5
5
  import { SUBSCRIPTIONS_QUERY_KEY } from "../constants/query-keys.constants";
6
6
  import { withAction } from "../../../utils/withAction";
7
+ import { useAuthQueryKey } from "../../../hooks/useAuthQueryKey";
7
8
 
8
9
  export function useActiveSubscription() {
10
+ const queryKey = useAuthQueryKey([...SUBSCRIPTIONS_QUERY_KEY, "active"]);
11
+
9
12
  return useQuery({
10
- queryKey: [...SUBSCRIPTIONS_QUERY_KEY, "active"],
13
+ queryKey,
11
14
  queryFn: async () => {
12
15
  return await withAction(listSubscriptionsAction)({ limit: 1 });
13
16
  },
@@ -6,10 +6,13 @@ import { parseResult } from '../../../infra/utils/parser';
6
6
  import { SubscriptionSchema, type FindSubscriptionsParams } from '../types/subscription.type';
7
7
  import { withAction } from '../../../utils/withAction';
8
8
  import { SUBSCRIPTIONS_QUERY_KEY } from '../constants/query-keys.constants';
9
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
9
10
 
10
11
  export function useSubscriptions(params?: Partial<FindSubscriptionsParams>) {
12
+ const queryKey = useAuthQueryKey([...SUBSCRIPTIONS_QUERY_KEY, params]);
13
+
11
14
  return useQuery({
12
- queryKey: [...SUBSCRIPTIONS_QUERY_KEY, params],
15
+ queryKey,
13
16
  queryFn: async () =>
14
17
  parseResult(SubscriptionSchema, await withAction(() => listSubscriptionsAction(params))()),
15
18
  });
@@ -3,11 +3,14 @@
3
3
  import { useMutation, useQueryClient } from '@tanstack/react-query';
4
4
  import { withAction } from '../../../utils/withAction';
5
5
  import { updateSubscriptionPlanAction } from '../actions/update-subscription-plan.action';
6
- import { SUBSCRIPTIONS_QUERY_KEY } from '../constants/query-keys.constants';
6
+ import { SUBSCRIPTIONS_QUERY_KEY, CHARGES_QUERY_KEY } from '../constants/query-keys.constants';
7
7
  import type { UpdateSubscriptionPlanRequest } from '../types/calculate-subscription.type';
8
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
8
9
 
9
10
  export function useUpdateSubscriptionPlan() {
10
11
  const queryClient = useQueryClient();
12
+ const subscriptionsKey = useAuthQueryKey([...SUBSCRIPTIONS_QUERY_KEY]);
13
+ const chargesKey = useAuthQueryKey([...CHARGES_QUERY_KEY]);
11
14
 
12
15
  return useMutation({
13
16
  mutationFn: ({
@@ -18,8 +21,8 @@ export function useUpdateSubscriptionPlan() {
18
21
  data: UpdateSubscriptionPlanRequest;
19
22
  }) => withAction(updateSubscriptionPlanAction)(subscriptionId, data),
20
23
  onSuccess: () => {
21
- queryClient.invalidateQueries({ queryKey: SUBSCRIPTIONS_QUERY_KEY });
22
- queryClient.invalidateQueries({ queryKey: ['charges'] });
24
+ queryClient.invalidateQueries({ queryKey: subscriptionsKey });
25
+ queryClient.invalidateQueries({ queryKey: chargesKey });
23
26
  },
24
27
  });
25
28
  }
@@ -6,21 +6,26 @@ import { markMessageAsReadAction } from '../action/mark-message-as-read.action';
6
6
  import { markAllMessagesAsReadAction } from '../action/mark-all-messages-as-read.action';
7
7
  import { withAction } from '../../../utils/withAction';
8
8
  import type { FindMessagesParams } from '../schema/messages.schema';
9
+ import { useAuthQueryKey } from '../../../hooks/useAuthQueryKey';
9
10
 
10
- export const MESSAGES_QUERY_KEY = ['messages'];
11
+ export const MESSAGES_QUERY_KEY = ['messages'] as const;
11
12
 
12
13
  const INFINITE_MESSAGES_PAGE_SIZE = 10;
13
14
 
14
15
  export function useMessages(params?: Partial<FindMessagesParams>) {
16
+ const queryKey = useAuthQueryKey([...MESSAGES_QUERY_KEY, params]);
17
+
15
18
  return useQuery({
16
- queryKey: [...MESSAGES_QUERY_KEY, params],
19
+ queryKey,
17
20
  queryFn: withAction(() => listMessagesAction(params)),
18
21
  });
19
22
  }
20
23
 
21
24
  export function useInfiniteMessages(params?: Partial<Omit<FindMessagesParams, 'page' | 'limit'>>) {
25
+ const queryKey = useAuthQueryKey([...MESSAGES_QUERY_KEY, 'infinite', params]);
26
+
22
27
  return useInfiniteQuery({
23
- queryKey: [...MESSAGES_QUERY_KEY, 'infinite', params],
28
+ queryKey,
24
29
  queryFn: ({ pageParam }) =>
25
30
  withAction(() =>
26
31
  listMessagesAction({
@@ -39,22 +44,24 @@ export function useInfiniteMessages(params?: Partial<Omit<FindMessagesParams, 'p
39
44
 
40
45
  export function useMarkMessageAsRead() {
41
46
  const queryClient = useQueryClient();
47
+ const messagesKey = useAuthQueryKey([...MESSAGES_QUERY_KEY]);
42
48
 
43
49
  return useMutation({
44
50
  mutationFn: withAction(markMessageAsReadAction),
45
51
  onSuccess: () => {
46
- queryClient.invalidateQueries({ queryKey: MESSAGES_QUERY_KEY });
52
+ queryClient.invalidateQueries({ queryKey: messagesKey });
47
53
  },
48
54
  });
49
55
  }
50
56
 
51
57
  export function useMarkAllMessagesAsRead() {
52
58
  const queryClient = useQueryClient();
59
+ const messagesKey = useAuthQueryKey([...MESSAGES_QUERY_KEY]);
53
60
 
54
61
  return useMutation({
55
62
  mutationFn: withAction(markAllMessagesAsReadAction),
56
63
  onSuccess: () => {
57
- queryClient.invalidateQueries({ queryKey: MESSAGES_QUERY_KEY });
64
+ queryClient.invalidateQueries({ queryKey: messagesKey });
58
65
  },
59
66
  });
60
67
  }