This commit is contained in:
2026-04-15 01:24:42 +02:00
parent 6786665cbf
commit 596b7a995e
15 changed files with 1206 additions and 115 deletions

View File

@@ -414,4 +414,38 @@ class FinancesController
header( 'Location: /finances/main_view/' );
exit;
}
public static function fakturowniaDocumentPositionSkip()
{
if ( !self::requireAuth() )
return false;
if ( !\S::csrf_verify() )
{
\S::alert( 'Nieprawidlowy token bezpieczenstwa. Odswiez strone i sproboj ponownie.' );
header( 'Location: /finances/main_view/' );
exit;
}
$externalId = trim( (string)\S::get( 'external_id' ) );
$documentType = trim( (string)\S::get( 'document_type' ) );
$externalItemKey = trim( (string)\S::get( 'external_item_key' ) );
$itemName = trim( (string)\S::get( 'item_name' ) );
if ( $externalId === '' || $documentType === '' || $externalItemKey === '' )
{
\S::alert( 'Nie udalo sie pominac pozycji — brakuje danych faktury.' );
header( 'Location: /finances/main_view/' );
exit;
}
$importRepo = self::importRepo();
$importRepo -> ensureTables();
$importRepo -> markDocumentPositionSkipped( $externalId, $documentType, $externalItemKey, $itemName );
$importRepo -> removeOccurrenceFromItemQueue( $externalItemKey, $externalId );
\S::alert( 'Pozycja zostala pominieta tylko dla faktury ' . $externalId . '.' );
header( 'Location: /finances/main_view/' );
exit;
}
}

View File

@@ -18,43 +18,109 @@ class FakturowniaApiClient
public function fetchSalesDocuments( $startDate, $page = 1 )
{
$query = [
'page' => (int)$page,
'per_page' => $this -> pageLimit
];
if ( $this -> canUseCurrentMonthPeriod( $startDate ) )
$query['period'] = 'this_month';
// period=more + date_from: Fakturownia filtruje po stronie API po issue_date.
// Dzieki temu nie pobieramy historycznych faktur i paginacja konczy sie naturalnie.
$query = $this -> buildDateRangeQuery( $startDate, $page );
return $this -> requestList( '/invoices.json', $query );
}
public function fetchCostDocuments( $startDate, $page = 1 )
{
$queries = [
[
'page' => (int)$page,
'per_page' => $this -> pageLimit,
'income' => 'no'
]
// W Fakturowni "faktura kosztowa" moze byc zapisana jako:
// a) zwykla faktura z income=false (widoczna w /invoices.json?income=no, URL /invoices/ID) — primary source
// b) koszt w oddzielnym module /costs.json
// c) wydatek w /expenses.json (starsze API)
// Odpytujemy wszystkie trzy i merge'ujemy po id, zeby zadna faktura nie przepadla.
// Pusta odpowiedz HTTP 200 z ktoregokolwiek endpointu NIE konczy pobierania —
// idziemy dalej do kolejnych sciezek (to byl bug przed 05-04).
// period=more + date_from filtruje po stronie API, wiec paginacja konczy sie naturalnie.
$baseQuery = $this -> buildDateRangeQuery( $startDate, $page );
$attempts = [
[ 'path' => '/invoices.json', 'query' => array_merge( $baseQuery, [ 'income' => 'no' ] ) ],
[ 'path' => '/costs.json', 'query' => $baseQuery ],
[ 'path' => '/expenses.json', 'query' => $baseQuery ]
];
if ( $this -> canUseCurrentMonthPeriod( $startDate ) )
$queries[0]['period'] = 'this_month';
$merged = [];
$seenIds = [];
$hadAnySuccess = false;
$lastError = null;
$paths = [ '/costs.json', '/expenses.json', '/invoices.json' ];
foreach ( $paths as $path )
foreach ( $attempts as $attempt )
{
foreach ( $queries as $query )
try
{
$response = $this -> requestList( $path, $query, true );
if ( $response['ok'] )
return $response['data'];
$response = $this -> requestList( $attempt['path'], $attempt['query'], true );
}
catch ( \Throwable $e )
{
$lastError = $e;
continue;
}
if ( !$response['ok'] )
{
$lastError = new \RuntimeException( 'Blad HTTP dla ' . $attempt['path'] );
continue;
}
$hadAnySuccess = true;
foreach ( $response['data'] as $document )
{
$id = $this -> extractDocumentId( $document );
if ( $id === '' )
{
$merged[] = $document;
continue;
}
if ( isset( $seenIds[ $id ] ) )
continue;
$seenIds[ $id ] = true;
$merged[] = $document;
}
}
throw new \RuntimeException( 'Nie udalo sie pobrac faktur kosztowych z API Fakturowni.' );
if ( !$hadAnySuccess && $lastError !== null )
throw new \RuntimeException( 'Nie udalo sie pobrac faktur kosztowych z API Fakturowni: ' . $lastError -> getMessage() );
return $merged;
}
private function buildDateRangeQuery( $startDate, $page )
{
$query = [
'page' => (int)$page,
'per_page' => $this -> pageLimit
];
if ( is_string( $startDate ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $startDate ) )
{
$query['period'] = 'more';
$query['date_from'] = $startDate;
$query['date_to'] = date( 'Y-m-d' );
}
return $query;
}
private function extractDocumentId( $document )
{
if ( !is_array( $document ) )
return '';
if ( isset( $document['invoice'] ) && is_array( $document['invoice'] ) )
$document = $document['invoice'];
if ( isset( $document['id'] ) && (string)$document['id'] !== '' )
return (string)$document['id'];
return '';
}
public function fetchInvoiceDetails( $invoiceId )
@@ -96,7 +162,7 @@ class FakturowniaApiClient
return $softFail ? [ 'ok' => true, 'data' => $list ] : $list;
}
private function request( $path, $query )
protected function request( $path, $query )
{
$query['api_token'] = $this -> apiToken;
$url = $this -> baseUrl . $path . '?' . http_build_query( $query );
@@ -152,11 +218,4 @@ class FakturowniaApiClient
return array_keys( $value ) === range( 0, count( $value ) - 1 );
}
private function canUseCurrentMonthPeriod( $startDate )
{
if ( !is_string( $startDate ) || !preg_match( '/^\d{4}-\d{2}-\d{2}$/', $startDate ) )
return false;
return $startDate === date( 'Y-m-01' );
}
}

View File

@@ -48,6 +48,19 @@ class FakturowniaImportRepository
) ENGINE=InnoDB DEFAULT CHARSET=utf8'
);
$this -> mdb -> query(
'CREATE TABLE IF NOT EXISTS `fakturownia_skipped_positions` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`external_id` VARCHAR(64) NOT NULL,
`document_type` VARCHAR(32) NOT NULL,
`external_item_key` VARCHAR(191) NOT NULL,
`item_name` VARCHAR(255) NOT NULL,
`created_at` DATETIME NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_doc_item` (`external_id`, `document_type`, `external_item_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8'
);
$this -> mdb -> query(
'CREATE TABLE IF NOT EXISTS `fakturownia_imported_documents` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
@@ -168,6 +181,89 @@ class FakturowniaImportRepository
$this -> resolveQueueItem( 'item', $externalItemKey );
}
public function markDocumentPositionSkipped( $externalId, $documentType, $externalItemKey, $itemName )
{
$this -> ensureTables();
$existing = $this -> mdb -> get( 'fakturownia_skipped_positions', 'id', [
'AND' => [
'external_id' => (string)$externalId,
'document_type' => (string)$documentType,
'external_item_key' => (string)$externalItemKey
]
] );
if ( $existing )
return;
$this -> mdb -> insert( 'fakturownia_skipped_positions', [
'external_id' => (string)$externalId,
'document_type' => (string)$documentType,
'external_item_key' => (string)$externalItemKey,
'item_name' => (string)$itemName,
'created_at' => date( 'Y-m-d H:i:s' )
] );
}
public function isDocumentPositionSkipped( $externalId, $documentType, $externalItemKey )
{
$this -> ensureTables();
return (bool)$this -> mdb -> has( 'fakturownia_skipped_positions', [
'AND' => [
'external_id' => (string)$externalId,
'document_type' => (string)$documentType,
'external_item_key' => (string)$externalItemKey
]
] );
}
public function removeOccurrenceFromItemQueue( $externalItemKey, $externalId )
{
$this -> ensureTables();
$row = $this -> mdb -> get( 'fakturownia_unmapped_queue', '*', [
'AND' => [
'queue_type' => 'item',
'external_key' => (string)$externalItemKey
]
] );
if ( !$row )
return;
$payload = [];
if ( isset( $row['payload_json'] ) && $row['payload_json'] )
{
$decoded = json_decode( $row['payload_json'], true );
if ( is_array( $decoded ) )
$payload = $decoded;
}
$occurrences = [];
if ( isset( $payload['occurrences'] ) && is_array( $payload['occurrences'] ) )
{
foreach ( $payload['occurrences'] as $occ )
{
if ( !is_array( $occ ) )
continue;
if ( (string)( $occ['document_id'] ?? '' ) === (string)$externalId )
continue;
$occurrences[] = $occ;
}
}
if ( empty( $occurrences ) )
{
$this -> mdb -> delete( 'fakturownia_unmapped_queue', [ 'id' => (int)$row['id'] ] );
return;
}
$payload['occurrences'] = $occurrences;
$this -> mdb -> update( 'fakturownia_unmapped_queue', [
'payload_json' => json_encode( $payload, JSON_UNESCAPED_UNICODE ),
'hits' => count( $occurrences ),
'last_seen_at' => date( 'Y-m-d H:i:s' )
], [ 'id' => (int)$row['id'] ] );
}
public function isDocumentImported( $externalDocumentKey )
{
$this -> ensureTables();
@@ -219,6 +315,64 @@ class FakturowniaImportRepository
] );
$now = date( 'Y-m-d H:i:s' );
// Dla queue_type='item' agregujemy occurrences per (document_id, item_key).
// Kazde wystapienie pozycji na innej fakturze to osobny wpis w payload.occurrences,
// zeby UI mogl pokazac liste i pozwolic na pomijanie per konkretna faktura.
if ( $queueType === 'item' )
{
$occurrence = $payload;
$payloadToStore = [ 'occurrences' => [ $occurrence ] ];
if ( $existing )
{
$existingPayload = [];
if ( isset( $existing['payload_json'] ) && $existing['payload_json'] )
{
$decoded = json_decode( $existing['payload_json'], true );
if ( is_array( $decoded ) )
$existingPayload = $decoded;
}
$occurrences = ( isset( $existingPayload['occurrences'] ) && is_array( $existingPayload['occurrences'] ) )
? $existingPayload['occurrences']
: [];
// Dedup po document_id — powtorny import nadpisuje istniejace wystapienie.
$occurrences = array_values( array_filter( $occurrences, function( $occ ) use ( $occurrence )
{
if ( !is_array( $occ ) )
return false;
return (string)( $occ['document_id'] ?? '' ) !== (string)( $occurrence['document_id'] ?? '' );
} ) );
$occurrences[] = $occurrence;
$payloadToStore = [ 'occurrences' => $occurrences ];
$this -> mdb -> update( 'fakturownia_unmapped_queue', [
'external_name' => $externalName,
'payload_json' => json_encode( $payloadToStore, JSON_UNESCAPED_UNICODE ),
'hits' => count( $occurrences ),
'resolved' => 0,
'last_seen_at' => $now
], [ 'id' => (int)$existing['id'] ] );
return;
}
$this -> mdb -> insert( 'fakturownia_unmapped_queue', [
'queue_type' => $queueType,
'external_key' => $externalKey,
'external_name' => $externalName,
'payload_json' => json_encode( $payloadToStore, JSON_UNESCAPED_UNICODE ),
'hits' => 1,
'resolved' => 0,
'first_seen_at' => $now,
'last_seen_at' => $now
] );
return;
}
// Pozostale queue_type (client) — zachowanie bez zmian.
$payloadJson = json_encode( $payload, JSON_UNESCAPED_UNICODE );
if ( $existing )

View File

@@ -8,6 +8,7 @@ class FakturowniaInvoiceImporter
private $apiClient;
private $startDate;
private $pageLimit = 100;
private $ownTaxNo = '';
public function __construct( $mdb = null )
{
@@ -37,6 +38,7 @@ class FakturowniaInvoiceImporter
$config['page_limit']
);
$this -> pageLimit = (int)$config['page_limit'];
$this -> ownTaxNo = (string)$config['own_tax_no'];
$summary = [
'imported' => 0,
@@ -85,13 +87,8 @@ class FakturowniaInvoiceImporter
if ( !is_array( $documents ) || empty( $documents ) )
break;
$hasRelevantDateInPage = false;
foreach ( $documents as $document )
{
if ( $this -> isDateRelevantForImport( $document ) )
$hasRelevantDateInPage = true;
$result = $this -> processSingleDocument( $document, $documentType );
$summary[ $result ]++;
}
@@ -99,11 +96,9 @@ class FakturowniaInvoiceImporter
if ( count( $documents ) < $this -> pageLimit )
break;
// API zwraca dokumenty malejaco po czasie. Gdy cala strona jest starsza niz startDate,
// kolejne strony tez beda starsze i nie ma sensu pobierac dalej.
if ( !$hasRelevantDateInPage )
break;
// Nie przerywamy petli na podstawie dat w liscie — API moze sortowac po updated_at/created_at
// zamiast issue_date, co powodowalo gubienie faktur z wcześniejsza data wystawienia.
// Filtr "za stare" dziala per-dokument w processSingleDocument (strtotime(date) < startDate).
$page++;
if ( $page > 100 )
break;
@@ -139,18 +134,39 @@ class FakturowniaInvoiceImporter
if ( !$clientMap )
{
$positionNames = [];
foreach ( $document['positions'] as $pos )
{
$name = trim( (string)( $pos['name'] ?? '' ) );
if ( $name !== '' )
$positionNames[] = $name;
}
$this -> repo -> queueUnmapped( 'client', $document['client_key'], $document['client_name'], [
'document_id' => $document['external_id'],
'document_number' => $document['number'],
'document_type' => $documentType,
'tax_no' => $document['client_tax_no']
'tax_no' => $document['client_tax_no'],
'positions' => $positionNames
] );
return 'unmapped';
}
$resolvedPositions = [];
$skippedPositions = [];
foreach ( $document['positions'] as $position )
{
// Per-dokument skip: uzytkownik oznaczyl konkretna pozycje na konkretnej fakturze jako pomijana.
// Pomijanie dzieje sie ZANIM sprawdzamy mapowanie, zeby pominieta pozycja nie blokowala importu.
if ( $this -> repo -> isDocumentPositionSkipped( $document['external_id'], $documentType, $position['item_key'] ) )
{
$skippedPositions[] = [
'item_key' => $position['item_key'],
'name' => $position['name']
];
continue;
}
$itemMap = $this -> repo -> getItemMapping( $position['item_key'] );
if ( !$itemMap )
{
@@ -159,7 +175,8 @@ class FakturowniaInvoiceImporter
'document_number' => $document['number'],
'document_type' => $documentType,
'buyer_name' => $document['buyer_name'],
'seller_name' => $document['seller_name']
'seller_name' => $document['seller_name'],
'position_name' => $position['name']
] );
return 'unmapped';
}
@@ -175,7 +192,9 @@ class FakturowniaInvoiceImporter
];
}
if ( empty( $resolvedPositions ) )
// Dokument bez zadnych pozycji do przetworzenia (ani resolved, ani skip) → nic nie zapisujemy.
// Nie oznaczamy jako imported, zeby nie zablokowal sie na zawsze.
if ( empty( $resolvedPositions ) && empty( $skippedPositions ) )
return 'skipped';
$operationIds = [];
@@ -206,7 +225,8 @@ class FakturowniaInvoiceImporter
$operationIds,
[
'number' => $document['number'],
'client_name' => $document['client_name']
'client_name' => $document['client_name'],
'skipped_positions' => $skippedPositions
]
);
@@ -261,22 +281,6 @@ class FakturowniaInvoiceImporter
return false;
}
private function isDateRelevantForImport( $rawDocument )
{
if ( isset( $rawDocument['invoice'] ) && is_array( $rawDocument['invoice'] ) )
$rawDocument = $rawDocument['invoice'];
if ( !is_array( $rawDocument ) )
return false;
$date = (string)( $rawDocument['issue_date'] ?? $rawDocument['sell_date'] ?? $rawDocument['created_at'] ?? '' );
$date = substr( $date, 0, 10 );
if ( !$date )
return false;
return strtotime( $date ) >= strtotime( $this -> startDate );
}
private function normalizeDocument( $rawDocument, $documentType )
{
if ( isset( $rawDocument['invoice'] ) && is_array( $rawDocument['invoice'] ) )
@@ -300,8 +304,22 @@ class FakturowniaInvoiceImporter
}
else
{
$clientName = (string)( $rawDocument['seller_name'] ?? $rawDocument['client_name'] ?? 'Nieznany kontrahent' );
$clientTaxNo = (string)( $rawDocument['seller_tax_no'] ?? $rawDocument['tax_no'] ?? '' );
// Dla kosztow kontrahentem jest "druga strona" — ta, ktorej NIP != naszego.
// Fakturownia dla wydatkow pobranych z KSeF (approval_status='received') odwraca role:
// seller_* to dane wlasnej firmy, buyer_* to prawdziwy dostawca. Bez tej heurystyki
// koszty z KSeF trafialyby do kolejki unmapped z wlasnym NIP-em jako klucz klienta.
$sellerTaxNo = (string)( $rawDocument['seller_tax_no'] ?? '' );
if ( $this -> taxNoEqualsOwn( $sellerTaxNo ) )
{
$clientName = (string)( $rawDocument['buyer_name'] ?? $rawDocument['client_name'] ?? 'Nieznany kontrahent' );
$clientTaxNo = (string)( $rawDocument['buyer_tax_no'] ?? $rawDocument['tax_no'] ?? '' );
}
else
{
$clientName = (string)( $rawDocument['seller_name'] ?? $rawDocument['client_name'] ?? 'Nieznany kontrahent' );
$clientTaxNo = $sellerTaxNo !== '' ? $sellerTaxNo : (string)( $rawDocument['tax_no'] ?? '' );
}
}
$positions = [];
@@ -436,6 +454,18 @@ class FakturowniaInvoiceImporter
return $normalizedTaxNo;
}
private function taxNoEqualsOwn( $taxNo )
{
if ( $this -> ownTaxNo === '' )
return false;
$normalized = $this -> normalizeTaxNo( $taxNo );
if ( $normalized === '' )
return false;
return $normalized === $this -> normalizeTaxNo( $this -> ownTaxNo );
}
private function buildItemKey( $rawPosition, $name )
{
if ( isset( $rawPosition['product_id'] ) && (string)$rawPosition['product_id'] !== '' )
@@ -483,6 +513,7 @@ class FakturowniaInvoiceImporter
$token = trim( (string)\Env::get( 'FAKTUROWNIA_API_TOKEN', '' ) );
$startDate = trim( (string)\Env::get( 'FAKTUROWNIA_START_DATE', '' ) );
$pageLimit = (int)\Env::get( 'FAKTUROWNIA_PAGE_LIMIT', 100 );
$ownTaxNo = trim( (string)\Env::get( 'FAKTUROWNIA_OWN_TAX_NO', '' ) );
if ( $domain === '' || $token === '' || $startDate === '' )
return [ 'status' => 'error', 'ok' => false, 'msg' => 'Import Fakturownia: brak konfiguracji w .env.' ];
@@ -498,7 +529,8 @@ class FakturowniaInvoiceImporter
'api_url' => rtrim( $domain, '/' ),
'token' => $token,
'start_date' => $startDate,
'page_limit' => $pageLimit > 0 ? $pageLimit : 100
'page_limit' => $pageLimit > 0 ? $pageLimit : 100,
'own_tax_no' => $ownTaxNo
];
}