Skip to content

Commit

Permalink
Merge pull request #91 from cabcookie/staging
Browse files Browse the repository at this point in the history
  • Loading branch information
cabcookie authored May 30, 2024
2 parents 663ea60 + 4ed4bd4 commit d0db544
Show file tree
Hide file tree
Showing 26 changed files with 1,737 additions and 73 deletions.
2 changes: 2 additions & 0 deletions amplify/data/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ const schema = a.schema({
projectsId: a.id().required(),
projects: a.belongsTo("Projects", "projectsId"),
})
.secondaryIndexes((index) => [index("projectsId")])
.authorization((allow) => [allow.owner()]),
Activity: a
.model({
Expand Down Expand Up @@ -150,6 +151,7 @@ const schema = a.schema({
projectsId: a.id().required(),
projects: a.belongsTo("Projects", "projectsId"),
})
.secondaryIndexes((index) => [index("projectsId"), index("accountId")])
.authorization((allow) => [allow.owner()]),
AccountResponsibilities: a
.model({
Expand Down
116 changes: 109 additions & 7 deletions api/ContextAccounts.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { type Schema } from "@/amplify/data/resource";
import { Responsibility } from "@/components/accounts/ResponsibilityRecord";
import {
EditorJsonContent,
transformNotesVersion,
} from "@/components/ui-elements/notes-writer/NotesWriter";
import { toISODateString } from "@/helpers/functional";
import { SelectionSet, generateClient } from "aws-amplify/data";
import { FC, ReactNode, createContext, useContext } from "react";
import useSWR from "swr";
Expand All @@ -24,25 +26,38 @@ interface AccountsContextType {
) => Promise<Schema["Account"]["type"] | undefined>;
getAccountById: (accountId: string) => Account | undefined;
updateAccount: (props: UpdateAccountProps) => Promise<string | undefined>;
addResponsibility: (newResp: Responsibility) => Promise<string | undefined>;
assignController: (
accountId: string,
controllerId: string | null
) => Promise<string | undefined>;
updateOrder: (accounts: Account[]) => Promise<(string | undefined)[]>;
}

export type Account = {
id: string;
name: string;
introduction?: EditorJsonContent | string;
controllerId?: string;
controller?: {
id: string;
name: string;
};
order: number;
responsibilities: { startDate: Date; endDate?: Date }[];
responsibilities: Responsibility[];
createdAt: Date;
};

const selectionSet = [
"id",
"name",
"accountSubsidiariesId",
"controller.id",
"controller.name",
"introduction",
"introductionJson",
"formatVersion",
"order",
"createdAt",
"responsibilities.id",
"responsibilities.startDate",
"responsibilities.endDate",
] as const;
Expand All @@ -52,12 +67,13 @@ type AccountData = SelectionSet<Schema["Account"]["type"], typeof selectionSet>;
export const mapAccount: (account: AccountData) => Account = ({
id,
name,
accountSubsidiariesId,
controller,
introduction,
introductionJson,
formatVersion,
order,
responsibilities,
createdAt,
}) => ({
id,
name,
Expand All @@ -66,10 +82,12 @@ export const mapAccount: (account: AccountData) => Account = ({
notes: introduction,
notesJson: introductionJson,
}),
controllerId: accountSubsidiariesId || undefined,
controller,
order: order || 0,
createdAt: new Date(createdAt),
responsibilities: responsibilities
.map(({ startDate, endDate }) => ({
.map(({ id, startDate, endDate }) => ({
id,
startDate: new Date(startDate),
endDate: !endDate ? undefined : new Date(endDate),
}))
Expand Down Expand Up @@ -97,7 +115,7 @@ export const AccountsContextProvider: FC<AccountsContextProviderProps> = ({
error: errorAccounts,
isLoading: loadingAccounts,
mutate,
} = useSWR(`/api/accounts/`, fetchAccounts);
} = useSWR("/api/accounts/", fetchAccounts);

const createAccount = async (
accountName: string
Expand All @@ -109,6 +127,7 @@ export const AccountsContextProvider: FC<AccountsContextProviderProps> = ({
name: accountName,
order: 0,
responsibilities: [],
createdAt: new Date(),
};

const updatedAccounts = [...(accounts || []), newAccount];
Expand Down Expand Up @@ -162,6 +181,86 @@ export const AccountsContextProvider: FC<AccountsContextProviderProps> = ({
return data?.id;
};

const assignController = async (
accountId: string,
controllerId: string | null
) => {
const updated: Account[] | undefined = accounts?.map((account) =>
account.id !== accountId
? account
: {
...account,
controller: !controllerId
? undefined
: {
id: controllerId,
name:
accounts.find(({ id }) => id === controllerId)?.name || "",
},
}
);
if (updated) mutate(updated, false);
const { data, errors } = await client.models.Account.update({
id: accountId,
accountSubsidiariesId: controllerId,
});
if (errors) handleApiErrors(errors, "Error updating parent company");
if (!data) return;
if (updated) mutate(updated);
return data.id;
};

const addResponsibility = async ({
id,
startDate,
endDate,
}: Responsibility) => {
const updated = accounts?.map((account) =>
account.id !== id
? account
: {
...account,
responsibilities: [{ id: crypto.randomUUID(), startDate, endDate }],
}
);
if (accounts) mutate(updated, false);

const { data, errors } = await client.models.AccountResponsibilities.create(
{
accountId: id,
startDate: toISODateString(startDate),
endDate: !endDate ? undefined : toISODateString(endDate),
}
);
if (errors) handleApiErrors(errors, "Error creating new responsibility");
if (accounts) mutate(updated);
if (!data) return;
return data.id;
};

const updateAccountOrderNo = async (
id: string,
order: number
): Promise<string | undefined> => {
const { data, errors } = await client.models.Account.update({ id, order });
if (errors) handleApiErrors(errors, "Error updating the order of accounts");
return data?.id;
};

const updateOrder = async (items: Account[]) => {
const updated: Account[] | undefined = accounts?.map(({ id, ...rest }) => ({
id,
...rest,
order: items.find((item) => item.id === id)?.order || rest.order,
}));
if (updated) mutate(updated, false);
const result = await Promise.all(
items.map(({ id, order }) => updateAccountOrderNo(id, order))
);
if (updated) mutate(updated);
return result;
};

return (
<AccountsContext.Provider
value={{
Expand All @@ -171,6 +270,9 @@ export const AccountsContextProvider: FC<AccountsContextProviderProps> = ({
createAccount,
getAccountById,
updateAccount,
addResponsibility,
assignController,
updateOrder,
}}
>
{children}
Expand Down
55 changes: 52 additions & 3 deletions api/ContextProjects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import {
EditorJsonContent,
transformNotesVersion,
} from "@/components/ui-elements/notes-writer/NotesWriter";
import { toast } from "@/components/ui/use-toast";
import { Context } from "@/contexts/ContextContext";
import { addDaysToDate } from "@/helpers/functional";
import { addDaysToDate, toISODateString } from "@/helpers/functional";
import { SelectionSet, generateClient } from "aws-amplify/data";
import { flow } from "lodash/fp";
import { FC, ReactNode, createContext, useContext } from "react";
import useSWR, { KeyedMutator } from "swr";
import useSWR, { KeyedMutator, mutate } from "swr";
import { handleApiErrors } from "./globals";
const client = generateClient<Schema>();

Expand Down Expand Up @@ -46,6 +48,12 @@ interface ProjectsContextType {
projectId: string,
accountId: string
) => Promise<string | undefined>;
removeAccountFromProject: (
projectId: string,
projectName: string,
accountId: string,
accountName: string
) => Promise<string | undefined>;
updateProjectContext: (
projectId: string,
context: Context
Expand Down Expand Up @@ -155,7 +163,7 @@ const fetchProjects = (context?: Context) => async () => {
{ done: { ne: true } },
{
doneOn: {
ge: addDaysToDate(-90)(new Date()).toISOString().split("T")[0],
ge: flow(addDaysToDate(-90), toISODateString)(new Date()),
},
},
],
Expand Down Expand Up @@ -354,6 +362,46 @@ export const ProjectsContextProvider: FC<ProjectsContextProviderProps> = ({
return data?.id;
};

const removeAccountFromProject = async (
projectId: string,
projectName: string,
accountId: string,
accountName: string
) => {
const updated: Project[] | undefined = projects?.map((p) =>
p.id !== projectId
? p
: {
...p,
accountIds: p.accountIds.filter((id) => id !== accountId),
}
);
if (updated) mutate(updated, false);

const accProj =
await client.models.AccountProjects.listAccountProjectsByProjectsId(
{ projectsId: projectId },
{ filter: { accountId: { eq: accountId } } }
);
if (accProj.errors)
handleApiErrors(accProj.errors, "Error fetching account/project link");
if (!accProj.data) return;
const result = await client.models.AccountProjects.delete({
id: accProj.data[0].id,
});
if (result.errors)
handleApiErrors(result.errors, "Error deleting account/project link");

if (updated) mutate(updated);

toast({
title: "Removed account from project",
description: `Removed account ${accountName} from project ${projectName}.`,
});

return result.data?.id;
};

const updateProjectContext = async (
projectId: string,
newContext: Context
Expand Down Expand Up @@ -383,6 +431,7 @@ export const ProjectsContextProvider: FC<ProjectsContextProviderProps> = ({
saveProjectDates,
updateProjectState,
addAccountToProject,
removeAccountFromProject,
updateProjectContext,
mutateProjects,
}}
Expand Down
Loading

0 comments on commit d0db544

Please sign in to comment.