You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
GHHub/src/views/products/Audit.jsx

324 lines
14 KiB
JavaScript

import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { App, Empty, Button, Collapse, Table, Space, Alert, Tooltip, Popover, Typography } from 'antd';
import { useProductsTypes, useProductsAuditStatesMapVal, formatGroupSize } from '@/hooks/useProductsSets';
import SecondHeaderWrapper from '@/components/SecondHeaderWrapper';
import { useTranslation } from 'react-i18next';
import useProductsStore, { getPPLogAction, getPPRunningAction, postProductsQuoteAuditAction, } from '@/stores/Products/Index';
import { cloneDeep, groupBy, isEmpty, isNotEmpty } from '@/utils/commons';
import useAuthStore from '@/stores/Auth';
import RequireAuth from '@/components/RequireAuth';
import { PERM_PRODUCTS_MANAGEMENT, PERM_PRODUCTS_OFFER_AUDIT, PERM_PRODUCTS_OFFER_PUT } from '@/config';
import Header from './Detail/Header';
import dayjs from 'dayjs';
import { usingStorage } from '@/hooks/usingStorage';
import { ClockCircleFilled, ClockCircleOutlined, PlusCircleFilled, PlusCircleOutlined } from '@ant-design/icons';
const parseJson = (str) => {
let result;
if (str === null || str === undefined || str === '') {
return [];
}
try {
result = JSON.parse(str);
return result;
} catch (e) {
return [];
}
};
const columnsSets = t => [
{ key: 'adult', title: t('AgeType.Adult'), width: '12rem', render: (_, { adult_cost, currency, unit_id, unit_name, lastedit_changed }) => {
const _changed = parseJson(lastedit_changed)?.reduce((acc, cur) => ({...acc, ...cur}), {});
const preValue = isNotEmpty(_changed.adult_cost) ? <div className='text-muted line-through '>{_changed.adult_cost}</div> : null;
return (<div>{preValue}{`${adult_cost} ${currency} / ${t(`PriceUnit.${unit_id}`)}`}</div>)} },
{ key: 'child', title: t('AgeType.Child'), width: '12rem', render: (_, { child_cost, currency, unit_id, unit_name, lastedit_changed }) => {
const _changed = parseJson(lastedit_changed)?.reduce((acc, cur) => ({...acc, ...cur}), {});
const preValue = isNotEmpty(_changed.child_cost) ? <div className='text-muted line-through '>{_changed.child_cost}</div> : null;
return <div>{preValue}{`${child_cost} ${currency} / ${t(`PriceUnit.${unit_id}`)}`}</div>;
} },
// {key: 'unit', title: t('Unit'), },
{
key: 'groupSize',
dataIndex: ['group_size_min'],
title: t('group_size'), width: '6rem',
render: (_, { audit_state_id, group_size_min, group_size_max, lastedit_changed }) => {
const _changed = parseJson(lastedit_changed)?.reduce((acc, cur) => ({...acc, ...cur}), {});
const preValue = ![-1, 1, 2].includes(audit_state_id) && (isNotEmpty(_changed.group_size_min) || isNotEmpty(_changed.group_size_max)) ? <div className='text-muted line-through '>{`${_changed.group_size_min ?? group_size_min} - ${_changed.group_size_max ?? group_size_max}`}</div> : null;
return <div>{preValue}{formatGroupSize(group_size_min, group_size_max)}</div>;
}
},
{
key: 'useDates',
dataIndex: ['use_dates_start'],
title: t('use_dates'), width: '12rem',
render: (_, { use_dates_start, use_dates_end, weekdays }) => `${use_dates_start} ~ ${use_dates_end}`, // + (weekdays ? `, ${t('OnWeekdays')}${weekdays}` : ''),
},
{ key: 'weekdays', dataIndex: ['weekdays'], title: t('Weekdays'), width: '6rem', render: (text, r) => text || t('Unlimited') },
];
const PriceLogPopover = ({ title, fetchData, ...props}) => {
const { t } = useTranslation('products');
const [open, setOpen] = useState(false);
const [logData, setLogData] = useState([]);
const getData = async () => {
const data = await fetchData();
setLogData(data);
};
const columns = [...columnsSets(t), { title: '时间', dataIndex: 'updatetime', key: 'updatetime'}];
return (
<Popover {...props}
title={
<div className='flex justify-between mt-0 gap-4 items-center'>
<Typography.Text strong>{title}</Typography.Text>
<Button size='small' onClick={() => setOpen(false)}>
&times;
</Button>
</div>
}
content={
<>
<Table columns={columns} dataSource={logData} size='small' />
</>
}
trigger={['click']}
placement='bottom'
className=''
rootClassName='w-5/6'
open={open}
onOpenChange={(v) => {
setOpen(v);
}}>
<Button onClick={getData} title={title}>
{title}
</Button>
</Popover>
);
};
const PriceTable = ({ productType, dataSource, refresh }) => {
const { t } = useTranslation('products');
const { travel_agency_id, use_year, audit_state } = useParams();
const isPermitted = useAuthStore(state => state.isPermitted);
const [loading, activeAgency] = useProductsStore((state) => [state.loading, state.activeAgency]);
const [setEditingProduct] = useProductsStore((state) => [state.setEditingProduct]);
const { message, notification } = App.useApp();
const stateMapVal = useProductsAuditStatesMapVal();
const [renderData, setRenderData] = useState(dataSource);
// console.log(dataSource);
const handleAuditPriceItem = (state, row, rowIndex) => {
postProductsQuoteAuditAction(state, { id: row.id, travel_agency_id: activeAgency.travel_agency_id })
.then((json) => {
if (json.errcode === 0) {
message.success(json.errmsg);
if (typeof refresh === 'function') {
// refresh(); // debug: 不要刷新, 等太久
// const newData = structuredClone(renderData);
const newData = cloneDeep(renderData);
newData.splice(rowIndex, 1, {...row, audit_state_id: state, });
setRenderData(newData);
}
}
})
.catch((ex) => {
notification.error({
message: 'Notification',
description: ex.message,
placement: 'top',
duration: 4,
});
});
};
const getLog = async ({ product_id, price_id }) => {
const data = await getPPLogAction({ travel_agency_id, product_id, price_id });
return data;
};
const getRunning = async ({ product_id }) => {
const data = await getPPRunningAction({ travel_agency_id, product_id_list: product_id });
return data?.[0]?.quotation || [];
};
const rowStyle = (r, tri) => {
const trCls = tri%2 !== 0 ? ' bg-stone-50' : ''; // 奇偶行
const [infoI, quoteI] = r.rowSpanI;
const bigTrCls = quoteI === 0 && tri !== 0 ? 'border-collapse border-double border-0 border-t-4 border-stone-300' : ''; // 合并行双下划线
// && isNotEmpty(r.lastedit_changed)
const editedCls = (r.audit_state_id === 0 ) ? '!bg-amber-100' : ''; // 待审核, 黄
const newCls = (r.audit_state_id === -1 ) ? '!bg-sky-100' : ''; // 新增, 蓝
const editedCls_ = isNotEmpty(r.lastedit_changed) ? (r.audit_state_id === 0 ? '!bg-red-100' : '!bg-sky-100') : '';
return [trCls, bigTrCls, newCls, editedCls].join(' ');
};
const columns = [
{ key: 'title', dataIndex: ['info', 'title'], width: '16rem', title: t('Title'), onCell: (r, index) => ({ rowSpan: r.rowSpan, }), className: 'bg-white', render: (text, r) => {
const title = text || r.lgc_details?.['2']?.title || r.lgc_details?.['1']?.title || '';
const itemLink = isPermitted(PERM_PRODUCTS_OFFER_AUDIT) ? `/products/${travel_agency_id}/${use_year}/${audit_state}/edit` : isPermitted(PERM_PRODUCTS_OFFER_PUT) ? `/products/edit` : '';
return <div className=''>{isNotEmpty(itemLink) ? <div className='' onClick={() => setEditingProduct({info: r.info})}><Link to={itemLink} >{title}</Link></div> : title}</div> ;
} },
...columnsSets(t),
{
key: 'state',
title: t('State'),
render: (_, r) => {
const stateCls = ` text-${stateMapVal[`${r.audit_state_id}`]?.color} `;
return <span className={stateCls}>{stateMapVal[`${r.audit_state_id}`]?.label}</span>;
},
},
{
title: '',
key: 'action',
render: (_, r, ri) =>
(Number(r.audit_state_id)) === 0 ? (
<RequireAuth subject={PERM_PRODUCTS_OFFER_AUDIT}>
<Space>
<Button onClick={() => handleAuditPriceItem('2', r, ri)}></Button>
<Button onClick={() => handleAuditPriceItem('3', r, ri)}></Button>
<PriceLogPopover title='查看历史' fetchData={() => getLog({ travel_agency_id, product_id: r.info.id, price_id: r.id })} {...{ travel_agency_id, product_id: r.info.id, price_id: r.id }} />
</Space>
</RequireAuth>
) : null,
},
{
title: '',
key: 'action2', width: '6rem',
onCell: (r, index) => ({ rowSpan: r.rowSpan, }),
render: (_, r) => {
const showPublicBtn = null; // r.pendingQuotation ? <Popover title='查看已发布的价格' trigger={['click']}> <Button size='small' className='ml-2' onClick={() => { }}>✈</Button></Popover> : null;
const btn2 = (
<PriceLogPopover
placement='bottom'
className='max-w-[1000px]'
title='已发布的'
fetchData={() => getRunning({ travel_agency_id, product_id: r.info.id, price_id: r.id })}
{...{ travel_agency_id, product_id: r.info.id, price_id: r.id }}
/>
);
return <div className="absolute bottom-2 right-1">{btn2}</div> ;
},
}
];
return (
<Table
size={'small'}
className='border-collapse'
rowHoverable={false}
rowClassName={rowStyle}
pagination={false}
{...{ columns }}
dataSource={renderData}
rowKey={(r) => r.id}
/>
);
};
/**
*
*/
const TypesPanels = (props) => {
const { t } = useTranslation();
const [loading, agencyProducts] = useProductsStore((state) => [state.loading, state.agencyProducts]);
// console.log(agencyProducts);
const productsTypes = useProductsTypes();
const [activeKey, setActiveKey] = useState([]);
const [showTypes, setShowTypes] = useState([]);
useEffect(() => {
// 只显示有产品的类型; 展开产品的价格表, 合并名称列; 转化为价格主表, 携带产品属性信息
const hasDataTypes = Object.keys(agencyProducts);
let tempKey = '';
const _show = productsTypes
.filter((kk) => hasDataTypes.includes(kk.value))
.map((ele) => {
const _children = agencyProducts[ele.value].reduce(
(r, c, ri) =>
r.concat(
c.quotation.map((q, i) => ({
...q,
weekdays: q.weekdays
.split(',')
.filter(Boolean)
.map((w) => t(`weekdaysShort.${w}`))
.join(', '),
info: c.info,
lgc_details: c.lgc_details.reduce((rlgc, clgc) => ({...rlgc, [clgc.lgc]: clgc}), {}),
rowSpan: i === 0 ? c.quotation.length : 0,
rowSpanI: [ri, i],
pendingQuotation: c.quotation.findIndex(q2 => q2.audit_state_id===0) !== -1 ,
}))
),
[]
);
tempKey = _children.length > 0 && tempKey==='' ? ele.key : tempKey;
const _childrenByState = groupBy(_children, 'audit_state_id');
// if (_children.length > 0) console.log('PriceTable\n'+ele.value+'\n', _children)
return {
...ele,
extra: <Space>
{_childrenByState['1']?.length > 0 && <Alert showIcon type='success' className='py-1 text-xs' message={_childrenByState['1']?.length || 0} />}
{_childrenByState['2']?.length > 0 && <Alert showIcon type='success' className='py-1 text-xs' message={_childrenByState['2']?.length || 0} icon={<ClockCircleOutlined />} />}
{_childrenByState['0']?.length > 0 && <Alert showIcon type='warning' className='py-1 text-xs' message={_childrenByState['0']?.length || 0} />}
{_childrenByState['3']?.length > 0 && <Alert showIcon type='error' className='py-1 text-xs' message={_childrenByState['3']?.length || 0} />}
{_childrenByState['-1']?.length > 0 && <Alert showIcon type='info' className='py-1 text-xs' message={_childrenByState['-1']?.length || 0} icon={<PlusCircleFilled />} />}
<span>{t('Table.Total', { total: _children.length })}</span>
</Space>,
children: (
<PriceTable
// loading={loading}
productType={ele.value}
dataSource={_children}
refresh={props.refresh}
/>
),
}});
setShowTypes(_show);
setActiveKey(isEmpty(_show) ? [] : [tempKey]);
return () => {};
}, [productsTypes, agencyProducts]);
const onCollapseChange = (_activeKey) => {
setActiveKey(_activeKey);
};
return isEmpty(agencyProducts) ? <Empty /> : <Collapse items={showTypes} activeKey={activeKey} onChange={onCollapseChange} />;
};
const Audit = ({ ...props }) => {
const { notification, modal } = App.useApp()
const isPermitted = useAuthStore(state => state.isPermitted);
const { travel_agency_id, use_year, audit_state } = useParams();
const [activeAgency, getAgencyProducts] = useProductsStore((state) => [state.activeAgency, state.getAgencyProducts]);
const [loading, setLoading] = useProductsStore(state => [state.loading, state.setLoading]);
const { travelAgencyId } = usingStorage();
const handleGetAgencyProducts = async ({pick_year, pick_agency, pick_state}={}) => {
const year = pick_year || use_year || dayjs().year();
const agency = pick_agency || travel_agency_id || travelAgencyId;
const state = pick_state ?? audit_state;
getAgencyProducts({ travel_agency_id: agency, use_year: year, audit_state: state }).catch(ex => {
setLoading(false);
notification.error({
message: 'Notification',
description: ex.message,
placement: 'top',
duration: 4,
})
});
};
return (
<>
<SecondHeaderWrapper loading={loading} backTo={isPermitted(PERM_PRODUCTS_MANAGEMENT) ? `/products` : false} header={<Header title={activeAgency.travel_agency_name} refresh={handleGetAgencyProducts} />} >
{/* <PrintContractPDF /> */}
<TypesPanels refresh={handleGetAgencyProducts} />
</SecondHeaderWrapper>
</>
);
};
export default Audit;