feat(导出): 新增分销商筛选功能及任务列表页面

- 添加分销商API接口及前端筛选组件
- 实现导出任务分页列表功能
- 优化导出任务状态展示和进度显示
- 增加EXPLAIN评分阈值检查
- 默认设置导出时间为当年范围
This commit is contained in:
zhouyonggao 2025-11-25 15:25:30 +08:00
parent 24891fa208
commit 6fa4abdcf5
8 changed files with 628 additions and 260 deletions

View File

@ -3,13 +3,14 @@ package api
import ( import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"log" "log"
"marketing-system-data-tool/server/internal/exporter"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"marketing-system-data-tool/server/internal/exporter"
) )
type ExportsAPI struct { type ExportsAPI struct {
@ -25,6 +26,10 @@ func ExportsHandler(meta, marketing *sql.DB) http.Handler {
api.create(w, r) api.create(w, r)
return return
} }
if r.Method == http.MethodGet && p == "" {
api.list(w, r)
return
}
if strings.HasPrefix(p, "/") { if strings.HasPrefix(p, "/") {
id := strings.TrimPrefix(p, "/") id := strings.TrimPrefix(p, "/")
if r.Method == http.MethodGet && !strings.HasSuffix(p, "/download") { if r.Method == http.MethodGet && !strings.HasSuffix(p, "/download") {
@ -71,7 +76,9 @@ func (a *ExportsAPI) create(w http.ResponseWriter, r *http.Request) {
fail(w, r, http.StatusBadRequest, "invalid template") fail(w, r, http.StatusBadRequest, "invalid template")
return return
} }
if p.Datasource != "" { ds = p.Datasource } if p.Datasource != "" {
ds = p.Datasource
}
var fs []string var fs []string
json.Unmarshal(fields, &fs) json.Unmarshal(fields, &fs)
wl := whitelist() wl := whitelist()
@ -89,8 +96,18 @@ func (a *ExportsAPI) create(w http.ResponseWriter, r *http.Request) {
fail(w, r, http.StatusBadRequest, err.Error()) fail(w, r, http.StatusBadRequest, err.Error())
return return
} }
ejSQL := "INSERT INTO export_jobs (template_id, status, requested_by, permission_scope_json, filters_json, options_json, explain_json, explain_score, file_format, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)" const passThreshold = 60
ejArgs := []interface{}{p.TemplateID, "queued", p.RequestedBy, toJSON(p.Permission), toJSON(p.Filters), toJSON(p.Options), toJSON(expRows), score, p.FileFormat, time.Now()} if score < passThreshold {
fail(w, r, http.StatusBadRequest, fmt.Sprintf("EXPLAIN 未通过:评分=%d请优化索引或缩小查询范围", score))
return
}
var estimate int64
for _, r := range expRows {
if r.Table.Valid && r.Table.String == "order" && r.Rows.Valid { estimate = r.Rows.Int64; break }
if r.Rows.Valid { estimate += r.Rows.Int64 }
}
ejSQL := "INSERT INTO export_jobs (template_id, status, requested_by, permission_scope_json, filters_json, options_json, explain_json, explain_score, row_estimate, file_format, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"
ejArgs := []interface{}{p.TemplateID, "queued", p.RequestedBy, toJSON(p.Permission), toJSON(p.Filters), toJSON(p.Options), toJSON(expRows), score, estimate, p.FileFormat, time.Now(), time.Now()}
log.Printf("trace_id=%s sql=%s args=%v", TraceIDFrom(r), ejSQL, ejArgs) log.Printf("trace_id=%s sql=%s args=%v", TraceIDFrom(r), ejSQL, ejArgs)
res, err := a.meta.Exec(ejSQL, ejArgs...) res, err := a.meta.Exec(ejSQL, ejArgs...)
if err != nil { if err != nil {
@ -104,7 +121,7 @@ func (a *ExportsAPI) create(w http.ResponseWriter, r *http.Request) {
func (a *ExportsAPI) runJob(id uint64, db *sql.DB, q string, args []interface{}, cols []string, fmt string) { func (a *ExportsAPI) runJob(id uint64, db *sql.DB, q string, args []interface{}, cols []string, fmt string) {
log.Printf("job_id=%d sql=%s args=%v", id, "UPDATE export_jobs SET status=?, started_at=? WHERE id= ?", []interface{}{"running", time.Now(), id}) log.Printf("job_id=%d sql=%s args=%v", id, "UPDATE export_jobs SET status=?, started_at=? WHERE id= ?", []interface{}{"running", time.Now(), id})
a.meta.Exec("UPDATE export_jobs SET status=?, started_at=? WHERE id= ?", "running", time.Now(), id) a.meta.Exec("UPDATE export_jobs SET status=?, started_at=?, updated_at=? WHERE id= ?", "running", time.Now(), time.Now(), id)
if fmt == "csv" { if fmt == "csv" {
w, err := exporter.NewCSVWriter("storage", "export") w, err := exporter.NewCSVWriter("storage", "export")
if err != nil { if err != nil {
@ -125,6 +142,7 @@ func (a *ExportsAPI) runJob(id uint64, db *sql.DB, q string, args []interface{},
dest[i] = &out[i] dest[i] = &out[i]
} }
var count int64 var count int64
var tick int64
for rows.Next() { for rows.Next() {
if err := rows.Scan(dest...); err != nil { if err := rows.Scan(dest...); err != nil {
a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=? WHERE id=?", "failed", time.Now(), id) a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=? WHERE id=?", "failed", time.Now(), id)
@ -142,12 +160,14 @@ func (a *ExportsAPI) runJob(id uint64, db *sql.DB, q string, args []interface{},
} }
w.WriteRow(vals) w.WriteRow(vals)
count++ count++
tick++
if tick%500 == 0 { a.meta.Exec("UPDATE export_jobs SET total_rows=?, updated_at=? WHERE id= ?", count, time.Now(), id) }
} }
path, size, _ := w.Close() path, size, _ := w.Close()
log.Printf("job_id=%d sql=%s args=%v", id, "INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at) VALUES (?,?,?,?,?)", []interface{}{id, path, count, size, time.Now()}) log.Printf("job_id=%d sql=%s args=%v", id, "INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at, updated_at) VALUES (?,?,?,?,?,?)", []interface{}{id, path, count, size, time.Now(), time.Now()})
a.meta.Exec("INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at) VALUES (?,?,?,?,?)", id, path, count, size, time.Now()) a.meta.Exec("INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at, updated_at) VALUES (?,?,?,?,?,?)", id, path, count, size, time.Now(), time.Now())
log.Printf("job_id=%d sql=%s args=%v", id, "UPDATE export_jobs SET status=?, finished_at=?, total_rows=? WHERE id= ?", []interface{}{"completed", time.Now(), count, id}) log.Printf("job_id=%d sql=%s args=%v", id, "UPDATE export_jobs SET status=?, finished_at=?, total_rows=?, updated_at=? WHERE id= ?", []interface{}{"completed", time.Now(), count, time.Now(), id})
a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=?, total_rows=? WHERE id=?", "completed", time.Now(), count, id) a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=?, total_rows=?, updated_at=? WHERE id= ?", "completed", time.Now(), count, time.Now(), id)
return return
} }
if fmt == "xlsx" { if fmt == "xlsx" {
@ -189,13 +209,13 @@ func (a *ExportsAPI) runJob(id uint64, db *sql.DB, q string, args []interface{},
count++ count++
} }
p, size, _ := x.Close(path) p, size, _ := x.Close(path)
log.Printf("job_id=%d sql=%s args=%v", id, "INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at) VALUES (?,?,?,?,?)", []interface{}{id, p, count, size, time.Now()}) log.Printf("job_id=%d sql=%s args=%v", id, "INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at, updated_at) VALUES (?,?,?,?,?,?)", []interface{}{id, p, count, size, time.Now(), time.Now()})
a.meta.Exec("INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at) VALUES (?,?,?,?,?)", id, p, count, size, time.Now()) a.meta.Exec("INSERT INTO export_job_files (job_id, storage_uri, row_count, size_bytes, created_at, updated_at) VALUES (?,?,?,?,?,?)", id, p, count, size, time.Now(), time.Now())
log.Printf("job_id=%d sql=%s args=%v", id, "UPDATE export_jobs SET status=?, finished_at=?, total_rows=? WHERE id= ?", []interface{}{"completed", time.Now(), count, id}) log.Printf("job_id=%d sql=%s args=%v", id, "UPDATE export_jobs SET status=?, finished_at=?, total_rows=?, updated_at=? WHERE id= ?", []interface{}{"completed", time.Now(), count, time.Now(), id})
a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=?, total_rows=? WHERE id=?", "completed", time.Now(), count, id) a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=?, total_rows=?, updated_at=? WHERE id= ?", "completed", time.Now(), count, time.Now(), id)
return return
} }
a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=? WHERE id= ?", "failed", time.Now(), id) a.meta.Exec("UPDATE export_jobs SET status=?, finished_at=?, updated_at=? WHERE id= ?", "failed", time.Now(), time.Now(), id)
} }
func (a *ExportsAPI) selectDataDB(ds string) *sql.DB { func (a *ExportsAPI) selectDataDB(ds string) *sql.DB {
@ -256,7 +276,7 @@ func (a *ExportsAPI) download(w http.ResponseWriter, r *http.Request, id string)
} }
func (a *ExportsAPI) cancel(w http.ResponseWriter, r *http.Request, id string) { func (a *ExportsAPI) cancel(w http.ResponseWriter, r *http.Request, id string) {
a.meta.Exec("UPDATE export_jobs SET status=? WHERE id=? AND status IN ('queued','running')", "canceled", id) a.meta.Exec("UPDATE export_jobs SET status=?, updated_at=? WHERE id=? AND status IN ('queued','running')", "canceled", time.Now(), id)
w.Write([]byte("ok")) w.Write([]byte("ok"))
} }
@ -276,3 +296,55 @@ func toString(v interface{}) string {
return "" return ""
} }
} }
func (a *ExportsAPI) list(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page := 1
size := 15
if p := q.Get("page"); p != "" {
if n, err := strconv.Atoi(p); err == nil && n > 0 { page = n }
}
if s := q.Get("page_size"); s != "" {
if n, err := strconv.Atoi(s); err == nil && n > 0 && n <= 100 { size = n }
}
tplIDStr := q.Get("template_id")
var tplID uint64
if tplIDStr != "" {
if n, err := strconv.ParseUint(tplIDStr, 10, 64); err == nil { tplID = n }
}
offset := (page - 1) * size
var totalCount int64
if tplID > 0 {
row := a.meta.QueryRow("SELECT COUNT(1) FROM export_jobs WHERE template_id = ?", tplID)
_ = row.Scan(&totalCount)
} else {
row := a.meta.QueryRow("SELECT COUNT(1) FROM export_jobs")
_ = row.Scan(&totalCount)
}
var rows *sql.Rows
var err error
if tplID > 0 {
rows, err = a.meta.Query("SELECT id, template_id, status, requested_by, row_estimate, total_rows, file_format, created_at, updated_at, explain_score FROM export_jobs WHERE template_id = ? ORDER BY id DESC LIMIT ? OFFSET ?", tplID, size, offset)
} else {
rows, err = a.meta.Query("SELECT id, template_id, status, requested_by, row_estimate, total_rows, file_format, created_at, updated_at, explain_score FROM export_jobs ORDER BY id DESC LIMIT ? OFFSET ?", size, offset)
}
if err != nil {
fail(w, r, http.StatusInternalServerError, err.Error())
return
}
defer rows.Close()
items := []map[string]interface{}{}
for rows.Next() {
var id, tid, req uint64
var status, fmtstr string
var estimate, total sql.NullInt64
var createdAt, updatedAt sql.NullTime
var score sql.NullInt64
if err := rows.Scan(&id, &tid, &status, &req, &estimate, &total, &fmtstr, &createdAt, &updatedAt, &score); err != nil { continue }
evalStatus := "通过"
if score.Int64 < 60 { evalStatus = "禁止" }
desc := fmt.Sprintf("评分:%d估算行数:%d%s", score.Int64, estimate.Int64, map[bool]string{true:"允许执行", false:"禁止执行"}[score.Int64>=60])
m := map[string]interface{}{"id": id, "template_id": tid, "status": status, "requested_by": req, "row_estimate": estimate.Int64, "total_rows": total.Int64, "file_format": fmtstr, "created_at": createdAt.Time, "updated_at": updatedAt.Time, "eval_status": evalStatus, "eval_desc": desc}
items = append(items, m)
}
ok(w, r, map[string]interface{}{"items": items, "total": totalCount, "page": page, "page_size": size})
}

View File

@ -0,0 +1,72 @@
package api
import (
"database/sql"
"net/http"
"strconv"
"strings"
)
type ResellersAPI struct {
marketing *sql.DB
}
func ResellersHandler(marketing *sql.DB) http.Handler {
api := &ResellersAPI{marketing: marketing}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(r.URL.Path, "/api/resellers")
if r.Method == http.MethodGet && p == "" {
api.list(w, r)
return
}
w.WriteHeader(http.StatusNotFound)
})
}
func (a *ResellersAPI) list(w http.ResponseWriter, r *http.Request) {
creatorsParam := r.URL.Query().Get("creator")
q := r.URL.Query().Get("q")
limitStr := r.URL.Query().Get("limit")
limit := 2000
if limitStr != "" {
if n, err := strconv.Atoi(limitStr); err == nil && n > 0 && n <= 10000 { limit = n }
}
creators := []string{}
for _, s := range strings.Split(creatorsParam, ",") {
s = strings.TrimSpace(s)
if s != "" { creators = append(creators, s) }
}
if len(creators) == 0 {
ok(w, r, []map[string]interface{}{})
return
}
ph := strings.Repeat("?,", len(creators))
ph = strings.TrimSuffix(ph, ",")
sql1 := "SELECT DISTINCT reseller_id, COALESCE(reseller_name,'') AS name FROM plan WHERE reseller_id IS NOT NULL AND creator IN (" + ph + ")"
args := []interface{}{}
for _, c := range creators { args = append(args, c) }
if q != "" {
sql1 += " AND (CAST(reseller_id AS CHAR) LIKE ? OR reseller_name LIKE ?)"
like := "%" + q + "%"
args = append(args, like, like)
}
sql1 += " ORDER BY reseller_id ASC LIMIT ?"
args = append(args, limit)
rows, err := a.marketing.Query(sql1, args...)
if err != nil {
fail(w, r, http.StatusInternalServerError, err.Error())
return
}
defer rows.Close()
out := []map[string]interface{}{}
for rows.Next() {
var id sql.NullInt64
var name sql.NullString
if err := rows.Scan(&id, &name); err != nil { continue }
if !id.Valid { continue }
m := map[string]interface{}{"id": id.Int64, "name": name.String}
out = append(out, m)
}
ok(w, r, out)
}

View File

@ -14,6 +14,8 @@ func NewRouter(metaDB *sql.DB, marketingDB *sql.DB) http.Handler {
mux.Handle("/api/exports/", withAccess(withTrace(ExportsHandler(metaDB, marketingDB)))) mux.Handle("/api/exports/", withAccess(withTrace(ExportsHandler(metaDB, marketingDB))))
mux.Handle("/api/creators", withAccess(withTrace(CreatorsHandler(marketingDB)))) mux.Handle("/api/creators", withAccess(withTrace(CreatorsHandler(marketingDB))))
mux.Handle("/api/creators/", withAccess(withTrace(CreatorsHandler(marketingDB)))) mux.Handle("/api/creators/", withAccess(withTrace(CreatorsHandler(marketingDB))))
mux.Handle("/api/resellers", withAccess(withTrace(ResellersHandler(marketingDB))))
mux.Handle("/api/resellers/", withAccess(withTrace(ResellersHandler(marketingDB))))
sd := staticDir() sd := staticDir()
mux.Handle("/", http.FileServer(http.Dir(sd))) mux.Handle("/", http.FileServer(http.Dir(sd)))
return mux return mux

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

View File

@ -39,6 +39,7 @@
<el-table-column label="操作" width="260"> <el-table-column label="操作" width="260">
<template #default="scope"> <template #default="scope">
<el-button size="small" type="primary" @click="openExport(scope.row)">执行</el-button> <el-button size="small" type="primary" @click="openExport(scope.row)">执行</el-button>
<el-button size="small" @click="openJobs(scope.row)">任务</el-button>
<el-button size="small" @click="openEdit(scope.row)">编辑</el-button> <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="removeTemplate(scope.row.id)">删除</el-button> <el-button size="small" type="danger" @click="removeTemplate(scope.row.id)">删除</el-button>
</template> </template>
@ -47,12 +48,28 @@
</el-card> </el-card>
</el-col> </el-col>
<el-col :span="24"> <el-col :span="24">
<el-card header="导出任务"> <el-card v-if="jobsVisible" :header="'导出任务(模板 '+ (jobsTplId||'') +''">
<div v-if="job.id" class="job"> <el-table :data="jobs" size="small" stripe>
任务 {{ job.id }} 状态:<b>{{ job.status }}</b> 行数:{{ job.total_rows || '' }} <el-table-column prop="id" label="ID"></el-table-column>
<el-button v-if="job.files && job.files.length" type="success" size="small" @click="download(job.id)">下载</el-button> <el-table-column prop="eval_status" label="校验状态"></el-table-column>
<el-table-column label="进度">
<template #default="scope">{{ jobPercent(scope.row) }}</template>
</el-table-column>
<el-table-column prop="eval_desc" label="评估描述"></el-table-column>
<el-table-column prop="total_rows" label="行数"></el-table-column>
<el-table-column prop="file_format" label="格式"></el-table-column>
<el-table-column prop="created_at" label="创建时间"></el-table-column>
<el-table-column label="操作" width="140">
<template #default="scope">
<el-button size="small" type="success" @click="download(scope.row.id)">下载</el-button>
</template>
</el-table-column>
</el-table>
<div style="display:flex;justify-content:space-between;margin-top:8px">
<div><el-button size="small" @click="closeJobs">关闭</el-button></div>
<div><el-pagination background layout="prev, pager, next, total" :total="jobsTotal" :page-size="jobsPageSize" :current-page="jobsPage" @current-change="(p)=>loadJobs(p)" /></div>
</div> </div>
<div v-else>暂无任务</div> <div v-if="!jobs || !jobs.length" style="padding:8px 0;color:#999">暂无任务</div>
</el-card> </el-card>
</el-col> </el-col>
</el-row> </el-row>
@ -143,13 +160,13 @@
<el-button type="primary" @click="saveEdit">保存</el-button> <el-button type="primary" @click="saveEdit">保存</el-button>
</template> </template>
</el-dialog> </el-dialog>
<el-dialog v-model="exportVisible" :title="exportTitle" width="700px"> <el-dialog v-model="exportVisible" :title="exportTitle" width="1100px">
<el-form ref="exportFormRef" :model="exportForm" :rules="exportRules" label-width="110px" status-icon> <el-form ref="exportFormRef" :model="exportForm" :rules="exportRules" label-width="110px" status-icon>
<el-divider content-position="left">筛选条件</el-divider> <el-divider content-position="left">筛选条件</el-divider>
<el-row :gutter="8"> <el-row :gutter="8">
<el-col :span="12"> <el-col :span="24">
<el-form-item label="时间范围" required show-message prop="dateRange"> <el-form-item label="时间范围" required show-message prop="dateRange">
<el-date-picker v-model="exportForm.dateRange" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" /> <el-date-picker v-model="exportForm.dateRange" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" />
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
@ -164,7 +181,9 @@
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-form-item label="分销商ID" prop="resellerId"> <el-form-item label="分销商ID" prop="resellerId">
<el-input v-model.number="exportForm.resellerId" :disabled="!hasCreators" placeholder="reseller_id" /> <el-select v-model.number="exportForm.resellerId" filterable :teleported="false" placeholder="请选择分销商" style="width:100%" :disabled="!hasCreators">
<el-option v-for="opt in resellerOptions" :key="opt.value" :label="opt.label||String(opt.value)" :value="opt.value" />
</el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>

View File

@ -3,6 +3,12 @@ const { createApp, reactive } = Vue;
setup(){ setup(){
const state = reactive({ const state = reactive({
templates: [], templates: [],
jobs: [],
jobsVisible: false,
jobsTplId: null,
jobsPage: 1,
jobsPageSize: 15,
jobsTotal: 0,
job: {}, job: {},
form: { form: {
name: '', name: '',
@ -345,6 +351,7 @@ const { createApp, reactive } = Vue;
return v || '' return v || ''
} }
const creatorOptions = Vue.ref([]) const creatorOptions = Vue.ref([])
const resellerOptions = Vue.ref([])
const hasCreators = Vue.computed(()=> Array.isArray(state.exportForm.creatorIds) && state.exportForm.creatorIds.length>0 ) const hasCreators = Vue.computed(()=> Array.isArray(state.exportForm.creatorIds) && state.exportForm.creatorIds.length>0 )
const hasReseller = Vue.computed(()=> !!state.exportForm.resellerId) const hasReseller = Vue.computed(()=> !!state.exportForm.resellerId)
const hasPlan = Vue.computed(()=> !!state.exportForm.planId) const hasPlan = Vue.computed(()=> !!state.exportForm.planId)
@ -358,6 +365,16 @@ const { createApp, reactive } = Vue;
creatorOptions.value = arr.map(it=>({label: it.name || String(it.id), value: Number(it.id)})) creatorOptions.value = arr.map(it=>({label: it.name || String(it.id), value: Number(it.id)}))
}catch(_e){ creatorOptions.value = [] } }catch(_e){ creatorOptions.value = [] }
} }
const loadResellers = async ()=>{
const ids = Array.isArray(state.exportForm.creatorIds) ? state.exportForm.creatorIds : []
if(!ids.length){ resellerOptions.value = []; return }
try{
const res = await fetch(API_BASE + '/api/resellers?creator=' + ids.join(','))
const data = await res.json()
const arr = Array.isArray(data?.data) ? data.data : (Array.isArray(data) ? data : [])
resellerOptions.value = arr.map(it=>({label: (it.name||'') + (it.name?'':'') , value: Number(it.id)}))
}catch(_e){ resellerOptions.value = [] }
}
const exportType = Vue.computed(()=>{ const exportType = Vue.computed(()=>{
const f = state.exportTpl && state.exportTpl.filters const f = state.exportTpl && state.exportTpl.filters
if(!f) return null if(!f) return null
@ -404,6 +421,12 @@ const { createApp, reactive } = Vue;
const pad=(n)=>String(n).padStart(2,'0'); const pad=(n)=>String(n).padStart(2,'0');
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
} }
const yearRange = ()=>{
const now = new Date()
const start = new Date(now.getFullYear(), 0, 1, 0, 0, 0)
const end = new Date(now.getFullYear(), 11, 31, 23, 59, 59)
return [ fmtDT(start), fmtDT(end) ]
}
const loadTemplates = async ()=>{ const loadTemplates = async ()=>{
try{ try{
const res = await fetch(API_BASE + '/api/templates'); const res = await fetch(API_BASE + '/api/templates');
@ -420,6 +443,33 @@ const { createApp, reactive } = Vue;
state.templates = [] state.templates = []
} }
} }
const loadJobs = async (page)=>{
if(!page) page = state.jobsPage
try{
const qs = new URLSearchParams()
qs.set('page', String(page))
qs.set('page_size', String(state.jobsPageSize))
if(state.jobsTplId){ qs.set('template_id', String(state.jobsTplId)) }
const res = await fetch(API_BASE + '/api/exports?' + qs.toString());
if(!res.ok){ state.jobs = []; return }
const data = await res.json();
const payload = data?.data || data || {}
const arr = Array.isArray(payload.items) ? payload.items : (Array.isArray(payload) ? payload : [])
state.jobs = arr
state.jobsTotal = Number(payload.total || 0)
state.jobsPage = Number(payload.page || page)
}catch(_e){ state.jobs = [] }
}
const openJobs = (row)=>{ state.jobsTplId = row.id; state.jobsVisible = true; loadJobs(1) }
const closeJobs = ()=>{ state.jobsVisible = false }
const jobPercent = (row)=>{
const est = Number(row.row_estimate || 0)
const done = Number(row.total_rows || 0)
if(row.status==='completed') return '100%'
if(row.status==='queued') return '0%'
if(est>0 && done>=0){ const p = Math.max(0, Math.min(100, Math.floor(done*100/est))); return p + '%' }
return row.status || ''
}
const createTemplate = async ()=>{ const createTemplate = async ()=>{
const formRef = createFormRef.value const formRef = createFormRef.value
const ok = formRef ? await formRef.validate().catch(()=>false) : true const ok = formRef ? await formRef.validate().catch(()=>false) : true
@ -463,6 +513,7 @@ const { createApp, reactive } = Vue;
state.exportForm.datasource = state.exportTpl.datasource || row.datasource || 'marketing' state.exportForm.datasource = state.exportTpl.datasource || row.datasource || 'marketing'
state.exportForm.file_format = state.exportTpl.file_format || row.file_format || 'xlsx' state.exportForm.file_format = state.exportTpl.file_format || row.file_format || 'xlsx'
if(state.exportForm.datasource==='marketing'){ loadCreators() } if(state.exportForm.datasource==='marketing'){ loadCreators() }
if(!Array.isArray(state.exportForm.dateRange) || state.exportForm.dateRange.length!==2){ state.exportForm.dateRange = yearRange() }
state.exportVisible = true state.exportVisible = true
} }
const loadTemplateDetail = async (id)=>{ const loadTemplateDetail = async (id)=>{
@ -501,9 +552,9 @@ const { createApp, reactive } = Vue;
const j=await r.json(); const j=await r.json();
const jid = j?.data?.id ?? j?.id const jid = j?.data?.id ?? j?.id
state.exportVisible=false state.exportVisible=false
if(jid){ loadJob(jid) } else { msg('任务创建返回异常','error') } if(jid){ loadJob(jid); loadJobs() } else { msg('任务创建返回异常','error') }
} }
Vue.watch(()=>state.exportForm.creatorIds, ()=>{ state.exportForm.resellerId=null; state.exportForm.planId=null; state.exportForm.keyBatchId=null; state.exportForm.codeBatchId=null; state.exportForm.productId=null }) Vue.watch(()=>state.exportForm.creatorIds, ()=>{ state.exportForm.resellerId=null; state.exportForm.planId=null; state.exportForm.keyBatchId=null; state.exportForm.codeBatchId=null; state.exportForm.productId=null; loadResellers() })
Vue.watch(()=>state.exportForm.resellerId, ()=>{ state.exportForm.planId=null; state.exportForm.keyBatchId=null; state.exportForm.codeBatchId=null; state.exportForm.productId=null }) Vue.watch(()=>state.exportForm.resellerId, ()=>{ state.exportForm.planId=null; state.exportForm.keyBatchId=null; state.exportForm.codeBatchId=null; state.exportForm.productId=null })
Vue.watch(()=>state.exportForm.planId, ()=>{ state.exportForm.keyBatchId=null; state.exportForm.codeBatchId=null; state.exportForm.productId=null }) Vue.watch(()=>state.exportForm.planId, ()=>{ state.exportForm.keyBatchId=null; state.exportForm.codeBatchId=null; state.exportForm.productId=null })
Vue.watch(()=>state.exportForm.keyBatchId, ()=>{ state.exportForm.codeBatchId=null; state.exportForm.productId=null }) Vue.watch(()=>state.exportForm.keyBatchId, ()=>{ state.exportForm.codeBatchId=null; state.exportForm.productId=null })
@ -562,7 +613,8 @@ const { createApp, reactive } = Vue;
} }
const download = (id)=>{ window.open(API_BASE + '/api/exports/'+id+'/download','_blank') } const download = (id)=>{ window.open(API_BASE + '/api/exports/'+id+'/download','_blank') }
loadTemplates() loadTemplates()
return { ...Vue.toRefs(state), visibilityOptions, formatOptions, datasourceOptions, fieldOptions, loadTemplates, createTemplate, openExport, submitExport, loadJob, download, openEdit, saveEdit, removeTemplate, resizeDialog, createRules, exportRules, editRules, createFormRef, exportFormRef, editFormRef, dsLabel, exportType, isOrder, exportTitle }
return { ...Vue.toRefs(state), visibilityOptions, formatOptions, datasourceOptions, fieldOptions, loadTemplates, createTemplate, openExport, submitExport, loadJob, loadJobs, openJobs, closeJobs, download, openEdit, saveEdit, removeTemplate, resizeDialog, createRules, exportRules, editRules, createFormRef, exportFormRef, editFormRef, dsLabel, exportType, isOrder, exportTitle, creatorOptions, resellerOptions, hasCreators, hasReseller, hasPlan, hasKeyBatch, hasCodeBatch, jobPercent }
} }
}) })
app.use(ElementPlus) app.use(ElementPlus)