From 74f30205fc91795aa9ab03e0abf7df42e450316b Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Tue, 16 Apr 2024 13:35:04 +0200 Subject: [PATCH 01/29] feat(admin-ui): added possibility to add draws, minor text color changes and solve bug we created --- kabinizer-front-end/src/pages/admin/index.tsx | 196 +++++++++++++++++- kabinizer-front-end/src/pages/home/index.tsx | 14 +- .../pages/selectPeriods/Calendar/Calendar.tsx | 2 - .../pages/selectPeriods/Calendar/Months.tsx | 2 +- kabinizer-front-end/src/utils/admins.ts | 1 + kabinizer-front-end/src/utils/calendar.ts | 3 +- 6 files changed, 203 insertions(+), 15 deletions(-) diff --git a/kabinizer-front-end/src/pages/admin/index.tsx b/kabinizer-front-end/src/pages/admin/index.tsx index 628a0a3..bf06054 100644 --- a/kabinizer-front-end/src/pages/admin/index.tsx +++ b/kabinizer-front-end/src/pages/admin/index.tsx @@ -1,8 +1,9 @@ import { useMutation } from "react-query"; import Button from "../../components/Button"; -import { BookingRequestService } from "../../../api"; +import { BookingRequestService, CreateDrawDto } from "../../../api"; import useUser from "../../hooks/useUser"; -import { useEffect } from "react"; +import { useEffect, useState } from "react"; +import { DrawService } from "../../../api/services/DrawService"; const Admin = () => { const { isAdmin } = useUser(); @@ -21,6 +22,79 @@ const Admin = () => { }, }, ); + const [isClicked, setIsClicked] = useState(false); + const [draw, setDraw] = useState({ + deadlineStart: "", + deadlineEnd: "", + title: "", + isSpecial: false, + drawPeriods: [{ start: "", end: "", title: "" }], + }); + + const generateNewPeriod = () => { + setIsClicked(!isClicked); + }; + + const handleChangePeriod = (e) => { + const isSpecial = + e.target.name === "isSpecial" ? e.target.checked : draw.isSpecial; + setDraw({ + ...draw, + [e.target.name]: e.target.value, + isSpecial, + }); + }; + + const handleSubmit = () => { + const specialDates = draw?.drawPeriods?.filter( + (date) => date?.start !== "", + ); + + DrawService.postApiDraw({ + ...draw, + drawPeriods: specialDates, + }); + }; + + const addToDrawPeriods = (e, key) => { + const { name, value } = e.target; + const addTextToPeriodDraw = draw?.drawPeriods?.map((date, index) => { + if (index === key) { + return { + ...date, + [name]: value, + }; + } + return date; + }, []); + setDraw({ + ...draw, + drawPeriods: addTextToPeriodDraw, + }); + }; + + const addTitleToDrawPeriods = (value: string, key: number) => { + const addTextToPeriodDraw = draw?.drawPeriods?.map((date, index) => { + if (index === key) { + return { + ...date, + title: value, + }; + } + return date; + }, []); + setDraw({ + ...draw, + drawPeriods: addTextToPeriodDraw, + }); + }; + + const addDrawPeriods = () => { + setDraw({ + ...draw, + drawPeriods: [...draw.drawPeriods, { start: "", end: "", title: "" }], + }); + }; useEffect(() => { if (!isAdmin) { @@ -33,12 +107,128 @@ const Admin = () => {
-

Download selected periods

+
+

+ Download selected periods +

+
+
+ +
+ {isClicked ? ( +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + + {draw?.drawPeriods?.map((date, key) => { + return ( +
+ + addToDrawPeriods(e, key)} + /> + + addToDrawPeriods(e, key)} + /> + + addTitleToDrawPeriods(e.target.value, key)} + /> +
+ ); + })} +
+ +
+
+ +
+
+ ) : null}
); diff --git a/kabinizer-front-end/src/pages/home/index.tsx b/kabinizer-front-end/src/pages/home/index.tsx index bbb3f84..c65a6cc 100644 --- a/kabinizer-front-end/src/pages/home/index.tsx +++ b/kabinizer-front-end/src/pages/home/index.tsx @@ -19,7 +19,7 @@ const Welcome = () => {

Velkommen til Tjørhomfjellet

-

+

I Miles Stavanger/Haugesund har vi tilgang til en flott firmahytte på Tjørhomfjellet i Sirdal, kun 1,5 time fra Stavanger. Her kan du ta med familie og venner og nyte alle årstider 😀 @@ -54,10 +54,10 @@ const Location = () => {

-

+

Odden 7D, 4443 Tjørhom

-

+

Kjør inn til Tjørhom fjellet og ta første vei til høyre. Følg veien helt til endes. (du passerer stolheisen på venstre side) Hytten ligger på nederste rad, merket med Miles skilt utenfor @@ -95,7 +95,7 @@ const Activeties = () => {

Vinter aktiviteter

-
    +
    • Alpinanlegg med stolheis, tallerkenheis og tautrekk
    • Langrennsløyper
    • Opplyst akebakke
    • @@ -106,7 +106,7 @@ const Activeties = () => {

      Sommer, vår, høst

      -
        +
        • Vannpark
        • Klatrepark
        • Sommerheis
        • @@ -142,7 +142,7 @@ const ImportantInformation = () => {

          Hva du må ta med

          -
            +
            • Sengetøy
            • Håndklær
            • Kjøkkenhåndklær
            • @@ -152,7 +152,7 @@ const ImportantInformation = () => {

              Regler

              -
                +
                • Firbente venner får lov til å bli med på hytta, men de får ikke være i sofa/senger! diff --git a/kabinizer-front-end/src/pages/selectPeriods/Calendar/Calendar.tsx b/kabinizer-front-end/src/pages/selectPeriods/Calendar/Calendar.tsx index 1c22f2f..b2d4ecb 100644 --- a/kabinizer-front-end/src/pages/selectPeriods/Calendar/Calendar.tsx +++ b/kabinizer-front-end/src/pages/selectPeriods/Calendar/Calendar.tsx @@ -18,7 +18,6 @@ const Calendar = ({ .sort((a, b) => { return CompareDates(a, b); }); - const onClick = (periodId: string) => { const checked = selected.find((s) => s.periodId === periodId); @@ -44,7 +43,6 @@ const Calendar = ({ const data = GetWeeklyPeriods(periods, draws); const monthMap = getMonthsMap(data); - console.log(monthMap); return ; }; diff --git a/kabinizer-front-end/src/pages/selectPeriods/Calendar/Months.tsx b/kabinizer-front-end/src/pages/selectPeriods/Calendar/Months.tsx index 7439c49..4f3b3f9 100644 --- a/kabinizer-front-end/src/pages/selectPeriods/Calendar/Months.tsx +++ b/kabinizer-front-end/src/pages/selectPeriods/Calendar/Months.tsx @@ -35,7 +35,7 @@ const Month = ({ children, month }: MonthProps) => {
                  { const weeksMap = getWeeksMap(data); for (const week in weeksMap) { - const month = weeksMap[week][0].month; + const month = weeksMap[week][0]?.month; if (!monthsMap[month]) { monthsMap[month] = {}; } monthsMap[month][Number(week)] = weeksMap[week]; } - return monthsMap; }; From fe0fe48f2e726ad492d3ba1892effe162d90677f Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Tue, 16 Apr 2024 13:47:35 +0200 Subject: [PATCH 02/29] feat(admin-ui): update titles and css --- kabinizer-front-end/src/pages/admin/index.tsx | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/kabinizer-front-end/src/pages/admin/index.tsx b/kabinizer-front-end/src/pages/admin/index.tsx index bf06054..a16e160 100644 --- a/kabinizer-front-end/src/pages/admin/index.tsx +++ b/kabinizer-front-end/src/pages/admin/index.tsx @@ -126,7 +126,7 @@ const Admin = () => {
                  { />
                  -
                  -
                  -
                  - {isClicked ? ( -
                  -
                  - - -
                  -
                  - - -
                  -
                  - - -
                  -
                  - - -
                  - - - {draw?.drawPeriods?.map((date, key) => { - return ( -
                  - - addToDrawPeriods(e, key)} - /> - - addToDrawPeriods(e, key)} - /> - - addTitleToDrawPeriods(e.target.value, key)} - /> -
                  - ); - })} -
                  - -
                  -
                  - -
                  -
                  - ) : null} + {showNewPeriodView && }
                  ); From b37edac5d9f8cf67803edf6e91a837ce41199cf7 Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 10:35:39 +0200 Subject: [PATCH 05/29] chore(admin-ui): generate api update spec tool --- kabinizer-front-end/api/core/ApiError.ts | 36 +- .../api/core/ApiRequestOptions.ts | 29 +- kabinizer-front-end/api/core/ApiResult.ts | 10 +- .../api/core/CancelablePromise.ts | 221 ++++---- kabinizer-front-end/api/core/OpenAPI.ts | 38 +- kabinizer-front-end/api/core/request.ts | 529 ++++++++++-------- kabinizer-front-end/api/index.ts | 28 +- .../api/models/BookingRequest.ts | 11 +- .../api/models/CreateBookingRequestDto.ts | 3 +- .../api/models/CreateDrawDto.ts | 13 +- kabinizer-front-end/api/models/Draw.ts | 15 +- kabinizer-front-end/api/models/DrawPeriod.ts | 7 +- kabinizer-front-end/api/models/Period.ts | 11 +- kabinizer-front-end/api/models/User.ts | 5 +- .../api/services/BookingRequestService.ts | 114 ++-- .../api/services/DrawService.ts | 75 ++- .../api/services/PeriodService.ts | 30 +- 17 files changed, 615 insertions(+), 560 deletions(-) diff --git a/kabinizer-front-end/api/core/ApiError.ts b/kabinizer-front-end/api/core/ApiError.ts index d6b8fcc..ebc1161 100644 --- a/kabinizer-front-end/api/core/ApiError.ts +++ b/kabinizer-front-end/api/core/ApiError.ts @@ -2,24 +2,28 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; +import type { ApiRequestOptions } from "./ApiRequestOptions"; +import type { ApiResult } from "./ApiResult"; export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: any; - public readonly request: ApiRequestOptions; + public readonly url: string; + public readonly status: number; + public readonly statusText: string; + public readonly body: any; + public readonly request: ApiRequestOptions; - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); + constructor( + request: ApiRequestOptions, + response: ApiResult, + message: string, + ) { + super(message); - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } + this.name = "ApiError"; + this.url = response.url; + this.status = response.status; + this.statusText = response.statusText; + this.body = response.body; + this.request = request; + } } diff --git a/kabinizer-front-end/api/core/ApiRequestOptions.ts b/kabinizer-front-end/api/core/ApiRequestOptions.ts index c19adcc..ac9a2ca 100644 --- a/kabinizer-front-end/api/core/ApiRequestOptions.ts +++ b/kabinizer-front-end/api/core/ApiRequestOptions.ts @@ -3,15 +3,22 @@ /* tslint:disable */ /* eslint-disable */ export type ApiRequestOptions = { - readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; - readonly url: string; - readonly path?: Record; - readonly cookies?: Record; - readonly headers?: Record; - readonly query?: Record; - readonly formData?: Record; - readonly body?: any; - readonly mediaType?: string; - readonly responseHeader?: string; - readonly errors?: Record; + readonly method: + | "GET" + | "PUT" + | "POST" + | "DELETE" + | "OPTIONS" + | "HEAD" + | "PATCH"; + readonly url: string; + readonly path?: Record; + readonly cookies?: Record; + readonly headers?: Record; + readonly query?: Record; + readonly formData?: Record; + readonly body?: any; + readonly mediaType?: string; + readonly responseHeader?: string; + readonly errors?: Record; }; diff --git a/kabinizer-front-end/api/core/ApiResult.ts b/kabinizer-front-end/api/core/ApiResult.ts index ad8fef2..63ed6c4 100644 --- a/kabinizer-front-end/api/core/ApiResult.ts +++ b/kabinizer-front-end/api/core/ApiResult.ts @@ -3,9 +3,9 @@ /* tslint:disable */ /* eslint-disable */ export type ApiResult = { - readonly url: string; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly body: any; + readonly url: string; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly body: any; }; diff --git a/kabinizer-front-end/api/core/CancelablePromise.ts b/kabinizer-front-end/api/core/CancelablePromise.ts index 55fef85..6aefa9e 100644 --- a/kabinizer-front-end/api/core/CancelablePromise.ts +++ b/kabinizer-front-end/api/core/CancelablePromise.ts @@ -3,129 +3,128 @@ /* tslint:disable */ /* eslint-disable */ export class CancelError extends Error { - - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } + constructor(message: string) { + super(message); + this.name = "CancelError"; + } + + public get isCancelled(): boolean { + return true; + } } export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; + readonly isResolved: boolean; + readonly isRejected: boolean; + readonly isCancelled: boolean; - (cancelHandler: () => void): void; + (cancelHandler: () => void): void; } export class CancelablePromise implements Promise { - #isResolved: boolean; - #isRejected: boolean; - #isCancelled: boolean; - readonly #cancelHandlers: (() => void)[]; - readonly #promise: Promise; - #resolve?: (value: T | PromiseLike) => void; - #reject?: (reason?: any) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: any) => void, - onCancel: OnCancel - ) => void - ) { - this.#isResolved = false; - this.#isRejected = false; - this.#isCancelled = false; - this.#cancelHandlers = []; - this.#promise = new Promise((resolve, reject) => { - this.#resolve = resolve; - this.#reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#isResolved = true; - this.#resolve?.(value); - }; - - const onReject = (reason?: any): void => { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#isRejected = true; - this.#reject?.(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this.#isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this.#isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this.#isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag]() { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: any) => TResult2 | PromiseLike) | null - ): Promise { - return this.#promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: any) => TResult | PromiseLike) | null - ): Promise { - return this.#promise.catch(onRejected); - } + #isResolved: boolean; + #isRejected: boolean; + #isCancelled: boolean; + readonly #cancelHandlers: (() => void)[]; + readonly #promise: Promise; + #resolve?: (value: T | PromiseLike) => void; + #reject?: (reason?: any) => void; + + constructor( + executor: ( + resolve: (value: T | PromiseLike) => void, + reject: (reason?: any) => void, + onCancel: OnCancel, + ) => void, + ) { + this.#isResolved = false; + this.#isRejected = false; + this.#isCancelled = false; + this.#cancelHandlers = []; + this.#promise = new Promise((resolve, reject) => { + this.#resolve = resolve; + this.#reject = reject; + + const onResolve = (value: T | PromiseLike): void => { + if (this.#isResolved || this.#isRejected || this.#isCancelled) { + return; + } + this.#isResolved = true; + this.#resolve?.(value); + }; - public finally(onFinally?: (() => void) | null): Promise { - return this.#promise.finally(onFinally); - } + const onReject = (reason?: any): void => { + if (this.#isResolved || this.#isRejected || this.#isCancelled) { + return; + } + this.#isRejected = true; + this.#reject?.(reason); + }; - public cancel(): void { + const onCancel = (cancelHandler: () => void): void => { if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; + return; } - this.#isCancelled = true; - if (this.#cancelHandlers.length) { - try { - for (const cancelHandler of this.#cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } + this.#cancelHandlers.push(cancelHandler); + }; + + Object.defineProperty(onCancel, "isResolved", { + get: (): boolean => this.#isResolved, + }); + + Object.defineProperty(onCancel, "isRejected", { + get: (): boolean => this.#isRejected, + }); + + Object.defineProperty(onCancel, "isCancelled", { + get: (): boolean => this.#isCancelled, + }); + + return executor(onResolve, onReject, onCancel as OnCancel); + }); + } + + get [Symbol.toStringTag]() { + return "Cancellable Promise"; + } + + public then( + onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onRejected?: ((reason: any) => TResult2 | PromiseLike) | null, + ): Promise { + return this.#promise.then(onFulfilled, onRejected); + } + + public catch( + onRejected?: ((reason: any) => TResult | PromiseLike) | null, + ): Promise { + return this.#promise.catch(onRejected); + } + + public finally(onFinally?: (() => void) | null): Promise { + return this.#promise.finally(onFinally); + } + + public cancel(): void { + if (this.#isResolved || this.#isRejected || this.#isCancelled) { + return; + } + this.#isCancelled = true; + if (this.#cancelHandlers.length) { + try { + for (const cancelHandler of this.#cancelHandlers) { + cancelHandler(); } - this.#cancelHandlers.length = 0; - this.#reject?.(new CancelError('Request aborted')); + } catch (error) { + console.warn("Cancellation threw an error", error); + return; + } } + this.#cancelHandlers.length = 0; + this.#reject?.(new CancelError("Request aborted")); + } - public get isCancelled(): boolean { - return this.#isCancelled; - } + public get isCancelled(): boolean { + return this.#isCancelled; + } } diff --git a/kabinizer-front-end/api/core/OpenAPI.ts b/kabinizer-front-end/api/core/OpenAPI.ts index 0fdd044..dec19a3 100644 --- a/kabinizer-front-end/api/core/OpenAPI.ts +++ b/kabinizer-front-end/api/core/OpenAPI.ts @@ -2,31 +2,31 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -import type { ApiRequestOptions } from './ApiRequestOptions'; +import type { ApiRequestOptions } from "./ApiRequestOptions"; type Resolver = (options: ApiRequestOptions) => Promise; type Headers = Record; export type OpenAPIConfig = { - BASE: string; - VERSION: string; - WITH_CREDENTIALS: boolean; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - HEADERS?: Headers | Resolver | undefined; - ENCODE_PATH?: ((path: string) => string) | undefined; + BASE: string; + VERSION: string; + WITH_CREDENTIALS: boolean; + CREDENTIALS: "include" | "omit" | "same-origin"; + TOKEN?: string | Resolver | undefined; + USERNAME?: string | Resolver | undefined; + PASSWORD?: string | Resolver | undefined; + HEADERS?: Headers | Resolver | undefined; + ENCODE_PATH?: ((path: string) => string) | undefined; }; export const OpenAPI: OpenAPIConfig = { - BASE: '', - VERSION: '1.0', - WITH_CREDENTIALS: false, - CREDENTIALS: 'include', - TOKEN: undefined, - USERNAME: undefined, - PASSWORD: undefined, - HEADERS: undefined, - ENCODE_PATH: undefined, + BASE: "", + VERSION: "1.0", + WITH_CREDENTIALS: false, + CREDENTIALS: "include", + TOKEN: undefined, + USERNAME: undefined, + PASSWORD: undefined, + HEADERS: undefined, + ENCODE_PATH: undefined, }; diff --git a/kabinizer-front-end/api/core/request.ts b/kabinizer-front-end/api/core/request.ts index b018a07..72ed014 100644 --- a/kabinizer-front-end/api/core/request.ts +++ b/kabinizer-front-end/api/core/request.ts @@ -2,283 +2,310 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -export const isDefined = (value: T | null | undefined): value is Exclude => { - return value !== undefined && value !== null; +import { ApiError } from "./ApiError"; +import type { ApiRequestOptions } from "./ApiRequestOptions"; +import type { ApiResult } from "./ApiResult"; +import { CancelablePromise } from "./CancelablePromise"; +import type { OnCancel } from "./CancelablePromise"; +import type { OpenAPIConfig } from "./OpenAPI"; + +export const isDefined = ( + value: T | null | undefined, +): value is Exclude => { + return value !== undefined && value !== null; }; export const isString = (value: any): value is string => { - return typeof value === 'string'; + return typeof value === "string"; }; export const isStringWithValue = (value: any): value is string => { - return isString(value) && value !== ''; + return isString(value) && value !== ""; }; export const isBlob = (value: any): value is Blob => { - return ( - typeof value === 'object' && - typeof value.type === 'string' && - typeof value.stream === 'function' && - typeof value.arrayBuffer === 'function' && - typeof value.constructor === 'function' && - typeof value.constructor.name === 'string' && - /^(Blob|File)$/.test(value.constructor.name) && - /^(Blob|File)$/.test(value[Symbol.toStringTag]) - ); + return ( + typeof value === "object" && + typeof value.type === "string" && + typeof value.stream === "function" && + typeof value.arrayBuffer === "function" && + typeof value.constructor === "function" && + typeof value.constructor.name === "string" && + /^(Blob|File)$/.test(value.constructor.name) && + /^(Blob|File)$/.test(value[Symbol.toStringTag]) + ); }; export const isFormData = (value: any): value is FormData => { - return value instanceof FormData; + return value instanceof FormData; }; export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } + try { + return btoa(str); + } catch (err) { + // @ts-ignore + return Buffer.from(str).toString("base64"); + } }; export const getQueryString = (params: Record): string => { - const qs: string[] = []; + const qs: string[] = []; - const append = (key: string, value: any) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; + const append = (key: string, value: any) => { + qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); + }; - const process = (key: string, value: any) => { - if (isDefined(value)) { - if (Array.isArray(value)) { - value.forEach(v => { - process(key, v); - }); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => { - process(`${key}[${k}]`, v); - }); - } else { - append(key, value); - } - } - }; + const process = (key: string, value: any) => { + if (isDefined(value)) { + if (Array.isArray(value)) { + value.forEach((v) => { + process(key, v); + }); + } else if (typeof value === "object") { + Object.entries(value).forEach(([k, v]) => { + process(`${key}[${k}]`, v); + }); + } else { + append(key, value); + } + } + }; - Object.entries(params).forEach(([key, value]) => { - process(key, value); - }); + Object.entries(params).forEach(([key, value]) => { + process(key, value); + }); - if (qs.length > 0) { - return `?${qs.join('&')}`; - } + if (qs.length > 0) { + return `?${qs.join("&")}`; + } - return ''; + return ""; }; const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); + const encoder = config.ENCODE_PATH || encodeURI; + + const path = options.url + .replace("{api-version}", config.VERSION) + .replace(/{(.*?)}/g, (substring: string, group: string) => { + if (options.path?.hasOwnProperty(group)) { + return encoder(String(options.path[group])); + } + return substring; + }); - const url = `${config.BASE}${path}`; - if (options.query) { - return `${url}${getQueryString(options.query)}`; - } - return url; + const url = `${config.BASE}${path}`; + if (options.query) { + return `${url}${getQueryString(options.query)}`; + } + return url; }; -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); +export const getFormData = ( + options: ApiRequestOptions, +): FormData | undefined => { + if (options.formData) { + const formData = new FormData(); - const process = (key: string, value: any) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; + const process = (key: string, value: any) => { + if (isString(value) || isBlob(value)) { + formData.append(key, value); + } else { + formData.append(key, JSON.stringify(value)); + } + }; - Object.entries(options.formData) - .filter(([_, value]) => isDefined(value)) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; + Object.entries(options.formData) + .filter(([_, value]) => isDefined(value)) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => process(key, v)); + } else { + process(key, value); + } + }); + + return formData; + } + return undefined; }; type Resolver = (options: ApiRequestOptions) => Promise; -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; +export const resolve = async ( + options: ApiRequestOptions, + resolver?: T | Resolver, +): Promise => { + if (typeof resolver === "function") { + return (resolver as Resolver)(options); + } + return resolver; }; -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const token = await resolve(options, config.TOKEN); - const username = await resolve(options, config.USERNAME); - const password = await resolve(options, config.PASSWORD); - const additionalHeaders = await resolve(options, config.HEADERS); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([_, value]) => isDefined(value)) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } +export const getHeaders = async ( + config: OpenAPIConfig, + options: ApiRequestOptions, +): Promise => { + const token = await resolve(options, config.TOKEN); + const username = await resolve(options, config.USERNAME); + const password = await resolve(options, config.PASSWORD); + const additionalHeaders = await resolve(options, config.HEADERS); + + const headers = Object.entries({ + Accept: "application/json", + ...additionalHeaders, + ...options.headers, + }) + .filter(([_, value]) => isDefined(value)) + .reduce( + (headers, [key, value]) => ({ + ...headers, + [key]: String(value), + }), + {} as Record, + ); - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; + if (isStringWithValue(token)) { + headers["Authorization"] = `Bearer ${token}`; + } + + if (isStringWithValue(username) && isStringWithValue(password)) { + const credentials = base64(`${username}:${password}`); + headers["Authorization"] = `Basic ${credentials}`; + } + + if (options.body) { + if (options.mediaType) { + headers["Content-Type"] = options.mediaType; + } else if (isBlob(options.body)) { + headers["Content-Type"] = options.body.type || "application/octet-stream"; + } else if (isString(options.body)) { + headers["Content-Type"] = "text/plain"; + } else if (!isFormData(options.body)) { + headers["Content-Type"] = "application/json"; } + } - if (options.body) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); + return new Headers(headers); }; export const getRequestBody = (options: ApiRequestOptions): any => { - if (options.body !== undefined) { - if (options.mediaType?.includes('/json')) { - return JSON.stringify(options.body) - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } + if (options.body !== undefined) { + if (options.mediaType?.includes("/json")) { + return JSON.stringify(options.body); + } else if ( + isString(options.body) || + isBlob(options.body) || + isFormData(options.body) + ) { + return options.body; + } else { + return JSON.stringify(options.body); } - return undefined; + } + return undefined; }; export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel + config: OpenAPIConfig, + options: ApiRequestOptions, + url: string, + body: any, + formData: FormData | undefined, + headers: Headers, + onCancel: OnCancel, ): Promise => { - const controller = new AbortController(); + const controller = new AbortController(); - const request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; + const request: RequestInit = { + headers, + body: body ?? formData, + method: options.method, + signal: controller.signal, + }; - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } + if (config.WITH_CREDENTIALS) { + request.credentials = config.CREDENTIALS; + } - onCancel(() => controller.abort()); + onCancel(() => controller.abort()); - return await fetch(url, request); + return await fetch(url, request); }; -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } +export const getResponseHeader = ( + response: Response, + responseHeader?: string, +): string | undefined => { + if (responseHeader) { + const content = response.headers.get(responseHeader); + if (isString(content)) { + return content; } - return undefined; + } + return undefined; }; export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const jsonTypes = ['application/json', 'application/problem+json'] - const isJSON = jsonTypes.some(type => contentType.toLowerCase().startsWith(type)); - if (isJSON) { - return await response.json(); - } else { - return await response.text(); - } - } - } catch (error) { - console.error(error); + if (response.status !== 204) { + try { + const contentType = response.headers.get("Content-Type"); + if (contentType) { + const jsonTypes = ["application/json", "application/problem+json"]; + const isJSON = jsonTypes.some((type) => + contentType.toLowerCase().startsWith(type), + ); + if (isJSON) { + return await response.json(); + } else { + return await response.text(); } + } + } catch (error) { + console.error(error); } - return undefined; + } + return undefined; }; -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 403: 'Forbidden', - 404: 'Not Found', - 500: 'Internal Server Error', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } +export const catchErrorCodes = ( + options: ApiRequestOptions, + result: ApiResult, +): void => { + const errors: Record = { + 400: "Bad Request", + 401: "Unauthorized", + 403: "Forbidden", + 404: "Not Found", + 500: "Internal Server Error", + 502: "Bad Gateway", + 503: "Service Unavailable", + ...options.errors, + }; + + const error = errors[result.status]; + if (error) { + throw new ApiError(options, result, error); + } + + if (!result.ok) { + const errorStatus = result.status ?? "unknown"; + const errorStatusText = result.statusText ?? "unknown"; + const errorBody = (() => { + try { + return JSON.stringify(result.body, null, 2); + } catch (e) { + return undefined; + } + })(); + + throw new ApiError( + options, + result, + `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`, + ); + } }; /** @@ -288,33 +315,47 @@ export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): * @returns CancelablePromise * @throws ApiError */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - const response = await sendRequest(config, options, url, body, formData, headers, onCancel); - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); +export const request = ( + config: OpenAPIConfig, + options: ApiRequestOptions, +): CancelablePromise => { + return new CancelablePromise(async (resolve, reject, onCancel) => { + try { + const url = getUrl(config, options); + const formData = getFormData(options); + const body = getRequestBody(options); + const headers = await getHeaders(config, options); + + if (!onCancel.isCancelled) { + const response = await sendRequest( + config, + options, + url, + body, + formData, + headers, + onCancel, + ); + const responseBody = await getResponseBody(response); + const responseHeader = getResponseHeader( + response, + options.responseHeader, + ); + + const result: ApiResult = { + url, + ok: response.ok, + status: response.status, + statusText: response.statusText, + body: responseHeader ?? responseBody, + }; + + catchErrorCodes(options, result); + + resolve(result.body); + } + } catch (error) { + reject(error); + } + }); }; diff --git a/kabinizer-front-end/api/index.ts b/kabinizer-front-end/api/index.ts index 488602d..4601b85 100644 --- a/kabinizer-front-end/api/index.ts +++ b/kabinizer-front-end/api/index.ts @@ -2,19 +2,19 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -export { ApiError } from './core/ApiError'; -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI } from './core/OpenAPI'; -export type { OpenAPIConfig } from './core/OpenAPI'; +export { ApiError } from "./core/ApiError"; +export { CancelablePromise, CancelError } from "./core/CancelablePromise"; +export { OpenAPI } from "./core/OpenAPI"; +export type { OpenAPIConfig } from "./core/OpenAPI"; -export type { BookingRequest } from './models/BookingRequest'; -export type { CreateBookingRequestDto } from './models/CreateBookingRequestDto'; -export type { CreateDrawDto } from './models/CreateDrawDto'; -export type { Draw } from './models/Draw'; -export type { DrawPeriod } from './models/DrawPeriod'; -export type { Period } from './models/Period'; -export type { User } from './models/User'; +export type { BookingRequest } from "./models/BookingRequest"; +export type { CreateBookingRequestDto } from "./models/CreateBookingRequestDto"; +export type { CreateDrawDto } from "./models/CreateDrawDto"; +export type { Draw } from "./models/Draw"; +export type { DrawPeriod } from "./models/DrawPeriod"; +export type { Period } from "./models/Period"; +export type { User } from "./models/User"; -export { BookingRequestService } from './services/BookingRequestService'; -export { DrawService } from './services/DrawService'; -export { PeriodService } from './services/PeriodService'; +export { BookingRequestService } from "./services/BookingRequestService"; +export { DrawService } from "./services/DrawService"; +export { PeriodService } from "./services/PeriodService"; diff --git a/kabinizer-front-end/api/models/BookingRequest.ts b/kabinizer-front-end/api/models/BookingRequest.ts index 0b18f47..d8d33a4 100644 --- a/kabinizer-front-end/api/models/BookingRequest.ts +++ b/kabinizer-front-end/api/models/BookingRequest.ts @@ -3,12 +3,11 @@ /* tslint:disable */ /* eslint-disable */ -import type { Period } from './Period'; -import type { User } from './User'; +import type { Period } from "./Period"; +import type { User } from "./User"; export type BookingRequest = { - bookingRequestId?: string; - period?: Period; - user?: User; + bookingRequestId?: string; + period?: Period; + user?: User; }; - diff --git a/kabinizer-front-end/api/models/CreateBookingRequestDto.ts b/kabinizer-front-end/api/models/CreateBookingRequestDto.ts index 8efb255..73bfd30 100644 --- a/kabinizer-front-end/api/models/CreateBookingRequestDto.ts +++ b/kabinizer-front-end/api/models/CreateBookingRequestDto.ts @@ -4,6 +4,5 @@ /* eslint-disable */ export type CreateBookingRequestDto = { - periodId?: string; + periodId?: string; }; - diff --git a/kabinizer-front-end/api/models/CreateDrawDto.ts b/kabinizer-front-end/api/models/CreateDrawDto.ts index f169d92..61e53a4 100644 --- a/kabinizer-front-end/api/models/CreateDrawDto.ts +++ b/kabinizer-front-end/api/models/CreateDrawDto.ts @@ -3,13 +3,12 @@ /* tslint:disable */ /* eslint-disable */ -import type { DrawPeriod } from './DrawPeriod'; +import type { DrawPeriod } from "./DrawPeriod"; export type CreateDrawDto = { - deadlineStart?: string; - deadlineEnd?: string; - title?: string | null; - drawPeriods?: Array | null; - isSpecial?: boolean; + deadlineStart?: string; + deadlineEnd?: string; + title?: string | null; + drawPeriods?: Array | null; + isSpecial?: boolean; }; - diff --git a/kabinizer-front-end/api/models/Draw.ts b/kabinizer-front-end/api/models/Draw.ts index f00c417..5add249 100644 --- a/kabinizer-front-end/api/models/Draw.ts +++ b/kabinizer-front-end/api/models/Draw.ts @@ -3,14 +3,13 @@ /* tslint:disable */ /* eslint-disable */ -import type { Period } from './Period'; +import type { Period } from "./Period"; export type Draw = { - id?: string; - start?: string; - end?: string; - title?: string | null; - periods?: Array | null; - isSpecial?: boolean; + id?: string; + start?: string; + end?: string; + title?: string | null; + periods?: Array | null; + isSpecial?: boolean; }; - diff --git a/kabinizer-front-end/api/models/DrawPeriod.ts b/kabinizer-front-end/api/models/DrawPeriod.ts index 80a9566..729e794 100644 --- a/kabinizer-front-end/api/models/DrawPeriod.ts +++ b/kabinizer-front-end/api/models/DrawPeriod.ts @@ -4,8 +4,7 @@ /* eslint-disable */ export type DrawPeriod = { - start?: string; - end?: string; - title?: string | null; + start?: string; + end?: string; + title?: string | null; }; - diff --git a/kabinizer-front-end/api/models/Period.ts b/kabinizer-front-end/api/models/Period.ts index 72589c3..5fe4978 100644 --- a/kabinizer-front-end/api/models/Period.ts +++ b/kabinizer-front-end/api/models/Period.ts @@ -4,10 +4,9 @@ /* eslint-disable */ export type Period = { - id?: string; - periodStart?: string; - periodEnd?: string; - title?: string | null; - drawId?: string; + id?: string; + periodStart?: string; + periodEnd?: string; + title?: string | null; + drawId?: string; }; - diff --git a/kabinizer-front-end/api/models/User.ts b/kabinizer-front-end/api/models/User.ts index 427d455..60f8c3a 100644 --- a/kabinizer-front-end/api/models/User.ts +++ b/kabinizer-front-end/api/models/User.ts @@ -4,7 +4,6 @@ /* eslint-disable */ export type User = { - id?: string; - name?: string | null; + id?: string; + name?: string | null; }; - diff --git a/kabinizer-front-end/api/services/BookingRequestService.ts b/kabinizer-front-end/api/services/BookingRequestService.ts index f28625d..6afd577 100644 --- a/kabinizer-front-end/api/services/BookingRequestService.ts +++ b/kabinizer-front-end/api/services/BookingRequestService.ts @@ -2,67 +2,67 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -import type { BookingRequest } from '../models/BookingRequest'; -import type { CreateBookingRequestDto } from '../models/CreateBookingRequestDto'; +import type { BookingRequest } from "../models/BookingRequest"; +import type { CreateBookingRequestDto } from "../models/CreateBookingRequestDto"; -import type { CancelablePromise } from '../core/CancelablePromise'; -import { OpenAPI } from '../core/OpenAPI'; -import { request as __request } from '../core/request'; +import type { CancelablePromise } from "../core/CancelablePromise"; +import { OpenAPI } from "../core/OpenAPI"; +import { request as __request } from "../core/request"; export class BookingRequestService { + /** + * @returns BookingRequest Success + * @throws ApiError + */ + public static getApiBookingRequest(): CancelablePromise< + Array + > { + return __request(OpenAPI, { + method: "GET", + url: "/api/BookingRequest", + }); + } - /** - * @returns BookingRequest Success - * @throws ApiError - */ - public static getApiBookingRequest(): CancelablePromise> { - return __request(OpenAPI, { - method: 'GET', - url: '/api/BookingRequest', - }); - } + /** + * @param requestBody + * @returns any Success + * @throws ApiError + */ + public static postApiBookingRequest( + requestBody: Array, + ): CancelablePromise { + return __request(OpenAPI, { + method: "POST", + url: "/api/BookingRequest", + body: requestBody, + mediaType: "application/json", + }); + } - /** - * @param requestBody - * @returns any Success - * @throws ApiError - */ - public static postApiBookingRequest( - requestBody: Array, - ): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/BookingRequest', - body: requestBody, - mediaType: 'application/json', - }); - } - - /** - * @param requestBody - * @returns boolean Success - * @throws ApiError - */ - public static deleteApiBookingRequest( - requestBody: Array, - ): CancelablePromise { - return __request(OpenAPI, { - method: 'DELETE', - url: '/api/BookingRequest', - body: requestBody, - mediaType: 'application/json', - }); - } - - /** - * @returns any Success - * @throws ApiError - */ - public static getApiBookingRequestExport(): CancelablePromise { - return __request(OpenAPI, { - method: 'GET', - url: '/api/BookingRequest/export', - }); - } + /** + * @param requestBody + * @returns boolean Success + * @throws ApiError + */ + public static deleteApiBookingRequest( + requestBody: Array, + ): CancelablePromise { + return __request(OpenAPI, { + method: "DELETE", + url: "/api/BookingRequest", + body: requestBody, + mediaType: "application/json", + }); + } + /** + * @returns any Success + * @throws ApiError + */ + public static getApiBookingRequestExport(): CancelablePromise { + return __request(OpenAPI, { + method: "GET", + url: "/api/BookingRequest/export", + }); + } } diff --git a/kabinizer-front-end/api/services/DrawService.ts b/kabinizer-front-end/api/services/DrawService.ts index 6552f81..0649bd7 100644 --- a/kabinizer-front-end/api/services/DrawService.ts +++ b/kabinizer-front-end/api/services/DrawService.ts @@ -2,40 +2,53 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -import type { CreateDrawDto } from '../models/CreateDrawDto'; -import type { Draw } from '../models/Draw'; +import type { CreateDrawDto } from "../models/CreateDrawDto"; +import type { Draw } from "../models/Draw"; -import type { CancelablePromise } from '../core/CancelablePromise'; -import { OpenAPI } from '../core/OpenAPI'; -import { request as __request } from '../core/request'; +import type { CancelablePromise } from "../core/CancelablePromise"; +import { OpenAPI } from "../core/OpenAPI"; +import { request as __request } from "../core/request"; export class DrawService { + /** + * @returns Draw Success + * @throws ApiError + */ + public static getApiDraw(): CancelablePromise> { + return __request(OpenAPI, { + method: "GET", + url: "/api/Draw", + }); + } - /** - * @returns Draw Success - * @throws ApiError - */ - public static getApiDraw(): CancelablePromise> { - return __request(OpenAPI, { - method: 'GET', - url: '/api/Draw', - }); - } - - /** - * @param requestBody - * @returns any Success - * @throws ApiError - */ - public static postApiDraw( - requestBody: CreateDrawDto, - ): CancelablePromise { - return __request(OpenAPI, { - method: 'POST', - url: '/api/Draw', - body: requestBody, - mediaType: 'application/json', - }); - } + /** + * @param requestBody + * @returns any Success + * @throws ApiError + */ + public static postApiDraw( + requestBody: CreateDrawDto, + ): CancelablePromise { + return __request(OpenAPI, { + method: "POST", + url: "/api/Draw", + body: requestBody, + mediaType: "application/json", + }); + } + /** + * @param id + * @returns any Success + * @throws ApiError + */ + public static deleteApiDraw(id: string): CancelablePromise { + return __request(OpenAPI, { + method: "DELETE", + url: "/api/Draw", + query: { + id: id, + }, + }); + } } diff --git a/kabinizer-front-end/api/services/PeriodService.ts b/kabinizer-front-end/api/services/PeriodService.ts index 4601463..65f9352 100644 --- a/kabinizer-front-end/api/services/PeriodService.ts +++ b/kabinizer-front-end/api/services/PeriodService.ts @@ -2,23 +2,21 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -import type { Period } from '../models/Period'; +import type { Period } from "../models/Period"; -import type { CancelablePromise } from '../core/CancelablePromise'; -import { OpenAPI } from '../core/OpenAPI'; -import { request as __request } from '../core/request'; +import type { CancelablePromise } from "../core/CancelablePromise"; +import { OpenAPI } from "../core/OpenAPI"; +import { request as __request } from "../core/request"; export class PeriodService { - - /** - * @returns Period Success - * @throws ApiError - */ - public static getApiPeriod(): CancelablePromise> { - return __request(OpenAPI, { - method: 'GET', - url: '/api/Period', - }); - } - + /** + * @returns Period Success + * @throws ApiError + */ + public static getApiPeriod(): CancelablePromise> { + return __request(OpenAPI, { + method: "GET", + url: "/api/Period", + }); + } } From b1bb542b42905bc8dd674098c4d487cf1712ef08 Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 10:36:16 +0200 Subject: [PATCH 06/29] feat(admin-ui): add endpoint for delete draw --- .../kabinizer-api/Controllers/DrawController.cs | 17 ++++++++++++++++- .../kabinizer-api/Services/Draw/DrawService.cs | 7 +++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/kabinizer-back-end/kabinizer-api/Controllers/DrawController.cs b/kabinizer-back-end/kabinizer-api/Controllers/DrawController.cs index acd8636..f6e2db2 100644 --- a/kabinizer-back-end/kabinizer-api/Controllers/DrawController.cs +++ b/kabinizer-back-end/kabinizer-api/Controllers/DrawController.cs @@ -3,6 +3,7 @@ using kabinizer_api.Services.Draw; using kabinizer_data; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; @@ -21,7 +22,7 @@ public DrawController(EntityContext entityContext, DrawService drawService) this.entityContext = entityContext; this.drawService = drawService; } - + [HttpGet] public IEnumerable GetDraws() { @@ -33,4 +34,18 @@ public void CreateDraw([Required] CreateDrawDto draw) { drawService.CreateDraw(draw); } + + [HttpDelete] + public IActionResult DeleteDraw([Required] String id) + { + try + { + drawService.DeleteDraw(id); + return new NoContentResult(); + } + catch (Exception) + { + return new NotFoundResult(); + } + } } diff --git a/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs b/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs index b2c6ea8..f45bca5 100644 --- a/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs +++ b/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs @@ -30,4 +30,11 @@ public void CreateDraw(CreateDrawDto draw) entityContext.Draws.Add(drawEntity); entityContext.SaveChanges(); } + + public void DeleteDraw(string id) + { + var draw = entityContext.Draws.Find(id) ?? throw new Exception("Draw not found"); + entityContext.Draws.Remove(draw); + entityContext.SaveChanges(); + } } From 9b21663e5dc1dee34f6e0a4861b01d559d6d5daa Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 13:27:39 +0200 Subject: [PATCH 07/29] feat: correct delete endpoint stuff --- kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs | 4 ++-- kabinizer-back-end/kabinizer-data/Entities/DrawEntity.cs | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs b/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs index f45bca5..fc2bace 100644 --- a/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs +++ b/kabinizer-back-end/kabinizer-api/Services/Draw/DrawService.cs @@ -32,8 +32,8 @@ public void CreateDraw(CreateDrawDto draw) } public void DeleteDraw(string id) - { - var draw = entityContext.Draws.Find(id) ?? throw new Exception("Draw not found"); + { + var draw = entityContext.Draws.Find(Guid.Parse(id)) ?? throw new Exception("Draw not found"); entityContext.Draws.Remove(draw); entityContext.SaveChanges(); } diff --git a/kabinizer-back-end/kabinizer-data/Entities/DrawEntity.cs b/kabinizer-back-end/kabinizer-data/Entities/DrawEntity.cs index ca6eaa8..b81f761 100644 --- a/kabinizer-back-end/kabinizer-data/Entities/DrawEntity.cs +++ b/kabinizer-back-end/kabinizer-data/Entities/DrawEntity.cs @@ -1,10 +1,12 @@ -using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace kabinizer_data.Entities; [Table("Draw")] public class DrawEntity { + [Key] public Guid Id { get; set; } public DateTime DeadlineStart { get; set; } public DateTime DeadlineEnd { get; set; } From 90f6c34ef1c2f5c52955b1f447ff038784979502 Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 13:41:24 +0200 Subject: [PATCH 08/29] chore: comit stuff --- .../src/components/DeleteDraw.tsx | 45 +++++++++++++++++++ kabinizer-front-end/src/pages/admin/index.tsx | 18 +++++++- 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 kabinizer-front-end/src/components/DeleteDraw.tsx diff --git a/kabinizer-front-end/src/components/DeleteDraw.tsx b/kabinizer-front-end/src/components/DeleteDraw.tsx new file mode 100644 index 0000000..b30b67c --- /dev/null +++ b/kabinizer-front-end/src/components/DeleteDraw.tsx @@ -0,0 +1,45 @@ +import { format } from "date-fns"; +import { DrawService } from "../../api/services/DrawService"; +import { Draw } from "../../api/models/Draw"; + +const DeleteDraw = (draw : Array ) => { + + + console.log("asdf data deletedraw", draw); + const deleteDrawPeriods = (id: string | undefined) => { + console.log("asdf id", id); + if (!id) return; + DrawService.deleteApiDraw(id); + }; + + const formatDate = (date: string | undefined) => { + if (!date) return ""; + + return format(new Date(date), "dd-MM-yyyy"); + }; + + return ( +
                  +
                  +

                  Delete draw and period?

                  +
                  + {draw.length > 0 && draw?.map((draws) => ( + + ))} +
                  + ); +}; +export default DeleteDraw; diff --git a/kabinizer-front-end/src/pages/admin/index.tsx b/kabinizer-front-end/src/pages/admin/index.tsx index e807192..babe427 100644 --- a/kabinizer-front-end/src/pages/admin/index.tsx +++ b/kabinizer-front-end/src/pages/admin/index.tsx @@ -1,9 +1,11 @@ -import { useMutation } from "react-query"; +import { useMutation, useQuery } from "react-query"; import Button from "../../components/Button"; import { BookingRequestService } from "../../../api"; import useUser from "../../hooks/useUser"; import { useEffect, useState } from "react"; import NewPeriodView from "../../components/NewPeriodView"; +import { DrawService } from "../../../api/services/DrawService"; +import DeleteDraw from "../../components/DeleteDraw"; const Admin = () => { const { isAdmin } = useUser(); @@ -23,6 +25,7 @@ const Admin = () => { }, ); const [showNewPeriodView, setShowNewPeriodView] = useState(false); + const [drawsExist, setDrawsExist] = useState(false); const generateNewPeriod = () => { setShowNewPeriodView(!showNewPeriodView); @@ -34,6 +37,18 @@ const Admin = () => { } }, [isAdmin]); + const { data : drawPeriod} = useQuery(["getApiDraw"], () => + DrawService.getApiDraw(), + ); + + console.log("asdf data", drawPeriod); + + useEffect(() => { + if (drawPeriod) { + setDrawsExist(true); + } + }, [drawPeriod]); + return (
                  @@ -55,6 +70,7 @@ const Admin = () => {
                  {showNewPeriodView && } + {drawsExist && }
                  ); From 0fc87854763525dea8c4baf115070a548bd738f1 Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 13:52:30 +0200 Subject: [PATCH 09/29] chore: date fns --- kabinizer-front-end/package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/kabinizer-front-end/package.json b/kabinizer-front-end/package.json index ca6b8ca..da06702 100644 --- a/kabinizer-front-end/package.json +++ b/kabinizer-front-end/package.json @@ -29,7 +29,8 @@ "react-query": "^3.39.3", "sass": "^1.68.0", "tailwind-merge": "^2.2.0", - "tailwindcss-animate": "^1.0.7" + "tailwindcss-animate": "^1.0.7", + "date-fns": "^3.6.0" }, "devDependencies": { "@azure/msal-browser": "^3.6.0", From 5c00e177968d6cd96ee3fcf002825428111caa16 Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 14:11:50 +0200 Subject: [PATCH 10/29] feat(admin-ui): can delete stuff --- .../src/components/DeleteDraw.tsx | 33 ++++++++----------- kabinizer-front-end/src/pages/admin/index.tsx | 13 +++----- 2 files changed, 18 insertions(+), 28 deletions(-) diff --git a/kabinizer-front-end/src/components/DeleteDraw.tsx b/kabinizer-front-end/src/components/DeleteDraw.tsx index b30b67c..6b990bb 100644 --- a/kabinizer-front-end/src/components/DeleteDraw.tsx +++ b/kabinizer-front-end/src/components/DeleteDraw.tsx @@ -2,12 +2,8 @@ import { format } from "date-fns"; import { DrawService } from "../../api/services/DrawService"; import { Draw } from "../../api/models/Draw"; -const DeleteDraw = (draw : Array ) => { - - - console.log("asdf data deletedraw", draw); +const DeleteDraw = ({ draw }: { draw: Array }) => { const deleteDrawPeriods = (id: string | undefined) => { - console.log("asdf id", id); if (!id) return; DrawService.deleteApiDraw(id); }; @@ -23,21 +19,20 @@ const DeleteDraw = (draw : Array ) => {

                  Delete draw and period?

                  - {draw.length > 0 && draw?.map((draws) => ( - +

                  + ))} +
+ +
))} ); diff --git a/kabinizer-front-end/src/pages/admin/index.tsx b/kabinizer-front-end/src/pages/admin/index.tsx index babe427..67badc8 100644 --- a/kabinizer-front-end/src/pages/admin/index.tsx +++ b/kabinizer-front-end/src/pages/admin/index.tsx @@ -25,7 +25,6 @@ const Admin = () => { }, ); const [showNewPeriodView, setShowNewPeriodView] = useState(false); - const [drawsExist, setDrawsExist] = useState(false); const generateNewPeriod = () => { setShowNewPeriodView(!showNewPeriodView); @@ -37,17 +36,13 @@ const Admin = () => { } }, [isAdmin]); - const { data : drawPeriod} = useQuery(["getApiDraw"], () => + const { data : draws, isLoading} = useQuery(["getApiDraw"], () => DrawService.getApiDraw(), ); - console.log("asdf data", drawPeriod); + console.log("asdf data", draws, isLoading); - useEffect(() => { - if (drawPeriod) { - setDrawsExist(true); - } - }, [drawPeriod]); + return (
@@ -70,7 +65,7 @@ const Admin = () => {
{showNewPeriodView && } - {drawsExist && } + {!isLoading && } ); From 5ff0102a83b0c34467f487fb04b25948419f662b Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Wed, 17 Apr 2024 14:20:13 +0200 Subject: [PATCH 11/29] chore(admin-ui): remove log --- kabinizer-front-end/src/pages/admin/index.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/kabinizer-front-end/src/pages/admin/index.tsx b/kabinizer-front-end/src/pages/admin/index.tsx index 67badc8..b86f5ca 100644 --- a/kabinizer-front-end/src/pages/admin/index.tsx +++ b/kabinizer-front-end/src/pages/admin/index.tsx @@ -40,7 +40,6 @@ const Admin = () => { DrawService.getApiDraw(), ); - console.log("asdf data", draws, isLoading); From 99feefa637619d378f2c0b1d549d2ec44d1ab477 Mon Sep 17 00:00:00 2001 From: Kristoffer Marthinsen Date: Thu, 18 Apr 2024 09:36:50 +0200 Subject: [PATCH 12/29] feat(admin-ui): delete periods, beautiful design --- .../src/components/DeleteButtonIcon.tsx | 37 +++++++++++++++++++ .../src/components/DeleteDraw.tsx | 16 ++++---- .../src/components/NewPeriodView.tsx | 4 +- kabinizer-front-end/src/pages/admin/index.tsx | 4 +- 4 files changed, 50 insertions(+), 11 deletions(-) create mode 100644 kabinizer-front-end/src/components/DeleteButtonIcon.tsx diff --git a/kabinizer-front-end/src/components/DeleteButtonIcon.tsx b/kabinizer-front-end/src/components/DeleteButtonIcon.tsx new file mode 100644 index 0000000..370c608 --- /dev/null +++ b/kabinizer-front-end/src/components/DeleteButtonIcon.tsx @@ -0,0 +1,37 @@ +const DeleteButtonIcon = () => { + return ( + + delete [#1487] + Created with Sketch. + + + + + + + + + + ); +}; + +export default DeleteButtonIcon; diff --git a/kabinizer-front-end/src/components/DeleteDraw.tsx b/kabinizer-front-end/src/components/DeleteDraw.tsx index 6b990bb..9e1a9c8 100644 --- a/kabinizer-front-end/src/components/DeleteDraw.tsx +++ b/kabinizer-front-end/src/components/DeleteDraw.tsx @@ -1,6 +1,7 @@ import { format } from "date-fns"; import { DrawService } from "../../api/services/DrawService"; import { Draw } from "../../api/models/Draw"; +import DeleteButtonIcon from "../components/DeleteButtonIcon"; const DeleteDraw = ({ draw }: { draw: Array }) => { const deleteDrawPeriods = (id: string | undefined) => { @@ -20,17 +21,18 @@ const DeleteDraw = ({ draw }: { draw: Array }) => {

Delete draw and period?

{draw?.map((draws) => ( -
-
))} diff --git a/kabinizer-front-end/src/components/NewPeriodView.tsx b/kabinizer-front-end/src/components/NewPeriodView.tsx index 55b0c73..fa89240 100644 --- a/kabinizer-front-end/src/components/NewPeriodView.tsx +++ b/kabinizer-front-end/src/components/NewPeriodView.tsx @@ -74,8 +74,8 @@ const NewPeriodView = () => { }; return ( -
-
+
+