From f4d7aacf942399d3a6c02613d4845a31011c8d01 Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 01:36:35 -0600 Subject: [PATCH 01/15] feat(sponsors): add company name matcher for sponsor csv import --- .../Imp/SponsorImport/CompanyNameMatcher.php | 108 ++++++++++++++++++ .../SponsorImport/CompanyNameMatcherTest.php | 68 +++++++++++ 2 files changed, 176 insertions(+) create mode 100644 app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php create mode 100644 tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php new file mode 100644 index 000000000..cb438ceaf --- /dev/null +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -0,0 +1,108 @@ + exact key => lowest-id company + */ + private $exact = []; + + /** + * @var array> exact key => every id, ascending + */ + private $exact_ids = []; + + /** + * @var array> normalized key => companies + */ + private $by_key = []; + + /** + * @param list $companies + */ + public function __construct(array $companies) + { + foreach ($companies as $company) { + $name = $company['name'] ?? null; + if (!is_string($name) || trim($name) === '') continue; + $id = (int)$company['id']; + + $exact_key = self::exactKey($name); + $this->exact_ids[$exact_key][] = $id; + if (!isset($this->exact[$exact_key]) || $id < $this->exact[$exact_key]['id']) { + $this->exact[$exact_key] = ['id' => $id, 'name' => $name]; + } + + $key = self::key($name); + if ($key === '') continue; + $this->by_key[$key][] = ['id' => $id, 'name' => $name]; + } + foreach ($this->exact_ids as &$ids) { + sort($ids); + } + } + + public static function key(string $name): string + { + $s = \Normalizer::normalize($name, \Normalizer::FORM_C); + if ($s === false) $s = $name; + $s = mb_strtolower($s); + $s = trim(preg_replace('/[^\p{L}\p{N}]+/u', ' ', $s)); + if ($s === '') return ''; + $words = explode(' ', $s); + while (count($words) > 1 && in_array(end($words), self::LegalSuffixes, true)) { + array_pop($words); + } + return implode(' ', $words); + } + + private static function exactKey(string $name): string + { + $s = \Normalizer::normalize($name, \Normalizer::FORM_C); + if ($s === false) $s = $name; + return mb_strtolower(trim($s)); + } + + public function resolve(string $name): array + { + $exact_key = self::exactKey($name); + if ($exact_key !== '' && isset($this->exact[$exact_key])) { + $hit = $this->exact[$exact_key]; + return ['match' => 'exact', 'id' => $hit['id'], 'name' => $hit['name'], 'ids' => $this->exact_ids[$exact_key]]; + } + + $key = self::key($name); + if ($key === '' || !isset($this->by_key[$key])) return ['match' => 'none']; + + $candidates = $this->by_key[$key]; + if (count($candidates) === 1) { + return ['match' => 'normalized', 'id' => $candidates[0]['id'], 'name' => $candidates[0]['name']]; + } + $names = array_column($candidates, 'name'); + usort($names, 'strcasecmp'); + return ['match' => 'ambiguous', 'candidates' => $names]; + } +} diff --git a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php new file mode 100644 index 000000000..f3372c4cf --- /dev/null +++ b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php @@ -0,0 +1,68 @@ +assertSame('super micro computer', CompanyNameMatcher::key('Super Micro Computer, Inc.')); + $this->assertSame('foo', CompanyNameMatcher::key('Foo Co., Ltd.')); + $this->assertSame('te connectivity', CompanyNameMatcher::key(' TE Connectivity Corporation ')); + $this->assertSame('co', CompanyNameMatcher::key('Co')); // never strips the last word + $this->assertSame('', CompanyNameMatcher::key(' -- ')); + $this->assertSame('münchen', CompanyNameMatcher::key('München GmbH')); + } + + public function testExactWinsOverNormalizedAndLowestIdBreaksTies(): void + { + $m = new CompanyNameMatcher([ + ['id' => 30, 'name' => 'Microsoft'], ['id' => 10, 'name' => 'MICROSOFT'], + ['id' => 20, 'name' => 'Microsoft Corporation'], + ]); + $this->assertSame(['match' => 'exact', 'id' => 10, 'name' => 'MICROSOFT', 'ids' => [10, 30]], $m->resolve(' microsoft ')); + } + + public function testNfcAndNullNames(): void + { + $m = new CompanyNameMatcher([['id' => 1, 'name' => "Cafe\u{0301} Corp"], ['id' => 2, 'name' => null], ['id' => 3, 'name' => ' ']]); + $this->assertSame(1, $m->resolve("Café Corp")['id']); // precomposed input matches decomposed stored name (exact) + $this->assertSame(['match' => 'none'], $m->resolve('')); + } + + public function testNormalizedSingleCandidate(): void + { + $m = new CompanyNameMatcher([['id' => 5, 'name' => 'Wiwynn Corporation']]); + $this->assertSame(['match' => 'normalized', 'id' => 5, 'name' => 'Wiwynn Corporation'], $m->resolve('Wiwynn')); + } + + public function testNormalizedSeveralCandidatesIsAmbiguousSorted(): void + { + $m = new CompanyNameMatcher([['id' => 1, 'name' => 'Arm Ltd.'], ['id' => 2, 'name' => 'arm, inc']]); + $this->assertSame(['match' => 'ambiguous', 'candidates' => ['Arm Ltd.', 'arm, inc']], $m->resolve('Arm Corp')); + } + + public function testNoMatchAndEmptyKeyNeverNormalizes(): void + { + $m = new CompanyNameMatcher([['id' => 1, 'name' => '--']]); + $this->assertSame(['match' => 'none'], $m->resolve('Acme')); + $this->assertSame(['match' => 'none'], $m->resolve('!!')); // key '' must not match '--' + } +} From acabea1b0089ed06886935d722111f7eceec830f Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 01:39:23 -0600 Subject: [PATCH 02/15] fix(sponsors): dedupe matcher candidates by id and tighten matcher tests --- .../Imp/SponsorImport/CompanyNameMatcher.php | 6 +++++- .../SponsorImport/CompanyNameMatcherTest.php | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php index cb438ceaf..14bacf78f 100644 --- a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -45,10 +45,13 @@ final class CompanyNameMatcher */ public function __construct(array $companies) { + $seen = []; foreach ($companies as $company) { $name = $company['name'] ?? null; if (!is_string($name) || trim($name) === '') continue; $id = (int)$company['id']; + if (isset($seen[$id])) continue; + $seen[$id] = true; $exact_key = self::exactKey($name); $this->exact_ids[$exact_key][] = $id; @@ -60,8 +63,9 @@ public function __construct(array $companies) if ($key === '') continue; $this->by_key[$key][] = ['id' => $id, 'name' => $name]; } - foreach ($this->exact_ids as &$ids) { + foreach ($this->exact_ids as $k => $ids) { sort($ids); + $this->exact_ids[$k] = $ids; } } diff --git a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php index f3372c4cf..a33fe5e82 100644 --- a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php +++ b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php @@ -29,6 +29,7 @@ public function testKeyStripsPunctuationAndRepeatedSuffixes(): void $this->assertSame('co', CompanyNameMatcher::key('Co')); // never strips the last word $this->assertSame('', CompanyNameMatcher::key(' -- ')); $this->assertSame('münchen', CompanyNameMatcher::key('München GmbH')); + $this->assertSame('münchen', CompanyNameMatcher::key('MÜNCHEN GMBH')); } public function testExactWinsOverNormalizedAndLowestIdBreaksTies(): void @@ -43,7 +44,11 @@ public function testExactWinsOverNormalizedAndLowestIdBreaksTies(): void public function testNfcAndNullNames(): void { $m = new CompanyNameMatcher([['id' => 1, 'name' => "Cafe\u{0301} Corp"], ['id' => 2, 'name' => null], ['id' => 3, 'name' => ' ']]); - $this->assertSame(1, $m->resolve("Café Corp")['id']); // precomposed input matches decomposed stored name (exact) + // precomposed input matches decomposed stored name (exact) + $this->assertSame(['match' => 'exact', 'id' => 1, 'name' => "Cafe\u{0301} Corp", 'ids' => [1]], $m->resolve("Café Corp")); + // and the reverse direction + $r = new CompanyNameMatcher([['id' => 4, 'name' => "Café Corp"]]); + $this->assertSame(['match' => 'exact', 'id' => 4, 'name' => "Café Corp", 'ids' => [4]], $r->resolve("Cafe\u{0301} Corp")); $this->assertSame(['match' => 'none'], $m->resolve('')); } @@ -55,7 +60,7 @@ public function testNormalizedSingleCandidate(): void public function testNormalizedSeveralCandidatesIsAmbiguousSorted(): void { - $m = new CompanyNameMatcher([['id' => 1, 'name' => 'Arm Ltd.'], ['id' => 2, 'name' => 'arm, inc']]); + $m = new CompanyNameMatcher([['id' => 2, 'name' => 'arm, inc'], ['id' => 1, 'name' => 'Arm Ltd.']]); $this->assertSame(['match' => 'ambiguous', 'candidates' => ['Arm Ltd.', 'arm, inc']], $m->resolve('Arm Corp')); } @@ -65,4 +70,11 @@ public function testNoMatchAndEmptyKeyNeverNormalizes(): void $this->assertSame(['match' => 'none'], $m->resolve('Acme')); $this->assertSame(['match' => 'none'], $m->resolve('!!')); // key '' must not match '--' } + + public function testDuplicateInputRowsAreDedupedById(): void + { + $m = new CompanyNameMatcher([['id' => 5, 'name' => 'Wiwynn Corporation'], ['id' => 5, 'name' => 'Wiwynn Corporation']]); + $this->assertSame(['match' => 'normalized', 'id' => 5, 'name' => 'Wiwynn Corporation'], $m->resolve('Wiwynn')); + $this->assertSame(['match' => 'exact', 'id' => 5, 'name' => 'Wiwynn Corporation', 'ids' => [5]], $m->resolve('wiwynn corporation')); + } } From b6bdee5970de8ec0de304cfe464ec4f462688b4d Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 01:42:07 -0600 Subject: [PATCH 03/15] feat(sponsors): plan sponsor csv import rows --- app/Services/Model/ISummitSponsorService.php | 5 + .../SponsorImport/SponsorImportPlanner.php | 218 ++++++++++++++++++ .../SponsorImportPlannerTest.php | 197 ++++++++++++++++ 3 files changed, 420 insertions(+) create mode 100644 app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php create mode 100644 tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php diff --git a/app/Services/Model/ISummitSponsorService.php b/app/Services/Model/ISummitSponsorService.php index 5ee65b688..922b0909f 100644 --- a/app/Services/Model/ISummitSponsorService.php +++ b/app/Services/Model/ISummitSponsorService.php @@ -34,6 +34,11 @@ */ interface ISummitSponsorService { + /** + * Separates tier names within the tier cell of a sponsors CSV import. + */ + const ImportTierSeparator = '|'; + /** * @param Summit $summit * @param array $payload diff --git a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php new file mode 100644 index 000000000..bce17cb32 --- /dev/null +++ b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php @@ -0,0 +1,218 @@ + lowercase tier name => tier + */ + private $tiers; + + /** + * @var array company id => true + */ + private $sponsor_company_ids; + + /** + * @param CompanyNameMatcher $matcher + * @param array $tiers + * @param list $sponsorCompanyIds + */ + public function __construct(CompanyNameMatcher $matcher, array $tiers, array $sponsorCompanyIds) + { + $this->matcher = $matcher; + $this->tiers = $tiers; + $this->sponsor_company_ids = array_fill_keys(array_map('intval', $sponsorCompanyIds), true); + } + + /** + * @param list $rows + * @return list + */ + public function plan(array $rows): array + { + $planned = []; + $seen = []; // identity => row number, non-error rows only + foreach ($rows as $input) { + $row = $this->newRow($input); + $company_name = trim($input['company']); + + if ($company_name === '') { + $planned[] = $this->fail($row, 'Company is required.'); + continue; + } + + $tier_names = []; + foreach (explode(ISummitSponsorService::ImportTierSeparator, $input['tier']) as $segment) { + $segment = trim($segment); + if ($segment !== '') $tier_names[] = $segment; + } + if (count($tier_names) === 0) { + $planned[] = $this->fail($row, 'Tier is required.'); + continue; + } + + $tier_ids = []; + $tier_labels = []; + $unknown = null; + foreach ($tier_names as $name) { + $tier = $this->tiers[mb_strtolower($name)] ?? null; + if ($tier === null) { + $unknown = $name; + break; + } + if (in_array($tier['id'], $tier_ids, true)) continue; + $tier_ids[] = $tier['id']; + $tier_labels[] = $tier['name']; + } + if ($unknown !== null) { + $available = implode(', ', array_column($this->tiers, 'name')); + $planned[] = $this->fail($row, sprintf('Unknown tier "%s". This show\'s tiers: %s.', $unknown, $available)); + continue; + } + $row['tiers'] = $tier_labels; + $row['tier_ids'] = $tier_ids; + + $match = $this->matcher->resolve($company_name); + if ($match['match'] === 'ambiguous') { + $row['candidates'] = $match['candidates']; + $planned[] = $this->fail($row, sprintf( + 'Several companies match "%s". Use the exact name of one of: %s', + $company_name, implode(', ', $match['candidates']))); + continue; + } + + if ($match['match'] === 'none') { + $row['company'] = ['id' => null, 'name' => $company_name, 'match' => 'new']; + $key = CompanyNameMatcher::key($company_name); + $identity = $key !== '' ? 'key:' . $key : 'name:' . mb_strtolower($company_name); + $is_sponsor = false; + } else { + $id = $match['id']; + if ($match['match'] === 'exact') { + foreach ($match['ids'] as $candidate_id) { + if (isset($this->sponsor_company_ids[$candidate_id])) { + $id = $candidate_id; + break; + } + } + } + $row['company'] = ['id' => $id, 'name' => $match['name'], 'match' => $match['match']]; + $identity = 'id:' . $id; + $is_sponsor = isset($this->sponsor_company_ids[$id]); + } + + if ($is_sponsor) { + $row['action'] = 'skip_existing_sponsor'; + } elseif (isset($seen[$identity])) { + $row['action'] = 'skip_duplicate'; + $row['duplicate_of_row'] = $seen[$identity]; + } else { + $row['action'] = 'create'; + } + $seen[$identity] = $seen[$identity] ?? $row['row']; + $planned[] = $row; + } + return $planned; + } + + /** + * @param list $rows + * @param bool $dryRun + * @return array{dry_run:bool,summary:array} + */ + public static function summarize(array $rows, bool $dryRun): array + { + $summary = [ + 'total' => count($rows), + 'sponsors_created' => 0, + 'companies_created' => 0, + 'skipped' => 0, + 'errors' => 0, + 'not_attempted' => 0, + ]; + foreach ($rows as $row) { + $action = $row['action']; + if ($action === 'create') $summary['sponsors_created']++; + elseif ($action === 'skip_existing_sponsor' || $action === 'skip_duplicate') $summary['skipped']++; + elseif ($action === 'error') $summary['errors']++; + elseif ($action === 'not_attempted') $summary['not_attempted']++; + + // a company created before its sponsor failed still counts + if (($row['company']['match'] ?? null) === 'new' && + ($action === 'create' || ($row['company']['id'] ?? null) !== null)) { + $summary['companies_created']++; + } + } + return ['dry_run' => $dryRun, 'summary' => $summary]; + } + + /** + * Marks row $index with $action/$message and turns every later planned create into not_attempted. + * @param list $rows + * @param int $index + * @param string $message + * @param string $action + * @return list + */ + public static function markStopped(array $rows, int $index, string $message, string $action = 'error'): array + { + $rows[$index]['action'] = $action; + $rows[$index]['error'] = $message; + $count = count($rows); + for ($i = $index + 1; $i < $count; $i++) { + if ($rows[$i]['action'] === 'create') $rows[$i]['action'] = 'not_attempted'; + } + return $rows; + } + + private function newRow(array $input): array + { + return [ + 'row' => $input['row'], + 'company_input' => $input['company'], + 'tier_input' => $input['tier'], + 'action' => 'create', + 'company' => null, + 'tiers' => [], + 'sponsor_id' => null, + 'duplicate_of_row' => null, + 'candidates' => [], + 'error' => null, + 'tier_ids' => [], + ]; + } + + private function fail(array $row, string $message): array + { + $row['action'] = 'error'; + $row['error'] = $message; + return $row; + } +} diff --git a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php new file mode 100644 index 000000000..35f7ad003 --- /dev/null +++ b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php @@ -0,0 +1,197 @@ + 7, 'name' => 'Acme'], + ['id' => 12, 'name' => 'NVIDIA'], + ['id' => 20, 'name' => 'Arm Ltd.'], + ['id' => 21, 'name' => 'arm, inc'], + ['id' => 10, 'name' => 'Dup Co'], + ['id' => 99, 'name' => 'Dup Co'], + ['id' => 50, 'name' => 'Existing Sponsor'], + ]); + $tiers = ['gold' => ['id' => 1, 'name' => 'Gold'], 'silver' => ['id' => 2, 'name' => 'Silver']]; + return new SponsorImportPlanner($matcher, $tiers, [99, 50]); + } + + private function row(int $n, string $company, string $tier): array + { + return ['row' => $n, 'company' => $company, 'tier' => $tier]; + } + + public function testCreatesWithExactMatchAndCanonicalTierNames(): void + { + $out = $this->planner()->plan([$this->row(2, 'acme', 'gold|SILVER')]); + $r = $out[0]; + $this->assertSame('create', $r['action']); + $this->assertSame(['id' => 7, 'name' => 'Acme', 'match' => 'exact'], $r['company']); + $this->assertSame(['Gold', 'Silver'], $r['tiers']); + $this->assertSame([1, 2], $r['tier_ids']); + $this->assertSame(2, $r['row']); + $this->assertSame('acme', $r['company_input']); + $this->assertSame('gold|SILVER', $r['tier_input']); + $this->assertNull($r['sponsor_id']); + $this->assertNull($r['duplicate_of_row']); + $this->assertSame([], $r['candidates']); + $this->assertNull($r['error']); + } + + public function testMissingCompanyOrTierIsError(): void + { + $out = $this->planner()->plan([$this->row(2, '', 'Gold'), $this->row(3, 'Acme', '')]); + $this->assertSame('error', $out[0]['action']); + $this->assertSame('Company is required.', $out[0]['error']); + $this->assertNull($out[0]['company']); + $this->assertSame('error', $out[1]['action']); + $this->assertSame('Tier is required.', $out[1]['error']); + } + + public function testUnknownTierListsAvailableTiers(): void + { + $out = $this->planner()->plan([$this->row(2, 'Acme', 'Platnum')]); + $this->assertSame('error', $out[0]['action']); + $this->assertSame('Unknown tier "Platnum". This show\'s tiers: Gold, Silver.', $out[0]['error']); + } + + public function testAmbiguousIsErrorWithCandidates(): void + { + $out = $this->planner()->plan([$this->row(2, 'Arm Corp', 'Gold')]); + $this->assertSame('error', $out[0]['action']); + $this->assertNull($out[0]['company']); + $this->assertSame(['Arm Ltd.', 'arm, inc'], $out[0]['candidates']); + $this->assertSame('Several companies match "Arm Corp". Use the exact name of one of: Arm Ltd., arm, inc', $out[0]['error']); + } + + public function testExistingSponsorIsSkipped(): void + { + $out = $this->planner()->plan([$this->row(2, 'Existing Sponsor', 'Gold')]); + $this->assertSame('skip_existing_sponsor', $out[0]['action']); + $this->assertSame(50, $out[0]['company']['id']); + } + + public function testDuplicateBySpellingWithinFile(): void + { + $out = $this->planner()->plan([$this->row(2, 'NVIDIA', 'Gold'), $this->row(9, 'Nvidia Corp.', 'Silver')]); + $this->assertSame('create', $out[0]['action']); + $this->assertSame(12, $out[0]['company']['id']); + $this->assertSame('skip_duplicate', $out[1]['action']); + $this->assertSame(2, $out[1]['duplicate_of_row']); + $this->assertSame(12, $out[1]['company']['id']); + $this->assertSame('normalized', $out[1]['company']['match']); + } + + public function testNewCompanyDuplicateDoesNotCreateTwice(): void + { + $out = $this->planner()->plan([$this->row(2, 'Acme Robotics Inc', 'Gold'), $this->row(3, 'ACME Robotics', 'Gold')]); + $this->assertSame('create', $out[0]['action']); + $this->assertSame(['id' => null, 'name' => 'Acme Robotics Inc', 'match' => 'new'], $out[0]['company']); + $this->assertSame('skip_duplicate', $out[1]['action']); + $this->assertSame(2, $out[1]['duplicate_of_row']); + } + + public function testErrorRowDoesNotReserveCompany(): void + { + $out = $this->planner()->plan([$this->row(2, 'Acme', 'Platnum'), $this->row(3, 'Acme', 'Gold')]); + $this->assertSame('error', $out[0]['action']); + $this->assertSame('create', $out[1]['action']); + $this->assertNull($out[1]['duplicate_of_row']); + } + + public function testTierCellDedupesAndDropsEmptySegments(): void + { + $out = $this->planner()->plan([$this->row(2, 'Acme', 'Gold| |gold'), $this->row(3, 'NVIDIA', '||')]); + $this->assertSame('create', $out[0]['action']); + $this->assertSame(['Gold'], $out[0]['tiers']); + $this->assertSame([1], $out[0]['tier_ids']); + $this->assertSame('error', $out[1]['action']); + $this->assertSame('Tier is required.', $out[1]['error']); + } + + public function testExactDuplicatePrefersCompanyAlreadySponsoring(): void + { + $out = $this->planner()->plan([$this->row(2, 'Dup Co', 'Gold')]); + $this->assertSame('skip_existing_sponsor', $out[0]['action']); + $this->assertSame(99, $out[0]['company']['id']); + $this->assertSame('exact', $out[0]['company']['match']); + } + + public function testSummarizeCountsEachAction(): void + { + $rows = $this->planner()->plan([ + $this->row(2, 'Acme', 'Gold'), + $this->row(3, 'Brand New Co Labs', 'Gold'), + $this->row(4, 'Existing Sponsor', 'Gold'), + $this->row(5, 'acme', 'Gold'), + $this->row(6, '', 'Gold'), + ]); + $this->assertSame( + ['total' => 5, 'sponsors_created' => 2, 'companies_created' => 1, 'skipped' => 2, 'errors' => 1, 'not_attempted' => 0], + SponsorImportPlanner::summarize($rows, true)['summary'] + ); + $this->assertTrue(SponsorImportPlanner::summarize($rows, true)['dry_run']); + $this->assertFalse(SponsorImportPlanner::summarize($rows, false)['dry_run']); + } + + public function testMarkStoppedErrorsRowAndMarksLaterCreatesNotAttempted(): void + { + $rows = [ + ['row' => 2, 'action' => 'create', 'error' => null], + ['row' => 3, 'action' => 'create', 'error' => null], + ['row' => 4, 'action' => 'error', 'error' => 'Tier is required.'], + ['row' => 5, 'action' => 'create', 'error' => null], + ]; + $out = SponsorImportPlanner::markStopped($rows, 1, 'boom'); + $this->assertSame(['create', 'error', 'error', 'not_attempted'], array_column($out, 'action')); + $this->assertSame('boom', $out[1]['error']); + $this->assertNull($out[0]['error']); + $this->assertSame('Tier is required.', $out[2]['error']); + $this->assertNull($out[3]['error']); + } + + public function testMarkStoppedAsNotAttemptedForConnectionReset(): void + { + $rows = [ + ['row' => 2, 'action' => 'create', 'error' => null], + ['row' => 3, 'action' => 'create', 'error' => null], + ]; + $out = SponsorImportPlanner::markStopped($rows, 0, 'reset', 'not_attempted'); + $this->assertSame(['not_attempted', 'not_attempted'], array_column($out, 'action')); + $this->assertSame('reset', $out[0]['error']); + } + + public function testSummarizeCountsCompanyCreatedBeforeFailedSponsor(): void + { + $rows = [ + ['row' => 2, 'action' => 'error', 'company' => ['id' => 301, 'name' => 'X', 'match' => 'new']], + ['row' => 3, 'action' => 'not_attempted', 'company' => ['id' => null, 'name' => 'Y', 'match' => 'new']], + ]; + $s = SponsorImportPlanner::summarize($rows, false)['summary']; + $this->assertSame(1, $s['companies_created']); + $this->assertSame(1, $s['errors']); + $this->assertSame(1, $s['not_attempted']); + $this->assertSame(0, $s['sponsors_created']); + } +} From 6d7a50e01887990cc643b77cae62c8690d6bbd1a Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 01:45:55 -0600 Subject: [PATCH 04/15] feat(companies): list company ids and names for sponsor import matching --- .../Main/Repositories/ICompanyRepository.php | 5 ++ app/Models/Foundation/Summit/Summit.php | 9 +++ .../Main/DoctrineCompanyRepository.php | 21 +++++- ...DoctrineCompanyRepositoryIdAndNameTest.php | 75 +++++++++++++++++++ 4 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php diff --git a/app/Models/Foundation/Main/Repositories/ICompanyRepository.php b/app/Models/Foundation/Main/Repositories/ICompanyRepository.php index c87d290f2..1cf46c595 100644 --- a/app/Models/Foundation/Main/Repositories/ICompanyRepository.php +++ b/app/Models/Foundation/Main/Repositories/ICompanyRepository.php @@ -19,4 +19,9 @@ interface ICompanyRepository extends IBaseRepository { public function getByName(string $name):?Company; + + /** + * @return array + */ + public function getAllIdAndName(): array; } \ No newline at end of file diff --git a/app/Models/Foundation/Summit/Summit.php b/app/Models/Foundation/Summit/Summit.php index f2a7dfc41..151bc3e11 100644 --- a/app/Models/Foundation/Summit/Summit.php +++ b/app/Models/Foundation/Summit/Summit.php @@ -35,6 +35,7 @@ use Cocur\Slugify\Slugify; use DateTime; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\NoResultException; @@ -4333,6 +4334,14 @@ public function getSummitSponsorshipTypeById(int $id): ?SummitSponsorshipType return $sponsorship === false ? null : $sponsorship; } + /** + * @return Collection + */ + public function getSummitSponsorshipTypes(): Collection + { + return $this->sponsorship_types; + } + /** * @param SponsorshipType $type * @return SummitSponsorshipType|null diff --git a/app/Repositories/Main/DoctrineCompanyRepository.php b/app/Repositories/Main/DoctrineCompanyRepository.php index aa53643be..bbd66acdd 100644 --- a/app/Repositories/Main/DoctrineCompanyRepository.php +++ b/app/Repositories/Main/DoctrineCompanyRepository.php @@ -73,4 +73,23 @@ public function getByName(string $name): ?Company ->getQuery() ->getOneOrNullResult(); } -} \ No newline at end of file + + /** + * Scalar projection, no entity hydration. + * @return array + */ + public function getAllIdAndName(): array + { + $rows = $this->getEntityManager() + ->createQueryBuilder() + ->select("e.id AS id", "e.name AS name") + ->from($this->getBaseEntity(), "e") + ->getQuery() + ->getArrayResult(); + + return array_map( + static fn(array $row): array => ['id' => (int)$row['id'], 'name' => $row['name']], + $rows + ); + } +} diff --git a/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php new file mode 100644 index 000000000..171071bcb --- /dev/null +++ b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php @@ -0,0 +1,75 @@ +em = Registry::getManager(SilverstripeBaseModel::EntityManager); + if (!$this->em->isOpen()) { + $this->em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + } + } + + protected function tearDown(): void + { + foreach ($this->companies as $company) { + $managed = $this->em->find(Company::class, $company->getId()); + if (!is_null($managed)) { + $this->em->remove($managed); + } + } + $this->em->flush(); + parent::tearDown(); + } + + public function testGetAllIdAndNameReturnsScalarPairs(): void + { + foreach (['A', 'B'] as $suffix) { + $company = new Company(); + $company->setName('Company IdName ' . $suffix . ' ' . str_random(16)); + $this->em->persist($company); + $this->companies[] = $company; + } + $this->em->flush(); + + $repo = App::make(ICompanyRepository::class); + $rows = $repo->getAllIdAndName(); + + foreach ($this->companies as $company) { + $this->assertContains(['id' => $company->getId(), 'name' => $company->getName()], $rows); + } + foreach ($rows as $row) { + $this->assertIsInt($row['id']); + } + } +} From b9a2c97e4db178488d5874308755798e2fe37113 Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 01:51:19 -0600 Subject: [PATCH 05/15] test(companies): align id-and-name repository test namespace --- .../Repositories/DoctrineCompanyRepositoryIdAndNameTest.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php index 171071bcb..459a0ad8f 100644 --- a/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php +++ b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php @@ -1,4 +1,4 @@ - Date: Sun, 15 Nov 2026 03:02:13 -0600 Subject: [PATCH 06/15] feat(sponsors): import sponsors from csv with dry run and per-row report --- .../OAuth2SummitSponsorApiController.php | 127 ++++++++++ app/Services/Model/ISummitSponsorService.php | 10 + .../Model/Imp/SummitSponsorService.php | 173 ++++++++++++++ .../config/Version20261115120000.php | 67 ++++++ database/seeders/ApiEndpointsSeeder.php | 13 + routes/api_v1.php | 1 + .../SummitSponsorServiceImportFaultTest.php | 181 ++++++++++++++ tests/oauth2/OAuth2SummitSponsorApiTest.php | 223 +++++++++++++++++- 8 files changed, 794 insertions(+), 1 deletion(-) create mode 100644 database/migrations/config/Version20261115120000.php create mode 100644 tests/Unit/Services/SummitSponsorServiceImportFaultTest.php diff --git a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php index d9bc5c8a2..6a1d0837d 100644 --- a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php +++ b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php @@ -23,6 +23,8 @@ use App\Security\SummitScopes; use Illuminate\Http\Request as LaravelRequest; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Validator; +use models\exceptions\ValidationException; use models\oauth2\IResourceServerContext; use models\summit\ISummitRepository; use models\summit\Sponsor; @@ -612,6 +614,131 @@ public function addV2($summit_id){ return $this->add($summit_id); } + #[OA\Post( + path: "/api/v1/summits/{id}/sponsors/csv", + description: "Import sponsors from a CSV file with company and tier columns (tiers separated by '|'). Missing companies are created. With dry_run, returns the per-row plan and writes nothing.", + summary: 'Import Sponsors from CSV', + operationId: 'importSponsors', + tags: ['Sponsors'], + security: [ + [ + 'summit_sponsor_oauth2' => [ + SummitScopes::WriteSummitData, + ] + ] + ], + x: [ + 'required-groups' => [ + IGroup::SuperAdmins, + IGroup::Administrators, + IGroup::SummitAdministrators, + ] + ], + parameters: [ + new OA\Parameter( + name: 'id', + in: 'path', + required: true, + schema: new OA\Schema(type: 'integer'), + description: 'The summit id' + ), + ], + requestBody: new OA\RequestBody( + required: true, + content: new OA\MediaType( + mediaType: 'multipart/form-data', + schema: new OA\Schema( + type: 'object', + required: ['file'], + properties: [ + new OA\Property( + property: 'file', + type: 'string', + format: 'binary', + description: 'UTF-8 CSV file with company and tier columns' + ), + new OA\Property( + property: 'dry_run', + type: 'boolean', + description: 'Plan only, write nothing' + ), + ] + ) + ) + ), + responses: [ + new OA\Response( + response: Response::HTTP_OK, + description: 'Per-row import report', + content: new OA\JsonContent( + type: 'object', + properties: [ + new OA\Property(property: 'dry_run', type: 'boolean'), + new OA\Property(property: 'summary', type: 'object', properties: [ + new OA\Property(property: 'total', type: 'integer'), + new OA\Property(property: 'sponsors_created', type: 'integer'), + new OA\Property(property: 'companies_created', type: 'integer'), + new OA\Property(property: 'skipped', type: 'integer'), + new OA\Property(property: 'errors', type: 'integer'), + new OA\Property(property: 'not_attempted', type: 'integer'), + ]), + new OA\Property(property: 'rows', type: 'array', items: new OA\Items(type: 'object', properties: [ + new OA\Property(property: 'row', type: 'integer'), + new OA\Property(property: 'company_input', type: 'string'), + new OA\Property(property: 'tier_input', type: 'string'), + new OA\Property(property: 'action', type: 'string', enum: ['create', 'skip_existing_sponsor', 'skip_duplicate', 'error', 'not_attempted']), + new OA\Property(property: 'company', type: 'object', nullable: true, properties: [ + new OA\Property(property: 'id', type: 'integer', nullable: true), + new OA\Property(property: 'name', type: 'string'), + new OA\Property(property: 'match', type: 'string', enum: ['exact', 'normalized', 'new']), + ]), + new OA\Property(property: 'tiers', type: 'array', items: new OA\Items(type: 'string')), + new OA\Property(property: 'sponsor_id', type: 'integer', nullable: true), + new OA\Property(property: 'duplicate_of_row', type: 'integer', nullable: true), + new OA\Property(property: 'candidates', type: 'array', items: new OA\Items(type: 'string')), + new OA\Property(property: 'error', type: 'string', nullable: true), + ])), + ] + ) + ), + new OA\Response(response: Response::HTTP_UNAUTHORIZED, description: "Unauthorized"), + new OA\Response(response: Response::HTTP_FORBIDDEN, description: "Forbidden"), + new OA\Response(response: Response::HTTP_NOT_FOUND, description: "Not Found"), + new OA\Response(response: Response::HTTP_PRECONDITION_FAILED, description: "Validation Error"), + new OA\Response(response: Response::HTTP_INTERNAL_SERVER_ERROR, description: "Server Error") + ] + )] + /** + * @param LaravelRequest $request + * @param $summit_id + * @return \Illuminate\Http\JsonResponse|mixed + */ + public function import(LaravelRequest $request, $summit_id) + { + return $this->processRequest(function () use ($request, $summit_id) { + $summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->resource_server_context)->find($summit_id); + if (is_null($summit)) return $this->error404(); + + // same authz as addChild ( SERVICE or authz member ) + $application_type = $this->resource_server_context->getApplicationType(); + $current_member = $this->resource_server_context->getCurrentUser(); + $is_authz = $application_type == IResourceServerContext::ApplicationType_Service || + (!is_null($current_member) && $current_member->isAuthzFor($summit)); + + if (!$is_authz) + throw new HTTP403ForbiddenException("You are not allowed to perform this action."); + + $validation = Validator::make($request->all(), ['file' => 'required|file']); + if ($validation->fails()) { + throw new ValidationException($validation->messages()->toArray()); + } + + $report = $this->service->importSponsors($summit, $request->file('file'), $request->boolean('dry_run')); + + return $this->ok($report); + }); + } + /** * @return ISummitRepository */ diff --git a/app/Services/Model/ISummitSponsorService.php b/app/Services/Model/ISummitSponsorService.php index 922b0909f..aa35c8d2b 100644 --- a/app/Services/Model/ISummitSponsorService.php +++ b/app/Services/Model/ISummitSponsorService.php @@ -48,6 +48,16 @@ interface ISummitSponsorService */ public function addSponsor(Summit $summit, array $payload):Sponsor; + /** + * Creates sponsors (and missing companies) from a CSV with company and tier columns. + * @param Summit $summit + * @param UploadedFile $file + * @param bool $dry_run plan only, write nothing + * @return array{dry_run:bool,summary:array,rows:list} + * @throws ValidationException + */ + public function importSponsors(Summit $summit, UploadedFile $file, bool $dry_run):array; + /** * @param Summit $summit * @param int $sponsor_id diff --git a/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index d7ed335f5..a34a0f7f1 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -35,7 +35,15 @@ use App\Models\Foundation\Summit\Repositories\ISponsorExtraQuestionTypeRepository; use App\Models\Foundation\Summit\Repositories\ISummitSponsorshipRepository; use App\Models\Foundation\Summit\SponsorStatistics; +use App\Models\Foundation\Main\Factories\CompanyFactory; use App\Services\Model\Imp\ExtraQuestionTypeService; +use App\Services\Model\Imp\SponsorImport\CompanyNameMatcher; +use App\Services\Model\Imp\SponsorImport\SponsorImportPlanner; +use LaravelDoctrine\ORM\Facades\Registry; +use League\Csv\Reader; +use League\Csv\UnableToProcessCsv; +use models\utils\SilverstripeBaseModel; +use services\utils\AmbiguousCommitException; use Doctrine\Common\Collections\ArrayCollection; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Log; @@ -56,6 +64,7 @@ use models\summit\Summit; use models\summit\SummitLeadReportSetting; use models\summit\SummitSponsorship; +use models\summit\SummitSponsorshipType; use services\model\ISummitSponsorService; /** @@ -223,6 +232,170 @@ public function addSponsor(Summit $summit, array $payload): Sponsor return $sponsor; } + /** + * @param Summit $summit + * @param UploadedFile $file + * @param bool $dry_run + * @return array + * @throws ValidationException + */ + public function importSponsors(Summit $summit, UploadedFile $file, bool $dry_run): array + { + Log::debug(sprintf("SummitSponsorService::importSponsors summit %s dry_run %s", $summit->getId(), $dry_run ? "true" : "false")); + + $rows = $this->parseSponsorsCsv($file); + + $tiers = []; + foreach ($summit->getSummitSponsorshipTypes() as $summit_sponsorship_type) { + if (!$summit_sponsorship_type instanceof SummitSponsorshipType) continue; + $type = $summit_sponsorship_type->getType(); + if (is_null($type)) continue; + $tiers[mb_strtolower($type->getName())] = ['id' => $summit_sponsorship_type->getId(), 'name' => $type->getName()]; + } + + $sponsor_company_ids = []; + foreach ($summit->getSummitSponsors() as $sponsor) { + if ($sponsor instanceof Sponsor && $sponsor->hasCompany()) + $sponsor_company_ids[] = $sponsor->getCompanyId(); + } + + $planner = new SponsorImportPlanner( + new CompanyNameMatcher($this->company_repository->getAllIdAndName()), + $tiers, + $sponsor_company_ids + ); + $rows = $planner->plan($rows); + + if (!$dry_run) { + $rows = $this->executeSponsorsImport($summit, $rows); + } + + $report = SponsorImportPlanner::summarize($rows, $dry_run); + $report['rows'] = array_map(static function (array $row): array { + unset($row['tier_ids']); + return $row; + }, $rows); + return $report; + } + + /** + * @param UploadedFile $file + * @return list + * @throws ValidationException + */ + private function parseSponsorsCsv(UploadedFile $file): array + { + if (!in_array($file->extension(), ['csv', 'txt'])) { + throw new ValidationException("File does not has a valid extension ('csv')."); + } + + $content = file_get_contents($file->getRealPath()); + if ($content === false || $content === '') + throw new ValidationException("File content is empty."); + + // Excel's plain "CSV (comma delimited)" export is cp1252 and would create garbled companies + if (!mb_check_encoding($content, 'UTF-8')) + throw new ValidationException("File is not UTF-8 encoded. In Excel, use Save As > CSV UTF-8."); + + try { + $csv = Reader::createFromString($content); + $csv->setHeaderOffset(0); + + $columns = []; + foreach ($csv->getHeader() as $header) { + $normalized = mb_strtolower(trim($header)); + if (isset($columns[$normalized])) + throw new ValidationException(sprintf("File has more than one %s column.", $normalized)); + $columns[$normalized] = $header; + } + foreach (['company', 'tier'] as $required) { + if (!isset($columns[$required])) + throw new ValidationException(sprintf("File is missing the %s column.", $required)); + } + + $rows = []; + foreach ($csv->getRecords() as $offset => $record) { + $company = (string)($record[$columns['company']] ?? ''); + $tier = (string)($record[$columns['tier']] ?? ''); + if (trim($company) === '' && trim($tier) === '') continue; + $rows[] = ['row' => $offset + 1, 'company' => $company, 'tier' => $tier]; + } + } catch (UnableToProcessCsv $ex) { + throw new ValidationException(sprintf("CSV is not valid: %s", $ex->getMessage())); + } + + if (count($rows) > SponsorImportPlanner::MAX_ROWS) + throw new ValidationException(sprintf("File has %d rows; the maximum is %d.", count($rows), SponsorImportPlanner::MAX_ROWS)); + + return $rows; + } + + /** + * Runs the planned creates in order, each through its own transaction(s); never wrapped in an outer one, + * so addSponsor publishes its domain events after its own commit. + * @param Summit $summit + * @param list $rows + * @return list + */ + private function executeSponsorsImport(Summit $summit, array $rows): array + { + $connection_reset = "The import stopped because the database connection was reset. Rows below were not imported."; + $could_not_confirm = "Could not confirm whether this sponsor was saved; the import stopped here. Check the sponsor list before importing this file again."; + $could_not_create = "Could not create this sponsor; the import stopped here. Rows below were not imported."; + + foreach ($rows as $index => $row) { + if ($row['action'] !== 'create') continue; + + if (!$this->isSummitManaged($summit)) { + return SponsorImportPlanner::markStopped($rows, $index, $connection_reset, 'not_attempted'); + } + + $company_created = null; + try { + $company_id = $row['company']['id']; + if ($row['company']['match'] === 'new') { + $name = $row['company']['name']; + $company = $this->tx_service->transaction(function () use ($name) { + $company = CompanyFactory::build(['name' => $name]); + $this->company_repository->add($company, true); + return $company; + }); + $company_id = $company->getId(); + $rows[$index]['company']['id'] = $company_id; + $company_created = sprintf(' Company "%s" was created.', $company->getName()); + + if (!$this->isSummitManaged($summit)) { + return SponsorImportPlanner::markStopped($rows, $index, $connection_reset . $company_created); + } + } + + $sponsor = $this->addSponsor($summit, [ + 'company_id' => $company_id, + 'sponsorships' => array_map(static fn(int $type_id): array => ['type_id' => $type_id], $row['tier_ids']), + ]); + + $sponsor_id = $sponsor->getId(); + if (!$this->isSummitManaged($summit) || !is_int($sponsor_id) || $sponsor_id <= 0) { + // addSponsor's own retry may have run against a detached summit + return SponsorImportPlanner::markStopped($rows, $index, $could_not_confirm . ($company_created ?? '')); + } + $rows[$index]['sponsor_id'] = $sponsor_id; + } catch (\Throwable $ex) { + // Stop instead of log-and-skip: a failed transaction clears the EntityManager, which detaches + // $summit, so later rows would act on detached entities. Bad rows were already caught by the plan. + Log::error(sprintf("SummitSponsorService::importSponsors summit %s row %s: %s", $summit->getId(), $row['row'], $ex->getMessage()), ['exception' => $ex]); + $message = $ex instanceof AmbiguousCommitException ? $could_not_confirm : $could_not_create; + return SponsorImportPlanner::markStopped($rows, $index, $message . ($company_created ?? '')); + } + } + return $rows; + } + + private function isSummitManaged(Summit $summit): bool + { + return Registry::getManager(SilverstripeBaseModel::EntityManager)->contains($summit); + } + /** * @param Summit $summit * @param int $sponsor_id diff --git a/database/migrations/config/Version20261115120000.php b/database/migrations/config/Version20261115120000.php new file mode 100644 index 000000000..a98815f22 --- /dev/null +++ b/database/migrations/config/Version20261115120000.php @@ -0,0 +1,67 @@ + 'import-sponsors', + 'route' => '/api/v1/summits/{id}/sponsors/csv', + 'http_method' => 'POST', + 'scopes' => [ + SummitScopes::WriteSummitData, + ], + 'authz_groups' => [ + IGroup::SuperAdmins, + IGroup::Administrators, + IGroup::SummitAdministrators, + ], + ], + ]; + + public function getDescription(): string + { + return 'Register the sponsor CSV import endpoint.'; + } + + public function up(Schema $schema): void + { + $this->registerEndpoints(self::API_NAME, self::ENDPOINTS); + } + + public function down(Schema $schema): void + { + $this->unregisterEndpoints(self::API_NAME, array_column(self::ENDPOINTS, 'name')); + } +} diff --git a/database/seeders/ApiEndpointsSeeder.php b/database/seeders/ApiEndpointsSeeder.php index af083c4c3..fcffbae58 100644 --- a/database/seeders/ApiEndpointsSeeder.php +++ b/database/seeders/ApiEndpointsSeeder.php @@ -2077,6 +2077,19 @@ private function seedSummitEndpoints() IGroup::SummitAdministrators, ] ], + [ + 'name' => 'import-sponsors', + 'route' => '/api/v1/summits/{id}/sponsors/csv', + 'http_method' => 'POST', + 'scopes' => [ + SummitScopes::WriteSummitData, + ], + 'authz_groups' => [ + IGroup::SuperAdmins, + IGroup::Administrators, + IGroup::SummitAdministrators, + ] + ], [ 'name' => 'add-sponsor-v2', 'route' => '/api/v2/summits/{id}/sponsors', diff --git a/routes/api_v1.php b/routes/api_v1.php index bf0df1cd1..f72b0f6d9 100644 --- a/routes/api_v1.php +++ b/routes/api_v1.php @@ -1254,6 +1254,7 @@ Route::group(['prefix' => 'sponsors'], function () { Route::get('', ['middleware' => 'auth.user', 'uses' => 'OAuth2SummitSponsorApiController@getAllBySummit']); Route::post('', ['middleware' => 'auth.user', 'uses' => 'OAuth2SummitSponsorApiController@add']); + Route::post('csv', ['middleware' => 'auth.user', 'uses' => 'OAuth2SummitSponsorApiController@import']); Route::group(['prefix' => 'all'], function () { Route::group(['prefix' => 'extra-questions'], function () { Route::get('metadata', ['middleware' => 'auth.user', 'uses' => 'OAuth2SummitSponsorApiController@getMetadata']); diff --git a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php new file mode 100644 index 000000000..463a244b8 --- /dev/null +++ b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php @@ -0,0 +1,181 @@ +inner = $inner; + $this->on_call = $on_call; + $this->throw = $throw; + $this->clear_after = $clear_after; + } + + public function transaction(Closure $callback, int $isolationLevel = 2) + { + $this->calls++; + if ($this->calls === $this->on_call && !is_null($this->throw)) { + throw $this->throw; + } + $result = $this->inner->transaction($callback, $isolationLevel); + if ($this->calls === $this->on_call && $this->clear_after) { + Registry::getManager(SilverstripeBaseModel::EntityManager)->clear(); + } + return $result; + } +} + +/** + * Class SummitSponsorServiceImportFaultTest + * Execution failures during a sponsor CSV import stop the run with a per-row report. + * @package Tests\Unit\Services + */ +class SummitSponsorServiceImportFaultTest extends TestCase +{ + use InsertSummitTestData; + + const ConnectionResetMessage = 'The import stopped because the database connection was reset. Rows below were not imported.'; + const CouldNotConfirmMessage = 'Could not confirm whether this sponsor was saved; the import stopped here. Check the sponsor list before importing this file again.'; + + /** + * @var string[] + */ + private $names = []; + + protected function setUp(): void + { + parent::setUp(); + self::insertSummitTestData(); + $this->names = []; + } + + public function tearDown(): void + { + self::clearSummitTestData(); + $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + foreach ($this->names as $name) { + foreach ($em->getRepository(Company::class)->findBy(['name' => $name]) as $company) { + $em->remove($company); + } + } + $em->flush(); + parent::tearDown(); + } + + private function bindFake(int $on_call, ?\Throwable $throw, bool $clear_after): FaultInjectingTransactionService + { + $fake = new FaultInjectingTransactionService(app(ITransactionService::class), $on_call, $throw, $clear_after); + $this->app->instance(ITransactionService::class, $fake); + // singleton: a service resolved earlier would keep the real transaction service + $this->app->forgetInstance(ISummitSponsorService::class); + return $fake; + } + + private function importThreeNewCompanies(): array + { + $csv = "company,tier\n"; + for ($i = 0; $i < 3; $i++) { + $name = sprintf('Import Fault %s %s', $i, str_random(16)); + $this->names[] = $name; + $csv .= "\"{$name}\",Default\n"; + } + $path = tempnam(sys_get_temp_dir(), 'sponsor_import') . '.csv'; + file_put_contents($path, $csv); + $file = new UploadedFile($path, 'sponsors.csv', 'text/csv', null, true); + return app(ISummitSponsorService::class)->importSponsors(self::$summit, $file, false); + } + + private function assertLaterRowsNotAttempted(array $report): void + { + $this->assertSame(['error', 'not_attempted', 'not_attempted'], array_column($report['rows'], 'action')); + $this->assertSame(1, $report['summary']['errors']); + $this->assertSame(2, $report['summary']['not_attempted']); + $this->assertSame(0, $report['summary']['sponsors_created']); + $this->assertNull($report['rows'][1]['sponsor_id']); + $this->assertNull($report['rows'][2]['sponsor_id']); + } + + public function testAmbiguousCommitOnSponsorStopsWithConfirmMessage(): void + { + Queue::fake(); + // call 1 = row 1 company, call 2 = row 1 addSponsor + $fake = $this->bindFake(2, new AmbiguousCommitException('x'), false); + + $report = $this->importThreeNewCompanies(); + + $this->assertLaterRowsNotAttempted($report); + $row = $report['rows'][0]; + $this->assertSame(self::CouldNotConfirmMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); + $this->assertGreaterThan(0, $row['company']['id']); + $this->assertNull($row['sponsor_id']); + $this->assertSame(1, $report['summary']['companies_created']); + $this->assertGreaterThan(0, $fake->calls); + } + + public function testDetachAfterCompanyCreationStopsBeforeAddSponsor(): void + { + Queue::fake(); + $fake = $this->bindFake(1, null, true); + + $report = $this->importThreeNewCompanies(); + + $this->assertLaterRowsNotAttempted($report); + $row = $report['rows'][0]; + $this->assertSame(self::ConnectionResetMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); + $this->assertGreaterThan(0, $row['company']['id']); + $this->assertSame(1, $report['summary']['companies_created']); + // addSponsor never ran + $this->assertSame(1, $fake->calls); + Queue::assertNotPushed(PublishSponsorServiceDomainEventsJob::class); + } + + public function testDetachAfterAddSponsorStopsWithConfirmMessage(): void + { + Queue::fake(); + $fake = $this->bindFake(2, null, true); + + $report = $this->importThreeNewCompanies(); + + $this->assertLaterRowsNotAttempted($report); + $row = $report['rows'][0]; + $this->assertSame(self::CouldNotConfirmMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); + $this->assertNull($row['sponsor_id']); + $this->assertSame(2, $fake->calls); + } +} diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index 47384ca96..30951cf0e 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -18,6 +18,14 @@ use models\summit\SummitLeadReportSetting; use App\Models\Foundation\Main\IGroup; use App\Models\ResourceServer\IAccessTokenService; +use Illuminate\Support\Facades\App; +use Illuminate\Support\Facades\Queue; +use LaravelDoctrine\ORM\Facades\Registry; +use models\main\Company; +use models\summit\Sponsor; +use models\summit\Summit; +use models\utils\SilverstripeBaseModel; +use services\model\ISummitSponsorService; /** * Class OAuth2SummitSponsorApiTest */ @@ -51,6 +59,7 @@ protected function setUp(): void protected function tearDown(): void { self::clearSummitTestData(); + $this->removeImportedCompanies(); parent::tearDown(); } @@ -1647,7 +1656,15 @@ private function makeMemberSponsorUser(): void */ private function useSponsorOnlyToken(): void { - $stub = new AccessTokenServiceStub([['slug' => IGroup::Sponsors]]); + $this->useTokenWithGroups([IGroup::Sponsors]); + } + + /** + * @param string[] $group_slugs + */ + private function useTokenWithGroups(array $group_slugs): void + { + $stub = new AccessTokenServiceStub(array_map(fn($slug) => ['slug' => $slug], $group_slugs)); $stub->setUserId(self::$member->getUserExternalId()); $stub->setUserExternalId(self::$member->getUserExternalId()); $stub->setUserEmail(self::$member->getEmail()); @@ -1823,4 +1840,208 @@ public function testBulkUpdateSponsorServicesStatisticsValidationError() $this->assertResponseStatus(412); } + + // ---- CSV import ---- + + /** + * @var string[] names of companies the import tests may create, removed on tear down + */ + private $imported_company_names = []; + + private function newCompanyName(): string + { + $name = 'Import Co ' . str_random(16); + $this->imported_company_names[] = $name; + return $name; + } + + private function removeImportedCompanies(): void + { + if (count($this->imported_company_names) === 0) return; + $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + foreach ($this->imported_company_names as $name) { + foreach ($em->getRepository(Company::class)->findBy(['name' => $name]) as $company) { + $em->remove($company); + } + foreach ($em->getRepository(Company::class)->findBy(['name' => $name . ', Inc.']) as $company) { + $em->remove($company); + } + } + $em->flush(); + $this->imported_company_names = []; + } + + private function buildCsvFile(string $content): UploadedFile + { + $path = tempnam(sys_get_temp_dir(), 'sponsor_import') . '.csv'; + file_put_contents($path, $content); + return new UploadedFile($path, 'sponsors.csv', 'text/csv', null, true); + } + + private function importCsv(string $content, bool $dry_run) + { + return $this->action( + "POST", + "OAuth2SummitSponsorApiController@import", + ['id' => self::$summit->getId()], + ['dry_run' => $dry_run ? '1' : '0'], + [], + ['file' => $this->buildCsvFile($content)], + // not getAuthHeaders(): its JSON content type replaces the form fields + ["HTTP_Authorization" => " Bearer " . $this->access_token] + ); + } + + public function testImportCreatesSponsorsAndCompanies(){ + Queue::fake(); + $existing = self::$companies_without_sponsor[0]->getName(); + $new_name = $this->newCompanyName(); + $sponsor_company = self::$sponsors[0]->getCompany()->getName(); + + $csv = "company,tier\n" . + "\"{$existing}\",Default\n" . + "\"{$new_name}\",Default|Default2\n" . + "\"{$sponsor_company}\",Default\n" . + "\"{$this->newCompanyName()}\",Nope\n"; + + $response = $this->importCsv($csv, false); + $this->assertResponseStatus(200); + $report = json_decode($response->getContent(), true); + + $this->assertFalse($report['dry_run']); + $this->assertSame(['create', 'create', 'skip_existing_sponsor', 'error'], array_column($report['rows'], 'action')); + $this->assertSame(2, $report['summary']['sponsors_created']); + $this->assertSame(1, $report['summary']['companies_created']); + $this->assertSame(1, $report['summary']['skipped']); + $this->assertSame(1, $report['summary']['errors']); + $this->assertSame(0, $report['summary']['not_attempted']); + $this->assertGreaterThan(0, $report['rows'][0]['sponsor_id']); + $this->assertGreaterThan(0, $report['rows'][1]['sponsor_id']); + $this->assertGreaterThan(0, $report['rows'][1]['company']['id']); + $this->assertSame('new', $report['rows'][1]['company']['match']); + $this->assertSame(['Default', 'Default2'], $report['rows'][1]['tiers']); + foreach ($report['rows'] as $row) { + $this->assertArrayNotHasKey('tier_ids', $row); + } + + // the request closed the cached manager + $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + $sponsor = $em->find(Sponsor::class, $report['rows'][1]['sponsor_id']); + $this->assertInstanceOf(Sponsor::class, $sponsor); + $this->assertSame($new_name, $sponsor->getCompany()->getName()); + $this->assertCount(2, $sponsor->getSponsorships()); + } + + public function testDryRunWritesNothing(){ + $new_name = $this->newCompanyName(); + $sponsors_before = self::$summit->getSummitSponsors()->count(); + $summit_id = self::$summit->getId(); + + $response = $this->importCsv("company,tier\n\"{$new_name}\",Default\n", true); + $this->assertResponseStatus(200); + $report = json_decode($response->getContent(), true); + + $this->assertTrue($report['dry_run']); + $this->assertSame('create', $report['rows'][0]['action']); + $this->assertSame('new', $report['rows'][0]['company']['match']); + $this->assertNull($report['rows'][0]['sponsor_id']); + $this->assertSame(1, $report['summary']['sponsors_created']); + $this->assertSame(1, $report['summary']['companies_created']); + + $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + $this->assertNull($em->getRepository(Company::class)->findOneBy(['name' => $new_name])); + $this->assertSame($sponsors_before, $em->find(Summit::class, $summit_id)->getSummitSponsors()->count()); + } + + public function testDryRunMatchesRealRun(){ + Queue::fake(); + $new_name = $this->newCompanyName(); + $csv = "company,tier\n" . + "\"{$new_name}\",Default\n" . + "\"" . strtoupper($new_name) . " Inc.\",Default2\n" . + "\"" . self::$companies_without_sponsor[1]->getName() . "\",Default2\n" . + "\"" . self::$sponsors[0]->getCompany()->getName() . "\",Default\n" . + ",Default\n"; + + // dry run through the service: no HTTP request, so the manager stays open for the real run + $dry = App::make(ISummitSponsorService::class)->importSponsors(self::$summit, $this->buildCsvFile($csv), true); + + $response = $this->importCsv($csv, false); + $this->assertResponseStatus(200); + $real = json_decode($response->getContent(), true); + + $this->assertTrue($dry['dry_run']); + $this->assertFalse($real['dry_run']); + $this->assertSame(['create', 'skip_duplicate', 'create', 'skip_existing_sponsor', 'error'], array_column($dry['rows'], 'action')); + $this->assertSame(array_column($dry['rows'], 'action'), array_column($real['rows'], 'action')); + $this->assertSame($dry['summary'], $real['summary']); + // two spellings of one new company create it once + $this->assertSame(1, $real['summary']['companies_created']); + } + + public function testImportHandlesExcelQuirks(){ + Queue::fake(); + $name = $this->newCompanyName(); + $content = "\xEF\xBB\xBF Company ,TIER\r\n\"{$name}, Inc.\",Default\r\n\r\n"; + + $response = $this->importCsv($content, true); + $this->assertResponseStatus(200); + $report = json_decode($response->getContent(), true); + + $this->assertCount(1, $report['rows']); + $this->assertSame('create', $report['rows'][0]['action']); + $this->assertSame(2, $report['rows'][0]['row']); + $this->assertSame("{$name}, Inc.", $report['rows'][0]['company_input']); + $this->assertSame(1, $report['summary']['total']); + } + + public function testImportValidationMissingTierColumn(){ + $response = $this->importCsv("company,level\nAcme,Default\n", true); + $this->assertResponseStatus(412); + $this->assertStringContainsString('tier', $response->getContent()); + } + + public function testImportValidationDuplicateNormalizedHeader(){ + $response = $this->importCsv("company, Company ,tier\nAcme,Acme,Default\n", true); + $this->assertResponseStatus(412); + $this->assertStringContainsString('more than one company column', $response->getContent()); + } + + public function testImportValidationTooManyRows(){ + $csv = "company,tier\n"; + for ($i = 0; $i < 501; $i++) $csv .= "Company {$i},Default\n"; + $response = $this->importCsv($csv, true); + $this->assertResponseStatus(412); + $this->assertStringContainsString('501 rows', $response->getContent()); + } + + public function testImportValidationNotUtf8(){ + // Excel's plain "CSV (comma delimited)" export is cp1252 + $response = $this->importCsv("company,tier\nCaf\xE9 Ltd,Default\n", true); + $this->assertResponseStatus(412); + $this->assertStringContainsString('not UTF-8 encoded', $response->getContent()); + } + + public function testImportForbiddenForNonAuthzMember(){ + $this->useSponsorOnlyToken(); + $this->assertFalse(self::$member->isAdmin()); + $this->assertFalse(self::$member->isAuthzFor(self::$summit)); + + $response = $this->importCsv("company,tier\n\"{$this->newCompanyName()}\",Default\n", true); + $this->assertResponseStatus(403); + // the auth.user group gate answered (sponsors is not in the endpoint's authz groups) + $this->assertStringContainsString('unauthorized member', $response->getContent()); + } + + public function testImportForbiddenForSummitAdminOfAnotherSummit(){ + // passes the endpoint's group gate, but the member is not allowed on this summit + $this->useTokenWithGroups([IGroup::SummitAdministrators]); + $this->assertFalse(self::$member->isAdmin()); + $this->assertFalse(self::$member->isAuthzFor(self::$summit)); + + $response = $this->importCsv("company,tier\n\"{$this->newCompanyName()}\",Default\n", true); + $this->assertResponseStatus(403); + // the controller's authz check answered, not the auth.user group gate + $this->assertStringNotContainsString('unauthorized member', $response->getContent()); + } } From c52b49d79410e9cdfa530b6b7e407f2bef0d6376 Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 03:12:47 -0600 Subject: [PATCH 07/15] fix(sponsors): keep import errors free of file content and harden matcher --- .../Imp/SponsorImport/CompanyNameMatcher.php | 16 ++++++-- .../Model/Imp/SummitSponsorService.php | 14 +++++-- .../SummitSponsorServiceImportFaultTest.php | 10 +++-- tests/oauth2/OAuth2SummitSponsorApiTest.php | 37 ++++++++++++++++++- 4 files changed, 65 insertions(+), 12 deletions(-) diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php index 14bacf78f..9d59287f0 100644 --- a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -71,8 +71,7 @@ public function __construct(array $companies) public static function key(string $name): string { - $s = \Normalizer::normalize($name, \Normalizer::FORM_C); - if ($s === false) $s = $name; + $s = self::nfc($name); $s = mb_strtolower($s); $s = trim(preg_replace('/[^\p{L}\p{N}]+/u', ' ', $s)); if ($s === '') return ''; @@ -83,10 +82,19 @@ public static function key(string $name): string return implode(' ', $words); } - private static function exactKey(string $name): string + /** + * NFC when intl is available; otherwise the name as given. + */ + private static function nfc(string $name): string { + if (!class_exists(\Normalizer::class)) return $name; $s = \Normalizer::normalize($name, \Normalizer::FORM_C); - if ($s === false) $s = $name; + return $s === false ? $name : $s; + } + + private static function exactKey(string $name): string + { + $s = self::nfc($name); return mb_strtolower(trim($s)); } diff --git a/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index a34a0f7f1..9c0555bee 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -301,14 +301,19 @@ private function parseSponsorsCsv(UploadedFile $file): array $csv = Reader::createFromString($content); $csv->setHeaderOffset(0); + // messages never echo file content: the admin UI renders them as HTML + $required_columns = ['company', 'tier']; $columns = []; foreach ($csv->getHeader() as $header) { - $normalized = mb_strtolower(trim($header)); + // Excel can leave a trailing NBSP on a header + $normalized = mb_strtolower(preg_replace('/^[\s\x{00A0}]+|[\s\x{00A0}]+$/u', '', (string)$header)); + $required = array_search($normalized, $required_columns, true); + if ($required === false) continue; if (isset($columns[$normalized])) - throw new ValidationException(sprintf("File has more than one %s column.", $normalized)); + throw new ValidationException(sprintf("File has more than one %s column.", $required_columns[$required])); $columns[$normalized] = $header; } - foreach (['company', 'tier'] as $required) { + foreach ($required_columns as $required) { if (!isset($columns[$required])) throw new ValidationException(sprintf("File is missing the %s column.", $required)); } @@ -321,7 +326,8 @@ private function parseSponsorsCsv(UploadedFile $file): array $rows[] = ['row' => $offset + 1, 'company' => $company, 'tier' => $tier]; } } catch (UnableToProcessCsv $ex) { - throw new ValidationException(sprintf("CSV is not valid: %s", $ex->getMessage())); + Log::warning(sprintf("SummitSponsorService::importSponsors CSV is not valid: %s", $ex->getMessage())); + throw new ValidationException("CSV is not valid."); } if (count($rows) > SponsorImportPlanner::MAX_ROWS) diff --git a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php index 463a244b8..bc9e0068e 100644 --- a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php +++ b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php @@ -115,10 +115,14 @@ private function importThreeNewCompanies(): array $this->names[] = $name; $csv .= "\"{$name}\",Default\n"; } - $path = tempnam(sys_get_temp_dir(), 'sponsor_import') . '.csv'; + $path = sprintf('%s/sponsor_import_%s.csv', sys_get_temp_dir(), str_random(16)); file_put_contents($path, $csv); - $file = new UploadedFile($path, 'sponsors.csv', 'text/csv', null, true); - return app(ISummitSponsorService::class)->importSponsors(self::$summit, $file, false); + try { + $file = new UploadedFile($path, 'sponsors.csv', 'text/csv', null, true); + return app(ISummitSponsorService::class)->importSponsors(self::$summit, $file, false); + } finally { + unlink($path); + } } private function assertLaterRowsNotAttempted(array $report): void diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index 30951cf0e..0ab0d3c77 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -1857,6 +1857,10 @@ private function newCompanyName(): string private function removeImportedCompanies(): void { + foreach ($this->csv_paths as $path) { + if (is_file($path)) unlink($path); + } + $this->csv_paths = []; if (count($this->imported_company_names) === 0) return; $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); foreach ($this->imported_company_names as $name) { @@ -1871,10 +1875,16 @@ private function removeImportedCompanies(): void $this->imported_company_names = []; } + /** + * @var string[] temp upload paths, removed on tear down + */ + private $csv_paths = []; + private function buildCsvFile(string $content): UploadedFile { - $path = tempnam(sys_get_temp_dir(), 'sponsor_import') . '.csv'; + $path = sprintf('%s/sponsor_import_%s.csv', sys_get_temp_dir(), str_random(16)); file_put_contents($path, $content); + $this->csv_paths[] = $path; return new UploadedFile($path, 'sponsors.csv', 'text/csv', null, true); } @@ -1995,6 +2005,31 @@ public function testImportHandlesExcelQuirks(){ $this->assertSame(1, $report['summary']['total']); } + public function testImportRecognizesHeaderWithTrailingNbsp(){ + $name = $this->newCompanyName(); + $response = $this->importCsv("company\u{00A0},\u{00A0}tier\n\"{$name}\",Default\n", true); + $this->assertResponseStatus(200); + $report = json_decode($response->getContent(), true); + $this->assertSame(['create'], array_column($report['rows'], 'action')); + } + + public function testImportInvalidCsvDoesNotEchoLibraryMessage(){ + // identical raw headers make League throw; its message names the header + $response = $this->importCsv("company,tier,y,y\nAcme,Default,1,2\n", true); + $this->assertResponseStatus(412); + $this->assertStringContainsString('CSV is not valid.', $response->getContent()); + $this->assertStringNotContainsString('', $response->getContent()); + } + + public function testImportIgnoresDuplicateExtraColumnsWithoutEchoingThem(){ + $name = $this->newCompanyName(); + $response = $this->importCsv("x,X,company,tier\n1,2,\"{$name}\",Default\n", true); + $this->assertResponseStatus(200); + $this->assertStringNotContainsString('', $response->getContent()); + $report = json_decode($response->getContent(), true); + $this->assertSame(['create'], array_column($report['rows'], 'action')); + } + public function testImportValidationMissingTierColumn(){ $response = $this->importCsv("company,level\nAcme,Default\n", true); $this->assertResponseStatus(412); From c618c4fff9b3bae2fbef491c3658fc68f801e9f5 Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 04:28:29 -0600 Subject: [PATCH 08/15] fix(sponsors): cap import at 200 rows and correct stopped-run report rows --- .../Imp/SponsorImport/CompanyNameMatcher.php | 3 +- .../SponsorImport/SponsorImportPlanner.php | 17 ++++++-- .../Model/Imp/SummitSponsorService.php | 17 +++++--- .../SponsorImportPlannerTest.php | 41 +++++++++++++++++++ .../SummitSponsorServiceImportFaultTest.php | 19 +++++++++ tests/oauth2/OAuth2SummitSponsorApiTest.php | 4 +- 6 files changed, 89 insertions(+), 12 deletions(-) diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php index 9d59287f0..34f8c9f2b 100644 --- a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -83,7 +83,8 @@ public static function key(string $name): string } /** - * NFC when intl is available; otherwise the name as given. + * NFC. Normalizer normally comes from symfony/polyfill-intl-normalizer when intl is absent, so the + * class_exists guard is only defensive. */ private static function nfc(string $name): string { diff --git a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php index bce17cb32..e9bf24df4 100644 --- a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php +++ b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php @@ -22,7 +22,8 @@ */ final class SponsorImportPlanner { - const MAX_ROWS = 500; + // a synchronous real run of 500 new companies measured ~24 s CPU against FPM's 30 s limit; 200 took ~7 s + const MAX_ROWS = 200; /** * @var CompanyNameMatcher @@ -61,7 +62,8 @@ public function plan(array $rows): array $seen = []; // identity => row number, non-error rows only foreach ($rows as $input) { $row = $this->newRow($input); - $company_name = trim($input['company']); + // NBSP too: cells pasted from web pages or Excel carry it + $company_name = preg_replace('/^[\s\x{00A0}]+|[\s\x{00A0}]+$/u', '', $input['company']); if ($company_name === '') { $planned[] = $this->fail($row, 'Company is required.'); @@ -174,7 +176,8 @@ public static function summarize(array $rows, bool $dryRun): array } /** - * Marks row $index with $action/$message and turns every later planned create into not_attempted. + * Marks row $index with $action/$message and turns every later planned create into not_attempted, + * along with any later skip_duplicate whose original row was stopped or not attempted. * @param list $rows * @param int $index * @param string $message @@ -185,9 +188,15 @@ public static function markStopped(array $rows, int $index, string $message, str { $rows[$index]['action'] = $action; $rows[$index]['error'] = $message; + $stopped = [$rows[$index]['row'] => true]; // row numbers with nothing imported $count = count($rows); for ($i = $index + 1; $i < $count; $i++) { - if ($rows[$i]['action'] === 'create') $rows[$i]['action'] = 'not_attempted'; + $action_i = $rows[$i]['action']; + if ($action_i === 'create' || + ($action_i === 'skip_duplicate' && isset($stopped[$rows[$i]['duplicate_of_row'] ?? null]))) { + $rows[$i]['action'] = 'not_attempted'; + $stopped[$rows[$i]['row']] = true; + } } return $rows; } diff --git a/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index 9c0555bee..d824abf81 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -361,11 +361,18 @@ private function executeSponsorsImport(Summit $summit, array $rows): array $company_id = $row['company']['id']; if ($row['company']['match'] === 'new') { $name = $row['company']['name']; - $company = $this->tx_service->transaction(function () use ($name) { - $company = CompanyFactory::build(['name' => $name]); - $this->company_repository->add($company, true); - return $company; - }); + try { + $company = $this->tx_service->transaction(function () use ($name) { + $company = CompanyFactory::build(['name' => $name]); + $this->company_repository->add($company, true); + return $company; + }); + } catch (AmbiguousCommitException $ex) { + Log::error(sprintf("SummitSponsorService::importSponsors summit %s row %s: %s", $summit->getId(), $row['row'], $ex->getMessage()), ['exception' => $ex]); + return SponsorImportPlanner::markStopped($rows, $index, sprintf( + 'Could not confirm whether company "%s" was saved; the import stopped here. Check the sponsor list before importing this file again.', + $name)); + } $company_id = $company->getId(); $rows[$index]['company']['id'] = $company_id; $company_created = sprintf(' Company "%s" was created.', $company->getName()); diff --git a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php index 35f7ad003..223e5753e 100644 --- a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php +++ b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php @@ -182,6 +182,47 @@ public function testMarkStoppedAsNotAttemptedForConnectionReset(): void $this->assertSame('reset', $out[0]['error']); } + public function testMarkStoppedAlsoStopsDuplicatesOfStoppedRows(): void + { + $rows = $this->planner()->plan([ + $this->row(2, 'Acme Robotics Inc', 'Gold'), + $this->row(3, 'ACME Robotics', 'Gold'), + $this->row(4, 'Beta Labs', 'Gold'), + $this->row(5, 'beta labs', 'Gold'), + $this->row(6, 'NVIDIA', 'Gold'), + ]); + $this->assertSame(['create', 'skip_duplicate', 'create', 'skip_duplicate', 'create'], array_column($rows, 'action')); + + $out = SponsorImportPlanner::markStopped($rows, 0, 'boom'); + + // row 3 duplicates the stopped row, row 5 duplicates a row that is now not_attempted + $this->assertSame(['error', 'not_attempted', 'not_attempted', 'not_attempted', 'not_attempted'], array_column($out, 'action')); + $this->assertNull($out[1]['error']); + $s = SponsorImportPlanner::summarize($out, false)['summary']; + $this->assertSame(0, $s['skipped']); + $this->assertSame(4, $s['not_attempted']); + $this->assertSame(1, $s['errors']); + } + + public function testMarkStoppedKeepsDuplicateOfRowCreatedBeforeTheStop(): void + { + $rows = $this->planner()->plan([ + $this->row(2, 'Acme Robotics Inc', 'Gold'), + $this->row(3, 'NVIDIA', 'Gold'), + $this->row(4, 'ACME Robotics', 'Gold'), + ]); + $out = SponsorImportPlanner::markStopped($rows, 1, 'boom'); + $this->assertSame(['create', 'error', 'skip_duplicate'], array_column($out, 'action')); + $this->assertSame(1, SponsorImportPlanner::summarize($out, false)['summary']['skipped']); + } + + public function testCompanyCellTrimsNbsp(): void + { + $out = $this->planner()->plan([$this->row(2, "\u{00A0}Acme\u{00A0}", 'Gold')]); + $this->assertSame('create', $out[0]['action']); + $this->assertSame(['id' => 7, 'name' => 'Acme', 'match' => 'exact'], $out[0]['company']); + } + public function testSummarizeCountsCompanyCreatedBeforeFailedSponsor(): void { $rows = [ diff --git a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php index bc9e0068e..420a14e85 100644 --- a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php +++ b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php @@ -152,6 +152,25 @@ public function testAmbiguousCommitOnSponsorStopsWithConfirmMessage(): void $this->assertGreaterThan(0, $fake->calls); } + public function testAmbiguousCommitOnCompanyStopsWithCompanyConfirmMessage(): void + { + Queue::fake(); + // call 1 = row 1 company + $fake = $this->bindFake(1, new AmbiguousCommitException('x'), false); + + $report = $this->importThreeNewCompanies(); + + $this->assertLaterRowsNotAttempted($report); + $row = $report['rows'][0]; + $this->assertSame(sprintf( + 'Could not confirm whether company "%s" was saved; the import stopped here. Check the sponsor list before importing this file again.', + $this->names[0]), $row['error']); + $this->assertNull($row['company']['id']); + $this->assertSame(0, $report['summary']['companies_created']); + $this->assertSame(1, $fake->calls); + Queue::assertNotPushed(PublishSponsorServiceDomainEventsJob::class); + } + public function testDetachAfterCompanyCreationStopsBeforeAddSponsor(): void { Queue::fake(); diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index 0ab0d3c77..ec541aa14 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -2044,10 +2044,10 @@ public function testImportValidationDuplicateNormalizedHeader(){ public function testImportValidationTooManyRows(){ $csv = "company,tier\n"; - for ($i = 0; $i < 501; $i++) $csv .= "Company {$i},Default\n"; + for ($i = 0; $i < 201; $i++) $csv .= "Company {$i},Default\n"; $response = $this->importCsv($csv, true); $this->assertResponseStatus(412); - $this->assertStringContainsString('501 rows', $response->getContent()); + $this->assertStringContainsString('201 rows', $response->getContent()); } public function testImportValidationNotUtf8(){ From 5f4dc1a277c54b9b04bb87f543b072e38e1d747e Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 13:29:19 -0600 Subject: [PATCH 09/15] refactor(sponsors): align sponsor import with summit-api conventions --- .../OAuth2SummitSponsorApiController.php | 55 +++-------------- app/Services/Model/ISummitSponsorService.php | 3 + .../SponsorImport/SponsorImportPlanner.php | 15 ++--- .../Model/Imp/SummitSponsorService.php | 4 +- app/Swagger/SponsorSchemas.php | 61 +++++++++++++++++++ tests/oauth2/OAuth2SummitSponsorApiTest.php | 23 +++++++ 6 files changed, 102 insertions(+), 59 deletions(-) diff --git a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php index 6a1d0837d..a78acf9c0 100644 --- a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php +++ b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php @@ -647,60 +647,16 @@ public function addV2($summit_id){ required: true, content: new OA\MediaType( mediaType: 'multipart/form-data', - schema: new OA\Schema( - type: 'object', - required: ['file'], - properties: [ - new OA\Property( - property: 'file', - type: 'string', - format: 'binary', - description: 'UTF-8 CSV file with company and tier columns' - ), - new OA\Property( - property: 'dry_run', - type: 'boolean', - description: 'Plan only, write nothing' - ), - ] - ) + schema: new OA\Schema(ref: '#/components/schemas/SponsorImportRequest') ) ), responses: [ new OA\Response( response: Response::HTTP_OK, description: 'Per-row import report', - content: new OA\JsonContent( - type: 'object', - properties: [ - new OA\Property(property: 'dry_run', type: 'boolean'), - new OA\Property(property: 'summary', type: 'object', properties: [ - new OA\Property(property: 'total', type: 'integer'), - new OA\Property(property: 'sponsors_created', type: 'integer'), - new OA\Property(property: 'companies_created', type: 'integer'), - new OA\Property(property: 'skipped', type: 'integer'), - new OA\Property(property: 'errors', type: 'integer'), - new OA\Property(property: 'not_attempted', type: 'integer'), - ]), - new OA\Property(property: 'rows', type: 'array', items: new OA\Items(type: 'object', properties: [ - new OA\Property(property: 'row', type: 'integer'), - new OA\Property(property: 'company_input', type: 'string'), - new OA\Property(property: 'tier_input', type: 'string'), - new OA\Property(property: 'action', type: 'string', enum: ['create', 'skip_existing_sponsor', 'skip_duplicate', 'error', 'not_attempted']), - new OA\Property(property: 'company', type: 'object', nullable: true, properties: [ - new OA\Property(property: 'id', type: 'integer', nullable: true), - new OA\Property(property: 'name', type: 'string'), - new OA\Property(property: 'match', type: 'string', enum: ['exact', 'normalized', 'new']), - ]), - new OA\Property(property: 'tiers', type: 'array', items: new OA\Items(type: 'string')), - new OA\Property(property: 'sponsor_id', type: 'integer', nullable: true), - new OA\Property(property: 'duplicate_of_row', type: 'integer', nullable: true), - new OA\Property(property: 'candidates', type: 'array', items: new OA\Items(type: 'string')), - new OA\Property(property: 'error', type: 'string', nullable: true), - ])), - ] - ) + content: new OA\JsonContent(ref: '#/components/schemas/SponsorImportReport') ), + new OA\Response(response: Response::HTTP_BAD_REQUEST, description: "Bad Request"), new OA\Response(response: Response::HTTP_UNAUTHORIZED, description: "Unauthorized"), new OA\Response(response: Response::HTTP_FORBIDDEN, description: "Forbidden"), new OA\Response(response: Response::HTTP_NOT_FOUND, description: "Not Found"), @@ -728,7 +684,10 @@ public function import(LaravelRequest $request, $summit_id) if (!$is_authz) throw new HTTP403ForbiddenException("You are not allowed to perform this action."); - $validation = Validator::make($request->all(), ['file' => 'required|file']); + $validation = Validator::make($request->all(), [ + 'file' => 'required|file', + 'dry_run' => 'sometimes|boolean', + ]); if ($validation->fails()) { throw new ValidationException($validation->messages()->toArray()); } diff --git a/app/Services/Model/ISummitSponsorService.php b/app/Services/Model/ISummitSponsorService.php index aa35c8d2b..5179c9a00 100644 --- a/app/Services/Model/ISummitSponsorService.php +++ b/app/Services/Model/ISummitSponsorService.php @@ -39,6 +39,9 @@ interface ISummitSponsorService */ const ImportTierSeparator = '|'; + // a synchronous real run of 500 new companies measured ~24 s CPU against FPM's 30 s limit; 200 took ~7 s + const ImportMaxRows = 200; + /** * @param Summit $summit * @param array $payload diff --git a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php index e9bf24df4..70995a088 100644 --- a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php +++ b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php @@ -22,9 +22,6 @@ */ final class SponsorImportPlanner { - // a synchronous real run of 500 new companies measured ~24 s CPU against FPM's 30 s limit; 200 took ~7 s - const MAX_ROWS = 200; - /** * @var CompanyNameMatcher */ @@ -43,13 +40,13 @@ final class SponsorImportPlanner /** * @param CompanyNameMatcher $matcher * @param array $tiers - * @param list $sponsorCompanyIds + * @param list $sponsor_company_ids */ - public function __construct(CompanyNameMatcher $matcher, array $tiers, array $sponsorCompanyIds) + public function __construct(CompanyNameMatcher $matcher, array $tiers, array $sponsor_company_ids) { $this->matcher = $matcher; $this->tiers = $tiers; - $this->sponsor_company_ids = array_fill_keys(array_map('intval', $sponsorCompanyIds), true); + $this->sponsor_company_ids = array_fill_keys(array_map('intval', $sponsor_company_ids), true); } /** @@ -146,10 +143,10 @@ public function plan(array $rows): array /** * @param list $rows - * @param bool $dryRun + * @param bool $dry_run * @return array{dry_run:bool,summary:array} */ - public static function summarize(array $rows, bool $dryRun): array + public static function summarize(array $rows, bool $dry_run): array { $summary = [ 'total' => count($rows), @@ -172,7 +169,7 @@ public static function summarize(array $rows, bool $dryRun): array $summary['companies_created']++; } } - return ['dry_run' => $dryRun, 'summary' => $summary]; + return ['dry_run' => $dry_run, 'summary' => $summary]; } /** diff --git a/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index d824abf81..cfcec8e4f 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -330,8 +330,8 @@ private function parseSponsorsCsv(UploadedFile $file): array throw new ValidationException("CSV is not valid."); } - if (count($rows) > SponsorImportPlanner::MAX_ROWS) - throw new ValidationException(sprintf("File has %d rows; the maximum is %d.", count($rows), SponsorImportPlanner::MAX_ROWS)); + if (count($rows) > ISummitSponsorService::ImportMaxRows) + throw new ValidationException(sprintf("File has %d rows; the maximum is %d.", count($rows), ISummitSponsorService::ImportMaxRows)); return $rows; } diff --git a/app/Swagger/SponsorSchemas.php b/app/Swagger/SponsorSchemas.php index dcad40830..34d4c428d 100644 --- a/app/Swagger/SponsorSchemas.php +++ b/app/Swagger/SponsorSchemas.php @@ -270,3 +270,64 @@ class PaginatedSponsorV2ResponseSchema {} ] )] class SponsorServicesStatisticsUpsertRequestSchema {} + +#[OA\Schema( + schema: 'SponsorImportRequest', + type: 'object', + description: 'Request to import sponsors from a UTF-8 CSV file with company and tier columns (tiers separated by |)', + required: ['file'], + properties: [ + new OA\Property(property: 'file', type: 'string', format: 'binary', description: 'CSV file with company and tier columns'), + new OA\Property(property: 'dry_run', type: 'boolean', description: 'Plan only, write nothing'), + ] +)] +class SponsorImportRequestSchema {} + +#[OA\Schema( + schema: 'SponsorImportReportRow', + type: 'object', + properties: [ + new OA\Property(property: 'row', type: 'integer', example: 2), + new OA\Property(property: 'company_input', type: 'string', example: 'Acme Robotics'), + new OA\Property(property: 'tier_input', type: 'string', example: 'Gold|Silver'), + new OA\Property(property: 'action', type: 'string', enum: ['create', 'skip_existing_sponsor', 'skip_duplicate', 'error', 'not_attempted']), + new OA\Property( + property: 'company', + type: 'object', + nullable: true, + properties: [ + new OA\Property(property: 'id', type: 'integer', nullable: true), + new OA\Property(property: 'name', type: 'string'), + new OA\Property(property: 'match', type: 'string', enum: ['exact', 'normalized', 'new']), + ] + ), + new OA\Property(property: 'tiers', type: 'array', items: new OA\Items(type: 'string')), + new OA\Property(property: 'sponsor_id', type: 'integer', nullable: true), + new OA\Property(property: 'duplicate_of_row', type: 'integer', nullable: true), + new OA\Property(property: 'candidates', type: 'array', items: new OA\Items(type: 'string')), + new OA\Property(property: 'error', type: 'string', nullable: true), + ] +)] +class SponsorImportReportRowSchema {} + +#[OA\Schema( + schema: 'SponsorImportReport', + type: 'object', + properties: [ + new OA\Property(property: 'dry_run', type: 'boolean'), + new OA\Property( + property: 'summary', + type: 'object', + properties: [ + new OA\Property(property: 'total', type: 'integer'), + new OA\Property(property: 'sponsors_created', type: 'integer'), + new OA\Property(property: 'companies_created', type: 'integer'), + new OA\Property(property: 'skipped', type: 'integer'), + new OA\Property(property: 'errors', type: 'integer'), + new OA\Property(property: 'not_attempted', type: 'integer'), + ] + ), + new OA\Property(property: 'rows', type: 'array', items: new OA\Items(ref: '#/components/schemas/SponsorImportReportRow')), + ] +)] +class SponsorImportReportSchema {} diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index ec541aa14..cc8c0cb6c 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -2050,6 +2050,29 @@ public function testImportValidationTooManyRows(){ $this->assertStringContainsString('201 rows', $response->getContent()); } + public function testImportValidationRejectsNonBooleanDryRun(){ + $new_name = $this->newCompanyName(); + $sponsors_before = self::$summit->getSummitSponsors()->count(); + $summit_id = self::$summit->getId(); + + // a typo must not fall through to a real import + $response = $this->action( + "POST", + "OAuth2SummitSponsorApiController@import", + ['id' => $summit_id], + ['dry_run' => 'ture'], + [], + ['file' => $this->buildCsvFile("company,tier\n\"{$new_name}\",Default\n")], + ["HTTP_Authorization" => " Bearer " . $this->access_token] + ); + $this->assertResponseStatus(412); + $this->assertStringContainsString('dry run', $response->getContent()); + + $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + $this->assertNull($em->getRepository(Company::class)->findOneBy(['name' => $new_name])); + $this->assertSame($sponsors_before, $em->find(Summit::class, $summit_id)->getSummitSponsors()->count()); + } + public function testImportValidationNotUtf8(){ // Excel's plain "CSV (comma delimited)" export is cp1252 $response = $this->importCsv("company,tier\nCaf\xE9 Ltd,Default\n", true); From 36e0c78ac2dc897057ef2a40939f3c61be481f7a Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 14:50:46 -0600 Subject: [PATCH 10/15] test(sponsors): tighten import tests and trim comments --- .../Imp/SponsorImport/CompanyNameMatcher.php | 5 +- ...DoctrineCompanyRepositoryIdAndNameTest.php | 3 -- .../SponsorImport/CompanyNameMatcherTest.php | 1 - .../SponsorImportPlannerTest.php | 38 ++++++-------- .../SummitSponsorServiceImportFaultTest.php | 21 +++++++- tests/oauth2/OAuth2SummitSponsorApiTest.php | 50 +++++++++---------- 6 files changed, 62 insertions(+), 56 deletions(-) diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php index 34f8c9f2b..a0ce0afeb 100644 --- a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -82,10 +82,7 @@ public static function key(string $name): string return implode(' ', $words); } - /** - * NFC. Normalizer normally comes from symfony/polyfill-intl-normalizer when intl is absent, so the - * class_exists guard is only defensive. - */ + // class_exists is defensive: symfony/polyfill-intl-normalizer supplies Normalizer without intl private static function nfc(string $name): string { if (!class_exists(\Normalizer::class)) return $name; diff --git a/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php index 459a0ad8f..4bbf9c4d7 100644 --- a/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php +++ b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php @@ -69,8 +69,5 @@ public function testGetAllIdAndNameReturnsScalarPairs(): void foreach ($this->companies as $company) { $this->assertContains(['id' => $company->getId(), 'name' => $company->getName()], $rows); } - foreach ($rows as $row) { - $this->assertIsInt($row['id']); - } } } diff --git a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php index a33fe5e82..1310c0a49 100644 --- a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php +++ b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php @@ -46,7 +46,6 @@ public function testNfcAndNullNames(): void $m = new CompanyNameMatcher([['id' => 1, 'name' => "Cafe\u{0301} Corp"], ['id' => 2, 'name' => null], ['id' => 3, 'name' => ' ']]); // precomposed input matches decomposed stored name (exact) $this->assertSame(['match' => 'exact', 'id' => 1, 'name' => "Cafe\u{0301} Corp", 'ids' => [1]], $m->resolve("Café Corp")); - // and the reverse direction $r = new CompanyNameMatcher([['id' => 4, 'name' => "Café Corp"]]); $this->assertSame(['match' => 'exact', 'id' => 4, 'name' => "Café Corp", 'ids' => [4]], $r->resolve("Cafe\u{0301} Corp")); $this->assertSame(['match' => 'none'], $m->resolve('')); diff --git a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php index 223e5753e..935dc1424 100644 --- a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php +++ b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php @@ -45,18 +45,19 @@ private function row(int $n, string $company, string $tier): array public function testCreatesWithExactMatchAndCanonicalTierNames(): void { $out = $this->planner()->plan([$this->row(2, 'acme', 'gold|SILVER')]); - $r = $out[0]; - $this->assertSame('create', $r['action']); - $this->assertSame(['id' => 7, 'name' => 'Acme', 'match' => 'exact'], $r['company']); - $this->assertSame(['Gold', 'Silver'], $r['tiers']); - $this->assertSame([1, 2], $r['tier_ids']); - $this->assertSame(2, $r['row']); - $this->assertSame('acme', $r['company_input']); - $this->assertSame('gold|SILVER', $r['tier_input']); - $this->assertNull($r['sponsor_id']); - $this->assertNull($r['duplicate_of_row']); - $this->assertSame([], $r['candidates']); - $this->assertNull($r['error']); + $this->assertSame([ + 'row' => 2, + 'company_input' => 'acme', + 'tier_input' => 'gold|SILVER', + 'action' => 'create', + 'company' => ['id' => 7, 'name' => 'Acme', 'match' => 'exact'], + 'tiers' => ['Gold', 'Silver'], + 'sponsor_id' => null, + 'duplicate_of_row' => null, + 'candidates' => [], + 'error' => null, + 'tier_ids' => [1, 2], + ], $out[0]); } public function testMissingCompanyOrTierIsError(): void @@ -169,17 +170,10 @@ public function testMarkStoppedErrorsRowAndMarksLaterCreatesNotAttempted(): void $this->assertNull($out[0]['error']); $this->assertSame('Tier is required.', $out[2]['error']); $this->assertNull($out[3]['error']); - } - public function testMarkStoppedAsNotAttemptedForConnectionReset(): void - { - $rows = [ - ['row' => 2, 'action' => 'create', 'error' => null], - ['row' => 3, 'action' => 'create', 'error' => null], - ]; - $out = SponsorImportPlanner::markStopped($rows, 0, 'reset', 'not_attempted'); - $this->assertSame(['not_attempted', 'not_attempted'], array_column($out, 'action')); - $this->assertSame('reset', $out[0]['error']); + $reset = SponsorImportPlanner::markStopped($rows, 1, 'reset', 'not_attempted'); + $this->assertSame(['create', 'not_attempted', 'error', 'not_attempted'], array_column($reset, 'action')); + $this->assertSame('reset', $reset[1]['error']); } public function testMarkStoppedAlsoStopsDuplicatesOfStoppedRows(): void diff --git a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php index 420a14e85..20694c6ab 100644 --- a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php +++ b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php @@ -71,6 +71,7 @@ class SummitSponsorServiceImportFaultTest extends TestCase use InsertSummitTestData; const ConnectionResetMessage = 'The import stopped because the database connection was reset. Rows below were not imported.'; + const CouldNotCreateMessage = 'Could not create this sponsor; the import stopped here. Rows below were not imported.'; const CouldNotConfirmMessage = 'Could not confirm whether this sponsor was saved; the import stopped here. Check the sponsor list before importing this file again.'; /** @@ -149,7 +150,25 @@ public function testAmbiguousCommitOnSponsorStopsWithConfirmMessage(): void $this->assertGreaterThan(0, $row['company']['id']); $this->assertNull($row['sponsor_id']); $this->assertSame(1, $report['summary']['companies_created']); - $this->assertGreaterThan(0, $fake->calls); + $this->assertSame(2, $fake->calls); + } + + public function testWriteFailureOnSponsorStopsWithCouldNotCreateMessage(): void + { + Queue::fake(); + // call 1 = row 1 company, call 2 = row 1 addSponsor + $fake = $this->bindFake(2, new \RuntimeException('x'), false); + + $report = $this->importThreeNewCompanies(); + + $this->assertLaterRowsNotAttempted($report); + $row = $report['rows'][0]; + $this->assertStringContainsString('Could not create this sponsor; the import stopped here', $row['error']); + $this->assertSame(self::CouldNotCreateMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); + $this->assertNull($row['sponsor_id']); + $this->assertSame(1, $report['summary']['companies_created']); + $this->assertSame(3, $report['summary']['total']); + $this->assertSame(2, $fake->calls); } public function testAmbiguousCommitOnCompanyStopsWithCompanyConfirmMessage(): void diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index cc8c0cb6c..a7ad59951 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -1867,9 +1867,6 @@ private function removeImportedCompanies(): void foreach ($em->getRepository(Company::class)->findBy(['name' => $name]) as $company) { $em->remove($company); } - foreach ($em->getRepository(Company::class)->findBy(['name' => $name . ', Inc.']) as $company) { - $em->remove($company); - } } $em->flush(); $this->imported_company_names = []; @@ -1990,9 +1987,9 @@ public function testDryRunMatchesRealRun(){ } public function testImportHandlesExcelQuirks(){ - Queue::fake(); $name = $this->newCompanyName(); - $content = "\xEF\xBB\xBF Company ,TIER\r\n\"{$name}, Inc.\",Default\r\n\r\n"; + // ",\r\n" is Excel's formatted-but-empty row: League keeps it, the import must skip it + $content = "\xEF\xBB\xBF Company ,TIER\r\n\"{$name}, Inc.\",Default\r\n,\r\n\r\n"; $response = $this->importCsv($content, true); $this->assertResponseStatus(200); @@ -2013,12 +2010,11 @@ public function testImportRecognizesHeaderWithTrailingNbsp(){ $this->assertSame(['create'], array_column($report['rows'], 'action')); } - public function testImportInvalidCsvDoesNotEchoLibraryMessage(){ - // identical raw headers make League throw; its message names the header - $response = $this->importCsv("company,tier,y,y\nAcme,Default,1,2\n", true); + public function testImportInvalidCsvIs412(){ + // identical raw headers make League throw + $response = $this->importCsv("company,tier,y,y\nAcme,Default,1,2\n", true); $this->assertResponseStatus(412); $this->assertStringContainsString('CSV is not valid.', $response->getContent()); - $this->assertStringNotContainsString('', $response->getContent()); } public function testImportIgnoresDuplicateExtraColumnsWithoutEchoingThem(){ @@ -2043,34 +2039,38 @@ public function testImportValidationDuplicateNormalizedHeader(){ } public function testImportValidationTooManyRows(){ - $csv = "company,tier\n"; - for ($i = 0; $i < 201; $i++) $csv .= "Company {$i},Default\n"; - $response = $this->importCsv($csv, true); + $max = ISummitSponsorService::ImportMaxRows; + $response = $this->importCsv($this->rowsCsv($max + 1), true); $this->assertResponseStatus(412); - $this->assertStringContainsString('201 rows', $response->getContent()); + $this->assertStringContainsString(sprintf('File has %d rows; the maximum is %d.', $max + 1, $max), $response->getContent()); } - public function testImportValidationRejectsNonBooleanDryRun(){ - $new_name = $this->newCompanyName(); - $sponsors_before = self::$summit->getSummitSponsors()->count(); - $summit_id = self::$summit->getId(); + public function testImportAcceptsExactlyMaxRows(){ + $response = $this->importCsv($this->rowsCsv(ISummitSponsorService::ImportMaxRows), true); + $this->assertResponseStatus(200); + $report = json_decode($response->getContent(), true); + $this->assertSame(ISummitSponsorService::ImportMaxRows, $report['summary']['total']); + } + private function rowsCsv(int $count): string + { + $csv = "company,tier\n"; + for ($i = 0; $i < $count; $i++) $csv .= "Company {$i},Default\n"; + return $csv; + } + + public function testImportValidationRejectsNonBooleanDryRun(){ // a typo must not fall through to a real import - $response = $this->action( + $this->action( "POST", "OAuth2SummitSponsorApiController@import", - ['id' => $summit_id], + ['id' => self::$summit->getId()], ['dry_run' => 'ture'], [], - ['file' => $this->buildCsvFile("company,tier\n\"{$new_name}\",Default\n")], + ['file' => $this->buildCsvFile("company,tier\n\"{$this->newCompanyName()}\",Default\n")], ["HTTP_Authorization" => " Bearer " . $this->access_token] ); $this->assertResponseStatus(412); - $this->assertStringContainsString('dry run', $response->getContent()); - - $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); - $this->assertNull($em->getRepository(Company::class)->findOneBy(['name' => $new_name])); - $this->assertSame($sponsors_before, $em->find(Summit::class, $summit_id)->getSummitSponsors()->count()); } public function testImportValidationNotUtf8(){ From 96976e952ae5e211496fc54f87c1be1c2e74c37f Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 14:56:15 -0600 Subject: [PATCH 11/15] test(sponsors): assert an invalid dry_run writes nothing --- tests/oauth2/OAuth2SummitSponsorApiTest.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index a7ad59951..34fb52ca2 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -2061,16 +2061,23 @@ private function rowsCsv(int $count): string public function testImportValidationRejectsNonBooleanDryRun(){ // a typo must not fall through to a real import + $new_name = $this->newCompanyName(); + $sponsors_before = self::$summit->getSummitSponsors()->count(); + $summit_id = self::$summit->getId(); $this->action( "POST", "OAuth2SummitSponsorApiController@import", - ['id' => self::$summit->getId()], + ['id' => $summit_id], ['dry_run' => 'ture'], [], - ['file' => $this->buildCsvFile("company,tier\n\"{$this->newCompanyName()}\",Default\n")], + ['file' => $this->buildCsvFile("company,tier\n\"{$new_name}\",Default\n")], ["HTTP_Authorization" => " Bearer " . $this->access_token] ); $this->assertResponseStatus(412); + + $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); + $this->assertNull($em->getRepository(Company::class)->findOneBy(['name' => $new_name])); + $this->assertSame($sponsors_before, $em->find(Summit::class, $summit_id)->getSummitSponsors()->count()); } public function testImportValidationNotUtf8(){ From 48f0e2f5879c4cea8772b509d56251aed64167ee Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 15:21:37 -0600 Subject: [PATCH 12/15] fix(sponsors): keep combining marks and trim NBSP in company keys, document dry_run as 0/1 --- .../Model/Imp/SponsorImport/CompanyNameMatcher.php | 5 +++-- app/Swagger/SponsorSchemas.php | 2 +- .../Services/SponsorImport/CompanyNameMatcherTest.php | 11 +++++++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php index a0ce0afeb..b657bcf6d 100644 --- a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -73,7 +73,7 @@ public static function key(string $name): string { $s = self::nfc($name); $s = mb_strtolower($s); - $s = trim(preg_replace('/[^\p{L}\p{N}]+/u', ' ', $s)); + $s = trim(preg_replace('/[^\p{L}\p{M}\p{N}]+/u', ' ', $s)); if ($s === '') return ''; $words = explode(' ', $s); while (count($words) > 1 && in_array(end($words), self::LegalSuffixes, true)) { @@ -93,7 +93,8 @@ private static function nfc(string $name): string private static function exactKey(string $name): string { $s = self::nfc($name); - return mb_strtolower(trim($s)); + // same trim as CSV cells, so NBSP padding on a stored name can't defeat the exact match + return mb_strtolower(preg_replace('/^[\s\x{00A0}]+|[\s\x{00A0}]+$/u', '', $s)); } public function resolve(string $name): array diff --git a/app/Swagger/SponsorSchemas.php b/app/Swagger/SponsorSchemas.php index 34d4c428d..2df3d73ed 100644 --- a/app/Swagger/SponsorSchemas.php +++ b/app/Swagger/SponsorSchemas.php @@ -278,7 +278,7 @@ class SponsorServicesStatisticsUpsertRequestSchema {} required: ['file'], properties: [ new OA\Property(property: 'file', type: 'string', format: 'binary', description: 'CSV file with company and tier columns'), - new OA\Property(property: 'dry_run', type: 'boolean', description: 'Plan only, write nothing'), + new OA\Property(property: 'dry_run', type: 'integer', enum: [0, 1], description: 'Send 1 to plan only and write nothing, 0 (default) to import. true/false strings are rejected.'), ] )] class SponsorImportRequestSchema {} diff --git a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php index 1310c0a49..f2f37af5d 100644 --- a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php +++ b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php @@ -32,6 +32,17 @@ public function testKeyStripsPunctuationAndRepeatedSuffixes(): void $this->assertSame('münchen', CompanyNameMatcher::key('MÜNCHEN GMBH')); } + public function testKeyKeepsCombiningMarks(): void + { + $this->assertNotSame(CompanyNameMatcher::key('कला'), CompanyNameMatcher::key('कली')); + } + + public function testExactKeyIgnoresNbspPaddingOnStoredNames(): void + { + $m = new CompanyNameMatcher([['id' => 1, 'name' => "Acme\u{00A0}"], ['id' => 2, 'name' => 'Acme Inc']]); + $this->assertSame(['match' => 'exact', 'id' => 1, 'name' => "Acme\u{00A0}", 'ids' => [1]], $m->resolve('Acme')); + } + public function testExactWinsOverNormalizedAndLowestIdBreaksTies(): void { $m = new CompanyNameMatcher([ From bde67d12b4793baa617124afe3d6923ab6bb13b1 Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Sun, 15 Nov 2026 15:50:31 -0600 Subject: [PATCH 13/15] fix(sponsors): skip tiers whose sponsorship type was deleted during import --- .../Foundation/Summit/SummitSponsorshipType.php | 8 ++++++++ app/Services/Model/Imp/SummitSponsorService.php | 4 ++-- tests/oauth2/OAuth2SummitSponsorApiTest.php | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/Models/Foundation/Summit/SummitSponsorshipType.php b/app/Models/Foundation/Summit/SummitSponsorshipType.php index 94d72a2ef..c474bd016 100644 --- a/app/Models/Foundation/Summit/SummitSponsorshipType.php +++ b/app/Models/Foundation/Summit/SummitSponsorshipType.php @@ -397,6 +397,14 @@ public function getType(): SponsorshipType return $this->type; } + /** + * @return bool + */ + public function hasType(): bool + { + return !is_null($this->type); + } + /** * @param SponsorshipType $type */ diff --git a/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index cfcec8e4f..68c3a2973 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -247,9 +247,9 @@ public function importSponsors(Summit $summit, UploadedFile $file, bool $dry_run $tiers = []; foreach ($summit->getSummitSponsorshipTypes() as $summit_sponsorship_type) { - if (!$summit_sponsorship_type instanceof SummitSponsorshipType) continue; + // the type FK is SET NULL on delete, and getType() is not nullable + if (!$summit_sponsorship_type instanceof SummitSponsorshipType || !$summit_sponsorship_type->hasType()) continue; $type = $summit_sponsorship_type->getType(); - if (is_null($type)) continue; $tiers[mb_strtolower($type->getName())] = ['id' => $summit_sponsorship_type->getId(), 'name' => $type->getName()]; } diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index 34fb52ca2..664671a6a 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -24,6 +24,7 @@ use models\main\Company; use models\summit\Sponsor; use models\summit\Summit; +use models\summit\SummitSponsorshipType; use models\utils\SilverstripeBaseModel; use services\model\ISummitSponsorService; /** @@ -1986,6 +1987,19 @@ public function testDryRunMatchesRealRun(){ $this->assertSame(1, $real['summary']['companies_created']); } + public function testImportSkipsTierWhoseSponsorshipTypeWasDeleted(){ + $em = Registry::getManager(SilverstripeBaseModel::EntityManager); + $orphan = new SummitSponsorshipType(); + self::$summit->addSponsorshipType($orphan); + $em->persist($orphan); + $em->flush(); + + $response = $this->importCsv("company,tier\n\"{$this->newCompanyName()}\",Default\n", true); + $this->assertResponseStatus(200); + $report = json_decode($response->getContent(), true); + $this->assertSame('create', $report['rows'][0]['action']); + } + public function testImportHandlesExcelQuirks(){ $name = $this->newCompanyName(); // ",\r\n" is Excel's formatted-but-empty row: League keeps it, the import must skip it From 051b41e029175a969b0b8c739a22a99c66bad6ae Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Mon, 16 Nov 2026 11:58:58 -0600 Subject: [PATCH 14/15] fix(sponsors): skip failed import rows, lock real runs, cap upload size - addSponsor resolves the summit by id inside each transaction attempt, so a retry on a fresh EntityManager persists the sponsor, and it refuses to publish events for a sponsor id of 0 - the import logs and skips a failed row and continues; only an ambiguous commit stops the run - real runs are serialized per summit with ILockManagerService; a concurrent run gets a 412, dry runs take no lock - uploads are limited to 1 MB and the 200-row cap is enforced while parsing --- .../OAuth2SummitSponsorApiController.php | 4 +- app/Services/Model/ISummitSponsorService.php | 6 + .../SponsorImport/SponsorImportPlanner.php | 28 +++- .../Model/Imp/SummitSponsorService.php | 101 +++++++++----- app/Swagger/SponsorSchemas.php | 2 +- .../SponsorImportPlannerTest.php | 20 ++- .../SummitSponsorServiceImportFaultTest.php | 127 ++++++++++-------- tests/oauth2/OAuth2SummitSponsorApiTest.php | 31 ++++- 8 files changed, 217 insertions(+), 102 deletions(-) diff --git a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php index a78acf9c0..4148ef198 100644 --- a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php +++ b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php @@ -660,7 +660,7 @@ public function addV2($summit_id){ new OA\Response(response: Response::HTTP_UNAUTHORIZED, description: "Unauthorized"), new OA\Response(response: Response::HTTP_FORBIDDEN, description: "Forbidden"), new OA\Response(response: Response::HTTP_NOT_FOUND, description: "Not Found"), - new OA\Response(response: Response::HTTP_PRECONDITION_FAILED, description: "Validation Error"), + new OA\Response(response: Response::HTTP_PRECONDITION_FAILED, description: "Validation Error, or another import is already running for this summit"), new OA\Response(response: Response::HTTP_INTERNAL_SERVER_ERROR, description: "Server Error") ] )] @@ -685,7 +685,7 @@ public function import(LaravelRequest $request, $summit_id) throw new HTTP403ForbiddenException("You are not allowed to perform this action."); $validation = Validator::make($request->all(), [ - 'file' => 'required|file', + 'file' => 'required|file|max:' . ISummitSponsorService::ImportMaxFileSizeKB, 'dry_run' => 'sometimes|boolean', ]); if ($validation->fails()) { diff --git a/app/Services/Model/ISummitSponsorService.php b/app/Services/Model/ISummitSponsorService.php index 5179c9a00..81757d113 100644 --- a/app/Services/Model/ISummitSponsorService.php +++ b/app/Services/Model/ISummitSponsorService.php @@ -42,6 +42,12 @@ interface ISummitSponsorService // a synchronous real run of 500 new companies measured ~24 s CPU against FPM's 30 s limit; 200 took ~7 s const ImportMaxRows = 200; + // rejected before parsing; 200 rows of company,tier is far below this + const ImportMaxFileSizeKB = 1024; + + // seconds; matches php-fpm's request_terminate_timeout, so a killed request does not hold the lock for long + const ImportLockLifetime = 300; + /** * @param Summit $summit * @param array $payload diff --git a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php index 70995a088..8cbf3e6db 100644 --- a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php +++ b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php @@ -173,17 +173,37 @@ public static function summarize(array $rows, bool $dry_run): array } /** - * Marks row $index with $action/$message and turns every later planned create into not_attempted, + * Marks row $index as an error with $message, and turns any later skip_duplicate of it into not_attempted. + * @param list $rows + * @param int $index + * @param string $message + * @return list + */ + public static function markFailed(array $rows, int $index, string $message): array + { + $rows[$index]['action'] = 'error'; + $rows[$index]['error'] = $message; + $failed_row = $rows[$index]['row']; + $count = count($rows); + for ($i = $index + 1; $i < $count; $i++) { + if ($rows[$i]['action'] === 'skip_duplicate' && ($rows[$i]['duplicate_of_row'] ?? null) === $failed_row) { + $rows[$i]['action'] = 'not_attempted'; + } + } + return $rows; + } + + /** + * Marks row $index as an error with $message and turns every later planned create into not_attempted, * along with any later skip_duplicate whose original row was stopped or not attempted. * @param list $rows * @param int $index * @param string $message - * @param string $action * @return list */ - public static function markStopped(array $rows, int $index, string $message, string $action = 'error'): array + public static function markStopped(array $rows, int $index, string $message): array { - $rows[$index]['action'] = $action; + $rows[$index]['action'] = 'error'; $rows[$index]['error'] = $message; $stopped = [$rows[$index]['row'] => true]; // row numbers with nothing imported $count = count($rows); diff --git a/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index 68c3a2973..8c4643e5b 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -39,10 +39,11 @@ use App\Services\Model\Imp\ExtraQuestionTypeService; use App\Services\Model\Imp\SponsorImport\CompanyNameMatcher; use App\Services\Model\Imp\SponsorImport\SponsorImportPlanner; -use LaravelDoctrine\ORM\Facades\Registry; +use App\Services\Utils\Exceptions\UnacquiredLockException; +use App\Services\Utils\ILockManagerService; use League\Csv\Reader; use League\Csv\UnableToProcessCsv; -use models\utils\SilverstripeBaseModel; +use models\summit\ISummitRepository; use services\utils\AmbiguousCommitException; use Doctrine\Common\Collections\ArrayCollection; use Illuminate\Http\UploadedFile; @@ -105,6 +106,16 @@ final class SummitSponsorService */ private $audit_log_repository; + /** + * @var ISummitRepository + */ + private $summit_repository; + + /** + * @var ILockManagerService + */ + private $lock_service; + /** * @param IMemberRepository $member_repository * @param ICompanyRepository $company_repository @@ -113,6 +124,8 @@ final class SummitSponsorService * @param ISponsorUserInfoGrantRepository $user_info_grant_repository * @param IFileUploader $file_uploader * @param IAuditLogRepository $audit_log_repository + * @param ISummitRepository $summit_repository + * @param ILockManagerService $lock_service * @param ITransactionService $tx_service */ public function __construct @@ -124,10 +137,14 @@ public function __construct ISponsorUserInfoGrantRepository $user_info_grant_repository, IFileUploader $file_uploader, IAuditLogRepository $audit_log_repository, + ISummitRepository $summit_repository, + ILockManagerService $lock_service, ITransactionService $tx_service ) { parent::__construct($tx_service); + $this->summit_repository = $summit_repository; + $this->lock_service = $lock_service; $this->audit_log_repository = $audit_log_repository; $this->user_info_grant_repository = $user_info_grant_repository; $this->member_repository = $member_repository; @@ -146,7 +163,13 @@ public function __construct */ public function addSponsor(Summit $summit, array $payload): Sponsor { - [$sponsor, $new_sponsorships] = $this->tx_service->transaction(function () use ($summit, $payload) { + $summit_id = $summit->getId(); + [$sponsor, $new_sponsorships] = $this->tx_service->transaction(function () use ($summit_id, $payload) { + // resolved per attempt: a retried transaction runs on a fresh EntityManager, where a captured summit is detached + $summit = $this->summit_repository->getById($summit_id); + if (!$summit instanceof Summit) + throw new EntityNotFoundException("Summit not found."); + $company_id = intval($payload['company_id']); $featured_event_id = isset($payload['featured_event_id']) ? intval($payload['featured_event_id']) : 0; @@ -205,6 +228,10 @@ public function addSponsor(Summit $summit, array $payload): Sponsor return [$sponsor, $new_sponsorships]; }); + // never publish an id of 0 to sponsor services + if ($sponsor->getId() <= 0) + throw new \RuntimeException("SummitSponsorService::addSponsor sponsor was not persisted; domain events not published."); + try { PublishSponsorServiceDomainEventsJob::dispatch( SummitSponsorCreatedEventDTO::fromSummitSponsor($sponsor)->serialize(), @@ -245,6 +272,30 @@ public function importSponsors(Summit $summit, UploadedFile $file, bool $dry_run $rows = $this->parseSponsorsCsv($file); + if ($dry_run) { + return $this->planAndRunSponsorsImport($summit, $rows, true); + } + + // planning reads the show's sponsors once, so two real runs at the same time would both plan the same creates + try { + return $this->lock_service->lock( + sprintf('summit.%s.sponsors.import.lock', $summit->getId()), + fn() => $this->planAndRunSponsorsImport($summit, $rows, false), + ISummitSponsorService::ImportLockLifetime + ); + } catch (UnacquiredLockException $ex) { + throw new ValidationException("An import is already running for this show. Try again when it finishes."); + } + } + + /** + * @param Summit $summit + * @param list $rows + * @param bool $dry_run + * @return array + */ + private function planAndRunSponsorsImport(Summit $summit, array $rows, bool $dry_run): array + { $tiers = []; foreach ($summit->getSummitSponsorshipTypes() as $summit_sponsorship_type) { // the type FK is SET NULL on delete, and getType() is not nullable @@ -323,6 +374,9 @@ private function parseSponsorsCsv(UploadedFile $file): array $company = (string)($record[$columns['company']] ?? ''); $tier = (string)($record[$columns['tier']] ?? ''); if (trim($company) === '' && trim($tier) === '') continue; + // fail on the first row over the cap instead of building the whole file + if (count($rows) >= ISummitSponsorService::ImportMaxRows) + throw new ValidationException(sprintf("File has more than %d rows.", ISummitSponsorService::ImportMaxRows)); $rows[] = ['row' => $offset + 1, 'company' => $company, 'tier' => $tier]; } } catch (UnableToProcessCsv $ex) { @@ -330,32 +384,27 @@ private function parseSponsorsCsv(UploadedFile $file): array throw new ValidationException("CSV is not valid."); } - if (count($rows) > ISummitSponsorService::ImportMaxRows) - throw new ValidationException(sprintf("File has %d rows; the maximum is %d.", count($rows), ISummitSponsorService::ImportMaxRows)); - return $rows; } /** * Runs the planned creates in order, each through its own transaction(s); never wrapped in an outer one, - * so addSponsor publishes its domain events after its own commit. + * so addSponsor publishes its domain events after its own commit. A failed row is reported and skipped; + * only a commit with an unknown outcome stops the run. + * addSponsor resolves the summit by id inside its transaction, so a failed row (which clears the + * EntityManager and detaches $summit) does not affect the rows after it. * @param Summit $summit * @param list $rows * @return list */ private function executeSponsorsImport(Summit $summit, array $rows): array { - $connection_reset = "The import stopped because the database connection was reset. Rows below were not imported."; $could_not_confirm = "Could not confirm whether this sponsor was saved; the import stopped here. Check the sponsor list before importing this file again."; - $could_not_create = "Could not create this sponsor; the import stopped here. Rows below were not imported."; + $could_not_create = "Could not create this sponsor."; foreach ($rows as $index => $row) { if ($row['action'] !== 'create') continue; - if (!$this->isSummitManaged($summit)) { - return SponsorImportPlanner::markStopped($rows, $index, $connection_reset, 'not_attempted'); - } - $company_created = null; try { $company_id = $row['company']['id']; @@ -376,39 +425,25 @@ private function executeSponsorsImport(Summit $summit, array $rows): array $company_id = $company->getId(); $rows[$index]['company']['id'] = $company_id; $company_created = sprintf(' Company "%s" was created.', $company->getName()); - - if (!$this->isSummitManaged($summit)) { - return SponsorImportPlanner::markStopped($rows, $index, $connection_reset . $company_created); - } } $sponsor = $this->addSponsor($summit, [ 'company_id' => $company_id, 'sponsorships' => array_map(static fn(int $type_id): array => ['type_id' => $type_id], $row['tier_ids']), ]); - - $sponsor_id = $sponsor->getId(); - if (!$this->isSummitManaged($summit) || !is_int($sponsor_id) || $sponsor_id <= 0) { - // addSponsor's own retry may have run against a detached summit - return SponsorImportPlanner::markStopped($rows, $index, $could_not_confirm . ($company_created ?? '')); - } - $rows[$index]['sponsor_id'] = $sponsor_id; + $rows[$index]['sponsor_id'] = $sponsor->getId(); + } catch (AmbiguousCommitException $ex) { + // the sponsor may or may not exist; continuing could hide that, so stop and report + Log::error(sprintf("SummitSponsorService::importSponsors summit %s row %s: %s", $summit->getId(), $row['row'], $ex->getMessage()), ['exception' => $ex]); + return SponsorImportPlanner::markStopped($rows, $index, $could_not_confirm . ($company_created ?? '')); } catch (\Throwable $ex) { - // Stop instead of log-and-skip: a failed transaction clears the EntityManager, which detaches - // $summit, so later rows would act on detached entities. Bad rows were already caught by the plan. Log::error(sprintf("SummitSponsorService::importSponsors summit %s row %s: %s", $summit->getId(), $row['row'], $ex->getMessage()), ['exception' => $ex]); - $message = $ex instanceof AmbiguousCommitException ? $could_not_confirm : $could_not_create; - return SponsorImportPlanner::markStopped($rows, $index, $message . ($company_created ?? '')); + $rows = SponsorImportPlanner::markFailed($rows, $index, $could_not_create . ($company_created ?? '')); } } return $rows; } - private function isSummitManaged(Summit $summit): bool - { - return Registry::getManager(SilverstripeBaseModel::EntityManager)->contains($summit); - } - /** * @param Summit $summit * @param int $sponsor_id diff --git a/app/Swagger/SponsorSchemas.php b/app/Swagger/SponsorSchemas.php index 2df3d73ed..6dcae63c5 100644 --- a/app/Swagger/SponsorSchemas.php +++ b/app/Swagger/SponsorSchemas.php @@ -277,7 +277,7 @@ class SponsorServicesStatisticsUpsertRequestSchema {} description: 'Request to import sponsors from a UTF-8 CSV file with company and tier columns (tiers separated by |)', required: ['file'], properties: [ - new OA\Property(property: 'file', type: 'string', format: 'binary', description: 'CSV file with company and tier columns'), + new OA\Property(property: 'file', type: 'string', format: 'binary', description: 'CSV file with company and tier columns, at most 1 MB and 200 rows'), new OA\Property(property: 'dry_run', type: 'integer', enum: [0, 1], description: 'Send 1 to plan only and write nothing, 0 (default) to import. true/false strings are rejected.'), ] )] diff --git a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php index 935dc1424..f696af5b9 100644 --- a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php +++ b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php @@ -170,10 +170,24 @@ public function testMarkStoppedErrorsRowAndMarksLaterCreatesNotAttempted(): void $this->assertNull($out[0]['error']); $this->assertSame('Tier is required.', $out[2]['error']); $this->assertNull($out[3]['error']); + } + + public function testMarkFailedErrorsOnlyThatRowAndItsDuplicates(): void + { + $rows = $this->planner()->plan([ + $this->row(2, 'Acme Robotics Inc', 'Gold'), + $this->row(3, 'Beta Labs', 'Gold'), + $this->row(4, 'ACME Robotics', 'Gold'), + $this->row(5, 'beta labs', 'Gold'), + ]); + $this->assertSame(['create', 'create', 'skip_duplicate', 'skip_duplicate'], array_column($rows, 'action')); + + $out = SponsorImportPlanner::markFailed($rows, 0, 'boom'); - $reset = SponsorImportPlanner::markStopped($rows, 1, 'reset', 'not_attempted'); - $this->assertSame(['create', 'not_attempted', 'error', 'not_attempted'], array_column($reset, 'action')); - $this->assertSame('reset', $reset[1]['error']); + // later creates still run; only the duplicate of the failed row loses its skip + $this->assertSame(['error', 'create', 'not_attempted', 'skip_duplicate'], array_column($out, 'action')); + $this->assertSame('boom', $out[0]['error']); + $this->assertNull($out[2]['error']); } public function testMarkStoppedAlsoStopsDuplicatesOfStoppedRows(): void diff --git a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php index 20694c6ab..78c24caf4 100644 --- a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php +++ b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php @@ -12,6 +12,7 @@ * limitations under the License. **/ +use App\Events\SponsorServices\SponsorDomainEvents; use App\Jobs\SponsorServices\PublishSponsorServiceDomainEventsJob; use Closure; use Illuminate\Http\UploadedFile; @@ -26,35 +27,45 @@ use Tests\TestCase; /** - * Wraps the real transaction service and, on one configured call, either throws instead of - * running the callback or runs it and then clears the model EntityManager (what a retried - * transaction on a fresh manager leaves behind: a detached summit and no exception). + * Wraps the real transaction service and, on one configured call, does one of: + * - throw instead of running the callback (clearing the EntityManager, as a failed root transaction does); + * - run it and then clear the EntityManager; + * - reset the EntityManager first and then run it (what a retry after a connection reset looks like). */ final class FaultInjectingTransactionService implements ITransactionService { + const Throw = 'throw'; + const ClearAfter = 'clear_after'; + const ResetBefore = 'reset_before'; + public $calls = 0; private $inner; private $on_call; + private $mode; private $throw; - private $clear_after; - public function __construct(ITransactionService $inner, int $on_call, ?\Throwable $throw, bool $clear_after) + public function __construct(ITransactionService $inner, int $on_call, string $mode, ?\Throwable $throw = null) { $this->inner = $inner; $this->on_call = $on_call; + $this->mode = $mode; $this->throw = $throw; - $this->clear_after = $clear_after; } public function transaction(Closure $callback, int $isolationLevel = 2) { $this->calls++; - if ($this->calls === $this->on_call && !is_null($this->throw)) { + $hit = $this->calls === $this->on_call; + if ($hit && $this->mode === self::Throw) { + Registry::getManager(SilverstripeBaseModel::EntityManager)->clear(); throw $this->throw; } + if ($hit && $this->mode === self::ResetBefore) { + Registry::resetManager(SilverstripeBaseModel::EntityManager); + } $result = $this->inner->transaction($callback, $isolationLevel); - if ($this->calls === $this->on_call && $this->clear_after) { + if ($hit && $this->mode === self::ClearAfter) { Registry::getManager(SilverstripeBaseModel::EntityManager)->clear(); } return $result; @@ -63,15 +74,14 @@ public function transaction(Closure $callback, int $isolationLevel = 2) /** * Class SummitSponsorServiceImportFaultTest - * Execution failures during a sponsor CSV import stop the run with a per-row report. + * Write failures during a sponsor CSV import: a failed row is skipped, an unknown commit outcome stops the run. * @package Tests\Unit\Services */ class SummitSponsorServiceImportFaultTest extends TestCase { use InsertSummitTestData; - const ConnectionResetMessage = 'The import stopped because the database connection was reset. Rows below were not imported.'; - const CouldNotCreateMessage = 'Could not create this sponsor; the import stopped here. Rows below were not imported.'; + const CouldNotCreateMessage = 'Could not create this sponsor.'; const CouldNotConfirmMessage = 'Could not confirm whether this sponsor was saved; the import stopped here. Check the sponsor list before importing this file again.'; /** @@ -88,6 +98,8 @@ protected function setUp(): void public function tearDown(): void { + // a ResetBefore test leaves self::$em pointing at the discarded manager + self::$em = Registry::getManager(SilverstripeBaseModel::EntityManager); self::clearSummitTestData(); $em = Registry::resetManager(SilverstripeBaseModel::EntityManager); foreach ($this->names as $name) { @@ -99,9 +111,9 @@ public function tearDown(): void parent::tearDown(); } - private function bindFake(int $on_call, ?\Throwable $throw, bool $clear_after): FaultInjectingTransactionService + private function bindFake(int $on_call, string $mode, ?\Throwable $throw = null): FaultInjectingTransactionService { - $fake = new FaultInjectingTransactionService(app(ITransactionService::class), $on_call, $throw, $clear_after); + $fake = new FaultInjectingTransactionService(app(ITransactionService::class), $on_call, $mode, $throw); $this->app->instance(ITransactionService::class, $fake); // singleton: a service resolved earlier would keep the real transaction service $this->app->forgetInstance(ISummitSponsorService::class); @@ -126,98 +138,97 @@ private function importThreeNewCompanies(): array } } - private function assertLaterRowsNotAttempted(array $report): void + /** + * @return int[] ids carried by the queued SponsorCreated payloads + */ + private function publishedSponsorIds(): array { - $this->assertSame(['error', 'not_attempted', 'not_attempted'], array_column($report['rows'], 'action')); - $this->assertSame(1, $report['summary']['errors']); - $this->assertSame(2, $report['summary']['not_attempted']); - $this->assertSame(0, $report['summary']['sponsors_created']); - $this->assertNull($report['rows'][1]['sponsor_id']); - $this->assertNull($report['rows'][2]['sponsor_id']); + $jobs = Queue::pushed(PublishSponsorServiceDomainEventsJob::class, function ($job) { + return $job->getEventType() === SponsorDomainEvents::SponsorCreated; + })->all(); + return array_values(array_map(static fn($job) => $job->getPayload()['id'], $jobs)); + } + + private function assertAllRowsCreated(array $report): void + { + $this->assertSame(['create', 'create', 'create'], array_column($report['rows'], 'action')); + $this->assertSame(3, $report['summary']['sponsors_created']); + $sponsor_ids = array_column($report['rows'], 'sponsor_id'); + foreach ($sponsor_ids as $sponsor_id) { + $this->assertGreaterThan(0, $sponsor_id); + } + $this->assertSame($sponsor_ids, $this->publishedSponsorIds()); } public function testAmbiguousCommitOnSponsorStopsWithConfirmMessage(): void { Queue::fake(); // call 1 = row 1 company, call 2 = row 1 addSponsor - $fake = $this->bindFake(2, new AmbiguousCommitException('x'), false); + $fake = $this->bindFake(2, FaultInjectingTransactionService::Throw, new AmbiguousCommitException('x')); $report = $this->importThreeNewCompanies(); - $this->assertLaterRowsNotAttempted($report); + $this->assertSame(['error', 'not_attempted', 'not_attempted'], array_column($report['rows'], 'action')); $row = $report['rows'][0]; $this->assertSame(self::CouldNotConfirmMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); $this->assertGreaterThan(0, $row['company']['id']); $this->assertNull($row['sponsor_id']); $this->assertSame(1, $report['summary']['companies_created']); + $this->assertSame(2, $report['summary']['not_attempted']); $this->assertSame(2, $fake->calls); } - public function testWriteFailureOnSponsorStopsWithCouldNotCreateMessage(): void + public function testWriteFailureOnSponsorSkipsThatRowAndImportsTheRest(): void { Queue::fake(); // call 1 = row 1 company, call 2 = row 1 addSponsor - $fake = $this->bindFake(2, new \RuntimeException('x'), false); + $fake = $this->bindFake(2, FaultInjectingTransactionService::Throw, new \RuntimeException('x')); $report = $this->importThreeNewCompanies(); - $this->assertLaterRowsNotAttempted($report); - $row = $report['rows'][0]; - $this->assertStringContainsString('Could not create this sponsor; the import stopped here', $row['error']); - $this->assertSame(self::CouldNotCreateMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); - $this->assertNull($row['sponsor_id']); - $this->assertSame(1, $report['summary']['companies_created']); - $this->assertSame(3, $report['summary']['total']); - $this->assertSame(2, $fake->calls); + $this->assertSame(['error', 'create', 'create'], array_column($report['rows'], 'action')); + $this->assertSame(self::CouldNotCreateMessage . sprintf(' Company "%s" was created.', $this->names[0]), $report['rows'][0]['error']); + $this->assertNull($report['rows'][0]['sponsor_id']); + $this->assertGreaterThan(0, $report['rows'][1]['sponsor_id']); + $this->assertGreaterThan(0, $report['rows'][2]['sponsor_id']); + $this->assertSame(['sponsors_created' => 2, 'companies_created' => 3, 'errors' => 1, 'not_attempted' => 0], + array_intersect_key($report['summary'], array_flip(['sponsors_created', 'companies_created', 'errors', 'not_attempted']))); + $this->assertSame(6, $fake->calls); } public function testAmbiguousCommitOnCompanyStopsWithCompanyConfirmMessage(): void { Queue::fake(); // call 1 = row 1 company - $fake = $this->bindFake(1, new AmbiguousCommitException('x'), false); + $fake = $this->bindFake(1, FaultInjectingTransactionService::Throw, new AmbiguousCommitException('x')); $report = $this->importThreeNewCompanies(); - $this->assertLaterRowsNotAttempted($report); - $row = $report['rows'][0]; + $this->assertSame(['error', 'not_attempted', 'not_attempted'], array_column($report['rows'], 'action')); $this->assertSame(sprintf( 'Could not confirm whether company "%s" was saved; the import stopped here. Check the sponsor list before importing this file again.', - $this->names[0]), $row['error']); - $this->assertNull($row['company']['id']); + $this->names[0]), $report['rows'][0]['error']); + $this->assertNull($report['rows'][0]['company']['id']); $this->assertSame(0, $report['summary']['companies_created']); $this->assertSame(1, $fake->calls); Queue::assertNotPushed(PublishSponsorServiceDomainEventsJob::class); } - public function testDetachAfterCompanyCreationStopsBeforeAddSponsor(): void + public function testClearedEntityManagerAfterARowDoesNotAffectLaterRows(): void { Queue::fake(); - $fake = $this->bindFake(1, null, true); - - $report = $this->importThreeNewCompanies(); + // clears after row 1's addSponsor, detaching the request's summit + $this->bindFake(2, FaultInjectingTransactionService::ClearAfter); - $this->assertLaterRowsNotAttempted($report); - $row = $report['rows'][0]; - $this->assertSame(self::ConnectionResetMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); - $this->assertGreaterThan(0, $row['company']['id']); - $this->assertSame(1, $report['summary']['companies_created']); - // addSponsor never ran - $this->assertSame(1, $fake->calls); - Queue::assertNotPushed(PublishSponsorServiceDomainEventsJob::class); + $this->assertAllRowsCreated($this->importThreeNewCompanies()); } - public function testDetachAfterAddSponsorStopsWithConfirmMessage(): void + public function testRetryOnAFreshEntityManagerPersistsTheSponsorAndPublishesItsId(): void { Queue::fake(); - $fake = $this->bindFake(2, null, true); - - $report = $this->importThreeNewCompanies(); + // resets before row 1's addSponsor callback runs, as a retry after a connection reset does + $this->bindFake(2, FaultInjectingTransactionService::ResetBefore); - $this->assertLaterRowsNotAttempted($report); - $row = $report['rows'][0]; - $this->assertSame(self::CouldNotConfirmMessage . sprintf(' Company "%s" was created.', $this->names[0]), $row['error']); - $this->assertNull($row['sponsor_id']); - $this->assertSame(2, $fake->calls); + $this->assertAllRowsCreated($this->importThreeNewCompanies()); } } diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index 664671a6a..6ddb5502d 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -18,6 +18,7 @@ use models\summit\SummitLeadReportSetting; use App\Models\Foundation\Main\IGroup; use App\Models\ResourceServer\IAccessTokenService; +use App\Services\Utils\ILockManagerService; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Queue; use LaravelDoctrine\ORM\Facades\Registry; @@ -2056,7 +2057,35 @@ public function testImportValidationTooManyRows(){ $max = ISummitSponsorService::ImportMaxRows; $response = $this->importCsv($this->rowsCsv($max + 1), true); $this->assertResponseStatus(412); - $this->assertStringContainsString(sprintf('File has %d rows; the maximum is %d.', $max + 1, $max), $response->getContent()); + $this->assertStringContainsString(sprintf('File has more than %d rows.', $max), $response->getContent()); + } + + public function testImportValidationFileTooLarge(){ + // header plus one padding column, so the size check fires and not the row cap + $csv = "company,tier,notes\nAcme,Default," . str_repeat('x', ISummitSponsorService::ImportMaxFileSizeKB * 1024) . "\n"; + $response = $this->importCsv($csv, true); + $this->assertResponseStatus(412); + $this->assertStringContainsString(sprintf('greater than %d kilobytes', ISummitSponsorService::ImportMaxFileSizeKB), $response->getContent()); + } + + public function testImportRealRunIsRefusedWhileAnotherRunHoldsTheLock(){ + Queue::fake(); + $new_name = $this->newCompanyName(); + $csv = "company,tier\n\"{$new_name}\",Default\n"; + $lock_name = sprintf('summit.%s.sponsors.import.lock', self::$summit->getId()); + + App::make(ILockManagerService::class)->lock($lock_name, function () use ($csv) { + $response = $this->importCsv($csv, false); + $this->assertResponseStatus(412); + $this->assertStringContainsString('An import is already running for this show.', $response->getContent()); + + // dry runs write nothing and do not take the lock + $this->importCsv($csv, true); + $this->assertResponseStatus(200); + }, 30); + + $this->importCsv($csv, false); + $this->assertResponseStatus(200); } public function testImportAcceptsExactlyMaxRows(){ From 9b0113c26f3fd5398c0b0173238c75587426a85a Mon Sep 17 00:00:00 2001 From: Casey Locker Date: Tue, 17 Nov 2026 09:08:03 -0600 Subject: [PATCH 15/15] fix(sponsors): report the tie-break company's own name in import rows --- .../Model/Imp/SponsorImport/CompanyNameMatcher.php | 11 +++++++++++ .../Imp/SponsorImport/SponsorImportPlanner.php | 4 +++- .../SponsorImport/SponsorImportPlannerTest.php | 13 +++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php index b657bcf6d..e4a276c0d 100644 --- a/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -40,6 +40,11 @@ final class CompanyNameMatcher */ private $by_key = []; + /** + * @var array id => stored name + */ + private $names = []; + /** * @param list $companies */ @@ -55,6 +60,7 @@ public function __construct(array $companies) $exact_key = self::exactKey($name); $this->exact_ids[$exact_key][] = $id; + $this->names[$id] = $name; if (!isset($this->exact[$exact_key]) || $id < $this->exact[$exact_key]['id']) { $this->exact[$exact_key] = ['id' => $id, 'name' => $name]; } @@ -97,6 +103,11 @@ private static function exactKey(string $name): string return mb_strtolower(preg_replace('/^[\s\x{00A0}]+|[\s\x{00A0}]+$/u', '', $s)); } + public function nameOf(int $id): ?string + { + return $this->names[$id] ?? null; + } + public function resolve(string $name): array { $exact_key = self::exactKey($name); diff --git a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php index 8cbf3e6db..1b028ce65 100644 --- a/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php +++ b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php @@ -114,15 +114,17 @@ public function plan(array $rows): array $is_sponsor = false; } else { $id = $match['id']; + $name = $match['name']; if ($match['match'] === 'exact') { foreach ($match['ids'] as $candidate_id) { if (isset($this->sponsor_company_ids[$candidate_id])) { $id = $candidate_id; + $name = $this->matcher->nameOf($candidate_id) ?? $name; break; } } } - $row['company'] = ['id' => $id, 'name' => $match['name'], 'match' => $match['match']]; + $row['company'] = ['id' => $id, 'name' => $name, 'match' => $match['match']]; $identity = 'id:' . $id; $is_sponsor = isset($this->sponsor_company_ids[$id]); } diff --git a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php index f696af5b9..978dc846d 100644 --- a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php +++ b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php @@ -139,6 +139,19 @@ public function testExactDuplicatePrefersCompanyAlreadySponsoring(): void $this->assertSame('exact', $out[0]['company']['match']); } + public function testExactDuplicateTieBreakReportsTheSelectedCompanysName(): void + { + $matcher = new CompanyNameMatcher([ + ['id' => 10, 'name' => 'ACME'], + ['id' => 99, 'name' => 'Acme'], + ]); + $planner = new SponsorImportPlanner($matcher, ['gold' => ['id' => 1, 'name' => 'Gold']], [99]); + + $out = $planner->plan([$this->row(2, 'acme', 'Gold')]); + $this->assertSame('skip_existing_sponsor', $out[0]['action']); + $this->assertSame(['id' => 99, 'name' => 'Acme', 'match' => 'exact'], $out[0]['company']); + } + public function testSummarizeCountsEachAction(): void { $rows = $this->planner()->plan([