# QuickBooks Payment Gateway - Refactored Structure

This directory contains the refactored, modular version of the QuickBooks Payment Gateway.

## 🏗️ Architecture

### Directory Structure
```
src/
├── server.js              # Main server file (entry point)
├── config/
│   └── environment.js     # Environment configuration
├── services/
│   ├── quickbooks-online.js    # QuickBooks Online API service
│   └── quickbooks-payments.js  # QuickBooks Payments API service
├── routes/
│   ├── payments.js        # Payment processing routes
│   └── admin.js          # Admin management routes
├── middleware/
│   ├── auth.js           # Authentication middleware
│   └── rate-limit.js     # Rate limiting middleware
└── utils/
    ├── network.js        # Network utilities
    ├── logging.js        # Logging utilities
    └── validation.js     # Input validation utilities
```

## 🚀 Key Improvements

### 1. **Modular Architecture**
- Separated concerns into logical modules
- Each service handles a specific responsibility
- Easy to test and maintain individual components

### 2. **Enhanced Refund Handling**
- **NEW**: Automatic RefundReceipt creation in QuickBooks Online
- **NEW**: Links refunds to original Sales Receipts
- **NEW**: Complete accounting audit trail for refunds

### 3. **Improved Transaction Management**
- **NEW**: Void transaction support with QBO integration
- **NEW**: Sales Receipt lookup by transaction ID
- **NEW**: Proper accounting entries for all transaction types

### 4. **Better Error Handling**
- Centralized error logging
- Graceful fallbacks for accounting operations
- Detailed audit trails

## 🔧 Usage

### Starting the Server
```bash
# Use the new modular structure
npm start

# Or run the old monolithic version
npm run start-old
```

### Environment Variables
All configuration is handled in `src/config/environment.js`. Required variables:
- `QB_CLIENT_ID`
- `QB_CLIENT_SECRET`
- `QB_REDIRECT_URI`
- `ADMIN_API_KEY`
- `ADMIN_USERNAME`
- `ADMIN_PASSWORD`

## 📊 Transaction Flow

### Payment Processing
1. **Payment Request** → `src/routes/payments.js`
2. **Validation** → `src/utils/validation.js`
3. **Customer Lookup/Creation** → `src/services/quickbooks-online.js`
4. **Payment Processing** → `src/services/quickbooks-payments.js`
5. **Sales Receipt Creation** → `src/services/quickbooks-online.js`

### Refund Processing (NEW!)
1. **Refund Request** → `src/routes/admin.js`
2. **Process Refund** → `src/services/quickbooks-payments.js`
3. **Find Original Sales Receipt** → `src/services/quickbooks-online.js`
4. **Create Refund Receipt** → `src/services/quickbooks-online.js`
5. **Link Transactions** → Complete audit trail

## 🧪 Testing

The modular structure makes testing much easier:

```javascript
// Example: Testing the QuickBooks Online service
const QuickBooksOnlineService = require('./src/services/quickbooks-online');

const qboService = new QuickBooksOnlineService(accessToken, realmId, 'sandbox');
const customer = await qboService.findCustomerByEmail('test@example.com');
```

## 📈 Benefits

### For Accounting
- ✅ **Complete audit trail** for all transactions
- ✅ **Proper refund receipts** in QuickBooks Online
- ✅ **Linked transactions** (payment → refund)
- ✅ **Voided transactions** properly handled

### For Development
- ✅ **Modular code** easier to maintain
- ✅ **Separated concerns** for better testing
- ✅ **Reusable services** across different routes
- ✅ **Centralized configuration** and utilities

### For Operations
- ✅ **Better error handling** with detailed logging
- ✅ **Graceful degradation** if QBO operations fail
- ✅ **Rate limiting** and security middleware
- ✅ **Health checks** and monitoring endpoints

## 🔄 Migration

To migrate from the old `server.js`:

1. **Backup your current setup**
2. **Update package.json** to use `src/server.js`
3. **Copy your `.env` file** (no changes needed)
4. **Copy your `.tokens.json`** file (no changes needed)
5. **Test in sandbox environment**
6. **Deploy to production**

The new structure is fully backward compatible with your existing QuickBooks connections and data.
