knowledge_article_system/TECHNICAL_DOCUMENTATION.md
2025-11-25 16:41:54 -06:00

9.9 KiB

Knowledge Article System - Technical Documentation

System Architecture

Overview

The KA System is a local desktop application with a client-server architecture:

  • Backend: Node.js + Express + SQLite (sql.js)
  • Frontend: React (Vite)
  • Database: SQLite file-based database

Components

knowledge_article_system/
├── server/                 # Backend
│   ├── server.js          # Express server
│   ├── db.js              # Database functions
│   ├── ka.db              # SQLite database (created at runtime)
│   └── package.json       # Dependencies
│
└── client/                # Frontend
    ├── src/
    │   ├── App.jsx        # Main application component
    │   ├── components/    # UI components
    │   └── App.css        # Styles
    └── package.json       # Dependencies

Installation & Setup

Prerequisites

  • Node.js (v16 or higher)
  • npm (comes with Node.js)

First-Time Setup

Backend Setup

cd server
npm install

Dependencies installed:

  • express - Web server framework
  • sql.js - SQLite database
  • cors - Cross-origin resource sharing

Frontend Setup

cd client/kb-frontend
npm install

Dependencies installed:

  • react - UI framework
  • vite - Build tool and dev server
  • react-quill - Rich text editor (optional, currently using textarea)

Running the Application

Start Backend (Terminal 1)

cd server
node server.js

Server runs on: http://localhost:9000

Start Frontend (Terminal 2)

cd client/kb-frontend
npm run dev

Frontend runs on: http://localhost:5173


API Documentation

Base URL

http://localhost:9000/api

Endpoints

Get All Articles

GET /api/articles

Returns: Array of all articles, ordered by creation date (newest first)

Response:

[
  {
    "id": 1,
    "ka_number": "KA001",
    "title": "How to Reset Password",
    "content": "Steps to reset...",
    "created_at": "2024-11-24 12:00:00",
    "updated_at": null
  }
]

Get Single Article

GET /api/articles/:ka_number

Parameters: ka_number (e.g., "KA001")

Returns: Single article object or 404 if not found

Search Articles

GET /api/search?q={query}

Query Parameters: q - search term

Searches across: title, content, and ka_number

Returns: Array of matching articles

Create Article

POST /api/articles

Headers: Content-Type: application/json

Body:

{
  "title": "Article Title",
  "content": "Article content..."
}

Returns: Newly created article with auto-generated KA number

Update Article

PUT /api/articles/:ka_number

Headers: Content-Type: application/json

Body:

{
  "title": "Updated Title",
  "content": "Updated content..."
}

Returns: Updated article object

Delete Article

DELETE /api/articles/:ka_number

Returns: Success message


Database Schema

Articles Table

CREATE TABLE articles (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  ka_number TEXT UNIQUE NOT NULL,
  title TEXT NOT NULL,
  content TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME
);

CREATE INDEX idx_ka_number ON articles(ka_number);

Fields

Field Type Description
id INTEGER Auto-incrementing primary key
ka_number TEXT Unique identifier (KA001, KA002, etc.)
title TEXT Article title (required)
content TEXT Article content (HTML/text)
created_at DATETIME Timestamp of creation
updated_at DATETIME Timestamp of last update

KA Number Generation

KA numbers are auto-generated sequentially:

  • Format: KA + 3-digit number padded with zeros
  • Examples: KA001, KA002, ..., KA999
  • Logic in db.jsgetNextKANumber()

Code Structure

Backend (server.js)

Key Components:

  • Express server initialization
  • CORS configuration for frontend access
  • JSON body parsing middleware
  • API route handlers
  • Error handling

Important:

  • app.use(express.json()) must be present for POST/PUT requests
  • app.use(cors()) allows frontend to make requests
  • Database is initialized before routes are registered

Database Layer (db.js)

Functions:

  • initDb() - Initialize/load database
  • getAllArticles() - Fetch all articles
  • getArticle(ka_number) - Get single article
  • createArticle(title, content) - Create new article
  • updateArticle(ka_number, title, content) - Update article
  • deleteArticle(ka_number) - Delete article
  • searchArticles(query) - Search articles

Key Points:

  • Uses prepared statements for security
  • Database saved to disk after each write operation
  • KA numbers generated automatically

Frontend (App.jsx)

State Management:

  • currentView - Controls which view to show ('list', 'detail', 'edit')
  • selectedArticle - Currently selected article
  • articles - Array of articles for the list view

Key Functions:

  • handleSearch() - Search or load all articles
  • handleArticleClick() - View article details
  • handleEdit() - Switch to edit mode
  • handleSave() - Save new or updated article
  • handleDelete() - Delete article
  • handleCreateNew() - Create new article

Component Tree:

App
├── Header
├── SearchBar (list view)
├── ArticleList (list view)
├── ArticleDetail (detail view)
└── ArticleEditor (edit view)

Maintenance

Database Backup

Manual Backup:

# Stop the server first
cp server/ka.db server/ka.db.backup-$(date +%Y%m%d)

Automated Backup Script (Linux/Mac):

#!/bin/bash
# save as backup-ka.sh

SOURCE="./server/ka.db"
DEST="./backups/ka.db.$(date +%Y%m%d-%H%M%S)"

mkdir -p backups
cp $SOURCE $DEST
echo "Backup created: $DEST"

# Keep only last 30 backups
ls -t backups/ka.db.* | tail -n +31 | xargs rm -f

Windows Backup Script:

@echo off
REM save as backup-ka.bat

set SOURCE=server\ka.db
set DEST=backups\ka.db.%date:~-4,4%%date:~-10,2%%date:~-7,2%

if not exist backups mkdir backups
copy %SOURCE% %DEST%
echo Backup created: %DEST%

Database Restore

  1. Stop the backend server
  2. Replace server/ka.db with backup file
  3. Restart the server

Troubleshooting

Server won't start:

  • Check port 9000 is available
  • Verify npm dependencies installed
  • Check for syntax errors in server.js

Frontend won't connect:

  • Verify backend is running on port 9000
  • Check CORS is enabled in server.js
  • Clear browser cache

Database corruption:

  • Restore from backup
  • If no backup, delete ka.db and restart (creates new empty database)

Search not working:

  • Check database has articles
  • Verify search endpoint in server.js
  • Check browser console for errors

Deployment

Building for Production

Backend

Use pkg to create executable:

npm install -g pkg
cd server
pkg server.js

Creates executables:

  • server-win.exe (Windows)
  • server-linux (Linux)
  • server-macos (macOS)

Frontend

Build static files:

cd client/kb-frontend
npm run build

Output in dist/ folder - can be served by any static file server.

Distribution

COMING SOON


Future Enhancements

Potential features for Week 2+:

  • Rich text editor improvements
  • Article categories/tags
  • Attachment support (screenshots, logs)
  • Version history
  • Export to PDF
  • Article templates
  • User tracking (who created/edited)
  • Dark mode
  • Keyboard shortcuts

Security Considerations

Current State:

  • No authentication (local use only)
  • No input sanitization for XSS
  • SQL injection protected by prepared statements

For Production Use:

  • Add user authentication
  • Implement role-based access control
  • Sanitize HTML content from editor
  • Add rate limiting
  • Use HTTPS
  • Validate all inputs

Performance

Current Performance:

  • Handles hundreds of articles easily
  • Search is fast with ka_number index
  • No pagination needed for small teams

If Database Grows:

  • Add pagination to article list
  • Implement full-text search (SQLite FTS5)
  • Add more indexes
  • Consider caching frequently accessed articles

Testing

Manual Testing Checklist

Backend:

  • Server starts without errors
  • All API endpoints return correct data
  • Create article returns new article with KA number
  • Update article modifies existing article
  • Delete article removes from database
  • Search returns relevant results

Frontend:

  • Article list displays all articles
  • Search updates results correctly
  • Clicking article shows detail view
  • Edit button opens editor with current data
  • Save button updates article
  • Cancel button returns without saving
  • Delete button removes article after confirmation
  • Create new article generates KA number

API Testing with curl

# Create article
curl -X POST http://localhost:9000/api/articles \
  -H "Content-Type: application/json" \
  -d '{"title":"Test","content":"Test content"}'

# Get all articles
curl http://localhost:9000/api/articles

# Search
curl "http://localhost:9000/api/search?q=test"

# Update article
curl -X PUT http://localhost:9000/api/articles/KA001 \
  -H "Content-Type: application/json" \
  -d '{"title":"Updated","content":"New content"}'

# Delete article
curl -X DELETE http://localhost:9000/api/articles/KA001

Version History

v0.0.1 (MVP) - Week 1

Features:

  • Basic CRUD operations (Create, Read, Update, Delete)
  • Search functionality (title, content, KA number)
  • Auto-generated KA numbers
  • Simple text editor (textarea)
  • Responsive layout
  • Local SQLite database

Known Limitations:

  • No rich text editing (plain text/basic HTML only)
  • No authentication
  • No version history
  • No attachments
  • No categories/tags

Support

For issues or questions:

  • Check this documentation
  • Review USER_GUIDE.md for usage questions
  • Contact: Matt Taylor (developer)

License

MIT License