Skip to content

Commit

Permalink
#1034 update promotion page (#1055)
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenvanhadncntt authored Sep 23, 2024
1 parent 357d2ea commit d9bcfec
Show file tree
Hide file tree
Showing 8 changed files with 162 additions and 28 deletions.
3 changes: 1 addition & 2 deletions backoffice/common/items/Input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@ export const Select = <T extends FieldValues>({
id={field}
className={`form-select ${error ? 'border-danger' : ''}`}
{...register(field, registerOptions)}
defaultValue={defaultValue}
disabled={disabled}
multiple={isMultiple}
onChange={onChange}
Expand All @@ -162,7 +161,7 @@ export const Select = <T extends FieldValues>({
{placeholder}
</option>
{options.map((item) => (
<option key={item.value} value={item.value}>
<option key={item.value} value={item.value} selected={item.value === defaultValue}>
{item.label}
</option>
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ type props = {
onRemoveElement: (value: any) => void;
optionSelectedIds: number[];
isSubmitting: boolean;
addedOptions?: any[];
};

const MultipleAutoComplete = (props: props) => {
const [isFocusing, setIsFocusing] = useState(false);
const [optionSelecteds, setOptionSelecteds] = useState<any[]>([]);
const [optionSelecteds, setOptionSelecteds] = useState<any[]>(props.addedOptions ?? []);
const queryData = (query: string) => {
props.fetchOptions(query);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,32 @@ const PromotionGeneralInformation = ({
const [discountType, setDiscountType] = useState(promotion?.discountType);
const [usageType, setUsageType] = useState(promotion?.usageType);
const [applyTo, setApplyTo] = useState(promotion?.applyTo);
const [brands, setBrands] = useState(promotion?.brands.map((brand) => brand.id) ?? []);
const [brands, setBrands] = useState(promotion?.brands?.map((brand) => brand.id) ?? []);
const [categories, setCategories] = useState(
promotion?.categories.map((category) => category.id) ?? []
promotion?.categories?.map((category) => category.id) ?? []
);
const [products, setProducts] = useState(promotion?.products.map((product) => product.id) ?? []);
const [products, setProducts] = useState(promotion?.products?.map((product) => product.id) ?? []);
const [productVms, setProductVms] = useState(promotion?.products ?? []);
const [brandVms, setBrandVms] = useState(promotion?.brands ?? []);
const [categoryVms, setCategoryVms] = useState(promotion?.categories ?? []);

useEffect(() => {
if (promotion) {
setDiscountType(promotion.discountType);
setUsageType(promotion.usageType);
setApplyTo(promotion.applyTo);

setProducts(promotion.products?.map((product) => product.id) ?? []);
setProductVms(promotion.products ?? []);

setBrands(promotion.brands?.map((brand) => brand.id) ?? []);
setBrandVms(promotion.brands ?? []);

setCategories(promotion.categories?.map((category) => category.id) ?? []);
setCategoryVms(promotion.categories ?? []);
}
}, [promotion]);

useEffect(() => {
if (applyTo === 'PRODUCT') {
searchProducts('').then((data) => {
Expand All @@ -45,10 +62,13 @@ const PromotionGeneralInformation = ({
const convertDateToString = (date?: Date | string) => {
if (date) {
if (typeof date === 'string') {
return date;
date = new Date(date);
}
const month = date.getMonth() + 1;
return `${date.getFullYear()}-${month > 9 ? month : '0' + month}-${date.getDate()}`;
const dateInMonth = date.getDate();
return `${date.getFullYear()}-${month > 9 ? month : '0' + month}-${
dateInMonth > 9 ? dateInMonth : '0' + dateInMonth
}`;
}
return '';
};
Expand Down Expand Up @@ -161,7 +181,6 @@ const PromotionGeneralInformation = ({
setDiscountType(event.target.value);
}}
/>

{discountType === 'PERCENTAGE' && (
<Input
labelText="Discount percentage"
Expand Down Expand Up @@ -265,7 +284,6 @@ const PromotionGeneralInformation = ({
<MultipleAutoComplete
labelText="Product"
field="product"
defaultValue={promotion?.products}
register={register}
registerOptions={{
required: { value: true, message: 'Product is required' },
Expand All @@ -276,13 +294,13 @@ const PromotionGeneralInformation = ({
optionSelectedIds={products}
isSubmitting={isSubmitting}
onRemoveElement={(id) => removeProduct(id)}
addedOptions={promotion?.products}
/>
)}
{!isSubmitting && applyTo === 'CATEGORY' && (
<MultipleAutoComplete
labelText="Category"
field="category"
defaultValue={promotion?.categories}
register={register}
registerOptions={{
required: { value: true, message: 'Category is required' },
Expand All @@ -293,13 +311,13 @@ const PromotionGeneralInformation = ({
optionSelectedIds={categories}
isSubmitting={isSubmitting}
onRemoveElement={(id) => removeCategory(id)}
addedOptions={promotion?.categories}
/>
)}
{!isSubmitting && applyTo === 'BRAND' && (
<MultipleAutoComplete
labelText="Brand"
field="brand"
defaultValue={promotion?.brands}
register={register}
registerOptions={{
required: { value: true, message: 'Brand is required' },
Expand All @@ -310,6 +328,7 @@ const PromotionGeneralInformation = ({
optionSelectedIds={brands}
isSubmitting={isSubmitting}
onRemoveElement={(id) => removeBrand(id)}
addedOptions={promotion?.brands}
/>
)}
</>
Expand Down
8 changes: 4 additions & 4 deletions backoffice/modules/promotion/models/Promotion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export type PromotionDetail = {
discountPercentage: number;
discountAmount: number;
isActive: boolean;
startDate: Date | string;
endDate: Date | string;
startDate: string;
endDate: string;
brands: BrandVm[];
categories: CategoryGetVm[];
products: ProductVm[];
Expand Down Expand Up @@ -51,8 +51,8 @@ export type PromotionDto = {
discountPercentage?: number;
discountAmount?: number;
isActive: boolean;
startDate: Date;
endDate: Date;
startDate: string;
endDate: string;
brandIds: number[];
categoryIds: number[];
productIds: number[];
Expand Down
10 changes: 6 additions & 4 deletions backoffice/modules/promotion/services/PromotionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,11 @@ export async function getPromotions(request: PromotionListRequest) {
}

export async function createPromotion(promotion: PromotionDto) {
const url = `${baseUrl}`;
return (await apiClientService.post(url, JSON.stringify(promotion))).json();
return await apiClientService.post(baseUrl, JSON.stringify(promotion));
}

export async function updatePromotion(promotion: PromotionDto) {
const url = `${baseUrl}/${promotion.id}`;
return (await apiClientService.put(url, promotion)).json();
return await apiClientService.put(baseUrl, JSON.stringify(promotion));
}

export async function getPromotion(id: number) {
Expand All @@ -30,3 +28,7 @@ function createRequestFromObject(request: any): string {
})
.join('&');
}

export const cancel = () => {
window.location.href = '/promotion/manager-promotion';
};
111 changes: 111 additions & 0 deletions backoffice/pages/promotion/manager-promotion/[id]/edit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { toastError } from '@commonServices/ToastService';
import PromotionGeneralInformation from 'modules/promotion/components/PromotionGeneralInformation';
import { PromotionDetail, PromotionDto } from 'modules/promotion/models/Promotion';
import { cancel, getPromotion, updatePromotion } from 'modules/promotion/services/PromotionService';
import { NextPage } from 'next';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';

const PromotionUpdate: NextPage = () => {
const router = useRouter();
const { id } = router.query;

const {
register,
handleSubmit,
formState: { errors },
setValue,
trigger,
} = useForm<PromotionDto>();

const [isSubmittingForm, setIsSubmittingForm] = useState(false);

const [promotion, setPromotion] = useState<PromotionDetail>();

useEffect(() => {
if (id) {
getPromotion(+id).then((data) => {
setPromotion(data);
setDefaultValues(data);
});
} else {
toastError(`Promotion id ${id} not found`);
router.push({ pathname: `/404` }); //NOSONAR
}
}, []);

const setDefaultValues = (promotion: PromotionDetail) => {
setValue('slug', promotion.slug);
setValue('couponCode', promotion.couponCode);
setValue('name', promotion.name);
setValue('applyTo', promotion.applyTo);
setValue('startDate', removeTime(promotion.startDate));
setValue('endDate', removeTime(promotion.endDate));
setValue('discountAmount', promotion.discountAmount);
setValue('discountPercentage', promotion.discountPercentage);
setValue('usageLimit', promotion.usageLimit);
setValue('usageType', promotion.usageType);
setValue('discountType', promotion.discountType);
setValue('description', promotion.description);
setValue('brandIds', promotion.brands?.map((brand) => brand.id) ?? []);
setValue('categoryIds', promotion.categories?.map((category) => category.id) ?? []);
setValue('productIds', promotion.products?.map((product) => product.id) ?? []);
setValue('isActive', promotion.isActive);
};

const removeTime = (date: string) => {
const DATE_PATTERN = /\d{4}-\d{2}-\d{2}/g;
return date.match(DATE_PATTERN)![0];
};

const handleUpdatePromotion = async (dataForm: PromotionDto) => {
dataForm.id = +id!;
dataForm.discountAmount = dataForm.discountAmount ?? 0;
dataForm.discountPercentage = dataForm.discountPercentage ?? 0;

updatePromotion(dataForm).then((response) => {
if (response.status === 200) {
router.replace('/promotion/manager-promotion');
}
});
};

const submitUpdateForm = () => {
setIsSubmittingForm(true);
handleSubmit(handleUpdatePromotion)();
};

return (
<div className="row mt-5">
<div className="col-md-8">
<h2>Update Promotion</h2>
<form>
<PromotionGeneralInformation
register={register}
errors={errors}
setValue={setValue}
trigger={trigger}
promotion={promotion}
isSubmitting={isSubmittingForm}
/>
<div className="mt-5">
<button
className="btn btn-primary"
style={{ marginRight: '20px' }}
type="button"
onClick={submitUpdateForm}
>
Save
</button>
<button className="btn btn-danger ml-4" type="button" onClick={cancel}>
Cancel
</button>
</div>
</form>
</div>
</div>
);
};

export default PromotionUpdate;
11 changes: 5 additions & 6 deletions backoffice/pages/promotion/manager-promotion/create.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import PromotionGeneralInformation from 'modules/promotion/components/PromotionGeneralInformation';
import { PromotionDto } from 'modules/promotion/models/Promotion';
import { createPromotion } from 'modules/promotion/services/PromotionService';
import { cancel, createPromotion } from 'modules/promotion/services/PromotionService';
import { NextPage } from 'next';
import { useRouter } from 'next/router';
import { useState } from 'react';
import { useForm } from 'react-hook-form';

const PromotionCreate: NextPage = () => {
const router = useRouter();

const {
register,
handleSubmit,
Expand Down Expand Up @@ -38,15 +41,11 @@ const PromotionCreate: NextPage = () => {

createPromotion(promotion).then((response) => {
if (response.status === 201) {
window.location.href = '/promotion/manager-promotion';
router.replace('/promotion/manager-promotion');
}
});
};

const cancel = () => {
window.location.href = '/promotion/manager-promotion';
};

const submitForm = () => {
setIsSubmitting(true);
handleSubmit(handleSubmitPromotion)();
Expand Down
7 changes: 5 additions & 2 deletions backoffice/pages/promotion/manager-promotion/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ const PromotionList: NextPage = () => {
date = new Date(date);
}
const month = date.getMonth() + 1;
return `${date.getFullYear()}-${month > 9 ? month : '0' + month}-${date.getDate()}`;
const dateNumber = date.getDate();
return `${date.getFullYear()}-${month > 9 ? month : '0' + month}-${
dateNumber > 9 ? dateNumber : '0' + dateNumber
}`;
};

return (
Expand Down Expand Up @@ -118,7 +121,7 @@ const PromotionList: NextPage = () => {
<td>{convertToStringDate(promotion.startDate)}</td>
<td>{convertToStringDate(promotion.endDate)}</td>
<td>
<Link href={`/promotion/manager-promotion/${promotion.id}`}>
<Link href={`/promotion/manager-promotion/${promotion.id}/edit`}>
<button className="btn btn-outline-primary btn-sm" type="button">
Edit
</button>
Expand Down

0 comments on commit d9bcfec

Please sign in to comment.