(feature): patch account form complete

This commit is contained in:
Maksym Sadovnychyy 2024-07-04 23:34:23 +02:00
parent a7ea95fd2b
commit 3e0c25158e
9 changed files with 340 additions and 196 deletions

View File

@ -18,6 +18,7 @@ import { FaPlus, FaTrash } from 'react-icons/fa'
import { PageContainer } from '@/components/pageContainer'
import { OffCanvas } from '@/components/offcanvas'
import { AccountEdit } from '@/partials/accoutEdit'
import { get } from 'http'
export default function Page() {
const [accounts, setAccounts] = useState<CacheAccount[]>([])
@ -34,11 +35,13 @@ export default function Page() {
const fetchAccounts = async () => {
const newAccounts: CacheAccount[] = []
const accounts = await httpService.get<GetAccountResponse[]>(
const gatAccountsResult = await httpService.get<GetAccountResponse[]>(
GetApiRoute(ApiRoutes.ACCOUNTS)
)
accounts?.forEach((account) => {
if (!gatAccountsResult.isSuccess) return
gatAccountsResult.data?.forEach((account) => {
newAccounts.push({
accountId: account.accountId,
isDisabled: account.isDisabled,
@ -79,10 +82,15 @@ export default function Page() {
}
const deleteAccount = (accountId: string) => {
setAccounts(accounts.filter((account) => account.accountId !== accountId))
// TODO: Revoke all certificates
// TODO: Remove from cache
httpService
.delete(GetApiRoute(ApiRoutes.ACCOUNT_ID, accountId))
.then((response) => {
if (response.isSuccess) {
setAccounts(
accounts.filter((account) => account.accountId !== accountId)
)
}
})
}
return (
@ -195,7 +203,14 @@ export default function Page() {
isOpen={editingAccount !== null}
onClose={() => setEditingAccount(null)}
>
{editingAccount && <AccountEdit account={editingAccount} />}
{editingAccount && (
<AccountEdit
account={editingAccount}
setAccount={setEditingAccount}
onCancel={() => setEditingAccount(null)}
onDelete={deleteAccount}
/>
)}
</OffCanvas>
</>
)

View File

@ -8,7 +8,7 @@ export interface CustomSelectOption {
export interface CustomSelectPropsBase {
selectedValue: string | null | undefined
onChange: (value: string) => void
onChange?: (value: string) => void
readOnly?: boolean
disabled?: boolean
title?: string
@ -45,7 +45,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
const handleOptionClick = (option: CustomSelectOption) => {
if (!readOnly && !disabled) {
onChange(option.value)
onChange?.(option.value)
setIsOpen(false)
}
}

View File

@ -1,3 +1,5 @@
import { PatchOperation } from './PatchOperation'
export interface PatchAction<T> {
op: PatchOperation // Enum for operation type
index?: number // Index for the operation (for arrays/lists)

View File

@ -1,5 +1,6 @@
enum PatchOperation {
export enum PatchOperation {
Add,
Remove,
Replace
Replace,
None
}

View File

@ -1,6 +1,13 @@
import { PatchAction } from '@/models/PatchAction'
export interface PatchHostnameRequest {
hostname?: PatchAction<string>
isDisabled?: PatchAction<boolean>
}
export interface PatchAccountRequest {
description?: PatchAction<string>
isDisabled?: PatchAction<boolean>
contacts?: PatchAction<string>[]
hostnames?: PatchHostnameRequest[]
}

View File

@ -1,6 +1,6 @@
'use client'
import { FormEvent, useCallback, useState } from 'react'
import { Dispatch, FormEvent, SetStateAction, useEffect, useState } from 'react'
import {
useValidation,
isValidEmail,
@ -17,39 +17,71 @@ import {
import { CacheAccount } from '@/entities/CacheAccount'
import { FaPlus, FaTrash } from 'react-icons/fa'
import { ChallengeTypes } from '@/entities/ChallengeTypes'
import { deepCopy } from '@/functions'
import { ApiRoutes, GetApiRoute } from '@/ApiRoutes'
import { httpService } from '@/services/httpService'
import { PatchAccountRequest } from '@/models/letsEncryptServer/account/requests/PatchAccountRequest'
import { PatchOperation } from '@/models/PatchOperation'
import { useAppDispatch } from '@/redux/store'
import { showToast } from '@/redux/slices/toastSlice'
interface AccountEditProps {
account: CacheAccount
setAccount: Dispatch<SetStateAction<CacheAccount | null>>
onCancel?: () => void
onSave?: (account: CacheAccount) => void
onDelete?: (accountId: string) => void
onSubmit?: (account: CacheAccount) => void
onDelete: (accountId: string) => void
}
const AccountEdit: React.FC<AccountEditProps> = (props) => {
const { account, onCancel, onSave, onDelete } = props
const AccountEdit: React.FC<AccountEditProps> = ({
account,
setAccount,
onCancel,
onSubmit,
onDelete
}) => {
const dispatch = useAppDispatch()
const [newAccount, setNewAccount] = useState<PatchAccountRequest>({
description: { op: PatchOperation.None, value: account.description },
isDisabled: { op: PatchOperation.None, value: account.isDisabled },
contacts: account.contacts.map((contact) => ({
op: PatchOperation.None,
value: contact
})),
hostnames: account.hostnames?.map((hostname) => ({
hostname: { op: PatchOperation.None, value: hostname.hostname },
isDisabled: { op: PatchOperation.None, value: hostname.isDisabled }
}))
})
const [editingAccount, setEditingAccount] = useState<CacheAccount>(account)
const [newContact, setNewContact] = useState('')
const [newHostname, setNewHostname] = useState('')
const setDescription = useCallback(
(newDescription: string) => {
if (editingAccount) {
setEditingAccount({ ...editingAccount, description: newDescription })
}
},
[editingAccount]
)
useEffect(() => {
console.log(newAccount)
}, [newAccount])
const {
value: description,
error: descriptionError,
handleChange: handleDescriptionChange,
reset: resetDescription
handleChange: handleDescriptionChange
} = useValidation<string>({
defaultValue: '',
externalValue: account.description,
setExternalValue: setDescription,
externalValue: newAccount.description?.value ?? '',
setExternalValue: (newDescription) => {
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
newAccount.description = {
op:
newDescription !== account.description
? PatchOperation.Replace
: PatchOperation.None,
value: newDescription
}
return newAccount
})
},
validateFn: isBypass,
errorMessage: ''
})
@ -81,122 +113,147 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
})
const handleIsDisabledChange = (value: boolean) => {
// setAccount({ ...account, isDisabled: value })
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
newAccount.isDisabled = {
op:
value !== account.isDisabled
? PatchOperation.Replace
: PatchOperation.None,
value
}
return newAccount
})
}
const handleChallengeTypeChange = (option: any) => {
//setAccount({ ...account, challengeType: option.value })
const handleAddContact = () => {
if (newContact === '' || contactError) return
// Check if the contact already exists in the account
const contactExists = newAccount.contacts?.some(
(contact) => contact.value === newContact
)
if (contactExists) {
// Optionally, handle the duplicate contact case, e.g., show an error message
dispatch(
showToast({ message: 'Contact already exists.', type: 'warning' })
)
resetContact()
return
}
// If the contact does not exist, add it
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
newAccount.contacts?.push({ op: PatchOperation.Add, value: newContact })
return newAccount
})
resetContact()
}
const handleDeleteContact = (contact: string) => {
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
newAccount.contacts = newAccount.contacts
?.map((c) => {
if (c.value === contact && c.op !== PatchOperation.Add)
c.op = PatchOperation.Remove
return c
})
.filter((c) => !(c.value === contact && c.op === PatchOperation.Add))
return newAccount
})
}
const handleAddHostname = () => {
if (newHostname === '' || hostnameError) return
// Check if the hostname already exists in the account
const hostnameExists = newAccount.hostnames?.some(
(hostname) => hostname.hostname?.value === newHostname
)
if (hostnameExists) {
// Optionally, handle the duplicate hostname case, e.g., show an error message
dispatch(
showToast({ message: 'Hostname already exists.', type: 'warning' })
)
resetHostname()
return
}
// If the hostname does not exist, add it
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
newAccount.hostnames?.push({
hostname: { op: PatchOperation.Add, value: newHostname },
isDisabled: { op: PatchOperation.Add, value: false }
})
return newAccount
})
resetHostname()
}
const handleHostnameDisabledChange = (hostname: string, value: boolean) => {
// setAccount({
// ...account,
// hostnames: account.hostnames.map((h) =>
// h.hostname === hostname ? { ...h, isDisabled: value } : h
// )
// })
// }
// const handleStagingChange = (value: string) => {
// setAccount({ ...account, isStaging: value === 'staging' })
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
const targetHostname = newAccount.hostnames?.find(
(h) => h.hostname?.value === hostname
)
if (targetHostname) {
targetHostname.isDisabled = {
op:
value !== targetHostname.isDisabled?.value
? PatchOperation.Replace
: PatchOperation.None,
value
}
}
return newAccount
})
}
const deleteContact = (contact: string) => {
if (account?.contacts.length ?? 0 < 1) return
// setAccount({
// ...account,
// contacts: account.contacts.filter((c) => c !== contact)
// })
// }
// const addContact = () => {
// if (newContact === '' || contactError) {
// return
// }
// if (account.contacts.includes(newContact)) return
// setAccount({ ...account, contacts: [...account.contacts, newContact] })
// resetContact()
const handleDeleteHostname = (hostname: string) => {
setNewAccount((prev) => {
const newAccount = deepCopy(prev)
newAccount.hostnames = newAccount.hostnames
?.map((h) => {
if (
h.hostname?.value === hostname &&
h.hostname?.op !== PatchOperation.Add
)
h.hostname.op = PatchOperation.Remove
return h
})
.filter(
(h) =>
!(
h.hostname?.value === hostname &&
h.hostname?.op === PatchOperation.Add
)
)
return newAccount
})
}
const deleteHostname = (hostname: string) => {
//if (account?.hostnames.length ?? 0 < 1) return
// setAccount({
// ...account,
// hostnames: account.hostnames.filter((h) => h.hostname !== hostname)
// })
// }
// const addHostname = () => {
// if (newHostname === '' || hostnameError) {
// return
// }
// if (account.hostnames.some((h) => h.hostname === newHostname)) return
// setAccount({
// ...account,
// hostnames: [
// ...account.hostnames,
// {
// hostname: newHostname,
// expires: new Date(),
// isUpcomingExpire: false,
// isDisabled: false
// }
// ]
// })
resetHostname()
const handleCancel = () => {
onCancel?.()
}
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
// const contactChanges = {
// added: account.contacts.filter(
// (contact) => !initialAccountState.contacts.includes(contact)
// ),
// removed: initialAccountState.contacts.filter(
// (contact) => !account.contacts.includes(contact)
// )
// }
httpService.patch<PatchAccountRequest, CacheAccount>(
GetApiRoute(ApiRoutes.ACCOUNT_ID, account.accountId),
newAccount
)
}
// const hostnameChanges = {
// added: account.hostnames.filter(
// (hostname) =>
// !initialAccountState.hostnames.some(
// (h) => h.hostname === hostname.hostname
// )
// ),
// removed: initialAccountState.hostnames.filter(
// (hostname) =>
// !account.hostnames.some((h) => h.hostname === hostname.hostname)
// )
// }
// // Handle contact changes
// if (contactChanges.added.length > 0) {
// // TODO: POST new contacts
// console.log('Added contacts:', contactChanges.added)
// }
// if (contactChanges.removed.length > 0) {
// // TODO: DELETE removed contacts
// console.log('Removed contacts:', contactChanges.removed)
// }
// // Handle hostname changes
// if (hostnameChanges.added.length > 0) {
// // TODO: POST new hostnames
// console.log('Added hostnames:', hostnameChanges.added)
// }
// if (hostnameChanges.removed.length > 0) {
// // TODO: DELETE removed hostnames
// console.log('Removed hostnames:', hostnameChanges.removed)
// }
// onSave(account)
const handleDelete = (accountId: string) => {
onDelete?.(accountId)
}
return (
@ -217,19 +274,9 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
<div className="mb-4">
<CustomCheckbox
checked={account.isDisabled}
checked={newAccount.isDisabled?.value ?? false}
label="Disabled"
onChange={(value) => handleIsDisabledChange(value)}
className="mr-2 flex-grow"
/>
</div>
<div className="mb-4">
<CustomEnumSelect
title="Challenge Type"
enumType={ChallengeTypes}
selectedValue={account.challengeType}
onChange={(option) => handleChallengeTypeChange(option)}
onChange={handleIsDisabledChange}
className="mr-2 flex-grow"
/>
</div>
@ -237,22 +284,24 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
<div className="mb-4">
<h3 className="text-xl font-medium mb-2">Contacts:</h3>
<ul className="list-disc list-inside pl-4 mb-2">
{account.contacts.map((contact) => (
<li key={contact} className="text-gray-700 mb-2 inline-flex">
{contact}
<CustomButton
type="button"
onClick={() => deleteContact(contact)}
className="bg-red-500 text-white p-2 rounded ml-2"
>
<FaTrash />
</CustomButton>
{newAccount.contacts?.map((contact) => (
<li key={contact.value} className="text-gray-700 mb-2">
<div className="inline-flex">
{contact.value}
<CustomButton
type="button"
onClick={() => handleDeleteContact(contact.value ?? '')}
className="bg-red-500 text-white p-2 rounded ml-2"
>
<FaTrash />
</CustomButton>
</div>
</li>
))}
</ul>
<div className="flex items-center mb-4">
<CustomInput
value={newContact}
value={contact}
onChange={handleContactChange}
placeholder="Add new contact"
type="email"
@ -264,43 +313,49 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
/>
<CustomButton
type="button"
//onClick={addContact}
onClick={handleAddContact}
className="bg-green-500 text-white p-2 rounded ml-2"
>
<FaPlus />
</CustomButton>
</div>
</div>
<div className="mb-4">
<CustomEnumSelect
title="Challenge Type"
enumType={ChallengeTypes}
selectedValue={account.challengeType}
className="mr-2 flex-grow"
disabled={true}
/>
</div>
<div>
<h3 className="text-xl font-medium mb-2">Hostnames:</h3>
<ul className="list-disc list-inside pl-4 mb-2">
{account.hostnames?.map((hostname) => (
<li key={hostname.hostname} className="text-gray-700 mb-2">
{newAccount.hostnames?.map((hostname) => (
<li key={hostname.hostname?.value} className="text-gray-700 mb-2">
<div className="inline-flex">
{hostname.hostname} - {hostname.expires.toDateString()} -{' '}
<span
className={`ml-2 px-2 py-1 rounded ${
hostname.isUpcomingExpire
? 'bg-yellow-200 text-yellow-800'
: 'bg-green-200 text-green-800'
}`}
>
{hostname.isUpcomingExpire ? 'Upcoming' : 'Not Upcoming'}
</span>{' '}
-{' '}
{hostname.hostname?.value} -{' '}
<CustomCheckbox
className="ml-2"
checked={hostname.isDisabled}
checked={hostname.isDisabled?.value ?? false}
label="Disabled"
onChange={(value) =>
handleHostnameDisabledChange(hostname.hostname, value)
handleHostnameDisabledChange(
hostname.hostname?.value ?? '',
value
)
}
/>
</div>
<CustomButton
type="button"
onClick={() => deleteHostname(hostname.hostname)}
onClick={() =>
handleDeleteHostname(hostname.hostname?.value ?? '')
}
className="bg-red-500 text-white p-2 rounded ml-2"
>
<FaTrash />
@ -310,7 +365,7 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
</ul>
<div className="flex items-center">
<CustomInput
value={newHostname}
value={hostname}
onChange={handleHostnameChange}
placeholder="Add new hostname"
type="text"
@ -322,7 +377,7 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
/>
<CustomButton
type="button"
//onClick={addHostname}
onClick={handleAddHostname}
className="bg-green-500 text-white p-2 rounded ml-2"
>
<FaPlus />
@ -345,13 +400,15 @@ const AccountEdit: React.FC<AccountEditProps> = (props) => {
</div>
<div className="flex justify-between mt-4">
<CustomButton
//onClick={() => onDelete(account.accountId)}
type="button"
onClick={() => handleDelete(account.accountId)}
className="bg-red-500 text-white p-2 rounded ml-2"
>
<FaTrash />
</CustomButton>
<CustomButton
onClick={onCancel}
type="button"
onClick={handleCancel}
className="bg-yellow-500 text-white p-2 rounded ml-2"
>
Cancel

View File

@ -1,6 +1,13 @@
import { store } from '@/redux/store'
import { increment, decrement } from '@/redux/slices/loaderSlice'
import { showToast } from '@/redux/slices/toastSlice'
import { PatchOperation } from '@/models/PatchOperation'
interface HttpResponse<T> {
data: T | null
status: number
isSuccess: boolean
}
interface RequestInterceptor {
(req: XMLHttpRequest): void
@ -47,7 +54,7 @@ class HttpService {
method: string,
url: string,
data?: any
): Promise<TResponse | null> {
): Promise<HttpResponse<TResponse>> {
const xhr = new XMLHttpRequest()
xhr.open(method, url)
@ -59,7 +66,7 @@ class HttpService {
this.invokeIncrement()
return new Promise<TResponse | null>((resolve) => {
return new Promise<HttpResponse<TResponse>>((resolve) => {
xhr.onload = () => this.handleLoad<TResponse>(xhr, resolve)
xhr.onerror = () => this.handleNetworkError(resolve)
xhr.send(data ? JSON.stringify(data) : null)
@ -102,7 +109,7 @@ class HttpService {
private handleLoad<TResponse>(
xhr: XMLHttpRequest,
resolve: (value: TResponse | null) => void
resolve: (value: HttpResponse<TResponse>) => void
): void {
this.invokeDecrement()
if (xhr.status >= 200 && xhr.status < 300) {
@ -114,14 +121,22 @@ class HttpService {
private handleSuccessfulResponse<TResponse>(
xhr: XMLHttpRequest,
resolve: (value: TResponse | null) => void
resolve: (value: HttpResponse<TResponse>) => void
): void {
try {
if (xhr.response) {
const response = JSON.parse(xhr.response)
resolve(this.handleResponseInterceptors(response, null) as TResponse)
resolve({
data: this.handleResponseInterceptors(response, null) as TResponse,
status: xhr.status,
isSuccess: true
})
} else {
resolve(null)
resolve({
data: null,
status: xhr.status,
isSuccess: true
})
}
} catch (error) {
const problemDetails = this.createProblemDetails(
@ -130,13 +145,17 @@ class HttpService {
xhr.status
)
this.showProblemDetails(problemDetails)
resolve(null)
resolve({
data: null,
status: xhr.status,
isSuccess: false
})
}
}
private handleErrorResponse<TResponse>(
xhr: XMLHttpRequest,
resolve: (value: TResponse | null) => void
resolve: (value: HttpResponse<TResponse>) => void
): void {
const problemDetails = this.createProblemDetails(
xhr.statusText,
@ -144,15 +163,23 @@ class HttpService {
xhr.status
)
this.showProblemDetails(problemDetails)
resolve(this.handleResponseInterceptors(null, problemDetails))
resolve({
data: this.handleResponseInterceptors(null, problemDetails),
status: xhr.status,
isSuccess: false
})
}
private handleNetworkError<TResponse>(
resolve: (value: TResponse | null) => void
resolve: (value: HttpResponse<TResponse>) => void
): void {
const problemDetails = this.createProblemDetails('Network Error', null, 0)
this.showProblemDetails(problemDetails)
resolve(this.handleResponseInterceptors(null, problemDetails))
resolve({
data: this.handleResponseInterceptors(null, problemDetails),
status: 0,
isSuccess: false
})
}
private createProblemDetails(
@ -178,26 +205,57 @@ class HttpService {
}
}
public async get<TResponse>(url: string): Promise<TResponse | null> {
public async get<TResponse>(url: string): Promise<HttpResponse<TResponse>> {
return await this.request<TResponse>('GET', url)
}
public async post<TRequest, TResponse>(
url: string,
data: TRequest
): Promise<TResponse | null> {
): Promise<HttpResponse<TResponse>> {
return await this.request<TResponse>('POST', url, data)
}
public async put<TRequest, TResponse>(
url: string,
data: TRequest
): Promise<TResponse | null> {
): Promise<HttpResponse<TResponse>> {
return await this.request<TResponse>('PUT', url, data)
}
public async delete<TResponse>(url: string): Promise<TResponse | null> {
return await this.request<TResponse>('DELETE', url)
private cleanPatchRequest(obj: any): any {
if (Array.isArray(obj)) {
const cleanedArray = obj
.map(this.cleanPatchRequest)
.filter((item) => item !== null && item !== undefined)
return cleanedArray.length > 0 ? cleanedArray : null
} else if (typeof obj === 'object' && obj !== null) {
if (obj.op !== undefined && obj.op === PatchOperation.None) {
return null
}
const cleanedObject: any = {}
Object.keys(obj).forEach((key) => {
const cleanedValue = this.cleanPatchRequest(obj[key])
if (cleanedValue !== null) {
cleanedObject[key] = cleanedValue
}
})
return Object.keys(cleanedObject).length > 0 ? cleanedObject : null
}
return obj
}
public async patch<TRequest, TResponse>(
url: string,
data: TRequest
): Promise<HttpResponse<TResponse>> {
const cleanedData = this.cleanPatchRequest(data)
return await this.request<TResponse>('PATCH', url, cleanedData)
}
public async delete(url: string): Promise<HttpResponse<null>> {
return await this.request<null>('DELETE', url)
}
public addRequestInterceptor(interceptor: RequestInterceptor): void {
@ -233,10 +291,10 @@ export { httpService }
// Example usage of the httpService
// async function fetchData() {
// const data = await httpService.get<any>('/api/data');
// if (data) {
// console.log('Data received:', data);
// const response = await httpService.get<any>('/api/data');
// if (response.isSuccess) {
// console.log('Data received:', response.data);
// } else {
// console.error('Failed to fetch data');
// console.error('Failed to fetch data, status code:', response.status);
// }
// }

View File

@ -182,6 +182,9 @@ public class AccountService : IAccountService {
}
public async Task<IDomainResult> DeleteAccountAsync(Guid accountId) {
// TODO: Revoke all certificates
// Remove from cache
return await _cacheService.DeleteFromCacheAsync(accountId);
}
#endregion

View File

@ -216,10 +216,11 @@ public class CertsFlowService : ICertsFlowService {
public (string?, IDomainResult) AcmeChallenge(string fileName) {
DeleteExporedChallenges();
var fileContent = File.ReadAllText(Path.Combine(_acmePath, fileName));
if (fileContent == null)
var challengePath = Path.Combine(_acmePath, fileName);
if(!File.Exists(challengePath))
return IDomainResult.NotFound<string?>();
var fileContent = File.ReadAllText(Path.Combine(_acmePath, fileName));
return IDomainResult.Success(fileContent);
}