Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(DEV-12235): Payment terms create/update/delete #478

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { useState } from 'react';
import { useFormContext } from 'react-hook-form';

import { components } from '@/api';
import { CreateReceivablesFormProps } from '@/components/receivables/InvoiceDetails/CreateReceivable/validation';
import { RHFTextField } from '@/components/RHF/RHFTextField';
import { t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import {
Box,
FormHelperText,
MenuItem,
Skeleton,
useTheme,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import { Box, MenuItem, Skeleton, useTheme, Button } from '@mui/material';

import {
PaymentTermsSummary,
PaymentTermsDialog,
} from './components/PaymentTerms';
import type { SectionGeneralProps } from './Section.types';

type Props = SectionGeneralProps & {
Expand All @@ -22,46 +22,95 @@ type Props = SectionGeneralProps & {
}
| undefined;
isLoading: boolean;
selectedPaymentTerm?: components['schemas']['PaymentTermsResponse'];
onPaymentTermsChange: (
id?: components['schemas']['PaymentTermsResponse']['id']
) => void;
};

enum TermsDialogState {
Closed,
Create,
Update,
}

export const PaymentSection = ({
disabled,
paymentTerms,
isLoading,
selectedPaymentTerm,
onPaymentTermsChange,
}: Props) => {
const { i18n } = useLingui();
const { control } = useFormContext<CreateReceivablesFormProps>();
const [termsDialogState, setTermsDialogState] = useState<TermsDialogState>(
TermsDialogState.Closed
);

const openEditDialog = () => {
setTermsDialogState(TermsDialogState.Update);
};

const onTermsDialogClosed = (id?: string, deleted?: boolean) => {
setTermsDialogState(TermsDialogState.Closed);

if (id || deleted) {
onPaymentTermsChange(id);
}
};

return (
<Box>
{isLoading ? (
<SelectSkeleton />
) : (
<RHFTextField
fullWidth
select
name="payment_terms_id"
control={control}
label={t(i18n)`Payment terms`}
disabled={disabled || !paymentTerms?.data?.length}
required
>
{!paymentTerms?.data?.length && <MenuItem value="" />}
{paymentTerms?.data?.map(({ id, name, description }) => (
<MenuItem key={id} value={id}>
{name}
{description && ` (${description})`}
</MenuItem>
))}
</RHFTextField>
)}

{!isLoading && !paymentTerms?.data?.length && (
<FormHelperText>
{t(
i18n
)`There is no payment terms available. Please create one in the settings.`}
</FormHelperText>
<>
<RHFTextField
fullWidth
select
name="payment_terms_id"
control={control}
label={t(i18n)`Payment terms`}
disabled={disabled}
required
>
<Button
variant="text"
startIcon={<AddIcon />}
fullWidth
sx={{
justifyContent: 'flex-start',
px: 2,
}}
onClick={() => setTermsDialogState(TermsDialogState.Create)}
>
{t(i18n)`Create payment term`}
</Button>
{paymentTerms?.data?.map(({ id, name, description }) => (
<MenuItem key={id} value={id}>
{name}
{description && ` (${description})`}
</MenuItem>
))}
</RHFTextField>
{selectedPaymentTerm && (
<Box sx={{ mt: 1 }}>
<PaymentTermsSummary
paymentTerm={selectedPaymentTerm}
openEditDialog={openEditDialog}
/>
</Box>
)}
<PaymentTermsDialog
show={termsDialogState !== TermsDialogState.Closed}
closeDialog={onTermsDialogClosed}
selectedTerm={
termsDialogState === TermsDialogState.Update
? selectedPaymentTerm
: undefined
}
/>
</>
)}
</Box>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@ export const FullfillmentSummary = ({ disabled }: SectionGeneralProps) => {

const { api } = useMoniteContext();

const { data: paymentTerms, isLoading: isPaymentTermsLoading } =
api.paymentTerms.getPaymentTerms.useQuery();
const {
data: paymentTerms,
isLoading: isPaymentTermsLoading,
refetch,
} = api.paymentTerms.getPaymentTerms.useQuery();

const { root } = useRootElements();
const dateTimeFormat = useDateTimeFormat();
Expand All @@ -38,6 +41,11 @@ export const FullfillmentSummary = ({ disabled }: SectionGeneralProps) => {
(term) => term.id === paymentTermsId
);

const handlePaymentTermsChange = async (newId: string = '') => {
await refetch();
setValue('payment_terms_id', newId);
};

return (
<>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
Expand Down Expand Up @@ -146,6 +154,8 @@ export const FullfillmentSummary = ({ disabled }: SectionGeneralProps) => {
disabled={disabled}
paymentTerms={paymentTerms}
isLoading={isPaymentTermsLoading}
selectedPaymentTerm={selectedPaymentTerm}
onPaymentTermsChange={handlePaymentTermsChange}
/>
</Box>
</Box>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { components } from '@/api';
import { Dialog } from '@/components';
import { i18n } from '@lingui/core';
import { t } from '@lingui/macro';
import {
DialogTitle,
DialogContent,
DialogActions,
Button,
} from '@mui/material';

import { usePaymentTermsApi } from './usePaymentTermsApi';

export interface DeletePaymentTermsProps {
show: boolean;
closeDialog: (payload: boolean) => void;
paymentTermsId: components['schemas']['PaymentTermsResponse']['id'];
}

export const DeletePaymentTerms = ({
show,
closeDialog,
paymentTermsId,
}: DeletePaymentTermsProps) => {
const { deletePaymentTerm } = usePaymentTermsApi({
onSuccessfullChange: () => closeDialog(true),
});

return (
<Dialog open={show}>
<DialogTitle>{t(i18n)`Delete payment term?`}</DialogTitle>
<DialogContent>
{t(
i18n
)`You won’t be able to use it to create new invoices, but it won’t affect the existing invoices with this term and their future copies.`}
</DialogContent>
<DialogActions>
<Button variant="text" onClick={() => closeDialog(false)}>{t(
i18n
)`Cancel`}</Button>
<Button
variant="outlined"
color="error"
onClick={() => deletePaymentTerm(paymentTermsId)}
>
{t(i18n)`Delete`}
</Button>
</DialogActions>
</Dialog>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { useEffect, useState } from 'react';
import { UseFormRegister, FieldErrors, FieldError } from 'react-hook-form';

import { i18n } from '@lingui/core';
import { t } from '@lingui/macro';
import DeleteIcon from '@mui/icons-material/Delete';
import {
Alert,
Typography,
Button,
Stack,
Card,
CardContent,
CardHeader,
TextField,
} from '@mui/material';

import { TermField, PaymentTermsFields } from './types';

export interface DiscountFormProps {
field: TermField;
index: number;
isLast: boolean;
remove: () => void;
register: UseFormRegister<PaymentTermsFields>;
errors: FieldErrors<PaymentTermsFields>;
}

export const DiscountForm = ({
field,
index,
isLast,
remove,
register,
errors,
}: DiscountFormProps) => {
const [error, setError] = useState<string | undefined>('');

useEffect(() => {
if (Object.keys(errors).length > 0) {
const flatErrors = Object.values(errors[field] || {}).map(
(error) => (error as FieldError)?.message
);

setError(flatErrors[0]);
} else {
setError('');
}
}, [errors, field]);

return (
<>
{!!error && (
<Alert severity="error" sx={{ my: 1 }}>
{error}
</Alert>
)}
<Card>
<CardHeader
title={t(i18n)`Discount ${index + 1}`}
titleTypographyProps={{
variant: 'subtitle1',
}}
action={
<Button
variant="text"
color="error"
size="small"
disabled={!isLast}
startIcon={<DeleteIcon />}
onClick={remove}
>
{t(i18n)`Delete`}
</Button>
}
/>
<CardContent>
<Stack direction="row" alignItems="center" gap={1} useFlexGap>
<Typography variant="body2" sx={{ whiteSpace: 'nowrap' }}>{t(
i18n
)`Pay in`}</Typography>
<TextField
{...register(`${field}.number_of_days`)}
type="number"
error={!!errors?.[field]?.number_of_days}
InputProps={{
endAdornment: t(i18n)`days`,
}}
/>
<Typography variant="body2" sx={{ whiteSpace: 'nowrap' }}>{t(
i18n
)`to get discount`}</Typography>
<TextField
{...register(`${field}.discount`)}
type="number"
error={!!errors?.[field]?.discount}
InputProps={{
endAdornment: '%',
}}
/>
</Stack>
</CardContent>
</Card>
</>
);
};
Loading
Loading