Compare commits

..

1 Commits

Author SHA1 Message Date
Lei OT 1ff690f606 test: iframe 渲染邮件正文 1 year ago

30
.gitignore vendored

@ -10,11 +10,11 @@ lerna-debug.log*
node_modules node_modules
dist dist
dist-ssr dist-ssr
*.local *.local
distTest distTest
dev-dist dev-dist
tmp tmp
schema* schema*
.gitkeep .gitkeep
# Editor directories and files # Editor directories and files
@ -29,14 +29,12 @@ schema*
*.sw? *.sw?
/package-lock.json /package-lock.json
pnpm-lock.yaml
**/LexicalEditor0
**/LexicalEditor0
*.zip
*.zip
.env.*
.env.*
vonage-client*
vonage-client* **/test
**/test
*.bak

@ -1,18 +1,3 @@
## 查找使用邮件功能人数
select group_concat(opi_sn_value separator ''',''') as 'opi_list' from (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(request_uri, 'opi_sn=', -1), '&', 1) AS opi_sn_value,
COUNT(*) AS count
FROM log_message
WHERE request_uri LIKE '%/v3/dir_count%'
GROUP BY opi_sn_value
) a
select DISTINCT OPI_RealName from V_Operator_Info voi
where OPI2_OPI_SN in ('513','5130','466','621','404','622','383','609','510','512','582','586','633','0','415','639','641','640','577','654','601','602','599','535','568','496','648','691','690','525','540','626','162','634','487','585','594','628','611','624','674','637','522','676','606','631','451','551','489','583','495','503','719','698','644','605','587','588','589','509','552','526','227','501','515','581','216','575','484','687','679','370','580','490','617','618','619','261','600','603','604','114','579','481','387','629','354','492','632','414','660','574','79','486','663','391','584','482','252','264','265','376','453','649','651','650','210','212','343','565','143','591','590','328','476','593','514','576','595','536','543','564','178','528','541','625','119','571','598','573','332','413','155','330','627','550','742','612','444','360','519','421','146','553','441')
## 查找出掉线的 WhatsApp ## 查找出掉线的 WhatsApp
select * select *
from whatsapp_individual.connections from whatsapp_individual.connections

@ -1,7 +1,7 @@
{ {
"name": "global-sales", "name": "global-sales",
"private": true, "private": true,
"version": "1.6.13", "version": "1.4.7",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@ -10,48 +10,31 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@ant-design/icons": "^6.0.0",
"@dckj/react-better-modal": "^0.1.2", "@dckj/react-better-modal": "^0.1.2",
"@haina/utils-commons": "https://research.hainatravel.com/npm/utils-commons-0.1.2.tgz", "@lexical/react": "^0.20.0",
"@haina/utils-pagespy": "https://research.hainatravel.com/npm/utils-pagespy-0.1.2.tgz",
"@haina/utils-request": "https://research.hainatravel.com/npm/utils-request-0.1.2.tgz",
"@lexical/code": "^0.34.0",
"@lexical/hashtag": "^0.34.0",
"@lexical/html": "^0.34.0",
"@lexical/link": "^0.34.0",
"@lexical/list": "^0.34.0",
"@lexical/markdown": "^0.34.0",
"@lexical/react": "^0.34.0",
"@lexical/rich-text": "^0.34.0",
"@lexical/selection": "^0.34.0",
"@lexical/table": "^0.34.0",
"@lexical/utils": "^0.34.0",
"@vonage/client-sdk": "^2.0.0", "@vonage/client-sdk": "^2.0.0",
"antd": "^5.25.2", "antd": "^5.22.2",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"dingtalk-jsapi": "^3.0.41", "dingtalk-jsapi": "^3.0.41",
"emoji-picker-react": "^4.12.0", "emoji-picker-react": "^4.12.0",
"lexical": "^0.34.0", "lexical": "^0.20.0",
"prismjs": "^1.30.0",
"prop-types": "^15.8.1",
"react": "^18.3.1", "react": "^18.3.1",
"react-chat-elements": "^12.0.18", "react-chat-elements": "^12.0.17",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-markdown": "^10.1.0", "react-router-dom": "^6.28.0",
"react-router-dom": "^6.30.1",
"remark-gfm": "^4.0.1",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
"uuid": "^9.0.1", "uuid": "^9.0.1",
"workbox-window": "^7.3.0", "zustand": "^4.5.5"
"zustand": "^4.5.7"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.33.0",
"@types/react": "^18.3.12", "@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1", "@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3", "@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"eslint": "^9.33.0", "eslint": "^8.45.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.14",
"postcss": "^8.4.49", "postcss": "^8.4.49",
"tailwindcss": "^3.4.15", "tailwindcss": "^3.4.15",
"vite": "^4.5.1", "vite": "^4.5.1",

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="M11 4H21V6H11V4ZM6 7V11H4V7H1L5 3L9 7H6ZM6 17H9L5 21L1 17H4V13H6V17ZM11 18H21V20H11V18ZM9 11H21V13H9V11Z"></path></svg>

Before

Width:  |  Height:  |  Size: 208 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,4 +1,4 @@
import { fetchJSON, postForm, } from '@haina/utils-request'; import { fetchJSON, postForm, } from '@/utils/request';
import { API_HOST } from '@/config'; import { API_HOST } from '@/config';
/** /**

@ -1,9 +1,9 @@
import { groupBy, isNotEmpty, pick, sortArrayByOrder, sortBy } from '@haina/utils-commons'; import { groupBy, isNotEmpty, pick, sortArrayByOrder, sortBy } from '@/utils/commons';
import { fetchJSON, postJSON, postForm } from '@haina/utils-request' import { fetchJSON, postJSON, postForm } from '@/utils/request'
import { parseRenderMessageList } from '@/channel/bubbleMsgUtils'; import { parseRenderMessageList } from '@/channel/bubbleMsgUtils';
import { API_HOST } from '@/config'; import { API_HOST } from '@/config';
import { isEmpty } from '@haina/utils-commons'; import { isEmpty } from '@/utils/commons';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
/** /**
@ -11,9 +11,6 @@ import dayjs from 'dayjs';
*/ */
export const fetchTemplates = async (params) => { export const fetchTemplates = async (params) => {
const data = await fetchJSON(`${API_HOST}/listtemplates`, params); const data = await fetchJSON(`${API_HOST}/listtemplates`, params);
const leftPageCnt = Math.ceil( data?.result?.total/100 || 0)-1;
const leftData = await Promise.all(Array.from({ length: leftPageCnt }, (_, i) => fetchJSON(`${API_HOST}/listtemplates`, {...params, page: i+2})));
const leftItems = leftData.map(item => item.result.items).flat();
const topName = [ const topName = [
'agent_intro_with_update_v1', 'agent_intro_with_update_v1',
'online_inquiry_received', 'online_inquiry_received',
@ -23,22 +20,14 @@ export const fetchTemplates = async (params) => {
'travel_service_update_v2', 'travel_service_update_v2',
'travel_service_update_v1', 'travel_service_update_v1',
'order_updated_specialist_assigned_sharon', 'order_updated_specialist_assigned_sharon',
'travel_service_update_v3',
'first_message_for_not_reply', 'first_message_for_not_reply',
// 'free_style_3', // 'free_style_3',
// 'free_style_4', // 'free_style_4',
// CR
'notification_of_following_up_by_cr_v3','notification_of_following_up_by_cr_v1',
'notification_of_following_up_by_cr_v2',
'membership_activation_update_by_cr_v1', '45d_before_the_trip_referral_voucher_by_cr_v0',
'membership_activation_update_by_cr_v0',
'departure_reminder_by_cr_v5','departure_reminder_by_cr_v2',
]; ];
// shouwcase // shouwcase
const scNames = ['trip_planner_showcase', 'showcase_different', 'order_status_updated']; const scNames = ['trip_planner_showcase', 'showcase_different', 'order_status_updated'];
// 客运 // 客运
const crNames = [ const crNames = [
'notification_of_next_trip_planning',
// 'notification_of_following_up_by_cr_v3', // 'notification_of_following_up_by_cr_v3',
'notification_of_one_day_before_ending_the_trip_by_cr_v2', 'notification_of_one_day_before_ending_the_trip_by_cr_v2',
'one_day_after_payment_by_yuni', 'one_day_after_payment_by_yuni',
@ -47,14 +36,7 @@ export const fetchTemplates = async (params) => {
'one_day_before_ending_the_trip_contacted_by_yuni','one_day_before_ending_the_trip_first_time_by_yuni', 'one_day_before_ending_the_trip_contacted_by_yuni','one_day_before_ending_the_trip_first_time_by_yuni',
'post_booking_confirmation_welcome', 'post_booking_confirmation_welcome',
]; ];
const crNamesAuto = [ const crNamesOmit = [
'notification_of_status_changed', 'notification_of_next_trip_planning_by_cr_v2',
'notification_of_payment_received_3_asea_by_cr', 'one_day_after_payment_by_yuni',
'30_days_after_end_of_the_trip_asean_referral_voucher_by_cr',
'7notification_of_one_day_before_ending_the_trip_only_asean_by_cr_v7',
'notification_of_one_day_before_ending_the_trip_by_cr_v2',
];
const NamesOmit = [
'birthday_greetings_by_marketing','one_day_before_ending_the_trip_by_marketing', 'birthday_greetings_by_marketing','one_day_before_ending_the_trip_by_marketing',
'introduce_the_voucher_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', 'birthday_greetings_by_customer_relations_0',
@ -69,9 +51,8 @@ export const fetchTemplates = async (params) => {
'notification_of_account_updated_by_cr', 'notification_of_account_updated_by_cr',
'birthday_greetings_by_customer_relations', 'birthday_greetings_by_customer_relations',
'one_day_before_ending_the_trip_by_customer_relations', 'one_day_before_ending_the_trip_by_customer_relations',
'network_troubleshooting',
] ]
const canUseTemplates = (data?.result?.items || []).concat(leftItems) 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)) .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) => ({ .map((ele, i) => ({
...ele, ...ele,
@ -79,16 +60,8 @@ export const fetchTemplates = async (params) => {
components: groupBy(ele.components, (_c) => _c.type.toLowerCase()), components: groupBy(ele.components, (_c) => _c.type.toLowerCase()),
key: ele.name, key: ele.name,
// displayName: ele.name.startsWith('order_updated') ? templatesDisplayNameMap['order_updated']+`_${i}` : templatesDisplayNameMap?.[ele.name] || 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), displayName: templatesDisplayNameMap?.[ele.name] || (ele.name.startsWith('order_updated') ? templatesDisplayNameMap['order_updated']+`_${i}` : ele.name),
displayLanguage: NamesOmit.includes(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,
? '--'
: crNamesAuto.includes(ele.name)
? '客运Task'
: crNames.includes(ele.name) || ele.name.includes('by_cr')
? ele.language + '-客运'
: scNames.includes(ele.name)
? ele.language + '-示例'
: ele.language.slice(0, 2),
})) }))
const top2Name = topName.concat(canUseTemplates.filter(_t => _t.name.startsWith('order_updated')).map(_tem => _tem.name)); const top2Name = topName.concat(canUseTemplates.filter(_t => _t.name.startsWith('order_updated')).map(_tem => _tem.name));
@ -98,7 +71,7 @@ export const fetchTemplates = async (params) => {
const secondS = second.sort(sortBy('name')); const secondS = second.sort(sortBy('name'));
const raw = canUseTemplates.filter((_t) => !top2Name.includes(_t.name) && !_t.name.includes('free_style')); const raw = canUseTemplates.filter((_t) => !top2Name.includes(_t.name) && !_t.name.includes('free_style'));
// 剩下的排序 // 剩下的排序
const rawS = sortArrayByOrder(raw, 'name', [...crNames, ...scNames, ...NamesOmit ]); const rawS = sortArrayByOrder(raw, 'name', [...crNames, ...scNames, ...crNamesOmit ]);
return [...top, ...secondS, ...rawS]; return [...top, ...secondS, ...rawS];
}; };
/** /**
@ -117,7 +90,7 @@ const templatesDisplayNameMap = {
'agent_intro_with_update_v1': 'quick_update_v1', 'agent_intro_with_update_v1': 'quick_update_v1',
}; };
export const CONVERSATION_PAGE_SIZE = 100; export const CONVERSATION_PAGE_SIZE = 50;
/** /**
* *
* @param {object} params { opisn } * @param {object} params { opisn }
@ -378,11 +351,3 @@ export const deleteConversationTags = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/set_conversation_tags_del`, params); const { errcode, result } = await fetchJSON(`${API_HOST}/set_conversation_tags_del`, params);
return errcode !== 0 ? {} : result; return errcode !== 0 ? {} : result;
} }
/**
* 发送一条WhatsApp消息
*/
export const postSendWAMsg = async (params) => {
const { errcode, result } = await postJSON(`${API_HOST}/whatsapp_msg_send`, params);
return errcode !== 0 ? {} : result;
}

@ -1,36 +1,13 @@
import { fetchJSON, postForm, postJSON } from '@haina/utils-request'; import { fetchJSON, postForm } from '@/utils/request';
import { API_HOST, API_HOST_V3, DATE_FORMAT, DATEEND_FORMAT, DATETIME_FORMAT, EMAIL_HOST, EMAIL_HOST_v3 } from '@/config'; import { API_HOST, EMAIL_HOST } from '@/config';
import { buildTree, groupBy, isEmpty, objectMapper, omitEmpty, uniqWith } from '@haina/utils-commons';
import { readIndexDB, writeIndexDB } from '@/utils/indexedDB';
import dayjs from 'dayjs';
import { internalEventEmitter } from '@/utils/EventEmitterService';
export const parseHTMLString = (html, needText = false) => { const parseHTMLString = (html) => {
const parser = new DOMParser() const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html') const doc = parser.parseFromString(html, 'text/html')
let bodyContent = doc.body.innerHTML 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\';"') // 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
}
export const EMAIL_CHANNEL_NAME = 'mailbox_changes'; return bodyContent
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)
} }
/** /**
@ -41,8 +18,7 @@ export const getSalesSignatureAction = async (params) => {
try { try {
const { result } = await fetchJSON(`${EMAIL_HOST}/email_sign`, params) const { result } = await fetchJSON(`${EMAIL_HOST}/email_sign`, params)
const { SignContent: html } = result const { SignContent: html } = result
const bodyContent = parseHTMLString(html); return parseHTMLString(html);
return bodyContent;
} catch (error) { } catch (error) {
return ''; return '';
} }
@ -81,16 +57,17 @@ export const postResendEmailAction = async (body) => {
const encodeEmailInfo = (info) => { const encodeEmailInfo = (info) => {
const encodeQuote = (str = '') => str.replace(/"/g, ''); //.replace(/</g,'&lt;').replace(/>/g,'&gt;') const encodeQuote = (str = '') => str.replace(/"/g, ''); //.replace(/</g,'&lt;').replace(/>/g,'&gt;')
const CSsClean = encodeQuote(info.MAI_CS.replace(';', ',')).split(','); const CSsClean = encodeQuote(info.MAI_CS).includes(',') ? encodeQuote(info.MAI_CS).split(',') : encodeQuote(info.MAI_CS).split(';');
const tosClean = (encodeQuote(info.MAI_To.replace(';', ',')).split(',')).map(e => e.trim()).filter(s => s); const tosClean = (encodeQuote(info.MAI_To).includes(',') ? encodeQuote(info.MAI_To).split(',') : encodeQuote(info.MAI_To).split(';')).concat(CSsClean);
const replyTo = info.MAI_Direction === 1 ? info.MAI_To : info.MAI_From; const replyTo = info.MAI_Direction === 1 ? info.MAI_To : info.MAI_From;
const replyToAll = [].concat([info.MAI_From], tosClean); const replyToAll = (tosClean.length > 1) ?
(info.MAI_Direction === 1 ? tosClean.join(',') : `${tosClean.join(',')}, ${info.MAI_From}`)
: (info.MAI_Direction === 1 ? info.MAI_To : info.MAI_From)
return { return {
...info, ...info,
MAI_From: encodeQuote(info.MAI_From), MAI_From: encodeQuote(info.MAI_From),
MAI_To: encodeQuote(info.MAI_To), MAI_To: encodeQuote(info.MAI_To),
tos: [...new Set(tosClean)], tos: [...new Set(tosClean)],
ccs: [...new Set(CSsClean)],
replyToAll, replyToAll,
replyTo, replyTo,
} }
@ -100,37 +77,15 @@ const encodeEmailInfo = (info) => {
* @param {object} { mai_sn } * @param {object} { mai_sn }
*/ */
export const getEmailDetailAction = async (params) => { 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); const { result } = await fetchJSON(`${EMAIL_HOST}/getmail`, params);
let mailType = result.MailInfo?.[0]?.MAI_ContentType || ''; let mailType = result.MailInfo?.[0]?.MAI_ContentType || '';
mailType = mailType === '' && (result.MailContent||'').includes('<html') ? 'text/html' : mailType; mailType = mailType === '' && (result.MailContent||'').includes('<html') ? 'text/html' : mailType;
const emailInfo = encodeEmailInfo(result.MailInfo?.[0] || {}); return {
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 ret = {
info: { ...encodeEmailInfo(result.MailInfo?.[0] || {}), mailType }, info: { ...encodeEmailInfo(result.MailInfo?.[0] || {}), mailType },
content: mailType === 'text/html' ? html : result.MailContent || '', content: mailType === 'text/html' ? parseHTMLString((result.MailContent || '').replace(/\r\n/g, '')) : result.MailContent || '',
abstract: bodyText || result.MailContent || '', attachments: result?.AttachList || [],
attachments,
insideAttachments,
AttachList: isEmpty(result?.AttachList) ? [] : result.AttachList,
} }
// writeIndexDB([{key: cacheKey, data: ret}], 'mailinfo', 'mailbox')
return ret;
} }
export const getEmailOrderAction = async ({ colisn }) => { export const getEmailOrderAction = async ({ colisn }) => {
@ -168,323 +123,3 @@ export const fetchEmailBindOrderAction = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/mailinfo_bindorder`, params) const { errcode, result } = await fetchJSON(`${API_HOST}/mailinfo_bindorder`, params)
return errcode === 0 ? true : false; 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,4 +1,4 @@
import { fetchJSON, postForm, postJSON } from '@haina/utils-request' import { fetchJSON, postForm, postJSON } from '@/utils/request'
import { usingStorage } from '@/utils/usingStorage' import { usingStorage } from '@/utils/usingStorage'
const WAI_SERVER_KEY = 'G-STR:WAI_SERVER' const WAI_SERVER_KEY = 'G-STR:WAI_SERVER'

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

File diff suppressed because it is too large Load Diff

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

@ -1,4 +1,4 @@
import { cloneDeep, isEmpty, olog, fixTo2Decimals, pick, objectMapper } from "@haina/utils-commons"; import { cloneDeep, isEmpty, olog, fixTo2Decimals, pick, objectMapper } from "@/utils/commons";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { v4 as uuid } from "uuid"; import { v4 as uuid } from "uuid";
@ -58,27 +58,6 @@ export const WABAccounts = [
"requestedVerifiedName": "Customer Relation Specialist", "requestedVerifiedName": "Customer Relation Specialist",
"rejectionReason": "NONE" "rejectionReason": "NONE"
}, },
{
"id": "955633124303178",
"phoneNumber": "+85265210895",
"wabaId": "190290134156880",
"verifiedName": "Customer Relation Specialist at Highlights",
"qualityRating": "UNKNOWN",
"qualityUpdateEvent": "ONBOARDING",
"messagingLimit": "TIER_2K",
"whatsappBusinessManagerMessagingLimit": "TIER_2K",
"isOfficialBusinessAccount": false,
"codeVerificationStatus": "VERIFIED",
"status": "CONNECTED",
"displayPhoneNumber": "+852 6521 0895",
"nameStatus": "APPROVED",
"newName": "Customer Relation Specialist at Highlights",
"newNameStatus": "NONE",
"decision": "APPROVED",
"requestedVerifiedName": "Customer Relation Specialist at Highlights",
"rejectionReason": "NONE",
"isOnBizApp": false
},
]; ];
export const WABAccountsMapped = WABAccounts.reduce((a, c) => ({ ...a, [removeFirstPlus(c.phoneNumber)]: c, [c.phoneNumber]: c }), {}) export const WABAccountsMapped = WABAccounts.reduce((a, c) => ({ ...a, [removeFirstPlus(c.phoneNumber)]: c, [c.phoneNumber]: c }), {})
@ -87,8 +66,9 @@ export const replaceTemplateString = (str, replacements) => {
let keys = str.match(/{{(.*?)}}/g).map(key => key.replace(/{{|}}/g, '')); let keys = str.match(/{{(.*?)}}/g).map(key => key.replace(/{{|}}/g, ''));
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
const replaceValue = replacements[i]; let replaceValue = replacements[i];
result = result.replaceAll(`{{${keys[i]}}}`, replaceValue); let template = new RegExp(`{{${keys[i]}}}`, 'g');
result = result.replace(template, replaceValue);
} }
return result; return result;
@ -139,7 +119,7 @@ const mediaMsg = {
...msg, ...msg,
actionId: msg.id, actionId: msg.id,
conversationid: msg.id.split('.')[0], conversationid: msg.id.split('.')[0],
data: { ...msg.data, status: { download: true, click: true, loading: 0 } }, data: { ...msg.data, status: { download: msg.data?.loading ? false : true, click: true, loading: msg.data.loading } },
...(msg.context ...(msg.context
? { ? {
reply: { reply: {
@ -508,7 +488,7 @@ const sessionMsgMapped = {
getMsg: (result) => { getMsg: (result) => {
// sessionItem 是数组 // sessionItem 是数组
return isEmpty(result?.sessionItem) return isEmpty(result?.sessionItem)
? [] ? null
: result.sessionItem.map((ele) => ({ : result.sessionItem.map((ele) => ({
...ele, ...ele,
customer_name: `${ele.whatsapp_name || ''}`.trim(), customer_name: `${ele.whatsapp_name || ''}`.trim(),
@ -561,8 +541,6 @@ export const receivedMsgTypeMapped = {
getMsg: (result) => result, getMsg: (result) => result,
contentToRender: () => null, contentToRender: () => null,
contentToUpdate: (msgcontent) => { contentToUpdate: (msgcontent) => {
if (isEmpty(msgcontent)) return null;
if (isEmpty(msgcontent.error)) return null;
let apiErrorCode, let apiErrorCode,
apiErrorMsg = ''; apiErrorMsg = '';
const waCode = msgcontent.error.message.match(/\(#(\d+)\)/); const waCode = msgcontent.error.message.match(/\(#(\d+)\)/);
@ -712,12 +690,12 @@ export const whatsappMsgTypeMapped = {
unsupported: { unsupported: {
type: 'text', type: 'text',
data: (msg) => ({ id: msg.wamid, text: `[对方删除消息](${msg.wamid})`, dateString: `${dayjs(msg.sendTime).format('MM-DD HH:mm')} [ WhatsApp未提供消息内容 ] 客人删除消息/会话` }), data: (msg) => ({ id: msg.wamid, text: `[对方删除消息](${msg.wamid})`, dateString: `${dayjs(msg.sendTime).format('MM-DD HH:mm')} [ WhatsApp未提供消息内容 ] 客人删除消息/会话` }),
renderForReply: (msg) => ({ id: msg?.wamid || msg?.id || '', message: `[Message type unsupported](${msg.wamid})` }), renderForReply: (msg) => ({ id: msg?.wamid || msg.id, message: `[Message type unsupported](${msg.wamid})` }),
}, },
unresolvable: { unresolvable: {
type: 'text', type: 'text',
data: (msg) => ({ id: msg.wamid, text: `[无法解析](${msg.wamid})`, }), data: (msg) => ({ id: msg.wamid, text: `[无法解析](${msg.wamid})`, }),
renderForReply: (msg) => ({ id: msg?.wamid || msg?.id || '', message: `[无法解析](${msg.wamid})` }), renderForReply: (msg) => ({ id: msg?.wamid || msg.id, message: `[无法解析](${msg.wamid})` }),
}, },
reaction: { reaction: {
type: 'text', type: 'text',
@ -846,18 +824,15 @@ export const parseRenderMessageItem = (msg) => {
origin: msg.context, origin: msg.context,
}), }),
msg_source: msg?.msg_source || msg.type, msg_source: msg?.msg_source || msg.type,
whatsapp_msg_type: '',
waba: '',
wabaName: '',
...((msg.msg_source) === 'WABA' ? { ...((msg.msg_source) === 'WABA' ? {
whatsapp_msg_type: msg.type, whatsapp_msg_type: msg.type,
waba: msg.msg_direction === 'outbound' ? msg.from : msg.to, waba: msg.msg_direction === 'outbound' ? msg.from : msg.to,
wabaName: WABAccountsMapped[msg.msg_direction === 'outbound' ? msg.from : msg.to]?.verifiedName, wabaName: WABAccountsMapped[msg.msg_direction === 'outbound' ? msg.from : msg.to]?.verifiedName,
} : {}), } : {
...((msg.msg_source) === 'wai' ? { whatsapp_msg_type: '',
whatsapp_msg_type: msg.type, waba: '',
wabaName: '个人号', wabaName: '',
} : {}), }),
}; };
}; };
/** /**
@ -883,14 +858,14 @@ export const parseRenderMessageList = (messages) => {
msgContent.template = msg.msgtype === 'template' ? { ...msgContent.template, ...template } : {}; msgContent.template = msg.msgtype === 'template' ? { ...msgContent.template, ...template } : {};
// const parseMethod = msgContent.bizType === 'whatsapp' ? cloneDeep(whatsappMsgTypeMapped) : {}; // const parseMethod = msgContent.bizType === 'whatsapp' ? cloneDeep(whatsappMsgTypeMapped) : {};
let waCode, waError = ''; let waCode, waError = '';
if ((msgContent?.status || 'accepted') === 'failed' && (msgContent.errorMessage || msg.errors_code) && msg.msg_direction === 'outbound') { if ((msgContent?.status || 'accepted') === 'failed' && msgContent.errorMessage && msg.msg_direction === 'outbound') {
(waCode = (msgContent.errorMessage || msg.errors_code).match(/\(#(\d+)\)/)); (waCode = msgContent.errorMessage.match(/\(#(\d+)\)/));
(waError = (whatsappError?.[waCode?.[1]] || whatsappError?.[msgContent.errorCode] || msgContent.errorMessage || whatsappError?.[msg.errors_code])); (waError = (whatsappError?.[waCode?.[1]] || whatsappError?.[msgContent.errorCode] || msgContent.errorMessage));
if (!isEmpty(msgContent.whatsappApiError)) { if (!isEmpty(msgContent.whatsappApiError)) {
waError = whatsappError?.[msgContent.whatsappApiError.code] || msgContent.whatsappApiError.message; waError = whatsappError?.[msgContent.whatsappApiError.code] || msgContent.whatsappApiError.message;
// waError += `\n[${msgContent.errorCode}] ${whatsappError?.[msgContent.errorCode] || msgContent.errorMessage}`; // 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; waError = whatsappError.INVALID_PHONE_NUMBER;
} }
} }
@ -970,7 +945,7 @@ export const whatsappError = {
'100': '参数错误, 请联系技术组', '100': '参数错误, 请联系技术组',
'FORBIDDEN': '[FORBIDDEN] ', 'FORBIDDEN': '[FORBIDDEN] ',
'4': '[4] 无法连接WhatsApp.\n请稍后重试', // (#4) Application request limit reached '4': '[4] 无法连接WhatsApp.\n请稍后重试', // (#4) Application request limit reached
'131026': '[131026] 消息无法投递(未同意WhatsApp 的隐私政策).\n请使用 邮件/个人WhatsApp 联系', '131026': '[131026] 消息无法投递(未同意WhatsApp 的隐私政策).\n请使用邮件联系',
'131047': '[131047] 会话未激活. \n请使用模板消息💬发送', '131047': '[131047] 会话未激活. \n请使用模板消息💬发送',
'131053': '[131053] 文件上传失败.', '131053': '[131053] 文件上传失败.',
'131048': '[131048] 账户被风控.', // 消息发送太多, 达到垃圾数量限制 '131048': '[131048] 账户被风控.', // 消息发送太多, 达到垃圾数量限制
@ -1094,120 +1069,3 @@ export const phoneNumberToWAID = (input) => {
} }
export const uploadProgressSimulate = () => fixTo2Decimals(Math.random() * (0.8 - 0.2) + 0.2); export const uploadProgressSimulate = () => fixTo2Decimals(Math.random() * (0.8 - 0.2) + 0.2);
// Parse text segments for URLs and numbers
const parseTextForMarkdown = (text) => {
// Find URLs and four-digit numbers
const urlRegex = /https?:\/\/[^\s]+/g;
const numberRegex = /\d{4,}/g;
const matches = [];
// Find all URLs
let match;
while ((match = urlRegex.exec(text)) !== null) {
matches.push({ start: match.index, end: match.index + match[0].length, type: 'url', content: match[0] });
}
// Find all 4+ digit numbers
numberRegex.lastIndex = 0; // Reset regex
while ((match = numberRegex.exec(text)) !== null) {
matches.push({ start: match.index, end: match.index + match[0].length, type: 'number', content: match[0] });
}
// Sort matches by position
matches.sort((a, b) => a.start - b.start);
// Remove overlapping matches (URLs take priority)
const filteredMatches = [];
for (const current of matches) {
const isOverlapping = filteredMatches.some(existing =>
(current.start >= existing.start && current.start < existing.end) ||
(current.end > existing.start && current.end <= existing.end)
);
if (!isOverlapping) {
filteredMatches.push(current);
}
}
// Split text into segments
const segments = [];
let currentIndex = 0;
for (const match of filteredMatches) {
if (currentIndex < match.start) {
const textContent = text.slice(currentIndex, match.start);
if (textContent) {
segments.push({ type: 'text', content: textContent });
}
}
segments.push(match);
currentIndex = match.end;
}
if (currentIndex < text.length) {
const textContent = text.slice(currentIndex);
if (textContent) {
segments.push({ type: 'text', content: textContent });
}
}
return segments.length > 0 ? segments : [{ type: 'text', content: text }];
};
// Parse markdown with nesting support, autolinks, and number recognition
export const parseSimpleMarkdown = (text) => {
const tokens = [];
let current = '';
let i = 0;
while (i < text.length) {
const char = text[i];
if (char === '*' || char === '_') {
// Save any accumulated text before processing markdown
if (current) {
tokens.push(...parseTextForMarkdown(current));
current = '';
}
// Find the closing marker
const marker = char;
let j = i + 1;
let content = '';
let found = false;
while (j < text.length) {
if (text[j] === marker) {
found = true;
break;
}
content += text[j];
j++;
}
if (found && content) {
// Recursively parse the content inside the markers
tokens.push({
type: marker === '*' ? 'bold' : 'italic',
content: parseSimpleMarkdown(content)
});
i = j + 1; // Skip past the closing marker
} else {
// If no closing marker found, treat as regular text
current += char;
i++;
}
} else {
current += char;
i++;
}
}
// Add any remaining text
if (current) {
tokens.push(...parseTextForMarkdown(current));
}
return tokens;
};

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

@ -2,7 +2,7 @@ import { createContext, useEffect, useState } from 'react';
import {} from 'antd'; import {} from 'antd';
import Modal from '@dckj/react-better-modal'; import Modal from '@dckj/react-better-modal';
import '@dckj/react-better-modal/dist/index.css'; import '@dckj/react-better-modal/dist/index.css';
import { isEmpty } from '@haina/utils-commons'; import { isEmpty } from '@/utils/commons';
import useStyleStore from '@/stores/StyleStore'; import useStyleStore from '@/stores/StyleStore';
const DnDModal = ({ children, open, setOpen, onCancel, onMove, onResize, initial = {}, title, footer=null, ...props }) => { const DnDModal = ({ children, open, setOpen, onCancel, onMove, onResize, initial = {}, title, footer=null, ...props }) => {
@ -46,7 +46,7 @@ const DnDModal = ({ children, open, setOpen, onCancel, onMove, onResize, initial
maskClosable={false} maskClosable={false}
// theme='dark' // theme='dark'
// className={'!border !border-solid !border-indigo-500 rounded !p-2' } // 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' contentClassName='!p-2'
footerClassName='!p-2' footerClassName='!p-2'
className={`!rounded-t !rounded-b-none !border !border-solid !shadow-heavy ${props.rootClassName}`} className={`!rounded-t !rounded-b-none !border !border-solid !shadow-heavy ${props.rootClassName}`}

@ -1,6 +1,6 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import LexicalEditor from '@/components/LexicalEditor' import LexicalEditor from '@/components/LexicalEditor'
import { isEmpty } from '@haina/utils-commons'; import { isEmpty } from '@/utils/commons';
/** /**
* 封装的编辑组件, 用于在Form.Item 中使用 * 封装的编辑组件, 用于在Form.Item 中使用

@ -15,9 +15,7 @@ class ErrorBoundary extends PureComponent {
componentDidCatch(error, info) { componentDidCatch(error, info) {
console.error('Sorry, Something went wrong.') console.error('Sorry, Something went wrong.')
console.error(error) 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 }) this.setState({ hasError: true, info: error.message })
} }

@ -1,7 +1,7 @@
import Icon from '@ant-design/icons'; import Icon from '@ant-design/icons';
import ReplyLineSVG from '@/assets/icons/reply-line.svg?react'; 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 AttachmentLineSVG from '@/assets/icons/attachment-line.svg?react';
import AttachmentFillSVG from '@/assets/icons/attachment-fill.svg?react'; import AttachmentFillSVG from '@/assets/icons/attachment-fill.svg?react';
// import ShareForwardFillSVG from '@/assets/icons/share-forward-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 ResendLineSVG from '@/assets/icons/reset-left-line.svg?react';
import EditLineSVG from '@/assets/icons/quill-pen-line.svg?react'; import EditLineSVG from '@/assets/icons/quill-pen-line.svg?react';
import MailDownloadLineSVG from '@/assets/icons/mail-download-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} />; 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 ResendIcon = (props) => <Icon component={ResendLineSVG} {...props} />;
export const EditIcon = (props) => <Icon component={EditLineSVG} {...props} />; export const EditIcon = (props) => <Icon component={EditLineSVG} {...props} />;
export const MailDownloadIcon = (props) => <Icon component={MailDownloadLineSVG} {...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 = () => ( const WABSvg = () => (
<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' width='16' height='16'> <svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' width='16' height='16'>

@ -45,13 +45,11 @@ import TableCellResizer from './plugins/TableCellResizer';
// import {useLexicalEditable} from '@lexical/react/useLexicalEditable'; // import {useLexicalEditable} from '@lexical/react/useLexicalEditable';
import FormatPaintPlugin from './plugins/FormatPaint';
import { TextNode, $getRoot, $getSelection, $createParagraphNode } from 'lexical'; import { TextNode, $getRoot, $getSelection, $createParagraphNode } from 'lexical';
import { $generateHtmlFromNodes, $generateNodesFromDOM, } from '@lexical/html'; import { $generateHtmlFromNodes, $generateNodesFromDOM, } from '@lexical/html';
// import { } from '@lexical/clipboard'; // import { } from '@lexical/clipboard';
import { isEmpty } from '@haina/utils-commons'; import { isEmpty } from '@/utils/commons';
import {useSettings} from './context/SettingsContext'; import {useSettings} from './context/SettingsContext';
import './styles.css'; import './styles.css';
@ -205,7 +203,6 @@ export default function Editor({ isRichText, isDebug, editorRef, onChange, defau
<EditorRefPlugin editorRef={editorRef} /> <EditorRefPlugin editorRef={editorRef} />
<ImagesPlugin /> <ImagesPlugin />
<InlineImagePlugin /> <InlineImagePlugin />
<FormatPaintPlugin />
<MyOnChangePlugin onChange={onChange}/> <MyOnChangePlugin onChange={onChange}/>
</div> </div>
</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, $isRangeSelection,
$createParagraphNode, $createParagraphNode,
$getNodeByKey, $getNodeByKey,
$isTextNode,
} from 'lexical'; } from 'lexical';
import { $isLinkNode, $toggleLink, TOGGLE_LINK_COMMAND } from '@lexical/link'; import { $isLinkNode, $toggleLink, TOGGLE_LINK_COMMAND } from '@lexical/link';
import { import {
@ -26,14 +25,12 @@ import {
// $wrapNodes, // $wrapNodes,
$isAtNodeEnd, $isAtNodeEnd,
} from '@lexical/selection'; } 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 { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, REMOVE_LIST_COMMAND, $isListNode, ListNode } from '@lexical/list';
import { createPortal } from 'react-dom'; 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 { $createCodeNode, $isCodeNode, getDefaultCodeLanguage, getCodeLanguages } from '@lexical/code';
import { INSERT_HORIZONTAL_RULE_COMMAND } from '@lexical/react/LexicalHorizontalRuleNode'; 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 DropDown, { DropDownItem } from './../ui/DropDown';
import DropdownColorPicker from '../ui/DropdownColorPicker'; import DropdownColorPicker from '../ui/DropdownColorPicker';
import { import {
@ -42,7 +39,6 @@ import {
// InsertImagePayload, // InsertImagePayload,
} from './ImagesPlugin'; } from './ImagesPlugin';
import {InsertInlineImageDialog} from './InlineImagePlugin'; import {InsertInlineImageDialog} from './InlineImagePlugin';
import FormatPainterToolbarButton from './FormatPaint/FormatPainterToolbarButton';
import useModal from './../hooks/useModal'; import useModal from './../hooks/useModal';
@ -74,32 +70,16 @@ const FONT_FAMILY_OPTIONS = [
const FONT_SIZE_OPTIONS = [ const FONT_SIZE_OPTIONS = [
['10px', '10px'], ['10px', '10px'],
// ['11px', '11px'], ['11px', '11px'],
['12px', '12px'], ['12px', '12px'],
['13px', '13px'], ['13px', '13px'],
['14px', '14px'], ['14px', '14px'],
// ['15px', '15px'], ['15px', '15px'],
['16px', '16px'], ['16px', '16px'],
// ['17px', '17px'], ['17px', '17px'],
['18px', '18px'], ['18px', '18px'],
// ['19px', '19px'], ['19px', '19px'],
['20px', '20px'], ['20px', '20px'],
['24px', '24px'],
['32px', '32px'],
// ['48px', '48px'],
];
const LINE_SPACING_OPTIONS = [
['1', '1'],
['1.25', '1.25'],
['1.5', '1.5'],
['2', '2'],
['2.5', '2.5'],
['3', '3'],
// ['3.5', '3.5'],
// ['4', '4'],
// ['4.5', '4.5'],
// ['5', '5'],
]; ];
const ELEMENT_FORMAT_OPTIONS = { const ELEMENT_FORMAT_OPTIONS = {
@ -111,62 +91,6 @@ const ELEMENT_FORMAT_OPTIONS = {
start: { icon: 'left-align', iconRTL: 'right-align', name: 'Start Align' }, 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) { function dropDownActiveClass(active) {
if (active) { if (active) {
return 'active dropdown-item-active'; return 'active dropdown-item-active';
@ -547,26 +471,6 @@ function BlockOptionsDropdownList({ editor, blockType, toolbarRef, setShowBlockO
); );
} }
const FontDropDownMapped = {
'font-family': {
buttonAriaLabel: 'Formatting options for font family',
IconClassName: 'icon icon2 block-type font-family',
options: FONT_FAMILY_OPTIONS,
styleName: 'fontFamily',
},
'font-size': {
buttonAriaLabel: 'Formatting options for font size',
IconClassName: '',
options: FONT_SIZE_OPTIONS,
styleName: 'fontSize',
},
'line-height': {
buttonAriaLabel: 'Formatting options for line spacing',
IconClassName: 'icon icon2 line-height',
options: LINE_SPACING_OPTIONS,
styleName: 'lineHeight',
},
}
function FontDropDown({ editor, value, style, disabled = false }) { function FontDropDown({ editor, value, style, disabled = false }) {
const handleClick = useCallback( const handleClick = useCallback(
(option) => { (option) => {
@ -582,23 +486,25 @@ function FontDropDown({ editor, value, style, disabled = false }) {
[editor, style] [editor, style]
); );
const buttonIconClassName = FontDropDownMapped[style].IconClassName; const buttonAriaLabel = style === 'font-family' ? 'Formatting options for font family' : 'Formatting options for font size';
const buttonAriaLabel = FontDropDownMapped[style].buttonAriaLabel;
const dropdownOptions = FontDropDownMapped[style].options;
return ( return (
<DropDown disabled={disabled} buttonClassName={'toolbar-item ' + style} buttonLabel={value} buttonIconClassName={buttonIconClassName} buttonAriaLabel={buttonAriaLabel}> <DropDown
{dropdownOptions.map(([option, text]) => ( disabled={disabled}
buttonClassName={'toolbar-item ' + style}
// 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 <DropDownItem
className={`item font-m-${option.replace(/\s+/g, '_')} ${dropDownActiveClass(value === option)} ${style === 'font-size' ? 'fontsize-item' : ''}`} 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)} onClick={() => handleClick(option)}
key={option}> key={option}>
<span className='text'>{text}</span> <span className='text'>{text}</span>
</DropDownItem> </DropDownItem>
))} ))}
</DropDown> </DropDown>
) );
} }
function ElementFormatDropdown({ editor, value, isRTL, disabled = false }) { function ElementFormatDropdown({ editor, value, isRTL, disabled = false }) {
@ -699,11 +605,9 @@ export default function ToolbarPlugin() {
const [isStrikethrough, setIsStrikethrough] = useState(false); const [isStrikethrough, setIsStrikethrough] = useState(false);
const [isCode, setIsCode] = useState(false); const [isCode, setIsCode] = useState(false);
const [fontFamily, setFontFamily] = useState('Arial'); const [fontFamily, setFontFamily] = useState('Arial');
const [fontSize, setFontSize] = useState('16px');
const [fontColor, setFontColor] = useState('#000'); const [fontColor, setFontColor] = useState('#000');
const [bgColor, setBgColor] = useState('#fff'); const [bgColor, setBgColor] = useState('#fff');
const [elementFormat, setElementFormat] = useState('left'); const [elementFormat, setElementFormat] = useState('left');
const [lineSpacing, setLineSpacing] = useState('1.5');
const [floatingAnchorElem, setFloatingAnchorElem] = useState(null); const [floatingAnchorElem, setFloatingAnchorElem] = useState(null);
const [isSmallWidthViewport, setIsSmallWidthViewport] = useState(false); const [isSmallWidthViewport, setIsSmallWidthViewport] = useState(false);
@ -788,12 +692,6 @@ export default function ToolbarPlugin() {
setFontFamily( setFontFamily(
$getSelectionStyleValueForProperty(selection, 'font-family', 'Arial'), $getSelectionStyleValueForProperty(selection, 'font-family', 'Arial'),
); );
setFontSize(
$getSelectionStyleValueForProperty(selection, 'font-size', '16px'),
);
setLineSpacing(
$getSelectionStyleValueForProperty(selection, 'line-height', '1.5'),
);
let matchingParent; let matchingParent;
if ($isLinkNode(parent)) { if ($isLinkNode(parent)) {
// If node is a link, we need to fetch the parent paragraph node to set format // If node is a link, we need to fetch the parent paragraph node to set format
@ -887,14 +785,6 @@ export default function ToolbarPlugin() {
aria-label='Redo'> aria-label='Redo'>
<i className='format redo' /> <i className='format redo' />
</button> </button>
<FormatPainterToolbarButton />
<button type='button'
onClick={() => clearFormatting(activeEditor)}
className='toolbar-item'
title="清除格式"
aria-label='Clear'>
<i className='format clear' />
</button>
<Divider /> <Divider />
{supportedBlockTypes.has(blockType) && ( {supportedBlockTypes.has(blockType) && (
<> <>
@ -924,18 +814,6 @@ export default function ToolbarPlugin() {
value={fontFamily} value={fontFamily}
editor={editor} editor={editor}
/> />
<FontDropDown
disabled={!isEditable}
style={'font-size'}
value={fontSize}
editor={editor}
/>
<FontDropDown
disabled={!isEditable}
style={'line-height'}
value={lineSpacing}
editor={editor}
/>
<Divider /> <Divider />
<button type='button' <button type='button'
onClick={() => { onClick={() => {

@ -80,14 +80,13 @@
.editor-input { .editor-input {
min-height: 150px; min-height: 150px;
resize: none; resize: none;
font-size: 16px; font-size: 15px;
caret-color: rgb(5, 5, 5); caret-color: rgb(5, 5, 5);
position: relative; position: relative;
tab-size: 1; tab-size: 1;
outline: 0; outline: 0;
padding: 15px 10px; padding: 15px 10px;
caret-color: #444; caret-color: #444;
line-height: 1.5;
} }
.editor-pure-input { .editor-pure-input {
@ -405,7 +404,6 @@ pre::-webkit-scrollbar-thumb {
padding: 8px; padding: 8px;
cursor: pointer; cursor: pointer;
vertical-align: middle; vertical-align: middle;
word-break: keep-all;
} }
.toolbar button.toolbar-item:disabled { .toolbar button.toolbar-item:disabled {
@ -416,7 +414,7 @@ pre::-webkit-scrollbar-thumb {
margin-right: 2px; margin-right: 2px;
} }
.toolbar button.toolbar-item i.format, .toolbar button.toolbar-item .icon2 { .toolbar button.toolbar-item i.format {
background-size: contain; background-size: contain;
display: inline-block; display: inline-block;
height: 18px; height: 18px;
@ -432,8 +430,7 @@ pre::-webkit-scrollbar-thumb {
} }
.toolbar button.toolbar-item.active { .toolbar button.toolbar-item.active {
/* background-color: rgba(223, 232, 250, 0.8); */ background-color: rgba(223, 232, 250, 0.3);
background-color: #eef2ff;
} }
.toolbar button.toolbar-item.active i { .toolbar button.toolbar-item.active i {
@ -478,12 +475,12 @@ pre::-webkit-scrollbar-thumb {
.toolbar .toolbar-item .text { .toolbar .toolbar-item .text {
display: flex; display: flex;
line-height: 20px; line-height: 20px;
/* width: 200px; */ width: 200px;
vertical-align: middle; vertical-align: middle;
font-size: 14px; font-size: 14px;
color: #777; color: #777;
text-overflow: ellipsis; text-overflow: ellipsis;
width: 3rem; width: 70px;
overflow: hidden; overflow: hidden;
height: 20px; height: 20px;
text-align: left; text-align: left;
@ -607,8 +604,7 @@ i.chevron-down {
background-size: contain; background-size: contain;
} }
button.item.dropdown-item-active { button.item.dropdown-item-active {
/* background-color: #dfe8fa4d; */ background-color: #dfe8fa4d;
background-color: #eef2ff;
} }
.dropdown .item:first-child { .dropdown .item:first-child {
@ -765,9 +761,6 @@ i.undo {
i.redo { i.redo {
background-image: url(/images/icons/arrow-clockwise.svg); background-image: url(/images/icons/arrow-clockwise.svg);
} }
i.clear{
background-image: url(/images/icons/eraser-line.svg);
}
.icon.paragraph { .icon.paragraph {
background-image: url(/images/icons/text-paragraph.svg); background-image: url(/images/icons/text-paragraph.svg);
@ -843,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") 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 { i.bold {
background-image: url(/images/icons/type-bold.svg); background-image: url(/images/icons/type-bold.svg);
} }
@ -890,10 +879,6 @@ i.justify-align {
background-image: url(/images/icons/justify.svg); background-image: url(/images/icons/justify.svg);
} }
i.line-height, .icon.line-height {
background-image: url(/images/icons/line-height.svg);
}
.editor-container span.editor-image { .editor-container span.editor-image {
cursor: default; cursor: default;
display: inline-block; display: inline-block;

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

@ -1,77 +0,0 @@
import { useState } from "react";
import { Popover, message, FloatButton, Button, Form, Input } from "antd";
import { BugOutlined } from "@ant-design/icons";
import useAuthStore from '@/stores/AuthStore'
import { sendNotify } from "@/utils/pagespy";
import { uploadPageSpyLog } from "@haina/utils-pagespy";
function LogUploader() {
const [open, setOpen] = useState(false);
const hide = () => {
setOpen(false);
};
const handleOpenChange = (newOpen) => {
setOpen(newOpen);
};
const [loginUser] = useAuthStore((s) => [s.loginUser]);
const [messageApi, contextHolder] = message.useMessage();
const [formBug] = Form.useForm();
const popoverContent = (
<Form
layout={"vertical"}
form={formBug}
initialValues={{ problem: '' }}
scrollToFirstError
onFinish={async (values) => {
const success = await uploadPageSpyLog();
messageApi.success("Thanks for the feedback😊");
if (success) {
sendNotify(`${loginUser?.username}(${loginUser?.userIdStr})说:${values.problem}`);
} else {
sendNotify(`${loginUser?.username}(${loginUser?.userIdStr})上传日志失败`);
}
hide();
formBug.setFieldsValue({problem: ''});
}}
>
<Form.Item
name="problem"
label="Need help?"
rules={[{ required: true, message: "Specify issue needing support." }]}
>
<Input.TextArea rows={3} />
</Form.Item>
<Button
type="primary"
htmlType="submit"
color="cyan"
variant="solid"
block
>
Submit
</Button>
</Form>
);
return (
<>
{contextHolder}
<Popover
content={popoverContent}
trigger={["click"]}
placement="topRight"
open={open}
onOpenChange={handleOpenChange}
fresh
destroyOnHidden
>
<FloatButton icon={<BugOutlined />} tooltip={<div>上传日志给研发部</div>} />
</Popover>
</>
);
}
export default LogUploader;

@ -1,363 +0,0 @@
import {
WhatsAppOutlined,
FileAddOutlined,
MailOutlined,
PhoneOutlined,
UserOutlined,
FieldNumberOutlined,
CompassOutlined,
CalendarOutlined,
EditOutlined,
CheckOutlined,
CopyOutlined
} 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, Empty, Form, Input } from 'antd'
import { useOrderStore, OrderLabelDefaultOptions, OrderStatusDefaultOptions, remindStatusOptions } from '@/stores/OrderStore'
import { copy, isEmpty } from '@haina/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 = structuredClone(OrderLabelDefaultOptions)
orderLabelOptions.unshift({ value: 0, label: '未设置', disabled: true })
const orderStatusOptions = structuredClone(OrderStatusDefaultOptions)
const [orderDetail, customerDetail, fetchOrderDetail, setOrderPropValue,
appendOrderComment, updateWhatsapp, updateExtraInfo, remindCheckList, updateRemindState] = useOrderStore((s) => [
s.orderDetail,
s.customerDetail,
s.fetchOrderDetail,
s.setOrderPropValue,
s.appendOrderComment,
s.updateWhatsapp,
s.updateExtraInfo,
s.remindCheckList,
s.updateRemindState
])
const loginUser = useAuthStore((state) => state.loginUser)
const currentOrder = useConversationStore(useShallow((state) => state.currentConversation?.coli_sn || ''))
const orderId = coliSN || currentOrder
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) => {
try {
await updateRemindState(coliSN, checkedValue)
message.success('设置成功')
} catch (error) {
notification.warning({ message: '设置失败', description: error.message, placement: 'top', duration: 60 })
}
}
const getCustomerName = () => {
if (orderDetail.buytime > 0) return customerDetail.name + '(R' + orderDetail.buytime + ')'
return customerDetail.name
}
const getPlanStatus = () => {
return orderDetail.DidPlan === 0 ? '未做计划' : '已做计划'
}
const renderOrderDetail = () => {
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}
<CopyOutlined onClick={() => {
navigator.clipboard.writeText(orderDetail.order_no)
message.success('已复制😀')
}}/>
</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={remindCheckList} 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>
</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>
</>
)
}
const renderDefaultEmpty = () => {
return (
<Empty description={<span>没有订单关联</span>}>
</Empty>
)
}
if (orderId) {
return renderOrderDetail()
} else {
return props.renderEmpty ? props.renderEmpty() : renderDefaultEmpty()
}
}
export default OrderProfile

@ -1,6 +1,6 @@
import React, { useMemo, useRef, useState } from 'react'; import React, { useMemo, useRef, useState } from 'react';
import { Select, Spin } from 'antd'; import { Select, Spin } from 'antd';
import { debounce } from '@haina/utils-commons'; import { debounce } from '@/utils/commons';
function DebounceSelect({ fetchOptions, debounceTimeout = 800, ...props }) { function DebounceSelect({ fetchOptions, debounceTimeout = 800, ...props }) {
const [fetching, setFetching] = useState(false); const [fetching, setFetching] = useState(false);

@ -6,31 +6,26 @@
// export const WS_URL = 'wss://p9axztuwd7x8a7.mycht.cn/whatsapp_144'; // prod: Slave // export const WS_URL = 'wss://p9axztuwd7x8a7.mycht.cn/whatsapp_144'; // prod: Slave
// debug: // debug:
// export const API_HOST = 'http://202.103.68.144:8888/v2'; // 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:8888';
// 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.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_HOST = 'http://localhost:3031/api/v1'; // 美国服务器
export const WAI_SERVER_KEY = 'G-STR:WAI_SERVER' export const WAI_SERVER_KEY = 'G-STR:WAI_SERVER'
// prod:--------------------------------------------------------------------------------------------------
export const EMAIL_ATTA_HOST = 'https://p9axztuwd7x8a7.mycht.cn/attachment'; // 邮件附件 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 = '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 = '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 WS_URL = 'wss://p9axztuwd7x8a7.mycht.cn/whatsapp_server'; // prod:
export const VONAGE_URL = 'https://p9axztuwd7x8a7.mycht.cn/vonage-server'; // 语音和视频接口: 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 HT3 = process.env.NODE_ENV === 'production' ? 'https://p9axztuwd7x8a7.mycht.cn/ht3' : 'https://p9axztuwd7x8a7.mycht.cn/ht3';
export const CRM_HOST = process.env.NODE_ENV === 'production' ? 'https://wendao.hainatravel.com/crm_service' : 'http://202.103.68.157:8012/crm_service';
export const DATE_FORMAT = 'YYYY-MM-DD'; export const DATE_FORMAT = 'YYYY-MM-DD';
export const DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; 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_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_AP = 'https://hiana-crm.oss-ap-southeast-1.aliyuncs.com/WAMedia/';
export const OSS_URL = OSS_URL_AP; export const OSS_URL = OSS_URL_AP;
@ -40,9 +35,6 @@ export const DEFAULT_WABA = '+8617607730395';
const __BUILD_VERSION__ = `__BUILD_VERSION__`.replace(/"/g, '') const __BUILD_VERSION__ = `__BUILD_VERSION__`.replace(/"/g, '')
const __BUILD_DATE__ = `__BUILD_DATE__`; const __BUILD_DATE__ = `__BUILD_DATE__`;
const __GIT_HEAD__ = `__GIT_HEAD__`
export const BUILD_VERSION = import.meta.env.PROD ? __BUILD_VERSION__ : import.meta.env.MODE;
export const BUILD_DATE = import.meta.env.PROD ? __BUILD_DATE__ : new Date().toLocaleString();
export const GIT_HEAD = import.meta.env.PROD ? __GIT_HEAD__ : 'current';
export const POPUP_FEATURES = 'left=20,top=20,width=1000,height=800,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no'; 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();

@ -1,7 +1,7 @@
import useAuthStore from '@/stores/AuthStore'; import useAuthStore from '@/stores/AuthStore';
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import { fetchConversationsList, fetchOrderConversationsList, postNewOrEditConversationItem } from '@/actions/ConversationActions'; import { fetchConversationsList, fetchOrderConversationsList, postNewOrEditConversationItem } from '@/actions/ConversationActions';
import { isEmpty } from '@haina/utils-commons'; import { isEmpty } from '@/utils/commons';
const CHAT_ITEM_RECORD = { const CHAT_ITEM_RECORD = {
"sn": null, "sn": null,

@ -1,19 +1,16 @@
import { useState, useEffect, useCallback } from 'react' import { useState, useEffect, useCallback } from 'react'
import { isEmpty, objectMapper, olog, } from '@haina/utils-commons' import { isEmpty } from '@/utils/commons'
import { readIndexDB } from '@/utils/indexedDB' import { getEmailDetailAction, postResendEmailAction, getSalesSignatureAction, getEmailOrderAction } from '@/actions/EmailActions'
import { getEmailDetailAction, postResendEmailAction, getSalesSignatureAction, getEmailOrderAction, queryEmailListAction, searchEmailListAction, getReminderEmailTemplateAction, saveEmailDraftOrSendAction, updateEmailAction, getEmailChangesChannel, EMAIL_CHANNEL_NAME } from '@/actions/EmailActions'
import { App } from 'antd' import { App } from 'antd'
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import { msgStatusRenderMapped } from '@/channel/bubbleMsgUtils'; import { msgStatusRenderMapped } from '@/channel/bubbleMsgUtils';
import { POPUP_FEATURES } from '@/config';
import { internalEventEmitter } from '@/utils/EventEmitterService';
export const useEmailSignature = (opi_sn) => { export const useEmailSignature = (opi_sn) => {
const [signature, setSignature] = useState('') const [signature, setSignature] = useState('')
const getSignature = useCallback(async () => { const getSignature = useCallback(async () => {
if (isEmpty(Number(opi_sn))) { if (isEmpty(opi_sn)) {
return false return false
} }
try { try {
@ -26,418 +23,90 @@ export const useEmailSignature = (opi_sn) => {
useEffect(() => { useEffect(() => {
getSignature() getSignature()
}, [getSignature]) }, [opi_sn])
return { signature } return { signature, getSignature }
} }
/** /**
* 邮件详情
*
* @param mai_sn 邮件编号ID * @param mai_sn 邮件编号ID
* @param data 直接传递, 不重复获取 * @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 {notification} = App.useApp()
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [mailData, setMailData] = useState({ loading, info: { MAI_COLI_SN: 0 }, content: '', attachments: [], AttachList: [] }) const [mailData, setMailData] = useState({ loading, info: {}, content: '', attachments: [] })
const [maiSN, setMaiSN] = useState(mai_sn); const [coliSN, setColiSN] = useState('');
const [coliSN, setColiSN] = useState(oid);
const [orderDetail, setOrderDetail] = useState({}); const [orderDetail, setOrderDetail] = useState({});
const [refreshTrigger, setRefreshTrigger] = useState(0); const [updateMessageItem] = useConversationStore(state => [state.updateMessageItem]);
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
}
if (!isEmpty(data)) { useEffect(() => {
setMailData(data) const getEmailDetail = async () => {
return false if (isEmpty(mai_sn)) {
} return false
}
try { try {
setLoading(true) setLoading(true)
const data = await getEmailDetailAction({ mai_sn: Number(mai_sn) || maiSN }) const data = await getEmailDetailAction({ mai_sn })
// console.log(data) console.log('mail detail', data);
setMailData(data) setMailData(data)
setColiSN(oid === false ? 0 : data.info.MAI_COLI_SN) setColiSN(data.info.MAI_COLI_SN)
setLoading(false) setLoading(false)
// `已读` } catch (err) {
if (markRead !== false && data.info?.MOI_ReadState !== 1) { setLoading(false)
updateEmailAction({ notification.error({
opi_sn: data.info.MAI_OPI_SN, message: "请求失败",
mai_sn_list: [Number(mai_sn) || maiSN], description: err.message || '网络异常',
set: { read: 1 }, 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(() => { useEffect(() => {
getEmailDetail(); const getOrderDetail = async () => {
}, [getEmailDetail]) 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()
}, [getOrderDetail]) }, [coliSN])
const postEmailResend = async ({ mai_sn, conversationid: externalid, actionId: actionid, ...body }) => { const postEmailResend = async ({ mai_sn, conversationid: externalid, actionId: actionid, ...body }) => {
if (isEmpty(Number(mai_sn))) { if (isEmpty(mai_sn)) {
return false return false
} }
await postResendEmailAction({ mai_sn, externalid, actionid, token: 0 }) await postResendEmailAction({ mai_sn, externalid, actionid, token: 0 })
// 重发没有状态返回值, 此处前端处理为'待发送', todo: 刷新页面后消息仍为上一个状态'失败'
updateMessageItem({ conversationid: externalid, actionid, id: actionid, status: msgStatusRenderMapped['accepted'] })
} }
const postEmailSaveOrSend = async (body, isDraft) => { return { loading, mailData, orderDetail, postEmailResend }
const { id: savedID } = await saveEmailDraftOrSendAction(body, isDraft)
setMaiSN(savedID)
if (isDraft) {
refresh()
}
return savedID
};
return { loading, mailData, orderDetail, postEmailResend, postEmailSaveOrSend }
} }
export const EmailBuilder = ({subject, content}) => { 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: '一催模版1鼓励客人回复和讨论行程' },
{ type: 'RemindOneWL', index: 2, key: '2@RemindOneWL', value: '2@RemindOneWL', label: '一催模版2询问客人对于报价是否有疑问' },
{ type: 'divider' },
{ type: 'RemindTwoWL', index: 1, key: '1@RemindTwoWL', value: '1@RemindTwoWL', label: '二催模版1省钱的方式' },
{ type: 'RemindTwoWL', index: 2, key: '2@RemindTwoWL', value: '2@RemindTwoWL', label: '二催模版2Why us' },
{ type: 'divider' },
{ type: 'RemindThreeWL', index: 1, key: '1@RemindThreeWL', value: '1@RemindThreeWL', label: '三催模版1再次强调服务' },
{ type: 'RemindThreeWL', index: 2, key: '2@RemindThreeWL', value: '2@RemindThreeWL', label: '三催模版2客人常见问题询问' },
];
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: '已处理邮件' },
]

@ -1,5 +1,5 @@
import { useEffect } from 'react' import { useEffect } from 'react'
import { isEmpty } from '@haina/utils-commons' import { isEmpty } from '@/utils/commons'
import { App, notification } from 'antd' import { App, notification } from 'antd'
import useConversationStore from '@/stores/ConversationStore' import useConversationStore from '@/stores/ConversationStore'

@ -1,124 +0,0 @@
import { useCallback } from 'react';
import useConversationStore from '@/stores/ConversationStore';
const useShortUrlChange = () => {
const setGlobalNotify = useConversationStore((state) => state.setGlobalNotify);
const apiPrefix = {
"japanhighlights.com": "https://www.japanhighlights.com/index.php",
"chinahighlights.com": "https://www.chinahighlights.com/guide-use.php",
"highlightstravel.com": "https://www.highlightstravel.com/index.php",
"asiahighlights.com": "https://www.asiahighlights.com/index.php",
"globalhighlights.com": "https://www.globalhighlights.com/index.php",
};
const fetchNowConversationsitems = async (base64Url, apiUrl) => {
try {
const formData = new FormData();
formData.append(' url', base64Url);
formData.append('type', 'info');
const response = await fetch(`${apiUrl}/apps/short_link/index/create`, {
method: 'POST',
body: formData,
});
const data = await response.json();
if (data[0].name == 'ok') {
return data[0].value;
}
return null;
} catch (error) {
console.error('获取短链接转换内容失败:', error);
return null;
}
};
const urlBase64 = (longUrl) => {
try {
const extracted2 = longUrl.match(/https:\/\/www\.([^\/]+)/)?.[1] || '';
const encoder = new TextEncoder();
const utf8Bytes = encoder.encode(longUrl);
const base64Url = btoa(String.fromCharCode(...utf8Bytes));
return { base64Url, extracted2 };
} catch (error) {
setGlobalNotify([{
key: Date.now().toString(),
title: '错误',
content: '转换失败请检查输入的URL是否正确',
type: 'error'
}]);
console.error('URL转换错误:', error);
return { base64Url: '', extracted2: '' };
}
};
const normalizeUrl = (longUrl) => {
try {
const hasProtocol = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(longUrl);
const url = new URL(hasProtocol ? longUrl : `http://${longUrl}`);
const params = Object.fromEntries(url.searchParams.entries());
return {
url: url.href,
valid: true,
origin: url.origin,
hostname: url.hostname,
pathname: url.pathname,
params
};
} catch (e) {
return { valid: false, error: "Invalid URL" };
}
};
const convertUrl = useCallback(async (longUrl) => {
const normalizedUrl = normalizeUrl(longUrl);
if (!normalizedUrl.valid || Object.keys(normalizedUrl?.params || {}).length === 0) {
setGlobalNotify([{
key: Date.now().toString(),
title: '错误',
content: '没有需要转换的长链接, 请重新输入',
type: 'warning'
}]);
return null;
}
const { base64Url, extracted2 } = urlBase64(normalizedUrl.url);
if (base64Url) {
const apiUrl = apiPrefix[extracted2] || apiPrefix["chinahighlights.com"];
const extracted1 = apiUrl.match(/^https?:\/\/[^\/]*\.com/)?.[0] || '';
const data = await fetchNowConversationsitems(base64Url, apiUrl);
if (data) {
const resultShortUrl = extracted1 + data.isl_link;
setGlobalNotify([{
key: Date.now().toString(),
title: '成功',
content: '转换成功!',
type: 'success'
}]);
return resultShortUrl;
} else {
setGlobalNotify([{
key: Date.now().toString(),
title: '错误',
content: '转换失败请检查输入的URL是否正确',
type: 'error'
}]);
return null;
}
} else {
setGlobalNotify([{
key: Date.now().toString(),
title: '错误',
content: 'URL格式不正确请输入完整的URL',
type: 'error'
}]);
return null;
}
}, [setGlobalNotify]);
return { convertUrl };
};
export default useShortUrlChange;

@ -17,7 +17,7 @@ import MobileConversation from '@/views/mobile/Conversation'
import MobileChat from '@/views/mobile/Chat' import MobileChat from '@/views/mobile/Chat'
import CallCenter from '@/views/CallCenter' import CallCenter from '@/views/CallCenter'
import MobileSecondHeader from '@/views/mobile/SecondHeaderWrapper' 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 SnippetList from '@/views/accounts/SnippetList'
import GeneratePayment from '@/views/accounts/GeneratePayment' import GeneratePayment from '@/views/accounts/GeneratePayment'
@ -27,20 +27,11 @@ import ChatAssign from '@/views/Conversations/ChatAssign'
import DingdingLogin from '@/views/dingding/Login' import DingdingLogin from '@/views/dingding/Login'
import DingdingQRCode from '@/views/dingding/QRCode' import DingdingQRCode from '@/views/dingding/QRCode'
import DingdingAuthCode from '@/views/dingding/AuthCode' import DingdingAuthCode from '@/views/dingding/AuthCode'
import LocalWhatsAppQRCode from '@/views/accounts/LocalWhatsAppQRCode'
import useAuthStore from '@/stores/AuthStore' import useAuthStore from '@/stores/AuthStore'
import '@/assets/index.css' import '@/assets/index.css'
import CustomerRelation from '@/views/customer_relation/index' import CustomerRelation from '@/views/customer_relation/index'
import CustomerProfile from '@/views/customer-profile/all-in-one'
import NewEmail from '@/views/NewEmail'
import EmailDetailWindow from '@/views/EmailDetailWindow'
import { executeDailyCleanupTask, setupDailyMidnightCleanupScheduler } from '@/utils/indexedDB'
import { appendRequestHeader } from '@haina/utils-request';
import { BUILD_VERSION } from '@/config'
appendRequestHeader('X-Web-Version', BUILD_VERSION);
useAuthStore.getState().loadUserSession() useAuthStore.getState().loadUserSession()
const isMobileApp = const isMobileApp =
@ -69,7 +60,7 @@ const router = createBrowserRouter([
{ {
element: <MobileSecondHeader />, element: <MobileSecondHeader />,
children: [ children: [
{ path: 'm/order', element: <OrderProfile /> }, { path: 'm/order', element: <CustomerProfile /> },
{ path: 'callcenter/call', element: <CallCenter /> }, { path: 'callcenter/call', element: <CallCenter /> },
{ path: 'callcenter/call/:phonenumber', element: <CallCenter /> }, { path: 'callcenter/call/:phonenumber', element: <CallCenter /> },
], ],
@ -93,14 +84,8 @@ const router = createBrowserRouter([
{ path: 'callcenter/call', element: <CallCenter /> }, { path: 'callcenter/call', element: <CallCenter /> },
{ path: 'callcenter/call/:phonenumber', element: <CallCenter /> }, { path: 'callcenter/call/:phonenumber', element: <CallCenter /> },
{ path: 'customer_relation/index', element: <CustomerRelation /> }, { path: 'customer_relation/index', element: <CustomerRelation /> },
{ path: 'customer/profile', element: <CustomerProfile /> },
], ],
}, },
{ 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 />},
], ],
}, },
{ {
@ -113,7 +98,6 @@ const router = createBrowserRouter([
{ path: 'dingding/callback', element: <DingdingCallback /> }, { path: 'dingding/callback', element: <DingdingCallback /> },
{ path: 'dingding/qr-code', element: <DingdingQRCode /> }, { path: 'dingding/qr-code', element: <DingdingQRCode /> },
{ path: 'dingding/auth-code', element: <DingdingAuthCode /> }, { path: 'dingding/auth-code', element: <DingdingAuthCode /> },
{ path: 'whatsapp/qr-code', element: <LocalWhatsAppQRCode /> },
], ],
}, },
]) ])
@ -151,13 +135,3 @@ createRoot(root).render(
</ThemeContext.Provider> </ThemeContext.Provider>
</React.Suspense>, </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();
});

@ -1,4 +1,4 @@
import { clearAllCaches } from '@haina/utils-commons'; import { clearAllCaches } from '@/utils/commons';
import { BUILD_VERSION, BUILD_DATE } from '@/config' import { BUILD_VERSION, BUILD_DATE } from '@/config'
const MaintenancePage = () => { const MaintenancePage = () => {

@ -1,7 +1,7 @@
import { create } from 'zustand' import { create } from 'zustand'
import { devtools } from 'zustand/middleware' import { devtools } from 'zustand/middleware'
import { fetchJSON } from '@haina/utils-request' import { fetchJSON } from '@/utils/request'
import { isEmpty, isNotEmpty } from '@haina/utils-commons' import { isEmpty, isNotEmpty } from '@/utils/commons'
import { API_HOST, BUILD_VERSION } from '@/config' import { API_HOST, BUILD_VERSION } from '@/config'
import { usingStorage } from '@/utils/usingStorage'; import { usingStorage } from '@/utils/usingStorage';
@ -70,8 +70,9 @@ const useAuthStore = create(devtools((set, get) => ({
) )
if (json.errcode === 0 && isNotEmpty(json.result.opisn)) { if (json.errcode === 0 && isNotEmpty(json.result.opisn)) {
// TODO保存个人 WhatsApp 服务器地址
const waiServer = json.result.whatsappinfo.length > 0 ? json.result.whatsappinfo[0].wai_server : '' const waiServer = json.result.whatsappinfo.length > 0 ? json.result.whatsappinfo[0].wai_server : ''
setStorage(WAI_SERVER_KEY, waiServer) setStorage('G-STR:WAI_SERVER', waiServer)
set(() => ({ set(() => ({
loginUser: { loginUser: {
userId: json.result.opisn, userId: json.result.opisn,
@ -107,67 +108,6 @@ const useAuthStore = create(devtools((set, get) => ({
} }
}, },
parseLoginJson: (json) => {
const { setStorage } = usingStorage()
if (json.errcode === 0 && isNotEmpty(json.result.opisn)) {
const waiServer = json.result.whatsappinfo.length > 0 ? json.result.whatsappinfo[0].wai_server : ''
setStorage(WAI_SERVER_KEY, waiServer)
const parsedUser = {
userId: json.result.opisn,
userIdStr: json.result?.accountlist
.map((acc) => {
return acc.OPI_SN
})
.join(','),
emailList: json.result?.emaillist.map(item => {
return {
opi_sn: item.opi_sn,
mat_sn: item.mat_sn,
email: item.email,
default: item.Isdefaultemail == 1,
backup: item.Isbakemail == 1,
}
}),
whatsAppBusiness: json.result.whatsappinfo.length > 0 ? json.result.whatsappinfo[0].whatsapp_waba : '',
whatsAppNo: json.result.whatsappinfo.length > 0 ? json.result.whatsappinfo[0].whatsapp_wa : '',
accountName: json.result.opicode,
username: json.result.nick,
avatarUrl: json.result.avatarUrl,
mobile: '+' + json.result.stateCode + '-' + json.result.mobile,
email: json.result.email,
openId: json.result.openId,
accountList: json.result.accountlist,
}
return parsedUser
} else { return null }
},
// 钉钉免登后获取用户信息
loginByJSAuth: async (authCode) => {
const { saveUserSession, setLoginStatus, parseLoginJson } = get()
setLoginStatus(200)
const json = await fetchJSON(
'https://p9axztuwd7x8a7.mycht.cn/dingtalk/dingtalkwork/Getusers_auth_wa',
{ code: authCode },
)
const parsedUser = parseLoginJson(json)
if (parsedUser) {
set(() => ({
loginUser: parsedUser,
}))
saveUserSession()
setLoginStatus(302)
} else {
setLoginStatus(403)
}
},
getPrimaryEmail: () => { getPrimaryEmail: () => {
const { loginUser } = get() const { loginUser } = get()
@ -218,7 +158,13 @@ const useAuthStore = create(devtools((set, get) => ({
loadUserSession: () => { loadUserSession: () => {
let sessionData = window.sessionStorage.getItem('GLOBAL_SALES_LOGIN_USER') let sessionData = window.sessionStorage.getItem('GLOBAL_SALES_LOGIN_USER')
// 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"}]}`
// window.localStorage.setItem('GLOBAL_SALES_LOGIN_USER', sessionData)
// }
if (import.meta.env.DEV && isEmpty(sessionData)) { if (import.meta.env.DEV && isEmpty(sessionData)) {
sessionData = window.localStorage.getItem('GLOBAL_SALES_LOGIN_USER') sessionData = window.localStorage.getItem('GLOBAL_SALES_LOGIN_USER')
} }
@ -261,6 +207,26 @@ const useAuthStore = create(devtools((set, get) => ({
} }
}) })
}, },
sendNotify: async () => {
const { loginUser } = get()
const notifyUrl = 'https://p9axztuwd7x8a7.mycht.cn/dingtalk/dingtalkwork/SendMDMsgByDingRobotToGroup'
const params = {
groupid: 'cidFtzcIzNwNoiaGU9Q795CIg==',
msgTitle: '有人求助',
msgText: loginUser.username + '上传了销售平台' + BUILD_VERSION + '的日志'
};
return fetchJSON(notifyUrl, params)
.then(json => {
if (json.errcode === 0) {
console.info('发送通知成功')
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
}), { name: 'authStore' })) }), { name: 'authStore' }))
export default useAuthStore export default useAuthStore

@ -1,7 +1,7 @@
import { create } from "zustand"; import { create } from "zustand";
import { VonageClient, ClientConfig, ConfigRegion, LoggingLevel } from '@vonage/client-sdk' import { VonageClient, ClientConfig, ConfigRegion, LoggingLevel } from '@vonage/client-sdk'
import { fetchJSON } from "@haina/utils-request"; import { fetchJSON } from "@/utils/request";
import { prepareUrl, isNotEmpty, } from "@haina/utils-commons"; import { prepareUrl, isNotEmpty, } from "@/utils/commons";
import { VONAGE_URL, DATETIME_FORMAT } from "@/config"; import { VONAGE_URL, DATETIME_FORMAT } from "@/config";
import dayjs from "dayjs"; import dayjs from "dayjs";

@ -1,13 +1,11 @@
import { create } from 'zustand'; import { create } from 'zustand';
import { RealTimeAPI } from '@/channel/realTimeAPI'; import { RealTimeAPI } from '@/channel/realTimeAPI';
import { olog, isEmpty, groupBy, sortArrayByOrder, pick, sortKeys, omit, sortObjectsByKeysMap, merge } from '@haina/utils-commons'; import { olog, isEmpty, groupBy, sortArrayByOrder, logWebsocket, pick, sortKeys, omit, sortObjectsByKeysMap } from '@/utils/commons';
import { logWebsocket, clean7DaysWebsocketLog } from '@/utils/indexedDB'
import { receivedMsgTypeMapped, handleNotification } from '@/channel/bubbleMsgUtils'; import { receivedMsgTypeMapped, handleNotification } from '@/channel/bubbleMsgUtils';
import { fetchConversationsList, fetchTemplates, fetchConversationsSearch, UNREAD_MARK, fetchTags } from '@/actions/ConversationActions'; import { fetchConversationsList, fetchTemplates, fetchConversationsSearch, UNREAD_MARK, fetchTags } from '@/actions/ConversationActions';
import { devtools } from 'zustand/middleware'; import { devtools } from 'zustand/middleware';
import { WS_URL, DATETIME_FORMAT } from '@/config'; import { WS_URL, DATETIME_FORMAT } from '@/config';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import EmailSlice from './EmailSlice';
const replaceObjectsByKey = (arr1, arr2, key) => { const replaceObjectsByKey = (arr1, arr2, key) => {
const map2 = new Map(arr2.map(ele => [ele[key], ele])); const map2 = new Map(arr2.map(ele => [ele[key], ele]));
@ -179,7 +177,7 @@ const websocketSlice = (set, get) => ({
logWebsocket(data, 'I'); logWebsocket(data, 'I');
// olog('websocket Messages ----', data); // olog('websocket Messages ----', data);
// console.log(data); // console.log(data);
const { updateMessageItem, sentOrReceivedNewMessage, addGlobalNotify, setWai, addToConversationList, updateMailboxCount } = get() const { updateMessageItem, sentOrReceivedNewMessage, addGlobalNotify, setWai, addToConversationList } = get();
const { errcode, errmsg, result } = data; const { errcode, errmsg, result } = data;
if (!result) { if (!result) {
@ -195,18 +193,10 @@ const websocketSlice = (set, get) => ({
const msgRender = receivedMsgTypeMapped[resultType].contentToRender(msgObj); const msgRender = receivedMsgTypeMapped[resultType].contentToRender(msgObj);
const msgUpdate = receivedMsgTypeMapped[resultType].contentToUpdate(msgObj); const msgUpdate = receivedMsgTypeMapped[resultType].contentToUpdate(msgObj);
// console.log('msgRender msgUpdate', msgRender, msgUpdate); // 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 ([ if ([
'whatsapp.message.updated', 'message', 'error', 'whatsapp.message.updated', 'message', 'error',
'email.updated', 'wai.message.updated', 'email.updated', 'wai.message.updated',
].includes(resultType) && !isEmpty(msgUpdate)) { ].includes(resultType)) {
updateMessageItem(msgUpdate); updateMessageItem(msgUpdate);
} }
if (!isEmpty(msgRender)) { if (!isEmpty(msgRender)) {
@ -238,11 +228,9 @@ const websocketSlice = (set, get) => ({
// }, 60_000); // }, 60_000);
} }
// 会话表 更新 // 会话表 更新
if (['session.new', 'session.updated'].includes(resultType) if (['session.new', 'session.updated'].includes(resultType)) {
&& result.webhooksource !== 'email'
) {
const sessionList = receivedMsgTypeMapped[resultType].getMsg(result); const sessionList = receivedMsgTypeMapped[resultType].getMsg(result);
addToConversationList(sessionList || [], 'top') addToConversationList(sessionList, 'top');
} }
// console.log('handleMessage*******************'); // console.log('handleMessage*******************');
}, },
@ -278,17 +266,13 @@ const conversationSlice = (set, get) => ({
// 让当前会话显示在页面上 // 让当前会话显示在页面上
let _tmpCurrentMsgs = []; let _tmpCurrentMsgs = [];
if (currentConversation.sn) { if (currentConversation.sn) {
// _tmpCurrentMsgs = activeConversations[currentConversation.sn]; _tmpCurrentMsgs = activeConversations[currentConversation.sn];
} }
const conversationsMapped = conversationsList.reduce((r, v) => ({ ...r, [`${v.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 (currentConversation.sn) {
if (indexCurrent !== -1) { const hasCurrent = Object.keys(conversationsMapped).findIndex(sn => Number(sn) === Number(currentConversation.sn)) !== -1;
const [currentElement] = conversationsList.splice(indexCurrent, 1); conversationsMapped[currentConversation.sn] = _tmpCurrentMsgs;
conversationsList.unshift(currentElement); // Add to top const _len = hasCurrent ? 0 : conversationsList.unshift(currentConversation);
// 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);
} }
const { topList, pageList } = sortConversationList(conversationsList); const { topList, pageList } = sortConversationList(conversationsList);
@ -324,11 +308,9 @@ const conversationSlice = (set, get) => ({
const needUpdateCurrent = -1 !== newList.findIndex(row => Number(row.sn) === Number(currentConversation.sn)); 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 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 (currentConversation.sn) {
if (indexCurrent !== -1 ) { const hasCurrent = -1 !== Object.keys(mergedListMsgs).findIndex(sn => Number(sn) === Number(currentConversation.sn));
const [currentElement] = mergedList.splice(indexCurrent, 1); hasCurrent ? 0 : mergedList.unshift(currentConversation);
mergedList.unshift(currentElement); // Add to top
// 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 refreshTotalNotify = mergedList.reduce((r, c) => r+(c.unread_msg_count === UNREAD_MARK ? 0 : c.unread_msg_count), 0);
@ -452,25 +434,136 @@ const messageSlice = (set, get) => ({
targetMsgs.push(message); 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 }); setFilter({ loadNextPage: true });
// const { topList, pageList } = sortConversationList(mergedList);
return set({ return set({
// topList,
// pageList,
// conversationsList: mergedList,
activeConversations: { ...activeConversations, [String(targetId)]: targetMsgs }, activeConversations: { ...activeConversations, [String(targetId)]: targetMsgs },
}); });
}, },
sentOrReceivedNewMessage: (targetId, message) => { sentOrReceivedNewMessage: (targetId, message) => {
// msgRender: // msgRender:
// console.log('sentOrReceivedNewMessage', targetId, message) // console.log('sentOrReceivedNewMessage', targetId, message)
const { activeConversations, setFilter } = get(); const { activeConversations, conversationsList, currentConversation, totalNotify, setFilter } = get();
const targetMsgs = activeConversations[String(targetId)] || []; 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 }); 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({ return set({
// currentConversation: updatedCurrent,
// topList,
// pageList,
// conversationsList: [...conversationsList],
// totalNotify: totalNotify + (message.sender === 'me' ? 0 : 1),
activeConversations: { ...activeConversations, [String(targetId)]: [...targetMsgs, message] }, 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( export const useConversationStore = create(
devtools((set, get) => ({ devtools((set, get) => ({
...initialConversationState, ...initialConversationState,
@ -483,7 +576,7 @@ export const useConversationStore = create(
...tagsSlice(set, get), ...tagsSlice(set, get),
...filterSlice(set, get), ...filterSlice(set, get),
...globalNotifySlice(set, get), ...globalNotifySlice(set, get),
...EmailSlice(set, get), ...emailSlice(set, get),
...waiSlice(set, get), ...waiSlice(set, get),
// state actions // state actions
@ -492,10 +585,7 @@ export const useConversationStore = create(
// side effects // side effects
fetchInitialData: async ({userId, whatsAppBusiness, ...loginUser}) => { fetchInitialData: async ({userId, whatsAppBusiness, ...loginUser}) => {
const { addToConversationList, setTemplates, setInitial, setTags, const { addToConversationList, setTemplates, setInitial, setTags } = get();
initMailbox } = get();
initMailbox({ userId, dei_sn: loginUser.accountList[0].OPI_DEI_SN, opi_sn: loginUser.accountList[0].OPI_SN, userIdStr: loginUser.userIdStr })
const conversationsList = await fetchConversationsList({ opisn: userId }); const conversationsList = await fetchConversationsList({ opisn: userId });
addToConversationList(conversationsList); addToConversationList(conversationsList);

@ -1,8 +1,8 @@
import { create } from 'zustand' import { create } from 'zustand'
import { devtools } from 'zustand/middleware' import { devtools } from 'zustand/middleware'
import { fetchJSON, postForm } from '@haina/utils-request' import { fetchJSON, postForm } from '@/utils/request'
import { HT3, EMAIL_HOST } from '@/config' import { HT3, EMAIL_HOST } from '@/config'
import { isNotEmpty, prepareUrl } from '@haina/utils-commons' import { isNotEmpty, prepareUrl } from '@/utils/commons'
export const useCustomerRelationStore = create((set, get) => ({ export const useCustomerRelationStore = create((set, get) => ({
loading: false, loading: false,

@ -1,189 +0,0 @@
import { getEmailDirAction, getMailboxCountAction, getRootMailboxDirAction, getEmailChangesChannel, EMAIL_CHANNEL_NAME } from '@/actions/EmailActions'
import { buildTree, isEmpty, olog, sortArrayByOrder } from '@haina/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 }), setMsgHistorySelectMatch: (msgHistorySelectMatch) => set({ msgHistorySelectMatch }),
msgListParams: {}, msgListParams: {},
setMsgListParams: (msgListParams) => set(state => ({ msgListParams: {...state.msgListParams, ...msgListParams} })), setMsgListParams: (msgListParams) => set(state => ({ msgListParams: {...state.msgListParams, ...msgListParams} })),
ImageAlbum: [], ImageAlbum: [],
setImageAlbum: (ImageAlbum) => set({ ImageAlbum }), setImageAlbum: (ImageAlbum) => set({ ImageAlbum }),
ImagePreviewSrc: '', ImagePreviewSrc: '',
setImagePreviewSrc: (ImagePreviewSrc) => set({ ImagePreviewSrc }), setImagePreviewSrc: (ImagePreviewSrc) => set({ ImagePreviewSrc }),
EmailList: [],
setEmailList: (EmailList) => set({ EmailList }),
// 订单跟踪页面 // 订单跟踪页面
orderFollowForm: { orderFollowForm: {
type: 'today', type: 'today',

@ -1,8 +1,8 @@
import { create } from 'zustand' import { create } from 'zustand'
import { devtools } from 'zustand/middleware' import { devtools } from 'zustand/middleware'
import { fetchJSON, postForm, postJSON } from '@haina/utils-request' import { fetchJSON, postForm } from '@/utils/request'
import { API_HOST, API_HOST_V3, EMAIL_HOST } from '@/config' import { API_HOST, EMAIL_HOST } from '@/config'
import { isEmpty, isNotEmpty, prepareUrl, uniqWith } from '@haina/utils-commons' import { isNotEmpty, prepareUrl } from '@/utils/commons'
const initialState = { const initialState = {
orderList: [], orderList: [],
@ -11,261 +11,212 @@ const initialState = {
lastQuotation: {}, lastQuotation: {},
quotationList: [], quotationList: [],
otherEmailList: [], otherEmailList: [],
remindCheckList: [], };
}
export const useOrderStore = create(devtools((set, get) => ({
export const useOrderStore = create(
devtools( ...initialState,
(set, get) => ({ drawerOpen: false,
...initialState,
drawerOpen: false, resetOrderStore: () => set(initialState),
resetOrderStore: () => set(initialState), openDrawer: () => {
set(() => ({
openDrawer: () => { drawerOpen: true
set(() => ({ }))
drawerOpen: true, },
}))
}, closeDrawer: () => {
set(() => ({
closeDrawer: () => { drawerOpen: false
set(() => ({ }))
drawerOpen: false, },
}))
}, fetchOrderList: async (formValues, loginUser) => {
let fetchOrderUrl = `${API_HOST}/getwlorder?opisn=${loginUser.userIdStr}&otype=${formValues.type}`
fetchOrderList: async (formValues, loginUser) => { const params = {};
let fetchOrderUrl = `${API_HOST}/getwlorder?opisn=${loginUser.userIdStr}&otype=${formValues.type}`
const params = {} if (formValues.type === 'advance') {
fetchOrderUrl = `${API_HOST}/getdvancedwlorder?opisn=${loginUser.userIdStr}`;
if (formValues.type === 'advance') { const { type, ...formParams } = formValues;
fetchOrderUrl = `${API_HOST}/getdvancedwlorder?opisn=${loginUser.userIdStr}` Object.assign(params, formParams)
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 } fetchOrderDetail: (colisn) => {
}) return fetchJSON(`${API_HOST}/getorderinfo`, { colisn })
const _result_unique = uniqWith(_result, (a, b) => a.COLI_SN === b.COLI_SN) .then(json => {
set(() => ({ if (json.errcode === 0 && json.result.length > 0) {
orderList: _result_unique, const orderResult = json.result[0]
})) set(() => ({
} else { orderDetail: {...orderResult, coli_sn: colisn },
throw new Error(json?.errmsg + ': ' + json.errcode) customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
} lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
}) quotationList: orderResult.quotes,
}, }))
return {
fetchOrderDetail: (colisn) => { orderDetail: {...orderResult, coli_sn: colisn },
return fetchJSON(`${API_HOST}/getorderinfo`, { colisn }).then((json) => { customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
if (json.errcode === 0 && json.result.length > 0) { lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
const orderResult = json.result[0] quotationList: orderResult.quotes,
set(() => ({
remindCheckList: transferRemind2Checklist(orderResult.remindstate),
orderDetail: { ...orderResult, coli_sn: colisn },
customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
}))
return {
orderDetail: { ...orderResult, coli_sn: colisn },
customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
}
} else {
throw new Error(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('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)
}
})
updateRemindState: async (orderId, checkedValue) => { },
set(() => ({
remindCheckList: checkedValue, importEmailMessage: ({ orderId, orderNumber }) => {
})) return fetchJSON(`${API_HOST}/generate_email_msg`, { coli_sn: orderId, coli_id: orderNumber })
const finalState = { .then(json => {
'FirstRemind': checkedValue.includes('FirstRemind') ? 1 : 0, if (json.errcode === 0) {
'SecondRemind': checkedValue.includes('SecondRemind') ? 1 : 0, return json
'ThirdRemind': checkedValue.includes('ThirdRemind') ? 1 : 0, } else {
'important': checkedValue.includes('important') ? 1 : 0, throw new Error(json?.errmsg + ': ' + json.errcode)
'sendsurvey': checkedValue.includes('sendsurvey') ? 1 : 0,
} }
const { errcode, result } = await postJSON(`${API_HOST}/SetRemindState`, { coli_sn: orderId, remindstate: JSON.stringify(finalState)}) })
return errcode === 0 ? result : {} },
},
batchImportEmailMessage: () => {
appendOrderComment: async (opi_sn, coli_sn, comment) => { const { orderList } = get()
const { fetchOrderDetail } = get()
const formData = new FormData() const orderPromiseList = orderList.map(order => {
formData.append('opi_sn', opi_sn) return new Promise((resolve, reject) => {
formData.append('coli_sn', coli_sn) fetchJSON(`${API_HOST}/generate_email_msg`, { coli_sn: order.COLI_SN, coli_id: order.COLI_ID })
formData.append('remark', comment) .then(json => {
if (json.errcode === 0) {
return postForm(`${API_HOST}/remark_order`, formData).then((json) => { resolve(json)
if (json.errcode === 0) { } else {
return fetchOrderDetail(coli_sn) reject(json?.errmsg + ': ' + json.errcode)
} 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) Promise.all(orderPromiseList).then((values) => {
}) console.log(values);
}, })
},
fetchOtherEmail: (coli_sn) => {
return fetchJSON(`${EMAIL_HOST}/email_supplier`, { coli_sn }).then((json) => { fetchOtherEmail: (coli_sn) => {
if (json.errcode === 0) { return fetchJSON(`${EMAIL_HOST}/email_supplier`, { coli_sn })
set(() => ({ .then(json => {
otherEmailList: json.result.MailInfo ?? [], if (json.errcode === 0) {
})) set(() => ({
} else { otherEmailList: json.result.MailInfo ?? [],
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,
},
})) }))
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
} }
})
},
if (propName === 'orderstatus') { setOrderPropValue: async (colisn, propName, value) => {
set((state) => ({
orderDetail: { if (propName === 'orderlabel') {
...state.orderDetail, set((state) => ({
states: value, orderDetail: {
}, ...state.orderDetail,
})) tags: value
}
}))
}
if (propName === 'orderstatus') {
set((state) => ({
orderDetail: {
...state.orderDetail,
states: value
} }
}))
}
return fetchJSON(`${API_HOST}/setorderstatus`, { colisn, stype: propName, svalue: value }).then((json) => { return fetchJSON(`${API_HOST}/setorderstatus`, { colisn, stype: propName, svalue: value })
if (json.errcode > 0) { .then(json => {
throw new Error(json?.errmsg + ': ' + json.errcode) if (json.errcode > 0) {
} throw new Error(json?.errmsg + ': ' + json.errcode)
}) }
}, })
}), },
{ name: 'orderStore' },
), }), { name: 'orderStore' }))
)
export const OrderLabelDefaultOptions = [ export const OrderLabelDefaultOptions = [
{ value: 240003, label: '重点', emoji: '❣️' }, { value: 240003, label: '重点', emoji: '❣️' },
{ value: 240002, label: '次重点', emoji: '❗' }, { value: 240002, label: '次重点', emoji: '❗' },
{ value: 240001, label: '一般', emoji: '' }, { value: 240001, label: '一般', emoji: '' }
] ]
export const OrderLabelDefaultOptionsMapped = OrderLabelDefaultOptions.reduce((acc, cur) => { export const OrderLabelDefaultOptionsMapped = OrderLabelDefaultOptions.reduce((acc, cur) => {
return { ...acc, [String(cur.value)]: cur } return { ...acc, [String(cur.value)]: cur }
}, {}) }, {}) ;
export const OrderStatusDefaultOptions = [ export const OrderStatusDefaultOptions = [
{ value: 1, label: '新订单', emoji: '' }, { value: 1, label: '新订单', emoji: '' },
@ -274,8 +225,8 @@ export const OrderStatusDefaultOptions = [
{ value: 4, label: '等待付订金', emoji: '🛒' }, { value: 4, label: '等待付订金', emoji: '🛒' },
{ value: 5, label: '成行', emoji: '💰' }, { value: 5, label: '成行', emoji: '💰' },
{ value: 6, label: '丢失', emoji: '🎈' }, { value: 6, label: '丢失', emoji: '🎈' },
// { value: 7, label: '取消', emoji: '🚫' }, // 取消要顾问确认后才能执行操作,暂时到 HT 操作 { value: 7, label: '取消', emoji: '🚫' },
{ value: 8, label: '未报价', emoji: '' }, { value: 8, label: '未报价', emoji: '' }
] ]
export const OrderStatusDefaultOptionsMapped = OrderStatusDefaultOptions.reduce((acc, cur) => { export const OrderStatusDefaultOptionsMapped = OrderStatusDefaultOptions.reduce((acc, cur) => {
return { ...acc, [String(cur.value)]: cur } return { ...acc, [String(cur.value)]: cur }
@ -287,32 +238,25 @@ export const OrderStatusDefaultOptionsMapped = OrderStatusDefaultOptions.reduce(
export const RemindStateDefaultOptions = [ export const RemindStateDefaultOptions = [
{ value: '1', label: '一催' }, { value: '1', label: '一催' },
{ value: '2', label: '二催' }, { value: '2', label: '二催' },
{ value: '3', label: '三催' }, { value: '3', label: '三催' }
] ]
/** /**
* @useage 订单信息: 标记状态 * @useage 订单信息: 标记状态
*/ */
export const remindStatusOptions = [ export const remindStatusOptions = [
{ value: 'FirstRemind', label: '已发一催' }, { value: '1', label: '已发一催' },
{ value: 'SecondRemind', label: '已发二催' }, { value: '2', label: '已发二催' },
{ value: 'ThirdRemind', label: '已发三催' }, { value: '3', label: '已发三催' },
{ value: 'important', label: '重点团' }, { value: 'important', label: '重点团' },
{ value: 'sendsurvey', label: '已发 travel advisor survey' }, { value: 'sendsurvey', label: '已发 travel advisor survey' },
] ];
const transferRemind2Checklist = (remindstate) => {
const remindValueList = []
if (isEmpty(remindstate)) return remindValueList
Object.keys(remindstate).forEach(prop => {
if (remindstate[prop]) remindValueList.push(prop)
})
return remindValueList
}
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 : {};
};

@ -1,8 +1,8 @@
import { create } from 'zustand' import { create } from 'zustand'
import { devtools } from 'zustand/middleware' import { devtools } from 'zustand/middleware'
import { fetchJSON, postForm } from '@haina/utils-request' import { fetchJSON, postForm } from '@/utils/request'
import { API_HOST } from '@/config' import { API_HOST } from '@/config'
import { copy } from '@haina/utils-commons' import { copy } from '@/utils/commons'
const useSnippetStore = create(devtools((set, get) => ({ const useSnippetStore = create(devtools((set, get) => ({
@ -41,7 +41,7 @@ const useSnippetStore = create(devtools((set, get) => ({
const mapTypeList = json?.result?.type.map(item => { const mapTypeList = json?.result?.type.map(item => {
return { value: item.vsn, label: item.vname } return { value: item.vsn, label: item.vname }
}) })
const mapTypeAllList = structuredClone(mapTypeList); const mapTypeAllList = copy(mapTypeList);
mapTypeAllList.unshift({ value: '', label: '全部' }); mapTypeAllList.unshift({ value: '', label: '全部' });
set(() => ({ set(() => ({
ownerList: json?.result?.owner.map(item => { ownerList: json?.result?.owner.map(item => {

@ -1,21 +0,0 @@
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
const useUrlStore = create(devtools((set, get) => ({
drawerOpen: false,
openDrawer: () => {
set(() => ({
drawerOpen: true
}))
},
closeDrawer: () => {
set(() => ({
drawerOpen: false
}))
},
}), { name: 'urlStore' }))
export default useUrlStore

@ -1,132 +0,0 @@
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { fetchJSON, postForm, postJSON } from '@haina/utils-request'
import { CRM_HOST } from '@/config'
import { isEmpty, isNotEmpty, prepareUrl, uniqWith } from '@haina/utils-commons'
const initialState = {
customerList: [],
contactList: [],
orderList: [],
customerDetail: {},
customerSummary: '',
customerMaster: '',
orderProfile: {},
}
export const useCustomerProfileStore = create(
devtools(
(set, get) => ({
...initialState,
reset: () => set(initialState),
fetchCustomerList: async (input) => {
const fetchCustomerUrl = `${CRM_HOST}/search_customers`
return fetchJSON(fetchCustomerUrl, {keyword: input}).then((json) => {
if (json.errcode === 0) {
set(() => ({
customerList: json.result,
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchCustomerDetail: async (customerId) => {
const fetchCustomerUrl = `${CRM_HOST}/get_customer_detail`
return fetchJSON(fetchCustomerUrl, {customer_id: customerId}).then((json) => {
if (json.errcode === 0) {
set(() => ({
customerDetail: json.result,
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchCustomerSummary: async (customerId) => {
const fetchCustomerUrl = `${CRM_HOST}/get_customer_summary`
return fetchJSON(fetchCustomerUrl, {customer_id: customerId}).then((json) => {
if (json.errcode === 0) {
set(() => ({
customerSummary: json.result??'',
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchCustomerMaster: async (customerId) => {
// /get_customer_primary?customer_id=79174
const fetchCustomerUrl = `${CRM_HOST}/get_customer_primary`
return fetchJSON(fetchCustomerUrl, {customer_id: customerId}).then((json) => {
if (json.errcode === 0) {
set(() => ({
customerMaster: json.result??'',
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchContactList: async (customerId) => {
const fetchCustomerUrl = `${CRM_HOST}/get_customer_contact`
return fetchJSON(fetchCustomerUrl, {customer_id: customerId}).then((json) => {
if (json.errcode === 0) {
set(() => ({
contactList: json.result,
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchOrderList: async (customerId) => {
const fetchCustomerUrl = `${CRM_HOST}/get_customer_order`
return fetchJSON(fetchCustomerUrl, {customer_id: customerId}).then((json) => {
if (json.errcode === 0) {
set(() => ({
orderList: json.result,
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
fetchOrderProfile: async (orderSn) => {
const fetchCustomerUrl = `${CRM_HOST}/get_customer_profile`
return fetchJSON(fetchCustomerUrl, {order_sn: orderSn}).then((json) => {
if (json.errcode === 0) {
set(() => ({
orderProfile: json.result,
}))
return json.result
} else {
throw new Error(json?.errmsg + ': ' + json.errcode)
}
})
},
}),
{ name: 'customerProfile' },
),
)

@ -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();

@ -1,4 +1,3 @@
console.warn('Warning: `commons.js` is deprecated and will be removed in next version.');
export function copy(obj) { export function copy(obj) {
return JSON.parse(JSON.stringify(obj)) return JSON.parse(JSON.stringify(obj))
} }
@ -189,8 +188,6 @@ export function merge(...objects) {
* 数组分组 * 数组分组
* - 相当于 lodash _.groupBy * - 相当于 lodash _.groupBy
* @see https://www.lodashjs.com/docs/lodash.groupBy#_groupbycollection-iteratee_identity * @see https://www.lodashjs.com/docs/lodash.groupBy#_groupbycollection-iteratee_identity
* ECMAScript 2021 原生
* - Object.groupBy(items, callbackFn)
*/ */
export function groupBy(array = [], callback) { export function groupBy(array = [], callback) {
return array.reduce((groups, item) => { return array.reduce((groups, item) => {
@ -229,15 +226,6 @@ export function omit(object, keysToOmit) {
return Object.fromEntries(Object.entries(object).filter(([key]) => !keysToOmit.includes(key))); 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;
};
/** /**
* 深拷贝 * 深拷贝
*/ */
@ -604,77 +592,69 @@ export const TagColorStyle = (tag, outerStyle = false) => {
return { color: `${color}`, ...outerStyleObj }; 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: [] }) => { export const logWebsocket = (message, direction) => {
if (!list || list.length === 0) { var open = indexedDB.open('LogWebsocketData', 2)
return [] open.onupgradeneeded = function () {
var db = open.result
// 数据库是否存在
if (!db.objectStoreNames.contains('LogStore')) {
var store = db.createObjectStore('LogStore', { keyPath: 'id', autoIncrement: true })
}
} }
open.onsuccess = function () {
const nodeMap = new Map() var db = open.result
const treeRoots = [] var tx = db.transaction('LogStore', 'readwrite')
var store = tx.objectStore('LogStore')
list.forEach((item) => { store.put({ direction, message, date: new Date().toLocaleString() })
const node = createTreeNode(item[keyMap.key], item[keyMap.name], item[keyMap.parent], keyMap, item) tx.oncomplete = function () {
nodeMap.set(item[keyMap.key], node) db.close()
}) }
}
list.forEach((item) => { };
const node = nodeMap.get(item[keyMap.key]) export const readWebsocketLog = () => {
if (keyMap.rootKeys.includes(item[keyMap.parent]) || item[keyMap.parent] === null || item[keyMap.parent] === undefined) { return new Promise((resolve, reject) => {
// This is a root node let openRequest = indexedDB.open('LogWebsocketData')
treeRoots.push(node) openRequest.onerror = function (e) {
} else { reject('Error opening database.')
const parentNode = nodeMap.get(item[keyMap.parent]) }
if (keyMap.ignoreKeys.includes(item[keyMap.parent])) { openRequest.onsuccess = function (e) {
const grandParentNode = nodeMap.get(parentNode.parent); let db = e.target.result
node.rawParent = node.parent; // 数据库是否存在
node.parent = parentNode.parent; if (!db.objectStoreNames.contains('LogStore')) {
node.parentTitle = parentNode.title; resolve('Database does not exist.')
node.parentIconIndex = parentNode.iconIndex; return
grandParentNode.children.push(node)
} else if (keyMap.ignoreKeys.includes(item[keyMap.key])) {
//
} }
else if (parentNode) { let transaction = db.transaction('LogStore')
node.parentTitle = parentNode.title; let store = transaction.objectStore('LogStore')
node.parentIconIndex = parentNode.iconIndex; let request = store.getAll()
parentNode.children.push(node) request.onerror = function (e) {
} else { reject('Error getting all records.')
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) 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,588 +0,0 @@
import { isEmpty } from '@haina/utils-commons';
/**
*
*/
/**
* 数据库版本
* ! 每次涉及indexedDB的更新都要往上+1
* @type {number}
*/
const INDEXED_DB_VERSION = 6;
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, keySet = {keyPath: 'key' }) => {
var open = indexedDB.open(database, INDEXED_DB_VERSION)
// console.trace('createIndexedDBStore');
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, keySet)
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 store = openRequest.transaction.objectStore(table)
if (!store.indexNames.contains('timestamp')) {
store.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' }) {
createIndexedDBStore(storeNames, database, keySet);
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,125 +1,53 @@
import { loadScript } from '@haina/utils-commons' import { loadScript, readWebsocketLog } from '@/utils/commons'
import { fetchJSON } from '@haina/utils-request'
import { readWebsocketLog } from '@/utils/indexedDB'
import { BUILD_VERSION, BUILD_DATE } from '@/config' import { BUILD_VERSION, BUILD_DATE } from '@/config'
/** export const loadPageSpy = (title) => {
* @deprecated if (import.meta.env.DEV || window.$pageSpy) return
*/
// export const loadPageSpy = (title) => { const PageSpyConfig = { api: 'page-spy.mycht.cn', project: 'Sales CRM', title: title + '(v' + BUILD_VERSION + ')', autoRender: false, offline: true }
// if (import.meta.env.DEV || window.$pageSpy) return
const PageSpySrc = [
// const PageSpyConfig = { api: 'page-spy.mycht.cn', project: 'Sales CRM', title: title + '(v' + BUILD_VERSION + ')', autoRender: false, offline: true } 'https://page-spy.mycht.cn/page-spy/index.min.js' + `?${BUILD_DATE}`,
'https://page-spy.mycht.cn/plugin/data-harbor/index.min.js' + `?${BUILD_DATE}`,
// const PageSpySrc = [ 'https://page-spy.mycht.cn/plugin/rrweb/index.min.js' + `?${BUILD_DATE}`,
// 'https://page-spy.mycht.cn/page-spy/index.min.js' + `?${BUILD_DATE}`, ]
// 'https://page-spy.mycht.cn/plugin/data-harbor/index.min.js' + `?${BUILD_DATE}`, Promise.all(PageSpySrc.map((src) => loadScript(src))).then(() => {
// 'https://page-spy.mycht.cn/plugin/rrweb/index.min.js' + `?${BUILD_DATE}`, // 注册插件
// ] window.$harbor = new DataHarborPlugin()
// Promise.all(PageSpySrc.map((src) => loadScript(src))).then(() => { window.$rrweb = new RRWebPlugin()
// // 注册插件 ;[window.$harbor, window.$rrweb].forEach((p) => {
// window.$harbor = new DataHarborPlugin() PageSpy.registerPlugin(p)
// window.$rrweb = new RRWebPlugin() })
// ;[window.$harbor, window.$rrweb].forEach((p) => { window.$pageSpy = new PageSpy(PageSpyConfig)
// PageSpy.registerPlugin(p)
// }) // PageSpy.registerPlugin(new DataHarborPlugin());
// window.$pageSpy = new PageSpy(PageSpyConfig) // PageSpy.registerPlugin(new RRWebPlugin());
// 实例化 PageSpy
// // PageSpy.registerPlugin(new DataHarborPlugin()); // window.$pageSpy = new PageSpy({ api: 'page-spy.mycht.cn', project: 'Sales CRM', title: title + '(v' + BUILD_VERSION + ')', autoRender: false, offline: true, });
// // PageSpy.registerPlugin(new RRWebPlugin()); console.log('[PageSpy]', window.$pageSpy.version)
// // 实例化 PageSpy // window.addEventListener('beforeunload', (e) => {
// // window.$pageSpy = new PageSpy({ api: 'page-spy.mycht.cn', project: 'Sales CRM', title: title + '(v' + BUILD_VERSION + ')', autoRender: false, offline: true, }); // e.preventDefault() // If you prevent default behavior in Mozilla Firefox
// console.log('[PageSpy]', window.$pageSpy.version) // e.returnValue = '' // Chrome requires returnValue to be set
// // window.addEventListener('beforeunload', (e) => {
// // e.preventDefault() // If you prevent default behavior in Mozilla Firefox // window.$harbor.upload({ clearCache: false, remark: '自动上传' }) // 上传日志 { clearCache: true, remark: '' }
// // e.returnValue = '' // Chrome requires returnValue to be set // })
window.onerror = async function (msg, url, lineNo, columnNo, error) {
// // window.$harbor.upload({ clearCache: false, remark: '自动上传' }) // 上传日志 { clearCache: true, remark: '' } await readWebsocketLog()
// // }) // 上传最近 3 分钟的日志
// window.onerror = async function (msg, url, lineNo, columnNo, error) { const now = Date.now()
// await readWebsocketLog() await window.$harbor.uploadPeriods({
// // 上传最近 3 分钟的日志 startTime: now - 3 * 60000,
// const now = Date.now() endTime: now,
// await window.$harbor.uploadPeriods({ remark: `\`onerror\`自动上传. ${msg}`,
// startTime: now - 3 * 60000, })
// endTime: now,
// remark: `\`onerror\`自动上传. ${msg}`,
// })
// }
// })
// }
/**
* @deprecated
*/
// export const uploadPageSpyLog = async () => {
// // window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
// // if (window.$pageSpy) {
// // await window.$harbor.upload() // 上传日志 { clearCache: true, remark: '' }
// // }
// if (import.meta.env.DEV) return true;
// if (window.$pageSpy) {
// try {
// await readWebsocketLog()
// // await window.$harbor.upload() // 上传日志 { clearCache: true, remark: '' }
// // 上传最近 1 小时的日志, 直接upload 所有日志: 413 Payload Too Large
// const now = Date.now();
// await window.$harbor.uploadPeriods({
// startTime: now - 60 * 60000,
// endTime: now,
// });
// return true;
// } catch (error) {
// return false;
// }
// } else {
// return false;
// }
// }
export const sendNotify = async (message) => {
const notifyUrl = 'https://p9axztuwd7x8a7.mycht.cn/dingtalk/dingtalkwork/SendMDMsgByDingRobotToGroup';
const params = {
groupid: 'cidFtzcIzNwNoiaGU9Q795CIg==',
msgTitle: '有人求助',
msgText: `${message}\\n\\nSales CRM (${BUILD_VERSION})`,
};
return fetchJSON(notifyUrl, params).then((json) => {
if (json.errcode === 0) {
console.info('发送通知成功');
} else {
throw new Error(json?.errmsg + ': ' + json.errcode);
} }
}); })
}; }
/** export const uploadPageSpyLog = async () => {
* @deprecated await readWebsocketLog()
*/ // window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
// const uploadLog = async () => { if (window.$pageSpy) {
// await readWebsocketLog() await window.$harbor.upload() // 上传日志 { clearCache: true, remark: '' }
// if (window.$pageSpy) { }
// // window.$pageSpy.triggerPlugins('onOfflineLog', 'upload') }
// try {
// // await window.$harbor.upload() // 上传日志 { clearCache: true, remark: '' }
// // 上传最近 1 小时的日志, 直接upload 所有日志: 413 Payload Too Large
// const now = Date.now()
// await window.$harbor.uploadPeriods({
// startTime: now - 60 * 60000,
// endTime: now,
// })
// messageApi.info('Success')
// // clearWebsocketLog()
// sendNotify()
// } catch (error) {
// messageApi.error('Failure')
// }
// } else {
// messageApi.error('Failure')
// }
// }

@ -1,10 +1,6 @@
import { BUILD_VERSION } from '@/config' import { BUILD_VERSION } from '@/config'
console.warn('Warning: `request.js` is deprecated and will be removed in next version.');
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const customHeaders = [] const customHeaders = []
// 添加 HTTP Reuqest 自定义头部 // 添加 HTTP Reuqest 自定义头部

@ -6,37 +6,39 @@ import {
App as AntApp, App as AntApp,
ConfigProvider, ConfigProvider,
Empty, Empty,
Modal, FloatButton, Modal,
theme message,
FloatButton,
theme,
} from 'antd' } from 'antd'
import { CustomerServiceOutlined } from '@ant-design/icons' import { BugOutlined, CustomerServiceOutlined } from '@ant-design/icons'
import zhLocale from 'antd/locale/zh_CN' import zhLocale from 'antd/locale/zh_CN'
import 'dayjs/locale/zh-cn' import 'dayjs/locale/zh-cn'
import { useEffect } from 'react' import { useEffect } from 'react'
import { Outlet, useHref, useNavigate } from 'react-router-dom' import { Outlet, useHref, useNavigate } from 'react-router-dom'
import { appendRequestHeader } from '@haina/utils-request' import { appendRequestHeader } from '@/utils/request'
import { loadPageSpy } from '@haina/utils-pagespy' import { loadPageSpy } from '@/utils/pagespy'
import AppLogo from '@/assets/highlights_travel_300_300.png' import AppLogo from '@/assets/highlights_travel_300_300.png'
import '@/assets/App.css' import '@/assets/App.css'
import 'react-chat-elements/dist/main.css' import 'react-chat-elements/dist/main.css'
import EmailFetch from './Conversations/Online/Components/EmailFetch' import EmailFetch from './Conversations/Online/Components/EmailFetch'
import FetchEmailWorker from './../workers/fetchEmailWorker?worker&url' import FetchEmailWorker from './../workers/fetchEmailWorker?worker&url'
import { clearWebsocketLog, readWebsocketLog } from '@/utils/commons'
import { useGlobalNotify } from '@/hooks/useGlobalNotify' import { useGlobalNotify } from '@/hooks/useGlobalNotify'
import GeneratePaymentDrawer from './Conversations/Online/Components/GeneratePaymentDrawer'
import GenerateAutoDocDrawer from './Conversations/Online/Components/GenerateAutoDocDrawer'
import GenerateShorturlDrawer from './Conversations/Online/Components/GenerateShorturlDrawer'
import LogUploader from '@/components/LogUploader'
import { BUILD_VERSION } from '@/config'
// const fetchEmailWorkerURL = new URL('/src/workers/fetchEmailWorker.js', import.meta.url);
const fetchEmailWorker = new Worker(FetchEmailWorker, { type: 'module' }); const fetchEmailWorker = new Worker(FetchEmailWorker, { type: 'module' });
function AuthApp() { function AuthApp() {
const navigate = useNavigate() const navigate = useNavigate()
const [messageApi, contextHolder] = message.useMessage()
const { colorPrimary, borderRadius } = useThemeContext() const { colorPrimary, borderRadius } = useThemeContext()
const [loginUser] = useAuthStore((state) => [ const [loginUser, sendNotify] = useAuthStore((state) => [
state.loginUser state.loginUser, state.sendNotify
]) ])
const href = useHref() const href = useHref()
@ -57,7 +59,7 @@ function AuthApp() {
let _fetchEmailWorker; let _fetchEmailWorker;
if (loginUser.userId > 0) { if (loginUser.userId > 0) {
appendRequestHeader('X-User-Id', loginUser.userId) appendRequestHeader('X-User-Id', loginUser.userId)
loadPageSpy(loginUser.username + '(v' + BUILD_VERSION + ')', 'Sales CRM', true) loadPageSpy(loginUser.username)
connectWebsocket(loginUser.userId) connectWebsocket(loginUser.userId)
fetchInitialData(loginUser) fetchInitialData(loginUser)
@ -86,6 +88,29 @@ function AuthApp() {
return fetchEmailWorker; return fetchEmailWorker;
} }
const uploadLog = async () => {
await readWebsocketLog()
if (window.$pageSpy) {
// window.$pageSpy.triggerPlugins('onOfflineLog', 'upload')
try {
// await window.$harbor.upload() // { clearCache: true, remark: '' }
// 1 , upload : 413 Payload Too Large
const now = Date.now()
await window.$harbor.uploadPeriods({
startTime: now - 60 * 60000,
endTime: now,
})
messageApi.info('Success')
clearWebsocketLog()
sendNotify()
} catch (error) {
messageApi.error('Failure')
}
} else {
messageApi.error('Failure')
}
}
// /p... // /p...
const needToLogin = loginUser.userId === -1 && href.indexOf('/p/') === -1 const needToLogin = loginUser.userId === -1 && href.indexOf('/p/') === -1
@ -124,19 +149,18 @@ function AuthApp() {
<ErrorBoundary> <ErrorBoundary>
<FloatButton.Group <FloatButton.Group
shape='square' shape='square'
placement={'left'}
trigger={floatTrigger} trigger={floatTrigger}
style={{ style={{
insetInlineEnd: floatButtonLineEnd, insetInlineEnd: floatButtonLineEnd,
insetBlockEnd: floatButtonLineEnd, insetBlockEnd: floatButtonLineEnd,
flexDirection: 'row',
}} }}
icon={<CustomerServiceOutlined />} icon={<CustomerServiceOutlined />}
> >
<EmailFetch /> <EmailFetch />
<LogUploader /> <FloatButton icon={<BugOutlined />} tooltip={<div>上传日志给研发部</div>} onClick={() => uploadLog()} />
<FloatButton.BackTop /> <FloatButton.BackTop />
</FloatButton.Group> </FloatButton.Group>
{contextHolder}
{needToLogin ? <>login...</> : <Outlet />} {needToLogin ? <>login...</> : <Outlet />}
<dialog id="about-dialog" className="border-0"> <dialog id="about-dialog" className="border-0">
<img className="logo" src={AppLogo} alt="logo" /> <img className="logo" src={AppLogo} alt="logo" />
@ -161,9 +185,6 @@ function AuthApp() {
</button> </button>
</form> </form>
</dialog> </dialog>
<GeneratePaymentDrawer />
<GenerateAutoDocDrawer />
<GenerateShorturlDrawer />
</ErrorBoundary> </ErrorBoundary>
</AntApp> </AntApp>
</ConfigProvider> </ConfigProvider>

@ -2,7 +2,7 @@ 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, Alert } from "antd";
import { PhoneOutlined, CustomerServiceOutlined, AudioOutlined } from "@ant-design/icons"; import { PhoneOutlined, CustomerServiceOutlined, AudioOutlined } from "@ant-design/icons";
import { useParams, useHref, useNavigate } from "react-router-dom"; import { useParams, useHref, useNavigate } from "react-router-dom";
import { isEmpty } from "@haina/utils-commons"; import { isEmpty } from "@/utils/commons";
import callCenterStore from "@/stores/CallCenterStore"; import callCenterStore from "@/stores/CallCenterStore";
import useAuthStore from "@/stores/AuthStore"; import useAuthStore from "@/stores/AuthStore";

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

@ -6,7 +6,7 @@ import ConversationsList from './Conversations/History/ConversationsList';
import MessagesMatchList from './Conversations/History/MessagesMatchList'; import MessagesMatchList from './Conversations/History/MessagesMatchList';
import MessagesList from './Conversations/History/MessagesList'; import MessagesList from './Conversations/History/MessagesList';
import ImageAlbumPreview from './Conversations/History/ImageAlumPreview'; import ImageAlbumPreview from './Conversations/History/ImageAlumPreview';
import { flush, pick } from '@haina/utils-commons'; import { flush, pick } from '@/utils/commons';
import { fetchConversationsSearch, fetchConversationsUnassigned } from '@/actions/ConversationActions'; import { fetchConversationsSearch, fetchConversationsUnassigned } from '@/actions/ConversationActions';
const { Sider, Content } = Layout; const { Sider, Content } = Layout;

@ -1,36 +1,27 @@
import { useState } from 'react' import { useEffect, useState } from 'react';
import { Layout, Empty, Button } from 'antd' import { Layout, Spin, Button } from 'antd';
import { RightOutlined, LeftOutlined } from '@ant-design/icons' import { RightCircleOutlined, RightOutlined, ReloadOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import MessagesHeader from './Conversations/Online/MessagesHeader' // import { useParams, useNavigate } from 'react-router-dom';
import MessagesWrapper from './Conversations/Online/MessagesWrapper' import MessagesHeader from './Conversations/Online/MessagesHeader';
import ConversationsList from './Conversations/Online/ConversationsList' import MessagesWrapper from './Conversations/Online/MessagesWrapper';
import OrderProfile from '@/components/OrderProfile' import InputComposer from './Conversations/Online/Input/InputComposer';
import useAuthStore from '@/stores/AuthStore' import ConversationsList from './Conversations/Online/ConversationsList';
import ReplyWrapper from './Conversations/Online/ReplyWrapper' import CustomerProfile from './Conversations/Online/order/CustomerProfile';
import useConversationStore from '@/stores/ConversationStore' // import { useAuthContext } from '@/stores/AuthContext';
import { useShallow } from 'zustand/react/shallow' // import useConversationStore from '@/stores/ConversationStore';
import ReplyWrapper from './Conversations/Online/ReplyWrapper';
import ConversationBind from '@/views/Conversations/Online/ConversationBind' import './Conversations/Conversations.css';
import './Conversations/Conversations.css'
import EmailEditorPopup from './Conversations/Online/Input/EmailEditorPopup'
const { Sider, Content, Header, Footer } = Layout const { Sider, Content, Header, Footer } = Layout;
/**
*
*/
const ChatWindow = () => { const ChatWindow = () => {
const [collapsedRight, setCollapsedRight] = useState(false)
const loginUser = useAuthStore((state) => state.loginUser) const [collapsedLeft, setCollapsedLeft] = useState(false);
const currentOrder = useConversationStore(useShallow((state) => state.currentConversation?.coli_sn || '')) const [collapsedRight, setCollapsedRight] = useState(false);
const currentConversationID = useConversationStore(useShallow((state) => state.currentConversation?.sn || ''))
const [updateCurrentConversation] = useConversationStore((state) => [state.updateCurrentConversation])
const renderEmptyOrder = () => {
return (
<Empty description={<span>没有订单关联</span>}>
<ConversationBind currentConversationID={currentConversationID} userId={loginUser.userId} onBoundSuccess={(coli_sn) => updateCurrentConversation({ coli_sn })} />
</Empty>
)
}
return ( return (
<> <>
@ -46,7 +37,7 @@ const ChatWindow = () => {
collapsed={false} collapsed={false}
onBreakpoint={(broken) => { onBreakpoint={(broken) => {
// setCollapsedLeft(broken) // setCollapsedLeft(broken)
// setCollapsedRight(broken) setCollapsedRight(broken)
}} }}
trigger={null}> trigger={null}>
<ConversationsList /> <ConversationsList />
@ -58,9 +49,9 @@ const ChatWindow = () => {
{/* <Button type='text' icon={collapsedLeft ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} onClick={() => setCollapsedLeft(!collapsedLeft)} className=' rounded-none rounded-l' /> */} {/* <Button type='text' icon={collapsedLeft ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} onClick={() => setCollapsedLeft(!collapsedLeft)} className=' rounded-none rounded-l' /> */}
<MessagesHeader /> <MessagesHeader />
{/* <Button type='text' icon={<ReloadOutlined />} onClick={() => setCollapsedRight(!collapsedRight)} className='' title='最新消息记录' /> */} {/* <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> </Header>
<Content className='flex-grow bg-whatsapp-bg relative'> <Content className="flex-grow bg-whatsapp-bg relative" >
<MessagesWrapper /> <MessagesWrapper />
</Content> </Content>
<Footer className='ant-layout-sider-light p-0'> <Footer className='ant-layout-sider-light p-0'>
@ -81,12 +72,11 @@ const ChatWindow = () => {
collapsedWidth={0} collapsedWidth={0}
trigger={null} trigger={null}
collapsed={collapsedRight}> collapsed={collapsedRight}>
<OrderProfile coliSN={currentOrder} renderEmpty={renderEmptyOrder} /> <CustomerProfile />
</Sider> </Sider>
</Layout> </Layout>
<EmailEditorPopup key='email-editor-online' />
</> </>
) );
} };
export default ChatWindow export default ChatWindow;

@ -1,6 +1,6 @@
import { createContext, useContext, useEffect, useState } from 'react'; import { createContext, useContext, useEffect, useState } from 'react';
import { App } from 'antd'; import { App } from 'antd';
import { calcCacheSizes, clearAllCaches } from '@haina/utils-commons'; import { calcCacheSizes, clearAllCaches } from '@/utils/commons';
const ClearCache = (props) => { const ClearCache = (props) => {
const { message } = App.useApp(); const { message } = App.useApp();

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

@ -1,16 +1,14 @@
import { useRef, useEffect, useState, forwardRef, memo } from 'react'; 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 { LoadingOutlined } from '@ant-design/icons';
import { MessageBox } from 'react-chat-elements'; import { MessageBox } from 'react-chat-elements';
import { MESSAGE_PAGE_SIZE, fetchMessagesHistory } from '@/actions/ConversationActions'; import { MESSAGE_PAGE_SIZE, fetchMessagesHistory } from '@/actions/ConversationActions';
import useFormStore from '@/stores/FormStore'; import useFormStore from '@/stores/FormStore';
import { isEmpty, stringToColour, groupBy, isNotEmpty, TagColorStyle } from '@haina/utils-commons'; import { isEmpty, stringToColour, groupBy, isNotEmpty } from '@/utils/commons';
import { useShallow } from 'zustand/react/shallow'; import { useShallow } from 'zustand/react/shallow';
import MergeConversationTo from './MergeConversationTo'; import MergeConversationTo from './MergeConversationTo';
import BubbleIM from '../Online/Components/BubbleIM'; import BubbleIM from '../Online/Components/BubbleIM';
import BubbleEmail from '../Online/Components/BubbleEmail'; import BubbleEmail from '../Online/Components/BubbleEmail';
import { ERROR_IMG, POPUP_FEATURES } from '@/config';
import { parseSimpleMarkdown } from '@/channel/bubbleMsgUtils';
const BIG_PAGE_SIZE = MESSAGE_PAGE_SIZE * 20; const BIG_PAGE_SIZE = MESSAGE_PAGE_SIZE * 20;
const MessagesList = ({ ...listProps }) => { const MessagesList = ({ ...listProps }) => {
@ -21,7 +19,6 @@ const MessagesList = ({ ...listProps }) => {
const [paramsForMsgList, setParamsForMsgList] = useFormStore((state) => [state.msgListParams, state.setMsgListParams]); const [paramsForMsgList, setParamsForMsgList] = useFormStore((state) => [state.msgListParams, state.setMsgListParams]);
const [selectMatch, setSelectedMatch] = useFormStore((state) => [state.msgHistorySelectMatch, state.setMsgHistorySelectMatch]); const [selectMatch, setSelectedMatch] = useFormStore((state) => [state.msgHistorySelectMatch, state.setMsgHistorySelectMatch]);
const [setImageAlbumList, setImagePreviewSrc] = useFormStore(useShallow((state) => [state.setImageAlbum, state.setImagePreviewSrc])); const [setImageAlbumList, setImagePreviewSrc] = useFormStore(useShallow((state) => [state.setImageAlbum, state.setImagePreviewSrc]));
const [ setEmailList] = useFormStore(useShallow((state) => [ state.setEmailList]));
const [chatItemMessages, setChatItemMessages] = useState([]); const [chatItemMessages, setChatItemMessages] = useState([]);
const [messageListPreLoading, setMessageListPreLoading] = useState(false); const [messageListPreLoading, setMessageListPreLoading] = useState(false);
@ -112,8 +109,6 @@ const MessagesList = ({ ...listProps }) => {
// setParamsForMsgList({ pretime: chatItemMessages[0].msgtime, lasttime: chatItemMessages[chatItemMessages.length - 1].msgtime }); // 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); const album = chatItemMessages.filter((ele) => ele.whatsapp_msg_type === 'image').map((ele) => ele.data.uri);
setImageAlbumList(album); 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 () => {}; return () => {};
}, [chatItemMessages]); }, [chatItemMessages]);
@ -149,27 +144,6 @@ const MessagesList = ({ ...listProps }) => {
setFocusMsg(id); setFocusMsg(id);
} }
}; };
// Render parsed tokens to React elements
const renderMDTokens = (tokens) => {
return tokens.map((token, index) => {
switch (token.type) {
case 'text':
return <span key={index}>{token.content}</span>;
case 'bold':
return <b key={index}>{renderMDTokens(token.content)}</b>;
case 'italic':
return <i key={index}>{renderMDTokens(token.content)}</i>;
case 'url':
return (
<a key={index} href={token.content} target='_blank' rel='noopener noreferrer' className=' underline text-sm'>
{token.content}
</a>
)
default:
return <span key={index}>{token.content}</span>;
}
});
};
const RenderText = memo(function renderText({ str, className, template }) { const RenderText = memo(function renderText({ str, className, template }) {
let headerObj, footerObj, buttonsArr; let headerObj, footerObj, buttonsArr;
@ -179,12 +153,27 @@ const MessagesList = ({ ...listProps }) => {
footerObj = componentsObj?.footer?.[0]; footerObj = componentsObj?.footer?.[0];
buttonsArr = componentsObj?.buttons?.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})/gmu).filter((s) => s !== '');
const links = str.match(/https?:\/\/[^\s()]+/gi) || [];
const emojis = str.match(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g) || [];
const extraClass = isEmpty(emojis) ? '' : '';
const objArr = parts.reduce((prev, curr, index) => {
if (links.includes(curr)) {
prev.push({ type: 'link', key: curr });
} else if (emojis.includes(curr)) {
prev.push({ type: 'emoji', key: curr });
} else {
prev.push({ type: 'text', key: curr });
}
return prev;
}, []);
return ( return (
<span className={`text-sm leading-5 emoji-text whitespace-pre-wrap ${className} `} key={'msg-text'}> <span className={`text-sm leading-5 emoji-text whitespace-pre-wrap ${className} ${extraClass} `} key={'msg-text'}>
{headerObj ? ( {headerObj ? (
<div className='text-neutral-500 text-center'> <div className='text-neutral-500 text-center'>
{'text' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <div>{headerObj.text}</div>} {'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()) && ( {['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'> <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;] [&nbsp;{headerObj.parameters[0].type}&nbsp;]
@ -192,7 +181,17 @@ const MessagesList = ({ ...listProps }) => {
)} )}
</div> </div>
) : null} ) : null}
{renderMDTokens(parseSimpleMarkdown(str))} {(objArr || []).map((part, index) => {
if (part.type === 'link') {
return (
<a href={part.key} target='_blank' key={`${part.key}${index}`} rel='noreferrer' className='text-sm'>
{part.key}
</a>
);
} else {
return part.key;
}
})}
</span> </span>
); );
}); });
@ -212,7 +211,7 @@ const MessagesList = ({ ...listProps }) => {
return false; return false;
case 'document': 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; return false;
default: default:
@ -286,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'}}> <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 <span
className={`p-1 rounded-b ${message.msg_direction === 'outbound' ? 'text-white' : ''} `} 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} {message.msg_direction === 'outbound' ? selectedConversation.OPI_Name : message.senderName}
</span> </span>
<span>{message.dateString || message.localDate}</span> <span>{message.dateString || message.localDate}</span>

@ -1,6 +1,6 @@
import { ChatItem } from 'react-chat-elements'; import { ChatItem } from 'react-chat-elements';
import useFormStore from '@/stores/FormStore'; import useFormStore from '@/stores/FormStore';
import { isNotEmpty } from '@haina/utils-commons'; import { isNotEmpty } from '@/utils/commons';
const MessagesMatchList = ({ ...props }) => { const MessagesMatchList = ({ ...props }) => {
const [formValues] = useFormStore((state) => [state.chatHistoryForm]); const [formValues] = useFormStore((state) => [state.chatHistoryForm]);

@ -2,7 +2,7 @@
import { memo } from 'react'; import { memo } from 'react';
import { Form, Flex, Input, Button, DatePicker, Select } from 'antd'; import { Form, Flex, Input, Button, DatePicker, Select } from 'antd';
import SearchInput from '@/components/SearchInput'; import SearchInput from '@/components/SearchInput';
import { isNotEmpty } from '@haina/utils-commons'; import { isNotEmpty } from '@/utils/commons';
import { fetchSalesAgentWithDD as fetchSalesAgent, fetchCustomerList } from '@/actions/CommonActions'; import { fetchSalesAgentWithDD as fetchSalesAgent, fetchCustomerList } from '@/actions/CommonActions';
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
@ -40,13 +40,13 @@ const SearchForm = memo(function ({ initialValues, onSubmit, onReset }) {
<Input placeholder='关键词' allowClear /> <Input placeholder='关键词' allowClear />
</Form.Item> </Form.Item>
<Form.Item label='消息渠道' name='mchannel' className='w-52'> <Form.Item label='消息渠道' name='mchannel' className='w-52'>
<Select maxTagCount={0} allowClear options={[ <Select mode='multiple' maxTagCount={0} allowClear options={[
{ key: 'WABA', label: 'WA商业号', value: 'WABA' }, { key: 'waba', label: 'WA商业号', value: 'waba' },
{ key: 'email', label: '邮件', value: 'email' }, { key: 'email', label: '邮件', value: 'email' },
{ key: 'wai', label: 'WhatsApp', value: 'wai' }, { key: 'whatsapp', label: 'WhatsApp', value: 'whatsapp' },
]} className='w-8' /> ]} className='w-8' />
</Form.Item> </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={[ <Select mode='multiple' maxTagCount={0} allowClear options={[
{ key: 'image', label: '图片', value: 'image' }, { key: 'image', label: '图片', value: 'image' },
{ key: 'video', label: '视频', value: 'video' }, { key: 'video', label: '视频', value: 'video' },
@ -54,10 +54,10 @@ const SearchForm = memo(function ({ initialValues, onSubmit, onReset }) {
{ key: 'file', label: '文件', value: 'file' }, { key: 'file', label: '文件', value: 'file' },
{ key: 'email', label: '邮件', value: 'email' }, { key: 'email', label: '邮件', value: 'email' },
]} className='w-8' /> ]} className='w-8' />
</Form.Item> */} </Form.Item>
<Form.Item label='日期' name='msgDateRange'> <Form.Item label='日期' name='msgDateRange'>
<RangePicker format={'YYYY-MM-DD'} /> <RangePicker format={'YYYY-MM-DD'} />
</Form.Item> </Form.Item>
</Flex> </Flex>
<div style={{ flex: '0 1 64px' }} className='flex justify-between'> <div style={{ flex: '0 1 64px' }} className='flex justify-between'>

@ -2,7 +2,7 @@ import { memo } from 'react';
import { App } from 'antd'; import { App } from 'antd';
import { MailOutlined } from '@ant-design/icons'; import { MailOutlined } from '@ant-design/icons';
import { MessageBox } from 'react-chat-elements'; import { MessageBox } from 'react-chat-elements';
import { isEmpty, } from '@haina/utils-commons'; import { isEmpty, } from '@/utils/commons';
import { useEmailDetail, } from '@/hooks/useEmail'; import { useEmailDetail, } from '@/hooks/useEmail';
const BubbleEmail = ({ onOpenEditor, onOpenEmail, ...message }) => { const BubbleEmail = ({ onOpenEditor, onOpenEmail, ...message }) => {
@ -56,11 +56,11 @@ const BubbleEmail = ({ onOpenEditor, onOpenEmail, ...message }) => {
<> <>
<b>From: </b> <b>From: </b>
<span> <span>
{/* {message?.emailOrigin?.fromName}&nbsp;&lt;{message?.emailOrigin.fromEmail}&gt; */}
{message.msgOrigin?.from} {message.msgOrigin?.from}
</span> </span>
</> : <><b>To: </b>{message.msgOrigin?.to}</> </> : <><b>To: </b>{message.msgOrigin?.to}</>
} }
{/* <b>Subject: </b>{message.msgOrigin.email.subject} */}
</span> </span>
</> </>
} }

@ -1,14 +1,12 @@
import { memo } from 'react'; import { memo } from 'react';
import { App, Button, Image } from 'antd'; import { App, Button } from 'antd';
import { ExportOutlined, CopyOutlined, PhoneOutlined } from '@ant-design/icons'; import { ExportOutlined, CopyOutlined, PhoneOutlined } from '@ant-design/icons';
import { MessageBox } from 'react-chat-elements'; import { MessageBox } from 'react-chat-elements';
import { groupBy, isEmpty, TagColorStyle } from '@haina/utils-commons'; import { groupBy, isEmpty, TagColorStyle } from '@/utils/commons';
import { parseSimpleMarkdown } from '@/channel/bubbleMsgUtils';
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import { useShallow } from 'zustand/react/shallow'; import { useShallow } from 'zustand/react/shallow';
import { ReplyIcon } from '@/components/Icons'; import { ReplyIcon } from '@/components/Icons';
import ChannelLogo from './ChannelLogo'; import ChannelLogo from './ChannelLogo';
import { ERROR_IMG } from '@/config';
const outboundStyle = { const outboundStyle = {
'waba': { color: '#ccd4ae' }, 'waba': { color: '#ccd4ae' },
@ -24,34 +22,6 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
setNewChatModalVisible(true); setNewChatModalVisible(true);
setNewChatFormValues((prev) => ({ ...prev, phone_number: wa_id, name: wa_name })); setNewChatFormValues((prev) => ({ ...prev, phone_number: wa_id, name: wa_name }));
}; };
// Render parsed tokens to React elements
const renderMDTokens = (tokens) => {
return tokens.map((token, index) => {
switch (token.type) {
case 'text':
return <span key={index}>{token.content}</span>
case 'bold':
return <b key={index}>{renderMDTokens(token.content)}</b>
case 'italic':
return <i key={index}>{renderMDTokens(token.content)}</i>
case 'url':
return (
<a key={index} href={token.content} target='_blank' rel='noopener noreferrer' className=' underline text-sm'>
{token.content}
</a>
)
case 'number':
return (
<a key={`${index}`} className='text-sm ' onClick={() => openNewChatModal({ wa_id: token.content, wa_name: token.content })}>
{token.content}
</a>
)
default:
return <span key={index}>{token.content}</span>
}
})
};
const RenderText = memo(function renderText({ str, className, template, message }) { const RenderText = memo(function renderText({ str, className, template, message }) {
let headerObj, footerObj, buttonsArr; let headerObj, footerObj, buttonsArr;
if (!isEmpty(template) && !isEmpty(template.components)) { if (!isEmpty(template) && !isEmpty(template.components)) {
@ -61,12 +31,30 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
buttonsArr = componentsObj?.button; // ?.reduce((r, c) => r.concat(c.buttons), []); buttonsArr = componentsObj?.button; // ?.reduce((r, c) => r.concat(c.buttons), []);
} }
const parts = str.split(/(https?:\/\/[^\s()]+|\p{Emoji_Presentation}|\d{4,})/gmu).filter((s) => s !== '');
const links = str.match(/https?:\/\/[^\s()]+/gi) || [];
const numbers = str.match(/\d{4,}/g) || [];
const emojis = str.match(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g) || [];
const extraClass = isEmpty(emojis) ? '' : '';
const objArr = parts.reduce((prev, curr, index) => {
if (links.includes(curr)) {
prev.push({ type: 'link', key: curr });
} else if (numbers.includes(curr)) {
prev.push({ type: 'number', key: curr });
} else if (emojis.includes(curr)) {
prev.push({ type: 'emoji', key: curr });
} else {
prev.push({ type: 'text', key: curr });
}
return prev;
}, []);
return ( return (
<div className={`text-sm leading-5 emoji-text whitespace-pre-wrap ${className}`} key={'msg-text'}> <span className={`text-sm leading-5 emoji-text whitespace-pre-wrap ${className} ${extraClass}`} key={'msg-text'}>
{headerObj ? ( {headerObj ? (
<div className='text-neutral-500 text-center'> <div className='text-neutral-500 text-center'>
{'text' === (headerObj?.parameters?.[0]?.type || '').toLowerCase() && <div>{headerObj.text}</div>} {'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()) && ( {['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'> <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;] [&nbsp;{headerObj.parameters[0].type}&nbsp;]
@ -74,7 +62,24 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
)} )}
</div> </div>
) : null} ) : null}
{renderMDTokens(parseSimpleMarkdown(str))} {(objArr || []).map((part, index) => {
if (part.type === 'link') {
return (
<a href={part.key} target='_blank' key={`${part.key}${index}`} rel='noreferrer' className='text-sm'>
{part.key}
</a>
)
} else if (part.type === 'number') {
return (
<a key={`${part.key}${index}`} className='text-sm' onClick={() => openNewChatModal({ wa_id: part.key, wa_name: part.key })}>
{part.key}
</a>
)
} else {
// if (part.type === 'emoji')
return part.key
}
})}
{footerObj ? <div className=' text-neutral-500'>{footerObj.text}</div> : null} {footerObj ? <div className=' text-neutral-500'>{footerObj.text}</div> : null}
{buttonsArr && buttonsArr.length > 0 ? ( {buttonsArr && buttonsArr.length > 0 ? (
<div className='flex flex-row gap-1'> <div className='flex flex-row gap-1'>
@ -95,7 +100,7 @@ const BubbleIM = ({ handlePreview, handleContactClick, setNewChatModalVisible, s
)} )}
</div> </div>
) : null} ) : null}
</div> </span>
) )
}); });
return ( return (

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

@ -5,7 +5,7 @@ import { CloseCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { fetchConversationItemClose, fetchConversationsSearch, fetchConversationItemUnread, fetchConversationItemTop, postConversationTags, deleteConversationTags, fetchCleanUnreadMsgCount } from '@/actions/ConversationActions'; import { fetchConversationItemClose, fetchConversationsSearch, fetchConversationItemUnread, fetchConversationItemTop, postConversationTags, deleteConversationTags, fetchCleanUnreadMsgCount } from '@/actions/ConversationActions';
import { ChatItem } from 'react-chat-elements'; import { ChatItem } from 'react-chat-elements';
// import ConversationsNewItem from './ConversationsNewItem'; // import ConversationsNewItem from './ConversationsNewItem';
import { flush, isEmpty, isNotEmpty, stringToColour, TagColorStyle } from '@haina/utils-commons'; import { flush, isEmpty, isNotEmpty, stringToColour, TagColorStyle } from '@/utils/commons';
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import useAuthStore from '@/stores/AuthStore'; import useAuthStore from '@/stores/AuthStore';
import ChannelLogo from './ChannelLogo'; import ChannelLogo from './ChannelLogo';
@ -230,7 +230,7 @@ const ChatListItem = (({item, refreshConversationList,setListUpdateFlag,onSwitch
{ label: '编辑联系人', key: 'edit0' }, { label: '编辑联系人', key: 'edit0' },
{ type: 'divider' }, { type: 'divider' },
{ label: '移到🗂隐藏列表', key: 'close', danger: true }, { label: '移到🗂已处理', key: 'close', danger: true },
], ],
triggerSubMenuAction: 'click', triggerSubMenuAction: 'click',
openKeys: openTags, openKeys: openTags,

@ -1,25 +1,20 @@
import { useState } from 'react' 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 { ApiOutlined } from '@ant-design/icons'
import { isEmpty, cloneDeep } from '@haina/utils-commons' import { isEmpty, cloneDeep } from '@/utils/commons'
import { fetchJSON } from '@haina/utils-request' import { fetchJSON } from '@/utils/request'
import AdvanceSearchForm from '../../../orders/AdvanceSearchForm' import AdvanceSearchForm from '../../../orders/AdvanceSearchForm'
import { API_HOST } from '@/config' import { API_HOST } from '@/config'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import useAuthStore from '@/stores/AuthStore' import useAuthStore from '@/stores/AuthStore'
import { fetchEmailBindOrderAction } from '@/actions/EmailActions' import { fetchEmailBindOrderAction } from '@/actions/EmailActions'
const fetchMyOrderList = async (params) => { const fetchOrderList = async (params) => {
const { errcode, result } = await fetchJSON(`${API_HOST}/getdvancedwlorder`, params) const { errcode, result } = await fetchJSON(`${API_HOST}/getdvancedwlorder`, params)
return errcode !== 0 ? [] : result 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 }) => { export const EmailBindFormModal = ({ mai_sn, conversationid, userId, onBoundSuccess, ...props }) => {
const [form] = Form.useForm()
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const { userId: loginUserId } = useAuthStore((state) => state.loginUser) const { userId: loginUserId } = useAuthStore((state) => state.loginUser)
@ -33,7 +28,7 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
const copyObject = cloneDeep(values) const copyObject = cloneDeep(values)
delete copyObject.type delete copyObject.type
const allEmpty = Object.values(copyObject).every((val) => { const allEmpty = Object.values(copyObject).every((val) => {
return val === null || String(val).trim() === '' || val === undefined return val === null || val === '' || val === undefined
}) })
if (allEmpty) { if (allEmpty) {
notification.warning({ notification.warning({
@ -44,14 +39,12 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
}) })
return false return false
} }
// values.opisn = loginUserId values.opisn = loginUserId
values.sourcetype = values.is_biz ? '227002' : '227001'
delete values.is_biz
setLoading(false) setLoading(false)
setSearchLoading(true) setSearchLoading(true)
setSearchResult([]) setSearchResult([])
const result = await fetchHTOrderList(values) const result = await fetchOrderList(values)
setSearchResult(result.map(ele => ({...ele, sourcetype: values.sourcetype}))) setSearchResult(result)
setSearchLoading(false) setSearchLoading(false)
} }
@ -83,58 +76,40 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
width: 222, width: 222,
}, },
{ {
title: '顾问', title: '客人姓名',
key: 'OperatorName', key: 'coli_guest',
dataIndex: 'OperatorName', dataIndex: 'coli_guest',
width: 100, render: (text, record) => {
let regularText = ''
if (record.buytime > 0) regularText = '(R' + record.buytime + ')'
return text + regularText
},
}, },
{ {
title: '分配时间', title: '出发日期',
key: 'COLI_AssignDate', key: 'COLI_OrderStartDate',
dataIndex: 'COLI_AssignDate', dataIndex: 'COLI_OrderStartDate',
width: 100, 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: '天数', title: '附加信息',
key: 'COLI_Days', ellipsis: true,
dataIndex: 'COLI_Days', key: 'COLI_Introduction',
width: 100, 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: '', title: '',
key: 'action', key: 'action',
width: 150, width: 150,
render: (_, record) => ( 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> </Button>
), ),
@ -156,31 +131,9 @@ export const EmailBindFormModal = ({ mai_sn, conversationid, userId, coliID, onB
onCancel={() => { onCancel={() => {
setOpen(false) setOpen(false)
}} }}
destroyOnHidden> destroyOnClose>
{/* <AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} /> */} <AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} />
<Form <Table key={'advanceOrderTable'} loading={loading} dataSource={searchResult} columns={searchResultColumns} pagination={searchResult.length <= 10 ? false : paginationProps} />
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'} />
</Modal> </Modal>
</> </>
) )

@ -1,8 +1,7 @@
import { POPUP_FEATURES } from '@/config'
import React, { useState, useEffect, useRef } from 'react' import React, { useState, useEffect, useRef } from 'react'
const EmailContent = ({ id, content: MailContent, className='', ...props }) => { const EmailContent = ({ id, content: MailContent, ...props }) => {
const [iframeHeight, setIframeHeight] = useState(5000) // Initial height const [iframeHeight, setIframeHeight] = useState(200) // Initial height
const [content, setContent] = useState(MailContent) const [content, setContent] = useState(MailContent)
const iframeRef = useRef(null) const iframeRef = useRef(null)
const containerRef = useRef(null) const containerRef = useRef(null)
@ -29,15 +28,12 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
margin: 0; margin: 0;
padding: 0; padding: 0;
/*overflow-y: hidden;*/ /*overflow-y: hidden;*/
width: 900px;
max-width: 100%;
} }
img { img {
max-width: 90%; max-width: 90%;
height: auto; height: auto;
object-fit: contain; /*object-fit: contain;*/
} }
img:not(a img){ cursor: pointer;}
</style> </style>
</head> </head>
<body> <body>
@ -55,23 +51,6 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
const body = doc.body const body = doc.body
if (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(() => { requestAnimationFrame(() => {
const newHeight = Math.max(body.scrollHeight, body.offsetHeight, body.clientHeight) const newHeight = Math.max(body.scrollHeight, body.offsetHeight, body.clientHeight)
@ -79,9 +58,8 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
// console.log('body.offsetHeight: ', body.offsetHeight) // console.log('body.offsetHeight: ', body.offsetHeight)
// console.log('body.clientHeight: ', body.clientHeight) // console.log('body.clientHeight: ', body.clientHeight)
const addMore = Math.max(Math.ceil(newHeight * 0.05), 120) console.log('Calculated height:', newHeight)
// console.log('Calculated height:', newHeight, addMore) setIframeHeight(newHeight + 120)
setIframeHeight(newHeight + addMore)
}) })
return return
} else { } else {
@ -93,11 +71,12 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
} catch (error) { } catch (error) {
console.error('Error calculating height:', error) console.error('Error calculating height:', error)
} }
// setIframeHeight(200) setIframeHeight(200)
} }
useEffect(() => { useEffect(() => {
const handleLoad = () => { const handleLoad = () => {
console.log('iframe loaded')
calculateHeight() calculateHeight()
} }
@ -105,7 +84,7 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
if (currentIframe) { if (currentIframe) {
currentIframe.addEventListener('load', handleLoad) currentIframe.addEventListener('load', handleLoad)
setIframeContent(currentIframe, content) setIframeContent(currentIframe, content) // Set content on initial load
} }
return () => { return () => {
@ -123,8 +102,8 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
// }, [content]) // }, [content])
return ( return (
<div ref={containerRef} className={`space-y-4 w-full ${className}`}> <div ref={containerRef} className='space-y-4 w-full'>
<div className='w-full relative pt-2'> <div className='w-full relative'>
<iframe <iframe
key={id} key={id}
ref={iframeRef} ref={iframeRef}
@ -136,7 +115,8 @@ const EmailContent = ({ id, content: MailContent, className='', ...props }) => {
border: 'none', border: 'none',
display: 'block', display: 'block',
}} }}
sandbox='allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-forms allow-top-navigation' title='Dynamic Height Iframe'
sandbox='allow-scripts allow-same-origin'
/> />
</div> </div>
</div> </div>

@ -0,0 +1,156 @@
import React, { useState, useEffect, useRef } from 'react';
const EmailContent = ({ content: MailContent, ...props}) => {
const [iframeHeight, setIframeHeight] = useState(200); // Initial height
const [content, setContent] = useState(MailContent);
const iframeRef = useRef(null);
const containerRef = useRef(null);
useEffect(() => {
setContent(MailContent);
}, [MailContent]);
const calculateHeight = () => {
if (iframeRef.current && iframeRef.current.contentDocument) {
const doc = iframeRef.current.contentDocument;
const body = doc.body;
// Ensure the body is loaded before attempting to get its height.
if (body) {
// Use Math.max to get the larger of scrollHeight, clientHeight, and offsetHeight
const newHeight = Math.max(
body.scrollHeight,
body.offsetHeight,
body.clientHeight
);
setIframeHeight(newHeight);
}
}
};
useEffect(() => {
const handleLoad = () => {
calculateHeight();
};
if (iframeRef.current) {
iframeRef.current.addEventListener('load', handleLoad);
}
return () => {
if (iframeRef.current) {
iframeRef.current.removeEventListener('load', handleLoad);
}
};
}, [content]); // Recalculate when content changes
// const handleContentChange = (newContent) => {
// setContent(newContent);
// };
// const handleReset = () => {
// const defaultContent = `
// <h1>Welcome to the Iframe Test</h1>
// <p>This is the default content inside the iframe. It should adjust its height dynamically.</p>
// <h2>Section 1</h2>
// <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
// `;
// setContent(defaultContent);
// };
return (
<div ref={containerRef} className="space-y-4 w-full">
{/* <h1 className="text-2xl font-bold text-gray-200">Iframe Height Calculator</h1>
<p className="text-gray-400">
This example demonstrates how to dynamically adjust the height of an iframe to fit its content, eliminating vertical scrollbars.
</p> */}
<div className="w-full relative">
<iframe
ref={iframeRef}
style={{
width: '100%',
height: `${iframeHeight}px`,
border: '1px solid #e5e7eb',
display: 'block', // Ensure iframe is treated as a block element
}}
title="Dynamic Height Iframe"
sandbox="allow-scripts allow-same-origin" // Important for script execution and accessing content
/>
{/* Render the content directly. The iframe will load this. */}
{iframeRef.current?.contentDocument && (
<div className="p-4">
{/* Added styling for better rendering inside the iframe */}
<style>{`
body {
margin: 0;
padding: 0;
font-family: sans-serif; /* Added a default font */
line-height: 1.5; /* Improved default line height */
}
p {
margin-bottom: 1em;
}
h1 {
font-size: 2em;
margin-bottom: 0.75em;
}
h2 {
font-size: 1.5em;
margin-bottom: 0.6em;
}
h3 {
font-size: 1.17em;
margin-bottom: 0.5em;
}
a {
color: #0078d7; /* Standard link color */
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
`}</style>
<div dangerouslySetInnerHTML={{ __html: content }} />
</div>
)}
</div>
{/* <div className="flex flex-wrap gap-4">
<button
onClick={() =>
handleContentChange(`
<h1>Dynamic Content Update</h1>
<p>This content was added dynamically!</p>
<ul><li>Item 1</li><li>Item 2</li></ul>
<p>The iframe should resize to fit this new content.</p>
<p>Testing a very long paragraph to see how the iframe handles wrapping and height adjustment. This is a long sentence that should wrap to multiple lines within the iframe's body, and the iframe should increase its height to accommodate all of this text without creating a vertical scrollbar. We want the iframe to behave like a native div element in terms of height.</p>
`)
}
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
>
Change Content
</button>
<button
onClick={() =>
handleContentChange(`
<h1>Another Content Change</h1>
<p>This is different content.</p>
<ol><li>Step 1</li><li>Step 2</li></ol>
`)
}
className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
>
Change Content Again
</button>
<button
onClick={handleReset}
className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
>
Reset Content
</button>
</div> */}
</div>
);
};
export default EmailContent;

@ -2,9 +2,9 @@ import { useState, useEffect } from 'react'
import { App, Button, Divider, Avatar } from 'antd' import { App, Button, Divider, Avatar } from 'antd'
import { LoadingOutlined, ApiOutlined } from '@ant-design/icons'; import { LoadingOutlined, ApiOutlined } from '@ant-design/icons';
import { EditIcon, ReplyIcon, ResendIcon, ShareForwardIcon } from '@/components/Icons' import { EditIcon, ReplyIcon, ResendIcon, ShareForwardIcon } from '@/components/Icons'
import { isEmpty, TagColorStyle } from '@haina/utils-commons' import { isEmpty, TagColorStyle } from '@/utils/commons'
import EmailEditorPopup from '../Input/EmailEditorPopup' import EmailEditorPopup from '../Input/EmailEditorPopup'
import DnDModal from '@/components/DnDModal' import DnDModal from '@/components/DndModal'
import useStyleStore from '@/stores/StyleStore' import useStyleStore from '@/stores/StyleStore'
import { useEmailDetail, } from '@/hooks/useEmail'; import { useEmailDetail, } from '@/hooks/useEmail';
import { EMAIL_ATTA_HOST } from '@/config'; import { EMAIL_ATTA_HOST } from '@/config';
@ -14,7 +14,6 @@ import EmailContent from './EmailContent';
/** /**
* @property {*} emailMsg - 邮件数据. { conversationid, actionId, order_opi, coli_sn, msgOrigin: { from, to, id, email: { subject, mai_sn, } } } * @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 }) => { const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) => {
@ -25,16 +24,16 @@ const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) =
const { conversationid, actionId, order_opi, coli_sn } = emailMsg const { conversationid, actionId, order_opi, coli_sn } = emailMsg
const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {} const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {}
const mailID = mai_sn || id const mailID = mai_sn || id
// const [initialPosition, setInitialPosition] = useState({}) const [initialPosition, setInitialPosition] = useState({})
// const [initialSize, setInitialSize] = useState({}) const [initialSize, setInitialSize] = useState({})
function onHandleMove(e) { function onHandleMove(e) {
const { top, left, width, height } = e const { top, left, width, height } = e
props?.setInitialPosition({ top, left }) setInitialPosition({ top, left })
} }
function onHandleResize(e) { function onHandleResize(e) {
const { top, left, width, height } = e const { top, left, width, height } = e
props?.setInitialPosition({ top, left }) setInitialPosition({ top, left })
props?.setInitialSize({ width, height }) setInitialSize({ width, height })
} }
const [action, setAction] = useState('') const [action, setAction] = useState('')
@ -143,13 +142,66 @@ const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) =
{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.email?.subject} {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: initialPosition.left || (300 + 24), top: initialPosition.top || 74 }}
onMove={onHandleMove} onMove={onHandleMove}
onResize={onHandleResize} onResize={onHandleResize}
footer={<ActionBtns className='w-full !justify-start' />}> 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> */}
{mailData.info?.mailType === 'text/html' ? <EmailContent content={mailData.content} id={mailID} key={mailID} /> : <div className='mt-2 whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: mailData.content }}></div>}
</div>
</div>
</DnDModal> </DnDModal>
{/* <EmailEditorPopup <EmailEditorPopup
open={openEmailEditor} open={openEmailEditor}
setOpen={setOpenEmailEditor} setOpen={setOpenEmailEditor}
fromEmail={fromEmail} fromEmail={fromEmail}
@ -160,11 +212,11 @@ const EmailDetail = ({ open, setOpen, emailMsg={}, disabled=false, ...props }) =
customerDetail={orderDetail.customerDetail} customerDetail={orderDetail.customerDetail}
// emailMsg={ReferEmailMsg} // emailMsg={ReferEmailMsg}
quoteid={mailID} quoteid={mailID}
initial={{ ...props.initialPosition, ...props.initialSize }} initial={{ ...initialPosition, ...initialSize }}
mailData={mailData} mailData={mailData}
action={action} action={action}
key={`email-detail-inner-${action}_${mailID}`} key={`email-detail-inner-${action}-popup_${mailID}`}
/> */} />
</> </>
) )
} }

@ -1,104 +1,53 @@
import { useState, useEffect, useRef, useMemo } from 'react' import { useState, useEffect } from 'react'
import { App, Button, Divider, Avatar, List, Flex, Typography, Tooltip, Empty } from 'antd' import { App, Button, Divider, Avatar } from 'antd'
import { LoadingOutlined, ApiOutlined, FilePdfOutlined, FileOutlined, FileWordOutlined, FileExcelOutlined, FileJpgOutlined, FileImageOutlined, FileTextOutlined, FileGifOutlined, GlobalOutlined, FileZipOutlined, DeleteOutlined, ExpandOutlined } from '@ant-design/icons' import { LoadingOutlined, ApiOutlined } from '@ant-design/icons';
import { EditIcon, MailCheckIcon, ReplyAllIcon, ReplyIcon, ResendIcon, ShareForwardIcon, SendPlaneFillIcon, InboxIcon } from '@/components/Icons' import { EditIcon, ReplyIcon, ResendIcon, ShareForwardIcon } from '@/components/Icons'
import { isEmpty, TagColorStyle } from '@haina/utils-commons' import { isEmpty, TagColorStyle } from '@/utils/commons'
import EmailEditorPopup from '../Input/EmailEditorPopup' import EmailEditorPopup from '../Input/EmailEditorPopup'
import DnDModal from '@/components/DnDModal' import DnDModal from '@/components/DndModal'
import useStyleStore from '@/stores/StyleStore' import useStyleStore from '@/stores/StyleStore'
import { openPopup, useEmailDetail, } from '@/hooks/useEmail' import { useEmailDetail, } from '@/hooks/useEmail';
import { EMAIL_ATTA_HOST, POPUP_FEATURES } from '@/config' import { EMAIL_ATTA_HOST } from '@/config';
import EmailBindFormModal from './EmailBind' import EmailBindFormModal from './EmailBind';
import EmailContent from './EmailContent' 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} />;
};
/** /**
* @property {*} emailMsg - 邮件数据. { conversationid, actionId, order_opi, coli_sn, msgOrigin: { from, to, id, email: { subject, mai_sn, } } } * @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 }) => { const EmailDetailInline = ({ mailID, open, setOpen = () => {}, emailMsg={}, disabled=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 NEW_EMAIL_CONFIG = useMemo(() => { // console.log('emailDetail', emailMsg);
// 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]);
const { notification, message } = App.useApp() const {notification, message} = App.useApp()
const { conversationid, actionId, order_opi, coli_sn } = emailMsg const { conversationid, actionId, order_opi, coli_sn } = emailMsg
const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {} const { mai_sn, id } = emailMsg.msgOrigin?.email || emailMsg.msgOrigin || {}
// const mailID = mai_sn || id // const mailID = mai_sn || id
// const [action, setAction] = useState('') const [action, setAction] = useState('')
// const [openEmailEditor, setOpenEmailEditor] = useState(false) const [openEmailEditor, setOpenEmailEditor] = useState(false)
// const [fromEmail, setFromEmail] = useState('') const [fromEmail, setFromEmail] = useState('')
// useEffect(() => { useEffect(() => {
// setOpenEmailEditor(false) setOpenEmailEditor(false)
// return () => {}
// }, [mailID])
const onOpenEditor = (msgOrigin, action='reply') => { return () => {}
openPopup(`/email/${action}/${mailID || 0}`, `${action}-${mailID || 0}`) }, [mailID])
if (typeof props.onOpenEditor === 'function') {
props.onOpenEditor(msgOrigin, action); const onOpenEditor = (msgOrigin, action) => {
} else { const { from, to } = msgOrigin
// const { from, to } = msgOrigin setOpenEmailEditor(true)
// setOpenEmailEditor(true) setFromEmail(action === 'edit' ? from : to)
// setFromEmail(action === 'edit' ? from : to) setAction(action)
// setAction(action) // setOpen(false)
// // setOpen(false)
}
} }
const { loading, mailData, orderDetail, postEmailResend } = useEmailDetail(mailID, null, false, autoMark) const { loading, mailData, orderDetail, postEmailResend } = useEmailDetail(mailID)
const [showBindBtn, setShowBindBtn] = useState(false) const [showBindBtn, setShowBindBtn] = useState(false);
useEffect(() => { useEffect(() => {
setShowBindBtn(mailID ? isEmpty(mailData.info?.MAI_COLI_SN) : false) setShowBindBtn(isEmpty(mailData.info?.MAI_COLI_SN))
return () => {} return () => {}
}, [mailID, mailData.info?.MAI_COLI_SN]) }, [mailData.info?.MAI_COLI_SN])
const handleView = async () => {
openPopup(`/email/view/${mailID || 0}`, `view-${mailID || 0}`, { fullscreen: true })
};
const handleResend = async () => { const handleResend = async () => {
if (isEmpty(mai_sn)) { if (isEmpty(mai_sn)) {
@ -109,27 +58,11 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
// setOpen(false) // setOpen(false)
} catch (err) { } catch (err) {
notification.error({ notification.error({
message: '请求失败', message: "请求失败",
description: err.message, description: err.message,
placement: 'top', placement: "top",
duration: 3, 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 +73,15 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
* * 失败: 重发 * * 失败: 重发
* todo: disabled 不显示 * todo: disabled 不显示
*/ */
const renderActionBtns = ({ className, ...props }) => { const ActionBtns = ({className, ...props}) => {
const { status } = mailData.info const { status } = mailData.info
let btns = [] 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) { if (showBindBtn) {
btns.push(<EmailBindFormModal key={'bind'} onBoundSuccess={() => setShowBindBtn(false)} {...{ conversationid, mai_sn, 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(<Divider key='divider1' type='vertical' />);
} }
switch (status) { switch (status) {
@ -161,166 +90,94 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
case 'sent': case 'sent':
case '': // case '': //
btns.push( 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' />}> <Button key={'reply'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'reply')} size='small' type='text' icon={<ReplyIcon className='text-indigo-500' />}>
{compactBtn ? '' : '回复'} 回复
</Button> </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( btns.push(
<Tooltip key='forward-t' title='转发'> <Button key={'forward'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'forward')} size='small' type='text' icon={<ShareForwardIcon className='text-primary' />}>
<Button key={'forward'} onClick={() => onOpenEditor(emailMsg.msgOrigin, 'forward')} size='small' type='text' icon={<ShareForwardIcon className='text-primary' />}>{compactBtn ? '' : '转发'}</Button></Tooltip>, 转发
</Button>
) )
break break
case 'failed': case 'failed':
btns.push( btns.push(
// <Tooltip key='delete-t' title=''> <Button key={'resend'} onClick={() => handleResend()} size='small' type='text' icon={<ResendIcon className='text-orange-500' />}>
// <Button key={'delete'} danger onClick={() => handleDel()} size='small' type='text' icon={<DeleteOutlined className='text-red-500' />}>{compactBtn ? '' : ''}</Button></Tooltip>, 重发
</Button>
<Tooltip key='resend-t' title='发送'>
<Button key={'resend'} onClick={() => handleResend()} size='small' type='text' icon={<SendPlaneFillIcon className='text-orange-500' />}>{compactBtn ? '' : '发送'}</Button></Tooltip>,
) )
btns.push( 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' />}>
<Button 编辑
key={'edit'} </Button>
onClick={() => onOpenEditor({ ...(emailMsg.msgOrigin || {}), content: mailData.content }, 'edit')}
size='small'
type='text'
icon={<EditIcon className='text-indigo-500' />}>{compactBtn ? '' : '编辑'}</Button></Tooltip>,
) )
break break
default: default:
break 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 ( return (
<List <div className={`flex justify-end items-center w-full ${className || ''}`}>
dataSource={list} {btns}
size='small' </div>
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}${encodeURIComponent(atta.ATI_ServerFile)}`, atta.ATI_SN)} size='small' className='text-blue-500 cursor-pointer'>
{atta.ATI_Name}
</span>
</Typography.Text>
</List.Item>
)}
/>
) )
};
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='email-container flex flex-col gap-2 *:p-2 *:rounded-sm *:border-b *:border-gray-200 *:shadow-1md'>
<div className=''> <div className=' font-bold'>{loading ? <LoadingOutlined className='mr-1' /> : null}{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.subject}</div>
<div className='flex flex-wrap justify-between'>
<span className={(mailData.info?.MAI_ReadState || 0) > 0 ? '' : ' font-bold '}> <div>
{loading ? <LoadingOutlined className='mr-1' /> : null} <div className={['flex flex-wrap justify-end', window.innerWidth < 600 ? 'flex-col' : 'flex-row '].join(' ')}>
{mailData.info?.MAI_Subject || emailMsg?.msgOrigin?.subject} <div className=' grow shrink basis-0 flex flex-wrap gap-2 mb-2 items-center'>
</span> <Avatar className='' style={TagColorStyle(mailData.info?.MAI_From, true)}>
{/* <ActionBtns key='actions' className={'ml-auto'} /> */} {(mailData.info?.MAI_From || '').substring(0, 1)}
{renderActionBtns({ className: 'ml-auto'})} </Avatar>
</div> <div className=' flex flex-col '>
<Divider className='my-2' /> {/* <span className=' font-bold text-base'>{mailData.info?.fromName}</span> */}
<div className={['flex flex-wrap justify-end', window.innerWidth < 800 ? 'flex-col' : 'flex-row '].join(' ')}> <span className='text-neutral-500 text-wrap break-words break-all '>{mailData.info?.MAI_From}</span>
<div className=' flex-auto basis-0 flex flex-wrap gap-2 mb-2 items-center'> </div>
<Avatar className='' style={TagColorStyle(mailData.info?.MAI_From, true)}> </div>
{(mailData.info?.MAI_From || '').substring(0, 1)} <div className=' shrink-0 flex flex-col justify-start gap-1 items-end'>
</Avatar> <ActionBtns />
<div className=' flex flex-col '> <div className='text-xs '>{mailData.info?.MAI_SendDate || emailMsg.localDate}</div>
{/* <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> </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'> <div className='text-sm'>
<span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{ textAlignLast: 'justify' }}> <span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>收件人</span>
密送 {mailData.info?.MAI_To}
</span>
{mailData.info.bcc}
</div> </div>
)} {mailData.info?.MAI_CS && (
</div> <div className='text-sm'>
<div className='overflow-auto'> <span className='text-neutral-500 pr-2 w-12 inline-block text-justify' style={{textAlignLast: 'justify'}}>抄送</span>
<Flex className={` divide-gray-200 divide-solid gap-0 ${compactBtn === false ? 'divide-y-0 divide-x' : 'flex-col-reverse divide-x-0 '}`}> {mailData.info.MAI_CS}
{mailData.info?.mailType === 'text/html' ? ( </div>
<EmailContent content={mailData.content} id={mailID} key={mailID} /> )}
) : ( {mailData.info?.bcc && (
<div className='mt-2 whitespace-pre-wrap flex-auto' dangerouslySetInnerHTML={{ __html: mailData.content }}></div> <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 && ( {mailData.attachments.length > 0 && (
<div className={`${compactBtn === false ? 'w-48' : 'border-b border-t-0'} overflow-hidden`}> <div className='mt-2 *:ml-2'>
{mailData.attachments.length > 0 && ( <span>{mailData.attachments.length}个附件</span>
<> <div className='flex flex-wrap gap-2'>
<span>&nbsp;附件 ({mailData.attachments.length})</span> {mailData.attachments.map((atta) => (
{renderAttaList({ list: mailData.attachments || []})} <a href={`${EMAIL_ATTA_HOST}${atta.ATI_ServerFile}`} key={atta.ATI_SN} target='_blank' rel='noreferrer'>
</> {atta.ATI_Name}
)} </a>
{mailData.insideAttachments.length > 0 && <details> ))}
<summary> </div>
<span className='text-gray-500 italic'>&nbsp;文内附件 ({mailData.insideAttachments.length}) 已在正文显示&nbsp;</span><span className='cursor-pointer underline'>点击展开</span>
</summary>
{renderAttaList({ list: mailData.insideAttachments || []})}
</details>}
</div> </div>
)} )}
</Flex> <Divider className='my-2' />
{/* <div className='mt-2 whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: mailData.content }}></div> */}
{mailData.info?.mailType === 'text/html' ? <EmailContent content={mailData.content} id={mailID} key={mailID} /> : <div className='mt-2 whitespace-pre-wrap' dangerouslySetInnerHTML={{ __html: mailData.content }}></div>}
</div>
</div> </div>
</div> <EmailEditorPopup
{/* <EmailEditorPopup
open={openEmailEditor} open={openEmailEditor}
setOpen={setOpenEmailEditor} setOpen={setOpenEmailEditor}
fromEmail={fromEmail} fromEmail={fromEmail}
@ -334,11 +191,9 @@ const EmailDetailInline = ({ mailID, emailMsg = {}, disabled = false, variant, s
// initial={{ ...initialPosition, ...initialSize }} // initial={{ ...initialPosition, ...initialSize }}
mailData={void 0} mailData={void 0}
action={action} 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 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 '@haina/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

@ -5,7 +5,7 @@ import { useOrderStore } from '@/stores/OrderStore'
import useAuthStore from '@/stores/AuthStore' import useAuthStore from '@/stores/AuthStore'
import useConversationStore from '@/stores/ConversationStore' import useConversationStore from '@/stores/ConversationStore'
import { getEmailQuotationDraftAction } from '@/actions/EmailActions' import { getEmailQuotationDraftAction } from '@/actions/EmailActions'
import { isEmpty } from '@haina/utils-commons' import { isEmpty } from '@/utils/commons'
const EmailQuotation = ({ sfi_sn, ...props }) => { const EmailQuotation = ({ sfi_sn, ...props }) => {
const {notification} = App.useApp() const {notification} = App.useApp()
@ -69,7 +69,7 @@ const EmailQuotation = ({ sfi_sn, ...props }) => {
邮件 邮件
</Button> </Button>
{/* <EmailEditorPopup <EmailEditorPopup
open={editorOpen} open={editorOpen}
setOpen={setEditorOpen} setOpen={setEditorOpen}
fromEmail={pickEmail.key} fromEmail={pickEmail.key}
@ -86,7 +86,7 @@ const EmailQuotation = ({ sfi_sn, ...props }) => {
// customerDetail={customerDetail} // customerDetail={customerDetail}
action={'new'} action={'new'}
key={`email-quotation-new-popup_${currentConversation.sn}`} 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,14 +0,0 @@
import { createContext, useEffect, useState } from 'react'
import { Drawer } from 'antd'
import useUrlStore from '@/stores/UrlStore'
import ShorturlConversion from '@/views/accounts/ShorturlConversion'
const GenerateShorturlDrawer = ({ ...props }) => {
const [openShorturlDrawer, closeShorturlDrawer, shorturlDrawerOpen] = useUrlStore((state) => [state.openDrawer, state.closeDrawer, state.drawerOpen])
return (
<Drawer title='短链接转换' placement={'top'} onClose={() => closeShorturlDrawer()} open={shorturlDrawerOpen}>
<ShorturlConversion/>
</Drawer>
)
}
export default GenerateShorturlDrawer

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

@ -1,7 +1,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { App, Modal, Button, Table } from 'antd'; import { App, Modal, Button, Table } from 'antd';
import { isEmpty, cloneDeep } from '@haina/utils-commons'; import { isEmpty, cloneDeep } from '@/utils/commons';
import { fetchJSON } from '@haina/utils-request'; import { fetchJSON } from '@/utils/request';
import AdvanceSearchForm from './../../orders/AdvanceSearchForm'; import AdvanceSearchForm from './../../orders/AdvanceSearchForm';
import { API_HOST } from '@/config'; import { API_HOST } from '@/config';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
@ -126,7 +126,7 @@ export const ConversationBindFormModal = ({ currentConversationID, userId, onBou
onCancel={() => { onCancel={() => {
setOpen(false); setOpen(false);
}} }}
destroyOnHidden> destroyOnClose>
<AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} /> <AdvanceSearchForm onSubmit={onSearchOrder} loading={searchLoading} />
<Table <Table
key={'advanceOrderTable'} key={'advanceOrderTable'}

@ -4,7 +4,7 @@ import { App, Input, Button, Empty, Tooltip, List } from 'antd';
import { PlusOutlined, LoadingOutlined, HistoryOutlined, FireOutlined,AudioTwoTone } from '@ant-design/icons'; import { PlusOutlined, LoadingOutlined, HistoryOutlined, FireOutlined,AudioTwoTone } from '@ant-design/icons';
import { fetchConversationsList, fetchOrderConversationsList, CONVERSATION_PAGE_SIZE } from '@/actions/ConversationActions'; import { fetchConversationsList, fetchOrderConversationsList, CONVERSATION_PAGE_SIZE } from '@/actions/ConversationActions';
import ConversationsNewItem from './ConversationsNewItem'; import ConversationsNewItem from './ConversationsNewItem';
import { debounce, flush, isEmpty, isNotEmpty, pick } from '@haina/utils-commons'; import { debounce, flush, isEmpty, isNotEmpty, pick } from '@/utils/commons';
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import useAuthStore from '@/stores/AuthStore'; import useAuthStore from '@/stores/AuthStore';
// import { useOrderStore, OrderLabelDefaultOptions, OrderStatusDefaultOptions } from "@/stores/OrderStore"; // import { useOrderStore, OrderLabelDefaultOptions, OrderStatusDefaultOptions } from "@/stores/OrderStore";
@ -318,25 +318,30 @@ const Conversations = () => {
// enterButton={'Filter'} // enterButton={'Filter'}
/> />
{/* TODO 这个在完成搜索历史会话后去掉,待讨论查询规则 */} {/* 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 ? ( {conversationsListLoading ? (
<div className='text-center py-1 px-2'> <div className='text-center py-1 px-2'>
<LoadingOutlined className='text-orange-400 ' /> <LoadingOutlined className='text-orange-400 ' />
</div> </div>
) : ) :
<Tooltip key={'conversation-list'} title={activeList ? '🗂已隐藏' : '活跃会话'}> <Tooltip key={'conversation-list'} title={activeList ? '🗂已处理' : '活跃会话'}>
<Button onClick={toggleClosedConversationsList} icon={activeList ? '🗂' : '📌'} type='text' /> <Button onClick={toggleClosedConversationsList} icon={activeList ? '🗂' : '📌'} type='text' />
</Tooltip> </Tooltip>
} }
{mobile && (
<AudioTwoTone className='px-2'
onClick={() => {
navigate(`/callcenter/call`)
}}
/>
)}
</div> </div>
<ChatListFilter key='chat-list-filter'
onFilterChange={(d) => {
refreshConversationList()
}}
activeList={activeList}
/>
<div className='flex-1 overflow-x-hidden overflow-y-auto relative'> <div className='flex-1 overflow-x-hidden overflow-y-auto relative'>
{/* {mobile && conversationsListLoading && dataSource.length === 0 ? ( */} {/* {mobile && conversationsListLoading && dataSource.length === 0 ? ( */}

@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { Form, Input, Modal } from 'antd'; import { Form, Input, Modal } from 'antd';
import { isEmpty, isNotEmpty, pick } from '@haina/utils-commons'; import { isEmpty, isNotEmpty, pick } from '@/utils/commons';
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import { phoneNumberToWAID } from '@/channel/bubbleMsgUtils'; import { phoneNumberToWAID } from '@/channel/bubbleMsgUtils';
import { useConversationNewItem } from '@/hooks/useConversation'; import { useConversationNewItem } from '@/hooks/useConversation';
@ -59,7 +59,7 @@ export const ConversationItemForm = ({ initialValues, onFormInstanceReady }) =>
<Form.Item label='WhatsApp' name={'wa_id'} dependencies={['phone_number']}> <Form.Item label='WhatsApp' name={'wa_id'} dependencies={['phone_number']}>
<Input disabled={!initialValues.is_new && isNotEmpty(initialValues.wa_id)} /> <Input disabled={!initialValues.is_new && isNotEmpty(initialValues.wa_id)} />
</Form.Item> </Form.Item>
<Form.Item hidden <Form.Item
name={'email'} name={'email'}
label='邮箱' label='邮箱'
validateStatus={contactValidateStatus} validateStatus={contactValidateStatus}
@ -124,7 +124,7 @@ export const ConversationItemFormModal = ({ open, onCreate, onCancel, initialVal
onCancel(); onCancel();
formInstance?.resetFields(); formInstance?.resetFields();
}} }}
destroyOnHidden destroyOnClose
onOk={async () => { onOk={async () => {
try { try {
const values = await formInstance?.validateFields(); const values = await formInstance?.validateFields();

@ -1,223 +0,0 @@
import { createContext, useEffect, useState } from 'react'
import { Checkbox, Popover } from 'antd'
import useAuthStore from '@/stores/AuthStore'
import BubbleIM from '../Components/BubbleIM'
import { MessageBox } from 'react-chat-elements'
import { cloneDeep, objectMapper, removeFormattingChars, getNestedValue } from '@haina/utils-commons'
import { replaceTemplateString, whatsappTemplateBtnParamTypesMapped } from '@/channel/bubbleMsgUtils'
const DEI_Lgc_Mapped = {
1: { DEI_SN: 1, DEI_DepartmentName: 'CH直销组', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
2: { DEI_SN: 2, DEI_DepartmentName: 'CH大客户组', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
7: { DEI_SN: 7, DEI_DepartmentName: '市场推广', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
8: { DEI_SN: 8, DEI_DepartmentName: '德语市场', DEI_LGC: 4, lgc_n: 'German', LANGUAGE: 'de' },
9: { DEI_SN: 9, DEI_DepartmentName: '日语市场', DEI_LGC: 3, lgc_n: 'Japanese', LANGUAGE: 'ja' },
10: { DEI_SN: 10, DEI_DepartmentName: '商旅市场', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
11: { DEI_SN: 11, DEI_DepartmentName: '法语市场', DEI_LGC: 5, lgc_n: 'French', LANGUAGE: 'fr' },
12: { DEI_SN: 12, DEI_DepartmentName: '西语市场', DEI_LGC: 6, lgc_n: 'Spanish', LANGUAGE: 'es' },
13: { DEI_SN: 13, DEI_DepartmentName: '英文在线组', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
14: { DEI_SN: 14, DEI_DepartmentName: 'Train Spread', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
15: { DEI_SN: 15, DEI_DepartmentName: 'CH产品', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
16: { DEI_SN: 16, DEI_DepartmentName: 'APP移动项目组', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
17: { DEI_SN: 17, DEI_DepartmentName: 'ChinaTravel组(精华线路使用)', DEI_LGC: 104, lgc_n: 'English(CT)', LANGUAGE: 'en' },
18: { DEI_SN: 18, DEI_DepartmentName: 'CT市场', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
19: { DEI_SN: 19, DEI_DepartmentName: '(待删除)', DEI_LGC: 1, lgc_n: 'English', LANGUAGE: 'en' },
20: { DEI_SN: 20, DEI_DepartmentName: '俄语市场', DEI_LGC: 7, lgc_n: 'Russian', LANGUAGE: 'ru' },
21: { DEI_SN: 21, DEI_DepartmentName: '意语市场', DEI_LGC: 8, lgc_n: 'Italian', LANGUAGE: 'it' },
22: { DEI_SN: 22, DEI_DepartmentName: '爱游网', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
23: { DEI_SN: 23, DEI_DepartmentName: '三峡站(YZ)', DEI_LGC: 102, lgc_n: 'English(YZ)', LANGUAGE: 'en' },
24: { DEI_SN: 24, DEI_DepartmentName: '桂林站(GL)', DEI_LGC: 103, lgc_n: 'English(GL)', LANGUAGE: 'en' },
25: { DEI_SN: 25, DEI_DepartmentName: '上海站(SHT)', DEI_LGC: 107, lgc_n: 'English(SH)', LANGUAGE: 'en' },
26: { DEI_SN: 26, DEI_DepartmentName: '北京站(MBJ)', DEI_LGC: 106, lgc_n: 'English(BJ)', LANGUAGE: 'en' },
27: { DEI_SN: 27, DEI_DepartmentName: '西藏站(TBT)', DEI_LGC: 105, lgc_n: 'English(TBT)', LANGUAGE: 'en' },
28: { DEI_SN: 28, DEI_DepartmentName: 'HT项目组(前AH)', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
29: { DEI_SN: 29, DEI_DepartmentName: 'DMC地接组', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
30: { DEI_SN: 30, DEI_DepartmentName: 'Trippest项目组', DEI_LGC: 0, lgc_n: 'English', LANGUAGE: 'en' },
31: { DEI_SN: 31, DEI_DepartmentName: '花梨鹰', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
32: { DEI_SN: 32, DEI_DepartmentName: 'Daytours板块(Trippest)', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
33: { DEI_SN: 33, DEI_DepartmentName: 'GH项目组', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
34: { DEI_SN: 34, DEI_DepartmentName: 'trippest网站', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
35: { DEI_SN: 35, DEI_DepartmentName: 'newsletter营销', DEI_LGC: null, lgc_n: 'English', LANGUAGE: 'en' },
}
const DEI_Template_mapped = {
// GH: agent_intro_with_update_v1
en: {
name: 'agent_intro_with_update_v1',
language: { code: 'en' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
{
type: 'text',
text: 'We got your inquiry. I\'ve just sent you an email about your trip. Would you see if you\'ve received it or not? (It might be in your "filtered" mail box.)If you have not received it or have any other questions, do not hesitate to ask me.',
},
{ type: 'text', text: 'yoyo' },
],
text: "Hi {{customer_name}}, this is {{your_name1}} , your trip advisor. \nHere's a quick update for you: {{quick_detail}}\nKindest regards, {{your_name2}}. ",
},
],
},
// email_sent_confirm_ru_v1
ru: {
name: 'email_sent_confirm_ru_v1',
language: { code: 'ru' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
],
text: 'Добрый день, {{customer_name}}! Это {{your_name}}, ваш консультант . Ваш запрос по поводу поездки принята. Я отправила предложение по туру вам на почту, посмотрите, пожалуйста. Благодарю!',
},
],
},
// inquiry_confirm_v1
fr: {
name: 'inquiry_confirm_v1',
language: { code: 'fr' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
],
text: 'Bonjour {{customer_name}},Cest {{your_name}}, votre conseillère de voyage chez {{agency_name}}. Votre demande de voyage est bien traitée. Je viens de vous envoyer la proposition de prix par email, merci de bien vouloir vérifier votre boîte mail.',
},
],
},
// inquiry_confirm_ja_v4
ja: {
name: 'inquiry_confirm_ja_v4',
language: { code: 'ja' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
],
text: 'いつもお世話になっております。{{customer_name}} 様、こちら {{your_name}} でございます。ご旅行のご相談を承りました。先ほどメールにて旅程のご提案を送付いたしましたので、ご確認いただけますようお願いいたします。よろしくお願いいたします。',
},
],
},
// inquiry_confirm_it_v1
it: {
name: 'inquiry_confirm_it_v1',
language: { code: 'it' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
],
text: "Buongiorno, {{customer_name}}, sono  {{your_name}} da China Highlights, grazie per l'interesse verso il nostro servizio, la Sua richiesta di consulenza di viaggio è stata presa in carico. Le ho appena inviato una proposta di itinerario via email, la invito a controllare la sua casella di posta. Grazie.",
},
],
},
// email_sent_confirm_es_v4
es: {
name: 'email_sent_confirm_es_v4',
language: { code: 'es' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
],
text: 'Hola{{customer_name}}soy su asesora de viaje {{your_name}}hemos recibido su consulta sobre el viaje. Acabo de mandarle un correo sobre el itinerario, por favor, revise su correo, muchas gracias! ',
},
],
},
// inquiry_confirm_v1
de: {
name: 'inquiry_confirm_v1',
language: { code: 'de' },
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'test OT 22' },
{ type: 'text', text: 'yoyo' },
],
text: 'Hallo {{customer_name}}, Ihre Anfrage wurde bearbeitet und Sie haben eine erste E-Mail erhalten. Bitte bestätigen Sie den Erhalt. Vielen Dank.',
},
],
},
}
const DEFAULT_FILL = {
agent_intro_with_update_v1: {
quick_detail:
'We got your inquiry. I\'ve just sent you an email about your trip. Would you see if you\'ve received it or not? (It might be in your "filtered" mail box). If you have not received it or have any other questions, do not hesitate to ask me.',
},
inquiry_confirm_v1: {
agency_name: 'China Highlights',
},
}
const AutoSendWAForEmail = ({ disabled, orderDetail, onChange, ...props }) => {
const [loginUser] = useAuthStore((state) => [state.loginUser])
loginUser.usernameEN = (loginUser.accountList[0]?.OPI_NameEN || '').split(' ')?.[0] || loginUser.username;
const dei = loginUser.accountList[0].OPI_DEI_SN
const dei_mapped = DEI_Template_mapped[DEI_Lgc_Mapped[dei].LANGUAGE || 'en']
const keys = (dei_mapped.components[0].text.match(/{{(.*?)}}/g) || []).map((key) => key.replace(/{{|}}/g, ''))
const valueMapped = {
...cloneDeep(orderDetail),
...objectMapper(loginUser, { username: [{ key: 'agent_name' }, { key: 'your_name' }, { key: 'your_name1' }, { key: 'your_name2' }] }),
...objectMapper(loginUser, { usernameEN: [{ key: 'agent_name' }, { key: 'your_name' }, { key: 'your_name1' }, { key: 'your_name2' }] }),
...{ order_number: orderDetail.order_no, customer_name: orderDetail?.customerDetail?.name },
...DEFAULT_FILL[dei_mapped.name],
}
const paramsVal = keys.reduce((r, k) => ({ ...r, [k]: getNestedValue(valueMapped, [k]) }), {})
const params = keys.map((v) => ({ type: 'text', text: getNestedValue(paramsVal, [v]) }))
const paramText = keys.length ? params.map((p) => p.text) : []
const fillTemplate = paramText.length ? replaceTemplateString(dei_mapped.components[0].text || '', paramText) : citem?.text || ''
const [openTemplates, setOpenTemplates] = useState(false);
const handleSendChange = ({ target: { checked } }) => {
const _template = cloneDeep(dei_mapped)
_template.components[0].parameters = params
_template.components[0].text = fillTemplate
if (typeof onChange === 'function') {
onChange(checked !== true ? null : _template)
}
}
return (
<>
<Popover
fresh
forceRender
placement='bottomRight'
classNames={{ root: 'w-3/5' }}
open={openTemplates}
onOpenChange={(v) => {
if ( ! disabled) setOpenTemplates(v);
}}
content={
<MessageBox
notch={false}
type='text'
position='right'
text={fillTemplate}
className={[
'whitespace-pre-wrap mb-2',
`[&_.rce-mbox]:bg-waba-me`,
].join(' ')}
/>
}>
<Checkbox disabled={disabled} onChange={handleSendChange}>同时发送WhatsApp</Checkbox>
</Popover>
</>
)
}
export default AutoSendWAForEmail

@ -6,8 +6,7 @@ import InputMediaUpload from './MediaUpload'
import PaymentlinkBtn from './PaymentlinkBtn' import PaymentlinkBtn from './PaymentlinkBtn'
import SnippestBtn from './SnippestBtn' import SnippestBtn from './SnippestBtn'
import useConversationStore from '@/stores/ConversationStore' import useConversationStore from '@/stores/ConversationStore'
import { isEmpty } from '@haina/utils-commons' import { isEmpty } from '@/utils/commons'
import ShortlinkBtn from './ShortlinkBtn'
const ComposerTools = ({ channel, invokeSendUploadMessage, invokeSendMessage, invokeUploadFileMessage, inputEmoji, ...props }) => { const ComposerTools = ({ channel, invokeSendUploadMessage, invokeSendMessage, invokeUploadFileMessage, inputEmoji, ...props }) => {
const websocket = useConversationStore((state) => state.websocket) const websocket = useConversationStore((state) => state.websocket)
@ -26,7 +25,6 @@ const ComposerTools = ({ channel, invokeSendUploadMessage, invokeSendMessage, in
<PaymentlinkBtn /> <PaymentlinkBtn />
<SnippestBtn /> <SnippestBtn />
<ShortlinkBtn />
{/* <Button type='text' className='' icon={<YoutubeOutlined />} size={'middle'} /> {/* <Button type='text' className='' icon={<YoutubeOutlined />} size={'middle'} />
<Button type='text' className='' icon={<AudioOutlined />} size={'middle'} /> */} <Button type='text' className='' icon={<AudioOutlined />} size={'middle'} /> */}

@ -4,11 +4,11 @@ import { DownOutlined, DollarOutlined, ExpandAltOutlined, ExpandOutlined, SendOu
import EmailEditorPopup from './EmailEditorPopup' import EmailEditorPopup from './EmailEditorPopup'
import useStyleStore from '@/stores/StyleStore' import useStyleStore from '@/stores/StyleStore'
import useAuthStore from '@/stores/AuthStore' import useAuthStore from '@/stores/AuthStore'
// import { isEmpty, } from '@haina/utils-commons'; // import { isEmpty, } from '@/utils/commons';
import useConversationStore from '@/stores/ConversationStore' import useConversationStore from '@/stores/ConversationStore'
import { useOrderStore } from '@/stores/OrderStore' import { useOrderStore } from '@/stores/OrderStore'
import { EditIcon } from '@/components/Icons' import { EditIcon } from '@/components/Icons'
import { cloneDeep, isEmpty } from '@haina/utils-commons' import { cloneDeep, isEmpty } from '@/utils/commons'
import { v4 as uuid } from 'uuid' import { v4 as uuid } from 'uuid'
import { postSendEmail } from '@/actions/EmailActions' import { postSendEmail } from '@/actions/EmailActions'
import { sentMsgTypeMapped, } from '@/channel/bubbleMsgUtils'; import { sentMsgTypeMapped, } from '@/channel/bubbleMsgUtils';
@ -258,7 +258,7 @@ const EmailComposer = ({ ...props }) => {
<Alert message="账户没有配置邮箱地址" description='请 重新登录 获取最新配置' type="warning" showIcon className=' absolute top-0 left-0 right-0 bottom-0' /> <Alert message="账户没有配置邮箱地址" description='请 重新登录 获取最新配置' type="warning" showIcon className=' absolute top-0 left-0 right-0 bottom-0' />
} }
{/* <EmailEditorPopup <EmailEditorPopup
{...{ open, setOpen }} {...{ open, setOpen }}
fromEmail={fromEmail} fromEmail={fromEmail}
fromUser={fromUser} fromUser={fromUser}
@ -270,7 +270,7 @@ const EmailComposer = ({ ...props }) => {
customerDetail={customerDetail} customerDetail={customerDetail}
action='new' action='new'
key={'email-new-editor-popup'} key={'email-new-editor-popup'}
/> */} />
</ConfigProvider> </ConfigProvider>
) )
} }

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

@ -5,7 +5,7 @@ import PropTypes from 'prop-types';
import useAuthStore from '@/stores/AuthStore'; import useAuthStore from '@/stores/AuthStore';
import useConversationStore from '@/stores/ConversationStore'; import useConversationStore from '@/stores/ConversationStore';
import { SendOutlined, CloseCircleOutlined, LoadingOutlined, FileOutlined } from '@ant-design/icons' import { SendOutlined, CloseCircleOutlined, LoadingOutlined, FileOutlined } from '@ant-design/icons'
import { isEmpty, } from '@haina/utils-commons'; import { isEmpty, } from '@/utils/commons';
import { v4 as uuid } from 'uuid'; import { v4 as uuid } from 'uuid';
import { sentMsgTypeMapped, whatsappSupportFileTypes, uploadProgressSimulate, WABAccountsMapped } from '@/channel/bubbleMsgUtils'; import { sentMsgTypeMapped, whatsappSupportFileTypes, uploadProgressSimulate, WABAccountsMapped } from '@/channel/bubbleMsgUtils';
import { OSS_URL as aliOSSHost, DEFAULT_WABA } from '@/config'; import { OSS_URL as aliOSSHost, DEFAULT_WABA } from '@/config';

@ -4,7 +4,7 @@ import { FileAddOutlined } from '@ant-design/icons';
import { v4 as uuid } from 'uuid'; import { v4 as uuid } from 'uuid';
import { API_HOST, OSS_URL as aliOSSHost } from '@/config'; import { API_HOST, OSS_URL as aliOSSHost } from '@/config';
import { whatsappSupportFileTypes, uploadProgressSimulate } from '@/channel/bubbleMsgUtils'; import { whatsappSupportFileTypes, uploadProgressSimulate } from '@/channel/bubbleMsgUtils';
import { isEmpty, sanitizeFilename } from '@haina/utils-commons'; import { isEmpty, sanitizeFilename } from '@/utils/commons';
// import useConversationStore from '@/stores/ConversationStore'; // import useConversationStore from '@/stores/ConversationStore';
const ImageUpload = ({ disabled, invokeUploadFileMessage, invokeSendUploadMessage }) => { const ImageUpload = ({ disabled, invokeUploadFileMessage, invokeSendUploadMessage }) => {

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

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save