/var/www/html/back/app/Imports/PaymentImport.php
<?php
namespace App\Imports;
use App\Domain\Payment\Enums\PaymentStatusEnum;
use App\Domain\Payment\Enums\PaymentTypeEnum;
use App\Models\Account;
use App\Models\Article;
use App\Models\Counterparty;
use App\Models\Payment;
use App\Models\PaymentDistribution;
use App\Models\Project;
use App\Models\User;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
class PaymentImport implements ToModel, WithStartRow
{
public function startRow(): int
{
return 2;
}
public function model(array $row)
{
$user = User::query()->where(['first_name' => 'Финансист', 'is_active' => true])->first();
if (!isset($user)) {
$user = User::query()->create(['first_name' => 'Финансист', 'password' => 123, 'is_active' => true]);
}
if (isset($row[7])) {
$account = Account::query()->firstOrCreate(['model_id' => 3, 'name' => $row[7]]);
}
if (isset($row[4])) {
$counterparty = Counterparty::query()->firstOrCreate(['model_id' => 3, 'name' => $row[4]]);
}
$article = Article::query()->firstOrCreate(['model_id' => 3, 'name' => $row[2]]);
if ($article->article_type == 'credit') {
$type = PaymentTypeEnum::PAYMENT_TYPE_RECEPTION->value;
} else {
$type = PaymentTypeEnum::PAYMENT_TYPE_PAYMENT->value;
}
$unixDate = ($row[1] - 25569) * 86400;
$dateString = date('Y-m-d', $unixDate);
$payment = Payment::query()->create(
[
'user_id' => $user->id,
'model_id' => 3,
'name' => $row[6],
'payment_date' => Carbon::parse($dateString)->format('Y-m-d'),
'amount' => $row[3],
'status' => PaymentStatusEnum::STATUS_SENT,
'account_id' => $account->id,
'counterparty_id' => $counterparty->id,
'payment_type' => $type,
'organization_id' => $account->organization_id ?? null,
]);
if ($payment) {
if (isset($row[5])) {
$project = Project::query()->firstOrCreate(['model_id' => 3, 'offer_number' => $row[5]]);
}
return new PaymentDistribution([
'payment_id' => $payment->id,
'project_id' => $project->id ?? null,
'article_id' => $article->id,
'payment_date' => $row[1],
'amount' => $row[3],
]);
}
return 0;
}
}