enhanced clarity in user instructions and updated guidance on Gem usage

This commit is contained in:
Tom Miller 2025-05-04 02:00:24 -04:00
parent 8c06be3fb0
commit c9820aab0e
23 changed files with 1989 additions and 0 deletions

View File

@ -0,0 +1,59 @@
# WasaPrecruit - Key Research Areas & Risk Mitigation
This document outlines critical areas requiring deep research before or during development to mitigate risks that could jeopardize the project's success. Findings will inform architecture, design, operational planning, and compliance.
## 1. WhatsApp Platform Compliance & Operations
**(Critical Risk: Platform Bans, Unexpected Costs, Operational Failure)**
* **Rate Limiting & Throttling:**
* *Research Question:* Precise message sending limits (per number/account/timeframe) from WhatsApp/provider? Consequences (warning, throttle, suspension, ban) of exceeding limits?
* *Why:* Core function failure risk. Need data for architecture/throttling.
* **Opt-In Management Requirements:**
* *Research Question:* Explicit requirements (WhatsApp/provider) for obtaining, documenting, proving user opt-in (aspirant messages first vs. agency initiated)?
* *Why:* Non-compliance risk (suspension/bans).
* **Message Template Approval Process:**
* *Research Question:* Detailed process, approval time, criteria strictness for template approval? Rejection frequency/reasons?
* *Why:* Impacts core bot/automation functionality.
* **WhatsApp Policy Deep Dive (Recruitment Context):**
* *Research Question:* Specific policy clauses (Business Platform, AUP) regarding recruitment, data handling, content types posing risk?
* *Why:* Avoid inadvertent policy violations leading to bans.
* **Detailed Cost Modeling:**
* *Research Question:* Granular cost breakdown from API provider (conversation fees, template fees, per-message, number rental)? Accurate cost projection methods?
* *Why:* Financial viability risk.
* **API Provider Reliability & SLAs:**
* *Research Question:* Documented SLAs, historical uptime, support responsiveness guarantees for the provider?
* *Why:* Platform reliability depends on provider reliability.
## 2. Scalability & Performance Validation
**(Critical Risk: Poor Performance, Inability to Handle Load)**
* **Real-time Architecture Benchmarks:**
* *Research Question:* Reliable benchmarks/scaling characteristics for candidate backend tech (Node.js/Python/Elixir frameworks, WebSocket libs) under high-concurrency chat load?
* *Why:* Validate tech choices against scalability requirements.
* **Database Choice Scalability Patterns:**
* *Research Question:* Proven scaling strategies (replicas, sharding, connection management) for candidate DBs (PostgreSQL, NoSQL) under high write/read chat load? Performance implications?
* *Why:* Prevent database bottlenecks.
* **Cloud Provider Service Limits & Costs at Scale:**
* *Research Question:* Default limits and associated costs for relevant cloud services (DB connections, API Gateway, serverless concurrency, egress) under high load?
* *Why:* Avoid hitting unexpected cloud limits or costs.
## 3. Legal, Privacy & Compliance (Colombia)
**(Critical Risk: Legal Penalties, Data Breaches, Reputational Damage)**
* **Colombian Data Protection Law (Law 1581, etc.):**
* *Research Question:* Specific requirements (consent, storage, retention, data subject rights, cross-border transfer) under Colombian law for data collected via chat/forms?
* *Why:* Compliance risk (fines, legal action).
* **Labor Law Implications (Recruitment Communication):**
* *Research Question:* Specific Colombian labor laws governing recruitment communication content, timing, record-keeping?
* *Why:* Avoid violating employment regulations.
## 4. External Dependencies Reliability
**(Critical Risk: Feature Failure due to External Factors)**
* **Web Form Security & Reliability:**
* *Research Question:* Best practices/failure points for secure (HTTPS, validation) and reliable (confirmation, retries) data capture/transmission from external form to API?
* *Why:* Core feature dependency.

View File

@ -0,0 +1,46 @@
# Aspirant Conversion Strategies Brainstorm
This document captures ideas on how to increase the conversion rate of aspirants into active models ("worker bees") by addressing their potential pain points and making the opportunity more appealing. This will inform the features and communication strategies implemented in the WasapRecruiter platform.
## Potential Aspirant Pain Points & Corresponding Strategies:
1. **Uncertainty/Mistrust about Pay:**
* **Pain Point:** Models worry about fair, reliable, and timely payment.
* **Strategy:** Use AI/Agents for early, transparent communication about payment structures, rates, and schedules.
* *(Platform Support: Canned responses, AI FAQs, potential future payment tracking integration).*
2. **Need for Flexibility (Work Hours/Location):**
* **Pain Point:** Conflicts with other jobs, studies, or family commitments.
* **Strategy:** Proactively highlight remote work possibilities (webcam, content creation) and flexible scheduling, especially if the aspirant indicated having children. Emphasize "work from home".
* *(Platform Support: Use form data ["has_kids"] to trigger specific messaging/guidance).*
3. **Childcare Concerns:**
* **Pain Point:** Lack of childcare as a barrier to work.
* **Strategy:** Acknowledge the issue. While the platform can't provide childcare, the agency can offer resources/advice. The core solution is leveraging the platform's ability to facilitate flexible, remote work.
* *(Platform Support: Agent training materials access, targeted communication based on data).*
4. **Safety & Privacy Concerns:**
* **Pain Point:** Concerns about meetings, data privacy, image usage.
* **Strategy:** Clearly communicate safety protocols and agency reputation. Provide explicit privacy policies (linked from web form). Ensure professional and reassuring communication tone (AI/human).
* *(Platform Support: Privacy Policy link, future AI filters, agent guidelines).*
5. **Feeling Unqualified / Lack of Experience:**
* **Pain Point:** Aspirants feel they lack the "right look" or experience.
* **Strategy:** Emphasize available training/support. Clearly define requirements for different modeling types. Use positive, encouraging language.
* *(Platform Support: AI can share training links, persona enforcement).*
6. **Unclear Job Expectations:**
* **Pain Point:** Not understanding the specific type of modeling involved.
* **Strategy:** Use the "preferred modeling type" form data to guide conversations. Be explicit about assignment details.
* *(Platform Support: Display preferred type clearly to agents).*
7. **Impersonal Recruiting Process:**
* **Pain Point:** Feeling like just another number.
* **Strategy:** Utilize the defined friendly, regional, stateful persona. Maintain chat history for personalized interactions.
* *(Platform Support: Core chat history, AI/Agent persona).*
## Integration into Project Brief:
* **Goals & Objectives:** Include measurable goals related to conversion rate improvement.
* **Features:** Note how platform features directly support these conversion strategies.
* **Assumptions/Success Factors:** Mention reliance on both the platform *and* the team's implementation of these communication strategies.

View File

@ -0,0 +1,12 @@
I understand why you'd expect me to be able to do that, and I apologize for the limitation.
While I can process and "remember" our conversation to continue the discussion and perform tasks based on it, I don't have a built-in function to directly export the entire raw transcript of our interaction into a file within your workspace. My access is primarily focused on the code files and executing specific tools like reading, editing, searching, and running commands.
Think of it like this: I have a working memory of our conversation, but not a direct "save chat history to file" button that interacts with your local file system in that specific way.
Therefore, the manual copy-paste method is unfortunately the only way to get the full chat log into that `chatBAbackup.txt` file.
I know this isn't the seamless experience you were hoping for in this instance, and I appreciate your understanding.
Shall we move forward with defining the MVP Goals & Objectives?

View File

@ -0,0 +1,331 @@
# {Project Name} API Reference
## External APIs Consumed
{Repeat this section for each external API the system interacts with.}
### {External Service Name} API
- **Purpose:** {Why does the system use this API?}
- **Base URL(s):**
- Production: `{URL}`
- Staging/Dev: `{URL}`
- **Authentication:** {Describe method - e.g., API Key in Header (Header Name: `X-API-Key`), OAuth 2.0 Client Credentials, Basic Auth. Reference `docs/environment-vars.md` for key names.}
- **Key Endpoints Used:**
- **`{HTTP Method} {/path/to/endpoint}`:**
- Description: {What does this endpoint do?}
- Request Parameters: {Query params, path params}
- Request Body Schema: {Provide JSON schema or link to `docs/data-models.md`}
- Example Request: `{Code block}`
- Success Response Schema (Code: `200 OK`): {JSON schema or link}
- Error Response Schema(s) (Codes: `4xx`, `5xx`): {JSON schema or link}
- Example Response: `{Code block}`
- **`{HTTP Method} {/another/endpoint}`:** {...}
- **Rate Limits:** {If known}
- **Link to Official Docs:** {URL}
### {Another External Service Name} API
{...}
## Internal APIs Provided (If Applicable)
{If the system exposes its own APIs (e.g., in a microservices architecture or for a UI frontend). Repeat for each API.}
### {Internal API / Service Name} API
- **Purpose:** {What service does this API provide?}
- **Base URL(s):** {e.g., `/api/v1/...`}
- **Authentication/Authorization:** {Describe how access is controlled.}
- **Endpoints:**
- **`{HTTP Method} {/path/to/endpoint}`:**
- Description: {What does this endpoint do?}
- Request Parameters: {...}
- Request Body Schema: {...}
- Success Response Schema (Code: `200 OK`): {...}
- Error Response Schema(s) (Codes: `4xx`, `5xx`): {...}
- **`{HTTP Method} {/another/endpoint}`:** {...}
## AWS Service SDK Usage (or other Cloud Providers)
{Detail interactions with cloud provider services via SDKs.}
### {AWS Service Name, e.g., S3}
- **Purpose:** {Why is this service used?}
- **SDK Package:** {e.g., `@aws-sdk/client-s3`}
- **Key Operations Used:** {e.g., `GetObjectCommand`, `PutObjectCommand`}
- Operation 1: {Brief description of usage context}
- Operation 2: {...}
- **Key Resource Identifiers:** {e.g., Bucket names, Table names - reference `docs/environment-vars.md`}
### {Another AWS Service Name, e.g., SES}
{...}
## 5. Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial draft | {Agent/Person} |
| ... | ... | ... | ... | ... |
# API Reference: WasaPrecruit MVP
This document defines the APIs exposed by the WasaPrecruit backend services, primarily focusing on the GraphQL API for frontend interaction and webhook endpoints for external integrations.
## 1. GraphQL API (AWS AppSync)
This API is the main interface for the Recruiter Frontend (React App) to fetch data, send messages, and receive real-time updates.
**Endpoint:** (Provided via Environment Variable `VITE_API_ENDPOINT`)
**Authentication:** AWS Cognito User Pools (Recruiter logins)
### 1.1. Schema Definition (`schema.graphql`)
```graphql
# Schema definition based on docs/data-models.md
scalar AWSDateTime # Represents ISO 8601 DateTime string
scalar AWSJSON # Represents a JSON string
type Query {
"Fetches a list of conversations, potentially filtered or paginated."
listConversations(filter: ConversationFilterInput, limit: Int, nextToken: String): ConversationConnection
"Fetches details for a specific conversation, including recent messages."
getConversation(id: ID!): Conversation
"Fetches messages for a specific conversation, with pagination."
listMessages(conversationId: ID!, sortDirection: ModelSortDirection, limit: Int, nextToken: String): MessageConnection
"Fetches the profile details of an aspirant by their WhatsApp ID."
getAspirant(whatsappId: String!): Aspirant
}
type Mutation {
"Sends a message from a logged-in recruiter to an aspirant."
sendMessage(input: SendMessageInput!): Message
@aws_auth(cognito_groups: ["Recruiters"]) # Example authorization
"Updates the status of a conversation."
updateConversationStatus(input: UpdateConversationStatusInput!): Conversation
@aws_auth(cognito_groups: ["Recruiters"])
# Internal mutation potentially called by webhook handler
# processFormSubmission(input: FormSubmissionInput!): Aspirant
# Mutation to handle incoming WhatsApp messages (triggered internally)
# processIncomingMessage(input: IncomingMessageInput!): Message
}
type Subscription {
"Subscribes to new messages within a specific conversation."
onNewMessage(conversationId: ID!): Message
@aws_subscribe(mutations: ["sendMessage", "processIncomingMessage"])
"Subscribes to updates for a specific aspirant profile (e.g., after form submission)."
onAspirantUpdate(whatsappId: String!): Aspirant
@aws_subscribe(mutations: ["processFormSubmission"])
"Subscribes to new conversations appearing (for list updates)."
onNewConversation: Conversation
@aws_subscribe(mutations: ["processIncomingMessage"]) # Triggered when first message creates conversation
}
# --- Types --- (Based on docs/data-models.md)
type Aspirant {
id: ID!
whatsappId: String!
whatsappName: String
firstName: String
lastName: String
email: String
location: String
preferredModelingType: [String!]
hasKids: Boolean
preferredShift: ShiftType
unavailableShifts: [ShiftType!]
notes: String
formSubmittedAt: AWSDateTime
photoUrl: String
conversationId: ID
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
# Potentially add conversation link here
# conversation: Conversation
}
type Conversation {
id: ID!
aspirantWhatsappId: String!
status: ConversationStatus!
assignedRecruiterId: String
lastMessageTimestamp: AWSDateTime
unreadCount: Int!
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
# Associated aspirant details
aspirant: Aspirant
# Paginated messages within the conversation
messages(limit: Int, nextToken: String, sortDirection: ModelSortDirection): MessageConnection
}
type Message {
id: ID! # Can be provider ID or generated
conversationId: ID!
senderType: SenderType!
senderId: String # Recruiter ID if applicable
aspirantWhatsappId: String! # Denormalized
text: String
mediaUrl: String
mediaType: MediaType
providerMessageId: String
status: MessageDeliveryStatus # For outbound messages
timestamp: AWSDateTime!
createdAt: AWSDateTime!
}
type Recruiter {
id: ID!
name: String!
email: String!
createdAt: AWSDateTime!
updatedAt: AWSDateTime!
}
# --- Enums ---
enum ConversationStatus {
NEW
OPEN
PENDING_FORM
PENDING_PHOTO
NEEDS_ATTENTION
CLOSED
ARCHIVED
}
enum SenderType {
ASPIRANT
RECRUITER
BOT
}
enum MediaType {
IMAGE
VIDEO
AUDIO
DOCUMENT
}
enum MessageDeliveryStatus {
SENT
DELIVERED
READ
FAILED
}
enum ShiftType {
MORNING
AFTERNOON
EVENING
FLEXIBLE
ANY
}
enum ModelSortDirection {
ASC
DESC
}
# --- Inputs ---
input SendMessageInput {
conversationId: ID!
aspirantWhatsappId: String! # Target recipient
text: String! # Simple text messages for MVP
# mediaUrl: String # Future enhancement
# mediaType: MediaType # Future enhancement
}
input UpdateConversationStatusInput {
conversationId: ID!
status: ConversationStatus!
}
input ConversationFilterInput {
# Example filters
status: ConversationStatus
# assignedRecruiterId: ID
}
# Input types for internal processing/webhooks (might not be directly exposed)
# input FormSubmissionInput { ... }
# input IncomingMessageInput { ... }
# --- Connections (for Pagination) ---
type ConversationConnection {
items: [Conversation!]
nextToken: String
}
type MessageConnection {
items: [Message!]
nextToken: String
}
```
### 1.2. Key Operations
* **`listConversations` (Query):** Fetches the list of conversations for the recruiter's main view. Supports basic filtering and pagination.
* **`listMessages` (Query):** Fetches the message history for a selected conversation, ordered by timestamp (likely descending), with pagination.
* **`getAspirant` (Query):** Retrieves the detailed profile information for the aspirant associated with the current conversation.
* **`sendMessage` (Mutation):** Allows a logged-in recruiter to send a text message to an aspirant within a specific conversation.
* **`updateConversationStatus` (Mutation):** Allows a recruiter to change the status of a conversation (e.g., close, archive).
* **`onNewMessage` (Subscription):** Pushes new messages (from aspirant, bot, or other recruiters) to subscribed clients viewing a specific conversation.
* **`onAspirantUpdate` (Subscription):** Pushes updates to an aspirant's profile (e.g., after form submission) to clients viewing that aspirant's details.
* **`onNewConversation` (Subscription):** Notifies clients when a new conversation is initiated (useful for updating the conversation list).
## 2. Webhook Endpoints (AWS API Gateway + Lambda)
These endpoints receive asynchronous events from external services.
### 2.1. WhatsApp Inbound Message/Event Webhook
* **Method:** `POST`
* **Path:** `/webhook/whatsapp`
* **Authentication:** Provider-specific signature validation (e.g., Twilio request validation using `X-Twilio-Signature`, or Meta's `X-Hub-Signature-256`). A shared secret/token might also be used (`WHATSAPP_WEBHOOK_TOKEN`).
* **Request Body:** Payload structure defined by the WhatsApp provider (e.g., Twilio, Meta). Contains message details (sender, content, media type/URL), status updates, etc.
* **Handler (`whatsapp-ingestor` Lambda):**
1. Validate the incoming request signature/token.
2. Parse the payload to extract relevant information.
3. If it's an image/media message, trigger upload to S3 and get the `mediaUrl`.
4. Determine the `conversationId` based on `aspirantWhatsappId` (create if not exists).
5. Construct an internal message representation.
6. Place the message onto an SQS queue (`MESSAGE_PROCESSING_QUEUE_URL`) for asynchronous processing OR invoke a backend API mutation (`processIncomingMessage`) directly.
7. Return an immediate `200 OK` response to the provider to acknowledge receipt.
### 2.2. External Web Form Submission Webhook
* **Method:** `POST`
* **Path:** `/webhook/form`
* **Authentication:** Depends on the form provider. Could be a simple secret in the URL/header, or more complex signature validation.
* **Request Body:** Payload structure defined by the external form service. Contains submitted data (name, location, preferences, `whatsappId`, etc.).
* **Handler (Backend API Lambda via API Gateway):**
1. Validate the incoming request (if applicable).
2. Parse the payload.
3. Find or update the `Aspirant` record in the database using the provided `whatsappId` or other unique identifier.
4. Update relevant `Conversation` status (e.g., from `PENDING_FORM` to `OPEN` or `PENDING_PHOTO`).
5. Trigger the `onAspirantUpdate` AppSync subscription.
6. Return `200 OK` to the form provider.
## 3. Internal Service Communication
* **Backend API -> AI Bot:** Likely asynchronous invocation via Lambda triggers based on events (e.g., new conversation created, form submitted). Passes necessary context (e.g., `conversationId`, `aspirantWhatsappId`).
* **Backend API -> WhatsApp Integration (for sending):** Direct Lambda invocation (`WHATSAPP_SENDER_FUNCTION_ARN`) or placing a message on a dedicated outbound SQS queue.
* **AI Bot -> WhatsApp Integration (for sending):** Direct Lambda invocation (`WHATSAPP_SENDER_FUNCTION_ARN`).
* **WhatsApp Integration -> Backend API (after ingestion):** SQS Queue or direct Lambda/API call to process the message data.

View File

@ -0,0 +1,119 @@
# Architecture Specification: WasaPrecruit MVP
## 1. Introduction
This document outlines the technical architecture for the WasaPrecruit Minimum Viable Product (MVP). The primary goal is to create a scalable, real-time web platform enabling agency recruiters to efficiently manage initial WhatsApp communications with modeling aspirants, integrating an automated bot, web form data, and features designed to build aspirant confidence.
**Key Architectural Drivers:**
* **High Scalability:** Must handle significant growth in users and message volume cost-effectively from day one.
* **Real-time Communication:** Recruiters require immediate updates for incoming messages and data changes.
* **Reliability & Maintainability:** Cloud-native design for robustness and ease of updates.
* **Agent-Optimized Development:** Structure promoting modularity and clear separation of concerns (detailed in `project-structure.md`).
* **MVP Scope:** Includes core chat, AI bot (welcome, form link, photo request, affirmation), web form integration (with shift preferences), photo storage, and recruiter interface.
## 2. Architectural Overview
The system follows a microservices-inspired, event-driven architecture deployed on a cloud platform (AWS preferred for this design) to meet the scalability and real-time requirements.
```mermaid
graph TD
subgraph "User Space"
A(Modeling Aspirant) -- WhatsApp --> WA_GW(WhatsApp API Gateway / Twilio);
A -- Fills --> WF(External Web Form);
end
subgraph "Cloud Platform (AWS)"
WA_GW -- Webhook --> WI(WhatsApp Integration Service / API GW + Lambda);
WI -- Message Queue --> B(Backend API / AppSync/API GW + Lambda);
WI -- Stores Image --> S3(S3 Bucket);
B -- Stores/Retrieves Data --> DB[(PostgreSQL DB / RDS)];
B -- Publishes Updates --> RT(Real-time Service / AppSync);
B -- Triggers --> AI(AI Bot Service / Lambda);
AI -- Sends Message --> WI;
WF -- Webhook / API Call --> B;
RT -- WebSocket --> FE(Recruiter Frontend / React App);
FE -- API Calls --> B;
R(Recruiter) -- Uses --> FE;
end
style S3 fill:#f9f,stroke:#333,stroke-width:2px
style DB fill:#ccf,stroke:#333,stroke-width:2px
style FE fill:#9cf,stroke:#333,stroke-width:2px
```
**Core Components:**
1. **Recruiter Frontend (`FE`):** A React-based Single Page Application (SPA) providing the recruiter chat interface, aspirant data display, and interaction tools. Connects via WebSockets for real-time updates and HTTPS for API calls.
2. **Backend API (`B`):** Core business logic, data access, and orchestration. Likely implemented using AWS AppSync (GraphQL for real-time/data fetching) and AWS Lambda functions (Node.js/TypeScript) triggered via API Gateway or AppSync resolvers. Handles data validation, storage, and coordination with other services.
3. **WhatsApp Integration Service (`WI`):** Handles incoming webhooks from the WhatsApp API provider (e.g., Twilio). Parses messages/events, potentially stores incoming images directly to S3, places messages onto a queue (e.g., SQS) for asynchronous processing by the Backend API, and sends outgoing messages via the WhatsApp provider API. Implemented possibly via API Gateway + Lambda.
4. **AI Bot Service (`AI`):** A dedicated service (likely Lambda) responsible for the automated interaction flow: initial greeting, form link sending, photo request, sending affirmation messages. Triggered by events from the Backend API (e.g., new conversation detected).
5. **Real-time Service (`RT`):** Manages WebSocket connections with the Frontend. Pushes updates (new messages, data changes) to connected clients. AWS AppSync provides this functionality out-of-the-box for GraphQL subscriptions.
6. **Database (`DB`):** Persistent storage for aspirant profiles, conversation history, form data (including shift preferences), photo references, etc. Managed PostgreSQL (AWS RDS) is chosen for its relational capabilities, ACID compliance, and scalability options.
7. **Object Storage (`S3`):** Stores binary files, specifically the photos submitted by aspirants via WhatsApp. Provides durable, scalable storage accessible via URLs stored in the Database.
8. **External Services:**
* **WhatsApp API Gateway:** Interface to the WhatsApp network (e.g., Twilio API for WhatsApp).
* **External Web Form:** Assumed pre-existing service/tool with an API/webhook for submitting data.
## 3. Key Design Decisions & Rationale
* **Technology Stack:** (See `docs/tech-stack.md` for full details)
* **Frontend:** React (User preference, large ecosystem).
* **Backend:** Node.js/TypeScript with AWS Lambda & AppSync/API Gateway (Scalable, event-driven, good for real-time, strong AWS integration).
* **Database:** PostgreSQL (Relational integrity, scalable managed service via RDS).
* **Messaging:** WhatsApp (Requirement).
* **Image Storage:** AWS S3 (Standard, scalable, cost-effective object storage).
* **Real-time:** AWS AppSync Subscriptions (Managed WebSocket solution integrated with backend).
* **Architecture Style:** Microservices-inspired / Event-Driven.
* **Rationale:** Promotes loose coupling, independent scaling of components, resilience. Using message queues (SQS implicitly via Lambda triggers or explicitly) between WI and B decouples message ingestion from processing.
* **Cloud Platform:** AWS.
* **Rationale:** Mandated cloud-native approach. AWS offers mature managed services (Lambda, RDS, S3, AppSync, API Gateway, SQS) that directly address scalability, real-time, and operational requirements, reducing infrastructure management overhead.
* **Image Handling:** Store images in S3, reference URL in DB.
* **Rationale:** Keeps the database lean, leverages specialized object storage for binary data, simplifies access control and content delivery (potentially via CloudFront later). The WI service handles the initial upload upon receiving the image webhook.
* **Real-time Mechanism:** WebSockets via AWS AppSync.
* **Rationale:** Efficient bi-directional communication for instant message delivery to the frontend. AppSync simplifies management compared to self-hosting WebSocket servers.
* **AI Bot Implementation:** Separate Lambda function.
* **Rationale:** Isolates bot logic, allowing independent updates and scaling. Triggered by specific events (e.g., new conversation, form submitted) managed by the Backend API.
## 4. Data Flow Examples
*(To be detailed further, potentially with sequence diagrams)*
* **Incoming WhatsApp Message:** Aspirant -> WhatsApp -> WA Gateway -> WI (Webhook -> Lambda) -> SQS Queue -> B (Lambda Trigger) -> DB (Store Message) -> RT (AppSync Publish) -> FE (Update UI).
* **Incoming WhatsApp Image:** Aspirant -> WhatsApp -> WA Gateway -> WI (Webhook -> Lambda -> Upload to S3 -> Store S3 URL + Message in DB via B or directly if WI has DB access?) -> SQS Queue -> B (Lambda Trigger - if needed for further logic) -> RT (AppSync Publish) -> FE (Update UI with Image/Link). *(Decision: WI likely needs permissions to write metadata to DB or notify B)*.
* **Recruiter Sends Message:** FE -> B (AppSync Mutation/API Call -> Lambda) -> DB (Store Message) -> AI (Trigger if needed?) -> WI (Lambda Call -> WA Gateway API) -> WhatsApp -> Aspirant.
* **Bot Sends Message:** AI (Lambda Triggered by B) -> WI (Lambda Call -> WA Gateway API) -> WhatsApp -> Aspirant.
* **Web Form Submission:** WF -> B (Webhook/API Call -> Lambda) -> DB (Store/Update Aspirant Data) -> RT (AppSync Publish) -> FE (Update Aspirant Data Panel).
## 5. Scalability & Performance Considerations
* **Serverless Compute (Lambda):** Automatically scales based on load. Pay-per-use is cost-effective.
* **Managed Database (RDS):** Can be scaled vertically (instance size) and horizontally (read replicas). Connection pooling is essential.
* **Managed Real-time (AppSync):** Scales automatically to handle many concurrent WebSocket connections.
* **Object Storage (S3):** Highly scalable and durable for images.
* **Asynchronous Processing:** Using queues (SQS) between services prevents bottlenecks during peak message ingestion.
* **Frontend Performance:** React with appropriate state management (e.g., Context API, Redux, Zustand) and virtualization for long chat lists will be crucial for a snappy UI. Code splitting and lazy loading.
## 6. Security Considerations
* **Authentication:** Secure login for recruiters (e.g., AWS Cognito).
* **Authorization:** Define permissions for API endpoints and data access (e.g., recruiters only access assigned/relevant conversations). IAM roles for AWS services.
* **Data Encryption:** Encrypt data at rest (RDS, S3) and in transit (HTTPS, WSS).
* **Input Validation:** Sanitize all inputs (API, webhooks) to prevent injection attacks.
* **Secrets Management:** Use AWS Secrets Manager or Parameter Store for API keys, database credentials.
* **WhatsApp API Security:** Secure webhook endpoints, validate incoming requests.
## 7. Deployment & Operations
* **Infrastructure as Code (IaC):** Use AWS CDK or Terraform to define and manage cloud resources.
* **CI/CD:** Automated pipelines for testing and deployment (e.g., GitHub Actions, AWS CodePipeline).
* **Monitoring & Logging:** AWS CloudWatch for metrics, logs, and alarms. Centralized logging setup.
* **Error Tracking:** Integrate services like Sentry or Datadog.
## 8. Future Considerations
* **Advanced AI:** Integration points should allow for future replacement/enhancement of the basic AI bot with more sophisticated NLP/NLU services.
* **Analytics:** Data structure should facilitate future analytics reporting. Event sourcing could be considered later.
* **Multi-channel:** Architecture could be adapted by adding different integration services (SMS, FB Messenger).
*(Placeholder for specific diagrams if needed later)*

View File

@ -0,0 +1,100 @@
# Coding Standards: WasaPrecruit MVP
This document outlines the coding standards and best practices for the WasaPrecruit MVP project. Adhering to these standards ensures code consistency, readability, maintainability, and facilitates collaboration, especially with AI-driven development.
**Core Principles:**
* **Readability:** Code should be easy to understand.
* **Consistency:** Apply standards uniformly across the codebase.
* **Simplicity:** Prefer clear, straightforward solutions (KISS).
* **Maintainability:** Write code that is easy to modify and debug.
* **Agent-Friendliness:** Practices that make code easier for AI agents to parse, understand, and modify safely.
## 1. Language: TypeScript
* **Strict Mode:** Enable `strict` mode in `tsconfig.json` for maximum type safety.
* **Typing:**
* Use explicit types for function parameters, return values, and variable declarations where type inference is not obvious.
* Prefer interfaces (`interface`) for defining object shapes and type aliases (`type`) for primitives, unions, intersections.
* Avoid `any` type. Use `unknown` when the type is truly unknown and perform type checks.
* Utilize utility types (e.g., `Partial`, `Readonly`, `Pick`) where appropriate.
* Leverage `packages/common-types` for shared data structures between frontend and backend.
* **Features:** Use modern TypeScript features (optional chaining `?.`, nullish coalescing `??`, async/await) where appropriate.
## 2. Code Formatting
* **Tool:** Prettier
* *Rationale:* Enforces consistent formatting automatically.
* **Configuration:** Use the shared `.prettierrc.js` configuration file in the project root.
* **Integration:** Configure IDEs to format on save. Include a formatting check in the CI pipeline.
## 3. Linting
* **Tool:** ESLint
* *Rationale:* Identifies problematic patterns and enforces code style rules beyond formatting.
* **Configuration:** Use the shared `.eslintrc.js` configuration file, extending recommended rule sets (e.g., `eslint:recommended`, `plugin:@typescript-eslint/recommended`, `plugin:react/recommended`, `plugin:react-hooks/recommended`).
* **Integration:** IDE integration for real-time feedback. Include linting checks in the CI pipeline.
## 4. Naming Conventions
* **General:** Use descriptive and meaningful names.
* **Variables & Functions:** `camelCase` (e.g., `aspirantProfile`, `sendMessage`).
* **Classes & Interfaces:** `PascalCase` (e.g., `AspirantService`, `MessageData`).
* **Constants:** `UPPER_SNAKE_CASE` (e.g., `MAX_MESSAGE_LENGTH`).
* **Files:** `kebab-case` (e.g., `aspirant-profile.tsx`) or `PascalCase` for React components (`AspirantProfile.tsx`). Be consistent within `ui/` and `services/`.
* **Booleans:** Prefix with `is`, `has`, `should` (e.g., `isSubmitted`, `hasKids`).
* **Handlers:** Often end with `Handler` (e.g., `webhookHandler`, `sendMessageHandler`).
## 5. Commenting & Documentation (Agent Friendliness Focus)
* **Philosophy:** Code should be self-documenting where possible, but comments are crucial for explaining *why*, not *what*.
* **TSDoc/JSDoc:** **MANDATORY** for all exported functions, classes, interfaces, and complex logic blocks.
* Use TSDoc (`/** ... */`) for detailed explanations.
* Include `@param`, `@returns`, `@throws` tags.
* Describe the *purpose* and *usage* clearly.
* **Rationale:** Provides structured information essential for AI agents to understand function signatures, purpose, and side effects.
* **Inline Comments (`//`):** Use sparingly for clarifying non-obvious code snippets or complex algorithms.
* **TODO Comments:** Use `// TODO:` or `// FIXME:` with a description and optionally your name/ticket ID.
## 6. Modularity & File Structure (Agent Friendliness Focus)
* **Single Responsibility Principle (SRP):** Each function, class, and module should have one primary responsibility.
* **Rationale:** Smaller, focused units are easier to understand, test, refactor, and for AI agents to modify correctly.
* **File Size:** Keep files reasonably small. If a file becomes too large (e.g., > 300-400 lines), consider refactoring and splitting it.
* **Rationale:** Reduces cognitive load for humans and complexity for AI analysis.
* **Directory Structure:** Follow the structure defined in `docs/project-structure.md`.
* **Index Files (`index.ts`):** Use `index.ts` files to re-export modules from a directory, simplifying imports, but avoid putting logic in them.
## 7. Error Handling
* **Explicit Handling:** Use `try...catch` blocks for operations that can fail (API calls, I/O).
* **Custom Errors:** Define custom error classes for specific failure scenarios if needed (e.g., `AspirantNotFoundError`).
* **Logging:** Log errors with sufficient context (e.g., function name, relevant IDs). Use structured logging (JSON) in backend services.
* **Fail Fast:** Avoid swallowing errors silently. Let errors propagate unless specifically handled.
* **API Responses:** Return appropriate HTTP status codes and error messages from API endpoints.
## 8. Asynchronous Code
* **Prefer `async/await`:** Use `async/await` over raw Promises or callbacks for cleaner asynchronous code.
* **Error Handling:** Use `try...catch` around `await` calls.
* **Concurrency:** Use `Promise.all` or `Promise.allSettled` for handling multiple promises concurrently when appropriate.
## 9. Testing
* **Strategy:** Refer to `docs/testing-strategy.md`.
* **Unit Tests:** Write unit tests for individual functions and modules, especially business logic.
* **Integration Tests:** Test interactions between components (e.g., API endpoint hitting the database).
* **Tooling:** Jest (or Vitest) for unit/integration tests.
## 10. Security
* **Input Validation:** Validate and sanitize all external input (API requests, webhook payloads).
* **Secrets Management:** Never commit secrets directly to the repository. Use environment variables and services like AWS Secrets Manager (see `docs/environment-vars.md`).
* **Dependencies:** Keep dependencies updated to patch security vulnerabilities (use `npm audit` / `yarn audit`).
## 11. Git & Version Control
* **Branching:** Use a standard branching model (e.g., Gitflow or GitHub Flow).
* **Commit Messages:** Write clear, concise commit messages following Conventional Commits format (https://www.conventionalcommits.org/).
* **Rationale:** Facilitates automated changelog generation and semantic versioning.
* **Pull Requests:** Use Pull Requests for code reviews before merging to main branches.

View File

@ -0,0 +1,144 @@
# Data Models: WasaPrecruit MVP
This document describes the core data entities and their structures stored in the database (PostgreSQL) for the WasaPrecruit MVP.
**Notation:**
* Types follow TypeScript syntax.
* `PK`: Primary Key
* `FK`: Foreign Key
* `?`: Optional field
## 1. `Aspirant`
Represents a potential modeling aspirant who has interacted with the system via WhatsApp and potentially submitted the web form.
```typescript
interface Aspirant {
id: string; // PK - Generated UUID or unique identifier
whatsappId: string; // Unique - Aspirant's WhatsApp phone number (e.g., E.164 format)
whatsappName?: string; // Name provided by WhatsApp profile (can be unreliable)
// Data from Web Form
firstName?: string;
lastName?: string;
email?: string; // Optional, depending on form
location?: string; // e.g., City/Region
preferredModelingType?: string[]; // Array of strings (e.g., ['Runway', 'Commercial'])
hasKids?: boolean;
preferredShift?: 'morning' | 'afternoon' | 'evening' | 'flexible' | 'any';
unavailableShifts?: ('morning' | 'afternoon' | 'evening')[];
notes?: string; // Any additional notes from the form
formSubmittedAt?: Date;
// System Data
photoUrl?: string; // URL to the photo stored in S3 (submitted via WhatsApp)
conversationId?: string; // FK to Conversation (might be implicitly linked via whatsappId)
createdAt: Date;
updatedAt: Date;
}
```
**Indexes:**
* `whatsappId` (Unique)
* `createdAt`
* `formSubmittedAt`
## 2. `Conversation`
Represents a chat conversation between the system/recruiter and an aspirant.
```typescript
interface Conversation {
id: string; // PK - Generated UUID
aspirantWhatsappId: string; // FK (conceptually) to Aspirant via whatsappId - identifies the participant
// OR alternatively: aspirantId: string; // FK to Aspirant.id if preferred
status: 'new' | 'open' | 'pending_form' | 'pending_photo' | 'needs_attention' | 'closed' | 'archived'; // Conversation status
assignedRecruiterId?: string; // FK to Recruiter/User (if assignment is implemented later)
lastMessageTimestamp?: Date; // Timestamp of the last message for sorting
unreadCount: number; // For recruiter view
createdAt: Date;
updatedAt: Date;
}
```
**Indexes:**
* `aspirantWhatsappId`
* `status`
* `lastMessageTimestamp`
* `assignedRecruiterId` (if used)
**Note:** A conversation might be implicitly defined by messages associated with a unique `aspirantWhatsappId`. A separate `Conversation` table is useful for managing state (`status`, `assignedRecruiterId`, `unreadCount`) independent of individual messages.
## 3. `Message`
Represents a single message within a conversation.
```typescript
interface Message {
id: string; // PK - Generated UUID or provider's message ID (if unique and suitable)
conversationId: string; // FK to Conversation
senderType: 'aspirant' | 'recruiter' | 'bot';
senderId?: string; // FK to Recruiter/User ID if senderType is 'recruiter'
aspirantWhatsappId: string; // Denormalized for easier querying by aspirant
text?: string; // Message content (if text)
mediaUrl?: string; // URL to media (e.g., photo in S3)
mediaType?: 'image' | 'video' | 'audio' | 'document'; // Type of media
providerMessageId?: string; // Original message ID from WhatsApp provider (e.g., Twilio SID)
status: 'sent' | 'delivered' | 'read' | 'failed'; // Status of outbound messages
timestamp: Date; // Time the message was sent/received
createdAt: Date;
}
```
**Indexes:**
* `conversationId`
* `aspirantWhatsappId`
* `timestamp`
* `senderType`
## 4. `Recruiter` (User Model)
Represents an agency recruiter using the platform (details depend on authentication provider like Cognito).
```typescript
interface Recruiter {
id: string; // PK - Often corresponds to Cognito User Sub
name: string;
email: string; // Unique
// Add roles/permissions if needed later
createdAt: Date;
updatedAt: Date;
}
```
**Indexes:**
* `email` (Unique)
## Relationships
* One `Aspirant` potentially relates to one `Conversation` (based on `whatsappId`).
* One `Conversation` contains many `Messages`.
* One `Recruiter` can send many `Messages`.
## Notes on Evolution
* **Normalization:** Some fields like `aspirantWhatsappId` are denormalized onto `Message` for query performance. Assess trade-offs if data consistency becomes complex.
* **JSONB:** Consider using PostgreSQL's JSONB type for flexible fields like `formDetails` if the web form structure is expected to change frequently, though explicit columns offer better indexing and type safety initially.
* **Scalability:** Partitioning message tables by date or `conversationId` might be necessary for very high volumes in the future.
## Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial draft | {Agent/Person} |
| ... | ... | ... | ... | ... |

View File

@ -0,0 +1 @@
{replace with relevant report}

View File

@ -0,0 +1 @@
{replace with relevant report}

View File

@ -0,0 +1 @@
{replace with relevant report}

View File

@ -0,0 +1,119 @@
# Environment Variables: WasaPrecruit MVP
This document outlines the strategy for managing environment variables and configuration for the different services within the WasaPrecruit MVP.
## Strategy
* **Centralized Management:** For deployed environments (Staging, Production), use AWS Systems Manager Parameter Store or AWS Secrets Manager to securely store and manage configuration values, especially secrets.
* **IaC Integration:** Infrastructure as Code (AWS CDK / Terraform) will be responsible for provisioning the parameters/secrets and injecting them into the relevant service environments (e.g., Lambda function environment variables, build-time injection for Frontend if necessary).
* **Local Development:** Use `.env` files (git-ignored) in the respective service directories (`services/api`, `services/ai-bot`, `ui`, etc.) for local configuration. A `.env.example` file should be committed for each service, listing required variables without their values.
* **Naming Convention:** Use `UPPER_SNAKE_CASE` for environment variable names.
* **TypeScript Access:** Use a configuration loading utility (or plain `process.env`) within services to access variables with type safety where possible.
## Variables by Service
*(Note: This is an initial list and may evolve. Actual names might vary slightly based on IaC implementation.)*
### 1. Frontend (`ui/.env`)
```plaintext
# .env.example for ui
# AWS AppSync / API Gateway Endpoint
VITE_API_ENDPOINT= # e.g., https://<appsync_id>.appsync-api.<region>.amazonaws.com/graphql
VITE_API_REGION= # e.g., us-east-1
# AWS Cognito Configuration
VITE_COGNITO_USER_POOL_ID=
VITE_COGNITO_USER_POOL_WEB_CLIENT_ID=
VITE_COGNITO_REGION= # e.g., us-east-1
# Optional: Analytics, feature flags, etc.
```
* **Rationale:** Variables prefixed with `VITE_` are exposed to the frontend build process by Vite.
### 2. Backend API (`services/api/.env`)
```plaintext
# .env.example for services/api
# Database Connection (Provided by RDS via Secrets Manager)
# DB_HOST=
# DB_PORT=
# DB_USER=
# DB_PASSWORD=
# DB_NAME=
DATABASE_SECRET_ARN= # ARN of the Secrets Manager secret containing DB credentials
# AWS Region
AWS_REGION=us-east-1
# WhatsApp Integration Service Endpoint/ARN (If direct invocation needed)
WHATSAPP_SENDER_FUNCTION_ARN=
# AI Bot Service Endpoint/ARN (If direct invocation needed)
AI_BOT_FUNCTION_ARN=
# SQS Queue URL (If explicitly used)
MESSAGE_PROCESSING_QUEUE_URL=
# CORS Origins (for API Gateway if used)
ALLOWED_ORIGINS= # e.g., http://localhost:3000,https://yourdomain.com
```
* **Note:** Database credentials should **not** be directly in environment variables in deployed stages; use integration with Secrets Manager.
### 3. AI Bot Service (`services/ai-bot/.env`)
```plaintext
# .env.example for services/ai-bot
# AWS Region
AWS_REGION=us-east-1
# WhatsApp Integration Service Endpoint/ARN (for sending messages)
WHATSAPP_SENDER_FUNCTION_ARN=
# Pre-defined Bot Messages (Can be env vars or config files)
BOT_WELCOME_MESSAGE="Welcome! Please fill out our form: {formLink}"
BOT_PHOTO_REQUEST_MESSAGE="Thanks! Could you please send a recent photo?"
BOT_AFFIRMATION_MESSAGE="Thank you! You look great. We've received your info and you're approved to proceed. We'll contact you about training soon."
# External Web Form Base URL (to construct unique links)
FORM_BASE_URL=https://forms.example.com/aspirant
```
### 4. WhatsApp Integration Service (`services/whatsapp-ingestor/.env`)
```plaintext
# .env.example for services/whatsapp-ingestor
# WhatsApp Provider Credentials (via Secrets Manager ideally)
# TWILIO_ACCOUNT_SID=
# TWILIO_AUTH_TOKEN=
# TWILIO_WHATSAPP_NUMBER=
WHATSAPP_CREDENTIALS_SECRET_ARN= # ARN of the Secrets Manager secret
# S3 Bucket for Images
IMAGE_BUCKET_NAME=
# Backend API Endpoint / SQS Queue
MESSAGE_PROCESSING_QUEUE_URL=
# OR API_ENDPOINT= if calling API directly
# Webhook Validation Token (If required by provider)
WHATSAPP_WEBHOOK_TOKEN=
# AWS Region
AWS_REGION=us-east-1
```
## Security
* **NEVER** commit `.env` files or actual secret values to version control.
* Use AWS Secrets Manager for sensitive credentials (Database passwords, API keys).
* Restrict permissions (IAM Roles) so that services can only access the configuration they need.
## Management
* IaC code (CDK/Terraform) is the source of truth for configuration in deployed environments.
* Update `.env.example` files whenever new required variables are added.

46
CURRENT-V2/docs/epicN.md Normal file
View File

@ -0,0 +1,46 @@
# Epic {N}: {Epic Title}
**Goal:** {State the overall goal this epic aims to achieve, linking back to the PRD goals.}
## Story List
{List all stories within this epic. Repeat the structure below for each story.}
### Story {N}.{M}: {Story Title}
- **User Story / Goal:** {Describe the story goal, ideally in "As a [role], I want [action], so that [benefit]" format, or clearly state the technical goal.}
- **Detailed Requirements:**
- {Bulleted list explaining the specific functionalities, behaviors, or tasks required for this story.}
- {Reference other documents for context if needed, e.g., "Handle data according to `docs/data-models.md#EntityName`".}
- {Include any technical constraints or details identified during refinement - added by Architect/PM/Tech SM.}
- **Acceptance Criteria (ACs):**
- AC1: {Specific, verifiable condition that must be met.}
- AC2: {Another verifiable condition.}
- ACN: {...}
- **Tasks (Optional Initial Breakdown):**
- [ ] {High-level task 1}
- [ ] {High-level task 2}
---
### Story {N}.{M+1}: {Story Title}
- **User Story / Goal:** {...}
- **Detailed Requirements:**
- {...}
- **Acceptance Criteria (ACs):**
- AC1: {...}
- AC2: {...}
- **Tasks (Optional Initial Breakdown):**
- [ ] {...}
---
{... Add more stories ...}
## Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ----------------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial epic definition | {Agent/Person} |
| ... | ... | ... | ... | ... |

View File

@ -0,0 +1,74 @@
# Frontend Architecture: WasaPrecruit MVP
This document provides a high-level overview of the WasaPrecruit frontend application architecture, built with React and TypeScript.
## 1. Overview
The frontend is a Single Page Application (SPA) designed to provide a real-time, multi-pane chat interface for recruiters.
* **Framework:** React (v18+)
* **Language:** TypeScript
* **Build Tool:** Vite
* **Key Libraries:**
* UI Components: Material UI (MUI) or Chakra UI
* State Management: Zustand
* API Communication: Apollo Client (for GraphQL/AppSync)
* Routing: React Router
## 2. Core Components & Structure
(Refer to `docs/project-structure.md` for the detailed directory layout within `ui/`)
* **`main.tsx` / `App.tsx`:** Entry point, sets up routing, providers (Apollo, Zustand, Theme).
* **`pages/`:** Top-level views corresponding to routes (e.g., `LoginPage`, `ChatDashboardPage`).
* **`layouts/`:** Structural components defining the overall page layout (e.g., `DashboardLayout` with sidebar and main content area).
* **`features/`:** Self-contained modules representing major application features:
* **`chat/`:** Components related to the conversation list, message display, message input area.
* **`aspirant/`:** Components for displaying the aspirant's profile data (from form/system).
* **`auth/`:** Login forms, authentication logic integration (with Cognito).
* **`components/`:** Generic, reusable UI elements (Buttons, Inputs, Modals, etc.) used across features.
* **`hooks/`:** Custom React hooks for shared logic (e.g., `useAuth`, `useRealtimeUpdates`).
* **`services/`:** API interaction layer. Contains GraphQL query/mutation/subscription definitions and functions for interacting with the AppSync backend via Apollo Client.
* **`store/`:** Zustand stores for managing global or feature-specific state.
* **`types/`:** Frontend-specific TypeScript types, potentially importing/extending from `packages/common-types`.
* **`styles/`:** Global CSS, theme configuration (e.g., MUI theme overrides).
## 3. State Management (Zustand)
* Use Zustand for managing global state (e.g., authenticated user, connection status) and potentially complex feature state.
* Create separate stores for different domains (e.g., `useAuthStore`, `useConversationStore`).
* Leverage middleware as needed (e.g., persistence, logging).
* Simpler component state can be managed with `useState` or `useReducer`.
## 4. API Communication (Apollo Client / AppSync)
* Configure Apollo Client to connect to the AWS AppSync endpoint.
* Use Apollo hooks (`useQuery`, `useMutation`, `useSubscription`) within components or the `services/` layer to interact with the GraphQL API.
* Handle loading and error states gracefully.
* Leverage Apollo cache for optimistic UI updates and minimizing redundant requests where appropriate.
## 5. Real-time Updates
* Use Apollo Client's `useSubscription` hook to subscribe to relevant AppSync subscriptions (`onNewMessage`, `onAspirantUpdate`, `onNewConversation`).
* Update the local state (Zustand store or component state) when new data arrives via subscriptions.
* Ensure efficient updates, especially for the message list (potentially using virtualization libraries like `react-window` or `react-virtualized` if lists become very long).
## 6. Performance Considerations
* **Code Splitting:** Leverage Vite's automatic code splitting to load code only when needed.
* **Lazy Loading:** Use `React.lazy` and `Suspense` for lazily loading components/pages.
* **Memoization:** Use `React.memo`, `useMemo`, `useCallback` to prevent unnecessary re-renders.
* **List Virtualization:** Implement for potentially long lists (conversations, messages) to ensure UI responsiveness.
* **Bundle Size Analysis:** Regularly analyze bundle size to identify optimization opportunities.
## 7. Authentication
* Integrate with AWS Cognito using AWS Amplify UI components or a custom implementation using Amplify Auth library.
* Secure routes requiring authentication.
* Manage user sessions and tokens.
## 8. Future Considerations
* **UI Testing:** Implement component tests using React Testing Library.
* **Accessibility:** Ensure components meet WCAG standards.
* **Internationalization (i18n):** Structure for potential future language support.

90
CURRENT-V2/docs/prd.md Normal file
View File

@ -0,0 +1,90 @@
# {Project Name} Product Requirements Document (PRD)
## Intro
{Short 1-2 paragraph describing the what and why of the product/system being built for this version/MVP, referencing the `project-brief.md`.}
## Goals and Context
- **Project Objectives:** {Summarize the key business/user objectives this product/MVP aims to achieve. Refine goals from the Project Brief.}
- **Measurable Outcomes:** {How will success be tangibly measured? Define specific outcomes.}
- **Success Criteria:** {What conditions must be met for the MVP/release to be considered successful?}
- **Key Performance Indicators (KPIs):** {List the specific metrics that will be tracked.}
## Scope and Requirements (MVP / Current Version)
### Functional Requirements (High-Level)
{List the major capabilities the system must have. Describe _what_ the system does, not _how_. Group related requirements.}
- Capability 1: ...
- Capability 2: ...
### Non-Functional Requirements (NFRs)
{List key quality attributes and constraints.}
- **Performance:** {e.g., Response times, load capacity}
- **Scalability:** {e.g., Ability to handle growth}
- **Reliability/Availability:** {e.g., Uptime requirements, error handling expectations}
- **Security:** {e.g., Authentication, authorization, data protection, compliance}
- **Maintainability:** {e.g., Code quality standards, documentation needs}
- **Usability/Accessibility:** {High-level goals; details in UI/UX Spec if applicable}
- **Other Constraints:** {e.g., Technology constraints, budget, timeline}
### User Experience (UX) Requirements (High-Level)
{Describe the key aspects of the desired user experience. If a UI exists, link to `docs/ui-ux-spec.md` for details.}
- UX Goal 1: ...
- UX Goal 2: ...
### Integration Requirements (High-Level)
{List key external systems or services this product needs to interact with.}
- Integration Point 1: {e.g., Payment Gateway, External API X, Internal Service Y}
- Integration Point 2: ...
- _(See `docs/api-reference.md` for technical details)_
### Testing Requirements (High-Level)
{Briefly outline the overall expectation for testing - as the details will be in the testing strategy doc.}
- {e.g., "Comprehensive unit, integration, and E2E tests are required.", "Specific performance testing is needed for component X."}
- _(See `docs/testing-strategy.md` for details)_
## Epic Overview (MVP / Current Version)
{List the major epics that break down the work for the MVP. Include a brief goal for each epic. Detailed stories reside in `docs/epicN.md` files.}
- **Epic 1: {Epic Title}** - Goal: {...}
- **Epic 2: {Epic Title}** - Goal: {...}
- **Epic N: {Epic Title}** - Goal: {...}
## Key Reference Documents
{Link to other relevant documents in the `docs/` folder.}
- `docs/project-brief.md`
- `docs/architecture.md`
- `docs/epic1.md`, `docs/epic2.md`, ...
- `docs/tech-stack.md`
- `docs/api-reference.md`
- `docs/testing-strategy.md`
- `docs/ui-ux-spec.md` (if applicable)
- ... (other relevant docs)
## Post-MVP / Future Enhancements
{List ideas or planned features for future versions beyond the scope of the current PRD.}
- Idea 1: ...
- Idea 2: ...
## Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ---------------------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial draft based on brief | {Agent/Person} |
| ... | ... | ... | ... | ... |

View File

@ -0,0 +1,60 @@
# WasaPrecruit - Product Backlog (Brainstorm)
This document captures potential features, enhancements, and ideas for future development beyond the initial MVP. Items are loosely categorized and range from concrete next steps to vague, long-term possibilities.
## AI & Automation
* **Conversational AI:** Expand AI capabilities beyond basic FAQ to handle more complex questions or initial qualification dialogues.
* **Sentiment Analysis:** Analyze aspirant message sentiment to flag potential issues or positive engagement for recruiters.
* **AI-Suggested Replies:** Provide recruiters with context-aware reply suggestions.
* **Advanced FAQ Handling:** Allow AI to manage a broader, more dynamic set of FAQs based on aspirant questions.
* **Persona Consistency AI:** Explore AI assistance in helping recruiters maintain the target persona (e.g., tone checks).
* **A/B Testing (Bot Messages):** Allow testing different initial contact messages or FAQ responses.
## Recruiter Workflow & UI/UX
* **Conversation Assignment:** Manually or automatically assign conversations to specific recruiters.
* **Advanced Routing/Assignment Logic (e.g., load, skills):** Implement sophisticated chat routing beyond basic assignment.
* **Advanced Status Tracking:** Implement custom conversation stages/pipeline (e.g., "Form Sent," "Qualified," "Interview Scheduled").
* **Qualification Workflow Support:** UI elements/steps to guide recruiters through standardized qualification.
* **Internal Notes & Tagging:** Allow recruiters to add private notes or tags (e.g., #urgent, #followup) to conversations.
* **Canned Responses:** Enable recruiters to quickly insert pre-written responses for common complex questions.
* **Bulk messaging capabilities:** Allow sending messages to multiple aspirants simultaneously (use with caution regarding WhatsApp policies).
* **UI Highlighting:** Automatically highlight key data points in the aspirant info panel (e.g., location, `has_kids`).
* **Proactive Aspirant Data Utilization (Automated triggers/highlights based on form data):** Use form data for more than just display.
* **Scheduled Messages:** Allow recruiters to schedule messages for later delivery.
* **Recruiter Gamification:** Introduce elements to track and incentivize performance (e.g., conversion leaderboards).
* **Rich Media Handling:** Improve support for sending/receiving images or documents directly in the chat interface (beyond basic WA support).
* **In-Platform Training:** Embed guidelines, persona docs, or training materials.
* **Persona Guidance Tools (UI elements/reminders):** Subtle prompts/links in UI to aid persona consistency.
* **Easy Privacy Policy Sharing:** One-click button for recruiters to send the privacy policy link.
## Integrations
* **Payment System Integration:** Connect with payment platforms for tracking or initiating payments.
* **CRM Integration:** Sync aspirant data and conversation status with the main agency CRM.
* **Calendar Integration:** Facilitate scheduling interviews or calls directly from the platform.
* **Multi-channel Support:** Integrate other messaging channels (SMS, Facebook Messenger, etc.).
* **Internal Comms Integration:** Link with Slack/Teams for notifications or internal discussion about aspirants.
## Analytics & Reporting
* **Comprehensive Dashboard:** Develop a dashboard with detailed metrics on recruiter activity, conversion funnels, message volume, FAQ usage, etc.
* **Aspirant Insights:** Analyze aggregated data for insights into common pain points, drop-off reasons, or successful communication patterns.
## Operational & Technical
* **Robust Error Handling/Monitoring:** Enhanced monitoring and alerting for API failures (WhatsApp, Form).
* **Performance Optimization:** Specific efforts to optimize for high concurrency and message volume.
* **Load Testing:** Implement regular load testing.
* **Specific Scalability/Security/Compliance Targets Definition:** Define concrete NFRs for future iterations.
* **Automated E2E Testing:** Build out a comprehensive automated testing suite.
* **Role-Based Access Control:** Introduce different permission levels (e.g., Recruiter, Manager, Admin).
* **Audit Log:** Detailed logging of user actions within the platform.
## Long-Term / Vague Ideas
* **Aspirant Portal:** A simple web portal for aspirants to check status, update info, or access resources (significant effort).
* **Video Call Integration:** Initiate video calls directly from the chat interface.
* **Automated Qualification Scoring:** AI-based scoring of aspirant potential based on form data and chat interaction.
* **Integrated Web Form Builder/Management:** Build form capabilities directly into the platform.

View File

@ -0,0 +1,111 @@
# Project Brief: WasaPrecruit - MVP
## Introduction / Problem Statement
The current process of managing initial recruitment conversations with potential modeling aspirants via standard WhatsApp is inefficient and prone to inconsistencies, hindering the agency's ability to scale recruitment and effectively convert interested leads. Key problems include:
1. **Inefficient Communication Handling:** Recruiters struggle to manage a high volume of incoming WhatsApp messages effectively, leading to delays, missed conversations, and difficulty tracking interactions across multiple chats without a centralized system.
2. **Manual & Repetitive Tasks:** Sending initial greetings, sharing application form links, and re-collecting basic information manually consumes significant recruiter time, detracting from higher-value activities like building rapport and qualifying aspirants.
3. **Lack of Centralized Aspirant Data:** Recruiter access to essential aspirant information (submitted via a separate process or gathered piecemeal in chat) is often delayed or disorganized. This prevents recruiters from quickly personalizing communication and proactively addressing potential concerns revealed in the aspirant's profile (e.g., childcare needs mentioned due to `has_kids` flag).
4. **Inconsistent Communication & Trust Building:** Without standardized tools and easy access to context (like chat history and structured data), maintaining a consistent, empathetic, and reassuring brand persona across all recruiter interactions is challenging. This can fail to address aspirant anxieties effectively, leading to drop-offs.
5. **Lost Conversion Opportunities:** The combination of inefficiency, lack of personalization, and potential inconsistencies results in a suboptimal experience for aspirants, contributing to lower conversion rates from initial contact to formal application/onboarding. Aspirant doubts regarding pay, safety, flexibility, and qualifications are not systematically addressed early in the process.
This platform aims to solve these problems by centralizing communication, automating initial steps, providing immediate access to aspirant data, and equipping recruiters to address concerns more effectively, ultimately improving both recruiter efficiency and aspirant conversion rates.
## Goals & Objectives (MVP)
The primary goals for the Minimum Viable Product (MVP) are:
1. **Enable Core Communication:** Provide recruiters with a stable web-based platform to reliably receive, view, and reply to WhatsApp messages from potential aspirants.
2. **Streamline Initial Contact:** Automate the initial greeting and web form link delivery to aspirants via an AI bot upon receiving their first message.
3. **Centralize Aspirant Data:** Capture key aspirant information (e.g., name, contact, location, `has_kids`, preferred modeling type) through a web form and display it clearly to the recruiter within the chat interface.
4. **Improve Recruiter Efficiency:** Reduce the time recruiters spend on initial message handling and information gathering compared to manual WhatsApp usage.
5. **Address Aspirant Doubts:** Equip recruiters with the necessary tools and readily available information (aspirant data from form, chat history) to proactively identify and address common aspirant concerns and anxieties (regarding pay, safety, flexibility, qualifications, etc.) early and effectively within the chat interface.
6. **Boost Conversion Foundation:** Establish the platform foundation necessary to significantly improve the aspirant application-to-onboarding conversion rate by facilitating trust-building communication and addressing key drop-off points.
7. **Establish Scalable Foundation:** Build the MVP on a **highly scalable technical architecture** capable of handling significant growth in aspirant volume and recruiter usage from day one, ensuring performance under load.
## Target Audience / Users
1. **Primary Users: Agency Recruiters**
* **Role:** Full-time or part-time recruitment agents employed by the modeling agency.
* **Location:** Likely operating from an agency office or potentially remotely within Colombia.
* **Core Tasks:** Manage initial WhatsApp communications with a high volume of potential modeling aspirants, guide them through the initial application steps (form submission), answer questions, address concerns, build rapport using a defined persona, and qualify leads for the next stage of the onboarding process.
* **Needs:** An efficient, centralized platform to handle multiple WhatsApp conversations simultaneously. Quick access to aspirant-submitted data (from the web form) and conversation history to personalize interactions and address concerns effectively. Tools that reduce repetitive tasks (like initial greetings) and allow focus on relationship-building and qualification.
* **Assumed Technical Proficiency:** Comfortable using standard web-based applications and chat interfaces. The platform should be intuitive and require minimal specialized technical training. They need reliability and speed to manage conversation flow effectively.
2. **Secondary Audience: Potential Modeling Aspirants**
* **Role:** Individuals in Colombia interested in modeling opportunities offered by the agency.
* **Interaction:** Communicate with the agency primarily via their personal WhatsApp accounts. They will receive automated messages (greetings, form links) and engage in chat conversations with the Primary Users (recruiters). They will also interact with a web form to submit their initial application details.
* **Key Characteristics & Needs:** Seeking clear, trustworthy information about modeling opportunities, payment, scheduling flexibility, and safety protocols. They respond positively to personalized, empathetic communication that addresses their potential anxieties and makes them feel valued. They require a simple, mobile-friendly way to provide their information (web form) and communicate (WhatsApp). They expect reasonably prompt responses.
## Key Features / Scope (MVP)
1. **WhatsApp Integration (Core Engine):**
* Ability to connect to the WhatsApp Business API (or chosen intermediary like Twilio).
* Reliably send and receive messages between the platform and aspirant WhatsApp numbers.
* Handle incoming messages and route them to the appropriate recruiter/view.
2. **Recruiter Web Interface (Chat Client):**
* Secure login for recruiters.
* A multi-pane view displaying: List of active conversations, selected conversation's chat history, input area for composing/sending replies, and a dedicated panel for aspirant data from the web form.
* Real-time updates for new incoming messages.
* Ability to view message history for each conversation.
3. **AI Bot (Initial Contact & Basic FAQ):**
* Automatically detect the first message from a new aspirant number.
* Send a pre-defined, persona-aligned welcome message.
* Send a unique link to the web application form.
* Respond automatically to 1-2 pre-defined, high-frequency initial questions (e.g., regarding payment structure) with pre-written answers/links.
4. **Web Application Form Integration:**
* Mechanism to generate a unique link to an external web form (assume form exists or is built separately for MVP).
* API endpoint or method to receive submitted form data (e.g., Name, Phone, Location, `has_kids`, Preferred Modeling Type).
* Store submitted data associated with the correct aspirant/conversation.
* Display submitted data clearly within the recruiter's chat interface panel.
5. **Basic Conversation Management:**
* Indication of unread messages.
* Ability to mark conversations as needing attention or perhaps archive/close (basic status).
**Out of Scope for MVP (Examples):** Advanced AI replies, payment integration, analytics dashboard, internal recruiter chat, bulk messaging, specific conversation assignment, advanced filtering/searching.
## Success Metrics (MVP)
1. **System Uptime & Reliability:** >99% operational uptime.
2. **Recruiter Adoption Rate:** % of target recruiters actively using daily/weekly within first month.
3. **Reduction in Initial Response Time:** Measure bot response time vs. manual baseline.
4. **Form Submission Rate:** % of aspirants receiving link who submit the form.
5. **Recruiter Efficiency Feedback:** Qualitative feedback via surveys/interviews.
6. **Conversion Rate Benchmark:** Establish baseline conversion rate (Contact -> Form -> Next Step).
7. **Qualitative Feedback on Addressing Doubts:** Assess recruiter perception of platform's helpfulness in addressing concerns.
## Technical Considerations / Platform (Initial Thoughts)
* **Platform:** Web Application.
* **Core Architectural Driver: High Scalability:** The chosen technologies and architecture *must* support significant, cost-effective scaling to handle potentially large numbers of concurrent recruiters and high message throughput. This is a non-negotiable requirement for the MVP.
* **Deployment:** Cloud-native design (AWS, GCP, Azure) is mandated to facilitate scalability, reliability, and maintainability.
* **Interfaces:** WhatsApp Business API (e.g., Twilio), External Web Form API/Webhook.
* **Frontend:** Modern JavaScript framework (React, Vue, Angular).
* **Backend:** Technology choice must prioritize demonstrable scalability and real-time capabilities (e.g., Python/Node.js frameworks suitable for WebSockets and scalable deployments).
* **Database:** Choice must support scalability and potentially high write/read loads (e.g., PostgreSQL, MySQL with appropriate scaling strategies, or managed NoSQL options).
* **Critical Requirements:** Real-time message display in the recruiter UI; **Demonstrable Architectural Scalability** from launch.
## Key Assumptions & Success Factors
1. **WhatsApp API Stability:** Assumes reliable performance of the chosen provider.
2. **External Web Form:** Assumes a functional external form and API exist.
3. **Recruiter Training & Adoption:** Relies on user training and buy-in.
4. **Persona Implementation:** Success depends on recruiters using the platform tools *and* the defined persona effectively.
5. **FAQ Accuracy:** Assumes bot's pre-defined answers are accurate and helpful.
6. **Tools -> Conversion Link:** Assumes platform improvements will lead to better conversion.
7. **Network Stability:** Requires stable internet for users.
8. **Scalable MVP Architecture Achieved:** The successful implementation of an inherently scalable architecture *within the MVP phase* is critical for long-term viability and achieving efficiency goals under expected load.
## Future Considerations / Potential Enhancements
* **Advanced AI:** Conversational AI, sentiment analysis, suggested replies.
* **Integrations:** Payment systems, CRM, Calendars.
* **Workflow Tools:** Conversation assignment, advanced status tracking, internal notes, tagging.
* **Analytics:** Detailed reporting dashboard.
* **Multi-channel Support:** SMS, FB Messenger, etc.
* **In-Platform Training Resources.**

View File

@ -0,0 +1,34 @@
# Project Brief: {Project Name}
## Introduction / Problem Statement
{Describe the core idea, the problem being solved, or the opportunity being addressed. Why is this project needed?}
## Vision & Goals
- **Vision:** {Describe the high-level desired future state or impact of this project.}
- **Primary Goals:** {List 2-5 specific, measurable, achievable, relevant, time-bound (SMART) goals for the Minimum Viable Product (MVP).}
- Goal 1: ...
- Goal 2: ...
- **Success Metrics (Initial Ideas):** {How will we measure if the project/MVP is successful? List potential KPIs.}
## Target Audience / Users
{Describe the primary users of this product/system. Who are they? What are their key characteristics or needs relevant to this project?}
## Key Features / Scope (High-Level Ideas for MVP)
{List the core functionalities or features envisioned for the MVP. Keep this high-level; details will go in the PRD/Epics.}
- Feature Idea 1: ...
- Feature Idea 2: ...
- Feature Idea N: ...
## Known Technical Constraints or Preferences
- **Constraints:** {List any known limitations and technical mandates or preferences - e.g., budget, timeline, specific technology mandates, required integrations, compliance needs.}
- **Risks:** {Identify potential risks - e.g., technical challenges, resource availability, market acceptance, dependencies.}
## Relevant Research (Optional)
{Link to or summarize findings from any initial research conducted (e.g., `deep-research-report-BA.md`).}

View File

@ -0,0 +1,132 @@
# Project Structure: WasaPrecruit MVP
This document outlines the proposed directory structure for the WasaPrecruit MVP codebase. The structure aims for clarity, modularity, separation of concerns, and ease of navigation, particularly facilitating development by AI agents working on specific components.
**Guiding Principles:**
* **Separation of Concerns:** Frontend, Backend API, AI Bot logic, Infrastructure code, and shared utilities are clearly separated.
* **Modularity:** Components are broken down into smaller, focused modules/files (Single Responsibility Principle - SRP).
* **Discoverability:** Logical naming conventions and clear directory hierarchies.
* **Agent-Friendliness:** Small, well-defined files with clear inputs/outputs are easier for AI agents to understand, modify, and test.
* **Technology-Based Grouping:** Within major components (like backend), grouping by feature or function might be used, but initial grouping often aligns with technology patterns (e.g., Lambda handlers, GraphQL resolvers).
## Root Directory Structure
```plaintext
/
├── .github/ # CI/CD workflows (e.g., GitHub Actions)
│ └── workflows/
│ └── deploy.yml
├── .vscode/ # VS Code settings (launch configs, extensions)
├── docs/ # Project documentation (Architecture, Epics, etc.)
│ ├── templates/ # Original templates
│ ├── architecture.md
│ ├── coding-standards.md
│ ├── data-models.md
│ ├── environment-vars.md
│ ├── epic1.md # Example Epic
│ ├── product-backlog.md
│ ├── project-brief-mvp.md
│ ├── project-structure.md
│ ├── tech-stack.md
│ └── testing-strategy.md
│ └── api-reference.md
│ └── frontend-architecture.md # (If needed later for deep FE specifics)
├── infrastructure/ # Infrastructure as Code (IaC - e.g., AWS CDK)
│ ├── bin/
│ │ └── infrastructure.ts
│ ├── lib/
│ │ ├── database-stack.ts
│ │ ├── backend-api-stack.ts
│ │ ├── frontend-deployment-stack.ts
│ │ └── ... (other stacks: auth, storage, etc.)
│ ├── package.json
│ ├── tsconfig.json
│ └── cdk.json
├── packages/ # Shared libraries/utilities (using npm/yarn workspaces)
│ └── common-types/ # Shared TypeScript types (DTOs, interfaces)
│ ├── src/
│ │ ├── index.ts
│ │ └── aspirant.ts
│ ├── package.json
│ └── tsconfig.json
├── services/ # Backend services (Lambda functions, etc.)
│ ├── api/ # Backend API Lambdas (triggered by AppSync/API GW)
│ │ ├── src/
│ │ │ ├── graphql/ # GraphQL specific files (schema, resolvers)
│ │ │ │ ├── schema.graphql
│ │ │ │ └── resolvers/
│ │ │ │ ├── aspirant.ts
│ │ │ │ └── message.ts
│ │ │ ├── handlers/ # Lambda handler entry points
│ │ │ │ ├── getAspirant.ts
│ │ │ │ └── sendMessage.ts
│ │ │ └── utils/ # API specific utilities
│ │ ├── package.json
│ │ ├── tsconfig.json
│ │ └── serverless.yml # Or similar deployment config if not solely CDK
│ ├── ai-bot/ # AI Bot Service Lambda
│ │ ├── src/
│ │ │ ├── handler.ts # Main entry point
│ │ │ └── logic.ts # Bot interaction flow logic
│ │ ├── package.json
│ │ └── tsconfig.json
│ ├── whatsapp-ingestor/ # WhatsApp Integration Service Lambda
│ │ ├── src/
│ │ │ ├── handler.ts # Webhook handler
│ │ │ └── imageProcessor.ts # Logic for handling image uploads to S3
│ │ ├── package.json
│ │ └── tsconfig.json
│ └── ... # Other potential microservices/Lambdas
├── ui/ # Frontend React Application
│ ├── public/
│ ├── src/
│ │ ├── App.tsx
│ │ ├── main.tsx
│ │ ├── components/ # Reusable UI components (atoms, molecules)
│ │ ├── features/ # Feature-specific components/logic (e.g., Chat, AspirantProfile)
│ │ │ ├── chat/
│ │ │ │ ├── ChatWindow.tsx
│ │ │ │ └── MessageList.tsx
│ │ │ └── aspirant/
│ │ │ └── AspirantProfilePanel.tsx
│ │ ├── hooks/ # Custom React hooks
│ │ ├── layouts/ # Top-level page layouts
│ │ ├── pages/ # Page components
│ │ ├── services/ # API interaction logic (e.g., AppSync/GraphQL calls)
│ │ ├── store/ # State management (e.g., Zustand stores)
│ │ ├── styles/ # Global styles, theme configuration
│ │ └── types/ # Frontend specific types (can import from packages/common-types)
│ ├── index.html
│ ├── package.json
│ ├── tsconfig.json
│ └── vite.config.ts
├── .env.example # Example environment variables
├── .eslintignore
├── .eslintrc.js # ESLint configuration
├── .gitignore
├── .prettierrc.js # Prettier configuration
├── package.json # Root package.json (for workspaces, scripts)
├── README.md # Project overview, setup instructions
└── tsconfig.base.json # Base TypeScript config shared across packages/services
```
## Key Directory Explanations
* **`docs/`**: All non-code documentation.
* **`infrastructure/`**: Contains all IaC code (using AWS CDK in this example) to define and deploy the cloud resources.
* **`packages/`**: Monorepo setup for shared code. `common-types` is crucial for ensuring type consistency between frontend and backend services.
* **`services/`**: Houses the backend microservices/functions. Each subdirectory represents a deployable unit (usually a Lambda function or a related group).
* **`api/`**: The main backend API logic, potentially including GraphQL schema/resolvers and Lambda handlers.
* **`ai-bot/`**: Isolated logic for the automated bot interactions.
* **`whatsapp-ingestor/`**: Handles incoming webhooks from the WhatsApp provider.
* **`ui/`**: The React frontend application code, structured by feature and component type.
This structure provides a clear separation, making it easier for developers (and AI agents) to locate relevant code, understand dependencies, and work on specific parts of the system without unintended side effects.
## Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial draft | {Agent/Person} |
| ... | ... | ... | ... | ... |

View File

@ -0,0 +1,84 @@
# Story {EpicNum}.{StoryNum}: {Short Title Copied from Epic File}
**Status:** Draft | In-Progress | Complete
## Goal & Context
**User Story:** {As a [role], I want [action], so that [benefit] - Copied or derived from Epic file}
**Context:** {Briefly explain how this story fits into the Epic's goal and the overall workflow. Mention the previous story's outcome if relevant. Example: "This story builds upon the project setup (Story 1.1) by defining the S3 resource needed for state persistence..."}
## Detailed Requirements
{Copy the specific requirements/description for this story directly from the corresponding `docs/epicN.md` file.}
## Acceptance Criteria (ACs)
{Copy the Acceptance Criteria for this story directly from the corresponding `docs/epicN.md` file.}
- AC1: ...
- AC2: ...
- ACN: ...
## Technical Implementation Context
**Guidance:** Use the following details for implementation. Refer to the linked `docs/` files for broader context if needed.
- **Relevant Files:**
- Files to Create: {e.g., `src/services/s3-service.ts`, `test/unit/services/s3-service.test.ts`}
- Files to Modify: {e.g., `lib/hacker-news-briefing-stack.ts`, `src/common/types.ts`}
- _(Hint: See `docs/project-structure.md` for overall layout)_
- **Key Technologies:**
- {e.g., TypeScript, Node.js 22.x, AWS CDK (`aws-s3` construct), AWS SDK v3 (`@aws-sdk/client-s3`), Jest}
- {If a UI story, mention specific frontend libraries/framework features (e.g., React Hooks, Vuex store, CSS Modules)}
- _(Hint: See `docs/tech-stack.md` for full list)_
- **API Interactions / SDK Usage:**
- {e.g., "Use `@aws-sdk/client-s3`: `S3Client`, `GetObjectCommand`, `PutObjectCommand`.", "Handle `NoSuchKey` error specifically for `GetObjectCommand`."}
- _(Hint: See `docs/api-reference.md` for details on external APIs and SDKs)_
- **UI/UX Notes:** ONLY IF THIS IS A UI Focused Epic or Story
- **Data Structures:**
- {e.g., "Define/Use `AppState` interface in `src/common/types.ts`: `{ processedStoryIds: string[] }`.", "Handle JSON parsing/stringifying for state."}
- _(Hint: See `docs/data-models.md` for key project data structures)_
- **Environment Variables:**
- {e.g., `S3_BUCKET_NAME` (Read via `config.ts` or passed to CDK)}
- _(Hint: See `docs/environment-vars.md` for all variables)_
- **Coding Standards Notes:**
- {e.g., "Use `async/await` for all S3 calls.", "Implement error logging using `console.error`.", "Follow `kebab-case` for filenames, `PascalCase` for interfaces."}
- _(Hint: See `docs/coding-standards.md` for full standards)_
## Tasks / Subtasks
{Copy the initial task breakdown from the corresponding `docs/epicN.md` file and expand or clarify as needed to ensure the agent can complete all AC. The agent can check these off as it proceeds.}
- [ ] Task 1
- [ ] Task 2
- [ ] Subtask 2.1
- [ ] Task 3
## Testing Requirements
**Guidance:** Verify implementation against the ACs using the following tests.
- **Unit Tests:** {e.g., "Write unit tests for `src/services/s3-service.ts`. Mock `S3Client` and its commands (`GetObjectCommand`, `PutObjectCommand`). Test successful read/write, JSON parsing/stringifying, and `NoSuchKey` error handling."}
- **Integration Tests:** {e.g., "No specific integration tests required for _just_ this story's module, but it will be covered later in `test/integration/fetch-flow.test.ts`."}
- **Manual/CLI Verification:** {e.g., "Not applicable directly, but functionality tested via `npm run fetch-stories` later."}
- _(Hint: See `docs/testing-strategy.md` for the overall approach)_
## Story Wrap Up (Agent Populates After Execution)
- **Agent Model Used:** `<Agent Model Name/Version>`
- **Completion Notes:** {Any notes about implementation choices, difficulties, or follow-up needed}
- **Change Log:** {Track changes _within this specific story file_ if iterations occur}
- Initial Draft
- ...

View File

@ -0,0 +1,77 @@
# Technology Stack: WasaPrecruit MVP
This document details the technology stack selected for the WasaPrecruit MVP, aligned with the architecture defined in `docs/architecture.md`.
## Frontend
* **Framework:** React (v18+)
* *Rationale:* User preference, large community, rich ecosystem of libraries, component-based architecture suitable for complex UIs.
* **Language:** TypeScript
* *Rationale:* Static typing improves code quality, maintainability, and developer productivity, especially important for AI-assisted development.
* **State Management:** Zustand (or potentially Redux Toolkit / Context API)
* *Rationale:* Zustand offers a simple, scalable, and performant state management solution suitable for React. Final choice might depend on specific team preference and complexity encountered.
* **UI Library:** Material UI (MUI) or Chakra UI
* *Rationale:* Provides pre-built, accessible, and customizable components to accelerate development and ensure a consistent look and feel. MUI is a robust and popular choice.
* **Real-time Communication:** AWS Amplify UI Components with AppSync Subscription support / Apollo Client for GraphQL
* *Rationale:* Libraries to handle WebSocket connections managed by AWS AppSync for receiving real-time updates.
* **Build Tool:** Vite
* *Rationale:* Fast development server and optimized production builds.
* **Deployment:** AWS S3 + CloudFront
* *Rationale:* Standard, scalable, and cost-effective way to host and distribute static web applications globally.
## Backend
* **Platform:** Node.js (LTS version, e.g., v18 or v20)
* *Rationale:* Efficient event-driven I/O suitable for real-time applications and chat systems. JavaScript/TypeScript allows for code sharing/consistency with the frontend. Large package ecosystem (npm).
* **Language:** TypeScript
* *Rationale:* Same benefits as for the frontend: type safety, maintainability.
* **Runtime Environment:** AWS Lambda
* *Rationale:* Serverless compute enables automatic scaling, reduces operational overhead, cost-effective pay-per-use model.
* **API Layer:** AWS AppSync (GraphQL) and/or AWS API Gateway (REST)
* *Rationale:* AppSync provides managed GraphQL including real-time subscriptions via WebSockets. API Gateway can be used for RESTful endpoints (like webhooks). Combination offers flexibility.
* **Framework (Optional for Lambda):** Potentially lightweight frameworks like Express.js within Lambda handlers if complex routing/middleware is needed, but often plain handlers suffice.
* **Messaging Queue (Implicit/Explicit):** AWS SQS (Simple Queue Service)
* *Rationale:* Decouples services (e.g., WhatsApp Ingestion from Backend Processing), improves fault tolerance and scalability. Can be used explicitly or implicitly via Lambda event source mappings.
## Database
* **Type:** Relational Database (RDBMS)
* **Service:** AWS RDS for PostgreSQL (latest stable version)
* *Rationale:* Managed service simplifies administration, backups, scaling. PostgreSQL offers ACID compliance, rich feature set (JSONB support), and good performance.
* **ORM/Query Builder (Optional):** Prisma or TypeORM
* *Rationale:* Improves developer productivity and type safety when interacting with the database from TypeScript.
## AI Bot Service
* **Runtime Environment:** AWS Lambda (Node.js/TypeScript)
* *Rationale:* Same benefits as backend Lambda functions - isolated, scalable, event-driven.
* **Logic:** Custom TypeScript code implementing the defined flow (welcome, form link, photo request, affirmation).
* *Rationale:* Sufficient for the defined MVP bot scope. Can be enhanced later.
## Infrastructure & Cloud Services
* **Cloud Provider:** Amazon Web Services (AWS)
* *Rationale:* Mandated cloud-native. Offers mature and comprehensive services needed for the architecture (Lambda, AppSync, RDS, S3, SQS, API Gateway, Cognito, CloudFront).
* **Image Storage:** AWS S3 (Simple Storage Service)
* *Rationale:* Scalable, durable, cost-effective object storage for aspirant photos.
* **Authentication:** AWS Cognito
* *Rationale:* Managed user identity and authentication service for securing the recruiter frontend.
* **Infrastructure as Code (IaC):** AWS CDK (Cloud Development Kit) or Terraform
* *Rationale:* Define infrastructure programmatically for repeatability, versioning, and automated provisioning. CDK allows using TypeScript.
* **Monitoring & Logging:** AWS CloudWatch
* *Rationale:* Integrated monitoring, logging, and alerting for AWS resources.
* **CI/CD:** GitHub Actions or AWS CodePipeline/CodeBuild
* *Rationale:* Automate testing and deployment processes.
## External Interfaces
* **WhatsApp API:** Twilio API for WhatsApp (or similar provider like Vonage/Meta directly)
* *Rationale:* Need a reliable provider for the WhatsApp Business API connection.
* **External Web Form API:** TBD (Depends on the service hosting the form - requires a webhook or API endpoint for data submission).
## Development Tools
* **Version Control:** Git / GitHub (or similar)
* **Package Managers:** npm / yarn (for Node.js/Frontend), uv pip (for Python if any utility scripts needed)
* **IDE:** VS Code / Cursor
* **Containerization (for local dev):** Docker (Optional, but recommended for standardizing local DB/environment)

View File

@ -0,0 +1,114 @@
# Testing Strategy: WasaPrecruit MVP
This document outlines the testing strategy for the WasaPrecruit MVP to ensure quality, reliability, and correctness.
## Goals
* Verify functional requirements are met.
* Ensure system stability and performance under expected load.
* Catch regressions before they reach production.
* Build confidence in deployments.
* Facilitate safe refactoring and modifications (by humans and AI).
## Testing Levels
We will employ a multi-layered testing approach:
1. **Static Analysis (Linting/Formatting):**
* **Tools:** ESLint, Prettier, TypeScript Compiler.
* **Scope:** Enforce code style, detect syntax errors, enforce type safety.
* **Execution:** Run automatically on commit hooks and in CI pipeline.
* **Rationale:** Catches basic errors early and enforces consistency.
2. **Unit Tests:**
* **Tools:** Jest or Vitest (for both Frontend and Backend Node.js/TS code).
* **Scope:** Test individual functions, modules, components, and classes in isolation. Focus on business logic, utility functions, and pure UI components.
* **Execution:** Run locally during development and in CI pipeline on every push/PR.
* **Mocking:** Use Jest/Vitest mocking capabilities to isolate units from external dependencies (APIs, databases, cloud services).
* **Target Coverage:** Aim for high coverage (>80%) of critical business logic.
* **Rationale:** Fast feedback loop, verifies correctness of small units, enables safe refactoring.
3. **Integration Tests:**
* **Tools:** Jest/Vitest, potentially with libraries like `supertest` (for HTTP endpoints) or tools to interact with deployed AWS resources (e.g., AWS SDK).
* **Scope:** Test interactions between different components or services. Examples:
* API endpoint handler correctly interacting with the database (using a test database or mocking the DB layer).
* Message processing flow (e.g., WhatsApp Ingestor -> SQS -> Backend API Lambda).
* Frontend component fetching data from the backend API (mocking the API).
* **Execution:** Run in CI pipeline, potentially less frequently than unit tests due to longer execution time.
* **Rationale:** Verifies collaboration between units and integration points.
4. **End-to-End (E2E) Tests:**
* **Tools:** Playwright or Cypress.
* **Scope:** Simulate real user scenarios by interacting with the live application (Frontend UI) through a browser. Examples:
* Recruiter logs in, receives a message, views aspirant data, sends a reply.
* Verify real-time message updates in the UI.
* **Environment:** Run against a dedicated test/staging environment that mirrors production closely.
* **Execution:** Run in CI pipeline, likely triggered less frequently (e.g., before production deployments) due to complexity and duration.
* **Rationale:** Provides highest confidence that user flows work as expected across the entire stack.
5. **Manual / Exploratory Testing:**
* **Scope:** Unscripted testing performed by humans to uncover usability issues, edge cases, or unexpected behavior not covered by automated tests.
* **Execution:** Performed periodically, especially before major releases or after significant changes.
* **Rationale:** Catches issues that automated tests might miss, provides qualitative feedback.
## Testing Specific Areas
* **Frontend (React UI):**
* Unit tests for components (logic & rendering, using React Testing Library).
* Unit tests for hooks and state management stores.
* Integration tests for data fetching.
* E2E tests for user flows.
* **Backend (Lambda Functions):**
* Unit tests for handlers and business logic (mocking AWS SDKs, DB interactions).
* Integration tests for API endpoints/resolvers (using local mocks or testing against deployed dev/staging resources).
* **AI Bot Logic:**
* Unit tests for the state machine/flow logic.
* Integration tests verifying interaction with the WhatsApp sending mechanism.
* **Infrastructure (IaC):**
* Linting and validation of CDK/Terraform code.
* Testing deployed infrastructure (e.g., checking resource creation, basic connectivity) can be part of integration/E2E tests or specific infrastructure tests.
## CI/CD Integration
* The CI/CD pipeline (e.g., GitHub Actions) will automate the execution of static analysis, unit tests, and integration tests on every pull request and push to main branches.
* E2E tests might run on merges to staging or before production deployment triggers.
* Builds/deployments should fail if tests do not pass.
## Quality Gates
* **Pull Requests:** Require passing static analysis and unit/integration tests before merging.
* **Staging Deployment:** Require passing E2E tests before promoting to production.
* **Code Coverage:** Monitor code coverage trends, aiming for a baseline (e.g., 70-80% for unit tests on critical code) but focusing on testing quality over raw numbers.
## Specialized Testing Types (Add sections as needed)
### Performance Testing
- **Scope & Goals:** {What needs performance testing? What are the targets (latency, throughput)?}
- **Tools:** {e.g., K6, JMeter, Locust}
### Security Testing
- **Scope & Goals:** {e.g., Dependency scanning, SAST, DAST, penetration testing requirements.}
- **Tools:** {e.g., Snyk, OWASP ZAP, Dependabot}
### Accessibility Testing (UI)
- **Scope & Goals:** {Target WCAG level, key areas.}
- **Tools:** {e.g., Axe, Lighthouse, manual checks}
### Visual Regression Testing (UI)
- **Scope & Goals:** {Prevent unintended visual changes.}
- **Tools:** {e.g., Percy, Applitools Eyes, Playwright visual comparisons}
## Test Data Management
{How is test data generated, managed, and reset for different testing levels?}
## Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial draft | {Agent/Person} |
| ... | ... | ... | ... | ... |

View File

@ -0,0 +1,99 @@
# {Project Name} UI/UX Specification
## Introduction
{State the purpose - to define the user experience goals, information architecture, user flows, and visual design specifications for the project's user interface.}
- **Link to Primary Design Files:** {e.g., Figma, Sketch, Adobe XD URL}
- **Link to Deployed Storybook / Design System:** {URL, if applicable}
## Overall UX Goals & Principles
- **Target User Personas:** {Reference personas or briefly describe key user types and their goals.}
- **Usability Goals:** {e.g., Ease of learning, efficiency of use, error prevention.}
- **Design Principles:** {List 3-5 core principles guiding the UI/UX design - e.g., "Clarity over cleverness", "Consistency", "Provide feedback".}
## Information Architecture (IA)
- **Site Map / Screen Inventory:**
```mermaid
graph TD
A[Homepage] --> B(Dashboard);
A --> C{Settings};
B --> D[View Details];
C --> E[Profile Settings];
C --> F[Notification Settings];
```
_(Or provide a list of all screens/pages)_
- **Navigation Structure:** {Describe primary navigation (e.g., top bar, sidebar), secondary navigation, breadcrumbs, etc.}
## User Flows
{Detail key user tasks. Use diagrams or descriptions.}
### {User Flow Name, e.g., User Login}
- **Goal:** {What the user wants to achieve.}
- **Steps / Diagram:**
```mermaid
graph TD
Start --> EnterCredentials[Enter Email/Password];
EnterCredentials --> ClickLogin[Click Login Button];
ClickLogin --> CheckAuth{Auth OK?};
CheckAuth -- Yes --> Dashboard;
CheckAuth -- No --> ShowError[Show Error Message];
ShowError --> EnterCredentials;
```
_(Or: Link to specific flow diagram in Figma/Miro)_
### {Another User Flow Name}
{...}
## Wireframes & Mockups
{Reference the main design file link above. Optionally embed key mockups or describe main screen layouts.}
- **Screen / View Name 1:** {Description of layout and key elements. Link to specific Figma frame/page.}
- **Screen / View Name 2:** {...}
## Component Library / Design System Reference
{Link to the primary source (Storybook, Figma Library). If none exists, define key components here.}
### {Component Name, e.g., Primary Button}
- **Appearance:** {Reference mockup or describe styles.}
- **States:** {Default, Hover, Active, Disabled, Loading.}
- **Behavior:** {Interaction details.}
### {Another Component Name}
{...}
## Branding & Style Guide Reference
{Link to the primary source or define key elements here.}
- **Color Palette:** {Primary, Secondary, Accent, Feedback colors (hex codes).}
- **Typography:** {Font families, sizes, weights for headings, body, etc.}
- **Iconography:** {Link to icon set, usage notes.}
- **Spacing & Grid:** {Define margins, padding, grid system rules.}
## Accessibility (AX) Requirements
- **Target Compliance:** {e.g., WCAG 2.1 AA}
- **Specific Requirements:** {Keyboard navigation patterns, ARIA landmarks/attributes for complex components, color contrast minimums.}
## Responsiveness
- **Breakpoints:** {Define pixel values for mobile, tablet, desktop, etc.}
- **Adaptation Strategy:** {Describe how layout and components adapt across breakpoints. Reference designs.}
## Change Log
| Change | Date | Version | Description | Author |
| ------------- | ---------- | ------- | ------------------- | -------------- |
| Initial draft | YYYY-MM-DD | 0.1 | Initial draft | {Agent/Person} |
| Added Flow X | YYYY-MM-DD | 0.2 | Defined user flow X | {Agent/Person} |
| ... | ... | ... | ... | ... |

View File

@ -0,0 +1,135 @@
```mermaid
flowchart TD
subgraph subGraph0["Phase 0: Ideation (Optional)"]
A1["BA / Researcher"]
A0["User Idea"]
A2["project-brief"]
A3["DR: BA"]
end
subgraph subGraph1["Phase 1: Product Definition"]
B1["Product Manager"]
B2["prd"]
B3["epicN (Functional Draft)"]
B4["DR: PRD"]
end
subgraph subGraph2["Phase 2: Technical Design"]
C1["Architect"]
C2["architecture"]
C3["Reference Files"]
C4["DR: Architecture"]
end
subgraph subGraph3["Phase 3: Refinement, Validation & Approval"]
R1{"Refine & Validate Plan"}
R2["PM + Architect + Tech SM"]
R3["PO Validation"]
R4{"Final Approval?"}
R5["Approved Docs Finalized"]
R6["index"]
end
subgraph subGraph4["Phase 4: Story Generation"]
E1["Technical Scrum Master"]
E2["story-template"]
E3["story_X_Y"]
end
subgraph subGraph5["Phase 5: Development"]
F1["Developer Agent"]
F2["Code + Tests Committed"]
F3["Story File Updated"]
end
subgraph subGraph6["Phase 6: Review & Acceptance"]
G1{"Review Code & Functionality"}
G1_1["Tech SM / Architect"]
G1_2["User / QA Agent"]
G2{"Story Done?"}
G3["Story Done"]
end
subgraph subGraph7["Phase 7: Deployment"]
H1("Developer Agent")
H2@{ label: "Run IaC Deploy Command (e.g., `cdk deploy`)" }
H3["Deployed Update"]
end
A0 -- PO Input on Value --> A1
A1 --> A2 & A3
A2 --> B1
A3 --> B1
B4 <--> B1
B1 --> B2 & B3
B2 --> C1 & R1
B3 <-- Functional Req --> C1
C4 -.-> C1
C1 --> C2 & C3
B3 --> R1
C2 --> R1
C3 --> R1
R1 -- Collaboration --> R2
R2 -- Technical Input --> B3
R1 -- Refined Plan --> R3
R3 -- "Checks: <br>1. Scope/Value OK?<br>2. Story Sequence/Deps OK?<br>3. Holistic PRD Alignment OK?" --> R4
R4 -- Yes --> R5
R4 -- No --> R1
R5 --> R6 & E1
B3 -- Uses Refined Version --> E1
C3 -- Uses Approved Version --> E1
E1 -- Uses --> E2
E1 --> E3
E3 --> F1
F1 --> F2 & F3
F2 --> G1
F3 --> G1
G1 -- Code Review --> G1_1
G1 -- Functional Review --> G1_2
G1_1 -- Feedback --> F1
G1_2 -- Feedback --> F1
G1_1 -- Code OK --> G2
G1_2 -- Functionality OK --> G2
G2 -- Yes --> G3
G3 --> H1
H1 --> H2
H2 --> H3
H3 --> E1
H2@{ shape: rect}
A0:::default
A1:::agent
A2:::doc
A3:::doc
B1:::default
B2:::doc
B3:::doc
B4:::doc
C1:::default
C2:::doc
C3:::doc
C4:::doc
F2:::default
F3:::doc
H3:::default
R1:::process
R2:::agent
R3:::agent
R4:::process
R5:::default
R6:::doc
E1:::agent
E2:::doc
E3:::doc
F1:::agent
G1:::process
G1_1:::agent
G1_2:::agent
G2:::process
G3:::process
H1:::agent
H2:::process
classDef agent fill:#1a73e8,stroke:#0d47a1,stroke-width:2px,color:white,font-size:14px
classDef doc fill:#43a047,stroke:#1b5e20,stroke-width:1px,color:white,font-size:14px
classDef process fill:#ff9800,stroke:#e65100,stroke-width:1px,color:white,font-size:14px
classDef default fill:#333333,color:white,stroke:#999999,stroke-width:1px,font-size:14px
%% Styling for subgraphs
classDef subGraphStyle font-size:16px,font-weight:bold
class subGraph0,subGraph1,subGraph2,subGraph3,subGraph4,subGraph5,subGraph6,subGraph7 subGraphStyle
%% Styling for edge labels
linkStyle default font-size:12px
```