Implement keyboard shortcuts and workflow changes

This commit is contained in:
2026-08-25 18:51:03 +05:30
parent 1b2ef5126e
commit fa2522e678
36 changed files with 1865 additions and 181 deletions
@@ -119,7 +119,7 @@
<button <button
mat-raised-button mat-raised-button
color="primary" color="primary"
[disabled]="!glAccountForm.valid" [disabled]="!glAccountForm.valid || submitting"
*mifosxHasPermission="'CREATE_GLACCOUNT'" *mifosxHasPermission="'CREATE_GLACCOUNT'"
> >
{{ 'labels.buttons.Submit' | translate }} {{ 'labels.buttons.Submit' | translate }}
@@ -14,6 +14,7 @@ import { MatDialog } from '@angular/material/dialog';
/** Custom Services */ /** Custom Services */
import { AccountingService } from '../../accounting.service'; import { AccountingService } from '../../accounting.service';
import { AlertService } from 'app/core/alert/alert.service';
import { PopoverService } from '../../../configuration-wizard/popover/popover.service'; import { PopoverService } from '../../../configuration-wizard/popover/popover.service';
import { ConfigurationWizardService } from '../../../configuration-wizard/configuration-wizard.service'; import { ConfigurationWizardService } from '../../../configuration-wizard/configuration-wizard.service';
@@ -42,6 +43,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CreateGlAccountComponent implements OnInit, AfterViewInit { export class CreateGlAccountComponent implements OnInit, AfterViewInit {
private formBuilder = inject(UntypedFormBuilder); private formBuilder = inject(UntypedFormBuilder);
private accountingService = inject(AccountingService); private accountingService = inject(AccountingService);
private alertService = inject(AlertService);
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private router = inject(Router); private router = inject(Router);
private configurationWizardService = inject(ConfigurationWizardService); private configurationWizardService = inject(ConfigurationWizardService);
@@ -50,6 +52,8 @@ export class CreateGlAccountComponent implements OnInit, AfterViewInit {
/** GL account form. */ /** GL account form. */
glAccountForm: UntypedFormGroup; glAccountForm: UntypedFormGroup;
/** Submitting state to prevent duplicate submissions. */
submitting = false;
/** Chart of accounts data. */ /** Chart of accounts data. */
chartOfAccountsData: any; chartOfAccountsData: any;
/** Account type data. */ /** Account type data. */
@@ -166,13 +170,16 @@ export class CreateGlAccountComponent implements OnInit, AfterViewInit {
/** /**
* Submits the gl account form and creates gl account, * Submits the gl account form and creates gl account,
* if successful redirects to view created account. * if successful redirects to view created account or back to list if awaiting approval.
*/ */
submit() { submit() {
if (this.glAccountForm.invalid) { if (this.glAccountForm.invalid || this.submitting) {
return; return;
} }
this.accountingService.createGlAccount(this.glAccountForm.value).subscribe((response: any) => { this.submitting = true;
this.accountingService.createGlAccount(this.glAccountForm.value).subscribe({
next: (response: any) => {
if (response?.resourceId) {
if (this.configurationWizardService.showChartofAccounts) { if (this.configurationWizardService.showChartofAccounts) {
this.configurationWizardService.showChartofAccounts = false; this.configurationWizardService.showChartofAccounts = false;
this.openDialog(); this.openDialog();
@@ -185,6 +192,19 @@ export class CreateGlAccountComponent implements OnInit, AfterViewInit {
{ relativeTo: this.route } { relativeTo: this.route }
); );
} }
} else if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'GL Account submitted successfully for approval.'
});
this.router.navigate([this.cancelRoute], { relativeTo: this.route });
} else {
this.router.navigate([this.cancelRoute], { relativeTo: this.route });
}
},
error: () => {
this.submitting = false;
}
}); });
} }
+1 -1
View File
@@ -16,7 +16,7 @@ import { Observable, of, throwError } from 'rxjs';
import { switchMap } from 'rxjs/operators'; import { switchMap } from 'rxjs/operators';
import { map, catchError } from 'rxjs/operators'; import { map, catchError } from 'rxjs/operators';
import { environment } from 'environments/environment'; import { environment } from '../../environments/environment';
import { dataUrlToFile } from 'app/shared/utils/data-url.util'; import { dataUrlToFile } from 'app/shared/utils/data-url.util';
/** /**
@@ -11,7 +11,7 @@ import { UntypedFormGroup } from '@angular/forms';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, switchMap, takeUntil, timeout, catchError } from 'rxjs/operators'; import { debounceTime, distinctUntilChanged, filter, switchMap, takeUntil, timeout, catchError } from 'rxjs/operators';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { environment } from 'environments/environment'; import { environment } from '../../../environments/environment';
import { ClientsService } from '../clients.service'; import { ClientsService } from '../clients.service';
import { import {
EXTERNAL_ID_STATUS_KEYS, EXTERNAL_ID_STATUS_KEYS,
@@ -0,0 +1,228 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Injectable, inject, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { fromEvent, Subscription, BehaviorSubject } from 'rxjs';
import { KeyboardShortcutsConfiguration } from '../../keyboards-shortcut-config';
import { AuthenticationService } from '../authentication/authentication.service';
import { UserPreferenceService } from './user-preference.service';
import { DocumentationLinksService } from '../../shared/services/documentation-links.service';
export interface ShortcutItem {
title: string;
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
key: string;
route: string;
id?: string;
custom?: boolean;
action?: string;
}
@Injectable({
providedIn: 'root'
})
export class KeyboardShortcutService implements OnDestroy {
private router = inject(Router);
private activatedRoute = inject(ActivatedRoute);
private authenticationService = inject(AuthenticationService);
private userPreferenceService = inject(UserPreferenceService);
private documentationLinks = inject(DocumentationLinksService);
private keydownSubscription: Subscription;
private activeShortcutsSubject = new BehaviorSubject<ShortcutItem[]>([]);
public activeShortcuts$ = this.activeShortcutsSubject.asObservable();
constructor() {
this.keydownSubscription = fromEvent<KeyboardEvent>(window, 'keydown').subscribe((event) => {
this.handleKeydown(event);
});
}
ngOnDestroy(): void {
if (this.keydownSubscription) {
this.keydownSubscription.unsubscribe();
}
}
public initShortcuts(): void {
const credentials = this.authenticationService.getCredentials();
if (!credentials || !credentials.userId) {
this.loadDefaults();
return;
}
this.userPreferenceService.getPreference(credentials.userId, 'keyboard_shortcuts').subscribe({
next: (data) => {
if (data && data.value) {
try {
const parsed = JSON.parse(data.value);
if (Array.isArray(parsed)) {
parsed.forEach((shortcut: ShortcutItem) => {
if (shortcut.custom && shortcut.action === 'navigate' && shortcut.route) {
shortcut.route = this.normalizeRouteStr(shortcut.route);
}
});
}
this.activeShortcutsSubject.next(parsed);
} catch (e) {
console.error('Error parsing shortcuts', e);
this.loadDefaults();
}
} else {
this.loadDefaults();
}
},
error: () => {
this.loadDefaults();
}
});
}
public loadDefaults(): void {
const config = new KeyboardShortcutsConfiguration();
this.activeShortcutsSubject.next(config.buttonsArray);
}
public updateShortcuts(shortcuts: ShortcutItem[]): void {
const credentials = this.authenticationService.getCredentials();
if (credentials && credentials.userId) {
const cleanedShortcuts = shortcuts.map((s) => {
const clean: any = {
title: s.title,
ctrlKey: s.ctrlKey,
shiftKey: s.shiftKey,
altKey: s.altKey,
key: s.key,
route: s.route
};
if (s.id !== undefined) clean.id = s.id;
if (s.custom !== undefined) clean.custom = s.custom;
if (s.action !== undefined) clean.action = s.action;
return clean;
});
this.userPreferenceService
.updatePreference(credentials.userId, 'keyboard_shortcuts', JSON.stringify(cleanedShortcuts))
.subscribe(() => {
this.activeShortcutsSubject.next(shortcuts);
});
} else {
this.activeShortcutsSubject.next(shortcuts);
}
}
public resetToDefaults(): void {
const credentials = this.authenticationService.getCredentials();
const config = new KeyboardShortcutsConfiguration();
if (credentials && credentials.userId) {
this.userPreferenceService
.updatePreference(credentials.userId, 'keyboard_shortcuts', JSON.stringify(config.buttonsArray))
.subscribe(() => {
this.activeShortcutsSubject.next(config.buttonsArray);
});
} else {
this.activeShortcutsSubject.next(config.buttonsArray);
}
}
private handleKeydown(event: KeyboardEvent): void {
const activeShortcuts = this.activeShortcutsSubject.getValue();
const routeD = activeShortcuts.find(
(x) =>
x.ctrlKey === event.ctrlKey &&
x.shiftKey === event.shiftKey &&
x.altKey === event.altKey &&
x.key.toLowerCase() === event.key.toLowerCase()
);
if (routeD !== undefined) {
event.preventDefault(); // Prevent default browser actions for matched shortcuts
if (routeD.custom) {
if (routeD.action === 'navigate' && routeD.route) {
this.router.navigate([routeD.route]);
}
} else {
switch (routeD.id) {
case 'logout':
this.authenticationService.logout().subscribe(() => this.router.navigate(['/login'], { replaceUrl: true }));
break;
case 'help':
this.documentationLinks.open('userManual');
break;
case 'runReport':
const runReportElement = document.getElementById('runReport');
if (runReportElement) runReportElement.click();
break;
case 'cancel':
const cancelEl = document.querySelector('[data-shortcut-action="cancel"]') as HTMLElement;
if (cancelEl) {
cancelEl.click();
} else {
const cancelButtons = Array.from(document.querySelectorAll('button')).filter(
(el) => el.textContent && el.textContent.trim() === 'Cancel'
);
if (cancelButtons.length > 0) cancelButtons[0].click();
}
break;
case 'submit':
const submitEl = document.querySelector('[data-shortcut-action="submit"]') as HTMLElement;
if (submitEl) {
submitEl.click();
} else {
const submitButtons = Array.from(document.querySelectorAll('button')).filter(
(el) => el.textContent && el.textContent.trim() === 'Submit'
);
if (submitButtons.length > 0) submitButtons[0].click();
}
break;
default:
this.router.navigate([routeD.route], { relativeTo: this.activatedRoute });
}
}
}
}
public normalizeRouteStr(route: string | undefined | null): string {
if (!route) return '';
let r = route.trim();
try {
if (r.startsWith('http://') || r.startsWith('https://')) {
const url = new URL(r);
if (url.hash && url.hash.startsWith('#')) {
let path = url.hash.substring(1);
if (!path.startsWith('/')) {
path = '/' + path;
}
return path;
}
return url.pathname + url.search;
}
} catch (e) {
// Ignore
}
if (r.includes('#/')) {
r = r.substring(r.indexOf('#/') + 1);
}
if (/^[a-zA-Z0-9]+:/.test(r)) {
return '/';
}
if (!r.startsWith('/')) {
r = '/' + r;
}
return r;
}
}
@@ -0,0 +1,161 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Injectable, inject, OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';
import { AuthenticationService } from '../authentication/authentication.service';
import { KeyboardShortcutService } from './keyboard-shortcut.service';
import { UserPreferenceService } from './user-preference.service';
import { KeyboardShortcutsDialogComponent } from '../../shared/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.component';
import { filter, take } from 'rxjs/operators';
import { Subscription } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ShortcutSuggestionService implements OnDestroy {
private router = inject(Router);
private titleService = inject(Title);
private snackBar = inject(MatSnackBar);
private dialog = inject(MatDialog);
private authenticationService = inject(AuthenticationService);
private keyboardShortcutService = inject(KeyboardShortcutService);
private userPreferenceService = inject(UserPreferenceService);
private readonly FREQUENCY_THRESHOLD = 5;
private readonly PREF_KEY = 'shortcut_suggestions_state';
private routerSubscription!: Subscription;
private state: { dismissed: string[] } = { dismissed: [] };
private get userId(): number | null {
const creds = this.authenticationService.getCredentials();
return creds ? creds.userId : null;
}
private getVisitsKey(): string {
return `route_visits_${this.userId}`;
}
private getVisits(): Record<string, number> {
const key = this.getVisitsKey();
if (!key) return {};
const val = localStorage.getItem(key);
return val ? JSON.parse(val) : {};
}
private saveVisits(visits: Record<string, number>) {
const key = this.getVisitsKey();
if (key) {
localStorage.setItem(key, JSON.stringify(visits));
}
}
private isSuggestionOpen = false;
public init() {
const uid = this.userId;
if (uid) {
this.userPreferenceService.getPreference(uid, this.PREF_KEY).subscribe({
next: (data) => {
if (data && data.value) {
try {
this.state = JSON.parse(data.value);
if (!this.state.dismissed) this.state.dismissed = [];
} catch (e) {
this.state = { dismissed: [] };
}
}
},
error: () => {}
});
}
this.routerSubscription = this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe((event: any) => {
this.handleNavigation(event.urlAfterRedirects);
});
}
private handleNavigation(url: string) {
if (!this.userId) return;
let path = url.split('?')[0];
path = this.keyboardShortcutService.normalizeRouteStr(path);
const visits = this.getVisits();
visits[path] = (visits[path] || 0) + 1;
this.saveVisits(visits);
}
public getUsageData(): { route: string; pageName: string; visits: number; hasShortcut: boolean }[] {
const visits = this.getVisits();
const result: { route: string; pageName: string; visits: number; hasShortcut: boolean }[] = [];
// Get current shortcuts (sync)
let currentShortcuts: any[] = [];
this.keyboardShortcutService.activeShortcuts$.pipe(take(1)).subscribe((s) => (currentShortcuts = s));
for (const route of Object.keys(visits)) {
const count = visits[route];
const hasShortcut = currentShortcuts.some(
(s) =>
(s.custom && s.action === 'navigate' && this.keyboardShortcutService.normalizeRouteStr(s.route) === route) ||
(!s.custom && this.keyboardShortcutService.normalizeRouteStr(s.route) === route)
);
let pageName = route.split('/').pop() || route;
// Capitalize and clean
pageName = pageName.replace(/-/g, ' ');
pageName = pageName.charAt(0).toUpperCase() + pageName.slice(1);
result.push({ route, pageName, visits: count, hasShortcut });
}
return result.sort((a, b) => b.visits - a.visits);
}
public markAsDismissed(route: string) {
if (!this.state.dismissed.includes(route)) {
this.state.dismissed.push(route);
const uid = this.userId;
if (uid) {
this.userPreferenceService.updatePreference(uid, this.PREF_KEY, JSON.stringify(this.state)).subscribe();
}
}
}
public openCreateShortcutDialog(pageName: string, route: string) {
this.dialog
.open(KeyboardShortcutsDialogComponent, {
data: {
prefill: {
title: pageName,
route: route,
action: 'navigate'
}
}
})
.afterClosed()
.subscribe((saved) => {
if (saved) {
this.markAsDismissed(route);
}
});
}
ngOnDestroy() {
if (this.routerSubscription) {
this.routerSubscription.unsubscribe();
}
}
}
@@ -0,0 +1,28 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserPreferenceService {
private http = inject(HttpClient);
getPreference(userId: number, preferenceName: string): Observable<{ name: string; value: string }> {
const timestamp = new Date().getTime();
return this.http.get<{ name: string; value: string }>(
`/users/${userId}/preferences/${preferenceName}?_t=${timestamp}`
);
}
updatePreference(userId: number, preferenceName: string, value: string): Observable<{ name: string; value: string }> {
return this.http.put<{ name: string; value: string }>(`/users/${userId}/preferences/${preferenceName}`, { value });
}
}
+20 -19
View File
@@ -31,7 +31,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'n', key: 'n',
route: 'navigation' route: 'navigation',
id: 'navigation_page'
}, },
// Run Report - ctrl + t // Run Report - ctrl + t
{ {
@@ -50,17 +51,9 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'i', key: 'i',
route: 'checker-inbox-and-tasks/checker-inbox' route: 'checker-inbox-and-tasks/checker-inbox',
id: 'checker_inbox'
}, },
// Collection Sheet- ctrl + alt + o
// {
// title: 'Collection Sheet',
// ctrlKey: true,
// shiftKey: false,
// altKey: true,
// key: 'o',
// route: ''
// },
// Create Client - ctrl + c // Create Client - ctrl + c
{ {
title: 'Create Client', title: 'Create Client',
@@ -68,7 +61,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: true, altKey: true,
key: 'c', key: 'c',
route: 'clients/create' route: 'clients/create',
id: 'create_client'
}, },
// Create Group - ctrl + g // Create Group - ctrl + g
{ {
@@ -77,7 +71,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'g', key: 'g',
route: 'groups/create' route: 'groups/create',
id: 'create_group'
}, },
// Create Center - ctrl + q // Create Center - ctrl + q
{ {
@@ -86,7 +81,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'q', key: 'q',
route: 'centers/create' route: 'centers/create',
id: 'create_center'
}, },
// Frequent Posting - ctrl + f // Frequent Posting - ctrl + f
{ {
@@ -95,7 +91,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'f', key: 'f',
route: 'accounting/journal-entries/frequent-postings' route: 'accounting/journal-entries/frequent-postings',
id: 'frequent_posting'
}, },
// Closure Entries - ctrl + e // Closure Entries - ctrl + e
{ {
@@ -104,7 +101,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'e', key: 'e',
route: 'accounting/closing-entries' route: 'accounting/closing-entries',
id: 'closure_entries'
}, },
// Journal Entry - ctrl + j // Journal Entry - ctrl + j
{ {
@@ -113,7 +111,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'j', key: 'j',
route: 'accounting/journal-entries/create' route: 'accounting/journal-entries/create',
id: 'journal_entry'
}, },
// Reports - ctrl + r // Reports - ctrl + r
{ {
@@ -122,7 +121,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: false, altKey: false,
key: 'r', key: 'r',
route: 'reports' route: 'reports',
id: 'reports_page'
}, },
// Accounting - ctrl + a // Accounting - ctrl + a
{ {
@@ -131,7 +131,8 @@ export class KeyboardShortcutsConfiguration {
shiftKey: false, shiftKey: false,
altKey: true, altKey: true,
key: 'a', key: 'a',
route: 'accounting' route: 'accounting',
id: 'accounting_page'
}, },
// Save/Submit Forms - ctrl + s // Save/Submit Forms - ctrl + s
{ {
@@ -20,6 +20,7 @@ import { Router, ActivatedRoute, RouterLink } from '@angular/router';
/** Custom Services */ /** Custom Services */
import { ProductsService } from '../../products.service'; import { ProductsService } from '../../products.service';
import { SettingsService } from 'app/settings/settings.service'; import { SettingsService } from 'app/settings/settings.service';
import { AlertService } from 'app/core/alert/alert.service';
import { Dates } from 'app/core/utils/dates'; import { Dates } from 'app/core/utils/dates';
import { minNumberValueValidator } from 'app/shared/validators/min-number-value.validator'; import { minNumberValueValidator } from 'app/shared/validators/min-number-value.validator';
import { maxNumberValueValidator } from 'app/shared/validators/max-number-value.validator'; import { maxNumberValueValidator } from 'app/shared/validators/max-number-value.validator';
@@ -45,6 +46,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CreateChargeComponent implements OnInit { export class CreateChargeComponent implements OnInit {
private formBuilder = inject(UntypedFormBuilder); private formBuilder = inject(UntypedFormBuilder);
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private router = inject(Router); private router = inject(Router);
private dateUtils = inject(Dates); private dateUtils = inject(Dates);
@@ -352,8 +354,16 @@ export class CreateChargeComponent implements OnInit {
if (!data.maxCap) { if (!data.maxCap) {
delete data.maxCap; delete data.maxCap;
} }
this.productsService.createCharge(data).subscribe((response: any) => { this.productsService.createCharge(data).subscribe({
next: (response: any) => {
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Charge submitted successfully for approval.'
});
}
this.router.navigate(['../'], { relativeTo: this.route }); this.router.navigate(['../'], { relativeTo: this.route });
}
}); });
} }
} }
@@ -14,6 +14,7 @@ import { ActivatedRoute, Router, RouterLink } from '@angular/router';
/** Custom Services */ /** Custom Services */
import { ProductsService } from 'app/products/products.service'; import { ProductsService } from 'app/products/products.service';
import { SettingsService } from 'app/settings/settings.service'; import { SettingsService } from 'app/settings/settings.service';
import { AlertService } from 'app/core/alert/alert.service';
import { maxNumberValueValidator } from 'app/shared/validators/max-number-value.validator'; import { maxNumberValueValidator } from 'app/shared/validators/max-number-value.validator';
import { minNumberValueValidator } from 'app/shared/validators/min-number-value.validator'; import { minNumberValueValidator } from 'app/shared/validators/min-number-value.validator';
import { ValidateOnFocusDirective } from '../../../directives/validate-on-focus.directive'; import { ValidateOnFocusDirective } from '../../../directives/validate-on-focus.directive';
@@ -37,6 +38,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
}) })
export class EditChargeComponent implements OnInit { export class EditChargeComponent implements OnInit {
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private formBuilder = inject(UntypedFormBuilder); private formBuilder = inject(UntypedFormBuilder);
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private router = inject(Router); private router = inject(Router);
@@ -222,8 +224,16 @@ export class EditChargeComponent implements OnInit {
if (!charges.maxCap) { if (!charges.maxCap) {
delete charges.maxCap; delete charges.maxCap;
} }
this.productsService.updateCharge(this.chargeData.id.toString(), charges).subscribe((response: any) => { this.productsService.updateCharge(this.chargeData.id.toString(), charges).subscribe({
next: (response: any) => {
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Charge update submitted successfully for approval.'
});
}
this.router.navigate(['../'], { relativeTo: this.route }); this.router.navigate(['../'], { relativeTo: this.route });
}
}); });
} }
} }
@@ -18,6 +18,7 @@ import { CurrentProductAccountingStepComponent } from '../current-product-steppe
import { CurrentProductPreviewStepComponent } from '../current-product-stepper/current-product-preview-step/current-product-preview-step.component'; import { CurrentProductPreviewStepComponent } from '../current-product-stepper/current-product-preview-step/current-product-preview-step.component';
import { ProductsService } from 'app/products/products.service'; import { ProductsService } from 'app/products/products.service';
import { SettingsService } from 'app/settings/settings.service'; import { SettingsService } from 'app/settings/settings.service';
import { AlertService } from 'app/core/alert/alert.service';
import { Accounting } from 'app/core/utils/accounting'; import { Accounting } from 'app/core/utils/accounting';
import { MatTabsModule } from '@angular/material/tabs'; import { MatTabsModule } from '@angular/material/tabs';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
@@ -42,6 +43,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CreateCurrentProductComponent { export class CreateCurrentProductComponent {
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private router = inject(Router); private router = inject(Router);
private settingsService = inject(SettingsService); private settingsService = inject(SettingsService);
private accounting = inject(Accounting); private accounting = inject(Accounting);
@@ -144,7 +146,15 @@ export class CreateCurrentProductComponent {
submit() { submit() {
const currentProduct = this.prepareCurrentProductPayload(); const currentProduct = this.prepareCurrentProductPayload();
console.log('Current product submit payload:', currentProduct); console.log('Current product submit payload:', currentProduct);
this.productsService.createCurrentProduct(currentProduct).subscribe((response: any) => { this.productsService.createCurrentProduct(currentProduct).subscribe({
next: (response: any) => {
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Current product creation request submitted successfully for approval.'
});
this.router.navigate(['../'], { relativeTo: this.route });
} else {
this.router.navigate( this.router.navigate(
[ [
'../', '../',
@@ -152,6 +162,8 @@ export class CreateCurrentProductComponent {
], ],
{ relativeTo: this.route } { relativeTo: this.route }
); );
}
}
}); });
} }
} }
@@ -35,7 +35,7 @@
<p class="empty-text">No slabs defined. Click "Add Slab" to begin.</p> <p class="empty-text">No slabs defined. Click "Add Slab" to begin.</p>
} @else { } @else {
<form [formGroup]="forms[fdType]"> <form [formGroup]="forms[fdType]">
<table mat-table [dataSource]="slabs(fdType).controls" class="slabs-table"> <table mat-table [dataSource]="slabsDataSources[fdType]" class="slabs-table">
<ng-container matColumnDef="srNo"> <ng-container matColumnDef="srNo">
<th mat-header-cell *matHeaderCellDef>#</th> <th mat-header-cell *matHeaderCellDef>#</th>
<td mat-cell *matCellDef="let row">{{ row.get('srNo').value }}</td> <td mat-cell *matCellDef="let row">{{ row.get('srNo').value }}</td>
@@ -139,12 +139,25 @@
</mat-form-field> </mat-form-field>
</form> </form>
@if (getSlabValidationErrors(fdType).length > 0) {
<div class="validation-errors-box">
<mat-icon color="warn">error_outline</mat-icon>
<div class="error-list">
@for (err of getSlabValidationErrors(fdType); track err) {
<p class="error-item">{{ err }}</p>
}
</div>
</div>
}
<div class="actions-row"> <div class="actions-row">
<button <button
type="button" type="button"
mat-raised-button mat-raised-button
color="primary" color="primary"
[disabled]="forms[fdType].invalid || slabs(fdType).length === 0" [disabled]="
forms[fdType].invalid || slabs(fdType).length === 0 || getSlabValidationErrors(fdType).length > 0
"
(click)="openPreview(fdType)" (click)="openPreview(fdType)"
> >
Preview & Save Preview & Save
@@ -78,6 +78,30 @@
min-width: 200px; min-width: 200px;
} }
/* ── Validation Errors ── */
.validation-errors-box {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.75rem 1rem;
background: #fef2f2;
border: 1px solid #fecaca;
border-radius: 6px;
color: #b91c1c;
font-size: 0.875rem;
margin-bottom: 0.5rem;
.error-list {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.error-item {
margin: 0;
}
}
/* ── Actions ── */ /* ── Actions ── */
.actions-row { .actions-row {
display: flex; display: flex;
@@ -7,13 +7,14 @@
*/ */
import { Component, OnInit, inject } from '@angular/core'; import { Component, OnInit, inject } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { MatTabsModule } from '@angular/material/tabs'; import { MatTabsModule } from '@angular/material/tabs';
import { MatIconButton } from '@angular/material/button'; import { MatIconButton } from '@angular/material/button';
import { MatExpansionModule } from '@angular/material/expansion'; import { MatExpansionModule } from '@angular/material/expansion';
import { import {
MatTable, MatTable,
MatTableDataSource,
MatColumnDef, MatColumnDef,
MatHeaderCellDef, MatHeaderCellDef,
MatHeaderCell, MatHeaderCell,
@@ -26,6 +27,7 @@ import {
} from '@angular/material/table'; } from '@angular/material/table';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { ProductsService } from 'app/products/products.service'; import { ProductsService } from 'app/products/products.service';
import { AlertService } from 'app/core/alert/alert.service';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
@Component({ @Component({
@@ -54,6 +56,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class BaseFdInterestRateChartComponent implements OnInit { export class BaseFdInterestRateChartComponent implements OnInit {
private fb = inject(FormBuilder); private fb = inject(FormBuilder);
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
readonly fdTypes = [ readonly fdTypes = [
'SINGLE', 'SINGLE',
@@ -87,6 +90,7 @@ export class BaseFdInterestRateChartComponent implements OnInit {
]; ];
forms: Record<string, FormGroup> = {}; forms: Record<string, FormGroup> = {};
slabsDataSources: Record<string, MatTableDataSource<AbstractControl>> = {};
activeRates: Record<string, any> = {}; activeRates: Record<string, any> = {};
historyRates: any[] = []; historyRates: any[] = [];
@@ -98,6 +102,7 @@ export class BaseFdInterestRateChartComponent implements OnInit {
ngOnInit(): void { ngOnInit(): void {
this.fdTypes.forEach((type) => { this.fdTypes.forEach((type) => {
this.forms[type] = this.buildForm(); this.forms[type] = this.buildForm();
this.slabsDataSources[type] = new MatTableDataSource<AbstractControl>([]);
this.isSaving[type] = false; this.isSaving[type] = false;
this.saveMessage[type] = ''; this.saveMessage[type] = '';
this.showPreview[type] = false; this.showPreview[type] = false;
@@ -111,15 +116,140 @@ export class BaseFdInterestRateChartComponent implements OnInit {
addSlab(fdType: string): void { addSlab(fdType: string): void {
const arr = this.slabs(fdType); const arr = this.slabs(fdType);
arr.push(this.buildSlabRow({ srNo: arr.length + 1 })); let nextFrom = 1;
let periodType = this.getDefaultPeriodType(fdType);
if (arr.length > 0) {
const lastSlab = arr.at(arr.length - 1).value;
periodType = lastSlab.periodTypeEnum ?? periodType;
if (lastSlab.toPeriod != null && lastSlab.toPeriod >= 0) {
nextFrom = Number(lastSlab.toPeriod) + 1;
} else if (lastSlab.fromPeriod != null && lastSlab.fromPeriod >= 0) {
nextFrom = Number(lastSlab.fromPeriod) + 1;
}
}
const desc = this.generateSlabDescription(nextFrom, null, periodType);
arr.push(
this.buildSlabRow({
srNo: arr.length + 1,
description: desc,
periodTypeEnum: periodType,
fromPeriod: nextFrom,
toPeriod: null,
annualInterestRate: 0,
seniorCitizenRate: 0
})
);
this.slabsDataSources[fdType].data = [...arr.controls];
} }
removeSlab(fdType: string, index: number): void { removeSlab(fdType: string, index: number): void {
this.slabs(fdType).removeAt(index); this.slabs(fdType).removeAt(index);
this.slabs(fdType).controls.forEach((c, i) => c.patchValue({ srNo: i + 1 })); this.slabs(fdType).controls.forEach((c, i) => c.patchValue({ srNo: i + 1 }));
this.slabsDataSources[fdType].data = [...this.slabs(fdType).controls];
}
getDefaultPeriodType(fdType: string): number {
switch (fdType) {
case 'SINGLE':
return 0; // Days
case 'DOUBLE':
return 3; // Years
case 'SPECIAL':
return 2; // Months
default:
return 0;
}
}
generateSlabDescription(from: number, to: number | null, periodTypeEnum: number): string {
const unit = this.getPeriodLabel(periodTypeEnum);
if (to == null) {
return `${from}+ ${unit}`;
}
return `${from} to ${to} ${unit}`;
}
getSlabValidationErrors(fdType: string): string[] {
const errors: string[] = [];
const arr = this.slabs(fdType);
if (!arr || arr.length === 0) {
return errors;
}
const slabs = arr.controls.map((c) => c.value);
const expectedPeriodType = slabs[0].periodTypeEnum;
let expectedFrom = 1;
for (let i = 0; i < slabs.length; i++) {
const s = slabs[i];
const slabNum = i + 1;
if (s.periodTypeEnum !== expectedPeriodType) {
errors.push(`Slab #${slabNum}: Period type must be consistent across all slabs.`);
}
if (s.fromPeriod == null || s.fromPeriod < 0) {
errors.push(`Slab #${slabNum}: 'From' period must be a non-negative number.`);
} else if (s.fromPeriod !== expectedFrom) {
if (i === 0) {
errors.push(`Slab #${slabNum}: First slab must start from 1 (found: ${s.fromPeriod}).`);
} else if (s.fromPeriod < expectedFrom) {
errors.push(
`Slab #${slabNum}: Range overlaps with previous slab (expected start: ${expectedFrom}, found: ${s.fromPeriod}).`
);
} else {
errors.push(
`Slab #${slabNum}: Gap detected in range (expected start: ${expectedFrom}, found: ${s.fromPeriod}).`
);
}
}
if (i < slabs.length - 1) {
// Non-final slab
if (s.toPeriod == null) {
errors.push(`Slab #${slabNum}: 'To' period is required for non-final slabs.`);
} else {
if (s.toPeriod < 0) {
errors.push(`Slab #${slabNum}: 'To' period must be non-negative.`);
}
if (s.fromPeriod != null && s.toPeriod < s.fromPeriod) {
errors.push(
`Slab #${slabNum}: 'From' period (${s.fromPeriod}) cannot be greater than 'To' period (${s.toPeriod}).`
);
}
expectedFrom = Number(s.toPeriod) + 1;
}
} else {
// Final slab
if (s.toPeriod != null) {
if (s.toPeriod < 0) {
errors.push(`Slab #${slabNum}: 'To' period must be non-negative.`);
}
if (s.fromPeriod != null && s.toPeriod < s.fromPeriod) {
errors.push(
`Slab #${slabNum}: 'From' period (${s.fromPeriod}) cannot be greater than 'To' period (${s.toPeriod}).`
);
}
}
}
if (s.annualInterestRate == null || s.annualInterestRate < 0) {
errors.push(`Slab #${slabNum}: Annual Interest Rate cannot be negative.`);
}
if (s.seniorCitizenRate != null && s.seniorCitizenRate < 0) {
errors.push(`Slab #${slabNum}: Senior Citizen Rate cannot be negative.`);
}
}
return errors;
} }
openPreview(fdType: string): void { openPreview(fdType: string): void {
if (this.getSlabValidationErrors(fdType).length > 0) {
return;
}
this.showPreview[fdType] = true; this.showPreview[fdType] = true;
this.saveMessage[fdType] = ''; this.saveMessage[fdType] = '';
} }
@@ -129,13 +259,24 @@ export class BaseFdInterestRateChartComponent implements OnInit {
} }
confirmSave(fdType: string): void { confirmSave(fdType: string): void {
if (this.isSaving[fdType]) {
return;
}
this.isSaving[fdType] = true; this.isSaving[fdType] = true;
const { versionLabel, remarks, slabs } = this.forms[fdType].value; const { versionLabel, remarks, slabs } = this.forms[fdType].value;
this.productsService.saveFdBaseInterestRates({ fdType, versionLabel, remarks, slabs }).subscribe({ this.productsService.saveFdBaseInterestRates({ fdType, versionLabel, remarks, slabs }).subscribe({
next: () => { next: (response: any) => {
this.saveMessage[fdType] = 'New version activated. Previous version deactivated.';
this.showPreview[fdType] = false;
this.isSaving[fdType] = false; this.isSaving[fdType] = false;
this.showPreview[fdType] = false;
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Base interest rate configuration submitted successfully for approval.'
});
this.saveMessage[fdType] = 'Base interest rate configuration submitted successfully for approval.';
} else {
this.saveMessage[fdType] = 'New version activated. Previous version deactivated.';
}
this.loadAll(); this.loadAll();
}, },
error: () => { error: () => {
@@ -171,6 +312,7 @@ export class BaseFdInterestRateChartComponent implements OnInit {
const arr = this.slabs(type); const arr = this.slabs(type);
arr.clear(); arr.clear();
(active?.slabs ?? []).forEach((s: any) => arr.push(this.buildSlabRow(s))); (active?.slabs ?? []).forEach((s: any) => arr.push(this.buildSlabRow(s)));
this.slabsDataSources[type].data = [...arr.controls];
this.forms[type].patchValue({ versionLabel: '', remarks: '' }); this.forms[type].patchValue({ versionLabel: '', remarks: '' });
}, },
error: () => { error: () => {
@@ -21,6 +21,7 @@ import { LoanProductInterestRefundStepComponent } from '../loan-product-stepper/
/** Custom Services */ /** Custom Services */
import { ProductsService } from 'app/products/products.service'; import { ProductsService } from 'app/products/products.service';
import { AlertService } from 'app/core/alert/alert.service';
import { LoanProducts } from '../loan-products'; import { LoanProducts } from '../loan-products';
import { import {
AdvancedPaymentAllocation, AdvancedPaymentAllocation,
@@ -63,6 +64,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CreateLoanProductComponent implements OnInit { export class CreateLoanProductComponent implements OnInit {
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private loanProducts = inject(LoanProducts); private loanProducts = inject(LoanProducts);
private router = inject(Router); private router = inject(Router);
private accounting = inject(Accounting); private accounting = inject(Accounting);
@@ -313,7 +315,15 @@ export class CreateLoanProductComponent implements OnInit {
delete loanProduct['daysInYearCustomStrategy']; delete loanProduct['daysInYearCustomStrategy'];
} }
this.productsService.createLoanProduct(loanProduct).subscribe((response: any) => { this.productsService.createLoanProduct(loanProduct).subscribe({
next: (response: any) => {
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Loan product creation request submitted successfully for approval.'
});
this.router.navigate(['../'], { relativeTo: this.route });
} else {
this.router.navigate( this.router.navigate(
[ [
'../', '../',
@@ -321,6 +331,8 @@ export class CreateLoanProductComponent implements OnInit {
], ],
{ relativeTo: this.route } { relativeTo: this.route }
); );
}
}
}); });
} }
@@ -1,4 +1,4 @@
/** /**
* Copyright since 2025 Mifos Initiative * Copyright since 2025 Mifos Initiative
* *
* This Source Code Form is subject to the terms of the Mozilla Public * This Source Code Form is subject to the terms of the Mozilla Public
@@ -22,6 +22,7 @@ import { SavingProductAccountingStepComponent } from '../saving-product-stepper/
/** Custom Services */ /** Custom Services */
import { ProductsService } from 'app/products/products.service'; import { ProductsService } from 'app/products/products.service';
import { SettingsService } from 'app/settings/settings.service'; import { SettingsService } from 'app/settings/settings.service';
import { AlertService } from 'app/core/alert/alert.service';
import { Accounting } from 'app/core/utils/accounting'; import { Accounting } from 'app/core/utils/accounting';
import { SavingProductPreviewStepComponent } from '../saving-product-stepper/saving-product-preview-step/saving-product-preview-step.component'; import { SavingProductPreviewStepComponent } from '../saving-product-stepper/saving-product-preview-step/saving-product-preview-step.component';
import { MatTabsModule } from '@angular/material/tabs'; import { MatTabsModule } from '@angular/material/tabs';
@@ -47,6 +48,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CreateSavingProductComponent { export class CreateSavingProductComponent {
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private router = inject(Router); private router = inject(Router);
private settingsService = inject(SettingsService); private settingsService = inject(SettingsService);
private accounting = inject(Accounting); private accounting = inject(Accounting);
@@ -162,7 +164,15 @@ export class CreateSavingProductComponent {
submit() { submit() {
const savingProduct = this.prepareSavingProductPayload(); const savingProduct = this.prepareSavingProductPayload();
console.log('Saving product submit payload:', savingProduct); console.log('Saving product submit payload:', savingProduct);
this.productsService.createSavingProduct(savingProduct).subscribe((response: any) => { this.productsService.createSavingProduct(savingProduct).subscribe({
next: (response: any) => {
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Savings product creation request submitted successfully for approval.'
});
this.router.navigate(['../'], { relativeTo: this.route });
} else {
this.router.navigate( this.router.navigate(
[ [
'../', '../',
@@ -170,6 +180,8 @@ export class CreateSavingProductComponent {
], ],
{ relativeTo: this.route } { relativeTo: this.route }
); );
}
}
}); });
} }
} }
@@ -22,6 +22,7 @@ import { ShareProductAccountingStepComponent } from '../share-product-stepper/sh
/** Custom Services */ /** Custom Services */
import { ProductsService } from 'app/products/products.service'; import { ProductsService } from 'app/products/products.service';
import { SettingsService } from 'app/settings/settings.service'; import { SettingsService } from 'app/settings/settings.service';
import { AlertService } from 'app/core/alert/alert.service';
import { Accounting } from 'app/core/utils/accounting'; import { Accounting } from 'app/core/utils/accounting';
import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { ShareProductPreviewStepComponent } from '../share-product-stepper/share-product-preview-step/share-product-preview-step.component'; import { ShareProductPreviewStepComponent } from '../share-product-stepper/share-product-preview-step/share-product-preview-step.component';
@@ -49,6 +50,7 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CreateShareProductComponent { export class CreateShareProductComponent {
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private productsService = inject(ProductsService); private productsService = inject(ProductsService);
private alertService = inject(AlertService);
private router = inject(Router); private router = inject(Router);
private settingsService = inject(SettingsService); private settingsService = inject(SettingsService);
private accounting = inject(Accounting); private accounting = inject(Accounting);
@@ -143,7 +145,15 @@ export class CreateShareProductComponent {
chargesSelected: this.shareProduct.chargesSelected.map((charge: any) => ({ id: charge.id })), chargesSelected: this.shareProduct.chargesSelected.map((charge: any) => ({ id: charge.id })),
locale: this.settingsService.language.code // locale required for digitsAfterDecimal locale: this.settingsService.language.code // locale required for digitsAfterDecimal
}; };
this.productsService.createShareProduct(shareProduct).subscribe((response: any) => { this.productsService.createShareProduct(shareProduct).subscribe({
next: (response: any) => {
if (response?.rollbackTransaction) {
this.alertService.alert({
type: 'Success',
message: 'Share product creation request submitted successfully for approval.'
});
this.router.navigate(['../'], { relativeTo: this.route });
} else {
this.router.navigate( this.router.navigate(
[ [
'../', '../',
@@ -151,6 +161,8 @@ export class CreateShareProductComponent {
], ],
{ relativeTo: this.route } { relativeTo: this.route }
); );
}
}
}); });
} }
} }
+4
View File
@@ -7,6 +7,10 @@
--> -->
<div class="container m-b-10 layout-row layout-lt-md-column align-end gap-1percent"> <div class="container m-b-10 layout-row layout-lt-md-column align-end gap-1percent">
<button mat-raised-button color="primary" class="m-r-10" (click)="configureShortcuts()">
<fa-icon icon="keyboard" class="m-r-10"></fa-icon>
{{ 'labels.buttons.Configure Shortcuts' | translate }}
</button>
<button mat-raised-button color="primary" class="m-r-10" [routerLink]="['/system', 'roles-and-permissions']"> <button mat-raised-button color="primary" class="m-r-10" [routerLink]="['/system', 'roles-and-permissions']">
<fa-icon icon="check" class="m-r-10"></fa-icon> <fa-icon icon="check" class="m-r-10"></fa-icon>
{{ 'labels.buttons.Permissions' | translate }} {{ 'labels.buttons.Permissions' | translate }}
+8 -1
View File
@@ -28,6 +28,7 @@ import { Router, RouterLink } from '@angular/router';
import { AuthenticationService } from 'app/core/authentication/authentication.service'; import { AuthenticationService } from 'app/core/authentication/authentication.service';
import { ChangePasswordDialogComponent } from 'app/shared/change-password-dialog/change-password-dialog.component'; import { ChangePasswordDialogComponent } from 'app/shared/change-password-dialog/change-password-dialog.component';
import { SettingsService } from 'app/settings/settings.service'; import { SettingsService } from 'app/settings/settings.service';
import { KeyboardShortcutsDialogComponent } from 'app/shared/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.component';
import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
@@ -108,7 +109,13 @@ export class ProfileComponent implements OnInit {
}); });
} }
get tenantIdentifier(): string { get tenantIdentifier() {
return this.settingsService.tenantIdentifier || 'default'; return this.settingsService.tenantIdentifier || 'default';
} }
configureShortcuts() {
this.dialog.open(KeyboardShortcutsDialogComponent, {
width: '800px'
});
}
} }
+1 -1
View File
@@ -9,7 +9,7 @@
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { environment } from 'environments/environment'; import { environment } from '../../environments/environment';
export interface OpenProjectWorkPackage { export interface OpenProjectWorkPackage {
id: number; id: number;
@@ -6,37 +6,205 @@
file, You can obtain one at http://mozilla.org/MPL/2.0/. file, You can obtain one at http://mozilla.org/MPL/2.0/.
--> -->
<h1 mat-dialog-title>{{ 'labels.heading.Keyboard Shortcuts' | translate }}</h1> <div class="ks-header">
<h1 mat-dialog-title class="ks-title">{{ 'labels.heading.Configure Keyboard Shortcuts' | translate }}</h1>
<button mat-icon-button (click)="openUsagePopup()" matTooltip="Shortcut Usage">
<mat-icon>analytics</mat-icon>
</button>
</div>
<div mat-dialog-content> <div mat-dialog-content>
<div class="layout-column gap-2px"> @if (validationError) {
@for (item of buttonConfig.buttonCombinations; track item) { <div class="alert error margin-b-10">
<mat-divider [inset]="true"></mat-divider> {{ validationError }}
<div class="flex-fill flex-50"> </div>
<span class="flex-50">
@if (item.ctrlKey) {
<span>
<span class="modifier-key">{{ 'labels.inputs.Ctrl' | translate }}</span> +
</span>
} }
@if (item.shiftKey) {
<span> <table class="ks-table">
<span class="modifier-key">{{ 'labels.inputs.Shift' | translate }}</span> + <thead>
</span> <tr>
<th>{{ 'labels.inputs.Shortcut Name' | translate }}</th>
<th>{{ 'Key Combination' }}</th>
</tr>
</thead>
<tbody>
@for (item of shortcuts; track item) {
<tr style="cursor: pointer" (click)="showShortcutDetails(item)">
<td [attr.colspan]="editingShortcutId === item.id || (!item.id && editingShortcutId === item.title) ? 2 : 1">
@if (editingShortcutId === item.id || (!item.id && editingShortcutId === item.title)) {
<!-- Edit Mode -->
<div class="layout-row-wrap layout-lt-md-column gap-2percent padding-y-10">
<h4 class="flex-100 margin-0 margin-b-10">Edit Shortcut</h4>
<mat-form-field class="ks-field flex-48">
<mat-label>Shortcut Name</mat-label>
<input matInput [(ngModel)]="editingShortcutData.title" [disabled]="!item.custom" />
</mat-form-field>
@if (item.custom || item.route) {
<mat-form-field class="ks-field flex-48">
<mat-label>URL / Route</mat-label>
<input matInput [(ngModel)]="editingShortcutData.route" [disabled]="!item.custom" />
</mat-form-field>
} }
@if (item.altKey) {
<span> @if (item.custom) {
<span class="modifier-key">{{ 'labels.inputs.Alt' | translate }}</span> + <mat-form-field class="ks-field flex-48">
</span> <mat-label>Action</mat-label>
<mat-select [(ngModel)]="editingShortcutData.action">
<mat-option value="navigate">Navigate</mat-option>
</mat-select>
</mat-form-field>
} }
@if (item.key) {
<span> <mat-form-field class="ks-field flex-48">
<span class="modifier-key">{{ item.key }}</span></span <mat-label>Key Combination</mat-label>
<input
matInput
readonly
[value]="formatShortcut(editingShortcutData)"
(keydown)="onKeyDown($event, editingShortcutData, true)"
placeholder="Press keys..."
/>
</mat-form-field>
<div class="flex-100 layout-row justify-content-end gap-10px">
<button mat-stroked-button class="ks-actions__cancel" (click)="cancelEditShortcut()">Cancel</button>
<button
mat-flat-button
class="ks-actions__confirm ks-actions__confirm--basic"
(click)="saveEditShortcut()"
> >
Save
</button>
</div>
</div>
} @else {
<!-- View Mode -->
<span style="text-transform: capitalize; padding: 8px 0; display: inline-block">{{ item.title }}</span>
} }
</span> </td>
<span class="flex-50">{{ item.title }}</span>
@if (!(editingShortcutId === item.id || (!item.id && editingShortcutId === item.title))) {
<td (click)="$event.stopPropagation()">
<mat-form-field class="ks-field" subscriptSizing="dynamic" style="width: 250px">
<input
matInput
readonly
[value]="formatShortcut(item)"
(keydown)="onKeyDown($event, item)"
(focus)="activeInputItem = item"
(blur)="activeInputItem = null"
placeholder="Click and press keys..."
matTooltip="Click here and press your desired key combination"
/>
</mat-form-field>
</td>
}
</tr>
}
</tbody>
</table>
@if (isAddingNew) {
<div
class="layout-row-wrap layout-lt-md-column gap-2percent padding-20 mat-elevation-z1 margin-t-10"
style="background-color: white; border-radius: 4px"
>
<h4 class="flex-100 margin-0 margin-b-10">Add Custom Shortcut</h4>
<mat-form-field class="ks-field flex-48">
<mat-label>Shortcut Name</mat-label>
<input matInput [(ngModel)]="newShortcut.title" placeholder="e.g. Share Holder" />
</mat-form-field>
<mat-form-field class="ks-field flex-48">
<mat-label>URL / Route</mat-label>
<input matInput [(ngModel)]="newShortcut.route" placeholder="e.g. /shares/share-holders" />
</mat-form-field>
<mat-form-field class="ks-field flex-48">
<mat-label>Action</mat-label>
<mat-select [(ngModel)]="newShortcut.action">
<mat-option value="navigate">Navigate</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="ks-field flex-48">
<mat-label>Key Combination</mat-label>
<input
matInput
readonly
[value]="formatShortcut(newShortcut)"
(keydown)="onKeyDown($event, newShortcut, true)"
placeholder="Press keys..."
/>
</mat-form-field>
<div class="flex-100 layout-row justify-content-end gap-10px">
<button mat-stroked-button class="ks-actions__cancel" (click)="cancelAddShortcut()">Cancel</button>
<button mat-flat-button class="ks-actions__confirm ks-actions__confirm--basic" (click)="saveNewShortcut()">
Save
</button>
</div>
</div>
} @else {
<div class="margin-t-10">
<button mat-button color="primary" (click)="startAddShortcut()"><mat-icon>add</mat-icon> Add Shortcut</button>
</div> </div>
} }
</div> </div>
<mat-dialog-actions class="ks-actions">
<button mat-flat-button class="ks-actions__confirm ks-actions__confirm--warn" (click)="resetToDefaults()">
Reset to Defaults
</button>
<div class="ks-actions__right">
<button mat-stroked-button class="ks-actions__cancel" (click)="cancel()">
{{ 'labels.button.cancel' | translate }}
</button>
<button
mat-flat-button
class="ks-actions__confirm ks-actions__confirm--basic"
(click)="save()"
[disabled]="validationError !== null"
>
{{ 'labels.button.save' | translate }}
</button>
</div> </div>
</mat-dialog-actions>
<ng-template #shortcutDetailsTemplate let-data>
<h2 mat-dialog-title style="text-transform: capitalize">{{ data.title }}</h2>
<div mat-dialog-content>
<div class="layout-column gap-10px padding-y-10" style="font-size: 14px">
<div>
<strong>Shortcut Name:</strong> <br />
<span style="text-transform: capitalize">{{ data.title }}</span>
</div>
<div>
<strong>Key Combination:</strong> <br />
{{ formatShortcut(data) }}
</div>
<div>
<strong>Action:</strong> <br />
{{ data.action === 'navigate' ? 'Navigate' : data.action || data.id || 'Predefined' }}
</div>
@if (data.route) {
<div>
<strong>URL / Route:</strong> <br />
{{ data.route }}
</div>
}
<div>
<strong>Description:</strong> <br />
{{ getShortcutDescription(data) }}
</div>
</div>
</div>
<mat-dialog-actions align="end">
<button mat-button color="primary" (click)="startEditShortcut(data)">Edit</button>
<button mat-button color="warn" (click)="deleteShortcut(data)">Delete</button>
<button mat-button mat-dialog-close>Close</button>
</mat-dialog-actions>
</ng-template>
@@ -6,15 +6,157 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/ */
.modifier-key { $primary: #1a73e8;
border: 1px solid #0000004d; $gray-50: #f8f9fa;
padding: 0.3rem; $gray-100: #f1f3f4;
background: #f8f8f8; $gray-200: #e8eaed;
color: #00000086; $gray-500: #9aa0a6;
font-weight: bold; $gray-700: #5f6368;
border-radius: 0.3rem; $gray-900: #202124;
} $red: #ef4444;
$navy: #0d1b2a;
$white: #fff;
.mat-divider.mat-divider-inset { .mat-divider.mat-divider-inset {
margin-left: 0; margin-left: 0;
} }
/* --- Header (from form-dialog) --- */
.ks-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 24px 12px;
border-bottom: 1px solid $gray-200;
}
.ks-title {
margin: 0 !important;
padding: 0 !important;
font-size: 17px !important;
font-weight: 600 !important;
color: $gray-900;
letter-spacing: -0.2px;
}
/* --- Table Rows (from bank-calendar) --- */
.ks-table {
width: 100%;
border-collapse: collapse;
font-size: 12.5px;
thead th {
position: sticky;
top: 0;
z-index: 1;
background: #f1f5f9;
color: #475569;
text-align: left;
padding: 10px 14px;
font-size: 10.5px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
border-bottom: 1px solid #e2e8f0;
}
tbody td {
padding: 9px 14px;
border-bottom: 1px solid #f1f5f9;
vertical-align: middle;
color: $navy;
}
tbody tr {
transition: background 0.12s;
&:hover {
background: #f8fafc;
}
}
}
/* --- Inputs/Forms (from form-dialog) --- */
.ks-field {
min-width: 0;
::ng-deep {
.mat-mdc-form-field {
width: 100%;
}
.mat-mdc-text-field-wrapper {
background: $gray-50;
border-radius: 8px;
}
.mdc-text-field--outlined .mdc-notched-outline__leading,
.mdc-text-field--outlined .mdc-notched-outline__trailing,
.mdc-text-field--outlined .mdc-notched-outline__notch {
border-color: $gray-200;
}
.mdc-text-field--outlined:not(.mdc-text-field--disabled):hover .mdc-notched-outline__leading,
.mdc-text-field--outlined:not(.mdc-text-field--disabled):hover .mdc-notched-outline__trailing,
.mdc-text-field--outlined:not(.mdc-text-field--disabled):hover .mdc-notched-outline__notch {
border-color: $primary;
}
.mat-mdc-floating-label {
font-size: 13px;
color: $gray-700;
}
input.mat-mdc-input-element {
font-size: 14px;
color: $gray-900;
}
}
}
/* --- Dialog Footer & Buttons (from confirmation-dialog) --- */
.ks-actions {
padding: 14px 24px 20px !important;
border-top: 1px solid $gray-200;
margin: 0 !important;
display: flex !important;
justify-content: space-between !important;
align-items: center !important;
gap: 10px !important;
.ks-actions__right {
display: flex;
gap: 10px;
align-items: center;
}
&__cancel {
border-radius: 8px !important;
font-size: 13px !important;
font-weight: 600 !important;
padding: 0 20px !important;
height: 38px !important;
color: $gray-700 !important;
border-color: $gray-200 !important;
}
&__confirm {
border-radius: 8px !important;
font-size: 13px !important;
font-weight: 600 !important;
padding: 0 24px !important;
height: 38px !important;
letter-spacing: 0.2px;
color: $white !important;
&--basic {
background: $primary !important;
box-shadow: 0 1px 3px rgb(26 115 232 / 30%) !important;
}
&--warn {
background: $red !important;
box-shadow: 0 1px 3px rgb(239 68 68 / 30%) !important;
}
}
}
@@ -6,16 +6,31 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/ */
/** Angular Imports */ import { Component, OnInit, inject, ViewChild } from '@angular/core';
import { Component, OnInit, inject } from '@angular/core'; import {
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogTitle, MatDialogContent } from '@angular/material/dialog'; MatDialogRef,
import { KeyboardShortcutsConfiguration } from '../../keyboards-shortcut-config'; MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialog,
MatDialogClose,
MAT_DIALOG_DATA
} from '@angular/material/dialog';
import { CdkScrollable } from '@angular/cdk/scrolling'; import { CdkScrollable } from '@angular/cdk/scrolling';
import { MatDivider } from '@angular/material/divider'; import { MatDivider } from '@angular/material/divider';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** import { KeyboardShortcutService, ShortcutItem } from '../../core/services/keyboard-shortcut.service';
* Delete dialog component. import { FormsModule } from '@angular/forms';
*/ import { NgClass } from '@angular/common';
import { MatButton } from '@angular/material/button';
import { ConfirmationDialogComponent } from '../confirmation-dialog/confirmation-dialog.component';
import { ShortcutUsageDialogComponent } from '../shortcut-usage-dialog/shortcut-usage-dialog.component';
import { MatIcon } from '@angular/material/icon';
import { MatFormField, MatLabel } from '@angular/material/form-field';
import { MatInput } from '@angular/material/input';
import { MatSelect } from '@angular/material/select';
import { MatOption } from '@angular/material/core';
@Component({ @Component({
selector: 'mifosx-keyboard-shortcuts-dialog', selector: 'mifosx-keyboard-shortcuts-dialog',
templateUrl: './keyboard-shortcuts-dialog.component.html', templateUrl: './keyboard-shortcuts-dialog.component.html',
@@ -25,16 +40,293 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
MatDialogTitle, MatDialogTitle,
CdkScrollable, CdkScrollable,
MatDialogContent, MatDialogContent,
MatDivider MatDialogActions,
MatDialogClose,
MatDivider,
MatButton,
FormsModule,
NgClass,
MatIcon,
MatFormField,
MatLabel,
MatInput,
MatSelect,
MatOption
] ]
}) })
export class KeyboardShortcutsDialogComponent implements OnInit { export class KeyboardShortcutsDialogComponent implements OnInit {
dialogRef = inject<MatDialogRef<KeyboardShortcutsDialogComponent>>(MatDialogRef); dialogRef = inject<MatDialogRef<KeyboardShortcutsDialogComponent>>(MatDialogRef);
private keyboardShortcutService = inject(KeyboardShortcutService);
public data = inject(MAT_DIALOG_DATA, { optional: true });
buttonConfig: KeyboardShortcutsConfiguration; shortcuts: ShortcutItem[] = [];
validationError: string | null = null;
activeInputItem: ShortcutItem | null = null;
displayedColumns: string[] = [
'title',
'keyCombination'
];
isAddingNew = false;
newShortcut: Partial<ShortcutItem> = {};
activeNewInput = false;
editingShortcutId: string | null = null;
editingShortcutData: Partial<ShortcutItem> = {};
activeEditInput = false;
ngOnInit() { ngOnInit() {
this.dialogRef.updateSize(`800px`); this.dialogRef.updateSize('800px');
this.buttonConfig = new KeyboardShortcutsConfiguration(); this.keyboardShortcutService.activeShortcuts$.subscribe((shortcuts) => {
// Deep copy to allow editing without affecting the global state immediately
this.shortcuts = JSON.parse(JSON.stringify(shortcuts));
});
if (this.data && this.data.prefill) {
this.startAddShortcut();
this.newShortcut = {
...this.newShortcut,
...this.data.prefill
};
}
}
formatShortcut(item: Partial<ShortcutItem>): string {
if (!item || (!item.key && !item.ctrlKey && !item.shiftKey && !item.altKey)) return '';
const parts = [];
if (item.ctrlKey) parts.push('Ctrl');
if (item.shiftKey) parts.push('Shift');
if (item.altKey) parts.push('Alt');
if (item.key) parts.push(item.key.toUpperCase());
return parts.join(' + ');
}
onKeyDown(event: KeyboardEvent, item: Partial<ShortcutItem>, isNewOrEdit: boolean = false) {
event.preventDefault();
event.stopPropagation();
// Ignore if only modifier keys are pressed
if ([
'Control',
'Shift',
'Alt',
'Meta'
].includes(event.key)) {
return;
}
item.ctrlKey = event.ctrlKey;
item.shiftKey = event.shiftKey;
item.altKey = event.altKey;
item.key = event.key.toLowerCase();
if (!isNewOrEdit) {
this.activeInputItem = null;
this.validateShortcuts();
} else {
this.activeNewInput = false;
this.activeEditInput = false;
}
}
validateShortcuts() {
this.validationError = null;
const seen = new Set<string>();
for (const item of this.shortcuts) {
if (!item.key) {
this.validationError = `Invalid shortcut for ${item.title}: Key is required`;
return;
}
const keyStr = `${!!item.ctrlKey}-${!!item.shiftKey}-${!!item.altKey}-${item.key.toLowerCase()}`;
if (seen.has(keyStr)) {
this.validationError = `Duplicate shortcut detected: ${this.formatShortcut(item)}`;
return;
}
seen.add(keyStr);
}
}
startAddShortcut() {
this.isAddingNew = true;
this.newShortcut = {
title: '',
route: '',
key: '',
ctrlKey: false,
shiftKey: false,
altKey: false,
action: 'navigate',
custom: true,
id: 'custom_' + Date.now()
};
this.validationError = null;
}
cancelAddShortcut() {
this.isAddingNew = false;
this.validationError = null;
}
private dialog = inject(MatDialog);
@ViewChild('shortcutDetailsTemplate') shortcutDetailsTemplate: any;
private detailsDialogRef: MatDialogRef<any> | null = null;
showShortcutDetails(item: ShortcutItem) {
this.detailsDialogRef = this.dialog.open(this.shortcutDetailsTemplate, {
data: item,
width: '400px'
});
}
openUsagePopup() {
this.dialog.open(ShortcutUsageDialogComponent, {
width: '600px'
});
}
getShortcutDescription(item: Partial<ShortcutItem>): string {
if (item.custom) {
if (item.action === 'navigate') {
return `Navigates to the ${item.title} page.`;
}
return `Executes the ${item.action} action.`;
} else {
switch (item.id) {
case 'logout':
return 'Logs you out of the application securely.';
case 'help':
return 'Opens the user manual and help documentation.';
case 'runReport':
return 'Executes the currently selected report.';
case 'cancel':
return 'Cancels the current operation or form.';
case 'submit':
return 'Submits the current form or dialog.';
default:
return `Navigates to the predefined ${item.title} feature.`;
}
}
}
saveNewShortcut() {
if (this.newShortcut.action === 'navigate' && this.newShortcut.route) {
this.newShortcut.route = this.keyboardShortcutService.normalizeRouteStr(this.newShortcut.route);
}
if (this.validateSingleShortcut(this.newShortcut, null)) {
this.shortcuts.push(this.newShortcut as ShortcutItem);
this.isAddingNew = false;
this.validateShortcuts();
if (!this.validationError) {
this.keyboardShortcutService.updateShortcuts(this.shortcuts);
}
}
}
startEditShortcut(item: ShortcutItem) {
if (this.detailsDialogRef) {
this.detailsDialogRef.close();
this.detailsDialogRef = null;
}
this.editingShortcutId = item.id || null;
this.editingShortcutData = { ...item };
this.validationError = null;
}
cancelEditShortcut() {
this.editingShortcutId = null;
this.validationError = null;
}
saveEditShortcut() {
if (this.editingShortcutData.action === 'navigate' && this.editingShortcutData.route) {
this.editingShortcutData.route = this.keyboardShortcutService.normalizeRouteStr(this.editingShortcutData.route);
}
if (this.validateSingleShortcut(this.editingShortcutData, this.editingShortcutId)) {
const index = this.shortcuts.findIndex((s) => s.id === this.editingShortcutId);
if (index > -1) {
this.shortcuts[index] = { ...this.editingShortcutData } as ShortcutItem;
}
this.editingShortcutId = null;
this.validateShortcuts();
if (!this.validationError) {
this.keyboardShortcutService.updateShortcuts(this.shortcuts);
}
}
}
deleteShortcut(item: ShortcutItem) {
if (this.detailsDialogRef) {
this.detailsDialogRef.close();
this.detailsDialogRef = null;
}
this.shortcuts = this.shortcuts.filter((s) => (s.id ? s.id !== item.id : s.title !== item.title));
this.validateShortcuts();
if (!this.validationError) {
this.keyboardShortcutService.updateShortcuts(this.shortcuts);
}
}
validateSingleShortcut(item: Partial<ShortcutItem>, excludeId: string | null): boolean {
if (!item.title || item.title.trim() === '') {
this.validationError = 'Shortcut Name is required';
return false;
}
if (!item.key) {
this.validationError = 'Key combination is required';
return false;
}
if (item.action === 'navigate' && (!item.route || item.route.trim() === '')) {
this.validationError = 'URL / Route is required';
return false;
}
const keyStr = `${!!item.ctrlKey}-${!!item.shiftKey}-${!!item.altKey}-${item.key.toLowerCase()}`;
const seen = new Set<string>();
for (const s of this.shortcuts) {
if (excludeId && s.id === excludeId) continue;
seen.add(`${!!s.ctrlKey}-${!!s.shiftKey}-${!!s.altKey}-${s.key.toLowerCase()}`);
}
if (seen.has(keyStr)) {
this.validationError = `Duplicate shortcut detected: ${this.formatShortcut(item)}`;
return false;
}
this.validationError = null;
return true;
}
save() {
this.validateShortcuts();
if (!this.validationError) {
this.keyboardShortcutService.updateShortcuts(this.shortcuts);
this.dialogRef.close(true);
}
}
resetToDefaults() {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
data: {
heading: 'Reset Keyboard Shortcuts',
dialogContext:
'Are you sure you want to reset all keyboard shortcuts to their default configuration? This will remove all custom shortcuts and restore default keys.',
type: 'Warn'
}
});
dialogRef.afterClosed().subscribe((confirm: boolean) => {
if (confirm) {
this.keyboardShortcutService.resetToDefaults();
this.dialogRef.close(true);
}
});
}
cancel() {
this.dialogRef.close(false);
} }
} }
@@ -0,0 +1,22 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="suggestion-container">
<div class="suggestion-text">
<strong
>💡 You frequently use <span style="text-transform: capitalize">{{ data.pageName }}</span></strong
><br />
Would you like to create a keyboard shortcut for faster access?
</div>
<div class="suggestion-actions margin-t-10" style="display: flex; justify-content: flex-end; gap: 8px">
<button mat-button style="color: #bbb" (click)="dismiss()">Not Now</button>
<button mat-button style="color: #fff; background-color: rgba(255, 255, 255, 0.1)" (click)="createShortcut()">
Create Shortcut
</button>
</div>
</div>
@@ -0,0 +1,19 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
.suggestion-container {
display: flex;
flex-direction: column;
gap: 10px;
}
.suggestion-text {
font-size: 14px;
line-height: 1.4;
color: #fff;
}
@@ -0,0 +1,34 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, inject } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material/snack-bar';
import { MatButton } from '@angular/material/button';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
@Component({
selector: 'mifosx-shortcut-suggestion-snackbar',
templateUrl: './shortcut-suggestion-snackbar.component.html',
styleUrls: ['./shortcut-suggestion-snackbar.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatButton
]
})
export class ShortcutSuggestionSnackbarComponent {
snackBarRef = inject(MatSnackBarRef<ShortcutSuggestionSnackbarComponent>);
data: { pageName: string; route: string } = inject(MAT_SNACK_BAR_DATA);
createShortcut() {
this.snackBarRef.dismissWithAction();
}
dismiss() {
this.snackBarRef.dismiss();
}
}
@@ -0,0 +1,55 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="ks-header">
<h1 mat-dialog-title class="ks-title">Create Shortcut</h1>
</div>
<div mat-dialog-content>
@if (validationError) {
<div class="alert error margin-b-10" style="color: #ef4444; margin-bottom: 15px; font-size: 13px">
{{ validationError }}
</div>
}
<div class="layout-column gap-10px" style="padding-top: 10px">
<mat-form-field class="ks-field" style="width: 100%">
<mat-label>Shortcut Name</mat-label>
<input matInput [(ngModel)]="newShortcut.title" />
</mat-form-field>
<mat-form-field class="ks-field" style="width: 100%">
<mat-label>Key Combination</mat-label>
<input
matInput
readonly
[value]="formatShortcut(newShortcut)"
(keydown)="onKeyDown($event)"
placeholder="Click and press keys..."
/>
</mat-form-field>
<mat-form-field class="ks-field" style="width: 100%">
<mat-label>Route</mat-label>
<input matInput [ngModel]="newShortcut.route" disabled="true" />
</mat-form-field>
<mat-form-field class="ks-field" style="width: 100%">
<mat-label>Action</mat-label>
<input matInput [ngModel]="'Navigate'" disabled="true" />
</mat-form-field>
</div>
</div>
<mat-dialog-actions class="ks-actions">
<div style="flex: 1"></div>
<div class="ks-actions__right">
<button mat-stroked-button class="ks-actions__cancel" (click)="cancel()">Cancel</button>
<button mat-flat-button class="ks-actions__confirm ks-actions__confirm--basic" (click)="save()">Save</button>
</div>
</mat-dialog-actions>
@@ -0,0 +1,129 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, inject } from '@angular/core';
import {
MAT_DIALOG_DATA,
MatDialogRef,
MatDialogTitle,
MatDialogContent,
MatDialogActions
} from '@angular/material/dialog';
import { KeyboardShortcutService, ShortcutItem } from '../../core/services/keyboard-shortcut.service';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { FormsModule } from '@angular/forms';
import { MatButton } from '@angular/material/button';
import { MatFormField, MatLabel, MatError } from '@angular/material/form-field';
import { MatInput } from '@angular/material/input';
import { take } from 'rxjs/operators';
@Component({
selector: 'mifosx-inline-create-shortcut-dialog',
templateUrl: './inline-create-shortcut-dialog.component.html',
styleUrls: ['../keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatButton,
FormsModule,
MatFormField,
MatLabel,
MatInput,
MatError
]
})
export class InlineCreateShortcutDialogComponent {
dialogRef = inject<MatDialogRef<InlineCreateShortcutDialogComponent>>(MatDialogRef);
data = inject(MAT_DIALOG_DATA);
private keyboardShortcutService = inject(KeyboardShortcutService);
newShortcut: Partial<ShortcutItem> = {
title: this.data.pageName,
route: this.data.route,
action: 'navigate',
key: '',
ctrlKey: false,
shiftKey: false,
altKey: false,
custom: true,
id: 'custom_' + Date.now()
};
validationError: string | null = null;
formatShortcut(item: Partial<ShortcutItem>): string {
if (!item || (!item.key && !item.ctrlKey && !item.shiftKey && !item.altKey)) return '';
const parts = [];
if (item.ctrlKey) parts.push('Ctrl');
if (item.shiftKey) parts.push('Shift');
if (item.altKey) parts.push('Alt');
if (item.key) parts.push(item.key.toUpperCase());
return parts.join(' + ');
}
onKeyDown(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
// Ignore if only modifier keys are pressed
if ([
'Control',
'Shift',
'Alt',
'Meta'
].includes(event.key)) {
return;
}
this.newShortcut.ctrlKey = event.ctrlKey;
this.newShortcut.shiftKey = event.shiftKey;
this.newShortcut.altKey = event.altKey;
this.newShortcut.key = event.key.toLowerCase();
this.validationError = null;
}
save() {
if (!this.newShortcut.title || this.newShortcut.title.trim() === '') {
this.validationError = 'Shortcut Name is required';
return;
}
if (!this.newShortcut.key) {
this.validationError = 'Key combination is required';
return;
}
const keyStr = `${!!this.newShortcut.ctrlKey}-${!!this.newShortcut.shiftKey}-${!!this.newShortcut.altKey}-${this.newShortcut.key.toLowerCase()}`;
this.keyboardShortcutService.activeShortcuts$.pipe(take(1)).subscribe((shortcuts) => {
// Check for duplicates
const seen = new Set<string>();
for (const s of shortcuts) {
seen.add(`${!!s.ctrlKey}-${!!s.shiftKey}-${!!s.altKey}-${s.key.toLowerCase()}`);
}
if (seen.has(keyStr)) {
this.validationError = `Duplicate shortcut detected: ${this.formatShortcut(this.newShortcut)}`;
return;
}
// Add and save
if (this.newShortcut.route) {
this.newShortcut.route = this.keyboardShortcutService.normalizeRouteStr(this.newShortcut.route);
}
shortcuts.push(this.newShortcut as ShortcutItem);
this.keyboardShortcutService.updateShortcuts(shortcuts);
this.dialogRef.close(true);
});
}
cancel() {
this.dialogRef.close(false);
}
}
@@ -0,0 +1,58 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<h1 mat-dialog-title>Shortcut Usage</h1>
<div mat-dialog-content>
<table mat-table [dataSource]="usageData" class="mat-elevation-z1" style="width: 100%; margin-top: 10px">
<!-- Page Column -->
<ng-container matColumnDef="page">
<th mat-header-cell *matHeaderCellDef>Page</th>
<td mat-cell *matCellDef="let item">
<div>{{ item.pageName }}</div>
<div style="font-size: 11px; color: #888">{{ item.route }}</div>
</td>
</ng-container>
<!-- Visits Column -->
<ng-container matColumnDef="visits">
<th mat-header-cell *matHeaderCellDef style="text-align: center">Visits</th>
<td mat-cell *matCellDef="let item" style="text-align: center">
<span style="font-weight: 500">{{ item.visits }}</span>
</td>
</ng-container>
<!-- Status / Action Column -->
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef style="text-align: right">Status / Action</th>
<td mat-cell *matCellDef="let item" style="text-align: right">
@if (item.hasShortcut) {
<span style="color: #4caf50; font-size: 13px; font-weight: 500">✓ Shortcut exists</span>
} @else if (item.visits >= 5) {
<span style="color: #ff9800; font-size: 12px; margin-right: 10px; font-weight: 500">Frequently Used</span>
<button mat-button color="primary" (click)="createShortcut(item)">Create Shortcut</button>
} @else {
<span style="color: #aaa; font-size: 12px">Not enough visits</span>
}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (usageData.length === 0) {
<div style="padding: 20px; text-align: center; color: #888; border: 1px solid #eee; border-top: none">
No usage data collected yet.
</div>
}
</div>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Close</button>
</mat-dialog-actions>
@@ -0,0 +1,9 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// Usage dialog styling
@@ -0,0 +1,92 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, OnInit, inject } from '@angular/core';
import {
MatDialogRef,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose,
MatDialog
} from '@angular/material/dialog';
import { ShortcutSuggestionService } from '../../core/services/shortcut-suggestion.service';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { MatButton } from '@angular/material/button';
import {
MatTable,
MatColumnDef,
MatHeaderCellDef,
MatHeaderCell,
MatCellDef,
MatCell,
MatHeaderRowDef,
MatHeaderRow,
MatRowDef,
MatRow
} from '@angular/material/table';
import { InlineCreateShortcutDialogComponent } from './inline-create-shortcut-dialog.component';
@Component({
selector: 'mifosx-shortcut-usage-dialog',
templateUrl: './shortcut-usage-dialog.component.html',
styleUrls: ['./shortcut-usage-dialog.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose,
MatButton,
MatTable,
MatColumnDef,
MatHeaderCellDef,
MatHeaderCell,
MatCellDef,
MatCell,
MatHeaderRowDef,
MatHeaderRow,
MatRowDef,
MatRow
]
})
export class ShortcutUsageDialogComponent implements OnInit {
dialogRef = inject<MatDialogRef<ShortcutUsageDialogComponent>>(MatDialogRef);
private shortcutSuggestionService = inject(ShortcutSuggestionService);
private dialog = inject(MatDialog);
usageData: { route: string; pageName: string; visits: number; hasShortcut: boolean }[] = [];
displayedColumns: string[] = [
'page',
'visits',
'status'
];
ngOnInit() {
this.refreshData();
}
refreshData() {
this.usageData = this.shortcutSuggestionService.getUsageData();
}
createShortcut(item: { pageName: string; route: string }) {
const inlineDialogRef = this.dialog.open(InlineCreateShortcutDialogComponent, {
data: item,
width: '400px',
disableClose: true
});
inlineDialogRef.afterClosed().subscribe((saved) => {
if (saved) {
this.shortcutSuggestionService.markAsDismissed(item.route);
this.refreshData(); // update the table so the checkmark appears!
}
});
}
}
@@ -123,7 +123,9 @@ export class CheckerInboxComponent implements OnInit {
]; ];
private excludeProductEdits(items: any[]): any[] { private excludeProductEdits(items: any[]): any[] {
return (items || []).filter((item: any) => !this.productEditEntities.includes(item?.entityName)); return (items || []).filter(
(item: any) => !(this.productEditEntities.includes(item?.entityName) && item?.actionName === 'UPDATE')
);
} }
/** /**
@@ -65,7 +65,10 @@ export class ViewCheckerInboxComponent {
]; ];
get isProductEditEntry(): boolean { get isProductEditEntry(): boolean {
return this.productEditEntities.includes(this.checkerInboxDetail?.entityName); return (
this.productEditEntities.includes(this.checkerInboxDetail?.entityName) &&
this.checkerInboxDetail?.actionName === 'UPDATE'
);
} }
/** /**
+7 -47
View File
@@ -37,11 +37,12 @@ import { ErrorDialogComponent } from './shared/error-dialog/error-dialog.compone
/** Custom Items */ /** Custom Items */
import { Alert } from './core/alert/alert.model'; import { Alert } from './core/alert/alert.model';
import { KeyboardShortcutsConfiguration } from './keyboards-shortcut-config';
import { Dates } from './core/utils/dates'; import { Dates } from './core/utils/dates';
import { animate, style, transition, trigger } from '@angular/animations'; import { animate, style, transition, trigger } from '@angular/animations';
import { I18nService } from './core/i18n/i18n.service'; import { I18nService } from './core/i18n/i18n.service';
import { ThemingService } from './shared/theme-toggle/theming.service'; import { ThemingService } from './shared/theme-toggle/theming.service';
import { KeyboardShortcutService } from './core/services/keyboard-shortcut.service';
import { ShortcutSuggestionService } from './core/services/shortcut-suggestion.service';
/** Initialize Logger */ /** Initialize Logger */
const log = new Logger('MifosX'); const log = new Logger('MifosX');
@@ -97,8 +98,6 @@ registerLocaleData(localeSW);
standalone: false standalone: false
}) })
export class WebAppComponent implements OnInit, OnDestroy { export class WebAppComponent implements OnInit, OnDestroy {
buttonConfig: KeyboardShortcutsConfiguration;
i18nService: I18nService; i18nService: I18nService;
private authSubscription: Subscription; private authSubscription: Subscription;
@@ -132,7 +131,9 @@ export class WebAppComponent implements OnInit, OnDestroy {
private dateUtils: Dates, private dateUtils: Dates,
private idle: IdleTimeoutService, private idle: IdleTimeoutService,
private dialog: MatDialog, private dialog: MatDialog,
private documentationLinks: DocumentationLinksService private documentationLinks: DocumentationLinksService,
private keyboardShortcutService: KeyboardShortcutService,
private shortcutSuggestionService: ShortcutSuggestionService
) {} ) {}
@HostBinding('class') public cssClass: string; @HostBinding('class') public cssClass: string;
@@ -246,7 +247,6 @@ export class WebAppComponent implements OnInit, OnDestroy {
verticalPosition: 'top' verticalPosition: 'top'
}); });
}); });
this.buttonConfig = new KeyboardShortcutsConfiguration();
// initialize language and date format if they are null. // initialize language and date format if they are null.
if (!localStorage.getItem('mifosXLanguage')) { if (!localStorage.getItem('mifosXLanguage')) {
@@ -269,6 +269,8 @@ export class WebAppComponent implements OnInit, OnDestroy {
this.authSubscription = this.authenticationService.isAuthenticated$.subscribe((loggedIn) => { this.authSubscription = this.authenticationService.isAuthenticated$.subscribe((loggedIn) => {
if (loggedIn) { if (loggedIn) {
this.idle.start(); this.idle.start();
this.keyboardShortcutService.initShortcuts();
this.shortcutSuggestionService.init();
} else { } else {
this.idle.stop(); this.idle.stop();
} }
@@ -311,46 +313,4 @@ export class WebAppComponent implements OnInit, OnDestroy {
help() { help() {
this.documentationLinks.open('userManual'); this.documentationLinks.open('userManual');
} }
// Monitor all keyboard events and excute keyboard shortcuts
@HostListener('window:keydown', ['$event'])
onKeydownHandler(event: KeyboardEvent) {
const routeD = this.buttonConfig.buttonCombinations.find(
(x) =>
x.ctrlKey === event.ctrlKey && x.shiftKey === event.shiftKey && x.altKey === event.altKey && x.key === event.key
);
if (!(routeD === undefined)) {
switch (routeD.id) {
case 'logout':
this.logout();
break;
case 'help':
this.help();
break;
case 'runReport':
document.getElementById('runReport').click();
break;
case 'cancel':
const cancelButtons = document.querySelectorAll('button');
const filteredcancelButtons = Array.prototype.filter.call(cancelButtons, function (el: any) {
return el.textContent.trim() === 'Cancel';
});
if (filteredcancelButtons.length > 0) {
filteredcancelButtons[0].click();
}
break;
case 'submit':
const submitButton = document.querySelectorAll('button');
const filteredSubmitButton = Array.prototype.filter.call(submitButton, function (el: any) {
return el.textContent.trim() === 'Submit';
});
if (filteredSubmitButton.length > 0) {
filteredSubmitButton[0].click();
}
break;
default:
this.router.navigate([routeD.route], { relativeTo: this.activatedRoute });
}
}
}
} }
+2 -2
View File
@@ -9,8 +9,8 @@
/* tslint:disable */ /* tslint:disable */
export default { export default {
'mifos_x': { 'mifos_x': {
'version': '260813', 'version': '260825',
'hash': '5a6fb1f9' 'hash': '1b2ef512'
}, },
'allow_switching_backend_instance': true 'allow_switching_backend_instance': true
}; };
+3
View File
@@ -8,6 +8,9 @@
], ],
"app/*": [ "app/*": [
"src/app/*" "src/app/*"
],
"environments/*": [
"src/environments/*"
] ]
}, },
"importHelpers": true, "importHelpers": true,