diff --git a/ATS_PRODUCT_DOCUMENT.md b/ATS_PRODUCT_DOCUMENT.md new file mode 100644 index 0000000..e4f5282 --- /dev/null +++ b/ATS_PRODUCT_DOCUMENT.md @@ -0,0 +1,454 @@ +# KAAUH Applicant Tracking System (ATS) - Product Document + +## 1. Product Overview + +### 1.1 Product Description +The King Abdulaziz University Hospital (KAAUH) Applicant Tracking System (ATS) is a comprehensive recruitment management platform designed to streamline and optimize the entire hiring process. The system provides end-to-end functionality for job posting, candidate management, interview coordination, and integration with external recruitment platforms. + +### 1.2 Target Users +- **System Administrators**: Manage system configurations, user accounts, and integrations +- **Hiring Managers**: Create job postings, review candidates, and make hiring decisions +- **Recruiters**: Manage candidate pipelines, conduct screenings, and coordinate interviews +- **Interviewers**: Schedule and conduct interviews, provide feedback +- **Candidates**: Apply for positions, track application status, and participate in interviews +- **External Agencies**: Submit candidates and track progress + +### 1.3 Key Features +- **Job Management**: Create, edit, and publish job postings with customizable templates +- **Candidate Pipeline**: Track candidates through all stages of recruitment +- **Interview Scheduling**: Automated scheduling with calendar integration +- **Video Interviews**: Zoom integration for seamless virtual interviews +- **Form Builder**: Dynamic application forms with custom fields +- **LinkedIn Integration**: Automated job posting and profile synchronization +- **Reporting & Analytics**: Comprehensive dashboards and reporting tools +- **Multi-language Support**: Arabic and English interfaces + +## 2. User Stories + +### 2.1 Hiring Manager Stories +``` +As a Hiring Manager, I want to: +- Create job postings with detailed requirements and qualifications +- Review and shortlist candidates based on predefined criteria +- Track the status of all recruitment activities +- Generate reports on hiring metrics and trends +- Collaborate with recruiters and interviewers +- Post jobs directly to LinkedIn + +Acceptance Criteria: +- Can create job postings with rich text descriptions +- Can filter candidates by stage, skills, and match score +- Can view real-time recruitment metrics +- Can approve or reject candidates +- Can post jobs to LinkedIn with one click +``` + +### 2.2 Recruiter Stories +``` +As a Recruiter, I want to: +- Source and screen candidates from multiple channels +- Move candidates through the recruitment pipeline +- Schedule interviews and manage availability +- Send automated notifications and updates +- Track candidate engagement and response rates +- Maintain a database of potential candidates + +Acceptance Criteria: +- Can bulk import candidates from CSV files +- Can update candidate stages in bulk +- Can schedule interviews with calendar sync +- Can send automated email/SMS notifications +- Can track candidate communication history +``` + +### 2.3 Interviewer Stories +``` +As an Interviewer, I want to: +- View my interview schedule and availability +- Join video interviews seamlessly +- Provide structured feedback for candidates +- Access candidate information and resumes +- Confirm or reschedule interviews +- View interview history and patterns + +Acceptance Criteria: +- Receive email/SMS reminders for upcoming interviews +- Can join Zoom meetings with one click +- Can submit structured feedback forms +- Can access all candidate materials +- Can update interview status and availability +``` + +### 2.4 Candidate Stories +``` +As a Candidate, I want to: +- Search and apply for relevant positions +- Track my application status in real-time +- Receive timely updates about my application +- Participate in virtual interviews +- Submit required documents securely +- Communicate with recruiters easily + +Acceptance Criteria: +- Can create a profile and upload resumes +- Can search jobs by department and keywords +- Can track application status history +- Can schedule interviews within available slots +- Can receive notifications via email/SMS +- Can access all application materials +``` + +### 2.5 System Administrator Stories +``` +As a System Administrator, I want to: +- Manage user accounts and permissions +- Configure system settings and integrations +- Monitor system performance and usage +- Generate audit logs and reports +- Manage integrations with external systems +- Ensure data security and compliance + +Acceptance Criteria: +- Can create and manage user roles +- Can configure API keys and integrations +- Can monitor system health and performance +- Can generate audit trails for all actions +- Can backup and restore data +- Can ensure GDPR compliance +``` + +## 3. Functional Requirements + +### 3.1 Job Management Module +#### 3.1.1 Job Creation & Editing +- **FR1.1.1**: Users must be able to create new job postings with all required fields +- **FR1.1.2**: System must auto-generate unique internal job IDs +- **FR1.1.3**: Users must be able to edit job postings at any stage +- **FR1.1.4**: System must support job cloning for similar positions +- **FR1.1.5**: System must support multi-language content + +#### 3.1.2 Job Publishing & Distribution +- **FR1.2.1**: System must support job status management (Draft, Active, Closed) +- **FR1.2.2**: System must integrate with LinkedIn for job posting +- **FR1.2.3**: System must generate career pages for active jobs +- **FR1.2.4**: System must support application limits per job posting +- **FR1.2.5**: System must track application sources and effectiveness + +### 3.2 Candidate Management Module +#### 3.2.1 Candidate Database +- **FR2.1.1**: System must store comprehensive candidate profiles +- **FR2.1.2**: System must parse and analyze uploaded resumes +- **FR2.1.3**: System must support candidate import from various sources +- **FR2.1.4**: System must provide candidate search and filtering +- **FR2.1.5**: System must calculate match scores for candidates + +#### 3.2.2 Candidate Pipeline +- **FR2.2.1**: System must support customizable candidate stages +- **FR2.2.2**: System must enforce stage transition rules +- **FR2.2.3**: System must track all candidate interactions +- **FR2.2.4**: System must support bulk candidate operations +- **FR2.2.5**: System must provide candidate relationship management + +### 3.3 Interview Management Module +#### 3.3.1 Interview Scheduling +- **FR3.1.1**: System must support automated interview scheduling +- **FR3.1.2**: System must integrate with calendar systems +- **FR3.1.3**: System must handle timezone conversions +- **FR3.1.4**: System must support buffer times between interviews +- **FR3.1.5**: System must prevent scheduling conflicts + +#### 3.3.2 Video Interviews +- **FR3.2.1**: System must integrate with Zoom for video interviews +- **FR3.2.2**: System must create Zoom meetings automatically +- **FR3.2.3**: System must handle meeting updates and cancellations +- **FR3.2.4**: System must support meeting recordings +- **FR3.2.5**: System must manage meeting access controls + +### 3.4 Form Builder Module +#### 3.4.1 Form Creation +- **FR4.1.1**: System must support multi-stage form creation +- **FR4.1.2**: System must provide various field types +- **FR4.1.3**: System must support form validation rules +- **FR4.1.4**: System must allow conditional logic +- **FR4.1.5**: System must support form templates + +#### 3.4.2 Form Processing +- **FR4.2.1**: System must handle form submissions securely +- **FR4.2.2**: System must support file uploads +- **FR4.2.3**: System must extract data from submissions +- **FR4.2.4**: System must create candidates from submissions +- **FR4.2.5**: System must provide submission analytics + +### 3.5 Reporting & Analytics Module +#### 3.5.1 Dashboards +- **FR5.1.1**: System must provide role-based dashboards +- **FR5.1.2**: System must display key performance indicators +- **FR5.1.3**: System must support real-time data updates +- **FR5.1.4**: System must allow customization of dashboard views +- **FR5.1.5**: System must support data visualization + +#### 3.5.2 Reports +- **FR5.2.1**: System must generate standard reports +- **FR5.2.2**: System must support custom report generation +- **FR5.2.3**: System must export data in multiple formats +- **FR5.2.4**: System must schedule automated reports +- **FR5.2.5**: System must support report distribution + +## 4. Non-Functional Requirements + +### 4.1 Performance Requirements +- **NF1.1**: System must support concurrent users (100+) +- **NF1.2**: Page load time must be under 3 seconds +- **NF1.3**: API response time must be under 1 second +- **NF1.4**: System must handle 10,000+ job postings +- **NF1.5**: System must handle 100,000+ candidate records + +### 4.2 Security Requirements +- **NF2.1**: All data must be encrypted in transit and at rest +- **NF2.2**: System must support role-based access control +- **NF2.3**: System must maintain audit logs for all actions +- **NF2.4**: System must comply with GDPR regulations +- **NF2.5**: System must protect against common web vulnerabilities + +### 4.3 Usability Requirements +- **NF3.1**: Interface must be intuitive and easy to use +- **NF3.2**: System must support both Arabic and English +- **NF3.3**: System must be responsive and mobile-friendly +- **NF3.4**: System must provide clear error messages +- **NF3.5**: System must support keyboard navigation + +### 4.4 Reliability Requirements +- **NF4.1**: System must have 99.9% uptime +- **NF4.2**: System must handle failures gracefully +- **NF4.3**: System must support data backup and recovery +- **NF4.4**: System must provide monitoring and alerts +- **NF4.5**: System must support load balancing + +### 4.5 Scalability Requirements +- **NF5.1**: System must scale horizontally +- **NF5.2**: System must handle peak loads +- **NF5.3**: System must support database sharding +- **NF5.4**: System must cache frequently accessed data +- **NF5.5**: System must support microservices architecture + +## 5. Integration Requirements + +### 5.1 External Integrations +- **INT1.1**: Zoom API for video conferencing +- **INT1.2**: LinkedIn API for job posting and profiles +- **INT1.3**: Email/SMS services for notifications +- **INT1.4**: Calendar systems for scheduling +- **INT1.5**: ERP systems for employee data + +### 5.2 Internal Integrations +- **INT2.1**: Single Sign-On (SSO) for authentication +- **INT2.2**: File storage system for documents +- **INT2.3**: Search engine for candidate matching +- **INT2.4**: Analytics platform for reporting +- **INT2.5**: Task queue for background processing + +## 6. Business Rules + +### 6.1 Job Posting Rules +- **BR1.1**: Job postings must be approved before publishing +- **BR1.2**: Application limits must be enforced per job +- **BR1.3**: Job postings must have required fields completed +- **BR1.4**: LinkedIn posts must follow platform guidelines +- **BR1.5**: Job postings must comply with equal opportunity laws + +### 6.2 Candidate Management Rules +- **BR2.1**: Candidates can only progress to next stage with approval +- **BR2.2**: Duplicate candidates must be prevented +- **BR2.3**: Candidate data must be kept confidential +- **BR2.4**: Communication must be tracked for all candidates +- **BR2.5**: Background checks must be completed before offers + +### 6.3 Interview Scheduling Rules +- **BR3.1**: Interviews must be scheduled during business hours +- **BR3.2**: Buffer time must be respected between interviews +- **BR3.3**: Interviewers must be available for scheduled times +- **BR3.4**: Cancellations must be handled according to policy +- **BR3.5**: Feedback must be collected after each interview + +### 6.4 Form Processing Rules +- **BR4.1**: Required fields must be validated before submission +- **BR4.2**: File uploads must be scanned for security +- **BR4.3**: Form submissions must be processed in order +- **BR4.4**: Duplicate submissions must be prevented +- **BR4.5**: Form data must be extracted accurately + +## 7. User Interface Requirements + +### 7.1 Design Principles +- **UI1.1**: Clean, modern interface with consistent branding +- **UI1.2**: Intuitive navigation with clear hierarchy +- **UI1.3**: Responsive design for all devices +- **UI1.4**: Accessibility compliance (WCAG 2.1) +- **UI1.5**: Fast loading with optimized performance + +### 7.2 Key Screens +- **UI2.1**: Dashboard with key metrics and quick actions +- **UI2.2**: Job posting creation and management interface +- **UI2.3**: Candidate pipeline with drag-and-drop stages +- **UI2.4**: Interview scheduling calendar view +- **UI2.5**: Form builder with drag-and-drop fields +- **UI2.6**: Reports and analytics with interactive charts +- **UI2.7**: Candidate profile with comprehensive information +- **UI2.8**: Meeting interface with Zoom integration + +### 7.3 Interaction Patterns +- **UI3.1**: Consistent button styles and behaviors +- **UI3.2**: Clear feedback for all user actions +- **UI3.3**: Progressive disclosure for complex forms +- **UI3.4**: Contextual help and tooltips +- **UI3.5**: Keyboard shortcuts for power users + +## 8. Data Management + +### 8.1 Data Storage +- **DM1.1**: All data must be stored securely +- **DM1.2**: Sensitive data must be encrypted +- **DM1.3**: Data must be backed up regularly +- **DM1.4**: Data retention policies must be enforced +- **DM1.5**: Data must be accessible for reporting + +### 8.2 Data Migration +- **DM2.1**: Support import from legacy systems +- **DM2.2**: Provide data validation during migration +- **DM2.3**: Support incremental data updates +- **DM2.4**: Maintain data integrity during migration +- **DM2.5**: Provide rollback capabilities + +### 8.3 Data Quality +- **DM3.1**: Implement data validation rules +- **DM3.2**: Provide data cleansing tools +- **DM3.3**: Monitor data quality metrics +- **DM3.4**: Handle duplicate data detection +- **DM3.5**: Support data standardization + +## 9. Implementation Plan + +### 9.1 Development Phases +#### Phase 1: Core Functionality (Months 1-3) +- User authentication and authorization +- Basic job posting and management +- Candidate database and pipeline +- Basic reporting dashboards +- Form builder with essential fields + +#### Phase 2: Enhanced Features (Months 4-6) +- Interview scheduling and Zoom integration +- LinkedIn integration for job posting +- Advanced reporting and analytics +- Candidate matching and scoring +- Mobile-responsive design + +#### Phase 3: Advanced Features (Months 7-9) +- AI-powered candidate matching +- Advanced form builder with conditions +- Integration with external systems +- Performance optimization +- Security hardening + +#### Phase 4: Production Readiness (Months 10-12) +- Load testing and performance optimization +- Security audit and compliance +- Documentation and training materials +- Beta testing with real users +- Production deployment + +### 9.2 Team Structure +- **Project Manager**: Overall project coordination +- **Product Owner**: Requirements and backlog management +- **UI/UX Designer**: Interface design and user experience +- **Backend Developers**: Server-side development +- **Frontend Developers**: Client-side development +- **QA Engineers**: Testing and quality assurance +- **DevOps Engineers**: Deployment and infrastructure +- **Business Analyst**: Requirements gathering and analysis + +### 9.3 Technology Stack +- **Frontend**: HTML5, CSS3, JavaScript, Bootstrap 5, HTMX +- **Backend**: Django 5.2.1, Python 3.11 +- **Database**: PostgreSQL (production), SQLite (development) +- **APIs**: Django REST Framework +- **Authentication**: Django Allauth, OAuth 2.0 +- **Real-time**: HTMX, WebSocket +- **Task Queue**: Celery with Redis +- **Storage**: Local filesystem, AWS S3 +- **Monitoring**: Prometheus, Grafana +- **CI/CD**: Docker, Kubernetes + +## 10. Success Metrics + +### 10.1 Business Metrics +- **BM1.1**: Reduce time-to-hire by 30% +- **BM1.2**: Improve candidate quality by 25% +- **BM1.3**: Increase recruiter efficiency by 40% +- **BM1.4**: Reduce recruitment costs by 20% +- **BM1.5**: Improve candidate satisfaction by 35% + +### 10.2 Technical Metrics +- **TM1.1**: System uptime of 99.9% +- **TM1.2**: Page load time under 3 seconds +- **TM1.3**: API response time under 1 second +- **TM1.4**: 0 critical security vulnerabilities +- **TM1.5**: 95% test coverage + +### 10.3 User Adoption Metrics +- **UM1.1**: 90% of target users actively using the system +- **UM1.2**: 80% reduction in manual processes +- **UM1.3**: 75% improvement in user satisfaction +- **UM1.4**: 50% reduction in recruitment time +- **UM1.5**: 95% data accuracy in the system + +## 11. Risk Assessment + +### 11.1 Technical Risks +- **TR1.1**: Integration complexity with external systems +- **TR1.2**: Performance issues with large datasets +- **TR1.3**: Security vulnerabilities in third-party APIs +- **TR1.4**: Data migration challenges +- **TR1.5**: Scalability concerns + +### 11.2 Business Risks +- **BR1.1**: User resistance to new system +- **BR1.2**: Changes in recruitment processes +- **BR1.3**: Budget constraints +- **BR1.4**: Timeline delays +- **BR1.5**: Regulatory changes + +### 11.3 Mitigation Strategies +- **MS1.1**: Phased implementation with user feedback +- **MS1.2**: Regular performance testing and optimization +- **MS1.3**: Security audits and penetration testing +- **MS1.4**: Comprehensive training and support +- **MS1.5**: Flexible architecture for future changes + +## 12. Training & Support + +### 12.1 User Training +- **TU1.1**: Role-based training programs +- **TU1.2**: Online documentation and help guides +- **TU1.3**: Video tutorials for key features +- **TU1.4**: In-person training sessions +- **TU1.5**: Refresher courses and updates + +### 12.2 Technical Support +- **TS1.1**: Helpdesk with dedicated support staff +- **TS1.2**: Online ticketing system +- **TS1.3**: Remote support capabilities +- **TS1.4**: Knowledge base and FAQs +- **TS1.5**: 24/7 support for critical issues + +### 12.3 System Maintenance +- **SM1.1**: Regular system updates and patches +- **SM1.2**: Performance monitoring and optimization +- **SM1.3**: Data backup and recovery procedures +- **SM1.4**: System health checks +- **SM1.5**: Continuous improvement based on feedback + +--- + +*Document Version: 1.0* +*Last Updated: October 17, 2025* diff --git a/ATS_PROJECT_HLD.md b/ATS_PROJECT_HLD.md new file mode 100644 index 0000000..8d3ae2c --- /dev/null +++ b/ATS_PROJECT_HLD.md @@ -0,0 +1,241 @@ +# KAAUH Applicant Tracking System (ATS) - High Level Design Document + +## 1. Executive Summary + +This document outlines the High-Level Design (HLD) for the King Abdulaziz University Hospital (KAAUH) Applicant Tracking System (ATS). The system is designed to streamline the recruitment process by providing comprehensive tools for job posting, candidate management, interview scheduling, and integration with external platforms. + +## 2. System Overview + +### 2.1 Vision +To create a modern, efficient, and user-friendly recruitment management system that automates and optimizes the hiring process at KAAUH. + +### 2.2 Mission +The ATS aims to: +- Centralize recruitment activities +- Improve candidate experience +- Enhance recruiter efficiency +- Provide data-driven insights +- Integrate with external platforms (Zoom, LinkedIn, ERP) + +### 2.3 Goals +- Reduce time-to-hire +- Improve candidate quality +- Enhance reporting and analytics +- Provide seamless user experience +- Ensure system scalability and maintainability + +## 3. Architecture Overview + +### 3.1 Technology Stack +- **Backend**: Django 5.2.1 (Python) +- **Frontend**: HTML5, CSS3, JavaScript, Bootstrap 5 +- **Database**: SQLite (development), PostgreSQL (production) +- **APIs**: REST API with Django REST Framework +- **Real-time**: HTMX for dynamic UI updates +- **Authentication**: Django Allauth with OAuth (LinkedIn) +- **File Storage**: Local filesystem +- **Task Queue**: Celery with Redis +- **Communication**: Email, Webhooks (Zoom) + +### 3.2 System Architecture +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ Web Browser │ │ Mobile App │ │ Admin Panel │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ + │ │ │ + └───────────────────────┼───────────────────────┘ + │ + ┌─────────────────┐ + │ Load Balancer │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ Web Server │ + │ (Gunicorn) │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ Application │ + │ (Django) │ + └─────────────────┘ + │ │ + ┌───────────────┴─────────┐ ┌─────┴────────────────┐ + │ Database Layer │ │ External Services│ + │ (SQLite/PostgreSQL) │ │ (Zoom, LinkedIn) │ + └─────────────────────────┘ └─────────────────────┘ +``` + +## 4. Core Components + +### 4.1 User Management +- **Role-based Access Control**: + - System Administrators + - Hiring Managers + - Recruiters + - Interviewers + - Candidates +- **Authentication**: + - User registration and login + - LinkedIn OAuth integration + - Session management + +### 4.2 Job Management +- **Job Posting**: + - Create, edit, delete job postings + - Job templates and cloning + - Multi-language support + - Approval workflows +- **Job Distribution**: + - LinkedIn integration + - Career page management + - Application tracking + +### 4.3 Candidate Management +- **Candidate Database**: + - Profile management + - Resume parsing and storage + - Skills assessment + - Candidate scoring +- **Candidate Tracking**: + - Application status tracking + - Stage transitions + - Communication logging + - Candidate relationship management + +### 4.4 Interview Management +- **Scheduling**: + - Automated interview scheduling + - Calendar integration + - Time slot management + - Buffer time configuration +- **Video Interviews**: + - Zoom API integration + - Meeting creation and management + - Recording and playback + - Interview feedback collection + +### 4.5 Form Builder +- **Dynamic Forms**: + - Multi-stage form creation + - Custom field types + - Validation rules + - File upload support +- **Application Processing**: + - Form submission handling + - Data extraction and storage + - Notification systems + +### 4.6 Reporting and Analytics +- **Dashboards**: + - Executive dashboard + - Recruitment metrics + - Candidate analytics + - Department-specific reports +- **Data Export**: + - CSV, Excel, PDF exports + - Custom report generation + - Scheduled reports + +## 5. Integration Architecture + +### 5.1 External API Integrations +- **Zoom Video Conferencing**: + - Meeting creation and management + - Webhook event handling + - Recording and transcription +- **LinkedIn Recruitment**: + - Job posting automation + - Profile synchronization + - Analytics tracking +- **ERP Systems**: + - Employee data synchronization + - Position management + - Financial integration + +### 5.2 Internal Integrations +- **Email System**: + - Automated notifications + - Interview reminders + - Status updates +- **Calendar System**: + - Interview scheduling + - Availability management + - Conflict detection + +## 6. Security Architecture + +### 6.1 Authentication & Authorization +- Multi-factor authentication support +- Role-based access control +- JWT token authentication +- OAuth 2.0 integration + +### 6.2 Data Protection +- Data encryption at rest and in transit +- Secure file storage +- Personal data protection +- Audit logging + +### 6.3 System Security +- Input validation and sanitization +- SQL injection prevention +- XSS protection +- CSRF protection +- Rate limiting + +## 7. Scalability & Performance + +### 7.1 Performance Optimization +- Database indexing +- Query optimization +- Caching strategies (Redis) +- Asynchronous task processing (Celery) + +### 7.2 Scalability Considerations +- Horizontal scaling support +- Load balancing +- Database replication +- Microservices-ready architecture + +## 8. Deployment & Operations + +### 8.1 Deployment Strategy +- Container-based deployment (Docker) +- Environment management +- CI/CD pipeline +- Automated testing + +### 8.2 Monitoring & Maintenance +- Application monitoring +- Performance metrics +- Error tracking +- Automated backups + +## 9. Future Roadmap + +### 9.1 Phase 1 (Current) +- Core ATS functionality +- Basic reporting +- Zoom and LinkedIn integration +- Mobile-responsive design + +### 9.2 Phase 2 (Next 6 months) +- Advanced analytics +- AI-powered candidate matching +- Enhanced reporting +- Mobile app development + +### 9.3 Phase 3 (Next 12 months) +- Voice interview support +- Video interview AI analysis +- Advanced integrations +- Multi-tenant support + +## 10. Conclusion + +The KAAUH ATS system is designed to be a comprehensive, modern, and scalable solution for managing the recruitment lifecycle. By leveraging Django's robust framework and integrating with external platforms, the system will significantly improve recruitment efficiency and provide valuable insights for decision-making. + +--- + +*Document Version: 1.0* +*Last Updated: October 17, 2025* diff --git a/ATS_PROJECT_LLD.md b/ATS_PROJECT_LLD.md new file mode 100644 index 0000000..f0337f9 --- /dev/null +++ b/ATS_PROJECT_LLD.md @@ -0,0 +1,1083 @@ +# KAAUH Applicant Tracking System (ATS) - Low Level Design Document + +## 1. Introduction + +This document provides the Low-Level Design (LLD) for the KAAUH Applicant Tracking System (ATS). It details the technical specifications, database schema, API endpoints, and implementation details for the system. + +## 2. Database Design + +### 2.1 Entity-Relationship Diagram (ERD) + +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ JobPosting │ │ Candidate │ │ ZoomMeeting │ +├─────────────────┤ ├─────────────────┤ ├─────────────────┤ +│ id (PK) │ │ id (PK) │ │ id (PK) │ +│ slug │ │ slug │ │ slug │ +│ title │ │ first_name │ │ topic │ +│ department │ │ last_name │ │ meeting_id │ +│ job_type │ │ email │ │ start_time │ +│ workplace_type │ │ phone │ │ duration │ +│ location_city │ │ address │ │ timezone │ +│ location_state │ │ resume │ │ join_url │ +│ location_country│ │ is_resume_parsed│ │ password │ +│ description │ │ stage │ │ status │ +│ qualifications │ │ exam_status │ │ created_at │ +│ salary_range │ │ interview_status│ │ updated_at │ +│ benefits │ │ offer_status │ │ │ +│ application_url │ │ match_score │ │ │ +│ status │ │ strengths │ │ │ +│ created_by │ │ weaknesses │ │ │ +│ created_at │ │ job (FK) │ │ │ +│ updated_at │ │ │ │ │ +│ │ │ │ │ │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ + │ │ │ + └───────────────────────┼───────────────────────┘ + │ + ┌─────────────────┐ + │ ScheduledInterview │ + ├─────────────────┤ + │ id (PK) │ + │ candidate (FK) │ + │ job (FK) │ + │ zoom_meeting (FK)│ + │ interview_date │ + │ interview_time │ + │ status │ + │ created_at │ + │ updated_at │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ FormTemplate │ + ├─────────────────┤ + │ id (PK) │ + │ slug │ + │ name │ + │ description │ + │ job (FK) │ + │ is_active │ + │ created_by (FK) │ + │ created_at │ + │ updated_at │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ FormStage │ + ├─────────────────┤ + │ id (PK) │ + │ name │ + │ order │ + │ is_predefined │ + │ template (FK) │ + │ created_at │ + │ updated_at │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ FormField │ + ├─────────────────┤ + │ id (PK) │ + │ label │ + │ field_type │ + │ placeholder │ + │ required │ + │ order │ + │ options │ + │ file_types │ + │ max_file_size │ + │ stage (FK) │ + │ created_at │ + │ updated_at │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ FormSubmission │ + ├─────────────────┤ + │ id (PK) │ + │ slug │ + │ template (FK) │ + │ submitted_by (FK)│ + │ submitted_at │ + │ applicant_name │ + │ applicant_email │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ FieldResponse │ + ├─────────────────┤ + │ id (PK) │ + │ submission (FK) │ + │ field (FK) │ + │ value │ + │ uploaded_file │ + │ created_at │ + │ updated_at │ + └─────────────────┘ + │ + ┌─────────────────┐ + │ MeetingComment │ + ├─────────────────┤ + │ id (PK) │ + │ meeting (FK) │ + │ author (FK) │ + │ content │ + │ created_at │ + │ updated_at │ + └─────────────────┘ +``` + +### 2.2 Detailed Schema Definitions + +#### 2.2.1 Base Model +```python +class Base(models.Model): + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + slug = RandomCharField(length=8, unique=True, editable=False) +``` + +#### 2.2.2 JobPosting Model +```python +class JobPosting(Base): + JOB_TYPES = [ + ("FULL_TIME", "Full-time"), + ("PART_TIME", "Part-time"), + ("CONTRACT", "Contract"), + ("INTERNSHIP", "Internship"), + ("FACULTY", "Faculty"), + ("TEMPORARY", "Temporary"), + ] + + WORKPLACE_TYPES = [ + ("ON_SITE", "On-site"), + ("REMOTE", "Remote"), + ("HYBRID", "Hybrid"), + ] + + STATUS_CHOICES = [ + ("DRAFT", "Draft"), + ("ACTIVE", "Active"), + ("CLOSED", "Closed"), + ("CANCELLED", "Cancelled"), + ("ARCHIVED", "Archived"), + ] + + title = models.CharField(max_length=200) + department = models.CharField(max_length=100, blank=True) + job_type = models.CharField(max_length=20, choices=JOB_TYPES, default="FULL_TIME") + workplace_type = models.CharField(max_length=20, choices=WORKPLACE_TYPES, default="ON_SITE") + location_city = models.CharField(max_length=100, blank=True) + location_state = models.CharField(max_length=100, blank=True) + location_country = models.CharField(max_length=100, default="Saudia Arabia") + description = CKEditor5Field(config_name='extends') + qualifications = CKEditor5Field(blank=True, config_name='extends') + salary_range = models.CharField(max_length=200, blank=True) + benefits = CKEditor5Field(blank=True, config_name='extends') + application_url = models.URLField(blank=True) + application_start_date = models.DateField(null=True, blank=True) + application_deadline = models.DateField(null=True, blank=True) + application_instructions = CKEditor5Field(blank=True, config_name='extends') + internal_job_id = models.CharField(max_length=50, primary_key=True, editable=False) + created_by = models.CharField(max_length=100, blank=True) + status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="DRAFT") + hash_tags = models.CharField(max_length=200, blank=True, validators=[validate_hash_tags]) + linkedin_post_id = models.CharField(max_length=200, blank=True) + linkedin_post_url = models.URLField(blank=True) + posted_to_linkedin = models.BooleanField(default=False) + linkedin_post_status = models.CharField(max_length=50, blank=True) + linkedin_posted_at = models.DateTimeField(null=True, blank=True) + published_at = models.DateTimeField(null=True, blank=True) + position_number = models.CharField(max_length=50, blank=True) + reporting_to = models.CharField(max_length=100, blank=True) + joining_date = models.DateField(null=True, blank=True) + open_positions = models.PositiveIntegerField(default=1) + source = models.ForeignKey("Source", on_delete=models.SET_NULL, null=True, blank=True) + max_applications = models.PositiveIntegerField(default=1000) + hiring_agency = models.ManyToManyField("HiringAgency", blank=True) + cancel_reason = models.TextField(blank=True) + cancelled_by = models.CharField(max_length=100, blank=True) + cancelled_at = models.DateTimeField(null=True, blank=True) +``` + +#### 2.2.3 Candidate Model +```python +class Candidate(Base): + class Stage(models.TextChoices): + APPLIED = "Applied", _("Applied") + EXAM = "Exam", _("Exam") + INTERVIEW = "Interview", _("Interview") + OFFER = "Offer", _("Offer") + + class ExamStatus(models.TextChoices): + PASSED = "Passed", _("Passed") + FAILED = "Failed", _("Failed") + + class Status(models.TextChoices): + ACCEPTED = "Accepted", _("Accepted") + REJECTED = "Rejected", _("Rejected") + + class ApplicantType(models.TextChoices): + APPLICANT = "Applicant", _("Applicant") + CANDIDATE = "Candidate", _("Candidate") + + STAGE_SEQUENCE = { + "Applied": ["Exam", "Interview", "Offer"], + "Exam": ["Interview", "Offer"], + "Interview": ["Offer"], + "Offer": [], + } + + job = models.ForeignKey(JobPosting, on_delete=models.CASCADE, related_name="candidates") + first_name = models.CharField(max_length=255) + last_name = models.CharField(max_length=255) + email = models.EmailField() + phone = models.CharField(max_length=20) + address = models.TextField(max_length=200) + resume = models.FileField(upload_to="resumes/") + is_resume_parsed = models.BooleanField(default=False) + is_potential_candidate = models.BooleanField(default=False) + parsed_summary = models.TextField(blank=True) + applied = models.BooleanField(default=False) + stage = models.CharField(max_length=100, default="Applied", choices=Stage.choices) + applicant_status = models.CharField(max_length=100, default="Applicant", choices=ApplicantType.choices) + exam_date = models.DateTimeField(null=True, blank=True) + exam_status = models.CharField(max_length=100, null=True, blank=True, choices=ExamStatus.choices) + interview_date = models.DateTimeField(null=True, blank=True) + interview_status = models.CharField(max_length=100, null=True, blank=True, choices=Status.choices) + offer_date = models.DateField(null=True, blank=True) + offer_status = models.CharField(max_length=100, null=True, blank=True, choices=Status.choices) + join_date = models.DateField(null=True, blank=True) + match_score = models.IntegerField(null=True, blank=True) + strengths = models.TextField(blank=True) + weaknesses = models.TextField(blank=True) + criteria_checklist = models.JSONField(default=dict, blank=True) + resume_parsed_category = models.TextField(blank=True) + submitted_by_agency = models.ForeignKey("HiringAgency", on_delete=models.SET_NULL, null=True, blank=True) +``` + +#### 2.2.4 ZoomMeeting Model +```python +class ZoomMeeting(Base): + class MeetingStatus(models.TextChoices): + SCHEDULED = "waiting", _("Waiting") + STARTED = "started", _("Started") + ENDED = "ended", _("Ended") + CANCELLED = "cancelled", _("Cancelled") + + topic = models.CharField(max_length=255) + meeting_id = models.CharField(max_length=20, unique=True) + start_time = models.DateTimeField() + duration = models.PositiveIntegerField() + timezone = models.CharField(max_length=50) + join_url = models.URLField() + participant_video = models.BooleanField(default=True) + password = models.CharField(max_length=20, blank=True, null=True) + join_before_host = models.BooleanField(default=False) + mute_upon_entry = models.BooleanField(default=False) + waiting_room = models.BooleanField(default=False) + zoom_gateway_response = models.JSONField(blank=True, null=True) + status = models.CharField(max_length=20, null=True, blank=True) +``` + +#### 2.2.5 FormTemplate Model +```python +class FormTemplate(Base): + job = models.OneToOneField(JobPosting, on_delete=models.CASCADE, related_name="form_template") + name = models.CharField(max_length=200) + description = models.TextField(blank=True) + created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="form_templates", null=True, blank=True) + is_active = models.BooleanField(default=False) +``` + +#### 2.2.6 FormStage Model +```python +class FormStage(Base): + template = models.ForeignKey(FormTemplate, on_delete=models.CASCADE, related_name="stages") + name = models.CharField(max_length=200) + order = models.PositiveIntegerField(default=0) + is_predefined = models.BooleanField(default=False) +``` + +#### 2.2.7 FormField Model +```python +class FormField(Base): + FIELD_TYPES = [ + ("text", "Text Input"), + ("email", "Email"), + ("phone", "Phone"), + ("textarea", "Text Area"), + ("file", "File Upload"), + ("date", "Date Picker"), + ("select", "Dropdown"), + ("radio", "Radio Buttons"), + ("checkbox", "Checkboxes"), + ] + + stage = models.ForeignKey(FormStage, on_delete=models.CASCADE, related_name="fields") + label = models.CharField(max_length=200) + field_type = models.CharField(max_length=20, choices=FIELD_TYPES) + placeholder = models.CharField(max_length=200, blank=True) + required = models.BooleanField(default=False) + order = models.PositiveIntegerField(default=0) + is_predefined = models.BooleanField(default=False) + options = models.JSONField(default=list, blank=True) + file_types = models.CharField(max_length=200, blank=True) + max_file_size = models.PositiveIntegerField(default=5) + multiple_files = models.BooleanField(default=False) + max_files = models.PositiveIntegerField(default=1) +``` + +#### 2.2.8 FormSubmission Model +```python +class FormSubmission(Base): + template = models.ForeignKey(FormTemplate, on_delete=models.CASCADE, related_name="submissions") + submitted_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name="form_submissions") + submitted_at = models.DateTimeField(auto_now_add=True) + applicant_name = models.CharField(max_length=200, blank=True) + applicant_email = models.EmailField(blank=True) +``` + +#### 2.2.9 FieldResponse Model +```python +class FieldResponse(Base): + submission = models.ForeignKey(FormSubmission, on_delete=models.CASCADE, related_name="responses") + field = models.ForeignKey(FormField, on_delete=models.CASCADE, related_name="responses") + value = models.JSONField(null=True, blank=True) + uploaded_file = models.FileField(upload_to="form_uploads/", null=True, blank=True) +``` + +#### 2.2.10 ScheduledInterview Model +```python +class ScheduledInterview(Base): + candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="scheduled_interviews") + job = models.ForeignKey(JobPosting, on_delete=models.CASCADE, related_name="scheduled_interviews") + zoom_meeting = models.OneToOneField(ZoomMeeting, on_delete=models.CASCADE, related_name="interview") + schedule = models.ForeignKey(InterviewSchedule, on_delete=models.CASCADE, related_name="interviews", null=True, blank=True) + interview_date = models.DateField() + interview_time = models.TimeField() + status = models.CharField(max_length=20, choices=[ + ("scheduled", "Scheduled"), + ("confirmed", "Confirmed"), + ("cancelled", "Cancelled"), + ("completed", "Completed"), + ], default="scheduled") +``` + +#### 2.2.11 InterviewSchedule Model +```python +class InterviewSchedule(Base): + job = models.ForeignKey(JobPosting, on_delete=models.CASCADE, related_name="interview_schedules") + candidates = models.ManyToManyField(Candidate, related_name="interview_schedules", blank=True, null=True) + start_date = models.DateField() + end_date = models.DateField() + working_days = models.JSONField() + start_time = models.TimeField() + end_time = models.TimeField() + break_start_time = models.TimeField(null=True, blank=True) + break_end_time = models.TimeField(null=True, blank=True) + interview_duration = models.PositiveIntegerField() + buffer_time = models.PositiveIntegerField(default=0) + created_by = models.ForeignKey(User, on_delete=models.CASCADE) +``` + +#### 2.2.12 MeetingComment Model +```python +class MeetingComment(Base): + meeting = models.ForeignKey(ZoomMeeting, on_delete=models.CASCADE, related_name="comments") + author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="meeting_comments") + content = CKEditor5Field(config_name='extends') +``` + +## 3. API Design + +### 3.1 REST API Endpoints + +#### 3.1.1 Job Posting Endpoints +``` +GET /api/jobs/ # List all job postings +POST /api/jobs/ # Create new job posting +GET /api/jobs/{id}/ # Get specific job posting +PUT /api/jobs/{id}/ # Update job posting +DELETE /api/jobs/{id}/ # Delete job posting +``` + +#### 3.1.2 Candidate Endpoints +``` +GET /api/candidates/ # List all candidates +POST /api/candidates/ # Create new candidate +GET /api/candidates/{id}/ # Get specific candidate +PUT /api/candidates/{id}/ # Update candidate +DELETE /api/candidates/{id}/ # Delete candidate +GET /api/candidates/job/{job_id}/ # Get candidates for specific job +``` + +#### 3.1.3 Meeting Endpoints +``` +GET /api/meetings/ # List all meetings +POST /api/meetings/ # Create new meeting +GET /api/meetings/{id}/ # Get specific meeting +PUT /api/meetings/{id}/ # Update meeting +DELETE /api/meetings/{id}/ # Delete meeting +POST /api/meetings/{id}/join/ # Join meeting +``` + +#### 3.1.4 Form Template Endpoints +``` +GET /api/templates/ # List form templates +POST /api/templates/ # Create form template +GET /api/templates/{id}/ # Get specific template +PUT /api/templates/{id}/ # Update template +DELETE /api/templates/{id}/ # Delete template +POST /api/templates/{id}/submit/ # Submit form +``` + +### 3.2 WebSocket Events (HTMX) + +#### 3.2.1 Real-time Updates +```javascript +// Meeting status updates +event: 'meeting:status_update' +data: { meeting_id: '123', status: 'started' } + +// Candidate status updates +event: 'candidate:stage_update' +data: { candidate_id: '456', stage: 'Interview' } + +// Interview schedule updates +event: 'interview:schedule_update' +data: { interview_id: '789', date: '2025-10-20' } +``` + +## 4. Authentication & Authorization + +### 4.1 Authentication Flow +```python +# Authentication Middleware +class CustomAuthenticationMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # Check for session authentication + if 'user_id' in request.session: + request.user = get_user_from_session(request.session['user_id']) + # Check for JWT token + elif 'Authorization' in request.headers: + request.user = authenticate_jwt(request.headers['Authorization']) + else: + request.user = AnonymousUser() + + return self.get_response(request) +``` + +### 4.2 Permission Classes +```python +# Custom Permission Classes +class IsHiringManager(permissions.BasePermission): + def has_permission(self, request, view): + return request.user.groups.filter(name='Hiring Managers').exists() + +class IsRecruiter(permissions.BasePermission): + def has_permission(self, request, view): + return request.user.groups.filter(name='Recruiters').exists() + +class IsInterviewer(permissions.BasePermission): + def has_permission(self, request, view): + return request.user.groups.filter(name='Interviewers').exists() + +class IsCandidate(permissions.BasePermission): + def has_permission(self, request, view): + return request.user.groups.filter(name='Candidates').exists() +``` + +## 5. Business Logic Implementation + +### 5.1 Candidate Stage Transitions +```python +class CandidateService: + @staticmethod + def advance_candidate_stage(candidate, new_stage): + """Advance candidate to new stage with validation""" + if new_stage not in candidate.get_available_stages(): + raise ValidationError(f"Cannot advance from {candidate.stage} to {new_stage}") + + old_stage = candidate.stage + candidate.stage = new_stage + + # Auto-set exam date when moving to Exam stage + if new_stage == "Exam" and not candidate.exam_date: + candidate.exam_date = timezone.now() + timedelta(days=7) + + # Auto-set interview date when moving to Interview stage + if new_stage == "Interview" and not candidate.interview_date: + candidate.interview_date = timezone.now() + timedelta(days=14) + + # Auto-set offer date when moving to Offer stage + if new_stage == "Offer" and not candidate.offer_date: + candidate.offer_date = timezone.now() + timedelta(days=3) + + candidate.save() + + # Log stage transition + StageTransition.objects.create( + candidate=candidate, + old_stage=old_stage, + new_stage=new_stage, + changed_by=candidate.changed_by + ) + + return candidate +``` + +### 5.2 Interview Scheduling Logic +```python +class InterviewScheduler: + @staticmethod + def get_available_slots(schedule, date): + """Get available interview slots for a specific date""" + # Get working hours + start_time = datetime.combine(date, schedule.start_time) + end_time = datetime.combine(date, schedule.end_time) + + # Apply break times + if schedule.break_start_time and schedule.break_end_time: + break_start = datetime.combine(date, schedule.break_start_time) + break_end = datetime.combine(date, schedule.break_end_time) + end_time = break_start # Remove break time from available slots + + # Calculate available slots + slots = [] + current_time = start_time + + while current_time < end_time: + slot_end = current_time + timedelta(minutes=schedule.interview_duration + schedule.buffer_time) + if slot_end <= end_time: + slots.append({ + 'start': current_time.time(), + 'end': slot_end.time(), + 'available': True + }) + current_time = slot_end + + # Filter out booked slots + booked_slots = ScheduledInterview.objects.filter( + interview_date=date, + job=schedule.job + ).values_list('interview_time', 'interview_time') + + for slot in slots: + if slot['start'] in booked_slots: + slot['available'] = False + + return slots + + @staticmethod + def schedule_interview(candidate, job, schedule_data): + """Schedule an interview with candidate""" + # Create Zoom meeting + zoom_meeting = create_zoom_meeting( + topic=f"Interview: {job.title} with {candidate.name}", + start_time=schedule_data['start_time'], + duration=schedule_data['duration'] + ) + + # Create scheduled interview + interview = ScheduledInterview.objects.create( + candidate=candidate, + job=job, + zoom_meeting=zoom_meeting, + interview_date=schedule_data['start_date'], + interview_time=schedule_data['start_time'].time(), + status='scheduled' + ) + + return interview +``` + +### 5.3 Form Submission Processing +```python +class FormSubmissionService: + @staticmethod + def process_submission(template, submission_data, files=None): + """Process form submission and create candidate""" + with transaction.atomic(): + # Create submission record + submission = FormSubmission.objects.create( + template=template, + applicant_name=submission_data.get('applicant_name', ''), + applicant_email=submission_data.get('applicant_email', '') + ) + + # Process field responses + for field_id, value in submission_data.items(): + if field_id.startswith('field_'): + field_id = field_id.replace('field_', '') + try: + field = FormField.objects.get(id=field_id, stage__template=template) + response = FieldResponse.objects.create( + submission=submission, + field=field, + value=value if value else None + ) + + # Handle file uploads + if field.field_type == 'file' and files: + file_key = f'field_{field_id}' + if file_key in files: + response.uploaded_file = files[file_key] + response.save() + except FormField.DoesNotExist: + continue + + # Create candidate if required fields are present + try: + first_name = submission.responses.get(field__label='First Name') + last_name = submission.responses.get(field__label='Last Name') + email = submission.responses.get(field__label='Email Address') + phone = submission.responses.get(field__label='Phone Number') + address = submission.responses.get(field__label='Address') + resume = submission.responses.get(field__label='Resume Upload') + + candidate = Candidate.objects.create( + first_name=first_name.display_value, + last_name=last_name.display_value, + email=email.display_value, + phone=phone.display_value, + address=address.display_value, + resume=resume.get_file if resume.is_file else None, + job=template.job + ) + + return submission, candidate + except Exception as e: + logger.error(f"Candidate creation failed: {e}") + return submission, None +``` + +## 6. Error Handling Strategy + +### 6.1 Custom Exception Classes +```python +class ATSException(Exception): + """Base exception for ATS system""" + pass + +class CandidateStageTransitionError(ATSException): + """Raised when candidate stage transition fails""" + pass + +class InterviewSchedulingError(ATSException): + """Raised when interview scheduling fails""" + pass + +class FormSubmissionError(ATSException): + """Raised when form submission processing fails""" + pass + +class ZoomAPIError(ATSException): + """Raised when Zoom API calls fail""" + pass + +class LinkedInAPIError(ATSException): + """Raised when LinkedIn API calls fail""" + pass +``` + +### 6.2 Error Response Format +```python +class ErrorResponse: + def __init__(self, error_code, message, details=None): + self.error_code = error_code + self.message = message + self.details = details + self.timestamp = timezone.now() + + def to_dict(self): + return { + 'error': { + 'code': self.error_code, + 'message': self.message, + 'details': self.details, + 'timestamp': self.timestamp.isoformat() + } + } +``` + +## 7. Caching Strategy + +### 7.1 Cache Configuration +```python +# settings.py +CACHES = { + 'default': { + 'BACKEND': 'django_redis.cache.RedisCache', + 'LOCATION': 'redis://127.0.0.1:6379/1', + 'OPTIONS': { + 'CLIENT_CLASS': 'django_redis.client.DefaultClient', + } + } +} + +# Cache timeouts +CACHE_TIMEOUTS = { + 'job_listings': 60 * 15, # 15 minutes + 'candidate_profiles': 60 * 30, # 30 minutes + 'meeting_details': 60 * 5, # 5 minutes + 'form_templates': 60 * 60, # 1 hour +} +``` + +### 7.2 Cache Implementation +```python +class CacheService: + @staticmethod + def get_or_set(key, func, timeout=None): + """Get from cache or set if not exists""" + cached_value = cache.get(key) + if cached_value is None: + cached_value = func() + cache.set(key, cached_value, timeout or CACHE_TIMEOUTS.get(key, 300)) + return cached_value + + @staticmethod + def invalidate_pattern(pattern): + """Invalidate all keys matching pattern""" + keys = cache.keys(pattern) + if keys: + cache.delete_many(keys) +``` + +## 8. Logging Strategy + +### 8.1 Logging Configuration +```python +# settings.py +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'verbose': { + 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', + 'style': '{', + }, + 'simple': { + 'format': '{levelname} {message}', + 'style': '{', + }, + }, + 'handlers': { + 'file': { + 'level': 'INFO', + 'class': 'logging.FileHandler', + 'filename': 'logs/ats.log', + 'formatter': 'verbose', + }, + 'console': { + 'level': 'DEBUG', + 'class': 'logging.StreamHandler', + 'formatter': 'simple', + }, + }, + 'loggers': { + 'ats': { + 'handlers': ['file', 'console'], + 'level': 'DEBUG', + 'propagate': False, + }, + }, +} +``` + +### 8.2 Audit Logging +```python +class AuditLogger: + @staticmethod + def log_action(user, action, model, instance_id, details=None): + """Log user actions for audit trail""" + AuditLog.objects.create( + user=user, + action=action, + model=model, + instance_id=instance_id, + details=details + ) + + @staticmethod + def log_candidate_stage_transition(candidate, old_stage, new_stage, user): + """Log candidate stage transitions""" + CandidateStageTransition.objects.create( + candidate=candidate, + old_stage=old_stage, + new_stage=new_stage, + changed_by=user + ) +``` + +## 9. Security Implementation + +### 9.1 Data Encryption +```python +from cryptography.fernet import Fernet + +class EncryptionService: + def __init__(self): + self.key = Fernet.generate_key() + self.cipher = Fernet(self.key) + + def encrypt(self, data): + """Encrypt sensitive data""" + return self.cipher.encrypt(data.encode()).decode() + + def decrypt(self, encrypted_data): + """Decrypt sensitive data""" + return self.cipher.decrypt(encrypted_data.encode()).decode() +``` + +### 9.2 File Upload Security +```python +class SecureFileUpload: + @staticmethod + def validate_file(file): + """Validate uploaded file for security""" + # Check file size + if file.size > 10 * 1024 * 1024: # 10MB + raise ValidationError("File size exceeds 10MB limit") + + # Check file type + allowed_types = [ + 'application/pdf', + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + ] + if file.content_type not in allowed_types: + raise ValidationError("Invalid file type") + + # Scan for malware (placeholder) + if not SecureFileUpload.scan_malware(file): + raise ValidationError("File contains malicious content") + + return True + + @staticmethod + def scan_malware(file): + """Placeholder for malware scanning""" + # Implement actual malware scanning logic + return True +``` + +## 10. Testing Strategy + +### 10.1 Unit Test Structure +```python +class CandidateTestCase(TestCase): + def setUp(self): + self.job = JobPosting.objects.create( + title="Software Engineer", + department="IT", + status="ACTIVE" + ) + self.candidate = Candidate.objects.create( + first_name="John", + last_name="Doe", + email="john@example.com", + phone="1234567890", + job=self.job + ) + + def test_candidate_stage_transition(self): + """Test candidate stage transitions""" + # Test valid transition + self.candidate.stage = "Exam" + self.candidate.save() + self.assertEqual(self.candidate.stage, "Exam") + + # Test invalid transition + with self.assertRaises(ValidationError): + self.candidate.stage = "Offer" + self.candidate.save() +``` + +### 10.2 Integration Tests +```python +class InterviewSchedulingTestCase(TestCase): + def setUp(self): + self.job = JobPosting.objects.create( + title="Product Manager", + department="Product", + status="ACTIVE" + ) + self.candidate = Candidate.objects.create( + first_name="Jane", + last_name="Smith", + email="jane@example.com", + phone="9876543210", + job=self.job + ) + self.schedule = InterviewSchedule.objects.create( + job=self.job, + start_date=timezone.now().date(), + end_date=timezone.now().date() + timedelta(days=7), + working_days=[0, 1, 2, 3, 4], + start_time=time(9, 0), + end_time=time(17, 0), + interview_duration=60, + buffer_time=15, + created_by=self.user + ) + + def test_interview_scheduling(self): + """Test interview scheduling process""" + # Test slot availability + available_slots = InterviewScheduler.get_available_slots( + self.schedule, + timezone.now().date() + ) + self.assertGreater(len(available_slots), 0) + + # Test interview scheduling + schedule_data = { + 'start_date': timezone.now().date(), + 'start_time': timezone.now().time(), + 'duration': 60 + } + interview = InterviewScheduler.schedule_interview( + self.candidate, + self.job, + schedule_data + ) + self.assertIsNotNone(interview) +``` + +## 11. Deployment Configuration + +### 11.1 Production Settings +```python +# settings/production.py +DEBUG = False +ALLOWED_HOSTS = ['your-domain.com'] +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': 'ats_db', + 'USER': 'ats_user', + 'PASSWORD': 'secure_password', + 'HOST': 'localhost', + 'PORT': '5432', + } +} +STATIC_ROOT = '/var/www/ats/static/' +MEDIA_ROOT = '/var/www/ats/media/' +SECURE_SSL_REDIRECT = True +SESSION_COOKIE_SECURE = True +CSRF_COOKIE_SECURE = True +``` + +### 11.2 Docker Configuration +```dockerfile +# Dockerfile +FROM python:3.11-slim + +WORKDIR /app +COPY requirements.txt . +RUN pip install -r requirements.txt + +COPY . . +EXPOSE 8000 + +CMD ["gunicorn", "--bind", "0.0.0.0:8000", "kaauh_ats.wsgi:application"] +``` + +```yaml +# docker-compose.yml +version: '3.8' +services: + web: + build: . + ports: + - "8000:8000" + depends_on: + - db + - redis + environment: + - DEBUG=0 + - DATABASE_URL=postgresql://ats_user:secure_password@db:5432/ats_db + - REDIS_URL=redis://redis:6379/0 + + db: + image: postgres:13 + environment: + - POSTGRES_DB=ats_db + - POSTGRES_USER=ats_user + - POSTGRES_PASSWORD=secure_password + volumes: + - postgres_data:/var/lib/postgresql/data + + redis: + image: redis:6-alpine + volumes: + - redis_data:/data + +volumes: + postgres_data: + redis_data: +``` + +## 12. Monitoring & Analytics + +### 12.1 Performance Monitoring +```python +# monitoring.py +class PerformanceMonitor: + @staticmethod + def track_performance(func): + """Decorator to track function performance""" + def wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + + # Log performance metrics + PerformanceMetric.objects.create( + function_name=func.__name__, + execution_time=end_time - start_time, + timestamp=timezone.now() + ) + + return result + return wrapper +``` + +### 12.2 Analytics Dashboard +```python +# analytics.py +class AnalyticsService: + @staticmethod + def get_recruitment_metrics(): + """Get recruitment performance metrics""" + return { + 'total_jobs': JobPosting.objects.count(), + 'active_jobs': JobPosting.objects.filter(status='ACTIVE').count(), + 'total_candidates': Candidate.objects.count(), + 'conversion_rate': AnalyticsService.calculate_conversion_rate(), + 'time_to_hire': AnalyticsService.calculate_average_time_to_hire(), + 'source_effectiveness': AnalyticsService.get_source_effectiveness() + } + + @staticmethod + def calculate_conversion_rate(): + """Calculate candidate conversion rate""" + total_candidates = Candidate.objects.count() + hired_candidates = Candidate.objects.filter( + stage='Offer', + offer_status='Accepted' + ).count() + + return (hired_candidates / total_candidates * 100) if total_candidates > 0 else 0 +``` + +--- + +*Document Version: 1.0* +*Last Updated: October 17, 2025* diff --git a/NorahUniversity/__pycache__/settings.cpython-313.pyc b/NorahUniversity/__pycache__/settings.cpython-313.pyc index 73b3ff6..ceb77b7 100644 Binary files a/NorahUniversity/__pycache__/settings.cpython-313.pyc and b/NorahUniversity/__pycache__/settings.cpython-313.pyc differ diff --git a/NorahUniversity/__pycache__/urls.cpython-313.pyc b/NorahUniversity/__pycache__/urls.cpython-313.pyc index 180c130..27f06b2 100644 Binary files a/NorahUniversity/__pycache__/urls.cpython-313.pyc and b/NorahUniversity/__pycache__/urls.cpython-313.pyc differ diff --git a/NorahUniversity/settings.py b/NorahUniversity/settings.py index e2d8d8f..38db2a2 100644 --- a/NorahUniversity/settings.py +++ b/NorahUniversity/settings.py @@ -59,7 +59,6 @@ INSTALLED_APPS = [ 'django_q', 'widget_tweaks', 'easyaudit' - ] @@ -67,13 +66,13 @@ INSTALLED_APPS = [ SITE_ID = 1 -LOGIN_REDIRECT_URL = '/dashboard/' +LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_REDIRECT_URL = '/' -ACCOUNT_SIGNUP_REDIRECT_URL = '/dashboard/' +ACCOUNT_SIGNUP_REDIRECT_URL = '/' LOGIN_URL = '/accounts/login/' @@ -135,11 +134,14 @@ WSGI_APPLICATION = 'NorahUniversity.wsgi.application' DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': BASE_DIR / 'db.sqlite3', + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'norahuniversity', + 'USER': 'norahuniversity', + 'PASSWORD': 'norahuniversity', + 'HOST': '127.0.0.1', + 'PORT': '5432', } } - # Password validation # https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators @@ -249,6 +251,7 @@ Q_CLUSTER = { 'workers': 8, 'recycle': 500, 'timeout': 60, + 'max_attempts': 1, 'compress': True, 'save_limit': 250, 'queue_limit': 500, @@ -257,7 +260,7 @@ Q_CLUSTER = { 'redis': { 'host': '127.0.0.1', 'port': 6379, - 'db': 0, }, + 'db': 3, }, 'ALT_CLUSTERS': { 'long': { 'timeout': 3000, @@ -369,4 +372,4 @@ CKEDITOR_5_CONFIGS = { } # Define a constant in settings.py to specify file upload permissions -CKEDITOR_5_FILE_UPLOAD_PERMISSION = "staff" # Possible values: "staff", "authenticated", "any" \ No newline at end of file +CKEDITOR_5_FILE_UPLOAD_PERMISSION = "staff" # Possible values: "staff", "authenticated", "any" diff --git a/TESTING_GUIDE.md b/TESTING_GUIDE.md new file mode 100644 index 0000000..c4b77f3 --- /dev/null +++ b/TESTING_GUIDE.md @@ -0,0 +1,312 @@ +# Recruitment Application Testing Guide + +This guide provides comprehensive information about testing the Recruitment Application (ATS) system. + +## Test Structure + +The test suite is organized into several modules: + +### 1. Basic Tests (`recruitment/tests.py`) +- **BaseTestCase**: Common setup for all tests +- **ModelTests**: Basic model functionality tests +- **ViewTests**: Standard view tests +- **FormTests**: Basic form validation tests +- **IntegrationTests**: Simple integration scenarios + +### 2. Advanced Tests (`recruitment/tests_advanced.py`) +- **AdvancedModelTests**: Complex model scenarios and edge cases +- **AdvancedViewTests**: Complex view logic with multiple filters and workflows +- **AdvancedFormTests**: Complex form validation and dynamic fields +- **AdvancedIntegrationTests**: End-to-end workflows and concurrent operations +- **SecurityTests**: Security-focused testing + +### 3. Configuration Files +- **`pytest.ini`**: Pytest configuration with coverage settings +- **`conftest.py`**: Pytest fixtures and common test setup + +## Running Tests + +### Basic Test Execution +```bash +# Run all tests +python manage.py test recruitment + +# Run specific test class +python manage.py test recruitment.tests.AdvancedModelTests + +# Run with verbose output +python manage.py test recruitment --verbosity=2 + +# Run tests with coverage +python manage.py test recruitment --coverage +``` + +### Using Pytest +```bash +# Install pytest and required packages +pip install pytest pytest-django pytest-cov + +# Run all tests +pytest + +# Run specific test file +pytest recruitment/tests.py + +# Run with coverage +pytest --cov=recruitment --cov-report=html + +# Run with markers +pytest -m unit # Run only unit tests +pytest -m integration # Run only integration tests +pytest -m "not slow" # Skip slow tests +``` + +### Test Markers +- `@pytest.mark.unit`: For unit tests +- `@pytest.mark.integration`: For integration tests +- `@pytest.mark.security`: For security tests +- `@pytest.mark.api`: For API tests +- `@pytest.mark.slow`: For performance-intensive tests + +## Test Coverage + +The test suite aims for 80% code coverage. Coverage reports are generated in: +- HTML: `htmlcov/index.html` +- Terminal: Shows missing lines + +### Improving Coverage +1. Add tests for untested branches +2. Test error conditions and edge cases +3. Use mocking for external dependencies + +## Key Testing Areas + +### 1. Model Testing +- **JobPosting**: ID generation, validation, methods +- **Candidate**: Stage transitions, relationships +- **ZoomMeeting**: Time validation, status handling +- **FormTemplate**: Template integrity, field ordering +- **InterviewSchedule**: Scheduling logic, slot generation + +### 2. View Testing +- **Job Management**: CRUD operations, search, filtering +- **Candidate Management**: Stage updates, bulk operations +- **Meeting Management**: Scheduling, API integration +- **Form Handling**: Submission processing, validation + +### 3. Form Testing +- **JobPostingForm**: Complex validation, field dependencies +- **CandidateForm**: File upload, validation +- **InterviewScheduleForm**: Dynamic fields, validation +- **MeetingCommentForm**: Comment creation/editing + +### 4. Integration Testing +- **Complete Hiring Workflow**: Job → Application → Interview → Hire +- **Data Integrity**: Cross-component data consistency +- **API Integration**: Zoom API, LinkedIn integration +- **Concurrent Operations**: Multi-threading scenarios + +### 5. Security Testing +- **Access Control**: Permission validation +- **CSRF Protection**: Form security +- **Input Validation**: SQL injection, XSS prevention +- **Authentication**: User authorization + +## Test Fixtures + +Common fixtures available in `conftest.py`: + +- **User Fixtures**: `user`, `staff_user`, `profile` +- **Model Fixtures**: `job`, `candidate`, `zoom_meeting`, `form_template` +- **Form Data Fixtures**: `job_form_data`, `candidate_form_data` +- **Mock Fixtures**: `mock_zoom_api`, `mock_time_slots` +- **Client Fixtures**: `client`, `authenticated_client`, `authenticated_staff_client` + +## Writing New Tests + +### Test Naming Convention +- Use descriptive names: `test_user_can_create_job_posting` +- Follow the pattern: `test_[subject]_[action]_[expected_result]` + +### Best Practices +1. **Use Fixtures**: Leverage existing fixtures instead of creating test data +2. **Mock External Dependencies**: Use `@patch` for API calls +3. **Test Edge Cases**: Include invalid data, boundary conditions +4. **Maintain Independence**: Each test should be runnable independently +5. **Use Assertions**: Be specific about expected outcomes + +### Example Test Structure +```python +from django.test import TestCase +from recruitment.models import JobPosting +from recruitment.tests import BaseTestCase + +class JobPostingTests(BaseTestCase): + + def test_job_creation_minimal_data(self): + """Test job creation with minimal required fields""" + job = JobPosting.objects.create( + title='Minimal Job', + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + created_by=self.user + ) + self.assertEqual(job.title, 'Minimal Job') + self.assertIsNotNone(job.slug) + + def test_job_posting_validation_invalid_data(self): + """Test that invalid data raises validation errors""" + with self.assertRaises(ValueError): + JobPosting.objects.create( + title='', # Empty title + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + created_by=self.user + ) +``` + +## Testing External Integrations + +### Zoom API Integration +```python +@patch('recruitment.views.create_zoom_meeting') +def test_meeting_creation(self, mock_zoom): + """Test Zoom meeting creation with mocked API""" + mock_zoom.return_value = { + 'status': 'success', + 'meeting_details': { + 'meeting_id': '123456789', + 'join_url': 'https://zoom.us/j/123456789' + } + } + + # Test meeting creation logic + result = create_zoom_meeting('Test Meeting', start_time, duration) + self.assertEqual(result['status'], 'success') + mock_zoom.assert_called_once() +``` + +### LinkedIn Integration +```python +@patch('recruitment.views.LinkedinService') +def test_linkedin_posting(self, mock_linkedin): + """Test LinkedIn job posting with mocked service""" + mock_service = mock_linkedin.return_value + mock_service.create_job_post.return_value = { + 'success': True, + 'post_id': 'linkedin123', + 'post_url': 'https://linkedin.com/jobs/view/linkedin123' + } + + # Test LinkedIn posting logic + result = mock_service.create_job_post(job) + self.assertTrue(result['success']) +``` + +## Performance Testing + +### Running Performance Tests +```bash +# Run slow tests only +pytest -m slow + +# Profile test execution +pytest --profile +``` + +### Performance Considerations +1. Use `TransactionTestCase` for tests that require database commits +2. Mock external API calls to avoid network delays +3. Use `select_related` and `prefetch_related` in queries +4. Test with realistic data volumes + +## Continuous Integration + +### GitHub Actions Integration +```yaml +name: Tests +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.9, 3.10, 3.11] + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + pip install pytest pytest-django pytest-cov + - name: Run tests + run: | + pytest --cov=recruitment --cov-report=xml + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1 +``` + +## Troubleshooting Common Issues + +### Database Issues +```python +# Use TransactionTestCase for tests that modify database structure +from django.test import TransactionTestCase + +class MyTests(TransactionTestCase): + def test_database_modification(self): + # This test will properly clean up the database + pass +``` + +### Mocking Issues +```python +# Correct way to mock imports +from unittest.mock import patch + +@patch('recruitment.views.zoom_api.ZoomClient') +def test_zoom_integration(self, mock_zoom_client): + mock_instance = mock_zoom_client.return_value + mock_instance.create_meeting.return_value = {'success': True} + + # Test code +``` + +### HTMX Testing +```python +# Test HTMX responses +def test_htmx_partial_update(self): + response = self.client.get('/some-url/', HTTP_HX_REQUEST='true') + self.assertEqual(response.status_code, 200) + self.assertIn('partial-content', response.content) +``` + +## Contributing to Tests + +### Adding New Tests +1. Place tests in appropriate test modules +2. Use existing fixtures when possible +3. Add descriptive docstrings +4. Mark tests with appropriate markers +5. Ensure new tests maintain coverage requirements + +### Test Review Checklist +- [ ] Tests are properly isolated +- [ ] Fixtures are used effectively +- [ ] External dependencies are mocked +- [ ] Edge cases are covered +- [ ] Naming conventions are followed +- [ ] Documentation is clear + +## Resources + +- [Django Testing Documentation](https://docs.djangoproject.com/en/stable/topics/testing/) +- [Pytest Documentation](https://docs.pytest.org/) +- [Test-Driven Development](https://testdriven.io/blog/tdd-with-django-and-react/) +- [Code Coverage Best Practices](https://pytest-cov.readthedocs.io/) diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..864753a --- /dev/null +++ b/conftest.py @@ -0,0 +1,394 @@ +""" +Pytest configuration and fixtures for the recruitment application tests. +""" + +import os +import sys +import django +from pathlib import Path + +# Setup Django +BASE_DIR = Path(__file__).resolve().parent + +# Add the project root to sys.path +sys.path.append(str(BASE_DIR)) + +# Set the Django settings module +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NorahUniversity.settings') + +# Configure Django +django.setup() + +import pytest +from django.test import TestCase +from django.contrib.auth.models import User +from django.core.files.uploadedfile import SimpleUploadedFile +from django.utils import timezone +from datetime import datetime, time, timedelta, date + +from recruitment.models import ( + JobPosting, Candidate, ZoomMeeting, FormTemplate, FormStage, FormField, + FormSubmission, FieldResponse, InterviewSchedule, ScheduledInterview, + TrainingMaterial, Source, HiringAgency, Profile, MeetingComment, JobPostingImage, + BreakTime +) +from recruitment.forms import ( + JobPostingForm, CandidateForm, ZoomMeetingForm, MeetingCommentForm, + CandidateStageForm, InterviewScheduleForm, BreakTimeFormSet +) + + +# Removed: django_db_setup fixture conflicts with Django TestCase +# Django TestCase handles its own database setup + + +@pytest.fixture +def user(): + """Create a regular user for testing""" + return User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=False + ) + + +@pytest.fixture +def staff_user(): + """Create a staff user for testing""" + return User.objects.create_user( + username='staffuser', + email='staff@example.com', + password='testpass123', + is_staff=True + ) + + +@pytest.fixture +def profile(user): + """Create a user profile""" + return Profile.objects.create(user=user) + + +@pytest.fixture +def job(staff_user): + """Create a job posting for testing""" + return JobPosting.objects.create( + title='Software Engineer', + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + location_country='Saudi Arabia', + description='Job description', + qualifications='Job qualifications', + created_by=staff_user, + status='ACTIVE', + max_applications=100, + open_positions=1 + ) + + +@pytest.fixture +def candidate(job): + """Create a candidate for testing""" + return Candidate.objects.create( + first_name='John', + last_name='Doe', + email='john@example.com', + phone='1234567890', + job=job, + stage='Applied' + ) + + +@pytest.fixture +def zoom_meeting(): + """Create a Zoom meeting for testing""" + return ZoomMeeting.objects.create( + topic='Interview with John Doe', + start_time=timezone.now() + timedelta(hours=1), + duration=60, + timezone='UTC', + join_url='https://zoom.us/j/123456789', + meeting_id='123456789', + status='waiting' + ) + + +@pytest.fixture +def form_template(staff_user, job): + """Create a form template for testing""" + return FormTemplate.objects.create( + job=job, + name='Test Application Form', + description='Test form template', + created_by=staff_user, + is_active=True + ) + + +@pytest.fixture +def form_stage(form_template): + """Create a form stage for testing""" + return FormStage.objects.create( + template=form_template, + name='Personal Information', + order=0 + ) + + +@pytest.fixture +def form_field(form_stage): + """Create a form field for testing""" + return FormField.objects.create( + stage=form_stage, + label='First Name', + field_type='text', + order=0, + required=True + ) + + +@pytest.fixture +def form_submission(form_template): + """Create a form submission for testing""" + return FormSubmission.objects.create( + template=form_template, + applicant_name='John Doe', + applicant_email='john@example.com' + ) + + +@pytest.fixture +def field_response(form_submission, form_field): + """Create a field response for testing""" + return FieldResponse.objects.create( + submission=form_submission, + field=form_field, + value='John' + ) + + +@pytest.fixture +def interview_schedule(staff_user, job): + """Create an interview schedule for testing""" + # Create candidates first + candidates = [] + for i in range(3): + candidate = Candidate.objects.create( + first_name=f'Candidate{i}', + last_name=f'Test{i}', + email=f'candidate{i}@example.com', + phone=f'12345678{i}', + job=job, + stage='Interview' + ) + candidates.append(candidate) + + return InterviewSchedule.objects.create( + job=job, + created_by=staff_user, + start_date=date.today() + timedelta(days=1), + end_date=date.today() + timedelta(days=7), + working_days=[0, 1, 2, 3, 4], # Mon-Fri + start_time=time(9, 0), + end_time=time(17, 0), + interview_duration=60, + buffer_time=15, + break_start_time=time(12, 0), + break_end_time=time(13, 0) + ) + + +@pytest.fixture +def scheduled_interview(candidate, job, zoom_meeting): + """Create a scheduled interview for testing""" + return ScheduledInterview.objects.create( + candidate=candidate, + job=job, + zoom_meeting=zoom_meeting, + interview_date=timezone.now().date(), + interview_time=time(10, 0), + status='scheduled' + ) + + +@pytest.fixture +def meeting_comment(user, zoom_meeting): + """Create a meeting comment for testing""" + return MeetingComment.objects.create( + meeting=zoom_meeting, + author=user, + content='This is a test comment' + ) + + +@pytest.fixture +def file_content(): + """Create test file content""" + return b'%PDF-1.4\n% ... test content ...' + + +@pytest.fixture +def uploaded_file(file_content): + """Create an uploaded file for testing""" + return SimpleUploadedFile( + 'test_file.pdf', + file_content, + content_type='application/pdf' + ) + + +@pytest.fixture +def job_form_data(): + """Basic job posting form data for testing""" + return { + 'title': 'Test Job Title', + 'department': 'IT', + 'job_type': 'FULL_TIME', + 'workplace_type': 'REMOTE', + 'location_city': 'Riyadh', + 'location_state': 'Riyadh', + 'location_country': 'Saudi Arabia', + 'description': 'Job description', + 'qualifications': 'Job qualifications', + 'salary_range': '5000-7000', + 'application_deadline': '2025-12-31', + 'max_applications': '100', + 'open_positions': '1', + 'hash_tags': '#hiring, #jobopening' + } + + +@pytest.fixture +def candidate_form_data(job): + """Basic candidate form data for testing""" + return { + 'job': job.id, + 'first_name': 'John', + 'last_name': 'Doe', + 'phone': '1234567890', + 'email': 'john@example.com' + } + + +@pytest.fixture +def zoom_meeting_form_data(): + """Basic Zoom meeting form data for testing""" + start_time = timezone.now() + timedelta(hours=1) + return { + 'topic': 'Test Meeting', + 'start_time': start_time.strftime('%Y-%m-%dT%H:%M'), + 'duration': 60 + } + + +@pytest.fixture +def interview_schedule_form_data(job): + """Basic interview schedule form data for testing""" + # Create candidates first + candidates = [] + for i in range(2): + candidate = Candidate.objects.create( + first_name=f'Interview{i}', + last_name=f'Candidate{i}', + email=f'interview{i}@example.com', + phone=f'12345678{i}', + job=job, + stage='Interview' + ) + candidates.append(candidate) + + return { + 'candidates': [c.pk for c in candidates], + 'start_date': (date.today() + timedelta(days=1)).isoformat(), + 'end_date': (date.today() + timedelta(days=7)).isoformat(), + 'working_days': [0, 1, 2, 3, 4], + 'start_time': '09:00', + 'end_time': '17:00', + 'interview_duration': '60', + 'buffer_time': '15' + } + + +@pytest.fixture +def client(): + """Django test client""" + from django.test import Client + return Client() + + +@pytest.fixture +def authenticated_client(client, user): + """Authenticated Django test client""" + client.force_login(user) + return client + + +@pytest.fixture +def authenticated_staff_client(client, staff_user): + """Authenticated staff Django test client""" + client.force_login(staff_user) + return client + + +@pytest.fixture +def mock_zoom_api(): + """Mock Zoom API responses""" + with pytest.MonkeyPatch().context() as m: + m.setattr('recruitment.utils.create_zoom_meeting', lambda *args, **kwargs: { + 'status': 'success', + 'meeting_details': { + 'meeting_id': '123456789', + 'join_url': 'https://zoom.us/j/123456789', + 'password': 'meeting123' + }, + 'zoom_gateway_response': {'status': 'waiting'} + }) + yield + + +@pytest.fixture +def mock_time_slots(): + """Mock available time slots for interview scheduling""" + return [ + {'date': date.today() + timedelta(days=1), 'time': '10:00'}, + {'date': date.today() + timedelta(days=1), 'time': '11:00'}, + {'date': date.today() + timedelta(days=1), 'time': '14:00'}, + {'date': date.today() + timedelta(days=2), 'time': '09:00'}, + {'date': date.today() + timedelta(days=2), 'time': '15:00'} + ] + + +# Test markers +def pytest_configure(config): + """Configure custom markers""" + config.addinivalue_line( + "markers", "slow: marks tests as slow (deselect with '-m \"not slow\"')" + ) + config.addinivalue_line( + "markers", "integration: marks tests as integration tests" + ) + config.addinivalue_line( + "markers", "unit: marks tests as unit tests" + ) + config.addinivalue_line( + "markers", "security: marks tests as security tests" + ) + config.addinivalue_line( + "markers", "api: marks tests as API tests" + ) + + +# Pytest hooks for better test output +# Note: HTML reporting hooks are commented out to avoid plugin validation issues +# def pytest_html_report_title(report): +# """Set the HTML report title""" +# report.title = "Recruitment Application Test Report" + + +# def pytest_runtest_logreport(report): +# """Customize test output""" +# if report.when == 'call' and report.failed: +# # Add custom information for failed tests +# pass diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..df55272 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,20 @@ +[tool:pytest] +DJANGO_SETTINGS_MODULE = NorahUniversity.settings +python_files = tests.py test_*.py *_tests.py +python_classes = Test* +python_functions = test_* +addopts = + --verbose + --tb=short + --strict-markers + --durations=10 + --cov=recruitment + --cov-report=term-missing + --cov-report=html:htmlcov + --cov-fail-under=80 +testpaths = recruitment +markers = + slow: marks tests as slow (deselect with '-m "not slow"') + integration: marks tests as integration tests + unit: marks tests as unit tests + security: marks tests as security tests diff --git a/recruitment/__pycache__/admin.cpython-313.pyc b/recruitment/__pycache__/admin.cpython-313.pyc index c67547f..87d1eb6 100644 Binary files a/recruitment/__pycache__/admin.cpython-313.pyc and b/recruitment/__pycache__/admin.cpython-313.pyc differ diff --git a/recruitment/__pycache__/forms.cpython-313.pyc b/recruitment/__pycache__/forms.cpython-313.pyc index 606d3d5..231e316 100644 Binary files a/recruitment/__pycache__/forms.cpython-313.pyc and b/recruitment/__pycache__/forms.cpython-313.pyc differ diff --git a/recruitment/__pycache__/models.cpython-313.pyc b/recruitment/__pycache__/models.cpython-313.pyc index ebc6d92..0e7f3a1 100644 Binary files a/recruitment/__pycache__/models.cpython-313.pyc and b/recruitment/__pycache__/models.cpython-313.pyc differ diff --git a/recruitment/__pycache__/urls.cpython-313.pyc b/recruitment/__pycache__/urls.cpython-313.pyc index 46150fb..b74264a 100644 Binary files a/recruitment/__pycache__/urls.cpython-313.pyc and b/recruitment/__pycache__/urls.cpython-313.pyc differ diff --git a/recruitment/__pycache__/utils.cpython-313.pyc b/recruitment/__pycache__/utils.cpython-313.pyc index 3218023..fefa995 100644 Binary files a/recruitment/__pycache__/utils.cpython-313.pyc and b/recruitment/__pycache__/utils.cpython-313.pyc differ diff --git a/recruitment/__pycache__/views.cpython-313.pyc b/recruitment/__pycache__/views.cpython-313.pyc index fe6f2a1..6a70d42 100644 Binary files a/recruitment/__pycache__/views.cpython-313.pyc and b/recruitment/__pycache__/views.cpython-313.pyc differ diff --git a/recruitment/__pycache__/views_frontend.cpython-313.pyc b/recruitment/__pycache__/views_frontend.cpython-313.pyc index 961ccff..fd64128 100644 Binary files a/recruitment/__pycache__/views_frontend.cpython-313.pyc and b/recruitment/__pycache__/views_frontend.cpython-313.pyc differ diff --git a/recruitment/admin.py b/recruitment/admin.py index bfcf6cc..6b7cb8b 100644 --- a/recruitment/admin.py +++ b/recruitment/admin.py @@ -5,7 +5,7 @@ from django.utils import timezone from .models import ( JobPosting, Candidate, TrainingMaterial, ZoomMeeting, FormTemplate, FormStage, FormField, FormSubmission, FieldResponse, - SharedFormTemplate, Source, HiringAgency, IntegrationLog,InterviewSchedule,Profile,JobPostingImage + SharedFormTemplate, Source, HiringAgency, IntegrationLog,InterviewSchedule,Profile,JobPostingImage,MeetingComment ) class FormFieldInline(admin.TabularInline): @@ -152,13 +152,13 @@ class CandidateAdmin(admin.ModelAdmin): 'fields': ('first_name', 'last_name', 'email', 'phone', 'resume') }), ('Application Details', { - 'fields': ('job', 'applied', 'stage') + 'fields': ('job', 'applied', 'stage','is_resume_parsed') }), ('Interview Process', { 'fields': ('exam_date', 'exam_status', 'interview_date', 'interview_status', 'offer_date', 'offer_status', 'join_date') }), ('Scoring', { - 'fields': ('match_score', 'strengths', 'weaknesses', 'criteria_checklist') + 'fields': ('ai_analysis_data',) }), ('Additional Information', { 'fields': ('submitted_by_agency', 'created_at', 'updated_at') @@ -206,7 +206,7 @@ class ZoomMeetingAdmin(admin.ModelAdmin): readonly_fields = ['created_at', 'updated_at'] fieldsets = ( ('Meeting Details', { - 'fields': ('topic', 'meeting_id', 'start_time', 'duration', 'timezone') + 'fields': ('topic', 'meeting_id', 'start_time', 'duration', 'timezone','status') }), ('Meeting Settings', { 'fields': ('participant_video', 'join_before_host', 'mute_upon_entry', 'waiting_room') @@ -221,6 +221,26 @@ class ZoomMeetingAdmin(admin.ModelAdmin): save_on_top = True +@admin.register(MeetingComment) +class MeetingCommentAdmin(admin.ModelAdmin): + list_display = ['meeting', 'author', 'created_at', 'updated_at'] + list_filter = ['created_at', 'author', 'meeting'] + search_fields = ['content', 'meeting__topic', 'author__username'] + readonly_fields = ['created_at', 'updated_at', 'slug'] + fieldsets = ( + ('Meeting Information', { + 'fields': ('meeting', 'author') + }), + ('Comment Content', { + 'fields': ('content',) + }), + ('Timestamps', { + 'fields': ('created_at', 'updated_at', 'slug') + }), + ) + save_on_top = True + + @admin.register(FormTemplate) class FormTemplateAdmin(admin.ModelAdmin): list_display = ['name', 'created_by', 'created_at', 'is_active'] @@ -265,4 +285,4 @@ admin.site.register(Profile) # admin.site.register(HiringAgency) -admin.site.register(JobPostingImage) \ No newline at end of file +admin.site.register(JobPostingImage) diff --git a/recruitment/forms.py b/recruitment/forms.py index a43ace2..561e237 100644 --- a/recruitment/forms.py +++ b/recruitment/forms.py @@ -7,7 +7,7 @@ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column, Field, Div from .models import ( ZoomMeeting, Candidate,TrainingMaterial,JobPosting, - FormTemplate,InterviewSchedule,BreakTime,JobPostingImage + FormTemplate,InterviewSchedule,BreakTime,JobPostingImage,MeetingComment,ScheduledInterview ) # from django_summernote.widgets import SummernoteWidget from django_ckeditor_5.widgets import CKEditor5Widget @@ -70,50 +70,50 @@ class CandidateStageForm(forms.ModelForm): 'stage': forms.Select(attrs={'class': 'form-select'}), } - def __init__(self, *args, **kwargs): - # Get the current candidate instance for validation - self.candidate = kwargs.pop('candidate', None) - super().__init__(*args, **kwargs) + # def __init__(self, *args, **kwargs): + # # Get the current candidate instance for validation + # self.candidate = kwargs.pop('candidate', None) + # super().__init__(*args, **kwargs) - # Dynamically filter stage choices based on current stage - if self.candidate and self.candidate.pk: - current_stage = self.candidate.stage - available_stages = self.candidate.get_available_stages() + # # Dynamically filter stage choices based on current stage + # if self.candidate and self.candidate.pk: + # current_stage = self.candidate.stage + # available_stages = self.candidate.get_available_stages() - # Filter choices to only include available stages - choices = [(stage, self.candidate.Stage(stage).label) - for stage in available_stages] - self.fields['stage'].choices = choices + # # Filter choices to only include available stages + # choices = [(stage, self.candidate.Stage(stage).label) + # for stage in available_stages] + # self.fields['stage'].choices = choices - # Set initial value to current stage - self.fields['stage'].initial = current_stage - else: - # For new candidates, only show 'Applied' stage - self.fields['stage'].choices = [('Applied', _('Applied'))] - self.fields['stage'].initial = 'Applied' + # # Set initial value to current stage + # self.fields['stage'].initial = current_stage + # else: + # # For new candidates, only show 'Applied' stage + # self.fields['stage'].choices = [('Applied', _('Applied'))] + # self.fields['stage'].initial = 'Applied' - def clean_stage(self): - """Validate stage transition""" - new_stage = self.cleaned_data.get('stage') - if not new_stage: - raise forms.ValidationError(_('Please select a stage.')) + # def clean_stage(self): + # """Validate stage transition""" + # new_stage = self.cleaned_data.get('stage') + # if not new_stage: + # raise forms.ValidationError(_('Please select a stage.')) - # Use model validation for stage transitions - if self.candidate and self.candidate.pk: - current_stage = self.candidate.stage - if new_stage != current_stage: - if not self.candidate.can_transition_to(new_stage): - allowed_stages = self.candidate.get_available_stages() - raise forms.ValidationError( - _('Cannot transition from "%(current)s" to "%(new)s". ' - 'Allowed transitions: %(allowed)s') % { - 'current': current_stage, - 'new': new_stage, - 'allowed': ', '.join(allowed_stages) or 'None (final stage)' - } - ) + # # Use model validation for stage transitions + # if self.candidate and self.candidate.pk: + # current_stage = self.candidate.stage + # if new_stage != current_stage: + # if not self.candidate.can_transition_to(new_stage): + # allowed_stages = self.candidate.get_available_stages() + # raise forms.ValidationError( + # _('Cannot transition from "%(current)s" to "%(new)s". ' + # 'Allowed transitions: %(allowed)s') % { + # 'current': current_stage, + # 'new': new_stage, + # 'allowed': ', '.join(allowed_stages) or 'None (final stage)' + # } + # ) - return new_stage + # return new_stage class ZoomMeetingForm(forms.ModelForm): class Meta: @@ -564,6 +564,33 @@ class InterviewScheduleForm(forms.ModelForm): # Convert string values to integers return [int(day) for day in working_days] +class MeetingCommentForm(forms.ModelForm): + """Form for creating and editing meeting comments""" + class Meta: + model = MeetingComment + fields = ['content'] + widgets = { + 'content': CKEditor5Widget( + attrs={'class': 'form-control', 'placeholder': _('Enter your comment or note')}, + config_name='extends' + ), + } + labels = { + 'content': _('Comment'), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.helper = FormHelper() + self.helper.form_method = 'post' + self.helper.form_class = 'form-horizontal' + self.helper.label_class = 'col-md-3' + self.helper.field_class = 'col-md-9' + self.helper.layout = Layout( + Field('content', css_class='form-control'), + Submit('submit', _('Add Comment'), css_class='btn btn-primary mt-3') + ) + # --- ScheduleInterviewForCandiateForm remains unchanged --- class ScheduleInterviewForCandiateForm(forms.ModelForm): @@ -580,3 +607,10 @@ class ScheduleInterviewForCandiateForm(forms.ModelForm): 'break_start_time': forms.TimeInput(attrs={'type': 'time', 'class': 'form-control'}), 'break_end_time': forms.TimeInput(attrs={'type': 'time', 'class': 'form-control'}), } + + +class InterviewForm(forms.ModelForm): + + class Meta: + model = ScheduledInterview + fields = ['job','candidate'] \ No newline at end of file diff --git a/recruitment/migrations/0021_meetingcomment.py b/recruitment/migrations/0021_meetingcomment.py new file mode 100644 index 0000000..734d421 --- /dev/null +++ b/recruitment/migrations/0021_meetingcomment.py @@ -0,0 +1,35 @@ +# Generated by Django 5.2.6 on 2025-10-16 13:52 + +import django.db.models.deletion +import django_ckeditor_5.fields +import django_extensions.db.fields +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0020_alter_interviewschedule_created_at'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='MeetingComment', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')), + ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Updated at')), + ('slug', django_extensions.db.fields.RandomCharField(blank=True, editable=False, length=8, unique=True, verbose_name='Slug')), + ('content', django_ckeditor_5.fields.CKEditor5Field(verbose_name='Content')), + ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='meeting_comments', to=settings.AUTH_USER_MODEL, verbose_name='Author')), + ('meeting', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='recruitment.zoommeeting', verbose_name='Meeting')), + ], + options={ + 'verbose_name': 'Meeting Comment', + 'verbose_name_plural': 'Meeting Comments', + 'ordering': ['-created_at'], + }, + ), + ] diff --git a/recruitment/migrations/0022_candidate_resume_parsed_category.py b/recruitment/migrations/0022_candidate_resume_parsed_category.py new file mode 100644 index 0000000..f767301 --- /dev/null +++ b/recruitment/migrations/0022_candidate_resume_parsed_category.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.6 on 2025-10-16 19:39 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0021_meetingcomment'), + ] + + operations = [ + migrations.AddField( + model_name='candidate', + name='resume_parsed_category', + field=models.TextField(blank=True, verbose_name='Resume Parsed Category'), + ), + ] diff --git a/recruitment/migrations/0023_alter_jobposting_max_applications.py b/recruitment/migrations/0023_alter_jobposting_max_applications.py new file mode 100644 index 0000000..94104e1 --- /dev/null +++ b/recruitment/migrations/0023_alter_jobposting_max_applications.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.6 on 2025-10-16 19:47 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0022_candidate_resume_parsed_category'), + ] + + operations = [ + migrations.AlterField( + model_name='jobposting', + name='max_applications', + field=models.PositiveIntegerField(blank=True, default=1000, help_text='Maximum number of applications allowed', null=True), + ), + ] diff --git a/recruitment/migrations/0024_alter_zoommeeting_status.py b/recruitment/migrations/0024_alter_zoommeeting_status.py new file mode 100644 index 0000000..9a69166 --- /dev/null +++ b/recruitment/migrations/0024_alter_zoommeeting_status.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.4 on 2025-10-17 20:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0023_alter_jobposting_max_applications'), + ] + + operations = [ + migrations.AlterField( + model_name='zoommeeting', + name='status', + field=models.CharField(blank=True, default='waiting', max_length=20, null=True, verbose_name='Status'), + ), + ] diff --git a/recruitment/migrations/0025_candidate_recommendation.py b/recruitment/migrations/0025_candidate_recommendation.py new file mode 100644 index 0000000..061dbf7 --- /dev/null +++ b/recruitment/migrations/0025_candidate_recommendation.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.4 on 2025-10-17 21:35 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0024_alter_zoommeeting_status'), + ] + + operations = [ + migrations.AddField( + model_name='candidate', + name='recommendation', + field=models.TextField(blank=True, verbose_name='Recommendation'), + ), + ] diff --git a/recruitment/migrations/0026_remove_candidate_resume_parsed_category_and_more.py b/recruitment/migrations/0026_remove_candidate_resume_parsed_category_and_more.py new file mode 100644 index 0000000..1a06a70 --- /dev/null +++ b/recruitment/migrations/0026_remove_candidate_resume_parsed_category_and_more.py @@ -0,0 +1,22 @@ +# Generated by Django 5.2.4 on 2025-10-17 21:50 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0025_candidate_recommendation'), + ] + + operations = [ + migrations.RemoveField( + model_name='candidate', + name='resume_parsed_category', + ), + migrations.AddField( + model_name='candidate', + name='major_category_name', + field=models.TextField(blank=True, verbose_name='Major Category Name'), + ), + ] diff --git a/recruitment/migrations/0027_alter_candidate_email_and_more.py b/recruitment/migrations/0027_alter_candidate_email_and_more.py new file mode 100644 index 0000000..af3b674 --- /dev/null +++ b/recruitment/migrations/0027_alter_candidate_email_and_more.py @@ -0,0 +1,159 @@ +# Generated by Django 5.2.6 on 2025-10-18 17:51 + +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0026_remove_candidate_resume_parsed_category_and_more'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AlterField( + model_name='candidate', + name='email', + field=models.EmailField(db_index=True, max_length=254, verbose_name='Email'), + ), + migrations.AlterField( + model_name='candidate', + name='major_category_name', + field=models.TextField(blank=True, db_index=True, verbose_name='Major Category Name'), + ), + migrations.AlterField( + model_name='candidate', + name='match_score', + field=models.IntegerField(blank=True, db_index=True, null=True), + ), + migrations.AlterField( + model_name='candidate', + name='stage', + field=models.CharField(choices=[('Applied', 'Applied'), ('Exam', 'Exam'), ('Interview', 'Interview'), ('Offer', 'Offer')], db_index=True, default='Applied', max_length=100, verbose_name='Stage'), + ), + migrations.AlterField( + model_name='formsubmission', + name='applicant_email', + field=models.EmailField(blank=True, db_index=True, help_text='Email of the applicant', max_length=254), + ), + migrations.AlterField( + model_name='formsubmission', + name='submitted_at', + field=models.DateTimeField(auto_now_add=True, db_index=True), + ), + migrations.AlterField( + model_name='interviewschedule', + name='end_date', + field=models.DateField(db_index=True, verbose_name='End Date'), + ), + migrations.AlterField( + model_name='interviewschedule', + name='start_date', + field=models.DateField(db_index=True, verbose_name='Start Date'), + ), + migrations.AlterField( + model_name='jobposting', + name='application_deadline', + field=models.DateField(blank=True, db_index=True, null=True), + ), + migrations.AlterField( + model_name='jobposting', + name='published_at', + field=models.DateTimeField(blank=True, db_index=True, null=True), + ), + migrations.AlterField( + model_name='jobposting', + name='status', + field=models.CharField(choices=[('DRAFT', 'Draft'), ('ACTIVE', 'Active'), ('CLOSED', 'Closed'), ('CANCELLED', 'Cancelled'), ('ARCHIVED', 'Archived')], db_index=True, default='DRAFT', max_length=20), + ), + migrations.AlterField( + model_name='scheduledinterview', + name='interview_date', + field=models.DateField(db_index=True, verbose_name='Interview Date'), + ), + migrations.AlterField( + model_name='scheduledinterview', + name='status', + field=models.CharField(choices=[('scheduled', 'Scheduled'), ('confirmed', 'Confirmed'), ('cancelled', 'Cancelled'), ('completed', 'Completed')], db_index=True, default='scheduled', max_length=20), + ), + migrations.AlterField( + model_name='zoommeeting', + name='meeting_id', + field=models.CharField(db_index=True, max_length=20, unique=True, verbose_name='Meeting ID'), + ), + migrations.AlterField( + model_name='zoommeeting', + name='start_time', + field=models.DateTimeField(db_index=True, verbose_name='Start Time'), + ), + migrations.AlterField( + model_name='zoommeeting', + name='status', + field=models.CharField(blank=True, db_index=True, default='waiting', max_length=20, null=True, verbose_name='Status'), + ), + migrations.AddIndex( + model_name='candidate', + index=models.Index(fields=['job', 'stage'], name='recruitment_job_id_766dbe_idx'), + ), + migrations.AddIndex( + model_name='candidate', + index=models.Index(fields=['job', 'stage', 'match_score'], name='recruitment_job_id_bd6512_idx'), + ), + migrations.AddIndex( + model_name='candidate', + index=models.Index(fields=['created_at'], name='recruitment_created_73590f_idx'), + ), + migrations.AddIndex( + model_name='fieldresponse', + index=models.Index(fields=['submission'], name='recruitment_submiss_474130_idx'), + ), + migrations.AddIndex( + model_name='fieldresponse', + index=models.Index(fields=['field'], name='recruitment_field_i_097e5b_idx'), + ), + migrations.AddIndex( + model_name='formsubmission', + index=models.Index(fields=['submitted_at'], name='recruitment_submitt_7946c8_idx'), + ), + migrations.AddIndex( + model_name='formtemplate', + index=models.Index(fields=['created_at'], name='recruitment_created_c21775_idx'), + ), + migrations.AddIndex( + model_name='formtemplate', + index=models.Index(fields=['is_active'], name='recruitment_is_acti_ae5efb_idx'), + ), + migrations.AddIndex( + model_name='interviewschedule', + index=models.Index(fields=['start_date'], name='recruitment_start_d_15d55e_idx'), + ), + migrations.AddIndex( + model_name='interviewschedule', + index=models.Index(fields=['end_date'], name='recruitment_end_dat_aeb00e_idx'), + ), + migrations.AddIndex( + model_name='interviewschedule', + index=models.Index(fields=['created_by'], name='recruitment_created_d0bdcc_idx'), + ), + migrations.AddIndex( + model_name='jobposting', + index=models.Index(fields=['status', 'created_at'], name='recruitment_status_42c036_idx'), + ), + migrations.AddIndex( + model_name='jobposting', + index=models.Index(fields=['slug'], name='recruitment_slug_004045_idx'), + ), + migrations.AddIndex( + model_name='scheduledinterview', + index=models.Index(fields=['job', 'status'], name='recruitment_job_id_f09e22_idx'), + ), + migrations.AddIndex( + model_name='scheduledinterview', + index=models.Index(fields=['interview_date', 'interview_time'], name='recruitment_intervi_7f5877_idx'), + ), + migrations.AddIndex( + model_name='scheduledinterview', + index=models.Index(fields=['candidate', 'job'], name='recruitment_candida_43d5b0_idx'), + ), + ] diff --git a/recruitment/migrations/0028_alter_candidate_interview_status.py b/recruitment/migrations/0028_alter_candidate_interview_status.py new file mode 100644 index 0000000..f9b6c05 --- /dev/null +++ b/recruitment/migrations/0028_alter_candidate_interview_status.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.4 on 2025-10-18 21:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0027_alter_candidate_email_and_more'), + ] + + operations = [ + migrations.AlterField( + model_name='candidate', + name='interview_status', + field=models.CharField(blank=True, choices=[('Passed', 'Passed'), ('Failed', 'Failed')], max_length=100, null=True, verbose_name='Interview Status'), + ), + ] diff --git a/recruitment/migrations/0029_remove_candidate_recruitment_job_id_766dbe_idx_and_more.py b/recruitment/migrations/0029_remove_candidate_recruitment_job_id_766dbe_idx_and_more.py new file mode 100644 index 0000000..1ab4af2 --- /dev/null +++ b/recruitment/migrations/0029_remove_candidate_recruitment_job_id_766dbe_idx_and_more.py @@ -0,0 +1,62 @@ +# Generated by Django 5.2.4 on 2025-10-19 10:26 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0028_alter_candidate_interview_status'), + ] + + operations = [ + migrations.RemoveIndex( + model_name='candidate', + name='recruitment_job_id_766dbe_idx', + ), + migrations.RemoveIndex( + model_name='candidate', + name='recruitment_job_id_bd6512_idx', + ), + migrations.RemoveIndex( + model_name='jobposting', + name='recruitment_status_42c036_idx', + ), + migrations.RemoveField( + model_name='candidate', + name='criteria_checklist', + ), + migrations.RemoveField( + model_name='candidate', + name='major_category_name', + ), + migrations.RemoveField( + model_name='candidate', + name='match_score', + ), + migrations.RemoveField( + model_name='candidate', + name='recommendation', + ), + migrations.RemoveField( + model_name='candidate', + name='strengths', + ), + migrations.RemoveField( + model_name='candidate', + name='weaknesses', + ), + migrations.AddField( + model_name='candidate', + name='ai_analysis_data', + field=models.JSONField(default=dict, help_text='Full JSON output from the resume scoring model.', verbose_name='AI Analysis Data'), + ), + migrations.AddIndex( + model_name='candidate', + index=models.Index(fields=['stage'], name='recruitment_stage_f1c6eb_idx'), + ), + migrations.AddIndex( + model_name='jobposting', + index=models.Index(fields=['status', 'created_at', 'title'], name='recruitment_status_8b77aa_idx'), + ), + ] diff --git a/recruitment/migrations/0030_alter_candidate_options.py b/recruitment/migrations/0030_alter_candidate_options.py new file mode 100644 index 0000000..eff8232 --- /dev/null +++ b/recruitment/migrations/0030_alter_candidate_options.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.6 on 2025-10-19 13:39 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0029_remove_candidate_recruitment_job_id_766dbe_idx_and_more'), + ] + + operations = [ + migrations.AlterModelOptions( + name='candidate', + options={'ordering': ['-ai_analysis_data__match_score', '-created_at'], 'verbose_name': 'Candidate', 'verbose_name_plural': 'Candidates'}, + ), + ] diff --git a/recruitment/migrations/0031_alter_candidate_options.py b/recruitment/migrations/0031_alter_candidate_options.py new file mode 100644 index 0000000..ffdc406 --- /dev/null +++ b/recruitment/migrations/0031_alter_candidate_options.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.6 on 2025-10-19 13:43 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('recruitment', '0030_alter_candidate_options'), + ] + + operations = [ + migrations.AlterModelOptions( + name='candidate', + options={'verbose_name': 'Candidate', 'verbose_name_plural': 'Candidates'}, + ), + ] diff --git a/recruitment/models.py b/recruitment/models.py index 0b6bb54..eaba811 100644 --- a/recruitment/models.py +++ b/recruitment/models.py @@ -1,7 +1,9 @@ from django.db import models from django.urls import reverse +from typing import List,Dict,Any from django.utils import timezone -from django.db.models import JSONField +from django.db.models import FloatField,CharField +from django.db.models.functions import Cast from django.contrib.auth.models import User from django.core.validators import URLValidator from django_countries.fields import CountryField @@ -78,7 +80,7 @@ class JobPosting(Base): blank=True, ) application_start_date=models.DateField(null=True, blank=True) - application_deadline = models.DateField(null=True, blank=True) + application_deadline = models.DateField(db_index=True, null=True, blank=True) # Added index application_instructions =CKEditor5Field( blank=True, null=True,config_name='extends' ) @@ -98,7 +100,7 @@ class JobPosting(Base): ("ARCHIVED", "Archived"), ] status = models.CharField( - max_length=20, choices=STATUS_CHOICES, default="DRAFT" + db_index=True, max_length=20, choices=STATUS_CHOICES, default="DRAFT" # Added index ) # hashtags for social media @@ -122,7 +124,7 @@ class JobPosting(Base): ) linkedin_posted_at = models.DateTimeField(null=True, blank=True) - published_at = models.DateTimeField(null=True, blank=True) + published_at = models.DateTimeField(db_index=True, null=True, blank=True) # Added index # University Specific Fields position_number = models.CharField( max_length=50, blank=True, help_text="University position number" @@ -142,9 +144,10 @@ class JobPosting(Base): null=True, blank=True, help_text="The system or channel from which this job posting originated or was first published.", + db_index=True # Explicitly index ForeignKey ) max_applications = models.PositiveIntegerField( - default=1000, help_text="Maximum number of applications allowed" + default=1000, help_text="Maximum number of applications allowed",null=True,blank=True ) hiring_agency = models.ManyToManyField( "HiringAgency", @@ -172,6 +175,10 @@ class JobPosting(Base): ordering = ["-created_at"] verbose_name = "Job Posting" verbose_name_plural = "Job Postings" + indexes = [ + models.Index(fields=['status', 'created_at','title']), + models.Index(fields=['slug']), + ] def __str__(self): return f"{self.title} - {self.internal_job_id}-{self.get_status_display()}" @@ -239,7 +246,23 @@ class JobPosting(Base): return True return self.current_applications_count >= self.max_applications + @property + def all_candidates(self): + return self.candidates.annotate(sortable_score=Cast('ai_analysis_data__match_score',output_field=CharField())).order_by('-sortable_score') + @property + def screening_candidates(self): + return self.all_candidates.filter(stage="Applied") + @property + def exam_candidates(self): + return self.all_candidates.filter(stage="Exam") + @property + def interview_candidates(self): + return self.all_candidates.filter(stage="Interview") + + @property + def offer_candidates(self): + return self.all_candidates.filter(stage="Offer") class JobPostingImage(models.Model): job=models.OneToOneField('JobPosting',on_delete=models.CASCADE,related_name='post_images') @@ -281,7 +304,7 @@ class Candidate(Base): ) first_name = models.CharField(max_length=255, verbose_name=_("First Name")) last_name = models.CharField(max_length=255, verbose_name=_("Last Name")) - email = models.EmailField(verbose_name=_("Email")) + email = models.EmailField(db_index=True, verbose_name=_("Email")) # Added index phone = models.CharField(max_length=20, verbose_name=_("Phone")) address = models.TextField(max_length=200, verbose_name=_("Address")) resume = models.FileField(upload_to="resumes/", verbose_name=_("Resume")) @@ -294,7 +317,7 @@ class Candidate(Base): parsed_summary = models.TextField(blank=True, verbose_name=_("Parsed Summary")) applied = models.BooleanField(default=False, verbose_name=_("Applied")) stage = models.CharField( - max_length=100, + db_index=True, max_length=100, # Added index default="Applied", choices=Stage.choices, verbose_name=_("Stage"), @@ -319,7 +342,7 @@ class Candidate(Base): null=True, blank=True, verbose_name=_("Interview Date") ) interview_status = models.CharField( - choices=Status.choices, + choices=ExamStatus.choices, max_length=100, null=True, blank=True, @@ -334,13 +357,18 @@ class Candidate(Base): verbose_name=_("Offer Status"), ) join_date = models.DateField(null=True, blank=True, verbose_name=_("Join Date")) - + ai_analysis_data = models.JSONField( + verbose_name="AI Analysis Data", + default=dict, + help_text="Full JSON output from the resume scoring model." + ) # Scoring fields (populated by signal) - match_score = models.IntegerField(null=True, blank=True) - strengths = models.TextField(blank=True) - weaknesses = models.TextField(blank=True) - criteria_checklist = models.JSONField(default=dict, blank=True) - + # match_score = models.IntegerField(db_index=True, null=True, blank=True) # Added index + # strengths = models.TextField(blank=True) + # weaknesses = models.TextField(blank=True) + # criteria_checklist = models.JSONField(default=dict, blank=True) + # major_category_name = models.TextField(db_index=True, blank=True, verbose_name=_("Major Category Name")) # Added index + # recommendation = models.TextField(blank=True, verbose_name=_("Recommendation")) submitted_by_agency = models.ForeignKey( "HiringAgency", on_delete=models.SET_NULL, @@ -353,6 +381,103 @@ class Candidate(Base): class Meta: verbose_name = _("Candidate") verbose_name_plural = _("Candidates") + indexes = [ + models.Index(fields=['stage']), + models.Index(fields=['created_at']), + ] + def set_field(self, key: str, value: Any): + """ + Generic method to set any single key-value pair and save. + """ + self.ai_analysis_data[key] = value + self.save(update_fields=['ai_analysis_data']) + + # ==================================================================== + # ✨ PROPERTIES (GETTERS) + # ==================================================================== + + @property + def match_score(self) -> int: + """1. A score from 0 to 100 representing how well the candidate fits the role.""" + return self.ai_analysis_data.get('match_score', 0) + + @property + def years_of_experience(self) -> float: + """4. The total number of years of professional experience as a numerical value.""" + return self.ai_analysis_data.get('years_of_experience', 0.0) + + @property + def soft_skills_score(self) -> int: + """15. A score (0-100) for inferred non-technical skills.""" + return self.ai_analysis_data.get('soft_skills_score', 0) + + @property + def industry_match_score(self) -> int: + """16. A score (0-100) for the relevance of the candidate's industry experience.""" + # Renamed to clarify: experience_industry_match + return self.ai_analysis_data.get('experience_industry_match', 0) + + # --- Properties for Funnel & Screening Efficiency --- + + @property + def min_requirements_met(self) -> bool: + """14. Boolean (true/false) indicating if all non-negotiable minimum requirements are met.""" + return self.ai_analysis_data.get('min_req_met_bool', False) + + @property + def screening_stage_rating(self) -> str: + """13. A standardized rating (e.g., "A - Highly Qualified", "B - Qualified").""" + return self.ai_analysis_data.get('screening_stage_rating', 'N/A') + + @property + def top_3_keywords(self) -> List[str]: + """10. A list of the three most dominant and relevant technical skills or technologies.""" + return self.ai_analysis_data.get('top_3_keywords', []) + + @property + def most_recent_job_title(self) -> str: + """8. The candidate's most recent or current professional job title.""" + return self.ai_analysis_data.get('most_recent_job_title', 'N/A') + + # --- Properties for Structured Detail --- + + @property + def criteria_checklist(self) -> Dict[str, str]: + """5 & 6. An object rating the candidate's match for each specific criterion.""" + return self.ai_analysis_data.get('criteria_checklist', {}) + + @property + def professional_category(self) -> str: + """7. The most fitting professional field or category for the individual.""" + return self.ai_analysis_data.get('category', 'N/A') + + @property + def language_fluency(self) -> List[Dict[str, str]]: + """12. A list of languages and their fluency levels mentioned.""" + return self.ai_analysis_data.get('language_fluency', []) + + # --- Properties for Summaries and Narrative --- + + @property + def strengths(self) -> str: + """2. A brief summary of why the candidate is a strong fit.""" + return self.ai_analysis_data.get('strengths', '') + + @property + def weaknesses(self) -> str: + """3. A brief summary of where the candidate falls short or what criteria are missing.""" + return self.ai_analysis_data.get('weaknesses', '') + + @property + def job_fit_narrative(self) -> str: + """11. A single, concise sentence summarizing the core fit.""" + return self.ai_analysis_data.get('job_fit_narrative', '') + + @property + def recommendation(self) -> str: + """9. Provide a detailed final recommendation for the candidate.""" + # Using a more descriptive name to avoid conflict with potential built-in methods + return self.ai_analysis_data.get('recommendation', '') @property def name(self): @@ -448,16 +573,16 @@ class TrainingMaterial(Base): class ZoomMeeting(Base): class MeetingStatus(models.TextChoices): - SCHEDULED = "scheduled", _("Scheduled") + WAITING = "waiting", _("Waiting") STARTED = "started", _("Started") ENDED = "ended", _("Ended") CANCELLED = "cancelled",_("Cancelled") # Basic meeting details topic = models.CharField(max_length=255, verbose_name=_("Topic")) meeting_id = models.CharField( - max_length=20, unique=True, verbose_name=_("Meeting ID") + db_index=True, max_length=20, unique=True, verbose_name=_("Meeting ID") # Added index ) # Unique identifier for the meeting - start_time = models.DateTimeField(verbose_name=_("Start Time")) + start_time = models.DateTimeField(db_index=True, verbose_name=_("Start Time")) # Added index duration = models.PositiveIntegerField( verbose_name=_("Duration") ) # Duration in minutes @@ -483,10 +608,11 @@ class ZoomMeeting(Base): blank=True, null=True, verbose_name=_("Zoom Gateway Response") ) status = models.CharField( - max_length=20, + db_index=True, max_length=20, # Added index null=True, blank=True, verbose_name=_("Status"), + default=MeetingStatus.WAITING, ) # Timestamps @@ -494,20 +620,51 @@ class ZoomMeeting(Base): return self.topic +class MeetingComment(Base): + """ + Model for storing meeting comments/notes + """ + meeting = models.ForeignKey( + ZoomMeeting, + on_delete=models.CASCADE, + related_name="comments", + verbose_name=_("Meeting") + ) + author = models.ForeignKey( + User, + on_delete=models.CASCADE, + related_name="meeting_comments", + verbose_name=_("Author") + ) + content = CKEditor5Field( + verbose_name=_("Content"), + config_name='extends' + ) + # Inherited from Base: created_at, updated_at, slug + + class Meta: + verbose_name = _("Meeting Comment") + verbose_name_plural = _("Meeting Comments") + ordering = ['-created_at'] + + def __str__(self): + return f"Comment by {self.author.get_username()} on {self.meeting.topic}" + + class FormTemplate(Base): """ Represents a complete form template with multiple stages """ job = models.OneToOneField( - JobPosting, on_delete=models.CASCADE, related_name="form_template" + JobPosting, on_delete=models.CASCADE, related_name="form_template", db_index=True ) name = models.CharField(max_length=200, help_text="Name of the form template") description = models.TextField( blank=True, help_text="Description of the form template" ) created_by = models.ForeignKey( - User, on_delete=models.CASCADE, related_name="form_templates",null=True,blank=True + User, on_delete=models.CASCADE, related_name="form_templates",null=True,blank=True, db_index=True ) is_active = models.BooleanField( default=False, help_text="Whether this template is active" @@ -517,6 +674,10 @@ class FormTemplate(Base): ordering = ["-created_at"] verbose_name = "Form Template" verbose_name_plural = "Form Templates" + indexes = [ + models.Index(fields=['created_at']), + models.Index(fields=['is_active']), + ] def __str__(self): return self.name @@ -534,7 +695,7 @@ class FormStage(Base): """ template = models.ForeignKey( - FormTemplate, on_delete=models.CASCADE, related_name="stages" + FormTemplate, on_delete=models.CASCADE, related_name="stages", db_index=True ) name = models.CharField(max_length=200, help_text="Name of the stage") order = models.PositiveIntegerField( @@ -575,7 +736,7 @@ class FormField(Base): ] stage = models.ForeignKey( - FormStage, on_delete=models.CASCADE, related_name="fields" + FormStage, on_delete=models.CASCADE, related_name="fields", db_index=True ) label = models.CharField(max_length=200, help_text="Label for the field") field_type = models.CharField( @@ -666,7 +827,7 @@ class FormSubmission(Base): """ template = models.ForeignKey( - FormTemplate, on_delete=models.CASCADE, related_name="submissions" + FormTemplate, on_delete=models.CASCADE, related_name="submissions", db_index=True ) submitted_by = models.ForeignKey( User, @@ -674,17 +835,21 @@ class FormSubmission(Base): null=True, blank=True, related_name="form_submissions", + db_index=True ) - submitted_at = models.DateTimeField(auto_now_add=True) + submitted_at = models.DateTimeField(db_index=True, auto_now_add=True) # Added index applicant_name = models.CharField( max_length=200, blank=True, help_text="Name of the applicant" ) - applicant_email = models.EmailField(blank=True, help_text="Email of the applicant") + applicant_email = models.EmailField(db_index=True, blank=True, help_text="Email of the applicant") # Added index class Meta: ordering = ["-submitted_at"] verbose_name = "Form Submission" verbose_name_plural = "Form Submissions" + indexes = [ + models.Index(fields=['submitted_at']), + ] def __str__(self): return f"Submission for {self.template.name} - {self.submitted_at.strftime('%Y-%m-%d %H:%M')}" @@ -696,10 +861,10 @@ class FieldResponse(Base): """ submission = models.ForeignKey( - FormSubmission, on_delete=models.CASCADE, related_name="responses" + FormSubmission, on_delete=models.CASCADE, related_name="responses", db_index=True ) field = models.ForeignKey( - FormField, on_delete=models.CASCADE, related_name="responses" + FormField, on_delete=models.CASCADE, related_name="responses", db_index=True ) # Store the response value as JSON to handle different data types @@ -713,6 +878,10 @@ class FieldResponse(Base): class Meta: verbose_name = "Field Response" verbose_name_plural = "Field Responses" + indexes = [ + models.Index(fields=['submission']), + models.Index(fields=['field']), + ] def __str__(self): return f"Response to {self.field.label} in {self.submission}" @@ -950,11 +1119,11 @@ class InterviewSchedule(Base): """Stores the scheduling criteria for interviews""" job = models.ForeignKey( - JobPosting, on_delete=models.CASCADE, related_name="interview_schedules" + JobPosting, on_delete=models.CASCADE, related_name="interview_schedules", db_index=True ) candidates = models.ManyToManyField(Candidate, related_name="interview_schedules", blank=True,null=True) - start_date = models.DateField(verbose_name=_("Start Date")) - end_date = models.DateField(verbose_name=_("End Date")) + start_date = models.DateField(db_index=True, verbose_name=_("Start Date")) # Added index + end_date = models.DateField(db_index=True, verbose_name=_("End Date")) # Added index working_days = models.JSONField( verbose_name=_("Working Days") ) # Store days of week as [0,1,2,3,4] for Mon-Fri @@ -970,11 +1139,18 @@ class InterviewSchedule(Base): buffer_time = models.PositiveIntegerField( verbose_name=_("Buffer Time (minutes)"), default=0 ) - created_by = models.ForeignKey(User, on_delete=models.CASCADE) + created_by = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) # Added index def __str__(self): return f"Interview Schedule for {self.job.title}" + class Meta: + indexes = [ + models.Index(fields=['start_date']), + models.Index(fields=['end_date']), + models.Index(fields=['created_by']), + ] + class ScheduledInterview(Base): """Stores individual scheduled interviews""" @@ -983,21 +1159,22 @@ class ScheduledInterview(Base): Candidate, on_delete=models.CASCADE, related_name="scheduled_interviews", + db_index=True ) job = models.ForeignKey( - "JobPosting", on_delete=models.CASCADE, related_name="scheduled_interviews" + "JobPosting", on_delete=models.CASCADE, related_name="scheduled_interviews", db_index=True ) zoom_meeting = models.OneToOneField( - ZoomMeeting, on_delete=models.CASCADE, related_name="interview" + ZoomMeeting, on_delete=models.CASCADE, related_name="interview", db_index=True ) schedule = models.ForeignKey( - InterviewSchedule, on_delete=models.CASCADE, related_name="interviews",null=True,blank=True + InterviewSchedule, on_delete=models.CASCADE, related_name="interviews",null=True,blank=True, db_index=True ) - interview_date = models.DateField(verbose_name=_("Interview Date")) + interview_date = models.DateField(db_index=True, verbose_name=_("Interview Date")) # Added index interview_time = models.TimeField(verbose_name=_("Interview Time")) status = models.CharField( - max_length=20, + db_index=True, max_length=20, # Added index choices=[ ("scheduled", _("Scheduled")), ("confirmed", _("Confirmed")), @@ -1011,3 +1188,10 @@ class ScheduledInterview(Base): def __str__(self): return f"Interview with {self.candidate.name} for {self.job.title}" + + class Meta: + indexes = [ + models.Index(fields=['job', 'status']), + models.Index(fields=['interview_date', 'interview_time']), + models.Index(fields=['candidate', 'job']), + ] diff --git a/recruitment/tasks.py b/recruitment/tasks.py index 103fc4e..c70927e 100644 --- a/recruitment/tasks.py +++ b/recruitment/tasks.py @@ -4,14 +4,18 @@ import logging import requests from PyPDF2 import PdfReader from datetime import datetime +from django.db import transaction from .utils import create_zoom_meeting from recruitment.models import Candidate from .models import ScheduledInterview, ZoomMeeting, Candidate, JobPosting, InterviewSchedule logger = logging.getLogger(__name__) -OPENROUTER_API_KEY ='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' -OPENROUTER_MODEL = 'qwen/qwen-2.5-72b-instruct:free' +OPENROUTER_API_KEY ='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' +# OPENROUTER_MODEL = 'qwen/qwen-2.5-72b-instruct:free' +# OPENROUTER_MODEL = 'openai/gpt-oss-20b:free' +OPENROUTER_MODEL = 'openai/gpt-oss-20b' +# OPENROUTER_MODEL = 'mistralai/mistral-small-3.2-24b-instruct:free' if not OPENROUTER_API_KEY: logger.warning("OPENROUTER_API_KEY not set. Resume scoring will be skipped.") @@ -49,114 +53,324 @@ def ai_handler(prompt): res = response.json() content = res["choices"][0]['message']['content'] try: - + # print(content) content = content.replace("```json","").replace("```","") - res = json.loads(content) - + print("success response") + return {"status": "success", "data": res} except Exception as e: print(e) - - # res = raw_output["choices"][0]["message"]["content"] + return {"status": "error", "data": str(e)} else: print("error response") - return res + return {"status": "error", "data": response.json()} + + +# def handle_reume_parsing_and_scoring(pk): +# from django.db import transaction + +# logger.info(f"Scoring resume for candidate {pk}") +# instance = Candidate.objects.get(pk=pk) +# try: +# file_path = instance.resume.path +# with transaction.atomic(): +# if not os.path.exists(file_path): +# logger.warning(f"Resume file not found: {file_path}") +# return + +# resume_text = extract_text_from_pdf(file_path) +# job_detail= f"{instance.job.description} {instance.job.qualifications}" +# resume_parser_prompt = f""" +# You are an expert resume parser and summarizer. Given a resume in plain text format, extract and organize the following key-value information into a clean, valid JSON object: + +# full_name: Full name of the candidate +# current_title: Most recent or current job title +# location: City and state (or country if outside the U.S.) +# contact: Phone number and email (as a single string or separate fields) +# linkedin: LinkedIn profile URL (if present) +# github: GitHub or portfolio URL (if present) +# summary: Brief professional profile or summary (1–2 sentences) +# education: List of degrees, each with: +# institution +# degree +# year +# gpa (if provided) +# relevant_courses (as a list, if mentioned) +# skills: Grouped by category if possible (e.g., programming, big data, visualization), otherwise as a flat list of technologies/tools +# experience: List of roles, each with: +# company +# job_title +# location +# start_date and end_date (or "Present" if applicable) +# key_achievements (as a list of concise bullet points) +# projects: List of notable projects (if clearly labeled), each with: +# name +# year +# technologies_used +# brief_description +# Instructions: + +# Be concise but preserve key details. +# Normalize formatting (e.g., “Jun. 2014” → “2014-06”). +# Omit redundant or promotional language. +# If a section is missing, omit the key or set it to null/empty list as appropriate. +# Output only valid JSON—no markdown, no extra text. +# Now, process the following resume text: +# {resume_text} +# """ +# resume_parser_result = ai_handler(resume_parser_prompt) +# resume_scoring_prompt = f""" +# You are an expert technical recruiter. Your task is to score the following candidate for the role based on the provided job criteria. + +# **Job Criteria:** +# {job_detail} + +# **Candidate's Extracted Resume Json:** +# \"\"\" +# {resume_parser_result} +# \"\"\" + +# **Your Task:** +# Provide a response in strict JSON format with the following keys: +# 1. 'match_score': A score from 0 to 100 representing how well the candidate fits the role. +# 2. 'strengths': A brief summary of why the candidate is a strong fit, referencing specific criteria. +# 3. 'weaknesses': A brief summary of where the candidate falls short or what criteria are missing. +# 4. 'years_of_experience': The total number of years of professional experience mentioned in the resume as a numerical value (e.g., 6.5). +# 5. 'criteria_checklist': An object where you rate the candidate's match for each specific criterion (e.g., {{'Python': 'Met', 'AWS': 'Not Mentioned'}}). +# 6. 'criteria_checklist': An object where you rate the candidate's match for each specific criterion (e.g., {{'Python': 'Met', 'AWS': 'Not Mentioned'}}). +# 7. 'category': Based on the content provided, determine the most fitting professional field or category for the individual. (e.g., {{"category" : "Data Science"}}) only output the category name and no other text example ('Software Development', 'correct') , ('Software Development and devops','wrong'). +# 8. 'most_recent_job_title': The candidate's most recent or current professional job title. +# 9. 'recommendation': Provide a recommendation for the candidate (e.g., {{"recommendation": " +# Conclusion and Minor Considerations +# Overall Assessment: Highly Recommended Candidate. + +# [Candidate] is an exceptionally strong candidate for this role. His proven track record with the core technology stack (Django, Python, Docker, CI/CD) and relevant experience in large-scale, high-impact enterprise projects (Telecom BPM/MDM) make him an excellent technical fit. His fluency in Arabic and English directly addresses a major non-negotiable requirement. + +# The only minor area not explicitly mentioned is the mentoring aspect, but his senior level of experience and technical breadth strongly suggest he possesses the capability to mentor junior engineers. + +# The hiring manager should move forward with this candidate with high confidence. +# ."}}). +# 10. 'top_3_keywords': A list of the three most dominant and relevant technical skills or technologies from the resume that match the job criteria. +# 11. 'job_fit_narrative': A single, concise sentence summarizing the core fit. +# 12. 'language_fluency': A list of languages and their fluency levels mentioned. +# 13. 'screening_stage_rating': A standardized rating (e.g., "A - Highly Qualified", "B - Qualified"). +# 14. 'min_req_met_bool': Boolean (true/false) indicating if all non-negotiable minimum requirements are met. +# 15. 'soft_skills_score': A score (0-100) for inferred non-technical skills like leadership and communication. +# 16. 'experience_industry_match': A score (0-100) for the relevance of the candidate's industry experience. + +# Only output valid JSON. Do not include any other text. +# """ + +# resume_scoring_result = ai_handler(resume_scoring_prompt) + +# print(resume_scoring_result) + +# instance.parsed_summary = str(resume_parser_result) + + +# # Core Scores +# instance.set_field('match_score', resume_scoring_result.get('match_score', 0)) # Set default for int +# instance.set_field('years_of_experience', resume_scoring_result.get('years_of_experience', 0.0)) # Set default for float +# instance.set_field('soft_skills_score', resume_scoring_result.get('soft_skills_score', 0)) +# instance.set_field('experience_industry_match', resume_scoring_result.get('experience_industry_match', 0)) + +# # Screening & Funnel +# instance.set_field('min_req_met_bool', resume_scoring_result.get('min_req_met_bool', False)) # Set default for bool +# instance.set_field('screening_stage_rating', resume_scoring_result.get('screening_stage_rating', 'N/A')) +# instance.set_field('most_recent_job_title', resume_scoring_result.get('most_recent_job_title', 'N/A')) +# instance.set_field('top_3_keywords', resume_scoring_result.get('top_3_keywords', [])) # Set default for list + +# # Summaries & Narrative +# instance.set_field('strengths', resume_scoring_result.get('strengths', '')) +# instance.set_field('weaknesses', resume_scoring_result.get('weaknesses', '')) +# instance.set_field('job_fit_narrative', resume_scoring_result.get('job_fit_narrative', '')) +# instance.set_field('recommendation', resume_scoring_result.get('recommendation', '')) + +# # Structured Data +# instance.set_field('criteria_checklist', resume_scoring_result.get('criteria_checklist', {})) # Set default for dict +# instance.set_field('language_fluency', resume_scoring_result.get('language_fluency', [])) # Set default for list + +# instance.set_field('category', resume_scoring_result.get('category', 'Uncategorized')) # Use 'category' key + +# instance.is_resume_parsed = True + +# instance.save(update_fields=['ai_analysis_data', 'is_resume_parsed','parsed_summary']) + +# logger.info(f"Successfully scored resume for candidate {instance.id}") + +# except Exception as e: +# instance.is_resume_parsed = False +# instance.save(update_fields=['is_resume_parsed']) +# logger.error(f"Failed to score resume for candidate:{instance.pk} {e}") def handle_reume_parsing_and_scoring(pk): - logger.info(f"Scoring resume for candidate {pk}") + """ + Optimized Django-Q task to parse a resume, score the candidate against a job, + and atomically save the results. + """ + + # --- 1. Robust Object Retrieval (Prevents looping on DoesNotExist) --- try: instance = Candidate.objects.get(pk=pk) + except Candidate.DoesNotExist: + # Exit gracefully if the candidate was deleted after the task was queued + logger.warning(f"Candidate matching query does not exist for pk={pk}. Exiting task.") + print(f"Candidate matching query does not exist for pk={pk}. Exiting task.") + return + + logger.info(f"Scoring resume for candidate {pk}") + print(f"Scoring resume for candidate {pk}") + + # --- 2. I/O and Initial Data Check --- + try: file_path = instance.resume.path if not os.path.exists(file_path): logger.warning(f"Resume file not found: {file_path}") + print(f"Resume file not found: {file_path}") + # Consider marking the task as unsuccessful but don't re-queue return resume_text = extract_text_from_pdf(file_path) - job_detail= f"{instance.job.description} {instance.job.qualifications}" - resume_parser_prompt = f""" - You are an expert resume parser and summarizer. Given a resume in plain text format, extract and organize the following key-value information into a clean, valid JSON object: - - full_name: Full name of the candidate - current_title: Most recent or current job title - location: City and state (or country if outside the U.S.) - contact: Phone number and email (as a single string or separate fields) - linkedin: LinkedIn profile URL (if present) - github: GitHub or portfolio URL (if present) - summary: Brief professional profile or summary (1–2 sentences) - education: List of degrees, each with: - institution - degree - year - gpa (if provided) - relevant_courses (as a list, if mentioned) - skills: Grouped by category if possible (e.g., programming, big data, visualization), otherwise as a flat list of technologies/tools - experience: List of roles, each with: - company - job_title - location - start_date and end_date (or "Present" if applicable) - key_achievements (as a list of concise bullet points) - projects: List of notable projects (if clearly labeled), each with: - name - year - technologies_used - brief_description - Instructions: - - Be concise but preserve key details. - Normalize formatting (e.g., “Jun. 2014” → “2014-06”). - Omit redundant or promotional language. - If a section is missing, omit the key or set it to null/empty list as appropriate. - Output only valid JSON—no markdown, no extra text. - Now, process the following resume text: - {resume_text} - """ - resume_parser_result = ai_handler(resume_parser_prompt) - resume_scoring_prompt = f""" - You are an expert technical recruiter. Your task is to score the following candidate for the role of a Senior Data Analyst based on the provided job criteria. - - **Job Criteria:** - {job_detail} - - **Candidate's Extracted Resume Json:** - \"\"\" - {resume_parser_result} - \"\"\" - - **Your Task:** - Provide a response in strict JSON format with the following keys: - 1. 'match_score': A score from 0 to 100 representing how well the candidate fits the role. - 2. 'strengths': A brief summary of why the candidate is a strong fit, referencing specific criteria. - 3. 'weaknesses': A brief summary of where the candidate falls short or what criteria are missing. - 4. 'criteria_checklist': An object where you rate the candidate's match for each specific criterion (e.g., {{'Python': 'Met', 'AWS': 'Not Mentioned'}}). - - - Only output valid JSON. Do not include any other text. - """ - - resume_scoring_result = ai_handler(resume_scoring_prompt) - - instance.parsed_summary = str(resume_parser_result) - - # Update candidate with scoring results - instance.match_score = resume_scoring_result.get('match_score') - instance.strengths = resume_scoring_result.get('strengths', '') - instance.weaknesses = resume_scoring_result.get('weaknesses', '') - instance.criteria_checklist = resume_scoring_result.get('criteria_checklist', {}) - - instance.is_resume_parsed = True - - # Save only scoring-related fields to avoid recursion - instance.save(update_fields=[ - 'match_score', 'strengths', 'weaknesses', - 'criteria_checklist','parsed_summary', 'is_resume_parsed' - ]) - - logger.info(f"Successfully scored resume for candidate {instance.id}") + job_detail = f"{instance.job.description} {instance.job.qualifications}" except Exception as e: - logger.error(f"Failed to score resume for candidate {instance.id}: {e}") + logger.error(f"Error during initial data retrieval/parsing for candidate {instance.pk}: {e}") + print(f"Error during initial data retrieval/parsing for candidate {instance.pk}: {e}") + return + # --- 3. Single, Combined LLM Prompt (Major Cost & Latency Optimization) --- + prompt = f""" + You are an expert AI system functioning as both a Resume Parser and a Technical Recruiter. + + Your task is to: + 1. **PARSE**: Extract all key-value information from the provided RESUME TEXT into a clean JSON structure under the key 'parsed_data'. + 2. **SCORE**: Analyze the parsed data against the JOB CRITERIA and generate a comprehensive score and analysis under the key 'scoring_data'. + + **JOB CRITERIA:** + {job_detail} + + **RESUME TEXT:** + {resume_text} + + **STRICT JSON OUTPUT INSTRUCTIONS:** + Output a single, valid JSON object with ONLY the following two top-level keys: + + 1. "parsed_data": {{ + "full_name": "Full name of the candidate", + "current_title": "Most recent or current job title", + "location": "City and state", + "contact": "Phone number and email", + "linkedin": "LinkedIn profile URL", + "github": "GitHub or portfolio URL", + "summary": "Brief professional profile or summary (1–2 sentences)", + "education": [{{ + "institution": "Institution name", + "degree": "Degree name", + "year": "Year of graduation", + "gpa": "GPA (if provided)", + "relevant_courses": ["list", "of", "courses"] + }}], + "skills": {{ + "category_1": ["skill_a", "skill_b"], + "uncategorized": ["tool_x"] + }}, + "experience": [{{ + "company": "Company name", + "job_title": "Job Title", + "location": "Location", + "start_date": "YYYY-MM", + "end_date": "YYYY-MM or Present", + "key_achievements": ["concise", "bullet", "points"] + }}], + "projects": [{{ + "name": "Project name", + "year": "Year", + "technologies_used": ["list", "of", "tech"], + "brief_description": "description" + }}] + }} + + 2. "scoring_data": {{ + "match_score": "Score 0-100", + "strengths": "Brief summary of strengths", + "weaknesses": "Brief summary of weaknesses", + "years_of_experience": "Total years of experience (float, e.g., 6.5)", + "criteria_checklist": {{ "Python": "Met", "AWS": "Not Mentioned"}}, + "category": "Most fitting professional field (e.g., Data Science)", + "most_recent_job_title": "Candidate's most recent job title", + "recommendation": "Detailed hiring recommendation narrative", + "top_3_keywords": ["keyword1", "keyword2", "keyword3"], + "job_fit_narrative": "Single, concise summary sentence", + "language_fluency": ["language: fluency_level"], + "screening_stage_rating": "Standardized rating (e.g., A - Highly Qualified)", + "min_req_met_bool": "Boolean (true/false)", + "soft_skills_score": "Score 0-100 for inferred non-technical skills", + "experience_industry_match": "Score 0-100 for industry relevance" + }} + + If a top-level key or its required fields are missing, set the field to null, an empty list, or an empty object as appropriate. + + Output only valid JSON—no markdown, no extra text. + """ + + try: + result = ai_handler(prompt) + if result['status'] == 'error': + logger.error(f"AI handler returned error for candidate {instance.pk}") + print(f"AI handler returned error for candidate {instance.pk}") + return + # Ensure the result is parsed as a Python dict (if ai_handler returns a JSON string) + data = result['data'] + if isinstance(data, str): + data = json.loads(data) + print(data) + + parsed_summary = data.get('parsed_data', {}) + scoring_result = data.get('scoring_data', {}) + + except Exception as e: + logger.error(f"AI handler failed for candidate {instance.pk}: {e}") + print(f"AI handler failed for candidate {instance.pk}: {e}") + return + + # --- 4. Atomic Database Update (Ensures data integrity) --- + with transaction.atomic(): + + # Map JSON keys to model fields with appropriate defaults + update_map = { + 'match_score': ('match_score', 0), + 'years_of_experience': ('years_of_experience', 0.0), + 'soft_skills_score': ('soft_skills_score', 0), + 'experience_industry_match': ('experience_industry_match', 0), + + 'min_req_met_bool': ('min_req_met_bool', False), + 'screening_stage_rating': ('screening_stage_rating', 'N/A'), + 'most_recent_job_title': ('most_recent_job_title', 'N/A'), + 'top_3_keywords': ('top_3_keywords', []), + + 'strengths': ('strengths', ''), + 'weaknesses': ('weaknesses', ''), + 'job_fit_narrative': ('job_fit_narrative', ''), + 'recommendation': ('recommendation', ''), + + 'criteria_checklist': ('criteria_checklist', {}), + 'language_fluency': ('language_fluency', []), + 'category': ('category', 'N/A'), + } + + # Apply scoring results to the instance + for model_field, (json_key, default_value) in update_map.items(): + instance.ai_analysis_data[model_field] = scoring_result.get(json_key, default_value) + # instance.set_field(model_field, scoring_result.get(json_key, default_value)) + + # Apply parsing results + instance.parsed_summary = json.dumps(parsed_summary) + instance.is_resume_parsed = True + + instance.save(update_fields=['ai_analysis_data','parsed_summary', 'is_resume_parsed']) + + logger.info(f"Successfully scored and saved analysis for candidate {instance.id}") + print(f"Successfully scored and saved analysis for candidate {instance.id}") def create_interview_and_meeting( candidate_id, @@ -189,6 +403,8 @@ def create_interview_and_meeting( meeting_id=result["meeting_details"]["meeting_id"], join_url=result["meeting_details"]["join_url"], zoom_gateway_response=result["zoom_gateway_response"], + host_email=result["meeting_details"]["host_email"], + password=result["meeting_details"]["password"] ) ScheduledInterview.objects.create( candidate=candidate, @@ -249,8 +465,7 @@ def handle_zoom_webhook_event(payload): meeting_instance.duration = object_data.get('duration', meeting_instance.duration) meeting_instance.timezone = object_data.get('timezone', meeting_instance.timezone) - # Also update join_url, password, etc., if needed based on the payload structure - meeting_instance.status = 'scheduled' + meeting_instance.status = object_data.get('status', meeting_instance.status) meeting_instance.save(update_fields=['topic', 'start_time', 'duration', 'timezone', 'status']) @@ -268,9 +483,11 @@ def handle_zoom_webhook_event(payload): # --- 3. Deletion Event (User Action) --- elif event_type == 'meeting.deleted': if meeting_instance: - # Mark as cancelled/deleted instead of physically deleting for audit trail - meeting_instance.status = 'cancelled' - meeting_instance.save(update_fields=['status']) + try: + meeting_instance.status = 'cancelled' + meeting_instance.save(update_fields=['status']) + except Exception as e: + logger.error(f"Failed to mark Zoom meeting as cancelled: {e}") return True diff --git a/recruitment/templatetags/__pycache__/form_filters.cpython-313.pyc b/recruitment/templatetags/__pycache__/form_filters.cpython-313.pyc index 0d10186..b9a5e2b 100644 Binary files a/recruitment/templatetags/__pycache__/form_filters.cpython-313.pyc and b/recruitment/templatetags/__pycache__/form_filters.cpython-313.pyc differ diff --git a/recruitment/tests.py b/recruitment/tests.py index 7ce503c..ecf0a7b 100644 --- a/recruitment/tests.py +++ b/recruitment/tests.py @@ -1,3 +1,626 @@ -from django.test import TestCase +from django.test import TestCase, Client +from django.contrib.auth.models import User +from django.urls import reverse +from django.utils import timezone +from django.core.files.uploadedfile import SimpleUploadedFile +from datetime import datetime, time, timedelta +import json +from unittest.mock import patch, MagicMock -# Create your tests here. +from .models import ( + JobPosting, Candidate, ZoomMeeting, FormTemplate, FormStage, FormField, + FormSubmission, FieldResponse, InterviewSchedule, ScheduledInterview, + TrainingMaterial, Source, HiringAgency, Profile, MeetingComment +) +from .forms import ( + JobPostingForm, CandidateForm, ZoomMeetingForm, MeetingCommentForm, + CandidateStageForm, InterviewScheduleForm +) +from .views import ( + ZoomMeetingListView, ZoomMeetingCreateView, job_detail, candidate_screening_view, + candidate_exam_view, candidate_interview_view, submit_form, api_schedule_candidate_meeting +) +from .views_frontend import CandidateListView, JobListView +from .utils import create_zoom_meeting, get_candidates_from_request + + +class BaseTestCase(TestCase): + """Base test case setup with common test data""" + + def setUp(self): + self.client = Client() + self.user = User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=True + ) + self.profile = Profile.objects.create(user=self.user) + + # Create test data + self.job = JobPosting.objects.create( + title='Software Engineer', + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + location_country='Saudi Arabia', + description='Job description', + qualifications='Job qualifications', + created_by=self.user + ) + + self.candidate = Candidate.objects.create( + first_name='John', + last_name='Doe', + email='john@example.com', + phone='1234567890', + resume=SimpleUploadedFile('resume.pdf', b'file_content', content_type='application/pdf'), + job=self.job, + stage='Applied' + ) + + self.zoom_meeting = ZoomMeeting.objects.create( + topic='Interview with John Doe', + start_time=timezone.now() + timedelta(hours=1), + duration=60, + timezone='UTC', + join_url='https://zoom.us/j/123456789', + meeting_id='123456789' + ) + + +class ModelTests(BaseTestCase): + """Test cases for models""" + + def test_job_posting_creation(self): + """Test JobPosting model creation""" + self.assertEqual(self.job.title, 'Software Engineer') + self.assertEqual(self.job.department, 'IT') + self.assertIsNotNone(self.job.slug) + self.assertEqual(self.job.status, 'DRAFT') + + def test_job_posting_unique_id_generation(self): + """Test unique internal job ID generation""" + self.assertTrue(self.job.internal_job_id.startswith('KAAUH')) + self.assertIn(str(timezone.now().year), self.job.internal_job_id) + + def test_job_posting_methods(self): + """Test JobPosting model methods""" + # Test is_expired method + self.assertFalse(self.job.is_expired()) + + # Test location display + self.assertIn('Saudi Arabia', self.job.get_location_display()) + + def test_candidate_creation(self): + """Test Candidate model creation""" + self.assertEqual(self.candidate.first_name, 'John') + self.assertEqual(self.candidate.stage, 'Applied') + self.assertEqual(self.candidate.job, self.job) + + def test_candidate_stage_transitions(self): + """Test candidate stage transition logic""" + # Test current available stages + available_stages = self.candidate.get_available_stages() + self.assertIn('Exam', available_stages) + self.assertIn('Interview', available_stages) + + def test_zoom_meeting_creation(self): + """Test ZoomMeeting model creation""" + self.assertEqual(self.zoom_meeting.topic, 'Interview with John Doe') + self.assertEqual(self.zoom_meeting.duration, 60) + self.assertIsNotNone(self.zoom_meeting.meeting_id) + + def test_template_creation(self): + """Test FormTemplate model creation""" + template = FormTemplate.objects.create( + name='Test Template', + job=self.job, + created_by=self.user + ) + self.assertEqual(template.name, 'Test Template') + self.assertEqual(template.job, self.job) + + def test_scheduled_interview_creation(self): + """Test ScheduledInterview model creation""" + scheduled = ScheduledInterview.objects.create( + candidate=self.candidate, + job=self.job, + zoom_meeting=self.zoom_meeting, + interview_date=timezone.now().date(), + interview_time=time(10, 0), + status='scheduled' + ) + self.assertEqual(scheduled.candidate, self.candidate) + self.assertEqual(scheduled.status, 'scheduled') + + +class ViewTests(BaseTestCase): + """Test cases for views""" + + def test_job_list_view(self): + """Test JobListView""" + response = self.client.get(reverse('job_list')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Software Engineer') + + def test_job_list_search(self): + """Test JobListView search functionality""" + response = self.client.get(reverse('job_list'), {'search': 'Software'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Software Engineer') + + def test_job_detail_view(self): + """Test job_detail view""" + response = self.client.get(reverse('job_detail', kwargs={'slug': self.job.slug})) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Software Engineer') + self.assertContains(response, 'John Doe') + + def test_zoom_meeting_list_view(self): + """Test ZoomMeetingListView""" + response = self.client.get(reverse('list_meetings')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Interview with John Doe') + + def test_zoom_meeting_list_search(self): + """Test ZoomMeetingListView search functionality""" + response = self.client.get(reverse('list_meetings'), {'q': 'Interview'}) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Interview with John Doe') + + def test_zoom_meeting_list_filter_status(self): + """Test ZoomMeetingListView status filter""" + response = self.client.get(reverse('list_meetings'), {'status': 'waiting'}) + self.assertEqual(response.status_code, 200) + + def test_zoom_meeting_create_view(self): + """Test ZoomMeetingCreateView""" + self.client.login(username='testuser', password='testpass123') + response = self.client.get(reverse('create_meeting')) + self.assertEqual(response.status_code, 200) + + def test_candidate_screening_view(self): + """Test candidate_screening_view""" + response = self.client.get(reverse('candidate_screening_view', kwargs={'slug': self.job.slug})) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'John Doe') + + def test_candidate_screening_view_filters(self): + """Test candidate_screening_view with filters""" + response = self.client.get( + reverse('candidate_screening_view', kwargs={'slug': self.job.slug}), + {'min_ai_score': '50', 'tier1_count': '5'} + ) + self.assertEqual(response.status_code, 200) + + def test_candidate_exam_view(self): + """Test candidate_exam_view""" + response = self.client.get(reverse('candidate_exam_view', kwargs={'slug': self.job.slug})) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'John Doe') + + def test_candidate_interview_view(self): + """Test candidate_interview_view""" + response = self.client.get(reverse('candidate_interview_view', kwargs={'slug': self.job.slug})) + self.assertEqual(response.status_code, 200) + + @patch('recruitment.views.create_zoom_meeting') + def test_schedule_candidate_meeting(self, mock_create_zoom): + """Test api_schedule_candidate_meeting view""" + mock_create_zoom.return_value = { + 'status': 'success', + 'meeting_details': { + 'meeting_id': '987654321', + 'join_url': 'https://zoom.us/j/987654321', + 'password': '123456' + }, + 'zoom_gateway_response': {'status': 'waiting'} + } + + self.client.login(username='testuser', password='testpass123') + data = { + 'start_time': (timezone.now() + timedelta(hours=2)).isoformat(), + 'duration': 60 + } + response = self.client.post( + reverse('api_schedule_candidate_meeting', + kwargs={'job_slug': self.job.slug, 'candidate_pk': self.candidate.pk}), + data + ) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'success') + + def test_submit_form(self): + """Test submit_form view""" + # Create a form template first + template = FormTemplate.objects.create( + job=self.job, + name='Test Template', + created_by=self.user, + is_active=True + ) + + data = { + 'field_1': 'John', # Assuming field ID 1 corresponds to First Name + 'field_2': 'Doe', # Assuming field ID 2 corresponds to Last Name + 'field_3': 'john@example.com', # Email + } + + response = self.client.post( + reverse('submit_form', kwargs={'template_id': template.id}), + data + ) + # After successful submission, should redirect to success page + self.assertEqual(response.status_code, 302) + + +class FormTests(BaseTestCase): + """Test cases for forms""" + + def test_job_posting_form(self): + """Test JobPostingForm""" + form_data = { + 'title': 'New Job Title', + 'department': 'New Department', + 'job_type': 'FULL_TIME', + 'workplace_type': 'REMOTE', + 'location_city': 'Riyadh', + 'location_state': 'Riyadh', + 'location_country': 'Saudi Arabia', + 'description': 'Job description', + 'qualifications': 'Job qualifications', + 'salary_range': '5000-7000', + 'application_deadline': '2025-12-31', + 'max_applications': '100', + 'open_positions': '2', + 'hash_tags': '#hiring, #jobopening' + } + form = JobPostingForm(data=form_data) + self.assertTrue(form.is_valid()) + + def test_candidate_form(self): + """Test CandidateForm""" + form_data = { + 'job': self.job.id, + 'first_name': 'Jane', + 'last_name': 'Smith', + 'phone': '9876543210', + 'email': 'jane@example.com', + 'resume': SimpleUploadedFile('resume.pdf', b'file_content', content_type='application/pdf') + } + form = CandidateForm(data=form_data, files=form_data) + self.assertTrue(form.is_valid()) + + def test_zoom_meeting_form(self): + """Test ZoomMeetingForm""" + form_data = { + 'topic': 'Test Meeting', + 'start_time': (timezone.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M'), + 'duration': 60 + } + form = ZoomMeetingForm(data=form_data) + self.assertTrue(form.is_valid()) + + def test_meeting_comment_form(self): + """Test MeetingCommentForm""" + form_data = { + 'content': 'This is a test comment' + } + form = MeetingCommentForm(data=form_data) + self.assertTrue(form.is_valid()) + + def test_candidate_stage_form(self): + """Test CandidateStageForm with valid transition""" + form_data = { + 'stage': 'Exam' + } + form = CandidateStageForm(data=form_data, candidate=self.candidate) + self.assertTrue(form.is_valid()) + + def test_interview_schedule_form(self): + """Test InterviewScheduleForm""" + form_data = { + 'candidates': [self.candidate.id], + 'start_date': (timezone.now() + timedelta(days=1)).date(), + 'end_date': (timezone.now() + timedelta(days=7)).date(), + 'working_days': [0, 1, 2, 3, 4], # Monday to Friday + 'start_time': '09:00', + 'end_time': '17:00', + 'interview_duration': 60, + 'buffer_time': 15 + } + form = InterviewScheduleForm(slug=self.job.slug, data=form_data) + self.assertTrue(form.is_valid()) + + +class IntegrationTests(BaseTestCase): + """Integration tests for multiple components""" + + def test_candidate_journey(self): + """Test the complete candidate journey from application to interview""" + # 1. Create candidate + candidate = Candidate.objects.create( + first_name='Jane', + last_name='Smith', + email='jane@example.com', + phone='9876543210', + resume=SimpleUploadedFile('resume.pdf', b'file_content', content_type='application/pdf'), + job=self.job, + stage='Applied' + ) + + # 2. Move to Exam stage + candidate.stage = 'Exam' + candidate.save() + + # 3. Move to Interview stage + candidate.stage = 'Interview' + candidate.save() + + # 4. Create interview schedule + scheduled_interview = ScheduledInterview.objects.create( + candidate=candidate, + job=self.job, + zoom_meeting=self.zoom_meeting, + interview_date=timezone.now().date(), + interview_time=time(10, 0), + status='scheduled' + ) + + # 5. Verify all stages and relationships + self.assertEqual(Candidate.objects.count(), 2) + self.assertEqual(ScheduledInterview.objects.count(), 1) + self.assertEqual(candidate.stage, 'Interview') + self.assertEqual(scheduled_interview.candidate, candidate) + + def test_meeting_candidate_association(self): + """Test the association between meetings and candidates""" + # Create a scheduled interview + scheduled_interview = ScheduledInterview.objects.create( + candidate=self.candidate, + job=self.job, + zoom_meeting=self.zoom_meeting, + interview_date=timezone.now().date(), + interview_time=time(10, 0), + status='scheduled' + ) + + # Verify the relationship + self.assertEqual(self.zoom_meeting.interview, scheduled_interview) + self.assertEqual(self.candidate.get_meetings().count(), 1) + + def test_form_submission_candidate_creation(self): + """Test creating a candidate through form submission""" + # Create a form template + template = FormTemplate.objects.create( + job=self.job, + name='Application Form', + created_by=self.user, + is_active=True + ) + + # Create form stages and fields + stage = FormStage.objects.create( + template=template, + name='Personal Information', + order=0 + ) + + FormField.objects.create( + stage=stage, + label='First Name', + field_type='text', + order=0 + ) + FormField.objects.create( + stage=stage, + label='Last Name', + field_type='text', + order=1 + ) + FormField.objects.create( + stage=stage, + label='Email', + field_type='email', + order=2 + ) + + # Submit form data + form_data = { + 'field_1': 'New', + 'field_2': 'Candidate', + 'field_3': 'new@example.com' + } + + response = self.client.post( + reverse('submit_form', kwargs={'template_id': template.id}), + form_data + ) + + # Verify candidate was created + self.assertEqual(Candidate.objects.filter(email='new@example.com').count(), 1) + + +class PerformanceTests(BaseTestCase): + """Basic performance tests""" + + def test_large_dataset_pagination(self): + """Test pagination with large datasets""" + # Create many candidates + for i in range(100): + Candidate.objects.create( + first_name=f'Candidate{i}', + last_name=f'Test{i}', + email=f'candidate{i}@example.com', + phone=f'123456789{i}', + job=self.job, + stage='Applied' + ) + + # Test pagination + response = self.client.get(reverse('candidate_list')) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Candidate') + + +class AuthenticationTests(BaseTestCase): + """Authentication and permission tests""" + + def test_unauthorized_access(self): + """Test that unauthorized users cannot access protected views""" + # Create a non-staff user + regular_user = User.objects.create_user( + username='regularuser', + email='regular@example.com', + password='testpass123' + ) + + # Try to access a view that requires staff privileges + self.client.login(username='regularuser', password='testpass123') + response = self.client.get(reverse('job_list')) + # Should still be accessible for now (can be adjusted based on actual requirements) + self.assertEqual(response.status_code, 200) + + def test_login_required(self): + """Test that login is required for certain operations""" + # Test form submission without login + template = FormTemplate.objects.create( + job=self.job, + name='Test Template', + created_by=self.user, + is_active=True + ) + + response = self.client.post( + reverse('submit_form', kwargs={'template_id': template.id}), + {} + ) + # Should redirect to login page + self.assertEqual(response.status_code, 302) + + +class EdgeCaseTests(BaseTestCase): + """Tests for edge cases and error handling""" + + def test_invalid_job_id(self): + """Test handling of invalid job slug""" + response = self.client.get(reverse('job_detail', kwargs={'slug': 'invalid-slug'})) + self.assertEqual(response.status_code, 404) + + def test_meeting_past_time(self): + """Test handling of meeting with past time""" + # This would be tested in the view that validates meeting time + pass + + def test_duplicate_submission(self): + """Test handling of duplicate form submissions""" + # Create form template + template = FormTemplate.objects.create( + job=self.job, + name='Test Template', + created_by=self.user, + is_active=True + ) + + # Submit form twice + response1 = self.client.post( + reverse('submit_form', kwargs={'template_id': template.id}), + {'field_1': 'John', 'field_2': 'Doe'} + ) + + # This should be handled by the view logic + # Currently, it would create a duplicate candidate + # We can add validation to prevent this if needed + + def test_invalid_stage_transition(self): + """Test invalid candidate stage transitions""" + # Try to transition from Interview back to Applied (should be invalid) + self.candidate.stage = 'Interview' + self.candidate.save() + + # The model should prevent this through validation + # This would be tested in the model's clean method or view logic + pass + + +class UtilityFunctionTests(BaseTestCase): + """Tests for utility functions""" + + @patch('recruitment.views.create_zoom_meeting') + def test_create_zoom_meeting_utility(self, mock_create): + """Test the create_zoom_meeting utility function""" + mock_create.return_value = { + 'status': 'success', + 'meeting_details': { + 'meeting_id': '123456789', + 'join_url': 'https://zoom.us/j/123456789' + } + } + + result = create_zoom_meeting( + topic='Test Meeting', + start_time=timezone.now() + timedelta(hours=1), + duration=60 + ) + + self.assertEqual(result['status'], 'success') + self.assertIn('meeting_id', result['meeting_details']) + + def test_get_candidates_from_request(self): + """Test the get_candidates_from_request utility function""" + # This would be tested with a request that has candidate_ids + pass + + +# Factory classes for test data (can be expanded with factory_boy) +class TestFactories: + """Factory methods for creating test data""" + + @staticmethod + def create_job_posting(**kwargs): + defaults = { + 'title': 'Test Job', + 'department': 'Test Department', + 'job_type': 'FULL_TIME', + 'workplace_type': 'ON_SITE', + 'location_country': 'Saudi Arabia', + 'description': 'Test description', + 'created_by': User.objects.create_user('factoryuser', 'factory@example.com', 'password') + } + defaults.update(kwargs) + return JobPosting.objects.create(**defaults) + + @staticmethod + def create_candidate(**kwargs): + job = TestFactories.create_job_posting() + defaults = { + 'first_name': 'Test', + 'last_name': 'Candidate', + 'email': 'test@example.com', + 'phone': '1234567890', + 'job': job, + 'stage': 'Applied' + } + defaults.update(kwargs) + return Candidate.objects.create(**defaults) + + @staticmethod + def create_zoom_meeting(**kwargs): + defaults = { + 'topic': 'Test Meeting', + 'start_time': timezone.now() + timedelta(hours=1), + 'duration': 60, + 'timezone': 'UTC', + 'join_url': 'https://zoom.us/j/test123', + 'meeting_id': 'test123' + } + defaults.update(kwargs) + return ZoomMeeting.objects.create(**defaults) + + +# Test runner configuration (can be added to settings) +""" +TEST_RUNNER = 'django.test.runner.DiscoverRunner' +TEST_DISCOVER_TOPS = ['recruitment'] +""" diff --git a/recruitment/tests_advanced.py b/recruitment/tests_advanced.py new file mode 100644 index 0000000..70f1dac --- /dev/null +++ b/recruitment/tests_advanced.py @@ -0,0 +1,1078 @@ +""" +Advanced test cases for the recruitment application. +These tests cover complex scenarios, API integrations, and edge cases. +""" + +from django.test import TestCase, Client, TransactionTestCase +from django.contrib.auth.models import User, Group +from django.urls import reverse +from django.utils import timezone +from django.core.files.uploadedfile import SimpleUploadedFile +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from django.db.models import ProtectedError, Q +from django.test.utils import override_settings +from django.core.management import call_command +from django.conf import settings +from unittest.mock import patch, MagicMock, Mock +from datetime import datetime, time, timedelta, date +import json +import os +import tempfile +from io import BytesIO +from PIL import Image + +from .models import ( + JobPosting, Candidate, ZoomMeeting, FormTemplate, FormStage, FormField, + FormSubmission, FieldResponse, InterviewSchedule, ScheduledInterview, + TrainingMaterial, Source, HiringAgency, Profile, MeetingComment, JobPostingImage, + BreakTime +) +from .forms import ( + JobPostingForm, CandidateForm, ZoomMeetingForm, MeetingCommentForm, + CandidateStageForm, InterviewScheduleForm, BreakTimeFormSet +) +from .views import ( + ZoomMeetingListView, ZoomMeetingCreateView, job_detail, candidate_screening_view, + candidate_exam_view, candidate_interview_view, submit_form, api_schedule_candidate_meeting, + schedule_interviews_view, confirm_schedule_interviews_view, _handle_preview_submission, + _handle_confirm_schedule, _handle_get_request +) +from .views_frontend import CandidateListView, JobListView, JobCreateView +from .utils import ( + create_zoom_meeting, delete_zoom_meeting, update_zoom_meeting, + get_zoom_meeting_details, get_candidates_from_request, + get_available_time_slots +) +from .zoom_api import ZoomAPIError + + +class AdvancedModelTests(TestCase): + """Advanced model tests with complex scenarios""" + + def setUp(self): + self.user = User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=True + ) + self.profile = Profile.objects.create(user=self.user) + + self.job = JobPosting.objects.create( + title='Software Engineer', + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + location_country='Saudi Arabia', + description='Job description', + qualifications='Job qualifications', + created_by=self.user, + max_applications=10, + open_positions=2 + ) + + def test_job_posting_complex_validation(self): + """Test complex validation scenarios for JobPosting""" + # Test with valid data + valid_data = { + 'title': 'Valid Job Title', + 'department': 'IT', + 'job_type': 'FULL_TIME', + 'workplace_type': 'REMOTE', + 'location_city': 'Riyadh', + 'location_state': 'Riyadh', + 'location_country': 'Saudi Arabia', + 'description': 'Job description', + 'qualifications': 'Job qualifications', + 'salary_range': '5000-7000', + 'application_deadline': '2025-12-31', + 'max_applications': '100', + 'open_positions': '2', + 'hash_tags': '#hiring, #jobopening' + } + form = JobPostingForm(data=valid_data) + self.assertTrue(form.is_valid()) + + def test_job_posting_invalid_data_scenarios(self): + """Test various invalid data scenarios for JobPosting""" + # Test empty title + invalid_data = { + 'title': '', + 'department': 'IT', + 'job_type': 'FULL_TIME', + 'workplace_type': 'REMOTE' + } + form = JobPostingForm(data=invalid_data) + self.assertFalse(form.is_valid()) + self.assertIn('title', form.errors) + + # Test invalid max_applications + invalid_data['title'] = 'Test Job' + invalid_data['max_applications'] = '0' + form = JobPostingForm(data=invalid_data) + self.assertFalse(form.is_valid()) + + # Test invalid hash_tags + invalid_data['max_applications'] = '100' + invalid_data['hash_tags'] = 'invalid hash tags without #' + form = JobPostingForm(data=invalid_data) + self.assertFalse(form.is_valid()) + + def test_candidate_stage_transition_validation(self): + """Test advanced candidate stage transition validation""" + candidate = Candidate.objects.create( + first_name='John', + last_name='Doe', + email='john@example.com', + phone='1234567890', + job=self.job, + stage='Applied' + ) + + # Test valid transitions + valid_transitions = ['Exam', 'Interview', 'Offer'] + for stage in valid_transitions: + candidate.stage = stage + candidate.save() + form = CandidateStageForm(data={'stage': stage}, candidate=candidate) + self.assertTrue(form.is_valid()) + + # Test invalid transition (e.g., from Offer back to Applied) + candidate.stage = 'Offer' + candidate.save() + form = CandidateStageForm(data={'stage': 'Applied'}, candidate=candidate) + # This should fail based on your STAGE_SEQUENCE logic + # Note: You'll need to implement can_transition_to method in Candidate model + + def test_zoom_meeting_conflict_detection(self): + """Test conflict detection for overlapping meetings""" + # Create a meeting + meeting1 = ZoomMeeting.objects.create( + topic='Meeting 1', + start_time=timezone.now() + timedelta(hours=1), + duration=60, + timezone='UTC', + join_url='https://zoom.us/j/123456789', + meeting_id='123456789' + ) + + # Try to create overlapping meeting (this logic would be in your view/service) + # This is a placeholder for actual conflict detection implementation + with self.assertRaises(ValidationError): + # This would trigger your conflict validation + pass + + def test_form_template_integrity(self): + """Test form template data integrity""" + template = FormTemplate.objects.create( + job=self.job, + name='Test Template', + created_by=self.user + ) + + # Create stages + stage1 = FormStage.objects.create(template=template, name='Stage 1', order=0) + stage2 = FormStage.objects.create(template=template, name='Stage 2', order=1) + + # Create fields + field1 = FormField.objects.create( + stage=stage1, label='Field 1', field_type='text', order=0 + ) + field2 = FormField.objects.create( + stage=stage1, label='Field 2', field_type='email', order=1 + ) + + # Test stage ordering + stages = template.stages.all() + self.assertEqual(stages[0], stage1) + self.assertEqual(stages[1], stage2) + + # Test field ordering within stage + fields = stage1.fields.all() + self.assertEqual(fields[0], field1) + self.assertEqual(fields[1], field2) + + def test_interview_schedule_complex_validation(self): + """Test interview schedule validation with complex constraints""" + # Create candidates + candidate1 = Candidate.objects.create( + first_name='John', last_name='Doe', email='john@example.com', + phone='1234567890', job=self.job, stage='Interview' + ) + candidate2 = Candidate.objects.create( + first_name='Jane', last_name='Smith', email='jane@example.com', + phone='9876543210', job=self.job, stage='Interview' + ) + + # Create schedule with valid data + schedule_data = { + 'candidates': [candidate1.id, candidate2.id], + 'start_date': date.today() + timedelta(days=1), + 'end_date': date.today() + timedelta(days=7), + 'working_days': [0, 1, 2, 3, 4], # Mon-Fri + 'start_time': '09:00', + 'end_time': '17:00', + 'interview_duration': 60, + 'buffer_time': 15, + 'break_start_time': '12:00', + 'break_end_time': '13:00' + } + + form = InterviewScheduleForm(slug=self.job.slug, data=schedule_data) + self.assertTrue(form.is_valid()) + + def test_field_response_data_types(self): + """Test different data types for field responses""" + # Create template and field + template = FormTemplate.objects.create( + job=self.job, name='Test Template', created_by=self.user + ) + stage = FormStage.objects.create(template=template, name='Stage 1', order=0) + field = FormField.objects.create( + stage=stage, label='Test Field', field_type='text', order=0 + ) + + # Create submission + submission = FormSubmission.objects.create(template=template) + + # Test different value types + response = FieldResponse.objects.create( + submission=submission, + field=field, + value="Test string value" + ) + self.assertEqual(response.display_value, "Test string value") + + # Test list value (for checkbox/radio) + field.field_type = 'checkbox' + field.save() + response_checkbox = FieldResponse.objects.create( + submission=submission, + field=field, + value=["option1", "option2"] + ) + self.assertEqual(response_checkbox.display_value, "option1, option2") + + # Test file upload + file_content = b"Test file content" + uploaded_file = SimpleUploadedFile( + 'test_file.pdf', file_content, content_type='application/pdf' + ) + response_file = FieldResponse.objects.create( + submission=submission, + field=field, + uploaded_file=uploaded_file + ) + self.assertTrue(response_file.is_file) + self.assertEqual(response_file.get_file_size, len(file_content)) + + +class AdvancedViewTests(TestCase): + """Advanced view tests with complex scenarios""" + + def setUp(self): + self.client = Client() + self.user = User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=True + ) + self.profile = Profile.objects.create(user=self.user) + + self.job = JobPosting.objects.create( + title='Software Engineer', + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + location_country='Saudi Arabia', + description='Job description', + qualifications='Job qualifications', + created_by=self.user, + status='ACTIVE' + ) + + self.candidate = Candidate.objects.create( + first_name='John', + last_name='Doe', + email='john@example.com', + phone='1234567890', + job=self.job, + stage='Applied' + ) + + self.zoom_meeting = ZoomMeeting.objects.create( + topic='Interview with John Doe', + start_time=timezone.now() + timedelta(hours=1), + duration=60, + timezone='UTC', + join_url='https://zoom.us/j/123456789', + meeting_id='123456789' + ) + + def test_job_detail_with_multiple_candidates(self): + """Test job detail view with multiple candidates at different stages""" + # Create more candidates at different stages + Candidate.objects.create( + first_name='Jane', last_name='Smith', email='jane@example.com', + phone='9876543210', job=self.job, stage='Exam' + ) + Candidate.objects.create( + first_name='Bob', last_name='Johnson', email='bob@example.com', + phone='5555555555', job=self.job, stage='Interview' + ) + Candidate.objects.create( + first_name='Alice', last_name='Brown', email='alice@example.com', + phone='4444444444', job=self.job, stage='Offer' + ) + + response = self.client.get(reverse('job_detail', kwargs={'slug': self.job.slug})) + self.assertEqual(response.status_code, 200) + + # Check that counts are correct + self.assertContains(response, 'Total Applicants: 4') + self.assertContains(response, 'Applied: 1') + self.assertContains(response, 'Exam: 1') + self.assertContains(response, 'Interview: 1') + self.assertContains(response, 'Offer: 1') + + def test_meeting_list_with_complex_filters(self): + """Test meeting list view with multiple filter combinations""" + # Create meetings with different statuses and candidates + meeting2 = ZoomMeeting.objects.create( + topic='Interview with Jane Smith', + start_time=timezone.now() + timedelta(hours=2), + duration=60, + timezone='UTC', + join_url='https://zoom.us/j/987654321', + meeting_id='987654321', + status='started' + ) + + # Create scheduled interviews + ScheduledInterview.objects.create( + candidate=self.candidate, + job=self.job, + zoom_meeting=self.zoom_meeting, + interview_date=timezone.now().date(), + interview_time=time(10, 0), + status='scheduled' + ) + + ScheduledInterview.objects.create( + candidate=Candidate.objects.create( + first_name='Jane', last_name='Smith', email='jane@example.com', + phone='9876543210', job=self.job, stage='Interview' + ), + job=self.job, + zoom_meeting=meeting2, + interview_date=timezone.now().date(), + interview_time=time(11, 0), + status='scheduled' + ) + + # Test combined filters + response = self.client.get(reverse('list_meetings'), { + 'q': 'Interview', + 'status': 'waiting', + 'candidate_name': 'John' + }) + self.assertEqual(response.status_code, 200) + + def test_candidate_list_advanced_search(self): + """Test candidate list view with advanced search functionality""" + # Create more candidates for testing + Candidate.objects.create( + first_name='Jane', last_name='Smith', email='jane@example.com', + phone='9876543210', job=self.job, stage='Exam' + ) + Candidate.objects.create( + first_name='Bob', last_name='Johnson', email='bob@example.com', + phone='5555555555', job=self.job, stage='Interview' + ) + + # Test search by name + response = self.client.get(reverse('candidate_list'), { + 'search': 'Jane' + }) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Jane Smith') + + # Test search by email + response = self.client.get(reverse('candidate_list'), { + 'search': 'bob@example.com' + }) + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'Bob Johnson') + + # Test filter by job + response = self.client.get(reverse('candidate_list'), { + 'job': self.job.slug + }) + self.assertEqual(response.status_code, 200) + + # Test filter by stage + response = self.client.get(reverse('candidate_list'), { + 'stage': 'Exam' + }) + self.assertEqual(response.status_code, 200) + + def test_interview_scheduling_workflow(self): + """Test the complete interview scheduling workflow""" + # Create candidates for scheduling + candidates = [] + for i in range(3): + candidate = Candidate.objects.create( + first_name=f'Candidate{i}', + last_name=f'Test{i}', + email=f'candidate{i}@example.com', + phone=f'123456789{i}', + job=self.job, + stage='Interview' + ) + candidates.append(candidate) + + # Test GET request (initial form) + request = self.client.get(reverse('schedule_interviews', kwargs={'slug': self.job.slug})) + self.assertEqual(request.status_code, 200) + + # Test POST request with preview + with patch('recruitment.views.get_available_time_slots') as mock_slots: + # Mock available time slots + mock_slots.return_value = [ + {'date': date.today() + timedelta(days=1), 'time': '10:00'}, + {'date': date.today() + timedelta(days=1), 'time': '11:00'}, + {'date': date.today() + timedelta(days=1), 'time': '14:00'} + ] + + # Test _handle_preview_submission + self.client.login(username='testuser', password='testpass123') + post_data = { + 'candidates': [c.pk for c in candidates], + 'start_date': (date.today() + timedelta(days=1)).isoformat(), + 'end_date': (date.today() + timedelta(days=7)).isoformat(), + 'working_days': [0, 1, 2, 3, 4], + 'start_time': '09:00', + 'end_time': '17:00', + 'interview_duration': '60', + 'buffer_time': '15' + } + + # This would normally be handled by the view, but we test the logic directly + # In a real test, you'd make a POST request to the view + request = self.client.post( + reverse('schedule_interviews', kwargs={'slug': self.job.slug}), + data=post_data + ) + self.assertEqual(request.status_code, 200) # Should show preview + + @patch('recruitment.views.create_zoom_meeting') + def test_meeting_creation_with_api_errors(self, mock_create): + """Test meeting creation when API returns errors""" + # Test API error + mock_create.return_value = { + 'status': 'error', + 'message': 'Failed to create meeting' + } + + self.client.login(username='testuser', password='testpass123') + data = { + 'topic': 'Test Meeting', + 'start_time': (timezone.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M'), + 'duration': 60 + } + + response = self.client.post(reverse('create_meeting'), data) + # Should show error message + self.assertEqual(response.status_code, 200) # Form with error + + def test_htmx_responses(self): + """Test HTMX responses for partial updates""" + # Test HTMX request for candidate screening + response = self.client.get( + reverse('candidate_screening_view', kwargs={'slug': self.job.slug}), + HTTP_HX_REQUEST='true' + ) + self.assertEqual(response.status_code, 200) + + # Test HTMX request for meeting details + response = self.client.get( + reverse('meeting_details', kwargs={'slug': self.zoom_meeting.slug}), + HTTP_HX_REQUEST='true' + ) + self.assertEqual(response.status_code, 200) + + def test_bulk_operations(self): + """Test bulk operations on candidates""" + # Create multiple candidates + candidates = [] + for i in range(5): + candidate = Candidate.objects.create( + first_name=f'Bulk{i}', + last_name=f'Test{i}', + email=f'bulk{i}@example.com', + phone=f'123456789{i}', + job=self.job, + stage='Applied' + ) + candidates.append(candidate) + + # Test bulk status update + candidate_ids = [c.pk for c in candidates] + self.client.login(username='testuser', password='testpass123') + + # This would be tested via a form submission + # For now, we test the view logic directly + request = self.client.post( + reverse('candidate_update_status', kwargs={'slug': self.job.slug}), + data={'candidate_ids': candidate_ids, 'mark_as': 'Exam'} + ) + # Should redirect back to the view + self.assertEqual(request.status_code, 302) + + # Verify candidates were updated + updated_count = Candidate.objects.filter( + pk__in=candidate_ids, + stage='Exam' + ).count() + self.assertEqual(updated_count, len(candidates)) + + +class AdvancedFormTests(TestCase): + """Advanced form tests with complex validation scenarios""" + + def setUp(self): + self.user = User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=True + ) + + self.job = JobPosting.objects.create( + title='Software Engineer', + department='IT', + job_type='FULL_TIME', + workplace_type='REMOTE', + location_country='Saudi Arabia', + description='Job description', + qualifications='Job qualifications', + created_by=self.user + ) + + def test_complex_form_validation_scenarios(self): + """Test complex validation scenarios for forms""" + # Test JobPostingForm with all field types + complex_data = { + 'title': 'Senior Software Engineer', + 'department': 'Engineering', + 'job_type': 'FULL_TIME', + 'workplace_type': 'HYBRID', + 'location_city': 'Riyadh', + 'location_state': 'Riyadh', + 'location_country': 'Saudi Arabia', + 'description': 'Detailed job description', + 'qualifications': 'Detailed qualifications', + 'salary_range': '8000-12000 SAR', + 'benefits': 'Health insurance, annual leave', + 'application_start_date': '2025-01-01', + 'application_deadline': '2025-12-31', + 'application_instructions': 'Submit your resume online', + 'position_number': 'ENG-2025-001', + 'reporting_to': 'Engineering Manager', + 'joining_date': '2025-06-01', + 'created_by': self.user.get_full_name(), + 'open_positions': '3', + 'hash_tags': '#tech, #engineering, #senior', + 'max_applications': '200' + } + + form = JobPostingForm(data=complex_data) + self.assertTrue(form.is_valid(), form.errors) + + def test_form_dependency_validation(self): + """Test validation for dependent form fields""" + # Test InterviewScheduleForm with dependent fields + schedule_data = { + 'candidates': [], # Empty for now + 'start_date': '2025-01-15', + 'end_date': '2025-01-10', # Invalid: end_date before start_date + 'working_days': [0, 1, 2, 3, 4], + 'start_time': '09:00', + 'end_time': '17:00', + 'interview_duration': '60', + 'buffer_time': '15' + } + + form = InterviewScheduleForm(slug=self.job.slug, data=schedule_data) + self.assertFalse(form.is_valid()) + self.assertIn('end_date', form.errors) + + def test_file_upload_validation(self): + """Test file upload validation in forms""" + # Test valid file upload + valid_file = SimpleUploadedFile( + 'valid_resume.pdf', + b'%PDF-1.4\n% ...', + content_type='application/pdf' + ) + + candidate_data = { + 'job': self.job.id, + 'first_name': 'John', + 'last_name': 'Doe', + 'phone': '1234567890', + 'email': 'john@example.com', + 'resume': valid_file + } + + form = CandidateForm(data=candidate_data, files=candidate_data) + self.assertTrue(form.is_valid()) + + # Test invalid file type (would need custom validator) + # This test depends on your actual file validation logic + + def test_dynamic_form_fields(self): + """Test forms with dynamically populated fields""" + # Test InterviewScheduleForm with dynamic candidate queryset + # Create candidates in Interview stage + candidates = [] + for i in range(3): + candidate = Candidate.objects.create( + first_name=f'Interview{i}', + last_name=f'Candidate{i}', + email=f'interview{i}@example.com', + phone=f'123456789{i}', + job=self.job, + stage='Interview' + ) + candidates.append(candidate) + + # Form should only show Interview stage candidates + form = InterviewScheduleForm(slug=self.job.slug) + self.assertEqual(form.fields['candidates'].queryset.count(), 3) + + for candidate in candidates: + self.assertIn(candidate, form.fields['candidates'].queryset) + + +class AdvancedIntegrationTests(TransactionTestCase): + """Advanced integration tests covering multiple components""" + + def setUp(self): + self.client = Client() + self.user = User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=True + ) + self.profile = Profile.objects.create(user=self.user) + + def test_complete_hiring_workflow(self): + """Test the complete hiring workflow from job posting to hire""" + # 1. Create job + job = JobPosting.objects.create( + title='Product Manager', + department='Product', + job_type='FULL_TIME', + workplace_type='ON_SITE', + location_country='Saudi Arabia', + description='Product Manager job description', + qualifications='Product management experience', + created_by=self.user, + status='ACTIVE' + ) + + # 2. Create form template for applications + template = FormTemplate.objects.create( + job=job, + name='Product Manager Application', + created_by=self.user, + is_active=True + ) + + # 3. Create form stages and fields + personal_stage = FormStage.objects.create( + template=template, + name='Personal Information', + order=0 + ) + + FormField.objects.create( + stage=personal_stage, + label='First Name', + field_type='text', + order=0, + required=True + ) + FormField.objects.create( + stage=personal_stage, + label='Last Name', + field_type='text', + order=1, + required=True + ) + FormField.objects.create( + stage=personal_stage, + label='Email', + field_type='email', + order=2, + required=True + ) + + experience_stage = FormStage.objects.create( + template=template, + name='Work Experience', + order=1 + ) + + FormField.objects.create( + stage=experience_stage, + label='Years of Experience', + field_type='number', + order=0 + ) + + # 4. Submit application + submission_data = { + 'field_1': 'Sarah', + 'field_2': 'Johnson', + 'field_3': 'sarah@example.com', + 'field_4': '5' + } + + response = self.client.post( + reverse('submit_form', kwargs={'template_id': template.id}), + submission_data + ) + self.assertEqual(response.status_code, 302) # Redirect to success page + + # 5. Verify candidate was created + candidate = Candidate.objects.get(email='sarah@example.com') + self.assertEqual(candidate.stage, 'Applied') + self.assertEqual(candidate.job, job) + + # 6. Move candidate to Exam stage + candidate.stage = 'Exam' + candidate.save() + + # 7. Move candidate to Interview stage + candidate.stage = 'Interview' + candidate.save() + + # 8. Create interview schedule + scheduled_interview = ScheduledInterview.objects.create( + candidate=candidate, + job=job, + interview_date=timezone.now().date() + timedelta(days=7), + interview_time=time(14, 0), + status='scheduled' + ) + + # 9. Create Zoom meeting + zoom_meeting = ZoomMeeting.objects.create( + topic=f'Interview: {job.title} with {candidate.name}', + start_time=timezone.now() + timedelta(days=7, hours=14), + duration=60, + timezone='UTC', + join_url='https://zoom.us/j/interview123', + meeting_id='interview123' + ) + + # 10. Assign meeting to interview + scheduled_interview.zoom_meeting = zoom_meeting + scheduled_interview.save() + + # 11. Verify all relationships + self.assertEqual(candidate.scheduled_interviews.count(), 1) + self.assertEqual(zoom_meeting.interview, scheduled_interview) + self.assertEqual(job.candidates.count(), 1) + + # 12. Complete hire process + candidate.stage = 'Offer' + candidate.save() + + # 13. Verify final state + self.assertEqual(Candidate.objects.filter(stage='Offer').count(), 1) + + def test_data_integrity_across_operations(self): + """Test data integrity across multiple operations""" + # Create complex data structure + job = JobPosting.objects.create( + title='Data Scientist', + department='Analytics', + job_type='FULL_TIME', + workplace_type='REMOTE', + location_country='Saudi Arabia', + description='Data Scientist position', + created_by=self.user, + max_applications=5 + ) + + # Create multiple candidates + candidates = [] + for i in range(3): + candidate = Candidate.objects.create( + first_name=f'Data{i}', + last_name=f'Scientist{i}', + email=f'data{i}@example.com', + phone=f'123456789{i}', + job=job, + stage='Applied' + ) + candidates.append(candidate) + + # Create form template + template = FormTemplate.objects.create( + job=job, + name='Data Scientist Application', + created_by=self.user, + is_active=True + ) + + # Create submissions for candidates + for i, candidate in enumerate(candidates): + submission = FormSubmission.objects.create( + template=template, + applicant_name=f'{candidate.first_name} {candidate.last_name}', + applicant_email=candidate.email + ) + + # Create field responses + FieldResponse.objects.create( + submission=submission, + field=FormField.objects.create( + stage=FormStage.objects.create(template=template, name='Stage 1', order=0), + label='Test Field', + field_type='text' + ), + value=f'Test response {i}' + ) + + # Verify data consistency + self.assertEqual(FormSubmission.objects.filter(template=template).count(), 3) + self.assertEqual(FieldResponse.objects.count(), 3) + + # Test application limit + for i in range(3): # Try to add more candidates than limit + Candidate.objects.create( + first_name=f'Extra{i}', + last_name=f'Candidate{i}', + email=f'extra{i}@example.com', + phone=f'11111111{i}', + job=job, + stage='Applied' + ) + + # Verify that the job shows application limit warning + job.refresh_from_db() + self.assertTrue(job.is_application_limit_reached) + + @patch('recruitment.views.create_zoom_meeting') + def test_zoom_integration_workflow(self, mock_create): + """Test complete Zoom integration workflow""" + # Setup job and candidate + job = JobPosting.objects.create( + title='Remote Developer', + department='Engineering', + job_type='REMOTE', + created_by=self.user + ) + + candidate = Candidate.objects.create( + first_name='Remote', + last_name='Developer', + email='remote@example.com', + job=job, + stage='Interview' + ) + + # Mock successful Zoom meeting creation + mock_create.return_value = { + 'status': 'success', + 'meeting_details': { + 'meeting_id': 'zoom123', + 'join_url': 'https://zoom.us/j/zoom123', + 'password': 'meeting123' + }, + 'zoom_gateway_response': { + 'status': 'waiting', + 'id': 'meeting_zoom123' + } + } + + # Schedule meeting via API + with patch('recruitment.views.ScheduledInterview.objects.create') as mock_create_interview: + mock_create_interview.return_value = ScheduledInterview( + candidate=candidate, + job=job, + zoom_meeting=None, + interview_date=timezone.now().date(), + interview_time=time(15, 0), + status='scheduled' + ) + + response = self.client.post( + reverse('api_schedule_candidate_meeting', + kwargs={'job_slug': job.slug, 'candidate_pk': candidate.pk}), + data={ + 'start_time': (timezone.now() + timedelta(hours=1)).isoformat(), + 'duration': 60 + } + ) + + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'success') + + # Verify Zoom API was called + mock_create.assert_called_once() + + # Verify interview was created + mock_create_interview.assert_called_once() + + def test_concurrent_operations(self): + """Test handling of concurrent operations""" + # Create job + job = JobPosting.objects.create( + title='Concurrency Test', + department='Test', + created_by=self.user + ) + + # Create candidates + candidates = [] + for i in range(10): + candidate = Candidate.objects.create( + first_name=f'Concurrent{i}', + last_name=f'Test{i}', + email=f'concurrent{i}@example.com', + job=job, + stage='Applied' + ) + candidates.append(candidate) + + # Test concurrent candidate updates + from concurrent.futures import ThreadPoolExecutor + + def update_candidate(candidate_id, stage): + from django.test import TestCase + from django.db import transaction + from recruitment.models import Candidate + + with transaction.atomic(): + candidate = Candidate.objects.select_for_update().get(pk=candidate_id) + candidate.stage = stage + candidate.save() + + # Update candidates concurrently + with ThreadPoolExecutor(max_workers=3) as executor: + futures = [ + executor.submit(update_candidate, c.pk, 'Exam') + for c in candidates + ] + + for future in futures: + future.result() + + # Verify all updates completed + self.assertEqual(Candidate.objects.filter(stage='Exam').count(), len(candidates)) + + +class SecurityTests(TestCase): + """Security-focused tests""" + + def setUp(self): + self.client = Client() + self.user = User.objects.create_user( + username='testuser', + email='test@example.com', + password='testpass123', + is_staff=False + ) + self.staff_user = User.objects.create_user( + username='staffuser', + email='staff@example.com', + password='testpass123', + is_staff=True + ) + + self.job = JobPosting.objects.create( + title='Security Test Job', + department='Security', + job_type='FULL_TIME', + created_by=self.staff_user + ) + + def test_unauthorized_access_control(self): + """Test that unauthorized users cannot access protected resources""" + # Test regular user accessing staff-only functionality + self.client.login(username='testuser', password='testpass123') + + # Access job list (should be accessible) + response = self.client.get(reverse('job_list')) + self.assertEqual(response.status_code, 200) + + # Try to edit job (should be restricted based on your actual implementation) + response = self.client.get(reverse('job_update', kwargs={'slug': self.job.slug})) + # This depends on your actual access control implementation + # For now, we'll assume it redirects or shows 403 + + def test_csrf_protection(self): + """Test CSRF protection on forms""" + # Test POST request without CSRF token (should fail) + self.client.login(username='staffuser', password='testpass123') + + response = self.client.post( + reverse('create_meeting'), + data={ + 'topic': 'Test Meeting', + 'start_time': (timezone.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M'), + 'duration': 60 + }, + HTTP_X_CSRFTOKEN='invalid' # Invalid or missing CSRF token + ) + # Should be blocked by Django's CSRF protection + # The exact behavior depends on your middleware setup + + def test_sql_injection_prevention(self): + """Test that forms prevent SQL injection""" + # Test SQL injection in form fields + malicious_input = "Robert'); DROP TABLE candidates;--" + + form_data = { + 'title': f'SQL Injection Test {malicious_input}', + 'department': 'IT', + 'job_type': 'FULL_TIME', + 'workplace_type': 'REMOTE' + } + + form = JobPostingForm(data=form_data) + # Form should still be valid (malicious input stored as text, not executed) + self.assertTrue(form.is_valid()) + + # The actual protection comes from Django's ORM parameterized queries + + def test_xss_prevention(self): + """Test that forms prevent XSS attacks""" + # Test XSS attempt in form fields + xss_script = '' + + form_data = { + 'title': f'XSS Test {xss_script}', + 'department': 'IT', + 'job_type': 'FULL_TIME', + 'workplace_type': 'REMOTE' + } + + form = JobPostingForm(data=form_data) + self.assertTrue(form.is_valid()) + + # The actual protection should be in template rendering + # Test template rendering with potentially malicious content + job = JobPosting.objects.create( + title=f'XSS Test {xss_script}', + department='IT', + created_by=self.staff_user + ) diff --git a/recruitment/urls.py b/recruitment/urls.py index c20dd58..5e93c73 100644 --- a/recruitment/urls.py +++ b/recruitment/urls.py @@ -4,7 +4,7 @@ from . import views from . import views_integration urlpatterns = [ - path('dashboard/', views_frontend.dashboard_view, name='dashboard'), + path('', views_frontend.dashboard_view, name='dashboard'), # Job URLs (using JobPosting model) path('jobs/', views_frontend.JobListView.as_view(), name='job_list'), @@ -68,6 +68,8 @@ urlpatterns = [ path('jobs//candidate_screening_view/', views.candidate_screening_view, name='candidate_screening_view'), path('jobs//candidate_exam_view/', views.candidate_exam_view, name='candidate_exam_view'), path('jobs//candidate_interview_view/', views.candidate_interview_view, name='candidate_interview_view'), + path('jobs//candidate_offer_view/', views_frontend.candidate_offer_view, name='candidate_offer_view'), + path('jobs//candidates//update_status///', views_frontend.update_candidate_status, name='update_candidate_status'), path('jobs///reschedule_meeting_for_candidate//', views.reschedule_meeting_for_candidate, name='reschedule_meeting_for_candidate'), @@ -108,4 +110,11 @@ urlpatterns = [ # users urls path('user/',views.user_detail,name='user_detail'), + + # Meeting Comments URLs + path('meetings//comments/add/', views.add_meeting_comment, name='add_meeting_comment'), + path('meetings//comments//edit/', views.edit_meeting_comment, name='edit_meeting_comment'), + path('meetings//comments//delete/', views.delete_meeting_comment, name='delete_meeting_comment'), + + path('meetings//set_meeting_candidate/', views.set_meeting_candidate, name='set_meeting_candidate'), ] diff --git a/recruitment/views.py b/recruitment/views.py index bc6899b..9d58fd6 100644 --- a/recruitment/views.py +++ b/recruitment/views.py @@ -1,6 +1,9 @@ import json import requests from django.contrib.auth.models import User +from django.contrib.auth.decorators import login_required +from django.contrib.auth.mixins import LoginRequiredMixin +from django import forms from rich import print from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_exempt @@ -14,12 +17,13 @@ from django.conf import settings from django.utils import timezone from .forms import ( CandidateExamDateForm, + InterviewForm, ZoomMeetingForm, JobPostingForm, FormTemplateForm, InterviewScheduleForm,JobPostingStatusForm, BreakTimeFormSet, - JobPostingImageForm + JobPostingImageForm,MeetingCommentForm ) from rest_framework import viewsets from django.contrib import messages @@ -51,7 +55,7 @@ from .models import ( ZoomMeeting, Candidate, JobPosting, - ScheduledInterview + ScheduledInterview,MeetingComment ) import logging from datastar_py.django import ( @@ -61,10 +65,12 @@ from datastar_py.django import ( ) from django.db import transaction from django_q.tasks import async_task +from django.db.models import Prefetch +from django.db.models import Q, Count, Avg +from django.db.models import FloatField logger = logging.getLogger(__name__) - class JobPostingViewSet(viewsets.ModelViewSet): queryset = JobPosting.objects.all() serializer_class = JobPostingSerializer @@ -75,7 +81,7 @@ class CandidateViewSet(viewsets.ModelViewSet): serializer_class = CandidateSerializer -class ZoomMeetingCreateView(CreateView): +class ZoomMeetingCreateView(LoginRequiredMixin, CreateView): model = ZoomMeeting template_name = "meetings/create_meeting.html" form_class = ZoomMeetingForm @@ -87,9 +93,8 @@ class ZoomMeetingCreateView(CreateView): topic = instance.topic if instance.start_time < timezone.now(): messages.error(self.request, "Start time must be in the future.") - return redirect("/create-meeting/", status=400) + return redirect(reverse("create_meeting",kwargs={"slug": instance.slug})) start_time = instance.start_time - # start_time = instance.start_time.isoformat() + "Z" duration = instance.duration result = create_zoom_meeting(topic, start_time, duration) @@ -103,15 +108,16 @@ class ZoomMeetingCreateView(CreateView): instance.save() messages.success(self.request, result["message"]) - return redirect("/", status=201) + return redirect(reverse("list_meetings")) else: messages.error(self.request, result["message"]) - return redirect("/", status=400) + return redirect(reverse("create_meeting",kwargs={"slug": instance.slug})) except Exception as e: - return redirect("/", status=500) + messages.error(self.request, f"Error creating meeting: {e}") + return redirect(reverse("create_meeting",kwargs={"slug": instance.slug})) -class ZoomMeetingListView(ListView): +class ZoomMeetingListView(LoginRequiredMixin, ListView): model = ZoomMeeting template_name = "meetings/list_meetings.html" context_object_name = "meetings" @@ -121,7 +127,7 @@ class ZoomMeetingListView(ListView): queryset = super().get_queryset().order_by("-start_time") # Prefetch related interview data efficiently - from django.db.models import Prefetch + queryset = queryset.prefetch_related( Prefetch( 'interview', # related_name from ZoomMeeting to ScheduledInterview @@ -161,13 +167,13 @@ class ZoomMeetingListView(ListView): return context -class ZoomMeetingDetailsView(DetailView): +class ZoomMeetingDetailsView(LoginRequiredMixin, DetailView): model = ZoomMeeting template_name = "meetings/meeting_details.html" context_object_name = "meeting" -class ZoomMeetingUpdateView(UpdateView): +class ZoomMeetingUpdateView(LoginRequiredMixin, UpdateView): model = ZoomMeeting form_class = ZoomMeetingForm context_object_name = "meeting" @@ -198,7 +204,7 @@ class ZoomMeetingUpdateView(UpdateView): } if instance.start_time < timezone.now(): messages.error(self.request, "Start time must be in the future.") - return redirect(f"/update-meeting/{instance.pk}/", status=400) + return redirect(reverse("meeting_details", kwargs={"slug": instance.slug})) result = update_meeting(instance, updated_data) @@ -209,21 +215,22 @@ class ZoomMeetingUpdateView(UpdateView): return redirect(reverse("meeting_details", kwargs={"slug": instance.slug})) -def ZoomMeetingDeleteView(request, pk): - meeting = get_object_or_404(ZoomMeeting, pk=pk) - meeting_id = meeting.meeting_id - try: - result = delete_zoom_meeting(meeting_id) - if result["status"] == "success": - meeting.delete() - messages.success(request, result["message"]) - else: - messages.error(request, result["message"]) - return redirect("/") - except Exception as e: - messages.error(request, str(e)) - return redirect("/") - +def ZoomMeetingDeleteView(request, slug): + meeting = get_object_or_404(ZoomMeeting, slug=slug) + if "HX-Request" in request.headers: + return render(request, "meetings/delete_meeting_form.html", {"meeting": meeting,"delete_url": reverse("delete_meeting", kwargs={"slug": meeting.slug})}) + if request.method == "POST": + try: + result = delete_zoom_meeting(meeting.meeting_id) + if result["status"] == "success" or "Meeting does not exist" in result["details"]["message"]: + meeting.delete() + messages.success(request, "Meeting deleted successfully.") + else: + messages.error(request, f"{result["message"]} , {result['details']["message"]}") + return redirect(reverse("list_meetings")) + except Exception as e: + messages.error(request, str(e)) + return redirect(reverse("list_meetings")) # Job Posting # def job_list(request): @@ -247,6 +254,7 @@ def ZoomMeetingDeleteView(request, pk): # }) +@login_required def create_job(request): """Create a new job posting""" @@ -285,10 +293,11 @@ def create_job(request): return render(request, "jobs/create_job.html", {"form": form}) +@login_required def edit_job(request, slug): """Edit an existing job posting""" + job = get_object_or_404(JobPosting, slug=slug) if request.method == "POST": - job = get_object_or_404(JobPosting, slug=slug) form = JobPostingForm( request.POST, instance=job, @@ -321,14 +330,13 @@ def edit_job(request, slug): return render(request, "jobs/edit_job.html", {"form": form, "job": job}) +@login_required def job_detail(request, slug): """View details of a specific job""" job = get_object_or_404(JobPosting, slug=slug) - print(job) # Get all candidates for this job, ordered by most recent applicants = job.candidates.all().order_by("-created_at") - print(applicants) # Count candidates by stage for summary statistics total_applicant = applicants.count() @@ -341,12 +349,10 @@ def job_detail(request, slug): offer_count = applicants.filter(stage="Offer").count() - status_form = JobPostingStatusForm(instance=job) image_upload_form=JobPostingImageForm(instance=job) - # 2. Check for POST request (Status Update Submission) if request.method == 'POST': @@ -365,6 +371,19 @@ def job_detail(request, slug): messages.error(request, "Failed to update status due to validation errors.") + category_data = applicants.filter( + major_category_name__isnull=False, + ai_analysis_data__match_score__isnull=False # This was part of the original query, ensure it's intentional + ).values('major_category_name').annotate( + candidate_count=Count('id'), + ai_analysis_data__avg_match_score=Avg('match_score', output_field=FloatField()) + ).order_by('major_category_name') + + # Prepare data for Chart.js + categories = [item['major_category_name'] for item in category_data] + candidate_counts = [item['candidate_count'] for item in category_data] + avg_scores = [round(item['avg_match_score'], 2) if item['avg_match_score'] is not None else 0 for item in category_data] + context = { "job": job, @@ -375,10 +394,14 @@ def job_detail(request, slug): "interview_count": interview_count, "offer_count": offer_count, 'status_form':status_form, - 'image_upload_form':image_upload_form + 'image_upload_form':image_upload_form, + 'categories': categories, + 'candidate_counts': candidate_counts, + 'avg_scores': avg_scores } return render(request, "jobs/job_detail.html", context) +@login_required def job_image_upload(request, slug): #only for handling the post request job=get_object_or_404(JobPosting,slug=slug) @@ -417,6 +440,7 @@ def job_detail_candidate(request, slug): return render(request, "jobs/job_detail_candidate.html", {"job": job}) +@login_required def post_to_linkedin(request, slug): """Post a job to LinkedIn""" job = get_object_or_404(JobPosting, slug=slug) @@ -516,243 +540,8 @@ def application_success(request,slug): job=get_object_or_404(JobPosting,slug=slug) return render(request,'jobs/application_success.html',{'job':job}) - - - - -# Form Preview Views -# from django.http import JsonResponse -# from django.views.decorators.csrf import csrf_exempt -# from django.core.paginator import Paginator -# from django.contrib.auth.decorators import login_required -# import json - -# def form_list(request): -# """Display list of all available forms""" -# forms = Form.objects.filter(is_active=True).order_by('-created_at') - -# # Pagination -# paginator = Paginator(forms, 12) -# page_number = request.GET.get('page') -# page_obj = paginator.get_page(page_number) - -# return render(request, 'forms/form_list.html', { -# 'page_obj': page_obj -# }) - -# def form_preview(request, form_id): -# """Display form preview for end users""" -# form = get_object_or_404(Form, id=form_id, is_active=True) - -# # Get submission count for analytics -# submission_count = form.submissions.count() - -# return render(request, 'forms/form_preview.html', { -# 'form': form, -# 'submission_count': submission_count, -# 'is_embed': request.GET.get('embed', 'false') == 'true' -# }) - -# @csrf_exempt -# def form_submit(request, form_id): -# """Handle form submission via AJAX""" -# if request.method != 'POST': -# return JsonResponse({'success': False, 'error': 'Only POST method allowed'}, status=405) - -# form = get_object_or_404(Form, id=form_id, is_active=True) - -# try: -# # Parse form data -# submission_data = {} -# files = {} - -# # Process regular form fields -# for key, value in request.POST.items(): -# if key != 'csrfmiddlewaretoken': -# submission_data[key] = value - -# # Process file uploads -# for key, file in request.FILES.items(): -# if file: -# files[key] = file - -# # Create form submission -# submission = FormSubmission.objects.create( -# form=form, -# submission_data=submission_data, -# ip_address=request.META.get('REMOTE_ADDR'), -# user_agent=request.META.get('HTTP_USER_AGENT', '') -# ) - -# # Handle file uploads -# for field_id, file in files.items(): -# UploadedFile.objects.create( -# submission=submission, -# field_id=field_id, -# file=file, -# original_filename=file.name -# ) - -# # TODO: Send email notification if configured - -# return JsonResponse({ -# 'success': True, -# 'message': 'Form submitted successfully!', -# 'submission_id': submission.id -# }) - -# except Exception as e: -# logger.error(f"Error submitting form {form_id}: {e}") -# return JsonResponse({ -# 'success': False, -# 'error': 'An error occurred while submitting the form. Please try again.' -# }, status=500) - -# def form_embed(request, form_id): -# """Display embeddable version of form""" -# form = get_object_or_404(Form, id=form_id, is_active=True) - -# return render(request, 'forms/form_embed.html', { -# 'form': form, -# 'is_embed': True -# }) - -# @login_required -# def save_form_builder(request): -# """Save form from builder to database""" -# if request.method != 'POST': -# return JsonResponse({'success': False, 'error': 'Only POST method allowed'}, status=405) - -# try: -# data = json.loads(request.body) -# form_data = data.get('form', {}) - -# # Check if this is an update or create -# form_id = data.get('form_id') - -# if form_id: -# # Update existing form -# form = Form.objects.get(id=form_id, created_by=request.user) -# form.title = form_data.get('title', 'Untitled Form') -# form.description = form_data.get('description', '') -# form.structure = form_data -# form.save() -# else: -# # Create new form -# form = Form.objects.create( -# title=form_data.get('title', 'Untitled Form'), -# description=form_data.get('description', ''), -# structure=form_data, -# created_by=request.user -# ) - -# return JsonResponse({ -# 'success': True, -# 'form_id': form.id, -# 'message': 'Form saved successfully!' -# }) - -# except json.JSONDecodeError: -# return JsonResponse({ -# 'success': False, -# 'error': 'Invalid JSON data' -# }, status=400) -# except Exception as e: -# logger.error(f"Error saving form: {e}") -# return JsonResponse({ -# 'success': False, -# 'error': 'An error occurred while saving the form' -# }, status=500) - -# @login_required -# def load_form(request, form_id): -# """Load form data for editing in builder""" -# try: -# form = get_object_or_404(Form, id=form_id, created_by=request.user) - -# return JsonResponse({ -# 'success': True, -# 'form': { -# 'id': form.id, -# 'title': form.title, -# 'description': form.description, -# 'structure': form.structure -# } -# }) - -# except Exception as e: -# logger.error(f"Error loading form {form_id}: {e}") -# return JsonResponse({ -# 'success': False, -# 'error': 'An error occurred while loading the form' -# }, status=500) - -# @csrf_exempt -# def update_form_builder(request, form_id): -# """Update existing form from builder""" -# if request.method != 'POST': -# return JsonResponse({'success': False, 'error': 'Only POST method allowed'}, status=405) - -# try: -# form = get_object_or_404(Form, id=form_id) - -# # Check if user has permission to edit this form -# if form.created_by != request.user: -# return JsonResponse({ -# 'success': False, -# 'error': 'You do not have permission to edit this form' -# }, status=403) - -# data = json.loads(request.body) -# form_data = data.get('form', {}) - -# # Update form -# form.title = form_data.get('title', 'Untitled Form') -# form.description = form_data.get('description', '') -# form.structure = form_data -# form.save() - -# return JsonResponse({ -# 'success': True, -# 'form_id': form.id, -# 'message': 'Form updated successfully!' -# }) - -# except json.JSONDecodeError: -# return JsonResponse({ -# 'success': False, -# 'error': 'Invalid JSON data' -# }, status=400) -# except Exception as e: -# logger.error(f"Error updating form {form_id}: {e}") -# return JsonResponse({ -# 'success': False, -# 'error': 'An error occurred while updating the form' -# }, status=500) - -# def edit_form(request, form_id): -# """Display form edit page""" -# form = get_object_or_404(Form, id=form_id) - -# # Check if user has permission to edit this form -# if form.created_by != request.user: -# messages.error(request, 'You do not have permission to edit this form.') -# return redirect('form_list') - -# return render(request, 'forms/edit_form.html', { -# 'form': form -# }) - -# def form_submissions(request, form_id): -# """View submissions for a specific form""" -# form = get_object_or_404(Form, id=form_id, created_by=request.user) -# submissions = form.submissions.all().order_by('-submitted_at') - -# # Pagination -# - - @ensure_csrf_cookie +@login_required def form_builder(request, template_id=None): """Render the form builder interface""" context = {} @@ -878,6 +667,7 @@ def load_form_template(request, template_id): ) +@login_required def form_templates_list(request): """List all form templates for the current user""" query = request.GET.get("q", "") @@ -898,6 +688,7 @@ def form_templates_list(request): return render(request, "forms/form_templates_list.html", context) +@login_required def create_form_template(request): """Create a new form template""" if request.method == "POST": @@ -916,6 +707,7 @@ def create_form_template(request): return render(request, "forms/create_form_template.html", {"form": form}) +@login_required @require_http_methods(["GET"]) def list_form_templates(request): """List all form templates for the current user""" @@ -925,6 +717,7 @@ def list_form_templates(request): return JsonResponse({"success": True, "templates": list(templates)}) +@login_required @require_http_methods(["DELETE"]) def delete_form_template(request, template_id): """Delete a form template""" @@ -1038,6 +831,7 @@ def submit_form(request, template_id): ) +@login_required def form_template_submissions_list(request, slug): """List all submissions for a specific form template""" template = get_object_or_404(FormTemplate, slug=slug) @@ -1058,6 +852,7 @@ def form_template_submissions_list(request, slug): ) +@login_required def form_template_all_submissions(request, template_id): """Display all submissions for a form template in table format""" template = get_object_or_404(FormTemplate, id=template_id) @@ -1084,6 +879,7 @@ def form_template_all_submissions(request, template_id): ) +@login_required def form_submission_details(request, template_id, slug): """Display detailed view of a specific form submission""" # Get the form template and verify ownership @@ -1123,6 +919,7 @@ def _handle_get_request(request, slug, job): from the session for persistence. """ SESSION_KEY = f"schedule_candidate_ids_{slug}" + form = InterviewScheduleForm(slug=slug) # break_formset = BreakTimeFormSet(prefix='breaktime') @@ -1131,6 +928,7 @@ def _handle_get_request(request, slug, job): # 1. Capture IDs from HTMX request and store in session (when first clicked) if "HX-Request" in request.headers: candidate_ids = request.GET.getlist("candidate_ids") + if candidate_ids: request.session[SESSION_KEY] = candidate_ids selected_ids = candidate_ids @@ -1340,90 +1138,6 @@ def _handle_confirm_schedule(request, slug, job): if SESSION_ID_KEY in request.session: del request.session[SESSION_ID_KEY] return redirect("job_detail", slug=slug) -# def _handle_confirm_schedule(request, slug, job): -# """ -# Handles the final POST request (Confirm Schedule). -# Creates all database records (Schedule, Meetings, Interviews) and clears sessions. -# """ -# SESSION_DATA_KEY = "interview_schedule_data" -# SESSION_ID_KEY = f"schedule_candidate_ids_{slug}" - -# # 1. Get schedule data from session -# schedule_data = request.session.get(SESSION_DATA_KEY) - -# if not schedule_data: -# messages.error(request, "Session expired. Please try again.") -# return redirect("schedule_interviews", slug=slug) -# # 2. Create the Interview Schedule (Your existing logic) -# schedule = InterviewSchedule.objects.create( -# job=job, -# created_by=request.user, -# start_date=datetime.fromisoformat(schedule_data["start_date"]).date(), -# end_date=datetime.fromisoformat(schedule_data["end_date"]).date(), -# working_days=schedule_data["working_days"], -# start_time=time.fromisoformat(schedule_data["start_time"]), -# end_time=time.fromisoformat(schedule_data["end_time"]), -# interview_duration=schedule_data["interview_duration"], -# buffer_time=schedule_data["buffer_time"], -# break_start_time=schedule_data["break_start_time"], -# break_end_time=schedule_data["break_end_time"], -# ) - -# # 3. Setup candidates and get slots -# candidates = Candidate.objects.filter(id__in=schedule_data["candidate_ids"]) -# schedule.candidates.set(candidates) -# available_slots = get_available_time_slots(schedule) - -# # 4. Create scheduled interviews -# scheduled_count = 0 -# for i, candidate in enumerate(candidates): -# if i < len(available_slots): -# slot = available_slots[i] -# interview_datetime = datetime.combine(slot['date'], slot['time']) - -# meeting_topic = f"Interview for {job.title} - {candidate.name}" -# result = create_zoom_meeting(meeting_topic, interview_datetime, schedule.interview_duration) - -# if result["status"] == "success": -# zoom_meeting = ZoomMeeting.objects.create( -# topic=meeting_topic, -# start_time=interview_datetime, -# duration=schedule.interview_duration, -# meeting_id=result["meeting_details"]["meeting_id"], -# join_url=result["meeting_details"]["join_url"], -# zoom_gateway_response=result["zoom_gateway_response"], -# ) -# ScheduledInterview.objects.create( -# candidate=candidate, -# job=job, -# zoom_meeting=zoom_meeting, -# schedule=schedule, -# interview_date=slot['date'], -# interview_time=slot['time'] -# ) -# scheduled_count += 1 -# else: -# messages.error(request, result["message"]) -# schedule.delete() -# # Clear candidate IDs session key only on error return -# if SESSION_ID_KEY in request.session: del request.session[SESSION_ID_KEY] -# return redirect("candidate_interview_view", slug=slug) - -# # 5. Success and Cleanup -# messages.success( -# request, f"Successfully scheduled {scheduled_count} interviews." -# ) - -# # Clear both session data keys upon successful completion -# if SESSION_DATA_KEY in request.session: -# del request.session[SESSION_DATA_KEY] -# if SESSION_ID_KEY in request.session: -# del request.session[SESSION_ID_KEY] - -# return redirect("job_detail", slug=slug) - - -# --- Main View Function --- def schedule_interviews_view(request, slug): job = get_object_or_404(JobPosting, slug=slug) @@ -1436,524 +1150,15 @@ def confirm_schedule_interviews_view(request, slug): job = get_object_or_404(JobPosting, slug=slug) if request.method == "POST": return _handle_confirm_schedule(request, slug, job) -# def schedule_interviews_view(request, slug): -# job = get_object_or_404(JobPosting, slug=slug) -# SESSION_KEY = f"schedule_candidate_ids_{slug}" -# if request.method == "POST": -# form = InterviewScheduleForm(slug, request.POST) -# break_formset = BreakTimeFormSet(request.POST) - -# # Check if this is a confirmation request -# if "confirm_schedule" in request.POST: -# # Get the schedule data from session -# schedule_data = request.session.get("interview_schedule_data") -# if not schedule_data: -# messages.error(request, "Session expired. Please try again.") -# return redirect("schedule_interviews", slug=slug) - -# # Create the interview schedule -# schedule = InterviewSchedule.objects.create( -# job=job, -# created_by=request.user, -# start_date=datetime.fromisoformat(schedule_data["start_date"]).date(), -# end_date=datetime.fromisoformat(schedule_data["end_date"]).date(), -# working_days=schedule_data["working_days"], -# start_time=time.fromisoformat(schedule_data["start_time"]), -# end_time=time.fromisoformat(schedule_data["end_time"]), -# interview_duration=schedule_data["interview_duration"], -# buffer_time=schedule_data["buffer_time"], -# breaks=schedule_data["breaks"], -# ) - -# # Add candidates to the schedule -# candidates = Candidate.objects.filter(id__in=schedule_data["candidate_ids"]) -# schedule.candidates.set(candidates) - -# # Create temporary break time objects for slot calculation -# temp_breaks = [] -# for break_data in schedule_data["breaks"]: -# temp_breaks.append( -# BreakTime( -# start_time=datetime.strptime( -# break_data["start_time"], "%H:%M:%S" -# ).time(), -# end_time=datetime.strptime( -# break_data["end_time"], "%H:%M:%S" -# ).time(), -# ) -# ) - -# # Get available slots -# available_slots = get_available_time_slots(schedule) - -# # Create scheduled interviews -# scheduled_count = 0 -# for i, candidate in enumerate(candidates): -# if i < len(available_slots): -# slot = available_slots[i] -# interview_datetime = datetime.combine(slot['date'], slot['time']) - -# # Create Zoom meeting -# meeting_topic = f"Interview for {job.title} - {candidate.name}" - -# start_time = interview_datetime - -# # zoom_meeting = create_zoom_meeting( -# # topic=meeting_topic, -# # start_time=start_time, -# # duration=schedule.interview_duration -# # ) - -# result = create_zoom_meeting(meeting_topic, start_time, schedule.interview_duration) -# if result["status"] == "success": -# zoom_meeting = ZoomMeeting.objects.create( -# topic=meeting_topic, -# start_time=interview_datetime, -# duration=schedule.interview_duration, -# meeting_id=result["meeting_details"]["meeting_id"], -# join_url=result["meeting_details"]["join_url"], -# zoom_gateway_response=result["zoom_gateway_response"], -# ) -# # Create scheduled interview record -# ScheduledInterview.objects.create( -# candidate=candidate, -# job=job, -# zoom_meeting=zoom_meeting, -# schedule=schedule, -# interview_date=slot['date'], -# interview_time=slot['time'] -# ) - -# else: -# messages.error(request, result["message"]) -# schedule.delete() -# return redirect("candidate_interview_view", slug=slug) - -# # Send email to candidate -# # try: -# # send_interview_email(scheduled_interview) -# # except Exception as e: -# # messages.warning( -# # request, -# # f"Interview scheduled for {candidate.name}, but failed to send email: {str(e)}" -# # ) - -# scheduled_count += 1 - -# messages.success( -# request, f"Successfully scheduled {scheduled_count} interviews." -# ) - -# # Clear the session data -# if "interview_schedule_data" in request.session: -# del request.session["interview_schedule_data"] - -# return redirect("job_detail", slug=slug) - -# # This is the initial form submission -# if form.is_valid() and break_formset.is_valid(): -# # Get the form data -# candidates = form.cleaned_data["candidates"] -# start_date = form.cleaned_data["start_date"] -# end_date = form.cleaned_data["end_date"] -# working_days = form.cleaned_data["working_days"] -# start_time = form.cleaned_data["start_time"] -# end_time = form.cleaned_data["end_time"] -# interview_duration = form.cleaned_data["interview_duration"] -# buffer_time = form.cleaned_data["buffer_time"] - -# # Process break times -# breaks = [] -# for break_form in break_formset: -# if break_form.cleaned_data and not break_form.cleaned_data.get( -# "DELETE" -# ): -# breaks.append( -# { -# "start_time": break_form.cleaned_data[ -# "start_time" -# ].strftime("%H:%M:%S"), -# "end_time": break_form.cleaned_data["end_time"].strftime("%H:%M:%S"), -# } -# ) - -# # Create a temporary schedule object (not saved to DB) -# temp_schedule = InterviewSchedule( -# job=job, -# start_date=start_date, -# end_date=end_date, -# working_days=working_days, -# start_time=start_time, -# end_time=end_time, -# interview_duration=interview_duration, -# buffer_time=buffer_time, -# breaks=breaks, -# ) - -# # Create temporary break time objects -# temp_breaks = [] -# for break_data in breaks: -# temp_breaks.append( -# BreakTime( -# start_time=datetime.strptime( -# break_data["start_time"], "%H:%M:%S" -# ).time(), -# end_time=datetime.strptime( -# break_data["end_time"], "%H:%M:%S" -# ).time(), -# ) -# ) - -# # Get available slots -# available_slots = get_available_time_slots(temp_schedule) - -# if len(available_slots) < len(candidates): -# messages.error( -# request, -# f"Not enough available slots. Required: {len(candidates)}, Available: {len(available_slots)}", -# ) -# return render( -# request, -# "interviews/schedule_interviews.html", -# {"form": form, "break_formset": break_formset, "job": job}, -# ) - -# # Create a preview schedule -# preview_schedule = [] -# for i, candidate in enumerate(candidates): -# slot = available_slots[i] -# preview_schedule.append( -# {"candidate": candidate, "date": slot["date"], "time": slot["time"]} -# ) - -# # Save the form data to session for later use -# schedule_data = { -# "start_date": start_date.isoformat(), -# "end_date": end_date.isoformat(), -# "working_days": working_days, -# "start_time": start_time.isoformat(), -# "end_time": end_time.isoformat(), -# "interview_duration": interview_duration, -# "buffer_time": buffer_time, -# "candidate_ids": [c.id for c in candidates], -# "breaks": breaks, -# } -# request.session["interview_schedule_data"] = schedule_data - -# # Render the preview page -# return render( -# request, -# "interviews/preview_schedule.html", -# { -# "job": job, -# "schedule": preview_schedule, -# "start_date": start_date, -# "end_date": end_date, -# "working_days": working_days, -# "start_time": start_time, -# "end_time": end_time, -# "breaks": breaks, -# "interview_duration": interview_duration, -# "buffer_time": buffer_time, -# }, -# ) -# else: -# form = InterviewScheduleForm(slug=slug) -# break_formset = BreakTimeFormSet() - -# selected_ids = [] - -# # 1. Capture IDs from HTMX request and store in session (when first clicked from timeline) -# if "HX-Request" in request.headers: -# candidate_ids = request.GET.getlist("candidate_ids") -# if candidate_ids: -# request.session[SESSION_KEY] = candidate_ids -# selected_ids = candidate_ids - -# # 2. Restore IDs from session (on refresh or navigation) -# if not selected_ids: -# selected_ids = request.session.get(SESSION_KEY, []) - -# # 3. Use the list of IDs to initialize the form -# if selected_ids: -# # Load Candidate objects corresponding to the IDs -# candidates_to_load = Candidate.objects.filter(pk__in=selected_ids) -# # This line sets the selected values for {{ form.candidates }} -# form.initial["candidates"] = candidates_to_load - -# return render( -# request, -# "interviews/schedule_interviews.html", -# {"form": form, "break_formset": break_formset, "job": job}, -# ) - -# def schedule_interviews_view(request, slug): -# job = get_object_or_404(JobPosting, slug=slug) - -# if request.method == "POST": -# form = InterviewScheduleForm(slug, request.POST) -# break_formset = BreakTimeFormSet(request.POST) - -# # Check if this is a confirmation request -# if "confirm_schedule" in request.POST: -# # Get the schedule data from session -# schedule_data = request.session.get("interview_schedule_data") -# if not schedule_data: -# messages.error(request, "Session expired. Please try again.") -# return redirect("schedule_interviews", slug=slug) - -# # Create the interview schedule -# schedule = InterviewSchedule.objects.create( -# job=job, -# created_by=request.user, -# start_date=datetime.fromisoformat(schedule_data["start_date"]).date(), -# end_date=datetime.fromisoformat(schedule_data["end_date"]).date(), -# working_days=schedule_data["working_days"], -# start_time=time.fromisoformat(schedule_data["start_time"]), -# end_time=time.fromisoformat(schedule_data["end_time"]), -# interview_duration=schedule_data["interview_duration"], -# buffer_time=schedule_data["buffer_time"], -# breaks=schedule_data["breaks"], # Direct assignment for JSON field -# ) - -# # Add candidates to the schedule -# candidates = Candidate.objects.filter(id__in=schedule_data["candidate_ids"]) -# schedule.candidates.set(candidates) - -# # Schedule the interviews -# try: -# scheduled_count = schedule_interviews(schedule) -# messages.success( -# request, f"Successfully scheduled {scheduled_count} interviews." -# ) -# # Clear the session data -# if "interview_schedule_data" in request.session: -# del request.session["interview_schedule_data"] -# return redirect("job_detail", slug=slug) -# except Exception as e: -# messages.error(request, f"Error scheduling interviews: {str(e)}") -# return redirect("schedule_interviews", slug=slug) - -# # This is the initial form submission -# if form.is_valid() and break_formset.is_valid(): -# # Get the form data -# candidates = form.cleaned_data["candidates"] -# start_date = form.cleaned_data["start_date"] -# end_date = form.cleaned_data["end_date"] -# working_days = form.cleaned_data["working_days"] -# start_time = form.cleaned_data["start_time"] -# end_time = form.cleaned_data["end_time"] -# interview_duration = form.cleaned_data["interview_duration"] -# buffer_time = form.cleaned_data["buffer_time"] - -# # Process break times -# breaks = [] -# for break_form in break_formset: -# if break_form.cleaned_data and not break_form.cleaned_data.get( -# "DELETE" -# ): -# breaks.append( -# { -# "start_time": break_form.cleaned_data[ -# "start_time" -# ].strftime("%H:%M:%S"), -# "end_time": break_form.cleaned_data["end_time"].strftime("%H:%M:%S"), -# } -# ) - -# # Create a temporary schedule object (not saved to DB) -# temp_schedule = InterviewSchedule( -# job=job, -# start_date=start_date, -# end_date=end_date, -# working_days=working_days, -# start_time=start_time, -# end_time=end_time, -# interview_duration=interview_duration, -# buffer_time=buffer_time, -# breaks=breaks, # Direct assignment for JSON field -# ) - -# # Get available slots -# available_slots = get_available_time_slots(temp_schedule) - -# if len(available_slots) < len(candidates): -# messages.error( -# request, -# f"Not enough available slots. Required: {len(candidates)}, Available: {len(available_slots)}", -# ) -# return render( -# request, -# "interviews/schedule_interviews.html", -# {"form": form, "break_formset": break_formset, "job": job}, -# ) - -# # Create a preview schedule -# preview_schedule = [] -# for i, candidate in enumerate(candidates): -# slot = available_slots[i] -# preview_schedule.append( -# {"candidate": candidate, "date": slot["date"], "time": slot["time"]} -# ) - -# # Save the form data to session for later use -# schedule_data = { -# "start_date": start_date.isoformat(), -# "end_date": end_date.isoformat(), -# "working_days": working_days, -# "start_time": start_time.isoformat(), -# "end_time": end_time.isoformat(), -# "interview_duration": interview_duration, -# "buffer_time": buffer_time, -# "candidate_ids": [c.id for c in candidates], -# "breaks": breaks, -# } -# request.session["interview_schedule_data"] = schedule_data - -# # Render the preview page -# return render( -# request, -# "interviews/preview_schedule.html", -# { -# "job": job, -# "schedule": preview_schedule, -# "start_date": start_date, -# "end_date": end_date, -# "working_days": working_days, -# "start_time": start_time, -# "end_time": end_time, -# "breaks": breaks, -# "interview_duration": interview_duration, -# "buffer_time": buffer_time, -# }, -# ) -# else: -# form = InterviewScheduleForm(slug=slug) -# break_formset = BreakTimeFormSet() - -# return render( -# request, -# "interviews/schedule_interviews.html", -# {"form": form, "break_formset": break_formset, "job": job}, -# ) +@login_required def candidate_screening_view(request, slug): """ Manage candidate tiers and stage transitions """ job = get_object_or_404(JobPosting, slug=slug) - applied_count=job.candidates.filter(stage='Applied').count() - exam_count=job.candidates.filter(stage='Exam').count() - interview_count=job.candidates.filter(stage='Interview').count() - offer_count=job.candidates.filter(stage='Offer').count() - # Get all candidates for this job, ordered by match score (descending) - candidates = job.candidates.filter(stage="Applied").order_by("-match_score") - - - - # Get tier categorization parameters - # tier1_count = int(request.GET.get("tier1_count", 100)) - - # # Categorize candidates into tiers - # tier1_candidates = candidates[:tier1_count] if tier1_count > 0 else [] - # remaining_candidates = candidates[tier1_count:] if tier1_count > 0 else [] - - # if len(remaining_candidates) > 0: - # # Tier 2: Next 50% of remaining candidates - # tier2_count = max(1, len(remaining_candidates) // 2) - # tier2_candidates = remaining_candidates[:tier2_count] - # tier3_candidates = remaining_candidates[tier2_count:] - # else: - # tier2_candidates = [] - # tier3_candidates = [] - - # # Handle form submissions - # if request.method == "POST": - # # Update tier categorization - # if "update_tiers" in request.POST: - # tier1_count = int(request.POST.get("tier1_count", 100)) - # messages.success(request, f"Tier categorization updated. Tier 1: {tier1_count} candidates") - # return redirect("candidate_screening_view", slug=slug) - - # # Update individual candidate stages - # elif "update_stage" in request.POST: - # candidate_id = request.POST.get("candidate_id") - # new_stage = request.POST.get("new_stage") - # candidate = get_object_or_404(Candidate, id=candidate_id, job=job) - - # if candidate.can_transition_to(new_stage): - # old_stage = candidate.stage - # candidate.stage = new_stage - # candidate.save() - # messages.success(request, f"Updated {candidate.name} from {old_stage} to {new_stage}") - # else: - # messages.error(request, f"Cannot transition {candidate.name} from {candidate.stage} to {new_stage}") - - # # Update exam status - # elif "update_exam_status" in request.POST: - # candidate_id = request.POST.get("candidate_id") - # exam_status = request.POST.get("exam_status") - # exam_date = request.POST.get("exam_date") - # candidate = get_object_or_404(Candidate, id=candidate_id, job=job) - - # if candidate.stage == "Exam": - # candidate.exam_status = exam_status - # if exam_date: - # candidate.exam_date = exam_date - # candidate.save() - # messages.success(request, f"Updated exam status for {candidate.name}") - # else: - # messages.error(request, f"Can only update exam status for candidates in Exam stage") - - # # Bulk stage update - # elif "bulk_update_stage" in request.POST: - # selected_candidates = request.POST.getlist("selected_candidates") - # new_stage = request.POST.get("bulk_new_stage") - # updated_count = 0 - - # for candidate_id in selected_candidates: - # candidate = get_object_or_404(Candidate, id=candidate_id, job=job) - # if candidate.can_transition_to(new_stage): - # candidate.stage = new_stage - # candidate.save() - # updated_count += 1 - - # messages.success(request, f"Updated {updated_count} candidates to {new_stage} stage") - - # # Mark individual candidate as Candidate - # elif "mark_as_candidate" in request.POST: - # candidate_id = request.POST.get("candidate_id") - # candidate = get_object_or_404(Candidate, id=candidate_id, job=job) - - # if candidate.applicant_status == "Applicant": - # candidate.applicant_status = "Candidate" - # candidate.save() - # messages.success(request, f"Marked {candidate.name} as Candidate") - # else: - # messages.info(request, f"{candidate.name} is already marked as Candidate") - - # # Mark all Tier 1 candidates as Candidates - # elif "mark_as_candidates" in request.POST: - # updated_count = 0 - # for candidate in tier1_candidates: - # if candidate.applicant_status == "Applicant": - # candidate.applicant_status = "Candidate" - # candidate.save() - # updated_count += 1 - - # if updated_count > 0: - # messages.success(request, f"Marked {updated_count} Tier 1 candidates as Candidates") - # else: - # messages.info(request, "All Tier 1 candidates are already marked as Candidates") - - # Group candidates by current stage for display - # stage_groups = { - # "Applied": candidates.filter(stage="Applied"), - # "Exam": candidates.filter(stage="Exam"), - # "Interview": candidates.filter(stage="Interview"), - # "Offer": candidates.filter(stage="Offer"), - # } + candidates = job.screening_candidates min_ai_score_str = request.GET.get('min_ai_score') tier1_count_str = request.GET.get('tier1_count') @@ -1985,42 +1190,28 @@ def candidate_screening_view(request, slug): context = { "job": job, "candidates": candidates, - # "stage_groups": stage_groups, - # "tier1_count": tier1_count, - # "total_candidates": candidates.count(), 'min_ai_score':min_ai_score, 'tier1_count':tier1_count, - 'applied_count':applied_count, - 'exam_count':exam_count, - 'interview_count':interview_count, - 'offer_count':offer_count, "current_stage" : "Applied" } return render(request, "recruitment/candidate_screening_view.html", context) +@login_required def candidate_exam_view(request, slug): """ Manage candidate tiers and stage transitions """ job = get_object_or_404(JobPosting, slug=slug) - applied_count=job.candidates.filter(stage='Applied').count() - exam_count=job.candidates.filter(stage='Exam').count() - interview_count=job.candidates.filter(stage='Interview').count() - offer_count=job.candidates.filter(stage='Offer').count() - candidates = job.candidates.filter(stage="Exam").order_by("-match_score") context = { "job": job, - "candidates": candidates, - 'applied_count':applied_count, - 'exam_count':exam_count, - 'interview_count':interview_count, - 'offer_count':offer_count, + "candidates": job.exam_candidates, 'current_stage' : "Exam" } return render(request, "recruitment/candidate_exam_view.html", context) +@login_required def update_candidate_exam_status(request, slug): candidate = get_object_or_404(Candidate, slug=slug) if request.method == "POST": @@ -2031,6 +1222,7 @@ def update_candidate_exam_status(request, slug): else: form = CandidateExamDateForm(request.POST, instance=candidate) return render(request, "includes/candidate_exam_status_form.html", {"candidate": candidate,"form": form}) +@login_required def bulk_update_candidate_exam_status(request,slug): job = get_object_or_404(JobPosting, slug=slug) status = request.headers.get('status') @@ -2053,6 +1245,7 @@ def candidate_criteria_view_htmx(request, pk): return render(request, "includes/candidate_modal_body.html", {"candidate": candidate}) +@login_required def candidate_set_exam_date(request, slug): candidate = get_object_or_404(Candidate, slug=slug) candidate.exam_date = timezone.now() @@ -2060,27 +1253,27 @@ def candidate_set_exam_date(request, slug): messages.success(request, f"Set exam date for {candidate.name} to {candidate.exam_date}") return redirect("candidate_screening_view", slug=candidate.job.slug) +@login_required def candidate_update_status(request, slug): job = get_object_or_404(JobPosting, slug=slug) mark_as = request.POST.get('mark_as') - candidate_ids = request.POST.getlist("candidate_ids") - if c := Candidate.objects.filter(pk__in = candidate_ids): - c.update(stage=mark_as,exam_date=timezone.now(),applicant_status="Candidate" if mark_as in ["Exam","Interview","Offer"] else "Applicant") + if mark_as != '----------': + candidate_ids = request.POST.getlist("candidate_ids") + if c := Candidate.objects.filter(pk__in = candidate_ids): + c.update(stage=mark_as,exam_date=timezone.now(),applicant_status="Candidate" if mark_as in ["Exam","Interview","Offer"] else "Applicant") - messages.success(request, f"Candidates Updated") + messages.success(request, f"Candidates Updated") response = HttpResponse(redirect("candidate_screening_view", slug=job.slug)) response.headers["HX-Refresh"] = "true" return response +@login_required def candidate_interview_view(request,slug): job = get_object_or_404(JobPosting,slug=slug) - applied_count=job.candidates.filter(stage='Applied').count() - exam_count=job.candidates.filter(stage='Exam').count() - interview_count=job.candidates.filter(stage='Interview').count() - offer_count=job.candidates.filter(stage='Offer').count() - context = {"job":job,"candidates":job.candidates.filter(stage="Interview").order_by("-match_score"),'applied_count':applied_count,'exam_count':exam_count,'interview_count':interview_count,'offer_count':offer_count,"current_stage":"Interview"} + context = {"job":job,"candidates":job.interview_candidates,'current_stage':'Interview'} return render(request,"recruitment/candidate_interview_view.html",context) +@login_required def reschedule_meeting_for_candidate(request,slug,candidate_id,meeting_id): job = get_object_or_404(JobPosting,slug=slug) candidate = get_object_or_404(Candidate,pk=candidate_id) @@ -2112,22 +1305,24 @@ def reschedule_meeting_for_candidate(request,slug,candidate_id,meeting_id): return render(request,"meetings/reschedule_meeting.html",context) +@login_required def delete_meeting_for_candidate(request,slug,candidate_pk,meeting_id): job = get_object_or_404(JobPosting,slug=slug) candidate = get_object_or_404(Candidate,pk=candidate_pk) meeting = get_object_or_404(ZoomMeeting,pk=meeting_id) if request.method == "POST": result = delete_zoom_meeting(meeting.meeting_id) - if result["status"] == "success": + if result["status"] == "success" or "Meeting does not exist" in result["details"]["message"]: meeting.delete() - messages.success(request, result["message"]) + messages.success(request, "Meeting deleted successfully") else: messages.error(request, result["message"]) return redirect(reverse("candidate_interview_view", kwargs={"slug": job.slug})) - context = {"job":job,"candidate":candidate,"meeting":meeting} + context = {"job":job,"candidate":candidate,"meeting":meeting,'delete_url':reverse("delete_meeting_for_candidate",kwargs={"slug":job.slug,"candidate_pk":candidate_pk,"meeting_id":meeting_id})} return render(request,"meetings/delete_meeting_form.html",context) +@login_required def interview_calendar_view(request, slug): job = get_object_or_404(JobPosting, slug=slug) @@ -2181,6 +1376,7 @@ def interview_calendar_view(request, slug): return render(request, 'recruitment/interview_calendar.html', context) +@login_required def interview_detail_view(request, slug, interview_id): job = get_object_or_404(JobPosting, slug=slug) interview = get_object_or_404( @@ -2711,6 +1907,7 @@ def schedule_meeting_for_candidate(request, slug, candidate_pk): +@login_required def user_detail(requests,pk): user=get_object_or_404(User,pk=pk) return render(requests,'user/profile.html') @@ -2727,8 +1924,155 @@ def zoom_webhook_view(request): payload = json.loads(request.body) async_task("recruitment.tasks.handle_zoom_webhook_event", payload) return HttpResponse(status=200) - except Exception: - # Bad data or internal server error return HttpResponse(status=400) - return HttpResponse(status=405) # Method Not Allowed \ No newline at end of file + return HttpResponse(status=405) + + +# Meeting Comments Views +@login_required +def add_meeting_comment(request, slug): + """Add a comment to a meeting""" + meeting = get_object_or_404(ZoomMeeting, slug=slug) + + if request.method == 'POST': + form = MeetingCommentForm(request.POST) + if form.is_valid(): + comment = form.save(commit=False) + comment.meeting = meeting + comment.author = request.user + comment.save() + messages.success(request, 'Comment added successfully!') + + # HTMX response - return just the comment section + if 'HX-Request' in request.headers: + return render(request, 'includes/comment_list.html', { + 'comments': meeting.comments.all().order_by('-created_at'), + 'meeting': meeting + }) + + return redirect('meeting_details', slug=slug) + else: + form = MeetingCommentForm() + + context = { + 'form': form, + 'meeting': meeting, + } + + # HTMX response - return the comment form + if 'HX-Request' in request.headers: + return render(request, 'includes/comment_form.html', context) + + return redirect('meeting_details', slug=slug) + + +@login_required +def edit_meeting_comment(request, slug, comment_id): + """Edit a meeting comment""" + meeting = get_object_or_404(ZoomMeeting, slug=slug) + comment = get_object_or_404(MeetingComment, id=comment_id, meeting=meeting) + + # Check if user is the author + if comment.author != request.user: + messages.error(request, 'You can only edit your own comments.') + return redirect('meeting_details', slug=slug) + + if request.method == 'POST': + form = MeetingCommentForm(request.POST, instance=comment) + if form.is_valid(): + form.save() + messages.success(request, 'Comment updated successfully!') + + # HTMX response - return just the comment section + if 'HX-Request' in request.headers: + return render(request, 'includes/comment_list.html', { + 'comments': meeting.comments.all().order_by('-created_at'), + 'meeting': meeting + }) + + return redirect('meeting_details', slug=slug) + else: + form = MeetingCommentForm(instance=comment) + + context = { + 'form': form, + 'meeting': meeting, + 'comment': comment, + } + + # HTMX response - return the comment form + if 'HX-Request' in request.headers: + return render(request, 'includes/edit_comment_form.html', context) + + return redirect('meeting_details', slug=slug) + + +@login_required +def delete_meeting_comment(request, slug, comment_id): + """Delete a meeting comment""" + meeting = get_object_or_404(ZoomMeeting, slug=slug) + comment = get_object_or_404(MeetingComment, id=comment_id, meeting=meeting) + + # Check if user is the author + if comment.author != request.user and not request.user.is_staff: + messages.error(request, 'You can only delete your own comments.') + return redirect('meeting_details', slug=slug) + + if request.method == 'POST': + comment.delete() + messages.success(request, 'Comment deleted successfully!') + + # HTMX response - return just the comment section + if 'HX-Request' in request.headers: + return render(request, 'includes/comment_list.html', { + 'comments': meeting.comments.all().order_by('-created_at'), + 'meeting': meeting + }) + + return redirect('meeting_details', slug=slug) + + # HTMX response - return the delete confirmation modal + if 'HX-Request' in request.headers: + return render(request, 'includes/delete_comment_form.html', { + 'meeting': meeting, + 'comment': comment, + 'delete_url': reverse('delete_meeting_comment', kwargs={'slug': slug, 'comment_id': comment_id}) + }) + + return redirect('meeting_details', slug=slug) + + + +@login_required +def set_meeting_candidate(request,slug): + meeting = get_object_or_404(ZoomMeeting, slug=slug) + if request.method == 'POST' and 'HX-Request' not in request.headers: + form = InterviewForm(request.POST) + if form.is_valid(): + candidate = form.save(commit=False) + candidate.zoom_meeting = meeting + candidate.interview_date = meeting.start_time.date() + candidate.interview_time = meeting.start_time.time() + candidate.save() + messages.success(request, 'Candidate added successfully!') + return redirect('list_meetings') + job = request.GET.get("job") + form = InterviewForm() + + if job: + form.fields['candidate'].queryset = Candidate.objects.filter(job=job) + + else: + form.fields['candidate'].queryset = Candidate.objects.none() + form.fields['job'].widget.attrs.update({ + 'hx-get': reverse('set_meeting_candidate', kwargs={'slug': slug}), + 'hx-target': '#div_id_candidate', + 'hx-select': '#div_id_candidate', + 'hx-swap': 'outerHTML' + }) + context = { + "form": form, + "meeting": meeting + } + return render(request, 'meetings/set_candidate_form.html', context) diff --git a/recruitment/views_frontend.py b/recruitment/views_frontend.py index 51bf44f..5f71202 100644 --- a/recruitment/views_frontend.py +++ b/recruitment/views_frontend.py @@ -16,7 +16,8 @@ from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView # JobForm removed - using JobPostingForm instead from django.urls import reverse_lazy -from django.db.models import Q +from django.db.models import Q, Count, Avg +from django.db.models import FloatField from datastar_py.django import ( DatastarResponse, @@ -224,6 +225,7 @@ def training_list(request): return render(request, 'recruitment/training_list.html', {'materials': materials}) +@login_required def candidate_detail(request, slug): from rich.json import JSON candidate = get_object_or_404(models.Candidate, slug=slug) @@ -235,7 +237,7 @@ def candidate_detail(request, slug): # Create stage update form for staff users stage_form = None if request.user.is_staff: - stage_form = forms.CandidateStageForm(candidate=candidate) + stage_form = forms.CandidateStageForm() # parsed = JSON(json.dumps(parsed), indent=2, highlight=True, skip_keys=False, ensure_ascii=False, check_circular=True, allow_nan=True, default=None, sort_keys=False) # parsed = json_to_markdown_table([parsed]) @@ -245,10 +247,11 @@ def candidate_detail(request, slug): 'stage_form': stage_form, }) +@login_required def candidate_update_stage(request, slug): """Handle HTMX stage update requests""" candidate = get_object_or_404(models.Candidate, slug=slug) - form = forms.CandidateStageForm(request.POST, candidate=candidate) + form = forms.CandidateStageForm(request.POST, instance=candidate) if form.is_valid(): stage_value = form.cleaned_data['stage'] candidate.stage = stage_value @@ -318,6 +321,7 @@ class TrainingDeleteView(LoginRequiredMixin, SuccessMessageMixin, DeleteView): success_message = 'Training material deleted successfully.' +@login_required def dashboard_view(request): total_jobs = models.JobPosting.objects.count() total_candidates = models.Candidate.objects.count() @@ -335,3 +339,79 @@ def dashboard_view(request): 'average_applications': average_applications, } return render(request, 'recruitment/dashboard.html', context) + + +@login_required +def candidate_offer_view(request, slug): + """View for candidates in the Offer stage""" + job = get_object_or_404(models.JobPosting, slug=slug) + + # Filter candidates for this specific job and stage + candidates = job.offer_candidates + + # Handle search + search_query = request.GET.get('search', '') + if search_query: + candidates = candidates.filter( + Q(first_name__icontains=search_query) | + Q(last_name__icontains=search_query) | + Q(email__icontains=search_query) | + Q(phone__icontains=search_query) + ) + + candidates = candidates.order_by('-created_at') + + context = { + 'job': job, + 'candidates': candidates, + 'search_query': search_query, + 'current_stage': 'Offer', + } + return render(request, 'recruitment/candidate_offer_view.html', context) + + +@login_required +def update_candidate_status(request, job_slug, candidate_slug, stage_type, status): + """Handle exam/interview/offer status updates""" + from django.utils import timezone + + job = get_object_or_404(models.JobPosting, slug=job_slug) + candidate = get_object_or_404(models.Candidate, slug=candidate_slug, job=job) + print(stage_type,status) + + if request.method == "POST": + if stage_type == 'exam': + candidate.exam_status = status + candidate.exam_date = timezone.now() + candidate.save(update_fields=['exam_status', 'exam_date']) + elif stage_type == 'interview': + candidate.interview_status = status + candidate.interview_date = timezone.now() + candidate.save(update_fields=['interview_status', 'interview_date']) + elif stage_type == 'offer': + candidate.offer_status = status + candidate.offer_date = timezone.now() + candidate.save(update_fields=['offer_status', 'offer_date']) + messages.success(request, f"Candidate {status} successfully!") + else: + messages.error(request, "No changes made.") + + if stage_type == 'exam': + return redirect('candidate_exam_view', job.slug) + elif stage_type == 'interview': + return redirect('candidate_interview_view', job.slug) + elif stage_type == 'offer': + return redirect('candidate_offer_view', job.slug) + + return redirect('candidate_detail', candidate.slug) + else: + if stage_type == 'exam': + return render(request,"includes/candidate_update_exam_form.html",{'candidate':candidate,'job':job}) + elif stage_type == 'interview': + return render(request,"includes/candidate_update_interview_form.html",{'candidate':candidate,'job':job}) + elif stage_type == 'offer': + return render(request,"includes/candidate_update_offer_form.html",{'candidate':candidate,'job':job}) + + +# Removed incorrect JobDetailView class. +# The job_detail view is handled by function-based view in recruitment.views diff --git a/run.py b/run.py index 7d1388c..cd38ff7 100644 --- a/run.py +++ b/run.py @@ -37,4 +37,8 @@ if __name__ == "__main__": duration = 60 host_email = "your_zoom_email" response = create_zoom_meeting(topic, start_time, duration, host_email) - print(response.json()) \ No newline at end of file + print(response.json()) + + + + diff --git a/template_partials/__init__.py b/template_partials/__init__.py new file mode 100644 index 0000000..579c83f --- /dev/null +++ b/template_partials/__init__.py @@ -0,0 +1 @@ +# Template partials app diff --git a/template_partials/apps.py b/template_partials/apps.py new file mode 100644 index 0000000..e5dddab --- /dev/null +++ b/template_partials/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class TemplatePartialsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'template_partials' + verbose_name = 'Template Partials' diff --git a/templates/base.html b/templates/base.html index ffe4948..819171c 100644 --- a/templates/base.html +++ b/templates/base.html @@ -1,5 +1,5 @@ {% load i18n static %} -{% load partials %} + diff --git a/templates/forms/form_template_all_submissions.html b/templates/forms/form_template_all_submissions.html index 9b0e498..b62f404 100644 --- a/templates/forms/form_template_all_submissions.html +++ b/templates/forms/form_template_all_submissions.html @@ -1,6 +1,6 @@ {% extends 'base.html' %} {% load static i18n form_filters %} -{% load partials %} + {% block title %}All Submissions for {{ template.name }} - ATS{% endblock %} diff --git a/templates/forms/form_template_submissions_list.html b/templates/forms/form_template_submissions_list.html index f552085..5ef90ba 100644 --- a/templates/forms/form_template_submissions_list.html +++ b/templates/forms/form_template_submissions_list.html @@ -1,6 +1,6 @@ {% extends 'base.html' %} {% load static i18n crispy_forms_tags %} -{% load partials %} + {% block title %}Submissions for {{ template.name }} - ATS{% endblock %} diff --git a/templates/forms/form_templates_list.html b/templates/forms/form_templates_list.html index 6c14e28..e20a366 100644 --- a/templates/forms/form_templates_list.html +++ b/templates/forms/form_templates_list.html @@ -1,6 +1,6 @@ {% extends 'base.html' %} {% load static i18n crispy_forms_tags %} -{% load partials %} + {% block title %}Form Templates - {{ block.super }}{% endblock %} @@ -76,13 +76,13 @@ transform: none; box-shadow: 0 4px 12px rgba(0,0,0,0.06); } - + /* Card Header (For Search/Filter Card) */ .card-header { font-weight: 600; padding: 1.25rem; border-bottom: 1px solid var(--kaauh-border); - background-color: var(--kaauh-gray-light); + background-color: var(--kaauh-gray-light); } /* Stats Theming */ @@ -205,7 +205,7 @@ {{ template.job|default:"N/A" }} - + {# Stats #}
@@ -217,7 +217,7 @@
{% trans "Fields" %}
- + {# Description #}

{% if template.description %} diff --git a/templates/icons/delete.html b/templates/icons/delete.html index 56aef3d..a35dfcb 100644 --- a/templates/icons/delete.html +++ b/templates/icons/delete.html @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/templates/includes/candidate_modal_body.html b/templates/includes/candidate_modal_body.html index 139555b..45a5f03 100644 --- a/templates/includes/candidate_modal_body.html +++ b/templates/includes/candidate_modal_body.html @@ -1,25 +1,31 @@ {% load i18n %} -

+
{% trans "AI Score" %}: {{ candidate.match_score }} {{ candidate.professional_category }}
+
- - + +
- - + +
- + + +
+
+
    {% for key, value in candidate.criteria_checklist.items %}
  • - {{ key }} + {{ key }} {% if value == 'Met' %} - Yes + Yes {% else %} - Not Mentioned + Not Mentioned {% endif %}
  • {% endfor %}
-
\ No newline at end of file + + diff --git a/templates/includes/candidate_update_exam_form.html b/templates/includes/candidate_update_exam_form.html new file mode 100644 index 0000000..ea40514 --- /dev/null +++ b/templates/includes/candidate_update_exam_form.html @@ -0,0 +1,10 @@ +{% load i18n %} + \ No newline at end of file diff --git a/templates/includes/candidate_update_interview_form.html b/templates/includes/candidate_update_interview_form.html new file mode 100644 index 0000000..1214319 --- /dev/null +++ b/templates/includes/candidate_update_interview_form.html @@ -0,0 +1,10 @@ +{% load i18n %} + \ No newline at end of file diff --git a/templates/includes/candidate_update_offer_form.html b/templates/includes/candidate_update_offer_form.html new file mode 100644 index 0000000..821395b --- /dev/null +++ b/templates/includes/candidate_update_offer_form.html @@ -0,0 +1,10 @@ +{% load i18n %} + \ No newline at end of file diff --git a/templates/includes/comment_form.html b/templates/includes/comment_form.html new file mode 100644 index 0000000..4ef849a --- /dev/null +++ b/templates/includes/comment_form.html @@ -0,0 +1,24 @@ +
+
+
Add Comment
+
+
+
+ {% csrf_token %} +
+ {{ form.content }} + {% if form.content.errors %} +
+ {% for error in form.content.errors %} + {{ error }} + {% endfor %} +
+ {% endif %} +
+ + {% if 'HX-Request' in request.headers %} + + {% endif %} +
+
+
diff --git a/templates/includes/comment_list.html b/templates/includes/comment_list.html new file mode 100644 index 0000000..40e37ef --- /dev/null +++ b/templates/includes/comment_list.html @@ -0,0 +1,56 @@ +
+
+
+
Comments ({{ comments.count }})
+ {% if 'HX-Request' in request.headers %} + + {% endif %} +
+
+ {% if comments %} +
+ {% for comment in comments %} +
+
+
+
+ {{ comment.author.get_full_name|default:comment.author.username }} + {% if comment.author != user %} + Comment + {% endif %} +
+ {{ comment.created_at|date:"M d, Y P" }} +
+
+

{{ comment.content|safe }}

+
+ +
+
+ {% endfor %} +
+ {% else %} +

No comments yet. Be the first to comment!

+ {% endif %} +
+
+
diff --git a/templates/includes/delete_comment_form.html b/templates/includes/delete_comment_form.html new file mode 100644 index 0000000..ba4953e --- /dev/null +++ b/templates/includes/delete_comment_form.html @@ -0,0 +1,16 @@ +
+
+
Delete Comment
+
+
+

Are you sure you want to delete this comment by {{ comment.author.get_full_name|default:comment.author.username }}?

+

{{ comment.created_at|date:"F d, Y P" }}

+
+ {% csrf_token %} + + {% if 'HX-Request' in request.headers %} + + {% endif %} +
+
+
diff --git a/templates/includes/delete_modal.html b/templates/includes/delete_modal.html index da5a213..06f8176 100644 --- a/templates/includes/delete_modal.html +++ b/templates/includes/delete_modal.html @@ -1,32 +1,18 @@ {% load i18n %} - @@ -426,4 +576,4 @@ {% if user.is_staff %} {% include "recruitment/partials/stage_update_modal.html" with candidate=candidate form=stage_form %} {% endif %} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/recruitment/candidate_exam_view.html b/templates/recruitment/candidate_exam_view.html index a41bd50..6ceb9d7 100644 --- a/templates/recruitment/candidate_exam_view.html +++ b/templates/recruitment/candidate_exam_view.html @@ -37,15 +37,18 @@ {% csrf_token %} @@ -56,7 +59,7 @@ - - - - - - - + + + + + + @@ -86,14 +89,6 @@ - - + + @@ -227,4 +227,4 @@ } }); -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/recruitment/candidate_interview_view.html b/templates/recruitment/candidate_interview_view.html index 03740c9..6f3abe2 100644 --- a/templates/recruitment/candidate_interview_view.html +++ b/templates/recruitment/candidate_interview_view.html @@ -30,15 +30,18 @@ {% csrf_token %} @@ -50,12 +53,13 @@ {% endif %} +
{% csrf_token %}
+ {% if candidates %}
{% endif %}
{% trans "Name" %}{% trans "Contact" %}{% trans "AI Score" %}{% trans "Exam Status" %}{% trans "Exam Date" %}{% trans "Actions" %}{% trans "Name" %}{% trans "Contact" %}{% trans "AI Score" %}{% trans "Exam Date" %}{% trans "Exam Results" %}{% trans "Actions" %}
{{ candidate.name }} - {# Tier badges now use defined stage-badge and tier-X-badge classes #} - {% if forloop.counter <= tier1_count %} - Tier 1 - {% elif forloop.counter <= tier1_count|default:0|add:tier1_count %} - Tier 2 - {% else %} - Tier 3+ - {% endif %}
@@ -105,34 +100,39 @@ {{ candidate.match_score|default:"0" }}% - {% if candidate.exam_status == "Passed" %} - {{ candidate.exam_status }} - {% elif candidate.exam_status == "Failed" %} - {{ candidate.exam_status }} - {% else %} - Pending - {% endif %} - - {{candidate.exam_date|date:"M d, Y h:i A"|default:"N/A"}} + {{candidate.exam_date|date:"d-m-Y h:i A"|default:"--"}} + + + {% if not candidate.exam_status %} + + {% else %} + {% if candidate.exam_status == "Passed" %} + {{ candidate.exam_status }} + {% elif candidate.exam_status == "Failed" %} + {{ candidate.exam_status }} + {% else %} + -- + {% endif %} + {% endif %} + -
- - - - - - - - + + + + + + + + + @@ -91,28 +97,77 @@ {{ candidate.phone }} - - + + + + {% endfor %} @@ -163,7 +218,7 @@ {% endif %} - + @@ -182,11 +237,7 @@ {% trans "Loading content..." %} - + @@ -293,4 +344,4 @@ }); }); -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/recruitment/candidate_list.html b/templates/recruitment/candidate_list.html index 8588135..7500c2c 100644 --- a/templates/recruitment/candidate_list.html +++ b/templates/recruitment/candidate_list.html @@ -186,11 +186,11 @@
- {% if job_filter or search_query %} - + {% trans "Clear" %} {% endif %} @@ -212,13 +212,14 @@
+ {% if candidates %}
{% endif %}
{% trans "Name" %}{% trans "Contact" %}{% trans "Topic" %}{% trans "Duration" %}{% trans "Interview Date" %}{% trans "Interview Link" %}{% trans "Actions" %} {% trans "Name" %} {% trans "Contact" %} {% trans "Topic" %} {% trans "Duration" %} {% trans "Meeting Date" %} {% trans "Link" %} {% trans "Meeting Status" %} {% trans "Interview Result" %} {% trans "Actions" %}
{{ candidate.get_latest_meeting.topic }}
{{ candidate.get_latest_meeting.duration }} min
+ {% if candidate.get_latest_meeting.topic %} + {{ candidate.get_latest_meeting.topic }} + {% else %} + -- + {% endif %} +
+ {% if candidate.get_latest_meeting.duration %} + {{ candidate.get_latest_meeting.duration }} {% trans _("Minutes") %} + {% else %} + -- + {% endif %} +
{% with latest_meeting=candidate.get_latest_meeting %} {% if latest_meeting %} - {{ latest_meeting.start_time|date:"M d, Y h:i A" }} + {{ latest_meeting.start_time|date:"d-m-Y h:i A" }} {% else %} - N/A + -- {% endif %} {% endwith %} {% with latest_meeting=candidate.get_latest_meeting %} {% if latest_meeting and latest_meeting.join_url %} - - + + click to join + {% else %} -- {% endif %} {% endwith %} + {{ latest_meeting.status }} + {% with latest_meeting=candidate.get_latest_meeting %} + {% if latest_meeting %} + + {% if latest_meeting.status == 'started' %} + + {% endif %} + {{ latest_meeting.status|title }} + + {% else %} + -- + {% endif %} + {% endwith %} + + {% if not candidate.interview_status %} + + {% else %} + {% if candidate.interview_status == "Passed" %} + {{ candidate.interview_status }} + {% elif candidate.interview_status == "Failed" %} + {{ candidate.interview_status }} + {% else %} + -- + {% endif %} + {% endif %} + - - {% else %} - - {% endif %} + {% endif %} +
- - - + + + + - - + + @@ -228,12 +229,19 @@ + - +
{% trans "Name" %}{% trans "Email" %}{% trans "Phone" %}{% trans "Name" %}{% trans "Email" %}{% trans "Phone" %} {% trans "Job" %}{% trans "Major" %} {% trans "Stage" %}{% trans "Created" %}{% trans "Actions" %}{% trans "created At" %}{% trans "Actions" %}
{{ candidate.email }} {{ candidate.phone }} {{ candidate.job.title }} + {% if candidate.professional_category != 'Uncategorized' %} + + {{ candidate.professional_category }} + + {% endif %} + {{ candidate.stage }} {{ candidate.created_at|date:"M d, Y" }}{{ candidate.created_at|date:"d-m-Y" }}
diff --git a/templates/recruitment/candidate_offer_view.html b/templates/recruitment/candidate_offer_view.html new file mode 100644 index 0000000..98ecd81 --- /dev/null +++ b/templates/recruitment/candidate_offer_view.html @@ -0,0 +1,273 @@ +{% extends 'base.html' %} +{% load static i18n %} + +{% block title %}- {{ job.title }} - ATS{% endblock %} + +{% block content %} +
+ +
+ {% include 'jobs/partials/applicant_tracking.html' %} +
+ +
+ {% if candidates %} +
+ +
+ {% csrf_token %} + + +
+ +
+ +
+ {% endif %} +
+
+ {% csrf_token %} + + + + + + + + + + + + + + + + + {% for candidate in candidates %} + + + + + + + + + + + + + {% endfor %} + +
+ {% if candidates %} +
+ +
+ {% endif %} +
{% trans "Name" %} {% trans "Contact" %} {% trans "Topic" %} {% trans "Duration" %} {% trans "Meeting Date" %} {% trans "Meeting Link" %} {% trans "Meeting Status" %} {% trans "Offer" %} {% trans "Actions" %}
+
+ +
+
+
+ {{ candidate.name }} +
+
+
+ {{ candidate.email }}
+ {{ candidate.phone }} +
+
+ {% if candidate.get_latest_meeting.topic %} + {{ candidate.get_latest_meeting.topic }} + {% else %} + -- + {% endif %} +
+ {% if candidate.get_latest_meeting.duration %} + {{ candidate.get_latest_meeting.duration }} {% trans _("Minutes") %} + {% else %} + -- + {% endif %} +
+ {% with latest_meeting=candidate.get_latest_meeting %} + {% if latest_meeting %} + {{ latest_meeting.start_time|date:"d-m-Y h:i A" }} + {% else %} + -- + {% endif %} + {% endwith %} + + {% with latest_meeting=candidate.get_latest_meeting %} + {% if latest_meeting and latest_meeting.join_url %} + + click to join + + + {% else %} + -- + {% endif %} + {% endwith %} + + {{ latest_meeting.status }} + {% with latest_meeting=candidate.get_latest_meeting %} + {% if latest_meeting %} + + {% if latest_meeting.status == 'started' %} + + {% endif %} + {{ latest_meeting.status|title }} + + {% else %} + -- + {% endif %} + {% endwith %} + + {% if not candidate.offer_status %} + + {% else %} + {% if candidate.offer_status == "Accepted" %} + {{ candidate.offer_status }} + {% elif candidate.offer_status == "Rejected" %} + {{ candidate.offer_status }} + {% else %} + -- + {% endif %} + {% endif %} + + +
+ {% if not candidates %} + + {% endif %} +
+
+
+ +
+ + + +{% endblock %} + +{% block customJS %} + +{% endblock %} diff --git a/templates/recruitment/candidate_screening_view.html b/templates/recruitment/candidate_screening_view.html index 05938fa..7597fa9 100644 --- a/templates/recruitment/candidate_screening_view.html +++ b/templates/recruitment/candidate_screening_view.html @@ -72,6 +72,9 @@ {% csrf_token %} - - - - - - - + + + + + + + @@ -128,26 +146,38 @@ - - + + +
+ {% if candidates %}
{% endif %}
{% trans "Candidate Name" %}{% trans "Contact Info" %}{% trans "AI Score" %}{% trans "Application Status" %}{% trans "Current Stage" %}{% trans "Actions" %} + {% trans "Candidate Name" %} + + {% trans "Contact Info" %} + + {% trans "AI Score" %} + + {% trans "Is Qualified?" %} + + {% trans "Professional Category" %} + + {% trans "Top 3 Skills" %} + + {% trans "Actions" %} +
- - {{ candidate.match_score|default:"0" }}% - + {% if candidate.match_score %} + + {{ candidate.match_score|default:"0" }}% + + {% endif %} - - {{ candidate.get_applicant_status_display }} - - - - {{ candidate.get_stage_display }} - - {% if candidate.stage == "Exam" and candidate.exam_status %} -
- - {{ candidate.get_exam_status_display }} +
+ {% if candidate.screening_stage_rating %} + + {{ candidate.screening_stage_rating|default:"--" }} {% endif %} + {% if candidate.professional_category %} + + {{ candidate.professional_category }} + + {% endif %} + + {% if candidate.top_3_keywords %} +
+ {% for skill in candidate.top_3_keywords %} + + {{ skill }} + + {% endfor %} +
+ {% endif %} +
- {% partialdef stage-modal %} @@ -64,8 +60,7 @@ - {% endpartialdef %} - {% partial stage-modal %} +