Compare commits
81 Commits
ee641586c3
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ffc60aba5 | |||
| 7ab890005b | |||
| b6405764a9 | |||
| 256b311c43 | |||
| 32fe2fbc9b | |||
| e3bc5da7e3 | |||
| b6bfa17980 | |||
| fd81e8ce2d | |||
| 054202dc32 | |||
| 92f54f7103 | |||
| 8f8c5c5a12 | |||
| 187cb4f127 | |||
| 7881508a7b | |||
| 821985469e | |||
| a5257df2b7 | |||
| 342d9d0700 | |||
| d54fc9914d | |||
| f8d1579cb2 | |||
| d80c99c6c0 | |||
| 9c773be3ec | |||
| 9c6878d1bd | |||
| 5f9d00b575 | |||
| 2cc765912e | |||
| b6e66f0e64 | |||
| 0aa95fba47 | |||
| 0b082549b9 | |||
| b0d2aa93ab | |||
| c16dd51199 | |||
| 245caea4dc | |||
| dda118a005 | |||
| 8147fedd04 | |||
| b1c531bb70 | |||
| 9cc1b7072c | |||
| 2968bcf3f8 | |||
| ad0f7a7a01 | |||
| 368b0a7cf7 | |||
| aa375ce0da | |||
| 340e16c610 | |||
| 33b236d881 | |||
| fb7704027b | |||
| e5902706f1 | |||
| 229c100cc4 | |||
| 9a4897bf0c | |||
| d779e4d7a1 | |||
| b2a9350d0f | |||
| d64a67cf76 | |||
| 068bbdf583 | |||
| cc4c07717e | |||
| 28f28be1b8 | |||
| 27bdb942ab | |||
| ebf9f29200 | |||
| 7eaab16e30 | |||
| 6a2dd860fa | |||
| 091fb07646 | |||
| 357a254e82 | |||
| aa93c96d31 | |||
| ca8754cd94 | |||
| 8fdc0d6359 | |||
| df6c3133ec | |||
| f646b6530a | |||
| 7fc4520dbf | |||
| f66bbbf842 | |||
| 4f605451e1 | |||
| dc41862afc | |||
| c4d2f6e473 | |||
| 711438d79f | |||
| fb6474ab88 | |||
| 6871fe8796 | |||
| 137e0b45ad | |||
| 2ad24216ae | |||
| c4d9ecb39e | |||
| 70a5d015e0 | |||
| 8031501d25 | |||
| 703b52ff59 | |||
| 9fc5b54b8a | |||
| 082a637719 | |||
| b9f66cbfbe | |||
| 36b63a180d | |||
| 84b75143df | |||
| dea7432deb | |||
| f8623a6071 |
@@ -0,0 +1,29 @@
|
|||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.github
|
||||||
|
.gitattributes
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.production.example
|
||||||
|
node_modules
|
||||||
|
npm-debug.log
|
||||||
|
vendor
|
||||||
|
storage/app/*
|
||||||
|
storage/framework/cache/*
|
||||||
|
storage/framework/sessions/*
|
||||||
|
storage/framework/views/*
|
||||||
|
storage/logs/*
|
||||||
|
bootstrap/cache/*
|
||||||
|
public/storage
|
||||||
|
public/hot
|
||||||
|
*.md
|
||||||
|
!README.md
|
||||||
|
tests
|
||||||
|
.phpunit.result.cache
|
||||||
|
phpunit.xml
|
||||||
|
docker-compose*.yml
|
||||||
|
.editorconfig
|
||||||
|
.styleci.yml
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
APP_NAME="Teren App"
|
||||||
|
APP_ENV=local
|
||||||
|
APP_KEY=
|
||||||
|
APP_DEBUG=true
|
||||||
|
APP_TIMEZONE=UTC
|
||||||
|
APP_URL=http://localhost:8080
|
||||||
|
|
||||||
|
APP_LOCALE=sl
|
||||||
|
APP_FALLBACK_LOCALE=en
|
||||||
|
APP_FAKER_LOCALE=sl_SI
|
||||||
|
|
||||||
|
APP_MAINTENANCE_DRIVER=file
|
||||||
|
APP_MAINTENANCE_STORE=database
|
||||||
|
|
||||||
|
BCRYPT_ROUNDS=12
|
||||||
|
|
||||||
|
BROADCAST_CONNECTION=log
|
||||||
|
FILESYSTEM_DISK=local
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DB_CONNECTION=pgsql
|
||||||
|
DB_HOST=postgres
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_DATABASE=teren_app
|
||||||
|
DB_USERNAME=teren_user
|
||||||
|
DB_PASSWORD=local_password
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
REDIS_CLIENT=phpredis
|
||||||
|
REDIS_HOST=redis
|
||||||
|
REDIS_PORT=6379
|
||||||
|
|
||||||
|
# Queue
|
||||||
|
QUEUE_CONNECTION=redis
|
||||||
|
|
||||||
|
# Session
|
||||||
|
SESSION_DRIVER=redis
|
||||||
|
SESSION_LIFETIME=120
|
||||||
|
SESSION_ENCRYPT=false
|
||||||
|
SESSION_PATH=/
|
||||||
|
SESSION_DOMAIN=
|
||||||
|
SESSION_SECURE_COOKIE=false
|
||||||
|
SESSION_SAME_SITE=lax
|
||||||
|
|
||||||
|
# Cache
|
||||||
|
CACHE_STORE=redis
|
||||||
|
|
||||||
|
# Mail (Mailpit for local testing)
|
||||||
|
MAIL_MAILER=smtp
|
||||||
|
MAIL_HOST=mailpit
|
||||||
|
MAIL_PORT=1025
|
||||||
|
MAIL_USERNAME=null
|
||||||
|
MAIL_PASSWORD=null
|
||||||
|
MAIL_ENCRYPTION=null
|
||||||
|
SCOUT_PREFIX=
|
||||||
|
SCOUT_QUEUE=true
|
||||||
|
|
||||||
|
# Sanctum
|
||||||
|
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1,localhost:8080,127.0.0.1:8080
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
LOG_CHANNEL=stack
|
||||||
|
LOG_STACK=single
|
||||||
|
LOG_DEPRECATIONS_CHANNEL=null
|
||||||
|
LOG_LEVEL=debug
|
||||||
|
|
||||||
|
# Vite
|
||||||
|
VITE_APP_NAME="${APP_NAME}"
|
||||||
|
VITE_DEV_SERVER_KEY=
|
||||||
|
VITE_DEV_SERVER_CERT=
|
||||||
|
|
||||||
|
# LibreOffice for document previews (Docker container path)
|
||||||
|
LIBREOFFICE_BIN=/usr/bin/soffice
|
||||||
|
|
||||||
|
# Storage configuration for generated previews
|
||||||
|
FILES_PREVIEW_DISK=public
|
||||||
|
FILES_PREVIEW_BASE=previews/casesNEL=null
|
||||||
|
LOG_LEVEL=debug
|
||||||
|
|
||||||
|
# Vite
|
||||||
|
VITE_DEV_SERVER_KEY=
|
||||||
|
VITE_DEV_SERVER_CERT=
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
APP_NAME="Teren App"
|
||||||
|
APP_ENV=production
|
||||||
|
APP_KEY= # Generate with: php artisan key:generate
|
||||||
|
APP_DEBUG=false
|
||||||
|
APP_TIMEZONE=UTC
|
||||||
|
APP_URL=https://example.com # Your domain
|
||||||
|
|
||||||
|
APP_LOCALE=sl
|
||||||
|
APP_FALLBACK_LOCALE=en
|
||||||
|
APP_FAKER_LOCALE=sl_SI
|
||||||
|
|
||||||
|
APP_MAINTENANCE_DRIVER=file
|
||||||
|
APP_MAINTENANCE_STORE=database
|
||||||
|
|
||||||
|
BCRYPT_ROUNDS=12
|
||||||
|
|
||||||
|
BROADCAST_CONNECTION=log
|
||||||
|
FILESYSTEM_DISK=local
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DB_CONNECTION=pgsql
|
||||||
|
DB_HOST=postgres
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_DATABASE=teren_app
|
||||||
|
DB_USERNAME=teren_user
|
||||||
|
DB_PASSWORD= # Generate a strong password
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
REDIS_CLIENT=phpredis
|
||||||
|
REDIS_HOST=redis
|
||||||
|
REDIS_PORT=6379
|
||||||
|
|
||||||
|
# Queue
|
||||||
|
QUEUE_CONNECTION=redis
|
||||||
|
|
||||||
|
# Session
|
||||||
|
SESSION_DRIVER=redis
|
||||||
|
SESSION_LIFETIME=120
|
||||||
|
SESSION_ENCRYPT=false
|
||||||
|
SESSION_PATH=/
|
||||||
|
SESSION_DOMAIN=
|
||||||
|
SESSION_SECURE_COOKIE=true
|
||||||
|
SESSION_SAME_SITE=lax
|
||||||
|
|
||||||
|
# Cache
|
||||||
|
CACHE_STORE=redis
|
||||||
|
|
||||||
|
# pgAdmin
|
||||||
|
PGADMIN_EMAIL=admin@example.com
|
||||||
|
PGADMIN_PASSWORD= # Generate a strong password
|
||||||
|
|
||||||
|
# WireGuard VPN (REQUIRED - app is VPN-only)
|
||||||
|
WG_SERVERURL=vpn.example.com # Your VPS public IP or domain
|
||||||
|
WG_UI_PASSWORD= # Generate a strong password for WireGuard dashboard
|
||||||
|
|
||||||
|
# Mail (configure as needed)
|
||||||
|
MAIL_MAILER=log
|
||||||
|
MAIL_HOST=127.0.0.1
|
||||||
|
MAIL_PORT=2525
|
||||||
|
MAIL_USERNAME=null
|
||||||
|
MAIL_PA
|
||||||
|
SCOUT_DRIVER=database
|
||||||
|
SCOUT_PREFIX=
|
||||||
|
SCOUT_QUEUE=true
|
||||||
|
|
||||||
|
# Sanctum
|
||||||
|
SANCTUM_STATEFUL_DOMAINS=example.com,www.example.com,10.13.13.1
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
LOG_CHANNEL=stack
|
||||||
|
LOG_STACK=single
|
||||||
|
LOG_DEPRECATIONS_CHANNEL=null
|
||||||
|
LOG_LEVEL=error
|
||||||
|
|
||||||
|
# Vite
|
||||||
|
VITE_APP_NAME="${APP_NAME}"
|
||||||
|
|
||||||
|
# LibreOffice for document previews (Docker container path)
|
||||||
|
LIBREOFFICE_BIN=/usr/bin/soffice
|
||||||
|
|
||||||
|
# Storage configuration for generated previews
|
||||||
|
FILES_PREVIEW_DISK=public
|
||||||
|
FILES_PREVIEW_BASE=previews/cases
|
||||||
|
# Logging
|
||||||
|
LOG_CHANNEL=stack
|
||||||
|
LOG_STACK=single
|
||||||
|
LOG_DEPRECATIONS_CHANNEL=null
|
||||||
|
LOG_LEVEL=error
|
||||||
+19
@@ -20,3 +20,22 @@ yarn-error.log
|
|||||||
/.vscode
|
/.vscode
|
||||||
/.zed
|
/.zed
|
||||||
/shadcn-vue
|
/shadcn-vue
|
||||||
|
|
||||||
|
# Development/Testing Scripts
|
||||||
|
check-*.php
|
||||||
|
test-*.php
|
||||||
|
fix-*.php
|
||||||
|
clean-*.php
|
||||||
|
mark-*.php
|
||||||
|
|
||||||
|
# Development Documentation
|
||||||
|
IMPORT_*.md
|
||||||
|
V2_*.md
|
||||||
|
REPORTS_*.md
|
||||||
|
DEDUPLICATION_*.md
|
||||||
|
|
||||||
|
# Docker Local Testing
|
||||||
|
docker-compose.local.yaml
|
||||||
|
docker-compose.override.yaml
|
||||||
|
.env.local
|
||||||
|
.env.docker
|
||||||
@@ -0,0 +1,654 @@
|
|||||||
|
# V2 Deduplication Implementation Plan
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
Currently, ImportServiceV2 allows duplicate Person records and related entities when:
|
||||||
|
1. A ClientCase with the same `client_ref` already exists in the database
|
||||||
|
2. A Contract with the same `reference` already exists for the client
|
||||||
|
3. Person data is present in the import row
|
||||||
|
|
||||||
|
This causes data duplication because V2 doesn't check for existing entities before creating Person and related entities (addresses, phones, emails, activities).
|
||||||
|
|
||||||
|
## V1 Deduplication Strategy (Analysis)
|
||||||
|
|
||||||
|
### V1 Person Resolution Order (Lines 913-1015)
|
||||||
|
V1 follows this hierarchical lookup before creating a new Person:
|
||||||
|
|
||||||
|
1. **Contract Reference Lookup** (Lines 913-922)
|
||||||
|
- If contract.reference exists → Find existing Contract → Get ClientCase → Get Person
|
||||||
|
- Prevents creating new Person when Contract already exists
|
||||||
|
|
||||||
|
2. **Account Result Derivation** (Lines 924-936)
|
||||||
|
- If Account processing resolved/created a Contract → Get ClientCase → Get Person
|
||||||
|
|
||||||
|
3. **ClientCase.client_ref Lookup** (Lines 937-945)
|
||||||
|
- If client_ref exists → Find ClientCase by (client_id, client_ref) → Get Person
|
||||||
|
- Prevents creating new Person when ClientCase already exists
|
||||||
|
|
||||||
|
4. **Contact Values Lookup** (Lines 949-964)
|
||||||
|
- Check Email.value → Get Person
|
||||||
|
- Check PersonPhone.nu → Get Person
|
||||||
|
- Check PersonAddress.address → Get Person
|
||||||
|
|
||||||
|
5. **Person Identifiers Lookup** (Lines 1005-1007)
|
||||||
|
- Check tax_number, ssn, etc. via `findPersonIdByIdentifiers()`
|
||||||
|
|
||||||
|
6. **Create New Person** (Lines 1009-1011)
|
||||||
|
- Only if all above fail
|
||||||
|
|
||||||
|
### V1 Contract Deduplication (Lines 2158-2196)
|
||||||
|
|
||||||
|
**Early Contract Lookup** (Lines 2168-2180):
|
||||||
|
```php
|
||||||
|
// Try to find existing contract EARLY by (client_id, reference)
|
||||||
|
// across all cases to prevent duplicates
|
||||||
|
$existing = Contract::query()->withTrashed()
|
||||||
|
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
||||||
|
->where('client_cases.client_id', $clientId)
|
||||||
|
->where('contracts.reference', $reference)
|
||||||
|
->select('contracts.*')
|
||||||
|
->first();
|
||||||
|
```
|
||||||
|
|
||||||
|
**ClientCase Reuse Logic** (Lines 2214-2228):
|
||||||
|
```php
|
||||||
|
// If we have a client and client_ref, try to reuse existing case
|
||||||
|
// to avoid creating extra persons
|
||||||
|
if ($clientId && $clientRef) {
|
||||||
|
$cc = ClientCase::where('client_id', $clientId)
|
||||||
|
->where('client_ref', $clientRef)
|
||||||
|
->first();
|
||||||
|
if ($cc) {
|
||||||
|
// Reuse this case
|
||||||
|
$clientCaseId = $cc->id;
|
||||||
|
// If case has no person yet, set it
|
||||||
|
if (!$cc->person_id) {
|
||||||
|
// Find or create person and attach
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key V1 Design Principles
|
||||||
|
|
||||||
|
✅ **Resolution before Creation** - Always check for existing entities first
|
||||||
|
✅ **Chain Derivation** - Contract → ClientCase → Person (reuse existing chain)
|
||||||
|
✅ **Contact Deduplication** - Match by email/phone/address before creating
|
||||||
|
✅ **Client-Scoped Lookups** - All queries scoped to import.client_id
|
||||||
|
✅ **Minimal Person Creation** - Only create Person as last resort
|
||||||
|
|
||||||
|
## V2 Current Architecture Issues
|
||||||
|
|
||||||
|
### Problem Areas
|
||||||
|
|
||||||
|
1. **PersonHandler** (`app/Services/Import/Handlers/PersonHandler.php`)
|
||||||
|
- Currently only deduplicates by tax_number/ssn (Lines 38-58)
|
||||||
|
- Doesn't check if Person exists via Contract/ClientCase
|
||||||
|
- Processes independently without context awareness
|
||||||
|
|
||||||
|
2. **ClientCaseHandler** (`app/Services/Import/Handlers/ClientCaseHandler.php`)
|
||||||
|
- Correctly resolves by client_ref (Lines 16-27)
|
||||||
|
- But doesn't prevent PersonHandler from running afterwards
|
||||||
|
|
||||||
|
3. **ContractHandler** (`app/Services/Import/Handlers/ContractHandler.php`)
|
||||||
|
- Missing early resolution logic
|
||||||
|
- Doesn't derive Person from existing Contract chain
|
||||||
|
|
||||||
|
4. **Processing Order Issue**
|
||||||
|
- Current priority: Person(100) → ClientCase(95) → Contract(90)
|
||||||
|
- Person runs BEFORE we know if ClientCase/Contract exists
|
||||||
|
- Should be reversed: Contract → ClientCase → Person
|
||||||
|
|
||||||
|
## V2 Deduplication Plan
|
||||||
|
|
||||||
|
### Phase 1: Reverse Processing Order ✅
|
||||||
|
|
||||||
|
**Change entity priorities in database seeder:**
|
||||||
|
```php
|
||||||
|
// NEW ORDER (descending priority)
|
||||||
|
Contract: 100
|
||||||
|
ClientCase: 95
|
||||||
|
Person: 90
|
||||||
|
Email: 80
|
||||||
|
Address: 70
|
||||||
|
Phone: 60
|
||||||
|
Account: 50
|
||||||
|
Payment: 40
|
||||||
|
Activity: 30
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rationale:** Process high-level entities first (Contract, ClientCase) so we can derive Person from existing chains.
|
||||||
|
|
||||||
|
### Phase 2: Early Resolution Service 🔧
|
||||||
|
|
||||||
|
**Create:** `app/Services/Import/EntityResolutionService.php`
|
||||||
|
|
||||||
|
This service will be called BEFORE handlers process entities:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class EntityResolutionService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Resolve Person ID from import context (existing entities).
|
||||||
|
* Returns Person ID if found, null otherwise.
|
||||||
|
*/
|
||||||
|
public function resolvePersonFromContext(
|
||||||
|
Import $import,
|
||||||
|
array $mapped,
|
||||||
|
array $context
|
||||||
|
): ?int {
|
||||||
|
// 1. Check if Contract already processed
|
||||||
|
if ($contract = $context['contract']['entity'] ?? null) {
|
||||||
|
$personId = $this->getPersonFromContract($contract);
|
||||||
|
if ($personId) return $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Check if ClientCase already processed
|
||||||
|
if ($clientCase = $context['client_case']['entity'] ?? null) {
|
||||||
|
if ($clientCase->person_id) {
|
||||||
|
return $clientCase->person_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Check for existing Contract by reference
|
||||||
|
if ($contractRef = $mapped['contract']['reference'] ?? null) {
|
||||||
|
$personId = $this->getPersonFromContractReference(
|
||||||
|
$import->client_id,
|
||||||
|
$contractRef
|
||||||
|
);
|
||||||
|
if ($personId) return $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Check for existing ClientCase by client_ref
|
||||||
|
if ($clientRef = $mapped['client_case']['client_ref'] ?? null) {
|
||||||
|
$personId = $this->getPersonFromClientRef(
|
||||||
|
$import->client_id,
|
||||||
|
$clientRef
|
||||||
|
);
|
||||||
|
if ($personId) return $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Check for existing Person by contact values
|
||||||
|
$personId = $this->resolvePersonByContacts($mapped);
|
||||||
|
if ($personId) return $personId;
|
||||||
|
|
||||||
|
return null; // No existing Person found
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if ClientCase exists for this client_ref.
|
||||||
|
*/
|
||||||
|
public function clientCaseExists(int $clientId, string $clientRef): bool
|
||||||
|
{
|
||||||
|
return ClientCase::where('client_id', $clientId)
|
||||||
|
->where('client_ref', $clientRef)
|
||||||
|
->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if Contract exists for this reference.
|
||||||
|
*/
|
||||||
|
public function contractExists(int $clientId, string $reference): bool
|
||||||
|
{
|
||||||
|
return Contract::query()
|
||||||
|
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
||||||
|
->where('client_cases.client_id', $clientId)
|
||||||
|
->where('contracts.reference', $reference)
|
||||||
|
->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getPersonFromContract(Contract $contract): ?int
|
||||||
|
{
|
||||||
|
if ($contract->client_case_id) {
|
||||||
|
return ClientCase::where('id', $contract->client_case_id)
|
||||||
|
->value('person_id');
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getPersonFromContractReference(
|
||||||
|
?int $clientId,
|
||||||
|
string $reference
|
||||||
|
): ?int {
|
||||||
|
if (!$clientId) return null;
|
||||||
|
|
||||||
|
$clientCaseId = Contract::query()
|
||||||
|
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
||||||
|
->where('client_cases.client_id', $clientId)
|
||||||
|
->where('contracts.reference', $reference)
|
||||||
|
->value('contracts.client_case_id');
|
||||||
|
|
||||||
|
if ($clientCaseId) {
|
||||||
|
return ClientCase::where('id', $clientCaseId)
|
||||||
|
->value('person_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getPersonFromClientRef(
|
||||||
|
?int $clientId,
|
||||||
|
string $clientRef
|
||||||
|
): ?int {
|
||||||
|
if (!$clientId) return null;
|
||||||
|
|
||||||
|
return ClientCase::where('client_id', $clientId)
|
||||||
|
->where('client_ref', $clientRef)
|
||||||
|
->value('person_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resolvePersonByContacts(array $mapped): ?int
|
||||||
|
{
|
||||||
|
// Check email
|
||||||
|
if ($email = $mapped['email']['value'] ?? $mapped['emails'][0]['value'] ?? null) {
|
||||||
|
$personId = Email::where('value', trim($email))->value('person_id');
|
||||||
|
if ($personId) return $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check phone
|
||||||
|
if ($phone = $mapped['phone']['nu'] ?? $mapped['person_phones'][0]['nu'] ?? null) {
|
||||||
|
$personId = PersonPhone::where('nu', trim($phone))->value('person_id');
|
||||||
|
if ($personId) return $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check address
|
||||||
|
if ($address = $mapped['address']['address'] ?? $mapped['person_addresses'][0]['address'] ?? null) {
|
||||||
|
$personId = PersonAddress::where('address', trim($address))->value('person_id');
|
||||||
|
if ($personId) return $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3: Update PersonHandler 🔧
|
||||||
|
|
||||||
|
**Modify:** `app/Services/Import/Handlers/PersonHandler.php`
|
||||||
|
|
||||||
|
Add resolution service check before creating:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function process(Import $import, array $mapped, array $raw, array $context = []): array
|
||||||
|
{
|
||||||
|
// FIRST: Check if Person already resolved from context
|
||||||
|
$resolutionService = app(EntityResolutionService::class);
|
||||||
|
$existingPersonId = $resolutionService->resolvePersonFromContext(
|
||||||
|
$import,
|
||||||
|
$mapped,
|
||||||
|
$context
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($existingPersonId) {
|
||||||
|
$existing = Person::find($existingPersonId);
|
||||||
|
|
||||||
|
// Update if configured
|
||||||
|
$mode = $this->getOption('update_mode', 'update');
|
||||||
|
|
||||||
|
if ($mode === 'skip') {
|
||||||
|
return [
|
||||||
|
'action' => 'skipped',
|
||||||
|
'entity' => $existing,
|
||||||
|
'message' => 'Person already exists (found via Contract/ClientCase chain)',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update logic...
|
||||||
|
return [
|
||||||
|
'action' => 'updated',
|
||||||
|
'entity' => $existing,
|
||||||
|
'count' => 1,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// SECOND: Try existing deduplication (tax_number, ssn)
|
||||||
|
$existing = $this->resolve($mapped, $context);
|
||||||
|
|
||||||
|
if ($existing) {
|
||||||
|
// Update logic...
|
||||||
|
}
|
||||||
|
|
||||||
|
// THIRD: Check contacts deduplication
|
||||||
|
$personIdFromContacts = $resolutionService->resolvePersonByContacts($mapped);
|
||||||
|
if ($personIdFromContacts) {
|
||||||
|
$existing = Person::find($personIdFromContacts);
|
||||||
|
// Update logic...
|
||||||
|
}
|
||||||
|
|
||||||
|
// LAST: Create new Person only if all checks failed
|
||||||
|
$payload = $this->buildPayload($mapped);
|
||||||
|
$person = Person::create($payload);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'action' => 'inserted',
|
||||||
|
'entity' => $person,
|
||||||
|
'count' => 1,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 4: Update ContractHandler 🔧
|
||||||
|
|
||||||
|
**Modify:** `app/Services/Import/Handlers/ContractHandler.php`
|
||||||
|
|
||||||
|
Add early Contract lookup and ClientCase reuse:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function process(Import $import, array $mapped, array $raw, array $context = []): array
|
||||||
|
{
|
||||||
|
$clientId = $import->client_id;
|
||||||
|
$reference = $mapped['reference'] ?? null;
|
||||||
|
|
||||||
|
if (!$clientId || !$reference) {
|
||||||
|
return [
|
||||||
|
'action' => 'invalid',
|
||||||
|
'errors' => ['Contract requires client_id and reference'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// EARLY LOOKUP: Check if Contract exists across all cases
|
||||||
|
$existing = Contract::query()
|
||||||
|
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
||||||
|
->where('client_cases.client_id', $clientId)
|
||||||
|
->where('contracts.reference', $reference)
|
||||||
|
->select('contracts.*')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($existing) {
|
||||||
|
// Contract exists - update or skip
|
||||||
|
$mode = $this->getOption('update_mode', 'update');
|
||||||
|
|
||||||
|
if ($mode === 'skip') {
|
||||||
|
return [
|
||||||
|
'action' => 'skipped',
|
||||||
|
'entity' => $existing,
|
||||||
|
'message' => 'Contract already exists',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update logic...
|
||||||
|
return [
|
||||||
|
'action' => 'updated',
|
||||||
|
'entity' => $existing,
|
||||||
|
'count' => 1,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creating new Contract - resolve/create ClientCase
|
||||||
|
$clientCaseId = $this->resolveOrCreateClientCase($import, $mapped, $context);
|
||||||
|
|
||||||
|
if (!$clientCaseId) {
|
||||||
|
return [
|
||||||
|
'action' => 'invalid',
|
||||||
|
'errors' => ['Unable to resolve client_case_id'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create Contract
|
||||||
|
$payload = array_merge($this->buildPayload($mapped), [
|
||||||
|
'client_case_id' => $clientCaseId,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$contract = Contract::create($payload);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'action' => 'inserted',
|
||||||
|
'entity' => $contract,
|
||||||
|
'count' => 1,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveOrCreateClientCase(
|
||||||
|
Import $import,
|
||||||
|
array $mapped,
|
||||||
|
array $context
|
||||||
|
): ?int {
|
||||||
|
$clientId = $import->client_id;
|
||||||
|
$clientRef = $mapped['client_ref'] ??
|
||||||
|
$context['client_case']['entity']?->client_ref ??
|
||||||
|
null;
|
||||||
|
|
||||||
|
// If ClientCase already processed in this row
|
||||||
|
if ($clientCaseId = $context['client_case']['entity']?->id ?? null) {
|
||||||
|
return $clientCaseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find existing ClientCase by client_ref
|
||||||
|
if ($clientRef) {
|
||||||
|
$existing = ClientCase::where('client_id', $clientId)
|
||||||
|
->where('client_ref', $clientRef)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($existing) {
|
||||||
|
// REUSE existing ClientCase (and its Person)
|
||||||
|
return $existing->id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create new ClientCase (Person should already be processed)
|
||||||
|
$personId = $context['person']['entity']?->id ?? null;
|
||||||
|
|
||||||
|
if (!$personId) {
|
||||||
|
// Person wasn't in import, create minimal
|
||||||
|
$personId = Person::create(['type_id' => 1])->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
$clientCase = ClientCase::create([
|
||||||
|
'client_id' => $clientId,
|
||||||
|
'person_id' => $personId,
|
||||||
|
'client_ref' => $clientRef,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $clientCase->id;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 5: Update ClientCaseHandler 🔧
|
||||||
|
|
||||||
|
**Modify:** `app/Services/Import/Handlers/ClientCaseHandler.php`
|
||||||
|
|
||||||
|
Ensure it uses resolved Person from context:
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function process(Import $import, array $mapped, array $raw, array $context = []): array
|
||||||
|
{
|
||||||
|
$clientId = $import->client_id ?? null;
|
||||||
|
$clientRef = $mapped['client_ref'] ?? null;
|
||||||
|
|
||||||
|
// Get Person from context (should be processed first now)
|
||||||
|
$personId = $context['person']['entity']?->id ?? null;
|
||||||
|
|
||||||
|
if (!$clientId) {
|
||||||
|
return [
|
||||||
|
'action' => 'skipped',
|
||||||
|
'message' => 'ClientCase requires client_id',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$existing = $this->resolve($mapped, $context);
|
||||||
|
|
||||||
|
if ($existing) {
|
||||||
|
$mode = $this->getOption('update_mode', 'update');
|
||||||
|
|
||||||
|
if ($mode === 'skip') {
|
||||||
|
return [
|
||||||
|
'action' => 'skipped',
|
||||||
|
'entity' => $existing,
|
||||||
|
'message' => 'ClientCase already exists (skip mode)',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = $this->buildPayload($mapped, $existing);
|
||||||
|
|
||||||
|
// Update person_id ONLY if provided and different
|
||||||
|
if ($personId && $existing->person_id !== $personId) {
|
||||||
|
$payload['person_id'] = $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
$appliedFields = $this->trackAppliedFields($existing, $payload);
|
||||||
|
$existing->update($payload);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'action' => 'updated',
|
||||||
|
'entity' => $existing,
|
||||||
|
'count' => 1,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create new ClientCase
|
||||||
|
$payload = $this->buildPayload($mapped);
|
||||||
|
|
||||||
|
// Attach Person if resolved
|
||||||
|
if ($personId) {
|
||||||
|
$payload['person_id'] = $personId;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload['client_id'] = $clientId;
|
||||||
|
|
||||||
|
$clientCase = ClientCase::create($payload);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'action' => 'inserted',
|
||||||
|
'entity' => $clientCase,
|
||||||
|
'count' => 1,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 6: Integration into ImportServiceV2 🔧
|
||||||
|
|
||||||
|
**Modify:** `app/Services/Import/ImportServiceV2.php`
|
||||||
|
|
||||||
|
Inject resolution service into processRow:
|
||||||
|
|
||||||
|
```php
|
||||||
|
protected function processRow(Import $import, array $mapped, array $raw, array $context): array
|
||||||
|
{
|
||||||
|
$entityResults = [];
|
||||||
|
$lastEntityType = null;
|
||||||
|
$lastEntityId = null;
|
||||||
|
$hasErrors = false;
|
||||||
|
|
||||||
|
// NEW: Add resolution service to context
|
||||||
|
$context['resolution_service'] = app(EntityResolutionService::class);
|
||||||
|
|
||||||
|
// Process entities in configured priority order
|
||||||
|
foreach ($this->entityConfigs as $root => $config) {
|
||||||
|
// ... existing logic ...
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... rest of method ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementation Checklist
|
||||||
|
|
||||||
|
### Step 1: Update Database Priority ✅
|
||||||
|
- [ ] Modify `database/seeders/ImportEntitiesV2Seeder.php`
|
||||||
|
- [ ] Change priorities: Contract(100), ClientCase(95), Person(90)
|
||||||
|
- [ ] Run seeder: `php artisan db:seed --class=ImportEntitiesV2Seeder --force`
|
||||||
|
|
||||||
|
### Step 2: Create EntityResolutionService 🔧
|
||||||
|
- [ ] Create `app/Services/Import/EntityResolutionService.php`
|
||||||
|
- [ ] Implement all resolution methods
|
||||||
|
- [ ] Add comprehensive PHPDoc
|
||||||
|
- [ ] Add logging for debugging
|
||||||
|
|
||||||
|
### Step 3: Update PersonHandler 🔧
|
||||||
|
- [ ] Modify `process()` method to check resolution service first
|
||||||
|
- [ ] Add contact-based deduplication
|
||||||
|
- [ ] Ensure proper skip/update modes
|
||||||
|
|
||||||
|
### Step 4: Update ContractHandler 🔧
|
||||||
|
- [ ] Add early Contract lookup (client_id + reference)
|
||||||
|
- [ ] Implement ClientCase reuse logic
|
||||||
|
- [ ] Prevent duplicate Contract creation
|
||||||
|
|
||||||
|
### Step 5: Update ClientCaseHandler 🔧
|
||||||
|
- [ ] Use Person from context
|
||||||
|
- [ ] Handle person_id properly on updates
|
||||||
|
- [ ] Maintain existing deduplication
|
||||||
|
|
||||||
|
### Step 6: Integrate into ImportServiceV2 🔧
|
||||||
|
- [ ] Add resolution service to context
|
||||||
|
- [ ] Test with existing imports
|
||||||
|
|
||||||
|
### Step 7: Testing 🧪
|
||||||
|
- [ ] Test import with existing client_ref
|
||||||
|
- [ ] Test import with existing contract reference
|
||||||
|
- [ ] Test import with existing email/phone
|
||||||
|
- [ ] Test mixed scenarios
|
||||||
|
- [ ] Verify no duplicate Persons created
|
||||||
|
- [ ] Check all related entities linked correctly
|
||||||
|
|
||||||
|
## Expected Behavior After Implementation
|
||||||
|
|
||||||
|
### Scenario 1: Existing ClientCase by client_ref
|
||||||
|
```
|
||||||
|
Import Row: {client_ref: "B387055", name: "John", email: "john@test.com"}
|
||||||
|
|
||||||
|
Before V2 Fix:
|
||||||
|
❌ Creates new Person (duplicate)
|
||||||
|
❌ Creates new Email (duplicate)
|
||||||
|
✅ Reuses ClientCase
|
||||||
|
|
||||||
|
After V2 Fix:
|
||||||
|
✅ Finds existing Person via ClientCase
|
||||||
|
✅ Updates Person if needed
|
||||||
|
✅ Reuses ClientCase
|
||||||
|
✅ Reuses/updates Email
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scenario 2: Existing Contract by reference
|
||||||
|
```
|
||||||
|
Import Row: {contract.reference: "REF-123", person.name: "Jane"}
|
||||||
|
|
||||||
|
Before V2 Fix:
|
||||||
|
❌ Creates new Person (duplicate)
|
||||||
|
❌ Contract might be created or updated
|
||||||
|
❌ New Person not linked to existing ClientCase
|
||||||
|
|
||||||
|
After V2 Fix:
|
||||||
|
✅ Finds existing Contract
|
||||||
|
✅ Derives Person from Contract → ClientCase chain
|
||||||
|
✅ Updates Person if needed
|
||||||
|
✅ No duplicate Person created
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scenario 3: New Import (no existing entities)
|
||||||
|
```
|
||||||
|
Import Row: {client_ref: "NEW-001", name: "Bob"}
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
✅ Creates new Person
|
||||||
|
✅ Creates new ClientCase
|
||||||
|
✅ Links correctly
|
||||||
|
✅ No duplicates
|
||||||
|
```
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
✅ **No duplicate Persons** when client_ref or contract reference exists
|
||||||
|
✅ **Proper entity linking** - all entities connected to correct Person
|
||||||
|
✅ **Backward compatibility** - existing imports still work
|
||||||
|
✅ **Skip mode respected** - handlers honor skip/update modes
|
||||||
|
✅ **Contact deduplication** - matches by email/phone/address
|
||||||
|
✅ **Performance maintained** - no significant slowdown
|
||||||
|
|
||||||
|
## Rollback Plan
|
||||||
|
|
||||||
|
If issues occur:
|
||||||
|
1. Revert priority changes in database
|
||||||
|
2. Disable EntityResolutionService by commenting out context injection
|
||||||
|
3. Fall back to original handler behavior
|
||||||
|
4. Investigate and fix issues
|
||||||
|
5. Re-implement with fixes
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- This plan maintains V2's modular handler architecture
|
||||||
|
- Resolution logic is centralized in EntityResolutionService
|
||||||
|
- Handlers remain independent but context-aware
|
||||||
|
- Similar to V1 but cleaner separation of concerns
|
||||||
|
- Can be implemented incrementally (phase by phase)
|
||||||
|
- Each phase can be tested independently
|
||||||
+1045
File diff suppressed because it is too large
Load Diff
+83
@@ -0,0 +1,83 @@
|
|||||||
|
ARG PHP_VERSION=8.4
|
||||||
|
FROM php:${PHP_VERSION}-fpm-alpine
|
||||||
|
|
||||||
|
# Set working directory
|
||||||
|
WORKDIR /var/www
|
||||||
|
|
||||||
|
# Install system dependencies
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
git \
|
||||||
|
curl \
|
||||||
|
zip \
|
||||||
|
unzip \
|
||||||
|
supervisor \
|
||||||
|
nginx \
|
||||||
|
postgresql-dev \
|
||||||
|
libpng-dev \
|
||||||
|
libjpeg-turbo-dev \
|
||||||
|
freetype-dev \
|
||||||
|
libwebp-dev \
|
||||||
|
oniguruma-dev \
|
||||||
|
libxml2-dev \
|
||||||
|
linux-headers \
|
||||||
|
${PHPIZE_DEPS}
|
||||||
|
|
||||||
|
# Configure and install PHP extensions
|
||||||
|
RUN docker-php-ext-configure gd --with-freetype --with-jpeg --with-webp \
|
||||||
|
&& docker-php-ext-install -j$(nproc) \
|
||||||
|
pdo_pgsql \
|
||||||
|
pgsql \
|
||||||
|
mbstring \
|
||||||
|
exif \
|
||||||
|
pcntl \
|
||||||
|
bcmath \
|
||||||
|
gd \
|
||||||
|
opcache
|
||||||
|
|
||||||
|
# Install Redis extension via PECL
|
||||||
|
RUN pecl install redis \
|
||||||
|
&& docker-php-ext-enable redis
|
||||||
|
|
||||||
|
# Install LibreOffice from community repository
|
||||||
|
RUN apk add --no-cache --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community \
|
||||||
|
libreoffice-common \
|
||||||
|
libreoffice-writer \
|
||||||
|
libreoffice-calc
|
||||||
|
|
||||||
|
# Install Composer
|
||||||
|
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
|
||||||
|
|
||||||
|
# Create system user to run Composer and Artisan Commands
|
||||||
|
RUN addgroup -g 1000 -S www && \
|
||||||
|
adduser -u 1000 -S www -G www
|
||||||
|
|
||||||
|
# Copy application files (will be overridden by volume mount in local development)
|
||||||
|
COPY --chown=www:www . /var/www
|
||||||
|
|
||||||
|
# Copy supervisor configuration
|
||||||
|
COPY docker/supervisor/supervisord.conf /etc/supervisor/supervisord.conf
|
||||||
|
COPY docker/supervisor/conf.d /etc/supervisor/conf.d
|
||||||
|
|
||||||
|
# Set permissions
|
||||||
|
RUN chown -R www:www /var/www \
|
||||||
|
&& chmod -R 755 /var/www/storage \
|
||||||
|
&& chmod -R 755 /var/www/bootstrap/cache
|
||||||
|
|
||||||
|
# PHP Configuration for production
|
||||||
|
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
|
||||||
|
|
||||||
|
# Copy PHP custom configuration
|
||||||
|
COPY docker/php/custom.ini $PHP_INI_DIR/conf.d/custom.ini
|
||||||
|
|
||||||
|
# Configure PHP-FPM to listen on all interfaces (0.0.0.0) instead of just localhost
|
||||||
|
# This is needed for nginx running in a separate container to reach PHP-FPM
|
||||||
|
RUN sed -i 's/listen = 127.0.0.1:9000/listen = 9000/' /usr/local/etc/php-fpm.d/www.conf
|
||||||
|
|
||||||
|
# Expose port 9000 for PHP-FPM
|
||||||
|
EXPOSE 9000
|
||||||
|
|
||||||
|
# Create directories for supervisor logs
|
||||||
|
RUN mkdir -p /var/log/supervisor
|
||||||
|
|
||||||
|
# Start supervisor (which will manage both PHP-FPM and Laravel queue workers)
|
||||||
|
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
# Local Testing Guide - Windows/Mac/Linux
|
||||||
|
|
||||||
|
This guide helps you test the Teren App Docker setup on your local machine without WireGuard VPN.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Prerequisites
|
||||||
|
|
||||||
|
- Docker Desktop installed and running
|
||||||
|
- Git
|
||||||
|
- 8GB RAM recommended
|
||||||
|
- Ports available: 8080, 5433 (PostgreSQL), 5050, 6379, 9000, 8025, 1025
|
||||||
|
- **Note:** If you have local PostgreSQL on port 5432, the Docker container uses 5433 instead
|
||||||
|
|
||||||
|
### 2. Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Clone repository (if not already)
|
||||||
|
git clone YOUR_GITEA_URL
|
||||||
|
cd Teren-app
|
||||||
|
|
||||||
|
# Copy local environment file
|
||||||
|
cp .env.local.example .env
|
||||||
|
|
||||||
|
# Start all services
|
||||||
|
docker compose -f docker-compose.local.yaml up -d
|
||||||
|
|
||||||
|
# Wait for services to start (30 seconds)
|
||||||
|
timeout 30
|
||||||
|
|
||||||
|
# Generate application key
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan key:generate
|
||||||
|
|
||||||
|
# Run migrations
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan migrate
|
||||||
|
|
||||||
|
# Seed database (optional)
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan db:seed
|
||||||
|
|
||||||
|
# Install frontend dependencies (if needed)
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Access Services
|
||||||
|
|
||||||
|
| Service | URL | Credentials |
|
||||||
|
|---------|-----|-------------|
|
||||||
|
| **Laravel App** | http://localhost:8080 | - |
|
||||||
|
| **Portainer** | http://localhost:9000 | Set on first visit |
|
||||||
|
| **pgAdmin** | http://localhost:5050 | admin@local.dev / admin |
|
||||||
|
| **Mailpit** | http://localhost:8025 | - |
|
||||||
|
| **PostgreSQL** | localhost:5433 | teren_user / local_password |
|
||||||
|
| **Redis** | localhost:6379 | - |
|
||||||
|
|
||||||
|
**Note:** PostgreSQL uses port 5433 to avoid conflicts with any local PostgreSQL installation.
|
||||||
|
|
||||||
|
## Common Commands
|
||||||
|
|
||||||
|
### Docker Compose Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start all services
|
||||||
|
docker compose -f docker-compose.local.yaml up -d
|
||||||
|
|
||||||
|
# Stop all services
|
||||||
|
docker compose -f docker-compose.local.yaml down
|
||||||
|
|
||||||
|
# View logs
|
||||||
|
docker compose -f docker-compose.local.yaml logs -f
|
||||||
|
|
||||||
|
# View specific service logs
|
||||||
|
docker compose -f docker-compose.local.yaml logs -f app
|
||||||
|
|
||||||
|
# Restart a service
|
||||||
|
docker compose -f docker-compose.local.yaml restart app
|
||||||
|
|
||||||
|
# Rebuild containers
|
||||||
|
docker compose -f docker-compose.local.yaml up -d --build
|
||||||
|
|
||||||
|
# Stop and remove everything (including volumes)
|
||||||
|
docker compose -f docker-compose.local.yaml down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
### Laravel Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run artisan commands
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan [command]
|
||||||
|
|
||||||
|
# Examples:
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan migrate
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan db:seed
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan cache:clear
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan config:clear
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan queue:work
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan test
|
||||||
|
|
||||||
|
# Access container shell
|
||||||
|
docker compose -f docker-compose.local.yaml exec app sh
|
||||||
|
|
||||||
|
# Run Composer commands
|
||||||
|
docker compose -f docker-compose.local.yaml exec app composer install
|
||||||
|
docker compose -f docker-compose.local.yaml exec app composer update
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Connect to PostgreSQL (from inside container)
|
||||||
|
docker compose -f docker-compose.local.yaml exec postgres psql -U teren_user -d teren_app
|
||||||
|
|
||||||
|
# Connect from Windows host
|
||||||
|
psql -h localhost -p 5433 -U teren_user -d teren_app
|
||||||
|
|
||||||
|
# Backup database
|
||||||
|
docker compose -f docker-compose.local.yaml exec postgres pg_dump -U teren_user teren_app > backup.sql
|
||||||
|
|
||||||
|
# Restore database
|
||||||
|
docker compose -f docker-compose.local.yaml exec -T postgres psql -U teren_user teren_app < backup.sql
|
||||||
|
|
||||||
|
# Reset database
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan migrate:fresh --seed
|
||||||
|
```
|
||||||
|
|
||||||
|
## pgAdmin Setup
|
||||||
|
|
||||||
|
1. Open http://localhost:5050
|
||||||
|
2. Login: `admin@local.dev` / `admin`
|
||||||
|
3. Add Server:
|
||||||
|
- **General Tab:**
|
||||||
|
- Name: `Teren Local`
|
||||||
|
- **Connection Tab:**
|
||||||
|
- Host: `postgres`
|
||||||
|
- Port: `5432`
|
||||||
|
- Database: `teren_app`
|
||||||
|
- Username: `teren_user`
|
||||||
|
- Passwo
|
||||||
|
|
||||||
|
**External Connection:** To connect from your Windows machine (e.g., DBeaver, pgAdmin desktop), use:
|
||||||
|
- Host: `localhost`
|
||||||
|
- Port: `5433` (not 5432)
|
||||||
|
- Database: `teren_app`
|
||||||
|
- Username: `teren_user`
|
||||||
|
- Password: `local_password`rd: `local_password`
|
||||||
|
4. Click Save
|
||||||
|
|
||||||
|
## Mailpit - Email Testing
|
||||||
|
|
||||||
|
All emails sent by the application are caught by Mailpit.
|
||||||
|
|
||||||
|
- Access: http://localhost:8025
|
||||||
|
- View all emails in the web interface
|
||||||
|
- Test email sending:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan tinker
|
||||||
|
# In tinker:
|
||||||
|
Mail::raw('Test email', function($msg) {
|
||||||
|
$msg->to('test@example.com')->subject('Test');
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Portainer Setup
|
||||||
|
|
||||||
|
1. Open http://localhost:9000
|
||||||
|
2. On first visit, create admin account
|
||||||
|
3. Select "Docker" environment
|
||||||
|
4. Click "Connect"
|
||||||
|
|
||||||
|
Use Portainer to:
|
||||||
|
- View and manage containers
|
||||||
|
- Check logs
|
||||||
|
- Execute commands in containers
|
||||||
|
- Monitor resource usage
|
||||||
|
|
||||||
|
## Development Workflow
|
||||||
|
|
||||||
|
### Frontend Development
|
||||||
|
|
||||||
|
The local setup supports live reloading:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run Vite dev server (outside Docker)
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# Or inside Docker
|
||||||
|
docker compose -f docker-compose.local.yaml exec app npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Access: http://localhost:8080
|
||||||
|
|
||||||
|
### Code Changes
|
||||||
|
|
||||||
|
All code changes are automatically reflected because the source code is mounted as a volume:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
volumes:
|
||||||
|
- ./:/var/www # Live code mounting
|
||||||
|
```
|
||||||
|
|
||||||
|
### Queue Workers
|
||||||
|
|
||||||
|
Queue workers are running via Supervisor inside the container. To restart:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Restart queue workers
|
||||||
|
docker compose -f docker-compose.local.yaml exec app supervisorctl restart all
|
||||||
|
|
||||||
|
# Check status
|
||||||
|
docker compose -f docker-compose.local.yaml exec app supervisorctl status
|
||||||
|
|
||||||
|
# View worker logs
|
||||||
|
docker compose -f docker-compose.local.yaml exec app tail -f storage/logs/worker.log
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Port Already in Use
|
||||||
|
|
||||||
|
If you get "port is already allocated" error:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Windows - Find process using port
|
||||||
|
netstat -ano | findstr :8080
|
||||||
|
|
||||||
|
# Kill process by PID
|
||||||
|
taskkill /PID <PID> /F
|
||||||
|
|
||||||
|
# Or change port in docker-compose.local.yaml
|
||||||
|
ports:
|
||||||
|
- "8081:80" # Change 8080 to 8081
|
||||||
|
```
|
||||||
|
|
||||||
|
### Container Won't Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check logs
|
||||||
|
docker compose -f docker-compose.local.yaml logs app
|
||||||
|
|
||||||
|
# Rebuild containers
|
||||||
|
docker compose -f docker-compose.local.yaml down
|
||||||
|
docker compose -f docker-compose.local.yaml up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Permission Errors (Linux/Mac)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Fix storage permissions
|
||||||
|
docker compose -f docker-compose.local.yaml exec app chown -R www:www /var/www/storage
|
||||||
|
docker compose -f docker-compose.local.yaml exec app chmod -R 775 /var/www/storage
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Connection Failed
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check if PostgreSQL is running
|
||||||
|
docker compose -f docker-compose.local.yaml ps postgres
|
||||||
|
|
||||||
|
# Check logs
|
||||||
|
docker compose -f docker-compose.local.yaml logs postgres
|
||||||
|
|
||||||
|
# Restart PostgreSQL
|
||||||
|
docker compose -f docker-compose.local.yaml restart postgres
|
||||||
|
```
|
||||||
|
|
||||||
|
### Clear All Data and Start Fresh
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Stop and remove everything
|
||||||
|
docker compose -f docker-compose.local.yaml down -v
|
||||||
|
|
||||||
|
# Remove images
|
||||||
|
docker compose -f docker-compose.local.yaml down --rmi all
|
||||||
|
|
||||||
|
# Start fresh
|
||||||
|
docker compose -f docker-compose.local.yaml up -d --build
|
||||||
|
|
||||||
|
# Re-initialize
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan key:generate
|
||||||
|
docker compose -f docker-compose.local.yaml exec app php artisan migrate:fresh --seed
|
||||||
|
```
|
||||||
|
|
||||||
|
## Performance Tips
|
||||||
|
|
||||||
|
### Windows Performance
|
||||||
|
|
||||||
|
If using WSL2 (recommended):
|
||||||
|
|
||||||
|
1. Clone repo inside WSL2 filesystem, not Windows filesystem
|
||||||
|
2. Use WSL2 terminal for commands
|
||||||
|
3. Enable WSL2 integration in Docker Desktop settings
|
||||||
|
|
||||||
|
### Mac Performance
|
||||||
|
|
||||||
|
1. Enable VirtioFS in Docker Desktop settings
|
||||||
|
2. Disable file watching if not needed
|
||||||
|
3. Use Docker volumes for vendor directories:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
volumes:
|
||||||
|
- ./:/var/www
|
||||||
|
- /var/www/vendor # Anonymous volume for vendor
|
||||||
|
- /var/www/node_modules # Anonymous volume for node_modules
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Production-Like Setup
|
||||||
|
|
||||||
|
To test the production VPN setup locally (advanced):
|
||||||
|
|
||||||
|
1. Enable WireGuard in `docker-compose.yaml.example`
|
||||||
|
2. Change all `10.13.13.1` bindings to `127.0.0.1`
|
||||||
|
3. Test SSL with self-signed certificates
|
||||||
|
|
||||||
|
## Differences from Production
|
||||||
|
|
||||||
|
| Feature | Local | Production |
|
||||||
|
|---------|-------|------------|
|
||||||
|
| **VPN** | No VPN | WireGuard required |
|
||||||
|
| **Port** | :8080 | :80/:443 |
|
||||||
|
| **SSL** | No SSL | Let's Encrypt |
|
||||||
|
| **Debug** | Enabled | Disabled |
|
||||||
|
| **Emails** | Mailpit | Real SMTP |
|
||||||
|
| **Logs** | Debug level | Error level |
|
||||||
|
| **Code** | Live mount | Built into image |
|
||||||
|
|
||||||
|
## Next Steps
|
||||||
|
|
||||||
|
After testing locally:
|
||||||
|
|
||||||
|
1. Review `docker-compose.yaml.example` for production
|
||||||
|
2. Follow `DEPLOYMENT_GUIDE.md` for VPS setup
|
||||||
|
3. Configure WireGuard VPN
|
||||||
|
4. Deploy to production
|
||||||
|
|
||||||
|
## Useful Resources
|
||||||
|
|
||||||
|
- [Docker Compose Documentation](https://docs.docker.com/compose/)
|
||||||
|
- [Laravel Docker Documentation](https://laravel.com/docs/deployment)
|
||||||
|
- [PostgreSQL Docker](https://hub.docker.com/_/postgres)
|
||||||
|
- [Mailpit Documentation](https://github.com/axllent/mailpit)
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# Quick Start: VPN-Only Access Setup
|
||||||
|
|
||||||
|
⚠️ **IMPORTANT:** This application is configured for VPN-ONLY access. It will NOT be publicly accessible.
|
||||||
|
|
||||||
|
## Quick Setup Steps
|
||||||
|
|
||||||
|
### 1. Install Docker (on VPS)
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://get.docker.com | sh
|
||||||
|
sudo usermod -aG docker $USER
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Clone & Configure
|
||||||
|
```bash
|
||||||
|
git clone YOUR_GITEA_REPO/Teren-app.git
|
||||||
|
cd Teren-app
|
||||||
|
cp docker-compose.yaml.example docker-compose.yaml
|
||||||
|
cp .env.production.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Edit Configuration
|
||||||
|
```bash
|
||||||
|
vim .env
|
||||||
|
```
|
||||||
|
|
||||||
|
**Required changes:**
|
||||||
|
- `WG_SERVERURL` = Your VPS public IP (e.g., `123.45.67.89`)
|
||||||
|
- `WG_UI_PASSWORD` = Strong password for WireGuard dashboard
|
||||||
|
- `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD` = Database credentials
|
||||||
|
- `PGADMIN_EMAIL`, `PGADMIN_PASSWORD` = pgAdmin credentials
|
||||||
|
|
||||||
|
### 4. Start WireGuard First
|
||||||
|
```bash
|
||||||
|
# Enable kernel module
|
||||||
|
sudo modprobe wireguard
|
||||||
|
|
||||||
|
# Start WireGuard
|
||||||
|
docker compose up -d wireguard
|
||||||
|
|
||||||
|
# Wait 10 seconds
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
# Check status
|
||||||
|
docker compose logs wireguard
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Setup VPN Client (on your laptop/desktop)
|
||||||
|
|
||||||
|
**Access WireGuard Dashboard:** `http://YOUR_VPS_IP:51821`
|
||||||
|
|
||||||
|
1. Login with password from step 3
|
||||||
|
2. Click "New Client"
|
||||||
|
3. Name it (e.g., "MyLaptop")
|
||||||
|
4. Download config or scan QR code
|
||||||
|
|
||||||
|
**Install WireGuard Client:**
|
||||||
|
- Windows: https://www.wireguard.com/install/
|
||||||
|
- macOS: App Store
|
||||||
|
- Linux: `sudo apt install wireguard`
|
||||||
|
- Mobile: App Store / Play Store
|
||||||
|
|
||||||
|
**Import config and CONNECT**
|
||||||
|
|
||||||
|
### 6. Verify VPN Works
|
||||||
|
```bash
|
||||||
|
# From your local machine (while connected to VPN)
|
||||||
|
ping 10.13.13.1
|
||||||
|
```
|
||||||
|
|
||||||
|
Should get responses ✅
|
||||||
|
|
||||||
|
### 7. Secure WireGuard Dashboard
|
||||||
|
|
||||||
|
Edit `docker-compose.yaml`:
|
||||||
|
```yaml
|
||||||
|
# Find wireguard service, change:
|
||||||
|
ports:
|
||||||
|
- "51821:51821/tcp"
|
||||||
|
# To:
|
||||||
|
ports:
|
||||||
|
- "10.13.13.1:51821:51821/tcp"
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose down
|
||||||
|
docker compose up -d wireguard
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8. Start All Services
|
||||||
|
```bash
|
||||||
|
# Make sure you're connected to VPN!
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9. Initialize Application
|
||||||
|
```bash
|
||||||
|
# Generate app key
|
||||||
|
docker compose exec app php artisan key:generate
|
||||||
|
|
||||||
|
# Run migrations
|
||||||
|
docker compose exec app php artisan migrate --force
|
||||||
|
|
||||||
|
# Cache config
|
||||||
|
docker compose exec app php artisan config:cache
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10. Access Your Services
|
||||||
|
|
||||||
|
**While connected to VPN:**
|
||||||
|
|
||||||
|
| Service | URL |
|
||||||
|
|---------|-----|
|
||||||
|
| **Laravel App** | http://10.13.13.1 |
|
||||||
|
| **Portainer** | http://10.13.13.1:9000 |
|
||||||
|
| **pgAdmin** | http://10.13.13.1:5050 |
|
||||||
|
| **WireGuard UI** | http://10.13.13.1:51821 |
|
||||||
|
|
||||||
|
## Firewall Configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ufw allow 22/tcp # SSH
|
||||||
|
sudo ufw allow 51820/udp # WireGuard VPN
|
||||||
|
sudo ufw enable
|
||||||
|
```
|
||||||
|
|
||||||
|
**That's it!** ✅
|
||||||
|
|
||||||
|
## Adding More VPN Clients
|
||||||
|
|
||||||
|
1. Connect to VPN
|
||||||
|
2. Open: `http://10.13.13.1:51821`
|
||||||
|
3. Click "New Client"
|
||||||
|
4. Download config
|
||||||
|
5. Import on new device
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
**Can't connect to VPN:**
|
||||||
|
```bash
|
||||||
|
docker compose logs wireguard
|
||||||
|
sudo ufw status
|
||||||
|
```
|
||||||
|
|
||||||
|
**Can't access app after VPN connection:**
|
||||||
|
```bash
|
||||||
|
ping 10.13.13.1
|
||||||
|
docker compose ps
|
||||||
|
docker compose logs nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
**Check which ports are exposed:**
|
||||||
|
```bash
|
||||||
|
docker compose ps
|
||||||
|
sudo netstat -tulpn | grep 10.13.13.1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Full Documentation
|
||||||
|
|
||||||
|
See `DEPLOYMENT_GUIDE.md` for complete setup instructions, SSL configuration, automated deployments, and troubleshooting.
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
# Reports Backend Rework Plan
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
Transform the current hardcoded report system into a flexible, database-driven architecture that allows dynamic report configuration without code changes.
|
||||||
|
|
||||||
|
## Current Architecture Analysis
|
||||||
|
|
||||||
|
### Existing Structure
|
||||||
|
- **Report Classes**: Individual PHP classes (`ActiveContractsReport`, `ActivitiesPerPeriodReport`, etc.)
|
||||||
|
- **Registry Pattern**: `ReportRegistry` stores report instances in memory
|
||||||
|
- **Service Provider**: `ReportServiceProvider` registers reports at boot time
|
||||||
|
- **Base Class**: `BaseEloquentReport` provides common pagination logic
|
||||||
|
- **Contract Interface**: `Report` interface defines required methods (`slug`, `name`, `description`, `inputs`, `columns`, `query`)
|
||||||
|
- **Controller**: `ReportController` handles index, show, data, export routes
|
||||||
|
|
||||||
|
### Current Features
|
||||||
|
1. **Report Definition**: Each report defines:
|
||||||
|
- Slug (unique identifier)
|
||||||
|
- Name & Description
|
||||||
|
- Input parameters (filters)
|
||||||
|
- Column definitions
|
||||||
|
- Eloquent query builder
|
||||||
|
2. **Filter Types**: `date`, `string`, `select:client`, etc.
|
||||||
|
3. **Export**: PDF and CSV export functionality
|
||||||
|
4. **Pagination**: Server-side pagination support
|
||||||
|
|
||||||
|
## Proposed New Architecture
|
||||||
|
|
||||||
|
### 1. Database Schema
|
||||||
|
|
||||||
|
#### `reports` Table
|
||||||
|
```sql
|
||||||
|
CREATE TABLE reports (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
slug VARCHAR(255) UNIQUE NOT NULL,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NULL,
|
||||||
|
category VARCHAR(100) NULL, -- e.g., 'contracts', 'activities', 'financial'
|
||||||
|
enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
order INT DEFAULT 0,
|
||||||
|
created_at TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP,
|
||||||
|
INDEX idx_slug (slug),
|
||||||
|
INDEX idx_enabled_order (enabled, order)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `report_entities` Table
|
||||||
|
Defines which database entities (models) the report queries.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE report_entities (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
report_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
model_class VARCHAR(255) NOT NULL, -- e.g., 'App\Models\Contract'
|
||||||
|
alias VARCHAR(50) NULL, -- table alias for joins
|
||||||
|
join_type ENUM('base', 'join', 'leftJoin', 'rightJoin') DEFAULT 'base',
|
||||||
|
join_first VARCHAR(100) NULL, -- first column for join
|
||||||
|
join_operator VARCHAR(10) NULL, -- =, !=, etc.
|
||||||
|
join_second VARCHAR(100) NULL, -- second column for join
|
||||||
|
order INT DEFAULT 0,
|
||||||
|
created_at TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP,
|
||||||
|
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
|
||||||
|
INDEX idx_report_order (report_id, order)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `report_columns` Table
|
||||||
|
Defines selectable columns and their presentation.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE report_columns (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
report_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
key VARCHAR(100) NOT NULL, -- column identifier
|
||||||
|
label VARCHAR(255) NOT NULL, -- display label
|
||||||
|
type VARCHAR(50) DEFAULT 'string', -- string, number, date, boolean, currency
|
||||||
|
expression TEXT NOT NULL, -- SQL expression or column path
|
||||||
|
sortable BOOLEAN DEFAULT TRUE,
|
||||||
|
visible BOOLEAN DEFAULT TRUE,
|
||||||
|
order INT DEFAULT 0,
|
||||||
|
format_options JSON NULL, -- { "decimals": 2, "prefix": "$" }
|
||||||
|
created_at TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP,
|
||||||
|
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
|
||||||
|
INDEX idx_report_order (report_id, order)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `report_filters` Table
|
||||||
|
Defines available filter parameters.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE report_filters (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
report_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
key VARCHAR(100) NOT NULL, -- filter identifier
|
||||||
|
label VARCHAR(255) NOT NULL,
|
||||||
|
type VARCHAR(50) NOT NULL, -- date, string, select, multiselect, number, boolean
|
||||||
|
nullable BOOLEAN DEFAULT TRUE,
|
||||||
|
default_value TEXT NULL,
|
||||||
|
options JSON NULL, -- For select/multiselect: [{"label":"...", "value":"..."}]
|
||||||
|
data_source VARCHAR(255) NULL, -- e.g., 'clients', 'segments' for dynamic selects
|
||||||
|
order INT DEFAULT 0,
|
||||||
|
created_at TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP,
|
||||||
|
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
|
||||||
|
INDEX idx_report_order (report_id, order)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `report_conditions` Table
|
||||||
|
Defines WHERE clause conditions (rules) for filtering data.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE report_conditions (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
report_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
column VARCHAR(255) NOT NULL, -- e.g., 'contracts.start_date'
|
||||||
|
operator VARCHAR(50) NOT NULL, -- =, !=, >, <, >=, <=, LIKE, IN, BETWEEN, IS NULL, etc.
|
||||||
|
value_type VARCHAR(50) NOT NULL, -- static, filter, expression
|
||||||
|
value TEXT NULL, -- static value or expression
|
||||||
|
filter_key VARCHAR(100) NULL, -- references report_filters.key
|
||||||
|
logical_operator ENUM('AND', 'OR') DEFAULT 'AND',
|
||||||
|
group_id INT NULL, -- for grouping conditions (AND within group, OR between groups)
|
||||||
|
order INT DEFAULT 0,
|
||||||
|
enabled BOOLEAN DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP,
|
||||||
|
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
|
||||||
|
INDEX idx_report_group (report_id, group_id, order)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `report_orders` Table
|
||||||
|
Defines default ORDER BY clauses.
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE report_orders (
|
||||||
|
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
report_id BIGINT UNSIGNED NOT NULL,
|
||||||
|
column VARCHAR(255) NOT NULL,
|
||||||
|
direction ENUM('ASC', 'DESC') DEFAULT 'ASC',
|
||||||
|
order INT DEFAULT 0,
|
||||||
|
created_at TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP,
|
||||||
|
FOREIGN KEY (report_id) REFERENCES reports(id) ON DELETE CASCADE,
|
||||||
|
INDEX idx_report_order (report_id, order)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Model Structure
|
||||||
|
|
||||||
|
#### Report Model
|
||||||
|
```php
|
||||||
|
class Report extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = ['slug', 'name', 'description', 'category', 'enabled', 'order'];
|
||||||
|
protected $casts = ['enabled' => 'boolean'];
|
||||||
|
|
||||||
|
public function entities(): HasMany { return $this->hasMany(ReportEntity::class); }
|
||||||
|
public function columns(): HasMany { return $this->hasMany(ReportColumn::class); }
|
||||||
|
public function filters(): HasMany { return $this->hasMany(ReportFilter::class); }
|
||||||
|
public function conditions(): HasMany { return $this->hasMany(ReportCondition::class); }
|
||||||
|
public function orders(): HasMany { return $this->hasMany(ReportOrder::class); }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Query Builder Service
|
||||||
|
|
||||||
|
Create `ReportQueryBuilder` service to dynamically construct queries:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class ReportQueryBuilder
|
||||||
|
{
|
||||||
|
public function build(Report $report, array $filters = []): Builder
|
||||||
|
{
|
||||||
|
// 1. Start with base model query
|
||||||
|
// 2. Apply joins from report_entities
|
||||||
|
// 3. Select columns from report_columns
|
||||||
|
// 4. Apply conditions from report_conditions
|
||||||
|
// 5. Apply filter values to parameterized conditions
|
||||||
|
// 6. Apply ORDER BY from report_orders
|
||||||
|
// 7. Return Builder instance
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Backward Compatibility Layer
|
||||||
|
|
||||||
|
Keep existing Report classes but load from database:
|
||||||
|
|
||||||
|
```php
|
||||||
|
class DatabaseReport extends BaseEloquentReport implements Report
|
||||||
|
{
|
||||||
|
public function __construct(protected Report $dbReport) {}
|
||||||
|
|
||||||
|
public function slug(): string { return $this->dbReport->slug; }
|
||||||
|
public function name(): string { return $this->dbReport->name; }
|
||||||
|
public function description(): ?string { return $this->dbReport->description; }
|
||||||
|
|
||||||
|
public function inputs(): array {
|
||||||
|
return $this->dbReport->filters()
|
||||||
|
->orderBy('order')
|
||||||
|
->get()
|
||||||
|
->map(fn($f) => [
|
||||||
|
'key' => $f->key,
|
||||||
|
'type' => $f->type,
|
||||||
|
'label' => $f->label,
|
||||||
|
'nullable' => $f->nullable,
|
||||||
|
'default' => $f->default_value,
|
||||||
|
'options' => $f->options,
|
||||||
|
])
|
||||||
|
->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function columns(): array {
|
||||||
|
return $this->dbReport->columns()
|
||||||
|
->where('visible', true)
|
||||||
|
->orderBy('order')
|
||||||
|
->get()
|
||||||
|
->map(fn($c) => ['key' => $c->key, 'label' => $c->label])
|
||||||
|
->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function query(array $filters): Builder {
|
||||||
|
return app(ReportQueryBuilder::class)->build($this->dbReport, $filters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Migration Strategy
|
||||||
|
|
||||||
|
#### Phase 1: Database Setup
|
||||||
|
1. Create migrations for all new tables
|
||||||
|
2. Create models with relationships
|
||||||
|
3. Create seeders to migrate existing hardcoded reports
|
||||||
|
|
||||||
|
#### Phase 2: Service Layer
|
||||||
|
1. Build `ReportQueryBuilder` service
|
||||||
|
2. Build `DatabaseReport` adapter class
|
||||||
|
3. Update `ReportRegistry` to load from database
|
||||||
|
4. Create report management CRUD (admin UI)
|
||||||
|
|
||||||
|
#### Phase 3: Testing & Validation
|
||||||
|
1. Unit tests for query builder
|
||||||
|
2. Integration tests comparing old vs new results
|
||||||
|
3. Performance benchmarks
|
||||||
|
4. Export functionality validation
|
||||||
|
|
||||||
|
#### Phase 4: Migration Seeder
|
||||||
|
1. Create seeder that converts each hardcoded report into database records
|
||||||
|
2. Example for `ActiveContractsReport`:
|
||||||
|
```php
|
||||||
|
$report = Report::create([
|
||||||
|
'slug' => 'active-contracts',
|
||||||
|
'name' => 'Aktivne pogodbe',
|
||||||
|
'description' => 'Pogodbe, ki so aktivne...',
|
||||||
|
'enabled' => true,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Add entities (joins)
|
||||||
|
$report->entities()->create([
|
||||||
|
'model_class' => 'App\Models\Contract',
|
||||||
|
'join_type' => 'base',
|
||||||
|
'order' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->entities()->create([
|
||||||
|
'model_class' => 'App\Models\ClientCase',
|
||||||
|
'join_type' => 'join',
|
||||||
|
'join_first' => 'contracts.client_case_id',
|
||||||
|
'join_operator' => '=',
|
||||||
|
'join_second' => 'client_cases.id',
|
||||||
|
'order' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Add columns
|
||||||
|
$report->columns()->create([
|
||||||
|
'key' => 'contract_reference',
|
||||||
|
'label' => 'Pogodba',
|
||||||
|
'expression' => 'contracts.reference',
|
||||||
|
'order' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Add filters
|
||||||
|
$report->filters()->create([
|
||||||
|
'key' => 'client_uuid',
|
||||||
|
'label' => 'Stranka',
|
||||||
|
'type' => 'select',
|
||||||
|
'data_source' => 'clients',
|
||||||
|
'nullable' => true,
|
||||||
|
'order' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Add conditions
|
||||||
|
$report->conditions()->create([
|
||||||
|
'column' => 'contracts.start_date',
|
||||||
|
'operator' => '<=',
|
||||||
|
'value_type' => 'expression',
|
||||||
|
'value' => 'CURRENT_DATE',
|
||||||
|
'group_id' => 1,
|
||||||
|
'order' => 0,
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Phase 5: Remove Old Report System
|
||||||
|
Once the new database-driven system is validated and working:
|
||||||
|
|
||||||
|
1. **Delete Hardcoded Report Classes**:
|
||||||
|
- Remove `app/Reports/ActiveContractsReport.php`
|
||||||
|
- Remove `app/Reports/ActivitiesPerPeriodReport.php`
|
||||||
|
- Remove `app/Reports/ActionsDecisionsCountReport.php`
|
||||||
|
- Remove `app/Reports/DecisionsCountReport.php`
|
||||||
|
- Remove `app/Reports/FieldJobsCompletedReport.php`
|
||||||
|
- Remove `app/Reports/SegmentActivityCountsReport.php`
|
||||||
|
|
||||||
|
2. **Remove Base Classes/Interfaces** (if no longer needed):
|
||||||
|
- Remove `app/Reports/BaseEloquentReport.php`
|
||||||
|
- Remove `app/Reports/Contracts/Report.php` interface
|
||||||
|
|
||||||
|
3. **Remove/Update Service Provider**:
|
||||||
|
- Remove `app/Providers/ReportServiceProvider.php`
|
||||||
|
- Or update it to only load reports from database
|
||||||
|
|
||||||
|
4. **Update ReportRegistry**:
|
||||||
|
- Modify to load from database instead of manual registration
|
||||||
|
- Remove all hardcoded `register()` calls
|
||||||
|
|
||||||
|
5. **Clean Up Config**:
|
||||||
|
- Remove any report-specific configuration files if they exist
|
||||||
|
- Update `bootstrap/providers.php` to remove ReportServiceProvider
|
||||||
|
|
||||||
|
6. **Documentation Cleanup**:
|
||||||
|
- Update any documentation referencing old report classes
|
||||||
|
- Add migration guide for future report creation
|
||||||
|
|
||||||
|
### 6. Admin UI for Report Management
|
||||||
|
|
||||||
|
Create CRUD interface at `Settings/Reports/*`:
|
||||||
|
- **Index**: List all reports with enable/disable toggle
|
||||||
|
- **Create**: Wizard-style form for building new reports
|
||||||
|
- **Edit**: Visual query builder interface
|
||||||
|
- **Test**: Preview report results
|
||||||
|
- **Clone**: Duplicate existing report as starting point
|
||||||
|
|
||||||
|
### 7. Advanced Features (Future)
|
||||||
|
|
||||||
|
1. **Calculated Fields**: Allow expressions like `(column_a + column_b) / 2`
|
||||||
|
2. **Aggregations**: Support SUM, AVG, COUNT, MIN, MAX
|
||||||
|
3. **Subqueries**: Define subquery relationships
|
||||||
|
4. **Report Templates**: Predefined report structures
|
||||||
|
5. **Scheduled Reports**: Email reports on schedule
|
||||||
|
6. **Report Sharing**: Share reports with specific users/roles
|
||||||
|
7. **Version History**: Track report definition changes
|
||||||
|
8. **Report Permissions**: Control who can view/edit reports
|
||||||
|
|
||||||
|
## Benefits
|
||||||
|
|
||||||
|
1. **No Code Changes**: Add/modify reports through UI
|
||||||
|
2. **Flexibility**: Non-developers can create reports
|
||||||
|
3. **Consistency**: All reports follow same structure
|
||||||
|
4. **Maintainability**: Centralized report logic
|
||||||
|
5. **Reusability**: Share entities, filters, conditions
|
||||||
|
6. **Version Control**: Track changes to report definitions
|
||||||
|
7. **Performance**: Optimize query builder once
|
||||||
|
8. **Export**: Works with any report automatically
|
||||||
|
|
||||||
|
## Risks & Considerations
|
||||||
|
|
||||||
|
1. **Complexity**: Query builder must handle diverse SQL patterns
|
||||||
|
2. **Performance**: Dynamic query building overhead
|
||||||
|
3. **Security**: SQL injection risks with user input
|
||||||
|
4. **Learning Curve**: Team needs to understand new system
|
||||||
|
5. **Testing**: Comprehensive test suite required
|
||||||
|
6. **Migration**: Convert all existing reports correctly
|
||||||
|
7. **Edge Cases**: Complex queries may be difficult to represent
|
||||||
|
|
||||||
|
## Timeline Estimate
|
||||||
|
|
||||||
|
- **Phase 1 (Database)**: 2-3 days
|
||||||
|
- **Phase 2 (Services)**: 4-5 days
|
||||||
|
- **Phase 3 (Testing)**: 2-3 days
|
||||||
|
- **Phase 4 (Migration)**: 1-2 days
|
||||||
|
- **Phase 5 (Cleanup)**: 1 day
|
||||||
|
- **Admin UI**: 3-4 days
|
||||||
|
- **Total**: 13-18 days
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
1. ✅ All existing reports work identically
|
||||||
|
2. ✅ New reports can be created via UI
|
||||||
|
3. ✅ Export functionality preserved
|
||||||
|
4. ✅ Performance within 10% of current
|
||||||
|
5. ✅ Zero SQL injection vulnerabilities
|
||||||
|
6. ✅ Comprehensive test coverage (>80%)
|
||||||
|
7. ✅ Documentation complete
|
||||||
@@ -0,0 +1,528 @@
|
|||||||
|
# Reports Frontend Rework Plan
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
This plan outlines the modernization of Reports frontend pages (`Index.vue` and `Show.vue`) using shadcn-vue components and AppCard containers, following the same patterns established in the Settings pages rework.
|
||||||
|
|
||||||
|
## Current State Analysis
|
||||||
|
|
||||||
|
### Reports/Index.vue (30 lines)
|
||||||
|
**Current Implementation:**
|
||||||
|
- Simple grid layout with native divs
|
||||||
|
- Report cards: `border rounded-lg p-4 bg-white shadow-sm hover:shadow-md`
|
||||||
|
- Grid: `md:grid-cols-2 lg:grid-cols-3`
|
||||||
|
- Each card shows: name (h2), description (p), Link to report
|
||||||
|
- **No shadcn-vue components used**
|
||||||
|
|
||||||
|
**Identified Issues:**
|
||||||
|
- Native HTML/Tailwind instead of shadcn-vue Card
|
||||||
|
- Inconsistent with Settings pages styling
|
||||||
|
- No icons for visual interest
|
||||||
|
- Basic hover effects only
|
||||||
|
|
||||||
|
### Reports/Show.vue (314 lines)
|
||||||
|
**Current Implementation:**
|
||||||
|
- Complex page with filters, export buttons, and data table
|
||||||
|
- Header section: title, description, export buttons (lines 190-196)
|
||||||
|
- Buttons: `px-3 py-2 rounded bg-gray-200 hover:bg-gray-300`
|
||||||
|
- Filter section: grid layout `md:grid-cols-4` (lines 218-270)
|
||||||
|
- Native inputs: `border rounded px-2 py-1`
|
||||||
|
- Native selects: `border rounded px-2 py-1`
|
||||||
|
- DatePicker component (already working)
|
||||||
|
- Filter buttons: Apply (`bg-indigo-600`) and Reset (`bg-gray-100`)
|
||||||
|
- Data table: DataTableServer component (lines 285-300)
|
||||||
|
- Formatting functions: formatNumberEU, formatDateEU, formatDateTimeEU, formatCell
|
||||||
|
|
||||||
|
**Identified Issues:**
|
||||||
|
- No Card containers for sections
|
||||||
|
- Native buttons instead of shadcn Button
|
||||||
|
- Native input/select elements instead of shadcn Input/Select
|
||||||
|
- No visual separation between sections
|
||||||
|
- Filter section could be extracted to partial
|
||||||
|
|
||||||
|
## Target Architecture
|
||||||
|
|
||||||
|
### Pattern Reference from Settings Pages
|
||||||
|
|
||||||
|
**Settings/Index.vue Pattern:**
|
||||||
|
```vue
|
||||||
|
<Card class="hover:shadow-lg transition-shadow">
|
||||||
|
<CardHeader>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<component :is="icon" class="h-5 w-5 text-muted-foreground" />
|
||||||
|
<CardTitle>Title</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>Description</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button variant="ghost">Action →</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Settings/Archive/Index.vue Pattern:**
|
||||||
|
- Uses AppCard for main container
|
||||||
|
- Extracted partials: ArchiveRuleCard, CreateRuleForm, EditRuleForm
|
||||||
|
- Alert components for warnings
|
||||||
|
- Badge components for status indicators
|
||||||
|
|
||||||
|
## Implementation Plan
|
||||||
|
|
||||||
|
### Phase 1: Reports/Index.vue Rework (Simple)
|
||||||
|
|
||||||
|
**Goal:** Replace native divs with shadcn-vue Card components, add icons
|
||||||
|
|
||||||
|
**Changes:**
|
||||||
|
1. **Import shadcn-vue components:**
|
||||||
|
```js
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/ui/card";
|
||||||
|
import { Button } from "@/Components/ui/button";
|
||||||
|
import { BarChart3, FileText, Activity, Users, TrendingUp, Calendar } from "lucide-vue-next";
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Add icon mapping for reports:**
|
||||||
|
```js
|
||||||
|
const reportIcons = {
|
||||||
|
'contracts': FileText,
|
||||||
|
'field': TrendingUp,
|
||||||
|
'activities': Activity,
|
||||||
|
// fallback icon
|
||||||
|
default: BarChart3,
|
||||||
|
};
|
||||||
|
|
||||||
|
function getReportIcon(category) {
|
||||||
|
return reportIcons[category] || reportIcons.default;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Replace report card structure:**
|
||||||
|
- Remove native `<div class="border rounded-lg p-4 bg-white shadow-sm hover:shadow-md">`
|
||||||
|
- Use `<Card class="hover:shadow-lg transition-shadow cursor-pointer">`
|
||||||
|
- Structure:
|
||||||
|
```vue
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<component :is="getReportIcon(report.category)" class="h-5 w-5 text-muted-foreground" />
|
||||||
|
<CardTitle>{{ report.name }}</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>{{ report.description }}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Link :href="route('reports.show', report.slug)">
|
||||||
|
<Button variant="ghost" size="sm" class="w-full justify-start">
|
||||||
|
Odpri →
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Update page header:**
|
||||||
|
- Wrap in proper container with consistent spacing
|
||||||
|
- Match Settings/Index.vue header style
|
||||||
|
|
||||||
|
**Estimated Changes:**
|
||||||
|
- Lines: 30 → ~65 lines (with imports and icon logic)
|
||||||
|
- Files modified: 1 (Index.vue)
|
||||||
|
- Files created: 0
|
||||||
|
|
||||||
|
**Risk Level:** Low (simple page, straightforward replacement)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 2: Reports/Show.vue Rework - Structure (Medium)
|
||||||
|
|
||||||
|
**Goal:** Add Card containers for sections, replace native buttons
|
||||||
|
|
||||||
|
**Changes:**
|
||||||
|
|
||||||
|
1. **Import shadcn-vue components:**
|
||||||
|
```js
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/Components/ui/card";
|
||||||
|
import { Button } from "@/Components/ui/button";
|
||||||
|
import { Input } from "@/Components/ui/input";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
|
||||||
|
import { Label } from "@/Components/ui/label";
|
||||||
|
import { Badge } from "@/Components/ui/badge";
|
||||||
|
import { Separator } from "@/Components/ui/separator";
|
||||||
|
import { Download, Filter, RotateCcw } from "lucide-vue-next";
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Wrap header + export buttons in Card:**
|
||||||
|
```vue
|
||||||
|
<Card class="mb-6">
|
||||||
|
<CardHeader>
|
||||||
|
<div class="flex items-start justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle>{{ name }}</CardTitle>
|
||||||
|
<CardDescription v-if="description">{{ description }}</CardDescription>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button variant="outline" size="sm" @click="exportFile('csv')">
|
||||||
|
<Download class="mr-2 h-4 w-4" />
|
||||||
|
CSV
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" @click="exportFile('pdf')">
|
||||||
|
<Download class="mr-2 h-4 w-4" />
|
||||||
|
PDF
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" @click="exportFile('xlsx')">
|
||||||
|
<Download class="mr-2 h-4 w-4" />
|
||||||
|
Excel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Wrap filters in Card:**
|
||||||
|
```vue
|
||||||
|
<Card class="mb-6">
|
||||||
|
<CardHeader>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Filter class="h-5 w-5 text-muted-foreground" />
|
||||||
|
<CardTitle>Filtri</CardTitle>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<!-- Filter grid here -->
|
||||||
|
<div class="grid gap-4 md:grid-cols-4">
|
||||||
|
<!-- Filter inputs -->
|
||||||
|
</div>
|
||||||
|
<Separator class="my-4" />
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button @click="applyFilters">
|
||||||
|
<Filter class="mr-2 h-4 w-4" />
|
||||||
|
Prikaži
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" @click="resetFilters">
|
||||||
|
<RotateCcw class="mr-2 h-4 w-4" />
|
||||||
|
Ponastavi
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Wrap DataTableServer in Card:**
|
||||||
|
```vue
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Rezultati</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Skupaj {{ meta?.total || 0 }} {{ meta?.total === 1 ? 'rezultat' : 'rezultatov' }}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<DataTableServer
|
||||||
|
<!-- props -->
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **Replace all native buttons with shadcn Button:**
|
||||||
|
- Export buttons: `variant="outline" size="sm"`
|
||||||
|
- Apply filter button: default variant
|
||||||
|
- Reset button: `variant="outline"`
|
||||||
|
|
||||||
|
**Estimated Changes:**
|
||||||
|
- Lines: 314 → ~350 lines (with imports and Card wrappers)
|
||||||
|
- Files modified: 1 (Show.vue)
|
||||||
|
- Files created: 0
|
||||||
|
- **Keep formatting functions unchanged** (working correctly)
|
||||||
|
|
||||||
|
**Risk Level:** Low-Medium (more complex but no logic changes)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 3: Reports/Show.vue - Replace Native Inputs (Medium)
|
||||||
|
|
||||||
|
**Goal:** Replace native input/select elements with shadcn-vue components
|
||||||
|
|
||||||
|
**Changes:**
|
||||||
|
|
||||||
|
1. **Replace date inputs:**
|
||||||
|
```vue
|
||||||
|
<!-- Keep DatePicker as-is (already working) -->
|
||||||
|
<div class="space-y-2">
|
||||||
|
<Label>{{ inp.label || inp.key }}</Label>
|
||||||
|
<DatePicker
|
||||||
|
v-model="filters[inp.key]"
|
||||||
|
format="dd.MM.yyyy"
|
||||||
|
placeholder="Izberi datum"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Replace text/number inputs:**
|
||||||
|
```vue
|
||||||
|
<div class="space-y-2">
|
||||||
|
<Label>{{ inp.label || inp.key }}</Label>
|
||||||
|
<Input
|
||||||
|
v-model="filters[inp.key]"
|
||||||
|
:type="inp.type === 'integer' ? 'number' : 'text'"
|
||||||
|
placeholder="Vnesi vrednost"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Replace select inputs (user/client):**
|
||||||
|
```vue
|
||||||
|
<div class="space-y-2">
|
||||||
|
<Label>{{ inp.label || inp.key }}</Label>
|
||||||
|
<Select v-model="filters[inp.key]">
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="— brez —" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem :value="null">— brez —</SelectItem>
|
||||||
|
<SelectItem v-for="u in userOptions" :key="u.id" :value="u.id">
|
||||||
|
{{ u.name }}
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<div v-if="userLoading" class="text-xs text-muted-foreground">Nalagam…</div>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Update filter grid layout:**
|
||||||
|
- Change from `md:grid-cols-4` to `md:grid-cols-2 lg:grid-cols-4`
|
||||||
|
- Use `space-y-2` for label/input spacing
|
||||||
|
- Consistent gap: `gap-4`
|
||||||
|
|
||||||
|
**Estimated Changes:**
|
||||||
|
- Lines: ~350 → ~380 lines (shadcn Input/Select have more markup)
|
||||||
|
- Files modified: 1 (Show.vue)
|
||||||
|
- Files created: 0
|
||||||
|
|
||||||
|
**Risk Level:** Medium (v-model binding changes, test thoroughly)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 4: Optional - Extract Filter Section Partial (Optional)
|
||||||
|
|
||||||
|
**Goal:** Reduce Show.vue complexity by extracting filter logic
|
||||||
|
|
||||||
|
**Decision Criteria:**
|
||||||
|
- If filter section exceeds ~80 lines → extract to partial
|
||||||
|
- If multiple filter types need separate handling → extract
|
||||||
|
|
||||||
|
**Potential Partial Structure:**
|
||||||
|
```
|
||||||
|
resources/js/Pages/Reports/Partials/
|
||||||
|
FilterSection.vue
|
||||||
|
```
|
||||||
|
|
||||||
|
**FilterSection.vue:**
|
||||||
|
- Props: `inputs`, `filters` (reactive object), `userOptions`, `clientOptions`, `loading states`
|
||||||
|
- Emits: `@apply`, `@reset`
|
||||||
|
- Contains: entire filter grid + buttons
|
||||||
|
|
||||||
|
**Benefits:**
|
||||||
|
- Show.vue reduced from ~380 lines to ~300 lines
|
||||||
|
- Filter logic isolated and reusable
|
||||||
|
- Easier to maintain filter types
|
||||||
|
|
||||||
|
**Risks:**
|
||||||
|
- Adds complexity with props/emits
|
||||||
|
- Might not be worth it if filter logic is simple
|
||||||
|
|
||||||
|
**Recommendation:** Evaluate after Phase 3 completion. If filter section is clean and under 80 lines, skip this phase.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Component Inventory
|
||||||
|
|
||||||
|
### shadcn-vue Components Needed
|
||||||
|
|
||||||
|
**Already Installed (verify):**
|
||||||
|
- Card, CardHeader, CardTitle, CardDescription, CardContent
|
||||||
|
- Button
|
||||||
|
- Input
|
||||||
|
- Select, SelectTrigger, SelectValue, SelectContent, SelectItem
|
||||||
|
- Label
|
||||||
|
- Badge
|
||||||
|
- Separator
|
||||||
|
|
||||||
|
**Need to Check:**
|
||||||
|
- lucide-vue-next icons (Download, Filter, RotateCcw, BarChart3, FileText, Activity, TrendingUp, Calendar)
|
||||||
|
|
||||||
|
### Custom Components
|
||||||
|
- AppCard (if needed for consistency)
|
||||||
|
- DatePicker (already working, keep as-is)
|
||||||
|
- DataTableServer (keep as-is)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing Checklist
|
||||||
|
|
||||||
|
### Reports/Index.vue Testing:
|
||||||
|
- [ ] Cards display with correct icons
|
||||||
|
- [ ] Card hover effects work
|
||||||
|
- [ ] Links navigate to correct report
|
||||||
|
- [ ] Grid layout responsive (2 cols MD, 3 cols LG)
|
||||||
|
- [ ] Icons match report categories
|
||||||
|
|
||||||
|
### Reports/Show.vue Testing:
|
||||||
|
- [ ] Header Card displays title, description, export buttons
|
||||||
|
- [ ] Export buttons work (CSV, PDF, Excel)
|
||||||
|
- [ ] Filter Card displays all filter inputs correctly
|
||||||
|
- [ ] Date filters use DatePicker component
|
||||||
|
- [ ] User/Client selects load options async
|
||||||
|
- [ ] Apply filters button triggers report refresh
|
||||||
|
- [ ] Reset button clears all filters
|
||||||
|
- [ ] DataTableServer Card displays results
|
||||||
|
- [ ] Formatting functions work (dates, numbers, currencies)
|
||||||
|
- [ ] Pagination works
|
||||||
|
- [ ] All 6 reports render correctly:
|
||||||
|
- [ ] active-contracts
|
||||||
|
- [ ] field-jobs-completed
|
||||||
|
- [ ] decisions-counts
|
||||||
|
- [ ] segment-activity-counts
|
||||||
|
- [ ] actions-decisions-counts
|
||||||
|
- [ ] activities-per-period
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Order
|
||||||
|
|
||||||
|
### Step 1: Reports/Index.vue (30 min)
|
||||||
|
1. Import shadcn-vue components + icons
|
||||||
|
2. Add icon mapping function
|
||||||
|
3. Replace native divs with Card structure
|
||||||
|
4. Test navigation and layout
|
||||||
|
5. Verify responsive grid
|
||||||
|
|
||||||
|
### Step 2: Reports/Show.vue - Structure (45 min)
|
||||||
|
1. Import shadcn-vue components + icons
|
||||||
|
2. Wrap header + exports in Card
|
||||||
|
3. Wrap filters in Card
|
||||||
|
4. Wrap DataTableServer in Card
|
||||||
|
5. Replace all native buttons
|
||||||
|
6. Test all 6 reports
|
||||||
|
|
||||||
|
### Step 3: Reports/Show.vue - Inputs (60 min)
|
||||||
|
1. Replace text/number inputs with shadcn Input
|
||||||
|
2. Replace select inputs with shadcn Select
|
||||||
|
3. Add Label components
|
||||||
|
4. Test v-model bindings
|
||||||
|
5. Test async user/client loading
|
||||||
|
6. Test filter apply/reset
|
||||||
|
7. Verify all filter types work
|
||||||
|
|
||||||
|
### Step 4: Optional Partial Extraction (30 min, if needed)
|
||||||
|
1. Create FilterSection.vue partial
|
||||||
|
2. Move filter logic to partial
|
||||||
|
3. Set up props/emits
|
||||||
|
4. Test with all reports
|
||||||
|
|
||||||
|
### Step 5: Final Testing (30 min)
|
||||||
|
1. Test complete workflow (Index → Show → Filters → Export)
|
||||||
|
2. Verify all 6 reports
|
||||||
|
3. Test responsive layouts (mobile, tablet, desktop)
|
||||||
|
4. Check formatting consistency
|
||||||
|
5. Verify no regressions
|
||||||
|
|
||||||
|
**Total Estimated Time:** 2.5 - 3.5 hours
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risk Assessment
|
||||||
|
|
||||||
|
### Low Risk:
|
||||||
|
- Index.vue rework (simple structure, straightforward replacement)
|
||||||
|
- Adding Card containers to Show.vue
|
||||||
|
- Replacing native buttons with shadcn Button
|
||||||
|
|
||||||
|
### Medium Risk:
|
||||||
|
- Replacing native inputs with shadcn Input/Select
|
||||||
|
- v-model bindings might need adjustments
|
||||||
|
- Async select loading needs testing
|
||||||
|
- Number input behavior might differ
|
||||||
|
|
||||||
|
### Mitigation Strategies:
|
||||||
|
1. Test each phase incrementally
|
||||||
|
2. Keep formatting functions unchanged (already working)
|
||||||
|
3. Test v-model bindings immediately after input replacement
|
||||||
|
4. Verify async loading with console logs
|
||||||
|
5. Test all 6 reports after each phase
|
||||||
|
6. Keep git commits small and atomic
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
### Functional Requirements:
|
||||||
|
✅ All reports navigate from Index page
|
||||||
|
✅ All filters work correctly (date, text, number, user select, client select)
|
||||||
|
✅ Apply filters refreshes report data
|
||||||
|
✅ Reset filters clears all inputs
|
||||||
|
✅ Export buttons generate CSV/PDF/Excel files
|
||||||
|
✅ DataTableServer displays results correctly
|
||||||
|
✅ Pagination works
|
||||||
|
✅ Formatting functions work (dates, numbers)
|
||||||
|
|
||||||
|
### Visual Requirements:
|
||||||
|
✅ Consistent Card-based layout
|
||||||
|
✅ shadcn-vue components throughout
|
||||||
|
✅ Icons for visual interest
|
||||||
|
✅ Hover effects on cards
|
||||||
|
✅ Proper spacing and alignment
|
||||||
|
✅ Responsive layout (mobile, tablet, desktop)
|
||||||
|
✅ Matches Settings pages style
|
||||||
|
|
||||||
|
### Code Quality:
|
||||||
|
✅ No code duplication
|
||||||
|
✅ Clean component imports
|
||||||
|
✅ Consistent naming conventions
|
||||||
|
✅ Proper TypeScript/Vue 3 patterns
|
||||||
|
✅ Formatting functions unchanged
|
||||||
|
✅ No regressions in functionality
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- **DatePicker component:** Already working, imported correctly, no changes needed
|
||||||
|
- **Formatting functions:** Keep unchanged (formatNumberEU, formatDateEU, formatDateTimeEU, formatCell)
|
||||||
|
- **DataTableServer:** Keep as-is, already working well
|
||||||
|
- **Async loading:** User/client select loading works, just needs shadcn Select wrapper
|
||||||
|
- **Pattern consistency:** Follow Settings/Index.vue and Settings/Archive/Index.vue patterns
|
||||||
|
- **Icon usage:** Add icons to Index.vue for visual interest, use lucide-vue-next
|
||||||
|
- **Button variants:** Use `variant="outline"` for secondary actions, default for primary
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Post-Implementation
|
||||||
|
|
||||||
|
After completing all phases:
|
||||||
|
|
||||||
|
1. **Documentation:**
|
||||||
|
- Update this document with actual implementation notes
|
||||||
|
- Document any deviations from plan
|
||||||
|
- Note any unexpected issues
|
||||||
|
|
||||||
|
2. **Code Review:**
|
||||||
|
- Check for consistent component usage
|
||||||
|
- Verify no native HTML/CSS buttons/inputs remain
|
||||||
|
- Ensure proper import structure
|
||||||
|
|
||||||
|
3. **User Feedback:**
|
||||||
|
- Test with actual users
|
||||||
|
- Gather feedback on UI improvements
|
||||||
|
- Note any requested adjustments
|
||||||
|
|
||||||
|
4. **Performance:**
|
||||||
|
- Verify no performance regressions
|
||||||
|
- Check bundle size impact
|
||||||
|
- Monitor async loading times
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Conclusion
|
||||||
|
|
||||||
|
This plan provides a structured approach to modernizing the Reports frontend pages using shadcn-vue components. The phased approach allows for incremental testing and reduces risk. The estimated total time is 2.5-3.5 hours, with low to medium risk level.
|
||||||
|
|
||||||
|
**Recommendation:** Start with Phase 1 (Index.vue) as a proof of concept, then proceed to Phase 2 and 3 for Show.vue. Evaluate Phase 4 (partial extraction) after Phase 3 completion based on actual complexity.
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class FixImportMappingEntities extends Command
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The name and signature of the console command.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $signature = 'import:fix-mapping-entities {--dry-run : Show changes without applying them}';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The console command description.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $description = 'Fix entity names in import_mappings table to use canonical roots';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entity name mappings from incorrect to correct canonical roots
|
||||||
|
*/
|
||||||
|
protected array $entityMapping = [
|
||||||
|
'contracts' => 'contract',
|
||||||
|
'contract' => 'contract',
|
||||||
|
'client_cases' => 'client_case',
|
||||||
|
'client_case' => 'client_case',
|
||||||
|
'person_addresses' => 'address',
|
||||||
|
'addresses' => 'address',
|
||||||
|
'address' => 'address',
|
||||||
|
'person_phones' => 'phone',
|
||||||
|
'phones' => 'phone',
|
||||||
|
'phone' => 'phone',
|
||||||
|
'emails' => 'email',
|
||||||
|
'email' => 'email',
|
||||||
|
'activities' => 'activity',
|
||||||
|
'activity' => 'activity',
|
||||||
|
'persons' => 'person',
|
||||||
|
'person' => 'person',
|
||||||
|
'accounts' => 'account',
|
||||||
|
'account' => 'account',
|
||||||
|
'payments' => 'payment',
|
||||||
|
'payment' => 'payment',
|
||||||
|
'bookings' => 'booking',
|
||||||
|
'booking' => 'booking',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the console command.
|
||||||
|
*/
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
$dryRun = $this->option('dry-run');
|
||||||
|
|
||||||
|
if ($dryRun) {
|
||||||
|
$this->info('Running in DRY-RUN mode - no changes will be made');
|
||||||
|
}
|
||||||
|
|
||||||
|
$mappings = DB::table('import_mappings')
|
||||||
|
->whereNotNull('entity')
|
||||||
|
->where('entity', '!=', '')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
if ($mappings->isEmpty()) {
|
||||||
|
$this->info('No mappings found to fix.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info("Found {$mappings->count()} mappings to check");
|
||||||
|
$this->newLine();
|
||||||
|
|
||||||
|
$updates = [];
|
||||||
|
$unchanged = 0;
|
||||||
|
|
||||||
|
foreach ($mappings as $mapping) {
|
||||||
|
$currentEntity = trim($mapping->entity);
|
||||||
|
|
||||||
|
if (isset($this->entityMapping[$currentEntity])) {
|
||||||
|
$correctEntity = $this->entityMapping[$currentEntity];
|
||||||
|
|
||||||
|
if ($currentEntity !== $correctEntity) {
|
||||||
|
$updates[] = [
|
||||||
|
'id' => $mapping->id,
|
||||||
|
'current' => $currentEntity,
|
||||||
|
'correct' => $correctEntity,
|
||||||
|
'source' => $mapping->source_column,
|
||||||
|
'target' => $mapping->target_field,
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
$unchanged++;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$this->warn("Unknown entity type: {$currentEntity} (ID: {$mapping->id})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($updates)) {
|
||||||
|
$this->info("✓ All {$unchanged} mappings already have correct entity names!");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Display changes
|
||||||
|
$this->info("Changes to be made:");
|
||||||
|
$this->newLine();
|
||||||
|
|
||||||
|
$table = [];
|
||||||
|
foreach ($updates as $update) {
|
||||||
|
$table[] = [
|
||||||
|
$update['id'],
|
||||||
|
$update['source'],
|
||||||
|
$update['target'],
|
||||||
|
$update['current'],
|
||||||
|
$update['correct'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->table(
|
||||||
|
['ID', 'Source Column', 'Target Field', 'Current Entity', 'Correct Entity'],
|
||||||
|
$table
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->newLine();
|
||||||
|
$this->info("Total changes: " . count($updates));
|
||||||
|
$this->info("Unchanged: {$unchanged}");
|
||||||
|
|
||||||
|
if ($dryRun) {
|
||||||
|
$this->newLine();
|
||||||
|
$this->warn('DRY-RUN mode: No changes were made. Run without --dry-run to apply changes.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Confirm before proceeding
|
||||||
|
if (!$this->confirm('Do you want to apply these changes?', true)) {
|
||||||
|
$this->info('Operation cancelled.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply updates
|
||||||
|
$updated = 0;
|
||||||
|
foreach ($updates as $update) {
|
||||||
|
DB::table('import_mappings')
|
||||||
|
->where('id', $update['id'])
|
||||||
|
->update(['entity' => $update['correct']]);
|
||||||
|
$updated++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->newLine();
|
||||||
|
$this->info("✓ Successfully updated {$updated} mappings!");
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class PopulateImportMappingEntities extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'import:populate-mapping-entities {--dry-run : Show changes without applying them}';
|
||||||
|
|
||||||
|
protected $description = 'Populate entity column from target_field for mappings where entity is null';
|
||||||
|
|
||||||
|
protected array $entityMap = [
|
||||||
|
'contracts' => 'contract',
|
||||||
|
'client_cases' => 'client_case',
|
||||||
|
'person_addresses' => 'address',
|
||||||
|
'person_phones' => 'phone',
|
||||||
|
'emails' => 'email',
|
||||||
|
'activities' => 'activity',
|
||||||
|
'payments' => 'payment',
|
||||||
|
'accounts' => 'account',
|
||||||
|
'persons' => 'person',
|
||||||
|
'person' => 'person',
|
||||||
|
'contract' => 'contract',
|
||||||
|
'client_case' => 'client_case',
|
||||||
|
'address' => 'address',
|
||||||
|
'phone' => 'phone',
|
||||||
|
'email' => 'email',
|
||||||
|
'activity' => 'activity',
|
||||||
|
'payment' => 'payment',
|
||||||
|
'account' => 'account',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
$dryRun = $this->option('dry-run');
|
||||||
|
|
||||||
|
$this->info('Populating entity column from target_field...');
|
||||||
|
if ($dryRun) {
|
||||||
|
$this->warn('DRY RUN MODE - No changes will be made');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all mappings where entity is null
|
||||||
|
$mappings = DB::table('import_mappings')
|
||||||
|
->whereNull('entity')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
if ($mappings->isEmpty()) {
|
||||||
|
$this->info('No mappings found with null entity.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info("Found {$mappings->count()} mappings to process.");
|
||||||
|
$this->newLine();
|
||||||
|
|
||||||
|
$updated = 0;
|
||||||
|
$skipped = 0;
|
||||||
|
|
||||||
|
foreach ($mappings as $mapping) {
|
||||||
|
$targetField = $mapping->target_field;
|
||||||
|
|
||||||
|
// Parse the target_field to extract entity and field
|
||||||
|
if (str_contains($targetField, '.')) {
|
||||||
|
[$rawEntity, $field] = explode('.', $targetField, 2);
|
||||||
|
} elseif (str_contains($targetField, '->')) {
|
||||||
|
[$rawEntity, $field] = explode('->', $targetField, 2);
|
||||||
|
} else {
|
||||||
|
$this->warn("Skipping mapping ID {$mapping->id}: Cannot parse target_field '{$targetField}'");
|
||||||
|
$skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rawEntity = trim($rawEntity);
|
||||||
|
$field = trim($field);
|
||||||
|
|
||||||
|
// Map to canonical entity name
|
||||||
|
$canonicalEntity = $this->entityMap[$rawEntity] ?? $rawEntity;
|
||||||
|
|
||||||
|
$this->line(sprintf(
|
||||||
|
"ID %d: '%s' -> '%s' => entity='%s', field='%s'",
|
||||||
|
$mapping->id,
|
||||||
|
$mapping->source_column,
|
||||||
|
$targetField,
|
||||||
|
$canonicalEntity,
|
||||||
|
$field
|
||||||
|
));
|
||||||
|
|
||||||
|
if (!$dryRun) {
|
||||||
|
DB::table('import_mappings')
|
||||||
|
->where('id', $mapping->id)
|
||||||
|
->update([
|
||||||
|
'entity' => $canonicalEntity,
|
||||||
|
'target_field' => $field,
|
||||||
|
]);
|
||||||
|
$updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->newLine();
|
||||||
|
if ($dryRun) {
|
||||||
|
$this->info("Dry run complete. Would have updated {$mappings->count()} mappings.");
|
||||||
|
} else {
|
||||||
|
$this->info("Successfully updated {$updated} mappings.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($skipped > 0) {
|
||||||
|
$this->warn("Skipped {$skipped} mappings that couldn't be parsed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Models\Import;
|
||||||
|
use App\Services\Import\ImportSimulationServiceV2;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class SimulateImportV2Command extends Command
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The name and signature of the console command.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $signature = 'import:simulate-v2 {import_id} {--limit=100 : Number of rows to simulate} {--verbose : Include detailed information}';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The console command description.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $description = 'Simulate ImportServiceV2 without persisting data';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the console command.
|
||||||
|
*/
|
||||||
|
public function handle(ImportSimulationServiceV2 $service): int
|
||||||
|
{
|
||||||
|
$importId = $this->argument('import_id');
|
||||||
|
$limit = (int) $this->option('limit');
|
||||||
|
$verbose = (bool) $this->option('verbose');
|
||||||
|
|
||||||
|
$import = Import::find($importId);
|
||||||
|
|
||||||
|
if (! $import) {
|
||||||
|
$this->error("Import #{$importId} not found.");
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info("Simulating import #{$importId} - {$import->file_name}");
|
||||||
|
$this->info("Client: ".($import->client->name ?? 'N/A'));
|
||||||
|
$this->info("Limit: {$limit} rows");
|
||||||
|
$this->line('');
|
||||||
|
|
||||||
|
$result = $service->simulate($import, $limit, $verbose);
|
||||||
|
|
||||||
|
if (! $result['success']) {
|
||||||
|
$this->error('Simulation failed: '.$result['error']);
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info("✓ Simulated {$result['total_simulated']} rows");
|
||||||
|
$this->line('');
|
||||||
|
|
||||||
|
// Display summaries
|
||||||
|
if (! empty($result['summaries'])) {
|
||||||
|
$this->info('=== Entity Summaries ===');
|
||||||
|
$summaryRows = [];
|
||||||
|
|
||||||
|
foreach ($result['summaries'] as $entity => $stats) {
|
||||||
|
$summaryRows[] = [
|
||||||
|
'entity' => $entity,
|
||||||
|
'create' => $stats['create'],
|
||||||
|
'update' => $stats['update'],
|
||||||
|
'skip' => $stats['skip'],
|
||||||
|
'invalid' => $stats['invalid'],
|
||||||
|
'total' => array_sum($stats),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->table(
|
||||||
|
['Entity', 'Create', 'Update', 'Skip', 'Invalid', 'Total'],
|
||||||
|
$summaryRows
|
||||||
|
);
|
||||||
|
$this->line('');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Display row previews (first 5)
|
||||||
|
if (! empty($result['rows'])) {
|
||||||
|
$this->info('=== Row Previews (first 5) ===');
|
||||||
|
|
||||||
|
foreach (array_slice($result['rows'], 0, 5) as $row) {
|
||||||
|
$this->line("Row #{$row['row_number']}:");
|
||||||
|
|
||||||
|
if (! empty($row['entities'])) {
|
||||||
|
foreach ($row['entities'] as $entity => $data) {
|
||||||
|
$action = $data['action'];
|
||||||
|
$color = match ($action) {
|
||||||
|
'create' => 'green',
|
||||||
|
'update' => 'yellow',
|
||||||
|
'skip' => 'gray',
|
||||||
|
'invalid', 'error' => 'red',
|
||||||
|
default => 'white',
|
||||||
|
};
|
||||||
|
|
||||||
|
$line = " {$entity}: <fg={$color}>{$action}</>";
|
||||||
|
|
||||||
|
if (isset($data['reference'])) {
|
||||||
|
$line .= " ({$data['reference']})";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($data['existing_id'])) {
|
||||||
|
$line .= " [ID: {$data['existing_id']}]";
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->line($line);
|
||||||
|
|
||||||
|
if ($verbose && ! empty($data['changes'])) {
|
||||||
|
foreach ($data['changes'] as $field => $change) {
|
||||||
|
$this->line(" {$field}: {$change['old']} → {$change['new']}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! empty($data['errors'])) {
|
||||||
|
foreach ($data['errors'] as $error) {
|
||||||
|
$this->error(" ✗ {$error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! empty($row['warnings'])) {
|
||||||
|
foreach ($row['warnings'] as $warning) {
|
||||||
|
$this->warn(" ⚠ {$warning}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! empty($row['errors'])) {
|
||||||
|
foreach ($row['errors'] as $error) {
|
||||||
|
$this->error(" ✗ {$error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->line('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info('Simulation completed successfully.');
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Console\Commands;
|
||||||
|
|
||||||
|
use App\Jobs\ProcessLargeImportJob;
|
||||||
|
use App\Models\Import;
|
||||||
|
use App\Services\Import\ImportServiceV2;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
|
||||||
|
class TestImportV2Command extends Command
|
||||||
|
{
|
||||||
|
protected $signature = 'import:test-v2 {import_id : The import ID to process} {--queue : Process via queue}';
|
||||||
|
|
||||||
|
protected $description = 'Test ImportServiceV2 with an existing import';
|
||||||
|
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
$importId = $this->argument('import_id');
|
||||||
|
$useQueue = $this->option('queue');
|
||||||
|
|
||||||
|
$import = Import::find($importId);
|
||||||
|
|
||||||
|
if (! $import) {
|
||||||
|
$this->error("Import {$importId} not found.");
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info("Processing import: {$import->id} ({$import->file_name})");
|
||||||
|
$this->info("Source: {$import->source_type}");
|
||||||
|
$this->info("Status: {$import->status}");
|
||||||
|
$this->newLine();
|
||||||
|
|
||||||
|
if ($useQueue) {
|
||||||
|
$this->info('Dispatching to queue...');
|
||||||
|
ProcessLargeImportJob::dispatch($import, auth()->id());
|
||||||
|
$this->info('Job dispatched successfully. Monitor queue for progress.');
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->info('Processing synchronously...');
|
||||||
|
$service = app(ImportServiceV2::class);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$results = $service->process($import, auth()->user());
|
||||||
|
|
||||||
|
$this->newLine();
|
||||||
|
$this->info('Processing completed!');
|
||||||
|
$this->table(
|
||||||
|
['Metric', 'Count'],
|
||||||
|
[
|
||||||
|
['Total rows', $results['total']],
|
||||||
|
['Imported', $results['imported']],
|
||||||
|
['Skipped', $results['skipped']],
|
||||||
|
['Invalid', $results['invalid']],
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$this->error('Processing failed: '.$e->getMessage());
|
||||||
|
$this->error($e->getTraceAsString());
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Exports;
|
||||||
|
|
||||||
|
use App\Models\Contract;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Maatwebsite\Excel\Concerns\FromQuery;
|
||||||
|
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||||
|
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Cell\Cell;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||||||
|
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
|
||||||
|
|
||||||
|
class ClientContractsExport extends DefaultValueBinder implements FromQuery, ShouldAutoSize, WithColumnFormatting, WithCustomValueBinder, WithHeadings, WithMapping
|
||||||
|
{
|
||||||
|
public const DATE_EXCEL_FORMAT = 'dd"."mm"."yyyy';
|
||||||
|
|
||||||
|
public const TEXT_EXCEL_FORMAT = NumberFormat::FORMAT_TEXT;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
private array $columnLetterMap = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, array{label: string}>
|
||||||
|
*/
|
||||||
|
public const COLUMN_METADATA = [
|
||||||
|
'reference' => ['label' => 'Referenca'],
|
||||||
|
'customer' => ['label' => 'Stranka'],
|
||||||
|
'address' => ['label' => 'Naslov'],
|
||||||
|
'start' => ['label' => 'Začetek'],
|
||||||
|
'segment' => ['label' => 'Segment'],
|
||||||
|
'balance' => ['label' => 'Stanje'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $columns
|
||||||
|
*/
|
||||||
|
public function __construct(private Builder $query, private array $columns) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public static function allowedColumns(): array
|
||||||
|
{
|
||||||
|
return array_keys(self::COLUMN_METADATA);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function columnLabel(string $column): string
|
||||||
|
{
|
||||||
|
return self::COLUMN_METADATA[$column]['label'] ?? $column;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function query(): Builder
|
||||||
|
{
|
||||||
|
return $this->query;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, mixed>
|
||||||
|
*/
|
||||||
|
public function map($row): array
|
||||||
|
{
|
||||||
|
return array_map(fn (string $column) => $this->resolveValue($row, $column), $this->columns);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public function headings(): array
|
||||||
|
{
|
||||||
|
return array_map(fn (string $column) => self::columnLabel($column), $this->columns);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function columnFormats(): array
|
||||||
|
{
|
||||||
|
$formats = [];
|
||||||
|
|
||||||
|
foreach ($this->getColumnLetterMap() as $letter => $column) {
|
||||||
|
if ($column === 'reference') {
|
||||||
|
$formats[$letter] = self::TEXT_EXCEL_FORMAT;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($column === 'start') {
|
||||||
|
$formats[$letter] = self::DATE_EXCEL_FORMAT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $formats;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resolveValue(Contract $contract, string $column): mixed
|
||||||
|
{
|
||||||
|
return match ($column) {
|
||||||
|
'reference' => $contract->reference,
|
||||||
|
'customer' => optional($contract->clientCase?->person)->full_name,
|
||||||
|
'address' => optional($contract->clientCase?->person?->address)->address,
|
||||||
|
'start' => $this->formatDate($contract->start_date),
|
||||||
|
'segment' => $contract->segments?->first()?->name,
|
||||||
|
'balance' => optional($contract->account)->balance_amount,
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function formatDate(?string $date): mixed
|
||||||
|
{
|
||||||
|
if (empty($date)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$carbon = Carbon::parse($date);
|
||||||
|
|
||||||
|
return ExcelDate::dateTimeToExcel($carbon);
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
private function getColumnLetterMap(): array
|
||||||
|
{
|
||||||
|
if ($this->columnLetterMap !== []) {
|
||||||
|
return $this->columnLetterMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
$letter = 'A';
|
||||||
|
foreach ($this->columns as $column) {
|
||||||
|
$this->columnLetterMap[$letter] = $column;
|
||||||
|
$letter++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->columnLetterMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function bindValue(Cell $cell, $value): bool
|
||||||
|
{
|
||||||
|
if (is_numeric($value)) {
|
||||||
|
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::bindValue($cell, $value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ class SegmentContractsExport extends DefaultValueBinder implements FromQuery, Sh
|
|||||||
public const COLUMN_METADATA = [
|
public const COLUMN_METADATA = [
|
||||||
'reference' => ['label' => 'Pogodba'],
|
'reference' => ['label' => 'Pogodba'],
|
||||||
'client_case' => ['label' => 'Primer'],
|
'client_case' => ['label' => 'Primer'],
|
||||||
|
'address' => ['label' => 'Naslov'],
|
||||||
'client' => ['label' => 'Stranka'],
|
'client' => ['label' => 'Stranka'],
|
||||||
'type' => ['label' => 'Vrsta'],
|
'type' => ['label' => 'Vrsta'],
|
||||||
'start_date' => ['label' => 'Začetek'],
|
'start_date' => ['label' => 'Začetek'],
|
||||||
@@ -107,6 +108,7 @@ private function resolveValue(Contract $contract, string $column): mixed
|
|||||||
return match ($column) {
|
return match ($column) {
|
||||||
'reference' => $contract->reference,
|
'reference' => $contract->reference,
|
||||||
'client_case' => optional($contract->clientCase?->person)->full_name,
|
'client_case' => optional($contract->clientCase?->person)->full_name,
|
||||||
|
'address' => optional($contract->clientCase?->person?->address)->address,
|
||||||
'client' => optional($contract->clientCase?->client?->person)->full_name,
|
'client' => optional($contract->clientCase?->client?->person)->full_name,
|
||||||
'type' => optional($contract->type)->name,
|
'type' => optional($contract->type)->name,
|
||||||
'start_date' => $this->formatDate($contract->start_date),
|
'start_date' => $this->formatDate($contract->start_date),
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Requests\StoreInstallmentRequest;
|
||||||
|
use App\Models\Account;
|
||||||
|
use App\Models\Activity;
|
||||||
|
use App\Models\Booking;
|
||||||
|
use App\Models\Installment;
|
||||||
|
use App\Models\InstallmentSetting;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
|
||||||
|
class AccountInstallmentController extends Controller
|
||||||
|
{
|
||||||
|
public function list(Account $account): JsonResponse
|
||||||
|
{
|
||||||
|
$installments = Installment::query()
|
||||||
|
->where('account_id', $account->id)
|
||||||
|
->orderByDesc('installment_at')
|
||||||
|
->get(['id', 'amount', 'balance_before', 'currency', 'reference', 'installment_at', 'created_at'])
|
||||||
|
->map(function (Installment $i) {
|
||||||
|
return [
|
||||||
|
'id' => $i->id,
|
||||||
|
'amount' => (float) $i->amount,
|
||||||
|
'balance_before' => (float) ($i->balance_before ?? 0),
|
||||||
|
'currency' => $i->currency,
|
||||||
|
'reference' => $i->reference,
|
||||||
|
'installment_at' => optional($i->installment_at)?->toDateString(),
|
||||||
|
'created_at' => optional($i->created_at)?->toDateTimeString(),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'account' => [
|
||||||
|
'id' => $account->id,
|
||||||
|
'balance_amount' => $account->balance_amount,
|
||||||
|
],
|
||||||
|
'installments' => $installments,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(StoreInstallmentRequest $request, Account $account): RedirectResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validated();
|
||||||
|
|
||||||
|
$amountCents = (int) round(((float) $validated['amount']) * 100);
|
||||||
|
|
||||||
|
$settings = InstallmentSetting::query()->first();
|
||||||
|
$defaultCurrency = strtoupper($settings->default_currency ?? 'EUR');
|
||||||
|
|
||||||
|
$installment = Installment::query()->create([
|
||||||
|
'account_id' => $account->id,
|
||||||
|
'balance_before' => (float) ($account->balance_amount ?? 0),
|
||||||
|
'amount' => (float) $validated['amount'],
|
||||||
|
'currency' => strtoupper($validated['currency'] ?? $defaultCurrency),
|
||||||
|
'reference' => $validated['reference'] ?? null,
|
||||||
|
'installment_at' => $validated['installment_at'] ?? now(),
|
||||||
|
'meta' => $validated['meta'] ?? null,
|
||||||
|
'created_by' => $request->user()?->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Debit booking — increases the account balance
|
||||||
|
Booking::query()->create([
|
||||||
|
'account_id' => $account->id,
|
||||||
|
'payment_id' => null,
|
||||||
|
'amount_cents' => $amountCents,
|
||||||
|
'type' => 'debit',
|
||||||
|
'description' => $installment->reference ? ('Obremenitev '.$installment->reference) : 'Obremenitev',
|
||||||
|
'booked_at' => $installment->installment_at ?? now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($settings && ($settings->create_activity_on_installment ?? false)) {
|
||||||
|
$note = $settings->activity_note_template ?? 'Dodan obrok';
|
||||||
|
$note = str_replace(['{amount}', '{currency}'], [number_format($amountCents / 100, 2, ',', '.'), $installment->currency], $note);
|
||||||
|
|
||||||
|
$account->refresh();
|
||||||
|
$beforeStr = number_format((float) ($installment->balance_before ?? 0), 2, ',', '.').' '.$installment->currency;
|
||||||
|
$afterStr = number_format((float) ($account->balance_amount ?? 0), 2, ',', '.').' '.$installment->currency;
|
||||||
|
$note .= " (Stanje pred: {$beforeStr}, Stanje po: {$afterStr}; Izvor: obrok)";
|
||||||
|
|
||||||
|
$account->loadMissing('contract');
|
||||||
|
$clientCaseId = $account->contract?->client_case_id;
|
||||||
|
if ($clientCaseId) {
|
||||||
|
$activity = Activity::query()->create([
|
||||||
|
'due_date' => null,
|
||||||
|
'amount' => $amountCents / 100,
|
||||||
|
'note' => $note,
|
||||||
|
'action_id' => $settings->default_action_id,
|
||||||
|
'decision_id' => $settings->default_decision_id,
|
||||||
|
'client_case_id' => $clientCaseId,
|
||||||
|
'contract_id' => $account->contract_id,
|
||||||
|
]);
|
||||||
|
$installment->update(['activity_id' => $activity->id]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return back()->with('success', 'Installment created.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy(Account $account, Installment $installment): RedirectResponse|JsonResponse
|
||||||
|
{
|
||||||
|
if ($installment->account_id !== $account->id) {
|
||||||
|
abort(404);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete related debit booking(s) to revert balance via model events
|
||||||
|
Booking::query()
|
||||||
|
->where('account_id', $account->id)
|
||||||
|
->where('type', 'debit')
|
||||||
|
->whereDate('booked_at', optional($installment->installment_at)?->toDateString())
|
||||||
|
->where('amount_cents', (int) round(((float) $installment->amount) * 100))
|
||||||
|
->whereNull('payment_id')
|
||||||
|
->get()
|
||||||
|
->each->delete();
|
||||||
|
|
||||||
|
if ($installment->activity_id) {
|
||||||
|
$activity = Activity::query()->find($installment->activity_id);
|
||||||
|
if ($activity) {
|
||||||
|
$activity->delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$installment->delete();
|
||||||
|
|
||||||
|
if (request()->wantsJson()) {
|
||||||
|
return response()->json(['success' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return back()->with('success', 'Installment deleted.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
use App\Models\EmailLog;
|
use App\Models\EmailLog;
|
||||||
use App\Models\EmailTemplate;
|
use App\Models\EmailTemplate;
|
||||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
@@ -69,4 +70,15 @@ public function show(EmailLog $emailLog): Response
|
|||||||
'log' => $emailLog,
|
'log' => $emailLog,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function body(EmailLog $emailLog): JsonResponse
|
||||||
|
{
|
||||||
|
$this->authorize('viewAny', EmailTemplate::class);
|
||||||
|
|
||||||
|
$emailLog->load('body');
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'html' => $emailLog->body?->body_html ?? '',
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
use App\Models\EmailLog;
|
use App\Models\EmailLog;
|
||||||
use App\Models\EmailLogStatus;
|
use App\Models\EmailLogStatus;
|
||||||
use App\Models\EmailTemplate;
|
use App\Models\EmailTemplate;
|
||||||
|
use App\Models\MailProfile;
|
||||||
use App\Services\EmailTemplateRenderer;
|
use App\Services\EmailTemplateRenderer;
|
||||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
@@ -55,8 +56,14 @@ public function create(): Response
|
|||||||
{
|
{
|
||||||
$this->authorize('create', EmailTemplate::class);
|
$this->authorize('create', EmailTemplate::class);
|
||||||
|
|
||||||
|
$actions = \App\Models\Action::query()
|
||||||
|
->with(['decisions:id,name'])
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
|
||||||
return Inertia::render('Admin/EmailTemplates/Edit', [
|
return Inertia::render('Admin/EmailTemplates/Edit', [
|
||||||
'template' => null,
|
'template' => null,
|
||||||
|
'actions' => $actions,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +100,7 @@ public function preview(Request $request, EmailTemplate $emailTemplate): JsonRes
|
|||||||
// Context resolution (shared logic with renderFinalHtml)
|
// Context resolution (shared logic with renderFinalHtml)
|
||||||
$ctx = [];
|
$ctx = [];
|
||||||
if ($id = $request->integer('activity_id')) {
|
if ($id = $request->integer('activity_id')) {
|
||||||
$activity = Activity::query()->with(['action', 'decision', 'contract.clientCase.client.person', 'clientCase.client.person'])->find($id);
|
$activity = Activity::query()->with(['action', 'decision', 'contract.clientCase.client.person', 'contract.account', 'clientCase.client.person'])->find($id);
|
||||||
if ($activity) {
|
if ($activity) {
|
||||||
$ctx['activity'] = $activity;
|
$ctx['activity'] = $activity;
|
||||||
// Derive base entities from activity when not explicitly provided
|
// Derive base entities from activity when not explicitly provided
|
||||||
@@ -110,7 +117,7 @@ public function preview(Request $request, EmailTemplate $emailTemplate): JsonRes
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($id = $request->integer('contract_id')) {
|
if ($id = $request->integer('contract_id')) {
|
||||||
$contract = Contract::query()->with(['clientCase.client.person'])->find($id);
|
$contract = Contract::query()->with(['clientCase.client.person', 'account'])->find($id);
|
||||||
if ($contract) {
|
if ($contract) {
|
||||||
$ctx['contract'] = $contract;
|
$ctx['contract'] = $contract;
|
||||||
if ($contract->clientCase) {
|
if ($contract->clientCase) {
|
||||||
@@ -140,6 +147,7 @@ public function preview(Request $request, EmailTemplate $emailTemplate): JsonRes
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
$ctx['extra'] = (array) $request->input('extra', []);
|
$ctx['extra'] = (array) $request->input('extra', []);
|
||||||
|
$ctx['mail_profile'] = MailProfile::query()->orderBy('active', 'desc')->orderBy('priority')->orderBy('id')->first();
|
||||||
|
|
||||||
$rendered = $renderer->render([
|
$rendered = $renderer->render([
|
||||||
'subject' => $subject,
|
'subject' => $subject,
|
||||||
@@ -161,8 +169,14 @@ public function edit(EmailTemplate $emailTemplate): Response
|
|||||||
$q->select(['id', 'documentable_id', 'documentable_type', 'name', 'path', 'size', 'created_at']);
|
$q->select(['id', 'documentable_id', 'documentable_type', 'name', 'path', 'size', 'created_at']);
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
|
$actions = \App\Models\Action::query()
|
||||||
|
->with(['decisions:id,name'])
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
|
||||||
return Inertia::render('Admin/EmailTemplates/Edit', [
|
return Inertia::render('Admin/EmailTemplates/Edit', [
|
||||||
'template' => $emailTemplate,
|
'template' => $emailTemplate,
|
||||||
|
'actions' => $actions,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +195,7 @@ public function sendTest(Request $request, EmailTemplate $emailTemplate)
|
|||||||
// Context resolution
|
// Context resolution
|
||||||
$ctx = [];
|
$ctx = [];
|
||||||
if ($id = $request->integer('activity_id')) {
|
if ($id = $request->integer('activity_id')) {
|
||||||
$activity = Activity::query()->with(['action', 'decision', 'contract.clientCase.client.person', 'clientCase.client.person'])->find($id);
|
$activity = Activity::query()->with(['action', 'decision', 'contract.clientCase.client.person', 'contract.account', 'clientCase.client.person'])->find($id);
|
||||||
if ($activity) {
|
if ($activity) {
|
||||||
$ctx['activity'] = $activity;
|
$ctx['activity'] = $activity;
|
||||||
if ($activity->contract && ! isset($ctx['contract'])) {
|
if ($activity->contract && ! isset($ctx['contract'])) {
|
||||||
@@ -197,7 +211,7 @@ public function sendTest(Request $request, EmailTemplate $emailTemplate)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($id = $request->integer('contract_id')) {
|
if ($id = $request->integer('contract_id')) {
|
||||||
$contract = Contract::query()->with(['clientCase.client.person'])->find($id);
|
$contract = Contract::query()->with(['clientCase.client.person', 'account'])->find($id);
|
||||||
if ($contract) {
|
if ($contract) {
|
||||||
$ctx['contract'] = $contract;
|
$ctx['contract'] = $contract;
|
||||||
if ($contract->clientCase) {
|
if ($contract->clientCase) {
|
||||||
@@ -227,6 +241,7 @@ public function sendTest(Request $request, EmailTemplate $emailTemplate)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
$ctx['extra'] = (array) $request->input('extra', []);
|
$ctx['extra'] = (array) $request->input('extra', []);
|
||||||
|
$ctx['mail_profile'] = MailProfile::query()->orderBy('active', 'desc')->orderBy('priority')->orderBy('id')->first();
|
||||||
|
|
||||||
// Render preview values; we store a minimal snapshot on the log
|
// Render preview values; we store a minimal snapshot on the log
|
||||||
$rendered = $renderer->render([
|
$rendered = $renderer->render([
|
||||||
@@ -293,7 +308,7 @@ public function renderFinalHtml(Request $request, EmailTemplate $emailTemplate)
|
|||||||
// Context resolution (same as sendTest)
|
// Context resolution (same as sendTest)
|
||||||
$ctx = [];
|
$ctx = [];
|
||||||
if ($id = $request->integer('activity_id')) {
|
if ($id = $request->integer('activity_id')) {
|
||||||
$activity = Activity::query()->with(['action', 'decision', 'contract.clientCase.client.person', 'clientCase.client.person'])->find($id);
|
$activity = Activity::query()->with(['action', 'decision', 'contract.clientCase.client.person', 'contract.account', 'clientCase.client.person'])->find($id);
|
||||||
if ($activity) {
|
if ($activity) {
|
||||||
$ctx['activity'] = $activity;
|
$ctx['activity'] = $activity;
|
||||||
if ($activity->contract && ! isset($ctx['contract'])) {
|
if ($activity->contract && ! isset($ctx['contract'])) {
|
||||||
@@ -309,7 +324,7 @@ public function renderFinalHtml(Request $request, EmailTemplate $emailTemplate)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($id = $request->integer('contract_id')) {
|
if ($id = $request->integer('contract_id')) {
|
||||||
$contract = Contract::query()->with(['clientCase.client.person'])->find($id);
|
$contract = Contract::query()->with(['clientCase.client.person', 'account'])->find($id);
|
||||||
if ($contract) {
|
if ($contract) {
|
||||||
$ctx['contract'] = $contract;
|
$ctx['contract'] = $contract;
|
||||||
if ($contract->clientCase) {
|
if ($contract->clientCase) {
|
||||||
@@ -339,6 +354,7 @@ public function renderFinalHtml(Request $request, EmailTemplate $emailTemplate)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
$ctx['extra'] = (array) $request->input('extra', []);
|
$ctx['extra'] = (array) $request->input('extra', []);
|
||||||
|
$ctx['mail_profile'] = MailProfile::query()->orderBy('active', 'desc')->orderBy('priority')->orderBy('id')->first();
|
||||||
|
|
||||||
$rendered = $renderer->render([
|
$rendered = $renderer->render([
|
||||||
'subject' => $subject,
|
'subject' => $subject,
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public function index(): Response
|
|||||||
->orderBy('priority')
|
->orderBy('priority')
|
||||||
->orderBy('id')
|
->orderBy('id')
|
||||||
->get([
|
->get([
|
||||||
'id', 'name', 'active', 'host', 'port', 'encryption', 'from_address', 'priority', 'last_success_at', 'last_error_at', 'last_error_message', 'test_status', 'test_checked_at',
|
'id', 'name', 'active', 'auto_mailer', 'host', 'port', 'username', 'from_name', 'encryption', 'from_address', 'priority', 'signature', 'last_success_at', 'last_error_at', 'last_error_message', 'test_status', 'test_checked_at',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return Inertia::render('Admin/MailProfiles/Index', [
|
return Inertia::render('Admin/MailProfiles/Index', [
|
||||||
@@ -76,6 +76,15 @@ public function toggle(Request $request, MailProfile $mailProfile)
|
|||||||
return back()->with('success', 'Status updated');
|
return back()->with('success', 'Status updated');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function toggleAutoMailer(Request $request, MailProfile $mailProfile)
|
||||||
|
{
|
||||||
|
$this->authorize('update', $mailProfile);
|
||||||
|
$mailProfile->auto_mailer = ! $mailProfile->auto_mailer;
|
||||||
|
$mailProfile->save();
|
||||||
|
|
||||||
|
return back()->with('success', 'Auto-mailer updated');
|
||||||
|
}
|
||||||
|
|
||||||
public function test(Request $request, MailProfile $mailProfile)
|
public function test(Request $request, MailProfile $mailProfile)
|
||||||
{
|
{
|
||||||
$this->authorize('test', $mailProfile);
|
$this->authorize('test', $mailProfile);
|
||||||
|
|||||||
@@ -3,13 +3,16 @@
|
|||||||
namespace App\Http\Controllers\Admin;
|
namespace App\Http\Controllers\Admin;
|
||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Http\Requests\StoreEmailPackageFromContractsRequest;
|
||||||
use App\Http\Requests\StorePackageFromContractsRequest;
|
use App\Http\Requests\StorePackageFromContractsRequest;
|
||||||
use App\Http\Requests\StorePackageRequest;
|
use App\Http\Requests\StorePackageRequest;
|
||||||
|
use App\Jobs\PackageItemEmailJob;
|
||||||
use App\Jobs\PackageItemSmsJob;
|
use App\Jobs\PackageItemSmsJob;
|
||||||
use App\Models\Contract;
|
use App\Models\Contract;
|
||||||
use App\Models\Package;
|
use App\Models\Package;
|
||||||
use App\Models\PackageItem;
|
use App\Models\PackageItem;
|
||||||
use App\Models\SmsTemplate;
|
use App\Models\SmsTemplate;
|
||||||
|
use App\Services\Contact\EmailSelector;
|
||||||
use App\Services\Contact\PhoneSelector;
|
use App\Services\Contact\PhoneSelector;
|
||||||
use App\Services\Sms\SmsService;
|
use App\Services\Sms\SmsService;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
@@ -21,11 +24,41 @@
|
|||||||
|
|
||||||
class PackageController extends Controller
|
class PackageController extends Controller
|
||||||
{
|
{
|
||||||
public function index(Request $request): Response
|
public function landing(): Response
|
||||||
{
|
{
|
||||||
|
return Inertia::render('Packages/Index');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function smsIndex(Request $request): Response
|
||||||
|
{
|
||||||
|
$perPage = $request->input('per_page') ?? 25;
|
||||||
|
|
||||||
$packages = Package::query()
|
$packages = Package::query()
|
||||||
|
->where('type', Package::TYPE_SMS)
|
||||||
->latest('id')
|
->latest('id')
|
||||||
->paginate(20);
|
->paginate($perPage);
|
||||||
|
|
||||||
|
return Inertia::render('Packages/Sms/Index', [
|
||||||
|
'packages' => $packages,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function emailIndex(Request $request): Response
|
||||||
|
{
|
||||||
|
$perPage = $request->input('per_page') ?? 25;
|
||||||
|
|
||||||
|
$packages = Package::query()
|
||||||
|
->where('type', Package::TYPE_EMAIL)
|
||||||
|
->latest('id')
|
||||||
|
->paginate($perPage);
|
||||||
|
|
||||||
|
return Inertia::render('Packages/Mail/Index', [
|
||||||
|
'packages' => $packages,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function smsCreate(Request $request): Response
|
||||||
|
{
|
||||||
// Minimal lookups for create form (active only)
|
// Minimal lookups for create form (active only)
|
||||||
$profiles = \App\Models\SmsProfile::query()
|
$profiles = \App\Models\SmsProfile::query()
|
||||||
->where('active', true)
|
->where('active', true)
|
||||||
@@ -40,6 +73,7 @@ public function index(Request $request): Response
|
|||||||
->get(['id', 'name', 'content']);
|
->get(['id', 'name', 'content']);
|
||||||
$segments = \App\Models\Segment::query()
|
$segments = \App\Models\Segment::query()
|
||||||
->where('active', true)
|
->where('active', true)
|
||||||
|
->where('exclude', false)
|
||||||
->orderBy('name')
|
->orderBy('name')
|
||||||
->get(['id', 'name']);
|
->get(['id', 'name']);
|
||||||
// Provide a lightweight list of recent clients with person names for filtering
|
// Provide a lightweight list of recent clients with person names for filtering
|
||||||
@@ -58,8 +92,7 @@ public function index(Request $request): Response
|
|||||||
})
|
})
|
||||||
->values();
|
->values();
|
||||||
|
|
||||||
return Inertia::render('Admin/Packages/Index', [
|
return Inertia::render('Packages/Sms/Create', [
|
||||||
'packages' => $packages,
|
|
||||||
'profiles' => $profiles,
|
'profiles' => $profiles,
|
||||||
'senders' => $senders,
|
'senders' => $senders,
|
||||||
'templates' => $templates,
|
'templates' => $templates,
|
||||||
@@ -68,7 +101,53 @@ public function index(Request $request): Response
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Package $package, SmsService $sms): Response
|
public function emailCreate(): Response
|
||||||
|
{
|
||||||
|
$emailTemplates = \App\Models\EmailTemplate::query()
|
||||||
|
->where('active', true)
|
||||||
|
->where('client', false)
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name', 'subject_template', 'text_template', 'html_template'])
|
||||||
|
->map(fn ($t) => [
|
||||||
|
'id' => $t->id,
|
||||||
|
'name' => $t->name,
|
||||||
|
'subject_template' => $t->subject_template,
|
||||||
|
'text_template' => $t->text_template,
|
||||||
|
'has_body_text' => (bool) preg_match('/{{\s*body_text\s*}}/', (string) $t->html_template),
|
||||||
|
])->values();
|
||||||
|
$mailProfiles = \App\Models\MailProfile::query()
|
||||||
|
->where('active', true)
|
||||||
|
->orderBy('priority')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
$segments = \App\Models\Segment::query()
|
||||||
|
->where('active', true)
|
||||||
|
->where('exclude', false)
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name']);
|
||||||
|
$clients = \App\Models\Client::query()
|
||||||
|
->with(['person' => function ($q) {
|
||||||
|
$q->select('id', 'uuid', 'full_name');
|
||||||
|
}])
|
||||||
|
->latest('id')
|
||||||
|
->get(['id', 'uuid', 'person_id'])
|
||||||
|
->map(function ($c) {
|
||||||
|
return [
|
||||||
|
'id' => $c->id,
|
||||||
|
'uuid' => $c->uuid,
|
||||||
|
'name' => $c->person?->full_name ?? ('Client #'.$c->id),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return Inertia::render('Packages/Mail/Create', [
|
||||||
|
'emailTemplates' => $emailTemplates,
|
||||||
|
'mailProfiles' => $mailProfiles,
|
||||||
|
'segments' => $segments,
|
||||||
|
'clients' => $clients,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function smsShow(Package $package, SmsService $sms): Response
|
||||||
{
|
{
|
||||||
$items = $package->items()->latest('id')->paginate(25);
|
$items = $package->items()->latest('id')->paginate(25);
|
||||||
|
|
||||||
@@ -202,13 +281,23 @@ public function show(Package $package, SmsService $sms): Response
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('Admin/Packages/Show', [
|
return Inertia::render('Packages/Sms/Show', [
|
||||||
'package' => $package,
|
'package' => $package,
|
||||||
'items' => $items,
|
'items' => $items,
|
||||||
'preview' => $preview,
|
'preview' => $preview,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function emailShow(Package $package): Response
|
||||||
|
{
|
||||||
|
$items = $package->items()->latest('id')->paginate(25);
|
||||||
|
|
||||||
|
return Inertia::render('Packages/Mail/Show', [
|
||||||
|
'package' => $package,
|
||||||
|
'items' => $items,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
public function store(StorePackageRequest $request): RedirectResponse
|
public function store(StorePackageRequest $request): RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validated();
|
$data = $request->validated();
|
||||||
@@ -250,7 +339,11 @@ public function dispatch(Package $package): RedirectResponse
|
|||||||
return back()->with('error', 'Package not in a dispatchable state.');
|
return back()->with('error', 'Package not in a dispatchable state.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$jobs = $package->items()->whereIn('status', ['queued', 'failed'])->get()->map(function (PackageItem $item) {
|
$jobs = $package->items()->whereIn('status', ['queued', 'failed'])->get()->map(function (PackageItem $item) use ($package) {
|
||||||
|
if ($package->type === Package::TYPE_EMAIL) {
|
||||||
|
return new PackageItemEmailJob($item->id);
|
||||||
|
}
|
||||||
|
|
||||||
return new PackageItemSmsJob($item->id);
|
return new PackageItemSmsJob($item->id);
|
||||||
})->all();
|
})->all();
|
||||||
|
|
||||||
@@ -276,7 +369,7 @@ public function dispatch(Package $package): RedirectResponse
|
|||||||
$package->save();
|
$package->save();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
->onQueue('sms')
|
->onQueue($package->type === Package::TYPE_EMAIL ? 'email' : 'sms')
|
||||||
->dispatch();
|
->dispatch();
|
||||||
|
|
||||||
return back()->with('success', 'Package dispatched');
|
return back()->with('success', 'Package dispatched');
|
||||||
@@ -312,7 +405,6 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
$request->validate([
|
$request->validate([
|
||||||
'segment_id' => ['nullable', 'integer', 'exists:segments,id'],
|
'segment_id' => ['nullable', 'integer', 'exists:segments,id'],
|
||||||
'q' => ['nullable', 'string'],
|
'q' => ['nullable', 'string'],
|
||||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
|
||||||
'client_id' => ['nullable', 'integer', 'exists:clients,id'],
|
'client_id' => ['nullable', 'integer', 'exists:clients,id'],
|
||||||
'only_mobile' => ['nullable', 'boolean'],
|
'only_mobile' => ['nullable', 'boolean'],
|
||||||
'only_validated' => ['nullable', 'boolean'],
|
'only_validated' => ['nullable', 'boolean'],
|
||||||
@@ -323,13 +415,13 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
$segmentId = $request->input('segment_id') ? (int) $request->input('segment_id') : null;
|
$segmentId = $request->input('segment_id') ? (int) $request->input('segment_id') : null;
|
||||||
$perPage = (int) ($request->input('per_page') ?? 25);
|
|
||||||
|
|
||||||
$query = Contract::query()
|
$query = Contract::query()
|
||||||
->with([
|
->with([
|
||||||
'clientCase.person.phones',
|
'clientCase.person.phones',
|
||||||
'clientCase.client.person',
|
'clientCase.client.person',
|
||||||
'account',
|
'account',
|
||||||
|
'segments:id,name',
|
||||||
])
|
])
|
||||||
->select('contracts.*')
|
->select('contracts.*')
|
||||||
->latest('contracts.id');
|
->latest('contracts.id');
|
||||||
@@ -341,6 +433,15 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
->where('contract_segment.segment_id', '=', $segmentId)
|
->where('contract_segment.segment_id', '=', $segmentId)
|
||||||
->where('contract_segment.active', true);
|
->where('contract_segment.active', true);
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
// Only include contracts that have at least one active, non-excluded segment
|
||||||
|
$query->whereExists(fn ($exist) => $exist->select(\DB::raw(1))
|
||||||
|
->from('contract_segment')
|
||||||
|
->join('segments', 'segments.id', '=', 'contract_segment.segment_id')
|
||||||
|
->where('contract_segment.active', true)
|
||||||
|
->where('segments.exclude', false)
|
||||||
|
->whereColumn('contract_segment.contract_id', 'contracts.id')
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($q = trim((string) $request->input('q'))) {
|
if ($q = trim((string) $request->input('q'))) {
|
||||||
@@ -390,13 +491,14 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
$contracts = $query->paginate($perPage);
|
$contracts = $query->limit(500)->get();
|
||||||
|
|
||||||
$data = collect($contracts->items())->map(function (Contract $contract) use ($selector) {
|
$data = collect($contracts)->map(function (Contract $contract) use ($selector) {
|
||||||
$person = $contract->clientCase?->person;
|
$person = $contract->clientCase?->person;
|
||||||
$selected = $person ? $selector->selectForPerson($person) : ['phone' => null, 'reason' => 'no_person'];
|
$selected = $person ? $selector->selectForPerson($person) : ['phone' => null, 'reason' => 'no_person'];
|
||||||
$phone = $selected['phone'];
|
$phone = $selected['phone'];
|
||||||
$clientPerson = $contract->clientCase?->client?->person;
|
$clientPerson = $contract->clientCase?->client?->person;
|
||||||
|
$segment = collect($contract->segments)->last();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $contract->id,
|
'id' => $contract->id,
|
||||||
@@ -414,6 +516,7 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
'uuid' => $person?->uuid,
|
'uuid' => $person?->uuid,
|
||||||
'full_name' => $person?->full_name,
|
'full_name' => $person?->full_name,
|
||||||
],
|
],
|
||||||
|
'segment' => $segment,
|
||||||
// Stranka: the client person
|
// Stranka: the client person
|
||||||
'client' => $clientPerson ? [
|
'client' => $clientPerson ? [
|
||||||
'id' => $contract->clientCase?->client?->id,
|
'id' => $contract->clientCase?->client?->id,
|
||||||
@@ -425,6 +528,7 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
'number' => $phone->nu,
|
'number' => $phone->nu,
|
||||||
'validated' => $phone->validated,
|
'validated' => $phone->validated,
|
||||||
'type' => $phone->phone_type?->value,
|
'type' => $phone->phone_type?->value,
|
||||||
|
'description' => $phone->description,
|
||||||
] : null,
|
] : null,
|
||||||
'no_phone_reason' => $phone ? null : ($selected['reason'] ?? 'unknown'),
|
'no_phone_reason' => $phone ? null : ($selected['reason'] ?? 'unknown'),
|
||||||
];
|
];
|
||||||
@@ -432,12 +536,6 @@ public function contracts(Request $request, PhoneSelector $selector): \Illuminat
|
|||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'data' => $data,
|
'data' => $data,
|
||||||
'meta' => [
|
|
||||||
'current_page' => $contracts->currentPage(),
|
|
||||||
'last_page' => $contracts->lastPage(),
|
|
||||||
'per_page' => $contracts->perPage(),
|
|
||||||
'total' => $contracts->total(),
|
|
||||||
],
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,6 +625,213 @@ public function storeFromContracts(StorePackageFromContractsRequest $request, Ph
|
|||||||
return back()->with('success', 'Package created from contracts');
|
return back()->with('success', 'Package created from contracts');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List contracts with selected email per person (for email packages).
|
||||||
|
*/
|
||||||
|
public function contractsForEmail(Request $request, EmailSelector $selector): \Illuminate\Http\JsonResponse
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'segment_id' => ['nullable', 'integer', 'exists:segments,id'],
|
||||||
|
'q' => ['nullable', 'string'],
|
||||||
|
'client_id' => ['nullable', 'integer', 'exists:clients,id'],
|
||||||
|
'only_verified' => ['nullable', 'boolean'],
|
||||||
|
'only_with_email' => ['nullable', 'boolean'],
|
||||||
|
'start_date_from' => ['nullable', 'date'],
|
||||||
|
'start_date_to' => ['nullable', 'date'],
|
||||||
|
'promise_date_from' => ['nullable', 'date'],
|
||||||
|
'promise_date_to' => ['nullable', 'date'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$segmentId = $request->input('segment_id') ? (int) $request->input('segment_id') : null;
|
||||||
|
|
||||||
|
$query = Contract::query()
|
||||||
|
->with([
|
||||||
|
'clientCase.person.emails',
|
||||||
|
'clientCase.client.person',
|
||||||
|
'account',
|
||||||
|
'segments:id,name',
|
||||||
|
])
|
||||||
|
->select('contracts.*')
|
||||||
|
->latest('contracts.id');
|
||||||
|
|
||||||
|
if ($segmentId) {
|
||||||
|
$query->join('contract_segment', function ($j) use ($segmentId) {
|
||||||
|
$j->on('contract_segment.contract_id', '=', 'contracts.id')
|
||||||
|
->where('contract_segment.segment_id', '=', $segmentId)
|
||||||
|
->where('contract_segment.active', true);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
$query->whereExists(fn ($exist) => $exist->select(\DB::raw(1))
|
||||||
|
->from('contract_segment')
|
||||||
|
->join('segments', 'segments.id', '=', 'contract_segment.segment_id')
|
||||||
|
->where('contract_segment.active', true)
|
||||||
|
->where('segments.exclude', false)
|
||||||
|
->whereColumn('contract_segment.contract_id', 'contracts.id')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($q = trim((string) $request->input('q'))) {
|
||||||
|
$query->where('contracts.reference', 'ILIKE', "%{$q}%");
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($clientId = $request->integer('client_id')) {
|
||||||
|
$query->join('client_cases', 'client_cases.id', '=', 'contracts.client_case_id')
|
||||||
|
->where('client_cases.client_id', $clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($startDateFrom = $request->input('start_date_from')) {
|
||||||
|
$query->where('contracts.start_date', '>=', $startDateFrom);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($startDateTo = $request->input('start_date_to')) {
|
||||||
|
$query->where('contracts.start_date', '<=', $startDateTo);
|
||||||
|
}
|
||||||
|
|
||||||
|
$promiseDateFrom = $request->input('promise_date_from');
|
||||||
|
$promiseDateTo = $request->input('promise_date_to');
|
||||||
|
|
||||||
|
if ($promiseDateFrom || $promiseDateTo) {
|
||||||
|
$query->whereHas('account', function ($q) use ($promiseDateFrom, $promiseDateTo) {
|
||||||
|
if ($promiseDateFrom) {
|
||||||
|
$q->where('promise_date', '>=', $promiseDateFrom);
|
||||||
|
}
|
||||||
|
if ($promiseDateTo) {
|
||||||
|
$q->where('promise_date', '<=', $promiseDateTo);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->boolean('only_verified')) {
|
||||||
|
$query->whereHas('clientCase.person.emails', function ($q) {
|
||||||
|
$q->where('is_active', true)->whereNotNull('verified_at');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->boolean('only_with_email')) {
|
||||||
|
$query->whereHas('clientCase.person.emails', function ($q) {
|
||||||
|
$q->where('is_active', true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$contracts = $query->limit(500)->get();
|
||||||
|
|
||||||
|
$data = collect($contracts)->map(function (Contract $contract) use ($selector) {
|
||||||
|
$person = $contract->clientCase?->person;
|
||||||
|
$selected = $person ? $selector->selectForPerson($person) : ['email' => null, 'reason' => 'no_person'];
|
||||||
|
$email = $selected['email'];
|
||||||
|
$clientPerson = $contract->clientCase?->client?->person;
|
||||||
|
$segment = collect($contract->segments)->last();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $contract->id,
|
||||||
|
'uuid' => $contract->uuid,
|
||||||
|
'reference' => $contract->reference,
|
||||||
|
'start_date' => $contract->start_date,
|
||||||
|
'promise_date' => $contract->account?->promise_date,
|
||||||
|
'case' => [
|
||||||
|
'id' => $contract->clientCase?->id,
|
||||||
|
'uuid' => $contract->clientCase?->uuid,
|
||||||
|
],
|
||||||
|
'person' => [
|
||||||
|
'id' => $person?->id,
|
||||||
|
'uuid' => $person?->uuid,
|
||||||
|
'full_name' => $person?->full_name,
|
||||||
|
],
|
||||||
|
'segment' => $segment,
|
||||||
|
'client' => $clientPerson ? [
|
||||||
|
'id' => $contract->clientCase?->client?->id,
|
||||||
|
'uuid' => $contract->clientCase?->client?->uuid,
|
||||||
|
'name' => $clientPerson->full_name,
|
||||||
|
] : null,
|
||||||
|
'selected_email' => $email ? [
|
||||||
|
'id' => $email->id,
|
||||||
|
'value' => $email->value,
|
||||||
|
'is_primary' => $email->is_primary,
|
||||||
|
'verified' => $email->verified_at !== null,
|
||||||
|
'label' => $email->label,
|
||||||
|
] : null,
|
||||||
|
'no_email_reason' => $email ? null : ($selected['reason'] ?? 'unknown'),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json(['data' => $data]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an email package from a list of contracts by selecting recipient emails.
|
||||||
|
*/
|
||||||
|
public function storeEmailFromContracts(StoreEmailPackageFromContractsRequest $request, EmailSelector $selector): RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validated();
|
||||||
|
|
||||||
|
$contracts = Contract::query()
|
||||||
|
->with(['clientCase.person', 'account.type'])
|
||||||
|
->whereIn('id', $data['contract_ids'])
|
||||||
|
->get();
|
||||||
|
|
||||||
|
$items = [];
|
||||||
|
$skipped = 0;
|
||||||
|
foreach ($contracts as $contract) {
|
||||||
|
$person = $contract->clientCase?->person;
|
||||||
|
if (! $person) {
|
||||||
|
$skipped++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$selected = $selector->selectForPerson($person);
|
||||||
|
/** @var ?\App\Models\Email $email */
|
||||||
|
$email = $selected['email'];
|
||||||
|
if (! $email) {
|
||||||
|
$skipped++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$items[] = [
|
||||||
|
'email' => $email->value,
|
||||||
|
'email_id' => $email->id,
|
||||||
|
'payload' => $data['payload'] ?? [],
|
||||||
|
'contract_id' => $contract->id,
|
||||||
|
'account_id' => $contract->account?->id,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($items)) {
|
||||||
|
return back()->with('error', 'No recipients found for selected contracts.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Package::query()->create([
|
||||||
|
'uuid' => (string) Str::uuid(),
|
||||||
|
'type' => Package::TYPE_EMAIL,
|
||||||
|
'status' => Package::STATUS_DRAFT,
|
||||||
|
'name' => $data['name'] ?? null,
|
||||||
|
'description' => $data['description'] ?? null,
|
||||||
|
'meta' => array_merge($data['meta'] ?? [], [
|
||||||
|
'source' => 'contracts',
|
||||||
|
'skipped' => $skipped,
|
||||||
|
]),
|
||||||
|
'created_by' => optional($request->user())->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$packageItems = collect($items)->map(function (array $row) {
|
||||||
|
return new PackageItem([
|
||||||
|
'status' => 'queued',
|
||||||
|
'target_json' => [
|
||||||
|
'email' => $row['email'],
|
||||||
|
'email_id' => $row['email_id'],
|
||||||
|
'contract_id' => $row['contract_id'] ?? null,
|
||||||
|
'account_id' => $row['account_id'] ?? null,
|
||||||
|
],
|
||||||
|
'payload_json' => $row['payload'] ?? [],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
$package->items()->saveMany($packageItems);
|
||||||
|
$package->total_items = $packageItems->count();
|
||||||
|
$package->save();
|
||||||
|
|
||||||
|
return back()->with('success', 'Email package created from contracts');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flatten nested meta structure into dot-notation key-value pairs.
|
* Flatten nested meta structure into dot-notation key-value pairs.
|
||||||
* Extracts 'value' from objects with {title, value, type} structure.
|
* Extracts 'value' from objects with {title, value, type} structure.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public function index(Request $request): Response
|
|||||||
{
|
{
|
||||||
Gate::authorize('manage-settings');
|
Gate::authorize('manage-settings');
|
||||||
|
|
||||||
$users = User::with('roles:id,slug,name')->orderBy('name')->get(['id', 'name', 'email', 'active']);
|
$users = User::with('roles:id,slug,name')->orderBy('name')->get(['id', 'name', 'email', 'active', 'login_redirect']);
|
||||||
$roles = Role::with('permissions:id,slug,name')->orderBy('name')->get(['id', 'name', 'slug']);
|
$roles = Role::with('permissions:id,slug,name')->orderBy('name')->get(['id', 'name', 'slug']);
|
||||||
$permissions = Permission::orderBy('slug')->get(['id', 'name', 'slug']);
|
$permissions = Permission::orderBy('slug')->get(['id', 'name', 'slug']);
|
||||||
|
|
||||||
@@ -73,4 +73,17 @@ public function toggleActive(User $user): RedirectResponse
|
|||||||
|
|
||||||
return back()->with('success', "Uporabnik {$status}");
|
return back()->with('success', "Uporabnik {$status}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function updateSettings(Request $request, User $user): RedirectResponse
|
||||||
|
{
|
||||||
|
Gate::authorize('manage-settings');
|
||||||
|
|
||||||
|
$validated = $request->validate([
|
||||||
|
'login_redirect' => ['nullable', 'string', 'max:255'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user->update($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Nastavitve shranjene');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\CallLater;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
|
||||||
|
class CallLaterController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): \Inertia\Response
|
||||||
|
{
|
||||||
|
$query = CallLater::query()
|
||||||
|
->with([
|
||||||
|
'clientCase.person',
|
||||||
|
'contract',
|
||||||
|
'user',
|
||||||
|
'activity',
|
||||||
|
])
|
||||||
|
->whereNull('completed_at')
|
||||||
|
->orderBy('call_back_at', 'asc');
|
||||||
|
|
||||||
|
if ($request->filled('date_from')) {
|
||||||
|
$query->whereDate('call_back_at', '>=', $request->date_from);
|
||||||
|
}
|
||||||
|
if ($request->filled('date_to')) {
|
||||||
|
$query->whereDate('call_back_at', '<=', $request->date_to);
|
||||||
|
}
|
||||||
|
if ($request->filled('search')) {
|
||||||
|
$term = '%'.$request->search.'%';
|
||||||
|
$query->whereHas('clientCase.person', function ($q) use ($term) {
|
||||||
|
$q->where('first_name', 'ilike', $term)
|
||||||
|
->orWhere('last_name', 'ilike', $term)
|
||||||
|
->orWhere('full_name', 'ilike', $term)
|
||||||
|
->orWhereRaw("CONCAT(first_name, ' ', last_name) ILIKE ?", [$term]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$callLaters = $query->paginate(50)->withQueryString();
|
||||||
|
|
||||||
|
return Inertia::render('CallLaters/Index', [
|
||||||
|
'callLaters' => $callLaters,
|
||||||
|
'filters' => $request->only(['date_from', 'date_to', 'search']),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function complete(CallLater $callLater): \Illuminate\Http\RedirectResponse
|
||||||
|
{
|
||||||
|
$callLater->update(['completed_at' => now()]);
|
||||||
|
|
||||||
|
return back()->with('success', 'Klic označen kot opravljen.');
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -71,10 +71,8 @@ public function index(ClientCase $clientCase, Request $request)
|
|||||||
$que->whereDate('client_cases.created_at', '<=', $to);
|
$que->whereDate('client_cases.created_at', '<=', $to);
|
||||||
})
|
})
|
||||||
->groupBy('client_cases.id')
|
->groupBy('client_cases.id')
|
||||||
->addSelect([
|
->selectRaw('COUNT(DISTINCT CASE WHEN contract_segment.id IS NOT NULL THEN contracts.id END) as active_contracts_count')
|
||||||
\DB::raw('COUNT(DISTINCT CASE WHEN contract_segment.id IS NOT NULL THEN contracts.id END) as active_contracts_count'),
|
->selectRaw('COALESCE(SUM(CASE WHEN contract_segment.id IS NOT NULL THEN accounts.balance_amount END), 0) as active_contracts_balance_sum')
|
||||||
\DB::raw('COALESCE(SUM(CASE WHEN contract_segment.id IS NOT NULL THEN accounts.balance_amount END), 0) as active_contracts_balance_sum'),
|
|
||||||
])
|
|
||||||
->with(['person.client', 'client.person'])
|
->with(['person.client', 'client.person'])
|
||||||
->orderByDesc('client_cases.created_at');
|
->orderByDesc('client_cases.created_at');
|
||||||
|
|
||||||
@@ -223,7 +221,11 @@ public function updateContract(ClientCase $clientCase, string $uuid, UpdateContr
|
|||||||
return back()->with('warning', __('contracts.edit_not_allowed_archived'));
|
return back()->with('warning', __('contracts.edit_not_allowed_archived'));
|
||||||
}
|
}
|
||||||
|
|
||||||
\DB::transaction(function () use ($request, $contract) {
|
$balanceChanged = false;
|
||||||
|
$oldBalance = null;
|
||||||
|
$newBalance = null;
|
||||||
|
|
||||||
|
\DB::transaction(function () use ($request, $contract, &$balanceChanged, &$oldBalance, &$newBalance) {
|
||||||
$contract->update([
|
$contract->update([
|
||||||
'reference' => $request->input('reference'),
|
'reference' => $request->input('reference'),
|
||||||
'type_id' => $request->input('type_id'),
|
'type_id' => $request->input('type_id'),
|
||||||
@@ -254,6 +256,7 @@ public function updateContract(ClientCase $clientCase, string $uuid, UpdateContr
|
|||||||
$accountData['type_id'] = $request->input('account_type_id');
|
$accountData['type_id'] = $request->input('account_type_id');
|
||||||
}
|
}
|
||||||
if ($currentAccount) {
|
if ($currentAccount) {
|
||||||
|
$oldBalance = (float) $currentAccount->balance_amount;
|
||||||
$currentAccount->update($accountData);
|
$currentAccount->update($accountData);
|
||||||
if (array_key_exists('balance_amount', $accountData)) {
|
if (array_key_exists('balance_amount', $accountData)) {
|
||||||
$currentAccount->forceFill(['balance_amount' => $accountData['balance_amount']])->save();
|
$currentAccount->forceFill(['balance_amount' => $accountData['balance_amount']])->save();
|
||||||
@@ -264,6 +267,10 @@ public function updateContract(ClientCase $clientCase, string $uuid, UpdateContr
|
|||||||
->update(['balance_amount' => $accountData['balance_amount'], 'updated_at' => now()]);
|
->update(['balance_amount' => $accountData['balance_amount'], 'updated_at' => now()]);
|
||||||
$freshBal = (float) optional($currentAccount->fresh())->balance_amount;
|
$freshBal = (float) optional($currentAccount->fresh())->balance_amount;
|
||||||
}
|
}
|
||||||
|
$newBalance = $freshBal;
|
||||||
|
if ($oldBalance !== $freshBal) {
|
||||||
|
$balanceChanged = true;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
$freshBal = (float) optional($currentAccount->fresh())->balance_amount;
|
$freshBal = (float) optional($currentAccount->fresh())->balance_amount;
|
||||||
}
|
}
|
||||||
@@ -276,6 +283,27 @@ public function updateContract(ClientCase $clientCase, string $uuid, UpdateContr
|
|||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Fire activity if balance changed and settings require it
|
||||||
|
if ($balanceChanged) {
|
||||||
|
$contractSetting = \App\Models\ContractSetting::query()->first();
|
||||||
|
if ($contractSetting && $contractSetting->create_activity_on_balance_change) {
|
||||||
|
$note = str_replace(
|
||||||
|
['{old_balance}', '{new_balance}', '{currency}'],
|
||||||
|
[number_format($oldBalance, 2, '.', ''), number_format($newBalance, 2, '.', ''), 'EUR'],
|
||||||
|
$contractSetting->activity_note_template ?? ''
|
||||||
|
);
|
||||||
|
\App\Models\Activity::query()->create([
|
||||||
|
'due_date' => null,
|
||||||
|
'amount' => $newBalance,
|
||||||
|
'note' => $note,
|
||||||
|
'action_id' => $contractSetting->default_action_id,
|
||||||
|
'decision_id' => $contractSetting->default_decision_id,
|
||||||
|
'client_case_id' => $contract->client_case_id,
|
||||||
|
'contract_id' => $contract->id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Preserve segment filter if present
|
// Preserve segment filter if present
|
||||||
$segment = request('segment');
|
$segment = request('segment');
|
||||||
|
|
||||||
@@ -306,11 +334,15 @@ public function storeActivity(ClientCase $clientCase, Request $request)
|
|||||||
try {
|
try {
|
||||||
$attributes = $request->validate([
|
$attributes = $request->validate([
|
||||||
'due_date' => 'nullable|date',
|
'due_date' => 'nullable|date',
|
||||||
|
'call_back_at' => 'nullable|date_format:Y-m-d H:i:s|after_or_equal:now',
|
||||||
'amount' => 'nullable|decimal:0,4',
|
'amount' => 'nullable|decimal:0,4',
|
||||||
'note' => 'nullable|string',
|
'note' => 'nullable|string',
|
||||||
'action_id' => 'exists:\App\Models\Action,id',
|
'action_id' => 'exists:\App\Models\Action,id',
|
||||||
'decision_id' => 'exists:\App\Models\Decision,id',
|
'decision_id' => 'exists:\App\Models\Decision,id',
|
||||||
'contract_uuid' => 'nullable|uuid',
|
'contract_uuid' => 'nullable|uuid',
|
||||||
|
'contract_uuids' => 'nullable|array',
|
||||||
|
'contract_uuids.*' => 'uuid',
|
||||||
|
'create_for_all_contracts' => 'nullable|boolean',
|
||||||
'phone_view' => 'nullable|boolean',
|
'phone_view' => 'nullable|boolean',
|
||||||
'send_auto_mail' => 'sometimes|boolean',
|
'send_auto_mail' => 'sometimes|boolean',
|
||||||
'attachment_document_ids' => 'sometimes|array',
|
'attachment_document_ids' => 'sometimes|array',
|
||||||
@@ -318,84 +350,132 @@ public function storeActivity(ClientCase $clientCase, Request $request)
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
$isPhoneView = $attributes['phone_view'] ?? false;
|
$isPhoneView = $attributes['phone_view'] ?? false;
|
||||||
|
$createForAll = $attributes['create_for_all_contracts'] ?? false;
|
||||||
|
$contractUuids = $attributes['contract_uuids'] ?? [];
|
||||||
|
|
||||||
// Map contract_uuid to contract_id within the same client case, if provided
|
// Determine which contracts to process
|
||||||
$contractId = null;
|
$contractIds = [];
|
||||||
if (! empty($attributes['contract_uuid'])) {
|
if ($createForAll && ! empty($contractUuids)) {
|
||||||
|
// Get all contract IDs from the provided UUIDs
|
||||||
|
$contracts = Contract::withTrashed()
|
||||||
|
->whereIn('uuid', $contractUuids)
|
||||||
|
->where('client_case_id', $clientCase->id)
|
||||||
|
->get();
|
||||||
|
$contractIds = $contracts->pluck('id')->toArray();
|
||||||
|
} elseif (! empty($contractUuids) && isset($contractUuids[0])) {
|
||||||
|
// Single contract mode
|
||||||
|
$contract = Contract::withTrashed()
|
||||||
|
->where('uuid', $contractUuids[0])
|
||||||
|
->where('client_case_id', $clientCase->id)
|
||||||
|
->first();
|
||||||
|
if ($contract) {
|
||||||
|
$contractIds = [$contract->id];
|
||||||
|
}
|
||||||
|
} elseif (! empty($attributes['contract_uuid'])) {
|
||||||
|
// Legacy single contract_uuid support
|
||||||
$contract = Contract::withTrashed()
|
$contract = Contract::withTrashed()
|
||||||
->where('uuid', $attributes['contract_uuid'])
|
->where('uuid', $attributes['contract_uuid'])
|
||||||
->where('client_case_id', $clientCase->id)
|
->where('client_case_id', $clientCase->id)
|
||||||
->first();
|
->first();
|
||||||
if ($contract) {
|
if ($contract) {
|
||||||
// Archived contracts are allowed: link activity regardless of active flag
|
$contractIds = [$contract->id];
|
||||||
$contractId = $contract->id;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create activity
|
// If no contracts specified, create a single activity without contract
|
||||||
$row = $clientCase->activities()->create([
|
if (empty($contractIds)) {
|
||||||
'due_date' => $attributes['due_date'] ?? null,
|
$contractIds = [null];
|
||||||
'amount' => $attributes['amount'] ?? null,
|
|
||||||
'note' => $attributes['note'] ?? null,
|
|
||||||
'action_id' => $attributes['action_id'],
|
|
||||||
'decision_id' => $attributes['decision_id'],
|
|
||||||
'contract_id' => $contractId,
|
|
||||||
]);
|
|
||||||
|
|
||||||
if ($isPhoneView && $contractId) {
|
|
||||||
$fieldJob = $contract->fieldJobs()
|
|
||||||
->whereNull('completed_at')
|
|
||||||
->whereNull('cancelled_at')
|
|
||||||
->where('assigned_user_id', \Auth::id())
|
|
||||||
->orderByDesc('id')
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($fieldJob) {
|
|
||||||
$fieldJob->update([
|
|
||||||
'added_activity' => true,
|
|
||||||
'last_activity' => $row->created_at,
|
|
||||||
]);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger()->info('Activity successfully inserted', $attributes);
|
$createdActivities = [];
|
||||||
|
$sendFlag = (bool) ($attributes['send_auto_mail'] ?? true);
|
||||||
|
|
||||||
// Auto mail dispatch (best-effort)
|
// Disable auto mail if creating activities for multiple contracts
|
||||||
try {
|
if ($sendFlag && count($contractIds) > 1) {
|
||||||
$sendFlag = (bool) ($attributes['send_auto_mail'] ?? true);
|
$sendFlag = false;
|
||||||
$row->load(['decision', 'clientCase.client.person', 'clientCase.person', 'contract']);
|
logger()->info('Auto mail disabled: multiple contracts selected', ['contract_count' => count($contractIds)]);
|
||||||
// Filter attachments to those belonging to the selected contract
|
}
|
||||||
$attachmentIds = collect($attributes['attachment_document_ids'] ?? [])
|
|
||||||
->filter()
|
foreach ($contractIds as $contractId) {
|
||||||
->map(fn ($v) => (int) $v)
|
// Create activity
|
||||||
->values();
|
$row = $clientCase->activities()->create([
|
||||||
$validAttachmentIds = collect();
|
'due_date' => $attributes['due_date'] ?? null,
|
||||||
if ($attachmentIds->isNotEmpty() && $contractId) {
|
'call_back_at' => $attributes['call_back_at'] ?? null,
|
||||||
$validAttachmentIds = Document::query()
|
'amount' => $attributes['amount'] ?? null,
|
||||||
->where('documentable_type', Contract::class)
|
'note' => $attributes['note'] ?? null,
|
||||||
->where('documentable_id', $contractId)
|
'action_id' => $attributes['action_id'],
|
||||||
->whereIn('id', $attachmentIds)
|
'decision_id' => $attributes['decision_id'],
|
||||||
->pluck('id');
|
'contract_id' => $contractId,
|
||||||
}
|
|
||||||
$result = app(\App\Services\AutoMailDispatcher::class)->maybeQueue($row, $sendFlag, [
|
|
||||||
'attachment_ids' => $validAttachmentIds->all(),
|
|
||||||
]);
|
]);
|
||||||
if (($result['skipped'] ?? null) === 'missing-contract' && $sendFlag) {
|
|
||||||
// If template requires contract and user attempted to send, surface a validation message
|
$createdActivities[] = $row;
|
||||||
return back()->with('warning', 'Email not queued: required contract is missing for the selected template.');
|
|
||||||
|
if ($isPhoneView && $contractId) {
|
||||||
|
$contract = Contract::find($contractId);
|
||||||
|
if ($contract) {
|
||||||
|
$fieldJob = $contract->fieldJobs()
|
||||||
|
->whereNull('completed_at')
|
||||||
|
->whereNull('cancelled_at')
|
||||||
|
->where('assigned_user_id', \Auth::id())
|
||||||
|
->orderByDesc('id')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($fieldJob) {
|
||||||
|
$fieldJob->update([
|
||||||
|
'added_activity' => true,
|
||||||
|
'last_activity' => $row->created_at,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (($result['skipped'] ?? null) === 'no-recipients' && $sendFlag) {
|
|
||||||
return back()->with('warning', 'Email not queued: no eligible client emails to receive auto mails.');
|
logger()->info('Activity successfully inserted', array_merge($attributes, ['contract_id' => $contractId]));
|
||||||
|
|
||||||
|
// Auto mail dispatch (best-effort)
|
||||||
|
try {
|
||||||
|
$row->load(['decision', 'clientCase.client.person', 'clientCase.person', 'contract']);
|
||||||
|
// Filter attachments to those belonging to the selected contract
|
||||||
|
$attachmentIds = collect($attributes['attachment_document_ids'] ?? [])
|
||||||
|
->filter()
|
||||||
|
->map(fn ($v) => (int) $v)
|
||||||
|
->values();
|
||||||
|
$validAttachmentIds = collect();
|
||||||
|
if ($attachmentIds->isNotEmpty() && $contractId) {
|
||||||
|
$validAttachmentIds = Document::query()
|
||||||
|
->where('documentable_type', Contract::class)
|
||||||
|
->where('documentable_id', $contractId)
|
||||||
|
->whereIn('id', $attachmentIds)
|
||||||
|
->pluck('id');
|
||||||
|
$validAttachmentIds = Document::query()
|
||||||
|
->where('documentable_type', Contract::class)
|
||||||
|
->where('documentable_id', $contractId)
|
||||||
|
->whereIn('id', $attachmentIds)
|
||||||
|
->pluck('id');
|
||||||
|
}
|
||||||
|
$result = app(\App\Services\AutoMailDispatcher::class)->maybeQueue($row, $sendFlag, [
|
||||||
|
'attachment_ids' => $validAttachmentIds->all(),
|
||||||
|
]);
|
||||||
|
if (($result['skipped'] ?? null) === 'missing-contract' && $sendFlag) {
|
||||||
|
// If template requires contract and user attempted to send, surface a validation message
|
||||||
|
logger()->warning('Email not queued: required contract is missing for the selected template.');
|
||||||
|
}
|
||||||
|
if (($result['skipped'] ?? null) === 'no-recipients' && $sendFlag) {
|
||||||
|
logger()->warning('Email not queued: no eligible client emails to receive auto mails.');
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Do not fail activity creation due to mailing issues
|
||||||
|
logger()->warning('Auto mail dispatch failed: '.$e->getMessage());
|
||||||
}
|
}
|
||||||
} catch (\Throwable $e) {
|
|
||||||
// Do not fail activity creation due to mailing issues
|
|
||||||
logger()->warning('Auto mail dispatch failed: '.$e->getMessage());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$activityCount = count($createdActivities);
|
||||||
|
$successMessage = $activityCount > 1
|
||||||
|
? "Successfully created {$activityCount} activities!"
|
||||||
|
: 'Successfully created activity!';
|
||||||
|
|
||||||
// Stay on the current page (desktop or phone) instead of forcing a redirect to the desktop route.
|
// Stay on the current page (desktop or phone) instead of forcing a redirect to the desktop route.
|
||||||
// Use 303 to align with Inertia's recommended POST/Redirect/GET behavior.
|
// Use 303 to align with Inertia's recommended POST/Redirect/GET behavior.
|
||||||
return back(303)->with('success', 'Successful created!')->with('flash_method', 'POST');
|
return back(303)->with('success', $successMessage)->with('flash_method', 'POST');
|
||||||
} catch (QueryException $e) {
|
} catch (QueryException $e) {
|
||||||
logger()->error('Database error occurred:', ['error' => $e->getMessage()]);
|
logger()->error('Database error occurred:', ['error' => $e->getMessage()]);
|
||||||
|
|
||||||
@@ -552,9 +632,9 @@ public function storeDocument(ClientCase $clientCase, Request $request)
|
|||||||
$contract = null;
|
$contract = null;
|
||||||
if (! empty($validated['contract_uuid'])) {
|
if (! empty($validated['contract_uuid'])) {
|
||||||
$contract = $clientCase->contracts()->where('uuid', $validated['contract_uuid'])->first();
|
$contract = $clientCase->contracts()->where('uuid', $validated['contract_uuid'])->first();
|
||||||
if ($contract && ! $contract->active) {
|
/*if ($contract && ! $contract->active) {
|
||||||
return back()->with('warning', __('contracts.document_not_allowed_archived'));
|
return back()->with('warning', __('contracts.document_not_allowed_archived'));
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
$directory = $contract
|
$directory = $contract
|
||||||
? ('contracts/'.$contract->uuid.'/documents')
|
? ('contracts/'.$contract->uuid.'/documents')
|
||||||
@@ -775,9 +855,8 @@ public function show(ClientCase $clientCase)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get contracts using service
|
// Get contracts using service
|
||||||
$contractsPerPage = request()->integer('contracts_per_page', 10);
|
$contracts = $this->caseDataService->getContracts($case, $segmentId);
|
||||||
$contracts = $this->caseDataService->getContracts($case, $segmentId, $contractsPerPage);
|
$contractIds = collect($contracts)->pluck('id')->all();
|
||||||
$contractIds = collect($contracts->items())->pluck('id')->all();
|
|
||||||
|
|
||||||
// Get activities using service
|
// Get activities using service
|
||||||
$activitiesPerPage = request()->integer('activities_per_page', 15);
|
$activitiesPerPage = request()->integer('activities_per_page', 15);
|
||||||
@@ -818,11 +897,14 @@ public function show(ClientCase $clientCase)
|
|||||||
'decisions.emailTemplate' => function ($q) {
|
'decisions.emailTemplate' => function ($q) {
|
||||||
$q->select('id', 'name', 'entity_types', 'allow_attachments');
|
$q->select('id', 'name', 'entity_types', 'allow_attachments');
|
||||||
},
|
},
|
||||||
|
'decisions.events' => function ($q) {
|
||||||
|
$q->select('events.id', 'events.key', 'events.name');
|
||||||
|
},
|
||||||
])
|
])
|
||||||
->get(['id', 'name', 'color_tag', 'segment_id']),
|
->get(['id', 'name', 'color_tag', 'segment_id']),
|
||||||
'types' => $types,
|
'types' => $types,
|
||||||
'segments' => $case->segments()->wherePivot('active', true)->get(['segments.id', 'segments.name']),
|
'segments' => $case->segments()->wherePivot('active', true)->get(['segments.id', 'segments.name']),
|
||||||
'all_segments' => \App\Models\Segment::query()->where('active', true)->get(['id', 'name']),
|
'all_segments' => Segment::query()->where('active', true)->get(['id', 'name']),
|
||||||
'current_segment' => $currentSegment,
|
'current_segment' => $currentSegment,
|
||||||
'sms_profiles' => \App\Models\SmsProfile::query()
|
'sms_profiles' => \App\Models\SmsProfile::query()
|
||||||
->select(['id', 'name', 'default_sender_id'])
|
->select(['id', 'name', 'default_sender_id'])
|
||||||
@@ -831,14 +913,27 @@ public function show(ClientCase $clientCase)
|
|||||||
->get(),
|
->get(),
|
||||||
'sms_senders' => \App\Models\SmsSender::query()
|
'sms_senders' => \App\Models\SmsSender::query()
|
||||||
->select(['id', 'profile_id'])
|
->select(['id', 'profile_id'])
|
||||||
->addSelect(\DB::raw('sname as name'))
|
->selectRaw('sname as name')
|
||||||
->addSelect(\DB::raw('phone_number as phone'))
|
->selectRaw('phone_number as phone')
|
||||||
->orderBy('sname')
|
->orderBy('sname')
|
||||||
->get(),
|
->get(),
|
||||||
'sms_templates' => \App\Models\SmsTemplate::query()
|
'sms_templates' => \App\Models\SmsTemplate::query()
|
||||||
->select(['id', 'name', 'content', 'allow_custom_body'])
|
->select(['id', 'name', 'content', 'allow_custom_body'])
|
||||||
->orderBy('name')
|
->orderBy('name')
|
||||||
->get(),
|
->get(),
|
||||||
|
'email_templates' => \App\Models\EmailTemplate::query()
|
||||||
|
->select(['id', 'name', 'subject_template', 'text_template', 'action_id', 'decision_id'])
|
||||||
|
->where('active', true)
|
||||||
|
->where('client', false)
|
||||||
|
->orderBy('name')
|
||||||
|
->get(),
|
||||||
|
'mail_profiles' => \App\Models\MailProfile::query()
|
||||||
|
->select(['id', 'name'])
|
||||||
|
->where('active', true)
|
||||||
|
->orderBy('priority')
|
||||||
|
->orderBy('name')
|
||||||
|
->get(),
|
||||||
|
'auto_mail_decisions' => \App\Models\Decision::query()->where('auto_mail', true)->orderBy('name')->get(['id', 'name']),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1029,6 +1124,158 @@ public function archiveContract(ClientCase $clientCase, string $uuid, Request $r
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Archive multiple contracts in a batch operation
|
||||||
|
*/
|
||||||
|
public function archiveBatch(Request $request)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'contracts' => 'required|array',
|
||||||
|
'contracts.*' => 'required|uuid|exists:contracts,uuid',
|
||||||
|
'reactivate' => 'boolean',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$reactivate = $validated['reactivate'] ?? false;
|
||||||
|
|
||||||
|
// Get archive setting
|
||||||
|
$setting = \App\Models\ArchiveSetting::query()
|
||||||
|
->where('enabled', true)
|
||||||
|
->whereIn('strategy', ['immediate', 'manual'])
|
||||||
|
->where('reactivate', $reactivate)
|
||||||
|
->orderByDesc('id')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $setting) {
|
||||||
|
\Log::warning('No archive settings found for batch archive');
|
||||||
|
|
||||||
|
return back()->with('flash', [
|
||||||
|
'error' => 'No archive settings found',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$executor = app(\App\Services\Archiving\ArchiveExecutor::class);
|
||||||
|
$successCount = 0;
|
||||||
|
$skippedCount = 0;
|
||||||
|
$errors = [];
|
||||||
|
|
||||||
|
foreach ($validated['contracts'] as $contractUuid) {
|
||||||
|
try {
|
||||||
|
$contract = Contract::where('uuid', $contractUuid)->firstOrFail();
|
||||||
|
|
||||||
|
// Skip if contract is already archived (active = 0)
|
||||||
|
if (! $contract->active) {
|
||||||
|
$skippedCount++;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$clientCase = $contract->clientCase;
|
||||||
|
|
||||||
|
$context = [
|
||||||
|
'contract_id' => $contract->id,
|
||||||
|
'client_case_id' => $clientCase->id,
|
||||||
|
'account_id' => $contract->account->id ?? null,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Execute archive setting
|
||||||
|
$executor->executeSetting($setting, $context, \Auth::id());
|
||||||
|
|
||||||
|
// Transaction for segment updates and activity logging
|
||||||
|
\DB::transaction(function () use ($contract, $clientCase, $setting, $reactivate) {
|
||||||
|
// Create activity log
|
||||||
|
if ($setting->action_id && $setting->decision_id) {
|
||||||
|
$activityData = [
|
||||||
|
'client_case_id' => $clientCase->id,
|
||||||
|
'action_id' => $setting->action_id,
|
||||||
|
'decision_id' => $setting->decision_id,
|
||||||
|
'note' => ($reactivate)
|
||||||
|
? "Ponovno aktivirana pogodba $contract->reference"
|
||||||
|
: "Arhivirana pogodba $contract->reference",
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
\App\Models\Activity::create($activityData);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
\Log::warning('Activity could not be created during batch archive');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move to archive segment if specified
|
||||||
|
if ($setting->segment_id) {
|
||||||
|
$segmentId = $setting->segment_id;
|
||||||
|
|
||||||
|
// Deactivate all current segments
|
||||||
|
$contract->segments()
|
||||||
|
->allRelatedIds()
|
||||||
|
->map(fn (int $val) => $contract->segments()->updateExistingPivot($val, [
|
||||||
|
'active' => false,
|
||||||
|
'updated_at' => now(),
|
||||||
|
]));
|
||||||
|
|
||||||
|
// Activate archive segment
|
||||||
|
if ($contract->attachedSegments()->find($segmentId)->pluck('id')->isNotEmpty()) {
|
||||||
|
$contract->attachedSegments()->updateExistingPivot($segmentId, [
|
||||||
|
'active' => true,
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
} else {
|
||||||
|
$contract->segments()->attach($segmentId, [
|
||||||
|
'active' => true,
|
||||||
|
'created_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel pending field jobs
|
||||||
|
$contract->fieldJobs()
|
||||||
|
->whereNull('completed_at')
|
||||||
|
->whereNull('cancelled_at')
|
||||||
|
->update([
|
||||||
|
'cancelled_at' => date('Y-m-d'),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
$successCount++;
|
||||||
|
} catch (Exception $e) {
|
||||||
|
\Log::error('Error archiving contract in batch', [
|
||||||
|
'uuid' => $contractUuid,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
$errors[] = [
|
||||||
|
'uuid' => $contractUuid,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count($errors) > 0) {
|
||||||
|
$message = "Archived $successCount contracts";
|
||||||
|
if ($skippedCount > 0) {
|
||||||
|
$message .= ", skipped $skippedCount already archived";
|
||||||
|
}
|
||||||
|
$message .= ', '.count($errors).' failed';
|
||||||
|
|
||||||
|
return back()->with('flash', [
|
||||||
|
'error' => $message,
|
||||||
|
'details' => $errors,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$message = $reactivate
|
||||||
|
? "Successfully reactivated $successCount contracts"
|
||||||
|
: "Successfully archived $successCount contracts";
|
||||||
|
|
||||||
|
if ($skippedCount > 0) {
|
||||||
|
$message .= " ($skippedCount already archived)";
|
||||||
|
}
|
||||||
|
|
||||||
|
return back()->with('flash', [
|
||||||
|
'success' => $message,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Emergency: recreate a missing / soft-deleted person for a client case and re-link related data.
|
* Emergency: recreate a missing / soft-deleted person for a client case and re-link related data.
|
||||||
*/
|
*/
|
||||||
@@ -1145,10 +1392,10 @@ public function sendSmsToPhone(ClientCase $clientCase, Request $request, int $ph
|
|||||||
if (! empty($validated['sender_id'])) {
|
if (! empty($validated['sender_id'])) {
|
||||||
$sender = \App\Models\SmsSender::query()->find($validated['sender_id']);
|
$sender = \App\Models\SmsSender::query()->find($validated['sender_id']);
|
||||||
if (! $sender) {
|
if (! $sender) {
|
||||||
return back()->with('error', 'Izbran pošiljatelj ne obstaja.');
|
return back()->with('error', 'Izbran pošiljatelj ne obstaja.');
|
||||||
}
|
}
|
||||||
if ($profile && (int) $sender->profile_id !== (int) $profile->id) {
|
if ($profile && (int) $sender->profile_id !== (int) $profile->id) {
|
||||||
return back()->with('error', 'Izbran pošiljatelj ne pripada izbranemu profilu.');
|
return back()->with('error', 'Izbran pošiljatelj ne pripada izbranemu profilu.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (! $profile) {
|
if (! $profile) {
|
||||||
@@ -1191,7 +1438,7 @@ public function sendSmsToPhone(ClientCase $clientCase, Request $request, int $ph
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create an activity before sending
|
// Create an activity before sending
|
||||||
$activityNote = sprintf('Št: %s | Telo: %s', (string) $phone->nu, (string) $validated['message']);
|
$activityNote = sprintf('Št: %s | Telo: %s', (string) $phone->nu, (string) $validated['message']);
|
||||||
$activityData = [
|
$activityData = [
|
||||||
'note' => $activityNote,
|
'note' => $activityNote,
|
||||||
'user_id' => optional($request->user())->id,
|
'user_id' => optional($request->user())->id,
|
||||||
@@ -1340,6 +1587,161 @@ public function previewSms(ClientCase $clientCase, Request $request, SmsService
|
|||||||
* Extracts 'value' from objects with {title, value, type} structure.
|
* Extracts 'value' from objects with {title, value, type} structure.
|
||||||
* Also creates direct access aliases for nested fields (skipping numeric keys).
|
* Also creates direct access aliases for nested fields (skipping numeric keys).
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Render an email template preview with context from the client case.
|
||||||
|
*/
|
||||||
|
public function previewEmailForEmail(ClientCase $clientCase, Request $request, int $email_id): \Illuminate\Http\JsonResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'template_id' => ['required', 'integer', 'exists:email_templates,id'],
|
||||||
|
'contract_uuid' => ['sometimes', 'nullable', 'uuid'],
|
||||||
|
'body_text' => ['sometimes', 'nullable', 'string', 'max:10000'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$email = \App\Models\Email::query()
|
||||||
|
->where('id', $email_id)
|
||||||
|
->where('person_id', $clientCase->person_id)
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$template = \App\Models\EmailTemplate::findOrFail((int) $validated['template_id']);
|
||||||
|
|
||||||
|
$contract = null;
|
||||||
|
if (! empty($validated['contract_uuid'])) {
|
||||||
|
$contract = $clientCase->contracts()
|
||||||
|
->where('uuid', $validated['contract_uuid'])
|
||||||
|
->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
$ctx = $this->buildCaseEmailContext($clientCase, $contract);
|
||||||
|
$ctx['body_text'] = (string) ($validated['body_text'] ?? '');
|
||||||
|
|
||||||
|
$renderer = app(\App\Services\EmailTemplateRenderer::class);
|
||||||
|
$rendered = $renderer->render([
|
||||||
|
'subject' => (string) $template->subject_template,
|
||||||
|
'html' => (string) $template->html_template,
|
||||||
|
'text' => (string) $template->text_template,
|
||||||
|
], $ctx);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'subject' => $rendered['subject'] ?? '',
|
||||||
|
'html' => (string) ($rendered['html'] ?? ''),
|
||||||
|
'has_body_text' => (bool) preg_match('/{{\s*body_text\s*}}/', (string) $template->html_template),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a (possibly templated) email to a person email address belonging to this case.
|
||||||
|
*/
|
||||||
|
public function sendEmailToEmail(ClientCase $clientCase, Request $request, int $email_id)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'subject' => ['required', 'string', 'max:255'],
|
||||||
|
'html_body' => ['nullable', 'string'],
|
||||||
|
'body_text' => ['nullable', 'string', 'max:10000'],
|
||||||
|
'template_id' => ['sometimes', 'nullable', 'integer', 'exists:email_templates,id'],
|
||||||
|
'mail_profile_id' => ['sometimes', 'nullable', 'integer', 'exists:mail_profiles,id'],
|
||||||
|
'contract_uuid' => ['sometimes', 'nullable', 'uuid'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Ensure the email belongs to the person of this case
|
||||||
|
$email = \App\Models\Email::query()
|
||||||
|
->where('id', $email_id)
|
||||||
|
->where('person_id', $clientCase->person_id)
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$to = (string) $email->value;
|
||||||
|
|
||||||
|
/** @var \App\Models\MailProfile|null $mailProfile */
|
||||||
|
$mailProfile = ! empty($validated['mail_profile_id'])
|
||||||
|
? \App\Models\MailProfile::query()->where('id', $validated['mail_profile_id'])->where('active', true)->first()
|
||||||
|
: \App\Models\MailProfile::query()->where('active', true)->orderBy('priority')->orderBy('id')->first();
|
||||||
|
|
||||||
|
if (! $mailProfile) {
|
||||||
|
return back()->with('error', 'Ni aktivnega e-poštnega profila.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$contract = null;
|
||||||
|
if (! empty($validated['contract_uuid'])) {
|
||||||
|
$contract = $clientCase->contracts()->where('uuid', $validated['contract_uuid'])->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
$htmlBody = (string) ($validated['html_body'] ?? '');
|
||||||
|
$bodyText = (string) ($validated['body_text'] ?? '');
|
||||||
|
|
||||||
|
// Apply {{body_text}} substitution if the html body contains the placeholder
|
||||||
|
if ($bodyText !== '' && preg_match('/{{\s*body_text\s*}}/', $htmlBody)) {
|
||||||
|
$renderer = app(\App\Services\EmailTemplateRenderer::class);
|
||||||
|
$htmlBody = $renderer->applyBodyText($htmlBody, $bodyText, html: true) ?? $htmlBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
$subject = (string) $validated['subject'];
|
||||||
|
|
||||||
|
$log = new \App\Models\EmailLog;
|
||||||
|
$log->fill([
|
||||||
|
'uuid' => (string) \Illuminate\Support\Str::uuid(),
|
||||||
|
'template_id' => $validated['template_id'] ?? null,
|
||||||
|
'mail_profile_id' => $mailProfile->id,
|
||||||
|
'to_email' => $to,
|
||||||
|
'to_recipients' => [$to],
|
||||||
|
'subject' => $subject,
|
||||||
|
'body_html_hash' => $htmlBody !== '' ? hash('sha256', $htmlBody) : null,
|
||||||
|
'body_text_preview' => null,
|
||||||
|
'embed_mode' => 'base64',
|
||||||
|
'status' => \App\Models\EmailLogStatus::Queued,
|
||||||
|
'queued_at' => now(),
|
||||||
|
'client_id' => $clientCase->client_id,
|
||||||
|
'client_case_id' => $clientCase->id,
|
||||||
|
'contract_id' => $contract?->id,
|
||||||
|
'ip' => $request->ip(),
|
||||||
|
]);
|
||||||
|
$log->save();
|
||||||
|
|
||||||
|
$log->body()->create([
|
||||||
|
'body_html' => $htmlBody,
|
||||||
|
'body_text' => $bodyText,
|
||||||
|
'inline_css' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
dispatch(new \App\Jobs\SendEmailTemplateJob($log->id));
|
||||||
|
|
||||||
|
// Create activity if template has action/decision
|
||||||
|
if (! empty($validated['template_id'])) {
|
||||||
|
$template = \App\Models\EmailTemplate::find((int) $validated['template_id']);
|
||||||
|
if ($template && ($template->action_id || $template->decision_id)) {
|
||||||
|
$activity = $clientCase->activities()->create(array_filter([
|
||||||
|
'contract_id' => $contract?->id,
|
||||||
|
'action_id' => $template->action_id,
|
||||||
|
'decision_id' => $template->decision_id,
|
||||||
|
'note' => 'Poslano: '.$to.($bodyText !== '' ? ' | Vsebina: '.mb_strimwidth($bodyText, 0, 500, '…') : ''),
|
||||||
|
'user_id' => optional($request->user())->id,
|
||||||
|
], fn ($v) => ! is_null($v)));
|
||||||
|
$activity->emailLogs()->attach($log->id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return back()->with('success', "E-pošta poslana na {$to}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a template rendering context from the given client case and optional contract.
|
||||||
|
*/
|
||||||
|
private function buildCaseEmailContext(ClientCase $clientCase, ?\App\Models\Contract $contract = null): array
|
||||||
|
{
|
||||||
|
$clientCase->loadMissing('client.person');
|
||||||
|
$ctx = [
|
||||||
|
'client_case' => $clientCase,
|
||||||
|
'client' => $clientCase->client,
|
||||||
|
'person' => optional($clientCase->client)->person,
|
||||||
|
'mail_profile' => \App\Models\MailProfile::query()->where('active', true)->orderBy('priority')->orderBy('id')->first(),
|
||||||
|
];
|
||||||
|
if ($contract) {
|
||||||
|
$contract->loadMissing(['clientCase.client.person', 'account.type']);
|
||||||
|
$ctx['contract'] = $contract;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $ctx;
|
||||||
|
}
|
||||||
|
|
||||||
private function flattenMeta(array $meta, string $prefix = ''): array
|
private function flattenMeta(array $meta, string $prefix = ''): array
|
||||||
{
|
{
|
||||||
$result = [];
|
$result = [];
|
||||||
|
|||||||
@@ -2,11 +2,15 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Exports\ClientContractsExport;
|
||||||
|
use App\Http\Requests\ExportClientContractsRequest;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
use App\Services\ReferenceDataCache;
|
use App\Services\ReferenceDataCache;
|
||||||
use DB;
|
use DB;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
|
use Maatwebsite\Excel\Facades\Excel;
|
||||||
|
|
||||||
class ClientController extends Controller
|
class ClientController extends Controller
|
||||||
{
|
{
|
||||||
@@ -23,7 +27,7 @@ public function index(Client $client, Request $request)
|
|||||||
->where('person.full_name', 'ilike', '%'.$search.'%')
|
->where('person.full_name', 'ilike', '%'.$search.'%')
|
||||||
->groupBy('clients.id');
|
->groupBy('clients.id');
|
||||||
})
|
})
|
||||||
->where('clients.active', 1)
|
// ->where('clients.active', 1)
|
||||||
// Use LEFT JOINs for aggregated data to avoid subqueries
|
// Use LEFT JOINs for aggregated data to avoid subqueries
|
||||||
->leftJoin('client_cases', 'client_cases.client_id', '=', 'clients.id')
|
->leftJoin('client_cases', 'client_cases.client_id', '=', 'clients.id')
|
||||||
->leftJoin('contracts', function ($join) {
|
->leftJoin('contracts', function ($join) {
|
||||||
@@ -36,18 +40,14 @@ public function index(Client $client, Request $request)
|
|||||||
})
|
})
|
||||||
->leftJoin('accounts', 'accounts.contract_id', '=', 'contracts.id')
|
->leftJoin('accounts', 'accounts.contract_id', '=', 'contracts.id')
|
||||||
->groupBy('clients.id')
|
->groupBy('clients.id')
|
||||||
->addSelect([
|
->selectRaw('COUNT(DISTINCT CASE WHEN contract_segment.id IS NOT NULL THEN client_cases.id END) as cases_with_active_contracts_count')
|
||||||
// Number of client cases for this client that have at least one active contract
|
->selectRaw('COALESCE(SUM(CASE WHEN contract_segment.id IS NOT NULL THEN accounts.balance_amount END), 0) as active_contracts_balance_sum')
|
||||||
DB::raw('COUNT(DISTINCT CASE WHEN contract_segment.id IS NOT NULL THEN client_cases.id END) as cases_with_active_contracts_count'),
|
|
||||||
// Sum of account balances for active contracts
|
|
||||||
DB::raw('COALESCE(SUM(CASE WHEN contract_segment.id IS NOT NULL THEN accounts.balance_amount END), 0) as active_contracts_balance_sum'),
|
|
||||||
])
|
|
||||||
->with('person')
|
->with('person')
|
||||||
->orderByDesc('clients.created_at');
|
->orderByDesc('clients.created_at');
|
||||||
|
|
||||||
return Inertia::render('Client/Index', [
|
return Inertia::render('Client/Index', [
|
||||||
'clients' => $query
|
'clients' => $query
|
||||||
->paginate($request->integer('per_page', 15))
|
->paginate($request->integer('per_page', default: 100))
|
||||||
->withQueryString(),
|
->withQueryString(),
|
||||||
'filters' => $request->only(['search']),
|
'filters' => $request->only(['search']),
|
||||||
]);
|
]);
|
||||||
@@ -67,6 +67,7 @@ public function show(Client $client, Request $request)
|
|||||||
|
|
||||||
return Inertia::render('Client/Show', [
|
return Inertia::render('Client/Show', [
|
||||||
'client' => $data,
|
'client' => $data,
|
||||||
|
'auto_mail_decisions' => \App\Models\Decision::query()->where('auto_mail', true)->orderBy('name')->get(['id', 'name']),
|
||||||
'client_cases' => $data->clientCases()
|
'client_cases' => $data->clientCases()
|
||||||
->select('client_cases.*')
|
->select('client_cases.*')
|
||||||
->when($request->input('search'), function ($que, $search) {
|
->when($request->input('search'), function ($que, $search) {
|
||||||
@@ -84,10 +85,8 @@ public function show(Client $client, Request $request)
|
|||||||
})
|
})
|
||||||
->leftJoin('accounts', 'accounts.contract_id', '=', 'contracts.id')
|
->leftJoin('accounts', 'accounts.contract_id', '=', 'contracts.id')
|
||||||
->groupBy('client_cases.id')
|
->groupBy('client_cases.id')
|
||||||
->addSelect([
|
->selectRaw('COUNT(DISTINCT CASE WHEN contract_segment.id IS NOT NULL THEN contracts.id END) as active_contracts_count')
|
||||||
\DB::raw('COUNT(DISTINCT CASE WHEN contract_segment.id IS NOT NULL THEN contracts.id END) as active_contracts_count'),
|
->selectRaw('COALESCE(SUM(CASE WHEN contract_segment.id IS NOT NULL THEN accounts.balance_amount END), 0) as active_contracts_balance_sum')
|
||||||
\DB::raw('COALESCE(SUM(CASE WHEN contract_segment.id IS NOT NULL THEN accounts.balance_amount END), 0) as active_contracts_balance_sum'),
|
|
||||||
])
|
|
||||||
->with(['person', 'client.person'])
|
->with(['person', 'client.person'])
|
||||||
->where('client_cases.active', 1)
|
->where('client_cases.active', 1)
|
||||||
->orderByDesc('client_cases.created_at')
|
->orderByDesc('client_cases.created_at')
|
||||||
@@ -137,6 +136,7 @@ public function contracts(Client $client, Request $request)
|
|||||||
->with([
|
->with([
|
||||||
'clientCase:id,uuid,person_id',
|
'clientCase:id,uuid,person_id',
|
||||||
'clientCase.person:id,full_name',
|
'clientCase.person:id,full_name',
|
||||||
|
'clientCase.person.address',
|
||||||
'segments' => function ($q) {
|
'segments' => function ($q) {
|
||||||
$q->wherePivot('active', true)->select('segments.id', 'segments.name');
|
$q->wherePivot('active', true)->select('segments.id', 'segments.name');
|
||||||
},
|
},
|
||||||
@@ -157,6 +157,7 @@ public function contracts(Client $client, Request $request)
|
|||||||
|
|
||||||
return Inertia::render('Client/Contracts', [
|
return Inertia::render('Client/Contracts', [
|
||||||
'client' => $data,
|
'client' => $data,
|
||||||
|
'auto_mail_decisions' => \App\Models\Decision::query()->where('auto_mail', true)->orderBy('name')->get(['id', 'name']),
|
||||||
'contracts' => $contractsQuery
|
'contracts' => $contractsQuery
|
||||||
->paginate($perPage, ['*'], 'contracts_page', $pageNumber)
|
->paginate($perPage, ['*'], 'contracts_page', $pageNumber)
|
||||||
->withQueryString(),
|
->withQueryString(),
|
||||||
@@ -166,6 +167,84 @@ public function contracts(Client $client, Request $request)
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function exportContracts(ExportClientContractsRequest $request, Client $client)
|
||||||
|
{
|
||||||
|
$data = $request->validated();
|
||||||
|
$columns = array_values(array_unique($data['columns']));
|
||||||
|
|
||||||
|
$from = $data['from'] ?? null;
|
||||||
|
$to = $data['to'] ?? null;
|
||||||
|
$search = $data['search'] ?? null;
|
||||||
|
$segmentsParam = $data['segments'] ?? null;
|
||||||
|
$segmentIds = $segmentsParam ? array_filter(explode(',', $segmentsParam)) : [];
|
||||||
|
|
||||||
|
$query = \App\Models\Contract::query()
|
||||||
|
->whereHas('clientCase', function ($q) use ($client) {
|
||||||
|
$q->where('client_id', $client->id);
|
||||||
|
})
|
||||||
|
->with([
|
||||||
|
'clientCase:id,uuid,person_id',
|
||||||
|
'clientCase.person:id,full_name',
|
||||||
|
'clientCase.person.address',
|
||||||
|
'segments' => function ($q) {
|
||||||
|
$q->wherePivot('active', true)->select('segments.id', 'segments.name');
|
||||||
|
},
|
||||||
|
'account:id,accounts.contract_id,balance_amount',
|
||||||
|
])
|
||||||
|
->select(['id', 'uuid', 'reference', 'start_date', 'client_case_id'])
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->when($from || $to, function ($q) use ($from, $to) {
|
||||||
|
if (! empty($from)) {
|
||||||
|
$q->whereDate('start_date', '>=', $from);
|
||||||
|
}
|
||||||
|
if (! empty($to)) {
|
||||||
|
$q->whereDate('start_date', '<=', $to);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
->when($search, function ($q) use ($search) {
|
||||||
|
$q->where(function ($inner) use ($search) {
|
||||||
|
$inner->where('reference', 'ilike', '%'.$search.'%')
|
||||||
|
->orWhereHas('clientCase.person', function ($p) use ($search) {
|
||||||
|
$p->where('full_name', 'ilike', '%'.$search.'%');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->when($segmentIds, function ($q) use ($segmentIds) {
|
||||||
|
$q->whereHas('segments', function ($s) use ($segmentIds) {
|
||||||
|
$s->whereIn('segments.id', $segmentIds)
|
||||||
|
->where('contract_segment.active', true);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
->orderByDesc('start_date');
|
||||||
|
|
||||||
|
if (($data['scope'] ?? ExportClientContractsRequest::SCOPE_ALL) === ExportClientContractsRequest::SCOPE_CURRENT) {
|
||||||
|
$page = max(1, (int) ($data['page'] ?? 1));
|
||||||
|
$perPage = max(1, min(200, (int) ($data['per_page'] ?? 15)));
|
||||||
|
$query->forPage($page, $perPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
$filename = $this->buildExportFilename($client);
|
||||||
|
|
||||||
|
return Excel::download(new ClientContractsExport($query, $columns), $filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildExportFilename(Client $client): string
|
||||||
|
{
|
||||||
|
$datePrefix = now()->format('dmy');
|
||||||
|
$clientName = $this->slugify($client->person?->full_name ?? 'stranka');
|
||||||
|
|
||||||
|
return sprintf('%s_%s-Pogodbe.xlsx', $datePrefix, $clientName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function slugify(?string $value): string
|
||||||
|
{
|
||||||
|
if (empty($value)) {
|
||||||
|
return 'data';
|
||||||
|
}
|
||||||
|
|
||||||
|
return Str::slug($value, '-') ?: 'data';
|
||||||
|
}
|
||||||
|
|
||||||
public function store(Request $request)
|
public function store(Request $request)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
class ContractSettingController extends Controller
|
||||||
|
{
|
||||||
|
public function edit(): \Inertia\Response
|
||||||
|
{
|
||||||
|
$setting = \App\Models\ContractSetting::query()->first();
|
||||||
|
if (! $setting) {
|
||||||
|
$setting = \App\Models\ContractSetting::query()->create([
|
||||||
|
'create_activity_on_balance_change' => false,
|
||||||
|
'default_action_id' => null,
|
||||||
|
'default_decision_id' => null,
|
||||||
|
'activity_note_template' => 'Sprememba stanja pogodbe: {old_balance} → {new_balance} {currency}',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$decisions = \App\Models\Decision::query()->orderBy('name')->get(['id', 'name']);
|
||||||
|
$actions = \App\Models\Action::query()
|
||||||
|
->with(['decisions:id'])
|
||||||
|
->orderBy('name')
|
||||||
|
->get()
|
||||||
|
->map(function (\App\Models\Action $a) {
|
||||||
|
return [
|
||||||
|
'id' => $a->id,
|
||||||
|
'name' => $a->name,
|
||||||
|
'decision_ids' => $a->decisions->pluck('id')->values(),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return \Inertia\Inertia::render('Settings/Contracts/Index', [
|
||||||
|
'setting' => [
|
||||||
|
'id' => $setting->id,
|
||||||
|
'create_activity_on_balance_change' => (bool) $setting->create_activity_on_balance_change,
|
||||||
|
'default_action_id' => $setting->default_action_id,
|
||||||
|
'default_decision_id' => $setting->default_decision_id,
|
||||||
|
'activity_note_template' => $setting->activity_note_template,
|
||||||
|
],
|
||||||
|
'decisions' => $decisions,
|
||||||
|
'actions' => $actions,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(\App\Http\Requests\UpdateContractSettingRequest $request): \Illuminate\Http\RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validated();
|
||||||
|
$setting = \App\Models\ContractSetting::query()->firstOrFail();
|
||||||
|
|
||||||
|
$data['create_activity_on_balance_change'] = (bool) ($data['create_activity_on_balance_change'] ?? false);
|
||||||
|
|
||||||
|
$setting->update($data);
|
||||||
|
|
||||||
|
return back()->with('success', 'Nastavitve shranjene.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,6 @@
|
|||||||
use App\Services\Sms\SmsService;
|
use App\Services\Sms\SmsService;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
|
|
||||||
@@ -47,9 +46,9 @@ public function __invoke(SmsService $sms): Response
|
|||||||
return Account::whereHas('contract', function ($q) {
|
return Account::whereHas('contract', function ($q) {
|
||||||
$q->whereNull('deleted_at');
|
$q->whereNull('deleted_at');
|
||||||
})
|
})
|
||||||
->whereNotNull('promise_date')
|
->whereNotNull('promise_date')
|
||||||
->whereDate('promise_date', '>=', $today)
|
->whereDate('promise_date', '>=', $today)
|
||||||
->count();
|
->count();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Activities (limit 10) - cached
|
// Activities (limit 10) - cached
|
||||||
@@ -80,14 +79,14 @@ public function __invoke(SmsService $sms): Response
|
|||||||
->map(fn ($i) => now()->subDays(6 - $i)->format('Y-m-d'));
|
->map(fn ($i) => now()->subDays(6 - $i)->format('Y-m-d'));
|
||||||
|
|
||||||
$fieldJobTrendRaw = FieldJob::whereBetween(DB::raw('COALESCE(assigned_at, created_at)'), [$start, $end])
|
$fieldJobTrendRaw = FieldJob::whereBetween(DB::raw('COALESCE(assigned_at, created_at)'), [$start, $end])
|
||||||
->selectRaw('DATE(COALESCE(assigned_at, created_at)) as d, COUNT(*) as c')
|
->selectRaw("DATE(COALESCE(assigned_at, created_at) AT TIME ZONE 'Europe/Ljubljana') as d, COUNT(*) as c")
|
||||||
->groupBy('d')
|
->groupBy('d')
|
||||||
->pluck('c', 'd');
|
->pluck('c', 'd');
|
||||||
|
|
||||||
// Completed field jobs last 7 days
|
// Completed field jobs last 7 days
|
||||||
$fieldJobCompletedRaw = FieldJob::whereNotNull('completed_at')
|
$fieldJobCompletedRaw = FieldJob::whereNotNull('completed_at')
|
||||||
->whereBetween('completed_at', [$start, $end])
|
->whereBetween('completed_at', [$start, $end])
|
||||||
->selectRaw('DATE(completed_at) as d, COUNT(*) as c')
|
->selectRaw("DATE(completed_at AT TIME ZONE 'Europe/Ljubljana') as d, COUNT(*) as c")
|
||||||
->groupBy('d')
|
->groupBy('d')
|
||||||
->pluck('c', 'd');
|
->pluck('c', 'd');
|
||||||
|
|
||||||
@@ -101,13 +100,13 @@ public function __invoke(SmsService $sms): Response
|
|||||||
// Field jobs assigned today - cached
|
// Field jobs assigned today - cached
|
||||||
$fieldJobsAssignedToday = Cache::remember('dashboard:field_jobs_assigned_today:'.now()->format('Y-m-d'), $cacheMinutes * 60, function () use ($today) {
|
$fieldJobsAssignedToday = Cache::remember('dashboard:field_jobs_assigned_today:'.now()->format('Y-m-d'), $cacheMinutes * 60, function () use ($today) {
|
||||||
return FieldJob::query()
|
return FieldJob::query()
|
||||||
->whereDate(DB::raw('COALESCE(assigned_at, created_at)'), $today)
|
->whereRaw('DATE(COALESCE(assigned_at, created_at)) = ?', [$today->toDateString()])
|
||||||
->select(['id', 'assigned_user_id', 'priority', 'assigned_at', 'created_at', 'contract_id'])
|
->select(['id', 'assigned_user_id', 'priority', 'assigned_at', 'created_at', 'contract_id'])
|
||||||
->with(['contract' => function ($q) {
|
->with(['contract' => function ($q) {
|
||||||
$q->select('id', 'uuid', 'reference', 'client_case_id')
|
$q->select('id', 'uuid', 'reference', 'client_case_id')
|
||||||
->with(['clientCase:id,uuid,person_id', 'clientCase.person:id,full_name', 'segments:id,name']);
|
->with(['clientCase:id,uuid,person_id', 'clientCase.person:id,full_name', 'segments:id,name']);
|
||||||
}])
|
}])
|
||||||
->latest(DB::raw('COALESCE(assigned_at, created_at)'))
|
->orderByRaw('COALESCE(assigned_at, created_at) DESC')
|
||||||
->limit(15)
|
->limit(15)
|
||||||
->get()
|
->get()
|
||||||
->map(function ($fj) {
|
->map(function ($fj) {
|
||||||
@@ -120,20 +119,26 @@ public function __invoke(SmsService $sms): Response
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (! $contract) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $fj->id,
|
'id' => $fj->id,
|
||||||
'priority' => $fj->priority,
|
'priority' => $fj->priority,
|
||||||
'assigned_at' => $fj->assigned_at?->toIso8601String(),
|
'assigned_at' => $fj->assigned_at?->toIso8601String(),
|
||||||
'created_at' => $fj->created_at?->toIso8601String(),
|
'created_at' => $fj->created_at?->toIso8601String(),
|
||||||
'contract' => $contract ? [
|
'contract' => [
|
||||||
'uuid' => $contract->uuid,
|
'uuid' => $contract->uuid,
|
||||||
'reference' => $contract->reference,
|
'reference' => $contract->reference,
|
||||||
'client_case_uuid' => optional($contract->clientCase)->uuid,
|
'client_case_uuid' => optional($contract->clientCase)->uuid,
|
||||||
'person_full_name' => optional(optional($contract->clientCase)->person)->full_name,
|
'person_full_name' => optional(optional($contract->clientCase)->person)->full_name,
|
||||||
'segment_id' => $segmentId,
|
'segment_id' => $segmentId,
|
||||||
] : null,
|
],
|
||||||
];
|
];
|
||||||
});
|
})
|
||||||
|
->filter()
|
||||||
|
->values();
|
||||||
});
|
});
|
||||||
|
|
||||||
// System health for timestamp
|
// System health for timestamp
|
||||||
|
|||||||
@@ -25,56 +25,109 @@ public function index(Request $request)
|
|||||||
optional($setting)->segment_id,
|
optional($setting)->segment_id,
|
||||||
])->filter()->unique()->values();
|
])->filter()->unique()->values();
|
||||||
|
|
||||||
$contracts = Contract::query()
|
$search = $request->input('search');
|
||||||
->with(['clientCase.person', 'clientCase.client.person', 'type', 'account'])
|
$searchAssigned = $request->input('search_assigned');
|
||||||
->when($segmentIds->isNotEmpty(), function ($q) use ($segmentIds) {
|
$assignedUserId = $request->input('assigned_user_id');
|
||||||
$q->whereHas('segments', function ($sq) use ($segmentIds) {
|
$unassignedClientUuids = $request->input('unassigned_client_uuids');
|
||||||
// Relation already filters on active pivots
|
$assignedClientUuids = $request->input('assigned_client_uuids');
|
||||||
$sq->whereIn('segments.id', $segmentIds);
|
|
||||||
});
|
|
||||||
}, function ($q) {
|
|
||||||
// No segments configured on FieldJobSetting -> return none
|
|
||||||
$q->whereRaw('1 = 0');
|
|
||||||
})
|
|
||||||
->latest('id')
|
|
||||||
->limit(50)
|
|
||||||
->get();
|
|
||||||
|
|
||||||
// Mirror client onto the contract for simpler frontend access: c.client.person.full_name
|
$unassignedContracts = Contract::query()
|
||||||
$contracts->each(function (Contract $contract): void {
|
->with(['clientCase.person.addresses', 'clientCase.client.person:id,uuid,full_name', 'type', 'account'])
|
||||||
if ($contract->relationLoaded('clientCase') && $contract->clientCase) {
|
->when($segmentIds->isNotEmpty(), fn($q) =>
|
||||||
$contract->setRelation('client', $contract->clientCase->client);
|
$q->whereHas('segments', fn($rq) => $rq->whereIn('segments.id', $segmentIds)),
|
||||||
}
|
fn($q) => $q->whereRaw('1 = 0')
|
||||||
});
|
)
|
||||||
|
->when( !empty($search), fn ($q) =>
|
||||||
|
$q->where(fn($sq) =>
|
||||||
|
$sq->where('reference', 'like', "%{$search}%")
|
||||||
|
->orWhereHas('clientCase.person', fn($psq) =>
|
||||||
|
$psq->where('full_name', 'ilike', "%{$search}%")
|
||||||
|
)
|
||||||
|
->orWhereHas('clientCase.person.addresses', fn ($ccpaq) =>
|
||||||
|
$ccpaq->where('address', 'ilike', "%{$search}")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
->when(!empty($unassignedClientUuids) && is_array($unassignedClientUuids), fn ($q) =>
|
||||||
|
$q->whereHas('clientCase.client', fn($cq) =>
|
||||||
|
$cq->whereIn('uuid', $unassignedClientUuids)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
->whereDoesntHave('fieldJobs', fn ($q) =>
|
||||||
|
$q->whereNull('completed_at')
|
||||||
|
->whereNull('cancelled_at')
|
||||||
|
)
|
||||||
|
->latest('id');
|
||||||
|
|
||||||
// Build active assignment map keyed by contract uuid for quicker UI checks
|
$unassignedClients = $unassignedContracts->get()
|
||||||
$assignments = collect();
|
->pluck('clientCase.client')
|
||||||
if ($contracts->isNotEmpty()) {
|
->filter()
|
||||||
$activeJobs = FieldJob::query()
|
->unique('id')
|
||||||
->whereIn('contract_id', $contracts->pluck('id'))
|
->values();
|
||||||
->whereNull('completed_at')
|
|
||||||
->whereNull('cancelled_at')
|
|
||||||
->with(['assignedUser:id,name', 'user:id,name', 'contract:id,uuid'])
|
|
||||||
->get();
|
|
||||||
|
|
||||||
$assignments = $activeJobs->mapWithKeys(function (FieldJob $job) {
|
|
||||||
return [
|
$assignedContracts = Contract::query()
|
||||||
optional($job->contract)->uuid => [
|
->with(['clientCase.person.addresses', 'clientCase.client.person:id,uuid,full_name', 'type', 'account', 'lastFieldJobs', 'lastFieldJobs.assignedUser', 'lastFieldJobs.user'])
|
||||||
'assigned_to' => $job->assignedUser ? ['id' => $job->assignedUser->id, 'name' => $job->assignedUser->name] : null,
|
->when($segmentIds->isNotEmpty(), fn($q) =>
|
||||||
'assigned_by' => $job->user ? ['id' => $job->user->id, 'name' => $job->user->name] : null,
|
$q->whereHas('segments', fn($rq) => $rq->whereIn('segments.id', $segmentIds)),
|
||||||
'assigned_at' => $job->assigned_at,
|
fn($q) => $q->whereRaw('1 = 0')
|
||||||
],
|
)
|
||||||
];
|
->when( !empty($searchAssigned), fn ($q) =>
|
||||||
})->filter();
|
$q->where(fn($sq) =>
|
||||||
}
|
$sq->where('reference', 'like', "%{$searchAssigned}%")
|
||||||
|
->orWhereHas('clientCase.person', fn($psq) =>
|
||||||
|
$psq->where('full_name', 'ilike', "%{$searchAssigned}%")
|
||||||
|
)
|
||||||
|
->orWhereHas('clientCase.person.addresses', fn ($ccpaq) =>
|
||||||
|
$ccpaq->where('address', 'ilike', "%{$searchAssigned}")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
->when(!empty($assignedClientUuids) && is_array($assignedClientUuids), fn ($q) =>
|
||||||
|
$q->whereHas('clientCase.client', fn($cq) =>
|
||||||
|
$cq->whereIn('uuid', $assignedClientUuids)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
->whereHas('lastFieldJobs', fn ($q) =>
|
||||||
|
$q->whereNull('completed_at')
|
||||||
|
->whereNull('cancelled_at')
|
||||||
|
->when($assignedUserId && $assignedUserId !== 'all', fn ($jq) =>
|
||||||
|
$jq->where('assigned_user_id', $assignedUserId))
|
||||||
|
)
|
||||||
|
->latest('id');
|
||||||
|
|
||||||
|
$assignedClients = $assignedContracts->get()
|
||||||
|
->pluck('clientCase.client')
|
||||||
|
->filter()
|
||||||
|
->unique('id')
|
||||||
|
->values();
|
||||||
|
|
||||||
$users = User::query()->orderBy('name')->get(['id', 'name']);
|
$users = User::query()->orderBy('name')->get(['id', 'name']);
|
||||||
|
|
||||||
return Inertia::render('FieldJob/Index', [
|
return Inertia::render('FieldJob/Index', [
|
||||||
'setting' => $setting,
|
'setting' => $setting,
|
||||||
'contracts' => $contracts,
|
'unassignedContracts' => $unassignedContracts->paginate(
|
||||||
|
$request->input('per_page_contracts', 10),
|
||||||
|
['*'],
|
||||||
|
'page_contracts',
|
||||||
|
$request->input('page_contracts', 1)
|
||||||
|
),
|
||||||
|
'assignedContracts' => $assignedContracts->paginate(
|
||||||
|
$request->input('per_page_assignments', 10),
|
||||||
|
['*'],
|
||||||
|
'page_assignments',
|
||||||
|
$request->input('page_assignments', 1)
|
||||||
|
),
|
||||||
|
'unassignedClients' => $unassignedClients,
|
||||||
|
'assignedClients' => $assignedClients,
|
||||||
'users' => $users,
|
'users' => $users,
|
||||||
'assignments' => $assignments,
|
'filters' => [
|
||||||
|
'search' => $search,
|
||||||
|
'search_assigned' => $searchAssigned,
|
||||||
|
'assigned_user_id' => $assignedUserId,
|
||||||
|
'unassigned_client_uuids' => $unassignedClientUuids,
|
||||||
|
'assigned_client_uuids' => $assignedClientUuids,
|
||||||
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
use App\Models\ImportEvent;
|
use App\Models\ImportEvent;
|
||||||
use App\Models\ImportTemplate;
|
use App\Models\ImportTemplate;
|
||||||
use App\Services\CsvImportService;
|
use App\Services\CsvImportService;
|
||||||
|
use App\Services\Import\ImportSimulationServiceV2;
|
||||||
use App\Services\ImportProcessor;
|
use App\Services\ImportProcessor;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -21,14 +22,35 @@ class ImportController extends Controller
|
|||||||
// List imports (paginated)
|
// List imports (paginated)
|
||||||
public function index(Request $request)
|
public function index(Request $request)
|
||||||
{
|
{
|
||||||
$paginator = Import::query()
|
$query = Import::query()
|
||||||
->with([
|
->with([
|
||||||
'client:id,uuid,person_id',
|
'client:id,uuid,person_id',
|
||||||
'client.person:id,uuid,full_name',
|
'client.person:id,uuid,full_name',
|
||||||
'template:id,name',
|
'template:id,name',
|
||||||
])
|
])
|
||||||
->orderByDesc('created_at')
|
->orderByDesc('created_at');
|
||||||
->paginate(15);
|
|
||||||
|
// Apply search filter
|
||||||
|
if ($search = $request->input('search')) {
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('original_name', 'LIKE', "%{$search}%")
|
||||||
|
->orWhere('status', 'LIKE', "%{$search}%")
|
||||||
|
->orWhereHas('client.person', function ($q) use ($search) {
|
||||||
|
$q->where('full_name', 'LIKE', "%{$search}%");
|
||||||
|
})
|
||||||
|
->orWhereHas('template', function ($q) use ($search) {
|
||||||
|
$q->where('name', 'LIKE', "%{$search}%");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get per_page from request, default to 25
|
||||||
|
$perPage = (int) $request->input('per_page', 25);
|
||||||
|
if ($perPage < 1 || $perPage > 100) {
|
||||||
|
$perPage = 25;
|
||||||
|
}
|
||||||
|
|
||||||
|
$paginator = $query->paginate($perPage);
|
||||||
|
|
||||||
$imports = [
|
$imports = [
|
||||||
'data' => $paginator->items(),
|
'data' => $paginator->items(),
|
||||||
@@ -42,6 +64,7 @@ public function index(Request $request)
|
|||||||
'current_page' => $paginator->currentPage(),
|
'current_page' => $paginator->currentPage(),
|
||||||
'from' => $paginator->firstItem(),
|
'from' => $paginator->firstItem(),
|
||||||
'last_page' => $paginator->lastPage(),
|
'last_page' => $paginator->lastPage(),
|
||||||
|
'links' => $paginator->linkCollection()->toArray(),
|
||||||
'path' => $paginator->path(),
|
'path' => $paginator->path(),
|
||||||
'per_page' => $paginator->perPage(),
|
'per_page' => $paginator->perPage(),
|
||||||
'to' => $paginator->lastItem(),
|
'to' => $paginator->lastItem(),
|
||||||
@@ -164,9 +187,25 @@ public function store(Request $request)
|
|||||||
public function process(Import $import, Request $request, ImportProcessor $processor)
|
public function process(Import $import, Request $request, ImportProcessor $processor)
|
||||||
{
|
{
|
||||||
$import->update(['status' => 'validating', 'started_at' => now()]);
|
$import->update(['status' => 'validating', 'started_at' => now()]);
|
||||||
$result = $processor->process($import, user: $request->user());
|
|
||||||
|
|
||||||
return response()->json($result);
|
try {
|
||||||
|
$result = $processor->process($import, user: $request->user());
|
||||||
|
|
||||||
|
return response()->json($result);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
\Log::error('Import processing failed', [
|
||||||
|
'import_id' => $import->id,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
'trace' => $e->getTraceAsString(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$import->update(['status' => 'failed']);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => false,
|
||||||
|
'message' => 'Import processing failed: '.$e->getMessage(),
|
||||||
|
], 500);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Analyze the uploaded file and return column headers or positional indices
|
// Analyze the uploaded file and return column headers or positional indices
|
||||||
@@ -405,7 +444,7 @@ public function missingContracts(Import $import)
|
|||||||
|
|
||||||
// Query active, non-archived contracts for this client that were not in import
|
// Query active, non-archived contracts for this client that were not in import
|
||||||
// Include person full_name (owner of the client case) and aggregate active accounts' balance_amount
|
// Include person full_name (owner of the client case) and aggregate active accounts' balance_amount
|
||||||
$contractsQ = \App\Models\Contract::query()
|
$contractsQ = Contract::query()
|
||||||
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
||||||
->join('person', 'person.id', '=', 'client_cases.person_id')
|
->join('person', 'person.id', '=', 'client_cases.person_id')
|
||||||
->leftJoin('accounts', function ($join) {
|
->leftJoin('accounts', function ($join) {
|
||||||
@@ -493,7 +532,7 @@ public function getEvents(Import $import)
|
|||||||
public function missingKeyrefRows(Import $import)
|
public function missingKeyrefRows(Import $import)
|
||||||
{
|
{
|
||||||
// Identify row IDs from events. Prefer specific event key, fallback to message pattern
|
// Identify row IDs from events. Prefer specific event key, fallback to message pattern
|
||||||
$rowIds = \App\Models\ImportEvent::query()
|
$rowIds = ImportEvent::query()
|
||||||
->where('import_id', $import->id)
|
->where('import_id', $import->id)
|
||||||
->where(function ($q) {
|
->where(function ($q) {
|
||||||
$q->where('event', 'contract_keyref_not_found')
|
$q->where('event', 'contract_keyref_not_found')
|
||||||
@@ -673,6 +712,8 @@ public function simulatePayments(Import $import, Request $request)
|
|||||||
* using the first N rows and current saved mappings. Works for both payments and non-payments
|
* using the first N rows and current saved mappings. Works for both payments and non-payments
|
||||||
* templates. For payments templates, payment-specific summaries/entities will be included
|
* templates. For payments templates, payment-specific summaries/entities will be included
|
||||||
* automatically by the simulation service when mappings contain the payment root.
|
* automatically by the simulation service when mappings contain the payment root.
|
||||||
|
*
|
||||||
|
* @return \Illuminate\Http\JsonResponse
|
||||||
*/
|
*/
|
||||||
public function simulate(Import $import, Request $request)
|
public function simulate(Import $import, Request $request)
|
||||||
{
|
{
|
||||||
@@ -683,7 +724,7 @@ public function simulate(Import $import, Request $request)
|
|||||||
$limit = (int) ($validated['limit'] ?? 100);
|
$limit = (int) ($validated['limit'] ?? 100);
|
||||||
$verbose = (bool) ($validated['verbose'] ?? false);
|
$verbose = (bool) ($validated['verbose'] ?? false);
|
||||||
|
|
||||||
$service = app(\App\Services\ImportSimulationService::class);
|
$service = app(ImportSimulationServiceV2::class);
|
||||||
$result = $service->simulate($import, $limit, $verbose);
|
$result = $service->simulate($import, $limit, $verbose);
|
||||||
|
|
||||||
return response()->json($result);
|
return response()->json($result);
|
||||||
@@ -785,6 +826,21 @@ public function destroy(Request $request, Import $import)
|
|||||||
|
|
||||||
$import->delete();
|
$import->delete();
|
||||||
|
|
||||||
return back()->with(['ok' => true]);
|
return back()->with('success', 'Import deleted successfully');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Download the original import file
|
||||||
|
public function download(Import $import)
|
||||||
|
{
|
||||||
|
// Verify file exists
|
||||||
|
if (! $import->disk || ! $import->path || ! Storage::disk($import->disk)->exists($import->path)) {
|
||||||
|
return response()->json([
|
||||||
|
'error' => 'File not found',
|
||||||
|
], 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
$fileName = $import->original_name ?? 'import_'.$import->uuid;
|
||||||
|
|
||||||
|
return Storage::disk($import->disk)->download($import->path, $fileName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,16 @@ public function index()
|
|||||||
->orderBy('name')
|
->orderBy('name')
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
|
// Preload options for import mapping
|
||||||
|
$clients = Client::query()
|
||||||
|
->join('person', 'person.id', '=', 'clients.person_id')
|
||||||
|
->orderBy('person.full_name')
|
||||||
|
->get(['clients.uuid', DB::raw('person.full_name as name')]);
|
||||||
|
|
||||||
|
$segments = Segment::query()->orderBy('name')->get(['id', 'name']);
|
||||||
|
$decisions = Decision::query()->orderBy('name')->get(['id', 'name']);
|
||||||
|
$actions = Action::query()->orderBy('name')->get(['id', 'name']);
|
||||||
|
|
||||||
return Inertia::render('Imports/Templates/Index', [
|
return Inertia::render('Imports/Templates/Index', [
|
||||||
'templates' => $templates->map(fn ($t) => [
|
'templates' => $templates->map(fn ($t) => [
|
||||||
'uuid' => $t->uuid,
|
'uuid' => $t->uuid,
|
||||||
@@ -35,6 +45,10 @@ public function index()
|
|||||||
'name' => $t->client->person?->full_name,
|
'name' => $t->client->person?->full_name,
|
||||||
] : null,
|
] : null,
|
||||||
]),
|
]),
|
||||||
|
'clients' => $clients,
|
||||||
|
'segments' => $segments,
|
||||||
|
'decisions' => $decisions,
|
||||||
|
'actions' => $actions,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -547,6 +561,7 @@ public function updateMapping(Request $request, ImportTemplate $template, Import
|
|||||||
'options' => 'nullable|array',
|
'options' => 'nullable|array',
|
||||||
'position' => 'nullable|integer',
|
'position' => 'nullable|integer',
|
||||||
])->validate();
|
])->validate();
|
||||||
|
|
||||||
$mapping->update([
|
$mapping->update([
|
||||||
'source_column' => $data['source_column'],
|
'source_column' => $data['source_column'],
|
||||||
'entity' => $data['entity'] ?? null,
|
'entity' => $data['entity'] ?? null,
|
||||||
@@ -557,8 +572,7 @@ public function updateMapping(Request $request, ImportTemplate $template, Import
|
|||||||
'position' => $data['position'] ?? $mapping->position,
|
'position' => $data['position'] ?? $mapping->position,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return redirect()->route('importTemplates.edit', ['template' => $template->uuid])
|
return back()->with('success', 'Mapping updated');
|
||||||
->with('success', 'Mapping updated');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete a mapping
|
// Delete a mapping
|
||||||
@@ -643,6 +657,7 @@ public function applyToImport(Request $request, ImportTemplate $template, Import
|
|||||||
|
|
||||||
$import->update([
|
$import->update([
|
||||||
'import_template_id' => $template->id,
|
'import_template_id' => $template->id,
|
||||||
|
'reactivate' => $template->reactivate,
|
||||||
'meta' => $merged,
|
'meta' => $merged,
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
@@ -664,4 +679,138 @@ public function destroy(ImportTemplate $template)
|
|||||||
|
|
||||||
return redirect()->route('importTemplates.index')->with('success', 'Template deleted');
|
return redirect()->route('importTemplates.index')->with('success', 'Template deleted');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Export template as JSON file
|
||||||
|
public function export(ImportTemplate $template)
|
||||||
|
{
|
||||||
|
$template->load('mappings');
|
||||||
|
|
||||||
|
$data = [
|
||||||
|
'name' => $template->name,
|
||||||
|
'description' => $template->description,
|
||||||
|
'source_type' => $template->source_type,
|
||||||
|
'default_record_type' => $template->default_record_type,
|
||||||
|
'sample_headers' => $template->sample_headers,
|
||||||
|
'is_active' => $template->is_active,
|
||||||
|
'reactivate' => $template->reactivate,
|
||||||
|
'meta' => $template->meta,
|
||||||
|
'mappings' => $template->mappings->map(fn ($m) => [
|
||||||
|
'source_column' => $m->source_column,
|
||||||
|
'entity' => $m->entity,
|
||||||
|
'target_field' => $m->target_field,
|
||||||
|
'transform' => $m->transform,
|
||||||
|
'apply_mode' => $m->apply_mode,
|
||||||
|
'options' => $m->options,
|
||||||
|
'position' => $m->position,
|
||||||
|
])->values()->toArray(),
|
||||||
|
];
|
||||||
|
|
||||||
|
$filename = Str::slug($template->name).'-'.now()->format('Y-m-d').'.json';
|
||||||
|
|
||||||
|
return response()->json($data)
|
||||||
|
->header('Content-Disposition', 'attachment; filename="'.$filename.'"');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Import template from JSON file
|
||||||
|
public function import(Request $request)
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'file' => 'required|file|mimes:json,txt|max:10240',
|
||||||
|
'client_uuid' => 'nullable|string|exists:clients,uuid',
|
||||||
|
'segment_id' => 'nullable|integer|exists:segments,id',
|
||||||
|
'decision_id' => 'nullable|integer|exists:decisions,id',
|
||||||
|
'action_id' => 'nullable|integer|exists:actions,id',
|
||||||
|
'activity_action_id' => 'nullable|integer|exists:actions,id',
|
||||||
|
'activity_decision_id' => 'nullable|integer|exists:decisions,id',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$file = $request->file('file');
|
||||||
|
$contents = file_get_contents($file->getRealPath());
|
||||||
|
$json = json_decode($contents, true);
|
||||||
|
|
||||||
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
|
return back()->withErrors(['file' => 'Invalid JSON file']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate structure
|
||||||
|
$validator = validator($json, [
|
||||||
|
'name' => 'required|string|max:100',
|
||||||
|
'description' => 'nullable|string|max:255',
|
||||||
|
'source_type' => 'required|string|in:csv,xml,xls,xlsx,json',
|
||||||
|
'default_record_type' => 'nullable|string|max:50',
|
||||||
|
'sample_headers' => 'nullable|array',
|
||||||
|
'is_active' => 'nullable|boolean',
|
||||||
|
'reactivate' => 'nullable|boolean',
|
||||||
|
'meta' => 'nullable|array',
|
||||||
|
'mappings' => 'nullable|array',
|
||||||
|
'mappings.*.source_column' => 'required|string',
|
||||||
|
'mappings.*.entity' => 'nullable|string',
|
||||||
|
'mappings.*.target_field' => 'nullable|string',
|
||||||
|
'mappings.*.transform' => 'nullable|string',
|
||||||
|
'mappings.*.apply_mode' => 'nullable|string|in:insert,update,both,keyref',
|
||||||
|
'mappings.*.options' => 'nullable|array',
|
||||||
|
'mappings.*.position' => 'nullable|integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($validator->fails()) {
|
||||||
|
return back()->withErrors($validator)->withInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
$clientId = null;
|
||||||
|
if (! empty($data['client_uuid'])) {
|
||||||
|
$clientId = Client::where('uuid', $data['client_uuid'])->value('id');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace IDs in meta if provided
|
||||||
|
$meta = $json['meta'] ?? [];
|
||||||
|
if (! empty($data['segment_id'])) {
|
||||||
|
$meta['segment_id'] = (int) $data['segment_id'];
|
||||||
|
}
|
||||||
|
if (! empty($data['decision_id'])) {
|
||||||
|
$meta['decision_id'] = (int) $data['decision_id'];
|
||||||
|
}
|
||||||
|
if (! empty($data['action_id'])) {
|
||||||
|
$meta['action_id'] = (int) $data['action_id'];
|
||||||
|
}
|
||||||
|
if (! empty($data['activity_action_id'])) {
|
||||||
|
$meta['activity_action_id'] = (int) $data['activity_action_id'];
|
||||||
|
}
|
||||||
|
if (! empty($data['activity_decision_id'])) {
|
||||||
|
$meta['activity_decision_id'] = (int) $data['activity_decision_id'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$template = null;
|
||||||
|
DB::transaction(function () use (&$template, $request, $json, $clientId, $meta) {
|
||||||
|
$template = ImportTemplate::create([
|
||||||
|
'uuid' => (string) Str::uuid(),
|
||||||
|
'name' => $json['name'],
|
||||||
|
'description' => $json['description'] ?? null,
|
||||||
|
'source_type' => $json['source_type'],
|
||||||
|
'default_record_type' => $json['default_record_type'] ?? null,
|
||||||
|
'sample_headers' => $json['sample_headers'] ?? null,
|
||||||
|
'user_id' => $request->user()?->id,
|
||||||
|
'client_id' => $clientId,
|
||||||
|
'is_active' => $json['is_active'] ?? true,
|
||||||
|
'reactivate' => $json['reactivate'] ?? false,
|
||||||
|
'meta' => $meta,
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach (($json['mappings'] ?? []) as $m) {
|
||||||
|
ImportTemplateMapping::create([
|
||||||
|
'import_template_id' => $template->id,
|
||||||
|
'entity' => $m['entity'] ?? null,
|
||||||
|
'source_column' => $m['source_column'],
|
||||||
|
'target_field' => $m['target_field'] ?? null,
|
||||||
|
'transform' => $m['transform'] ?? null,
|
||||||
|
'apply_mode' => $m['apply_mode'] ?? 'both',
|
||||||
|
'options' => $m['options'] ?? null,
|
||||||
|
'position' => $m['position'] ?? null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return redirect()
|
||||||
|
->route('importTemplates.edit', ['template' => $template->uuid])
|
||||||
|
->with('success', 'Template imported successfully');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Requests\UpdateInstallmentSettingRequest;
|
||||||
|
use App\Models\Action;
|
||||||
|
use App\Models\Decision;
|
||||||
|
use App\Models\InstallmentSetting;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
|
class InstallmentSettingController extends Controller
|
||||||
|
{
|
||||||
|
public function edit(): Response
|
||||||
|
{
|
||||||
|
$setting = InstallmentSetting::query()->first();
|
||||||
|
if (! $setting) {
|
||||||
|
$setting = InstallmentSetting::query()->create([
|
||||||
|
'default_currency' => 'EUR',
|
||||||
|
'create_activity_on_installment' => false,
|
||||||
|
'default_decision_id' => null,
|
||||||
|
'default_action_id' => null,
|
||||||
|
'activity_note_template' => 'Dodan obrok: {amount} {currency}',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$decisions = Decision::query()->orderBy('name')->get(['id', 'name']);
|
||||||
|
$actions = Action::query()
|
||||||
|
->with(['decisions:id'])
|
||||||
|
->orderBy('name')
|
||||||
|
->get()
|
||||||
|
->map(function (Action $a) {
|
||||||
|
return [
|
||||||
|
'id' => $a->id,
|
||||||
|
'name' => $a->name,
|
||||||
|
'decision_ids' => $a->decisions->pluck('id')->values(),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return Inertia::render('Settings/Installments/Index', [
|
||||||
|
'setting' => [
|
||||||
|
'id' => $setting->id,
|
||||||
|
'default_currency' => $setting->default_currency,
|
||||||
|
'create_activity_on_installment' => (bool) $setting->create_activity_on_installment,
|
||||||
|
'default_decision_id' => $setting->default_decision_id,
|
||||||
|
'default_action_id' => $setting->default_action_id,
|
||||||
|
'activity_note_template' => $setting->activity_note_template,
|
||||||
|
],
|
||||||
|
'decisions' => $decisions,
|
||||||
|
'actions' => $actions,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(UpdateInstallmentSettingRequest $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validated();
|
||||||
|
$setting = InstallmentSetting::query()->firstOrFail();
|
||||||
|
|
||||||
|
$data['create_activity_on_installment'] = (bool) ($data['create_activity_on_installment'] ?? false);
|
||||||
|
|
||||||
|
$setting->update($data);
|
||||||
|
|
||||||
|
return back()->with('success', 'Nastavitve shranjene.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,7 @@ public function unread(Request $request)
|
|||||||
}
|
}
|
||||||
|
|
||||||
$today = now()->toDateString();
|
$today = now()->toDateString();
|
||||||
$perPage = max(1, min(100, (int) $request->integer('perPage', 15)));
|
$perPage = max(1, min(100, (int) $request->integer('per_page', 15)));
|
||||||
$search = trim((string) $request->input('search', ''));
|
$search = trim((string) $request->input('search', ''));
|
||||||
$clientUuid = trim((string) $request->input('client', ''));
|
$clientUuid = trim((string) $request->input('client', ''));
|
||||||
$clientId = null;
|
$clientId = null;
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\BankAccount;
|
|
||||||
use App\Models\Person\Person;
|
use App\Models\Person\Person;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
@@ -22,14 +21,14 @@ public function update(Person $person, Request $request)
|
|||||||
'tax_number' => 'nullable|integer',
|
'tax_number' => 'nullable|integer',
|
||||||
'social_security_number' => 'nullable|integer',
|
'social_security_number' => 'nullable|integer',
|
||||||
'description' => 'nullable|string|max:500',
|
'description' => 'nullable|string|max:500',
|
||||||
|
'employer' => 'nullable|string|max:255',
|
||||||
|
'birthday' => 'nullable|date',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$person->update($attributes);
|
$person->update($attributes);
|
||||||
|
|
||||||
return back()->with('success', 'Person updated')->with('flash_method', 'PUT');
|
return back()->with('success', 'Person updated')->with('flash_method', 'PUT');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function createAddress(Person $person, Request $request)
|
public function createAddress(Person $person, Request $request)
|
||||||
@@ -80,7 +79,6 @@ public function deleteAddress(Person $person, int $address_id, Request $request)
|
|||||||
$address = $person->addresses()->findOrFail($address_id);
|
$address = $person->addresses()->findOrFail($address_id);
|
||||||
$address->delete(); // soft delete
|
$address->delete(); // soft delete
|
||||||
|
|
||||||
|
|
||||||
return back()->with('success', 'Address deleted')->with('flash_method', 'DELETE');
|
return back()->with('success', 'Address deleted')->with('flash_method', 'DELETE');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,12 +136,19 @@ public function createEmail(Person $person, Request $request)
|
|||||||
'is_primary' => 'boolean',
|
'is_primary' => 'boolean',
|
||||||
'is_active' => 'boolean',
|
'is_active' => 'boolean',
|
||||||
'valid' => 'boolean',
|
'valid' => 'boolean',
|
||||||
|
'failed' => 'boolean',
|
||||||
'receive_auto_mails' => 'sometimes|boolean',
|
'receive_auto_mails' => 'sometimes|boolean',
|
||||||
'verified_at' => 'nullable|date',
|
'verified_at' => 'nullable|date',
|
||||||
'preferences' => 'nullable|array',
|
'preferences' => 'nullable|array',
|
||||||
'meta' => 'nullable|array',
|
'meta' => 'nullable|array',
|
||||||
|
'decision_ids' => 'nullable|array',
|
||||||
|
'decision_ids.*' => 'integer|exists:decisions,id',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$decisionIds = array_map('intval', $attributes['decision_ids'] ?? []);
|
||||||
|
unset($attributes['decision_ids']);
|
||||||
|
$attributes['preferences'] = array_merge($attributes['preferences'] ?? [], ['decision_ids' => $decisionIds]);
|
||||||
|
|
||||||
// Dedup: avoid duplicate email per person by value
|
// Dedup: avoid duplicate email per person by value
|
||||||
$email = $person->emails()->firstOrCreate([
|
$email = $person->emails()->firstOrCreate([
|
||||||
'value' => $attributes['value'],
|
'value' => $attributes['value'],
|
||||||
@@ -160,14 +165,21 @@ public function updateEmail(Person $person, int $email_id, Request $request)
|
|||||||
'is_primary' => 'boolean',
|
'is_primary' => 'boolean',
|
||||||
'is_active' => 'boolean',
|
'is_active' => 'boolean',
|
||||||
'valid' => 'boolean',
|
'valid' => 'boolean',
|
||||||
|
'failed' => 'boolean',
|
||||||
'receive_auto_mails' => 'sometimes|boolean',
|
'receive_auto_mails' => 'sometimes|boolean',
|
||||||
'verified_at' => 'nullable|date',
|
'verified_at' => 'nullable|date',
|
||||||
'preferences' => 'nullable|array',
|
'preferences' => 'nullable|array',
|
||||||
'meta' => 'nullable|array',
|
'meta' => 'nullable|array',
|
||||||
|
'decision_ids' => 'nullable|array',
|
||||||
|
'decision_ids.*' => 'integer|exists:decisions,id',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$email = $person->emails()->findOrFail($email_id);
|
$email = $person->emails()->findOrFail($email_id);
|
||||||
|
|
||||||
|
$decisionIds = array_map('intval', $attributes['decision_ids'] ?? []);
|
||||||
|
unset($attributes['decision_ids']);
|
||||||
|
$attributes['preferences'] = array_merge($email->preferences ?? [], $attributes['preferences'] ?? [], ['decision_ids' => $decisionIds]);
|
||||||
|
|
||||||
$email->update($attributes);
|
$email->update($attributes);
|
||||||
|
|
||||||
return back()->with('success', 'Email updated successfully')->with('flash_method', 'PUT');
|
return back()->with('success', 'Email updated successfully')->with('flash_method', 'PUT');
|
||||||
@@ -204,10 +216,8 @@ public function createTrr(Person $person, Request $request)
|
|||||||
// Create without dedup (IBAN may be null or vary); could dedup by IBAN if provided
|
// Create without dedup (IBAN may be null or vary); could dedup by IBAN if provided
|
||||||
$trr = $person->bankAccounts()->create($attributes);
|
$trr = $person->bankAccounts()->create($attributes);
|
||||||
|
|
||||||
|
|
||||||
return back()->with('success', 'TRR added successfully')->with('flash_method', 'POST');
|
return back()->with('success', 'TRR added successfully')->with('flash_method', 'POST');
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateTrr(Person $person, int $trr_id, Request $request)
|
public function updateTrr(Person $person, int $trr_id, Request $request)
|
||||||
@@ -238,7 +248,6 @@ public function deleteTrr(Person $person, int $trr_id, Request $request)
|
|||||||
$trr = $person->bankAccounts()->findOrFail($trr_id);
|
$trr = $person->bankAccounts()->findOrFail($trr_id);
|
||||||
$trr->delete();
|
$trr->delete();
|
||||||
|
|
||||||
|
|
||||||
return back()->with('success', 'TRR deleted')->with('flash_method', 'DELETE');
|
return back()->with('success', 'TRR deleted')->with('flash_method', 'DELETE');
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,45 +10,97 @@
|
|||||||
class PhoneViewController extends Controller
|
class PhoneViewController extends Controller
|
||||||
{
|
{
|
||||||
public function __construct(protected ReferenceDataCache $referenceCache) {}
|
public function __construct(protected ReferenceDataCache $referenceCache) {}
|
||||||
public function index(Request $request)
|
|
||||||
|
public function index(Request $request): \Inertia\Response
|
||||||
{
|
{
|
||||||
$userId = $request->user()->id;
|
$userId = $request->user()->id;
|
||||||
|
$search = $request->input('search');
|
||||||
|
$clientFilter = $request->input('client');
|
||||||
|
|
||||||
$jobs = FieldJob::query()
|
$eagerLoad = [
|
||||||
|
'contract' => function ($q) {
|
||||||
|
$q->with([
|
||||||
|
'type:id,name',
|
||||||
|
'account',
|
||||||
|
'clientCase.person.address.type',
|
||||||
|
'clientCase.person.phones',
|
||||||
|
'clientCase.client:id,uuid,person_id',
|
||||||
|
'clientCase.client.person:id,full_name',
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
$baseQuery = FieldJob::query()
|
||||||
->where('assigned_user_id', $userId)
|
->where('assigned_user_id', $userId)
|
||||||
->whereNull('completed_at')
|
->whereNull('completed_at')
|
||||||
->whereNull('cancelled_at')
|
->whereNull('cancelled_at')
|
||||||
->with([
|
->with($eagerLoad);
|
||||||
'contract' => function ($q) {
|
|
||||||
$q->with([
|
if ($clientFilter) {
|
||||||
'type:id,name',
|
$baseQuery->whereHas('contract.clientCase.client', function ($q) use ($clientFilter) {
|
||||||
'account',
|
$q->where('uuid', $clientFilter);
|
||||||
'clientCase.person' => function ($pq) {
|
});
|
||||||
$pq->with(['addresses', 'phones']);
|
}
|
||||||
},
|
|
||||||
'clientCase.client:id,uuid,person_id',
|
if ($search) {
|
||||||
'clientCase.client.person:id,full_name',
|
$baseQuery->where(function ($q) use ($search) {
|
||||||
]);
|
$q->whereHas('contract', function ($cq) use ($search) {
|
||||||
},
|
$cq->where('reference', 'ilike', '%'.$search.'%')
|
||||||
|
->orWhereHas('clientCase.person', function ($pq) use ($search) {
|
||||||
|
$pq->where('full_name', 'ilike', '%'.$search.'%');
|
||||||
|
})
|
||||||
|
->orWhereHas('clientCase.client.person', function ($pq) use ($search) {
|
||||||
|
$pq->where('full_name', 'ilike', '%'.$search.'%');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$pendingQuery = (clone $baseQuery)
|
||||||
|
->where(fn ($q) => $q->where('added_activity', false)->orWhereNull('added_activity'))
|
||||||
|
->orderByDesc('assigned_at');
|
||||||
|
|
||||||
|
$processedQuery = (clone $baseQuery)
|
||||||
|
->where('added_activity', true)
|
||||||
|
->orderByDesc('assigned_at');
|
||||||
|
|
||||||
|
$clients = \App\Models\Client::query()
|
||||||
|
->whereHas('clientCases.contracts.fieldJobs', function ($q) use ($userId) {
|
||||||
|
$q->where('assigned_user_id', $userId)
|
||||||
|
->whereNull('completed_at')
|
||||||
|
->whereNull('cancelled_at');
|
||||||
|
})
|
||||||
|
->with(['person:id,full_name'])
|
||||||
|
->get(['uuid', 'person_id'])
|
||||||
|
->map(fn ($c) => [
|
||||||
|
'uuid' => (string) $c->uuid,
|
||||||
|
'name' => (string) optional($c->person)->full_name,
|
||||||
])
|
])
|
||||||
->orderByDesc('assigned_at')
|
->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)
|
||||||
->limit(100)
|
->values();
|
||||||
->get();
|
|
||||||
|
|
||||||
return Inertia::render('Phone/Index', [
|
return Inertia::render('Phone/Index', [
|
||||||
'jobs' => $jobs,
|
'pendingJobs' => Inertia::scroll(fn () => $pendingQuery->paginate(15, pageName: 'pending')),
|
||||||
|
'processedJobs' => Inertia::scroll(fn () => $processedQuery->paginate(15, pageName: 'processed')),
|
||||||
|
'clients' => $clients,
|
||||||
'view_mode' => 'assigned',
|
'view_mode' => 'assigned',
|
||||||
|
'filters' => [
|
||||||
|
'search' => $search,
|
||||||
|
'client' => $clientFilter,
|
||||||
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function completedToday(Request $request)
|
public function completedToday(Request $request): \Inertia\Response
|
||||||
{
|
{
|
||||||
$userId = $request->user()->id;
|
$userId = $request->user()->id;
|
||||||
|
$search = $request->input('search');
|
||||||
|
$clientFilter = $request->input('client');
|
||||||
|
|
||||||
$start = now()->startOfDay();
|
$start = now()->startOfDay();
|
||||||
$end = now()->endOfDay();
|
$end = now()->endOfDay();
|
||||||
|
|
||||||
$jobs = FieldJob::query()
|
$query = FieldJob::query()
|
||||||
->where('assigned_user_id', $userId)
|
->where('assigned_user_id', $userId)
|
||||||
->whereNull('cancelled_at')
|
->whereNull('cancelled_at')
|
||||||
->whereBetween('completed_at', [$start, $end])
|
->whereBetween('completed_at', [$start, $end])
|
||||||
@@ -57,21 +109,60 @@ public function completedToday(Request $request)
|
|||||||
$q->with([
|
$q->with([
|
||||||
'type:id,name',
|
'type:id,name',
|
||||||
'account',
|
'account',
|
||||||
'clientCase.person' => function ($pq) {
|
'clientCase.person.address.type',
|
||||||
$pq->with(['addresses', 'phones']);
|
'clientCase.person.phones',
|
||||||
},
|
|
||||||
'clientCase.client:id,uuid,person_id',
|
'clientCase.client:id,uuid,person_id',
|
||||||
'clientCase.client.person:id,full_name',
|
'clientCase.client.person:id,full_name',
|
||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
])
|
])
|
||||||
->orderByDesc('completed_at')
|
->orderByDesc('completed_at');
|
||||||
->limit(100)
|
|
||||||
->get();
|
// Apply client filter
|
||||||
|
if ($clientFilter) {
|
||||||
|
$query->whereHas('contract.clientCase.client', function ($q) use ($clientFilter) {
|
||||||
|
$q->where('uuid', $clientFilter);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply search filter
|
||||||
|
if ($search) {
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->whereHas('contract', function ($cq) use ($search) {
|
||||||
|
$cq->where('reference', 'ilike', '%'.$search.'%')
|
||||||
|
->orWhereHas('clientCase.person', function ($pq) use ($search) {
|
||||||
|
$pq->where('full_name', 'ilike', '%'.$search.'%');
|
||||||
|
})
|
||||||
|
->orWhereHas('clientCase.client.person', function ($pq) use ($search) {
|
||||||
|
$pq->where('full_name', 'ilike', '%'.$search.'%');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$clients = \App\Models\Client::query()
|
||||||
|
->whereHas('clientCases.contracts.fieldJobs', function ($q) use ($userId, $start, $end) {
|
||||||
|
$q->where('assigned_user_id', $userId)
|
||||||
|
->whereNull('cancelled_at')
|
||||||
|
->whereBetween('completed_at', [$start, $end]);
|
||||||
|
})
|
||||||
|
->with(['person:id,full_name'])
|
||||||
|
->get(['uuid', 'person_id'])
|
||||||
|
->map(fn ($c) => [
|
||||||
|
'uuid' => (string) $c->uuid,
|
||||||
|
'name' => (string) optional($c->person)->full_name,
|
||||||
|
])
|
||||||
|
->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)
|
||||||
|
->values();
|
||||||
|
|
||||||
return Inertia::render('Phone/Index', [
|
return Inertia::render('Phone/Index', [
|
||||||
'jobs' => $jobs,
|
'completedJobs' => Inertia::scroll(fn () => $query->paginate(15, pageName: 'completed')),
|
||||||
|
'clients' => $clients,
|
||||||
'view_mode' => 'completed-today',
|
'view_mode' => 'completed-today',
|
||||||
|
'filters' => [
|
||||||
|
'search' => $search,
|
||||||
|
'client' => $clientFilter,
|
||||||
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,7 +172,7 @@ public function showCase(\App\Models\ClientCase $clientCase, Request $request)
|
|||||||
$completedMode = $request->boolean('completed');
|
$completedMode = $request->boolean('completed');
|
||||||
|
|
||||||
// Eager load case with person details
|
// Eager load case with person details
|
||||||
$case = $clientCase->load('person.addresses', 'person.phones', 'person.emails', 'person.bankAccounts');
|
$case = $clientCase->load('person.address.type', 'person.phones', 'person.emails', 'person.bankAccounts');
|
||||||
|
|
||||||
// Query contracts based on field jobs
|
// Query contracts based on field jobs
|
||||||
$contractsQuery = FieldJob::query()
|
$contractsQuery = FieldJob::query()
|
||||||
@@ -131,7 +222,7 @@ public function showCase(\App\Models\ClientCase $clientCase, Request $request)
|
|||||||
->unique();
|
->unique();
|
||||||
|
|
||||||
return Inertia::render('Phone/Case/Index', [
|
return Inertia::render('Phone/Case/Index', [
|
||||||
'client' => $case->client->load('person.addresses', 'person.phones', 'person.emails', 'person.bankAccounts'),
|
'client' => $case->client->load('person.address.type', 'person.phones', 'person.emails', 'person.bankAccounts'),
|
||||||
'client_case' => $case,
|
'client_case' => $case,
|
||||||
'contracts' => $contracts,
|
'contracts' => $contracts,
|
||||||
'documents' => $documents,
|
'documents' => $documents,
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Reports\ReportRegistry;
|
use App\Models\Report;
|
||||||
|
use App\Services\ReportQueryBuilder;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
|
|
||||||
@@ -10,15 +11,19 @@
|
|||||||
|
|
||||||
class ReportController extends Controller
|
class ReportController extends Controller
|
||||||
{
|
{
|
||||||
public function __construct(protected ReportRegistry $registry) {}
|
public function __construct(protected ReportQueryBuilder $queryBuilder) {}
|
||||||
|
|
||||||
public function index(Request $request)
|
public function index(Request $request)
|
||||||
{
|
{
|
||||||
$reports = collect($this->registry->all())
|
$reports = Report::where('enabled', true)
|
||||||
|
->orderBy('order')
|
||||||
|
->orderBy('name')
|
||||||
|
->get()
|
||||||
->map(fn ($r) => [
|
->map(fn ($r) => [
|
||||||
'slug' => $r->slug(),
|
'slug' => $r->slug,
|
||||||
'name' => $r->name(),
|
'name' => $r->name,
|
||||||
'description' => $r->description(),
|
'description' => $r->description,
|
||||||
|
'category' => $r->category,
|
||||||
])
|
])
|
||||||
->values();
|
->values();
|
||||||
|
|
||||||
@@ -29,26 +34,30 @@ public function index(Request $request)
|
|||||||
|
|
||||||
public function show(string $slug, Request $request)
|
public function show(string $slug, Request $request)
|
||||||
{
|
{
|
||||||
$report = $this->registry->findBySlug($slug);
|
$report = Report::with(['filters', 'columns'])
|
||||||
abort_if(! $report, 404);
|
->where('slug', $slug)
|
||||||
$report->authorize($request);
|
->where('enabled', true)
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
// Accept filters & pagination from query and return initial data for server-driven table
|
// Accept filters & pagination from query and return initial data for server-driven table
|
||||||
$filters = $this->validateFilters($report->inputs(), $request);
|
$inputs = $this->buildInputsArray($report);
|
||||||
|
$filters = $this->validateFilters($inputs, $request);
|
||||||
\Log::info('Report filters', ['filters' => $filters, 'request' => $request->all()]);
|
\Log::info('Report filters', ['filters' => $filters, 'request' => $request->all()]);
|
||||||
|
|
||||||
$perPage = (int) ($request->integer('per_page') ?: 25);
|
$perPage = (int) ($request->integer('per_page') ?: 25);
|
||||||
$paginator = $report->paginate($filters, $perPage);
|
$query = $this->queryBuilder->build($report, $filters);
|
||||||
|
$paginator = $query->paginate($perPage);
|
||||||
|
|
||||||
$rows = collect($paginator->items())
|
$rows = collect($paginator->items())
|
||||||
->map(fn ($row) => $this->normalizeRow($row))
|
->map(fn ($row) => $this->normalizeRow($row))
|
||||||
->values();
|
->values();
|
||||||
|
|
||||||
return Inertia::render('Reports/Show', [
|
return Inertia::render('Reports/Show', [
|
||||||
'slug' => $report->slug(),
|
'slug' => $report->slug,
|
||||||
'name' => $report->name(),
|
'name' => $report->name,
|
||||||
'description' => $report->description(),
|
'description' => $report->description,
|
||||||
'inputs' => $report->inputs(),
|
'inputs' => $inputs,
|
||||||
'columns' => $report->columns(),
|
'columns' => $this->buildColumnsArray($report),
|
||||||
'rows' => $rows,
|
'rows' => $rows,
|
||||||
'meta' => [
|
'meta' => [
|
||||||
'total' => $paginator->total(),
|
'total' => $paginator->total(),
|
||||||
@@ -62,14 +71,17 @@ public function show(string $slug, Request $request)
|
|||||||
|
|
||||||
public function data(string $slug, Request $request)
|
public function data(string $slug, Request $request)
|
||||||
{
|
{
|
||||||
$report = $this->registry->findBySlug($slug);
|
$report = Report::with(['filters', 'columns'])
|
||||||
abort_if(! $report, 404);
|
->where('slug', $slug)
|
||||||
$report->authorize($request);
|
->where('enabled', true)
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
$filters = $this->validateFilters($report->inputs(), $request);
|
$inputs = $this->buildInputsArray($report);
|
||||||
|
$filters = $this->validateFilters($inputs, $request);
|
||||||
$perPage = (int) ($request->integer('per_page') ?: 25);
|
$perPage = (int) ($request->integer('per_page') ?: 25);
|
||||||
|
|
||||||
$paginator = $report->paginate($filters, $perPage);
|
$query = $this->queryBuilder->build($report, $filters);
|
||||||
|
$paginator = $query->paginate($perPage);
|
||||||
|
|
||||||
$rows = collect($paginator->items())
|
$rows = collect($paginator->items())
|
||||||
->map(fn ($row) => $this->normalizeRow($row))
|
->map(fn ($row) => $this->normalizeRow($row))
|
||||||
@@ -85,20 +97,23 @@ public function data(string $slug, Request $request)
|
|||||||
|
|
||||||
public function export(string $slug, Request $request)
|
public function export(string $slug, Request $request)
|
||||||
{
|
{
|
||||||
$report = $this->registry->findBySlug($slug);
|
$report = Report::with(['filters', 'columns'])
|
||||||
abort_if(! $report, 404);
|
->where('slug', $slug)
|
||||||
$report->authorize($request);
|
->where('enabled', true)
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
$filters = $this->validateFilters($report->inputs(), $request);
|
$inputs = $this->buildInputsArray($report);
|
||||||
|
$filters = $this->validateFilters($inputs, $request);
|
||||||
$format = strtolower((string) $request->get('format', 'csv'));
|
$format = strtolower((string) $request->get('format', 'csv'));
|
||||||
|
|
||||||
$rows = $report->query($filters)->get()->map(fn ($row) => $this->normalizeRow($row));
|
$query = $this->queryBuilder->build($report, $filters);
|
||||||
$columns = $report->columns();
|
$rows = $query->get()->map(fn ($row) => $this->normalizeRow($row));
|
||||||
$filename = $report->slug().'-'.now()->format('Ymd_His');
|
$columns = $this->buildColumnsArray($report);
|
||||||
|
$filename = $report->slug.'-'.now()->format('Ymd_His');
|
||||||
|
|
||||||
if ($format === 'pdf') {
|
if ($format === 'pdf') {
|
||||||
$pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('reports.pdf.table', [
|
$pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('reports.pdf.table', [
|
||||||
'name' => $report->name(),
|
'name' => $report->name,
|
||||||
'columns' => $columns,
|
'columns' => $columns,
|
||||||
'rows' => $rows,
|
'rows' => $rows,
|
||||||
]);
|
]);
|
||||||
@@ -264,9 +279,9 @@ public function clients(Request $request)
|
|||||||
$clients = \App\Models\Client::query()
|
$clients = \App\Models\Client::query()
|
||||||
->with('person:id,full_name')
|
->with('person:id,full_name')
|
||||||
->get()
|
->get()
|
||||||
->map(fn($c) => [
|
->map(fn ($c) => [
|
||||||
'id' => $c->uuid,
|
'id' => $c->uuid,
|
||||||
'name' => $c->person->full_name ?? 'Unknown'
|
'name' => $c->person->full_name ?? 'Unknown',
|
||||||
])
|
])
|
||||||
->sortBy('name')
|
->sortBy('name')
|
||||||
->values();
|
->values();
|
||||||
@@ -274,6 +289,41 @@ public function clients(Request $request)
|
|||||||
return response()->json($clients);
|
return response()->json($clients);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight actions lookup for select:action filters.
|
||||||
|
*/
|
||||||
|
public function actions(Request $request)
|
||||||
|
{
|
||||||
|
$actions = \App\Models\Action::query()
|
||||||
|
->orderBy('name')
|
||||||
|
->get(['id', 'name'])
|
||||||
|
->map(fn ($a) => ['id' => $a->id, 'name' => $a->name])
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return response()->json($actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight decisions lookup for select:decision filters.
|
||||||
|
* Optionally filtered by action_id (for dependent filter UI).
|
||||||
|
*/
|
||||||
|
public function decisions(Request $request)
|
||||||
|
{
|
||||||
|
$actionId = $request->integer('action_id', 0) ?: null;
|
||||||
|
|
||||||
|
$q = \App\Models\Decision::query()->orderBy('name');
|
||||||
|
|
||||||
|
if ($actionId !== null) {
|
||||||
|
$q->whereHas('actions', fn ($qq) => $qq->where('actions.id', $actionId));
|
||||||
|
}
|
||||||
|
|
||||||
|
$decisions = $q->get(['id', 'name'])
|
||||||
|
->map(fn ($d) => ['id' => $d->id, 'name' => $d->name])
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return response()->json($decisions);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build validation rules based on inputs descriptor and validate.
|
* Build validation rules based on inputs descriptor and validate.
|
||||||
*
|
*
|
||||||
@@ -292,6 +342,8 @@ protected function validateFilters(array $inputs, Request $request): array
|
|||||||
'integer' => [$nullable, 'integer'],
|
'integer' => [$nullable, 'integer'],
|
||||||
'select:user' => [$nullable, 'integer', 'exists:users,id'],
|
'select:user' => [$nullable, 'integer', 'exists:users,id'],
|
||||||
'select:client' => [$nullable, 'string', 'exists:clients,uuid'],
|
'select:client' => [$nullable, 'string', 'exists:clients,uuid'],
|
||||||
|
'select:action' => [$nullable, 'integer', 'exists:actions,id'],
|
||||||
|
'select:decision' => [$nullable, 'integer', 'exists:decisions,id'],
|
||||||
default => [$nullable, 'string'],
|
default => [$nullable, 'string'],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -299,6 +351,35 @@ protected function validateFilters(array $inputs, Request $request): array
|
|||||||
return $request->validate($rules);
|
return $request->validate($rules);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build inputs array from report filters.
|
||||||
|
*/
|
||||||
|
protected function buildInputsArray(Report $report): array
|
||||||
|
{
|
||||||
|
return $report->filters->map(fn ($filter) => [
|
||||||
|
'key' => $filter->key,
|
||||||
|
'type' => $filter->type,
|
||||||
|
'label' => $filter->label,
|
||||||
|
'nullable' => $filter->nullable,
|
||||||
|
'default' => $filter->default_value,
|
||||||
|
'options' => $filter->options,
|
||||||
|
])->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build columns array from report columns.
|
||||||
|
*/
|
||||||
|
protected function buildColumnsArray(Report $report): array
|
||||||
|
{
|
||||||
|
return $report->columns
|
||||||
|
->where('visible', true)
|
||||||
|
->map(fn ($col) => [
|
||||||
|
'key' => $col->key,
|
||||||
|
'label' => $col->label,
|
||||||
|
])
|
||||||
|
->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure derived export/display fields exist on row objects.
|
* Ensure derived export/display fields exist on row objects.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -65,6 +65,12 @@ public function show(Segment $segment)
|
|||||||
|
|
||||||
$contracts = $this->hydrateClientShortcut($contracts);
|
$contracts = $this->hydrateClientShortcut($contracts);
|
||||||
|
|
||||||
|
// Hide addresses array since we're using the singular address relationship
|
||||||
|
$contracts->getCollection()->each(function ($contract) {
|
||||||
|
$contract->clientCase?->person?->makeHidden('addresses');
|
||||||
|
$contract->clientCase?->client?->person?->makeHidden('addresses');
|
||||||
|
});
|
||||||
|
|
||||||
$clients = Client::query()
|
$clients = Client::query()
|
||||||
->whereHas('clientCases.contracts.segments', function ($q) use ($segment) {
|
->whereHas('clientCases.contracts.segments', function ($q) use ($segment) {
|
||||||
$q->where('segments.id', $segment->id)
|
$q->where('segments.id', $segment->id)
|
||||||
@@ -191,8 +197,7 @@ private function buildContractsQuery(Segment $segment, ?string $search, ?string
|
|||||||
->where('contract_segment.active', '=', 1);
|
->where('contract_segment.active', '=', 1);
|
||||||
})
|
})
|
||||||
->with([
|
->with([
|
||||||
'clientCase.person',
|
'clientCase.person.address',
|
||||||
'clientCase.client.person',
|
|
||||||
'type',
|
'type',
|
||||||
'account',
|
'account',
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -0,0 +1,293 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Settings;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Models\Report;
|
||||||
|
use App\Models\ReportEntity;
|
||||||
|
use App\Models\ReportColumn;
|
||||||
|
use App\Models\ReportFilter;
|
||||||
|
use App\Models\ReportCondition;
|
||||||
|
use App\Models\ReportOrder;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
|
||||||
|
class ReportSettingsController extends Controller
|
||||||
|
{
|
||||||
|
public function index()
|
||||||
|
{
|
||||||
|
$reports = Report::orderBy('order')->orderBy('name')->get();
|
||||||
|
|
||||||
|
return Inertia::render('Settings/Reports/Index', [
|
||||||
|
'reports' => $reports,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function edit(Report $report)
|
||||||
|
{
|
||||||
|
$report->load(['entities', 'columns', 'filters', 'conditions', 'orders']);
|
||||||
|
|
||||||
|
return Inertia::render('Settings/Reports/Edit', [
|
||||||
|
'report' => $report,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'slug' => 'required|string|unique:reports,slug|max:255',
|
||||||
|
'name' => 'required|string|max:255',
|
||||||
|
'description' => 'nullable|string',
|
||||||
|
'category' => 'nullable|string|max:100',
|
||||||
|
'enabled' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report = Report::create($validated);
|
||||||
|
|
||||||
|
return redirect()->route('settings.reports.index')
|
||||||
|
->with('success', 'Report created successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Request $request, Report $report)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'slug' => 'required|string|unique:reports,slug,' . $report->id . '|max:255',
|
||||||
|
'name' => 'required|string|max:255',
|
||||||
|
'description' => 'nullable|string',
|
||||||
|
'category' => 'nullable|string|max:100',
|
||||||
|
'enabled' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->update($validated);
|
||||||
|
|
||||||
|
return redirect()->route('settings.reports.index')
|
||||||
|
->with('success', 'Report updated successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroy(Report $report)
|
||||||
|
{
|
||||||
|
$report->delete();
|
||||||
|
|
||||||
|
return redirect()->route('settings.reports.index')
|
||||||
|
->with('success', 'Report deleted successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toggleEnabled(Report $report)
|
||||||
|
{
|
||||||
|
$report->update(['enabled' => !$report->enabled]);
|
||||||
|
|
||||||
|
return back()->with('success', 'Report status updated.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entity CRUD
|
||||||
|
public function storeEntity(Request $request, Report $report)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'model_class' => 'required|string|max:255',
|
||||||
|
'alias' => 'nullable|string|max:50',
|
||||||
|
'join_type' => 'required|in:base,join,leftJoin,rightJoin',
|
||||||
|
'join_first' => 'nullable|string|max:100',
|
||||||
|
'join_operator' => 'nullable|string|max:10',
|
||||||
|
'join_second' => 'nullable|string|max:100',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->entities()->create($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Entity added successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateEntity(Request $request, ReportEntity $entity)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'model_class' => 'required|string|max:255',
|
||||||
|
'alias' => 'nullable|string|max:50',
|
||||||
|
'join_type' => 'required|in:base,join,leftJoin,rightJoin',
|
||||||
|
'join_first' => 'nullable|string|max:100',
|
||||||
|
'join_operator' => 'nullable|string|max:10',
|
||||||
|
'join_second' => 'nullable|string|max:100',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$entity->update($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Entity updated successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroyEntity(ReportEntity $entity)
|
||||||
|
{
|
||||||
|
$entity->delete();
|
||||||
|
|
||||||
|
return back()->with('success', 'Entity deleted successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Column CRUD
|
||||||
|
public function storeColumn(Request $request, Report $report)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'key' => 'required|string|max:100',
|
||||||
|
'label' => 'required|string|max:255',
|
||||||
|
'type' => 'required|string|max:50',
|
||||||
|
'expression' => 'required|string',
|
||||||
|
'sortable' => 'boolean',
|
||||||
|
'visible' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
'format_options' => 'nullable|array',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->columns()->create($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Column added successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateColumn(Request $request, ReportColumn $column)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'key' => 'required|string|max:100',
|
||||||
|
'label' => 'required|string|max:255',
|
||||||
|
'type' => 'required|string|max:50',
|
||||||
|
'expression' => 'required|string',
|
||||||
|
'sortable' => 'boolean',
|
||||||
|
'visible' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
'format_options' => 'nullable|array',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$column->update($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Column updated successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroyColumn(ReportColumn $column)
|
||||||
|
{
|
||||||
|
$column->delete();
|
||||||
|
|
||||||
|
return back()->with('success', 'Column deleted successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter CRUD
|
||||||
|
public function storeFilter(Request $request, Report $report)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'key' => 'required|string|max:100',
|
||||||
|
'label' => 'required|string|max:255',
|
||||||
|
'type' => 'required|string|max:50',
|
||||||
|
'nullable' => 'boolean',
|
||||||
|
'default_value' => 'nullable|string',
|
||||||
|
'options' => 'nullable|array',
|
||||||
|
'data_source' => 'nullable|string|max:255',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->filters()->create($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Filter added successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateFilter(Request $request, ReportFilter $filter)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'key' => 'required|string|max:100',
|
||||||
|
'label' => 'required|string|max:255',
|
||||||
|
'type' => 'required|string|max:50',
|
||||||
|
'nullable' => 'boolean',
|
||||||
|
'default_value' => 'nullable|string',
|
||||||
|
'options' => 'nullable|array',
|
||||||
|
'data_source' => 'nullable|string|max:255',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$filter->update($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Filter updated successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroyFilter(ReportFilter $filter)
|
||||||
|
{
|
||||||
|
$filter->delete();
|
||||||
|
|
||||||
|
return back()->with('success', 'Filter deleted successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Condition CRUD
|
||||||
|
public function storeCondition(Request $request, Report $report)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'column' => 'required|string|max:255',
|
||||||
|
'operator' => 'required|string|max:50',
|
||||||
|
'value_type' => 'required|in:static,filter,expression',
|
||||||
|
'value' => 'nullable|string',
|
||||||
|
'filter_key' => 'nullable|string|max:100',
|
||||||
|
'logical_operator' => 'required|in:AND,OR',
|
||||||
|
'group_id' => 'nullable|integer',
|
||||||
|
'order' => 'integer',
|
||||||
|
'enabled' => 'boolean',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->conditions()->create($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Condition added successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateCondition(Request $request, ReportCondition $condition)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'column' => 'required|string|max:255',
|
||||||
|
'operator' => 'required|string|max:50',
|
||||||
|
'value_type' => 'required|in:static,filter,expression',
|
||||||
|
'value' => 'nullable|string',
|
||||||
|
'filter_key' => 'nullable|string|max:100',
|
||||||
|
'logical_operator' => 'required|in:AND,OR',
|
||||||
|
'group_id' => 'nullable|integer',
|
||||||
|
'order' => 'integer',
|
||||||
|
'enabled' => 'boolean',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$condition->update($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Condition updated successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroyCondition(ReportCondition $condition)
|
||||||
|
{
|
||||||
|
$condition->delete();
|
||||||
|
|
||||||
|
return back()->with('success', 'Condition deleted successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Order CRUD
|
||||||
|
public function storeOrder(Request $request, Report $report)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'column' => 'required|string|max:255',
|
||||||
|
'direction' => 'required|in:ASC,DESC',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$report->orders()->create($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Order clause added successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateOrder(Request $request, ReportOrder $order)
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'column' => 'required|string|max:255',
|
||||||
|
'direction' => 'required|in:ASC,DESC',
|
||||||
|
'order' => 'integer',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$order->update($validated);
|
||||||
|
|
||||||
|
return back()->with('success', 'Order clause updated successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function destroyOrder(ReportOrder $order)
|
||||||
|
{
|
||||||
|
$order->delete();
|
||||||
|
|
||||||
|
return back()->with('success', 'Order clause deleted successfully.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
use App\Models\Decision;
|
use App\Models\Decision;
|
||||||
use App\Models\EmailTemplate;
|
use App\Models\EmailTemplate;
|
||||||
use App\Models\Segment;
|
use App\Models\Segment;
|
||||||
|
use App\Services\DecisionEvents\ConditionEvaluator;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
@@ -22,6 +23,8 @@ public function index(Request $request)
|
|||||||
'email_templates' => EmailTemplate::query()->where('active', true)->get(['id', 'name', 'entity_types']),
|
'email_templates' => EmailTemplate::query()->where('active', true)->get(['id', 'name', 'entity_types']),
|
||||||
'events' => \App\Models\Event::query()->orderBy('name')->get(['id', 'name', 'key', 'description', 'active']),
|
'events' => \App\Models\Event::query()->orderBy('name')->get(['id', 'name', 'key', 'description', 'active']),
|
||||||
'archive_settings' => ArchiveSetting::query()->where('enabled', true)->orderBy('id')->get(['id', 'name']),
|
'archive_settings' => ArchiveSetting::query()->where('enabled', true)->orderBy('id')->get(['id', 'name']),
|
||||||
|
'condition_fields' => ConditionEvaluator::availableFields(),
|
||||||
|
'condition_operators' => ConditionEvaluator::availableOperators(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,6 +86,9 @@ public function updateAction(int $id, Request $request)
|
|||||||
|
|
||||||
public function storeDecision(Request $request)
|
public function storeDecision(Request $request)
|
||||||
{
|
{
|
||||||
|
$allowedConditionFields = collect(ConditionEvaluator::availableFields())->pluck('key')->implode(',');
|
||||||
|
$allowedOperators = 'in:=,!=,>,>=,<,<=,contains';
|
||||||
|
|
||||||
$attributes = $request->validate([
|
$attributes = $request->validate([
|
||||||
'name' => 'required|string|max:50',
|
'name' => 'required|string|max:50',
|
||||||
'color_tag' => 'nullable|string|max:25',
|
'color_tag' => 'nullable|string|max:25',
|
||||||
@@ -96,6 +102,14 @@ public function storeDecision(Request $request)
|
|||||||
'events.*.active' => 'sometimes|boolean',
|
'events.*.active' => 'sometimes|boolean',
|
||||||
'events.*.run_order' => 'nullable|integer',
|
'events.*.run_order' => 'nullable|integer',
|
||||||
'events.*.config' => 'nullable|array',
|
'events.*.config' => 'nullable|array',
|
||||||
|
'events.*.config.segment_id' => 'nullable|integer|exists:segments,id',
|
||||||
|
'events.*.config.deactivate_previous' => 'sometimes|boolean',
|
||||||
|
'events.*.config.archive_setting_id' => 'nullable|integer|exists:archive_settings,id',
|
||||||
|
'events.*.config.reactivate' => 'sometimes|boolean',
|
||||||
|
'events.*.config.conditions' => 'nullable|array',
|
||||||
|
'events.*.config.conditions.*.field' => "required_with:events.*.config.conditions.*|string|in:{$allowedConditionFields}",
|
||||||
|
'events.*.config.conditions.*.operator' => "required_with:events.*.config.conditions.*|string|{$allowedOperators}",
|
||||||
|
'events.*.config.conditions.*.value' => 'required_with:events.*.config.conditions.*',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
|
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
|
||||||
@@ -112,12 +126,12 @@ public function storeDecision(Request $request)
|
|||||||
$key = $eventModel?->key ?? ($ev['key'] ?? null);
|
$key = $eventModel?->key ?? ($ev['key'] ?? null);
|
||||||
if ($key === 'add_segment') {
|
if ($key === 'add_segment') {
|
||||||
$seg = $ev['config']['segment_id'] ?? null;
|
$seg = $ev['config']['segment_id'] ?? null;
|
||||||
if (empty($seg) || ! Segment::where('id', $seg)->exists()) {
|
if (empty($seg)) {
|
||||||
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
|
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
|
||||||
}
|
}
|
||||||
} elseif ($key === 'archive_contract') {
|
} elseif ($key === 'archive_contract') {
|
||||||
$as = $ev['config']['archive_setting_id'] ?? null;
|
$as = $ev['config']['archive_setting_id'] ?? null;
|
||||||
if (empty($as) || ! ArchiveSetting::where('id', $as)->exists()) {
|
if (empty($as)) {
|
||||||
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
|
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -174,6 +188,9 @@ public function updateDecision(int $id, Request $request)
|
|||||||
{
|
{
|
||||||
$row = Decision::findOrFail($id);
|
$row = Decision::findOrFail($id);
|
||||||
|
|
||||||
|
$allowedConditionFields = collect(ConditionEvaluator::availableFields())->pluck('key')->implode(',');
|
||||||
|
$allowedOperators = 'in:=,!=,>,>=,<,<=,contains';
|
||||||
|
|
||||||
$attributes = $request->validate([
|
$attributes = $request->validate([
|
||||||
'name' => 'required|string|max:50',
|
'name' => 'required|string|max:50',
|
||||||
'color_tag' => 'nullable|string|max:25',
|
'color_tag' => 'nullable|string|max:25',
|
||||||
@@ -187,6 +204,14 @@ public function updateDecision(int $id, Request $request)
|
|||||||
'events.*.active' => 'sometimes|boolean',
|
'events.*.active' => 'sometimes|boolean',
|
||||||
'events.*.run_order' => 'nullable|integer',
|
'events.*.run_order' => 'nullable|integer',
|
||||||
'events.*.config' => 'nullable|array',
|
'events.*.config' => 'nullable|array',
|
||||||
|
'events.*.config.segment_id' => 'nullable|integer|exists:segments,id',
|
||||||
|
'events.*.config.deactivate_previous' => 'sometimes|boolean',
|
||||||
|
'events.*.config.archive_setting_id' => 'nullable|integer|exists:archive_settings,id',
|
||||||
|
'events.*.config.reactivate' => 'sometimes|boolean',
|
||||||
|
'events.*.config.conditions' => 'nullable|array',
|
||||||
|
'events.*.config.conditions.*.field' => "required_with:events.*.config.conditions.*|string|in:{$allowedConditionFields}",
|
||||||
|
'events.*.config.conditions.*.operator' => "required_with:events.*.config.conditions.*|string|{$allowedOperators}",
|
||||||
|
'events.*.config.conditions.*.value' => 'required_with:events.*.config.conditions.*',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
|
$actionIds = collect($attributes['actions'] ?? [])->pluck('id')->toArray();
|
||||||
@@ -203,12 +228,12 @@ public function updateDecision(int $id, Request $request)
|
|||||||
$key = $eventModel?->key ?? ($ev['key'] ?? null);
|
$key = $eventModel?->key ?? ($ev['key'] ?? null);
|
||||||
if ($key === 'add_segment') {
|
if ($key === 'add_segment') {
|
||||||
$seg = $ev['config']['segment_id'] ?? null;
|
$seg = $ev['config']['segment_id'] ?? null;
|
||||||
if (empty($seg) || ! Segment::where('id', $seg)->exists()) {
|
if (empty($seg)) {
|
||||||
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
|
$validationErrors["events.$i.config.segment_id"] = 'Please select a valid segment for the add_segment event.';
|
||||||
}
|
}
|
||||||
} elseif ($key === 'archive_contract') {
|
} elseif ($key === 'archive_contract') {
|
||||||
$as = $ev['config']['archive_setting_id'] ?? null;
|
$as = $ev['config']['archive_setting_id'] ?? null;
|
||||||
if (empty($as) || ! ArchiveSetting::where('id', $as)->exists()) {
|
if (empty($as)) {
|
||||||
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
|
$validationErrors["events.$i.config.archive_setting_id"] = 'Please select a valid archive setting for the archive_contract event.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,6 +59,15 @@ public function share(Request $request): array
|
|||||||
'info' => fn () => $request->session()->get('info'),
|
'info' => fn () => $request->session()->get('info'),
|
||||||
'method' => fn () => $request->session()->get('flash_method'), // HTTP method for toast styling
|
'method' => fn () => $request->session()->get('flash_method'), // HTTP method for toast styling
|
||||||
],
|
],
|
||||||
|
'callLaterCount' => function () use ($request) {
|
||||||
|
if (! $request->user()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return \App\Models\CallLater::query()
|
||||||
|
->whereNull('completed_at')
|
||||||
|
->count();
|
||||||
|
},
|
||||||
'notifications' => function () use ($request) {
|
'notifications' => function () use ($request) {
|
||||||
try {
|
try {
|
||||||
$user = $request->user();
|
$user = $request->user();
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use App\Exports\ClientContractsExport;
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
|
class ExportClientContractsRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public const SCOPE_CURRENT = 'current';
|
||||||
|
|
||||||
|
public const SCOPE_ALL = 'all';
|
||||||
|
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return $this->user() !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
$columnRule = Rule::in(ClientContractsExport::allowedColumns());
|
||||||
|
|
||||||
|
return [
|
||||||
|
'scope' => ['required', Rule::in([self::SCOPE_CURRENT, self::SCOPE_ALL])],
|
||||||
|
'columns' => ['required', 'array', 'min:1'],
|
||||||
|
'columns.*' => ['string', $columnRule],
|
||||||
|
'search' => ['nullable', 'string', 'max:255'],
|
||||||
|
'from' => ['nullable', 'date'],
|
||||||
|
'to' => ['nullable', 'date'],
|
||||||
|
'segments' => ['nullable', 'string'],
|
||||||
|
'page' => ['nullable', 'integer', 'min:1'],
|
||||||
|
'per_page' => ['nullable', 'integer', 'min:1', 'max:200'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function prepareForValidation(): void
|
||||||
|
{
|
||||||
|
$this->merge([
|
||||||
|
'per_page' => $this->input('per_page') ?? $this->input('perPage'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class StoreEmailPackageFromContractsRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return $this->user()?->can('manage-settings') ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type' => ['required', 'in:email'],
|
||||||
|
'name' => ['nullable', 'string', 'max:255'],
|
||||||
|
'description' => ['nullable', 'string'],
|
||||||
|
'meta' => ['nullable', 'array'],
|
||||||
|
|
||||||
|
// Common payload for all items
|
||||||
|
'payload' => ['required', 'array'],
|
||||||
|
'payload.mail_profile_id' => ['nullable', 'integer', 'exists:mail_profiles,id'],
|
||||||
|
'payload.template_id' => ['nullable', 'integer', 'exists:email_templates,id'],
|
||||||
|
'payload.subject' => ['nullable', 'string', 'max:255'],
|
||||||
|
'payload.body_text' => ['nullable', 'string', 'max:10000'],
|
||||||
|
'payload.variables' => ['nullable', 'array'],
|
||||||
|
|
||||||
|
// Source contracts to derive items from
|
||||||
|
'contract_ids' => ['required', 'array', 'min:1'],
|
||||||
|
'contract_ids.*' => ['integer', 'exists:contracts,id'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,9 @@ public function rules(): array
|
|||||||
'entity_types.*' => ['string', 'in:client,client_case,contract,person'],
|
'entity_types.*' => ['string', 'in:client,client_case,contract,person'],
|
||||||
'allow_attachments' => ['sometimes', 'boolean'],
|
'allow_attachments' => ['sometimes', 'boolean'],
|
||||||
'active' => ['boolean'],
|
'active' => ['boolean'],
|
||||||
|
'client' => ['sometimes', 'boolean'],
|
||||||
|
'action_id' => ['nullable', 'integer', 'exists:actions,id'],
|
||||||
|
'decision_id' => ['nullable', 'integer', 'exists:decisions,id'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class StoreInstallmentRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'amount' => ['required', 'numeric', 'min:0.01'],
|
||||||
|
'currency' => ['nullable', 'string', 'size:3'],
|
||||||
|
'reference' => ['nullable', 'string', 'max:100'],
|
||||||
|
'installment_at' => ['nullable', 'date'],
|
||||||
|
'meta' => ['nullable', 'array'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,9 @@ public function rules(): array
|
|||||||
'reply_to_name' => ['nullable', 'string', 'max:190'],
|
'reply_to_name' => ['nullable', 'string', 'max:190'],
|
||||||
'priority' => ['nullable', 'integer', 'between:0,65535'],
|
'priority' => ['nullable', 'integer', 'between:0,65535'],
|
||||||
'max_daily_quota' => ['nullable', 'integer', 'min:0'],
|
'max_daily_quota' => ['nullable', 'integer', 'min:0'],
|
||||||
|
'signature' => ['nullable', 'array'],
|
||||||
|
'signature.*' => ['nullable', 'string', 'max:1000'],
|
||||||
|
'auto_mailer' => ['nullable', 'boolean'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class UpdateContractSettingRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'create_activity_on_balance_change' => ['sometimes', 'boolean'],
|
||||||
|
'default_action_id' => ['nullable', 'integer', 'exists:actions,id'],
|
||||||
|
'default_decision_id' => ['nullable', 'integer', 'exists:decisions,id'],
|
||||||
|
'activity_note_template' => ['nullable', 'string', 'max:255'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,9 @@ public function rules(): array
|
|||||||
'entity_types.*' => ['string', 'in:client,client_case,contract,person'],
|
'entity_types.*' => ['string', 'in:client,client_case,contract,person'],
|
||||||
'allow_attachments' => ['sometimes', 'boolean'],
|
'allow_attachments' => ['sometimes', 'boolean'],
|
||||||
'active' => ['boolean'],
|
'active' => ['boolean'],
|
||||||
|
'client' => ['sometimes', 'boolean'],
|
||||||
|
'action_id' => ['nullable', 'integer', 'exists:actions,id'],
|
||||||
|
'decision_id' => ['nullable', 'integer', 'exists:decisions,id'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class UpdateInstallmentSettingRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'default_currency' => ['required', 'string', 'size:3'],
|
||||||
|
'create_activity_on_installment' => ['sometimes', 'boolean'],
|
||||||
|
'default_decision_id' => ['nullable', 'integer', 'exists:decisions,id'],
|
||||||
|
'default_action_id' => ['nullable', 'integer', 'exists:actions,id'],
|
||||||
|
'activity_note_template' => ['nullable', 'string', 'max:255'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,6 +27,9 @@ public function rules(): array
|
|||||||
'priority' => ['nullable', 'integer', 'between:0,65535'],
|
'priority' => ['nullable', 'integer', 'between:0,65535'],
|
||||||
'max_daily_quota' => ['nullable', 'integer', 'min:0'],
|
'max_daily_quota' => ['nullable', 'integer', 'min:0'],
|
||||||
'active' => ['nullable', 'boolean'],
|
'active' => ['nullable', 'boolean'],
|
||||||
|
'signature' => ['nullable', 'array'],
|
||||||
|
'signature.*' => ['nullable', 'string', 'max:1000'],
|
||||||
|
'auto_mailer' => ['nullable', 'boolean'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Responses;
|
||||||
|
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
|
||||||
|
|
||||||
|
class LoginResponse implements LoginResponseContract
|
||||||
|
{
|
||||||
|
public function toResponse($request): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
$default = $user?->login_redirect ?: config('fortify.home');
|
||||||
|
|
||||||
|
return redirect()->intended($default);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Jobs;
|
||||||
|
|
||||||
|
use App\Models\Contract;
|
||||||
|
use App\Models\Email;
|
||||||
|
use App\Models\EmailLog;
|
||||||
|
use App\Models\EmailLogStatus;
|
||||||
|
use App\Models\EmailTemplate;
|
||||||
|
use App\Models\MailProfile;
|
||||||
|
use App\Models\Package;
|
||||||
|
use App\Models\PackageItem;
|
||||||
|
use App\Services\EmailSender;
|
||||||
|
use App\Services\EmailTemplateRenderer;
|
||||||
|
use Illuminate\Bus\Batchable;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
class PackageItemEmailJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Batchable, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public function __construct(public int $packageItemId)
|
||||||
|
{
|
||||||
|
$this->onQueue('email');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(EmailTemplateRenderer $renderer, EmailSender $sender): void
|
||||||
|
{
|
||||||
|
/** @var PackageItem|null $item */
|
||||||
|
$item = PackageItem::query()->find($this->packageItemId);
|
||||||
|
if (! $item) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Package $package */
|
||||||
|
$package = $item->package;
|
||||||
|
if (! $package || $package->status === Package::STATUS_CANCELED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($item->status, ['sent', 'failed', 'canceled', 'skipped'], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($item->status === 'queued') {
|
||||||
|
$item->status = 'processing';
|
||||||
|
$item->save();
|
||||||
|
$package->increment('processing_count');
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = (array) $item->payload_json;
|
||||||
|
$target = (array) $item->target_json;
|
||||||
|
|
||||||
|
$to = $target['email'] ?? null;
|
||||||
|
if (! is_string($to) || ! filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
||||||
|
$item->status = 'failed';
|
||||||
|
$item->last_error = 'Missing or invalid recipient email.';
|
||||||
|
$item->save();
|
||||||
|
$this->updatePackageCounters($item, $package);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$templateId = $payload['template_id'] ?? null;
|
||||||
|
$mailProfileId = $payload['mail_profile_id'] ?? null;
|
||||||
|
$variables = (array) ($payload['variables'] ?? []);
|
||||||
|
$subjectOverride = isset($payload['subject']) ? trim((string) $payload['subject']) : null;
|
||||||
|
if ($subjectOverride === '') {
|
||||||
|
$subjectOverride = null;
|
||||||
|
}
|
||||||
|
$bodyText = isset($payload['body_text']) ? (string) $payload['body_text'] : '';
|
||||||
|
|
||||||
|
// Enrich variables with contract/account context when available
|
||||||
|
$contract = null;
|
||||||
|
if (! empty($target['contract_id'])) {
|
||||||
|
$contract = Contract::query()->with(['clientCase.person', 'account.type'])->find($target['contract_id']);
|
||||||
|
if ($contract) {
|
||||||
|
$variables['contract'] = [
|
||||||
|
'id' => $contract->id,
|
||||||
|
'uuid' => $contract->uuid,
|
||||||
|
'reference' => $contract->reference,
|
||||||
|
'start_date' => (string) ($contract->start_date ?? ''),
|
||||||
|
'end_date' => (string) ($contract->end_date ?? ''),
|
||||||
|
];
|
||||||
|
if (is_array($contract->meta) && ! empty($contract->meta)) {
|
||||||
|
$variables['contract']['meta'] = $this->flattenMeta($contract->meta);
|
||||||
|
}
|
||||||
|
if ($contract->account) {
|
||||||
|
$initialRaw = (string) $contract->account->initial_amount;
|
||||||
|
$balanceRaw = (string) $contract->account->balance_amount;
|
||||||
|
$variables['account'] = [
|
||||||
|
'id' => $contract->account->id,
|
||||||
|
'reference' => $contract->account->reference,
|
||||||
|
'initial_amount' => $this->formatAmountEu($initialRaw),
|
||||||
|
'balance_amount' => $this->formatAmountEu($balanceRaw),
|
||||||
|
'initial_amount_raw' => $initialRaw,
|
||||||
|
'balance_amount_raw' => $balanceRaw,
|
||||||
|
'type' => $contract->account->type?->name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if ($contract->clientCase?->person) {
|
||||||
|
$person = $contract->clientCase->person;
|
||||||
|
$variables['person'] = [
|
||||||
|
'full_name' => $person->full_name,
|
||||||
|
'first_name' => $person->first_name,
|
||||||
|
'last_name' => $person->last_name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var EmailTemplate|null $template */
|
||||||
|
$template = $templateId ? EmailTemplate::with(['action', 'decision'])->find((int) $templateId) : null;
|
||||||
|
|
||||||
|
/** @var MailProfile|null $mailProfile */
|
||||||
|
$mailProfile = $mailProfileId
|
||||||
|
? MailProfile::find((int) $mailProfileId)
|
||||||
|
: MailProfile::query()->where('active', true)->orderBy('priority')->orderBy('id')->first();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (! $template && ! $subjectOverride) {
|
||||||
|
throw new \RuntimeException('No email template or subject provided.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$rendered = $template
|
||||||
|
? $renderer->render([
|
||||||
|
'subject' => $subjectOverride ?? (string) $template->subject_template,
|
||||||
|
'html' => (string) $template->html_template,
|
||||||
|
'text' => (string) $template->text_template,
|
||||||
|
], array_filter([
|
||||||
|
'contract' => $contract,
|
||||||
|
'person' => $contract?->clientCase?->person,
|
||||||
|
'client' => $contract?->clientCase?->client,
|
||||||
|
'client_case' => $contract?->clientCase,
|
||||||
|
'mail_profile' => $mailProfile,
|
||||||
|
'extra' => $variables,
|
||||||
|
'body_text' => $bodyText !== '' ? $bodyText : null,
|
||||||
|
]))
|
||||||
|
: [
|
||||||
|
'subject' => $subjectOverride ?? '',
|
||||||
|
'html' => null,
|
||||||
|
'text' => null,
|
||||||
|
];
|
||||||
|
|
||||||
|
$log = new EmailLog;
|
||||||
|
$log->fill([
|
||||||
|
'uuid' => (string) Str::uuid(),
|
||||||
|
'template_id' => $template?->id,
|
||||||
|
'mail_profile_id' => $mailProfile?->id,
|
||||||
|
'to_email' => $to,
|
||||||
|
'to_recipients' => [$to],
|
||||||
|
'subject' => $rendered['subject'],
|
||||||
|
'body_html_hash' => isset($rendered['html']) ? hash('sha256', (string) $rendered['html']) : null,
|
||||||
|
'body_text_preview' => isset($rendered['text']) ? mb_strimwidth((string) $rendered['text'], 0, 4096) : null,
|
||||||
|
'embed_mode' => 'base64',
|
||||||
|
'status' => EmailLogStatus::Queued,
|
||||||
|
'queued_at' => now(),
|
||||||
|
'contract_id' => $contract?->id,
|
||||||
|
'client_id' => $contract?->clientCase?->client?->id,
|
||||||
|
'client_case_id' => $contract?->clientCase?->id,
|
||||||
|
'extra_context' => ['package_id' => $item->package_id, 'package_item_id' => $item->id],
|
||||||
|
]);
|
||||||
|
$log->save();
|
||||||
|
|
||||||
|
$log->body()->create([
|
||||||
|
'body_html' => (string) ($rendered['html'] ?? ''),
|
||||||
|
'body_text' => (string) ($rendered['text'] ?? ''),
|
||||||
|
'inline_css' => true,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Send directly (synchronous within job context)
|
||||||
|
$start = microtime(true);
|
||||||
|
$log->status = EmailLogStatus::Sending;
|
||||||
|
$log->started_at = now();
|
||||||
|
$log->attempt = 1;
|
||||||
|
$log->save();
|
||||||
|
|
||||||
|
$sender->sendFromLog($log);
|
||||||
|
|
||||||
|
$log->status = EmailLogStatus::Sent;
|
||||||
|
$log->sent_at = now();
|
||||||
|
$log->duration_ms = (int) round((microtime(true) - $start) * 1000);
|
||||||
|
$log->save();
|
||||||
|
|
||||||
|
$item->status = 'sent';
|
||||||
|
$item->result_json = ['email_log_id' => $log->id, 'subject' => $rendered['subject']];
|
||||||
|
$item->last_error = null;
|
||||||
|
$item->save();
|
||||||
|
|
||||||
|
// Clear failed flag on successful delivery
|
||||||
|
Email::query()->where('value', $to)->where('failed', true)->update(['failed' => false]);
|
||||||
|
|
||||||
|
// Create activity if the template has action/decision configured
|
||||||
|
if ($template && ($template->action_id || $template->decision_id) && $contract && $contract->client_case_id) {
|
||||||
|
$activity = \App\Models\Activity::create(array_filter([
|
||||||
|
'client_case_id' => $contract->client_case_id,
|
||||||
|
'contract_id' => $contract->id,
|
||||||
|
'action_id' => $template->action_id,
|
||||||
|
'decision_id' => $template->decision_id,
|
||||||
|
'note' => 'Poslano: '.$to.', Uspešno'.($bodyText !== '' ? ' | Vsebina: '.mb_strimwidth($bodyText, 0, 500, '…') : ''),
|
||||||
|
]));
|
||||||
|
$activity->emailLogs()->attach($log->id);
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$item->status = 'failed';
|
||||||
|
$item->last_error = $e->getMessage();
|
||||||
|
$item->save();
|
||||||
|
|
||||||
|
// Create activity for failed send if the template has action/decision configured
|
||||||
|
if ($template && ($template->action_id || $template->decision_id) && isset($contract) && $contract && $contract->client_case_id) {
|
||||||
|
$shortError = mb_strimwidth($e->getMessage(), 0, 120, '…');
|
||||||
|
$activity = \App\Models\Activity::create(array_filter([
|
||||||
|
'client_case_id' => $contract->client_case_id,
|
||||||
|
'contract_id' => $contract->id,
|
||||||
|
'action_id' => $template->action_id,
|
||||||
|
'decision_id' => $template->decision_id,
|
||||||
|
'note' => 'Poslano: '.$to.', Napaka pri pošiljanju: '.$shortError.($bodyText !== '' ? ' | Vsebina: '.mb_strimwidth($bodyText, 0, 500, '…') : ''),
|
||||||
|
]));
|
||||||
|
if (isset($log) && $log->exists) {
|
||||||
|
$activity->emailLogs()->attach($log->id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark the email address as failed in the DB.
|
||||||
|
if (isset($to)) {
|
||||||
|
Email::query()
|
||||||
|
->where('value', $to)
|
||||||
|
->update(['failed' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Permanent SMTP rejection (550 user unknown, 551 not local, 553 invalid address)
|
||||||
|
// means the address definitively does not exist — also mark it invalid.
|
||||||
|
if ($e instanceof \Symfony\Component\Mailer\Exception\TransportExceptionInterface
|
||||||
|
&& preg_match('/\b55[013]\b/', $e->getMessage())
|
||||||
|
&& isset($to)) {
|
||||||
|
Email::query()
|
||||||
|
->where('value', $to)
|
||||||
|
->update(['valid' => false]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->updatePackageCounters($item, $package);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function updatePackageCounters(PackageItem $item, Package $package): void
|
||||||
|
{
|
||||||
|
if ($item->status === 'sent') {
|
||||||
|
$package->increment('sent_count');
|
||||||
|
} else {
|
||||||
|
$package->increment('failed_count');
|
||||||
|
}
|
||||||
|
|
||||||
|
$package->decrement('processing_count');
|
||||||
|
|
||||||
|
$package->refresh();
|
||||||
|
$done = $package->sent_count + $package->failed_count;
|
||||||
|
if ($done >= $package->total_items) {
|
||||||
|
$package->status = $package->failed_count > 0 ? Package::STATUS_FAILED : Package::STATUS_COMPLETED;
|
||||||
|
$package->finished_at = now();
|
||||||
|
$package->save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function flattenMeta(array $meta, string $prefix = ''): array
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
foreach ($meta as $key => $value) {
|
||||||
|
$newKey = $prefix === '' ? $key : "{$prefix}.{$key}";
|
||||||
|
if (is_array($value)) {
|
||||||
|
if (isset($value['value'])) {
|
||||||
|
$result[$newKey] = $value['value'];
|
||||||
|
} else {
|
||||||
|
$nested = $this->flattenMeta($value, $newKey);
|
||||||
|
$result = array_merge($result, $nested);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$result[$newKey] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function formatAmountEu(string $raw): string
|
||||||
|
{
|
||||||
|
$numeric = preg_replace('/[^0-9.]/', '', $raw);
|
||||||
|
$float = (float) $numeric;
|
||||||
|
|
||||||
|
return number_format($float, 2, ',', '.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Jobs;
|
||||||
|
|
||||||
|
use App\Models\Import;
|
||||||
|
use App\Models\ImportEvent;
|
||||||
|
use App\Services\Import\ImportServiceV2;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Queue\Queueable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
|
class ProcessLargeImportJob implements ShouldQueue
|
||||||
|
{
|
||||||
|
use InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public $timeout = 3600; // 1 hour
|
||||||
|
|
||||||
|
public $tries = 3;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new job instance.
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
public Import $import,
|
||||||
|
public ?int $userId = null
|
||||||
|
) {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the job.
|
||||||
|
*/
|
||||||
|
public function handle(): void
|
||||||
|
{
|
||||||
|
Log::info('ProcessLargeImportJob started', [
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'user_id' => $this->userId,
|
||||||
|
]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$user = $this->userId ? \App\Models\User::find($this->userId) : null;
|
||||||
|
|
||||||
|
$service = app(ImportServiceV2::class);
|
||||||
|
$results = $service->process($this->import, $user);
|
||||||
|
|
||||||
|
Log::info('ProcessLargeImportJob completed', [
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'results' => $results,
|
||||||
|
]);
|
||||||
|
|
||||||
|
ImportEvent::create([
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'user_id' => $this->userId,
|
||||||
|
'event' => 'queue_job_completed',
|
||||||
|
'level' => 'info',
|
||||||
|
'message' => sprintf(
|
||||||
|
'Queued import completed: %d imported, %d skipped, %d invalid',
|
||||||
|
$results['imported'],
|
||||||
|
$results['skipped'],
|
||||||
|
$results['invalid']
|
||||||
|
),
|
||||||
|
'context' => $results,
|
||||||
|
]);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
Log::error('ProcessLargeImportJob failed', [
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
'trace' => $e->getTraceAsString(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->import->update(['status' => 'failed']);
|
||||||
|
|
||||||
|
ImportEvent::create([
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'user_id' => $this->userId,
|
||||||
|
'event' => 'queue_job_failed',
|
||||||
|
'level' => 'error',
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle a job failure.
|
||||||
|
*/
|
||||||
|
public function failed(\Throwable $exception): void
|
||||||
|
{
|
||||||
|
Log::error('ProcessLargeImportJob permanently failed', [
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'error' => $exception->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->import->update(['status' => 'failed']);
|
||||||
|
|
||||||
|
ImportEvent::create([
|
||||||
|
'import_id' => $this->import->id,
|
||||||
|
'user_id' => $this->userId,
|
||||||
|
'event' => 'queue_job_permanently_failed',
|
||||||
|
'level' => 'error',
|
||||||
|
'message' => 'Import job failed after maximum retries: '.$exception->getMessage(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
use App\Models\Activity;
|
use App\Models\Activity;
|
||||||
use App\Models\Event as DecisionEventModel;
|
use App\Models\Event as DecisionEventModel;
|
||||||
|
use App\Services\DecisionEvents\ConditionEvaluator;
|
||||||
use App\Services\DecisionEvents\DecisionEventContext;
|
use App\Services\DecisionEvents\DecisionEventContext;
|
||||||
use App\Services\DecisionEvents\Registry;
|
use App\Services\DecisionEvents\Registry;
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
@@ -68,6 +69,23 @@ public function handle(): void
|
|||||||
user: $activity->user,
|
user: $activity->user,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// [2] Condition check — skip the event if any condition is not met
|
||||||
|
$conditions = $this->config['conditions'] ?? [];
|
||||||
|
if (! empty($conditions)) {
|
||||||
|
$conditionsMet = app(ConditionEvaluator::class)->evaluate($conditions, $context);
|
||||||
|
if (! $conditionsMet) {
|
||||||
|
DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->update([
|
||||||
|
'status' => 'skipped',
|
||||||
|
'message' => 'Condition not met',
|
||||||
|
'finished_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// [3] Resolve handler → handle()
|
||||||
$handler->handle($context, $this->config);
|
$handler->handle($context, $this->config);
|
||||||
|
|
||||||
DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->update([
|
DB::table('decision_event_logs')->where('idempotency_key', $idempotencyKey)->update([
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Jobs;
|
namespace App\Jobs;
|
||||||
|
|
||||||
|
use App\Models\Email;
|
||||||
use App\Models\EmailLog;
|
use App\Models\EmailLog;
|
||||||
use App\Models\EmailLogStatus;
|
use App\Models\EmailLogStatus;
|
||||||
use App\Services\EmailSender;
|
use App\Services\EmailSender;
|
||||||
@@ -53,6 +54,10 @@ public function handle(): void
|
|||||||
$log->duration_ms = (int) round((microtime(true) - $start) * 1000);
|
$log->duration_ms = (int) round((microtime(true) - $start) * 1000);
|
||||||
$log->save();
|
$log->save();
|
||||||
|
|
||||||
|
if ($log->to_email) {
|
||||||
|
Email::query()->where('value', $log->to_email)->update(['failed' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
throw $e;
|
throw $e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -118,10 +118,10 @@ public function handle(SmsService $sms): void
|
|||||||
if ($template && $case) {
|
if ($template && $case) {
|
||||||
$note = '';
|
$note = '';
|
||||||
if ($log->status === 'sent') {
|
if ($log->status === 'sent') {
|
||||||
$note = sprintf('Št: %s | Telo: %s', (string) $this->to, (string) $this->content);
|
$note = sprintf('Tel: %s | Telo: %s', (string) $this->to, (string) $this->content);
|
||||||
} elseif ($log->status === 'failed') {
|
} elseif ($log->status === 'failed') {
|
||||||
$note = sprintf(
|
$note = sprintf(
|
||||||
'Št: %s | Telo: %s | Napaka: %s',
|
'Tel: %s | Telo: %s | Napaka: %s',
|
||||||
(string) $this->to,
|
(string) $this->to,
|
||||||
(string) $this->content,
|
(string) $this->content,
|
||||||
'SMS ni bil poslan!'
|
'SMS ni bil poslan!'
|
||||||
|
|||||||
@@ -6,12 +6,15 @@
|
|||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
|
||||||
class Account extends Model
|
class Account extends Model
|
||||||
{
|
{
|
||||||
/** @use HasFactory<\Database\Factories\Person/AccountFactory> */
|
|
||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
|
/** @use HasFactory<\Database\Factories\Person/AccountFactory> */
|
||||||
|
use SoftDeletes;
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'reference',
|
'reference',
|
||||||
'description',
|
'description',
|
||||||
@@ -56,6 +59,11 @@ public function payments(): HasMany
|
|||||||
return $this->hasMany(\App\Models\Payment::class);
|
return $this->hasMany(\App\Models\Payment::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function installments(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(\App\Models\Installment::class);
|
||||||
|
}
|
||||||
|
|
||||||
public function bookings(): HasMany
|
public function bookings(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(\App\Models\Booking::class);
|
return $this->hasMany(\App\Models\Booking::class);
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
|
||||||
class Activity extends Model
|
class Activity extends Model
|
||||||
@@ -18,6 +19,7 @@ class Activity extends Model
|
|||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'due_date',
|
'due_date',
|
||||||
|
'call_back_at',
|
||||||
'amount',
|
'amount',
|
||||||
'note',
|
'note',
|
||||||
'action_id',
|
'action_id',
|
||||||
@@ -27,6 +29,13 @@ class Activity extends Model
|
|||||||
'client_case_id',
|
'client_case_id',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/*protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'call_back_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}*/
|
||||||
|
|
||||||
protected $hidden = [
|
protected $hidden = [
|
||||||
'action_id',
|
'action_id',
|
||||||
'decision_id',
|
'decision_id',
|
||||||
@@ -146,4 +155,14 @@ public function user(): BelongsTo
|
|||||||
{
|
{
|
||||||
return $this->belongsTo(\App\Models\User::class);
|
return $this->belongsTo(\App\Models\User::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function callLaters(): \Illuminate\Database\Eloquent\Relations\HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(\App\Models\CallLater::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function emailLogs(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(EmailLog::class, 'activity_email_logs');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class CallLater extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'activity_id',
|
||||||
|
'client_case_id',
|
||||||
|
'contract_id',
|
||||||
|
'user_id',
|
||||||
|
'call_back_at',
|
||||||
|
'completed_at',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'call_back_at' => 'datetime',
|
||||||
|
'completed_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function activity(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Activity::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function clientCase(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(ClientCase::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function contract(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Contract::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function user(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,6 +29,7 @@ class Contract extends Model
|
|||||||
'end_date',
|
'end_date',
|
||||||
'client_case_id',
|
'client_case_id',
|
||||||
'type_id',
|
'type_id',
|
||||||
|
'active',
|
||||||
'description',
|
'description',
|
||||||
'meta',
|
'meta',
|
||||||
];
|
];
|
||||||
@@ -140,6 +141,10 @@ public function fieldJobs(): HasMany
|
|||||||
return $this->hasMany(\App\Models\FieldJob::class);
|
return $this->hasMany(\App\Models\FieldJob::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function lastFieldJobs(): HasOne {
|
||||||
|
return $this->hasOne(\App\Models\FieldJob::class)->latestOfMany();
|
||||||
|
}
|
||||||
|
|
||||||
public function latestObject(): HasOne
|
public function latestObject(): HasOne
|
||||||
{
|
{
|
||||||
return $this->hasOne(\App\Models\CaseObject::class)
|
return $this->hasOne(\App\Models\CaseObject::class)
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class ContractSetting extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'create_activity_on_balance_change',
|
||||||
|
'default_action_id',
|
||||||
|
'default_decision_id',
|
||||||
|
'activity_note_template',
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ class Email extends Model
|
|||||||
'is_primary',
|
'is_primary',
|
||||||
'is_active',
|
'is_active',
|
||||||
'valid',
|
'valid',
|
||||||
|
'failed',
|
||||||
'receive_auto_mails',
|
'receive_auto_mails',
|
||||||
'verified_at',
|
'verified_at',
|
||||||
'preferences',
|
'preferences',
|
||||||
@@ -28,6 +29,7 @@ class Email extends Model
|
|||||||
'is_primary' => 'boolean',
|
'is_primary' => 'boolean',
|
||||||
'is_active' => 'boolean',
|
'is_active' => 'boolean',
|
||||||
'valid' => 'boolean',
|
'valid' => 'boolean',
|
||||||
|
'failed' => 'boolean',
|
||||||
'receive_auto_mails' => 'boolean',
|
'receive_auto_mails' => 'boolean',
|
||||||
'verified_at' => 'datetime',
|
'verified_at' => 'datetime',
|
||||||
'preferences' => 'array',
|
'preferences' => 'array',
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
|
|
||||||
enum EmailLogStatus: string
|
enum EmailLogStatus: string
|
||||||
@@ -83,4 +84,9 @@ public function body(): HasOne
|
|||||||
{
|
{
|
||||||
return $this->hasOne(EmailLogBody::class, 'email_log_id');
|
return $this->hasOne(EmailLogBody::class, 'email_log_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function activities(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(Activity::class, 'activity_email_logs');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||||
|
|
||||||
class EmailTemplate extends Model
|
class EmailTemplate extends Model
|
||||||
@@ -19,10 +20,14 @@ class EmailTemplate extends Model
|
|||||||
'entity_types',
|
'entity_types',
|
||||||
'allow_attachments',
|
'allow_attachments',
|
||||||
'active',
|
'active',
|
||||||
|
'action_id',
|
||||||
|
'decision_id',
|
||||||
|
'client',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
'active' => 'boolean',
|
'active' => 'boolean',
|
||||||
|
'client' => 'boolean',
|
||||||
'entity_types' => 'array',
|
'entity_types' => 'array',
|
||||||
'allow_attachments' => 'boolean',
|
'allow_attachments' => 'boolean',
|
||||||
];
|
];
|
||||||
@@ -31,4 +36,14 @@ public function documents(): MorphMany
|
|||||||
{
|
{
|
||||||
return $this->morphMany(Document::class, 'documentable');
|
return $this->morphMany(Document::class, 'documentable');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function action(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Action::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function decision(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Decision::class);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,11 @@ class ImportEntity extends Model
|
|||||||
'meta',
|
'meta',
|
||||||
'rules',
|
'rules',
|
||||||
'ui',
|
'ui',
|
||||||
|
'handler_class',
|
||||||
|
'validation_rules',
|
||||||
|
'processing_options',
|
||||||
|
'is_active',
|
||||||
|
'priority',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
@@ -27,5 +32,9 @@ class ImportEntity extends Model
|
|||||||
'meta' => 'boolean',
|
'meta' => 'boolean',
|
||||||
'rules' => 'array',
|
'rules' => 'array',
|
||||||
'ui' => 'array',
|
'ui' => 'array',
|
||||||
|
'validation_rules' => 'array',
|
||||||
|
'processing_options' => 'array',
|
||||||
|
'is_active' => 'boolean',
|
||||||
|
'priority' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,11 @@ class ImportTemplate extends Model
|
|||||||
'reactivate' => 'boolean',
|
'reactivate' => 'boolean',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public function getRouteKeyName(): string
|
||||||
|
{
|
||||||
|
return 'uuid';
|
||||||
|
}
|
||||||
|
|
||||||
public function user(): BelongsTo
|
public function user(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class);
|
return $this->belongsTo(User::class);
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
|
||||||
|
class Installment extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
use SoftDeletes;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'account_id',
|
||||||
|
'amount',
|
||||||
|
'balance_before',
|
||||||
|
'currency',
|
||||||
|
'reference',
|
||||||
|
'installment_at',
|
||||||
|
'meta',
|
||||||
|
'created_by',
|
||||||
|
'activity_id',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'installment_at' => 'datetime',
|
||||||
|
'meta' => 'array',
|
||||||
|
'amount' => 'decimal:4',
|
||||||
|
'balance_before' => 'decimal:4',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function account(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Account::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function activity(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Activity::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
class InstallmentSetting extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'default_currency',
|
||||||
|
'create_activity_on_installment',
|
||||||
|
'default_decision_id',
|
||||||
|
'default_action_id',
|
||||||
|
'activity_note_template',
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -10,13 +10,15 @@ class MailProfile extends Model
|
|||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'name', 'active', 'host', 'port', 'encryption', 'username', 'from_address', 'from_name',
|
'name', 'active', 'auto_mailer', 'host', 'port', 'encryption', 'username', 'from_address', 'from_name',
|
||||||
'reply_to_address', 'reply_to_name', 'priority', 'max_daily_quota', 'emails_sent_today',
|
'reply_to_address', 'reply_to_name', 'priority', 'signature', 'max_daily_quota', 'emails_sent_today',
|
||||||
'last_success_at', 'last_error_at', 'last_error_message', 'failover_to_id', 'test_status', 'test_checked_at',
|
'last_success_at', 'last_error_at', 'last_error_message', 'failover_to_id', 'test_status', 'test_checked_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $casts = [
|
protected $casts = [
|
||||||
'active' => 'boolean',
|
'active' => 'boolean',
|
||||||
|
'auto_mailer' => 'boolean',
|
||||||
|
'signature' => 'array',
|
||||||
'last_success_at' => 'datetime',
|
'last_success_at' => 'datetime',
|
||||||
'last_error_at' => 'datetime',
|
'last_error_at' => 'datetime',
|
||||||
'test_checked_at' => 'datetime',
|
'test_checked_at' => 'datetime',
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ public function items()
|
|||||||
|
|
||||||
public const TYPE_SMS = 'sms';
|
public const TYPE_SMS = 'sms';
|
||||||
|
|
||||||
|
public const TYPE_EMAIL = 'email';
|
||||||
|
|
||||||
public const STATUS_DRAFT = 'draft';
|
public const STATUS_DRAFT = 'draft';
|
||||||
|
|
||||||
public const STATUS_QUEUED = 'queued';
|
public const STATUS_QUEUED = 'queued';
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ class Person extends Model
|
|||||||
'group_id',
|
'group_id',
|
||||||
'type_id',
|
'type_id',
|
||||||
'user_id',
|
'user_id',
|
||||||
|
'employer'
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $hidden = [
|
protected $hidden = [
|
||||||
@@ -112,6 +113,14 @@ public function addresses(): HasMany
|
|||||||
->orderBy('id');
|
->orderBy('id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function address(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(\App\Models\Person\PersonAddress::class)
|
||||||
|
->with(['type'])
|
||||||
|
->where('active', '=', 1)
|
||||||
|
->oldestOfMany('id');
|
||||||
|
}
|
||||||
|
|
||||||
public function emails(): HasMany
|
public function emails(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(\App\Models\Email::class, 'person_id')
|
return $this->hasMany(\App\Models\Email::class, 'person_id')
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
class Report extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'slug',
|
||||||
|
'name',
|
||||||
|
'description',
|
||||||
|
'category',
|
||||||
|
'enabled',
|
||||||
|
'order',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'enabled' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function entities(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ReportEntity::class)->orderBy('order');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function columns(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ReportColumn::class)->orderBy('order');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function filters(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ReportFilter::class)->orderBy('order');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function conditions(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ReportCondition::class)->orderBy('order');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function orders(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(ReportOrder::class)->orderBy('order');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class ReportColumn extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'report_id',
|
||||||
|
'key',
|
||||||
|
'label',
|
||||||
|
'type',
|
||||||
|
'expression',
|
||||||
|
'sortable',
|
||||||
|
'visible',
|
||||||
|
'order',
|
||||||
|
'format_options',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'sortable' => 'boolean',
|
||||||
|
'visible' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
'format_options' => 'array',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function report(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Report::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class ReportCondition extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'report_id',
|
||||||
|
'column',
|
||||||
|
'operator',
|
||||||
|
'value_type',
|
||||||
|
'value',
|
||||||
|
'filter_key',
|
||||||
|
'logical_operator',
|
||||||
|
'group_id',
|
||||||
|
'order',
|
||||||
|
'enabled',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'enabled' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
'group_id' => 'integer',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function report(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Report::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class ReportEntity extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'report_id',
|
||||||
|
'model_class',
|
||||||
|
'alias',
|
||||||
|
'join_type',
|
||||||
|
'join_first',
|
||||||
|
'join_operator',
|
||||||
|
'join_second',
|
||||||
|
'order',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'order' => 'integer',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function report(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Report::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class ReportFilter extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'report_id',
|
||||||
|
'key',
|
||||||
|
'label',
|
||||||
|
'type',
|
||||||
|
'nullable',
|
||||||
|
'default_value',
|
||||||
|
'options',
|
||||||
|
'data_source',
|
||||||
|
'order',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'nullable' => 'boolean',
|
||||||
|
'order' => 'integer',
|
||||||
|
'options' => 'array',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function report(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Report::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class ReportOrder extends Model
|
||||||
|
{
|
||||||
|
protected $fillable = [
|
||||||
|
'report_id',
|
||||||
|
'column',
|
||||||
|
'direction',
|
||||||
|
'order',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'order' => 'integer',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function report(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Report::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ class User extends Authenticatable
|
|||||||
'email',
|
'email',
|
||||||
'password',
|
'password',
|
||||||
'active',
|
'active',
|
||||||
|
'login_redirect',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
use App\Actions\Fortify\ResetUserPassword;
|
use App\Actions\Fortify\ResetUserPassword;
|
||||||
use App\Actions\Fortify\UpdateUserPassword;
|
use App\Actions\Fortify\UpdateUserPassword;
|
||||||
use App\Actions\Fortify\UpdateUserProfileInformation;
|
use App\Actions\Fortify\UpdateUserProfileInformation;
|
||||||
|
use App\Http\Responses\LoginResponse;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use Illuminate\Cache\RateLimiting\Limit;
|
use Illuminate\Cache\RateLimiting\Limit;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -14,6 +15,7 @@
|
|||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
|
||||||
use Laravel\Fortify\Fortify;
|
use Laravel\Fortify\Fortify;
|
||||||
|
|
||||||
class FortifyServiceProvider extends ServiceProvider
|
class FortifyServiceProvider extends ServiceProvider
|
||||||
@@ -23,7 +25,7 @@ class FortifyServiceProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function register(): void
|
public function register(): void
|
||||||
{
|
{
|
||||||
//
|
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Providers;
|
|
||||||
|
|
||||||
use App\Reports\ActionsDecisionsCountReport;
|
|
||||||
use App\Reports\ActivitiesPerPeriodReport;
|
|
||||||
use App\Reports\ActiveContractsReport;
|
|
||||||
use App\Reports\FieldJobsCompletedReport;
|
|
||||||
use App\Reports\DecisionsCountReport;
|
|
||||||
use App\Reports\ReportRegistry;
|
|
||||||
use App\Reports\SegmentActivityCountsReport;
|
|
||||||
use Illuminate\Support\ServiceProvider;
|
|
||||||
|
|
||||||
class ReportServiceProvider extends ServiceProvider
|
|
||||||
{
|
|
||||||
public function register(): void
|
|
||||||
{
|
|
||||||
$this->app->singleton(ReportRegistry::class, function () {
|
|
||||||
$registry = new ReportRegistry;
|
|
||||||
// Register built-in reports here
|
|
||||||
$registry->register(new FieldJobsCompletedReport);
|
|
||||||
$registry->register(new SegmentActivityCountsReport);
|
|
||||||
$registry->register(new ActionsDecisionsCountReport);
|
|
||||||
$registry->register(new ActivitiesPerPeriodReport);
|
|
||||||
$registry->register(new DecisionsCountReport);
|
|
||||||
$registry->register(new ActiveContractsReport);
|
|
||||||
|
|
||||||
return $registry;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function boot(): void
|
|
||||||
{
|
|
||||||
//
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Models\Activity;
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
|
|
||||||
class ActionsDecisionsCountReport extends BaseEloquentReport implements Report
|
|
||||||
{
|
|
||||||
public function slug(): string
|
|
||||||
{
|
|
||||||
return 'actions-decisions-counts';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function name(): string
|
|
||||||
{
|
|
||||||
return 'Dejanja / Odločitve – štetje';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return 'Število aktivnosti po dejanjih in odločitvah v obdobju.';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function inputs(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'from', 'type' => 'date', 'label' => 'Od', 'nullable' => true],
|
|
||||||
['key' => 'to', 'type' => 'date', 'label' => 'Do', 'nullable' => true],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function columns(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'action_name', 'label' => 'Dejanje'],
|
|
||||||
['key' => 'decision_name', 'label' => 'Odločitev'],
|
|
||||||
['key' => 'activities_count', 'label' => 'Št. aktivnosti'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function query(array $filters): Builder
|
|
||||||
{
|
|
||||||
return Activity::query()
|
|
||||||
->leftJoin('actions', 'activities.action_id', '=', 'actions.id')
|
|
||||||
->leftJoin('decisions', 'activities.decision_id', '=', 'decisions.id')
|
|
||||||
->when(! empty($filters['from']), fn ($q) => $q->whereDate('activities.created_at', '>=', $filters['from']))
|
|
||||||
->when(! empty($filters['to']), fn ($q) => $q->whereDate('activities.created_at', '<=', $filters['to']))
|
|
||||||
->groupBy('actions.name', 'decisions.name')
|
|
||||||
->selectRaw("COALESCE(actions.name, '—') as action_name, COALESCE(decisions.name, '—') as decision_name, COUNT(*) as activities_count");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Models\Contract;
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
|
|
||||||
class ActiveContractsReport extends BaseEloquentReport implements Report
|
|
||||||
{
|
|
||||||
public function slug(): string
|
|
||||||
{
|
|
||||||
return 'active-contracts';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function name(): string
|
|
||||||
{
|
|
||||||
return 'Aktivne pogodbe';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return 'Pogodbe, ki so aktivne na izbrani dan, z možnostjo filtriranja po stranki.';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function inputs(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'client_uuid', 'type' => 'select:client', 'label' => 'Stranka', 'nullable' => true],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function columns(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'contract_reference', 'label' => 'Pogodba'],
|
|
||||||
['key' => 'client_name', 'label' => 'Stranka'],
|
|
||||||
['key' => 'person_name', 'label' => 'Zadeva (oseba)'],
|
|
||||||
['key' => 'start_date', 'label' => 'Začetek'],
|
|
||||||
['key' => 'end_date', 'label' => 'Konec'],
|
|
||||||
['key' => 'balance_amount', 'label' => 'Saldo'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function query(array $filters): Builder
|
|
||||||
{
|
|
||||||
$asOf = now()->toDateString();
|
|
||||||
|
|
||||||
return Contract::query()
|
|
||||||
->join('client_cases', 'contracts.client_case_id', '=', 'client_cases.id')
|
|
||||||
->leftJoin('clients', 'client_cases.client_id', '=', 'clients.id')
|
|
||||||
->leftJoin('person as client_people', 'clients.person_id', '=', 'client_people.id')
|
|
||||||
->leftJoin('person as subject_people', 'client_cases.person_id', '=', 'subject_people.id')
|
|
||||||
->leftJoin('accounts', 'contracts.id', '=', 'accounts.contract_id')
|
|
||||||
->when(! empty($filters['client_uuid']), fn ($q) => $q->where('clients.uuid', $filters['client_uuid']))
|
|
||||||
// Active as of date: start_date <= as_of (or null) AND (end_date is null OR end_date >= as_of)
|
|
||||||
->where(function ($q) use ($asOf) {
|
|
||||||
$q->whereNull('contracts.start_date')
|
|
||||||
->orWhereDate('contracts.start_date', '<=', $asOf);
|
|
||||||
})
|
|
||||||
->where(function ($q) use ($asOf) {
|
|
||||||
$q->whereNull('contracts.end_date')
|
|
||||||
->orWhereDate('contracts.end_date', '>=', $asOf);
|
|
||||||
})
|
|
||||||
->select([
|
|
||||||
'contracts.id',
|
|
||||||
'contracts.start_date',
|
|
||||||
'contracts.end_date',
|
|
||||||
])
|
|
||||||
->addSelect([
|
|
||||||
\DB::raw('contracts.reference as contract_reference'),
|
|
||||||
\DB::raw('client_people.full_name as client_name'),
|
|
||||||
\DB::raw('subject_people.full_name as person_name'),
|
|
||||||
\DB::raw('CAST(accounts.balance_amount AS FLOAT) as balance_amount'),
|
|
||||||
])
|
|
||||||
->orderBy('contracts.start_date', 'asc');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Models\Activity;
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
class ActivitiesPerPeriodReport extends BaseEloquentReport implements Report
|
|
||||||
{
|
|
||||||
public function slug(): string
|
|
||||||
{
|
|
||||||
return 'activities-per-period';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function name(): string
|
|
||||||
{
|
|
||||||
return 'Aktivnosti po obdobjih';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return 'Seštevek aktivnosti po dneh/tednih/mesecih v obdobju.';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function inputs(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'from', 'type' => 'date', 'label' => 'Od', 'nullable' => true],
|
|
||||||
['key' => 'to', 'type' => 'date', 'label' => 'Do', 'nullable' => true],
|
|
||||||
['key' => 'period', 'type' => 'string', 'label' => 'Obdobje (day|week|month)', 'default' => 'day'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function columns(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'period', 'label' => 'Obdobje'],
|
|
||||||
['key' => 'activities_count', 'label' => 'Št. aktivnosti'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function query(array $filters): Builder
|
|
||||||
{
|
|
||||||
$periodRaw = $filters['period'] ?? 'day';
|
|
||||||
$period = in_array($periodRaw, ['day', 'week', 'month'], true) ? $periodRaw : 'day';
|
|
||||||
$driver = DB::getDriverName();
|
|
||||||
|
|
||||||
// Build database-compatible period expressions
|
|
||||||
if ($driver === 'sqlite') {
|
|
||||||
if ($period === 'day') {
|
|
||||||
// Use string slice to avoid timezone conversion differences in SQLite
|
|
||||||
$selectExpr = DB::raw('SUBSTR(activities.created_at, 1, 10) as period');
|
|
||||||
$groupExpr = DB::raw('SUBSTR(activities.created_at, 1, 10)');
|
|
||||||
$orderExpr = DB::raw('SUBSTR(activities.created_at, 1, 10)');
|
|
||||||
} elseif ($period === 'month') {
|
|
||||||
$selectExpr = DB::raw("strftime('%Y-%m-01', activities.created_at) as period");
|
|
||||||
$groupExpr = DB::raw("strftime('%Y-%m-01', activities.created_at)");
|
|
||||||
$orderExpr = DB::raw("strftime('%Y-%m-01', activities.created_at)");
|
|
||||||
} else { // week
|
|
||||||
$selectExpr = DB::raw("strftime('%Y-%W', activities.created_at) as period");
|
|
||||||
$groupExpr = DB::raw("strftime('%Y-%W', activities.created_at)");
|
|
||||||
$orderExpr = DB::raw("strftime('%Y-%W', activities.created_at)");
|
|
||||||
}
|
|
||||||
} elseif ($driver === 'mysql') {
|
|
||||||
if ($period === 'day') {
|
|
||||||
$selectExpr = DB::raw('DATE(activities.created_at) as period');
|
|
||||||
$groupExpr = DB::raw('DATE(activities.created_at)');
|
|
||||||
$orderExpr = DB::raw('DATE(activities.created_at)');
|
|
||||||
} elseif ($period === 'month') {
|
|
||||||
$selectExpr = DB::raw("DATE_FORMAT(activities.created_at, '%Y-%m-01') as period");
|
|
||||||
$groupExpr = DB::raw("DATE_FORMAT(activities.created_at, '%Y-%m-01')");
|
|
||||||
$orderExpr = DB::raw("DATE_FORMAT(activities.created_at, '%Y-%m-01')");
|
|
||||||
} else { // week
|
|
||||||
// ISO week-year-week number for grouping; adequate for summary grouping
|
|
||||||
$selectExpr = DB::raw("DATE_FORMAT(activities.created_at, '%x-%v') as period");
|
|
||||||
$groupExpr = DB::raw("DATE_FORMAT(activities.created_at, '%x-%v')");
|
|
||||||
$orderExpr = DB::raw("DATE_FORMAT(activities.created_at, '%x-%v')");
|
|
||||||
}
|
|
||||||
} else { // postgres and others supporting date_trunc
|
|
||||||
$selectExpr = DB::raw("date_trunc('".$period."', activities.created_at) as period");
|
|
||||||
$groupExpr = DB::raw("date_trunc('".$period."', activities.created_at)");
|
|
||||||
$orderExpr = DB::raw("date_trunc('".$period."', activities.created_at)");
|
|
||||||
}
|
|
||||||
|
|
||||||
return Activity::query()
|
|
||||||
->when(! empty($filters['from']), fn ($q) => $q->whereDate('activities.created_at', '>=', $filters['from']))
|
|
||||||
->when(! empty($filters['to']), fn ($q) => $q->whereDate('activities.created_at', '<=', $filters['to']))
|
|
||||||
->groupBy($groupExpr)
|
|
||||||
->orderBy($orderExpr)
|
|
||||||
->select($selectExpr)
|
|
||||||
->selectRaw('COUNT(*) as activities_count');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
||||||
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
|
||||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
abstract class BaseEloquentReport implements Report
|
|
||||||
{
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function authorize(Request $request): void
|
|
||||||
{
|
|
||||||
// Default: no extra checks. Controllers can gate via middleware.
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
*/
|
|
||||||
public function paginate(array $filters, int $perPage = 25): LengthAwarePaginator
|
|
||||||
{
|
|
||||||
/** @var EloquentBuilder|QueryBuilder $query */
|
|
||||||
$query = $this->query($filters);
|
|
||||||
|
|
||||||
return $query->paginate($perPage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports\Contracts;
|
|
||||||
|
|
||||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
||||||
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
|
||||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
|
|
||||||
interface Report
|
|
||||||
{
|
|
||||||
public function slug(): string;
|
|
||||||
|
|
||||||
public function name(): string;
|
|
||||||
|
|
||||||
public function description(): ?string;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return an array describing input filters (type, label, default, options) for UI.
|
|
||||||
* Example item: ['key' => 'from', 'type' => 'date', 'label' => 'Od', 'default' => today()]
|
|
||||||
*
|
|
||||||
* @return array<int, array<string, mixed>>
|
|
||||||
*/
|
|
||||||
public function inputs(): array;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return column definitions for the table and exports.
|
|
||||||
* Example: [ ['key' => 'id', 'label' => '#'], ['key' => 'user', 'label' => 'Uporabnik'] ]
|
|
||||||
*
|
|
||||||
* @return array<int, array<string, mixed>>
|
|
||||||
*/
|
|
||||||
public function columns(): array;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build the data source query for the report based on validated filters.
|
|
||||||
* Should return an Eloquent or Query builder.
|
|
||||||
*
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
* @return EloquentBuilder|QueryBuilder
|
|
||||||
*/
|
|
||||||
public function query(array $filters);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Optional per-report authorization logic.
|
|
||||||
*/
|
|
||||||
public function authorize(Request $request): void;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute the report and return a paginator for UI.
|
|
||||||
*
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
*/
|
|
||||||
public function paginate(array $filters, int $perPage = 25): LengthAwarePaginator;
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Models\Activity;
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
|
|
||||||
class DecisionsCountReport extends BaseEloquentReport implements Report
|
|
||||||
{
|
|
||||||
public function slug(): string
|
|
||||||
{
|
|
||||||
return 'decisions-counts';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function name(): string
|
|
||||||
{
|
|
||||||
return 'Odločitve – štetje';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return 'Število aktivnosti po odločitvah v izbranem obdobju.';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function inputs(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'from', 'type' => 'date', 'label' => 'Od', 'nullable' => true],
|
|
||||||
['key' => 'to', 'type' => 'date', 'label' => 'Do', 'nullable' => true],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function columns(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'decision_name', 'label' => 'Odločitev'],
|
|
||||||
['key' => 'activities_count', 'label' => 'Št. aktivnosti'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function query(array $filters): Builder
|
|
||||||
{
|
|
||||||
return Activity::query()
|
|
||||||
->leftJoin('decisions', 'activities.decision_id', '=', 'decisions.id')
|
|
||||||
->when(!empty($filters['from']), fn ($q) => $q->whereDate('activities.created_at', '>=', $filters['from']))
|
|
||||||
->when(!empty($filters['to']), fn ($q) => $q->whereDate('activities.created_at', '<=', $filters['to']))
|
|
||||||
->groupBy('decisions.name')
|
|
||||||
->selectRaw("COALESCE(decisions.name, '—') as decision_name, COUNT(*) as activities_count");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Models\FieldJob;
|
|
||||||
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
|
||||||
|
|
||||||
class FieldJobsCompletedReport extends BaseEloquentReport
|
|
||||||
{
|
|
||||||
public function slug(): string
|
|
||||||
{
|
|
||||||
return 'field-jobs-completed';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function name(): string
|
|
||||||
{
|
|
||||||
return 'Zaključeni tereni';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return 'Pregled zaključenih terenov po datumu in uporabniku.';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function inputs(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'from', 'type' => 'date', 'label' => 'Od', 'default' => now()->startOfMonth()->toDateString()],
|
|
||||||
['key' => 'to', 'type' => 'date', 'label' => 'Do', 'default' => now()->toDateString()],
|
|
||||||
['key' => 'user_id', 'type' => 'select:user', 'label' => 'Uporabnik', 'default' => null],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function columns(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'id', 'label' => '#'],
|
|
||||||
['key' => 'contract_reference', 'label' => 'Pogodba'],
|
|
||||||
['key' => 'assigned_user_name', 'label' => 'Terenski'],
|
|
||||||
['key' => 'completed_at', 'label' => 'Zaključeno'],
|
|
||||||
['key' => 'notes', 'label' => 'Opombe'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $filters
|
|
||||||
*/
|
|
||||||
public function query(array $filters): EloquentBuilder
|
|
||||||
{
|
|
||||||
$from = isset($filters['from']) ? now()->parse($filters['from'])->startOfDay() : now()->startOfMonth();
|
|
||||||
$to = isset($filters['to']) ? now()->parse($filters['to'])->endOfDay() : now()->endOfDay();
|
|
||||||
|
|
||||||
return FieldJob::query()
|
|
||||||
->whereNull('cancelled_at')
|
|
||||||
->whereBetween('completed_at', [$from, $to])
|
|
||||||
->when(! empty($filters['user_id']), fn ($q) => $q->where('assigned_user_id', $filters['user_id']))
|
|
||||||
->with(['assignedUser:id,name', 'contract:id,reference'])
|
|
||||||
->select(['id', 'assigned_user_id', 'contract_id', 'completed_at', 'notes']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
|
|
||||||
class ReportRegistry
|
|
||||||
{
|
|
||||||
/** @var array<string, Report> */
|
|
||||||
protected array $reports = [];
|
|
||||||
|
|
||||||
public function register(Report $report): void
|
|
||||||
{
|
|
||||||
$this->reports[$report->slug()] = $report;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array<string, Report>
|
|
||||||
*/
|
|
||||||
public function all(): array
|
|
||||||
{
|
|
||||||
return $this->reports;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function findBySlug(string $slug): ?Report
|
|
||||||
{
|
|
||||||
return $this->reports[$slug] ?? null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Reports;
|
|
||||||
|
|
||||||
use App\Models\Activity;
|
|
||||||
use App\Reports\Contracts\Report;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
|
|
||||||
class SegmentActivityCountsReport extends BaseEloquentReport implements Report
|
|
||||||
{
|
|
||||||
public function slug(): string
|
|
||||||
{
|
|
||||||
return 'segment-activity-counts';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function name(): string
|
|
||||||
{
|
|
||||||
return 'Aktivnosti po segmentih';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function description(): ?string
|
|
||||||
{
|
|
||||||
return 'Število aktivnosti po segmentih v izbranem obdobju (glede na segment dejanja).';
|
|
||||||
}
|
|
||||||
|
|
||||||
public function inputs(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'from', 'type' => 'date', 'label' => 'Od', 'nullable' => true],
|
|
||||||
['key' => 'to', 'type' => 'date', 'label' => 'Do', 'nullable' => true],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function columns(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['key' => 'segment_name', 'label' => 'Segment'],
|
|
||||||
['key' => 'activities_count', 'label' => 'Št. aktivnosti'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function query(array $filters): Builder
|
|
||||||
{
|
|
||||||
$q = Activity::query()
|
|
||||||
->join('actions', 'activities.action_id', '=', 'actions.id')
|
|
||||||
->leftJoin('segments', 'actions.segment_id', '=', 'segments.id')
|
|
||||||
->when(! empty($filters['from']), fn ($qq) => $qq->whereDate('activities.created_at', '>=', $filters['from']))
|
|
||||||
->when(! empty($filters['to']), fn ($qq) => $qq->whereDate('activities.created_at', '<=', $filters['to']))
|
|
||||||
->groupBy('segments.name')
|
|
||||||
->selectRaw("COALESCE(segments.name, 'Brez segmenta') as segment_name, COUNT(*) as activities_count");
|
|
||||||
|
|
||||||
return $q;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -59,10 +59,23 @@ public function maybeQueue(Activity $activity, bool $sendFlag = true, array $opt
|
|||||||
// Resolve eligible recipients: client's person emails with receive_auto_mails = true
|
// Resolve eligible recipients: client's person emails with receive_auto_mails = true
|
||||||
$recipients = [];
|
$recipients = [];
|
||||||
if ($client && $client->person) {
|
if ($client && $client->person) {
|
||||||
$recipients = Email::query()
|
$emails = Email::query()
|
||||||
->where('person_id', $client->person->id)
|
->where('person_id', $client->person->id)
|
||||||
->where('is_active', true)
|
->where('is_active', true)
|
||||||
->where('receive_auto_mails', true)
|
->where('receive_auto_mails', true)
|
||||||
|
->get(['value', 'preferences']);
|
||||||
|
|
||||||
|
$recipients = $emails
|
||||||
|
->filter(function (Email $email) use ($decision): bool {
|
||||||
|
$decisionIds = $email->preferences['decision_ids'] ?? [];
|
||||||
|
|
||||||
|
// Empty list means "all decisions" — always receive
|
||||||
|
if (empty($decisionIds)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return in_array((int) $decision->id, array_map('intval', $decisionIds), true);
|
||||||
|
})
|
||||||
->pluck('value')
|
->pluck('value')
|
||||||
->map(fn ($v) => strtolower(trim((string) $v)))
|
->map(fn ($v) => strtolower(trim((string) $v)))
|
||||||
->filter(fn ($v) => filter_var($v, FILTER_VALIDATE_EMAIL))
|
->filter(fn ($v) => filter_var($v, FILTER_VALIDATE_EMAIL))
|
||||||
@@ -77,7 +90,30 @@ public function maybeQueue(Activity $activity, bool $sendFlag = true, array $opt
|
|||||||
// Ensure related names are available without extra queries
|
// Ensure related names are available without extra queries
|
||||||
$activity->loadMissing(['action', 'decision']);
|
$activity->loadMissing(['action', 'decision']);
|
||||||
|
|
||||||
|
// Ensure account is available on contract (needed for contract.account.* tokens)
|
||||||
|
if ($contract && ! $contract->relationLoaded('account')) {
|
||||||
|
$contract->load('account');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the sending profile once — used both for signature tokens and as the actual sender.
|
||||||
|
// Prefer the profile explicitly requested via options, fall back to highest-priority active one.
|
||||||
|
$mailProfile = isset($options['mail_profile_id'])
|
||||||
|
? MailProfile::query()->find($options['mail_profile_id'])
|
||||||
|
: null;
|
||||||
|
$mailProfile ??= MailProfile::query()
|
||||||
|
->where('active', true)
|
||||||
|
->where('auto_mailer', true)
|
||||||
|
->orderBy('priority')
|
||||||
|
->orderBy('id')
|
||||||
|
->first();
|
||||||
|
$mailProfile ??= MailProfile::query()
|
||||||
|
->where('active', true)
|
||||||
|
->orderBy('priority')
|
||||||
|
->orderBy('id')
|
||||||
|
->first();
|
||||||
|
|
||||||
// Render content
|
// Render content
|
||||||
|
$bodyText = isset($options['body_text']) ? (string) $options['body_text'] : '';
|
||||||
$rendered = $this->renderer->render([
|
$rendered = $this->renderer->render([
|
||||||
'subject' => (string) $template->subject_template,
|
'subject' => (string) $template->subject_template,
|
||||||
'html' => (string) $template->html_template,
|
'html' => (string) $template->html_template,
|
||||||
@@ -89,6 +125,8 @@ public function maybeQueue(Activity $activity, bool $sendFlag = true, array $opt
|
|||||||
'person' => $person,
|
'person' => $person,
|
||||||
'activity' => $activity,
|
'activity' => $activity,
|
||||||
'extra' => [],
|
'extra' => [],
|
||||||
|
'mail_profile' => $mailProfile,
|
||||||
|
'body_text' => $bodyText,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Create the log and body
|
// Create the log and body
|
||||||
@@ -96,7 +134,7 @@ public function maybeQueue(Activity $activity, bool $sendFlag = true, array $opt
|
|||||||
$log->fill([
|
$log->fill([
|
||||||
'uuid' => (string) \Str::uuid(),
|
'uuid' => (string) \Str::uuid(),
|
||||||
'template_id' => $template->id,
|
'template_id' => $template->id,
|
||||||
'mail_profile_id' => optional(MailProfile::query()->where('active', true)->orderBy('priority')->orderBy('id')->first())->id,
|
'mail_profile_id' => $mailProfile?->id,
|
||||||
'user_id' => auth()->id(),
|
'user_id' => auth()->id(),
|
||||||
'to_email' => (string) ($recipients[0] ?? ''),
|
'to_email' => (string) ($recipients[0] ?? ''),
|
||||||
'to_recipients' => $recipients,
|
'to_recipients' => $recipients,
|
||||||
@@ -136,7 +174,7 @@ public function maybeQueue(Activity $activity, bool $sendFlag = true, array $opt
|
|||||||
|
|
||||||
$log->body()->create([
|
$log->body()->create([
|
||||||
'body_html' => (string) ($rendered['html'] ?? ''),
|
'body_html' => (string) ($rendered['html'] ?? ''),
|
||||||
'body_text' => (string) ($rendered['text'] ?? ''),
|
'body_text' => $bodyText !== '' ? $bodyText : (string) ($rendered['text'] ?? ''),
|
||||||
'inline_css' => true,
|
'inline_css' => true,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -11,9 +11,9 @@
|
|||||||
class ClientCaseDataService
|
class ClientCaseDataService
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Get paginated contracts for a client case with optional segment filtering.
|
* Get contracts for a client case with optional segment filtering.
|
||||||
*/
|
*/
|
||||||
public function getContracts(ClientCase $clientCase, ?int $segmentId = null, int $perPage = 50): LengthAwarePaginator
|
public function getContracts(ClientCase $clientCase, ?int $segmentId = null): Collection
|
||||||
{
|
{
|
||||||
$query = $clientCase->contracts()
|
$query = $clientCase->contracts()
|
||||||
->select(['id', 'uuid', 'reference', 'start_date', 'end_date', 'description', 'meta', 'active', 'type_id', 'client_case_id', 'created_at'])
|
->select(['id', 'uuid', 'reference', 'start_date', 'end_date', 'description', 'meta', 'active', 'type_id', 'client_case_id', 'created_at'])
|
||||||
@@ -40,9 +40,7 @@ public function getContracts(ClientCase $clientCase, ?int $segmentId = null, int
|
|||||||
$query->forSegment($segmentId);
|
$query->forSegment($segmentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
$perPage = max(1, min(100, $perPage));
|
return $query->get();
|
||||||
|
|
||||||
return $query->paginate($perPage, ['*'], 'contracts_page')->withQueryString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -56,7 +54,7 @@ public function getActivities(
|
|||||||
int $perPage = 20
|
int $perPage = 20
|
||||||
): LengthAwarePaginator {
|
): LengthAwarePaginator {
|
||||||
$query = $clientCase->activities()
|
$query = $clientCase->activities()
|
||||||
->with(['action', 'decision', 'contract:id,uuid,reference', 'user:id,name'])
|
->with(['action', 'decision', 'contract:id,uuid,reference', 'user:id,name', 'emailLogs:id'])
|
||||||
->orderByDesc('created_at');
|
->orderByDesc('created_at');
|
||||||
|
|
||||||
if (! empty($segmentId)) {
|
if (! empty($segmentId)) {
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Contact;
|
||||||
|
|
||||||
|
use App\Models\Email;
|
||||||
|
use App\Models\Person\Person;
|
||||||
|
|
||||||
|
class EmailSelector
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Select the best email for a person following priority rules.
|
||||||
|
* Priority:
|
||||||
|
* 1) verified primary email that is active
|
||||||
|
* 2) primary email that is active
|
||||||
|
* 3) any active and valid email
|
||||||
|
* 4) first active email
|
||||||
|
*
|
||||||
|
* Returns an array shape: ['email' => ?Email, 'reason' => ?string]
|
||||||
|
*/
|
||||||
|
public function selectForPerson(Person $person): array
|
||||||
|
{
|
||||||
|
$emails = Email::query()
|
||||||
|
->where('person_id', $person->id)
|
||||||
|
->where('is_active', true)
|
||||||
|
->orderBy('is_primary', 'desc')
|
||||||
|
->orderBy('id')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
if ($emails->isEmpty()) {
|
||||||
|
return ['email' => null, 'reason' => 'no_active_emails'];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) verified primary
|
||||||
|
$email = $emails->first(fn (Email $e) => $e->is_primary && $e->verified_at !== null);
|
||||||
|
if ($email) {
|
||||||
|
return ['email' => $email, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) primary (any verification)
|
||||||
|
$email = $emails->first(fn (Email $e) => $e->is_primary);
|
||||||
|
if ($email) {
|
||||||
|
return ['email' => $email, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3) valid (any)
|
||||||
|
$email = $emails->first(fn (Email $e) => $e->valid);
|
||||||
|
if ($email) {
|
||||||
|
return ['email' => $email, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4) first active
|
||||||
|
return ['email' => $emails->first(), 'reason' => null];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,57 +2,11 @@
|
|||||||
|
|
||||||
namespace App\Services;
|
namespace App\Services;
|
||||||
|
|
||||||
class DateNormalizer
|
/**
|
||||||
|
* Backward compatibility alias for DateNormalizer.
|
||||||
|
* Old code references App\Services\DateNormalizer, but actual class is at App\Services\Import\DateNormalizer.
|
||||||
|
*/
|
||||||
|
class DateNormalizer extends \App\Services\Import\DateNormalizer
|
||||||
{
|
{
|
||||||
/**
|
// This class extends the actual DateNormalizer for backward compatibility
|
||||||
* Normalize a raw date string to Y-m-d (ISO) or return null if unparseable.
|
|
||||||
* Accepted examples: 30.10.2025, 30/10/2025, 30-10-2025, 1/2/25, 2025-10-30
|
|
||||||
*/
|
|
||||||
public static function toDate(?string $raw): ?string
|
|
||||||
{
|
|
||||||
if ($raw === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
$raw = trim($raw);
|
|
||||||
if ($raw === '') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Common European and ISO formats first (day-first, then ISO)
|
|
||||||
$candidates = [
|
|
||||||
'd.m.Y', 'd.m.y',
|
|
||||||
'd/m/Y', 'd/m/y',
|
|
||||||
'd-m-Y', 'd-m-y',
|
|
||||||
'Y-m-d', 'Y/m/d', 'Y.m.d',
|
|
||||||
];
|
|
||||||
|
|
||||||
foreach ($candidates as $fmt) {
|
|
||||||
$dt = \DateTime::createFromFormat($fmt, $raw);
|
|
||||||
if ($dt instanceof \DateTime) {
|
|
||||||
$errors = \DateTime::getLastErrors();
|
|
||||||
if ((int) ($errors['warning_count'] ?? 0) === 0 && (int) ($errors['error_count'] ?? 0) === 0) {
|
|
||||||
// Adjust two-digit years to reasonable century (00-69 => 2000-2069, 70-99 => 1970-1999)
|
|
||||||
$year = (int) $dt->format('Y');
|
|
||||||
if ($year < 100) {
|
|
||||||
$year += ($year <= 69) ? 2000 : 1900;
|
|
||||||
// Rebuild date with corrected year
|
|
||||||
$month = (int) $dt->format('m');
|
|
||||||
$day = (int) $dt->format('d');
|
|
||||||
|
|
||||||
return sprintf('%04d-%02d-%02d', $year, $month, $day);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $dt->format('Y-m-d');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: strtotime (permissive). If fails, return null.
|
|
||||||
$ts = @strtotime($raw);
|
|
||||||
if ($ts === false) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return date('Y-m-d', $ts);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\DecisionEvents;
|
||||||
|
|
||||||
|
class ConditionEvaluator
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Returns true when ALL conditions pass (AND logic).
|
||||||
|
*
|
||||||
|
* Each condition: { field: string, operator: string, value: mixed }
|
||||||
|
*
|
||||||
|
* @param array<int, array{field: string, operator: string, value: mixed}> $conditions
|
||||||
|
*/
|
||||||
|
public function evaluate(array $conditions, DecisionEventContext $context): bool
|
||||||
|
{
|
||||||
|
foreach ($conditions as $condition) {
|
||||||
|
if (! $this->evaluateOne($condition, $context)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function evaluateOne(array $condition, DecisionEventContext $context): bool
|
||||||
|
{
|
||||||
|
$field = $condition['field'] ?? '';
|
||||||
|
$operator = $condition['operator'] ?? '=';
|
||||||
|
$expected = $condition['value'] ?? null;
|
||||||
|
|
||||||
|
$actual = $this->resolveField($field, $context);
|
||||||
|
|
||||||
|
return $this->compare($actual, $operator, $expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveField(string $field, DecisionEventContext $context): mixed
|
||||||
|
{
|
||||||
|
return match ($field) {
|
||||||
|
'activity.amount' => $context->activity?->amount,
|
||||||
|
'activity.note' => $context->activity?->note,
|
||||||
|
'contract.active' => $context->contract !== null ? (bool) $context->contract->active : null,
|
||||||
|
'contract.account.balance_amount' => $this->resolveAccountBalance($context),
|
||||||
|
default => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resolveAccountBalance(DecisionEventContext $context): mixed
|
||||||
|
{
|
||||||
|
if (! $context->contract) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$context->contract->loadMissing('account');
|
||||||
|
|
||||||
|
return $context->contract->account?->balance_amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function compare(mixed $actual, string $operator, mixed $expected): bool
|
||||||
|
{
|
||||||
|
if ($actual === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($operator, ['>', '>=', '<', '<='], true)) {
|
||||||
|
$actual = (float) $actual;
|
||||||
|
$expected = (float) $expected;
|
||||||
|
}
|
||||||
|
|
||||||
|
return match ($operator) {
|
||||||
|
'=' => $actual == $expected,
|
||||||
|
'!=' => $actual != $expected,
|
||||||
|
'>' => $actual > $expected,
|
||||||
|
'>=' => $actual >= $expected,
|
||||||
|
'<' => $actual < $expected,
|
||||||
|
'<=' => $actual <= $expected,
|
||||||
|
'contains' => str_contains((string) $actual, (string) $expected),
|
||||||
|
default => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns available condition field definitions for the frontend.
|
||||||
|
*
|
||||||
|
* @return array<int, array{key: string, label: string, type: string}>
|
||||||
|
*/
|
||||||
|
public static function availableFields(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
['key' => 'activity.amount', 'label' => 'Aktivnost – znesek', 'type' => 'numeric'],
|
||||||
|
['key' => 'activity.note', 'label' => 'Aktivnost – opomba', 'type' => 'string'],
|
||||||
|
['key' => 'contract.active', 'label' => 'Pogodba – aktivna', 'type' => 'boolean'],
|
||||||
|
['key' => 'contract.account.balance_amount', 'label' => 'Račun – stanje', 'type' => 'numeric'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns available operators grouped by field type.
|
||||||
|
*
|
||||||
|
* @return array<string, array<int, array{key: string, label: string}>>
|
||||||
|
*/
|
||||||
|
public static function availableOperators(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'numeric' => [
|
||||||
|
['key' => '=', 'label' => 'je enako'],
|
||||||
|
['key' => '!=', 'label' => 'ni enako'],
|
||||||
|
['key' => '>', 'label' => 'je večje od'],
|
||||||
|
['key' => '>=', 'label' => 'je večje ali enako'],
|
||||||
|
['key' => '<', 'label' => 'je manjše od'],
|
||||||
|
['key' => '<=', 'label' => 'je manjše ali enako'],
|
||||||
|
],
|
||||||
|
'string' => [
|
||||||
|
['key' => '=', 'label' => 'je enako'],
|
||||||
|
['key' => '!=', 'label' => 'ni enako'],
|
||||||
|
['key' => 'contains', 'label' => 'vsebuje'],
|
||||||
|
],
|
||||||
|
'boolean' => [
|
||||||
|
['key' => '=', 'label' => 'je'],
|
||||||
|
['key' => '!=', 'label' => 'ni'],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,14 @@ public function handle(DecisionEventContext $context, array $config = []): void
|
|||||||
$setting->reactivate = (bool) $config['reactivate'];
|
$setting->reactivate = (bool) $config['reactivate'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cancel all active FieldJobs for this contract before archiving (raw update to avoid boot-event side effects)
|
||||||
|
\DB::table('field_jobs')
|
||||||
|
->where('contract_id', $contractId)
|
||||||
|
->whereNull('completed_at')
|
||||||
|
->whereNull('cancelled_at')
|
||||||
|
->whereNull('deleted_at')
|
||||||
|
->update(['cancelled_at' => now(), 'updated_at' => now()]);
|
||||||
|
|
||||||
$results = app(ArchiveExecutor::class)->executeSetting(
|
$results = app(ArchiveExecutor::class)->executeSetting(
|
||||||
$setting,
|
$setting,
|
||||||
['contract_id' => $contractId],
|
['contract_id' => $contractId],
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\DecisionEvents\Handlers;
|
||||||
|
|
||||||
|
use App\Models\CallLater;
|
||||||
|
use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
|
||||||
|
use App\Services\DecisionEvents\DecisionEventContext;
|
||||||
|
|
||||||
|
class CallLaterHandler implements DecisionEventHandler
|
||||||
|
{
|
||||||
|
public function handle(DecisionEventContext $context, array $config = []): void
|
||||||
|
{
|
||||||
|
$activity = $context->activity;
|
||||||
|
|
||||||
|
if (empty($activity->call_back_at)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
CallLater::create([
|
||||||
|
'activity_id' => $activity->id,
|
||||||
|
'client_case_id' => $activity->client_case_id,
|
||||||
|
'contract_id' => $activity->contract_id,
|
||||||
|
'user_id' => $activity->user_id,
|
||||||
|
'call_back_at' => $activity->call_back_at,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,15 +17,19 @@ class Registry
|
|||||||
'add_segment' => AddSegmentHandler::class,
|
'add_segment' => AddSegmentHandler::class,
|
||||||
'archive_contract' => \App\Services\DecisionEvents\Handlers\ArchiveContractHandler::class,
|
'archive_contract' => \App\Services\DecisionEvents\Handlers\ArchiveContractHandler::class,
|
||||||
'end_field_job' => \App\Services\DecisionEvents\Handlers\EndFieldJobHandler::class,
|
'end_field_job' => \App\Services\DecisionEvents\Handlers\EndFieldJobHandler::class,
|
||||||
|
'add_call_later' => \App\Services\DecisionEvents\Handlers\CallLaterHandler::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function resolve(string $key): DecisionEventHandler
|
public static function resolve(string $key): DecisionEventHandler
|
||||||
{
|
{
|
||||||
$key = trim(strtolower($key));
|
$key = trim(strtolower($key));
|
||||||
$class = static::$map[$key] ?? null;
|
$class = static::$map[$key] ?? null;
|
||||||
if (! $class || ! class_exists($class)) {
|
if (! $class) {
|
||||||
throw new InvalidArgumentException("Unknown decision event handler for key: {$key}");
|
throw new InvalidArgumentException("Unknown decision event handler for key: {$key}");
|
||||||
}
|
}
|
||||||
|
if (! class_exists($class)) {
|
||||||
|
throw new InvalidArgumentException("Handler class {$class} for key {$key} does not exist (check autoload)");
|
||||||
|
}
|
||||||
$handler = app($class);
|
$handler = app($class);
|
||||||
if (! $handler instanceof DecisionEventHandler) {
|
if (! $handler instanceof DecisionEventHandler) {
|
||||||
throw new InvalidArgumentException("Handler for key {$key} must implement DecisionEventHandler");
|
throw new InvalidArgumentException("Handler for key {$key} must implement DecisionEventHandler");
|
||||||
|
|||||||
@@ -152,19 +152,6 @@ public function sendFromLog(EmailLog $log): array
|
|||||||
$email->to(new Address($singleTo, (string) ($log->to_name ?? '')));
|
$email->to(new Address($singleTo, (string) ($log->to_name ?? '')));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always BCC the sender mailbox if present and not already in To
|
|
||||||
$senderBcc = null;
|
|
||||||
if ($fromAddr !== '' && filter_var($fromAddr, FILTER_VALIDATE_EMAIL)) {
|
|
||||||
// Check duplicates against toList
|
|
||||||
$lowerTo = array_map(fn ($v) => strtolower(trim((string) $v)), (array) ($log->to_recipients ?? [$log->to_email]));
|
|
||||||
if (! in_array(strtolower($fromAddr), $lowerTo, true)) {
|
|
||||||
$senderBcc = $fromAddr;
|
|
||||||
$email->bcc(new Address($senderBcc));
|
|
||||||
// Persist BCC for auditing
|
|
||||||
$log->bcc = [$senderBcc];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! empty($text)) {
|
if (! empty($text)) {
|
||||||
$email->text($text);
|
$email->text($text);
|
||||||
}
|
}
|
||||||
@@ -304,10 +291,6 @@ public function sendFromLog(EmailLog $log): array
|
|||||||
}
|
}
|
||||||
|
|
||||||
$mailer->send($email);
|
$mailer->send($email);
|
||||||
// Save log if we modified BCC
|
|
||||||
if (! empty($log->getAttribute('bcc'))) {
|
|
||||||
$log->save();
|
|
||||||
}
|
|
||||||
$headers = $email->getHeaders();
|
$headers = $email->getHeaders();
|
||||||
$messageIdHeader = $headers->get('Message-ID');
|
$messageIdHeader = $headers->get('Message-ID');
|
||||||
$messageId = $messageIdHeader ? $messageIdHeader->getBodyAsString() : null;
|
$messageId = $messageIdHeader ? $messageIdHeader->getBodyAsString() : null;
|
||||||
@@ -330,15 +313,6 @@ public function sendFromLog(EmailLog $log): array
|
|||||||
$message->to($singleTo);
|
$message->to($singleTo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// BCC the sender mailbox if resolvable and not already in To
|
|
||||||
$fromAddr = (string) ($log->from_email ?: (config('mail.from.address') ?? ''));
|
|
||||||
if ($fromAddr !== '' && filter_var($fromAddr, FILTER_VALIDATE_EMAIL)) {
|
|
||||||
$lowerTo = array_map(fn ($v) => strtolower(trim((string) $v)), (array) ($log->to_recipients ?? [$log->to_email]));
|
|
||||||
if (! in_array(strtolower($fromAddr), $lowerTo, true)) {
|
|
||||||
$message->bcc($fromAddr);
|
|
||||||
$log->bcc = [$fromAddr];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$message->subject($subject);
|
$message->subject($subject);
|
||||||
if (! empty($log->reply_to)) {
|
if (! empty($log->reply_to)) {
|
||||||
$message->replyTo($log->reply_to);
|
$message->replyTo($log->reply_to);
|
||||||
@@ -464,15 +438,6 @@ public function sendFromLog(EmailLog $log): array
|
|||||||
$message->to($singleTo);
|
$message->to($singleTo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// BCC the sender mailbox if resolvable and not already in To
|
|
||||||
$fromAddr = (string) ($log->from_email ?: (config('mail.from.address') ?? ''));
|
|
||||||
if ($fromAddr !== '' && filter_var($fromAddr, FILTER_VALIDATE_EMAIL)) {
|
|
||||||
$lowerTo = array_map(fn ($v) => strtolower(trim((string) $v)), (array) ($log->to_recipients ?? [$log->to_email]));
|
|
||||||
if (! in_array(strtolower($fromAddr), $lowerTo, true)) {
|
|
||||||
$message->bcc($fromAddr);
|
|
||||||
$log->bcc = [$fromAddr];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$message->subject($subject);
|
$message->subject($subject);
|
||||||
if (! empty($log->reply_to)) {
|
if (! empty($log->reply_to)) {
|
||||||
$message->replyTo($log->reply_to);
|
$message->replyTo($log->reply_to);
|
||||||
|
|||||||
@@ -30,17 +30,49 @@ public function render(array $template, array $ctx): array
|
|||||||
return preg_replace_callback('/{{\s*([a-zA-Z0-9_.]+)\s*}}/', function ($m) use ($map) {
|
return preg_replace_callback('/{{\s*([a-zA-Z0-9_.]+)\s*}}/', function ($m) use ($map) {
|
||||||
$key = $m[1];
|
$key = $m[1];
|
||||||
|
|
||||||
return (string) data_get($map, $key, '');
|
// body_text is handled separately by applyBodyText(); preserve as literal
|
||||||
|
if ($key === 'body_text') {
|
||||||
|
return $m[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = data_get($map, $key, '');
|
||||||
|
|
||||||
|
// If the resolved value is an array (e.g. {{ contract.meta }} used directly),
|
||||||
|
// return empty string instead of triggering "Array to string conversion".
|
||||||
|
if (is_array($value)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return (string) $value;
|
||||||
}, $input);
|
}, $input);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
$bodyText = isset($ctx['body_text']) ? (string) $ctx['body_text'] : '';
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'subject' => $replacer($template['subject']) ?? '',
|
'subject' => $replacer($template['subject']) ?? '',
|
||||||
'html' => $replacer($template['html'] ?? null) ?? null,
|
'html' => $this->applyBodyText($replacer($template['html'] ?? null) ?? null, $bodyText, html: true),
|
||||||
'text' => $replacer($template['text'] ?? null) ?? null,
|
'text' => $this->applyBodyText($replacer($template['text'] ?? null) ?? null, $bodyText, html: false),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Substitute the literal {{body_text}} placeholder with the user-supplied body text.
|
||||||
|
* In HTML context the text is HTML-escaped and newlines are converted to <br>.
|
||||||
|
* In plain-text context the raw value is used.
|
||||||
|
*/
|
||||||
|
public function applyBodyText(?string $content, string $bodyText, bool $html = true): ?string
|
||||||
|
{
|
||||||
|
if ($content === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$replacement = $html
|
||||||
|
? nl2br(htmlspecialchars($bodyText, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'))
|
||||||
|
: $bodyText;
|
||||||
|
|
||||||
|
return preg_replace('/{{\s*body_text\s*}}/', $replacement, $content);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array{client?:Client, person?:Person, client_case?:ClientCase, contract?:Contract, activity?:Activity, extra?:array} $ctx
|
* @param array{client?:Client, person?:Person, client_case?:ClientCase, contract?:Contract, activity?:Activity, extra?:array} $ctx
|
||||||
*/
|
*/
|
||||||
@@ -145,12 +177,18 @@ protected function buildMap(array $ctx): array
|
|||||||
'id' => data_get($co, 'id'),
|
'id' => data_get($co, 'id'),
|
||||||
'uuid' => data_get($co, 'uuid'),
|
'uuid' => data_get($co, 'uuid'),
|
||||||
'reference' => data_get($co, 'reference'),
|
'reference' => data_get($co, 'reference'),
|
||||||
// Format amounts in EU style for emails
|
// Account amounts — sourced from the related Account model
|
||||||
'amount' => $formatMoneyEu(data_get($co, 'amount')),
|
'account' => [
|
||||||
|
'balance_amount' => $formatMoneyEu(data_get($co, 'account.balance_amount')),
|
||||||
|
'initial_amount' => $formatMoneyEu(data_get($co, 'account.initial_amount')),
|
||||||
|
],
|
||||||
];
|
];
|
||||||
$meta = data_get($co, 'meta');
|
$meta = data_get($co, 'meta');
|
||||||
|
if (is_string($meta)) {
|
||||||
|
$meta = json_decode($meta, true) ?? [];
|
||||||
|
}
|
||||||
if (is_array($meta)) {
|
if (is_array($meta)) {
|
||||||
$out['contract']['meta'] = $meta;
|
$out['contract']['meta'] = $this->flattenMetaForTemplate($meta);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isset($ctx['activity'])) {
|
if (isset($ctx['activity'])) {
|
||||||
@@ -172,7 +210,50 @@ protected function buildMap(array $ctx): array
|
|||||||
if (! empty($ctx['extra']) && is_array($ctx['extra'])) {
|
if (! empty($ctx['extra']) && is_array($ctx['extra'])) {
|
||||||
$out['extra'] = $ctx['extra'];
|
$out['extra'] = $ctx['extra'];
|
||||||
}
|
}
|
||||||
|
if (isset($ctx['mail_profile'])) {
|
||||||
|
$mp = $ctx['mail_profile'];
|
||||||
|
$out['profile'] = [
|
||||||
|
'signature' => is_array($mp->signature) ? $mp->signature : [],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
return $out;
|
return $out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flatten a contract meta array so every leaf value is accessible by its bare key.
|
||||||
|
*
|
||||||
|
* Handles three formats stored in the wild:
|
||||||
|
* 1. Numeric wrapper: { "1": { "sklic": "SI00…", "job_days": 1 } }
|
||||||
|
* → { "sklic": "SI00…", "job_days": 1 }
|
||||||
|
* 2. Structured entry: { "sklic": { "value": "SI00…", "type": "string" } }
|
||||||
|
* → { "sklic": "SI00…" }
|
||||||
|
* 3. Already flat: { "sklic": "SI00…" }
|
||||||
|
* → { "sklic": "SI00…" }
|
||||||
|
*/
|
||||||
|
private function flattenMetaForTemplate(array $meta): array
|
||||||
|
{
|
||||||
|
$flat = [];
|
||||||
|
foreach ($meta as $key => $item) {
|
||||||
|
if (!is_array($item)) {
|
||||||
|
// Plain scalar — keep as-is (format 3)
|
||||||
|
if (!array_key_exists($key, $flat)) {
|
||||||
|
$flat[$key] = $item;
|
||||||
|
}
|
||||||
|
} elseif (array_key_exists('value', $item)) {
|
||||||
|
// Structured { value, type, title } entry (format 2)
|
||||||
|
$flat[$key] = $item['value'];
|
||||||
|
} elseif (is_numeric($key)) {
|
||||||
|
// Numeric wrapper key — recurse and alias without the prefix (format 1)
|
||||||
|
foreach ($this->flattenMetaForTemplate($item) as $nk => $nv) {
|
||||||
|
if (!array_key_exists($nk, $flat)) {
|
||||||
|
$flat[$nk] = $nv;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Non-numeric nested arrays without a 'value' key are silently skipped
|
||||||
|
}
|
||||||
|
|
||||||
|
return $flat;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services\Import;
|
||||||
|
|
||||||
|
use App\Models\ImportEntity;
|
||||||
|
use App\Services\Import\Contracts\EntityHandlerInterface;
|
||||||
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
|
||||||
|
abstract class BaseEntityHandler implements EntityHandlerInterface
|
||||||
|
{
|
||||||
|
protected ?ImportEntity $entityConfig;
|
||||||
|
|
||||||
|
public function __construct(?ImportEntity $entityConfig = null)
|
||||||
|
{
|
||||||
|
$this->entityConfig = $entityConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate mapped data using configuration rules.
|
||||||
|
*/
|
||||||
|
public function validate(array $mapped): array
|
||||||
|
{
|
||||||
|
$rules = $this->entityConfig?->validation_rules ?? [];
|
||||||
|
|
||||||
|
if (empty($rules)) {
|
||||||
|
return ['valid' => true, 'errors' => []];
|
||||||
|
}
|
||||||
|
|
||||||
|
$validator = Validator::make($mapped, $rules);
|
||||||
|
|
||||||
|
if ($validator->fails()) {
|
||||||
|
return [
|
||||||
|
'valid' => false,
|
||||||
|
'errors' => $validator->errors()->all(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['valid' => true, 'errors' => []];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get processing options from config.
|
||||||
|
*/
|
||||||
|
protected function getOption(string $key, mixed $default = null): mixed
|
||||||
|
{
|
||||||
|
return $this->entityConfig?->processing_options[$key] ?? $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if a field has changed.
|
||||||
|
*/
|
||||||
|
protected function hasChanged($model, string $field, mixed $newValue): bool
|
||||||
|
{
|
||||||
|
$current = $model->{$field};
|
||||||
|
|
||||||
|
if (is_null($newValue) && is_null($current)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $current != $newValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Track which fields were applied/changed.
|
||||||
|
*/
|
||||||
|
protected function trackAppliedFields($model, array $payload): array
|
||||||
|
{
|
||||||
|
$applied = [];
|
||||||
|
|
||||||
|
foreach ($payload as $field => $value) {
|
||||||
|
if ($this->hasChanged($model, $field, $value)) {
|
||||||
|
$applied[] = $field;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $applied;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default implementation returns null - override in specific handlers.
|
||||||
|
*/
|
||||||
|
public function resolve(array $mapped, array $context = []): mixed
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user