feat(ui): add content editor components for skills and thoughts
Some checks failed
CI / build-and-test (push) Failing after -31m24s
Some checks failed
CI / build-and-test (push) Failing after -31m24s
* Implement ContentEditorField for inline editing of content * Create ContentEditorModal for editing content in a modal * Introduce FormerShell for managing forms related to skills and thoughts * Enhance SkillsPage and ThoughtsPage with new components for better content management
This commit is contained in:
5
Makefile
5
Makefile
@@ -4,6 +4,7 @@ SERVER_BIN := $(BIN_DIR)/amcs-server
|
|||||||
CMD_SERVER := ./cmd/amcs-server
|
CMD_SERVER := ./cmd/amcs-server
|
||||||
BUILDINFO_PKG := git.warky.dev/wdevs/amcs/internal/buildinfo
|
BUILDINFO_PKG := git.warky.dev/wdevs/amcs/internal/buildinfo
|
||||||
UI_DIR := $(CURDIR)/ui
|
UI_DIR := $(CURDIR)/ui
|
||||||
|
AMCS_UI_BACKEND ?= http://127.0.0.1:8080
|
||||||
PATCH_INCREMENT ?= 1
|
PATCH_INCREMENT ?= 1
|
||||||
RELEASE_VERSION ?=
|
RELEASE_VERSION ?=
|
||||||
RELEASE_REMOTE ?= origin
|
RELEASE_REMOTE ?= origin
|
||||||
@@ -40,7 +41,7 @@ help:
|
|||||||
@echo " check-schema-drift Verify generated migration matches current schema"
|
@echo " check-schema-drift Verify generated migration matches current schema"
|
||||||
@echo " ui-install Install UI dependencies"
|
@echo " ui-install Install UI dependencies"
|
||||||
@echo " ui-build Build UI assets"
|
@echo " ui-build Build UI assets"
|
||||||
@echo " ui-dev Start UI dev server"
|
@echo " ui-dev Start UI dev server with local API proxy"
|
||||||
@echo " ui-check Run UI type checks"
|
@echo " ui-check Run UI type checks"
|
||||||
|
|
||||||
build: ui-build
|
build: ui-build
|
||||||
@@ -54,7 +55,7 @@ ui-build: ui-install
|
|||||||
cd $(UI_DIR) && $(PNPM) run build
|
cd $(UI_DIR) && $(PNPM) run build
|
||||||
|
|
||||||
ui-dev: ui-install
|
ui-dev: ui-install
|
||||||
cd $(UI_DIR) && $(PNPM) run dev
|
cd $(UI_DIR) && VITE_API_URL=/api AMCS_UI_BACKEND=$(AMCS_UI_BACKEND) $(PNPM) run dev
|
||||||
|
|
||||||
ui-check: ui-install
|
ui-check: ui-install
|
||||||
cd $(UI_DIR) && $(PNPM) run check
|
cd $(UI_DIR) && $(PNPM) run check
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ func routes(logger *slog.Logger, cfg *config.Config, info buildinfo.Info, db *st
|
|||||||
Backfill: backfillTool,
|
Backfill: backfillTool,
|
||||||
Reparse: tools.NewReparseMetadataTool(db, bgMetadata, cfg.Capture, activeProjects, logger),
|
Reparse: tools.NewReparseMetadataTool(db, bgMetadata, cfg.Capture, activeProjects, logger),
|
||||||
RetryMetadata: tools.NewRetryEnrichmentTool(enrichmentRetryer),
|
RetryMetadata: tools.NewRetryEnrichmentTool(enrichmentRetryer),
|
||||||
Maintenance: tools.NewMaintenanceTool(db),
|
//Maintenance: tools.NewMaintenanceTool(db),
|
||||||
Skills: tools.NewSkillsTool(db, activeProjects),
|
Skills: tools.NewSkillsTool(db, activeProjects),
|
||||||
ChatHistory: tools.NewChatHistoryTool(db, activeProjects),
|
ChatHistory: tools.NewChatHistoryTool(db, activeProjects),
|
||||||
Describe: tools.NewDescribeTool(db, mcpserver.BuildToolCatalog()),
|
Describe: tools.NewDescribeTool(db, mcpserver.BuildToolCatalog()),
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/resolvespec"
|
"github.com/bitechdev/ResolveSpec/pkg/resolvespec"
|
||||||
"github.com/uptrace/bunrouter"
|
"github.com/uptrace/bunrouter"
|
||||||
@@ -26,6 +27,21 @@ func registerResolveSpecAdminRoutes(mux *http.ServeMux, db *store.DB, middleware
|
|||||||
|
|
||||||
rsMount := http.StripPrefix("/api/rs", rsRouter)
|
rsMount := http.StripPrefix("/api/rs", rsRouter)
|
||||||
protectedRSMount := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
protectedRSMount := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/" && strings.HasSuffix(r.URL.Path, "/") {
|
||||||
|
trimmed := strings.TrimRight(r.URL.Path, "/")
|
||||||
|
if trimmed == "" {
|
||||||
|
trimmed = "/"
|
||||||
|
}
|
||||||
|
clone := r.Clone(r.Context())
|
||||||
|
clone.URL.Path = trimmed
|
||||||
|
if clone.URL.RawPath != "" {
|
||||||
|
clone.URL.RawPath = strings.TrimRight(clone.URL.RawPath, "/")
|
||||||
|
if clone.URL.RawPath == "" {
|
||||||
|
clone.URL.RawPath = "/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r = clone
|
||||||
|
}
|
||||||
if r.Method == http.MethodOptions {
|
if r.Method == http.MethodOptions {
|
||||||
rsMount.ServeHTTP(w, r)
|
rsMount.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
@@ -50,15 +66,36 @@ func registerResolveSpecGuards(rs *resolvespec.Handler) {
|
|||||||
mutableByEntity := map[string]map[string]struct{}{
|
mutableByEntity := map[string]map[string]struct{}{
|
||||||
"projects": {
|
"projects": {
|
||||||
"create": {},
|
"create": {},
|
||||||
|
"update": {},
|
||||||
|
"delete": {},
|
||||||
},
|
},
|
||||||
"thoughts": {
|
"thoughts": {
|
||||||
|
"create": {},
|
||||||
|
"update": {},
|
||||||
|
"delete": {},
|
||||||
|
},
|
||||||
|
"plans": {
|
||||||
|
"create": {},
|
||||||
|
"update": {},
|
||||||
|
"delete": {},
|
||||||
|
},
|
||||||
|
"learnings": {
|
||||||
|
"create": {},
|
||||||
"update": {},
|
"update": {},
|
||||||
"delete": {},
|
"delete": {},
|
||||||
},
|
},
|
||||||
"agent_skills": {
|
"agent_skills": {
|
||||||
|
"create": {},
|
||||||
|
"update": {},
|
||||||
"delete": {},
|
"delete": {},
|
||||||
},
|
},
|
||||||
"agent_guardrails": {
|
"agent_guardrails": {
|
||||||
|
"create": {},
|
||||||
|
"update": {},
|
||||||
|
"delete": {},
|
||||||
|
},
|
||||||
|
"stored_files": {
|
||||||
|
"update": {},
|
||||||
"delete": {},
|
"delete": {},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -98,33 +135,35 @@ type resolveSpecModel struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func resolveSpecModels() []resolveSpecModel {
|
func resolveSpecModels() []resolveSpecModel {
|
||||||
|
//This must be generated with relspec to include all models
|
||||||
|
//Use the relspec command with template generation. It supprot templ.
|
||||||
return []resolveSpecModel{
|
return []resolveSpecModel{
|
||||||
{schema: "public", entity: "activities", model: generatedmodels.ModelPublicActivities{}},
|
// {schema: "public", entity: "activities", model: generatedmodels.ModelPublicActivities{}},
|
||||||
{schema: "public", entity: "agent_guardrails", model: generatedmodels.ModelPublicAgentGuardrails{}},
|
{schema: "public", entity: "agent_guardrails", model: generatedmodels.ModelPublicAgentGuardrails{}},
|
||||||
{schema: "public", entity: "agent_skills", model: generatedmodels.ModelPublicAgentSkills{}},
|
{schema: "public", entity: "agent_skills", model: generatedmodels.ModelPublicAgentSkills{}},
|
||||||
{schema: "public", entity: "chat_histories", model: generatedmodels.ModelPublicChatHistories{}},
|
{schema: "public", entity: "chat_histories", model: generatedmodels.ModelPublicChatHistories{}},
|
||||||
{schema: "public", entity: "contact_interactions", model: generatedmodels.ModelPublicContactInteractions{}},
|
// {schema: "public", entity: "contact_interactions", model: generatedmodels.ModelPublicContactInteractions{}},
|
||||||
{schema: "public", entity: "embeddings", model: generatedmodels.ModelPublicEmbeddings{}},
|
{schema: "public", entity: "embeddings", model: generatedmodels.ModelPublicEmbeddings{}},
|
||||||
{schema: "public", entity: "family_members", model: generatedmodels.ModelPublicFamilyMembers{}},
|
// {schema: "public", entity: "family_members", model: generatedmodels.ModelPublicFamilyMembers{}},
|
||||||
{schema: "public", entity: "household_items", model: generatedmodels.ModelPublicHouseholdItems{}},
|
// {schema: "public", entity: "household_items", model: generatedmodels.ModelPublicHouseholdItems{}},
|
||||||
{schema: "public", entity: "household_vendors", model: generatedmodels.ModelPublicHouseholdVendors{}},
|
// {schema: "public", entity: "household_vendors", model: generatedmodels.ModelPublicHouseholdVendors{}},
|
||||||
{schema: "public", entity: "important_dates", model: generatedmodels.ModelPublicImportantDates{}},
|
// {schema: "public", entity: "important_dates", model: generatedmodels.ModelPublicImportantDates{}},
|
||||||
{schema: "public", entity: "learnings", model: generatedmodels.ModelPublicLearnings{}},
|
{schema: "public", entity: "learnings", model: generatedmodels.ModelPublicLearnings{}},
|
||||||
{schema: "public", entity: "maintenance_logs", model: generatedmodels.ModelPublicMaintenanceLogs{}},
|
// {schema: "public", entity: "maintenance_logs", model: generatedmodels.ModelPublicMaintenanceLogs{}},
|
||||||
{schema: "public", entity: "maintenance_tasks", model: generatedmodels.ModelPublicMaintenanceTasks{}},
|
// {schema: "public", entity: "maintenance_tasks", model: generatedmodels.ModelPublicMaintenanceTasks{}},
|
||||||
{schema: "public", entity: "meal_plans", model: generatedmodels.ModelPublicMealPlans{}},
|
// {schema: "public", entity: "meal_plans", model: generatedmodels.ModelPublicMealPlans{}},
|
||||||
{schema: "public", entity: "opportunities", model: generatedmodels.ModelPublicOpportunities{}},
|
// {schema: "public", entity: "opportunities", model: generatedmodels.ModelPublicOpportunities{}},
|
||||||
{schema: "public", entity: "plan_dependencies", model: generatedmodels.ModelPublicPlanDependencies{}},
|
{schema: "public", entity: "plan_dependencies", model: generatedmodels.ModelPublicPlanDependencies{}},
|
||||||
{schema: "public", entity: "plan_guardrails", model: generatedmodels.ModelPublicPlanGuardrails{}},
|
{schema: "public", entity: "plan_guardrails", model: generatedmodels.ModelPublicPlanGuardrails{}},
|
||||||
{schema: "public", entity: "plan_related_plans", model: generatedmodels.ModelPublicPlanRelatedPlans{}},
|
{schema: "public", entity: "plan_related_plans", model: generatedmodels.ModelPublicPlanRelatedPlans{}},
|
||||||
{schema: "public", entity: "plan_skills", model: generatedmodels.ModelPublicPlanSkills{}},
|
{schema: "public", entity: "plan_skills", model: generatedmodels.ModelPublicPlanSkills{}},
|
||||||
{schema: "public", entity: "plans", model: generatedmodels.ModelPublicPlans{}},
|
{schema: "public", entity: "plans", model: generatedmodels.ModelPublicPlans{}},
|
||||||
{schema: "public", entity: "professional_contacts", model: generatedmodels.ModelPublicProfessionalContacts{}},
|
// {schema: "public", entity: "professional_contacts", model: generatedmodels.ModelPublicProfessionalContacts{}},
|
||||||
{schema: "public", entity: "project_guardrails", model: generatedmodels.ModelPublicProjectGuardrails{}},
|
{schema: "public", entity: "project_guardrails", model: generatedmodels.ModelPublicProjectGuardrails{}},
|
||||||
{schema: "public", entity: "project_skills", model: generatedmodels.ModelPublicProjectSkills{}},
|
{schema: "public", entity: "project_skills", model: generatedmodels.ModelPublicProjectSkills{}},
|
||||||
{schema: "public", entity: "projects", model: generatedmodels.ModelPublicProjects{}},
|
{schema: "public", entity: "projects", model: generatedmodels.ModelPublicProjects{}},
|
||||||
{schema: "public", entity: "recipes", model: generatedmodels.ModelPublicRecipes{}},
|
// {schema: "public", entity: "recipes", model: generatedmodels.ModelPublicRecipes{}},
|
||||||
{schema: "public", entity: "shopping_lists", model: generatedmodels.ModelPublicShoppingLists{}},
|
// {schema: "public", entity: "shopping_lists", model: generatedmodels.ModelPublicShoppingLists{}},
|
||||||
{schema: "public", entity: "stored_files", model: generatedmodels.ModelPublicStoredFiles{}},
|
{schema: "public", entity: "stored_files", model: generatedmodels.ModelPublicStoredFiles{}},
|
||||||
{schema: "public", entity: "thought_links", model: generatedmodels.ModelPublicThoughtLinks{}},
|
{schema: "public", entity: "thought_links", model: generatedmodels.ModelPublicThoughtLinks{}},
|
||||||
{schema: "public", entity: "thoughts", model: generatedmodels.ModelPublicThoughts{}},
|
{schema: "public", entity: "thoughts", model: generatedmodels.ModelPublicThoughts{}},
|
||||||
|
|||||||
@@ -63,10 +63,25 @@ func TestResolveSpecGuardAllowsSupportedMutations(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{name: "learnings read", entity: "learnings", operation: "read"},
|
{name: "learnings read", entity: "learnings", operation: "read"},
|
||||||
{name: "projects create", entity: "projects", operation: "create"},
|
{name: "projects create", entity: "projects", operation: "create"},
|
||||||
|
{name: "projects update", entity: "projects", operation: "update"},
|
||||||
|
{name: "projects delete", entity: "projects", operation: "delete"},
|
||||||
|
{name: "plans create", entity: "plans", operation: "create"},
|
||||||
|
{name: "plans update", entity: "plans", operation: "update"},
|
||||||
|
{name: "plans delete", entity: "plans", operation: "delete"},
|
||||||
|
{name: "learnings create", entity: "learnings", operation: "create"},
|
||||||
|
{name: "learnings update", entity: "learnings", operation: "update"},
|
||||||
|
{name: "learnings delete", entity: "learnings", operation: "delete"},
|
||||||
|
{name: "thoughts create", entity: "thoughts", operation: "create"},
|
||||||
{name: "thoughts update", entity: "thoughts", operation: "update"},
|
{name: "thoughts update", entity: "thoughts", operation: "update"},
|
||||||
{name: "thoughts delete", entity: "thoughts", operation: "delete"},
|
{name: "thoughts delete", entity: "thoughts", operation: "delete"},
|
||||||
|
{name: "agent_skills create", entity: "agent_skills", operation: "create"},
|
||||||
|
{name: "agent_skills update", entity: "agent_skills", operation: "update"},
|
||||||
{name: "agent_skills delete", entity: "agent_skills", operation: "delete"},
|
{name: "agent_skills delete", entity: "agent_skills", operation: "delete"},
|
||||||
|
{name: "agent_guardrails create", entity: "agent_guardrails", operation: "create"},
|
||||||
|
{name: "agent_guardrails update", entity: "agent_guardrails", operation: "update"},
|
||||||
{name: "agent_guardrails delete", entity: "agent_guardrails", operation: "delete"},
|
{name: "agent_guardrails delete", entity: "agent_guardrails", operation: "delete"},
|
||||||
|
{name: "stored_files update", entity: "stored_files", operation: "update"},
|
||||||
|
{name: "stored_files delete", entity: "stored_files", operation: "delete"},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
@@ -100,32 +115,18 @@ func TestResolveSpecGuardBlocksUnsupportedMutations(t *testing.T) {
|
|||||||
wantMessageIn string
|
wantMessageIn string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "create not allowed on thoughts",
|
name: "mutations blocked for non-allowlisted operation",
|
||||||
entity: "thoughts",
|
entity: "stored_files",
|
||||||
operation: "create",
|
operation: "create",
|
||||||
wantCode: http.StatusForbidden,
|
wantCode: http.StatusForbidden,
|
||||||
wantMessageIn: `operation "create" is not allowed for public.thoughts`,
|
wantMessageIn: `operation "create" is not allowed for public.stored_files`,
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "delete not allowed on projects",
|
|
||||||
entity: "projects",
|
|
||||||
operation: "delete",
|
|
||||||
wantCode: http.StatusForbidden,
|
|
||||||
wantMessageIn: `operation "delete" is not allowed for public.projects`,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "mutations blocked for non-allowlisted entity",
|
name: "mutations blocked for non-allowlisted entity",
|
||||||
entity: "stored_files",
|
entity: "maintenance_logs",
|
||||||
operation: "delete",
|
operation: "delete",
|
||||||
wantCode: http.StatusForbidden,
|
wantCode: http.StatusForbidden,
|
||||||
wantMessageIn: `operation "delete" is not allowed for public.stored_files`,
|
wantMessageIn: `operation "delete" is not allowed for public.maintenance_logs`,
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "mutations blocked for learnings",
|
|
||||||
entity: "learnings",
|
|
||||||
operation: "delete",
|
|
||||||
wantCode: http.StatusForbidden,
|
|
||||||
wantMessageIn: `operation "delete" is not allowed for public.learnings`,
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "unknown operation is rejected",
|
name: "unknown operation is rejected",
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicActivities struct {
|
|
||||||
bun.BaseModel `bun:"table:public.activities,alias:activities"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
ActivityType resolvespec_common.SqlString `bun:"activity_type,type:text,nullzero," json:"activity_type"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
DayOfWeek resolvespec_common.SqlString `bun:"day_of_week,type:text,nullzero," json:"day_of_week"`
|
|
||||||
EndDate resolvespec_common.SqlDate `bun:"end_date,type:date,nullzero," json:"end_date"`
|
|
||||||
EndTime resolvespec_common.SqlTime `bun:"end_time,type:time,nullzero," json:"end_time"`
|
|
||||||
FamilyMemberID resolvespec_common.SqlUUID `bun:"family_member_id,type:uuid,nullzero," json:"family_member_id"`
|
|
||||||
Location resolvespec_common.SqlString `bun:"location,type:text,nullzero," json:"location"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
StartDate resolvespec_common.SqlDate `bun:"start_date,type:date,nullzero," json:"start_date"`
|
|
||||||
StartTime resolvespec_common.SqlTime `bun:"start_time,type:time,nullzero," json:"start_time"`
|
|
||||||
Title resolvespec_common.SqlString `bun:"title,type:text,notnull," json:"title"`
|
|
||||||
RelFamilyMemberID *ModelPublicFamilyMembers `bun:"rel:has-one,join:family_member_id=id" json:"relfamilymemberid,omitempty"` // Has one ModelPublicFamilyMembers
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicActivities
|
|
||||||
func (m ModelPublicActivities) TableName() string {
|
|
||||||
return "public.activities"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicActivities
|
|
||||||
func (m ModelPublicActivities) TableNameOnly() string {
|
|
||||||
return "activities"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicActivities
|
|
||||||
func (m ModelPublicActivities) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicActivities) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicActivities) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicActivities) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicActivities) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicActivities) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicActivities) GetPrefix() string {
|
|
||||||
return "ACT"
|
|
||||||
}
|
|
||||||
@@ -15,7 +15,7 @@ type ModelPublicAgentGuardrails struct {
|
|||||||
Description resolvespec_common.SqlString `bun:"description,type:text,default:'',notnull," json:"description"`
|
Description resolvespec_common.SqlString `bun:"description,type:text,default:'',notnull," json:"description"`
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
||||||
Severity resolvespec_common.SqlString `bun:"severity,type:text,default:'medium',notnull," json:"severity"`
|
Severity resolvespec_common.SqlString `bun:"severity,type:text,default:'medium',notnull," json:"severity"`
|
||||||
Tags resolvespec_common.SqlStringArray `bun:"tags,type:text,default:'{}',notnull," json:"tags"`
|
Tags resolvespec_common.SqlString `bun:"tags,type:text,nullzero," json:"tags"`
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
||||||
RelGuardrailIDPublicPlanGuardrails []*ModelPublicPlanGuardrails `bun:"rel:has-many,join:id=guardrail_id" json:"relguardrailidpublicplanguardrails,omitempty"` // Has many ModelPublicPlanGuardrails
|
RelGuardrailIDPublicPlanGuardrails []*ModelPublicPlanGuardrails `bun:"rel:has-many,join:id=guardrail_id" json:"relguardrailidpublicplanguardrails,omitempty"` // Has many ModelPublicPlanGuardrails
|
||||||
RelGuardrailIDPublicProjectGuardrails []*ModelPublicProjectGuardrails `bun:"rel:has-many,join:id=guardrail_id" json:"relguardrailidpublicprojectguardrails,omitempty"` // Has many ModelPublicProjectGuardrails
|
RelGuardrailIDPublicProjectGuardrails []*ModelPublicProjectGuardrails `bun:"rel:has-many,join:id=guardrail_id" json:"relguardrailidpublicprojectguardrails,omitempty"` // Has many ModelPublicProjectGuardrails
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ type ModelPublicAgentSkills struct {
|
|||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
||||||
Description resolvespec_common.SqlString `bun:"description,type:text,default:'',notnull," json:"description"`
|
Description resolvespec_common.SqlString `bun:"description,type:text,default:'',notnull," json:"description"`
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
||||||
Tags resolvespec_common.SqlStringArray `bun:"tags,type:text,default:'{}',notnull," json:"tags"`
|
Tags resolvespec_common.SqlString `bun:"tags,type:text,nullzero," json:"tags"`
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
||||||
RelRelatedSkillIDPublicLearnings []*ModelPublicLearnings `bun:"rel:has-many,join:id=related_skill_id" json:"relrelatedskillidpubliclearnings,omitempty"` // Has many ModelPublicLearnings
|
RelRelatedSkillIDPublicLearnings []*ModelPublicLearnings `bun:"rel:has-many,join:id=related_skill_id" json:"relrelatedskillidpubliclearnings,omitempty"` // Has many ModelPublicLearnings
|
||||||
RelSkillIDPublicPlanSkills []*ModelPublicPlanSkills `bun:"rel:has-many,join:id=skill_id" json:"relskillidpublicplanskills,omitempty"` // Has many ModelPublicPlanSkills
|
RelSkillIDPublicPlanSkills []*ModelPublicPlanSkills `bun:"rel:has-many,join:id=skill_id" json:"relskillidpublicplanskills,omitempty"` // Has many ModelPublicPlanSkills
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ type ModelPublicChatHistories struct {
|
|||||||
AgentID resolvespec_common.SqlString `bun:"agent_id,type:text,nullzero," json:"agent_id"`
|
AgentID resolvespec_common.SqlString `bun:"agent_id,type:text,nullzero," json:"agent_id"`
|
||||||
Channel resolvespec_common.SqlString `bun:"channel,type:text,nullzero," json:"channel"`
|
Channel resolvespec_common.SqlString `bun:"channel,type:text,nullzero," json:"channel"`
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
||||||
Messages resolvespec_common.SqlJSONB `bun:"messages,type:jsonb,default:'',notnull," json:"messages"`
|
Messages resolvespec_common.SqlJSONB `bun:"messages,type:jsonb,default:'[',notnull," json:"messages"`
|
||||||
Metadata resolvespec_common.SqlJSONB `bun:"metadata,type:jsonb,default:'{}',notnull," json:"metadata"`
|
Metadata resolvespec_common.SqlJSONB `bun:"metadata,type:jsonb,default:'{}',notnull," json:"metadata"`
|
||||||
ProjectID resolvespec_common.SqlUUID `bun:"project_id,type:uuid,nullzero," json:"project_id"`
|
ProjectID resolvespec_common.SqlUUID `bun:"project_id,type:uuid,nullzero," json:"project_id"`
|
||||||
SessionID resolvespec_common.SqlString `bun:"session_id,type:text,notnull," json:"session_id"`
|
SessionID resolvespec_common.SqlString `bun:"session_id,type:text,notnull," json:"session_id"`
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicContactInteractions struct {
|
|
||||||
bun.BaseModel `bun:"table:public.contact_interactions,alias:contact_interactions"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
ContactID resolvespec_common.SqlUUID `bun:"contact_id,type:uuid,notnull," json:"contact_id"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
FollowUpNeeded bool `bun:"follow_up_needed,type:boolean,default:false,notnull," json:"follow_up_needed"`
|
|
||||||
FollowUpNotes resolvespec_common.SqlString `bun:"follow_up_notes,type:text,nullzero," json:"follow_up_notes"`
|
|
||||||
InteractionType resolvespec_common.SqlString `bun:"interaction_type,type:text,notnull," json:"interaction_type"`
|
|
||||||
OccurredAt resolvespec_common.SqlTimeStamp `bun:"occurred_at,type:timestamptz,default:now(),notnull," json:"occurred_at"`
|
|
||||||
Summary resolvespec_common.SqlString `bun:"summary,type:text,notnull," json:"summary"`
|
|
||||||
RelContactID *ModelPublicProfessionalContacts `bun:"rel:has-one,join:contact_id=id" json:"relcontactid,omitempty"` // Has one ModelPublicProfessionalContacts
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicContactInteractions
|
|
||||||
func (m ModelPublicContactInteractions) TableName() string {
|
|
||||||
return "public.contact_interactions"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicContactInteractions
|
|
||||||
func (m ModelPublicContactInteractions) TableNameOnly() string {
|
|
||||||
return "contact_interactions"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicContactInteractions
|
|
||||||
func (m ModelPublicContactInteractions) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicContactInteractions) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicContactInteractions) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicContactInteractions) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicContactInteractions) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicContactInteractions) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicContactInteractions) GetPrefix() string {
|
|
||||||
return "CIO"
|
|
||||||
}
|
|
||||||
@@ -11,8 +11,8 @@ type ModelPublicEmbeddings struct {
|
|||||||
bun.BaseModel `bun:"table:public.embeddings,alias:embeddings"`
|
bun.BaseModel `bun:"table:public.embeddings,alias:embeddings"`
|
||||||
ID resolvespec_common.SqlInt64 `bun:"id,type:bigserial,pk,autoincrement," json:"id"`
|
ID resolvespec_common.SqlInt64 `bun:"id,type:bigserial,pk,autoincrement," json:"id"`
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),nullzero," json:"created_at"`
|
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),nullzero," json:"created_at"`
|
||||||
Dim int32 `bun:"dim,type:int,notnull," json:"dim"`
|
Dim resolvespec_common.SqlInt32 `bun:"dim,type:int,notnull," json:"dim"`
|
||||||
Embedding resolvespec_common.SqlVector `bun:"embedding,type:vector,notnull," json:"embedding"`
|
Embedding resolvespec_common.SqlString `bun:"embedding,type:vector,notnull," json:"embedding"`
|
||||||
GUID resolvespec_common.SqlUUID `bun:"guid,type:uuid,default:gen_random_uuid(),notnull," json:"guid"`
|
GUID resolvespec_common.SqlUUID `bun:"guid,type:uuid,default:gen_random_uuid(),notnull," json:"guid"`
|
||||||
Model resolvespec_common.SqlString `bun:"model,type:text,notnull,unique:uidx_embeddings_thought_id_model," json:"model"`
|
Model resolvespec_common.SqlString `bun:"model,type:text,notnull,unique:uidx_embeddings_thought_id_model," json:"model"`
|
||||||
ThoughtID resolvespec_common.SqlUUID `bun:"thought_id,type:uuid,notnull,unique:uidx_embeddings_thought_id_model," json:"thought_id"`
|
ThoughtID resolvespec_common.SqlUUID `bun:"thought_id,type:uuid,notnull,unique:uidx_embeddings_thought_id_model," json:"thought_id"`
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicFamilyMembers struct {
|
|
||||||
bun.BaseModel `bun:"table:public.family_members,alias:family_members"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
BirthDate resolvespec_common.SqlDate `bun:"birth_date,type:date,nullzero," json:"birth_date"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
Relationship resolvespec_common.SqlString `bun:"relationship,type:text,nullzero," json:"relationship"`
|
|
||||||
RelFamilyMemberIDPublicActivities []*ModelPublicActivities `bun:"rel:has-many,join:id=family_member_id" json:"relfamilymemberidpublicactivities,omitempty"` // Has many ModelPublicActivities
|
|
||||||
RelFamilyMemberIDPublicImportantDates []*ModelPublicImportantDates `bun:"rel:has-many,join:id=family_member_id" json:"relfamilymemberidpublicimportantdates,omitempty"` // Has many ModelPublicImportantDates
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicFamilyMembers
|
|
||||||
func (m ModelPublicFamilyMembers) TableName() string {
|
|
||||||
return "public.family_members"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicFamilyMembers
|
|
||||||
func (m ModelPublicFamilyMembers) TableNameOnly() string {
|
|
||||||
return "family_members"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicFamilyMembers
|
|
||||||
func (m ModelPublicFamilyMembers) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicFamilyMembers) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicFamilyMembers) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicFamilyMembers) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicFamilyMembers) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicFamilyMembers) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicFamilyMembers) GetPrefix() string {
|
|
||||||
return "FMA"
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicHouseholdItems struct {
|
|
||||||
bun.BaseModel `bun:"table:public.household_items,alias:household_items"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
Category resolvespec_common.SqlString `bun:"category,type:text,nullzero," json:"category"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Details resolvespec_common.SqlJSONB `bun:"details,type:jsonb,default:'{}',notnull," json:"details"`
|
|
||||||
Location resolvespec_common.SqlString `bun:"location,type:text,nullzero," json:"location"`
|
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicHouseholdItems
|
|
||||||
func (m ModelPublicHouseholdItems) TableName() string {
|
|
||||||
return "public.household_items"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicHouseholdItems
|
|
||||||
func (m ModelPublicHouseholdItems) TableNameOnly() string {
|
|
||||||
return "household_items"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicHouseholdItems
|
|
||||||
func (m ModelPublicHouseholdItems) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicHouseholdItems) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicHouseholdItems) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicHouseholdItems) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicHouseholdItems) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicHouseholdItems) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicHouseholdItems) GetPrefix() string {
|
|
||||||
return "HIO"
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicHouseholdVendors struct {
|
|
||||||
bun.BaseModel `bun:"table:public.household_vendors,alias:household_vendors"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Email resolvespec_common.SqlString `bun:"email,type:text,nullzero," json:"email"`
|
|
||||||
LastUsed resolvespec_common.SqlDate `bun:"last_used,type:date,nullzero," json:"last_used"`
|
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
Phone resolvespec_common.SqlString `bun:"phone,type:text,nullzero," json:"phone"`
|
|
||||||
Rating resolvespec_common.SqlInt32 `bun:"rating,type:int,nullzero," json:"rating"`
|
|
||||||
ServiceType resolvespec_common.SqlString `bun:"service_type,type:text,nullzero," json:"service_type"`
|
|
||||||
Website resolvespec_common.SqlString `bun:"website,type:text,nullzero," json:"website"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicHouseholdVendors
|
|
||||||
func (m ModelPublicHouseholdVendors) TableName() string {
|
|
||||||
return "public.household_vendors"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicHouseholdVendors
|
|
||||||
func (m ModelPublicHouseholdVendors) TableNameOnly() string {
|
|
||||||
return "household_vendors"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicHouseholdVendors
|
|
||||||
func (m ModelPublicHouseholdVendors) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicHouseholdVendors) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicHouseholdVendors) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicHouseholdVendors) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicHouseholdVendors) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicHouseholdVendors) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicHouseholdVendors) GetPrefix() string {
|
|
||||||
return "HVO"
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicImportantDates struct {
|
|
||||||
bun.BaseModel `bun:"table:public.important_dates,alias:important_dates"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
DateValue resolvespec_common.SqlDate `bun:"date_value,type:date,notnull," json:"date_value"`
|
|
||||||
FamilyMemberID resolvespec_common.SqlUUID `bun:"family_member_id,type:uuid,nullzero," json:"family_member_id"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
RecurringYearly bool `bun:"recurring_yearly,type:boolean,default:false,notnull," json:"recurring_yearly"`
|
|
||||||
ReminderDaysBefore int32 `bun:"reminder_days_before,type:int,default:7,notnull," json:"reminder_days_before"`
|
|
||||||
Title resolvespec_common.SqlString `bun:"title,type:text,notnull," json:"title"`
|
|
||||||
RelFamilyMemberID *ModelPublicFamilyMembers `bun:"rel:has-one,join:family_member_id=id" json:"relfamilymemberid,omitempty"` // Has one ModelPublicFamilyMembers
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicImportantDates
|
|
||||||
func (m ModelPublicImportantDates) TableName() string {
|
|
||||||
return "public.important_dates"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicImportantDates
|
|
||||||
func (m ModelPublicImportantDates) TableNameOnly() string {
|
|
||||||
return "important_dates"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicImportantDates
|
|
||||||
func (m ModelPublicImportantDates) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicImportantDates) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicImportantDates) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicImportantDates) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicImportantDates) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicImportantDates) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicImportantDates) GetPrefix() string {
|
|
||||||
return "IDM"
|
|
||||||
}
|
|
||||||
@@ -28,7 +28,7 @@ type ModelPublicLearnings struct {
|
|||||||
Status resolvespec_common.SqlString `bun:"status,type:text,default:'pending',notnull," json:"status"`
|
Status resolvespec_common.SqlString `bun:"status,type:text,default:'pending',notnull," json:"status"`
|
||||||
Summary resolvespec_common.SqlString `bun:"summary,type:text,notnull," json:"summary"`
|
Summary resolvespec_common.SqlString `bun:"summary,type:text,notnull," json:"summary"`
|
||||||
SupersedesLearningID resolvespec_common.SqlUUID `bun:"supersedes_learning_id,type:uuid,nullzero," json:"supersedes_learning_id"`
|
SupersedesLearningID resolvespec_common.SqlUUID `bun:"supersedes_learning_id,type:uuid,nullzero," json:"supersedes_learning_id"`
|
||||||
Tags resolvespec_common.SqlStringArray `bun:"tags,type:text,default:'{}',notnull," json:"tags"`
|
Tags resolvespec_common.SqlString `bun:"tags,type:text,nullzero," json:"tags"`
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
||||||
RelDuplicateOfLearningID *ModelPublicLearnings `bun:"rel:has-one,join:duplicate_of_learning_id=id" json:"relduplicateoflearningid,omitempty"` // Has one ModelPublicLearnings
|
RelDuplicateOfLearningID *ModelPublicLearnings `bun:"rel:has-one,join:duplicate_of_learning_id=id" json:"relduplicateoflearningid,omitempty"` // Has one ModelPublicLearnings
|
||||||
RelProjectID *ModelPublicProjects `bun:"rel:has-one,join:project_id=guid" json:"relprojectid,omitempty"` // Has one ModelPublicProjects
|
RelProjectID *ModelPublicProjects `bun:"rel:has-one,join:project_id=guid" json:"relprojectid,omitempty"` // Has one ModelPublicProjects
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicMaintenanceLogs struct {
|
|
||||||
bun.BaseModel `bun:"table:public.maintenance_logs,alias:maintenance_logs"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
CompletedAt resolvespec_common.SqlTimeStamp `bun:"completed_at,type:timestamptz,default:now(),notnull," json:"completed_at"`
|
|
||||||
Cost resolvespec_common.SqlFloat64 `bun:"cost,type:decimal(10,2),nullzero," json:"cost"`
|
|
||||||
NextAction resolvespec_common.SqlString `bun:"next_action,type:text,nullzero," json:"next_action"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
PerformedBy resolvespec_common.SqlString `bun:"performed_by,type:text,nullzero," json:"performed_by"`
|
|
||||||
TaskID resolvespec_common.SqlUUID `bun:"task_id,type:uuid,notnull," json:"task_id"`
|
|
||||||
RelTaskID *ModelPublicMaintenanceTasks `bun:"rel:has-one,join:task_id=id" json:"reltaskid,omitempty"` // Has one ModelPublicMaintenanceTasks
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicMaintenanceLogs
|
|
||||||
func (m ModelPublicMaintenanceLogs) TableName() string {
|
|
||||||
return "public.maintenance_logs"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicMaintenanceLogs
|
|
||||||
func (m ModelPublicMaintenanceLogs) TableNameOnly() string {
|
|
||||||
return "maintenance_logs"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicMaintenanceLogs
|
|
||||||
func (m ModelPublicMaintenanceLogs) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicMaintenanceLogs) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicMaintenanceLogs) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicMaintenanceLogs) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicMaintenanceLogs) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicMaintenanceLogs) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicMaintenanceLogs) GetPrefix() string {
|
|
||||||
return "MLA"
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicMaintenanceTasks struct {
|
|
||||||
bun.BaseModel `bun:"table:public.maintenance_tasks,alias:maintenance_tasks"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
Category resolvespec_common.SqlString `bun:"category,type:text,nullzero," json:"category"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
FrequencyDays resolvespec_common.SqlInt32 `bun:"frequency_days,type:int,nullzero," json:"frequency_days"`
|
|
||||||
LastCompleted resolvespec_common.SqlTimeStamp `bun:"last_completed,type:timestamptz,nullzero," json:"last_completed"`
|
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
|
||||||
NextDue resolvespec_common.SqlTimeStamp `bun:"next_due,type:timestamptz,nullzero," json:"next_due"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
Priority resolvespec_common.SqlString `bun:"priority,type:text,default:'medium',notnull," json:"priority"`
|
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
|
||||||
RelTaskIDPublicMaintenanceLogs []*ModelPublicMaintenanceLogs `bun:"rel:has-many,join:id=task_id" json:"reltaskidpublicmaintenancelogs,omitempty"` // Has many ModelPublicMaintenanceLogs
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicMaintenanceTasks
|
|
||||||
func (m ModelPublicMaintenanceTasks) TableName() string {
|
|
||||||
return "public.maintenance_tasks"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicMaintenanceTasks
|
|
||||||
func (m ModelPublicMaintenanceTasks) TableNameOnly() string {
|
|
||||||
return "maintenance_tasks"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicMaintenanceTasks
|
|
||||||
func (m ModelPublicMaintenanceTasks) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicMaintenanceTasks) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicMaintenanceTasks) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicMaintenanceTasks) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicMaintenanceTasks) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicMaintenanceTasks) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicMaintenanceTasks) GetPrefix() string {
|
|
||||||
return "MTA"
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicMealPlans struct {
|
|
||||||
bun.BaseModel `bun:"table:public.meal_plans,alias:meal_plans"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
CustomMeal resolvespec_common.SqlString `bun:"custom_meal,type:text,nullzero," json:"custom_meal"`
|
|
||||||
DayOfWeek resolvespec_common.SqlString `bun:"day_of_week,type:text,notnull," json:"day_of_week"`
|
|
||||||
MealType resolvespec_common.SqlString `bun:"meal_type,type:text,notnull," json:"meal_type"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
RecipeID resolvespec_common.SqlUUID `bun:"recipe_id,type:uuid,nullzero," json:"recipe_id"`
|
|
||||||
Servings resolvespec_common.SqlInt32 `bun:"servings,type:int,nullzero," json:"servings"`
|
|
||||||
WeekStart resolvespec_common.SqlDate `bun:"week_start,type:date,notnull," json:"week_start"`
|
|
||||||
RelRecipeID *ModelPublicRecipes `bun:"rel:has-one,join:recipe_id=id" json:"relrecipeid,omitempty"` // Has one ModelPublicRecipes
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicMealPlans
|
|
||||||
func (m ModelPublicMealPlans) TableName() string {
|
|
||||||
return "public.meal_plans"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicMealPlans
|
|
||||||
func (m ModelPublicMealPlans) TableNameOnly() string {
|
|
||||||
return "meal_plans"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicMealPlans
|
|
||||||
func (m ModelPublicMealPlans) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicMealPlans) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicMealPlans) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicMealPlans) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicMealPlans) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicMealPlans) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicMealPlans) GetPrefix() string {
|
|
||||||
return "MPE"
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicOpportunities struct {
|
|
||||||
bun.BaseModel `bun:"table:public.opportunities,alias:opportunities"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
ContactID resolvespec_common.SqlUUID `bun:"contact_id,type:uuid,nullzero," json:"contact_id"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Description resolvespec_common.SqlString `bun:"description,type:text,nullzero," json:"description"`
|
|
||||||
ExpectedCloseDate resolvespec_common.SqlDate `bun:"expected_close_date,type:date,nullzero," json:"expected_close_date"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
Stage resolvespec_common.SqlString `bun:"stage,type:text,default:'identified',notnull," json:"stage"`
|
|
||||||
Title resolvespec_common.SqlString `bun:"title,type:text,notnull," json:"title"`
|
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
|
||||||
Value resolvespec_common.SqlFloat64 `bun:"value,type:decimal(12,2),nullzero," json:"value"`
|
|
||||||
RelContactID *ModelPublicProfessionalContacts `bun:"rel:has-one,join:contact_id=id" json:"relcontactid,omitempty"` // Has one ModelPublicProfessionalContacts
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicOpportunities
|
|
||||||
func (m ModelPublicOpportunities) TableName() string {
|
|
||||||
return "public.opportunities"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicOpportunities
|
|
||||||
func (m ModelPublicOpportunities) TableNameOnly() string {
|
|
||||||
return "opportunities"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicOpportunities
|
|
||||||
func (m ModelPublicOpportunities) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicOpportunities) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicOpportunities) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicOpportunities) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicOpportunities) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicOpportunities) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicOpportunities) GetPrefix() string {
|
|
||||||
return "OPP"
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,7 @@ type ModelPublicPlans struct {
|
|||||||
ReviewedBy resolvespec_common.SqlString `bun:"reviewed_by,type:text,nullzero," json:"reviewed_by"`
|
ReviewedBy resolvespec_common.SqlString `bun:"reviewed_by,type:text,nullzero," json:"reviewed_by"`
|
||||||
Status resolvespec_common.SqlString `bun:"status,type:text,default:'draft',notnull," json:"status"` // draft, active, blocked, completed, cancelled, superseded
|
Status resolvespec_common.SqlString `bun:"status,type:text,default:'draft',notnull," json:"status"` // draft, active, blocked, completed, cancelled, superseded
|
||||||
SupersedesPlanID resolvespec_common.SqlUUID `bun:"supersedes_plan_id,type:uuid,nullzero," json:"supersedes_plan_id"`
|
SupersedesPlanID resolvespec_common.SqlUUID `bun:"supersedes_plan_id,type:uuid,nullzero," json:"supersedes_plan_id"`
|
||||||
Tags resolvespec_common.SqlStringArray `bun:"tags,type:text,default:'{}',notnull," json:"tags"`
|
Tags resolvespec_common.SqlString `bun:"tags,type:text,nullzero," json:"tags"`
|
||||||
Title resolvespec_common.SqlString `bun:"title,type:text,notnull," json:"title"`
|
Title resolvespec_common.SqlString `bun:"title,type:text,notnull," json:"title"`
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
||||||
RelProjectID *ModelPublicProjects `bun:"rel:has-one,join:project_id=guid" json:"relprojectid,omitempty"` // Has one ModelPublicProjects
|
RelProjectID *ModelPublicProjects `bun:"rel:has-one,join:project_id=guid" json:"relprojectid,omitempty"` // Has one ModelPublicProjects
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicProfessionalContacts struct {
|
|
||||||
bun.BaseModel `bun:"table:public.professional_contacts,alias:professional_contacts"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
Company resolvespec_common.SqlString `bun:"company,type:text,nullzero," json:"company"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Email resolvespec_common.SqlString `bun:"email,type:text,nullzero," json:"email"`
|
|
||||||
FollowUpDate resolvespec_common.SqlDate `bun:"follow_up_date,type:date,nullzero," json:"follow_up_date"`
|
|
||||||
HowWeMet resolvespec_common.SqlString `bun:"how_we_met,type:text,nullzero," json:"how_we_met"`
|
|
||||||
LastContacted resolvespec_common.SqlTimeStamp `bun:"last_contacted,type:timestamptz,nullzero," json:"last_contacted"`
|
|
||||||
LinkedinURL resolvespec_common.SqlString `bun:"linkedin_url,type:text,nullzero," json:"linkedin_url"`
|
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
Phone resolvespec_common.SqlString `bun:"phone,type:text,nullzero," json:"phone"`
|
|
||||||
Tags resolvespec_common.SqlStringArray `bun:"tags,type:text,default:'{}',notnull," json:"tags"`
|
|
||||||
Title resolvespec_common.SqlString `bun:"title,type:text,nullzero," json:"title"`
|
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
|
||||||
RelContactIDPublicContactInteractions []*ModelPublicContactInteractions `bun:"rel:has-many,join:id=contact_id" json:"relcontactidpubliccontactinteractions,omitempty"` // Has many ModelPublicContactInteractions
|
|
||||||
RelContactIDPublicOpportunities []*ModelPublicOpportunities `bun:"rel:has-many,join:id=contact_id" json:"relcontactidpublicopportunities,omitempty"` // Has many ModelPublicOpportunities
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicProfessionalContacts
|
|
||||||
func (m ModelPublicProfessionalContacts) TableName() string {
|
|
||||||
return "public.professional_contacts"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicProfessionalContacts
|
|
||||||
func (m ModelPublicProfessionalContacts) TableNameOnly() string {
|
|
||||||
return "professional_contacts"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicProfessionalContacts
|
|
||||||
func (m ModelPublicProfessionalContacts) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicProfessionalContacts) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicProfessionalContacts) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicProfessionalContacts) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicProfessionalContacts) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicProfessionalContacts) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicProfessionalContacts) GetPrefix() string {
|
|
||||||
return "PCR"
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicRecipes struct {
|
|
||||||
bun.BaseModel `bun:"table:public.recipes,alias:recipes"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
CookTimeMinutes resolvespec_common.SqlInt32 `bun:"cook_time_minutes,type:int,nullzero," json:"cook_time_minutes"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Cuisine resolvespec_common.SqlString `bun:"cuisine,type:text,nullzero," json:"cuisine"`
|
|
||||||
Ingredients resolvespec_common.SqlJSONB `bun:"ingredients,type:jsonb,default:'',notnull," json:"ingredients"`
|
|
||||||
Instructions resolvespec_common.SqlJSONB `bun:"instructions,type:jsonb,default:'',notnull," json:"instructions"`
|
|
||||||
Name resolvespec_common.SqlString `bun:"name,type:text,notnull," json:"name"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
PrepTimeMinutes resolvespec_common.SqlInt32 `bun:"prep_time_minutes,type:int,nullzero," json:"prep_time_minutes"`
|
|
||||||
Rating resolvespec_common.SqlInt32 `bun:"rating,type:int,nullzero," json:"rating"`
|
|
||||||
Servings resolvespec_common.SqlInt32 `bun:"servings,type:int,nullzero," json:"servings"`
|
|
||||||
Tags resolvespec_common.SqlStringArray `bun:"tags,type:text,default:'{}',notnull," json:"tags"`
|
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
|
||||||
RelRecipeIDPublicMealPlans []*ModelPublicMealPlans `bun:"rel:has-many,join:id=recipe_id" json:"relrecipeidpublicmealplans,omitempty"` // Has many ModelPublicMealPlans
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicRecipes
|
|
||||||
func (m ModelPublicRecipes) TableName() string {
|
|
||||||
return "public.recipes"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicRecipes
|
|
||||||
func (m ModelPublicRecipes) TableNameOnly() string {
|
|
||||||
return "recipes"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicRecipes
|
|
||||||
func (m ModelPublicRecipes) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicRecipes) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicRecipes) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicRecipes) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicRecipes) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicRecipes) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicRecipes) GetPrefix() string {
|
|
||||||
return "REC"
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
// Code generated by relspecgo. DO NOT EDIT.
|
|
||||||
package generatedmodels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
|
||||||
"github.com/uptrace/bun"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ModelPublicShoppingLists struct {
|
|
||||||
bun.BaseModel `bun:"table:public.shopping_lists,alias:shopping_lists"`
|
|
||||||
ID resolvespec_common.SqlUUID `bun:"id,type:uuid,pk,default:gen_random_uuid()," json:"id"`
|
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),notnull," json:"created_at"`
|
|
||||||
Items resolvespec_common.SqlJSONB `bun:"items,type:jsonb,default:'',notnull," json:"items"`
|
|
||||||
Notes resolvespec_common.SqlString `bun:"notes,type:text,nullzero," json:"notes"`
|
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),notnull," json:"updated_at"`
|
|
||||||
WeekStart resolvespec_common.SqlDate `bun:"week_start,type:date,notnull," json:"week_start"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableName returns the table name for ModelPublicShoppingLists
|
|
||||||
func (m ModelPublicShoppingLists) TableName() string {
|
|
||||||
return "public.shopping_lists"
|
|
||||||
}
|
|
||||||
|
|
||||||
// TableNameOnly returns the table name without schema for ModelPublicShoppingLists
|
|
||||||
func (m ModelPublicShoppingLists) TableNameOnly() string {
|
|
||||||
return "shopping_lists"
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaName returns the schema name for ModelPublicShoppingLists
|
|
||||||
func (m ModelPublicShoppingLists) SchemaName() string {
|
|
||||||
return "public"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the primary key value
|
|
||||||
func (m ModelPublicShoppingLists) GetID() int64 {
|
|
||||||
return m.ID.Int64()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDStr returns the primary key as a string
|
|
||||||
func (m ModelPublicShoppingLists) GetIDStr() string {
|
|
||||||
return fmt.Sprintf("%v", m.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetID sets the primary key value
|
|
||||||
func (m ModelPublicShoppingLists) SetID(newid int64) {
|
|
||||||
m.UpdateID(newid)
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateID updates the primary key value
|
|
||||||
func (m *ModelPublicShoppingLists) UpdateID(newid int64) {
|
|
||||||
m.ID.FromString(fmt.Sprintf("%d", newid))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIDName returns the name of the primary key column
|
|
||||||
func (m ModelPublicShoppingLists) GetIDName() string {
|
|
||||||
return "id"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetPrefix returns the table prefix
|
|
||||||
func (m ModelPublicShoppingLists) GetPrefix() string {
|
|
||||||
return "SLH"
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ type ModelPublicThoughts struct {
|
|||||||
Content resolvespec_common.SqlString `bun:"content,type:text,notnull," json:"content"`
|
Content resolvespec_common.SqlString `bun:"content,type:text,notnull," json:"content"`
|
||||||
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),nullzero," json:"created_at"`
|
CreatedAt resolvespec_common.SqlTimeStamp `bun:"created_at,type:timestamptz,default:now(),nullzero," json:"created_at"`
|
||||||
GUID resolvespec_common.SqlUUID `bun:"guid,type:uuid,default:gen_random_uuid(),notnull," json:"guid"`
|
GUID resolvespec_common.SqlUUID `bun:"guid,type:uuid,default:gen_random_uuid(),notnull," json:"guid"`
|
||||||
Metadata resolvespec_common.SqlJSONB `bun:"metadata,type:jsonb,default:{}::jsonb,nullzero," json:"metadata"`
|
Metadata resolvespec_common.SqlJSONB `bun:"metadata,type:jsonb,default:'{}::jsonb',nullzero," json:"metadata"`
|
||||||
ProjectID resolvespec_common.SqlUUID `bun:"project_id,type:uuid,nullzero," json:"project_id"`
|
ProjectID resolvespec_common.SqlUUID `bun:"project_id,type:uuid,nullzero," json:"project_id"`
|
||||||
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),nullzero," json:"updated_at"`
|
UpdatedAt resolvespec_common.SqlTimeStamp `bun:"updated_at,type:timestamptz,default:now(),nullzero," json:"updated_at"`
|
||||||
RelProjectID *ModelPublicProjects `bun:"rel:has-one,join:project_id=guid" json:"relprojectid,omitempty"` // Has one ModelPublicProjects
|
RelProjectID *ModelPublicProjects `bun:"rel:has-one,join:project_id=guid" json:"relprojectid,omitempty"` // Has one ModelPublicProjects
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ type ToolSet struct {
|
|||||||
Backfill *tools.BackfillTool
|
Backfill *tools.BackfillTool
|
||||||
Reparse *tools.ReparseMetadataTool
|
Reparse *tools.ReparseMetadataTool
|
||||||
RetryMetadata *tools.RetryEnrichmentTool
|
RetryMetadata *tools.RetryEnrichmentTool
|
||||||
Maintenance *tools.MaintenanceTool
|
//Maintenance *tools.MaintenanceTool
|
||||||
Skills *tools.SkillsTool
|
Skills *tools.SkillsTool
|
||||||
ChatHistory *tools.ChatHistoryTool
|
ChatHistory *tools.ChatHistoryTool
|
||||||
Describe *tools.DescribeTool
|
Describe *tools.DescribeTool
|
||||||
@@ -422,30 +422,30 @@ func registerMaintenanceTools(server *mcp.Server, logger *slog.Logger, toolSet T
|
|||||||
}, toolSet.RetryMetadata.Handle); err != nil {
|
}, toolSet.RetryMetadata.Handle); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := addTool(server, logger, &mcp.Tool{
|
// if err := addTool(server, logger, &mcp.Tool{
|
||||||
Name: "add_maintenance_task",
|
// Name: "add_maintenance_task",
|
||||||
Description: "Create a recurring or one-time home maintenance task.",
|
// Description: "Create a recurring or one-time home maintenance task.",
|
||||||
}, toolSet.Maintenance.AddTask); err != nil {
|
// }, toolSet.Maintenance.AddTask); err != nil {
|
||||||
return err
|
// return err
|
||||||
}
|
// }
|
||||||
if err := addTool(server, logger, &mcp.Tool{
|
// if err := addTool(server, logger, &mcp.Tool{
|
||||||
Name: "log_maintenance",
|
// Name: "log_maintenance",
|
||||||
Description: "Log completed maintenance; updates next due date.",
|
// Description: "Log completed maintenance; updates next due date.",
|
||||||
}, toolSet.Maintenance.LogWork); err != nil {
|
// }, toolSet.Maintenance.LogWork); err != nil {
|
||||||
return err
|
// return err
|
||||||
}
|
// }
|
||||||
if err := addTool(server, logger, &mcp.Tool{
|
// if err := addTool(server, logger, &mcp.Tool{
|
||||||
Name: "get_upcoming_maintenance",
|
// Name: "get_upcoming_maintenance",
|
||||||
Description: "List maintenance tasks due within the next N days.",
|
// Description: "List maintenance tasks due within the next N days.",
|
||||||
}, toolSet.Maintenance.GetUpcoming); err != nil {
|
// }, toolSet.Maintenance.GetUpcoming); err != nil {
|
||||||
return err
|
// return err
|
||||||
}
|
// }
|
||||||
if err := addTool(server, logger, &mcp.Tool{
|
// if err := addTool(server, logger, &mcp.Tool{
|
||||||
Name: "search_maintenance_history",
|
// Name: "search_maintenance_history",
|
||||||
Description: "Search the maintenance log by task name, category, or date range.",
|
// Description: "Search the maintenance log by task name, category, or date range.",
|
||||||
}, toolSet.Maintenance.SearchHistory); err != nil {
|
// }, toolSet.Maintenance.SearchHistory); err != nil {
|
||||||
return err
|
// return err
|
||||||
}
|
// }
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -207,7 +207,7 @@ func streamableTestToolSet() ToolSet {
|
|||||||
Backfill: new(tools.BackfillTool),
|
Backfill: new(tools.BackfillTool),
|
||||||
Reparse: new(tools.ReparseMetadataTool),
|
Reparse: new(tools.ReparseMetadataTool),
|
||||||
RetryMetadata: new(tools.RetryEnrichmentTool),
|
RetryMetadata: new(tools.RetryEnrichmentTool),
|
||||||
Maintenance: new(tools.MaintenanceTool),
|
//Maintenance: new(tools.MaintenanceTool),
|
||||||
Skills: new(tools.SkillsTool),
|
Skills: new(tools.SkillsTool),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,206 +1,206 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"fmt"
|
// "fmt"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
// "git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
func (db *DB) AddFamilyMember(ctx context.Context, m ext.FamilyMember) (ext.FamilyMember, error) {
|
// func (db *DB) AddFamilyMember(ctx context.Context, m ext.FamilyMember) (ext.FamilyMember, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into family_members (name, relationship, birth_date, notes)
|
// insert into family_members (name, relationship, birth_date, notes)
|
||||||
values ($1, $2, $3, $4)
|
// values ($1, $2, $3, $4)
|
||||||
returning id, created_at
|
// returning id, created_at
|
||||||
`, m.Name, nullStr(m.Relationship), m.BirthDate, nullStr(m.Notes))
|
// `, m.Name, nullStr(m.Relationship), m.BirthDate, nullStr(m.Notes))
|
||||||
|
|
||||||
created := m
|
// created := m
|
||||||
var model generatedmodels.ModelPublicFamilyMembers
|
// var model generatedmodels.ModelPublicFamilyMembers
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
||||||
return ext.FamilyMember{}, fmt.Errorf("insert family member: %w", err)
|
// return ext.FamilyMember{}, fmt.Errorf("insert family member: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) ListFamilyMembers(ctx context.Context) ([]ext.FamilyMember, error) {
|
// func (db *DB) ListFamilyMembers(ctx context.Context) ([]ext.FamilyMember, error) {
|
||||||
rows, err := db.pool.Query(ctx, `select id, name, relationship, birth_date, notes, created_at from family_members order by name`)
|
// rows, err := db.pool.Query(ctx, `select id, name, relationship, birth_date, notes, created_at from family_members order by name`)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("list family members: %w", err)
|
// return nil, fmt.Errorf("list family members: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var members []ext.FamilyMember
|
// var members []ext.FamilyMember
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicFamilyMembers
|
// var model generatedmodels.ModelPublicFamilyMembers
|
||||||
if err := rows.Scan(&model.ID, &model.Name, &model.Relationship, &model.BirthDate, &model.Notes, &model.CreatedAt); err != nil {
|
// if err := rows.Scan(&model.ID, &model.Name, &model.Relationship, &model.BirthDate, &model.Notes, &model.CreatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan family member: %w", err)
|
// return nil, fmt.Errorf("scan family member: %w", err)
|
||||||
}
|
// }
|
||||||
members = append(members, familyMemberFromModel(model))
|
// members = append(members, familyMemberFromModel(model))
|
||||||
}
|
// }
|
||||||
return members, rows.Err()
|
// return members, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) AddActivity(ctx context.Context, a ext.Activity) (ext.Activity, error) {
|
// func (db *DB) AddActivity(ctx context.Context, a ext.Activity) (ext.Activity, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into activities (family_member_id, title, activity_type, day_of_week, start_time, end_time, start_date, end_date, location, notes)
|
// insert into activities (family_member_id, title, activity_type, day_of_week, start_time, end_time, start_date, end_date, location, notes)
|
||||||
values ($1, $2, $3, $4, $5::time, $6::time, $7, $8, $9, $10)
|
// values ($1, $2, $3, $4, $5::time, $6::time, $7, $8, $9, $10)
|
||||||
returning id, created_at
|
// returning id, created_at
|
||||||
`, a.FamilyMemberID, a.Title, nullStr(a.ActivityType), nullStr(a.DayOfWeek),
|
// `, a.FamilyMemberID, a.Title, nullStr(a.ActivityType), nullStr(a.DayOfWeek),
|
||||||
nullStr(a.StartTime), nullStr(a.EndTime), a.StartDate, a.EndDate,
|
// nullStr(a.StartTime), nullStr(a.EndTime), a.StartDate, a.EndDate,
|
||||||
nullStr(a.Location), nullStr(a.Notes))
|
// nullStr(a.Location), nullStr(a.Notes))
|
||||||
|
|
||||||
created := a
|
// created := a
|
||||||
var model generatedmodels.ModelPublicActivities
|
// var model generatedmodels.ModelPublicActivities
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
||||||
return ext.Activity{}, fmt.Errorf("insert activity: %w", err)
|
// return ext.Activity{}, fmt.Errorf("insert activity: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetWeekSchedule(ctx context.Context, weekStart time.Time) ([]ext.Activity, error) {
|
// func (db *DB) GetWeekSchedule(ctx context.Context, weekStart time.Time) ([]ext.Activity, error) {
|
||||||
weekEnd := weekStart.AddDate(0, 0, 7)
|
// weekEnd := weekStart.AddDate(0, 0, 7)
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, `
|
// rows, err := db.pool.Query(ctx, `
|
||||||
select a.id, a.family_member_id, fm.name, a.title, a.activity_type,
|
// select a.id, a.family_member_id, fm.name, a.title, a.activity_type,
|
||||||
a.day_of_week, a.start_time::text, a.end_time::text,
|
// a.day_of_week, a.start_time::text, a.end_time::text,
|
||||||
a.start_date, a.end_date, a.location, a.notes, a.created_at
|
// a.start_date, a.end_date, a.location, a.notes, a.created_at
|
||||||
from activities a
|
// from activities a
|
||||||
left join family_members fm on fm.id = a.family_member_id
|
// left join family_members fm on fm.id = a.family_member_id
|
||||||
where (a.start_date >= $1 and a.start_date < $2)
|
// where (a.start_date >= $1 and a.start_date < $2)
|
||||||
or (a.day_of_week is not null and (a.end_date is null or a.end_date >= $1))
|
// or (a.day_of_week is not null and (a.end_date is null or a.end_date >= $1))
|
||||||
order by a.start_date, a.start_time
|
// order by a.start_date, a.start_time
|
||||||
`, weekStart, weekEnd)
|
// `, weekStart, weekEnd)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("get week schedule: %w", err)
|
// return nil, fmt.Errorf("get week schedule: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
return scanActivities(rows)
|
// return scanActivities(rows)
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) SearchActivities(ctx context.Context, query, activityType string, memberID *uuid.UUID) ([]ext.Activity, error) {
|
// func (db *DB) SearchActivities(ctx context.Context, query, activityType string, memberID *uuid.UUID) ([]ext.Activity, error) {
|
||||||
args := []any{}
|
// args := []any{}
|
||||||
conditions := []string{}
|
// conditions := []string{}
|
||||||
|
|
||||||
if q := strings.TrimSpace(query); q != "" {
|
// if q := strings.TrimSpace(query); q != "" {
|
||||||
args = append(args, "%"+q+"%")
|
// args = append(args, "%"+q+"%")
|
||||||
conditions = append(conditions, fmt.Sprintf("(a.title ILIKE $%d OR a.notes ILIKE $%d)", len(args), len(args)))
|
// conditions = append(conditions, fmt.Sprintf("(a.title ILIKE $%d OR a.notes ILIKE $%d)", len(args), len(args)))
|
||||||
}
|
// }
|
||||||
if t := strings.TrimSpace(activityType); t != "" {
|
// if t := strings.TrimSpace(activityType); t != "" {
|
||||||
args = append(args, t)
|
// args = append(args, t)
|
||||||
conditions = append(conditions, fmt.Sprintf("a.activity_type = $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("a.activity_type = $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if memberID != nil {
|
// if memberID != nil {
|
||||||
args = append(args, *memberID)
|
// args = append(args, *memberID)
|
||||||
conditions = append(conditions, fmt.Sprintf("a.family_member_id = $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("a.family_member_id = $%d", len(args)))
|
||||||
}
|
// }
|
||||||
|
|
||||||
q := `
|
// q := `
|
||||||
select a.id, a.family_member_id, fm.name, a.title, a.activity_type,
|
// select a.id, a.family_member_id, fm.name, a.title, a.activity_type,
|
||||||
a.day_of_week, a.start_time::text, a.end_time::text,
|
// a.day_of_week, a.start_time::text, a.end_time::text,
|
||||||
a.start_date, a.end_date, a.location, a.notes, a.created_at
|
// a.start_date, a.end_date, a.location, a.notes, a.created_at
|
||||||
from activities a
|
// from activities a
|
||||||
left join family_members fm on fm.id = a.family_member_id
|
// left join family_members fm on fm.id = a.family_member_id
|
||||||
`
|
// `
|
||||||
if len(conditions) > 0 {
|
// if len(conditions) > 0 {
|
||||||
q += " where " + strings.Join(conditions, " and ")
|
// q += " where " + strings.Join(conditions, " and ")
|
||||||
}
|
// }
|
||||||
q += " order by a.start_date, a.start_time"
|
// q += " order by a.start_date, a.start_time"
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, q, args...)
|
// rows, err := db.pool.Query(ctx, q, args...)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("search activities: %w", err)
|
// return nil, fmt.Errorf("search activities: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
return scanActivities(rows)
|
// return scanActivities(rows)
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) AddImportantDate(ctx context.Context, d ext.ImportantDate) (ext.ImportantDate, error) {
|
// func (db *DB) AddImportantDate(ctx context.Context, d ext.ImportantDate) (ext.ImportantDate, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into important_dates (family_member_id, title, date_value, recurring_yearly, reminder_days_before, notes)
|
// insert into important_dates (family_member_id, title, date_value, recurring_yearly, reminder_days_before, notes)
|
||||||
values ($1, $2, $3, $4, $5, $6)
|
// values ($1, $2, $3, $4, $5, $6)
|
||||||
returning id, created_at
|
// returning id, created_at
|
||||||
`, d.FamilyMemberID, d.Title, d.DateValue, d.RecurringYearly, d.ReminderDaysBefore, nullStr(d.Notes))
|
// `, d.FamilyMemberID, d.Title, d.DateValue, d.RecurringYearly, d.ReminderDaysBefore, nullStr(d.Notes))
|
||||||
|
|
||||||
created := d
|
// created := d
|
||||||
var model generatedmodels.ModelPublicImportantDates
|
// var model generatedmodels.ModelPublicImportantDates
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
||||||
return ext.ImportantDate{}, fmt.Errorf("insert important date: %w", err)
|
// return ext.ImportantDate{}, fmt.Errorf("insert important date: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetUpcomingDates(ctx context.Context, daysAhead int) ([]ext.ImportantDate, error) {
|
// func (db *DB) GetUpcomingDates(ctx context.Context, daysAhead int) ([]ext.ImportantDate, error) {
|
||||||
if daysAhead <= 0 {
|
// if daysAhead <= 0 {
|
||||||
daysAhead = 30
|
// daysAhead = 30
|
||||||
}
|
// }
|
||||||
now := time.Now()
|
// now := time.Now()
|
||||||
cutoff := now.AddDate(0, 0, daysAhead)
|
// cutoff := now.AddDate(0, 0, daysAhead)
|
||||||
|
|
||||||
// For yearly recurring events, check if this year's occurrence falls in range
|
// // For yearly recurring events, check if this year's occurrence falls in range
|
||||||
rows, err := db.pool.Query(ctx, `
|
// rows, err := db.pool.Query(ctx, `
|
||||||
select d.id, d.family_member_id, fm.name, d.title, d.date_value,
|
// select d.id, d.family_member_id, fm.name, d.title, d.date_value,
|
||||||
d.recurring_yearly, d.reminder_days_before, d.notes, d.created_at
|
// d.recurring_yearly, d.reminder_days_before, d.notes, d.created_at
|
||||||
from important_dates d
|
// from important_dates d
|
||||||
left join family_members fm on fm.id = d.family_member_id
|
// left join family_members fm on fm.id = d.family_member_id
|
||||||
where (
|
// where (
|
||||||
(d.recurring_yearly = false and d.date_value between $1 and $2)
|
// (d.recurring_yearly = false and d.date_value between $1 and $2)
|
||||||
or
|
// or
|
||||||
(d.recurring_yearly = true and
|
// (d.recurring_yearly = true and
|
||||||
make_date(extract(year from now())::int, extract(month from d.date_value)::int, extract(day from d.date_value)::int)
|
// make_date(extract(year from now())::int, extract(month from d.date_value)::int, extract(day from d.date_value)::int)
|
||||||
between $1 and $2)
|
// between $1 and $2)
|
||||||
)
|
// )
|
||||||
order by d.date_value
|
// order by d.date_value
|
||||||
`, now, cutoff)
|
// `, now, cutoff)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("get upcoming dates: %w", err)
|
// return nil, fmt.Errorf("get upcoming dates: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var dates []ext.ImportantDate
|
// var dates []ext.ImportantDate
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicImportantDates
|
// var model generatedmodels.ModelPublicImportantDates
|
||||||
var memberName *string
|
// var memberName *string
|
||||||
if err := rows.Scan(&model.ID, &model.FamilyMemberID, &memberName, &model.Title, &model.DateValue,
|
// if err := rows.Scan(&model.ID, &model.FamilyMemberID, &memberName, &model.Title, &model.DateValue,
|
||||||
&model.RecurringYearly, &model.ReminderDaysBefore, &model.Notes, &model.CreatedAt); err != nil {
|
// &model.RecurringYearly, &model.ReminderDaysBefore, &model.Notes, &model.CreatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan important date: %w", err)
|
// return nil, fmt.Errorf("scan important date: %w", err)
|
||||||
}
|
// }
|
||||||
dates = append(dates, importantDateFromModel(model, strVal(memberName)))
|
// dates = append(dates, importantDateFromModel(model, strVal(memberName)))
|
||||||
}
|
// }
|
||||||
return dates, rows.Err()
|
// return dates, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|
||||||
func scanActivities(rows interface {
|
// func scanActivities(rows interface {
|
||||||
Next() bool
|
// Next() bool
|
||||||
Scan(...any) error
|
// Scan(...any) error
|
||||||
Err() error
|
// Err() error
|
||||||
Close()
|
// Close()
|
||||||
}) ([]ext.Activity, error) {
|
// }) ([]ext.Activity, error) {
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
var activities []ext.Activity
|
// var activities []ext.Activity
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicActivities
|
// var model generatedmodels.ModelPublicActivities
|
||||||
var memberName *string
|
// var memberName *string
|
||||||
if err := rows.Scan(
|
// if err := rows.Scan(
|
||||||
&model.ID, &model.FamilyMemberID, &memberName, &model.Title, &model.ActivityType,
|
// &model.ID, &model.FamilyMemberID, &memberName, &model.Title, &model.ActivityType,
|
||||||
&model.DayOfWeek, &model.StartTime, &model.EndTime,
|
// &model.DayOfWeek, &model.StartTime, &model.EndTime,
|
||||||
&model.StartDate, &model.EndDate, &model.Location, &model.Notes, &model.CreatedAt,
|
// &model.StartDate, &model.EndDate, &model.Location, &model.Notes, &model.CreatedAt,
|
||||||
); err != nil {
|
// ); err != nil {
|
||||||
return nil, fmt.Errorf("scan activity: %w", err)
|
// return nil, fmt.Errorf("scan activity: %w", err)
|
||||||
}
|
// }
|
||||||
activities = append(activities, activityFromModel(model, strVal(memberName)))
|
// activities = append(activities, activityFromModel(model, strVal(memberName)))
|
||||||
}
|
// }
|
||||||
return activities, rows.Err()
|
// return activities, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,235 +1,235 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"fmt"
|
// "fmt"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
// "git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
func (db *DB) AddProfessionalContact(ctx context.Context, c ext.ProfessionalContact) (ext.ProfessionalContact, error) {
|
// func (db *DB) AddProfessionalContact(ctx context.Context, c ext.ProfessionalContact) (ext.ProfessionalContact, error) {
|
||||||
if c.Tags == nil {
|
// if c.Tags == nil {
|
||||||
c.Tags = []string{}
|
// c.Tags = []string{}
|
||||||
}
|
// }
|
||||||
|
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into professional_contacts (name, company, title, email, phone, linkedin_url, how_we_met, tags, notes, follow_up_date)
|
// insert into professional_contacts (name, company, title, email, phone, linkedin_url, how_we_met, tags, notes, follow_up_date)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
// values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
returning id, created_at, updated_at
|
// returning id, created_at, updated_at
|
||||||
`, c.Name, nullStr(c.Company), nullStr(c.Title), nullStr(c.Email), nullStr(c.Phone),
|
// `, c.Name, nullStr(c.Company), nullStr(c.Title), nullStr(c.Email), nullStr(c.Phone),
|
||||||
nullStr(c.LinkedInURL), nullStr(c.HowWeMet), c.Tags, nullStr(c.Notes), c.FollowUpDate)
|
// nullStr(c.LinkedInURL), nullStr(c.HowWeMet), c.Tags, nullStr(c.Notes), c.FollowUpDate)
|
||||||
|
|
||||||
created := c
|
// created := c
|
||||||
var model generatedmodels.ModelPublicProfessionalContacts
|
// var model generatedmodels.ModelPublicProfessionalContacts
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.ProfessionalContact{}, fmt.Errorf("insert contact: %w", err)
|
// return ext.ProfessionalContact{}, fmt.Errorf("insert contact: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
created.UpdatedAt = model.UpdatedAt.Time()
|
// created.UpdatedAt = model.UpdatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) SearchContacts(ctx context.Context, query string, tags []string) ([]ext.ProfessionalContact, error) {
|
// func (db *DB) SearchContacts(ctx context.Context, query string, tags []string) ([]ext.ProfessionalContact, error) {
|
||||||
args := []any{}
|
// args := []any{}
|
||||||
conditions := []string{}
|
// conditions := []string{}
|
||||||
|
|
||||||
if q := strings.TrimSpace(query); q != "" {
|
// if q := strings.TrimSpace(query); q != "" {
|
||||||
args = append(args, "%"+q+"%")
|
// args = append(args, "%"+q+"%")
|
||||||
idx := len(args)
|
// idx := len(args)
|
||||||
conditions = append(conditions, fmt.Sprintf(
|
// conditions = append(conditions, fmt.Sprintf(
|
||||||
"(name ILIKE $%[1]d OR company ILIKE $%[1]d OR title ILIKE $%[1]d OR notes ILIKE $%[1]d)", idx))
|
// "(name ILIKE $%[1]d OR company ILIKE $%[1]d OR title ILIKE $%[1]d OR notes ILIKE $%[1]d)", idx))
|
||||||
}
|
// }
|
||||||
if len(tags) > 0 {
|
// if len(tags) > 0 {
|
||||||
args = append(args, tags)
|
// args = append(args, tags)
|
||||||
conditions = append(conditions, fmt.Sprintf("tags @> $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("tags @> $%d", len(args)))
|
||||||
}
|
// }
|
||||||
|
|
||||||
q := `select id, name, company, title, email, phone, linkedin_url, how_we_met, tags::text[], notes, last_contacted, follow_up_date, created_at, updated_at from professional_contacts`
|
// q := `select id, name, company, title, email, phone, linkedin_url, how_we_met, tags::text[], notes, last_contacted, follow_up_date, created_at, updated_at from professional_contacts`
|
||||||
if len(conditions) > 0 {
|
// if len(conditions) > 0 {
|
||||||
q += " where " + strings.Join(conditions, " and ")
|
// q += " where " + strings.Join(conditions, " and ")
|
||||||
}
|
// }
|
||||||
q += " order by name"
|
// q += " order by name"
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, q, args...)
|
// rows, err := db.pool.Query(ctx, q, args...)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("search contacts: %w", err)
|
// return nil, fmt.Errorf("search contacts: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
return scanContacts(rows)
|
// return scanContacts(rows)
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetContact(ctx context.Context, id uuid.UUID) (ext.ProfessionalContact, error) {
|
// func (db *DB) GetContact(ctx context.Context, id uuid.UUID) (ext.ProfessionalContact, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
select id, name, company, title, email, phone, linkedin_url, how_we_met, tags::text[], notes, last_contacted, follow_up_date, created_at, updated_at
|
// select id, name, company, title, email, phone, linkedin_url, how_we_met, tags::text[], notes, last_contacted, follow_up_date, created_at, updated_at
|
||||||
from professional_contacts where id = $1
|
// from professional_contacts where id = $1
|
||||||
`, id)
|
// `, id)
|
||||||
|
|
||||||
var model generatedmodels.ModelPublicProfessionalContacts
|
// var model generatedmodels.ModelPublicProfessionalContacts
|
||||||
var tags []string
|
// var tags []string
|
||||||
if err := row.Scan(&model.ID, &model.Name, &model.Company, &model.Title, &model.Email, &model.Phone,
|
// if err := row.Scan(&model.ID, &model.Name, &model.Company, &model.Title, &model.Email, &model.Phone,
|
||||||
&model.LinkedinURL, &model.HowWeMet, &tags, &model.Notes, &model.LastContacted, &model.FollowUpDate,
|
// &model.LinkedinURL, &model.HowWeMet, &tags, &model.Notes, &model.LastContacted, &model.FollowUpDate,
|
||||||
&model.CreatedAt, &model.UpdatedAt); err != nil {
|
// &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.ProfessionalContact{}, fmt.Errorf("get contact: %w", err)
|
// return ext.ProfessionalContact{}, fmt.Errorf("get contact: %w", err)
|
||||||
}
|
// }
|
||||||
c := professionalContactFromModel(model, tags)
|
// c := professionalContactFromModel(model, tags)
|
||||||
return c, nil
|
// return c, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) LogInteraction(ctx context.Context, interaction ext.ContactInteraction) (ext.ContactInteraction, error) {
|
// func (db *DB) LogInteraction(ctx context.Context, interaction ext.ContactInteraction) (ext.ContactInteraction, error) {
|
||||||
occurredAt := interaction.OccurredAt
|
// occurredAt := interaction.OccurredAt
|
||||||
if occurredAt.IsZero() {
|
// if occurredAt.IsZero() {
|
||||||
occurredAt = time.Now()
|
// occurredAt = time.Now()
|
||||||
}
|
// }
|
||||||
|
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into contact_interactions (contact_id, interaction_type, occurred_at, summary, follow_up_needed, follow_up_notes)
|
// insert into contact_interactions (contact_id, interaction_type, occurred_at, summary, follow_up_needed, follow_up_notes)
|
||||||
values ($1, $2, $3, $4, $5, $6)
|
// values ($1, $2, $3, $4, $5, $6)
|
||||||
returning id, created_at
|
// returning id, created_at
|
||||||
`, interaction.ContactID, interaction.InteractionType, occurredAt, interaction.Summary,
|
// `, interaction.ContactID, interaction.InteractionType, occurredAt, interaction.Summary,
|
||||||
interaction.FollowUpNeeded, nullStr(interaction.FollowUpNotes))
|
// interaction.FollowUpNeeded, nullStr(interaction.FollowUpNotes))
|
||||||
|
|
||||||
created := interaction
|
// created := interaction
|
||||||
created.OccurredAt = occurredAt
|
// created.OccurredAt = occurredAt
|
||||||
var model generatedmodels.ModelPublicContactInteractions
|
// var model generatedmodels.ModelPublicContactInteractions
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
||||||
return ext.ContactInteraction{}, fmt.Errorf("insert interaction: %w", err)
|
// return ext.ContactInteraction{}, fmt.Errorf("insert interaction: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetContactHistory(ctx context.Context, contactID uuid.UUID) (ext.ContactHistory, error) {
|
// func (db *DB) GetContactHistory(ctx context.Context, contactID uuid.UUID) (ext.ContactHistory, error) {
|
||||||
contact, err := db.GetContact(ctx, contactID)
|
// contact, err := db.GetContact(ctx, contactID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.ContactHistory{}, err
|
// return ext.ContactHistory{}, err
|
||||||
}
|
// }
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, `
|
// rows, err := db.pool.Query(ctx, `
|
||||||
select id, contact_id, interaction_type, occurred_at, summary, follow_up_needed, follow_up_notes, created_at
|
// select id, contact_id, interaction_type, occurred_at, summary, follow_up_needed, follow_up_notes, created_at
|
||||||
from contact_interactions where contact_id = $1 order by occurred_at desc
|
// from contact_interactions where contact_id = $1 order by occurred_at desc
|
||||||
`, contactID)
|
// `, contactID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.ContactHistory{}, fmt.Errorf("get interactions: %w", err)
|
// return ext.ContactHistory{}, fmt.Errorf("get interactions: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var interactions []ext.ContactInteraction
|
// var interactions []ext.ContactInteraction
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicContactInteractions
|
// var model generatedmodels.ModelPublicContactInteractions
|
||||||
if err := rows.Scan(&model.ID, &model.ContactID, &model.InteractionType, &model.OccurredAt, &model.Summary,
|
// if err := rows.Scan(&model.ID, &model.ContactID, &model.InteractionType, &model.OccurredAt, &model.Summary,
|
||||||
&model.FollowUpNeeded, &model.FollowUpNotes, &model.CreatedAt); err != nil {
|
// &model.FollowUpNeeded, &model.FollowUpNotes, &model.CreatedAt); err != nil {
|
||||||
return ext.ContactHistory{}, fmt.Errorf("scan interaction: %w", err)
|
// return ext.ContactHistory{}, fmt.Errorf("scan interaction: %w", err)
|
||||||
}
|
// }
|
||||||
interactions = append(interactions, contactInteractionFromModel(model))
|
// interactions = append(interactions, contactInteractionFromModel(model))
|
||||||
}
|
// }
|
||||||
if err := rows.Err(); err != nil {
|
// if err := rows.Err(); err != nil {
|
||||||
return ext.ContactHistory{}, err
|
// return ext.ContactHistory{}, err
|
||||||
}
|
// }
|
||||||
|
|
||||||
oppRows, err := db.pool.Query(ctx, `
|
// oppRows, err := db.pool.Query(ctx, `
|
||||||
select id, contact_id, title, description, stage, value, expected_close_date, notes, created_at, updated_at
|
// select id, contact_id, title, description, stage, value, expected_close_date, notes, created_at, updated_at
|
||||||
from opportunities where contact_id = $1 order by created_at desc
|
// from opportunities where contact_id = $1 order by created_at desc
|
||||||
`, contactID)
|
// `, contactID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.ContactHistory{}, fmt.Errorf("get opportunities: %w", err)
|
// return ext.ContactHistory{}, fmt.Errorf("get opportunities: %w", err)
|
||||||
}
|
// }
|
||||||
defer oppRows.Close()
|
// defer oppRows.Close()
|
||||||
|
|
||||||
var opportunities []ext.Opportunity
|
// var opportunities []ext.Opportunity
|
||||||
for oppRows.Next() {
|
// for oppRows.Next() {
|
||||||
var model generatedmodels.ModelPublicOpportunities
|
// var model generatedmodels.ModelPublicOpportunities
|
||||||
if err := oppRows.Scan(&model.ID, &model.ContactID, &model.Title, &model.Description, &model.Stage, &model.Value,
|
// if err := oppRows.Scan(&model.ID, &model.ContactID, &model.Title, &model.Description, &model.Stage, &model.Value,
|
||||||
&model.ExpectedCloseDate, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// &model.ExpectedCloseDate, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.ContactHistory{}, fmt.Errorf("scan opportunity: %w", err)
|
// return ext.ContactHistory{}, fmt.Errorf("scan opportunity: %w", err)
|
||||||
}
|
// }
|
||||||
opportunities = append(opportunities, opportunityFromModel(model))
|
// opportunities = append(opportunities, opportunityFromModel(model))
|
||||||
}
|
// }
|
||||||
if err := oppRows.Err(); err != nil {
|
// if err := oppRows.Err(); err != nil {
|
||||||
return ext.ContactHistory{}, err
|
// return ext.ContactHistory{}, err
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.ContactHistory{
|
// return ext.ContactHistory{
|
||||||
Contact: contact,
|
// Contact: contact,
|
||||||
Interactions: interactions,
|
// Interactions: interactions,
|
||||||
Opportunities: opportunities,
|
// Opportunities: opportunities,
|
||||||
}, nil
|
// }, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) CreateOpportunity(ctx context.Context, o ext.Opportunity) (ext.Opportunity, error) {
|
// func (db *DB) CreateOpportunity(ctx context.Context, o ext.Opportunity) (ext.Opportunity, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into opportunities (contact_id, title, description, stage, value, expected_close_date, notes)
|
// insert into opportunities (contact_id, title, description, stage, value, expected_close_date, notes)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7)
|
// values ($1, $2, $3, $4, $5, $6, $7)
|
||||||
returning id, created_at, updated_at
|
// returning id, created_at, updated_at
|
||||||
`, o.ContactID, o.Title, nullStr(o.Description), o.Stage, o.Value, o.ExpectedCloseDate, nullStr(o.Notes))
|
// `, o.ContactID, o.Title, nullStr(o.Description), o.Stage, o.Value, o.ExpectedCloseDate, nullStr(o.Notes))
|
||||||
|
|
||||||
created := o
|
// created := o
|
||||||
var model generatedmodels.ModelPublicOpportunities
|
// var model generatedmodels.ModelPublicOpportunities
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.Opportunity{}, fmt.Errorf("insert opportunity: %w", err)
|
// return ext.Opportunity{}, fmt.Errorf("insert opportunity: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
created.UpdatedAt = model.UpdatedAt.Time()
|
// created.UpdatedAt = model.UpdatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetFollowUpsDue(ctx context.Context, daysAhead int) ([]ext.ProfessionalContact, error) {
|
// func (db *DB) GetFollowUpsDue(ctx context.Context, daysAhead int) ([]ext.ProfessionalContact, error) {
|
||||||
if daysAhead <= 0 {
|
// if daysAhead <= 0 {
|
||||||
daysAhead = 7
|
// daysAhead = 7
|
||||||
}
|
// }
|
||||||
cutoff := time.Now().AddDate(0, 0, daysAhead)
|
// cutoff := time.Now().AddDate(0, 0, daysAhead)
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, `
|
// rows, err := db.pool.Query(ctx, `
|
||||||
select id, name, company, title, email, phone, linkedin_url, how_we_met, tags::text[], notes, last_contacted, follow_up_date, created_at, updated_at
|
// select id, name, company, title, email, phone, linkedin_url, how_we_met, tags::text[], notes, last_contacted, follow_up_date, created_at, updated_at
|
||||||
from professional_contacts
|
// from professional_contacts
|
||||||
where follow_up_date <= $1
|
// where follow_up_date <= $1
|
||||||
order by follow_up_date asc
|
// order by follow_up_date asc
|
||||||
`, cutoff)
|
// `, cutoff)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("get follow-ups: %w", err)
|
// return nil, fmt.Errorf("get follow-ups: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
return scanContacts(rows)
|
// return scanContacts(rows)
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) AppendThoughtToContactNotes(ctx context.Context, contactID uuid.UUID, thoughtContent string) error {
|
// func (db *DB) AppendThoughtToContactNotes(ctx context.Context, contactID uuid.UUID, thoughtContent string) error {
|
||||||
_, err := db.pool.Exec(ctx, `
|
// _, err := db.pool.Exec(ctx, `
|
||||||
update professional_contacts
|
// update professional_contacts
|
||||||
set notes = coalesce(notes, '') || $2
|
// set notes = coalesce(notes, '') || $2
|
||||||
where id = $1
|
// where id = $1
|
||||||
`, contactID, thoughtContent)
|
// `, contactID, thoughtContent)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return fmt.Errorf("append thought to contact: %w", err)
|
// return fmt.Errorf("append thought to contact: %w", err)
|
||||||
}
|
// }
|
||||||
return nil
|
// return nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func scanContacts(rows interface {
|
// func scanContacts(rows interface {
|
||||||
Next() bool
|
// Next() bool
|
||||||
Scan(...any) error
|
// Scan(...any) error
|
||||||
Err() error
|
// Err() error
|
||||||
Close()
|
// Close()
|
||||||
}) ([]ext.ProfessionalContact, error) {
|
// }) ([]ext.ProfessionalContact, error) {
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
var contacts []ext.ProfessionalContact
|
// var contacts []ext.ProfessionalContact
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicProfessionalContacts
|
// var model generatedmodels.ModelPublicProfessionalContacts
|
||||||
var tags []string
|
// var tags []string
|
||||||
if err := rows.Scan(&model.ID, &model.Name, &model.Company, &model.Title, &model.Email, &model.Phone,
|
// if err := rows.Scan(&model.ID, &model.Name, &model.Company, &model.Title, &model.Email, &model.Phone,
|
||||||
&model.LinkedinURL, &model.HowWeMet, &tags, &model.Notes, &model.LastContacted, &model.FollowUpDate,
|
// &model.LinkedinURL, &model.HowWeMet, &tags, &model.Notes, &model.LastContacted, &model.FollowUpDate,
|
||||||
&model.CreatedAt, &model.UpdatedAt); err != nil {
|
// &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan contact: %w", err)
|
// return nil, fmt.Errorf("scan contact: %w", err)
|
||||||
}
|
// }
|
||||||
contacts = append(contacts, professionalContactFromModel(model, tags))
|
// contacts = append(contacts, professionalContactFromModel(model, tags))
|
||||||
}
|
// }
|
||||||
return contacts, rows.Err()
|
// return contacts, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,133 +1,133 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"encoding/json"
|
// "encoding/json"
|
||||||
"fmt"
|
// "fmt"
|
||||||
"strings"
|
// "strings"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
// "git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
func (db *DB) AddHouseholdItem(ctx context.Context, item ext.HouseholdItem) (ext.HouseholdItem, error) {
|
// func (db *DB) AddHouseholdItem(ctx context.Context, item ext.HouseholdItem) (ext.HouseholdItem, error) {
|
||||||
details, err := json.Marshal(item.Details)
|
// details, err := json.Marshal(item.Details)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.HouseholdItem{}, fmt.Errorf("marshal details: %w", err)
|
// return ext.HouseholdItem{}, fmt.Errorf("marshal details: %w", err)
|
||||||
}
|
// }
|
||||||
|
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into household_items (name, category, location, details, notes)
|
// insert into household_items (name, category, location, details, notes)
|
||||||
values ($1, $2, $3, $4::jsonb, $5)
|
// values ($1, $2, $3, $4::jsonb, $5)
|
||||||
returning id, created_at, updated_at
|
// returning id, created_at, updated_at
|
||||||
`, item.Name, nullStr(item.Category), nullStr(item.Location), details, nullStr(item.Notes))
|
// `, item.Name, nullStr(item.Category), nullStr(item.Location), details, nullStr(item.Notes))
|
||||||
|
|
||||||
created := item
|
// created := item
|
||||||
var model generatedmodels.ModelPublicHouseholdItems
|
// var model generatedmodels.ModelPublicHouseholdItems
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.HouseholdItem{}, fmt.Errorf("insert household item: %w", err)
|
// return ext.HouseholdItem{}, fmt.Errorf("insert household item: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
created.UpdatedAt = model.UpdatedAt.Time()
|
// created.UpdatedAt = model.UpdatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) SearchHouseholdItems(ctx context.Context, query, category, location string) ([]ext.HouseholdItem, error) {
|
// func (db *DB) SearchHouseholdItems(ctx context.Context, query, category, location string) ([]ext.HouseholdItem, error) {
|
||||||
args := []any{}
|
// args := []any{}
|
||||||
conditions := []string{}
|
// conditions := []string{}
|
||||||
|
|
||||||
if q := strings.TrimSpace(query); q != "" {
|
// if q := strings.TrimSpace(query); q != "" {
|
||||||
args = append(args, "%"+q+"%")
|
// args = append(args, "%"+q+"%")
|
||||||
conditions = append(conditions, fmt.Sprintf("(name ILIKE $%d OR notes ILIKE $%d)", len(args), len(args)))
|
// conditions = append(conditions, fmt.Sprintf("(name ILIKE $%d OR notes ILIKE $%d)", len(args), len(args)))
|
||||||
}
|
// }
|
||||||
if c := strings.TrimSpace(category); c != "" {
|
// if c := strings.TrimSpace(category); c != "" {
|
||||||
args = append(args, c)
|
// args = append(args, c)
|
||||||
conditions = append(conditions, fmt.Sprintf("category = $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("category = $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if l := strings.TrimSpace(location); l != "" {
|
// if l := strings.TrimSpace(location); l != "" {
|
||||||
args = append(args, "%"+l+"%")
|
// args = append(args, "%"+l+"%")
|
||||||
conditions = append(conditions, fmt.Sprintf("location ILIKE $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("location ILIKE $%d", len(args)))
|
||||||
}
|
// }
|
||||||
|
|
||||||
q := `select id, name, category, location, details, notes, created_at, updated_at from household_items`
|
// q := `select id, name, category, location, details, notes, created_at, updated_at from household_items`
|
||||||
if len(conditions) > 0 {
|
// if len(conditions) > 0 {
|
||||||
q += " where " + strings.Join(conditions, " and ")
|
// q += " where " + strings.Join(conditions, " and ")
|
||||||
}
|
// }
|
||||||
q += " order by name"
|
// q += " order by name"
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, q, args...)
|
// rows, err := db.pool.Query(ctx, q, args...)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("search household items: %w", err)
|
// return nil, fmt.Errorf("search household items: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var items []ext.HouseholdItem
|
// var items []ext.HouseholdItem
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicHouseholdItems
|
// var model generatedmodels.ModelPublicHouseholdItems
|
||||||
if err := rows.Scan(&model.ID, &model.Name, &model.Category, &model.Location, &model.Details, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := rows.Scan(&model.ID, &model.Name, &model.Category, &model.Location, &model.Details, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan household item: %w", err)
|
// return nil, fmt.Errorf("scan household item: %w", err)
|
||||||
}
|
// }
|
||||||
items = append(items, householdItemFromModel(model))
|
// items = append(items, householdItemFromModel(model))
|
||||||
}
|
// }
|
||||||
return items, rows.Err()
|
// return items, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetHouseholdItem(ctx context.Context, id uuid.UUID) (ext.HouseholdItem, error) {
|
// func (db *DB) GetHouseholdItem(ctx context.Context, id uuid.UUID) (ext.HouseholdItem, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
select id, name, category, location, details, notes, created_at, updated_at
|
// select id, name, category, location, details, notes, created_at, updated_at
|
||||||
from household_items where id = $1
|
// from household_items where id = $1
|
||||||
`, id)
|
// `, id)
|
||||||
|
|
||||||
var model generatedmodels.ModelPublicHouseholdItems
|
// var model generatedmodels.ModelPublicHouseholdItems
|
||||||
if err := row.Scan(&model.ID, &model.Name, &model.Category, &model.Location, &model.Details, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.Name, &model.Category, &model.Location, &model.Details, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.HouseholdItem{}, fmt.Errorf("get household item: %w", err)
|
// return ext.HouseholdItem{}, fmt.Errorf("get household item: %w", err)
|
||||||
}
|
// }
|
||||||
return householdItemFromModel(model), nil
|
// return householdItemFromModel(model), nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) AddVendor(ctx context.Context, v ext.HouseholdVendor) (ext.HouseholdVendor, error) {
|
// func (db *DB) AddVendor(ctx context.Context, v ext.HouseholdVendor) (ext.HouseholdVendor, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into household_vendors (name, service_type, phone, email, website, notes, rating, last_used)
|
// insert into household_vendors (name, service_type, phone, email, website, notes, rating, last_used)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7, $8)
|
// values ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||||
returning id, created_at
|
// returning id, created_at
|
||||||
`, v.Name, nullStr(v.ServiceType), nullStr(v.Phone), nullStr(v.Email),
|
// `, v.Name, nullStr(v.ServiceType), nullStr(v.Phone), nullStr(v.Email),
|
||||||
nullStr(v.Website), nullStr(v.Notes), v.Rating, v.LastUsed)
|
// nullStr(v.Website), nullStr(v.Notes), v.Rating, v.LastUsed)
|
||||||
|
|
||||||
created := v
|
// created := v
|
||||||
var model generatedmodels.ModelPublicHouseholdVendors
|
// var model generatedmodels.ModelPublicHouseholdVendors
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
||||||
return ext.HouseholdVendor{}, fmt.Errorf("insert vendor: %w", err)
|
// return ext.HouseholdVendor{}, fmt.Errorf("insert vendor: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) ListVendors(ctx context.Context, serviceType string) ([]ext.HouseholdVendor, error) {
|
// func (db *DB) ListVendors(ctx context.Context, serviceType string) ([]ext.HouseholdVendor, error) {
|
||||||
args := []any{}
|
// args := []any{}
|
||||||
q := `select id, name, service_type, phone, email, website, notes, rating, last_used, created_at from household_vendors`
|
// q := `select id, name, service_type, phone, email, website, notes, rating, last_used, created_at from household_vendors`
|
||||||
if st := strings.TrimSpace(serviceType); st != "" {
|
// if st := strings.TrimSpace(serviceType); st != "" {
|
||||||
args = append(args, st)
|
// args = append(args, st)
|
||||||
q += " where service_type = $1"
|
// q += " where service_type = $1"
|
||||||
}
|
// }
|
||||||
q += " order by name"
|
// q += " order by name"
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, q, args...)
|
// rows, err := db.pool.Query(ctx, q, args...)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("list vendors: %w", err)
|
// return nil, fmt.Errorf("list vendors: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var vendors []ext.HouseholdVendor
|
// var vendors []ext.HouseholdVendor
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicHouseholdVendors
|
// var model generatedmodels.ModelPublicHouseholdVendors
|
||||||
if err := rows.Scan(&model.ID, &model.Name, &model.ServiceType, &model.Phone, &model.Email, &model.Website, &model.Notes, &model.Rating, &model.LastUsed, &model.CreatedAt); err != nil {
|
// if err := rows.Scan(&model.ID, &model.Name, &model.ServiceType, &model.Phone, &model.Email, &model.Website, &model.Notes, &model.Rating, &model.LastUsed, &model.CreatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan vendor: %w", err)
|
// return nil, fmt.Errorf("scan vendor: %w", err)
|
||||||
}
|
// }
|
||||||
vendors = append(vendors, householdVendorFromModel(model))
|
// vendors = append(vendors, householdVendorFromModel(model))
|
||||||
}
|
// }
|
||||||
return vendors, rows.Err()
|
// return vendors, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,137 +1,137 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"fmt"
|
// "fmt"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
// "git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
func (db *DB) AddMaintenanceTask(ctx context.Context, t ext.MaintenanceTask) (ext.MaintenanceTask, error) {
|
// func (db *DB) AddMaintenanceTask(ctx context.Context, t ext.MaintenanceTask) (ext.MaintenanceTask, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into maintenance_tasks (name, category, frequency_days, next_due, priority, notes)
|
// insert into maintenance_tasks (name, category, frequency_days, next_due, priority, notes)
|
||||||
values ($1, $2, $3, $4, $5, $6)
|
// values ($1, $2, $3, $4, $5, $6)
|
||||||
returning id, created_at, updated_at
|
// returning id, created_at, updated_at
|
||||||
`, t.Name, nullStr(t.Category), t.FrequencyDays, t.NextDue, t.Priority, nullStr(t.Notes))
|
// `, t.Name, nullStr(t.Category), t.FrequencyDays, t.NextDue, t.Priority, nullStr(t.Notes))
|
||||||
|
|
||||||
created := t
|
// created := t
|
||||||
var model generatedmodels.ModelPublicMaintenanceTasks
|
// var model generatedmodels.ModelPublicMaintenanceTasks
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.MaintenanceTask{}, fmt.Errorf("insert maintenance task: %w", err)
|
// return ext.MaintenanceTask{}, fmt.Errorf("insert maintenance task: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
created.UpdatedAt = model.UpdatedAt.Time()
|
// created.UpdatedAt = model.UpdatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) LogMaintenance(ctx context.Context, log ext.MaintenanceLog) (ext.MaintenanceLog, error) {
|
// func (db *DB) LogMaintenance(ctx context.Context, log ext.MaintenanceLog) (ext.MaintenanceLog, error) {
|
||||||
completedAt := log.CompletedAt
|
// completedAt := log.CompletedAt
|
||||||
if completedAt.IsZero() {
|
// if completedAt.IsZero() {
|
||||||
completedAt = time.Now()
|
// completedAt = time.Now()
|
||||||
}
|
// }
|
||||||
|
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into maintenance_logs (task_id, completed_at, performed_by, cost, notes, next_action)
|
// insert into maintenance_logs (task_id, completed_at, performed_by, cost, notes, next_action)
|
||||||
values ($1, $2, $3, $4, $5, $6)
|
// values ($1, $2, $3, $4, $5, $6)
|
||||||
returning id
|
// returning id
|
||||||
`, log.TaskID, completedAt, nullStr(log.PerformedBy), log.Cost, nullStr(log.Notes), nullStr(log.NextAction))
|
// `, log.TaskID, completedAt, nullStr(log.PerformedBy), log.Cost, nullStr(log.Notes), nullStr(log.NextAction))
|
||||||
|
|
||||||
created := log
|
// created := log
|
||||||
created.CompletedAt = completedAt
|
// created.CompletedAt = completedAt
|
||||||
var model generatedmodels.ModelPublicMaintenanceLogs
|
// var model generatedmodels.ModelPublicMaintenanceLogs
|
||||||
if err := row.Scan(&model.ID); err != nil {
|
// if err := row.Scan(&model.ID); err != nil {
|
||||||
return ext.MaintenanceLog{}, fmt.Errorf("insert maintenance log: %w", err)
|
// return ext.MaintenanceLog{}, fmt.Errorf("insert maintenance log: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetUpcomingMaintenance(ctx context.Context, daysAhead int) ([]ext.MaintenanceTask, error) {
|
// func (db *DB) GetUpcomingMaintenance(ctx context.Context, daysAhead int) ([]ext.MaintenanceTask, error) {
|
||||||
if daysAhead <= 0 {
|
// if daysAhead <= 0 {
|
||||||
daysAhead = 30
|
// daysAhead = 30
|
||||||
}
|
// }
|
||||||
cutoff := time.Now().Add(time.Duration(daysAhead) * 24 * time.Hour)
|
// cutoff := time.Now().Add(time.Duration(daysAhead) * 24 * time.Hour)
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, `
|
// rows, err := db.pool.Query(ctx, `
|
||||||
select id, name, category, frequency_days, last_completed, next_due, priority, notes, created_at, updated_at
|
// select id, name, category, frequency_days, last_completed, next_due, priority, notes, created_at, updated_at
|
||||||
from maintenance_tasks
|
// from maintenance_tasks
|
||||||
where next_due <= $1 or next_due is null
|
// where next_due <= $1 or next_due is null
|
||||||
order by next_due asc nulls last, priority desc
|
// order by next_due asc nulls last, priority desc
|
||||||
`, cutoff)
|
// `, cutoff)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("get upcoming maintenance: %w", err)
|
// return nil, fmt.Errorf("get upcoming maintenance: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
tasks := make([]ext.MaintenanceTask, 0)
|
// tasks := make([]ext.MaintenanceTask, 0)
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicMaintenanceTasks
|
// var model generatedmodels.ModelPublicMaintenanceTasks
|
||||||
if err := rows.Scan(&model.ID, &model.Name, &model.Category, &model.FrequencyDays, &model.LastCompleted, &model.NextDue, &model.Priority, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := rows.Scan(&model.ID, &model.Name, &model.Category, &model.FrequencyDays, &model.LastCompleted, &model.NextDue, &model.Priority, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan maintenance task: %w", err)
|
// return nil, fmt.Errorf("scan maintenance task: %w", err)
|
||||||
}
|
// }
|
||||||
tasks = append(tasks, maintenanceTaskFromModel(model))
|
// tasks = append(tasks, maintenanceTaskFromModel(model))
|
||||||
}
|
// }
|
||||||
return tasks, rows.Err()
|
// return tasks, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) SearchMaintenanceHistory(ctx context.Context, query, category string, start, end *time.Time) ([]ext.MaintenanceLogWithTask, error) {
|
// func (db *DB) SearchMaintenanceHistory(ctx context.Context, query, category string, start, end *time.Time) ([]ext.MaintenanceLogWithTask, error) {
|
||||||
args := []any{}
|
// args := []any{}
|
||||||
conditions := []string{}
|
// conditions := []string{}
|
||||||
|
|
||||||
if q := strings.TrimSpace(query); q != "" {
|
// if q := strings.TrimSpace(query); q != "" {
|
||||||
args = append(args, "%"+q+"%")
|
// args = append(args, "%"+q+"%")
|
||||||
conditions = append(conditions, fmt.Sprintf("(mt.name ILIKE $%d OR ml.notes ILIKE $%d)", len(args), len(args)))
|
// conditions = append(conditions, fmt.Sprintf("(mt.name ILIKE $%d OR ml.notes ILIKE $%d)", len(args), len(args)))
|
||||||
}
|
// }
|
||||||
if c := strings.TrimSpace(category); c != "" {
|
// if c := strings.TrimSpace(category); c != "" {
|
||||||
args = append(args, c)
|
// args = append(args, c)
|
||||||
conditions = append(conditions, fmt.Sprintf("mt.category = $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("mt.category = $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if start != nil {
|
// if start != nil {
|
||||||
args = append(args, *start)
|
// args = append(args, *start)
|
||||||
conditions = append(conditions, fmt.Sprintf("ml.completed_at >= $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("ml.completed_at >= $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if end != nil {
|
// if end != nil {
|
||||||
args = append(args, *end)
|
// args = append(args, *end)
|
||||||
conditions = append(conditions, fmt.Sprintf("ml.completed_at <= $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("ml.completed_at <= $%d", len(args)))
|
||||||
}
|
// }
|
||||||
|
|
||||||
q := `
|
// q := `
|
||||||
select ml.id, ml.task_id, ml.completed_at, ml.performed_by, ml.cost, ml.notes, ml.next_action,
|
// select ml.id, ml.task_id, ml.completed_at, ml.performed_by, ml.cost, ml.notes, ml.next_action,
|
||||||
mt.name, mt.category
|
// mt.name, mt.category
|
||||||
from maintenance_logs ml
|
// from maintenance_logs ml
|
||||||
join maintenance_tasks mt on mt.id = ml.task_id
|
// join maintenance_tasks mt on mt.id = ml.task_id
|
||||||
`
|
// `
|
||||||
if len(conditions) > 0 {
|
// if len(conditions) > 0 {
|
||||||
q += " where " + strings.Join(conditions, " and ")
|
// q += " where " + strings.Join(conditions, " and ")
|
||||||
}
|
// }
|
||||||
q += " order by ml.completed_at desc"
|
// q += " order by ml.completed_at desc"
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, q, args...)
|
// rows, err := db.pool.Query(ctx, q, args...)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("search maintenance history: %w", err)
|
// return nil, fmt.Errorf("search maintenance history: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var logs []ext.MaintenanceLogWithTask
|
// var logs []ext.MaintenanceLogWithTask
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicMaintenanceLogs
|
// var model generatedmodels.ModelPublicMaintenanceLogs
|
||||||
var taskName, taskCategory string
|
// var taskName, taskCategory string
|
||||||
if err := rows.Scan(
|
// if err := rows.Scan(
|
||||||
&model.ID, &model.TaskID, &model.CompletedAt, &model.PerformedBy, &model.Cost, &model.Notes, &model.NextAction,
|
// &model.ID, &model.TaskID, &model.CompletedAt, &model.PerformedBy, &model.Cost, &model.Notes, &model.NextAction,
|
||||||
&taskName, &taskCategory,
|
// &taskName, &taskCategory,
|
||||||
); err != nil {
|
// ); err != nil {
|
||||||
return nil, fmt.Errorf("scan maintenance log: %w", err)
|
// return nil, fmt.Errorf("scan maintenance log: %w", err)
|
||||||
}
|
// }
|
||||||
l := ext.MaintenanceLogWithTask{
|
// l := ext.MaintenanceLogWithTask{
|
||||||
MaintenanceLog: maintenanceLogFromModel(model),
|
// MaintenanceLog: maintenanceLogFromModel(model),
|
||||||
TaskName: taskName,
|
// TaskName: taskName,
|
||||||
TaskCategory: taskCategory,
|
// TaskCategory: taskCategory,
|
||||||
}
|
// }
|
||||||
logs = append(logs, l)
|
// logs = append(logs, l)
|
||||||
}
|
// }
|
||||||
return logs, rows.Err()
|
// return logs, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,280 +1,280 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"encoding/json"
|
// "encoding/json"
|
||||||
"fmt"
|
// "fmt"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
// "git.warky.dev/wdevs/amcs/internal/generatedmodels"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
func (db *DB) AddRecipe(ctx context.Context, r ext.Recipe) (ext.Recipe, error) {
|
// func (db *DB) AddRecipe(ctx context.Context, r ext.Recipe) (ext.Recipe, error) {
|
||||||
ingredients, err := json.Marshal(r.Ingredients)
|
// ingredients, err := json.Marshal(r.Ingredients)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("marshal ingredients: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("marshal ingredients: %w", err)
|
||||||
}
|
// }
|
||||||
instructions, err := json.Marshal(r.Instructions)
|
// instructions, err := json.Marshal(r.Instructions)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("marshal instructions: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("marshal instructions: %w", err)
|
||||||
}
|
// }
|
||||||
if r.Tags == nil {
|
// if r.Tags == nil {
|
||||||
r.Tags = []string{}
|
// r.Tags = []string{}
|
||||||
}
|
// }
|
||||||
|
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into recipes (name, cuisine, prep_time_minutes, cook_time_minutes, servings, ingredients, instructions, tags, rating, notes)
|
// insert into recipes (name, cuisine, prep_time_minutes, cook_time_minutes, servings, ingredients, instructions, tags, rating, notes)
|
||||||
values ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, $8, $9, $10)
|
// values ($1, $2, $3, $4, $5, $6::jsonb, $7::jsonb, $8, $9, $10)
|
||||||
returning id, created_at, updated_at
|
// returning id, created_at, updated_at
|
||||||
`, r.Name, nullStr(r.Cuisine), r.PrepTimeMinutes, r.CookTimeMinutes, r.Servings,
|
// `, r.Name, nullStr(r.Cuisine), r.PrepTimeMinutes, r.CookTimeMinutes, r.Servings,
|
||||||
ingredients, instructions, r.Tags, r.Rating, nullStr(r.Notes))
|
// ingredients, instructions, r.Tags, r.Rating, nullStr(r.Notes))
|
||||||
|
|
||||||
created := r
|
// created := r
|
||||||
var model generatedmodels.ModelPublicRecipes
|
// var model generatedmodels.ModelPublicRecipes
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("insert recipe: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("insert recipe: %w", err)
|
||||||
}
|
// }
|
||||||
created.ID = model.ID.UUID()
|
// created.ID = model.ID.UUID()
|
||||||
created.CreatedAt = model.CreatedAt.Time()
|
// created.CreatedAt = model.CreatedAt.Time()
|
||||||
created.UpdatedAt = model.UpdatedAt.Time()
|
// created.UpdatedAt = model.UpdatedAt.Time()
|
||||||
return created, nil
|
// return created, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) SearchRecipes(ctx context.Context, query, cuisine string, tags []string, ingredient string) ([]ext.Recipe, error) {
|
// func (db *DB) SearchRecipes(ctx context.Context, query, cuisine string, tags []string, ingredient string) ([]ext.Recipe, error) {
|
||||||
args := []any{}
|
// args := []any{}
|
||||||
conditions := []string{}
|
// conditions := []string{}
|
||||||
|
|
||||||
if q := strings.TrimSpace(query); q != "" {
|
// if q := strings.TrimSpace(query); q != "" {
|
||||||
args = append(args, "%"+q+"%")
|
// args = append(args, "%"+q+"%")
|
||||||
conditions = append(conditions, fmt.Sprintf("name ILIKE $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("name ILIKE $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if c := strings.TrimSpace(cuisine); c != "" {
|
// if c := strings.TrimSpace(cuisine); c != "" {
|
||||||
args = append(args, c)
|
// args = append(args, c)
|
||||||
conditions = append(conditions, fmt.Sprintf("cuisine = $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("cuisine = $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if len(tags) > 0 {
|
// if len(tags) > 0 {
|
||||||
args = append(args, tags)
|
// args = append(args, tags)
|
||||||
conditions = append(conditions, fmt.Sprintf("tags @> $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("tags @> $%d", len(args)))
|
||||||
}
|
// }
|
||||||
if ing := strings.TrimSpace(ingredient); ing != "" {
|
// if ing := strings.TrimSpace(ingredient); ing != "" {
|
||||||
args = append(args, "%"+ing+"%")
|
// args = append(args, "%"+ing+"%")
|
||||||
conditions = append(conditions, fmt.Sprintf("ingredients::text ILIKE $%d", len(args)))
|
// conditions = append(conditions, fmt.Sprintf("ingredients::text ILIKE $%d", len(args)))
|
||||||
}
|
// }
|
||||||
|
|
||||||
q := `select id, name, cuisine, prep_time_minutes, cook_time_minutes, servings, ingredients, instructions, tags::text[], rating, notes, created_at, updated_at from recipes`
|
// q := `select id, name, cuisine, prep_time_minutes, cook_time_minutes, servings, ingredients, instructions, tags::text[], rating, notes, created_at, updated_at from recipes`
|
||||||
if len(conditions) > 0 {
|
// if len(conditions) > 0 {
|
||||||
q += " where " + strings.Join(conditions, " and ")
|
// q += " where " + strings.Join(conditions, " and ")
|
||||||
}
|
// }
|
||||||
q += " order by name"
|
// q += " order by name"
|
||||||
|
|
||||||
rows, err := db.pool.Query(ctx, q, args...)
|
// rows, err := db.pool.Query(ctx, q, args...)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("search recipes: %w", err)
|
// return nil, fmt.Errorf("search recipes: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var recipes []ext.Recipe
|
// var recipes []ext.Recipe
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
r, err := scanRecipeRow(rows)
|
// r, err := scanRecipeRow(rows)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, err
|
// return nil, err
|
||||||
}
|
// }
|
||||||
recipes = append(recipes, r)
|
// recipes = append(recipes, r)
|
||||||
}
|
// }
|
||||||
return recipes, rows.Err()
|
// return recipes, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetRecipe(ctx context.Context, id uuid.UUID) (ext.Recipe, error) {
|
// func (db *DB) GetRecipe(ctx context.Context, id uuid.UUID) (ext.Recipe, error) {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
select id, name, cuisine, prep_time_minutes, cook_time_minutes, servings, ingredients, instructions, tags::text[], rating, notes, created_at, updated_at
|
// select id, name, cuisine, prep_time_minutes, cook_time_minutes, servings, ingredients, instructions, tags::text[], rating, notes, created_at, updated_at
|
||||||
from recipes where id = $1
|
// from recipes where id = $1
|
||||||
`, id)
|
// `, id)
|
||||||
|
|
||||||
var model generatedmodels.ModelPublicRecipes
|
// var model generatedmodels.ModelPublicRecipes
|
||||||
var tags []string
|
// var tags []string
|
||||||
if err := row.Scan(&model.ID, &model.Name, &model.Cuisine, &model.PrepTimeMinutes, &model.CookTimeMinutes, &model.Servings,
|
// if err := row.Scan(&model.ID, &model.Name, &model.Cuisine, &model.PrepTimeMinutes, &model.CookTimeMinutes, &model.Servings,
|
||||||
&model.Ingredients, &model.Instructions, &tags, &model.Rating, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// &model.Ingredients, &model.Instructions, &tags, &model.Rating, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("get recipe: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("get recipe: %w", err)
|
||||||
}
|
// }
|
||||||
if tags == nil {
|
// if tags == nil {
|
||||||
tags = []string{}
|
// tags = []string{}
|
||||||
}
|
// }
|
||||||
return recipeFromModel(model, tags), nil
|
// return recipeFromModel(model, tags), nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) UpdateRecipe(ctx context.Context, id uuid.UUID, r ext.Recipe) (ext.Recipe, error) {
|
// func (db *DB) UpdateRecipe(ctx context.Context, id uuid.UUID, r ext.Recipe) (ext.Recipe, error) {
|
||||||
ingredients, err := json.Marshal(r.Ingredients)
|
// ingredients, err := json.Marshal(r.Ingredients)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("marshal ingredients: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("marshal ingredients: %w", err)
|
||||||
}
|
// }
|
||||||
instructions, err := json.Marshal(r.Instructions)
|
// instructions, err := json.Marshal(r.Instructions)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("marshal instructions: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("marshal instructions: %w", err)
|
||||||
}
|
// }
|
||||||
if r.Tags == nil {
|
// if r.Tags == nil {
|
||||||
r.Tags = []string{}
|
// r.Tags = []string{}
|
||||||
}
|
// }
|
||||||
|
|
||||||
_, err = db.pool.Exec(ctx, `
|
// _, err = db.pool.Exec(ctx, `
|
||||||
update recipes set
|
// update recipes set
|
||||||
name = $2, cuisine = $3, prep_time_minutes = $4, cook_time_minutes = $5,
|
// name = $2, cuisine = $3, prep_time_minutes = $4, cook_time_minutes = $5,
|
||||||
servings = $6, ingredients = $7::jsonb, instructions = $8::jsonb,
|
// servings = $6, ingredients = $7::jsonb, instructions = $8::jsonb,
|
||||||
tags = $9, rating = $10, notes = $11
|
// tags = $9, rating = $10, notes = $11
|
||||||
where id = $1
|
// where id = $1
|
||||||
`, id, r.Name, nullStr(r.Cuisine), r.PrepTimeMinutes, r.CookTimeMinutes, r.Servings,
|
// `, id, r.Name, nullStr(r.Cuisine), r.PrepTimeMinutes, r.CookTimeMinutes, r.Servings,
|
||||||
ingredients, instructions, r.Tags, r.Rating, nullStr(r.Notes))
|
// ingredients, instructions, r.Tags, r.Rating, nullStr(r.Notes))
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("update recipe: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("update recipe: %w", err)
|
||||||
}
|
// }
|
||||||
return db.GetRecipe(ctx, id)
|
// return db.GetRecipe(ctx, id)
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) CreateMealPlan(ctx context.Context, weekStart time.Time, entries []ext.MealPlanInput) ([]ext.MealPlanEntry, error) {
|
// func (db *DB) CreateMealPlan(ctx context.Context, weekStart time.Time, entries []ext.MealPlanInput) ([]ext.MealPlanEntry, error) {
|
||||||
if _, err := db.pool.Exec(ctx, `delete from meal_plans where week_start = $1`, weekStart); err != nil {
|
// if _, err := db.pool.Exec(ctx, `delete from meal_plans where week_start = $1`, weekStart); err != nil {
|
||||||
return nil, fmt.Errorf("clear meal plan: %w", err)
|
// return nil, fmt.Errorf("clear meal plan: %w", err)
|
||||||
}
|
// }
|
||||||
|
|
||||||
var results []ext.MealPlanEntry
|
// var results []ext.MealPlanEntry
|
||||||
for _, e := range entries {
|
// for _, e := range entries {
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into meal_plans (week_start, day_of_week, meal_type, recipe_id, custom_meal, servings, notes)
|
// insert into meal_plans (week_start, day_of_week, meal_type, recipe_id, custom_meal, servings, notes)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7)
|
// values ($1, $2, $3, $4, $5, $6, $7)
|
||||||
returning id, created_at
|
// returning id, created_at
|
||||||
`, weekStart, e.DayOfWeek, e.MealType, e.RecipeID, nullStr(e.CustomMeal), e.Servings, nullStr(e.Notes))
|
// `, weekStart, e.DayOfWeek, e.MealType, e.RecipeID, nullStr(e.CustomMeal), e.Servings, nullStr(e.Notes))
|
||||||
|
|
||||||
entry := ext.MealPlanEntry{
|
// entry := ext.MealPlanEntry{
|
||||||
WeekStart: weekStart,
|
// WeekStart: weekStart,
|
||||||
DayOfWeek: e.DayOfWeek,
|
// DayOfWeek: e.DayOfWeek,
|
||||||
MealType: e.MealType,
|
// MealType: e.MealType,
|
||||||
RecipeID: e.RecipeID,
|
// RecipeID: e.RecipeID,
|
||||||
CustomMeal: e.CustomMeal,
|
// CustomMeal: e.CustomMeal,
|
||||||
Servings: e.Servings,
|
// Servings: e.Servings,
|
||||||
Notes: e.Notes,
|
// Notes: e.Notes,
|
||||||
}
|
// }
|
||||||
var model generatedmodels.ModelPublicMealPlans
|
// var model generatedmodels.ModelPublicMealPlans
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("insert meal plan entry: %w", err)
|
// return nil, fmt.Errorf("insert meal plan entry: %w", err)
|
||||||
}
|
// }
|
||||||
entry.ID = model.ID.UUID()
|
// entry.ID = model.ID.UUID()
|
||||||
entry.CreatedAt = model.CreatedAt.Time()
|
// entry.CreatedAt = model.CreatedAt.Time()
|
||||||
results = append(results, entry)
|
// results = append(results, entry)
|
||||||
}
|
// }
|
||||||
return results, nil
|
// return results, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GetMealPlan(ctx context.Context, weekStart time.Time) ([]ext.MealPlanEntry, error) {
|
// func (db *DB) GetMealPlan(ctx context.Context, weekStart time.Time) ([]ext.MealPlanEntry, error) {
|
||||||
rows, err := db.pool.Query(ctx, `
|
// rows, err := db.pool.Query(ctx, `
|
||||||
select mp.id, mp.week_start, mp.day_of_week, mp.meal_type, mp.recipe_id, r.name, mp.custom_meal, mp.servings, mp.notes, mp.created_at
|
// select mp.id, mp.week_start, mp.day_of_week, mp.meal_type, mp.recipe_id, r.name, mp.custom_meal, mp.servings, mp.notes, mp.created_at
|
||||||
from meal_plans mp
|
// from meal_plans mp
|
||||||
left join recipes r on r.id = mp.recipe_id
|
// left join recipes r on r.id = mp.recipe_id
|
||||||
where mp.week_start = $1
|
// where mp.week_start = $1
|
||||||
order by
|
// order by
|
||||||
case mp.day_of_week
|
// case mp.day_of_week
|
||||||
when 'monday' then 1 when 'tuesday' then 2 when 'wednesday' then 3
|
// when 'monday' then 1 when 'tuesday' then 2 when 'wednesday' then 3
|
||||||
when 'thursday' then 4 when 'friday' then 5 when 'saturday' then 6
|
// when 'thursday' then 4 when 'friday' then 5 when 'saturday' then 6
|
||||||
when 'sunday' then 7 else 8
|
// when 'sunday' then 7 else 8
|
||||||
end,
|
// end,
|
||||||
case mp.meal_type
|
// case mp.meal_type
|
||||||
when 'breakfast' then 1 when 'lunch' then 2 when 'dinner' then 3
|
// when 'breakfast' then 1 when 'lunch' then 2 when 'dinner' then 3
|
||||||
when 'snack' then 4 else 5
|
// when 'snack' then 4 else 5
|
||||||
end
|
// end
|
||||||
`, weekStart)
|
// `, weekStart)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, fmt.Errorf("get meal plan: %w", err)
|
// return nil, fmt.Errorf("get meal plan: %w", err)
|
||||||
}
|
// }
|
||||||
defer rows.Close()
|
// defer rows.Close()
|
||||||
|
|
||||||
var entries []ext.MealPlanEntry
|
// var entries []ext.MealPlanEntry
|
||||||
for rows.Next() {
|
// for rows.Next() {
|
||||||
var model generatedmodels.ModelPublicMealPlans
|
// var model generatedmodels.ModelPublicMealPlans
|
||||||
var recipeName *string
|
// var recipeName *string
|
||||||
if err := rows.Scan(&model.ID, &model.WeekStart, &model.DayOfWeek, &model.MealType, &model.RecipeID, &recipeName, &model.CustomMeal, &model.Servings, &model.Notes, &model.CreatedAt); err != nil {
|
// if err := rows.Scan(&model.ID, &model.WeekStart, &model.DayOfWeek, &model.MealType, &model.RecipeID, &recipeName, &model.CustomMeal, &model.Servings, &model.Notes, &model.CreatedAt); err != nil {
|
||||||
return nil, fmt.Errorf("scan meal plan entry: %w", err)
|
// return nil, fmt.Errorf("scan meal plan entry: %w", err)
|
||||||
}
|
// }
|
||||||
entries = append(entries, mealPlanEntryFromModel(model, strVal(recipeName)))
|
// entries = append(entries, mealPlanEntryFromModel(model, strVal(recipeName)))
|
||||||
}
|
// }
|
||||||
return entries, rows.Err()
|
// return entries, rows.Err()
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (db *DB) GenerateShoppingList(ctx context.Context, weekStart time.Time) (ext.ShoppingList, error) {
|
// func (db *DB) GenerateShoppingList(ctx context.Context, weekStart time.Time) (ext.ShoppingList, error) {
|
||||||
entries, err := db.GetMealPlan(ctx, weekStart)
|
// entries, err := db.GetMealPlan(ctx, weekStart)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.ShoppingList{}, err
|
// return ext.ShoppingList{}, err
|
||||||
}
|
// }
|
||||||
|
|
||||||
recipeIDs := map[uuid.UUID]bool{}
|
// recipeIDs := map[uuid.UUID]bool{}
|
||||||
for _, e := range entries {
|
// for _, e := range entries {
|
||||||
if e.RecipeID != nil {
|
// if e.RecipeID != nil {
|
||||||
recipeIDs[*e.RecipeID] = true
|
// recipeIDs[*e.RecipeID] = true
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
aggregated := map[string]*ext.ShoppingItem{}
|
// aggregated := map[string]*ext.ShoppingItem{}
|
||||||
for id := range recipeIDs {
|
// for id := range recipeIDs {
|
||||||
recipe, err := db.GetRecipe(ctx, id)
|
// recipe, err := db.GetRecipe(ctx, id)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
continue
|
// continue
|
||||||
}
|
// }
|
||||||
for _, ing := range recipe.Ingredients {
|
// for _, ing := range recipe.Ingredients {
|
||||||
key := strings.ToLower(ing.Name)
|
// key := strings.ToLower(ing.Name)
|
||||||
if existing, ok := aggregated[key]; ok {
|
// if existing, ok := aggregated[key]; ok {
|
||||||
if ing.Quantity != "" {
|
// if ing.Quantity != "" {
|
||||||
existing.Quantity += "+" + ing.Quantity
|
// existing.Quantity += "+" + ing.Quantity
|
||||||
}
|
// }
|
||||||
} else {
|
// } else {
|
||||||
recipeIDCopy := id
|
// recipeIDCopy := id
|
||||||
aggregated[key] = &ext.ShoppingItem{
|
// aggregated[key] = &ext.ShoppingItem{
|
||||||
Name: ing.Name,
|
// Name: ing.Name,
|
||||||
Quantity: ing.Quantity,
|
// Quantity: ing.Quantity,
|
||||||
Unit: ing.Unit,
|
// Unit: ing.Unit,
|
||||||
Purchased: false,
|
// Purchased: false,
|
||||||
RecipeID: &recipeIDCopy,
|
// RecipeID: &recipeIDCopy,
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
items := make([]ext.ShoppingItem, 0, len(aggregated))
|
// items := make([]ext.ShoppingItem, 0, len(aggregated))
|
||||||
for _, item := range aggregated {
|
// for _, item := range aggregated {
|
||||||
items = append(items, *item)
|
// items = append(items, *item)
|
||||||
}
|
// }
|
||||||
|
|
||||||
itemsJSON, err := json.Marshal(items)
|
// itemsJSON, err := json.Marshal(items)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return ext.ShoppingList{}, fmt.Errorf("marshal shopping items: %w", err)
|
// return ext.ShoppingList{}, fmt.Errorf("marshal shopping items: %w", err)
|
||||||
}
|
// }
|
||||||
|
|
||||||
row := db.pool.QueryRow(ctx, `
|
// row := db.pool.QueryRow(ctx, `
|
||||||
insert into shopping_lists (week_start, items)
|
// insert into shopping_lists (week_start, items)
|
||||||
values ($1, $2::jsonb)
|
// values ($1, $2::jsonb)
|
||||||
on conflict (week_start) do update set items = excluded.items, updated_at = now()
|
// on conflict (week_start) do update set items = excluded.items, updated_at = now()
|
||||||
returning id, created_at, updated_at
|
// returning id, created_at, updated_at
|
||||||
`, weekStart, itemsJSON)
|
// `, weekStart, itemsJSON)
|
||||||
|
|
||||||
var model generatedmodels.ModelPublicShoppingLists
|
// var model generatedmodels.ModelPublicShoppingLists
|
||||||
list := ext.ShoppingList{WeekStart: weekStart, Items: items}
|
// list := ext.ShoppingList{WeekStart: weekStart, Items: items}
|
||||||
if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// if err := row.Scan(&model.ID, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.ShoppingList{}, fmt.Errorf("upsert shopping list: %w", err)
|
// return ext.ShoppingList{}, fmt.Errorf("upsert shopping list: %w", err)
|
||||||
}
|
// }
|
||||||
list.ID = model.ID.UUID()
|
// list.ID = model.ID.UUID()
|
||||||
list.CreatedAt = model.CreatedAt.Time()
|
// list.CreatedAt = model.CreatedAt.Time()
|
||||||
list.UpdatedAt = model.UpdatedAt.Time()
|
// list.UpdatedAt = model.UpdatedAt.Time()
|
||||||
return list, nil
|
// return list, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
func scanRecipeRow(rows interface{ Scan(...any) error }) (ext.Recipe, error) {
|
// func scanRecipeRow(rows interface{ Scan(...any) error }) (ext.Recipe, error) {
|
||||||
var model generatedmodels.ModelPublicRecipes
|
// var model generatedmodels.ModelPublicRecipes
|
||||||
var tags []string
|
// var tags []string
|
||||||
if err := rows.Scan(&model.ID, &model.Name, &model.Cuisine, &model.PrepTimeMinutes, &model.CookTimeMinutes, &model.Servings,
|
// if err := rows.Scan(&model.ID, &model.Name, &model.Cuisine, &model.PrepTimeMinutes, &model.CookTimeMinutes, &model.Servings,
|
||||||
&model.Ingredients, &model.Instructions, &tags, &model.Rating, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
// &model.Ingredients, &model.Instructions, &tags, &model.Rating, &model.Notes, &model.CreatedAt, &model.UpdatedAt); err != nil {
|
||||||
return ext.Recipe{}, fmt.Errorf("scan recipe: %w", err)
|
// return ext.Recipe{}, fmt.Errorf("scan recipe: %w", err)
|
||||||
}
|
// }
|
||||||
if tags == nil {
|
// if tags == nil {
|
||||||
tags = []string{}
|
// tags = []string{}
|
||||||
}
|
// }
|
||||||
return recipeFromModel(model, tags), nil
|
// return recipeFromModel(model, tags), nil
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -81,342 +81,342 @@ func storedFileFromModel(m generatedmodels.ModelPublicStoredFiles) ext.StoredFil
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func maintenanceTaskFromModel(m generatedmodels.ModelPublicMaintenanceTasks) ext.MaintenanceTask {
|
// func maintenanceTaskFromModel(m generatedmodels.ModelPublicMaintenanceTasks) ext.MaintenanceTask {
|
||||||
var frequencyDays *int
|
// var frequencyDays *int
|
||||||
if m.FrequencyDays.Valid {
|
// if m.FrequencyDays.Valid {
|
||||||
n := int(m.FrequencyDays.Int64())
|
// n := int(m.FrequencyDays.Int64())
|
||||||
frequencyDays = &n
|
// frequencyDays = &n
|
||||||
}
|
// }
|
||||||
|
|
||||||
var lastCompleted *time.Time
|
// var lastCompleted *time.Time
|
||||||
if m.LastCompleted.Valid {
|
// if m.LastCompleted.Valid {
|
||||||
t := m.LastCompleted.Time()
|
// t := m.LastCompleted.Time()
|
||||||
lastCompleted = &t
|
// lastCompleted = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
var nextDue *time.Time
|
// var nextDue *time.Time
|
||||||
if m.NextDue.Valid {
|
// if m.NextDue.Valid {
|
||||||
t := m.NextDue.Time()
|
// t := m.NextDue.Time()
|
||||||
nextDue = &t
|
// nextDue = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.MaintenanceTask{
|
// return ext.MaintenanceTask{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
Name: m.Name.String(),
|
// Name: m.Name.String(),
|
||||||
Category: m.Category.String(),
|
// Category: m.Category.String(),
|
||||||
FrequencyDays: frequencyDays,
|
// FrequencyDays: frequencyDays,
|
||||||
LastCompleted: lastCompleted,
|
// LastCompleted: lastCompleted,
|
||||||
NextDue: nextDue,
|
// NextDue: nextDue,
|
||||||
Priority: m.Priority.String(),
|
// Priority: m.Priority.String(),
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
UpdatedAt: m.UpdatedAt.Time(),
|
// UpdatedAt: m.UpdatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func maintenanceLogFromModel(m generatedmodels.ModelPublicMaintenanceLogs) ext.MaintenanceLog {
|
// func maintenanceLogFromModel(m generatedmodels.ModelPublicMaintenanceLogs) ext.MaintenanceLog {
|
||||||
var cost *float64
|
// var cost *float64
|
||||||
if m.Cost.Valid {
|
// if m.Cost.Valid {
|
||||||
v := m.Cost.Float64()
|
// v := m.Cost.Float64()
|
||||||
cost = &v
|
// cost = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.MaintenanceLog{
|
// return ext.MaintenanceLog{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
TaskID: m.TaskID.UUID(),
|
// TaskID: m.TaskID.UUID(),
|
||||||
CompletedAt: m.CompletedAt.Time(),
|
// CompletedAt: m.CompletedAt.Time(),
|
||||||
PerformedBy: m.PerformedBy.String(),
|
// PerformedBy: m.PerformedBy.String(),
|
||||||
Cost: cost,
|
// Cost: cost,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
NextAction: m.NextAction.String(),
|
// NextAction: m.NextAction.String(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func householdItemFromModel(m generatedmodels.ModelPublicHouseholdItems) ext.HouseholdItem {
|
// func householdItemFromModel(m generatedmodels.ModelPublicHouseholdItems) ext.HouseholdItem {
|
||||||
details := map[string]any{}
|
// details := map[string]any{}
|
||||||
if len(m.Details) > 0 {
|
// if len(m.Details) > 0 {
|
||||||
if err := json.Unmarshal(m.Details, &details); err != nil {
|
// if err := json.Unmarshal(m.Details, &details); err != nil {
|
||||||
details = map[string]any{}
|
// details = map[string]any{}
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.HouseholdItem{
|
// return ext.HouseholdItem{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
Name: m.Name.String(),
|
// Name: m.Name.String(),
|
||||||
Category: m.Category.String(),
|
// Category: m.Category.String(),
|
||||||
Location: m.Location.String(),
|
// Location: m.Location.String(),
|
||||||
Details: details,
|
// Details: details,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
UpdatedAt: m.UpdatedAt.Time(),
|
// UpdatedAt: m.UpdatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func householdVendorFromModel(m generatedmodels.ModelPublicHouseholdVendors) ext.HouseholdVendor {
|
// func householdVendorFromModel(m generatedmodels.ModelPublicHouseholdVendors) ext.HouseholdVendor {
|
||||||
var rating *int
|
// var rating *int
|
||||||
if m.Rating.Valid {
|
// if m.Rating.Valid {
|
||||||
v := int(m.Rating.Int64())
|
// v := int(m.Rating.Int64())
|
||||||
rating = &v
|
// rating = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
var lastUsed *time.Time
|
// var lastUsed *time.Time
|
||||||
if m.LastUsed.Valid {
|
// if m.LastUsed.Valid {
|
||||||
t := m.LastUsed.Time()
|
// t := m.LastUsed.Time()
|
||||||
lastUsed = &t
|
// lastUsed = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.HouseholdVendor{
|
// return ext.HouseholdVendor{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
Name: m.Name.String(),
|
// Name: m.Name.String(),
|
||||||
ServiceType: m.ServiceType.String(),
|
// ServiceType: m.ServiceType.String(),
|
||||||
Phone: m.Phone.String(),
|
// Phone: m.Phone.String(),
|
||||||
Email: m.Email.String(),
|
// Email: m.Email.String(),
|
||||||
Website: m.Website.String(),
|
// Website: m.Website.String(),
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
Rating: rating,
|
// Rating: rating,
|
||||||
LastUsed: lastUsed,
|
// LastUsed: lastUsed,
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func familyMemberFromModel(m generatedmodels.ModelPublicFamilyMembers) ext.FamilyMember {
|
// func familyMemberFromModel(m generatedmodels.ModelPublicFamilyMembers) ext.FamilyMember {
|
||||||
var birthDate *time.Time
|
// var birthDate *time.Time
|
||||||
if m.BirthDate.Valid {
|
// if m.BirthDate.Valid {
|
||||||
t := m.BirthDate.Time()
|
// t := m.BirthDate.Time()
|
||||||
birthDate = &t
|
// birthDate = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.FamilyMember{
|
// return ext.FamilyMember{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
Name: m.Name.String(),
|
// Name: m.Name.String(),
|
||||||
Relationship: m.Relationship.String(),
|
// Relationship: m.Relationship.String(),
|
||||||
BirthDate: birthDate,
|
// BirthDate: birthDate,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func activityFromModel(m generatedmodels.ModelPublicActivities, memberName string) ext.Activity {
|
// func activityFromModel(m generatedmodels.ModelPublicActivities, memberName string) ext.Activity {
|
||||||
var familyMemberID *uuid.UUID
|
// var familyMemberID *uuid.UUID
|
||||||
if m.FamilyMemberID.Valid {
|
// if m.FamilyMemberID.Valid {
|
||||||
id := m.FamilyMemberID.UUID()
|
// id := m.FamilyMemberID.UUID()
|
||||||
familyMemberID = &id
|
// familyMemberID = &id
|
||||||
}
|
// }
|
||||||
|
|
||||||
var startDate *time.Time
|
// var startDate *time.Time
|
||||||
if m.StartDate.Valid {
|
// if m.StartDate.Valid {
|
||||||
t := m.StartDate.Time()
|
// t := m.StartDate.Time()
|
||||||
startDate = &t
|
// startDate = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
var endDate *time.Time
|
// var endDate *time.Time
|
||||||
if m.EndDate.Valid {
|
// if m.EndDate.Valid {
|
||||||
t := m.EndDate.Time()
|
// t := m.EndDate.Time()
|
||||||
endDate = &t
|
// endDate = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.Activity{
|
// return ext.Activity{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
FamilyMemberID: familyMemberID,
|
// FamilyMemberID: familyMemberID,
|
||||||
MemberName: memberName,
|
// MemberName: memberName,
|
||||||
Title: m.Title.String(),
|
// Title: m.Title.String(),
|
||||||
ActivityType: m.ActivityType.String(),
|
// ActivityType: m.ActivityType.String(),
|
||||||
DayOfWeek: m.DayOfWeek.String(),
|
// DayOfWeek: m.DayOfWeek.String(),
|
||||||
StartTime: m.StartTime.String(),
|
// StartTime: m.StartTime.String(),
|
||||||
EndTime: m.EndTime.String(),
|
// EndTime: m.EndTime.String(),
|
||||||
StartDate: startDate,
|
// StartDate: startDate,
|
||||||
EndDate: endDate,
|
// EndDate: endDate,
|
||||||
Location: m.Location.String(),
|
// Location: m.Location.String(),
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func importantDateFromModel(m generatedmodels.ModelPublicImportantDates, memberName string) ext.ImportantDate {
|
// func importantDateFromModel(m generatedmodels.ModelPublicImportantDates, memberName string) ext.ImportantDate {
|
||||||
var familyMemberID *uuid.UUID
|
// var familyMemberID *uuid.UUID
|
||||||
if m.FamilyMemberID.Valid {
|
// if m.FamilyMemberID.Valid {
|
||||||
id := m.FamilyMemberID.UUID()
|
// id := m.FamilyMemberID.UUID()
|
||||||
familyMemberID = &id
|
// familyMemberID = &id
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.ImportantDate{
|
// return ext.ImportantDate{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
FamilyMemberID: familyMemberID,
|
// FamilyMemberID: familyMemberID,
|
||||||
MemberName: memberName,
|
// MemberName: memberName,
|
||||||
Title: m.Title.String(),
|
// Title: m.Title.String(),
|
||||||
DateValue: m.DateValue.Time(),
|
// DateValue: m.DateValue.Time(),
|
||||||
RecurringYearly: m.RecurringYearly,
|
// RecurringYearly: m.RecurringYearly,
|
||||||
ReminderDaysBefore: int(m.ReminderDaysBefore),
|
// ReminderDaysBefore: int(m.ReminderDaysBefore),
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func professionalContactFromModel(m generatedmodels.ModelPublicProfessionalContacts, tags []string) ext.ProfessionalContact {
|
// func professionalContactFromModel(m generatedmodels.ModelPublicProfessionalContacts, tags []string) ext.ProfessionalContact {
|
||||||
var lastContacted *time.Time
|
// var lastContacted *time.Time
|
||||||
if m.LastContacted.Valid {
|
// if m.LastContacted.Valid {
|
||||||
t := m.LastContacted.Time()
|
// t := m.LastContacted.Time()
|
||||||
lastContacted = &t
|
// lastContacted = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
var followUpDate *time.Time
|
// var followUpDate *time.Time
|
||||||
if m.FollowUpDate.Valid {
|
// if m.FollowUpDate.Valid {
|
||||||
t := m.FollowUpDate.Time()
|
// t := m.FollowUpDate.Time()
|
||||||
followUpDate = &t
|
// followUpDate = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.ProfessionalContact{
|
// return ext.ProfessionalContact{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
Name: m.Name.String(),
|
// Name: m.Name.String(),
|
||||||
Company: m.Company.String(),
|
// Company: m.Company.String(),
|
||||||
Title: m.Title.String(),
|
// Title: m.Title.String(),
|
||||||
Email: m.Email.String(),
|
// Email: m.Email.String(),
|
||||||
Phone: m.Phone.String(),
|
// Phone: m.Phone.String(),
|
||||||
LinkedInURL: m.LinkedinURL.String(),
|
// LinkedInURL: m.LinkedinURL.String(),
|
||||||
HowWeMet: m.HowWeMet.String(),
|
// HowWeMet: m.HowWeMet.String(),
|
||||||
Tags: tags,
|
// Tags: tags,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
LastContacted: lastContacted,
|
// LastContacted: lastContacted,
|
||||||
FollowUpDate: followUpDate,
|
// FollowUpDate: followUpDate,
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
UpdatedAt: m.UpdatedAt.Time(),
|
// UpdatedAt: m.UpdatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func contactInteractionFromModel(m generatedmodels.ModelPublicContactInteractions) ext.ContactInteraction {
|
// func contactInteractionFromModel(m generatedmodels.ModelPublicContactInteractions) ext.ContactInteraction {
|
||||||
return ext.ContactInteraction{
|
// return ext.ContactInteraction{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
ContactID: m.ContactID.UUID(),
|
// ContactID: m.ContactID.UUID(),
|
||||||
InteractionType: m.InteractionType.String(),
|
// InteractionType: m.InteractionType.String(),
|
||||||
OccurredAt: m.OccurredAt.Time(),
|
// OccurredAt: m.OccurredAt.Time(),
|
||||||
Summary: m.Summary.String(),
|
// Summary: m.Summary.String(),
|
||||||
FollowUpNeeded: m.FollowUpNeeded,
|
// FollowUpNeeded: m.FollowUpNeeded,
|
||||||
FollowUpNotes: m.FollowUpNotes.String(),
|
// FollowUpNotes: m.FollowUpNotes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func opportunityFromModel(m generatedmodels.ModelPublicOpportunities) ext.Opportunity {
|
// func opportunityFromModel(m generatedmodels.ModelPublicOpportunities) ext.Opportunity {
|
||||||
var contactID *uuid.UUID
|
// var contactID *uuid.UUID
|
||||||
if m.ContactID.Valid {
|
// if m.ContactID.Valid {
|
||||||
id := m.ContactID.UUID()
|
// id := m.ContactID.UUID()
|
||||||
contactID = &id
|
// contactID = &id
|
||||||
}
|
// }
|
||||||
|
|
||||||
var value *float64
|
// var value *float64
|
||||||
if m.Value.Valid {
|
// if m.Value.Valid {
|
||||||
v := m.Value.Float64()
|
// v := m.Value.Float64()
|
||||||
value = &v
|
// value = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
var expectedCloseDate *time.Time
|
// var expectedCloseDate *time.Time
|
||||||
if m.ExpectedCloseDate.Valid {
|
// if m.ExpectedCloseDate.Valid {
|
||||||
t := m.ExpectedCloseDate.Time()
|
// t := m.ExpectedCloseDate.Time()
|
||||||
expectedCloseDate = &t
|
// expectedCloseDate = &t
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.Opportunity{
|
// return ext.Opportunity{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
ContactID: contactID,
|
// ContactID: contactID,
|
||||||
Title: m.Title.String(),
|
// Title: m.Title.String(),
|
||||||
Description: m.Description.String(),
|
// Description: m.Description.String(),
|
||||||
Stage: m.Stage.String(),
|
// Stage: m.Stage.String(),
|
||||||
Value: value,
|
// Value: value,
|
||||||
ExpectedCloseDate: expectedCloseDate,
|
// ExpectedCloseDate: expectedCloseDate,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
UpdatedAt: m.UpdatedAt.Time(),
|
// UpdatedAt: m.UpdatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func recipeFromModel(m generatedmodels.ModelPublicRecipes, tags []string) ext.Recipe {
|
// func recipeFromModel(m generatedmodels.ModelPublicRecipes, tags []string) ext.Recipe {
|
||||||
var prepTimeMinutes *int
|
// var prepTimeMinutes *int
|
||||||
if m.PrepTimeMinutes.Valid {
|
// if m.PrepTimeMinutes.Valid {
|
||||||
v := int(m.PrepTimeMinutes.Int64())
|
// v := int(m.PrepTimeMinutes.Int64())
|
||||||
prepTimeMinutes = &v
|
// prepTimeMinutes = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
var cookTimeMinutes *int
|
// var cookTimeMinutes *int
|
||||||
if m.CookTimeMinutes.Valid {
|
// if m.CookTimeMinutes.Valid {
|
||||||
v := int(m.CookTimeMinutes.Int64())
|
// v := int(m.CookTimeMinutes.Int64())
|
||||||
cookTimeMinutes = &v
|
// cookTimeMinutes = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
var servings *int
|
// var servings *int
|
||||||
if m.Servings.Valid {
|
// if m.Servings.Valid {
|
||||||
v := int(m.Servings.Int64())
|
// v := int(m.Servings.Int64())
|
||||||
servings = &v
|
// servings = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
var rating *int
|
// var rating *int
|
||||||
if m.Rating.Valid {
|
// if m.Rating.Valid {
|
||||||
v := int(m.Rating.Int64())
|
// v := int(m.Rating.Int64())
|
||||||
rating = &v
|
// rating = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
recipe := ext.Recipe{
|
// recipe := ext.Recipe{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
Name: m.Name.String(),
|
// Name: m.Name.String(),
|
||||||
Cuisine: m.Cuisine.String(),
|
// Cuisine: m.Cuisine.String(),
|
||||||
PrepTimeMinutes: prepTimeMinutes,
|
// PrepTimeMinutes: prepTimeMinutes,
|
||||||
CookTimeMinutes: cookTimeMinutes,
|
// CookTimeMinutes: cookTimeMinutes,
|
||||||
Servings: servings,
|
// Servings: servings,
|
||||||
Tags: tags,
|
// Tags: tags,
|
||||||
Rating: rating,
|
// Rating: rating,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
UpdatedAt: m.UpdatedAt.Time(),
|
// UpdatedAt: m.UpdatedAt.Time(),
|
||||||
}
|
// }
|
||||||
|
|
||||||
if err := json.Unmarshal(m.Ingredients, &recipe.Ingredients); err != nil {
|
// if err := json.Unmarshal(m.Ingredients, &recipe.Ingredients); err != nil {
|
||||||
recipe.Ingredients = []ext.Ingredient{}
|
// recipe.Ingredients = []ext.Ingredient{}
|
||||||
}
|
// }
|
||||||
if err := json.Unmarshal(m.Instructions, &recipe.Instructions); err != nil {
|
// if err := json.Unmarshal(m.Instructions, &recipe.Instructions); err != nil {
|
||||||
recipe.Instructions = []string{}
|
// recipe.Instructions = []string{}
|
||||||
}
|
// }
|
||||||
return recipe
|
// return recipe
|
||||||
}
|
// }
|
||||||
|
|
||||||
func mealPlanEntryFromModel(m generatedmodels.ModelPublicMealPlans, recipeName string) ext.MealPlanEntry {
|
// func mealPlanEntryFromModel(m generatedmodels.ModelPublicMealPlans, recipeName string) ext.MealPlanEntry {
|
||||||
var recipeID *uuid.UUID
|
// var recipeID *uuid.UUID
|
||||||
if m.RecipeID.Valid {
|
// if m.RecipeID.Valid {
|
||||||
id := m.RecipeID.UUID()
|
// id := m.RecipeID.UUID()
|
||||||
recipeID = &id
|
// recipeID = &id
|
||||||
}
|
// }
|
||||||
|
|
||||||
var servings *int
|
// var servings *int
|
||||||
if m.Servings.Valid {
|
// if m.Servings.Valid {
|
||||||
v := int(m.Servings.Int64())
|
// v := int(m.Servings.Int64())
|
||||||
servings = &v
|
// servings = &v
|
||||||
}
|
// }
|
||||||
|
|
||||||
return ext.MealPlanEntry{
|
// return ext.MealPlanEntry{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
WeekStart: m.WeekStart.Time(),
|
// WeekStart: m.WeekStart.Time(),
|
||||||
DayOfWeek: m.DayOfWeek.String(),
|
// DayOfWeek: m.DayOfWeek.String(),
|
||||||
MealType: m.MealType.String(),
|
// MealType: m.MealType.String(),
|
||||||
RecipeID: recipeID,
|
// RecipeID: recipeID,
|
||||||
RecipeName: recipeName,
|
// RecipeName: recipeName,
|
||||||
CustomMeal: m.CustomMeal.String(),
|
// CustomMeal: m.CustomMeal.String(),
|
||||||
Servings: servings,
|
// Servings: servings,
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
func shoppingListFromModel(m generatedmodels.ModelPublicShoppingLists) ext.ShoppingList {
|
// func shoppingListFromModel(m generatedmodels.ModelPublicShoppingLists) ext.ShoppingList {
|
||||||
list := ext.ShoppingList{
|
// list := ext.ShoppingList{
|
||||||
ID: m.ID.UUID(),
|
// ID: m.ID.UUID(),
|
||||||
WeekStart: m.WeekStart.Time(),
|
// WeekStart: m.WeekStart.Time(),
|
||||||
Notes: m.Notes.String(),
|
// Notes: m.Notes.String(),
|
||||||
CreatedAt: m.CreatedAt.Time(),
|
// CreatedAt: m.CreatedAt.Time(),
|
||||||
UpdatedAt: m.UpdatedAt.Time(),
|
// UpdatedAt: m.UpdatedAt.Time(),
|
||||||
}
|
// }
|
||||||
if err := json.Unmarshal(m.Items, &list.Items); err != nil {
|
// if err := json.Unmarshal(m.Items, &list.Items); err != nil {
|
||||||
list.Items = []ext.ShoppingItem{}
|
// list.Items = []ext.ShoppingItem{}
|
||||||
}
|
// }
|
||||||
return list
|
// return list
|
||||||
}
|
// }
|
||||||
|
|
||||||
func planFromModel(m generatedmodels.ModelPublicPlans, tags []string) ext.Plan {
|
func planFromModel(m generatedmodels.ModelPublicPlans, tags []string) ext.Plan {
|
||||||
var projectID *uuid.UUID
|
var projectID *uuid.UUID
|
||||||
|
|||||||
@@ -1,212 +1,212 @@
|
|||||||
package tools
|
package tools
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
// "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/store"
|
// "git.warky.dev/wdevs/amcs/internal/store"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
type CalendarTool struct {
|
// type CalendarTool struct {
|
||||||
store *store.DB
|
// store *store.DB
|
||||||
}
|
// }
|
||||||
|
|
||||||
func NewCalendarTool(db *store.DB) *CalendarTool {
|
// func NewCalendarTool(db *store.DB) *CalendarTool {
|
||||||
return &CalendarTool{store: db}
|
// return &CalendarTool{store: db}
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_family_member
|
// // add_family_member
|
||||||
|
|
||||||
type AddFamilyMemberInput struct {
|
// type AddFamilyMemberInput struct {
|
||||||
Name string `json:"name" jsonschema:"person's name"`
|
// Name string `json:"name" jsonschema:"person's name"`
|
||||||
Relationship string `json:"relationship,omitempty" jsonschema:"e.g. self, spouse, child, parent"`
|
// Relationship string `json:"relationship,omitempty" jsonschema:"e.g. self, spouse, child, parent"`
|
||||||
BirthDate *time.Time `json:"birth_date,omitempty"`
|
// BirthDate *time.Time `json:"birth_date,omitempty"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddFamilyMemberOutput struct {
|
// type AddFamilyMemberOutput struct {
|
||||||
Member ext.FamilyMember `json:"member"`
|
// Member ext.FamilyMember `json:"member"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) AddMember(ctx context.Context, _ *mcp.CallToolRequest, in AddFamilyMemberInput) (*mcp.CallToolResult, AddFamilyMemberOutput, error) {
|
// func (t *CalendarTool) AddMember(ctx context.Context, _ *mcp.CallToolRequest, in AddFamilyMemberInput) (*mcp.CallToolResult, AddFamilyMemberOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, AddFamilyMemberOutput{}, errRequiredField("name")
|
// return nil, AddFamilyMemberOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
member, err := t.store.AddFamilyMember(ctx, ext.FamilyMember{
|
// member, err := t.store.AddFamilyMember(ctx, ext.FamilyMember{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
Relationship: strings.TrimSpace(in.Relationship),
|
// Relationship: strings.TrimSpace(in.Relationship),
|
||||||
BirthDate: in.BirthDate,
|
// BirthDate: in.BirthDate,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddFamilyMemberOutput{}, err
|
// return nil, AddFamilyMemberOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddFamilyMemberOutput{Member: member}, nil
|
// return nil, AddFamilyMemberOutput{Member: member}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// list_family_members
|
// // list_family_members
|
||||||
|
|
||||||
type ListFamilyMembersInput struct{}
|
// type ListFamilyMembersInput struct{}
|
||||||
|
|
||||||
type ListFamilyMembersOutput struct {
|
// type ListFamilyMembersOutput struct {
|
||||||
Members []ext.FamilyMember `json:"members"`
|
// Members []ext.FamilyMember `json:"members"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) ListMembers(ctx context.Context, _ *mcp.CallToolRequest, _ ListFamilyMembersInput) (*mcp.CallToolResult, ListFamilyMembersOutput, error) {
|
// func (t *CalendarTool) ListMembers(ctx context.Context, _ *mcp.CallToolRequest, _ ListFamilyMembersInput) (*mcp.CallToolResult, ListFamilyMembersOutput, error) {
|
||||||
members, err := t.store.ListFamilyMembers(ctx)
|
// members, err := t.store.ListFamilyMembers(ctx)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, ListFamilyMembersOutput{}, err
|
// return nil, ListFamilyMembersOutput{}, err
|
||||||
}
|
// }
|
||||||
if members == nil {
|
// if members == nil {
|
||||||
members = []ext.FamilyMember{}
|
// members = []ext.FamilyMember{}
|
||||||
}
|
// }
|
||||||
return nil, ListFamilyMembersOutput{Members: members}, nil
|
// return nil, ListFamilyMembersOutput{Members: members}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_activity
|
// // add_activity
|
||||||
|
|
||||||
type AddActivityInput struct {
|
// type AddActivityInput struct {
|
||||||
Title string `json:"title" jsonschema:"activity title"`
|
// Title string `json:"title" jsonschema:"activity title"`
|
||||||
ActivityType string `json:"activity_type,omitempty" jsonschema:"e.g. sports, medical, school, social"`
|
// ActivityType string `json:"activity_type,omitempty" jsonschema:"e.g. sports, medical, school, social"`
|
||||||
FamilyMemberID *uuid.UUID `json:"family_member_id,omitempty" jsonschema:"leave empty for whole-family activities"`
|
// FamilyMemberID *uuid.UUID `json:"family_member_id,omitempty" jsonschema:"leave empty for whole-family activities"`
|
||||||
DayOfWeek string `json:"day_of_week,omitempty" jsonschema:"for recurring: monday, tuesday, etc."`
|
// DayOfWeek string `json:"day_of_week,omitempty" jsonschema:"for recurring: monday, tuesday, etc."`
|
||||||
StartTime string `json:"start_time,omitempty" jsonschema:"HH:MM format"`
|
// StartTime string `json:"start_time,omitempty" jsonschema:"HH:MM format"`
|
||||||
EndTime string `json:"end_time,omitempty" jsonschema:"HH:MM format"`
|
// EndTime string `json:"end_time,omitempty" jsonschema:"HH:MM format"`
|
||||||
StartDate *time.Time `json:"start_date,omitempty"`
|
// StartDate *time.Time `json:"start_date,omitempty"`
|
||||||
EndDate *time.Time `json:"end_date,omitempty" jsonschema:"for recurring activities, when they end"`
|
// EndDate *time.Time `json:"end_date,omitempty" jsonschema:"for recurring activities, when they end"`
|
||||||
Location string `json:"location,omitempty"`
|
// Location string `json:"location,omitempty"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddActivityOutput struct {
|
// type AddActivityOutput struct {
|
||||||
Activity ext.Activity `json:"activity"`
|
// Activity ext.Activity `json:"activity"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) AddActivity(ctx context.Context, _ *mcp.CallToolRequest, in AddActivityInput) (*mcp.CallToolResult, AddActivityOutput, error) {
|
// func (t *CalendarTool) AddActivity(ctx context.Context, _ *mcp.CallToolRequest, in AddActivityInput) (*mcp.CallToolResult, AddActivityOutput, error) {
|
||||||
if strings.TrimSpace(in.Title) == "" {
|
// if strings.TrimSpace(in.Title) == "" {
|
||||||
return nil, AddActivityOutput{}, errRequiredField("title")
|
// return nil, AddActivityOutput{}, errRequiredField("title")
|
||||||
}
|
// }
|
||||||
activity, err := t.store.AddActivity(ctx, ext.Activity{
|
// activity, err := t.store.AddActivity(ctx, ext.Activity{
|
||||||
FamilyMemberID: in.FamilyMemberID,
|
// FamilyMemberID: in.FamilyMemberID,
|
||||||
Title: strings.TrimSpace(in.Title),
|
// Title: strings.TrimSpace(in.Title),
|
||||||
ActivityType: strings.TrimSpace(in.ActivityType),
|
// ActivityType: strings.TrimSpace(in.ActivityType),
|
||||||
DayOfWeek: strings.ToLower(strings.TrimSpace(in.DayOfWeek)),
|
// DayOfWeek: strings.ToLower(strings.TrimSpace(in.DayOfWeek)),
|
||||||
StartTime: strings.TrimSpace(in.StartTime),
|
// StartTime: strings.TrimSpace(in.StartTime),
|
||||||
EndTime: strings.TrimSpace(in.EndTime),
|
// EndTime: strings.TrimSpace(in.EndTime),
|
||||||
StartDate: in.StartDate,
|
// StartDate: in.StartDate,
|
||||||
EndDate: in.EndDate,
|
// EndDate: in.EndDate,
|
||||||
Location: strings.TrimSpace(in.Location),
|
// Location: strings.TrimSpace(in.Location),
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddActivityOutput{}, err
|
// return nil, AddActivityOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddActivityOutput{Activity: activity}, nil
|
// return nil, AddActivityOutput{Activity: activity}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_week_schedule
|
// // get_week_schedule
|
||||||
|
|
||||||
type GetWeekScheduleInput struct {
|
// type GetWeekScheduleInput struct {
|
||||||
WeekStart time.Time `json:"week_start" jsonschema:"start of the week (Monday) to retrieve"`
|
// WeekStart time.Time `json:"week_start" jsonschema:"start of the week (Monday) to retrieve"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetWeekScheduleOutput struct {
|
// type GetWeekScheduleOutput struct {
|
||||||
Activities []ext.Activity `json:"activities"`
|
// Activities []ext.Activity `json:"activities"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) GetWeekSchedule(ctx context.Context, _ *mcp.CallToolRequest, in GetWeekScheduleInput) (*mcp.CallToolResult, GetWeekScheduleOutput, error) {
|
// func (t *CalendarTool) GetWeekSchedule(ctx context.Context, _ *mcp.CallToolRequest, in GetWeekScheduleInput) (*mcp.CallToolResult, GetWeekScheduleOutput, error) {
|
||||||
activities, err := t.store.GetWeekSchedule(ctx, in.WeekStart)
|
// activities, err := t.store.GetWeekSchedule(ctx, in.WeekStart)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetWeekScheduleOutput{}, err
|
// return nil, GetWeekScheduleOutput{}, err
|
||||||
}
|
// }
|
||||||
if activities == nil {
|
// if activities == nil {
|
||||||
activities = []ext.Activity{}
|
// activities = []ext.Activity{}
|
||||||
}
|
// }
|
||||||
return nil, GetWeekScheduleOutput{Activities: activities}, nil
|
// return nil, GetWeekScheduleOutput{Activities: activities}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// search_activities
|
// // search_activities
|
||||||
|
|
||||||
type SearchActivitiesInput struct {
|
// type SearchActivitiesInput struct {
|
||||||
Query string `json:"query,omitempty" jsonschema:"search text matching title or notes"`
|
// Query string `json:"query,omitempty" jsonschema:"search text matching title or notes"`
|
||||||
ActivityType string `json:"activity_type,omitempty" jsonschema:"filter by type"`
|
// ActivityType string `json:"activity_type,omitempty" jsonschema:"filter by type"`
|
||||||
FamilyMemberID *uuid.UUID `json:"family_member_id,omitempty" jsonschema:"filter by family member"`
|
// FamilyMemberID *uuid.UUID `json:"family_member_id,omitempty" jsonschema:"filter by family member"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type SearchActivitiesOutput struct {
|
// type SearchActivitiesOutput struct {
|
||||||
Activities []ext.Activity `json:"activities"`
|
// Activities []ext.Activity `json:"activities"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) SearchActivities(ctx context.Context, _ *mcp.CallToolRequest, in SearchActivitiesInput) (*mcp.CallToolResult, SearchActivitiesOutput, error) {
|
// func (t *CalendarTool) SearchActivities(ctx context.Context, _ *mcp.CallToolRequest, in SearchActivitiesInput) (*mcp.CallToolResult, SearchActivitiesOutput, error) {
|
||||||
activities, err := t.store.SearchActivities(ctx, in.Query, in.ActivityType, in.FamilyMemberID)
|
// activities, err := t.store.SearchActivities(ctx, in.Query, in.ActivityType, in.FamilyMemberID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, SearchActivitiesOutput{}, err
|
// return nil, SearchActivitiesOutput{}, err
|
||||||
}
|
// }
|
||||||
if activities == nil {
|
// if activities == nil {
|
||||||
activities = []ext.Activity{}
|
// activities = []ext.Activity{}
|
||||||
}
|
// }
|
||||||
return nil, SearchActivitiesOutput{Activities: activities}, nil
|
// return nil, SearchActivitiesOutput{Activities: activities}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_important_date
|
// // add_important_date
|
||||||
|
|
||||||
type AddImportantDateInput struct {
|
// type AddImportantDateInput struct {
|
||||||
Title string `json:"title" jsonschema:"description of the date"`
|
// Title string `json:"title" jsonschema:"description of the date"`
|
||||||
DateValue time.Time `json:"date_value" jsonschema:"the date"`
|
// DateValue time.Time `json:"date_value" jsonschema:"the date"`
|
||||||
FamilyMemberID *uuid.UUID `json:"family_member_id,omitempty"`
|
// FamilyMemberID *uuid.UUID `json:"family_member_id,omitempty"`
|
||||||
RecurringYearly bool `json:"recurring_yearly,omitempty" jsonschema:"if true, reminds every year"`
|
// RecurringYearly bool `json:"recurring_yearly,omitempty" jsonschema:"if true, reminds every year"`
|
||||||
ReminderDaysBefore int `json:"reminder_days_before,omitempty" jsonschema:"how many days before to remind (default: 7)"`
|
// ReminderDaysBefore int `json:"reminder_days_before,omitempty" jsonschema:"how many days before to remind (default: 7)"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddImportantDateOutput struct {
|
// type AddImportantDateOutput struct {
|
||||||
Date ext.ImportantDate `json:"date"`
|
// Date ext.ImportantDate `json:"date"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) AddImportantDate(ctx context.Context, _ *mcp.CallToolRequest, in AddImportantDateInput) (*mcp.CallToolResult, AddImportantDateOutput, error) {
|
// func (t *CalendarTool) AddImportantDate(ctx context.Context, _ *mcp.CallToolRequest, in AddImportantDateInput) (*mcp.CallToolResult, AddImportantDateOutput, error) {
|
||||||
if strings.TrimSpace(in.Title) == "" {
|
// if strings.TrimSpace(in.Title) == "" {
|
||||||
return nil, AddImportantDateOutput{}, errRequiredField("title")
|
// return nil, AddImportantDateOutput{}, errRequiredField("title")
|
||||||
}
|
// }
|
||||||
reminder := in.ReminderDaysBefore
|
// reminder := in.ReminderDaysBefore
|
||||||
if reminder <= 0 {
|
// if reminder <= 0 {
|
||||||
reminder = 7
|
// reminder = 7
|
||||||
}
|
// }
|
||||||
d, err := t.store.AddImportantDate(ctx, ext.ImportantDate{
|
// d, err := t.store.AddImportantDate(ctx, ext.ImportantDate{
|
||||||
FamilyMemberID: in.FamilyMemberID,
|
// FamilyMemberID: in.FamilyMemberID,
|
||||||
Title: strings.TrimSpace(in.Title),
|
// Title: strings.TrimSpace(in.Title),
|
||||||
DateValue: in.DateValue,
|
// DateValue: in.DateValue,
|
||||||
RecurringYearly: in.RecurringYearly,
|
// RecurringYearly: in.RecurringYearly,
|
||||||
ReminderDaysBefore: reminder,
|
// ReminderDaysBefore: reminder,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddImportantDateOutput{}, err
|
// return nil, AddImportantDateOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddImportantDateOutput{Date: d}, nil
|
// return nil, AddImportantDateOutput{Date: d}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_upcoming_dates
|
// // get_upcoming_dates
|
||||||
|
|
||||||
type GetUpcomingDatesInput struct {
|
// type GetUpcomingDatesInput struct {
|
||||||
DaysAhead int `json:"days_ahead,omitempty" jsonschema:"how many days to look ahead (default: 30)"`
|
// DaysAhead int `json:"days_ahead,omitempty" jsonschema:"how many days to look ahead (default: 30)"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetUpcomingDatesOutput struct {
|
// type GetUpcomingDatesOutput struct {
|
||||||
Dates []ext.ImportantDate `json:"dates"`
|
// Dates []ext.ImportantDate `json:"dates"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CalendarTool) GetUpcomingDates(ctx context.Context, _ *mcp.CallToolRequest, in GetUpcomingDatesInput) (*mcp.CallToolResult, GetUpcomingDatesOutput, error) {
|
// func (t *CalendarTool) GetUpcomingDates(ctx context.Context, _ *mcp.CallToolRequest, in GetUpcomingDatesInput) (*mcp.CallToolResult, GetUpcomingDatesOutput, error) {
|
||||||
dates, err := t.store.GetUpcomingDates(ctx, in.DaysAhead)
|
// dates, err := t.store.GetUpcomingDates(ctx, in.DaysAhead)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetUpcomingDatesOutput{}, err
|
// return nil, GetUpcomingDatesOutput{}, err
|
||||||
}
|
// }
|
||||||
if dates == nil {
|
// if dates == nil {
|
||||||
dates = []ext.ImportantDate{}
|
// dates = []ext.ImportantDate{}
|
||||||
}
|
// }
|
||||||
return nil, GetUpcomingDatesOutput{Dates: dates}, nil
|
// return nil, GetUpcomingDatesOutput{Dates: dates}, nil
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,240 +1,240 @@
|
|||||||
package tools
|
package tools
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"errors"
|
// "errors"
|
||||||
"fmt"
|
// "fmt"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
"github.com/jackc/pgx/v5"
|
// "github.com/jackc/pgx/v5"
|
||||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
// "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/store"
|
// "git.warky.dev/wdevs/amcs/internal/store"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
type CRMTool struct {
|
// type CRMTool struct {
|
||||||
store *store.DB
|
// store *store.DB
|
||||||
}
|
// }
|
||||||
|
|
||||||
func NewCRMTool(db *store.DB) *CRMTool {
|
// func NewCRMTool(db *store.DB) *CRMTool {
|
||||||
return &CRMTool{store: db}
|
// return &CRMTool{store: db}
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_professional_contact
|
// // add_professional_contact
|
||||||
|
|
||||||
type AddContactInput struct {
|
// type AddContactInput struct {
|
||||||
Name string `json:"name" jsonschema:"contact's full name"`
|
// Name string `json:"name" jsonschema:"contact's full name"`
|
||||||
Company string `json:"company,omitempty"`
|
// Company string `json:"company,omitempty"`
|
||||||
Title string `json:"title,omitempty" jsonschema:"job title"`
|
// Title string `json:"title,omitempty" jsonschema:"job title"`
|
||||||
Email string `json:"email,omitempty"`
|
// Email string `json:"email,omitempty"`
|
||||||
Phone string `json:"phone,omitempty"`
|
// Phone string `json:"phone,omitempty"`
|
||||||
LinkedInURL string `json:"linkedin_url,omitempty"`
|
// LinkedInURL string `json:"linkedin_url,omitempty"`
|
||||||
HowWeMet string `json:"how_we_met,omitempty"`
|
// HowWeMet string `json:"how_we_met,omitempty"`
|
||||||
Tags []string `json:"tags,omitempty"`
|
// Tags []string `json:"tags,omitempty"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
FollowUpDate *time.Time `json:"follow_up_date,omitempty"`
|
// FollowUpDate *time.Time `json:"follow_up_date,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddContactOutput struct {
|
// type AddContactOutput struct {
|
||||||
Contact ext.ProfessionalContact `json:"contact"`
|
// Contact ext.ProfessionalContact `json:"contact"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) AddContact(ctx context.Context, _ *mcp.CallToolRequest, in AddContactInput) (*mcp.CallToolResult, AddContactOutput, error) {
|
// func (t *CRMTool) AddContact(ctx context.Context, _ *mcp.CallToolRequest, in AddContactInput) (*mcp.CallToolResult, AddContactOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, AddContactOutput{}, errRequiredField("name")
|
// return nil, AddContactOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
if in.Tags == nil {
|
// if in.Tags == nil {
|
||||||
in.Tags = []string{}
|
// in.Tags = []string{}
|
||||||
}
|
// }
|
||||||
contact, err := t.store.AddProfessionalContact(ctx, ext.ProfessionalContact{
|
// contact, err := t.store.AddProfessionalContact(ctx, ext.ProfessionalContact{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
Company: strings.TrimSpace(in.Company),
|
// Company: strings.TrimSpace(in.Company),
|
||||||
Title: strings.TrimSpace(in.Title),
|
// Title: strings.TrimSpace(in.Title),
|
||||||
Email: strings.TrimSpace(in.Email),
|
// Email: strings.TrimSpace(in.Email),
|
||||||
Phone: strings.TrimSpace(in.Phone),
|
// Phone: strings.TrimSpace(in.Phone),
|
||||||
LinkedInURL: strings.TrimSpace(in.LinkedInURL),
|
// LinkedInURL: strings.TrimSpace(in.LinkedInURL),
|
||||||
HowWeMet: strings.TrimSpace(in.HowWeMet),
|
// HowWeMet: strings.TrimSpace(in.HowWeMet),
|
||||||
Tags: in.Tags,
|
// Tags: in.Tags,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
FollowUpDate: in.FollowUpDate,
|
// FollowUpDate: in.FollowUpDate,
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddContactOutput{}, err
|
// return nil, AddContactOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddContactOutput{Contact: contact}, nil
|
// return nil, AddContactOutput{Contact: contact}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// search_contacts
|
// // search_contacts
|
||||||
|
|
||||||
type SearchContactsInput struct {
|
// type SearchContactsInput struct {
|
||||||
Query string `json:"query,omitempty" jsonschema:"search text matching name, company, title, or notes"`
|
// Query string `json:"query,omitempty" jsonschema:"search text matching name, company, title, or notes"`
|
||||||
Tags []string `json:"tags,omitempty" jsonschema:"filter by tags (all must match)"`
|
// Tags []string `json:"tags,omitempty" jsonschema:"filter by tags (all must match)"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type SearchContactsOutput struct {
|
// type SearchContactsOutput struct {
|
||||||
Contacts []ext.ProfessionalContact `json:"contacts"`
|
// Contacts []ext.ProfessionalContact `json:"contacts"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) SearchContacts(ctx context.Context, _ *mcp.CallToolRequest, in SearchContactsInput) (*mcp.CallToolResult, SearchContactsOutput, error) {
|
// func (t *CRMTool) SearchContacts(ctx context.Context, _ *mcp.CallToolRequest, in SearchContactsInput) (*mcp.CallToolResult, SearchContactsOutput, error) {
|
||||||
contacts, err := t.store.SearchContacts(ctx, in.Query, in.Tags)
|
// contacts, err := t.store.SearchContacts(ctx, in.Query, in.Tags)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, SearchContactsOutput{}, err
|
// return nil, SearchContactsOutput{}, err
|
||||||
}
|
// }
|
||||||
if contacts == nil {
|
// if contacts == nil {
|
||||||
contacts = []ext.ProfessionalContact{}
|
// contacts = []ext.ProfessionalContact{}
|
||||||
}
|
// }
|
||||||
return nil, SearchContactsOutput{Contacts: contacts}, nil
|
// return nil, SearchContactsOutput{Contacts: contacts}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// log_interaction
|
// // log_interaction
|
||||||
|
|
||||||
type LogInteractionInput struct {
|
// type LogInteractionInput struct {
|
||||||
ContactID uuid.UUID `json:"contact_id" jsonschema:"id of the contact"`
|
// ContactID uuid.UUID `json:"contact_id" jsonschema:"id of the contact"`
|
||||||
InteractionType string `json:"interaction_type" jsonschema:"one of: meeting, email, call, coffee, event, linkedin, other"`
|
// InteractionType string `json:"interaction_type" jsonschema:"one of: meeting, email, call, coffee, event, linkedin, other"`
|
||||||
OccurredAt *time.Time `json:"occurred_at,omitempty" jsonschema:"when it happened (defaults to now)"`
|
// OccurredAt *time.Time `json:"occurred_at,omitempty" jsonschema:"when it happened (defaults to now)"`
|
||||||
Summary string `json:"summary" jsonschema:"summary of the interaction"`
|
// Summary string `json:"summary" jsonschema:"summary of the interaction"`
|
||||||
FollowUpNeeded bool `json:"follow_up_needed,omitempty"`
|
// FollowUpNeeded bool `json:"follow_up_needed,omitempty"`
|
||||||
FollowUpNotes string `json:"follow_up_notes,omitempty"`
|
// FollowUpNotes string `json:"follow_up_notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type LogInteractionOutput struct {
|
// type LogInteractionOutput struct {
|
||||||
Interaction ext.ContactInteraction `json:"interaction"`
|
// Interaction ext.ContactInteraction `json:"interaction"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) LogInteraction(ctx context.Context, _ *mcp.CallToolRequest, in LogInteractionInput) (*mcp.CallToolResult, LogInteractionOutput, error) {
|
// func (t *CRMTool) LogInteraction(ctx context.Context, _ *mcp.CallToolRequest, in LogInteractionInput) (*mcp.CallToolResult, LogInteractionOutput, error) {
|
||||||
if strings.TrimSpace(in.Summary) == "" {
|
// if strings.TrimSpace(in.Summary) == "" {
|
||||||
return nil, LogInteractionOutput{}, errRequiredField("summary")
|
// return nil, LogInteractionOutput{}, errRequiredField("summary")
|
||||||
}
|
// }
|
||||||
occurredAt := time.Now()
|
// occurredAt := time.Now()
|
||||||
if in.OccurredAt != nil {
|
// if in.OccurredAt != nil {
|
||||||
occurredAt = *in.OccurredAt
|
// occurredAt = *in.OccurredAt
|
||||||
}
|
// }
|
||||||
interaction, err := t.store.LogInteraction(ctx, ext.ContactInteraction{
|
// interaction, err := t.store.LogInteraction(ctx, ext.ContactInteraction{
|
||||||
ContactID: in.ContactID,
|
// ContactID: in.ContactID,
|
||||||
InteractionType: in.InteractionType,
|
// InteractionType: in.InteractionType,
|
||||||
OccurredAt: occurredAt,
|
// OccurredAt: occurredAt,
|
||||||
Summary: strings.TrimSpace(in.Summary),
|
// Summary: strings.TrimSpace(in.Summary),
|
||||||
FollowUpNeeded: in.FollowUpNeeded,
|
// FollowUpNeeded: in.FollowUpNeeded,
|
||||||
FollowUpNotes: strings.TrimSpace(in.FollowUpNotes),
|
// FollowUpNotes: strings.TrimSpace(in.FollowUpNotes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, LogInteractionOutput{}, err
|
// return nil, LogInteractionOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, LogInteractionOutput{Interaction: interaction}, nil
|
// return nil, LogInteractionOutput{Interaction: interaction}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_contact_history
|
// // get_contact_history
|
||||||
|
|
||||||
type GetContactHistoryInput struct {
|
// type GetContactHistoryInput struct {
|
||||||
ContactID uuid.UUID `json:"contact_id" jsonschema:"id of the contact"`
|
// ContactID uuid.UUID `json:"contact_id" jsonschema:"id of the contact"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetContactHistoryOutput struct {
|
// type GetContactHistoryOutput struct {
|
||||||
History ext.ContactHistory `json:"history"`
|
// History ext.ContactHistory `json:"history"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) GetHistory(ctx context.Context, _ *mcp.CallToolRequest, in GetContactHistoryInput) (*mcp.CallToolResult, GetContactHistoryOutput, error) {
|
// func (t *CRMTool) GetHistory(ctx context.Context, _ *mcp.CallToolRequest, in GetContactHistoryInput) (*mcp.CallToolResult, GetContactHistoryOutput, error) {
|
||||||
history, err := t.store.GetContactHistory(ctx, in.ContactID)
|
// history, err := t.store.GetContactHistory(ctx, in.ContactID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetContactHistoryOutput{}, err
|
// return nil, GetContactHistoryOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, GetContactHistoryOutput{History: history}, nil
|
// return nil, GetContactHistoryOutput{History: history}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// create_opportunity
|
// // create_opportunity
|
||||||
|
|
||||||
type CreateOpportunityInput struct {
|
// type CreateOpportunityInput struct {
|
||||||
ContactID *uuid.UUID `json:"contact_id,omitempty"`
|
// ContactID *uuid.UUID `json:"contact_id,omitempty"`
|
||||||
Title string `json:"title" jsonschema:"opportunity title"`
|
// Title string `json:"title" jsonschema:"opportunity title"`
|
||||||
Description string `json:"description,omitempty"`
|
// Description string `json:"description,omitempty"`
|
||||||
Stage string `json:"stage,omitempty" jsonschema:"one of: identified, in_conversation, proposal, negotiation, won, lost (default: identified)"`
|
// Stage string `json:"stage,omitempty" jsonschema:"one of: identified, in_conversation, proposal, negotiation, won, lost (default: identified)"`
|
||||||
Value *float64 `json:"value,omitempty" jsonschema:"monetary value"`
|
// Value *float64 `json:"value,omitempty" jsonschema:"monetary value"`
|
||||||
ExpectedCloseDate *time.Time `json:"expected_close_date,omitempty"`
|
// ExpectedCloseDate *time.Time `json:"expected_close_date,omitempty"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type CreateOpportunityOutput struct {
|
// type CreateOpportunityOutput struct {
|
||||||
Opportunity ext.Opportunity `json:"opportunity"`
|
// Opportunity ext.Opportunity `json:"opportunity"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) CreateOpportunity(ctx context.Context, _ *mcp.CallToolRequest, in CreateOpportunityInput) (*mcp.CallToolResult, CreateOpportunityOutput, error) {
|
// func (t *CRMTool) CreateOpportunity(ctx context.Context, _ *mcp.CallToolRequest, in CreateOpportunityInput) (*mcp.CallToolResult, CreateOpportunityOutput, error) {
|
||||||
if strings.TrimSpace(in.Title) == "" {
|
// if strings.TrimSpace(in.Title) == "" {
|
||||||
return nil, CreateOpportunityOutput{}, errRequiredField("title")
|
// return nil, CreateOpportunityOutput{}, errRequiredField("title")
|
||||||
}
|
// }
|
||||||
stage := strings.TrimSpace(in.Stage)
|
// stage := strings.TrimSpace(in.Stage)
|
||||||
if stage == "" {
|
// if stage == "" {
|
||||||
stage = "identified"
|
// stage = "identified"
|
||||||
}
|
// }
|
||||||
opp, err := t.store.CreateOpportunity(ctx, ext.Opportunity{
|
// opp, err := t.store.CreateOpportunity(ctx, ext.Opportunity{
|
||||||
ContactID: in.ContactID,
|
// ContactID: in.ContactID,
|
||||||
Title: strings.TrimSpace(in.Title),
|
// Title: strings.TrimSpace(in.Title),
|
||||||
Description: strings.TrimSpace(in.Description),
|
// Description: strings.TrimSpace(in.Description),
|
||||||
Stage: stage,
|
// Stage: stage,
|
||||||
Value: in.Value,
|
// Value: in.Value,
|
||||||
ExpectedCloseDate: in.ExpectedCloseDate,
|
// ExpectedCloseDate: in.ExpectedCloseDate,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, CreateOpportunityOutput{}, err
|
// return nil, CreateOpportunityOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, CreateOpportunityOutput{Opportunity: opp}, nil
|
// return nil, CreateOpportunityOutput{Opportunity: opp}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_follow_ups_due
|
// // get_follow_ups_due
|
||||||
|
|
||||||
type GetFollowUpsDueInput struct {
|
// type GetFollowUpsDueInput struct {
|
||||||
DaysAhead int `json:"days_ahead,omitempty" jsonschema:"look ahead window in days (default: 7)"`
|
// DaysAhead int `json:"days_ahead,omitempty" jsonschema:"look ahead window in days (default: 7)"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetFollowUpsDueOutput struct {
|
// type GetFollowUpsDueOutput struct {
|
||||||
Contacts []ext.ProfessionalContact `json:"contacts"`
|
// Contacts []ext.ProfessionalContact `json:"contacts"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) GetFollowUpsDue(ctx context.Context, _ *mcp.CallToolRequest, in GetFollowUpsDueInput) (*mcp.CallToolResult, GetFollowUpsDueOutput, error) {
|
// func (t *CRMTool) GetFollowUpsDue(ctx context.Context, _ *mcp.CallToolRequest, in GetFollowUpsDueInput) (*mcp.CallToolResult, GetFollowUpsDueOutput, error) {
|
||||||
contacts, err := t.store.GetFollowUpsDue(ctx, in.DaysAhead)
|
// contacts, err := t.store.GetFollowUpsDue(ctx, in.DaysAhead)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetFollowUpsDueOutput{}, err
|
// return nil, GetFollowUpsDueOutput{}, err
|
||||||
}
|
// }
|
||||||
if contacts == nil {
|
// if contacts == nil {
|
||||||
contacts = []ext.ProfessionalContact{}
|
// contacts = []ext.ProfessionalContact{}
|
||||||
}
|
// }
|
||||||
return nil, GetFollowUpsDueOutput{Contacts: contacts}, nil
|
// return nil, GetFollowUpsDueOutput{Contacts: contacts}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// link_thought_to_contact
|
// // link_thought_to_contact
|
||||||
|
|
||||||
type LinkThoughtToContactInput struct {
|
// type LinkThoughtToContactInput struct {
|
||||||
ContactID uuid.UUID `json:"contact_id" jsonschema:"id of the contact"`
|
// ContactID uuid.UUID `json:"contact_id" jsonschema:"id of the contact"`
|
||||||
ThoughtID uuid.UUID `json:"thought_id" jsonschema:"id of the thought to link"`
|
// ThoughtID uuid.UUID `json:"thought_id" jsonschema:"id of the thought to link"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type LinkThoughtToContactOutput struct {
|
// type LinkThoughtToContactOutput struct {
|
||||||
Contact ext.ProfessionalContact `json:"contact"`
|
// Contact ext.ProfessionalContact `json:"contact"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *CRMTool) LinkThought(ctx context.Context, _ *mcp.CallToolRequest, in LinkThoughtToContactInput) (*mcp.CallToolResult, LinkThoughtToContactOutput, error) {
|
// func (t *CRMTool) LinkThought(ctx context.Context, _ *mcp.CallToolRequest, in LinkThoughtToContactInput) (*mcp.CallToolResult, LinkThoughtToContactOutput, error) {
|
||||||
thought, err := t.store.GetThought(ctx, in.ThoughtID)
|
// thought, err := t.store.GetThought(ctx, in.ThoughtID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
// if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, LinkThoughtToContactOutput{}, errEntityNotFound("thought", "thought_id", in.ThoughtID.String())
|
// return nil, LinkThoughtToContactOutput{}, errEntityNotFound("thought", "thought_id", in.ThoughtID.String())
|
||||||
}
|
// }
|
||||||
return nil, LinkThoughtToContactOutput{}, err
|
// return nil, LinkThoughtToContactOutput{}, err
|
||||||
}
|
// }
|
||||||
|
|
||||||
appendText := fmt.Sprintf("\n\n[Linked thought %s]: %s", thought.ID, thought.Content)
|
// appendText := fmt.Sprintf("\n\n[Linked thought %s]: %s", thought.ID, thought.Content)
|
||||||
if err := t.store.AppendThoughtToContactNotes(ctx, in.ContactID, appendText); err != nil {
|
// if err := t.store.AppendThoughtToContactNotes(ctx, in.ContactID, appendText); err != nil {
|
||||||
return nil, LinkThoughtToContactOutput{}, err
|
// return nil, LinkThoughtToContactOutput{}, err
|
||||||
}
|
// }
|
||||||
|
|
||||||
contact, err := t.store.GetContact(ctx, in.ContactID)
|
// contact, err := t.store.GetContact(ctx, in.ContactID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
// if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, LinkThoughtToContactOutput{}, errEntityNotFound("contact", "contact_id", in.ContactID.String())
|
// return nil, LinkThoughtToContactOutput{}, errEntityNotFound("contact", "contact_id", in.ContactID.String())
|
||||||
}
|
// }
|
||||||
return nil, LinkThoughtToContactOutput{}, err
|
// return nil, LinkThoughtToContactOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, LinkThoughtToContactOutput{Contact: contact}, nil
|
// return nil, LinkThoughtToContactOutput{Contact: contact}, nil
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,151 +1,151 @@
|
|||||||
package tools
|
package tools
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"strings"
|
// "strings"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
// "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/store"
|
// "git.warky.dev/wdevs/amcs/internal/store"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
type HouseholdTool struct {
|
// type HouseholdTool struct {
|
||||||
store *store.DB
|
// store *store.DB
|
||||||
}
|
// }
|
||||||
|
|
||||||
func NewHouseholdTool(db *store.DB) *HouseholdTool {
|
// func NewHouseholdTool(db *store.DB) *HouseholdTool {
|
||||||
return &HouseholdTool{store: db}
|
// return &HouseholdTool{store: db}
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_household_item
|
// // add_household_item
|
||||||
|
|
||||||
type AddHouseholdItemInput struct {
|
// type AddHouseholdItemInput struct {
|
||||||
Name string `json:"name" jsonschema:"name of the item"`
|
// Name string `json:"name" jsonschema:"name of the item"`
|
||||||
Category string `json:"category,omitempty" jsonschema:"category (e.g. paint, appliance, measurement, document)"`
|
// Category string `json:"category,omitempty" jsonschema:"category (e.g. paint, appliance, measurement, document)"`
|
||||||
Location string `json:"location,omitempty" jsonschema:"where in the home this item is"`
|
// Location string `json:"location,omitempty" jsonschema:"where in the home this item is"`
|
||||||
Details map[string]any `json:"details,omitempty" jsonschema:"flexible metadata (model numbers, colors, specs, etc.)"`
|
// Details map[string]any `json:"details,omitempty" jsonschema:"flexible metadata (model numbers, colors, specs, etc.)"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddHouseholdItemOutput struct {
|
// type AddHouseholdItemOutput struct {
|
||||||
Item ext.HouseholdItem `json:"item"`
|
// Item ext.HouseholdItem `json:"item"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *HouseholdTool) AddItem(ctx context.Context, _ *mcp.CallToolRequest, in AddHouseholdItemInput) (*mcp.CallToolResult, AddHouseholdItemOutput, error) {
|
// func (t *HouseholdTool) AddItem(ctx context.Context, _ *mcp.CallToolRequest, in AddHouseholdItemInput) (*mcp.CallToolResult, AddHouseholdItemOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, AddHouseholdItemOutput{}, errRequiredField("name")
|
// return nil, AddHouseholdItemOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
if in.Details == nil {
|
// if in.Details == nil {
|
||||||
in.Details = map[string]any{}
|
// in.Details = map[string]any{}
|
||||||
}
|
// }
|
||||||
item, err := t.store.AddHouseholdItem(ctx, ext.HouseholdItem{
|
// item, err := t.store.AddHouseholdItem(ctx, ext.HouseholdItem{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
Category: strings.TrimSpace(in.Category),
|
// Category: strings.TrimSpace(in.Category),
|
||||||
Location: strings.TrimSpace(in.Location),
|
// Location: strings.TrimSpace(in.Location),
|
||||||
Details: in.Details,
|
// Details: in.Details,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddHouseholdItemOutput{}, err
|
// return nil, AddHouseholdItemOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddHouseholdItemOutput{Item: item}, nil
|
// return nil, AddHouseholdItemOutput{Item: item}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// search_household_items
|
// // search_household_items
|
||||||
|
|
||||||
type SearchHouseholdItemsInput struct {
|
// type SearchHouseholdItemsInput struct {
|
||||||
Query string `json:"query,omitempty" jsonschema:"search text matching name or notes"`
|
// Query string `json:"query,omitempty" jsonschema:"search text matching name or notes"`
|
||||||
Category string `json:"category,omitempty" jsonschema:"filter by category"`
|
// Category string `json:"category,omitempty" jsonschema:"filter by category"`
|
||||||
Location string `json:"location,omitempty" jsonschema:"filter by location"`
|
// Location string `json:"location,omitempty" jsonschema:"filter by location"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type SearchHouseholdItemsOutput struct {
|
// type SearchHouseholdItemsOutput struct {
|
||||||
Items []ext.HouseholdItem `json:"items"`
|
// Items []ext.HouseholdItem `json:"items"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *HouseholdTool) SearchItems(ctx context.Context, _ *mcp.CallToolRequest, in SearchHouseholdItemsInput) (*mcp.CallToolResult, SearchHouseholdItemsOutput, error) {
|
// func (t *HouseholdTool) SearchItems(ctx context.Context, _ *mcp.CallToolRequest, in SearchHouseholdItemsInput) (*mcp.CallToolResult, SearchHouseholdItemsOutput, error) {
|
||||||
items, err := t.store.SearchHouseholdItems(ctx, in.Query, in.Category, in.Location)
|
// items, err := t.store.SearchHouseholdItems(ctx, in.Query, in.Category, in.Location)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, SearchHouseholdItemsOutput{}, err
|
// return nil, SearchHouseholdItemsOutput{}, err
|
||||||
}
|
// }
|
||||||
if items == nil {
|
// if items == nil {
|
||||||
items = []ext.HouseholdItem{}
|
// items = []ext.HouseholdItem{}
|
||||||
}
|
// }
|
||||||
return nil, SearchHouseholdItemsOutput{Items: items}, nil
|
// return nil, SearchHouseholdItemsOutput{Items: items}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_household_item
|
// // get_household_item
|
||||||
|
|
||||||
type GetHouseholdItemInput struct {
|
// type GetHouseholdItemInput struct {
|
||||||
ID uuid.UUID `json:"id" jsonschema:"item id"`
|
// ID uuid.UUID `json:"id" jsonschema:"item id"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetHouseholdItemOutput struct {
|
// type GetHouseholdItemOutput struct {
|
||||||
Item ext.HouseholdItem `json:"item"`
|
// Item ext.HouseholdItem `json:"item"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *HouseholdTool) GetItem(ctx context.Context, _ *mcp.CallToolRequest, in GetHouseholdItemInput) (*mcp.CallToolResult, GetHouseholdItemOutput, error) {
|
// func (t *HouseholdTool) GetItem(ctx context.Context, _ *mcp.CallToolRequest, in GetHouseholdItemInput) (*mcp.CallToolResult, GetHouseholdItemOutput, error) {
|
||||||
item, err := t.store.GetHouseholdItem(ctx, in.ID)
|
// item, err := t.store.GetHouseholdItem(ctx, in.ID)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetHouseholdItemOutput{}, err
|
// return nil, GetHouseholdItemOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, GetHouseholdItemOutput{Item: item}, nil
|
// return nil, GetHouseholdItemOutput{Item: item}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_vendor
|
// // add_vendor
|
||||||
|
|
||||||
type AddVendorInput struct {
|
// type AddVendorInput struct {
|
||||||
Name string `json:"name" jsonschema:"vendor name"`
|
// Name string `json:"name" jsonschema:"vendor name"`
|
||||||
ServiceType string `json:"service_type,omitempty" jsonschema:"type of service (e.g. plumber, electrician, landscaper)"`
|
// ServiceType string `json:"service_type,omitempty" jsonschema:"type of service (e.g. plumber, electrician, landscaper)"`
|
||||||
Phone string `json:"phone,omitempty"`
|
// Phone string `json:"phone,omitempty"`
|
||||||
Email string `json:"email,omitempty"`
|
// Email string `json:"email,omitempty"`
|
||||||
Website string `json:"website,omitempty"`
|
// Website string `json:"website,omitempty"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
Rating *int `json:"rating,omitempty" jsonschema:"1-5 rating"`
|
// Rating *int `json:"rating,omitempty" jsonschema:"1-5 rating"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddVendorOutput struct {
|
// type AddVendorOutput struct {
|
||||||
Vendor ext.HouseholdVendor `json:"vendor"`
|
// Vendor ext.HouseholdVendor `json:"vendor"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *HouseholdTool) AddVendor(ctx context.Context, _ *mcp.CallToolRequest, in AddVendorInput) (*mcp.CallToolResult, AddVendorOutput, error) {
|
// func (t *HouseholdTool) AddVendor(ctx context.Context, _ *mcp.CallToolRequest, in AddVendorInput) (*mcp.CallToolResult, AddVendorOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, AddVendorOutput{}, errRequiredField("name")
|
// return nil, AddVendorOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
vendor, err := t.store.AddVendor(ctx, ext.HouseholdVendor{
|
// vendor, err := t.store.AddVendor(ctx, ext.HouseholdVendor{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
ServiceType: strings.TrimSpace(in.ServiceType),
|
// ServiceType: strings.TrimSpace(in.ServiceType),
|
||||||
Phone: strings.TrimSpace(in.Phone),
|
// Phone: strings.TrimSpace(in.Phone),
|
||||||
Email: strings.TrimSpace(in.Email),
|
// Email: strings.TrimSpace(in.Email),
|
||||||
Website: strings.TrimSpace(in.Website),
|
// Website: strings.TrimSpace(in.Website),
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
Rating: in.Rating,
|
// Rating: in.Rating,
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddVendorOutput{}, err
|
// return nil, AddVendorOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddVendorOutput{Vendor: vendor}, nil
|
// return nil, AddVendorOutput{Vendor: vendor}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// list_vendors
|
// // list_vendors
|
||||||
|
|
||||||
type ListVendorsInput struct {
|
// type ListVendorsInput struct {
|
||||||
ServiceType string `json:"service_type,omitempty" jsonschema:"filter by service type"`
|
// ServiceType string `json:"service_type,omitempty" jsonschema:"filter by service type"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type ListVendorsOutput struct {
|
// type ListVendorsOutput struct {
|
||||||
Vendors []ext.HouseholdVendor `json:"vendors"`
|
// Vendors []ext.HouseholdVendor `json:"vendors"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *HouseholdTool) ListVendors(ctx context.Context, _ *mcp.CallToolRequest, in ListVendorsInput) (*mcp.CallToolResult, ListVendorsOutput, error) {
|
// func (t *HouseholdTool) ListVendors(ctx context.Context, _ *mcp.CallToolRequest, in ListVendorsInput) (*mcp.CallToolResult, ListVendorsOutput, error) {
|
||||||
vendors, err := t.store.ListVendors(ctx, in.ServiceType)
|
// vendors, err := t.store.ListVendors(ctx, in.ServiceType)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, ListVendorsOutput{}, err
|
// return nil, ListVendorsOutput{}, err
|
||||||
}
|
// }
|
||||||
if vendors == nil {
|
// if vendors == nil {
|
||||||
vendors = []ext.HouseholdVendor{}
|
// vendors = []ext.HouseholdVendor{}
|
||||||
}
|
// }
|
||||||
return nil, ListVendorsOutput{Vendors: vendors}, nil
|
// return nil, ListVendorsOutput{Vendors: vendors}, nil
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,137 +1,137 @@
|
|||||||
package tools
|
package tools
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
// "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/store"
|
// "git.warky.dev/wdevs/amcs/internal/store"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
type MaintenanceTool struct {
|
// type MaintenanceTool struct {
|
||||||
store *store.DB
|
// store *store.DB
|
||||||
}
|
// }
|
||||||
|
|
||||||
func NewMaintenanceTool(db *store.DB) *MaintenanceTool {
|
// func NewMaintenanceTool(db *store.DB) *MaintenanceTool {
|
||||||
return &MaintenanceTool{store: db}
|
// return &MaintenanceTool{store: db}
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_maintenance_task
|
// // add_maintenance_task
|
||||||
|
|
||||||
type AddMaintenanceTaskInput struct {
|
// type AddMaintenanceTaskInput struct {
|
||||||
Name string `json:"name" jsonschema:"task name"`
|
// Name string `json:"name" jsonschema:"task name"`
|
||||||
Category string `json:"category,omitempty" jsonschema:"e.g. hvac, plumbing, exterior, appliance, landscaping"`
|
// Category string `json:"category,omitempty" jsonschema:"e.g. hvac, plumbing, exterior, appliance, landscaping"`
|
||||||
FrequencyDays *int `json:"frequency_days,omitempty" jsonschema:"recurrence interval in days; omit for one-time tasks"`
|
// FrequencyDays *int `json:"frequency_days,omitempty" jsonschema:"recurrence interval in days; omit for one-time tasks"`
|
||||||
NextDue *time.Time `json:"next_due,omitempty" jsonschema:"when the task is next due"`
|
// NextDue *time.Time `json:"next_due,omitempty" jsonschema:"when the task is next due"`
|
||||||
Priority string `json:"priority,omitempty" jsonschema:"low, medium, high, or urgent (default: medium)"`
|
// Priority string `json:"priority,omitempty" jsonschema:"low, medium, high, or urgent (default: medium)"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddMaintenanceTaskOutput struct {
|
// type AddMaintenanceTaskOutput struct {
|
||||||
Task ext.MaintenanceTask `json:"task"`
|
// Task ext.MaintenanceTask `json:"task"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MaintenanceTool) AddTask(ctx context.Context, _ *mcp.CallToolRequest, in AddMaintenanceTaskInput) (*mcp.CallToolResult, AddMaintenanceTaskOutput, error) {
|
// func (t *MaintenanceTool) AddTask(ctx context.Context, _ *mcp.CallToolRequest, in AddMaintenanceTaskInput) (*mcp.CallToolResult, AddMaintenanceTaskOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, AddMaintenanceTaskOutput{}, errRequiredField("name")
|
// return nil, AddMaintenanceTaskOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
priority := strings.TrimSpace(in.Priority)
|
// priority := strings.TrimSpace(in.Priority)
|
||||||
if priority == "" {
|
// if priority == "" {
|
||||||
priority = "medium"
|
// priority = "medium"
|
||||||
}
|
// }
|
||||||
task, err := t.store.AddMaintenanceTask(ctx, ext.MaintenanceTask{
|
// task, err := t.store.AddMaintenanceTask(ctx, ext.MaintenanceTask{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
Category: strings.TrimSpace(in.Category),
|
// Category: strings.TrimSpace(in.Category),
|
||||||
FrequencyDays: in.FrequencyDays,
|
// FrequencyDays: in.FrequencyDays,
|
||||||
NextDue: in.NextDue,
|
// NextDue: in.NextDue,
|
||||||
Priority: priority,
|
// Priority: priority,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddMaintenanceTaskOutput{}, err
|
// return nil, AddMaintenanceTaskOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddMaintenanceTaskOutput{Task: task}, nil
|
// return nil, AddMaintenanceTaskOutput{Task: task}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// log_maintenance
|
// // log_maintenance
|
||||||
|
|
||||||
type LogMaintenanceInput struct {
|
// type LogMaintenanceInput struct {
|
||||||
TaskID uuid.UUID `json:"task_id" jsonschema:"id of the maintenance task"`
|
// TaskID uuid.UUID `json:"task_id" jsonschema:"id of the maintenance task"`
|
||||||
CompletedAt *time.Time `json:"completed_at,omitempty" jsonschema:"when the work was done (defaults to now)"`
|
// CompletedAt *time.Time `json:"completed_at,omitempty" jsonschema:"when the work was done (defaults to now)"`
|
||||||
PerformedBy string `json:"performed_by,omitempty" jsonschema:"who did the work (self, vendor name, etc.)"`
|
// PerformedBy string `json:"performed_by,omitempty" jsonschema:"who did the work (self, vendor name, etc.)"`
|
||||||
Cost *float64 `json:"cost,omitempty" jsonschema:"cost of the work"`
|
// Cost *float64 `json:"cost,omitempty" jsonschema:"cost of the work"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
NextAction string `json:"next_action,omitempty" jsonschema:"recommended follow-up"`
|
// NextAction string `json:"next_action,omitempty" jsonschema:"recommended follow-up"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type LogMaintenanceOutput struct {
|
// type LogMaintenanceOutput struct {
|
||||||
Log ext.MaintenanceLog `json:"log"`
|
// Log ext.MaintenanceLog `json:"log"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MaintenanceTool) LogWork(ctx context.Context, _ *mcp.CallToolRequest, in LogMaintenanceInput) (*mcp.CallToolResult, LogMaintenanceOutput, error) {
|
// func (t *MaintenanceTool) LogWork(ctx context.Context, _ *mcp.CallToolRequest, in LogMaintenanceInput) (*mcp.CallToolResult, LogMaintenanceOutput, error) {
|
||||||
completedAt := time.Now()
|
// completedAt := time.Now()
|
||||||
if in.CompletedAt != nil {
|
// if in.CompletedAt != nil {
|
||||||
completedAt = *in.CompletedAt
|
// completedAt = *in.CompletedAt
|
||||||
}
|
// }
|
||||||
log, err := t.store.LogMaintenance(ctx, ext.MaintenanceLog{
|
// log, err := t.store.LogMaintenance(ctx, ext.MaintenanceLog{
|
||||||
TaskID: in.TaskID,
|
// TaskID: in.TaskID,
|
||||||
CompletedAt: completedAt,
|
// CompletedAt: completedAt,
|
||||||
PerformedBy: strings.TrimSpace(in.PerformedBy),
|
// PerformedBy: strings.TrimSpace(in.PerformedBy),
|
||||||
Cost: in.Cost,
|
// Cost: in.Cost,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
NextAction: strings.TrimSpace(in.NextAction),
|
// NextAction: strings.TrimSpace(in.NextAction),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, LogMaintenanceOutput{}, err
|
// return nil, LogMaintenanceOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, LogMaintenanceOutput{Log: log}, nil
|
// return nil, LogMaintenanceOutput{Log: log}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_upcoming_maintenance
|
// // get_upcoming_maintenance
|
||||||
|
|
||||||
type GetUpcomingMaintenanceInput struct {
|
// type GetUpcomingMaintenanceInput struct {
|
||||||
DaysAhead int `json:"days_ahead,omitempty" jsonschema:"how many days to look ahead (default: 30)"`
|
// DaysAhead int `json:"days_ahead,omitempty" jsonschema:"how many days to look ahead (default: 30)"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetUpcomingMaintenanceOutput struct {
|
// type GetUpcomingMaintenanceOutput struct {
|
||||||
Tasks []ext.MaintenanceTask `json:"tasks"`
|
// Tasks []ext.MaintenanceTask `json:"tasks"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MaintenanceTool) GetUpcoming(ctx context.Context, _ *mcp.CallToolRequest, in GetUpcomingMaintenanceInput) (*mcp.CallToolResult, GetUpcomingMaintenanceOutput, error) {
|
// func (t *MaintenanceTool) GetUpcoming(ctx context.Context, _ *mcp.CallToolRequest, in GetUpcomingMaintenanceInput) (*mcp.CallToolResult, GetUpcomingMaintenanceOutput, error) {
|
||||||
tasks, err := t.store.GetUpcomingMaintenance(ctx, in.DaysAhead)
|
// tasks, err := t.store.GetUpcomingMaintenance(ctx, in.DaysAhead)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetUpcomingMaintenanceOutput{}, err
|
// return nil, GetUpcomingMaintenanceOutput{}, err
|
||||||
}
|
// }
|
||||||
if tasks == nil {
|
// if tasks == nil {
|
||||||
tasks = []ext.MaintenanceTask{}
|
// tasks = []ext.MaintenanceTask{}
|
||||||
}
|
// }
|
||||||
return nil, GetUpcomingMaintenanceOutput{Tasks: tasks}, nil
|
// return nil, GetUpcomingMaintenanceOutput{Tasks: tasks}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// search_maintenance_history
|
// // search_maintenance_history
|
||||||
|
|
||||||
type SearchMaintenanceHistoryInput struct {
|
// type SearchMaintenanceHistoryInput struct {
|
||||||
Query string `json:"query,omitempty" jsonschema:"search text matching task name or notes"`
|
// Query string `json:"query,omitempty" jsonschema:"search text matching task name or notes"`
|
||||||
Category string `json:"category,omitempty" jsonschema:"filter by task category"`
|
// Category string `json:"category,omitempty" jsonschema:"filter by task category"`
|
||||||
Start *time.Time `json:"start,omitempty" jsonschema:"filter logs completed on or after this date"`
|
// Start *time.Time `json:"start,omitempty" jsonschema:"filter logs completed on or after this date"`
|
||||||
End *time.Time `json:"end,omitempty" jsonschema:"filter logs completed on or before this date"`
|
// End *time.Time `json:"end,omitempty" jsonschema:"filter logs completed on or before this date"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type SearchMaintenanceHistoryOutput struct {
|
// type SearchMaintenanceHistoryOutput struct {
|
||||||
Logs []ext.MaintenanceLogWithTask `json:"logs"`
|
// Logs []ext.MaintenanceLogWithTask `json:"logs"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MaintenanceTool) SearchHistory(ctx context.Context, _ *mcp.CallToolRequest, in SearchMaintenanceHistoryInput) (*mcp.CallToolResult, SearchMaintenanceHistoryOutput, error) {
|
// func (t *MaintenanceTool) SearchHistory(ctx context.Context, _ *mcp.CallToolRequest, in SearchMaintenanceHistoryInput) (*mcp.CallToolResult, SearchMaintenanceHistoryOutput, error) {
|
||||||
logs, err := t.store.SearchMaintenanceHistory(ctx, in.Query, in.Category, in.Start, in.End)
|
// logs, err := t.store.SearchMaintenanceHistory(ctx, in.Query, in.Category, in.Start, in.End)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, SearchMaintenanceHistoryOutput{}, err
|
// return nil, SearchMaintenanceHistoryOutput{}, err
|
||||||
}
|
// }
|
||||||
if logs == nil {
|
// if logs == nil {
|
||||||
logs = []ext.MaintenanceLogWithTask{}
|
// logs = []ext.MaintenanceLogWithTask{}
|
||||||
}
|
// }
|
||||||
return nil, SearchMaintenanceHistoryOutput{Logs: logs}, nil
|
// return nil, SearchMaintenanceHistoryOutput{Logs: logs}, nil
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,210 +1,210 @@
|
|||||||
package tools
|
package tools
|
||||||
|
|
||||||
import (
|
// import (
|
||||||
"context"
|
// "context"
|
||||||
"strings"
|
// "strings"
|
||||||
"time"
|
// "time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
// "github.com/google/uuid"
|
||||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
// "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||||
|
|
||||||
"git.warky.dev/wdevs/amcs/internal/store"
|
// "git.warky.dev/wdevs/amcs/internal/store"
|
||||||
ext "git.warky.dev/wdevs/amcs/internal/types"
|
// ext "git.warky.dev/wdevs/amcs/internal/types"
|
||||||
)
|
// )
|
||||||
|
|
||||||
type MealsTool struct {
|
// type MealsTool struct {
|
||||||
store *store.DB
|
// store *store.DB
|
||||||
}
|
// }
|
||||||
|
|
||||||
func NewMealsTool(db *store.DB) *MealsTool {
|
// func NewMealsTool(db *store.DB) *MealsTool {
|
||||||
return &MealsTool{store: db}
|
// return &MealsTool{store: db}
|
||||||
}
|
// }
|
||||||
|
|
||||||
// add_recipe
|
// // add_recipe
|
||||||
|
|
||||||
type AddRecipeInput struct {
|
// type AddRecipeInput struct {
|
||||||
Name string `json:"name" jsonschema:"recipe name"`
|
// Name string `json:"name" jsonschema:"recipe name"`
|
||||||
Cuisine string `json:"cuisine,omitempty"`
|
// Cuisine string `json:"cuisine,omitempty"`
|
||||||
PrepTimeMinutes *int `json:"prep_time_minutes,omitempty"`
|
// PrepTimeMinutes *int `json:"prep_time_minutes,omitempty"`
|
||||||
CookTimeMinutes *int `json:"cook_time_minutes,omitempty"`
|
// CookTimeMinutes *int `json:"cook_time_minutes,omitempty"`
|
||||||
Servings *int `json:"servings,omitempty"`
|
// Servings *int `json:"servings,omitempty"`
|
||||||
Ingredients []ext.Ingredient `json:"ingredients,omitempty" jsonschema:"list of ingredients with name, quantity, unit"`
|
// Ingredients []ext.Ingredient `json:"ingredients,omitempty" jsonschema:"list of ingredients with name, quantity, unit"`
|
||||||
Instructions []string `json:"instructions,omitempty" jsonschema:"ordered list of steps"`
|
// Instructions []string `json:"instructions,omitempty" jsonschema:"ordered list of steps"`
|
||||||
Tags []string `json:"tags,omitempty"`
|
// Tags []string `json:"tags,omitempty"`
|
||||||
Rating *int `json:"rating,omitempty" jsonschema:"1-5 rating"`
|
// Rating *int `json:"rating,omitempty" jsonschema:"1-5 rating"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type AddRecipeOutput struct {
|
// type AddRecipeOutput struct {
|
||||||
Recipe ext.Recipe `json:"recipe"`
|
// Recipe ext.Recipe `json:"recipe"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MealsTool) AddRecipe(ctx context.Context, _ *mcp.CallToolRequest, in AddRecipeInput) (*mcp.CallToolResult, AddRecipeOutput, error) {
|
// func (t *MealsTool) AddRecipe(ctx context.Context, _ *mcp.CallToolRequest, in AddRecipeInput) (*mcp.CallToolResult, AddRecipeOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, AddRecipeOutput{}, errRequiredField("name")
|
// return nil, AddRecipeOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
if in.Ingredients == nil {
|
// if in.Ingredients == nil {
|
||||||
in.Ingredients = []ext.Ingredient{}
|
// in.Ingredients = []ext.Ingredient{}
|
||||||
}
|
// }
|
||||||
if in.Instructions == nil {
|
// if in.Instructions == nil {
|
||||||
in.Instructions = []string{}
|
// in.Instructions = []string{}
|
||||||
}
|
// }
|
||||||
if in.Tags == nil {
|
// if in.Tags == nil {
|
||||||
in.Tags = []string{}
|
// in.Tags = []string{}
|
||||||
}
|
// }
|
||||||
recipe, err := t.store.AddRecipe(ctx, ext.Recipe{
|
// recipe, err := t.store.AddRecipe(ctx, ext.Recipe{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
Cuisine: strings.TrimSpace(in.Cuisine),
|
// Cuisine: strings.TrimSpace(in.Cuisine),
|
||||||
PrepTimeMinutes: in.PrepTimeMinutes,
|
// PrepTimeMinutes: in.PrepTimeMinutes,
|
||||||
CookTimeMinutes: in.CookTimeMinutes,
|
// CookTimeMinutes: in.CookTimeMinutes,
|
||||||
Servings: in.Servings,
|
// Servings: in.Servings,
|
||||||
Ingredients: in.Ingredients,
|
// Ingredients: in.Ingredients,
|
||||||
Instructions: in.Instructions,
|
// Instructions: in.Instructions,
|
||||||
Tags: in.Tags,
|
// Tags: in.Tags,
|
||||||
Rating: in.Rating,
|
// Rating: in.Rating,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, AddRecipeOutput{}, err
|
// return nil, AddRecipeOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, AddRecipeOutput{Recipe: recipe}, nil
|
// return nil, AddRecipeOutput{Recipe: recipe}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// search_recipes
|
// // search_recipes
|
||||||
|
|
||||||
type SearchRecipesInput struct {
|
// type SearchRecipesInput struct {
|
||||||
Query string `json:"query,omitempty" jsonschema:"search by recipe name"`
|
// Query string `json:"query,omitempty" jsonschema:"search by recipe name"`
|
||||||
Cuisine string `json:"cuisine,omitempty"`
|
// Cuisine string `json:"cuisine,omitempty"`
|
||||||
Tags []string `json:"tags,omitempty" jsonschema:"filter by tags (all must match)"`
|
// Tags []string `json:"tags,omitempty" jsonschema:"filter by tags (all must match)"`
|
||||||
Ingredient string `json:"ingredient,omitempty" jsonschema:"filter by ingredient name"`
|
// Ingredient string `json:"ingredient,omitempty" jsonschema:"filter by ingredient name"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type SearchRecipesOutput struct {
|
// type SearchRecipesOutput struct {
|
||||||
Recipes []ext.Recipe `json:"recipes"`
|
// Recipes []ext.Recipe `json:"recipes"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MealsTool) SearchRecipes(ctx context.Context, _ *mcp.CallToolRequest, in SearchRecipesInput) (*mcp.CallToolResult, SearchRecipesOutput, error) {
|
// func (t *MealsTool) SearchRecipes(ctx context.Context, _ *mcp.CallToolRequest, in SearchRecipesInput) (*mcp.CallToolResult, SearchRecipesOutput, error) {
|
||||||
recipes, err := t.store.SearchRecipes(ctx, in.Query, in.Cuisine, in.Tags, in.Ingredient)
|
// recipes, err := t.store.SearchRecipes(ctx, in.Query, in.Cuisine, in.Tags, in.Ingredient)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, SearchRecipesOutput{}, err
|
// return nil, SearchRecipesOutput{}, err
|
||||||
}
|
// }
|
||||||
if recipes == nil {
|
// if recipes == nil {
|
||||||
recipes = []ext.Recipe{}
|
// recipes = []ext.Recipe{}
|
||||||
}
|
// }
|
||||||
return nil, SearchRecipesOutput{Recipes: recipes}, nil
|
// return nil, SearchRecipesOutput{Recipes: recipes}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// update_recipe
|
// // update_recipe
|
||||||
|
|
||||||
type UpdateRecipeInput struct {
|
// type UpdateRecipeInput struct {
|
||||||
ID uuid.UUID `json:"id" jsonschema:"recipe id to update"`
|
// ID uuid.UUID `json:"id" jsonschema:"recipe id to update"`
|
||||||
Name string `json:"name" jsonschema:"recipe name"`
|
// Name string `json:"name" jsonschema:"recipe name"`
|
||||||
Cuisine string `json:"cuisine,omitempty"`
|
// Cuisine string `json:"cuisine,omitempty"`
|
||||||
PrepTimeMinutes *int `json:"prep_time_minutes,omitempty"`
|
// PrepTimeMinutes *int `json:"prep_time_minutes,omitempty"`
|
||||||
CookTimeMinutes *int `json:"cook_time_minutes,omitempty"`
|
// CookTimeMinutes *int `json:"cook_time_minutes,omitempty"`
|
||||||
Servings *int `json:"servings,omitempty"`
|
// Servings *int `json:"servings,omitempty"`
|
||||||
Ingredients []ext.Ingredient `json:"ingredients,omitempty"`
|
// Ingredients []ext.Ingredient `json:"ingredients,omitempty"`
|
||||||
Instructions []string `json:"instructions,omitempty"`
|
// Instructions []string `json:"instructions,omitempty"`
|
||||||
Tags []string `json:"tags,omitempty"`
|
// Tags []string `json:"tags,omitempty"`
|
||||||
Rating *int `json:"rating,omitempty"`
|
// Rating *int `json:"rating,omitempty"`
|
||||||
Notes string `json:"notes,omitempty"`
|
// Notes string `json:"notes,omitempty"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type UpdateRecipeOutput struct {
|
// type UpdateRecipeOutput struct {
|
||||||
Recipe ext.Recipe `json:"recipe"`
|
// Recipe ext.Recipe `json:"recipe"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MealsTool) UpdateRecipe(ctx context.Context, _ *mcp.CallToolRequest, in UpdateRecipeInput) (*mcp.CallToolResult, UpdateRecipeOutput, error) {
|
// func (t *MealsTool) UpdateRecipe(ctx context.Context, _ *mcp.CallToolRequest, in UpdateRecipeInput) (*mcp.CallToolResult, UpdateRecipeOutput, error) {
|
||||||
if strings.TrimSpace(in.Name) == "" {
|
// if strings.TrimSpace(in.Name) == "" {
|
||||||
return nil, UpdateRecipeOutput{}, errRequiredField("name")
|
// return nil, UpdateRecipeOutput{}, errRequiredField("name")
|
||||||
}
|
// }
|
||||||
if in.Ingredients == nil {
|
// if in.Ingredients == nil {
|
||||||
in.Ingredients = []ext.Ingredient{}
|
// in.Ingredients = []ext.Ingredient{}
|
||||||
}
|
// }
|
||||||
if in.Instructions == nil {
|
// if in.Instructions == nil {
|
||||||
in.Instructions = []string{}
|
// in.Instructions = []string{}
|
||||||
}
|
// }
|
||||||
if in.Tags == nil {
|
// if in.Tags == nil {
|
||||||
in.Tags = []string{}
|
// in.Tags = []string{}
|
||||||
}
|
// }
|
||||||
recipe, err := t.store.UpdateRecipe(ctx, in.ID, ext.Recipe{
|
// recipe, err := t.store.UpdateRecipe(ctx, in.ID, ext.Recipe{
|
||||||
Name: strings.TrimSpace(in.Name),
|
// Name: strings.TrimSpace(in.Name),
|
||||||
Cuisine: strings.TrimSpace(in.Cuisine),
|
// Cuisine: strings.TrimSpace(in.Cuisine),
|
||||||
PrepTimeMinutes: in.PrepTimeMinutes,
|
// PrepTimeMinutes: in.PrepTimeMinutes,
|
||||||
CookTimeMinutes: in.CookTimeMinutes,
|
// CookTimeMinutes: in.CookTimeMinutes,
|
||||||
Servings: in.Servings,
|
// Servings: in.Servings,
|
||||||
Ingredients: in.Ingredients,
|
// Ingredients: in.Ingredients,
|
||||||
Instructions: in.Instructions,
|
// Instructions: in.Instructions,
|
||||||
Tags: in.Tags,
|
// Tags: in.Tags,
|
||||||
Rating: in.Rating,
|
// Rating: in.Rating,
|
||||||
Notes: strings.TrimSpace(in.Notes),
|
// Notes: strings.TrimSpace(in.Notes),
|
||||||
})
|
// })
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, UpdateRecipeOutput{}, err
|
// return nil, UpdateRecipeOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, UpdateRecipeOutput{Recipe: recipe}, nil
|
// return nil, UpdateRecipeOutput{Recipe: recipe}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// create_meal_plan
|
// // create_meal_plan
|
||||||
|
|
||||||
type CreateMealPlanInput struct {
|
// type CreateMealPlanInput struct {
|
||||||
WeekStart time.Time `json:"week_start" jsonschema:"Monday of the week to plan"`
|
// WeekStart time.Time `json:"week_start" jsonschema:"Monday of the week to plan"`
|
||||||
Meals []ext.MealPlanInput `json:"meals" jsonschema:"list of meal entries for the week"`
|
// Meals []ext.MealPlanInput `json:"meals" jsonschema:"list of meal entries for the week"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type CreateMealPlanOutput struct {
|
// type CreateMealPlanOutput struct {
|
||||||
Entries []ext.MealPlanEntry `json:"entries"`
|
// Entries []ext.MealPlanEntry `json:"entries"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MealsTool) CreateMealPlan(ctx context.Context, _ *mcp.CallToolRequest, in CreateMealPlanInput) (*mcp.CallToolResult, CreateMealPlanOutput, error) {
|
// func (t *MealsTool) CreateMealPlan(ctx context.Context, _ *mcp.CallToolRequest, in CreateMealPlanInput) (*mcp.CallToolResult, CreateMealPlanOutput, error) {
|
||||||
if len(in.Meals) == 0 {
|
// if len(in.Meals) == 0 {
|
||||||
return nil, CreateMealPlanOutput{}, errInvalidInput("meals are required")
|
// return nil, CreateMealPlanOutput{}, errInvalidInput("meals are required")
|
||||||
}
|
// }
|
||||||
entries, err := t.store.CreateMealPlan(ctx, in.WeekStart, in.Meals)
|
// entries, err := t.store.CreateMealPlan(ctx, in.WeekStart, in.Meals)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, CreateMealPlanOutput{}, err
|
// return nil, CreateMealPlanOutput{}, err
|
||||||
}
|
// }
|
||||||
if entries == nil {
|
// if entries == nil {
|
||||||
entries = []ext.MealPlanEntry{}
|
// entries = []ext.MealPlanEntry{}
|
||||||
}
|
// }
|
||||||
return nil, CreateMealPlanOutput{Entries: entries}, nil
|
// return nil, CreateMealPlanOutput{Entries: entries}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// get_meal_plan
|
// // get_meal_plan
|
||||||
|
|
||||||
type GetMealPlanInput struct {
|
// type GetMealPlanInput struct {
|
||||||
WeekStart time.Time `json:"week_start" jsonschema:"Monday of the week to retrieve"`
|
// WeekStart time.Time `json:"week_start" jsonschema:"Monday of the week to retrieve"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GetMealPlanOutput struct {
|
// type GetMealPlanOutput struct {
|
||||||
Entries []ext.MealPlanEntry `json:"entries"`
|
// Entries []ext.MealPlanEntry `json:"entries"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MealsTool) GetMealPlan(ctx context.Context, _ *mcp.CallToolRequest, in GetMealPlanInput) (*mcp.CallToolResult, GetMealPlanOutput, error) {
|
// func (t *MealsTool) GetMealPlan(ctx context.Context, _ *mcp.CallToolRequest, in GetMealPlanInput) (*mcp.CallToolResult, GetMealPlanOutput, error) {
|
||||||
entries, err := t.store.GetMealPlan(ctx, in.WeekStart)
|
// entries, err := t.store.GetMealPlan(ctx, in.WeekStart)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GetMealPlanOutput{}, err
|
// return nil, GetMealPlanOutput{}, err
|
||||||
}
|
// }
|
||||||
if entries == nil {
|
// if entries == nil {
|
||||||
entries = []ext.MealPlanEntry{}
|
// entries = []ext.MealPlanEntry{}
|
||||||
}
|
// }
|
||||||
return nil, GetMealPlanOutput{Entries: entries}, nil
|
// return nil, GetMealPlanOutput{Entries: entries}, nil
|
||||||
}
|
// }
|
||||||
|
|
||||||
// generate_shopping_list
|
// // generate_shopping_list
|
||||||
|
|
||||||
type GenerateShoppingListInput struct {
|
// type GenerateShoppingListInput struct {
|
||||||
WeekStart time.Time `json:"week_start" jsonschema:"Monday of the week to generate shopping list for"`
|
// WeekStart time.Time `json:"week_start" jsonschema:"Monday of the week to generate shopping list for"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
type GenerateShoppingListOutput struct {
|
// type GenerateShoppingListOutput struct {
|
||||||
ShoppingList ext.ShoppingList `json:"shopping_list"`
|
// ShoppingList ext.ShoppingList `json:"shopping_list"`
|
||||||
}
|
// }
|
||||||
|
|
||||||
func (t *MealsTool) GenerateShoppingList(ctx context.Context, _ *mcp.CallToolRequest, in GenerateShoppingListInput) (*mcp.CallToolResult, GenerateShoppingListOutput, error) {
|
// func (t *MealsTool) GenerateShoppingList(ctx context.Context, _ *mcp.CallToolRequest, in GenerateShoppingListInput) (*mcp.CallToolResult, GenerateShoppingListOutput, error) {
|
||||||
list, err := t.store.GenerateShoppingList(ctx, in.WeekStart)
|
// list, err := t.store.GenerateShoppingList(ctx, in.WeekStart)
|
||||||
if err != nil {
|
// if err != nil {
|
||||||
return nil, GenerateShoppingListOutput{}, err
|
// return nil, GenerateShoppingListOutput{}, err
|
||||||
}
|
// }
|
||||||
return nil, GenerateShoppingListOutput{ShoppingList: list}, nil
|
// return nil, GenerateShoppingListOutput{ShoppingList: list}, nil
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en" class="dark">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
content="AMCS is a memory server that captures, links, and retrieves structured project thoughts for AI assistants using semantic search, summaries, and MCP tools."
|
content="AMCS is a memory server that captures, links, and retrieves structured project thoughts for AI assistants using semantic search, summaries, and MCP tools."
|
||||||
/>
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body class="bg-slate-950">
|
<body class="bg-slate-950" data-theme="amcs">
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
<script type="module" src="/src/main.ts"></script>
|
<script type="module" src="/src/main.ts"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -21,12 +21,12 @@
|
|||||||
"vite": "^8.0.10"
|
"vite": "^8.0.10"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@sentry/svelte": "^10.50.0",
|
"@sentry/svelte": "^10.51.0",
|
||||||
"@skeletonlabs/skeleton": "^4.15.2",
|
"@skeletonlabs/skeleton": "^4.15.2",
|
||||||
"@skeletonlabs/skeleton-svelte": "^4.15.2",
|
"@skeletonlabs/skeleton-svelte": "^4.15.2",
|
||||||
"@tanstack/svelte-virtual": "^3.13.24",
|
"@tanstack/svelte-virtual": "^3.13.24",
|
||||||
"@warkypublic/artemis-kit": "^1.0.10",
|
"@warkypublic/artemis-kit": "^1.0.10",
|
||||||
"@warkypublic/resolvespec-js": "^1.0.1",
|
"@warkypublic/resolvespec-js": "^1.0.1",
|
||||||
"@warkypublic/svelix": "^0.1.39"
|
"@warkypublic/svelix": "^0.1.40"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
82
ui/pnpm-lock.yaml
generated
82
ui/pnpm-lock.yaml
generated
@@ -9,8 +9,8 @@ importers:
|
|||||||
.:
|
.:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry/svelte':
|
'@sentry/svelte':
|
||||||
specifier: ^10.50.0
|
specifier: ^10.51.0
|
||||||
version: 10.50.0(svelte@5.55.5)
|
version: 10.51.0(svelte@5.55.5)
|
||||||
'@skeletonlabs/skeleton':
|
'@skeletonlabs/skeleton':
|
||||||
specifier: ^4.15.2
|
specifier: ^4.15.2
|
||||||
version: 4.15.2(tailwindcss@4.2.4)
|
version: 4.15.2(tailwindcss@4.2.4)
|
||||||
@@ -27,8 +27,8 @@ importers:
|
|||||||
specifier: ^1.0.1
|
specifier: ^1.0.1
|
||||||
version: 1.0.1
|
version: 1.0.1
|
||||||
'@warkypublic/svelix':
|
'@warkypublic/svelix':
|
||||||
specifier: ^0.1.39
|
specifier: ^0.1.40
|
||||||
version: 0.1.39(highlight.js@11.8.0)(svelte@5.55.5)(unified@11.0.5)
|
version: 0.1.40(highlight.js@11.8.0)(svelte@5.55.5)(unified@11.0.5)
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@sveltejs/vite-plugin-svelte':
|
'@sveltejs/vite-plugin-svelte':
|
||||||
specifier: ^7.0.0
|
specifier: ^7.0.0
|
||||||
@@ -315,32 +315,32 @@ packages:
|
|||||||
'@rolldown/pluginutils@1.0.0-rc.17':
|
'@rolldown/pluginutils@1.0.0-rc.17':
|
||||||
resolution: {integrity: sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg==}
|
resolution: {integrity: sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg==}
|
||||||
|
|
||||||
'@sentry-internal/browser-utils@10.50.0':
|
'@sentry-internal/browser-utils@10.51.0':
|
||||||
resolution: {integrity: sha512-42bxyRTxnCmYlWnvz4CxikuQNanw8UNma2WJrtxJ0f1MAJV2GhQGSHDLnA+lvFlmiz6qct3pfen/NXGyOTegTA==}
|
resolution: {integrity: sha512-lNKBS4P7RUvf1niojXQWe9bU3gnBUCbST4Dj0pSiyat1N96cXVyHkeE+uGxowD0RrVWhs+kGHiVX3FcmRWF6sA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@sentry-internal/feedback@10.50.0':
|
'@sentry-internal/feedback@10.51.0':
|
||||||
resolution: {integrity: sha512-0k9XZF0wn86f77mIO2U3gNNyDZooy139CnEanRzHinrN106vVzvBZ6TUEQoHtoO1fqQxr+nWWVrqV/PXUqk47w==}
|
resolution: {integrity: sha512-bCM95bcpphx28e6aU0bwRLxOgwosYsdNzezM1sM0pVOkb0TB3hDFRamramVDK+/Hp1o8qmRxS4c5w/A7YBZGkA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@sentry-internal/replay-canvas@10.50.0':
|
'@sentry-internal/replay-canvas@10.51.0':
|
||||||
resolution: {integrity: sha512-jx6RKBmcJSWdI92qDGS/sBv1w+7Cww879Z/moX7bw7ipHa/Ts3iDcB3rgZwvhmi17U+mvYsbJeL2DXkPo3TjPw==}
|
resolution: {integrity: sha512-8PW1Pp+Yl3lPwYqhBCr5SgkuhDanu9ZLzUqD2bPKL/ElqbM2eDVIWxq4z4ZzePrmZa6IcCjTv6sVQJ7Z4dLyLA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@sentry-internal/replay@10.50.0':
|
'@sentry-internal/replay@10.51.0':
|
||||||
resolution: {integrity: sha512-51FYNfnvVLAWw1rrEWPFfwHuMRb9mkVCFGA4J9/un7SpeGBsQDziGB0Di4fsCxI7+EdSBpfLHPF0csKtCCw0oQ==}
|
resolution: {integrity: sha512-jCpI5HXSwK6ZT2HX70+mDRciAocHzSiDk4DTgvzV69Wvd+Ei5WLgE+d39eaEPsm8lUC0Ydntb5sJIB6uG9D4bw==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@sentry/browser@10.50.0':
|
'@sentry/browser@10.51.0':
|
||||||
resolution: {integrity: sha512-1f6rAvET6myiTaSeYqvaaBwvq1LfxqWjAPIoAW/NVC9bPMkeEcuvgDajHrnZMrBeWoJ81NMyoLkyX+iOc7MoFA==}
|
resolution: {integrity: sha512-Zdc0sKfenxUtW/OGhtJ7xHFN44bXR7YqxJ1zBDzlZfW0nTbeTTUZBq9z5NUw6qdS0Vs/i3V4qzAKTbRKWfqSEA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@sentry/core@10.50.0':
|
'@sentry/core@10.51.0':
|
||||||
resolution: {integrity: sha512-J4A+vzUO3adl0TkFCjaN1+4miamrjHiEIYuLHiuu1lmAjq5WIVw32ObvAh4yMwNtxyaEMosTrrh5M6f12XSJFg==}
|
resolution: {integrity: sha512-Y45V/YXvVLEXmOdkbD1oG1gkRWFi9guCEGg3PlIlIpRjAbZUrvLGgjRJIc1E7XpSzmOnWbs5BbUxMv4PDaPj2w==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@sentry/svelte@10.50.0':
|
'@sentry/svelte@10.51.0':
|
||||||
resolution: {integrity: sha512-pkd9HNpZN+8x9i8n24fpV+Q3/sKDkBKyJ29iNzbhGnZ3CeRPwKxwQOoiBBPQkllYWzr/a7cYFtBKNLdpmTFCOg==}
|
resolution: {integrity: sha512-2/OwIs+WXk+H/CAnWeiQMvXx5EG8LxCtqu4m+HdHtJTUQtERC388zNShZTJU9YYR71KoDOVAU0Q6B2sKNcssFA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
svelte: 3.x || 4.x || 5.x
|
svelte: 3.x || 4.x || 5.x
|
||||||
@@ -758,8 +758,8 @@ packages:
|
|||||||
resolution: {integrity: sha512-uXP1HouxpOKXfwE6qpy0gCcrMPIgjDT53aVGkfork4QejRSunbKWSKKawW2nIm7RnyFhSjPILMXcnT5xUiXOew==}
|
resolution: {integrity: sha512-uXP1HouxpOKXfwE6qpy0gCcrMPIgjDT53aVGkfork4QejRSunbKWSKKawW2nIm7RnyFhSjPILMXcnT5xUiXOew==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@warkypublic/svelix@0.1.39':
|
'@warkypublic/svelix@0.1.40':
|
||||||
resolution: {integrity: sha512-CeKOyabAXTt5MXzRkQyG0G7+1wwgYD/e4+fX9gRsQWxlVVrHv8qdbK1HxHHKMmu4ZW9csf0dXWcEIt/TSM9qAg==}
|
resolution: {integrity: sha512-Pn4T+VVI1Pfrtkbr61oqVyhaUTySU0r6gti9SeSqL+ZJeRfXAj+ZTuwlHzk0w9BxrwlWDnVinGyrpbSjnwb+iQ==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
svelte: ^5.0.0
|
svelte: ^5.0.0
|
||||||
|
|
||||||
@@ -2062,38 +2062,38 @@ snapshots:
|
|||||||
|
|
||||||
'@rolldown/pluginutils@1.0.0-rc.17': {}
|
'@rolldown/pluginutils@1.0.0-rc.17': {}
|
||||||
|
|
||||||
'@sentry-internal/browser-utils@10.50.0':
|
'@sentry-internal/browser-utils@10.51.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry/core': 10.50.0
|
'@sentry/core': 10.51.0
|
||||||
|
|
||||||
'@sentry-internal/feedback@10.50.0':
|
'@sentry-internal/feedback@10.51.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry/core': 10.50.0
|
'@sentry/core': 10.51.0
|
||||||
|
|
||||||
'@sentry-internal/replay-canvas@10.50.0':
|
'@sentry-internal/replay-canvas@10.51.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry-internal/replay': 10.50.0
|
'@sentry-internal/replay': 10.51.0
|
||||||
'@sentry/core': 10.50.0
|
'@sentry/core': 10.51.0
|
||||||
|
|
||||||
'@sentry-internal/replay@10.50.0':
|
'@sentry-internal/replay@10.51.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry-internal/browser-utils': 10.50.0
|
'@sentry-internal/browser-utils': 10.51.0
|
||||||
'@sentry/core': 10.50.0
|
'@sentry/core': 10.51.0
|
||||||
|
|
||||||
'@sentry/browser@10.50.0':
|
'@sentry/browser@10.51.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry-internal/browser-utils': 10.50.0
|
'@sentry-internal/browser-utils': 10.51.0
|
||||||
'@sentry-internal/feedback': 10.50.0
|
'@sentry-internal/feedback': 10.51.0
|
||||||
'@sentry-internal/replay': 10.50.0
|
'@sentry-internal/replay': 10.51.0
|
||||||
'@sentry-internal/replay-canvas': 10.50.0
|
'@sentry-internal/replay-canvas': 10.51.0
|
||||||
'@sentry/core': 10.50.0
|
'@sentry/core': 10.51.0
|
||||||
|
|
||||||
'@sentry/core@10.50.0': {}
|
'@sentry/core@10.51.0': {}
|
||||||
|
|
||||||
'@sentry/svelte@10.50.0(svelte@5.55.5)':
|
'@sentry/svelte@10.51.0(svelte@5.55.5)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sentry/browser': 10.50.0
|
'@sentry/browser': 10.51.0
|
||||||
'@sentry/core': 10.50.0
|
'@sentry/core': 10.51.0
|
||||||
magic-string: 0.30.21
|
magic-string: 0.30.21
|
||||||
svelte: 5.55.5
|
svelte: 5.55.5
|
||||||
|
|
||||||
@@ -2556,7 +2556,7 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
uuid: 13.0.0
|
uuid: 13.0.0
|
||||||
|
|
||||||
'@warkypublic/svelix@0.1.39(highlight.js@11.8.0)(svelte@5.55.5)(unified@11.0.5)':
|
'@warkypublic/svelix@0.1.40(highlight.js@11.8.0)(svelte@5.55.5)(unified@11.0.5)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@cartamd/plugin-anchor': 2.2.0(carta-md@4.11.2(svelte@5.55.5))
|
'@cartamd/plugin-anchor': 2.2.0(carta-md@4.11.2(svelte@5.55.5))
|
||||||
'@cartamd/plugin-attachment': 4.2.0(carta-md@4.11.2(svelte@5.55.5))
|
'@cartamd/plugin-attachment': 4.2.0(carta-md@4.11.2(svelte@5.55.5))
|
||||||
|
|||||||
@@ -199,7 +199,7 @@
|
|||||||
<title>AMCS Admin</title>
|
<title>AMCS Admin</title>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<div class="min-h-screen bg-slate-950 text-slate-100">
|
<div data-theme="amcs" class="min-h-screen bg-slate-950 text-slate-100">
|
||||||
{#if !isLoggedIn.current}
|
{#if !isLoggedIn.current}
|
||||||
<LoginPage
|
<LoginPage
|
||||||
{isOAuthCallback}
|
{isOAuthCallback}
|
||||||
|
|||||||
218
ui/src/amcs.theme.css
Normal file
218
ui/src/amcs.theme.css
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
||||||
|
|
||||||
|
[data-theme='amcs'] {
|
||||||
|
--text-scaling: 1;
|
||||||
|
--base-font-color: var(--color-surface-950);
|
||||||
|
--base-font-color-dark: var(--color-surface-50);
|
||||||
|
--base-font-family: 'Inter', system-ui, sans-serif;
|
||||||
|
--base-font-size: inherit;
|
||||||
|
--base-line-height: 1.5;
|
||||||
|
--base-font-weight: 400;
|
||||||
|
--base-font-style: normal;
|
||||||
|
--base-letter-spacing: 0;
|
||||||
|
--heading-font-color: inherit;
|
||||||
|
--heading-font-color-dark: inherit;
|
||||||
|
--heading-font-family: 'Inter', system-ui, sans-serif;
|
||||||
|
--heading-font-weight: 600;
|
||||||
|
--heading-font-style: normal;
|
||||||
|
--heading-letter-spacing: -0.01em;
|
||||||
|
--anchor-font-color: var(--color-primary-400);
|
||||||
|
--anchor-font-color-dark: var(--color-primary-300);
|
||||||
|
--anchor-font-family: inherit;
|
||||||
|
--anchor-font-size: inherit;
|
||||||
|
--anchor-line-height: inherit;
|
||||||
|
--anchor-font-weight: inherit;
|
||||||
|
--anchor-font-style: inherit;
|
||||||
|
--anchor-letter-spacing: inherit;
|
||||||
|
--anchor-text-decoration: none;
|
||||||
|
--anchor-text-decoration-hover: underline;
|
||||||
|
--anchor-text-decoration-active: none;
|
||||||
|
--anchor-text-decoration-focus: none;
|
||||||
|
--spacing: 0.25rem;
|
||||||
|
--radius-base: 0.75rem;
|
||||||
|
--radius-container: 1rem;
|
||||||
|
--default-border-width: 1px;
|
||||||
|
--default-divide-width: 1px;
|
||||||
|
--default-ring-width: 1px;
|
||||||
|
--body-background-color: var(--color-surface-50);
|
||||||
|
--body-background-color-dark: var(--color-surface-950);
|
||||||
|
|
||||||
|
/* Primary: AMCS cyan */
|
||||||
|
--color-primary-50: oklch(98.4% 0.019 200.87deg);
|
||||||
|
--color-primary-100: oklch(95.6% 0.045 203.39deg);
|
||||||
|
--color-primary-200: oklch(91.7% 0.08 205.04deg);
|
||||||
|
--color-primary-300: oklch(86.5% 0.127 207.08deg);
|
||||||
|
--color-primary-400: oklch(78.9% 0.154 211.53deg);
|
||||||
|
--color-primary-500: oklch(71.5% 0.143 215.22deg);
|
||||||
|
--color-primary-600: oklch(60.9% 0.126 221.72deg);
|
||||||
|
--color-primary-700: oklch(51.9% 0.105 223.13deg);
|
||||||
|
--color-primary-800: oklch(45% 0.085 224.28deg);
|
||||||
|
--color-primary-900: oklch(39.8% 0.07 227.39deg);
|
||||||
|
--color-primary-950: oklch(30.2% 0.056 229.7deg);
|
||||||
|
--color-primary-contrast-dark: var(--color-primary-950);
|
||||||
|
--color-primary-contrast-light: var(--color-primary-50);
|
||||||
|
--color-primary-contrast-50: var(--color-primary-contrast-dark);
|
||||||
|
--color-primary-contrast-100: var(--color-primary-contrast-dark);
|
||||||
|
--color-primary-contrast-200: var(--color-primary-contrast-dark);
|
||||||
|
--color-primary-contrast-300: var(--color-primary-contrast-dark);
|
||||||
|
--color-primary-contrast-400: var(--color-primary-contrast-dark);
|
||||||
|
--color-primary-contrast-500: var(--color-primary-contrast-dark);
|
||||||
|
--color-primary-contrast-600: var(--color-primary-contrast-light);
|
||||||
|
--color-primary-contrast-700: var(--color-primary-contrast-light);
|
||||||
|
--color-primary-contrast-800: var(--color-primary-contrast-light);
|
||||||
|
--color-primary-contrast-900: var(--color-primary-contrast-light);
|
||||||
|
--color-primary-contrast-950: var(--color-primary-contrast-light);
|
||||||
|
|
||||||
|
/* Secondary: deeper steel blue */
|
||||||
|
--color-secondary-50: oklch(97.7% 0.006 247.9deg);
|
||||||
|
--color-secondary-100: oklch(95.2% 0.011 250.1deg);
|
||||||
|
--color-secondary-200: oklch(90.7% 0.021 252.8deg);
|
||||||
|
--color-secondary-300: oklch(83.8% 0.036 254.6deg);
|
||||||
|
--color-secondary-400: oklch(70.4% 0.05 256.7deg);
|
||||||
|
--color-secondary-500: oklch(55.4% 0.046 257.4deg);
|
||||||
|
--color-secondary-600: oklch(46.1% 0.043 257.3deg);
|
||||||
|
--color-secondary-700: oklch(38.7% 0.044 257.3deg);
|
||||||
|
--color-secondary-800: oklch(30.5% 0.043 260deg);
|
||||||
|
--color-secondary-900: oklch(24.6% 0.042 264deg);
|
||||||
|
--color-secondary-950: oklch(17.8% 0.041 265deg);
|
||||||
|
--color-secondary-contrast-dark: var(--color-secondary-950);
|
||||||
|
--color-secondary-contrast-light: var(--color-secondary-50);
|
||||||
|
--color-secondary-contrast-50: var(--color-secondary-contrast-dark);
|
||||||
|
--color-secondary-contrast-100: var(--color-secondary-contrast-dark);
|
||||||
|
--color-secondary-contrast-200: var(--color-secondary-contrast-dark);
|
||||||
|
--color-secondary-contrast-300: var(--color-secondary-contrast-dark);
|
||||||
|
--color-secondary-contrast-400: var(--color-secondary-contrast-light);
|
||||||
|
--color-secondary-contrast-500: var(--color-secondary-contrast-light);
|
||||||
|
--color-secondary-contrast-600: var(--color-secondary-contrast-light);
|
||||||
|
--color-secondary-contrast-700: var(--color-secondary-contrast-light);
|
||||||
|
--color-secondary-contrast-800: var(--color-secondary-contrast-light);
|
||||||
|
--color-secondary-contrast-900: var(--color-secondary-contrast-light);
|
||||||
|
--color-secondary-contrast-950: var(--color-secondary-contrast-light);
|
||||||
|
|
||||||
|
/* Tertiary: bright highlight cyan */
|
||||||
|
--color-tertiary-50: oklch(98.5% 0.02 214deg);
|
||||||
|
--color-tertiary-100: oklch(96.2% 0.05 214deg);
|
||||||
|
--color-tertiary-200: oklch(92.4% 0.088 213deg);
|
||||||
|
--color-tertiary-300: oklch(87.1% 0.132 212deg);
|
||||||
|
--color-tertiary-400: oklch(80.2% 0.157 211deg);
|
||||||
|
--color-tertiary-500: oklch(73.8% 0.145 210deg);
|
||||||
|
--color-tertiary-600: oklch(64.2% 0.126 214deg);
|
||||||
|
--color-tertiary-700: oklch(55.2% 0.107 218deg);
|
||||||
|
--color-tertiary-800: oklch(46.1% 0.087 221deg);
|
||||||
|
--color-tertiary-900: oklch(38.7% 0.07 225deg);
|
||||||
|
--color-tertiary-950: oklch(29.1% 0.053 229deg);
|
||||||
|
--color-tertiary-contrast-dark: var(--color-tertiary-950);
|
||||||
|
--color-tertiary-contrast-light: var(--color-tertiary-50);
|
||||||
|
--color-tertiary-contrast-50: var(--color-tertiary-contrast-dark);
|
||||||
|
--color-tertiary-contrast-100: var(--color-tertiary-contrast-dark);
|
||||||
|
--color-tertiary-contrast-200: var(--color-tertiary-contrast-dark);
|
||||||
|
--color-tertiary-contrast-300: var(--color-tertiary-contrast-dark);
|
||||||
|
--color-tertiary-contrast-400: var(--color-tertiary-contrast-dark);
|
||||||
|
--color-tertiary-contrast-500: var(--color-tertiary-contrast-dark);
|
||||||
|
--color-tertiary-contrast-600: var(--color-tertiary-contrast-light);
|
||||||
|
--color-tertiary-contrast-700: var(--color-tertiary-contrast-light);
|
||||||
|
--color-tertiary-contrast-800: var(--color-tertiary-contrast-light);
|
||||||
|
--color-tertiary-contrast-900: var(--color-tertiary-contrast-light);
|
||||||
|
--color-tertiary-contrast-950: var(--color-tertiary-contrast-light);
|
||||||
|
|
||||||
|
--color-success-50: oklch(97.9% 0.021 166deg);
|
||||||
|
--color-success-100: oklch(95.1% 0.05 167deg);
|
||||||
|
--color-success-200: oklch(90.5% 0.09 166deg);
|
||||||
|
--color-success-300: oklch(84.2% 0.137 165deg);
|
||||||
|
--color-success-400: oklch(76.5% 0.146 164deg);
|
||||||
|
--color-success-500: oklch(69.6% 0.135 163deg);
|
||||||
|
--color-success-600: oklch(59.6% 0.115 163deg);
|
||||||
|
--color-success-700: oklch(50.8% 0.096 164deg);
|
||||||
|
--color-success-800: oklch(42.7% 0.077 165deg);
|
||||||
|
--color-success-900: oklch(35.4% 0.061 166deg);
|
||||||
|
--color-success-950: oklch(24.5% 0.041 168deg);
|
||||||
|
--color-success-contrast-dark: var(--color-success-950);
|
||||||
|
--color-success-contrast-light: var(--color-success-50);
|
||||||
|
--color-success-contrast-50: var(--color-success-contrast-dark);
|
||||||
|
--color-success-contrast-100: var(--color-success-contrast-dark);
|
||||||
|
--color-success-contrast-200: var(--color-success-contrast-dark);
|
||||||
|
--color-success-contrast-300: var(--color-success-contrast-dark);
|
||||||
|
--color-success-contrast-400: var(--color-success-contrast-dark);
|
||||||
|
--color-success-contrast-500: var(--color-success-contrast-dark);
|
||||||
|
--color-success-contrast-600: var(--color-success-contrast-light);
|
||||||
|
--color-success-contrast-700: var(--color-success-contrast-light);
|
||||||
|
--color-success-contrast-800: var(--color-success-contrast-light);
|
||||||
|
--color-success-contrast-900: var(--color-success-contrast-light);
|
||||||
|
--color-success-contrast-950: var(--color-success-contrast-light);
|
||||||
|
|
||||||
|
--color-warning-50: oklch(98.7% 0.022 95deg);
|
||||||
|
--color-warning-100: oklch(96.2% 0.05 93deg);
|
||||||
|
--color-warning-200: oklch(92.5% 0.095 90deg);
|
||||||
|
--color-warning-300: oklch(87.9% 0.145 86deg);
|
||||||
|
--color-warning-400: oklch(82.8% 0.168 81deg);
|
||||||
|
--color-warning-500: oklch(76.9% 0.164 74deg);
|
||||||
|
--color-warning-600: oklch(66.6% 0.149 66deg);
|
||||||
|
--color-warning-700: oklch(56.3% 0.13 60deg);
|
||||||
|
--color-warning-800: oklch(47.8% 0.111 56deg);
|
||||||
|
--color-warning-900: oklch(40.5% 0.094 53deg);
|
||||||
|
--color-warning-950: oklch(28.2% 0.066 49deg);
|
||||||
|
--color-warning-contrast-dark: var(--color-warning-950);
|
||||||
|
--color-warning-contrast-light: var(--color-warning-50);
|
||||||
|
--color-warning-contrast-50: var(--color-warning-contrast-dark);
|
||||||
|
--color-warning-contrast-100: var(--color-warning-contrast-dark);
|
||||||
|
--color-warning-contrast-200: var(--color-warning-contrast-dark);
|
||||||
|
--color-warning-contrast-300: var(--color-warning-contrast-dark);
|
||||||
|
--color-warning-contrast-400: var(--color-warning-contrast-dark);
|
||||||
|
--color-warning-contrast-500: var(--color-warning-contrast-dark);
|
||||||
|
--color-warning-contrast-600: var(--color-warning-contrast-light);
|
||||||
|
--color-warning-contrast-700: var(--color-warning-contrast-light);
|
||||||
|
--color-warning-contrast-800: var(--color-warning-contrast-light);
|
||||||
|
--color-warning-contrast-900: var(--color-warning-contrast-light);
|
||||||
|
--color-warning-contrast-950: var(--color-warning-contrast-light);
|
||||||
|
|
||||||
|
--color-error-50: oklch(97.1% 0.014 17deg);
|
||||||
|
--color-error-100: oklch(93.7% 0.032 18deg);
|
||||||
|
--color-error-200: oklch(88.5% 0.062 19deg);
|
||||||
|
--color-error-300: oklch(81.4% 0.104 21deg);
|
||||||
|
--color-error-400: oklch(71.2% 0.164 24deg);
|
||||||
|
--color-error-500: oklch(63.7% 0.208 25deg);
|
||||||
|
--color-error-600: oklch(57.7% 0.204 26deg);
|
||||||
|
--color-error-700: oklch(50.5% 0.182 27deg);
|
||||||
|
--color-error-800: oklch(44.4% 0.156 27deg);
|
||||||
|
--color-error-900: oklch(39.6% 0.129 28deg);
|
||||||
|
--color-error-950: oklch(25.8% 0.082 28deg);
|
||||||
|
--color-error-contrast-dark: var(--color-error-950);
|
||||||
|
--color-error-contrast-light: var(--color-error-50);
|
||||||
|
--color-error-contrast-50: var(--color-error-contrast-dark);
|
||||||
|
--color-error-contrast-100: var(--color-error-contrast-dark);
|
||||||
|
--color-error-contrast-200: var(--color-error-contrast-dark);
|
||||||
|
--color-error-contrast-300: var(--color-error-contrast-dark);
|
||||||
|
--color-error-contrast-400: var(--color-error-contrast-dark);
|
||||||
|
--color-error-contrast-500: var(--color-error-contrast-light);
|
||||||
|
--color-error-contrast-600: var(--color-error-contrast-light);
|
||||||
|
--color-error-contrast-700: var(--color-error-contrast-light);
|
||||||
|
--color-error-contrast-800: var(--color-error-contrast-light);
|
||||||
|
--color-error-contrast-900: var(--color-error-contrast-light);
|
||||||
|
--color-error-contrast-950: var(--color-error-contrast-light);
|
||||||
|
|
||||||
|
/* Surface: slate-based AMCS dark shell */
|
||||||
|
--color-surface-50: oklch(98.4% 0.003 247.86deg);
|
||||||
|
--color-surface-100: oklch(96.8% 0.007 247.9deg);
|
||||||
|
--color-surface-200: oklch(92.9% 0.013 255.51deg);
|
||||||
|
--color-surface-300: oklch(86.9% 0.022 252.89deg);
|
||||||
|
--color-surface-400: oklch(70.4% 0.04 256.79deg);
|
||||||
|
--color-surface-500: oklch(55.4% 0.046 257.42deg);
|
||||||
|
--color-surface-600: oklch(44.6% 0.043 257.28deg);
|
||||||
|
--color-surface-700: oklch(37.2% 0.044 257.29deg);
|
||||||
|
--color-surface-800: oklch(27.9% 0.041 260.03deg);
|
||||||
|
--color-surface-900: oklch(20.8% 0.042 265.76deg);
|
||||||
|
--color-surface-950: oklch(12.9% 0.042 264.7deg);
|
||||||
|
--color-surface-contrast-dark: var(--color-surface-950);
|
||||||
|
--color-surface-contrast-light: var(--color-surface-50);
|
||||||
|
--color-surface-contrast-50: var(--color-surface-contrast-dark);
|
||||||
|
--color-surface-contrast-100: var(--color-surface-contrast-dark);
|
||||||
|
--color-surface-contrast-200: var(--color-surface-contrast-dark);
|
||||||
|
--color-surface-contrast-300: var(--color-surface-contrast-dark);
|
||||||
|
--color-surface-contrast-400: var(--color-surface-contrast-light);
|
||||||
|
--color-surface-contrast-500: var(--color-surface-contrast-light);
|
||||||
|
--color-surface-contrast-600: var(--color-surface-contrast-light);
|
||||||
|
--color-surface-contrast-700: var(--color-surface-contrast-light);
|
||||||
|
--color-surface-contrast-800: var(--color-surface-contrast-light);
|
||||||
|
--color-surface-contrast-900: var(--color-surface-contrast-light);
|
||||||
|
--color-surface-contrast-950: var(--color-surface-contrast-light);
|
||||||
|
}
|
||||||
@@ -152,7 +152,10 @@ export const api = {
|
|||||||
create: (name: string, description: string) =>
|
create: (name: string, description: string) =>
|
||||||
rsCall<import('./types').Project>('/api/rs/public/projects', 'create', {
|
rsCall<import('./types').Project>('/api/rs/public/projects', 'create', {
|
||||||
data: { name, description }
|
data: { name, description }
|
||||||
})
|
}),
|
||||||
|
update: (id: string, data: { name?: string; description?: string }) =>
|
||||||
|
rsCall<void>(`/api/rs/public/projects/${id}`, 'update', { data }),
|
||||||
|
delete: (id: string) => rsCall<void>(`/api/rs/public/projects/${id}`, 'delete')
|
||||||
},
|
},
|
||||||
thoughts: {
|
thoughts: {
|
||||||
list: (params: { q?: string; project_id?: string; limit?: number; offset?: number; include_archived?: boolean }) => {
|
list: (params: { q?: string; project_id?: string; limit?: number; offset?: number; include_archived?: boolean }) => {
|
||||||
@@ -232,7 +235,11 @@ export const api = {
|
|||||||
archive: (id: string) =>
|
archive: (id: string) =>
|
||||||
rsCall<void>(`/api/rs/public/thoughts/${id}`, 'update', {
|
rsCall<void>(`/api/rs/public/thoughts/${id}`, 'update', {
|
||||||
data: { archived_at: new Date().toISOString() }
|
data: { archived_at: new Date().toISOString() }
|
||||||
})
|
}),
|
||||||
|
create: (data: { content: string; project_id?: string }) =>
|
||||||
|
rsCall<import('./types').Thought>('/api/rs/public/thoughts', 'create', { data }),
|
||||||
|
update: (id: string, data: { content?: string }) =>
|
||||||
|
rsCall<void>(`/api/rs/public/thoughts/${id}`, 'update', { data })
|
||||||
},
|
},
|
||||||
skills: {
|
skills: {
|
||||||
list: async (tag?: string) => {
|
list: async (tag?: string) => {
|
||||||
@@ -243,7 +250,18 @@ export const api = {
|
|||||||
});
|
});
|
||||||
return rows.map((row) => ({ ...row, tags: normalizeTags(row.tags) }));
|
return rows.map((row) => ({ ...row, tags: normalizeTags(row.tags) }));
|
||||||
},
|
},
|
||||||
delete: (id: string) => rsCall<void>(`/api/rs/public/agent_skills/${id}`, 'delete')
|
get: async (id: string) => {
|
||||||
|
const row = await rsCall<Omit<import('./types').AgentSkill, 'tags'> & { tags?: unknown }>(
|
||||||
|
`/api/rs/public/agent_skills/${id}`,
|
||||||
|
'read'
|
||||||
|
);
|
||||||
|
return { ...row, tags: normalizeTags(row.tags) };
|
||||||
|
},
|
||||||
|
create: (data: { name: string; description?: string; content: string; tags?: string[] }) =>
|
||||||
|
rsCall<import('./types').AgentSkill>('/api/rs/public/agent_skills', 'create', { data }),
|
||||||
|
delete: (id: string) => rsCall<void>(`/api/rs/public/agent_skills/${id}`, 'delete'),
|
||||||
|
update: (id: string, data: Partial<import('./types').AgentSkill>) =>
|
||||||
|
rsCall<void>(`/api/rs/public/agent_skills/${id}`, 'update', { data })
|
||||||
},
|
},
|
||||||
guardrails: {
|
guardrails: {
|
||||||
list: async (params?: { tag?: string; severity?: string }) => {
|
list: async (params?: { tag?: string; severity?: string }) => {
|
||||||
@@ -258,7 +276,9 @@ export const api = {
|
|||||||
});
|
});
|
||||||
return rows.map((row) => ({ ...row, tags: normalizeTags(row.tags) }));
|
return rows.map((row) => ({ ...row, tags: normalizeTags(row.tags) }));
|
||||||
},
|
},
|
||||||
delete: (id: string) => rsCall<void>(`/api/rs/public/agent_guardrails/${id}`, 'delete')
|
delete: (id: string) => rsCall<void>(`/api/rs/public/agent_guardrails/${id}`, 'delete'),
|
||||||
|
update: (id: string, data: Partial<import('./types').AgentGuardrail>) =>
|
||||||
|
rsCall<void>(`/api/rs/public/agent_guardrails/${id}`, 'update', { data })
|
||||||
},
|
},
|
||||||
files: {
|
files: {
|
||||||
list: (params?: { project_id?: string; thought_id?: string; kind?: string }) => {
|
list: (params?: { project_id?: string; thought_id?: string; kind?: string }) => {
|
||||||
@@ -326,7 +346,34 @@ export const api = {
|
|||||||
sort: [{ column: 'updated_at', direction: 'desc' }]
|
sort: [{ column: 'updated_at', direction: 'desc' }]
|
||||||
});
|
});
|
||||||
return rows.map((row) => ({ ...row, tags: normalizeTags(row.tags) }));
|
return rows.map((row) => ({ ...row, tags: normalizeTags(row.tags) }));
|
||||||
}
|
},
|
||||||
|
get: async (id: string) => {
|
||||||
|
const row = await rsCall<Omit<import('./types').Plan, 'tags'> & { tags?: unknown }>(
|
||||||
|
`/api/rs/public/plans/${id}`,
|
||||||
|
'read'
|
||||||
|
);
|
||||||
|
return { ...row, tags: normalizeTags(row.tags) };
|
||||||
|
},
|
||||||
|
create: (data: object) =>
|
||||||
|
rsCall<import('./types').Plan>('/api/rs/public/plans', 'create', { data }),
|
||||||
|
update: (id: string, data: Partial<import('./types').Plan>) =>
|
||||||
|
rsCall<void>(`/api/rs/public/plans/${id}`, 'update', { data }),
|
||||||
|
delete: (id: string) => rsCall<void>(`/api/rs/public/plans/${id}`, 'delete')
|
||||||
|
},
|
||||||
|
learnings: {
|
||||||
|
list: (params?: { limit?: number; offset?: number }) =>
|
||||||
|
rsReadMany<import('./types').Learning>('learnings', {
|
||||||
|
limit: params?.limit ?? 500,
|
||||||
|
...(params?.offset !== undefined ? { offset: params.offset } : {}),
|
||||||
|
sort: [{ column: 'created_at', direction: 'desc' }]
|
||||||
|
}),
|
||||||
|
get: (id: string) =>
|
||||||
|
rsCall<import('./types').Learning>(`/api/rs/public/learnings/${id}`, 'read'),
|
||||||
|
create: (data: object) =>
|
||||||
|
rsCall<import('./types').Learning>('/api/rs/public/learnings', 'create', { data }),
|
||||||
|
update: (id: string, data: Partial<import('./types').Learning>) =>
|
||||||
|
rsCall<void>(`/api/rs/public/learnings/${id}`, 'update', { data }),
|
||||||
|
delete: (id: string) => rsCall<void>(`/api/rs/public/learnings/${id}`, 'delete')
|
||||||
},
|
},
|
||||||
stats: async () => {
|
stats: async () => {
|
||||||
type StatsThoughtRow = {
|
type StatsThoughtRow = {
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
|
@custom-variant dark (&:where(.dark, .dark *));
|
||||||
|
@import '@warkypublic/svelix/css/tailwind-source.css';
|
||||||
|
@import './amcs.theme.css';
|
||||||
|
@import '@skeletonlabs/skeleton';
|
||||||
|
@import '@skeletonlabs/skeleton-svelte';
|
||||||
|
@import '@skeletonlabs/skeleton/themes/cerberus';
|
||||||
|
|
||||||
|
@source '../node_modules/@skeletonlabs/skeleton-svelte/dist/**/*.{js,svelte,ts}';
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
@@ -14,3 +22,12 @@ body,
|
|||||||
body {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
.input::placeholder,
|
||||||
|
.textarea::placeholder,
|
||||||
|
input::placeholder,
|
||||||
|
textarea::placeholder {
|
||||||
|
opacity: 0.65;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,11 +1,162 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import {
|
||||||
import { api } from '../../api';
|
ErrorBoundary,
|
||||||
import type { StoredFile } from '../../types';
|
FormerResolveSpecAPI,
|
||||||
|
GridlerFull,
|
||||||
|
TextAreaCtrl,
|
||||||
|
TextInputCtrl,
|
||||||
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem,
|
||||||
|
} from "@warkypublic/svelix";
|
||||||
|
import { adminGridTheme } from "../../gridTheme";
|
||||||
|
import { GlobalStateStore } from "../../shellState";
|
||||||
|
import type { StoredFile } from "../../types";
|
||||||
|
import FormerShell from "../shared/FormerShell.svelte";
|
||||||
|
|
||||||
let files = $state<StoredFile[]>([]);
|
type FileForm = {
|
||||||
let loading = $state(true);
|
id?: string;
|
||||||
let error = $state('');
|
name: string;
|
||||||
|
media_type: string;
|
||||||
|
kind: string;
|
||||||
|
project_id?: string;
|
||||||
|
thought_id?: string;
|
||||||
|
encoding?: string;
|
||||||
|
content?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const FILE_PRIMARY_KEY = 'id';
|
||||||
|
|
||||||
|
let selectedFile = $state<StoredFile | null>(null);
|
||||||
|
let gridTotal = $state<number | null>(null);
|
||||||
|
let formOpened = $state(false);
|
||||||
|
let formRequest = $state<'insert' | 'update' | 'delete'>('update');
|
||||||
|
let formValues = $state<FileForm>({ name: '', media_type: '', kind: 'file', encoding: 'base64', content: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const filesOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/stored_files'
|
||||||
|
}));
|
||||||
|
|
||||||
|
const columns: GridlerColumn[] = [
|
||||||
|
{ id: 'name', title: 'Name', dataKey: 'name', width: 280 },
|
||||||
|
{ id: 'media_type', title: 'Type', dataKey: 'media_type', width: 220 },
|
||||||
|
{ id: 'kind', title: 'Kind', dataKey: 'kind', width: 120 },
|
||||||
|
{ id: 'size_bytes', title: 'Size', dataKey: 'size_bytes', width: 120, format: 'number' },
|
||||||
|
{ id: 'thought_id', title: 'Thought', dataKey: 'thought_id', width: 220 },
|
||||||
|
{ id: 'project_id', title: 'Project', dataKey: 'project_id', width: 220 },
|
||||||
|
{ id: 'created_at', title: 'Uploaded', dataKey: 'created_at', width: 180, format: 'datetime' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
|
{ id: 'edit', label: 'Edit' },
|
||||||
|
{ id: 'delete', label: 'Delete' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const filesDataSourceOptions = {
|
||||||
|
url: '/api/rs',
|
||||||
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
|
schema: 'public',
|
||||||
|
entity: 'stored_files',
|
||||||
|
uniqueID: FILE_PRIMARY_KEY,
|
||||||
|
hotfields: [FILE_PRIMARY_KEY, 'guid', 'project_id', 'thought_id'],
|
||||||
|
columns: ['id', 'guid', 'name', 'media_type', 'kind', 'size_bytes', 'created_at', 'updated_at', 'project_id', 'thought_id'],
|
||||||
|
sort: [{ column: 'created_at', direction: 'desc' }]
|
||||||
|
} as unknown as {
|
||||||
|
url: string;
|
||||||
|
authToken?: string;
|
||||||
|
schema: string;
|
||||||
|
entity: string;
|
||||||
|
uniqueID: string;
|
||||||
|
hotfields: string[];
|
||||||
|
columns: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeFile(rowData: Record<string, unknown>): StoredFile {
|
||||||
|
return {
|
||||||
|
id: String(rowData.id ?? ''),
|
||||||
|
name: String(rowData.name ?? ''),
|
||||||
|
media_type: String(rowData.media_type ?? ''),
|
||||||
|
kind: String(rowData.kind ?? ''),
|
||||||
|
size_bytes: Number(rowData.size_bytes ?? 0),
|
||||||
|
thought_id: typeof rowData.thought_id === 'string' ? rowData.thought_id : undefined,
|
||||||
|
project_id: typeof rowData.project_id === 'string' ? rowData.project_id : undefined,
|
||||||
|
sha256: String(rowData.sha256 ?? ''),
|
||||||
|
created_at: String(rowData.created_at ?? ''),
|
||||||
|
updated_at: String(rowData.updated_at ?? '')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFileRecordForFormer(data: Record<string, unknown>): FileForm {
|
||||||
|
return {
|
||||||
|
id: typeof data.id === 'string' || typeof data.id === 'number' ? String(data.id) : undefined,
|
||||||
|
name: typeof data.name === 'string' ? data.name : '',
|
||||||
|
media_type: typeof data.media_type === 'string' ? data.media_type : '',
|
||||||
|
kind: typeof data.kind === 'string' ? data.kind : 'file',
|
||||||
|
project_id: typeof data.project_id === 'string' && data.project_id ? data.project_id : undefined,
|
||||||
|
thought_id: typeof data.thought_id === 'string' && data.thought_id ? data.thought_id : undefined,
|
||||||
|
encoding: typeof data.encoding === 'string' ? data.encoding : 'base64',
|
||||||
|
content: typeof data.content === 'string' ? data.content : ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadFileFromRow(rowData: Record<string, unknown>): Promise<FileForm> {
|
||||||
|
const id = String(rowData[FILE_PRIMARY_KEY] ?? '');
|
||||||
|
const data = await filesOnAPICall('read', 'update', undefined, id) as Record<string, unknown>;
|
||||||
|
return normalizeFileRecordForFormer(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
selectedFile = rowData ? normalizeFile(rowData) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (!contextRow) return;
|
||||||
|
formValues = normalizeFileRecordForFormer(contextRow);
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onGridEvent(
|
||||||
|
type: string,
|
||||||
|
_item?: unknown,
|
||||||
|
_column?: unknown,
|
||||||
|
_coords?: unknown,
|
||||||
|
detail?: Record<string, unknown>
|
||||||
|
) {
|
||||||
|
if (type !== 'page_loaded' && type !== 'load') return;
|
||||||
|
const total = detail?.total;
|
||||||
|
if (typeof total === 'number') gridTotal = total;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFileForm(data: FileForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
name: data.name.trim(),
|
||||||
|
media_type: data.media_type.trim(),
|
||||||
|
kind: data.kind.trim(),
|
||||||
|
project_id: data.project_id?.trim() || undefined,
|
||||||
|
thought_id: data.thought_id?.trim() || undefined
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleFileSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
if (contextRow) {
|
||||||
|
selectedFile = normalizeFile(contextRow);
|
||||||
|
}
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
|
|
||||||
function formatBytes(n: number): string {
|
function formatBytes(n: number): string {
|
||||||
if (n < 1024) return `${n} B`;
|
if (n < 1024) return `${n} B`;
|
||||||
@@ -13,80 +164,145 @@
|
|||||||
return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(value: string) {
|
function formatDate(value?: string): string {
|
||||||
|
if (!value) return '—';
|
||||||
return new Date(value).toLocaleString();
|
return new Date(value).toLocaleString();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function load() {
|
|
||||||
loading = true;
|
|
||||||
error = '';
|
|
||||||
try {
|
|
||||||
files = await api.files.list();
|
|
||||||
} catch (e) {
|
|
||||||
error = e instanceof Error ? e.message : 'Failed to load files';
|
|
||||||
} finally {
|
|
||||||
loading = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(load);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="space-y-4">
|
<div class="space-y-4 w-full">
|
||||||
<div class="flex items-end justify-between">
|
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-2xl font-semibold text-white">Files</h2>
|
<h2 class="text-2xl font-semibold text-white">Files</h2>
|
||||||
<p class="mt-1 text-sm text-slate-400">{files.length} file{files.length !== 1 ? 's' : ''}</p>
|
<p class="mt-1 text-sm text-slate-400">
|
||||||
</div>
|
{#if gridTotal === null}
|
||||||
<button
|
Server-backed grid
|
||||||
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
|
||||||
onclick={load}
|
|
||||||
>Refresh</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if error}
|
|
||||||
<div class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-4 text-sm text-rose-100">{error}</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if loading}
|
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-400">Loading…</div>
|
|
||||||
{:else if files.length === 0}
|
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-500">No files stored.</div>
|
|
||||||
{:else}
|
{:else}
|
||||||
<div class="overflow-hidden rounded-2xl border border-white/10">
|
{gridTotal} file{gridTotal !== 1 ? 's' : ''}
|
||||||
<table class="min-w-full divide-y divide-white/10 text-sm text-slate-300">
|
{/if}
|
||||||
<thead class="bg-white/5 text-xs uppercase tracking-[0.18em] text-slate-500">
|
</p>
|
||||||
<tr>
|
</div>
|
||||||
<th class="px-4 py-3 text-left font-medium">Name</th>
|
</div>
|
||||||
<th class="px-4 py-3 text-left font-medium">Type</th>
|
|
||||||
<th class="px-4 py-3 text-left font-medium">Kind</th>
|
<div class="flex flex-col gap-4">
|
||||||
<th class="px-4 py-3 text-right font-medium">Size</th>
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
<th class="px-4 py-3 text-right font-medium">Uploaded</th>
|
{#key refreshKey}
|
||||||
<th class="px-4 py-3 text-right font-medium">Download</th>
|
<ErrorBoundary namespace="FilesGridlerFull">
|
||||||
</tr>
|
<GridlerFull
|
||||||
</thead>
|
{columns}
|
||||||
<tbody class="divide-y divide-white/5 bg-slate-950/30">
|
theme={adminGridTheme}
|
||||||
{#each files as f}
|
rowMarkers="number"
|
||||||
<tr class="hover:bg-white/[0.03]">
|
height={560}
|
||||||
<td class="max-w-xs truncate px-4 py-3 font-medium text-white">{f.name}</td>
|
width="100%"
|
||||||
<td class="px-4 py-3 text-slate-400 text-xs">{f.media_type}</td>
|
pageSize={40}
|
||||||
<td class="px-4 py-3">
|
dataSource="resolvespec"
|
||||||
<span class="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-xs text-slate-300">{f.kind || '—'}</span>
|
dataSourceOptions={filesDataSourceOptions}
|
||||||
</td>
|
serverSideSearch={true}
|
||||||
<td class="px-4 py-3 text-right tabular-nums text-slate-200">{formatBytes(f.size_bytes)}</td>
|
searchColumns={['name', 'media_type', 'kind', 'project_id', 'thought_id']}
|
||||||
<td class="px-4 py-3 text-right text-slate-400">{formatDate(f.created_at)}</td>
|
{menuItems}
|
||||||
<td class="px-4 py-3 text-right">
|
{onGridEvent}
|
||||||
|
{onRowClick}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
|
<h3 class="text-sm font-semibold text-white">File Inspector</h3>
|
||||||
|
{#if !selectedFile}
|
||||||
|
<p class="mt-3 text-sm text-slate-500">Select a file row to inspect metadata.</p>
|
||||||
|
{:else}
|
||||||
|
<div class="mt-3 space-y-3 text-sm text-slate-300">
|
||||||
|
<p class="text-base font-semibold text-slate-100">{selectedFile.name}</p>
|
||||||
|
<div class="rounded-xl border border-white/10 bg-white/5 p-3 space-y-1">
|
||||||
|
<p><strong class="text-slate-100">Type:</strong> {selectedFile.media_type}</p>
|
||||||
|
<p><strong class="text-slate-100">Kind:</strong> {selectedFile.kind || '—'}</p>
|
||||||
|
<p><strong class="text-slate-100">Size:</strong> {formatBytes(selectedFile.size_bytes)}</p>
|
||||||
|
<p><strong class="text-slate-100">Thought:</strong> {selectedFile.thought_id || '—'}</p>
|
||||||
|
<p><strong class="text-slate-100">Project:</strong> {selectedFile.project_id || '—'}</p>
|
||||||
|
<p><strong class="text-slate-100">Uploaded:</strong> {formatDate(selectedFile.created_at)}</p>
|
||||||
|
<p><strong class="text-slate-100">Updated:</strong> {formatDate(selectedFile.updated_at)}</p>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
<a
|
<a
|
||||||
href={`/files/${f.id}`}
|
href={`/files/${selectedFile.id}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noreferrer"
|
rel="noreferrer"
|
||||||
class="text-xs text-cyan-400 hover:text-cyan-300"
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
>↓</a>
|
>Download</a>
|
||||||
</td>
|
</div>
|
||||||
</tr>
|
|
||||||
{/each}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="FilesFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'update' ? 'Edit File' : 'Delete File'}
|
||||||
|
uniqueKeyField={FILE_PRIMARY_KEY}
|
||||||
|
onAPICall={filesOnAPICall}
|
||||||
|
afterGet={async (data) => normalizeFileRecordForFormer(data as Record<string, unknown>)}
|
||||||
|
beforeSave={normalizeFileForm}
|
||||||
|
afterSave={handleFileSaved}
|
||||||
|
onClose={() => { formOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<div class="space-y-4 p-4">
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Name"
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.name ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, name: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Media Type"
|
||||||
|
name="media_type"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.media_type ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, media_type: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Kind"
|
||||||
|
name="kind"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.kind ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, kind: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Project ID"
|
||||||
|
name="project_id"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.project_id ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, project_id: v || undefined })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Thought ID"
|
||||||
|
name="thought_id"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.thought_id ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, thought_id: v || undefined })}
|
||||||
|
/>
|
||||||
|
{#if state.request !== 'delete'}
|
||||||
|
<TextAreaCtrl
|
||||||
|
label="Content"
|
||||||
|
name="content"
|
||||||
|
rows={4}
|
||||||
|
disabled={true}
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
onchange={() => {}}
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
@@ -1,103 +1,407 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import {
|
||||||
import { api } from '../../api';
|
ErrorBoundary,
|
||||||
import type { AgentGuardrail } from '../../types';
|
FormerResolveSpecAPI,
|
||||||
|
GridlerFull,
|
||||||
|
NativeSelectCtrl,
|
||||||
|
TextInputCtrl,
|
||||||
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem,
|
||||||
|
} from "@warkypublic/svelix";
|
||||||
|
import { adminGridTheme } from "../../gridTheme";
|
||||||
|
import { GlobalStateStore } from "../../shellState";
|
||||||
|
import type { AgentGuardrail } from "../../types";
|
||||||
|
import FormerShell from "../shared/FormerShell.svelte";
|
||||||
|
import ContentEditorField from "../shared/ContentEditorField.svelte";
|
||||||
|
|
||||||
const severityColour: Record<string, string> = {
|
type GuardrailForm = {
|
||||||
low: 'border-emerald-400/20 bg-emerald-400/10 text-emerald-200',
|
id?: string;
|
||||||
medium: 'border-amber-400/20 bg-amber-400/10 text-amber-200',
|
name: string;
|
||||||
high: 'border-orange-400/20 bg-orange-400/10 text-orange-200',
|
description: string;
|
||||||
critical: 'border-rose-400/20 bg-rose-400/10 text-rose-200'
|
content: string;
|
||||||
|
severity: string;
|
||||||
|
tags: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
let guardrails = $state<AgentGuardrail[]>([]);
|
const GUARDRAIL_PRIMARY_KEY = 'id';
|
||||||
let loading = $state(true);
|
|
||||||
let error = $state('');
|
|
||||||
let busy = $state<string | null>(null);
|
|
||||||
|
|
||||||
async function load() {
|
const severityClasses: Record<string, string> = {
|
||||||
loading = true;
|
low: 'bg-emerald-400/10 text-emerald-200',
|
||||||
error = '';
|
medium: 'bg-amber-400/10 text-amber-200',
|
||||||
try {
|
high: 'bg-orange-400/10 text-orange-200',
|
||||||
guardrails = await api.guardrails.list();
|
critical: 'bg-rose-400/10 text-rose-200'
|
||||||
} catch (e) {
|
};
|
||||||
error = e instanceof Error ? e.message : 'Failed to load guardrails';
|
|
||||||
} finally {
|
let selectedGuardrail = $state<AgentGuardrail | null>(null);
|
||||||
loading = false;
|
let gridTotal = $state<number | null>(null);
|
||||||
|
let formOpened = $state(false);
|
||||||
|
let formRequest = $state<'insert' | 'update' | 'delete'>('insert');
|
||||||
|
let formValues = $state<GuardrailForm>({
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
content: '',
|
||||||
|
severity: 'medium',
|
||||||
|
tags: ''
|
||||||
|
});
|
||||||
|
let editorOpened = $state(false);
|
||||||
|
let editorValues = $state<{ id?: string; content: string }>({ content: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const guardrailOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/agent_guardrails'
|
||||||
|
}));
|
||||||
|
|
||||||
|
const columns: GridlerColumn[] = [
|
||||||
|
{ id: 'name', title: 'Name', dataKey: 'name', width: 240 },
|
||||||
|
{ id: 'description', title: 'Description', dataKey: 'description', width: 320 },
|
||||||
|
{ id: 'severity', title: 'Severity', dataKey: 'severity', width: 120 },
|
||||||
|
{ id: 'tags', title: 'Tags', dataKey: 'tags', width: 220 },
|
||||||
|
{ id: 'created_at', title: 'Created', dataKey: 'created_at', width: 180, format: 'datetime' },
|
||||||
|
{ id: 'updated_at', title: 'Updated', dataKey: 'updated_at', width: 180, format: 'datetime' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
|
{ id: 'add', label: 'Add' },
|
||||||
|
{ id: 'edit', label: 'Edit' },
|
||||||
|
{ id: 'edit_content', label: 'Edit Content' },
|
||||||
|
{ id: 'delete', label: 'Delete' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const guardrailsDataSourceOptions = {
|
||||||
|
url: '/api/rs',
|
||||||
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
|
schema: 'public',
|
||||||
|
entity: 'agent_guardrails',
|
||||||
|
uniqueID: GUARDRAIL_PRIMARY_KEY,
|
||||||
|
hotfields: [GUARDRAIL_PRIMARY_KEY],
|
||||||
|
sort: [{ column: 'created_at', direction: 'desc' }]
|
||||||
|
} as unknown as {
|
||||||
|
url: string;
|
||||||
|
authToken?: string;
|
||||||
|
schema: string;
|
||||||
|
entity: string;
|
||||||
|
uniqueID: string;
|
||||||
|
hotfields: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeTags(value: unknown): string[] {
|
||||||
|
if (Array.isArray(value)) return value.map((tag) => String(tag).trim()).filter(Boolean);
|
||||||
|
if (typeof value !== 'string' || !value.trim()) return [];
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
|
||||||
|
return trimmed
|
||||||
|
.slice(1, -1)
|
||||||
|
.split(',')
|
||||||
|
.map((tag) => tag.trim().replace(/^"(.*)"$/, '$1'))
|
||||||
|
.filter(Boolean);
|
||||||
}
|
}
|
||||||
|
return trimmed.split(',').map((tag) => tag.trim()).filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remove(id: string, name: string) {
|
function normalizeGuardrail(rowData: Record<string, unknown>): AgentGuardrail {
|
||||||
if (!confirm(`Delete guardrail "${name}"?`)) return;
|
return {
|
||||||
busy = id;
|
id: String(rowData.id ?? ''),
|
||||||
try {
|
name: String(rowData.name ?? ''),
|
||||||
await api.guardrails.delete(id);
|
description: String(rowData.description ?? ''),
|
||||||
await load();
|
content: String(rowData.content ?? ''),
|
||||||
} catch (e) {
|
severity: (typeof rowData.severity === 'string' ? rowData.severity : 'medium') as AgentGuardrail['severity'],
|
||||||
error = e instanceof Error ? e.message : 'Delete failed';
|
tags: normalizeTags(rowData.tags),
|
||||||
} finally {
|
created_at: String(rowData.created_at ?? ''),
|
||||||
busy = null;
|
updated_at: String(rowData.updated_at ?? '')
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(load);
|
function toGuardrailForm(guardrail: AgentGuardrail): GuardrailForm {
|
||||||
|
return {
|
||||||
|
id: guardrail.id,
|
||||||
|
name: guardrail.name,
|
||||||
|
description: guardrail.description,
|
||||||
|
content: guardrail.content,
|
||||||
|
severity: guardrail.severity,
|
||||||
|
tags: guardrail.tags.join(', ')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeGuardrailRecordForFormer(data: Record<string, unknown>): GuardrailForm {
|
||||||
|
return {
|
||||||
|
id: data.id != null ? String(data.id) : undefined,
|
||||||
|
name: typeof data.name === 'string' ? data.name : '',
|
||||||
|
description: typeof data.description === 'string' ? data.description : '',
|
||||||
|
content: typeof data.content === 'string' ? data.content : '',
|
||||||
|
severity: typeof data.severity === 'string' ? data.severity : 'medium',
|
||||||
|
tags: normalizeTags(data.tags).join(', ')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadGuardrailFromRow(rowData: Record<string, unknown>): Promise<AgentGuardrail> {
|
||||||
|
const id = String(rowData[GUARDRAIL_PRIMARY_KEY] ?? '');
|
||||||
|
return await guardrailOnAPICall('read', 'update', undefined, id) as AgentGuardrail;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
selectedGuardrail = rowData ? normalizeGuardrail(rowData) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (item.id === 'add') {
|
||||||
|
formValues = { name: '', description: '', content: '', severity: 'medium', tags: '' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!contextRow) return;
|
||||||
|
if (item.id === 'edit_content') {
|
||||||
|
const guardrail = normalizeGuardrail(contextRow);
|
||||||
|
selectedGuardrail = guardrail;
|
||||||
|
editorValues = { id: guardrail.id, content: guardrail.content };
|
||||||
|
editorOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const guardrail = normalizeGuardrail(contextRow);
|
||||||
|
formValues = toGuardrailForm(guardrail);
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onGridEvent(
|
||||||
|
type: string,
|
||||||
|
_item?: unknown,
|
||||||
|
_column?: unknown,
|
||||||
|
_coords?: unknown,
|
||||||
|
detail?: Record<string, unknown>
|
||||||
|
) {
|
||||||
|
if (type !== 'page_loaded' && type !== 'load') return;
|
||||||
|
const total = detail?.total;
|
||||||
|
if (typeof total === 'number') gridTotal = total;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeGuardrailForm(data: GuardrailForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
name: data.name.trim(),
|
||||||
|
description: data.description.trim(),
|
||||||
|
content: data.content,
|
||||||
|
severity: data.severity,
|
||||||
|
tags: data.tags.split(',').map((tag) => tag.trim()).filter(Boolean)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGuardrailSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
if (contextRow?.id) {
|
||||||
|
selectedGuardrail = await loadGuardrailFromRow(contextRow);
|
||||||
|
}
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGuardrailEditorSaved() {
|
||||||
|
editorOpened = false;
|
||||||
|
if (editorValues.id) {
|
||||||
|
selectedGuardrail = await guardrailOnAPICall('read', 'update', undefined, editorValues.id) as AgentGuardrail;
|
||||||
|
editorValues = { id: selectedGuardrail.id, content: selectedGuardrail.content };
|
||||||
|
}
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(value?: string): string {
|
||||||
|
if (!value) return '—';
|
||||||
|
return new Date(value).toLocaleString();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="space-y-4">
|
<div class="space-y-4 w-full">
|
||||||
<div class="flex items-end justify-between">
|
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-2xl font-semibold text-white">Guardrails</h2>
|
<h2 class="text-2xl font-semibold text-white">Guardrails</h2>
|
||||||
<p class="mt-1 text-sm text-slate-400">{guardrails.length} guardrail{guardrails.length !== 1 ? 's' : ''}</p>
|
<p class="mt-1 text-sm text-slate-400">
|
||||||
|
{#if gridTotal === null}
|
||||||
|
Server-backed grid
|
||||||
|
{:else}
|
||||||
|
{gridTotal} guardrail{gridTotal !== 1 ? 's' : ''}
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
<button
|
<button
|
||||||
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
||||||
onclick={load}
|
onclick={() => {
|
||||||
>Refresh</button>
|
formValues = { name: '', description: '', content: '', severity: 'medium', tags: '' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
}}
|
||||||
|
>New Guardrail</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if error}
|
<div class="flex flex-col gap-4">
|
||||||
<div class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-4 text-sm text-rose-100">{error}</div>
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
{/if}
|
{#key refreshKey}
|
||||||
|
<ErrorBoundary namespace="GuardrailsGridlerFull">
|
||||||
|
<GridlerFull
|
||||||
|
{columns}
|
||||||
|
theme={adminGridTheme}
|
||||||
|
rowMarkers="number"
|
||||||
|
height={560}
|
||||||
|
width="100%"
|
||||||
|
pageSize={40}
|
||||||
|
dataSource="resolvespec"
|
||||||
|
dataSourceOptions={guardrailsDataSourceOptions}
|
||||||
|
serverSideSearch={true}
|
||||||
|
searchColumns={['name', 'description', 'content', 'severity', 'tags']}
|
||||||
|
{menuItems}
|
||||||
|
{onGridEvent}
|
||||||
|
{onRowClick}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
|
</div>
|
||||||
|
|
||||||
{#if loading}
|
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-400">Loading…</div>
|
<div class="flex items-center justify-between">
|
||||||
{:else if guardrails.length === 0}
|
<h3 class="text-sm font-semibold text-white">Guardrail Inspector</h3>
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-500">No guardrails registered.</div>
|
{#if selectedGuardrail}
|
||||||
|
<button
|
||||||
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
|
onclick={() => {
|
||||||
|
const guardrail = selectedGuardrail;
|
||||||
|
if (!guardrail) return;
|
||||||
|
editorValues = { id: guardrail.id, content: guardrail.content };
|
||||||
|
editorOpened = true;
|
||||||
|
}}
|
||||||
|
>Edit Content</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if !selectedGuardrail}
|
||||||
|
<p class="mt-3 text-sm text-slate-500">Select a guardrail row to inspect its rule content.</p>
|
||||||
{:else}
|
{:else}
|
||||||
<div class="space-y-3">
|
<div class="mt-3 space-y-3 text-sm text-slate-300">
|
||||||
{#each guardrails as g}
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
<div class="rounded-2xl border border-white/10 bg-white/5 p-5">
|
<p class="text-base font-semibold text-slate-100">{selectedGuardrail.name}</p>
|
||||||
<div class="flex items-start justify-between gap-4">
|
<span class={`inline-flex items-center rounded-lg px-2.5 py-0.5 text-xs font-medium ${severityClasses[selectedGuardrail.severity] ?? severityClasses.medium}`}>
|
||||||
<div class="min-w-0">
|
{selectedGuardrail.severity}
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<p class="font-semibold text-white">{g.name}</p>
|
|
||||||
<span class={`rounded-full border px-2 py-0.5 text-xs font-medium ${severityColour[g.severity] ?? severityColour.medium}`}>
|
|
||||||
{g.severity}
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{#if g.description}
|
|
||||||
<p class="mt-1 text-sm text-slate-400">{g.description}</p>
|
<div class="rounded-xl border border-white/10 bg-white/5 p-3 space-y-1">
|
||||||
{/if}
|
<p><strong class="text-slate-100">Description:</strong> {selectedGuardrail.description || '—'}</p>
|
||||||
{#if g.tags?.length}
|
<p><strong class="text-slate-100">Created:</strong> {formatDate(selectedGuardrail.created_at)}</p>
|
||||||
<div class="mt-2 flex flex-wrap gap-1">
|
<p><strong class="text-slate-100">Updated:</strong> {formatDate(selectedGuardrail.updated_at)}</p>
|
||||||
{#each g.tags as tag}
|
</div>
|
||||||
<span class="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-xs text-slate-400">{tag}</span>
|
|
||||||
|
<div class="rounded-xl border border-white/10 bg-white/5 p-3">
|
||||||
|
<p class="text-xs uppercase tracking-[0.18em] text-slate-500">Content</p>
|
||||||
|
<p class="mt-2 whitespace-pre-wrap text-slate-300">{selectedGuardrail.content}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-xl border border-white/10 bg-white/5 p-3">
|
||||||
|
<p class="text-xs uppercase tracking-[0.18em] text-slate-500">Tags</p>
|
||||||
|
<div class="mt-2 flex flex-wrap gap-1.5">
|
||||||
|
{#if selectedGuardrail.tags.length}
|
||||||
|
{#each selectedGuardrail.tags as tag}
|
||||||
|
<span class="rounded-md bg-white/10 px-2 py-0.5 text-xs text-slate-300">{tag}</span>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
{:else}
|
||||||
|
<span class="text-slate-500">No tags</span>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<button
|
|
||||||
class="shrink-0 text-xs text-rose-400 hover:text-rose-300 disabled:opacity-40"
|
|
||||||
onclick={() => remove(g.id, g.name)}
|
|
||||||
disabled={busy === g.id}
|
|
||||||
>Delete</button>
|
|
||||||
</div>
|
</div>
|
||||||
<details class="mt-3">
|
|
||||||
<summary class="cursor-pointer text-xs text-slate-500 hover:text-slate-300">View content</summary>
|
|
||||||
<pre class="mt-2 overflow-x-auto rounded-xl bg-slate-950/60 p-3 text-xs text-slate-300 whitespace-pre-wrap">{g.content}</pre>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="GuardrailsEditorFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={editorOpened}
|
||||||
|
bind:values={editorValues}
|
||||||
|
request="update"
|
||||||
|
title="Edit Guardrail Content"
|
||||||
|
uniqueKeyField={GUARDRAIL_PRIMARY_KEY}
|
||||||
|
width="min(96vw, 90rem)"
|
||||||
|
onAPICall={guardrailOnAPICall}
|
||||||
|
beforeSave={(data) => ({ content: data.content })}
|
||||||
|
afterSave={handleGuardrailEditorSaved}
|
||||||
|
onClose={() => { editorOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<ContentEditorField
|
||||||
|
filename="guardrail.md"
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, content: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="GuardrailsFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'insert' ? 'New Guardrail' : formRequest === 'update' ? 'Edit Guardrail' : 'Delete Guardrail'}
|
||||||
|
uniqueKeyField={GUARDRAIL_PRIMARY_KEY}
|
||||||
|
onAPICall={guardrailOnAPICall}
|
||||||
|
afterGet={async (data) => normalizeGuardrailRecordForFormer(data as Record<string, unknown>)}
|
||||||
|
beforeSave={normalizeGuardrailForm}
|
||||||
|
afterSave={handleGuardrailSaved}
|
||||||
|
onClose={() => { formOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<div class="space-y-4 p-4">
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Name"
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.name ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, name: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Description"
|
||||||
|
name="description"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.description ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, description: v })}
|
||||||
|
/>
|
||||||
|
<ContentEditorField
|
||||||
|
filename="guardrail.md"
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, content: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Severity"
|
||||||
|
name="severity"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.severity ?? 'medium'}
|
||||||
|
options={['low', 'medium', 'high', 'critical']}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, severity: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Tags"
|
||||||
|
name="tags"
|
||||||
|
placeholder="comma-separated"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.tags ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, tags: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
@@ -1,18 +1,163 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { GridlerFull, type GridlerColumn } from "@warkypublic/svelix";
|
import {
|
||||||
import { GlobalStateStore } from "../../shellState";
|
ErrorBoundary,
|
||||||
|
FormerResolveSpecAPI,
|
||||||
|
GridlerFull,
|
||||||
|
NativeSelectCtrl,
|
||||||
|
SwitchCtrl,
|
||||||
|
TextInputCtrl,
|
||||||
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem,
|
||||||
|
} from "@warkypublic/svelix";
|
||||||
|
import FormerShell from "../shared/FormerShell.svelte";
|
||||||
import { adminGridTheme } from "../../gridTheme";
|
import { adminGridTheme } from "../../gridTheme";
|
||||||
|
import { GlobalStateStore } from "../../shellState";
|
||||||
import type { Learning } from "../../types";
|
import type { Learning } from "../../types";
|
||||||
|
import ContentEditorField from "../shared/ContentEditorField.svelte";
|
||||||
|
|
||||||
|
type LearningForm = {
|
||||||
|
id?: string;
|
||||||
|
summary: string;
|
||||||
|
details: string;
|
||||||
|
category: string;
|
||||||
|
area: string;
|
||||||
|
status: string;
|
||||||
|
priority: string;
|
||||||
|
confidence: string;
|
||||||
|
action_required: boolean;
|
||||||
|
source_type?: string;
|
||||||
|
source_ref?: string;
|
||||||
|
tags?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LEARNING_PRIMARY_KEY = 'id';
|
||||||
|
|
||||||
let selectedLearning = $state<Learning | null>(null);
|
let selectedLearning = $state<Learning | null>(null);
|
||||||
let gridTotal = $state<number | null>(null);
|
let gridTotal = $state<number | null>(null);
|
||||||
|
let formOpened = $state(false);
|
||||||
|
let formRequest = $state<'insert' | 'update' | 'delete'>('insert');
|
||||||
|
let formValues = $state<LearningForm>({ summary: '', details: '', category: '', area: '', status: 'active', priority: 'medium', confidence: 'medium', action_required: false });
|
||||||
|
let editorOpened = $state(false);
|
||||||
|
let editorValues = $state<{ id?: string; details: string }>({ details: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const learningOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/learnings'
|
||||||
|
}));
|
||||||
|
|
||||||
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
|
{ id: 'add', label: 'Add' },
|
||||||
|
{ id: 'edit', label: 'Edit' },
|
||||||
|
{ id: 'edit_content', label: 'Edit Content' },
|
||||||
|
{ id: 'delete', label: 'Delete' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toLearningForm(learning: Learning): LearningForm {
|
||||||
|
return {
|
||||||
|
id: learning.id,
|
||||||
|
summary: learning.summary,
|
||||||
|
details: learning.details,
|
||||||
|
category: learning.category,
|
||||||
|
area: learning.area,
|
||||||
|
status: learning.status,
|
||||||
|
priority: learning.priority,
|
||||||
|
confidence: learning.confidence,
|
||||||
|
action_required: learning.action_required,
|
||||||
|
source_type: learning.source_type,
|
||||||
|
source_ref: learning.source_ref,
|
||||||
|
tags: learning.tags
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningRecordForFormer(data: Record<string, unknown>): LearningForm {
|
||||||
|
return {
|
||||||
|
id: data.id != null ? String(data.id) : undefined,
|
||||||
|
summary: typeof data.summary === 'string' ? data.summary : '',
|
||||||
|
details: typeof data.details === 'string' ? data.details : '',
|
||||||
|
category: typeof data.category === 'string' ? data.category : '',
|
||||||
|
area: typeof data.area === 'string' ? data.area : '',
|
||||||
|
status: typeof data.status === 'string' ? data.status : 'active',
|
||||||
|
priority: typeof data.priority === 'string' ? data.priority : 'medium',
|
||||||
|
confidence: typeof data.confidence === 'string' ? data.confidence : 'medium',
|
||||||
|
action_required: Boolean(data.action_required),
|
||||||
|
source_type: typeof data.source_type === 'string' && data.source_type ? data.source_type : undefined,
|
||||||
|
source_ref: typeof data.source_ref === 'string' && data.source_ref ? data.source_ref : undefined,
|
||||||
|
tags: typeof data.tags === 'string' ? data.tags : undefined
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadLearningFromRow(rowData: Record<string, unknown>): Promise<Learning> {
|
||||||
|
const id = String(rowData[LEARNING_PRIMARY_KEY] ?? '');
|
||||||
|
return await learningOnAPICall('read', 'update', undefined, id) as Learning;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (item.id === 'add') {
|
||||||
|
formValues = { summary: '', details: '', category: '', area: '', status: 'active', priority: 'medium', confidence: 'medium', action_required: false };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!contextRow) return;
|
||||||
|
if (item.id === 'edit_content') {
|
||||||
|
const learning = normalizeLearning(contextRow);
|
||||||
|
selectedLearning = learning;
|
||||||
|
editorValues = { id: learning.id, details: learning.details };
|
||||||
|
editorOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const learning = normalizeLearning(contextRow);
|
||||||
|
formValues = toLearningForm(learning);
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLearningForm(data: LearningForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
summary: data.summary.trim(),
|
||||||
|
details: data.details,
|
||||||
|
category: data.category.trim(),
|
||||||
|
area: data.area.trim(),
|
||||||
|
status: data.status,
|
||||||
|
priority: data.priority,
|
||||||
|
confidence: data.confidence,
|
||||||
|
action_required: data.action_required,
|
||||||
|
source_type: data.source_type?.trim() || undefined,
|
||||||
|
source_ref: data.source_ref?.trim() || undefined,
|
||||||
|
tags: data.tags?.trim() || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLearningSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
if (contextRow?.id) {
|
||||||
|
selectedLearning = await loadLearningFromRow(contextRow);
|
||||||
|
}
|
||||||
|
refreshKey++;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLearningEditorSaved() {
|
||||||
|
editorOpened = false;
|
||||||
|
if (editorValues.id) {
|
||||||
|
selectedLearning = await learningOnAPICall('read', 'update', undefined, editorValues.id) as Learning;
|
||||||
|
editorValues = { id: selectedLearning.id, details: selectedLearning.details };
|
||||||
|
}
|
||||||
|
refreshKey++;
|
||||||
|
}
|
||||||
|
|
||||||
const learningsDataSourceOptions = {
|
const learningsDataSourceOptions = {
|
||||||
url: "/api/rs",
|
url: "/api/rs",
|
||||||
authToken: GlobalStateStore.getState().session.authToken,
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
schema: "public",
|
schema: "public",
|
||||||
entity: "learnings",
|
entity: "learnings",
|
||||||
uniqueID: "id",
|
uniqueID: LEARNING_PRIMARY_KEY,
|
||||||
|
hotfields: [LEARNING_PRIMARY_KEY],
|
||||||
sort: [{ column: "created_at", direction: "desc" }],
|
sort: [{ column: "created_at", direction: "desc" }],
|
||||||
} as unknown as {
|
} as unknown as {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -20,6 +165,7 @@
|
|||||||
schema: string;
|
schema: string;
|
||||||
entity: string;
|
entity: string;
|
||||||
uniqueID: string;
|
uniqueID: string;
|
||||||
|
hotfields: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns: GridlerColumn[] = [
|
const columns: GridlerColumn[] = [
|
||||||
@@ -90,6 +236,12 @@
|
|||||||
selectedLearning = normalizeLearning(rowData);
|
selectedLearning = normalizeLearning(rowData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
function onGridEvent(
|
function onGridEvent(
|
||||||
type: string,
|
type: string,
|
||||||
_item?: unknown,
|
_item?: unknown,
|
||||||
@@ -120,10 +272,18 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
||||||
|
onclick={() => { formValues = { summary: '', details: '', category: '', area: '', status: 'active', priority: 'medium', confidence: 'medium', action_required: false }; formRequest = 'insert'; formOpened = true; }}>New Learning</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
|
{#key refreshKey}
|
||||||
|
<ErrorBoundary namespace="LearningsGridlerFull">
|
||||||
<GridlerFull
|
<GridlerFull
|
||||||
{columns}
|
{columns}
|
||||||
theme={adminGridTheme}
|
theme={adminGridTheme}
|
||||||
@@ -135,14 +295,30 @@
|
|||||||
dataSourceOptions={learningsDataSourceOptions}
|
dataSourceOptions={learningsDataSourceOptions}
|
||||||
serverSideSearch={true}
|
serverSideSearch={true}
|
||||||
searchColumns={["summary", "details", "category", "area", "status"]}
|
searchColumns={["summary", "details", "category", "area", "status"]}
|
||||||
|
{menuItems}
|
||||||
{onGridEvent}
|
{onGridEvent}
|
||||||
{onRowClick}
|
{onRowClick}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
/>
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
<div class="flex items-start justify-between gap-3">
|
<div class="flex items-start justify-between gap-3">
|
||||||
<h3 class="text-sm font-semibold text-white">Learning Inspector</h3>
|
<h3 class="text-sm font-semibold text-white">Learning Inspector</h3>
|
||||||
|
{#if selectedLearning}
|
||||||
|
<button
|
||||||
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
|
onclick={() => {
|
||||||
|
const learning = selectedLearning;
|
||||||
|
if (!learning) return;
|
||||||
|
editorValues = { id: learning.id, details: learning.details };
|
||||||
|
editorOpened = true;
|
||||||
|
}}>Edit Content</button>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if !selectedLearning}
|
{#if !selectedLearning}
|
||||||
@@ -217,3 +393,127 @@
|
|||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="LearningsEditorFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={editorOpened}
|
||||||
|
bind:values={editorValues}
|
||||||
|
request="update"
|
||||||
|
title="Edit Learning Details"
|
||||||
|
uniqueKeyField={LEARNING_PRIMARY_KEY}
|
||||||
|
width="min(96vw, 90rem)"
|
||||||
|
onAPICall={learningOnAPICall}
|
||||||
|
beforeSave={(data) => ({ details: data.details })}
|
||||||
|
afterSave={handleLearningEditorSaved}
|
||||||
|
onClose={() => { editorOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<ContentEditorField
|
||||||
|
filename="learning.md"
|
||||||
|
value={state.values?.details ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, details: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="LearningsFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'insert' ? 'New Learning' : formRequest === 'update' ? 'Edit Learning' : 'Delete Learning'}
|
||||||
|
uniqueKeyField={LEARNING_PRIMARY_KEY}
|
||||||
|
onAPICall={learningOnAPICall}
|
||||||
|
afterGet={async (data) => normalizeLearningRecordForFormer(data as Record<string, unknown>)}
|
||||||
|
beforeSave={normalizeLearningForm}
|
||||||
|
afterSave={handleLearningSaved}
|
||||||
|
onClose={() => { formOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<div class="space-y-4 p-4">
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Summary"
|
||||||
|
name="summary"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.summary ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, summary: v })}
|
||||||
|
/>
|
||||||
|
<ContentEditorField
|
||||||
|
filename="learning.md"
|
||||||
|
value={state.values?.details ?? ''}
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, details: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Category"
|
||||||
|
name="category"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.category ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, category: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Area"
|
||||||
|
name="area"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.area ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, area: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Status"
|
||||||
|
name="status"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.status ?? 'active'}
|
||||||
|
options={['active', 'completed', 'pending', 'archived']}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, status: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Priority"
|
||||||
|
name="priority"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.priority ?? 'medium'}
|
||||||
|
options={['low', 'medium', 'high', 'critical']}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, priority: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Confidence"
|
||||||
|
name="confidence"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.confidence ?? 'medium'}
|
||||||
|
options={['low', 'medium', 'high']}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, confidence: v })}
|
||||||
|
/>
|
||||||
|
<SwitchCtrl
|
||||||
|
label="Action Required"
|
||||||
|
name="action_required"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
checked={state.values?.action_required ?? false}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, action_required: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Source Type"
|
||||||
|
name="source_type"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.source_type ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, source_type: v || undefined })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Source Ref"
|
||||||
|
name="source_ref"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.source_ref ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, source_ref: v || undefined })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Tags"
|
||||||
|
name="tags"
|
||||||
|
placeholder="comma-separated"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.tags ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, tags: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
@@ -1,18 +1,148 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { GridlerFull, type GridlerColumn } from "@warkypublic/svelix";
|
import {
|
||||||
import { GlobalStateStore } from "../../shellState";
|
ErrorBoundary,
|
||||||
|
FormerResolveSpecAPI,
|
||||||
|
GridlerFull,
|
||||||
|
NativeSelectCtrl,
|
||||||
|
TextInputCtrl,
|
||||||
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem,
|
||||||
|
} from "@warkypublic/svelix";
|
||||||
|
import FormerShell from "../shared/FormerShell.svelte";
|
||||||
import { adminGridTheme } from "../../gridTheme";
|
import { adminGridTheme } from "../../gridTheme";
|
||||||
|
import { GlobalStateStore } from "../../shellState";
|
||||||
import type { Plan } from "../../types";
|
import type { Plan } from "../../types";
|
||||||
|
import ContentEditorField from "../shared/ContentEditorField.svelte";
|
||||||
|
|
||||||
|
type PlanForm = {
|
||||||
|
id?: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
status: string;
|
||||||
|
priority: string;
|
||||||
|
owner?: string;
|
||||||
|
due_date?: string;
|
||||||
|
tags?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const PLAN_PRIMARY_KEY = 'id';
|
||||||
|
|
||||||
let selectedPlan = $state<Plan | null>(null);
|
let selectedPlan = $state<Plan | null>(null);
|
||||||
let gridTotal = $state<number | null>(null);
|
let gridTotal = $state<number | null>(null);
|
||||||
|
let formOpened = $state(false);
|
||||||
|
let formRequest = $state<'insert' | 'update' | 'delete'>('insert');
|
||||||
|
let formValues = $state<PlanForm>({ title: '', description: '', status: 'draft', priority: 'medium' });
|
||||||
|
let editorOpened = $state(false);
|
||||||
|
let editorValues = $state<{ id?: string; description: string }>({ description: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const planOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/plans'
|
||||||
|
}));
|
||||||
|
|
||||||
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
|
{ id: 'add', label: 'Add' },
|
||||||
|
{ id: 'edit', label: 'Edit' },
|
||||||
|
{ id: 'edit_content', label: 'Edit Content' },
|
||||||
|
{ id: 'delete', label: 'Delete' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPlanFromRow(rowData: Record<string, unknown>): Promise<Plan> {
|
||||||
|
const data = await planOnAPICall('read', 'update', undefined, String(rowData[PLAN_PRIMARY_KEY] ?? '')) as Record<string, unknown>;
|
||||||
|
return normalizePlan(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toPlanForm(plan: Plan): PlanForm {
|
||||||
|
return {
|
||||||
|
id: plan.id,
|
||||||
|
title: plan.title,
|
||||||
|
description: plan.description,
|
||||||
|
status: plan.status,
|
||||||
|
priority: plan.priority,
|
||||||
|
owner: plan.owner,
|
||||||
|
due_date: plan.due_date ? String(plan.due_date).slice(0, 10) : undefined,
|
||||||
|
tags: plan.tags.join(', ')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePlanRecordForFormer(data: Record<string, unknown>): PlanForm {
|
||||||
|
return {
|
||||||
|
id: data.id != null ? String(data.id) : undefined,
|
||||||
|
title: typeof data.title === 'string' ? data.title : '',
|
||||||
|
description: typeof data.description === 'string' ? data.description : '',
|
||||||
|
status: typeof data.status === 'string' ? data.status : 'draft',
|
||||||
|
priority: typeof data.priority === 'string' ? data.priority : 'medium',
|
||||||
|
owner: typeof data.owner === 'string' && data.owner ? data.owner : undefined,
|
||||||
|
due_date: typeof data.due_date === 'string' && data.due_date ? data.due_date.slice(0, 10) : undefined,
|
||||||
|
tags: normalizeTags(data.tags).join(', ')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (item.id === 'add') {
|
||||||
|
formValues = { title: '', description: '', status: 'draft', priority: 'medium' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!contextRow) return;
|
||||||
|
if (item.id === 'edit_content') {
|
||||||
|
const plan = normalizePlan(contextRow);
|
||||||
|
selectedPlan = plan;
|
||||||
|
editorValues = { id: plan.id, description: plan.description };
|
||||||
|
editorOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const plan = normalizePlan(contextRow);
|
||||||
|
formValues = toPlanForm(plan);
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePlanForm(data: PlanForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
title: data.title.trim(),
|
||||||
|
description: data.description,
|
||||||
|
status: data.status,
|
||||||
|
priority: data.priority,
|
||||||
|
owner: data.owner?.trim() || undefined,
|
||||||
|
due_date: data.due_date || undefined,
|
||||||
|
tags: data.tags?.split(',').map((t) => t.trim()).filter(Boolean) ?? []
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handlePlanSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
if (contextRow?.id) {
|
||||||
|
const data = await planOnAPICall('read', 'update', undefined, String(contextRow.id)) as Record<string, unknown>;
|
||||||
|
selectedPlan = normalizePlan(data);
|
||||||
|
}
|
||||||
|
refreshKey++;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handlePlanEditorSaved() {
|
||||||
|
editorOpened = false;
|
||||||
|
if (editorValues.id) {
|
||||||
|
const data = await planOnAPICall('read', 'update', undefined, String(editorValues.id)) as Record<string, unknown>;
|
||||||
|
selectedPlan = normalizePlan(data);
|
||||||
|
editorValues = { id: selectedPlan.id, description: selectedPlan.description };
|
||||||
|
}
|
||||||
|
refreshKey++;
|
||||||
|
}
|
||||||
|
|
||||||
const plansDataSourceOptions = {
|
const plansDataSourceOptions = {
|
||||||
url: "/api/rs",
|
url: "/api/rs",
|
||||||
authToken: GlobalStateStore.getState().session.authToken,
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
schema: "public",
|
schema: "public",
|
||||||
entity: "plans",
|
entity: "plans",
|
||||||
uniqueID: "id",
|
uniqueID: PLAN_PRIMARY_KEY,
|
||||||
|
hotfields: [PLAN_PRIMARY_KEY],
|
||||||
sort: [{ column: "updated_at", direction: "desc" }],
|
sort: [{ column: "updated_at", direction: "desc" }],
|
||||||
} as unknown as {
|
} as unknown as {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -20,6 +150,7 @@
|
|||||||
schema: string;
|
schema: string;
|
||||||
entity: string;
|
entity: string;
|
||||||
uniqueID: string;
|
uniqueID: string;
|
||||||
|
hotfields: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns: GridlerColumn[] = [
|
const columns: GridlerColumn[] = [
|
||||||
@@ -66,6 +197,12 @@
|
|||||||
selectedPlan = rowData ? normalizePlan(rowData) : null;
|
selectedPlan = rowData ? normalizePlan(rowData) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
function onGridEvent(
|
function onGridEvent(
|
||||||
type: string,
|
type: string,
|
||||||
_item?: unknown,
|
_item?: unknown,
|
||||||
@@ -112,10 +249,18 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
||||||
|
onclick={() => { formValues = { title: '', description: '', status: 'draft', priority: 'medium' }; formRequest = 'insert'; formOpened = true; }}>New Plan</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
|
{#key refreshKey}
|
||||||
|
<ErrorBoundary namespace="PlansGridlerFull">
|
||||||
<GridlerFull
|
<GridlerFull
|
||||||
{columns}
|
{columns}
|
||||||
theme={adminGridTheme}
|
theme={adminGridTheme}
|
||||||
@@ -127,13 +272,31 @@
|
|||||||
dataSourceOptions={plansDataSourceOptions}
|
dataSourceOptions={plansDataSourceOptions}
|
||||||
serverSideSearch={true}
|
serverSideSearch={true}
|
||||||
searchColumns={["title", "description", "status", "priority", "owner"]}
|
searchColumns={["title", "description", "status", "priority", "owner"]}
|
||||||
|
{menuItems}
|
||||||
{onGridEvent}
|
{onGridEvent}
|
||||||
{onRowClick}
|
{onRowClick}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
/>
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
<h3 class="text-sm font-semibold text-white">Plan Inspector</h3>
|
<h3 class="text-sm font-semibold text-white">Plan Inspector</h3>
|
||||||
|
{#if selectedPlan}
|
||||||
|
<button
|
||||||
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
|
onclick={() => {
|
||||||
|
const plan = selectedPlan;
|
||||||
|
if (!plan) return;
|
||||||
|
editorValues = { id: plan.id, description: plan.description };
|
||||||
|
editorOpened = true;
|
||||||
|
}}>Edit Content</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
{#if !selectedPlan}
|
{#if !selectedPlan}
|
||||||
<p class="mt-3 text-sm text-slate-500">
|
<p class="mt-3 text-sm text-slate-500">
|
||||||
@@ -195,3 +358,99 @@
|
|||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="PlansEditorFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={editorOpened}
|
||||||
|
bind:values={editorValues}
|
||||||
|
request="update"
|
||||||
|
title="Edit Plan Description"
|
||||||
|
uniqueKeyField={PLAN_PRIMARY_KEY}
|
||||||
|
width="min(96vw, 90rem)"
|
||||||
|
onAPICall={planOnAPICall}
|
||||||
|
beforeSave={(data) => ({ description: data.description })}
|
||||||
|
afterSave={handlePlanEditorSaved}
|
||||||
|
onClose={() => { editorOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<ContentEditorField
|
||||||
|
filename="plan.md"
|
||||||
|
value={state.values?.description ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, description: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="PlansFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'insert' ? 'New Plan' : formRequest === 'update' ? 'Edit Plan' : 'Delete Plan'}
|
||||||
|
uniqueKeyField={PLAN_PRIMARY_KEY}
|
||||||
|
onAPICall={planOnAPICall}
|
||||||
|
afterGet={async (data) => normalizePlanRecordForFormer(data as Record<string, unknown>)}
|
||||||
|
beforeSave={normalizePlanForm}
|
||||||
|
afterSave={handlePlanSaved}
|
||||||
|
onClose={() => { formOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<div class="space-y-4 p-4">
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Title"
|
||||||
|
name="title"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.title ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, title: v })}
|
||||||
|
/>
|
||||||
|
<ContentEditorField
|
||||||
|
filename="plan.md"
|
||||||
|
value={state.values?.description ?? ''}
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, description: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Status"
|
||||||
|
name="status"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.status ?? 'draft'}
|
||||||
|
options={['draft', 'active', 'blocked', 'completed', 'cancelled', 'superseded']}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, status: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Priority"
|
||||||
|
name="priority"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.priority ?? 'medium'}
|
||||||
|
options={['low', 'medium', 'high', 'critical']}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, priority: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Owner"
|
||||||
|
name="owner"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.owner ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, owner: v || undefined })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Due Date"
|
||||||
|
name="due_date"
|
||||||
|
type="date"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.due_date ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, due_date: v || undefined })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Tags"
|
||||||
|
name="tags"
|
||||||
|
placeholder="comma-separated"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.tags ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, tags: v })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
@@ -1,27 +1,56 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import {
|
||||||
import { GridlerFull, TextInputCtrl, type GridlerColumn } from '@warkypublic/svelix';
|
ErrorBoundary,
|
||||||
import { api } from '../../api';
|
FormerResolveSpecAPI,
|
||||||
|
GridlerFull,
|
||||||
|
TextInputCtrl,
|
||||||
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem
|
||||||
|
} from '@warkypublic/svelix';
|
||||||
import { GlobalStateStore } from '../../shellState';
|
import { GlobalStateStore } from '../../shellState';
|
||||||
import { adminGridTheme } from '../../gridTheme';
|
import { adminGridTheme } from '../../gridTheme';
|
||||||
import type { ProjectSummary } from '../../types';
|
import type { ProjectSummary } from '../../types';
|
||||||
|
import FormerShell from '../shared/FormerShell.svelte';
|
||||||
|
import ContentEditorField from '../shared/ContentEditorField.svelte';
|
||||||
|
|
||||||
|
type ProjectForm = {
|
||||||
|
id?: string;
|
||||||
|
guid?: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const PROJECT_PRIMARY_KEY = 'id';
|
||||||
|
|
||||||
let projects = $state<ProjectSummary[]>([]);
|
|
||||||
let loading = $state(true);
|
|
||||||
let error = $state('');
|
|
||||||
let creating = $state(false);
|
|
||||||
let showCreate = $state(false);
|
|
||||||
let newName = $state('');
|
|
||||||
let newDesc = $state('');
|
|
||||||
let createError = $state('');
|
|
||||||
let selectedProject = $state<ProjectSummary | null>(null);
|
let selectedProject = $state<ProjectSummary | null>(null);
|
||||||
|
let selectedProjectRecordID = $state<string | null>(null);
|
||||||
|
let gridTotal = $state<number | null>(null);
|
||||||
|
let formOpened = $state(false);
|
||||||
|
let formRequest = $state<'insert' | 'update' | 'delete'>('insert');
|
||||||
|
let formValues = $state<ProjectForm>({ name: '', description: '' });
|
||||||
|
let editorOpened = $state(false);
|
||||||
|
let editorValues = $state<{ id?: string; description: string }>({ description: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const projectOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/projects'
|
||||||
|
}));
|
||||||
|
|
||||||
const projectDataSourceOptions = {
|
const projectDataSourceOptions = {
|
||||||
url: '/api/rs',
|
url: '/api/rs',
|
||||||
authToken: GlobalStateStore.getState().session.authToken,
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
schema: 'public',
|
schema: 'public',
|
||||||
entity: 'projects',
|
entity: 'projects',
|
||||||
uniqueID: 'id',
|
uniqueID: PROJECT_PRIMARY_KEY,
|
||||||
hotfields: ['id', 'guid'],
|
hotfields: [PROJECT_PRIMARY_KEY, 'guid'],
|
||||||
|
computedColumns: [
|
||||||
|
{
|
||||||
|
name: 'thought_count',
|
||||||
|
expression: 'COALESCE((SELECT COUNT(*) FROM public.thoughts t WHERE t.project_id = projects.guid), 0)'
|
||||||
|
}
|
||||||
|
],
|
||||||
sort: [{ column: 'created_at', direction: 'desc' }]
|
sort: [{ column: 'created_at', direction: 'desc' }]
|
||||||
} as unknown as {
|
} as unknown as {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -30,6 +59,7 @@
|
|||||||
entity: string;
|
entity: string;
|
||||||
uniqueID: string;
|
uniqueID: string;
|
||||||
hotfields: string[];
|
hotfields: string[];
|
||||||
|
computedColumns: { name: string; expression: string }[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const columns: GridlerColumn[] = [
|
const columns: GridlerColumn[] = [
|
||||||
@@ -39,44 +69,30 @@
|
|||||||
{ id: 'created_at', title: 'Created', dataKey: 'created_at', width: 200, format: 'datetime' }
|
{ id: 'created_at', title: 'Created', dataKey: 'created_at', width: 200, format: 'datetime' }
|
||||||
];
|
];
|
||||||
|
|
||||||
async function load() {
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
loading = true;
|
{ id: 'add', label: 'Add' },
|
||||||
error = '';
|
{ id: 'edit', label: 'Edit' },
|
||||||
try {
|
{ id: 'edit_content', label: 'Edit Content' },
|
||||||
projects = await api.projects.list();
|
{ id: 'delete', label: 'Delete' }
|
||||||
if (selectedProject) {
|
];
|
||||||
selectedProject = projects.find((project) => project.id === selectedProject?.id) ?? null;
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
error = e instanceof Error ? e.message : 'Failed to load projects';
|
|
||||||
} finally {
|
|
||||||
loading = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function create() {
|
function toProjectForm(rowData: Record<string, unknown>): ProjectForm {
|
||||||
if (!newName.trim()) return;
|
return {
|
||||||
creating = true;
|
id: String(rowData.id ?? ''),
|
||||||
createError = '';
|
guid: String(rowData.guid ?? ''),
|
||||||
try {
|
name: String(rowData.name ?? ''),
|
||||||
await api.projects.create(newName.trim(), newDesc.trim());
|
description: String(rowData.description ?? '')
|
||||||
newName = '';
|
};
|
||||||
newDesc = '';
|
|
||||||
showCreate = false;
|
|
||||||
await load();
|
|
||||||
} catch (e) {
|
|
||||||
createError = e instanceof Error ? e.message : 'Failed to create project';
|
|
||||||
} finally {
|
|
||||||
creating = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onProjectRowClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
function onProjectRowClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
if (!rowData) {
|
if (!rowData) {
|
||||||
selectedProject = null;
|
selectedProject = null;
|
||||||
|
selectedProjectRecordID = null;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const id = String(rowData.guid ?? rowData.id ?? '');
|
selectedProjectRecordID = String(rowData[PROJECT_PRIMARY_KEY] ?? '');
|
||||||
|
const id = String(rowData.guid ?? rowData[PROJECT_PRIMARY_KEY] ?? '');
|
||||||
selectedProject = {
|
selectedProject = {
|
||||||
id,
|
id,
|
||||||
name: String(rowData.name ?? ''),
|
name: String(rowData.name ?? ''),
|
||||||
@@ -87,70 +103,86 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(load);
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (item.id === 'add') {
|
||||||
|
formValues = { name: '', description: '' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!contextRow) return;
|
||||||
|
if (item.id === 'edit_content') {
|
||||||
|
onProjectRowClick(0, contextRow);
|
||||||
|
editorValues = {
|
||||||
|
id: String(contextRow[PROJECT_PRIMARY_KEY] ?? ''),
|
||||||
|
description: String(contextRow.description ?? '')
|
||||||
|
};
|
||||||
|
editorOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
formValues = toProjectForm(contextRow);
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeProjectForm(data: ProjectForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
name: data.name.trim(),
|
||||||
|
description: data.description.trim()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleProjectSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleEditorSaved() {
|
||||||
|
editorOpened = false;
|
||||||
|
if (selectedProjectRecordID && editorValues.id === selectedProjectRecordID && selectedProject) {
|
||||||
|
selectedProject.description = editorValues.description;
|
||||||
|
}
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
<div class="flex items-end justify-between">
|
<div class="flex items-end justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-2xl font-semibold text-white">Projects</h2>
|
<h2 class="text-2xl font-semibold text-white">Projects</h2>
|
||||||
<p class="mt-1 text-sm text-slate-400">{projects.length} project{projects.length !== 1 ? 's' : ''}</p>
|
<p class="mt-1 text-sm text-slate-400">
|
||||||
|
{#if gridTotal === null}
|
||||||
|
Server-backed grid
|
||||||
|
{:else}
|
||||||
|
{gridTotal} project{gridTotal !== 1 ? 's' : ''}
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex gap-2">
|
<div class="flex gap-2">
|
||||||
<button
|
|
||||||
class="inline-flex items-center rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm font-medium text-slate-200 transition hover:bg-white/10"
|
|
||||||
onclick={load}
|
|
||||||
>Refresh</button>
|
|
||||||
<button
|
<button
|
||||||
class="inline-flex items-center rounded-xl border border-cyan-300/30 bg-cyan-400/10 px-4 py-2 text-sm font-medium text-cyan-100 transition hover:bg-cyan-400/20"
|
class="inline-flex items-center rounded-xl border border-cyan-300/30 bg-cyan-400/10 px-4 py-2 text-sm font-medium text-cyan-100 transition hover:bg-cyan-400/20"
|
||||||
onclick={() => { showCreate = !showCreate; }}
|
onclick={() => {
|
||||||
|
formValues = { name: '', description: '' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
}}
|
||||||
>New project</button>
|
>New project</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if showCreate}
|
|
||||||
<div class="rounded-2xl border border-cyan-400/20 bg-slate-900 p-5">
|
|
||||||
<h3 class="text-sm font-semibold text-white">Create project</h3>
|
|
||||||
<div class="mt-3 space-y-3">
|
|
||||||
<TextInputCtrl
|
|
||||||
label="Project name"
|
|
||||||
placeholder="Name"
|
|
||||||
required
|
|
||||||
bind:value={newName}
|
|
||||||
/>
|
|
||||||
<TextInputCtrl
|
|
||||||
label="Description"
|
|
||||||
placeholder="Description (optional)"
|
|
||||||
bind:value={newDesc}
|
|
||||||
/>
|
|
||||||
{#if createError}<p class="text-xs text-rose-300">{createError}</p>{/if}
|
|
||||||
<div class="flex gap-2">
|
|
||||||
<button
|
|
||||||
class="rounded-xl border border-cyan-300/30 bg-cyan-400/10 px-4 py-2 text-sm font-medium text-cyan-100 transition hover:bg-cyan-400/20 disabled:opacity-50"
|
|
||||||
onclick={create}
|
|
||||||
disabled={creating || !newName.trim()}
|
|
||||||
>{creating ? 'Creating…' : 'Create'}</button>
|
|
||||||
<button
|
|
||||||
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300 transition hover:bg-white/10"
|
|
||||||
onclick={() => { showCreate = false; createError = ''; }}
|
|
||||||
>Cancel</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if loading}
|
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-400">
|
|
||||||
Loading…
|
|
||||||
</div>
|
|
||||||
{:else if error}
|
|
||||||
<div class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-4 text-sm text-rose-100">{error}</div>
|
|
||||||
{:else if projects.length === 0}
|
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-500">
|
|
||||||
No projects yet.
|
|
||||||
</div>
|
|
||||||
{:else}
|
|
||||||
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
|
{#key refreshKey}
|
||||||
|
<ErrorBoundary namespace="ProjectsGridlerFull">
|
||||||
<GridlerFull
|
<GridlerFull
|
||||||
{columns}
|
{columns}
|
||||||
theme={adminGridTheme}
|
theme={adminGridTheme}
|
||||||
@@ -160,15 +192,97 @@
|
|||||||
dataSourceOptions={projectDataSourceOptions}
|
dataSourceOptions={projectDataSourceOptions}
|
||||||
serverSideSearch={true}
|
serverSideSearch={true}
|
||||||
searchColumns={['name', 'description']}
|
searchColumns={['name', 'description']}
|
||||||
|
{menuItems}
|
||||||
onRowClick={onProjectRowClick}
|
onRowClick={onProjectRowClick}
|
||||||
|
onGridEvent={(type, _item, _column, _coords, detail) => {
|
||||||
|
if (type !== 'page_loaded' && type !== 'load') return;
|
||||||
|
const total = detail?.total;
|
||||||
|
if (typeof total === 'number') gridTotal = total;
|
||||||
|
}}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
/>
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
{#if selectedProject}
|
{#if selectedProject}
|
||||||
<div class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
<div class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
<h3 class="text-sm font-semibold text-white">Selected project</h3>
|
<h3 class="text-sm font-semibold text-white">Selected project</h3>
|
||||||
|
<button
|
||||||
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
|
onclick={() => {
|
||||||
|
const project = selectedProject;
|
||||||
|
if (!project) return;
|
||||||
|
editorValues = {
|
||||||
|
id: selectedProjectRecordID ?? undefined,
|
||||||
|
description: project.description
|
||||||
|
};
|
||||||
|
editorOpened = true;
|
||||||
|
}}
|
||||||
|
>Edit Content</button>
|
||||||
|
</div>
|
||||||
<p class="mt-2 text-sm text-slate-300"><strong class="text-slate-100">{selectedProject.name}</strong> · {selectedProject.thought_count} thoughts</p>
|
<p class="mt-2 text-sm text-slate-300"><strong class="text-slate-100">{selectedProject.name}</strong> · {selectedProject.thought_count} thoughts</p>
|
||||||
<p class="mt-1 text-sm text-slate-400">{selectedProject.description || 'No description.'}</p>
|
<p class="mt-1 text-sm text-slate-400">{selectedProject.description || 'No description.'}</p>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="ProjectsEditorFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={editorOpened}
|
||||||
|
bind:values={editorValues}
|
||||||
|
request="update"
|
||||||
|
title="Edit Project Description"
|
||||||
|
uniqueKeyField={PROJECT_PRIMARY_KEY}
|
||||||
|
width="min(96vw, 90rem)"
|
||||||
|
onAPICall={projectOnAPICall}
|
||||||
|
beforeSave={(data) => ({ description: data.description.trim() })}
|
||||||
|
afterSave={handleEditorSaved}
|
||||||
|
onClose={() => {
|
||||||
|
editorOpened = false;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<ContentEditorField
|
||||||
|
filename="project.md"
|
||||||
|
value={state.values?.description ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, description: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="ProjectsFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'insert' ? 'New Project' : formRequest === 'update' ? 'Edit Project' : 'Delete Project'}
|
||||||
|
uniqueKeyField={PROJECT_PRIMARY_KEY}
|
||||||
|
onAPICall={projectOnAPICall}
|
||||||
|
beforeSave={normalizeProjectForm}
|
||||||
|
afterSave={handleProjectSaved}
|
||||||
|
onClose={() => {
|
||||||
|
formOpened = false;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Project name"
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.name ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, name: v })}
|
||||||
|
/>
|
||||||
|
<ContentEditorField
|
||||||
|
filename="project.md"
|
||||||
|
value={state.values?.description ?? ''}
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, description: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
44
ui/src/components/shared/ContentEditorField.svelte
Normal file
44
ui/src/components/shared/ContentEditorField.svelte
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { ContentEditor } from '@warkypublic/svelix';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
value: string;
|
||||||
|
filename: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
onchange: (text: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { value, filename, disabled = false, onchange }: Props = $props();
|
||||||
|
|
||||||
|
let currentBlob = $state<Blob | undefined>(undefined);
|
||||||
|
|
||||||
|
const initialBlob = $derived(new Blob([value ?? ''], { type: 'text/plain' }));
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
currentBlob = undefined;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function handleBlobChange(blob?: Blob) {
|
||||||
|
currentBlob = blob;
|
||||||
|
if (!blob) {
|
||||||
|
onchange('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onchange(await blob.text());
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="rounded-xl border border-white/10 bg-slate-950/60 overflow-hidden">
|
||||||
|
<div class="border-b border-white/10 px-4 py-2 text-xs uppercase tracking-[0.18em] text-slate-500">
|
||||||
|
{filename}
|
||||||
|
</div>
|
||||||
|
<div class:opacity-60={disabled} class:pointer-events-none={disabled}>
|
||||||
|
<ContentEditor
|
||||||
|
value={currentBlob ?? initialBlob}
|
||||||
|
{filename}
|
||||||
|
colorScheme="dark"
|
||||||
|
hideHeader={true}
|
||||||
|
onChange={(blob) => { void handleBlobChange(blob); }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
94
ui/src/components/shared/ContentEditorModal.svelte
Normal file
94
ui/src/components/shared/ContentEditorModal.svelte
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { ContentEditor } from '@warkypublic/svelix';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
filename: string;
|
||||||
|
onSave: (text: string) => Promise<void>;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { open, title, content, filename, onSave, onClose }: Props = $props();
|
||||||
|
|
||||||
|
let saveError = $state('');
|
||||||
|
let saving = $state(false);
|
||||||
|
let fullscreen = $state(false);
|
||||||
|
let currentBlob = $state<Blob | undefined>(undefined);
|
||||||
|
|
||||||
|
const initialBlob = $derived(open ? new Blob([content], { type: 'text/plain' }) : undefined);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (open) currentBlob = undefined;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const blob = currentBlob ?? initialBlob;
|
||||||
|
if (!blob) return;
|
||||||
|
saveError = '';
|
||||||
|
saving = true;
|
||||||
|
try {
|
||||||
|
const text = await blob.text();
|
||||||
|
await onSave(text);
|
||||||
|
onClose();
|
||||||
|
} catch (e) {
|
||||||
|
saveError = e instanceof Error ? e.message : 'Save failed';
|
||||||
|
} finally {
|
||||||
|
saving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKeydown(e: KeyboardEvent) {
|
||||||
|
if (e.key === 'Escape') { if (fullscreen) { fullscreen = false; } else { onClose(); } }
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||||
|
e.preventDefault();
|
||||||
|
void save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:window onkeydown={onKeydown} />
|
||||||
|
|
||||||
|
{#if open}
|
||||||
|
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-8" class:p-0={fullscreen}>
|
||||||
|
<div
|
||||||
|
class="flex flex-col w-full max-w-5xl bg-slate-900 transition-all"
|
||||||
|
class:max-w-5xl={!fullscreen}
|
||||||
|
style={fullscreen ? 'height: 100vh; border-radius: 0; border: none;' : 'height: 85vh; border-radius: 1rem; overflow: hidden; border: 1px solid rgba(255,255,255,0.1);'}
|
||||||
|
>
|
||||||
|
<div class="flex-none flex items-center justify-between px-5 py-3 border-b border-white/10 bg-slate-800">
|
||||||
|
<h2 class="text-sm font-semibold text-white">{title}</h2>
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
{#if saveError}
|
||||||
|
<p class="text-xs text-rose-300">{saveError}</p>
|
||||||
|
{/if}
|
||||||
|
<button
|
||||||
|
onclick={() => { fullscreen = !fullscreen; }}
|
||||||
|
class="text-xs text-slate-400 hover:text-white"
|
||||||
|
title={fullscreen ? 'Exit fullscreen' : 'Fullscreen'}
|
||||||
|
>{fullscreen ? '⊡' : '⛶'}</button>
|
||||||
|
<button
|
||||||
|
onclick={onClose}
|
||||||
|
class="text-xs text-slate-400 hover:text-white"
|
||||||
|
>Cancel</button>
|
||||||
|
<button
|
||||||
|
onclick={save}
|
||||||
|
disabled={saving}
|
||||||
|
class="rounded-lg bg-cyan-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-cyan-500 disabled:opacity-50"
|
||||||
|
>{saving ? 'Saving…' : 'Save'}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 overflow-hidden bg-slate-900">
|
||||||
|
<ContentEditor
|
||||||
|
value={initialBlob}
|
||||||
|
{filename}
|
||||||
|
colorScheme="dark"
|
||||||
|
hideHeader={true}
|
||||||
|
onChange={(v) => { currentBlob = v; }}
|
||||||
|
onSave={save}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
38
ui/src/components/shared/FormerShell.svelte
Normal file
38
ui/src/components/shared/FormerShell.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { FormerDrawer } from '@warkypublic/svelix';
|
||||||
|
import type { FormerProps, FormRequestType } from '@warkypublic/svelix';
|
||||||
|
import type { Snippet } from 'svelte';
|
||||||
|
|
||||||
|
interface Props extends FormerProps<any> {
|
||||||
|
title?: string;
|
||||||
|
width?: string;
|
||||||
|
children?: Snippet<[any]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
title = 'Form',
|
||||||
|
opened = $bindable(false),
|
||||||
|
values = $bindable<any>(undefined),
|
||||||
|
request = $bindable<FormRequestType>('insert'),
|
||||||
|
layout = { buttonArea: 'bottom' },
|
||||||
|
width = '36rem',
|
||||||
|
children: formContent,
|
||||||
|
...rest
|
||||||
|
}: Props = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<FormerDrawer
|
||||||
|
bind:opened
|
||||||
|
bind:values
|
||||||
|
bind:request
|
||||||
|
{title}
|
||||||
|
{layout}
|
||||||
|
{width}
|
||||||
|
{...rest}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<div class="space-y-4 p-6">
|
||||||
|
{@render formContent?.(state)}
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</FormerDrawer>
|
||||||
@@ -1,91 +1,382 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import {
|
||||||
import { api } from '../../api';
|
ErrorBoundary,
|
||||||
|
FormerResolveSpecAPI,
|
||||||
|
GridlerFull,
|
||||||
|
TextInputCtrl,
|
||||||
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem
|
||||||
|
} from '@warkypublic/svelix';
|
||||||
|
import { adminGridTheme } from '../../gridTheme';
|
||||||
|
import { GlobalStateStore } from '../../shellState';
|
||||||
import type { AgentSkill } from '../../types';
|
import type { AgentSkill } from '../../types';
|
||||||
|
import FormerShell from '../shared/FormerShell.svelte';
|
||||||
|
import ContentEditorField from '../shared/ContentEditorField.svelte';
|
||||||
|
|
||||||
let skills = $state<AgentSkill[]>([]);
|
type SkillForm = {
|
||||||
let loading = $state(true);
|
id?: string;
|
||||||
let error = $state('');
|
name: string;
|
||||||
let busy = $state<string | null>(null);
|
description: string;
|
||||||
|
content: string;
|
||||||
|
tags: string;
|
||||||
|
};
|
||||||
|
|
||||||
async function load() {
|
const SKILL_PRIMARY_KEY = 'id';
|
||||||
loading = true;
|
|
||||||
error = '';
|
let selectedSkill = $state<AgentSkill | null>(null);
|
||||||
try {
|
let gridTotal = $state<number | null>(null);
|
||||||
skills = await api.skills.list();
|
let formOpened = $state(false);
|
||||||
} catch (e) {
|
let formRequest = $state<'insert' | 'update' | 'delete'>('insert');
|
||||||
error = e instanceof Error ? e.message : 'Failed to load skills';
|
let formValues = $state<SkillForm>({
|
||||||
} finally {
|
name: '',
|
||||||
loading = false;
|
description: '',
|
||||||
|
content: '',
|
||||||
|
tags: ''
|
||||||
|
});
|
||||||
|
let editorOpened = $state(false);
|
||||||
|
let editorValues = $state<{ id?: string; content: string }>({ content: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const skillOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/agent_skills'
|
||||||
|
}));
|
||||||
|
|
||||||
|
const skillsDataSourceOptions = {
|
||||||
|
url: '/api/rs',
|
||||||
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
|
schema: 'public',
|
||||||
|
entity: 'agent_skills',
|
||||||
|
uniqueID: SKILL_PRIMARY_KEY,
|
||||||
|
hotfields: [SKILL_PRIMARY_KEY],
|
||||||
|
sort: [{ column: 'created_at', direction: 'desc' }]
|
||||||
|
} as unknown as {
|
||||||
|
url: string;
|
||||||
|
authToken?: string;
|
||||||
|
schema: string;
|
||||||
|
entity: string;
|
||||||
|
uniqueID: string;
|
||||||
|
hotfields: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const columns: GridlerColumn[] = [
|
||||||
|
{ id: 'name', title: 'Name', dataKey: 'name', width: 240 },
|
||||||
|
{ id: 'description', title: 'Description', dataKey: 'description', width: 300 },
|
||||||
|
{ id: 'tags', title: 'Tags', dataKey: 'tags', width: 220 },
|
||||||
|
{ id: 'created_at', title: 'Created', dataKey: 'created_at', width: 180, format: 'datetime' },
|
||||||
|
{ id: 'updated_at', title: 'Updated', dataKey: 'updated_at', width: 180, format: 'datetime' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
|
{ id: 'add', label: 'Add' },
|
||||||
|
{ id: 'edit', label: 'Edit' },
|
||||||
|
{ id: 'edit_content', label: 'Edit Content' },
|
||||||
|
{ id: 'delete', label: 'Delete' }
|
||||||
|
];
|
||||||
|
|
||||||
|
function normalizeTags(value: unknown): string[] {
|
||||||
|
if (Array.isArray(value)) return value.map((tag) => String(tag).trim()).filter(Boolean);
|
||||||
|
if (typeof value !== 'string' || !value.trim()) return [];
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
|
||||||
|
return trimmed
|
||||||
|
.slice(1, -1)
|
||||||
|
.split(',')
|
||||||
|
.map((tag) => tag.trim().replace(/^"(.*)"$/, '$1'))
|
||||||
|
.filter(Boolean);
|
||||||
}
|
}
|
||||||
|
return trimmed.split(',').map((tag) => tag.trim()).filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remove(id: string, name: string) {
|
function normalizeSkill(rowData: Record<string, unknown>): AgentSkill {
|
||||||
if (!confirm(`Delete skill "${name}"?`)) return;
|
return {
|
||||||
busy = id;
|
id: String(rowData.id ?? ''),
|
||||||
try {
|
name: String(rowData.name ?? ''),
|
||||||
await api.skills.delete(id);
|
description: String(rowData.description ?? ''),
|
||||||
await load();
|
content: String(rowData.content ?? ''),
|
||||||
} catch (e) {
|
tags: normalizeTags(rowData.tags),
|
||||||
error = e instanceof Error ? e.message : 'Delete failed';
|
created_at: String(rowData.created_at ?? ''),
|
||||||
} finally {
|
updated_at: String(rowData.updated_at ?? '')
|
||||||
busy = null;
|
};
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(load);
|
function toSkillForm(skill: AgentSkill): SkillForm {
|
||||||
|
return {
|
||||||
|
id: skill.id,
|
||||||
|
name: skill.name,
|
||||||
|
description: skill.description,
|
||||||
|
content: skill.content,
|
||||||
|
tags: skill.tags.join(', ')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSkillRecordForFormer(data: Record<string, unknown>): SkillForm {
|
||||||
|
return {
|
||||||
|
id: data.id != null ? String(data.id) : undefined,
|
||||||
|
name: typeof data.name === 'string' ? data.name : '',
|
||||||
|
description: typeof data.description === 'string' ? data.description : '',
|
||||||
|
content: typeof data.content === 'string' ? data.content : '',
|
||||||
|
tags: normalizeTags(data.tags).join(', ')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
selectedSkill = rowData ? normalizeSkill(rowData) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSkillFromRow(rowData: Record<string, unknown>): Promise<AgentSkill> {
|
||||||
|
const id = String(rowData[SKILL_PRIMARY_KEY] ?? '');
|
||||||
|
const data = await skillOnAPICall('read', 'update', undefined, id) as Record<string, unknown>;
|
||||||
|
return normalizeSkill(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (item.id === 'add') {
|
||||||
|
formValues = { name: '', description: '', content: '', tags: '' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!contextRow) return;
|
||||||
|
if (item.id === 'edit_content') {
|
||||||
|
const skill = normalizeSkill(contextRow);
|
||||||
|
selectedSkill = skill;
|
||||||
|
editorValues = { id: skill.id, content: skill.content };
|
||||||
|
editorOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const skill = normalizeSkill(contextRow);
|
||||||
|
formValues = toSkillForm(skill);
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onGridEvent(
|
||||||
|
type: string,
|
||||||
|
_item?: unknown,
|
||||||
|
_column?: unknown,
|
||||||
|
_coords?: unknown,
|
||||||
|
detail?: Record<string, unknown>
|
||||||
|
) {
|
||||||
|
if (type !== 'page_loaded' && type !== 'load') return;
|
||||||
|
const total = detail?.total;
|
||||||
|
if (typeof total === 'number') gridTotal = total;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSkillForm(data: SkillForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
name: data.name.trim(),
|
||||||
|
description: data.description.trim(),
|
||||||
|
content: data.content,
|
||||||
|
tags: data.tags.split(',').map((tag) => tag.trim()).filter(Boolean)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSkillSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
if (contextRow?.[SKILL_PRIMARY_KEY]) {
|
||||||
|
const data = await skillOnAPICall('read', 'update', undefined, String(contextRow[SKILL_PRIMARY_KEY])) as Record<string, unknown>;
|
||||||
|
selectedSkill = normalizeSkill(data);
|
||||||
|
}
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleEditorSaved() {
|
||||||
|
editorOpened = false;
|
||||||
|
if (editorValues.id) {
|
||||||
|
const data = await skillOnAPICall('read', 'update', undefined, String(editorValues.id)) as Record<string, unknown>;
|
||||||
|
const refreshed = normalizeSkill(data);
|
||||||
|
selectedSkill = refreshed;
|
||||||
|
editorValues = { id: refreshed.id, content: refreshed.content };
|
||||||
|
}
|
||||||
|
refreshKey += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(value?: string): string {
|
||||||
|
if (!value) return '—';
|
||||||
|
return new Date(value).toLocaleString();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="space-y-4">
|
<div class="space-y-4 w-full">
|
||||||
<div class="flex items-end justify-between">
|
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-2xl font-semibold text-white">Skills</h2>
|
<h2 class="text-2xl font-semibold text-white">Skills</h2>
|
||||||
<p class="mt-1 text-sm text-slate-400">{skills.length} skill{skills.length !== 1 ? 's' : ''}</p>
|
<p class="mt-1 text-sm text-slate-400">
|
||||||
</div>
|
{#if gridTotal === null}
|
||||||
<button
|
Server-backed grid
|
||||||
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
|
||||||
onclick={load}
|
|
||||||
>Refresh</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if error}
|
|
||||||
<div class="rounded-2xl border border-rose-400/30 bg-rose-400/10 px-4 py-4 text-sm text-rose-100">{error}</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if loading}
|
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-400">Loading…</div>
|
|
||||||
{:else if skills.length === 0}
|
|
||||||
<div class="rounded-2xl border border-dashed border-white/10 bg-slate-950/40 py-12 text-center text-slate-500">No skills registered.</div>
|
|
||||||
{:else}
|
{:else}
|
||||||
<div class="space-y-3">
|
{gridTotal} skill{gridTotal !== 1 ? 's' : ''}
|
||||||
{#each skills as skill}
|
|
||||||
<div class="rounded-2xl border border-white/10 bg-white/5 p-5">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<div class="min-w-0">
|
|
||||||
<p class="font-semibold text-white">{skill.name}</p>
|
|
||||||
{#if skill.description}
|
|
||||||
<p class="mt-1 text-sm text-slate-400">{skill.description}</p>
|
|
||||||
{/if}
|
|
||||||
{#if skill.tags?.length}
|
|
||||||
<div class="mt-2 flex flex-wrap gap-1">
|
|
||||||
{#each skill.tags as tag}
|
|
||||||
<span class="rounded-full border border-white/10 bg-white/5 px-2 py-0.5 text-xs text-slate-400">{tag}</span>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
{/if}
|
{/if}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
<button
|
<button
|
||||||
class="shrink-0 text-xs text-rose-400 hover:text-rose-300 disabled:opacity-40"
|
class="rounded-xl border border-cyan-300/30 bg-cyan-400/10 px-4 py-2 text-sm font-medium text-cyan-100 transition hover:bg-cyan-400/20"
|
||||||
onclick={() => remove(skill.id, skill.name)}
|
onclick={() => {
|
||||||
disabled={busy === skill.id}
|
formValues = { name: '', description: '', content: '', tags: '' };
|
||||||
>Delete</button>
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
}}
|
||||||
|
>New Skill</button>
|
||||||
</div>
|
</div>
|
||||||
<details class="mt-3">
|
|
||||||
<summary class="cursor-pointer text-xs text-slate-500 hover:text-slate-300">View content</summary>
|
|
||||||
<pre class="mt-2 overflow-x-auto rounded-xl bg-slate-950/60 p-3 text-xs text-slate-300 whitespace-pre-wrap">{skill.content}</pre>
|
|
||||||
</details>
|
|
||||||
</div>
|
</div>
|
||||||
{/each}
|
<div class="flex flex-col gap-4">
|
||||||
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
|
{#key refreshKey}
|
||||||
|
<ErrorBoundary namespace="SkillsGridlerFull">
|
||||||
|
<GridlerFull
|
||||||
|
{columns}
|
||||||
|
theme={adminGridTheme}
|
||||||
|
rowMarkers="number"
|
||||||
|
height={420}
|
||||||
|
width="100%"
|
||||||
|
pageSize={40}
|
||||||
|
dataSource="resolvespec"
|
||||||
|
dataSourceOptions={skillsDataSourceOptions}
|
||||||
|
serverSideSearch={true}
|
||||||
|
searchColumns={['name', 'description', 'content', 'tags']}
|
||||||
|
{menuItems}
|
||||||
|
{onGridEvent}
|
||||||
|
{onRowClick}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
|
<div class="flex items-start justify-between gap-3">
|
||||||
|
<h3 class="text-sm font-semibold text-white">Skill Inspector</h3>
|
||||||
|
{#if selectedSkill}
|
||||||
|
<button
|
||||||
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
|
onclick={() => {
|
||||||
|
if (!selectedSkill) return;
|
||||||
|
editorValues = { id: selectedSkill.id, content: selectedSkill.content };
|
||||||
|
editorOpened = true;
|
||||||
|
}}
|
||||||
|
>Edit Content</button>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{#if !selectedSkill}
|
||||||
|
<p class="mt-3 text-sm text-slate-500">
|
||||||
|
Select a skill row to inspect details.
|
||||||
|
</p>
|
||||||
|
{:else}
|
||||||
|
<div class="mt-3 space-y-3 text-sm text-slate-300">
|
||||||
|
<p class="text-base font-semibold text-slate-100">{selectedSkill.name}</p>
|
||||||
|
<p><strong class="text-slate-100">Description:</strong> {selectedSkill.description || '—'}</p>
|
||||||
|
<p><strong class="text-slate-100">Created:</strong> {formatDate(selectedSkill.created_at)}</p>
|
||||||
|
<p><strong class="text-slate-100">Updated:</strong> {formatDate(selectedSkill.updated_at)}</p>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p class="text-xs uppercase tracking-[0.18em] text-slate-500">Tags</p>
|
||||||
|
<div class="mt-2 flex flex-wrap gap-2">
|
||||||
|
{#if selectedSkill.tags.length}
|
||||||
|
{#each selectedSkill.tags as tag}
|
||||||
|
<span class="rounded-md bg-white/10 px-2 py-0.5 text-xs text-slate-300">{tag}</span>
|
||||||
|
{/each}
|
||||||
|
{:else}
|
||||||
|
<span class="text-slate-500">No tags</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p class="text-xs uppercase tracking-[0.18em] text-slate-500">Content</p>
|
||||||
|
<pre class="mt-2 overflow-x-auto rounded-xl bg-slate-950/60 p-3 text-xs text-slate-300 whitespace-pre-wrap">{selectedSkill.content}</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="SkillsEditorFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={editorOpened}
|
||||||
|
bind:values={editorValues}
|
||||||
|
request="update"
|
||||||
|
title="Edit Skill Content"
|
||||||
|
uniqueKeyField={SKILL_PRIMARY_KEY}
|
||||||
|
width="min(96vw, 90rem)"
|
||||||
|
onAPICall={skillOnAPICall}
|
||||||
|
beforeSave={(data) => ({ content: data.content })}
|
||||||
|
afterSave={handleEditorSaved}
|
||||||
|
onClose={() => {
|
||||||
|
editorOpened = false;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<ContentEditorField
|
||||||
|
filename="skill.md"
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, content: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="SkillsFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'insert' ? 'New Skill' : formRequest === 'update' ? 'Edit Skill' : 'Delete Skill'}
|
||||||
|
uniqueKeyField={SKILL_PRIMARY_KEY}
|
||||||
|
onAPICall={skillOnAPICall}
|
||||||
|
afterGet={async (data) => normalizeSkillRecordForFormer(data as Record<string, unknown>)}
|
||||||
|
beforeSave={normalizeSkillForm}
|
||||||
|
afterSave={handleSkillSaved}
|
||||||
|
onClose={() => {
|
||||||
|
formOpened = false;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Name"
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.name ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, name: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Description"
|
||||||
|
name="description"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.description ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, description: v })}
|
||||||
|
/>
|
||||||
|
<TextInputCtrl
|
||||||
|
label="Tags"
|
||||||
|
name="tags"
|
||||||
|
placeholder="comma-separated"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.tags ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, tags: v })}
|
||||||
|
/>
|
||||||
|
<ContentEditorField
|
||||||
|
filename="skill.md"
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, content: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
@@ -1,13 +1,24 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import {
|
import {
|
||||||
|
ErrorBoundary,
|
||||||
|
FormerResolveSpecAPI,
|
||||||
GridlerFull,
|
GridlerFull,
|
||||||
|
NativeSelectCtrl,
|
||||||
type GridColumnFilters,
|
type GridColumnFilters,
|
||||||
type GridlerColumn,
|
type GridlerColumn,
|
||||||
|
type GridlerContextMenuItem,
|
||||||
} from "@warkypublic/svelix";
|
} from "@warkypublic/svelix";
|
||||||
|
import FormerShell from "../shared/FormerShell.svelte";
|
||||||
|
import { onMount } from "svelte";
|
||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { GlobalStateStore } from "../../shellState";
|
|
||||||
import { adminGridTheme } from "../../gridTheme";
|
import { adminGridTheme } from "../../gridTheme";
|
||||||
|
import { GlobalStateStore } from "../../shellState";
|
||||||
import type { StoredFile, Thought, ThoughtLink } from "../../types";
|
import type { StoredFile, Thought, ThoughtLink } from "../../types";
|
||||||
|
import ContentEditorField from "../shared/ContentEditorField.svelte";
|
||||||
|
|
||||||
|
type ThoughtForm = { id?: string; content: string; project_id?: string };
|
||||||
|
|
||||||
|
const THOUGHT_PRIMARY_KEY = 'id';
|
||||||
|
|
||||||
let includeArchived = $state(false);
|
let includeArchived = $state(false);
|
||||||
let actionBusy = $state<string | null>(null);
|
let actionBusy = $state<string | null>(null);
|
||||||
@@ -16,14 +27,107 @@
|
|||||||
let selectedThought = $state<Thought | null>(null);
|
let selectedThought = $state<Thought | null>(null);
|
||||||
let relatedLinks = $state<ThoughtLink[]>([]);
|
let relatedLinks = $state<ThoughtLink[]>([]);
|
||||||
let relatedFiles = $state<StoredFile[]>([]);
|
let relatedFiles = $state<StoredFile[]>([]);
|
||||||
|
let formOpened = $state(false);
|
||||||
|
let formRequest = $state<'insert' | 'update' | 'delete'>('insert');
|
||||||
|
let formValues = $state<ThoughtForm>({ content: '' });
|
||||||
|
let editorOpened = $state(false);
|
||||||
|
let editorValues = $state<{ id?: string; content: string }>({ content: '' });
|
||||||
|
let contextRow = $state<Record<string, unknown> | null>(null);
|
||||||
|
let refreshKey = $state(0);
|
||||||
|
let projectOptions = $state<{ label: string; value: string }[]>([]);
|
||||||
|
const authToken = GlobalStateStore.getState().session.authToken ?? '';
|
||||||
|
const thoughtOnAPICall = $derived(FormerResolveSpecAPI({
|
||||||
|
authToken,
|
||||||
|
url: '/api/rs/public/thoughts'
|
||||||
|
}));
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
const projects = await api.projects.list();
|
||||||
|
projectOptions = projects.map((p) => ({ label: p.name, value: p.id }));
|
||||||
|
});
|
||||||
|
|
||||||
|
const menuItems: GridlerContextMenuItem[] = [
|
||||||
|
{ id: 'add', label: 'Add' },
|
||||||
|
{ id: 'edit', label: 'Edit' },
|
||||||
|
{ id: 'edit_content', label: 'Edit Content' },
|
||||||
|
{ id: 'delete', label: 'Delete' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function onRowContextMenu(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
contextRow = rowData ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeThoughtRecordForFormer(data: Record<string, unknown>): ThoughtForm {
|
||||||
|
return {
|
||||||
|
id: data.id != null ? String(data.id) : undefined,
|
||||||
|
content: typeof data.content === 'string' ? data.content : '',
|
||||||
|
project_id: typeof data.project_id === 'string' && data.project_id ? data.project_id : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadThoughtFromRow(rowData: Record<string, unknown>): Promise<Thought> {
|
||||||
|
const id = String(rowData[THOUGHT_PRIMARY_KEY] ?? '');
|
||||||
|
return await thoughtOnAPICall('read', 'update', undefined, id) as Thought;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onMenuItemSelect(item: GridlerContextMenuItem) {
|
||||||
|
if (item.id === 'add') {
|
||||||
|
formValues = { content: '' };
|
||||||
|
formRequest = 'insert';
|
||||||
|
formOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!contextRow) return;
|
||||||
|
if (item.id === 'edit_content') {
|
||||||
|
const thought = normalizeThought(contextRow);
|
||||||
|
selectedThought = thought;
|
||||||
|
editorValues = { id: thought.id, content: thought.content };
|
||||||
|
editorOpened = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const thought = normalizeThought(contextRow);
|
||||||
|
formValues = {
|
||||||
|
id: thought.id,
|
||||||
|
content: thought.content,
|
||||||
|
project_id: thought.project_id
|
||||||
|
};
|
||||||
|
formRequest = item.id === 'delete' ? 'delete' : 'update';
|
||||||
|
formOpened = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeThoughtForm(data: ThoughtForm): Record<string, unknown> {
|
||||||
|
return {
|
||||||
|
content: data.content,
|
||||||
|
project_id: data.project_id || undefined
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleThoughtSaved() {
|
||||||
|
formOpened = false;
|
||||||
|
if (contextRow?.id) {
|
||||||
|
const thought = await loadThoughtFromRow(contextRow);
|
||||||
|
await inspectThought(thought);
|
||||||
|
}
|
||||||
|
refreshKey++;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleThoughtEditorSaved() {
|
||||||
|
editorOpened = false;
|
||||||
|
if (editorValues.id) {
|
||||||
|
const thought = await thoughtOnAPICall('read', 'update', undefined, editorValues.id) as Thought;
|
||||||
|
editorValues = { id: thought.id, content: thought.content };
|
||||||
|
await inspectThought(thought);
|
||||||
|
}
|
||||||
|
refreshKey++;
|
||||||
|
}
|
||||||
let gridTotal = $state<number | null>(null);
|
let gridTotal = $state<number | null>(null);
|
||||||
const thoughtsDataSourceOptions = {
|
const thoughtsDataSourceOptions = {
|
||||||
url: "/api/rs",
|
url: "/api/rs",
|
||||||
authToken: GlobalStateStore.getState().session.authToken,
|
authToken: GlobalStateStore.getState().session.authToken,
|
||||||
schema: "public",
|
schema: "public",
|
||||||
entity: "thoughts",
|
entity: "thoughts",
|
||||||
uniqueID: "id",
|
uniqueID: THOUGHT_PRIMARY_KEY,
|
||||||
hotfields: ["guid", "metadata", "project_id", "archived_at"],
|
hotfields: [THOUGHT_PRIMARY_KEY, "guid", "metadata", "project_id", "archived_at"],
|
||||||
sort: [{ column: "created_at", direction: "desc" }],
|
sort: [{ column: "created_at", direction: "desc" }],
|
||||||
} as unknown as {
|
} as unknown as {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -177,6 +281,12 @@
|
|||||||
void inspectThought(normalizeThought(rowData));
|
void inspectThought(normalizeThought(rowData));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onRowDblClick(_row: number, rowData: Record<string, unknown> | undefined) {
|
||||||
|
if (!rowData) return;
|
||||||
|
contextRow = rowData;
|
||||||
|
void onMenuItemSelect({ id: 'edit', label: 'Edit' });
|
||||||
|
}
|
||||||
|
|
||||||
function onGridEvent(
|
function onGridEvent(
|
||||||
type: string,
|
type: string,
|
||||||
_item?: unknown,
|
_item?: unknown,
|
||||||
@@ -220,6 +330,10 @@
|
|||||||
/>
|
/>
|
||||||
Archived
|
Archived
|
||||||
</label>
|
</label>
|
||||||
|
<button
|
||||||
|
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
||||||
|
onclick={() => { formValues = { content: '' }; formRequest = 'insert'; formOpened = true; }}>New Thought</button
|
||||||
|
>
|
||||||
<button
|
<button
|
||||||
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
class="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-200 transition hover:bg-white/10"
|
||||||
onclick={() => {
|
onclick={() => {
|
||||||
@@ -237,6 +351,8 @@
|
|||||||
|
|
||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
<div class="rounded-2xl border border-white/10 bg-slate-950/30 p-3">
|
||||||
|
{#key refreshKey}
|
||||||
|
<ErrorBoundary namespace="ThoughtsGridlerFull">
|
||||||
<GridlerFull
|
<GridlerFull
|
||||||
{columns}
|
{columns}
|
||||||
theme={adminGridTheme}
|
theme={adminGridTheme}
|
||||||
@@ -249,9 +365,15 @@
|
|||||||
serverSideSearch={true}
|
serverSideSearch={true}
|
||||||
searchColumns={["content"]}
|
searchColumns={["content"]}
|
||||||
filters={baseFilters}
|
filters={baseFilters}
|
||||||
|
{menuItems}
|
||||||
{onGridEvent}
|
{onGridEvent}
|
||||||
{onRowClick}
|
{onRowClick}
|
||||||
|
{onRowDblClick}
|
||||||
|
{onRowContextMenu}
|
||||||
|
{onMenuItemSelect}
|
||||||
/>
|
/>
|
||||||
|
</ErrorBoundary>
|
||||||
|
{/key}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
<aside class="rounded-2xl border border-white/10 bg-slate-900/70 p-4">
|
||||||
@@ -259,6 +381,15 @@
|
|||||||
<h3 class="text-sm font-semibold text-white">Thought Inspector</h3>
|
<h3 class="text-sm font-semibold text-white">Thought Inspector</h3>
|
||||||
{#if selectedThought}
|
{#if selectedThought}
|
||||||
<div class="flex gap-2">
|
<div class="flex gap-2">
|
||||||
|
<button
|
||||||
|
class="text-xs text-cyan-300 hover:text-cyan-200"
|
||||||
|
onclick={() => {
|
||||||
|
const thought = selectedThought;
|
||||||
|
if (!thought) return;
|
||||||
|
editorValues = { id: thought.id, content: thought.content };
|
||||||
|
editorOpened = true;
|
||||||
|
}}>Edit Content</button
|
||||||
|
>
|
||||||
{#if !isSelectedArchived()}
|
{#if !isSelectedArchived()}
|
||||||
<button
|
<button
|
||||||
class="text-xs text-slate-300 hover:text-white"
|
class="text-xs text-slate-300 hover:text-white"
|
||||||
@@ -387,3 +518,60 @@
|
|||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="ThoughtsEditorFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={editorOpened}
|
||||||
|
bind:values={editorValues}
|
||||||
|
request="update"
|
||||||
|
title="Edit Thought"
|
||||||
|
uniqueKeyField={THOUGHT_PRIMARY_KEY}
|
||||||
|
width="min(96vw, 90rem)"
|
||||||
|
onAPICall={thoughtOnAPICall}
|
||||||
|
beforeSave={(data) => ({ content: data.content })}
|
||||||
|
afterSave={handleThoughtEditorSaved}
|
||||||
|
onClose={() => { editorOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<ContentEditorField
|
||||||
|
filename="thought.md"
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, content: v })}
|
||||||
|
/>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|
||||||
|
<ErrorBoundary namespace="ThoughtsFormer">
|
||||||
|
<FormerShell
|
||||||
|
bind:opened={formOpened}
|
||||||
|
bind:values={formValues}
|
||||||
|
bind:request={formRequest}
|
||||||
|
title={formRequest === 'insert' ? 'New Thought' : formRequest === 'update' ? 'Edit Thought' : 'Delete Thought'}
|
||||||
|
uniqueKeyField={THOUGHT_PRIMARY_KEY}
|
||||||
|
onAPICall={thoughtOnAPICall}
|
||||||
|
afterGet={async (data) => normalizeThoughtRecordForFormer(data as Record<string, unknown>)}
|
||||||
|
beforeSave={normalizeThoughtForm}
|
||||||
|
afterSave={handleThoughtSaved}
|
||||||
|
onClose={() => { formOpened = false; }}
|
||||||
|
>
|
||||||
|
{#snippet children(state)}
|
||||||
|
<div class="space-y-4 p-4">
|
||||||
|
<ContentEditorField
|
||||||
|
filename="thought.md"
|
||||||
|
value={state.values?.content ?? ''}
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, content: v })}
|
||||||
|
/>
|
||||||
|
<NativeSelectCtrl
|
||||||
|
label="Project"
|
||||||
|
name="project_id"
|
||||||
|
disabled={state.request === 'delete'}
|
||||||
|
value={state.values?.project_id ?? ''}
|
||||||
|
options={[{ label: '— None —', value: '' }, ...projectOptions]}
|
||||||
|
onchange={(v) => state.setState('values', { ...state.values, project_id: v || undefined })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</FormerShell>
|
||||||
|
</ErrorBoundary>
|
||||||
|
|||||||
Reference in New Issue
Block a user