Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Added disable merch toggle button #143

Merged
merged 16 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 99 additions & 19 deletions apps/cms/src/admin/utils/RenderCellFactory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,122 @@ import React from "react";
import payload from "payload";

export class RenderCellFactory {

static get(element: unknown, key: string) {
console.log(key)
if (element[key] == undefined) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
payload.logger.error(`Attribute ${key} cannot be found in element ${element.toString()}`);
payload.logger.error(
`Attribute ${key} cannot be found in element ${element.toString()}`
);
return null;
}

const isImageUrl = new RegExp("http(s?):\\/\\/.*.(jpg|png|jpeg)$");

if (Array.isArray(element[key])) {
if (
(element[key] as string[]).every((item: string) =>
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
isImageUrl.test((item as string).toString())
)
) {
// If the element is an array, render images accordingly
const ImagesComponent: React.FC<{ children?: React.ReactNode[] }> = ({
children,
}) => (
<span>
{children.map((imageUrl: string, index: number) => (
<img
key={index}
src={imageUrl}
alt={`image ${index + 1}`}
style={{ paddingTop: 10, paddingBottom: 10 }}
/>
))}
</span>
);
const ImagesComponentCell = (row, data) => (
<ImagesComponent>{data}</ImagesComponent>
);
return ImagesComponentCell;
} else {
// If the element is an array of strings, render them
const StringsComponent: React.FC<{ children?: React.ReactNode[] }> = ({
children,
}) => (
<span>
{children.map((text: string, index: number) => (
<span key={index}>
{index > 0 && ", "} {text}
</span>
))}
</span>
);
const StringsComponentCell = (row, data) => (
<StringsComponent>{data}</StringsComponent>
);
return StringsComponentCell;
}
}

if (isImageUrl.test((element[key] as string).toString())) {
const ImageComponent: React.FC<{children?: React.ReactNode}> = ({ children }) => (
const ImageComponent: React.FC<{ children?: React.ReactNode }> = ({
children,
}) => (
<span>
<img src={children.toString()} alt="image of object"/>
<img src={children.toString()} alt="image of object" />
</span>
);
const ImageComponentCell = (row, data) => <ImageComponent>{data}</ImageComponent>;
const ImageComponentCell = (row, data) => (
<ImageComponent>{data}</ImageComponent>
);
return ImageComponentCell;
}
if (key === "stock") {
const ObjectComponent: React.FC<{ data: string }> = ({ data }) => (
<div>
{Object.entries(data).map(([subKey, value], index) => (
<div key={index}>
<strong>{subKey}:</strong>{" "}
<span>
{typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)}
</span>
</div>
))}
</div>
);
const ObjectComponentCell = (row, data: string) => (
<ObjectComponent data={data} />
);
return ObjectComponentCell;

}
if (typeof element[key] == "object") {
const DateComponent: React.FC<{ children?: React.ReactNode }> = ({
children,
}) => <span>{(children as unknown as Date).toDateString()}</span>;
const DateComponentCell = (row, data) => (
<DateComponent>{data}</DateComponent>
);
return DateComponentCell;
}

if (typeof element[key] == 'object') {
const DateComponent: React.FC<{children?: React.ReactNode}> = ({ children }) => (
<span>
{(children as unknown as Date).toDateString()}
</span>
if (typeof element[key] === "boolean") {
// If the element is a boolean, render "Yes" or "No"
const BooleanComponent: React.FC<{ children?: React.ReactNode }> = ({
children,
}) => <span>{children ? "Yes" : "No"}</span>;
const BooleanComponentCell = (row, data) => (
<BooleanComponent>{data}</BooleanComponent>
);
const DateComponentCell = (row, data) => <DateComponent>{data}</DateComponent>;
return DateComponentCell
return BooleanComponentCell;
}

const TextComponent: React.FC<{children?: React.ReactNode}> = ({ children }) => (
<span>
{children}
</span>
const TextComponent: React.FC<{ children?: React.ReactNode }> = ({
children,
}) => <span>{children}</span>;
const TextComponentCell = (row, data) => (
<TextComponent>{data}</TextComponent>
);
const TextComponentCell = (row, data) => <TextComponent>{data}</TextComponent>;
return TextComponentCell
return TextComponentCell;
}
}
65 changes: 64 additions & 1 deletion apps/cms/src/admin/views/MerchOverview.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,49 @@
import React from "react";
import React, { useEffect, useState, ChangeEvent } from "react";
import { Button } from "payload/components/elements";
import { AdminView } from "payload/config";
import ViewTemplate from "./ViewTemplate";
import StoreApi from "../../apis/store.api";

const MerchOverview: AdminView = ({ user, canAccessAdmin }) => {
const [displayText, setDisplayText] = useState<string>(
"We are currently preparing for the next merch sale. Please look forward to our email!"
);
const [isStoreDisabled, setIsStoreDisabled] = useState<boolean>(true);
const [loading, setLoading] = useState<boolean>(true);

const SHOW_DISPLAY_TEXT_INPUT = false;

useEffect(() => {
const fetchStoreStatus = async () => {
try {
const { disabled } = await StoreApi.getStoreStatus();
setIsStoreDisabled(disabled);
setLoading(false);
} catch (error) {
console.error(error);
setLoading(false);
}
};

// eslint-disable-next-line @typescript-eslint/no-floating-promises
fetchStoreStatus();
}, []);

const disableStore = async () => {
// TODO: Calls api to disable merch store
try {
setLoading(true);
await StoreApi.setStoreStatus({
displayText,
disabled: !isStoreDisabled,
});
setIsStoreDisabled(!isStoreDisabled);
setLoading(false);
} catch (error) {
console.error(error);
setLoading(false);
}
};
return (
<ViewTemplate
user={user}
Expand All @@ -19,6 +59,29 @@ const MerchOverview: AdminView = ({ user, canAccessAdmin }) => {
<Button el="link" to={"/admin"} buttonStyle="primary">
Go to Main Admin View
</Button>
<p style={{ paddingTop: 20 }}>{`Current state of merch store: ${
loading ? "..." : isStoreDisabled ? "Disabled" : "Live"
}`}</p>
{SHOW_DISPLAY_TEXT_INPUT && (
<textarea
value={displayText}
onChange={(e: ChangeEvent<HTMLTextAreaElement>) =>
setDisplayText(e.target.value)
}
placeholder="Enter display text"
rows={4}
cols={50}
/>
)}
<Button
limivann marked this conversation as resolved.
Show resolved Hide resolved
// eslint-disable-next-line @typescript-eslint/no-misused-promises
onClick={disableStore}
disabled={loading}
buttonStyle="primary"
el="a"
>
Disable Store
</Button>
</ViewTemplate>
);
};
Expand Down
102 changes: 97 additions & 5 deletions apps/cms/src/admin/views/MerchProducts.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,103 @@
import React from "react";
import React, { useEffect, useState } from "react";
import { Button } from "payload/components/elements";
import { AdminView } from "payload/config";
import ViewTemplate from "./ViewTemplate";
import { Column } from "payload/dist/admin/components/elements/Table/types";
import { RenderCellFactory } from "../utils/RenderCellFactory";
import SortedColumn from "../utils/SortedColumn";
import { Table } from "payload/dist/admin/components/elements/Table";
import { Product } from "types";
import ProductsApi from "../../apis/products.api";

const MerchProducts: AdminView = ({ user, canAccessAdmin }) => {
// Get data from API
const [data, setData] = useState<Product[]>(null);
useEffect(() => {
ProductsApi.getProducts()
.then((res: Product[]) => setData(res))
.catch((error) => console.log(error));
}, []);

// Output human-readable table headers based on the attribute names from the API
function prettifyKey(str: string): string {
let res = "";
for (const i of str.split("_")) {
res += i.charAt(0).toUpperCase() + i.slice(1) + " ";
}
return res;
}

// Do not load table until we receive the data
if (data == null) {
return <div> Loading... </div>;
}

const tableCols = new Array<Column>();
if (data && data.length > 0) {
const sampleProduct = data[0];
const keys = Object.keys(sampleProduct);
for (const key of keys) {
const renderCell: React.FC<{ children?: React.ReactNode }> = RenderCellFactory.get(sampleProduct, key);
const col: Column = {
accessor: key,
components: {
Heading: (
<SortedColumn
label={prettifyKey(key)}
name={key}
data={data as never[]}
/>
),
renderCell: renderCell,
},
label: "",
name: "",
active: true,
};
tableCols.push(col);
}
}

const editColumn: Column = {
accessor: "edit",
components: {
Heading: <div>Edit</div>,
renderCell: ({ children }) => (
<Button onClick={() => handleEdit(children as string)}>Edit</Button>
),
},
label: "Edit",
name: "edit",
active: true,
};

tableCols.push(editColumn);

const deleteColumn: Column = {
accessor: "delete",
components: {
Heading: <div>Delete</div>,
renderCell: ({ children }) => (
<Button onClick={() => handleDelete(children as string)}>Delete</Button>
),
},
label: "Delete",
name: "delete",
active: true,
};

tableCols.push(deleteColumn);

const handleEdit = (orderId: string) => {
console.log(`Dummy. Order ID: ${orderId}`);
};

const handleDelete = (orderId: string) => {
console.log(`Dummy. Order ID: ${orderId}`);
};

console.log(tableCols);

return (
<ViewTemplate
user={user}
Expand All @@ -12,13 +106,11 @@ const MerchProducts: AdminView = ({ user, canAccessAdmin }) => {
keywords=""
title="Merchandise Products"
>
<p>
Here is a custom route that was added in the Payload config. It uses the
Default Template, so the sidebar is rendered.
</p>
<Button el="link" to={"/admin"} buttonStyle="primary">
Go to Main Admin View
</Button>

<Table data={data} columns={tableCols} />
</ViewTemplate>
);
};
Expand Down
Loading
Loading