Merge pull request #39 from BarkProductions/38-add-customer-page

38 add customer page
This commit is contained in:
Drew Rautenberg
2026-07-18 19:00:45 -05:00
committed by GitHub
9 changed files with 455 additions and 0 deletions
+69
View File
@@ -47,6 +47,10 @@ var itemStatusGroup = app.MapGroup(prefix: "/itemstatus")
.WithTags("Item Status") .WithTags("Item Status")
.WithDescription("Endpoints for managing item status"); .WithDescription("Endpoints for managing item status");
var customerGroup = app.MapGroup(prefix: "/customers")
.WithTags("Customers")
.WithDescription("Endpoints for managing customers");
inventoryGroup.MapGet("", async (BarkContext db) => inventoryGroup.MapGet("", async (BarkContext db) =>
await db.Inventory.OrderBy(item => item.Barcode).ToListAsync()); await db.Inventory.OrderBy(item => item.Barcode).ToListAsync());
@@ -163,6 +167,71 @@ itemStatusGroup.MapDelete("/{id}", async (string id, BarkContext db) =>
return Results.Ok(new { Message = "Item status deleted successfully" }); return Results.Ok(new { Message = "Item status deleted successfully" });
}); });
customerGroup.MapGet("", async (BarkContext db) =>
await db.Customers.OrderBy(customer => customer.Id).ToListAsync());
customerGroup.MapGet("/{id}", async (int id, BarkContext db) =>
{
var customer = await db.Customers
.FirstOrDefaultAsync(i => i.Id == id);
if (customer == null)
{
return Results.NotFound(new { Message = "Customer not found" });
}
return Results.Ok(customer);
});
customerGroup.MapPut("/{id}", async (int id, Customers updatedCustomer, BarkContext db) =>
{
var existingCustomer = await db.Customers.FindAsync(id);
if (existingCustomer == null)
{
return Results.NotFound(new { Message = "Customer not found" });
}
existingCustomer.Name = updatedCustomer.Name;
existingCustomer.Company = updatedCustomer.Company;
existingCustomer.Email = updatedCustomer.Email;
existingCustomer.PhoneNumber = updatedCustomer.PhoneNumber;
existingCustomer.Address = updatedCustomer.Address;
existingCustomer.BillingTerms = updatedCustomer.BillingTerms;
existingCustomer.Notes = updatedCustomer.Notes;
await db.SaveChangesAsync();
return Results.Ok(existingCustomer);
});
customerGroup.MapPost("", async (Customers newCustomerInput, BarkContext db) =>
{
var newCustomer = new Customers()
{
Name = newCustomerInput.Name,
Email = newCustomerInput.Email,
Company = newCustomerInput.Company,
PhoneNumber = newCustomerInput.PhoneNumber,
Address = newCustomerInput.Address,
};
db.Customers.Add(newCustomer);
await db.SaveChangesAsync();
return Results.Created($"/customers/{newCustomer.Id}", newCustomer);
});
customerGroup.MapDelete("/{id}", async (int id, BarkContext db) =>
{
var customer = await db.Customers.FindAsync(id);
if (customer == null)
{
return Results.NotFound(new { Message = "Customer not found" });
}
db.Customers.Remove(customer);
await db.SaveChangesAsync();
return Results.Ok(new { Message = "Customer deleted successfully" });
});
using (var serviceScope = app.Services.CreateScope()) using (var serviceScope = app.Services.CreateScope())
{ {
var dbContext = serviceScope.ServiceProvider.GetRequiredService<BarkContext>(); var dbContext = serviceScope.ServiceProvider.GetRequiredService<BarkContext>();
+9
View File
@@ -10,6 +10,10 @@ import {BarkHeader} from "./common/components/BarkHeader.tsx";
import AddItem from "./features/inventory/AddItem.tsx"; import AddItem from "./features/inventory/AddItem.tsx";
import { Notifications } from '@mantine/notifications'; import { Notifications } from '@mantine/notifications';
import '@mantine/notifications/styles.css'; import '@mantine/notifications/styles.css';
import CustomerList from "@/features/customers/CustomerList.tsx";
import AddCustomer from "@/features/customers/AddCustomer.tsx";
import CustomerDetail from "@/features/customers/CustomerDetail.tsx";
import EditCustomer from "@/features/customers/EditCustomer.tsx";
// Create a client // Create a client
const queryClient = new QueryClient() const queryClient = new QueryClient()
@@ -46,6 +50,11 @@ function App() {
<Route path="inventory/itemDetail/:itemId" element={<ItemDetail/>}/> <Route path="inventory/itemDetail/:itemId" element={<ItemDetail/>}/>
<Route path="inventory/editItem/:itemId" element={<EditItem/>}/> <Route path="inventory/editItem/:itemId" element={<EditItem/>}/>
<Route path="inventory/addItem" element={<AddItem/>}/> <Route path="inventory/addItem" element={<AddItem/>}/>
<Route path="customers" element={<CustomerList/>}/>
<Route path="customers/addCustomer" element={<AddCustomer/>}/>
<Route path="customers/customerDetail/:customerId" element={<CustomerDetail/>}/>
<Route path="customers/editCustomer/:customerId" element={<EditCustomer/>}/>
</Routes> </Routes>
</> </>
</QueryClientProvider> </QueryClientProvider>
@@ -7,6 +7,7 @@ import BarkLogo from '@/assets/barklogo.png';
const links = [ const links = [
{ link: '/', label: 'Home' }, { link: '/', label: 'Home' },
{ link: '/customers', label: 'Customers' },
{ link: '/inventory', label: 'Inventory' }, { link: '/inventory', label: 'Inventory' },
]; ];
@@ -0,0 +1,109 @@
import {Button, Group, TextInput, Container, Title, Flex} from '@mantine/core';
import {useForm} from '@mantine/form';
import {useMutation} from "@tanstack/react-query";
import {NewCustomer} from "./types.ts";
import {useNavigate} from "react-router";
import {IconX, IconCheck} from '@tabler/icons-react';
import {notifications} from '@mantine/notifications';
import useCustomerList from "./hooks/useCustomerList.tsx";
function AddCustomer() {
const navigate = useNavigate();
const customerQuery = useCustomerList();
const newCustomerForm = useForm<NewCustomer>({
mode: 'uncontrolled',
initialValues: {
name: "",
company: "",
email: "",
phone: "",
address: "",
},
validate: {},
});
const updateCustomer = useMutation({
mutationFn: async (values: NewCustomer) => {
const result = await fetch(import.meta.env.VITE_API_URL + '/customers', {
method: 'POST',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json'
}
});
if (result.ok) {
notifications.show({
icon: <IconCheck size={20}/>,
color: "teal",
title: "All good!",
message: "Customer Created",
position: 'top-center',
});
navigate("/customers");
}
if (!result.ok) {
notifications.show({
icon: <IconX size={20}/>,
color: "red",
title: "Bummer!",
message: "Something went wrong",
position: 'top-center',
});
throw new Error('Failed to create customer');
}
},
})
if (customerQuery.isPending) return 'Loading...'
if (customerQuery.error) return 'An error has occurred: ' + customerQuery.error.message
return (
<>
<form onSubmit={newCustomerForm.onSubmit(async (values) => await
updateCustomer.mutateAsync(values))}>
<Container m="lg">
<Flex mih={50}
gap="md"
justify="flex-start"
align="flex-start"
direction="column"
wrap="wrap">
<Title order={1}>Add Item</Title>
<TextInput withAsterisk key={newCustomerForm.key('name')} size="md" label="Name"
placeholder="Name" {...newCustomerForm.getInputProps('name')}/>
<TextInput size="md" key={newCustomerForm.key('company')} label="Company"
placeholder="Company"{...newCustomerForm.getInputProps('company')}/>
<TextInput withAsterisk size="md" key={newCustomerForm.key('email')} label="Email"
placeholder="Email" {...newCustomerForm.getInputProps('email')}/>
<TextInput size="md" key={newCustomerForm.key('phone')} label="Phone"
placeholder="Phone" {...newCustomerForm.getInputProps('phone')}/>
<TextInput size="md" key={newCustomerForm.key('address')} label="Address"
placeholder="Address" {...newCustomerForm.getInputProps('address')}/>
<Group justify="flex-end" mt="md">
<Button type="submit">Submit</Button>
</Group>
</Flex>
</Container>
</form>
</>
);
}
export default AddCustomer;
@@ -0,0 +1,45 @@
import {Container, Text, Title} from "@mantine/core";
import {Link, useParams} from "react-router";
import {Customer} from "./types.ts";
import {useQuery} from "@tanstack/react-query";
function CustomerDetail() {
const params = useParams();
const {isPending, error, data, isFetching} = useQuery({
queryKey: ['customers', params.customerId],
queryFn: async (): Promise<Customer> => {
const response = await fetch(
import.meta.env.VITE_API_URL + '/customers/' + params.customerId,
)
if (!response.ok) throw new Error('Failed to fetch customer ' + response.statusText)
return await response.json()
},
});
if (isPending) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<>
<Container m="lg">
<Title order={1}>Customer Detail</Title>
<div>{isFetching ? 'Updating...' : ''}</div>
<Text>Name: {data.name}</Text>
<Text>Company: {data.company}</Text>
<Text>Email: {data.email}</Text>
<Text>Phone Number: {data.phone}</Text>
<Text>Address: ${data.address}</Text>
<Text>Notes: {data.notes}</Text>
<Link to={`/customers/editCustomer/${data.id}`}>Edit</Link>
</Container>
</>
)
}
export default CustomerDetail
@@ -0,0 +1,54 @@
import {Flex, Table} from '@mantine/core';
import BarkButton from "../../common/components/BarkButton.tsx";
import {Link, NavLink} from "react-router";
import useCustomerList from "./hooks/useCustomerList.tsx";
function CustomerList() {
const customerQuery = useCustomerList();
if (customerQuery.isPending) return 'Loading...'
if (customerQuery.error) return 'An error has occurred: ' + customerQuery.error.message
return (
<>
<Flex
mih={50}
gap="xl"
justify="center"
align="center"
direction="row"
wrap="wrap"
>
<p>
ARFF ARFF BARK BARK
</p>
<NavLink to={'/customers/AddCustomer'}><BarkButton>Add Customer</BarkButton></NavLink>
</Flex>
<Table striped>
<Table.Thead>
<Table.Tr>
<Table.Th c="red">Name</Table.Th>
<Table.Th c="red">Company</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{customerQuery.data?.map((data) => (
<Table.Tr key={data.id}>
<Table.Td>{data.name}</Table.Td>
<Table.Td>{data.company}</Table.Td>
<Table.Td>
<Link to={`/customers/customerDetail/${data.id}`}>Details</Link>
</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
</Table>
</>
)
}
export default CustomerList;
@@ -0,0 +1,134 @@
import {Button, Group, TextInput, Container, Title, Flex} from '@mantine/core';
import {useForm} from '@mantine/form';
import {useNavigate, useParams} from "react-router";
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
import {Customer} from "./types.ts";
import {useEffect} from "react";
import {notifications} from "@mantine/notifications";
import {IconCheck, IconX} from "@tabler/icons-react";
type EditableCustomer= Omit<Customer, 'id'>;
function EditCustomer() {
const params = useParams();
const navigate = useNavigate();
const editCustomerForm = useForm<EditableCustomer>({
mode: 'uncontrolled',
initialValues: {
name: "",
company: "",
email: "",
phone: "",
address: "",
billingTerms: "",
notes: "",
},
validate: {},
});
const {isPending, error, data, isFetching} = useQuery({
queryKey: ['customer', params.customerId],
queryFn: async (): Promise<Customer> => {
const response = await fetch(
import.meta.env.VITE_API_URL + '/customers/' + params.customerId,
)
if (!response.ok) throw new Error('Failed to fetch customer ' + response.statusText)
return await response.json()
},
});
const queryClient = useQueryClient();
const updateCustomer = useMutation({
mutationFn: async (values: EditableCustomer) => {
// await <call the api, do the things>
const result = await fetch(import.meta.env.VITE_API_URL + '/customers/' + params.customerId, {
method: 'PUT',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json'
}
});
if (result.ok) {
notifications.show({
icon: <IconCheck size={20} />,
color:"teal",
title: "All good!",
message: "Customer Updated",
position: 'top-center',
});
navigate("/customers");
}
if (!result.ok) {
notifications.show({
icon: <IconX size={20} />,
color:"red",
title: "Bummer!",
message: "Something went wrong",
position: 'top-center',
});
throw new Error('Failed to update customer');
}
// invalidate the queries so they pull updated information
// this is a prefix, so it covers both the query that pulls a list, and also `['customers', customerId]` in this file
await queryClient.invalidateQueries({
queryKey: ['customers']
});
}
})
useEffect(() => {
if (data) {
// Even if query.data changes, form will be initialized only once
editCustomerForm.initialize(data);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data]);
if (isPending) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<form onSubmit={editCustomerForm.onSubmit(async (values) => await
updateCustomer.mutateAsync(values))}>
<Container m="lg">
<Flex mih={50}
gap="md"
justify="flex-start"
align="flex-start"
direction="column"
wrap="wrap">
<div>{isFetching ? 'Updating...' : ''}</div>
<Title order={1}>Edit Customer</Title>
<TextInput withAsterisk key={editCustomerForm.key('name')} size="md" label="Name"
placeholder="Name" {...editCustomerForm.getInputProps('name')}/>
<TextInput size="md" key={editCustomerForm.key('company')} label="Company"
placeholder="Company"{...editCustomerForm.getInputProps('company')}/>
<TextInput withAsterisk size="md" key={editCustomerForm.key('email')} label="Email"
placeholder="Email" {...editCustomerForm.getInputProps('email')}/>
<TextInput size="md" key={editCustomerForm.key('phone')} label="Phone"
placeholder="Phone" {...editCustomerForm.getInputProps('phone')}/>
<TextInput size="md" key={editCustomerForm.key('address')} label="Address"
placeholder="Address" {...editCustomerForm.getInputProps('address')}/>
<Group justify="flex-end" mt="md">
<Button type="submit">Submit</Button>
</Group>
</Flex>
</Container>
</form>
);
}
export default EditCustomer;
@@ -0,0 +1,17 @@
import {useQuery} from "@tanstack/react-query";
import {Customer} from "../types.ts";
const useCustomerList = () => useQuery({
queryKey: ['customer'],
queryFn: async (): Promise<Customer[]> => {
const response = await fetch(
import.meta.env.VITE_API_URL + '/customers',
)
if (!response.ok) throw new Error('Failed to fetch customers ' + response.statusText)
return await response.json()
},
});
export default useCustomerList;
+17
View File
@@ -0,0 +1,17 @@
export interface Customer {
id: number,
name: string,
company: string,
email: string,
phone: string,
address: string,
billingTerms: string,
notes: string,
}
export interface NewCustomer {
name: string,
company: string,
email: string,
phone: string,
address: string,
}