All files / webapp/controller SupportStatus.controller.ts

94.35% Statements 117/124
77.77% Branches 28/36
100% Functions 25/25
94.35% Lines 117/124

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                                                                                  13x           13x         13x               13x   13x         13x     13x   13x       13x 13x         13x           39x     39x     39x       39x     39x     39x         39x               13x 13x         13x 13x         4x         3x         4x       4x           4x         2x 6x       6x     2x 10x       10x     2x       2x               1x 1x         1x       1x   1x   1x       1x   1x       1x 1x   1x               39x 39x   39x       39x 39x   39x         4x                     4x 4x     35x   35x       35x       35x 4x   20x               4x               35x 105x       105x   105x 1x                   35x 175x       175x       175x 1x                   35x       35x       35x 1x       5x                 35x         35x       35x   35x       35x               35x   35x         1x 1x   1x       1x   5x   1x           1x 2x       1x                 1x 1x         39x 39x   39x       39x     39x         39x   39x                         35x     35x   35x     151x 604x                   151x             35x               13x     13x     13x       13x   13x       13x   13x               13x      
import BaseController from "./BaseController";
import Dialog from "sap/m/Dialog";
import Input from "sap/m/Input";
import JSONModel from "sap/ui/model/json/JSONModel";
import SearchField from "sap/m/SearchField";
import Select from "sap/m/Select";
import Table from "sap/m/Table";
import ToggleButton from "sap/m/ToggleButton";
import Filter from "sap/ui/model/Filter";
import FilterOperator from "sap/ui/model/FilterOperator";
import FilterType from "sap/ui/model/FilterType";
import ListBinding from "sap/ui/model/ListBinding";
import Sorter from "sap/ui/model/Sorter";
 
import { compareDates, isDateWithinRelativePeriod } from "../model/germanDate";
import {
    FilterOption,
    SEARCH_FIELDS,
    TEXT_FILTERS,
    SELECT_FILTERS,
    DATE_FIELDS,
    MAINSTREAM_MAINTENANCE_FIELD,
    createFilterOptions,
    buildFieldDistribution
} from "../model/pamFilters";
import { PamProduct, PRODUCT_KEY_FIELDS, getProductFieldValue } from "../model/productKey";
 
interface FilterModelData {
    currentStatus: FilterOption[];
    unrestrictedAvailable: FilterOption[];
    restrictedAvailableNotAllowed: FilterOption[];
    mainstreamMaintenance: FilterOption[];
    extendedMaintenance: FilterOption[];
}
 
/**
 * @namespace de.itsfullofstars.sap.pam.controller
 */
export default class SupportStatus extends BaseController {
    /** Sets up the supportStatus/filter/view models and loads the initial filter/own-products state. */
    public onInit(): void {
        const supportStatusModel = new JSONModel({
            hasOwnProducts: false,
            noOwnProducts: true,
            heading: this.getText("supportStatus.heading", [0])
        });
 
        this.setModel(
            supportStatusModel,
            "supportStatus"
        );
 
        const filterModel = new JSONModel({
            currentStatus: [],
            unrestrictedAvailable: [],
            restrictedAvailableNotAllowed: [],
            mainstreamMaintenance: [],
            extendedMaintenance: []
        });
 
        this.setModel(filterModel, "filter");
 
        this.setModel(new JSONModel({
            supportEndHighlightDate: null,  // null = no highlighting
            showAdvancedFilters: false
        }), "view");
 
        const pamModel = this.getOwnerComponent()
            .getModel("pam") as JSONModel;
 
        this.updateOwnProductsState();
 
        this.getRouter()
            .getRoute("supportstatus")
            ?.attachPatternMatched(this.onRouteMatched.bind(this));
 
        Eif (pamModel) {
            this.updateFilterValues();
 
            // The "pam" model's data loads asynchronously (manifest "uri"), so it may
            // not be available yet when onInit runs - rebuild the filter options once
            // it is.
            pamModel.attachRequestCompleted(this.updateFilterValues.bind(this));
        }
    }
 
    /** Updates the "supportStatus" model's hasOwnProducts/noOwnProducts flags from the current own-products data. */
    private updateOwnProductsState(): void {
        const ownProductsModel = this.getOwnerComponent()
            .getModel("ownProducts") as JSONModel;
 
        const supportStatusModel = this.getView()
            .getModel("supportStatus") as JSONModel;
 
        Iif (!supportStatusModel) {
            return;
        }
 
        const ownProducts = ownProductsModel?.getData() as PamProduct[] | undefined;
 
        const hasOwnProducts =
            Array.isArray(ownProducts) &&
            ownProducts.length > 0;
 
        supportStatusModel.setProperty(
            "/hasOwnProducts",
            hasOwnProducts
        );
 
        supportStatusModel.setProperty(
            "/noOwnProducts",
            !hasOwnProducts
        );
    }
 
    /** Refreshes own-products state and table filters once the view has rendered. */
    public onAfterRendering(): void {
        this.updateOwnProductsState();
        this.applyTableState();
    }
 
    /** Refreshes own-products state and table filters whenever this route is (re-)matched. */
    public onRouteMatched(): void {
        this.updateOwnProductsState();
        this.applyTableState();
    }
 
    /** Re-applies filters/sorting after the global search field's value changes. */
    public onSearchChange(): void {
        this.applyTableState();
    }
 
    /** Re-applies filters/sorting after a filter panel value changes. */
    public onFilterChange(): void {
        this.applyTableState();
    }
 
    /** Updates the sort direction button label and re-applies filters/sorting. */
    public onSortChange(): void {
        const sortButton = this.byId(
            "sortAscending"
        ) as ToggleButton;
 
        sortButton.setText(
            sortButton.getPressed()
                ? this.getText("table.sortAscending")
                : this.getText("table.sortDescending")
        );
 
        this.applyTableState();
    }
 
    /** Clears all filter panel input/select values, without touching search or sorting. */
    private resetFilterPanelValues(): void {
        TEXT_FILTERS.forEach((filterDefinition) => {
            const input = this.byId(
                filterDefinition.id
            ) as Input;
 
            input.setValue("");
        });
 
        SELECT_FILTERS.forEach((filterDefinition) => {
            const select = this.byId(
                filterDefinition.id
            ) as Select;
 
            select.setSelectedKey("");
        });
 
        const relativeFilter = this.byId(
            "filterMainstreamMaintenanceRelative"
        ) as Select;
 
        relativeFilter.setSelectedKey("");
    }
 
    /**
     * Resets only the filter panel's values. Unlike {@link onReset}, the
     * table's full-text search and sorting are left untouched.
     */
    public onResetFilters(): void {
        this.resetFilterPanelValues();
        this.applyTableState();
    }
 
    /** Resets search, filters and sorting back to their defaults. */
    public onReset(): void {
        const searchField = this.byId(
            "globalSearch"
        ) as SearchField;
 
        searchField.setValue("");
 
        this.resetFilterPanelValues();
 
        const sortField = this.byId(
            "sortField"
        ) as Select;
 
        sortField.setSelectedKey("version");
 
        const sortButton = this.byId(
            "sortAscending"
        ) as ToggleButton;
 
        sortButton.setPressed(true);
        sortButton.setText(this.getText("table.sortAscending"));
 
        this.applyTableState();
    }
 
    /**
     * Rebuilds the table's filters and sorter from the own-products
     * selection and the current search/filter/sort controls.
     */
    private applyTableState(): void {
        const table = this.byId("supportStatusTable") as Table;
        const binding = table?.getBinding("items") as ListBinding | undefined;
 
        Iif (!binding) {
            return;
        }
 
        const ownProductsModel = this.getOwnerComponent().getModel("ownProducts") as JSONModel;
        const ownProducts = ownProductsModel?.getData() as PamProduct[] | undefined;
 
        if (!Array.isArray(ownProducts) || ownProducts.length === 0) {
            /*
            * Additionally filter the table to empty. It is also hidden
            * via the supportStatus model.
            */
            binding.filter(
                [
                    new Filter(
                        "version",
                        FilterOperator.EQ,
                        "__NO_OWN_PRODUCTS__"
                    )
                ],
                FilterType.Application
            );
 
            this.updateHeading();
            return;
        }
 
        const filters: Filter[] = [this.createOwnProductsFilter()];
 
        const searchField = this.byId(
            "globalSearch"
        ) as SearchField;
 
        const searchValue = searchField
            .getValue()
            .trim();
 
        if (searchValue) {
            const searchFilters = SEARCH_FIELDS.map(
                (field) => {
                    return new Filter(
                        field,
                        FilterOperator.Contains,
                        searchValue
                    );
                }
            );
 
            filters.push(
                new Filter({
                    filters: searchFilters,
                    and: false
                })
            );
        }
 
        TEXT_FILTERS.forEach((filterDefinition) => {
            const input = this.byId(
                filterDefinition.id
            ) as Input;
 
            const value = input.getValue().trim();
 
            if (value) {
                filters.push(
                    new Filter(
                        filterDefinition.path,
                        FilterOperator.Contains,
                        value
                    )
                );
            }
        });
 
        SELECT_FILTERS.forEach((filterDefinition) => {
            const select = this.byId(
                filterDefinition.id
            ) as Select;
 
            const selectedValue = select
                .getSelectedKey()
                .trim();
 
            if (selectedValue) {
                filters.push(
                    new Filter(
                        filterDefinition.path,
                        FilterOperator.EQ,
                        selectedValue
                    )
                );
            }
        });
 
        const relativeFilter = this.byId(
            "filterMainstreamMaintenanceRelative"
        ) as Select;
 
        const relativeMonths = Number(
            relativeFilter.getSelectedKey()
        );
 
        if (relativeMonths > 0) {
            filters.push(
                new Filter({
                    path: MAINSTREAM_MAINTENANCE_FIELD,
                    test: (value: unknown): boolean => {
                        return isDateWithinRelativePeriod(
                            value,
                            relativeMonths
                        );
                    }
                })
            );
        }
 
        binding.filter(
            filters,
            FilterType.Application
        );
 
        const sortField = this.byId(
            "sortField"
        ) as Select;
 
        const sortPath = sortField.getSelectedKey();
 
        const sortButton = this.byId(
            "sortAscending"
        ) as ToggleButton;
 
        const sorter = new Sorter({
            path: sortPath,
            descending: !sortButton.getPressed(),
            comparator: DATE_FIELDS.includes(sortPath)
                ? compareDates
                : undefined
        });
 
        binding.sort(sorter);
 
        this.updateHeading();
    }
 
    /** Opens the chart analysis dialog with the status distribution of the currently filtered table rows. */
    public onShowChartAnalysis(): void {
        const table = this.byId("supportStatusTable") as Table;
        const binding = table?.getBinding("items") as ListBinding | undefined;
 
        Iif (!binding) {
            return;
        }
 
        const entries = binding
            .getContexts(0, binding.getLength())
            .map((context) => context.getObject() as PamProduct);
 
        const distribution = buildFieldDistribution(
            entries,
            "status",
            this.getText("chart.unspecifiedValue")
        );
 
        const maxCount = distribution.reduce(
            (max, entry) => Math.max(max, entry.count),
            1
        );
 
        this.setModel(
            new JSONModel({
                totalText: this.getText("chart.entriesShown", [entries.length]),
                maxCount,
                distribution
            }),
            "chart"
        );
 
        const dialog = this.byId("chartAnalysisDialog") as Dialog;
        dialog.open();
    }
 
    /** Updates the table heading with the current (filtered) row count. */
    private updateHeading(): void {
        const table = this.byId("supportStatusTable") as Table;
        const binding = table?.getBinding("items") as ListBinding | undefined;
 
        Iif (!binding) {
            return;
        }
 
        const count = binding.getLength();
 
        // Don't overwrite with a bogus value while still loading
        Iif (count < 0) {
            return;
        }
 
        const supportStatusModel =
            this.getModel("supportStatus") as JSONModel;
 
        supportStatusModel.setProperty(
            "/heading",
            this.getText("supportStatus.heading", [count.toLocaleString("de-DE")])
        );
    }
 
    /**
     * Builds an OR-of-ANDs filter matching any of the user's own products
     * (by the {@link PRODUCT_KEY_FIELDS} tuple). Only ever called from
     * {@link applyTableState} once it has already confirmed `ownProducts`
     * is a non-empty array, so that case isn't re-checked here.
     */
    private createOwnProductsFilter(): Filter {
        const ownProductsModel = this.getOwnerComponent()
            .getModel("ownProducts") as JSONModel;
 
        const ownProducts = ownProductsModel.getData() as PamProduct[];
 
        const ownProductFilters = ownProducts.map(
            (product: PamProduct) => {
                const productFieldFilters =
                    PRODUCT_KEY_FIELDS.map((field) => {
                        return new Filter(
                            field,
                            FilterOperator.EQ,
                            getProductFieldValue(
                                product,
                                field
                            )
                        );
                    });
 
                return new Filter({
                    filters: productFieldFilters,
                    and: true
                });
            }
        );
 
        return new Filter({
            filters: ownProductFilters,
            and: false
        });
    }
 
    /** Rebuilds the "filter" model's dropdown options from the current "pam" model data. */
    private updateFilterValues(): void {
        const pamModel = this.getOwnerComponent()
            .getModel("pam") as JSONModel;
 
        const filterModel = this.getView()
            .getModel("filter") as JSONModel;
 
        Iif (!pamModel || !filterModel) {
            return;
        }
 
        const data = pamModel.getData() as PamProduct[];
 
        Iif (!Array.isArray(data)) {
            return;
        }
 
        const allLabel = this.getText("filter.relativeAll");
 
        const filterData: FilterModelData = {
            currentStatus: createFilterOptions(data, "status", allLabel),
            unrestrictedAvailable: createFilterOptions(data, "ua", allLabel),
            restrictedAvailableNotAllowed: createFilterOptions(data, "ra_puna", allLabel),
            mainstreamMaintenance: createFilterOptions(data, "eomm", allLabel),
            extendedMaintenance: createFilterOptions(data, "eom", allLabel)
        };
 
        filterModel.setData(filterData);
    }
}