Compare commits

..

10 Commits

1
.gitignore vendored

@ -38,4 +38,3 @@ schema*
vonage-client*
**/test
*.bak

@ -1,7 +1,7 @@
{
"name": "global-sales",
"private": true,
"version": "1.5.4",
"version": "1.4.1",
"type": "module",
"scripts": {
"dev": "vite",
@ -13,7 +13,7 @@
"@dckj/react-better-modal": "^0.1.2",
"@lexical/react": "^0.20.0",
"@vonage/client-sdk": "^2.0.0",
"antd": "^5.25.2",
"antd": "^5.22.2",
"dayjs": "^1.11.13",
"dingtalk-jsapi": "^3.0.41",
"emoji-picker-react": "^4.12.0",
@ -21,10 +21,10 @@
"react": "^18.3.1",
"react-chat-elements": "^12.0.17",
"react-dom": "^18.3.1",
"react-router-dom": "^6.30.1",
"react-router-dom": "^6.28.0",
"rxjs": "^7.8.1",
"uuid": "^9.0.1",
"zustand": "^4.5.7"
"zustand": "^4.5.5"
},
"devDependencies": {
"@types/react": "^18.3.12",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M8 19.9967V14.9967H10V19.9967H19V12.9967H5V19.9967H8ZM4 10.9967H20V7.9967H14V3.9967H10V7.9967H4V10.9967ZM3 20.9967V12.9967H2V6.9967C2 6.44442 2.44772 5.9967 3 5.9967H8V2.9967C8 2.44442 8.44772 1.9967 9 1.9967H15C15.5523 1.9967 16 2.44442 16 2.9967V5.9967H21C21.5523 5.9967 22 6.44442 22 6.9967V12.9967H21V20.9967C21 21.549 20.5523 21.9967 20 21.9967H4C3.44772 21.9967 3 21.549 3 20.9967Z"></path></svg>

Before

Width:  |  Height:  |  Size: 491 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M8.58564 8.85449L3.63589 13.8042L8.83021 18.9985L9.99985 18.9978V18.9966H11.1714L14.9496 15.2184L8.58564 8.85449ZM9.99985 7.44027L16.3638 13.8042L19.1922 10.9758L12.8283 4.61185L9.99985 7.44027ZM13.9999 18.9966H20.9999V20.9966H11.9999L8.00229 20.9991L1.51457 14.5113C1.12405 14.1208 1.12405 13.4877 1.51457 13.0971L12.1212 2.49053C12.5117 2.1 13.1449 2.1 13.5354 2.49053L21.3136 10.2687C21.7041 10.6592 21.7041 11.2924 21.3136 11.6829L13.9999 18.9966Z"></path></svg>

Before

Width:  |  Height:  |  Size: 555 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M5 4.9967V7.9967H19V4.9967H5ZM4 2.9967H20C20.5523 2.9967 21 3.44442 21 3.9967V8.9967C21 9.54899 20.5523 9.9967 20 9.9967H4C3.44772 9.9967 3 9.54899 3 8.9967V3.9967C3 3.44442 3.44772 2.9967 4 2.9967ZM6 11.9967H12C12.5523 11.9967 13 12.4444 13 12.9967V15.9967H14V21.9967H10V15.9967H11V13.9967H5C4.44772 13.9967 4 13.549 4 12.9967V10.9967H6V11.9967ZM17.7322 13.7289L19.5 11.9612L21.2678 13.7289C22.2441 14.7052 22.2441 16.2882 21.2678 17.2645C20.2915 18.2408 18.7085 18.2408 17.7322 17.2645C16.7559 16.2882 16.7559 14.7052 17.7322 13.7289Z"></path></svg>

Before

Width:  |  Height:  |  Size: 640 B

@ -12,47 +12,15 @@ import dayjs from 'dayjs';
export const fetchTemplates = async (params) => {
const data = await fetchJSON(`${API_HOST}/listtemplates`, params);
const topName = [
'agent_intro_with_update_v1',
'order_updated_specialist_assigned_sharon',
'online_inquiry_received',
'say_hello_again',
'first_message_for_not_reply',
'order_updated_specialist_assigned_christy',
'order_resumed_specialist_followup_schedule_sharon',
'travel_service_update_v2',
'travel_service_update_v1',
'order_updated_specialist_assigned_sharon',
'first_message_for_not_reply',
// 'free_style_3',
// 'free_style_4',
];
// shouwcase
const scNames = ['trip_planner_showcase', 'showcase_different', 'order_status_updated'];
// 客运
const crNames = [
'notification_of_next_trip_planning',
// 'notification_of_following_up_by_cr_v3',
'notification_of_one_day_before_ending_the_trip_by_cr_v2',
'one_day_after_payment_by_yuni',
'notification_of_status_changed',
'notification_of_one_day_before_ending_the_trip_by_cr','one_day_after_payment_by_customer_relations',
'one_day_before_ending_the_trip_contacted_by_yuni','one_day_before_ending_the_trip_first_time_by_yuni',
'post_booking_confirmation_welcome',
];
const crNamesOmit = [
'birthday_greetings_by_marketing','one_day_before_ending_the_trip_by_marketing',
'introduce_the_voucher_one_day_before_ending_the_trip_by_marketing',
'birthday_greetings_by_customer_relations_0',
'post_trip_voucher_issued',
'account_updated_order_ref',
'post_trip_account_updated_from_cr',
'post_trip_account_updated',
'account_update_birthday',
'post_trip_birthday_reward',
'birthday_greetings_by_customer_relations_2',
'birthday_greetings_by_customer_relations_1',
'notification_of_account_updated_by_cr',
'birthday_greetings_by_customer_relations',
'one_day_before_ending_the_trip_by_customer_relations',
]
const canUseTemplates = (data?.result?.items || [])
.filter((_t) => _t.status === 'APPROVED' && !['say_hello_from_trip_advisor', 'free_style_7', 'free_style_1', 'free_style_2'].includes(_t.name))
.map((ele, i) => ({
@ -60,9 +28,7 @@ export const fetchTemplates = async (params) => {
components_origin: ele.components,
components: groupBy(ele.components, (_c) => _c.type.toLowerCase()),
key: ele.name,
// displayName: ele.name.startsWith('order_updated') ? templatesDisplayNameMap['order_updated']+`_${i}` : templatesDisplayNameMap?.[ele.name] || ele.name,
displayName: templatesDisplayNameMap?.[ele.name] || (ele.name.startsWith('order_updated') ? templatesDisplayNameMap['order_updated']+`_${i}` : ele.name),
displayLanguage: crNamesOmit.includes(ele.name) ? '客运-' : (crNames.includes(ele.name) || ele.name.includes('by_cr')) ? ele.language + '-客运' : scNames.includes(ele.name) ? ele.language + '-示例' : ele.language,
displayName: ele.name.startsWith('order_updated') ? templatesDisplayNameMap['order_updated'] : templatesDisplayNameMap?.[ele.name] || ele.name,
}))
const top2Name = topName.concat(canUseTemplates.filter(_t => _t.name.startsWith('order_updated')).map(_tem => _tem.name));
@ -71,9 +37,7 @@ export const fetchTemplates = async (params) => {
const second = canUseTemplates.filter(_t => _t.name.includes('free_style'));
const secondS = second.sort(sortBy('name'));
const raw = canUseTemplates.filter((_t) => !top2Name.includes(_t.name) && !_t.name.includes('free_style'));
// 剩下的排序
const rawS = sortArrayByOrder(raw, 'name', [...crNames, ...scNames, ...crNamesOmit ]);
return [...top, ...secondS, ...rawS];
return [...top, ...secondS, ...raw];
};
/**
* 上面的模板名称bak
@ -84,14 +48,13 @@ export const fetchTemplates = async (params) => {
*/
const templatesDisplayNameMap = {
'order_updated_specialist_assigned_sharon': 'specialist_followup',
'order_updated_specialist_assigned_christy': 'specialist_followup_1',
'order_updated_specialist_assigned_christy': 'specialist_followup',
'online_inquiry_received': 'online_inquiry_received/say_hello',
'order_resumed_specialist_followup_schedule_sharon': 'order_resumed/specialist_followup',
'order_updated': 'specialist_followup',
'agent_intro_with_update_v1': 'quick_update_v1',
};
export const CONVERSATION_PAGE_SIZE = 100;
export const CONVERSATION_PAGE_SIZE = 50;
/**
*
* @param {object} params { opisn }
@ -121,7 +84,7 @@ export const fetchConversationsList = async (params) => {
customer_name: `${ele.whatsapp_name || ''}`.trim(),
whatsapp_name: `${ele.whatsapp_name || ''}`.trim(),
show_default: ele.conversation_memo || ele.whatsapp_name || ele?.channels?.whatsapp_phone_number || ele?.channels?.phone_number || ele?.channels?.email || '',
// coli_id: ele.COLI_ID,
coli_id: ele.COLI_ID,
top_state: ele.top_state || 0,
}))
return list;

@ -1,36 +1,12 @@
import { fetchJSON, postForm, postJSON } from '@/utils/request';
import { API_HOST, API_HOST_V3, DATE_FORMAT, DATEEND_FORMAT, DATETIME_FORMAT, EMAIL_HOST, EMAIL_HOST_v3 } from '@/config';
import { buildTree, groupBy, isEmpty, objectMapper, omitEmpty, uniqWith } from '@/utils/commons';
import { readIndexDB, writeIndexDB } from '@/utils/indexedDB';
import dayjs from 'dayjs';
import { internalEventEmitter } from '@/utils/EventEmitterService';
import { fetchJSON, postForm } from '@/utils/request';
import { API_HOST, EMAIL_HOST } from '@/config';
export const parseHTMLString = (html, needText = false) => {
const parseHTMLString = (html) => {
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')
let bodyContent = doc.body.innerHTML
// bodyContent = bodyContent.replace(/<img/g, '<img onerror="this.onerror=null;this.src=\'https://hiana-crm.oss-accelerate.aliyuncs.com/WAMedia/afe412d4-3acf-4e79-a623-048aeb4d696a.png\';"')
const bodyText = (doc.body.innerText);
return needText ? { html, bodyContent, bodyText } : bodyContent
}
const bodyContent = doc.body.innerHTML
export const EMAIL_CHANNEL_NAME = 'mailbox_changes';
let emailChangesChannel = null;
export function getEmailChangesChannel() {
if (!emailChangesChannel) {
emailChangesChannel = new BroadcastChannel(EMAIL_CHANNEL_NAME)
}
return emailChangesChannel
}
// 通知邮件列表数据更新
const notifyMailboxUpdate = (payload) => {
const notificationPayload = payload
// - 多个tab
const channel = getEmailChangesChannel()
channel.postMessage(notificationPayload)
// - 当前tab
internalEventEmitter.emit(EMAIL_CHANNEL_NAME, notificationPayload)
return bodyContent
}
/**
@ -41,8 +17,7 @@ export const getSalesSignatureAction = async (params) => {
try {
const { result } = await fetchJSON(`${EMAIL_HOST}/email_sign`, params)
const { SignContent: html } = result
const bodyContent = parseHTMLString(html);
return bodyContent;
return parseHTMLString(html);
} catch (error) {
return '';
}
@ -81,11 +56,10 @@ export const postResendEmailAction = async (body) => {
const encodeEmailInfo = (info) => {
const encodeQuote = (str = '') => str.replace(/"/g, ''); //.replace(/</g,'&lt;').replace(/>/g,'&gt;')
const CSsClean = encodeQuote(info.MAI_CS).includes(',') ? encodeQuote(info.MAI_CS).split(',') : encodeQuote(info.MAI_CS).split(';');
const tosClean = (encodeQuote(info.MAI_To).includes(',') ? encodeQuote(info.MAI_To).split(',') : encodeQuote(info.MAI_To).split(';')).concat(CSsClean).filter(s => s);
const tosClean = encodeQuote(info.MAI_To).includes(',') ? encodeQuote(info.MAI_To).split(',') : encodeQuote(info.MAI_To).split(';');
const replyTo = info.MAI_Direction === 1 ? info.MAI_To : info.MAI_From;
const replyToAll = (tosClean.length > 1) ?
(info.MAI_Direction === 1 ? tosClean.join(',') : [...tosClean, info.MAI_From].join(','))
(info.MAI_Direction === 1 ? tosClean.join(',') : `${tosClean.join(',')}, ${info.MAI_From}`)
: (info.MAI_Direction === 1 ? info.MAI_To : info.MAI_From)
return {
...info,
@ -101,37 +75,10 @@ const encodeEmailInfo = (info) => {
* @param {object} { mai_sn }
*/
export const getEmailDetailAction = async (params) => {
// const cacheKey = params.mai_sn;
// const readCache = await readIndexDB(cacheKey, 'mailinfo', 'mailbox');
// if (!isEmpty(readCache)) { // todo: 除了草稿
// return readCache.data;
// }
const { result } = await fetchJSON(`${EMAIL_HOST}/getmail`, params);
let mailType = result.MailInfo?.[0]?.MAI_ContentType || '';
mailType = mailType === '' && (result.MailContent||'').includes('<html') ? 'text/html' : mailType;
const emailInfo = encodeEmailInfo(result.MailInfo?.[0] || {});
const isFromHub = emailInfo.MAI_From.includes('info@chinahighlights.net');
const delLinefeed = mailType === 'text/html' ? (result.MailContent||'').includes('<html') ? true : false : true;
const cleanContent = (result.MailContent || '').replace(/\r\n/g, delLinefeed ? '' : (isFromHub ? '<br>' : ''));
const { html, bodyContent, bodyText } = mailType === 'text/html' ? parseHTMLString(cleanContent, true) : { html: '', bodyContent: '', bodyText: '' };
const attachments = (isEmpty(result?.AttachList) ? [] : result.AttachList).filter(ele => isEmpty(ele.ATI_ContentID) || ele.ATI_ContentID == '0');
const insideAttachments = (isEmpty(result?.AttachList) ? [] : result.AttachList).filter(ele => !isEmpty(ele.ATI_ContentID) && ele.ATI_ContentID != '0');
const mailType = result.MailInfo?.[0]?.MAI_ContentType || '';
const ret = {
info: { ...encodeEmailInfo(result.MailInfo?.[0] || {}), mailType },
content: mailType === 'text/html' ? html : result.MailContent || '',
abstract: bodyText || result.MailContent || '',
attachments,
insideAttachments,
AttachList: isEmpty(result?.AttachList) ? [] : result.AttachList,
}
// writeIndexDB([{key: cacheKey, data: ret}], 'mailinfo', 'mailbox')
return ret;
return { info: encodeEmailInfo(result.MailInfo?.[0] || {}), content: mailType === 'text/html' ? parseHTMLString((result.MailContent || '').replace(/\r\n/g, '')) : (result.MailContent || ''), attachments: result?.AttachList || [] };
}
export const getEmailOrderAction = async ({ colisn }) => {
@ -169,323 +116,3 @@ export const fetchEmailBindOrderAction = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/mailinfo_bindorder`, params)
return errcode === 0 ? true : false;
}
const todoTypes = {
// 1新订单2WhatsApp未读消息3需一催4需二催5需三催6未处理邮件入境提醒coli_ordertype=7余款提醒coli_ordertype=8
1: '新订单',
2: '未读WhatsApp',
3: '一催',
4: '二催',
5: '三催',
6: '老邮件',
7: '入境提醒',
8: '余款提醒',
}
/**
* 顾问的邮箱目录
* @param {object} params { opi_sn, year, by_start_date, by_success, important, if_want_book, if_thinking }
* @param {boolean} retOrder 是否直接返回订单列表 -- 忽略
*/
export const getEmailDirAction = async (params = { opi_sn: '' }, retOrder=false) => {
const defaultParams = { opi_sn: 0, year: dayjs().year(), by_start_date: -1, by_success: -1, important: -1, if_want_book: -1, if_thinking: -1 }
const { errcode, result } = await fetchJSON(`${API_HOST_V3}/email_dir`, { ...defaultParams, ...params })
const mailboxSort = result //.sort(sortBy('MDR_Order'));
let tree = buildTree(mailboxSort, { key: 'VKey', parent: 'VParent', name: 'VName', iconIndex: 'ImageIndex', rootKeys: [1], ignoreKeys: [-227001, -227002] })
tree = tree.filter((ele) => ele.key !== 1)
const retTree = errcode === 0 ? tree : [];
const orderList = groupBy(result, row => `${row.IsTrue}`)?.['0'] || [];
return retOrder !== false ? orderList : { [`${params.opi_sn}`]: retTree }
};
export const getMailboxCountAction = async (params = { opi_sn: '' }, update = true) => {
const defaultParams = {
opi_sn: 0,
// date1: dayjs().subtract(1, 'year').startOf('year').format(DATE_FORMAT),
date1: dayjs().subtract(180, 'days').format(DATE_FORMAT),
date2: dayjs().format(DATEEND_FORMAT)
}
const { errcode, result } = await fetchJSON(`${API_HOST_V3}/dir_count`, {...defaultParams, ...params})
const ret = errcode !== 0 ? { [`${params.opi_sn}`]: {} } : { [`${params.opi_sn}`]: result }
// 更新数量
if (update !== false) {
const readCacheDir = (await readIndexDB(Number(params.opi_sn), 'dirs', 'mailbox')) || {};
const mailboxDir = isEmpty(readCacheDir) ? [] : readCacheDir.tree.filter(node => node?._raw?.IsTrue === 1);
const _MapDir = new Map(mailboxDir.map((obj) => [obj.key, obj]))
Object.keys(result).map(dirKey => {
_MapDir.set(Number(dirKey), {..._MapDir.get(Number(dirKey)), count: result[dirKey]});
})
const _newToUpdate = Array.from(_MapDir.values());
const _MapRoot = new Map((readCacheDir?.tree || []).map((obj) => [obj.key, obj]))
_newToUpdate.forEach((row) => {
_MapRoot.set(row.key, row)
})
const _newRoot = Array.from(_MapRoot.values())
writeIndexDB([{ ...readCacheDir, key: Number(params.opi_sn), tree: _newRoot }], 'dirs', 'mailbox')
notifyMailboxUpdate({ type: 'dirs', key: Number(params.opi_sn) })
}
return ret;
};
export const getTodoOrdersAction = async (params) => {
const opi_arr = params.opisn.split(',')
const defaultStickyTree = opi_arr.reduce(
(a, ele) => ({
...a,
[ele]: [
{
key: ele + '-today',
title: '今日任务',
getMails: false,
iconIndex: 'star',
children: [],
COLI_SN: 0,
},
{
key: ele + '-todo',
title: '待办任务',
getMails: false,
iconIndex: 'calendar',
children: [],
COLI_SN: 0,
},
// {
// key: ele.OPI_DEI_SN + '-reminder',
// title: '催信',
// getMails: false,iconIndex: 'reminder',
// icon: <BellTwoTone />,
// children: [], COLI_SN: 0,
// },
],
}),
{},
)
const { errcode, result } = await fetchJSON(`${API_HOST}/getwlorder`, params)
// 订单重复时, 取后一个状态, 因此翻转两次
const _result_unique = uniqWith(result.reverse(), (a, b) => a.COLI_SN === b.COLI_SN).reverse();
const orderList = errcode === 0 ? _result_unique : []
const byOPI = groupBy(orderList, 'OPI_SN')
const byState = Object.keys(byOPI).reduce((acc, key) => {
const sticky = groupBy(byOPI[key], (ele) => ([1, 6].includes(ele.coli_ordertype) ? 0 : [2, 3, 4, 5].includes(ele.coli_ordertype) ? 1 : 2))
const treeNode = [
{
key: key + '-today',
title: '今日任务',
getMails: false,
iconIndex: 'star',
_raw: { COLI_SN: 0, IsTrue: 0 },
children: (sticky[0] || []).map((o) => ({
key: `today-${o.COLI_SN}`,
title: `(${todoTypes[o.coli_ordertype] || o.COLI_State}) ${o.COLI_ID}`,
iconIndex: 13,
parent: key + '-today',
parentTitle: '今日任务',
parentIconIndex: 'star',
_raw: { ...o, VKey: o.COLI_SN, VName: o.COLI_ID, VParent: key + '-today', IsTrue: 0, ApplyDate: '', OrderSourceType: 227001, parent: key + '-today' },
})),
},
{
key: key + '-todo',
title: '待办任务',
getMails: false,
iconIndex: 'calendar',
_raw: { COLI_SN: 0, IsTrue: 0 },
children: (sticky[2] || []).map((o) => ({
key: `todo-${o.COLI_SN}`,
title: `(${todoTypes[o.coli_ordertype] || o.COLI_State}) ${o.COLI_ID}`,
iconIndex: 13,
parent: key + '-todo',
parentTitle: '待办任务',
parentIconIndex: 'calendar',
_raw: { ...o, VKey: o.COLI_SN, VName: o.COLI_ID, VParent: key + '-todo', IsTrue: 0, ApplyDate: '', OrderSourceType: 227001, parent: key + '-todo' },
})),
},
...(!isEmpty(sticky[1] || [])
? [
{
key: key + '-reminder',
title: '催信',
getMails: false,
iconIndex: 'reminder',
_raw: { COLI_SN: 0, IsTrue: 0 },
children: (sticky[1] || []).map((o) => ({
key: `reminder-${o.COLI_SN}`,
title: `(${todoTypes[o.coli_ordertype] || o.COLI_State}) ${o.COLI_ID}`,
iconIndex: 13,
parent: key + '-reminder',
parentTitle: '催信',
parentIconIndex: 'reminder',
_raw: { ...o, VKey: o.COLI_SN, VName: o.COLI_ID, VParent: key + '-reminder', IsTrue: 0, ApplyDate: '', OrderSourceType: 227001, parent: key + '-reminder' },
})),
},
]
: []),
]
return { ...acc, [key]: treeNode }
}, defaultStickyTree)
return errcode === 0 ? byState : defaultStickyTree
};
/**
* 获取待办目录和邮箱目录
* @param {object} params { opi_sn, userIdStr }
* @param {number} params.opi_sn
* @param {string} params.userIdStr - 用户ID字符串默认为空
*/
export const getRootMailboxDirAction = async ({ opi_sn = 0, userIdStr = '' } = {}) => {
const [stickyTree, ...mailboxDir] = await Promise.all([
getTodoOrdersAction({ opisn: userIdStr || String(opi_sn), otype: 'today' }),
...(userIdStr.split(',').map(_opi => getEmailDirAction({ opi_sn: _opi }))),
])
const mailBoxCount = await Promise.all(userIdStr.split(',').map(_opi => getMailboxCountAction({ opi_sn: _opi }, false)));
const mailboxDirCountByOPI = mailBoxCount.reduce((a, c) => ({ ...a, ...c, }), {})
const mailboxDirByOPI = mailboxDir.reduce((a, c) => ({ ...a, ...(Object.keys(c).reduce((a, opi) => ({...a, [opi]: c[`${opi}`].map((dir) => ({ ...dir, count: mailboxDirCountByOPI[opi][`${dir.key}`] })) }), {} )) }), {})
const rootTree = Object.keys(stickyTree).map((opi) => ({ key: Number(opi), tree: [...stickyTree[opi], ...(mailboxDirByOPI?.[opi] || [])], treeTimestamp: Date.now() }))
writeIndexDB(rootTree, 'dirs', 'mailbox')
const _mapped = groupBy(rootTree, 'key')
return _mapped[opi_sn]?.[0]?.tree || []
}
/**
* 获取邮件列表
* @usage 邮件目录下的邮件列表
* @usage 订单的邮件列表
*/
export const queryEmailListAction = async ({ opi_sn = '', pagesize = 10, last_id = '', node = {}, } = {}) => {
const _params = {
vkey: 0,
vparent: 0,
order_source_type: 0,
// mai_senddate1: dayjs().subtract(1, 'year').startOf('year').format(DATE_FORMAT),
mai_senddate1: dayjs().subtract(180, 'days').format(DATE_FORMAT),
mai_senddate2: dayjs().format(DATEEND_FORMAT),
...omitEmpty({
...node,
opi_sn,
}),
}
_params.mai_senddate1 = dayjs(_params.mai_senddate1).format(DATE_FORMAT)
const cacheKey = isEmpty(_params.coli_sn) ? `dir-${node.vkey}` : `order-${node.vkey}`;
const { errcode, result } = await fetchJSON(`${API_HOST_V3}/mail_list`, _params)
const ret = errcode === 0 ? result : []
if (!isEmpty(ret)) {
const listids = [...new Set(ret.map(ele => ele.MAI_SN))];
writeIndexDB([{key: cacheKey, data: listids}], 'maillist', 'mailbox')
writeIndexDB(ret.map(ele => ({ data: {...ele, listKey: cacheKey }, key: ele.MAI_SN})), 'listrow', 'mailbox')
}
return ret;
}
export const searchEmailListAction = async ({opi_sn = '', mailboxtype = 'ALL', sender = '', receiver = '', subject = '', content=''}={}) => {
const formData = new FormData()
formData.append('opi_sn', opi_sn)
formData.append('mailboxtype', mailboxtype)
formData.append('sender', sender)
formData.append('receiver', receiver)
formData.append('subject', subject)
// formData.append('content', content)
const { errcode, result } = await postForm(`${API_HOST_V3}/mail_search`, formData)
const ret = errcode === 0 ? result : []
notifyMailboxUpdate({ type: 'maillist-search-result', query: [sender, receiver, subject].filter(s => s).join(' '), data: ret.map(ele => ({...ele, key: ele.MAI_SN, showFolder: true })) })
return ret;
}
const removeFromCurrentList = async (params) => {
const readRow0 = await readIndexDB(params.mai_sn_list[0], 'listrow', 'mailbox')
const listKey = readRow0?.data?.listKey || ''
if (listKey) {
const readCache = await readIndexDB(listKey, 'maillist', 'mailbox')
const updatedMailList = readCache.data.filter((mai_sn) => !params.mai_sn_list.includes(mai_sn))
writeIndexDB([{ key: listKey, data: updatedMailList }], 'maillist', 'mailbox')
notifyMailboxUpdate({ type: 'listrow', listKey, affectKeys: params.mai_sn_list })
}
}
const updateEmailKeyMap = { read: 'MOI_ReadState' };
const updateEmailKeyFun = {
read: async (params) => {
const readCache = await readIndexDB(params.mai_sn_list, 'listrow', 'mailbox')
const updateField = Object.keys(params.set).reduce((a, c) => ({ ...a, [updateEmailKeyMap[c]]: params.set[c] }), {})
writeIndexDB(
params.mai_sn_list.map((ele) => ({ data: { ...(readCache.get(ele)?.data || {}), ...updateField }, key: ele })),
'listrow',
'mailbox',
)
// 通知邮件列表数据更新
const listKey = readCache.get(params.mai_sn_list[0])?.data?.listKey || '';
const notificationPayload = { type: 'listrow', listKey, affectKeys: params.mai_sn_list }
notifyMailboxUpdate(notificationPayload)
},
processed: removeFromCurrentList,
delete: removeFromCurrentList
}
/**
* 更新邮件属性
*/
export const updateEmailAction = async (params = { opi_sn: 0, mai_sn_list: [], set: {} }) => {
if (isEmpty(params.mai_sn_list)) {
throw new Error('没有需要更新的邮件');
}
const { errcode, result } = await postJSON(`${API_HOST_V3}/mail_update`, params)
if (errcode === 0 ) {
for (const [key, value] of Object.entries(params.set)) {
const updateFun = updateEmailKeyFun[key] || (() => {});
updateFun(params)
}
}
getMailboxCountAction({ opi_sn: params.opi_sn });
return errcode === 0 ? result : {}
}
/**
* 获取邮件模板
* @param {object} params - Parameters for the email template request.
* @param {number} [params.coli_sn] - Customer order line item serial number.
* @param {number} [params.lgc] - Language code.
* @param {number} [params.opi_sn] - Order product item serial number.
* @param {string} [params.remind_type] - Type of reminder.
* @param {number} [params.remind_index] - Index of the reminder.
*/
export const getReminderEmailTemplateAction = async (params = { coli_sn: 0, lgc: 1, opi_sn: 0, remind_type: '', remind_index: 0 }) => {
const { errcode, result } = await fetchJSON(`${API_HOST_V3}/reminder_letter`, params)
const { html, bodyContent, bodyText } = parseHTMLString(result?.MailContent, true) ;
return errcode === 0 ? {...result, bodyContent }: {}
}
/**
* 保存邮件草稿
* @param {object} body - The body of the email.
* @param {boolean} [isDraft=false] - Whether the email is a draft.
*/
export const saveEmailDraftOrSendAction = async (body, isDraft = false) => {
const url = isDraft !== false ? `${API_HOST_V3}/email_draft_save` : `${EMAIL_HOST_v3}/sendmail`;
const { attaList=[], atta, content, ...bodyData } = body;
bodyData.ordertype = 227001;
const formData = new FormData();
Object.keys(bodyData).forEach(function (key) {
formData.append(key, bodyData[key] || '');
});
// 附件只传新增的
attaList.filter(ele => !ele.fullPath).forEach(function (item) {
formData.append('attachment', item);
});
const { errcode, result } = await postForm(url, formData);
return errcode === 0 ? (result || {}) : {}
};
/**
* 删除邮件附件
*/
export const deleteEmailAttachmentAction = async (ati_sn_list) => {
const { errcode, result } = await postJSON(`${API_HOST_V3}/mail_attachment_delete`, { ati_sn_list })
return errcode === 0 ? result : {}
};
export const queryHTOrderListAction = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/query_order`, params)
return errcode !== 0 ? [] : result
}
export const queryOPIOrderAction = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/getdvancedwlorder`, params)
return errcode !== 0 ? [] : result
};

@ -1,6 +1,6 @@
.logo {
float: left;
height: 60px;
height: 68px;
margin: 0 6px 0 0;
background: rgba(255, 255, 255, 0.3);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M22 20V7L20 3H4L2 7.00353V20C2 20.5523 2.44772 21 3 21H21C21.5523 21 22 20.5523 22 20ZM4 9H20V19H4V9ZM5.236 5H18.764L19.764 7H4.237L5.236 5ZM15 11H9V13H15V11Z"></path></svg>

Before

Width:  |  Height:  |  Size: 262 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M13.9999 18.9966H20.9999V20.9966H11.9999L8.00229 20.9991L1.51457 14.5113C1.12405 14.1208 1.12405 13.4877 1.51457 13.0971L12.1212 2.49053C12.5117 2.1 13.1449 2.1 13.5354 2.49053L21.3136 10.2687C21.7041 10.6592 21.7041 11.2924 21.3136 11.6829L13.9999 18.9966ZM15.6567 14.5113L19.1922 10.9758L12.8283 4.61185L9.29275 8.14738L15.6567 14.5113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 442 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M8.58564 8.85449L3.63589 13.8042L8.83021 18.9985L9.99985 18.9978V18.9966H11.1714L14.9496 15.2184L8.58564 8.85449ZM9.99985 7.44027L16.3638 13.8042L19.1922 10.9758L12.8283 4.61185L9.99985 7.44027ZM13.9999 18.9966H20.9999V20.9966H11.9999L8.00229 20.9991L1.51457 14.5113C1.12405 14.1208 1.12405 13.4877 1.51457 13.0971L12.1212 2.49053C12.5117 2.1 13.1449 2.1 13.5354 2.49053L21.3136 10.2687C21.7041 10.6592 21.7041 11.2924 21.3136 11.6829L13.9999 18.9966Z"></path></svg>

Before

Width:  |  Height:  |  Size: 555 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12.6512 14.0654L11.6047 20H9.57389L10.9247 12.339L3.51465 4.92892L4.92886 3.51471L20.4852 19.0711L19.071 20.4853L12.6512 14.0654ZM11.7727 7.53009L12.0425 5.99999H10.2426L8.24257 3.99999H19.9999V5.99999H14.0733L13.4991 9.25652L11.7727 7.53009Z"></path></svg>

Before

Width:  |  Height:  |  Size: 347 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M22 13.3414C21.3744 13.1203 20.7013 13 20 13C16.6863 13 14 15.6863 14 19C14 19.7013 14.1203 20.3744 14.3414 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V13.3414ZM12.0606 11.6829L5.64722 6.2377L4.35278 7.7623L12.0731 14.3171L19.6544 7.75616L18.3456 6.24384L12.0606 11.6829ZM21 18H24V20H21V23H19V20H16V18H19V15H21V18Z"></path></svg>

Before

Width:  |  Height:  |  Size: 460 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M22 13H20V7.23792L12.0718 14.338L4 7.21594V19H14V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V13ZM4.51146 5L12.0619 11.662L19.501 5H4.51146ZM21 18H24V20H21V23H19V20H16V18H19V15H21V18Z"></path></svg>

Before

Width:  |  Height:  |  Size: 328 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M22 13.3414C21.3744 13.1203 20.7013 13 20 13C16.6863 13 14 15.6863 14 19C14 19.7013 14.1203 20.3744 14.3414 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V13.3414ZM12.0606 11.6829L5.64722 6.2377L4.35278 7.7623L12.0731 14.3171L19.6544 7.75616L18.3456 6.24384L12.0606 11.6829ZM19 22L15.4645 18.4645L16.8787 17.0503L19 19.1716L22.5355 15.636L23.9497 17.0503L19 22Z"></path></svg>

Before

Width:  |  Height:  |  Size: 504 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M22 14H20V7.23792L12.0718 14.338L4 7.21594V19H14V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V14ZM4.51146 5L12.0619 11.662L19.501 5H4.51146ZM19 22L15.4645 18.4645L16.8787 17.0503L19 19.1716L22.5355 15.636L23.9497 17.0503L19 22Z"></path></svg>

Before

Width:  |  Height:  |  Size: 372 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M18.8032 8.4928C19.4663 8.81764 20.2118 9 21 9C21.3425 9 21.6769 8.96557 22 8.89998V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H16.1C16.0344 3.32311 16 3.65753 16 4C16 5.23672 16.449 6.36857 17.1929 7.24142L12.0606 11.6829L5.64722 6.2377L4.35278 7.7623L12.0731 14.3171L18.8032 8.4928ZM21 7C19.3431 7 18 5.65685 18 4C18 2.34315 19.3431 1 21 1C22.6569 1 24 2.34315 24 4C24 5.65685 22.6569 7 21 7Z"></path></svg>

Before

Width:  |  Height:  |  Size: 539 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M16.1 3C16.0344 3.32311 16 3.65753 16 4C16 4.34247 16.0344 4.67689 16.1 5H4.51146L12.0619 11.662L17.1098 7.14141C17.5363 7.66888 18.0679 8.10787 18.6728 8.42652L12.0718 14.338L4 7.21594V19H20V8.89998C20.3231 8.96557 20.6575 9 21 9C21.3425 9 21.6769 8.96557 22 8.89998V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H16.1ZM21 1C22.6569 1 24 2.34315 24 4C24 5.65685 22.6569 7 21 7C19.3431 7 18 5.65685 18 4C18 2.34315 19.3431 1 21 1Z"></path></svg>

Before

Width:  |  Height:  |  Size: 572 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M5 4.9967V7.9967H19V4.9967H5ZM4 2.9967H20C20.5523 2.9967 21 3.44442 21 3.9967V8.9967C21 9.54899 20.5523 9.9967 20 9.9967H4C3.44772 9.9967 3 9.54899 3 8.9967V3.9967C3 3.44442 3.44772 2.9967 4 2.9967ZM6 11.9967H12C12.5523 11.9967 13 12.4444 13 12.9967V15.9967H14V21.9967H10V15.9967H11V13.9967H5C4.44772 13.9967 4 13.549 4 12.9967V10.9967H6V11.9967ZM17.7322 13.7289L19.5 11.9612L21.2678 13.7289C22.2441 14.7052 22.2441 16.2882 21.2678 17.2645C20.2915 18.2408 18.7085 18.2408 17.7322 17.2645C16.7559 16.2882 16.7559 14.7052 17.7322 13.7289Z"></path></svg>

Before

Width:  |  Height:  |  Size: 640 B

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M13 6V21H11V6H5V4H19V6H13Z"></path></svg>

Before

Width:  |  Height:  |  Size: 130 B

@ -74,11 +74,6 @@ export const replaceTemplateString = (str, replacements) => {
return result;
}
export const whatsappTemplateBtnParamTypesMapped = {
'copy_code': 'coupon_code',
// 'quick_reply': 'payload',
};
/**
* @deprecated 在渲染时处理
*/
@ -231,18 +226,18 @@ export const sentMsgTypeMapped = {
...msg.template,
components: [
...msg.template.components.filter((com) => !['footer', 'buttons'].includes(com.type.toLowerCase())),
// ...(msg.template.components.filter((com) => 'buttons' === com.type.toLowerCase()).length > 0
// ? msg.template.components
// .filter((com) => 'buttons' === com.type.toLowerCase())[0]
// // .buttons.filter((btns) => ! ['phone_number', 'url'].includes( btns.type.toLowerCase()))
// .buttons.filter((btns) => !isEmpty(btns.example)) // 静态按钮不发
// .map((btn, btnI) => ({
// type: 'button',
// sub_type: btn.type.toLowerCase(),
// index: btnI,
// // parameters: [{ text: 'lq1FTtA8', type: 'text' }]
// }))
// : []),
...(msg.template.components.filter((com) => 'buttons' === com.type.toLowerCase()).length > 0
? msg.template.components
.filter((com) => 'buttons' === com.type.toLowerCase())[0]
// .buttons.filter((btns) => ! ['phone_number', 'url'].includes( btns.type.toLowerCase()))
.buttons.filter((btns) => !isEmpty(btns.example)) // 静态按钮不发
.map((btn, btnI) => ({
type: 'button',
sub_type: btn.type.toLowerCase(),
index: btnI,
// parameters: [{ text: 'lq1FTtA8', type: 'text' }]
}))
: []),
],
},
}),
@ -464,47 +459,6 @@ const emailMsgMapped = {
},
}
}
const sessionMsgMapped = {
'session.new': {
getMsg: (result) => {
// sessionItem 是数组
return isEmpty(result?.sessionItem)
? null
: result.sessionItem.map((ele) => ({
...ele,
customer_name: `${ele.whatsapp_name || ''}`.trim(),
whatsapp_name: `${ele.whatsapp_name || ''}`.trim(),
show_default: ele.conversation_memo || ele.whatsapp_name || ele?.channels?.whatsapp_phone_number || ele?.channels?.phone_number || ele?.channels?.email || '',
// coli_id: ele.COLI_ID,
top_state: ele.top_state || 0,
msg_source: 'session',
msg_direction: 'inbound',
}))
},
contentToRender: (contentObj) => null,
contentToUpdate: (msgcontent) => null,
},
'session.updated': {
getMsg: (result) => {
// sessionItem 是数组
return isEmpty(result?.sessionItem)
? []
: result.sessionItem.map((ele) => ({
...ele,
customer_name: `${ele.whatsapp_name || ''}`.trim(),
whatsapp_name: `${ele.whatsapp_name || ''}`.trim(),
show_default: ele.conversation_memo || ele.whatsapp_name || ele?.channels?.whatsapp_phone_number || ele?.channels?.phone_number || ele?.channels?.email || '',
// coli_id: ele.COLI_ID,
top_state: ele.top_state || 0,
msg_source: 'session',
msg_direction: 'inbound',
// last_message: {...ele.last_message, text: { body: ele.last_message?.text_body || '', preview_url: null }},
}))
},
contentToRender: (contentObj) => null,
contentToUpdate: (msgcontent) => null,
},
}
export const msgStatusRenderMapped = {
'accepted': 'waiting', // 'sent', // 接口的发送请求
'sent': 'sent',
@ -541,8 +495,6 @@ export const receivedMsgTypeMapped = {
getMsg: (result) => result,
contentToRender: () => null,
contentToUpdate: (msgcontent) => {
if (isEmpty(msgcontent)) return null;
if (isEmpty(msgcontent.error)) return null;
let apiErrorCode,
apiErrorMsg = '';
const waCode = msgcontent.error.message.match(/\(#(\d+)\)/);
@ -564,7 +516,6 @@ export const receivedMsgTypeMapped = {
},
},
...cloneDeep(emailMsgMapped),
...cloneDeep(sessionMsgMapped),
};
/**
* 消息类型处理, 合并各渠道类型
@ -704,11 +655,6 @@ export const whatsappMsgTypeMapped = {
data: (msg) => ({ id: msg.wamid, text: msg.reaction?.emoji || '' }),
renderForReply: (msg) => ({ id: msg.wamid, message: msg.reaction?.emoji || '' }),
},
button: {
type: 'text', // todo: 后端返回 type='button' button: { payload, text }
data: (msg) => ({ id: msg.wamid, text: msg.button?.payload || msg.button?.text || '' }),
renderForReply: (msg) => ({ id: msg.wamid, message: msg.button?.payload || msg.button?.text || '' }),
},
document: {
type: 'file',
data: (msg) => ({
@ -860,14 +806,14 @@ export const parseRenderMessageList = (messages) => {
msgContent.template = msg.msgtype === 'template' ? { ...msgContent.template, ...template } : {};
// const parseMethod = msgContent.bizType === 'whatsapp' ? cloneDeep(whatsappMsgTypeMapped) : {};
let waCode, waError = '';
if ((msgContent?.status || 'accepted') === 'failed' && (msgContent.errorMessage || msg.errors_code) && msg.msg_direction === 'outbound') {
(waCode = (msgContent.errorMessage || msg.errors_code).match(/\(#(\d+)\)/));
(waError = (whatsappError?.[waCode?.[1]] || whatsappError?.[msgContent.errorCode] || msgContent.errorMessage || whatsappError?.[msg.errors_code]));
if ((msgContent?.status || 'accepted') === 'failed' && msgContent.errorMessage && msg.msg_direction === 'outbound') {
(waCode = msgContent.errorMessage.match(/\(#(\d+)\)/));
(waError = (whatsappError?.[waCode?.[1]] || whatsappError?.[msgContent.errorCode] || msgContent.errorMessage));
if (!isEmpty(msgContent.whatsappApiError)) {
waError = whatsappError?.[msgContent.whatsappApiError.code] || msgContent.whatsappApiError.message;
// waError += `\n[${msgContent.errorCode}] ${whatsappError?.[msgContent.errorCode] || msgContent.errorMessage}`;
}
if ((msgContent.errorMessage || msg.errors_code).includes('Invalid E.146 phone number')) {
if (msgContent.errorMessage.includes('Invalid E.146 phone number')) {
waError = whatsappError.INVALID_PHONE_NUMBER;
}
}
@ -947,7 +893,7 @@ export const whatsappError = {
'100': '参数错误, 请联系技术组',
'FORBIDDEN': '[FORBIDDEN] ',
'4': '[4] 无法连接WhatsApp.\n请稍后重试', // (#4) Application request limit reached
'131026': '[131026] 消息无法投递(未同意WhatsApp 的隐私政策).\n请使用 邮件/个人WhatsApp 联系',
'131026': '[131026] 消息无法投递(未同意WhatsApp 的隐私政策).\n请使用邮件联系',
'131047': '[131047] 会话未激活. \n请使用模板消息💬发送',
'131053': '[131053] 文件上传失败.',
'131048': '[131048] 账户被风控.', // 消息发送太多, 达到垃圾数量限制

@ -2,7 +2,7 @@ import { webSocket } from 'rxjs/webSocket';
import { of, timer, concatMap, EMPTY, takeWhile, concat } from 'rxjs';
import { filter, buffer, map, tap, retryWhen, retry, delay, take, catchError } from 'rxjs/operators';
import { v4 as uuid } from 'uuid';
import { logWebsocket } from '@/utils/indexedDB';
import { logWebsocket } from '@/utils/commons';
export class RealTimeAPI {
constructor(param, onOpenCallback, onCloseCallback, onRetryCallback) {

@ -46,7 +46,7 @@ const DnDModal = ({ children, open, setOpen, onCancel, onMove, onResize, initial
maskClosable={false}
// theme='dark'
// className={'!border !border-solid !border-indigo-500 rounded !p-2' }
titleBarClassName={`!bg-neutral-100 !rounded !rounded-b-none !border-none !p-3 !font-bold !text-slate-600 ${props.titleClassName}`}
titleBarClassName='!bg-neutral-100 !rounded !rounded-b-none !border-none !p-3 !font-bold !text-slate-600'
contentClassName='!p-2'
footerClassName='!p-2'
className={`!rounded-t !rounded-b-none !border !border-solid !shadow-heavy ${props.rootClassName}`}

@ -15,9 +15,7 @@ class ErrorBoundary extends PureComponent {
componentDidCatch(error, info) {
console.error('Sorry, Something went wrong.')
console.error(error)
if (import.meta.env.PROD && window.$pageSpy) {
window.$pageSpy.triggerPlugins('onOfflineLog', 'upload')
}
window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
this.setState({ hasError: true, info: error.message })
}

@ -1,7 +1,7 @@
import Icon from '@ant-design/icons';
import ReplyLineSVG from '@/assets/icons/reply-line.svg?react';
import ReplyAllLineSVG from '@/assets/icons/reply-all-fill.svg?react';
import ReplyAllLineSVG from '@/assets/icons/reply-all-line.svg?react';
import AttachmentLineSVG from '@/assets/icons/attachment-line.svg?react';
import AttachmentFillSVG from '@/assets/icons/attachment-fill.svg?react';
// import ShareForwardFillSVG from '@/assets/icons/share-forward-fill.svg?react';
@ -13,12 +13,6 @@ import SendPlaneLineSVG from '@/assets/icons/send-plane-line.svg?react';
import ResendLineSVG from '@/assets/icons/reset-left-line.svg?react';
import EditLineSVG from '@/assets/icons/quill-pen-line.svg?react';
import MailDownloadLineSVG from '@/assets/icons/mail-download-line.svg?react';
import MailOpenLineSVG from '@/assets/icons/mail-open-line.svg?react';
import MailAddLineSVG from '@/assets/icons/mail-add-line.svg?react';
import MailCheckSVG from '@/assets/icons/mail-check-line.svg?react';
import MailUnreadSVG from '@/assets/icons/mail-unread-line.svg?react';
import MailArchiveSVG from '@/assets/icons/archive-2-line.svg?react';
import TextSVG from '@/assets/icons/text.svg?react';
export const ReplyIcon = (props) => <Icon component={ReplyLineSVG} {...props} />;
@ -33,13 +27,6 @@ export const SendPlaneLineIcon = (props) => <Icon component={SendPlaneLineSVG} {
export const ResendIcon = (props) => <Icon component={ResendLineSVG} {...props} />;
export const EditIcon = (props) => <Icon component={EditLineSVG} {...props} />;
export const MailDownloadIcon = (props) => <Icon component={MailDownloadLineSVG} {...props} />;
export const MailOpenIcon = (props) => <Icon component={MailOpenLineSVG} {...props} />;
export const MailAddloadIcon = (props) => <Icon component={MailAddLineSVG} {...props} />;
export const MailCheckIcon = (props) => <Icon component={MailCheckSVG} {...props} />;
export const MailUnreadIcon = (props) => <Icon component={MailUnreadSVG} {...props} />;
export const MailArchiveIcon = (props) => <Icon component={MailArchiveSVG} {...props} />;
export const TextIcon = (props) => <Icon component={TextSVG} {...props} />;
const WABSvg = () => (
<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' width='16' height='16'>
@ -70,16 +57,6 @@ const Sent = () => (
)
export const SentIcon = (props) => <Icon component={Sent} {...props} />;
const Waiting = () => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" height="1em" width="1em"><path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM13 12H17V14H11V7H13V12Z" stroke="none"></path></svg>
)
export const WaitingIcon = (props) => <Icon component={Waiting} {...props} />;
const Failed = () => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" color='#ED1C24' height="1em" width="1em"><path d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z" stroke="none"></path></svg>
)
export const FailedIcon = (props) => <Icon component={Failed} {...props} />;
const Filter = () => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" height="1em" width="1em" fill="currentColor"><path d="M6.17071 18C6.58254 16.8348 7.69378 16 9 16C10.3062 16 11.4175 16.8348 11.8293 18H22V20H11.8293C11.4175 21.1652 10.3062 22 9 22C7.69378 22 6.58254 21.1652 6.17071 20H2V18H6.17071ZM12.1707 11C12.5825 9.83481 13.6938 9 15 9C16.3062 9 17.4175 9.83481 17.8293 11H22V13H17.8293C17.4175 14.1652 16.3062 15 15 15C13.6938 15 12.5825 14.1652 12.1707 13H2V11H12.1707ZM6.17071 4C6.58254 2.83481 7.69378 2 9 2C10.3062 2 11.4175 2.83481 11.8293 4H22V6H11.8293C11.4175 7.16519 10.3062 8 9 8C7.69378 8 6.58254 7.16519 6.17071 6H2V4H6.17071Z"></path></svg>
)

@ -45,8 +45,6 @@ import TableCellResizer from './plugins/TableCellResizer';
// import {useLexicalEditable} from '@lexical/react/useLexicalEditable';
import FormatPaintPlugin from './plugins/FormatPaint';
import { TextNode, $getRoot, $getSelection, $createParagraphNode } from 'lexical';
import { $generateHtmlFromNodes, $generateNodesFromDOM, } from '@lexical/html';
@ -205,7 +203,6 @@ export default function Editor({ isRichText, isDebug, editorRef, onChange, defau
<EditorRefPlugin editorRef={editorRef} />
<ImagesPlugin />
<InlineImagePlugin />
<FormatPaintPlugin />
<MyOnChangePlugin onChange={onChange}/>
</div>
</div>

@ -1,27 +0,0 @@
import { LexicalCommand, createCommand, TextFormatType } from 'lexical';
export interface CopiedFormat {
textFormatFlags: number; // 从node.getFormat()
style: string; // 从node.getStyle()
// todo: p 标签的样式
}
export interface ActivateFormatPainterPayload {
sticky: boolean;
}
// activate the format painter and copy the current selection's format
export const ACTIVATE_FORMAT_PAINTER_COMMAND: LexicalCommand<ActivateFormatPainterPayload> =
createCommand('ACTIVATE_FORMAT_PAINTER_COMMAND');
// deactivate the format painter
export const DEACTIVATE_FORMAT_PAINTER_COMMAND: LexicalCommand<void> =
createCommand('DEACTIVATE_FORMAT_PAINTER_COMMAND');
// dispatched by the plugin to inform UI about state changes
export interface FormatPainterState {
isActive: boolean;
isSticky: boolean;
}
export const FORMAT_PAINTER_STATE_UPDATE_COMMAND: LexicalCommand<FormatPainterState> =
createCommand('FORMAT_PAINTER_STATE_UPDATE_COMMAND');

@ -1,86 +0,0 @@
import React, { useState, useEffect, useCallback } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $getSelection, $isRangeSelection, LexicalEditor, COMMAND_PRIORITY_NORMAL } from 'lexical';
import {
ACTIVATE_FORMAT_PAINTER_COMMAND,
DEACTIVATE_FORMAT_PAINTER_COMMAND,
FORMAT_PAINTER_STATE_UPDATE_COMMAND,
FormatPainterState,
} from './FormatPainterCommands';
const PaintBrushIcon = () => <i className='format painter' />;
export function FormatPainterToolbarButton() {
const [editor] = useLexicalComposerContext();
const [isActive, setIsActive] = useState(false);
const [isSticky, setIsSticky] = useState(false);
const [canCopy, setCanCopy] = useState(false);
// 插件状态
useEffect(() => {
return editor.registerCommand<FormatPainterState>(
FORMAT_PAINTER_STATE_UPDATE_COMMAND,
(payload) => {
setIsActive(payload.isActive);
setIsSticky(payload.isSticky);
return true;
},
COMMAND_PRIORITY_NORMAL,
);
}, [editor]);
// 选区状态
useEffect(() => {
return editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
const selection = $getSelection();
if ($isRangeSelection(selection) && !selection.isCollapsed()) {
setCanCopy(true);
} else {
setCanCopy(false);
}
});
});
}, [editor]);
const handleClick = () => {
if (isActive) {
editor.dispatchCommand(DEACTIVATE_FORMAT_PAINTER_COMMAND, undefined);
} else if (canCopy) {
editor.dispatchCommand(ACTIVATE_FORMAT_PAINTER_COMMAND, { sticky: false });
}
// * !isActive and !canCopy 什么也不做
};
// 双击 保持激活
const handleDoubleClick = () => {
if (isActive && isSticky) {
editor.dispatchCommand(DEACTIVATE_FORMAT_PAINTER_COMMAND, undefined);
} else if (canCopy) {
editor.dispatchCommand(ACTIVATE_FORMAT_PAINTER_COMMAND, { sticky: true });
}
};
return (
<button
type="button"
onClick={handleClick}
onDoubleClick={handleDoubleClick}
className={`toolbar-item spaced ${isActive ? 'active' : ''}`}
// title={isActive ? (isSticky ? 'Format Painter (Sticky)' : 'Format Painter (Active)') : 'Format Painter'}
title={'格式刷'}
aria-label={isActive ? (isSticky ? 'Deactivate Format Painter (Sticky)' : 'Deactivate Format Painter (Active)') : 'Activate Format Painter'}
disabled={!isActive && !canCopy}
>
<PaintBrushIcon />
{/* <span style={{wordBreak: 'keep-all'}}>格式刷</span> */}
</button>
);
}
{/* <button type='button'
className={'toolbar-item spaced ' + (isActive ? 'active' : '')}
aria-label='Format Painter'>
<i className='format painter' />
</button> */}
export default FormatPainterToolbarButton;

@ -1,267 +0,0 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import {
$getSelection,
$isRangeSelection,
$isTextNode,
TextFormatType,
LexicalEditor,
COMMAND_PRIORITY_NORMAL,
COMMAND_PRIORITY_LOW,
} from 'lexical';
import { $patchStyleText, } from '@lexical/selection';
// $patchStyleText is more efficient for merging styles.
import {
CopiedFormat,
ACTIVATE_FORMAT_PAINTER_COMMAND,
DEACTIVATE_FORMAT_PAINTER_COMMAND,
FORMAT_PAINTER_STATE_UPDATE_COMMAND,
ActivateFormatPainterPayload,
FormatPainterState,
} from './FormatPainterCommands';
// parse style string to object for $patchStyleText
function parseStyleText(style: string): Record<string, string> {
const styleObj: Record<string, string> = {};
style.split(';').forEach((rule) => {
const [key, value] = rule.split(':');
if (key && value && key.trim() && value.trim()) {
styleObj[key.trim()] = value.trim();
}
});
return styleObj;
}
// map format flags to TextFormatType
const textFormatTypeMap: { flag: number; type: TextFormatType }[] = [
{ flag: 1, type: 'bold' },
{ flag: 2, type: 'italic' },
{ flag: 4, type: 'strikethrough' },
{ flag: 8, type: 'underline' },
{ flag: 16, type: 'code' },
{ flag: 32, type: 'subscript' },
{ flag: 64, type: 'superscript' },
];
export function FormatPainterPlugin(): null {
const [editor] = useLexicalComposerContext();
const [copiedFormat, setCopiedFormat] = useState<CopiedFormat | null>(null);
const [isActive, setIsActive] = useState(false);
const [isSticky, setIsSticky] = useState(false);
// 避免多次复制
const isPickingUpRef = useRef(false);
const broadcastState = useCallback(() => {
editor.dispatchCommand(FORMAT_PAINTER_STATE_UPDATE_COMMAND, {
isActive,
isSticky,
});
}, [editor, isActive, isSticky]);
// Update broadcast whenever state changes
useEffect(() => {
broadcastState();
}, [isActive, isSticky, broadcastState]);
// Activate Format Painter (Copy Format)
useEffect(() => {
return editor.registerCommand<ActivateFormatPainterPayload>(
ACTIVATE_FORMAT_PAINTER_COMMAND,
(payload) => {
isPickingUpRef.current = true;
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection) && !selection.isCollapsed()) {
const anchorNode = selection.anchor.getNode();
let formatToCopy: CopiedFormat | null = null;
if ($isTextNode(anchorNode)) {
formatToCopy = {
textFormatFlags: anchorNode.getFormat(),
style: anchorNode.getStyle(),
};
} else {
// ? todo: 从第一个字符获取格式
const nodes = selection.getNodes();
for (const node of nodes) {
if ($isTextNode(node)) {
formatToCopy = {
textFormatFlags: node.getFormat(),
style: node.getStyle(),
};
break;
}
}
}
if (formatToCopy) {
setCopiedFormat(formatToCopy);
setIsActive(true);
setIsSticky(payload.sticky);
// console.log('Format Painter Activated. Sticky:', payload.sticky, 'Format:', formatToCopy);
}
}
});
// 鼠标抬起
setTimeout(() => { isPickingUpRef.current = false; }, 50);
return true;
},
COMMAND_PRIORITY_NORMAL,
);
}, [editor]);
// Deactivate Format Painter
useEffect(() => {
return editor.registerCommand<void>(
DEACTIVATE_FORMAT_PAINTER_COMMAND,
() => {
if (!isActive) return false;
setIsActive(false);
setIsSticky(false);
// 不保留
setCopiedFormat(null);
// console.log('Format Painter Deactivated.');
return true;
},
COMMAND_PRIORITY_NORMAL,
);
}, [editor, isActive]);
// 应用复制的格式
const applyFormat = useCallback(() => {
if (!isActive || !copiedFormat || isPickingUpRef.current) {
return false;
}
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection) && copiedFormat) {
// console.log('copiedFormat:', copiedFormat, '\ntextFormatTypeMap:', textFormatTypeMap);
// TextNode (bold, italic, ...)
textFormatTypeMap.forEach(fmt => {
if (copiedFormat.textFormatFlags & fmt.flag) {
selection.formatText(fmt.type);
} else {
const currentSelection = $getSelection();
if ($isRangeSelection(currentSelection)) {
textFormatTypeMap.forEach(fmt => {
const shouldHaveFormat = (copiedFormat.textFormatFlags & fmt.flag) > 0;
if (currentSelection.hasFormat(fmt.type) !== shouldHaveFormat) {
currentSelection.formatText(fmt.type);
}
});
}
}
});
// ensure applied
let newSelection = $getSelection();
if ($isRangeSelection(newSelection)) {
textFormatTypeMap.forEach(fmt => {
if (copiedFormat.textFormatFlags & fmt.flag) {
if (!newSelection!.hasFormat(fmt.type)) newSelection!.formatText(fmt.type);
} else {
if (newSelection!.hasFormat(fmt.type)) newSelection!.formatText(fmt.type);
}
});
}
// inline styles (font-family, color, font-size, ...)
const stylesToApply = parseStyleText(copiedFormat.style);
// console.log('inline style', stylesToApply);
if (Object.keys(stylesToApply).length > 0) {
newSelection = $getSelection();
if ($isRangeSelection(newSelection)) {
$patchStyleText(newSelection as any, stylesToApply);
}
} else {
// 清除格式
const selectedNodes = newSelection.getNodes();
selectedNodes.forEach(node => {
if ($isTextNode(node)) {
if (node.getStyle() !== "") {
node.setStyle(""); // 清除
}
}
// todo: <p> node
});
}
// console.log('Format Applied. Sticky:', isSticky);
if (!isSticky) {
setIsActive(false);
}
}
});
return true;
}, [editor, isActive, isSticky, copiedFormat]);
// 鼠标抬起
useEffect(() => {
if (!isActive || !copiedFormat) return;
const editorElement = editor.getRootElement();
if (!editorElement) return;
const handleMouseUp = (event: MouseEvent) => {
if (isPickingUpRef.current) return;
if (editorElement.contains(event.target as Node)) {
// todo: 改为在下一帧更新
setTimeout(() => {
const selection = editor.getEditorState().read($getSelection);
if ($isRangeSelection(selection) && !selection.isCollapsed()) {
applyFormat();
} else if ($isRangeSelection(selection) && selection.isCollapsed()) {
// 折叠的选区, 也应用
// applyFormat();
}
}, 0);
}
};
document.addEventListener('mouseup', handleMouseUp);
return () => {
document.removeEventListener('mouseup', handleMouseUp);
};
}, [editor, isActive, copiedFormat, applyFormat]);
// 按 esc 键取消格式
useEffect(() => {
if (!isActive) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
editor.dispatchCommand(DEACTIVATE_FORMAT_PAINTER_COMMAND, undefined);
}
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [editor, isActive]);
// 鼠标样式
useEffect(() => {
const editorElement = editor.getRootElement();
if (editorElement) {
editorElement.style.cursor = isActive ? 'copy' : 'auto';
}
return () => {
if (editorElement) {
editorElement.style.cursor = 'auto';
}
};
}, [editor, isActive]);
return null;
}
export default FormatPainterPlugin;

@ -15,7 +15,6 @@ import {
$isRangeSelection,
$createParagraphNode,
$getNodeByKey,
$isTextNode,
} from 'lexical';
import { $isLinkNode, $toggleLink, TOGGLE_LINK_COMMAND } from '@lexical/link';
import {
@ -26,14 +25,12 @@ import {
// $wrapNodes,
$isAtNodeEnd,
} from '@lexical/selection';
import { $findMatchingParent, $getNearestNodeOfType, $getNearestBlockElementAncestorOrThrow, mergeRegister } from '@lexical/utils';
import { $findMatchingParent, $getNearestNodeOfType, mergeRegister } from '@lexical/utils';
import { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, REMOVE_LIST_COMMAND, $isListNode, ListNode } from '@lexical/list';
import { createPortal } from 'react-dom';
import { $createHeadingNode, $createQuoteNode, $isHeadingNode, $isQuoteNode } from '@lexical/rich-text';
import { $createHeadingNode, $createQuoteNode, $isHeadingNode } from '@lexical/rich-text';
import { $createCodeNode, $isCodeNode, getDefaultCodeLanguage, getCodeLanguages } from '@lexical/code';
import { INSERT_HORIZONTAL_RULE_COMMAND } from '@lexical/react/LexicalHorizontalRuleNode';
import {$isDecoratorBlockNode} from '@lexical/react/LexicalDecoratorBlockNode';
import {$isTableSelection} from '@lexical/table';
import DropDown, { DropDownItem } from './../ui/DropDown';
import DropdownColorPicker from '../ui/DropdownColorPicker';
import {
@ -42,7 +39,6 @@ import {
// InsertImagePayload,
} from './ImagesPlugin';
import {InsertInlineImageDialog} from './InlineImagePlugin';
import FormatPainterToolbarButton from './FormatPaint/FormatPainterToolbarButton';
import useModal from './../hooks/useModal';
@ -74,19 +70,16 @@ const FONT_FAMILY_OPTIONS = [
const FONT_SIZE_OPTIONS = [
['10px', '10px'],
// ['11px', '11px'],
['11px', '11px'],
['12px', '12px'],
['13px', '13px'],
['14px', '14px'],
// ['15px', '15px'],
['15px', '15px'],
['16px', '16px'],
// ['17px', '17px'],
['17px', '17px'],
['18px', '18px'],
// ['19px', '19px'],
['19px', '19px'],
['20px', '20px'],
['24px', '24px'],
['32px', '32px'],
// ['48px', '48px'],
];
const ELEMENT_FORMAT_OPTIONS = {
@ -98,62 +91,6 @@ const ELEMENT_FORMAT_OPTIONS = {
start: { icon: 'left-align', iconRTL: 'right-align', name: 'Start Align' },
};
// toolbar utils
const clearFormatting = (editor) => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection) || $isTableSelection(selection)) {
const anchor = selection.anchor;
const focus = selection.focus;
const nodes = selection.getNodes();
const extractedNodes = selection.extract();
if (anchor.key === focus.key && anchor.offset === focus.offset) {
return;
}
nodes.forEach((node, idx) => {
// We split the first and last node by the selection
// So that we don't format unselected text inside those nodes
if ($isTextNode(node)) {
// Use a separate variable to ensure TS does not lose the refinement
let textNode = node;
if (idx === 0 && anchor.offset !== 0) {
textNode = textNode.splitText(anchor.offset)[1] || textNode;
}
if (idx === nodes.length - 1) {
textNode = textNode.splitText(focus.offset)[0] || textNode;
}
/**
* If the selected text has one format applied
* selecting a portion of the text, could
* clear the format to the wrong portion of the text.
*
* The cleared text is based on the length of the selected text.
*/
// We need this in case the selected text only has one format
const extractedTextNode = extractedNodes[0];
if (nodes.length === 1 && $isTextNode(extractedTextNode)) {
textNode = extractedTextNode;
}
if (textNode.__style !== '') {
textNode.setStyle('');
}
if (textNode.__format !== 0) {
textNode.setFormat(0);
$getNearestBlockElementAncestorOrThrow(textNode).setFormat('');
}
node = textNode;
} else if ($isHeadingNode(node) || $isQuoteNode(node)) {
node.replace($createParagraphNode(), true);
} else if ($isDecoratorBlockNode(node)) {
node.setFormat('');
}
});
}
});
};
function dropDownActiveClass(active) {
if (active) {
return 'active dropdown-item-active';
@ -555,13 +492,12 @@ function FontDropDown({ editor, value, style, disabled = false }) {
<DropDown
disabled={disabled}
buttonClassName={'toolbar-item ' + style}
buttonLabel={value}
// buttonLabel={value}
buttonIconClassName={style === 'font-family' ? 'icon block-type font-family' : ''}
buttonAriaLabel={buttonAriaLabel}>
{(style === 'font-family' ? FONT_FAMILY_OPTIONS : FONT_SIZE_OPTIONS).map(([option, text]) => (
<DropDownItem
className={`item font-m-${option.replace(/\s+/g, '_')} ${dropDownActiveClass(value === option)} ${style === 'font-size' ? 'fontsize-item' : ''}`}
style={{ fontFamily: style === 'font-family' ? option : undefined, fontSize: style === 'font-size' ? option : undefined }}
onClick={() => handleClick(option)}
key={option}>
<span className='text'>{text}</span>
@ -669,7 +605,6 @@ export default function ToolbarPlugin() {
const [isStrikethrough, setIsStrikethrough] = useState(false);
const [isCode, setIsCode] = useState(false);
const [fontFamily, setFontFamily] = useState('Arial');
const [fontSize, setFontSize] = useState('16px');
const [fontColor, setFontColor] = useState('#000');
const [bgColor, setBgColor] = useState('#fff');
const [elementFormat, setElementFormat] = useState('left');
@ -757,9 +692,6 @@ export default function ToolbarPlugin() {
setFontFamily(
$getSelectionStyleValueForProperty(selection, 'font-family', 'Arial'),
);
setFontSize(
$getSelectionStyleValueForProperty(selection, 'font-size', '16px'),
);
let matchingParent;
if ($isLinkNode(parent)) {
// If node is a link, we need to fetch the parent paragraph node to set format
@ -853,14 +785,6 @@ export default function ToolbarPlugin() {
aria-label='Redo'>
<i className='format redo' />
</button>
<FormatPainterToolbarButton />
<button type='button'
onClick={() => clearFormatting(activeEditor)}
className='toolbar-item'
title="清除格式"
aria-label='Clear'>
<i className='format clear' />
</button>
<Divider />
{supportedBlockTypes.has(blockType) && (
<>
@ -890,12 +814,6 @@ export default function ToolbarPlugin() {
value={fontFamily}
editor={editor}
/>
<FontDropDown
disabled={!isEditable}
style={'font-size'}
value={fontSize}
editor={editor}
/>
<Divider />
<button type='button'
onClick={() => {

@ -80,7 +80,7 @@
.editor-input {
min-height: 150px;
resize: none;
font-size: 16px;
font-size: 15px;
caret-color: rgb(5, 5, 5);
position: relative;
tab-size: 1;
@ -404,7 +404,6 @@ pre::-webkit-scrollbar-thumb {
padding: 8px;
cursor: pointer;
vertical-align: middle;
word-break: keep-all;
}
.toolbar button.toolbar-item:disabled {
@ -431,8 +430,7 @@ pre::-webkit-scrollbar-thumb {
}
.toolbar button.toolbar-item.active {
/* background-color: rgba(223, 232, 250, 0.8); */
background-color: #eef2ff;
background-color: rgba(223, 232, 250, 0.3);
}
.toolbar button.toolbar-item.active i {
@ -477,12 +475,12 @@ pre::-webkit-scrollbar-thumb {
.toolbar .toolbar-item .text {
display: flex;
line-height: 20px;
/* width: 200px; */
width: 200px;
vertical-align: middle;
font-size: 14px;
color: #777;
text-overflow: ellipsis;
width: 3rem;
width: 70px;
overflow: hidden;
height: 20px;
text-align: left;
@ -606,8 +604,7 @@ i.chevron-down {
background-size: contain;
}
button.item.dropdown-item-active {
/* background-color: #dfe8fa4d; */
background-color: #eef2ff;
background-color: #dfe8fa4d;
}
.dropdown .item:first-child {
@ -764,9 +761,6 @@ i.undo {
i.redo {
background-image: url(/images/icons/arrow-clockwise.svg);
}
i.clear{
background-image: url(/images/icons/eraser-line.svg);
}
.icon.paragraph {
background-image: url(/images/icons/text-paragraph.svg);
@ -842,10 +836,6 @@ i.outdent {
background-image: url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='16'%20height='16'%20fill='currentColor'%20class='bi%20bi-text-indent-right'%3e%3cpath%20d='M2%203.5a.5.5%200%200%201%20.5-.5h11a.5.5%200%200%201%200%201h-11a.5.5%200%200%201-.5-.5zm10.646%202.146a.5.5%200%200%201%20.708.708L11.707%208l1.647%201.646a.5.5%200%200%201-.708.708l-2-2a.5.5%200%200%201%200-.708l2-2zM2%206.5a.5.5%200%200%201%20.5-.5h6a.5.5%200%200%201%200%201h-6a.5.5%200%200%201-.5-.5zm0%203a.5.5%200%200%201%20.5-.5h6a.5.5%200%200%201%200%201h-6a.5.5%200%200%201-.5-.5zm0%203a.5.5%200%200%201%20.5-.5h11a.5.5%200%200%201%200%201h-11a.5.5%200%200%201-.5-.5z'/%3e%3c/svg%3e")
}
i.painter {
background-image: url(/images/icons/brush-3-line.svg);
}
i.bold {
background-image: url(/images/icons/type-bold.svg);
}

@ -29,13 +29,12 @@ export function DropDownItem({
children,
className,
onClick,
title, style
title,
}: {
children: React.ReactNode;
className: string;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
title?: string;
style?: React.CSSProperties;
}) {
const ref = useRef<HTMLButtonElement>(null);
@ -54,7 +53,7 @@ export function DropDownItem({
}, [ref, registerItem]);
return (
<button style={style}
<button
className={className}
onClick={onClick}
ref={ref}

@ -1,356 +0,0 @@
import {
WhatsAppOutlined,
FileAddOutlined,
MailOutlined,
PhoneOutlined,
UserOutlined,
FieldNumberOutlined,
CompassOutlined,
CalendarOutlined,
EditOutlined,
CheckOutlined,
ReloadOutlined,
} from '@ant-design/icons'
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { App, Flex, Select, Tooltip, Divider, Typography, Skeleton, Checkbox, Drawer, Button, Form, Input } from 'antd'
import { useOrderStore, fetchSetRemindStateAction, OrderLabelDefaultOptions, OrderStatusDefaultOptions, remindStatusOptions } from '@/stores/OrderStore'
import { copy, isEmpty } from '@/utils/commons'
import { useShallow } from 'zustand/react/shallow'
import useConversationStore from '@/stores/ConversationStore'
import useAuthStore from '@/stores/AuthStore'
const OrderProfile = ({ coliSN, ...props }) => {
const { notification, message } = App.useApp()
const [formComment] = Form.useForm()
const [formWhatsApp] = Form.useForm()
const [formExtra] = Form.useForm()
const [loading, setLoading] = useState(false)
const [openOrderCommnet, setOpenOrderCommnet] = useState(false)
const [openWhatsApp, setOpenWhatsApp] = useState(false)
const [openExtra, setOpenExtra] = useState(false)
const orderLabelOptions = copy(OrderLabelDefaultOptions)
orderLabelOptions.unshift({ value: 0, label: '未设置', disabled: true })
const orderStatusOptions = copy(OrderStatusDefaultOptions)
const [orderDetail, customerDetail, fetchOrderDetail, setOrderPropValue, appendOrderComment, updateWhatsapp, updateExtraInfo] = useOrderStore((s) => [
s.orderDetail,
s.customerDetail,
s.fetchOrderDetail,
s.setOrderPropValue,
s.appendOrderComment,
s.updateWhatsapp,
s.updateExtraInfo,
])
const loginUser = useAuthStore((state) => state.loginUser)
const currentOrder = useConversationStore(useShallow((state) => state.currentConversation?.coli_sn || ''))
const orderId = coliSN || currentOrder
const [orderRemindState, setOrderRemindState] = useState(orderDetail.remindstate)
useEffect(() => {
setOrderRemindState(orderDetail.remindstate)
}, [orderDetail.remindstate])
useEffect(() => {
if (orderId) {
setLoading(true)
fetchOrderDetail(orderId)
.finally(() => setLoading(false))
.catch((reason) => {
notification.error({
message: '查询出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}
return () => {}
}, [orderId])
const handleSetRemindState = async (checkedValue) => {
const state = checkedValue.filter((v) => v !== orderRemindState)
const oldState = orderRemindState
try {
if (isEmpty(state)) {
setOrderRemindState(null)
} else {
setOrderRemindState(state[0])
}
await fetchSetRemindStateAction({ coli_sn: coliSN, remindstate: state })
message.success('设置成功')
} catch (error) {
notification.warning({ message: '设置失败', description: error.message, placement: 'top', duration: 60 })
setOrderRemindState(oldState)
}
}
const getCustomerName = () => {
if (orderDetail.buytime > 0) return customerDetail.name + '(R' + orderDetail.buytime + ')'
return customerDetail.name
}
const getPlanStatus = () => {
return orderDetail.DidPlan === 0 ? '未做计划' : '已做计划'
}
return (
<>
<Skeleton active loading={loading}>
<Flex gap='small' vertical={true} justify='space-between' className='p-2'>
<Typography.Text>
<FieldNumberOutlined className='pr-1' />
{orderDetail.order_no}
</Typography.Text>
<Typography.Text>
<UserOutlined className=' pr-1' />
{getCustomerName()}
</Typography.Text>
<Typography.Text>
<CompassOutlined className=' pr-1' />
{orderDetail.MEI_Country}
</Typography.Text>
<Typography.Text>
<PhoneOutlined className=' pr-1' />
{customerDetail.phone}
</Typography.Text>
<Typography.Text>
<MailOutlined className='pr-1' />
{customerDetail.email}
</Typography.Text>
<Typography.Text>
<WhatsAppOutlined className='pr-1' />
{isEmpty(customerDetail.whatsapp_phone_number) ? (
<Button type='text' onClick={() => setOpenWhatsApp(true)} size='small'>
设置 WhatsApp
</Button>
) : (
<Link to={`/order/chat/${coliSN}`} state={{...orderDetail, coli_guest_WhatsApp: customerDetail.whatsapp_phone_number, }}>
{customerDetail.whatsapp_phone_number}
</Link>
)}
</Typography.Text>
<Typography.Text>
<Tooltip title='出发日期'>
<CalendarOutlined className='pr-1' />
{orderDetail.COLI_OrderStartDate}
</Tooltip>
</Typography.Text>
<Typography.Text>
<Tooltip title='计划状态'>
<CheckOutlined className='pr-1' />
{getPlanStatus()}
</Tooltip>
</Typography.Text>
</Flex>
<Divider orientation='left'>
<Typography.Text strong>订单状态</Typography.Text>
</Divider>
<Flex gap='small' vertical={false} justify='space-between'>
<Select
className={`[&_.ant-select-selection-item]:text-gray-950`}
key={'orderlabel'}
size='small'
style={{
width: '100%',
}}
variant='underlined'
onSelect={(value) => {
setOrderPropValue(coliSN, 'orderlabel', value)
.then(() => {
message.success('设置成功')
})
.catch((reason) => {
notification.error({
message: '设置出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}}
value={orderDetail.tags}
options={orderLabelOptions}
/>
<Select
className={`[&_.ant-select-selection-item]:text-gray-950`}
key={'orderstatus'}
size='small'
style={{
width: '100%',
}}
variant='underlined'
onSelect={(value) => {
setOrderPropValue(coliSN, 'orderstatus', value)
.then(() => {
message.success('设置成功')
})
.catch((reason) => {
notification.error({
message: '设置出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}}
value={orderDetail.states}
options={orderStatusOptions}
/>
</Flex>
<Divider orientation='left'>
<Typography.Text strong>催信</Typography.Text>
</Divider>
<Checkbox.Group key='substatus' className='px-2' value={[orderRemindState]} options={remindStatusOptions} onChange={handleSetRemindState} />
<Divider orientation='left'>
<Typography.Text strong>表单信息</Typography.Text>
<Tooltip title='添加'>
<FileAddOutlined
className='pl-1'
onClick={() => {
setOpenOrderCommnet(true)
}}
/>
</Tooltip>
</Divider>
<p className='p-2 overflow-auto m-0 break-words whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: orderDetail.order_detail }}></p>
<Divider orientation='left'>
<Typography.Text strong>特殊要求</Typography.Text>
</Divider>
<Typography.Text>{orderDetail.customer_request}</Typography.Text>
<Divider orientation='left'>
<Typography.Text strong>外联备注</Typography.Text>
{/* <Tooltip title=''>
<EditOutlined className='pl-1' />
</Tooltip> */}
</Divider>
<Typography.Text>{orderDetail.wl_memo}</Typography.Text>
<Divider orientation='left'>
<Typography.Text strong>附加信息</Typography.Text>
<Tooltip title='修改'>
<EditOutlined
className='pl-1'
onClick={() => {
formExtra.setFieldsValue({ extra: orderDetail.COLI_Introduction })
setOpenExtra(true)
}}
/>
</Tooltip>
</Divider>
<Typography.Text>{orderDetail.COLI_Introduction}</Typography.Text>
</Skeleton>
<Drawer title='添加表单信息' closable={{ 'aria-label': 'Close Button' }} onClose={() => setOpenOrderCommnet(false)} open={openOrderCommnet}>
<Form
layout={'vertical'}
form={formComment}
initialValues={{ comment: '' }}
scrollToFirstError
onFinish={(values) => {
appendOrderComment(loginUser.userId, orderId, values.comment)
.then(() => {
notification.success({
message: '温性提示',
description: '添加表单信息成功',
})
setOpenOrderCommnet(false)
formComment.setFieldsValue({ comment: '' })
})
.catch((reason) => {
notification.error({
message: '添加出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}}>
<Form.Item name='comment' label='表单信息' rules={[{ required: true, message: '请输入表单信息' }]}>
<Input.TextArea rows={4} />
</Form.Item>
<Form.Item>
<Button type='primary' htmlType='submit'>
提交
</Button>
</Form.Item>
</Form>
</Drawer>
<Drawer title='设置 WhatsApp' closable={{ 'aria-label': 'Close Button' }} onClose={() => setOpenWhatsApp(false)} open={openWhatsApp}>
<Form
layout={'vertical'}
form={formWhatsApp}
initialValues={{ number: '' }}
scrollToFirstError
onFinish={(values) => {
updateWhatsapp(orderId, values.number)
.then(() => {
notification.success({
message: '温性提示',
description: '设置 WhatsApp 成功',
})
setOpenWhatsApp(false)
formWhatsApp.setFieldsValue({ number: '' })
})
.catch((reason) => {
notification.error({
message: '设置出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}}>
<Form.Item name='number' label='WhatsApp' rules={[{ required: true, message: '请输入 WhatsApp 号码' }]}>
<Input placeholder='国家代码+城市代码+电话号码' />
</Form.Item>
<Form.Item>
<Button type='primary' htmlType='submit'>
提交
</Button>
</Form.Item>
</Form>
</Drawer>
<Drawer title='设置附加信息' closable={{ 'aria-label': 'Close Button' }} onClose={() => setOpenExtra(false)} open={openExtra}>
<Form
layout={'vertical'}
form={formExtra}
scrollToFirstError
onFinish={(values) => {
updateExtraInfo(orderId, values.extra)
.then(() => {
notification.success({
message: '温性提示',
description: '设置附加信息成功',
})
setOpenExtra(false)
})
.catch((reason) => {
notification.error({
message: '设置出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}}>
<Form.Item name='extra' label='附加信息' rules={[{ required: true, message: '请输入附加信息' }]}>
<Input />
</Form.Item>
<Form.Item>
<Button type='primary' htmlType='submit'>
提交
</Button>
</Form.Item>
</Form>
</Drawer>
</>
)
}
export default OrderProfile

@ -7,28 +7,26 @@
// debug:
// export const API_HOST = 'http://202.103.68.144:8889/v2';
// export const WS_URL = 'ws://202.103.68.144:8888';
// export const WS_URL = 'ws://202.103.68.144:8889';
// export const EMAIL_HOST = 'http://202.103.68.231:888/service-mail';
// export const WAI_HOST = 'http://47.83.248.120/api/v1'; // 香港服务器
// export const WAI_HOST = 'http://47.254.53.81/api/v1'; // 美国服务器
export const WAI_HOST = 'http://47.254.53.81/api/v1'; // 美国服务器
// export const WAI_HOST = 'http://localhost:3031/api/v1'; // 美国服务器
export const WAI_SERVER_KEY = 'G-STR:WAI_SERVER'
// prod:--------------------------------------------------------------------------------------------------
export const EMAIL_ATTA_HOST = 'https://p9axztuwd7x8a7.mycht.cn/attachment'; // 邮件附件
export const WAI_HOST = 'https://wai-server-qq4qmtq7wc9he4.mycht.cn/api/v1';
// prod:
// export const WAI_HOST = 'https://wai-server-qq4qmtq7wc9he4.mycht.cn/api/v1';
export const EMAIL_HOST = 'https://p9axztuwd7x8a7.mycht.cn/mail-server/service-mail';
export const EMAIL_HOST_v3 = 'https://p9axztuwd7x8a7.mycht.cn/mail-server/service-mail';
export const API_HOST = 'https://p9axztuwd7x8a7.mycht.cn/whatsapp_server/v2';
export const API_HOST_V3 = 'https://p9axztuwd7x8a7.mycht.cn/whatsapp_server/v3';
export const WS_URL = 'wss://p9axztuwd7x8a7.mycht.cn/whatsapp_server'; // prod:
export const VONAGE_URL = 'https://p9axztuwd7x8a7.mycht.cn/vonage-server'; // 语音和视频接口:
export const HT3 = process.env.NODE_ENV === 'production' ? 'https://p9axztuwd7x8a7.mycht.cn/ht3' : 'https://p9axztuwd7x8a7.mycht.cn/ht3';
// export const VONAGE_URL = 'https://p9axztuwd7x8a7.mycht.cn/vonage-server'; // 语音和视频接口:
export const VONAGE_URL = 'http://p6t3mr.natappfree.cc'; // 语音和视频接口:
export const HT3 = process.env.NODE_ENV === 'production' ? 'https://p9axztuwd7x8a7.mycht.cn/ht3' : 'http://127.0.0.1:8000';
export const DATE_FORMAT = 'YYYY-MM-DD';
export const DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
export const DATEEND_FORMAT = 'YYYY-MM-DD 23:59';
export const ERROR_IMG = 'https://hiana-crm.oss-accelerate.aliyuncs.com/WAMedia/afe412d4-3acf-4e79-a623-048aeb4d696a.png';
export const OSS_URL_CN = 'https://haina-sale-system.oss-cn-shenzhen.aliyuncs.com/WAMedia/';
export const OSS_URL_AP = 'https://hiana-crm.oss-ap-southeast-1.aliyuncs.com/WAMedia/';
export const OSS_URL = OSS_URL_AP;
@ -41,5 +39,3 @@ const __BUILD_DATE__ = `__BUILD_DATE__`;
export const BUILD_VERSION = process.env.NODE_ENV === 'production' ? __BUILD_VERSION__ : process.env.NODE_ENV;
export const BUILD_DATE = process.env.NODE_ENV === 'production' ? __BUILD_DATE__ : new Date().toLocaleString();
export const POPUP_FEATURES = 'left=20,top=20,width=1000,height=800,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no';

@ -1,19 +1,16 @@
import { useState, useEffect, useCallback } from 'react'
import { isEmpty, objectMapper, olog, } from '@/utils/commons'
import { readIndexDB } from '@/utils/indexedDB'
import { getEmailDetailAction, postResendEmailAction, getSalesSignatureAction, getEmailOrderAction, queryEmailListAction, searchEmailListAction, getReminderEmailTemplateAction, saveEmailDraftOrSendAction, updateEmailAction, getEmailChangesChannel, EMAIL_CHANNEL_NAME } from '@/actions/EmailActions'
import { isEmpty } from '@/utils/commons'
import { getEmailDetailAction, postResendEmailAction, getSalesSignatureAction, getEmailOrderAction } from '@/actions/EmailActions'
import { App } from 'antd'
import useConversationStore from '@/stores/ConversationStore';
import { msgStatusRenderMapped } from '@/channel/bubbleMsgUtils';
import { POPUP_FEATURES } from '@/config';
import { internalEventEmitter } from '@/utils/EventEmitterService';
export const useEmailSignature = (opi_sn) => {
const [signature, setSignature] = useState('')
const getSignature = useCallback(async () => {
if (isEmpty(Number(opi_sn))) {
if (isEmpty(opi_sn)) {
return false
}
try {
@ -26,417 +23,89 @@ export const useEmailSignature = (opi_sn) => {
useEffect(() => {
getSignature()
}, [getSignature])
}, [opi_sn])
return { signature }
return { signature, getSignature }
}
/**
* 邮件详情
*
* @param mai_sn 邮件编号ID
* @param data 直接传递, 不重复获取
* * 在详情点击`回复`呼出编辑时
* @param {number|boolean} oid 订单ID
* - If `number`: 直接传递, 直接获取订单详情
* - If `false`: 不需要获取订单信息
*/
export const useEmailDetail = (mai_sn=0, data={}, oid=0, markRead=false) => {
export const useEmailDetail = (mai_sn, data) => {
const {notification} = App.useApp()
const [loading, setLoading] = useState(false)
const [mailData, setMailData] = useState({ loading, info: { MAI_COLI_SN: 0 }, content: '', attachments: [], AttachList: [] })
const [maiSN, setMaiSN] = useState(mai_sn);
const [coliSN, setColiSN] = useState(oid);
const [mailData, setMailData] = useState({ loading, info: {}, content: '', attachments: [] })
const [coliSN, setColiSN] = useState('');
const [orderDetail, setOrderDetail] = useState({});
const [refreshTrigger, setRefreshTrigger] = useState(0);
const refresh = useCallback(() => {
setRefreshTrigger(prev => prev + 1);
}, []);
// console.log(maiSN, 'mailSN', mai_sn)
// const [updateMessageItem] = useConversationStore(state => [state.updateMessageItem]);
const getEmailDetail = useCallback(async () => {
if (isEmpty(Number(maiSN)) && isEmpty(Number(mai_sn))) {
return false
}
const [updateMessageItem] = useConversationStore(state => [state.updateMessageItem]);
if (!isEmpty(data)) {
setMailData(data)
return false
}
try {
setLoading(true)
const data = await getEmailDetailAction({ mai_sn: Number(mai_sn) || maiSN })
// console.log(data)
setMailData(data)
setColiSN(oid === false ? 0 : data.info.MAI_COLI_SN)
setLoading(false)
// `已读`
if (markRead !== false && data.info?.MOI_ReadState !== 1) {
updateEmailAction({
opi_sn: data.info.MAI_OPI_SN,
mai_sn_list: [Number(mai_sn) || maiSN],
set: { read: 1 },
})
useEffect(() => {
const getEmailDetail = async () => {
if (isEmpty(mai_sn)) {
return false
}
try {
setLoading(true)
const data = await getEmailDetailAction({ mai_sn })
setMailData(data)
setColiSN(data.info.MAI_COLI_SN)
setLoading(false)
} catch (err) {
setLoading(false)
notification.error({
message: "请求失败",
description: err.message || '网络异常',
placement: "top",
duration: 3,
});
}
} catch (err) {
setLoading(false)
notification.error({
message: '请求失败',
description: err.message || '网络异常',
placement: 'top',
duration: 3,
})
}
}, [mai_sn, maiSN, refreshTrigger])
if (isEmpty(data)) getEmailDetail()
else setMailData(data)
}, [mai_sn])
const getOrderDetail = useCallback(async () => {
// console.log(coliSN, '====colisn======')
if (isEmpty(Number(coliSN))) {
return false
}
try {
setLoading(true)
const data = await getEmailOrderAction({ colisn: coliSN })
setOrderDetail(data)
setLoading(false)
} catch (err) {
setLoading(false)
notification.error({
message: '请求失败',
description: err.message || '网络异常',
placement: 'top',
duration: 3,
})
}
}, [coliSN])
useEffect(() => {
getEmailDetail();
}, [getEmailDetail])
const getOrderDetail = async () => {
if (isEmpty(coliSN)) {
return false
}
try {
setLoading(true)
const data = await getEmailOrderAction({ colisn: coliSN })
setOrderDetail(data)
setLoading(false)
} catch (err) {
setLoading(false)
notification.error({
message: "请求失败",
description: err.message || '网络异常',
placement: "top",
duration: 3,
});
}
}
useEffect(() => {
getOrderDetail()
}, [getOrderDetail])
}, [coliSN])
const postEmailResend = async ({ mai_sn, conversationid: externalid, actionId: actionid, ...body }) => {
if (isEmpty(Number(mai_sn))) {
if (isEmpty(mai_sn)) {
return false
}
await postResendEmailAction({ mai_sn, externalid, actionid, token: 0 })
// 重发没有状态返回值, 此处前端处理为'待发送', todo: 刷新页面后消息仍为上一个状态'失败'
updateMessageItem({ conversationid: externalid, actionid, id: actionid, status: msgStatusRenderMapped['accepted'] })
}
const postEmailSaveOrSend = async (body, isDraft) => {
const { id: savedID } = await saveEmailDraftOrSendAction(body, isDraft)
setMaiSN(savedID)
if (isDraft) {
refresh()
}
return savedID
};
return { loading, mailData, orderDetail, postEmailResend, postEmailSaveOrSend }
return { loading, mailData, orderDetail, postEmailResend }
}
export const EmailBuilder = ({subject, content}) => {
return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html lang="en"><head><title></title><meta http-equiv="Content-Type" content="text/html charset=UTF-8" /><meta content="width=device-width" name="viewport"><meta charset="UTF-8"><meta content="IE=edge" http-equiv="X-UA-Compatible"><meta content="width=device-width" name="viewport"><meta charset="UTF-8"><meta content="IE=edge" http-equiv="X-UA-Compatible"><meta content="telephone=no,address=no,email=no,date=no,url=no" name="format-detection"><meta content="light" name="color-scheme"><meta content="light" name="supported-color-schemes"><style id="font">body#highlights-email{ font-family: Verdana, sans-serif;} table{ border-collapse: collapse; border-spacing: 0;} </style></head><body id="highlights-email" style="margin: 0 auto; padding: 0; width: 900px; background-color: #fcfcfc;">${content}</body></html>`;
return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html lang="en"><head><title>${subject}</title><meta http-equiv="Content-Type" content="text/html charset=UTF-8" /><meta content="width=device-width" name="viewport"><meta charset="UTF-8"><meta content="IE=edge" http-equiv="X-UA-Compatible"><meta content="width=device-width" name="viewport"><meta charset="UTF-8"><meta content="IE=edge" http-equiv="X-UA-Compatible"><meta content="telephone=no,address=no,email=no,date=no,url=no" name="format-detection"><meta content="light" name="color-scheme"><meta content="light" name="supported-color-schemes"><style id="font">body#highlights-email{ font-family: Verdana, sans-serif;} table{ border-collapse: collapse; border-spacing: 0;} </style></head><body id="highlights-email" style="margin: 0 auto; padding: undefined; width: 900px; background-color: #fcfcfc;">${content}</body></html>`;
}
const objectToFeatureString = (obj) =>
obj && typeof obj === 'object'
? Object.entries(obj)
.map(([key, value]) => `${key}=${typeof value === 'boolean' ? (value ? 'yes' : 'no') : String(value)}`)
.join(',')
: '';
export const openPopup = (url, target, extraFeatures = {}) => {
let features2 = objectToFeatureString(extraFeatures)
let screenWidth = window.screen.availWidth;
let screenHeight = window.screen.availHeight;
features2 += extraFeatures?.fullscreen === true ? `,width=${screenWidth},height=${screenHeight}` : ''
window.open(url, target, POPUP_FEATURES+`,${features2}`);
};
export const useEmailList = (mailboxDirNode) => {
const [loading, setLoading] = useState(false)
const [mailList, setMailList] = useState([])
const [error, setError] = useState(null)
const [isFreshData, setIsFreshData] = useState(false)
const [refreshTrigger, setRefreshTrigger] = useState(0)
const [tempBreadcrumb, setTempBreadcrumb] = useState(null);
const refresh = useCallback(() => {
setRefreshTrigger((prev) => prev + 1)
}, [])
const { OPI_SN: opi_sn, COLI_SN, VKey, VParent, ApplyDate, OrderSourceType, IsTrue } = mailboxDirNode
const markAsUnread = useCallback(
async (sn_list) => {
// 优化性能的话,需要更新 mailList 数据,
// 但是更新 mailList 会造成页面全部刷新
// 所以还是先用 refresh()
// const updatedMailList = mailList.map(mail => {
// if (sn_list.includes(mail.MAI_SN)) {
// return { ...mail, MOI_ReadState: 1 };
// }
// return mail;
// });
// setMailList(updatedMailList);
// setLoading(true)
await updateEmailAction({
opi_sn: opi_sn,
mai_sn_list: sn_list,
set: { read: 0 },
})
},
[VKey],
)
const markAsProcessed = useCallback(
async (sn_list) => {
await updateEmailAction({
opi_sn: opi_sn,
mai_sn_list: sn_list,
set: { processed: 1 },
})
},
[VKey],
)
const markAsDeleted = useCallback(
async (sn_list) => {
await updateEmailAction({
opi_sn: opi_sn,
mai_sn_list: sn_list,
set: { delete: 1 },
})
},
[VKey],
)
const loadMailListFromCache = useCallback(async (payload) => {
const cacheKey = isEmpty(COLI_SN) ? `dir-${VKey}` : `order-${VKey}`
const readCacheIDList = await readIndexDB(cacheKey, 'maillist', 'mailbox')
if (!isEmpty(readCacheIDList)) {
const readCacheListRowsMap = await readIndexDB(readCacheIDList.data, 'listrow', 'mailbox')
const _x = readCacheIDList.data.map((ele) => readCacheListRowsMap.get(ele).data || {})
setMailList(_x)
setLoading(false)
}
}, [VKey])
const getMailList = useCallback(async () => {
// console.log('getMailList', mailboxDirNode)
if (!opi_sn || !VKey || (!IsTrue && !COLI_SN)) {
setMailList([])
setLoading(false)
setError(null)
setIsFreshData(false)
return
}
setTempBreadcrumb(null)
setLoading(true)
setError(null)
setIsFreshData(false)
// const cacheKey = isEmpty(COLI_SN) ? `dir-${VKey}` : `order-${VKey}`
try {
// 1. 先从缓存读取
await loadMailListFromCache();
// 2. 从接口获取最新的列表
const nodeParam = { coli_sn: COLI_SN, order_source_type: OrderSourceType, vkey: VKey, vparent: VParent, mai_senddate1: ApplyDate }
const x = await queryEmailListAction({ opi_sn, node: nodeParam })
// 配合List的结构
const _x = x.map((ele) => ({
...ele,
key: ele.MAI_SN,
}))
setMailList(_x)
} catch (networkError) {
setError(new Error(`Failed to get mail list: ${networkError.message}.`))
} finally {
setLoading(false)
}
}, [VKey, refreshTrigger])
useEffect(() => {
getMailList()
// --- Setup Internal Event Listener ---
const handleInternalUpdate = (event) => {
// console.log(`🔔[useEmailList] Received internal event. `, event.detail)
if (isEmpty(event.detail)) {
return false;
}
const { type, } = event.detail
if (type === 'listrow') {
loadMailListFromCache()
}
if (type === 'maillist-search-result') {
const { data, query } = event.detail
setMailList(data)
setTempBreadcrumb([{title: '查找邮件:'+query, iconIndex: 'search'}]);
}
}
internalEventEmitter.on(EMAIL_CHANNEL_NAME, handleInternalUpdate)
// --- Setup BroadcastChannel Listener ---
const channel = getEmailChangesChannel()
const handleMessage = (event) => {
// console.log(`[useEmailList] Received channel event. `, event.data)
if (isEmpty(event.data)) {
return false;
}
const { type, } = event.data
const cacheKey = isEmpty(COLI_SN) ? `dir-${VKey}` : `order-${VKey}`
if (type === 'listrow' && cacheKey === event.data.listKey) {
// cacheKey 不相同时, 不需要更新; 邮箱目录不相同
loadMailListFromCache(event.data)
}
if (type === 'maillist-search-result') {
// 搜索的结果不需要更新所有页面
// const { data } = event.detail
// setMailList(data)
}
}
channel.addEventListener('message', handleMessage)
// Cleanup
return () => {
internalEventEmitter.off(EMAIL_CHANNEL_NAME, handleInternalUpdate)
channel.removeEventListener('message', handleMessage)
}
}, [getMailList])
return { loading, isFreshData, error, mailList, tempBreadcrumb, refresh, markAsUnread, markAsProcessed, markAsDeleted }
}
const orderMailTypes = new Map([
['48001', '发送一催'],
['48002', '发送二催'],
['48003', '发送三催'],
['48004', '发送已收客人付款通知'],
['48005', '发送FAQ及PreSurvey'],
['48006', '发送降价邮件'],
['48007', '发送亚马逊津贴'],
['48008', '发送报价信'],
['48009', '提交调度'],
['48010', '发送确认信'],
['48011', '发送余款提醒信'],
['48012', '发送入境提醒'],
['48013', '首站关怀'],
['48014', '抵桂面谈'],
['48015', '末站关怀'],
['48016', '发送计划'],
['48017', '报价中'],
['48018', '以后联系'],
['48019', '成行'],
['48020', '团款收讫'],
['48021', '取消'],
['48022', '丢失'],
['48023', '已做计划'],
['48024', '一催回复'],
['48025', '二催回复'],
['48026', '第一次报价回复'],
['48027', '发送商务感谢信'],
['48028', '商务酒店房满邮件'],
['48029', '商务预订传真'],
['48030', '商务取消邮件'],
['48031', '商务单团财务表'],
['48032', '商务收款单'],
['48033', '商务退款单'],
['48034', '商务财务转帐申请'],
['48035', '商务未订先确认'],
['48036', '商务等待确认'],
['48037', '商务已确认'],
['48038', '商务已付款'],
['48039', '商务成功订单'],
['48040', '商务取消订单'],
['48041', '商务不成行订单'],
['48042', '商务已付款未出票'],
['48043', '商务已付款并出票'],
['48044', '商务无效订单'],
['48045', '问候提醒'],
['48046', '发送邮件'],
['48047', '来华一周年问候'],
['48048', '来华二周年提醒'],
['48049', 'CH Phone询问邮件'],
['48050', '订单电话销售'],
['48051', '等待付订金'],
['48052', '商务订单预订中'],
['48053', '客户需求调查'],
['48054', '发送TourCredits通知邮件'],
['48055', 'GH海外PostSurvey'],
])
export const emailTemplates = [
{ type: 'RemindOneWL', index: 1, key: '1@RemindOneWL', value: '1@RemindOneWL', label: '一催模板一,询问客人是否收到报价信' },
{ type: 'RemindOneWL', index: 2, key: '2@RemindOneWL', value: '2@RemindOneWL', label: '一催模板二,询问客人是否修改行程' },
{ type: 'divider' },
{ type: 'RemindTwoWL', index: 1, key: '1@RemindTwoWL', value: '1@RemindTwoWL', label: '二催模板一,询问客人对行程的看法' },
{ type: 'RemindTwoWL', index: 2, key: '2@RemindTwoWL', value: '2@RemindTwoWL', label: '二催模板二,表达服务的意识' },
{ type: 'divider' },
{ type: 'RemindThreeWL', index: 1, key: '1@RemindThreeWL', value: '1@RemindThreeWL', label: '三催模板三,强调价格有效期' },
];
export const emailTemplateMap = emailTemplates.reduce((acc, cur) => {
if (cur.type === 'divider') {
return acc
}
acc[cur.key] = cur
return acc
}, {});
/**
*
* @param {object} params - Parameters for the email template request.
* @param {number} [params.coli_sn] - Customer order line item serial number.
* @param {number} [params.lgc] - Language code.
* @param {number} [params.opi_sn] - Order product item serial number.
*/
export const useEmailTemplate = (templateKey, params) => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const [templateContent, setTemplateContent] = useState({ mailtype: '', mailtypeName: '', subject: '', mailcontent: '' })
const getTemplateContent = useCallback(async () => {
if (!templateKey || !Number(params.coli_sn) || !Number(params.opi_sn)) {
setTemplateContent({ mailtype: '', mailtypeName: '', subject: '', mailcontent: '' })
setLoading(false)
setError(null)
return
}
setLoading(true)
setError(null)
try {
const { index: remind_index, type: remind_type } = emailTemplateMap[templateKey] || {};
const _params = { ...params, remind_index, remind_type};
const x = await getReminderEmailTemplateAction(_params)
const lowerCaseShallow = Object.keys(x).reduce((acc, key) => ({...acc, [key.toLowerCase()]: x[key]}), {})
setTemplateContent({...lowerCaseShallow, mailtypeName: orderMailTypes.get(lowerCaseShallow.mailtype)})
} catch (networkError) {
setError(new Error(`Failed to get template content: ${networkError.message}.`))
} finally {
setLoading(false)
}
}, [templateKey, params.opi_sn, params.coli_sn, params.lgc])
useEffect(() => {
getTemplateContent()
}, [getTemplateContent])
return { loading, error, templateContent };
}
export const mailboxSystemDirs = [
{ key: 1, value: 1, label: '收件箱' },
{ key: 2, value: 2, label: '未读邮件' },
{ key: 3, value: 3, label: '已发邮件' },
{ key: 4, value: 4, label: '待发邮件' },
{ key: 5, value: 5, label: '草稿' },
{ key: 6, value: 6, label: '垃圾邮件' },
{ key: 7, value: 7, label: '已处理邮件' },
]

@ -17,7 +17,7 @@ import MobileConversation from '@/views/mobile/Conversation'
import MobileChat from '@/views/mobile/Chat'
import CallCenter from '@/views/CallCenter'
import MobileSecondHeader from '@/views/mobile/SecondHeaderWrapper'
import OrderProfile from '@/components/OrderProfile'
import CustomerProfile from '@/views/Conversations/Online/order/CustomerProfile'
import SnippetList from '@/views/accounts/SnippetList'
import GeneratePayment from '@/views/accounts/GeneratePayment'
@ -31,10 +31,6 @@ import useAuthStore from '@/stores/AuthStore'
import '@/assets/index.css'
import CustomerRelation from '@/views/customer_relation/index'
import NewEmail from '@/views/NewEmail'
import EmailDetailWindow from '@/views/EmailDetailWindow'
import { executeDailyCleanupTask, setupDailyMidnightCleanupScheduler } from '@/utils/indexedDB'
useAuthStore.getState().loadUserSession()
@ -64,7 +60,7 @@ const router = createBrowserRouter([
{
element: <MobileSecondHeader />,
children: [
{ path: 'm/order', element: <OrderProfile /> },
{ path: 'm/order', element: <CustomerProfile /> },
{ path: 'callcenter/call', element: <CallCenter /> },
{ path: 'callcenter/call/:phonenumber', element: <CallCenter /> },
],
@ -90,11 +86,6 @@ const router = createBrowserRouter([
{ path: 'customer_relation/index', element: <CustomerRelation /> },
],
},
{ path: 'email/view/:mailid', element: <EmailDetailWindow />},
{ path: 'email/:action/:quoteid/:oid/:templateKey', element: <NewEmail />},
{ path: 'email/:action/:quoteid/:oid', element: <NewEmail />},
{ path: 'email/:action/:quoteid', element: <NewEmail />},
// { path: 'email/new/0/:oid', element: <NewEmail />},
],
},
{
@ -144,13 +135,3 @@ createRoot(root).render(
</ThemeContext.Provider>
</React.Suspense>,
)
// --- Global Setup After React App Mounts ---
// This part will run once when the application script is loaded and executed.
document.addEventListener('DOMContentLoaded', () => {
console.log(`[${new Date().toLocaleTimeString()}] Application fully loaded. Initiating global daily cleanup checks.`);
executeDailyCleanupTask();
setupDailyMidnightCleanupScheduler();
});

@ -158,7 +158,7 @@ const useAuthStore = create(devtools((set, get) => ({
loadUserSession: () => {
let sessionData = window.sessionStorage.getItem('GLOBAL_SALES_LOGIN_USER')
// if (import.meta.env.DEV) sessionData ='{"userId":"155","userIdStr":"155","emailList":[],"whatsAppBusiness":"+8617607730395","whatsAppNo":null,"username":"尹诚诚","avatarUrl":"https://static-legacy.dingtalk.com/media/lADPBE1XYG_HAcDNAgDNAgA_512_512.jpg","mobile":"+86-18507832160","email":"ycc@hainatravel.com","openId":"K8BNXMf8ESSr1DzLVUrX7wiEiE","accountList":[{"OPI_SN":155,"OPI_Code":"YCC","OPI_NameCN":"尹诚诚","OPI_DEI_SN":1,"OPI_NameEN":"Yin Chengcheng"}]}'
// let sessionData ='{"userId":"155","userIdStr":"155","emailList":[],"whatsAppBusiness":"+8617607730395","whatsAppNo":null,"username":"尹诚诚","avatarUrl":"https://static-legacy.dingtalk.com/media/lADPBE1XYG_HAcDNAgDNAgA_512_512.jpg","mobile":"+86-18507832160","email":"ycc@hainatravel.com","openId":"K8BNXMf8ESSr1DzLVUrX7wiEiE","accountList":[{"OPI_SN":155,"OPI_Code":"YCC","OPI_NameCN":"尹诚诚","OPI_DEI_SN":1,"OPI_NameEN":"Yin Chengcheng"}]}'
// if (window.location.hostname === '202.103.68.93' && window.location.port === '4173' && isEmpty(sessionData)) {
// sessionData = `{"userId":"383","userIdStr":"383,609","emailList":[{"opi_sn":383,"mat_sn":760,"email":"lyj@asiahighlights.com","default":false,"backup":false},{"opi_sn":383,"mat_sn":759,"email":"lyj@chinahighlights.com","default":true,"backup":false},{"opi_sn":383,"mat_sn":758,"email":"lyj@hainatravel.com","default":false,"backup":false}],"username":"廖一军","avatarUrl":"https://static-legacy.dingtalk.com/media/lALPBDDrhXr716HNAoDNAoA_640_640.png","mobile":"+86-18777396951","email":"lyj@hainatravel.com","whatsAppBusiness":"8617458471254","openId":"iioljiPmZ4RPoOYpkFiSn7IKAiEiE","accountList":[{"OPI_SN":383,"OPI_Code":"LYJ","OPI_NameCN":"廖一军","OPI_DEI_SN":7,"OPI_NameEN":"Jimmy Liow"},{"OPI_SN":609,"OPI_Code":"LYJAH","OPI_NameCN":"廖一军ah","OPI_DEI_SN":28,"OPI_NameEN":"Jimmy Liow"}]}`

@ -1,17 +1,15 @@
import { create } from 'zustand';
import { RealTimeAPI } from '@/channel/realTimeAPI';
import { olog, isEmpty, groupBy, sortArrayByOrder, pick, sortKeys, omit, sortObjectsByKeysMap, merge } from '@/utils/commons';
import { logWebsocket, clean7DaysWebsocketLog } from '@/utils/indexedDB'
import { olog, isEmpty, groupBy, sortArrayByOrder, logWebsocket, pick, sortKeys, omit, sortObjectsByKeysMap } from '@/utils/commons';
import { receivedMsgTypeMapped, handleNotification } from '@/channel/bubbleMsgUtils';
import { fetchConversationsList, fetchTemplates, fetchConversationsSearch, UNREAD_MARK, fetchTags } from '@/actions/ConversationActions';
import { devtools } from 'zustand/middleware';
import { WS_URL, DATETIME_FORMAT } from '@/config';
import dayjs from 'dayjs';
import EmailSlice from './EmailSlice';
const replaceObjectsByKey = (arr1, arr2, key) => {
const map2 = new Map(arr2.map(ele => [ele[key], ele]));
return arr1.map(item => map2.has(item[key]) ? map2.get(item[key]) : item);
const map = new Map(arr2.map(ele => [ele[key], ele]));
return arr1.map(item => map.has(item[key]) ? map.get(item[key]) : item);
}
const sortConversationList = (list) => {
@ -179,13 +177,13 @@ const websocketSlice = (set, get) => ({
logWebsocket(data, 'I');
// olog('websocket Messages ----', data);
// console.log(data);
const { updateMessageItem, sentOrReceivedNewMessage, addGlobalNotify, setWai, addToConversationList, updateMailboxCount } = get()
const { updateMessageItem, sentOrReceivedNewMessage, addGlobalNotify, setWai } = get();
const { errcode, errmsg, result } = data;
if (!result) {
return false;
}
let resultType = result?.action || result?.type;
let resultType = result?.action || result.type;
if (errcode !== 0) {
// addError('Error Connecting to Server');
resultType = 'error';
@ -195,18 +193,10 @@ const websocketSlice = (set, get) => ({
const msgRender = receivedMsgTypeMapped[resultType].contentToRender(msgObj);
const msgUpdate = receivedMsgTypeMapped[resultType].contentToUpdate(msgObj);
// console.log('msgRender msgUpdate', msgRender, msgUpdate);
if (['email.updated', 'email.inbound.received',].includes(resultType)) {
updateMailboxCount({ opi_sn: msgObj.opi_sn })
// if (!isEmpty(msgRender)) {
// const msgNotify = receivedMsgTypeMapped[resultType].contentToNotify(msgObj);
// addGlobalNotify(msgNotify);
// }
return false;
}
if ([
'whatsapp.message.updated', 'message', 'error',
'email.updated', 'wai.message.updated',
].includes(resultType) && !isEmpty(msgUpdate)) {
].includes(resultType)) {
updateMessageItem(msgUpdate);
}
if (!isEmpty(msgRender)) {
@ -237,13 +227,6 @@ const websocketSlice = (set, get) => ({
// setWai({}); // 60s 后清空
// }, 60_000);
}
// 会话表 更新
if (['session.new', 'session.updated'].includes(resultType)
&& result.webhooksource !== 'email'
) {
const sessionList = receivedMsgTypeMapped[resultType].getMsg(result);
addToConversationList(sessionList || [], 'top')
}
// console.log('handleMessage*******************');
},
});
@ -278,17 +261,13 @@ const conversationSlice = (set, get) => ({
// 让当前会话显示在页面上
let _tmpCurrentMsgs = [];
if (currentConversation.sn) {
// _tmpCurrentMsgs = activeConversations[currentConversation.sn];
_tmpCurrentMsgs = activeConversations[currentConversation.sn];
}
const conversationsMapped = conversationsList.reduce((r, v) => ({ ...r, [`${v.sn}`]: [] }), {});
const indexCurrent = currentConversation.sn ? conversationsList.findIndex(ele => Number(ele.sn) === Number(currentConversation.sn)) : -1;
if (indexCurrent !== -1) {
const [currentElement] = conversationsList.splice(indexCurrent, 1);
conversationsList.unshift(currentElement); // Add to top
// const hasCurrent = Object.keys(conversationsMapped).findIndex(sn => Number(sn) === Number(currentConversation.sn)) !== -1;
// conversationsMapped[currentConversation.sn] = _tmpCurrentMsgs;
// conversationsList.unshift(hasCurrent ? )
// hasCurrent ? 0 : conversationsList.unshift(currentConversation);
if (currentConversation.sn) {
const hasCurrent = Object.keys(conversationsMapped).findIndex(sn => Number(sn) === Number(currentConversation.sn)) !== -1;
conversationsMapped[currentConversation.sn] = _tmpCurrentMsgs;
const _len = hasCurrent ? 0 : conversationsList.unshift(currentConversation);
}
const { topList, pageList } = sortConversationList(conversationsList);
@ -321,21 +300,16 @@ const conversationSlice = (set, get) => ({
const mergedList = position==='top' ? [...newList, ...withoutNew] : [...updateList, ...newConversations];
const mergedListMsgs = { ...newConversationsMapped, ...activeConversations, };
const needUpdateCurrent = -1 !== newList.findIndex(row => Number(row.sn) === Number(currentConversation.sn));
const updateCurrent = needUpdateCurrent ? { currentConversation: newList.find(row => Number(row.sn) === Number(currentConversation.sn)) } : {};
// 让当前会话显示在页面上
const indexCurrent = currentConversation.sn ? mergedList.findIndex(ele => Number(ele.sn) === Number(currentConversation.sn)) : -1;
if (indexCurrent !== -1 ) {
const [currentElement] = mergedList.splice(indexCurrent, 1);
mergedList.unshift(currentElement); // Add to top
// hasCurrent ? 0 : mergedList.unshift(currentConversation);
if (currentConversation.sn) {
const hasCurrent = -1 !== Object.keys(mergedListMsgs).findIndex(sn => Number(sn) === Number(currentConversation.sn));
const _len = hasCurrent ? 0 : mergedList.unshift(currentConversation);
}
const refreshTotalNotify = mergedList.reduce((r, c) => r+(c.unread_msg_count === UNREAD_MARK ? 0 : c.unread_msg_count), 0);
const { topList, pageList } = sortConversationList(mergedList)
return set((state) => ({
...updateCurrent,
topList,
pageList,
conversationsList: mergedList,
@ -452,25 +426,136 @@ const messageSlice = (set, get) => ({
targetMsgs.push(message);
}
const targetIndex = conversationsList.findIndex((ele) => String(ele.sn) === String(targetId));
let newConversations = [];
if (targetIndex !== -1) { // 'delivered'
// 更新列表的时间
conversationsList.splice(targetIndex, 1, {
...conversationsList[targetIndex],
last_received_time: message.status === 'received' ? dayjs(message.deliverTime).add(8, 'hours').format(DATETIME_FORMAT) : conversationsList[targetIndex].last_received_time,
conversation_expiretime: message?.conversation?.expireTime || conversationsList[targetIndex].conversation_expiretime || '', // 保留使用UTC时间
last_message: { ...message, source: message.msg_source },
})
} else if (targetIndex === -1) {
// 当前客户端不存在的会话
// todo: 设置为当前(在WhatsApp返回号码不一致时)
const newContact = message.msg_direction === 'outbound' ? message.to : message.from;
newConversations = [{
...conversationRow,
...message,
sn: targetId,
opi_sn: currentConversation.opi_sn, // todo: coli sn
last_received_time: message.date,
unread_msg_count: 0,
whatsapp_name: newContact, //message?.senderName || message?.sender || '',
customer_name: newContact, // message?.senderName || message?.sender || '',
conversation_expiretime: message?.conversation?.expireTime || '', // 保留使用UTC时间
whatsapp_phone_number: message.type === 'email' ? null : newContact,
show_default: message?.conversation?.name || newContact || '',
session_type: message?.conversation?.type === 'group' ? 1 : 0,
last_message: { ...message, source: message.msg_source },
channels: {
"email": message.type === 'email' ? newContact : null,
"phone_number": message.type === 'email' ? null : newContact,
"whatsapp_phone_number": message.type === 'email' ? null : newContact,
},
}];
}
const mergedList = [...newConversations, ...conversationsList]
setFilter({ loadNextPage: true });
const { topList, pageList } = sortConversationList(mergedList);
return set({
topList,
pageList,
conversationsList: mergedList,
activeConversations: { ...activeConversations, [String(targetId)]: targetMsgs },
});
},
sentOrReceivedNewMessage: (targetId, message) => {
// msgRender:
// console.log('sentOrReceivedNewMessage', targetId, message)
const { activeConversations, setFilter } = get();
const { activeConversations, conversationsList, currentConversation, totalNotify, setFilter } = get();
const targetMsgs = activeConversations[String(targetId)] || [];
const targetIndex = conversationsList.findIndex((ele) => Number(ele.sn) === Number(targetId));
const lastReceivedTime = (message.type !== 'system' && message.sender !== 'me') ? dayjs(message.date).add(8, 'hours').format(DATETIME_FORMAT) : null;
const newContact = message.msg_direction === 'outbound' ? message.to : message.from;
const newConversation =
targetIndex !== -1
? {
...conversationsList[targetIndex],
last_received_time: lastReceivedTime || conversationsList[targetIndex].last_received_time,
unread_msg_count:
Number(targetId) !== Number(currentConversation.sn) && message.sender !== 'me'
? conversationsList[targetIndex].unread_msg_count + 1
: conversationsList[targetIndex].unread_msg_count,
last_message: { ...message, source: message.msg_source },
}
: {
...conversationRow,
...message,
sn: Number(targetId),
opi_sn: message.opi_sn || currentConversation.opi_sn, // todo: coli sn
last_received_time: dayjs(message.date).add(8, 'hours').format(DATETIME_FORMAT),
unread_msg_count: message.sender === 'me' ? 0 : 1,
whatsapp_name: message?.senderName || message?.sender || '',
customer_name: message?.senderName || message?.sender || '',
whatsapp_phone_number: message.type === 'email' ? null : newContact,
show_default: message?.conversation?.name || message?.senderName || message?.sender || newContact || '',
session_type: message?.conversation?.type === 'group' ? 1 : 0,
last_message: { ...message, source: message.msg_source },
channels: {
"email": message.type === 'email' ? newContact : null,
"phone_number": message.type === 'email' ? null : newContact,
"whatsapp_phone_number": message.type === 'email' ? null : newContact,
},
};
if (targetIndex === -1) {
conversationsList.unshift(newConversation);
} else {
// if (String(targetId)!== '0') {
conversationsList.splice(targetIndex, 1);
conversationsList.unshift(newConversation);
}
// console.log('find in list, i:', targetIndex);
// console.log('find in list, chat updated and Top: \n', JSON.stringify(newConversation, null, 2));
// console.log('list updated : \n', JSON.stringify(conversationsList, null, 2));
setFilter({ loadNextPage: true });
const isCurrent = Number(targetId) === Number(currentConversation.sn);
const updatedCurrent = isCurrent
? {
...currentConversation,
last_received_time: dayjs(message.date).add(8, 'hours').format(DATETIME_FORMAT),
conversation_expiretime: dayjs(message.date).add(24, 'hours').format(DATETIME_FORMAT),
last_message: { ...message, source: message.msg_source },
}
: {...currentConversation, last_message: message,};
const { topList, pageList } = sortConversationList(conversationsList);
return set({
currentConversation: updatedCurrent,
topList,
pageList,
conversationsList: [...conversationsList],
totalNotify: totalNotify + (message.sender === 'me' ? 0 : 1),
activeConversations: { ...activeConversations, [String(targetId)]: [...targetMsgs, message] },
});
},
});
/**
* Email
*/
const emailSlice = (set, get) => ({
emailMsg: { id: -1, conversationid: '', actionId: '', order_opi: '', coli_sn: '', msgOrigin: {} },
setEmailMsg: (emailMsg) => set({ emailMsg }),
detailPopupOpen: false,
setDetailOpen: (v) => set({ detailPopupOpen: v }),
openDetail: () => set(() => ({ detailPopupOpen: true })),
closeDetail: () => set(() => ({ detailPopupOpen: false })),
})
export const useConversationStore = create(
devtools((set, get) => ({
...initialConversationState,
@ -483,7 +568,7 @@ export const useConversationStore = create(
...tagsSlice(set, get),
...filterSlice(set, get),
...globalNotifySlice(set, get),
...EmailSlice(set, get),
...emailSlice(set, get),
...waiSlice(set, get),
// state actions
@ -492,10 +577,7 @@ export const useConversationStore = create(
// side effects
fetchInitialData: async ({userId, whatsAppBusiness, ...loginUser}) => {
const { addToConversationList, setTemplates, setInitial, setTags,
initMailbox } = get();
initMailbox({ userId, dei_sn: loginUser.accountList[0].OPI_DEI_SN, opi_sn: loginUser.accountList[0].OPI_SN, userIdStr: loginUser.userIdStr })
const { addToConversationList, setTemplates, setInitial, setTags } = get();
const conversationsList = await fetchConversationsList({ opisn: userId });
addToConversationList(conversationsList);

@ -1,189 +0,0 @@
import { getEmailDirAction, getMailboxCountAction, getRootMailboxDirAction, getEmailChangesChannel, EMAIL_CHANNEL_NAME } from '@/actions/EmailActions'
import { buildTree, isEmpty, olog, sortArrayByOrder } from '@/utils/commons'
import { readIndexDB, writeIndexDB, createIndexedDBStore, clean7DaysMailboxLog } from '@/utils/indexedDB';
import { internalEventEmitter } from '@/utils/EventEmitterService';
/**
* Email
*/
const emailSlice = (set, get) => ({
emailMsg: { id: -1, conversationid: '', actionId: '', order_opi: '', coli_sn: '', msgOrigin: {} },
setEmailMsg: (emailMsg) => {
const { editorOpen } = get()
return editorOpen ? false : set({ emailMsg }) // 已经打开的不更新
},
detailPopupOpen: false,
setDetailOpen: (v) => set({ detailPopupOpen: v }),
openDetail: () => set(() => ({ detailPopupOpen: true })),
closeDetail: () => set(() => ({ detailPopupOpen: false })),
editorOpen: false,
setEditorOpen: (v) => set({ editorOpen: v }),
openEditor: () => set(() => ({ editorOpen: true })),
closeEditor: () => set(() => ({ editorOpen: false })),
// EmailEditorPopup 组件的 props
// @property {string} fromEmail - 发件人邮箱
// @property {string} fromUser - 发件人用户
// @property {string} fromOrder - 发件订单
// @property {string} toEmail - 收件人邮箱
// @property {string} conversationid - 会话ID
// @property {string} quoteid - 引用邮件ID
// @property {object} draft - 草稿
// @property {string} action - reply / forward / new / edit
// @property {string} oid - coli_sn
// @property {object} mailData - 邮件内容
// @property {string} receiverName - 收件人称呼
emailEdiorProps: new Map(),
setEditorProps: (v) => {
const { emailEdiorProps } = get()
const uniqueKey = v.quoteid || Date.now().toString(32)
const currentEditValue = { ...v, key: `${v.action}-${uniqueKey}` }
const news = new Map(emailEdiorProps).set(currentEditValue.key, currentEditValue)
for (const [key, value] of news.entries()) {
console.log(value)
}
return set((state) => ({ emailEdiorProps: news, currentEditKey: currentEditValue.key, currentEditValue }))
// return set((state) => ({ emailEdiorProps: { ...state.emailEdiorProps, ...v } }))
},
closeEditor1: (key) => {
const { emailEdiorProps } = get()
const newProps = new Map(emailEdiorProps)
newProps.delete(key)
return set(() => ({ emailEdiorProps: newProps }))
},
clearEditor: () => {
return set(() => ({ emailEdiorProps: new Map() }))
},
currentEditKey: '',
setCurrentEditKey: (key) => {
const { emailEdiorProps, setCurrentEditValue } = get()
const value = emailEdiorProps.get(key)
setCurrentEditValue(value)
return set(() => ({ currentEditKey: key }))
},
currentEditValue: {},
setCurrentEditValue: (v) => {
return set(() => ({ currentEditValue: v }))
},
// mailboxNestedDirs: new Map(),
// setMailboxNestedDirs: (opi, dirs) => {
// const { mailboxNestedDirs } = get()
// const news = mailboxNestedDirs.set(opi, dirs)
// return set(() => ({ mailboxNestedDirs: news }))
// },
currentMailboxDEI: 0,
setCurrentMailboxDEI: (id) => {
return set(() => ({ currentMailboxDEI: id }))
},
currentMailboxOPI: 0,
setCurrentMailboxOPI: (id) => {
return set(() => ({ currentMailboxOPI: id }))
},
mailboxNestedDirsActive: [],
setMailboxNestedDirsActive: (dir) => {
return set(() => ({ mailboxNestedDirsActive: dir }))
},
updateCurrentMailboxNestedDirs: (dirs) => {
const { mailboxNestedDirsActive } = get()
const _Map = new Map(mailboxNestedDirsActive.map((obj) => [obj.key, obj]))
dirs.forEach((row) => {
_Map.set(row.key, row)
})
// const _newValue = sortArrayByOrder(Array.from(_Map.values()), 'key', ['search-orders'])
const _newValue = Array.from(_Map.values())
return set(() => ({ mailboxNestedDirsActive: _newValue }))
},
mailboxActiveNode: {},
setMailboxActiveNode: (node) => {
return set(() => ({ mailboxActiveNode: node }))
},
mailboxList: [],
setMailboxList: (list) => {
return set(() => ({ mailboxList: list }))
},
mailboxActiveMAI: 0,
setMailboxActiveMAI: (mai) => {
return set(() => ({ mailboxActiveMAI: mai }))
},
mailboxActiveCOLI: 0,
setMailboxActiveCOLI: (coli) => {
return set(() => ({ mailboxActiveCOLI: coli }))
},
getOPIEmailDir: async (opi_sn = 0, userIdStr = '', refreshNow = false) => {
// console.log('🌐requesting opi dir', opi_sn, typeof opi_sn)
const { setMailboxNestedDirsActive, updateMailboxCount } = get()
const readCache = await readIndexDB(Number(opi_sn), 'dirs', 'mailbox')
// console.log(readCache);
let isNeedRefresh = refreshNow
if (!isEmpty(readCache)) {
setMailboxNestedDirsActive(readCache?.tree || [])
isNeedRefresh = refreshNow || Date.now() - readCache.treeTimestamp > 1 * 60 * 60 * 1000
// isNeedRefresh = true; // test: 0
}
if (isEmpty(readCache) || isNeedRefresh) {
// > {4} 更新
const rootTree = await getRootMailboxDirAction({ opi_sn, userIdStr: String(userIdStr || opi_sn) })
// console.log('empty', opi_sn, userIdStr, isEmpty(readCache), isNeedRefresh, rootTree);
setMailboxNestedDirsActive(rootTree)
} else {
// 只更新数量
updateMailboxCount({ opi_sn })
}
return false
},
/**
* 更新数量
* @usage 1. 邮件列表页切换用户时
* @usage 2. 收到新邮件推送时
*
*/
updateMailboxCount: async ({ opi_sn }) => {
// const { setMailboxNestedDirsActive } = get()
await getMailboxCountAction({ opi_sn })
// const readCache = await readIndexDB(Number(opi_sn), 'dirs', 'mailbox')
// if (!isEmpty(readCache)) {
// setMailboxNestedDirsActive(readCache?.tree || [])
// }
},
async initMailbox({ opi_sn, dei_sn, userIdStr }) {
olog('Initialize Mailbox ---- ')
const { currentMailboxOPI, setCurrentMailboxOPI, setCurrentMailboxDEI, getOPIEmailDir, setMailboxNestedDirsActive, } = get()
createIndexedDBStore(['dirs', 'maillist', 'listrow', 'mailinfo', 'draft'], 'mailbox')
setCurrentMailboxOPI(opi_sn)
setCurrentMailboxDEI(dei_sn)
getOPIEmailDir(opi_sn, userIdStr, true)
// --- Setup Internal Event Listener ---
internalEventEmitter.on(EMAIL_CHANNEL_NAME, async (event) => {
// console.log(`🔔Received internal event. `, event.detail)
if (event.detail && event.detail.type === 'dirs') {
const readCache = await readIndexDB(event.detail.key, 'dirs', 'mailbox')
if (!isEmpty(readCache)) {
setMailboxNestedDirsActive(readCache?.tree || [])
}
}
})
// --- Setup BroadcastChannel Listener ---
const channel = getEmailChangesChannel()
channel.addEventListener('message', async (event) => {
// console.log(`📣Received channel event. `, event.data)
if (event.data.type === 'dirs' && currentMailboxOPI === event.data.key) {
const readCache = await readIndexDB(event.data.key, 'dirs', 'mailbox')
if (!isEmpty(readCache)) {
setMailboxNestedDirsActive(readCache?.tree || [])
}
}
})
},
})
export default emailSlice

@ -12,15 +12,11 @@ export const useFormStore = create(
setMsgHistorySelectMatch: (msgHistorySelectMatch) => set({ msgHistorySelectMatch }),
msgListParams: {},
setMsgListParams: (msgListParams) => set(state => ({ msgListParams: {...state.msgListParams, ...msgListParams} })),
ImageAlbum: [],
setImageAlbum: (ImageAlbum) => set({ ImageAlbum }),
ImagePreviewSrc: '',
setImagePreviewSrc: (ImagePreviewSrc) => set({ ImagePreviewSrc }),
EmailList: [],
setEmailList: (EmailList) => set({ EmailList }),
// 订单跟踪页面
orderFollowForm: {
type: 'today',

@ -1,8 +1,8 @@
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { fetchJSON, postForm, postJSON } from '@/utils/request'
import { API_HOST, API_HOST_V3, EMAIL_HOST } from '@/config'
import { isNotEmpty, prepareUrl, uniqWith } from '@/utils/commons'
import { fetchJSON, postForm } from '@/utils/request'
import { API_HOST, EMAIL_HOST } from '@/config'
import { isNotEmpty, prepareUrl } from '@/utils/commons'
const initialState = {
orderList: [],
@ -11,247 +11,212 @@ const initialState = {
lastQuotation: {},
quotationList: [],
otherEmailList: [],
}
export const useOrderStore = create(
devtools(
(set, get) => ({
...initialState,
drawerOpen: false,
resetOrderStore: () => set(initialState),
openDrawer: () => {
set(() => ({
drawerOpen: true,
}))
},
closeDrawer: () => {
set(() => ({
drawerOpen: false,
}))
},
fetchOrderList: async (formValues, loginUser) => {
let fetchOrderUrl = `${API_HOST}/getwlorder?opisn=${loginUser.userIdStr}&otype=${formValues.type}`
const params = {}
if (formValues.type === 'advance') {
fetchOrderUrl = `${API_HOST}/getdvancedwlorder?opisn=${loginUser.userIdStr}`
const { type, ...formParams } = formValues
Object.assign(params, formParams)
};
export const useOrderStore = create(devtools((set, get) => ({
...initialState,
drawerOpen: false,
resetOrderStore: () => set(initialState),
openDrawer: () => {
set(() => ({
drawerOpen: true
}))
},
closeDrawer: () => {
set(() => ({
drawerOpen: false
}))
},
fetchOrderList: async (formValues, loginUser) => {
let fetchOrderUrl = `${API_HOST}/getwlorder?opisn=${loginUser.userIdStr}&otype=${formValues.type}`
const params = {};
if (formValues.type === 'advance') {
fetchOrderUrl = `${API_HOST}/getdvancedwlorder?opisn=${loginUser.userIdStr}`;
const { type, ...formParams } = formValues;
Object.assign(params, formParams)
}
return fetchJSON(fetchOrderUrl, params)
.then(json => {
if (json.errcode === 0) {
set(() => ({
orderList: json.result.map((order) => { return { ...order, key: order.COLI_ID } }),
}))
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
return fetchJSON(fetchOrderUrl, params).then((json) => {
if (json.errcode === 0) {
const _result = json.result.map((order) => {
return { ...order, key: order.COLI_ID }
})
const _result_unique = uniqWith(_result, (a, b) => a.COLI_SN === b.COLI_SN)
set(() => ({
orderList: _result_unique,
}))
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
},
fetchOrderDetail: (colisn) => {
return fetchJSON(`${API_HOST}/getorderinfo`, { colisn })
.then(json => {
if (json.errcode === 0 && json.result.length > 0) {
const orderResult = json.result[0]
set(() => ({
orderDetail: {...orderResult, coli_sn: colisn },
customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
quotationList: orderResult.quotes,
}))
return {
orderDetail: {...orderResult, coli_sn: colisn },
customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
quotationList: orderResult.quotes,
}
})
},
fetchOrderDetail: (colisn) => {
return fetchJSON(`${API_HOST}/getorderinfo`, { colisn }).then((json) => {
if (json.errcode === 0 && json.result.length > 0) {
const orderResult = json.result[0]
set(() => ({
orderDetail: { ...orderResult, coli_sn: colisn },
customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
// lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
// quotationList: orderResult.quotes,
}))
return {
orderDetail: { ...orderResult, coli_sn: colisn },
customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
// lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
// quotationList: orderResult.quotes,
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
appendOrderComment: async (opi_sn, coli_sn, comment) => {
const { fetchOrderDetail } = get()
const formData = new FormData()
formData.append('opi_sn', opi_sn)
formData.append('coli_sn', coli_sn)
formData.append('remark', comment)
return postForm(`${API_HOST}/remark_order`, formData)
.then(json => {
if (json.errcode === 0) {
return fetchOrderDetail(coli_sn)
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
generatePayment: async (formValues) => {
const formData = new FormData()
formData.append('descriptions', formValues.description)
formData.append('currency', formValues.currency)
formData.append('lgc', formValues.langauge)
formData.append('amount', formValues.amount)
formData.append('coli_id', formValues.orderNumber)
formData.append('wlemail', formValues.notifyEmail)
formData.append('ordertype', formValues.orderType)
formData.append('opisn', formValues.userId)
formData.append('paytype', 'SYT')
formData.append('wxzh', 'cht')
formData.append('fq', 0)
formData.append('onlyusa', 0)
formData.append('useyhm', 0)
return postForm(`${API_HOST}/generate_payment_links`, formData)
.then(json => {
if (json.errcode === 0) {
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchHistoryOrder: (userId, email, whatsappid='') => {
return fetchJSON(`${API_HOST}/query_guest_order`, { opisn: userId, whatsappid, email: email })
.then(json => {
if (json.errcode === 0) {
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
importEmailMessage: ({ orderId, orderNumber }) => {
return fetchJSON(`${API_HOST}/generate_email_msg`, { coli_sn: orderId, coli_id: orderNumber })
.then(json => {
if (json.errcode === 0) {
return json
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
batchImportEmailMessage: () => {
const { orderList } = get()
const orderPromiseList = orderList.map(order => {
return new Promise((resolve, reject) => {
fetchJSON(`${API_HOST}/generate_email_msg`, { coli_sn: order.COLI_SN, coli_id: order.COLI_ID })
.then(json => {
if (json.errcode === 0) {
resolve(json)
} else {
reject(json?.errmsg + ': ' + json.errcode)
}
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
appendOrderComment: async (opi_sn, coli_sn, comment) => {
const { fetchOrderDetail } = get()
const formData = new FormData()
formData.append('opi_sn', opi_sn)
formData.append('coli_sn', coli_sn)
formData.append('remark', comment)
return postForm(`${API_HOST}/remark_order`, formData).then((json) => {
if (json.errcode === 0) {
return fetchOrderDetail(coli_sn)
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
generatePayment: async (formValues) => {
const formData = new FormData()
formData.append('descriptions', formValues.description)
formData.append('currency', formValues.currency)
formData.append('lgc', formValues.langauge)
formData.append('amount', formValues.amount)
formData.append('coli_id', formValues.orderNumber)
formData.append('ordertype', formValues.orderType)
formData.append('opisn', formValues.userId)
formData.append('paytype', 'SYT')
formData.append('wxzh', 'cht')
formData.append('fq', 0)
formData.append('onlyusa', 0)
formData.append('useyhm', 0)
return postForm(`${API_HOST}/generate_payment_links`, formData).then((json) => {
if (json.errcode === 0) {
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchHistoryOrder: (userId, email, whatsappid = '') => {
return fetchJSON(`${API_HOST}/query_guest_order`, { opisn: userId, whatsappid, email: email }).then((json) => {
if (json.errcode === 0) {
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
importEmailMessage: ({ orderId, orderNumber }) => {
return fetchJSON(`${API_HOST}/generate_email_msg`, { coli_sn: orderId, coli_id: orderNumber }).then((json) => {
if (json.errcode === 0) {
return json
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
batchImportEmailMessage: () => {
const { orderList } = get()
const orderPromiseList = orderList.map((order) => {
return new Promise((resolve, reject) => {
fetchJSON(`${API_HOST}/generate_email_msg`, { coli_sn: order.COLI_SN, coli_id: order.COLI_ID }).then((json) => {
if (json.errcode === 0) {
resolve(json)
} else {
reject(json?.errmsg + ': ' + json.errcode)
}
})
})
})
Promise.all(orderPromiseList).then((values) => {
console.log(values)
})
},
fetchOtherEmail: (coli_sn) => {
return fetchJSON(`${EMAIL_HOST}/email_supplier`, { coli_sn }).then((json) => {
if (json.errcode === 0) {
set(() => ({
otherEmailList: json.result.MailInfo ?? [],
}))
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
updateWhatsapp: (coli_sn, number) => {
return postJSON(`${API_HOST_V3}/order_update`, {
coli_sn: coli_sn,
set: {
concat_whatsapp: number,
},
}).then((json) => {
if (json.errcode > 0) {
throw new Error(json?.errmsg + ': ' + json.errcode)
} else {
set((state) => ({
customerDetail: {
...state.customerDetail,
whatsapp_phone_number: number,
},
}))
}
})
},
updateExtraInfo: (coli_sn, extra) => {
const { orderDetail } = get()
return postJSON(`${API_HOST_V3}/order_update`, {
coli_sn: coli_sn,
set: {
extra_info: extra,
},
}).then((json) => {
if (json.errcode > 0) {
throw new Error(json?.errmsg + ': ' + json.errcode)
} else {
set((state) => ({
orderDetail: {
...state.orderDetail,
COLI_Introduction: extra,
},
}))
}
})
},
setOrderPropValue: async (colisn, propName, value) => {
if (propName === 'orderlabel') {
set((state) => ({
orderDetail: {
...state.orderDetail,
tags: value,
},
})
})
Promise.all(orderPromiseList).then((values) => {
console.log(values);
})
},
fetchOtherEmail: (coli_sn) => {
return fetchJSON(`${EMAIL_HOST}/email_supplier`, { coli_sn })
.then(json => {
if (json.errcode === 0) {
set(() => ({
otherEmailList: json.result.MailInfo ?? [],
}))
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
if (propName === 'orderstatus') {
set((state) => ({
orderDetail: {
...state.orderDetail,
states: value,
},
}))
setOrderPropValue: async (colisn, propName, value) => {
if (propName === 'orderlabel') {
set((state) => ({
orderDetail: {
...state.orderDetail,
tags: value
}
}))
}
return fetchJSON(`${API_HOST}/setorderstatus`, { colisn, stype: propName, svalue: value }).then((json) => {
if (json.errcode > 0) {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
}),
{ name: 'orderStore' },
),
)
if (propName === 'orderstatus') {
set((state) => ({
orderDetail: {
...state.orderDetail,
states: value
}
}))
}
return fetchJSON(`${API_HOST}/setorderstatus`, { colisn, stype: propName, svalue: value })
.then(json => {
if (json.errcode > 0) {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
}), { name: 'orderStore' }))
export const OrderLabelDefaultOptions = [
{ value: 240003, label: '重点', emoji: '❣️' },
{ value: 240002, label: '次重点', emoji: '❗' },
{ value: 240001, label: '一般', emoji: '' },
{ value: 240001, label: '一般', emoji: '' }
]
export const OrderLabelDefaultOptionsMapped = OrderLabelDefaultOptions.reduce((acc, cur) => {
return { ...acc, [String(cur.value)]: cur }
}, {})
}, {}) ;
export const OrderStatusDefaultOptions = [
{ value: 1, label: '新订单', emoji: '' },
@ -260,8 +225,8 @@ export const OrderStatusDefaultOptions = [
{ value: 4, label: '等待付订金', emoji: '🛒' },
{ value: 5, label: '成行', emoji: '💰' },
{ value: 6, label: '丢失', emoji: '🎈' },
// { value: 7, label: '取消', emoji: '🚫' }, // 取消要顾问确认后才能执行操作,暂时到 HT 操作
{ value: 8, label: '未报价', emoji: '' },
{ value: 7, label: '取消', emoji: '🚫' },
{ value: 8, label: '未报价', emoji: '' }
]
export const OrderStatusDefaultOptionsMapped = OrderStatusDefaultOptions.reduce((acc, cur) => {
return { ...acc, [String(cur.value)]: cur }
@ -273,27 +238,25 @@ export const OrderStatusDefaultOptionsMapped = OrderStatusDefaultOptions.reduce(
export const RemindStateDefaultOptions = [
{ value: '1', label: '一催' },
{ value: '2', label: '二催' },
{ value: '3', label: '三催' },
{ value: '3', label: '三催' }
]
/**
* @useage 订单信息: 标记状态
*/
export const remindStatusOptions = [
{ value: 1, label: '已发一催' },
{ value: 2, label: '已发二催' },
{ value: 3, label: '已发三催' },
{ value: '1', label: '已发一催' },
{ value: '2', label: '已发二催' },
{ value: '3', label: '已发三催' },
{ value: 'important', label: '重点团' },
{ value: 'sendsurvey', label: '已发 travel advisor survey' },
]
export const remindStatusOptionsMapped = remindStatusOptions.reduce((acc, cur) => {
return { ...acc, [String(cur.value)]: cur }
}, {})
];
/**
* @param {Object} params { coli_sn, remindstate }
*/
export const fetchSetRemindStateAction = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/SetRemindState`, params)
return errcode === 0 ? result : {}
}
const { errcode, result } = await fetchJSON(`${API_HOST}/SetRemindState`, params);
return errcode === 0 ? result : {};
};

@ -1,20 +0,0 @@
class EventEmitterService extends EventTarget {
constructor() {
super();
// console.log('Internal EventEmitterService created.'); // For debugging
}
emit(eventName, detail) {
this.dispatchEvent(new CustomEvent(eventName, { detail }));
}
on(eventName, handler) {
this.addEventListener(eventName, handler);
}
off(eventName, handler) {
this.removeEventListener(eventName, handler);
}
}
export const internalEventEmitter = new EventEmitterService();

@ -226,15 +226,6 @@ export function omit(object, keysToOmit) {
return Object.fromEntries(Object.entries(object).filter(([key]) => !keysToOmit.includes(key)));
}
/**
* 去除无效的值: undefined, null, '', []
* * 只删除 null undefined: flush 方法;
*/
export const omitEmpty = _object => {
Object.keys(_object).forEach(key => (_object[key] == null || _object[key] === '' || _object[key].length === 0) && delete _object[key]);
return _object;
};
/**
* 深拷贝
*/
@ -601,77 +592,66 @@ export const TagColorStyle = (tag, outerStyle = false) => {
return { color: `${color}`, ...outerStyleObj };
};
// 数组去掉重复
export function unique(arr) {
const x = new Set(arr);
return [...x];
}
export const uniqWith = (arr, fn) => arr.filter((element, index) => arr.findIndex((step) => fn(element, step)) === index);
/**
* Creates a new tree node object.
* @param {string} key - The unique identifier for the node.
* @param {string} name - The display name of the node.
* @param {string|null} parent - The key of the parent node, or null if it's a root.
* @returns {object} A plain JavaScript object representing the tree node.
*/
function createTreeNode(key, name, parent = null, keyMap={}, _raw={}) {
return {
key: key,
title: name,
parent: parent,
icon: _raw?.icon,
iconIndex: _raw?.[keyMap.iconIndex],
_raw: _raw,
children: [],
parentTitle: '',
parentIconIndex: '',
};
}
/**
* Builds a tree structure from a flat list of nodes.
* @returns {Array<object>} An array of root tree nodes.
*
*/
export const buildTree = (list, keyMap={ rootKeys: [], ignoreKeys: [] }) => {
if (!list || list.length === 0) {
return []
export const logWebsocket = (message, direction) => {
var open = indexedDB.open('LogWebsocketData', 2)
open.onupgradeneeded = function () {
var db = open.result
var store = db.createObjectStore('LogStore', { keyPath: 'id', autoIncrement: true })
}
const nodeMap = new Map()
const treeRoots = []
list.forEach((item) => {
const node = createTreeNode(item[keyMap.key], item[keyMap.name], item[keyMap.parent], keyMap, item)
nodeMap.set(item[keyMap.key], node)
})
list.forEach((item) => {
const node = nodeMap.get(item[keyMap.key])
if (keyMap.rootKeys.includes(item[keyMap.parent]) || item[keyMap.parent] === null || item[keyMap.parent] === undefined) {
// This is a root node
treeRoots.push(node)
} else {
const parentNode = nodeMap.get(item[keyMap.parent])
if (keyMap.ignoreKeys.includes(item[keyMap.parent])) {
const grandParentNode = nodeMap.get(parentNode.parent);
node.rawParent = node.parent;
node.parent = parentNode.parent;
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
grandParentNode.children.push(node)
} else if (keyMap.ignoreKeys.includes(item[keyMap.key])) {
//
open.onsuccess = function () {
var db = open.result
var tx = db.transaction('LogStore', 'readwrite')
var store = tx.objectStore('LogStore')
store.put({ direction, message, date: new Date().toLocaleString() })
tx.oncomplete = function () {
db.close()
}
}
};
export const readWebsocketLog = () => {
return new Promise((resolve, reject) => {
let openRequest = indexedDB.open('LogWebsocketData')
openRequest.onerror = function (e) {
reject('Error opening database.')
}
openRequest.onsuccess = function (e) {
let db = e.target.result
// 数据库是否存在
if (!db.objectStoreNames.contains('LogStore')) {
resolve('Database does not exist.')
return
}
else if (parentNode) {
node.parentTitle = parentNode.title;
node.parentIconIndex = parentNode.iconIndex;
parentNode.children.push(node)
} else {
console.warn(`Parent with key '${item[keyMap.parent]}' not found for node '${item[keyMap.key]}'. This node will be treated as a root.`)
treeRoots.push(node)
let transaction = db.transaction('LogStore')
let store = transaction.objectStore('LogStore')
let request = store.getAll()
request.onerror = function (e) {
reject('Error getting all records.')
}
request.onsuccess = function (e) {
let data = e.target.result
sessionStorage.setItem('websocketLogData', JSON.stringify(data))
console.log(JSON.stringify(data))
resolve(data)
}
}
})
return treeRoots
};
export const clearWebsocketLog = () => {
let openRequest = indexedDB.open('LogWebsocketData')
openRequest.onerror = function (e) {}
openRequest.onsuccess = function (e) {
let db = e.target.result
if (!db.objectStoreNames.contains('LogStore')) {
return
}
let transaction = db.transaction('LogStore', 'readwrite')
let store = transaction.objectStore('LogStore')
// Clear the store
let clearRequest = store.clear()
clearRequest.onerror = function (e) {}
clearRequest.onsuccess = function (e) {}
}
}

@ -1,586 +0,0 @@
import { isEmpty } from './commons';
/**
*
*/
/**
* 数据库版本
* ! 每次涉及indexedDB的更新都要往上+1
* @type {number}
*/
const INDEXED_DB_VERSION = 5;
export const logWebsocket = (message, direction) => {
var open = indexedDB.open('LogWebsocketData', INDEXED_DB_VERSION)
open.onupgradeneeded = function () {
var db = open.result
// 数据库是否存在
if (!db.objectStoreNames.contains('LogStore')) {
var store = db.createObjectStore('LogStore', { keyPath: 'id', autoIncrement: true })
store.createIndex('timestamp', 'timestamp', { unique: false })
} else {
const logStore = open.transaction.objectStore('LogStore')
if (!logStore.indexNames.contains('timestamp')) {
logStore.createIndex('timestamp', 'timestamp', { unique: false })
}
}
}
open.onsuccess = function () {
var db = open.result
var tx = db.transaction('LogStore', 'readwrite')
var store = tx.objectStore('LogStore')
store.put({ direction, message, _date: new Date().toLocaleString(), timestamp: Date.now() })
tx.oncomplete = function () {
db.close()
}
}
};
export const readWebsocketLog = (limit = 20) => {
return new Promise((resolve, reject) => {
let openRequest = indexedDB.open('LogWebsocketData')
openRequest.onupgradeneeded = function () {
var db = openRequest.result
// 数据库是否存在
if (!db.objectStoreNames.contains('LogStore')) {
var store = db.createObjectStore('LogStore', { keyPath: 'id', autoIncrement: true })
store.createIndex('timestamp', 'timestamp', { unique: false })
} else {
const logStore = openRequest.transaction.objectStore('LogStore')
if (!logStore.indexNames.contains('timestamp')) {
logStore.createIndex('timestamp', 'timestamp', { unique: false })
}
}
}
openRequest.onerror = function (e) {
reject('Error opening database.')
}
openRequest.onsuccess = function (e) {
let db = e.target.result
// 数据库是否存在
if (!db.objectStoreNames.contains('LogStore')) {
resolve('Database does not exist.')
return
}
let transaction = db.transaction('LogStore', 'readonly')
let store = transaction.objectStore('LogStore')
const request = store.openCursor(null, 'prev'); // 从后往前
const results = [];
let count = 0;
request.onerror = function (e) {
reject('Error getting records.')
}
request.onsuccess = function (e) {
const cursor = e.target.result
if (cursor) {
if (count < limit) {
results.unshift(cursor.value)
count++
cursor.continue()
} else {
console.log(JSON.stringify(results))
resolve(results)
}
} else {
console.log(JSON.stringify(results))
resolve(results)
}
}
}
})
};
/**
* @deprecated
*/
export const clearWebsocketLog = () => {
let openRequest = indexedDB.open('LogWebsocketData')
openRequest.onerror = function (e) {}
openRequest.onsuccess = function (e) {
let db = e.target.result
if (!db.objectStoreNames.contains('LogStore')) {
return
}
let transaction = db.transaction('LogStore', 'readwrite')
let store = transaction.objectStore('LogStore')
// Clear the store
let clearRequest = store.clear()
clearRequest.onerror = function (e) {}
clearRequest.onsuccess = function (e) {}
}
}
export const createIndexedDBStore = (tables, database) => {
var open = indexedDB.open(database, INDEXED_DB_VERSION)
open.onupgradeneeded = function () {
// console.log('createIndexedDBStore onupgradeneeded', database, )
var db = open.result
// 数据库是否存在
for (const table of tables) {
if (!db.objectStoreNames.contains(table)) {
var store = db.createObjectStore(table, { keyPath: 'key' })
store.createIndex('timestamp', 'timestamp', { unique: false })
} else {
const objectStore = open.transaction.objectStore(table)
if (!objectStore.indexNames.contains('timestamp')) {
objectStore.createIndex('timestamp', 'timestamp', { unique: false })
}
}
}
}
};
export const writeIndexDB = (rows, table, database) => {
var open = indexedDB.open(database, INDEXED_DB_VERSION)
open.onupgradeneeded = function () {
// console.log('readIndexDB onupgradeneeded', table, )
var db = open.result
// 数据库是否存在
if (!db.objectStoreNames.contains(table)) {
var store = db.createObjectStore(table, { keyPath: 'key' })
store.createIndex('timestamp', 'timestamp', { unique: false })
} else {
const objectStore = open.transaction.objectStore(table)
if (!objectStore.indexNames.contains('timestamp')) {
objectStore.createIndex('timestamp', 'timestamp', { unique: false })
}
}
}
open.onsuccess = function () {
var db = open.result
// 数据库是否存在
if (!db.objectStoreNames.contains(table)) {
console.warn(`writeIndexDB > Database does not exist.`, table);
return
}
var tx = db.transaction(table, 'readwrite')
var store = tx.objectStore(table)
rows.forEach(row => {
store.put({ ...row, _date: new Date().toLocaleString(), timestamp: Date.now() })
});
tx.oncomplete = function () {
db.close()
}
}
};
/**
* Reads data from an IndexedDB object store.
* It can read a single record by key, multiple records by an array of keys, or all records.
*
* @param {string|string[]|null} keys - The key(s) to read.
* - If `string`: Reads a single record and returns the data object directly.
* - If `string[]`: Reads multiple records and returns a Map of `rowkey` to `data` objects.
* - If `null` or `undefined` or `empty string/array`: Reads all records and returns a Map of `rowkey` to `data` objects.
* @param {string} table - The name of the IndexedDB object store (table).
* @param {string} database - The name of the IndexedDB database.
* @returns {Promise<any|Map<string, any>>} A promise that resolves with the data.
* - Single key: Resolves with the data object or `undefined` if not found.
* - Array of keys or All records: Resolves with a `Map` where keys are rowkeys and values are data objects.
* The Map will be empty if no records are found.
* - Rejects if there's an error opening the database or during the transaction.
*/
export const readIndexDB = (keys=null, table, database) => {
return new Promise((resolve, reject) => {
let openRequest = indexedDB.open(database)
openRequest.onupgradeneeded = function () {
// console.log('readIndexDB onupgradeneeded', table, )
var db = openRequest.result
// 数据库是否存在
if (!db.objectStoreNames.contains(table)) {
var store = db.createObjectStore(table, { keyPath: 'key' })
store.createIndex('timestamp', 'timestamp', { unique: false })
} else {
const logStore = openRequest.transaction.objectStore(table)
if (!logStore.indexNames.contains('timestamp')) {
logStore.createIndex('timestamp', 'timestamp', { unique: false })
}
}
}
openRequest.onerror = function (e) {
console.error(`Error opening database.`, table, e)
reject('Error opening database.')
}
openRequest.onsuccess = function (e) {
let db = e.target.result
// 数据库是否存在
if (!db.objectStoreNames.contains(table)) {
console.warn(`readIndexDB > Database does not exist.`, table);
resolve();
return
}
let transaction = db.transaction(table, 'readonly')
let store = transaction.objectStore(table)
// read by key
// Handle array of keys
if (Array.isArray(keys) && keys.length > 0) {
const promises = keys.map(key => {
return new Promise((innerResolve) => {
const getRequest = store.get(key);
getRequest.onsuccess = (event) => {
const result = event.target.result;
if (result) {
// console.log(`💾Found record with key ${key}:`, result);
innerResolve([key, result]); // Resolve with [key, data] tuple
} else {
// console.log(`No record found with key ${key}.`);
innerResolve(void 0); // Resolve with undefined for non-existent keys
}
};
getRequest.onerror = (event) => {
console.error(`Error getting record with key ${key}:`, event.target.error);
innerResolve(undefined); // Resolve with undefined on error, or innerReject if you want to fail fast
};
});
});
Promise.all(promises)
.then(results => {
const resultMap = new Map();
results.forEach(item => {
if (item !== undefined) {
resultMap.set(item[0], item[1]); // item[0] is key, item[1] is data
}
});
resolve(resultMap);
})
.catch(error => {
console.error('Error during batch read:', error);
reject(error); // Reject the main promise if Promise.all encounters an error
});
} else if (!isEmpty(keys)) { // Handle single key
const getRequest = store.get(keys);
getRequest.onsuccess = (event) => {
const result = event.target.result;
if (result) {
// console.log(`💾Found record with key ${keys}:`, result);
resolve(result);
} else {
// console.log(`No record found with key ${keys}.`);
resolve();
}
};
getRequest.onerror = (event) => {
console.error(`Error getting record with key ${keys}:`, event.target.error);
reject(event.target.error);
};
} else { // Handle read all
const getAllRequest = store.getAll();
getAllRequest.onsuccess = (event) => {
const allData = event.target.result;
const resultMap = new Map();
if (allData && allData.length > 0) {
allData.forEach(item => {
resultMap.set(item.key, item);
});
// console.log(`💾Found all records:`, resultMap);
resolve(resultMap);
} else {
// console.log(`No records found.`);
resolve(resultMap); // Resolve with an empty Map if no records
}
};
getAllRequest.onerror = (event) => {
console.error(`Error getting all records:`, event.target.error);
reject(event.target.error);
};
}
}
})
};
export const deleteIndexDBbyKey = (keys=null, table, database) => {
return new Promise((resolve, reject) => {
var open = indexedDB.open(database, INDEXED_DB_VERSION)
open.onupgradeneeded = function () {
// var db = open.result
// // 数据库是否存在
// if (!db.objectStoreNames.contains(table)) {
// var store = db.createObjectStore(table, { keyPath: 'id', autoIncrement: true })
// }
}
open.onsuccess = function (e) {
let db = e.target.result
// 数据库是否存在
if (!db.objectStoreNames.contains(table)) {
console.warn('deleteIndexDBbyKey > Database does not exist.', table)
resolve();
return
}
var tx = db.transaction(table, 'readwrite')
var store = tx.objectStore(table)
if (Array.isArray(keys) && keys.length > 0) {
const promises = keys.map((key) => {
return new Promise((innerResolve) => {
const delRequest = store.delete(key)
delRequest.onsuccess = (event) => {
const result = event.target.result
if (result) {
innerResolve()
} else {
innerResolve(void 0) // Resolve with undefined for non-existent keys
}
}
delRequest.onerror = (event) => {
innerResolve(undefined)
}
})
})
Promise.allSettled(promises)
.then((results) => {
resolve(results)
})
.catch((error) => {
reject(error)
})
} else if (!isEmpty(keys)) { // Handle single key
const delRequest = store.delete(keys);
delRequest.onsuccess = (event) => {
const result = event.target.result;
if (result) {
resolve(result);
} else {
resolve();
}
};
delRequest.onerror = (event) => {
reject(event.target.error);
};
} else {
// 删除所有
let clearRequest = store.clear()
clearRequest.onsuccess = function (e) {
resolve(e.target.result)
}
clearRequest.onerror = function (e) {
reject(e.target.error)
}
}
tx.oncomplete = function () {
db.close()
}
}
})
};
function cleanOldData(database, storeNames=[], dateKey = 'timestamp', keySet = { keyPath: 'key' }) {
return function (daysToKeep = 7) {
return new Promise((resolve, reject) => {
let deletedCount = 0
const recordsToDelete = new Set()
let openRequest = indexedDB.open(database, INDEXED_DB_VERSION)
openRequest.onupgradeneeded = function () {
// console.log('----cleanOldData onupgradeneeded----')
var db = openRequest.result
storeNames.forEach(storeName => {
// 数据库是否存在
if (!db.objectStoreNames.contains(storeName)) {
var store = db.createObjectStore(storeName, keySet)
// var store = db.createObjectStore(storeName, { keyPath: 'id', autoIncrement: true })
store.createIndex('timestamp', 'timestamp', { unique: false })
} else {
const logStore = openRequest.transaction.objectStore(storeName)
if (!logStore.indexNames.contains('timestamp')) {
logStore.createIndex('timestamp', 'timestamp', { unique: false })
}
}
})
}
openRequest.onsuccess = function (e) {
let db = e.target.result
// 数据库是否存在
// if (!db.objectStoreNames.contains(storeName)) {
// resolve('Database does not exist.')
// return
// }
// Calculate the cutoff timestamp for "X days ago"
const cutoffTimestamp = Date.now() - daysToKeep * 24 * 60 * 60 * 1000
const objectStoreNames = isEmpty(storeNames) ? db.objectStoreNames : storeNames
if (!isEmpty(objectStoreNames)) {
const objectStores = Array.from(objectStoreNames).map((storeName) => db.transaction([storeName], 'readwrite').objectStore(storeName))
for (const objectStore of objectStores) {
// Identify old data using the date index and primary key ID
if (!objectStore.indexNames.contains(`${dateKey}`)) {
// Clear the store
let clearRequest = objectStore.clear()
console.log(`Cleanup complete. clear ${objectStore.name} records.`)
resolve()
clearRequest.onerror = function (e) {}
clearRequest.onsuccess = function (e) {}
return
}
// Get records older than 'daysToKeep' using the index
const dateIndex = objectStore.index(`${dateKey}`)
const dateRange = IDBKeyRange.upperBound(cutoffTimestamp, false) // Get keys < cutoffTimestamp (strictly older)
const dateCursorRequest = dateIndex.openCursor(dateRange)
dateCursorRequest.onsuccess = (event) => {
const cursor = event.target.result
if (cursor) {
recordsToDelete.add(cursor.primaryKey) // Add the primary key of the record to the set
cursor.continue()
} else {
const storeName = objectStore.name;
// Delete identified data in a new transaction
const deleteTransaction = db.transaction([storeName], 'readwrite')
const deleteObjectStore = deleteTransaction.objectStore(storeName)
deleteTransaction.oncomplete = () => {
console.log(`Cleanup complete. Deleted ${deletedCount} records in ${database}.${storeName}.`)
resolve(deletedCount)
}
deleteTransaction.onerror = (event) => {
console.error('Deletion transaction error:', event.target.error)
reject(event.target.error)
}
// Convert Set to Array for forEach
Array.from(recordsToDelete).forEach((key) => {
const deleteRequest = deleteObjectStore.delete(key)
deleteRequest.onsuccess = () => {
deletedCount++
}
deleteRequest.onerror = (event) => {
console.warn(`Failed to delete record with key ${key}:`, event.target.error)
}
})
}
}
dateCursorRequest.onerror = (event) => {
console.error('Error opening date cursor for deletion:', event.target.error)
reject(event.target.error)
}
}
} else {
console.warn('cleanOldData: No data to delete.', database);
}
}
openRequest.onerror = function (e) {
reject('Error opening database:'+database, e)
}
})
}
}
export const clean7DaysWebsocketLog = cleanOldData('LogWebsocketData', ['LogStore'], 'timestamp', { keyPath: 'id', autoIncrement: true });
export const clean7DaysMailboxLog = cleanOldData('mailbox', ['dirs', 'maillist', 'listrow', 'mailinfo', 'draft']);
/**
* 缓存清除策略: 清理7天前的
* - 每次进入
* - 每天半夜
*/
export const LAST_SCHEDULED_CLEANUP_DAY_KEY = 'lastScheduledCleanupDay'; // For tracking scheduling
export const LAST_EXECUTED_CLEANUP_DAY_KEY = 'lastExecutedCleanupDay'; // For tracking actual execution
let cleanupTimeoutId = null; // To store the ID of the setTimeout
/**
* Determines if the cleanup needs to be scheduled for today.
* This is based on when it was *last scheduled* to prevent re-scheduling
* if the app was merely refreshed within the same day.
* @returns {boolean} True if a new schedule for today is needed.
*/
function shouldScheduleForToday() {
const lastScheduledDay = localStorage.getItem(LAST_SCHEDULED_CLEANUP_DAY_KEY);
const today = new Date().toDateString(); // e.g., "Fri Jun 13 2025"
return !lastScheduledDay || lastScheduledDay !== today;
}
/**
* Determines if the cleanup was already *executed* today.
* This is to prevent running the cleanup task multiple times in one day
* if the app stays open past midnight or if it is refreshed.
* @returns {boolean} True if the cleanup has not executed today.
*/
function hasCleanupExecutedToday() {
const lastExecutedDay = localStorage.getItem(LAST_EXECUTED_CLEANUP_DAY_KEY);
const today = new Date().toDateString();
return lastExecutedDay === today;
}
/**
* Executes the cleanup and updates the last execution timestamp.
* This function is designed to be called via requestIdleCallback.
*/
export async function executeDailyCleanupTask() {
// const lastExecutedDay = localStorage.getItem(LAST_EXECUTED_CLEANUP_DAY_KEY)
const today = new Date().toDateString()
if (!hasCleanupExecutedToday()) {
if ('requestIdleCallback' in window) {
// console.log(`[${new Date().toLocaleTimeString()}] Scheduling cleanup via requestIdleCallback for execution.`);
requestIdleCallback(
async (deadline) => {
console.log(`[${new Date().toLocaleTimeString()}] Running scheduled cleanup. Time remaining: ${deadline.timeRemaining().toFixed(2)}ms, Did timeout: ${deadline.didTimeout}`)
try {
await clean7DaysMailboxLog()
await clean7DaysWebsocketLog()
// Mark that cleanup was successfully executed for today
localStorage.setItem(LAST_EXECUTED_CLEANUP_DAY_KEY, today)
console.log('Daily cleanup marked as executed for today.')
} catch (error) {
console.error('Error during scheduled cleanup execution:', error)
}
},
{ timeout: 5000 },
) // Give it up to 5 seconds to find idle time
} else {
console.warn('requestIdleCallback not supported. Executing cleanup directly (might cause jank).')
// Fallback for very old browsers: run directly.
try {
await clean7DaysMailboxLog()
await clean7DaysWebsocketLog()
localStorage.setItem(LAST_EXECUTED_CLEANUP_DAY_KEY, today)
console.log('Daily cleanup marked as executed for today (without rIC).')
} catch (error) {
console.error('Error during direct cleanup execution:', error)
}
}
} else {
console.log(`[${new Date().toLocaleTimeString()}] Cleanup already executed today.`)
}
}
/**
* Initiates or re-initiates the daily midnight cleanup scheduler.
* This function calls itself recursively to set up the next day's schedule.
*/
export function setupDailyMidnightCleanupScheduler() {
if (cleanupTimeoutId) {
clearTimeout(cleanupTimeoutId)
cleanupTimeoutId = null
}
const now = new Date()
const midnight = new Date(now)
// Set to midnight (00:00:00)
midnight.setDate(now.getDate() + 1)
midnight.setHours(0, 0, 0, 0)
const msToMidnight = midnight.getTime() - now.getTime()
console.log(`[${new Date().toLocaleTimeString()}] Scheduling next daily cleanup at ${midnight.toLocaleTimeString()}, in ${msToMidnight / (1000 * 60 * 60)} hours.`)
// Set the timeout for the next midnight
cleanupTimeoutId = setTimeout(async () => {
console.log(`[${new Date().toLocaleTimeString()}] Midnight trigger fired.`)
if (!hasCleanupExecutedToday()) {
await executeDailyCleanupTask()
} else {
console.log(`[${new Date().toLocaleTimeString()}] Cleanup already executed today, skipping re-execution.`)
}
setupDailyMidnightCleanupScheduler()
}, msToMidnight)
}

@ -1,5 +1,4 @@
import { loadScript } from '@/utils/commons'
import { readWebsocketLog } from '@/utils/indexedDB'
import { loadScript, readWebsocketLog } from '@/utils/commons'
import { BUILD_VERSION, BUILD_DATE } from '@/config'
export const loadPageSpy = (title) => {

@ -11,11 +11,11 @@ import {
FloatButton,
theme,
} from 'antd'
import { AudioOutlined, AudioTwoTone, BugOutlined, CustomerServiceOutlined } from '@ant-design/icons'
import { BugOutlined, CustomerServiceOutlined } from '@ant-design/icons'
import zhLocale from 'antd/locale/zh_CN'
import 'dayjs/locale/zh-cn'
import { useEffect } from 'react'
import { Link, NavLink, Outlet, useHref, useNavigate } from 'react-router-dom'
import { Outlet, useHref, useNavigate } from 'react-router-dom'
import { appendRequestHeader } from '@/utils/request'
import { loadPageSpy } from '@/utils/pagespy'
@ -24,10 +24,8 @@ import '@/assets/App.css'
import 'react-chat-elements/dist/main.css'
import EmailFetch from './Conversations/Online/Components/EmailFetch'
import FetchEmailWorker from './../workers/fetchEmailWorker?worker&url'
import { readWebsocketLog } from '@/utils/indexedDB'
import { clearWebsocketLog, readWebsocketLog } from '@/utils/commons'
import { useGlobalNotify } from '@/hooks/useGlobalNotify'
import GeneratePaymentDrawer from './Conversations/Online/Components/GeneratePaymentDrawer'
import GenerateAutoDocDrawer from './Conversations/Online/Components/GenerateAutoDocDrawer'
// const fetchEmailWorkerURL = new URL('/src/workers/fetchEmailWorker.js', import.meta.url);
const fetchEmailWorker = new Worker(FetchEmailWorker, { type: 'module' });
@ -103,7 +101,7 @@ function AuthApp() {
endTime: now,
})
messageApi.info('Success')
// clearWebsocketLog()
clearWebsocketLog()
sendNotify()
} catch (error) {
messageApi.error('Failure')
@ -122,8 +120,6 @@ function AuthApp() {
) !== null
const floatButtonLineEnd = isMobileApp ? 0 : 24
const floatTrigger = isMobileApp ? 'click' : null
useEffect(() => {
if (needToLogin) {
@ -151,12 +147,10 @@ function AuthApp() {
<ErrorBoundary>
<FloatButton.Group
shape='square'
placement={'left'}
trigger={floatTrigger}
trigger='click'
style={{
insetInlineEnd: floatButtonLineEnd,
insetBlockEnd: floatButtonLineEnd,
flexDirection: 'row',
}}
icon={<CustomerServiceOutlined />}
>
@ -189,8 +183,6 @@ function AuthApp() {
</button>
</form>
</dialog>
<GeneratePaymentDrawer />
<GenerateAutoDocDrawer />
</ErrorBoundary>
</AntApp>
</ConfigProvider>

@ -1,5 +1,5 @@
import { useCallback, useState, useEffect } from "react";
import { Grid, Divider, Layout, Flex, Spin, Input, Col, Row, List, Typography, Alert } from "antd";
import { Grid, Divider, Layout, Flex, Spin, Input, Col, Row, List, Typography } from "antd";
import { PhoneOutlined, CustomerServiceOutlined, AudioOutlined } from "@ant-design/icons";
import { useParams, useHref, useNavigate } from "react-router-dom";
import { isEmpty } from "@/utils/commons";
@ -50,15 +50,9 @@ const CallCenter = props => {
setPhone_number(e.target.value);
}}></Input.Search>
</Col>
<Col md={24} lg={8} xxl={9}>
<Alert message={'不支持拨打中国大陆(+86)号码'} type="info" showIcon />
</Col>
</Row>
<Row gutter={16}>
<Col md={24} lg={8} xxl={9}></Col>
<Col md={24} lg={8} xxl={6}>
</Col>
</Row>
</Row>
<Divider plain orientation="left" className="mb-0"></Divider>
<List header={<Typography.Text strong>Console Logs</Typography.Text>} bordered dataSource={logs} renderItem={item => <List.Item>{item}</List.Item>} />
</>

@ -9,14 +9,12 @@ import ImageAlbumPreview from './Conversations/History/ImageAlumPreview';
import { flush, pick } from '@/utils/commons';
import { fetchConversationsSearch, CONVERSATION_PAGE_SIZE } from '@/actions/ConversationActions';
import EmailDetail from './Conversations/Online/Components/EmailDetail';
import SupplierEmailDrawer from './Conversations/Online/Components/EmailListDrawer';
const { Sider, Content } = Layout;
const Index = (props) => {
const [formValues, setFormValues] = useFormStore((state) => [state.chatHistoryForm, state.setChatHistoryForm]);
const [selectedConversation, setSelectedConversation] = useFormStore((state) => [state.chatHistorySelectChat, state.setChatHistorySelectChat]);
const [EmailList, ] = useFormStore((state) => [state.EmailList, ]);
const [conversationsListLoading, setConversationsListLoading] = useState(false);
const [conversationsList, setConversationsList] = useState([]);
@ -51,15 +49,9 @@ const Index = (props) => {
const [openEmailDetail, setOpenEmailDetail] = useState(false);
const [emailDetail, setEmailDetail] = useState({});
const [initialPosition, setInitialPosition] = useState({})
const [initialSize, setInitialSize] = useState({})
const [emailItem, setEmailItem] = useState({});
const onOpenEmail = (emailMsg) => {
// setOpenEmailDetail(true);
// setEmailDetail({...emailMsg, order_opi: Number(selectedConversation?.opi_sn || 0)});
// console.log(emailMsg);
setEmailItem({ MAI_SN: emailMsg.msgtext?.email?.mai_sn, MAI_Subject: emailMsg.msgtext?.email?.subject, SenderReceiver: '', MAI_SendDate: '' })
setOpenEmailDetail(true);
setEmailDetail({...emailMsg, order_opi: Number(selectedConversation?.opi_sn || 0)});
}
return (
@ -76,8 +68,7 @@ const Index = (props) => {
<MessagesList onOpenEmail={onOpenEmail} />
</Flex>
<ImageAlbumPreview />
<EmailDetail open={openEmailDetail} setOpen={setOpenEmailDetail} emailMsg={emailDetail} key={`history-email-detail-${emailDetail.id}`} disabled {...{initialPosition, initialSize, setInitialPosition, setInitialSize}} />
<SupplierEmailDrawer showExpandBtn={false} list={EmailList} opi_sn={selectedConversation?.opi_sn} currentConversationID={selectedConversation?.sn} oid={selectedConversation?.coli_sn} emailItem={emailItem} />
<EmailDetail open={openEmailDetail} setOpen={setOpenEmailDetail} emailMsg={emailDetail} key={`history-email-detail-${emailDetail.id}`} disabled />
</Content>
</Layout>
</>

@ -1,17 +1,17 @@
import { useEffect, useState } from 'react';
import { Layout, Spin, Button } from 'antd';
import { RightCircleOutlined, RightOutlined, ReloadOutlined, MenuFoldOutlined, MenuUnfoldOutlined, LeftOutlined } from '@ant-design/icons';
import { RightCircleOutlined, RightOutlined, ReloadOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
// import { useParams, useNavigate } from 'react-router-dom';
import MessagesHeader from './Conversations/Online/MessagesHeader';
import MessagesWrapper from './Conversations/Online/MessagesWrapper';
import InputComposer from './Conversations/Online/Input/InputComposer';
import ConversationsList from './Conversations/Online/ConversationsList';
import OrderProfile from '@/components/OrderProfile'
import CustomerProfile from './Conversations/Online/order/CustomerProfile';
// import { useAuthContext } from '@/stores/AuthContext';
// import useConversationStore from '@/stores/ConversationStore';
import ReplyWrapper from './Conversations/Online/ReplyWrapper';
import useConversationStore from '@/stores/ConversationStore';
import { useShallow } from 'zustand/react/shallow';
import './Conversations/Conversations.css';
import EmailEditorPopup from './Conversations/Online/Input/EmailEditorPopup';
const { Sider, Content, Header, Footer } = Layout;
@ -21,10 +21,7 @@ const { Sider, Content, Header, Footer } = Layout;
const ChatWindow = () => {
const [collapsedLeft, setCollapsedLeft] = useState(false);
const [collapsedRight, setCollapsedRight] = useState(true);
const currentOrder = useConversationStore(useShallow(state => state.currentConversation?.coli_sn || ""));
const [collapsedRight, setCollapsedRight] = useState(false);
return (
<>
@ -40,7 +37,7 @@ const ChatWindow = () => {
collapsed={false}
onBreakpoint={(broken) => {
// setCollapsedLeft(broken)
// setCollapsedRight(broken)
setCollapsedRight(broken)
}}
trigger={null}>
<ConversationsList />
@ -52,7 +49,7 @@ const ChatWindow = () => {
{/* <Button type='text' icon={collapsedLeft ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} onClick={() => setCollapsedLeft(!collapsedLeft)} className=' rounded-none rounded-l' /> */}
<MessagesHeader />
{/* <Button type='text' icon={<ReloadOutlined />} onClick={() => setCollapsedRight(!collapsedRight)} className='' title='最新消息记录' /> */}
<Button type='text' icon={collapsedRight ? <RightOutlined /> : <LeftOutlined />} onClick={() => setCollapsedRight(!collapsedRight)} className=' rounded-none rounded-r' />
<Button type='text' icon={collapsedRight ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />} onClick={() => setCollapsedRight(!collapsedRight)} className=' rounded-none rounded-r' />
</Header>
<Content className="flex-grow bg-whatsapp-bg relative" >
<MessagesWrapper />
@ -75,10 +72,9 @@ const ChatWindow = () => {
collapsedWidth={0}
trigger={null}
collapsed={collapsedRight}>
<OrderProfile coliSN={currentOrder} />
<CustomerProfile />
</Sider>
</Layout>
<EmailEditorPopup key='email-editor-online' />
</>
);
};

@ -103,7 +103,7 @@ const MergeConversationTo = ({ currentWAID, opi_sn, ...props }) => {
setOpen(false);
formInstance?.resetFields();
}}
destroyOnHidden
destroyOnClose
onOk={async () => {
try {
const values = await formInstance?.validateFields();

@ -1,15 +1,14 @@
import { useRef, useEffect, useState, forwardRef, memo } from 'react';
import { App, Flex, List, Button, Image } from 'antd';
import { App, Flex, List, Button, } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { MessageBox } from 'react-chat-elements';
import { MESSAGE_PAGE_SIZE, fetchMessagesHistory } from '@/actions/ConversationActions';
import useFormStore from '@/stores/FormStore';
import { isEmpty, stringToColour, groupBy, isNotEmpty, TagColorStyle } from '@/utils/commons';
import { isEmpty, stringToColour, groupBy, isNotEmpty } from '@/utils/commons';
import { useShallow } from 'zustand/react/shallow';
import MergeConversationTo from './MergeConversationTo';
import BubbleIM from '../Online/Components/BubbleIM';
import BubbleEmail from '../Online/Components/BubbleEmail';
import { ERROR_IMG, POPUP_FEATURES } from '@/config';
const BIG_PAGE_SIZE = MESSAGE_PAGE_SIZE * 20;
const MessagesList = ({ ...listProps }) => {
@ -20,7 +19,6 @@ const MessagesList = ({ ...listProps }) => {
const [paramsForMsgList, setParamsForMsgList] = useFormStore((state) => [state.msgListParams, state.setMsgListParams]);
const [selectMatch, setSelectedMatch] = useFormStore((state) => [state.msgHistorySelectMatch, state.setMsgHistorySelectMatch]);
const [setImageAlbumList, setImagePreviewSrc] = useFormStore(useShallow((state) => [state.setImageAlbum, state.setImagePreviewSrc]));
const [ setEmailList] = useFormStore(useShallow((state) => [ state.setEmailList]));
const [chatItemMessages, setChatItemMessages] = useState([]);
const [messageListPreLoading, setMessageListPreLoading] = useState(false);
@ -111,8 +109,6 @@ const MessagesList = ({ ...listProps }) => {
// setParamsForMsgList({ pretime: chatItemMessages[0].msgtime, lasttime: chatItemMessages[chatItemMessages.length - 1].msgtime });
const album = chatItemMessages.filter((ele) => ele.whatsapp_msg_type === 'image').map((ele) => ele.data.uri);
setImageAlbumList(album);
const emailList = chatItemMessages.filter((ele) => ele.msg_source === 'email').map(ele => ({...ele, MAI_SN: ele.msgtext?.email?.mai_sn, MAI_Subject: ele.msgtext?.email?.subject, SenderReceiver: ele.from, MAI_SendDate: ele.msgtime, Direction: ele.msg_direction === 'inbound' ? '收' : '发' })).reverse();
setEmailList(emailList);
}
return () => {};
}, [chatItemMessages]);
@ -177,7 +173,7 @@ const MessagesList = ({ ...listProps }) => {
{headerObj ? (
<div className='text-neutral-500 text-center'>
{'text' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <div>{headerObj.text}</div>}
{'image' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <Image src={headerObj.parameters[0].image.link} height={100} fallback={ERROR_IMG}></Image>}
{'image' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <img src={headerObj.parameters[0].image.link} height={100}></img>}
{['document', 'video'].includes((headerObj?.parameters?.[0]?.type || '').toLowerCase()) && (
<a href={headerObj.parameters[0][headerObj.parameters[0].type].link} target='_blank' key={headerObj.format} rel='noreferrer' className='text-sm'>
[&nbsp;{headerObj.parameters[0].type}&nbsp;]
@ -215,7 +211,7 @@ const MessagesList = ({ ...listProps }) => {
return false;
case 'document':
window.open(msg.data.link || msg.data.uri, msg.data.uri, POPUP_FEATURES);
window.open(msg.data.link || msg.data.uri, '_blank', 'noopener,noreferrer');
return false;
default:
@ -289,7 +285,7 @@ const MessagesList = ({ ...listProps }) => {
<div key={'msg-prefix'} className='border-dashed border-0 border-t border-slate-300 text-slate-600 space-x-2 emoji ' style={{backgroundColor: 'unset'}}>
<span
className={`p-1 rounded-b ${message.msg_direction === 'outbound' ? 'text-white' : ''} `}
style={{ backgroundColor: message.msg_direction === 'outbound' ? stringToColour(message.senderName) : 'unset', ...TagColorStyle(message.senderName, true) }}>
style={{ backgroundColor: message.msg_direction === 'outbound' ? stringToColour(message.senderName) : 'unset' }}>
{message.msg_direction === 'outbound' ? selectedConversation.OPI_Name : message.senderName}
</span>
<span>{message.dateString || message.localDate}</span>

@ -40,13 +40,13 @@ const SearchForm = memo(function ({ initialValues, onSubmit, onReset }) {
<Input placeholder='关键词' allowClear />
</Form.Item>
<Form.Item label='消息渠道' name='mchannel' className='w-52'>
<Select maxTagCount={0} allowClear options={[
{ key: 'WABA', label: 'WA商业号', value: 'WABA' },
<Select mode='multiple' maxTagCount={0} allowClear options={[
{ key: 'waba', label: 'WA商业号', value: 'waba' },
{ key: 'email', label: '邮件', value: 'email' },
{ key: 'wai', label: 'WhatsApp', value: 'wai' },
{ key: 'whatsapp', label: 'WhatsApp', value: 'whatsapp' },
]} className='w-8' />
</Form.Item>
{/* <Form.Item label='' name='mtype' className='w-44'>
<Form.Item label='消息类型' name='mtype' className='w-44'>
<Select mode='multiple' maxTagCount={0} allowClear options={[
{ key: 'image', label: '图片', value: 'image' },
{ key: 'video', label: '视频', value: 'video' },
@ -54,10 +54,10 @@ const SearchForm = memo(function ({ initialValues, onSubmit, onReset }) {
{ key: 'file', label: '文件', value: 'file' },
{ key: 'email', label: '邮件', value: 'email' },
]} className='w-8' />
</Form.Item> */}
</Form.Item>
<Form.Item label='日期' name='msgDateRange'>
<RangePicker format={'YYYY-MM-DD'} />
</Form.Item>
</Flex>
<div style={{ flex: '0 1 64px' }} className='flex justify-between'>

@ -56,11 +56,11 @@ const BubbleEmail = ({ onOpenEditor, onOpenEmail, ...message }) => {
<>
<b>From: </b>
<span>
{/* {message?.emailOrigin?.fromName}&nbsp;&lt;{message?.emailOrigin.fromEmail}&gt; */}
{message.msgOrigin?.from}
</span>
</> : <><b>To: </b>{message.msgOrigin?.to}</>
}
{/* <b>Subject: </b>{message.msgOrigin.email.subject} */}
</span>
</>
}

@ -1,13 +1,12 @@
import { memo } from 'react';
import { App, Button, Image } from 'antd';
import { ExportOutlined, CopyOutlined, PhoneOutlined } from '@ant-design/icons';
import { createContext, useEffect, useState, memo } from 'react';
import { App, Button } from 'antd';
import { MailFilled, MailOutlined, WhatsAppOutlined } from '@ant-design/icons';
import { MessageBox } from 'react-chat-elements';
import { groupBy, isEmpty, TagColorStyle } from '@/utils/commons';
import { groupBy, isEmpty } from '@/utils/commons';
import useConversationStore from '@/stores/ConversationStore';
import { useShallow } from 'zustand/react/shallow';
import { ReplyIcon } from '@/components/Icons';
import { WABIcon } from '@/components/Icons';
import ChannelLogo from './ChannelLogo';
import { ERROR_IMG } from '@/config';
const outboundStyle = {
'waba': { color: '#ccd4ae' },
@ -26,10 +25,10 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
const RenderText = memo(function renderText({ str, className, template, message }) {
let headerObj, footerObj, buttonsArr;
if (!isEmpty(template) && !isEmpty(template.components)) {
const componentsObj = groupBy(template.components.concat(template?.components_omit || []), (item) => item.type);
const componentsObj = groupBy(template.components, (item) => item.type);
headerObj = componentsObj?.header?.[0];
footerObj = componentsObj?.footer?.[0];
buttonsArr = componentsObj?.button; // ?.reduce((r, c) => r.concat(c.buttons), []);
buttonsArr = componentsObj?.buttons?.reduce((r, c) => r.concat(c.buttons), []);
}
const parts = str.split(/(https?:\/\/[^\s()]+|\p{Emoji_Presentation}|\d{4,})/gmu).filter((s) => s !== '');
@ -55,7 +54,7 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
{headerObj ? (
<div className='text-neutral-500 text-center'>
{'text' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <div>{headerObj.text}</div>}
{'image' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <Image src={headerObj.parameters[0].image.link} height={100} fallback={ERROR_IMG}></Image>}
{'image' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <img src={headerObj.parameters[0].image.link} height={100}></img>}
{['document', 'video'].includes((headerObj?.parameters?.[0]?.type || '').toLowerCase()) && (
<a href={headerObj.parameters[0][headerObj.parameters[0].type].link} target='_blank' key={headerObj.format} rel='noreferrer' className='text-sm'>
[&nbsp;{headerObj.parameters[0].type}&nbsp;]
@ -85,17 +84,17 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
{buttonsArr && buttonsArr.length > 0 ? (
<div className='flex flex-row gap-1'>
{buttonsArr.map((btn, index) =>
btn.sub_type.toLowerCase() === 'url' ? (
<Button className='text-blue-500' size={'small'} href={btn.url} target={'_blank'} key={`${btn.sub_type}_${btn.index}`} rel='noreferrer' icon={<ExportOutlined />}>
btn.type.toLowerCase() === 'url' ? (
<Button className='text-blue-500' size={'small'} href={btn.url} target={'_blank'} key={btn.url} rel='noreferrer'>
{btn.text}
</Button>
) : btn.sub_type.toLowerCase() === 'phone_number' ? (
<Button className='text-blue-500' size={'small'} key={btn.phone_number} rel='noreferrer' icon={<PhoneOutlined />}>
) : btn.type.toLowerCase() === 'phone_number' ? (
<Button className='text-blue-500' size={'small'} key={btn.phone_number} rel='noreferrer'>
{btn.text} ({btn.phone_number})
</Button>
) : (
<Button className='text-blue-500' size={'small'} key={`${btn.type}_${btn.sub_type}_${btn.index}`} icon={btn.sub_type.toLowerCase() === 'copy_code' ? <CopyOutlined /> : btn.sub_type.toLowerCase() === 'quick_reply' ? <ReplyIcon /> : null}>
{btn.text || btn.sub_type.toUpperCase()}
<Button className='text-blue-500' size={'small'} key={btn.type}>
{btn.text}
</Button>
),
)}
@ -106,7 +105,7 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
});
return (
<MessageBox
{...message} titleColor={TagColorStyle(message.title).color}
{...message}
key={`IM.${message.id}`}
position={message.sender === 'me' ? 'right' : 'left'}
onReplyClick={() => setReferenceMsg(message)}

@ -1,9 +1,9 @@
import React, { useState, useEffect } from 'react';
import { Button, Tag, Radio, Popover, Form, Space, Tooltip } from 'antd';
import { Button, Tag, Radio, Popover, Form } from 'antd';
import { isEmpty, objectMapper, TagColorStyle } from '@/utils/commons';
import useConversationStore from '@/stores/ConversationStore';
import { OrderLabelDefaultOptions } from '@/stores/OrderStore';
import { FilterOutlined, FilterTwoTone } from '@ant-design/icons';
import { FilterIcon } from '@/components/Icons';
const otypes = [
{ label: 'All', value: '', labelValue: '' },
@ -117,7 +117,7 @@ const ChatListFilter = ({ onFilterChange, activeList, ...props }) => {
return (
<>
<div className='my-1 flex justify-between items-center '>
{/* <Radio.Group
<Radio.Group
optionType={'button'}
buttonStyle='solid'
size='small'
@ -126,20 +126,7 @@ const ChatListFilter = ({ onFilterChange, activeList, ...props }) => {
onChange={(e) => {
setFilterOtype(e.target.value)
}}
/> */}
{tags.slice(0, 3).map((tag, ti) => (
<Tag.CheckableTag
className='mb-1'
key={tag.key}
checked={selectedTags.includes(tag.key)}
onChange={(checked) => handleTagsChange(tag, checked)}
style={TagColorStyle(
tag.label,
selectedTags.includes(tag.key),
)}>
{tag.label}
</Tag.CheckableTag>
))}
/>
<Popover
destroyTooltipOnHide
placement='bottomLeft'
@ -165,14 +152,14 @@ const ChatListFilter = ({ onFilterChange, activeList, ...props }) => {
initialValues={{}}
onFinish={onFinish}
className='*:mb-2'>
{/* <Form.Item label=''>
<Form.Item label='订单'>
<Tag
key={selectedOType}
closeIcon={selectedOType !== ''}
onClose={() => setFilterOtype('')}>
{otypesMapped[selectedOType]?.label || 'All'}
</Tag>
</Form.Item> */}
</Form.Item>
<Form.Item name={'tags'} label='标签' className='*.div:gap-1'>
{tags.map((tag, ti) => (
<Tag.CheckableTag
@ -190,27 +177,29 @@ const ChatListFilter = ({ onFilterChange, activeList, ...props }) => {
</Form.Item>
<Form.Item noStyle className='flex justify-center mb-0'>
<Space.Compact>
<Button.Group>
<Button onClick={onReset} type='primary' ghost>
重置
</Button>
{/* <Button htmlType='submit' type='primary'>
确定
</Button> */}
</Space.Compact>
</Button.Group>
</Form.Item>
</Form>
</>
}>
<Tooltip title='更多筛选' >
<Button
icon={
isEmpty(selectedTags) ? <FilterOutlined className='text-neutral-500' /> : <FilterTwoTone />
}
type='text'
size='middle'
/>
</Tooltip>
<Button
icon={
<FilterIcon
className={
isEmpty(selectedTags) ? 'text-neutral-500' : 'text-blue-500'
}
/>
}
type='text'
size='middle'
/>
</Popover>
</div>
</>

@ -230,7 +230,7 @@ const ChatListItem = (({item, refreshConversationList,setListUpdateFlag,onSwitch
{ label: '编辑联系人', key: 'edit0' },
{ type: 'divider' },
{ label: '移到🗂隐藏列表', key: 'close', danger: true },
{ label: '移到🗂已处理', key: 'close', danger: true },
],
triggerSubMenuAction: 'click',
openKeys: openTags,

@ -1,5 +1,5 @@
import { useState } from 'react'
import { App, Modal, Button, Table, Form, Row, Col, Input, Checkbox } from 'antd'
import { App, Modal, Button, Table } from 'antd'
import { ApiOutlined } from '@ant-design/icons'
import { isEmpty, cloneDeep } from '@/utils/commons'
import { fetchJSON } from '@/utils/request'
@ -9,17 +9,12 @@ import dayjs from 'dayjs'
import useAuthStore from '@/stores/AuthStore'
import { fetchEmailBindOrderAction } from '@/actions/EmailActions'
const fetchMyOrderList = async (params) => {
const fetchOrderList = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/getdvancedwlorder`, params)
return errcode !== 0 ? [] : result
}
const fetchHTOrderList = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/query_order`, params)
return errcode !== 0 ? [] : result
}
export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onBoundSuccess, ...props }) => {
const [form] = Form.useForm()
export const EmailBindFormModal = ({ mai_sn, conversationid, userId, onBoundSuccess, ...props }) => {
const [open, setOpen] = useState(false)
const { userId: loginUserId } = useAuthStore((state) => state.loginUser)
@ -33,7 +28,7 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
const copyObject = cloneDeep(values)
delete copyObject.type
const allEmpty = Object.values(copyObject).every((val) => {
return val === null || String(val).trim() === '' || val === undefined
return val === null || val === '' || val === undefined
})
if (allEmpty) {
notification.warning({
@ -44,14 +39,12 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
})
return false
}
// values.opisn = loginUserId
values.sourcetype = values.is_biz ? '227002' : '227001'
delete values.is_biz
values.opisn = loginUserId
setLoading(false)
setSearchLoading(true)
setSearchResult([])
const result = await fetchHTOrderList(values)
setSearchResult(result.map(ele => ({...ele, sourcetype: values.sourcetype})))
const result = await fetchOrderList(values)
setSearchResult(result)
setSearchLoading(false)
}
@ -83,58 +76,40 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
width: 222,
},
{
title: '顾问',
key: 'OperatorName',
dataIndex: 'OperatorName',
width: 100,
title: '客人姓名',
key: 'coli_guest',
dataIndex: 'coli_guest',
render: (text, record) => {
let regularText = ''
if (record.buytime > 0) regularText = '(R' + record.buytime + ')'
return text + regularText
},
},
{
title: '分配时间',
key: 'COLI_AssignDate',
dataIndex: 'COLI_AssignDate',
width: 100,
title: '出发日期',
key: 'COLI_OrderStartDate',
dataIndex: 'COLI_OrderStartDate',
width: 120,
hidden: false,
sortDirections: ['ascend', 'descend'],
sorter: (a, b) => {
const datejsA = isEmpty(a.COLI_OrderStartDate) ? 0 : new dayjs(a.COLI_OrderStartDate).valueOf()
const datejsB = isEmpty(b.COLI_OrderStartDate) ? 0 : new dayjs(b.COLI_OrderStartDate).valueOf()
return datejsA - datejsB
},
},
{
title: '天数',
key: 'COLI_Days',
dataIndex: 'COLI_Days',
width: 100,
title: '附加信息',
ellipsis: true,
key: 'COLI_Introduction',
dataIndex: 'COLI_Introduction',
},
// {
// title: '',
// key: 'coli_guest',
// dataIndex: 'coli_guest',
// render: (text, record) => {
// let regularText = ''
// if (record.buytime > 0) regularText = '(R' + record.buytime + ')'
// return text + regularText
// },
// },
// {
// title: '',
// key: 'COLI_OrderStartDate',
// dataIndex: 'COLI_OrderStartDate',
// width: 120,
// hidden: false,
// sortDirections: ['ascend', 'descend'],
// sorter: (a, b) => {
// const datejsA = isEmpty(a.COLI_OrderStartDate) ? 0 : new dayjs(a.COLI_OrderStartDate).valueOf()
// const datejsB = isEmpty(b.COLI_OrderStartDate) ? 0 : new dayjs(b.COLI_OrderStartDate).valueOf()
// return datejsA - datejsB
// },
// },
// {
// title: '',
// ellipsis: true,
// key: 'COLI_Introduction',
// dataIndex: 'COLI_Introduction',
// },
{
title: '',
key: 'action',
width: 150,
render: (_, record) => (
<Button type={'text'} className='text-primary' onClick={() => handleBindOrder({ coli_sn: record.COLI_SN, coli_id: record.COLI_ID, sourcetype: record.sourcetype })}>
<Button type={'text'} className='text-primary' onClick={() => handleBindOrder({ coli_sn: record.COLI_SN, coli_id: record.COLI_ID })}>
关联此订单
</Button>
),
@ -156,31 +131,9 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
onCancel={() => {
setOpen(false)
}}
destroyOnHidden>
{/* <AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} /> */}
<Form
layout={'inline'}
form={form}
initialValues={{
orderLabel: '',
orderStatus: '',
remindState: '',
// ...initialValues,
}}
onFinish={onSearchOrder}>
<Form.Item label='订单号' name='coli_id' initialValue={coliID} rules={[{ required: true, message: '请输入订单号' }]}>
<Input placeholder='订单号' allowClear />
</Form.Item>
<Form.Item name='is_biz' className='' valuePropName='checked'>
<Checkbox>商务订单</Checkbox>
</Form.Item>
<div style={{ flex: '0 1 64px' }} className='flex justify-between'>
<Button type='primary' htmlType='submit' loading={searchLoading}>
搜索
</Button>
</div>
</Form>
<Table key={'advanceOrderTable'} loading={loading} dataSource={searchResult} columns={searchResultColumns} pagination={searchResult.length <= 10 ? false : paginationProps} rowKey={'COLI_SN'} />
destroyOnClose>
<AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} />
<Table key={'advanceOrderTable'} loading={loading} dataSource={searchResult} columns={searchResultColumns} pagination={searchResult.length <= 10 ? false : paginationProps} />
</Modal>
</>
)

@ -1,146 +0,0 @@
import { POPUP_FEATURES } from '@/config'
import React, { useState, useEffect, useRef } from 'react'
const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
const [iframeHeight, setIframeHeight] = useState(5000) // Initial height
const [content, setContent] = useState(MailContent)
const iframeRef = useRef(null)
const containerRef = useRef(null)
useEffect(() => {
setContent(MailContent)
}, [MailContent])
const setIframeContent = (iframe, content) => {
if (!iframe || !iframe.contentDocument) {
console.error('Iframe not loaded or contentDocument is null')
return
}
const doc = iframe.contentDocument
doc.open()
// doc.write(content)
doc.write(`
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
/*overflow-y: hidden;*/
width: 900px;
max-width: 100%;
}
img {
max-width: 90%;
height: auto;
object-fit: contain;
}
img:not(a img){ cursor: pointer;}
</style>
</head>
<body>
${content}
</body>
</html>
`);
doc.close()
}
const calculateHeight = () => {
try {
if (iframeRef.current && iframeRef.current.contentDocument) {
const doc = iframeRef.current.contentDocument
const body = doc.body
if (body) {
try {
const links = doc.querySelectorAll('a')
links.forEach((link) => {
link.setAttribute('target', '_blank')
})
const imgs = doc.querySelectorAll('img:not(a img)')
imgs.forEach((img) => {
// open img in new tab
img.addEventListener('click', (e) => {
// e.preventDefault()
img.style.cursor = 'pointer'
window.open(img.src, img.src, POPUP_FEATURES)
})
})
} catch (e) {
// console.error('Could not access iframe content due to Same-Origin Policy or other error:', e)
}
requestAnimationFrame(() => {
const newHeight = Math.max(body.scrollHeight, body.offsetHeight, body.clientHeight)
// console.log('body.scrollHeight: ', body.scrollHeight)
// console.log('body.offsetHeight: ', body.offsetHeight)
// console.log('body.clientHeight: ', body.clientHeight)
const addMore = Math.max(Math.ceil(newHeight * 0.05), 120)
// console.log('Calculated height:', newHeight, addMore)
setIframeHeight(newHeight + addMore)
})
return
} else {
console.warn('iframe body is null or undefined')
}
} else {
console.warn('iframeRef.current or contentDocument is null')
}
} catch (error) {
console.error('Error calculating height:', error)
}
// setIframeHeight(200)
}
useEffect(() => {
const handleLoad = () => {
calculateHeight()
}
const currentIframe = iframeRef.current
if (currentIframe) {
currentIframe.addEventListener('load', handleLoad)
setIframeContent(currentIframe, content)
}
return () => {
if (currentIframe) {
currentIframe.removeEventListener('load', handleLoad)
}
}
}, [content])
// useEffect(() => {
// if(iframeRef.current){
// setIframeContent(iframeRef.current, content);
// calculateHeight();
// }
// }, [content])
return (
<div ref={containerRef} className={`space-y-4 w-full ${className}`}>
<div className='w-full relative pt-2'>
<iframe
key={id}
ref={iframeRef}
height={iframeHeight}
style={{
width: '100%',
height: `${iframeHeight}px`,
// border: '1px solid #e5e7eb',
border: 'none',
display: 'block',
}}
sandbox='allow-scripts allow-same-origin allow-popups'
/>
</div>
</div>
)
}
export default EmailContent

@ -4,17 +4,15 @@ import { LoadingOutlined, ApiOutlined } from '@ant-design/icons';
import { EditIcon, ReplyIcon, ResendIcon, ShareForwardIcon } from '@/components/Icons'
import { isEmpty, TagColorStyle } from '@/utils/commons'
import EmailEditorPopup from '../Input/EmailEditorPopup'
import DnDModal from '@/components/DnDModal'
import DnDModal from '@/components/DndModal'
import useStyleStore from '@/stores/StyleStore'
import { useEmailDetail, } from '@/hooks/useEmail';
import { EMAIL_ATTA_HOST } from '@/config';
import EmailBindFormModal from './EmailBind';
import EmailDetailInline from './EmailDetailInline';
import EmailContent from './EmailContent';
/**
* @property {*} emailMsg - 邮件数据. { conversationid, actionId, order_opi, coli_sn, msgOrigin: { from, to, id, email: { subject, mai_sn, } } }
* @property {*} disabled - 是否禁用操作: 回复, 转发
*/
const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) => {
@ -25,16 +23,16 @@ const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) =
const { conversationid, actionId, order_opi, coli_sn } = emailMsg
const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {}
const mailID = mai_sn || id
// const [initialPosition, setInitialPosition] = useState({})
// const [initialSize, setInitialSize] = useState({})
const [initialPosition, setInitialPosition] = useState({})
const [initialSize, setInitialSize] = useState({})
function onHandleMove(e) {
const { top, left, width, height } = e
props?.setInitialPosition({ top, left })
setInitialPosition({ top, left })
}
function onHandleResize(e) {
const { top, left, width, height } = e
props?.setInitialPosition({ top, left })
props?.setInitialSize({ width, height })
setInitialPosition({ top, left })
setInitialSize({ width, height })
}
const [action, setAction] = useState('')
@ -143,13 +141,64 @@ const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) =
{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.email?.subject}
</>
}
initial={{ width: props.initialSize?.width || (window.innerWidth - 740), height: props.initialSize?.height || (window.innerHeight - 100), left: props.initialPosition?.left || (300 + 24), top: props.initialPosition?.top || 74 }}
initial={{ width: window.innerWidth - 740, height: window.innerHeight - 100, left: 300 + 24, top: 74 }}
onMove={onHandleMove}
onResize={onHandleResize}
footer={<ActionBtns className='w-full !justify-start' />}>
<EmailDetailInline { ...{ mailData, emailMsg, loading, mailID } } />
{/* <EmailDetailInline { ...{ mailData, loading, mailID } } /> */}
<div className='email-container flex flex-col gap-2 *:p-2 *:rounded-sm *:border-b *:border-gray-200 *:shadow-1md'>
<div className=' font-bold'>{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.subject}</div>
<div>
<div className={['flex flex-wrap justify-end', window.innerWidth < 600 ? 'flex-col' : 'flex-row '].join(' ')}>
<div className=' grow shrink basis-0 flex flex-wrap gap-2 mb-2 items-center'>
<Avatar className='' style={TagColorStyle(mailData.info?.MAI_From, true)}>
{(mailData.info?.MAI_From || '').substring(0, 1)}
</Avatar>
<div className=' flex flex-col '>
{/* <span className=' font-bold text-base'>{mailData.info?.fromName}</span> */}
<span className='text-neutral-500 text-wrap break-words break-all '>{mailData.info?.MAI_From}</span>
</div>
</div>
<div className=' shrink-0 flex flex-col justify-start gap-1 items-end'>
<ActionBtns />
<div className='text-xs '>{mailData.info?.MAI_SendDate || emailMsg.localDate}</div>
</div>
</div>
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>收件人</span>
{mailData.info?.MAI_To}
</div>
{mailData.info?.MAI_CS && (
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>抄送</span>
{mailData.info.MAI_CS}
</div>
)}
{mailData.info?.bcc && (
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>密送</span>
{mailData.info.bcc}
</div>
)}
{mailData.attachments.length > 0 && (
<div className='mt-2 *:ml-2'>
<span>{mailData.attachments.length}个附件</span>
<div className='flex flex-wrap gap-2'>
{mailData.attachments.map((atta) => (
<a href={`${EMAIL_ATTA_HOST}${atta.ATI_ServerFile}`} key={atta.ATI_SN} target='_blank' rel='noreferrer'>
{atta.ATI_Name}
</a>
))}
</div>
</div>
)}
<Divider className='my-2' />
<div className={`mt-2 ${mailData.info?.MAI_ContentType === 'text/html' ? '' : 'whitespace-pre-wrap'}`} dangerouslySetInnerHTML={{ __html: mailData.content }}></div>
</div>
</div>
</DnDModal>
{/* <EmailEditorPopup
<EmailEditorPopup
open={openEmailEditor}
setOpen={setOpenEmailEditor}
fromEmail={fromEmail}
@ -160,11 +209,11 @@ const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) =
customerDetail={orderDetail.customerDetail}
// emailMsg={ReferEmailMsg}
quoteid={mailID}
initial={{ ...props.initialPosition, ...props.initialSize }}
initial={{ ...initialPosition, ...initialSize }}
mailData={mailData}
action={action}
key={`email-detail-inner-${action}_${mailID}`}
/> */}
key={`email-detail-inner-${action}-popup_${mailID}`}
/>
</>
)
}

@ -1,104 +1,52 @@
import { useState, useEffect, useRef, useMemo } from 'react'
import { App, Button, Divider, Avatar, List, Flex, Typography, Tooltip, Empty } from 'antd'
import { LoadingOutlined, ApiOutlined, FilePdfOutlined, FileOutlined, FileWordOutlined, FileExcelOutlined, FileJpgOutlined, FileImageOutlined, FileTextOutlined, FileGifOutlined, GlobalOutlined, FileZipOutlined, DeleteOutlined, ExpandOutlined } from '@ant-design/icons'
import { EditIcon, MailCheckIcon, ReplyAllIcon, ReplyIcon, ResendIcon, ShareForwardIcon, SendPlaneFillIcon, InboxIcon } from '@/components/Icons'
import { useState, useEffect } from 'react'
import { App, Button, Divider, Avatar } from 'antd'
import { LoadingOutlined, ApiOutlined } from '@ant-design/icons';
import { EditIcon, ReplyIcon, ResendIcon, ShareForwardIcon } from '@/components/Icons'
import { isEmpty, TagColorStyle } from '@/utils/commons'
import EmailEditorPopup from '../Input/EmailEditorPopup'
import DnDModal from '@/components/DnDModal'
import DnDModal from '@/components/DndModal'
import useStyleStore from '@/stores/StyleStore'
import { openPopup, useEmailDetail, } from '@/hooks/useEmail'
import { EMAIL_ATTA_HOST, POPUP_FEATURES } from '@/config'
import EmailBindFormModal from './EmailBind'
import EmailContent from './EmailContent'
const extTypeMapped = {
txt: { icon: FileTextOutlined },
zip: { icon: FileZipOutlined, color: '#ffe78f' },
pdf: { icon: FilePdfOutlined, color: '#ad0b00' },
doc: { icon: FileWordOutlined, color: '#103f91' },
docx: { icon: FileWordOutlined, color: '#103f91' },
rtf: { icon: FileWordOutlined, color: '#103f91' },
xls: { icon: FileExcelOutlined, color: '#0c7d0c' },
xlsx: { icon: FileExcelOutlined, color: '#0c7d0c' },
jpg: { icon: FileImageOutlined, color: '#1985ff' },
jpeg: { icon: FileImageOutlined, color: '#1985ff' },
png: { icon: FileImageOutlined, color: '#1985ff' },
gif: { icon: FileGifOutlined, color: '#1985ff' },
html: { icon: GlobalOutlined, color: '#1985ff' },
htm: { icon: GlobalOutlined, color: '#1985ff' },
default: { icon: FileOutlined }, // rtf bmp
}
const FileTypeIcon = ({fileName}) => {
const ext = fileName.split('.').pop() || 'default';
const Com = extTypeMapped[ext]?.icon || FileOutlined;
const color = extTypeMapped[ext]?.color || 'inherit';
return <Com style={{ color: color }} size={36} />;
};
import { useEmailDetail, } from '@/hooks/useEmail';
import { EMAIL_ATTA_HOST } from '@/config';
import EmailBindFormModal from './EmailBind';
/**
* @property {*} emailMsg - 邮件数据. { conversationid, actionId, order_opi, coli_sn, msgOrigin: { from, to, id, email: { subject, mai_sn, } } }
*/
const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, size, autoMark = false, ...props }) => {
// console.log('emailDetail', emailMsg);
const componentRef = useRef(null);
const [compactBtn, setCompactBtn] = useState(size==='small');
useEffect(() => {
if (componentRef.current) {
// console.log(componentRef.current.getBoundingClientRect().width);
setCompactBtn(componentRef.current.offsetWidth < 800);
}
return () => {}
}, [])
const EmailDetailInline = ({ mailID, open, setOpen = () => {}, emailMsg={}, disabled=false, ...props }) => {
// const NEW_EMAIL_CONFIG = useMemo(() => {
// return ['new', 'edit', 'reply', 'replyall', 'forward'].reduce((a, action) => ({...a, [`${action}-${mailID || 0}`]: {
// url: `/email/${action}/${mailID || 0}`,
// name: `${action}-${mailID || 0}`,
// features: POPUP_FEATURES,
// }}), {});
// }, [mailID]);
// console.log('emailDetail', emailMsg);
const { notification, message } = App.useApp()
const {notification, message} = App.useApp()
const { conversationid, actionId, order_opi, coli_sn } = emailMsg
const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {}
// const mailID = mai_sn || id
// const [action, setAction] = useState('')
const [action, setAction] = useState('')
// const [openEmailEditor, setOpenEmailEditor] = useState(false)
// const [fromEmail, setFromEmail] = useState('')
// useEffect(() => {
// setOpenEmailEditor(false)
// return () => {}
// }, [mailID])
const [openEmailEditor, setOpenEmailEditor] = useState(false)
const [fromEmail, setFromEmail] = useState('')
useEffect(() => {
setOpenEmailEditor(false)
const onOpenEditor = (msgOrigin, action='reply') => {
openPopup(`/email/${action}/${mailID || 0}`, `${action}-${mailID || 0}`)
if (typeof props.onOpenEditor === 'function') {
props.onOpenEditor(msgOrigin, action);
} else {
// const { from, to } = msgOrigin
// setOpenEmailEditor(true)
// setFromEmail(action === 'edit' ? from : to)
// setAction(action)
// // setOpen(false)
}
return () => {}
}, [mailID])
const onOpenEditor = (msgOrigin, action) => {
const { from, to } = msgOrigin
setOpenEmailEditor(true)
setFromEmail(action === 'edit' ? from : to)
setAction(action)
// setOpen(false)
}
const { loading, mailData, orderDetail, postEmailResend } = useEmailDetail(mailID, null, false, autoMark)
const [showBindBtn, setShowBindBtn] = useState(false)
const { loading, mailData, orderDetail, postEmailResend } = useEmailDetail(mailID)
const [showBindBtn, setShowBindBtn] = useState(false);
useEffect(() => {
setShowBindBtn(mailID ? isEmpty(mailData.info?.MAI_COLI_SN) : false)
setShowBindBtn(isEmpty(mailData.info?.MAI_COLI_SN))
return () => {}
}, [mailID, mailData.info?.MAI_COLI_SN])
const handleView = async () => {
openPopup(`/email/view/${mailID || 0}`, `view-${mailID || 0}`, { fullscreen: true })
};
}, [mailData.info?.MAI_COLI_SN])
const handleResend = async () => {
if (isEmpty(mai_sn)) {
@ -109,27 +57,11 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
// setOpen(false)
} catch (err) {
notification.error({
message: '请求失败',
message: "请求失败",
description: err.message,
placement: 'top',
placement: "top",
duration: 3,
})
}
}
const handleDel = async () => {
if (isEmpty(mai_sn)) {
return false
}
try {
//
} catch (err) {
notification.error({
message: '请求失败',
description: err.message,
placement: 'top',
duration: 3,
})
});
}
}
@ -140,19 +72,15 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
* * 失败: 重发
* todo: disabled 不显示
*/
const renderActionBtns = ({ className, ...props }) => {
const ActionBtns = ({className, ...props}) => {
const { status } = mailData.info
let btns = []
// const showDoneBtn = mailData.info?.MAI_Direction !== 1 ? true : false
// if (showDoneBtn) {
// btns.push(<Button type='text' key={'set-done'} onClick={() => { alert('todo')}} icon={<MailCheckIcon className={'text-yellow-600'} />} size='small'></Button>)
// }
// ``
if (showBindBtn) {
btns.push(<EmailBindFormModal key={'bind'} onBoundSuccess={() => setShowBindBtn(false)} {...{ conversationid, mai_sn, showBindBtn }} />)
btns.push(<Divider key='divider1' type='vertical' className='mx-0' />)
btns.push(<EmailBindFormModal key={'bind'} onBoundSuccess={() => setShowBindBtn(false)} {...{conversationid, mai_sn, showBindBtn}} />)
btns.push(<Divider key='divider1' type='vertical' />);
}
switch (status) {
@ -161,166 +89,93 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
case 'sent':
case '': //
btns.push(
<Tooltip key='reply-t' title='回复'>
<Button key={'reply'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'reply')} size='small' type='text' icon={<ReplyIcon className='text-indigo-500' />}>
{compactBtn ? '' : '回复'}
回复
</Button>
</Tooltip>,
)
btns.push(
<Tooltip key='replyall-t' title='回复全部'>
<Button key={'replyall'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'replyall')} size='small' type='text' icon={<ReplyAllIcon className='text-indigo-500' />} >{compactBtn ? '' : '回复全部'}</Button>
</Tooltip>,
)
btns.push(
<Tooltip key='forward-t' title='转发'>
<Button key={'forward'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'forward')} size='small' type='text' icon={<ShareForwardIcon className='text-primary' />}>{compactBtn ? '' : '转发'}</Button></Tooltip>,
<Button key={'forward'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'forward')} size='small' type='text' icon={<ShareForwardIcon className='text-primary' />}>
转发
</Button>
)
break
case 'failed':
btns.push(
// <Tooltip key='delete-t' title=''>
// <Button key={'delete'} danger onClick={() => handleDel()} size='small' type='text' icon={<DeleteOutlined className='text-red-500' />}>{compactBtn ? '' : ''}</Button></Tooltip>,
<Tooltip key='resend-t' title='发送'>
<Button key={'resend'} onClick={() => handleResend()} size='small' type='text' icon={<SendPlaneFillIcon className='text-orange-500' />}>{compactBtn ? '' : '发送'}</Button></Tooltip>,
<Button key={'resend'} onClick={() => handleResend()} size='small' type='text' icon={<ResendIcon className='text-orange-500' />}>
重发
</Button>
)
btns.push(
<Tooltip key='edit-t' title='编辑'>
<Button
key={'edit'}
onClick={() => onOpenEditor({ ...(emailMsg.msgOrigin || {}), content: mailData.content }, 'edit')}
size='small'
type='text'
icon={<EditIcon className='text-indigo-500' />}>{compactBtn ? '' : '编辑'}</Button></Tooltip>,
<Button key={'edit'} onClick={() => onOpenEditor({...(emailMsg.msgOrigin || {}), content: mailData.content}, 'edit')} size='small' type='text' icon={<EditIcon className='text-indigo-500' />}>
编辑
</Button>
)
break
default:
break
}
const showFullBtn = variant !== 'full'
if (showFullBtn) {
btns.push(<Divider key='divider2' type='vertical' className='mx-0' />);
btns.push(
<Button key={'view'} onClick={() => handleView()} size='small' type='text' icon={<ExpandOutlined className='text-indigo-500' />}>
最大化
</Button>
)
}
return <div className={`flex justify-end items-center gap-1 ${className || ''}`}>{btns}</div>
}
const renderAttaList = ({ list }) => {
return (
<List
dataSource={list}
size='small'
className='[&_.ant-list-item]:p-1 [&_.ant-list-item]:justify-start'
renderItem={(atta) => (
<List.Item>
<FileTypeIcon fileName={atta.ATI_Name} />
<Typography.Text ellipsis={{ tooltip: { title: atta.ATI_Name, placement: 'left' } }} className='text-inherit'>
<span key={atta.ATI_SN} onClick={() => openPopup(`${EMAIL_ATTA_HOST}${atta.ATI_ServerFile}`, atta.ATI_SN)} size='small' className='text-blue-500 cursor-pointer'>
{atta.ATI_Name}
</span>
</Typography.Text>
</List.Item>
)}
/>
<div className={`flex justify-end items-center w-full ${className || ''}`}>
{btns}
</div>
)
};
const variantCls = (variant) => {
switch (variant) {
case 'outline':
return 'h-full border-y-0 border-x border-solid border-neutral-200'
case 'full':
return 'h-[calc(100dvh-16px)]'
default:
return 'h-full'
}
}
return mailID ? (
return (
<>
<div ref={componentRef} className={`email-container flex flex-col gap-0 divide-y divide-neutral-200 divide-solid *:p-2 *:border-0 bg-white ${variantCls(variant)}`}>
<div className=''>
<div className='flex flex-wrap justify-between'>
<span className={(mailData.info?.MAI_ReadState || 0) > 0 ? '' : ' font-bold '}>
{loading ? <LoadingOutlined className='mr-1' /> : null}
{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.subject}
</span>
{/* <ActionBtns key='actions' className={'ml-auto'} /> */}
{renderActionBtns({ className: 'ml-auto'})}
</div>
<Divider className='my-2' />
<div className={['flex flex-wrap justify-end', window.innerWidth < 800 ? 'flex-col' : 'flex-row '].join(' ')}>
<div className=' flex-auto basis-0 flex flex-wrap gap-2 mb-2 items-center'>
<Avatar className='' style={TagColorStyle(mailData.info?.MAI_From, true)}>
{(mailData.info?.MAI_From || '').substring(0, 1)}
</Avatar>
<div className=' flex flex-col '>
{/* <span className=' font-bold text-base'>{mailData.info?.fromName}</span> */}
<span className='text-neutral-500 text-wrap break-words break-all '>{mailData.info?.MAI_From}</span>
<div className='email-container flex flex-col gap-2 *:p-2 *:rounded-sm *:border-b *:border-gray-200 *:shadow-1md'>
<div className=' font-bold'>{loading ? <LoadingOutlined className='mr-1' /> : null}{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.subject}</div>
<div>
<div className={['flex flex-wrap justify-end', window.innerWidth < 600 ? 'flex-col' : 'flex-row '].join(' ')}>
<div className=' grow shrink basis-0 flex flex-wrap gap-2 mb-2 items-center'>
<Avatar className='' style={TagColorStyle(mailData.info?.MAI_From, true)}>
{(mailData.info?.MAI_From || '').substring(0, 1)}
</Avatar>
<div className=' flex flex-col '>
{/* <span className=' font-bold text-base'>{mailData.info?.fromName}</span> */}
<span className='text-neutral-500 text-wrap break-words break-all '>{mailData.info?.MAI_From}</span>
</div>
</div>
<div className=' shrink-0 flex flex-col justify-start gap-1 items-end'>
<ActionBtns />
<div className='text-xs '>{mailData.info?.MAI_SendDate || emailMsg.localDate}</div>
</div>
</div>
<div className=' ml-auto flex flex-col justify-start gap-1 items-end'>
{/* <ActionBtns /> */}
<div className='text-xs '>{mailData.info?.MAI_SendDate || emailMsg.localDate}</div>
</div>
</div>
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-14 inline-block text-justify' style={{ textAlignLast: 'justify' }}>
收件人
</span>
{mailData.info?.MAI_To}
</div>
{mailData.info?.MAI_CS && (
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{ textAlignLast: 'justify' }}>
抄送
</span>
{mailData.info.MAI_CS}
</div>
)}
{mailData.info?.bcc && (
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{ textAlignLast: 'justify' }}>
密送
</span>
{mailData.info.bcc}
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>收件人</span>
{mailData.info?.MAI_To}
</div>
)}
</div>
<div className='overflow-auto'>
<Flex className={` divide-gray-200 divide-solid gap-0 ${compactBtn === false ? 'divide-y-0 divide-x' : 'flex-col-reverse divide-x-0 '}`}>
{mailData.info?.mailType === 'text/html' ? (
<EmailContent content={mailData.content} id={mailID} key={mailID} />
) : (
<div className='mt-2 whitespace-pre-wrap flex-auto' dangerouslySetInnerHTML={{ __html: mailData.content }}></div>
{mailData.info?.MAI_CS && (
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>抄送</span>
{mailData.info.MAI_CS}
</div>
)}
{mailData.info?.bcc && (
<div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>密送</span>
{mailData.info.bcc}
</div>
)}
{mailData.AttachList.length > 0 && (
<div className={`${compactBtn === false ? 'w-48' : 'border-b border-t-0'} overflow-hidden`}>
{mailData.attachments.length > 0 && (
<>
<span>&nbsp;附件 ({mailData.attachments.length})</span>
{renderAttaList({ list: mailData.attachments || []})}
</>
)}
{mailData.insideAttachments.length > 0 && <details>
<summary>
<span className='text-gray-500 italic'>&nbsp;文内附件 ({mailData.insideAttachments.length}) 已在正文显示&nbsp;</span><span className='cursor-pointer underline'>点击展开</span>
</summary>
{renderAttaList({ list: mailData.insideAttachments || []})}
</details>}
{mailData.attachments.length > 0 && (
<div className='mt-2 *:ml-2'>
<span>{mailData.attachments.length}个附件</span>
<div className='flex flex-wrap gap-2'>
{mailData.attachments.map((atta) => (
<a href={`${EMAIL_ATTA_HOST}${atta.ATI_ServerFile}`} key={atta.ATI_SN} target='_blank' rel='noreferrer'>
{atta.ATI_Name}
</a>
))}
</div>
</div>
)}
</Flex>
<Divider className='my-2' />
<div className='mt-2 whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: mailData.content }}></div>
</div>
</div>
</div>
{/* <EmailEditorPopup
<EmailEditorPopup
open={openEmailEditor}
setOpen={setOpenEmailEditor}
fromEmail={fromEmail}
@ -334,11 +189,9 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
// initial={{ ...initialPosition, ...initialSize }}
mailData={void 0}
action={action}
key={`email-detail-inline-${action}_${mailID}`}
/> */}
key={`email-detail-inner-${action}-inline_${mailID}`}
/>
</>
) : (
<Empty description={'未打开邮件'} image={Empty.PRESENTED_IMAGE_SIMPLE} />
)
}
export default EmailDetailInline

@ -1,145 +0,0 @@
import { createContext, useEffect, useState, useRef, useMemo } from 'react'
import { App, Button, Card, Empty, Flex, Select, Spin, Typography, Divider, Modal, List, Row, Col, Tag, Drawer, Input, Tooltip } from 'antd'
import { CloseOutlined, DownloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'
import { InboxIcon, SendPlaneFillIcon, ExpandIcon } from '@/components/Icons'
import EmailDetailInline from './EmailDetailInline'
import { debounce, isEmpty } from '@/utils/commons'
import useConversationStore from '@/stores/ConversationStore';
const EmailListDrawer = ({ showExpandBtn=true, title, list: otherEmailList, currentConversationID, opi_sn, oid, emailItem: clickItem, onOpenEditor, ...props }) => {
const [, setEmailMsg] = useConversationStore((state) => [state.emailMsg, state.setEmailMsg]);
const [open, setOpen] = useState(false)
const [selectedEmail, setSelectedEmail] = useState({})
const searchInputRef = useRef(null)
const [dataSource, setDataSource] = useState([])
useEffect(() => {
setOpen(false);
setDataSource(otherEmailList)
// setSelectedEmail({ MAI_SN: -1000 });
return () => {}
}, [otherEmailList])
const onClearSearch = () => {
setDataSource(otherEmailList)
}
const handleSearch = (value) => {
if (isEmpty(value)) onClearSearch()
const res = otherEmailList.filter((ele) => `${ele.MAI_Subject}${ele.SenderReceiver}`.toLowerCase().includes(value.toLowerCase()))
setDataSource(res)
}
const onClickEmailItem = (emailItem) => {
const emailMsg = {
conversationid: currentConversationID,
order_opi: opi_sn,
coli_sn: oid,
id: emailItem.MAI_SN,
MAI_SN: emailItem.MAI_SN,
msgOrigin: {
from: '',
to: '',
...(emailItem?.msgOrigin || {}),
id: emailItem.MAI_SN,
email: { mai_sn: emailItem.MAI_SN, subject: emailItem.MAI_Subject, id: emailItem.MAI_SN },
subject: emailItem.MAI_Subject,
},
}
console.log('emailItem', emailItem);
setSelectedEmail(emailMsg)
setEmailMsg(emailMsg);
};
const [pageCurrent, setPageCurrent] = useState(1);
const onChangePagination = (page, size) => {
setPageCurrent(page)
}
useEffect(() => {
if (!isEmpty(clickItem)) {
const itemIndex = dataSource.findIndex((ele) => ele.MAI_SN === clickItem.MAI_SN);
const page = Math.ceil((itemIndex+1) / 8) || 1;
setPageCurrent(page);
onClickEmailItem({...clickItem, ...dataSource[itemIndex]});
setOpen(true);
}
return () => {}
}, [clickItem]);
return (
<>
{showExpandBtn ? <Button
icon={<ExpandIcon />}
type={'primary'}
className='ml-2'
ghost
size='small'
onClick={() => {
setOpen(true)
}}
/> : null}
<Drawer
zIndex={3}
mask={false}
width={1000}
styles={{ header: {} }}
title={
<>
<Button icon={<CloseOutlined />} onClick={() => setOpen(false)} type='text' size='small' className='text-gray-500' />
<b>{title || '邮件列表'}</b>
<Input.Search
className=''
ref={searchInputRef}
allowClear
onClear={onClearSearch}
onPressEnter={(e) => {
handleSearch(e.target.value)
return false
}}
onSearch={(v, e, { source }) => handleSearch(v)}
placeholder={`输入: 标题/发件人, 回车搜索`}
/>
<List
dataSource={dataSource}
className='h-[30vh] overflow-y-auto'
pagination={false}
renderItem={(emailItem) => (
<List.Item
className={`hover:bg-stone-50 cursor-pointer !py-1 ${selectedEmail.MAI_SN === emailItem.MAI_SN ? 'bg-blue-100 font-bold ' : ''}`}
onClick={() => onClickEmailItem(emailItem)}>
<Flex vertical={false} wrap={false} className='w-full'>
<div className='flex-auto ml-auto min-w-40 line-clamp-2'>
{emailItem.Direction === '收' ? <InboxIcon className='text-indigo-500' /> : <SendPlaneFillIcon className='text-primary' />}
{/* <Tooltip title={emailItem.MAI_Subject}> */}
<Typography.Text>{emailItem.MAI_Subject}</Typography.Text>
{/* </Tooltip> */}
</div>
<div className='ml-1 max-w-40'>
<Typography.Text ellipsis={{ tooltip: emailItem.SenderReceiver }}>{emailItem.SenderReceiver.replaceAll('"', '')}</Typography.Text>
</div>
<div className='ml-1 max-w-20'>
<Typography.Text ellipsis={{ tooltip: emailItem.MAI_SendDate }}>{dayjs(emailItem.MAI_SendDate).format('MM-DD HH:mm')}</Typography.Text>
</div>
</Flex>
</List.Item>
)}
/>
</>
}
classNames={{ header: '!py-1 !px-2 [&_.ant-drawer-title]:font-normal [&_.ant-list-pagination]:m-0', body: '!p-1 [&_.ant-list-pagination]:ms-1' }}
placement='right'
closeIcon={null}
onClose={() => {
setOpen(false)
}}
open={open}>
<EmailDetailInline {...{ mailID: selectedEmail.MAI_SN, emailMsg: selectedEmail, onOpenEditor }} />
</Drawer>
</>
)
}
export default EmailListDrawer

@ -69,7 +69,7 @@ const EmailQuotation = ({ sfi_sn, ...props }) => {
邮件
</Button>
{/* <EmailEditorPopup
<EmailEditorPopup
open={editorOpen}
setOpen={setEditorOpen}
fromEmail={pickEmail.key}
@ -86,7 +86,7 @@ const EmailQuotation = ({ sfi_sn, ...props }) => {
// customerDetail={customerDetail}
action={'new'}
key={`email-quotation-new-popup_${currentConversation.sn}`}
/> */}
/>
</>
)
}

@ -1,14 +0,0 @@
import { createContext, useEffect, useState } from 'react'
import { Drawer } from 'antd'
import SnippetList from '@/views/accounts/SnippetList'
import useSnippetStore from '@/stores/SnippetStore'
const GenerateAutoDocDrawer = ({ ...props }) => {
const [openSnippetDrawer, closeSnippetDrawer, snippetDrawerOpen] = useSnippetStore((state) => [state.openDrawer, state.closeDrawer, state.drawerOpen])
return (
<Drawer title='图文集' placement={'top'} size={'large'} onClose={() => closeSnippetDrawer()} open={snippetDrawerOpen}>
<SnippetList></SnippetList>
</Drawer>
)
}
export default GenerateAutoDocDrawer

@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { App, Button, Popover, Tabs, List, Image, Avatar, Card, Flex, Space,Typography } from 'antd';
import { App, Button, Popover, Tabs, List, Image, Avatar, Card, Flex, Space } from 'antd';
import { FileSearchOutlined, LoadingOutlined } from '@ant-design/icons';
import { RotateLeftOutlined, RotateRightOutlined, ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons'
import { InboxIcon, SendPlaneFillIcon } from '@/components/Icons';
@ -13,7 +13,6 @@ import useStyleStore from '@/stores/StyleStore';
import useAuthStore from '@/stores/AuthStore';
import { sentMsgTypeMapped } from '@/channel/bubbleMsgUtils';
import { v4 as uuid } from 'uuid';
import dayjs from 'dayjs'
const BIG_PAGE_SIZE = MESSAGE_PAGE_SIZE * 10;
@ -321,9 +320,6 @@ const MessageListFilter = ({ ...props }) => {
const [openEmailDetail, setOpenEmailDetail] = useState(false);
const [emailDetail, setEmailDetail] = useState({});
const [initialPosition, setInitialPosition] = useState({})
const [initialSize, setInitialSize] = useState({})
const onOpenEmail = (email_detail) => {
setOpenEmailDetail(true);
setEmailDetail(email_detail);
@ -341,36 +337,39 @@ const MessageListFilter = ({ ...props }) => {
renderItem={({ msgtext, ...item }) => (
<List.Item
// actions={[item.localDate]}
className='cursor-pointer !py-1'
className='cursor-pointer'
onClick={() => {
onOpenEmail({ msgtext, ...item });
// setOpenPopup(false);
setOpenPopup(false);
}}>
<Flex vertical={false} wrap={false} className='w-full'>
<div className='flex-auto ml-auto min-w-40 line-clamp-2'>
{item.sender !== 'me' ? <InboxIcon className='text-indigo-500' /> : <SendPlaneFillIcon className='text-primary' />}
{/* <Tooltip title={emailItem.MAI_Subject}> */}
<Typography.Text>{msgtext?.email?.subject}</Typography.Text>
{/* </Tooltip> */}
</div>
<div className='ml-1 max-w-40'>
<Typography.Text ellipsis={{ tooltip: msgtext.to }}>{msgtext.to.replaceAll('"', '')}</Typography.Text>
</div>
<div className='ml-1 max-w-20'>
<Typography.Text ellipsis={{ tooltip: item.localDate }}>{dayjs(item.localDate).format('MM-DD HH:mm')}</Typography.Text>
</div>
</Flex>
<List.Item.Meta
avatar={
item.sender === 'me' ? <SendPlaneFillIcon className='text-primary' /> : <InboxIcon className='text-indigo-500' />
// <Avatar size='small' style={CalColorStyle(item.senderName)}>
// {item.senderName.substring(0, 3)}
// </Avatar>
}
title={msgtext?.email?.subject}
// description={`To: ${msgtext.to}`}
description={
<Flex justify={'space-between'} className='max-w-full overflow-hidden'>
<div className='flex-auto line-clamp-1 break-all pr-2'>{`To: ${msgtext.to}`}</div>
<div className=' basis-32 flex-grow-0 flex-shrink-0'>{item.localDate}</div>
</Flex>
}
/>
{msgtext?.email?.abstract}
</List.Item>
)}
/>
<EmailDetail open={openEmailDetail} setOpen={setOpenEmailDetail} emailMsg={emailDetail} key={`email-detail-1-${emailDetail.id}`} {...{initialPosition, initialSize, setInitialPosition, setInitialSize}} />
<EmailDetail open={openEmailDetail} setOpen={setOpenEmailDetail} emailMsg={emailDetail} key={`email-detail-1-${emailDetail.id}`} />
</>
);
};
return (
<>
<Popover zIndex={3}
<Popover
// destroyTooltipOnHide
placement='bottom'
overlayClassName={[mobile === false ? 'w-2/5' : 'w-full max-h-full', 'max-h-[70%]'].join(' ')}
@ -390,7 +389,7 @@ const MessageListFilter = ({ ...props }) => {
{ key: 'video', label: '视频', children: <Videos /> },
{ key: 'audio', label: '音频', children: <Audios /> },
{ key: 'file', label: '文件', children: <FileList /> },
// { key: 'email', label: '', children: <EmailList /> },
{ key: 'email', label: '邮件', children: <EmailList /> },
]}
/>
</>

@ -0,0 +1,114 @@
import { createContext, useEffect, useState, useRef, useMemo } from 'react'
import { App, Button, Card, Empty, Flex, Select, Spin, Typography, Divider, Modal, List, Row, Col, Tag, Drawer, Input, Tooltip } from 'antd'
import { DownloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'
import { InboxIcon, SendPlaneFillIcon, ExpandIcon } from '@/components/Icons'
import EmailDetailInline from '../Components/EmailDetailInline'
import { debounce, isEmpty } from '@/utils/commons'
const SupplierEmailDrawer = ({ list: otherEmailList, currentConversationID, opi_sn, oid, ...props }) => {
const [open, setOpen] = useState(false)
const [selectedEmail, setSelectedEmail] = useState({})
const searchInputRef = useRef(null)
const [dataSource, setDataSource] = useState([])
useEffect(() => {
setOpen(false);
setDataSource(otherEmailList)
// setSelectedEmail({ MAI_SN: -1000 });
return () => {}
}, [otherEmailList])
const onClearSearch = () => {
setDataSource(otherEmailList)
}
const handleSearch = (value) => {
if (isEmpty(value)) onClearSearch()
const res = otherEmailList.filter((ele) => `${ele.MAI_Subject}${ele.SenderReceiver}`.toLowerCase().includes(value.toLowerCase()))
setDataSource(res)
}
return (
<>
<Button
icon={<ExpandIcon />}
type={'primary'}
className='ml-2'
ghost
size='small'
onClick={() => {
setOpen(true)
}}
/>
<Drawer
zIndex={3}
mask={false}
width={900}
styles={{ header: {} }}
title={`供应商邮件`}
classNames={{ header: '!py-1 !px-2', body: '!p-1 [&_.ant-list-pagination]:ms-1' }}
placement='right'
onClose={() => {
setOpen(false)
}}
open={open}>
<Input.Search
className=''
ref={searchInputRef}
allowClear
onClear={onClearSearch}
onPressEnter={(e) => {
handleSearch(e.target.value)
return false
}}
onSearch={(v, e, { source }) => handleSearch(v)}
placeholder={`输入: 标题/发件人, 回车搜索`}
/>
<List
dataSource={dataSource}
pagination={{
pageSize: 10,
// showLessItems: true,
showSizeChanger: false,
size: 'small',
}}
renderItem={(emailItem) => (
<List.Item
className={`hover:bg-stone-50 cursor-pointer !py-1 ${selectedEmail.MAI_SN === emailItem.MAI_SN ? 'bg-blue-100 font-bold ' : ''}`}
onClick={() => {
const emailMsg = {
conversationid: currentConversationID,
order_opi: opi_sn,
coli_sn: oid,
id: emailItem.MAI_SN,
MAI_SN: emailItem.MAI_SN,
msgOrigin: {
from: '',
to: '',
id: emailItem.MAI_SN,
email: { mai_sn: emailItem.MAI_SN, subject: emailItem.MAI_Subject, id: emailItem.MAI_SN },
},
}
setSelectedEmail(emailMsg)
}}>
<Flex vertical={false} wrap={false} className='w-full'>
<div className='flex-auto ml-auto min-w-40 line-clamp-1'>
{emailItem.Direction === '收' ? <InboxIcon className='text-indigo-500' /> : <SendPlaneFillIcon className='text-primary' />}
{/* <Tooltip title={emailItem.MAI_Subject}> */}
<Typography.Text >{emailItem.MAI_Subject}</Typography.Text>
{/* </Tooltip> */}
</div>
<div className='ml-1 max-w-40'>
<Typography.Text ellipsis={{ tooltip: emailItem.SenderReceiver }}>{emailItem.SenderReceiver.replaceAll('"', '')}</Typography.Text>
</div>
<div className='ml-1 max-w-20'>
<Typography.Text ellipsis={{ tooltip: emailItem.MAI_SendDate }}>{dayjs(emailItem.MAI_SendDate).format('MM-DD HH:mm')}</Typography.Text>
</div>
</Flex>
</List.Item>
)}
/>
<EmailDetailInline {...{ mailID: selectedEmail.MAI_SN, emailMsg: selectedEmail }} />
</Drawer>
</>
)
}
export default SupplierEmailDrawer

@ -126,7 +126,7 @@ export const ConversationBindFormModal = ({ currentConversationID, userId, onBou
onCancel={() => {
setOpen(false);
}}
destroyOnHidden>
destroyOnClose>
<AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} />
<Table
key={'advanceOrderTable'}

@ -318,32 +318,30 @@ const Conversations = () => {
// enterButton={'Filter'}
/>
{/* TODO 这个在完成搜索历史会话后去掉,待讨论查询规则 */}
</div>
<div className="flex gap-1 justify-between items-center shadow">
<div className='mr-auto'>{/* 占位 */}</div>
<ChatListFilter key='chat-list-filter'
onFilterChange={(d) => {
refreshConversationList()
}}
activeList={activeList}
/>
{conversationsListLoading ? (
<div className='text-center py-1 px-2'>
<LoadingOutlined className='text-orange-400 ' />
</div>
) :
<Tooltip key={'conversation-list'} title={activeList ? '🗂已隐藏' : '活跃会话'}>
<Tooltip key={'conversation-list'} title={activeList ? '🗂已处理' : '活跃会话'}>
<Button onClick={toggleClosedConversationsList} icon={activeList ? '🗂' : '📌'} type='text' />
</Tooltip>
}
{mobile && (
<AudioTwoTone className='px-3'
<AudioTwoTone
onClick={() => {
navigate(`/callcenter/call`)
}}
/>
)}
</div>
<ChatListFilter key='chat-list-filter'
onFilterChange={(d) => {
refreshConversationList()
}}
activeList={activeList}
/>
<div className='flex-1 overflow-x-hidden overflow-y-auto relative'>
{/* {mobile && conversationsListLoading && dataSource.length === 0 ? ( */}

@ -59,7 +59,7 @@ export const ConversationItemForm = ({ initialValues, onFormInstanceReady }) =>
<Form.Item label='WhatsApp' name={'wa_id'} dependencies={['phone_number']}>
<Input disabled={!initialValues.is_new && isNotEmpty(initialValues.wa_id)} />
</Form.Item>
<Form.Item hidden
<Form.Item
name={'email'}
label='邮箱'
validateStatus={contactValidateStatus}
@ -124,7 +124,7 @@ export const ConversationItemFormModal = ({ open, onCreate, onCancel, initialVal
onCancel();
formInstance?.resetFields();
}}
destroyOnHidden
destroyOnClose
onOk={async () => {
try {
const values = await formInstance?.validateFields();

@ -258,7 +258,7 @@ const EmailComposer = ({ ...props }) => {
<Alert message="账户没有配置邮箱地址" description='请 重新登录 获取最新配置' type="warning" showIcon className=' absolute top-0 left-0 right-0 bottom-0' />
}
{/* <EmailEditorPopup
<EmailEditorPopup
{...{ open, setOpen }}
fromEmail={fromEmail}
fromUser={fromUser}
@ -270,7 +270,7 @@ const EmailComposer = ({ ...props }) => {
customerDetail={customerDetail}
action='new'
key={'email-new-editor-popup'}
/> */}
/>
</ConfigProvider>
)
}

@ -1,8 +1,8 @@
import { useEffect, useState, useRef, useCallback } from 'react';
import { App, ConfigProvider, Button, Form, Input, Flex, Checkbox, Popconfirm, Select, Space, Upload, Divider, Modal, Tabs } from 'antd';
import { useEffect, useState } from 'react';
import { App, ConfigProvider, Button, Form, Input, Flex, Checkbox, Popconfirm, Select, Space, Upload, Divider, Modal } from 'antd';
import { UploadOutlined, LoadingOutlined } from '@ant-design/icons';
import '@dckj/react-better-modal/dist/index.css';
import DnDModal from '@/components/DnDModal';
import DnDModal from '@/components/DndModal';
import useStyleStore from '@/stores/StyleStore';
import useConversationStore from '@/stores/ConversationStore';
import useAuthStore from '@/stores/AuthStore';
@ -10,8 +10,7 @@ import useAuthStore from '@/stores/AuthStore';
import LexicalEditor from '@/components/LexicalEditor';
import { v4 as uuid } from 'uuid';
import { cloneDeep, debounce, isEmpty, } from '@/utils/commons';
import { writeIndexDB } from '@/utils/indexedDB';
import { cloneDeep, isEmpty, } from '@/utils/commons';
import './EmailEditor.css';
import { postSendEmail } from '@/actions/EmailActions';
import { sentMsgTypeMapped, } from '@/channel/bubbleMsgUtils';
@ -61,9 +60,10 @@ const generateMailContent = (mailData) => `<br><br><p>${mailData.content}</p>`
* @property {string} quoteid - 引用邮件ID
* @property {object} draft - 草稿
*/
const EmailEditorPopup = () => {
const EmailEditorPopup = ({ open, setOpen, fromEmail, fromUser, fromOrder, oid, toEmail, conversationid, quoteid, initial = {}, mailData: _mailData, action = 'reply', draft = {}, customerDetail={}, ...props }) => {
const { notification, message } = App.useApp();
const [form] = Form.useForm();
const [mobile] = useStyleStore((state) => [state.mobile]);
const [userId, username, emailList] = useAuthStore((state) => [state.loginUser.userId, state.loginUser.username, state.loginUser.emailList]);
const emailListOption = emailList?.map(ele => ({ ...ele, label: ele.email, key: ele.email, value: ele.email })) || [];
@ -72,35 +72,8 @@ const EmailEditorPopup = () => {
const emailListMatMapped = emailListOption?.reduce((r, v) => ({ ...r, [v.mat_sn]: v }), {});
// console.log('emailListMapped', emailListOption, emailListAddrMapped);
const emailEdiorProps = useConversationStore((state) => state.emailEdiorProps);
const [open, setOpen, closeEditor1, currentEditKey, setCurrentEditKey] = useConversationStore((state) => [state.editorOpen, state.setEditorOpen, state.closeEditor1, state.currentEditKey, state.setCurrentEditKey]);
const propsKeysArr = Array.from(emailEdiorProps.keys());
const propsArr = Array.from(emailEdiorProps.values());
const [activeEdit, setActiveEdit] = useState(emailEdiorProps.get(currentEditKey) || {});
// const { fromEmail, fromUser, fromOrder, oid, toEmail, conversationid, quoteid, initial = {}, mailData: _mailData, action = 'reply', draft = {}, receiverName, ...props } = emailEdiorProps.get(currentEditKey) || {};
const onChangeActiveEditor = (key) => {
setCurrentEditKey(key);
const _find = emailEdiorProps.get(key) || {};
setActiveEdit(_find);
};
const onEditTab = (targetKey, action) => {
if (action === 'add') {
//
} else {
if (propsKeysArr.length === 1) {
setOpen(false);
}
closeEditor1(targetKey);
}
};
const mai_sn = activeEdit.quoteid;
const { loading: getLoading, mailData } = useEmailDetail(mai_sn, activeEdit.mailData)
const mai_sn = quoteid;
const { loading: getLoading, mailData } = useEmailDetail(mai_sn, _mailData)
const [stickToProps, setStickToProps] = useState({});
@ -126,24 +99,24 @@ const EmailEditorPopup = () => {
// : ID,
// , 使focus, ID
// , , ID,
const [stickToCid, setStickToCid] = useState(activeEdit.conversationid);
const [stickToCid, setStickToCid] = useState(conversationid);
useEffect(() => {
const propsObj = { ...activeEdit, mai: activeEdit.mailData?.info?.MAI_MAT_SN, }
const propsObj = { open, setOpen, fromEmail, fromUser, fromOrder, oid, toEmail, conversationid, quoteid, mai: _mailData?.info?.MAI_MAT_SN, action, draft }
setContentPrefix(activeEdit.oid ? `<p>Dear Mr./Ms. ${activeEdit.receiverName || ''}</p><p>Reference Number: ${activeEdit.oid}</p>` : '');
setContentPrefix(oid ? `<p>Dear Mr./Ms. ${customerDetail.name || ''}</p><p>Reference Number: ${oid}</p>` : '');
//
if (isEmpty(activeEdit.quoteid)) {
if (isEmpty(quoteid)) {
setStickToProps(propsObj)
setPropsSerialize(JSON.stringify(propsObj))
setStickToCid(activeEdit.conversationid)
setEmailOrder(activeEdit.fromOrder)
setEmailOPI(activeEdit.fromUser)
setNewFromEmail(activeEdit.fromEmail)
setNewToEmail(activeEdit.toEmail)
setStickToCid(conversationid)
setEmailOrder(fromOrder)
setEmailOPI(fromUser)
setNewFromEmail(fromEmail)
setNewToEmail(toEmail)
const _findMat = emailListAddrMapped?.[activeEdit.fromEmail]?.mat_sn
const _findMat = emailListAddrMapped?.[fromEmail]?.mat_sn
setEmailMat(_findMat)
// if (open !== true) {
@ -156,7 +129,7 @@ const EmailEditorPopup = () => {
const reEmailUser = mailData.info?.MAI_OPI_SN
const reEmailUserMat = mailData.info?.MAI_MAT_SN
setEmailOrder((prev) => reEmailO || prev || activeEdit.fromOrder)
setEmailOrder((prev) => reEmailO || prev || fromOrder)
setEmailOPI((prev) => reEmailUser || prev)
setEmailMat((prev) => reEmailUserMat || prev)
@ -205,7 +178,6 @@ const EmailEditorPopup = () => {
setTextContent(textContent);
form.setFieldValue('content', htmlContent);
form.setFieldValue('abstract', getAbstract(textContent));
debouncedSave({htmlContent});
};
const [initialForm, setInitialForm] = useState({});
@ -217,7 +189,7 @@ const EmailEditorPopup = () => {
useEffect(() => {
// console.log('quoteid', quoteid, isEmpty(quoteid), isEmpty(mailData.info));
if (isEmpty(activeEdit.quoteid) && activeEdit.action !== 'new') {
if (isEmpty(quoteid) && action !== 'new') {
return () => {}
}
const { info } = mailData
@ -229,7 +201,7 @@ const EmailEditorPopup = () => {
// const _initialContent = isEmpty(mailData.info) ? signatureBody : signatureBody+preQuoteBody
if (!isEmpty(mailData.info) && activeEdit.action !== 'edit') {
if (!isEmpty(mailData.info) && action !== 'edit') {
setInitialContent(contentPrefix + signatureBody)
}
@ -240,14 +212,14 @@ const EmailEditorPopup = () => {
subject: `Re: ${info.MAI_Subject || ''}`,
}
const forwardValues = { from: newFromEmail, subject: `Fw: ${info.MAI_Subject || ''}` }
if (activeEdit.action === 'reply') {
if (action === 'reply') {
form.setFieldsValue(_formValues)
setInitialForm(_formValues)
} else if (activeEdit.action === 'forward') {
} else if (action === 'forward') {
setStickToCid('0')
form.setFieldsValue(forwardValues)
setInitialForm(forwardValues)
} else if (activeEdit.action === 'edit') {
} else if (action === 'edit') {
const thisFormValues = {
to: info?.MAI_To || '',
cc: info?.MAI_CS || '',
@ -259,11 +231,11 @@ const EmailEditorPopup = () => {
// console.log('thisBody', thisBody);
setInitialContent(thisBody)
} else if (activeEdit.action === 'new') {
const newEmail = { to: newToEmail, subject: activeEdit.draft?.subject || '' }
} else if (action === 'new') {
const newEmail = { to: newToEmail, subject: draft?.subject || '' }
form.setFieldsValue(newEmail)
setInitialForm(newEmail)
setInitialContent((activeEdit.draft?.content || contentPrefix || '') + signatureBody)
setInitialContent((draft?.content || contentPrefix || '') + signatureBody)
}
return () => {}
@ -419,7 +391,7 @@ const EmailEditorPopup = () => {
body.coli_sn = emailOrder || '';
// console.log('body', body, '\n', emailOrder);
const values = await form.validateFields();
const preQuoteBody = activeEdit.quoteid ? (quoteContent ? quoteContent : generateQuoteContent(mailData, isRichText)) : '';
const preQuoteBody = quoteid ? (quoteContent ? quoteContent : generateQuoteContent(mailData, isRichText)) : '';
body.mailcontent = isRichText ? EmailBuilder({ subject: values.subject, content: htmlContent+preQuoteBody }) : textContent+preQuoteBody
body.cc = values.cc || '';
body.bcc = values.bcc || '';
@ -478,32 +450,6 @@ const EmailEditorPopup = () => {
const [openDrawerSnippet] = useSnippetStore((state) => [state.openDrawer])
const [openPaymentDrawer] = useOrderStore((state) => [state.openDrawer])
const [bakData, setBakData] = useState({});
const idleCallbackId = useRef(null);
const debouncedSave = useCallback(
debounce((data) => {
idleCallbackId.current = window.requestIdleCallback(() => {
console.log('Saving data (idle, debounced):', data);
if (currentEditKey) writeIndexDB([{ ...data, key: currentEditKey }], 'draft', 'EmailEditor')
});
}, 1500), // 1.5s
[]
);
const onEditChange = (changedValues, allValues) => {
console.log('onEditChange', changedValues,'\n', allValues)
// const { name, value } = e.target;
// setBakData(prevData => ({ ...prevData, [name]: value }));
// debouncedSave(bakData);
};
useEffect(() => {
return () => {
if (idleCallbackId.current && window.cancelIdleCallback) {
window.cancelIdleCallback(idleCallbackId.current);
}
};
}, [debouncedSave]);
return (
<>
<ConfigProvider theme={{ token: { colorPrimary: '#6366f1' } }}>
@ -511,19 +457,15 @@ const EmailEditorPopup = () => {
rootClassName='email-editor-wrapper !border-indigo-300 '
open={open}
setOpen={setOpen}
// 300 + 24
// window.innerWidth - 600
initial={{ width: 880, height: window.innerHeight - 40, left: 20, top: 20 }}
initial={{ width: window.innerWidth - 600, height: window.innerHeight - 40, left: 300 + 24, top: 20 }}
onCancel={() => {
form.resetFields()
stateReset()
}}
titleClassName={`!pl-0 !pt-0 !pb-0`}
title={
<>
{/* {getLoading ? <LoadingOutlined className='mr-1' /> : null} */}
{/* {initialForm.subject || `${!isEmpty(quoteid) ? '回复: ' : '写邮件: '} ${newFromEmail || ''}`} */}
<Tabs editable type={'editable-card'} activeKey={currentEditKey} onChange={onChangeActiveEditor} className='[&_.ant-tabs-nav]:mb-0' items={propsArr.map(ele=>({...ele, label: (!isEmpty(activeEdit.quoteid) ? '回复: ' : '新邮件: ')+ele.subject}))} onEdit={onEditTab} hideAdd />
{getLoading ? <LoadingOutlined className='mr-1' /> : null}
{initialForm.subject || `${!isEmpty(quoteid) ? '回复: ' : '写邮件: '} ${newFromEmail || ''}`}
</>
}
footer={
@ -544,7 +486,7 @@ const EmailEditorPopup = () => {
</div>
}>
<Form
form={form} onValuesChange={onEditChange}
form={form}
preserve={false}
name={`email_max_form-${Date.now().toString(32)}`}
size='small'
@ -631,7 +573,7 @@ const EmailEditorPopup = () => {
</Form.Item>
</Form>
<LexicalEditor {...{ isRichText }} onChange={handleEditorChange} defaultValue={initialContent} />
{activeEdit.quoteid && !showQuoteContent && (
{quoteid && !showQuoteContent && (
<div className='flex justify-start items-center ml-2'>
<Button className='flex gap-2 ' type='link' onClick={() => setShowQuoteContent(!showQuoteContent)}>
显示引用内容
@ -642,7 +584,7 @@ const EmailEditorPopup = () => {
</div>
)}
{showQuoteContent && (
<blockquote contentEditable className='border-0 outline-none' onBlur={(e) => setQuoteContent(`<blockquote>${e.target.innerHTML}</blockquote>`)} dangerouslySetInnerHTML={{ __html: generateQuoteContent(mailData) }}></blockquote>
<div contentEditable className='border-0 outline-none' onBlur={(e) => setQuoteContent(e.target.innerHTML)} dangerouslySetInnerHTML={{ __html: generateQuoteContent(mailData) }}></div>
)}
</DnDModal>
</ConfigProvider>

@ -8,7 +8,7 @@ const PaymentlinkBtn = ({ type, ...props }) => {
return (
<>
{/* <GeneratePaymentDrawer /> */}
<GeneratePaymentDrawer />
<Tooltip title='支付链接'>
{/* <Button type='text' onClick={() => openPaymentDrawer()} icon={<DollarOutlined className='text-orange-500' />} size={'middle'} /> */}

@ -3,8 +3,8 @@ import { App, Popover, Flex, Button, List, Input, Tabs, Tag, Alert, Divider } fr
import { MessageOutlined, SendOutlined } from '@ant-design/icons';
import useAuthStore from '@/stores/AuthStore';
import useConversationStore from '@/stores/ConversationStore';
import { cloneDeep, flush, getNestedValue, groupBy, objectMapper, removeFormattingChars, sortArrayByOrder, sortObjectsByKeysMap, TagColorStyle } from '@/utils/commons';
import { replaceTemplateString, whatsappTemplateBtnParamTypesMapped } from '@/channel/bubbleMsgUtils';
import { cloneDeep, getNestedValue, groupBy, objectMapper, removeFormattingChars, sortArrayByOrder, sortObjectsByKeysMap, TagColorStyle } from '@/utils/commons';
import { replaceTemplateString } from '@/channel/bubbleMsgUtils';
import { isEmpty } from '@/utils/commons';
import useStyleStore from '@/stores/StyleStore';
@ -36,33 +36,16 @@ const CategoryList = ({ dataSource, handleSendTemplate, valueMapped, onInput, ac
const keys = (templateText.match(/{{(.*?)}}/g) || []).map((key) => key.replace(/{{|}}/g, ''))
const paramsVal = keys.reduce((r, k) => ({ ...r, [k]: getNestedValue(valueMapped, [k]) }), {})
if (key === 'header' && tempItem.components?.header?.[0]?.example?.header_url) {
const headerImg = { key: 'header_url', placeholder: '头图地址' };
tempArr.unshift(headerImg);
}
if (key === 'buttons' && (tempItem.components?.buttons?.[0]?.buttons || []).findIndex(btn => btn.type === 'COPY_CODE') !== -1) {
const btnCode = { key: 'copy_code', placeholder: '复制条码' };
tempArr.push(btnCode);
}
if (key === 'buttons' ) {
(tempItem.components?.buttons?.[0]?.buttons || []).filter(btn0 => btn0.type === 'URL').forEach((btn) => {
const hasParam = Object.prototype.hasOwnProperty.call(btn, "example");
const templateUrl = btn.url || ''
const urlParamKeys = (templateUrl.match(/{{(.*?)}}/g) || []).map((key) => key.replace(/{{|}}/g, '')).map(key => ({ key }))
hasParam ? tempArr.push(...urlParamKeys) : false;
});
}
return (
<>
{tempArr.map((ele, i) =>
{tempArr.map((ele) =>
typeof ele === 'string' ? (
<span key={ele.trim()} className=' text-wrap'>
{ele.replace(/\n+/g, '\n')}
</span>
) : ele.key.includes('free') || ele.key.includes('detail') ? (
<Input.TextArea
key={`${ele.key}_${i}`}
key={ele.key}
rows={2}
onChange={(e) => {
onInput(tempItem, ele.key, e.target.value, paramsVal)
@ -76,14 +59,14 @@ const CategoryList = ({ dataSource, handleSendTemplate, valueMapped, onInput, ac
/>
) : (
<Input
key={`${ele.key}_${i}`}
key={ele.key}
onChange={(e) => {
onInput(tempItem, ele.key, e.target.value, paramsVal)
}}
className={ele.key.includes('free') || ele.key.includes('detail') ? `w-full block ` : `w-auto ${paramsVal[ele.key] ? 'max-w-24' : 'max-w-60'}`}
size={'small'}
title={ele.key}
placeholder={`${paramsVal[ele.key] || ele.key} ${ele?.placeholder || '按Tab键跳到下一个空格'}`}
placeholder={`${paramsVal[ele.key] || ele.key} 按Tab键跳到下一个空格`}
value={activeInput[tempItem.name]?.[ele.key] || paramsVal[ele.key] || ''}
// onPressEnter={() => handleSendTemplate(tempItem)}
/>
@ -100,19 +83,14 @@ const CategoryList = ({ dataSource, handleSendTemplate, valueMapped, onInput, ac
return (
<div className='pb-1'>
{'text' === headerObj.format.toLowerCase() && <div>{renderForm({ tempItem }, 'header')}</div>}
{'image' === headerObj.format.toLowerCase() && (
<div className='flex items-center'>
<img src={headerObj.example.header_url} height={100} className='mr-1'></img>
{renderForm({ tempItem }, 'header')}
</div>
)}
{'image' === headerObj.format.toLowerCase() && <img src={headerObj.example.header_url} height={100}></img>}
{['document', 'video'].includes(headerObj.format.toLowerCase()) && (
<a href={headerObj.example.header_url} target='_blank' key={headerObj.format} rel='noreferrer' className='text-sm'>
[&nbsp;{headerObj.format}&nbsp;]({headerObj.example.header_url})
</a>
)}
</div>
)
);
}
const renderButtons = ({ tempItem }) => {
if (isEmpty(tempItem.components.buttons)) {
@ -122,8 +100,7 @@ const CategoryList = ({ dataSource, handleSendTemplate, valueMapped, onInput, ac
return (
<div className='flex gap-1 pt-1'>
{buttons.map((btn, index) =>
<>
{btn.type.toLowerCase() === 'url' ? (
btn.type.toLowerCase() === 'url' ? (
<Button className='text-blue-500' size={'small'} href={btn.url} target={'_blank'} key={btn.url} rel='noreferrer'>
{btn.text}
</Button>
@ -131,18 +108,11 @@ const CategoryList = ({ dataSource, handleSendTemplate, valueMapped, onInput, ac
<Button className='text-blue-500' size={'small'} key={btn.phone_number} rel='noreferrer'>
{btn.text} ({btn.phone_number})
</Button>
)
: btn.type.toLowerCase() === 'copy_code' ? null
// (
// <span>{renderForm({ tempItem }, 'buttons')}</span>
// )
: (
<Button className='text-blue-500' size={'small'} key={`${btn.type}_${index}`} rel='noreferrer'>
) : (
<Button className='text-blue-500' size={'small'} key={btn.type} rel='noreferrer'>
{btn.text}
</Button>
)}
{Object.prototype.hasOwnProperty.call(btn, "example") ? (<span key={`${btn.type}_${index}`}>{renderForm({ tempItem }, 'buttons')}</span>) : null}
</>
)
)}
</div>
);
@ -209,12 +179,12 @@ const InputTemplate = ({ disabled = false, invokeSendMessage, channel }) => {
const [searchContent, setSearchContent] = useState('');
// : customer, agent
const valueMapped = { ...cloneDeep(currentConversation), ...objectMapper(loginUser, { usernameEN: [{ key: 'agent_name' }, { key: 'your_name' }, { key: 'your_name1' }, { key: 'your_name2' }] }), ...{ order_number: currentConversation.coli_id } };
const valueMapped = { ...cloneDeep(currentConversation), ...objectMapper(loginUser, { usernameEN: [{ key: 'agent_name' }, { key: 'your_name' }, { key: 'your_name1' }, { key: 'your_name2' }] }) };
useEffect(() => {
setDataSource([]);
// setDataSource(templates);
const mappedByCategory = groupBy(templates, 'category');
const mappedByLang = sortObjectsByKeysMap(groupBy(templates, 'displayLanguage'), ['en']); // todo:
const mappedByLang = sortObjectsByKeysMap(groupBy(templates, 'language'), ['en']); // todo:
setTemplateCMapped(mappedByCategory);
setTemplateLangMapped(mappedByLang);
return () => {};
@ -243,7 +213,6 @@ const InputTemplate = ({ disabled = false, invokeSendMessage, channel }) => {
const handleSendTemplate = (fromTemplate) => {
const mergeInput = { ...cloneDeep(valueMapped), ...activeInput[fromTemplate.name] };
// console.log('----------------------------------------------', mergeInput)
let valid = true;
const msgObj = {
type: 'whatsappTemplate',
@ -251,82 +220,29 @@ const InputTemplate = ({ disabled = false, invokeSendMessage, channel }) => {
template: {
name: fromTemplate.name,
language: { code: fromTemplate.language },
components: sortArrayByOrder(fromTemplate.components_origin.reduce((r, citem) => {
components: sortArrayByOrder(fromTemplate.components_origin.map((citem) => {
const keys = ((citem?.text || '').match(/{{(.*?)}}/g) || []).map((key) => key.replace(/{{|}}/g, ''));
const params = keys.map((v) => ({ type: 'text', text: getNestedValue(mergeInput, [v]) }));
const notTextKeys = [];
const paramNotText = [];
if (citem.type.toLowerCase() === 'header' && (citem?.format || 'text').toLowerCase() !== 'text') {
params[0] = { type: citem.format.toLowerCase(), [citem.format.toLowerCase()]: { link: mergeInput?.header_url || citem.example.header_url[0] } };
//
// notTextKeys.push('header_url');
// mergeInput?.header_url ? paramNotText.push(mergeInput?.header_url || '') : false;
params[0] = { type: citem.format.toLowerCase(), [citem.format.toLowerCase()]: { link: citem.example.header_url[0] } };
}
let buttonsComponents;
if (citem.type.toLowerCase() === 'buttons' ) {
buttonsComponents = citem.buttons.map((btn, i) => {
const hasParam = Object.prototype.hasOwnProperty.call(btn, "example"); // whatsappTemplateBtnParamTypesMapped
let fillBtn = {};
const paramKey = whatsappTemplateBtnParamTypesMapped[btn.type.toLowerCase()];
if (paramKey) {
params[0] = { type: paramKey, [paramKey]: mergeInput?.[btn.type.toLowerCase()] || '' };
notTextKeys.push(paramKey);
mergeInput?.[btn.type.toLowerCase()] ? paramNotText.push(mergeInput?.[btn.type.toLowerCase()] || '') : false;
fillBtn = { text: btn.text || `${btn.type}:${mergeInput?.[btn.type.toLowerCase()] || ''}` };
}
if (btn.type.toLowerCase() === 'url') {
const templateUrl = btn.url || '';
const urlParamKeys = (templateUrl.match(/{{(.*?)}}/g) || []).map((key) => key.replace(/{{|}}/g, ''));
const urlParams = urlParamKeys.map(key => ({ type: 'text', text: getNestedValue(mergeInput, [key]) }))
params.push(...urlParams);
notTextKeys.push(...urlParamKeys);
urlParamKeys.forEach(key => {
if (getNestedValue(mergeInput, [key])) {
paramNotText.push(getNestedValue(mergeInput, [key]));
}
});
fillBtn = hasParam ? { text: btn.text, url: replaceTemplateString(templateUrl, paramNotText) } : {};
}
// if (hasParam) {
// notTextKeys.push(paramKey);
// mergeInput?.[btn.type.toLowerCase()] ? paramNotText.push(mergeInput?.[btn.type.toLowerCase()] || '') : false;
// }
return hasParam ? { type: 'button', index: i, sub_type: btn.type.toLowerCase(), parameters: params, ...fillBtn } : null;
})
buttonsComponents = flush(buttonsComponents);
}
// console.log('******', buttonsComponents, '\n', notTextKeys, '\n', paramNotText)
const paramText = keys.length ? params.map((p) => p.text) : [];
const fillTemplate = paramText.length ? replaceTemplateString(citem?.text || '', paramText) : citem?.text || '';
valid = keys.length !== paramText.filter((s) => s).length ? false : valid;
valid = notTextKeys.length !== paramNotText.filter((s) => s).length ? false : valid;
const _components = ['body', 'header'].includes(citem.type.toLowerCase()) ? [{
return ['body', 'header'].includes(citem.type.toLowerCase()) ? {
type: citem.type.toLowerCase(),
parameters: params,
text: fillTemplate,
}] : ['buttons'].includes(citem.type.toLowerCase()) ? buttonsComponents : [{...citem, type: citem.type.toLowerCase(),}];
return r.concat(_components);
}, []), 'type', ['body', 'header', 'footer', 'button', 'buttons'] ),
components_omit: fromTemplate.components_origin.reduce((r, citem) => {
const _componentItems =
citem.type.toLowerCase() === 'buttons'
? citem.buttons.map((btn, index) => ({ ...btn, index, type: 'button', sub_type: btn.type.toLowerCase() }))
: [{ ...citem, type: citem.type.toLowerCase() }]
const staticComponents = _componentItems.filter((item) => !item.example && item.type.toLowerCase() !== 'body')
return r.concat(staticComponents)
}, []),
} : {...citem, type: citem.type.toLowerCase(),};
}), 'type', ['header', 'body', 'footer', 'buttons'] ),
},
template_origin: fromTemplate,
};
const plainTextMsgObj = {
type: 'text',
text: msgObj.template.components.filter(com => com.type.toLowerCase() === 'body').map((citem) => citem.text).join(''),
text: msgObj.template.components.map((citem) => citem.text).join(''),
};
if (valid !== true) {
notification.warning({
@ -338,7 +254,6 @@ const InputTemplate = ({ disabled = false, invokeSendMessage, channel }) => {
});
return false;
}
// console.log('------------------------------------------------------------------------------', msgObj );
invokeSendMessage(channel === 'waba' ? msgObj : plainTextMsgObj);
setOpenTemplates(false);
setActiveInput({});
@ -352,6 +267,10 @@ const InputTemplate = ({ disabled = false, invokeSendMessage, channel }) => {
});
};
return (
<>
<Popover
@ -399,7 +318,7 @@ const InputTemplate = ({ disabled = false, invokeSendMessage, channel }) => {
...(Object.keys(templateLangMapped).map(lang => ({
key: lang, label: lang.toUpperCase(), children: <CategoryList key={'lang-templates-'+lang} dataSource={templateLangMapped[lang]} {...{ handleSendTemplate, activeInput, onInput, valueMapped}} />
})))
]} defaultActiveKey='utility' tabBarExtraContent={{right: <Alert type='info' message={channel==='waba'?'请优先使用"触达率高"模板': '模板消息将用纯文本发送'} showIcon className='py-0' />, }} size='small' />
]} defaultActiveKey='utility' tabBarExtraContent={{right: <Alert type='info' message={channel==='waba'?'为提升账号质量, 请尽量使用"触达率高"模板': '模板消息将用纯文本发送'} showIcon className='py-0' />, }} size='small' />
) :
(
// Search result

@ -42,6 +42,7 @@ const MessagesHeader = () => {
{currentConversation.sn ? (
<div className='flex flex-col'>
<Typography.Text>{currentConversation.session_type === 1 ? '' : currentConversation?.channels?.whatsapp_phone_number}</Typography.Text>
<Typography.Text>{currentConversation?.channels?.email}</Typography.Text>
</div>
) : (
<Typography.Text strong type='danger'>

@ -13,8 +13,6 @@ import EmailDetail from './Components/EmailDetail';
import { useOrderStore, } from "@/stores/OrderStore";
import { isEmpty } from '@/utils/commons';
import useStyleStore from '@/stores/StyleStore';
import EmailListDrawer from './Components/EmailListDrawer';
import { POPUP_FEATURES } from '@/config';
const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
const userId = useAuthStore((state) => state.loginUser.userId);
@ -89,7 +87,7 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
setLongList(activeMessages);
const thisLastTime = activeMessages.length > 0 ? activeMessages[0].msgtime : '';
const loadNextPage = !(activeMessages.length === 0 || activeMessages.length < MESSAGE_PAGE_SIZE);
updateCurrentConversation({ lasttime1: thisLastTime, loadNextPage, });
updateCurrentConversation({ lasttime: thisLastTime, loadNextPage, });
return () => {};
}, [activeMessages, currentConversationSN]);
@ -125,7 +123,7 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
const thisLastTime = data.length > 0 ? data[0].msgtime : ''; // orgmsgtime
const loadNextPage = !(data.length === 0 || data.length < MESSAGE_PAGE_SIZE);
updateCurrentConversation({ lasttime1: thisLastTime, loadNextPage, });
updateCurrentConversation({ lasttime: thisLastTime, loadNextPage, });
// setPrevSN(item.sn);
setMsgLoading(false);
@ -147,7 +145,7 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
setLongList(prevValue => data.concat(prevValue));
const thisLastTime = data.length > 0 ? data[0].msgtime : '';
const loadNextPage = !(data.length === 0 || data.length < MESSAGE_PAGE_SIZE);
updateCurrentConversation({ lasttime1: thisLastTime, loadNextPage, });
updateCurrentConversation({ lasttime: thisLastTime, loadNextPage, });
return data.length;
};
@ -167,7 +165,7 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
return false;
case 'document':
window.open(msg.data.link || msg.data.uri, msg.data.link || msg.data.uri, POPUP_FEATURES);
window.open(msg.data.link || msg.data.uri, '_blank', 'noopener,noreferrer');
return false;
default:
@ -193,66 +191,27 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
const handleContactClick = (data) => {
return data.length > 1 ? handleContactListClick(data) : handleContactItemClick(data[0]);
}
// EmailEditor
const [setEditorOpen, setEditorProps] = useConversationStore((state) => [state.setEditorOpen, state.setEditorProps]);
const [openEmailEditor, setOpenEmailEditor] = useState(false);
const [fromEmail, setFromEmail] = useState('');
const [ReferEmailMsg, setReferEmailMsg] = useState('');
const [action, setAction] = useState('')
const onOpenEditor = (emailMsgContent, action='reply') => {
const onOpenEditor = (emailMsgContent) => {
const { from, to } = emailMsgContent; // msgtext
console.log('emailMsgContent', emailMsgContent);
// console.log('emailMsgContent', emailMsgContent);
setOpenEmailEditor(true);
// setFromEmail(to);
setFromEmail(action === 'edit' ? from : to)
setFromEmail(to);
setReferEmailMsg({...emailMsgContent, order_opi: Number(orderDetail?.opi_sn || userId)});
setAction(action)
setEditorProps({
action,
fromEmail: action === 'edit' ? from : to,
fromUser: Number(orderDetail?.opi_sn || userId),
fromOrder: currentConversation.coli_sn,
oid: orderDetail?.order_no || emailMsgContent?.coli_id,
receiverName: customerDetail.name,
quoteid: emailMsgContent.mai_sn || emailMsgContent.id,
conversationid: currentConversation.sn,
subject: emailMsgContent.subject,
});
// setEditorOpen(true);
};
const [openEmailDetail, setOpenEmailDetail] = useState(false);
const [emailDetail, setEmailDetail] = useState({});
const [initialPosition, setInitialPosition] = useState({})
const [initialSize, setInitialSize] = useState({})
const [emailItem, setEmailItem] = useState({});
const onOpenEmail = (emailMsg) => {
// setOpenEmailDetail(true);
// setEmailDetail({...emailMsg, order_opi: Number(orderDetail?.opi_sn || userId)});
setEmailItem({ MAI_SN: emailMsg.msgtext?.email?.mai_sn, MAI_Subject: emailMsg.msgtext?.email?.subject, SenderReceiver: '', MAI_SendDate: '' })
setOpenEmailDetail(true);
setEmailDetail({...emailMsg, order_opi: Number(orderDetail?.opi_sn || userId)});
}
const [emailList, setEmailList] = useState([]);
useEffect(() => {
const _emailList = longList
.filter((item) => item.msg_source === 'email')
.map((ele) => ({
...ele,
MAI_SN: ele.msgtext?.email?.mai_sn,
MAI_Subject: ele.msgtext?.email?.subject,
SenderReceiver: ele.from,
MAI_SendDate: ele.msgtime,
Direction: ele.msg_direction === 'inbound' ? '收' : '发',
}))
.reverse()
setEmailList(_emailList);
setEmailItem({});
}, [longList]);
return (
<>
<MessagesList key={`${currentConversationSN}_${currentConversationColiSN}`}
@ -302,7 +261,7 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
onCancel={() => setNewChatModalVisible(false)}
/>
{/* <EmailEditor open ={openEmailEditor} setOpen={setOpenEmailEditor} reference={ReferEmailMsg} setRefernce={setReferEmailMsg} {...{ fromEmail, }} key={'email-editor-reply'} /> */}
{/* <EmailEditorPopup
<EmailEditorPopup
open={openEmailEditor}
setOpen={setOpenEmailEditor}
fromEmail={fromEmail}
@ -312,11 +271,9 @@ const MessagesWrapper = ({ updateRead = true, forceGetMessages }) => {
customerDetail={customerDetail}
quoteid={ReferEmailMsg.mai_sn || ReferEmailMsg.id}
conversationid={currentConversation.sn}
key={`email-msg-reply-online_${ReferEmailMsg.id}`}
action={action}
/> */}
<EmailDetail open={openEmailDetail} setOpen={setOpenEmailDetail} emailMsg={emailDetail} key={`email-detail-${emailDetail.id}`} {...{initialPosition, initialSize, setInitialPosition, setInitialSize}} />
<EmailListDrawer showExpandBtn={false} list={emailList} emailItem={emailItem} currentConversationID={currentConversation.sn} oid={currentConversation.coli_sn} opi_sn={currentConversation.opi_sn} {...{onOpenEditor}} />
key={`email-msg-reply-top-popup_${ReferEmailMsg.id}`}
/>
<EmailDetail open={openEmailDetail} setOpen={setOpenEmailDetail} emailMsg={emailDetail} key={`email-detail-${emailDetail.id}`} />
</>
)
};

@ -87,7 +87,7 @@ const ReplyWrapper = () => {
icon: <WABIcon className={sessionType === 1 ? 'text-gray-500 [&_path]:fill-current' : ''} />,
children: <InputComposer currentActive={activeChannel === 'waba'} channel={'waba'} lastWABAMsg={lastWABAMsg} />,
},
// { key: 'email', label: mobile ? '' : '', icon: <MailOutlined className='text-indigo-500' />, children: <EmailComposer currentActive={activeChannel === 'email'} /> },
{ key: 'email', label: mobile ? '' : '邮件', icon: <MailOutlined className='text-indigo-500' />, children: <EmailComposer currentActive={activeChannel === 'email'} /> },
{
key: 'wai',
label: mobile ? '' : 'WhatsApp',

@ -1,13 +1,13 @@
import { LinkOutlined, MailOutlined, PhoneOutlined, UserOutlined, WhatsAppOutlined, FieldNumberOutlined } from "@ant-design/icons";
import { App, Button, Card, Empty, Flex, Select, Spin, Typography, Divider, Modal, List, Row, Col, Tag, Checkbox, Drawer, Input, Badge } from "antd";
import { App, Button, Card, Empty, Flex, Select, Spin, Typography, Divider, Modal, List, Row, Col, Tag, Checkbox, Drawer, Input } from "antd";
import { useEffect, useState, useRef, useCallback } from "react";
import { useNavigate, } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { useShallow } from 'zustand/react/shallow';
import { copy, isEmpty } from "@/utils/commons";
import { Conditional } from "@/components/Conditional";
import useConversationStore from "@/stores/ConversationStore";
import { useOrderStore, OrderLabelDefaultOptions, OrderStatusDefaultOptions, remindStatusOptions, fetchSetRemindStateAction, remindStatusOptionsMapped } from "@/stores/OrderStore";
import { useOrderStore, OrderLabelDefaultOptions, OrderStatusDefaultOptions, remindStatusOptions, fetchSetRemindStateAction } from "@/stores/OrderStore";
import useAuthStore from "@/stores/AuthStore";
import QuotesHistory from "./QuotesHistory";
import ConversationBind from "./../ConversationBind";
@ -16,11 +16,11 @@ import { useConversationNewItem } from "@/hooks/useConversation";
import EmailDetail from './../Components/EmailDetail';
import { postEditConversationItemColiAction } from "@/actions/ConversationActions";
import useStyleStore from '@/stores/StyleStore';
import SupplierEmailDrawer from "../Components/EmailListDrawer";
import { ExpandIcon } from "@/components/Icons";
import EmailDetailInline from "../Components/EmailDetailInline";
import SupplierEmailDrawer from "../Components/SupplierEmailDrawer";
// @Deprecated OrderProfile
const CustomerProfile = ({ disabled }) => {
const navigate = useNavigate();
const CustomerProfile = () => {
const { notification, message } = App.useApp();
const [loading, setLoading] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
@ -33,6 +33,7 @@ const CustomerProfile = ({ disabled }) => {
const currentConversationID = useConversationStore(useShallow(state => state.currentConversation?.sn || ""));
const channels = useConversationStore(state => state.currentConversation?.channels);
const [updateCurrentConversation] = useConversationStore(state => [state.updateCurrentConversation]);
const [emailMsg, setEmailMsg, detailPopupOpen, setDetailOpen, openDetail] = useConversationStore(state => [state.emailMsg, state.setEmailMsg, state.detailPopupOpen, state.setDetailOpen, state.openDetail]);
const loginUser = useAuthStore(state => state.loginUser);
const [
orderDetail, customerDetail, lastQuotation, quotationList, fetchOrderDetail, setOrderPropValue, appendOrderComment, fetchOtherEmail, otherEmailList, fetchHistoryOrder
@ -95,19 +96,19 @@ const CustomerProfile = ({ disabled }) => {
});
// fetchOtherEmail(currentOrder)
// .then(result => {
// // console.info(result)
// })
// .finally(() => setLoading(false))
// .catch(reason => {
// notification.error({
// message: "",
// description: reason.message,
// placement: "top",
// duration: 60,
// });
// });
fetchOtherEmail(currentOrder)
.then(result => {
// console.info(result)
})
.finally(() => setLoading(false))
.catch(reason => {
notification.error({
message: "查询供应商邮件出错",
description: reason.message,
placement: "top",
duration: 60,
});
});
} else if (isEmpty(currentOrder)) {
resetOrderStore();
}
@ -126,7 +127,22 @@ const CustomerProfile = ({ disabled }) => {
setNewChatModalVisible(false);
};
const [clicked3rdEmailItem, setClicked3rdEmailItem] = useState({});
const handle3rdEmailItemClick = useCallback((emailItem) => {
const emailMsg = {
conversationid: currentConversationID,
order_opi: orderDetail.opi_sn,
coli_sn: currentOrder,
id: emailItem.MAI_SN,
msgOrigin: {
from: '',
to: '',
id: emailItem.MAI_SN,
email: { mai_sn: emailItem.MAI_SN, subject: emailItem.MAI_Subject, id: emailItem.MAI_SN },
},
}
setEmailMsg(emailMsg);
openDetail();
}, [])
const handleOrderSwitch = async (coli_sn) => {
await postEditConversationItemColiAction({conversationid: currentConversationID, coli_sn });
@ -154,7 +170,7 @@ const CustomerProfile = ({ disabled }) => {
if (currentOrder) {
return (
<div className="divide-x-0 divide-y divide-dashed divide-gray-300 [&_.ant-divider]:my-1">
<div className="divide-x-0 divide-y divide-dashed divide-gray-300">
<Spin spinning={loading}>
<Card
className="p-2 "
@ -170,7 +186,7 @@ const CustomerProfile = ({ disabled }) => {
onChange={handleOrderSwitch}
/>}
actions={[
<Select disabled={disabled} className={`[&_.ant-select-selection-item]:text-gray-950`}
<Select
key={"orderlabel"}
size="small"
style={{
@ -194,7 +210,7 @@ const CustomerProfile = ({ disabled }) => {
value={orderDetail.tags}
options={orderLabelOptions}
/>,
<Select disabled={disabled} className={`[&_.ant-select-selection-item]:text-gray-950`}
<Select
key={"orderstatus"}
size="small"
style={{
@ -270,9 +286,7 @@ const CustomerProfile = ({ disabled }) => {
<Divider orientation="left">
<Typography.Text strong>催信:</Typography.Text>
</Divider>
{disabled ? (<div className="px-2"><span>{remindStatusOptionsMapped[orderRemindState]?.label}</span></div>) : <Checkbox.Group key='substatus' className="px-2" value={[orderRemindState]} options={remindStatusOptions} onChange={handleSetRemindState} />}
{/*
<Checkbox.Group key='substatus' value={[orderRemindState]} options={remindStatusOptions} onChange={handleSetRemindState} />
<Divider orientation="left">
<Typography.Text strong>最新报价</Typography.Text>
</Divider>
@ -283,7 +297,7 @@ const CustomerProfile = ({ disabled }) => {
whenTrue={
<>
<p className="m-0 py-2 line-clamp-2 ">
<a target="_blank" href={lastQuotation.letterurl} rel="noreferrer">
<a target="_blank" href={lastQuotation.letterurl}>
<LinkOutlined />
&nbsp;{lastQuotation.lettertitle}
</a>
@ -294,12 +308,11 @@ const CustomerProfile = ({ disabled }) => {
</>
}
/>
</Flex>*/}
{/*
</Flex>
<Divider orientation="left">
<Typography.Text strong>供应商邮件</Typography.Text>
<Badge count={otherEmailList.length} className='ml-2' color="oklch(62.3% 0.214 259.815)" />
<SupplierEmailDrawer title={'供应商邮件'} list={otherEmailList} currentConversationID={currentConversationID} opi_sn={orderDetail.opi_sn} oid={currentOrder} emailItem={clicked3rdEmailItem} />
<SupplierEmailDrawer list={otherEmailList} currentConversationID={currentConversationID} opi_sn={orderDetail.opi_sn} oid={currentOrder} />
</Divider>
<List
dataSource={otherEmailList}
@ -312,27 +325,21 @@ const CustomerProfile = ({ disabled }) => {
}
renderItem={(email) => (
<List.Item
className='hover:bg-stone-50 cursor-pointer [&.ant-list-item]:py-1 [&.ant-list-item]:px-2'
onClick={() => setClicked3rdEmailItem(email) }>
className='hover:bg-stone-50 cursor-pointer'
onClick={() => {
handle3rdEmailItemClick(email)
}}>
<Flex
vertical className="w-full"
vertical
>
<div className="text-stone-600 line-clamp-1">
<Typography.Text ellipsis={{tooltip: email.SenderReceiver}} className="text-stone-600">{email.SenderReceiver}</Typography.Text></div>
<div className="">{email.MAI_Subject}</div>
<div><Typography.Text ellipsis={{tooltip: email.SenderReceiver}} style={{width: 280}}><b>From: </b>{email.SenderReceiver}</Typography.Text></div>
<div><Typography.Text ellipsis={{tooltip: email.MAI_Subject}} style={{width: 280}}><b>Subject: </b>{email.MAI_Subject}</Typography.Text></div>
</Flex>
</List.Item>
)}
/> */}
/>
<Divider orientation="left">
<Typography.Text strong>表单信息</Typography.Text>
<Button className="ml-2"
size={"small"} disabled={disabled}
onClick={() => {
setIsModalOpen(true);
}}>
添加备注
</Button>
</Divider>
<p className="p-2 overflow-auto m-0 break-words whitespace-pre-wrap" dangerouslySetInnerHTML={{ __html: orderDetail.order_detail }}></p>
<Modal
@ -364,8 +371,16 @@ const CustomerProfile = ({ disabled }) => {
}}>
<textarea ref={orderCommentRef} className="w-full" rows={4}></textarea>
</Modal>
<Button
size={"small"}
onClick={() => {
setIsModalOpen(true);
}}>
添加备注
</Button>
</Spin>
<ConversationsNewItem initialValues={newChatFormValues} open={newChatModalVisible} onCreate={handleNewChat} onCancel={() => setNewChatModalVisible(false)} />
<EmailDetail open={detailPopupOpen} setOpen={setDetailOpen} emailMsg={emailMsg} key={`supplier-email-detail-1-${emailMsg?.id}`} />
</div>
);

@ -3,7 +3,6 @@ import { Button, Flex, List, Popover } from 'antd'
import { useState } from 'react'
import EmailQuotation from '../Components/EmailQuotation'
// @Deprecated
const QuotesHistory = ((props) => {
const [open, setOpen] = useState(false)

@ -22,11 +22,14 @@ import { useEffect, useState, useCallback, useRef } from 'react'
import { Link, NavLink, Outlet, useHref } from 'react-router-dom'
import '@/assets/App.css'
import AppLogo from '@/assets/highlights_travel_300_300_250613.png'
import AppLogo from '@/assets/highlights_travel_300_300.png'
import 'react-chat-elements/dist/main.css'
import ReloadPrompt from './ReloadPrompt'
import ClearCache from './ClearCache'
import SnippetList from '@/views/accounts/SnippetList'
import GeneratePayment from '@/views/accounts/GeneratePayment'
import { BUILD_VERSION, BUILD_DATE } from '@/config'
const { Header, Footer, Content } = Layout
@ -122,8 +125,26 @@ function DesktopApp() {
width: '100%',
background: 'white',
}}>
<Drawer
title='图文集'
placement={'top'}
size={'large'}
onClose={() => closeSnippetDrawer()}
open={snippetDrawerOpen}
>
<SnippetList></SnippetList>
</Drawer>
<Drawer
title='支付链接'
placement={'top'}
size={'large'}
onClose={() => closePaymentDrawer()}
open={paymentDrawerOpen}
>
<GeneratePayment></GeneratePayment>
</Drawer>
<Row gutter={{ md: 24 }} align='middle'>
<Col flex='240px'>
<Col flex='220px'>
<NavLink to='/'>
<img src={AppLogo} className='logo' alt='App logo' />
</NavLink>
@ -152,13 +173,13 @@ function DesktopApp() {
</Link>
),
},
// {
// key: '/callcenter/call',
// label: <Link to='/callcenter/call'></Link>,
// },
{
key: '/callcenter/call',
label: <Link to='/callcenter/call'>语音通话</Link>,
},
{
key: '/chat/history',
label: <Link to='/chat/history'>历史记录</Link>,
label: <Link to='/chat/history'>聊天记录</Link>,
},
{
key: '/customer_relation/index',

@ -1,28 +0,0 @@
import { useParams } from 'react-router-dom';
import { App, ConfigProvider } from 'antd'
import useStyleStore from '@/stores/StyleStore'
import EmailDetailInline from './Conversations/Online/Components/EmailDetailInline';
/**
* 独立窗口查看邮件
*
* - 从销售平台进入: 自动复制 storage, 可读取loginUser
*
* ! 无状态管理
*/
const EmailDetailWindow = () => {
const pageParam = useParams();
// console.log(pageParam)
// const [mobile] = useStyleStore((state) => [state.mobile])
return (
<>
<ConfigProvider theme={{ token: { colorPrimary: '#6366f1' } }}>
<EmailDetailInline mailID={pageParam.mailid} variant={'full'} />
</ConfigProvider>
</>
)
}
export default EmailDetailWindow

@ -1,739 +0,0 @@
import { useEffect, useState, useRef, useCallback, useMemo } from 'react'
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { App, ConfigProvider, Button, Form, Input, Flex, Checkbox, Popconfirm, Select, Space, Upload, Divider, Modal, Tabs, Radio, Typography, } from 'antd'
import { UploadOutlined, LoadingOutlined, SaveOutlined, SendOutlined, CheckCircleOutlined, ExclamationCircleFilled } from '@ant-design/icons'
import useStyleStore from '@/stores/StyleStore'
// import useConversationStore from '@/stores/ConversationStore'
import useAuthStore from '@/stores/AuthStore'
import LexicalEditor from '@/components/LexicalEditor'
import { v4 as uuid } from 'uuid'
import { cloneDeep, debounce, isEmpty, olog, omitEmpty } from '@/utils/commons'
import { writeIndexDB, readIndexDB, deleteIndexDBbyKey, } from '@/utils/indexedDB';
import '@/views/Conversations/Online/Input/EmailEditor.css'
import { deleteEmailAttachmentAction, parseHTMLString, postSendEmail, saveEmailDraftOrSendAction } from '@/actions/EmailActions'
import { sentMsgTypeMapped } from '@/channel/bubbleMsgUtils'
import { EmailBuilder, openPopup, useEmailDetail, useEmailSignature, useEmailTemplate } from '@/hooks/useEmail'
import useSnippetStore from '@/stores/SnippetStore'
// import { useOrderStore } from '@/stores/OrderStore'
import PaymentlinkBtn from '@/views/Conversations/Online/Input/PaymentlinkBtn'
import { TextIcon } from '@/components/Icons';
import { EMAIL_ATTA_HOST, POPUP_FEATURES } from '@/config';
const {confirm} = Modal;
//
// .application, .exe, .app
const disallowedAttachmentTypes = [
'.ps1',
'.msi',
'application/x-msdownload',
'application/x-ms-dos-executable',
'application/x-ms-wmd',
'application/x-ms-wmz',
'application/x-ms-xbap',
'application/x-msaccess',
]
const getAbstract = (longtext) => {
const lines = longtext.split('\n')
const firstLine = lines[0]
const abstract = firstLine.substring(0, 20)
return abstract
}
const parseHTMLText = (html) => {
const parser = new DOMParser()
const dom = parser.parseFromString(html, 'text/html')
// Replace <br> and <p> with line breaks
// Array.from(dom.body.querySelectorAll('br, p')).forEach((el) => {
// el.textContent = '<br>' + el.textContent
// })
// Replace <hr> with a line of dashes
// Array.from(dom.body.querySelectorAll('hr')).forEach((el) => {
// el.innerHTML = '<p><hr>------------------------------------------------------------------</p>'
// })
const line = '<p>------------------------------------------------------------------</p>'
return line+(dom.body.innerHTML || '')
}
const generateQuoteContent = (mailData, isRichText = true) => {
const html = `<br><hr><blockquote><p class="font-sans"><b><strong >From: </strong></b><span >${(mailData.info?.MAI_From || '')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')} </span></p><p class="font-sans"><b><strong >Sent: </strong></b><span >${
mailData.info?.MAI_SendDate || ''
}</span></p><p class="font-sans"><b><strong >To: </strong></b><span >${(mailData.info?.MAI_To || '')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')}</span></p><p class="font-sans"><b><strong >Subject: </strong></b><span >${mailData.info?.MAI_Subject || ''}</span></p><p>${
mailData.info?.MAI_ContentType === 'text/html' ? mailData.content : mailData.content.replace(/\r\n/g, '<br>')
}</p></blockquote>`
return isRichText ? html : parseHTMLText(html)
}
const generateMailContent = (mailData) => mailData.info?.MAI_ContentType === 'text/html' ? `${mailData.content}<br>` : `<p>${mailData.content.replace(/\r\n/g, '<br>')}</p>`
/**
* 独立窗口编辑器
*
* - 从销售平台进入: 自动复制 storage, 可读取loginUser
*
* ! 无状态管理
*/
const NewEmail = () => {
const pageParam = useParams();
const { templateKey } = pageParam
const editorKey = pageParam.action==='new' ? `new-0-${pageParam.oid}` : `${pageParam.action}-${pageParam.quoteid}`
const { notification, message } = App.useApp()
const [form] = Form.useForm()
const [mobile] = useStyleStore((state) => [state.mobile])
const [userId, username, emailList] = useAuthStore((state) => [state.loginUser.userId, state.loginUser.username, state.loginUser.emailList])
const emailListOption = useMemo(() => emailList?.map((ele) => ({ ...ele, label: ele.email, key: ele.email, value: ele.email })) || [], [emailList])
const emailListOPIMapped = useMemo(() => emailListOption?.reduce((r, v) => ({ ...r, [v.opi_sn]: v }), {}), [emailListOption]);
const emailListAddrMapped = useMemo(() => emailListOption?.reduce((r, v) => ({ ...r, [v.email]: v }), {}), [emailListOption])
const emailListMatMapped = useMemo(() => emailListOption?.reduce((r, v) => ({ ...r, [v.mat_sn]: v }), {}), [emailListOption])
// console.log('emailListMapped', emailListOption, emailListAddrMapped);
const [emailAccount, setEmailAccount] = useState({});
const [emailAccountOPI, setEmailAccountOPI] = useState(0);
const mai_sn = pageParam.quoteid // activeEdit.quoteid
const { loading: quoteLoading, mailData, orderDetail, postEmailSaveOrSend } = useEmailDetail(mai_sn, null, pageParam.oid)
const { loading: loadingTamplate, templateContent } = useEmailTemplate(templateKey, {coli_sn: pageParam.oid, opi_sn: orderDetail.opi_sn || mailData.info?.MAI_OPI_SN || 0, lgc: 1});
const initOPI = useMemo(() => emailAccountOPI || orderDetail.opi_sn || mailData.info?.MAI_OPI_SN || 0, [emailAccountOPI, mailData, orderDetail])
const { signature } = useEmailSignature(initOPI)
const [initialContent, setInitialContent] = useState('')
const [showQuoteContent, setShowQuoteContent] = useState(false)
const [quoteContent, setQuoteContent] = useState('')
// const [newFromEmail, setNewFromEmail] = useState('')
// const [newToEmail, setNewToEmail] = useState('')
// const [emailOPI, setEmailOPI] = useState('')
// const [emailOrder, setEmailOrder] = useState('')
// const [emailOrderSN, setEmailOrderSN] = useState('')
// const [emailMat, setEmailMat] = useState('')
// const [contentPrefix, setContentPrefix] = useState('')
const [localDraft, setLocalDraft] = useState();
// const readMailboxLocalCache = async () => {
// console.log('===============', 'readMailboxLocalCache')
// const readCache = await readIndexDB(editorKey, 'draft', 'mailbox')
// if (readCache) {
// const btn = (
// <Space>
// <Button type='link' size='small' onClick={() => notification.destroy()}>
//
// </Button>
// {/* <Button type="primary" size="small" onClick={() => notification.destroy()}>
// Confirm
// </Button> */}
// </Space>
// )
// // notification.open({
// // key: editorKey,
// // placement: 'top',
// // // message: '',
// // description: '',
// // duration: 0,
// // actions: btn,
// // })
// setLocalDraft(readCache)
// if (!isEmpty(localDraft)) {
// const { htmlContent, ...draftFormsValues } = localDraft
// const _findMatOld = emailListMatMapped?.[draftFormsValues.mat_sn]
// const _from = draftFormsValues?.from || _findMatOld?.email || ''
// form.setFieldsValue(draftFormsValues)
// setNewFromEmail(_from)
// setEmailOPI(draftFormsValues.opi_sn)
// setEmailMat(draftFormsValues.mat_sn)
// setEmailOrder(draftFormsValues.coli_sn)
// requestAnimationFrame(() => {
// setInitialContent(htmlContent)
// })
// return false
// }
// }
// }
// useEffect(() => {
// readMailboxLocalCache()
// return () => {}
// }, [])
//
// -
// -
useEffect(() => {
// console.log('useEffect 1---- \nform.setFieldsValue ');
if (isEmpty(mailData.content) && isEmpty(orderDetail.order_no)) {
// return () => {}
}
const docTitle = mailData.info?.MAI_Subject || 'New Email-';
document.title = docTitle
const { order_no } = orderDetail
// setContentPrefix(order_no ? `<p>Dear Mr./Ms. ${orderDetail.contact?.[0]?.name || ''}</p><p>Reference Number: ${order_no}</p>` : '')
const orderPrefix = order_no ? `<p>Dear Mr./Ms. ${orderDetail.contact?.[0]?.name || ''}</p><p>Reference Number: ${order_no}</p>` : ''
const { info } = mailData
const { ...templateFormValues } = templateContent;
const orderReceiver = orderDetail.contact?.[0]?.email || ''
const _findMatOld = emailListOPIMapped?.[orderDetail.opi_sn]
const orderSender = _findMatOld?.email || ''
const _findMatOldE = emailListMatMapped?.[info.MAI_MAT_SN]
const quotedMailSender = _findMatOldE?.email || ''
const sender = quotedMailSender || orderSender
const quotedMailSenderObj = emailAccount?.email || sender; // { key: sender, label: sender, value: sender }
const defaultMAT = emailListAddrMapped?.[sender]?.mat_sn || ''
const _form2 = {
coli_sn: Number(pageParam.oid) || info?.MAI_COLI_SN || '',
mat_sn: emailAccount?.mat_sn || info?.MAI_MAT_SN || defaultMAT,
opi_sn: emailAccount?.opi_sn || info?.MAI_OPI_SN || orderDetail.opi_sn || '',
}
const originalContentType = info?.mailType === 'text/html';
setIsRichText(originalContentType)
let readyToInitialContent = '';
let _formValues = {};
// setShowCc(!isEmpty(mailData.info?.MAI_CS));
const signatureBody = generateMailContent({ content: signature })
// const preQuoteBody = generateQuoteContent(mailData)
// const _initialContent = isEmpty(mailData.info) ? signatureBody : signatureBody+preQuoteBody
// 稿: ``id
if (!isEmpty(mailData.info) && !['edit'].includes(pageParam.action)) {
readyToInitialContent = orderPrefix + '<br>' + signatureBody
}
switch (pageParam.action) {
case 'reply':
_formValues = {
from: quotedMailSenderObj,
to: info?.replyTo || orderReceiver,
cc: info?.MAI_CS || '',
// bcc: quote.bcc || '',
subject: `Re: ${info.MAI_Subject || ''}`,
..._form2
}
readyToInitialContent += generateQuoteContent(mailData, originalContentType)
break
case 'replyall':
_formValues = {
from: quotedMailSenderObj,
to: info?.replyToAll || orderReceiver,
cc: info?.MAI_CS || '',
// bcc: quote.bcc || '',
subject: `Re: ${info.MAI_Subject || ''}`,
..._form2
}
readyToInitialContent += generateQuoteContent(mailData, originalContentType)
break
case 'forward':
_formValues = {
from: quotedMailSenderObj,
subject: `Fw: ${info.MAI_Subject || ''}`,
// coli_sn: pageParam.oid,
..._form2
}
readyToInitialContent += generateQuoteContent(mailData, originalContentType)
break
case 'edit':
_formValues = {
from: quotedMailSenderObj,
to: info?.MAI_To || '',
cc: info?.MAI_CS || '',
subject: `${info.MAI_Subject || ''}`,
id: pageParam.quoteid,
mai_sn: pageParam.quoteid,
..._form2
}
readyToInitialContent = generateMailContent(mailData)
setFileList(mailData.attachments.map(ele => ({ uid: ele.ATI_SN, name: ele.ATI_Name, url: ele.ATI_ServerFile, fullPath: `${EMAIL_ATTA_HOST}${ele.ATI_ServerFile}` })))
break
case 'new':
_formValues = {
...templateFormValues,
from: quotedMailSenderObj,
to: orderReceiver || info?.MAI_To || '',
subject: `${info.MAI_Subject || templateFormValues.subject || ''}`,
..._form2,
}
readyToInitialContent = generateMailContent({ content: templateContent.bodycontent || readyToInitialContent || `<p></p><br>${signatureBody}` || '' })
// setFileList(mailData.attachments.map(ele => ({ uid: ele.ATI_SN, name: ele.ATI_Name, url: ele.ATI_ServerFile, fullPath: `${EMAIL_ATTA_HOST}${ele.ATI_ServerFile}` })))
setIsRichText(true)
break
default:
break
}
// olog('222', _formValues, pageParam.action)
form.setFieldsValue(_formValues) // todo: from
setInitialContent(readyToInitialContent);
return () => {}
}, [orderDetail.order_no, quoteLoading, loadingTamplate, emailAccount, signature])
// const readFromTemplate = () => {
// const { mailcontent, ...templateFormValues } = templateContent;
// if (mailcontent) {
// const _findMatOld = emailListOPIMapped?.[orderDetail.opi_sn]
// const _from = _findMatOld?.email || ''
// form.setFieldsValue({...templateFormValues, to: orderDetail?.contact?.[0]?.email || '', from1: { key: _from, value: _from, label: _from}});
// // setNewFromEmail(_from);
// // setEmailOPI(draftFormsValues.opi_sn)
// requestAnimationFrame(() => {
// setInitialContent(mailcontent);
// });
// }
// }
useEffect(() => {
// readMailboxLocalCache()
if (loadingTamplate) {
notification.open({
key: editorKey,
placement: 'top',
// message: '',
description: '正在加载邮件模板...',
duration: 0,
icon: <LoadingOutlined />,
// actions: btn,
// closeIcon: null,
closable: false,
})
} else {
notification.destroy(editorKey)
}
// readFromTemplate();
return () => {}
}, [loadingTamplate])
const handleSwitchEmail = (value) => {
// const { value } = labelValue
// setNewFromEmail(value)
const _findMat = emailListAddrMapped?.[value]
form.setFieldsValue({ mat_sn: _findMat?.mat_sn, opi_sn: _findMat?.opi_sn })
// console.log(_findMat, 'handleSwitchEmail')
setEmailAccount(_findMat)
setEmailAccountOPI(_findMat?.opi_sn)
}
const [isRichText, setIsRichText] = useState(mobile === false)
// const [isRichText, setIsRichText] = useState(false); //
const [htmlContent, setHtmlContent] = useState('')
const [textContent, setTextContent] = useState('')
const [showCc, setShowCc] = useState(true)
const [showBcc, setShowBcc] = useState(false)
const handleShowCc = () => {
setShowCc(true)
}
const handleShowBcc = () => {
setShowBcc(true)
}
const handleEditorChange = ({ editorStateJSON, htmlContent, textContent }) => {
const _text = textContent.replace(/\r\n/g, '\n').replace(/\n{2,}/g, '\n')
// console.log('textContent---\n', textContent, 'textContent');
// console.log('html', html);
setHtmlContent(htmlContent)
setTextContent(_text)
form.setFieldValue('content', htmlContent)
const abstract = _text;
// const { bodyText: abstract } = parseHTMLString(htmlContent, true);
// form.setFieldValue('abstract', getAbstract(textContent))
const formValues = omitEmpty(form.getFieldsValue());
if (!isEmpty(formValues)) {
debouncedSave({ ...form.getFieldsValue(), htmlContent, abstract, })
}
}
const [openPlainTextConfirm, setOpenPlainTextConfirm] = useState(false)
const handlePlainTextOpenChange = ({ target }) => {
const { value: newChecked } = target
if (newChecked === true) {
setIsRichText(true)
setOpenPlainTextConfirm(false)
return
}
setOpenPlainTextConfirm(true)
}
const confirmPlainText = () => {
setIsRichText(false)
setOpenPlainTextConfirm(false)
}
// :
// 1. ~~
// 2.
const [fileList, setFileList] = useState([])
// const handleChange = (info) => {
// let newFileList = [...info.fileList]
// // 2. Read from response and show file link
// newFileList = newFileList.map((file) => {
// if (file.response) {
// // Component will show file.url as link
// file.url = file.response.url
// }
// return file
// })
// setFileList(newFileList)
// }
const normFile = (e) => {
// console.log('Upload event:', e);
if (Array.isArray(e)) {
return e
}
return e?.fileList
}
const uploadProps = {
// action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
// onChange: handleChange,
multiple: true,
fileList,
beforeUpload: (file) => {
// console.log('beforeUpload', file);
const lastDotIndex = file.name.lastIndexOf('.')
const extension = file.name.slice(lastDotIndex).toLocaleLowerCase()
if (disallowedAttachmentTypes.includes(file.type) || disallowedAttachmentTypes.includes(extension)) {
message.warning('不支持的文件格式: ' + extension)
return false
}
setFileList((prev) => [...prev, file])
return false // ,
},
onRemove: async (file) => {
console.log('onRomove', file)
if (file.fullPath) {
try {
const x = await deleteEmailAttachmentAction([file.uid]);
message.success(`已删除 ${file.name}`, 2)
} catch (error) {
console.error(error)
notification.error({
key: editorKey,
message: '删除失败',
description: error.message,
placement: 'top',
duration: 3,
})
return false;
}
}
const index = fileList.indexOf(file)
const newFileList = fileList.slice()
newFileList.splice(index, 1)
setFileList(newFileList)
},
onPreview: (file) => {
// console.log('pn preview', file);
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = (e) => {
if (file.size > 1.5 * 1024 * 1024) {
message.info('附件太大,无法预览')
// message.info(', ')
// var downloadLink = document.createElement('a');
// downloadLink.href = e.target.result;
// downloadLink.download = file.name;
// downloadLink.click();
resolve(e.target.result)
return
}
var win = window.open('', file.uid, POPUP_FEATURES)
win.document.body.style.margin = '0'
if (file.type.startsWith('image/')) {
win.document.write("<img src='" + e.target.result + '\' style="max-width: 100%;" />')
} else if (file.type.startsWith('text/') || file.type === 'application/html' || file.type === 'application/xhtml+xml') {
var iframe = win.document.createElement('iframe')
iframe.srcdoc = e.target.result
iframe.style.width = '100%'
iframe.style.height = '100%'
iframe.style.border = 'none'
win.document.body.appendChild(iframe)
win.document.body.style.margin = '0'
} else if (file.type === 'application/pdf') {
// win.document.write("<iframe src='" + e.target.result + "' width='100%' height='100%' frameborder=\"0\"></iframe>");
win.document.write("<embed src='" + e.target.result + "' width='100%' height='100%' style=\"border:none\"></embed>")
win.document.body.style.margin = '0'
} else if (file.type.startsWith('audio/')) {
win.document.write("<audio controls src='" + e.target.result + '\' style="max-width: 100%;"></audio>')
} else if (file.type.startsWith('video/')) {
win.document.write("<video controls src='" + e.target.result + '\' style="max-width: 100%;"></video>')
} else {
win.document.write('<h2>Preview not available for this file type</h2>')
}
// win.document.write("<iframe src='" + dataURL + "' width='100%' height='100%' style=\"border:none\"></iframe>");
resolve(reader.result)
}
if (file.fullPath) {
openPopup(file.fullPath, file.uid)
}
else if (file.type.startsWith('text/') || file.type === 'application/html' || file.type === 'application/xhtml+xml') {
reader.readAsText(file)
} else {
reader.readAsDataURL(file)
}
// reader.readAsDataURL(file);
reader.onerror = (error) => reject(error)
})
},
}
const [sendLoading, setSendLoading] = useState(false)
const onHandleSaveOrSend = async (isDraft = false) => {
// console.log('onSend callback', '\nisRichText', isRichText);
// console.log(form.getFieldsValue());
const body = structuredClone(form.getFieldsValue())
body.attaList = fileList;
// console.log('body', body, '\n', fileList);
const values = await form.validateFields()
// const preQuoteBody = !['edit', 'new'].includes(pageParam.action) && pageParam.quoteid ? (quoteContent ? quoteContent : generateQuoteContent(mailData, isRichText)) : ''
body.mailcontent = isRichText ? EmailBuilder({ subject: values.subject, content: htmlContent }) : textContent
body.cc = values.cc || ''
body.bcc = values.bcc || ''
body.mailtype = values.mailtype || ''
body.order_mail_type = values.mailtype || ''
setSendLoading(!isDraft)
notification.open({
key: editorKey,
placement: 'top',
// message: '',
description: '正在保存...',
duration: 0,
icon: <LoadingOutlined className='text-primary' />,
closable: false,
})
// body.externalID = stickToCid
// body.actionID = `${stickToCid}.${msgObj.id}`
body.contenttype = isRichText ? 'text/html' : 'text/plain'
try {
// console.log('postSendEmail', body, '\n');
// console.log('🎈postSendEmail mailContent', body.mailcontent, '\n');
// throw new Error('test')
// return;
const mailSavedId = await postEmailSaveOrSend(body, isDraft)
form.setFieldsValue({
mai_sn: mailSavedId,
id: mailSavedId,
})
// bubbleMsg.email.mai_sn = mailSavedId
// setSendLoading(false);
if (!isDraft) {
notification.success({
key: editorKey,
message: '成功',
description: isDraft ? '' : '窗口将自动关闭...',
placement: 'top',
duration: 2,
showProgress: true,
pauseOnHover: true,
onClose: () => {
deleteIndexDBbyKey(editorKey, 'draft', 'mailbox');
isDraft ? false : window.close();
},
})
} else { notification.destroy(editorKey) }
// setOpen(false)
} catch (error) {
console.error(error)
notification.error({
key: editorKey,
message: '邮件保存失败',
description: error.message,
placement: 'top',
duration: 3,
})
} finally {
setSendLoading(false)
}
}
const [openDrawerSnippet] = useSnippetStore((state) => [state.openDrawer])
const idleCallbackId = useRef(null)
const debouncedSave = useCallback(
debounce((data) => {
idleCallbackId.current = window.requestIdleCallback(() => {
console.log('Saving data (idle, debounced):', data)
writeIndexDB([{ ...data, key: editorKey }], 'draft', 'mailbox')
})
}, 1500), // 1.5s
[],
)
useEffect(() => {
return () => {
if (idleCallbackId.current && window.cancelIdleCallback) {
window.cancelIdleCallback(idleCallbackId.current)
}
}
}, [debouncedSave])
const onEditChange = (changedValues, allValues) => {
// console.log('onEditChange', changedValues, '\n', allValues)
if ('from' in changedValues) {
handleSwitchEmail(allValues.from);
}
}
return (
<>
<ConfigProvider theme={{ token: { colorPrimary: '#6366f1' } }}>
<Form
form={form}
onValuesChange={onEditChange}
// onFinishFailed={onFinishFailed}
preserve={false}
name={`email_max_form`}
size='small'
layout={'inline'}
variant={'borderless'}
// initialValues={{}}
// onFinish={() => {}}
className='email-editor-wrapper *:mb-2 *:border-b *:border-t-0 *:border-x-0 *:border-indigo-100 *:border-solid '
requiredMark={false}
// labelCol={{ span: 3 }}
>
<div className='w-full flex flex-wrap gap-2 justify-start items-center text-indigo-600 pb-1 mb-2 border-x-0 border-t-0 border-b border-solid border-neutral-200'>
<Button type='primary' size='middle' onClick={() => onHandleSaveOrSend()} loading={sendLoading} icon={<SendOutlined />}>
发送
</Button>
<Form.Item name={'from'} rules={[{ required: true, message: '请选择发件地址' }]} >
<Select labelInValue={false} options={emailListOption} labelRender={item => `发件人: ${item?.label || '选择'}`} variant={'borderless'} placeholder='发件人: 选择' className='[&_.ant-select-selection-item]:font-bold [&_.ant-select-selection-placeholder]:font-bold [&_.ant-select-selection-placeholder]:text-black' classNames={{popup: {root:'min-w-60'}}} />
</Form.Item>
{/* <div className="ant-form-item-explain-error text-red-500" >请选择发件地址</div> */}
<div className='ml-auto'></div>
<span>{orderDetail.order_no}</span>
<span>{templateContent.mailtypeName}</span>
<Popconfirm trigger1={['hover', 'click']}
description='切换内容为纯文本格式将丢失信件和签名的格式, 确定使用纯文本?'
onConfirm={confirmPlainText}
open={openPlainTextConfirm}
onCancel={() => setOpenPlainTextConfirm(false)}>
{/* <Checkbox checked={!isRichText} onChange={handlePlainTextOpenChange}>
纯文本
</Checkbox> */}
{/* <Button type='link' size='small' icon={<TextIcon />} className=' ' >纯文本</Button> */}
<Radio.Group options={[{label: '纯文本', value: false}, {label: '富文本', value: true}]} optionType="button" buttonStyle="solid" onChange={handlePlainTextOpenChange} value={isRichText} size='small' />
</Popconfirm>
<Button onClick={() => onHandleSaveOrSend(true)} type='dashed' icon={<SaveOutlined />} size='small' className='' >存草稿</Button>
</div>
<Form.Item className='w-full'>
<Space.Compact className='w-full'>
<Form.Item name={'to'} label='收件人' rules={[{ required: true }]} className='!flex-1'>
<Input className='w-full' />
</Form.Item>
<Flex gap={4}>
{!showCc && (
<Button type='text' onClick={handleShowCc}>
抄送
</Button>
)}
{!showBcc && (
<Button type='text' hidden={showBcc} onClick={handleShowBcc}>
密送
</Button>
)}
</Flex>
</Space.Compact>
</Form.Item>
<Form.Item label='抄&nbsp;&nbsp;&nbsp;&nbsp;送' name={'cc'} hidden={!showCc} className='w-full pt-1'>
<Input />
</Form.Item>
<Form.Item label='密&nbsp;&nbsp;&nbsp;&nbsp;送' name={'bcc'} hidden={!showBcc} className='w-full pt-1'>
<Input />
</Form.Item>
<Form.Item label='主&nbsp;&nbsp;&nbsp;&nbsp;题' name={'subject'} rules={[{ required: true }]} className='w-full pt-1'>
<Input />
</Form.Item>
<Form.Item name='atta' label='' className='w-full py-1 border-b-0' valuePropName='fileList' getValueFromEvent={normFile}>
<Flex justify='space-between'>
<Upload {...uploadProps} name='file' className='w-full [&_.ant-upload-list-item-name]:cursor-pointer'>
<Button icon={<UploadOutlined />}>附件</Button>
</Upload>
<Flex align={'center'} className='absolute right-0'>
<Divider type='vertical' />
<Button type={'link'} onClick={() => openDrawerSnippet()}>
图文集
</Button>
<PaymentlinkBtn type={'link'} />
{/* 更多工具 */}
{/* <Popover
content={
<div className='flex flex-col gap-2'>
<Button type={'link'}>??</Button>
</div>
}
trigger='click'
><MoreOutlined /></Popover> */}
</Flex>
</Flex>
</Form.Item>
<Form.Item name='content' hidden>
<Input />
</Form.Item>
<Form.Item name='abstract' hidden>
<Input />
</Form.Item>
<Form.Item name='id' hidden>
<Input />
</Form.Item>
<Form.Item name='mai_sn' hidden>
<Input />
</Form.Item>
<Form.Item name='mat_sn' hidden>
<Input />
</Form.Item>
<Form.Item name='coli_sn' hidden>
<Input />
</Form.Item>
<Form.Item name='opi_sn' hidden>
<Input />
</Form.Item>
<Form.Item name='mailtype' hidden>
<Input />
</Form.Item>
</Form>
<LexicalEditor {...{ isRichText }} onChange={handleEditorChange} defaultValue={initialContent} />
{/* {!isEmpty(Number(pageParam.quoteid)) && pageParam.action!=='edit' && !showQuoteContent && (
<div className='flex justify-start items-center ml-2'>
<Button className='flex gap-2 ' type='link' onClick={() => {
setShowQuoteContent(!showQuoteContent);
setInitialContent(pre => pre + generateQuoteContent(mailData))
}}>
显示引用内容
</Button>
</div>
)}
{showQuoteContent && (
<blockquote
// contentEditable
className='border-0 outline-none cursor-text'
onBlur={(e) => setQuoteContent(`<blockquote>${e.target.innerHTML}</blockquote>`)}
dangerouslySetInnerHTML={{ __html: generateQuoteContent(mailData) }}></blockquote>
)} */}
</ConfigProvider>
</>
)
}
export default NewEmail

@ -45,7 +45,7 @@ function GeneratePayment() {
const orderNumber = result.orderDetail.order_no
const travelAdvisor = loginUser.accountList.length > 0 ? (loginUser.accountList[0]?.OPI_NameEN || '') : ''
generateForm.setFieldsValue({
// notifyEmail: getPrimaryEmail(),
notifyEmail: getPrimaryEmail(),
orderNumber: orderNumber,
description: 'Tracking Code: ' + orderNumber + '\r\nTravel Advisor: ' + travelAdvisor + '\r\nContent: \r\n',
langauge: 'US',
@ -60,7 +60,7 @@ function GeneratePayment() {
// })
} else {
generateForm.setFieldsValue({
// notifyEmail: getPrimaryEmail(),
notifyEmail: getPrimaryEmail(),
description: 'Tracking Code: \r\nTravel Advisor: \r\nContent: \r\n',
langauge: 'US',
orderType: '227001',
@ -110,7 +110,6 @@ function GeneratePayment() {
<Select
options={[
{ value: 'US', label: '英语' },
{ value: 'en_HTravel', label: '英语(Highlights)' },
{ value: 'de_de', label: '德语' },
{ value: 'fr_fr', label: '法语' },
{ value: 'es_es', label: '西语' },
@ -171,6 +170,9 @@ function GeneratePayment() {
<Form.Item label='描述' name='description'>
<Input.TextArea rows={4} />
</Form.Item>
<Form.Item label='通知邮箱' name='notifyEmail'>
<Input />
</Form.Item>
</Form>
<Flex gap='middle' justify='center'>
<Button type='primary' loading={isHtmlLoading} onClick={handleGenerate}>

@ -113,7 +113,7 @@ function SnippetList() {
snippetForm.resetFields()
setSnippetModalOpen(false)}
}
destroyOnHidden
destroyOnClose
forceRender
modalRender={(dom) => (
<Form
@ -210,7 +210,7 @@ function SnippetList() {
</Button>
</Form.Item>
</Form>
<Row gutter={6} className=' ' style={{height: '591px'}}>
<Row gutter={6} className=' ' style={{height: 'calc(100vh - 196px)'}}>
<Col span={8} className='h-[inherit] overflow-x-hidden overflow-y-auto'>
<List
bordered

@ -1,23 +1,11 @@
import { Link } from 'react-router-dom'
import React, { useState } from 'react'
import { Form, Input, Button, DatePicker, Select, Table } from 'antd'
import dayjs from 'dayjs'
import { ReadIcon, DeliverIcon, SentIcon, WaitingIcon, FailedIcon } from '@/components/Icons'
import { MessageTwoTone } from '@ant-design/icons'
import useCustomerRelationStore from '@/stores/CustomerRelationStore'
const { RangePicker } = DatePicker
const { Option } = Select
//
const statusIconMap = {
read: <ReadIcon title='read' />,
delivered: <DeliverIcon title='delivered' />,
sent: <SentIcon title='sent' />,
failed: <FailedIcon title='failed' />,
accepted: <WaitingIcon title='accepted' />,
default: <WaitingIcon title='waiting' />,
}
const Index = () => {
const { loading, tasksList, fetchSearchTasks } = useCustomerRelationStore()
@ -38,80 +26,6 @@ const Index = () => {
fetchSearchTasks(formattedValues)
}
// crt_template msg_status
const templateStatusCount = {}
tasksList.forEach((item) => {
const { crt_template, msg_status, msg_reply } = item
if (msg_status !== null && msg_status !== undefined) {
if (!templateStatusCount[crt_template]) {
templateStatusCount[crt_template] = {}
templateStatusCount[crt_template]['msgreply'] = 0
}
if (!templateStatusCount[crt_template][msg_status]) {
templateStatusCount[crt_template][msg_status] = 0
}
templateStatusCount[crt_template][msg_status]++
if (msg_reply) {
templateStatusCount[crt_template]['msgreply']++
}
}
})
//
const groupedResult = {}
for (const template in templateStatusCount) {
//msgreplymsgreply
const total = Object.values(templateStatusCount[template]).reduce((acc, val) => acc + val, 0) - templateStatusCount[template]['msgreply']
groupedResult[template] = {}
for (const status in templateStatusCount[template]) {
const count = templateStatusCount[template][status]
const percentage = ((count / total) * 100).toFixed(2)
groupedResult[template][`${status}_count`] = count
groupedResult[template][`${status}_percentage`] = `${percentage}%`
}
}
// groupedResult
const groupedData = Object.entries(groupedResult).map(([template, stats]) => {
return {
key: template,
crt_template: template,
...stats,
}
})
//
const groupedColumns = []
groupedColumns.push({
title: '模板名称',
dataIndex: 'crt_template',
key: 'crt_template',
})
const allStatuses = new Set(['msgreply'])
tasksList.forEach((item) => {
if (item.msg_status !== null && item.msg_status !== undefined) {
allStatuses.add(item.msg_status)
}
})
// Set
const sortedStatuses = Array.from(allStatuses).sort()
sortedStatuses.forEach((status) => {
groupedColumns.push({
title: `${status} 计数`,
dataIndex: `${status}_count`,
key: `${status}_count`,
})
groupedColumns.push({
title: `${status} 百分比`,
dataIndex: `${status}_percentage`,
key: `${status}_percentage`,
})
})
const DATE_RANGE_PRESETS = [
{
label: '本周',
@ -158,28 +72,15 @@ const Index = () => {
return '失败'
},
},
{ title: '发送时间', dataIndex: 'crt_send_datetime', key: 'crt_send_datetime', sorter: (a, b) => dayjs(a.crt_send_datetime).unix() - dayjs(b.crt_send_datetime).unix() },
{ title: '发送时间', dataIndex: 'crt_send_datetime', key: 'crt_send_datetime' },
{ title: '模板', dataIndex: 'crt_template', key: 'crt_template' },
{ title: 'WhatsApp', dataIndex: 'crt_whatsapp', key: 'crt_whatsapp' },
{
title: '会话',
dataIndex: 'crt_conversation_id',
key: 'crt_conversation_id',
render: (text, record) => {
if (text) {
const icon = statusIconMap[record.msg_status] || statusIconMap['default']
return (
<Link to={`/order/chat/${record.crt_coli_sn}`} title={record.errors_code ? record.errors_code + '' + record.errors_title : ''}>
查看会话 {icon} {record.msg_reply ? <MessageTwoTone title='已回复' /> : ''}
</Link>
)
}
},
},
// { title: 'ID', dataIndex: 'crt_message_id', key: 'crt_message_id' },
{ title: '会话ID', dataIndex: 'crt_conversation_id', key: 'crt_conversation_id' },
{ title: '消息ID', dataIndex: 'crt_message_id', key: 'crt_message_id' },
// { title: '', dataIndex: 'crt_mei_maillist', key: 'crt_mei_maillist' },
// { title: '', dataIndex: 'ct_datetime', key: 'ct_datetime' },
// { title: '', dataIndex: 'crt_mei_country', key: 'crt_mei_country' },
]
return (
@ -206,11 +107,11 @@ const Index = () => {
</Form.Item>
</Form>
{/* 搜索结果 */}
<span>搜索结果总数: {tasksList && tasksList.length}</span>
<Table dataSource={tasksList} columns={columns} pagination={false} rowKey='crt_sn' loading={loading} />
<h2>统计结果</h2>
<Table dataSource={groupedData} columns={groupedColumns} pagination={false} loading={loading} />
</>
)
}

@ -1,229 +1,373 @@
import { Conditional } from '@/components/Conditional'
import useAuthStore from '@/stores/AuthStore'
import { pick } from '@/utils/commons'
import { UnorderedListOutlined, LeftOutlined } from '@ant-design/icons'
import { Flex, Segmented, Tree, Typography, Layout, Splitter, Button, Tooltip, Badge } from 'antd'
import { useEffect, useMemo, useState, useRef } from 'react'
import EmailDetailInline from '../Conversations/Online/Components/EmailDetailInline'
import OrderProfile from '@/components/OrderProfile'
import Mailbox from './components/Mailbox'
import useConversationStore from '@/stores/ConversationStore';
import { MailboxDirIcon } from './components/MailboxDirIcon'
import { useVisibilityState } from '@/hooks/useVisibilityState'
const deptMap = new Map([
['1', 'CH'], // CH
['2', 'CH大客户组'],
['7', '市场推广'],
['8', '德语市场'],
['9', '日语市场'],
['10', '商旅市场'],
['11', '法语市场'],
['12', '西语市场'],
['13', '英文在线组'],
['14', '商务Biztravel'],
['15', 'CH产品'],
['16', 'APP移动项目组'],
['17', 'ChinaTravel组'],
['18', 'CT市场'],
['20', '俄语市场'],
['21', '意语市场'],
['22', '爱游网'],
['23', '三峡站'],
['24', '桂林站'],
['25', '上海站'],
['26', '北京站'],
['27', '西藏站'],
['28', 'AH'], // AH
['29', 'DMC地接组'],
['30', 'Trippest项目组'], //
['31', '花梨鹰'],
['32', 'Daytours板块'],
['33', 'GH'], // GH
['34', 'trippest网站'],
['35', 'newsletter营销'],
])
import { PERM_IMPORT_EMAIL } from '@/stores/AuthStore'
import useFormStore from '@/stores/FormStore'
import { useOrderStore } from '@/stores/OrderStore'
import { copy, isNotEmpty, isEmpty } from '@/utils/commons'
import { WhatsAppOutlined, ImportOutlined } from '@ant-design/icons'
import { App, Badge, Empty, Flex, Button, Radio, Space, Switch, Table, Tabs, Divider, Tag, Tooltip } from 'antd'
import dayjs from 'dayjs'
import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { useShallow } from 'zustand/react/shallow'
import { UNREAD_MARK } from '@/actions/ConversationActions'
import AdvanceSearchForm from './AdvanceSearchForm'
function Follow() {
function OrderGroupTable({ formValues }) {
const handleImportEmail = useCallback((order) => {
importEmailMessage({ orderId: order.COLI_SN, orderNumber: order.COLI_ID })
.then((r) => {
console.info(r)
notification.info({
message: 'Notification',
description: '订单:' + order.COLI_ID + ' 导入' + r.result.length + '条邮件消息',
placement: 'top',
})
})
.catch((ex) =>
notification.error({
message: 'Notification',
description: ex.message,
placement: 'top',
duration: 4,
}),
)
}, [])
const [collapsed, setCollapsed] = useState(true)
const mailboxTreeRef = useRef(null);
const [treeHeight, setTreeHeight] = useState(500);
const orderColumns = [
{
title: '订单号',
dataIndex: 'COLI_ID',
width: 222,
render: (text, record) => {
let tagIcon = ''
const [loginUser, isPermitted] = useAuthStore((state) => [state.loginUser, state.isPermitted])
const { accountList } = loginUser
const accountListDEIMapped = useMemo(() => accountList.reduce((a, c) => ({ ...a, [c.OPI_DEI_SN]: c }), {}), [accountList])
const accountDEI = useMemo(() => {
return accountList.map((ele) => ({ key: ele.OPI_DEI_SN, value: ele.OPI_DEI_SN, label: deptMap.get(`${ele.OPI_DEI_SN}`) }))
}, [accountList])
const [getOPIEmailDir] = useConversationStore(state => [state.getOPIEmailDir]);
const [currentMailboxDEI, setCurrentMailboxDEI, mailboxNestedDirsActive] = useConversationStore(state => [state.currentMailboxDEI, state.setCurrentMailboxDEI, state.mailboxNestedDirsActive]);
const [currentMailboxOPI, setCurrentMailboxOPI] = useConversationStore(state => [state.currentMailboxOPI, state.setCurrentMailboxOPI]);
const [mailboxActiveNode, setMailboxActiveNode] = useConversationStore(state => [state.mailboxActiveNode, state.setMailboxActiveNode]);
const [activeEmailId, setActiveEmailId] = useConversationStore(state => [state.mailboxActiveMAI, state.setMailboxActiveMAI]);
const [mailboxActiveCOLI, setMailboxActiveCOLI] = useConversationStore(state => [state.mailboxActiveCOLI, state.setMailboxActiveCOLI]);
const computedBreadcrumb = useMemo(() => {
const { title, iconIndex, parentTitle, parentIconIndex } = mailboxActiveNode
const x = [
{ title: parentTitle, iconIndex: parentIconIndex },
{ title, iconIndex },
].filter((ele) => ele.title)
return x
}, [mailboxActiveNode.VKey])
const [expandTree, setExpandTree] = useState([])
const handleSwitchAccount = (value) => {
setActiveEmailId(0);
// setExpandTree([]);
setCurrentMailboxDEI(value)
const opi = accountListDEIMapped[value].OPI_SN
getOPIEmailDir(opi)
setCurrentMailboxOPI(opi);
}
if (record.COLI_LineGrade === 240003) tagIcon = <Tag color='red'>重点</Tag>
else if (record.COLI_LineGrade === 240002) tagIcon = <Tag color='green'>次重点</Tag>
else if (record.COLI_LineGrade === 240001) tagIcon = <Tag color='blue'>一般</Tag>
const handleTreeSelectGetMails = (selectedKeys, { node }) => {
// console.info('selectedTreeKeys: ', node)
const treeNode = pick(node, ['key', 'parent', 'iconIndex', 'getMails', 'title', 'parentTitle', 'parentIconIndex' ]);
const { COLI_SN, VKey, VParent, ApplyDate, OrderSourceType, IsTrue } = node?._raw || {}
if (VKey && !(!IsTrue && !COLI_SN)) {
setMailboxActiveNode({...treeNode, ...node._raw, key: treeNode.key, OPI_SN: currentMailboxOPI});
setActiveEmailId(0);
setMailboxActiveCOLI(COLI_SN);
} else {
const _expandTree = expandTree.includes(node.key) ? expandTree.filter(ele => ele !== node.key) : [...expandTree, ...selectedKeys]
setExpandTree(_expandTree)
}
}
return (
<Space>
<Conditional
condition={isPermitted(PERM_IMPORT_EMAIL)}
whenTrue={<Button type='default' shape='round' icon={<ImportOutlined />} size='small' onClick={() => handleImportEmail(record)} />}
/>
<Link to={`/order/chat/${record.COLI_SN}`} state={record}>
{text}
</Link>
{tagIcon}
</Space>
)
},
},
{
title: '客人姓名',
dataIndex: 'coli_guest',
render: (text, record) => {
let regularText = ''
if (record.buytime > 0) regularText = '(R' + record.buytime + ')'
return (
<Space>
<Conditional
condition={isPermitted(record.coli_guest_WhatsApp)}
whenTrue={
<Tooltip title={record.coli_guest_WhatsApp}>
<WhatsAppOutlined className={['pl-1', record.last_received_time ? 'text-whatsapp' : 'text-neutral-500']} />
</Tooltip>
}
/>
{text + regularText}
<Badge
count={record.unread_msg >= UNREAD_MARK ? ' ' : record.unread_msg}
style={{
backgroundColor: '#52c41a',
}}
/>
</Space>
)
},
},
{
title: '订单状态',
dataIndex: 'COLI_State',
width: 140,
render: (text, record) => {
let extra = ''
if (record.coli_ordertype === 3 || record.coli_ordertype === 4 || record.coli_ordertype === 5) {
extra = '(' + (record.coli_ordertype - 2) + '催)'
}
const [selectedEmail, setSelectedEmail] = useState({});
const onClickEmailItem = (emailItem) => {
const mai_sn = emailItem.MAI_SN;
setActiveEmailId(mai_sn);
setMailboxActiveCOLI(emailItem.MAI_COLI_SN || 0)
const emailMsg = {
conversationid: '',
order_opi: currentMailboxOPI,
coli_sn: 'oid',
id: emailItem.MAI_SN,
MAI_SN: emailItem.MAI_SN,
msgOrigin: {
from: '',
to: '',
...(emailItem?.msgOrigin || {}),
id: emailItem.MAI_SN,
email: { mai_sn: emailItem.MAI_SN, subject: emailItem.MAI_Subject, id: emailItem.MAI_SN },
subject: emailItem.MAI_Subject,
return (
<Space>
{extra}
{text}
</Space>
)
},
}
// console.log('emailItem', emailItem);
setSelectedEmail(emailMsg)
};
},
{
title: '报价 Title',
dataIndex: 'lettertitle',
ellipsis: true,
hidden: false,
},
{
title: '出发日期',
dataIndex: 'COLI_OrderStartDate',
width: 120,
hidden: false,
sortDirections: ['ascend', 'descend'],
sorter: (a, b) => {
const datejsA = isEmpty(a.COLI_OrderStartDate) ? 0 : new dayjs(a.COLI_OrderStartDate).valueOf()
const datejsB = isEmpty(b.COLI_OrderStartDate) ? 0 : new dayjs(b.COLI_OrderStartDate).valueOf()
return datejsA - datejsB
},
},
{
title: '客人最后一次回复时间',
dataIndex: 'last_received_time',
width: 180,
render: (text, record) => {
if (record.last_received_time) {
return new dayjs(record.last_received_time).format('YYYY-MM-DD HH:mm:ss')
}
},
},
{
title: '附加信息',
ellipsis: true,
dataIndex: 'COLI_Introduction',
},
]
const { notification } = App.useApp()
const [loading, setLoading] = useState(false)
const orderList = useOrderStore((state) => state.orderList)
const fetchOrderList = useOrderStore((state) => state.fetchOrderList)
const importEmailMessage = useOrderStore((state) => state.importEmailMessage)
const [loginUser, isPermitted] = useAuthStore((state) => [state.loginUser, state.isPermitted])
// 123456coli_ordertype=7coli_ordertype=8
useEffect(() => {
const first = currentMailboxDEI || accountDEI[0].value
const opi = accountListDEIMapped[first].OPI_SN
setExpandTree([...[`${opi}-today`, `${opi}-todo`, `search-orders` ]])
let canSearch = true
return () => {}
}, [currentMailboxDEI ])
if (formValues.type === 'advance') {
const copyObject = copy(formValues)
delete copyObject.type
const allEmpty = Object.values(copyObject).every((val) => {
return val === null || val === '' || val === undefined
})
if (allEmpty) {
canSearch = false
notification.warning({
message: '温馨提示',
description: '请输入至少一个条件',
placement: 'top',
duration: 60,
})
}
}
useEffect(() => {
if (mailboxActiveNode?.expand === true) {
setExpandTree([mailboxActiveNode.key])
if (canSearch) {
setLoading(true)
fetchOrderList(formValues, loginUser)
.finally(() => setLoading(false))
.catch((reason) => {
notification.error({
message: '查询出错',
description: reason.message,
placement: 'top',
duration: 60,
})
})
}
}, [formValues])
return () => {}
}, [mailboxActiveNode])
const paginationProps = {
showQuickJumper: true,
showLessItems: true,
showSizeChanger: true,
showTotal: (total) => {
return `总数:${total}`
},
}
useEffect(() => {
const targetRect = mailboxTreeRef.current?.getBoundingClientRect()
setTreeHeight(Math.floor(targetRect.height))
function groupByParam(array, param) {
return array.reduce((result, item) => {
;(result[item[param]] = result[item[param]] || []).push(item)
return result
}, {})
}
return () => {}
}, [])
const deptMap = new Map([
['1', 'CH直销组'],
['2', 'CH大客户组'],
['7', '市场推广'],
['8', '德语市场'],
['9', '日语市场'],
['10', '商旅市场'],
['11', '法语市场'],
['12', '西语市场'],
['13', '英文在线组'],
['14', '商务Biztravel'],
['15', 'CH产品'],
['16', 'APP移动项目组'],
['17', 'ChinaTravel组'],
['18', 'CT市场'],
['20', '俄语市场'],
['21', '意语市场'],
['22', '爱游网'],
['23', '三峡站'],
['24', '桂林站'],
['25', '上海站'],
['26', '北京站'],
['27', '西藏站'],
['28', 'AH亚洲项目组'],
['29', 'DMC地接组'],
['30', 'Trippest项目组'],
['31', '花梨鹰'],
['32', 'Daytours板块'],
['33', 'GH项目组'],
['34', 'trippest网站'],
['35', 'newsletter营销'],
])
const isVisible = useVisibilityState();
useEffect(() => {
// console.log('effect isVisible', isVisible);
if (isVisible && currentMailboxOPI) {
getOPIEmailDir(currentMailboxOPI, null, true)
const groupOrderData = groupByParam(orderList, 'OPI_DEI_SN')
const deptKeys = Object.keys(groupOrderData)
const deptItems = []
deptKeys.forEach((deptNo, index) => {
const deptOrderList = groupOrderData[deptNo]
// 123456coli_ordertype=7coli_ordertype=8
const newOrderList = deptOrderList.filter((o) => {
return o.coli_ordertype === 1
})
const newMsgList = deptOrderList.filter((o) => {
return o.coli_ordertype === 2 || o.coli_ordertype === 6
})
const followUpList = deptOrderList.filter((o) => {
return o.coli_ordertype === 3 || o.coli_ordertype === 4 || o.coli_ordertype === 5
})
const entryList = deptOrderList.filter((o) => {
return o.coli_ordertype === 7
})
const paymentList = deptOrderList.filter((o) => {
return o.coli_ordertype === 8
})
if (formValues.type === 'today') {
deptItems.push({
key: index,
label: deptMap.get(deptNo),
children: (
<>
<Divider orientation='left'>新订单</Divider>
<Conditional
condition={newOrderList.length > 0}
whenTrue={<Table key={'newOrderTable' + deptNo} loading={loading} dataSource={newOrderList} columns={orderColumns} pagination={newOrderList.length <= 10 ? false : paginationProps} />}
whenFalse={<Empty />}
/>
<Divider orientation='left'>新消息/老邮件</Divider>
<Conditional
condition={newMsgList.length > 0}
whenTrue={<Table key={'newMsgTable' + deptNo} loading={loading} dataSource={newMsgList} columns={orderColumns} pagination={newMsgList.length <= 10 ? false : paginationProps} />}
whenFalse={<Empty />}
/>
<Divider orientation='left'>催信</Divider>
<Conditional
condition={followUpList.length > 0}
whenTrue={<Table key={'followUpTable' + deptNo} loading={loading} dataSource={followUpList} columns={orderColumns} pagination={followUpList.length <= 10 ? false : paginationProps} />}
whenFalse={<Empty />}
/>
<Divider orientation='left'>余款收付</Divider>
<Conditional
condition={paymentList.length > 0}
whenTrue={<Table key={'paymentTable' + deptNo} loading={loading} dataSource={paymentList} columns={orderColumns} pagination={paymentList.length <= 10 ? false : paginationProps} />}
whenFalse={<Empty />}
/>
<Divider orientation='left'>入境提醒</Divider>
<Conditional
condition={entryList.length > 0}
whenTrue={<Table key={'entryTable' + deptNo} loading={loading} dataSource={entryList} columns={orderColumns} pagination={entryList.length <= 10 ? false : paginationProps} />}
whenFalse={<Empty />}
/>
</>
),
})
} else {
deptItems.push({
key: index,
label: deptMap.get(deptNo),
children: (
<>
<Table key={'advanceOrderTable' + deptNo} loading={loading} dataSource={deptOrderList} columns={orderColumns} pagination={deptOrderList.length <= 10 ? false : paginationProps} />
</>
),
})
}
})
return () => {}
}, [isVisible]);
return <Conditional condition={orderList.length > 0} whenTrue={<Tabs defaultActiveKey={0} items={deptItems} />} whenFalse={<Empty />} />
}
function Follow() {
const [formValues, setFormValues] = useFormStore(useShallow((state) => [state.orderFollowForm, state.setOrderFollowForm]))
const [advanceChecked, toggleAdvance] = useFormStore(useShallow((state) => [state.orderFollowAdvanceChecked, state.setOrderFollowAdvanceChecked]))
const batchImportEmailMessage = useOrderStore((state) => state.batchImportEmailMessage)
const [isPermitted] = useAuthStore((state) => [state.isPermitted])
const handleImportEmail = useCallback(() => {
batchImportEmailMessage()
}, [])
const handleSubmit = useCallback((values) => {
setFormValues({ ...values, type: 'advance' })
}, [])
return (
<>
<Layout>
<Layout.Sider width='300' theme='light' style={{ height: 'calc(100vh - 166px)' }} className=' relative'>
<Flex justify='start' align='start' vertical className='h-full'>
<Segmented className='w-full' block shape='round' options={accountDEI} value={currentMailboxDEI} onChange={handleSwitchAccount} />
<div ref={mailboxTreeRef} className='overflow-y-auto flex-auto w-full [&_.ant-tree-switcher]:me-0 [&_.ant-tree-node-content-wrapper]:px-0 [&_.ant-tree-node-content-wrapper]:text-ellipsis [&_.ant-tree-node-content-wrapper]:overflow-hidden [&_.ant-tree-node-content-wrapper]:whitespace-nowrap'>
<Tree
className='[&_.ant-typography-ellipsis]:max-w-44 [&_.ant-typography-ellipsis]:min-w-36'
key='sticky-today'
blockNode
showIcon
showLine
height={treeHeight}
autoExpandParent={true}
expandAction={'doubleClick'}
onSelect={handleTreeSelectGetMails}
selectedKeys={[mailboxActiveNode.key]}
onExpand={(expandedKeys) => setExpandTree(expandedKeys)}
expandedKeys={expandTree}
defaultExpandedKeys={expandTree}
treeData={mailboxNestedDirsActive}
icon={(node) => <MailboxDirIcon type={node?.iconIndex} />}
titleRender={(node) => (
<Typography.Text ellipsis={{ tooltip: node.title }} className={`${node?._raw?.IsSuccess === 1 ? 'text-primary' : ''}`}>
{node.title}
<Badge size={'small'} count={node.count} offset={[3, 0]} style={{backgroundColor: "#1ba784", color1: '#1ba784'}} overflowCount={999} />
</Typography.Text>
)}
/>
</div>
</Flex>
</Layout.Sider>
<Layout.Content style={{ maxHeight: 'calc(100vh - 166px)', height: 'calc(100vh - 166px)', minWidth: '360px' }}>
<Splitter>
<Splitter.Panel defaultSize='40%' min={380} max='70%'>
<Mailbox breadcrumb={computedBreadcrumb} mailboxDir={mailboxActiveNode} onMailItemClick={(item) => onClickEmailItem(item)} currentActiveMailItem={activeEmailId} />
</Splitter.Panel>
<Splitter.Panel>
<EmailDetailInline mailID={activeEmailId || 0} emailMsg={selectedEmail} variant={'outline'} size={'small'} onUpdated={(prop) => {}} autoMark={true} />
</Splitter.Panel>
</Splitter>
</Layout.Content>
<Tooltip title={(collapsed ? '展开' : '收起') + '订单信息'} placement='left'>
<Button
icon={collapsed ? <LeftOutlined /> : <UnorderedListOutlined />}
onClick={() => setCollapsed(!collapsed)}
className={`absolute z-10 rounded-none ${collapsed ? 'right-1 top-20 rounded-l-xl' : 'right-8 top-20 rounded-l'}`}
size={collapsed ? 'small' : 'middle'}
<Space direction='vertical' size='large' style={{ width: '100%' }}>
<Flex gap='large' justify='start' align='center' horizontal='true'>
<Radio.Group
options={[
{ label: '今日任务', value: 'today' },
{ label: '重点订单', value: 'zhongdian' },
{ label: '次重点客户', value: 'qianli' },
{ label: '成行', value: 'chengxing' },
{ label: '走团中', value: 'zoutuan' },
{ label: '走团后一月', value: 'zoutuanhou' },
]}
value={formValues.type}
onChange={({ target: { value } }) => {
setFormValues({
...formValues,
type: value,
})
}}
optionType='button'
buttonStyle='solid'
disabled={advanceChecked}
/>
<Switch
checkedChildren='高级查询'
unCheckedChildren='高级查询'
checked={advanceChecked}
onChange={() => {
toggleAdvance(!advanceChecked)
}}
/>
<Conditional
condition={isPermitted(PERM_IMPORT_EMAIL)}
whenTrue={<Button type='default' shape='round' icon={<ImportOutlined />} size='small' onClick={handleImportEmail}/>}
/>
</Tooltip>
<Layout.Sider
width='280'
theme='light'
className='overflow-y-auto'
style={{
height: 'calc(100vh - 166px)',
}}
collapsible
collapsed={collapsed}
onCollapse={(value) => setCollapsed(value)}
collapsedWidth={0}
trigger={null}
reverseArrow={true}>
<OrderProfile coliSN={mailboxActiveCOLI} />
</Layout.Sider>
</Layout>
</Flex>
<Conditional condition={advanceChecked} whenTrue={<AdvanceSearchForm onSubmit={handleSubmit} initialValues={formValues} />} />
<OrderGroupTable formValues={formValues} />
</Space>
</>
)
}

@ -1,217 +0,0 @@
import { useEffect, useState } from 'react'
import { ReloadOutlined, ReadOutlined, RightOutlined, LeftOutlined, SearchOutlined, MailOutlined, DeleteOutlined, CloseOutlined, CloseCircleTwoTone, CloseCircleOutlined } from '@ant-design/icons'
import { Flex, Button, Tooltip, List, Form, Row, Col, Input, Checkbox, DatePicker, Switch, Breadcrumb, Skeleton, Popconfirm } from 'antd'
import { useEmailList } from '@/hooks/useEmail'
import { isEmpty } from '@/utils/commons'
import { MailboxDirIcon } from './MailboxDirIcon'
import { AttachmentIcon, MailCheckIcon, MailOpenIcon } from '@/components/Icons'
import NewEmailButton from './NewEmailButton'
import MailOrderSearchModal from './MailOrderSearchModal'
import MailListSearchModal from './MailListSearchModal'
const PAGE_SIZE = 50 //
const MailBox = ({ mailboxDir, onMailItemClick, ...props }) => {
const [selectedItems, setSelectedItems] = useState([])
const { mailList, loading, error, tempBreadcrumb, refresh, markAsUnread, markAsProcessed, markAsDeleted, } = useEmailList(mailboxDir)
const [pagination, setPagination] = useState({
current: 1,
pageSize: PAGE_SIZE,
total: 0,
pagedList: [],
})
useEffect(() => {
if (mailList) {
const total = mailList.length
const pageCount = Math.ceil(total / PAGE_SIZE)
setPagination((prev) => ({
...prev,
total,
pageCount,
current: 1, //
pagedList: getPagedData(mailList, 1),
}))
}
}, [mailList])
const getPagedData = (data, currentPage) => {
const startIndex = (currentPage - 1) * PAGE_SIZE
const endIndex = Math.min(startIndex + PAGE_SIZE, data.length)
return data.slice(startIndex, endIndex)
}
const prePage = () => {
if (pagination.current > 1) {
const newCurrent = pagination.current - 1
setPagination((prev) => ({
...prev,
current: newCurrent,
pagedList: getPagedData(mailList, newCurrent),
}))
}
}
const nextPage = () => {
if (pagination.current < Math.ceil(pagination.total / PAGE_SIZE)) {
const newCurrent = pagination.current + 1
setPagination((prev) => ({
...prev,
current: newCurrent,
pagedList: getPagedData(mailList, newCurrent),
}))
}
}
const mailItemRender = (item) => {
const isOrderNode = mailboxDir.COLI_SN > 0
const orderNumber = isEmpty(item.MAI_COLI_ID) || isOrderNode ? '' : item.MAI_COLI_ID + ' - '
const folderName = (item.showFolder) ? `[${item.FDir}] ` : ''
const orderMailType = item.MAT_Name ? <span className='text-neutral-600 text-xs'>{item.MAT_Name}</span> : ''
const countryName = isEmpty(item.CountryCN) ? '' : '[' + item.CountryCN + '] '
const mailStateClass = item.MOI_ReadState === 0 ? 'font-bold' : ''
const hasAtta = item.MAI_Attachment !== 0 ? <AttachmentIcon className='text-blue-500' /> : null
return (
<li
className={`flex border border-solid border-t-0 border-x-0 border-gray-200 hover:bg-neutral-50 active:bg-gray-200 p-2 ${props.currentActiveMailItem === item.MAI_SN ? 'bg-neutral-100' : ''}`}>
<div className=''>
<Checkbox
checked={selectedItems.some((i) => i.MAI_SN === item.MAI_SN)}
onClick={(e) => {
const isChecked = e.target.checked
const updatedSelection = isChecked ? [...selectedItems, item] : selectedItems.filter((item) => item.MAI_SN !== item.MAI_SN)
setSelectedItems(updatedSelection)
}}></Checkbox>
</div>
<div
className='flex-1 pl-2'
onClick={() => {
onMailItemClick(item)
}}>
<Flex gap='small' vertical={true} justify='space-between' className='cursor-pointer'>
<div>
{folderName}{orderNumber}
<span className={mailStateClass}>{item.MAI_Subject || '[无主题]'}</span>
{hasAtta}
</div>
<Flex gap='small' align='center' justify='flex-end' wrap className='text-neutral-500 text-wrap break-words break-all '>
<span className='mr-auto'>{countryName + item.SenderReceiver}</span>
{orderMailType}
<span className=''>{item.SRDate}</span>
</Flex>
</Flex>
</div>
</li>
)
}
return (
<div className='h-full flex flex-col gap-1 bg-white'>
<div className='bg-white h-auto px-1 flex gap-1 items-center'>
<Flex wrap gap='middle' justify={'center'} className='min-w-30 px-1'>
<Tooltip title='全选'>
<Checkbox
indeterminate={selectedItems.length > 0 && selectedItems.length < pagination.pagedList.length}
checked={pagination.pagedList.length === 0 ? false : pagination.pagedList.every((item) => selectedItems.some((selected) => selected.MAI_SN === item.MAI_SN))}
onChange={(e) => {
const isChecked = e.target.checked
if (isChecked) {
setSelectedItems((prev) => [...prev, ...pagination.pagedList])
} else {
setSelectedItems([])
}
}}></Checkbox>
</Tooltip>
<Tooltip title='刷新'>
<Button shape='circle' type='text' size='small' icon={<ReloadOutlined />} onClick={refresh} />
</Tooltip>
</Flex>
<Flex wrap gap={8} >
<NewEmailButton />
<Button
size='small'
icon={<MailOutlined />}
onClick={() => {
markAsUnread(selectedItems.map((item) => item.MAI_SN)).then(() => setSelectedItems([]))
}}>
未读
</Button>
<Button
size='small'
icon={<MailCheckIcon />}
onClick={() => {
markAsProcessed(selectedItems.map((item) => item.MAI_SN)).then(() => setSelectedItems([]))
}}>
已处理
</Button>
<Button
size='small' // danger
icon={<DeleteOutlined />}
onClick={() => {
markAsDeleted(selectedItems.map((item) => item.MAI_SN)).then(() => setSelectedItems([]))
}}>
删除
</Button>
<MailOrderSearchModal />
<MailListSearchModal />
</Flex>
</div>
<Flex align='center' justify='space-between' wrap className='px-1 border-0 border-b border-solid border-neutral-200'>
<Breadcrumb
items={(tempBreadcrumb || props.breadcrumb).map((bc) => {
return {
title: (
<>
<MailboxDirIcon type={bc?.iconIndex} />
<span>{bc.title}</span>
</>
),
}
})}
/>
{tempBreadcrumb && (<Button type="text" icon={<CloseCircleOutlined />} onClick={() => refresh()} />)}
<Flex align='center' justify='space-between' className='ml-auto'>
<span>已选: {selectedItems.length} </span>
<span>
{(pagination.current - 1) * PAGE_SIZE + 1}-{Math.min(pagination.current * PAGE_SIZE, pagination.total)} of {pagination.total}
</span>
<Button
icon={<LeftOutlined />}
type='text'
onClick={() => {
prePage()
}}
iconPosition={'end'}></Button>
<Button
icon={<RightOutlined />}
type='text'
onClick={() => {
nextPage()
}}
iconPosition={'end'}></Button>
</Flex>
</Flex>
<div className='bg-white overflow-auto px-2' style={{ height1: 'calc(100vh - 198px)' }}>
<Skeleton active loading={loading}>
<List
loading={loading}
className='flex flex-col h-full [&_.ant-list-items]:overflow-auto'
header={null}
itemLayout='vertical'
pagination={false}
dataSource={pagination.pagedList}
renderItem={mailItemRender}
/>
</Skeleton>
</div>
</div>
)
}
export default MailBox

@ -1,75 +0,0 @@
import { useState } from 'react'
import { SearchOutlined } from '@ant-design/icons'
import { Button, Modal, Form, Input, Radio } from 'antd'
import { searchEmailListAction } from '@/actions/EmailActions'
import useConversationStore from '@/stores/ConversationStore'
const MailListSearchModal = ({ ...props }) => {
const [currentMailboxOPI] = useConversationStore((state) => [state.currentMailboxOPI])
const [openForm, setOpenForm] = useState(false)
const [formSearch] = Form.useForm()
const [loading, setLoading] = useState(false)
const onSubmitSearchMailList = async (values) => {
setLoading(true)
await searchEmailListAction({...values, opi_sn: currentMailboxOPI});
setLoading(false)
setOpenForm(false)
}
return (
<>
<Button key={'bound'} onClick={() => setOpenForm(true)} size='small' icon={<SearchOutlined className='' />}>
查找邮件
</Button>
<Modal
width={window.innerWidth < 700 ? '95%' : 960}
open={openForm}
cancelText='关闭'
okText='查找'
confirmLoading={loading}
okButtonProps={{ autoFocus: true, htmlType: 'submit', type: 'default' }}
onCancel={() => setOpenForm(false)}
footer={null}
destroyOnHidden
modalRender={(dom) => (
<Form
layout='vertical'
form={formSearch}
name='searchmaillist_form_in_modal'
initialValues={{ mailboxtype: '' }}
clearOnDestroy
onFinish={(values) => onSubmitSearchMailList(values)}
className='[&_.ant-form-item]:m-2'>
{dom}
</Form>
)}>
<Form.Item name='mailboxtype' label='邮箱文件夹'>
<Radio.Group
options={[
{ key: 'All', value: '', label: 'All' },
{ key: '1', value: '1', label: '收件箱' },
{ key: '2', value: '2', label: '未读邮件' },
{ key: '3', value: '3', label: '已发邮件' },
{ key: '7', value: '7', label: '已处理邮件' },
]}
optionType='button'
/>
</Form.Item>
<Form.Item name='sender' label='发件人'>
<Input />
</Form.Item>
<Form.Item name='receiver' label='收件人'>
<Input />
</Form.Item>
<Form.Item name='subject' label='主题'>
<Input />
</Form.Item>
<Button type='primary' htmlType='submit' loading={loading}>
查找
</Button>
</Modal>
</>
)
}
export default MailListSearchModal

@ -1,147 +0,0 @@
import { useState } from 'react'
import { SearchOutlined } from '@ant-design/icons'
import { Button, Modal, Form, Input, Checkbox, Radio, DatePicker, Divider, Typography, Flex } from 'antd'
import dayjs from 'dayjs'
import { getEmailDirAction, queryHTOrderListAction, } from '@/actions/EmailActions'
import { isEmpty, objectMapper, pick } from '@/utils/commons'
import useConversationStore from '@/stores/ConversationStore'
const MailOrderSearchModal = ({ ...props }) => {
const [currentMailboxOPI] = useConversationStore((state) => [state.currentMailboxOPI])
const [updateCurrentMailboxNestedDirs, setMailboxActiveNode] = useConversationStore((state) => [state.updateCurrentMailboxNestedDirs, state.setMailboxActiveNode])
const [open, setOpen] = useState(false)
const [form] = Form.useForm()
const [loading, setLoading] = useState(false)
const onSubmitSearchMailOrder = async (values) => {
// console.log('Received values of form: ', values)
setLoading(true)
const valuesToSub = objectMapper(values, {
year: { key: 'year', transform: (val) => (val ? dayjs(val).year() : '') },
important: { key: 'important', transform: (val) => val || '-1' },
by_success: { key: 'by_success', transform: (val) => (val ? '1' : '0') },
if_want_book: { key: 'if_want_book', transform: (val) => (val ? '1' : '0') },
if_thinking: { key: 'if_thinking', transform: (val) => (val ? '1' : '0') },
by_start_date: { key: 'by_start_date', transform: (val) => (val ? '1' : '0') },
coli_id: { key: 'coli_id', transform: (val) => (val ? val : '') },
is_biz: { key: 'sourcetype', transform: (val) => (val ? '227002' : '227001') },
})
let result
if (isEmpty(valuesToSub.coli_id)) {
const { coli_id, sourcetype, ...mailboxParams } = valuesToSub
result = await getEmailDirAction({ ...mailboxParams, opi_sn: currentMailboxOPI }, false)
updateCurrentMailboxNestedDirs(result[`${currentMailboxOPI}`])
setMailboxActiveNode({expand:true, key: -1, title: '1月', iconIndex: 1, _raw: { VKey: -1, COLI_SN: 0, IsTrue: 0 }})
} else {
const htOrderParams = pick(valuesToSub, ['coli_id', 'sourcetype'])
result = await queryHTOrderListAction({ ...htOrderParams, opi_sn: currentMailboxOPI })
const addToTree = {
expand:true,
key: 'search-orders',
title: '查找订单',
iconIndex: 'search',
_raw: { COLI_SN: 0, IsTrue: 0 },
children: result.map((o) => ({
key: `search-${o.COLI_SN}`,
title: `${o.COLI_ID}`,
iconIndex: 13,
parent: 'search-orders',
parentTitle: '查找订单',
parentIconIndex: 'search',
_raw: { ...o, VKey: o.COLI_SN, VName: o.COLI_ID, VParent: 'search-orders', IsTrue: 0, ApplyDate: '', OrderSourceType: htOrderParams.sourcetype, parent: 'search-orders' },
})),
}
updateCurrentMailboxNestedDirs([addToTree])
setMailboxActiveNode(addToTree)
}
setLoading(false)
setOpen(false)
}
return (
<>
<Button key={'bound'} onClick={() => setOpen(true)} size='small' icon={<SearchOutlined className='' />}>
查找订单
</Button>
<Modal
width={window.innerWidth < 700 ? '95%' : 960}
// title='' //mask={false}
open={open}
cancelText='关闭'
okText='查找'
confirmLoading={loading}
okButtonProps={{ autoFocus: true, htmlType: 'submit', type: 'default' }}
onCancel={() => setOpen(false)}
footer={null}
destroyOnHidden
modalRender={(dom) => (
<Form
layout='inline'
// size='small'
form={form}
name='searchmailorder_form_in_modal'
initialValues={{ year: dayjs(), important: '-1' }}
clearOnDestroy
onFinish={(values) => onSubmitSearchMailOrder(values)}
className='[&_.ant-form-item]:m-2'>
{dom}
</Form>
)}>
<Flex wrap gap={8}>
<div>
<Typography.Text strong>按订单的时间范围</Typography.Text>
<Form.Item name='year' label='年份'>
<DatePicker picker='year' />
</Form.Item>
<Form.Item name='important' label='重要程度'>
<Radio.Group
options={[
{ key: '-1', value: '-1', label: 'All' },
{ key: '240001', value: '240001', label: '普通' },
{ key: '240002', value: '240002', label: '较重要' },
{ key: '240003', value: '240003', label: '很重要' },
]}
optionType='button'
/>
</Form.Item>
<div className='flex'>
<Form.Item name='by_success' className='' valuePropName='checked'>
<Checkbox>成行订单</Checkbox>
</Form.Item>
<Form.Item name='if_want_book' className='' valuePropName='checked'>
<Checkbox>要预定</Checkbox>
</Form.Item>
<Form.Item name='if_thinking' className='' valuePropName='checked'>
<Checkbox>犹豫中</Checkbox>
</Form.Item>
</div>
<Form.Item name='by_start_date' className='' valuePropName='checked'>
<Checkbox>按出发日期</Checkbox>
</Form.Item>
<div className='text-end'>
<Button type='primary' htmlType='submit' loading={loading}>
查找
</Button>
</div>
<Divider className='my-2' />
<Typography.Text strong>订单号精确查找</Typography.Text>
<Form.Item name='coli_id' label='订单号' className=''>
<Input />
</Form.Item>
<Form.Item name='is_biz' className='' valuePropName='checked'>
<Checkbox>商务订单</Checkbox>
</Form.Item>
<div className='text-end'>
<Button type='primary' htmlType='submit' loading={loading}>
查找
</Button>
</div>
</div>
</Flex>
</Modal>
</>
)
}
export default MailOrderSearchModal

@ -1,31 +0,0 @@
import { StarTwoTone, CalendarTwoTone, FolderOutlined, DeleteOutlined, ClockCircleOutlined, FormOutlined, DatabaseOutlined, BellTwoTone, SearchOutlined } from '@ant-design/icons'
import { InboxIcon, MailUnreadIcon, SendPlaneFillIcon } from '@/components/Icons'
const EmailDirTypeIcons = {
'search': { component: SearchOutlined, color: '', className: 'text-blue-600' },
'star': { component: StarTwoTone, color: '', className: '' },
'calendar': { component: CalendarTwoTone, color: '', className: '' },
'reminder': { component: BellTwoTone, color: '', className: '' },
0: { component: FolderOutlined, color: '#ffe78f', className: 'text-blue-500' },
1: { component: FolderOutlined, color: '#ffe78f', className: 'text-blue-500' },
3: { component: InboxIcon, color: '', className: 'text-indigo-500' },
17: { component: InboxIcon, color: '', className: 'text-indigo-500' },
11: { component: MailUnreadIcon, color: '', className: 'text-indigo-500' },
4: { component: SendPlaneFillIcon, color: '', className: 'text-primary' },
2: { component: ClockCircleOutlined, color: '', className: 'text-yellow-500' },
5: { component: FormOutlined, color: '', className: 'text-blue-500' },
7: { component: DeleteOutlined, color: '', className: 'text-red-500' },
// '3': { component: MailCheckIcon, color: '', className: 'text-yellow-600' },
12: { component: DatabaseOutlined, color: '', className: 'text-blue-600' },
13: { component: () => null, color: '', className: '' },
14: { component: () => '❗', color: '', className: '' }, // 240002 /
15: { component: () => '❣️', color: '', className: '' }, // 240003 /
}
export const MailboxDirIcon = ({ type }) => {
const Icon = EmailDirTypeIcons[type || '13']?.component || EmailDirTypeIcons['13'].component
const className = EmailDirTypeIcons[type || '13']?.className || EmailDirTypeIcons['13'].className
return <Icon className={className} />
}
export default MailboxDirIcon

@ -1,43 +0,0 @@
import { useMemo } from 'react'
import { App, Dropdown } from 'antd'
import useConversationStore from '@/stores/ConversationStore'
import { emailTemplates, openPopup } from '@/hooks/useEmail'
import { isEmpty } from '@/utils/commons'
const NewEmailButton = ({ ...props }) => {
const { notification } = App.useApp()
const [mailboxActiveNode] = useConversationStore((state) => [state.mailboxActiveNode])
const [mailboxActiveCOLI] = useConversationStore((state) => [state.mailboxActiveCOLI])
const COLI_SN = useMemo(() => mailboxActiveCOLI || mailboxActiveNode?.COLI_SN || 0, [mailboxActiveNode.COLI_SN, mailboxActiveCOLI])
const handleTemplateDropdown = ({ key, domEvent }) => {
if (isEmpty(COLI_SN)) {
notification.warning({ message: '无法绑定订单', description: '请先选择到订单目录或订单邮件', placement: 'top' })
return false
}
openPopup(`/email/new/0/${COLI_SN}/${key}`, `new-0-${COLI_SN}-${key}`)
}
const handleNewEmail = () => {
openPopup(`/email/new/0/${COLI_SN}`, `new-0-${COLI_SN}`)
}
return (
<>
<Dropdown.Button
size='small'
className={`w-auto ${props.className}`}
placement='bottom'
arrow
type={'primary'}
menu={{
items: emailTemplates,
onClick: handleTemplateDropdown,
}}
onClick={handleNewEmail}>
新邮件
</Dropdown.Button>
</>
)
}
export default NewEmailButton

@ -99,20 +99,6 @@ const manifestForPWAPlugIn = {
},
},
},
{
urlPattern: /^https:\/\/.*\.mycht\.cn\/attachment\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'mail-attachment',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 7, // <== 7 days
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
},
manifest: {
@ -183,9 +169,12 @@ export default defineConfig({
output: {
entryFileNames: '[name]/build.[hash].js',
manualChunks(id) {
if (id.includes('node_modules/')) {
// return 'vendor';
return id.toString().split('node_modules/')[1].split('/')[0].toString();
if (id.toLowerCase().includes('lexical')) {
return 'lexical';
}
if (id.includes('node_modules')) {
return 'vendor';
// return id.toString().split('node_modules/')[1].split('/')[0].toString();
}
},
// chunkFileNames: (chunkInfo) => {

@ -71,8 +71,7 @@ const uniqueMsgId = msg => (msg.id && msg.direction ? `${directionPrefix[msg.dir
*/
const webhookBodyBuilder = (messageData, messageType) => {
const defaultContent = { id: '', from: '', to: '', externalId: '', type: '', direction: '', status: '' };
const outboundStatus = statusMapped?.[messageData.status] || messageData.status || '';
const status = messageData.direction === 'inbound' ? '' : outboundStatus;
const status = messageData.direction === 'inbound' ? '' : statusMapped?.[messageData.status] || messageData.status || '';
const errors = messageData.status === 'error' ? { errorMessage: '未知错误', errorCode: '' } : {};
const message = {
id: `evt_${generateId().replace(/-/g, '')}`,

Loading…
Cancel
Save