# DFE Services Overview

This document outlines each of the DFE Services within the `app/Services` directory, describing their responsibilities, available actions (with function signatures), and whether they trigger notifications, use database transactions, log activities, or emit system logs.

---

## 1. DFEActivityService
**File:** `DFEActivityService.php`
**Description:** Manages the audit logging of account activities (Info, Success, Error). All actions store records in the `DFEAccountActivity` model to maintain a trace of system and user interactions.
- **Triggers Notifications:** No
- **Database Transactions:** No
- **System Logging (`Log::`):** No
- **Audit Logging:** Yes (Saves to `DFEAccountActivity`)

### Actions:
- `public function info(string $account_number, string $type, string $message)`
  - Creates an audit log entry with `INFO` state.
- `public function success($account_number, $type, $message)`
  - Creates an audit log entry with `SUCCESS` state.
- `public function error($account_number, $type, $message)`
  - Creates an audit log entry with `ERROR` state.

---

## 2. DFECoreNotificationService
**File:** `DFECoreNotificationService.php`
**Description:** Core service for formatting and dispatching email and SMS notifications (using jobs `SendEchoMail` and `SendEchoSMS`).
- **Triggers Notifications:** Yes (Email and SMS)
- **Database Transactions:** No
- **System Logging (`Log::`):** Yes (`Log::info` for all sent notifications)
- **Audit Logging:** No

### Actions:
- `public function dfeCreateAccount(DFEAccount $account)`
  - Triggers account creation notification (Email & SMS).
- `public function dfeCloseAccount(DFEAccount $account)`
  - Triggers account closure/cancellation notification.
- `public function dfeInstallmentsCompleted(DFEAccount $account)`
  - Triggers completion of installments notification.
- `public function dfePlanMatureCompleted(DFEAccount $account)`
  - Triggers plan maturity notification.
- `public function dfeSuccessfulPayment(DFEPayment $payment, $admin_mail)`
  - Triggers successful payment notification. If `$admin_mail` is true, also triggers `adminSuccessfulPayment`.
- `public function adminSuccessfulPayment($data)`
  - Dispatches admin notification email for successful payments.
- `public function dfeCancelPayment(DFEPayment $payment, $payment_remark)`
  - Triggers payment cancellation notification.
- `public function dfeUpcomingPayment(DFEAccount $account)`
  - Triggers upcoming payment reminder notification.
- `public function dfePendingPayment(DFEAccount $account, $days)`
  - Triggers overdue/pending payment reminder notification.
- `public function dfeRedeemAccount(DFEAccount $account)`
  - Triggers account redemption notification.

---

## 3. DFELedgerService
**File:** `DFELedgerService.php`
**Description:** Handles the financial audit trailing by creating ledger entries for DFE Accounts. 
- **Triggers Notifications:** No
- **Database Transactions:** No
- **System Logging (`Log::`):** No
- **Audit Logging:** Yes (Saves to `DFEAccountLedger`)

### Actions:
- `public function openAccount($account_number, $ledger_amount)`
  - Records an account open transaction.
- `public function creditAccount($account_number, $ledger_amount)`
  - Records a generic credit transaction.
- `public function debitAccount($account_number, $ledger_amount)`
  - Records a generic debit transaction.
- `public function closeAccount($account_number, $ledger_amount)`
  - Records an account close transaction.
- `public function debitEntry(DFEAccount $dFEAccount, $amount, $description = null, $payment_reference = null)`
  - Records a detailed debit entry.
- `public function creditEntry(DFEAccount $dFEAccount, $amount, $description = null, $payment_reference = null)`
  - Records a detailed credit entry.

---

## 4. DFENotificationService
**File:** `DFENotificationService.php`
**Description:** Extends `DFECoreNotificationService` and acts as a gateway by verifying if the store/account is blacklisted before sending notifications.
- **Triggers Notifications:** Yes (Conditional based on blacklist check)
- **Database Transactions:** No
- **System Logging (`Log::`):** Yes (`Log::info` if a notification is blocked due to blacklisting)
- **Audit Logging:** No

### Actions:
- `public function isBlacklisted(DFEAccount $account)`
  - Checks if the account's store is within the blacklisted stores.
- *Overrides all core notification methods (`dfeCreateAccount`, `dfeCloseAccount`, etc.) to apply the `isBlacklisted()` check before calling the parent method.*

---

## 5. DFEPaymentService
**File:** `DFEPaymentService.php`
**Description:** Manages all payment logic including offline and online (Razorpay) payment initiation and confirmation. Orchestrates updates, activity logging, and notifications.
- **Triggers Notifications:** Yes (Uses `DFENotificationService`)
- **Database Transactions:** Yes (`DB::beginTransaction()`, `DB::commit()`, `DB::rollback()`)
- **System Logging (`Log::`):** Yes (`Log::info` for success, `Log::error` for exceptions)
- **Audit Logging:** Yes (Uses `DFEActivityService`)

### Actions:
- `public function initiate_offline_payment($account_number, $installment_uuid, $payment_mode, $installment_amount, $reference_id, $payment_gateway)`
  - DB Transactions: Yes. Logs activity (Info, Success/Error). System log: Info/Error.
- `public function generate_signature($payment)` / `public function verify_signature($payment, $signature)`
  - Uses Laravel `Hash` to generate/verify offline payment signatures.
- `public function confirm_offline_payment($payment, $payment_signature)`
  - DB Transactions: Yes. Confirms offline payment. Triggers `dfeSuccessfulPayment` notification. Logs activity. System log: Info/Error.
- `public function onlinePayment($account_number, $installment_uuid, $order_id)`
  - DB Transactions: Yes. Initiates online payment process. Logs activity (Info, Success/Error).
- `public function completePayment($payment_id, $reference_id, $gateway_signature)`
  - DB Transactions: Yes. Validates and completes online payment. Triggers `dfeSuccessfulPayment` notification. Checks for account auto-completion. Logs activity.
- `public function cancelPayment(DFEPayment $payment, string $payment_remark)`
  - DB Transactions: Yes. Marks payment as cancelled and reverts installment status. Logs activity (Info, Success/Error).

---

## 6. DFEService
**File:** `DFEService.php`
**Description:** The core domain logic for managing DFE Accounts. Handles account creation, auto-completion, closure, redeeming, showroom switches, staff updates, and maturity logic.
- **Triggers Notifications:** Yes (Uses `DFENotificationService`)
- **Database Transactions:** Yes (Extensive use for state changes)
- **System Logging (`Log::`):** Yes (`Log::info` for various account actions)
- **Audit Logging:** Yes (Uses `DFEActivityService` & `DFELedgerService`)

### Actions (Key Methods):
- `public function create_dfe_account($dfe_details, $user_details, $store, User $support_user, $alias = [], $scheme = null, $payment_details = null)`
  - DB Transactions: Yes. Creates account, links user, sets up future installments. Calls ledger service. Triggers `dfeCreateAccount` (and optionally `dfeSuccessfulPayment`) notification. Dispatches `AccountZoho` job. Logs activity & system log.
- `public function account_auto_complete($account_number)`
  - DB Transactions: Yes. Validates if all installments are paid. Sets account to closed. Triggers `dfePlanMatureCompleted`. Logs activity.
- `public function account_close($account_number)`
  - DB Transactions: Yes. Forcibly closes account & pending installments. Triggers `dfeCloseAccount`. Logs activity.
- `public function update_staff(DFEAccount $account, $new_staff)`
  - DB Transactions: Yes. Updates support user. Logs activity & system log.
- `public function update_joining_date(DFEAccount $account, $new_joining_date)`
  - DB Transactions: Yes. Changes joining date and recalculates pending installment due dates. Logs activity & system log.
- `public function update_showroom(DFEAccount $account, $new_showroom)`
  - DB Transactions: Yes. Closes existing account and creates a new one in the target showroom. Logs activity.
- `public function update_amount(DFEAccount $account, $new_amount)`
  - DB Transactions: Yes. Updates monthly amount and benefit values across pending installments. Logs activity.
- `public function redeemDFEAccount(DFEAccount $account, string $redeemReference, float $amount, bool $force = false): bool`
  - Updates account json data to reflect redemption. Logs activity.
- `public function pending_payments($period)` / `public function upcoming_payments($period)`
  - System log: Yes (`Log::info`). Fetches lists of pending/upcoming payment accounts based on dates.

---

## 7. DFEUserService
**File:** `DFEUserService.php`
**Description:** Simple service for fetching and reading `DFEUser` model data.
- **Triggers Notifications:** No
- **Database Transactions:** No
- **System Logging (`Log::`):** No
- **Audit Logging:** No

### Actions:
- `public function all()`
- `public function getDFEUser($phoneNumber)`
- `public function getDFEUserFromEmail($email)`
- `public function getDFEUserByAlias($remote_id, $remote_type)`

---

## 8. DFEWebhookService
**File:** `DFEWebhookService.php`
**Description:** Acts as an endpoint service for incoming Razorpay webhooks, deciphering events and routing to `DFEPaymentService`.
- **Triggers Notifications:** No (Handled downstream by PaymentService)
- **Database Transactions:** Yes
- **System Logging (`Log::`):** Yes (`Log::error` on exception)
- **Audit Logging:** Yes (Logs activity for webhook reception via `DFEActivityService`)

### Actions:
- `public function updateWebhookStatus($event, $order_id, $reference_id, $gateway_signature)`
  - DB Transactions: Yes. Handles `payment.captured` by routing to `completePayment` or `refund.created` by routing to `cancelPayment`. Logs audit activity and system errors.

---

## 9. DFEZohoService
**File:** `DFEZohoService.php`
**Description:** Manages integrations and HTTP requests to Zoho CRM API.
- **Triggers Notifications:** No
- **Database Transactions:** No
- **System Logging (`Log::`):** No (Throws custom `ZohoException`)
- **Audit Logging:** No

### Actions:
- `public function generateRefreshToken()` / `public function generateAccessToken()`
  - Makes HTTP calls to Zoho OAuth endpoints.
- `public function create($module, $data)` / `public function get($module, $id = null)` / `public function delete($module, $id)` / `public function update($module, $data, $id)`
  - Performs CRUD actions against the Zoho API endpoints with the access token.

---

## 10. NativeUserService
**File:** `NativeUserService.php`
**Description:** Handles operations related to the system's native users (Staff/Admins/Agents).
- **Triggers Notifications:** No
- **Database Transactions:** No
- **System Logging (`Log::`):** No
- **Audit Logging:** No

### Actions:
- `public function register($uuid, $name, $email, $password, $store, $store_admin)`
- `public function recover(&$user)`
- `public function updatePassword(&$user, $password)`
- `public function revokeAPIKey(&$user)`
- `public function generateRefferalToken(&$user)`
