fix: extracted events are root entries, documents are references

- Reversed parent-child relationship: events/assessments are now root level
- Source document stored in data.source_id instead of parent_id
- Generic section summary uses section ID (e.g., '2 medications' not '2 items')
- Reprocessed Anastasiia's 62 entries
This commit is contained in:
Johan Jongsma 2026-02-02 07:22:27 +00:00
parent 8754a9df40
commit e46abbdddd
6 changed files with 344 additions and 214 deletions

View File

@ -1,7 +1,8 @@
# Inou Build System # Inou Build System
# Run on .253: make deploy (staging), make deploy-prod (production) # make deploy (staging @ .253), make deploy-prod (production @ .2)
VERSION := 1.0.0 VERSION := 1.0.0
STAGING_HOST := johan@192.168.1.253
PROD_HOST := johan@192.168.100.2 PROD_HOST := johan@192.168.100.2
BUILD_TIME := $(shell date '+%Y-%m-%d %H:%M:%S') BUILD_TIME := $(shell date '+%Y-%m-%d %H:%M:%S')
LDFLAGS := -ldflags "-X main.Version=$(VERSION) -X 'main.BuildTime=$(BUILD_TIME)'" LDFLAGS := -ldflags "-X main.Version=$(VERSION) -X 'main.BuildTime=$(BUILD_TIME)'"
@ -75,27 +76,19 @@ test:
test-rbac: test-rbac:
@./scripts/test-rbac.sh @./scripts/test-rbac.sh
# Deploy to production (builds, copies, restarts) # Deploy to STAGING (builds locally, copies to staging, restarts)
# Runs check-db FIRST to prevent deploying code with direct DB access # Runs check-db FIRST to prevent deploying code with direct DB access
deploy: check-db all $(BINDIR)/decrypt $(BINDIR)/fips-check deploy: check-db all $(BINDIR)/decrypt $(BINDIR)/fips-check
$(DEPLOY_DIR)/stop.sh @echo "=== Deploying to STAGING ($(STAGING_HOST)) ==="
mkdir -p $(DEPLOY_DIR)/bin ssh $(STAGING_HOST) "$(DEPLOY_DIR)/stop.sh"
mkdir -p $(DEPLOY_DIR)/templates rsync -avz $(BINDIR)/ $(STAGING_HOST):$(DEPLOY_DIR)/bin/
mkdir -p $(DEPLOY_DIR)/static rsync -avz --delete templates/ $(STAGING_HOST):$(DEPLOY_DIR)/templates/
cp $(BINDIR)/viewer $(DEPLOY_DIR)/bin/ rsync -avz static/ $(STAGING_HOST):$(DEPLOY_DIR)/static/
cp $(BINDIR)/portal $(DEPLOY_DIR)/bin/ rsync -avz lang/ $(STAGING_HOST):$(DEPLOY_DIR)/lang/
cp $(BINDIR)/api $(DEPLOY_DIR)/bin/ rsync -avz api/prompts/ $(STAGING_HOST):$(DEPLOY_DIR)/prompts/
cp $(BINDIR)/import-genome $(DEPLOY_DIR)/bin/ ssh $(STAGING_HOST) "$(DEPLOY_DIR)/start.sh"
cp $(BINDIR)/import-dicom $(DEPLOY_DIR)/bin/
cp $(BINDIR)/decrypt $(DEPLOY_DIR)/bin/
cp $(BINDIR)/fips-check $(DEPLOY_DIR)/bin/
cp $(BINDIR)/lab-* $(DEPLOY_DIR)/bin/ 2>/dev/null || true
rsync -av --delete portal/templates/ $(DEPLOY_DIR)/templates/
rsync -av portal/static/ $(DEPLOY_DIR)/static/
rsync -av portal/lang/ $(DEPLOY_DIR)/lang/
$(DEPLOY_DIR)/start.sh
@echo "" @echo ""
$(DEPLOY_DIR)/status.sh ssh $(STAGING_HOST) "$(DEPLOY_DIR)/status.sh"
# Deploy to PRODUCTION (builds locally, copies to prod, restarts) # Deploy to PRODUCTION (builds locally, copies to prod, restarts)
# This is a SEPARATE action from staging deploy - requires explicit invocation # This is a SEPARATE action from staging deploy - requires explicit invocation

76
PROMPT-FUNCTION-BRIEF.md Normal file
View File

@ -0,0 +1,76 @@
# Prompt Function — Flagship Feature Brief
## Vision
This is one of inou's flagship features. It must be **awesome beyond belief** — pretty, intuitive, fast, useful.
User types natural language → system understands, stores, and intelligently follows up.
**Examples:**
- "I had a headache, took a Tylenol" → logs both, asks tomorrow "Did you take Tylenol?"
- "Blood pressure 120/80" → stores with proper fields (systolic/diastolic)
- "Leg trainer: 3 sets, 12 reps, 45kg" → handles complex multi-parameter input
- "My period stopped" → does NOT ask about period the next day
- "I'm pregnant" then later "I had my period" → handles contradiction intelligently
## Core Concept
Everything displays as a **prompt card**. The card's state changes:
- **Due** — waiting for input
- **Completed** — what you just told us (confirmation)
- **Pending** — coming tomorrow
When you type freeform input, you immediately see it as a completed card. Tomorrow's follow-up appears as a due card.
## Smart & Sensitive
The system must be intelligent about follow-ups:
- One-time events don't generate recurring prompts
- Contradictions are handled (pregnancy → period means pregnancy ended)
- "Stopped taking X" dismisses the X prompt
- Context matters — understand what makes sense to ask again
## Design
Follow the styleguide: `inou.com/styleguide`
Cards are not in the styleguide yet — design freedom here, but match the inou aesthetic.
## Existing Code
**LLM Pipeline:**
- `api/prompts/triage.md` — categorizes input
- `api/prompts/*.md` — category-specific extraction prompts
- `api/api_llm.go``callLLMForPrompt()` orchestrates triage → extraction
- `api/api_prompts.go` — API endpoints, `tryGeneratePromptFromFreeform()`
**Data:**
- `lib/types.go``Prompt`, `Entry` structs
- `lib/prompt.go` — CRUD, respond, skip, dismiss
**UI:**
- `portal/prompts.go` — current prompts page
- `portal/templates/prompts.tmpl` — current template
**Test harness:**
- `test-prompts/main.go` — CLI tool: `./test-prompts "I took aspirin"`
## Flexibility
Input configs must handle:
- Single checkbox ("Did you take X?")
- Multiple checkboxes ("Morning pills: ☐ Lisinopril ☐ Metformin")
- Numeric with units ("Weight: ___ kg")
- Multi-field ("BP: ___/___ mmHg")
- Complex forms ("Leg trainer: sets ___ reps ___ weight ___")
- Scales ("Pain level 1-10")
The LLM extraction prompts define `input_config` — the UI renders whatever structure it returns.
## Must Have
- Edit recognized prompts (change question, schedule, fields)
- Delete/dismiss prompts
- Works beautifully on web and mobile (WebView)
- Fast — no jarring waits after input
- Immediate visual confirmation of what was captured

View File

@ -124,17 +124,18 @@ func createEventEntry(sourceID string, event map[string]interface{}) error {
} }
} }
// Build data // Build data - include source document as reference (not parent)
data := map[string]interface{}{ data := map[string]interface{}{
"where": where, "where": where,
"details": details, "details": details,
"source_id": sourceID, // reference to source document
} }
dataJSON, _ := json.Marshal(data) dataJSON, _ := json.Marshal(data)
entry := lib.Entry{ entry := lib.Entry{
EntryID: lib.NewID(), EntryID: lib.NewID(),
DossierID: dossierID, DossierID: dossierID,
ParentID: sourceID, // link to source document ParentID: "", // ROOT level - event is the primary entity
Category: category, Category: category,
Type: eventType, Type: eventType,
Value: what, Value: what,
@ -150,15 +151,17 @@ func createAssessmentEntry(sourceID string, assessment map[string]interface{}) e
by, _ := assessment["by"].(string) by, _ := assessment["by"].(string)
states, _ := assessment["states"].(string) states, _ := assessment["states"].(string)
// Include source document as reference (not parent)
data := map[string]interface{}{ data := map[string]interface{}{
"provider": by, "provider": by,
"source_id": sourceID, // reference to source document
} }
dataJSON, _ := json.Marshal(data) dataJSON, _ := json.Marshal(data)
entry := lib.Entry{ entry := lib.Entry{
EntryID: lib.NewID(), EntryID: lib.NewID(),
DossierID: dossierID, DossierID: dossierID,
ParentID: sourceID, // link to source document ParentID: "", // ROOT level - assessment is the primary entity
Category: lib.CategoryAssessment, Category: lib.CategoryAssessment,
Type: "clinical_opinion", Type: "clinical_opinion",
Value: states, Value: states,

View File

@ -178,7 +178,8 @@ func BuildDossierSections(targetID, targetHex string, target *lib.Dossier, p *li
if cfg.Category > 0 { if cfg.Category > 0 {
entries, _ := lib.EntryList(nil, "", cfg.Category, &lib.EntryFilter{DossierID: targetID, Limit: 50}) entries, _ := lib.EntryList(nil, "", cfg.Category, &lib.EntryFilter{DossierID: targetID, Limit: 50})
section.Items = entriesToSectionItems(entries) section.Items = entriesToSectionItems(entries)
section.Summary = fmt.Sprintf("%d items", len(entries)) // Use section ID for summary (e.g., "2 medications" not "2 items")
section.Summary = fmt.Sprintf("%d %s", len(entries), cfg.ID)
} }
} }

View File

@ -242,9 +242,19 @@ func handlePrompts(w http.ResponseWriter, r *http.Request) {
entries = append(entries, ev) entries = append(entries, ev)
} }
// Split prompts into due and upcoming
var duePrompts, upcomingPrompts []PromptView
for _, p := range prompts {
if p.IsDue || p.IsFreeform {
duePrompts = append(duePrompts, p)
} else {
upcomingPrompts = append(upcomingPrompts, p)
}
}
// Count due items (excluding freeform) // Count due items (excluding freeform)
dueCount := 0 dueCount := 0
for _, p := range prompts { for _, p := range duePrompts {
if !p.IsFreeform { if !p.IsFreeform {
dueCount++ dueCount++
} }
@ -254,11 +264,12 @@ func handlePrompts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Type", "text/html; charset=utf-8")
templates.ExecuteTemplate(w, "base.tmpl", struct { templates.ExecuteTemplate(w, "base.tmpl", struct {
PageData PageData
Prompts []PromptView DuePrompts []PromptView
Entries []EntryView UpcomingPrompts []PromptView
TargetHex string Entries []EntryView
DueCount int TargetHex string
}{data, prompts, entries, targetHex, dueCount}) DueCount int
}{data, duePrompts, upcomingPrompts, entries, targetHex, dueCount})
} }
func handlePromptRespond(w http.ResponseWriter, r *http.Request) { func handlePromptRespond(w http.ResponseWriter, r *http.Request) {

View File

@ -1,14 +1,19 @@
{{define "prompts"}} {{define "prompts"}}
<div class="sg-container"> <div class="sg-container">
<h1 style="font-size: 2.5rem; font-weight: 700;">{{if .TargetDossier}}{{.TargetDossier.Name}}'s {{end}}Daily Check-in</h1> <h1 style="font-size: 2.5rem; font-weight: 700;">Daily Check-in</h1>
<p class="intro" style="font-size: 1.15rem; font-weight: 300; line-height: 1.8;">Track daily measurements and observations</p> <p class="intro" style="font-size: 1.15rem; font-weight: 300; line-height: 1.8;">Track daily measurements and observations</p>
{{if .Error}}<div class="msg msg-error">{{.Error}}</div>{{end}} {{if .Error}}<div class="msg msg-error">{{.Error}}</div>{{end}}
{{if .Success}}<div class="msg msg-success">{{.Success}}</div>{{end}} {{if .Success}}<div class="msg msg-success">{{.Success}}</div>{{end}}
{{if .Prompts}} <!-- Processing Toast -->
<div id="processing-toast" class="processing-toast">
<div class="processing-spinner"></div>
<span id="processing-text">Processing...</span>
</div>
<!-- TODAY Section -->
<div class="data-card"> <div class="data-card">
<!-- Section header -->
<div class="prompt-section-header"> <div class="prompt-section-header">
<div class="prompt-section-bar"></div> <div class="prompt-section-bar"></div>
<div class="prompt-section-info"> <div class="prompt-section-info">
@ -17,7 +22,8 @@
</div> </div>
</div> </div>
<div class="prompt-list"> <div class="prompt-list" id="today-list">
<!-- Entries (readonly) -->
{{range .Entries}} {{range .Entries}}
<div class="prompt-item entry-item" data-entry-id="{{.ID}}"> <div class="prompt-item entry-item" data-entry-id="{{.ID}}">
<a href="#" class="prompt-dismiss" onclick="deleteEntry('{{.ID}}'); return false;" title="Delete">✕</a> <a href="#" class="prompt-dismiss" onclick="deleteEntry('{{.ID}}'); return false;" title="Delete">✕</a>
@ -46,10 +52,10 @@
{{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}} {{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}}
</div> </div>
{{end}} {{end}}
{{range .Prompts}}
{{$prompt := .}} <!-- Due Prompts (interactive) -->
<div class="prompt-item{{if not .IsDue}} prompt-item-future{{end}}" data-prompt-id="{{.ID}}"> {{range .DuePrompts}}
<!-- Dismiss button --> <div class="prompt-item" data-prompt-id="{{.ID}}">
<a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '{{.ID}}'); return false;" title="Don't ask again">✕</a> <a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '{{.ID}}'); return false;" title="Don't ask again">✕</a>
<div class="dismiss-confirm"> <div class="dismiss-confirm">
<span>Stop tracking?</span> <span>Stop tracking?</span>
@ -57,8 +63,8 @@
<a href="#" onclick="hideDismissConfirm(this); return false;">No</a> <a href="#" onclick="hideDismissConfirm(this); return false;">No</a>
</div> </div>
<!-- Saved state (only show if due AND has response) --> <!-- Saved state -->
<div class="prompt-saved" style="display: {{if and .HasResponse .IsDue}}block{{else}}none{{end}};"> <div class="prompt-saved" style="display: {{if .HasResponse}}block{{else}}none{{end}};">
<div class="prompt-saved-header"> <div class="prompt-saved-header">
<span class="prompt-question">{{.Question}}</span> <span class="prompt-question">{{.Question}}</span>
<span class="prompt-saved-value">{{.LastResponseRaw}}</span> <span class="prompt-saved-value">{{.LastResponseRaw}}</span>
@ -70,13 +76,13 @@
{{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}} {{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}}
</div> </div>
<!-- Input state (show if not due, OR if due but no response) --> <!-- Input form -->
<form class="prompt-form" data-prompt-id="{{.ID}}"{{if and .HasResponse .IsDue}} style="display: none;"{{end}}> <form class="prompt-form" data-prompt-id="{{.ID}}" data-is-freeform="{{.IsFreeform}}"{{if .HasResponse}} style="display: none;"{{end}}>
<div class="prompt-header"> <div class="prompt-header">
<span class="prompt-question">{{.Question}}</span> <span class="prompt-question">{{.Question}}</span>
{{if .IsFreeform}}<span class="prompt-due">optional</span>{{else if .NextAsk}}<span class="prompt-due{{if .IsOverdue}} prompt-overdue{{end}}">{{.NextAskFormatted}}</span>{{end}} {{if .IsFreeform}}<span class="prompt-due">optional</span>{{else if .NextAsk}}<span class="prompt-due{{if .IsOverdue}} prompt-overdue{{end}}">{{.NextAskFormatted}}</span>{{end}}
</div> </div>
<div class="prompt-body"> <div class="prompt-body">
{{if .Fields}} {{if .Fields}}
{{if eq (len .Fields) 1}} {{if eq (len .Fields) 1}}
@ -84,8 +90,8 @@
{{if eq .Type "number"}} {{if eq .Type "number"}}
<div class="prompt-input-row"> <div class="prompt-input-row">
<input type="number" name="field_{{.Key}}" <input type="number" name="field_{{.Key}}"
{{if .Min}}min="{{.Min}}"{{end}} {{if .Min}}min="{{.Min}}"{{end}}
{{if .Max}}max="{{.Max}}"{{end}} {{if .Max}}max="{{.Max}}"{{end}}
{{if .Step}}step="{{.Step}}"{{end}} {{if .Step}}step="{{.Step}}"{{end}}
{{if .Value}}value="{{.Value}}"{{end}} {{if .Value}}value="{{.Value}}"{{end}}
class="prompt-input-number"> class="prompt-input-number">
@ -161,7 +167,10 @@
{{end}} {{end}}
{{end}} {{end}}
{{else}} {{else}}
<textarea name="response_raw" class="prompt-textarea" rows="3" placeholder="Type your notes..."></textarea> <div class="freeform-input-row">
<textarea name="response_raw" class="prompt-textarea" rows="2" placeholder="Type anything... (press Enter to submit)"></textarea>
<button type="button" class="freeform-submit-btn" onclick="submitFreeform(this)">→</button>
</div>
{{end}} {{end}}
</div> </div>
</form> </form>
@ -169,10 +178,40 @@
{{end}} {{end}}
</div> </div>
</div> </div>
{{else}}
<div class="empty-state"> <!-- UPCOMING Section -->
<p>All caught up! No items due right now.</p> {{if .UpcomingPrompts}}
<a href="/dossier/{{.TargetHex}}/prompts?all=1" class="btn btn-secondary">View all items</a> <div class="data-card" style="margin-top: 24px;">
<div class="prompt-section-header">
<div class="prompt-section-bar" style="background: var(--text-muted);"></div>
<div class="prompt-section-info">
<div class="prompt-section-title">UPCOMING</div>
<div class="prompt-section-subtitle">{{len .UpcomingPrompts}} scheduled</div>
</div>
</div>
<div class="prompt-list">
{{range .UpcomingPrompts}}
<div class="prompt-item prompt-item-upcoming" data-prompt-id="{{.ID}}">
<a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '{{.ID}}'); return false;" title="Don't ask again">✕</a>
<div class="dismiss-confirm">
<span>Stop tracking?</span>
<a href="#" onclick="confirmDismiss('{{.ID}}'); return false;">Yes</a>
<a href="#" onclick="hideDismissConfirm(this); return false;">No</a>
</div>
<div class="prompt-header">
<span class="prompt-question">{{.Question}}</span>
<span class="prompt-due">{{.NextAskFormatted}}</span>
</div>
{{if .LastResponseRaw}}
<div class="prompt-body">
<span class="prompt-last-value">Last: {{.LastResponseRaw}}</span>
</div>
{{end}}
{{if .SourceInput}}<div class="prompt-source">↳ "{{.SourceInput}}"</div>{{end}}
</div>
{{end}}
</div>
</div> </div>
{{end}} {{end}}
@ -184,10 +223,60 @@
</div> </div>
<style> <style>
.page-subtitle { .processing-toast {
font-size: 1rem; display: none;
color: var(--text-muted); position: fixed;
margin-top: 4px; top: 20px;
left: 50%;
transform: translateX(-50%);
background: var(--text);
color: white;
padding: 12px 24px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 1000;
align-items: center;
gap: 12px;
}
.processing-toast.show {
display: flex;
animation: toastIn 0.2s ease-out;
}
@keyframes toastIn {
from { opacity: 0; transform: translateX(-50%) translateY(-10px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
.processing-spinner {
width: 18px;
height: 18px;
border: 2px solid rgba(255,255,255,0.3);
border-top-color: white;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.freeform-input-row {
display: flex;
gap: 8px;
align-items: flex-start;
}
.freeform-input-row .prompt-textarea {
flex: 1;
}
.freeform-submit-btn {
padding: 8px 16px;
background: var(--accent);
color: white;
border: none;
border-radius: 6px;
font-size: 1.1rem;
cursor: pointer;
transition: background 0.15s;
}
.freeform-submit-btn:hover {
background: #9a4408;
} }
.prompt-section-header { .prompt-section-header {
display: flex; display: flex;
@ -223,15 +312,13 @@
.prompt-item:last-child { .prompt-item:last-child {
border-bottom: none; border-bottom: none;
} }
.prompt-item-future { .prompt-item-upcoming {
opacity: 0.5; opacity: 0.6;
background: #fafafa; background: #fafafa;
} }
.prompt-item-future .prompt-question::after { .prompt-last-value {
content: ' (scheduled)'; font-size: 0.9rem;
font-size: 0.75rem; color: var(--text-muted);
color: #999;
font-weight: normal;
} }
.prompt-dismiss { .prompt-dismiss {
position: absolute; position: absolute;
@ -294,11 +381,6 @@
align-items: flex-end; align-items: flex-end;
gap: 8px; gap: 8px;
} }
.prompt-field-group {
display: flex;
flex-direction: column;
gap: 4px;
}
.prompt-field-row { .prompt-field-row {
display: flex; display: flex;
align-items: center; align-items: center;
@ -355,11 +437,6 @@
font-size: 0.875rem; font-size: 0.875rem;
color: var(--text-muted); color: var(--text-muted);
} }
.prompt-separator {
font-size: 1.1rem;
color: var(--text-muted);
margin-bottom: 8px;
}
.prompt-checkbox { .prompt-checkbox {
display: flex; display: flex;
align-items: center; align-items: center;
@ -430,10 +507,6 @@
border-color: var(--accent); border-color: var(--accent);
color: white; color: white;
} }
.prompt-scale-btn:focus {
outline: none;
box-shadow: 0 0 0 2px rgba(198, 93, 7, 0.2);
}
.prompt-select { .prompt-select {
padding: 8px 12px; padding: 8px 12px;
border: 1px solid #ddd; border: 1px solid #ddd;
@ -453,7 +526,7 @@
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: flex-start; align-items: flex-start;
padding-right: 40px; /* space for dismiss X */ padding-right: 40px;
gap: 20px; gap: 20px;
} }
.prompt-saved-value { .prompt-saved-value {
@ -502,54 +575,68 @@
font-weight: 600; font-weight: 600;
color: var(--accent); color: var(--accent);
} }
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style> </style>
<script> <script>
const targetHex = '{{.TargetHex}}'; const targetHex = '{{.TargetHex}}';
// Processing toast
function showProcessing(text) {
const toast = document.getElementById('processing-toast');
document.getElementById('processing-text').textContent = text || 'Processing...';
toast.classList.add('show');
}
function hideProcessing() {
document.getElementById('processing-toast').classList.remove('show');
}
// Initialize all prompt items
document.querySelectorAll('.prompt-item').forEach(item => { document.querySelectorAll('.prompt-item').forEach(item => {
item.addEventListener('focusout', (e) => { const form = item.querySelector('.prompt-form');
setTimeout(() => { if (!form) return;
if (!item.contains(document.activeElement)) {
saveItem(item); // Handle blur for non-freeform
} if (form.dataset.isFreeform !== 'true') {
}, 100); item.addEventListener('focusout', (e) => {
}); setTimeout(() => {
if (!item.contains(document.activeElement)) {
saveItem(item);
}
}, 100);
});
}
// Checkbox auto-save
item.querySelectorAll('input[type=checkbox]').forEach(cb => { item.querySelectorAll('input[type=checkbox]').forEach(cb => {
cb.addEventListener('change', () => saveItem(item)); cb.addEventListener('change', () => saveItem(item));
}); });
// Scale buttons
item.querySelectorAll('.prompt-scale-btn').forEach(btn => { item.querySelectorAll('.prompt-scale-btn').forEach(btn => {
btn.addEventListener('click', () => { btn.addEventListener('click', () => {
const field = btn.dataset.field;
const value = btn.dataset.value;
// Deselect siblings
btn.parentElement.querySelectorAll('.prompt-scale-btn').forEach(b => b.classList.remove('selected')); btn.parentElement.querySelectorAll('.prompt-scale-btn').forEach(b => b.classList.remove('selected'));
// Select this one
btn.classList.add('selected'); btn.classList.add('selected');
// Update hidden input const hidden = item.querySelector('input[name="field_' + btn.dataset.field + '"]');
const hidden = item.querySelector('input[name="field_' + field + '"]'); if (hidden) hidden.value = btn.dataset.value;
if (hidden) hidden.value = value;
// Auto-save
saveItem(item); saveItem(item);
}); });
}); });
// Select auto-save
item.querySelectorAll('.prompt-select').forEach(sel => { item.querySelectorAll('.prompt-select').forEach(sel => {
sel.addEventListener('change', () => saveItem(item)); sel.addEventListener('change', () => saveItem(item));
}); });
// Freeform Enter key
const textarea = item.querySelector('.prompt-textarea');
if (textarea && form.dataset.isFreeform === 'true') {
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitFreeform(textarea);
}
});
}
}); });
function showDismissConfirm(btn, promptId) { function showDismissConfirm(btn, promptId) {
@ -578,11 +665,9 @@ async function confirmDismiss(promptId) {
} }
async function deleteEntry(entryId) { async function deleteEntry(entryId) {
if (!confirm('Delete this entry and stop future tracking?')) return; if (!confirm('Delete this entry?')) return;
try { try {
await fetch('/dossier/' + targetHex + '/entries/' + entryId, { await fetch('/dossier/' + targetHex + '/entries/' + entryId, { method: 'DELETE' });
method: 'DELETE'
});
document.querySelector('.entry-item[data-entry-id="' + entryId + '"]').style.display = 'none'; document.querySelector('.entry-item[data-entry-id="' + entryId + '"]').style.display = 'none';
} catch (err) { } catch (err) {
console.error('Delete failed:', err); console.error('Delete failed:', err);
@ -590,7 +675,6 @@ async function deleteEntry(entryId) {
} }
function editEntry(btn) { function editEntry(btn) {
// TODO: implement entry editing
alert('Entry editing coming soon'); alert('Entry editing coming soon');
} }
@ -601,110 +685,66 @@ function editPrompt(btn) {
item.querySelector('.prompt-form input:not([type=hidden]), .prompt-form textarea')?.focus(); item.querySelector('.prompt-form input:not([type=hidden]), .prompt-form textarea')?.focus();
} }
function addNewPromptCard(prompt) { async function submitFreeform(el) {
const container = document.querySelector('.prompts-section'); const item = el.closest('.prompt-item');
if (!container) return; const form = item.querySelector('.prompt-form');
const textarea = form.querySelector('textarea[name="response_raw"]');
const hasResponse = prompt.last_response_raw || prompt.last_response; const value = textarea.value.trim();
const isDue = prompt.is_due !== false;
const futureClass = isDue ? '' : ' prompt-item-future'; if (!value) return;
// Build input fields HTML based on input_config showProcessing('Processing "' + value.substring(0, 30) + (value.length > 30 ? '...' : '') + '"');
let fieldsHtml = '';
if (prompt.input_config && prompt.input_config.fields) { try {
prompt.input_config.fields.forEach(field => { const res = await fetch('/dossier/' + targetHex + '/prompts/respond', {
if (field.type === 'checkbox') { method: 'POST',
fieldsHtml += ` headers: {
<label class="prompt-checkbox"> 'Content-Type': 'application/x-www-form-urlencoded',
<input type="checkbox" name="field_${field.key}" value="1"> 'Accept': 'application/json'
<span class="prompt-checkbox-box"></span> },
</label>`; body: new URLSearchParams({
} else if (field.type === 'number') { prompt_id: form.dataset.promptId,
const step = field.step || (field.datatype === 'float' ? '0.1' : '1'); action: 'respond',
const min = field.min !== undefined ? `min="${field.min}"` : ''; response: '{}',
const max = field.max !== undefined ? `max="${field.max}"` : ''; response_raw: value
const unit = field.unit ? `<span class="prompt-unit">${field.unit}</span>` : ''; })
fieldsHtml += `
<input type="number" name="field_${field.key}"
placeholder="${field.label || ''}"
step="${step}" ${min} ${max}
class="prompt-input prompt-input-number">
${unit}`;
} else {
fieldsHtml += `
<input type="text" name="field_${field.key}"
placeholder="${field.label || ''}"
class="prompt-input">`;
}
}); });
} else if (prompt.input_type === 'freeform') {
fieldsHtml = `<textarea name="response_raw" class="prompt-textarea" placeholder="Type here..."></textarea>`; if (res.ok) {
} const data = await res.json();
textarea.value = '';
const savedValue = prompt.last_response_raw || '';
const formDisplay = hasResponse ? 'none' : 'block'; hideProcessing();
const savedDisplay = hasResponse ? 'block' : 'none';
// Show success briefly then reload
const cardHtml = ` if (data.new_prompt) {
<div class="prompt-item prompt-item-new${futureClass}" style="animation: slideIn 0.3s ease-out;"> showProcessing('Created: ' + data.new_prompt.question);
<a href="#" class="prompt-dismiss" onclick="showDismissConfirm(this, '${prompt.id}'); return false;" title="Don't ask again">✕</a> setTimeout(() => {
<div class="dismiss-confirm"> hideProcessing();
<span>Stop tracking?</span> window.location.reload();
<a href="#" onclick="confirmDismiss('${prompt.id}'); return false;">Yes</a> }, 1500);
<a href="#" onclick="hideDismissConfirm(this); return false;">No</a> }
</div> } else {
<div class="prompt-saved" style="display: ${savedDisplay};"> hideProcessing();
<div class="prompt-saved-header">
<span class="prompt-question">${prompt.question}</span>
<span class="prompt-saved-value">${savedValue}</span>
</div>
<div class="prompt-saved-footer">
<span class="prompt-saved-time">just now</span>
<a href="#" class="prompt-edit" onclick="editPrompt(this); return false;">edit</a>
</div>
</div>
<form class="prompt-form" data-prompt-id="${prompt.id}" style="display: ${formDisplay};">
<div class="prompt-header">
<span class="prompt-question">${prompt.question}</span>
<span class="prompt-due">${isDue ? 'now' : 'tomorrow'}</span>
</div>
<div class="prompt-fields">
${fieldsHtml}
</div>
</form>
</div>`;
// Insert after the header
const header = container.querySelector('.section-header');
if (header) {
header.insertAdjacentHTML('afterend', cardHtml);
} else {
container.insertAdjacentHTML('afterbegin', cardHtml);
}
// Attach blur handler to new inputs
const newCard = container.querySelector('.prompt-item-new');
if (newCard) {
newCard.classList.remove('prompt-item-new');
if (!hasResponse) {
newCard.querySelectorAll('input, textarea').forEach(input => {
input.addEventListener('blur', () => setTimeout(() => saveItem(newCard), 100));
});
newCard.querySelector('input, textarea')?.focus();
} }
} catch (err) {
console.error('Submit failed:', err);
hideProcessing();
} }
} }
async function saveItem(item) { async function saveItem(item) {
const form = item.querySelector('.prompt-form'); const form = item.querySelector('.prompt-form');
if (!form) return;
const promptId = form.dataset.promptId; const promptId = form.dataset.promptId;
const inputs = form.querySelectorAll('input:not([type=hidden]), textarea'); const inputs = form.querySelectorAll('input:not([type=hidden]), textarea');
const response = {}; const response = {};
let hasValue = false; let hasValue = false;
let displayValue = ''; let displayValue = '';
let responseRaw = ''; let responseRaw = '';
inputs.forEach(input => { inputs.forEach(input => {
const key = input.name.replace('field_', '').replace('response_raw', 'raw'); const key = input.name.replace('field_', '').replace('response_raw', 'raw');
if (input.type === 'checkbox') { if (input.type === 'checkbox') {
@ -721,9 +761,20 @@ async function saveItem(item) {
responseRaw += (responseRaw ? ' / ' : '') + input.value; responseRaw += (responseRaw ? ' / ' : '') + input.value;
} }
}); });
// Also check hidden inputs for scale values
form.querySelectorAll('input[type=hidden]').forEach(hidden => {
if (hidden.value) {
const key = hidden.name.replace('field_', '');
response[key] = hidden.value;
hasValue = true;
displayValue += (displayValue ? ' / ' : '') + hidden.value;
responseRaw += (responseRaw ? ' / ' : '') + hidden.value;
}
});
if (!hasValue) return; if (!hasValue) return;
try { try {
const res = await fetch('/dossier/' + targetHex + '/prompts/respond', { const res = await fetch('/dossier/' + targetHex + '/prompts/respond', {
method: 'POST', method: 'POST',
@ -738,18 +789,13 @@ async function saveItem(item) {
response_raw: responseRaw response_raw: responseRaw
}) })
}); });
if (res.ok) { if (res.ok) {
const data = await res.json();
form.style.display = 'none'; form.style.display = 'none';
const saved = item.querySelector('.prompt-saved'); const saved = item.querySelector('.prompt-saved');
saved.querySelector('.prompt-saved-value').textContent = displayValue; if (saved) {
saved.style.display = 'block'; saved.querySelector('.prompt-saved-value').textContent = displayValue;
saved.style.display = 'block';
// If LLM generated a new prompt, add it to the deck
if (data.new_prompt) {
addNewPromptCard(data.new_prompt);
} }
} }
} catch (err) { } catch (err) {