服务模块

This commit is contained in:
‘Liammcl’
2024-12-28 15:51:26 +08:00
parent 4f0e7be806
commit d021f39b04
8 changed files with 623 additions and 895 deletions

View File

@@ -1,7 +1,24 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Form, Input, InputNumber, Button, Card, Typography, Modal, message, Divider, Select } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect, useMemo } from "react";
import {
Form,
Input,
InputNumber,
Button,
Card,
Typography,
Modal,
message,
Divider,
Select,
} from "antd";
import {
PlusOutlined,
DeleteOutlined,
EditOutlined,
CheckOutlined,
CloseOutlined,
} from "@ant-design/icons";
import { v4 as uuidv4 } from "uuid";
import { supabase } from "@/config/supabase";
import { supabaseService } from "@/hooks/supabaseService";
const { Text } = Typography;
@@ -10,17 +27,21 @@ const SectionList = ({
isView,
formValues,
type,
currentCurrency = 'CNY'
currentCurrency = "TWD",
}) => {
const [editingSectionIndex, setEditingSectionIndex] = useState(null);
const [editingSectionName, setEditingSectionName] = useState('');
const [editingSectionName, setEditingSectionName] = useState("");
const [templateModalVisible, setTemplateModalVisible] = useState(false);
const [availableSections, setAvailableSections] = useState([]);
const [loading, setLoading] = useState(false);
const [units, setUnits] = useState([]);
const [loadingUnits, setLoadingUnits] = useState(false);
const CURRENCY_SYMBOLS = {
CNY: "¥",
TWD: "NT$",
USD: "$",
};
// 内部计算方法
const calculateItemAmount = (quantity, price) => {
const safeQuantity = Number(quantity) || 0;
const safePrice = Number(price) || 0;
@@ -36,19 +57,13 @@ const SectionList = ({
};
const formatCurrency = (amount) => {
const CURRENCY_SYMBOLS = {
CNY: "¥",
TWD: "NT$",
USD: "$",
};
const safeAmount = Number(amount) || 0;
return `${CURRENCY_SYMBOLS[currentCurrency] || ""}${safeAmount.toLocaleString("zh-CN", {
return `${CURRENCY_SYMBOLS[currentCurrency] || "NT$"}${safeAmount.toLocaleString("zh-TW", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}`;
};
// 获取可用的小节模板
const fetchAvailableSections = async () => {
try {
setLoading(true);
@@ -56,6 +71,7 @@ const SectionList = ({
.from("resources")
.select("*")
.eq("type", "sections")
.eq("attributes->>template_type", [type])
.order("created_at", { ascending: false });
if (error) throw error;
@@ -68,134 +84,131 @@ const SectionList = ({
}
};
// 处理小节名称编辑
const handleSectionNameEdit = (sectionIndex, initialValue) => {
setEditingSectionIndex(sectionIndex);
setEditingSectionName(initialValue || '');
setEditingSectionName(initialValue || "");
};
const handleSectionNameSave = () => {
if (!editingSectionName.trim()) {
message.error('请输入小节名称');
message.error("请输入小节名称");
return;
}
const sections = form.getFieldValue('sections');
const sections = form.getFieldValue("sections");
const newSections = [...sections];
newSections[editingSectionIndex] = {
...newSections[editingSectionIndex],
sectionName: editingSectionName.trim()
sectionName: editingSectionName.trim(),
};
form.setFieldValue('sections', newSections);
form.setFieldValue("sections", newSections);
setEditingSectionIndex(null);
setEditingSectionName('');
setEditingSectionName("");
};
// 添加项目
const handleAddItem = (add) => {
add({
key: uuidv4(),
name: '',
description: '',
name: "",
description: "",
quantity: 1,
price: 0,
unit: ''
unit: "",
});
};
// 处理使用模板
const handleUseTemplate = (template, add) => {
const newSection = {
key: uuidv4(),
sectionName: template.attributes.name,
items: (template.attributes.items || []).map(item => ({
items: (template.attributes.items || []).map((item) => ({
key: uuidv4(),
name: item.name || '',
description: item.description || '',
name: item.name || "",
description: item.description || "",
price: item.price || 0,
quantity: item.quantity || 1,
unit: item.unit || '',
unit: item.unit || "",
})),
};
add(newSection);
setTemplateModalVisible(false);
message.success('套用模版成功');
message.success("套用模版成功");
};
// 处理创建自定义小节
const handleCreateCustom = (add, fieldsLength) => {
add({
key: uuidv4(),
sectionName: `服务类型 ${fieldsLength + 1}`,
items: [{
items: [
{
key: uuidv4(),
name: '',
description: '',
name: "",
description: "",
quantity: 1,
price: 0,
unit: ''
}]
unit: "",
},
],
});
setTemplateModalVisible(false);
};
// 获取单位列表
const fetchUnits = async () => {
setLoadingUnits(true);
try {
const { data: units } = await supabaseService.select('resources', {
const { data: units } = await supabaseService.select("resources", {
filter: {
'type': { eq: 'units' },
'attributes->>template_type': { in: `(${type},common)` }
type: { eq: "units" },
"attributes->>template_type": { in: `(${type},common)` },
},
order: {
column: 'created_at',
ascending: false
}
column: "created_at",
ascending: false,
},
});
setUnits(units || []);
} catch (error) {
message.error('获取单位列表失败');
message.error("获取单位列表失败");
console.error(error);
} finally {
setLoadingUnits(false);
}
};
// 在组件加载时获取单位列表
useEffect(() => {
fetchUnits();
}, []);
// 新增单位
const handleAddUnit = async (unitName) => {
try {
const { error } = await supabase
.from('resources')
.insert([{
type: 'units',
const { error } = await supabase.from("resources").insert([
{
type: "units",
attributes: {
name: unitName
name: unitName,
template_type: type,
},
schema_version: 1
}]);
schema_version: 1,
},
]);
if (error) throw error;
message.success('新增单位成功');
message.success("新增单位成功");
fetchUnits();
return true;
} catch (error) {
message.error('新增单位失败');
message.error("新增单位失败");
console.error(error);
return false;
}
};
// 模板选择弹窗内容
const renderTemplateModalContent = (add, fieldsLength) => (
<div className="space-y-6">
{availableSections.length > 0 ? (
<div className="flex flex-col">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{availableSections.map(section => (
{availableSections.map((section) => (
<div
key={section.id}
className="group relative bg-white rounded-lg shadow-sm border border-gray-200 hover:shadow-lg transition-all duration-300 cursor-pointer"
@@ -212,10 +225,19 @@ const SectionList = ({
</div>
<div className="space-y-2 mt-4 border-t pt-4">
{(section.attributes.items || []).slice(0, 3).map((item, index) => (
<div key={index} className="flex justify-between items-center">
<span className="text-sm text-gray-600 truncate flex-1">{item.name}</span>
<span className="text-sm text-gray-500 ml-2">{formatCurrency(item.price)}</span>
{(section.attributes.items || [])
.slice(0, 3)
.map((item, index) => (
<div
key={index}
className="flex justify-between items-center"
>
<span className="text-sm text-gray-600 truncate flex-1">
{item.name}
</span>
<span className="text-sm text-gray-500 ml-2">
{formatCurrency(item.price)}
</span>
</div>
))}
{(section.attributes.items || []).length > 3 && (
@@ -230,7 +252,8 @@ const SectionList = ({
<span className="text-base font-medium text-blue-500">
{formatCurrency(
(section.attributes.items || []).reduce(
(sum, item) => sum + (item.price * (item.quantity || 1) || 0),
(sum, item) =>
sum + (item.price * (item.quantity || 1) || 0),
0
)
)}
@@ -241,22 +264,55 @@ const SectionList = ({
))}
</div>
<Divider />
<div className="flex justify-center">
<Button
type="dashed"
type="primary"
icon={<PlusOutlined />}
onClick={() => handleCreateCustom(add, fieldsLength)}
className="w-1/3 border-2"
className="bg-blue-600 hover:bg-blue-700 border-0 shadow-md hover:shadow-lg transition-all duration-200 h-10 px-6 rounded-lg flex items-center gap-2"
>
自定义模块
<span className="font-medium">自定义模块</span>
</Button>
</div>
</div>
) : (
<div className="flex flex-col items-center justify-center py-16 px-4">
<div className="w-48 h-48 mb-8">
<svg
className="w-full h-full text-gray-200"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1}
d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
/>
</svg>
</div>
<h3 className="text-xl font-medium text-gray-900 mb-2">
暂无可用模板
</h3>
<p className="text-gray-500 text-center max-w-sm mb-8">
您可以选择创建一个自定义模块开始使用
</p>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => handleCreateCustom(add, fieldsLength)}
size="large"
className="shadow-md hover:shadow-lg transition-shadow"
>
创建自定义模块
</Button>
</div>
)}
</div>
);
// 修改项目小计的计算,将其封装为 memo 组件
const ItemSubtotal = React.memo(({ quantity, price, currentCurrency }) => {
const subtotal = useMemo(() => {
const safeQuantity = Number(quantity) || 0;
@@ -273,7 +329,6 @@ const SectionList = ({
);
});
// 修改小节总计的计算,将其封装为 memo 组件
const SectionTotal = React.memo(({ items, currentCurrency }) => {
const total = useMemo(() => {
if (!Array.isArray(items)) return 0;
@@ -281,7 +336,7 @@ const SectionList = ({
if (!item) return sum;
const safeQuantity = Number(item.quantity) || 0;
const safePrice = Number(item.price) || 0;
return sum + (safeQuantity * safePrice);
return sum + safeQuantity * safePrice;
}, 0);
}, [items]);
@@ -302,11 +357,11 @@ const SectionList = ({
<Form.List name="sections">
{(fields, { add, remove }) => (
<>
<div className="space-y-4">
<div className="space-y-4 overflow-auto">
{fields.map((field, sectionIndex) => (
<Card
key={field.key}
className="shadow-sm rounded-lg"
className="shadow-sm rounded-lg min-w-[1000px]"
type="inner"
title={
<div className="flex items-center justify-between">
@@ -315,7 +370,9 @@ const SectionList = ({
<div className="flex items-center gap-2">
<Input
value={editingSectionName}
onChange={(e) => setEditingSectionName(e.target.value)}
onChange={(e) =>
setEditingSectionName(e.target.value)
}
onPressEnter={handleSectionNameSave}
autoFocus
className="w-48"
@@ -331,7 +388,7 @@ const SectionList = ({
icon={<CloseOutlined />}
onClick={() => {
setEditingSectionIndex(null);
setEditingSectionName('');
setEditingSectionName("");
}}
className="text-red-500"
/>
@@ -340,17 +397,26 @@ const SectionList = ({
<div className="flex items-center gap-2">
<span className="w-1 h-4 bg-purple-500 rounded-full" />
<Text strong className="text-lg">
{form.getFieldValue(['sections', sectionIndex, 'sectionName'])
|| `服务类型 ${sectionIndex + 1}`}
{form.getFieldValue([
"sections",
sectionIndex,
"sectionName",
]) || `服务类型 ${sectionIndex + 1}`}
</Text>
{!isView && (
<Button
type="link"
icon={<EditOutlined />}
onClick={() => handleSectionNameEdit(
onClick={() =>
handleSectionNameEdit(
sectionIndex,
form.getFieldValue(['sections', sectionIndex, 'sectionName'])
)}
form.getFieldValue([
"sections",
sectionIndex,
"sectionName",
])
)
}
className="text-gray-400 hover:text-blue-500"
/>
)}
@@ -368,11 +434,9 @@ const SectionList = ({
</div>
}
>
{/* 项目列表 */}
<Form.List name={[field.name, "items"]}>
{(itemFields, { add: addItem, remove: removeItem }) => (
<>
{/* 表头 */}
<div className="grid grid-cols-[3fr_4fr_1fr_1fr_2fr_1fr_40px] gap-4 mb-2 text-gray-500 px-2">
<div>项目明细</div>
<div>描述/备注</div>
@@ -383,7 +447,6 @@ const SectionList = ({
<div></div>
</div>
{/* 项目列表 */}
{itemFields.map((itemField, itemIndex) => (
<div
key={itemField.key}
@@ -413,9 +476,10 @@ const SectionList = ({
loading={loadingUnits}
showSearch
allowClear
options={units.map(unit => ({
style={{ minWidth: "120px" }}
options={units.map((unit) => ({
label: unit.attributes.name,
value: unit.attributes.name
value: unit.attributes.name,
}))}
onDropdownVisibleChange={(open) => {
if (open) fetchUnits();
@@ -423,48 +487,32 @@ const SectionList = ({
dropdownRender={(menu) => (
<>
{menu}
<Divider style={{ margin: '8px 0' }} />
<Select.Option value="ADD_NEW">
<Button
type="text"
icon={<PlusOutlined />}
block
onClick={(e) => {
e.stopPropagation();
Modal.confirm({
title: '新增单位',
content: (
<Input
placeholder="请输入单位名称"
onChange={(e) => {
Modal.confirm.update({
okButtonProps: {
disabled: !e.target.value.trim()
}
});
}}
ref={(input) => {
if (input) {
setTimeout(() => input.focus(), 100);
<Divider style={{ margin: "12px 0" }} />
<div style={{ padding: "4px" }}>
<Input.Search
placeholder="输入新单位名称"
enterButton={<PlusOutlined />}
onSearch={async (value) => {
if (!value.trim()) return;
if (
await handleAddUnit(value.trim())
) {
const currentItems =
form.getFieldValue([
"sections",
field.name,
"items",
]);
currentItems[itemField.name].unit =
value.trim();
form.setFieldValue(
["sections", field.name, "items"],
currentItems
);
}
}}
/>
),
onOk: async (close) => {
const unitName = document.querySelector('.ant-modal-content input').value.trim();
if (await handleAddUnit(unitName)) {
const currentItems = form.getFieldValue(['sections', field.name, 'items']);
currentItems[itemField.name].unit = unitName;
form.setFieldValue(['sections', field.name, 'items'], currentItems);
close();
}
}
});
}}
>
新增单位
</Button>
</Select.Option>
</div>
</>
)}
/>
@@ -474,18 +522,34 @@ const SectionList = ({
name={[itemField.name, "quantity"]}
className="!mb-0"
>
<InputNumber placeholder="数量" min={0} className="w-full" />
<InputNumber
placeholder="数量"
min={0}
className="w-full"
/>
</Form.Item>
<Form.Item
{...itemField}
name={[itemField.name, "price"]}
className="!mb-0"
>
<InputNumber placeholder="单价" min={0} className="w-full" />
<InputNumber
placeholder="单价"
min={0}
className="w-full"
/>
</Form.Item>
<ItemSubtotal
quantity={formValues?.sections?.[sectionIndex]?.items?.[itemIndex]?.quantity}
price={formValues?.sections?.[sectionIndex]?.items?.[itemIndex]?.price}
quantity={
formValues?.sections?.[sectionIndex]?.items?.[
itemIndex
]?.quantity
}
price={
formValues?.sections?.[sectionIndex]?.items?.[
itemIndex
]?.price
}
currentCurrency={currentCurrency}
/>
{!isView && itemFields.length > 1 && (
@@ -555,4 +619,5 @@ const SectionList = ({
);
};
export default SectionList;

View File

@@ -18,16 +18,12 @@ import {
ArrowLeftOutlined,
SaveOutlined,
DeleteOutlined,
CloseOutlined,
EditOutlined,
CheckOutlined,
} from "@ant-design/icons";
import { supabase } from "@/config/supabase";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
const { TextArea } = Input;
const { Title, Text } = Typography;
import SectionList from '@/components/SectionList'
const { Title } = Typography;
// 添加货币符号映射
const CURRENCY_SYMBOLS = {
@@ -47,7 +43,7 @@ const QuotationForm = () => {
const [dataSource, setDataSource] = useState([{ id: Date.now() }]);
const [totalAmount, setTotalAmount] = useState(0);
const [loading, setLoading] = useState(false);
const [currentCurrency, setCurrentCurrency] = useState("CNY");
const [currentCurrency, setCurrentCurrency] = useState("TWD");
const [customers, setCustomers] = useState([]);
const [selectedCustomers, setSelectedCustomers] = useState([]);
const [formValues, setFormValues] = useState({});
@@ -737,304 +733,28 @@ const QuotationForm = () => {
</div>
</Card>
{/* 报价单细卡片 */}
<Form.List name="sections">
{(fields, { add, remove }) => (
<>
<div className="space-y-4">
{fields.map((field, sectionIndex) => (
<Card
key={`section-${field.key}`}
className="shadow-sm rounded-lg"
type="inner"
title={
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{editingSectionIndex === sectionIndex ? (
<div className="flex items-center gap-2">
<Input
value={editingSectionName}
onChange={(e) =>
setEditingSectionName(e.target.value)
}
onPressEnter={handleSectionNameSave}
autoFocus
className="w-48"
/>
<Button
type="link"
icon={<CheckOutlined />}
onClick={handleSectionNameSave}
className="text-green-500 hover:text-green-600"
/>
<Button
type="link"
icon={<CloseOutlined />}
onClick={handleSectionNameCancel}
className="text-red-500 hover:text-red-600"
/>
</div>
) : (
<div className="flex items-center gap-2">
<span className="w-1 h-4 bg-purple-500 rounded-full" />
<Text
strong
className="text-lg dark:text-gray-200"
>
{form.getFieldValue([
"sections",
sectionIndex,
"sectionName",
]) || `服务类<EFBFBD><EFBFBD> ${sectionIndex + 1}`}
</Text>
{(!id || isEdit) && (
<Button
type="link"
icon={<EditOutlined />}
onClick={() =>
handleSectionNameEdit(
sectionIndex,
form.getFieldValue([
"sections",
sectionIndex,
"sectionName",
]) || `服务类型 ${sectionIndex + 1}`
)
}
className="text-gray-400 hover:text-blue-500"
/>
)}
</div>
)}
</div>
</div>
}
>
<Form.List name={[field.name, "items"]}>
{(itemFields, { add: addItem, remove: removeItem }) => (
<>
{/* 表头 */}
<div className="grid grid-cols-[3fr_4fr_1fr_1fr_2fr_1fr_40px] gap-4 mb-2 text-gray-500 px-2">
<div>项目明细</div>
<div>描述/备注</div>
<div>单位</div>
<div className="text-center">数量</div>
<div className="text-center">单价</div>
<div className="text-right">小计</div>
<div>操作</div>
</div>
{itemFields.map((itemField, itemIndex) => (
<div
key={`${sectionIndex}-${itemIndex}`}
className="grid grid-cols-[3fr_4fr_1fr_1fr_2fr_1fr_40px] gap-4 mb-4 items-start"
>
<Form.Item
{...itemField}
name={[itemField.name, "productName"]}
className="!mb-0"
>
<Input placeholder="服务项目名称" />
</Form.Item>
<Form.Item
{...itemField}
name={[itemField.name, "note"]}
className="!mb-0"
>
<Input placeholder="请输入描述/备注" />
</Form.Item>
<Form.Item
{...itemField}
name={[itemField.name, "unit"]}
className="!mb-0"
>
<Input placeholder="单位" />
</Form.Item>
<Form.Item
{...itemField}
name={[itemField.name, "quantity"]}
className="!mb-0"
>
<InputNumber
placeholder="数量"
min={0}
className="w-full"
/>
</Form.Item>
<Form.Item
{...itemField}
name={[itemField.name, "price"]}
className="!mb-0"
>
<InputNumber
placeholder="单价"
min={0}
className="w-full"
/>
</Form.Item>
<div className="text-right">
<span className="text-gray-500">
{formatCurrency(
calculateItemAmount(
formValues?.sections?.[sectionIndex]
?.items?.[itemIndex]?.quantity,
formValues?.sections?.[sectionIndex]
?.items?.[itemIndex]?.price
)
)}
</span>
</div>
{!isView && (
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={() => removeItem(itemField.name)}
className="flex items-center justify-center"
/>
)}
</div>
))}
{!isView && (
<Button
type="dashed"
onClick={() =>
handleAddItem(addItem, sectionIndex)
}
icon={<PlusOutlined />}
className="w-full hover:border-blue-400 hover:text-blue-500 mb-4"
>
添加服务项目
</Button>
)}
<div className="flex justify-end border-t pt-4">
<span className="text-gray-500">
小计总额
<span className="text-blue-500 font-medium ml-2">
{formatCurrency(
calculateSectionTotal(
formValues?.sections?.[sectionIndex]
?.items
)
)}
</span>
</span>
</div>
</>
)}
</Form.List>
</Card>
))}
</div>
{/* Add section button */}
{!isView && (
<div className="mt-6 flex justify-center">
<Button
type="dashed"
onClick={handleAddSection}
icon={<PlusOutlined />}
className="w-1/3 border-2 hover:border-blue-400 hover:text-blue-500"
>
新建小节
</Button>
</div>
)}
{/* 总金额统计 */}
<div className="mt-6 space-y-4 pt-4 border-t">
<div className="flex justify-end items-center space-x-4">
<span className="text-gray-600 font-medium">税前总计:</span>
<span className="text-2xl font-semibold text-blue-600">
{formatCurrency(calculateTotalAmount(formValues?.sections))}
</span>
</div>
<div className="flex justify-end items-center space-x-4">
<span className="text-gray-600">税率:</span>
<div style={{ width: '150px' }}>
<Input
value={taxRate}
suffix="%"
onChange={(e) => {
const value = e.target.value.replace(/[^\d]/g, '');
setTaxRate(Number(value) || 0);
}}
/>
</div>
</div>
<div className="flex justify-end items-center space-x-4">
<span className="text-gray-600 font-medium">税后总计:</span>
<span className="text-xl font-semibold text-blue-600">
{formatCurrency(afterTaxAmount)}
</span>
</div>
<div className="flex justify-end items-center space-x-4">
<span className="text-gray-600">折扣价:</span>
<div style={{ width: '150px' }}>
<Input
value={discount}
prefix={CURRENCY_SYMBOLS[currentCurrency]}
onChange={(e) => {
const value = e.target.value.replace(/[^\d]/g, '');
setDiscount(Number(value) || 0);
}}
/>
</div>
</div>
<div className="flex justify-end items-center space-x-4">
<span className="text-gray-600 font-medium">最终金额:</span>
<span className="text-2xl font-semibold text-blue-600">
{formatCurrency(discount || afterTaxAmount)}
</span>
</div>
</div>
<Card
className="shadow-sm rounded-lg"
type="inner"
title={
<span className="flex items-center space-x-2 text-gray-700">
<span className="w-1 h-4 bg-purple-500 rounded-full" />
<span>补充说明</span>
<span className="w-1 h-4 bg-blue-500 rounded-full" />
<span>服务明细</span>
</span>
}
bordered={false}
>
<Form.Item name="description" className="mb-0">
<TextArea
rows={4}
placeholder="请输入补充说明信息"
className="rounded-md hover:border-purple-400 focus:border-purple-500"
<SectionList
type="quotation"
form={form}
isView={isView}
formValues={formValues}
currentCurrency={currentCurrency}
/>
</Form.Item>
</Card>
</>
)}
</Form.List>
</Form>
</Card>
<Modal
title={
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">
选择小节模版
</h3>
}
open={templateModalVisible}
onCancel={() => setTemplateModalVisible(false)}
footer={null}
width={800}
className="dark:bg-gray-800"
closeIcon={
<CloseOutlined className="text-gray-500 dark:text-gray-400" />
}
>
{renderTemplateModalContent()}
</Modal>
</div>
);
};

View File

@@ -354,7 +354,8 @@ const QuotationPage = () => {
<AppstoreOutlined /> 使用选中模板
</Button>,
]}
width={800}
width={900}
className="template-modal dark:bg-gray-800"
>
{loading ? (
<div className="flex justify-center items-center h-[400px]">
@@ -363,63 +364,74 @@ const QuotationPage = () => {
) : templates.length === 0 ? (
<Empty description="暂无可用模板" />
) : (
<div className="max-h-[600px] overflow-y-auto px-1">
<div className="max-h-[600px] overflow-y-auto px-2">
{getTemplatesByCategory().map((group, groupIndex) => (
<div key={groupIndex} className="mb-6 last:mb-2">
<div className="flex items-center gap-2 mb-3">
<div className="h-6 w-1 bg-blue-500 rounded-full"></div>
<h3 className="text-base font-medium text-gray-700">
<div key={groupIndex} className="mb-8 last:mb-2">
<div className="flex items-center gap-3 mb-4">
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">
{group.name}
<span className="ml-2 text-sm text-gray-400 font-normal">
<span className="ml-2 text-sm text-gray-500 dark:text-gray-400">
({group.templates.length})
</span>
</h3>
</div>
<div className="grid grid-cols-3 gap-3">
<div className="grid grid-cols-3 gap-4">
{group.templates.map(template => (
<div
key={template.id}
className={`
p-3 border rounded-lg cursor-pointer transition-all
${selectedTemplateId === template.id
? 'border-blue-500 bg-blue-50/50'
: 'border-gray-200 hover:border-blue-300 hover:bg-gray-50/50'
}
`}
onClick={() => handleTemplateSelect(template.id)}
className={`
relative p-4 rounded-xl cursor-pointer transition-all duration-200
${
selectedTemplateId === template.id
? 'ring-2 ring-blue-500 bg-blue-50/40 dark:bg-blue-900/40'
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50 border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-md'
}
dark:bg-gray-800
`}
>
<div className="flex justify-between items-start gap-2 mb-2">
<div className="flex justify-between items-start gap-3 mb-3">
<div className="flex-1 min-w-0">
<h4 className="font-medium text-gray-800 truncate">
<h4 className="text-base font-medium text-gray-900 dark:text-gray-100 truncate">
{template.attributes.templateName}
</h4>
<p className="text-xs text-gray-500 mt-1 line-clamp-1">
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1 line-clamp-2">
{template.attributes.description || '暂无描述'}
</p>
</div>
<span className="text-red-500 font-medium whitespace-nowrap text-sm">
<div className="text-blue-600 dark:text-blue-400 font-medium whitespace-nowrap">
¥{template.attributes.totalAmount?.toLocaleString()}
</span>
</div>
</div>
<div className="space-y-1">
<div className="space-y-2">
{template.attributes.sections.map((section, index) => (
<div
key={index}
className="bg-white/80 px-2 py-1 rounded text-xs border border-gray-100"
className="bg-white dark:bg-gray-700 rounded-lg p-2.5 text-sm border border-gray-100 dark:border-gray-600"
>
<div className="flex justify-between items-center">
<span className="font-medium text-blue-600 truncate flex-1">
<span className="font-medium text-gray-700 dark:text-gray-200 truncate flex-1">
{section.sectionName}
</span>
<span className="text-gray-400 ml-1">
<span className="text-gray-500 dark:text-gray-400 ml-2 text-xs">
{section.items.length}
</span>
</div>
</div>
))}
</div>
{selectedTemplateId === template.id && (
<div className="absolute top-3 right-3">
<div className="w-5 h-5 bg-blue-500 dark:bg-blue-600 rounded-full flex items-center justify-center">
<svg className="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
<path d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" />
</svg>
</div>
</div>
)}
</div>
))}
</div>

View File

@@ -31,7 +31,6 @@ const QuotationTemplate = ({ id, isView, onCancel,isEdit }) => {
'attributes->>template_type': { eq: TYPE }
}
});
console.log(data,'data');
if (data?.[0]) {
const formData = {

View File

@@ -38,7 +38,7 @@ const ServiceForm = () => {
}
return (
<div className="bg-gradient-to-b from-gray-50 to-white dark:from-gray-800 dark:to-gray-900/90 min-h-screen p-2">
<div className="bg-gradient-to-b from-gray-50 to-white dark:from-gray-800 dark:to-gray-900/90 min-h-screen p-2" >
<Card
className="shadow-lg rounded-lg border-0"
title={

View File

@@ -42,7 +42,8 @@ const ResourceManagement = () => {
onChange={setActiveType}
type="card"
className="bg-white rounded-lg shadow-sm"
items={TEMPLATE_TYPES.map(type => ({
items={TEMPLATE_TYPES.map(type => {
return ({
key: type.key,
label: (
<span className="flex items-center gap-2">
@@ -55,10 +56,12 @@ const ResourceManagement = () => {
<Card>
<Classify typeList={filterOption} activeType={activeType} setActiveType={setActiveType} />
<Unit typeList={filterOption} activeType={activeType} />
<Sections typeList={filterOption} activeType={activeType} />
</Card>
</div>
)
}))}
});
})}
/>

View File

@@ -1,127 +1,127 @@
import React, { useState, useEffect } from 'react';
import { Table, Button, Drawer, Modal, Form, Input, InputNumber, Space, message, Popconfirm, Select } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { supabase } from '@/config/supabase';
import {
Table,
Button,
Form,
Input,
Space,
message,
Popconfirm,
Select,
Segmented,
InputNumber,
Card,
Typography
} from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { supabaseService } from '@/hooks/supabaseService';
import { v4 as uuidv4 } from 'uuid';
const SectionManagement = () => {
const { Text } = Typography;
const SectionsManagement = ({ activeType = 'quotation', typeList }) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [drawerVisible, setDrawerVisible] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [editingRecord, setEditingRecord] = useState(null);
const [editingKey, setEditingKey] = useState('');
const [form] = Form.useForm();
const [units, setUnits] = useState([]);
const [filterType, setFilterType] = useState('all');
// 获取子模块数据
const fetchSections = async () => {
const fetchSections = async (type = activeType, filterTypeValue = filterType) => {
setLoading(true);
try {
const { data: sections, error } = await supabase
.from('resources')
.select('*')
.eq('type', 'sections');
let filterCondition;
switch (filterTypeValue) {
case 'current':
filterCondition = { eq: type };
break;
default:
filterCondition = { eq: type };
}
const { data: sections } = await supabaseService.select('resources', {
filter: {
'type': { eq: 'sections' },
'attributes->>template_type': filterCondition
},
order: {
column: 'created_at',
ascending: false
}
});
if (error) throw error;
setData(sections || []);
} catch (error) {
message.error('获取模块数据失败');
message.error('获取模块数据失败');
console.error(error);
} finally {
setLoading(false);
}
};
// 获取单位数据
const fetchUnits = async () => {
try {
const { data: unitsData, error } = await supabase
.from('resources')
.select('*')
.eq('type', 'units')
.order('created_at', { ascending: false });
if (error) throw error;
setUnits(unitsData || []);
} catch (error) {
message.error('获取单位数据失败');
console.error(error);
}
};
useEffect(() => {
if (drawerVisible) {
fetchSections();
}
fetchUnits();
}, [drawerVisible]);
fetchSections(activeType, filterType);
}, [activeType]);
// 打开新增/编辑模态框
const showModal = async (record = null) => {
setModalVisible(true);
setEditingRecord(record);
if (record) {
try {
const { data: section, error } = await supabase
.from('resources')
.select('*')
.eq('id', record.id)
.single();
if (error) throw error;
form.setFieldsValue({
name: section.attributes.name,
items: section.attributes.items
});
} catch (error) {
message.error('获取子模块详情失败');
console.error(error);
}
} else {
form.setFieldsValue({
const handleAdd = () => {
const newData = {
id: Date.now().toString(),
attributes: {
name: '',
items: [{ name: '', description: '', price: 0, quantity: 1, unit: '' }]
});
}
template_type: activeType,
items: [{
key: uuidv4(),
name: '',
description: '',
quantity: 1,
price: 0,
unit: ''
}]
},
isNew: true
};
setData([newData, ...data]);
setEditingKey(newData.id);
form.setFieldsValue(newData.attributes);
};
// 保存子模块数据
const handleSave = async (values) => {
const handleSave = async (record) => {
try {
if (editingRecord) {
// 更新
const { error } = await supabase
.from('resources')
.update({
attributes: {
name: values.name,
items: values.items
},
updated_at: new Date().toISOString()
})
.eq('id', editingRecord.id);
const values = await form.validateFields();
const items = form.getFieldValue(['items']) || [];
if (error) throw error;
} else {
// 新增
const { error } = await supabase
.from('resources')
.insert([{
// 验证items数组
if (!items.length || !items.some(item => item.name)) {
message.error('请至少添加一个有效的服务项目');
return;
}
if (record.isNew) {
await supabaseService.insert('resources', {
type: 'sections',
attributes: {
name: values.name,
items: values.items
template_type: activeType,
items: items.filter(item => item.name), // 只保存有名称的项目
},
schema_version: 1
}]);
if (error) throw error;
});
} else {
await supabaseService.update('resources',
{ id: record.id },
{
attributes: {
name: values.name,
template_type: activeType,
items: items.filter(item => item.name),
},
updated_at: new Date().toISOString()
}
);
}
message.success('保存成功');
setModalVisible(false);
form.resetFields();
setEditingKey('');
fetchSections();
} catch (error) {
message.error('保存失败');
@@ -129,15 +129,9 @@ const SectionManagement = () => {
}
};
// 删除子模块
const handleDelete = async (id) => {
const handleDelete = async (record) => {
try {
const { error } = await supabase
.from('resources')
.delete()
.eq('id', id);
if (error) throw error;
await supabaseService.delete('resources', { id: record.id });
message.success('删除成功');
fetchSections();
} catch (error) {
@@ -146,290 +140,226 @@ const SectionManagement = () => {
}
};
const drawerColumns = [
const columns = [
{
title: '项目名称',
dataIndex: 'name',
},
{
title: '描述',
dataIndex: 'description',
},
{
title: '单价',
dataIndex: 'price',
render: (price) => `¥${price}`
},
{
title: '数量',
dataIndex: 'quantity',
},
{
title: '单位',
dataIndex: 'unit',
}
];
// 添加模态框内表格列定义
const modalColumns = [
{
title: '项目名称',
dataIndex: 'name',
render: (_, __, index) => (
title: '模块名称',
dataIndex: ['attributes', 'name'],
width: 200,
render: (text, record) => {
const isEditing = record.id === editingKey;
return isEditing ? (
<Form.Item
name={[index, 'name']}
name="name"
style={{ margin: 0 }}
rules={[{ required: true, message: '请输入模块名称!' }]}
>
<Input
placeholder="请输入模块名称"
className="rounded-md"
/>
</Form.Item>
) : (
<span className="text-gray-700 font-medium">{text}</span>
);
},
},
{
title: '服务项目',
dataIndex: ['attributes', 'items'],
render: (items, record) => {
const isEditing = record.id === editingKey;
if (isEditing) {
return (
<Form.List name="items">
{(fields, { add, remove }) => (
<div className="space-y-2">
{fields.map((field, index) => (
<Card key={field.key} size="small" className="bg-gray-50">
<div className="grid grid-cols-6 gap-2">
<Form.Item
{...field}
name={[field.name, 'name']}
className="col-span-2 mb-0"
>
<Input placeholder="项目名称" />
</Form.Item>
)
},
{
title: '描述',
dataIndex: 'description',
render: (_, __, index) => (
<Form.Item
name={[index, 'description']}
style={{ margin: 0 }}
{...field}
name={[field.name, 'unit']}
className="mb-0"
>
<Input placeholder="描述" />
<Input placeholder="单位" />
</Form.Item>
)
},
{
title: '单价',
dataIndex: 'price',
render: (_, __, index) => (
<Form.Item
name={[index, 'price']}
rules={[{ required: true, message: '请输入单价!' }]}
style={{ margin: 0 }}
{...field}
name={[field.name, 'quantity']}
className="mb-0"
>
<InputNumber
min={0}
placeholder="单价"
className="w-full"
/>
</Form.Item>
)
},
{
title: '数量',
dataIndex: 'quantity',
render: (_, __, index) => (
<Form.Item
name={[index, 'quantity']}
rules={[{ required: true, message: '请输入数量!' }]}
style={{ margin: 0 }}
>
<InputNumber
min={1}
placeholder="数量"
min={0}
className="w-full"
/>
</Form.Item>
)
},
{
title: '单位',
dataIndex: 'unit',
render: (_, __, index) => (
<Form.Item
name={[index, 'unit']}
rules={[{ required: true, message: '请选择或输入单位!' }]}
style={{ margin: 0 }}
{...field}
name={[field.name, 'price']}
className="mb-0"
>
<Select
placeholder="请选择或输入单位"
<InputNumber
placeholder="单价"
min={0}
className="w-full"
showSearch
allowClear
options={units.map(unit => ({
label: unit.attributes.name,
value: unit.attributes.name
}))}
filterOption={(input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
}
/>
</Form.Item>
)
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={() => remove(field.name)}
className="flex items-center justify-center"
/>
</div>
</Card>
))}
<Button
type="dashed"
onClick={() => add({
key: uuidv4(),
name: '',
unit: '',
quantity: 1,
price: 0
})}
className="w-full"
>
<PlusOutlined /> 添加服务项目
</Button>
</div>
)}
</Form.List>
);
}
return (
<div className="space-y-1">
{(items || []).map((item, index) => (
<div key={index} className="flex justify-between text-sm">
<span className="text-gray-600">{item.name}</span>
<span className="text-gray-500">
{item.quantity} {item.unit} × ¥{item.price}
</span>
</div>
))}
</div>
);
},
},
{
title: '操作',
render: (_, __, index, { remove }) => (
<Button
type="link"
danger
icon={<DeleteOutlined />}
onClick={() => remove(index)}
/>
)
}
];
return (
<div>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => setDrawerVisible(true)}
className="flex items-center"
>
子模块管理
</Button>
<Drawer
title={
<span className="text-lg font-medium text-gray-800 dark:text-gray-200">
子模块管理
</span>
}
placement="right"
width={1000}
onClose={() => setDrawerVisible(false)}
open={drawerVisible}
className="dark:bg-gray-800"
>
<div className="flex flex-col h-full">
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => showModal()}
className="mb-4 w-32 flex items-center justify-center"
>
新增子模块
</Button>
<div className="space-y-6">
{data.map((section) => (
<div
key={section.id}
className="bg-white rounded-lg shadow-sm dark:bg-gray-800 border border-gray-200 dark:border-gray-700"
>
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
<h3 className="text-lg font-medium text-gray-800 dark:text-gray-200">
{section.attributes.name}
</h3>
width: 160,
fixed: 'right',
render: (_, record) => {
const isEditing = record.id === editingKey;
return isEditing ? (
<Space>
<Button
type="link"
icon={<EditOutlined />}
onClick={() => showModal(section)}
className="text-blue-600 hover:text-blue-500"
className="text-green-600 hover:text-green-500 font-medium"
onClick={() => handleSave(record)}
>
保存
</Button>
<Button
type="link"
className="text-gray-600 hover:text-gray-500 font-medium"
onClick={() => {
setEditingKey('');
if (record.isNew) {
setData(data.filter(item => item.id !== record.id));
}
}}
>
取消
</Button>
</Space>
) : (
<Space>
<Button
type="link"
className="text-blue-600 hover:text-blue-500 font-medium"
disabled={editingKey !== ''}
onClick={() => {
setEditingKey(record.id);
form.setFieldsValue({
name: record.attributes.name,
items: record.attributes.items
});
}}
>
编辑
</Button>
<Popconfirm
title="确定要删除吗?"
onConfirm={() => handleDelete(section.id)}
title="确认删除"
description="确定要删除这个模块吗?"
onConfirm={() => handleDelete(record)}
okText="确定"
cancelText="取消"
okButtonProps={{
className: "bg-red-500 hover:bg-red-600 border-red-500"
}}
>
<Button
type="link"
danger
icon={<DeleteOutlined />}
className="text-red-600 hover:text-red-500"
/>
className="text-red-600 hover:text-red-500 font-medium"
disabled={editingKey !== ''}
>
删除
</Button>
</Popconfirm>
</Space>
</div>
<div className="p-4">
<Table
scroll={{ x: true }}
dataSource={section.attributes.items}
columns={drawerColumns}
pagination={false}
rowKey={(record, index) => `${section.id}-${index}`}
className="border dark:border-gray-700 rounded-lg"
rowClassName="hover:bg-gray-50 dark:hover:bg-gray-700/50"
size="small"
/>
</div>
</div>
))}
</div>
</div>
</Drawer>
);
},
},
];
<Modal
title={`${editingRecord ? '编辑' : '新增'}子模块`}
open={modalVisible}
onCancel={() => {
setModalVisible(false);
setEditingRecord(null);
form.resetFields();
}}
footer={null}
width={1200}
destroyOnClose={true}
>
<Form
form={form}
onFinish={handleSave}
layout="vertical"
className="mt-4"
>
<Form.Item
name="name"
label="子模块名称"
rules={[{ required: true, message: '请输入子模块名称!' }]}
>
<Input placeholder="请输入子模块名称" />
</Form.Item>
<Form.List name="items">
{(fields, { add, remove }) => (
<div className="bg-white rounded-lg border dark:bg-gray-800 dark:border-gray-700">
<Table
dataSource={fields}
columns={modalColumns.map(col => ({
...col,
render: (...args) => col.render(...args, { remove })
}))}
pagination={false}
rowKey="key"
className="mb-4"
/>
<div className="p-4 border-t dark:border-gray-700">
return (
<div className="p-6 bg-gray-50">
<div className="bg-white rounded-lg shadow-sm mb-6 p-4">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div className="flex items-center gap-2">
<Button
type="dashed"
onClick={() => add({
name: '',
description: '',
price: 0,
quantity: 1,
unit: ''
})}
type="primary"
onClick={handleAdd}
icon={<PlusOutlined />}
className="w-full hover:border-blue-400 hover:text-blue-500
dark:border-gray-600 dark:text-gray-400 dark:hover:text-blue-400"
className="bg-blue-600 hover:bg-blue-700 border-0 shadow-sm h-10"
>
添加项目
新增模块
</Button>
</div>
</div>
)}
</Form.List>
</div>
<div className="flex justify-end gap-4 mt-6">
<Button onClick={() => {
setModalVisible(false);
setEditingRecord(null);
form.resetFields();
}}>
取消
</Button>
<Button type="primary" htmlType="submit">
保存
</Button>
</div>
<div className="bg-white rounded-lg shadow-sm">
<Form form={form}>
<Table
scroll={{ x: 1200 }}
columns={columns}
dataSource={data}
rowKey="id"
loading={loading}
pagination={{
pageSize: 10,
showTotal: (total) => `${total}`,
className: "px-4"
}}
className="rounded-lg"
/>
</Form>
</Modal>
</div>
</div>
);
};
export default SectionManagement;
export default SectionsManagement;

View File

@@ -79,7 +79,6 @@ export const TeamTable = ({ tableLoading,pagination,dataSource, onTableChange,on
},
{
title: '归属',
dataIndex: 'type',
dataIndex: ["attributes", "type"],
key: "type",
},