Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ec7bbdc20 |
@@ -105,10 +105,6 @@ type RecordQuery struct {
|
|||||||
Keyword string
|
Keyword string
|
||||||
Cursor string
|
Cursor string
|
||||||
Limit int
|
Limit int
|
||||||
// Granularity is only honoured by the statistics dashboard. Empty keeps the
|
|
||||||
// historical weekly board; "day"|"week"|"month"|"custom" makes every panel
|
|
||||||
// follow the selected Window alone.
|
|
||||||
Granularity string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type QualityKey struct {
|
type QualityKey struct {
|
||||||
|
|||||||
@@ -19,11 +19,10 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
var request struct {
|
var request struct {
|
||||||
Start string `json:"start"`
|
Start string `json:"start"`
|
||||||
End string `json:"end"`
|
End string `json:"end"`
|
||||||
Keyword string `json:"keyword"`
|
Keyword string `json:"keyword"`
|
||||||
Filters map[string]string `json:"filters,omitempty"`
|
Filters map[string]string `json:"filters,omitempty"`
|
||||||
Granularity string `json:"granularity,omitempty"`
|
|
||||||
}
|
}
|
||||||
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
||||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||||
@@ -39,7 +38,7 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
|||||||
qaOpsError(w, e)
|
qaOpsError(w, e)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters, Granularity: request.Granularity})
|
dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters})
|
||||||
if e != nil {
|
if e != nil {
|
||||||
if errors.Is(e, qaopsquality.ErrConflict) {
|
if errors.Is(e, qaopsquality.ErrConflict) {
|
||||||
writeQualityError(w, e)
|
writeQualityError(w, e)
|
||||||
|
|||||||
@@ -29,27 +29,6 @@ func (s *dashboardReaderSpy) ReadMasterDashboard(ctx context.Context, q dobotaio
|
|||||||
s.masterCalls++
|
s.masterCalls++
|
||||||
return s.ReadDashboard(ctx, q)
|
return s.ReadDashboard(ctx, q)
|
||||||
}
|
}
|
||||||
func TestQADashboardForwardsGranularityToTheReader(t *testing.T) {
|
|
||||||
reader := &dashboardReaderSpy{}
|
|
||||||
auth := newFakeAuthStore()
|
|
||||||
auth.sessions["dash-admin"] = "usr-boss"
|
|
||||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 12, 3, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}})
|
|
||||||
if e != nil {
|
|
||||||
t.Fatal(e)
|
|
||||||
}
|
|
||||||
body := `{"start":"2026-11-01T00:00:00+08:00","end":"2026-12-01T00:00:00+08:00","keyword":"","granularity":"month"}`
|
|
||||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(body))
|
|
||||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"})
|
|
||||||
r.Header.Set("X-Governance-Action", "qa-dashboard")
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
h.ServeHTTP(w, r)
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Fatalf("month dashboard status=%d want200", w.Code)
|
|
||||||
}
|
|
||||||
if reader.query.Granularity != "month" {
|
|
||||||
t.Fatalf("granularity = %q, want month", reader.query.Granularity)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
||||||
reader := &dashboardReaderSpy{}
|
reader := &dashboardReaderSpy{}
|
||||||
auth := newFakeAuthStore()
|
auth := newFakeAuthStore()
|
||||||
|
|||||||
@@ -128,21 +128,6 @@ SET publication_id = EXCLUDED.publication_id,
|
|||||||
resolution_reason = '',
|
resolution_reason = '',
|
||||||
created_at = EXCLUDED.created_at
|
created_at = EXCLUDED.created_at
|
||||||
RETURNING job_id
|
RETURNING job_id
|
||||||
), parked_publication AS (
|
|
||||||
-- 上传重试耗尽时把对账面同步成失败:否则 publication 停在
|
|
||||||
-- pending/uploading,重试入口(要求 failed/stalled)永远 409,
|
|
||||||
-- 页面上的「重试」看起来点了没反应。
|
|
||||||
UPDATE test_publications p
|
|
||||||
SET ingest_state = CASE WHEN p.ingest_state = 'uploading' THEN 'failed' ELSE p.ingest_state END,
|
|
||||||
processing_state = 'failed',
|
|
||||||
last_error = $3,
|
|
||||||
updated_at = $4
|
|
||||||
FROM updated
|
|
||||||
WHERE updated.state = 'failed'
|
|
||||||
AND updated.type = 'test.upload'
|
|
||||||
AND updated.payload->>'publication_id' = p.id
|
|
||||||
AND p.knowledge_id = ''
|
|
||||||
RETURNING p.id
|
|
||||||
)
|
)
|
||||||
SELECT id FROM updated
|
SELECT id FROM updated
|
||||||
`
|
`
|
||||||
|
|||||||
@@ -273,8 +273,8 @@ WITH updated AS (
|
|||||||
max_attempts, idempotency_key, created_at, updated_at
|
max_attempts, idempotency_key, created_at, updated_at
|
||||||
)
|
)
|
||||||
SELECT 'job-' || substring(md5($1 || '#test.poll#' || updated.retry_count || '#1') from 1 for 32),
|
SELECT 'job-' || substring(md5($1 || '#test.poll#' || updated.retry_count || '#1') from 1 for 32),
|
||||||
'test.poll', $5::jsonb, 'pending', $6, $7, $8,
|
'test.poll', $4::jsonb, 'pending', $5, $6, $7,
|
||||||
'test-poll:' || $1 || ':' || updated.retry_count || ':1', $4, $4
|
'test-poll:' || $1 || ':' || updated.retry_count || ':1', $3, $3
|
||||||
FROM updated
|
FROM updated
|
||||||
ON CONFLICT (idempotency_key) DO NOTHING
|
ON CONFLICT (idempotency_key) DO NOTHING
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -232,13 +232,6 @@ func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (Knowled
|
|||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||||
req.Header.Set("X-API-Key", c.apiKey)
|
req.Header.Set("X-API-Key", c.apiKey)
|
||||||
// A platform-scoped key is refused with 409 TENANT_REQUIRED until it names a
|
|
||||||
// workspace, and a multipart body cannot be replayed: the workspace has to be
|
|
||||||
// attached here, from the one BeginTask already discovered. Leaving it off
|
|
||||||
// turned every upload into a "conflict" that the handler read as a duplicate.
|
|
||||||
if tenant := c.currentTenant(); tenant != "" {
|
|
||||||
req.Header.Set("X-Tenant-ID", tenant)
|
|
||||||
}
|
|
||||||
resp, err := c.httpClient.Do(req)
|
resp, err := c.httpClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = pipeReader.CloseWithError(err)
|
_ = pipeReader.CloseWithError(err)
|
||||||
@@ -252,19 +245,8 @@ func (c *Client) UploadFile(ctx context.Context, request UploadRequest) (Knowled
|
|||||||
|
|
||||||
var response knowledgeResponse
|
var response knowledgeResponse
|
||||||
if resp.StatusCode == http.StatusConflict {
|
if resp.StatusCode == http.StatusConflict {
|
||||||
payload, readErr := io.ReadAll(io.LimitReader(resp.Body, c.maxResponseBytes+1))
|
if err := c.decodeBody(resp, &response); err != nil {
|
||||||
resp.Body.Close()
|
return Knowledge{}, err
|
||||||
if readErr != nil {
|
|
||||||
return Knowledge{}, errors.New("read WeKnora response")
|
|
||||||
}
|
|
||||||
// TENANT_REQUIRED shares the 409 status with a real duplicate. Reading it
|
|
||||||
// as ErrConflict made the caller adopt a "duplicate" that never existed,
|
|
||||||
// so it is reported as a bare 409 and dead-letters with a clear reason.
|
|
||||||
if bytes.Contains(payload, []byte(`"TENANT_REQUIRED"`)) {
|
|
||||||
return Knowledge{}, &HTTPError{StatusCode: http.StatusConflict}
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(payload, &response); err != nil {
|
|
||||||
return Knowledge{}, errors.New("decode WeKnora response")
|
|
||||||
}
|
}
|
||||||
return response.Data, ErrConflict
|
return response.Data, ErrConflict
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -555,106 +555,6 @@ func TestClientTenantKeyNeverSendsWorkspaceHeader(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// A multipart upload cannot be replayed, so the workspace that BeginTask
|
|
||||||
// discovered has to ride on the upload request itself. Without it a 0.9
|
|
||||||
// platform key gets 409 TENANT_REQUIRED and the caller reads that as a
|
|
||||||
// duplicate document.
|
|
||||||
func TestUploadFileSendsDiscoveredWorkspace(t *testing.T) {
|
|
||||||
const apiKey = "platform" + "-key"
|
|
||||||
var uploadTenant atomic.Value
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
switch r.URL.Path {
|
|
||||||
case "/api/v1/tenants/all":
|
|
||||||
_, _ = w.Write([]byte(`{"success":true,"data":{"items":[{"id":10000}]}}`))
|
|
||||||
case "/api/v1/knowledge-bases/kb-1":
|
|
||||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-1","tenant_id":10000}}`))
|
|
||||||
case "/api/v1/knowledge-bases/kb-1/knowledge/file":
|
|
||||||
uploadTenant.Store(r.Header.Get("X-Tenant-ID"))
|
|
||||||
if r.Header.Get("X-Tenant-ID") != "10000" {
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_, _ = w.Write([]byte(`{"success":true,"data":{"id":"knowledge-1","knowledge_base_id":"kb-1","parse_status":"processing"}}`))
|
|
||||||
default:
|
|
||||||
t.Fatalf("unexpected path %s", r.URL.Path)
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
|
|
||||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: apiKey, Timeout: time.Second})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if _, err := client.GetKnowledgeBase(context.Background(), "kb-1"); err != nil {
|
|
||||||
t.Fatalf("GetKnowledgeBase() error = %v", err)
|
|
||||||
}
|
|
||||||
knowledge, err := client.UploadFile(context.Background(), UploadRequest{
|
|
||||||
KnowledgeBaseID: "kb-1",
|
|
||||||
FileName: "doc.pdf",
|
|
||||||
Content: strings.NewReader("%PDF-1.4"),
|
|
||||||
})
|
|
||||||
if err != nil || knowledge.ID != "knowledge-1" {
|
|
||||||
t.Fatalf("UploadFile() = %#v, %v", knowledge, err)
|
|
||||||
}
|
|
||||||
if got, _ := uploadTenant.Load().(string); got != "10000" {
|
|
||||||
t.Fatalf("upload X-Tenant-ID = %q, want 10000", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A workspace refusal on the upload is not a duplicate: it must surface as a
|
|
||||||
// plain 409 so the handler dead-letters it with a readable reason.
|
|
||||||
func TestUploadFileTenantRequiredIsNotDuplicate(t *testing.T) {
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = w.Write([]byte(`{"code":"TENANT_REQUIRED","error":"Workspace required"}`))
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "platform-key", Timeout: time.Second})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
_, err = client.UploadFile(context.Background(), UploadRequest{
|
|
||||||
KnowledgeBaseID: "kb-1",
|
|
||||||
FileName: "doc.pdf",
|
|
||||||
Content: strings.NewReader("%PDF-1.4"),
|
|
||||||
})
|
|
||||||
if errors.Is(err, ErrConflict) {
|
|
||||||
t.Fatalf("TENANT_REQUIRED was reported as a duplicate conflict: %v", err)
|
|
||||||
}
|
|
||||||
var httpErr *HTTPError
|
|
||||||
if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {
|
|
||||||
t.Fatalf("UploadFile() error = %v, want HTTPError 409", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A real duplicate still reports ErrConflict so the handler can adopt the
|
|
||||||
// existing knowledge instead of dead-lettering.
|
|
||||||
func TestUploadFileKeepsDuplicateConflict(t *testing.T) {
|
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusConflict)
|
|
||||||
_, _ = w.Write([]byte(`{"success":false,"data":{"id":"knowledge-9","knowledge_base_id":"kb-1","file_hash":"abc"}}`))
|
|
||||||
}))
|
|
||||||
defer server.Close()
|
|
||||||
client, err := NewClient(ClientConfig{BaseURL: server.URL, APIKey: "tenant-key", Timeout: time.Second})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
knowledge, err := client.UploadFile(context.Background(), UploadRequest{
|
|
||||||
KnowledgeBaseID: "kb-1",
|
|
||||||
FileName: "doc.pdf",
|
|
||||||
Content: strings.NewReader("%PDF-1.4"),
|
|
||||||
})
|
|
||||||
if !errors.Is(err, ErrConflict) || knowledge.ID != "knowledge-9" {
|
|
||||||
t.Fatalf("UploadFile() = %#v, %v want duplicate conflict", knowledge, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// An upload conflict keeps its own meaning: 409 without TENANT_REQUIRED is not
|
// An upload conflict keeps its own meaning: 409 without TENANT_REQUIRED is not
|
||||||
// treated as a workspace refusal.
|
// treated as a workspace refusal.
|
||||||
func TestTenantRequiredIgnoresPlainConflict(t *testing.T) {
|
func TestTenantRequiredIgnoresPlainConflict(t *testing.T) {
|
||||||
|
|||||||
@@ -42,33 +42,28 @@ type DashboardRegion struct {
|
|||||||
UsageCoverage qaopsquality.Rate `json:"usage_coverage"`
|
UsageCoverage qaopsquality.Rate `json:"usage_coverage"`
|
||||||
}
|
}
|
||||||
type Dashboard struct {
|
type Dashboard struct {
|
||||||
Start time.Time `json:"start"`
|
Start time.Time `json:"start"`
|
||||||
End time.Time `json:"end"`
|
End time.Time `json:"end"`
|
||||||
Keyword string `json:"keyword"`
|
Keyword string `json:"keyword"`
|
||||||
Filters map[string]string `json:"filters,omitempty"`
|
Filters map[string]string `json:"filters,omitempty"`
|
||||||
Granularity string `json:"granularity,omitempty"`
|
AsOf time.Time `json:"as_of"`
|
||||||
Period *DashboardPeriod `json:"period,omitempty"`
|
LocalRevision int64 `json:"local_revision"`
|
||||||
PeriodIssues *int `json:"period_issues,omitempty"`
|
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||||
PrevPeriodIssues *int `json:"prev_period_issues,omitempty"`
|
TotalIssues int `json:"total_issues"`
|
||||||
PeriodQuality *DashboardStrictQuality `json:"period_quality,omitempty"`
|
NewThisWeek int `json:"new_this_week"`
|
||||||
AsOf time.Time `json:"as_of"`
|
WeekStart time.Time `json:"week_start"`
|
||||||
LocalRevision int64 `json:"local_revision"`
|
MonthStart time.Time `json:"month_start"`
|
||||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
Quality qaopsquality.Summary `json:"quality"`
|
||||||
TotalIssues int `json:"total_issues"`
|
IssueTypes []DashboardCount `json:"issue_types"`
|
||||||
NewThisWeek int `json:"new_this_week"`
|
Products []DashboardCount `json:"products"`
|
||||||
WeekStart time.Time `json:"week_start"`
|
Daily []DashboardDaily `json:"daily"`
|
||||||
MonthStart time.Time `json:"month_start"`
|
Regions []DashboardRegion `json:"regions"`
|
||||||
Quality qaopsquality.Summary `json:"quality"`
|
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
||||||
IssueTypes []DashboardCount `json:"issue_types"`
|
ReportedWeeks []DashboardReported `json:"reported_weeks"`
|
||||||
Products []DashboardCount `json:"products"`
|
CumulativeWeeks []DashboardCumulative `json:"cumulative_weeks"`
|
||||||
Daily []DashboardDaily `json:"daily"`
|
QualityPeriod *DashboardQualityPeriod `json:"quality_period,omitempty"`
|
||||||
Regions []DashboardRegion `json:"regions"`
|
MonthlyQuality *DashboardStrictQuality `json:"monthly_quality,omitempty"`
|
||||||
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
CalendarMonths []DashboardMonth `json:"calendar_months"`
|
||||||
ReportedWeeks []DashboardReported `json:"reported_weeks"`
|
|
||||||
CumulativeWeeks []DashboardCumulative `json:"cumulative_weeks"`
|
|
||||||
QualityPeriod *DashboardQualityPeriod `json:"quality_period,omitempty"`
|
|
||||||
MonthlyQuality *DashboardStrictQuality `json:"monthly_quality,omitempty"`
|
|
||||||
CalendarMonths []DashboardMonth `json:"calendar_months"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||||
|
|||||||
@@ -1,85 +0,0 @@
|
|||||||
package qaopsmirror
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"knowledge-governance/internal/dobotaiops"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The statistics board accepts an explicit granularity so every panel is cut
|
|
||||||
// from ONE selected range. Empty granularity keeps the historical weekly board
|
|
||||||
// (start/end derived from the selected week) byte-for-byte unchanged.
|
|
||||||
const (
|
|
||||||
dashboardGranularityDay = "day"
|
|
||||||
dashboardGranularityWeek = "week"
|
|
||||||
dashboardGranularityMonth = "month"
|
|
||||||
dashboardGranularityCustom = "custom"
|
|
||||||
)
|
|
||||||
|
|
||||||
func validDashboardGranularity(kind string) bool {
|
|
||||||
switch kind {
|
|
||||||
case "", dashboardGranularityDay, dashboardGranularityWeek, dashboardGranularityMonth, dashboardGranularityCustom:
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type DashboardPeriod struct {
|
|
||||||
Kind string `json:"kind"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
Start time.Time `json:"start"`
|
|
||||||
End time.Time `json:"end"`
|
|
||||||
PrevStart time.Time `json:"prev_start"`
|
|
||||||
PrevEnd time.Time `json:"prev_end"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// dashboardPeriod describes the selected range in Beijing time and derives the
|
|
||||||
// immediately preceding range of the same length so the board can show a
|
|
||||||
// like-for-like comparison instead of a second, hidden time window.
|
|
||||||
func dashboardPeriod(kind string, start, end time.Time) DashboardPeriod {
|
|
||||||
local := start.In(dashboardLocation)
|
|
||||||
finishLocal := end.In(dashboardLocation)
|
|
||||||
out := DashboardPeriod{Kind: kind, Start: start, End: end, PrevEnd: start}
|
|
||||||
switch kind {
|
|
||||||
case dashboardGranularityDay:
|
|
||||||
out.Label = local.Format("2006-01-02")
|
|
||||||
out.PrevStart = start.AddDate(0, 0, -1)
|
|
||||||
case dashboardGranularityWeek:
|
|
||||||
first := local.AddDate(0, 0, -((int(local.Weekday()) + 6) % 7))
|
|
||||||
year, week := first.ISOWeek()
|
|
||||||
out.Label = fmt.Sprintf("%d 第%d周", year, week)
|
|
||||||
out.PrevStart = start.AddDate(0, 0, -7)
|
|
||||||
case dashboardGranularityMonth:
|
|
||||||
out.Label = local.Format("2006-01")
|
|
||||||
out.PrevStart = start.AddDate(0, -1, 0)
|
|
||||||
default:
|
|
||||||
out.Label = fmt.Sprintf("%s 至 %s", local.Format("2006-01-02"), finishLocal.Format("2006-01-02"))
|
|
||||||
out.PrevStart = start.Add(-end.Sub(start))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// dashboardPeriodIssues counts records whose original asked_at falls inside the
|
|
||||||
// selected range. The historical "total_issues" keeps counting everything up to
|
|
||||||
// the range end, so the two numbers stay distinguishable on the board.
|
|
||||||
func (s *Store) dashboardPeriodIssues(ctx context.Context, tx pgx.Tx, q dobotaiops.RecordQuery, master bool, start, end time.Time) (int, error) {
|
|
||||||
table, question := "qa_ops_mirror_records", "lower(question)"
|
|
||||||
if master {
|
|
||||||
table = "qa_ops_master_read_model"
|
|
||||||
question = "lower(question||E'\\n'||chinese_question||E'\\n'||COALESCE(ai_fields->>'question_chinese',''))"
|
|
||||||
}
|
|
||||||
sql := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 AND ($4='' OR position(%s IN %s)>0)`, table, question, question)
|
|
||||||
args := []any{s.tenant, start, end, q.Keyword}
|
|
||||||
if q.MatchIDs != nil {
|
|
||||||
sql += " AND id=ANY($5::text[])"
|
|
||||||
args = append(args, q.MatchIDs)
|
|
||||||
}
|
|
||||||
var n int
|
|
||||||
if err := tx.QueryRow(ctx, sql, args...).Scan(&n); err != nil {
|
|
||||||
return 0, dobotaiops.ErrUnavailable
|
|
||||||
}
|
|
||||||
return n, nil
|
|
||||||
}
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
package qaopsmirror
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"knowledge-governance/internal/dobotaiops"
|
|
||||||
pg "knowledge-governance/internal/platform/postgres"
|
|
||||||
)
|
|
||||||
|
|
||||||
// A monthly board must cut every panel from the selected range: the in-range
|
|
||||||
// count, the daily trend, the strict quality sample and the previous range.
|
|
||||||
func TestMonthlyGranularityCutsEveryPanelFromTheSelectedRange(t *testing.T) {
|
|
||||||
pool := mirrorFixture(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
s := NewStore(pool, "fixture-monthly-period")
|
|
||||||
queue := pg.NewStore(pool)
|
|
||||||
rows := make([]dobotaiops.MirrorRecord, 0, 3)
|
|
||||||
for _, spec := range []struct{ id, askedAt string }{
|
|
||||||
{"oct-record", "2026-10-15T08:00:00+08:00"},
|
|
||||||
{"nov-early", "2026-11-02T08:00:00+08:00"},
|
|
||||||
{"nov-late", "2026-11-30T08:00:00+08:00"},
|
|
||||||
} {
|
|
||||||
entry := fixtureEntry(spec.id, "已有资料")
|
|
||||||
var wire map[string]any
|
|
||||||
if err := json.Unmarshal(entry.Payload, &wire); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
wire["asked_at"] = spec.askedAt
|
|
||||||
entry.Payload, _ = json.Marshal(wire)
|
|
||||||
rows = append(rows, entry)
|
|
||||||
}
|
|
||||||
job := claimMirrorJob(t, s, queue, "monthly-period-seed")
|
|
||||||
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
|
|
||||||
return &fixtureSource{rows: rows}, nil
|
|
||||||
}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
start, _ := time.Parse(time.RFC3339, "2026-11-01T00:00:00+08:00")
|
|
||||||
end, _ := time.Parse(time.RFC3339, "2026-12-01T00:00:00+08:00")
|
|
||||||
// The handler builds the window through dobotaiops.NewWindow, which
|
|
||||||
// normalises both ends to UTC. Feed the store the same shape here, otherwise
|
|
||||||
// this test keeps a +08 location the production path never has.
|
|
||||||
start, end = start.UTC(), end.UTC()
|
|
||||||
got, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{
|
|
||||||
Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end},
|
|
||||||
Granularity: dashboardGranularityMonth,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got.Period == nil || got.Period.Kind != dashboardGranularityMonth || got.Period.Label != "2026-11" {
|
|
||||||
t.Fatalf("period = %+v", got.Period)
|
|
||||||
}
|
|
||||||
if !got.Period.PrevStart.Equal(start.AddDate(0, -1, 0)) || !got.Period.PrevEnd.Equal(start) {
|
|
||||||
t.Fatalf("previous range = %s..%s", got.Period.PrevStart, got.Period.PrevEnd)
|
|
||||||
}
|
|
||||||
if got.PeriodIssues == nil || *got.PeriodIssues != 2 {
|
|
||||||
t.Fatalf("period issues = %v, want 2", got.PeriodIssues)
|
|
||||||
}
|
|
||||||
if got.PrevPeriodIssues == nil || *got.PrevPeriodIssues != 1 {
|
|
||||||
t.Fatalf("previous period issues = %v, want 1", got.PrevPeriodIssues)
|
|
||||||
}
|
|
||||||
if got.TotalIssues != 3 {
|
|
||||||
t.Fatalf("cumulative total = %d, want 3 (everything before the range end)", got.TotalIssues)
|
|
||||||
}
|
|
||||||
if len(got.Daily) != 30 || got.Daily[0].Date != "2026-11-01" || got.Daily[29].Date != "2026-11-30" {
|
|
||||||
t.Fatalf("daily trend does not cover the whole month: %d points, first=%v", len(got.Daily), got.Daily[0])
|
|
||||||
}
|
|
||||||
sum := 0
|
|
||||||
for _, point := range got.Daily {
|
|
||||||
sum += point.Count
|
|
||||||
}
|
|
||||||
if sum != *got.PeriodIssues || got.NewThisWeek != *got.PeriodIssues {
|
|
||||||
t.Fatalf("daily sum=%d, new_this_week=%d, period=%d", sum, got.NewThisWeek, *got.PeriodIssues)
|
|
||||||
}
|
|
||||||
if got.PeriodQuality == nil || got.PeriodQuality.Records != got.Quality.Total {
|
|
||||||
t.Fatalf("period quality = %+v, quality total = %d", got.PeriodQuality, got.Quality.Total)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Omitting granularity must keep the weekly board exactly as before.
|
|
||||||
func TestWeeklyBoardKeepsLegacyPanelsWithoutGranularity(t *testing.T) {
|
|
||||||
pool := mirrorFixture(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
s := NewStore(pool, "fixture-weekly-legacy")
|
|
||||||
queue := pg.NewStore(pool)
|
|
||||||
entry := fixtureEntry("legacy-week", "已有资料")
|
|
||||||
var wire map[string]any
|
|
||||||
_ = json.Unmarshal(entry.Payload, &wire)
|
|
||||||
wire["asked_at"] = "2026-11-30T08:00:00+08:00"
|
|
||||||
entry.Payload, _ = json.Marshal(wire)
|
|
||||||
job := claimMirrorJob(t, s, queue, "legacy-week-seed")
|
|
||||||
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
|
|
||||||
return &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}, nil
|
|
||||||
}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
start, _ := time.Parse(time.RFC3339, "2026-11-30T00:00:00+08:00")
|
|
||||||
end, _ := time.Parse(time.RFC3339, "2026-12-03T00:00:00+08:00")
|
|
||||||
got, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got.Period != nil || got.PeriodIssues != nil || got.PeriodQuality != nil || got.Granularity != "" {
|
|
||||||
t.Fatalf("granularity leaked into the legacy board: %+v", got.Period)
|
|
||||||
}
|
|
||||||
if got.NewThisWeek != 1 || len(got.Daily) != 3 {
|
|
||||||
t.Fatalf("legacy weekly panels changed: new=%d daily=%d", got.NewThisWeek, len(got.Daily))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package qaopsmirror
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func mustShanghai(t *testing.T, value string) time.Time {
|
|
||||||
t.Helper()
|
|
||||||
parsed, err := time.Parse(time.RFC3339, value)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("parse %s: %v", value, err)
|
|
||||||
}
|
|
||||||
return parsed
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDashboardPeriodResolution(t *testing.T) {
|
|
||||||
monthStart := mustShanghai(t, "2026-11-01T00:00:00+08:00")
|
|
||||||
monthEnd := mustShanghai(t, "2026-12-01T00:00:00+08:00")
|
|
||||||
month := dashboardPeriod(dashboardGranularityMonth, monthStart, monthEnd)
|
|
||||||
if month.Label != "2026-11" {
|
|
||||||
t.Fatalf("month label = %q, want 2026-11", month.Label)
|
|
||||||
}
|
|
||||||
if !month.PrevStart.Equal(mustShanghai(t, "2026-10-01T00:00:00+08:00")) || !month.PrevEnd.Equal(monthStart) {
|
|
||||||
t.Fatalf("month prev range = %s..%s", month.PrevStart, month.PrevEnd)
|
|
||||||
}
|
|
||||||
|
|
||||||
weekStart := mustShanghai(t, "2026-11-30T00:00:00+08:00")
|
|
||||||
week := dashboardPeriod(dashboardGranularityWeek, weekStart, mustShanghai(t, "2026-12-07T00:00:00+08:00"))
|
|
||||||
if week.Label != "2026 第49周" {
|
|
||||||
t.Fatalf("week label = %q", week.Label)
|
|
||||||
}
|
|
||||||
if !week.PrevStart.Equal(mustShanghai(t, "2026-11-23T00:00:00+08:00")) {
|
|
||||||
t.Fatalf("week prev start = %s", week.PrevStart)
|
|
||||||
}
|
|
||||||
|
|
||||||
day := dashboardPeriod(dashboardGranularityDay, weekStart, weekStart.AddDate(0, 0, 1))
|
|
||||||
if day.Label != "2026-11-30" || !day.PrevStart.Equal(weekStart.AddDate(0, 0, -1)) {
|
|
||||||
t.Fatalf("day period = %+v", day)
|
|
||||||
}
|
|
||||||
|
|
||||||
customEnd := mustShanghai(t, "2026-11-05T00:00:00+08:00")
|
|
||||||
custom := dashboardPeriod(dashboardGranularityCustom, monthStart, customEnd)
|
|
||||||
if !custom.PrevStart.Equal(mustShanghai(t, "2026-10-28T00:00:00+08:00")) || !custom.PrevEnd.Equal(monthStart) {
|
|
||||||
t.Fatalf("custom prev range = %s..%s", custom.PrevStart, custom.PrevEnd)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDashboardGranularityValidation(t *testing.T) {
|
|
||||||
for _, kind := range []string{"", "day", "week", "month", "custom"} {
|
|
||||||
if !validDashboardGranularity(kind) {
|
|
||||||
t.Fatalf("expected %q to be valid", kind)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, kind := range []string{"year", "Week", "quarter"} {
|
|
||||||
if validDashboardGranularity(kind) {
|
|
||||||
t.Fatalf("expected %q to be rejected", kind)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -61,9 +61,6 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
|||||||
if !s.valid() {
|
if !s.valid() {
|
||||||
return out, dobotaiops.ErrUnavailable
|
return out, dobotaiops.ErrUnavailable
|
||||||
}
|
}
|
||||||
if !validDashboardGranularity(q.Granularity) {
|
|
||||||
return out, dobotaiops.ErrInvalidQuery
|
|
||||||
}
|
|
||||||
if q.Window.TenantKey != s.tenant || !utf8.ValidString(q.Keyword) || utf8.RuneCountInString(q.Keyword) > 200 || strings.ContainsRune(q.Keyword, 0) {
|
if q.Window.TenantKey != s.tenant || !utf8.ValidString(q.Keyword) || utf8.RuneCountInString(q.Keyword) > 200 || strings.ContainsRune(q.Keyword, 0) {
|
||||||
return out, dobotaiops.ErrInvalidQuery
|
return out, dobotaiops.ErrInvalidQuery
|
||||||
}
|
}
|
||||||
@@ -224,15 +221,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
|||||||
}
|
}
|
||||||
out.Quality = qaopsquality.Summarize(views)
|
out.Quality = qaopsquality.Summarize(views)
|
||||||
products, types, daily := map[string]int{}, map[string]int{}, map[string]int{}
|
products, types, daily := map[string]int{}, map[string]int{}, map[string]int{}
|
||||||
dailyFrom := out.WeekStart
|
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||||
if q.Granularity != "" {
|
|
||||||
// Window.Start is UTC (NewWindow normalises it); the trend keys and the
|
|
||||||
// per-record buckets are Beijing dates, so cut the range in Beijing time
|
|
||||||
// or the first/last day drifts by one and the last day's records fall
|
|
||||||
// outside the pre-filled keys (the board then looks inconsistent).
|
|
||||||
dailyFrom = q.Window.Start.In(dashboardLocation)
|
|
||||||
}
|
|
||||||
for day := dailyFrom; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
|
||||||
daily[day.Format("2006-01-02")] = 0
|
daily[day.Format("2006-01-02")] = 0
|
||||||
}
|
}
|
||||||
regionIndex := map[string]int{}
|
regionIndex := map[string]int{}
|
||||||
@@ -248,25 +237,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
|||||||
users[region.Name] = map[string]bool{}
|
users[region.Name] = map[string]bool{}
|
||||||
out.Regions = append(out.Regions, r)
|
out.Regions = append(out.Regions, r)
|
||||||
}
|
}
|
||||||
inPeriod := 0
|
|
||||||
regionFrom := out.MonthStart
|
|
||||||
if q.Granularity != "" {
|
|
||||||
// 区域统计跟随所选区间:按天/周/月/自定义看板里,"这个区间用了多少"才是
|
|
||||||
// 用户要的数字。老周看板(granularity 为空)保持原来的自然月累计不变,
|
|
||||||
// 周报生成链路逐字段不变。分母仍是月度通讯录人数,由前端注明快照月份。
|
|
||||||
regionFrom = q.Window.Start
|
|
||||||
}
|
|
||||||
for _, r := range records {
|
for _, r := range records {
|
||||||
if q.Granularity == "" {
|
if !r.at.Before(out.WeekStart) {
|
||||||
if !r.at.Before(out.WeekStart) {
|
out.NewThisWeek++
|
||||||
out.NewThisWeek++
|
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
||||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
|
||||||
}
|
|
||||||
} else if !r.at.Before(q.Window.Start) {
|
|
||||||
inPeriod++
|
|
||||||
if _, ok := daily[r.at.In(dashboardLocation).Format("2006-01-02")]; ok {
|
|
||||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if !r.at.Before(q.Window.Start) {
|
if !r.at.Before(q.Window.Start) {
|
||||||
v, ok := views[r.id]
|
v, ok := views[r.id]
|
||||||
@@ -276,7 +250,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
|||||||
products[dashboardCategory(v.Effective.ProductCategory)]++
|
products[dashboardCategory(v.Effective.ProductCategory)]++
|
||||||
types[dashboardCategory(v.Effective.ProblemType)]++
|
types[dashboardCategory(v.Effective.ProblemType)]++
|
||||||
}
|
}
|
||||||
if !r.at.Before(regionFrom) {
|
if !r.at.Before(out.MonthStart) {
|
||||||
person := attribution.Resolve(r.identity.StaffID, r.identity.UnionID, r.fields["asker"], r.fields["trigger_person"])
|
person := attribution.Resolve(r.identity.StaffID, r.identity.UnionID, r.fields["asker"], r.fields["trigger_person"])
|
||||||
if index, ok := regionIndex[person.Region]; ok && person.PersonID != "" {
|
if index, ok := regionIndex[person.Region]; ok && person.PersonID != "" {
|
||||||
out.Regions[index].Questions++
|
out.Regions[index].Questions++
|
||||||
@@ -286,24 +260,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
|||||||
}
|
}
|
||||||
out.Products = dashboardCategories(products)
|
out.Products = dashboardCategories(products)
|
||||||
out.IssueTypes = dashboardCategories(types)
|
out.IssueTypes = dashboardCategories(types)
|
||||||
for day := dailyFrom; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||||
date := day.Format("2006-01-02")
|
date := day.Format("2006-01-02")
|
||||||
out.Daily = append(out.Daily, DashboardDaily{Date: date, Count: daily[date]})
|
out.Daily = append(out.Daily, DashboardDaily{Date: date, Count: daily[date]})
|
||||||
}
|
}
|
||||||
if q.Granularity != "" {
|
|
||||||
period := dashboardPeriod(q.Granularity, q.Window.Start, q.Window.End)
|
|
||||||
out.Granularity = q.Granularity
|
|
||||||
out.Period = &period
|
|
||||||
out.PeriodIssues = &inPeriod
|
|
||||||
// Keep the historical invariant "daily sums up to new_this_week" so old
|
|
||||||
// clients that only know this field still agree with the trend panel.
|
|
||||||
out.NewThisWeek = inPeriod
|
|
||||||
prev, err := s.dashboardPeriodIssues(ctx, tx, q, master, period.PrevStart, period.PrevEnd)
|
|
||||||
if err != nil {
|
|
||||||
return out, err
|
|
||||||
}
|
|
||||||
out.PrevPeriodIssues = &prev
|
|
||||||
}
|
|
||||||
for i := range out.Regions {
|
for i := range out.Regions {
|
||||||
r := &out.Regions[i]
|
r := &out.Regions[i]
|
||||||
if r.Users != nil {
|
if r.Users != nil {
|
||||||
@@ -347,10 +307,6 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
|||||||
out.QualityPeriod = &DashboardQualityPeriod{Month: month.Format("2006-01"), Start: month, CutoffAt: cutoff, CalculatedAt: calculated, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy}
|
out.QualityPeriod = &DashboardQualityPeriod{Month: month.Format("2006-01"), Start: month, CutoffAt: cutoff, CalculatedAt: calculated, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy}
|
||||||
rates := dashboardStrictQuality(timeline, month, cutoff)
|
rates := dashboardStrictQuality(timeline, month, cutoff)
|
||||||
out.MonthlyQuality = &rates
|
out.MonthlyQuality = &rates
|
||||||
if q.Granularity != "" {
|
|
||||||
periodRates := dashboardStrictQuality(timeline, q.Window.Start, q.Window.End)
|
|
||||||
out.PeriodQuality = &periodRates
|
|
||||||
}
|
|
||||||
out.CalendarMonths = dashboardCalendarMonths(timeline, cutoff, calculated)
|
out.CalendarMonths = dashboardCalendarMonths(timeline, cutoff, calculated)
|
||||||
} else {
|
} else {
|
||||||
out.CumulativeWeeks = []DashboardCumulative{}
|
out.CumulativeWeeks = []DashboardCumulative{}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -124,7 +123,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
|||||||
uploadMD5, _ := handler.hashSpool(candidate)
|
uploadMD5, _ := handler.hashSpool(candidate)
|
||||||
now := handler.now()
|
now := handler.now()
|
||||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||||
return fmt.Errorf("%w: %v", ErrUploadStateConflict, err)
|
return ErrUploadStateConflict
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -195,7 +194,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
|
|||||||
}
|
}
|
||||||
now := handler.now()
|
now := handler.now()
|
||||||
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
if _, err := handler.store.RecordUploadAndSchedulePoll(ctx, candidate.ID, knowledge.ID, uploadMD5, now, now.Add(handler.firstPollDelay)); err != nil {
|
||||||
return fmt.Errorf("%w: %v", ErrUploadStateConflict, err)
|
return ErrUploadStateConflict
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -404,12 +404,7 @@ def dingtalk_live_raw_key(manifest):
|
|||||||
for index in range(len(parts)):
|
for index in range(len(parts)):
|
||||||
drive = space_id.isdigit()
|
drive = space_id.isdigit()
|
||||||
args = ['drive', '+list', '--space-id', space_id] if drive else ['wiki', '+node-list', '--workspace', space_id]
|
args = ['drive', '+list', '--space-id', space_id] if drive else ['wiki', '+node-list', '--workspace', space_id]
|
||||||
# 翻页上限开关按命令族不同:wiki 叫 --page-limit,drive +list 叫 --max-pages。
|
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
|
||||||
# 混用会得到 `unknown flag: --page-limit`,被分类成 unknown 而成为终态失败。
|
|
||||||
if drive:
|
|
||||||
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--max-pages', '200']
|
|
||||||
else:
|
|
||||||
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
|
|
||||||
if folder:
|
if folder:
|
||||||
args += ['--folder', folder]
|
args += ['--folder', folder]
|
||||||
payload, verdict = dws_run(args, timeout=180)
|
payload, verdict = dws_run(args, timeout=180)
|
||||||
@@ -417,13 +412,7 @@ def dingtalk_live_raw_key(manifest):
|
|||||||
raise _dws_error(verdict)
|
raise _dws_error(verdict)
|
||||||
data = payload.get('data', {}) if isinstance(payload, dict) else {}
|
data = payload.get('data', {}) if isinstance(payload, dict) else {}
|
||||||
entries = data.get('files' if drive else 'nodes')
|
entries = data.get('files' if drive else 'nodes')
|
||||||
# 两族命令的“翻完了”证据不同:wiki 给 data.autoPageComplete,drive +list 只在
|
if not isinstance(entries, list) or data.get('hasMore') is not False or data.get('autoPageComplete') is not True:
|
||||||
# meta.pagination.endpoint_exhausted 里给。缺这一条会被当成目录读不全而永远可重试。
|
|
||||||
meta = payload.get('meta') if isinstance(payload, dict) else None
|
|
||||||
pagination = meta.get('pagination') if isinstance(meta, dict) else None
|
|
||||||
exhausted = (data.get('autoPageComplete') is True
|
|
||||||
or (isinstance(pagination, dict) and pagination.get('endpoint_exhausted') is True))
|
|
||||||
if not isinstance(entries, list) or data.get('hasMore') is not False or not exhausted:
|
|
||||||
raise FetchError('DingTalk directory response is incomplete', retryable=True, code='source_lookup_incomplete')
|
raise FetchError('DingTalk directory response is incomplete', retryable=True, code='source_lookup_incomplete')
|
||||||
matches = []
|
matches = []
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ describe('question dashboard projections', () => {
|
|||||||
const html = renderToStaticMarkup(
|
const html = renderToStaticMarkup(
|
||||||
<QADashboardView data={parseQADashboard(dashboardFixture)} loading={false} error="" onRetry={vi.fn()} />
|
<QADashboardView data={parseQADashboard(dashboardFixture)} loading={false} error="" onRetry={vi.fn()} />
|
||||||
)
|
)
|
||||||
for (const title of ['累计总量', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
|
for (const title of ['问题总数', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
|
||||||
expect(html).toContain(title)
|
expect(html).toContain(title)
|
||||||
expect(html).not.toContain('<img src=x')
|
expect(html).not.toContain('<img src=x')
|
||||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||||
|
|||||||
+4
-14
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import type { QAQuery } from './qaOps'
|
import type { QAQuery } from './qaOps'
|
||||||
import { fetchQADashboard, liveDashboardQuery } from './qaDashboardData'
|
import { fetchQADashboard, liveDashboardQuery } from './qaDashboardData'
|
||||||
import type { QADashboardData, DashboardGranularity } from './qaDashboardData'
|
import type { QADashboardData } from './qaDashboardData'
|
||||||
import { QADashboardDrawing } from './QADashboardDrawing'
|
import { QADashboardDrawing } from './QADashboardDrawing'
|
||||||
import { createDashboardPNG } from './qaDashboardExport'
|
import { createDashboardPNG } from './qaDashboardExport'
|
||||||
import { currentQAWeek } from './qaWeeks'
|
import { currentQAWeek } from './qaWeeks'
|
||||||
@@ -38,11 +38,7 @@ export function QADashboardView({ data, loading, error, onRetry }: QADashboardPr
|
|||||||
link = document.createElement('a'),
|
link = document.createElement('a'),
|
||||||
week = currentQAWeek(new Date(data.week_start))
|
week = currentQAWeek(new Date(data.week_start))
|
||||||
link.href = url
|
link.href = url
|
||||||
link.download = `DobotAI_QA_Dashboard_${
|
link.download = `DobotAI_QA_Dashboard_${week.year}_W${String(week.week).padStart(2, '0')}.png`
|
||||||
data.period
|
|
||||||
? data.period.label.replace(/[^\w.-]+/g, '_')
|
|
||||||
: `${week.year}_W${String(week.week).padStart(2, '0')}`
|
|
||||||
}.png`
|
|
||||||
document.body.append(link)
|
document.body.append(link)
|
||||||
link.click()
|
link.click()
|
||||||
link.remove()
|
link.remove()
|
||||||
@@ -85,13 +81,11 @@ export function QADashboard({
|
|||||||
error,
|
error,
|
||||||
revision,
|
revision,
|
||||||
onRetry,
|
onRetry,
|
||||||
granularity,
|
|
||||||
}: {
|
}: {
|
||||||
query: QAQuery | null
|
query: QAQuery | null
|
||||||
error: string | null
|
error: string | null
|
||||||
revision: number
|
revision: number
|
||||||
onRetry: () => void
|
onRetry: () => void
|
||||||
granularity?: DashboardGranularity
|
|
||||||
}) {
|
}) {
|
||||||
const [data, setData] = useState<QADashboardData | null>(null),
|
const [data, setData] = useState<QADashboardData | null>(null),
|
||||||
[failure, setFailure] = useState(''),
|
[failure, setFailure] = useState(''),
|
||||||
@@ -108,11 +102,7 @@ export function QADashboard({
|
|||||||
setLoading(true)
|
setLoading(true)
|
||||||
const refresh = async () => {
|
const refresh = async () => {
|
||||||
try {
|
try {
|
||||||
const next = await fetchQADashboard(
|
const next = await fetchQADashboard(liveDashboardQuery(query, new Date()), abort.signal)
|
||||||
liveDashboardQuery(query, new Date(), granularity),
|
|
||||||
abort.signal,
|
|
||||||
granularity
|
|
||||||
)
|
|
||||||
if (!abort.signal.aborted) {
|
if (!abort.signal.aborted) {
|
||||||
setData(next)
|
setData(next)
|
||||||
setFailure('')
|
setFailure('')
|
||||||
@@ -131,7 +121,7 @@ export function QADashboard({
|
|||||||
abort.abort()
|
abort.abort()
|
||||||
if (timer !== undefined) clearTimeout(timer)
|
if (timer !== undefined) clearTimeout(timer)
|
||||||
}
|
}
|
||||||
}, [query, revision, granularity])
|
}, [query, revision])
|
||||||
return (
|
return (
|
||||||
<div className="qa-dashboard-scroll">
|
<div className="qa-dashboard-scroll">
|
||||||
<QADashboardView data={data} loading={loading} error={error || failure} onRetry={onRetry} />
|
<QADashboardView data={data} loading={loading} error={error || failure} onRetry={onRetry} />
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ it('draws all eleven panels as a self-contained exportable SVG without HTML exec
|
|||||||
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={1280} />)
|
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={1280} />)
|
||||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||||
for (const title of [
|
for (const title of [
|
||||||
'累计总量',
|
'问题总数',
|
||||||
'本周新增',
|
'本周新增',
|
||||||
'覆盖率',
|
'覆盖率',
|
||||||
'正确率',
|
'正确率',
|
||||||
|
|||||||
@@ -467,13 +467,11 @@ function RegionTable({
|
|||||||
regions,
|
regions,
|
||||||
frequency,
|
frequency,
|
||||||
month,
|
month,
|
||||||
caption,
|
|
||||||
}: {
|
}: {
|
||||||
box: Box
|
box: Box
|
||||||
regions: DashboardRegion[]
|
regions: DashboardRegion[]
|
||||||
frequency: boolean
|
frequency: boolean
|
||||||
month: string
|
month: string
|
||||||
caption: string
|
|
||||||
}) {
|
}) {
|
||||||
const rows = [...regions].sort((a, b) => {
|
const rows = [...regions].sort((a, b) => {
|
||||||
const av = frequency ? a.frequency : a.usage_coverage.percent,
|
const av = frequency ? a.frequency : a.usage_coverage.percent,
|
||||||
@@ -506,7 +504,7 @@ function RegionTable({
|
|||||||
y += h
|
y += h
|
||||||
return (
|
return (
|
||||||
<g key={r.id}>
|
<g key={r.id}>
|
||||||
<title>{`${r.name};${caption};提问 ${r.questions} 次;去重使用 ${r.users ?? '未知'} 人 / 当前通讯录归属 ${r.roster_people ?? '未知'} 人`}</title>
|
<title>{`${r.name};${month}月内提问 ${r.questions} 次;去重使用 ${r.users ?? '未知'} 人 / 通讯录归属 ${r.roster_people ?? '未知'} 人`}</title>
|
||||||
{i % 2 === 0 ? <rect x={11} y={at - 15} width={box.w - 22} height={h} fill="#f7faff" /> : null}
|
{i % 2 === 0 ? <rect x={11} y={at - 15} width={box.w - 22} height={h} fill="#f7faff" /> : null}
|
||||||
{value !== null && i < 3 ? (
|
{value !== null && i < 3 ? (
|
||||||
<circle cx={30} cy={at - 4} r={9} fill={['#e9bd54', '#a8b6c9', '#dc9c73'][i]} />
|
<circle cx={30} cy={at - 4} r={9} fill={['#e9bd54', '#a8b6c9', '#dc9c73'][i]} />
|
||||||
@@ -522,7 +520,7 @@ function RegionTable({
|
|||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
<text x={box.w - 17} y={box.h - 17} textAnchor="end" fontSize={9.5} fill={muted}>
|
<text x={box.w - 17} y={box.h - 17} textAnchor="end" fontSize={9.5} fill={muted}>
|
||||||
{caption}
|
{month}月累计
|
||||||
</text>
|
</text>
|
||||||
</Panel>
|
</Panel>
|
||||||
)
|
)
|
||||||
@@ -546,9 +544,7 @@ export function QADashboardDrawing({
|
|||||||
unit = (inner - gap * 3) / 4,
|
unit = (inner - gap * 3) / 4,
|
||||||
week = currentQAWeek(new Date(data.week_start)),
|
week = currentQAWeek(new Date(data.week_start)),
|
||||||
filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11),
|
filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11),
|
||||||
heading = data.period
|
heading = `${data.week_start.slice(0, 10)} 起的自然周${data.quality_period ? ` · 质量 ${data.quality_period.month} 月内累计` : ''} · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`,
|
||||||
? `${data.period.label} · 全部指标按所选范围统计 · 区域统计按所选区间(分母为当前通讯录)`
|
|
||||||
: `${data.week_start.slice(0, 10)} 起的自然周${data.quality_period ? ` · 质量 ${data.quality_period.month} 月内累计` : ''} · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`,
|
|
||||||
headingLines = (mobile ? [heading.split(' · ')[0], heading.split(' · ').slice(1).join(' · ')] : [heading]).flatMap(
|
headingLines = (mobile ? [heading.split(' · ')[0], heading.split(' · ').slice(1).join(' · ')] : [heading]).flatMap(
|
||||||
(row) => wrap(row, inner - 16, 10.5)
|
(row) => wrap(row, inner - 16, 10.5)
|
||||||
),
|
),
|
||||||
@@ -608,8 +604,6 @@ export function QADashboardDrawing({
|
|||||||
height = mobile ? cursor + 540 + gap + pad : cursor + 270 + pad
|
height = mobile ? cursor + 540 + gap + pad : cursor + 270 + pad
|
||||||
const frozen = (correctness: boolean): PlotPoint[] => historicalTrend(data, correctness)
|
const frozen = (correctness: boolean): PlotPoint[] => historicalTrend(data, correctness)
|
||||||
const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)
|
const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)
|
||||||
// 有 granularity 时区域面板跟所选区间走,分母仍是月度通讯录;老周看板保持"月累计"。
|
|
||||||
const regionCaption = data.period ? '所选区间提问 / 去重使用 ÷ 当前通讯录' : `${month}月累计`
|
|
||||||
const tipWidth = Math.min(334, inner),
|
const tipWidth = Math.min(334, inner),
|
||||||
tipLines = wrap(tip ? definitions[tip.id] : '', tipWidth - 26, 11.5),
|
tipLines = wrap(tip ? definitions[tip.id] : '', tipWidth - 26, 11.5),
|
||||||
tipHeight = tipLines.length * 15.525 + 26,
|
tipHeight = tipLines.length * 15.525 + 26,
|
||||||
@@ -639,13 +633,13 @@ export function QADashboardDrawing({
|
|||||||
background: '#fff',
|
background: '#fff',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<title>{`问题统计看板 · ${data.period ? data.period.label : `${week.year}年第${week.week}周`}`}</title>
|
<title>{`问题统计看板 · ${week.year}年第${week.week}周`}</title>
|
||||||
<rect width={w} height={height} fill="#fff" />
|
<rect width={w} height={height} fill="#fff" />
|
||||||
<text x={pad + 6} y={27} fontSize={mobile ? 17 : 21} fontWeight={700} fill={ink}>
|
<text x={pad + 6} y={27} fontSize={mobile ? 17 : 21} fontWeight={700} fill={ink}>
|
||||||
问题统计看板
|
问题统计看板
|
||||||
</text>
|
</text>
|
||||||
<text x={w - pad - 6} y={27} textAnchor="end" fontSize={12} fill={muted}>
|
<text x={w - pad - 6} y={27} textAnchor="end" fontSize={12} fill={muted}>
|
||||||
{data.period ? data.period.label : `${week.year} · W${String(week.week).padStart(2, '0')}`}
|
{week.year} · W{String(week.week).padStart(2, '0')}
|
||||||
</text>
|
</text>
|
||||||
{headingLines.map((row, index) => (
|
{headingLines.map((row, index) => (
|
||||||
<Text key={index} x={pad + 6} y={46 + index * 14} width={inner - 16} size={10.5} fill={muted} value={row} />
|
<Text key={index} x={pad + 6} y={46 + index * 14} width={inner - 16} size={10.5} fill={muted} value={row} />
|
||||||
@@ -655,45 +649,37 @@ export function QADashboardDrawing({
|
|||||||
) : null}
|
) : null}
|
||||||
<Metric
|
<Metric
|
||||||
box={metrics[0]}
|
box={metrics[0]}
|
||||||
title="累计总量"
|
title="问题总数"
|
||||||
en="Total Issues"
|
en="Total Issues"
|
||||||
id="total"
|
id="total"
|
||||||
value={data.total_issues}
|
value={data.total_issues}
|
||||||
tint="#fff4e2"
|
tint="#fff4e2"
|
||||||
color="#c69b00"
|
color="#c69b00"
|
||||||
subtitle={data.period ? `截至 ${data.end.slice(0, 10)} 累计` : '所选周截止前累计'}
|
subtitle="所选周截止前累计"
|
||||||
/>
|
/>
|
||||||
<Metric
|
<Metric
|
||||||
box={metrics[1]}
|
box={metrics[1]}
|
||||||
title={data.period ? '本期新增' : '本周新增'}
|
title="本周新增"
|
||||||
en="New This Period"
|
en="New This week"
|
||||||
id="new-week"
|
id="new-week"
|
||||||
value={data.period_issues ?? data.new_this_week}
|
value={data.new_this_week}
|
||||||
tint="#ececff"
|
tint="#ececff"
|
||||||
color="#4056d6"
|
color="#4056d6"
|
||||||
subtitle={
|
subtitle="所选自然周"
|
||||||
data.period
|
|
||||||
? `${
|
|
||||||
data.prev_period_issues === undefined
|
|
||||||
? data.period.label
|
|
||||||
: `${data.period.label} · 上期 ${data.prev_period_issues} 条`
|
|
||||||
}`
|
|
||||||
: '所选自然周'
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
<Gauge
|
<Gauge
|
||||||
box={metrics[2]}
|
box={metrics[2]}
|
||||||
title="覆盖率"
|
title="覆盖率"
|
||||||
en={`Coverage Rate${data.period ? ` · ${data.period.label}` : data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
en={`Coverage Rate${data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
||||||
id="coverage"
|
id="coverage"
|
||||||
rate={data.period_quality?.coverage ?? data.monthly_quality?.coverage ?? data.quality.rates.coverage}
|
rate={data.monthly_quality?.coverage ?? data.quality.rates.coverage}
|
||||||
/>
|
/>
|
||||||
<Gauge
|
<Gauge
|
||||||
box={metrics[3]}
|
box={metrics[3]}
|
||||||
title="正确率"
|
title="正确率"
|
||||||
en={`Accuracy Rate${data.period ? ` · ${data.period.label}` : data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
en={`Accuracy Rate${data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
|
||||||
id="accuracy"
|
id="accuracy"
|
||||||
rate={data.period_quality?.correctness ?? data.monthly_quality?.correctness ?? data.quality.rates.correctness}
|
rate={data.monthly_quality?.correctness ?? data.quality.rates.correctness}
|
||||||
/>
|
/>
|
||||||
<Pie box={pie} points={data.issue_types} />
|
<Pie box={pie} points={data.issue_types} />
|
||||||
<Products box={products} points={data.products} />
|
<Products box={products} points={data.products} />
|
||||||
@@ -704,8 +690,8 @@ export function QADashboardDrawing({
|
|||||||
id="issue-trend"
|
id="issue-trend"
|
||||||
points={data.daily.map((p) => ({ label: p.date.slice(5), value: p.count, hint: `${p.date}:${p.count} 条` }))}
|
points={data.daily.map((p) => ({ label: p.date.slice(5), value: p.count, hint: `${p.date}:${p.count} 条` }))}
|
||||||
/>
|
/>
|
||||||
<RegionTable box={freq} regions={data.regions} frequency month={month} caption={regionCaption} />
|
<RegionTable box={freq} regions={data.regions} frequency month={month} />
|
||||||
<RegionTable box={usage} regions={data.regions} frequency={false} month={month} caption={regionCaption} />
|
<RegionTable box={usage} regions={data.regions} frequency={false} month={month} />
|
||||||
<Plot
|
<Plot
|
||||||
box={coverage}
|
box={coverage}
|
||||||
title="覆盖率趋势"
|
title="覆盖率趋势"
|
||||||
|
|||||||
+23
-105
@@ -7,7 +7,6 @@ import './qaOps.css'
|
|||||||
import { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering'
|
import { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering'
|
||||||
import { QARegionalStatistics } from './QADepartmentStatistics'
|
import { QARegionalStatistics } from './QADepartmentStatistics'
|
||||||
import { QADashboard } from './QADashboard'
|
import { QADashboard } from './QADashboard'
|
||||||
import type { DashboardGranularity } from './qaDashboardData'
|
|
||||||
import { QAWeekly } from './QAWeekly'
|
import { QAWeekly } from './QAWeekly'
|
||||||
import { QAInlineFields } from './QAInlineFields'
|
import { QAInlineFields } from './QAInlineFields'
|
||||||
import { QAHeaderFieldFilter, useQAFieldFilterOptions } from './QAFieldFilters'
|
import { QAHeaderFieldFilter, useQAFieldFilterOptions } from './QAFieldFilters'
|
||||||
@@ -411,37 +410,10 @@ export function QAOperationsView(props: ViewProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
type QARangeKind = 'week' | 'month' | 'custom'
|
|
||||||
const beijingInput = (now = new Date()) => new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 16)
|
|
||||||
function monthInputValue(now = new Date()) {
|
|
||||||
return beijingInput(now).slice(0, 7)
|
|
||||||
}
|
|
||||||
function monthQueryRange(month: string, now = new Date()) {
|
|
||||||
const [year, monthNumber] = month.split('-').map(Number)
|
|
||||||
if (!Number.isInteger(year) || !Number.isInteger(monthNumber) || monthNumber < 1 || monthNumber > 12)
|
|
||||||
throw new Error('月份无效')
|
|
||||||
const start = `${month}-01T00:00`
|
|
||||||
const nextYear = monthNumber === 12 ? year + 1 : year
|
|
||||||
const nextMonth = monthNumber === 12 ? 1 : monthNumber + 1
|
|
||||||
const end = `${nextYear}-${String(nextMonth).padStart(2, '0')}-01T00:00`
|
|
||||||
const current = beijingInput(now)
|
|
||||||
const bounded = end > current ? current : end
|
|
||||||
if (bounded <= start) throw new Error('该月份尚未开始,请选择已开始的时间范围')
|
|
||||||
return { start, end: bounded }
|
|
||||||
}
|
|
||||||
|
|
||||||
function initialDraft() {
|
function initialDraft() {
|
||||||
const current = currentQAWeek()
|
const current = currentQAWeek()
|
||||||
const { year, week, start, end } = qaWeekQueryRange(current.year, current.week)
|
const { year, week, start, end } = qaWeekQueryRange(current.year, current.week)
|
||||||
return {
|
return { year, week: week as number | null, start, end, keyword: '' }
|
||||||
kind: 'week' as QARangeKind,
|
|
||||||
year,
|
|
||||||
week: week as number | null,
|
|
||||||
month: monthInputValue(),
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
keyword: '',
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function QAOperations() {
|
export function QAOperations() {
|
||||||
@@ -453,7 +425,6 @@ export function QAOperations() {
|
|||||||
const auth = useOptionalAuth()
|
const auth = useOptionalAuth()
|
||||||
const canRead = auth?.identity?.role === 'admin'
|
const canRead = auth?.identity?.role === 'admin'
|
||||||
const [draft, setDraft] = useState(initialDraft)
|
const [draft, setDraft] = useState(initialDraft)
|
||||||
const [granularity, setGranularity] = useState<DashboardGranularity>('week')
|
|
||||||
const [filters, setFilters] = useState<NonNullable<QAQuery['filters']>>({})
|
const [filters, setFilters] = useState<NonNullable<QAQuery['filters']>>({})
|
||||||
const [exporting, setExporting] = useState(false),
|
const [exporting, setExporting] = useState(false),
|
||||||
[exportError, setExportError] = useState('')
|
[exportError, setExportError] = useState('')
|
||||||
@@ -481,7 +452,6 @@ export function QAOperations() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!canRead || query) return
|
if (!canRead || query) return
|
||||||
setGranularity(draft.kind)
|
|
||||||
setQuery({
|
setQuery({
|
||||||
start: qaDateTimeToISO(draft.start),
|
start: qaDateTimeToISO(draft.start),
|
||||||
end: qaDateTimeToISO(draft.end),
|
end: qaDateTimeToISO(draft.end),
|
||||||
@@ -581,7 +551,6 @@ export function QAOperations() {
|
|||||||
end = qaDateTimeToISO(draft.end)
|
end = qaDateTimeToISO(draft.end)
|
||||||
if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间')
|
if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间')
|
||||||
if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围')
|
if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围')
|
||||||
setGranularity(draft.kind)
|
|
||||||
setQuery({ start, end, keyword: draft.keyword, cursor: '', filters: { ...filters } })
|
setQuery({ start, end, keyword: draft.keyword, cursor: '', filters: { ...filters } })
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
setError(reason instanceof Error ? reason.message : '时间格式无效')
|
setError(reason instanceof Error ? reason.message : '时间格式无效')
|
||||||
@@ -664,83 +633,33 @@ export function QAOperations() {
|
|||||||
<>
|
<>
|
||||||
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
|
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
|
||||||
<form className="qa-ops-query" onSubmit={submit}>
|
<form className="qa-ops-query" onSubmit={submit}>
|
||||||
<label>
|
<QAWeekPicker
|
||||||
统计范围
|
year={draft.year}
|
||||||
<select
|
week={draft.week}
|
||||||
aria-label="统计范围"
|
onCurrentWeek={() => {
|
||||||
value={draft.kind}
|
const current = initialDraft()
|
||||||
onChange={(event) => {
|
setDraft({ ...current, keyword: draft.keyword })
|
||||||
const kind = event.target.value as QARangeKind
|
setQuery({
|
||||||
if (kind === 'week') {
|
start: qaDateTimeToISO(current.start),
|
||||||
const current = initialDraft()
|
end: qaDateTimeToISO(current.end),
|
||||||
setDraft({ ...current, keyword: draft.keyword })
|
keyword: draft.keyword,
|
||||||
} else if (kind === 'month') {
|
cursor: '',
|
||||||
const month = draft.month || monthInputValue()
|
filters: { ...filters },
|
||||||
try {
|
})
|
||||||
const range = monthQueryRange(month)
|
}}
|
||||||
setDraft({ ...draft, kind, month, week: null, ...range })
|
onChange={(year, week) =>
|
||||||
} catch {
|
setDraft((old) =>
|
||||||
setDraft({ ...draft, kind, month, week: null })
|
week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) }
|
||||||
}
|
)
|
||||||
} else {
|
}
|
||||||
setDraft({ ...draft, kind })
|
/>
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<option value="week">按周</option>
|
|
||||||
<option value="month">按月</option>
|
|
||||||
<option value="custom">自定义</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
{draft.kind === 'week' ? (
|
|
||||||
<QAWeekPicker
|
|
||||||
year={draft.year}
|
|
||||||
week={draft.week}
|
|
||||||
onCurrentWeek={() => {
|
|
||||||
const current = initialDraft()
|
|
||||||
setDraft({ ...current, keyword: draft.keyword })
|
|
||||||
setQuery({
|
|
||||||
start: qaDateTimeToISO(current.start),
|
|
||||||
end: qaDateTimeToISO(current.end),
|
|
||||||
keyword: draft.keyword,
|
|
||||||
cursor: '',
|
|
||||||
filters: { ...filters },
|
|
||||||
})
|
|
||||||
}}
|
|
||||||
onChange={(year, week) =>
|
|
||||||
setDraft((old) =>
|
|
||||||
week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
{draft.kind === 'month' ? (
|
|
||||||
<label>
|
|
||||||
月份
|
|
||||||
<input
|
|
||||||
type="month"
|
|
||||||
aria-label="统计月份"
|
|
||||||
value={draft.month}
|
|
||||||
max={monthInputValue()}
|
|
||||||
onChange={(event) => {
|
|
||||||
const month = event.target.value
|
|
||||||
try {
|
|
||||||
const range = monthQueryRange(month)
|
|
||||||
setDraft({ ...draft, month, week: null, ...range })
|
|
||||||
} catch {
|
|
||||||
setDraft({ ...draft, month })
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
) : null}
|
|
||||||
<label>
|
<label>
|
||||||
开始时间(北京时间)
|
开始时间(北京时间)
|
||||||
<input
|
<input
|
||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
required
|
required
|
||||||
value={draft.start}
|
value={draft.start}
|
||||||
onChange={(e) => setDraft({ ...draft, start: e.target.value, week: null, kind: 'custom' })}
|
onChange={(e) => setDraft({ ...draft, start: e.target.value, week: null })}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
@@ -749,7 +668,7 @@ export function QAOperations() {
|
|||||||
type="datetime-local"
|
type="datetime-local"
|
||||||
required
|
required
|
||||||
value={draft.end}
|
value={draft.end}
|
||||||
onChange={(e) => setDraft({ ...draft, end: e.target.value, week: null, kind: 'custom' })}
|
onChange={(e) => setDraft({ ...draft, end: e.target.value, week: null })}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="qa-ops-keyword">
|
<label className="qa-ops-keyword">
|
||||||
@@ -810,7 +729,6 @@ export function QAOperations() {
|
|||||||
) : view === 'dashboard' ? (
|
) : view === 'dashboard' ? (
|
||||||
<QADashboard
|
<QADashboard
|
||||||
query={query}
|
query={query}
|
||||||
granularity={granularity}
|
|
||||||
error={error}
|
error={error}
|
||||||
revision={qualityRevision}
|
revision={qualityRevision}
|
||||||
onRetry={() => {
|
onRetry={() => {
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
// 右侧抽屉(原生 <dialog>)必须能用三条路收回:关闭按钮、Esc、点抽屉外面。
|
||||||
|
// 这条用例专门盯第三条:内容比视口长时按钮会被滚走,只剩点外面能救场;
|
||||||
|
// 同时要保证点抽屉内部(含内边距)不会误关。
|
||||||
|
import { act } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import type { Root } from 'react-dom/client'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { FindingDetail } from './ReconciliationFindings'
|
||||||
|
import type { ReconciliationFinding } from './reconciliationApi'
|
||||||
|
|
||||||
|
const finding: ReconciliationFinding = {
|
||||||
|
id: 'f1',
|
||||||
|
run_id: 'run-1',
|
||||||
|
type: 'R3',
|
||||||
|
publication_id: 'tp-1',
|
||||||
|
document_id: '',
|
||||||
|
title: '线总览.md',
|
||||||
|
path: '产品/说明书',
|
||||||
|
source: '钉盘',
|
||||||
|
target_scope: 'internal',
|
||||||
|
ledger_state: 'completed',
|
||||||
|
weknora_parse_status: '',
|
||||||
|
normalized_state: 'completed',
|
||||||
|
ledger_sha256: 'deadbeef',
|
||||||
|
declared_sha256: 'deadbeef',
|
||||||
|
weknora_file_md5: 'deadbeef',
|
||||||
|
evidence_level: 'none',
|
||||||
|
confirmation_state: 'confirmed',
|
||||||
|
detail: '非平台导入条目,仅统计',
|
||||||
|
suggested_action: 'none',
|
||||||
|
action_state: 'open',
|
||||||
|
weknora_url: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
let container: HTMLDivElement
|
||||||
|
let root: Root
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const reactTestGlobal: { IS_REACT_ACT_ENVIRONMENT: boolean } = globalThis as unknown as {
|
||||||
|
IS_REACT_ACT_ENVIRONMENT: boolean
|
||||||
|
}
|
||||||
|
reactTestGlobal.IS_REACT_ACT_ENVIRONMENT = true
|
||||||
|
// jsdom 没有实现 dialog 的模态方法。
|
||||||
|
HTMLDialogElement.prototype.showModal = function showModal(this: HTMLDialogElement) {
|
||||||
|
this.open = true
|
||||||
|
}
|
||||||
|
container = document.createElement('div')
|
||||||
|
document.body.appendChild(container)
|
||||||
|
root = createRoot(container)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
act(() => root.unmount())
|
||||||
|
container.remove()
|
||||||
|
})
|
||||||
|
|
||||||
|
const renderDrawer = async () => {
|
||||||
|
const onClose = vi.fn()
|
||||||
|
await act(async () => root.render(<FindingDetail finding={finding} onClose={onClose} />))
|
||||||
|
const dialog = container.querySelector('dialog')
|
||||||
|
if (!dialog) throw new Error('抽屉没有渲染出来')
|
||||||
|
// 抽屉贴在视口右侧:x 800–1280、y 0–694。
|
||||||
|
dialog.getBoundingClientRect = () =>
|
||||||
|
({
|
||||||
|
left: 800,
|
||||||
|
right: 1280,
|
||||||
|
top: 0,
|
||||||
|
bottom: 694,
|
||||||
|
width: 480,
|
||||||
|
height: 694,
|
||||||
|
x: 800,
|
||||||
|
y: 0,
|
||||||
|
toJSON: () => ({}),
|
||||||
|
}) as DOMRect
|
||||||
|
return { onClose, dialog }
|
||||||
|
}
|
||||||
|
|
||||||
|
const click = async (target: Element, clientX: number, clientY: number) => {
|
||||||
|
await act(async () => {
|
||||||
|
target.dispatchEvent(new MouseEvent('click', { bubbles: true, clientX, clientY }))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('reconciliation finding drawer', () => {
|
||||||
|
it('closes when the backdrop is clicked', async () => {
|
||||||
|
const { onClose, dialog } = await renderDrawer()
|
||||||
|
await click(dialog, 200, 300)
|
||||||
|
expect(onClose).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stays open when the drawer body is clicked', async () => {
|
||||||
|
const { onClose, dialog } = await renderDrawer()
|
||||||
|
await click(dialog, 1000, 400)
|
||||||
|
expect(onClose).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
} from './reconciliationApi'
|
} from './reconciliationApi'
|
||||||
import { fetchReconciliationProgress } from './reconciliationApi'
|
import { fetchReconciliationProgress } from './reconciliationApi'
|
||||||
import { reconciliationErrorText, reconciliationFailureText, reconciliationStageText } from './reconciliationMessages'
|
import { reconciliationErrorText, reconciliationFailureText, reconciliationStageText } from './reconciliationMessages'
|
||||||
|
import { onBackdropClick } from './dialogBackdrop'
|
||||||
import './monitorWorkbench.css'
|
import './monitorWorkbench.css'
|
||||||
|
|
||||||
const time = (value: string | null | undefined) =>
|
const time = (value: string | null | undefined) =>
|
||||||
@@ -441,7 +442,7 @@ export function FindingDetail({ finding, onClose }: { finding: ReconciliationFin
|
|||||||
ref.current?.showModal()
|
ref.current?.showModal()
|
||||||
}, [])
|
}, [])
|
||||||
return (
|
return (
|
||||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose}>
|
<dialog className="monitor-drawer" ref={ref} onCancel={onClose} onClick={onBackdropClick(ref, onClose)}>
|
||||||
<header>
|
<header>
|
||||||
<h2>{typeLabels[finding.type]} · 处理详情</h2>
|
<h2>{typeLabels[finding.type]} · 处理详情</h2>
|
||||||
<button onClick={onClose} autoFocus>
|
<button onClick={onClose} autoFocus>
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import {
|
|||||||
} from './reconciliationApi'
|
} from './reconciliationApi'
|
||||||
import type { ReconciliationFinding, ReconciliationFindingPage, ReconciliationRunPage } from './reconciliationApi'
|
import type { ReconciliationFinding, ReconciliationFindingPage, ReconciliationRunPage } from './reconciliationApi'
|
||||||
import { isTestBindingMissing, reconciliationErrorText, reconciliationMessages } from './reconciliationMessages'
|
import { isTestBindingMissing, reconciliationErrorText, reconciliationMessages } from './reconciliationMessages'
|
||||||
|
import { onBackdropClick } from './dialogBackdrop'
|
||||||
import './monitorWorkbench.css'
|
import './monitorWorkbench.css'
|
||||||
|
|
||||||
const emptyRuns: ReconciliationRunPage = { items: [], total: 0, limit: 20, offset: 0 }
|
const emptyRuns: ReconciliationRunPage = { items: [], total: 0, limit: 20, offset: 0 }
|
||||||
@@ -522,7 +523,7 @@ export function TaskDetail({
|
|||||||
ref.current?.showModal()
|
ref.current?.showModal()
|
||||||
}, [])
|
}, [])
|
||||||
return (
|
return (
|
||||||
<dialog className="monitor-drawer" ref={ref} onCancel={onClose}>
|
<dialog className="monitor-drawer" ref={ref} onCancel={onClose} onClick={onBackdropClick(ref, onClose)}>
|
||||||
<header>
|
<header>
|
||||||
<h2>文件处理详情</h2>
|
<h2>文件处理详情</h2>
|
||||||
<button onClick={onClose} autoFocus>
|
<button onClick={onClose} autoFocus>
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// 原生 <dialog> 的 ::backdrop 点击会派发到 dialog 元素本身,但浏览器不会自动关闭它,
|
||||||
|
// 于是右侧抽屉一打开就只能靠「关闭」按钮或 Esc 收回;内容比视口长时按钮还会被滚走。
|
||||||
|
// 这里按坐标判断:落在 dialog 矩形外的点击才关闭(dialog 自己的内边距仍算内部,
|
||||||
|
// 不能因为点在内边距上就把抽屉关掉)。
|
||||||
|
export function onBackdropClick(
|
||||||
|
ref: { current: HTMLDialogElement | null },
|
||||||
|
close: () => void
|
||||||
|
): (event: { clientX: number; clientY: number }) => void {
|
||||||
|
return (event) => {
|
||||||
|
const dialog = ref.current
|
||||||
|
if (!dialog) return
|
||||||
|
const rect = dialog.getBoundingClientRect()
|
||||||
|
const inside =
|
||||||
|
event.clientX >= rect.left &&
|
||||||
|
event.clientX <= rect.right &&
|
||||||
|
event.clientY >= rect.top &&
|
||||||
|
event.clientY <= rect.bottom
|
||||||
|
if (!inside) close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -434,7 +434,9 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-left: 1px solid var(--border-base);
|
border-left: 1px solid var(--border-base);
|
||||||
padding: 25px;
|
/* 顶部的内边距交给 sticky 的 header:抽屉内容比视口长时,
|
||||||
|
「关闭」必须一直留在可见区,不能被滚走。 */
|
||||||
|
padding: 0 25px 25px;
|
||||||
background: var(--bg-panel);
|
background: var(--bg-panel);
|
||||||
color: var(--ink-base);
|
color: var(--ink-base);
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
@@ -448,6 +450,12 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
|
/* 长内容滚动时「关闭」不离屏:吸顶 + 盖住底下滚过的行 */
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 1;
|
||||||
|
padding: 25px 0 12px;
|
||||||
|
background: var(--bg-panel);
|
||||||
}
|
}
|
||||||
.monitor-drawer h2 {
|
.monitor-drawer h2 {
|
||||||
font-size: 19px;
|
font-size: 19px;
|
||||||
|
|||||||
+37
-114
@@ -68,15 +68,6 @@ export interface DashboardRegion {
|
|||||||
frequency: number | null
|
frequency: number | null
|
||||||
usage_coverage: QualityRate
|
usage_coverage: QualityRate
|
||||||
}
|
}
|
||||||
export type DashboardGranularity = 'day' | 'week' | 'month' | 'custom'
|
|
||||||
export interface DashboardPeriod {
|
|
||||||
kind: DashboardGranularity
|
|
||||||
label: string
|
|
||||||
start: string
|
|
||||||
end: string
|
|
||||||
prev_start: string
|
|
||||||
prev_end: string
|
|
||||||
}
|
|
||||||
export interface QADashboardData {
|
export interface QADashboardData {
|
||||||
filters?: QAQuery['filters']
|
filters?: QAQuery['filters']
|
||||||
start: string
|
start: string
|
||||||
@@ -100,11 +91,6 @@ export interface QADashboardData {
|
|||||||
quality_period?: DashboardQualityPeriod
|
quality_period?: DashboardQualityPeriod
|
||||||
monthly_quality?: DashboardStrictQuality
|
monthly_quality?: DashboardStrictQuality
|
||||||
calendar_months?: DashboardMonth[]
|
calendar_months?: DashboardMonth[]
|
||||||
granularity?: DashboardGranularity
|
|
||||||
period?: DashboardPeriod
|
|
||||||
period_issues?: number
|
|
||||||
prev_period_issues?: number
|
|
||||||
period_quality?: DashboardStrictQuality
|
|
||||||
}
|
}
|
||||||
const bad = (): never => {
|
const bad = (): never => {
|
||||||
throw new Error('统计看板响应无效,未展示可能失真的指标')
|
throw new Error('统计看板响应无效,未展示可能失真的指标')
|
||||||
@@ -156,9 +142,6 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
|||||||
Date.parse(month_start) !== month(Date.parse(end) - 1)
|
Date.parse(month_start) !== month(Date.parse(end) - 1)
|
||||||
)
|
)
|
||||||
return bad()
|
return bad()
|
||||||
const granularityRaw = v.granularity
|
|
||||||
if (granularityRaw !== undefined && !['day', 'week', 'month', 'custom'].includes(String(granularityRaw))) return bad()
|
|
||||||
const granularity = granularityRaw === undefined ? undefined : (granularityRaw as DashboardGranularity)
|
|
||||||
const quality = parseQualitySummary({
|
const quality = parseQualitySummary({
|
||||||
summary: v.quality,
|
summary: v.quality,
|
||||||
start,
|
start,
|
||||||
@@ -172,63 +155,6 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
|||||||
total_issues = count(v.total_issues),
|
total_issues = count(v.total_issues),
|
||||||
new_this_week = count(v.new_this_week)
|
new_this_week = count(v.new_this_week)
|
||||||
if (new_this_week > total_issues || quality.total > total_issues) return bad()
|
if (new_this_week > total_issues || quality.total > total_issues) return bad()
|
||||||
const monthlySource = 'master_live_calendar_month_v1' as const,
|
|
||||||
monthlyPolicy = 'calendar-month-strict-yes-over-yes-no-v2' as const,
|
|
||||||
nextMonth = (at: number) => {
|
|
||||||
const d = new Date(at + offset)
|
|
||||||
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1) - offset
|
|
||||||
},
|
|
||||||
monthLabel = (at: number) => new Date(at + offset).toISOString().slice(0, 7),
|
|
||||||
strictRates = (raw: Record<string, unknown>): DashboardStrictQuality => {
|
|
||||||
const records = count(raw.records),
|
|
||||||
unjudged = count(raw.unjudged),
|
|
||||||
coverage = parseQualityRate(raw.coverage),
|
|
||||||
correctness = parseQualityRate(raw.correctness)
|
|
||||||
if (
|
|
||||||
records > total_issues ||
|
|
||||||
unjudged > records ||
|
|
||||||
coverage.denominator > records ||
|
|
||||||
correctness.denominator + unjudged > records
|
|
||||||
)
|
|
||||||
return bad()
|
|
||||||
return { records, coverage, correctness, unjudged }
|
|
||||||
}
|
|
||||||
let period: DashboardPeriod | undefined
|
|
||||||
let period_issues: number | undefined
|
|
||||||
let prev_period_issues: number | undefined
|
|
||||||
let period_quality: DashboardStrictQuality | undefined
|
|
||||||
if (granularity) {
|
|
||||||
const p = obj(v.period),
|
|
||||||
kind = p.kind,
|
|
||||||
label = text(p.label),
|
|
||||||
periodStart = stamp(p.start),
|
|
||||||
periodEnd = stamp(p.end),
|
|
||||||
prevStart = stamp(p.prev_start),
|
|
||||||
prevEnd = stamp(p.prev_end)
|
|
||||||
if (
|
|
||||||
kind !== granularity ||
|
|
||||||
!label ||
|
|
||||||
Date.parse(periodStart) !== Date.parse(start) ||
|
|
||||||
Date.parse(periodEnd) !== Date.parse(end) ||
|
|
||||||
Date.parse(prevEnd) !== Date.parse(start) ||
|
|
||||||
Date.parse(prevStart) >= Date.parse(prevEnd)
|
|
||||||
)
|
|
||||||
return bad()
|
|
||||||
period = { kind: granularity, label, start: periodStart, end: periodEnd, prev_start: prevStart, prev_end: prevEnd }
|
|
||||||
period_issues = count(v.period_issues)
|
|
||||||
prev_period_issues = count(v.prev_period_issues)
|
|
||||||
if (period_issues !== new_this_week || period_issues > total_issues) return bad()
|
|
||||||
if (v.period_quality !== undefined) {
|
|
||||||
period_quality = strictRates(obj(v.period_quality))
|
|
||||||
if (period_quality.records !== period_issues) return bad()
|
|
||||||
}
|
|
||||||
} else if (
|
|
||||||
v.period !== undefined ||
|
|
||||||
v.period_issues !== undefined ||
|
|
||||||
v.prev_period_issues !== undefined ||
|
|
||||||
v.period_quality !== undefined
|
|
||||||
)
|
|
||||||
return bad()
|
|
||||||
const regionIDs = new Set<string>(),
|
const regionIDs = new Set<string>(),
|
||||||
regionNames = new Set<string>()
|
regionNames = new Set<string>()
|
||||||
const regions = list(v.regions).map((raw) => {
|
const regions = list(v.regions).map((raw) => {
|
||||||
@@ -263,22 +189,21 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
|||||||
return { id, name, questions, users, roster_people, frequency, usage_coverage }
|
return { id, name, questions, users, roster_people, frequency, usage_coverage }
|
||||||
})
|
})
|
||||||
if (regions.length !== (organization.region_names?.length ?? 0)) return bad()
|
if (regions.length !== (organization.region_names?.length ?? 0)) return bad()
|
||||||
const dailyAnchor = granularity ? start : week_start,
|
const daily = list(v.daily).map((raw, i) => {
|
||||||
daily = list(v.daily).map((raw, i) => {
|
const d = obj(raw),
|
||||||
const d = obj(raw),
|
date = text(d.date),
|
||||||
date = text(d.date),
|
n = count(d.count)
|
||||||
n = count(d.count)
|
if (
|
||||||
if (
|
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
||||||
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
|
Date.parse(date + 'T00:00:00+08:00') !== Date.parse(week_start) + i * dayMS
|
||||||
Date.parse(date + 'T00:00:00+08:00') !== Date.parse(dailyAnchor) + i * dayMS
|
)
|
||||||
)
|
return bad()
|
||||||
return bad()
|
return { date, count: n }
|
||||||
return { date, count: n }
|
})
|
||||||
})
|
|
||||||
if (
|
if (
|
||||||
daily.length < 1 ||
|
daily.length < 1 ||
|
||||||
daily.length > (granularity ? 92 : 7) ||
|
daily.length > 7 ||
|
||||||
daily.reduce((n, r) => n + r.count, 0) !== (granularity ? period_issues : new_this_week) ||
|
daily.reduce((n, r) => n + r.count, 0) !== new_this_week ||
|
||||||
Date.parse(daily[daily.length - 1].date + 'T00:00:00+08:00') >= Date.parse(end)
|
Date.parse(daily[daily.length - 1].date + 'T00:00:00+08:00') >= Date.parse(end)
|
||||||
)
|
)
|
||||||
return bad()
|
return bad()
|
||||||
@@ -410,6 +335,27 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
|||||||
let quality_period: DashboardQualityPeriod | undefined
|
let quality_period: DashboardQualityPeriod | undefined
|
||||||
let monthly_quality: DashboardStrictQuality | undefined
|
let monthly_quality: DashboardStrictQuality | undefined
|
||||||
let calendar_months: DashboardMonth[] | undefined
|
let calendar_months: DashboardMonth[] | undefined
|
||||||
|
const monthlySource = 'master_live_calendar_month_v1' as const,
|
||||||
|
monthlyPolicy = 'calendar-month-strict-yes-over-yes-no-v2' as const,
|
||||||
|
nextMonth = (at: number) => {
|
||||||
|
const d = new Date(at + offset)
|
||||||
|
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1) - offset
|
||||||
|
},
|
||||||
|
monthLabel = (at: number) => new Date(at + offset).toISOString().slice(0, 7),
|
||||||
|
strictRates = (raw: Record<string, unknown>): DashboardStrictQuality => {
|
||||||
|
const records = count(raw.records),
|
||||||
|
unjudged = count(raw.unjudged),
|
||||||
|
coverage = parseQualityRate(raw.coverage),
|
||||||
|
correctness = parseQualityRate(raw.correctness)
|
||||||
|
if (
|
||||||
|
records > total_issues ||
|
||||||
|
unjudged > records ||
|
||||||
|
coverage.denominator > records ||
|
||||||
|
correctness.denominator + unjudged > records
|
||||||
|
)
|
||||||
|
return bad()
|
||||||
|
return { records, coverage, correctness, unjudged }
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
v.quality_period !== undefined ||
|
v.quality_period !== undefined ||
|
||||||
v.monthly_quality !== undefined ||
|
v.monthly_quality !== undefined ||
|
||||||
@@ -514,11 +460,6 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
filters: parseQualityFilters(v.filters),
|
filters: parseQualityFilters(v.filters),
|
||||||
granularity,
|
|
||||||
period,
|
|
||||||
period_issues,
|
|
||||||
prev_period_issues,
|
|
||||||
period_quality,
|
|
||||||
quality_period,
|
quality_period,
|
||||||
monthly_quality,
|
monthly_quality,
|
||||||
calendar_months,
|
calendar_months,
|
||||||
@@ -542,19 +483,7 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
|||||||
frozen_weeks,
|
frozen_weeks,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export function liveDashboardQuery(query: QAQuery, now: Date, granularity?: string): QAQuery {
|
export function liveDashboardQuery(query: QAQuery, now: Date): QAQuery {
|
||||||
// A custom or single-day range is an explicit slice: never stretch it to "now".
|
|
||||||
if (granularity === 'custom' || granularity === 'day') return query
|
|
||||||
const beijingMonth = (at: number) => new Date(at + 8 * 3_600_000).toISOString().slice(0, 7)
|
|
||||||
// A chosen month is a closed accounting period: only the month that contains
|
|
||||||
// "now" may advance with the clock. Stretching a finished month to now pulled
|
|
||||||
// the region panels (natural-month cumulative) into the NEXT month, so an
|
|
||||||
// 11 月 selection showed 12 月 usage.
|
|
||||||
if (granularity === 'month') {
|
|
||||||
if (beijingMonth(Date.parse(query.end) - 1) !== beijingMonth(now.getTime())) return query
|
|
||||||
if (Date.parse(query.end) >= now.getTime()) return query
|
|
||||||
return { ...query, end: now.toISOString() }
|
|
||||||
}
|
|
||||||
const last = currentQAWeek(new Date(Date.parse(query.end) - 1)),
|
const last = currentQAWeek(new Date(Date.parse(query.end) - 1)),
|
||||||
current = currentQAWeek(now)
|
current = currentQAWeek(now)
|
||||||
if (
|
if (
|
||||||
@@ -566,11 +495,7 @@ export function liveDashboardQuery(query: QAQuery, now: Date, granularity?: stri
|
|||||||
return query
|
return query
|
||||||
return { ...query, end: now.toISOString() }
|
return { ...query, end: now.toISOString() }
|
||||||
}
|
}
|
||||||
export async function fetchQADashboard(
|
export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Promise<QADashboardData> {
|
||||||
query: QAQuery,
|
|
||||||
signal?: AbortSignal,
|
|
||||||
granularity?: DashboardGranularity
|
|
||||||
): Promise<QADashboardData> {
|
|
||||||
const response = await fetch('/api/v1/qa-ops/dashboard', {
|
const response = await fetch('/api/v1/qa-ops/dashboard', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
@@ -581,7 +506,6 @@ export async function fetchQADashboard(
|
|||||||
start: query.start,
|
start: query.start,
|
||||||
end: query.end,
|
end: query.end,
|
||||||
keyword: query.keyword,
|
keyword: query.keyword,
|
||||||
...(granularity ? { granularity } : {}),
|
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
const body: unknown = await response.json().catch(() => null)
|
const body: unknown = await response.json().catch(() => null)
|
||||||
@@ -594,8 +518,7 @@ export async function fetchQADashboard(
|
|||||||
Date.parse(data.start) !== Date.parse(query.start) ||
|
Date.parse(data.start) !== Date.parse(query.start) ||
|
||||||
Date.parse(data.end) !== Date.parse(query.end) ||
|
Date.parse(data.end) !== Date.parse(query.end) ||
|
||||||
data.keyword !== query.keyword ||
|
data.keyword !== query.keyword ||
|
||||||
Object.keys(data.filters ?? {}).length !== 0 ||
|
Object.keys(data.filters ?? {}).length !== 0
|
||||||
(granularity ?? undefined) !== data.granularity
|
|
||||||
)
|
)
|
||||||
throw new Error('看板返回范围与当前查询不一致,请重新读取')
|
throw new Error('看板返回范围与当前查询不一致,请重新读取')
|
||||||
return data
|
return data
|
||||||
|
|||||||
@@ -18,21 +18,3 @@ it('never rolls an already closed selected week into a different week', () => {
|
|||||||
const closed = { ...query, start: '2026-10-12T00:00:00+08:00', end: '2026-10-19T00:00:00+08:00' }
|
const closed = { ...query, start: '2026-10-12T00:00:00+08:00', end: '2026-10-19T00:00:00+08:00' }
|
||||||
expect(liveDashboardQuery(closed, new Date('2026-10-20T09:00:00+08:00'))).toEqual(closed)
|
expect(liveDashboardQuery(closed, new Date('2026-10-20T09:00:00+08:00'))).toEqual(closed)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('never stretches an explicit custom range to now', () => {
|
|
||||||
const custom = { ...query, start: '2026-10-01T00:00:00+08:00', end: '2026-10-03T00:00:00+08:00' }
|
|
||||||
expect(liveDashboardQuery(custom, new Date('2026-10-20T09:00:00+08:00'), 'custom')).toEqual(custom)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('never stretches a finished month into the next month', () => {
|
|
||||||
const closedMonth = { ...query, start: '2026-11-01T00:00:00+08:00', end: '2026-12-01T00:00:00+08:00' }
|
|
||||||
const now = new Date('2026-12-03T22:45:00+08:00')
|
|
||||||
expect(liveDashboardQuery(closedMonth, now, 'month')).toEqual(closedMonth)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps the current month live up to now', () => {
|
|
||||||
const openMonth = { ...query, start: '2026-12-01T00:00:00+08:00', end: '2026-12-03T22:00:00+08:00' }
|
|
||||||
const next = liveDashboardQuery(openMonth, new Date('2026-12-03T22:45:00+08:00'), 'month')
|
|
||||||
expect(next.end).toBe('2026-12-03T14:45:00.000Z')
|
|
||||||
expect(next.start).toBe(openMonth.start)
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,78 +0,0 @@
|
|||||||
import { renderToStaticMarkup } from 'react-dom/server'
|
|
||||||
import { describe, it, expect, vi } from 'vitest'
|
|
||||||
import { QADashboardView } from './QADashboard'
|
|
||||||
import { parseQADashboard } from './qaDashboardData'
|
|
||||||
import { dashboardFixture } from './qaDashboard.fixture'
|
|
||||||
|
|
||||||
const monthStart = '2026-11-01T00:00:00+08:00',
|
|
||||||
monthEnd = '2026-12-01T00:00:00+08:00'
|
|
||||||
const monthFixture = {
|
|
||||||
...dashboardFixture,
|
|
||||||
start: monthStart,
|
|
||||||
end: monthEnd,
|
|
||||||
week_start: '2026-11-30T00:00:00+08:00',
|
|
||||||
month_start: monthStart,
|
|
||||||
total_issues: 120,
|
|
||||||
new_this_week: 30,
|
|
||||||
granularity: 'month',
|
|
||||||
period: {
|
|
||||||
kind: 'month',
|
|
||||||
label: '2026-11',
|
|
||||||
start: monthStart,
|
|
||||||
end: monthEnd,
|
|
||||||
prev_start: '2026-10-01T00:00:00+08:00',
|
|
||||||
prev_end: monthStart,
|
|
||||||
},
|
|
||||||
period_issues: 30,
|
|
||||||
prev_period_issues: 25,
|
|
||||||
daily: Array.from({ length: 30 }, (_, i) => ({ date: `2026-11-${String(i + 1).padStart(2, '0')}`, count: 1 })),
|
|
||||||
frozen_weeks: [],
|
|
||||||
reported_weeks: [],
|
|
||||||
cumulative_weeks: [],
|
|
||||||
period_quality: {
|
|
||||||
records: 30,
|
|
||||||
unjudged: 0,
|
|
||||||
coverage: { numerator: 20, denominator: 30, percent: (100 * 20) / 30 },
|
|
||||||
correctness: { numerator: 18, denominator: 20, percent: 90 },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('monthly dashboard range', () => {
|
|
||||||
it('parses a monthly range and keeps the trend over the whole month', () => {
|
|
||||||
const data = parseQADashboard(monthFixture)
|
|
||||||
expect(data.period?.label).toBe('2026-11')
|
|
||||||
expect(data.period_issues).toBe(30)
|
|
||||||
expect(data.prev_period_issues).toBe(25)
|
|
||||||
expect(data.daily).toHaveLength(30)
|
|
||||||
expect(data.period_quality?.coverage.numerator).toBe(20)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('labels the cards from the selected range instead of a hardcoded week', () => {
|
|
||||||
const data = parseQADashboard(monthFixture)
|
|
||||||
const html = renderToStaticMarkup(<QADashboardView data={data} loading={false} error="" onRetry={vi.fn()} />)
|
|
||||||
expect(html).toContain('本期新增')
|
|
||||||
expect(html).toContain('2026-11 · 上期 25 条')
|
|
||||||
expect(html).toContain('全部指标按所选范围统计')
|
|
||||||
expect(html).not.toContain('所选自然周')
|
|
||||||
expect(html).toContain('66.7%')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('cuts the region panels from the selected range and names the roster month', () => {
|
|
||||||
const data = parseQADashboard(monthFixture)
|
|
||||||
const html = renderToStaticMarkup(<QADashboardView data={data} loading={false} error="" onRetry={vi.fn()} />)
|
|
||||||
expect(html).toContain('区域统计按所选区间')
|
|
||||||
expect(html).toContain('分母为当前通讯录')
|
|
||||||
expect(html).toContain('所选区间提问 / 去重使用 ÷ 当前通讯录')
|
|
||||||
expect(html).not.toContain('2026-11月累计')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects a payload that claims a month granularity without a matching period', () => {
|
|
||||||
const { period: _period, ...rest } = monthFixture
|
|
||||||
expect(() => parseQADashboard(rest)).toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rejects a trend that does not add up to the period total', () => {
|
|
||||||
const broken = { ...monthFixture, daily: monthFixture.daily.map((p) => ({ ...p, count: 1 })).slice(0, 29) }
|
|
||||||
expect(() => parseQADashboard(broken)).toThrow()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -3,38 +3,27 @@ const beijing = (at: string) => new Date(Date.parse(at) + 8 * 3600000).toISOStri
|
|||||||
const windowText = (start: string, end: string) => `北京时间 ${beijing(start)} 至 ${beijing(end)}(终点不含)。`
|
const windowText = (start: string, end: string) => `北京时间 ${beijing(start)} 至 ${beijing(end)}(终点不含)。`
|
||||||
export function dashboardStatisticsHelp(data: QADashboardData): Record<string, string> {
|
export function dashboardStatisticsHelp(data: QADashboardData): Record<string, string> {
|
||||||
const filter = '沿用已执行关键词筛选。',
|
const filter = '沿用已执行关键词筛选。',
|
||||||
selected = data.period,
|
week = windowText(data.start, data.end),
|
||||||
period = data.quality_period,
|
|
||||||
week = selected ? windowText(selected.start, selected.end) : windowText(data.start, data.end),
|
|
||||||
regionMonth = windowText(data.month_start, data.end),
|
regionMonth = windowText(data.month_start, data.end),
|
||||||
rates = selected ? data.period_quality : data.monthly_quality,
|
period = data.quality_period,
|
||||||
qualityRange = selected
|
rates = data.monthly_quality,
|
||||||
? windowText(selected.start, selected.end)
|
qualityRange = period ? windowText(period.start, period.cutoff_at) : week,
|
||||||
: period
|
|
||||||
? windowText(period.start, period.cutoff_at)
|
|
||||||
: week,
|
|
||||||
qualityRecords = rates?.records ?? data.quality.total,
|
qualityRecords = rates?.records ?? data.quality.total,
|
||||||
coverage = rates?.coverage ?? data.quality.rates.coverage,
|
coverage = rates?.coverage ?? data.quality.rates.coverage,
|
||||||
correctness = rates?.correctness ?? data.quality.rates.correctness,
|
correctness = rates?.correctness ?? data.quality.rates.correctness,
|
||||||
periodLabel = selected ? selected.label : '所选自然周',
|
|
||||||
periodCount = selected ? (data.period_issues ?? data.new_this_week) : data.new_this_week,
|
|
||||||
calendar =
|
calendar =
|
||||||
'每月1日重新累计,不累计之前月份,不平均周百分比;按原始提问时间归月,使用当前有效结论及点踩否,空分母留空。',
|
'每月1日重新累计,不累计之前月份,不平均周百分比;按原始提问时间归月,使用当前有效结论及点踩否,空分母留空。',
|
||||||
qualityScope = selected
|
qualityScope = period
|
||||||
? `统计范围 ${selected.label}(${qualityRange})。全部指标与看板筛选同一区间,不混用其它月份。`
|
? `统计月 ${period.month}。跨月周取周一所在月;当前未结束只截至实际时点。`
|
||||||
: period
|
: '旧接口按所选查询范围统计。'
|
||||||
? `统计月 ${period.month}。跨月周取周一所在月;当前未结束只截至实际时点。`
|
|
||||||
: '旧接口按所选查询范围统计。'
|
|
||||||
return {
|
return {
|
||||||
total: `截至北京时间 ${beijing(data.end)}(不含),治理总表历史导入和2.0收录的去重问题记录数,共 ${data.total_issues} 条;不把当前页条数当总数,不因缺少分析字段排除。${filter}`,
|
total: `截至北京时间 ${beijing(data.end)}(不含),治理总表历史导入和2.0收录的去重问题记录数,共 ${data.total_issues} 条;不把当前页条数当总数,不因缺少分析字段排除。${filter}`,
|
||||||
'new-week': `${week}${periodLabel}新增=原始提问时间落在所选范围内的问题数,共 ${periodCount} 条${
|
'new-week': `${windowText(data.week_start, data.end)}本周新增=原始提问时间落在本自然周内的问题数,共 ${data.new_this_week} 条;当前周截至当前,不按导入时间算新增。${filter}`,
|
||||||
selected && data.prev_period_issues !== undefined ? `;同一口径上一区间 ${data.prev_period_issues} 条` : ''
|
|
||||||
};不按导入时间算新增。${filter}`,
|
|
||||||
coverage: `${qualityScope}${qualityRange}${rates ? '覆盖率=覆盖是÷(是+否)×100%。部分覆盖、待确认、未知、空白、失效等不计分母。' : '旧覆盖率=覆盖是÷(覆盖是+覆盖否+部分覆盖)×100%。'}本范围 ${qualityRecords} 条;分子 ${coverage.numerator},分母 ${coverage.denominator},排除 ${qualityRecords - coverage.denominator} 条。${filter}`,
|
coverage: `${qualityScope}${qualityRange}${rates ? '覆盖率=覆盖是÷(是+否)×100%。部分覆盖、待确认、未知、空白、失效等不计分母。' : '旧覆盖率=覆盖是÷(覆盖是+覆盖否+部分覆盖)×100%。'}本范围 ${qualityRecords} 条;分子 ${coverage.numerator},分母 ${coverage.denominator},排除 ${qualityRecords - coverage.denominator} 条。${filter}`,
|
||||||
accuracy: `${qualityScope}${qualityRange}${rates ? '正确率=正确是÷(是+否)×100%;不限定仅已覆盖问题。' : '旧正确率=已覆盖样本内的正确是÷(是+否)×100%。'}本范围 ${qualityRecords} 条;分子 ${correctness.numerator},分母 ${correctness.denominator},排除 ${qualityRecords - correctness.denominator} 条。待确认、未知、空白、失效等排除;已判定样本正确率不代表全部问题已确认。${filter}`,
|
accuracy: `${qualityScope}${qualityRange}${rates ? '正确率=正确是÷(是+否)×100%;不限定仅已覆盖问题。' : '旧正确率=已覆盖样本内的正确是÷(是+否)×100%。'}本范围 ${qualityRecords} 条;分子 ${correctness.numerator},分母 ${correctness.denominator},排除 ${qualityRecords - correctness.denominator} 条。待确认、未知、空白、失效等排除;已判定样本正确率不代表全部问题已确认。${filter}`,
|
||||||
'issue-types': `${week}按本查询范围内每条问题的当前有效“问题类型”归组,每条计1次;缺失保留“未分类”。饼图占比=该类型条数÷范围内 ${data.quality.total} 条×100%。${filter}`,
|
'issue-types': `${week}按本查询范围内每条问题的当前有效“问题类型”归组,每条计1次;缺失保留“未分类”。饼图占比=该类型条数÷范围内 ${data.quality.total} 条×100%。${filter}`,
|
||||||
products: `${week}按当前有效“产品分类”归组,每条问题计1次,数量降序;缺失保留“未分类”,不与问题类型混用。范围共 ${data.quality.total} 条。${filter}`,
|
products: `${week}按当前有效“产品分类”归组,每条问题计1次,数量降序;缺失保留“未分类”,不与问题类型混用。范围共 ${data.quality.total} 条。${filter}`,
|
||||||
'issue-trend': `${week}按原始提问时间在北京时间逐日计数,零提问日保留;各日合计=${periodLabel}新增 ${periodCount} 条,不按导入日计算。${filter}`,
|
'issue-trend': `${windowText(data.week_start, data.end)}按原始提问时间在北京时间逐日计数,零提问日保留;各日合计=本周新增 ${data.new_this_week} 条,不按导入日计算。${filter}`,
|
||||||
frequency: `${regionMonth}区域平均使用频率=能稳定关联该区域的月内提问条数÷当前配置通讯录去重人数。缺失/待核对身份不强行归属,零分母显示“—”;当前名册不是在职或绩效名单。${filter}`,
|
frequency: `${regionMonth}区域平均使用频率=能稳定关联该区域的月内提问条数÷当前配置通讯录去重人数。缺失/待核对身份不强行归属,零分母显示“—”;当前名册不是在职或绩效名单。${filter}`,
|
||||||
'usage-coverage': `${regionMonth}区域使用覆盖率=月内稳定身份去重使用人数÷同一区域当前配置通讯录去重人数×100%。零使用者保留在分母,无法关联者不凑人数;无名单或零分母显示“—”,不是绩效结论。${filter}`,
|
'usage-coverage': `${regionMonth}区域使用覆盖率=月内稳定身份去重使用人数÷同一区域当前配置通讯录去重人数×100%。零使用者保留在分母,无法关联者不凑人数;无名单或零分母显示“—”,不是绩效结论。${filter}`,
|
||||||
'coverage-trend': period
|
'coverage-trend': period
|
||||||
|
|||||||
Reference in New Issue
Block a user