Merge pull request 'KAN-8 Add project template context to API and MCP' (#90) from koda/kan-8-add-project-template-to-mcp-api into main
linter / quality (push) Successful in 1m35s
tests / ci (8.4) (push) Has been cancelled

Reviewed-on: OpenSource/KanbanGit#90
This commit was merged in pull request #90.
This commit is contained in:
2026-06-23 21:18:09 +00:00
43 changed files with 2573 additions and 30 deletions
@@ -2,6 +2,8 @@
namespace App\Actions\Notifications;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Actions\Projects\ResolveProjectTemplateState;
use App\Enums\DiscordAllowedMentionType;
use App\Enums\NotificationChannel;
use App\Enums\NotificationEventType;
@@ -15,6 +17,7 @@ class BuildProjectNotificationSettingsPayload
{
public function __construct(
private readonly ListProjectNotificationActions $listProjectNotificationActions,
private readonly ResolveProjectTemplateState $resolveProjectTemplateState,
) {}
/**
@@ -33,6 +36,9 @@ class BuildProjectNotificationSettingsPayload
)->resolve(),
'project' => ProjectResource::make($project)->resolve(),
'status' => $status,
'templateState' => $this->resolveProjectTemplateState->handle($project, [
DuplicateProjectConfiguration::COPY_NOTIFICATION_ACTIONS,
]),
'templateVariables' => $this->templateVariables(),
];
}
@@ -9,6 +9,10 @@ use App\Models\Project;
class BuildProjectBoardSettingsPayload
{
public function __construct(
private readonly ResolveProjectTemplateState $resolveProjectTemplateState,
) {}
/**
* @return array<string, mixed>
*/
@@ -27,6 +31,9 @@ class BuildProjectBoardSettingsPayload
)->resolve(),
'project' => ProjectResource::make($project)->resolve(),
'status' => $status,
'templateState' => $this->resolveProjectTemplateState->handle($project, [
DuplicateProjectConfiguration::COPY_BOARD_WORKFLOW,
]),
'ticketStatuses' => TicketStatusResource::collection(
$project->ticketStatuses()
->with(['allowedTargetStatuses.boardColumn', 'boardColumn'])
@@ -13,6 +13,10 @@ use App\Models\TicketFieldDefinition;
class BuildProjectTicketMetadataSettingsPayload
{
public function __construct(
private readonly ResolveProjectTemplateState $resolveProjectTemplateState,
) {}
/**
* @return array<string, mixed>
*/
@@ -23,6 +27,13 @@ class BuildProjectTicketMetadataSettingsPayload
'project' => ProjectResource::make($project)->resolve(),
'error' => $error,
'status' => $status,
'templateState' => $this->resolveProjectTemplateState->handle($project, [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
DuplicateProjectConfiguration::COPY_TICKET_PRIORITIES,
DuplicateProjectConfiguration::COPY_TICKET_FIELDS,
DuplicateProjectConfiguration::COPY_TICKET_LINK_TYPES,
]),
'ticketFieldDefinitions' => TicketFieldDefinitionResource::collection($project->ticketFieldDefinitions()->get())->resolve(),
'ticketLinkTypes' => TicketLinkTypeResource::collection($project->ticketLinkTypes()->get())->resolve(),
'ticketPriorities' => TicketPriorityResource::collection($project->ticketPriorities()->get())->resolve(),
+45 -5
View File
@@ -6,25 +6,65 @@ use App\Actions\Permissions\PermissionService;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Enums\Permission;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class CreateProject
{
public function __construct(
private readonly CreateProjectBaseTemplate $createProjectBaseTemplate,
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
private readonly InitializeProjectTicketMetadata $initializeProjectTicketMetadata,
private readonly PermissionService $permissionService,
) {}
/**
* @param array{key: string, name: string} $attributes
* @param array{key: string, name: string, creation_mode?: string, source_project_id?: int|string|null, source_template_id?: int|string|null, copy_areas?: array<int, string>|null} $attributes
*/
public function handle(array $attributes, User $actor): Project
{
$project = Project::query()->create($attributes);
return DB::transaction(function () use ($attributes, $actor): Project {
$project = Project::query()->create(Arr::only($attributes, ['key', 'name']));
$this->initializeProjectTicketMetadata->handle($project);
$this->permissionService->grant($actor, Permission::ProjectAdmin, $project);
$this->initializeProjectTicketMetadata->handle($project);
$this->permissionService->grant($actor, Permission::ProjectAdmin, $project);
return $project;
$creationMode = $attributes['creation_mode'] ?? 'scratch';
if ($creationMode === 'duplicate' && isset($attributes['source_project_id'])) {
$sourceProject = Project::query()->findOrFail((int) $attributes['source_project_id']);
$this->duplicateProjectConfiguration->handle(
$sourceProject,
$project,
array_values($attributes['copy_areas'] ?? []),
);
}
if ($creationMode === 'template' && isset($attributes['source_template_id'])) {
$template = ProjectTemplate::query()->findOrFail((int) $attributes['source_template_id']);
$this->duplicateProjectConfiguration->apply(
$project,
$template->configuration_snapshot ?? [],
);
$project->forceFill([
'project_template_id' => $template->id,
])->save();
}
if ($project->project_template_id === null) {
$baseTemplate = $this->createProjectBaseTemplate->handle($project->fresh() ?? $project);
$project->forceFill([
'project_template_id' => $baseTemplate->id,
])->save();
}
return $project->fresh() ?? $project;
});
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Actions\Projects;
use App\Models\Project;
use App\Models\ProjectTemplate;
class CreateProjectBaseTemplate
{
public function __construct(
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
) {}
public function handle(Project $project): ProjectTemplate
{
$copyAreas = DuplicateProjectConfiguration::copyableAreas();
return ProjectTemplate::query()->create([
'project_id' => $project->id,
'source_project_id' => $project->id,
'name' => "{$project->name} base template",
'slug' => strtolower($project->key).'-base-template',
'is_published' => false,
'copy_areas' => $copyAreas,
'configuration_snapshot' => $this->duplicateProjectConfiguration->export($project, $copyAreas),
]);
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Actions\Projects;
use App\Models\Project;
use App\Models\ProjectTemplate;
use Illuminate\Support\Arr;
class CreateProjectTemplate
{
public function __construct(
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
) {}
/**
* @param array{name: string, slug: string, copy_areas?: array<int, string>} $attributes
*/
public function handle(Project $sourceProject, array $attributes): ProjectTemplate
{
$copyAreas = array_values(Arr::get($attributes, 'copy_areas', []));
return ProjectTemplate::query()->create([
'project_id' => null,
'source_project_id' => $sourceProject->id,
'name' => $attributes['name'],
'slug' => $attributes['slug'],
'is_published' => true,
'copy_areas' => $this->duplicateProjectConfiguration->normalizeCopyAreas($copyAreas),
'configuration_snapshot' => $this->duplicateProjectConfiguration->export($sourceProject, $copyAreas),
]);
}
}
@@ -0,0 +1,400 @@
<?php
namespace App\Actions\Projects;
use App\Models\Project;
class DuplicateProjectConfiguration
{
public const COPY_PROJECT_SETTINGS = 'project_settings';
public const COPY_BOARD_WORKFLOW = 'board_workflow';
public const COPY_TICKET_TYPES = 'ticket_types';
public const COPY_TICKET_PRIORITIES = 'ticket_priorities';
public const COPY_TICKET_FIELDS = 'ticket_fields';
public const COPY_TICKET_LINK_TYPES = 'ticket_link_types';
public const COPY_REPOSITORY_CONNECTIONS = 'repository_connections';
public const COPY_NOTIFICATION_ACTIONS = 'notification_actions';
/**
* @return list<string>
*/
public static function copyableAreas(): array
{
return [
self::COPY_PROJECT_SETTINGS,
self::COPY_BOARD_WORKFLOW,
self::COPY_TICKET_TYPES,
self::COPY_TICKET_PRIORITIES,
self::COPY_TICKET_FIELDS,
self::COPY_TICKET_LINK_TYPES,
self::COPY_REPOSITORY_CONNECTIONS,
self::COPY_NOTIFICATION_ACTIONS,
];
}
/**
* @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.',
],
];
}
/**
* @param list<string> $copyAreas
* @return list<string>
*/
public function normalizeCopyAreas(array $copyAreas): array
{
return array_values(array_intersect(self::copyableAreas(), array_unique($copyAreas)));
}
/**
* @param list<string> $copyAreas
* @return array<string, mixed>
*/
public function export(Project $sourceProject, array $copyAreas): array
{
$selectedAreas = $this->normalizeCopyAreas($copyAreas);
if ($selectedAreas === []) {
return [];
}
$sourceProject->loadMissing([
'boardColumns',
'notificationActions',
'repositoryConnections',
'ticketFieldDefinitions',
'ticketLinkTypes',
'ticketPriorities',
'ticketStatuses.allowedTargetStatuses',
'ticketTypes',
]);
$configuration = [];
if (in_array(self::COPY_PROJECT_SETTINGS, $selectedAreas, true)) {
$configuration[self::COPY_PROJECT_SETTINGS] = [
'show_author' => $sourceProject->show_author,
'show_story_points' => $sourceProject->show_story_points,
];
}
if (in_array(self::COPY_BOARD_WORKFLOW, $selectedAreas, true)) {
$boardColumnIndexes = [];
$boardColumns = [];
foreach ($sourceProject->boardColumns as $index => $boardColumn) {
$boardColumnIndexes[$boardColumn->id] = $index;
$boardColumns[] = [
'name' => $boardColumn->name,
'position' => $boardColumn->position,
];
}
$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;
}
/**
* @param array<string, mixed> $configuration
*/
public function apply(Project $targetProject, array $configuration): void
{
if (array_key_exists(self::COPY_PROJECT_SETTINGS, $configuration)) {
$projectSettings = $configuration[self::COPY_PROJECT_SETTINGS];
$targetProject->forceFill([
'show_author' => (bool) ($projectSettings['show_author'] ?? $targetProject->show_author),
'show_story_points' => (bool) ($projectSettings['show_story_points'] ?? $targetProject->show_story_points),
])->save();
}
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;
}
$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;
}
foreach (($configuration[self::COPY_BOARD_WORKFLOW]['ticket_statuses'] ?? []) as $index => $ticketStatus) {
$newTicketStatusId = $ticketStatusIds[$index] ?? null;
if ($newTicketStatusId === null) {
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(),
);
}
}
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'] ?? [],
]);
}
}
}
/**
* @param list<string> $copyAreas
*/
public function handle(Project $sourceProject, Project $targetProject, array $copyAreas): void
{
$this->apply($targetProject, $this->export($sourceProject, $copyAreas));
}
}
@@ -0,0 +1,92 @@
<?php
namespace App\Actions\Projects;
use App\Models\Project;
use App\Models\ProjectTemplate;
class ResolveProjectTemplateState
{
public function __construct(
private readonly DuplicateProjectConfiguration $duplicateProjectConfiguration,
) {}
/**
* @param list<string>|null $areas
* @return array<string, mixed>|null
*/
public function handle(Project $project, ?array $areas = null): ?array
{
$project->loadMissing('projectTemplate');
/** @var ProjectTemplate|null $projectTemplate */
$projectTemplate = $project->projectTemplate;
if ($projectTemplate === null) {
return null;
}
$selectedAreas = $areas === null
? DuplicateProjectConfiguration::copyableAreas()
: $this->duplicateProjectConfiguration->normalizeCopyAreas($areas);
$templateConfiguration = collect($projectTemplate->configuration_snapshot ?? [])
->only($selectedAreas)
->all();
$currentConfiguration = $this->duplicateProjectConfiguration->export($project, $selectedAreas);
$overriddenAreas = [];
$inheritedAreas = [];
foreach ($selectedAreas as $area) {
$label = $this->labelForArea($area);
$hasTemplateValue = array_key_exists($area, $templateConfiguration);
$hasCurrentValue = array_key_exists($area, $currentConfiguration);
if (! $hasTemplateValue && ! $hasCurrentValue) {
continue;
}
if ($hasTemplateValue && $hasCurrentValue && $currentConfiguration[$area] === $templateConfiguration[$area]) {
$inheritedAreas[] = [
'label' => $label,
'value' => $area,
];
continue;
}
$overriddenAreas[] = [
'label' => $label,
'value' => $area,
];
}
$overriddenAreaValues = array_flip(array_column($overriddenAreas, 'value'));
$inheritedAreaValues = array_flip(array_column($inheritedAreas, 'value'));
return [
'effectiveConfiguration' => array_replace($templateConfiguration, array_intersect_key($currentConfiguration, $overriddenAreaValues)),
'inheritedAreas' => $inheritedAreas,
'inheritedConfiguration' => array_intersect_key($templateConfiguration, $inheritedAreaValues),
'inheritsFromTemplate' => true,
'overriddenAreas' => $overriddenAreas,
'overriddenConfiguration' => array_intersect_key($currentConfiguration, $overriddenAreaValues),
'templateConfiguration' => $templateConfiguration,
'templateId' => $projectTemplate->id,
'templateName' => $projectTemplate->name,
'templateSlug' => $projectTemplate->slug,
];
}
private function labelForArea(string $area): string
{
foreach (DuplicateProjectConfiguration::copyAreaOptions() as $option) {
if ($option['value'] === $area) {
return $option['label'];
}
}
return $area;
}
}
@@ -4,6 +4,8 @@ namespace App\Actions\Repositories;
use App\Actions\Git\Data\GitRepository;
use App\Actions\Git\GitProviderManager;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Actions\Projects\ResolveProjectTemplateState;
use App\Http\Resources\AvailableGitRepositorySourceResource;
use App\Http\Resources\ProjectResource;
use App\Http\Resources\RepositoryConnectionResource;
@@ -18,6 +20,7 @@ class BuildProjectRepositorySettingsPayload
{
public function __construct(
private readonly GitProviderManager $gitProviderManager,
private readonly ResolveProjectTemplateState $resolveProjectTemplateState,
) {}
/**
@@ -41,6 +44,9 @@ class BuildProjectRepositorySettingsPayload
'project' => ProjectResource::make($project)->resolve(),
'repositoryConnections' => RepositoryConnectionResource::collection($repositoryConnections)->resolve(),
'status' => $status,
'templateState' => $this->resolveProjectTemplateState->handle($project, [
DuplicateProjectConfiguration::COPY_REPOSITORY_CONNECTIONS,
]),
];
}
+23 -1
View File
@@ -6,13 +6,17 @@ use App\Actions\Permissions\PermissionService;
use App\Actions\Projects\BuildProjectBacklogPayload;
use App\Actions\Projects\CreateProject;
use App\Actions\Projects\DeleteProject;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Actions\Projects\ListVisibleProjects;
use App\Actions\Projects\ResolveProjectTemplateState;
use App\Enums\Permission;
use App\Http\Requests\DeleteProjectRequest;
use App\Http\Requests\StoreProjectRequest;
use App\Http\Requests\SyncProjectPermissionsRequest;
use App\Http\Resources\PermissionOptionResource;
use App\Http\Resources\ProjectResource;
use App\Http\Resources\ProjectTemplateResource;
use App\Models\ProjectTemplate;
use App\Http\Resources\TeamResource;
use App\Http\Resources\UserResource;
use App\Models\Project;
@@ -32,6 +36,7 @@ class ProjectController extends Controller
private readonly DeleteProject $deleteProject,
private readonly ListVisibleProjects $listVisibleProjects,
private readonly PermissionService $permissionService,
private readonly ResolveProjectTemplateState $resolveProjectTemplateState,
) {}
public function index(Request $request): Response
@@ -51,7 +56,23 @@ class ProjectController extends Controller
403,
);
return Inertia::render('projects/Create');
$sourceTemplates = ProjectTemplate::query()
->published()
->with('sourceProject')
->orderBy('name')
->get();
$selectedTemplateId = $request->integer('template');
return Inertia::render('projects/Create', [
'copyAreaOptions' => DuplicateProjectConfiguration::copyAreaOptions(),
'sourceProjects' => ProjectResource::collection(
$this->listVisibleProjects->handle($request->user()),
)->resolve(),
'sourceTemplates' => ProjectTemplateResource::collection($sourceTemplates)->resolve(),
'selectedSourceTemplateId' => $sourceTemplates->contains('id', $selectedTemplateId)
? $selectedTemplateId
: null,
]);
}
public function store(StoreProjectRequest $request): RedirectResponse
@@ -73,6 +94,7 @@ class ProjectController extends Controller
return Inertia::render('projects/Show', [
'canManageAccess' => $this->permissionService->allows($user, Permission::ProjectAdmin, $project),
'project' => ProjectResource::make($project)->resolve(),
'templateState' => $this->resolveProjectTemplateState->handle($project),
]);
}
@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers;
use App\Actions\Projects\CreateProjectTemplate;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Http\Requests\StoreProjectTemplateRequest;
use App\Http\Resources\ProjectResource;
use App\Http\Resources\ProjectTemplateResource;
use App\Models\Project;
use App\Models\ProjectTemplate;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class ProjectTemplateController extends Controller
{
public function __construct(
private readonly CreateProjectTemplate $createProjectTemplate,
) {}
public function index(Request $request): Response
{
return Inertia::render('project-templates/Index', [
'status' => session('status'),
'templates' => ProjectTemplateResource::collection(
ProjectTemplate::query()
->published()
->with('sourceProject')
->orderBy('name')
->get(),
)->resolve(),
]);
}
public function create(Project $project): Response
{
return Inertia::render('project-templates/Create', [
'copyAreaOptions' => DuplicateProjectConfiguration::copyAreaOptions(),
'project' => ProjectResource::make($project)->resolve(),
]);
}
public function store(StoreProjectTemplateRequest $request, Project $project): RedirectResponse
{
$template = $this->createProjectTemplate->handle($project, $request->validated());
return to_route('project-templates.index')
->with('status', "Template {$template->name} was created.");
}
public function destroy(ProjectTemplate $projectTemplate): RedirectResponse
{
abort_if(! $projectTemplate->is_published, 404);
$templateName = $projectTemplate->name;
$projectTemplate->delete();
return to_route('project-templates.index')
->with('status', "Template {$templateName} was deleted.");
}
}
+59
View File
@@ -2,6 +2,10 @@
namespace App\Http\Requests;
use App\Actions\Permissions\PermissionService;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Enums\Permission;
use App\Models\Project;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
@@ -20,12 +24,21 @@ class StoreProjectRequest extends FormRequest
protected function prepareForValidation(): void
{
$key = Arr::get($this->all(), 'key');
$creationMode = Arr::get($this->all(), 'creation_mode', 'scratch');
$copyAreas = Arr::get($this->all(), 'copy_areas', []);
if ($key !== null) {
$this->merge([
'key' => strtoupper(trim((string) $key)),
]);
}
$this->merge([
'creation_mode' => is_string($creationMode) ? trim($creationMode) : 'scratch',
'copy_areas' => is_array($copyAreas)
? array_values($copyAreas)
: ($copyAreas === null || $copyAreas === '' ? [] : [(string) $copyAreas]),
]);
}
/**
@@ -36,6 +49,7 @@ class StoreProjectRequest extends FormRequest
public function rules(): array
{
return [
'creation_mode' => ['required', 'string', Rule::in(['scratch', 'duplicate', 'template'])],
'key' => [
'required',
'string',
@@ -44,6 +58,51 @@ class StoreProjectRequest extends FormRequest
Rule::unique('projects', 'key'),
],
'name' => ['required', 'string', 'max:255'],
'source_project_id' => [
Rule::requiredIf(fn (): bool => $this->input('creation_mode') === 'duplicate'),
'nullable',
'integer',
Rule::exists('projects', 'id'),
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === null || $value === '') {
return;
}
$project = Project::query()->find($value);
if ($project === null) {
return;
}
$permissionService = app(PermissionService::class);
if (! $permissionService->allows($this->user(), Permission::ProjectRead, $project)) {
$fail('Select a project you can access as the duplication source.');
}
},
],
'source_template_id' => [
Rule::requiredIf(fn (): bool => $this->input('creation_mode') === 'template'),
'nullable',
'integer',
Rule::exists('project_templates', 'id')->where(fn ($query) => $query->where('is_published', true)),
],
'copy_areas' => ['nullable', 'array'],
'copy_areas.*' => [
'string',
Rule::in(DuplicateProjectConfiguration::copyableAreas()),
],
];
}
/**
* @return array<string, string>
*/
public function messages(): array
{
return [
'source_project_id.required' => 'Select a source project to duplicate from.',
'source_template_id.required' => 'Select a template to create the project from.',
];
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Http\Requests;
use App\Actions\Projects\DuplicateProjectConfiguration;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class StoreProjectTemplateRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->can('create-project') ?? false;
}
protected function prepareForValidation(): void
{
if ($this->filled('slug')) {
$this->merge([
'slug' => Str::slug((string) $this->input('slug')),
]);
}
}
/**
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'slug' => ['required', 'string', 'max:255', 'alpha_dash', Rule::unique('project_templates', 'slug')],
'copy_areas' => ['required', 'array', 'min:1'],
'copy_areas.*' => ['string', Rule::in(DuplicateProjectConfiguration::copyableAreas())],
];
}
}
+24
View File
@@ -2,8 +2,10 @@
namespace App\Http\Resources;
use App\Actions\Projects\ResolveProjectTemplateState;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Arr;
class ProjectResource extends JsonResource
{
@@ -14,10 +16,32 @@ class ProjectResource extends JsonResource
*/
public function toArray(Request $request): array
{
$this->resource->loadMissing('projectTemplate');
$templateState = app(ResolveProjectTemplateState::class)->handle($this->resource);
return [
'id' => $this->id,
'name' => $this->name,
'key' => $this->key,
'project_template_id' => $this->project_template_id,
'project_template' => $this->projectTemplate === null
? null
: ProjectTemplateResource::make($this->projectTemplate)->resolve(),
'template_state' => $templateState === null
? null
: [
'effective_configuration' => Arr::get($templateState, 'effectiveConfiguration', []),
'inherited_areas' => Arr::get($templateState, 'inheritedAreas', []),
'inherited_configuration' => Arr::get($templateState, 'inheritedConfiguration', []),
'inherits_from_template' => Arr::get($templateState, 'inheritsFromTemplate', false),
'overridden_areas' => Arr::get($templateState, 'overriddenAreas', []),
'overridden_configuration' => Arr::get($templateState, 'overriddenConfiguration', []),
'template_configuration' => Arr::get($templateState, 'templateConfiguration', []),
'template_id' => Arr::get($templateState, 'templateId'),
'template_name' => Arr::get($templateState, 'templateName'),
'template_slug' => Arr::get($templateState, 'templateSlug'),
],
'show_author' => $this->show_author,
'show_story_points' => $this->show_story_points,
'created_at' => $this->created_at?->toISOString(),
@@ -0,0 +1,51 @@
<?php
namespace App\Http\Resources;
use App\Models\ProjectTemplate;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Arr;
class ProjectTemplateResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
if ($this->resource instanceof ProjectTemplate) {
return [
'id' => $this->id,
'project_id' => $this->project_id,
'source_project_id' => $this->source_project_id,
'source_project' => $this->relationLoaded('sourceProject') && $this->sourceProject !== null
? ProjectResource::make($this->sourceProject)->resolve()
: null,
'name' => $this->name,
'slug' => $this->slug,
'is_published' => $this->is_published,
'copy_areas' => $this->copy_areas ?? [],
'configuration_snapshot' => $this->configuration_snapshot ?? [],
'created_at' => $this->created_at?->toISOString(),
'updated_at' => $this->updated_at?->toISOString(),
];
}
return [
'id' => Arr::get($this->resource, 'id'),
'project_id' => Arr::get($this->resource, 'project_id'),
'source_project_id' => Arr::get($this->resource, 'source_project_id'),
'source_project' => Arr::get($this->resource, 'source_project'),
'name' => Arr::get($this->resource, 'name'),
'slug' => Arr::get($this->resource, 'slug'),
'is_published' => Arr::get($this->resource, 'is_published', true),
'copy_areas' => Arr::get($this->resource, 'copy_areas', []),
'configuration_snapshot' => Arr::get($this->resource, 'configuration_snapshot', []),
'created_at' => Arr::get($this->resource, 'created_at'),
'updated_at' => Arr::get($this->resource, 'updated_at'),
];
}
}
+14 -1
View File
@@ -7,11 +7,13 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Str;
#[Fillable(['name', 'key', 'show_author', 'show_story_points'])]
#[Fillable(['name', 'key', 'project_template_id', 'show_author', 'show_story_points'])]
class Project extends Model
{
/** @use HasFactory<ProjectFactory> */
@@ -44,6 +46,17 @@ class Project extends Model
return $this->morphMany(PermissionAssignment::class, 'scope');
}
public function projectTemplate(): BelongsTo
{
return $this->belongsTo(ProjectTemplate::class, 'project_template_id');
}
public function baseTemplate(): HasOne
{
return $this->hasOne(ProjectTemplate::class)
->where('is_published', false);
}
public function boardColumns(): HasMany
{
return $this->hasMany(BoardColumn::class)
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Models;
use Database\Factories\ProjectTemplateFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Builder;
#[Fillable(['project_id', 'source_project_id', 'name', 'slug', 'is_published', 'copy_areas', 'configuration_snapshot'])]
class ProjectTemplate extends Model
{
/** @use HasFactory<ProjectTemplateFactory> */
use HasFactory;
protected function casts(): array
{
return [
'copy_areas' => 'array',
'configuration_snapshot' => 'array',
'is_published' => 'boolean',
];
}
public function scopePublished(Builder $query): Builder
{
return $query->where('is_published', true);
}
public function project(): BelongsTo
{
return $this->belongsTo(Project::class);
}
public function sourceProject(): BelongsTo
{
return $this->belongsTo(Project::class, 'source_project_id');
}
}
@@ -0,0 +1,36 @@
<?php
namespace Database\Factories;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\Project;
use App\Models\ProjectTemplate;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends Factory<ProjectTemplate>
*/
class ProjectTemplateFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'source_project_id' => Project::factory(),
'name' => Str::title(fake()->unique()->words(3, true)),
'slug' => fake()->unique()->slug(),
'copy_areas' => [DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS],
'configuration_snapshot' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS => [
'show_author' => true,
'show_story_points' => true,
],
],
];
}
}
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('project_templates', function (Blueprint $table): void {
$table->id();
$table->foreignId('source_project_id')->nullable()->constrained('projects')->nullOnDelete();
$table->string('name');
$table->string('slug')->unique();
$table->json('copy_areas');
$table->json('configuration_snapshot');
$table->timestamps();
$table->index(['source_project_id', 'name']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('project_templates');
}
};
@@ -0,0 +1,54 @@
<?php
use App\Actions\Projects\CreateProjectBaseTemplate;
use App\Models\Project;
use App\Models\ProjectTemplate;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('project_templates', function (Blueprint $table): void {
$table->foreignId('project_id')->nullable()->after('id')->constrained('projects')->nullOnDelete();
$table->boolean('is_published')->default(true)->after('slug');
});
Schema::table('projects', function (Blueprint $table): void {
$table->foreignId('project_template_id')->nullable()->after('key')->constrained('project_templates')->nullOnDelete();
});
$projects = Project::query()->whereNull('project_template_id')->get();
$createProjectBaseTemplate = app(CreateProjectBaseTemplate::class);
foreach ($projects as $project) {
$baseTemplate = $createProjectBaseTemplate->handle($project);
$project->forceFill([
'project_template_id' => $baseTemplate->id,
])->save();
}
ProjectTemplate::query()
->whereNull('project_id')
->update(['is_published' => true]);
}
public function down(): void
{
Project::query()->update(['project_template_id' => null]);
ProjectTemplate::query()->where('is_published', false)->delete();
Schema::table('projects', function (Blueprint $table): void {
$table->dropConstrainedForeignId('project_template_id');
});
Schema::table('project_templates', function (Blueprint $table): void {
$table->dropConstrainedForeignId('project_id');
$table->dropColumn('is_published');
});
}
};
+9
View File
@@ -5,6 +5,7 @@ import {
Folder,
FolderGit2,
LayoutGrid,
Layers3,
Shield,
Users,
} from 'lucide-vue-next';
@@ -44,6 +45,14 @@ const mainNavItems = computed<NavItem[]>(() => {
},
];
if (page.props.auth.permissions.projectCreate) {
items.push({
title: 'Project templates',
href: '/project-templates',
icon: Layers3,
});
}
if (page.props.auth.permissions.globalAdmin) {
items.push({
title: 'Users',
@@ -0,0 +1,142 @@
<script setup lang="ts">
import { Head, Link, useForm } from '@inertiajs/vue3';
import { computed } from 'vue';
import Heading from '@/components/Heading.vue';
import InputError from '@/components/InputError.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/AppLayout.vue';
import { show as projectShow } from '@/routes/projects/index';
import type { BreadcrumbItem, ProjectTemplatesCreatePageProps } from '@/types';
const props = defineProps<ProjectTemplatesCreatePageProps>();
const breadcrumbs: BreadcrumbItem[] = [
{
title: 'Projects',
href: '/projects',
},
{
title: props.project.name,
href: projectShow(props.project.id),
},
{
title: 'Save as new template',
href: `/projects/${props.project.id}/templates/create`,
},
];
const form = useForm({
copy_areas: props.copyAreaOptions.map((copyAreaOption) => copyAreaOption.value),
name: `${props.project.name} template`,
slug: `${props.project.key.toLowerCase()}-template`,
});
const copyAreasError = computed(() => {
return (
form.errors.copy_areas ??
Object.entries(form.errors).find(([key]) => key.startsWith('copy_areas.'))?.[1] ??
''
);
});
const submit = (): void => {
form.post(`/projects/${props.project.id}/templates`, {
preserveScroll: true,
});
};
</script>
<template>
<AppLayout :breadcrumbs="breadcrumbs">
<Head :title="`Save ${project.name} as new template`" />
<div class="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-6 p-4">
<div class="space-y-3">
<Badge variant="outline" class="px-3 py-1">{{ project.key }}</Badge>
<Heading
:title="`Save ${project.name} as new template`"
description="Capture reusable project configuration without copying operational ticket data."
/>
</div>
<Card>
<CardHeader>
<CardTitle>Template details</CardTitle>
<CardDescription>
Pick the configuration groups that should be reusable in future projects.
</CardDescription>
</CardHeader>
<CardContent>
<form class="space-y-6" @submit.prevent="submit">
<div class="grid gap-2">
<Label for="name">Template name</Label>
<Input id="name" v-model="form.name" required placeholder="Foundation template" />
<InputError :message="form.errors.name" />
</div>
<div class="grid gap-2">
<Label for="slug">Template slug</Label>
<Input id="slug" v-model="form.slug" required placeholder="foundation-template" />
<p class="text-muted-foreground text-sm">
Slugs are normalized automatically and used to identify reusable templates.
</p>
<InputError :message="form.errors.slug" />
</div>
<div class="grid gap-3">
<div>
<Label>Configuration groups</Label>
<p class="text-muted-foreground text-sm">
Only the selected groups will be stored in the template.
</p>
</div>
<div class="grid gap-3">
<Label
v-for="copyAreaOption in copyAreaOptions"
:key="copyAreaOption.value"
class="flex cursor-pointer items-start gap-3 rounded-xl border p-4"
>
<input
v-model="form.copy_areas"
type="checkbox"
:value="copyAreaOption.value"
class="mt-1"
/>
<div class="space-y-1">
<div class="font-medium">{{ copyAreaOption.label }}</div>
<p class="text-muted-foreground text-sm">
{{ copyAreaOption.description }}
</p>
</div>
</Label>
</div>
<InputError :message="copyAreasError" />
</div>
<div class="flex items-center gap-3">
<Button type="submit" :disabled="form.processing">
Save new template
</Button>
<Button as-child variant="outline">
<Link :href="projectShow(project.id)">Cancel</Link>
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
</AppLayout>
</template>
@@ -0,0 +1,113 @@
<script setup lang="ts">
import { Head, Link, router } from '@inertiajs/vue3';
import Heading from '@/components/Heading.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import AppLayout from '@/layouts/AppLayout.vue';
import { create as projectsCreate, index as projectsIndex } from '@/routes/projects/index';
import type { BreadcrumbItem, ProjectTemplatesIndexPageProps } from '@/types';
const props = defineProps<ProjectTemplatesIndexPageProps>();
const breadcrumbs: BreadcrumbItem[] = [
{
title: 'Project templates',
href: '/project-templates',
},
];
const removeTemplate = (templateId: number): void => {
router.delete(`/project-templates/${templateId}`, {
preserveScroll: true,
});
};
</script>
<template>
<AppLayout :breadcrumbs="breadcrumbs">
<Head title="Project templates" />
<div class="flex flex-1 flex-col gap-6 p-4">
<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<Heading
title="Project templates"
description="Reusable published project templates. Internal project base templates stay hidden here by default."
/>
<div class="flex flex-wrap gap-3">
<Button as-child variant="outline">
<Link :href="projectsIndex()">Back to projects</Link>
</Button>
<Button as-child>
<Link :href="projectsCreate()">Create project</Link>
</Button>
</div>
</div>
<div
v-if="status"
class="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-900 dark:border-emerald-900/70 dark:bg-emerald-950/40 dark:text-emerald-100"
>
{{ status }}
</div>
<div v-if="templates.length === 0" class="text-muted-foreground text-sm">
No published project templates have been saved yet.
</div>
<div v-else class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<Card v-for="template in templates" :key="template.id" class="h-full">
<CardHeader>
<div class="flex flex-wrap items-center gap-2">
<CardTitle>{{ template.name }}</CardTitle>
<Badge variant="secondary">{{ template.slug }}</Badge>
</div>
<CardDescription>
<template v-if="template.source_project">
Saved from {{ template.source_project.name }} ({{ template.source_project.key }}).
</template>
<template v-else>
Saved template configuration.
</template>
</CardDescription>
</CardHeader>
<CardContent class="space-y-4">
<div class="flex flex-wrap gap-2">
<Badge
v-for="copyArea in template.copy_areas"
:key="copyArea"
variant="outline"
>
{{ copyArea }}
</Badge>
</div>
<div class="flex flex-wrap gap-3">
<Button as-child variant="outline">
<Link :href="projectsCreate({ query: { template: template.id } })">
Use template
</Link>
</Button>
<Button
type="button"
variant="destructive"
@click="removeTemplate(template.id)"
>
Delete
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
</AppLayout>
</template>
+207 -17
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { Form, Head, Link } from '@inertiajs/vue3';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { computed } from 'vue';
import ProjectController from '@/actions/App/Http/Controllers/ProjectController';
import Heading from '@/components/Heading.vue';
import InputError from '@/components/InputError.vue';
@@ -15,7 +16,9 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/AppLayout.vue';
import { create, index } from '@/routes/projects/index';
import type { BreadcrumbItem } from '@/types';
import type { BreadcrumbItem, ProjectsCreatePageProps } from '@/types';
const props = defineProps<ProjectsCreatePageProps>();
const breadcrumbs: BreadcrumbItem[] = [
{
@@ -27,6 +30,43 @@ const breadcrumbs: BreadcrumbItem[] = [
href: create(),
},
];
const defaultTemplateId = props.selectedSourceTemplateId ?? props.sourceTemplates[0]?.id ?? null;
const form = useForm({
copy_areas: [] as string[],
creation_mode: defaultTemplateId !== null ? 'template' : 'scratch',
key: '',
name: '',
source_project_id: props.sourceProjects[0]?.id ? String(props.sourceProjects[0].id) : '',
source_template_id: defaultTemplateId !== null ? String(defaultTemplateId) : '',
});
const hasSourceProjects = computed(() => props.sourceProjects.length > 0);
const hasSourceTemplates = computed(() => props.sourceTemplates.length > 0);
const copyAreasError = computed(() => {
return (
form.errors.copy_areas ??
Object.entries(form.errors).find(([key]) => key.startsWith('copy_areas.'))?.[1] ??
''
);
});
const submit = (): void => {
if (form.creation_mode !== 'duplicate') {
form.source_project_id = '';
form.copy_areas = [];
}
if (form.creation_mode !== 'template') {
form.source_template_id = '';
}
form.post(ProjectController.store(), {
preserveScroll: true,
});
};
</script>
<template>
@@ -36,7 +76,7 @@ const breadcrumbs: BreadcrumbItem[] = [
<div class="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-6 p-4">
<Heading
title="Create project"
description="Create a project with a stable uppercase key that will prefix all future ticket keys."
description="Create a fresh project, duplicate selected settings from an existing project, or start from a saved template."
/>
<Card>
@@ -49,28 +89,82 @@ const breadcrumbs: BreadcrumbItem[] = [
</CardHeader>
<CardContent>
<Form
v-bind="ProjectController.store.form()"
class="space-y-6"
v-slot="{ errors, processing }"
>
<form class="space-y-6" @submit.prevent="submit">
<div class="grid gap-3">
<Label>How do you want to start?</Label>
<div class="grid gap-3 sm:grid-cols-3">
<Label class="flex cursor-pointer items-start gap-3 rounded-xl border p-4">
<input
v-model="form.creation_mode"
type="radio"
value="scratch"
class="mt-1"
/>
<div class="space-y-1">
<div class="font-medium">Create from scratch</div>
<p class="text-muted-foreground text-sm">
Start with the default project setup.
</p>
</div>
</Label>
<Label
class="flex items-start gap-3 rounded-xl border p-4"
:class="hasSourceProjects ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'"
>
<input
v-model="form.creation_mode"
type="radio"
value="duplicate"
class="mt-1"
:disabled="!hasSourceProjects"
/>
<div class="space-y-1">
<div class="font-medium">Create from existing project</div>
<p class="text-muted-foreground text-sm">
Copy only the settings you explicitly select. Tickets are never duplicated.
</p>
</div>
</Label>
<Label
class="flex items-start gap-3 rounded-xl border p-4"
:class="hasSourceTemplates ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'"
>
<input
v-model="form.creation_mode"
type="radio"
value="template"
class="mt-1"
:disabled="!hasSourceTemplates"
/>
<div class="space-y-1">
<div class="font-medium">Create from template</div>
<p class="text-muted-foreground text-sm">
Reuse a saved configuration template.
</p>
</div>
</Label>
</div>
</div>
<div class="grid gap-2">
<Label for="name">Project name</Label>
<Input
id="name"
name="name"
v-model="form.name"
required
autofocus
placeholder="Kanban foundation"
/>
<InputError :message="errors.name" />
<InputError :message="form.errors.name" />
</div>
<div class="grid gap-2">
<Label for="key">Project key</Label>
<Input
id="key"
name="key"
v-model="form.key"
required
maxlength="5"
placeholder="CORE"
@@ -78,15 +172,111 @@ const breadcrumbs: BreadcrumbItem[] = [
/>
<p class="text-muted-foreground text-sm">
Example ticket keys will look like
<span class="text-foreground font-medium"
>CORE-1</span
>.
<span class="text-foreground font-medium">CORE-1</span>.
</p>
<InputError :message="errors.key" />
<InputError :message="form.errors.key" />
</div>
<div
v-if="form.creation_mode === 'duplicate'"
class="space-y-6 rounded-xl border border-dashed p-4"
>
<div class="grid gap-2">
<Label for="source_project_id">Source project</Label>
<select
id="source_project_id"
v-model="form.source_project_id"
class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="!hasSourceProjects"
>
<option value="">Select a source project</option>
<option
v-for="sourceProject in sourceProjects"
:key="sourceProject.id"
:value="String(sourceProject.id)"
>
{{ sourceProject.name }} ({{ sourceProject.key }})
</option>
</select>
<p class="text-muted-foreground text-sm">
The new project keeps its own identity, key, and future ticket numbering.
</p>
<InputError :message="form.errors.source_project_id" />
</div>
<div class="grid gap-3">
<div>
<Label>Copy options</Label>
<p class="text-muted-foreground text-sm">
Choose which settings should be copied into the new project.
</p>
</div>
<div class="grid gap-3">
<Label
v-for="copyAreaOption in copyAreaOptions"
:key="copyAreaOption.value"
class="flex cursor-pointer items-start gap-3 rounded-xl border p-4"
>
<input
v-model="form.copy_areas"
type="checkbox"
:value="copyAreaOption.value"
class="mt-1"
/>
<div class="space-y-1">
<div class="font-medium">{{ copyAreaOption.label }}</div>
<p class="text-muted-foreground text-sm">
{{ copyAreaOption.description }}
</p>
</div>
</Label>
</div>
<p class="text-muted-foreground text-sm">
Operational ticket data is always left behind so the new project starts clean.
</p>
<InputError :message="copyAreasError" />
</div>
</div>
<div
v-else-if="form.creation_mode === 'template'"
class="space-y-4 rounded-xl border border-dashed p-4"
>
<div class="grid gap-2">
<Label for="source_template_id">Template</Label>
<select
id="source_template_id"
v-model="form.source_template_id"
class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
:disabled="!hasSourceTemplates"
>
<option value="">Select a template</option>
<option
v-for="sourceTemplate in sourceTemplates"
:key="sourceTemplate.id"
:value="String(sourceTemplate.id)"
>
{{ sourceTemplate.name }} ({{ sourceTemplate.slug }})
</option>
</select>
<p class="text-muted-foreground text-sm">
Templates apply their saved configuration groups to the new project.
</p>
<InputError :message="form.errors.source_template_id" />
</div>
</div>
<div
v-else-if="!hasSourceProjects && !hasSourceTemplates"
class="text-muted-foreground text-sm"
>
No accessible source projects or saved templates are available yet.
</div>
<div class="flex items-center gap-3">
<Button type="submit" :disabled="processing">
<Button type="submit" :disabled="form.processing">
Create project
</Button>
@@ -94,7 +284,7 @@ const breadcrumbs: BreadcrumbItem[] = [
<Link :href="index()">Cancel</Link>
</Button>
</div>
</Form>
</form>
</CardContent>
</Card>
</div>
+36
View File
@@ -94,12 +94,48 @@ const projectAreas = [
</Link>
</Button>
<Button
v-if="$page.props.auth.permissions.projectCreate"
as-child
variant="outline"
>
<Link :href="`/projects/${project.id}/templates/create`">
Save as new template
</Link>
</Button>
<Button as-child variant="outline">
<Link :href="index()">Back to projects</Link>
</Button>
</div>
</div>
<Card v-if="templateState?.inheritsFromTemplate">
<CardHeader>
<CardTitle>
Built from template {{ templateState.templateName }}
</CardTitle>
<CardDescription>
This project keeps its template link. Inherited areas follow the template baseline; overridden areas were customized locally.
</CardDescription>
</CardHeader>
<CardContent class="flex flex-wrap gap-2">
<Badge
v-for="area in templateState.inheritedAreas"
:key="`inherited-${area.value}`"
variant="outline"
>
{{ area.label }} · inherited
</Badge>
<Badge
v-for="area in templateState.overriddenAreas"
:key="`overridden-${area.value}`"
>
{{ area.label }} · overridden
</Badge>
</CardContent>
</Card>
<div v-if="canManageAccess" class="flex flex-wrap gap-3">
<Button as-child>
<Link :href="boardSettings(project.id)">
@@ -138,6 +138,32 @@ const statusAllowsTarget = (
{{ status }}
</div>
<Card v-if="templateState?.inheritsFromTemplate">
<CardHeader>
<CardTitle>
Template inheritance: {{ templateState.templateName }}
</CardTitle>
<CardDescription>
This project stays linked to its template. Sections below show whether the current configuration is still inherited or has local overrides.
</CardDescription>
</CardHeader>
<CardContent class="flex flex-wrap gap-2">
<Badge
v-for="area in templateState.inheritedAreas"
:key="`inherited-${area.value}`"
variant="outline"
>
{{ area.label }} · inherited
</Badge>
<Badge
v-for="area in templateState.overriddenAreas"
:key="`overridden-${area.value}`"
>
{{ area.label }} · overridden
</Badge>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Workflow model</CardTitle>
@@ -115,6 +115,32 @@ const replacementTicketTypes = (ticketTypeId: number) =>
{{ status }}
</div>
<Card v-if="templateState?.inheritsFromTemplate">
<CardHeader>
<CardTitle>
Template inheritance: {{ templateState.templateName }}
</CardTitle>
<CardDescription>
Inherited sections stay synced with the template baseline. Local edits in these settings are treated as project-specific overrides.
</CardDescription>
</CardHeader>
<CardContent class="flex flex-wrap gap-2">
<Badge
v-for="area in templateState.inheritedAreas"
:key="`inherited-${area.value}`"
variant="outline"
>
{{ area.label }} · inherited
</Badge>
<Badge
v-for="area in templateState.overriddenAreas"
:key="`overridden-${area.value}`"
>
{{ area.label }} · overridden
</Badge>
</CardContent>
</Card>
<div class="grid gap-6 xl:grid-cols-2">
<Card class="gap-0 overflow-hidden">
<CardHeader class="border-b">
@@ -305,6 +305,32 @@ const notificationActionTimestamp = (
{{ status }}
</div>
<Card v-if="templateState?.inheritsFromTemplate">
<CardHeader>
<CardTitle>
Template inheritance: {{ templateState.templateName }}
</CardTitle>
<CardDescription>
Notification rules can remain inherited from the template or diverge here as project-level overrides.
</CardDescription>
</CardHeader>
<CardContent class="flex flex-wrap gap-2">
<Badge
v-for="area in templateState.inheritedAreas"
:key="`inherited-${area.value}`"
variant="outline"
>
{{ area.label }} · inherited
</Badge>
<Badge
v-for="area in templateState.overriddenAreas"
:key="`overridden-${area.value}`"
>
{{ area.label }} · overridden
</Badge>
</CardContent>
</Card>
<div class="grid gap-6 xl:grid-cols-[24rem_minmax(0,1fr)]">
<div class="space-y-6">
<Card>
@@ -277,6 +277,32 @@ const submitUpdate = (): void => {
{{ status }}
</div>
<Card v-if="templateState?.inheritsFromTemplate">
<CardHeader>
<CardTitle>
Template inheritance: {{ templateState.templateName }}
</CardTitle>
<CardDescription>
Repository links can stay inherited from the template or be replaced with project-specific overrides.
</CardDescription>
</CardHeader>
<CardContent class="flex flex-wrap gap-2">
<Badge
v-for="area in templateState.inheritedAreas"
:key="`inherited-${area.value}`"
variant="outline"
>
{{ area.label }} · inherited
</Badge>
<Badge
v-for="area in templateState.overriddenAreas"
:key="`overridden-${area.value}`"
>
{{ area.label }} · overridden
</Badge>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Personal Git access</CardTitle>
@@ -0,0 +1,14 @@
import type { ProjectModel } from '@/types/models/project-model';
export type ProjectTemplateModel = {
id: number;
is_published: boolean;
project_id: number | null;
source_project_id: number | null;
source_project: ProjectModel | null;
name: string;
slug: string;
copy_areas: string[];
created_at: string | null;
updated_at: string | null;
};
+44
View File
@@ -4,6 +4,7 @@ import type { NotificationActionModel } from '@/types/models/notification-action
import type { NotificationActionOptionModel } from '@/types/models/notification-action-option-model';
import type { NotificationActionTemplateVariableModel } from '@/types/models/notification-action-template-variable-model';
import type { ProjectModel } from '@/types/models/project-model';
import type { ProjectTemplateModel } from '@/types/models/project-template-model';
import type { RepositoryConnectionModel } from '@/types/models/repository-connection-model';
import type { TeamModel } from '@/types/models/team-model';
import type { TicketFieldDefinitionModel } from '@/types/models/ticket-field-definition-model';
@@ -32,14 +33,53 @@ export type AdminUserEditPageProps = {
user: UserModel;
};
export type ProjectDuplicateCopyAreaOption = {
description: string;
label: string;
value: string;
};
export type ProjectsIndexPageProps = {
projects: ProjectModel[];
status?: string | null;
};
export type ProjectsCreatePageProps = {
copyAreaOptions: ProjectDuplicateCopyAreaOption[];
selectedSourceTemplateId?: number | null;
sourceProjects: ProjectModel[];
sourceTemplates: ProjectTemplateModel[];
};
export type ProjectTemplatesIndexPageProps = {
status?: string | null;
templates: ProjectTemplateModel[];
};
export type ProjectTemplatesCreatePageProps = {
copyAreaOptions: ProjectDuplicateCopyAreaOption[];
project: ProjectModel;
};
export type ProjectTemplateStateArea = {
label: string;
value: string;
};
export type ProjectTemplateState = {
effectiveConfiguration: Record<string, unknown>;
inheritedAreas: ProjectTemplateStateArea[];
inheritsFromTemplate: boolean;
overriddenAreas: ProjectTemplateStateArea[];
templateId: number;
templateName: string;
templateSlug: string;
};
export type ProjectShowPageProps = {
canManageAccess: boolean;
project: ProjectModel;
templateState?: ProjectTemplateState | null;
};
export type PermissionOption = {
@@ -71,6 +111,7 @@ export type ProjectBoardSettingsPageProps = {
boardColumns: BoardColumnModel[];
project: ProjectModel;
status?: string | null;
templateState?: ProjectTemplateState | null;
ticketStatuses: TicketStatusModel[];
};
@@ -97,6 +138,7 @@ export type ProjectTicketMetadataSettingsPageProps = {
project: ProjectModel;
error?: boolean;
status?: string | null;
templateState?: ProjectTemplateState | null;
ticketFieldDefinitions: TicketFieldDefinitionModel[];
ticketLinkTypes: TicketLinkTypeModel[];
ticketPriorities: TicketPriorityModel[];
@@ -108,6 +150,7 @@ export type ProjectRepositorySettingsPageProps = {
project: ProjectModel;
repositoryConnections: RepositoryConnectionModel[];
status?: string | null;
templateState?: ProjectTemplateState | null;
};
export type ProjectNotificationSettingsPageProps = {
@@ -119,6 +162,7 @@ export type ProjectNotificationSettingsPageProps = {
notificationActions: NotificationActionModel[];
project: ProjectModel;
status?: string | null;
templateState?: ProjectTemplateState | null;
templateVariables: NotificationActionTemplateVariableModel[];
};
+1
View File
@@ -20,6 +20,7 @@ Route::middleware(['auth', 'verified'])->group(function () {
Route::inertia('dashboard', 'Dashboard')->name('dashboard');
require __DIR__.'/web/admin.php';
require __DIR__.'/web/project-templates.php';
require __DIR__.'/web/projects.php';
require __DIR__.'/web/teams.php';
});
+12
View File
@@ -0,0 +1,12 @@
<?php
use App\Http\Controllers\ProjectTemplateController;
use Illuminate\Support\Facades\Route;
Route::middleware('can:create-project')
->prefix('project-templates')
->name('project-templates.')
->group(function (): void {
Route::get('/', [ProjectTemplateController::class, 'index'])->name('index');
Route::delete('{projectTemplate}', [ProjectTemplateController::class, 'destroy'])->name('destroy');
});
+6
View File
@@ -2,6 +2,7 @@
use App\Http\Controllers\ProjectBoardController;
use App\Http\Controllers\ProjectController;
use App\Http\Controllers\ProjectTemplateController;
use Illuminate\Support\Facades\Route;
Route::prefix('projects')->name('projects.')->group(function (): void {
@@ -18,6 +19,11 @@ Route::prefix('projects')->name('projects.')->group(function (): void {
Route::get('/', [ProjectController::class, 'show'])->name('show');
Route::get('board', [ProjectBoardController::class, 'index'])->name('board.index');
Route::get('backlog', [ProjectController::class, 'backlog'])->name('backlog.index');
Route::middleware('can:create-project')->group(function (): void {
Route::get('templates/create', [ProjectTemplateController::class, 'create'])->name('templates.create');
Route::post('templates', [ProjectTemplateController::class, 'store'])->name('templates.store');
});
});
Route::delete('/', [ProjectController::class, 'destroy'])
+207
View File
@@ -3,7 +3,12 @@
namespace Tests\Feature\Api;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\BoardColumn;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\TicketStatus;
use App\Models\TicketType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
@@ -38,6 +43,7 @@ class ProjectApiTest extends TestCase
$this->withApplicationKey($user)
->postJson(route('api.projects.store'), [
'creation_mode' => 'scratch',
'key' => 'api',
'name' => 'API Project',
])
@@ -47,8 +53,209 @@ class ProjectApiTest extends TestCase
->assertJsonPath('meta.message', 'API Project was created.');
$project = Project::query()->where('key', 'API')->firstOrFail();
$project->refresh();
$this->assertSame(2, $project->ticketTypes()->count());
$this->assertSame(1, $project->ticketStatuses()->count());
$this->assertNotNull($project->project_template_id);
}
public function test_users_can_create_projects_from_templates_via_api(): void
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['create']);
$template = ProjectTemplate::factory()->create([
'name' => 'API Template',
'slug' => 'api-template',
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
],
'configuration_snapshot' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS => [
'show_author' => false,
'show_story_points' => false,
],
DuplicateProjectConfiguration::COPY_TICKET_TYPES => [
[
'name' => 'Spike',
'position' => 1,
'is_parent' => false,
],
],
],
]);
$this->withApplicationKey($user)
->postJson(route('api.projects.store'), [
'key' => 'tpl1',
'name' => 'Template API Project',
'creation_mode' => 'template',
'source_template_id' => $template->id,
])
->assertCreated()
->assertJsonPath('data.key', 'TPL1')
->assertJsonPath('data.name', 'Template API Project');
$project = Project::query()->where('key', 'TPL1')->firstOrFail();
$project->refresh();
$this->assertSame($template->id, $project->project_template_id);
$this->assertFalse($project->show_author);
$this->assertFalse($project->show_story_points);
$this->assertSame(['Spike'], $project->ticketTypes()->pluck('name')->all());
}
public function test_project_api_exposes_template_context_and_overrides(): void
{
$user = User::factory()->create();
$project = Project::factory()->create([
'key' => 'TMP1',
'name' => 'Template Driven Project',
'show_author' => false,
'show_story_points' => false,
]);
$template = ProjectTemplate::factory()->create([
'name' => 'Workflow Template',
'slug' => 'workflow-template',
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
],
'configuration_snapshot' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS => [
'show_author' => true,
'show_story_points' => true,
],
DuplicateProjectConfiguration::COPY_TICKET_TYPES => [
[
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
],
[
'name' => 'Feature',
'position' => 2,
'is_parent' => false,
],
],
],
]);
$project->update([
'project_template_id' => $template->id,
]);
$project->ticketTypes()->delete();
TicketType::factory()->create([
'project_id' => $project->id,
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
]);
TicketType::factory()->create([
'project_id' => $project->id,
'name' => 'Feature',
'position' => 2,
'is_parent' => false,
]);
$this->syncProjectPermissions($project, $user, ['view']);
$this->withApplicationKey($user)
->getJson(route('api.projects.show', $project))
->assertOk()
->assertJsonPath('data.project_template.id', $template->id)
->assertJsonPath('data.project_template.slug', 'workflow-template')
->assertJsonPath('data.project_template.configuration_snapshot.project_settings.show_author', true)
->assertJsonPath('data.template_state.inherits_from_template', true)
->assertJsonPath('data.template_state.template_id', $template->id)
->assertJsonPath('data.template_state.template_configuration.project_settings.show_author', true)
->assertJsonPath('data.template_state.effective_configuration.ticket_types.0.name', 'Bug')
->assertJsonPath('data.template_state.inherited_configuration.ticket_types.1.name', 'Feature')
->assertJsonPath('data.template_state.overridden_configuration.project_settings.show_author', false)
->assertJsonPath('data.template_state.overridden_areas.0.value', DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS);
}
public function test_users_can_duplicate_projects_via_api(): void
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['create']);
$sourceProject = Project::factory()->create([
'key' => 'SRC1',
'show_author' => false,
]);
$this->syncProjectPermissions($sourceProject, $user, ['view']);
$sourceProject->ticketTypes()->delete();
$sourceProject->ticketStatuses()->delete();
$sourceProject->boardColumns()->delete();
$column = BoardColumn::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'In Progress',
'position' => 1,
]);
$backlogStatus = TicketStatus::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Queued',
'position' => 1,
]);
$activeStatus = TicketStatus::factory()->create([
'project_id' => $sourceProject->id,
'board_column_id' => $column->id,
'name' => 'Active',
'position' => 1,
]);
$backlogStatus->allowedTargetStatuses()->sync([$activeStatus->id]);
TicketType::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Spike',
'position' => 1,
]);
$this->withApplicationKey($user)
->postJson(route('api.projects.store'), [
'key' => 'dup2',
'name' => 'Duplicated API Project',
'creation_mode' => 'duplicate',
'source_project_id' => $sourceProject->id,
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_BOARD_WORKFLOW,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
],
])
->assertCreated()
->assertJsonPath('data.key', 'DUP2')
->assertJsonPath('data.name', 'Duplicated API Project');
$project = Project::query()->where('key', 'DUP2')->firstOrFail();
$this->assertFalse($project->show_author);
$this->assertSame(['In Progress'], $project->boardColumns()->pluck('name')->all());
$this->assertSame(['Queued', 'Active'], $project->ticketStatuses()->pluck('name')->all());
$this->assertSame(['Spike'], $project->ticketTypes()->pluck('name')->all());
$this->assertSame(['Active'], $project->ticketStatuses()->where('name', 'Queued')->firstOrFail()->allowedTargetStatuses()->pluck('name')->all());
}
public function test_project_duplication_via_api_requires_visible_source_project(): void
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['create']);
$sourceProject = Project::factory()->create();
$this->withApplicationKey($user)
->postJson(route('api.projects.store'), [
'key' => 'nope',
'name' => 'No Access',
'creation_mode' => 'duplicate',
'source_project_id' => $sourceProject->id,
])
->assertStatus(422)
->assertJsonValidationErrors(['source_project_id']);
}
public function test_project_show_and_delete_enforce_permissions(): void
@@ -0,0 +1,73 @@
<?php
namespace Tests\Feature\Database;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class ProjectTemplateBaselineMigrationTest extends TestCase
{
public function test_migration_backfills_hidden_base_templates_for_existing_projects(): void
{
Artisan::call('migrate:fresh', [
'--path' => [
'database/migrations/0001_01_01_000000_create_users_table.php',
'database/migrations/0001_01_01_000001_create_cache_table.php',
'database/migrations/0001_01_01_000002_create_jobs_table.php',
'database/migrations/2025_08_14_170933_add_two_factor_columns_to_users_table.php',
'database/migrations/2026_03_24_234007_create_projects_table.php',
'database/migrations/2026_03_24_234734_create_teams_table.php',
'database/migrations/2026_03_24_234735_create_team_user_table.php',
'database/migrations/2026_03_25_002100_create_board_columns_table.php',
'database/migrations/2026_03_25_003100_create_ticket_types_table.php',
'database/migrations/2026_03_25_003101_create_ticket_priorities_table.php',
'database/migrations/2026_03_25_003102_create_ticket_field_definitions_table.php',
'database/migrations/2026_03_25_004098_create_ticket_statuses_table.php',
'database/migrations/2026_03_25_004099_create_ticket_statuses_transitionstable.php',
'database/migrations/2026_03_25_004100_create_tickets_table.php',
'database/migrations/2026_03_25_065302_create_ticket_worklog_entries_table.php',
'database/migrations/2026_03_25_070706_create_ticket_field_values_table.php',
'database/migrations/2026_03_25_073715_create_ticket_links_table.php',
'database/migrations/2026_03_25_073715_create_ticket_link_types_table.php',
'database/migrations/2026_03_26_074522_create_user_git_connections_table.php',
'database/migrations/2026_03_26_075849_create_repository_connections_table.php',
'database/migrations/2026_04_12_120000_create_permission_assignments_table.php',
'database/migrations/2026_04_20_174556_create_user_applications_table.php',
'database/migrations/2026_04_20_194646_create_notification_actions_table.php',
'database/migrations/2026_04_20_194646_create_notification_delivery_logs_table.php',
'database/migrations/2026_04_24_194800_add_filters_to_notification_actions_table.php',
'database/migrations/2026_04_24_203500_create_acceptance_criteria_table.php',
'database/migrations/2026_05_19_230500_drop_acceptance_criteria_from_tickets_table.php',
'database/migrations/2026_05_22_124700_add_must_change_password_on_next_login_to_users_table.php',
'database/migrations/2026_05_23_101900_add_counterpart_label_to_ticket_link_types_table.php',
'database/migrations/2026_05_25_011500_create_project_templates_table.php',
],
]);
DB::table('projects')->insert([
'name' => 'Legacy Project',
'key' => 'LGCY',
'show_author' => 0,
'show_story_points' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
$projectId = (int) DB::table('projects')->where('key', 'LGCY')->value('id');
Artisan::call('migrate', [
'--path' => 'database/migrations/2026_05_25_013000_project_templates_as_project_baselines.php',
]);
$project = DB::table('projects')->where('id', $projectId)->first();
$template = DB::table('project_templates')->where('id', $project->project_template_id)->first();
$this->assertNotNull($project->project_template_id);
$this->assertNotNull($template);
$this->assertSame($projectId, $template->project_id);
$this->assertSame($projectId, $template->source_project_id);
$this->assertSame(0, $template->is_published);
$this->assertSame('lgcy-base-template', $template->slug);
}
}
+63
View File
@@ -4,6 +4,7 @@ namespace Tests\Feature\Mcp;
use App\Actions\Notifications\DeliverNotificationAction;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Enums\NotificationDeliveryStatus;
use App\Mcp\Servers\KanbanGitServer;
use App\Mcp\Tools\GetTicket;
@@ -15,8 +16,10 @@ use App\Mcp\Tools\UpdateTicketDescription;
use App\Models\BoardColumn;
use App\Models\NotificationAction;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\Ticket;
use App\Models\TicketStatus;
use App\Models\TicketType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
@@ -207,6 +210,66 @@ class KanbanGitMcpTest extends TestCase
->etc());
}
public function test_get_ticket_exposes_project_template_context_and_overrides(): void
{
$user = User::factory()->create();
$project = $this->project('CORE', 'Core project');
$template = ProjectTemplate::factory()->create([
'name' => 'Agent Workflow Template',
'slug' => 'agent-workflow-template',
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
],
'configuration_snapshot' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS => [
'show_author' => true,
'show_story_points' => true,
],
DuplicateProjectConfiguration::COPY_TICKET_TYPES => [
[
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
],
],
],
]);
$project->update([
'project_template_id' => $template->id,
'show_author' => false,
'show_story_points' => false,
]);
$project->ticketTypes()->delete();
TicketType::factory()->create([
'project_id' => $project->id,
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
]);
$status = $project->ticketStatuses()->firstOrFail();
$ticket = $this->ticket($project, $status, [
'ticket_key' => 'CORE-1',
'title' => 'Template aware ticket',
]);
$this->syncProjectPermissions($project, $user, ['view']);
KanbanGitServer::actingAs($user)
->tool(GetTicket::class, [
'ticket_id' => $ticket->id,
])
->assertOk()
->assertStructuredContent(fn (AssertableJson $json) => $json
->where('data.project.project_template.id', $template->id)
->where('data.project.project_template.slug', 'agent-workflow-template')
->where('data.project.template_state.inherits_from_template', true)
->where('data.project.template_state.template_configuration.project_settings.show_author', true)
->where('data.project.template_state.overridden_configuration.project_settings.show_author', false)
->where('data.project.template_state.effective_configuration.ticket_types.0.name', 'Bug')
->etc());
}
public function test_description_update_requires_write_permission_and_preserves_unrelated_fields(): void
{
$user = User::factory()->create();
@@ -3,8 +3,10 @@
namespace Tests\Feature\Projects;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\BoardColumn;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\Ticket;
use App\Models\TicketStatus;
use App\Models\User;
@@ -31,6 +33,15 @@ class ProjectBoardSettingsControllerTest extends TestCase
'position' => 1,
]);
$template = ProjectTemplate::factory()->create([
'configuration_snapshot' => app(DuplicateProjectConfiguration::class)->export($project, [
DuplicateProjectConfiguration::COPY_BOARD_WORKFLOW,
]),
'copy_areas' => [DuplicateProjectConfiguration::COPY_BOARD_WORKFLOW],
'name' => 'Starter Workflow',
]);
$project->update(['project_template_id' => $template->id]);
$this->syncProjectPermissions($project, $user, ['edit']);
$this->actingAs($user)
@@ -41,7 +52,9 @@ class ProjectBoardSettingsControllerTest extends TestCase
->where('project.id', $project->id)
->where('backlogTicketStatuses.0.name', 'Backlog')
->where('boardColumns.0.name', 'Todo')
->where('ticketStatuses.0.name', 'Backlog'),
->where('ticketStatuses.0.name', 'Backlog')
->where('templateState.templateName', 'Starter Workflow')
->where('templateState.inheritedAreas.0.value', DuplicateProjectConfiguration::COPY_BOARD_WORKFLOW),
);
}
@@ -3,11 +3,19 @@
namespace Tests\Feature\Projects;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\BoardColumn;
use App\Models\NotificationAction;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\RepositoryConnection;
use App\Models\Team;
use App\Models\Ticket;
use App\Models\TicketFieldDefinition;
use App\Models\TicketLinkType;
use App\Models\TicketPriority;
use App\Models\TicketStatus;
use App\Models\TicketType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Inertia\Testing\AssertableInertia as Assert;
@@ -100,12 +108,40 @@ class ProjectControllerTest extends TestCase
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['project:create']);
$visibleProject = Project::factory()->create([
'name' => 'Visible Source',
'key' => 'SRC1',
]);
Project::factory()->create([
'name' => 'Hidden Source',
'key' => 'SRC2',
]);
$template = ProjectTemplate::factory()->create([
'name' => 'Reusable Setup',
'slug' => 'reusable-setup',
'source_project_id' => $visibleProject->id,
]);
ProjectTemplate::factory()->create([
'name' => 'Hidden Base',
'slug' => 'hidden-base',
'project_id' => $visibleProject->id,
'source_project_id' => $visibleProject->id,
'is_published' => false,
]);
$this->syncProjectPermissions($visibleProject, $user, ['view']);
$this->actingAs($user)
->get(route('projects.create'))
->get(route('projects.create', ['template' => $template->id]))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('projects/Create'),
->component('projects/Create')
->has('copyAreaOptions', count(DuplicateProjectConfiguration::copyableAreas()))
->has('sourceProjects', 1)
->has('sourceTemplates', 1)
->where('sourceProjects.0.id', $visibleProject->id)
->where('sourceTemplates.0.id', $template->id)
->where('selectedSourceTemplateId', $template->id)
->where('copyAreaOptions.0.value', DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS),
);
}
@@ -131,6 +167,7 @@ class ProjectControllerTest extends TestCase
$response = $this->actingAs($user)
->post(route('projects.store'), [
'creation_mode' => 'scratch',
'name' => 'Kanban Foundation',
'key' => 'core',
]);
@@ -144,6 +181,18 @@ class ProjectControllerTest extends TestCase
'key' => 'CORE',
]);
$project->refresh();
$this->assertNotNull($project->project_template_id);
$this->assertDatabaseHas('project_templates', [
'id' => $project->project_template_id,
'project_id' => $project->id,
'source_project_id' => $project->id,
'is_published' => false,
'slug' => 'core-base-template',
]);
$this->assertDatabaseHas('permission_assignments', [
'assignee_id' => $user->id,
'assignee_type' => $user->getMorphClass(),
@@ -187,6 +236,215 @@ class ProjectControllerTest extends TestCase
->assertRedirect(route('projects.create'));
}
public function test_authenticated_users_can_create_projects_from_saved_templates(): void
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['project:create']);
$sourceProject = Project::factory()->create([
'key' => 'SRC1',
'name' => 'Source Project',
'show_author' => false,
'show_story_points' => false,
]);
$template = ProjectTemplate::factory()->create([
'source_project_id' => $sourceProject->id,
'name' => 'Kanban Template',
'slug' => 'kanban-template',
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
],
'configuration_snapshot' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS => [
'show_author' => false,
'show_story_points' => false,
],
DuplicateProjectConfiguration::COPY_TICKET_TYPES => [
[
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
],
],
],
]);
$response = $this->actingAs($user)
->post(route('projects.store'), [
'creation_mode' => 'template',
'name' => 'Template Based Project',
'key' => 'TMP1',
'source_template_id' => $template->id,
]);
$project = Project::query()->where('key', 'TMP1')->firstOrFail();
$response->assertRedirect(route('projects.show', $project));
$project->refresh();
$this->assertSame($template->id, $project->project_template_id);
$this->assertSame(false, $project->show_author);
$this->assertSame(false, $project->show_story_points);
$this->assertDatabaseHas('ticket_types', [
'project_id' => $project->id,
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
]);
$this->assertDatabaseMissing('tickets', [
'project_id' => $project->id,
]);
}
public function test_authenticated_users_can_duplicate_projects_with_selected_settings_only(): void
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['project:create']);
$sourceProject = Project::factory()->create([
'key' => 'SRC1',
'name' => 'Source Project',
'show_author' => false,
'show_story_points' => false,
]);
$this->syncProjectPermissions($sourceProject, $user, ['view']);
$sourceProject->ticketTypes()->delete();
$sourceProject->ticketPriorities()->delete();
$sourceProject->ticketStatuses()->delete();
$sourceProject->boardColumns()->delete();
$todoColumn = BoardColumn::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Todo',
'position' => 1,
]);
$doingColumn = BoardColumn::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Doing',
'position' => 2,
]);
$backlogStatus = TicketStatus::factory()->create([
'project_id' => $sourceProject->id,
'board_column_id' => null,
'name' => 'Planned',
'position' => 1,
]);
$todoStatus = TicketStatus::factory()->create([
'project_id' => $sourceProject->id,
'board_column_id' => $todoColumn->id,
'name' => 'Todo',
'position' => 1,
]);
$doingStatus = TicketStatus::factory()->create([
'project_id' => $sourceProject->id,
'board_column_id' => $doingColumn->id,
'name' => 'Doing',
'position' => 1,
]);
$todoStatus->allowedTargetStatuses()->sync([$doingStatus->id]);
$backlogStatus->allowedTargetStatuses()->sync([$todoStatus->id]);
TicketType::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Bug',
'position' => 1,
]);
TicketType::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Epic',
'position' => 2,
'is_parent' => true,
]);
TicketPriority::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Urgent',
'position' => 1,
]);
TicketFieldDefinition::factory()->create([
'project_id' => $sourceProject->id,
'field_type' => 'number',
'label' => 'Story estimate',
'position' => 1,
]);
TicketLinkType::factory()->create([
'project_id' => $sourceProject->id,
'label' => 'Blocks',
'counterpart_label' => 'Blocked by',
'position' => 1,
]);
RepositoryConnection::factory()->create([
'project_id' => $sourceProject->id,
'repository_full_name' => 'OpenSource/source-project',
]);
NotificationAction::factory()->create([
'project_id' => $sourceProject->id,
'name' => 'Notify board changes',
]);
Ticket::factory()->create([
'project_id' => $sourceProject->id,
'sequence_number' => 42,
'title' => 'Existing ticket',
]);
$response = $this->actingAs($user)
->post(route('projects.store'), [
'name' => 'Duplicated Project',
'key' => 'dupe',
'creation_mode' => 'duplicate',
'source_project_id' => $sourceProject->id,
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_BOARD_WORKFLOW,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
DuplicateProjectConfiguration::COPY_TICKET_FIELDS,
],
]);
$project = Project::query()->where('key', 'DUPE')->firstOrFail();
$response->assertRedirect(route('projects.show', $project));
$this->assertSame('Duplicated Project', $project->name);
$this->assertFalse($project->show_author);
$this->assertFalse($project->show_story_points);
$this->assertSame(0, $project->tickets()->count());
$this->assertSame(['Todo', 'Doing'], $project->boardColumns()->pluck('name')->all());
$this->assertSame(['Planned', 'Todo', 'Doing'], $project->ticketStatuses()->pluck('name')->all());
$this->assertSame(['Bug', 'Epic'], $project->ticketTypes()->pluck('name')->all());
$this->assertSame(['Story estimate'], $project->ticketFieldDefinitions()->pluck('label')->all());
$this->assertSame(['Medium'], $project->ticketPriorities()->pluck('name')->all());
$this->assertCount(0, $project->ticketLinkTypes);
$this->assertCount(0, $project->repositoryConnections);
$this->assertCount(0, $project->notificationActions);
$duplicatedTodoStatus = $project->ticketStatuses()->where('name', 'Todo')->firstOrFail();
$this->assertSame(['Doing'], $duplicatedTodoStatus->allowedTargetStatuses()->pluck('name')->all());
}
public function test_project_duplication_requires_accessible_source_projects(): void
{
$user = User::factory()->create();
$this->syncGlobalPermissions($user, ['project:create']);
$sourceProject = Project::factory()->create();
$this->actingAs($user)
->from(route('projects.create'))
->post(route('projects.store'), [
'name' => 'Denied Duplicate',
'key' => 'deny',
'creation_mode' => 'duplicate',
'source_project_id' => $sourceProject->id,
])
->assertSessionHasErrors('source_project_id')
->assertRedirect(route('projects.create'));
}
/**
* Ensure project keys cannot exceed five characters.
*/
@@ -2,10 +2,12 @@
namespace Tests\Feature\Projects;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Enums\NotificationChannel;
use App\Enums\NotificationEventType;
use App\Models\NotificationAction;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Inertia\Testing\AssertableInertia as Assert;
@@ -41,6 +43,15 @@ class ProjectNotificationSettingsControllerTest extends TestCase
],
]);
$template = ProjectTemplate::factory()->create([
'configuration_snapshot' => app(DuplicateProjectConfiguration::class)->export($project, [
DuplicateProjectConfiguration::COPY_NOTIFICATION_ACTIONS,
]),
'copy_areas' => [DuplicateProjectConfiguration::COPY_NOTIFICATION_ACTIONS],
'name' => 'Alert Template',
]);
$project->update(['project_template_id' => $template->id]);
$this->syncProjectPermissions($project, $user, ['edit']);
$this->actingAs($user)
@@ -72,6 +83,8 @@ class ProjectNotificationSettingsControllerTest extends TestCase
->where('templateVariables.6.value', '$actor_name')
->where('templateVariables.7.value', '$assignee_from')
->where('templateVariables.8.value', '$assignee_to')
->where('templateState.templateName', 'Alert Template')
->where('templateState.inheritedAreas.0.value', DuplicateProjectConfiguration::COPY_NOTIFICATION_ACTIONS)
->missing('notificationActions.0.delivery_url'),
);
}
@@ -3,7 +3,9 @@
namespace Tests\Feature\Projects;
use App\Actions\Git\GitProviderKey;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\RepositoryConnection;
use App\Models\User;
use App\Models\UserGitConnection;
@@ -36,6 +38,15 @@ class ProjectRepositorySettingsControllerTest extends TestCase
'repository_url' => 'https://git.example.test/core-team/kanbangit',
]);
$template = ProjectTemplate::factory()->create([
'configuration_snapshot' => app(DuplicateProjectConfiguration::class)->export($project, [
DuplicateProjectConfiguration::COPY_REPOSITORY_CONNECTIONS,
]),
'copy_areas' => [DuplicateProjectConfiguration::COPY_REPOSITORY_CONNECTIONS],
'name' => 'Connected Template',
]);
$project->update(['project_template_id' => $template->id]);
$this->syncProjectPermissions($project, $user, ['edit']);
$this->actingAs($user)
@@ -46,7 +57,9 @@ class ProjectRepositorySettingsControllerTest extends TestCase
->where('project.id', $project->id)
->where('repositoryConnections.0.repository_full_name', 'core-team/kanbangit')
->where('repositoryConnections.0.has_personal_access', false)
->where('availableRepositorySources', []),
->where('availableRepositorySources', [])
->where('templateState.templateName', 'Connected Template')
->where('templateState.inheritedAreas.0.value', DuplicateProjectConfiguration::COPY_REPOSITORY_CONNECTIONS),
);
}
@@ -0,0 +1,152 @@
<?php
namespace Tests\Feature\Projects;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\BoardColumn;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\TicketStatus;
use App\Models\TicketType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class ProjectTemplateControllerTest extends TestCase
{
use RefreshDatabase;
public function test_users_with_project_create_permission_can_view_templates_index_and_create_screen(): void
{
$user = User::factory()->create();
$project = Project::factory()->create([
'name' => 'Core Platform',
'key' => 'CORE',
]);
$template = ProjectTemplate::factory()->create([
'name' => 'Foundation Template',
'slug' => 'foundation-template',
'source_project_id' => $project->id,
]);
ProjectTemplate::factory()->create([
'name' => 'Hidden Base Template',
'slug' => 'hidden-base-template',
'project_id' => $project->id,
'source_project_id' => $project->id,
'is_published' => false,
]);
$this->syncGlobalPermissions($user, ['project:create']);
$this->syncProjectPermissions($project, $user, ['view']);
$this->actingAs($user)
->get('/project-templates')
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('project-templates/Index')
->has('templates', 1)
->where('templates.0.id', $template->id)
->where('templates.0.slug', 'foundation-template')
->where('templates.0.is_published', true));
$this->actingAs($user)
->get(route('projects.templates.create', $project))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('project-templates/Create')
->where('project.id', $project->id)
->has('copyAreaOptions', count(DuplicateProjectConfiguration::copyableAreas())));
}
public function test_users_can_save_and_delete_templates_from_projects(): void
{
$user = User::factory()->create();
$project = Project::factory()->create([
'name' => 'Source Project',
'key' => 'SRC1',
'show_author' => false,
'show_story_points' => false,
]);
$this->syncGlobalPermissions($user, ['project:create']);
$this->syncProjectPermissions($project, $user, ['view']);
$project->ticketTypes()->delete();
$project->ticketStatuses()->delete();
$project->boardColumns()->delete();
$boardColumn = BoardColumn::factory()->create([
'project_id' => $project->id,
'name' => 'Doing',
'position' => 1,
]);
$ticketStatus = TicketStatus::factory()->create([
'project_id' => $project->id,
'board_column_id' => $boardColumn->id,
'name' => 'Doing',
'position' => 1,
]);
$ticketStatus->allowedTargetStatuses()->sync([$ticketStatus->id]);
TicketType::factory()->create([
'project_id' => $project->id,
'name' => 'Bug',
'position' => 1,
]);
$this->actingAs($user)
->post(route('projects.templates.store', $project), [
'name' => 'Core Reusable',
'slug' => 'core-reusable',
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
],
])
->assertRedirect('/project-templates');
$template = ProjectTemplate::query()->where('slug', 'core-reusable')->firstOrFail();
$this->assertTrue($template->is_published);
$this->assertNull($template->project_id);
$this->assertSame([
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS => [
'show_author' => false,
'show_story_points' => false,
],
DuplicateProjectConfiguration::COPY_TICKET_TYPES => [
[
'name' => 'Bug',
'position' => 1,
'is_parent' => false,
],
],
], $template->configuration_snapshot);
$this->actingAs($user)
->delete(route('project-templates.destroy', $template))
->assertRedirect('/project-templates');
$this->assertDatabaseMissing('project_templates', [
'id' => $template->id,
]);
}
public function test_hidden_base_templates_cannot_be_deleted_from_the_management_flow(): void
{
$user = User::factory()->create();
$project = Project::factory()->create();
$template = ProjectTemplate::factory()->create([
'project_id' => $project->id,
'source_project_id' => $project->id,
'is_published' => false,
]);
$this->syncGlobalPermissions($user, ['project:create']);
$this->actingAs($user)
->delete(route('project-templates.destroy', $template))
->assertNotFound();
}
}
@@ -3,7 +3,9 @@
namespace Tests\Feature\Projects;
use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Actions\Projects\DuplicateProjectConfiguration;
use App\Models\Project;
use App\Models\ProjectTemplate;
use App\Models\Ticket;
use App\Models\TicketFieldDefinition;
use App\Models\TicketLinkType;
@@ -37,6 +39,24 @@ class ProjectTicketMetadataSettingsControllerTest extends TestCase
'position' => 1,
]);
$template = ProjectTemplate::factory()->create([
'configuration_snapshot' => app(DuplicateProjectConfiguration::class)->export($project, [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
DuplicateProjectConfiguration::COPY_TICKET_LINK_TYPES,
]),
'copy_areas' => [
DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS,
DuplicateProjectConfiguration::COPY_TICKET_TYPES,
DuplicateProjectConfiguration::COPY_TICKET_LINK_TYPES,
],
'name' => 'Issue Tracker Template',
]);
$project->update([
'project_template_id' => $template->id,
'show_story_points' => false,
]);
$this->syncProjectPermissions($project, $user, ['edit']);
$this->actingAs($user)
@@ -45,12 +65,14 @@ class ProjectTicketMetadataSettingsControllerTest extends TestCase
->assertInertia(fn (Assert $page) => $page
->component('projects/settings/Metadata')
->where('project.show_author', true)
->where('project.show_story_points', true)
->where('project.show_story_points', false)
->where('ticketTypes.0.name', 'Task')
->where('ticketTypes.1.name', 'Release')
->where('ticketTypes.1.is_parent', true)
->where('ticketTypes.2.name', 'Bug')
->where('ticketLinkTypes.0.label', 'Relates to'),
->where('ticketLinkTypes.0.label', 'Relates to')
->where('templateState.templateName', 'Issue Tracker Template')
->where('templateState.overriddenAreas.0.value', DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS),
);
}