Commit d2b53e6d by 杨铁龙

run ok

parent 5e70c8d1
......@@ -71,7 +71,7 @@
private setting = 0;
private get hasInput() {
return this.isChatMember && this.chatError !== this.chatId;
return true;
}
@Provide() showReadSummary = true;
......@@ -156,10 +156,10 @@
this.setting = setTimeout(
() =>
this.currentChat &&
Chat.setRead(
this.currentChat.model_name,
this.currentChat.obj_id
),
// Chat.setRead(
// this.currentChat.model_name,
// this.currentChat.obj_id
// ),
300
);
this.$emit("send");
......
......@@ -3,7 +3,7 @@ import { parserMessage } from ".";
import { chatStore, ChatStore } from "@/customer-service/store/model";
import { formatTime, TimeFormatRule } from "@/customer-service/utils/time";
import { Chat as ChatItem } from "@/customer-service/xim/models/chat";
import { ChatUserInfoService } from "@/customer-service/utils/user-info";
// import { ChatUserInfoService } from "@/customer-service/utils/user-info";
@Component({ components: {} })
export default class ChatList extends Vue {
......@@ -68,9 +68,9 @@ export default class ChatList extends Vue {
if (this.userNames[data.last_msg_sender] === undefined) {
const id = data.last_msg_sender;
this.updateUserName({ id, name: "" });
ChatUserInfoService.getUserInfo(id).then((d) =>
this.updateUserName({ id, name: d.alias_name || d.name })
);
// ChatUserInfoService.getUserInfo(id).then((d) =>
// this.updateUserName({ id, name: d.alias_name || d.name })
// );
}
}
if (data.last_msg_content === "") {
......
......@@ -53,15 +53,15 @@ export function parserMessage(type: MessageType, rawMsg: string) {
export function rebuildImage(url: string, w = 300) {
if (url) {
const sdk = Chat.getSdk();
const s = sdk.mediaController.buildThumbnail;
if (fsImg.test(url)) {
const m = fsImg.exec(url);
if (m && m.length) {
return sdk.global.baseUrl + s(m[0], w);
}
}
return url;
// const sdk = Chat.getSdk();
// const s = sdk.mediaController.buildThumbnail;
// if (fsImg.test(url)) {
// const m = fsImg.exec(url);
// if (m && m.length) {
// return sdk.global.baseUrl + s(m[0], w);
// }
// }
// return url;
}
return "";
}
......@@ -10,7 +10,7 @@
import { Component, Ref, Vue, Watch } from "vue-property-decorator";
import ChatInput, { isFileElement, isImageOrFile } from "./hybrid-input.vue";
import { MessageType } from "../model";
import { uploadFile } from "../service/upload";
// import { uploadFile } from "../service/upload";
import xim from "../xim/xim";
import Chat from "../xim";
import { ChatStore, chatStore } from "@/customer-service/store/model";
......@@ -128,40 +128,40 @@
};
img.remove();
}
return uploadFile(
file,
(p: number) =>
type === MessageType.File &&
this.chatInput &&
this.chatInput.updateUploadProgress(p)
)
.then((r) => {
if (r) {
const msg = {
url: r,
name: file.name,
size: file.size,
};
if (this.source) {
Object.assign(msg, { source: this.source });
}
if (w && h) {
Object.assign(msg, { w, h });
}
this.sendMsg({
msgType: type,
msg: JSON.stringify(msg),
});
URL.revokeObjectURL(src.url);
}
})
.catch(() => {
Chat.error("发送文件失败");
this.chatInput &&
this.chatInput.updateUploadProgress(0);
});
// return uploadFile(
// file,
// (p: number) =>
// type === MessageType.File &&
// this.chatInput &&
// this.chatInput.updateUploadProgress(p)
// )
// .then((r) => {
// if (r) {
// const msg = {
// url: r,
// name: file.name,
// size: file.size,
// };
// if (this.source) {
// Object.assign(msg, { source: this.source });
// }
// if (w && h) {
// Object.assign(msg, { w, h });
// }
// this.sendMsg({
// msgType: type,
// msg: JSON.stringify(msg),
// });
// URL.revokeObjectURL(src.url);
// }
// })
// .catch(() => {
// Chat.error("发送文件失败");
// this.chatInput &&
// this.chatInput.updateUploadProgress(0);
// });
}
}
}
......
......@@ -158,13 +158,13 @@
import ActionMessage from "./message-item/action-message.vue";
import WithdrawMessage from "./message-item/withdraw-message.vue";
import PurchasePlanMessage from "./message-item/purchase-plan-message.vue";
import MyWelfareMessage from "./message-item/my-welfare-message.vue";
import QuestionAnswerMessage from "./message-item/question-answer-message.vue";
import PositionMessage from "./message-item/position-message.vue";
import PayMessage from "./message-item/pay-message.vue";
// import MyWelfareMessage from "./message-item/my-welfare-message.vue";
// import QuestionAnswerMessage from "./message-item/question-answer-message.vue";
// import PositionMessage from "./message-item/position-message.vue";
// import PayMessage from "./message-item/pay-message.vue";
import NotifyMessage from "./message-item/notify-message.vue";
import { ChatRole } from "@/customer-service/model";
import { ChatUserInfoService, getUserMapping } from "../utils/user-info";
// import { ChatUserInfoService, getUserMapping } from "../utils/user-info";
import Xim from "@/customer-service/xim";
import { CustomerServiceEvent, MessageEvent } from "../event";
import { PayMessageBody } from "../xim/models/chat";
......@@ -204,12 +204,12 @@
TextMessage,
WithdrawMessage,
PurchasePlanMessage,
MyWelfareMessage,
QuestionAnswerMessage,
// MyWelfareMessage,
// QuestionAnswerMessage,
ActionMessage,
PayMessage,
// PayMessage,
NotifyMessage,
PositionMessage,
// PositionMessage,
},
})
export default class Message extends Vue {
......@@ -382,7 +382,7 @@
const o = +this.messageBody.eid;
const m1 = o === +this.chatMyId;
if (m1 && Xim.isBackend() && this.messageBody.oid) {
return +this.messageBody.oid === +Xim.getOrgId();
return false;
}
return m1;
}
......@@ -424,14 +424,14 @@
}
private get avatar() {
const mapping = getUserMapping();
// const mapping = getUserMapping();
if (this.data) {
const value = mapping[this.data.eid];
if (value && value.icon) {
return value.icon;
}
}
// if (this.data) {
// const value = mapping[this.data.eid];
// if (value && value.icon) {
// return value.icon;
// }
// }
return this.refetchUserIcon;
}
......@@ -574,21 +574,21 @@
}
private refetchUsername4Message() {
if (this.data && this.data.eid) {
ChatUserInfoService.getUserInfo(this.data.eid).then((r) => {
if (r) {
if (Xim.isBackend() && r.alias_name) {
this.refetchUsername = `${r.alias_name}(${
r.name || r.phone
})`;
} else {
this.refetchUsername =
r.alias_name || r.name || r.phone;
}
r.icon && (this.refetchUserIcon = r.icon);
}
});
}
// if (this.data && this.data.eid) {
// ChatUserInfoService.getUserInfo(this.data.eid).then((r) => {
// if (r) {
// if (Xim.isBackend() && r.alias_name) {
// this.refetchUsername = `${r.alias_name}(${
// r.name || r.phone
// })`;
// } else {
// this.refetchUsername =
// r.alias_name || r.name || r.phone;
// }
// r.icon && (this.refetchUserIcon = r.icon);
// }
// });
// }
}
private onHover() {
......
......@@ -58,7 +58,7 @@
import avatar from "@/customer-service/components/avatar.vue";
import { ChatStore } from "@/customer-service/store/model";
import xim from "@/customer-service/xim/xim";
import { ChatUserInfoService } from "../utils/user-info";
// import { ChatUserInfoService } from "../utils/user-info";
const chatStoreNamespace = namespace("chatStore");
......@@ -113,57 +113,56 @@
}
private async getUserNameByid(eid: string) {
const data = await ChatUserInfoService.getUserInfo(eid);
return data.name;
// const data = await ChatUserInfoService.getUserInfo(eid);
// return data.name;
}
private async getReader() {
if (this.chatId == null) return;
if (this.msgId == null) return;
const data = await xim.fetchMsgInBox(this.chatId, this.msgId);
if (data == null) return;
const readerlist = this.uniqueReaderList(
data.args[0] as dto.OneWhoReadMessage[]
);
this.readlist = await Promise.all(
readerlist
.filter((k) => k.is_read)
.filter((k) => k.eid !== this.chatMyId)
.map(async (k) => {
const eid = k.eid;
const name = await this.getUserNameByid(eid);
return {
eid,
name,
avatar: "",
};
})
);
if (!this.readlist.length) {
this.tab = 2;
}
this.unreadlist = await Promise.all(
readerlist
.filter((k) => !k.is_read)
.filter((k) => k.eid !== this.chatMyId)
.map(async (k) => {
const eid = k.eid;
const name = await this.getUserNameByid(eid);
return {
eid,
name,
avatar: "",
};
})
);
if (!this.unreadlist.length) {
this.updateMessage({
chat: this.chatId,
start: this.msgId,
all: true,
});
}
// if (this.chatId == null) return;
// if (this.msgId == null) return;
// const data = await xim.fetchMsgInBox(this.chatId, this.msgId);
// if (data == null) return;
// const readerlist = this.uniqueReaderList(
// data.args[0] as dto.OneWhoReadMessage[]
// );
// this.readlist = await Promise.all(
// readerlist
// .filter((k) => k.is_read)
// .filter((k) => k.eid !== this.chatMyId)
// .map(async (k) => {
// const eid = k.eid;
// const name = await this.getUserNameByid(eid);
// return {
// eid,
// name,
// avatar: "",
// };
// })
// );
// if (!this.readlist.length) {
// this.tab = 2;
// }
// this.unreadlist = await Promise.all(
// readerlist
// .filter((k) => !k.is_read)
// .filter((k) => k.eid !== this.chatMyId)
// .map(async (k) => {
// const eid = k.eid;
// const name = await this.getUserNameByid(eid);
// return {
// eid,
// name,
// avatar: "",
// };
// })
// );
// if (!this.unreadlist.length) {
// this.updateMessage({
// chat: this.chatId,
// start: this.msgId,
// all: true,
// });
// }
}
private uniqueReaderList(data: dto.OneWhoReadMessage[]) {
......
import type { UniplatSdk } from "uniplat-sdk";
export * from "./order";
export * from "./order-product";
// export * from "./order";
// export * from "./order-product";
export const enum ChatRole {
Default = 25,
......@@ -46,31 +46,15 @@ export const enum ServiceType {
Backend,
}
export const enum ImEnvironment {
Dev = 1,
Stage,
Pro,
}
export const socketMapping = new Map<ImEnvironment, string>([
[ImEnvironment.Dev, "ws://hro.channel.jinsehuaqin.com:8080/ws"],
[ImEnvironment.Stage, "wss://pre-channel.qinqinxiaobao.com/ws"],
[ImEnvironment.Pro, "wss://channel.qinqinxiaobao.com/ws"],
]);
export type TokenStringGetter = () => Promise<string>;
export interface ChatOption {
/**
* IM 链接,如果使用系统配置,只需要传入环境标识即可,如果默认配置不满足,可以传入指定地址
*/
connection: ImEnvironment | string;
sdk: () => UniplatSdk;
orgId: () => string | number;
connection: string;
product?: CustomerServiceProduct;
token: string;
/**
* 用于标记会话启动是在客户端(用户)还是服务端(后端)
......
import { Chat } from "../xim/models/chat";
import { GeneralOrderDirection } from './order-product';
import { action } from 'uniplat-sdk';
export interface ChatGroup extends Chat {
children?: ChatGroup[];
}
export const enum OrderStatus {
None,
Waiting,
Progressing,
Finished,
Failed,
UserCancelled,
AdminCancelled,
Deleted,
}
export const statusMapping = new Map<OrderStatus, string>([
[OrderStatus.None, ""],
[OrderStatus.Waiting, "等待处理"],
[OrderStatus.Progressing, "处理中"],
[OrderStatus.Finished, "已完成"],
[OrderStatus.Failed, "处理失败"],
[OrderStatus.UserCancelled, "已取消"],
[OrderStatus.AdminCancelled, "已取消"],
[OrderStatus.Deleted, "已删除"],
]);
export interface OrderTableListItem {
id: string;
v: number;
no: string;
title: string;
time: string;
chat: number;
status: OrderStatus;
status_label: string;
editTitle: string;
remark: string;
/**
* 待支付金额
*/
PayAmount: number;
/**
* 已支付金额
*/
PaidAmount: number;
/**
* 待退款金额
*/
RefundAmount: number;
/**
* 已退款金额
*/
RefundedAmount: number;
chatTypeCode: string;
lastMsgContent: string;
lastMsgTime: string;
unreadCount: number;
logo?: string;
orderId?: string;
/**
* 付款笔数
*/
PayPaymentNum?: string | number;
product: GeneralOrderDirection;
}
export const orderPredict = {
id: "ID",
v: "uniplat_version",
no: "OrderDocNo",
title: "ProductId#product.OuterName",
editTitle: "Title",
status: "Status_label",
remark: "Remark",
time: "CreatedDate",
PayAmount: "PayAmount",
PaidAmount: "PaidAmount",
RefundAmount: "RefundAmount",
RefundedAmount: "RefundedAmount",
chat: "UniplatImChatId",
chatTypeCode: "UniplatChatTypeCode",
lastMsgContent: "UniplatLastMsgContent",
lastMsgTime: "UniplatLastMsgTime",
unreadCount: 0,
PayPaymentNum: "PayPaymentNum",
product: 'ProductId#product.Code'
};
export const enum PayStatus {
UnPay = 1,
Paied,
Cancel,
Deleted,
WaitRefund,
Refund,
}
export const payStatusMapping = new Map<PayStatus, string>([
[PayStatus.UnPay, "待支付"],
[PayStatus.Paied, "已支付"],
[PayStatus.Cancel, "已取消"],
[PayStatus.Deleted, "已删除"],
[PayStatus.WaitRefund, "待退费"],
[PayStatus.Refund, "已退费"],
]);
export const cardPayStatusMapping = new Map<PayStatus, string>([
[PayStatus.UnPay, "待转账"],
[PayStatus.Paied, "已转账"],
]);
export const enum PayMethod {
CardTransfer = 1,
Balance,
Refund2Card,
Refund2Balance,
}
export const payMethodMapping = new Map<PayMethod, string>([
[PayMethod.CardTransfer, "银行卡转账"],
[PayMethod.Balance, "余额扣费"],
[PayMethod.Refund2Card, "退款至银行卡"],
[PayMethod.Refund2Balance, "退款至余额"],
]);
export interface OrderPayItem {
id: number;
v: number;
title: string;
time: string;
dueTime: string;
value: number;
status: PayStatus;
method: PayMethod;
method_label: string;
type: string;
desc: string;
agent: string;
createdTime: string;
actions?: action[];
bankAccountName?: string;
OpenningBankName?: string;
bankAccountNo?: string;
paymentItemId?: number;
paymentDate: string;
}
export interface OrderComment {
id: number;
content: string;
user: string;
attachment: string;
attachment_label: string;
time: string;
}
export const orderPayItemPredict = {
status: "Status",
time: "PaymentDate",
dueTime: "PaymentDueDate",
method: "PaymentFunction_label",
type: "ItemName",
desc: "PaymentDesc",
agent: "ProviderCollectId#provider_all_agent.AgentTrueName",
id: "ID",
v: "uniplat_version",
title: "ItemName",
value: "Amount",
createdTime: "CreatedDate",
bankAccountName: "ProviderHandleId#ServiceProviderBank.AccountName",
OpenningBankName: "ProviderHandleId#ServiceProviderBank.OpenningBankName",
bankAccountNo: "ProviderHandleId#ServiceProviderBank.AccountNo",
paymentItemId: "PaymentItemId",
paymentDate: "PaymentDate",
};
export const enum ChatOpenDirection {
/**
* 通知外壳,打开一个新的Webview容器打开会话
*/
NewWebview,
/**
* 直接会用当前Webview,跳转到聊天页面
*/
Current,
}
export const enum SrcPlatform {
Backend = 1,
Website,
H5,
OtherApp,
QqxbApp,
}
export const enum OperationType {
User = 1,
Backend,
}
export interface UploadImageItem {
id: number;
v: number;
url: string;
fileName: string;
time: string;
fileSize: number;
}
import { UniplatSdk } from "uniplat-sdk";
// import { UniplatSdk } from "uniplat-sdk";
export const enum BenefitServiceName {
CompanyApi = 'company_api'
}
// export const enum BenefitServiceName {
// CompanyApi = 'company_api'
// }
export const enum BenefitApiName {
Home = 'home_data',
AccountVerify = 'account_pay_need_verify_setting',
AccountData = 'account_data',
GetWaitInvoiceFeeType = 'get_wait_invoice_fee_type',
ConfirmVoucherData = 'confirm_voucher_data',
UnitPivot = "unit_pivot",
UnitEmployeePivot = 'unit_employee_pivot'
}
// export const enum BenefitApiName {
// Home = 'home_data',
// AccountVerify = 'account_pay_need_verify_setting',
// AccountData = 'account_data',
// GetWaitInvoiceFeeType = 'get_wait_invoice_fee_type',
// ConfirmVoucherData = 'confirm_voucher_data',
// UnitPivot = "unit_pivot",
// UnitEmployeePivot = 'unit_employee_pivot'
// }
export class BenefitInvoker {
private static readonly subProject = 'welfare_v2';
private static readonly unsetupError = '服务尚未初始化';
private static sdk: UniplatSdk | null = null;
// export class BenefitInvoker {
// private static readonly subProject = 'welfare_v2';
// private static readonly unsetupError = '服务尚未初始化';
// private static sdk: UniplatSdk | null = null;
public static setup(sdk: UniplatSdk) {
this.sdk = sdk;
return this;
}
// public static setup(sdk: UniplatSdk) {
// this.sdk = sdk;
// return this;
// }
public static get<T>(service: BenefitServiceName, api: BenefitApiName) {
if (this.sdk) {
return this.sdk.domainService(this.subProject, service, api).request<{}, {}, T>('get');
}
return Promise.reject(this.unsetupError);
}
// public static get<T>(service: BenefitServiceName, api: BenefitApiName) {
// if (this.sdk) {
// return this.sdk.domainService(this.subProject, service, api).request<{}, {}, T>('get');
// }
// return Promise.reject(this.unsetupError);
// }
public static post<T>(service: BenefitServiceName, api: BenefitApiName, data?: any) {
if (this.sdk) {
return this.sdk.domainService(this.subProject, service, api).request<{}, {}, T>('post', { data });
}
return Promise.reject(this.unsetupError);
}
}
// public static post<T>(service: BenefitServiceName, api: BenefitApiName, data?: any) {
// if (this.sdk) {
// return this.sdk.domainService(this.subProject, service, api).request<{}, {}, T>('post', { data });
// }
// return Promise.reject(this.unsetupError);
// }
// }
export * from "./upload"
\ No newline at end of file
// export * from "./upload"
import Axios, { AxiosResponse, AxiosAdapter } from "axios";
import { UniplatSdk } from "uniplat-sdk";
import { ImEnvironment } from "../model";
import { devAppTools } from '../database/dev-tools';
export const enum Product {
Default = "default",
QqxbWeixin = "qqxb-weixin",
QqxbApp = "qqxb-app",
Fulibao = "fulibao",
HrManager = "hr-manager",
Hrs100 = "hrs100",
HrsApp = "hrs-app",
BiJie = "bi-jie",
Cashier = "cashier",
Uniplat = "uniplat",
DeShengJiuYeBao = "de-sheng-jiu-ye-bao",
}
const enum ProductTable {
Default = "",
Login = "login",
Error = "error",
}
export interface SdkMonitorOption {
userAgent?: boolean;
envir: ImEnvironment;
product: Product;
call?: (r: any) => void;
}
class WebMonitor {
private key = "";
private envir = ImEnvironment.Dev;
private product = Product.Default;
private readonly url = "https://pre-hrs-monitor.hrs100.com";
private adapter: AxiosAdapter | undefined;
public updateKey(key: string) {
this.key = key;
return this;
}
private buildHeaders() {
return {
headers: { authorization: "cdd0a34e-f537-4e5b-808e-2ba06af21845" },
adapter: this.adapter,
};
}
private enable() {
return this.envir !== ImEnvironment.Dev;
}
private envirString() {
if (this.envir === ImEnvironment.Dev) {
return "[Dev]";
}
if (this.envir === ImEnvironment.Stage) {
return "[Stage]";
}
return "";
}
public log(msg: any) {
return Axios.post(
this.url,
{
type: ProductTable.Login,
product: this.product,
msg: `${this.envirString()} ${msg} `,
key: this.key,
},
this.buildHeaders()
);
}
public error(msg: any) {
return this.enable() && Axios.post(
this.url,
{
type: ProductTable.Error,
product: this.product,
msg: `${this.envirString()} ${msg} `,
key: this.key,
},
this.buildHeaders()
);
}
public useSdk(
sdk: UniplatSdk,
options: SdkMonitorOption,
adapter?: AxiosAdapter
) {
this.envir = options.envir;
this.product = options.product;
this.adapter = adapter;
sdk.events.addUniversalErrorResponseCallback(
(r: AxiosResponse<any>) => {
options.call && options.call(r);
if (this.enable()) {
const msg: string[] = [];
msg.push(
`URL: ${decodeURIComponent(r.config.url as string)}`
);
msg.push(`Token: ${sdk.global.jwtToken}`);
const header = r.config.headers;
if (header) {
msg.push(`CurrentOrg: ${header.CurrentOrg}`);
msg.push(`Scenes: ${header.Scenes}`);
}
options &&
options.userAgent &&
msg.push(`UserAgent: ${window.navigator.userAgent}`);
r.config &&
r.config.params &&
msg.push(`Params: ${JSON.stringify(r.config.params)}`);
if (r.config && r.config.data) {
const form = r.config.data as FormData;
if (form.getAll) {
const p = form.getAll("parameters");
for (const item of p) {
msg.push(`Payload: ${item}`);
}
} else {
msg.push(
`Payload: ${JSON.stringify(r.config.data)}`
);
}
}
msg.push(`Location: ${window.location.href}`);
msg.push(
`Exception: ${(
(r.data.error as string) || ""
).substring(0, 500)}`
);
r && r.config && this.error(msg.join("\n"));
}
}
);
this.enable() && this.auditorLogin(sdk);
}
private auditorLogin(sdk: UniplatSdk) {
const name = this.key || sdk.global.username || sdk.global.uid;
const now = new Date();
const ts = `login-${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
devAppTools.getDataByKey(ts).then(r => {
const execute = () => {
devAppTools.addData(now.valueOf(), ts);
this.log(`用户 ${name}${now.valueOf()} 登录过,设备 ${window.navigator.userAgent}`);
};
if (r) {
const v = +r;
if (now.valueOf() - v > 60 * 60 * 1000) {
execute();
}
} else {
execute();
}
})
}
}
export const monitor = new WebMonitor();
import Chat from "@/customer-service/xim";
import { metaRow, UniplatSdkExtender, UniplatSdk } from "uniplat-sdk";
import {
OperationType,
OrderStatus,
OrderTableListItem,
orderPredict,
SrcPlatform,
OrderPayItem,
UploadImageItem,
orderPayItemPredict,
OrderComment,
PayStatus,
} from "../model";
import { GeneralOrderDirection } from "../model/order-product";
class OrderService {
public readonly generalOrder = "general_order_info";
public readonly generalOrderPaymentModel = "general_order_payment_info";
public readonly generalOrderDefaultDetailName = "userOrderDetail";
private readonly commentModel = "uniplat_model_remark@general_order";
private readonly fileModel = "general_order_payment_file_info";
private readonly handler = new UniplatSdkExtender();
private innerSdk: UniplatSdk | null = null;
public injectSdk(sdk: UniplatSdk) {
this.innerSdk = sdk;
return this;
}
private getSdk() {
return this.innerSdk || Chat.getSdk();
}
public openOrder(params: {
productCode: string;
srcPlatform: SrcPlatform;
createdType: OperationType;
/**
* 是否强制开启新订单,默认如果有已存在处理中的订单时会直接返回
*/
forceNewOrder?: boolean;
}) {
return this.getSdk()
.model(this.generalOrder)
.action(params.forceNewOrder ? "addOrder" : "getOrAddOrder")
.addInputs_parameter({
ProductCode: params.productCode,
SrcPlatform: params.srcPlatform,
CreatedType: params.createdType,
})
.execute();
}
public updateOrderStatus(
id: number | string,
v: number,
status: OrderStatus
) {
return this.getSdk()
.model(this.generalOrder)
.action("editStatus")
.addInputs_parameter({
Status: status,
userType: OperationType.User,
})
.updateInitialParams({ selected_list: [{ v, id: +id }] })
.execute();
}
/** 专项工单 */
public getOrders(
params: {
productCode?: GeneralOrderDirection;
index: number;
size?: number;
},
isHrs = false
) {
const list = this.getSdk()
.model(this.generalOrder)
.list(isHrs ? "hroOrgOrderList" : "userOrderList");
if (params.productCode) {
list.addPrefilter({ "ProductId#product.Code": params.productCode });
}
return list
.query({ item_size: params.size || 100, pageIndex: params.index })
.then((r) => {
return {
total: r.pageData.record_count,
list: this.handler.buildRows<OrderTableListItem>(
r.pageData.rows,
orderPredict
),
};
});
}
public getProcessOrders(params: {
productCode?: GeneralOrderDirection;
index: number;
size?: number;
}) {
const list = this.getSdk()
.model(this.generalOrder)
.list("hroOrgDoingOrderList");
if (params.productCode) {
list.addPrefilter({ "ProductId#product.Code": params.productCode });
}
return list
.query({ item_size: params.size || 100, pageIndex: params.index })
.then((r) => {
return {
total: r.pageData.record_count,
list: this.handler.buildRows<OrderTableListItem>(
r.pageData.rows,
orderPredict
),
};
});
}
/**
* 获取订单支付记录
* @param id 订单id
* @param withActions 是否获取行数据中action条目
*/
public getPayments(id: number, withActions = false) {
return this.getSdk()
.model(orderService.generalOrderPaymentModel)
.list(withActions ? "" : "userOrderPaymentList")
.addPrefilter({ OrderId: id })
.query({ pageIndex: 1, item_size: 100 })
.then((r) => {
if (r && r.pageData && r.pageData.rows) {
let items = this.handler.buildRows<OrderPayItem>(
r.pageData.rows,
orderPayItemPredict
);
if (!withActions) {
items = items.filter(
(i) =>
i.status !== PayStatus.Deleted &&
i.status !== PayStatus.Cancel
);
}
if (withActions) {
for (let i = 0; i < r.pageData.rows.length; i++) {
r.pageData &&
r.pageData.rows &&
r.pageData.rows[i] &&
items[i] &&
(items[i].actions = r.pageData.rows[i].actions);
}
}
return items;
}
return [];
});
}
public getPayment(id: string | number) {
return this.getSdk()
.model(orderService.generalOrderPaymentModel)
.detail(id as string, "userOrderPaymentDetail")
.query()
.then((r) =>
this.handler.buildRow<OrderPayItem>(r.row, orderPayItemPredict)
);
}
public addImage4Payment(payment: number | string, v: number, path: string) {
return this.getSdk()
.model(orderService.generalOrderPaymentModel)
.action("addImages")
.updateInitialParams({
selected_list: [{ v, id: payment as number }],
})
.addInputs_parameter({ images: path })
.execute();
}
public getImages4Payment(payment: number) {
return this.getSdk()
.model(this.fileModel)
.list()
.addPrefilter({ PaymentId: payment })
.query({ item_size: 10, pageIndex: 1 })
.then((r) =>
this.handler.buildRows<UploadImageItem>(r.pageData.rows, {
time: "CreatedDate",
fileSize: "FileSize",
fileName: "FileName",
url: "Url",
id: "ID",
v: "uniplat_version",
})
);
}
public deleteImage(payment: number, image: number, v: number) {
return this.getSdk()
.model(this.fileModel)
.action("delete")
.updateInitialParams({
selected_list: [{ v, id: image }],
prefilters: [{ property: "PaymentId", value: payment }],
})
.execute();
}
public buildOrder(o: metaRow) {
return this.handler.buildRow<OrderTableListItem>(o, orderPredict);
}
/** 设置备注 */
public setRemark(
id: string,
v: number,
data: { Title: string; Remark: string }
) {
return this.getSdk()
.model(this.generalOrder)
.action("editTitle")
.updateInitialParams({ selected_list: [{ v, id: +id }] })
.addInputs_parameter(data)
.execute();
}
public getOrderDetail(id: number | string) {
return this.getSdk()
.model(this.generalOrder)
.detail(id as string)
.query();
}
public sendPayAccountInfo(params: { send: string; type?: number }) {
return this.getSdk()
.domainService("hro_spview", "OrderSetting", "sendPayAccountInfo")
.request("get", { params });
}
public sendPayAccountInfoForAgent(params: {
send: string;
userOrderPaymentId: number;
}) {
return this.getSdk()
.domainService(
"hro_spview",
"OrderSetting",
"sendPayAccountInfoForAgent"
)
.request("get", { params });
}
public getComments(order: number | string) {
return this.getSdk()
.model(orderService.commentModel)
.list("system_remark")
.addPrefilter({ associate_id: order })
.query({ pageIndex: 1, item_size: 100 })
.then((r) => {
if (r && r.pageData && r.pageData.rows) {
const items = this.handler.buildRows<OrderComment>(
r.pageData.rows,
{
id: "",
time: "create_time",
attachment: "attachments_label",
user: "dealer_name",
content: "",
}
);
return items;
}
return [];
});
}
}
export const orderService = new OrderService();
......@@ -4,7 +4,7 @@ import chat from "../xim/index";
export function buildConfig(token: string, url: string) {
if (url && url.includes("/general")) {
return { headers: { Authorization: token, CurrentOrg: chat.getOrgId() } };
return { headers: { Authorization: token } };
}
return { headers: { Authorization: token } };
}
......
import Axios from 'axios';
const enum Status {
Default,
Upgrading
}
export class UpgradeController {
public static getUpgradingRange() {
return Axios
.get<{ code: Status; start: string; end: string }>(
`https://serverstatus.qinqinxiaobao.com/v0/servicestatus/apiservice/status/?t=${new Date().valueOf()}`
).then(r => {
if (r && r.data && r.data.code === Status.Upgrading) {
return { start: r.data.start, end: r.data.end };
}
return { start: '', end: '' };
});
}
}
import Chat from "@/customer-service/xim";
export async function uploadFile(file: File, uploading?: (p: number) => void) {
const sdk = Chat.getSdk();
const { url } = await sdk.uploadFileV2(file, {
onUploadProgress: (e) => uploading && uploading(e.percent),
});
return `${sdk.global.baseUrl}${url}`;
}
export const enum UploadType {
Default,
Image,
Camera
}
/**
* x
* @param type UploadType 默认值 UploadType.Default
* @param size 可不传 单位M
* @returns
*/
export function chooseFileAndUpload(type = UploadType.Default, size?: number) {
return chooseFile(type).then(r => {
const sdk = Chat.getSdk();
return sdk.uploadFileV2(r)
})
}
/**
*
* @param type UploadType
* @param size 可不传 单位M
* @returns
*/
export function chooseFile(type = UploadType.Default, size?: number) {
return new Promise<File>((resolve, reject) => {
const target = document.createElement('input');
target.setAttribute('type', 'file');
// 添加这个属性,就可以唤起相机的功能
(type === UploadType.Camera) && target.setAttribute('capture', 'camera');
// 这里如果不加属性 accept 是 "image/*" 或者 "video/*",就默认打开摄像头,既可以拍照也可以录像
(type === UploadType.Image) && target.setAttribute('accept', 'image/*');
target.setAttribute('style', 'display:none');
// 监听改变事件
target.addEventListener('change', (e: Event) => {
// 拿到文件对象
if (e && e.target) {
const t = e.target as HTMLInputElement;
const { files } = t;
if (files) {
// 返回的是一个文件对象
if (size && files[0].size >= size * 1024 * 1024) {
reject(`上传的${type === UploadType.Default ? "文件" : "图片"}太大了~`);
return;
}
resolve(files[0]);
setTimeout(() => target.remove(), 200);
return;
}
}
reject(new Error('系统不支持'));
setTimeout(() => target.remove(), 200);
});
document.body.appendChild(target);
// 这里是模拟点击了input控件
target.click();
});
}
\ No newline at end of file
import Chat from "../xim";
import { orderService } from "../service/order";
// import { orderService } from "../service/order";
export type ChatInfo = {
[eid: string]: any;
......@@ -26,79 +26,79 @@ function buildCache() {
if (!model2DetailNameMapping.size) {
// 用户端默认不使用chat内置的detailName(这个专属于服务端),所以这里加一层内置转换
if (!Chat.isBackend()) {
model2DetailNameMapping.set(
orderService.generalOrder,
orderService.generalOrderDefaultDetailName
);
// model2DetailNameMapping.set(
// orderService.generalOrder,
// orderService.generalOrderDefaultDetailName
// );
}
}
}
export async function getChatModelInfo(
modelName: string,
id: string | number,
detailname?: string,
forceReload = false
) {
buildCache();
const detail = model2DetailNameMapping.get(modelName) || detailname;
const key = `${modelName}-${id}-${detail}`;
if (loadingKeys.has(key)) {
return new Promise<ChatModelInfoData>((resolve) =>
waitingAction.push({ key, resolve })
);
}
if (chatInfo[key] && !forceReload) {
const d = chatInfo[key];
if (d.row && d.row.UniplatChatId) {
return Promise.resolve({
uniplatId: d.row.UniplatChatId.value,
chat_id: +d.row.UniplatImChatId.value,
uniplat_version: 0,
data: d,
} as ChatModelInfoData);
}
}
loadingKeys.add(key);
const info = await Chat.getSdk()
.model(modelName)
.detail(id + "", detail)
.query();
const data = info;
info && info.row.UniplatChatId && (chatInfo[key] = data);
loadingKeys.delete(key);
const o = (
info.row && info.row.UniplatChatId
? {
uniplatId: info.row.UniplatChatId.value,
chat_id: +(info.row.UniplatImChatId.value as string),
uniplat_version: 0,
data,
}
: {
uniplatId: 0,
chat_id: 0,
uniplat_version: 0,
data,
}
) as ChatModelInfoData;
const removing = [];
for (const item of waitingAction) {
if (item.key === key) {
item.resolve(o);
removing.push(item.key);
}
}
for (const item of removing) {
waitingAction = waitingAction.filter((i) => i.key !== item);
}
return o;
}
// export async function getChatModelInfo(
// modelName: string,
// id: string | number,
// detailname?: string,
// forceReload = false
// ) {
// buildCache();
// const detail = model2DetailNameMapping.get(modelName) || detailname;
// const key = `${modelName}-${id}-${detail}`;
// if (loadingKeys.has(key)) {
// return new Promise<ChatModelInfoData>((resolve) =>
// waitingAction.push({ key, resolve })
// );
// }
// if (chatInfo[key] && !forceReload) {
// const d = chatInfo[key];
// if (d.row && d.row.UniplatChatId) {
// return Promise.resolve({
// uniplatId: d.row.UniplatChatId.value,
// chat_id: +d.row.UniplatImChatId.value,
// uniplat_version: 0,
// data: d,
// } as ChatModelInfoData);
// }
// }
// loadingKeys.add(key);
// const info = await Chat.getSdk()
// .model(modelName)
// .detail(id + "", detail)
// .query();
// const data = info;
// info && info.row.UniplatChatId && (chatInfo[key] = data);
// loadingKeys.delete(key);
// const o = (
// info.row && info.row.UniplatChatId
// ? {
// uniplatId: info.row.UniplatChatId.value,
// chat_id: +(info.row.UniplatImChatId.value as string),
// uniplat_version: 0,
// data,
// }
// : {
// uniplatId: 0,
// chat_id: 0,
// uniplat_version: 0,
// data,
// }
// ) as ChatModelInfoData;
// const removing = [];
// for (const item of waitingAction) {
// if (item.key === key) {
// item.resolve(o);
// removing.push(item.key);
// }
// }
// for (const item of removing) {
// waitingAction = waitingAction.filter((i) => i.key !== item);
// }
// return o;
// }
import { UniplatSdk } from "uniplat-sdk";
import Chat from "../xim";
export interface ChatUserSummaryInfo {
name: string;
phone: string;
......@@ -30,71 +27,3 @@ let waitingAction: {
key: string;
resolve: (d: ChatUserSummaryInfo) => void;
}[] = [];
export class ChatUserInfoService {
public static async getUserInfo(eid: string, sdk?: UniplatSdk) {
if (userMapping[eid]) {
return userMapping[eid];
}
if (!+eid || +eid < 0) {
return { name: "", phone: "", icon: "", alias_name: "" };
}
if (loadingKeys.has(eid)) {
return new Promise<ChatUserSummaryInfo>((resolve) =>
waitingAction.push({ key: eid, resolve })
);
}
loadingKeys.add(eid);
const info = await (sdk || Chat.getSdk())
.domainService(
"passport",
"anonymous",
`oidc.account/user_info?id=${eid}`
)
.request<any, any, UserInfo>("get");
const data = {
name: info.realname || info.username || info.mobile || info.mobile,
phone: info.mobile,
icon:
(info.avatar_url && decodeURIComponent(info.avatar_url)) || "",
alias_name: info.alias_name,
};
userMapping[eid] = data;
const removing = [];
for (const item of waitingAction) {
if (item.key === eid) {
item.resolve(data);
removing.push(item.key);
}
}
for (const item of removing) {
waitingAction = waitingAction.filter((i) => i.key !== item);
}
loadingKeys.delete(eid);
return data;
}
public static updateCache(uid: string, alias_name: string) {
const t = userMapping[uid];
t && (t.alias_name = alias_name);
}
public static setAliasName(
uid: string | number,
name: string,
sdk?: UniplatSdk
) {
return (sdk || Chat.getSdk())
.domainService("passport", "anonymous", `oidc.account/set_alias`)
.request<any, any, {}>("post", {
data: { id: uid, alias_name: name },
});
}
}
......@@ -8,8 +8,6 @@ import {
ServiceType,
CustomerServiceProduct,
ChatMessageController,
socketMapping,
ImEnvironment,
} from "./../model";
import { ChatLoggerService } from "./logger";
import tokenManager from "./token";
......@@ -17,11 +15,8 @@ import xim from "./xim";
import { dbController } from "../database";
class Chat {
private _sdk?: () => UniplatSdk;
private _orgId: () => string | number = () => "0";
private token!: TokenStringGetter;
private serviceType = ServiceType.Backend;
private product = CustomerServiceProduct.Default;
private serviceType = ServiceType.Frontend;
private eventHub: Vue | null = null;
private keywords: string[] = [];
private ws = "";
......@@ -48,40 +43,23 @@ class Chat {
`You must specify a web socket address for chat service`
);
}
this._sdk = option.sdk;
this._orgId = option.orgId;
option.serviceType !== undefined &&
(this.serviceType = option.serviceType);
option.product && (this.product = option.product);
this.eventHub = option.eventHub || null;
option.message && (this.messageController = option.message);
option.avatar !== undefined && (this.defaultAvatar = option.avatar);
if(!option.disabledIndexDb){
await this.setupIndexDb(option.orgId()).catch(err => {
// 必须catch error不然小程序不会向后运行
console.error("setupIndexDb Error")
});
}
this.token = async () => option.sdk().global.jwtToken;
// if (!option.disabledIndexDb) {
// await this.setupIndexDb("test").catch((err) => {
// // 必须catch error不然小程序不会向后运行
// console.error("setupIndexDb Error");
// });
// }
this.token = async () => option.token;
tokenManager.save(this.token);
EmojiService.raiseOnReady(this.token);
option
.sdk()
.events.addTokenChanged((token) =>
this.setToken(() => new Promise((resolve) => resolve(token)))
);
// this.keywords = ["社保"];
const path =
(socketMapping.get(option.connection as ImEnvironment) as string) ||
(option.connection as string);
return this.initChatSdk((this.ws = path)).finally(() => {
return this.initChatSdk((this.ws = option.connection)).finally(() => {
this.connected = true;
for (const item of this.connectedActions) {
item();
......@@ -89,32 +67,14 @@ class Chat {
});
}
private setupIndexDb(orgId: number | string) {
if (this._sdk) {
const s = this._sdk();
const key = `${s.global.uid}-${orgId || 0}`;
private setupIndexDb(key: string) {
return dbController.setup(key);
}
return Promise.reject();
}
public resetup(org: () => string | number) {
this._orgId = org;
xim.onConnected();
return this.setupIndexDb(org());
}
public unSetup() {
xim.close();
}
public getSdk = () => {
if (!this._sdk) {
throw new Error("sdk shouldn't undefined");
}
return this._sdk();
};
public getServiceType() {
return this.serviceType;
}
......@@ -123,14 +83,6 @@ class Chat {
return this.serviceType === ServiceType.Backend;
}
public getProduct() {
return this.product;
}
public getOrgId = () => {
return this._orgId();
};
public setToken(token: TokenStringGetter) {
return xim.setToken(token);
}
......@@ -158,7 +110,9 @@ class Chat {
if (xim.isConnected()) {
setTimeout(resolve, 200);
} else {
reject(new Error(`客服系统连接出现错误,请尝试刷新页面`));
reject(
new Error(`客服系统连接出现错误,请尝试刷新页面`)
);
}
});
});
......@@ -210,15 +164,6 @@ class Chat {
public getAvatar() {
return this.defaultAvatar;
}
public setRead(model: string, obj: string) {
if (this.isBackend()) {
const sdk = this.getSdk();
if (sdk) {
sdk.getAxios().post(`/general/xim/model/${model}/${obj}/read`);
}
}
}
}
export default new Chat();
import {
MessageHandled,
MessageType,
PayMethod,
PayStatus,
// PayMethod,
// PayStatus,
} from "@/customer-service/model";
export interface Chat {
......@@ -204,8 +204,8 @@ export type CommentForwardMessageBody = {
};
export interface PayMessageBody {
status: PayStatus;
paymentFunction: PayMethod;
// status: PayStatus;
// paymentFunction: PayMethod;
itemName: string;
amount: string;
paymentId: string;
......
......@@ -5,7 +5,6 @@ import { TokenStringGetter } from "./../model";
import { ChatLoggerService } from "./logger";
import { Message, NotifyMessage } from "./models/chat";
import chat from "./index";
import { STATUS } from "xchat-client/dist/xchat";
wampDebug(false);
......@@ -67,6 +66,7 @@ export class Xim {
this.close();
token().then((t) => {
console.log({ token: t });
if (!t) return;
const client = new XChatClient(url, this.trimToken(t));
this.client = client;
......@@ -173,9 +173,9 @@ export class Xim {
if (this.client == null) {
throw new Error("client shouldn't undefined");
}
if (p && !p.isMember && p.model && p.obj) {
return this.queryMessageWhenIsNotMember(p, limit, lid, rid, desc);
}
// if (p && !p.isMember && p.model && p.obj) {
// return this.queryMessageWhenIsNotMember(p, limit, lid, rid, desc);
// }
const res = await this.client.fetchChatMsgs(chatType, chatId, {
lid,
rid,
......@@ -185,24 +185,24 @@ export class Xim {
return res.args[0];
}
private queryMessageWhenIsNotMember(
p: { isMember: boolean; model: string; obj: string },
limit: number,
lid: number,
rid: number,
desc: boolean
) {
return chat
.getSdk()
.getAxios()
.get<any, Message[]>(
`/general/xim/model/${p.model}/${
p.obj
}/msgs?lid=${lid}&rid=${rid}&limit=${limit}&desc=${
desc ? 1 : 0
}`
);
}
// private queryMessageWhenIsNotMember(
// p: { isMember: boolean; model: string; obj: string },
// limit: number,
// lid: number,
// rid: number,
// desc: boolean
// ) {
// return chat
// .getSdk()
// .getAxios()
// .get<any, Message[]>(
// `/general/xim/model/${p.model}/${
// p.obj
// }/msgs?lid=${lid}&rid=${rid}&limit=${limit}&desc=${
// desc ? 1 : 0
// }`
// );
// }
private setMessagesRead(chatId: number, msg: Message[]) {
if (!msg.length) {
......@@ -371,7 +371,8 @@ export class Xim {
public onConnected() {
if (this.client == null) return;
// 连接成功后,需要调用pubUserInfo, 否则服务端会认为此连接无效
this.client.pubUserInfo(JSON.stringify({ org_id: chat.getOrgId() }));
// TODO
this.client.pubUserInfo(JSON.stringify({ org_id: 2 }));
this.debug("xim connected");
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment