fix: make project template inheritance granular and safe
CI/CD / test_and_check_app (push) Failing after 3m8s
CI/CD / Publish immutable image (push) Skipped
CI/CD / test_and_check_app (pull_request) Failing after 3m8s
CI/CD / Publish immutable image (pull_request) Skipped

This commit is contained in:
Nico Schröder
2026-09-08 10:25:52 +00:00
committed by Twyco
parent fed6a282a4
commit 9895fc36db
50 changed files with 1504 additions and 624 deletions
@@ -2,11 +2,19 @@
namespace App\Actions\ProjectBoard;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Actions\Projects\ProjectTemplateOverrideManager;
use App\Actions\Projects\RefreshProjectBaseTemplate;
use App\Models\TicketStatus;
use Illuminate\Support\Arr;
class UpdateTicketStatusTransitions
{
public function __construct(
private readonly ProjectTemplateOverrideManager $projectTemplateOverrideManager,
private readonly RefreshProjectBaseTemplate $refreshProjectBaseTemplate,
) {}
/**
* @param array{allowed_ticket_status_ids?: array<int, int|string>|null} $validated
*/
@@ -19,6 +27,14 @@ class UpdateTicketStatusTransitions
->all();
$ticketStatus->allowedTargetStatuses()->sync($allowedTicketStatusIds);
$this->projectTemplateOverrideManager->mark(
$ticketStatus->project,
DuplicateProjectConfiguration::COPY_STATUS_TRANSITIONS,
);
$this->refreshProjectBaseTemplate->handle(
$ticketStatus->project,
DuplicateProjectConfiguration::COPY_STATUS_TRANSITIONS,
);
return $ticketStatus->fresh();
}
@@ -2,11 +2,19 @@
namespace App\Actions\ProjectTicketMetadata;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Actions\Projects\ProjectTemplateOverrideManager;
use App\Actions\Projects\RefreshProjectBaseTemplate;
use App\Models\Project;
use Illuminate\Support\Arr;
class UpdateProjectTicketMetadataSettings
{
public function __construct(
private readonly ProjectTemplateOverrideManager $projectTemplateOverrideManager,
private readonly RefreshProjectBaseTemplate $refreshProjectBaseTemplate,
) {}
/**
* @param array{show_author?: bool|null, show_story_points?: bool|null} $validated
*/
@@ -16,6 +24,14 @@ class UpdateProjectTicketMetadataSettings
'show_author' => Arr::get($validated, 'show_author', false),
'show_story_points' => Arr::get($validated, 'show_story_points', false),
]);
$this->projectTemplateOverrideManager->mark(
$project,
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
);
$this->refreshProjectBaseTemplate->handle(
$project,
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
);
return $project->fresh();
}
+8 -3
View File
@@ -18,6 +18,7 @@ class CreateProject
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
private readonly InitializeProjectTicketMetadata $initializeProjectTicketMetadata,
private readonly PermissionService $permissionService,
private readonly ProjectTemplateOverrideManager $projectTemplateOverrideManager,
) {}
/**
@@ -39,18 +40,22 @@ class CreateProject
$project->forceFill([
'project_template_id' => $sourceTemplate->id,
])->save();
'template_overrides' => [],
])->saveQuietly();
} else {
$baseTemplate = $this->createProjectBaseTemplate->handle($project);
$project->forceFill([
'project_template_id' => $baseTemplate->id,
])->save();
'template_overrides' => [],
])->saveQuietly();
}
$project = $project->fresh() ?? $project;
$this->initializeProjectTicketMetadata->handle($project);
$this->projectTemplateOverrideManager->withoutRecording(
fn () => $this->initializeProjectTicketMetadata->handle($project),
);
$this->permissionService->grant($actor, Permission::ProjectAdmin, $project);
if ($creationMode === 'duplicate' && Arr::get($attributes, 'source_project_id') !== null) {
@@ -3,12 +3,18 @@
namespace App\Actions\Projects;
use App\Models\Project;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model;
class DuplicateProjectConfiguration
{
public const COPY_PROJECT_SETTINGS = 'project_settings';
public const COPY_BOARD_WORKFLOW = 'board_workflow';
public const COPY_BOARD_COLUMNS = 'board_columns';
public const COPY_TICKET_STATUSES = 'ticket_statuses';
public const COPY_STATUS_TRANSITIONS = 'status_transitions';
public const COPY_TICKET_TYPES = 'ticket_types';
@@ -22,14 +28,20 @@ class DuplicateProjectConfiguration
public const COPY_NOTIFICATION_ACTIONS = 'notification_actions';
/**
* @return list<string>
*/
public const COPY_BOARD_WORKFLOW = 'board_workflow';
public function __construct(
private readonly ProjectTemplateOverrideManager $projectTemplateOverrideManager,
) {}
/** @return list<string> */
public static function copyableAreas(): array
{
return [
self::COPY_PROJECT_SETTINGS,
self::COPY_BOARD_WORKFLOW,
self::COPY_BOARD_COLUMNS,
self::COPY_TICKET_STATUSES,
self::COPY_STATUS_TRANSITIONS,
self::COPY_TICKET_TYPES,
self::COPY_TICKET_PRIORITIES,
self::COPY_TICKET_FIELDS,
@@ -39,68 +51,67 @@ class DuplicateProjectConfiguration
];
}
/**
* @return list<array{value: string, label: string, description: string}>
*/
/** @return list<string> */
public static function acceptedCopyAreas(): array
{
return [...self::copyableAreas(), self::COPY_BOARD_WORKFLOW];
}
/** @return list<array{value: string, label: string, description: string}> */
public static function copyAreaOptions(): array
{
return [
[
'value' => self::COPY_PROJECT_SETTINGS,
'label' => 'Project settings',
'description' => 'Copy general project preferences like story points and author visibility.',
],
[
'value' => self::COPY_BOARD_WORKFLOW,
'label' => 'Board workflow',
'description' => 'Copy board columns, ticket statuses, and allowed status transitions.',
],
[
'value' => self::COPY_TICKET_TYPES,
'label' => 'Ticket types',
'description' => 'Copy available ticket types, including parent-ticket types.',
],
[
'value' => self::COPY_TICKET_PRIORITIES,
'label' => 'Ticket priorities',
'description' => 'Copy the project-specific ticket priorities.',
],
[
'value' => self::COPY_TICKET_FIELDS,
'label' => 'Custom ticket fields',
'description' => 'Copy custom ticket field definitions without any ticket values.',
],
[
'value' => self::COPY_TICKET_LINK_TYPES,
'label' => 'Ticket link types',
'description' => 'Copy available relationship labels between tickets.',
],
[
'value' => self::COPY_REPOSITORY_CONNECTIONS,
'label' => 'Repository connections',
'description' => 'Copy linked repositories without changing the new project identity.',
],
[
'value' => self::COPY_NOTIFICATION_ACTIONS,
'label' => 'Notification actions',
'description' => 'Copy notification rules and delivery settings.',
],
['value' => self::COPY_PROJECT_SETTINGS, 'label' => 'Project settings', 'description' => 'General project preferences like story points and author visibility.'],
['value' => self::COPY_BOARD_COLUMNS, 'label' => 'Board columns', 'description' => 'Columns and their order on the project board.'],
['value' => self::COPY_TICKET_STATUSES, 'label' => 'Ticket statuses', 'description' => 'Statuses and their assignment to board columns.'],
['value' => self::COPY_STATUS_TRANSITIONS, 'label' => 'Status transitions', 'description' => 'Allowed moves between ticket statuses.'],
['value' => self::COPY_TICKET_TYPES, 'label' => 'Ticket types', 'description' => 'Available ticket types, including parent types.'],
['value' => self::COPY_TICKET_PRIORITIES, 'label' => 'Ticket priorities', 'description' => 'Available ticket priorities.'],
['value' => self::COPY_TICKET_FIELDS, 'label' => 'Custom ticket fields', 'description' => 'Custom field definitions without ticket values.'],
['value' => self::COPY_TICKET_LINK_TYPES, 'label' => 'Ticket link types', 'description' => 'Relationship labels between tickets.'],
['value' => self::COPY_REPOSITORY_CONNECTIONS, 'label' => 'Repository connections', 'description' => 'Repositories linked to the project.'],
['value' => self::COPY_NOTIFICATION_ACTIONS, 'label' => 'Notification actions', 'description' => 'Notification rules and delivery settings.'],
];
}
/**
* @param list<string> $copyAreas
* @return list<string>
*/
/** @param list<string> $copyAreas @return list<string> */
public function normalizeCopyAreas(array $copyAreas): array
{
if (in_array(self::COPY_BOARD_WORKFLOW, $copyAreas, true)) {
$copyAreas = [
...array_diff($copyAreas, [self::COPY_BOARD_WORKFLOW]),
self::COPY_BOARD_COLUMNS,
self::COPY_TICKET_STATUSES,
self::COPY_STATUS_TRANSITIONS,
];
}
return array_values(array_intersect(self::copyableAreas(), array_unique($copyAreas)));
}
/**
* @param list<string> $copyAreas
* @return array<string, mixed>
*/
/** @param array<string, mixed> $configuration @return array<string, mixed> */
public function normalizeConfiguration(array $configuration): array
{
$workflow = $configuration[self::COPY_BOARD_WORKFLOW] ?? null;
if (is_array($workflow)) {
$statuses = $workflow['ticket_statuses'] ?? [];
$configuration[self::COPY_BOARD_COLUMNS] ??= $workflow['board_columns'] ?? [];
$configuration[self::COPY_TICKET_STATUSES] ??= array_map(
static fn (array $status): array => array_diff_key($status, ['allowed_target_indexes' => true]),
$statuses,
);
$configuration[self::COPY_STATUS_TRANSITIONS] ??= array_map(
static fn (array $status): array => $status['allowed_target_indexes'] ?? [],
$statuses,
);
unset($configuration[self::COPY_BOARD_WORKFLOW]);
}
return $configuration;
}
/** @param list<string> $copyAreas @return array<string, mixed> */
public function export(Project $sourceProject, array $copyAreas): array
{
$selectedAreas = $this->normalizeCopyAreas($copyAreas);
@@ -109,17 +120,10 @@ class DuplicateProjectConfiguration
return [];
}
$sourceProject->loadMissing([
'boardColumns',
'notificationActions',
'repositoryConnections',
'ticketFieldDefinitions',
'ticketLinkTypes',
'ticketPriorities',
'ticketStatuses.allowedTargetStatuses',
'ticketTypes',
$sourceProject->load([
'boardColumns', 'notificationActions', 'repositoryConnections', 'ticketFieldDefinitions',
'ticketLinkTypes', 'ticketPriorities', 'ticketStatuses.allowedTargetStatuses', 'ticketTypes',
]);
$configuration = [];
if (in_array(self::COPY_PROJECT_SETTINGS, $selectedAreas, true)) {
@@ -129,120 +133,65 @@ class DuplicateProjectConfiguration
];
}
if (in_array(self::COPY_BOARD_WORKFLOW, $selectedAreas, true)) {
$boardColumnIndexes = [];
$boardColumns = [];
$columnIndexes = $sourceProject->boardColumns->values()->mapWithKeys(
static fn ($column, int $index): array => [$column->id => $index],
);
$statusIndexes = $sourceProject->ticketStatuses->values()->mapWithKeys(
static fn ($status, int $index): array => [$status->id => $index],
);
foreach ($sourceProject->boardColumns as $index => $boardColumn) {
$boardColumnIndexes[$boardColumn->id] = $index;
$boardColumns[] = [
'name' => $boardColumn->name,
'position' => $boardColumn->position,
];
if (in_array(self::COPY_BOARD_COLUMNS, $selectedAreas, true)) {
$configuration[self::COPY_BOARD_COLUMNS] = $sourceProject->boardColumns->values()->map(
static fn ($column): array => ['name' => $column->name, 'position' => $column->position],
)->all();
}
if (in_array(self::COPY_TICKET_STATUSES, $selectedAreas, true)) {
$configuration[self::COPY_TICKET_STATUSES] = $sourceProject->ticketStatuses->values()->map(
static fn ($status): array => [
'board_column_index' => $status->board_column_id === null ? null : $columnIndexes->get($status->board_column_id),
'name' => $status->name,
'position' => $status->position,
],
)->all();
}
if (in_array(self::COPY_STATUS_TRANSITIONS, $selectedAreas, true)) {
$configuration[self::COPY_STATUS_TRANSITIONS] = $sourceProject->ticketStatuses->values()->map(
static fn ($status): array => $status->allowedTargetStatuses->pluck('id')->map(
static fn (int $id): ?int => $statusIndexes->get($id),
)->filter(static fn (?int $index): bool => $index !== null)->values()->all(),
)->all();
}
$simpleAreas = [
self::COPY_TICKET_TYPES => fn ($item): array => ['name' => $item->name, 'position' => $item->position, 'is_parent' => $item->is_parent],
self::COPY_TICKET_PRIORITIES => fn ($item): array => ['name' => $item->name, 'position' => $item->position],
self::COPY_TICKET_FIELDS => fn ($item): array => ['field_type' => $item->field_type, 'label' => $item->label, 'position' => $item->position],
self::COPY_TICKET_LINK_TYPES => fn ($item): array => ['label' => $item->label, 'counterpart_label' => $item->counterpart_label, 'position' => $item->position],
self::COPY_REPOSITORY_CONNECTIONS => fn ($item): array => [
'provider' => $item->provider->value, 'base_url' => $item->base_url,
'provider_repository_id' => $item->provider_repository_id, 'owner_name' => $item->owner_name,
'repository_name' => $item->repository_name, 'repository_full_name' => $item->repository_full_name,
'repository_url' => $item->repository_url,
],
self::COPY_NOTIFICATION_ACTIONS => fn ($item): array => [
'name' => $item->name, 'enabled' => $item->enabled, 'event_type' => $item->event_type->value,
'channel' => $item->channel->value, 'channel_configuration' => $item->channel_configuration ?? [],
'message_template' => $item->message_template, 'delivery_url' => $item->delivery_url,
'filters' => $item->filters ?? [],
],
];
$relations = [
self::COPY_TICKET_TYPES => 'ticketTypes', self::COPY_TICKET_PRIORITIES => 'ticketPriorities',
self::COPY_TICKET_FIELDS => 'ticketFieldDefinitions', self::COPY_TICKET_LINK_TYPES => 'ticketLinkTypes',
self::COPY_REPOSITORY_CONNECTIONS => 'repositoryConnections', self::COPY_NOTIFICATION_ACTIONS => 'notificationActions',
];
foreach ($simpleAreas as $area => $mapper) {
if (in_array($area, $selectedAreas, true)) {
$configuration[$area] = $sourceProject->{$relations[$area]}->values()->map($mapper)->all();
}
$ticketStatusIndexes = [];
$ticketStatuses = [];
foreach ($sourceProject->ticketStatuses as $index => $ticketStatus) {
$ticketStatusIndexes[$ticketStatus->id] = $index;
$ticketStatuses[] = [
'board_column_index' => $ticketStatus->board_column_id === null
? null
: ($boardColumnIndexes[$ticketStatus->board_column_id] ?? null),
'name' => $ticketStatus->name,
'position' => $ticketStatus->position,
'allowed_target_indexes' => [],
];
}
foreach ($sourceProject->ticketStatuses as $index => $ticketStatus) {
$ticketStatuses[$index]['allowed_target_indexes'] = $ticketStatus->allowedTargetStatuses
->pluck('id')
->map(fn (int $statusId): ?int => $ticketStatusIndexes[$statusId] ?? null)
->filter(static fn (?int $statusIndex): bool => $statusIndex !== null)
->values()
->all();
}
$configuration[self::COPY_BOARD_WORKFLOW] = [
'board_columns' => $boardColumns,
'ticket_statuses' => $ticketStatuses,
];
}
if (in_array(self::COPY_TICKET_TYPES, $selectedAreas, true)) {
$configuration[self::COPY_TICKET_TYPES] = $sourceProject->ticketTypes
->map(fn ($ticketType): array => [
'name' => $ticketType->name,
'position' => $ticketType->position,
'is_parent' => $ticketType->is_parent,
])
->values()
->all();
}
if (in_array(self::COPY_TICKET_PRIORITIES, $selectedAreas, true)) {
$configuration[self::COPY_TICKET_PRIORITIES] = $sourceProject->ticketPriorities
->map(fn ($ticketPriority): array => [
'name' => $ticketPriority->name,
'position' => $ticketPriority->position,
])
->values()
->all();
}
if (in_array(self::COPY_TICKET_FIELDS, $selectedAreas, true)) {
$configuration[self::COPY_TICKET_FIELDS] = $sourceProject->ticketFieldDefinitions
->map(fn ($ticketFieldDefinition): array => [
'field_type' => $ticketFieldDefinition->field_type,
'label' => $ticketFieldDefinition->label,
'position' => $ticketFieldDefinition->position,
])
->values()
->all();
}
if (in_array(self::COPY_TICKET_LINK_TYPES, $selectedAreas, true)) {
$configuration[self::COPY_TICKET_LINK_TYPES] = $sourceProject->ticketLinkTypes
->map(fn ($ticketLinkType): array => [
'label' => $ticketLinkType->label,
'counterpart_label' => $ticketLinkType->counterpart_label,
'position' => $ticketLinkType->position,
])
->values()
->all();
}
if (in_array(self::COPY_REPOSITORY_CONNECTIONS, $selectedAreas, true)) {
$configuration[self::COPY_REPOSITORY_CONNECTIONS] = $sourceProject->repositoryConnections
->map(fn ($repositoryConnection): array => [
'provider' => $repositoryConnection->provider->value,
'base_url' => $repositoryConnection->base_url,
'provider_repository_id' => $repositoryConnection->provider_repository_id,
'owner_name' => $repositoryConnection->owner_name,
'repository_name' => $repositoryConnection->repository_name,
'repository_full_name' => $repositoryConnection->repository_full_name,
'repository_url' => $repositoryConnection->repository_url,
])
->values()
->all();
}
if (in_array(self::COPY_NOTIFICATION_ACTIONS, $selectedAreas, true)) {
$configuration[self::COPY_NOTIFICATION_ACTIONS] = $sourceProject->notificationActions
->map(fn ($notificationAction): array => [
'name' => $notificationAction->name,
'enabled' => $notificationAction->enabled,
'event_type' => $notificationAction->event_type->value,
'channel' => $notificationAction->channel->value,
'channel_configuration' => $notificationAction->channel_configuration ?? [],
'message_template' => $notificationAction->message_template,
'delivery_url' => $notificationAction->delivery_url,
'filters' => $notificationAction->filters ?? [],
])
->values()
->all();
}
return $configuration;
@@ -250,151 +199,141 @@ class DuplicateProjectConfiguration
/**
* @param array<string, mixed> $configuration
* @param array<int|string, int|string> $statusReplacements
* @return list<string> areas which retained referenced local values
*/
public function apply(Project $targetProject, array $configuration): void
public function apply(Project $targetProject, array $configuration, array $statusReplacements = []): array
{
if (array_key_exists(self::COPY_PROJECT_SETTINGS, $configuration)) {
$projectSettings = $configuration[self::COPY_PROJECT_SETTINGS];
$configuration = $this->normalizeConfiguration($configuration);
$targetProject->forceFill([
'show_author' => (bool) ($projectSettings['show_author'] ?? $targetProject->show_author),
'show_story_points' => (bool) ($projectSettings['show_story_points'] ?? $targetProject->show_story_points),
])->save();
}
$blockedAreas = $this->projectTemplateOverrideManager->withoutRecording(function () use ($targetProject, $configuration, $statusReplacements): array {
$blockedAreas = [];
if (array_key_exists(self::COPY_BOARD_WORKFLOW, $configuration)) {
$targetProject->ticketStatuses()->delete();
$targetProject->boardColumns()->delete();
$boardColumnIds = [];
foreach (($configuration[self::COPY_BOARD_WORKFLOW]['board_columns'] ?? []) as $boardColumn) {
$newBoardColumn = $targetProject->boardColumns()->create([
'name' => $boardColumn['name'],
'position' => $boardColumn['position'],
]);
$boardColumnIds[] = $newBoardColumn->id;
if (isset($configuration[self::COPY_PROJECT_SETTINGS])) {
$targetProject->forceFill($configuration[self::COPY_PROJECT_SETTINGS])->saveQuietly();
}
$ticketStatusIds = [];
foreach (($configuration[self::COPY_BOARD_WORKFLOW]['ticket_statuses'] ?? []) as $ticketStatus) {
$boardColumnIndex = $ticketStatus['board_column_index'] ?? null;
$newTicketStatus = $targetProject->ticketStatuses()->create([
'board_column_id' => $boardColumnIndex === null ? null : ($boardColumnIds[$boardColumnIndex] ?? null),
'name' => $ticketStatus['name'],
'position' => $ticketStatus['position'],
]);
$ticketStatusIds[] = $newTicketStatus->id;
if (isset($configuration[self::COPY_BOARD_COLUMNS])) {
$blocked = $this->syncModels(
$targetProject->boardColumns()->get(),
$configuration[self::COPY_BOARD_COLUMNS],
fn (array $item) => $targetProject->boardColumns()->create($item),
static fn (Model $model, array $item) => $model->forceFill($item)->saveQuietly(),
static fn (Model $column): bool => ! $column->ticketStatuses()->exists(),
);
if ($blocked) {
$blockedAreas[] = self::COPY_BOARD_COLUMNS;
}
}
foreach (($configuration[self::COPY_BOARD_WORKFLOW]['ticket_statuses'] ?? []) as $index => $ticketStatus) {
$newTicketStatusId = $ticketStatusIds[$index] ?? null;
if (isset($configuration[self::COPY_TICKET_STATUSES])) {
$columns = $targetProject->boardColumns()->get()->values();
$items = collect($configuration[self::COPY_TICKET_STATUSES])->map(static function (array $item) use ($columns): array {
$columnIndex = $item['board_column_index'] ?? null;
$item['board_column_id'] = $columnIndex === null ? null : $columns->get($columnIndex)?->id;
unset($item['board_column_index']);
if ($newTicketStatusId === null) {
return $item;
})->all();
$blocked = $this->syncModels(
$targetProject->ticketStatuses()->get(),
$items,
fn (array $item) => $targetProject->ticketStatuses()->create($item),
static fn (Model $model, array $item) => $model->forceFill($item)->saveQuietly(),
function (Model $status) use ($statusReplacements): bool {
if (! $status->tickets()->exists()) {
return true;
}
$replacementId = $statusReplacements[$status->id] ?? null;
if ($replacementId === null) {
return false;
}
$status->tickets()->update(['ticket_status_id' => $replacementId]);
return true;
},
);
if ($blocked) {
$blockedAreas[] = self::COPY_TICKET_STATUSES;
}
}
if (isset($configuration[self::COPY_STATUS_TRANSITIONS])) {
$statuses = $targetProject->ticketStatuses()->get()->values();
foreach ($configuration[self::COPY_STATUS_TRANSITIONS] as $index => $targets) {
$status = $statuses->get($index);
if ($status !== null) {
$status->allowedTargetStatuses()->sync(collect($targets)->map(fn (int $target): ?int => $statuses->get($target)?->id)->filter()->all());
}
}
}
$relations = [
self::COPY_TICKET_TYPES => ['ticketTypes', fn (Model $item): bool => ! $item->tickets()->exists()],
self::COPY_TICKET_PRIORITIES => ['ticketPriorities', fn (Model $item): bool => ! $item->tickets()->exists()],
self::COPY_TICKET_FIELDS => ['ticketFieldDefinitions', fn (Model $item): bool => ! $item->ticketFieldValues()->exists()],
self::COPY_TICKET_LINK_TYPES => ['ticketLinkTypes', fn (Model $item): bool => ! $item->ticketLinks()->exists()],
self::COPY_REPOSITORY_CONNECTIONS => ['repositoryConnections', null],
self::COPY_NOTIFICATION_ACTIONS => ['notificationActions', null],
];
foreach ($relations as $area => [$relation, $canDelete]) {
if (! isset($configuration[$area])) {
continue;
}
$targetProject->ticketStatuses()->findOrFail($newTicketStatusId)
->allowedTargetStatuses()
->sync(
collect($ticketStatus['allowed_target_indexes'] ?? [])
->map(fn (int $statusIndex): ?int => $ticketStatusIds[$statusIndex] ?? null)
->filter(static fn (?int $statusId): bool => $statusId !== null)
->values()
->all(),
);
$blocked = $this->syncModels(
$targetProject->{$relation}()->get(),
$configuration[$area],
fn (array $item) => $targetProject->{$relation}()->create($item),
static fn (Model $model, array $item) => $model->forceFill($item)->saveQuietly(),
$canDelete,
);
if ($blocked) {
$blockedAreas[] = $area;
}
}
foreach ($targetProject->configurationRelations() as $relation) {
$targetProject->{$relation}()->update(['project_template_id' => $targetProject->project_template_id]);
}
return array_values(array_unique($blockedAreas));
});
foreach ($blockedAreas as $area) {
$this->projectTemplateOverrideManager->mark($targetProject->fresh(), $area);
}
if (array_key_exists(self::COPY_TICKET_TYPES, $configuration)) {
$targetProject->ticketTypes()->delete();
foreach ($configuration[self::COPY_TICKET_TYPES] as $ticketType) {
$targetProject->ticketTypes()->create([
'name' => $ticketType['name'],
'position' => $ticketType['position'],
'is_parent' => $ticketType['is_parent'],
]);
}
}
if (array_key_exists(self::COPY_TICKET_PRIORITIES, $configuration)) {
$targetProject->ticketPriorities()->delete();
foreach ($configuration[self::COPY_TICKET_PRIORITIES] as $ticketPriority) {
$targetProject->ticketPriorities()->create([
'name' => $ticketPriority['name'],
'position' => $ticketPriority['position'],
]);
}
}
if (array_key_exists(self::COPY_TICKET_FIELDS, $configuration)) {
$targetProject->ticketFieldDefinitions()->delete();
foreach ($configuration[self::COPY_TICKET_FIELDS] as $ticketFieldDefinition) {
$targetProject->ticketFieldDefinitions()->create([
'field_type' => $ticketFieldDefinition['field_type'],
'label' => $ticketFieldDefinition['label'],
'position' => $ticketFieldDefinition['position'],
]);
}
}
if (array_key_exists(self::COPY_TICKET_LINK_TYPES, $configuration)) {
$targetProject->ticketLinkTypes()->delete();
foreach ($configuration[self::COPY_TICKET_LINK_TYPES] as $ticketLinkType) {
$targetProject->ticketLinkTypes()->create([
'label' => $ticketLinkType['label'],
'counterpart_label' => $ticketLinkType['counterpart_label'],
'position' => $ticketLinkType['position'],
]);
}
}
if (array_key_exists(self::COPY_REPOSITORY_CONNECTIONS, $configuration)) {
$targetProject->repositoryConnections()->delete();
foreach ($configuration[self::COPY_REPOSITORY_CONNECTIONS] as $repositoryConnection) {
$targetProject->repositoryConnections()->create([
'provider' => $repositoryConnection['provider'],
'base_url' => $repositoryConnection['base_url'],
'provider_repository_id' => $repositoryConnection['provider_repository_id'],
'owner_name' => $repositoryConnection['owner_name'],
'repository_name' => $repositoryConnection['repository_name'],
'repository_full_name' => $repositoryConnection['repository_full_name'],
'repository_url' => $repositoryConnection['repository_url'],
]);
}
}
if (array_key_exists(self::COPY_NOTIFICATION_ACTIONS, $configuration)) {
$targetProject->notificationActions()->delete();
foreach ($configuration[self::COPY_NOTIFICATION_ACTIONS] as $notificationAction) {
$targetProject->notificationActions()->create([
'name' => $notificationAction['name'],
'enabled' => $notificationAction['enabled'],
'event_type' => $notificationAction['event_type'],
'channel' => $notificationAction['channel'],
'channel_configuration' => $notificationAction['channel_configuration'] ?? [],
'message_template' => $notificationAction['message_template'] ?? null,
'delivery_url' => $notificationAction['delivery_url'],
'filters' => $notificationAction['filters'] ?? [],
]);
}
}
return $blockedAreas;
}
/**
* @param list<string> $copyAreas
*/
/** @param list<string> $copyAreas */
public function handle(Project $sourceProject, Project $targetProject, array $copyAreas): void
{
$this->apply($targetProject, $this->export($sourceProject, $copyAreas));
}
/**
* @param EloquentCollection<int, Model> $models
* @param array<int, array<string, mixed>> $items
*/
private function syncModels(EloquentCollection $models, array $items, callable $create, callable $update, ?callable $canDelete = null): bool
{
foreach ($items as $index => $item) {
$model = $models->get($index);
$model === null ? $create($item) : $update($model, $item);
}
$blocked = false;
foreach ($models->slice(count($items)) as $model) {
if ($canDelete !== null && ! $canDelete($model)) {
$blocked = true;
continue;
}
$model->deleteQuietly();
}
return $blocked;
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Actions\Projects;
use App\Models\Project;
class ProjectTemplateOverrideManager
{
private static int $suppressionDepth = 0;
public function mark(Project $project, string $area): void
{
if (self::$suppressionDepth > 0) {
return;
}
$project->loadMissing('projectTemplate');
if ($project->projectTemplate === null || ! $project->projectTemplate->is_published) {
return;
}
$overrides = array_values(array_unique([
...($project->template_overrides ?? []),
$area,
]));
$project->forceFill(['template_overrides' => $overrides])->saveQuietly();
}
/**
* @param list<string> $areas
*/
public function clear(Project $project, array $areas): void
{
$remaining = array_values(array_diff($project->template_overrides ?? [], $areas));
$project->forceFill(['template_overrides' => $remaining])->saveQuietly();
}
public function withoutRecording(callable $callback): mixed
{
self::$suppressionDepth++;
try {
return $callback();
} finally {
self::$suppressionDepth--;
}
}
public function isRecording(): bool
{
return self::$suppressionDepth === 0;
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Actions\Projects;
use App\Models\Project;
class RefreshProjectBaseTemplate
{
public function __construct(
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
) {}
public function handle(Project $project, string $area): void
{
$project->loadMissing('projectTemplate');
if ($project->projectTemplate === null || $project->projectTemplate->is_published) {
return;
}
$snapshot = $this->duplicateProjectConfiguration->normalizeConfiguration(
$project->projectTemplate->configuration_snapshot ?? [],
);
$project->projectTemplate->forceFill([
'configuration_snapshot' => array_replace(
$snapshot,
$this->duplicateProjectConfiguration->export($project->fresh(), [$area]),
),
])->saveQuietly();
}
}
@@ -30,10 +30,16 @@ class ResolveProjectTemplateState
? DuplicateProjectConfiguration::copyableAreas()
: $this->duplicateProjectConfiguration->normalizeCopyAreas($areas);
$templateConfiguration = collect($projectTemplate->configuration_snapshot ?? [])
$normalizedTemplateConfiguration = $this->duplicateProjectConfiguration->normalizeConfiguration(
$projectTemplate->configuration_snapshot ?? [],
);
$templateConfiguration = collect($normalizedTemplateConfiguration)
->only($selectedAreas)
->all();
$currentConfiguration = $this->duplicateProjectConfiguration->export($project, $selectedAreas);
$persistedOverrides = $projectTemplate->is_published
? array_values(array_intersect($project->template_overrides ?? [], $selectedAreas))
: [];
$overriddenAreas = [];
$inheritedAreas = [];
@@ -41,13 +47,12 @@ class ResolveProjectTemplateState
foreach ($selectedAreas as $area) {
$label = $this->labelForArea($area);
$hasTemplateValue = array_key_exists($area, $templateConfiguration);
$hasCurrentValue = array_key_exists($area, $currentConfiguration);
if (! $hasTemplateValue && ! $hasCurrentValue) {
if (! $hasTemplateValue) {
continue;
}
if ($hasTemplateValue && $hasCurrentValue && $currentConfiguration[$area] === $templateConfiguration[$area]) {
if (! in_array($area, $persistedOverrides, true)) {
$inheritedAreas[] = [
'label' => $label,
'value' => $area,
@@ -72,6 +77,7 @@ class ResolveProjectTemplateState
'inheritsFromTemplate' => $projectTemplate->is_published,
'overriddenAreas' => $overriddenAreas,
'overriddenConfiguration' => array_intersect_key($currentConfiguration, $overriddenAreaValues),
'resetRequirements' => $this->resetRequirements($project, $templateConfiguration, $persistedOverrides),
'templateConfiguration' => $templateConfiguration,
'templateId' => $projectTemplate->id,
'templateName' => $projectTemplate->name,
@@ -79,6 +85,44 @@ class ResolveProjectTemplateState
];
}
/**
* @param array<string, mixed> $templateConfiguration
* @param list<string> $persistedOverrides
* @return array<string, mixed>
*/
private function resetRequirements(Project $project, array $templateConfiguration, array $persistedOverrides): array
{
if (! in_array(DuplicateProjectConfiguration::COPY_TICKET_STATUSES, $persistedOverrides, true)) {
return [];
}
$templateStatuses = $templateConfiguration[DuplicateProjectConfiguration::COPY_TICKET_STATUSES] ?? [];
if (! is_array($templateStatuses)) {
return [];
}
$statuses = $project->ticketStatuses()->withCount('tickets')->get()->values();
$replacementOptions = $statuses->take(count($templateStatuses))->map(
static fn ($status): array => ['id' => $status->id, 'name' => $status->name],
)->all();
$removedStatuses = $statuses->slice(count($templateStatuses))
->filter(static fn ($status): bool => $status->tickets_count > 0)
->map(static fn ($status): array => [
'id' => $status->id,
'name' => $status->name,
'ticketCount' => $status->tickets_count,
])
->values()
->all();
return $removedStatuses === [] ? [] : [
DuplicateProjectConfiguration::COPY_TICKET_STATUSES => [
'removedStatuses' => $removedStatuses,
'replacementOptions' => $replacementOptions,
],
];
}
private function labelForArea(string $area): string
{
foreach (DuplicateProjectConfiguration::copyAreaOptions() as $option) {
+46 -24
View File
@@ -2,6 +2,7 @@
namespace App\Actions\Projects;
use App\Models\Project;
use App\Models\ProjectTemplate;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
@@ -10,6 +11,7 @@ class UpdateProjectTemplate
{
public function __construct(
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
private readonly ProjectTemplateOverrideManager $projectTemplateOverrideManager,
) {}
/**
@@ -17,48 +19,68 @@ class UpdateProjectTemplate
*/
public function handle(ProjectTemplate $projectTemplate, array $attributes): ProjectTemplate
{
$projectTemplate->loadMissing('sourceProject', 'linkedProjects.projectTemplate');
$projectTemplate->loadMissing('sourceProject');
$sourceProject = $projectTemplate->sourceProject;
abort_if($sourceProject === null, 422, 'This template cannot be edited because the source project is missing.');
$copyAreas = array_values(Arr::get($attributes, 'copy_areas', []));
$normalizedCopyAreas = $this->duplicateProjectConfiguration->normalizeCopyAreas($copyAreas);
$previousConfiguration = $projectTemplate->configuration_snapshot ?? [];
$previousConfiguration = $this->duplicateProjectConfiguration->normalizeConfiguration(
$projectTemplate->configuration_snapshot ?? [],
);
$nextConfiguration = $this->duplicateProjectConfiguration->export($sourceProject, $normalizedCopyAreas);
$affectedAreas = array_values(array_unique([
...array_keys($previousConfiguration),
...array_keys($nextConfiguration),
]));
$affectedAreas = collect(array_unique([...array_keys($previousConfiguration), ...array_keys($nextConfiguration)]))
->filter(fn (string $area): bool => ($previousConfiguration[$area] ?? null) !== ($nextConfiguration[$area] ?? null))
->values()
->all();
DB::transaction(function () use ($projectTemplate, $attributes, $normalizedCopyAreas, $nextConfiguration, $previousConfiguration, $affectedAreas): void {
ProjectTemplate::query()->whereKey($projectTemplate->id)->lockForUpdate()->firstOrFail();
$projectTemplate->forceFill([
'name' => $attributes['name'],
'copy_areas' => $normalizedCopyAreas,
'configuration_snapshot' => $nextConfiguration,
])->save();
foreach ($projectTemplate->linkedProjects as $linkedProject) {
$currentConfiguration = $this->duplicateProjectConfiguration->export($linkedProject->fresh(), $affectedAreas);
$replacementConfiguration = [];
Project::query()
->where('project_template_id', $projectTemplate->id)
->orderBy('id')
->chunkById(100, function ($linkedProjects) use ($affectedAreas, $nextConfiguration, $previousConfiguration): void {
foreach ($linkedProjects as $linkedProject) {
$linkedProject = Project::query()->whereKey($linkedProject->id)->lockForUpdate()->firstOrFail();
$currentConfiguration = $this->duplicateProjectConfiguration->export($linkedProject, $affectedAreas);
$overrides = $linkedProject->template_overrides ?? [];
$replacementConfiguration = [];
foreach ($nextConfiguration as $area => $configuration) {
$isNewTemplateArea = ! array_key_exists($area, $previousConfiguration);
$matchesPreviousTemplate = array_key_exists($area, $previousConfiguration)
&& array_key_exists($area, $currentConfiguration)
&& $currentConfiguration[$area] === $previousConfiguration[$area];
foreach ($affectedAreas as $area) {
if (in_array($area, $overrides, true)) {
continue;
}
if ($isNewTemplateArea || $matchesPreviousTemplate) {
$replacementConfiguration[$area] = $configuration;
if (! array_key_exists($area, $nextConfiguration)) {
$this->projectTemplateOverrideManager->mark($linkedProject, $area);
continue;
}
if (! array_key_exists($area, $previousConfiguration)
&& array_key_exists($area, $currentConfiguration)
&& $currentConfiguration[$area] !== []) {
$this->projectTemplateOverrideManager->mark($linkedProject, $area);
continue;
}
$replacementConfiguration[$area] = $nextConfiguration[$area];
}
if ($replacementConfiguration !== []) {
$this->duplicateProjectConfiguration->apply($linkedProject, $replacementConfiguration);
}
}
}
if ($replacementConfiguration === []) {
continue;
}
$this->duplicateProjectConfiguration->apply($linkedProject->fresh(), $replacementConfiguration);
}
});
});
return $projectTemplate->fresh(['sourceProject'])->loadCount('linkedProjects');
@@ -10,23 +10,39 @@ class UpdateProjectTemplateLink
{
public function __construct(
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
private readonly ProjectTemplateOverrideManager $projectTemplateOverrideManager,
) {}
public function switch(Project $project, ProjectTemplate $template): void
{
DB::transaction(function () use ($project, $template): void {
$project = Project::query()->whereKey($project->id)->lockForUpdate()->firstOrFail();
$configuration = $this->duplicateProjectConfiguration->normalizeConfiguration(
$template->configuration_snapshot ?? [],
);
$localAreas = array_values(array_diff(
DuplicateProjectConfiguration::copyableAreas(),
array_keys($configuration),
));
$project->forceFill([
'project_template_id' => $template->id,
])->save();
'template_overrides' => $localAreas,
])->saveQuietly();
$this->duplicateProjectConfiguration->apply(
$blockedAreas = $this->duplicateProjectConfiguration->apply($project, $configuration);
$this->projectTemplateOverrideManager->clear(
$project->fresh(),
$template->configuration_snapshot ?? [],
array_values(array_diff(array_keys($configuration), $blockedAreas)),
);
});
}
public function reset(Project $project): void
/**
* @param list<string> $areas
* @param array<int|string, int|string> $statusReplacements
*/
public function reset(Project $project, array $areas, array $statusReplacements = []): void
{
$template = $project->projectTemplate;
@@ -34,10 +50,19 @@ class UpdateProjectTemplateLink
return;
}
DB::transaction(function () use ($project, $template): void {
$this->duplicateProjectConfiguration->apply(
$project->fresh(),
DB::transaction(function () use ($project, $template, $areas, $statusReplacements): void {
$project = Project::query()->whereKey($project->id)->lockForUpdate()->firstOrFail();
$configuration = collect($this->duplicateProjectConfiguration->normalizeConfiguration(
$template->configuration_snapshot ?? [],
))->only($areas)->all();
$blockedAreas = $this->duplicateProjectConfiguration->apply(
$project,
$configuration,
$statusReplacements,
);
$this->projectTemplateOverrideManager->clear(
$project->fresh(),
array_values(array_diff(array_keys($configuration), $blockedAreas)),
);
});
}
+1 -5
View File
@@ -47,11 +47,7 @@ class CreateProjectTicket
$nextSequenceNumber = (int) Ticket::query()
->where('project_id', $project->id)
->max('sequence_number') + 1;
$ticketStatusQuery = TicketStatus::query()
->where(
$project->project_template_id === null ? 'project_id' : 'project_template_id',
$project->project_template_id ?? $project->id,
);
$ticketStatusQuery = TicketStatus::query()->where('project_id', $project->id);
$ticketStatus = $ticketStatusQuery->findOrFail(Arr::get($attributes, 'ticket_status_id'));