Skip to content

Risks and Improvements

  • Any system behavior that uses:
    • AiChatbot.isChatbotOn (global enable/disable)
    • AiChatbot.isOperatingHour + AiOperatingSchedule (time gating)
    • AiChatbot.modelType and prompt (runtime model/prompt selection)
    • WorkflowEnhancement linked to the chatbot (behavior modifiers)
  • Schedule overlap validation

    • Changes to validateTime(...) (in src/ai-chatbot/ai-chatbot.service.ts) directly affect what the UI can persist.
    • Regressions can cause:
      • overlapping schedules (double-activation)
      • inability to save valid schedules (customer friction)
  • Implicit prompt selection

    • Prompt is auto-linked by querying user prompt(s).
    • If prompt behavior changes (multiple prompts per user), the current implicit behavior becomes ambiguous and may select the wrong prompt.
  • One-per-user constraint

    • AiChatbot is unique per user in the DB.
    • Any attempt to support multiple bots per user is a breaking change across schema, API, and UI.
  • Endpoint coverage:
    • settings: create/get/update/delete
    • schedules: batch add/list/get/update/delete
  • Validation correctness:
    • overlaps on the same day
    • adjacent time ranges should be allowed
    • timezone conversion edge cases (DST transitions)
  • Security:
    • schedule ownership checks (must reject cross-user access)

Derived from current DTO/entity design and service behavior.

  • Runtime validation may be disabled

    • DTOs use class-validator, but if ValidationPipe is not enabled, malformed inputs can reach schedule validation and cause runtime errors (invalid timezone/time format).
  • Manual rollback is not a DB transaction

    • Create flow deletes the chatbot row if saving schedules fails.
    • This is simpler than a transaction but can leave partial state in some failure modes.
  • day stored as float

    • Entity stores day as float while DTOs treat it as int.
    • If non-integers are stored, overlap checks that compare by equality can become unreliable.
  • validateTime(...) is correctness-critical

    • Mixes time parsing assumptions (HH:mm), timezone conversion, and overlap detection.
    • High risk for regressions and DST-related bugs; requires dedicated tests.
  • update(...) orchestration complexity

    • Single method coordinates scalar changes, prompt linking, enhancement upsert, and schedule mutations.
    • Makes changes risky and difficult to reason about without regression tests.
  • Introduce TypeORM transactions

    • Wrap creation/updating of chatbot + enhancement + schedules in a single transaction for atomicity.
  • Make validation explicit

    • Ensure global ValidationPipe is enabled, or validate critical inputs in service:
      • timezone must be a valid IANA identifier
      • startHour/endHour must match HH:mm
      • define and validate allowed day range (e.g., 0–6 or 1–7)
  • Refactor update(...) into smaller units

    • Extract helper methods:
      • prompt attachment
      • enhancement upsert
      • schedule pipeline (load, validate, apply)
    • Improves testability and reduces accidental coupling.
  • Normalize schedule schema

    • Store day as an integer column.
    • Consider storing times as minutes-from-midnight to avoid string parsing assumptions.
  • Performance

    • Reduce repeated DB queries when updating many schedules (bulk load schedules and reuse in-memory comparisons).
  • Do not bypass ownership checks for schedules (security boundary).
  • Avoid silent changes to overlap rules without product alignment and explicit tests.
  • Avoid adding more responsibilities to AiChatbotService.update(...) without refactoring first.

title: Risks and Improvements sidebar: order: 4

Section titled “title: Risks and Improvements sidebar: order: 4”
  • Any runtime AI behavior that decides:
    • whether the chatbot should run (isChatbotOn)
    • whether operating hours are enforced (isOperatingHour)
    • whether current time is inside a schedule (operatingSchedule)
    • which model/prompt to use (modelType, prompt)
  • Enhancement-based behavior that reads WorkflowEnhancement linked to the chatbot.
  • Schedule overlap rules

    • Changing validateTime(...) will directly change what schedules the UI can save.
    • Small bugs here can allow overlaps (double-activation) or reject valid schedules (customer friction).
  • One-per-user invariant

    • DB uniqueness on user means any move to multi-chatbot-per-user is a breaking change.
  • Implicit prompt selection

    • Auto-linking prompt works only if “one prompt per user” remains true; future multi-prompt support would make this ambiguous.
  • Endpoint coverage:
    • settings: create/get/update/delete
    • schedules: add batch/list/get one/update/delete
  • Validation edge cases:
    • start == end (reject)
    • end <= start (reject)
    • adjacency (allow)
    • overlap detection (reject)
    • ownership checks (reject cross-user)
    • DST transitions in common timezones

Based on src/ai-chatbot/ai-chatbot.service.ts and DTO/entity definitions:

  • Runtime validation may be disabled

    • DTOs have class-validator decorators, but if ValidationPipe is not enabled, invalid time strings/timezones can reach date-fns-tz and throw unexpectedly.
  • Manual rollback is not a real transaction

    • Create deletes the chatbot row if schedule save fails.
    • This is not guaranteed to be atomic for all partial-failure scenarios.
  • day stored as float

    • Entity uses a float column but DTO expects int.
    • If non-integers are stored, equality comparisons used for overlap checks can become unreliable.
  • validateTime(...)

    • Combines time parsing (HH:mm), timezone conversion, and overlap logic.
    • Regression-prone and hard to reason about without tests.
  • update(...) orchestration

    • Mixes scalar updates, enhancement upsert, prompt linking, and schedule mutations in one method.
    • Higher chance of unintended side effects on changes.
  • Use TypeORM transactions

    • Wrap chatbot + enhancement + schedules writes in a single transaction for atomicity.
  • Make validation explicit

    • Ensure global ValidationPipe is enabled, or add defensive validation in the service for:
      • timezone format (IANA tz)
      • time format (HH:mm)
      • day range definition (documented and validated)
  • Refactor update(...)

    • Split into private helpers (prompt attachment, enhancement upsert, schedule pipeline) to reduce coupling and improve testability.
  • Clarify “day” semantics

    • Document the intended mapping (0–6 or 1–7) and store as integer.
  • Don’t bypass schedule ownership checks (security boundary).
  • Don’t change overlap rules without coordinating with product and updating tests.
  • Avoid adding more responsibilities to AiChatbotService.update(...) without first splitting it.

  • User-facing AI automation behavior

    • Any runtime that decides whether to respond automatically will likely depend on:
      • AiChatbot.isChatbotOn
      • AiChatbot.isOperatingHour
      • AiOperatingSchedule contents
      • AiChatbot.modelType and prompt
  • Workflow enhancements

    • WorkflowEnhancement is created/updated here and may be read by other modules to influence AI flows.
  • Prompt management

    • The module auto-links GptPrompt if present; changes here can affect which prompt is used at runtime.
  • Schedule overlap validation

    • Small changes to validateTime(...) can silently allow overlaps or incorrectly block valid schedules.
    • Any UI that expects the current overlap rules may start failing with new errors.
  • Enhancement handling

    • is_new_template is coerced into { id: ... } as any during enhancement creation/update.
    • Refactors can break template linkage without obvious type errors.
  • One-per-user constraint

    • DB uniqueness (@Unique(['user'])) is a hard constraint; introducing multiple chatbots per user requires migration + service rewrite + UI/API changes.
  • REST endpoints

    • POST /ai-chatbot with and without operatingSchedule and chatbotEnhancement
    • PATCH /ai-chatbot:
      • scalar updates only
      • enhancement upsert (existing vs new)
      • schedule updates (with id) and creates (without id)
    • Schedule endpoints:
      • add batch schedules
      • update schedule by id with ownership enforcement
      • delete schedule
  • Schedule validation cases

    • start == end (reject)
    • end < start (reject)
    • adjacent ranges (allow)
    • overlaps within a day (reject)
    • update overlaps with other schedules (reject) but excludes its own ID (allow)
    • timezone behavior (DST boundaries)

Derived from implementation details in src/ai-chatbot/ai-chatbot.service.ts and DTO/entity definitions.

  • Runtime DTO validation may be disabled

    • DTOs use class-validator, but if ValidationPipe is not enabled, malformed timezone/times can reach validateTime(...) and cause runtime errors.
  • Create flow assumes schedules exist

    • create(...) uses operatingSchedule.map(...) without guarding against operatingSchedule being undefined.
    • If schedules are omitted (and validation is off), this can throw.
  • Rollback is not transactional

    • On schedule-save failure in create, the service deletes the chatbot row as rollback.
    • This is not fully atomic in all failure modes; DB transactions would be safer.
  • day stored as float

    • Entity column is float but DTO expects int.
    • If non-integers are stored, equality checks (sch.day === day) can behave unexpectedly.
  • validateTime(...) is correctness-critical

    • Combines time parsing assumptions (HH:mm), timezone conversion, and overlap detection.
    • High regression risk; requires focused tests for DST and edge cases.
  • Coupling to “single prompt per user”

    • Update flow auto-links a prompt and includes a comment indicating there is only one prompt per user.
    • If the system later supports multiple prompts, this behaviour becomes ambiguous.
  • Large orchestration method

    • AiChatbotService.update(...) handles scalar updates, prompt linkage, enhancement upsert, and schedule create/update.
    • This increases regression risk and makes safe changes harder.
  • Introduce DB transactions

    • Wrap chatbot + enhancement + schedules writes in a TypeORM transaction for atomicity.
  • Enable or enforce validation

    • Ensure a global ValidationPipe is enabled, or validate in-service for critical fields (timezone, time format).
    • Add explicit time-format and timezone validation to prevent runtime surprises.
  • Normalize schedule schema

    • Store day as an integer and document the accepted range (e.g., 0–6 or 1–7).
    • Consider storing times as minutes-from-midnight or full timestamps to reduce parsing complexity.
  • Refactor update(...)

    • Split into focused helpers:
      • prompt attachment
      • enhancement upsert
      • schedule mutation pipeline
    • Improves testability and reduces change risk.
  • Reduce query repetition

    • For bulk schedule updates, preload schedules once and avoid per-item relation-heavy queries.
  • Do not bypass ownership checks

    • Schedule endpoints enforce user ownership; keep this invariant to avoid data leaks and privilege escalation.
  • Avoid silent schedule-rule changes

    • Schedule overlap rules directly affect customers; coordinate with product and add targeted tests before changes.
  • Avoid expanding update(...) further

    • Add new behavior via extracted helpers or separate services to limit complexity growth.