feat(*): 创作平台 - 升级短剧分镜工作流并完善模型计费与界面状态
This commit is contained in:
1 parent
4b75504f75
commit
0558cf4381
33 files changed
+2849
-239
No files matched your search
@@ -260,11 +260,14 @@ func migrations() []tableMigration {
|
|||||||
migrateTable[model.ProjectUnit]("project_units"),
|
migrateTable[model.ProjectUnit]("project_units"),
|
||||||
migrateTable[model.CanvasUnitLink]("canvas_unit_links"),
|
migrateTable[model.CanvasUnitLink]("canvas_unit_links"),
|
||||||
migrateTable[model.Shot]("shots"),
|
migrateTable[model.Shot]("shots"),
|
||||||
|
migrateTable[model.ShotRevision]("shot_revisions"),
|
||||||
|
migrateTable[model.ShotArtifact]("shot_artifacts"),
|
||||||
migrateTable[model.ShotAssetReference]("shot_asset_references"),
|
migrateTable[model.ShotAssetReference]("shot_asset_references"),
|
||||||
migrateTable[model.WorkflowTemplateVersion]("workflow_template_versions"),
|
migrateTable[model.WorkflowTemplateVersion]("workflow_template_versions"),
|
||||||
migrateTable[model.WorkflowInstance]("workflow_instances"),
|
migrateTable[model.WorkflowInstance]("workflow_instances"),
|
||||||
migrateTable[model.WorkflowStepInstance]("workflow_step_instances"),
|
migrateTable[model.WorkflowStepInstance]("workflow_step_instances"),
|
||||||
migrateTable[model.WorkflowStepTask]("workflow_step_tasks"),
|
migrateTable[model.WorkflowStepTask]("workflow_step_tasks"),
|
||||||
|
migrateTable[model.ProductionTaskLink]("production_task_links"),
|
||||||
migrateTable[model.CanvasProject]("canvas_projects"),
|
migrateTable[model.CanvasProject]("canvas_projects"),
|
||||||
migrateTable[model.CanvasShare]("canvas_shares"),
|
migrateTable[model.CanvasShare]("canvas_shares"),
|
||||||
migrateTable[model.PromptTemplate]("prompt_templates"),
|
migrateTable[model.PromptTemplate]("prompt_templates"),
|
||||||
|
|||||||
@@ -62,11 +62,14 @@ func Models() []any {
|
|||||||
&model.ProjectUnit{},
|
&model.ProjectUnit{},
|
||||||
&model.CanvasUnitLink{},
|
&model.CanvasUnitLink{},
|
||||||
&model.Shot{},
|
&model.Shot{},
|
||||||
|
&model.ShotRevision{},
|
||||||
|
&model.ShotArtifact{},
|
||||||
&model.ShotAssetReference{},
|
&model.ShotAssetReference{},
|
||||||
&model.WorkflowTemplateVersion{},
|
&model.WorkflowTemplateVersion{},
|
||||||
&model.WorkflowInstance{},
|
&model.WorkflowInstance{},
|
||||||
&model.WorkflowStepInstance{},
|
&model.WorkflowStepInstance{},
|
||||||
&model.WorkflowStepTask{},
|
&model.WorkflowStepTask{},
|
||||||
|
&model.ProductionTaskLink{},
|
||||||
&model.CanvasProject{},
|
&model.CanvasProject{},
|
||||||
&model.CanvasShare{},
|
&model.CanvasShare{},
|
||||||
&model.PromptTemplate{},
|
&model.PromptTemplate{},
|
||||||
|
|||||||
@@ -678,6 +678,25 @@ func RegisterProjectRoutes(r *gin.RouterGroup, svc *service.Service) {
|
|||||||
}
|
}
|
||||||
ok(c, gin.H{"shots": shots})
|
ok(c, gin.H{"shots": shots})
|
||||||
})
|
})
|
||||||
|
r.POST("/projects/:id/shots/:shotId/revisions", func(c *gin.Context) {
|
||||||
|
user, err := currentUser(c, svc)
|
||||||
|
if err != nil {
|
||||||
|
failService(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 256<<10)
|
||||||
|
var req service.ShotRevisionInput
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
fail(c, http.StatusBadRequest, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
shot, revision, err := svc.CreateShotRevision(user.ID, c.Param("id"), c.Param("shotId"), req)
|
||||||
|
if err != nil {
|
||||||
|
failService(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ok(c, gin.H{"shot": shot, "revision": revision})
|
||||||
|
})
|
||||||
r.POST("/projects/:id/shots/:shotId/assets", func(c *gin.Context) {
|
r.POST("/projects/:id/shots/:shotId/assets", func(c *gin.Context) {
|
||||||
user, err := currentUser(c, svc)
|
user, err := currentUser(c, svc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -203,16 +203,56 @@ type CanvasUnitLink struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Shot struct {
|
type Shot struct {
|
||||||
ID string `json:"id" gorm:"primaryKey;size:36"`
|
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||||
ProjectID string `json:"projectId" gorm:"index;size:36"`
|
ProjectID string `json:"projectId" gorm:"index;size:36"`
|
||||||
UnitID string `json:"unitId" gorm:"index;size:36"`
|
UnitID string `json:"unitId" gorm:"index;size:36"`
|
||||||
Title string `json:"title" gorm:"size:240"`
|
CurrentRevisionID string `json:"currentRevisionId,omitempty" gorm:"index;size:36"`
|
||||||
Description string `json:"description" gorm:"type:text"`
|
Title string `json:"title" gorm:"size:240"`
|
||||||
Position int `json:"position"`
|
Description string `json:"description" gorm:"type:text"`
|
||||||
DurationMs int64 `json:"durationMs"`
|
Position int `json:"position"`
|
||||||
Status string `json:"status" gorm:"index;size:24"`
|
DurationMs int64 `json:"durationMs"`
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
Status string `json:"status" gorm:"index;size:24"`
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShotRevision 保存可复现的分镜脚本版本;Shot 只保留稳定身份、排序和当前版本指针。
|
||||||
|
type ShotRevision struct {
|
||||||
|
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||||
|
ShotID string `json:"shotId" gorm:"index;size:36;uniqueIndex:idx_shot_revisions_version,priority:1"`
|
||||||
|
Version int `json:"version" gorm:"uniqueIndex:idx_shot_revisions_version,priority:2"`
|
||||||
|
PlotDescription string `json:"plotDescription" gorm:"type:text"`
|
||||||
|
Action string `json:"action" gorm:"type:text"`
|
||||||
|
Dialogue string `json:"dialogue" gorm:"type:text"`
|
||||||
|
ShotSize string `json:"shotSize" gorm:"size:80"`
|
||||||
|
CameraAngle string `json:"cameraAngle" gorm:"size:80"`
|
||||||
|
CameraMovement string `json:"cameraMovement" gorm:"size:120"`
|
||||||
|
DurationMs int64 `json:"durationMs"`
|
||||||
|
ImagePrompt string `json:"imagePrompt" gorm:"type:text"`
|
||||||
|
VideoPrompt string `json:"videoPrompt" gorm:"type:text"`
|
||||||
|
NegativePrompt string `json:"negativePrompt" gorm:"type:text"`
|
||||||
|
ContinuityNotes string `json:"continuityNotes" gorm:"type:text"`
|
||||||
|
ActionBeatsJSON string `json:"actionBeatsJson" gorm:"type:text"`
|
||||||
|
CreatedBy string `json:"createdBy,omitempty" gorm:"index;size:36"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShotArtifact 是镜头的版本化生产产物。修改分镜或资产引用时只标记 stale,不删除历史。
|
||||||
|
type ShotArtifact struct {
|
||||||
|
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||||
|
ProjectID string `json:"projectId" gorm:"index;size:36"`
|
||||||
|
UnitID string `json:"unitId" gorm:"index;size:36"`
|
||||||
|
ShotID string `json:"shotId" gorm:"index;size:36;uniqueIndex:idx_shot_artifacts_version,priority:1"`
|
||||||
|
RevisionID string `json:"revisionId,omitempty" gorm:"index;size:36"`
|
||||||
|
TaskID string `json:"taskId,omitempty" gorm:"index;size:36"`
|
||||||
|
Type string `json:"type" gorm:"index;size:40;uniqueIndex:idx_shot_artifacts_version,priority:2"`
|
||||||
|
Version int `json:"version" gorm:"uniqueIndex:idx_shot_artifacts_version,priority:3"`
|
||||||
|
ResourceID string `json:"resourceId,omitempty" gorm:"index;size:36"`
|
||||||
|
Status string `json:"status" gorm:"index;size:24"`
|
||||||
|
Selected bool `json:"selected" gorm:"index"`
|
||||||
|
MetadataJSON string `json:"metadataJson" gorm:"type:text"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShotAssetReference struct {
|
type ShotAssetReference struct {
|
||||||
@@ -268,6 +308,20 @@ type WorkflowStepTask struct {
|
|||||||
CreatedAt time.Time `json:"createdAt"`
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProductionTaskLink 显式区分领域项目、画布和镜头上下文,避免继续复用 Task.ProjectID 表达多种身份。
|
||||||
|
type ProductionTaskLink struct {
|
||||||
|
ID string `json:"id" gorm:"primaryKey;size:36"`
|
||||||
|
TaskID string `json:"taskId" gorm:"index;size:36;uniqueIndex:idx_production_task_context,priority:1"`
|
||||||
|
ProjectID string `json:"projectId" gorm:"index;size:36"`
|
||||||
|
CanvasID string `json:"canvasId,omitempty" gorm:"index;size:80"`
|
||||||
|
UnitID string `json:"unitId,omitempty" gorm:"index;size:36"`
|
||||||
|
ShotID string `json:"shotId,omitempty" gorm:"index;size:36;uniqueIndex:idx_production_task_context,priority:2"`
|
||||||
|
WorkflowStepID string `json:"workflowStepId,omitempty" gorm:"index;size:36"`
|
||||||
|
ArtifactType string `json:"artifactType,omitempty" gorm:"index;size:40;uniqueIndex:idx_production_task_context,priority:3"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
type CanvasProject struct {
|
type CanvasProject struct {
|
||||||
ID string `json:"id" gorm:"primaryKey;size:80"`
|
ID string `json:"id" gorm:"primaryKey;size:80"`
|
||||||
UserID string `json:"userId" gorm:"index;size:36;index:idx_canvas_projects_user_updated,priority:1"`
|
UserID string `json:"userId" gorm:"index;size:36;index:idx_canvas_projects_user_updated,priority:1"`
|
||||||
|
|||||||
@@ -1154,6 +1154,15 @@ func (r *Repository) DeleteProject(userID string, id string, canvasUpdates []mod
|
|||||||
return fmt.Errorf("项目删除时仍有 %d 个画布关联未处理", remainingCanvasCount)
|
return fmt.Errorf("项目删除时仍有 %d 个画布关联未处理", remainingCanvasCount)
|
||||||
}
|
}
|
||||||
shotIDs := tx.Model(&model.Shot{}).Select("id").Where("project_id = ?", id)
|
shotIDs := tx.Model(&model.Shot{}).Select("id").Where("project_id = ?", id)
|
||||||
|
if err := tx.Where("project_id = ?", id).Delete(&model.ProductionTaskLink{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("project_id = ?", id).Delete(&model.ShotArtifact{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotRevision{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotAssetReference{}).Error; err != nil {
|
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotAssetReference{}).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1253,10 +1262,27 @@ func (r *Repository) ProjectUnit(projectID string, id string) (*model.ProjectUni
|
|||||||
return &unit, nil
|
return &unit, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) UpdateProjectUnit(unit *model.ProjectUnit) error {
|
func (r *Repository) UpdateProjectUnit(unit *model.ProjectUnit, invalidateWorkflow bool) error {
|
||||||
return r.db.Model(&model.ProjectUnit{}).Where("id = ? AND project_id = ?", unit.ID, unit.ProjectID).Updates(map[string]any{
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
"parent_id": unit.ParentID, "title": unit.Title, "source_text": unit.SourceText, "status": unit.Status, "position": unit.Position, "updated_at": unit.UpdatedAt,
|
result := tx.Model(&model.ProjectUnit{}).Where("id = ? AND project_id = ?", unit.ID, unit.ProjectID).Updates(map[string]any{
|
||||||
}).Error
|
"parent_id": unit.ParentID, "title": unit.Title, "source_text": unit.SourceText, "status": unit.Status, "position": unit.Position, "updated_at": unit.UpdatedAt,
|
||||||
|
})
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected != 1 {
|
||||||
|
return gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
if invalidateWorkflow {
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("project_id = ? AND unit_id = ? AND status NOT IN ?", unit.ProjectID, unit.ID, []string{"failed", "stale"}).Updates(map[string]any{"status": "stale", "selected": false, "updated_at": unit.UpdatedAt}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := invalidateUnitWorkflowTx(tx, unit.ProjectID, unit.ID, "story", unit.UpdatedAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Model(&model.Project{}).Where("id = ?", unit.ProjectID).Updates(map[string]any{"revision": gorm.Expr("revision + 1"), "updated_at": unit.UpdatedAt}).Error
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) DeleteProjectUnit(projectID string, id string) error {
|
func (r *Repository) DeleteProjectUnit(projectID string, id string) error {
|
||||||
@@ -1265,6 +1291,15 @@ func (r *Repository) DeleteProjectUnit(projectID string, id string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
shotIDs := tx.Model(&model.Shot{}).Select("id").Where("project_id = ? AND unit_id = ?", projectID, id)
|
shotIDs := tx.Model(&model.Shot{}).Select("id").Where("project_id = ? AND unit_id = ?", projectID, id)
|
||||||
|
if err := tx.Where("project_id = ? AND unit_id = ?", projectID, id).Delete(&model.ProductionTaskLink{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("project_id = ? AND unit_id = ?", projectID, id).Delete(&model.ShotArtifact{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotRevision{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotAssetReference{}).Error; err != nil {
|
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotAssetReference{}).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1609,9 +1644,61 @@ func (r *Repository) SaveShot(shot *model.Shot, create bool) error {
|
|||||||
}).Error
|
}).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) ReplaceProjectUnitShots(projectID string, unitID string, shots []model.Shot) error {
|
// SaveShotWithRevision 原子保存镜头当前值、新版本和下游失效状态。
|
||||||
|
func (r *Repository) SaveShotWithRevision(shot *model.Shot, revision *model.ShotRevision, create bool) error {
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if create {
|
||||||
|
if err := tx.Create(shot).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result := tx.Model(&model.Shot{}).Where("id = ? AND project_id = ?", shot.ID, shot.ProjectID).Updates(map[string]any{
|
||||||
|
"unit_id": shot.UnitID, "title": shot.Title, "description": shot.Description, "position": shot.Position,
|
||||||
|
"duration_ms": shot.DurationMs, "status": shot.Status, "updated_at": shot.UpdatedAt,
|
||||||
|
})
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected != 1 {
|
||||||
|
return gorm.ErrRecordNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var currentVersion int
|
||||||
|
if err := tx.Model(&model.ShotRevision{}).Where("shot_id = ?", shot.ID).Select("COALESCE(MAX(version), 0)").Scan(¤tVersion).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
revision.Version = currentVersion + 1
|
||||||
|
if err := tx.Create(revision).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
shot.CurrentRevisionID = revision.ID
|
||||||
|
if err := tx.Model(&model.Shot{}).Where("id = ? AND project_id = ?", shot.ID, shot.ProjectID).Updates(map[string]any{
|
||||||
|
"current_revision_id": revision.ID, "description": shot.Description, "duration_ms": shot.DurationMs,
|
||||||
|
"status": shot.Status, "updated_at": shot.UpdatedAt,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !create {
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("shot_id = ? AND status NOT IN ?", shot.ID, []string{"failed", "stale"}).Updates(map[string]any{"status": "stale", "selected": false, "updated_at": shot.UpdatedAt}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := invalidateUnitWorkflowTx(tx, shot.ProjectID, shot.UnitID, "storyboard", shot.UpdatedAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(&model.Project{}).Where("id = ?", shot.ProjectID).Updates(map[string]any{"revision": gorm.Expr("revision + 1"), "updated_at": shot.UpdatedAt}).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ReplaceProjectUnitShots(projectID string, unitID string, shots []model.Shot, revisions []model.ShotRevision) error {
|
||||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
shotIDs := tx.Model(&model.Shot{}).Select("id").Where("project_id = ? AND unit_id = ?", projectID, unitID)
|
shotIDs := tx.Model(&model.Shot{}).Select("id").Where("project_id = ? AND unit_id = ?", projectID, unitID)
|
||||||
|
if err := tx.Where("project_id = ? AND unit_id = ?", projectID, unitID).Delete(&model.ShotArtifact{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotRevision{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotAssetReference{}).Error; err != nil {
|
if err := tx.Where("shot_id IN (?)", shotIDs).Delete(&model.ShotAssetReference{}).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1624,6 +1711,14 @@ func (r *Repository) ReplaceProjectUnitShots(projectID string, unitID string, sh
|
|||||||
if err := tx.Create(&shots).Error; err != nil {
|
if err := tx.Create(&shots).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if len(revisions) > 0 {
|
||||||
|
if err := tx.Create(&revisions).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := invalidateUnitWorkflowTx(tx, projectID, unitID, "storyboard", time.Now()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return tx.Model(&model.Project{}).Where("id = ?", projectID).Updates(map[string]any{"revision": gorm.Expr("revision + 1"), "updated_at": time.Now()}).Error
|
return tx.Model(&model.Project{}).Where("id = ?", projectID).Updates(map[string]any{"revision": gorm.Expr("revision + 1"), "updated_at": time.Now()}).Error
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1636,6 +1731,48 @@ func (r *Repository) ShotForProject(projectID string, shotID string) (*model.Sho
|
|||||||
return &shot, nil
|
return &shot, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ProjectShotRevisions(projectID string) ([]model.ShotRevision, error) {
|
||||||
|
var revisions []model.ShotRevision
|
||||||
|
err := r.db.Table("shot_revisions").Select("shot_revisions.*").
|
||||||
|
Joins("JOIN shots ON shots.id = shot_revisions.shot_id").
|
||||||
|
Where("shots.project_id = ?", projectID).
|
||||||
|
Order("shots.unit_id asc, shots.position asc, shot_revisions.version asc").Scan(&revisions).Error
|
||||||
|
return revisions, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ProjectShotArtifacts(projectID string) ([]model.ShotArtifact, error) {
|
||||||
|
var artifacts []model.ShotArtifact
|
||||||
|
err := r.db.Where("project_id = ?", projectID).Order("unit_id asc, shot_id asc, type asc, version asc").Find(&artifacts).Error
|
||||||
|
return artifacts, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) CreateShotArtifact(artifact *model.ShotArtifact) error {
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var currentVersion int
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("shot_id = ? AND type = ?", artifact.ShotID, artifact.Type).Select("COALESCE(MAX(version), 0)").Scan(¤tVersion).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
artifact.Version = currentVersion + 1
|
||||||
|
if artifact.Selected {
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("shot_id = ? AND type = ?", artifact.ShotID, artifact.Type).Updates(map[string]any{"selected": false, "updated_at": artifact.UpdatedAt}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Create(artifact).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) MarkShotArtifactsStale(shotID string, updatedAt time.Time) error {
|
||||||
|
return r.db.Model(&model.ShotArtifact{}).Where("shot_id = ? AND status NOT IN ?", shotID, []string{"failed", "stale"}).Updates(map[string]any{"status": "stale", "selected": false, "updated_at": updatedAt}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) UpsertProductionTaskLink(link *model.ProductionTaskLink) error {
|
||||||
|
return r.db.Where("task_id = ? AND shot_id = ? AND artifact_type = ?", link.TaskID, link.ShotID, link.ArtifactType).Assign(map[string]any{
|
||||||
|
"project_id": link.ProjectID, "canvas_id": link.CanvasID, "unit_id": link.UnitID, "shot_id": link.ShotID,
|
||||||
|
"workflow_step_id": link.WorkflowStepID, "artifact_type": link.ArtifactType, "updated_at": link.UpdatedAt,
|
||||||
|
}).FirstOrCreate(link).Error
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Repository) UpsertShotAssetReference(reference *model.ShotAssetReference) error {
|
func (r *Repository) UpsertShotAssetReference(reference *model.ShotAssetReference) error {
|
||||||
result := r.db.Model(&model.ShotAssetReference{}).Where("shot_id = ? AND asset_version_id = ? AND role = ?", reference.ShotID, reference.AssetVersionID, reference.Role).Updates(map[string]any{"status": reference.Status})
|
result := r.db.Model(&model.ShotAssetReference{}).Where("shot_id = ? AND asset_version_id = ? AND role = ?", reference.ShotID, reference.AssetVersionID, reference.Role).Updates(map[string]any{"status": reference.Status})
|
||||||
if result.Error != nil || result.RowsAffected > 0 {
|
if result.Error != nil || result.RowsAffected > 0 {
|
||||||
@@ -1644,6 +1781,75 @@ func (r *Repository) UpsertShotAssetReference(reference *model.ShotAssetReferenc
|
|||||||
return r.db.Create(reference).Error
|
return r.db.Create(reference).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *Repository) UpsertShotAssetReferenceAndInvalidate(projectID string, reference *model.ShotAssetReference, updatedAt time.Time) error {
|
||||||
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
result := tx.Model(&model.ShotAssetReference{}).Where("shot_id = ? AND asset_version_id = ? AND role = ?", reference.ShotID, reference.AssetVersionID, reference.Role).Updates(map[string]any{"status": reference.Status})
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected == 0 {
|
||||||
|
if err := tx.Create(reference).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("shot_id = ? AND status NOT IN ?", reference.ShotID, []string{"failed", "stale"}).Updates(map[string]any{"status": "stale", "selected": false, "updated_at": updatedAt}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var shot model.Shot
|
||||||
|
if err := tx.First(&shot, "id = ? AND project_id = ?", reference.ShotID, projectID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := invalidateUnitWorkflowTx(tx, projectID, shot.UnitID, "storyboard", updatedAt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Model(&model.Project{}).Where("id = ?", projectID).Updates(map[string]any{"revision": gorm.Expr("revision + 1"), "updated_at": updatedAt}).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func invalidateUnitWorkflowTx(tx *gorm.DB, projectID string, unitID string, fromStepKey string, updatedAt time.Time) error {
|
||||||
|
if strings.TrimSpace(unitID) == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var instances []model.WorkflowInstance
|
||||||
|
if err := tx.Where("project_id = ? AND unit_id = ?", projectID, unitID).Find(&instances).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, instance := range instances {
|
||||||
|
var steps []model.WorkflowStepInstance
|
||||||
|
if err := tx.Where("workflow_instance_id = ?", instance.ID).Order("position asc").Find(&steps).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fromPosition := -1
|
||||||
|
for _, step := range steps {
|
||||||
|
if step.StepKey == fromStepKey {
|
||||||
|
fromPosition = step.Position
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fromPosition < 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, step := range steps {
|
||||||
|
if step.Position < fromPosition {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status := model.WorkflowStepStatusPending
|
||||||
|
if step.Position == fromPosition {
|
||||||
|
status = model.WorkflowStepStatusRunning
|
||||||
|
}
|
||||||
|
if err := tx.Model(&model.WorkflowStepInstance{}).Where("id = ? AND workflow_instance_id = ?", step.ID, instance.ID).Updates(map[string]any{
|
||||||
|
"status": status, "error": "", "completed_at": nil, "updated_at": updatedAt,
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Model(&model.WorkflowInstance{}).Where("id = ?", instance.ID).Updates(map[string]any{"status": model.WorkflowStatusActive, "revision": gorm.Expr("revision + 1"), "updated_at": updatedAt}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Repository) ProjectShotAssetReferences(projectID string) ([]model.ShotAssetReference, error) {
|
func (r *Repository) ProjectShotAssetReferences(projectID string) ([]model.ShotAssetReference, error) {
|
||||||
var references []model.ShotAssetReference
|
var references []model.ShotAssetReference
|
||||||
err := r.db.Table("shot_asset_references").Select("shot_asset_references.*").
|
err := r.db.Table("shot_asset_references").Select("shot_asset_references.*").
|
||||||
@@ -1802,7 +2008,7 @@ func (r *Repository) UpdateWorkflowProgress(step *model.WorkflowStepInstance, ne
|
|||||||
}
|
}
|
||||||
|
|
||||||
// RegisterWorkflowTaskOutput 将成功任务、流程步骤和产物表示写入同一事务,重复回填使用任务与用途唯一键幂等。
|
// RegisterWorkflowTaskOutput 将成功任务、流程步骤和产物表示写入同一事务,重复回填使用任务与用途唯一键幂等。
|
||||||
func (r *Repository) RegisterWorkflowTaskOutput(step *model.WorkflowStepInstance, next *model.WorkflowStepInstance, instance *model.WorkflowInstance, projectID string, link *model.WorkflowStepTask, representation *model.AssetRepresentation) error {
|
func (r *Repository) RegisterWorkflowTaskOutput(step *model.WorkflowStepInstance, next *model.WorkflowStepInstance, instance *model.WorkflowInstance, projectID string, link *model.WorkflowStepTask, representation *model.AssetRepresentation, productionLink *model.ProductionTaskLink, artifact *model.ShotArtifact) error {
|
||||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||||
if err := tx.Where("workflow_step_id = ? AND task_id = ?", link.WorkflowStepID, link.TaskID).FirstOrCreate(link).Error; err != nil {
|
if err := tx.Where("workflow_step_id = ? AND task_id = ?", link.WorkflowStepID, link.TaskID).FirstOrCreate(link).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -1812,6 +2018,29 @@ func (r *Repository) RegisterWorkflowTaskOutput(step *model.WorkflowStepInstance
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if productionLink != nil {
|
||||||
|
if err := tx.Where("task_id = ? AND shot_id = ? AND artifact_type = ?", productionLink.TaskID, productionLink.ShotID, productionLink.ArtifactType).Assign(map[string]any{
|
||||||
|
"project_id": productionLink.ProjectID, "canvas_id": productionLink.CanvasID, "unit_id": productionLink.UnitID, "shot_id": productionLink.ShotID,
|
||||||
|
"workflow_step_id": productionLink.WorkflowStepID, "artifact_type": productionLink.ArtifactType, "updated_at": productionLink.UpdatedAt,
|
||||||
|
}).FirstOrCreate(productionLink).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if artifact != nil {
|
||||||
|
var currentVersion int
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("shot_id = ? AND type = ?", artifact.ShotID, artifact.Type).Select("COALESCE(MAX(version), 0)").Scan(¤tVersion).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
artifact.Version = currentVersion + 1
|
||||||
|
if artifact.Selected {
|
||||||
|
if err := tx.Model(&model.ShotArtifact{}).Where("shot_id = ? AND type = ?", artifact.ShotID, artifact.Type).Updates(map[string]any{"selected": false, "updated_at": artifact.UpdatedAt}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Create(artifact).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
stepResult := tx.Model(&model.WorkflowStepInstance{}).Where("id = ? AND workflow_instance_id = ?", step.ID, step.WorkflowInstanceID).Updates(map[string]any{
|
stepResult := tx.Model(&model.WorkflowStepInstance{}).Where("id = ? AND workflow_instance_id = ?", step.ID, step.WorkflowInstanceID).Updates(map[string]any{
|
||||||
"status": step.Status, "output_json": step.OutputJSON, "error": step.Error, "started_at": step.StartedAt,
|
"status": step.Status, "output_json": step.OutputJSON, "error": step.Error, "started_at": step.StartedAt,
|
||||||
"completed_at": step.CompletedAt, "updated_at": step.UpdatedAt,
|
"completed_at": step.CompletedAt, "updated_at": step.UpdatedAt,
|
||||||
|
|||||||
@@ -161,6 +161,19 @@ func (r *Repository) ResourceReferenceSnapshot(userID string, excludingAssetID s
|
|||||||
snapshot.Documents = append(snapshot.Documents, ResourceReferenceDocument{Kind: "工作流", ID: step.ID, Title: step.Title, PrimaryJSON: step.PrimaryJSON, SecondaryJSON: step.SecondaryJSON})
|
snapshot.Documents = append(snapshot.Documents, ResourceReferenceDocument{Kind: "工作流", ID: step.ID, Title: step.Title, PrimaryJSON: step.PrimaryJSON, SecondaryJSON: step.SecondaryJSON})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var shotArtifacts []joinedDocument
|
||||||
|
artifactDocumentQuery := r.db.Table("shot_artifacts").
|
||||||
|
Select("shot_artifacts.id, shots.title, shot_artifacts.metadata_json AS primary_json").
|
||||||
|
Joins("JOIN shots ON shots.id = shot_artifacts.shot_id").
|
||||||
|
Joins("JOIN projects ON projects.id = shots.project_id").
|
||||||
|
Where("projects.user_id = ?", userID)
|
||||||
|
if err := artifactDocumentQuery.Scan(&shotArtifacts).Error; err != nil {
|
||||||
|
return snapshot, err
|
||||||
|
}
|
||||||
|
for _, artifact := range shotArtifacts {
|
||||||
|
snapshot.Documents = append(snapshot.Documents, ResourceReferenceDocument{Kind: "镜头产物", ID: artifact.ID, Title: artifact.Title, PrimaryJSON: artifact.PrimaryJSON})
|
||||||
|
}
|
||||||
|
|
||||||
type joinedRepresentation struct {
|
type joinedRepresentation struct {
|
||||||
ID string
|
ID string
|
||||||
Title string
|
Title string
|
||||||
@@ -186,6 +199,24 @@ func (r *Repository) ResourceReferenceSnapshot(userID string, excludingAssetID s
|
|||||||
for _, voice := range voices {
|
for _, voice := range voices {
|
||||||
snapshot.Direct = append(snapshot.Direct, ResourceDirectReference{Kind: "声音", ID: voice.ID, Title: voice.Name, ResourceID: voice.SampleResourceID})
|
snapshot.Direct = append(snapshot.Direct, ResourceDirectReference{Kind: "声音", ID: voice.ID, Title: voice.Name, ResourceID: voice.SampleResourceID})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type joinedShotArtifact struct {
|
||||||
|
ID string
|
||||||
|
Title string
|
||||||
|
ResourceID string
|
||||||
|
}
|
||||||
|
var artifacts []joinedShotArtifact
|
||||||
|
if err := r.db.Table("shot_artifacts").
|
||||||
|
Select("shot_artifacts.id, shots.title, shot_artifacts.resource_id").
|
||||||
|
Joins("JOIN shots ON shots.id = shot_artifacts.shot_id").
|
||||||
|
Joins("JOIN projects ON projects.id = shots.project_id").
|
||||||
|
Where("projects.user_id = ? AND shot_artifacts.resource_id IN ?", userID, resourceIDs).
|
||||||
|
Scan(&artifacts).Error; err != nil {
|
||||||
|
return snapshot, err
|
||||||
|
}
|
||||||
|
for _, artifact := range artifacts {
|
||||||
|
snapshot.Direct = append(snapshot.Direct, ResourceDirectReference{Kind: "镜头产物", ID: artifact.ID, Title: artifact.Title, ResourceID: artifact.ResourceID})
|
||||||
|
}
|
||||||
return snapshot, nil
|
return snapshot, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ func TestCustomChannelTaskInputRequiresFeature(t *testing.T) {
|
|||||||
func TestCreateTaskDoesNotClassifyCustomChannelAsMissingSystemModel(t *testing.T) {
|
func TestCreateTaskDoesNotClassifyCustomChannelAsMissingSystemModel(t *testing.T) {
|
||||||
svc, _ := newFeatureAvailabilityTestService(t)
|
svc, _ := newFeatureAvailabilityTestService(t)
|
||||||
actor := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
|
actor := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
|
||||||
if _, err := svc.UpdateFeatureAvailability(actor, FeatureAvailability{ShortDramaEnabled: true, TaskCenterEnabled: true, CreditsEnabled: true, CustomChannelsEnabled: false}); err != nil {
|
if _, err := svc.UpdateFeatureAvailability(actor, FeatureAvailability{ShortDramaEnabled: true, TaskCenterEnabled: true, CreditsEnabled: true, CustomChannelsEnabled: false, FrontendModelsEnabled: true}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -452,7 +452,9 @@ func (s *Service) taskBillingOrder(userID string, task *model.Task, input map[st
|
|||||||
capability = capabilityFromTaskType(task.Type)
|
capability = capabilityFromTaskType(task.Type)
|
||||||
}
|
}
|
||||||
scene := firstNonEmpty(strings.TrimSpace(task.Operation), task.Type)
|
scene := firstNonEmpty(strings.TrimSpace(task.Operation), task.Type)
|
||||||
return s.newBillingOrder(userID, task.ID, "task:"+task.ID+":"+newID(), channelID, modelKey, capability, scene, billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability))
|
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
|
||||||
|
priceTierID, _ := config["priceTierId"].(string)
|
||||||
|
return s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelID, modelKey, capability, scene, billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability), strings.TrimSpace(priceTierID), intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, input map[string]any) (*model.BillingOrder, error) {
|
func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, input map[string]any) (*model.BillingOrder, error) {
|
||||||
@@ -474,7 +476,9 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
|
|||||||
capability = capabilityFromTaskType(task.Type)
|
capability = capabilityFromTaskType(task.Type)
|
||||||
}
|
}
|
||||||
if logicalModel.PricePolicy == "channel" {
|
if logicalModel.PricePolicy == "channel" {
|
||||||
order, priceErr := s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelModel.ChannelID, channelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability), strings.TrimSpace(fmt.Sprint(config["priceTierId"])))
|
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
|
||||||
|
priceTierID, _ := config["priceTierId"].(string)
|
||||||
|
order, priceErr := s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelModel.ChannelID, channelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability), strings.TrimSpace(priceTierID), intent)
|
||||||
if priceErr != nil {
|
if priceErr != nil {
|
||||||
return nil, priceErr
|
return nil, priceErr
|
||||||
}
|
}
|
||||||
@@ -560,7 +564,7 @@ func (s *Service) newBillingOrder(userID string, taskID string, idempotencyKey s
|
|||||||
return s.newBillingOrderWithPriceTier(userID, taskID, idempotencyKey, channelID, modelKey, capability, scene, requestedQuantity, tokenEstimate, "")
|
return s.newBillingOrderWithPriceTier(userID, taskID, idempotencyKey, channelID, modelKey, capability, scene, requestedQuantity, tokenEstimate, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, idempotencyKey string, channelID string, modelKey string, capability string, scene string, requestedQuantity int64, tokenEstimate tokenBillingEstimate, priceTierID string) (*model.BillingOrder, error) {
|
func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, idempotencyKey string, channelID string, modelKey string, capability string, scene string, requestedQuantity int64, tokenEstimate tokenBillingEstimate, priceTierID string, intents ...ModelRequestIntent) (*model.BillingOrder, error) {
|
||||||
item, err := s.repo.ChannelModelByKey(channelID, modelKey)
|
item, err := s.repo.ChannelModelByKey(channelID, modelKey)
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return nil, BadAuthRequest("当前模型暂时不可用,请重新选择")
|
return nil, BadAuthRequest("当前模型暂时不可用,请重新选择")
|
||||||
@@ -568,7 +572,7 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tier := channelModelPriceTierForBilling(*item, priceTierID, capability)
|
tier := channelModelPriceTierForBilling(*item, priceTierID, capability, intents...)
|
||||||
if tier == nil {
|
if tier == nil {
|
||||||
return nil, BadAuthRequest("当前模型尚未配置所选规格的用户积分价格")
|
return nil, BadAuthRequest("当前模型尚未配置所选规格的用户积分价格")
|
||||||
}
|
}
|
||||||
@@ -625,7 +629,7 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func channelModelPriceTierForBilling(channelModel model.ChannelModel, priceTierID string, capability string) *model.ChannelModelPriceTier {
|
func channelModelPriceTierForBilling(channelModel model.ChannelModel, priceTierID string, capability string, intents ...ModelRequestIntent) *model.ChannelModelPriceTier {
|
||||||
if priceTierID != "" {
|
if priceTierID != "" {
|
||||||
for index := range channelModel.PriceTiers {
|
for index := range channelModel.PriceTiers {
|
||||||
tier := &channelModel.PriceTiers[index]
|
tier := &channelModel.PriceTiers[index]
|
||||||
@@ -635,6 +639,13 @@ func channelModelPriceTierForBilling(channelModel model.ChannelModel, priceTierI
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
if len(intents) > 0 {
|
||||||
|
intent := intents[0]
|
||||||
|
if normalizeCapability(intent.Capability) == "" {
|
||||||
|
intent.Capability = capability
|
||||||
|
}
|
||||||
|
return channelModelPriceTierForIntent(channelModel, intent)
|
||||||
|
}
|
||||||
return channelModelPriceTierForIntent(channelModel, ModelRequestIntent{Capability: capability, Options: map[string]any{}})
|
return channelModelPriceTierForIntent(channelModel, ModelRequestIntent{Capability: capability, Options: map[string]any{}})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"infinite-canvas/backend/internal/model"
|
||||||
|
"infinite-canvas/backend/internal/repository"
|
||||||
|
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTaskBillingOrderMatchesSystemImagePriceTierFromRequestedSpec(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open("file:"+newID()+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&model.SystemSetting{}, &model.ChannelModel{}, &model.ChannelModelPriceTier{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
channelModel := model.ChannelModel{
|
||||||
|
ID: "channel-model-1", ChannelID: "channel-1", ModelKey: "gpt-image-2", ProviderModelKey: "gpt-image-2",
|
||||||
|
Capability: "image", Protocol: model.ChannelInterfaceOpenAIImage, BillingMode: "fixed_request",
|
||||||
|
PriceConfigured: true, Enabled: true, PriceVersion: 1,
|
||||||
|
}
|
||||||
|
if err := db.Create(&channelModel).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
tier := model.ChannelModelPriceTier{
|
||||||
|
ID: "tier-2k", ChannelModelID: channelModel.ID, SelectorKey: `{"quality":"2k"}`, SelectorJSON: `{"quality":"2k"}`,
|
||||||
|
Resolution: "*", ProviderModelKey: channelModel.ProviderModelKey, BillingMode: "fixed_request",
|
||||||
|
UnitPriceMicrocredits: 4_000_000, PriceConfigured: true, Enabled: true, PriceVersion: 1,
|
||||||
|
}
|
||||||
|
if err := db.Create(&tier).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := New(repository.New(db), t.TempDir())
|
||||||
|
order, err := svc.taskBillingOrder("user-1", &model.Task{ID: "task-1", Type: "canvas_image", Operation: "image"}, map[string]any{
|
||||||
|
"mode": "image",
|
||||||
|
"config": map[string]any{
|
||||||
|
"channelId": "channel-1",
|
||||||
|
"model": "gpt-image-2",
|
||||||
|
"quality": "2K",
|
||||||
|
"size": "*",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("taskBillingOrder() error = %v", err)
|
||||||
|
}
|
||||||
|
if order == nil || order.PriceTierID != tier.ID || order.AmountMicrocredits != tier.UnitPriceMicrocredits {
|
||||||
|
t.Fatalf("taskBillingOrder() = %#v, want tier %s", order, tier.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1086,7 +1086,8 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
|
|||||||
if capability == "" {
|
if capability == "" {
|
||||||
capability = capabilityFromTaskType(task.Type)
|
capability = capabilityFromTaskType(task.Type)
|
||||||
}
|
}
|
||||||
replacement, err = s.newBillingOrderWithPriceTier(task.UserID, task.ID, "route-switch:"+task.ID+":"+selected.Route.ID, selected.ChannelModel.ChannelID, selected.ChannelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(nextInput, capability), strings.TrimSpace(fmt.Sprint(config["priceTierId"])))
|
priceTierID, _ := config["priceTierId"].(string)
|
||||||
|
replacement, err = s.newBillingOrderWithPriceTier(task.UserID, task.ID, "route-switch:"+task.ID+":"+selected.Route.ID, selected.ChannelModel.ChannelID, selected.ChannelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(nextInput, capability), strings.TrimSpace(priceTierID), intent)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ type ProjectDetail struct {
|
|||||||
AssetFolders []model.ProjectAssetFolder `json:"assetFolders"`
|
AssetFolders []model.ProjectAssetFolder `json:"assetFolders"`
|
||||||
Workflows []ProjectWorkflowDetail `json:"workflows"`
|
Workflows []ProjectWorkflowDetail `json:"workflows"`
|
||||||
Shots []model.Shot `json:"shots"`
|
Shots []model.Shot `json:"shots"`
|
||||||
|
ShotRevisions []model.ShotRevision `json:"shotRevisions"`
|
||||||
|
ShotArtifacts []model.ShotArtifact `json:"shotArtifacts"`
|
||||||
ShotReferences []model.ShotAssetReference `json:"shotReferences"`
|
ShotReferences []model.ShotAssetReference `json:"shotReferences"`
|
||||||
AssetCandidates []model.ProjectAssetCandidate `json:"assetCandidates"`
|
AssetCandidates []model.ProjectAssetCandidate `json:"assetCandidates"`
|
||||||
}
|
}
|
||||||
@@ -177,6 +179,14 @@ func (s *Service) ProjectDetail(userID string, id string) (ProjectDetail, error)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return ProjectDetail{}, err
|
return ProjectDetail{}, err
|
||||||
}
|
}
|
||||||
|
shotRevisions, err := s.repo.ProjectShotRevisions(project.ID)
|
||||||
|
if err != nil {
|
||||||
|
return ProjectDetail{}, err
|
||||||
|
}
|
||||||
|
shotArtifacts, err := s.repo.ProjectShotArtifacts(project.ID)
|
||||||
|
if err != nil {
|
||||||
|
return ProjectDetail{}, err
|
||||||
|
}
|
||||||
shotReferences, err := s.repo.ProjectShotAssetReferences(project.ID)
|
shotReferences, err := s.repo.ProjectShotAssetReferences(project.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ProjectDetail{}, err
|
return ProjectDetail{}, err
|
||||||
@@ -185,7 +195,7 @@ func (s *Service) ProjectDetail(userID string, id string) (ProjectDetail, error)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return ProjectDetail{}, err
|
return ProjectDetail{}, err
|
||||||
}
|
}
|
||||||
return ProjectDetail{Project: *project, Units: units, Canvases: canvases, CanvasUnitLinks: canvasUnitLinks, Assets: assets, AssetFolders: assetFolders, Workflows: workflows, Shots: shots, ShotReferences: shotReferences, AssetCandidates: candidates}, nil
|
return ProjectDetail{Project: *project, Units: units, Canvases: canvases, CanvasUnitLinks: canvasUnitLinks, Assets: assets, AssetFolders: assetFolders, Workflows: workflows, Shots: shots, ShotRevisions: shotRevisions, ShotArtifacts: shotArtifacts, ShotReferences: shotReferences, AssetCandidates: candidates}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) CreateProject(userID string, req CreateProjectRequest) (model.Project, error) {
|
func (s *Service) CreateProject(userID string, req CreateProjectRequest) (model.Project, error) {
|
||||||
@@ -317,6 +327,17 @@ func (s *Service) DeleteProject(userID string, id string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) activeProjectForUser(userID string, projectID string) (*model.Project, error) {
|
||||||
|
project, err := s.repo.ProjectForUser(userID, projectID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if project.Status == model.ProjectStatusArchived {
|
||||||
|
return nil, BadAuthRequest("项目已归档,不能修改短剧生产数据")
|
||||||
|
}
|
||||||
|
return project, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Service) CreateProjectUnit(userID string, projectID string, req CreateProjectUnitRequest) (model.ProjectUnit, error) {
|
func (s *Service) CreateProjectUnit(userID string, projectID string, req CreateProjectUnitRequest) (model.ProjectUnit, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
||||||
return model.ProjectUnit{}, err
|
return model.ProjectUnit{}, err
|
||||||
@@ -439,6 +460,7 @@ func (s *Service) UpdateProjectUnit(userID string, projectID string, unitID stri
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return model.ProjectUnit{}, err
|
return model.ProjectUnit{}, err
|
||||||
}
|
}
|
||||||
|
sourceChanged := unit.SourceText != req.SourceText
|
||||||
if title := strings.TrimSpace(req.Title); title != "" {
|
if title := strings.TrimSpace(req.Title); title != "" {
|
||||||
unit.Title = title
|
unit.Title = title
|
||||||
}
|
}
|
||||||
@@ -450,10 +472,7 @@ func (s *Service) UpdateProjectUnit(userID string, projectID string, unitID stri
|
|||||||
unit.Status = status
|
unit.Status = status
|
||||||
}
|
}
|
||||||
unit.UpdatedAt = time.Now()
|
unit.UpdatedAt = time.Now()
|
||||||
if err := s.repo.UpdateProjectUnit(unit); err != nil {
|
if err := s.repo.UpdateProjectUnit(unit, sourceChanged); err != nil {
|
||||||
return model.ProjectUnit{}, err
|
|
||||||
}
|
|
||||||
if err := s.repo.BumpProjectRevision(projectID); err != nil {
|
|
||||||
return model.ProjectUnit{}, err
|
return model.ProjectUnit{}, err
|
||||||
}
|
}
|
||||||
return *unit, nil
|
return *unit, nil
|
||||||
|
|||||||
@@ -31,10 +31,13 @@ func newProjectDeleteTestService(t *testing.T) (*Service, *gorm.DB) {
|
|||||||
&model.Task{},
|
&model.Task{},
|
||||||
&model.Session{},
|
&model.Session{},
|
||||||
&model.Shot{},
|
&model.Shot{},
|
||||||
|
&model.ShotRevision{},
|
||||||
|
&model.ShotArtifact{},
|
||||||
&model.ShotAssetReference{},
|
&model.ShotAssetReference{},
|
||||||
&model.WorkflowInstance{},
|
&model.WorkflowInstance{},
|
||||||
&model.WorkflowStepInstance{},
|
&model.WorkflowStepInstance{},
|
||||||
&model.WorkflowStepTask{},
|
&model.WorkflowStepTask{},
|
||||||
|
&model.ProductionTaskLink{},
|
||||||
); err != nil {
|
); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -60,8 +63,12 @@ func TestDeleteProjectUnlinksCanvasAndKeepsIndependentRecords(t *testing.T) {
|
|||||||
&model.ProjectAssetLink{ID: "asset-link-1", ProjectID: project.ID, AssetID: asset.ID},
|
&model.ProjectAssetLink{ID: "asset-link-1", ProjectID: project.ID, AssetID: asset.ID},
|
||||||
&model.ProjectAssetFolder{ID: "folder-1", ProjectID: project.ID, Name: "角色", NameKey: "角色"},
|
&model.ProjectAssetFolder{ID: "folder-1", ProjectID: project.ID, Name: "角色", NameKey: "角色"},
|
||||||
&model.ProjectAssetCandidate{ID: "candidate-1", ProjectID: project.ID, UnitID: "unit-1", Name: "角色", Status: "pending_confirmation"},
|
&model.ProjectAssetCandidate{ID: "candidate-1", ProjectID: project.ID, UnitID: "unit-1", Name: "角色", Status: "pending_confirmation"},
|
||||||
|
&model.Shot{ID: "shot-1", ProjectID: project.ID, UnitID: "unit-1", CurrentRevisionID: "revision-1", Title: "镜头一"},
|
||||||
|
&model.ShotRevision{ID: "revision-1", ShotID: "shot-1", Version: 1, PlotDescription: "角色入场"},
|
||||||
|
&model.ShotArtifact{ID: "artifact-1", ProjectID: project.ID, UnitID: "unit-1", ShotID: "shot-1", RevisionID: "revision-1", Type: "storyboard", Version: 1, Status: "ready"},
|
||||||
&task,
|
&task,
|
||||||
&canvasTask,
|
&canvasTask,
|
||||||
|
&model.ProductionTaskLink{ID: "production-link-1", TaskID: task.ID, ProjectID: project.ID, UnitID: "unit-1", ShotID: "shot-1"},
|
||||||
&session,
|
&session,
|
||||||
&canvasSession,
|
&canvasSession,
|
||||||
}
|
}
|
||||||
@@ -105,6 +112,9 @@ func TestDeleteProjectUnlinksCanvasAndKeepsIndependentRecords(t *testing.T) {
|
|||||||
{name: "asset link", model: &model.ProjectAssetLink{}, where: "project_id = ?"},
|
{name: "asset link", model: &model.ProjectAssetLink{}, where: "project_id = ?"},
|
||||||
{name: "asset folder", model: &model.ProjectAssetFolder{}, where: "project_id = ?"},
|
{name: "asset folder", model: &model.ProjectAssetFolder{}, where: "project_id = ?"},
|
||||||
{name: "asset candidate", model: &model.ProjectAssetCandidate{}, where: "project_id = ?"},
|
{name: "asset candidate", model: &model.ProjectAssetCandidate{}, where: "project_id = ?"},
|
||||||
|
{name: "shot", model: &model.Shot{}, where: "project_id = ?"},
|
||||||
|
{name: "shot artifact", model: &model.ShotArtifact{}, where: "project_id = ?"},
|
||||||
|
{name: "production task link", model: &model.ProductionTaskLink{}, where: "project_id = ?"},
|
||||||
} {
|
} {
|
||||||
var count int64
|
var count int64
|
||||||
if err := db.Model(check.model).Where(check.where, project.ID).Count(&count).Error; err != nil {
|
if err := db.Model(check.model).Where(check.where, project.ID).Count(&count).Error; err != nil {
|
||||||
|
|||||||
@@ -9,13 +9,29 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type CreateProjectShotRequest struct {
|
type CreateProjectShotRequest struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
UnitID string `json:"unitId"`
|
UnitID string `json:"unitId"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
Position int `json:"position"`
|
Position int `json:"position"`
|
||||||
DurationMs int64 `json:"durationMs"`
|
DurationMs int64 `json:"durationMs"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
|
Revision ShotRevisionInput `json:"revision"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShotRevisionInput struct {
|
||||||
|
PlotDescription string `json:"plotDescription"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
Dialogue string `json:"dialogue"`
|
||||||
|
ShotSize string `json:"shotSize"`
|
||||||
|
CameraAngle string `json:"cameraAngle"`
|
||||||
|
CameraMovement string `json:"cameraMovement"`
|
||||||
|
DurationMs int64 `json:"durationMs"`
|
||||||
|
ImagePrompt string `json:"imagePrompt"`
|
||||||
|
VideoPrompt string `json:"videoPrompt"`
|
||||||
|
NegativePrompt string `json:"negativePrompt"`
|
||||||
|
ContinuityNotes string `json:"continuityNotes"`
|
||||||
|
ActionBeats []map[string]any `json:"actionBeats"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ReplaceProjectUnitShotsRequest struct {
|
type ReplaceProjectUnitShotsRequest struct {
|
||||||
@@ -40,7 +56,7 @@ type CreateAssetCandidatesRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) CreateProjectShot(userID string, projectID string, req CreateProjectShotRequest) (model.Shot, error) {
|
func (s *Service) CreateProjectShot(userID string, projectID string, req CreateProjectShotRequest) (model.Shot, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return model.Shot{}, err
|
return model.Shot{}, err
|
||||||
}
|
}
|
||||||
unitID := strings.TrimSpace(req.UnitID)
|
unitID := strings.TrimSpace(req.UnitID)
|
||||||
@@ -70,6 +86,9 @@ func (s *Service) CreateProjectShot(userID string, projectID string, req CreateP
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return model.Shot{}, err
|
return model.Shot{}, err
|
||||||
}
|
}
|
||||||
|
if unitID == "" {
|
||||||
|
unitID = existing.UnitID
|
||||||
|
}
|
||||||
if status == "" {
|
if status == "" {
|
||||||
status = existing.Status
|
status = existing.Status
|
||||||
}
|
}
|
||||||
@@ -78,18 +97,21 @@ func (s *Service) CreateProjectShot(userID string, projectID string, req CreateP
|
|||||||
if !validShotStatus(status) {
|
if !validShotStatus(status) {
|
||||||
return model.Shot{}, BadAuthRequest("不支持的镜头状态")
|
return model.Shot{}, BadAuthRequest("不支持的镜头状态")
|
||||||
}
|
}
|
||||||
shot := model.Shot{ID: shotID, ProjectID: projectID, UnitID: unitID, Title: title, Description: strings.TrimSpace(req.Description), Position: req.Position, DurationMs: req.DurationMs, Status: status, CreatedAt: now, UpdatedAt: time.Now()}
|
updatedAt := time.Now()
|
||||||
if err := s.repo.SaveShot(&shot, create); err != nil {
|
description := strings.TrimSpace(req.Description)
|
||||||
|
revision, err := newShotRevision(userID, shotID, req.Revision, description, req.DurationMs, updatedAt)
|
||||||
|
if err != nil {
|
||||||
return model.Shot{}, err
|
return model.Shot{}, err
|
||||||
}
|
}
|
||||||
if err := s.repo.BumpProjectRevision(projectID); err != nil {
|
shot := model.Shot{ID: shotID, ProjectID: projectID, UnitID: unitID, CurrentRevisionID: revision.ID, Title: title, Description: revision.PlotDescription, Position: req.Position, DurationMs: revision.DurationMs, Status: status, CreatedAt: now, UpdatedAt: updatedAt}
|
||||||
|
if err := s.repo.SaveShotWithRevision(&shot, &revision, create); err != nil {
|
||||||
return model.Shot{}, err
|
return model.Shot{}, err
|
||||||
}
|
}
|
||||||
return shot, nil
|
return shot, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) ReplaceProjectUnitShots(userID string, projectID string, unitID string, req ReplaceProjectUnitShotsRequest) ([]model.Shot, error) {
|
func (s *Service) ReplaceProjectUnitShots(userID string, projectID string, unitID string, req ReplaceProjectUnitShotsRequest) ([]model.Shot, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
unitID = strings.TrimSpace(unitID)
|
unitID = strings.TrimSpace(unitID)
|
||||||
@@ -101,21 +123,83 @@ func (s *Service) ReplaceProjectUnitShots(userID string, projectID string, unitI
|
|||||||
}
|
}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
shots := make([]model.Shot, 0, len(req.Shots))
|
shots := make([]model.Shot, 0, len(req.Shots))
|
||||||
|
revisions := make([]model.ShotRevision, 0, len(req.Shots))
|
||||||
for position, input := range req.Shots {
|
for position, input := range req.Shots {
|
||||||
title := strings.TrimSpace(input.Title)
|
title := strings.TrimSpace(input.Title)
|
||||||
description := strings.TrimSpace(input.Description)
|
description := strings.TrimSpace(input.Description)
|
||||||
if title == "" || description == "" || input.DurationMs < 0 {
|
if title == "" || description == "" || input.DurationMs < 0 {
|
||||||
return nil, BadAuthRequest("分镜标题、描述或时长无效")
|
return nil, BadAuthRequest("分镜标题、描述或时长无效")
|
||||||
}
|
}
|
||||||
shots = append(shots, model.Shot{ID: newID(), ProjectID: projectID, UnitID: unitID, Title: title, Description: description, Position: position, DurationMs: input.DurationMs, Status: "draft", CreatedAt: now, UpdatedAt: now})
|
shotID := newID()
|
||||||
|
revision, err := newShotRevision(userID, shotID, input.Revision, description, input.DurationMs, now)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
revision.Version = 1
|
||||||
|
shots = append(shots, model.Shot{ID: shotID, ProjectID: projectID, UnitID: unitID, CurrentRevisionID: revision.ID, Title: title, Description: revision.PlotDescription, Position: position, DurationMs: revision.DurationMs, Status: "draft", CreatedAt: now, UpdatedAt: now})
|
||||||
|
revisions = append(revisions, revision)
|
||||||
}
|
}
|
||||||
// 章节级重生成是一个整体写操作,旧镜头与引用必须和新镜头在同一事务中替换。
|
// 章节级重生成是一个整体写操作,旧镜头与引用必须和新镜头在同一事务中替换。
|
||||||
if err := s.repo.ReplaceProjectUnitShots(projectID, unitID, shots); err != nil {
|
if err := s.repo.ReplaceProjectUnitShots(projectID, unitID, shots, revisions); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return shots, nil
|
return shots, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) CreateShotRevision(userID string, projectID string, shotID string, input ShotRevisionInput) (model.Shot, model.ShotRevision, error) {
|
||||||
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
|
return model.Shot{}, model.ShotRevision{}, err
|
||||||
|
}
|
||||||
|
shot, err := s.repo.ShotForProject(projectID, strings.TrimSpace(shotID))
|
||||||
|
if err != nil {
|
||||||
|
return model.Shot{}, model.ShotRevision{}, err
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
revision, err := newShotRevision(userID, shot.ID, input, shot.Description, shot.DurationMs, now)
|
||||||
|
if err != nil {
|
||||||
|
return model.Shot{}, model.ShotRevision{}, err
|
||||||
|
}
|
||||||
|
shot.Description = revision.PlotDescription
|
||||||
|
shot.DurationMs = revision.DurationMs
|
||||||
|
shot.Status = "draft"
|
||||||
|
shot.UpdatedAt = now
|
||||||
|
if err := s.repo.SaveShotWithRevision(shot, &revision, false); err != nil {
|
||||||
|
return model.Shot{}, model.ShotRevision{}, err
|
||||||
|
}
|
||||||
|
return *shot, revision, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newShotRevision(userID string, shotID string, input ShotRevisionInput, fallbackDescription string, fallbackDuration int64, now time.Time) (model.ShotRevision, error) {
|
||||||
|
plotDescription := strings.TrimSpace(input.PlotDescription)
|
||||||
|
if plotDescription == "" {
|
||||||
|
plotDescription = strings.TrimSpace(fallbackDescription)
|
||||||
|
}
|
||||||
|
if plotDescription == "" {
|
||||||
|
return model.ShotRevision{}, BadAuthRequest("镜头画面描述不能为空")
|
||||||
|
}
|
||||||
|
durationMs := input.DurationMs
|
||||||
|
if durationMs == 0 {
|
||||||
|
durationMs = fallbackDuration
|
||||||
|
}
|
||||||
|
if durationMs < 0 {
|
||||||
|
return model.ShotRevision{}, BadAuthRequest("镜头时长不能为负数")
|
||||||
|
}
|
||||||
|
actionBeatsJSON := "[]"
|
||||||
|
if input.ActionBeats != nil {
|
||||||
|
encoded, err := json.Marshal(input.ActionBeats)
|
||||||
|
if err != nil {
|
||||||
|
return model.ShotRevision{}, BadAuthRequest("动作节拍格式无效")
|
||||||
|
}
|
||||||
|
actionBeatsJSON = string(encoded)
|
||||||
|
}
|
||||||
|
return model.ShotRevision{
|
||||||
|
ID: newID(), ShotID: shotID, PlotDescription: plotDescription, Action: strings.TrimSpace(input.Action), Dialogue: strings.TrimSpace(input.Dialogue),
|
||||||
|
ShotSize: strings.TrimSpace(input.ShotSize), CameraAngle: strings.TrimSpace(input.CameraAngle), CameraMovement: strings.TrimSpace(input.CameraMovement), DurationMs: durationMs,
|
||||||
|
ImagePrompt: strings.TrimSpace(input.ImagePrompt), VideoPrompt: strings.TrimSpace(input.VideoPrompt), NegativePrompt: strings.TrimSpace(input.NegativePrompt),
|
||||||
|
ContinuityNotes: strings.TrimSpace(input.ContinuityNotes), ActionBeatsJSON: actionBeatsJSON, CreatedBy: userID, CreatedAt: now,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func validShotStatus(status string) bool {
|
func validShotStatus(status string) bool {
|
||||||
switch status {
|
switch status {
|
||||||
case "draft", "ready", "running", "review", "completed", "failed":
|
case "draft", "ready", "running", "review", "completed", "failed":
|
||||||
@@ -126,7 +210,7 @@ func validShotStatus(status string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) LinkShotAsset(userID string, projectID string, shotID string, req LinkShotAssetRequest) (model.ShotAssetReference, error) {
|
func (s *Service) LinkShotAsset(userID string, projectID string, shotID string, req LinkShotAssetRequest) (model.ShotAssetReference, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return model.ShotAssetReference{}, err
|
return model.ShotAssetReference{}, err
|
||||||
}
|
}
|
||||||
if _, err := s.repo.ShotForProject(projectID, shotID); err != nil {
|
if _, err := s.repo.ShotForProject(projectID, shotID); err != nil {
|
||||||
@@ -140,18 +224,16 @@ func (s *Service) LinkShotAsset(userID string, projectID string, shotID string,
|
|||||||
if !validShotAssetRole(role) {
|
if !validShotAssetRole(role) {
|
||||||
return model.ShotAssetReference{}, BadAuthRequest("不支持的镜头素材用途")
|
return model.ShotAssetReference{}, BadAuthRequest("不支持的镜头素材用途")
|
||||||
}
|
}
|
||||||
reference := model.ShotAssetReference{ID: newID(), ShotID: shotID, AssetVersionID: versionID, Role: role, Status: "linked", CreatedAt: time.Now()}
|
now := time.Now()
|
||||||
if err := s.repo.UpsertShotAssetReference(&reference); err != nil {
|
reference := model.ShotAssetReference{ID: newID(), ShotID: shotID, AssetVersionID: versionID, Role: role, Status: "linked", CreatedAt: now}
|
||||||
return model.ShotAssetReference{}, err
|
if err := s.repo.UpsertShotAssetReferenceAndInvalidate(projectID, &reference, now); err != nil {
|
||||||
}
|
|
||||||
if err := s.repo.BumpProjectRevision(projectID); err != nil {
|
|
||||||
return model.ShotAssetReference{}, err
|
return model.ShotAssetReference{}, err
|
||||||
}
|
}
|
||||||
return reference, nil
|
return reference, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) CreateProjectAssetCandidates(userID string, projectID string, req CreateAssetCandidatesRequest) ([]model.ProjectAssetCandidate, error) {
|
func (s *Service) CreateProjectAssetCandidates(userID string, projectID string, req CreateAssetCandidatesRequest) ([]model.ProjectAssetCandidate, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if len(req.Candidates) == 0 || len(req.Candidates) > 100 {
|
if len(req.Candidates) == 0 || len(req.Candidates) > 100 {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const builtinShortDramaWorkflowKey = "short-drama-production"
|
const builtinShortDramaWorkflowKey = "short-drama-production"
|
||||||
const builtinShortDramaWorkflowVersion = 1
|
const builtinShortDramaWorkflowVersion = 2
|
||||||
|
|
||||||
type workflowStepDefinition struct {
|
type workflowStepDefinition struct {
|
||||||
Key string `json:"key"`
|
Key string `json:"key"`
|
||||||
@@ -20,13 +20,12 @@ type workflowStepDefinition struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var builtinShortDramaSteps = []workflowStepDefinition{
|
var builtinShortDramaSteps = []workflowStepDefinition{
|
||||||
{Key: "style", Name: "选择画风"},
|
{Key: "story", Name: "剧情与章节"},
|
||||||
{Key: "story", Name: "输入故事"},
|
{Key: "assets", Name: "资产拆分"},
|
||||||
{Key: "storyboard", Name: "生成分镜"},
|
{Key: "storyboard", Name: "分镜脚本"},
|
||||||
{Key: "assets", Name: "准备资产"},
|
{Key: "previz", Name: "黑白动作预演"},
|
||||||
{Key: "video", Name: "生成视频"},
|
{Key: "video", Name: "视频生成"},
|
||||||
{Key: "review", Name: "审核与重试"},
|
{Key: "delivery", Name: "交付与打包"},
|
||||||
{Key: "delivery", Name: "合并成片"},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ProjectWorkflowDetail struct {
|
type ProjectWorkflowDetail struct {
|
||||||
@@ -42,6 +41,10 @@ type UpdateWorkflowStepRequest struct {
|
|||||||
|
|
||||||
type RegisterTaskOutputRequest struct {
|
type RegisterTaskOutputRequest struct {
|
||||||
TaskID string `json:"taskId"`
|
TaskID string `json:"taskId"`
|
||||||
|
CanvasID string `json:"canvasId"`
|
||||||
|
UnitID string `json:"unitId"`
|
||||||
|
ShotID string `json:"shotId"`
|
||||||
|
ArtifactType string `json:"artifactType"`
|
||||||
AssetVersionID string `json:"assetVersionId"`
|
AssetVersionID string `json:"assetVersionId"`
|
||||||
ResourceID string `json:"resourceId"`
|
ResourceID string `json:"resourceId"`
|
||||||
MediaType string `json:"mediaType"`
|
MediaType string `json:"mediaType"`
|
||||||
@@ -60,7 +63,7 @@ func (s *Service) EnsureBuiltinProjectWorkflowTemplate() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
template := model.WorkflowTemplateVersion{ID: newID(), TemplateKey: builtinShortDramaWorkflowKey, Name: "短剧标准制作流程", Version: builtinShortDramaWorkflowVersion, DefinitionJSON: string(definition), CreatedAt: time.Now()}
|
template := model.WorkflowTemplateVersion{ID: newID(), TemplateKey: builtinShortDramaWorkflowKey, Name: "短剧分镜工作流", Version: builtinShortDramaWorkflowVersion, DefinitionJSON: string(definition), CreatedAt: time.Now()}
|
||||||
return s.repo.CreateWorkflowTemplateVersion(&template)
|
return s.repo.CreateWorkflowTemplateVersion(&template)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +114,7 @@ func (s *Service) ProjectWorkflows(projectID string) ([]ProjectWorkflowDetail, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) CreateUnitWorkflow(userID string, projectID string, unitID string) (ProjectWorkflowDetail, error) {
|
func (s *Service) CreateUnitWorkflow(userID string, projectID string, unitID string) (ProjectWorkflowDetail, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return ProjectWorkflowDetail{}, err
|
return ProjectWorkflowDetail{}, err
|
||||||
}
|
}
|
||||||
if _, err := s.repo.ProjectUnit(projectID, unitID); err != nil {
|
if _, err := s.repo.ProjectUnit(projectID, unitID); err != nil {
|
||||||
@@ -121,7 +124,7 @@ func (s *Service) CreateUnitWorkflow(userID string, projectID string, unitID str
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) UpdateWorkflowStep(userID string, projectID string, stepID string, req UpdateWorkflowStepRequest) (model.WorkflowStepInstance, error) {
|
func (s *Service) UpdateWorkflowStep(userID string, projectID string, stepID string, req UpdateWorkflowStepRequest) (model.WorkflowStepInstance, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return model.WorkflowStepInstance{}, err
|
return model.WorkflowStepInstance{}, err
|
||||||
}
|
}
|
||||||
step, err := s.repo.WorkflowStepForProject(projectID, stepID)
|
step, err := s.repo.WorkflowStepForProject(projectID, stepID)
|
||||||
@@ -155,6 +158,11 @@ func (s *Service) UpdateWorkflowStep(userID string, projectID string, stepID str
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return model.WorkflowStepInstance{}, err
|
return model.WorkflowStepInstance{}, err
|
||||||
}
|
}
|
||||||
|
if status == model.WorkflowStepStatusCompleted {
|
||||||
|
if err := s.validateWorkflowStepCompletion(projectID, instance, step); err != nil {
|
||||||
|
return model.WorkflowStepInstance{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
instance.Status = model.WorkflowStatusActive
|
instance.Status = model.WorkflowStatusActive
|
||||||
instance.Revision++
|
instance.Revision++
|
||||||
instance.UpdatedAt = now
|
instance.UpdatedAt = now
|
||||||
@@ -180,15 +188,29 @@ func (s *Service) UpdateWorkflowStep(userID string, projectID string, stepID str
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) RegisterTaskOutput(userID string, projectID string, stepID string, req RegisterTaskOutputRequest) (model.WorkflowStepInstance, error) {
|
func (s *Service) RegisterTaskOutput(userID string, projectID string, stepID string, req RegisterTaskOutputRequest) (model.WorkflowStepInstance, error) {
|
||||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
if _, err := s.activeProjectForUser(userID, projectID); err != nil {
|
||||||
return model.WorkflowStepInstance{}, err
|
return model.WorkflowStepInstance{}, err
|
||||||
}
|
}
|
||||||
task, err := s.repo.TaskForUser(userID, strings.TrimSpace(req.TaskID))
|
task, err := s.repo.TaskForUser(userID, strings.TrimSpace(req.TaskID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return model.WorkflowStepInstance{}, err
|
return model.WorkflowStepInstance{}, err
|
||||||
}
|
}
|
||||||
|
canvasID := strings.TrimSpace(req.CanvasID)
|
||||||
if task.ProjectID != projectID {
|
if task.ProjectID != projectID {
|
||||||
return model.WorkflowStepInstance{}, BadAuthRequest("任务不属于当前项目")
|
canvas, canvasErr := s.repo.CanvasProjectForUser(userID, task.ProjectID)
|
||||||
|
if canvasErr != nil || canvas.ProjectID != projectID {
|
||||||
|
return model.WorkflowStepInstance{}, BadAuthRequest("任务不属于当前项目")
|
||||||
|
}
|
||||||
|
if canvasID != "" && canvasID != canvas.ID {
|
||||||
|
return model.WorkflowStepInstance{}, BadAuthRequest("任务画布与产物画布不一致")
|
||||||
|
}
|
||||||
|
canvasID = canvas.ID
|
||||||
|
}
|
||||||
|
if canvasID != "" {
|
||||||
|
canvas, canvasErr := s.repo.CanvasProjectForUser(userID, canvasID)
|
||||||
|
if canvasErr != nil || canvas.ProjectID != projectID {
|
||||||
|
return model.WorkflowStepInstance{}, BadAuthRequest("画布不属于当前项目")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if task.Status != model.TaskStatusSucceeded {
|
if task.Status != model.TaskStatusSucceeded {
|
||||||
return model.WorkflowStepInstance{}, BadAuthRequest("只有成功任务才能登记产物")
|
return model.WorkflowStepInstance{}, BadAuthRequest("只有成功任务才能登记产物")
|
||||||
@@ -200,6 +222,24 @@ func (s *Service) RegisterTaskOutput(userID string, projectID string, stepID str
|
|||||||
if step.Status == model.WorkflowStepStatusFailed {
|
if step.Status == model.WorkflowStepStatusFailed {
|
||||||
return model.WorkflowStepInstance{}, BadAuthRequest("失败步骤不能登记成功产物")
|
return model.WorkflowStepInstance{}, BadAuthRequest("失败步骤不能登记成功产物")
|
||||||
}
|
}
|
||||||
|
unitID := strings.TrimSpace(req.UnitID)
|
||||||
|
shotID := strings.TrimSpace(req.ShotID)
|
||||||
|
var shot *model.Shot
|
||||||
|
if shotID != "" {
|
||||||
|
shot, err = s.repo.ShotForProject(projectID, shotID)
|
||||||
|
if err != nil {
|
||||||
|
return model.WorkflowStepInstance{}, err
|
||||||
|
}
|
||||||
|
if unitID == "" {
|
||||||
|
unitID = shot.UnitID
|
||||||
|
} else if unitID != shot.UnitID {
|
||||||
|
return model.WorkflowStepInstance{}, BadAuthRequest("镜头不属于指定章节")
|
||||||
|
}
|
||||||
|
} else if unitID != "" {
|
||||||
|
if _, err := s.repo.ProjectUnit(projectID, unitID); err != nil {
|
||||||
|
return model.WorkflowStepInstance{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
if versionID := strings.TrimSpace(req.AssetVersionID); versionID != "" {
|
if versionID := strings.TrimSpace(req.AssetVersionID); versionID != "" {
|
||||||
if _, err := s.repo.AssetVersionForProject(projectID, versionID); err != nil {
|
if _, err := s.repo.AssetVersionForProject(projectID, versionID); err != nil {
|
||||||
return model.WorkflowStepInstance{}, err
|
return model.WorkflowStepInstance{}, err
|
||||||
@@ -258,12 +298,112 @@ func (s *Service) RegisterTaskOutput(userID string, projectID string, stepID str
|
|||||||
representation = &model.AssetRepresentation{ID: newID(), TaskID: task.ID, AssetVersionID: strings.TrimSpace(req.AssetVersionID), ResourceID: strings.TrimSpace(req.ResourceID), MediaType: strings.TrimSpace(req.MediaType), Role: role, MetadataJSON: metadata, CreatedAt: now}
|
representation = &model.AssetRepresentation{ID: newID(), TaskID: task.ID, AssetVersionID: strings.TrimSpace(req.AssetVersionID), ResourceID: strings.TrimSpace(req.ResourceID), MediaType: strings.TrimSpace(req.MediaType), Role: role, MetadataJSON: metadata, CreatedAt: now}
|
||||||
}
|
}
|
||||||
link := &model.WorkflowStepTask{ID: newID(), WorkflowStepID: step.ID, TaskID: task.ID, CreatedAt: now}
|
link := &model.WorkflowStepTask{ID: newID(), WorkflowStepID: step.ID, TaskID: task.ID, CreatedAt: now}
|
||||||
if err := s.repo.RegisterWorkflowTaskOutput(step, next, instance, projectID, link, representation); err != nil {
|
artifactType := strings.TrimSpace(req.ArtifactType)
|
||||||
|
if artifactType == "" && shotID != "" && strings.TrimSpace(req.ResourceID) != "" {
|
||||||
|
artifactType = workflowArtifactType(step.StepKey)
|
||||||
|
}
|
||||||
|
productionLink := &model.ProductionTaskLink{ID: newID(), TaskID: task.ID, ProjectID: projectID, CanvasID: canvasID, UnitID: unitID, ShotID: shotID, WorkflowStepID: step.ID, ArtifactType: artifactType, CreatedAt: now, UpdatedAt: now}
|
||||||
|
var artifact *model.ShotArtifact
|
||||||
|
if shot != nil && strings.TrimSpace(req.ResourceID) != "" && artifactType != "" {
|
||||||
|
artifact = &model.ShotArtifact{ID: newID(), ProjectID: projectID, UnitID: shot.UnitID, ShotID: shot.ID, RevisionID: shot.CurrentRevisionID, TaskID: task.ID, Type: artifactType, ResourceID: strings.TrimSpace(req.ResourceID), Status: "ready", Selected: true, MetadataJSON: metadata, CreatedAt: now, UpdatedAt: now}
|
||||||
|
}
|
||||||
|
// 单镜产物成功只代表该镜头完成,不能提前放行整个章节阶段。
|
||||||
|
if shot != nil {
|
||||||
|
step.Status = model.WorkflowStepStatusRunning
|
||||||
|
step.CompletedAt = nil
|
||||||
|
instance.Status = model.WorkflowStatusActive
|
||||||
|
next = nil
|
||||||
|
}
|
||||||
|
if err := s.repo.RegisterWorkflowTaskOutput(step, next, instance, projectID, link, representation, productionLink, artifact); err != nil {
|
||||||
return model.WorkflowStepInstance{}, err
|
return model.WorkflowStepInstance{}, err
|
||||||
}
|
}
|
||||||
return *step, nil
|
return *step, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) validateWorkflowStepCompletion(projectID string, instance *model.WorkflowInstance, step *model.WorkflowStepInstance) error {
|
||||||
|
if instance == nil || strings.TrimSpace(instance.UnitID) == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
unit, err := s.repo.ProjectUnit(projectID, instance.UnitID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch step.StepKey {
|
||||||
|
case "story":
|
||||||
|
if strings.TrimSpace(unit.SourceText) == "" {
|
||||||
|
return BadAuthRequest("章节正文为空,不能完成剧情阶段")
|
||||||
|
}
|
||||||
|
case "assets":
|
||||||
|
candidates, candidateErr := s.repo.ProjectAssetCandidates(projectID)
|
||||||
|
if candidateErr != nil {
|
||||||
|
return candidateErr
|
||||||
|
}
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if candidate.UnitID == instance.UnitID && candidate.Status == "pending_confirmation" {
|
||||||
|
return BadAuthRequest("仍有待确认资产,不能完成资产拆分阶段")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "storyboard", "previz", "video", "delivery":
|
||||||
|
shots, shotErr := s.repo.ProjectShots(projectID)
|
||||||
|
if shotErr != nil {
|
||||||
|
return shotErr
|
||||||
|
}
|
||||||
|
unitShots := make([]model.Shot, 0, len(shots))
|
||||||
|
for _, shot := range shots {
|
||||||
|
if shot.UnitID == instance.UnitID {
|
||||||
|
unitShots = append(unitShots, shot)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(unitShots) == 0 {
|
||||||
|
return BadAuthRequest("当前章节还没有分镜,不能完成本阶段")
|
||||||
|
}
|
||||||
|
if step.StepKey == "storyboard" {
|
||||||
|
for _, shot := range unitShots {
|
||||||
|
if strings.TrimSpace(shot.CurrentRevisionID) == "" {
|
||||||
|
return BadAuthRequest("存在没有分镜版本的镜头,不能完成分镜阶段")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
artifactType := "action_board"
|
||||||
|
if step.StepKey == "video" || step.StepKey == "delivery" {
|
||||||
|
artifactType = "video"
|
||||||
|
}
|
||||||
|
artifacts, artifactErr := s.repo.ProjectShotArtifacts(projectID)
|
||||||
|
if artifactErr != nil {
|
||||||
|
return artifactErr
|
||||||
|
}
|
||||||
|
readyShots := make(map[string]struct{}, len(unitShots))
|
||||||
|
for _, artifact := range artifacts {
|
||||||
|
if artifact.UnitID == instance.UnitID && artifact.Type == artifactType && artifact.Selected && artifact.Status == "ready" {
|
||||||
|
readyShots[artifact.ShotID] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(readyShots) != len(unitShots) {
|
||||||
|
if artifactType == "action_board" {
|
||||||
|
return BadAuthRequest("仍有镜头缺少已通过的动作预演,不能完成本阶段")
|
||||||
|
}
|
||||||
|
return BadAuthRequest("仍有镜头缺少可交付视频,不能完成本阶段")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func workflowArtifactType(stepKey string) string {
|
||||||
|
switch strings.TrimSpace(stepKey) {
|
||||||
|
case "storyboard":
|
||||||
|
return "storyboard"
|
||||||
|
case "previz":
|
||||||
|
return "action_board"
|
||||||
|
case "video":
|
||||||
|
return "video"
|
||||||
|
case "delivery":
|
||||||
|
return "delivery"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Service) RegisterTaskOutputFromTask(task model.Task) error {
|
func (s *Service) RegisterTaskOutputFromTask(task model.Task) error {
|
||||||
if strings.TrimSpace(task.ProjectID) == "" || task.Status != model.TaskStatusSucceeded {
|
if strings.TrimSpace(task.ProjectID) == "" || task.Status != model.TaskStatusSucceeded {
|
||||||
return nil
|
return nil
|
||||||
@@ -278,6 +418,10 @@ func (s *Service) RegisterTaskOutputFromTask(task model.Task) error {
|
|||||||
var input struct {
|
var input struct {
|
||||||
WorkflowStepID string `json:"workflowStepId"`
|
WorkflowStepID string `json:"workflowStepId"`
|
||||||
DomainProjectID string `json:"domainProjectId"`
|
DomainProjectID string `json:"domainProjectId"`
|
||||||
|
CanvasID string `json:"canvasId"`
|
||||||
|
UnitID string `json:"unitId"`
|
||||||
|
ShotID string `json:"shotId"`
|
||||||
|
ArtifactType string `json:"artifactType"`
|
||||||
AssetVersionID string `json:"assetVersionId"`
|
AssetVersionID string `json:"assetVersionId"`
|
||||||
ResourceID string `json:"resourceId"`
|
ResourceID string `json:"resourceId"`
|
||||||
MediaType string `json:"mediaType"`
|
MediaType string `json:"mediaType"`
|
||||||
@@ -297,6 +441,18 @@ func (s *Service) RegisterTaskOutputFromTask(task model.Task) error {
|
|||||||
if input.AssetVersionID == "" {
|
if input.AssetVersionID == "" {
|
||||||
input.AssetVersionID, _ = input.Metadata["assetVersionId"].(string)
|
input.AssetVersionID, _ = input.Metadata["assetVersionId"].(string)
|
||||||
}
|
}
|
||||||
|
if input.CanvasID == "" {
|
||||||
|
input.CanvasID, _ = input.Metadata["canvasId"].(string)
|
||||||
|
}
|
||||||
|
if input.UnitID == "" {
|
||||||
|
input.UnitID, _ = input.Metadata["unitId"].(string)
|
||||||
|
}
|
||||||
|
if input.ShotID == "" {
|
||||||
|
input.ShotID, _ = input.Metadata["shotId"].(string)
|
||||||
|
}
|
||||||
|
if input.ArtifactType == "" {
|
||||||
|
input.ArtifactType, _ = input.Metadata["artifactType"].(string)
|
||||||
|
}
|
||||||
if input.ResourceID == "" {
|
if input.ResourceID == "" {
|
||||||
input.ResourceID, _ = input.Metadata["resourceId"].(string)
|
input.ResourceID, _ = input.Metadata["resourceId"].(string)
|
||||||
}
|
}
|
||||||
@@ -319,7 +475,7 @@ func (s *Service) RegisterTaskOutputFromTask(task model.Task) error {
|
|||||||
if projectID == "" {
|
if projectID == "" {
|
||||||
return errors.New("任务未提供短剧项目 ID,无法登记产物")
|
return errors.New("任务未提供短剧项目 ID,无法登记产物")
|
||||||
}
|
}
|
||||||
_, err = s.RegisterTaskOutput(task.UserID, projectID, input.WorkflowStepID, RegisterTaskOutputRequest{TaskID: task.ID, AssetVersionID: input.AssetVersionID, ResourceID: input.ResourceID, MediaType: input.MediaType, Role: input.Role, OutputJSON: task.ResultJSON})
|
_, err = s.RegisterTaskOutput(task.UserID, projectID, input.WorkflowStepID, RegisterTaskOutputRequest{TaskID: task.ID, CanvasID: input.CanvasID, UnitID: input.UnitID, ShotID: input.ShotID, ArtifactType: input.ArtifactType, AssetVersionID: input.AssetVersionID, ResourceID: input.ResourceID, MediaType: input.MediaType, Role: input.Role, OutputJSON: task.ResultJSON})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"infinite-canvas/backend/internal/model"
|
||||||
|
"infinite-canvas/backend/internal/repository"
|
||||||
|
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newProjectWorkflowV2TestService(t *testing.T) (*Service, *gorm.DB) {
|
||||||
|
t.Helper()
|
||||||
|
db, err := gorm.Open(sqlite.Open("file:"+newID()+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(
|
||||||
|
&model.Project{}, &model.ProjectUnit{}, &model.CanvasProject{}, &model.Asset{}, &model.AssetVersion{}, &model.ProjectAssetLink{},
|
||||||
|
&model.Shot{}, &model.ShotRevision{}, &model.ShotArtifact{}, &model.ShotAssetReference{},
|
||||||
|
&model.WorkflowTemplateVersion{}, &model.WorkflowInstance{}, &model.WorkflowStepInstance{}, &model.WorkflowStepTask{},
|
||||||
|
&model.ProductionTaskLink{}, &model.Task{}, &model.Resource{},
|
||||||
|
); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return &Service{repo: repository.New(db)}, db
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedWorkflowProject(t *testing.T, db *gorm.DB) (model.Project, model.ProjectUnit) {
|
||||||
|
t.Helper()
|
||||||
|
now := time.Now()
|
||||||
|
project := model.Project{ID: "project-1", UserID: "user-1", Name: "短剧", Status: model.ProjectStatusActive, Revision: 1, CreatedAt: now, UpdatedAt: now}
|
||||||
|
unit := model.ProjectUnit{ID: "unit-1", ProjectID: project.ID, Kind: model.ProjectUnitKindChapter, Title: "第一章", Status: model.ProjectUnitStatusDraft, CreatedAt: now, UpdatedAt: now}
|
||||||
|
if err := db.Create(&project).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.Create(&unit).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return project, unit
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShortDramaWorkflowV2UsesProductionOrder(t *testing.T) {
|
||||||
|
service, db := newProjectWorkflowV2TestService(t)
|
||||||
|
project, unit := seedWorkflowProject(t, db)
|
||||||
|
if err := service.EnsureBuiltinProjectWorkflowTemplate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
workflow, err := service.CreateUnitWorkflow("user-1", project.ID, unit.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(workflow.Steps))
|
||||||
|
for _, step := range workflow.Steps {
|
||||||
|
keys = append(keys, step.StepKey)
|
||||||
|
}
|
||||||
|
want := []string{"story", "assets", "storyboard", "previz", "video", "delivery"}
|
||||||
|
if !reflect.DeepEqual(keys, want) {
|
||||||
|
t.Fatalf("step keys = %v, want %v", keys, want)
|
||||||
|
}
|
||||||
|
if workflow.Steps[0].Status != model.WorkflowStepStatusReady {
|
||||||
|
t.Fatalf("first step status = %s, want ready", workflow.Steps[0].Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWorkflowCompletionRequiresStageGate(t *testing.T) {
|
||||||
|
service, db := newProjectWorkflowV2TestService(t)
|
||||||
|
project, unit := seedWorkflowProject(t, db)
|
||||||
|
if err := service.EnsureBuiltinProjectWorkflowTemplate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
workflow, err := service.CreateUnitWorkflow("user-1", project.ID, unit.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
step := workflow.Steps[0]
|
||||||
|
if _, err := service.UpdateWorkflowStep("user-1", project.ID, step.ID, UpdateWorkflowStepRequest{Status: "running"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := service.UpdateWorkflowStep("user-1", project.ID, step.ID, UpdateWorkflowStepRequest{Status: "completed"}); err == nil {
|
||||||
|
t.Fatal("empty chapter completed story gate")
|
||||||
|
}
|
||||||
|
unit.SourceText = "第一章正文"
|
||||||
|
unit.UpdatedAt = time.Now()
|
||||||
|
if err := db.Save(&unit).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := service.UpdateWorkflowStep("user-1", project.ID, step.ID, UpdateWorkflowStepRequest{Status: "completed"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateShotRevisionInvalidatesExistingArtifacts(t *testing.T) {
|
||||||
|
service, db := newProjectWorkflowV2TestService(t)
|
||||||
|
project, unit := seedWorkflowProject(t, db)
|
||||||
|
if err := service.EnsureBuiltinProjectWorkflowTemplate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
workflow, err := service.CreateUnitWorkflow("user-1", project.ID, unit.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
shot, err := service.CreateProjectShot("user-1", project.ID, CreateProjectShotRequest{UnitID: unit.ID, Title: "SC.01", Description: "人物推门进入", DurationMs: 3000})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.Model(&model.WorkflowStepInstance{}).Where("workflow_instance_id = ? AND step_key IN ?", workflow.Instance.ID, []string{"storyboard", "previz", "video", "delivery"}).Updates(map[string]any{"status": model.WorkflowStepStatusCompleted}).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
artifact := model.ShotArtifact{ID: "artifact-1", ProjectID: project.ID, UnitID: unit.ID, ShotID: shot.ID, RevisionID: shot.CurrentRevisionID, Type: "action_board", Version: 1, Status: "ready", Selected: true, CreatedAt: time.Now(), UpdatedAt: time.Now()}
|
||||||
|
if err := db.Create(&artifact).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
updatedShot, revision, err := service.CreateShotRevision("user-1", project.ID, shot.ID, ShotRevisionInput{PlotDescription: "人物推门后停在门口", Action: "推门、停顿", DurationMs: 3500})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if revision.Version != 2 || updatedShot.CurrentRevisionID != revision.ID {
|
||||||
|
t.Fatalf("revision = v%d current=%s, want v2 current revision", revision.Version, updatedShot.CurrentRevisionID)
|
||||||
|
}
|
||||||
|
var storedArtifact model.ShotArtifact
|
||||||
|
if err := db.First(&storedArtifact, "id = ?", artifact.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if storedArtifact.Status != "stale" || storedArtifact.Selected {
|
||||||
|
t.Fatalf("artifact status=%s selected=%v, want stale false", storedArtifact.Status, storedArtifact.Selected)
|
||||||
|
}
|
||||||
|
var storyboardStep model.WorkflowStepInstance
|
||||||
|
if err := db.First(&storyboardStep, "workflow_instance_id = ? AND step_key = ?", workflow.Instance.ID, "storyboard").Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if storyboardStep.Status != model.WorkflowStepStatusRunning {
|
||||||
|
t.Fatalf("storyboard step status = %s, want running", storyboardStep.Status)
|
||||||
|
}
|
||||||
|
var videoStep model.WorkflowStepInstance
|
||||||
|
if err := db.First(&videoStep, "workflow_instance_id = ? AND step_key = ?", workflow.Instance.ID, "video").Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if videoStep.Status != model.WorkflowStepStatusPending {
|
||||||
|
t.Fatalf("video step status = %s, want pending", videoStep.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateChapterSourceInvalidatesAllUnitArtifacts(t *testing.T) {
|
||||||
|
service, db := newProjectWorkflowV2TestService(t)
|
||||||
|
project, unit := seedWorkflowProject(t, db)
|
||||||
|
if err := service.EnsureBuiltinProjectWorkflowTemplate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
workflow, err := service.CreateUnitWorkflow("user-1", project.ID, unit.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
shot, err := service.CreateProjectShot("user-1", project.ID, CreateProjectShotRequest{UnitID: unit.ID, Title: "SC.01", Description: "旧剧情镜头", DurationMs: 3000})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
artifact := model.ShotArtifact{ID: "artifact-source-1", ProjectID: project.ID, UnitID: unit.ID, ShotID: shot.ID, RevisionID: shot.CurrentRevisionID, Type: "video", Version: 1, Status: "ready", Selected: true, CreatedAt: time.Now(), UpdatedAt: time.Now()}
|
||||||
|
if err := db.Create(&artifact).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := service.UpdateProjectUnit("user-1", project.ID, unit.ID, UpdateProjectUnitRequest{Title: unit.Title, SourceText: "修改后的章节正文"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var storedArtifact model.ShotArtifact
|
||||||
|
if err := db.First(&storedArtifact, "id = ?", artifact.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if storedArtifact.Status != "stale" || storedArtifact.Selected {
|
||||||
|
t.Fatalf("artifact status=%s selected=%v, want stale false", storedArtifact.Status, storedArtifact.Selected)
|
||||||
|
}
|
||||||
|
var storyStep model.WorkflowStepInstance
|
||||||
|
if err := db.First(&storyStep, "workflow_instance_id = ? AND step_key = ?", workflow.Instance.ID, "story").Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if storyStep.Status != model.WorkflowStepStatusRunning {
|
||||||
|
t.Fatalf("story step status = %s, want running", storyStep.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegisterTaskOutputAcceptsLinkedCanvasAndCreatesShotArtifact(t *testing.T) {
|
||||||
|
service, db := newProjectWorkflowV2TestService(t)
|
||||||
|
project, unit := seedWorkflowProject(t, db)
|
||||||
|
if err := service.EnsureBuiltinProjectWorkflowTemplate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
workflow, err := service.CreateUnitWorkflow("user-1", project.ID, unit.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
shot, err := service.CreateProjectShot("user-1", project.ID, CreateProjectShotRequest{UnitID: unit.ID, Title: "SC.01", Description: "人物走入画面", DurationMs: 3000})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
canvas := model.CanvasProject{ID: "canvas-1", UserID: "user-1", ProjectID: project.ID, Title: "探索画布", CreatedAt: time.Now(), UpdatedAt: time.Now()}
|
||||||
|
task := model.Task{ID: "task-1", UserID: "user-1", ProjectID: canvas.ID, Status: model.TaskStatusSucceeded, ResultJSON: `{}`, CreatedAt: time.Now(), UpdatedAt: time.Now()}
|
||||||
|
resource := model.Resource{ID: "resource-1", UserID: "user-1", Kind: "image", Status: model.ResourceStatusReady, CreatedAt: time.Now(), UpdatedAt: time.Now()}
|
||||||
|
for _, item := range []any{&canvas, &task, &resource} {
|
||||||
|
if err := db.Create(item).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
step := workflow.Steps[0]
|
||||||
|
updatedStep, err := service.RegisterTaskOutput("user-1", project.ID, step.ID, RegisterTaskOutputRequest{TaskID: task.ID, UnitID: unit.ID, ShotID: shot.ID, ArtifactType: "storyboard", ResourceID: resource.ID, MediaType: "image"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if updatedStep.Status != model.WorkflowStepStatusRunning {
|
||||||
|
t.Fatalf("step status = %s, want running until the unit gate is complete", updatedStep.Status)
|
||||||
|
}
|
||||||
|
var nextStep model.WorkflowStepInstance
|
||||||
|
if err := db.First(&nextStep, "workflow_instance_id = ? AND position = ?", workflow.Instance.ID, 1).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if nextStep.Status != model.WorkflowStepStatusPending {
|
||||||
|
t.Fatalf("next step status = %s, want pending", nextStep.Status)
|
||||||
|
}
|
||||||
|
var productionLink model.ProductionTaskLink
|
||||||
|
if err := db.First(&productionLink, "task_id = ?", task.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if productionLink.ProjectID != project.ID || productionLink.CanvasID != canvas.ID || productionLink.ShotID != shot.ID {
|
||||||
|
t.Fatalf("unexpected production link: %+v", productionLink)
|
||||||
|
}
|
||||||
|
var storedArtifact model.ShotArtifact
|
||||||
|
if err := db.First(&storedArtifact, "task_id = ?", task.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if storedArtifact.Type != "storyboard" || storedArtifact.Status != "ready" || !storedArtifact.Selected {
|
||||||
|
t.Fatalf("unexpected shot artifact: %+v", storedArtifact)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -127,9 +127,11 @@ func (s *Service) CreateTask(userID string, req CreateTaskRequest) (*model.Task,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// resolveTaskModelSelection 根据请求实际携带的模型选择决定路由方式。
|
// resolveTaskModelSelection 根据请求实际携带的模型选择决定路由方式。
|
||||||
// 显式系统渠道请求不能被全局前台模型开关误判,但仍必须通过渠道、模型和价格校验。
|
// 显式系统渠道和用户自定义渠道请求不能被全局前台模型开关误判;
|
||||||
|
// 它们仍分别进入系统目录校验或自定义渠道的功能、能力与安全校验。
|
||||||
func (s *Service) resolveTaskModelSelection(input map[string]any, logicalModelID string, taskType string, operation string, frontendEnabled bool) (*RoutedModel, map[string]any, error) {
|
func (s *Service) resolveTaskModelSelection(input map[string]any, logicalModelID string, taskType string, operation string, frontendEnabled bool) (*RoutedModel, map[string]any, error) {
|
||||||
if frontendEnabled && !taskInputUsesSystemChannel(input) {
|
customChannelTask := taskInputUsesCustomChannel(input)
|
||||||
|
if frontendEnabled && !taskInputUsesSystemChannel(input) && !customChannelTask {
|
||||||
if logicalModelID == "" {
|
if logicalModelID == "" {
|
||||||
return nil, input, InvalidModelSelection("前台模型模式下必须指定 logicalModelId")
|
return nil, input, InvalidModelSelection("前台模型模式下必须指定 logicalModelId")
|
||||||
}
|
}
|
||||||
@@ -146,7 +148,7 @@ func (s *Service) resolveTaskModelSelection(input map[string]any, logicalModelID
|
|||||||
}
|
}
|
||||||
// 自定义渠道没有系统 channelId;它会在后续由自定义渠道功能开关、
|
// 自定义渠道没有系统 channelId;它会在后续由自定义渠道功能开关、
|
||||||
// 能力校验和 provider 配置校验共同处理,不能误报为“缺少系统渠道”。
|
// 能力校验和 provider 配置校验共同处理,不能误报为“缺少系统渠道”。
|
||||||
if !taskInputUsesCustomChannel(input) {
|
if !customChannelTask {
|
||||||
if err := s.validateSystemChannelModelSelection(input); err != nil {
|
if err := s.validateSystemChannelModelSelection(input); err != nil {
|
||||||
return nil, input, err
|
return nil, input, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,26 @@ func TestResolveTaskModelSelectionAllowsExplicitSystemChannelWhenFrontendModelsE
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestResolveTaskModelSelectionAllowsCustomImageChannelWhenFrontendModelsEnabled(t *testing.T) {
|
||||||
|
input := map[string]any{
|
||||||
|
"mode": "image",
|
||||||
|
"config": map[string]any{
|
||||||
|
"baseUrl": "https://images.example.com/v1",
|
||||||
|
"apiKey": "custom-key",
|
||||||
|
"interfaceType": "openai-image",
|
||||||
|
"model": "custom-image-model",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
routed, resolvedInput, err := (&Service{}).resolveTaskModelSelection(input, "", "canvas_image", "image", true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("resolveTaskModelSelection() error = %v", err)
|
||||||
|
}
|
||||||
|
if routed != nil || resolvedInput["config"] == nil {
|
||||||
|
t.Fatalf("resolveTaskModelSelection() routed = %#v, input = %#v", routed, resolvedInput)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestResolveTaskModelSelectionStillRequiresLogicalModelWithoutExplicitSystemChannel(t *testing.T) {
|
func TestResolveTaskModelSelectionStillRequiresLogicalModelWithoutExplicitSystemChannel(t *testing.T) {
|
||||||
_, _, err := (&Service{}).resolveTaskModelSelection(map[string]any{
|
_, _, err := (&Service{}).resolveTaskModelSelection(map[string]any{
|
||||||
"mode": "video",
|
"mode": "video",
|
||||||
|
|||||||
@@ -7,6 +7,19 @@ description: 影策后端核心持久化表与状态边界
|
|||||||
|
|
||||||
后端通过 GORM 管理 SQLite 与 PostgreSQL 表结构。服务启动时由 `backend/internal/database/schema.go` 执行迁移;业务写路径必须通过 service 和 repository 的状态约束,不能直接依赖前端状态。
|
后端通过 GORM 管理 SQLite 与 PostgreSQL 表结构。服务启动时由 `backend/internal/database/schema.go` 执行迁移;业务写路径必须通过 service 和 repository 的状态约束,不能直接依赖前端状态。
|
||||||
|
|
||||||
|
## 短剧分镜生产
|
||||||
|
|
||||||
|
| 表 | 用途 | 关键边界 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `shots` | 保存章节内稳定的镜头身份、排序和当前版本指针 | 不保存完整生成历史;`current_revision_id` 指向当前采用的分镜脚本版本 |
|
||||||
|
| `shot_revisions` | 保存画面、动作、台词、景别、机位、运镜、提示词和动作节拍 | 每次编辑创建新版本;历史版本不可被静默覆盖 |
|
||||||
|
| `shot_asset_references` | 将镜头绑定到具体资产版本 | 修改引用时只使该镜头的下游产物过期,不影响其他镜头 |
|
||||||
|
| `shot_artifacts` | 保存分镜图、动作预演、首尾帧、视频等版本化产物 | `selected` 表示当前采用版本;上游变化后状态转为 `stale`,历史资源继续保留 |
|
||||||
|
| `production_task_links` | 显式记录生成任务所属的领域项目、画布、章节、镜头和工作流步骤 | `Task.project_id` 仍兼容画布任务身份,不再用它单独推断短剧领域归属 |
|
||||||
|
| `workflow_template_versions` / `workflow_instances` / `workflow_step_instances` | 保存短剧生产模板和项目、章节实例 | 短剧分镜工作流 v2 顺序为剧情、资产、分镜、动作预演、视频、交付 |
|
||||||
|
|
||||||
|
短剧项目状态以这些领域表为准。自由画布可以承载探索节点,但画布 metadata 不作为生产完成度、镜头版本或交付可用性的真相源。
|
||||||
|
|
||||||
## 模型渠道与目录
|
## 模型渠道与目录
|
||||||
|
|
||||||
| 表 | 用途 | 关键边界 |
|
| 表 | 用途 | 关键边界 |
|
||||||
|
|||||||
@@ -5,6 +5,17 @@ description: 影策已实现功能的手工验证清单与未确认边界
|
|||||||
|
|
||||||
# 待测试
|
# 待测试
|
||||||
|
|
||||||
|
## 短剧分镜工作流 v2
|
||||||
|
|
||||||
|
- [x] 后端新增镜头版本、镜头产物和生产任务上下文;分镜修改与资产版本变更会局部将旧产物标记为 `stale`,专项测试通过。
|
||||||
|
- [x] 短剧工作流调整为“剧情与章节 → 资产拆分 → 分镜脚本 → 黑白动作预演 → 视频生成 → 交付与打包”,旧 v1 实例保留,新章节使用 v2。
|
||||||
|
- [x] 项目工作台新增独立分镜工作流路由,支持初始化章节流程、新增镜头、保存分镜版本、绑定资产版本、查看预演/视频版本和交付缺失状态;前端生产构建通过。
|
||||||
|
- [ ] 在真实项目中初始化一个已有章节,确认不会误用旧 v1 工作流,刷新和切换章节后阶段、镜头和当前版本保持一致。
|
||||||
|
- [ ] 连续保存同一镜头多个版本并绑定不同资产版本,确认只有该镜头的动作预演和视频转为过期,其他镜头不受影响。
|
||||||
|
- [ ] 使用画布任务和项目任务分别登记镜头产物,确认 `production_task_links` 正确记录 Project、Canvas、Unit、Shot 和 WorkflowStep,且账号归属校验有效。
|
||||||
|
- [ ] 在浅色、深色、窄屏和常规桌面验证阶段导航、镜头列表、表单、检查器、媒体预览和长章节内容滚动。
|
||||||
|
- [ ] 当前“资产拆分 AI、多宫格生成提交、批量视频任务、后端交付包”仍是后续阶段,界面不得显示为已完成或可用。
|
||||||
|
|
||||||
## 画布生成结果命名
|
## 画布生成结果命名
|
||||||
|
|
||||||
- [x] 快捷键复制节点生成图片后保留 `_copyN`,参数变体生成图片后保留 `A/B/C/D` 版本标识;批量输出追加结果序号。
|
- [x] 快捷键复制节点生成图片后保留 `_copyN`,参数变体生成图片后保留 `A/B/C/D` 版本标识;批量输出追加结果序号。
|
||||||
@@ -90,6 +101,14 @@ description: 影策已实现功能的手工验证清单与未确认边界
|
|||||||
- [ ] 在画布中分别选择按次图片模型、按秒视频模型和前台逻辑模型,确认修改数量、时长、分辨率和参考素材后价格立即更新且与实际账单一致。
|
- [ ] 在画布中分别选择按次图片模型、按秒视频模型和前台逻辑模型,确认修改数量、时长、分辨率和参考素材后价格立即更新且与实际账单一致。
|
||||||
- [ ] 在浅色/深色主题及生成中、禁用状态下确认胶囊价格可读、圆形操作区清晰且不挤压模型与参数控件。
|
- [ ] 在浅色/深色主题及生成中、禁用状态下确认胶囊价格可读、圆形操作区清晰且不挤压模型与参数控件。
|
||||||
|
|
||||||
|
## 系统渠道默认积分价格
|
||||||
|
|
||||||
|
- [x] 新建渠道模型默认使用“所有规格统一价格”,管理员只需填写一次积分;1K/2K/4K、画幅和生成方式差异定价收进可选的“按规格定价”。
|
||||||
|
- [x] 系统渠道直连、前台逻辑模型按渠道计价和失败切换线路均按任务实际规格匹配价格档;缺失价格档 ID 不再被误转成 `"<nil>"`。
|
||||||
|
- [x] 后端全量测试、价格表单专项测试和前端生产构建通过。
|
||||||
|
- [ ] 在 `/admin/channels` 新建图片和视频模型,仅填写统一价格后分别生成不同质量、尺寸、分辨率和时长,确认都命中默认价格。
|
||||||
|
- [ ] 在默认价格之外新增一个 2K 或指定分辨率价格,确认精确规格优先、其他规格继续使用默认价格;关闭“可供用户使用”后该档不再参与匹配。
|
||||||
|
|
||||||
## 系统渠道模型 Logo
|
## 系统渠道模型 Logo
|
||||||
|
|
||||||
- [x] 后端保存系统渠道模型 Logo,并通过脱敏模型目录下发;前端类型检查与生产构建通过。
|
- [x] 后端保存系统渠道模型 Logo,并通过脱敏模型目录下发;前端类型检查与生产构建通过。
|
||||||
@@ -405,3 +424,23 @@ description: 影策已实现功能的手工验证清单与未确认边界
|
|||||||
- [ ] 打开快捷键中心,分别搜索“粘贴”“缩放”和“Alt L”,确认结果与分类计数正确,清空搜索后恢复完整列表。
|
- [ ] 打开快捷键中心,分别搜索“粘贴”“缩放”和“Alt L”,确认结果与分类计数正确,清空搜索后恢复完整列表。
|
||||||
- [ ] 确认浅色/深色主题下标题、分类选中态、搜索焦点环、键帽和滚动区域清晰可见。
|
- [ ] 确认浅色/深色主题下标题、分类选中态、搜索焦点环、键帽和滚动区域清晰可见。
|
||||||
- [ ] 在窄窗口确认分类可横向滚动、快捷键列表改为单列,弹窗不超出视口且长内容仅在列表区滚动。
|
- [ ] 在窄窗口确认分类可横向滚动、快捷键列表改为单列,弹窗不超出视口且长内容仅在列表区滚动。
|
||||||
|
|
||||||
|
## 短剧分镜工作流工作台
|
||||||
|
|
||||||
|
短剧工作流已按镜头生产重构为单层项目工作台,并将资产绑定、镜头编辑、生成预览和整集镜头轨道放入同一视口;以下场景仍需用户在真实项目数据与模型渠道下确认:
|
||||||
|
|
||||||
|
- [x] 工作流路由保留系统全局侧栏和顶栏;项目头部压缩为单行,移除额外六阶段横条,项目导航入口改为“分镜制作”。
|
||||||
|
- [x] 项目详情 API 对旧后端可能缺失的工作流、镜头版本、产物、引用、候选资产和文件夹数组统一规范为空数组;使用缺失这些字段的响应完成浏览器复现,页面正常加载且控制台无错误。
|
||||||
|
- [x] 未初始化章节不再显示阻断式居中空态;镜头编辑器可直接查看和保存,首次真实生成时按当前章节自动建立工作流记录。
|
||||||
|
- [x] 分镜脚本、黑白动作预演、视频生成共用资产栏、镜头表单、预览/历史栏和底部镜头轨道;前端生产构建通过。
|
||||||
|
- [x] 模型、时长、画幅、分辨率和镜头语言合并为默认折叠的“生成设置”,模型提示词与接戏信息合并为默认折叠的“生成补充”;折叠摘要会显示当前关键参数,浏览器展开/收起验证通过。
|
||||||
|
- [x] 删除项目头部重复且发生重叠的“新增分镜”入口,只保留底部镜头轨道中的新增卡片;1280px 与 1680px 浏览器检查无横向溢出,系统全局侧栏保持可见。
|
||||||
|
- [x] 右侧产物阶段从标题旁的隐藏下拉框改为常驻三段切换,分镜图、动作预演和镜头视频始终可见;1280px 与 1680px 下切换路由、阶段文案、最新/历史状态和全局侧栏浏览器验证通过。
|
||||||
|
- [x] 底部镜头卡片取消悬浮上移和向外扩张的选中阴影,改为不改变坐标与尺寸的底色、边框和内描边反馈;右侧移除“复制参数”“入素材库”,仅保留并排的重新生成与下载,1280px 浏览器悬浮和布局验证通过。
|
||||||
|
- [x] 镜头编辑器改为脚本优先顺序:镜头名称与画面、镜头资产、表演与动作、对白/旁白优先展示,生成规格和模型补充保持折叠;字段统一为画幅、镜头时长、机位角度、运镜方式、排除内容和接戏备注等生产术语。
|
||||||
|
- [x] 编辑器标题实时反映镜头名称与“已保存/有未保存修改/保存中”状态;无修改时禁止重复保存,切换或新增镜头前会拦截未保存修改。浏览器交互验证通过。
|
||||||
|
- [x] 镜头保存使用真实版本写接口;资产点击绑定具体版本;生成统一进入后端任务生命周期,成功后登记对应镜头产物;下载使用带登录凭据的资源接口。
|
||||||
|
- [ ] 使用包含角色、场景、道具和画风的真实项目,确认左侧分类、绑定状态、参考素材标签和镜头切换保持一致。
|
||||||
|
- [ ] 配置一个图片模型和一个视频模型,分别生成分镜预览、动作预演与视频,确认任务中心、镜头历史、最新预览和阶段状态同步更新。
|
||||||
|
- [ ] 在浅色/深色主题及 1280px、1050px、760px 三个断点检查项目导航、表单滚动、右侧预览和底部镜头轨道,确认没有遮挡或不可达控件。
|
||||||
|
- [ ] 验证下载视频、复制生成参数、将任务物化产物加入项目素材库、章节切换与新增分镜;确认失败任务展示真实错误且不会伪造产物成功。
|
||||||
@@ -4,6 +4,7 @@ import { useLocation, useNavigate } from "react-router";
|
|||||||
import { ModelSetupGuide } from "@/components/layout/model-setup-guide";
|
import { ModelSetupGuide } from "@/components/layout/model-setup-guide";
|
||||||
import { WorkspaceCommandPalette } from "@/components/layout/workspace-command-palette";
|
import { WorkspaceCommandPalette } from "@/components/layout/workspace-command-palette";
|
||||||
import { WorkspaceSidebarNav } from "@/components/layout/workspace-sidebar-nav";
|
import { WorkspaceSidebarNav } from "@/components/layout/workspace-sidebar-nav";
|
||||||
|
import { readWorkspaceSidebarCollapsed, writeWorkspaceSidebarCollapsed } from "@/components/layout/workspace-sidebar-state";
|
||||||
import { WorkspaceTopBar } from "@/components/layout/workspace-top-bar";
|
import { WorkspaceTopBar } from "@/components/layout/workspace-top-bar";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { isSpatialWorkbenchPath } from "@/lib/workspace-routes";
|
import { isSpatialWorkbenchPath } from "@/lib/workspace-routes";
|
||||||
@@ -12,7 +13,7 @@ export function AppWorkspaceShell({ children }: { children: ReactNode }) {
|
|||||||
const { pathname } = useLocation();
|
const { pathname } = useLocation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [mobileSidebarExpanded, setMobileSidebarExpanded] = useState(false);
|
const [mobileSidebarExpanded, setMobileSidebarExpanded] = useState(false);
|
||||||
const [desktopSidebarCollapsed, setDesktopSidebarCollapsed] = useState(false);
|
const [desktopSidebarCollapsed, setDesktopSidebarCollapsed] = useState(readWorkspaceSidebarCollapsed);
|
||||||
const [paletteOpen, setPaletteOpen] = useState(false);
|
const [paletteOpen, setPaletteOpen] = useState(false);
|
||||||
|
|
||||||
const hideChrome = pathname.startsWith("/admin") || /^\/canvas\/[^/]+/.test(pathname);
|
const hideChrome = pathname.startsWith("/admin") || /^\/canvas\/[^/]+/.test(pathname);
|
||||||
@@ -27,7 +28,16 @@ export function AppWorkspaceShell({ children }: { children: ReactNode }) {
|
|||||||
setMobileSidebarExpanded((current) => !current);
|
setMobileSidebarExpanded((current) => !current);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setDesktopSidebarCollapsed((current) => !current);
|
setDesktopSidebarCollapsed((current) => {
|
||||||
|
const next = !current;
|
||||||
|
writeWorkspaceSidebarCollapsed(next);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const expandDesktopSidebar = () => {
|
||||||
|
setDesktopSidebarCollapsed(false);
|
||||||
|
writeWorkspaceSidebarCollapsed(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleNavClick = () => {
|
const handleNavClick = () => {
|
||||||
@@ -75,7 +85,7 @@ export function AppWorkspaceShell({ children }: { children: ReactNode }) {
|
|||||||
collapsed={desktopSidebarCollapsed}
|
collapsed={desktopSidebarCollapsed}
|
||||||
onNavigate={handleNavClick}
|
onNavigate={handleNavClick}
|
||||||
onOpenSearch={() => setPaletteOpen(true)}
|
onOpenSearch={() => setPaletteOpen(true)}
|
||||||
onExpand={() => setDesktopSidebarCollapsed(false)}
|
onExpand={expandDesktopSidebar}
|
||||||
/>
|
/>
|
||||||
</aside>
|
</aside>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1 +1,29 @@
|
|||||||
export const WORKSPACE_SIDEBAR_STORAGE_KEY = "infinite-canvas:workspace-sidebar-collapsed";
|
export const WORKSPACE_SIDEBAR_STORAGE_KEY = "infinite-canvas:workspace-sidebar-collapsed";
|
||||||
|
|
||||||
|
type WorkspaceSidebarStorage = Pick<Storage, "getItem" | "setItem">;
|
||||||
|
|
||||||
|
function workspaceSidebarStorage(storage?: WorkspaceSidebarStorage) {
|
||||||
|
if (storage) return storage;
|
||||||
|
if (typeof window === "undefined") return undefined;
|
||||||
|
try {
|
||||||
|
return window.localStorage;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readWorkspaceSidebarCollapsed(storage?: WorkspaceSidebarStorage) {
|
||||||
|
try {
|
||||||
|
return workspaceSidebarStorage(storage)?.getItem(WORKSPACE_SIDEBAR_STORAGE_KEY) === "1";
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeWorkspaceSidebarCollapsed(collapsed: boolean, storage?: WorkspaceSidebarStorage) {
|
||||||
|
try {
|
||||||
|
workspaceSidebarStorage(storage)?.setItem(WORKSPACE_SIDEBAR_STORAGE_KEY, collapsed ? "1" : "0");
|
||||||
|
} catch {
|
||||||
|
// localStorage 不可用时保留当前内存状态,不能阻断侧栏交互。
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import { modelProtocolCapability, modelProtocolDefinition, modelProtocolLabel, m
|
|||||||
import { fetchPluginProviderCatalog } from "@/services/api/plugin-catalog";
|
import { fetchPluginProviderCatalog } from "@/services/api/plugin-catalog";
|
||||||
import { createAdminChannelModel, deleteAdminChannelModel, fetchAdminChannelModels, listAdminChannelModels, testAdminChannelModel, updateAdminChannelModel, type ChannelModel, type ChannelModelPriceTier } from "@/services/api/wallet";
|
import { createAdminChannelModel, deleteAdminChannelModel, fetchAdminChannelModels, listAdminChannelModels, testAdminChannelModel, updateAdminChannelModel, type ChannelModel, type ChannelModelPriceTier } from "@/services/api/wallet";
|
||||||
import type { ModelChannel } from "@/stores/use-config-store";
|
import type { ModelChannel } from "@/stores/use-config-store";
|
||||||
|
import { defaultPriceTier, legacyPriceTierToForm, priceTierResolutionFromForm, priceTierToForm, priceTierVideoSecondsFromForm, skuSelectorFromForm, type PriceTierFormValues } from "./channel-model-price-tier-form";
|
||||||
import { AdminPageFrame } from "./admin-shell";
|
import { AdminPageFrame } from "./admin-shell";
|
||||||
import { AdminDataTable, AdminFilterChip, AdminStatusBadge } from "./admin-ui";
|
import { AdminDataTable, AdminFilterChip, AdminStatusBadge } from "./admin-ui";
|
||||||
|
|
||||||
@@ -30,23 +31,6 @@ type FormValues = {
|
|||||||
capabilityConfig?: ModelCapabilityConfig;
|
capabilityConfig?: ModelCapabilityConfig;
|
||||||
};
|
};
|
||||||
|
|
||||||
type PriceTierFormValues = {
|
|
||||||
operation: string;
|
|
||||||
quality: string;
|
|
||||||
size: string;
|
|
||||||
resolution: string;
|
|
||||||
videoSeconds: number;
|
|
||||||
imageCount: number;
|
|
||||||
providerModelKey?: string;
|
|
||||||
billingMode: ChannelModel["billingMode"];
|
|
||||||
unitPrice: number;
|
|
||||||
inputTokenPrice: number;
|
|
||||||
outputTokenPrice: number;
|
|
||||||
cachedTokenPrice: number;
|
|
||||||
priceConfigured: boolean;
|
|
||||||
enabled: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function ChannelModelManager({ channel, onClose, onChanged }: { channel: ModelChannel; onClose: () => void; onChanged: () => void | Promise<void> }) {
|
export function ChannelModelManager({ channel, onClose, onChanged }: { channel: ModelChannel; onClose: () => void; onChanged: () => void | Promise<void> }) {
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const [items, setItems] = useState<ChannelModel[]>([]);
|
const [items, setItems] = useState<ChannelModel[]>([]);
|
||||||
@@ -69,6 +53,8 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
|||||||
const providerModelKey = Form.useWatch("providerModelKey", form) || "";
|
const providerModelKey = Form.useWatch("providerModelKey", form) || "";
|
||||||
const capabilityConfig = Form.useWatch("capabilityConfig", form);
|
const capabilityConfig = Form.useWatch("capabilityConfig", form);
|
||||||
const modelEnabled = Form.useWatch("enabled", form) !== false;
|
const modelEnabled = Form.useWatch("enabled", form) !== false;
|
||||||
|
const priceTiers = Form.useWatch("priceTiers", form) || [];
|
||||||
|
const hasDefaultPriceTier = priceTiers.some((tier) => tier.matchMode === "default");
|
||||||
|
|
||||||
const reload = async () => {
|
const reload = async () => {
|
||||||
if (!channel) return;
|
if (!channel) return;
|
||||||
@@ -84,7 +70,9 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void reload();
|
void reload();
|
||||||
void fetchPluginProviderCatalog("admin.system-channel").then(setAvailableProtocols).catch(() => setAvailableProtocols([]));
|
void fetchPluginProviderCatalog("admin.system-channel")
|
||||||
|
.then(setAvailableProtocols)
|
||||||
|
.catch(() => setAvailableProtocols([]));
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
setEditorOpen(false);
|
setEditorOpen(false);
|
||||||
setKeyword("");
|
setKeyword("");
|
||||||
@@ -161,8 +149,8 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
|||||||
protocol: values.protocol,
|
protocol: values.protocol,
|
||||||
priceTiers: values.priceTiers.map((tier) => ({
|
priceTiers: values.priceTiers.map((tier) => ({
|
||||||
selector: skuSelectorFromForm(values.capability, tier),
|
selector: skuSelectorFromForm(values.capability, tier),
|
||||||
resolution: values.capability === "video" ? tier.resolution || "*" : "*",
|
resolution: priceTierResolutionFromForm(values.capability, tier),
|
||||||
videoSeconds: values.capability === "video" ? Number(tier.videoSeconds || 0) : 0,
|
videoSeconds: priceTierVideoSecondsFromForm(values.capability, tier),
|
||||||
providerModelKey: tier.providerModelKey?.trim() || upstreamModel,
|
providerModelKey: tier.providerModelKey?.trim() || upstreamModel,
|
||||||
billingMode: tier.billingMode,
|
billingMode: tier.billingMode,
|
||||||
unitPriceMicrocredits: Math.round((tier.unitPrice || 0) * 1_000_000),
|
unitPriceMicrocredits: Math.round((tier.unitPrice || 0) * 1_000_000),
|
||||||
@@ -550,7 +538,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<section className="admin-form-section admin-model-editor-section">
|
<section className="admin-form-section admin-model-editor-section">
|
||||||
<SectionHeading title="规格价格档" description="按请求条件匹配上游模型与计费规则。" />
|
<SectionHeading title="用户积分价格" description="默认只需填写一个统一价格;需要区分生成方式、质量或尺寸时,再添加规格价格。" />
|
||||||
<div className="admin-model-editor-section-content">
|
<div className="admin-model-editor-section-content">
|
||||||
<Form.List
|
<Form.List
|
||||||
name="priceTiers"
|
name="priceTiers"
|
||||||
@@ -558,6 +546,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
|||||||
{
|
{
|
||||||
validator: async (_, value) => {
|
validator: async (_, value) => {
|
||||||
if (!value?.length) throw new Error("请至少配置一个价格档");
|
if (!value?.length) throw new Error("请至少配置一个价格档");
|
||||||
|
if (value.filter((tier: PriceTierFormValues) => tier.matchMode === "default").length > 1) throw new Error("只能配置一个所有规格统一价格");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
@@ -576,8 +565,8 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
|||||||
onRemove={() => remove(field.name)}
|
onRemove={() => remove(field.name)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
<Button className="admin-model-editor-add-tier" type="dashed" block icon={<Plus className="size-4" />} onClick={() => add(defaultPriceTier())}>
|
<Button className="admin-model-editor-add-tier" type="dashed" block icon={<Plus className="size-4" />} onClick={() => add(defaultPriceTier(hasDefaultPriceTier ? "advanced" : "default"))}>
|
||||||
新增价格档
|
{hasDefaultPriceTier ? "新增规格价格" : "新增统一默认价格"}
|
||||||
</Button>
|
</Button>
|
||||||
<Form.ErrorList errors={errors} />
|
<Form.ErrorList errors={errors} />
|
||||||
</div>
|
</div>
|
||||||
@@ -630,6 +619,9 @@ function PriceTierFields({
|
|||||||
onRemove: () => void;
|
onRemove: () => void;
|
||||||
}) {
|
}) {
|
||||||
const billingMode = Form.useWatch(["priceTiers", index, "billingMode"], form) || "fixed_request";
|
const billingMode = Form.useWatch(["priceTiers", index, "billingMode"], form) || "fixed_request";
|
||||||
|
const matchMode = Form.useWatch(["priceTiers", index, "matchMode"], form) || "default";
|
||||||
|
const priceConfigured = Form.useWatch(["priceTiers", index, "priceConfigured"], form) !== false;
|
||||||
|
const tierEnabled = Form.useWatch(["priceTiers", index, "enabled"], form) !== false;
|
||||||
const video = capabilityConfig?.video;
|
const video = capabilityConfig?.video;
|
||||||
const resolutionOptions = video?.resolutions || [];
|
const resolutionOptions = video?.resolutions || [];
|
||||||
const durationOptions = video?.duration.selection === "enum" ? video.duration.values || [] : [];
|
const durationOptions = video?.duration.selection === "enum" ? video.duration.values || [] : [];
|
||||||
@@ -640,8 +632,8 @@ function PriceTierFields({
|
|||||||
<div className="admin-price-tier-card">
|
<div className="admin-price-tier-card">
|
||||||
<div className="admin-price-tier-card-header">
|
<div className="admin-price-tier-card-header">
|
||||||
<div>
|
<div>
|
||||||
<div className="text-sm font-medium">价格档 {ordinal}</div>
|
<div className="text-sm font-medium">{matchMode === "default" ? "默认价格" : `规格价格 ${ordinal}`}</div>
|
||||||
<div className="mt-0.5 text-[var(--fs-tiny)] text-foreground/45">请求按以下条件命中后,使用本档模型与价格。</div>
|
<div className="mt-0.5 text-[var(--fs-tiny)] text-foreground/45">{matchMode === "default" ? "匹配所有生成请求,保存后即可供用户使用。" : "精确条件优先于默认价格。"}</div>
|
||||||
</div>
|
</div>
|
||||||
<Button type="text" danger aria-label={`删除价格档 ${ordinal}`} icon={<Trash2 className="size-3.5" />} onClick={onRemove}>
|
<Button type="text" danger aria-label={`删除价格档 ${ordinal}`} icon={<Trash2 className="size-3.5" />} onClick={onRemove}>
|
||||||
删除
|
删除
|
||||||
@@ -650,48 +642,61 @@ function PriceTierFields({
|
|||||||
<div className="admin-price-tier-card-body">
|
<div className="admin-price-tier-card-body">
|
||||||
<div className="admin-price-tier-block admin-price-tier-match-block">
|
<div className="admin-price-tier-block admin-price-tier-match-block">
|
||||||
<div className="admin-price-tier-block-title">
|
<div className="admin-price-tier-block-title">
|
||||||
<span>01</span> 匹配条件
|
<span>01</span> 价格适用范围
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-price-tier-match-grid">
|
<Form.Item className="mb-3" name={[index, "matchMode"]} label="定价方式" rules={[{ required: true }]}>
|
||||||
<Form.Item className="mb-0" name={[index, "operation"]} label="生成方式" rules={[{ required: true, message: "请选择生成方式" }]}>
|
<Segmented
|
||||||
<Select options={operationOptions(capability)} />
|
block
|
||||||
</Form.Item>
|
options={[
|
||||||
{isVideo ? (
|
{ label: "所有规格统一价格", value: "default" },
|
||||||
<Form.Item className="mb-0" name={[index, "resolution"]} label="分辨率" rules={[{ required: true, message: "请选择分辨率" }]}>
|
{ label: "按规格定价", value: "advanced" },
|
||||||
<Select options={[{ label: "任意分辨率", value: "*" }, ...resolutionOptions.map((value) => ({ label: value.toUpperCase(), value }))]} />
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
{matchMode === "default" ? (
|
||||||
|
<div className="rounded-md border border-border/70 bg-muted/25 px-3 py-2.5 text-xs leading-5 text-foreground/60">用户选择任意生成方式、质量和尺寸时,都使用这档价格。新增规格价格后,精确规则优先,默认价格负责兜底。</div>
|
||||||
|
) : (
|
||||||
|
<div className="admin-price-tier-match-grid">
|
||||||
|
<Form.Item className="mb-0" name={[index, "operation"]} label="生成方式" rules={[{ required: true, message: "请选择生成方式" }]}>
|
||||||
|
<Select options={operationOptions(capability)} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
) : null}
|
{isVideo ? (
|
||||||
{isVideo ? (
|
<Form.Item className="mb-0" name={[index, "resolution"]} label="分辨率" rules={[{ required: true, message: "请选择分辨率" }]}>
|
||||||
<Form.Item className="mb-0" name={[index, "videoSeconds"]} label="时长" rules={[{ required: true, message: "请输入时长" }]}>
|
<Select options={[{ label: "任意分辨率", value: "*" }, ...resolutionOptions.map((value) => ({ label: value.toUpperCase(), value }))]} />
|
||||||
{durationOptions.length ? <Select options={[{ label: "任意时长", value: 0 }, ...durationOptions.map((value) => ({ label: `${value} 秒`, value }))]} /> : <InputNumber className="w-full" min={0} precision={0} />}
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isVideo ? (
|
||||||
|
<Form.Item className="mb-0" name={[index, "videoSeconds"]} label="时长" rules={[{ required: true, message: "请输入时长" }]}>
|
||||||
|
{durationOptions.length ? <Select options={[{ label: "任意时长", value: 0 }, ...durationOptions.map((value) => ({ label: `${value} 秒`, value }))]} /> : <InputNumber className="w-full" min={0} precision={0} />}
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isVideo ? (
|
||||||
|
<Form.Item className="mb-0" name={[index, "imageCount"]} label="参考图数量" rules={[{ required: true, message: "请输入参考图数量" }]}>
|
||||||
|
<InputNumber className="w-full" min={0} max={9} precision={0} placeholder="0 表示任意数量" />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isImage ? (
|
||||||
|
<Form.Item className="mb-0" name={[index, "quality"]} label="质量/分辨率" rules={[{ required: true, message: "请选择质量或分辨率" }]}>
|
||||||
|
<Select
|
||||||
|
options={[
|
||||||
|
{ label: "任意质量", value: "*" },
|
||||||
|
{ label: "1K", value: "1k" },
|
||||||
|
{ label: "2K", value: "2k" },
|
||||||
|
{ label: "4K", value: "4k" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
{isImage ? (
|
||||||
|
<Form.Item className="mb-0" name={[index, "size"]} label="画幅/尺寸">
|
||||||
|
<Input placeholder="任意,或 1:1、16:9、1024x1024" />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
<Form.Item className="admin-price-tier-upstream mb-0" name={[index, "providerModelKey"]} label="命中后使用的上游模型 ID">
|
||||||
|
<Input placeholder="留空则使用模型默认上游 ID" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
) : null}
|
</div>
|
||||||
{isVideo ? (
|
)}
|
||||||
<Form.Item className="mb-0" name={[index, "imageCount"]} label="参考图数量" rules={[{ required: true, message: "请输入参考图数量" }]}>
|
|
||||||
<InputNumber className="w-full" min={0} max={9} precision={0} placeholder="0 表示任意数量" />
|
|
||||||
</Form.Item>
|
|
||||||
) : null}
|
|
||||||
{isImage ? (
|
|
||||||
<Form.Item className="mb-0" name={[index, "quality"]} label="质量/分辨率" rules={[{ required: true, message: "请选择质量或分辨率" }]}>
|
|
||||||
<Select
|
|
||||||
options={[
|
|
||||||
{ label: "任意质量", value: "*" },
|
|
||||||
{ label: "1K", value: "1k" },
|
|
||||||
{ label: "2K", value: "2k" },
|
|
||||||
{ label: "4K", value: "4k" },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
) : null}
|
|
||||||
{isImage ? (
|
|
||||||
<Form.Item className="mb-0" name={[index, "size"]} label="画幅/尺寸">
|
|
||||||
<Input placeholder="任意,或 1:1、16:9、1024x1024" />
|
|
||||||
</Form.Item>
|
|
||||||
) : null}
|
|
||||||
<Form.Item className="admin-price-tier-upstream mb-0" name={[index, "providerModelKey"]} label="命中后使用的上游模型 ID">
|
|
||||||
<Input placeholder="留空则使用模型默认上游 ID" />
|
|
||||||
</Form.Item>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="admin-price-tier-block admin-price-tier-billing-block">
|
<div className="admin-price-tier-block admin-price-tier-billing-block">
|
||||||
<div className="admin-price-tier-block-title">
|
<div className="admin-price-tier-block-title">
|
||||||
@@ -731,24 +736,26 @@ function PriceTierFields({
|
|||||||
<InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} />
|
<InputNumber className="w-full" min={0} max={1_000_000} precision={6} step={0.1} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
)}
|
)}
|
||||||
<div className="admin-price-tier-controls flex items-center gap-6">
|
<div className="admin-price-tier-controls">
|
||||||
|
<Form.Item name={[index, "priceConfigured"]} hidden valuePropName="checked">
|
||||||
|
<Switch />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[index, "enabled"]} hidden valuePropName="checked">
|
||||||
|
<Switch />
|
||||||
|
</Form.Item>
|
||||||
<div className="admin-price-tier-toggle">
|
<div className="admin-price-tier-toggle">
|
||||||
<div>
|
<div>
|
||||||
<strong>价格已配置</strong>
|
<strong>可供用户使用</strong>
|
||||||
<span>允许按此价格计费</span>
|
<span>关闭后保留配置,但用户请求不再匹配这档价格</span>
|
||||||
</div>
|
</div>
|
||||||
<Form.Item name={[index, "priceConfigured"]} noStyle valuePropName="checked">
|
<Switch
|
||||||
<Switch aria-label="价格已配置" />
|
aria-label="可供用户使用"
|
||||||
</Form.Item>
|
checked={priceConfigured && tierEnabled}
|
||||||
</div>
|
onChange={(checked) => {
|
||||||
<div className="admin-price-tier-toggle">
|
form.setFieldValue(["priceTiers", index, "priceConfigured"], checked);
|
||||||
<div>
|
form.setFieldValue(["priceTiers", index, "enabled"], checked);
|
||||||
<strong>启用价格档</strong>
|
}}
|
||||||
<span>允许参与请求匹配</span>
|
/>
|
||||||
</div>
|
|
||||||
<Form.Item name={[index, "enabled"]} noStyle valuePropName="checked">
|
|
||||||
<Switch aria-label="启用价格档" />
|
|
||||||
</Form.Item>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -758,63 +765,6 @@ function PriceTierFields({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function defaultPriceTier(): PriceTierFormValues {
|
|
||||||
return {
|
|
||||||
operation: "*",
|
|
||||||
quality: "*",
|
|
||||||
size: "*",
|
|
||||||
resolution: "*",
|
|
||||||
videoSeconds: 0,
|
|
||||||
imageCount: 0,
|
|
||||||
providerModelKey: "",
|
|
||||||
billingMode: "fixed_request",
|
|
||||||
unitPrice: 0,
|
|
||||||
inputTokenPrice: 0,
|
|
||||||
outputTokenPrice: 0,
|
|
||||||
cachedTokenPrice: 0,
|
|
||||||
priceConfigured: true,
|
|
||||||
enabled: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function priceTierToForm(tier: ChannelModelPriceTier): PriceTierFormValues {
|
|
||||||
return {
|
|
||||||
operation: tier.selector?.operation || "*",
|
|
||||||
quality: tier.selector?.quality || "*",
|
|
||||||
size: tier.selector?.size || "*",
|
|
||||||
resolution: tier.resolution || "*",
|
|
||||||
videoSeconds: tier.videoSeconds || 0,
|
|
||||||
imageCount: Number(tier.selector?.imageCount || 0),
|
|
||||||
providerModelKey: tier.providerModelKey || "",
|
|
||||||
billingMode: tier.billingMode,
|
|
||||||
unitPrice: tier.unitPriceMicrocredits / 1_000_000,
|
|
||||||
inputTokenPrice: tier.inputTokenPriceMicrocredits / 1_000_000,
|
|
||||||
outputTokenPrice: tier.outputTokenPriceMicrocredits / 1_000_000,
|
|
||||||
cachedTokenPrice: tier.cachedTokenPriceMicrocredits / 1_000_000,
|
|
||||||
priceConfigured: tier.priceConfigured,
|
|
||||||
enabled: tier.enabled,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function legacyPriceTierToForm(item: ChannelModel): PriceTierFormValues {
|
|
||||||
return {
|
|
||||||
operation: "*",
|
|
||||||
quality: "*",
|
|
||||||
size: "*",
|
|
||||||
resolution: "*",
|
|
||||||
videoSeconds: 0,
|
|
||||||
imageCount: 0,
|
|
||||||
providerModelKey: item.providerModelKey || "",
|
|
||||||
billingMode: item.billingMode,
|
|
||||||
unitPrice: item.unitPriceMicrocredits / 1_000_000,
|
|
||||||
inputTokenPrice: item.inputTokenPriceMicrocredits / 1_000_000,
|
|
||||||
outputTokenPrice: item.outputTokenPriceMicrocredits / 1_000_000,
|
|
||||||
cachedTokenPrice: item.cachedTokenPriceMicrocredits / 1_000_000,
|
|
||||||
priceConfigured: item.priceConfigured,
|
|
||||||
enabled: item.enabled,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function billingSummary(item: ChannelModel) {
|
function billingSummary(item: ChannelModel) {
|
||||||
const tiers = item.priceTiers?.filter((tier) => tier.enabled && tier.priceConfigured) || [];
|
const tiers = item.priceTiers?.filter((tier) => tier.enabled && tier.priceConfigured) || [];
|
||||||
if (!tiers.length) return <AdminStatusBadge label="未配置价格" tone="warning" />;
|
if (!tiers.length) return <AdminStatusBadge label="未配置价格" tone="warning" />;
|
||||||
@@ -855,21 +805,6 @@ function operationLabel(operation: string) {
|
|||||||
return ({ text_to_image: "文生图", image_to_image: "图生图", text_to_video: "文生视频", image_to_video: "图生视频", video_to_video: "视频生视频", text_generation: "文本生成" } as Record<string, string>)[operation] || operation;
|
return ({ text_to_image: "文生图", image_to_image: "图生图", text_to_video: "文生视频", image_to_video: "图生视频", video_to_video: "视频生视频", text_generation: "文本生成" } as Record<string, string>)[operation] || operation;
|
||||||
}
|
}
|
||||||
|
|
||||||
function skuSelectorFromForm(capability: EditableCapability, tier: PriceTierFormValues) {
|
|
||||||
const selector: Record<string, string> = {};
|
|
||||||
if (tier.operation && tier.operation !== "*") selector.operation = tier.operation;
|
|
||||||
if (capability === "video") {
|
|
||||||
if (tier.resolution && tier.resolution !== "*") selector.vquality = tier.resolution;
|
|
||||||
if (Number(tier.videoSeconds) > 0) selector.videoSeconds = String(Number(tier.videoSeconds));
|
|
||||||
if (Number(tier.imageCount) > 0) selector.imageCount = String(Number(tier.imageCount));
|
|
||||||
}
|
|
||||||
if (capability === "image") {
|
|
||||||
if (tier.quality && tier.quality !== "*") selector.quality = tier.quality;
|
|
||||||
if (tier.size && tier.size !== "*") selector.size = tier.size;
|
|
||||||
}
|
|
||||||
return selector;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatCredits(value: number) {
|
function formatCredits(value: number) {
|
||||||
return (value / 1_000_000).toLocaleString("zh-CN", { maximumFractionDigits: 6 });
|
return (value / 1_000_000).toLocaleString("zh-CN", { maximumFractionDigits: 6 });
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import type { ModelCapabilityChoice } from "@/components/model-protocol-picker";
|
||||||
|
import type { ChannelModel, ChannelModelPriceTier } from "@/services/api/wallet";
|
||||||
|
|
||||||
|
export type PriceTierMatchMode = "default" | "advanced";
|
||||||
|
|
||||||
|
export type PriceTierFormValues = {
|
||||||
|
matchMode: PriceTierMatchMode;
|
||||||
|
operation: string;
|
||||||
|
quality: string;
|
||||||
|
size: string;
|
||||||
|
resolution: string;
|
||||||
|
videoSeconds: number;
|
||||||
|
imageCount: number;
|
||||||
|
providerModelKey?: string;
|
||||||
|
billingMode: ChannelModel["billingMode"];
|
||||||
|
unitPrice: number;
|
||||||
|
inputTokenPrice: number;
|
||||||
|
outputTokenPrice: number;
|
||||||
|
cachedTokenPrice: number;
|
||||||
|
priceConfigured: boolean;
|
||||||
|
enabled: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function defaultPriceTier(matchMode: PriceTierMatchMode = "default"): PriceTierFormValues {
|
||||||
|
return {
|
||||||
|
matchMode,
|
||||||
|
operation: "*",
|
||||||
|
quality: "*",
|
||||||
|
size: "*",
|
||||||
|
resolution: "*",
|
||||||
|
videoSeconds: 0,
|
||||||
|
imageCount: 0,
|
||||||
|
providerModelKey: "",
|
||||||
|
billingMode: "fixed_request",
|
||||||
|
unitPrice: 0,
|
||||||
|
inputTokenPrice: 0,
|
||||||
|
outputTokenPrice: 0,
|
||||||
|
cachedTokenPrice: 0,
|
||||||
|
priceConfigured: true,
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function priceTierToForm(tier: ChannelModelPriceTier): PriceTierFormValues {
|
||||||
|
const selector = tier.selector || {};
|
||||||
|
const hasSpecificMatch = Object.values(selector).some((value) => value && value !== "*") || (tier.resolution && tier.resolution !== "*") || tier.videoSeconds > 0;
|
||||||
|
return {
|
||||||
|
matchMode: hasSpecificMatch ? "advanced" : "default",
|
||||||
|
operation: selector.operation || "*",
|
||||||
|
quality: selector.quality || "*",
|
||||||
|
size: selector.size || "*",
|
||||||
|
resolution: tier.resolution || "*",
|
||||||
|
videoSeconds: tier.videoSeconds || 0,
|
||||||
|
imageCount: Number(selector.imageCount || 0),
|
||||||
|
providerModelKey: tier.providerModelKey || "",
|
||||||
|
billingMode: tier.billingMode,
|
||||||
|
unitPrice: tier.unitPriceMicrocredits / 1_000_000,
|
||||||
|
inputTokenPrice: tier.inputTokenPriceMicrocredits / 1_000_000,
|
||||||
|
outputTokenPrice: tier.outputTokenPriceMicrocredits / 1_000_000,
|
||||||
|
cachedTokenPrice: tier.cachedTokenPriceMicrocredits / 1_000_000,
|
||||||
|
priceConfigured: tier.priceConfigured,
|
||||||
|
enabled: tier.enabled,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function legacyPriceTierToForm(item: ChannelModel): PriceTierFormValues {
|
||||||
|
return {
|
||||||
|
...defaultPriceTier(),
|
||||||
|
providerModelKey: item.providerModelKey || "",
|
||||||
|
billingMode: item.billingMode,
|
||||||
|
unitPrice: item.unitPriceMicrocredits / 1_000_000,
|
||||||
|
inputTokenPrice: item.inputTokenPriceMicrocredits / 1_000_000,
|
||||||
|
outputTokenPrice: item.outputTokenPriceMicrocredits / 1_000_000,
|
||||||
|
cachedTokenPrice: item.cachedTokenPriceMicrocredits / 1_000_000,
|
||||||
|
priceConfigured: item.priceConfigured,
|
||||||
|
enabled: item.enabled,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function skuSelectorFromForm(capability: ModelCapabilityChoice, tier: PriceTierFormValues) {
|
||||||
|
if (tier.matchMode !== "advanced") return {};
|
||||||
|
const selector: Record<string, string> = {};
|
||||||
|
if (tier.operation && tier.operation !== "*") selector.operation = tier.operation;
|
||||||
|
if (capability === "video") {
|
||||||
|
if (tier.resolution && tier.resolution !== "*") selector.vquality = tier.resolution;
|
||||||
|
if (Number(tier.videoSeconds) > 0) selector.videoSeconds = String(Number(tier.videoSeconds));
|
||||||
|
if (Number(tier.imageCount) > 0) selector.imageCount = String(Number(tier.imageCount));
|
||||||
|
}
|
||||||
|
if (capability === "image") {
|
||||||
|
if (tier.quality && tier.quality !== "*") selector.quality = tier.quality;
|
||||||
|
if (tier.size && tier.size !== "*") selector.size = tier.size;
|
||||||
|
}
|
||||||
|
return selector;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function priceTierResolutionFromForm(capability: ModelCapabilityChoice, tier: PriceTierFormValues) {
|
||||||
|
return capability === "video" && tier.matchMode === "advanced" ? tier.resolution || "*" : "*";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function priceTierVideoSecondsFromForm(capability: ModelCapabilityChoice, tier: PriceTierFormValues) {
|
||||||
|
return capability === "video" && tier.matchMode === "advanced" ? Number(tier.videoSeconds || 0) : 0;
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Alert, App, Button, Tooltip } from "antd";
|
import { Alert, App, Button, Select, Tooltip } from "antd";
|
||||||
import { ArrowLeft, BookOpenText, Images, LayoutDashboard, LayoutGrid, Plus, Settings2, type LucideIcon } from "lucide-react";
|
import { ArrowLeft, BookOpenText, Clapperboard, Images, LayoutDashboard, LayoutGrid, Plus, Settings2, type LucideIcon } from "lucide-react";
|
||||||
import { Link, Navigate, useNavigate, useParams } from "react-router";
|
import { Link, Navigate, useNavigate, useParams } from "react-router";
|
||||||
|
|
||||||
import { createCanvasProjectWithRemoteSync } from "@/services/user-data-sync";
|
import { createCanvasProjectWithRemoteSync } from "@/services/user-data-sync";
|
||||||
@@ -14,23 +14,25 @@ import ProjectCanvasesView from "./detail/canvases";
|
|||||||
import ProjectChaptersView from "./detail/chapters";
|
import ProjectChaptersView from "./detail/chapters";
|
||||||
import ProjectOverviewView from "./detail/overview";
|
import ProjectOverviewView from "./detail/overview";
|
||||||
import ProjectSettingsView from "./detail/settings";
|
import ProjectSettingsView from "./detail/settings";
|
||||||
|
import ProjectWorkflowView from "./detail/workflow";
|
||||||
|
|
||||||
type DetailView = "overview" | "chapters" | "canvases" | "assets" | "settings";
|
type DetailView = "overview" | "chapters" | "workflow" | "canvases" | "assets" | "settings";
|
||||||
|
|
||||||
const views: Array<{ key: DetailView; label: string; shortLabel: string; icon: LucideIcon }> = [
|
const views: Array<{ key: DetailView; label: string; shortLabel: string; icon: LucideIcon }> = [
|
||||||
{ key: "overview", label: "制作概览", shortLabel: "概览", icon: LayoutDashboard },
|
{ key: "overview", label: "制作概览", shortLabel: "概览", icon: LayoutDashboard },
|
||||||
{ key: "chapters", label: "剧情章节", shortLabel: "章节", icon: BookOpenText },
|
{ key: "chapters", label: "剧情章节", shortLabel: "章节", icon: BookOpenText },
|
||||||
|
{ key: "workflow", label: "分镜制作", shortLabel: "分镜", icon: Clapperboard },
|
||||||
{ key: "canvases", label: "项目画布", shortLabel: "画布", icon: LayoutGrid },
|
{ key: "canvases", label: "项目画布", shortLabel: "画布", icon: LayoutGrid },
|
||||||
{ key: "assets", label: "角色与资产", shortLabel: "资产", icon: Images },
|
{ key: "assets", label: "角色与资产", shortLabel: "资产", icon: Images },
|
||||||
{ key: "settings", label: "项目设置", shortLabel: "设置", icon: Settings2 },
|
{ key: "settings", label: "项目设置", shortLabel: "设置", icon: Settings2 },
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function ProjectDetailPage() {
|
export default function ProjectDetailPage() {
|
||||||
const { projectId = "", view, chapterId } = useParams();
|
const { projectId = "", view, chapterId, unitId, stage } = useParams();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { message } = App.useApp();
|
const { message } = App.useApp();
|
||||||
const activeView: DetailView = chapterId ? "chapters" : views.some((item) => item.key === view) ? view as DetailView : "overview";
|
const activeView: DetailView = unitId || view === "workflow" ? "workflow" : chapterId ? "chapters" : views.some((item) => item.key === view) ? view as DetailView : "overview";
|
||||||
const detail = useQuery({ queryKey: ["project", projectId], queryFn: () => getProject(projectId), enabled: Boolean(projectId), refetchOnMount: "always" });
|
const detail = useQuery({ queryKey: ["project", projectId], queryFn: () => getProject(projectId), enabled: Boolean(projectId), refetchOnMount: "always" });
|
||||||
const refreshProject = () => { void queryClient.invalidateQueries({ queryKey: ["project", projectId] }); void queryClient.invalidateQueries({ queryKey: ["projects"] }); };
|
const refreshProject = () => { void queryClient.invalidateQueries({ queryKey: ["project", projectId] }); void queryClient.invalidateQueries({ queryKey: ["projects"] }); };
|
||||||
const createCanvas = () => {
|
const createCanvas = () => {
|
||||||
@@ -63,36 +65,48 @@ export default function ProjectDetailPage() {
|
|||||||
navigate(`/canvas/${id}`);
|
navigate(`/canvas/${id}`);
|
||||||
}).catch((error) => message.error(error instanceof Error ? error.message : "画布创建失败"));
|
}).catch((error) => message.error(error instanceof Error ? error.message : "画布创建失败"));
|
||||||
};
|
};
|
||||||
|
|
||||||
if (detail.isLoading) return <WorkspacePage><WorkspaceLoadingState label="正在打开项目工作台" detail="读取章节、画布、资产和当前进度" /></WorkspacePage>;
|
if (detail.isLoading) return <WorkspacePage><WorkspaceLoadingState label="正在打开项目工作台" detail="读取章节、画布、资产和当前进度" /></WorkspacePage>;
|
||||||
if (detail.isError || !detail.data) return <WorkspacePage><WorkspaceErrorState title="项目不可用" description="项目不存在、已被删除,或当前账号没有访问权限。" actionLabel="返回项目中心" onRetry={() => navigate("/projects")} /></WorkspacePage>;
|
if (detail.isError || !detail.data) return <WorkspacePage><WorkspaceErrorState title="项目不可用" description="项目不存在、已被删除,或当前账号没有访问权限。" actionLabel="返回项目中心" onRetry={() => navigate("/projects")} /></WorkspacePage>;
|
||||||
if (!chapterId && (!view || !views.some((item) => item.key === view))) return <Navigate to={`/projects/${projectId}/overview`} replace />;
|
if (!chapterId && !unitId && (!view || !views.some((item) => item.key === view))) return <Navigate to={`/projects/${projectId}/overview`} replace />;
|
||||||
|
if (activeView === "workflow" && !unitId && detail.data.units.length) return <Navigate to={`/projects/${projectId}/workflow/${detail.data.units.slice().sort((left, right) => left.position - right.position)[0].id}/video`} replace />;
|
||||||
const chapterHref = projectChapterHref(detail.data.units, projectId, chapterId);
|
const chapterHref = projectChapterHref(detail.data.units, projectId, chapterId);
|
||||||
|
const workflowHref = projectWorkflowHref(detail.data.units, projectId, unitId, stage);
|
||||||
return (
|
return (
|
||||||
<WorkspacePage className="project-workbench-page !overflow-hidden" fluid>
|
<WorkspacePage className="project-workbench-page !overflow-hidden" fluid>
|
||||||
<div className="flex h-full min-h-0 flex-col">
|
<div className="flex h-full min-h-0 flex-col">
|
||||||
<header className="project-workbench-header shrink-0 bg-workspace-glass px-3 py-2 backdrop-blur-md sm:px-4 lg:px-5 lg:py-0">
|
<header className="project-workbench-header shrink-0 border-b border-border/60 bg-workspace-glass px-3 backdrop-blur-md sm:px-4 lg:px-5">
|
||||||
<div className="flex min-w-0 flex-wrap items-center gap-x-3 lg:min-h-16 lg:flex-nowrap">
|
<div className="flex min-h-11 min-w-0 items-center gap-x-3">
|
||||||
<div className="flex min-w-0 flex-1 items-center gap-2.5 lg:w-[250px] lg:flex-none xl:w-[290px]">
|
<div className="flex min-w-0 flex-1 items-center gap-2.5 lg:w-[250px] lg:flex-none xl:w-[290px]">
|
||||||
<button type="button" onClick={() => navigate("/projects")} className="grid size-9 shrink-0 place-items-center rounded-md text-foreground/42 transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label="返回项目" title="返回项目"><ArrowLeft className="size-4" /></button>
|
<button type="button" onClick={() => navigate("/projects")} className="grid size-8 shrink-0 place-items-center rounded-md text-foreground/42 transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label="返回项目" title="返回项目"><ArrowLeft className="size-4" /></button>
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<h1 className="min-w-0 truncate text-[var(--fs-body)] font-semibold text-foreground/90">{detail.data.project.name}</h1>
|
<h1 className="min-w-0 truncate text-[var(--fs-body)] font-semibold text-foreground/90">{detail.data.project.name}</h1>
|
||||||
<span className={`size-1.5 shrink-0 rounded-full ${detail.data.project.status === "archived" ? "bg-foreground/30" : "bg-[var(--workspace-accent)]"}`} />
|
<span className={`size-1.5 shrink-0 rounded-full ${detail.data.project.status === "archived" ? "bg-foreground/30" : "bg-[var(--workspace-accent)]"}`} />
|
||||||
<span className="hidden shrink-0 text-[var(--fs-tiny)] text-foreground/42 sm:inline">{detail.data.project.status === "archived" ? "已归档" : "进行中"}</span>
|
<span className="hidden shrink-0 text-[var(--fs-tiny)] text-foreground/42 sm:inline">{detail.data.project.status === "archived" ? "已归档" : "进行中"}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<nav className="thin-scrollbar order-last mt-1 flex h-11 w-full min-w-0 items-center gap-0.5 overflow-x-auto lg:order-none lg:mt-0 lg:h-16 lg:flex-1 lg:pl-3" aria-label="项目导航">
|
<nav className="thin-scrollbar flex h-11 min-w-0 flex-1 items-center gap-0.5 overflow-x-auto lg:pl-3" aria-label="项目导航">
|
||||||
{views.map((item) => { const Icon = item.icon; const active = item.key === activeView; const href = item.key === "chapters" ? chapterHref : `/projects/${projectId}/${item.key}`; return <Link key={item.key} to={href} className={`relative flex h-11 shrink-0 items-center gap-2 rounded-md px-2.5 text-[var(--fs-body)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:px-3 ${active ? "bg-[var(--workspace-accent-soft)] font-medium text-foreground lg:after:absolute lg:after:inset-x-3 lg:after:bottom-0 lg:after:h-0.5 lg:after:rounded-full lg:after:bg-[var(--workspace-accent)]" : "text-foreground/52 hover:bg-surface-hover hover:text-foreground"}`} aria-current={active ? "page" : undefined}><Icon className={`size-4 shrink-0 ${active ? "text-[var(--workspace-accent)]" : "text-foreground/45"}`} /><span className="sm:hidden">{item.shortLabel}</span><span className="hidden sm:inline">{item.label}</span></Link>; })}
|
{views.map((item) => { const Icon = item.icon; const active = item.key === activeView; const href = item.key === "chapters" ? chapterHref : item.key === "workflow" ? workflowHref : `/projects/${projectId}/${item.key}`; return <Link key={item.key} to={href} className={`relative flex h-9 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-[var(--fs-caption)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:px-3 ${active ? "bg-[var(--workspace-accent-soft)] font-medium text-foreground lg:after:absolute lg:after:inset-x-3 lg:after:bottom-0 lg:after:h-0.5 lg:after:rounded-full lg:after:bg-[var(--workspace-accent)]" : "text-foreground/52 hover:bg-surface-hover hover:text-foreground"}`} aria-current={active ? "page" : undefined}><Icon className={`size-3.5 shrink-0 ${active ? "text-[var(--workspace-accent)]" : "text-foreground/45"}`} /><span className="sm:hidden">{item.shortLabel}</span><span className="hidden sm:inline">{item.label}</span></Link>; })}
|
||||||
</nav>
|
</nav>
|
||||||
<Tooltip title={activeView === "chapters" && detail.data.units.length ? "新建当前章节画布" : "新建项目画布"}><Button size="small" className="!h-9 !shrink-0 !px-2 sm:!px-3" icon={<Plus className="size-4" />} onClick={createCanvas} aria-label={activeView === "chapters" && detail.data.units.length ? "新建当前章节画布" : "新建项目画布"}><span className="hidden sm:inline">新建画布</span></Button></Tooltip>
|
{activeView === "workflow" ? (
|
||||||
|
<Select
|
||||||
|
size="small"
|
||||||
|
className="hidden min-w-36 shrink-0 lg:block"
|
||||||
|
value={unitId || detail.data.units[0]?.id}
|
||||||
|
options={detail.data.units.slice().sort((left, right) => left.position - right.position).map((item, index) => ({ value: item.id, label: `${String(index + 1).padStart(2, "0")} · ${item.title}` }))}
|
||||||
|
onChange={(nextUnitId) => navigate(`/projects/${projectId}/workflow/${nextUnitId}/${stage || "video"}`)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Tooltip title={activeView === "chapters" && detail.data.units.length ? "新建当前章节画布" : "新建项目画布"}><Button size="small" className="!h-9 !shrink-0 !px-2 sm:!px-3" icon={<Plus className="size-4" />} onClick={createCanvas} aria-label={activeView === "chapters" && detail.data.units.length ? "新建当前章节画布" : "新建项目画布"}><span className="hidden sm:inline">新建画布</span></Button></Tooltip>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
{detail.data.project.status === "archived" ? <Alert type="warning" showIcon banner message="项目已归档,恢复后才能创建画布和生成任务" className="!border-x-0 !border-t-0" /> : null}
|
{detail.data.project.status === "archived" ? <Alert type="warning" showIcon banner message="项目已归档,恢复后才能创建画布和生成任务" className="!border-x-0 !border-t-0" /> : null}
|
||||||
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
<div className={activeView === "chapters" ? "min-h-0 flex-1" : "thin-scrollbar min-h-0 flex-1 overflow-y-auto px-3 py-5 sm:px-5 lg:px-8 lg:py-7"}>
|
<div className={activeView === "chapters" || activeView === "workflow" ? "min-h-0 flex-1" : "thin-scrollbar min-h-0 flex-1 overflow-y-auto px-3 py-5 sm:px-5 lg:px-8 lg:py-7"}>
|
||||||
<div className={activeView === "overview" ? "w-full" : activeView === "chapters" ? "h-full w-full" : "w-full"}>
|
<div className={activeView === "overview" ? "w-full" : activeView === "chapters" || activeView === "workflow" ? "h-full w-full" : "w-full"}>
|
||||||
{activeView === "overview" ? <ProjectOverviewView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
{activeView === "overview" ? <ProjectOverviewView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
||||||
{activeView === "chapters" ? <ProjectChaptersView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
{activeView === "chapters" ? <ProjectChaptersView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
||||||
|
{activeView === "workflow" ? <ProjectWorkflowView detail={detail.data} projectId={projectId} unitId={unitId || ""} stage={stage || "video"} /> : null}
|
||||||
{activeView === "canvases" ? <ProjectCanvasesView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
{activeView === "canvases" ? <ProjectCanvasesView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
||||||
{activeView === "assets" ? <ProjectAssetsView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
{activeView === "assets" ? <ProjectAssetsView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
||||||
{activeView === "settings" ? <ProjectSettingsView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
{activeView === "settings" ? <ProjectSettingsView detail={detail.data} refreshProject={refreshProject} onCreateCanvas={createCanvas} /> : null}
|
||||||
@@ -104,6 +118,11 @@ export default function ProjectDetailPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function projectWorkflowHref(units: Array<{ id: string; position: number }>, projectId: string, routeUnitId?: string, routeStage?: string) {
|
||||||
|
const targetId = [routeUnitId, sessionStorage.getItem(`project-active-chapter:${projectId}`) || ""].find((id) => id && units.some((unit) => unit.id === id)) || units.slice().sort((left, right) => left.position - right.position)[0]?.id;
|
||||||
|
return targetId ? `/projects/${projectId}/workflow/${targetId}/${routeStage || "video"}` : `/projects/${projectId}/workflow`;
|
||||||
|
}
|
||||||
|
|
||||||
function projectChapterHref(units: Array<{ id: string; position: number }>, projectId: string, routeChapterId?: string) {
|
function projectChapterHref(units: Array<{ id: string; position: number }>, projectId: string, routeChapterId?: string) {
|
||||||
const rememberedId = sessionStorage.getItem(`project-active-chapter:${projectId}`) || "";
|
const rememberedId = sessionStorage.getItem(`project-active-chapter:${projectId}`) || "";
|
||||||
const targetId = [routeChapterId, rememberedId].find((id) => id && units.some((unit) => unit.id === id)) || units.slice().sort((left, right) => left.position - right.position)[0]?.id;
|
const targetId = [routeChapterId, rememberedId].find((id) => id && units.some((unit) => unit.id === id)) || units.slice().sort((left, right) => left.position - right.position)[0]?.id;
|
||||||
|
|||||||
@@ -0,0 +1,478 @@
|
|||||||
|
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||||
|
import { useMutation } from "@tanstack/react-query";
|
||||||
|
import { App, Button, Empty, Form, Input, InputNumber, Segmented, Select, Tag } from "antd";
|
||||||
|
import { Box, ChevronDown, ChevronLeft, ChevronRight, Download, Film, Image as ImageIcon, Layers3, List, Play, Plus, RefreshCcw, Save, SlidersHorizontal, UsersRound, WandSparkles } from "lucide-react";
|
||||||
|
import { Link, useNavigate } from "react-router";
|
||||||
|
|
||||||
|
import { runBackendGenerationTask } from "@/services/api/generation-task";
|
||||||
|
import {
|
||||||
|
linkShotAsset,
|
||||||
|
createUnitWorkflow,
|
||||||
|
registerProjectTaskOutput,
|
||||||
|
saveProjectShot,
|
||||||
|
type ProjectAsset,
|
||||||
|
type ProjectDetail,
|
||||||
|
type ProjectShot,
|
||||||
|
type ShotArtifact,
|
||||||
|
type ShotRevisionInput,
|
||||||
|
type WorkflowStep,
|
||||||
|
} from "@/services/api/projects";
|
||||||
|
import { resourceFileUrl, resourceIdFromStorageKey } from "@/services/api/resources";
|
||||||
|
import { modelDisplayName, useConfigStore, useEffectiveConfig } from "@/stores/use-config-store";
|
||||||
|
import type { ReferenceImage } from "@/types/image";
|
||||||
|
|
||||||
|
import {
|
||||||
|
ArtifactStatus,
|
||||||
|
artifactTypeForStage,
|
||||||
|
assetCategoryLabel,
|
||||||
|
currentArtifact,
|
||||||
|
currentRevision,
|
||||||
|
formatDuration,
|
||||||
|
type ShortDramaWorkflowStage,
|
||||||
|
} from "./workflow-shared";
|
||||||
|
|
||||||
|
type ShotEditorValues = Omit<ShotRevisionInput, "durationMs"> & {
|
||||||
|
title: string;
|
||||||
|
durationSeconds: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
activeStage: ShortDramaWorkflowStage;
|
||||||
|
detail: ProjectDetail;
|
||||||
|
projectId: string;
|
||||||
|
unitId: string;
|
||||||
|
workflowStep?: WorkflowStep;
|
||||||
|
selectedShot?: ProjectShot;
|
||||||
|
onSelectShot: (id: string) => void;
|
||||||
|
onRefresh: () => Promise<void>;
|
||||||
|
onAddShot: () => void;
|
||||||
|
addingShot: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const productionStageCopy: Record<"storyboard" | "previz" | "video", { label: string; action: string; empty: string }> = {
|
||||||
|
storyboard: { label: "分镜图", action: "生成分镜图", empty: "生成静态分镜图,确认构图、景别与角色位置" },
|
||||||
|
previz: { label: "动作预演", action: "生成黑白预演", empty: "生成黑白动作预演,确认表演节拍与镜头运动" },
|
||||||
|
video: { label: "镜头视频", action: "生成镜头视频", empty: "选择视频模型后生成当前镜头" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function WorkflowProductionWorkbench(props: Props) {
|
||||||
|
const { activeStage, detail, projectId, unitId, workflowStep, selectedShot, onSelectShot, onRefresh, onAddShot, addingShot } = props;
|
||||||
|
const { message, modal } = App.useApp();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const effectiveConfig = useEffectiveConfig();
|
||||||
|
const isAiConfigReady = useConfigStore((state) => state.isAiConfigReady);
|
||||||
|
const [form] = Form.useForm<ShotEditorValues>();
|
||||||
|
const watchedDuration = Form.useWatch("durationSeconds", form);
|
||||||
|
const watchedTitle = Form.useWatch("title", form);
|
||||||
|
const [leftTab, setLeftTab] = useState<"assets" | "episodes" | "shots">("assets");
|
||||||
|
const [previewTab, setPreviewTab] = useState<"latest" | "history">("latest");
|
||||||
|
const [previewArtifactId, setPreviewArtifactId] = useState("");
|
||||||
|
const [editorDirty, setEditorDirty] = useState(false);
|
||||||
|
const shots = useMemo(() => (detail.shots || []).filter((item) => item.unitId === unitId).slice().sort((left, right) => left.position - right.position), [detail.shots, unitId]);
|
||||||
|
const shotIndex = selectedShot ? shots.findIndex((item) => item.id === selectedShot.id) : -1;
|
||||||
|
const revision = currentRevision(detail, selectedShot);
|
||||||
|
const artifactType = artifactTypeForStage(activeStage);
|
||||||
|
const artifacts = useMemo(() => selectedShot ? (detail.shotArtifacts || []).filter((item) => item.shotId === selectedShot.id && item.type === artifactType).slice().sort((left, right) => right.version - left.version) : [], [artifactType, detail.shotArtifacts, selectedShot]);
|
||||||
|
const newestArtifact = artifacts.find((item) => item.selected) || artifacts[0];
|
||||||
|
const previewArtifact = artifacts.find((item) => item.id === previewArtifactId) || newestArtifact;
|
||||||
|
const modelOptions = (activeStage === "video" ? effectiveConfig.videoModels : effectiveConfig.imageModels) || [];
|
||||||
|
const defaultModel = activeStage === "video" ? effectiveConfig.videoModel : effectiveConfig.imageModel;
|
||||||
|
const [selectedModel, setSelectedModel] = useState(defaultModel || modelOptions[0] || "");
|
||||||
|
const [aspectRatio, setAspectRatio] = useState(detail.project.aspectRatio || "16:9");
|
||||||
|
const [resolution, setResolution] = useState(effectiveConfig.vquality || "720");
|
||||||
|
const modelSummary = selectedModel ? modelDisplayName(effectiveConfig, selectedModel) : "未选择模型";
|
||||||
|
const durationSummary = `${Number(watchedDuration || Math.max(0.5, (selectedShot?.durationMs || 3000) / 1000))}s`;
|
||||||
|
const resolutionSummary = `${resolution.replace(/p$/i, "")}p`;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setSelectedModel(defaultModel || modelOptions[0] || "");
|
||||||
|
}, [activeStage, defaultModel, modelOptions]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
form.setFieldsValue({
|
||||||
|
title: selectedShot?.title || "",
|
||||||
|
plotDescription: revision?.plotDescription || selectedShot?.description || "",
|
||||||
|
action: revision?.action || "",
|
||||||
|
dialogue: revision?.dialogue || "",
|
||||||
|
shotSize: revision?.shotSize || "",
|
||||||
|
cameraAngle: revision?.cameraAngle || "",
|
||||||
|
cameraMovement: revision?.cameraMovement || "",
|
||||||
|
durationSeconds: Math.max(0.5, (revision?.durationMs || selectedShot?.durationMs || 3000) / 1000),
|
||||||
|
imagePrompt: revision?.imagePrompt || "",
|
||||||
|
videoPrompt: revision?.videoPrompt || "",
|
||||||
|
negativePrompt: revision?.negativePrompt || "",
|
||||||
|
continuityNotes: revision?.continuityNotes || "",
|
||||||
|
});
|
||||||
|
setPreviewArtifactId("");
|
||||||
|
setEditorDirty(!revision);
|
||||||
|
}, [form, revision?.id, selectedShot?.id]);
|
||||||
|
|
||||||
|
const saveShot = useMutation({
|
||||||
|
mutationFn: async (values: ShotEditorValues) => {
|
||||||
|
if (!selectedShot) throw new Error("请先选择镜头");
|
||||||
|
return saveProjectShot(projectId, {
|
||||||
|
id: selectedShot.id,
|
||||||
|
unitId,
|
||||||
|
title: values.title,
|
||||||
|
description: values.plotDescription,
|
||||||
|
position: selectedShot.position,
|
||||||
|
durationMs: Math.round(values.durationSeconds * 1000),
|
||||||
|
status: selectedShot.status,
|
||||||
|
revision: revisionInput(values),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: async () => { setEditorDirty(false); await onRefresh(); message.success("镜头脚本已保存为新版本"); },
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : "镜头保存失败"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const bindAsset = useMutation({
|
||||||
|
mutationFn: async (asset: ProjectAsset) => {
|
||||||
|
if (!selectedShot || !asset.primaryVersionId) throw new Error("该资产还没有可绑定版本");
|
||||||
|
return linkShotAsset(projectId, selectedShot.id, { assetVersionId: asset.primaryVersionId, role: "reference" });
|
||||||
|
},
|
||||||
|
onSuccess: async () => { await onRefresh(); message.success("资产已绑定到当前镜头"); },
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : "资产绑定失败"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const generateArtifact = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
if (!selectedShot) throw new Error("请先选择镜头");
|
||||||
|
let productionStep = workflowStep;
|
||||||
|
if (!productionStep) {
|
||||||
|
const initialized = await createUnitWorkflow(projectId, unitId);
|
||||||
|
productionStep = (initialized.workflow.steps || []).find((step) => step.stepKey === activeStage);
|
||||||
|
}
|
||||||
|
if (!productionStep) throw new Error("当前生成阶段不可用,请刷新页面后重试");
|
||||||
|
if (productionStep.status === "failed") throw new Error("当前生成阶段失败,请刷新后重试");
|
||||||
|
if (!selectedModel) throw new Error(activeStage === "video" ? "请先配置视频模型" : "请先配置图片模型");
|
||||||
|
if (selectedModel.startsWith("local:dreamina-cli")) throw new Error("本机即梦任务暂不能登记到分镜产物,请选择后端模型渠道");
|
||||||
|
const values = await form.validateFields();
|
||||||
|
const saved = await saveProjectShot(projectId, {
|
||||||
|
id: selectedShot.id,
|
||||||
|
unitId,
|
||||||
|
title: values.title,
|
||||||
|
description: values.plotDescription,
|
||||||
|
position: selectedShot.position,
|
||||||
|
durationMs: Math.round(values.durationSeconds * 1000),
|
||||||
|
status: selectedShot.status,
|
||||||
|
revision: revisionInput(values),
|
||||||
|
});
|
||||||
|
const mode = activeStage === "video" ? "video" as const : "image" as const;
|
||||||
|
const config = {
|
||||||
|
...effectiveConfig,
|
||||||
|
model: selectedModel,
|
||||||
|
imageModel: mode === "image" ? selectedModel : effectiveConfig.imageModel,
|
||||||
|
videoModel: mode === "video" ? selectedModel : effectiveConfig.videoModel,
|
||||||
|
size: aspectRatio,
|
||||||
|
vquality: resolution,
|
||||||
|
videoSeconds: String(Math.max(1, Math.round(values.durationSeconds))),
|
||||||
|
};
|
||||||
|
if (!isAiConfigReady(config, selectedModel)) throw new Error("当前模型渠道配置不完整,请先到设置中补齐");
|
||||||
|
const prompt = mode === "video"
|
||||||
|
? [values.videoPrompt || values.plotDescription, values.action, values.continuityNotes].filter(Boolean).join("\n")
|
||||||
|
: [values.imagePrompt || values.plotDescription, values.action, "黑白分镜草图,清晰动作节拍,电影构图"].filter(Boolean).join("\n");
|
||||||
|
let taskId = "";
|
||||||
|
const result = await runBackendGenerationTask({
|
||||||
|
projectId,
|
||||||
|
mode,
|
||||||
|
prompt,
|
||||||
|
config,
|
||||||
|
referenceImages: shotReferenceImages(detail, selectedShot.id),
|
||||||
|
metadata: {
|
||||||
|
workflowStepId: productionStep.id,
|
||||||
|
domainProjectId: projectId,
|
||||||
|
unitId,
|
||||||
|
shotId: saved.shot.id,
|
||||||
|
artifactType,
|
||||||
|
role: "output",
|
||||||
|
source: "short-drama-workflow",
|
||||||
|
},
|
||||||
|
onTaskUpdate: (task) => { taskId = task.id; },
|
||||||
|
});
|
||||||
|
const storageKey = mode === "video" ? result.video?.storageKey : result.images?.[0]?.storageKey;
|
||||||
|
const resourceId = resourceIdFromStorageKey(storageKey);
|
||||||
|
if (!taskId || !resourceId) throw new Error("生成已结束,但产物没有可登记的资源标识");
|
||||||
|
await registerProjectTaskOutput(projectId, productionStep.id, {
|
||||||
|
taskId,
|
||||||
|
unitId,
|
||||||
|
shotId: saved.shot.id,
|
||||||
|
artifactType,
|
||||||
|
resourceId,
|
||||||
|
mediaType: mode,
|
||||||
|
role: "output",
|
||||||
|
metadataJson: JSON.stringify({ model: selectedModel, aspectRatio, resolution, durationSeconds: values.durationSeconds }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: async () => { setEditorDirty(false); await onRefresh(); message.success(`${productionStageCopy[activeStage as "storyboard" | "previz" | "video"].label}已生成`); },
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : "生成失败"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const referencedVersionIds = new Set(selectedShot ? (detail.shotReferences || []).filter((item) => item.shotId === selectedShot.id).map((item) => item.assetVersionId) : []);
|
||||||
|
const stageCopy = productionStageCopy[activeStage as "storyboard" | "previz" | "video"];
|
||||||
|
|
||||||
|
if (!selectedShot) {
|
||||||
|
return <div className="workflow-empty-shot"><Empty description="当前章节还没有分镜"><Button type="primary" icon={<Plus className="size-4" />} loading={addingShot} onClick={onAddShot}>新增第一个分镜</Button></Empty></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestShotSelection = (nextShotId: string) => {
|
||||||
|
if (nextShotId === selectedShot.id) return;
|
||||||
|
if (!editorDirty) {
|
||||||
|
onSelectShot(nextShotId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
modal.confirm({
|
||||||
|
title: "当前镜头有未保存修改",
|
||||||
|
content: "切换镜头会放弃这些修改。",
|
||||||
|
okText: "放弃修改并切换",
|
||||||
|
cancelText: "继续编辑",
|
||||||
|
onOk: () => onSelectShot(nextShotId),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestAddShot = () => {
|
||||||
|
if (!editorDirty) {
|
||||||
|
onAddShot();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
modal.confirm({
|
||||||
|
title: "当前镜头有未保存修改",
|
||||||
|
content: "新增镜头会离开当前编辑内容。",
|
||||||
|
okText: "放弃修改并新增",
|
||||||
|
cancelText: "继续编辑",
|
||||||
|
onOk: onAddShot,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectRelativeShot = (offset: number) => {
|
||||||
|
const next = shots[shotIndex + offset];
|
||||||
|
if (next) requestShotSelection(next.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="workflow-production-shell">
|
||||||
|
<div className="workflow-production-main">
|
||||||
|
<aside className="workflow-library-panel">
|
||||||
|
<Segmented
|
||||||
|
block
|
||||||
|
size="small"
|
||||||
|
value={leftTab}
|
||||||
|
onChange={(value) => setLeftTab(value as typeof leftTab)}
|
||||||
|
options={[{ value: "assets", label: "资产" }, { value: "episodes", label: "章节" }, { value: "shots", label: "镜头" }]}
|
||||||
|
/>
|
||||||
|
<div className="workflow-library-scroll thin-scrollbar">
|
||||||
|
{leftTab === "assets" ? <AssetLibrary detail={detail} referencedVersionIds={referencedVersionIds} binding={bindAsset.isPending} onBind={(asset) => bindAsset.mutate(asset)} /> : null}
|
||||||
|
{leftTab === "episodes" ? <EpisodeLibrary detail={detail} activeUnitId={unitId} projectId={projectId} activeStage={activeStage} /> : null}
|
||||||
|
{leftTab === "shots" ? <ShotLibrary detail={detail} shots={shots} selectedShotId={selectedShot.id} onSelectShot={requestShotSelection} /> : null}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section className="workflow-shot-editor">
|
||||||
|
<header className="workflow-panel-header">
|
||||||
|
<div className="workflow-shot-heading">
|
||||||
|
<span className="workflow-shot-number">SC.{String(shotIndex + 1).padStart(2, "0")}</span>
|
||||||
|
<h2>{watchedTitle || selectedShot.title || "未命名镜头"}</h2>
|
||||||
|
<Tag className="!m-0" color={saveShot.isPending ? "blue" : editorDirty ? "orange" : revision ? "green" : undefined}>{saveShot.isPending ? "保存中" : editorDirty ? "有未保存修改" : revision ? "已保存" : "草稿"}</Tag>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1"><span className="mr-1 text-[var(--fs-micro)] text-foreground/45">{shotIndex + 1} / {shots.length}</span><Button type="text" size="small" icon={<ChevronLeft className="size-4" />} disabled={shotIndex <= 0} onClick={() => selectRelativeShot(-1)} aria-label="上一个镜头" /><Button type="text" size="small" icon={<ChevronRight className="size-4" />} disabled={shotIndex >= shots.length - 1} onClick={() => selectRelativeShot(1)} aria-label="下一个镜头" /></div>
|
||||||
|
</header>
|
||||||
|
<Form form={form} layout="vertical" className="workflow-shot-form" onValuesChange={() => setEditorDirty(true)} onFinish={(values) => saveShot.mutate(values)}>
|
||||||
|
<div className="workflow-shot-form-scroll thin-scrollbar">
|
||||||
|
<div className="workflow-form-section-heading"><span>镜头脚本</span><small>先写清镜头里发生什么,再调整生成参数</small></div>
|
||||||
|
<Form.Item name="title" label="镜头名称" rules={[{ required: true, message: "请输入镜头名称" }]}><Input placeholder="用一句话概括这个镜头" /></Form.Item>
|
||||||
|
<Form.Item name="plotDescription" label="镜头画面" rules={[{ required: true, message: "请输入镜头画面" }]}><Input.TextArea autoSize={{ minRows: 4, maxRows: 8 }} placeholder="描述主体、场景、动作、构图、光线,以及观众在这一镜看到的信息" /></Form.Item>
|
||||||
|
<BoundAssets detail={detail} shotId={selectedShot.id} />
|
||||||
|
<div className="workflow-form-grid">
|
||||||
|
<Form.Item name="action" label="表演与动作"><Input.TextArea autoSize={{ minRows: 3, maxRows: 6 }} placeholder="按动作节拍描述人物表演、走位和物体运动" /></Form.Item>
|
||||||
|
<Form.Item name="dialogue" label="对白 / 旁白"><Input.TextArea autoSize={{ minRows: 3, maxRows: 6 }} placeholder="填写对白、旁白或需要保留的声音信息" /></Form.Item>
|
||||||
|
</div>
|
||||||
|
<WorkflowDisclosure
|
||||||
|
icon={<SlidersHorizontal />}
|
||||||
|
title="生成设置"
|
||||||
|
description="生成规格与镜头语言"
|
||||||
|
summary={<><span>{durationSummary}</span><span>{aspectRatio}</span><span>{resolutionSummary}</span><span className="is-model">{modelSummary}</span></>}
|
||||||
|
>
|
||||||
|
<div className="workflow-settings-section">
|
||||||
|
<div className="workflow-settings-section-title">生成规格</div>
|
||||||
|
<Form.Item label="生成模型"><Select showSearch value={selectedModel || undefined} placeholder={activeStage === "video" ? "选择视频模型" : "选择图片模型"} onChange={setSelectedModel} options={modelOptions.map((value) => ({ value, label: modelDisplayName(effectiveConfig, value) }))} /></Form.Item>
|
||||||
|
<div className="workflow-form-grid is-three">
|
||||||
|
<Form.Item name="durationSeconds" label="镜头时长(秒)"><InputNumber className="w-full" min={0.5} max={60} step={0.5} /></Form.Item>
|
||||||
|
<Form.Item label="画幅"><Select value={aspectRatio} onChange={setAspectRatio} options={[detail.project.aspectRatio, "16:9", "9:16", "1:1"].filter((value, index, array) => value && array.indexOf(value) === index).map((value) => ({ value, label: value }))} /></Form.Item>
|
||||||
|
<Form.Item label="分辨率"><Select value={resolution} onChange={setResolution} options={[{ value: "480", label: "480p" }, { value: "720", label: "720p" }, { value: "1080", label: "1080p" }]} /></Form.Item>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="workflow-settings-section">
|
||||||
|
<div className="workflow-settings-section-title">镜头语言</div>
|
||||||
|
<div className="workflow-form-grid is-three">
|
||||||
|
<Form.Item name="shotSize" label="景别"><Select allowClear placeholder="自动" options={["特写", "近景", "中景", "全景", "远景"].map((value) => ({ value, label: value }))} /></Form.Item>
|
||||||
|
<Form.Item name="cameraAngle" label="机位角度"><Select allowClear placeholder="自动" options={["平视", "俯拍", "仰拍", "侧面", "过肩"].map((value) => ({ value, label: value }))} /></Form.Item>
|
||||||
|
<Form.Item name="cameraMovement" label="运镜方式"><Select allowClear placeholder="自动" options={["固定", "推镜", "拉镜", "摇镜", "移镜", "跟拍"].map((value) => ({ value, label: value }))} /></Form.Item>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</WorkflowDisclosure>
|
||||||
|
<WorkflowDisclosure
|
||||||
|
className="is-advanced"
|
||||||
|
icon={<WandSparkles />}
|
||||||
|
title="生成补充"
|
||||||
|
description="仅在模型需要额外约束时填写"
|
||||||
|
summary={<span>提示词 · 排除内容 · 接戏</span>}
|
||||||
|
>
|
||||||
|
<div className="workflow-form-grid">
|
||||||
|
<Form.Item name="imagePrompt" label="画面提示词"><Input.TextArea autoSize={{ minRows: 3, maxRows: 6 }} placeholder="留空时根据镜头画面自动生成" /></Form.Item>
|
||||||
|
<Form.Item name="videoPrompt" label="动态提示词"><Input.TextArea autoSize={{ minRows: 3, maxRows: 6 }} placeholder="补充动作节奏、运镜变化和动态细节" /></Form.Item>
|
||||||
|
<Form.Item name="negativePrompt" label="排除内容"><Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="填写不希望出现的元素、动作或画面问题" /></Form.Item>
|
||||||
|
<Form.Item name="continuityNotes" label="接戏备注"><Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="记录人物位置、朝向、服装、道具及前后镜延续关系" /></Form.Item>
|
||||||
|
</div>
|
||||||
|
</WorkflowDisclosure>
|
||||||
|
</div>
|
||||||
|
<footer className="workflow-editor-actions">
|
||||||
|
<div className="flex items-center gap-2"><Button htmlType="submit" icon={<Save className="size-4" />} loading={saveShot.isPending} disabled={!editorDirty}>保存脚本</Button><Button type="primary" icon={<Play className="size-4" />} loading={generateArtifact.isPending} onClick={() => generateArtifact.mutate()}>{stageCopy.action}</Button></div>
|
||||||
|
</footer>
|
||||||
|
</Form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<aside className="workflow-preview-panel">
|
||||||
|
<header className="workflow-preview-header">
|
||||||
|
<div className="workflow-preview-header-row">
|
||||||
|
<div className="workflow-preview-title"><Film className="size-4 shrink-0" /><span>产物预览</span></div>
|
||||||
|
<Segmented size="small" value={previewTab} onChange={(value) => setPreviewTab(value as typeof previewTab)} options={[{ value: "latest", label: "最新" }, { value: "history", label: `历史 ${artifacts.length}` }]} />
|
||||||
|
</div>
|
||||||
|
<Segmented
|
||||||
|
block
|
||||||
|
size="small"
|
||||||
|
className="workflow-preview-stage-switch"
|
||||||
|
value={activeStage}
|
||||||
|
options={[{ value: "storyboard", label: "分镜图" }, { value: "previz", label: "动作预演" }, { value: "video", label: "镜头视频" }]}
|
||||||
|
onChange={(nextStage) => navigate(`/projects/${projectId}/workflow/${unitId}/${nextStage}`)}
|
||||||
|
/>
|
||||||
|
</header>
|
||||||
|
<div className="workflow-preview-scroll thin-scrollbar">
|
||||||
|
{previewTab === "latest" ? <LatestPreview artifact={previewArtifact} emptyText={stageCopy.empty} /> : <ArtifactHistory artifacts={artifacts} activeId={previewArtifact?.id} onSelect={(artifact) => { setPreviewArtifactId(artifact.id); setPreviewTab("latest"); }} />}
|
||||||
|
<div className="workflow-preview-summary"><div className="flex items-center justify-between gap-2"><span className="text-xs font-medium">当前产物</span><ArtifactStatus artifact={newestArtifact} compact /></div><div className="mt-1 text-[var(--fs-micro)] text-foreground/45">{newestArtifact ? `${formatDuration(selectedShot.durationMs)} · ${resolution}p · v${newestArtifact.version}` : "当前镜头还没有生成产物"}</div></div>
|
||||||
|
<div className="workflow-preview-actions"><Button icon={<RefreshCcw className="size-3.5" />} loading={generateArtifact.isPending} onClick={() => generateArtifact.mutate()}>重新生成</Button><Button icon={<Download className="size-3.5" />} disabled={!previewArtifact?.resourceId} onClick={() => previewArtifact?.resourceId && void downloadArtifact(previewArtifact, selectedShot.title, message.error)}>下载{activeStage === "video" ? "视频" : "图片"}</Button></div>
|
||||||
|
<ArtifactHistory artifacts={artifacts.slice(0, 4)} activeId={previewArtifact?.id} onSelect={(artifact) => setPreviewArtifactId(artifact.id)} compact />
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ShotTimeline detail={detail} shots={shots} selectedShotId={selectedShot.id} onSelectShot={requestShotSelection} onAddShot={requestAddShot} addingShot={addingShot} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function WorkflowDisclosure({ icon, title, description, summary, className = "", children }: { icon: ReactNode; title: string; description: string; summary: ReactNode; className?: string; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<details className={`workflow-disclosure ${className}`}>
|
||||||
|
<summary>
|
||||||
|
<span className="workflow-disclosure-heading"><span className="workflow-disclosure-icon">{icon}</span><span><strong>{title}</strong><small>{description}</small></span></span>
|
||||||
|
<span className="workflow-disclosure-summary">{summary}<ChevronDown className="workflow-disclosure-chevron" /></span>
|
||||||
|
</summary>
|
||||||
|
<div className="workflow-disclosure-body"><div className="workflow-disclosure-content">{children}</div></div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AssetLibrary({ detail, referencedVersionIds, binding, onBind }: { detail: ProjectDetail; referencedVersionIds: Set<string>; binding: boolean; onBind: (asset: ProjectAsset) => void }) {
|
||||||
|
const groups = useMemo(() => {
|
||||||
|
const map = new Map<string, ProjectAsset[]>();
|
||||||
|
detail.assets.forEach((asset) => map.set(asset.category || "other", [...(map.get(asset.category || "other") || []), asset]));
|
||||||
|
return Array.from(map.entries());
|
||||||
|
}, [detail.assets]);
|
||||||
|
if (!groups.length) return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="项目还没有资产" />;
|
||||||
|
return <div className="workflow-asset-groups">{groups.map(([category, assets]) => <section key={category}><h3>{assetCategoryLabel(category)} <span>({assets.length})</span></h3><div className="workflow-asset-list">{assets.map((asset) => { const active = Boolean(asset.primaryVersionId && referencedVersionIds.has(asset.primaryVersionId)); const previewUrl = assetPreviewUrl(asset); return <button key={asset.id} type="button" className={`workflow-asset-row ${active ? "is-active" : ""}`} disabled={binding || !asset.primaryVersionId || active} onClick={() => onBind(asset)}><span className="workflow-asset-thumb">{previewUrl ? <img src={previewUrl} alt="" loading="lazy" /> : asset.category === "character" ? <UsersRound /> : asset.mediaType === "image" ? <ImageIcon /> : <Box />}</span><span className="min-w-0 flex-1"><strong>{asset.title}</strong><small>{active ? "已绑定当前镜头" : `${assetCategoryLabel(asset.category)} · v${Math.max(1, asset.versionCount)}`}</small></span>{active ? <span className="workflow-bound-dot" /> : null}</button>; })}</div></section>)}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function EpisodeLibrary({ detail, activeUnitId, projectId, activeStage }: { detail: ProjectDetail; activeUnitId: string; projectId: string; activeStage: ShortDramaWorkflowStage }) {
|
||||||
|
return <div className="workflow-simple-list">{detail.units.slice().sort((left, right) => left.position - right.position).map((unit, index) => <Link key={unit.id} to={`/projects/${projectId}/workflow/${unit.id}/${activeStage}`} className={unit.id === activeUnitId ? "is-active" : ""}><span>{String(index + 1).padStart(2, "0")}</span><strong>{unit.title}</strong></Link>)}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ShotLibrary({ detail, shots, selectedShotId, onSelectShot }: { detail: ProjectDetail; shots: ProjectShot[]; selectedShotId: string; onSelectShot: (id: string) => void }) {
|
||||||
|
return <div className="workflow-simple-list">{shots.map((shot, index) => { const video = currentArtifact(detail, shot.id, "video"); return <button key={shot.id} type="button" className={shot.id === selectedShotId ? "is-active" : ""} onClick={() => onSelectShot(shot.id)}><span>{String(index + 1).padStart(2, "0")}</span><span className="min-w-0 flex-1"><strong>{shot.title}</strong><small>{formatDuration(shot.durationMs)}</small></span><ArtifactStatus artifact={video} compact /></button>; })}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function BoundAssets({ detail, shotId }: { detail: ProjectDetail; shotId: string }) {
|
||||||
|
const references = (detail.shotReferences || []).filter((item) => item.shotId === shotId);
|
||||||
|
const assetByVersionId = useMemo(() => new Map(detail.assets.filter((asset) => asset.primaryVersionId).map((asset) => [asset.primaryVersionId as string, asset])), [detail.assets]);
|
||||||
|
return (
|
||||||
|
<div className="workflow-bound-assets">
|
||||||
|
<div className="workflow-bound-assets-heading"><span className="workflow-field-label">镜头资产</span><small>{references.length ? `已绑定 ${references.length} 项` : "从左侧资产栏点击绑定"}</small></div>
|
||||||
|
<div className="workflow-bound-assets-content">
|
||||||
|
{references.length ? references.map((reference) => {
|
||||||
|
const asset = assetByVersionId.get(reference.assetVersionId);
|
||||||
|
return <span key={reference.id} className="workflow-bound-asset-chip"><em>{asset ? assetCategoryLabel(asset.category) : "历史"}</em><span>{asset?.title || "历史资产版本"}</span></span>;
|
||||||
|
}) : <span>尚未绑定角色、场景或道具</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LatestPreview({ artifact, emptyText }: { artifact?: ShotArtifact; emptyText: string }) {
|
||||||
|
if (!artifact?.resourceId) return <div className="workflow-media-empty"><span><Play className="size-7" /></span><p>{emptyText}</p></div>;
|
||||||
|
const src = resourceFileUrl(artifact.resourceId);
|
||||||
|
if (artifact.type === "video") return <video className="workflow-preview-media" src={src} controls preload="metadata" />;
|
||||||
|
return <img className={`workflow-preview-media ${artifact.type === "action_board" ? "grayscale" : ""}`} src={src} alt="镜头生成预览" loading="eager" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ArtifactHistory({ artifacts, activeId, onSelect, compact = false }: { artifacts: ShotArtifact[]; activeId?: string; onSelect: (artifact: ShotArtifact) => void; compact?: boolean }) {
|
||||||
|
if (!artifacts.length) return compact ? null : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史版本" />;
|
||||||
|
return <section className={`workflow-history ${compact ? "is-compact" : ""}`}><div className="workflow-history-title">历史版本</div>{artifacts.map((artifact) => <button key={artifact.id} type="button" className={artifact.id === activeId ? "is-active" : ""} onClick={() => onSelect(artifact)}>{artifact.resourceId ? artifact.type === "video" ? <video src={resourceFileUrl(artifact.resourceId)} muted preload="metadata" /> : <img src={resourceFileUrl(artifact.resourceId)} alt="" loading="lazy" /> : <span className="workflow-history-placeholder"><Layers3 /></span>}<span className="min-w-0 flex-1"><strong>v{artifact.version}{artifact.selected ? " · 当前" : ""}</strong><small>{new Date(artifact.createdAt).toLocaleString("zh-CN", { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })}</small></span><ArtifactStatus artifact={artifact} compact /></button>)}</section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ShotTimeline({ detail, shots, selectedShotId, onSelectShot, onAddShot, addingShot }: { detail: ProjectDetail; shots: ProjectShot[]; selectedShotId: string; onSelectShot: (id: string) => void; onAddShot: () => void; addingShot: boolean }) {
|
||||||
|
return <section className="workflow-shot-timeline"><header><div><strong>{detail.units.find((item) => item.id === shots[0]?.unitId)?.title || "本集"}</strong><span>{shots.length} 镜 · 总时长 {formatDuration(shots.reduce((total, item) => total + item.durationMs, 0))}</span></div><div className="flex items-center gap-1 text-[var(--fs-micro)] text-foreground/40"><List className="size-3.5" /> 共 {shots.length} 镜</div></header><div className="workflow-shot-track thin-scrollbar">{shots.map((shot, index) => <TimelineShot key={shot.id} detail={detail} shot={shot} index={index} selected={shot.id === selectedShotId} onSelect={() => onSelectShot(shot.id)} />)}<button type="button" className="workflow-add-shot-card" disabled={addingShot} onClick={onAddShot}><Plus className="size-5" /><span>新增分镜</span></button></div></section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TimelineShot({ detail, shot, index, selected, onSelect }: { detail: ProjectDetail; shot: ProjectShot; index: number; selected: boolean; onSelect: () => void }) {
|
||||||
|
const video = currentArtifact(detail, shot.id, "video");
|
||||||
|
const previz = currentArtifact(detail, shot.id, "action_board");
|
||||||
|
const preview = video?.resourceId ? video : previz?.resourceId ? previz : undefined;
|
||||||
|
const stateArtifact = video || previz;
|
||||||
|
return <button type="button" className={`workflow-timeline-shot ${selected ? "is-active" : ""}`} onClick={onSelect}><span className="workflow-timeline-media">{preview?.resourceId ? preview.type === "video" ? <video src={resourceFileUrl(preview.resourceId)} muted preload="metadata" /> : <img src={resourceFileUrl(preview.resourceId)} alt="" loading="lazy" /> : <Film />}</span><span className="workflow-timeline-copy"><span><strong>SC.{String(index + 1).padStart(2, "0")}</strong><small>{formatDuration(shot.durationMs)}</small></span><em>{shot.title}</em><ArtifactStatus artifact={stateArtifact} compact /></span></button>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function revisionInput(values: ShotEditorValues): ShotRevisionInput {
|
||||||
|
return {
|
||||||
|
plotDescription: values.plotDescription,
|
||||||
|
action: values.action,
|
||||||
|
dialogue: values.dialogue,
|
||||||
|
shotSize: values.shotSize,
|
||||||
|
cameraAngle: values.cameraAngle,
|
||||||
|
cameraMovement: values.cameraMovement,
|
||||||
|
durationMs: Math.round(values.durationSeconds * 1000),
|
||||||
|
imagePrompt: values.imagePrompt,
|
||||||
|
videoPrompt: values.videoPrompt,
|
||||||
|
negativePrompt: values.negativePrompt,
|
||||||
|
continuityNotes: values.continuityNotes,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function shotReferenceImages(detail: ProjectDetail, shotId: string): ReferenceImage[] {
|
||||||
|
const versionIds = new Set((detail.shotReferences || []).filter((item) => item.shotId === shotId).map((item) => item.assetVersionId));
|
||||||
|
return detail.assets.filter((asset) => asset.primaryVersionId && versionIds.has(asset.primaryVersionId) && asset.mediaType === "image" && asset.storageKey).map((asset) => {
|
||||||
|
const resourceId = resourceIdFromStorageKey(asset.storageKey);
|
||||||
|
return { id: asset.id, name: asset.title, type: "image/*", dataUrl: "", ...(resourceId ? { url: resourceFileUrl(resourceId) } : {}), storageKey: asset.storageKey };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadArtifact(artifact: ShotArtifact, shotTitle: string, onError: (content: string) => void) {
|
||||||
|
if (!artifact.resourceId) return;
|
||||||
|
try {
|
||||||
|
const response = await fetch(resourceFileUrl(artifact.resourceId), { credentials: "include" });
|
||||||
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
|
const blob = await response.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const anchor = document.createElement("a");
|
||||||
|
anchor.href = url;
|
||||||
|
anchor.download = `${shotTitle || "shot"}-v${artifact.version}.${artifact.type === "video" ? "mp4" : "png"}`;
|
||||||
|
anchor.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (error) {
|
||||||
|
onError(error instanceof Error ? `下载失败:${error.message}` : "下载失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assetPreviewUrl(asset: ProjectAsset) {
|
||||||
|
const representation = asset.character?.representations?.find((item) => item.role === "primary") || asset.character?.representations?.[0];
|
||||||
|
if (representation?.resourceId) return resourceFileUrl(representation.resourceId);
|
||||||
|
const resourceId = resourceIdFromStorageKey(asset.storageKey);
|
||||||
|
return resourceId && asset.mediaType === "image" ? resourceFileUrl(resourceId) : "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { Tag } from "antd";
|
||||||
|
import { Check, CircleAlert } from "lucide-react";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
|
||||||
|
import type { ProjectDetail, ProjectShot, ShotArtifact, ShotRevision, WorkflowStep } from "@/services/api/projects";
|
||||||
|
|
||||||
|
export type ShortDramaWorkflowStage = "story" | "assets" | "storyboard" | "previz" | "video" | "delivery";
|
||||||
|
|
||||||
|
export const workflowStages: Array<{ key: ShortDramaWorkflowStage; label: string; shortLabel: string }> = [
|
||||||
|
{ key: "story", label: "剧情与章节", shortLabel: "剧情" },
|
||||||
|
{ key: "assets", label: "资产拆分", shortLabel: "资产" },
|
||||||
|
{ key: "storyboard", label: "分镜脚本", shortLabel: "分镜" },
|
||||||
|
{ key: "previz", label: "黑白动作预演", shortLabel: "预演" },
|
||||||
|
{ key: "video", label: "视频生成", shortLabel: "视频" },
|
||||||
|
{ key: "delivery", label: "交付与打包", shortLabel: "交付" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function WorkflowStageLink({ href, active, step, index, label, shortLabel }: { href: string; active: boolean; step?: WorkflowStep; index: number; label: string; shortLabel: string }) {
|
||||||
|
const completed = step?.status === "completed" || step?.status === "skipped";
|
||||||
|
const failed = step?.status === "failed";
|
||||||
|
return (
|
||||||
|
<Link to={href} className={`workflow-stage-link ${active ? "is-active" : ""}`} aria-current={active ? "step" : undefined}>
|
||||||
|
<span className={`workflow-stage-index ${completed ? "is-completed" : failed ? "is-failed" : ""}`}>
|
||||||
|
{completed ? <Check className="size-3" /> : failed ? <CircleAlert className="size-3" /> : index + 1}
|
||||||
|
</span>
|
||||||
|
<span className="sm:hidden">{shortLabel}</span>
|
||||||
|
<span className="hidden sm:inline">{label}</span>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StageHeading({ eyebrow, title, description }: { eyebrow: string; title: string; description: string }) {
|
||||||
|
return <div><div className="text-[var(--fs-micro)] font-medium uppercase tracking-[.18em] text-[var(--workspace-accent)]">{eyebrow}</div><h2 className="mt-2 text-xl font-semibold tracking-tight text-foreground sm:text-2xl">{title}</h2><p className="mt-2 max-w-2xl text-sm leading-6 text-foreground/50">{description}</p></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MetricCard({ icon, label, value }: { icon: ReactNode; label: string; value: string }) {
|
||||||
|
return <div className="rounded-xl border border-border/70 bg-surface p-5"><div className="text-foreground/35">{icon}</div><div className="mt-4 text-2xl font-semibold">{value}</div><div className="mt-1 text-xs text-foreground/45">{label}</div></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ArtifactStatus({ artifact, compact = false }: { artifact?: ShotArtifact; compact?: boolean }) {
|
||||||
|
if (!artifact) return <Tag className={compact ? "!m-0" : ""}>待生成</Tag>;
|
||||||
|
const color = artifact.status === "ready" ? "green" : artifact.status === "failed" ? "red" : artifact.status === "stale" ? "orange" : "blue";
|
||||||
|
const label = artifact.status === "ready" ? "已生成" : artifact.status === "failed" ? "失败" : artifact.status === "stale" ? "已过期" : "生成中";
|
||||||
|
return <Tag className={compact ? "!m-0" : ""} color={color}>{label}</Tag>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currentRevision(detail: ProjectDetail, shot?: ProjectShot): ShotRevision | undefined {
|
||||||
|
if (!shot) return undefined;
|
||||||
|
const revisions = detail.shotRevisions || [];
|
||||||
|
return revisions.find((item) => item.id === shot.currentRevisionId)
|
||||||
|
|| revisions.filter((item) => item.shotId === shot.id).slice().sort((left, right) => right.version - left.version)[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currentArtifact(detail: ProjectDetail, shotId: string, type: string) {
|
||||||
|
const artifacts = (detail.shotArtifacts || []).filter((item) => item.shotId === shotId && item.type === type).slice().sort((left, right) => right.version - left.version);
|
||||||
|
return artifacts.find((item) => item.selected) || artifacts[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function artifactTypeForStage(stage: ShortDramaWorkflowStage) {
|
||||||
|
if (stage === "video") return "video";
|
||||||
|
if (stage === "previz") return "action_board";
|
||||||
|
return "storyboard";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assetCategoryLabel(category: string) {
|
||||||
|
return ({ character: "角色", environment: "场景", wardrobe: "服饰", accessory: "配饰", prop: "道具", weapon: "武器", style: "画风" } as Record<string, string>)[category] || category || "其他";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDuration(durationMs: number) {
|
||||||
|
if (durationMs < 60_000) return `${Math.round(durationMs / 100) / 10}s`;
|
||||||
|
const minutes = Math.floor(durationMs / 60_000);
|
||||||
|
const seconds = Math.round((durationMs % 60_000) / 1000);
|
||||||
|
return `${minutes}m ${seconds}s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stageActionLabel(step?: WorkflowStep) {
|
||||||
|
if (!step || step.status === "pending") return "等待上一步";
|
||||||
|
if (step.status === "running" || step.status === "review") return "完成阶段";
|
||||||
|
if (step.status === "completed") return "重新打开";
|
||||||
|
if (step.status === "failed") return "重新开始";
|
||||||
|
return "开始阶段";
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Button } from "antd";
|
||||||
|
import { Clock3, Film, Layers3, PackageCheck } from "lucide-react";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
|
||||||
|
import type { ProjectDetail } from "@/services/api/projects";
|
||||||
|
|
||||||
|
import { assetCategoryLabel, formatDuration, MetricCard, StageHeading } from "./workflow-shared";
|
||||||
|
|
||||||
|
export function StoryStage({ detail, projectId, unitId }: { detail: ProjectDetail; projectId: string; unitId: string }) {
|
||||||
|
const unit = detail.units.find((item) => item.id === unitId)!;
|
||||||
|
return <section className="mx-auto max-w-5xl"><StageHeading eyebrow="01 / 剧情与章节" title={unit.title} description="章节原文是资产拆分、分镜版本和生成提示的唯一来源。" /><div className="mt-6 rounded-xl border border-border/70 bg-surface p-5"><div className="mb-3 flex items-center justify-between"><span className="text-xs font-medium text-foreground/55">章节原文</span><Link to={`/projects/${projectId}/chapters/${unit.id}`}><Button size="small">编辑章节</Button></Link></div><div className="max-h-[60vh] whitespace-pre-wrap text-sm leading-7 text-foreground/78">{unit.sourceText || "当前章节还没有正文。请先在剧情章节中上传小说或添加内容。"}</div></div></section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AssetsStage({ detail, projectId, unitId }: { detail: ProjectDetail; projectId: string; unitId: string }) {
|
||||||
|
const candidates = detail.assetCandidates.filter((item) => !item.unitId || item.unitId === unitId);
|
||||||
|
const categories = ["character", "environment", "wardrobe", "prop", "weapon"];
|
||||||
|
return <section className="mx-auto max-w-6xl"><StageHeading eyebrow="02 / 资产拆分" title="确认镜头真正会使用的资产" description="角色、场景、服饰、配饰与武器先建立稳定版本,镜头再绑定具体版本。" /><div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">{categories.map((category) => { const confirmed = detail.assets.filter((item) => item.category === category).length; const pending = candidates.filter((item) => item.category === category && item.status === "pending_confirmation").length; return <div key={category} className="border-t border-border/70 py-4"><div className="text-xs font-medium text-foreground/55">{assetCategoryLabel(category)}</div><div className="mt-3 text-2xl font-semibold">{confirmed}</div><div className="mt-1 text-[var(--fs-micro)] text-foreground/42">已确认 · {pending} 待处理</div></div>; })}</div><div className="mt-5 flex items-center justify-between border-y border-border/70 py-5"><div><h3 className="text-sm font-semibold">资产库承担版本确认与设定维护</h3><p className="mt-1 text-xs text-foreground/48">确认后可直接在分镜工作台左栏绑定到镜头。</p></div><Link to={`/projects/${projectId}/assets`}><Button type="primary">打开资产库</Button></Link></div></section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DeliveryStage({ detail, unitId }: { detail: ProjectDetail; unitId: string }) {
|
||||||
|
const shots = detail.shots.filter((item) => item.unitId === unitId);
|
||||||
|
const readyVideos = shots.filter((shot) => detail.shotArtifacts.some((item) => item.shotId === shot.id && item.type === "video" && item.selected && item.status === "ready"));
|
||||||
|
const stale = detail.shotArtifacts.filter((item) => item.unitId === unitId && item.status === "stale").length;
|
||||||
|
return <section className="mx-auto max-w-5xl"><StageHeading eyebrow="06 / 交付与打包" title="交付前质量门禁" description="所有镜头视频就绪、过期产物清零后,再打包成片与生产资料。" /><div className="mt-6 grid gap-4 sm:grid-cols-3"><MetricCard icon={<Film className="size-5" />} label="视频已就绪" value={`${readyVideos.length} / ${shots.length}`} /><MetricCard icon={<Clock3 className="size-5" />} label="总时长" value={formatDuration(shots.reduce((total, item) => total + item.durationMs, 0))} /><MetricCard icon={<Layers3 className="size-5" />} label="过期产物" value={String(stale)} /></div><div className="mt-5 border-y border-border/70 py-5"><div className="flex items-start gap-3"><PackageCheck className="mt-0.5 size-5 text-[var(--workspace-accent)]" /><div><h3 className="text-sm font-semibold">计划交付内容</h3><p className="mt-1 text-xs leading-5 text-foreground/48">成片 MP4、字幕 SRT、分镜 JSON/CSV、资产清单和生成参数 ZIP。</p></div></div><Button className="mt-5" disabled>生成交付包(后端打包尚未接入)</Button></div></section>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
.workflow-page-root {
|
||||||
|
display: flex;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--workspace-content);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-stage-content {
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-overview-scroll {
|
||||||
|
height: 100%;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 28px 32px 64px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-production-shell {
|
||||||
|
display: grid;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
grid-template-rows: minmax(0, 1fr) clamp(168px, 20vh, 210px);
|
||||||
|
background: var(--workspace-content);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-production-main {
|
||||||
|
display: grid;
|
||||||
|
min-height: 0;
|
||||||
|
grid-template-columns: 220px minmax(500px, 1fr) 370px;
|
||||||
|
border-bottom: 1px solid var(--workspace-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-library-panel,
|
||||||
|
.workflow-shot-editor,
|
||||||
|
.workflow-preview-panel {
|
||||||
|
min-width: 0;
|
||||||
|
min-height: 0;
|
||||||
|
background: var(--workspace-surface);
|
||||||
|
animation: workflow-panel-enter var(--motion-panel) var(--motion-ease-out) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-editor { animation-delay: 35ms; }
|
||||||
|
.workflow-preview-panel { animation-delay: 70ms; }
|
||||||
|
|
||||||
|
.workflow-library-panel {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
border-right: 1px solid var(--workspace-border);
|
||||||
|
padding: 12px 10px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-library-panel .ant-segmented {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-library-scroll {
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 2px 0 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-asset-groups {
|
||||||
|
display: grid;
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-asset-groups h3 {
|
||||||
|
margin: 0 8px 6px;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 47%, transparent);
|
||||||
|
font-size: var(--fs-micro);
|
||||||
|
font-weight: 650;
|
||||||
|
letter-spacing: .04em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-asset-groups h3 span { color: color-mix(in srgb, var(--foreground) 28%, transparent); font-weight: 500; }
|
||||||
|
.workflow-asset-list { display: grid; gap: 2px; }
|
||||||
|
|
||||||
|
.workflow-asset-row {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 50px;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
padding: 6px 8px;
|
||||||
|
text-align: left;
|
||||||
|
transition: background-color var(--motion-instant) ease-out, transform var(--motion-instant) ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-asset-row:hover:not(:disabled),
|
||||||
|
.workflow-asset-row:focus-visible { background: var(--surface-hover); }
|
||||||
|
.workflow-asset-row:hover:not(:disabled) { transform: translateX(2px); }
|
||||||
|
.workflow-asset-row:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; }
|
||||||
|
.workflow-asset-row.is-active { background: var(--workspace-accent-soft); }
|
||||||
|
.workflow-asset-row:disabled { cursor: default; opacity: 1; }
|
||||||
|
|
||||||
|
.workflow-asset-thumb {
|
||||||
|
display: grid;
|
||||||
|
width: 36px;
|
||||||
|
height: 36px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
place-items: center;
|
||||||
|
border: 1px solid var(--workspace-border);
|
||||||
|
border-radius: var(--r-sm);
|
||||||
|
background: color-mix(in srgb, var(--workspace-surface-strong) 92%, var(--workspace-accent) 8%);
|
||||||
|
color: color-mix(in srgb, var(--foreground) 44%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-asset-thumb svg { width: 16px; height: 16px; }
|
||||||
|
.workflow-asset-thumb img { width: 100%; height: 100%; object-fit: cover; }
|
||||||
|
.workflow-asset-row strong { display: block; overflow: hidden; color: color-mix(in srgb, var(--foreground) 84%, transparent); font-size: var(--fs-caption); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.workflow-asset-row small { display: block; margin-top: 2px; overflow: hidden; color: color-mix(in srgb, var(--foreground) 39%, transparent); font-size: var(--fs-micro); text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.workflow-bound-dot { width: 7px; height: 7px; flex: 0 0 auto; border-radius: var(--r-full); background: var(--workspace-accent); }
|
||||||
|
|
||||||
|
.workflow-simple-list { display: grid; gap: 3px; }
|
||||||
|
.workflow-simple-list a,
|
||||||
|
.workflow-simple-list button {
|
||||||
|
display: flex;
|
||||||
|
min-height: 44px;
|
||||||
|
align-items: center;
|
||||||
|
gap: 9px;
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
padding: 7px 9px;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 56%, transparent);
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.workflow-simple-list a:hover,
|
||||||
|
.workflow-simple-list button:hover,
|
||||||
|
.workflow-simple-list a.is-active,
|
||||||
|
.workflow-simple-list button.is-active { background: var(--surface-hover); color: var(--foreground); }
|
||||||
|
.workflow-simple-list a.is-active,
|
||||||
|
.workflow-simple-list button.is-active { background: var(--workspace-accent-soft); }
|
||||||
|
.workflow-simple-list a > span:first-child,
|
||||||
|
.workflow-simple-list button > span:first-child { color: color-mix(in srgb, var(--foreground) 34%, transparent); font-size: var(--fs-micro); font-variant-numeric: tabular-nums; }
|
||||||
|
.workflow-simple-list strong { display: block; overflow: hidden; font-size: var(--fs-caption); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.workflow-simple-list small { display: block; margin-top: 2px; color: color-mix(in srgb, var(--foreground) 38%, transparent); font-size: var(--fs-micro); }
|
||||||
|
|
||||||
|
.workflow-shot-editor {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-panel-header {
|
||||||
|
display: flex;
|
||||||
|
min-height: 48px;
|
||||||
|
flex: 0 0 48px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
border-bottom: 1px solid var(--workspace-border);
|
||||||
|
padding: 0 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-heading {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-heading h2 {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
font-size: var(--fs-body);
|
||||||
|
font-weight: 650;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-number {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 42%, transparent);
|
||||||
|
font-size: var(--fs-caption);
|
||||||
|
font-weight: 700;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
letter-spacing: .02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-header {
|
||||||
|
display: grid;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
gap: 8px;
|
||||||
|
border-bottom: 1px solid var(--workspace-border);
|
||||||
|
padding: 9px 12px 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-header-row {
|
||||||
|
display: flex;
|
||||||
|
min-height: 28px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
font-size: var(--fs-caption);
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-stage-switch { width: 100%; }
|
||||||
|
|
||||||
|
.workflow-shot-form {
|
||||||
|
display: flex;
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-form-scroll {
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 14px 18px 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-form .ant-form-item { margin-bottom: 14px; }
|
||||||
|
.workflow-shot-form .ant-form-item-label { padding-bottom: 5px; }
|
||||||
|
.workflow-shot-form .ant-form-item-label > label,
|
||||||
|
.workflow-field-label { color: color-mix(in srgb, var(--foreground) 52%, transparent); font-size: var(--fs-micro); font-weight: 560; }
|
||||||
|
|
||||||
|
.workflow-form-section-heading {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-form-section-heading > span {
|
||||||
|
color: color-mix(in srgb, var(--foreground) 82%, transparent);
|
||||||
|
font-size: var(--fs-caption);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-form-section-heading > small {
|
||||||
|
overflow: hidden;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 36%, transparent);
|
||||||
|
font-size: var(--fs-micro);
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 12px; }
|
||||||
|
.workflow-form-grid.is-three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||||
|
|
||||||
|
.workflow-disclosure {
|
||||||
|
overflow: hidden;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
border: 1px solid var(--workspace-border);
|
||||||
|
border-radius: var(--r-lg);
|
||||||
|
background: color-mix(in srgb, var(--workspace-surface-strong) 76%, transparent);
|
||||||
|
transition: border-color var(--motion-instant) ease-out, background-color var(--motion-instant) ease-out, box-shadow var(--motion-instant) ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure:hover { border-color: var(--workspace-border-strong); }
|
||||||
|
.workflow-disclosure[open] {
|
||||||
|
border-color: color-mix(in srgb, var(--workspace-accent) 36%, var(--workspace-border));
|
||||||
|
background: color-mix(in srgb, var(--workspace-surface-strong) 90%, transparent);
|
||||||
|
box-shadow: 0 8px 24px color-mix(in srgb, var(--foreground) 5%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure > summary {
|
||||||
|
display: flex;
|
||||||
|
min-height: 58px;
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 9px 12px;
|
||||||
|
transition: background-color var(--motion-instant) ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure > summary::-webkit-details-marker { display: none; }
|
||||||
|
.workflow-disclosure > summary:hover { background: var(--surface-hover); }
|
||||||
|
.workflow-disclosure > summary:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; }
|
||||||
|
|
||||||
|
.workflow-disclosure-heading {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure-heading strong { display: block; font-size: var(--fs-caption); font-weight: 650; }
|
||||||
|
.workflow-disclosure-heading small { display: block; margin-top: 2px; color: color-mix(in srgb, var(--foreground) 40%, transparent); font-size: var(--fs-micro); }
|
||||||
|
|
||||||
|
.workflow-disclosure-icon {
|
||||||
|
display: grid;
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
background: var(--workspace-accent-soft);
|
||||||
|
color: var(--workspace-accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure-icon svg { width: 15px; height: 15px; }
|
||||||
|
|
||||||
|
.workflow-disclosure-summary {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 5px;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 48%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure-summary > span {
|
||||||
|
max-width: 104px;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--workspace-border);
|
||||||
|
border-radius: var(--r-full);
|
||||||
|
background: var(--workspace-surface);
|
||||||
|
padding: 3px 7px;
|
||||||
|
font-size: var(--fs-micro);
|
||||||
|
line-height: 1.25;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure-summary > span.is-model { max-width: 150px; }
|
||||||
|
.workflow-disclosure.is-advanced .workflow-disclosure-summary > span { max-width: 190px; }
|
||||||
|
|
||||||
|
.workflow-disclosure-chevron {
|
||||||
|
width: 15px;
|
||||||
|
height: 15px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
margin-left: 2px;
|
||||||
|
transition: transform var(--motion-instant) var(--motion-ease-out);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure[open] .workflow-disclosure-chevron { transform: rotate(180deg); }
|
||||||
|
|
||||||
|
.workflow-disclosure-body {
|
||||||
|
border-top: 1px solid var(--workspace-border);
|
||||||
|
animation: workflow-disclosure-reveal var(--motion-state) var(--motion-ease-out) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-disclosure-content { padding: 13px 14px 4px; }
|
||||||
|
.workflow-disclosure .ant-form-item { margin-bottom: 10px; }
|
||||||
|
|
||||||
|
.workflow-settings-section + .workflow-settings-section {
|
||||||
|
margin-top: 4px;
|
||||||
|
border-top: 1px solid var(--workspace-border);
|
||||||
|
padding-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-settings-section-title {
|
||||||
|
margin-bottom: 9px;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 58%, transparent);
|
||||||
|
font-size: var(--fs-micro);
|
||||||
|
font-weight: 650;
|
||||||
|
letter-spacing: .02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-bound-assets { margin-bottom: 14px; }
|
||||||
|
.workflow-bound-assets-heading {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.workflow-bound-assets-heading small {
|
||||||
|
color: color-mix(in srgb, var(--foreground) 34%, transparent);
|
||||||
|
font-size: var(--fs-micro);
|
||||||
|
}
|
||||||
|
.workflow-bound-assets-content {
|
||||||
|
display: flex;
|
||||||
|
min-height: 48px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 5px;
|
||||||
|
border: 1px dashed var(--workspace-border-strong);
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
padding: 8px 10px;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 38%, transparent);
|
||||||
|
font-size: var(--fs-caption);
|
||||||
|
transition: border-color var(--motion-instant) ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-bound-assets-content:hover { border-color: var(--workspace-border-strong); }
|
||||||
|
|
||||||
|
.workflow-bound-asset-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
min-width: 0;
|
||||||
|
align-items: center;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--workspace-border);
|
||||||
|
border-radius: var(--r-sm);
|
||||||
|
background: var(--workspace-surface);
|
||||||
|
color: color-mix(in srgb, var(--foreground) 72%, transparent);
|
||||||
|
font-size: var(--fs-tiny);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-bound-asset-chip em {
|
||||||
|
align-self: stretch;
|
||||||
|
padding: 4px 6px;
|
||||||
|
background: var(--workspace-accent-soft);
|
||||||
|
color: color-mix(in srgb, var(--foreground) 54%, transparent);
|
||||||
|
font-size: var(--fs-micro);
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-bound-asset-chip > span {
|
||||||
|
overflow: hidden;
|
||||||
|
padding: 4px 7px;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-editor-actions {
|
||||||
|
display: flex;
|
||||||
|
min-height: 58px;
|
||||||
|
flex: 0 0 58px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 12px;
|
||||||
|
border-top: 1px solid var(--workspace-border);
|
||||||
|
padding: 9px 16px;
|
||||||
|
background: color-mix(in srgb, var(--workspace-surface) 92%, transparent);
|
||||||
|
box-shadow: 0 -8px 24px color-mix(in srgb, var(--foreground) 4%, transparent);
|
||||||
|
backdrop-filter: blur(14px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-panel {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
border-left: 1px solid var(--workspace-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-scroll {
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-media,
|
||||||
|
.workflow-media-empty {
|
||||||
|
width: 100%;
|
||||||
|
aspect-ratio: 16 / 9;
|
||||||
|
border-radius: var(--r-lg);
|
||||||
|
background: color-mix(in srgb, var(--foreground) 5%, var(--workspace-surface));
|
||||||
|
object-fit: cover;
|
||||||
|
transition: border-color var(--motion-instant) ease-out, transform var(--motion-instant) var(--motion-ease-out);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-media:hover { transform: scale(1.005); }
|
||||||
|
|
||||||
|
.workflow-media-empty {
|
||||||
|
display: grid;
|
||||||
|
place-content: center;
|
||||||
|
justify-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
border: 1px dashed var(--workspace-border-strong);
|
||||||
|
color: color-mix(in srgb, var(--foreground) 36%, transparent);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-media-empty > span {
|
||||||
|
display: grid;
|
||||||
|
width: 54px;
|
||||||
|
height: 54px;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: var(--r-full);
|
||||||
|
background: color-mix(in srgb, var(--workspace-surface-strong) 88%, var(--workspace-accent) 12%);
|
||||||
|
color: var(--workspace-accent);
|
||||||
|
}
|
||||||
|
.workflow-media-empty p { max-width: 220px; font-size: var(--fs-caption); line-height: 1.6; }
|
||||||
|
|
||||||
|
.workflow-preview-summary {
|
||||||
|
margin-top: 12px;
|
||||||
|
border-block: 1px solid var(--workspace-border);
|
||||||
|
padding: 11px 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-preview-actions {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-history { margin-top: 16px; }
|
||||||
|
.workflow-history-title { margin-bottom: 7px; color: color-mix(in srgb, var(--foreground) 58%, transparent); font-size: var(--fs-caption); font-weight: 650; }
|
||||||
|
.workflow-history button {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 54px;
|
||||||
|
align-items: center;
|
||||||
|
gap: 9px;
|
||||||
|
border: 1px solid var(--workspace-border);
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
padding: 6px;
|
||||||
|
text-align: left;
|
||||||
|
transition: border-color var(--motion-instant) ease-out, background-color var(--motion-instant) ease-out, transform var(--motion-instant) ease-out;
|
||||||
|
}
|
||||||
|
.workflow-history button + button { margin-top: 7px; }
|
||||||
|
.workflow-history button:hover,
|
||||||
|
.workflow-history button.is-active { border-color: var(--workspace-border-strong); background: var(--surface-hover); }
|
||||||
|
.workflow-history button:hover { transform: translateY(-1px); }
|
||||||
|
.workflow-history button.is-active { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--workspace-accent) 55%, transparent); }
|
||||||
|
.workflow-history img,
|
||||||
|
.workflow-history video,
|
||||||
|
.workflow-history-placeholder { width: 66px; height: 40px; flex: 0 0 auto; border-radius: var(--r-sm); background: color-mix(in srgb, var(--foreground) 6%, transparent); object-fit: cover; }
|
||||||
|
.workflow-history-placeholder { display: grid; place-items: center; color: color-mix(in srgb, var(--foreground) 30%, transparent); }
|
||||||
|
.workflow-history-placeholder svg { width: 16px; height: 16px; }
|
||||||
|
.workflow-history strong { display: block; font-size: var(--fs-caption); font-weight: 600; }
|
||||||
|
.workflow-history small { display: block; margin-top: 2px; color: color-mix(in srgb, var(--foreground) 38%, transparent); font-size: var(--fs-micro); }
|
||||||
|
|
||||||
|
.workflow-shot-timeline {
|
||||||
|
display: flex;
|
||||||
|
min-height: 0;
|
||||||
|
flex-direction: column;
|
||||||
|
background: var(--workspace-surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-shot-timeline > header {
|
||||||
|
display: flex;
|
||||||
|
min-height: 42px;
|
||||||
|
flex: 0 0 42px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 0 16px;
|
||||||
|
}
|
||||||
|
.workflow-shot-timeline > header strong { font-size: var(--fs-caption); font-weight: 650; }
|
||||||
|
.workflow-shot-timeline > header span { margin-left: 8px; color: color-mix(in srgb, var(--foreground) 42%, transparent); font-size: var(--fs-micro); }
|
||||||
|
|
||||||
|
.workflow-shot-track {
|
||||||
|
display: flex;
|
||||||
|
min-height: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
gap: 8px;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding: 0 14px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-timeline-shot,
|
||||||
|
.workflow-add-shot-card {
|
||||||
|
width: 148px;
|
||||||
|
min-width: 148px;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--workspace-border);
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
background: var(--workspace-surface-strong);
|
||||||
|
text-align: left;
|
||||||
|
transition: border-color var(--motion-instant) ease-out, background-color var(--motion-instant) ease-out, box-shadow var(--motion-instant) ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-timeline-shot:hover,
|
||||||
|
.workflow-timeline-shot:focus-visible { border-color: var(--workspace-border-strong); background: var(--surface-hover); }
|
||||||
|
.workflow-timeline-shot:focus-visible,
|
||||||
|
.workflow-add-shot-card:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; }
|
||||||
|
.workflow-timeline-shot.is-active { border-color: var(--workspace-accent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--workspace-accent) 42%, transparent); }
|
||||||
|
|
||||||
|
.workflow-timeline-media {
|
||||||
|
display: grid;
|
||||||
|
height: 62px;
|
||||||
|
place-items: center;
|
||||||
|
overflow: hidden;
|
||||||
|
background: color-mix(in srgb, var(--foreground) 5%, var(--workspace-surface));
|
||||||
|
color: color-mix(in srgb, var(--foreground) 25%, transparent);
|
||||||
|
}
|
||||||
|
.workflow-timeline-media img,
|
||||||
|
.workflow-timeline-media video { width: 100%; height: 100%; object-fit: cover; }
|
||||||
|
.workflow-timeline-media > svg { width: 20px; height: 20px; }
|
||||||
|
.workflow-timeline-copy { display: block; padding: 7px 9px 8px; }
|
||||||
|
.workflow-timeline-copy > span:first-child { display: flex; align-items: center; justify-content: space-between; gap: 6px; }
|
||||||
|
.workflow-timeline-copy strong { font-size: var(--fs-micro); font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||||
|
.workflow-timeline-copy small { color: color-mix(in srgb, var(--foreground) 42%, transparent); font-size: 10px; }
|
||||||
|
.workflow-timeline-copy em { display: block; overflow: hidden; margin: 3px 0 6px; color: color-mix(in srgb, var(--foreground) 58%, transparent); font-size: var(--fs-micro); font-style: normal; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
|
||||||
|
.workflow-add-shot-card {
|
||||||
|
display: grid;
|
||||||
|
place-content: center;
|
||||||
|
justify-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
border-style: dashed;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 42%, transparent);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.workflow-add-shot-card:hover { border-color: var(--workspace-accent); color: var(--foreground); }
|
||||||
|
.workflow-add-shot-card:hover { background: var(--workspace-accent-soft); }
|
||||||
|
.workflow-add-shot-card span { font-size: var(--fs-caption); }
|
||||||
|
|
||||||
|
.workflow-empty-shot {
|
||||||
|
display: grid;
|
||||||
|
height: 100%;
|
||||||
|
place-items: center;
|
||||||
|
border: 1px dashed var(--workspace-border-strong);
|
||||||
|
margin: 14px;
|
||||||
|
border-radius: var(--r-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.workflow-workbench-loading {
|
||||||
|
display: grid;
|
||||||
|
height: 100%;
|
||||||
|
place-items: center;
|
||||||
|
color: color-mix(in srgb, var(--foreground) 44%, transparent);
|
||||||
|
font-size: var(--fs-caption);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes workflow-panel-enter {
|
||||||
|
from { opacity: 0; transform: translateY(4px); }
|
||||||
|
to { opacity: 1; transform: translateY(0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes workflow-disclosure-reveal {
|
||||||
|
from { opacity: 0; transform: translateY(-4px); }
|
||||||
|
to { opacity: 1; transform: translateY(0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1280px) {
|
||||||
|
.workflow-production-main { grid-template-columns: 204px minmax(420px, 1fr) 320px; }
|
||||||
|
.workflow-disclosure-summary > span.is-model { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1050px) {
|
||||||
|
.workflow-production-main { grid-template-columns: minmax(420px, 1fr) 300px; }
|
||||||
|
.workflow-library-panel { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.workflow-production-shell { grid-template-rows: minmax(0, 1fr) 148px; }
|
||||||
|
.workflow-production-main { display: block; overflow: hidden; }
|
||||||
|
.workflow-shot-editor { height: 100%; }
|
||||||
|
.workflow-preview-panel { display: none; }
|
||||||
|
.workflow-form-grid,
|
||||||
|
.workflow-form-grid.is-three { grid-template-columns: 1fr; }
|
||||||
|
.workflow-disclosure-summary > span { display: none; }
|
||||||
|
.workflow-shot-form-scroll { padding-inline: 14px; }
|
||||||
|
.workflow-timeline-shot,
|
||||||
|
.workflow-add-shot-card { width: 138px; min-width: 138px; }
|
||||||
|
.workflow-overview-scroll { padding: 20px 16px 48px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.workflow-library-panel,
|
||||||
|
.workflow-shot-editor,
|
||||||
|
.workflow-preview-panel,
|
||||||
|
.workflow-disclosure-body { animation: none; }
|
||||||
|
.workflow-asset-row,
|
||||||
|
.workflow-preview-media,
|
||||||
|
.workflow-history button,
|
||||||
|
.workflow-timeline-shot,
|
||||||
|
.workflow-add-shot-card,
|
||||||
|
.workflow-disclosure-chevron { transition: none; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { lazy, Suspense, useEffect, useMemo, useState } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { App, Button, Empty } from "antd";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
|
||||||
|
import { saveProjectShot, type ProjectDetail } from "@/services/api/projects";
|
||||||
|
|
||||||
|
import { AssetsStage, DeliveryStage, StoryStage } from "./workflow-stage-views";
|
||||||
|
import { type ShortDramaWorkflowStage, workflowStages } from "./workflow-shared";
|
||||||
|
import "./workflow.css";
|
||||||
|
|
||||||
|
const WorkflowProductionWorkbench = lazy(() => import("./workflow-production-workbench"));
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
detail: ProjectDetail;
|
||||||
|
projectId: string;
|
||||||
|
unitId: string;
|
||||||
|
stage: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function ProjectWorkflowView({ detail, projectId, unitId, stage }: Props) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { message } = App.useApp();
|
||||||
|
const orderedUnits = useMemo(() => detail.units.slice().sort((left, right) => left.position - right.position), [detail.units]);
|
||||||
|
const unit = orderedUnits.find((item) => item.id === unitId) || orderedUnits[0];
|
||||||
|
const activeStage = workflowStages.some((item) => item.key === stage) ? stage as ShortDramaWorkflowStage : "video";
|
||||||
|
const shots = useMemo(() => (detail.shots || []).filter((item) => item.unitId === unit?.id).slice().sort((left, right) => left.position - right.position), [detail.shots, unit?.id]);
|
||||||
|
const workflow = useMemo(() => (detail.workflows || []).find((item) => item.instance?.unitId === unit?.id && (item.steps || []).some((step) => step.stepKey === "previz")), [detail.workflows, unit?.id]);
|
||||||
|
const rememberedShotId = sessionStorage.getItem(`project-workflow-selected-shot:${projectId}`) || "";
|
||||||
|
const [selectedShotId, setSelectedShotId] = useState(rememberedShotId);
|
||||||
|
const selectedShot = shots.find((item) => item.id === selectedShotId) || shots[0];
|
||||||
|
const activeStep = workflow?.steps?.find((item) => item.stepKey === activeStage);
|
||||||
|
const productionStage = activeStage === "storyboard" || activeStage === "previz" || activeStage === "video";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selectedShot) return;
|
||||||
|
if (selectedShot.id !== selectedShotId) setSelectedShotId(selectedShot.id);
|
||||||
|
sessionStorage.setItem(`project-workflow-selected-shot:${projectId}`, selectedShot.id);
|
||||||
|
}, [projectId, selectedShot, selectedShotId]);
|
||||||
|
|
||||||
|
const refresh = async () => {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["project", projectId] }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["projects"] }),
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
const addShot = useMutation({
|
||||||
|
mutationFn: () => {
|
||||||
|
if (!unit) throw new Error("请先添加章节");
|
||||||
|
return saveProjectShot(projectId, {
|
||||||
|
unitId: unit.id,
|
||||||
|
title: `SC.${String(shots.length + 1).padStart(2, "0")}`,
|
||||||
|
description: "待补充分镜画面",
|
||||||
|
position: shots.length,
|
||||||
|
durationMs: 3000,
|
||||||
|
revision: { plotDescription: "待补充分镜画面", durationMs: 3000 },
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: async ({ shot }) => {
|
||||||
|
setSelectedShotId(shot.id);
|
||||||
|
sessionStorage.setItem(`project-workflow-selected-shot:${projectId}`, shot.id);
|
||||||
|
await refresh();
|
||||||
|
message.success("已新增分镜");
|
||||||
|
},
|
||||||
|
onError: (error) => message.error(error instanceof Error ? error.message : "新增分镜失败"),
|
||||||
|
});
|
||||||
|
if (!unit) {
|
||||||
|
return <div className="grid h-full place-items-center"><Empty description="先添加一个章节,再进入分镜制作"><Link to={`/projects/${projectId}/chapters`}><Button type="primary">添加章节</Button></Link></Empty></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="workflow-page-root">
|
||||||
|
<main className={`workflow-stage-content ${productionStage ? "is-production" : ""}`}>
|
||||||
|
{activeStage === "story" ? <div className="workflow-overview-scroll thin-scrollbar"><StoryStage detail={detail} projectId={projectId} unitId={unit.id} /></div> : null}
|
||||||
|
{activeStage === "assets" ? <div className="workflow-overview-scroll thin-scrollbar"><AssetsStage detail={detail} projectId={projectId} unitId={unit.id} /></div> : null}
|
||||||
|
{productionStage ? <Suspense fallback={<div className="workflow-workbench-loading">正在准备分镜工作台…</div>}><WorkflowProductionWorkbench activeStage={activeStage} detail={detail} projectId={projectId} unitId={unit.id} workflowStep={activeStep} selectedShot={selectedShot} onSelectShot={setSelectedShotId} onRefresh={refresh} onAddShot={() => addShot.mutate()} addingShot={addShot.isPending} /></Suspense> : null}
|
||||||
|
{activeStage === "delivery" ? <div className="workflow-overview-scroll thin-scrollbar"><DeliveryStage detail={detail} unitId={unit.id} /></div> : null}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -149,6 +149,14 @@ export const router = createBrowserRouter([
|
|||||||
</RequireAuth>
|
</RequireAuth>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: "/projects/:projectId/workflow/:unitId/:stage",
|
||||||
|
element: (
|
||||||
|
<RequireAuth>
|
||||||
|
<RequireFeature feature="shortDramaEnabled">{deferred(<ProjectDetailPage />)}</RequireFeature>
|
||||||
|
</RequireAuth>
|
||||||
|
),
|
||||||
|
},
|
||||||
{ path: "/canvas", element: <RequireAuth>{deferred(<CanvasPage />)}</RequireAuth> },
|
{ path: "/canvas", element: <RequireAuth>{deferred(<CanvasPage />)}</RequireAuth> },
|
||||||
{ path: "/canvas/:id", element: <RequireAuth>{deferred(<CanvasProjectPage />)}</RequireAuth> },
|
{ path: "/canvas/:id", element: <RequireAuth>{deferred(<CanvasProjectPage />)}</RequireAuth> },
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ export type ProjectShot = {
|
|||||||
id: string;
|
id: string;
|
||||||
projectId: string;
|
projectId: string;
|
||||||
unitId?: string;
|
unitId?: string;
|
||||||
|
currentRevisionId?: string;
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
position: number;
|
position: number;
|
||||||
@@ -137,6 +138,58 @@ export type ProjectShot = {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type ShotRevision = {
|
||||||
|
id: string;
|
||||||
|
shotId: string;
|
||||||
|
version: number;
|
||||||
|
plotDescription: string;
|
||||||
|
action: string;
|
||||||
|
dialogue: string;
|
||||||
|
shotSize: string;
|
||||||
|
cameraAngle: string;
|
||||||
|
cameraMovement: string;
|
||||||
|
durationMs: number;
|
||||||
|
imagePrompt: string;
|
||||||
|
videoPrompt: string;
|
||||||
|
negativePrompt: string;
|
||||||
|
continuityNotes: string;
|
||||||
|
actionBeatsJson: string;
|
||||||
|
createdBy?: string;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ShotArtifact = {
|
||||||
|
id: string;
|
||||||
|
projectId: string;
|
||||||
|
unitId?: string;
|
||||||
|
shotId: string;
|
||||||
|
revisionId?: string;
|
||||||
|
taskId?: string;
|
||||||
|
type: "storyboard" | "action_board" | "start_frame" | "end_frame" | "video" | "audio" | "subtitle" | "delivery" | string;
|
||||||
|
version: number;
|
||||||
|
resourceId?: string;
|
||||||
|
status: "pending" | "running" | "ready" | "failed" | "stale" | string;
|
||||||
|
selected: boolean;
|
||||||
|
metadataJson: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ShotRevisionInput = {
|
||||||
|
plotDescription: string;
|
||||||
|
action?: string;
|
||||||
|
dialogue?: string;
|
||||||
|
shotSize?: string;
|
||||||
|
cameraAngle?: string;
|
||||||
|
cameraMovement?: string;
|
||||||
|
durationMs?: number;
|
||||||
|
imagePrompt?: string;
|
||||||
|
videoPrompt?: string;
|
||||||
|
negativePrompt?: string;
|
||||||
|
continuityNotes?: string;
|
||||||
|
actionBeats?: Array<Record<string, unknown>>;
|
||||||
|
};
|
||||||
|
|
||||||
export type ShotAssetReference = {
|
export type ShotAssetReference = {
|
||||||
id: string;
|
id: string;
|
||||||
shotId: string;
|
shotId: string;
|
||||||
@@ -187,6 +240,8 @@ export type ProjectDetail = {
|
|||||||
assetFolders: ProjectAssetFolder[];
|
assetFolders: ProjectAssetFolder[];
|
||||||
workflows: ProjectWorkflow[];
|
workflows: ProjectWorkflow[];
|
||||||
shots: ProjectShot[];
|
shots: ProjectShot[];
|
||||||
|
shotRevisions: ShotRevision[];
|
||||||
|
shotArtifacts: ShotArtifact[];
|
||||||
shotReferences: ShotAssetReference[];
|
shotReferences: ShotAssetReference[];
|
||||||
assetCandidates: ProjectAssetCandidate[];
|
assetCandidates: ProjectAssetCandidate[];
|
||||||
};
|
};
|
||||||
@@ -198,7 +253,43 @@ export function listProjects(params?: { page: number; pageSize: number }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getProject(id: string) {
|
export function getProject(id: string) {
|
||||||
return request<ProjectDetail>(api.get(`/projects/${encodeURIComponent(id)}`));
|
return request<ProjectDetail>(api.get(`/projects/${encodeURIComponent(id)}`)).then(normalizeProjectDetail);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeProjectDetail(detail: ProjectDetail): ProjectDetail {
|
||||||
|
const workflows = Array.isArray(detail.workflows)
|
||||||
|
? detail.workflows.map((workflow) => ({
|
||||||
|
...workflow,
|
||||||
|
steps: Array.isArray(workflow.steps) ? workflow.steps : [],
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
const assets = Array.isArray(detail.assets)
|
||||||
|
? detail.assets.map((asset) => ({
|
||||||
|
...asset,
|
||||||
|
usages: Array.isArray(asset.usages) ? asset.usages : [],
|
||||||
|
...(asset.character ? {
|
||||||
|
character: {
|
||||||
|
...asset.character,
|
||||||
|
representations: Array.isArray(asset.character.representations) ? asset.character.representations : [],
|
||||||
|
},
|
||||||
|
} : {}),
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
...detail,
|
||||||
|
units: Array.isArray(detail.units) ? detail.units : [],
|
||||||
|
canvases: Array.isArray(detail.canvases) ? detail.canvases : [],
|
||||||
|
canvasUnitLinks: Array.isArray(detail.canvasUnitLinks) ? detail.canvasUnitLinks : [],
|
||||||
|
assets,
|
||||||
|
assetFolders: Array.isArray(detail.assetFolders) ? detail.assetFolders : [],
|
||||||
|
workflows,
|
||||||
|
shots: Array.isArray(detail.shots) ? detail.shots : [],
|
||||||
|
shotRevisions: Array.isArray(detail.shotRevisions) ? detail.shotRevisions : [],
|
||||||
|
shotArtifacts: Array.isArray(detail.shotArtifacts) ? detail.shotArtifacts : [],
|
||||||
|
shotReferences: Array.isArray(detail.shotReferences) ? detail.shotReferences : [],
|
||||||
|
assetCandidates: Array.isArray(detail.assetCandidates) ? detail.assetCandidates : [],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createProject(input: { name: string; type: string; aspectRatio: string; sourceType: string; description?: string; stylePresetId?: string; styleProfileJson?: string }) {
|
export function createProject(input: { name: string; type: string; aspectRatio: string; sourceType: string; description?: string; stylePresetId?: string; styleProfileJson?: string }) {
|
||||||
@@ -317,7 +408,7 @@ export function createUnitWorkflow(projectId: string, unitId: string) {
|
|||||||
return request<{ workflow: ProjectWorkflow }>(api.post(`/projects/${encodeURIComponent(projectId)}/workflows`, { unitId }));
|
return request<{ workflow: ProjectWorkflow }>(api.post(`/projects/${encodeURIComponent(projectId)}/workflows`, { unitId }));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveProjectShot(projectId: string, input: { id?: string; unitId?: string; title: string; description?: string; position?: number; durationMs?: number; status?: string }) {
|
export function saveProjectShot(projectId: string, input: { id?: string; unitId?: string; title: string; description?: string; position?: number; durationMs?: number; status?: string; revision?: Partial<ShotRevisionInput> }) {
|
||||||
return request<{ shot: ProjectShot }>(api.post(`/projects/${encodeURIComponent(projectId)}/shots`, input));
|
return request<{ shot: ProjectShot }>(api.post(`/projects/${encodeURIComponent(projectId)}/shots`, input));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,6 +420,10 @@ export function linkShotAsset(projectId: string, shotId: string, input: { assetV
|
|||||||
return request<{ reference: ShotAssetReference }>(api.post(`/projects/${encodeURIComponent(projectId)}/shots/${encodeURIComponent(shotId)}/assets`, input));
|
return request<{ reference: ShotAssetReference }>(api.post(`/projects/${encodeURIComponent(projectId)}/shots/${encodeURIComponent(shotId)}/assets`, input));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function createShotRevision(projectId: string, shotId: string, input: ShotRevisionInput) {
|
||||||
|
return request<{ shot: ProjectShot; revision: ShotRevision }>(api.post(`/projects/${encodeURIComponent(projectId)}/shots/${encodeURIComponent(shotId)}/revisions`, input));
|
||||||
|
}
|
||||||
|
|
||||||
export function createProjectAssetCandidates(projectId: string, candidates: Array<{ unitId?: string; shotId?: string; name: string; category: string; details?: Record<string, unknown> }>) {
|
export function createProjectAssetCandidates(projectId: string, candidates: Array<{ unitId?: string; shotId?: string; name: string; category: string; details?: Record<string, unknown> }>) {
|
||||||
return request<{ candidates: ProjectAssetCandidate[] }>(api.post(`/projects/${encodeURIComponent(projectId)}/asset-candidates`, { candidates }));
|
return request<{ candidates: ProjectAssetCandidate[] }>(api.post(`/projects/${encodeURIComponent(projectId)}/asset-candidates`, { candidates }));
|
||||||
}
|
}
|
||||||
@@ -341,6 +436,6 @@ export function updateWorkflowStep(projectId: string, stepId: string, input: { s
|
|||||||
return request<{ step: WorkflowStep }>(api.patch(`/projects/${encodeURIComponent(projectId)}/workflow-steps/${encodeURIComponent(stepId)}`, input));
|
return request<{ step: WorkflowStep }>(api.patch(`/projects/${encodeURIComponent(projectId)}/workflow-steps/${encodeURIComponent(stepId)}`, input));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function registerProjectTaskOutput(projectId: string, stepId: string, input: { taskId: string; assetVersionId?: string; resourceId?: string; mediaType?: string; role?: string; metadataJson?: string; outputJson?: string }) {
|
export function registerProjectTaskOutput(projectId: string, stepId: string, input: { taskId: string; canvasId?: string; unitId?: string; shotId?: string; artifactType?: string; assetVersionId?: string; resourceId?: string; mediaType?: string; role?: string; metadataJson?: string; outputJson?: string }) {
|
||||||
return request<{ step: WorkflowStep }>(api.post(`/projects/${encodeURIComponent(projectId)}/workflow-steps/${encodeURIComponent(stepId)}/task-output`, input));
|
return request<{ step: WorkflowStep }>(api.post(`/projects/${encodeURIComponent(projectId)}/workflow-steps/${encodeURIComponent(stepId)}/task-output`, input));
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
|
||||||
|
import { defaultPriceTier, priceTierResolutionFromForm, priceTierToForm, priceTierVideoSecondsFromForm, skuSelectorFromForm } from "../src/pages/admin/components/channel-model-price-tier-form";
|
||||||
|
import type { ChannelModelPriceTier } from "../src/services/api/wallet";
|
||||||
|
|
||||||
|
describe("channel model price tier defaults", () => {
|
||||||
|
test("creates a usable all-spec fallback price by default", () => {
|
||||||
|
const tier = defaultPriceTier();
|
||||||
|
|
||||||
|
expect(tier.matchMode).toBe("default");
|
||||||
|
expect(tier.priceConfigured).toBe(true);
|
||||||
|
expect(tier.enabled).toBe(true);
|
||||||
|
expect(skuSelectorFromForm("image", { ...tier, quality: "2k", size: "1:1" })).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps explicit image specification pricing when advanced mode is selected", () => {
|
||||||
|
const tier = defaultPriceTier("advanced");
|
||||||
|
|
||||||
|
expect(skuSelectorFromForm("image", { ...tier, quality: "2k", size: "1:1" })).toEqual({ quality: "2k", size: "1:1" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("drops stale video selectors after switching back to the default price", () => {
|
||||||
|
const tier = { ...defaultPriceTier("advanced"), resolution: "1080p", videoSeconds: 10, imageCount: 2 };
|
||||||
|
const defaultTier = { ...tier, matchMode: "default" as const };
|
||||||
|
|
||||||
|
expect(skuSelectorFromForm("video", defaultTier)).toEqual({});
|
||||||
|
expect(priceTierResolutionFromForm("video", defaultTier)).toBe("*");
|
||||||
|
expect(priceTierVideoSecondsFromForm("video", defaultTier)).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("restores existing specific tiers in advanced mode and wildcard tiers as defaults", () => {
|
||||||
|
const base: ChannelModelPriceTier = {
|
||||||
|
id: "tier-1",
|
||||||
|
channelModelId: "model-1",
|
||||||
|
selector: {},
|
||||||
|
selectorKey: "{}",
|
||||||
|
resolution: "*",
|
||||||
|
videoSeconds: 0,
|
||||||
|
providerModelKey: "gpt-image-2",
|
||||||
|
billingMode: "fixed_request" as const,
|
||||||
|
unitPriceMicrocredits: 4_000_000,
|
||||||
|
inputTokenPriceMicrocredits: 0,
|
||||||
|
outputTokenPriceMicrocredits: 0,
|
||||||
|
cachedTokenPriceMicrocredits: 0,
|
||||||
|
priceConfigured: true,
|
||||||
|
enabled: true,
|
||||||
|
priceVersion: 1,
|
||||||
|
createdAt: "2026-08-29T00:00:00Z",
|
||||||
|
updatedAt: "2026-08-29T00:00:00Z",
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(priceTierToForm(base).matchMode).toBe("default");
|
||||||
|
expect(priceTierToForm({ ...base, selector: { quality: "2k" } }).matchMode).toBe("advanced");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
|
||||||
|
import {
|
||||||
|
readWorkspaceSidebarCollapsed,
|
||||||
|
WORKSPACE_SIDEBAR_STORAGE_KEY,
|
||||||
|
writeWorkspaceSidebarCollapsed,
|
||||||
|
} from "../src/components/layout/workspace-sidebar-state";
|
||||||
|
|
||||||
|
function memoryStorage(initial?: string) {
|
||||||
|
const values = new Map<string, string>();
|
||||||
|
if (initial !== undefined) values.set(WORKSPACE_SIDEBAR_STORAGE_KEY, initial);
|
||||||
|
return {
|
||||||
|
values,
|
||||||
|
getItem: (key: string) => values.get(key) ?? null,
|
||||||
|
setItem: (key: string, value: string) => values.set(key, value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("workspace sidebar state", () => {
|
||||||
|
test("restores the persisted collapsed state after refresh", () => {
|
||||||
|
expect(readWorkspaceSidebarCollapsed(memoryStorage("1"))).toBe(true);
|
||||||
|
expect(readWorkspaceSidebarCollapsed(memoryStorage("0"))).toBe(false);
|
||||||
|
expect(readWorkspaceSidebarCollapsed(memoryStorage())).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("persists both collapsed and expanded states", () => {
|
||||||
|
const storage = memoryStorage();
|
||||||
|
|
||||||
|
writeWorkspaceSidebarCollapsed(true, storage);
|
||||||
|
expect(storage.values.get(WORKSPACE_SIDEBAR_STORAGE_KEY)).toBe("1");
|
||||||
|
|
||||||
|
writeWorkspaceSidebarCollapsed(false, storage);
|
||||||
|
expect(storage.values.get(WORKSPACE_SIDEBAR_STORAGE_KEY)).toBe("0");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps sidebar interaction available when storage is blocked", () => {
|
||||||
|
const blockedStorage = {
|
||||||
|
getItem: () => {
|
||||||
|
throw new Error("blocked");
|
||||||
|
},
|
||||||
|
setItem: () => {
|
||||||
|
throw new Error("blocked");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(readWorkspaceSidebarCollapsed(blockedStorage)).toBe(false);
|
||||||
|
expect(() => writeWorkspaceSidebarCollapsed(true, blockedStorage)).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user