KAN-4 Duplicate Project #86

Merged
Twyco merged 1 commits from koda/kan-4-duplicate-project into epic/kan-3 2026-06-04 19:21:12 +00:00
8 changed files with 740 additions and 24 deletions
+20 -5
View File
@@ -7,24 +7,39 @@ use App\Actions\ProjectTicketMetadata\InitializeProjectTicketMetadata;
use App\Enums\Permission;
use App\Models\Project;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class CreateProject
{
public function __construct(
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, 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;
if (($attributes['creation_mode'] ?? 'scratch') === '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'] ?? []),
);
}
return $project->fresh() ?? $project;
});
}
}
@@ -0,0 +1,250 @@
<?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
*/
public function handle(Project $sourceProject, Project $targetProject, array $copyAreas): void
{
$selectedAreas = array_values(array_intersect(self::copyableAreas(), array_unique($copyAreas)));
if ($selectedAreas === []) {
return;
}
$sourceProject->loadMissing([
'boardColumns',
'notificationActions',
'repositoryConnections',
'ticketFieldDefinitions',
'ticketLinkTypes',
'ticketPriorities',
'ticketStatuses.allowedTargetStatuses',
'ticketTypes',
]);
if (in_array(self::COPY_PROJECT_SETTINGS, $selectedAreas, true)) {
$targetProject->forceFill([
'show_author' => $sourceProject->show_author,
'show_story_points' => $sourceProject->show_story_points,
])->save();
}
if (in_array(self::COPY_BOARD_WORKFLOW, $selectedAreas, true)) {
$targetProject->ticketStatuses()->delete();
$targetProject->boardColumns()->delete();
$boardColumnIdMap = [];
foreach ($sourceProject->boardColumns as $boardColumn) {
$newBoardColumn = $targetProject->boardColumns()->create([
'name' => $boardColumn->name,
'position' => $boardColumn->position,
]);
$boardColumnIdMap[$boardColumn->id] = $newBoardColumn->id;
}
$ticketStatusIdMap = [];
foreach ($sourceProject->ticketStatuses as $ticketStatus) {
$newTicketStatus = $targetProject->ticketStatuses()->create([
'board_column_id' => $ticketStatus->board_column_id === null
? null
: ($boardColumnIdMap[$ticketStatus->board_column_id] ?? null),
'name' => $ticketStatus->name,
'position' => $ticketStatus->position,
]);
$ticketStatusIdMap[$ticketStatus->id] = $newTicketStatus->id;
}
foreach ($sourceProject->ticketStatuses as $ticketStatus) {
$newTicketStatusId = $ticketStatusIdMap[$ticketStatus->id] ?? null;
if ($newTicketStatusId === null) {
continue;
}
$targetProject->ticketStatuses()
->findOrFail($newTicketStatusId)
->allowedTargetStatuses()
->sync(
$ticketStatus->allowedTargetStatuses
->pluck('id')
->map(fn (int $statusId): ?int => $ticketStatusIdMap[$statusId] ?? null)
->filter()
->values()
->all(),
);
}
}
if (in_array(self::COPY_TICKET_TYPES, $selectedAreas, true)) {
$targetProject->ticketTypes()->delete();
foreach ($sourceProject->ticketTypes as $ticketType) {
$targetProject->ticketTypes()->create([
'name' => $ticketType->name,
'position' => $ticketType->position,
'is_parent' => $ticketType->is_parent,
]);
}
}
if (in_array(self::COPY_TICKET_PRIORITIES, $selectedAreas, true)) {
$targetProject->ticketPriorities()->delete();
foreach ($sourceProject->ticketPriorities as $ticketPriority) {
$targetProject->ticketPriorities()->create([
'name' => $ticketPriority->name,
'position' => $ticketPriority->position,
]);
}
}
if (in_array(self::COPY_TICKET_FIELDS, $selectedAreas, true)) {
$targetProject->ticketFieldDefinitions()->delete();
foreach ($sourceProject->ticketFieldDefinitions as $ticketFieldDefinition) {
$targetProject->ticketFieldDefinitions()->create([
'field_type' => $ticketFieldDefinition->field_type,
'label' => $ticketFieldDefinition->label,
'position' => $ticketFieldDefinition->position,
]);
}
}
if (in_array(self::COPY_TICKET_LINK_TYPES, $selectedAreas, true)) {
$targetProject->ticketLinkTypes()->delete();
foreach ($sourceProject->ticketLinkTypes as $ticketLinkType) {
$targetProject->ticketLinkTypes()->create([
'label' => $ticketLinkType->label,
'counterpart_label' => $ticketLinkType->counterpart_label,
'position' => $ticketLinkType->position,
]);
}
}
if (in_array(self::COPY_REPOSITORY_CONNECTIONS, $selectedAreas, true)) {
$targetProject->repositoryConnections()->delete();
foreach ($sourceProject->repositoryConnections 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 (in_array(self::COPY_NOTIFICATION_ACTIONS, $selectedAreas, true)) {
$targetProject->notificationActions()->delete();
foreach ($sourceProject->notificationActions 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,
'delivery_url' => $notificationAction->delivery_url,
'filters' => $notificationAction->filters,
]);
}
}
}
}
+7 -1
View File
@@ -6,6 +6,7 @@ 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\Enums\Permission;
use App\Http\Requests\DeleteProjectRequest;
@@ -51,7 +52,12 @@ class ProjectController extends Controller
403,
);
return Inertia::render('projects/Create');
return Inertia::render('projects/Create', [
'copyAreaOptions' => DuplicateProjectConfiguration::copyAreaOptions(),
'sourceProjects' => ProjectResource::collection(
$this->listVisibleProjects->handle($request->user()),
)->resolve(),
Review

Nur klein: vorher einmal user setzen mit $request->user ? und dann nur noch user nutzen anstatt zweimal auf $request->user zu nutzen?

Nur klein: vorher einmal user setzen mit $request->user ? und dann nur noch user nutzen anstatt zweimal auf $request->user zu nutzen?
Review

Nein, würde mehr zeilen/code hinzufügen als zu kürzen,
wär jetzt $request->xxx->yyy->zzz->user() oder so oder öfter als 2x wär das was anders, dann zwischenspeichern

Nein, würde mehr zeilen/code hinzufügen als zu kürzen, wär jetzt $request->xxx->yyy->zzz->user() oder so oder öfter als 2x wär das was anders, dann zwischenspeichern
]);
}
public function store(StoreProjectRequest $request): RedirectResponse
+52
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'])],
'key' => [
'required',
'string',
@@ -44,6 +58,44 @@ 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.');
}
},
],
'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.',
];
}
}
+149 -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,35 @@ const breadcrumbs: BreadcrumbItem[] = [
href: create(),
},
];
const form = useForm({
copy_areas: [] as string[],
creation_mode: 'scratch',
key: '',
name: '',
source_project_id: props.sourceProjects[0]?.id ? String(props.sourceProjects[0].id) : '',
});
const hasSourceProjects = computed(() => props.sourceProjects.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 = [];
}
form.post(ProjectController.store(), {
preserveScroll: true,
});
};
</script>
<template>
@@ -36,7 +68,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 or start from an existing project's settings without copying any tickets."
/>
<Card>
@@ -49,28 +81,63 @@ 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-2">
<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>
</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 +145,80 @@ 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="!hasSourceProjects" class="text-muted-foreground text-sm">
No accessible source projects are available for duplication 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 +226,7 @@ const breadcrumbs: BreadcrumbItem[] = [
<Link :href="index()">Cancel</Link>
</Button>
</div>
</Form>
</form>
</CardContent>
</Card>
</div>
+11
View File
@@ -32,11 +32,22 @@ 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[];
sourceProjects: ProjectModel[];
};
export type ProjectShowPageProps = {
canManageAccess: boolean;
project: ProjectModel;
+84
View File
@@ -3,7 +3,11 @@
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\TicketStatus;
use App\Models\TicketType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
@@ -51,6 +55,86 @@ class ProjectApiTest extends TestCase
$this->assertSame(1, $project->ticketStatuses()->count());
}
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
{
$user = User::factory()->create();
@@ -3,11 +3,18 @@
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\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 +107,25 @@ 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',
]);
$this->syncProjectPermissions($visibleProject, $user, ['view']);
$this->actingAs($user)
->get(route('projects.create'))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('projects/Create'),
->component('projects/Create')
->has('copyAreaOptions', count(DuplicateProjectConfiguration::copyableAreas()))
->has('sourceProjects', 1)
->where('sourceProjects.0.id', $visibleProject->id)
->where('copyAreaOptions.0.value', DuplicateProjectConfiguration::COPY_PROJECT_SETTINGS),
);
}
@@ -187,6 +207,152 @@ class ProjectControllerTest extends TestCase
->assertRedirect(route('projects.create'));
}
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.
*/