Przeglądaj źródła

feat(分享): 修复海报落地丢码,新增沙龙海报/小程序码与我的海报入口

liaoxg 1 miesiąc temu
rodzic
commit
35407a489e

+ 110 - 0
train-backend/src/main/java/com/train/controller/ShareController.java

@@ -0,0 +1,110 @@
+package com.train.controller;
+
+import com.train.common.Result;
+import com.train.service.WechatService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * 分享物料:生成带参小程序码(沙龙/课程海报用)。
+ * 对齐 cfc(E:\cfc)ShareController#qrcode 的语义:{page, scene} → 小程序码图片。
+ * scene 里携带业务 id 与邀请码(如 id=12&ref=ABC123),落地页 onLoad 解析 scene 后建立推荐关系。
+ */
+@Slf4j
+@Tag(name = "分享")
+@RestController
+@RequestMapping("/api/share")
+public class ShareController {
+
+    /** 微信 getwxacodeunlimit 的 scene 最长 32 个可见字符 */
+    private static final int SCENE_MAX_LEN = 32;
+
+    @Resource
+    private WechatService wechatService;
+
+    @Value("${upload.base-dir}")
+    private String baseDir;
+
+    /**
+     * 生成分享小程序码。
+     * @param body { page: "pages/salon/list", scene: "id=12&ref=ABC123" }
+     * @return { qrCodeUrl, scene };test-mode 或微信接口失败时 qrCodeUrl 为空串,前端降级为本地占位海报
+     */
+    @Operation(summary = "生成分享小程序码")
+    @PostMapping("/qrcode")
+    public Result<Map<String, Object>> qrcode(@RequestBody Map<String, String> body) {
+        String page = body != null ? body.get("page") : null;
+        String scene = body != null ? body.get("scene") : null;
+        if (!StringUtils.hasText(page)) {
+            page = "pages/salon/list";
+        }
+        page = page.trim();
+        while (page.startsWith("/")) {
+            page = page.substring(1);
+        }
+        if (!page.startsWith("pages/")) {
+            return Result.error("page 参数非法");
+        }
+        if (!StringUtils.hasText(scene)) {
+            return Result.error("scene 参数不能为空");
+        }
+        scene = fitScene(scene.trim());
+
+        Map<String, Object> row = new HashMap<>();
+        row.put("qrCodeUrl", "");
+        row.put("scene", scene);
+
+        byte[] bytes = wechatService.generateWxacodeBytes(scene, page);
+        if (bytes == null || bytes.length == 0) {
+            // test-mode 或微信接口失败:不阻塞分享,前端用本地海报降级
+            return Result.success(row);
+        }
+
+        File dir = new File(baseDir);
+        if (!dir.exists() && !dir.mkdirs()) {
+            log.error("小程序码目录创建失败: {}", baseDir);
+            return Result.success(row);
+        }
+        String filename = "share_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16) + ".png";
+        try (FileOutputStream fos = new FileOutputStream(new File(dir, filename))) {
+            fos.write(bytes);
+        } catch (Exception e) {
+            log.error("小程序码写入失败", e);
+            return Result.success(row);
+        }
+        row.put("qrCodeUrl", "/uploads/" + filename);
+        return Result.success(row);
+    }
+
+    /**
+     * scene 超长时优先保留邀请码(ref=xxx),避免截断把推荐关系切断。
+     * 形如 id=12&ref=ABC123:超长则退化为 ref=ABC123(落地页仍能捕获邀请码)。
+     */
+    private String fitScene(String scene) {
+        if (scene.length() <= SCENE_MAX_LEN) {
+            return scene;
+        }
+        int idx = scene.indexOf("&ref=");
+        if (idx >= 0) {
+            String refPart = scene.substring(idx + 1);
+            if (refPart.length() <= SCENE_MAX_LEN) {
+                return refPart;
+            }
+        }
+        return scene.substring(0, SCENE_MAX_LEN);
+    }
+}

+ 51 - 0
train-backend/src/main/java/com/train/service/WechatService.java

@@ -4,10 +4,14 @@ import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.JSONObject;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
+import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Map;
 
 
@@ -35,6 +39,12 @@ public class WechatService {
     @Value("${wechat.token-url:https://api.weixin.qq.com/cgi-bin/token}")
     @Value("${wechat.token-url:https://api.weixin.qq.com/cgi-bin/token}")
     private String tokenUrl;
     private String tokenUrl;
 
 
+    @Value("${wechat.qrcode-url:https://api.weixin.qq.com/wxa/getwxacodeunlimit}")
+    private String qrcodeUrl;
+
+    @Value("${wechat.qrcode-env-version:release}")
+    private String qrcodeEnvVersion;
+
     @Value("${wechat.test-mode}")
     @Value("${wechat.test-mode}")
     private boolean testMode;
     private boolean testMode;
 
 
@@ -130,6 +140,47 @@ public class WechatService {
         }
         }
     }
     }
 
 
+    /**
+     * 生成带参小程序码(getwxacodeunlimit),返回 PNG 字节。
+     * scene 最长 32 字符(调用方负责截断);page 为小程序页面路径(不能是 tabBar 页)。
+     * test-mode / 接口失败返回 null,由调用方降级处理。
+     */
+    public byte[] generateWxacodeBytes(String scene, String page) {
+        if (testMode) {
+            return null;
+        }
+        try {
+            String accessToken = getAccessToken();
+            JSONObject body = new JSONObject();
+            body.put("scene", scene);
+            body.put("page", page);
+            body.put("check_path", false);
+            body.put("env_version", qrcodeEnvVersion);
+            body.put("width", 430);
+            HttpHeaders headers = new HttpHeaders();
+            headers.setContentType(MediaType.APPLICATION_JSON);
+            ResponseEntity<byte[]> response = restTemplate.postForEntity(
+                    qrcodeUrl + "?access_token=" + accessToken,
+                    new HttpEntity<>(body.toJSONString(), headers),
+                    byte[].class);
+            byte[] bytes = response.getBody();
+            if (bytes == null || bytes.length == 0) {
+                log.warn("生成小程序码返回空字节 scene={} page={}", scene, page);
+                return null;
+            }
+            // 微信失败时返回 JSON(含 errcode)而非图片字节,需识别后降级
+            String text = new String(bytes, StandardCharsets.UTF_8);
+            if (text.contains("\"errcode\"") && !text.contains("\"errcode\":0")) {
+                log.error("生成小程序码失败 scene={} page={} resp={}", scene, page, text);
+                return null;
+            }
+            return bytes;
+        } catch (Exception e) {
+            log.error("生成小程序码异常 scene={} page={}", scene, page, e);
+            return null;
+        }
+    }
+
     /** 获取 access_token(带缓存;供其他服务复用,如订阅消息发送) */
     /** 获取 access_token(带缓存;供其他服务复用,如订阅消息发送) */
     public String getAccessToken() {
     public String getAccessToken() {
         if (!testMode && cachedAccessToken != null && System.currentTimeMillis() < tokenExpireAt) {
         if (!testMode && cachedAccessToken != null && System.currentTimeMillis() < tokenExpireAt) {

+ 2 - 0
train-backend/src/main/resources/application.yml

@@ -54,6 +54,8 @@ wechat:
   test-phone: "13800138000"  # 测试模式下 getPhoneNumber 的模拟手机号
   test-phone: "13800138000"  # 测试模式下 getPhoneNumber 的模拟手机号
   subscribe-url: https://api.weixin.qq.com/cgi-bin/message/subscribe/send
   subscribe-url: https://api.weixin.qq.com/cgi-bin/message/subscribe/send
   qrcode-url: https://api.weixin.qq.com/wxa/getwxacodeunlimit
   qrcode-url: https://api.weixin.qq.com/wxa/getwxacodeunlimit
+  # 小程序码指向的版本:release(正式)/ trial(体验版)/ develop(开发版)
+  qrcode-env-version: release
   # 微信支付 API v3(对齐 cfc PaymentService;test-mode=true 时全部走 mock,无需配置)
   # 微信支付 API v3(对齐 cfc PaymentService;test-mode=true 时全部走 mock,无需配置)
   mch-id: ${WECHAT_MCH_ID:}                # 微信支付商户号
   mch-id: ${WECHAT_MCH_ID:}                # 微信支付商户号
   api-v3-key: ${WECHAT_API_V3_KEY:}        # API v3 密钥(32 字节,回调 AES-GCM 解密)
   api-v3-key: ${WECHAT_API_V3_KEY:}        # API v3 密钥(32 字节,回调 AES-GCM 解密)

+ 215 - 0
train-frontend/components/share-poster/share-poster.vue

@@ -0,0 +1,215 @@
+<template>
+  <view v-if="visible" class="poster-mask" @click="close">
+    <view class="poster-panel" @click.stop>
+      <canvas canvas-id="salonPosterCanvas" id="salonPosterCanvas" class="poster-canvas"></canvas>
+      <view class="poster-tip">长按图片可保存或转发给好友</view>
+      <view class="poster-actions">
+        <button class="poster-btn poster-btn-ghost" @click="close">关闭</button>
+        <button class="poster-btn poster-btn-primary" :loading="saving" :disabled="saving" @click="save">保存海报</button>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script>
+/**
+ * 沙龙分享海报:canvas 绘制标题/时间/地点/邀请码 + 小程序码。
+ * 小程序码由后端 /api/share/qrcode 生成(scene 携带沙龙 id 与邀请码);
+ * test-mode 或生成失败时 qrUrl 为空,降级为占位框,不阻塞保存。
+ */
+var CANVAS_W = 300
+var CANVAS_H = 480
+var QR_SIZE = 140
+var QR_X = (CANVAS_W - QR_SIZE) / 2
+var QR_Y = 225
+
+export default {
+  name: 'SharePoster',
+  props: {
+    visible: { type: Boolean, default: false },
+    title: { type: String, default: '' },
+    time: { type: String, default: '' },
+    place: { type: String, default: '' },
+    inviteCode: { type: String, default: '' },
+    qrUrl: { type: String, default: '' }
+  },
+  data() {
+    return { saving: false }
+  },
+  watch: {
+    visible: function(v) {
+      if (v) this.redraw()
+    },
+    qrUrl: function() {
+      if (this.visible) this.redraw()
+    }
+  },
+  methods: {
+    redraw() {
+      var self = this
+      this.$nextTick(function() {
+        setTimeout(function() {
+          self.draw()
+        }, 150)
+      })
+    },
+    draw() {
+      var self = this
+      var ctx = uni.createCanvasContext('salonPosterCanvas', self)
+      // 背景
+      ctx.setFillStyle('#FFFFFF')
+      ctx.fillRect(0, 0, CANVAS_W, CANVAS_H)
+      // 顶部品牌区
+      var gradient = ctx.createLinearGradient(0, 0, CANVAS_W, 0)
+      gradient.addColorStop(0, '#FC7A57')
+      gradient.addColorStop(1, '#F9494F')
+      ctx.setFillStyle(gradient)
+      ctx.fillRect(0, 0, CANVAS_W, 70)
+      ctx.setTextAlign('center')
+      ctx.setFillStyle('#FFFFFF')
+      ctx.setFontSize(18)
+      ctx.fillText('爱伴·AI之旅', CANVAS_W / 2, 32)
+      ctx.setFontSize(11)
+      ctx.fillText('沙龙活动邀请', CANVAS_W / 2, 52)
+      // 标题(最多两行)
+      ctx.setTextAlign('left')
+      ctx.setFillStyle('#2A2326')
+      ctx.setFontSize(17)
+      this.drawTitle(ctx, self.title || '沙龙活动', 24, 108, CANVAS_W - 48, 24, 2)
+      // 时间 / 地点
+      ctx.setFillStyle('#5A4F4B')
+      ctx.setFontSize(12)
+      ctx.fillText('时间:' + (self.time || '待定'), 24, 168)
+      ctx.fillText('地点:' + (self.place || '待定'), 24, 190)
+      // 分割线
+      ctx.setStrokeStyle('#F1F5F9')
+      ctx.setLineWidth(1)
+      ctx.beginPath()
+      ctx.moveTo(24, 206)
+      ctx.lineTo(CANVAS_W - 24, 206)
+      ctx.stroke()
+      // 小程序码
+      this.drawQr(ctx, function() {
+        // 邀请码
+        ctx.setTextAlign('center')
+        ctx.setFillStyle('#FC7A57')
+        ctx.setFontSize(13)
+        ctx.fillText(self.inviteCode ? '邀请码:' + self.inviteCode : '扫码查看活动详情', CANVAS_W / 2, 400)
+        ctx.setFillStyle('#94877F')
+        ctx.setFontSize(11)
+        ctx.fillText('长按识别小程序码,一起来成长', CANVAS_W / 2, 428)
+        ctx.setFillStyle('#CBD5E1')
+        ctx.setFontSize(10)
+        ctx.fillText('爱伴·AI之旅训练营', CANVAS_W / 2, 456)
+        ctx.draw()
+      })
+    },
+    drawTitle(ctx, text, x, y, maxWidth, lineHeight, maxLines) {
+      var chars = String(text).split('')
+      var line = ''
+      var lineY = y
+      var lines = 0
+      for (var i = 0; i < chars.length; i++) {
+        var test = line + chars[i]
+        if (ctx.measureText(test).width > maxWidth && line) {
+          lines++
+          if (lines >= maxLines) {
+            ctx.fillText(line.substring(0, line.length - 1) + '…', x, lineY)
+            return
+          }
+          ctx.fillText(line, x, lineY)
+          line = chars[i]
+          lineY += lineHeight
+        } else {
+          line = test
+        }
+      }
+      if (line) ctx.fillText(line, x, lineY)
+    },
+    drawQr(ctx, done) {
+      var self = this
+      if (!self.qrUrl) {
+        self.drawQrPlaceholder(ctx)
+        done()
+        return
+      }
+      uni.getImageInfo({
+        src: self.qrUrl,
+        success: function(res) {
+          ctx.drawImage(res.path, QR_X, QR_Y, QR_SIZE, QR_SIZE)
+          done()
+        },
+        fail: function() {
+          self.drawQrPlaceholder(ctx)
+          done()
+        }
+      })
+    },
+    drawQrPlaceholder(ctx) {
+      ctx.setFillStyle('#F8FAFC')
+      ctx.fillRect(QR_X, QR_Y, QR_SIZE, QR_SIZE)
+      ctx.setStrokeStyle('#E2E8F0')
+      ctx.setLineWidth(1)
+      ctx.strokeRect(QR_X, QR_Y, QR_SIZE, QR_SIZE)
+      ctx.setTextAlign('center')
+      ctx.setFillStyle('#94A3B8')
+      ctx.setFontSize(12)
+      ctx.fillText('小程序码', CANVAS_W / 2, QR_Y + QR_SIZE / 2 - 4)
+      ctx.setFontSize(10)
+      ctx.fillText('生成中 / 暂不可用', CANVAS_W / 2, QR_Y + QR_SIZE / 2 + 16)
+    },
+    close() {
+      this.$emit('close')
+    },
+    save() {
+      var self = this
+      if (this.saving) return
+      this.saving = true
+      uni.canvasToTempFilePath({
+        canvasId: 'salonPosterCanvas',
+        success: function(res) {
+          uni.saveImageToPhotosAlbum({
+            filePath: res.tempFilePath,
+            success: function() {
+              self.saving = false
+              uni.showToast({ title: '海报已保存到相册', icon: 'success' })
+            },
+            fail: function(err) {
+              self.saving = false
+              var msg = (err && err.errMsg) || ''
+              if (msg.indexOf('auth') > -1 || msg.indexOf('deny') > -1) {
+                uni.showModal({
+                  title: '需要相册权限',
+                  content: '请在设置中开启「保存到相册」权限',
+                  confirmText: '去设置',
+                  success: function(r) {
+                    if (r.confirm) uni.openSetting({})
+                  }
+                })
+              } else {
+                uni.showToast({ title: '保存失败,请稍后重试', icon: 'none' })
+              }
+            }
+          })
+        },
+        fail: function() {
+          self.saving = false
+          uni.showToast({ title: '海报生成失败', icon: 'none' })
+        }
+      }, this)
+    }
+  }
+}
+</script>
+
+<style scoped>
+.poster-mask { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); display: flex; align-items: center; justify-content: center; z-index: 999; }
+.poster-panel { background: #FFF; border-radius: 20rpx; padding: 24rpx; display: flex; flex-direction: column; align-items: center; }
+.poster-canvas { width: 300px; height: 480px; border-radius: 12rpx; }
+.poster-tip { font-size: 22rpx; color: #94877F; margin: 16rpx 0 20rpx; }
+.poster-actions { display: flex; align-items: center; width: 100%; }
+.poster-btn { flex: 1; height: 76rpx; line-height: 76rpx; font-size: 28rpx; border-radius: 38rpx; border: none; padding: 0; }
+.poster-btn-ghost { background: #F1F5F9; color: #5A4F4B; margin-right: 20rpx; }
+.poster-btn-primary { background: #FC7A57; color: #FFF; }
+.poster-btn:active { opacity: 0.85; }
+</style>

+ 5 - 0
train-frontend/pages/enroll/list.vue

@@ -69,6 +69,7 @@
 import { getCourseList, getMyEnrollments, cancelPayOrder, activateEnrollment } from '@/utils/api.js'
 import { getCourseList, getMyEnrollments, cancelPayOrder, activateEnrollment } from '@/utils/api.js'
 import { fenToYuan, formatDateTime } from '@/utils/format.js'
 import { fenToYuan, formatDateTime } from '@/utils/format.js'
 import { guardPage } from '@/utils/guard.js'
 import { guardPage } from '@/utils/guard.js'
+import { captureInviteCode } from '@/utils/invite.js'
 
 
 export default {
 export default {
   data() {
   data() {
@@ -79,6 +80,10 @@ export default {
       mineLoading: false
       mineLoading: false
     }
     }
   },
   },
+  onLoad(options) {
+    // 海报/分享文案落地页:捕获 inviteCode 与扫码 scene 中的邀请码,供报名表单回填
+    captureInviteCode(options)
+  },
   onShow() {
   onShow() {
     if (!guardPage()) return
     if (!guardPage()) return
     this.loadCourses()
     this.loadCourses()

+ 5 - 0
train-frontend/pages/mine/index.vue

@@ -79,6 +79,11 @@
         <text class="menu-text">报名中心</text>
         <text class="menu-text">报名中心</text>
         <text class="menu-arrow">›</text>
         <text class="menu-arrow">›</text>
       </view>
       </view>
+      <view class="menu-item" @click="goTo('/pages/share/index')">
+        <text class="menu-icon">🎁</text>
+        <text class="menu-text">邀请有礼 · 我的海报</text>
+        <text class="menu-arrow">›</text>
+      </view>
       <view class="menu-item" @click="goTo('/pages/group-order/index')">
       <view class="menu-item" @click="goTo('/pages/group-order/index')">
         <text class="menu-icon">👨‍👩‍👧‍👦</text>
         <text class="menu-icon">👨‍👩‍👧‍👦</text>
         <text class="menu-text">团报</text>
         <text class="menu-text">团报</text>

+ 107 - 8
train-frontend/pages/salon/list.vue

@@ -12,10 +12,19 @@
       <view v-if="loading" class="empty-tip">加载中…</view>
       <view v-if="loading" class="empty-tip">加载中…</view>
       <view v-else-if="salons.length === 0" class="empty-tip">暂无活动沙龙</view>
       <view v-else-if="salons.length === 0" class="empty-tip">暂无活动沙龙</view>
       <view v-else>
       <view v-else>
-        <view class="salon-card" v-for="item in salons" :key="item.id">
+        <view
+          class="salon-card"
+          :id="'salon-' + item.id"
+          :class="{ 'salon-card-active': highlightSalonId == item.id }"
+          v-for="item in salons"
+          :key="item.id"
+        >
           <view class="salon-head">
           <view class="salon-head">
-            <text class="salon-theme">{{ mapTheme(item.theme) }}</text>
-            <text class="salon-title">{{ item.title }}</text>
+            <view class="salon-head-main">
+              <text class="salon-theme">{{ mapTheme(item.theme) }}</text>
+              <text class="salon-title">{{ item.title }}</text>
+            </view>
+            <text class="poster-link" @click="openPoster(item)">生成海报</text>
           </view>
           </view>
           
           
           <view class="salon-info">
           <view class="salon-info">
@@ -68,23 +77,42 @@
         </view>
         </view>
       </view>
       </view>
     </view>
     </view>
+
+    <share-poster
+      :visible="posterVisible"
+      :title="posterTitle"
+      :time="posterTime"
+      :place="posterPlace"
+      :invite-code="posterInviteCode"
+      :qr-url="posterQrUrl"
+      @close="closePoster"
+    />
   </view>
   </view>
 </template>
 </template>
 
 
 <script>
 <script>
-import { getSalonList, getMyMember } from '@/utils/api.js'
+import { getSalonList, getMyMember, getShareQrCode } from '@/utils/api.js'
 import { fenToYuan, formatDateTime } from '@/utils/format.js'
 import { fenToYuan, formatDateTime } from '@/utils/format.js'
 import { guardPage } from '@/utils/guard.js'
 import { guardPage } from '@/utils/guard.js'
-import { loadInviteCode, getInviteCode, buildSharePath } from '@/utils/share.js'
-import { captureInviteCode } from '@/utils/invite.js'
+import { loadInviteCode, getInviteCode, buildSharePath, resolveAssetUrl } from '@/utils/share.js'
+import { captureInviteCode, getSceneParams } from '@/utils/invite.js'
+import SharePoster from '@/components/share-poster/share-poster.vue'
 
 
 export default {
 export default {
+  components: { SharePoster },
   data() {
   data() {
     return {
     return {
       salons: [],
       salons: [],
       loading: false,
       loading: false,
       member: {},
       member: {},
       shareTarget: null,
       shareTarget: null,
+      highlightSalonId: '',
+      posterVisible: false,
+      posterTitle: '',
+      posterTime: '',
+      posterPlace: '',
+      posterInviteCode: '',
+      posterQrUrl: '',
       themeMap: {
       themeMap: {
         ai_basic: 'AI 认知基础',
         ai_basic: 'AI 认知基础',
         wealth: '家庭财富管理',
         wealth: '家庭财富管理',
@@ -101,8 +129,11 @@ export default {
     }
     }
   },
   },
   onLoad(options) {
   onLoad(options) {
-    // 邀请链入站捕获:沙龙分享暂落列表页,带 inviteCode 时先落 storage 供报名回填
+    // 邀请链入站捕获:分享链接带 inviteCode;扫码进入时参数在 options.scene
     captureInviteCode(options)
     captureInviteCode(options)
+    var scene = getSceneParams(options)
+    var salonId = (options && options.salonId) || scene.salonId || scene.id || ''
+    this.highlightSalonId = salonId ? String(salonId) : ''
   },
   },
   onShow() {
   onShow() {
     loadInviteCode()
     loadInviteCode()
@@ -150,6 +181,9 @@ export default {
       self.loading = true
       self.loading = true
       getSalonList().then(function(resp) {
       getSalonList().then(function(resp) {
         self.salons = resp.data || []
         self.salons = resp.data || []
+        self.$nextTick(function() {
+          self.scrollToHighlight()
+        })
       }).catch(function() {
       }).catch(function() {
         uni.showToast({ title: '加载沙龙失败', icon: 'none' })
         uni.showToast({ title: '加载沙龙失败', icon: 'none' })
       }).finally(function() {
       }).finally(function() {
@@ -187,6 +221,67 @@ export default {
     },
     },
     goMine() {
     goMine() {
       uni.navigateTo({ url: '/pages/salon/mine' })
       uni.navigateTo({ url: '/pages/salon/mine' })
+    },
+    /** 分享链接/扫码进入:滚动定位到被分享的沙龙并高亮 */
+    scrollToHighlight() {
+      var id = this.highlightSalonId
+      if (!id) return
+      setTimeout(function() {
+        uni.createSelectorQuery()
+          .select('#salon-' + id)
+          .boundingClientRect()
+          .selectViewport()
+          .scrollOffset()
+          .exec(function(res) {
+            var rect = res && res[0]
+            var scroll = res && res[1]
+            if (rect && scroll) {
+              uni.pageScrollTo({ scrollTop: rect.top + scroll.scrollTop - 20, duration: 300 })
+            }
+          })
+      }, 200)
+    },
+    /** 生成沙龙海报:小程序码 scene 携带沙龙 id + 邀请码(对齐 cfc 海报模式) */
+    openPoster(item) {
+      var self = this
+      if (!self.$store.getters.isLoggedIn) {
+        self.promptLogin()
+        return
+      }
+      self.posterTitle = item.title || ''
+      self.posterTime = formatDateTime(item.time)
+      self.posterPlace = item.place || ''
+      self.posterInviteCode = getInviteCode()
+      self.posterQrUrl = ''
+      self.posterVisible = true
+      loadInviteCode().then(function(code) {
+        self.posterInviteCode = code || self.posterInviteCode
+        var scene = 'id=' + item.id + (code ? '&ref=' + code : '')
+        return getShareQrCode({ page: 'pages/salon/list', scene: scene })
+      }).then(function(resp) {
+        var url = (resp && resp.data && resp.data.qrCodeUrl) || ''
+        if (url && self.posterVisible) self.posterQrUrl = resolveAssetUrl(url)
+      }).catch(function() {
+        // 生成失败:海报保留占位框,仍可保存/转发
+      })
+    },
+    closePoster() {
+      this.posterVisible = false
+      this.posterQrUrl = ''
+    },
+    promptLogin() {
+      uni.showModal({
+        title: '登录后生成海报',
+        content: '登录后可生成带您专属邀请码的沙龙海报',
+        confirmText: '去登录',
+        success: function(res) {
+          if (!res.confirm) return
+          uni.switchTab({ url: '/pages/index/index' })
+          setTimeout(function() {
+            uni.$emit('showLoginSheet', {})
+          }, 400)
+        }
+      })
     }
     }
   }
   }
 }
 }
@@ -201,7 +296,11 @@ export default {
 .card-desc { display: block; font-size: 26rpx; color: #5A4F4B; margin-bottom: 24rpx; }
 .card-desc { display: block; font-size: 26rpx; color: #5A4F4B; margin-bottom: 24rpx; }
 .empty-tip { font-size: 26rpx; color: #94877F; padding: 32rpx 0; text-align: center; }
 .empty-tip { font-size: 26rpx; color: #94877F; padding: 32rpx 0; text-align: center; }
 .salon-card { border: 2rpx solid #E2E8F0; border-radius: 12rpx; padding: 24rpx; margin-bottom: 20rpx; }
 .salon-card { border: 2rpx solid #E2E8F0; border-radius: 12rpx; padding: 24rpx; margin-bottom: 20rpx; }
-.salon-head { margin-bottom: 16rpx; }
+.salon-card-active { border-color: #FC7A57; box-shadow: 0 0 0 4rpx rgba(252, 122, 87, 0.12); }
+.salon-head { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 16rpx; }
+.salon-head-main { flex: 1; min-width: 0; }
+.poster-link { flex-shrink: 0; font-size: 24rpx; color: #FC7A57; padding: 4rpx 0 0 16rpx; }
+.poster-link:active { opacity: 0.7; }
 .salon-theme { display: block; background: #FFF0E8; color: #FC7A57; font-size: 22rpx; font-weight: 600; padding: 4rpx 12rpx; border-radius: 4rpx; width: fit-content; margin-bottom: 8rpx; }
 .salon-theme { display: block; background: #FFF0E8; color: #FC7A57; font-size: 22rpx; font-weight: 600; padding: 4rpx 12rpx; border-radius: 4rpx; width: fit-content; margin-bottom: 8rpx; }
 .salon-title { display: block; font-size: 30rpx; font-weight: 600; color: #2A2326; }
 .salon-title { display: block; font-size: 30rpx; font-weight: 600; color: #2A2326; }
 .salon-info { margin-bottom: 16rpx; }
 .salon-info { margin-bottom: 16rpx; }

+ 2 - 1
train-frontend/pages/share/index.vue

@@ -36,6 +36,7 @@
 
 
 <script>
 <script>
 import { getMyPoster } from '@/utils/api.js'
 import { getMyPoster } from '@/utils/api.js'
+import { resolveAssetUrl } from '@/utils/share.js'
 import { guardPage } from '@/utils/guard.js'
 import { guardPage } from '@/utils/guard.js'
 
 
 export default {
 export default {
@@ -61,7 +62,7 @@ export default {
       getMyPoster().then(function(resp) {
       getMyPoster().then(function(resp) {
         var data = resp.data || {}
         var data = resp.data || {}
         self.inviteCode = data.inviteCode || ''
         self.inviteCode = data.inviteCode || ''
-        self.posterUrl = data.posterUrl || ''
+        self.posterUrl = resolveAssetUrl(data.posterUrl || '')
         self.shareText = data.shareText || ''
         self.shareText = data.shareText || ''
         if (self.inviteCode) {
         if (self.inviteCode) {
           // 重新绘制带邀请码的海报
           // 重新绘制带邀请码的海报

+ 3 - 0
train-frontend/utils/api.js

@@ -279,6 +279,9 @@ export const cancelPayOrder = (data) => {
 export const getMyPoster = () => {
 export const getMyPoster = () => {
   return request('/api/invite/myposter', 'POST')
   return request('/api/invite/myposter', 'POST')
 }
 }
+export const getShareQrCode = (data) => {
+  return request('/api/share/qrcode', 'POST', data)
+}
 export const getInviteStats = () => {
 export const getInviteStats = () => {
   return request('/api/invite/stats', 'POST')
   return request('/api/invite/stats', 'POST')
 }
 }

+ 45 - 7
train-frontend/utils/invite.js

@@ -6,6 +6,12 @@
  *           回填并随报名单上送 → 报名单创建成功后 consumeInviteCode 清除。
  *           回填并随报名单上送 → 报名单创建成功后 consumeInviteCode 清除。
  * 与 share.js 相对:share.js 管出站(分享路径带码),本模块管入站(链接收到的码)。
  * 与 share.js 相对:share.js 管出站(分享路径带码),本模块管入站(链接收到的码)。
  *
  *
+ * 入站来源有两种形态:
+ * 1) 普通分享链接:/pages/xxx?inviteCode=CODE(或 ?ref=CODE)
+ * 2) 小程序码扫码:参数在 onLoad 的 options.scene(URL 编码),
+ *    形如 scene=id=12&ref=CODE 或早期海报的裸码 scene=CODE;
+ *    普通二维码扫码时可能落在 options.q(整条链接)。
+ *
  * 说明:跨页面/跨登录保留待用邀请码(未登录用户点开分享链接→登录→报名仍能建立邀请链);
  * 说明:跨页面/跨登录保留待用邀请码(未登录用户点开分享链接→登录→报名仍能建立邀请链);
  * 一次邀请链接对应「首个」报名转化,成功后即消费清除。
  * 一次邀请链接对应「首个」报名转化,成功后即消费清除。
  */
  */
@@ -15,15 +21,47 @@ function isValidCode(code) {
   return /^[A-Za-z0-9]{4,20}$/.test(code || '')
   return /^[A-Za-z0-9]{4,20}$/.test(code || '')
 }
 }
 
 
-/** 从页面 onLoad options 捕获邀请码并持久化(无效码静默忽略) */
-export function captureInviteCode(options) {
-  var raw = (options && options.inviteCode) ? String(options.inviteCode) : ''
-  var code = ''
+function safeDecode(str) {
+  var raw = String(str || '')
   try {
   try {
-    code = decodeURIComponent(raw)
+    return decodeURIComponent(raw)
   } catch (e) {
   } catch (e) {
-    code = raw
+    return raw
+  }
+}
+
+/**
+ * 解析扫码参数(options.scene / options.q),返回键值对象。
+ * 兼容:id=12&ref=CODE、inviteCode=CODE、裸码 CODE、整条链接 URL。
+ */
+export function getSceneParams(options) {
+  var opts = options || {}
+  var raw = opts.scene || opts.q || ''
+  if (!raw) return {}
+  raw = safeDecode(raw)
+  // options.q 是完整链接:只取 query 部分
+  var qIndex = raw.indexOf('?')
+  if (qIndex > -1) raw = raw.substring(qIndex + 1)
+  var params = {}
+  var pairs = raw.split('&')
+  for (var i = 0; i < pairs.length; i++) {
+    if (!pairs[i]) continue
+    var kv = pairs[i].split('=')
+    if (kv.length === 2 && kv[0]) params[kv[0]] = safeDecode(kv[1])
+  }
+  // 裸码兼容:scene 直接就是邀请码(早期海报 scene=<inviteCode>)
+  if (!params.inviteCode && !params.ref && isValidCode(raw)) {
+    params.inviteCode = raw
   }
   }
+  return params
+}
+
+/** 从页面 onLoad options 捕获邀请码并持久化(无效码静默忽略) */
+export function captureInviteCode(options) {
+  var opts = options || {}
+  var scene = getSceneParams(opts)
+  var raw = opts.inviteCode || opts.ref || scene.inviteCode || scene.ref || ''
+  var code = safeDecode(raw)
   if (!isValidCode(code)) return
   if (!isValidCode(code)) return
   if (uni.getStorageSync(PENDING_KEY) === code) return
   if (uni.getStorageSync(PENDING_KEY) === code) return
   uni.setStorageSync(PENDING_KEY, code)
   uni.setStorageSync(PENDING_KEY, code)
@@ -37,4 +75,4 @@ export function getPendingInviteCode() {
 /** 报名单成功创建后消费待用邀请码(一次邀请链接只对应一次首个报名转化) */
 /** 报名单成功创建后消费待用邀请码(一次邀请链接只对应一次首个报名转化) */
 export function consumeInviteCode() {
 export function consumeInviteCode() {
   uni.removeStorageSync(PENDING_KEY)
   uni.removeStorageSync(PENDING_KEY)
-}
+}

+ 24 - 3
train-frontend/utils/share.js

@@ -6,6 +6,7 @@
  * 未登录 / 加载失败时不带邀请码,分享仍可用。
  * 未登录 / 加载失败时不带邀请码,分享仍可用。
  */
  */
 import { getMyPoster } from '@/utils/api.js'
 import { getMyPoster } from '@/utils/api.js'
+import config from '@/config.js'
 
 
 let cached = { userId: '', code: '' }
 let cached = { userId: '', code: '' }
 
 
@@ -24,19 +25,27 @@ function readInviteCode() {
   return cached.userId === userId ? cached.code : ''
   return cached.userId === userId ? cached.code : ''
 }
 }
 
 
-/** 后台预载当前用户邀请码(页面 onLoad/onShow 调用,不阻塞 UI、不弹登录框) */
+/**
+ * 预载当前用户邀请码(页面 onLoad/onShow 调用,不阻塞 UI、不弹登录框)。
+ * 返回 Promise<string>:已有缓存/无登录用户时立即 resolve,供「生成海报」等
+ * 需要邀请码才能继续的场景 await 后使用。
+ */
 export function loadInviteCode() {
 export function loadInviteCode() {
   var userId = currentUserId()
   var userId = currentUserId()
-  if (!userId || readInviteCode()) return
-  getMyPoster().then(function(resp) {
+  if (!userId) return Promise.resolve('')
+  var existing = readInviteCode()
+  if (existing) return Promise.resolve(existing)
+  return getMyPoster().then(function(resp) {
     var data = resp.data || {}
     var data = resp.data || {}
     var code = data.inviteCode || ''
     var code = data.inviteCode || ''
     if (code) {
     if (code) {
       cached = { userId: userId, code: code }
       cached = { userId: userId, code: code }
       uni.setStorageSync('invite_' + userId, code)
       uni.setStorageSync('invite_' + userId, code)
     }
     }
+    return code
   }).catch(function() {
   }).catch(function() {
     // 静默失败:分享路径不带邀请码
     // 静默失败:分享路径不带邀请码
+    return ''
   })
   })
 }
 }
 
 
@@ -50,4 +59,16 @@ export function buildSharePath(path) {
   var code = readInviteCode()
   var code = readInviteCode()
   if (!code) return path
   if (!code) return path
   return path + (path.indexOf('?') > -1 ? '&' : '?') + 'inviteCode=' + code
   return path + (path.indexOf('?') > -1 ? '&' : '?') + 'inviteCode=' + code
+}
+
+/**
+ * 后端返回的 /uploads/xxx 资源路径转绝对地址。
+ * 小程序端 <image> / uni.getImageInfo 不能使用 / 开头的相对路径(会被当作包内本地文件),
+ * H5 端 BASE_URL 为空时保持相对路径(由 nginx 同域提供)。
+ */
+export function resolveAssetUrl(path) {
+  if (!path) return ''
+  if (path.indexOf('http://') === 0 || path.indexOf('https://') === 0) return path
+  if (path.charAt(0) === '/') return config.api(path)
+  return path
 }
 }