index.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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. Page({
  13. /**
  14. * 页面的初始数据
  15. */
  16. data: {
  17. splashUrl: wx.getStorageSync("enabledOptions")[0],
  18. loading:true
  19. },
  20. /**
  21. * 生命周期函数--监听页面加载
  22. */
  23. onLoad: async function (options) {
  24. wx.login({
  25. success: function (res) {
  26. if (res.code) {
  27. console.log(res);
  28. // wx.request({
  29. // url: "https://server.fmode.cn/api/wxapp/auth_wxapp",
  30. // data: {
  31. // c: getApp().globalData.company,
  32. // code: res.code,
  33. // },
  34. // async success(res) {
  35. // wx.setStorageSync("userInfo", res.data);
  36. // resolve(res)
  37. // },
  38. // });
  39. }
  40. },
  41. fail: function (err) {
  42. wx.showToast({
  43. title: '服务器繁忙,请稍后重试',
  44. })
  45. }
  46. });
  47. wx.setStorageSync("invite", null);
  48. // 处理扫码链接(options.q 包含完整的URL或activityId)
  49. if (options.q) {
  50. let str = decodeURIComponent(options.q); // 扫描二维码获得的跳转链接
  51. // 兼容一些环境中把 & 编码成 & 的情况,防止参数解析错误(如 scanCount=0&storeId=...)
  52. if (str.indexOf('&') !== -1) {
  53. console.log('🔧 检测到 URL 中包含 &,自动还原为 &');
  54. str = str.replace(/&/g, '&');
  55. }
  56. // 检查是否是员工邀请链接(app.fmode.cn/dev/pobingfeng/manager/staff?invite=xxx)
  57. if (str.includes('app.fmode.cn/dev/pobingfeng/manager/staff')) {
  58. let obj = this.getParaName(str);
  59. if (obj && obj.invite) {
  60. wx.setStorageSync("invite", obj.invite);
  61. console.log('✅ 检测到员工邀请链接,invite:', obj.invite);
  62. }
  63. // 员工邀请链接不需要跳转到店铺,直接返回
  64. this.setData({ options: options });
  65. plugin.init(config, wx.getStorageSync('invite'));
  66. return;
  67. }
  68. // 检查是否是活动海报二维码(activityId作为qrCode参数值)
  69. // 如果str不包含http/https,且看起来像是一个ID,则可能是activityId
  70. if (!str.includes('http://') && !str.includes('https://') && !str.includes('?')) {
  71. // 可能是活动ID,尝试作为activityId处理
  72. if (str && str.length > 0 && !isNaN(str)) {
  73. options.activityId = str;
  74. console.log('✅ 检测到活动海报二维码,activityId:', str);
  75. // 活动二维码需要特殊处理,先保存activityId
  76. wx.setStorageSync("activityId", str);
  77. }
  78. }
  79. // 处理店铺相关的二维码链接(pwa.fmode.cn/gomini/pmd/)
  80. // 从完整URL中提取参数
  81. if (str.includes('pwa.fmode.cn/gomini/pmd') || str.includes('?')) {
  82. let obj = this.getParaName(str);
  83. if (obj && obj.invite) {
  84. wx.setStorageSync("invite", obj.invite);
  85. }
  86. // 将所有参数合并到 options 中
  87. obj && Object.keys(obj).forEach(key=> options[key] = obj[key]);
  88. }
  89. }
  90. // 兼容从编译参数或页面直达传入的 storeId
  91. if (options && options.scene && !options.storeId) {
  92. try {
  93. const sceneStr = decodeURIComponent(options.scene)
  94. if (sceneStr) {
  95. const pairs = sceneStr.split('&')
  96. for (const p of pairs) {
  97. const [k, v] = p.split('=')
  98. if (k === 'storeId' && v) {
  99. options.storeId = v
  100. break
  101. }
  102. }
  103. }
  104. } catch (e) {
  105. console.warn('解析 scene 失败:', e)
  106. }
  107. }
  108. this.setData({
  109. options: options
  110. })
  111. let {
  112. time,
  113. dramaId,
  114. roomId,
  115. orderId,
  116. shopId,
  117. invite,
  118. activityId,
  119. company,
  120. inviteHost,
  121. storeId
  122. } = options
  123. time && wx.setStorageSync("time", time);
  124. dramaId && wx.setStorageSync("dramaId", dramaId);
  125. roomId && wx.setStorageSync("roomId", roomId);
  126. orderId && wx.setStorageSync("orderId", orderId);
  127. shopId && wx.setStorageSync("shopId", shopId);
  128. invite && wx.setStorageSync("invite", invite);
  129. activityId && wx.setStorageSync("activityId", activityId);
  130. inviteHost && wx.setStorageSync("inviteHost", true);
  131. if (storeId) {
  132. wx.setStorageSync('storeId', storeId)
  133. getApp().globalData.storeId = storeId
  134. console.log('✅ 入口页已设置店铺 ID:', storeId)
  135. }
  136. if (company) getApp().globalData.toCompany = true;
  137. // 检查是否是扫码进入(需要统计扫码次数)
  138. this.checkAndHandleScan(options);
  139. plugin.init(config, wx.getStorageSync('invite'))
  140. },
  141. /**
  142. * 生命周期函数--监听页面初次渲染完成
  143. */
  144. onReady: async function () { },
  145. /**
  146. * 生命周期函数--监听页面显示
  147. */
  148. onShow: async function () {
  149. await this.review()
  150. },
  151. async review(force){
  152. try {
  153. let options = this.data.options
  154. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath
  155. if (options) {
  156. let objArr = Object.keys(options)
  157. if (objArr && objArr.length > 0) {
  158. let parms = '?'
  159. objArr.forEach((o, index) => {
  160. if (index > 0) {
  161. parms += '&' + o + '=' + options[o]
  162. } else {
  163. parms += o + '=' + options[o]
  164. }
  165. })
  166. url += parms
  167. }
  168. }
  169. let currentUser = Parse.User.current()
  170. console.log(Parse.User.current())
  171. // 修改:不强制登录,允许游客访问
  172. if (!currentUser || force) {
  173. // 尝试静默登录(不强制授权)
  174. let r = await checkAuth(false) // 改为 false,不强制授权
  175. console.log(r);
  176. // 即使登录失败,也允许继续访问
  177. if(!r) {
  178. console.log('⚠️ 用户未登录或拒绝授权,允许游客访问');
  179. // 不要 return,继续执行后面的跳转逻辑
  180. } else {
  181. // 登录成功,更新 currentUser 并设置 userLogin
  182. currentUser = Parse.User.current();
  183. if (currentUser && currentUser.get('mobile')) {
  184. wx.setStorageSync("userLogin", currentUser.id);
  185. console.log('✅ 授权登录成功,已设置 userLogin:', currentUser.id);
  186. console.log('✅ 用户手机号:', currentUser.get('mobile'));
  187. }
  188. // 检查是否有待记录的扫码信息
  189. await this.checkAndRecordPendingScan();
  190. }
  191. } else {
  192. // 用户已登录,确保 userLogin 已设置
  193. if (currentUser.get('mobile')) {
  194. wx.setStorageSync("userLogin", currentUser.id);
  195. }
  196. this.updateUser(currentUser.id)
  197. // 用户已登录,检查是否有待记录的扫码信息
  198. await this.checkAndRecordPendingScan();
  199. }
  200. getApp().Parse = Parse
  201. getApp().checkAuth = checkAuth
  202. if (!await this.getCompanyServerExpire(url)) {
  203. return
  204. }
  205. // 检查是否需要跳转到活动页面
  206. if (wx.getStorageSync('need_activity_redirect') === true) {
  207. await this.redirectToActivityPage();
  208. return;
  209. }
  210. // 检查是否需要跳转到扫码统计页面
  211. if (this.shouldRedirectToScanPage()) {
  212. await this.redirectToScanPage();
  213. return;
  214. }
  215. console.log('✅ 准备跳转到:', url);
  216. wx.redirectTo({
  217. url: url,
  218. success: () => {
  219. console.log('✅ redirectTo 跳转成功');
  220. },
  221. fail: (err) => {
  222. console.error('❌ redirectTo 失败:', err);
  223. console.log('⚠️ 尝试使用 reLaunch');
  224. // 降级:尝试使用 reLaunch
  225. wx.reLaunch({
  226. url: url,
  227. success: () => {
  228. console.log('✅ reLaunch 跳转成功');
  229. },
  230. fail: (err2) => {
  231. console.error('❌ reLaunch 也失败:', err2);
  232. // 显示错误提示
  233. this.setData({ loading: false });
  234. wx.showModal({
  235. title: '温馨提示',
  236. content: '页面加载失败,请检查网络后重试。',
  237. showCancel: true,
  238. cancelText: '退出',
  239. confirmText: '重试',
  240. success: (result) => {
  241. if (result.confirm) {
  242. this.review(true);
  243. } else {
  244. wx.exitMiniProgram();
  245. }
  246. }
  247. });
  248. }
  249. });
  250. }
  251. });
  252. }
  253. catch (err) {
  254. console.log(err);
  255. /* 登录身份信息到期,重新登陆 */
  256. if((err?.message.indexOf('Session token is expired') != -1 || err?.message.indexOf('Invalid session token') != -1) && !force){
  257. let invite = wx.getStorageSync('invite')
  258. wx.clearStorageSync()
  259. invite && wx.setStorageSync('invite', invite)
  260. /* 强制重新登录 */
  261. this.review(true)
  262. return
  263. }
  264. // 如果出错,尝试继续跳转到主页(游客模式)
  265. console.log('⚠️ 登录出错,尝试游客模式访问');
  266. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
  267. if (this.data.options) {
  268. let objArr = Object.keys(this.data.options)
  269. if (objArr && objArr.length > 0) {
  270. let parms = '?'
  271. objArr.forEach((o, index) => {
  272. if (index > 0) {
  273. parms += '&' + o + '=' + this.data.options[o]
  274. } else {
  275. parms += o + '=' + this.data.options[o]
  276. }
  277. })
  278. url += parms
  279. }
  280. }
  281. wx.redirectTo({
  282. url: url,
  283. fail: () => {
  284. // 如果跳转失败,显示错误提示
  285. this.setData({
  286. loading:false
  287. })
  288. wx.showModal({
  289. title: '温馨提示',
  290. content: '页面加载失败,请检查网络后重试。',
  291. showCancel: true,
  292. cancelText: '退出',
  293. confirmText: '重试',
  294. success: (result) => {
  295. if (result.confirm) {
  296. // 用户选择重试
  297. this.review(true)
  298. } else {
  299. // 用户选择退出
  300. wx.exitMiniProgram()
  301. }
  302. },
  303. });
  304. }
  305. });
  306. }
  307. },
  308. /**
  309. * 检查并记录待处理的扫码统计
  310. */
  311. async checkAndRecordPendingScan() {
  312. try {
  313. const pendingScan = wx.getStorageSync('pending_scan_record');
  314. if (!pendingScan) {
  315. return;
  316. }
  317. console.log('===========================================');
  318. console.log('======= 发现待记录的扫码信息 =======');
  319. console.log('扫码信息:', pendingScan);
  320. console.log('===========================================');
  321. // 检查是否超时(24小时)
  322. const now = Date.now();
  323. const scanTime = pendingScan.timestamp || 0;
  324. const hoursPassed = (now - scanTime) / (1000 * 60 * 60);
  325. if (hoursPassed > 24) {
  326. console.log('⚠️ 扫码信息已超过24小时,不再记录');
  327. wx.removeStorageSync('pending_scan_record');
  328. return;
  329. }
  330. // 记录扫码统计
  331. await this.recordScanStatistics({
  332. storeId: pendingScan.storeId,
  333. sourceType: pendingScan.sourceType,
  334. sourceId: pendingScan.sourceId,
  335. ownerId: pendingScan.ownerId,
  336. employeeId: pendingScan.employeeId,
  337. partnerId: pendingScan.partnerId,
  338. userId: pendingScan.userId,
  339. productId: pendingScan.productId,
  340. scanCount: pendingScan.scanCount
  341. });
  342. // 清除待记录的扫码信息
  343. wx.removeStorageSync('pending_scan_record');
  344. console.log('✅ 扫码统计已记录并清除');
  345. } catch (error) {
  346. console.error('❌ 记录待处理扫码信息失败:', error);
  347. }
  348. },
  349. async updateUser(id) {
  350. let User = new Parse.Query('_User')
  351. let user = await User.get(id)
  352. let invite = wx.getStorageSync('invite')
  353. //查询邀请人user
  354. let query = new Parse.Query("_User")
  355. query.equalTo('objectId', invite)
  356. let result = await query.first()
  357. if (result && result.id && result.get("invite")?.id == user.id) {
  358. console.error('邀请人不能是自己的下级')
  359. return
  360. }
  361. if (invite && !user.get('invite') && user.id != invite && !user.get('agentLevel')) {
  362. console.log('上下级绑定成功');
  363. user.set('invite', {
  364. __type: "Pointer",
  365. className: "_User",
  366. objectId: invite
  367. })
  368. user.set('agent', {
  369. __type: "Pointer",
  370. className: "_User",
  371. objectId: invite
  372. })
  373. await Parse.Cloud.run('user_save', {
  374. userJson: user.toJSON()
  375. })
  376. }
  377. },
  378. async getCompanyServerExpire(url) {
  379. let query = new Parse.Query('Company')
  380. query.equalTo('objectId', getApp().globalData.company)
  381. query.select('expireDate', 'expireMap')
  382. let com = await query.first()
  383. if (com?.id && com?.get('expireDate')) {
  384. let now = + new Date()
  385. let expireTime = + new Date(com?.get('expireDate'))
  386. if (com?.get('expireMap') && com.get('expireMap')[getApp().globalData.appid]) {
  387. expireTime = + new Date(com.get('expireMap')[getApp().globalData.appid])
  388. }
  389. if (now >= expireTime) {
  390. console.log('服务器到期');
  391. wx.reLaunch({
  392. url: `common-page/pages/loading/index?url=${url}`,
  393. });
  394. return
  395. }
  396. }
  397. return true
  398. },
  399. onUnload: function () {
  400. wx.setStorageSync("active", 0);
  401. },
  402. getParaName(url) {
  403. if (!url || url.indexOf('?') == -1) {
  404. return
  405. }
  406. // 兼容 URL 中 & 的情况,先统一还原为 &
  407. if (url.indexOf('&') !== -1) {
  408. url = url.replace(/&/g, '&');
  409. }
  410. // 提取查询参数部分(去除可能的 hash 部分)
  411. let queryString = url.split('?')[1];
  412. // 如果包含 #,只取 # 之前的部分
  413. if (queryString.indexOf('#') !== -1) {
  414. queryString = queryString.split('#')[0];
  415. }
  416. return this.setObject(queryString) //封装成对象
  417. },
  418. setObject(paraArr) {
  419. let obj = {}
  420. let arr1 = paraArr.split('&')
  421. arr1.forEach(item => {
  422. let str = item.split('=')
  423. let key = str[0]
  424. let val = str[1]
  425. obj[key] = val
  426. })
  427. return obj
  428. },
  429. /**
  430. * 检查并处理扫码参数
  431. * 支持所有类型的二维码:
  432. * 1. 推广员二维码: ?scanCount=0&storeId=xxx&userId=xxx
  433. * 2. 产品二维码: ?scanCount=0&storeId=xxx&productId=xxx
  434. * 3. 案例二维码: ?scanCount=0&storeId=xxx&caseId=xxx
  435. * 4. 活动海报二维码: activityId作为qrCode参数值
  436. * 5. 异业合作伙伴二维码(移动端 / PC端统一): ?scanCount=xxx&storeId=xxx&partnerId=xxx
  437. * 6. 员工邀请二维码(移动端): ?scanCount=0&storeId=xxx&employeeId=xxx
  438. * 7. 我的二维码(老板): ?scanCount=0&storeId=xxx&ownerId=xxx
  439. * 8. 我的二维码(员工): ?scanCount=0&storeId=xxx&employeeId=xxx
  440. */
  441. checkAndHandleScan(options) {
  442. const {
  443. scanCount,
  444. ownerId,
  445. employeeId,
  446. partnerId,
  447. storeId,
  448. productId,
  449. caseId,
  450. userId, // 推广员二维码使用userId
  451. activityId
  452. } = options;
  453. // 处理活动海报二维码(activityId作为qrCode参数值)
  454. if (activityId && !storeId) {
  455. console.log('===========================================');
  456. console.log('======= 检测到活动海报二维码 =======');
  457. console.log('活动ID (activityId):', activityId);
  458. console.log('===========================================');
  459. // 活动二维码需要跳转到活动页面,不需要跳转到店铺
  460. wx.setStorageSync('scan_activityId', activityId);
  461. wx.setStorageSync('need_activity_redirect', true);
  462. return;
  463. }
  464. // 如果存在 storeId,说明是扫码进入具体门店(包括异业分享)
  465. if (storeId) {
  466. console.log('===========================================');
  467. console.log('======= 检测到扫码参数 =======');
  468. console.log('店铺ID (storeId):', storeId);
  469. console.log('扫码次数 (scanCount):', scanCount || '0');
  470. // 确定来源类型
  471. let sourceType = 'unknown';
  472. let sourceId = null;
  473. if (employeeId) {
  474. sourceType = 'employee';
  475. sourceId = employeeId;
  476. console.log('来源类型: 员工展业');
  477. console.log('员工ID (employeeId):', employeeId);
  478. } else if (userId) {
  479. // 推广员二维码使用userId
  480. sourceType = 'promoter';
  481. sourceId = userId;
  482. console.log('来源类型: 推广员展业');
  483. console.log('推广员ID (userId):', userId);
  484. } else if (ownerId) {
  485. sourceType = 'owner';
  486. sourceId = ownerId;
  487. console.log('来源类型: 老板展业');
  488. console.log('老板ID (ownerId):', ownerId);
  489. } else if (partnerId) {
  490. sourceType = 'partner';
  491. sourceId = partnerId;
  492. console.log('来源类型: 异业合作伙伴');
  493. console.log('合作伙伴ID (partnerId):', partnerId);
  494. } else {
  495. sourceType = 'store';
  496. console.log('来源类型: 店铺分享');
  497. }
  498. if (productId) {
  499. console.log('产品ID (productId):', productId);
  500. }
  501. if (caseId) {
  502. console.log('案例ID (caseId):', caseId);
  503. }
  504. console.log('===========================================');
  505. // 保存到临时存储,用于后续跳转和统计
  506. wx.setStorageSync('scan_storeId', storeId);
  507. wx.setStorageSync('scan_scanCount', scanCount || '0');
  508. wx.setStorageSync('scan_sourceType', sourceType);
  509. wx.setStorageSync('scan_sourceId', sourceId || '');
  510. wx.setStorageSync('scan_ownerId', ownerId || '');
  511. wx.setStorageSync('scan_employeeId', employeeId || '');
  512. wx.setStorageSync('scan_partnerId', partnerId || '');
  513. wx.setStorageSync('scan_userId', userId || '');
  514. if (productId) {
  515. wx.setStorageSync('scan_productId', productId);
  516. }
  517. if (caseId) {
  518. wx.setStorageSync('scan_caseId', caseId);
  519. }
  520. wx.setStorageSync('need_scan_redirect', true);
  521. } else if (partnerId) {
  522. // 理论上异业二维码现在也必须带 storeId,这里仅作为兜底保护
  523. console.warn('⚠️ 检测到异业合作伙伴二维码缺少 storeId,无法确定门店,请检查二维码生成逻辑');
  524. }
  525. },
  526. /**
  527. * 判断是否需要跳转到扫码统计页面
  528. */
  529. shouldRedirectToScanPage() {
  530. return wx.getStorageSync('need_scan_redirect') === true;
  531. },
  532. /**
  533. * 跳转到扫码对应的店铺页面
  534. * 根据 storeId 跳转到对应店铺,同时记录所有来源信息用于统计
  535. */
  536. async redirectToScanPage() {
  537. try {
  538. // 获取所有扫码相关参数
  539. const storeId = wx.getStorageSync('scan_storeId');
  540. const scanCount = wx.getStorageSync('scan_scanCount');
  541. const sourceType = wx.getStorageSync('scan_sourceType');
  542. const sourceId = wx.getStorageSync('scan_sourceId');
  543. const ownerId = wx.getStorageSync('scan_ownerId');
  544. const employeeId = wx.getStorageSync('scan_employeeId');
  545. const partnerId = wx.getStorageSync('scan_partnerId');
  546. const userId = wx.getStorageSync('scan_userId');
  547. const productId = wx.getStorageSync('scan_productId');
  548. const caseId = wx.getStorageSync('scan_caseId');
  549. // 清除临时存储
  550. wx.removeStorageSync('scan_storeId');
  551. wx.removeStorageSync('scan_scanCount');
  552. wx.removeStorageSync('scan_sourceType');
  553. wx.removeStorageSync('scan_sourceId');
  554. wx.removeStorageSync('scan_ownerId');
  555. wx.removeStorageSync('scan_employeeId');
  556. wx.removeStorageSync('scan_partnerId');
  557. wx.removeStorageSync('scan_userId');
  558. wx.removeStorageSync('scan_productId');
  559. wx.removeStorageSync('scan_caseId');
  560. wx.removeStorageSync('need_scan_redirect');
  561. if (!storeId) {
  562. console.error('❌ 缺少 storeId 参数,无法跳转');
  563. return;
  564. }
  565. console.log('===========================================');
  566. console.log('======= 扫码进入店铺 =======');
  567. console.log('店铺 ID (storeId):', storeId);
  568. console.log('来源类型 (sourceType):', sourceType);
  569. console.log('来源 ID (sourceId):', sourceId || '无');
  570. console.log('扫码次数 (scanCount):', scanCount);
  571. if (ownerId) console.log('老板 ID (ownerId):', ownerId);
  572. if (employeeId) console.log('员工 ID (employeeId):', employeeId);
  573. if (partnerId) console.log('合作伙伴 ID (partnerId):', partnerId);
  574. if (userId) console.log('推广员 ID (userId):', userId);
  575. if (productId) console.log('产品 ID (productId):', productId);
  576. if (caseId) console.log('案例 ID (caseId):', caseId);
  577. console.log('===========================================');
  578. // 设置店铺 ID 到全局和本地存储
  579. wx.setStorageSync('storeId', storeId);
  580. getApp().globalData.storeId = storeId;
  581. // 保存来源信息到本地存储(用于后续统计或绑定关系)
  582. if (sourceId) {
  583. wx.setStorageSync('scan_from_sourceType', sourceType);
  584. wx.setStorageSync('scan_from_sourceId', sourceId);
  585. console.log('✅ 已记录来源信息:', sourceType, sourceId);
  586. }
  587. // 检查用户是否已登录
  588. const currentUser = Parse.User.current();
  589. if (currentUser) {
  590. // 用户已登录,立即记录扫码统计
  591. console.log('✅ 用户已登录,记录扫码统计');
  592. await this.recordScanStatistics({
  593. storeId,
  594. sourceType,
  595. sourceId,
  596. ownerId,
  597. employeeId,
  598. partnerId,
  599. userId,
  600. productId,
  601. scanCount
  602. });
  603. } else {
  604. // 用户未登录,保存扫码信息,等登录后再记录
  605. console.log('⚠️ 用户未登录,保存扫码信息待登录后记录');
  606. wx.setStorageSync('pending_scan_record', {
  607. storeId,
  608. sourceType,
  609. sourceId,
  610. ownerId,
  611. employeeId,
  612. partnerId,
  613. userId,
  614. productId,
  615. scanCount,
  616. timestamp: Date.now()
  617. });
  618. }
  619. // 如果有产品ID,直接跳转到产品详情的 H5 页面
  620. if (productId) {
  621. console.log('🎯 检测到产品ID,跳转到产品详情页');
  622. await this.redirectToProductDetail(storeId, productId, partnerId);
  623. return;
  624. }
  625. // 如果有案例ID,直接跳转到案例详情的 H5 页面
  626. if (caseId) {
  627. console.log('🎯 检测到案例ID,跳转到案例详情页');
  628. await this.redirectToCaseDetail(storeId, caseId, partnerId);
  629. return;
  630. }
  631. // 获取默认首页路径并跳转
  632. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
  633. url += `?storeId=${storeId}`;
  634. // 如果有产品ID,添加到URL参数中
  635. if (productId) {
  636. url += `&productId=${productId}`;
  637. }
  638. // 如果有异业合作伙伴ID,添加到URL参数中传回web-view
  639. if (partnerId) {
  640. url += `&partnerId=${partnerId}`;
  641. }
  642. console.log('✅ 跳转到店铺页面:', url);
  643. wx.redirectTo({
  644. url: url,
  645. fail: (err) => {
  646. console.error('❌ 跳转失败:', err);
  647. // 如果 redirectTo 失败,尝试 reLaunch
  648. wx.reLaunch({
  649. url: url,
  650. fail: (err2) => {
  651. console.error('❌ reLaunch 也失败:', err2);
  652. }
  653. });
  654. }
  655. });
  656. } catch (error) {
  657. console.error('❌ 跳转到店铺页面失败:', error);
  658. }
  659. },
  660. /**
  661. * 跳转到活动页面
  662. */
  663. async redirectToActivityPage() {
  664. try {
  665. const activityId = wx.getStorageSync('scan_activityId');
  666. // 清除临时存储
  667. wx.removeStorageSync('scan_activityId');
  668. wx.removeStorageSync('need_activity_redirect');
  669. if (!activityId) {
  670. console.error('❌ 缺少 activityId 参数,无法跳转');
  671. return;
  672. }
  673. console.log('===========================================');
  674. console.log('======= 扫码进入活动页面 =======');
  675. console.log('活动 ID (activityId):', activityId);
  676. console.log('===========================================');
  677. // 保存活动ID
  678. wx.setStorageSync('activityId', activityId);
  679. // 获取默认首页路径并跳转(活动页面可能需要根据实际路由调整)
  680. let url = getApp().globalData.rootPage || getApp().globalData.defaultTabBar.list[0].pagePath;
  681. url += `?activityId=${activityId}`;
  682. console.log('✅ 跳转到活动页面:', url);
  683. wx.redirectTo({
  684. url: url,
  685. fail: (err) => {
  686. console.error('❌ 跳转失败:', err);
  687. wx.reLaunch({
  688. url: url,
  689. fail: (err2) => {
  690. console.error('❌ reLaunch 也失败:', err2);
  691. }
  692. });
  693. }
  694. });
  695. } catch (error) {
  696. console.error('❌ 跳转到活动页面失败:', error);
  697. }
  698. },
  699. /**
  700. * 跳转到产品详情的 H5 页面
  701. * @param {string} storeId - 店铺 ID
  702. * @param {string} productId - 产品 ID
  703. * @param {string} partnerId - 可选的合作伙伴 ID
  704. */
  705. async redirectToProductDetail(storeId, productId, partnerId = null) {
  706. try {
  707. console.log('===========================================');
  708. console.log('======= 跳转到产品详情页 =======');
  709. console.log('店铺 ID:', storeId);
  710. console.log('产品 ID:', productId);
  711. if (partnerId) console.log('合作伙伴 ID:', partnerId);
  712. console.log('===========================================');
  713. const currentUser = Parse.User.current();
  714. const token = currentUser ? currentUser.getSessionToken() : null;
  715. // 构建产品详情的 H5 URL(不要在这里编码,后面统一编码)
  716. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/products?storeId=${storeId}`;
  717. // 如果有 token,添加到 URL
  718. if (token) {
  719. h5Url += `&token=${token}`;
  720. } else {
  721. // 如果没有 token,使用游客模式
  722. h5Url += `&guestMode=true`;
  723. }
  724. // 添加产品ID(不要在这里编码,避免双重编码)
  725. h5Url += `&productId=${productId}`;
  726. // 如果有合作伙伴ID,也添加到URL中
  727. if (partnerId) {
  728. h5Url += `&partnerId=${partnerId}`;
  729. }
  730. console.log('🌐 H5 URL:', h5Url);
  731. // 编码 URL(统一在这里编码一次)
  732. const encodedUrl = encodeURIComponent(h5Url);
  733. // 构建 web-view 页面路径
  734. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
  735. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  736. console.log('===========================================');
  737. wx.redirectTo({
  738. url: webViewPath,
  739. success: () => {
  740. console.log('✅ 跳转到产品详情页成功');
  741. },
  742. fail: (err) => {
  743. console.error('❌ 跳转失败:', err);
  744. // 如果 redirectTo 失败,尝试 reLaunch
  745. wx.reLaunch({
  746. url: webViewPath,
  747. fail: (err2) => {
  748. console.error('❌ reLaunch 也失败:', err2);
  749. }
  750. });
  751. }
  752. });
  753. } catch (error) {
  754. console.error('❌ 跳转到产品详情页失败:', error);
  755. }
  756. },
  757. /**
  758. * 跳转到案例详情的 H5 页面
  759. * @param {string} storeId - 店铺 ID
  760. * @param {string} caseId - 案例 ID
  761. * @param {string} partnerId - 可选的合作伙伴 ID
  762. */
  763. async redirectToCaseDetail(storeId, caseId, partnerId = null) {
  764. try {
  765. console.log('===========================================');
  766. console.log('======= 跳转到案例详情页 =======');
  767. console.log('店铺 ID:', storeId);
  768. console.log('案例 ID:', caseId);
  769. if (partnerId) console.log('合作伙伴 ID:', partnerId);
  770. console.log('===========================================');
  771. const currentUser = Parse.User.current();
  772. const token = currentUser ? currentUser.getSessionToken() : null;
  773. // 构建案例详情的 H5 URL(不要在这里编码,后面统一编码)
  774. let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/cases?storeId=${storeId}`;
  775. // 如果有 token,添加到 URL
  776. if (token) {
  777. h5Url += `&token=${token}`;
  778. } else {
  779. // 如果没有 token,使用游客模式
  780. h5Url += `&guestMode=true`;
  781. }
  782. // 添加案例ID(不要在这里编码,避免双重编码)
  783. h5Url += `&caseId=${caseId}`;
  784. // 如果有合作伙伴ID,也添加到URL中
  785. if (partnerId) {
  786. h5Url += `&partnerId=${partnerId}`;
  787. }
  788. console.log('🌐 H5 URL:', h5Url);
  789. // 编码 URL(统一在这里编码一次)
  790. const encodedUrl = encodeURIComponent(h5Url);
  791. // 构建 web-view 页面路径
  792. let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
  793. console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
  794. console.log('===========================================');
  795. wx.redirectTo({
  796. url: webViewPath,
  797. success: () => {
  798. console.log('✅ 跳转到案例详情页成功');
  799. },
  800. fail: (err) => {
  801. console.error('❌ 跳转失败:', err);
  802. // 如果 redirectTo 失败,尝试 reLaunch
  803. wx.reLaunch({
  804. url: webViewPath,
  805. fail: (err2) => {
  806. console.error('❌ reLaunch 也失败:', err2);
  807. }
  808. });
  809. }
  810. });
  811. } catch (error) {
  812. console.error('❌ 跳转到案例详情页失败:', error);
  813. }
  814. },
  815. /**
  816. * 记录扫码统计信息
  817. * @param {Object} params - 扫码参数对象
  818. * @param {string} params.storeId - 店铺 ID
  819. * @param {string} params.sourceType - 来源类型 (employee/owner/partner/promoter/store)
  820. * @param {string} params.sourceId - 来源 ID
  821. * @param {string} params.ownerId - 老板 ID
  822. * @param {string} params.employeeId - 员工 ID
  823. * @param {string} params.partnerId - 合作伙伴 ID
  824. * @param {string} params.userId - 推广员 ID
  825. * @param {string} params.productId - 产品 ID
  826. * @param {string} params.scanCount - 扫码次数
  827. */
  828. async recordScanStatistics(params) {
  829. try {
  830. const {
  831. storeId,
  832. sourceType,
  833. sourceId,
  834. ownerId,
  835. employeeId,
  836. partnerId,
  837. userId,
  838. productId,
  839. scanCount
  840. } = params;
  841. // 检查用户是否已登录
  842. const currentUser = Parse.User.current();
  843. if (!currentUser) {
  844. console.log('⚠️ 用户未登录,不记录扫码统计');
  845. return;
  846. }
  847. // 如果没有来源信息,不记录统计
  848. if (!sourceId && !ownerId && !employeeId && !partnerId && !userId) {
  849. console.log('ℹ️ 无来源信息,跳过统计记录');
  850. return;
  851. }
  852. console.log('✅ 用户已登录,记录扫码统计');
  853. // 创建扫码记录
  854. const ScanRecord = Parse.Object.extend('ScanRecord');
  855. const record = new ScanRecord();
  856. record.set('company', {
  857. __type: 'Pointer',
  858. className: 'Company',
  859. objectId: getApp().globalData.company
  860. });
  861. record.set('storeId', storeId);
  862. record.set('sourceType', sourceType || 'unknown');
  863. record.set('scanCount', parseInt(scanCount) || 0);
  864. record.set('scanTime', new Date());
  865. // 根据来源类型设置对应的ID
  866. if (ownerId) {
  867. record.set('ownerId', ownerId);
  868. }
  869. if (employeeId) {
  870. record.set('employeeId', employeeId);
  871. }
  872. if (partnerId) {
  873. record.set('partnerId', partnerId);
  874. }
  875. if (userId) {
  876. record.set('userId', userId);
  877. }
  878. if (productId) {
  879. record.set('productId', productId);
  880. }
  881. // 记录扫码用户
  882. record.set('user', {
  883. __type: 'Pointer',
  884. className: '_User',
  885. objectId: currentUser.id
  886. });
  887. await record.save();
  888. console.log('✅ 扫码记录已保存');
  889. // 如果存在异业合作伙伴ID,处理异业绑定和扫码次数
  890. if (partnerId) {
  891. try {
  892. console.log('===========================================');
  893. console.log('======= 处理异业扫码逻辑 =======');
  894. console.log('用户ID:', currentUser.id);
  895. console.log('异业ID:', partnerId);
  896. console.log('门店ID:', storeId);
  897. // 检查用户是否已经绑定了异业合作伙伴
  898. const userBoundPartner = currentUser.get('Partner');
  899. const userBoundPartnerId = userBoundPartner ? userBoundPartner.id : null;
  900. console.log('用户已绑定的异业ID:', userBoundPartnerId || '无');
  901. // 规则1:如果用户已绑定其他异业,不处理当前异业的扫码
  902. if (userBoundPartnerId && userBoundPartnerId !== partnerId) {
  903. console.log('⚠️ 用户已绑定其他异业,不处理当前异业的扫码');
  904. console.log(' 已绑定异业:', userBoundPartnerId);
  905. console.log(' 当前扫码异业:', partnerId);
  906. console.log('===========================================');
  907. return;
  908. }
  909. // 规则2:检查该用户在该门店是否已经扫过该异业的码
  910. const ScanRecord = Parse.Object.extend('ScanRecord');
  911. const scanQuery = new Parse.Query(ScanRecord);
  912. scanQuery.equalTo('user', {
  913. __type: 'Pointer',
  914. className: '_User',
  915. objectId: currentUser.id
  916. });
  917. scanQuery.equalTo('partnerId', partnerId);
  918. scanQuery.equalTo('storeId', storeId);
  919. const existingScan = await scanQuery.first();
  920. if (existingScan) {
  921. console.log('⚠️ 该用户在该门店已扫过该异业的码,不重复计数');
  922. console.log(' 首次扫码时间:', existingScan.get('scanTime'));
  923. console.log('===========================================');
  924. return;
  925. }
  926. console.log('✅ 该用户在该门店首次扫该异业码');
  927. // 规则3:如果用户还没有绑定异业,绑定当前异业
  928. if (!userBoundPartnerId) {
  929. console.log('🔗 用户首次扫异业码,绑定异业合作伙伴:', partnerId);
  930. currentUser.set('Partner', {
  931. __type: 'Pointer',
  932. className: 'Partner',
  933. objectId: partnerId
  934. });
  935. await currentUser.save();
  936. console.log('✅ 异业绑定成功');
  937. }
  938. // 规则4:为该异业在该门店增加扫码次数
  939. const Partner = Parse.Object.extend('Partner');
  940. const partnerQuery = new Parse.Query(Partner);
  941. const partnerObj = await partnerQuery.get(partnerId);
  942. if (partnerObj) {
  943. // 获取或初始化门店扫码次数映射
  944. let storeScans = partnerObj.get('storeScans') || {};
  945. // 为该门店的扫码次数 +1
  946. storeScans[storeId] = (storeScans[storeId] || 0) + 1;
  947. partnerObj.set('storeScans', storeScans);
  948. // 同时更新总扫码次数
  949. partnerObj.increment('scanCount', 1);
  950. await partnerObj.save();
  951. console.log('✅ 异业扫码次数已更新');
  952. console.log(' 门店ID:', storeId);
  953. console.log(' 该门店扫码次数:', storeScans[storeId]);
  954. console.log(' 总扫码次数:', partnerObj.get('scanCount'));
  955. }
  956. console.log('===========================================');
  957. } catch (e) {
  958. console.error('❌ 处理异业合作伙伴绑定失败:', e);
  959. console.log('===========================================');
  960. }
  961. }
  962. } catch (error) {
  963. console.warn('⚠️ 保存扫码记录失败:', error);
  964. // 不影响主流程
  965. }
  966. }
  967. });