Risks and Improvements
Change Impact Analysis
Section titled “Change Impact Analysis”What depends on this feature
Section titled “What depends on this feature”- Any system behavior that uses:
AiChatbot.isChatbotOn(global enable/disable)AiChatbot.isOperatingHour+AiOperatingSchedule(time gating)AiChatbot.modelTypeandprompt(runtime model/prompt selection)WorkflowEnhancementlinked to the chatbot (behavior modifiers)
What can break if changed
Section titled “What can break if changed”-
Schedule overlap validation
- Changes to
validateTime(...)(insrc/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)
- Changes to
-
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
AiChatbotis unique per user in the DB.- Any attempt to support multiple bots per user is a breaking change across schema, API, and UI.
What must be tested
Section titled “What must be tested”- 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)
- overlaps on the same
- 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 ifValidationPipeis not enabled, malformed inputs can reach schedule validation and cause runtime errors (invalid timezone/time format).
- DTOs use
-
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.
-
daystored as float- Entity stores
dayas float while DTOs treat it as int. - If non-integers are stored, overlap checks that compare by equality can become unreliable.
- Entity stores
Critical Areas
Section titled “Critical Areas”-
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.
- Mixes time parsing assumptions (
-
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.
Improvements
Section titled “Improvements”-
Introduce TypeORM transactions
- Wrap creation/updating of chatbot + enhancement + schedules in a single transaction for atomicity.
-
Make validation explicit
- Ensure global
ValidationPipeis enabled, or validate critical inputs in service:- timezone must be a valid IANA identifier
startHour/endHourmust matchHH:mm- define and validate allowed
dayrange (e.g., 0–6 or 1–7)
- Ensure global
-
Refactor
update(...)into smaller units- Extract helper methods:
- prompt attachment
- enhancement upsert
- schedule pipeline (load, validate, apply)
- Improves testability and reduces accidental coupling.
- Extract helper methods:
-
Normalize schedule schema
- Store
dayas an integer column. - Consider storing times as minutes-from-midnight to avoid string parsing assumptions.
- Store
-
Performance
- Reduce repeated DB queries when updating many schedules (bulk load schedules and reuse in-memory comparisons).
Warnings and Anti-Patterns
Section titled “Warnings and Anti-Patterns”- 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”Change Impact Analysis
Section titled “Change Impact Analysis”What depends on this feature
Section titled “What depends on this feature”- 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)
- whether the chatbot should run (
- Enhancement-based behavior that reads
WorkflowEnhancementlinked to the chatbot.
What can break if changed
Section titled “What can break if changed”-
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).
- Changing
-
One-per-user invariant
- DB uniqueness on
usermeans any move to multi-chatbot-per-user is a breaking change.
- DB uniqueness on
-
Implicit prompt selection
- Auto-linking prompt works only if “one prompt per user” remains true; future multi-prompt support would make this ambiguous.
What must be tested
Section titled “What must be tested”- 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-validatordecorators, but ifValidationPipeis not enabled, invalid time strings/timezones can reachdate-fns-tzand throw unexpectedly.
- DTOs have
-
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.
-
daystored 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.
Critical Areas
Section titled “Critical Areas”-
validateTime(...)- Combines time parsing (
HH:mm), timezone conversion, and overlap logic. - Regression-prone and hard to reason about without tests.
- Combines time parsing (
-
update(...)orchestration- Mixes scalar updates, enhancement upsert, prompt linking, and schedule mutations in one method.
- Higher chance of unintended side effects on changes.
Improvements
Section titled “Improvements”-
Use TypeORM transactions
- Wrap chatbot + enhancement + schedules writes in a single transaction for atomicity.
-
Make validation explicit
- Ensure global
ValidationPipeis enabled, or add defensive validation in the service for:- timezone format (IANA tz)
- time format (
HH:mm) - day range definition (documented and validated)
- Ensure global
-
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.
Warnings and Anti-Patterns
Section titled “Warnings and Anti-Patterns”- 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.
title: Risks and Improvements
Section titled “title: Risks and Improvements”Change Impact Analysis
Section titled “Change Impact Analysis”What depends on this feature
Section titled “What depends on this feature”-
User-facing AI automation behavior
- Any runtime that decides whether to respond automatically will likely depend on:
AiChatbot.isChatbotOnAiChatbot.isOperatingHourAiOperatingSchedulecontentsAiChatbot.modelTypeandprompt
- Any runtime that decides whether to respond automatically will likely depend on:
-
Workflow enhancements
WorkflowEnhancementis created/updated here and may be read by other modules to influence AI flows.
-
Prompt management
- The module auto-links
GptPromptif present; changes here can affect which prompt is used at runtime.
- The module auto-links
What can break if changed
Section titled “What can break if changed”-
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.
- Small changes to
-
Enhancement handling
is_new_templateis coerced into{ id: ... } as anyduring 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.
- DB uniqueness (
What must be tested
Section titled “What must be tested”-
REST endpoints
POST /ai-chatbotwith and withoutoperatingScheduleandchatbotEnhancementPATCH /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 ifValidationPipeis not enabled, malformedtimezone/times can reachvalidateTime(...)and cause runtime errors.
- DTOs use
-
Create flow assumes schedules exist
create(...)usesoperatingSchedule.map(...)without guarding againstoperatingSchedulebeing 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.
-
daystored as float- Entity column is float but DTO expects int.
- If non-integers are stored, equality checks (
sch.day === day) can behave unexpectedly.
Critical Areas
Section titled “Critical Areas”-
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.
- Combines time parsing assumptions (
-
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.
Improvements
Section titled “Improvements”-
Introduce DB transactions
- Wrap chatbot + enhancement + schedules writes in a TypeORM transaction for atomicity.
-
Enable or enforce validation
- Ensure a global
ValidationPipeis enabled, or validate in-service for critical fields (timezone, time format). - Add explicit time-format and timezone validation to prevent runtime surprises.
- Ensure a global
-
Normalize schedule schema
- Store
dayas 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.
- Store
-
Refactor
update(...)- Split into focused helpers:
- prompt attachment
- enhancement upsert
- schedule mutation pipeline
- Improves testability and reduces change risk.
- Split into focused helpers:
-
Reduce query repetition
- For bulk schedule updates, preload schedules once and avoid per-item relation-heavy queries.
Warnings and Anti-Patterns
Section titled “Warnings and Anti-Patterns”-
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.