All files / src/models PrjTaskManagementModel.ts

0% Statements 0/162
0% Branches 0/158
0% Functions 0/20
0% Lines 0/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { TFile, moment } from 'obsidian';
import { Logging } from 'src/classes/Logging';
import { Path } from 'src/classes/Path';
import type IMetadataCache from 'src/interfaces/IMetadataCache';
import { Inject } from 'src/libs/DependencyInjection/decorators/Inject';
import { IDIContainer } from 'src/libs/DependencyInjection/interfaces/IDIContainer';
import { HelperGeneral } from 'src/libs/Helper/General';
import type {
    IStatusType,
    IStatusType_,
} from 'src/libs/StatusType/interfaces/IStatusType';
import { Tag } from 'src/libs/Tags/Tag';
import type { IPrjSettings } from 'src/types/PrjSettings';
import { IPrjData } from './Data/interfaces/IPrjData';
import { IPrjTaskManagementData } from './Data/interfaces/IPrjTaskManagementData';
import PrjBaseData from './Data/PrjBaseData';
import PrjProjectData from './Data/PrjProjectData';
import PrjTaskData from './Data/PrjTaskData';
import PrjTopicData from './Data/PrjTopicData';
import { FileModel } from './FileModel';
import IPrjModel from './interfaces/IPrjModel';
 
/**
 * Represents a project, task or topic.
 */
export class PrjTaskManagementModel<
        T extends IPrjTaskManagementData & PrjBaseData<unknown>,
    >
    extends FileModel<T>
    implements IPrjModel<T>
{
    @Inject('IStatusType_')
    protected static _IStatusType: IStatusType_;
    /**
     * Gets the IStatusType.
     */
    protected get _IStatusType(): IStatusType_ {
        return PrjTaskManagementModel._IStatusType;
    }
 
    /**
     * The data of the model.
     */
    public get data(): T {
        return this._data as T;
    }
    /**
     * The data of the model.
     */
    public set data(value: Partial<T>) {
        this._data = value;
    }
 
    /**
     * Creates a new instance of the PrjTaskManagementModel.
     * @param file The file to create the PrjTaskManagementModel from.
     * @param ctor The constructor of the data class.
     * @param dependencies The optional dependencies to use.
     */
    constructor(
        file: TFile | undefined,
        ctor: new (data?: Partial<T>) => T,
        dependencies?: IDIContainer,
    ) {
        super(file, ctor, undefined, dependencies);
    }
 
    /**
     * Returns the corosponding symbol for the model from the settings.
     * @returns The corosponding symbol for the model. (Lucide icon string)
     */
    public getCorospondingSymbol(): string {
        switch (this.data.type?.toString()) {
            case 'Topic':
                return this._IPrjSettings.prjSettings.topicSymbol;
            case 'Project':
                return this._IPrjSettings.prjSettings.projectSymbol;
            case 'Task':
                return this._IPrjSettings.prjSettings.taskSymbol;
            default:
                return 'x-circle';
        }
    }
 
    /**
     * Returns the acronym of the title of the model.
     * @returns The acronym of the title.
     * @remarks - If the title is not available, an empty string is returned.
     * - Override if the acronym should be generated differently!
     */
    public getAcronym(): string {
        return HelperGeneral.generateAcronym(this.data.title as string);
    }
 
    /**
     * Check if the `newStatus` is valid and change the status of the model.
     * @param newStatus The new status to set.
     * @remarks - A history entry will be added if the status changes.
     * - This function will start and finish a transaction if no transaction is currently running.
     */
    public changeStatus(newStatus: unknown): void {
        Iif (!this._IStatusType.validate(newStatus)) return;
 
        Iif (!this.data.status?.equals(newStatus)) {
            let internalTransaction = false;
 
            Iif (!this.isTransactionActive) {
                this.startTransaction();
                internalTransaction = true;
            }
            this.data.status = newStatus;
 
            Iif (this.data.status == null) {
                return;
            }
            this.addHistoryEntry(this.data.status);
 
            Iif (internalTransaction) this.finishTransaction();
        }
    }
 
    /**
     * Returns the urgency of the model.
     */
    public get urgency(): number {
        return PrjTaskManagementModel.calculateUrgency(
            this as unknown as PrjTaskManagementModel<
                PrjTaskData | PrjTopicData | PrjProjectData
            >,
        );
    }
 
    /**
     * Add a new history entry to the model.
     * @param status The status to add to the history. If not provided, the current status of the model will be used.
     * @remarks - This function will not start or finish a transaction.
     * - If no status is provided and the model has no status, an error will be logged and the function will return.
     */
    private addHistoryEntry(status?: IStatusType | undefined): void {
        Iif (!status) {
            if (this.data.status) status = this.data.status;
            else {
                this._logger?.error('No status aviable to add to history');
 
                return;
            }
        }
 
        Iif (!this.data.history) this.data.history = [];
 
        this.data.history.push({
            status: status.toString(),
            date: moment().format('YYYY-MM-DDTHH:mm'),
        });
    }
 
    /**
     * Returns the aliases of the model as an array of strings
     * @returns Array of strings containing the aliases
     */
    public getAliases(): string[] {
        const aliases = this.data.aliases;
        let formattedAliases: string[] = [];
 
        if (aliases && typeof aliases === 'string') {
            formattedAliases = [aliases];
        } else Iif (Array.isArray(aliases)) {
            formattedAliases = [...aliases];
        }
 
        return formattedAliases;
    }
 
    /**
     * Retrieves the automatic filename based on the title and aliases.
     * @returns The automatic filename or undefined if the title or aliases are not available.
     * @remarks If the file's parent path is available, a new filename is generated by combining the last alias, title, and file extension.
     * @remarks If the title or aliases are not available, a warning message is logged and undefined is returned.
     */
    public getAutomaticFilename(): string | undefined {
        const title = this.data.title;
 
        const aliases =
            this.getAliases().length > 0
                ? new Tag(
                      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                      this.getAliases().first()!,
                  ).getElements()
                : undefined;
 
        let filename: string;
 
        Iif (!title) {
            this._logger?.warn(`No title found for file ${this.file?.path}`);
 
            return;
        }
 
        if (!aliases) {
            this._logger?.info(`No aliases found for file ${this.file?.path}`);
            filename = title;
        } else {
            filename = `${aliases.last()} - ${title}`;
        }
 
        Iif (this.file.parent?.path) {
            const newFileName = Path.sanitizeFilename(filename);
 
            this._logger?.debug(
                `New filename for ${this.file.path}: ${newFileName}`,
            );
 
            return newFileName;
        }
    }
 
    //#region Static API
    /**
     * Static API for the PrjTaskManagementModel class.
     */
 
    @Inject('IMetadataCache')
    protected static readonly _IMetadataCache: IMetadataCache;
    @Inject('IPrjSettings')
    protected static readonly _IPrjSettings: IPrjSettings;
 
    /**
     * The model factories for the PrjTaskManagementModel class.
     */
    private static readonly _modelFactories = new Map<
        string,
        (
            file: TFile,
        ) => PrjTaskManagementModel<
            IPrjData & IPrjTaskManagementData & PrjBaseData<unknown>
        >
    >();
 
    /**
     * Registers a new model factory for the given type.
     * @param type The type to register the factory for.
     * @param factory The factory to register.
     */
    public static registerModelFactory(
        type: string,
        factory: (
            file: TFile,
        ) => PrjTaskManagementModel<
            IPrjData & IPrjTaskManagementData & PrjBaseData<unknown>
        >,
    ): void {
        PrjTaskManagementModel._modelFactories.set(type, factory);
    }
 
    /**
     * Retrieves the corresponding model based on the file type.
     * @param file The file for which to retrieve the corresponding model.
     * @returns The corresponding model if found, otherwise undefined.
     */
    public static getCorospondingModel(
        file: TFile,
    ):
        | PrjTaskManagementModel<
              IPrjData & IPrjTaskManagementData & PrjBaseData<unknown>
          >
        | undefined {
        const entry = this._IMetadataCache.getEntry(file);
 
        Iif (!entry) return undefined;
        const type = entry.metadata.frontmatter?.type;
        const factory = PrjTaskManagementModel._modelFactories.get(type);
 
        return factory ? factory(file) : undefined;
    }
 
    /**
     * Sorts the models by urgency descending
     * @param models Array of PrjTaskManagementModels to sort
     * @remarks This function sorts the array in place
     * @see {@link statusToNumber}
     * @see {@link calculateUrgency}
     * @see {@link getLastHistoryDate}
     * @remarks The sorting is done as follows:
     * - If both are `done`, sort by last history entry
     * - If `a` or `b` is done, sort it lower
     * - Both are not done, sort by urgency
     * - Both have the same urgency, sort by status
     * - Both have the same status, sort by priority
     * - Fallback to sorting by last history entry
     * - Fallback to stop sorting
     */
    public static sortModelsByUrgency(
        models: PrjTaskManagementModel<
            PrjTaskData | PrjTopicData | PrjProjectData
        >[],
    ): void {
        models.sort((a, b) => {
            // If both are `done`, sort by last history entry
            const aDate = this.getLastHistoryDate(a);
            const bDate = this.getLastHistoryDate(b);
 
            Iif (
                a.data.status?.equals('Done') &&
                b.data.status?.equals('Done')
            ) {
                Iif (aDate && bDate) {
                    return bDate.getTime() - aDate.getTime();
                }
            }
 
            // If `a` is done, sort it lower
            Iif (a.data.status?.equals('Done')) {
                return 1;
            }
 
            // If `b` is done, sort it lower
            Iif (b.data.status?.equals('Done')) {
                return -1;
            }
 
            // Both are not done, sort by urgency
            const aUrgency = this.calculateUrgency(a);
            const bUrgency = this.calculateUrgency(b);
 
            Iif (bUrgency !== aUrgency) {
                return bUrgency - aUrgency;
            }
 
            // Both have the same urgency, sort by status
            const aStatus = this.statusToNumber(a.data.status);
 
            const bStatus = this.statusToNumber(b.data.status);
 
            Iif (bStatus !== aStatus) {
                return bStatus - aStatus;
            }
 
            // Both have the same status, sort by priority
            const aPrirority = a.data.priority ?? 0;
            const bPrirority = b.data.priority ?? 0;
 
            Iif (bPrirority !== aPrirority) {
                return bPrirority - aPrirority;
            }
 
            // Fallback to sorting by last history entry
            Iif (aDate && bDate) {
                return bDate.getTime() - aDate.getTime();
            }
 
            // Fallback to stop sorting
            return 0;
        });
    }
 
    /**
     * Returns the number representation of the status.
     * @param status The status to convert.
     * @returns The number representation of the status.
     * @remarks The number representation is:
     * - `Active` = 3
     * - `Waiting` = 2
     * - `Later` = 1
     * - `Someday` = 0
     * - `undefined` = -1
     */
    private static statusToNumber(
        status: IStatusType | undefined | null,
    ): number {
        switch (status?.toString()) {
            case 'Active':
                return 3;
            case 'Waiting':
                return 2;
            case 'Later':
                return 1;
            case 'Someday':
                return 0;
            default:
                return -1;
        }
    }
 
    /**
     * Calculates the urgency of the model.
     * @param model The model to calculate the urgency for.
     * @returns The urgency of the model.
     * @remarks The urgency is calculated as follows:
     * - No `status` or `status` is 'Done' = -2
     * - No `due` or `status` is 'Someday' = -1
     * - Due date is today or in the past = 3
     * - Due date is in the next 3 days = 2
     * - Due date is in the next 7 days = 1
     * - Due date is in more the future = 0
     */
    public static calculateUrgency(
        model: PrjTaskManagementModel<
            PrjTaskData | PrjTopicData | PrjProjectData
        >,
    ): number {
        Iif (!model.data.status || model.data.status.equals('Done')) {
            return -2;
        }
 
        Iif (model.data.status.equals('Someday')) {
            return -1;
        }
 
        Iif (!model.data.due) {
            return 0;
        }
 
        const dueDate = new Date(model.data.due);
        dueDate.setHours(0, 0, 0, 0);
 
        const today = new Date();
        today.setHours(0, 0, 0, 0);
 
        const differenceInDays =
            (dueDate.getTime() - today.getTime()) / (1000 * 3600 * 24);
 
        let urgency = 0;
 
        if (differenceInDays <= 0) {
            urgency = 3;
        } else if (differenceInDays <= 3) {
            urgency = 2;
        } else Iif (differenceInDays <= 7) {
            urgency = 1;
        }
 
        return urgency;
    }
 
    /**
     * Returns the date of the last history entry.
     * @param model The model to get the last history entry date from.
     * @returns The date of the last history entry.
     */
    private static getLastHistoryDate(
        model: PrjTaskManagementModel<
            PrjTaskData | PrjTopicData | PrjProjectData
        >,
    ): Date | null {
        if (
            model.data.history &&
            Array.isArray(model.data.history) &&
            model.data.history.length > 0
        ) {
            const history = model.data.history;
            const lastEntry = history[history.length - 1];
 
            return new Date(lastEntry.date);
        } else {
            return null;
        }
    }
 
    /**
     * Synchronizes the title of the file with its filename.
     * @param file - The file to synchronize the title and filename.
     * @see {@link PrjTaskManagementModel.getAutomaticFilename()}
     */
    public static syncTitleToFilename(file: TFile): void {
        const logger = Logging.getLogger(
            'StaticPrjTaskManagementModel/syncTitleToFilename',
        );
 
        const model = PrjTaskManagementModel.getCorospondingModel(file);
 
        Iif (!model) {
            logger.warn(`No model found for file ${file.path}`);
 
            return;
        }
 
        const automaticFilename = model.getAutomaticFilename();
 
        Iif (!automaticFilename) {
            logger.warn(`No automatic filename found for file ${file.path}`);
 
            return;
        }
 
        model.renameFile(automaticFilename);
    }
 
    /**
     * Syncs the status of the model to the path.
     * @param file The file to sync the status for.
     */
    public static syncStatusToPath(file: TFile): void {
        const model = PrjTaskManagementModel.getCorospondingModel(file);
 
        Iif (!model) {
            return;
        }
        const status = model.data.status;
 
        Iif (!status) {
            return;
        }
        const settings = this._IPrjSettings.prjSettings;
        let parentPath: string | undefined;
 
        Iif (model.file.parent?.path) {
            switch (model.data.type?.toString()) {
                case 'Topic':
                    Iif (settings.topicFolder) {
                        parentPath = settings.topicFolder;
                    }
                    break;
                case 'Project':
                    Iif (settings.projectFolder) {
                        parentPath = settings.projectFolder;
                    }
                    break;
                case 'Task':
                    Iif (settings.taskFolder) {
                        parentPath = settings.taskFolder;
                    }
                    break;
                default:
                    return;
            }
        }
 
        Iif (parentPath) {
            let movePath: string;
 
            if (model.data.status?.equals('Done')) {
                movePath = Path.join(parentPath, 'Archiv');
            } else if (this._IStatusType.isValid(model.data.status)) {
                movePath = parentPath;
            } else {
                return;
            }
 
            model.moveFile(movePath);
        }
    }
 
    //#endregion
}
 
Zur TypeDoc-Dokumentation