npm package: @nextocore/utils
Description: nextocore utils - Comprehensive utilities for Next.js + Odoo applications with AI features, collaboration, server actions, and development tools
Author: ABC Food Development Team
Latest version: 1.0.0

# @nextocore/utils

Comprehensive utilities for Next.js + Odoo applications with AI features, real-time collaboration, server actions, and development tools.

## 🚀 Features

- **🤖 AI-Powered Features**: Smart form suggestions and validation
- **👥 Real-Time Collaboration**: Multi-user editing with conflict resolution
- **⚡ Server Actions**: Form handling and file uploads for Next.js App Router
- **🔧 Core Utilities**: Validation, data manipulation, and helper functions
- **🛠️ Development Tools**: Testing framework, bundle analysis, and monitoring

## 📦 Installation

```bash
npm install @nextocore/utils
# or
pnpm add @nextocore/utils
# or
yarn add @nextocore/utils
```

## 🎯 Quick Start

### AI-Powered Form Suggestions

```typescript
import { useAISuggestions } from '@nextocore/utils/ai'

function EmailField() {
  const { suggestions, loading, generateSuggestions } = useAISuggestions(
    'email',
    { maxSuggestions: 3, confidenceThreshold: 0.8 }
  )

  return (
    <div>
      <input
        type="email"
        onChange={(e) => generateSuggestions(e.target.value)}
        placeholder="Enter email..."
      />
      {suggestions.map(suggestion => (
        <div key={suggestion.id}>
          {suggestion.value} (confidence: {suggestion.confidence})
        </div>
      ))}
    </div>
  )
}
```

### Smart Validation

```typescript
import { useSmartValidation } from '@nextocore/utils/ai'

function MyForm() {
  const [formData, setFormData] = useState({
    email: '',
    phone: '',
    birthDate: ''
  })

  const { isValidating, result, errors, warnings } = useSmartValidation(
    formData,
    { enabled: true, realTime: true }
  )

  return (
    <form>
      {/* Form fields */}
      {errors.map(error => (
        <div key={error.field} className="error">
          {error.message}
        </div>
      ))}
    </form>
  )
}
```

### Real-Time Collaboration

```typescript
import { useRealTimeForm } from '@nextocore/utils/collaboration'

function CollaborativeForm({ documentId }) {
  const { collaboration, sendOperation, isConnected, connectedUsers } = useRealTimeForm(
    documentId,
    {
      enabled: true,
      autoSave: true,
      conflictResolution: 'manual'
    }
  )

  const handleFieldChange = (field: string, value: any) => {
    sendOperation({
      type: 'update',
      field,
      newValue: value,
      oldValue: collaboration[field] || null
    })
  }

  return (
    <div>
      <div className="users">
        {connectedUsers.map(user => (
          <div key={user.id}>
            {user.name} - {user.isOnline ? '🟢' : '🔴'}
          </div>
        ))}
      </div>
      <form>
        {/* Form fields with collaboration */}
      </form>
    </div>
  )
}
```

### Server Actions

```typescript
import { submitForm, createRecord, uploadFile } from '@nextocore/utils/server-actions'

// Form submission with validation
export async function submitContactForm(data: ContactFormData) {
  return await submitForm(data, {
    endpoint: '/api/contact',
    method: 'POST',
    validate: true,
    validationRules: [
      { field: 'email', required: true, type: 'email' },
      { field: 'name', required: true, minLength: 2 }
    ],
    onSuccess: { message: 'Form submitted successfully!' },
    revalidate: ['contacts']
  })
}

// Record creation
export async function createCustomer(data: CustomerData) {
  return await createRecord('res.partner', data, {
    validate: true,
    revalidate: ['customers']
  })
}

// File upload
export async function uploadAvatar(file: File) {
  return await uploadFile(file, {
    maxSize: 2 * 1024 * 1024, // 2MB
    allowedTypes: ['image/jpeg', 'image/png'],
    processImage: {
      resize: { width: 200, height: 200 },
      quality: 80,
      format: 'jpeg'
    }
  })
}
```

### Core Utilities

```typescript
import {
  validateForm,
  ValidationRules,
  deepMerge,
  paginate,
  debounce
} from '@nextocore/utils/core'

// Form validation
const errors = validateForm(formData, [
  ValidationRules.required('email'),
  ValidationRules.email('email'),
  ValidationRules.minLength('name', 2),
  ValidationRules.custom('age', (value) => value >= 18, 'Must be 18 or older')
])

// Data manipulation
const mergedData = deepMerge(defaults, userData)
const paginatedResults = paginate(allItems, { page: 1, limit: 20 })

// Debounced search
const debouncedSearch = debounce((query: string) => {
  // Perform search
}, 300)
```

## 📚 Module Exports

### Core Utilities

```typescript
import {
  validateForm,
  ValidationRules,
  deepMerge,
  deepClone,
  pick,
  omit,
  debounce,
  throttle,
  paginate,
  groupBy,
  sortBy
} from '@nextocore/utils/core'
```

### AI Features

```typescript
import {
  useAISuggestions,
  useSmartValidation,
  AIEngine,
  SmartValidator
} from '@nextocore/utils/ai'
```

### Collaboration

```typescript
import {
  useRealTimeForm,
  useCollaboration,
  CollaborationManager,
  ConflictResolver,
  OperationalTransform
} from '@nextocore/utils/collaboration'
```

### Server Actions

```typescript
import {
  submitForm,
  createRecord,
  updateRecord,
  deleteRecord,
  batchOperations,
  uploadFile,
  uploadMultipleFiles,
  processImage
} from '@nextocore/utils/server-actions'
```

### Development Tools

```typescript
import {
  // Testing
  setupTesting,
  TestingFramework,
  MockDataGenerator,

  // Analysis
  analyzeBundle,
  runPerformanceAudit,
  CodeAnalyzer,

  // Monitoring
  startDebugSession,
  usePerformanceMonitor,
  ErrorTracker,

  // Development Server
  startDevServer,
  DevServer
} from '@nextocore/utils/devtools'
```

## 🔧 Configuration

### AI Features Configuration

```typescript
const aiConfig: AISuggestionConfig = {
  enabled: true,
  endpoint: 'https://api.openai.com/v1/completions',
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-3.5-turbo',
  maxSuggestions: 5,
  confidenceThreshold: 0.7
}
```

### Collaboration Configuration

```typescript
const collaborationConfig: RealTimeFormConfig = {
  enabled: true,
  endpoint: 'wss://your-collaboration-server.com',
  autoSave: true,
  saveInterval: 2000,
  conflictResolution: 'manual',
  enablePresence: true,
  enableCursors: true
}
```

### Validation Rules

```typescript
import { ValidationRules } from '@nextocore/utils/core'

const rules = [
  ValidationRules.required('email'),
  ValidationRules.email('email'),
  ValidationRules.minLength('password', 8),
  ValidationRules.pattern('phone', /^\+?[\d\s\-\(\)]+$/),
  ValidationRules.custom('confirmPassword',
    (value, formData) => value === formData.password,
    'Passwords must match'
  )
]
```

## 🧪 Testing

The utils package includes comprehensive testing utilities:

```typescript
import { setupTesting, MockDataGenerator } from '@nextocore/utils/devtools/testing'

// Set up complete testing framework
const setup = await setupTesting({
  framework: 'vitest',
  testingLibrary: true,
  coverage: true,
  mockData: true,
  odooIntegration: true
})

// Generate mock data
const mockPartner = MockDataGenerator.generatePartner({
  name: 'Test Customer',
  email: 'test@example.com'
})
```

## 📊 Bundle Analysis

Analyze your application bundle and performance:

```typescript
import { analyzeBundle, generateProjectReport } from '@nextocore/utils/devtools/analysis'

// Analyze bundle size
const bundleAnalysis = await analyzeBundle('./my-app')

// Generate comprehensive project report
const projectReport = await generateProjectReport('./my-app')
console.log(`Overall score: ${projectReport.overallScore}/100`)
```

## 🔍 Performance Monitoring

Monitor application performance in development:

```typescript
import { usePerformanceMonitor, trackError } from '@nextocore/utils/devtools/monitoring'

function MyComponent() {
  const { startTimer, endTimer, recordMetric } = usePerformanceMonitor()

  useEffect(() => {
    startTimer('component-render')
    // Component logic
    endTimer('component-render')
  }, [])

  const handleError = (error: Error) => {
    trackError(error, { component: 'MyComponent' })
  }
}
```

## 🚀 Development Server

Start a development server with hot reload and Odoo proxy:

```typescript
import { startDevServer } from '@nextocore/utils/devtools/server'

const server = await startDevServer({
  port: 3001,
  nextPort: 3000,
  odooUrl: 'http://localhost:8069',
  enableProxy: true,
  enableHotReload: true,
  enableMockData: true
})
```

## 📋 API Reference

### Types

The package provides comprehensive TypeScript types for all features:

```typescript
import type {
  // AI Types
  AISuggestion,
  SmartValidationConfig,

  // Collaboration Types
  CollaborationState,
  RealTimeFormConfig,

  // Form Types
  ServerActionResult,
  FormSubmissionConfig,

  // Common Types
  PaginatedResult,
  ApiResponse,
  DeepPartial
} from '@nextocore/utils/types'
```

## 🤝 Contributing

1. Clone the repository
2. Install dependencies: `pnpm install`
3. Run tests: `pnpm test`
4. Build the package: `pnpm build`
5. Make your changes and add tests
6. Submit a pull request

## 📄 License

MIT © ABC Food Development Team

## 🔗 Related Packages

- [@nextocore/odoo](https://github.com/abc-food/nextocore/tree/main/packages/odoo) - Odoo integration
- [@nextocore/ui](https://github.com/abc-food/nextocore/tree/main/packages/ui) - UI components
- [@nextocore/auth](https://github.com/abc-food/nextocore/tree/main/packages/auth) - Authentication

## 📞 Support

- 📧 Email: support@abc-food.com
- 📖 Documentation: https://docs.nextocore.com
- 🐛 Issues: https://github.com/abc-food/nextocore/issues