import { RouterLink } from '@angular/router';
import {
CdkDrag,
CdkDragDrop,
CdkDragHandle,
CdkDropList,
moveItemInArray,
} from '@angular/cdk/drag-drop';
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { PiCheckboxComponent, PiIconComponent, PiNoteComponent } from '@pi/ui';
import { GitIntegrationComponent } from '../ui/git-integration';
import { WebhooksComponent } from '../ui/webhooks';
import { TransferComponent } from '../ui/transfer';
import { AutomationsComponent } from '../ui/automations';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import {
CustomFieldType,
IssueTypeOption,
ProjectSettings,
SETTING_COLORS,
StatusCategory,
TYPE_ICONS,
} from '@task-stream/web/tracker/domain';
import { CATEGORY, COLOR_LABEL, ICON_LABEL, tone } from '../ui/copy';
type Section = 'statuses' | 'issueTypes' | 'areas' | 'customFields';
const FIELD_TYPES: { id: CustomFieldType; label: string }[] = [
{ id: CustomFieldType.TEXT, label: 'Texto' },
{ id: CustomFieldType.NUMBER, label: 'Número' },
{ id: CustomFieldType.DATE, label: 'Fecha' },
{ id: CustomFieldType.SELECT, label: 'Lista de opciones' },
];
const CATEGORIES = Object.values(StatusCategory);
/** "Datos y análisis" → "DATOS_Y_ANALISIS": ids of new values (they never change after saving). */
function idFrom(name: string): string {
const slug = name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.replace(/^[^A-Z]+/, '')
.slice(0, 30);
return slug || 'NUEVO';
}
/**
* "Configuración" (owners and admins): the project's statuses, how tickets
* move between them, ticket types and areas. Edits a local draft, saved in
* one go; values can be archived but not removed once saved.
*/
@Component({
selector: 'ts-settings-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
PiCheckboxComponent,
RouterLink,
GitIntegrationComponent,
WebhooksComponent,
TransferComponent,
AutomationsComponent,
CdkDropList,
CdkDrag,
CdkDragHandle,
NgTemplateOutlet,
PiIconComponent,
PiNoteComponent,
],
template: `
@if (!facade.canManage()) {
}
@if (facade.project(); as project) {
}
@if (draft(); as d) {
@if (facade.canManage() && facade.project(); as project) {
}
@if (facade.isOwner() && facade.project(); as project) {
}
}
@if (isNew(section, item.id)) {
} @else if (item.archived) {
Restaurar
} @else {
Archivar
}
`,
styles: `
:host {
display: grid;
gap: 1rem;
}
.ts-block.ts-visibility,
.ts-block.ts-danger {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1.5rem;
flex-wrap: wrap;
> div {
flex: 1 1 26rem;
}
p {
max-width: 46rem;
margin: 0.25rem 0 0;
font-size: 0.8125rem;
}
}
.ts-switch {
display: inline-flex;
align-items: center;
gap: 0.625rem;
font-size: 0.875rem;
font-weight: 600;
cursor: pointer;
input {
position: absolute;
opacity: 0;
width: 1px;
height: 1px;
}
input:focus-visible + .ts-switch__track {
outline: 2px solid var(--ts-brand);
outline-offset: 2px;
}
input:disabled ~ * {
opacity: 0.6;
cursor: default;
}
}
.ts-switch__track {
position: relative;
width: 2.5rem;
height: 1.375rem;
border-radius: 999px;
background: var(--ts-line-strong);
transition: background-color 0.15s ease;
&::after {
content: '';
position: absolute;
top: 3px;
left: 3px;
width: 1rem;
height: 1rem;
border-radius: 50%;
background: var(--ts-surface);
box-shadow: var(--ts-shadow);
transition: transform 0.15s ease;
}
}
.ts-switch input:checked + .ts-switch__track {
background: var(--ts-brand);
&::after {
transform: translateX(1.125rem);
}
}
.ts-danger {
border: 1px solid color-mix(in srgb, var(--ts-c-red) 45%, transparent);
h3 {
color: var(--ts-c-red);
}
}
.ts-danger__confirm {
display: flex;
align-items: flex-end;
gap: 0.75rem;
flex-wrap: wrap;
}
.ts-danger__label {
display: grid;
gap: 0.375rem;
font-size: 0.8125rem;
color: var(--ts-ink-soft);
code {
font-family: var(--ts-font-mono);
font-weight: 600;
}
.ts-input {
width: 12rem;
}
}
.ts-delete {
min-width: 0 !important;
height: 2.125rem;
padding: 0 1rem !important;
border: 0 !important;
border-radius: 999px !important;
background: var(--ts-c-red) !important;
color: #fff !important;
font: inherit;
font-size: 0.8125rem;
font-weight: 600;
cursor: pointer;
&:disabled {
opacity: 0.45;
cursor: default;
}
}
.ts-settings {
display: grid;
gap: 1rem;
padding-bottom: 0;
}
fieldset {
display: grid;
gap: 1rem;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.ts-settings__pair {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 26rem), 1fr));
gap: 1rem;
align-items: start;
}
.ts-block {
display: grid;
gap: 0.75rem;
min-width: 0;
padding: 1.25rem;
h3 {
margin: 0;
font-size: 1rem;
font-weight: 700;
}
}
.ts-block__head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
p {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
}
}
.ts-rows {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
list-style: none;
}
.ts-rows-head {
padding: 0 0.5rem;
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ts-muted);
}
.ts-status-grid {
display: grid;
grid-template-columns:
1.25rem minmax(10rem, 1fr)
9rem 8rem 5.5rem 5.5rem 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-template {
display: grid;
grid-column: 1 / -1;
gap: 0.5rem;
padding: 0.5rem 0 0.25rem;
}
.ts-template__field {
display: grid;
gap: 0.25rem;
font-size: 0.8125rem;
color: var(--ts-muted);
textarea {
font: inherit;
color: var(--ts-ink);
resize: vertical;
}
}
.ts-template-toggle {
white-space: nowrap;
&.has-template {
border-color: var(--ts-brand) !important;
color: var(--ts-ink) !important;
}
}
.ts-type-grid {
display: grid;
grid-template-columns: 2rem minmax(8rem, 1fr) 7rem 7rem auto 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-area-grid {
display: grid;
grid-template-columns: minmax(8rem, 1fr) 6.5rem;
align-items: center;
gap: 0.5rem;
}
/* Name and archive on top; the type (and options) below. */
.ts-field-grid {
display: grid;
grid-template-columns: minmax(8rem, 1fr) 6.5rem;
align-items: center;
gap: 0.5rem;
.ts-field-type {
grid-row: 2;
grid-column: 1 / -1;
}
}
.ts-field-options {
grid-column: 1 / -1;
display: grid;
gap: 0.25rem;
font-size: 0.8125rem;
color: var(--ts-muted);
textarea {
font: inherit;
color: var(--ts-ink);
background: var(--ts-surface);
border: 1px solid var(--ts-line);
border-radius: 0.5rem;
padding: 0.375rem 0.5rem;
resize: vertical;
}
}
.ts-empty-fields {
margin: 0;
}
.ts-row {
--tone: var(--ts-muted);
padding: 0.375rem 0.5rem;
border-radius: 0.625rem;
background: var(--ts-surface);
border: 1px solid var(--ts-line);
&.is-archived {
background: var(--ts-sunken);
.ts-input,
.ts-type-icon {
opacity: 0.6;
}
}
}
.cdk-drag-preview {
box-shadow: var(--ts-lift);
}
.cdk-drag-placeholder {
opacity: 0.35;
}
.ts-grip {
cursor: grab;
color: var(--ts-muted);
text-align: center;
user-select: none;
}
.ts-name {
position: relative;
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
.ts-input {
flex: 1;
min-width: 0;
}
}
.ts-swatch {
flex: none;
width: 0.625rem;
height: 0.625rem;
border-radius: 50%;
background: var(--tone);
}
.ts-id {
flex: 0 0 5.5rem;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--ts-font-mono);
font-size: 0.625rem;
color: var(--ts-muted);
}
.ts-input {
box-sizing: border-box;
height: 2.125rem;
width: 100%;
padding: 0 0.5rem;
border: 1px solid var(--ts-line);
border-radius: 0.5rem;
background: var(--ts-surface);
color: var(--ts-ink);
font: inherit;
font-size: 0.875rem;
&:focus-visible {
outline: 2px solid var(--ts-brand);
outline-offset: 1px;
}
&:disabled {
color: var(--ts-ink-soft);
background: transparent;
}
}
.ts-check {
display: grid;
place-items: center;
}
input[type='checkbox'] {
width: 1rem;
height: 1rem;
accent-color: var(--ts-brand);
cursor: pointer;
}
.ts-type-icon {
display: inline-grid;
place-items: center;
width: 2rem;
height: 2rem;
border-radius: 0.5rem;
color: var(--tone);
background: color-mix(in srgb, var(--tone) 12%, var(--ts-surface));
}
.ts-matrix-wrap {
overflow-x: auto;
}
.ts-matrix {
border-collapse: collapse;
font-size: 0.8125rem;
th,
td {
padding: 0.375rem 0.5rem;
border-bottom: 1px solid var(--ts-line);
text-align: center;
}
th[scope='row'] {
text-align: left;
white-space: nowrap;
}
thead th {
vertical-align: bottom;
}
tr.is-archived th[scope='row'] {
opacity: 0.6;
}
td:hover {
background: var(--pi-color-primary-25);
}
}
/* @pi/ui styles every : these opt back into a compact look. */
.ts-add,
.ts-archive,
.ts-template-toggle,
.ts-primary,
.ts-secondary {
min-width: 0 !important;
height: 2.125rem;
padding: 0 0.875rem !important;
border-radius: 999px !important;
font: inherit;
font-size: 0.8125rem;
font-weight: 600;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
.ts-add,
.ts-archive,
.ts-secondary {
border: 1px solid var(--ts-line-strong) !important;
background: var(--ts-surface) !important;
color: var(--ts-ink-soft) !important;
}
.ts-archive.is-archived {
border-style: dashed !important;
}
.ts-primary {
border: 0 !important;
background: var(--ts-brand) !important;
color: #fff !important;
}
.ts-savebar {
position: sticky;
bottom: 1rem;
z-index: 3;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
border-radius: 999px;
background: var(--ts-surface-raised);
border: 1px solid var(--ts-line-strong);
box-shadow: var(--ts-lift);
font-size: 0.875rem;
&.is-dirty {
border-color: var(--ts-brand);
}
}
.ts-savebar__status {
flex: 1;
min-width: 0;
}
.ts-problems {
display: grid;
gap: 0.125rem;
margin: 0;
padding: 0;
list-style: none;
color: var(--ts-c-red);
font-size: 0.8125rem;
li {
display: flex;
align-items: center;
gap: 0.375rem;
}
}
@media (max-width: 720px) {
.ts-rows-head {
display: none;
}
.ts-status-grid,
.ts-type-grid {
grid-template-columns: 1fr 1fr;
}
.ts-grip,
.ts-type-icon {
display: none;
}
.ts-name {
grid-column: 1 / -1;
}
.ts-savebar {
flex-wrap: wrap;
border-radius: var(--ts-radius);
}
}
`,
})
export class SettingsPage {
protected readonly facade = inject(ProjectFacade);
protected readonly categories = CATEGORIES;
protected readonly colors = SETTING_COLORS;
protected readonly icons = TYPE_ICONS;
protected readonly fieldTypes = FIELD_TYPES;
/** What the API has; the draft is compared against it. */
private readonly saved = computed(
() => this.facade.project()?.settings ?? null,
);
protected readonly draft = signal(null);
/** The key, typed to confirm deleting the project. */
protected readonly confirmKey = signal('');
protected readonly dirty = computed(
() =>
!!this.draft() &&
JSON.stringify(this.draft()) !== JSON.stringify(this.saved()),
);
protected readonly activeStatuses = computed(
() => this.draft()?.statuses.filter((s) => !s.archived) ?? [],
);
/** The same rules the API enforces, shown before saving. */
protected readonly problems = computed(() => {
const d = this.draft();
if (!d) return [];
const problems: string[] = [];
const lists = [d.statuses, d.issueTypes, d.areas, d.customFields];
if (lists.some((list) => list.some((item) => !item.name.trim())))
problems.push('Hay nombres vacíos');
if (
lists.some((list) => {
const ids = list.map((item) => item.id);
return ids.some((id, i) => ids.indexOf(id) !== i);
})
)
problems.push('Hay dos valores con el mismo nombre');
const active = d.statuses.filter((s) => !s.archived);
if (!active.some((s) => s.category === StatusCategory.TODO))
problems.push(
'Falta un estado activo «Pendiente» donde entren los tickets',
);
if (!active.some((s) => s.category === StatusCategory.DONE))
problems.push('Falta un estado activo «Hecho»');
if (!d.issueTypes.some((t) => !t.archived))
problems.push('Hace falta al menos un tipo de ticket activo');
for (const field of d.customFields)
if (
field.type === CustomFieldType.SELECT &&
!field.options.some((o) => o.trim())
)
problems.push(`El campo «${field.name}» necesita alguna opción`);
return problems;
});
constructor() {
// Follow the saved settings while there is nothing pending (after saving,
// the project comes back equal to the draft, so it is clean again).
effect(() => {
const saved = this.saved();
if (saved && !untracked(this.dirty))
this.draft.set(structuredClone(saved));
});
}
protected readonly toneOf = tone;
protected readonly categoryLabel = (c: StatusCategory) => CATEGORY[c].label;
protected readonly categoryHint = (c: StatusCategory) => CATEGORY[c].hint;
protected readonly iconLabel = (icon: string) => ICON_LABEL[icon] ?? icon;
protected readonly colorLabel = (c: (typeof SETTING_COLORS)[number]) =>
COLOR_LABEL[c];
/** Values the API does not have yet: they can still be removed or have their id follow the name. */
protected isNew(section: Section, id: string): boolean {
return !this.saved()?.[section].some((item) => item.id === id);
}
protected allows(from: string, to: string): boolean {
return !!this.draft()
?.transitions.find((t) => t.from === from)
?.to.includes(to);
}
/** '' (or anything below 1) clears the limit. */
protected wipFrom(value: string): number | null {
const limit = Math.round(Number(value));
return Number.isFinite(limit) && limit >= 1 ? Math.min(limit, 999) : null;
}
/** Index of the type whose template is open. */
protected readonly openTemplate = signal(null);
protected hasTemplate(type: IssueTypeOption): boolean {
return !!(
type.template?.description?.trim() ||
type.template?.checklist.some((s) => s.trim())
);
}
/** Edits the template in the draft; empty lines go when saved. */
protected setTemplate(
index: number,
changes: { description?: string; checklist?: string[] },
): void {
this.patch((d) => {
const type = d.issueTypes[index];
const current = type.template ?? { description: null, checklist: [] };
type.template = {
description:
changes.description !== undefined
? changes.description || null
: current.description,
checklist: (changes.checklist ?? current.checklist).slice(0, 20),
};
});
}
protected edit(section: Section, index: number, changes: object): void {
this.patch((d) => Object.assign(d[section][index], changes));
}
protected setName(section: Section, index: number, name: string): void {
this.patch((d) => {
const item = d[section][index];
item.name = name;
if (this.isNew(section, item.id)) {
const id = this.uniqueId(d[section], idFrom(name), index);
if (section === 'statuses') this.renameStatus(d, item.id, id);
item.id = id;
}
});
}
protected setStatusName(index: number, name: string): void {
this.setName('statuses', index, name);
}
protected toggleTransition(from: string, to: string, on: boolean): void {
this.patch((d) => {
let row = d.transitions.find((t) => t.from === from);
if (!row) {
row = { from, to: [] };
d.transitions.push(row);
}
row.to = on
? [...new Set([...row.to, to])]
: row.to.filter((target) => target !== to);
});
}
protected reorder(event: CdkDragDrop): void {
this.patch((d) =>
moveItemInArray(d.statuses, event.previousIndex, event.currentIndex),
);
}
protected addStatus(): void {
this.patch((d) => {
const id = this.uniqueId(d.statuses, 'NUEVO_ESTADO');
// Before the done/cancelled statuses, so it lands mid-board.
const at = d.statuses.findIndex(
(s) =>
s.category === StatusCategory.DONE ||
s.category === StatusCategory.CANCELLED,
);
d.statuses.splice(at === -1 ? d.statuses.length : at, 0, {
id,
name: 'Nuevo estado',
category: StatusCategory.IN_PROGRESS,
color: 'teal',
requiresReason: false,
archived: false,
});
d.transitions.push({ from: id, to: [] });
});
}
protected addType(): void {
this.patch((d) =>
d.issueTypes.push({
id: this.uniqueId(d.issueTypes, 'NUEVO_TIPO'),
name: 'Nuevo tipo',
icon: 'flag',
color: 'teal',
archived: false,
}),
);
}
protected addArea(): void {
this.patch((d) =>
d.areas.push({
id: this.uniqueId(d.areas, 'NUEVA_AREA'),
name: 'Nueva área',
archived: false,
}),
);
}
protected addField(): void {
this.patch((d) =>
d.customFields.push({
id: this.uniqueId(d.customFields, 'NUEVO_CAMPO'),
name: 'Nuevo campo',
type: CustomFieldType.TEXT,
options: [],
archived: false,
}),
);
}
protected setFieldType(index: number, type: CustomFieldType): void {
this.patch((d) => {
const field = d.customFields[index];
field.type = type;
if (type !== CustomFieldType.SELECT) field.options = [];
});
}
/** One per line; blank lines and repeats go when saved. */
protected setOptions(index: number, text: string): void {
this.patch((d) => {
d.customFields[index].options = text.split('\n').slice(0, 50);
});
}
/** Only for values never saved; saved ones are archived instead. */
protected remove(section: Section, index: number): void {
this.patch((d) => {
const [item] = d[section].splice(index, 1);
if (section === 'statuses') {
d.transitions = d.transitions
.filter((t) => t.from !== item.id)
.map((t) => ({ ...t, to: t.to.filter((to) => to !== item.id) }));
}
});
}
protected discard(): void {
const saved = this.saved();
if (saved) this.draft.set(structuredClone(saved));
}
protected save(): void {
const draft = this.draft();
if (!draft || !this.dirty() || this.problems().length) return;
// Options as the API keeps them, so the draft is clean once saved.
const cleaned: ProjectSettings = {
...draft,
customFields: draft.customFields.map((f) => ({
...f,
options: [...new Set(f.options.map((o) => o.trim()).filter(Boolean))],
})),
};
this.draft.set(cleaned);
this.facade.saveSettings({
...cleaned,
// Only rows with targets; unknown ids would be rejected anyway.
transitions: cleaned.transitions.filter((t) => t.to.length),
});
}
private patch(change: (draft: ProjectSettings) => void): void {
this.draft.update((d) => {
if (!d) return d;
const next = structuredClone(d);
change(next);
return next;
});
}
private uniqueId(list: { id: string }[], base: string, except = -1): string {
const taken = new Set(
list.filter((_, i) => i !== except).map((item) => item.id),
);
let id = base;
for (let n = 2; taken.has(id); n++) id = `${base.slice(0, 27)}_${n}`;
return id;
}
private renameStatus(d: ProjectSettings, from: string, to: string): void {
for (const row of d.transitions) {
if (row.from === from) row.from = to;
row.to = row.to.map((target) => (target === from ? to : target));
}
}
}