Files
kenyanghui 171003556d aiinvite2.1: 拆约(原邀悦圈)小程序 + Express/SQLite 后端
- wechat-miniprogram: 原生小程序,品牌化拆约+玄龙logo,API 指向 https://xhermes.aibay.asia
- yaoyue-sever: Express 单文件 server.js + better-sqlite3,GLM glm-5.3-flash(thinking disabled)
- 排除 node_modules/.env/*.db
2026-11-11 23:25:28 +08:00

373 lines
8.8 KiB
JavaScript

// utils/helpers.js - 工具函数
const { config } = require('../config');
const app = getApp();
/**
* 将日期字符串转换为 iOS 兼容格式
* iOS 不支持 "yyyy-MM-dd HH:mm:ss" 格式,需要转换为 "yyyy-MM-ddTHH:mm:ss"
* @param {string} dateStr - 日期字符串
* @returns {string} iOS 兼容的日期字符串
*/
const toISODateString = (dateStr) => {
if (!dateStr) return dateStr;
// 如果包含空格但不包含 T,则替换为 T
if (dateStr.includes(' ') && !dateStr.includes('T')) {
return dateStr.replace(' ', 'T');
}
return dateStr;
};
/**
* 获取完整的图片 URL
* @param {string} url - 图片路径
* @returns {string} 完整的图片 URL
*/
const getFullImageUrl = (url, noCache = false) => {
if (!url) return '';
// 如果已经是完整 URL(http 或 https 开头),直接返回
if (url.startsWith('http://') || url.startsWith('https://')) {
if (noCache) {
const sep = url.includes('?') ? '&' : '?';
return url + sep + '_t=' + Date.now();
}
return url;
}
// 如果是相对路径,拼接 API 基础 URL
const apiBaseUrl = app.globalData.apiBaseUrl || config.apiBaseUrl;
// 确保路径以 / 开头
const path = url.startsWith('/') ? url : `/${url}`;
const fullUrl = `${apiBaseUrl}${path}`;
if (noCache) return fullUrl + '?_t=' + Date.now();
return fullUrl;
};
/**
* 格式化日期时间
* @param {string} dateStr - 日期字符串
* @returns {string} 格式化后的日期时间
*/
const formatDateTime = (dateStr) => {
const date = new Date(toISODateString(dateStr));
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
};
/**
* 格式化日期
* @param {string} dateStr - 日期字符串
* @returns {string} 格式化后的日期
*/
const formatDate = (dateStr) => {
const date = new Date(toISODateString(dateStr));
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
/**
* 格式化时间
* @param {string} dateStr - 日期字符串
* @returns {string} 格式化后的时间
*/
const formatTime = (dateStr) => {
const date = new Date(toISODateString(dateStr));
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${hours}:${minutes}`;
};
/**
* 计算活动状态
* @param {string} startTime - 开始时间
* @param {number} duration - 持续时间(小时)
* @returns {string} 活动状态: upcoming/ongoing/expired
*/
const getActivityStatus = (startTime, duration) => {
const start = new Date(toISODateString(startTime)).getTime();
const end = start + duration * 60 * 60 * 1000;
const now = Date.now();
if (now < start) {
return 'upcoming';
} else if (now >= start && now <= end) {
return 'ongoing';
} else {
return 'expired';
}
};
/**
* 活动是否过期
* @param {string} startTime - 开始时间
* @param {number} duration - 持续时间(小时)
* @returns {boolean}
*/
const isActivityExpired = (startTime, duration) => {
const start = new Date(toISODateString(startTime)).getTime();
const end = start + duration * 60 * 60 * 1000;
return Date.now() > end;
};
/**
* 活动是否可以签到
* @param {string} startTime - 开始时间
* @param {number} duration - 持续时间(小时)
* @returns {boolean}
*/
const canCheckIn = (startTime, duration) => {
const start = new Date(toISODateString(startTime)).getTime();
const end = start + duration * 60 * 60 * 1000;
const now = Date.now();
// 活动开始前30分钟到活动结束都可以签到
const checkInStart = start - 30 * 60 * 1000;
return now >= checkInStart && now <= end;
};
/**
* 格式化持续时间
* @param {number} hours - 小时数
* @returns {string} 格式化后的持续时间
*/
const formatDuration = (hours) => {
if (hours < 1) {
return `${Math.round(hours * 60)}分钟`;
} else if (hours === Math.floor(hours)) {
return `${hours}小时`;
} else {
return `${Math.floor(hours)}小时${Math.round((hours % 1) * 60)}分钟`;
}
};
/**
* 截断文本
* @param {string} text - 文本
* @param {number} maxLength - 最大长度
* @returns {string} 截断后的文本
*/
const truncateText = (text, maxLength) => {
if (text.length <= maxLength) return text;
return text.slice(0, maxLength) + '...';
};
/**
* 计算资料完善度
* @param {object} profile - 用户资料
* @returns {number} 完善度百分比
*/
const calculateProfileCompletion = (profile) => {
const fields = [
{ key: 'nickname', weight: 15 },
{ key: 'avatarUrl', weight: 10 },
{ key: 'phone', weight: 15 },
{ key: 'companies', weight: 20, check: (v) => v && v.length > 0 },
{ key: 'position', weight: 10 },
{ key: 'industry', weight: 10 },
{ key: 'hometown', weight: 5 },
{ key: 'email', weight: 10 },
{ key: 'expertise', weight: 5 },
];
let totalPercent = 0;
fields.forEach((field) => {
const value = profile[field.key];
const checker = field.check || ((v) => Boolean(v));
if (checker(value)) {
totalPercent += field.weight;
}
});
return totalPercent;
};
/**
* 微信登录获取 code
* @returns {Promise<string>} code
*/
const getWechatCode = () => {
return new Promise((resolve, reject) => {
wx.login({
success: (res) => {
if (res.code) {
resolve(res.code);
} else {
reject(new Error('获取登录凭证失败'));
}
},
fail: (err) => {
reject(err);
},
});
});
};
/**
* 选择图片
* @param {number} count - 选择图片数量
* @returns {Promise<string[]>} 图片路径数组
*/
const chooseImages = (count = 1) => {
return new Promise((resolve, reject) => {
wx.chooseMedia({
count,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFiles = res.tempFiles.map((item) => item.tempFilePath);
resolve(tempFiles);
},
fail: (err) => {
reject(err);
},
});
});
};
/**
* 预览图片
* @param {string} url - 图片 URL
* @param {string[]} urls - 图片 URL 数组
*/
const previewImage = (url, urls) => {
wx.previewImage({
current: url,
urls: urls || [url],
});
};
/**
* 拨打电话
* @param {string} phoneNumber - 电话号码
*/
const makePhoneCall = (phoneNumber) => {
wx.makePhoneCall({
phoneNumber,
});
};
/**
* 复制文本到剪贴板
* @param {string} text - 文本
*/
const copyToClipboard = (text) => {
wx.setClipboardData({
data: text,
success: () => {
wx.showToast({
title: '已复制',
icon: 'success',
});
},
});
};
/**
* 显示Toast
* @param {string} title - 提示内容
* @param {string} icon - 图标类型
*/
const showToast = (title, icon = 'none') => {
wx.showToast({
title,
icon,
});
};
/**
* 显示确认对话框
* @param {string} title - 标题
* @param {string} content - 内容
* @returns {Promise<boolean>} 用户确认返回 true
*/
const showConfirm = (title, content) => {
return new Promise((resolve) => {
wx.showModal({
title,
content,
success: (res) => {
resolve(res.confirm);
},
});
});
};
/**
* 跳转到页面
* @param {string} url - 页面路径
* @param {object} params - 参数
*/
const navigateTo = (url, params) => {
if (params) {
const query = Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
url = `${url}?${query}`;
}
wx.navigateTo({ url });
};
/**
* 替换当前页面
* @param {string} url - 页面路径
* @param {object} params - 参数
*/
const redirectTo = (url, params) => {
if (params) {
const query = Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&');
url = `${url}?${query}`;
}
wx.redirectTo({ url });
};
/**
* 切换 TabBar 页面
* @param {string} url - 页面路径
*/
const switchTab = (url) => {
wx.switchTab({ url });
};
/**
* 返回上一页
* @param {number} delta - 返回的页面数
*/
const navigateBack = (delta = 1) => {
wx.navigateBack({ delta });
};
module.exports = {
getFullImageUrl,
formatDateTime,
formatDate,
formatTime,
getActivityStatus,
isActivityExpired,
canCheckIn,
formatDuration,
truncateText,
calculateProfileCompletion,
getWechatCode,
chooseImages,
previewImage,
makePhoneCall,
copyToClipboard,
showToast,
showConfirm,
navigateTo,
redirectTo,
switchTab,
navigateBack,
};