index.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  1. // var Parse = getApp().Parse;
  2. // var app = getApp()
  3. // const { wxLogin } = require('./utils/login')
  4. const CONFIG = require("config.js");
  5. let config = {
  6. appid: CONFIG.default.appid,
  7. company: CONFIG.default.company,
  8. rootPage: CONFIG.default.rootPage,
  9. }
  10. const plugin = requirePlugin('fm-plugin')
  11. const { Parse, checkAuth } = plugin
  12. // enabledOptions 可能由插件初始化写入;未授权/首登异常时可能为 undefined
  13. // 避免 data 初始化阶段直接读取 [0] 导致页面直接崩溃。
  14. const _enabledOptions = wx.getStorageSync("enabledOptions");
  15. const splashUrl = Array.isArray(_enabledOptions) && _enabledOptions.length ? _enabledOptions[0] : '';
  16. Page({
  17. /**
  18. * 页面的初始数据
  19. */
  20. data: {
  21. splashUrl,
  22. loading:true
  23. },
  24. /**
  25. * 生命周期函数--监听页面加载
  26. */
  27. onLoad: async function (options) {
  28. // 拦截插件的"登录信息已过期"提示
  29. const originalShowModal = wx.showModal;
  30. wx.showModal = function(options) {
  31. // 如果是"登录信息已过期"的提示,改为友好的重新登录提示
  32. if (options.content && options.content.includes('登录信息过期')) {
  33. console.log('⚠️ 拦截到"登录信息已过期"提示,改为友好提示');
  34. return originalShowModal.call(this, {
  35. title: '提示',
  36. content: '登录状态异常,是否重新登录?',
  37. showCancel: true,
  38. cancelText: '取消',
  39. confirmText: '重新登录',
  40. success: (result) => {
  41. if (result.confirm) {
  42. // 清除登录状态
  43. wx.removeStorageSync("sessionToken");
  44. wx.removeStorageSync("userLogin");
  45. // 重新加载首页
  46. const rootPage = getApp().globalData.rootPage || getApp().globalData.defaultTabBar?.list?.[0]?.pagePath || '/pages/index/index';
  47. wx.reLaunch({
  48. url: rootPage
  49. });
  50. }
  51. // 调用原始的 success 回调
  52. if (options.success) {
  53. options.success(result);
  54. }
  55. }
  56. });
  57. }
  58. // 其他提示正常显示
  59. return originalShowModal.call(this, options);
  60. };
  61. wx.login({
  62. success: function (res) {
  63. if (res.code) {
  64. console.log(res);
  65. // wx.request({
  66. // url: "https://server.fmode.cn/api/wxapp/auth_wxapp",
  67. // data: {
  68. // c: getApp().globalData.company,
  69. // code: res.code,
  70. // },
  71. // async success(res) {
  72. // wx.setStorageSync("userInfo", res.data);
  73. // resolve(res)
  74. // },
  75. // });
  76. }
  77. },
  78. fail: function (err) {
  79. wx.showToast({
  80. title: '服务器繁忙,请稍后重试',
  81. })
  82. }
  83. });
  84. wx.setStorageSync("invite", null);
  85. // 处理扫码链接(options.q 包含完整的URL或activityId)
  86. if (options.q) {
  87. let str = decodeURIComponent(options.q); // 扫描二维码获得的跳转链接
  88. // 兼容一些环境中把 & 编码成 & 的情况,防止参数解析错误(如 scanCount=0&storeId=...)
  89. if (str.indexOf('&') !== -1) {
  90. console.log('🔧 检测到 URL 中包含 &,自动还原为 &');
  91. str = str.replace(/&/g, '&');
  92. }
  93. // 检查是否是员工邀请链接(app.fmode.cn/dev/pobingfeng/manager/staff?invite=xxx)
  94. if (str.includes('app.fmode.cn/dev/pobingfeng/manager/staff')) {
  95. let obj = this.getParaName(str);
  96. if (obj && obj.invite) {
  97. wx.setStorageSync("invite", obj.invite);
  98. console.log('✅ 检测到员工邀请链接,invite:', obj.invite);
  99. }
  100. // 员工邀请链接不需要跳转到店铺,直接返回
  101. this.setData({ options: options });
  102. plugin.init(config, wx.getStorageSync('invite'));
  103. return;
  104. }
  105. // 检查是否是活动海报二维码(activityId作为qrCode参数值)
  106. // 如果str不包含http/https,且看起来像是一个ID,则可能是activityId
  107. if (!str.includes('http://') && !str.includes('https://') && !str.includes('?')) {
  108. // 可能是活动ID,尝试作为activityId处理
  109. if (str && str.length > 0 && !isNaN(str)) {
  110. options.activityId = str;
  111. console.log('✅ 检测到活动海报二维码,activityId:', str);
  112. // 活动二维码需要特殊处理,先保存activityId
  113. wx.setStorageSync("activityId", str);
  114. }
  115. }
  116. // 处理店铺相关的二维码链接(pwa.fmode.cn/gomini/pmd/)
  117. // 从完整URL中提取参数
  118. if (str.includes('pwa.fmode.cn/gomini/pmd') || str.includes('?')) {
  119. let obj = this.getParaName(str);
  120. if (obj && obj.invite) {
  121. wx.setStorageSync("invite", obj.invite);
  122. }
  123. // 将所有参数合并到 options 中
  124. obj && Object.keys(obj).forEach(key=> options[key] = obj[key]);
  125. }
  126. }
  127. // 兼容从编译参数或页面直达传入的 storeId
  128. if (options && options.scene && !options.storeId) {
  129. try {
  130. const sceneStr = decodeURIComponent(options.scene)
  131. if (sceneStr) {
  132. const pairs = sceneStr.split('&')
  133. for (const p of pairs) {
  134. const [k, v] = p.split('=')
  135. if (k === 'storeId' && v) {
  136. options.storeId = v
  137. break
  138. }
  139. }
  140. }
  141. } catch (e) {
  142. console.warn('解析 scene 失败:', e)
  143. }
  144. }
  145. this.setData({
  146. options: options
  147. })
  148. let {
  149. time,
  150. dramaId,
  151. roomId,
  152. orderId,
  153. shopId,
  154. invite,
  155. activityId,
  156. company,
  157. inviteHost,
  158. storeId
  159. } = options
  160. time && wx.setStorageSync("time", time);
  161. dramaId && wx.setStorageSync("dramaId", dramaId);
  162. roomId && wx.setStorageSync("roomId", roomId);
  163. orderId && wx.setStorageSync("orderId", orderId);
  164. shopId && wx.setStorageSync("shopId", shopId);
  165. invite && wx.setStorageSync("invite", invite);
  166. activityId && wx.setStorageSync("activityId", activityId);
  167. inviteHost && wx.setStorageSync("inviteHost", true);
  168. if (storeId) {
  169. // 扫码进入时,强制设置店铺 ID,标记为扫码来源
  170. wx.setStorageSync('storeId', storeId)
  171. getApp().globalData.storeId = storeId
  172. wx.setStorageSync('storeId_from_scan', true)
  173. console.log('✅ 入口页扫码进入,已设置店铺 ID(优先级最高):', storeId)
  174. }
  175. if (company) getApp().globalData.toCompany = true;
  176. // 禁用扫码逻辑(当前需求:不需要扫码验证/统计,减少进入 H5 的耗时与无效日志)
  177. // 仍保留 storeId 的显式入参处理(在上面 if (storeId) 块里已生效)。
  178. if (false) {
  179. this.checkAndHandleScan(options);
  180. }
  181. plugin.init(config, wx.getStorageSync('invite'))
  182. },
  183. /**
  184. * 生命周期函数--监听页面初次渲染完成
  185. */
  186. onReady: async function () { },
  187. /**
  188. * 生命周期函数--监听页面显示
  189. */
  190. onShow: async function () {
  191. await this.review()
  192. },
  193. async review(force){
  194. try {
  195. let options = this.data.options
  196. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath
  197. if (options) {
  198. let objArr = Object.keys(options)
  199. if (objArr && objArr.length > 0) {
  200. let parms = '?'
  201. objArr.forEach((o, index) => {
  202. if (index > 0) {
  203. parms += '&' + o + '=' + options[o]
  204. } else {
  205. parms += o + '=' + options[o]
  206. }
  207. })
  208. url += parms
  209. }
  210. }
  211. let currentUser = Parse.User.current()
  212. console.log('===========================================');
  213. console.log('======= index.js review 方法 =======');
  214. console.log('当前用户:', currentUser ? currentUser.id : '无');
  215. console.log('用户手机号:', currentUser?.get('mobile') || '无');
  216. console.log('用户名:', currentUser?.get('username') || '无');
  217. console.log('Session Token:', currentUser?.getSessionToken()?.substring(0, 20) || '无');
  218. console.log('userLogin 存储:', wx.getStorageSync('userLogin') || '无');
  219. console.log('force 参数:', force);
  220. console.log('===========================================');
  221. // 查询 Company 的 isPublishing 字段
  222. let isPublishing = false;
  223. try {
  224. const companyQuery = new Parse.Query('Company');
  225. companyQuery.equalTo('objectId', getApp().globalData.company);
  226. companyQuery.select('isPublishing');
  227. try {
  228. const companyObj = await companyQuery.first();
  229. if (companyObj) {
  230. isPublishing = companyObj.get('isPublishing') === true;
  231. console.log('📋 Company isPublishing:', isPublishing);
  232. } else {
  233. console.log('⚠️ 未找到 Company 记录,默认 isPublishing = false');
  234. isPublishing = false;
  235. }
  236. } catch (queryError) {
  237. console.error('❌ 查询 Company 失败(可能 token 无效):', queryError.message);
  238. // 查询失败时,默认为 false(强制登录)
  239. isPublishing = false;
  240. }
  241. // 保存到全局,供其他页面使用
  242. getApp().globalData.isPublishing = isPublishing;
  243. wx.setStorageSync('isPublishing', isPublishing);
  244. } catch (error) {
  245. console.error('❌ 查询 Company isPublishing 失败:', error);
  246. // 查询失败时,默认为 false(强制登录)
  247. isPublishing = false;
  248. }
  249. // 根据 isPublishing 决定是否强制登录
  250. // 扫码进入时,强制登录以确保能拿到 token 扣减流量
  251. const isScanEntry = options && (options.storeId && (options.scanCount || options.partnerId || options.userId || options.employeeId));
  252. if (!currentUser || force || isScanEntry) {
  253. console.log('🔄 开始调用 checkAuth...');
  254. // isPublishing == true 时不强制授权,否则强制授权
  255. // 但如果是扫码进入,则必须强制授权
  256. let forceAuth = !isPublishing;
  257. if (isScanEntry) {
  258. console.log('🚀 检测到扫码进入,强制登录以扣减流量');
  259. forceAuth = true;
  260. }
  261. console.log('🔐 是否强制登录:', forceAuth);
  262. let r = await checkAuth(forceAuth);
  263. console.log('===========================================');
  264. console.log('======= checkAuth 返回结果 =======');
  265. console.log('返回值:', r);
  266. // 重新获取用户信息
  267. currentUser = Parse.User.current();
  268. console.log('checkAuth 后的用户:', currentUser ? currentUser.id : '无');
  269. console.log('checkAuth 后的手机号:', currentUser?.get('mobile') || '无');
  270. console.log('checkAuth 后的 Session Token:', currentUser?.getSessionToken()?.substring(0, 20) || '无');
  271. console.log('===========================================');
  272. // 如果强制登录但用户未登录,不允许继续访问
  273. if (forceAuth && !r) {
  274. console.log('❌ 强制登录模式,用户未登录,停止访问');
  275. return;
  276. }
  277. // 即使登录失败,也允许继续访问(仅在非强制登录模式下)
  278. if(!r) {
  279. console.log('⚠️ 用户未登录或拒绝授权,允许游客访问');
  280. // 不要 return,继续执行后面的跳转逻辑
  281. } else {
  282. // 登录成功,设置 userLogin
  283. if (currentUser && currentUser.get('mobile')) {
  284. wx.setStorageSync("userLogin", currentUser.id);
  285. console.log('✅ 授权登录成功,已设置 userLogin:', currentUser.id);
  286. console.log('✅ 用户手机号:', currentUser.get('mobile'));
  287. } else {
  288. console.warn('⚠️ checkAuth 返回成功,但用户没有手机号!');
  289. console.warn(' 用户对象:', currentUser);
  290. }
  291. // 禁用扫码相关统计/来源记录
  292. if (false) {
  293. await this.checkAndRecordPendingScan();
  294. await this.checkAndRecordUserSourceOnLogin();
  295. }
  296. }
  297. } else {
  298. console.log('✅ 用户已登录,跳过 checkAuth');
  299. // 用户已登录,确保 userLogin 已设置
  300. if (currentUser.get('mobile')) {
  301. wx.setStorageSync("userLogin", currentUser.id);
  302. console.log('✅ 已确认 userLogin:', currentUser.id);
  303. }
  304. this.updateUser(currentUser.id);
  305. // 禁用扫码相关统计/来源记录
  306. if (false) {
  307. await this.checkAndRecordPendingScan();
  308. await this.checkAndRecordUserSourceOnLogin();
  309. }
  310. }
  311. getApp().Parse = Parse
  312. getApp().checkAuth = checkAuth
  313. if (!await this.getCompanyServerExpire(url)) {
  314. return
  315. }
  316. // 检查是否需要跳转到活动页面
  317. if (wx.getStorageSync('need_activity_redirect') === true) {
  318. await this.redirectToActivityPage();
  319. return;
  320. }
  321. // 禁用扫码跳转统计页
  322. if (false && this.shouldRedirectToScanPage()) {
  323. await this.redirectToScanPage();
  324. return;
  325. }
  326. console.log('✅ 准备跳转到:', url);
  327. wx.redirectTo({
  328. url: url,
  329. success: () => {
  330. console.log('✅ redirectTo 跳转成功');
  331. },
  332. fail: (err) => {
  333. console.error('❌ redirectTo 失败:', err);
  334. console.log('⚠️ 尝试使用 reLaunch');
  335. // 降级:尝试使用 reLaunch
  336. wx.reLaunch({
  337. url: url,
  338. success: () => {
  339. console.log('✅ reLaunch 跳转成功');
  340. },
  341. fail: (err2) => {
  342. console.error('❌ reLaunch 也失败:', err2);
  343. // 显示错误提示
  344. this.setData({ loading: false });
  345. wx.showModal({
  346. title: '温馨提示',
  347. content: '页面加载失败,请检查网络后重试。',
  348. showCancel: true,
  349. cancelText: '退出',
  350. confirmText: '重试',
  351. success: (result) => {
  352. if (result.confirm) {
  353. this.review(true);
  354. } else {
  355. wx.exitMiniProgram();
  356. }
  357. }
  358. });
  359. }
  360. });
  361. }
  362. });
  363. }
  364. catch (err) {
  365. console.log('❌ review 方法出错:', err);
  366. /* 登录身份信息到期,重新登陆 */
  367. if((err?.message?.indexOf('Session token is expired') != -1 || err?.message?.indexOf('Invalid session token') != -1) && !force){
  368. console.log('⚠️ Session Token 过期,准备重新登录');
  369. // 保存需要保留的数据
  370. const invite = wx.getStorageSync('invite');
  371. const agreementAccepted = wx.getStorageSync('user_agreement_accepted');
  372. const storeId = wx.getStorageSync('storeId');
  373. const isPublishing = wx.getStorageSync('isPublishing');
  374. // 先登出 Parse 用户
  375. try {
  376. await Parse.User.logOut();
  377. console.log('✅ Parse 用户已登出');
  378. } catch (logoutErr) {
  379. console.warn('⚠️ Parse 登出失败:', logoutErr);
  380. }
  381. // 清除所有存储
  382. wx.clearStorageSync();
  383. // 恢复需要保留的数据
  384. if (invite) wx.setStorageSync('invite', invite);
  385. if (agreementAccepted) wx.setStorageSync('user_agreement_accepted', agreementAccepted);
  386. if (storeId) wx.setStorageSync('storeId', storeId);
  387. if (isPublishing !== undefined) wx.setStorageSync('isPublishing', isPublishing);
  388. console.log('✅ 已清除过期登录信息,保留必要数据');
  389. console.log(' 保留的 invite:', invite || '无');
  390. console.log(' 保留的协议状态:', agreementAccepted || '无');
  391. console.log(' 保留的店铺ID:', storeId || '无');
  392. /* 强制重新登录 */
  393. this.review(true);
  394. return;
  395. }
  396. // 如果出错,尝试继续跳转到主页(游客模式)
  397. console.log('⚠️ 登录出错,尝试游客模式访问');
  398. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
  399. if (this.data.options) {
  400. let objArr = Object.keys(this.data.options)
  401. if (objArr && objArr.length > 0) {
  402. let parms = '?'
  403. objArr.forEach((o, index) => {
  404. if (index > 0) {
  405. parms += '&' + o + '=' + this.data.options[o]
  406. } else {
  407. parms += o + '=' + this.data.options[o]
  408. }
  409. })
  410. url += parms
  411. }
  412. }
  413. wx.redirectTo({
  414. url: url,
  415. fail: () => {
  416. // 如果跳转失败,显示错误提示
  417. this.setData({
  418. loading:false
  419. })
  420. wx.showModal({
  421. title: '温馨提示',
  422. content: '页面加载失败,请检查网络后重试。',
  423. showCancel: true,
  424. cancelText: '退出',
  425. confirmText: '重试',
  426. success: (result) => {
  427. if (result.confirm) {
  428. // 用户选择重试
  429. this.review(true)
  430. } else {
  431. // 用户选择退出
  432. wx.exitMiniProgram()
  433. }
  434. },
  435. });
  436. }
  437. });
  438. }
  439. },
  440. /**
  441. * 检查并记录待处理的扫码统计
  442. * 同时记录用户来源信息到 _User 表
  443. */
  444. async checkAndRecordPendingScan() {
  445. try {
  446. const pendingScan = wx.getStorageSync('pending_scan_record');
  447. if (!pendingScan) {
  448. return;
  449. }
  450. console.log('===========================================');
  451. console.log('======= 发现待记录的扫码信息 =======');
  452. console.log('扫码信息:', pendingScan);
  453. console.log('===========================================');
  454. // 检查是否超时(24小时)
  455. const now = Date.now();
  456. const scanTime = pendingScan.timestamp || 0;
  457. const hoursPassed = (now - scanTime) / (1000 * 60 * 60);
  458. if (hoursPassed > 24) {
  459. console.log('⚠️ 扫码信息已超过24小时,不再记录');
  460. wx.removeStorageSync('pending_scan_record');
  461. return;
  462. }
  463. // 记录用户来源信息
  464. await this.recordUserSource(pendingScan);
  465. // 记录扫码统计
  466. await this.recordScanStatistics({
  467. storeId: pendingScan.storeId,
  468. sourceType: pendingScan.sourceType,
  469. sourceId: pendingScan.sourceId,
  470. ownerId: pendingScan.ownerId,
  471. employeeId: pendingScan.employeeId,
  472. partnerId: pendingScan.partnerId,
  473. userId: pendingScan.userId,
  474. productId: pendingScan.productId,
  475. scanCount: pendingScan.scanCount
  476. });
  477. // 清除待记录的扫码信息
  478. wx.removeStorageSync('pending_scan_record');
  479. console.log('✅ 扫码统计已记录并清除');
  480. } catch (error) {
  481. console.error('❌ 记录待处理扫码信息失败:', error);
  482. }
  483. },
  484. /**
  485. * 记录用户来源信息到 _User 表
  486. * 根据扫码参数判断来源类型并保存到用户的 source 字段
  487. *
  488. * 来源类型:
  489. * 1. 渠道xxx→异业xxx(老板后台添加的异业)
  490. * 2. 渠道xxx→异业xxx→员工xxx(员工后台添加的异业)
  491. * 3. 员工xxx
  492. * 4. 老板
  493. * 5. 自主进入(无任何推荐)
  494. */
  495. async recordUserSource(scanInfo) {
  496. try {
  497. const currentUser = Parse.User.current();
  498. if (!currentUser) {
  499. console.log('⚠️ 用户未登录,无法记录来源');
  500. return;
  501. }
  502. // 如果用户已经有来源信息,不再覆盖(首次来源原则)
  503. const existingSource = currentUser.get('source');
  504. if (existingSource) {
  505. console.log('ℹ️ 用户已有来源信息,不覆盖:', existingSource);
  506. return;
  507. }
  508. console.log('📊 ===========================================');
  509. console.log('📊 [记录来源] 开始记录用户来源信息');
  510. console.log('📊 用户ID:', currentUser.id);
  511. console.log('📊 ===========================================');
  512. const { partnerId, employeeId, ownerId, userId, storeId } = scanInfo;
  513. let sourceInfo = {
  514. type: 'self_entry', // 默认为自主进入
  515. label: '自主进入',
  516. timestamp: new Date(),
  517. storeId: storeId
  518. };
  519. // 判断来源类型
  520. if (partnerId && employeeId) {
  521. // 情况2: 渠道xxx→异业xxx→员工xxx(员工后台添加的异业)
  522. console.log('🔍 [来源类型] 渠道→异业→员工');
  523. try {
  524. // 查询异业信息
  525. const partnerQuery = new Parse.Query('Partner');
  526. const partner = await partnerQuery.get(partnerId);
  527. const partnerName = partner.get('name') || '未知异业';
  528. const channelName = partner.get('channelName') || partner.get('category') || '未知渠道';
  529. // 查询员工信息
  530. const employeeQuery = new Parse.Query('Employee');
  531. const employee = await employeeQuery.get(employeeId);
  532. const employeeName = employee.get('name') || '未知员工';
  533. sourceInfo = {
  534. type: 'channel_partner_employee',
  535. label: `${channelName},${partnerName},员工${employeeName}`,
  536. channelName: channelName,
  537. partnerId: partnerId,
  538. partnerName: partnerName,
  539. employeeId: employeeId,
  540. employeeName: employeeName,
  541. timestamp: new Date(),
  542. storeId: storeId
  543. };
  544. console.log('✅ [来源信息] 渠道→异业→员工:', sourceInfo.label);
  545. } catch (error) {
  546. console.error('❌ 查询异业或员工信息失败:', error);
  547. }
  548. } else if (partnerId && !employeeId) {
  549. // 情况1: 渠道xxx→异业xxx(老板后台添加的异业)
  550. console.log('🔍 [来源类型] 渠道→异业');
  551. try {
  552. // 查询异业信息
  553. const partnerQuery = new Parse.Query('Partner');
  554. const partner = await partnerQuery.get(partnerId);
  555. const partnerName = partner.get('name') || '未知异业';
  556. const channelName = partner.get('channelName') || partner.get('category') || '未知渠道';
  557. sourceInfo = {
  558. type: 'channel_partner',
  559. label: `${channelName},${partnerName}`,
  560. channelName: channelName,
  561. partnerId: partnerId,
  562. partnerName: partnerName,
  563. timestamp: new Date(),
  564. storeId: storeId
  565. };
  566. console.log('✅ [来源信息] 渠道→异业:', sourceInfo.label);
  567. } catch (error) {
  568. console.error('❌ 查询异业信息失败:', error);
  569. }
  570. } else if (employeeId && !partnerId) {
  571. // 情况3: 员工xxx
  572. console.log('🔍 [来源类型] 员工');
  573. try {
  574. // 查询员工信息
  575. const employeeQuery = new Parse.Query('Employee');
  576. const employee = await employeeQuery.get(employeeId);
  577. const employeeName = employee.get('name') || '未知员工';
  578. sourceInfo = {
  579. type: 'employee',
  580. label: employeeName,
  581. employeeId: employeeId,
  582. employeeName: employeeName,
  583. timestamp: new Date(),
  584. storeId: storeId
  585. };
  586. console.log('✅ [来源信息] 员工:', sourceInfo.label);
  587. } catch (error) {
  588. console.error('❌ 查询员工信息失败:', error);
  589. }
  590. } else if (ownerId) {
  591. // 情况4: 老板
  592. console.log('🔍 [来源类型] 老板');
  593. sourceInfo = {
  594. type: 'owner',
  595. label: '老板',
  596. ownerId: ownerId,
  597. timestamp: new Date(),
  598. storeId: storeId
  599. };
  600. console.log('✅ [来源信息] 老板');
  601. } else if (userId) {
  602. // 推广员(如果有的话)
  603. console.log('🔍 [来源类型] 推广员');
  604. try {
  605. // 查询推广员信息
  606. const userQuery = new Parse.Query('_User');
  607. const promoter = await userQuery.get(userId);
  608. const promoterName = promoter.get('username') || promoter.get('mobile') || '未知推广员';
  609. sourceInfo = {
  610. type: 'promoter',
  611. label: `推广员${promoterName}`,
  612. userId: userId,
  613. promoterName: promoterName,
  614. timestamp: new Date(),
  615. storeId: storeId
  616. };
  617. console.log('✅ [来源信息] 推广员:', sourceInfo.label);
  618. } catch (error) {
  619. console.error('❌ 查询推广员信息失败:', error);
  620. }
  621. } else {
  622. // 情况5: 自主进入(无任何推荐)
  623. console.log('🔍 [来源类型] 自主进入');
  624. console.log('✅ [来源信息] 自主进入');
  625. }
  626. // 保存来源信息到用户
  627. currentUser.set('source', sourceInfo);
  628. await currentUser.save();
  629. console.log('✅ [保存成功] 用户来源信息已保存');
  630. console.log(' - 来源类型:', sourceInfo.type);
  631. console.log(' - 来源标签:', sourceInfo.label);
  632. console.log('📊 ===========================================');
  633. } catch (error) {
  634. console.error('❌ 记录用户来源失败:', error);
  635. }
  636. },
  637. /**
  638. * 用户登录后检查并记录来源信息
  639. * 如果用户是首次登录且没有来源信息,根据当前的扫码参数记录来源
  640. */
  641. async checkAndRecordUserSourceOnLogin() {
  642. try {
  643. const currentUser = Parse.User.current();
  644. if (!currentUser) {
  645. return;
  646. }
  647. // 如果用户已经有来源信息,不再处理
  648. const existingSource = currentUser.get('source');
  649. if (existingSource) {
  650. console.log('ℹ️ 用户已有来源信息,跳过记录');
  651. return;
  652. }
  653. // 检查是否有扫码参数
  654. const scanStoreId = wx.getStorageSync('scan_storeId');
  655. const scanPartnerId = wx.getStorageSync('scan_partnerId');
  656. const scanEmployeeId = wx.getStorageSync('scan_employeeId');
  657. const scanOwnerId = wx.getStorageSync('scan_ownerId');
  658. const scanUserId = wx.getStorageSync('scan_userId');
  659. // 如果有任何扫码参数,记录来源
  660. if (scanStoreId || scanPartnerId || scanEmployeeId || scanOwnerId || scanUserId) {
  661. console.log('📊 检测到扫码参数,记录用户来源');
  662. await this.recordUserSource({
  663. storeId: scanStoreId,
  664. partnerId: scanPartnerId,
  665. employeeId: scanEmployeeId,
  666. ownerId: scanOwnerId,
  667. userId: scanUserId
  668. });
  669. } else {
  670. // 没有任何扫码参数,标记为自主进入
  671. console.log('📊 无扫码参数,标记为自主进入');
  672. await this.recordUserSource({
  673. storeId: wx.getStorageSync('storeId') || null
  674. });
  675. }
  676. } catch (error) {
  677. console.error('❌ 检查并记录用户来源失败:', error);
  678. }
  679. },
  680. async updateUser(id) {
  681. try {
  682. let User = new Parse.Query('_User')
  683. let user = await User.get(id)
  684. let invite = wx.getStorageSync('invite')
  685. //查询邀请人user
  686. let query = new Parse.Query("_User")
  687. query.equalTo('objectId', invite)
  688. let result = await query.first()
  689. if (result && result.id && result.get("invite")?.id == user.id) {
  690. console.error('邀请人不能是自己的下级')
  691. return
  692. }
  693. if (invite && !user.get('invite') && user.id != invite && !user.get('agentLevel')) {
  694. console.log('上下级绑定成功');
  695. user.set('invite', {
  696. __type: "Pointer",
  697. className: "_User",
  698. objectId: invite
  699. })
  700. user.set('agent', {
  701. __type: "Pointer",
  702. className: "_User",
  703. objectId: invite
  704. })
  705. await Parse.Cloud.run('user_save', {
  706. userJson: user.toJSON()
  707. })
  708. }
  709. } catch (error) {
  710. console.error('❌ updateUser 失败:', error.message);
  711. // 不阻断流程,继续执行
  712. }
  713. },
  714. async getCompanyServerExpire(url) {
  715. try {
  716. let query = new Parse.Query('Company')
  717. query.equalTo('objectId', getApp().globalData.company)
  718. query.select('expireDate', 'expireMap')
  719. let com = await query.first()
  720. if (com?.id && com?.get('expireDate')) {
  721. let now = + new Date()
  722. let expireTime = + new Date(com?.get('expireDate'))
  723. if (com?.get('expireMap') && com.get('expireMap')[getApp().globalData.appid]) {
  724. expireTime = + new Date(com.get('expireMap')[getApp().globalData.appid])
  725. }
  726. if (now >= expireTime) {
  727. console.log('服务器到期');
  728. wx.reLaunch({
  729. url: `common-page/pages/loading/index?url=${url}`,
  730. });
  731. return
  732. }
  733. }
  734. return true
  735. } catch (error) {
  736. console.error('❌ getCompanyServerExpire 失败:', error.message);
  737. // 查询失败时,允许继续访问
  738. return true
  739. }
  740. },
  741. onUnload: function () {
  742. wx.setStorageSync("active", 0);
  743. },
  744. getParaName(url) {
  745. if (!url || url.indexOf('?') == -1) {
  746. return
  747. }
  748. // 兼容 URL 中 & 的情况,先统一还原为 &
  749. if (url.indexOf('&') !== -1) {
  750. url = url.replace(/&/g, '&');
  751. }
  752. // 提取查询参数部分(去除可能的 hash 部分)
  753. let queryString = url.split('?')[1];
  754. // 如果包含 #,只取 # 之前的部分
  755. if (queryString.indexOf('#') !== -1) {
  756. queryString = queryString.split('#')[0];
  757. }
  758. return this.setObject(queryString) //封装成对象
  759. },
  760. setObject(paraArr) {
  761. let obj = {}
  762. let arr1 = paraArr.split('&')
  763. arr1.forEach(item => {
  764. let str = item.split('=')
  765. let key = str[0]
  766. let val = str[1]
  767. obj[key] = val
  768. })
  769. return obj
  770. },
  771. /**
  772. * 检查并处理扫码参数
  773. * 支持所有类型的二维码:
  774. * 1. 推广员二维码: ?scanCount=0&storeId=xxx&userId=xxx
  775. * 2. 产品二维码: ?scanCount=0&storeId=xxx&productId=xxx
  776. * 3. 案例二维码: ?scanCount=0&storeId=xxx&caseId=xxx
  777. * 4. 活动海报二维码: activityId作为qrCode参数值
  778. * 5. 异业合作伙伴二维码(移动端 / PC端统一): ?scanCount=xxx&storeId=xxx&partnerId=xxx
  779. * 6. 员工邀请二维码(移动端): ?scanCount=0&storeId=xxx&employeeId=xxx
  780. * 7. 我的二维码(老板): ?scanCount=0&storeId=xxx&ownerId=xxx
  781. * 8. 我的二维码(员工): ?scanCount=0&storeId=xxx&employeeId=xxx
  782. * 9. 方案分享二维码: ?scanCount=0&storeId=xxx&planId=xxx&shareUserId=xxx
  783. */
  784. checkAndHandleScan(options) {
  785. console.log('🔍🔍🔍 ========================================');
  786. console.log('🔍 [扫码检测] 开始检查扫码参数');
  787. console.log('🔍 完整 options 对象:', JSON.stringify(options, null, 2));
  788. console.log('🔍🔍🔍 ========================================');
  789. const {
  790. scanCount,
  791. ownerId,
  792. employeeId,
  793. partnerId,
  794. storeId,
  795. productId,
  796. caseId,
  797. userId, // 推广员二维码使用userId
  798. activityId,
  799. schemeId, // 方案ID(旧参数名)
  800. planId, // 方案ID(新参数名,优先使用)
  801. shareUserId, // 分享方案的用户ID
  802. q // 扫码链接
  803. } = options;
  804. // planId 和 schemeId 兼容处理,优先使用 planId
  805. const finalPlanId = planId || schemeId;
  806. console.log('📋 [扫码参数] 提取的参数:');
  807. console.log(' - scanCount:', scanCount || '无');
  808. console.log(' - storeId:', storeId || '无');
  809. console.log(' - ownerId:', ownerId || '无');
  810. console.log(' - employeeId:', employeeId || '无');
  811. console.log(' - partnerId:', partnerId || '无');
  812. console.log(' - userId:', userId || '无');
  813. console.log(' - productId:', productId || '无');
  814. console.log(' - caseId:', caseId || '无');
  815. console.log(' - activityId:', activityId || '无');
  816. console.log(' - planId:', planId || '无');
  817. console.log(' - schemeId:', schemeId || '无');
  818. console.log(' - finalPlanId (最终使用):', finalPlanId || '无');
  819. console.log(' - shareUserId:', shareUserId || '无');
  820. console.log(' - q (扫码链接):', q || '无');
  821. // 处理活动海报二维码(activityId作为qrCode参数值)
  822. if (activityId && !storeId) {
  823. console.log('🎯 ===========================================');
  824. console.log('🎯 [活动二维码] 检测到活动海报二维码');
  825. console.log('🎯 活动ID (activityId):', activityId);
  826. console.log('🎯 来源类型: 活动海报');
  827. console.log('🎯 ===========================================');
  828. // 活动二维码需要跳转到活动页面,不需要跳转到店铺
  829. wx.setStorageSync('scan_activityId', activityId);
  830. wx.setStorageSync('need_activity_redirect', true);
  831. return;
  832. }
  833. // 如果存在 storeId,说明是扫码进入具体门店(包括异业分享)
  834. if (storeId) {
  835. console.log('🏪 ===========================================');
  836. console.log('🏪 [店铺扫码] 检测到扫码参数');
  837. console.log('🏪 店铺ID (storeId):', storeId);
  838. console.log('🏪 扫码次数 (scanCount):', scanCount || '0');
  839. // 确定来源类型
  840. // 规则:
  841. // 1. 扫描异业码(partnerId)→ sourceType = "partner"
  842. // 2. 扫描员工码(employeeId、老板/员工)→ sourceType = "sales" 或 "promoter"
  843. // 3. 扫描其他码(产品码、案例码等)→ sourceType = "scan"
  844. let sourceType = 'scan'; // 默认为通用扫码
  845. let sourceId = null;
  846. if (partnerId) {
  847. // 异业合作伙伴二维码
  848. sourceType = 'partner';
  849. sourceId = partnerId;
  850. console.log('🤝 [来源识别] 来源类型: 异业合作伙伴 (partner)');
  851. console.log('🤝 合作伙伴ID (partnerId):', partnerId);
  852. } else if (employeeId) {
  853. // 员工二维码(包括老板和员工)
  854. sourceType = 'sales';
  855. sourceId = employeeId;
  856. console.log('👤 [来源识别] 来源类型: 员工展业 (sales)');
  857. console.log('👤 员工ID (employeeId):', employeeId);
  858. } else if (ownerId) {
  859. // 老板二维码
  860. sourceType = 'sales';
  861. sourceId = ownerId;
  862. console.log('👔 [来源识别] 来源类型: 老板展业 (sales)');
  863. console.log('👔 老板ID (ownerId):', ownerId);
  864. } else if (userId) {
  865. // 推广员二维码
  866. sourceType = 'promoter';
  867. sourceId = userId;
  868. console.log('📢 [来源识别] 来源类型: 推广员展业 (promoter)');
  869. console.log('📢 推广员ID (userId):', userId);
  870. } else {
  871. // 其他情况(产品码、案例码、店铺分享等)
  872. sourceType = 'scan';
  873. console.log('🏬 [来源识别] 来源类型: 通用扫码 (scan)');
  874. }
  875. if (productId) {
  876. console.log('📦 [目标内容] 产品ID (productId):', productId);
  877. }
  878. if (caseId) {
  879. console.log('📸 [目标内容] 案例ID (caseId):', caseId);
  880. }
  881. if (finalPlanId) {
  882. console.log('📋 [目标内容] 方案ID (planId/schemeId):', finalPlanId);
  883. console.log('👤 [分享人] 分享用户ID (shareUserId):', shareUserId || '无');
  884. }
  885. console.log('🏪 ===========================================');
  886. // 保存到临时存储,用于后续跳转和统计
  887. console.log('💾 [保存扫码信息] 开始保存到本地存储...');
  888. wx.setStorageSync('scan_storeId', storeId);
  889. wx.setStorageSync('scan_scanCount', scanCount || '0');
  890. wx.setStorageSync('scan_sourceType', sourceType);
  891. wx.setStorageSync('scan_sourceId', sourceId || '');
  892. wx.setStorageSync('scan_ownerId', ownerId || '');
  893. wx.setStorageSync('scan_employeeId', employeeId || '');
  894. wx.setStorageSync('scan_partnerId', partnerId || '');
  895. wx.setStorageSync('scan_userId', userId || '');
  896. if (productId) {
  897. wx.setStorageSync('scan_productId', productId);
  898. }
  899. if (caseId) {
  900. wx.setStorageSync('scan_caseId', caseId);
  901. }
  902. if (finalPlanId) {
  903. wx.setStorageSync('scan_planId', finalPlanId);
  904. if (shareUserId) {
  905. wx.setStorageSync('scan_shareUserId', shareUserId);
  906. }
  907. }
  908. wx.setStorageSync('need_scan_redirect', true);
  909. console.log('✅ [保存完成] 扫码信息已保存');
  910. console.log('📋 [保存内容摘要]:');
  911. console.log(' - 来源类型:', sourceType);
  912. console.log(' - 来源ID:', sourceId || '无');
  913. console.log(' - 店铺ID:', storeId);
  914. console.log(' - 需要跳转:', true);
  915. } else if (partnerId) {
  916. // 理论上异业二维码现在也必须带 storeId,这里仅作为兜底保护
  917. console.warn('⚠️ 检测到异业合作伙伴二维码缺少 storeId,无法确定门店,请检查二维码生成逻辑');
  918. }
  919. },
  920. /**
  921. * 判断是否需要跳转到扫码统计页面
  922. */
  923. shouldRedirectToScanPage() {
  924. return wx.getStorageSync('need_scan_redirect') === true;
  925. },
  926. /**
  927. * 跳转到扫码对应的店铺页面
  928. * 根据 storeId 跳转到对应店铺,同时记录所有来源信息用于统计
  929. */
  930. async redirectToScanPage() {
  931. try {
  932. console.log('🚀 ===========================================');
  933. console.log('🚀 [跳转处理] 开始处理扫码跳转');
  934. console.log('🚀 ===========================================');
  935. // 获取所有扫码相关参数
  936. const storeId = wx.getStorageSync('scan_storeId');
  937. const scanCount = wx.getStorageSync('scan_scanCount');
  938. const sourceType = wx.getStorageSync('scan_sourceType');
  939. const sourceId = wx.getStorageSync('scan_sourceId');
  940. const ownerId = wx.getStorageSync('scan_ownerId');
  941. const employeeId = wx.getStorageSync('scan_employeeId');
  942. const partnerId = wx.getStorageSync('scan_partnerId');
  943. const userId = wx.getStorageSync('scan_userId');
  944. const productId = wx.getStorageSync('scan_productId');
  945. const caseId = wx.getStorageSync('scan_caseId');
  946. const planId = wx.getStorageSync('scan_planId');
  947. const shareUserId = wx.getStorageSync('scan_shareUserId');
  948. console.log('📖 [读取存储] 从本地存储读取扫码信息:');
  949. console.log(' - storeId:', storeId || '无');
  950. console.log(' - sourceType:', sourceType || '无');
  951. console.log(' - sourceId:', sourceId || '无');
  952. console.log(' - scanCount:', scanCount || '无');
  953. console.log(' - ownerId:', ownerId || '无');
  954. console.log(' - employeeId:', employeeId || '无');
  955. console.log(' - partnerId:', partnerId || '无');
  956. console.log(' - userId:', userId || '无');
  957. console.log(' - productId:', productId || '无');
  958. console.log(' - caseId:', caseId || '无');
  959. console.log(' - planId:', planId || '无');
  960. console.log(' - shareUserId:', shareUserId || '无');
  961. // 清除临时存储
  962. console.log('🧹 [清理存储] 清除临时扫码信息...');
  963. wx.removeStorageSync('scan_storeId');
  964. wx.removeStorageSync('scan_scanCount');
  965. wx.removeStorageSync('scan_sourceType');
  966. wx.removeStorageSync('scan_sourceId');
  967. wx.removeStorageSync('scan_ownerId');
  968. wx.removeStorageSync('scan_employeeId');
  969. wx.removeStorageSync('scan_partnerId');
  970. wx.removeStorageSync('scan_userId');
  971. wx.removeStorageSync('scan_productId');
  972. wx.removeStorageSync('scan_caseId');
  973. wx.removeStorageSync('scan_planId');
  974. wx.removeStorageSync('scan_shareUserId');
  975. wx.removeStorageSync('need_scan_redirect');
  976. console.log('✅ [清理完成] 临时存储已清除');
  977. if (!storeId) {
  978. console.error('❌ [错误] 缺少 storeId 参数,无法跳转');
  979. return;
  980. }
  981. console.log('📊 ===========================================');
  982. console.log('📊 [扫码来源汇总] 扫码进入店铺');
  983. console.log('📊 店铺 ID:', storeId);
  984. console.log('📊 来源类型:', sourceType);
  985. console.log('📊 来源 ID:', sourceId || '无');
  986. console.log('📊 扫码次数:', scanCount);
  987. if (ownerId) console.log('📊 老板 ID:', ownerId);
  988. if (employeeId) console.log('📊 员工 ID:', employeeId);
  989. if (partnerId) console.log('📊 合作伙伴 ID:', partnerId);
  990. if (userId) console.log('📊 推广员 ID:', userId);
  991. if (productId) console.log('📊 产品 ID:', productId);
  992. if (caseId) console.log('📊 案例 ID:', caseId);
  993. if (planId) {
  994. console.log('📊 方案 ID:', planId);
  995. console.log('📊 分享用户 ID:', shareUserId || '无');
  996. }
  997. console.log('📊 ===========================================');
  998. // 设置店铺 ID 到全局和本地存储
  999. wx.setStorageSync('storeId', storeId);
  1000. getApp().globalData.storeId = storeId;
  1001. // 保存来源信息到本地存储(用于后续统计或绑定关系)
  1002. if (sourceId) {
  1003. wx.setStorageSync('scan_from_sourceType', sourceType);
  1004. wx.setStorageSync('scan_from_sourceId', sourceId);
  1005. console.log('✅ 已记录来源信息:', sourceType, sourceId);
  1006. }
  1007. // 检查用户是否已登录
  1008. const currentUser = Parse.User.current();
  1009. console.log('👤 [登录检查] 检查用户登录状态...');
  1010. console.log(' - 当前用户:', currentUser ? currentUser.id : '未登录');
  1011. console.log(' - 手机号:', currentUser?.get('mobile') || '无');
  1012. if (currentUser) {
  1013. // 用户已登录,立即记录扫码统计
  1014. console.log('✅ [已登录] 用户已登录,立即记录扫码统计');
  1015. await this.recordScanStatistics({
  1016. storeId,
  1017. sourceType,
  1018. sourceId,
  1019. ownerId,
  1020. employeeId,
  1021. partnerId,
  1022. userId,
  1023. productId,
  1024. scanCount
  1025. });
  1026. } else {
  1027. // 用户未登录,保存扫码信息,等登录后再记录
  1028. console.log('⚠️ [未登录] 用户未登录,保存扫码信息待登录后记录');
  1029. const pendingData = {
  1030. storeId,
  1031. sourceType,
  1032. sourceId,
  1033. ownerId,
  1034. employeeId,
  1035. partnerId,
  1036. userId,
  1037. productId,
  1038. scanCount,
  1039. timestamp: Date.now()
  1040. };
  1041. console.log('💾 [待处理记录] 保存内容:', JSON.stringify(pendingData, null, 2));
  1042. wx.setStorageSync('pending_scan_record', pendingData);
  1043. console.log('✅ [保存成功] 待处理扫码记录已保存');
  1044. }
  1045. // 如果有产品ID,直接跳转到产品详情的 H5 页面
  1046. if (productId) {
  1047. console.log('🎯 检测到产品ID,跳转到产品详情页');
  1048. await this.redirectToProductDetail(storeId, productId, partnerId);
  1049. return;
  1050. }
  1051. // 如果有案例ID,直接跳转到案例详情的 H5 页面
  1052. if (caseId) {
  1053. console.log('🎯 检测到案例ID,跳转到案例详情页');
  1054. await this.redirectToCaseDetail(storeId, caseId, partnerId);
  1055. return;
  1056. }
  1057. // 如果有方案ID,跳转到门店首页并传递方案ID
  1058. if (planId) {
  1059. console.log('🎯 检测到方案ID,跳转到门店首页展示方案');
  1060. await this.redirectToStoreWithPlan(storeId, planId, shareUserId, partnerId);
  1061. return;
  1062. }
  1063. // 获取默认首页路径并跳转
  1064. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
  1065. url += `?storeId=${storeId}`;
  1066. // 如果有产品ID,添加到URL参数中
  1067. if (productId) {
  1068. url += `&productId=${productId}`;
  1069. }
  1070. // 如果有异业合作伙伴ID,添加到URL参数中传回web-view
  1071. if (partnerId) {
  1072. url += `&partnerId=${partnerId}`;
  1073. }
  1074. console.log('✅ 跳转到店铺页面:', url);
  1075. wx.redirectTo({
  1076. url: url,
  1077. fail: (err) => {
  1078. console.error('❌ 跳转失败:', err);
  1079. // 如果 redirectTo 失败,尝试 reLaunch
  1080. wx.reLaunch({
  1081. url: url,
  1082. fail: (err2) => {
  1083. console.error('❌ reLaunch 也失败:', err2);
  1084. }
  1085. });
  1086. }
  1087. });
  1088. } catch (error) {
  1089. console.error('❌ 跳转到店铺页面失败:', error);
  1090. }
  1091. },
  1092. /**
  1093. * 跳转到活动页面
  1094. */
  1095. async redirectToActivityPage() {
  1096. try {
  1097. const activityId = wx.getStorageSync('scan_activityId');
  1098. // 清除临时存储
  1099. wx.removeStorageSync('scan_activityId');
  1100. wx.removeStorageSync('need_activity_redirect');
  1101. if (!activityId) {
  1102. console.error('❌ 缺少 activityId 参数,无法跳转');
  1103. return;
  1104. }
  1105. console.log('===========================================');
  1106. console.log('======= 扫码进入活动页面 =======');
  1107. console.log('活动 ID (activityId):', activityId);
  1108. console.log('===========================================');
  1109. // 保存活动ID
  1110. wx.setStorageSync('activityId', activityId);
  1111. // 获取默认首页路径并跳转(活动页面可能需要根据实际路由调整)
  1112. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
  1113. url += `?activityId=${activityId}`;
  1114. console.log('✅ 跳转到活动页面:', url);
  1115. wx.redirectTo({
  1116. url: url,
  1117. fail: (err) => {
  1118. console.error('❌ 跳转失败:', err);
  1119. wx.reLaunch({
  1120. url: url,
  1121. fail: (err2) => {
  1122. console.error('❌ reLaunch 也失败:', err2);
  1123. }
  1124. });
  1125. }
  1126. });
  1127. } catch (error) {
  1128. console.error('❌ 跳转到活动页面失败:', error);
  1129. }
  1130. },
  1131. /**
  1132. * 跳转到产品详情的 H5 页面
  1133. * @param {string} storeId - 店铺 ID
  1134. * @param {string} productId - 产品 ID
  1135. * @param {string} partnerId - 可选的合作伙伴 ID
  1136. */
  1137. async redirectToProductDetail(storeId, productId, partnerId = null) {
  1138. try {
  1139. console.log('===========================================');
  1140. console.log('======= 跳转到产品详情页 =======');
  1141. console.log('店铺 ID:', storeId);
  1142. console.log('产品 ID:', productId);
  1143. if (partnerId) console.log('合作伙伴 ID:', partnerId);
  1144. console.log('===========================================');
  1145. const currentUser = Parse.User.current();
  1146. const token = currentUser ? currentUser.getSessionToken() : null;
  1147. // 构建产品详情的 H5 URL(不要在这里编码,后面统一编码)
  1148. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/products?storeId=${storeId}`;
  1149. // 如果有 token,添加到 URL
  1150. if (token) {
  1151. h5Url += `&token=${token}`;
  1152. } else {
  1153. // 如果没有 token,使用游客模式
  1154. h5Url += `&guestMode=true`;
  1155. }
  1156. // 添加产品ID(不要在这里编码,避免双重编码)
  1157. h5Url += `&productId=${productId}`;
  1158. // 如果有合作伙伴ID,也添加到URL中
  1159. if (partnerId) {
  1160. h5Url += `&partnerId=${partnerId}`;
  1161. }
  1162. console.log('🌐 H5 URL:', h5Url);
  1163. // 编码 URL(统一在这里编码一次)
  1164. const encodedUrl = encodeURIComponent(h5Url);
  1165. // 构建 web-view 页面路径
  1166. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
  1167. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  1168. console.log('===========================================');
  1169. wx.redirectTo({
  1170. url: webViewPath,
  1171. success: () => {
  1172. console.log('✅ 跳转到产品详情页成功');
  1173. },
  1174. fail: (err) => {
  1175. console.error('❌ 跳转失败:', err);
  1176. // 如果 redirectTo 失败,尝试 reLaunch
  1177. wx.reLaunch({
  1178. url: webViewPath,
  1179. fail: (err2) => {
  1180. console.error('❌ reLaunch 也失败:', err2);
  1181. }
  1182. });
  1183. }
  1184. });
  1185. } catch (error) {
  1186. console.error('❌ 跳转到产品详情页失败:', error);
  1187. }
  1188. },
  1189. /**
  1190. * 跳转到案例详情的 H5 页面
  1191. * @param {string} storeId - 店铺 ID
  1192. * @param {string} caseId - 案例 ID
  1193. * @param {string} partnerId - 可选的合作伙伴 ID
  1194. */
  1195. async redirectToCaseDetail(storeId, caseId, partnerId = null) {
  1196. try {
  1197. console.log('===========================================');
  1198. console.log('======= 跳转到案例详情页 =======');
  1199. console.log('店铺 ID:', storeId);
  1200. console.log('案例 ID:', caseId);
  1201. if (partnerId) console.log('合作伙伴 ID:', partnerId);
  1202. console.log('===========================================');
  1203. const currentUser = Parse.User.current();
  1204. const token = currentUser ? currentUser.getSessionToken() : null;
  1205. // 构建案例详情的 H5 URL(不要在这里编码,后面统一编码)
  1206. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/cases?storeId=${storeId}`;
  1207. // 如果有 token,添加到 URL
  1208. if (token) {
  1209. h5Url += `&token=${token}`;
  1210. } else {
  1211. // 如果没有 token,使用游客模式
  1212. h5Url += `&guestMode=true`;
  1213. }
  1214. // 添加案例ID(不要在这里编码,避免双重编码)
  1215. h5Url += `&caseId=${caseId}`;
  1216. // 如果有合作伙伴ID,也添加到URL中
  1217. if (partnerId) {
  1218. h5Url += `&partnerId=${partnerId}`;
  1219. }
  1220. console.log('🌐 H5 URL:', h5Url);
  1221. // 编码 URL(统一在这里编码一次)
  1222. const encodedUrl = encodeURIComponent(h5Url);
  1223. // 构建 web-view 页面路径
  1224. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
  1225. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  1226. console.log('===========================================');
  1227. wx.redirectTo({
  1228. url: webViewPath,
  1229. success: () => {
  1230. console.log('✅ 跳转到案例详情页成功');
  1231. },
  1232. fail: (err) => {
  1233. console.error('❌ 跳转失败:', err);
  1234. // 如果 redirectTo 失败,尝试 reLaunch
  1235. wx.reLaunch({
  1236. url: webViewPath,
  1237. fail: (err2) => {
  1238. console.error('❌ reLaunch 也失败:', err2);
  1239. }
  1240. });
  1241. }
  1242. });
  1243. } catch (error) {
  1244. console.error('❌ 跳转到案例详情页失败:', error);
  1245. }
  1246. },
  1247. /**
  1248. * 跳转到门店首页并展示方案
  1249. * @param {string} storeId - 店铺 ID
  1250. * @param {string} planId - 方案 ID
  1251. * @param {string} shareUserId - 分享方案的用户 ID
  1252. * @param {string} partnerId - 可选的合作伙伴 ID
  1253. */
  1254. async redirectToStoreWithPlan(storeId, planId, shareUserId = null, partnerId = null) {
  1255. try {
  1256. console.log('===========================================');
  1257. console.log('======= 跳转到门店首页展示方案 =======');
  1258. console.log('店铺 ID:', storeId);
  1259. console.log('方案 ID:', planId);
  1260. if (shareUserId) console.log('分享用户 ID:', shareUserId);
  1261. if (partnerId) console.log('合作伙伴 ID:', partnerId);
  1262. console.log('===========================================');
  1263. const currentUser = Parse.User.current();
  1264. const token = currentUser ? currentUser.getSessionToken() : null;
  1265. // 构建门店首页的 H5 URL,带上方案ID
  1266. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?storeId=${storeId}`;
  1267. // 如果有 token,添加到 URL
  1268. if (token) {
  1269. h5Url += `&token=${token}`;
  1270. } else {
  1271. // 如果没有 token,使用游客模式
  1272. h5Url += `&guestMode=true`;
  1273. }
  1274. // 添加方案ID(使用planId参数名)
  1275. h5Url += `&planId=${planId}`;
  1276. // 如果有分享用户ID,也添加到URL中
  1277. if (shareUserId) {
  1278. h5Url += `&shareUserId=${shareUserId}`;
  1279. }
  1280. // 如果有合作伙伴ID,也添加到URL中
  1281. if (partnerId) {
  1282. h5Url += `&partnerId=${partnerId}`;
  1283. }
  1284. console.log('🌐 H5 URL:', h5Url);
  1285. // 编码 URL
  1286. const encodedUrl = encodeURIComponent(h5Url);
  1287. // 构建 web-view 页面路径
  1288. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
  1289. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  1290. console.log('===========================================');
  1291. wx.redirectTo({
  1292. url: webViewPath,
  1293. success: () => {
  1294. console.log('✅ 跳转到门店首页展示方案成功');
  1295. },
  1296. fail: (err) => {
  1297. console.error('❌ 跳转失败:', err);
  1298. // 如果 redirectTo 失败,尝试 reLaunch
  1299. wx.reLaunch({
  1300. url: webViewPath,
  1301. fail: (err2) => {
  1302. console.error('❌ reLaunch 也失败:', err2);
  1303. }
  1304. });
  1305. }
  1306. });
  1307. } catch (error) {
  1308. console.error('❌ 跳转到门店首页展示方案失败:', error);
  1309. }
  1310. },
  1311. /**
  1312. * 记录扫码统计信息
  1313. * @param {Object} params - 扫码参数对象
  1314. * @param {string} params.storeId - 店铺 ID
  1315. * @param {string} params.sourceType - 来源类型 (employee/owner/partner/promoter/store)
  1316. * @param {string} params.sourceId - 来源 ID
  1317. * @param {string} params.ownerId - 老板 ID
  1318. * @param {string} params.employeeId - 员工 ID
  1319. * @param {string} params.partnerId - 合作伙伴 ID
  1320. * @param {string} params.userId - 推广员 ID
  1321. * @param {string} params.productId - 产品 ID
  1322. * @param {string} params.scanCount - 扫码次数
  1323. */
  1324. async recordScanStatistics(params) {
  1325. try {
  1326. console.log('📝 ===========================================');
  1327. console.log('📝 [扫码统计] 开始记录扫码统计');
  1328. console.log('📝 ===========================================');
  1329. const {
  1330. storeId,
  1331. sourceType,
  1332. sourceId,
  1333. ownerId,
  1334. employeeId,
  1335. partnerId,
  1336. userId,
  1337. productId,
  1338. scanCount
  1339. } = params;
  1340. console.log('📋 [统计参数] 接收到的参数:');
  1341. console.log(' - storeId:', storeId);
  1342. console.log(' - sourceType:', sourceType);
  1343. console.log(' - sourceId:', sourceId || '无');
  1344. console.log(' - ownerId:', ownerId || '无');
  1345. console.log(' - employeeId:', employeeId || '无');
  1346. console.log(' - partnerId:', partnerId || '无');
  1347. console.log(' - userId:', userId || '无');
  1348. console.log(' - productId:', productId || '无');
  1349. console.log(' - scanCount:', scanCount || '0');
  1350. // 检查用户是否已登录
  1351. const currentUser = Parse.User.current();
  1352. if (!currentUser) {
  1353. console.log('⚠️ [未登录] 用户未登录,不记录扫码统计');
  1354. return;
  1355. }
  1356. console.log('👤 [用户信息] 当前登录用户:');
  1357. console.log(' - 用户ID:', currentUser.id);
  1358. console.log(' - 手机号:', currentUser.get('mobile') || '无');
  1359. // 如果没有来源信息,不记录统计
  1360. if (!sourceId && !ownerId && !employeeId && !partnerId && !userId) {
  1361. console.log('ℹ️ [跳过] 无来源信息,跳过统计记录');
  1362. return;
  1363. }
  1364. console.log('✅ [开始记录] 用户已登录且有来源信息,开始记录');
  1365. // 创建扫码记录
  1366. const ScanRecord = Parse.Object.extend('ScanRecord');
  1367. const record = new ScanRecord();
  1368. record.set('company', {
  1369. __type: 'Pointer',
  1370. className: 'Company',
  1371. objectId: getApp().globalData.company
  1372. });
  1373. record.set('storeId', storeId);
  1374. record.set('sourceType', sourceType || 'unknown');
  1375. record.set('scanCount', parseInt(scanCount) || 0);
  1376. record.set('scanTime', new Date());
  1377. console.log('📦 [记录内容] 准备保存到 ScanRecord 表:');
  1378. console.log(' - company:', getApp().globalData.company);
  1379. console.log(' - storeId:', storeId);
  1380. console.log(' - sourceType:', sourceType || 'unknown');
  1381. console.log(' - scanCount:', parseInt(scanCount) || 0);
  1382. console.log(' - scanTime:', new Date().toISOString());
  1383. // 根据来源类型设置对应的ID
  1384. if (ownerId) {
  1385. record.set('ownerId', ownerId);
  1386. console.log(' - ownerId:', ownerId);
  1387. }
  1388. if (employeeId) {
  1389. record.set('employeeId', employeeId);
  1390. console.log(' - employeeId:', employeeId);
  1391. }
  1392. if (partnerId) {
  1393. record.set('partnerId', partnerId);
  1394. console.log(' - partnerId:', partnerId);
  1395. }
  1396. if (userId) {
  1397. record.set('userId', userId);
  1398. console.log(' - userId:', userId);
  1399. }
  1400. if (productId) {
  1401. record.set('productId', productId);
  1402. console.log(' - productId:', productId);
  1403. }
  1404. // 记录扫码用户
  1405. record.set('user', {
  1406. __type: 'Pointer',
  1407. className: '_User',
  1408. objectId: currentUser.id
  1409. });
  1410. console.log(' - user:', currentUser.id);
  1411. await record.save();
  1412. console.log('✅ [保存成功] 扫码记录已保存到数据库');
  1413. console.log(' - 记录ID:', record.id);
  1414. // 如果存在异业合作伙伴ID,处理异业绑定和扫码次数
  1415. if (partnerId) {
  1416. try {
  1417. console.log('🤝 ===========================================');
  1418. console.log('🤝 [异业处理] 开始处理异业扫码逻辑');
  1419. console.log('🤝 用户ID:', currentUser.id);
  1420. console.log('🤝 异业ID:', partnerId);
  1421. console.log('🤝 门店ID:', storeId);
  1422. console.log('🤝 ===========================================');
  1423. // 检查用户是否已经绑定了异业合作伙伴
  1424. const userBoundPartner = currentUser.get('Partner');
  1425. const userBoundPartnerId = userBoundPartner ? userBoundPartner.id : null;
  1426. console.log('🔍 [绑定检查] 用户已绑定的异业ID:', userBoundPartnerId || '无');
  1427. // 规则1:如果用户已绑定其他异业,不处理当前异业的扫码
  1428. if (userBoundPartnerId && userBoundPartnerId !== partnerId) {
  1429. console.log('⚠️ [规则1] 用户已绑定其他异业,不处理当前异业的扫码');
  1430. console.log(' - 已绑定异业:', userBoundPartnerId);
  1431. console.log(' - 当前扫码异业:', partnerId);
  1432. console.log('🤝 ===========================================');
  1433. return;
  1434. }
  1435. // 规则2:检查该用户在该门店是否已经扫过该异业的码
  1436. console.log('🔍 [重复检查] 检查是否已扫过该异业的码...');
  1437. const ScanRecord = Parse.Object.extend('ScanRecord');
  1438. const scanQuery = new Parse.Query(ScanRecord);
  1439. scanQuery.equalTo('user', {
  1440. __type: 'Pointer',
  1441. className: '_User',
  1442. objectId: currentUser.id
  1443. });
  1444. scanQuery.equalTo('partnerId', partnerId);
  1445. scanQuery.equalTo('storeId', storeId);
  1446. const existingScan = await scanQuery.first();
  1447. if (existingScan) {
  1448. console.log('⚠️ [规则2] 该用户在该门店已扫过该异业的码,不重复计数');
  1449. console.log(' - 首次扫码时间:', existingScan.get('scanTime'));
  1450. console.log(' - 记录ID:', existingScan.id);
  1451. console.log('🤝 ===========================================');
  1452. return;
  1453. }
  1454. console.log('✅ [首次扫码] 该用户在该门店首次扫该异业码');
  1455. // 规则3:如果用户还没有绑定异业,绑定当前异业
  1456. if (!userBoundPartnerId) {
  1457. console.log('🔗 [规则3] 用户首次扫异业码,开始绑定异业合作伙伴');
  1458. console.log(' - 异业ID:', partnerId);
  1459. currentUser.set('Partner', {
  1460. __type: 'Pointer',
  1461. className: 'Partner',
  1462. objectId: partnerId
  1463. });
  1464. await currentUser.save();
  1465. console.log('✅ [绑定成功] 异业绑定成功');
  1466. } else {
  1467. console.log('ℹ️ [已绑定] 用户已绑定该异业,无需重复绑定');
  1468. }
  1469. // 规则4:为该异业在该门店增加扫码次数
  1470. console.log('📊 [规则4] 开始更新异业扫码次数...');
  1471. const Partner = Parse.Object.extend('Partner');
  1472. const partnerQuery = new Parse.Query(Partner);
  1473. const partnerObj = await partnerQuery.get(partnerId);
  1474. if (partnerObj) {
  1475. console.log('📋 [异业信息] 找到异业合作伙伴记录');
  1476. console.log(' - 异业ID:', partnerObj.id);
  1477. console.log(' - 异业名称:', partnerObj.get('name') || '未设置');
  1478. // 获取或初始化门店扫码次数映射
  1479. let storeScans = partnerObj.get('storeScans') || {};
  1480. const oldCount = storeScans[storeId] || 0;
  1481. // 为该门店的扫码次数 +1
  1482. storeScans[storeId] = oldCount + 1;
  1483. partnerObj.set('storeScans', storeScans);
  1484. // 同时更新总扫码次数
  1485. const oldTotalCount = partnerObj.get('scanCount') || 0;
  1486. partnerObj.increment('scanCount', 1);
  1487. await partnerObj.save();
  1488. console.log('✅ [更新成功] 异业扫码次数已更新');
  1489. console.log(' - 门店ID:', storeId);
  1490. console.log(' - 该门店扫码次数: %d → %d', oldCount, storeScans[storeId]);
  1491. console.log(' - 总扫码次数: %d → %d', oldTotalCount, oldTotalCount + 1);
  1492. } else {
  1493. console.error('❌ [错误] 未找到异业合作伙伴记录');
  1494. }
  1495. console.log('🤝 ===========================================');
  1496. } catch (e) {
  1497. console.error('❌ [异业处理失败] 处理异业合作伙伴绑定失败:', e);
  1498. console.error(' - 错误信息:', e.message);
  1499. console.error(' - 错误堆栈:', e.stack);
  1500. console.log('🤝 ===========================================');
  1501. }
  1502. }
  1503. } catch (error) {
  1504. console.warn('⚠️ 保存扫码记录失败:', error);
  1505. // 不影响主流程
  1506. }
  1507. }
  1508. });