feat: improve gas station management workflow
This commit is contained in:
@@ -386,9 +386,8 @@ func ResourceResponse(value any) any {
|
||||
return stripInternalIDs(decoded)
|
||||
}
|
||||
|
||||
// PublicResourceResponse additionally resolves persisted relation keys into
|
||||
// their public identities. It is used by list/detail endpoints so an edit form
|
||||
// can round-trip the relation without ever receiving a surrogate database ID.
|
||||
// PublicResourceResponse preserves a resource's own ID for administrative
|
||||
// display while resolving and removing persistence-only relation IDs.
|
||||
func PublicResourceResponse(value any) (any, error) {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
@@ -450,7 +449,7 @@ type relationIdentityRecord struct {
|
||||
|
||||
func projectRelationIdentities(value any) (any, error) {
|
||||
groups := map[string]*relationIdentityGroup{}
|
||||
collectRelationIdentityReferences(value, groups)
|
||||
collectRelationIdentityReferences(value, groups, true)
|
||||
groupKeys := make([]string, 0, len(groups))
|
||||
for key := range groups {
|
||||
groupKeys = append(groupKeys, key)
|
||||
@@ -477,12 +476,14 @@ func projectRelationIdentities(value any) (any, error) {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func collectRelationIdentityReferences(value any, groups map[string]*relationIdentityGroup) {
|
||||
func collectRelationIdentityReferences(value any, groups map[string]*relationIdentityGroup, preserveRecordID bool) {
|
||||
switch data := value.(type) {
|
||||
case map[string]any:
|
||||
for key, item := range data {
|
||||
if key == "id" {
|
||||
delete(data, key)
|
||||
if !preserveRecordID {
|
||||
delete(data, key)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(key, "_id") {
|
||||
@@ -515,11 +516,11 @@ func collectRelationIdentityReferences(value any, groups map[string]*relationIde
|
||||
delete(data, key)
|
||||
continue
|
||||
}
|
||||
collectRelationIdentityReferences(item, groups)
|
||||
collectRelationIdentityReferences(item, groups, false)
|
||||
}
|
||||
case []any:
|
||||
for _, item := range data {
|
||||
collectRelationIdentityReferences(item, groups)
|
||||
collectRelationIdentityReferences(item, groups, preserveRecordID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,38 @@ func TestResourceResponseStripsInternalIDsRecursively(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicResourceResponsePreservesOnlyRecordID(t *testing.T) {
|
||||
got, err := PublicResourceResponse(map[string]any{
|
||||
"id": uint64(7), "identity": "record",
|
||||
"child": map[string]any{"id": uint64(8), "identity": "child"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record := got.(map[string]any)
|
||||
if record["id"] != float64(7) {
|
||||
t.Fatalf("record ID = %#v, want 7", record["id"])
|
||||
}
|
||||
if _, exists := record["child"].(map[string]any)["id"]; exists {
|
||||
t.Fatal("nested database ID was exposed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicResourceResponsePreservesListRecordIDs(t *testing.T) {
|
||||
got, err := PublicResourceResponse([]map[string]any{
|
||||
{"id": uint64(11), "identity": "first"},
|
||||
{"id": uint64(12), "identity": "second"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list := got.([]any)
|
||||
if list[0].(map[string]any)["id"] != float64(11) ||
|
||||
list[1].(map[string]any)["id"] != float64(12) {
|
||||
t.Fatalf("list record IDs were not preserved: %#v", list)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicFieldProtectionMasksGasorderContacts(t *testing.T) {
|
||||
value := map[string]any{"contact_name": "张三", "contact_phone": "13800138000"}
|
||||
ProtectPublicFields(value, false, false, false)
|
||||
|
||||
@@ -1,16 +1,38 @@
|
||||
package delivery
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
"git.apinb.com/bsm-sdk/core/infra"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/logic/common"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ListDeliveryBasic 查询配送点分页列表。
|
||||
func ListDeliveryBasic(ctx *gin.Context) { common.ListPage[models.DeliveryBasic](ctx) }
|
||||
func ListDeliveryBasic(ctx *gin.Context) {
|
||||
gasIdentities := strings.Split(strings.TrimSpace(ctx.Query("gas_basic_identities")), ",")
|
||||
if len(gasIdentities) == 1 && gasIdentities[0] == "" {
|
||||
gasIdentities = nil
|
||||
}
|
||||
if len(gasIdentities) > 100 {
|
||||
infra.Response.Error(ctx, errcode.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
common.ListPageFiltered[models.DeliveryBasic](ctx, func(query *gorm.DB) *gorm.DB {
|
||||
if len(gasIdentities) == 0 {
|
||||
return query
|
||||
}
|
||||
return query.Where(
|
||||
"gas_basic_id IN (SELECT id FROM gas_basic WHERE identity IN ? AND status <> ?)",
|
||||
gasIdentities,
|
||||
common.StatusArchived,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// GetDeliveryBasic 查询一个配送点。
|
||||
func GetDeliveryBasic(ctx *gin.Context) { common.GetByIdentity[models.DeliveryBasic](ctx) }
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
package gas
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.apinb.com/bsm-sdk/core/errcode"
|
||||
"git.apinb.com/bsm-sdk/core/infra"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/impl"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/logic/common"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// ListGasBasic 查询可燃气体站分页列表。
|
||||
@@ -46,3 +52,78 @@ func UpdateGasBasic(ctx *gin.Context) {
|
||||
}
|
||||
common.UpdateAllowedByIdentity(ctx, &models.GasBasic{}, gin.H{"name": request.Name, "credit_code": request.CreditCode, "principal": request.Principal, "address": request.Address, "longitude": request.Longitude, "latitude": request.Latitude}, []string{"name", "credit_code", "principal", "address", "longitude", "latitude"})
|
||||
}
|
||||
|
||||
// UpdateGasBasicStatus 仅允许已审核气站在启用和停用之间切换。
|
||||
func UpdateGasBasicStatus(ctx *gin.Context) {
|
||||
var request struct {
|
||||
Status int `json:"status" binding:"required"`
|
||||
}
|
||||
if err := ctx.ShouldBindJSON(&request); err != nil ||
|
||||
(request.Status != common.StatusEnable && request.Status != common.StatusDisable) {
|
||||
infra.Response.Error(ctx, errcode.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
result := impl.DBService.Model(&models.GasBasic{}).
|
||||
Where("identity = ? AND status IN ?", ctx.Param("identity"), []int{common.StatusEnable, common.StatusDisable}).
|
||||
Update("status", request.Status)
|
||||
if result.Error != nil {
|
||||
infra.Response.Error(ctx, result.Error)
|
||||
return
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
infra.Response.Error(ctx, errcode.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
infra.Response.Success(ctx, gin.H{"updated": true})
|
||||
}
|
||||
|
||||
// ReviewGasBasic 审核待审核气站;不通过时必须填写理由。
|
||||
func ReviewGasBasic(ctx *gin.Context) {
|
||||
var request struct {
|
||||
Approved bool `json:"approved"`
|
||||
Reason string `json:"reason" binding:"max=2000"`
|
||||
}
|
||||
if err := ctx.ShouldBindJSON(&request); err != nil ||
|
||||
(!request.Approved && strings.TrimSpace(request.Reason) == "") {
|
||||
infra.Response.Error(ctx, errcode.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
|
||||
operatorIdentity, operatorName := common.PlatformOperator(ctx)
|
||||
targetStatus := common.StatusDisable
|
||||
reviewStatus := common.StatusRejected
|
||||
if request.Approved {
|
||||
targetStatus = common.StatusEnable
|
||||
reviewStatus = common.StatusApproved
|
||||
}
|
||||
now := time.Now()
|
||||
err := impl.DBService.Transaction(func(tx *gorm.DB) error {
|
||||
var station models.GasBasic
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("identity = ? AND status <> ?", ctx.Param("identity"), common.StatusArchived).
|
||||
First(&station).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if station.Status != common.StatusDraft {
|
||||
return errors.New("gas station is not pending review")
|
||||
}
|
||||
if err := tx.Model(&station).Update("status", targetStatus).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
review := models.GasBasicReview{
|
||||
Entity: common.NewEntity(common.StatusEnable),
|
||||
GasBasicID: station.ID,
|
||||
ReviewStatus: reviewStatus,
|
||||
ReviewReason: strings.TrimSpace(request.Reason),
|
||||
ReviewerIdentity: operatorIdentity,
|
||||
ReviewerName: operatorName,
|
||||
ReviewedAt: now,
|
||||
}
|
||||
return tx.Create(&review).Error
|
||||
})
|
||||
if err != nil {
|
||||
common.RespondRecordError(ctx, err)
|
||||
return
|
||||
}
|
||||
infra.Response.Success(ctx, gin.H{"updated": true, "status": targetStatus})
|
||||
}
|
||||
|
||||
@@ -46,6 +46,9 @@ func platformMenuAllowsRequest(menus []platformbase.Menu, requestPath, method st
|
||||
(resource == "delivery_basic" || resource == "staff_account") {
|
||||
return true
|
||||
}
|
||||
if method == "GET" && menu.Identity == "gas_basic" && resource == "delivery_basic" {
|
||||
return true
|
||||
}
|
||||
if method == "GET" && relative == "wallet_basic" &&
|
||||
(menu.Identity == "gas_basic" || menu.Identity == "delivery_basic" ||
|
||||
menu.Identity == "staff" || menu.Identity == "user_account" ||
|
||||
|
||||
@@ -58,6 +58,16 @@ func TestOwnerMenusCanReadEmbeddedWallets(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGasManagementCanReadDeliveryPointCounts(t *testing.T) {
|
||||
menus := []platformbase.Menu{{Identity: "gas_basic"}}
|
||||
if !platformMenuAllowsRequest(menus, "/heqi/platform/v1/delivery_basic", "GET") {
|
||||
t.Fatal("gas management could not read its delivery point counts")
|
||||
}
|
||||
if platformMenuAllowsRequest(menus, "/heqi/platform/v1/delivery_basic", "POST") {
|
||||
t.Fatal("gas management unexpectedly received delivery point creation access")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocationScopeValuesAreExplicit(t *testing.T) {
|
||||
if !validLocationScope("standard") || !validLocationScope("precise") {
|
||||
t.Fatal("supported location scopes were rejected")
|
||||
|
||||
23
backend/api/internal/models/gas_basic_review.go
Normal file
23
backend/api/internal/models/gas_basic_review.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.apinb.com/bsm-sdk/core/database"
|
||||
)
|
||||
|
||||
// GasBasicReview 对应 gas_basic_review,保存气站审核记录。
|
||||
type GasBasicReview struct {
|
||||
Entity // 公共实体字段
|
||||
GasBasicID uint64 `gorm:"column:gas_basic_id;not null;index" json:"gas_basic_id"` // 气站自增主键
|
||||
ReviewStatus int `gorm:"column:review_status;not null;index" json:"review_status"` // 审核结果:已通过或已驳回
|
||||
ReviewReason string `gorm:"column:review_reason;type:text;not null;default:''" json:"review_reason"` // 审核不通过理由
|
||||
ReviewerIdentity string `gorm:"column:reviewer_identity;type:varchar(36);not null;default:'';index" json:"reviewer_identity"` // 审核人业务标识
|
||||
ReviewerName string `gorm:"column:reviewer_name;type:varchar(64);not null;default:''" json:"reviewer_name"` // 审核人姓名快照
|
||||
ReviewedAt time.Time `gorm:"column:reviewed_at;type:timestamptz;not null" json:"reviewed_at"` // 审核时间
|
||||
}
|
||||
|
||||
func init() { database.AppendMigrate(&GasBasicReview{}) }
|
||||
|
||||
// TableName 返回与模型、文件名一致的单数数据表名。
|
||||
func (table *GasBasicReview) TableName() string { return "gas_basic_review" }
|
||||
@@ -49,7 +49,14 @@ func RegisterPlatform(serviceKey string, engine *gin.Engine) {
|
||||
}
|
||||
|
||||
func registerGasRoute(group *gin.RouterGroup) {
|
||||
registerWritableResource(group, "/gas_basic", gas.ListGasBasic, gas.CreateGasBasic, gas.GetGasBasic, gas.UpdateGasBasic, &models.GasBasic{})
|
||||
basic := group.Group("/gas_basic")
|
||||
basic.GET("", gas.ListGasBasic)
|
||||
basic.POST("", gas.CreateGasBasic)
|
||||
basic.GET("/:identity", gas.GetGasBasic)
|
||||
basic.PUT("/:identity", gas.UpdateGasBasic)
|
||||
basic.PATCH("/:identity/status", gas.UpdateGasBasicStatus)
|
||||
basic.POST("/:identity/review", gas.ReviewGasBasic)
|
||||
basic.DELETE("/:identity", func(ctx *gin.Context) { common.ArchiveRecord(ctx, &models.GasBasic{}) })
|
||||
registerWritableResource(group, "/gas_account", gas.ListGasAccount, gas.CreateGasAccount, gas.GetGasAccount, gas.UpdateGasAccount, &models.GasAccount{})
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,18 @@ func TestPlatformGasRouteUsesGasBasic(t *testing.T) {
|
||||
t.Fatal("gas_basic list route is not registered")
|
||||
}
|
||||
|
||||
func TestPlatformGasRouteExposesReview(t *testing.T) {
|
||||
engine := gin.New()
|
||||
RegisterPlatform("heqi", engine)
|
||||
|
||||
for _, route := range engine.Routes() {
|
||||
if route.Method == http.MethodPost && route.Path == "/heqi/platform/v1/gas_basic/:identity/review" {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("gas_basic review route is not registered")
|
||||
}
|
||||
|
||||
func TestPlatformOrganizationAndAccountRoutesExposeResourceCRUD(t *testing.T) {
|
||||
engine := gin.New()
|
||||
RegisterPlatform("heqi", engine)
|
||||
|
||||
@@ -3,8 +3,14 @@
|
||||
<template #extra>
|
||||
<a-space>
|
||||
<a-button v-if="managedOwnerIdentity" @click="router.back()">返回机构列表</a-button>
|
||||
<a-button @click="load">刷新</a-button>
|
||||
<a-button v-if="canCreate" type="primary" @click="openCreate">新建</a-button>
|
||||
<a-button @click="load">
|
||||
<template #icon><icon-refresh /></template>
|
||||
刷新
|
||||
</a-button>
|
||||
<a-button v-if="canCreate" type="primary" @click="openCreate">
|
||||
<template #icon><icon-plus /></template>
|
||||
新建
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
<a-form :model="filters" layout="inline" class="filters" @submit.prevent="search">
|
||||
@@ -16,7 +22,7 @@
|
||||
</a-form>
|
||||
<a-table :data="list" :loading="loading" :pagination="false" row-key="identity">
|
||||
<template #columns>
|
||||
<a-table-column title="业务标识" data-index="identity" :width="220" ellipsis tooltip />
|
||||
<a-table-column title="ID" data-index="id" :width="100" />
|
||||
<a-table-column v-for="field in displayFields" :key="field.key" :title="field.label" ellipsis tooltip>
|
||||
<template #cell="{ record }">
|
||||
{{ displayFieldValue(field, record) }}
|
||||
@@ -25,6 +31,9 @@
|
||||
<a-table-column v-if="definition.accountManagement" title="账户数" :width="90">
|
||||
<template #cell="{ record }">{{ accountCounts[String(record.identity)] ?? 0 }}</template>
|
||||
</a-table-column>
|
||||
<a-table-column v-if="definition.name === 'gas_basic'" title="配送点数" :width="100">
|
||||
<template #cell="{ record }">{{ deliveryPointCounts[String(record.identity)] ?? 0 }}</template>
|
||||
</a-table-column>
|
||||
<a-table-column v-if="definition.name === 'staff_account'" title="审批状态" :width="100">
|
||||
<template #cell="{ record }">
|
||||
<a-tag :color="Number(record.status) === 1 ? 'green' : Number(record.status) === 2 ? 'red' : 'orange'">
|
||||
@@ -40,6 +49,13 @@
|
||||
<span v-else class="muted-text">未开通</span>
|
||||
</template>
|
||||
</a-table-column>
|
||||
<a-table-column v-if="definition.name === 'gas_basic'" title="状态" :width="90">
|
||||
<template #cell="{ record }">
|
||||
<a-tag :color="recordStatusColor(Number(record.status))">
|
||||
{{ recordStatusLabel(Number(record.status)) }}
|
||||
</a-tag>
|
||||
</template>
|
||||
</a-table-column>
|
||||
<a-table-column title="操作" :width="definition.accountManagement ? 350 : 280" fixed="right">
|
||||
<template #cell="{ record }">
|
||||
<a-space>
|
||||
@@ -47,7 +63,7 @@
|
||||
<a-button v-if="definition.name === 'staff_account'" size="mini" @click="viewCredentials(record)">查看资质</a-button>
|
||||
<a-button size="mini" @click="openDetail(record)">详情</a-button>
|
||||
<a-button v-if="canEdit" size="mini" :disabled="isProtectedRecord(record)" @click="openEdit(record)">编辑</a-button>
|
||||
<a-button v-if="canChangeStatus" size="mini" :disabled="isProtectedRecord(record)" @click="openStatus(record)">审核</a-button>
|
||||
<a-button v-if="canChangeStatus && definition.name !== 'gas_basic'" size="mini" :disabled="isProtectedRecord(record)" @click="openStatus(record)">审核</a-button>
|
||||
<a-button v-if="canArchive" size="mini" status="danger" :disabled="isProtectedRecord(record)" @click="confirmArchive(record)">删除</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
@@ -57,6 +73,76 @@
|
||||
<div class="pagination"><a-pagination :total="total" :current="page" :page-size="pageSize" show-total show-jumper @change="changePage" /></div>
|
||||
</a-card>
|
||||
|
||||
<a-modal
|
||||
:visible="accountModalVisible"
|
||||
:title="`${definition.accountManagement?.title ?? '账户管理'} · ${String(accountOwner.name ?? accountOwner.code ?? accountOwner.delivery_code ?? '')}`"
|
||||
:width="920"
|
||||
:footer="false"
|
||||
@cancel="accountModalVisible = false"
|
||||
>
|
||||
<div class="account-toolbar">
|
||||
<a-button @click="loadManagedAccounts">刷新</a-button>
|
||||
<a-button type="primary" @click="openAccountCreate">新建账户</a-button>
|
||||
</div>
|
||||
<a-table :data="accountList" :loading="accountLoading" :pagination="false" row-key="identity">
|
||||
<template #columns>
|
||||
<a-table-column title="用户名" data-index="username" />
|
||||
<a-table-column title="显示名称" data-index="display_name" />
|
||||
<a-table-column title="角色编码" data-index="role_code" />
|
||||
<a-table-column title="状态" :width="90">
|
||||
<template #cell="{ record }">
|
||||
<a-tag :color="Number(record.status) === 1 ? 'green' : 'red'">
|
||||
{{ Number(record.status) === 1 ? '启用' : '停用' }}
|
||||
</a-tag>
|
||||
</template>
|
||||
</a-table-column>
|
||||
<a-table-column title="操作" :width="240">
|
||||
<template #cell="{ record }">
|
||||
<a-space>
|
||||
<a-button size="mini" @click="openAccountEdit(record)">编辑</a-button>
|
||||
<a-button size="mini" @click="toggleAccountStatus(record)">
|
||||
{{ Number(record.status) === 1 ? '禁用' : '启用' }}
|
||||
</a-button>
|
||||
<a-button size="mini" status="danger" @click="archiveAccount(record)">删除</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</a-table-column>
|
||||
</template>
|
||||
</a-table>
|
||||
<div class="pagination">
|
||||
<a-pagination
|
||||
:total="accountTotal"
|
||||
:current="accountPage"
|
||||
:page-size="accountPageSize"
|
||||
show-total
|
||||
@change="changeAccountPage"
|
||||
/>
|
||||
</div>
|
||||
</a-modal>
|
||||
|
||||
<a-modal
|
||||
:visible="accountFormVisible"
|
||||
:title="accountEditingIdentity ? '编辑账户' : '新建账户'"
|
||||
:ok-loading="accountSaving"
|
||||
@cancel="accountFormVisible = false"
|
||||
@ok="saveAccount"
|
||||
>
|
||||
<a-form :model="accountForm" layout="vertical">
|
||||
<a-form-item label="用户名" required>
|
||||
<a-input v-model="accountForm.username" :disabled="Boolean(accountEditingIdentity)" />
|
||||
</a-form-item>
|
||||
<a-form-item v-if="!accountEditingIdentity" label="密码" required>
|
||||
<a-input-password v-model="accountForm.password" />
|
||||
</a-form-item>
|
||||
<a-form-item label="显示名称">
|
||||
<a-input v-model="accountForm.display_name" />
|
||||
</a-form-item>
|
||||
<a-form-item label="角色编码">
|
||||
<a-input v-model="accountForm.role_code" />
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
|
||||
<a-drawer :visible="formVisible" :title="editingIdentity ? `编辑${definition.title}` : `新建${definition.title}`" :width="520" :ok-loading="saving" @cancel="formVisible = false" @ok="save">
|
||||
<a-form :model="form" layout="vertical">
|
||||
<a-form-item v-for="field in formFields" :key="field.key" :label="field.label" :required="isResourceFieldRequired(field, formMode)">
|
||||
@@ -89,6 +175,37 @@
|
||||
<template v-else>{{ displayValue(key, value) }}</template>
|
||||
</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
<div v-if="definition.name === 'gas_basic'" class="status-editor">
|
||||
<span class="status-editor-label">当前状态</span>
|
||||
<a-tag :color="recordStatusColor(Number(detail.status))">
|
||||
{{ recordStatusLabel(Number(detail.status)) }}
|
||||
</a-tag>
|
||||
<template v-if="canChangeStatus">
|
||||
<span class="status-switch-label">修改状态</span>
|
||||
<a-switch
|
||||
:model-value="Number(detail.status) === 1"
|
||||
:loading="gasStatusSaving"
|
||||
:disabled="![1, 2].includes(Number(detail.status))"
|
||||
checked-text="启用"
|
||||
unchecked-text="停用"
|
||||
@change="updateGasStatus"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="definition.name === 'gas_basic' && canChangeStatus && Number(detail.status) === 0" class="review-panel">
|
||||
<div class="review-title">气站审核</div>
|
||||
<a-space direction="vertical" fill>
|
||||
<a-button type="primary" :loading="gasReviewSaving" @click="reviewGasStation(true)">审核通过</a-button>
|
||||
<a-textarea
|
||||
v-model="gasRejectReason"
|
||||
:max-length="2000"
|
||||
show-word-limit
|
||||
placeholder="审核不通过时,请填写理由"
|
||||
:auto-size="{ minRows: 2, maxRows: 5 }"
|
||||
/>
|
||||
<a-button status="danger" :loading="gasReviewSaving" @click="reviewGasStation(false)">审核不通过</a-button>
|
||||
</a-space>
|
||||
</div>
|
||||
<a-tabs v-if="detailCollections.length" class="detail-collections">
|
||||
<a-tab-pane v-for="collection in detailCollections" :key="collection.key" :title="collection.title">
|
||||
<a-table :data="collection.rows" :pagination="false" size="small">
|
||||
@@ -126,6 +243,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Message, Modal } from '@arco-design/web-vue';
|
||||
import { IconPlus, IconRefresh } from '@arco-design/web-vue/es/icon';
|
||||
import dayjs from 'dayjs';
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
@@ -156,6 +274,21 @@ const pageSize = 20;
|
||||
const total = ref(0);
|
||||
const list = ref<Row[]>([]);
|
||||
const accountCounts = ref<Record<string, number>>({});
|
||||
const deliveryPointCounts = ref<Record<string, number>>({});
|
||||
const accountModalVisible = ref(false);
|
||||
const accountLoading = ref(false);
|
||||
const accountList = ref<Row[]>([]);
|
||||
const accountOwner = ref<Row>({});
|
||||
const accountPage = ref(1);
|
||||
const accountPageSize = 10;
|
||||
const accountTotal = ref(0);
|
||||
const accountFormVisible = ref(false);
|
||||
const accountSaving = ref(false);
|
||||
const accountEditingIdentity = ref('');
|
||||
const accountForm = reactive<Record<string, any>>({});
|
||||
const gasStatusSaving = ref(false);
|
||||
const gasReviewSaving = ref(false);
|
||||
const gasRejectReason = ref('');
|
||||
const walletByOwner = ref<Record<string, Row>>({});
|
||||
const filters = reactive({
|
||||
keyword: typeof route.query.keyword === 'string' ? route.query.keyword : '',
|
||||
@@ -228,13 +361,21 @@ const formFields = computed(() =>
|
||||
);
|
||||
const displayFields = computed(() =>
|
||||
props.definition.fields
|
||||
.filter((field) => field.key !== 'password')
|
||||
.filter(
|
||||
(field) =>
|
||||
field.key !== 'password' &&
|
||||
!(
|
||||
props.definition.name === 'gas_basic' &&
|
||||
(field.key === 'longitude' || field.key === 'latitude')
|
||||
),
|
||||
)
|
||||
.slice(0, 6),
|
||||
);
|
||||
const detailEntries = computed(() => {
|
||||
const entries = Object.entries(detail.value).filter(
|
||||
([key, value]) =>
|
||||
key !== 'id' &&
|
||||
!(props.definition.name === 'gas_basic' && key === 'status') &&
|
||||
!key.endsWith('_id') &&
|
||||
!Array.isArray(value) &&
|
||||
!(value && typeof value === 'object' && key !== 'order' && key !== 'contract'),
|
||||
@@ -341,6 +482,7 @@ async function load() {
|
||||
total.value = result.total;
|
||||
}
|
||||
await loadAccountCounts();
|
||||
await loadDeliveryPointCounts();
|
||||
await loadWallets();
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
@@ -408,21 +550,169 @@ async function loadAccountCounts() {
|
||||
}, {});
|
||||
}
|
||||
|
||||
function manageAccounts(row: Row) {
|
||||
async function loadDeliveryPointCounts() {
|
||||
if (props.definition.name !== 'gas_basic') {
|
||||
deliveryPointCounts.value = {};
|
||||
return;
|
||||
}
|
||||
const gasIdentities = list.value
|
||||
.map((row) => String(row.identity ?? ''))
|
||||
.filter(Boolean);
|
||||
if (!gasIdentities.length) {
|
||||
deliveryPointCounts.value = {};
|
||||
return;
|
||||
}
|
||||
const deliveryPoints = await loadAllRows('/delivery_basic', {
|
||||
gas_basic_identities: gasIdentities.join(','),
|
||||
});
|
||||
deliveryPointCounts.value = deliveryPoints.reduce<Record<string, number>>(
|
||||
(counts, deliveryPoint) => {
|
||||
const identity = String(deliveryPoint.gas_basic_identity ?? '');
|
||||
if (identity) counts[identity] = (counts[identity] ?? 0) + 1;
|
||||
return counts;
|
||||
},
|
||||
{},
|
||||
);
|
||||
}
|
||||
|
||||
function recordStatusLabel(status: number) {
|
||||
return { 0: '待审核', 1: '启用', 2: '停用', 3: '已归档', 4: '已冻结' }[status] ?? '未知';
|
||||
}
|
||||
|
||||
function recordStatusColor(status: number) {
|
||||
return { 0: 'orange', 1: 'green', 2: 'red', 3: 'gray', 4: 'purple' }[status] ?? 'gray';
|
||||
}
|
||||
|
||||
async function manageAccounts(row: Row) {
|
||||
const management = props.definition.accountManagement;
|
||||
if (!management) return;
|
||||
const routeName = management.resource === '/gas_account'
|
||||
? 'organization-gas-account'
|
||||
: 'organization-delivery-account';
|
||||
router.push({
|
||||
name: routeName,
|
||||
query: {
|
||||
owner_identity: String(row.identity ?? ''),
|
||||
relation_key: management.relationKey,
|
||||
accountOwner.value = row;
|
||||
accountPage.value = 1;
|
||||
accountModalVisible.value = true;
|
||||
await loadManagedAccounts();
|
||||
}
|
||||
|
||||
async function loadManagedAccounts() {
|
||||
const management = props.definition.accountManagement;
|
||||
const ownerIdentity = String(accountOwner.value.identity ?? '');
|
||||
if (!management || !ownerIdentity) return;
|
||||
const filterKey = management.relationKey === 'gas_basic_identity'
|
||||
? 'gas_basic_identities'
|
||||
: 'delivery_basic_identities';
|
||||
accountLoading.value = true;
|
||||
try {
|
||||
const result = await resourceApi.list<Row>(
|
||||
management.resource,
|
||||
accountPage.value,
|
||||
accountPageSize,
|
||||
{ [filterKey]: ownerIdentity },
|
||||
);
|
||||
accountList.value = result.list;
|
||||
accountTotal.value = result.total;
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
} finally {
|
||||
accountLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetAccountForm(row?: Row) {
|
||||
accountForm.username = row?.username ?? '';
|
||||
accountForm.password = '';
|
||||
accountForm.display_name = row?.display_name ?? '';
|
||||
accountForm.role_code = row?.role_code ?? '';
|
||||
}
|
||||
|
||||
function openAccountCreate() {
|
||||
accountEditingIdentity.value = '';
|
||||
resetAccountForm();
|
||||
accountFormVisible.value = true;
|
||||
}
|
||||
|
||||
function openAccountEdit(row: Row) {
|
||||
accountEditingIdentity.value = String(row.identity ?? '');
|
||||
resetAccountForm(row);
|
||||
accountFormVisible.value = true;
|
||||
}
|
||||
|
||||
async function saveAccount() {
|
||||
const management = props.definition.accountManagement;
|
||||
const ownerIdentity = String(accountOwner.value.identity ?? '');
|
||||
if (!management || !ownerIdentity) return;
|
||||
if (!String(accountForm.username ?? '').trim() ||
|
||||
(!accountEditingIdentity.value && !String(accountForm.password ?? '').trim())) {
|
||||
Message.warning('请填写用户名和密码');
|
||||
return;
|
||||
}
|
||||
accountSaving.value = true;
|
||||
try {
|
||||
const payload: Record<string, unknown> = {
|
||||
display_name: String(accountForm.display_name ?? '').trim(),
|
||||
role_code: String(accountForm.role_code ?? '').trim(),
|
||||
[management.relationKey]: ownerIdentity,
|
||||
};
|
||||
if (!accountEditingIdentity.value) {
|
||||
payload.username = String(accountForm.username).trim();
|
||||
payload.password = accountForm.password;
|
||||
}
|
||||
if (accountEditingIdentity.value) {
|
||||
await resourceApi.update(management.resource, accountEditingIdentity.value, payload);
|
||||
} else {
|
||||
await resourceApi.create(management.resource, payload);
|
||||
}
|
||||
Message.success('账户保存成功');
|
||||
accountFormVisible.value = false;
|
||||
await Promise.all([loadManagedAccounts(), loadAccountCounts()]);
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
} finally {
|
||||
accountSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleAccountStatus(row: Row) {
|
||||
const management = props.definition.accountManagement;
|
||||
if (!management) return;
|
||||
const targetStatus = Number(row.status) === 1 ? 2 : 1;
|
||||
Modal.warning({
|
||||
title: targetStatus === 1 ? '确认启用账户' : '确认禁用账户',
|
||||
content: targetStatus === 1 ? '启用后该账户可以正常使用。' : '禁用后该账户将无法继续使用。',
|
||||
onOk: async () => {
|
||||
try {
|
||||
await resourceApi.updateStatus(management.resource, String(row.identity), targetStatus);
|
||||
Message.success('账户状态已更新');
|
||||
await loadManagedAccounts();
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function archiveAccount(row: Row) {
|
||||
const management = props.definition.accountManagement;
|
||||
if (!management) return;
|
||||
Modal.warning({
|
||||
title: '确认删除账户',
|
||||
content: '删除后该账户将被归档,无法继续登录。',
|
||||
onOk: async () => {
|
||||
try {
|
||||
await resourceApi.archive(management.resource, String(row.identity));
|
||||
Message.success('账户已删除');
|
||||
if (accountList.value.length === 1 && accountPage.value > 1) accountPage.value -= 1;
|
||||
await Promise.all([loadManagedAccounts(), loadAccountCounts()]);
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function changeAccountPage(next: number) {
|
||||
accountPage.value = next;
|
||||
await loadManagedAccounts();
|
||||
}
|
||||
|
||||
function viewCredentials(row: Row) {
|
||||
router.push({
|
||||
name: 'staff-credential',
|
||||
@@ -479,12 +769,57 @@ async function openDetail(row: Row) {
|
||||
props.definition.resource,
|
||||
String(row.identity),
|
||||
);
|
||||
if (props.definition.name === 'gas_basic') gasRejectReason.value = '';
|
||||
detailVisible.value = true;
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function updateGasStatus(enabled: string | number | boolean) {
|
||||
const identity = String(detail.value.identity ?? '');
|
||||
if (!identity) return;
|
||||
const targetStatus = Boolean(enabled) ? 1 : 2;
|
||||
gasStatusSaving.value = true;
|
||||
try {
|
||||
await resourceApi.updateStatus(
|
||||
props.definition.resource,
|
||||
identity,
|
||||
targetStatus,
|
||||
);
|
||||
Message.success('状态修改成功');
|
||||
await Promise.all([openDetail({ identity }), load()]);
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
} finally {
|
||||
gasStatusSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reviewGasStation(approved: boolean) {
|
||||
const identity = String(detail.value.identity ?? '');
|
||||
const reason = gasRejectReason.value.trim();
|
||||
if (!identity) return;
|
||||
if (!approved && !reason) {
|
||||
Message.warning('请填写审核不通过理由');
|
||||
return;
|
||||
}
|
||||
gasReviewSaving.value = true;
|
||||
try {
|
||||
await resourceApi.action(
|
||||
`${props.definition.resource}/${identity}/review`,
|
||||
'POST',
|
||||
{ approved, reason },
|
||||
);
|
||||
Message.success(approved ? '审核已通过' : '审核已拒绝');
|
||||
await Promise.all([openDetail({ identity }), load()]);
|
||||
} catch (error) {
|
||||
Message.error((error as Error).message);
|
||||
} finally {
|
||||
gasReviewSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openDetailAction(action: DetailAction) {
|
||||
activeAction.value = action;
|
||||
for (const field of action.fields ?? []) actionForm[field.key] = undefined;
|
||||
@@ -644,7 +979,7 @@ function formatValue(value: unknown) {
|
||||
|
||||
function fieldLabel(key: string) {
|
||||
const aliases: Record<string, string> = {
|
||||
identity: '业务标识',
|
||||
identity: '标识',
|
||||
created_at: '创建时间',
|
||||
updated_at: '更新时间',
|
||||
version: '版本',
|
||||
@@ -795,6 +1130,39 @@ function optionLabel(option: Row) {
|
||||
.detail-actions {
|
||||
margin-top: 16px;
|
||||
}
|
||||
.account-toolbar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.status-editor {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
padding: 16px;
|
||||
background: var(--color-fill-1);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.status-editor-label {
|
||||
color: var(--color-text-2);
|
||||
font-weight: 500;
|
||||
}
|
||||
.status-switch-label {
|
||||
margin-left: auto;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
.review-panel {
|
||||
margin-top: 12px;
|
||||
padding: 16px;
|
||||
background: var(--color-fill-1);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.review-title {
|
||||
margin-bottom: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.muted-text {
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user