ERP Crystal MFG Repository Analysis
Repository Overview
ErpCrystal_MFG is a comprehensive Enterprise Resource Planning (ERP) system specifically designed for manufacturing businesses. The system follows a clean, layered architecture with clear separation of concerns.
Architecture Pattern
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Web UI │ │ API UI │ │ Reports │ │
│ │ (Blazor) │ │ (Swagger) │ │ (PDF/Excel)│ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ Business Logic Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Services │ │ Controllers│ │ Schedulers│ │
│ │ (Web) │ │ (API) │ │ (Coravel) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ Data Access Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Repositories │ │ Dapper ORM │ │ EF Core │ │
│ │ (Interface) │ │ (Queries) │ │ (Models) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────────────────────────────────────┐
│ Data Storage │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ SQL Server│ │ File System│ │ AWS S3 │ │
│ │ (Multiple) │ │ (Reports) │ │ (Storage) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘Project Structure
Solution Architecture
- ErpCrystal_MFG.Web: Blazor Server-side application (Presentation Layer)
- ErpCrystal_MFG.Api: RESTful API layer (Business Logic & Data Access)
- ErpCrystal_MFG.Models: Shared data models and entities
Key Technologies & Dependencies
Backend (.NET 9.0)
- Framework: ASP.NET Core 9.0
- ORM:
- Entity Framework Core 6.0 (for model definitions)
- Dapper (for high-performance queries)
- Database: Microsoft SQL Server (multiple database support)
- Task Scheduling: Coravel 6.0.2 (primary focus)
- Logging: Serilog with Email sink
- PDF Generation: QuestPDF, ClosedXML
- Authentication: Microsoft Identity Web (Azure AD B2C)
- QR Code: QRCoder
Frontend (Blazor)
- Framework: Blazor Server-side
- UI Components: MudBlazor 6.9.0
- State Management: Blazored.LocalStorage
- Authentication: Microsoft Identity Web UI
Cloud Integration
- AWS SDK: S3 for file storage, BedRock for AI
- Email Integration: SMTP with Serilog
Coravel Task Scheduler Implementation
Architecture Overview
The task scheduler system is built using Coravel, a modern .NET scheduling library that provides a fluent API for defining and executing background tasks.
Key Components
1. TaskSchedulerInitializer
Location: ErpCrystal_MFG.Api/TaskScheduler/TaskSchedulerInitializer.cs
Purpose: Central orchestrator that dynamically schedules tasks based on database configurations.
Key Features:
- Fetches task configurations from database
- Groups tasks by type and schedule
- Prevents overlapping executions
- Supports timezone-aware scheduling
public async Task InitializeTasks(IScheduler scheduler)
{
var allTasks = await _ITaskSchedulerRepository.GetAllTaskSchedulerDetails();
var groupedTasks = allTasks.GroupBy(x => new { x.ScheduledTaskCode, x.CronExpression });
foreach (var group in groupedTasks)
{
switch (group.Key.ScheduledTaskCode)
{
case "001": // Indent Email Task
scheduler.ScheduleWithParams<IndentEmailScheduler>(dbList)
.Cron(cron)
.PreventOverlapping($"{nameof(IndentEmailScheduler)}_{cron}")
.Zoned(TimeZoneInfo.Local);
break;
// ... other task types
}
}
}2. Task Schedulers
Each scheduler implements IInvocable interface and handles specific business logic:
Available Schedulers:
IndentEmailScheduler- Code “001”InvoiceEmailScheduler- Code “002”SalesOrderEmailScheduler- Code “003”ArEmailScheduler- Code “004”VoucherPaymentEmailScheduler- Code “005”VoucherReceiptEmailScheduler- Code “006”AIInsightsScheduler- Code “007”
3. Database Configuration
TaskSchedulerConfig Model:
public class TaskSchedulerConfig
{
public string DbName { get; set; } // Database name
public string CronExpression { get; set; } // CRON schedule
public string ScheduledTaskCode { get; set; } // Task type identifier
public string ScheduledTaskName { get; set; } // Human-readable name
public int DayOfWeek { get; set; } // For weekly schedules
public string ScheduleType { get; set; } // Schedule type
public TimeSpan? SelectedDateTime { get; set;} // Specific time
public int DailyOccurrences { get; set; } // Daily run count
public TimeSpan? DailyTime1 { get; set; } // Daily run times
public TimeSpan? DailyTime2 { get; set; }
public TimeSpan? DailyTime3 { get; set; }
}Database Tables:
ScheduledTasks: Stores task configurationsTaskList: Defines available task types
Scheduler Workflow
graph TD
A[Application Start] --> B[Register Coravel Services]
B --> C[Configure Scheduler in Program.cs]
C --> D[TaskSchedulerInitializer.InitializeTasks]
D --> E[Fetch Task Configurations]
E --> F[Group by Task Type & Schedule]
F --> G[Schedule Each Task Group]
G --> H[Coravel Engine Runs Tasks]
H --> I[Execute IInvocable Tasks]
I --> J[Log Results]
J --> K[Handle Exceptions]Task Execution Pattern
Each scheduler follows a consistent pattern:
- Database Iteration: Process multiple databases in sequence
- Logging Setup: Create log directories and files
- Validation: Check prerequisites (standard instructions, headers/footers)
- Data Processing: Fetch and process relevant business data
- Email Generation: Create and send emails with attachments
- Result Logging: Record success/failure status
Example - IndentEmailScheduler:
public async Task Invoke()
{
foreach (var dbname in dbnamelist)
{
// Setup logging
string pathDirectoryName = $"\\MFGReports\\Docs\\{dbname}\\Logs";
Directory.CreateDirectory(pathDirectoryName);
// Get standard instructions
var stdInstructions = await _IUtilityMethodsRepository.GetStdInstructions(dbname, "5");
// Fetch scheduled indents
var indentList = await _IIndentRepository.GetScheduledIndents(dbname);
// Process each indent
foreach (var data in indentList)
{
// Generate PDF
var printData = IndentController.IndentPrint(data, dbname, "N");
// Get email info
var emailData = _IIndentRepository.GetPartyContactInfo(data.PartyId, data.BranchId, dbname, "");
// Send email
var emailController = new EmailController(_IEmailRepository, _IUtilityMethodsRepository);
await emailController.SendEmail(dbname, _ReceiverEmail, "C");
// Log result
LogMessage(logFilePath, $"Indent Email, {DateTime.Now}, {emailStatus}, ...");
}
}
}Advanced Features
1. Multi-Database Support
- Single scheduler instance can process multiple databases
- Each database has its own configuration and logging
- Supports tenant-based architecture
2. Overlap Prevention
.PreventOverlapping($"{nameof(IndentEmailScheduler)}_{cron}")Prevents multiple instances of the same task from running simultaneously.
3. Timezone Awareness
.Zoned(TimeZoneInfo.Local)Ensures tasks run according to local timezone settings.
4. Error Handling & Recovery
- Comprehensive exception handling
- Email notifications for critical failures
- Detailed logging for troubleshooting
- Graceful degradation when prerequisites aren’t met
5. AI Integration
The AIInsightsScheduler demonstrates advanced capabilities:
- Generates multiple dashboard reports
- Processes large datasets efficiently
- Integrates with AWS BedRock for AI insights
- Handles complex financial and inventory calculations
Configuration Management
Tasks are configured through the database, allowing runtime changes without code deployment:
CRON Expression Examples:
0 9 * * 1-5- Weekdays at 9 AM0 18 * * *- Daily at 6 PM0 0 1 * *- Monthly on 1st at midnight
Task Types:
- Email notifications (Invoices, Indents, Sales Orders)
- Financial reporting (AR/AP, Ledger, Payroll)
- Inventory management (Aging, Valuation, Consumption)
- Manufacturing insights (BOM, Job Work, Production)
Performance Considerations
- Batch Processing: Tasks process multiple records efficiently
- Resource Management: Proper disposal of database connections
- Memory Optimization: Streaming for large datasets
- Concurrency Control: Overlap prevention ensures system stability
- Logging Efficiency: Structured logging with minimal overhead
Security & Compliance
- Authentication: Azure AD B2C integration
- Authorization: Role-based access control
- Data Protection: Secure email transmission
- Audit Trail: Comprehensive logging for compliance
- Error Privacy: Error emails sent only to admin, not end users
Integration Points
External Services
- Email: SMTP with authentication
- Cloud Storage: AWS S3 for document storage
- AI Services: AWS BedRock for insights
- Authentication: Azure AD B2C
- E-invoicing: External API integration
Internal Dependencies
- Database: Multiple SQL Server instances
- File System: Local storage for reports and logs
- Cache: Session and local storage
- Monitoring: Serilog with email alerts
Conclusion
The ERP Crystal MFG system demonstrates a sophisticated, production-ready task scheduler implementation using Coravel. The architecture provides:
- Flexibility: Dynamic configuration through database
- Reliability: Comprehensive error handling and logging
- Scalability: Multi-database support and efficient processing
- Maintainability: Clean separation of concerns and consistent patterns
- Extensibility: Easy to add new task types and schedules
The Coravel integration is particularly well-suited for this ERP system due to its fluent API, overlap prevention, and support for dependency injection, making it an excellent choice for complex business scheduling requirements.