Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion modules/Addons/BankPayments/BankPaymentsModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function getDescription(): string

public function getVersion(): string
{
return '0.4.0';
return '0.4.1';
}

public function getAuthor(): string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public function up(): void

public function down(): void
{
// Rows without an e-mail message can only have come from a statement
// import. They are removed before restoring the NOT NULL column.
DB::table('bank_transactions')->whereNull('bank_message_id')->delete();

Schema::table('bank_transactions', function (Blueprint $table) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ public function index(Request $request): View
$this->ensureActive();

$validated = $request->validate([
'status' => ['nullable', 'string', 'in:pending,review,ambiguous,auto_ready,unmatched,manual_currency,error'],
'status' => ['nullable', 'string', 'in:pending,review,ambiguous,auto_ready,unmatched,manual_currency,error,rejected'],
'verification' => ['nullable', 'string', 'in:confirmed,unconfirmed'],
]);

$statuses = [
$queueStatuses = [
'pending', 'review', 'ambiguous', 'auto_ready',
'unmatched', 'manual_currency', 'error',
];
$filterStatuses = [...$queueStatuses, 'rejected'];

// One status arrives as a string, and whereIn() wants a list: handed
// the string it answered with a 500 (#511).
Expand All @@ -35,7 +36,7 @@ public function index(Request $request): View

$transactions = BankTransaction::query()
->with(['message.mailbox', 'matches.invoice.client'])
->whereIn('matching_status', $selectedStatus ? [$selectedStatus] : $statuses)
->whereIn('matching_status', $selectedStatus ? [$selectedStatus] : $queueStatuses)
->when($selectedVerification === 'confirmed', fn ($query) => $query->whereNotNull('verified_at'))
->when($selectedVerification === 'unconfirmed', fn ($query) => $query->whereNull('verified_at'))
->latest('transaction_date')
Expand All @@ -45,7 +46,7 @@ public function index(Request $request): View

return view('bank-payments::admin.matches.index', [
'transactions' => $transactions,
'statuses' => $statuses,
'statuses' => $filterStatuses,
'selectedStatus' => $selectedStatus,
'selectedVerification' => $selectedVerification,
'mode' => BankPaymentsSettings::mode(),
Expand Down Expand Up @@ -85,6 +86,27 @@ public function rematch(BankTransaction $transaction, InvoiceMatcher $matcher):
);
}

public function restore(BankTransaction $transaction, InvoiceMatcher $matcher): RedirectResponse
{
$this->ensureActive();

abort_unless((string) $transaction->matching_status === 'rejected', 404);
abort_if($transaction->import()->where('status', 'imported')->exists(), 404);

$transaction->update([
'matching_status' => 'pending',
'matching_score' => null,
'matching_reason' => null,
'matched_at' => null,
]);

$result = $matcher->match($transaction);

return back()->with('success', __('bank-payments::matches.restored', [
'status' => __('bank-payments::matches.status_'.$result['status']),
]));
}

public function dismiss(BankTransaction $transaction): RedirectResponse
{
$this->ensureActive();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function index(Request $request): View
'mailbox' => ['nullable', 'integer', 'exists:bank_mailboxes,id'],
'currency' => ['nullable', 'string', 'size:3'],
'q' => ['nullable', 'string', 'max:100'],
'matching' => ['nullable', 'string', 'in:pending,review,ambiguous,auto_ready,unmatched,manual_currency,error'],
'matching' => ['nullable', 'string', 'in:pending,review,ambiguous,auto_ready,unmatched,manual_currency,error,rejected'],
'verification' => ['nullable', 'string', 'in:confirmed,unconfirmed'],
]);

Expand Down
52 changes: 42 additions & 10 deletions modules/Addons/BankPayments/Services/BankCsvImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ public function import(UploadedFile $file, string $bank, bool $verifyOnly = fals
$duplicates = 0;
$errors = 0;
$skipped = 0;
$existingCounts = [];
$seenCounts = [];

foreach ($rows as $row) {
try {
Expand All @@ -64,16 +66,32 @@ public function import(UploadedFile $file, string $bank, bool $verifyOnly = fals
continue;
}

$duplicate = BankTransaction::query()
->where('bank', $bank)
->whereDate('transaction_date', $date)
->where('amount', $amount)
->where('currency', $currency)
->when($reference === null || $reference === '',
fn ($query) => $query->where(fn ($inner) => $inner->whereNull('reference')->orWhere('reference', '')),
fn ($query) => $query->where('reference', $reference))
->latest('id')
->first();
/*
* Identical rows are legitimate: a customer can pay the same
* invoice twice on the same day with the same title. Count the
* matching rows already stored and the occurrences in this
* statement; a row is a duplicate only when the stored rows
* already cover its position in the file.
*/
$key = implode('|', [
$bank,
(string) $date,
number_format($amount, 2, '.', ''),
$currency,
(string) $reference,
]);
$seen = $seenCounts[$key] ?? 0;
$seenCounts[$key] = $seen + 1;
$existingCounts[$key] ??= $this->matchingTransactions(
$bank, $date, $amount, $currency, $reference
)->count();

$duplicate = null;
if ($existingCounts[$key] > $seen) {
$duplicate = $this->matchingTransactions($bank, $date, $amount, $currency, $reference)
->latest('id')
->first();
}

if ($duplicate) {
if ($emailActive && $duplicate->verified_at === null) {
Expand Down Expand Up @@ -138,6 +156,20 @@ public function import(UploadedFile $file, string $bank, bool $verifyOnly = fals
return compact('imported', 'verified', 'duplicates', 'errors', 'skipped');
}

private function matchingTransactions(string $bank, mixed $date, float $amount, string $currency, ?string $reference)
{
return BankTransaction::query()
->where('bank', $bank)
->whereDate('transaction_date', $date)
->where('amount', $amount)
->where('currency', $currency)
->when(
$reference === null || $reference === '',
fn ($query) => $query->where(fn ($inner) => $inner->whereNull('reference')->orWhere('reference', '')),
fn ($query) => $query->where('reference', $reference)
);
}

private function format(UploadedFile $file, string $contents): string
{
$extension = strtolower($file->getClientOriginalExtension());
Expand Down
2 changes: 2 additions & 0 deletions modules/Addons/BankPayments/lang/de/matches.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@
'verified_mt940' => 'Durch MT940 bestätigt',
'verified' => 'Bestätigt',
'verified_camt053' => 'Durch CAMT.053 bestätigt',
'restore_action' => 'Wiederherstellen',
'restored' => 'Überweisung wiederhergestellt und erneut zugeordnet: :status.',
];
2 changes: 2 additions & 0 deletions modules/Addons/BankPayments/lang/en/matches.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
'dismiss_action' => 'Remove',
'dismiss_confirm' => 'Remove this transfer from the matching queue? It does not relate to a service payment.',
'dismissed' => 'Transfer removed from the queue as not related to a service payment.',
'restore_action' => 'Restore',
'restored' => 'Transfer restored and matched again: :status.',
'not_service_reason' => 'Not related to a service payment.',
'verified_mt940' => 'Confirmed by MT940',
'verified' => 'Confirmed',
Expand Down
2 changes: 2 additions & 0 deletions modules/Addons/BankPayments/lang/pl/matches.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
'dismiss_action' => 'Usuń',
'dismiss_confirm' => 'Usunąć tę wpłatę z kolejki dopasowań? Nie dotyczy płatności za usługi.',
'dismissed' => 'Wpłata usunięta z kolejki jako nie dotycząca płatności za usługi.',
'restore_action' => 'Przywróć',
'restored' => 'Wpłata przywrócona do kolejki i ponownie dopasowana: :status.',
'not_service_reason' => 'Nie dotyczy płatności za usługi.',
'verified_mt940' => 'Potwierdzone MT940',
'verified' => 'Potwierdzone',
Expand Down
2 changes: 2 additions & 0 deletions modules/Addons/BankPayments/lang/tr/matches.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@
'verified_mt940' => 'MT940 ile onaylandı',
'verified' => 'Onaylandı',
'verified_camt053' => 'CAMT.053 ile onaylandı',
'restore_action' => 'Geri yükle',
'restored' => 'Transfer geri yüklendi ve yeniden eşleştirildi: :status.',
];
2 changes: 2 additions & 0 deletions modules/Addons/BankPayments/lang/zh/matches.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@
'verified_mt940' => 'MT940 已确认',
'verified' => '已确认',
'verified_camt053' => 'CAMT.053 已确认',
'restore_action' => '恢复',
'restored' => '转账已恢复并重新匹配::status。',
];
1 change: 1 addition & 0 deletions modules/Addons/BankPayments/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
Route::get('transactions/{transaction}/assign', [BankAssignmentController::class, 'show'])->name('transactions.assign');
Route::post('transactions/{transaction}/assign', [BankAssignmentController::class, 'store'])->name('transactions.assign.store');
Route::post('transactions/{transaction}/rematch', [BankMatchController::class, 'rematch'])->name('transactions.rematch');
Route::post('transactions/{transaction}/restore', [BankMatchController::class, 'restore'])->name('transactions.restore');
Route::delete('transactions/{transaction}/dismiss', [BankMatchController::class, 'dismiss'])->name('transactions.dismiss');
Route::get('payers', [BankAssignmentController::class, 'payers'])->name('payers.index');
Route::delete('payers/{profile}', [BankAssignmentController::class, 'forgetPayer'])->name('payers.destroy');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,12 @@
@endif
<div style="margin-top:6px;display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap;">
<a href="{{ route('admin.bank-payments.transactions.assign', $transaction) }}" class="btn btn-default btn-xs">{{ __('bank-payments::matches.assign_action') }}</a>
@unless(in_array($transaction->matching_status, ['imported', 'rejected'], true))
@if($transaction->matching_status === 'rejected')
<form method="POST" action="{{ route('admin.bank-payments.transactions.restore', $transaction) }}" style="display:inline;">
@csrf
<button type="submit" class="btn btn-default btn-xs"><i class="fas fa-undo"></i> {{ __('bank-payments::matches.restore_action') }}</button>
</form>
@elseif(! in_array($transaction->matching_status, ['imported'], true))
<form method="POST" action="{{ route('admin.bank-payments.transactions.rematch', $transaction) }}" style="display:inline;">
@csrf
<button type="submit" class="btn btn-default btn-xs">{{ __('bank-payments::matches.rematch_action') }}</button>
Expand All @@ -77,7 +82,7 @@
@method('DELETE')
<button type="submit" class="btn btn-danger btn-xs"><i class="fas fa-trash"></i> {{ __('bank-payments::matches.dismiss_action') }}</button>
</form>
@endunless
@endif
</div>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
<label class="form-label" style="font-size:12px;">{{ __('bank-payments::matches.matching_status') }}</label>
<select name="matching" class="form-control">
<option value="">{{ __('bank-payments::transactions.all') }}</option>
@foreach(['pending','review','ambiguous','auto_ready','unmatched','manual_currency','error'] as $matchingStatus)
@foreach(['pending','review','ambiguous','auto_ready','unmatched','manual_currency','error','rejected'] as $matchingStatus)
<option value="{{ $matchingStatus }}" @selected(($filters['matching'] ?? '') === $matchingStatus)>{{ __('bank-payments::matches.status_'.$matchingStatus) }}</option>
@endforeach
</select>
Expand Down
86 changes: 86 additions & 0 deletions tests/Feature/BankPayments/BankAssignmentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,89 @@ function bankAssignmentInvoice(): array

$this->get(route('admin.bank-payments.matches.index', ['status' => '']))->assertOk();
});


it('keeps two genuinely identical statement rows and does not duplicate them on reimport', function () {
bankAssignmentBoot();
$this->actingAs(Admin::factory()->create(), 'admin');

$contents = file_get_contents(base_path('tests/Fixtures/BankPayments/duplicate-identical-transfers.csv'));

$this->post(route('admin.bank-payments.import.csv'), [
'bank' => 'standard',
'csv' => UploadedFile::fake()->createWithContent('duplicate-transfers.csv', $contents),
])->assertRedirect()->assertSessionHas('success');

$transactions = BankTransaction::where('bank', 'standard')->where('source', 'csv')->orderBy('id')->get();

expect($transactions)->toHaveCount(2)
->and($transactions[0]->reference)->toBe('PRO-2026/11-000005')
->and($transactions[1]->reference)->toBe('PRO-2026/11-000005');

$this->post(route('admin.bank-payments.import.csv'), [
'bank' => 'standard',
'csv' => UploadedFile::fake()->createWithContent('duplicate-transfers.csv', $contents),
])->assertRedirect()->assertSessionHas('info');

expect(BankTransaction::where('bank', 'standard')->where('source', 'csv')->count())->toBe(2);
});

it('adds only the extra row when one identical transfer already exists', function () {
bankAssignmentBoot();
$this->actingAs(Admin::factory()->create(), 'admin');

$existing = bankAssignmentTransaction('EXAMPLE BUYER', 1314.87);
$existing->update([
'bank' => 'standard',
'reference' => 'PRO-2026/11-000005',
'transaction_date' => '2026-11-27',
]);

$contents = file_get_contents(base_path('tests/Fixtures/BankPayments/duplicate-identical-transfers.csv'));

$this->post(route('admin.bank-payments.import.csv'), [
'bank' => 'standard',
'csv' => UploadedFile::fake()->createWithContent('duplicate-transfers.csv', $contents),
])->assertRedirect()->assertSessionHas('success');

$transactions = BankTransaction::where('bank', 'standard')->orderBy('id')->get();

expect($transactions)->toHaveCount(2)
->and($transactions->where('source', 'csv'))->toHaveCount(1);
});

it('restores a rejected transfer to the matching queue', function () {
bankAssignmentBoot();
$this->actingAs(Admin::factory()->create(), 'admin');
[, $invoice] = bankAssignmentInvoice();
$transaction = bankAssignmentTransaction();

$this->delete(route('admin.bank-payments.transactions.dismiss', $transaction))
->assertRedirect()->assertSessionHas('success');

expect($transaction->fresh()->matching_status)->toBe('rejected');

$this->get(route('admin.bank-payments.matches.index'))
->assertOk()
->assertDontSee(route('admin.bank-payments.transactions.restore', $transaction), false);

$this->get(route('admin.bank-payments.matches.index', ['status' => 'rejected']))
->assertOk()
->assertSee(route('admin.bank-payments.transactions.restore', $transaction), false);

$this->post(route('admin.bank-payments.transactions.restore', $transaction))
->assertRedirect()->assertSessionHas('success');

expect($transaction->fresh()->matching_status)->not->toBe('rejected')
->and(BankMatch::where('bank_transaction_id', $transaction->id)->where('invoice_id', $invoice->id)->exists())->toBeTrue();
});

it('does not restore a booked transfer', function () {
bankAssignmentBoot();
$this->actingAs(Admin::factory()->create(), 'admin');

$transaction = bankAssignmentTransaction();
$transaction->update(['matching_status' => 'imported']);

$this->post(route('admin.bank-payments.transactions.restore', $transaction))->assertNotFound();
});
3 changes: 3 additions & 0 deletions tests/Fixtures/BankPayments/duplicate-identical-transfers.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Data operacji,Kwota,Waluta,Dane kontrahenta,Tytuł operacji
27-11-2026,1314.87,PLN,EXAMPLE BUYER,PRO-2026/11-000005
27-11-2026,1314.87,PLN,EXAMPLE BUYER,PRO-2026/11-000005
Loading