# Carry Forward Feature

## Overview
Added a "CarryTo" functionality that allows users to carry forward (clone) existing reports to today's date. This feature is useful for continuing operations with similar configurations from previous days.

## Features

### ✅ **Core Functionality**
1. **Clone Report**: Creates an exact copy of an existing report with today's date
2. **Smart Validation**: Prevents carrying forward reports from today or future dates
3. **Conflict Prevention**: Checks for existing reports with same configuration for today
4. **Sheet Management**: Automatically manages sheet creation and completion status
5. **User Assignment**: Assigns the carried forward report to the current user

### ✅ **Business Logic**
- **Source Reports**: Only reports from previous days can be carried forward
- **Target Date**: Always creates the new report with today's date and current time
- **Data Preservation**: Copies all report data except stoppages (starts fresh for new day)
- **Sheet Completion**: Automatically marks sheets as "completed" when both day and night shifts exist

## User Interface

### ✅ **Desktop Actions**
```
[View] [Duplicate] [CarryTo] [Edit] [Delete]
```

### ✅ **Mobile Actions**
```
[View Details]
[Duplicate as Night Shift]
[Carry Forward to Today]
[Edit] [Delete]
```

### ✅ **Visual Design**
- **Color**: Purple theme to distinguish from duplicate (green)
- **Icon**: Forward arrow or calendar icon
- **Confirmation**: User confirmation dialog before execution
- **Feedback**: Success/error messages via toast notifications

## Technical Implementation

### ✅ **Validation Logic**
```typescript
const canCarryForwardReport = (report: any) => {
  const reportDate = new Date(report.createdDate);
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  reportDate.setHours(0, 0, 0, 0);
  
  // Cannot carry forward reports from today or future
  if (reportDate >= today) {
    return false;
  }
  
  return true;
};
```

### ✅ **Server-Side Processing**
```typescript
// 1. Validate source report exists and is from past
// 2. Check for existing report with same configuration today
// 3. Create new report with today's date
// 4. Manage sheet creation/updates
// 5. Check and update sheet completion status
```

### ✅ **Data Cloning**
```typescript
const carriedReport = await prisma.report.create({
  data: {
    employeeId: user.id, // Current user
    shift: originalReport.shift, // Same shift
    areaId: originalReport.areaId,
    dredgerLocationId: originalReport.dredgerLocationId,
    dredgerLineLength: originalReport.dredgerLineLength,
    reclamationLocationId: originalReport.reclamationLocationId,
    shoreConnection: originalReport.shoreConnection,
    reclamationHeight: originalReport.reclamationHeight,
    pipelineLength: originalReport.pipelineLength,
    stats: originalReport.stats,
    timeSheet: originalReport.timeSheet,
    stoppages: [], // Fresh start for new day
    notes: originalReport.notes,
    createdDate: new Date() // Today's date
  }
});
```

## Business Rules

### ✅ **Eligibility Criteria**
1. **Date Restriction**: Source report must be from a previous day
2. **User Access**: All authenticated users can carry forward reports
3. **Conflict Prevention**: Cannot create if same configuration exists for today
4. **Data Integrity**: Maintains referential integrity with areas, locations, etc.

### ✅ **What Gets Copied**
- ✅ Shift type (day/night)
- ✅ Area and location assignments
- ✅ Equipment configurations
- ✅ Pipeline lengths and heights
- ✅ Statistics and personnel counts
- ✅ Time sheet entries
- ✅ Notes and comments

### ✅ **What Gets Reset**
- ❌ Stoppages (starts with empty array)
- ❌ Creation date (set to current date/time)
- ❌ Employee assignment (assigned to current user)

## Sheet Management

### ✅ **Automatic Sheet Creation**
- Creates or updates sheet for today's date
- Links the carried forward report to appropriate shift slot
- Maintains proper sheet structure and relationships

### ✅ **Completion Logic**
```typescript
// Check if sheet has both day and night shifts
if (todaySheet && todaySheet.dayShiftId && todaySheet.nightShiftId) {
  await prisma.sheet.update({
    where: { id: todaySheet.id },
    data: { status: 'completed' }
  });
}
```

## Use Cases

### **Operational Scenarios**

1. **Continuous Operations**
   - Carry forward yesterday's day shift to today
   - Maintain same equipment and location setup
   - Start fresh with stoppages for new day

2. **Shift Handover**
   - Night shift carries forward day shift configuration
   - Ensures consistency in operational setup
   - Reduces setup time for similar operations

3. **Recurring Operations**
   - Weekly operations with similar patterns
   - Monthly maintenance cycles
   - Seasonal operational configurations

### **Workflow Examples**

1. **Daily Operations**
   ```
   Yesterday Day Shift → [CarryTo] → Today Day Shift
   - Same location, equipment, personnel
   - Fresh stoppages tracking
   - Current user assignment
   ```

2. **Shift Completion**
   ```
   Day Shift Carried Forward → Night Shift Created → Sheet Completed
   - Automatic sheet status update
   - Complete operational cycle
   - Ready for reporting
   ```

## Error Handling

### ✅ **Validation Errors**
- **Future Date**: "Cannot carry forward reports from today or future dates"
- **Duplicate Configuration**: "A [shift] shift report already exists for today with the same location configuration"
- **Missing Report**: "Report not found"
- **System Error**: "Failed to carry forward report"

### ✅ **User Feedback**
- **Success**: "Report carried forward to today as [shift] shift!"
- **Confirmation**: User must confirm before execution
- **Visual Indicators**: Button states show availability
- **Toast Notifications**: Success/error messages

## Security & Permissions

### ✅ **Access Control**
- All authenticated users (auth level 1+) can carry forward reports
- Users can carry forward any report, not just their own
- Carried forward report is assigned to current user
- Maintains audit trail with creation timestamps

### ✅ **Data Validation**
- Server-side validation of all business rules
- Prevents duplicate configurations for same day
- Ensures data integrity and consistency
- Proper error handling and user feedback

## Performance Considerations

### ✅ **Database Operations**
- Single transaction for report creation and sheet management
- Efficient queries for validation checks
- Proper indexing on date and location fields
- Minimal data transfer with focused queries

### ✅ **User Experience**
- Fast execution with immediate feedback
- Clear visual indicators for button availability
- Intuitive confirmation dialogs
- Consistent behavior across desktop and mobile

## Future Enhancements

### **Potential Improvements**
1. **Bulk Carry Forward**: Carry forward multiple reports at once
2. **Scheduled Carry Forward**: Automatic carry forward for recurring operations
3. **Template System**: Save common configurations as templates
4. **Selective Data Copy**: Choose which data elements to carry forward
5. **Carry Forward History**: Track which reports were carried forward from where

### **Advanced Features**
1. **Smart Suggestions**: Suggest reports to carry forward based on patterns
2. **Batch Operations**: Carry forward entire sheets or multiple shifts
3. **Custom Date Selection**: Carry forward to specific future dates
4. **Approval Workflow**: Require approval for certain carry forward operations
5. **Integration**: Connect with scheduling systems for automated carry forward

The Carry Forward feature streamlines operational continuity by allowing users to quickly replicate successful operational configurations from previous days, reducing setup time and ensuring consistency in operations."