362 lines
9.6 KiB
Go
362 lines
9.6 KiB
Go
package service
|
||
|
||
import (
|
||
"bytes"
|
||
"encoding/csv"
|
||
"fmt"
|
||
"io"
|
||
"strings"
|
||
|
||
"household-book/model"
|
||
|
||
"golang.org/x/text/encoding/simplifiedchinese"
|
||
"golang.org/x/text/transform"
|
||
)
|
||
|
||
// parseAlipayCSV 解析支付宝导出的"交易记录明细"CSV(GBK 编码)。
|
||
//
|
||
// 文件结构:
|
||
//
|
||
// 行 1:标题
|
||
// 行 2:账号
|
||
// 行 3:起止日期
|
||
// 行 4:分隔行
|
||
// 行 5:表头(包含"金额(元)"、"收/支"、"交易状态"等列)
|
||
// 行 6+:数据行;尾部还可能有一段统计/分隔行
|
||
func parseAlipayCSV(req model.ImportTransactionsRequest) ([]parsedImportTransaction, error) {
|
||
rows, err := readChineseCSV(req.Content, true)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("alipay csv: %w", err)
|
||
}
|
||
header, headerRow, ok := findCSVHeader(rows, []string{"收/支", "金额"})
|
||
if !ok {
|
||
return nil, fmt.Errorf("alipay csv: header row not found")
|
||
}
|
||
idxCreate := headerColumn(header, "交易创建时间")
|
||
idxPay := headerColumn(header, "付款时间")
|
||
idxCounterparty := headerColumn(header, "交易对方")
|
||
idxProduct := headerColumn(header, "商品名称")
|
||
idxAmount := headerColumn(header, "金额")
|
||
idxFlow := headerColumn(header, "收/支")
|
||
idxStatus := headerColumn(header, "交易状态")
|
||
idxTradeNo := headerColumn(header, "交易号")
|
||
|
||
if idxAmount < 0 || idxFlow < 0 {
|
||
return nil, fmt.Errorf("alipay csv: missing required columns")
|
||
}
|
||
|
||
items := make([]parsedImportTransaction, 0, len(rows)-headerRow-1)
|
||
for i := headerRow + 1; i < len(rows); i++ {
|
||
fields := rows[i]
|
||
if len(fields) <= idxAmount || len(fields) <= idxFlow {
|
||
continue
|
||
}
|
||
|
||
flow := strings.TrimSpace(getField(fields, idxFlow))
|
||
typ, ok := alipayFlowToType(flow)
|
||
if !ok {
|
||
continue
|
||
}
|
||
|
||
status := strings.TrimSpace(getField(fields, idxStatus))
|
||
if status != "" && !alipayAcceptStatus(status) {
|
||
continue
|
||
}
|
||
|
||
amount, err := yuanToCents(strings.TrimSpace(getField(fields, idxAmount)))
|
||
if err != nil || amount <= 0 {
|
||
continue
|
||
}
|
||
|
||
date := pickAlipayDate(getField(fields, idxPay), getField(fields, idxCreate))
|
||
if date == "" {
|
||
continue
|
||
}
|
||
|
||
counterparty := strings.TrimSpace(getField(fields, idxCounterparty))
|
||
product := strings.TrimSpace(getField(fields, idxProduct))
|
||
desc := composeDescription(counterparty, product)
|
||
if desc == "" {
|
||
desc = "支付宝交易"
|
||
}
|
||
|
||
identity := strings.TrimSpace(getField(fields, idxTradeNo))
|
||
if identity == "" {
|
||
identity = strings.Join([]string{date, fmt.Sprintf("%d", amount), desc, flow}, "|")
|
||
}
|
||
items = append(items, parsedImportTransaction{
|
||
Type: typ,
|
||
Amount: amount,
|
||
Date: date,
|
||
Description: desc,
|
||
Counterparty: counterparty,
|
||
SourceKey: sourceKey(req, identity),
|
||
})
|
||
}
|
||
return items, nil
|
||
}
|
||
|
||
// parseWechatCSV 解析微信支付导出的账单 CSV(UTF-8 with BOM)。
|
||
//
|
||
// 文件结构:
|
||
//
|
||
// 前 16 行是标题/统计/说明
|
||
// 含 "----------------------微信支付账单明细列表--------------------" 分隔
|
||
// 紧接的下一行是表头(交易时间, 交易类型, 交易对方, 商品, 收/支, 金额(元), 支付方式, 当前状态, 交易单号, 商户单号, 备注)
|
||
// 数据行从表头下一行开始
|
||
func parseWechatCSV(req model.ImportTransactionsRequest) ([]parsedImportTransaction, error) {
|
||
rows, err := readChineseCSV(req.Content, false)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("wechat csv: %w", err)
|
||
}
|
||
header, headerRow, ok := findCSVHeader(rows, []string{"收/支", "金额"})
|
||
if !ok {
|
||
return nil, fmt.Errorf("wechat csv: header row not found")
|
||
}
|
||
idxTime := headerColumn(header, "交易时间")
|
||
idxKind := headerColumn(header, "交易类型")
|
||
idxCounterparty := headerColumn(header, "交易对方")
|
||
idxProduct := headerColumn(header, "商品")
|
||
idxFlow := headerColumn(header, "收/支")
|
||
idxAmount := headerColumn(header, "金额")
|
||
idxStatus := headerColumn(header, "当前状态")
|
||
idxTradeNo := headerColumn(header, "交易单号")
|
||
|
||
if idxTime < 0 || idxAmount < 0 || idxFlow < 0 {
|
||
return nil, fmt.Errorf("wechat csv: missing required columns")
|
||
}
|
||
|
||
items := make([]parsedImportTransaction, 0, len(rows)-headerRow-1)
|
||
for i := headerRow + 1; i < len(rows); i++ {
|
||
fields := rows[i]
|
||
if len(fields) <= idxAmount || len(fields) <= idxFlow {
|
||
continue
|
||
}
|
||
|
||
flow := strings.TrimSpace(getField(fields, idxFlow))
|
||
typ, ok := wechatFlowToType(flow)
|
||
if !ok {
|
||
continue
|
||
}
|
||
|
||
status := strings.TrimSpace(getField(fields, idxStatus))
|
||
if status != "" && !wechatAcceptStatus(status) {
|
||
continue
|
||
}
|
||
|
||
rawAmount := strings.TrimSpace(getField(fields, idxAmount))
|
||
rawAmount = strings.TrimPrefix(rawAmount, "¥")
|
||
rawAmount = strings.TrimPrefix(rawAmount, "¥")
|
||
amount, err := yuanToCents(rawAmount)
|
||
if err != nil || amount <= 0 {
|
||
continue
|
||
}
|
||
|
||
date := wechatDate(getField(fields, idxTime))
|
||
if date == "" {
|
||
continue
|
||
}
|
||
|
||
counterparty := strings.TrimSpace(getField(fields, idxCounterparty))
|
||
product := wechatProduct(getField(fields, idxProduct))
|
||
kind := strings.TrimSpace(getField(fields, idxKind))
|
||
desc := composeDescription(counterparty, product)
|
||
if desc == "" {
|
||
desc = strings.TrimSpace(kind)
|
||
if desc == "" {
|
||
desc = "微信交易"
|
||
}
|
||
}
|
||
|
||
identity := strings.TrimSpace(getField(fields, idxTradeNo))
|
||
if identity == "" {
|
||
identity = strings.Join([]string{date, fmt.Sprintf("%d", amount), desc, flow}, "|")
|
||
}
|
||
items = append(items, parsedImportTransaction{
|
||
Type: typ,
|
||
Amount: amount,
|
||
Date: date,
|
||
Description: desc,
|
||
Counterparty: counterparty,
|
||
SourceKey: sourceKey(req, identity),
|
||
})
|
||
}
|
||
return items, nil
|
||
}
|
||
|
||
// readChineseCSV 读取 CSV 字节流。alipay=true 时按 GBK 解码;否则按 UTF-8(去除可能的 BOM)。
|
||
//
|
||
// 返回所有行;空行被保留以便上下文判断。
|
||
func readChineseCSV(content []byte, alipay bool) ([][]string, error) {
|
||
var reader io.Reader = bytes.NewReader(content)
|
||
if alipay {
|
||
reader = transform.NewReader(reader, simplifiedchinese.GBK.NewDecoder())
|
||
} else {
|
||
// 移除 UTF-8 BOM
|
||
if bytes.HasPrefix(content, []byte{0xEF, 0xBB, 0xBF}) {
|
||
reader = bytes.NewReader(content[3:])
|
||
}
|
||
}
|
||
c := csv.NewReader(reader)
|
||
c.FieldsPerRecord = -1
|
||
c.LazyQuotes = true
|
||
c.TrimLeadingSpace = false
|
||
rows, err := c.ReadAll()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return rows, nil
|
||
}
|
||
|
||
// findCSVHeader 在前 30 行中找包含全部 needles 子串的表头行。
|
||
func findCSVHeader(rows [][]string, needles []string) ([]string, int, bool) {
|
||
limit := len(rows)
|
||
if limit > 30 {
|
||
limit = 30
|
||
}
|
||
for i := 0; i < limit; i++ {
|
||
row := rows[i]
|
||
joined := strings.Join(row, "|")
|
||
matched := true
|
||
for _, n := range needles {
|
||
if !strings.Contains(joined, n) {
|
||
matched = false
|
||
break
|
||
}
|
||
}
|
||
if matched {
|
||
return row, i, true
|
||
}
|
||
}
|
||
return nil, 0, false
|
||
}
|
||
|
||
func headerColumn(header []string, contains string) int {
|
||
for i, name := range header {
|
||
if strings.Contains(name, contains) {
|
||
return i
|
||
}
|
||
}
|
||
return -1
|
||
}
|
||
|
||
func getField(fields []string, idx int) string {
|
||
if idx < 0 || idx >= len(fields) {
|
||
return ""
|
||
}
|
||
return fields[idx]
|
||
}
|
||
|
||
func alipayFlowToType(flow string) (string, bool) {
|
||
switch flow {
|
||
case "支出":
|
||
return "expense", true
|
||
case "收入":
|
||
return "income", true
|
||
default:
|
||
// 不计收支、空字符串等
|
||
return "", false
|
||
}
|
||
}
|
||
|
||
// alipayAcceptStatus 过滤掉退款成功、交易关闭等无效或重复状态。
|
||
func alipayAcceptStatus(status string) bool {
|
||
switch status {
|
||
case "交易成功", "支付成功", "等待确认收货", "代付成功":
|
||
return true
|
||
}
|
||
if strings.Contains(status, "成功") && !strings.Contains(status, "退款") {
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
func wechatFlowToType(flow string) (string, bool) {
|
||
switch flow {
|
||
case "支出":
|
||
return "expense", true
|
||
case "收入":
|
||
return "income", true
|
||
default:
|
||
return "", false
|
||
}
|
||
}
|
||
|
||
// wechatAcceptStatus 过滤掉已退款、转账失败等。
|
||
func wechatAcceptStatus(status string) bool {
|
||
if strings.Contains(status, "已退款") || strings.Contains(status, "失败") {
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
|
||
// pickAlipayDate 优先取付款时间,其次创建时间;返回 YYYY-MM-DD。
|
||
func pickAlipayDate(payTime, createTime string) string {
|
||
for _, raw := range []string{payTime, createTime} {
|
||
raw = strings.TrimSpace(raw)
|
||
if raw == "" {
|
||
continue
|
||
}
|
||
if d := normalizeDateOnly(raw); d != "" {
|
||
return d
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
|
||
func wechatDate(raw string) string {
|
||
return normalizeDateOnly(strings.TrimSpace(raw))
|
||
}
|
||
|
||
// normalizeDateOnly 接收 "2025/5/31 20:51" 或 "2024-12-26 11:51:58",返回 YYYY-MM-DD。
|
||
func normalizeDateOnly(raw string) string {
|
||
if raw == "" {
|
||
return ""
|
||
}
|
||
if i := strings.IndexAny(raw, " T"); i > 0 {
|
||
raw = raw[:i]
|
||
}
|
||
parts := strings.FieldsFunc(raw, func(r rune) bool { return r == '-' || r == '/' })
|
||
if len(parts) != 3 {
|
||
return ""
|
||
}
|
||
year := parts[0]
|
||
if len(year) != 4 {
|
||
return ""
|
||
}
|
||
return fmt.Sprintf("%s-%s-%s", year, padTwo(parts[1]), padTwo(parts[2]))
|
||
}
|
||
|
||
func padTwo(v string) string {
|
||
if len(v) >= 2 {
|
||
return v
|
||
}
|
||
return "0" + v
|
||
}
|
||
|
||
// composeDescription 优先用商品名,其次用对手方;两者拼接以兼容某些行只有一个有内容的情况。
|
||
func composeDescription(counterparty, product string) string {
|
||
counterparty = strings.TrimSpace(counterparty)
|
||
product = strings.TrimSpace(product)
|
||
if product == "" || product == "/" {
|
||
return counterparty
|
||
}
|
||
if counterparty == "" || counterparty == "/" {
|
||
return product
|
||
}
|
||
if strings.Contains(product, counterparty) {
|
||
return product
|
||
}
|
||
return counterparty + " " + product
|
||
}
|
||
|
||
// wechatProduct 微信账单的"商品"列经常用 "/" 表示空,且会带前后引号。
|
||
func wechatProduct(raw string) string {
|
||
raw = strings.TrimSpace(raw)
|
||
raw = strings.Trim(raw, "\"")
|
||
if raw == "/" {
|
||
return ""
|
||
}
|
||
return raw
|
||
}
|