Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,9 @@
interface ICompanyRepository extends IBaseRepository
{
public function getByName(string $name):?Company;

/**
* @return array<int, array{id:int,name:?string}>
*/
public function getAllIdAndName(): array;
}
9 changes: 9 additions & 0 deletions app/Models/Foundation/Summit/Summit.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions app/Models/Foundation/Summit/SummitSponsorshipType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
21 changes: 20 additions & 1 deletion app/Repositories/Main/DoctrineCompanyRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,23 @@ public function getByName(string $name): ?Company
->getQuery()
->getOneOrNullResult();
}
}

/**
* Scalar projection, no entity hydration.
* @return array<int, array{id:int,name:?string}>
*/
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
);
}
}
24 changes: 24 additions & 0 deletions app/Services/Model/ISummitSponsorService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<string,int>,rows:list<array>}
* @throws ValidationException
*/
public function importSponsors(Summit $summit, UploadedFile $file, bool $dry_run):array;

/**
* @param Summit $summit
* @param int $sponsor_id
Expand Down
130 changes: 130 additions & 0 deletions app/Services/Model/Imp/SponsorImport/CompanyNameMatcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php namespace App\Services\Model\Imp\SponsorImport;

/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

/**
* Class CompanyNameMatcher
* Resolves a CSV company name against existing companies: exact first, then by normalized key.
* @package App\Services\Model\Imp\SponsorImport
*/
final class CompanyNameMatcher
{
private const LegalSuffixes = [
'inc', 'incorporated', 'llc', 'corp', 'corporation', 'co', 'company', 'ltd', 'limited',
'gmbh', 'ag', 'sa', 'plc', 'bv', 'nv', 'pte', 'pty', 'srl', 'spa', 'kk', 'lp', 'llp',
];

/**
* @var array<string, array{id:int,name:string}> exact key => lowest-id company
*/
private $exact = [];

/**
* @var array<string, list<int>> exact key => every id, ascending
*/
private $exact_ids = [];

/**
* @var array<string, list<array{id:int,name:string}>> normalized key => companies
*/
private $by_key = [];

/**
* @var array<int, string> id => stored name
*/
private $names = [];

/**
* @param list<array{id:int,name:string}> $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];
}
}
Loading
Loading