diff --git a/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php b/app/Http/Controllers/Apis/Protected/Summit/OAuth2SummitSponsorApiController.php index d9bc5c8a26..4148ef1986 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,90 @@ 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(ref: '#/components/schemas/SponsorImportRequest') + ) + ), + responses: [ + new OA\Response( + response: Response::HTTP_OK, + description: 'Per-row import report', + 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"), + 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") + ] + )] + /** + * @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|max:' . ISummitSponsorService::ImportMaxFileSizeKB, + 'dry_run' => 'sometimes|boolean', + ]); + 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/Models/Foundation/Main/Repositories/ICompanyRepository.php b/app/Models/Foundation/Main/Repositories/ICompanyRepository.php index c87d290f25..1cf46c5955 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 f2a7dfc414..151bc3e117 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/Models/Foundation/Summit/SummitSponsorshipType.php b/app/Models/Foundation/Summit/SummitSponsorshipType.php index 94d72a2ef0..c474bd0165 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/Repositories/Main/DoctrineCompanyRepository.php b/app/Repositories/Main/DoctrineCompanyRepository.php index aa53643be3..bbd66acdd6 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/app/Services/Model/ISummitSponsorService.php b/app/Services/Model/ISummitSponsorService.php index 5ee65b688b..81757d113d 100644 --- a/app/Services/Model/ISummitSponsorService.php +++ b/app/Services/Model/ISummitSponsorService.php @@ -34,6 +34,20 @@ */ interface ISummitSponsorService { + /** + * Separates tier names within the tier cell of a sponsors CSV import. + */ + 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; + + // 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 @@ -43,6 +57,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/SponsorImport/CompanyNameMatcher.php b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php new file mode 100644 index 0000000000..e4a276c0d8 --- /dev/null +++ b/app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php @@ -0,0 +1,130 @@ + 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 = []; + + /** + * @var array id => stored name + */ + private $names = []; + + /** + * @param list $companies + */ + 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; + $this->names[$id] = $name; + 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 $k => $ids) { + sort($ids); + $this->exact_ids[$k] = $ids; + } + } + + public static function key(string $name): string + { + $s = self::nfc($name); + $s = mb_strtolower($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)) { + array_pop($words); + } + return implode(' ', $words); + } + + // 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; + $s = \Normalizer::normalize($name, \Normalizer::FORM_C); + return $s === false ? $name : $s; + } + + private static function exactKey(string $name): string + { + $s = self::nfc($name); + // 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 nameOf(int $id): ?string + { + return $this->names[$id] ?? null; + } + + 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/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php new file mode 100644 index 0000000000..1b028ce65b --- /dev/null +++ b/app/Services/Model/Imp/SponsorImport/SponsorImportPlanner.php @@ -0,0 +1,246 @@ + lowercase tier name => tier + */ + private $tiers; + + /** + * @var array company id => true + */ + private $sponsor_company_ids; + + /** + * @param CompanyNameMatcher $matcher + * @param array $tiers + * @param list $sponsor_company_ids + */ + 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', $sponsor_company_ids), 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); + // 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.'); + 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']; + $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' => $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 $dry_run + * @return array{dry_run:bool,summary:array} + */ + public static function summarize(array $rows, bool $dry_run): 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' => $dry_run, 'summary' => $summary]; + } + + /** + * 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 + * @return list + */ + public static function markStopped(array $rows, int $index, string $message): array + { + $rows[$index]['action'] = 'error'; + $rows[$index]['error'] = $message; + $stopped = [$rows[$index]['row'] => true]; // row numbers with nothing imported + $count = count($rows); + for ($i = $index + 1; $i < $count; $i++) { + $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; + } + + 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/app/Services/Model/Imp/SummitSponsorService.php b/app/Services/Model/Imp/SummitSponsorService.php index d7ed335f56..8c4643e5bc 100644 --- a/app/Services/Model/Imp/SummitSponsorService.php +++ b/app/Services/Model/Imp/SummitSponsorService.php @@ -35,7 +35,16 @@ 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 App\Services\Utils\Exceptions\UnacquiredLockException; +use App\Services\Utils\ILockManagerService; +use League\Csv\Reader; +use League\Csv\UnableToProcessCsv; +use models\summit\ISummitRepository; +use services\utils\AmbiguousCommitException; use Doctrine\Common\Collections\ArrayCollection; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Log; @@ -56,6 +65,7 @@ use models\summit\Summit; use models\summit\SummitLeadReportSetting; use models\summit\SummitSponsorship; +use models\summit\SummitSponsorshipType; use services\model\ISummitSponsorService; /** @@ -96,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 @@ -104,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 @@ -115,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; @@ -137,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; @@ -196,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(), @@ -223,6 +259,191 @@ 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); + + 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 + if (!$summit_sponsorship_type instanceof SummitSponsorshipType || !$summit_sponsorship_type->hasType()) continue; + $type = $summit_sponsorship_type->getType(); + $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); + + // messages never echo file content: the admin UI renders them as HTML + $required_columns = ['company', 'tier']; + $columns = []; + foreach ($csv->getHeader() as $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.", $required_columns[$required])); + $columns[$normalized] = $header; + } + foreach ($required_columns 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; + // 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) { + Log::warning(sprintf("SummitSponsorService::importSponsors CSV is not valid: %s", $ex->getMessage())); + throw new ValidationException("CSV is not valid."); + } + + 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. 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 + { + $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."; + + foreach ($rows as $index => $row) { + if ($row['action'] !== 'create') continue; + + $company_created = null; + try { + $company_id = $row['company']['id']; + if ($row['company']['match'] === 'new') { + $name = $row['company']['name']; + 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()); + } + + $sponsor = $this->addSponsor($summit, [ + 'company_id' => $company_id, + 'sponsorships' => array_map(static fn(int $type_id): array => ['type_id' => $type_id], $row['tier_ids']), + ]); + $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) { + Log::error(sprintf("SummitSponsorService::importSponsors summit %s row %s: %s", $summit->getId(), $row['row'], $ex->getMessage()), ['exception' => $ex]); + $rows = SponsorImportPlanner::markFailed($rows, $index, $could_not_create . ($company_created ?? '')); + } + } + return $rows; + } + /** * @param Summit $summit * @param int $sponsor_id diff --git a/app/Swagger/SponsorSchemas.php b/app/Swagger/SponsorSchemas.php index dcad408308..6dcae63c5b 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, 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.'), + ] +)] +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/database/migrations/config/Version20261115120000.php b/database/migrations/config/Version20261115120000.php new file mode 100644 index 0000000000..a98815f222 --- /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 af083c4c3a..fcffbae58a 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 bf0df1cd1d..f72b0f6d9b 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/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php new file mode 100644 index 0000000000..4bbf9c4d78 --- /dev/null +++ b/tests/Repositories/DoctrineCompanyRepositoryIdAndNameTest.php @@ -0,0 +1,73 @@ +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); + } + } +} diff --git a/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php new file mode 100644 index 0000000000..f2f37af5d3 --- /dev/null +++ b/tests/Unit/Services/SponsorImport/CompanyNameMatcherTest.php @@ -0,0 +1,90 @@ +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')); + $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([ + ['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' => ' ']]); + // precomposed input matches decomposed stored name (exact) + $this->assertSame(['match' => 'exact', 'id' => 1, 'name' => "Cafe\u{0301} Corp", 'ids' => [1]], $m->resolve("Café Corp")); + $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('')); + } + + 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' => 2, 'name' => 'arm, inc'], ['id' => 1, 'name' => 'Arm Ltd.']]); + $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 '--' + } + + 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')); + } +} diff --git a/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php new file mode 100644 index 0000000000..978dc846d8 --- /dev/null +++ b/tests/Unit/Services/SponsorImport/SponsorImportPlannerTest.php @@ -0,0 +1,259 @@ + 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')]); + $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 + { + $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 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([ + $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 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'); + + // 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 + { + $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 = [ + ['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']); + } +} diff --git a/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php new file mode 100644 index 0000000000..78c24caf4c --- /dev/null +++ b/tests/Unit/Services/SummitSponsorServiceImportFaultTest.php @@ -0,0 +1,234 @@ +inner = $inner; + $this->on_call = $on_call; + $this->mode = $mode; + $this->throw = $throw; + } + + public function transaction(Closure $callback, int $isolationLevel = 2) + { + $this->calls++; + $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 ($hit && $this->mode === self::ClearAfter) { + Registry::getManager(SilverstripeBaseModel::EntityManager)->clear(); + } + return $result; + } +} + +/** + * Class SummitSponsorServiceImportFaultTest + * 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 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.'; + + /** + * @var string[] + */ + private $names = []; + + protected function setUp(): void + { + parent::setUp(); + self::insertSummitTestData(); + $this->names = []; + } + + 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) { + foreach ($em->getRepository(Company::class)->findBy(['name' => $name]) as $company) { + $em->remove($company); + } + } + $em->flush(); + parent::tearDown(); + } + + private function bindFake(int $on_call, string $mode, ?\Throwable $throw = null): FaultInjectingTransactionService + { + $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); + 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 = sprintf('%s/sponsor_import_%s.csv', sys_get_temp_dir(), str_random(16)); + file_put_contents($path, $csv); + try { + $file = new UploadedFile($path, 'sponsors.csv', 'text/csv', null, true); + return app(ISummitSponsorService::class)->importSponsors(self::$summit, $file, false); + } finally { + unlink($path); + } + } + + /** + * @return int[] ids carried by the queued SponsorCreated payloads + */ + private function publishedSponsorIds(): array + { + $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, FaultInjectingTransactionService::Throw, new AmbiguousCommitException('x')); + + $report = $this->importThreeNewCompanies(); + + $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 testWriteFailureOnSponsorSkipsThatRowAndImportsTheRest(): void + { + Queue::fake(); + // call 1 = row 1 company, call 2 = row 1 addSponsor + $fake = $this->bindFake(2, FaultInjectingTransactionService::Throw, new \RuntimeException('x')); + + $report = $this->importThreeNewCompanies(); + + $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, FaultInjectingTransactionService::Throw, new AmbiguousCommitException('x')); + + $report = $this->importThreeNewCompanies(); + + $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]), $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 testClearedEntityManagerAfterARowDoesNotAffectLaterRows(): void + { + Queue::fake(); + // clears after row 1's addSponsor, detaching the request's summit + $this->bindFake(2, FaultInjectingTransactionService::ClearAfter); + + $this->assertAllRowsCreated($this->importThreeNewCompanies()); + } + + public function testRetryOnAFreshEntityManagerPersistsTheSponsorAndPublishesItsId(): void + { + Queue::fake(); + // resets before row 1's addSponsor callback runs, as a retry after a connection reset does + $this->bindFake(2, FaultInjectingTransactionService::ResetBefore); + + $this->assertAllRowsCreated($this->importThreeNewCompanies()); + } +} diff --git a/tests/oauth2/OAuth2SummitSponsorApiTest.php b/tests/oauth2/OAuth2SummitSponsorApiTest.php index 47384ca961..6ddb5502d8 100644 --- a/tests/oauth2/OAuth2SummitSponsorApiTest.php +++ b/tests/oauth2/OAuth2SummitSponsorApiTest.php @@ -18,6 +18,16 @@ 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; +use models\main\Company; +use models\summit\Sponsor; +use models\summit\Summit; +use models\summit\SummitSponsorshipType; +use models\utils\SilverstripeBaseModel; +use services\model\ISummitSponsorService; /** * Class OAuth2SummitSponsorApiTest */ @@ -51,6 +61,7 @@ protected function setUp(): void protected function tearDown(): void { self::clearSummitTestData(); + $this->removeImportedCompanies(); parent::tearDown(); } @@ -1647,7 +1658,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 +1842,314 @@ 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 + { + 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) { + foreach ($em->getRepository(Company::class)->findBy(['name' => $name]) as $company) { + $em->remove($company); + } + } + $em->flush(); + $this->imported_company_names = []; + } + + /** + * @var string[] temp upload paths, removed on tear down + */ + private $csv_paths = []; + + private function buildCsvFile(string $content): UploadedFile + { + $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); + } + + 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 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 + $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); + $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 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 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()); + } + + 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); + $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(){ + $max = ISummitSponsorService::ImportMaxRows; + $response = $this->importCsv($this->rowsCsv($max + 1), true); + $this->assertResponseStatus(412); + $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(){ + $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 + $new_name = $this->newCompanyName(); + $sponsors_before = self::$summit->getSummitSponsors()->count(); + $summit_id = self::$summit->getId(); + $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); + + $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); + $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()); + } }