Skip to content

Commit

Permalink
Offlines with s3 integration (#683)
Browse files Browse the repository at this point in the history
  • Loading branch information
henrikskog authored Nov 10, 2023
1 parent 530a12d commit 1d22871
Show file tree
Hide file tree
Showing 34 changed files with 1,187 additions and 14 deletions.
39 changes: 39 additions & 0 deletions apps/dashboard/src/app/(dashboard)/offline/[id]/edit-card.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { type FC } from "react"
import { type OfflineWrite } from "@dotkomonline/types"
import { useOfflineDetailsContext } from "./provider"
import { useEditOfflineMutation } from "../../../../modules/offline/mutations/use-edit-offline-mutation"
import { useS3UploadFile } from "../../../../modules/offline/use-s3-upload-file"
import { useOfflineWriteForm } from "../write-form"
import { type File } from "../../../../../stubs/file/File"

export const OfflineEditCard: FC = () => {
const { offline } = useOfflineDetailsContext()
const edit = useEditOfflineMutation()
const upload = useS3UploadFile()

const handleUpload = async (file?: File) => (file?.name ? await upload(file) : null)

const FormComponent = useOfflineWriteForm({
label: "Oppdater",
onSubmit: async (data) => {
// Only upload if files are present
const fileUrl = await handleUpload(data.file)
const imageUrl = await handleUpload(data.image)

const toSave: Partial<OfflineWrite> = {
...data,
fileUrl: fileUrl ?? data.fileUrl, // Preserving existing URL if no new file uploaded
imageUrl: imageUrl ?? data.imageUrl, // Preserving existing URL if no new image uploaded
}

edit.mutate({
id: offline.id,
input: {
...toSave,
},
})
},
defaultValues: offline,
})
return <FormComponent />
}
19 changes: 19 additions & 0 deletions apps/dashboard/src/app/(dashboard)/offline/[id]/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use client"

import { Loader } from "@mantine/core"
import { type PropsWithChildren } from "react"
import { OfflineDetailsContext } from "./provider"
import { trpc } from "../../../../utils/trpc"

export default function OfflineDetailsLayout({ children, params }: PropsWithChildren<{ params: { id: string } }>) {
const { data, isLoading } = trpc.offline.get.useQuery(params.id)
return (
<>
{isLoading || !data ? (
<Loader />
) : (
<OfflineDetailsContext.Provider value={{ offline: data }}>{children}</OfflineDetailsContext.Provider>
)}
</>
)
}
44 changes: 44 additions & 0 deletions apps/dashboard/src/app/(dashboard)/offline/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"use client"

import { Icon } from "@iconify/react"
import { Box, CloseButton, Group, Tabs, Title } from "@mantine/core"
import { useRouter } from "next/navigation"
import { OfflineEditCard } from "./edit-card"
import { useOfflineDetailsContext } from "./provider"

const SIDEBAR_LINKS = [
{
icon: "tabler:building-warehouse",
label: "Info",
slug: "info",
component: OfflineEditCard,
},
] as const

export default function OfflineDetailsPage() {
const { offline } = useOfflineDetailsContext()
const router = useRouter()
return (
<Box p="md">
<Group>
<CloseButton onClick={() => router.back()} />
<Title>{offline.title}</Title>
</Group>

<Tabs defaultValue={SIDEBAR_LINKS[0].slug}>
<Tabs.List>
{SIDEBAR_LINKS.map(({ label, icon, slug }) => (
<Tabs.Tab key={slug} value={slug} leftSection={<Icon icon={icon} width={14} height={14} />}>
{label}
</Tabs.Tab>
))}
</Tabs.List>
{SIDEBAR_LINKS.map(({ slug, component: Component }) => (
<Tabs.Panel mt="md" key={slug} value={slug}>
<Component />
</Tabs.Panel>
))}
</Tabs>
</Box>
)
}
17 changes: 17 additions & 0 deletions apps/dashboard/src/app/(dashboard)/offline/[id]/provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use client"

import { createContext, useContext } from "react"
import { type Offline } from "@dotkomonline/types"

/** Context consisting of everything required to use and render the form */
export const OfflineDetailsContext = createContext<{
offline: Offline
} | null>(null)

export const useOfflineDetailsContext = () => {
const ctx = useContext(OfflineDetailsContext)
if (ctx === null) {
throw new Error("useOfflineDetailsContext called without Provider in tree")
}
return ctx
}
35 changes: 35 additions & 0 deletions apps/dashboard/src/app/(dashboard)/offline/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"use client"

import { Icon } from "@iconify/react"
import { Button, ButtonGroup, Card, Group, Skeleton, Stack } from "@mantine/core"
import { GenericTable } from "../../../components/GenericTable"
import { useOfflineAllQuery } from "../../../modules/offline/queries/use-offlines-all-query"
import { useCreateOfflineModal } from "../../../modules/offline/modals/create-offline-modal"
import { useOfflineTable } from "../../../modules/offline/use-offline-table"

export default function OfflinePage() {
const { offlines, isLoading: isOfflinesLoading } = useOfflineAllQuery()
const open = useCreateOfflineModal()
const table = useOfflineTable({ data: offlines })

return (
<Skeleton visible={isOfflinesLoading}>
<Stack>
<Card withBorder>
<GenericTable table={table} />
</Card>
<Group justify="space-between">
<Button onClick={open}>Legg inn ny Offline</Button>
<ButtonGroup>
<Button variant="subtle">
<Icon icon="tabler:caret-left" />
</Button>
<Button variant="subtle">
<Icon icon="tabler:caret-right" />
</Button>
</ButtonGroup>
</Group>
</Stack>
</Skeleton>
)
}
54 changes: 54 additions & 0 deletions apps/dashboard/src/app/(dashboard)/offline/write-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { z } from "zod"
import { createDateTimeInput, createFileInput, createTextInput, useFormBuilder } from "src/app/form"
import { OfflineWriteSchema } from "../../../../../../packages/types/src/offline"

const OFFLINE_FORM_DEFAULT_VALUES: Partial<FormValidationSchema> = {
fileUrl: null,
imageUrl: null,
}

interface UseOfflineWriteFormProps {
onSubmit(data: FormValidationSchema): Promise<void>
defaultValues?: Partial<FormValidationSchema>
label?: string
}

export const FormValidationSchema = OfflineWriteSchema.extend({
file: z.any().optional(),
image: z.any().optional(),
fileUrl: z.string().nullable(),
imageUrl: z.string().nullable(),
})
type FormValidationSchema = z.infer<typeof FormValidationSchema>

export const useOfflineWriteForm = ({
onSubmit,
label = "Registrer",
defaultValues = OFFLINE_FORM_DEFAULT_VALUES,
}: UseOfflineWriteFormProps) =>
useFormBuilder({
schema: FormValidationSchema,
defaultValues,
onSubmit,
label,
fields: {
title: createTextInput({
label: "Tittel",
placeholder: "Offline #50",
}),
published: createDateTimeInput({
label: "Utgivelsesdato",
placeholder: "2023-10-05",
}),
file: createFileInput({
label: "Fil",
placeholder: "Last opp",
existingFileUrl: defaultValues.fileUrl ?? undefined,
}),
image: createFileInput({
label: "Bilde",
placeholder: "Last opp",
existingFileUrl: defaultValues.imageUrl ?? undefined,
}),
},
})
2 changes: 2 additions & 0 deletions apps/dashboard/src/app/ModalProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import { type FC, type PropsWithChildren } from "react"
import { CreateCompanyModal } from "src/modules/company/modals/create-company-modal"
import { CreateEventModal } from "src/modules/event/modals/create-event-modal"
import { CreateJobListingModal } from "src/modules/job-listing/modals/create-job-listing-modal"
import { CreateOfflineModal } from "../modules/offline/modals/create-offline-modal"
import { CreateEventExtrasModal } from "../modules/event/modals/create-event-extras-modal"
import { UpdateEventExtrasModal } from "../modules/event/modals/edit-event-extras-modal"

const modals = {
"event/create": CreateEventModal,
"jobListing/create": CreateJobListingModal,
"company/create": CreateCompanyModal,
"offline/create": CreateOfflineModal,
"extras/create": CreateEventExtrasModal,
"extras/update": UpdateEventExtrasModal,
} as const
Expand Down
61 changes: 50 additions & 11 deletions apps/dashboard/src/app/form.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
import { type z } from "zod"
import { type FC } from "react"
import { ErrorMessage } from "@hookform/error-message"
import { zodResolver } from "@hookform/resolvers/zod"
import {
Button,
Checkbox,
type CheckboxProps,
FileInput,
type FileInputProps,
Flex,
MultiSelect,
type MultiSelectProps,
NumberInput,
Select,
TagsInput,
TextInput,
Textarea,
type CheckboxProps,
type MultiSelectProps,
type NumberInputProps,
type SelectProps,
TagsInput,
type TagsInputProps,
Textarea,
type TextareaProps,
TextInput,
type TextInputProps,
type TextareaProps,
Text,
Box,
Anchor,
} from "@mantine/core"
import { DateTimePicker, type DateTimePickerProps } from "@mantine/dates"
import { type FC } from "react"
import {
type Control,
Controller,
useForm,
type Control,
type DefaultValues,
type FieldValue,
type FieldValues,
type FormState,
useForm,
type UseFormRegister,
type FieldValues,
} from "react-hook-form"
import { type z } from "zod"

interface InputFieldContext<T extends FieldValues> {
name: FieldValue<T>
Expand Down Expand Up @@ -190,6 +195,40 @@ export function createTextInput<F extends FieldValues>({
}
}

export function createFileInput<F extends FieldValues>({
...props
}: Omit<FileInputProps, "error"> & { existingFileUrl?: string }): InputProducerResult<F> {
return function FormFileInput({ name, state, control }) {
return (
<Box>
<Text>{props.label}</Text>
{props.existingFileUrl ? (
<Anchor href={props.existingFileUrl} mb="sm" display="block">
Link til ressurs
</Anchor>
) : (
<Text mb="sm" fs="italic">
Ingen fil lastet opp
</Text>
)}
<Controller
control={control}
name={name}
render={({ field }) => (
<FileInput
{...props}
value={field.value}
onChange={(value) => field.onChange({ target: { value } })}
error={state.errors[name] && <ErrorMessage errors={state.errors} name={name} />}
label=""
/>
)}
></Controller>
</Box>
)
}
}

export function createNumberInput<F extends FieldValues>({
...props
}: Omit<NumberInputProps, "error">): InputProducerResult<F> {
Expand Down
63 changes: 63 additions & 0 deletions apps/dashboard/src/modules/offline/modals/create-offline-modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { type FC } from "react"
import { type ContextModalProps, modals } from "@mantine/modals"
import { type OfflineWrite } from "@dotkomonline/types"
import { useCreateOfflineMutation } from "../mutations/use-create-offline-mutation"
import { type File } from "../../../../stubs/file/File"
import { useOfflineWriteForm } from "../../../app/(dashboard)/offline/write-form"
import { useS3UploadFile } from "../use-s3-upload-file"
import { useQueryNotification } from "../../../app/notifications"

export const CreateOfflineModal: FC<ContextModalProps> = ({ context, id }) => {
const close = () => context.closeModal(id)
const create = useCreateOfflineMutation()
const upload = useS3UploadFile()
const notification = useQueryNotification()

const handleUpload = async (file?: File) => (file?.name ? await upload(file) : null)

const FormComponent = useOfflineWriteForm({
onSubmit: async (data) => {
let fileUrl = null
let imageUrl = null

try {
fileUrl = await handleUpload(data.file)
} catch (e) {
notification.fail({
title: "Feil",
message: "Kunne ikke laste opp fil. ",
})
}

try {
imageUrl = await handleUpload(data.image)
} catch (e) {
notification.fail({
message: "Kunne ikke laste opp bilde",
title: "Feil",
})
}

const toSave: OfflineWrite = {
title: data.title,
published: data.published,
id: data.id,
fileUrl,
imageUrl,
}

create.mutate({
...toSave,
})
close()
},
})
return <FormComponent />
}

export const useCreateOfflineModal = () => () =>
modals.openContextModal({
modal: "offline/create",
title: "Opprett ny Offline",
innerProps: {},
})
Loading

0 comments on commit 1d22871

Please sign in to comment.