Files
investbrain/app/Imports/Sheets/DailyChangesSheet.php
T

79 lines
2.6 KiB
PHP
Raw Normal View History

2024-08-07 18:29:23 -05:00
<?php
namespace App\Imports\Sheets;
2024-08-29 23:36:44 -05:00
use App\Models\DailyChange;
2024-10-24 14:48:24 -05:00
use App\Models\BackupImport;
2024-10-18 21:59:35 -05:00
use Illuminate\Support\Carbon;
2024-10-24 14:48:24 -05:00
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithUpserts;
use App\Rules\PortfolioAccessValidationRule;
2024-08-07 18:29:23 -05:00
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
2024-08-29 21:39:59 -05:00
use Maatwebsite\Excel\Concerns\WithValidation;
2024-10-24 14:48:24 -05:00
use Maatwebsite\Excel\Concerns\WithBatchInserts;
2024-08-07 18:29:23 -05:00
2024-10-24 14:48:24 -05:00
class DailyChangesSheet implements ToModel, WithHeadingRow, WithValidation, WithBatchInserts, WithUpserts, SkipsEmptyRows, WithEvents
2024-08-07 18:29:23 -05:00
{
2024-10-24 14:48:24 -05:00
public function __construct(
public BackupImport $backupImport
) { }
2024-08-30 20:22:28 -05:00
2024-10-24 14:48:24 -05:00
/**
* @return array
*/
public function registerEvents(): array
2024-08-07 18:29:23 -05:00
{
2024-10-24 14:48:24 -05:00
return [
BeforeSheet::class => function(BeforeSheet $event) {
DB::commit();
$this->backupImport->update([
'message' => __('Importing daily changes...'),
]);
DB::beginTransaction();
}
];
}
public function model(array $dailyChange)
{
return new DailyChange([
'total_market_value' => $dailyChange['total_market_value'],
'total_cost_basis' => $dailyChange['total_cost_basis'],
'total_gain' => $dailyChange['total_gain'],
'total_dividends_earned' => $dailyChange['total_dividends_earned'],
'realized_gains' => $dailyChange['realized_gains'],
'annotation' => $dailyChange['annotation'],
'portfolio_id' => $dailyChange['portfolio_id'],
'date' => Carbon::parse($dailyChange['date'])->format('Y-m-d')
]);
}
public function batchSize(): int
{
return 150;
}
2024-10-18 21:59:35 -05:00
2024-10-24 14:48:24 -05:00
public function uniqueBy()
{
return ['portfolio_id', 'date'];
2024-08-07 18:29:23 -05:00
}
2024-08-29 21:39:59 -05:00
public function rules(): array
{
return [
2024-10-24 14:48:24 -05:00
'portfolio_id' => ['required', new PortfolioAccessValidationRule($this->backupImport->user_id)],
2024-08-29 21:39:59 -05:00
'date' => ['required', 'date'],
'total_market_value' => ['sometimes', 'nullable', 'numeric'],
'total_cost_basis' => ['sometimes', 'nullable', 'min:0', 'numeric'],
'total_gain' => ['sometimes', 'nullable', 'numeric'],
2024-10-18 21:59:35 -05:00
'total_dividends_earned' => ['sometimes', 'nullable', 'min:0', 'numeric'],
2024-08-29 21:39:59 -05:00
'realized_gains' => ['sometimes', 'nullable', 'numeric'],
'annotation' => ['sometimes', 'nullable', 'string'],
];
}
2024-08-07 18:29:23 -05:00
}