Skip to content

Commit

Permalink
Merge pull request #42 from Codehagen/41-feature-ux-and-error-handling
Browse files Browse the repository at this point in the history
41 feature ux and error handling
  • Loading branch information
Codehagen authored Jul 30, 2024
2 parents c2f8c9a + 16ec019 commit 39bd69f
Show file tree
Hide file tree
Showing 43 changed files with 971 additions and 494 deletions.
2 changes: 1 addition & 1 deletion apps/www/.content-collections/generated/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// generated by content-collections at Mon Jul 29 2024 19:17:30 GMT+0200 (Central European Summer Time)
// generated by content-collections at Tue Jul 30 2024 11:03:01 GMT+0200 (Central European Summer Time)

import allDocs from "./allDocs.js";
import allMetas from "./allMetas.js";
Expand Down
79 changes: 46 additions & 33 deletions apps/www/src/actions/create-contract.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,63 @@
"use server";
"use server"

import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/session";
import { prisma } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"

export async function createContract(contractData) {
const user = await getCurrentUser();
const userId = user?.id;
const user = await getCurrentUser()
const userId = user?.id

if (!userId) {
console.error("No user is currently logged in.");
return { success: false, error: "User not authenticated" };
console.error("No user is currently logged in.")
return { success: false, error: "User not authenticated" }
}

try {
// Fetch the user's workspace to associate the contract
const workspace = await prisma.workspace.findFirst({
where: { users: { some: { id: userId } } },
select: { id: true },
// Fetch the workspace associated with the user
const userWorkspace = await prisma.workspace.findFirst({
where: {
users: {
some: {
id: userId,
},
},
},
select: {
id: true,
},
});

if (!workspace) {
throw new Error("No workspace found for this user");
if (!userWorkspace) {
console.error("No workspace found for this user.")
return { success: false, error: "No workspace found" }
}

// Create a new contract
const newContract = await prisma.contract.create({
data: {
tenantId: contractData.tenantId,
propertyId: contractData.property,
buildingId: contractData.building,
floors: {
connect: { id: contractData.floor },
workspace: {
connect: { id: userWorkspace.id }
},
officeSpaces: {
connect: { id: contractData.officeSpace },
tenant: {
connect: { id: contractData.tenantId }
},
property: {
connect: { id: contractData.propertyId }
},
building: {
connect: { id: contractData.buildingId }
},
floors: contractData.floors,
officeSpaces: contractData.officeSpaces,
contact: {
connect: { id: contractData.contactId }
},
workspaceId: workspace.id,
contactId: parseInt(contractData.contactId), // Ensure contactId is passed correctly
contactName: contractData.contactName,
contactEmail: contractData.contactEmail,
contactPhone: contractData.contactPhone,
landlordOrgnr: contractData.landlordOrgnr,
landlordName: contractData.landlordName,
contractType: contractData.contractType,
contactName: contractData.contactName,
contactEmail: contractData.contactEmail,
contactPhone: contractData.contactPhone,
startDate: contractData.startDate,
endDate: contractData.endDate,
negotiationDate: contractData.negotiationDate,
Expand All @@ -57,15 +72,13 @@ export async function createContract(contractData) {
businessCategory: contractData.businessCategory,
collateral: contractData.collateral,
},
});
})

console.log(
`Created contract with ID: ${newContract.id} for workspace ID: ${workspace.id}.`
);
console.log(`Created contract with ID: ${newContract.id} for workspace ID: ${userWorkspace.id}.`)

return { success: true, contract: newContract };
return { success: true, contract: newContract }
} catch (error) {
console.error(`Error creating contract for user ID: ${userId}`, error);
return { success: false, error: error.message };
console.error(`Error creating contract for user ID: ${userId}`, error)
return { success: false, error: error.message }
}
}
}
32 changes: 16 additions & 16 deletions apps/www/src/actions/create-tenant.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
"use server";
"use server"

import { revalidatePath } from "next/cache";
import { revalidatePath } from "next/cache"

import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/session";
import { prisma } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"

export async function createTenant(tenantData) {
const user = await getCurrentUser();
const userId = user?.id;
const user = await getCurrentUser()
const userId = user?.id

if (!userId) {
console.error("No user is currently logged in.");
return { success: false, error: "User not authenticated" };
console.error("No user is currently logged in.")
return { success: false, error: "User not authenticated" }
}

try {
// Fetch the user's workspace to associate the tenant
const workspace = await prisma.workspace.findFirst({
where: { users: { some: { id: userId } } },
select: { id: true },
});
})

if (!workspace) {
throw new Error("No workspace found for this user");
throw new Error("No workspace found for this user")
}

// Create a new tenant within the found workspace
Expand All @@ -34,16 +34,16 @@ export async function createTenant(tenantData) {
propertyId: tenantData.propertyId,
buildingId: tenantData.buildingId,
},
});
})
console.log(
`Created tenant with ID: ${newTenant.id} for workspace ID: ${workspace.id}.`,
);
)

revalidatePath("/dashboard"); // Updates the cache for the dashboard page
revalidatePath("/tenant")

return { success: true, tenant: newTenant };
return { success: true, tenant: newTenant }
} catch (error) {
console.error(`Error creating tenant for user ID: ${userId}`, error);
return { success: false, error: error.message };
console.error(`Error creating tenant for user ID: ${userId}`, error)
return { success: false, error: error.message }
}
}
62 changes: 62 additions & 0 deletions apps/www/src/actions/delete-tenant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"use server"

import { revalidatePath } from "next/cache"

import { prisma } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"

export async function deleteTenant(tenantId: string) {
const user = await getCurrentUser()
const userId = user?.id

if (!userId) {
console.error("No user is currently logged in.")
return { success: false, error: "User not authenticated" }
}

try {
// Check if the tenant exists
const tenant = await prisma.tenant.findUnique({
where: { id: tenantId },
include: { property: true },
})

if (!tenant) {
throw new Error("Tenant not found")
}

// Check if the user has permission to delete this tenant
const userWorkspace = await prisma.workspace.findFirst({
where: { users: { some: { id: userId } } },
include: { properties: true },
})

if (
!userWorkspace ||
!userWorkspace.properties.some((p) => p.id === tenant.propertyId)
) {
throw new Error("You don't have permission to delete this tenant")
}

// Delete related records first
await prisma.$transaction([
// Delete contracts first
prisma.contract.deleteMany({ where: { tenantId } }),
// Then delete other related records
prisma.customerInvoice.deleteMany({ where: { tenantId } }),
prisma.tenantCommunications.deleteMany({ where: { tenantId } }),
prisma.contactPerson.deleteMany({ where: { tenantId } }),
// Finally, delete the tenant
prisma.tenant.delete({ where: { id: tenantId } }),
])

console.log(`Deleted tenant with ID: ${tenantId}`)

revalidatePath("/tenant")

return { success: true }
} catch (error) {
console.error(`Error deleting tenant with ID: ${tenantId}`, error)
return { success: false, error: error.message }
}
}
2 changes: 2 additions & 0 deletions apps/www/src/actions/get-tenant-details.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"use server"

import { revalidatePath } from "next/cache"

import { prisma } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"

Expand Down
23 changes: 22 additions & 1 deletion apps/www/src/actions/get-tenants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,36 @@ export async function getTenants(workspaceId: string) {
officeSpace: {
select: {
name: true,
isRented: true,
},
},
contracts: {
select: {
baseRent: true,
startDate: true,
endDate: true,
},
orderBy: {
startDate: "desc",
},
take: 1,
},
},
orderBy: {
name: "asc",
},
})

return { success: true, tenants }
return {
success: true,
tenants: tenants.map((tenant) => ({
...tenant,
isRenting: tenant.officeSpace?.isRented ?? false,
currentRent: tenant.contracts[0]?.baseRent ?? null,
contractStartDate: tenant.contracts[0]?.startDate ?? null,
contractEndDate: tenant.contracts[0]?.endDate ?? null,
})),
}
} catch (error) {
console.error("Error fetching tenants:", error)
return { success: false, error: error.message }
Expand Down
75 changes: 75 additions & 0 deletions apps/www/src/actions/update-tenant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"use server"

import { revalidatePath } from "next/cache"

import { prisma } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"

export async function updateTenant(
tenantId: string,
tenantData: {
name: string
orgnr?: number | null
numEmployees: number
buildingId: string
floorId?: string | null
officeSpaceId?: string | null
propertyId: string
},
) {
const user = await getCurrentUser()
const userId = user?.id

if (!userId) {
console.error("No user is currently logged in.")
return { success: false, error: "User not authenticated" }
}

try {
// Check if the tenant exists
const tenant = await prisma.tenant.findUnique({
where: { id: tenantId },
include: { property: true },
})

if (!tenant) {
throw new Error("Tenant not found")
}

// Check if the user has permission to update this tenant
const userWorkspace = await prisma.workspace.findFirst({
where: { users: { some: { id: userId } } },
include: { properties: true },
})

if (
!userWorkspace ||
!userWorkspace.properties.some((p) => p.id === tenant.propertyId)
) {
throw new Error("You don't have permission to update this tenant")
}

// Update the tenant
const updatedTenant = await prisma.tenant.update({
where: { id: tenantId },
data: {
name: tenantData.name,
orgnr: tenantData.orgnr,
numEmployees: tenantData.numEmployees,
buildingId: tenantData.buildingId,
floorId: tenantData.floorId,
officeSpaceId: tenantData.officeSpaceId,
propertyId: tenantData.propertyId,
},
})

console.log(`Updated tenant with ID: ${tenantId}`)

revalidatePath("/tenant")

return { success: true, tenant: updatedTenant }
} catch (error) {
console.error(`Error updating tenant with ID: ${tenantId}`, error)
return { success: false, error: error.message }
}
}
Loading

0 comments on commit 39bd69f

Please sign in to comment.