| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693 |
- // var Parse = getApp().Parse;
- // var app = getApp()
- // const { wxLogin } = require('./utils/login')
- const CONFIG = require("config.js");
- let config = {
- appid: CONFIG.default.appid,
- company: CONFIG.default.company,
- rootPage: CONFIG.default.rootPage,
- }
- const plugin = requirePlugin('fm-plugin')
- const { Parse, checkAuth } = plugin
- Page({
- /**
- * 页面的初始数据
- */
- data: {
- splashUrl: wx.getStorageSync("enabledOptions")[0],
- loading:true
- },
- /**
- * 生命周期函数--监听页面加载
- */
- onLoad: async function (options) {
- // 拦截插件的"登录信息已过期"提示
- const originalShowModal = wx.showModal;
- wx.showModal = function(options) {
- // 如果是"登录信息已过期"的提示,改为友好的重新登录提示
- if (options.content && options.content.includes('登录信息过期')) {
- console.log('⚠️ 拦截到"登录信息已过期"提示,改为友好提示');
-
- return originalShowModal.call(this, {
- title: '提示',
- content: '登录状态异常,是否重新登录?',
- showCancel: true,
- cancelText: '取消',
- confirmText: '重新登录',
- success: (result) => {
- if (result.confirm) {
- // 清除登录状态
- wx.removeStorageSync("sessionToken");
- wx.removeStorageSync("userLogin");
-
- // 重新加载首页
- const rootPage = getApp().globalData.rootPage || getApp().globalData.defaultTabBar?.list?.[0]?.pagePath || '/pages/index/index';
- wx.reLaunch({
- url: rootPage
- });
- }
-
- // 调用原始的 success 回调
- if (options.success) {
- options.success(result);
- }
- }
- });
- }
-
- // 其他提示正常显示
- return originalShowModal.call(this, options);
- };
-
- wx.login({
- success: function (res) {
- if (res.code) {
- console.log(res);
- // wx.request({
- // url: "https://server.fmode.cn/api/wxapp/auth_wxapp",
- // data: {
- // c: getApp().globalData.company,
- // code: res.code,
- // },
- // async success(res) {
- // wx.setStorageSync("userInfo", res.data);
- // resolve(res)
- // },
- // });
- }
- },
- fail: function (err) {
- wx.showToast({
- title: '服务器繁忙,请稍后重试',
- })
- }
- });
- wx.setStorageSync("invite", null);
-
- // 处理扫码链接(options.q 包含完整的URL或activityId)
- if (options.q) {
- let str = decodeURIComponent(options.q); // 扫描二维码获得的跳转链接
- // 兼容一些环境中把 & 编码成 & 的情况,防止参数解析错误(如 scanCount=0&storeId=...)
- if (str.indexOf('&') !== -1) {
- console.log('🔧 检测到 URL 中包含 &,自动还原为 &');
- str = str.replace(/&/g, '&');
- }
-
- // 检查是否是员工邀请链接(app.fmode.cn/dev/pobingfeng/manager/staff?invite=xxx)
- if (str.includes('app.fmode.cn/dev/pobingfeng/manager/staff')) {
- let obj = this.getParaName(str);
- if (obj && obj.invite) {
- wx.setStorageSync("invite", obj.invite);
- console.log('✅ 检测到员工邀请链接,invite:', obj.invite);
- }
- // 员工邀请链接不需要跳转到店铺,直接返回
- this.setData({ options: options });
- plugin.init(config, wx.getStorageSync('invite'));
- return;
- }
-
- // 检查是否是活动海报二维码(activityId作为qrCode参数值)
- // 如果str不包含http/https,且看起来像是一个ID,则可能是activityId
- if (!str.includes('http://') && !str.includes('https://') && !str.includes('?')) {
- // 可能是活动ID,尝试作为activityId处理
- if (str && str.length > 0 && !isNaN(str)) {
- options.activityId = str;
- console.log('✅ 检测到活动海报二维码,activityId:', str);
- // 活动二维码需要特殊处理,先保存activityId
- wx.setStorageSync("activityId", str);
- }
- }
-
- // 处理店铺相关的二维码链接(pwa.fmode.cn/gomini/pmd/)
- // 从完整URL中提取参数
- if (str.includes('pwa.fmode.cn/gomini/pmd') || str.includes('?')) {
- let obj = this.getParaName(str);
- if (obj && obj.invite) {
- wx.setStorageSync("invite", obj.invite);
- }
- // 将所有参数合并到 options 中
- obj && Object.keys(obj).forEach(key=> options[key] = obj[key]);
- }
- }
- // 兼容从编译参数或页面直达传入的 storeId
- if (options && options.scene && !options.storeId) {
- try {
- const sceneStr = decodeURIComponent(options.scene)
- if (sceneStr) {
- const pairs = sceneStr.split('&')
- for (const p of pairs) {
- const [k, v] = p.split('=')
- if (k === 'storeId' && v) {
- options.storeId = v
- break
- }
- }
- }
- } catch (e) {
- console.warn('解析 scene 失败:', e)
- }
- }
- this.setData({
- options: options
- })
- let {
- time,
- dramaId,
- roomId,
- orderId,
- shopId,
- invite,
- activityId,
- company,
- inviteHost,
- storeId
- } = options
- time && wx.setStorageSync("time", time);
- dramaId && wx.setStorageSync("dramaId", dramaId);
- roomId && wx.setStorageSync("roomId", roomId);
- orderId && wx.setStorageSync("orderId", orderId);
- shopId && wx.setStorageSync("shopId", shopId);
- invite && wx.setStorageSync("invite", invite);
- activityId && wx.setStorageSync("activityId", activityId);
- inviteHost && wx.setStorageSync("inviteHost", true);
- if (storeId) {
- // 扫码进入时,强制设置店铺 ID,标记为扫码来源
- wx.setStorageSync('storeId', storeId)
- getApp().globalData.storeId = storeId
- wx.setStorageSync('storeId_from_scan', true)
- console.log('✅ 入口页扫码进入,已设置店铺 ID(优先级最高):', storeId)
- }
- if (company) getApp().globalData.toCompany = true;
-
- // 检查是否是扫码进入(需要统计扫码次数)
- this.checkAndHandleScan(options);
-
- plugin.init(config, wx.getStorageSync('invite'))
- },
- /**
- * 生命周期函数--监听页面初次渲染完成
- */
- onReady: async function () { },
- /**
- * 生命周期函数--监听页面显示
- */
- onShow: async function () {
- await this.review()
- },
- async review(force){
- try {
- let options = this.data.options
- let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath
- if (options) {
- let objArr = Object.keys(options)
- if (objArr && objArr.length > 0) {
- let parms = '?'
- objArr.forEach((o, index) => {
- if (index > 0) {
- parms += '&' + o + '=' + options[o]
- } else {
- parms += o + '=' + options[o]
- }
- })
- url += parms
- }
- }
- let currentUser = Parse.User.current()
- console.log('===========================================');
- console.log('======= index.js review 方法 =======');
- console.log('当前用户:', currentUser ? currentUser.id : '无');
- console.log('用户手机号:', currentUser?.get('mobile') || '无');
- console.log('用户名:', currentUser?.get('username') || '无');
- console.log('Session Token:', currentUser?.getSessionToken()?.substring(0, 20) || '无');
- console.log('userLogin 存储:', wx.getStorageSync('userLogin') || '无');
- console.log('force 参数:', force);
- console.log('===========================================');
-
- // 查询 Company 的 isPublishing 字段
- let isPublishing = false;
- try {
- const companyQuery = new Parse.Query('Company');
- companyQuery.equalTo('objectId', getApp().globalData.company);
- companyQuery.select('isPublishing');
-
- try {
- const companyObj = await companyQuery.first();
-
- if (companyObj) {
- isPublishing = companyObj.get('isPublishing') === true;
- console.log('📋 Company isPublishing:', isPublishing);
- } else {
- console.log('⚠️ 未找到 Company 记录,默认 isPublishing = false');
- isPublishing = false;
- }
- } catch (queryError) {
- console.error('❌ 查询 Company 失败(可能 token 无效):', queryError.message);
- // 查询失败时,默认为 false(强制登录)
- isPublishing = false;
- }
-
- // 保存到全局,供其他页面使用
- getApp().globalData.isPublishing = isPublishing;
- wx.setStorageSync('isPublishing', isPublishing);
- } catch (error) {
- console.error('❌ 查询 Company isPublishing 失败:', error);
- // 查询失败时,默认为 false(强制登录)
- isPublishing = false;
- }
-
- // 根据 isPublishing 决定是否强制登录
- if (!currentUser || force) {
- console.log('🔄 开始调用 checkAuth...');
-
- // isPublishing == true 时不强制授权,否则强制授权
- const forceAuth = !isPublishing;
- console.log('🔐 是否强制登录:', forceAuth);
-
- let r = await checkAuth(forceAuth);
-
- console.log('===========================================');
- console.log('======= checkAuth 返回结果 =======');
- console.log('返回值:', r);
-
- // 重新获取用户信息
- currentUser = Parse.User.current();
- console.log('checkAuth 后的用户:', currentUser ? currentUser.id : '无');
- console.log('checkAuth 后的手机号:', currentUser?.get('mobile') || '无');
- console.log('checkAuth 后的 Session Token:', currentUser?.getSessionToken()?.substring(0, 20) || '无');
- console.log('===========================================');
-
- // 如果强制登录但用户未登录,不允许继续访问
- if (forceAuth && !r) {
- console.log('❌ 强制登录模式,用户未登录,停止访问');
- return;
- }
-
- // 即使登录失败,也允许继续访问(仅在非强制登录模式下)
- if(!r) {
- console.log('⚠️ 用户未登录或拒绝授权,允许游客访问');
- // 不要 return,继续执行后面的跳转逻辑
- } else {
- // 登录成功,设置 userLogin
- if (currentUser && currentUser.get('mobile')) {
- wx.setStorageSync("userLogin", currentUser.id);
- console.log('✅ 授权登录成功,已设置 userLogin:', currentUser.id);
- console.log('✅ 用户手机号:', currentUser.get('mobile'));
- } else {
- console.warn('⚠️ checkAuth 返回成功,但用户没有手机号!');
- console.warn(' 用户对象:', currentUser);
- }
-
- // 检查是否有待记录的扫码信息
- await this.checkAndRecordPendingScan();
-
- // 如果用户没有来源信息,且当前有扫码参数,记录来源
- await this.checkAndRecordUserSourceOnLogin();
- }
- } else {
- console.log('✅ 用户已登录,跳过 checkAuth');
-
- // 用户已登录,确保 userLogin 已设置
- if (currentUser.get('mobile')) {
- wx.setStorageSync("userLogin", currentUser.id);
- console.log('✅ 已确认 userLogin:', currentUser.id);
- }
- this.updateUser(currentUser.id);
-
- // 用户已登录,检查是否有待记录的扫码信息
- await this.checkAndRecordPendingScan();
-
- // 如果用户没有来源信息,且当前有扫码参数,记录来源
- await this.checkAndRecordUserSourceOnLogin();
- }
- getApp().Parse = Parse
- getApp().checkAuth = checkAuth
- if (!await this.getCompanyServerExpire(url)) {
- return
- }
-
- // 检查是否需要跳转到活动页面
- if (wx.getStorageSync('need_activity_redirect') === true) {
- await this.redirectToActivityPage();
- return;
- }
-
- // 检查是否需要跳转到扫码统计页面
- if (this.shouldRedirectToScanPage()) {
- await this.redirectToScanPage();
- return;
- }
-
- console.log('✅ 准备跳转到:', url);
-
- wx.redirectTo({
- url: url,
- success: () => {
- console.log('✅ redirectTo 跳转成功');
- },
- fail: (err) => {
- console.error('❌ redirectTo 失败:', err);
- console.log('⚠️ 尝试使用 reLaunch');
-
- // 降级:尝试使用 reLaunch
- wx.reLaunch({
- url: url,
- success: () => {
- console.log('✅ reLaunch 跳转成功');
- },
- fail: (err2) => {
- console.error('❌ reLaunch 也失败:', err2);
- // 显示错误提示
- this.setData({ loading: false });
- wx.showModal({
- title: '温馨提示',
- content: '页面加载失败,请检查网络后重试。',
- showCancel: true,
- cancelText: '退出',
- confirmText: '重试',
- success: (result) => {
- if (result.confirm) {
- this.review(true);
- } else {
- wx.exitMiniProgram();
- }
- }
- });
- }
- });
- }
- });
- }
- catch (err) {
- console.log('❌ review 方法出错:', err);
-
- /* 登录身份信息到期,重新登陆 */
- if((err?.message?.indexOf('Session token is expired') != -1 || err?.message?.indexOf('Invalid session token') != -1) && !force){
- console.log('⚠️ Session Token 过期,准备重新登录');
-
- // 保存需要保留的数据
- const invite = wx.getStorageSync('invite');
- const agreementAccepted = wx.getStorageSync('user_agreement_accepted');
- const storeId = wx.getStorageSync('storeId');
- const isPublishing = wx.getStorageSync('isPublishing');
-
- // 先登出 Parse 用户
- try {
- await Parse.User.logOut();
- console.log('✅ Parse 用户已登出');
- } catch (logoutErr) {
- console.warn('⚠️ Parse 登出失败:', logoutErr);
- }
-
- // 清除所有存储
- wx.clearStorageSync();
-
- // 恢复需要保留的数据
- if (invite) wx.setStorageSync('invite', invite);
- if (agreementAccepted) wx.setStorageSync('user_agreement_accepted', agreementAccepted);
- if (storeId) wx.setStorageSync('storeId', storeId);
- if (isPublishing !== undefined) wx.setStorageSync('isPublishing', isPublishing);
-
- console.log('✅ 已清除过期登录信息,保留必要数据');
- console.log(' 保留的 invite:', invite || '无');
- console.log(' 保留的协议状态:', agreementAccepted || '无');
- console.log(' 保留的店铺ID:', storeId || '无');
-
- /* 强制重新登录 */
- this.review(true);
- return;
- }
-
- // 如果出错,尝试继续跳转到主页(游客模式)
- console.log('⚠️ 登录出错,尝试游客模式访问');
-
- let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
- if (this.data.options) {
- let objArr = Object.keys(this.data.options)
- if (objArr && objArr.length > 0) {
- let parms = '?'
- objArr.forEach((o, index) => {
- if (index > 0) {
- parms += '&' + o + '=' + this.data.options[o]
- } else {
- parms += o + '=' + this.data.options[o]
- }
- })
- url += parms
- }
- }
-
- wx.redirectTo({
- url: url,
- fail: () => {
- // 如果跳转失败,显示错误提示
- this.setData({
- loading:false
- })
- wx.showModal({
- title: '温馨提示',
- content: '页面加载失败,请检查网络后重试。',
- showCancel: true,
- cancelText: '退出',
- confirmText: '重试',
- success: (result) => {
- if (result.confirm) {
- // 用户选择重试
- this.review(true)
- } else {
- // 用户选择退出
- wx.exitMiniProgram()
- }
- },
- });
- }
- });
- }
- },
-
- /**
- * 检查并记录待处理的扫码统计
- * 同时记录用户来源信息到 _User 表
- */
- async checkAndRecordPendingScan() {
- try {
- const pendingScan = wx.getStorageSync('pending_scan_record');
-
- if (!pendingScan) {
- return;
- }
-
- console.log('===========================================');
- console.log('======= 发现待记录的扫码信息 =======');
- console.log('扫码信息:', pendingScan);
- console.log('===========================================');
-
- // 检查是否超时(24小时)
- const now = Date.now();
- const scanTime = pendingScan.timestamp || 0;
- const hoursPassed = (now - scanTime) / (1000 * 60 * 60);
-
- if (hoursPassed > 24) {
- console.log('⚠️ 扫码信息已超过24小时,不再记录');
- wx.removeStorageSync('pending_scan_record');
- return;
- }
-
- // 记录用户来源信息
- await this.recordUserSource(pendingScan);
-
- // 记录扫码统计
- await this.recordScanStatistics({
- storeId: pendingScan.storeId,
- sourceType: pendingScan.sourceType,
- sourceId: pendingScan.sourceId,
- ownerId: pendingScan.ownerId,
- employeeId: pendingScan.employeeId,
- partnerId: pendingScan.partnerId,
- userId: pendingScan.userId,
- productId: pendingScan.productId,
- scanCount: pendingScan.scanCount
- });
-
- // 清除待记录的扫码信息
- wx.removeStorageSync('pending_scan_record');
- console.log('✅ 扫码统计已记录并清除');
-
- } catch (error) {
- console.error('❌ 记录待处理扫码信息失败:', error);
- }
- },
-
- /**
- * 记录用户来源信息到 _User 表
- * 根据扫码参数判断来源类型并保存到用户的 source 字段
- *
- * 来源类型:
- * 1. 渠道xxx→异业xxx(老板后台添加的异业)
- * 2. 渠道xxx→异业xxx→员工xxx(员工后台添加的异业)
- * 3. 员工xxx
- * 4. 老板
- * 5. 自主进入(无任何推荐)
- */
- async recordUserSource(scanInfo) {
- try {
- const currentUser = Parse.User.current();
- if (!currentUser) {
- console.log('⚠️ 用户未登录,无法记录来源');
- return;
- }
-
- // 如果用户已经有来源信息,不再覆盖(首次来源原则)
- const existingSource = currentUser.get('source');
- if (existingSource) {
- console.log('ℹ️ 用户已有来源信息,不覆盖:', existingSource);
- return;
- }
-
- console.log('📊 ===========================================');
- console.log('📊 [记录来源] 开始记录用户来源信息');
- console.log('📊 用户ID:', currentUser.id);
- console.log('📊 ===========================================');
-
- const { partnerId, employeeId, ownerId, userId, storeId } = scanInfo;
-
- let sourceInfo = {
- type: 'self_entry', // 默认为自主进入
- label: '自主进入',
- timestamp: new Date(),
- storeId: storeId
- };
-
- // 判断来源类型
- if (partnerId && employeeId) {
- // 情况2: 渠道xxx→异业xxx→员工xxx(员工后台添加的异业)
- console.log('🔍 [来源类型] 渠道→异业→员工');
-
- try {
- // 查询异业信息
- const partnerQuery = new Parse.Query('Partner');
- const partner = await partnerQuery.get(partnerId);
- const partnerName = partner.get('name') || '未知异业';
- const channelName = partner.get('channelName') || partner.get('category') || '未知渠道';
-
- // 查询员工信息
- const employeeQuery = new Parse.Query('Employee');
- const employee = await employeeQuery.get(employeeId);
- const employeeName = employee.get('name') || '未知员工';
-
- sourceInfo = {
- type: 'channel_partner_employee',
- label: `${channelName},${partnerName},员工${employeeName}`,
- channelName: channelName,
- partnerId: partnerId,
- partnerName: partnerName,
- employeeId: employeeId,
- employeeName: employeeName,
- timestamp: new Date(),
- storeId: storeId
- };
-
- console.log('✅ [来源信息] 渠道→异业→员工:', sourceInfo.label);
- } catch (error) {
- console.error('❌ 查询异业或员工信息失败:', error);
- }
-
- } else if (partnerId && !employeeId) {
- // 情况1: 渠道xxx→异业xxx(老板后台添加的异业)
- console.log('🔍 [来源类型] 渠道→异业');
-
- try {
- // 查询异业信息
- const partnerQuery = new Parse.Query('Partner');
- const partner = await partnerQuery.get(partnerId);
- const partnerName = partner.get('name') || '未知异业';
- const channelName = partner.get('channelName') || partner.get('category') || '未知渠道';
-
- sourceInfo = {
- type: 'channel_partner',
- label: `${channelName},${partnerName}`,
- channelName: channelName,
- partnerId: partnerId,
- partnerName: partnerName,
- timestamp: new Date(),
- storeId: storeId
- };
-
- console.log('✅ [来源信息] 渠道→异业:', sourceInfo.label);
- } catch (error) {
- console.error('❌ 查询异业信息失败:', error);
- }
-
- } else if (employeeId && !partnerId) {
- // 情况3: 员工xxx
- console.log('🔍 [来源类型] 员工');
-
- try {
- // 查询员工信息
- const employeeQuery = new Parse.Query('Employee');
- const employee = await employeeQuery.get(employeeId);
- const employeeName = employee.get('name') || '未知员工';
-
- sourceInfo = {
- type: 'employee',
- label: employeeName,
- employeeId: employeeId,
- employeeName: employeeName,
- timestamp: new Date(),
- storeId: storeId
- };
-
- console.log('✅ [来源信息] 员工:', sourceInfo.label);
- } catch (error) {
- console.error('❌ 查询员工信息失败:', error);
- }
-
- } else if (ownerId) {
- // 情况4: 老板
- console.log('🔍 [来源类型] 老板');
-
- sourceInfo = {
- type: 'owner',
- label: '老板',
- ownerId: ownerId,
- timestamp: new Date(),
- storeId: storeId
- };
-
- console.log('✅ [来源信息] 老板');
-
- } else if (userId) {
- // 推广员(如果有的话)
- console.log('🔍 [来源类型] 推广员');
-
- try {
- // 查询推广员信息
- const userQuery = new Parse.Query('_User');
- const promoter = await userQuery.get(userId);
- const promoterName = promoter.get('username') || promoter.get('mobile') || '未知推广员';
-
- sourceInfo = {
- type: 'promoter',
- label: `推广员${promoterName}`,
- userId: userId,
- promoterName: promoterName,
- timestamp: new Date(),
- storeId: storeId
- };
-
- console.log('✅ [来源信息] 推广员:', sourceInfo.label);
- } catch (error) {
- console.error('❌ 查询推广员信息失败:', error);
- }
-
- } else {
- // 情况5: 自主进入(无任何推荐)
- console.log('🔍 [来源类型] 自主进入');
- console.log('✅ [来源信息] 自主进入');
- }
-
- // 保存来源信息到用户
- currentUser.set('source', sourceInfo);
- await currentUser.save();
-
- console.log('✅ [保存成功] 用户来源信息已保存');
- console.log(' - 来源类型:', sourceInfo.type);
- console.log(' - 来源标签:', sourceInfo.label);
- console.log('📊 ===========================================');
-
- } catch (error) {
- console.error('❌ 记录用户来源失败:', error);
- }
- },
-
- /**
- * 用户登录后检查并记录来源信息
- * 如果用户是首次登录且没有来源信息,根据当前的扫码参数记录来源
- */
- async checkAndRecordUserSourceOnLogin() {
- try {
- const currentUser = Parse.User.current();
- if (!currentUser) {
- return;
- }
-
- // 如果用户已经有来源信息,不再处理
- const existingSource = currentUser.get('source');
- if (existingSource) {
- console.log('ℹ️ 用户已有来源信息,跳过记录');
- return;
- }
-
- // 检查是否有扫码参数
- const scanStoreId = wx.getStorageSync('scan_storeId');
- const scanPartnerId = wx.getStorageSync('scan_partnerId');
- const scanEmployeeId = wx.getStorageSync('scan_employeeId');
- const scanOwnerId = wx.getStorageSync('scan_ownerId');
- const scanUserId = wx.getStorageSync('scan_userId');
-
- // 如果有任何扫码参数,记录来源
- if (scanStoreId || scanPartnerId || scanEmployeeId || scanOwnerId || scanUserId) {
- console.log('📊 检测到扫码参数,记录用户来源');
-
- await this.recordUserSource({
- storeId: scanStoreId,
- partnerId: scanPartnerId,
- employeeId: scanEmployeeId,
- ownerId: scanOwnerId,
- userId: scanUserId
- });
- } else {
- // 没有任何扫码参数,标记为自主进入
- console.log('📊 无扫码参数,标记为自主进入');
-
- await this.recordUserSource({
- storeId: wx.getStorageSync('storeId') || null
- });
- }
-
- } catch (error) {
- console.error('❌ 检查并记录用户来源失败:', error);
- }
- },
- async updateUser(id) {
- try {
- let User = new Parse.Query('_User')
- let user = await User.get(id)
- let invite = wx.getStorageSync('invite')
- //查询邀请人user
- let query = new Parse.Query("_User")
- query.equalTo('objectId', invite)
- let result = await query.first()
- if (result && result.id && result.get("invite")?.id == user.id) {
- console.error('邀请人不能是自己的下级')
- return
- }
- if (invite && !user.get('invite') && user.id != invite && !user.get('agentLevel')) {
- console.log('上下级绑定成功');
- user.set('invite', {
- __type: "Pointer",
- className: "_User",
- objectId: invite
- })
- user.set('agent', {
- __type: "Pointer",
- className: "_User",
- objectId: invite
- })
- await Parse.Cloud.run('user_save', {
- userJson: user.toJSON()
- })
- }
- } catch (error) {
- console.error('❌ updateUser 失败:', error.message);
- // 不阻断流程,继续执行
- }
- },
- async getCompanyServerExpire(url) {
- try {
- let query = new Parse.Query('Company')
- query.equalTo('objectId', getApp().globalData.company)
- query.select('expireDate', 'expireMap')
- let com = await query.first()
- if (com?.id && com?.get('expireDate')) {
- let now = + new Date()
- let expireTime = + new Date(com?.get('expireDate'))
- if (com?.get('expireMap') && com.get('expireMap')[getApp().globalData.appid]) {
- expireTime = + new Date(com.get('expireMap')[getApp().globalData.appid])
- }
- if (now >= expireTime) {
- console.log('服务器到期');
- wx.reLaunch({
- url: `common-page/pages/loading/index?url=${url}`,
- });
- return
- }
- }
- return true
- } catch (error) {
- console.error('❌ getCompanyServerExpire 失败:', error.message);
- // 查询失败时,允许继续访问
- return true
- }
- },
- onUnload: function () {
- wx.setStorageSync("active", 0);
- },
- getParaName(url) {
- if (!url || url.indexOf('?') == -1) {
- return
- }
- // 兼容 URL 中 & 的情况,先统一还原为 &
- if (url.indexOf('&') !== -1) {
- url = url.replace(/&/g, '&');
- }
- // 提取查询参数部分(去除可能的 hash 部分)
- let queryString = url.split('?')[1];
- // 如果包含 #,只取 # 之前的部分
- if (queryString.indexOf('#') !== -1) {
- queryString = queryString.split('#')[0];
- }
- return this.setObject(queryString) //封装成对象
- },
- setObject(paraArr) {
- let obj = {}
- let arr1 = paraArr.split('&')
- arr1.forEach(item => {
- let str = item.split('=')
- let key = str[0]
- let val = str[1]
- obj[key] = val
- })
- return obj
- },
- /**
- * 检查并处理扫码参数
- * 支持所有类型的二维码:
- * 1. 推广员二维码: ?scanCount=0&storeId=xxx&userId=xxx
- * 2. 产品二维码: ?scanCount=0&storeId=xxx&productId=xxx
- * 3. 案例二维码: ?scanCount=0&storeId=xxx&caseId=xxx
- * 4. 活动海报二维码: activityId作为qrCode参数值
- * 5. 异业合作伙伴二维码(移动端 / PC端统一): ?scanCount=xxx&storeId=xxx&partnerId=xxx
- * 6. 员工邀请二维码(移动端): ?scanCount=0&storeId=xxx&employeeId=xxx
- * 7. 我的二维码(老板): ?scanCount=0&storeId=xxx&ownerId=xxx
- * 8. 我的二维码(员工): ?scanCount=0&storeId=xxx&employeeId=xxx
- * 9. 方案分享二维码: ?scanCount=0&storeId=xxx&planId=xxx&shareUserId=xxx
- */
- checkAndHandleScan(options) {
- console.log('🔍🔍🔍 ========================================');
- console.log('🔍 [扫码检测] 开始检查扫码参数');
- console.log('🔍 完整 options 对象:', JSON.stringify(options, null, 2));
- console.log('🔍🔍🔍 ========================================');
-
- const {
- scanCount,
- ownerId,
- employeeId,
- partnerId,
- storeId,
- productId,
- caseId,
- userId, // 推广员二维码使用userId
- activityId,
- schemeId, // 方案ID(旧参数名)
- planId, // 方案ID(新参数名,优先使用)
- shareUserId, // 分享方案的用户ID
- q // 扫码链接
- } = options;
-
- // planId 和 schemeId 兼容处理,优先使用 planId
- const finalPlanId = planId || schemeId;
-
- console.log('📋 [扫码参数] 提取的参数:');
- console.log(' - scanCount:', scanCount || '无');
- console.log(' - storeId:', storeId || '无');
- console.log(' - ownerId:', ownerId || '无');
- console.log(' - employeeId:', employeeId || '无');
- console.log(' - partnerId:', partnerId || '无');
- console.log(' - userId:', userId || '无');
- console.log(' - productId:', productId || '无');
- console.log(' - caseId:', caseId || '无');
- console.log(' - activityId:', activityId || '无');
- console.log(' - planId:', planId || '无');
- console.log(' - schemeId:', schemeId || '无');
- console.log(' - finalPlanId (最终使用):', finalPlanId || '无');
- console.log(' - shareUserId:', shareUserId || '无');
- console.log(' - q (扫码链接):', q || '无');
-
- // 处理活动海报二维码(activityId作为qrCode参数值)
- if (activityId && !storeId) {
- console.log('🎯 ===========================================');
- console.log('🎯 [活动二维码] 检测到活动海报二维码');
- console.log('🎯 活动ID (activityId):', activityId);
- console.log('🎯 来源类型: 活动海报');
- console.log('🎯 ===========================================');
-
- // 活动二维码需要跳转到活动页面,不需要跳转到店铺
- wx.setStorageSync('scan_activityId', activityId);
- wx.setStorageSync('need_activity_redirect', true);
- return;
- }
-
- // 如果存在 storeId,说明是扫码进入具体门店(包括异业分享)
- if (storeId) {
- console.log('🏪 ===========================================');
- console.log('🏪 [店铺扫码] 检测到扫码参数');
- console.log('🏪 店铺ID (storeId):', storeId);
- console.log('🏪 扫码次数 (scanCount):', scanCount || '0');
-
- // 确定来源类型
- let sourceType = 'unknown';
- let sourceId = null;
-
- if (employeeId) {
- sourceType = 'employee';
- sourceId = employeeId;
- console.log('👤 [来源识别] 来源类型: 员工展业');
- console.log('👤 员工ID (employeeId):', employeeId);
- } else if (userId) {
- // 推广员二维码使用userId
- sourceType = 'promoter';
- sourceId = userId;
- console.log('📢 [来源识别] 来源类型: 推广员展业');
- console.log('📢 推广员ID (userId):', userId);
- } else if (ownerId) {
- sourceType = 'owner';
- sourceId = ownerId;
- console.log('👔 [来源识别] 来源类型: 老板展业');
- console.log('👔 老板ID (ownerId):', ownerId);
- } else if (partnerId) {
- sourceType = 'partner';
- sourceId = partnerId;
- console.log('🤝 [来源识别] 来源类型: 异业合作伙伴');
- console.log('🤝 合作伙伴ID (partnerId):', partnerId);
- } else {
- sourceType = 'store';
- console.log('🏬 [来源识别] 来源类型: 店铺分享(无具体来源人)');
- }
-
- if (productId) {
- console.log('📦 [目标内容] 产品ID (productId):', productId);
- }
-
- if (caseId) {
- console.log('📸 [目标内容] 案例ID (caseId):', caseId);
- }
-
- if (finalPlanId) {
- console.log('📋 [目标内容] 方案ID (planId/schemeId):', finalPlanId);
- console.log('👤 [分享人] 分享用户ID (shareUserId):', shareUserId || '无');
- }
-
- console.log('🏪 ===========================================');
-
- // 保存到临时存储,用于后续跳转和统计
- console.log('💾 [保存扫码信息] 开始保存到本地存储...');
- wx.setStorageSync('scan_storeId', storeId);
- wx.setStorageSync('scan_scanCount', scanCount || '0');
- wx.setStorageSync('scan_sourceType', sourceType);
- wx.setStorageSync('scan_sourceId', sourceId || '');
- wx.setStorageSync('scan_ownerId', ownerId || '');
- wx.setStorageSync('scan_employeeId', employeeId || '');
- wx.setStorageSync('scan_partnerId', partnerId || '');
- wx.setStorageSync('scan_userId', userId || '');
- if (productId) {
- wx.setStorageSync('scan_productId', productId);
- }
- if (caseId) {
- wx.setStorageSync('scan_caseId', caseId);
- }
- if (finalPlanId) {
- wx.setStorageSync('scan_planId', finalPlanId);
- if (shareUserId) {
- wx.setStorageSync('scan_shareUserId', shareUserId);
- }
- }
- wx.setStorageSync('need_scan_redirect', true);
-
- console.log('✅ [保存完成] 扫码信息已保存');
- console.log('📋 [保存内容摘要]:');
- console.log(' - 来源类型:', sourceType);
- console.log(' - 来源ID:', sourceId || '无');
- console.log(' - 店铺ID:', storeId);
- console.log(' - 需要跳转:', true);
- } else if (partnerId) {
- // 理论上异业二维码现在也必须带 storeId,这里仅作为兜底保护
- console.warn('⚠️ 检测到异业合作伙伴二维码缺少 storeId,无法确定门店,请检查二维码生成逻辑');
- }
- },
- /**
- * 判断是否需要跳转到扫码统计页面
- */
- shouldRedirectToScanPage() {
- return wx.getStorageSync('need_scan_redirect') === true;
- },
- /**
- * 跳转到扫码对应的店铺页面
- * 根据 storeId 跳转到对应店铺,同时记录所有来源信息用于统计
- */
- async redirectToScanPage() {
- try {
- console.log('🚀 ===========================================');
- console.log('🚀 [跳转处理] 开始处理扫码跳转');
- console.log('🚀 ===========================================');
-
- // 获取所有扫码相关参数
- const storeId = wx.getStorageSync('scan_storeId');
- const scanCount = wx.getStorageSync('scan_scanCount');
- const sourceType = wx.getStorageSync('scan_sourceType');
- const sourceId = wx.getStorageSync('scan_sourceId');
- const ownerId = wx.getStorageSync('scan_ownerId');
- const employeeId = wx.getStorageSync('scan_employeeId');
- const partnerId = wx.getStorageSync('scan_partnerId');
- const userId = wx.getStorageSync('scan_userId');
- const productId = wx.getStorageSync('scan_productId');
- const caseId = wx.getStorageSync('scan_caseId');
- const planId = wx.getStorageSync('scan_planId');
- const shareUserId = wx.getStorageSync('scan_shareUserId');
-
- console.log('📖 [读取存储] 从本地存储读取扫码信息:');
- console.log(' - storeId:', storeId || '无');
- console.log(' - sourceType:', sourceType || '无');
- console.log(' - sourceId:', sourceId || '无');
- console.log(' - scanCount:', scanCount || '无');
- console.log(' - ownerId:', ownerId || '无');
- console.log(' - employeeId:', employeeId || '无');
- console.log(' - partnerId:', partnerId || '无');
- console.log(' - userId:', userId || '无');
- console.log(' - productId:', productId || '无');
- console.log(' - caseId:', caseId || '无');
- console.log(' - planId:', planId || '无');
- console.log(' - shareUserId:', shareUserId || '无');
-
- // 清除临时存储
- console.log('🧹 [清理存储] 清除临时扫码信息...');
- wx.removeStorageSync('scan_storeId');
- wx.removeStorageSync('scan_scanCount');
- wx.removeStorageSync('scan_sourceType');
- wx.removeStorageSync('scan_sourceId');
- wx.removeStorageSync('scan_ownerId');
- wx.removeStorageSync('scan_employeeId');
- wx.removeStorageSync('scan_partnerId');
- wx.removeStorageSync('scan_userId');
- wx.removeStorageSync('scan_productId');
- wx.removeStorageSync('scan_caseId');
- wx.removeStorageSync('scan_planId');
- wx.removeStorageSync('scan_shareUserId');
- wx.removeStorageSync('need_scan_redirect');
- console.log('✅ [清理完成] 临时存储已清除');
-
- if (!storeId) {
- console.error('❌ [错误] 缺少 storeId 参数,无法跳转');
- return;
- }
-
- console.log('📊 ===========================================');
- console.log('📊 [扫码来源汇总] 扫码进入店铺');
- console.log('📊 店铺 ID:', storeId);
- console.log('📊 来源类型:', sourceType);
- console.log('📊 来源 ID:', sourceId || '无');
- console.log('📊 扫码次数:', scanCount);
- if (ownerId) console.log('📊 老板 ID:', ownerId);
- if (employeeId) console.log('📊 员工 ID:', employeeId);
- if (partnerId) console.log('📊 合作伙伴 ID:', partnerId);
- if (userId) console.log('📊 推广员 ID:', userId);
- if (productId) console.log('📊 产品 ID:', productId);
- if (caseId) console.log('📊 案例 ID:', caseId);
- if (planId) {
- console.log('📊 方案 ID:', planId);
- console.log('📊 分享用户 ID:', shareUserId || '无');
- }
- console.log('📊 ===========================================');
-
- // 设置店铺 ID 到全局和本地存储
- wx.setStorageSync('storeId', storeId);
- getApp().globalData.storeId = storeId;
-
- // 保存来源信息到本地存储(用于后续统计或绑定关系)
- if (sourceId) {
- wx.setStorageSync('scan_from_sourceType', sourceType);
- wx.setStorageSync('scan_from_sourceId', sourceId);
- console.log('✅ 已记录来源信息:', sourceType, sourceId);
- }
-
- // 检查用户是否已登录
- const currentUser = Parse.User.current();
-
- console.log('👤 [登录检查] 检查用户登录状态...');
- console.log(' - 当前用户:', currentUser ? currentUser.id : '未登录');
- console.log(' - 手机号:', currentUser?.get('mobile') || '无');
-
- if (currentUser) {
- // 用户已登录,立即记录扫码统计
- console.log('✅ [已登录] 用户已登录,立即记录扫码统计');
- await this.recordScanStatistics({
- storeId,
- sourceType,
- sourceId,
- ownerId,
- employeeId,
- partnerId,
- userId,
- productId,
- scanCount
- });
- } else {
- // 用户未登录,保存扫码信息,等登录后再记录
- console.log('⚠️ [未登录] 用户未登录,保存扫码信息待登录后记录');
- const pendingData = {
- storeId,
- sourceType,
- sourceId,
- ownerId,
- employeeId,
- partnerId,
- userId,
- productId,
- scanCount,
- timestamp: Date.now()
- };
- console.log('💾 [待处理记录] 保存内容:', JSON.stringify(pendingData, null, 2));
- wx.setStorageSync('pending_scan_record', pendingData);
- console.log('✅ [保存成功] 待处理扫码记录已保存');
- }
-
- // 如果有产品ID,直接跳转到产品详情的 H5 页面
- if (productId) {
- console.log('🎯 检测到产品ID,跳转到产品详情页');
- await this.redirectToProductDetail(storeId, productId, partnerId);
- return;
- }
-
- // 如果有案例ID,直接跳转到案例详情的 H5 页面
- if (caseId) {
- console.log('🎯 检测到案例ID,跳转到案例详情页');
- await this.redirectToCaseDetail(storeId, caseId, partnerId);
- return;
- }
-
- // 如果有方案ID,跳转到门店首页并传递方案ID
- if (planId) {
- console.log('🎯 检测到方案ID,跳转到门店首页展示方案');
- await this.redirectToStoreWithPlan(storeId, planId, shareUserId, partnerId);
- return;
- }
-
- // 获取默认首页路径并跳转
- let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
- url += `?storeId=${storeId}`;
-
- // 如果有产品ID,添加到URL参数中
- if (productId) {
- url += `&productId=${productId}`;
- }
-
- // 如果有异业合作伙伴ID,添加到URL参数中传回web-view
- if (partnerId) {
- url += `&partnerId=${partnerId}`;
- }
-
- console.log('✅ 跳转到店铺页面:', url);
-
- wx.redirectTo({
- url: url,
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- // 如果 redirectTo 失败,尝试 reLaunch
- wx.reLaunch({
- url: url,
- fail: (err2) => {
- console.error('❌ reLaunch 也失败:', err2);
- }
- });
- }
- });
- } catch (error) {
- console.error('❌ 跳转到店铺页面失败:', error);
- }
- },
-
- /**
- * 跳转到活动页面
- */
- async redirectToActivityPage() {
- try {
- const activityId = wx.getStorageSync('scan_activityId');
-
- // 清除临时存储
- wx.removeStorageSync('scan_activityId');
- wx.removeStorageSync('need_activity_redirect');
-
- if (!activityId) {
- console.error('❌ 缺少 activityId 参数,无法跳转');
- return;
- }
-
- console.log('===========================================');
- console.log('======= 扫码进入活动页面 =======');
- console.log('活动 ID (activityId):', activityId);
- console.log('===========================================');
-
- // 保存活动ID
- wx.setStorageSync('activityId', activityId);
-
- // 获取默认首页路径并跳转(活动页面可能需要根据实际路由调整)
- let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
- url += `?activityId=${activityId}`;
-
- console.log('✅ 跳转到活动页面:', url);
-
- wx.redirectTo({
- url: url,
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- wx.reLaunch({
- url: url,
- fail: (err2) => {
- console.error('❌ reLaunch 也失败:', err2);
- }
- });
- }
- });
- } catch (error) {
- console.error('❌ 跳转到活动页面失败:', error);
- }
- },
-
- /**
- * 跳转到产品详情的 H5 页面
- * @param {string} storeId - 店铺 ID
- * @param {string} productId - 产品 ID
- * @param {string} partnerId - 可选的合作伙伴 ID
- */
- async redirectToProductDetail(storeId, productId, partnerId = null) {
- try {
- console.log('===========================================');
- console.log('======= 跳转到产品详情页 =======');
- console.log('店铺 ID:', storeId);
- console.log('产品 ID:', productId);
- if (partnerId) console.log('合作伙伴 ID:', partnerId);
- console.log('===========================================');
-
- const currentUser = Parse.User.current();
- const token = currentUser ? currentUser.getSessionToken() : null;
-
- // 构建产品详情的 H5 URL(不要在这里编码,后面统一编码)
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/products?storeId=${storeId}`;
-
- // 如果有 token,添加到 URL
- if (token) {
- h5Url += `&token=${token}`;
- } else {
- // 如果没有 token,使用游客模式
- h5Url += `&guestMode=true`;
- }
-
- // 添加产品ID(不要在这里编码,避免双重编码)
- h5Url += `&productId=${productId}`;
-
- // 如果有合作伙伴ID,也添加到URL中
- if (partnerId) {
- h5Url += `&partnerId=${partnerId}`;
- }
-
- console.log('🌐 H5 URL:', h5Url);
-
- // 编码 URL(统一在这里编码一次)
- const encodedUrl = encodeURIComponent(h5Url);
-
- // 构建 web-view 页面路径
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
-
- console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
- console.log('===========================================');
-
- wx.redirectTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 跳转到产品详情页成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- // 如果 redirectTo 失败,尝试 reLaunch
- wx.reLaunch({
- url: webViewPath,
- fail: (err2) => {
- console.error('❌ reLaunch 也失败:', err2);
- }
- });
- }
- });
- } catch (error) {
- console.error('❌ 跳转到产品详情页失败:', error);
- }
- },
-
- /**
- * 跳转到案例详情的 H5 页面
- * @param {string} storeId - 店铺 ID
- * @param {string} caseId - 案例 ID
- * @param {string} partnerId - 可选的合作伙伴 ID
- */
- async redirectToCaseDetail(storeId, caseId, partnerId = null) {
- try {
- console.log('===========================================');
- console.log('======= 跳转到案例详情页 =======');
- console.log('店铺 ID:', storeId);
- console.log('案例 ID:', caseId);
- if (partnerId) console.log('合作伙伴 ID:', partnerId);
- console.log('===========================================');
-
- const currentUser = Parse.User.current();
- const token = currentUser ? currentUser.getSessionToken() : null;
-
- // 构建案例详情的 H5 URL(不要在这里编码,后面统一编码)
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/cases?storeId=${storeId}`;
-
- // 如果有 token,添加到 URL
- if (token) {
- h5Url += `&token=${token}`;
- } else {
- // 如果没有 token,使用游客模式
- h5Url += `&guestMode=true`;
- }
-
- // 添加案例ID(不要在这里编码,避免双重编码)
- h5Url += `&caseId=${caseId}`;
-
- // 如果有合作伙伴ID,也添加到URL中
- if (partnerId) {
- h5Url += `&partnerId=${partnerId}`;
- }
-
- console.log('🌐 H5 URL:', h5Url);
-
- // 编码 URL(统一在这里编码一次)
- const encodedUrl = encodeURIComponent(h5Url);
-
- // 构建 web-view 页面路径
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
-
- console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
- console.log('===========================================');
-
- wx.redirectTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 跳转到案例详情页成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- // 如果 redirectTo 失败,尝试 reLaunch
- wx.reLaunch({
- url: webViewPath,
- fail: (err2) => {
- console.error('❌ reLaunch 也失败:', err2);
- }
- });
- }
- });
- } catch (error) {
- console.error('❌ 跳转到案例详情页失败:', error);
- }
- },
-
- /**
- * 跳转到门店首页并展示方案
- * @param {string} storeId - 店铺 ID
- * @param {string} planId - 方案 ID
- * @param {string} shareUserId - 分享方案的用户 ID
- * @param {string} partnerId - 可选的合作伙伴 ID
- */
- async redirectToStoreWithPlan(storeId, planId, shareUserId = null, partnerId = null) {
- try {
- console.log('===========================================');
- console.log('======= 跳转到门店首页展示方案 =======');
- console.log('店铺 ID:', storeId);
- console.log('方案 ID:', planId);
- if (shareUserId) console.log('分享用户 ID:', shareUserId);
- if (partnerId) console.log('合作伙伴 ID:', partnerId);
- console.log('===========================================');
-
- const currentUser = Parse.User.current();
- const token = currentUser ? currentUser.getSessionToken() : null;
-
- // 构建门店首页的 H5 URL,带上方案ID
- let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?storeId=${storeId}`;
-
- // 如果有 token,添加到 URL
- if (token) {
- h5Url += `&token=${token}`;
- } else {
- // 如果没有 token,使用游客模式
- h5Url += `&guestMode=true`;
- }
-
- // 添加方案ID(使用planId参数名)
- h5Url += `&planId=${planId}`;
-
- // 如果有分享用户ID,也添加到URL中
- if (shareUserId) {
- h5Url += `&shareUserId=${shareUserId}`;
- }
-
- // 如果有合作伙伴ID,也添加到URL中
- if (partnerId) {
- h5Url += `&partnerId=${partnerId}`;
- }
-
- console.log('🌐 H5 URL:', h5Url);
-
- // 编码 URL
- const encodedUrl = encodeURIComponent(h5Url);
-
- // 构建 web-view 页面路径
- let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
-
- console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
- console.log('===========================================');
-
- wx.redirectTo({
- url: webViewPath,
- success: () => {
- console.log('✅ 跳转到门店首页展示方案成功');
- },
- fail: (err) => {
- console.error('❌ 跳转失败:', err);
- // 如果 redirectTo 失败,尝试 reLaunch
- wx.reLaunch({
- url: webViewPath,
- fail: (err2) => {
- console.error('❌ reLaunch 也失败:', err2);
- }
- });
- }
- });
- } catch (error) {
- console.error('❌ 跳转到门店首页展示方案失败:', error);
- }
- },
-
- /**
- * 记录扫码统计信息
- * @param {Object} params - 扫码参数对象
- * @param {string} params.storeId - 店铺 ID
- * @param {string} params.sourceType - 来源类型 (employee/owner/partner/promoter/store)
- * @param {string} params.sourceId - 来源 ID
- * @param {string} params.ownerId - 老板 ID
- * @param {string} params.employeeId - 员工 ID
- * @param {string} params.partnerId - 合作伙伴 ID
- * @param {string} params.userId - 推广员 ID
- * @param {string} params.productId - 产品 ID
- * @param {string} params.scanCount - 扫码次数
- */
- async recordScanStatistics(params) {
- try {
- console.log('📝 ===========================================');
- console.log('📝 [扫码统计] 开始记录扫码统计');
- console.log('📝 ===========================================');
-
- const {
- storeId,
- sourceType,
- sourceId,
- ownerId,
- employeeId,
- partnerId,
- userId,
- productId,
- scanCount
- } = params;
-
- console.log('📋 [统计参数] 接收到的参数:');
- console.log(' - storeId:', storeId);
- console.log(' - sourceType:', sourceType);
- console.log(' - sourceId:', sourceId || '无');
- console.log(' - ownerId:', ownerId || '无');
- console.log(' - employeeId:', employeeId || '无');
- console.log(' - partnerId:', partnerId || '无');
- console.log(' - userId:', userId || '无');
- console.log(' - productId:', productId || '无');
- console.log(' - scanCount:', scanCount || '0');
-
- // 检查用户是否已登录
- const currentUser = Parse.User.current();
- if (!currentUser) {
- console.log('⚠️ [未登录] 用户未登录,不记录扫码统计');
- return;
- }
-
- console.log('👤 [用户信息] 当前登录用户:');
- console.log(' - 用户ID:', currentUser.id);
- console.log(' - 手机号:', currentUser.get('mobile') || '无');
-
- // 如果没有来源信息,不记录统计
- if (!sourceId && !ownerId && !employeeId && !partnerId && !userId) {
- console.log('ℹ️ [跳过] 无来源信息,跳过统计记录');
- return;
- }
-
- console.log('✅ [开始记录] 用户已登录且有来源信息,开始记录');
-
- // 创建扫码记录
- const ScanRecord = Parse.Object.extend('ScanRecord');
- const record = new ScanRecord();
-
- record.set('company', {
- __type: 'Pointer',
- className: 'Company',
- objectId: getApp().globalData.company
- });
- record.set('storeId', storeId);
- record.set('sourceType', sourceType || 'unknown');
- record.set('scanCount', parseInt(scanCount) || 0);
- record.set('scanTime', new Date());
-
- console.log('📦 [记录内容] 准备保存到 ScanRecord 表:');
- console.log(' - company:', getApp().globalData.company);
- console.log(' - storeId:', storeId);
- console.log(' - sourceType:', sourceType || 'unknown');
- console.log(' - scanCount:', parseInt(scanCount) || 0);
- console.log(' - scanTime:', new Date().toISOString());
-
- // 根据来源类型设置对应的ID
- if (ownerId) {
- record.set('ownerId', ownerId);
- console.log(' - ownerId:', ownerId);
- }
- if (employeeId) {
- record.set('employeeId', employeeId);
- console.log(' - employeeId:', employeeId);
- }
- if (partnerId) {
- record.set('partnerId', partnerId);
- console.log(' - partnerId:', partnerId);
- }
- if (userId) {
- record.set('userId', userId);
- console.log(' - userId:', userId);
- }
- if (productId) {
- record.set('productId', productId);
- console.log(' - productId:', productId);
- }
-
- // 记录扫码用户
- record.set('user', {
- __type: 'Pointer',
- className: '_User',
- objectId: currentUser.id
- });
- console.log(' - user:', currentUser.id);
-
- await record.save();
- console.log('✅ [保存成功] 扫码记录已保存到数据库');
- console.log(' - 记录ID:', record.id);
- // 如果存在异业合作伙伴ID,处理异业绑定和扫码次数
- if (partnerId) {
- try {
- console.log('🤝 ===========================================');
- console.log('🤝 [异业处理] 开始处理异业扫码逻辑');
- console.log('🤝 用户ID:', currentUser.id);
- console.log('🤝 异业ID:', partnerId);
- console.log('🤝 门店ID:', storeId);
- console.log('🤝 ===========================================');
-
- // 检查用户是否已经绑定了异业合作伙伴
- const userBoundPartner = currentUser.get('Partner');
- const userBoundPartnerId = userBoundPartner ? userBoundPartner.id : null;
-
- console.log('🔍 [绑定检查] 用户已绑定的异业ID:', userBoundPartnerId || '无');
-
- // 规则1:如果用户已绑定其他异业,不处理当前异业的扫码
- if (userBoundPartnerId && userBoundPartnerId !== partnerId) {
- console.log('⚠️ [规则1] 用户已绑定其他异业,不处理当前异业的扫码');
- console.log(' - 已绑定异业:', userBoundPartnerId);
- console.log(' - 当前扫码异业:', partnerId);
- console.log('🤝 ===========================================');
- return;
- }
-
- // 规则2:检查该用户在该门店是否已经扫过该异业的码
- console.log('🔍 [重复检查] 检查是否已扫过该异业的码...');
- const ScanRecord = Parse.Object.extend('ScanRecord');
- const scanQuery = new Parse.Query(ScanRecord);
- scanQuery.equalTo('user', {
- __type: 'Pointer',
- className: '_User',
- objectId: currentUser.id
- });
- scanQuery.equalTo('partnerId', partnerId);
- scanQuery.equalTo('storeId', storeId);
-
- const existingScan = await scanQuery.first();
-
- if (existingScan) {
- console.log('⚠️ [规则2] 该用户在该门店已扫过该异业的码,不重复计数');
- console.log(' - 首次扫码时间:', existingScan.get('scanTime'));
- console.log(' - 记录ID:', existingScan.id);
- console.log('🤝 ===========================================');
- return;
- }
-
- console.log('✅ [首次扫码] 该用户在该门店首次扫该异业码');
-
- // 规则3:如果用户还没有绑定异业,绑定当前异业
- if (!userBoundPartnerId) {
- console.log('🔗 [规则3] 用户首次扫异业码,开始绑定异业合作伙伴');
- console.log(' - 异业ID:', partnerId);
-
- currentUser.set('Partner', {
- __type: 'Pointer',
- className: 'Partner',
- objectId: partnerId
- });
- await currentUser.save();
- console.log('✅ [绑定成功] 异业绑定成功');
- } else {
- console.log('ℹ️ [已绑定] 用户已绑定该异业,无需重复绑定');
- }
-
- // 规则4:为该异业在该门店增加扫码次数
- console.log('📊 [规则4] 开始更新异业扫码次数...');
- const Partner = Parse.Object.extend('Partner');
- const partnerQuery = new Parse.Query(Partner);
- const partnerObj = await partnerQuery.get(partnerId);
- if (partnerObj) {
- console.log('📋 [异业信息] 找到异业合作伙伴记录');
- console.log(' - 异业ID:', partnerObj.id);
- console.log(' - 异业名称:', partnerObj.get('name') || '未设置');
-
- // 获取或初始化门店扫码次数映射
- let storeScans = partnerObj.get('storeScans') || {};
- const oldCount = storeScans[storeId] || 0;
-
- // 为该门店的扫码次数 +1
- storeScans[storeId] = oldCount + 1;
-
- partnerObj.set('storeScans', storeScans);
-
- // 同时更新总扫码次数
- const oldTotalCount = partnerObj.get('scanCount') || 0;
- partnerObj.increment('scanCount', 1);
-
- await partnerObj.save();
-
- console.log('✅ [更新成功] 异业扫码次数已更新');
- console.log(' - 门店ID:', storeId);
- console.log(' - 该门店扫码次数: %d → %d', oldCount, storeScans[storeId]);
- console.log(' - 总扫码次数: %d → %d', oldTotalCount, oldTotalCount + 1);
- } else {
- console.error('❌ [错误] 未找到异业合作伙伴记录');
- }
-
- console.log('🤝 ===========================================');
- } catch (e) {
- console.error('❌ [异业处理失败] 处理异业合作伙伴绑定失败:', e);
- console.error(' - 错误信息:', e.message);
- console.error(' - 错误堆栈:', e.stack);
- console.log('🤝 ===========================================');
- }
- }
- } catch (error) {
- console.warn('⚠️ 保存扫码记录失败:', error);
- // 不影响主流程
- }
- }
- });
|