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

151 lines
5.6 KiB
PHP
Raw Normal View History

2024-08-07 18:29:23 -05:00
<?php
2025-01-28 17:33:54 -06:00
declare(strict_types=1);
2024-08-07 18:29:23 -05:00
namespace App\Imports\Sheets;
use App\Imports\ValidatesPortfolioAccess;
2025-01-28 17:14:49 -06:00
use App\Models\BackupImport;
use App\Models\Currency;
use App\Models\CurrencyRate;
2024-10-24 14:48:24 -05:00
use App\Models\Holding;
2024-08-07 18:29:23 -05:00
use App\Models\Transaction;
2024-10-24 14:48:24 -05:00
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
2024-10-24 14:48:24 -05:00
use Illuminate\Support\Facades\DB;
2025-01-28 17:14:49 -06:00
use Illuminate\Support\Str;
2024-08-07 18:29:23 -05:00
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
2025-01-28 17:14:49 -06:00
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
2024-08-07 18:29:23 -05:00
use Maatwebsite\Excel\Concerns\WithHeadingRow;
2024-08-29 21:39:59 -05:00
use Maatwebsite\Excel\Concerns\WithValidation;
2025-01-28 17:14:49 -06:00
use Maatwebsite\Excel\Events\BeforeSheet;
2024-08-07 18:29:23 -05:00
2025-01-28 17:14:49 -06:00
class TransactionsSheet implements SkipsEmptyRows, ToCollection, WithEvents, WithHeadingRow, WithValidation
2024-08-07 18:29:23 -05:00
{
use ValidatesPortfolioAccess;
2024-10-24 14:48:24 -05:00
public function __construct(
public BackupImport $backupImport
2025-01-28 17:14:49 -06:00
) {}
2024-08-29 23:36:44 -05:00
2024-10-24 14:48:24 -05:00
public function registerEvents(): array
{
return [
2025-01-28 17:14:49 -06:00
BeforeSheet::class => function (BeforeSheet $event) {
2024-10-24 14:48:24 -05:00
DB::commit();
$this->backupImport->update([
'message' => __('Preparing to import transactions...'),
2024-10-24 14:48:24 -05:00
]);
DB::beginTransaction();
2025-01-28 17:14:49 -06:00
},
2024-10-24 14:48:24 -05:00
];
}
2024-08-29 23:36:44 -05:00
public function collection(Collection $transactions)
2024-10-24 14:48:24 -05:00
{
2024-08-29 23:36:44 -05:00
// if has any transactions not in base currency, need to sync timeseries conversion rates
if ($transactions->where('currency', '!=', config('investbrain.base_currency'))->isNotEmpty()) {
CurrencyRate::timeSeriesRates('', $transactions->min('date'));
}
$totalBatches = count($transactions) / $this->batchSize();
// chunk transactions
$transactions->chunk($this->batchSize())->each(function ($chunk, $index) use ($totalBatches) {
$this->backupImport->update([
'message' => __('Importing transactions (Batch :currentBatch of :totalBatches)...', ['currentBatch' => $index + 1, 'totalBatches' => $totalBatches]),
]);
2024-08-30 20:22:28 -05:00
$this->validatePortfolioAccess($chunk);
// have to cast to native values
$chunk = $chunk->map(function ($transaction) {
$date = Carbon::parse($transaction['date'])->toDateString();
// if transaction not in base currency, need to convert
if ($transaction['currency'] == config('investbrain.base_currency')) {
$cost_basis_base = $transaction['cost_basis'] ?? 0;
$sale_price_base = $transaction['sale_price'];
} else {
$cost_basis_base = Currency::convert($transaction['cost_basis'], $transaction['currency'], date: $date);
$sale_price_base = Currency::convert($transaction['sale_price'], $transaction['currency'], date: $date);
}
return [
'id' => $transaction['transaction_id'] ?? Str::uuid()->toString(),
'symbol' => strtoupper($transaction['symbol']),
'portfolio_id' => $transaction['portfolio_id'],
'transaction_type' => $transaction['transaction_type'],
'quantity' => $transaction['quantity'],
'cost_basis' => $transaction['cost_basis'] ?? 0,
'sale_price' => $transaction['sale_price'],
'cost_basis_base' => $cost_basis_base,
'sale_price_base' => $sale_price_base,
'split' => boolval($transaction['split']) ? 1 : 0,
'reinvested_dividend' => boolval($transaction['reinvested_dividend']) ? 1 : 0,
'date' => $date,
];
});
Transaction::upsert(
$chunk->toArray(),
['id'],
[
'id',
'symbol',
'portfolio_id',
'transaction_type',
'quantity',
'cost_basis',
'sale_price',
'split',
'reinvested_dividend',
2025-01-28 17:14:49 -06:00
'date',
]
);
// get unique symbol/portfolio id combination and stub out related holdings
2025-01-28 17:14:49 -06:00
$chunk->unique(fn ($item) => $item['symbol'].$item['portfolio_id'])
->each(function ($holding) {
Holding::firstOrCreate([
'symbol' => $holding['symbol'],
'portfolio_id' => $holding['portfolio_id'],
], [
'quantity' => 0,
'average_cost_basis' => 0,
'splits_synced_at' => now(),
]);
});
});
2024-10-24 14:48:24 -05:00
}
2024-08-29 23:36:44 -05:00
public function batchSize(): int
2024-10-24 14:48:24 -05:00
{
return 500;
2024-08-07 18:29:23 -05:00
}
2024-08-28 22:06:47 -05:00
2024-08-29 21:39:59 -05:00
public function rules(): array
{
return [
2024-10-28 19:20:52 -05:00
'transaction_id' => ['sometimes', 'nullable', 'uuid'],
2024-08-29 21:39:59 -05:00
'symbol' => ['required', 'string'],
2024-10-28 19:20:52 -05:00
'portfolio_id' => ['required', 'uuid'],
2024-08-29 21:39:59 -05:00
'quantity' => ['required', 'min:0', 'numeric'],
'transaction_type' => ['required', 'in:BUY,SELL'],
'date' => ['required', 'date'],
'quantity' => ['required', 'min:0', 'numeric'],
'currency' => ['required', 'string'],
2024-10-18 22:21:12 -05:00
'split' => ['sometimes', 'nullable', 'boolean'],
'reinvested_dividend' => ['sometimes', 'nullable', 'boolean'],
2024-08-29 21:39:59 -05:00
'cost_basis' => ['sometimes', 'nullable', 'min:0', 'numeric'],
'sale_price' => ['sometimes', 'nullable', 'min:0', 'numeric'],
];
}
2024-08-07 18:29:23 -05:00
}