Skip to content

Commit d7a15e2

Browse files
committed
Fix: Edit company
1 parent 68e8b62 commit d7a15e2

12 files changed

Lines changed: 239 additions & 60 deletions

File tree

package-lock.json

Lines changed: 30 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"@radix-ui/react-scroll-area": "^1.0.5",
2727
"@radix-ui/react-select": "^2.0.0",
2828
"@radix-ui/react-slot": "^1.0.2",
29+
"@radix-ui/react-switch": "^1.0.3",
2930
"@radix-ui/react-tabs": "^1.0.4",
3031
"@radix-ui/react-toast": "^1.1.5",
3132
"@radix-ui/react-toggle": "^1.0.3",
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
-- RedefineTables
2+
PRAGMA foreign_keys=OFF;
3+
CREATE TABLE "new_Job" (
4+
"id" TEXT NOT NULL PRIMARY KEY,
5+
"userId" TEXT NOT NULL,
6+
"jobUrl" TEXT,
7+
"description" TEXT NOT NULL,
8+
"jobType" TEXT NOT NULL,
9+
"createdAt" DATETIME NOT NULL,
10+
"applied" BOOLEAN NOT NULL DEFAULT false,
11+
"appliedDate" DATETIME,
12+
"dueDate" DATETIME,
13+
"statusId" TEXT NOT NULL,
14+
"jobTitleId" TEXT NOT NULL,
15+
"companyId" TEXT NOT NULL,
16+
"jobSourceId" TEXT,
17+
"salaryRange" TEXT,
18+
"locationId" TEXT,
19+
CONSTRAINT "Job_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
20+
CONSTRAINT "Job_statusId_fkey" FOREIGN KEY ("statusId") REFERENCES "JobStatus" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
21+
CONSTRAINT "Job_jobTitleId_fkey" FOREIGN KEY ("jobTitleId") REFERENCES "JobTitle" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
22+
CONSTRAINT "Job_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
23+
CONSTRAINT "Job_jobSourceId_fkey" FOREIGN KEY ("jobSourceId") REFERENCES "JobSource" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
24+
CONSTRAINT "Job_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location" ("id") ON DELETE SET NULL ON UPDATE CASCADE
25+
);
26+
INSERT INTO "new_Job" ("appliedDate", "companyId", "createdAt", "description", "dueDate", "id", "jobSourceId", "jobTitleId", "jobType", "locationId", "salaryRange", "statusId", "userId") SELECT "appliedDate", "companyId", "createdAt", "description", "dueDate", "id", "jobSourceId", "jobTitleId", "jobType", "locationId", "salaryRange", "statusId", "userId" FROM "Job";
27+
DROP TABLE "Job";
28+
ALTER TABLE "new_Job" RENAME TO "Job";
29+
PRAGMA foreign_key_check("Job");
30+
PRAGMA foreign_keys=ON;

prisma/schema.prisma

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,11 @@ model Job {
9292
id String @id @default(uuid())
9393
userId String
9494
User User @relation(fields: [userId], references: [id])
95+
jobUrl String?
9596
description String
9697
jobType String
9798
createdAt DateTime
99+
applied Boolean @default(false)
98100
appliedDate DateTime?
99101
dueDate DateTime?
100102
statusId String

src/actions/company.actions.ts

Lines changed: 78 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"use server";
22
import prisma from "@/lib/db";
3+
import { AddCompanyFormSchema } from "@/models/addCompanyForm.schema";
34
import { getCurrentUser } from "@/utils/user.utils";
5+
import { z } from "zod";
46

57
export const getCompanyList = async (
68
page = 1,
@@ -84,9 +86,8 @@ export const getAllCompanies = async (): Promise<any | undefined> => {
8486
}
8587
};
8688

87-
export const createCompany = async (
88-
label: string,
89-
logoUrl?: string
89+
export const addCompany = async (
90+
data: z.infer<typeof AddCompanyFormSchema>
9091
): Promise<any | undefined> => {
9192
try {
9293
const user = await getCurrentUser();
@@ -95,20 +96,85 @@ export const createCompany = async (
9596
throw new Error("Not authenticated");
9697
}
9798

98-
const value = label.trim().toLowerCase();
99+
const { company, logoUrl } = data;
99100

100-
// Upsert the name (create if it does not exist, update if it exists)
101-
const upsertedName = await prisma.company.upsert({
102-
where: { value },
103-
update: { label, value, logoUrl },
104-
create: { label, value, logoUrl, createdBy: user.id },
101+
const value = company.trim().toLowerCase();
102+
103+
const companyExists = await prisma.company.findUnique({
104+
where: {
105+
value,
106+
},
107+
});
108+
109+
if (companyExists) {
110+
throw new Error("Company already exists!");
111+
}
112+
113+
const res = await prisma.company.create({
114+
data: {
115+
createdBy: user.id,
116+
value,
117+
label: company,
118+
logoUrl,
119+
},
105120
});
106121

107-
return upsertedName;
122+
return { success: true, data: res };
108123
} catch (error) {
109-
const msg = "Failed to create company. ";
124+
const msg = "Failed to create company.";
110125
console.error(msg, error);
111-
throw new Error(msg);
126+
if (error instanceof Error) {
127+
return { success: false, message: error.message };
128+
}
129+
}
130+
};
131+
132+
export const updateCompany = async (
133+
data: z.infer<typeof AddCompanyFormSchema>
134+
): Promise<any | undefined> => {
135+
try {
136+
const user = await getCurrentUser();
137+
138+
if (!user) {
139+
throw new Error("Not authenticated");
140+
}
141+
142+
const { id, company, logoUrl, createdBy } = data;
143+
144+
if (!id || user.id != createdBy) {
145+
throw new Error("Id is not provided or no user privilages");
146+
}
147+
148+
const value = company.trim().toLowerCase();
149+
150+
const companyExists = await prisma.company.findUnique({
151+
where: {
152+
value,
153+
},
154+
});
155+
156+
if (companyExists) {
157+
throw new Error("Company already exists!");
158+
}
159+
160+
const res = await prisma.company.update({
161+
where: {
162+
id,
163+
},
164+
data: {
165+
value,
166+
label: company,
167+
logoUrl,
168+
},
169+
});
170+
171+
return { success: true, data: res };
172+
} catch (error) {
173+
const msg = "Failed to update company.";
174+
console.error(msg, error);
175+
if (error instanceof Error) {
176+
return { success: false, message: error.message };
177+
}
112178
}
113179
};
114180

src/actions/job.actions.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,6 @@ export const updateJob = async (
247247
throw new Error("Not authenticated");
248248
}
249249
if (!data.id || user.id != data.userId) {
250-
console.log({ data, user });
251250
throw new Error("Id is not provide or no user privilages");
252251
}
253252

src/app/dashboard/myjobs/page.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
getStatusList,
88
} from "@/actions/job.actions";
99
import JobsContainer from "@/components/JobsContainer";
10-
import { getAllCompanies, getCompanyList } from "@/actions/company.actions";
10+
import { getAllCompanies } from "@/actions/company.actions";
1111

1212
export const metadata: Metadata = {
1313
title: "My Jobs | JobSync",

src/components/AddCompany.tsx

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
Dialog,
66
DialogClose,
77
DialogContent,
8+
DialogDescription,
89
DialogFooter,
910
DialogHeader,
1011
DialogTitle,
@@ -25,7 +26,7 @@ import {
2526
} from "./ui/form";
2627
import { Input } from "./ui/input";
2728
import { toast } from "./ui/use-toast";
28-
import { createCompany } from "@/actions/company.actions";
29+
import { addCompany, updateCompany } from "@/actions/company.actions";
2930
import { Company } from "@/models/job.model";
3031

3132
type AddCompanyProps = {
@@ -48,13 +49,16 @@ function AddCompany({
4849
resolver: zodResolver(AddCompanyFormSchema),
4950
});
5051

51-
const { setValue, reset } = form;
52+
const { setValue, reset, formState } = form;
5253

5354
useEffect(() => {
5455
if (editCompany) {
5556
setValue("id", editCompany.id);
5657
setValue("company", editCompany.label);
57-
setValue("logoUrl", editCompany.logoUrl);
58+
setValue("createdBy", editCompany.createdBy);
59+
if (editCompany.logoUrl) {
60+
setValue("logoUrl", editCompany?.logoUrl);
61+
}
5862

5963
setDialogOpen(true);
6064
}
@@ -67,17 +71,27 @@ function AddCompany({
6771
};
6872

6973
const onSubmit = (data: z.infer<typeof AddCompanyFormSchema>) => {
70-
console.log("form data: ", data);
7174
startTransition(async () => {
72-
const res = await createCompany(data.company, data.logoUrl);
73-
reset();
74-
setDialogOpen(false);
75-
reloadCompanies();
76-
});
77-
toast({
78-
description: `Company has been ${
79-
editCompany ? "updated" : "created"
80-
} successfully`,
75+
const res = editCompany
76+
? await updateCompany(data)
77+
: await addCompany(data);
78+
if (!res.success) {
79+
toast({
80+
variant: "destructive",
81+
title: "Error!",
82+
description: res.message,
83+
});
84+
} else {
85+
reset();
86+
setDialogOpen(false);
87+
reloadCompanies();
88+
toast({
89+
variant: "success",
90+
description: `Company has been ${
91+
editCompany ? "updated" : "created"
92+
} successfully`,
93+
});
94+
}
8195
});
8296
};
8397

@@ -93,11 +107,15 @@ function AddCompany({
93107
<DialogContent className="lg:max-h-screen overflow-y-scroll">
94108
<DialogHeader>
95109
<DialogTitle>{pageTitle}</DialogTitle>
110+
<DialogDescription className="text-primary">
111+
Caution: Editing name of the company with affect all the related
112+
job records.
113+
</DialogDescription>
96114
</DialogHeader>
97115
<Form {...form}>
98116
<form
99117
onSubmit={form.handleSubmit(onSubmit)}
100-
className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4"
118+
className="grid grid-cols-1 md:grid-cols-2 gap-4 p-2"
101119
>
102120
{/* COMPANY NAME */}
103121
<div className="md:col-span-2">
@@ -145,7 +163,7 @@ function AddCompany({
145163
Cancel
146164
</Button>
147165
</DialogClose>
148-
<Button type="submit">
166+
<Button type="submit" disabled={!formState.isDirty}>
149167
Save
150168
{isPending ? (
151169
<Loader className="h-4 w-4 shrink-0 spinner" />

src/components/CompaniesTable.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
TableRow,
1919
} from "./ui/table";
2020
import { Company } from "@/models/job.model";
21-
import { MoreHorizontal } from "lucide-react";
21+
import { MoreHorizontal, Pencil } from "lucide-react";
2222
import { TablePagination } from "./TablePagination";
2323

2424
type CompaniesTableProps = {
@@ -92,7 +92,8 @@ function CompaniesTable({
9292
className="cursor-pointer"
9393
onClick={() => editCompany(company.id)}
9494
>
95-
Edit
95+
<Pencil className="mr-2 h-4 w-4" />
96+
Edit Company
9697
</DropdownMenuItem>
9798
<DropdownMenuItem>Delete</DropdownMenuItem>
9899
</DropdownMenuContent>

src/components/ui/switch.tsx

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"use client"
2+
3+
import * as React from "react"
4+
import * as SwitchPrimitives from "@radix-ui/react-switch"
5+
6+
import { cn } from "@/lib/utils"
7+
8+
const Switch = React.forwardRef<
9+
React.ElementRef<typeof SwitchPrimitives.Root>,
10+
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
11+
>(({ className, ...props }, ref) => (
12+
<SwitchPrimitives.Root
13+
className={cn(
14+
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
15+
className
16+
)}
17+
{...props}
18+
ref={ref}
19+
>
20+
<SwitchPrimitives.Thumb
21+
className={cn(
22+
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
23+
)}
24+
/>
25+
</SwitchPrimitives.Root>
26+
))
27+
Switch.displayName = SwitchPrimitives.Root.displayName
28+
29+
export { Switch }

0 commit comments

Comments
 (0)