repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/transaction.model.ts
|
import { SafeResourceUrl } from '@angular/platform-browser';
export type TransactionType = 'payment' | 'refund';
export type TransactionOptions = 'View receipt' | 'Download invoice';
export type TransactionStatus = 'Successful' | 'Refunded';
export interface Transaction {
transactionId: string;
ownershipId: string;
appId: string;
developerId: string;
userId: string;
date: number;
type: TransactionType;
amount: number;
customData?: any;
feeAmount?: number;
marketplaceAmount?: number;
developerAmount?: number;
recieptUrl?: string;
invoiceUrl?: string;
}
export interface FullTransaction extends Transaction {
appName?: string;
appIcon?: string | SafeResourceUrl;
options?: TransactionOptions[];
status?: TransactionStatus;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-checkbox/oc-checkbox.component.spec.ts
|
<filename>projects/angular-common-components/src/lib/common-components/oc-checkbox/oc-checkbox.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcCheckboxComponent } from './oc-checkbox.component';
import { FormsModule } from '@angular/forms';
describe('OcCheckboxComponent', () => {
let component: OcCheckboxComponent;
let fixture: ComponentFixture<OcCheckboxComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcCheckboxComponent],
imports: [FormsModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcCheckboxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain status value', () => {
component.writeValue(true);
expect(component.checked).toEqual(true);
});
it('should change status value', async () => {
component.writeValue(true);
const checkbox = fixture.nativeElement.querySelector('input');
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(checkbox.checked).toEqual(true);
});
});
it('should be disabled', async () => {
component.setDisabledState(true);
const checkbox = fixture.nativeElement.querySelector('input');
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(checkbox.disabled).toBeTruthy();
});
});
it('should contain label text', async () => {
component.labelText = 'Test label text';
const checkboxLabelText = fixture.nativeElement.querySelector('.form-checkbox__label');
fixture.detectChanges();
expect(component.labelText).toEqual('Test label text');
await fixture.whenStable().then(() => {
expect(checkboxLabelText.textContent.trim()).toEqual('Test label text');
});
});
it('should be required', async () => {
component.requiredIndicator = true;
fixture.detectChanges();
const checkboxIndicator = fixture.nativeElement.querySelector('.form-checkbox__required-glyph');
expect(component.requiredIndicator).toEqual(true);
await fixture.whenStable().then(() => {
expect(checkboxIndicator).toBeTruthy();
});
});
it('should call onChange with value', async () => {
const onChangeFunc = jest.fn();
component.registerOnChange(onChangeFunc);
const checkbox = fixture.nativeElement.querySelector('input');
checkbox.checked = true;
checkbox.dispatchEvent(new Event('change'));
expect(onChangeFunc).toHaveBeenCalled();
expect(onChangeFunc.mock.calls[0][0]).toBe(true);
});
it('should call onTouch on blur event', async () => {
const onTouchedFunc = jest.fn();
component.registerOnTouched(onTouchedFunc);
const checkbox = fixture.nativeElement.querySelector('input');
checkbox.checked = true;
checkbox.dispatchEvent(new Event('blur'));
expect(onTouchedFunc).toHaveBeenCalled();
});
it('should change value on label click', async () => {
const label = fixture.nativeElement.querySelector('label');
label.click();
fixture.detectChanges();
expect(component.checked).toEqual(true);
});
});
|
mukesh-openchannel/angular-template-libraries
|
src/review.stories.ts
|
<gh_stars>0
import { moduleMetadata } from '@storybook/angular';
import { OcRatingComponent, OcReviewComponent } from '@openchannel/angular-common-components/src/lib/market-components';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { AngularSvgIconModule } from 'angular-svg-icon';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components';
import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
import { NgModule } from '@angular/core';
import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model';
const modules: NgModule = {
imports: [
AngularSvgIconModule.forRoot(),
NgbModule,
HttpClientTestingModule,
ReactiveFormsModule,
FormsModule,
OcFormComponentsModule,
OcCommonLibModule,
],
declarations: [OcRatingComponent],
providers: [ERROR_MESSAGES_STORY_PROVIDER],
};
export default {
title: 'Review [BEM]',
component: OcReviewComponent,
decorators: [moduleMetadata(modules)],
argTypes: {
reviewFormData: { action: 'Review Data' },
cancelReview: { action: 'Review canceled' },
isFormInvalid: { action: 'Form validation status' },
},
};
const ReviewComponent = (args: OcReviewComponent) => ({
component: OcReviewComponent,
moduleMetadata: modules,
props: args,
});
export const SimpleReview = ReviewComponent.bind({});
SimpleReview.args = {};
export const FullReview = ReviewComponent.bind({});
FullReview.args = {
heading: 'Write a review',
enableButtons: true,
cancelButtonText: 'Cancel',
submitButtonText: 'Submit',
hidCancelButton: false,
};
export const FilledReview = ReviewComponent.bind({});
FilledReview.args = {
heading: 'Write a review',
enableButtons: true,
cancelButtonText: 'Cancel',
submitButtonText: 'Submit',
hidCancelButton: false,
reviewData: {
reviewId: '5463cee5e4b042e3e26f1e41',
appId: '5565322ae4b0a70b13a4563b',
appName: 'My App',
userId: '6843gfu34783gfg',
reportDate: 1432695338702,
rating: 400,
headline: 'Good App!',
description: 'It works great and looks good too.',
status: {
value: 'approved',
reason: '',
},
},
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/model/multi-select-checkbox.model.ts
|
export interface DropdownItem {
label: string | number;
value: any;
}
export type DropdownItemType = number | string | DropdownItem;
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-dropdown-form/oc-dropdown-form.service.ts
|
<gh_stars>0
import { AppFormField, DropdownFormField } from '../model/app-form-model';
import { cloneDeep } from 'lodash';
export class OcDropdownFormUtils {
static getFormFields(field: DropdownFormField, oldValue?: string): AppFormField[] {
const {
attributes: {
dropdownSettings: { dropdownForms, dropdownField },
},
} = field || ({} as DropdownFormField);
if (!dropdownForms || !dropdownField) {
// tslint:disable-next-line:no-console
console.warn(`Incorrect field settings. Please check dropdown field: id=${field?.id}.`);
return null;
}
const dropdownOption = this.findDropdownValue(dropdownField, oldValue?.[dropdownField.id] || dropdownField.defaultValue);
if (!dropdownOption) {
console.warn(`Can't init dropdown value. fieldId=${dropdownField}`);
return null;
}
const clonedDropdownField = cloneDeep(dropdownField);
const clonedFields = cloneDeep(dropdownForms[dropdownOption] || []);
clonedFields.forEach(fieldItem => this.setDefaultValue(fieldItem, oldValue?.[fieldItem.id]));
this.setDefaultValue(clonedDropdownField, dropdownOption);
return [clonedDropdownField, ...clonedFields];
}
private static findDropdownValue(field: AppFormField, defaultValue: any): string {
if (field?.options) {
return field.options.find((option: any) => option?.toLowerCase() === defaultValue?.toLowerCase()) || field.options[0];
}
return null;
}
private static setDefaultValue(field: AppFormField, defaultValue: any): void {
if (defaultValue) {
field.defaultValue = defaultValue;
}
}
}
|
mukesh-openchannel/angular-template-libraries
|
src/color.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcColorComponent, OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components';
const modules = {
imports: [OcFormComponentsModule],
};
export default {
title: 'Color [BEM]',
component: OcColorComponent,
decorators: [moduleMetadata(modules)],
};
const ChartComponent = (args: OcColorComponent) => ({
component: OcColorComponent,
moduleMetadata: modules,
props: args,
});
export const BasicColorComponent = ChartComponent.bind({});
BasicColorComponent.args = {
placeholder: 'Enter color value here',
colorPickerPosition: 'bottom-left',
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/model/image-gallery.model.ts
|
/**
* Gallery Item interface
* @property {string} title - String value with image title
* @property {string} description - String value with description for the title
* @property {string} image - Image URL value, not set this value if your data is video
* @property {string} video Video URL value, not set this value if your data is image
*/
export interface GalleryItem {
title?: string;
description?: string;
image?: string;
video?: string;
mediaWidth?: number;
}
/**
* Interface for the media item of the [Image Gallery]{@link OcImageGalleryComponent}.
* Setting height and width of the item in different units.
* @property {string} height set height of the media.
* @property {string} width set width of the media
*
* @example
* {
* height: "192px",
* width: "100%"
* }
*/
export interface GalleryMediaDimensions {
height: string;
width: string;
}
/**
* Interface for the configuration of the path of icons, used in [Image Gallery Component]{@link OcImageGalleryComponent}.
* @property {string} arrowRight path to the right arrow icon of the carousel
* @property {string} arrowLeft path to the left arrow icon of the carousel
* @property {string} closeIcon path to the close cross icon of the modal window
*
* @example
* {
* arrowLeft: "assets/angular-common-components/arrow-left.svg",
* arrowRight: "assets/angular-common-components/arrow-right.svg",
* closeIcon: "assets/angular-common-components/cross.svg",
* }
*/
export interface GalleryIconsAssets {
/** path to the right arrow icon of the carousel */
arrowLeft?: string;
/** path to the left arrow icon of the carousel */
arrowRight?: string;
/** path to the close cross icon of the modal window */
closeIcon?: string;
}
export enum KEY_CODE {
RIGHT_ARROW = 39,
LEFT_ARROW = 37,
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/portal-components/oc-app-table/oc-app-table.component.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import {
AfterViewInit,
ChangeDetectorRef,
Component,
Directive,
EventEmitter,
Input,
Output,
QueryList,
TemplateRef,
ViewChildren,
} from '@angular/core';
import {
AppGridSortChosen,
AppGridSortColumn,
AppGridSortOptions,
AppListing,
AppListingOptions,
AppListMenuAction,
AppsNotFoundTemplateContext,
ColumnTemplateContext,
FieldPathConfig,
ModifyColumnConfig,
ModifyColumnId,
} from '../models/app-listing.model';
/**
* Interface for the sorting apps in the table.
*/
export interface SortChosen {
/** fields by which sorting will be implemented */
by: 'name' | 'created' | 'status';
/** ascending or descending sort */
ascending: boolean;
}
interface ColumnPattern {
columnId: ModifyColumnId;
headerCellTemplate: TemplateRef<any>;
rowCellTemplate: TemplateRef<ColumnTemplateContext>;
}
@Directive({
selector: 'ng-template[name]',
})
export class OcAppTableCellPattern {
@Input() name: ModifyColumnId;
@Input() type: 'header-cell' | 'row-cell';
constructor(public template: TemplateRef<any>) {}
}
/**
* Component represents table with apps, demonstrates subversion of app.
* Shows title, summary, date of creation and status of the app.
* Also has a dropdown menu with actions for each app in the table.
*/
@Component({
selector: 'oc-app-table',
templateUrl: './oc-app-table.component.html',
styleUrls: ['./oc-app-table.component.css'],
})
export class OcAppTableComponent implements AfterViewInit {
/** Used for getting text field for default 'Status' column. */
readonly statusPattern = {
inDevelopment: { style: 'in-development', text: 'Draft' },
inReview: { style: 'in-review', text: 'In review' },
pending: { style: 'pending', text: 'Pending' },
approved: { style: 'approved', text: 'Approved' },
rejected: { style: 'rejected', text: 'Rejected' },
suspended: { style: 'suspended', text: 'Suspended' },
};
/**
* Configuration of the component.
* By this configuration view and content of the component will be built.
*/
@Input() properties: AppListing;
/**
* Message that will be shown if no apps in the data array..
* @default empty
*/
@Input() noAppMessage: string = 'You have no apps in your list';
/**
* Path to the custom icon for the hidden menu toggle button.
* @default icon with three horizontal dots
*/
@Input() menuUrl: string = 'assets/angular-common-components/dots-menu.svg';
/**
* Path to the custom icon for the `sort` button when ascending sorting chosen.
* @default empty
*/
@Input() ascendingSortIcon: string = '';
/**
* Path to the custom icon for the `sort` button when descending sorting chosen.
* @default empty
*/
@Input() descendingSortIcon: string = '';
/**
* Set default app icon that will be
* shown when icon of the app is not present
* @default no icon
*/
@Input() defaultAppIcon: string = '';
/** List of columns ID for displaying. Columns will display by this ordering. */
@Input() activeColumns: ModifyColumnId[] = [
'left-placeholder',
'name',
'summary',
'create-date',
'status',
'app-options',
'right-placeholder',
];
/** Modify default table cells or add a new column. */
@Input() modifyColumns: ModifyColumnConfig = {};
/** Setup sort icon direction for columns. */
@Input() set sortOptions(options: AppGridSortOptions) {
this.isOldSortImplementation = false;
if (options) {
this.currentSortOptions = options;
}
}
/** This is table bottom area (after all apps), by default used for showing message 'You have no apps in your list' */
@Input() tableBottomRowTemplate: TemplateRef<AppsNotFoundTemplateContext>;
/**
* Modify getting text data for default cells ('Name' & 'Summary').<br>
* @param config Specific paths for getting a text value from {@link FullAppData}.
*/
@Input() set selectAppFieldByPathConfig(config: FieldPathConfig) {
this.fieldsPathConfig = { ...this.fieldsPathConfig, ...(config || {}) };
}
/**
* Output of menu list item clicked action.
* Contains an action name, app ID, app version
*/
@Output() readonly menuClicked: EventEmitter<AppListMenuAction> = new EventEmitter<AppListMenuAction>();
/**
* Output with page number for new apps request
* Start number = 1
*/
@Output() readonly pageScrolled: EventEmitter<number> = new EventEmitter<number>();
/**
* @deprecated Please use: @Input {@link #sortOptions} and @Output {@link #sortOptionsChosen}.
* Returns clicked sorting type.
* Contains fields:
*
* `by` - chosen sorting type, can be `name`, `created` or `status`;
*
* `ascending` - `true` for ascending sort or `false` for descending sort.
*/
@Output() readonly sortChosen: EventEmitter<SortChosen> = new EventEmitter<SortChosen>();
/**
* Returns new sort options with changed column.<br>
* For updating current sort options, use @Input {@link #sortOptions}.
*/
@Output() readonly sortOptionsChosen: EventEmitter<AppGridSortChosen> = new EventEmitter<AppGridSortChosen>();
@ViewChildren(OcAppTableCellPattern) _cellPatterns: QueryList<OcAppTableCellPattern>;
/** Default app paths for getting text fields. */
fieldsPathConfig: FieldPathConfig = {
appIconPath: 'customData.icon',
appDescriptionPath: 'customData.summary',
};
private _defaultColumnsPattern: ModifyColumnConfig = {
'left-placeholder': {},
name: {},
summary: {},
'create-date': {},
status: {},
'app-options': {},
'right-placeholder': {},
};
/** All columns for displaying. */
columnsPattern: ColumnPattern[] = [];
/** Sort apps by specific fields. */
sortingObjects: SortChosen[] = [
{
by: 'name',
ascending: false,
},
{
by: 'created',
ascending: false,
},
{
by: 'status',
ascending: false,
},
];
isOldSortImplementation: boolean = true;
/** Default sort options. All sort icons to down. */
currentSortOptions: AppGridSortOptions = {
name: -1,
status: -1,
created: -1,
};
constructor(private cdRef: ChangeDetectorRef) {}
ngAfterViewInit(): void {
this.fillDefaultColumnsPattern();
this.columnsPattern = this.mapColumnsConfigToColumnsArray(
this.activeColumns,
this.modifyColumnsConfigByUserConfig(this.modifyColumns, this._defaultColumnsPattern),
);
// run detect changes, because some component field changed after view.
this.cdRef.detectChanges();
}
fillDefaultColumnsPattern(): void {
const temp: any = {
headerCell: {},
rowCell: {},
};
this._cellPatterns.forEach(p => (temp[p.type][p.name] = p.template));
for (const columnId in this._defaultColumnsPattern) {
this._defaultColumnsPattern[columnId].rowCellTemplate = temp.rowCell[columnId];
this._defaultColumnsPattern[columnId].headerCellTemplate = temp.headerCell[columnId];
}
}
modifyColumnsConfigByUserConfig(newConfig: ModifyColumnConfig, oldConfig: ModifyColumnConfig): ModifyColumnConfig {
const resultConfig: ModifyColumnConfig = { ...oldConfig };
for (const columnId in newConfig) {
if (newConfig[columnId]) {
resultConfig[columnId] = {
headerCellTemplate: newConfig[columnId]?.headerCellTemplate || resultConfig[columnId].headerCellTemplate,
rowCellTemplate: newConfig[columnId]?.rowCellTemplate || resultConfig[columnId].rowCellTemplate,
};
}
}
return resultConfig;
}
mapColumnsConfigToColumnsArray(columnsActive: ModifyColumnId[], config: ModifyColumnConfig): ColumnPattern[] {
return (columnsActive || [])
.map(columnId => ({
columnId,
headerCellTemplate: config[columnId]?.headerCellTemplate,
rowCellTemplate: config[columnId]?.rowCellTemplate,
}))
.filter(column => column.columnId && column.headerCellTemplate && column.rowCellTemplate);
}
/**
* Click on dropdown menu of the app.
* @param menu chosen menu option
* @param appId ID of the current app
* @param appVersion version of the current app
* @param isChild is the the current app a subversion of the main app
*/
action(menu: AppListingOptions, appId: string, appVersion: number, isChild?: boolean): void {
const appAction: AppListMenuAction = {
action: menu,
appId,
appVersion,
isChild,
};
this.menuClicked.emit(appAction);
}
/**
* Parser for the dropdown menu actions. Shows only actions which has been appropriate for current app.
* @param action action for check
* @param appStatus status of the app
* @param modifiedBy what type of user was last who modified the app
*/
needToShowItem(action: AppListingOptions, appStatus: string, modifiedBy: string): boolean {
if (appStatus.includes(action.toLowerCase())) {
return false;
} else {
switch (action) {
case 'PREVIEW':
return !!this.properties.previewTemplate;
case 'PUBLISH':
case 'SUBMIT':
return appStatus === 'inDevelopment';
case 'UNSUSPEND':
return appStatus === 'suspended' && modifiedBy === 'developer';
case 'SUSPEND':
return appStatus === 'approved';
default:
return true;
}
}
}
/**
* Trigger {@link #pageScrolled} when user use down scroll.
*/
onScrollDown(): void {
this.pageScrolled.emit();
}
sortAppsByKey(columnName: AppGridSortColumn): void {
if (this.isOldSortImplementation) {
this.oldSortAppsByKey(columnName);
} else {
this.newSortAppsByKey(columnName);
}
}
/** Only one column can be sorted, all other columns will be cleaned. */
private oldSortAppsByKey(columnName: AppGridSortColumn): void {
Object.keys(this.currentSortOptions).forEach(tempColumnName => {
if (columnName === tempColumnName) {
this.updateSortDirection(this.currentSortOptions, tempColumnName);
this.sortChosen.emit({
by: tempColumnName,
ascending: this.currentSortOptions[tempColumnName] === -1,
});
} else {
this.currentSortOptions[tempColumnName] = -1;
}
});
}
/**
* Expand sort value for selected column (-1 => 1; null => -1; 1 => -1).<br>
* Not update current sort options.<br>
* Returns new sort options with selected column.<br>
*
* Note: For updating current sort options, use @Input {@link #sortOptions}.
*/
private newSortAppsByKey(columnName: AppGridSortColumn): void {
const newSortOptions = { ...this.currentSortOptions };
this.updateSortDirection(newSortOptions, columnName);
this.sortOptionsChosen.emit({
sortOptions: newSortOptions,
changedSortOption: columnName,
});
}
/**
* Expand sort value for selected column (-1 => 1; null => -1; 1 => -1).
*/
private updateSortDirection(sortOptions: AppGridSortOptions, columnName: AppGridSortColumn): void {
if (!sortOptions[columnName]) {
sortOptions[columnName] = -1;
} else {
sortOptions[columnName] *= -1;
}
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/chart-service.ts
|
<filename>projects/angular-common-services/src/lib/service/chart-service.ts
import { Injectable } from '@angular/core';
import { HttpRequestService } from './http-request-services';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { OcHttpParams } from '../model/api/http-params-encoder-model';
import { ChartStatisticDataModelResponse, ChartStatisticPeriodModelResponse } from '../model/components/frontend.model';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
* Description: Service for setting up site config.<br>
*
* Endpoints:
*
* GET 'v2/stats/series/period/fields'
*
* Methods:
*
* getTimeSeries
*
* getDateStartByCurrentPeriod
*/
@Injectable({
providedIn: 'root',
})
export class ChartService {
constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
*
* Description: Get chart statistic data
*
* @param {string} period - Period of time per devision
* @param {string} field - Field name
* @param {number} dateStartMS - timestamp of Start
* @param {number} dateEndMS - timestamp of End
* @param {string} appId - (optional)
* @returns {Observable<ChartStatisticDataModelResponse>} `Observable<ChartStatisticDataModelResponse>`
*
* ### Example:
*
* `getTimeSeries('month','name', 628376482734, 287364872364, '98agsd87has8d7h8as7d')`
*/
getTimeSeries(
period: string,
field: string,
dateStartMS: number,
dateEndMS: number,
appId?: string,
): Observable<ChartStatisticDataModelResponse> {
const query = appId ? JSON.stringify({ appId }) : '';
const mainUrl = `${this.apiPaths.stats}/series/${period}/${field}`;
const params = new OcHttpParams().append('start', String(dateStartMS)).append('end', String(dateEndMS)).append('query', query);
return this.httpRequest.get(mainUrl, { params }).pipe(
map(chartResponse => {
if (chartResponse) {
let labelsDataX: string[];
let tabularLabels: string[];
if (period === 'month') {
labelsDataX = chartResponse.map(chart => new Date(chart[0]).toLocaleDateString('default', { month: 'short' }));
tabularLabels = chartResponse.map(chart => new Date(chart[0]).toLocaleDateString('default', { month: 'long' }));
} else {
tabularLabels = labelsDataX = chartResponse
.map(chart => new Date(chart[0]))
.map(date => {
return `${date.toLocaleDateString('default', { month: 'short' })} ${date.getDate()}`;
});
}
return {
labelsX: labelsDataX,
labelsY: chartResponse.map(chart => chart[1]),
tabularLabels,
};
} else {
return null;
}
}),
);
}
/**
*
* Description: Get Start Date by period
*
* @param {Date} dateEnd - End Date
* @param {ChartStatisticPeriodModelResponse} period - Period Data Object
* @returns {Date} `Date`
*
* ### Example
*
* `getDateStartByCurrentPeriod(297364872634, {
* id:'98sdh9f8hsd9',
* label:'label',
* active:true,
* tabularLabel:'tLabel',
* };`
*/
getDateStartByCurrentPeriod(dateEnd: Date, period: ChartStatisticPeriodModelResponse): Date {
const dateStart = new Date(dateEnd);
if (period?.id === 'month') {
dateStart.setFullYear(dateEnd.getFullYear() - 1);
} else if (period?.id === 'day') {
dateStart.setTime(dateStart.getTime() - 31 * 24 * 60 * 60 * 1000);
} else {
dateStart.setMonth(dateStart.getTime() - 31 * 24 * 60 * 60 * 1000);
}
return dateStart;
}
}
|
mukesh-openchannel/angular-template-libraries
|
src/app-getstarted.stories.ts
|
<gh_stars>0
import { moduleMetadata } from '@storybook/angular';
import { OcAppGetStartedComponent } from '@openchannel/angular-common-components/src/lib/market-components';
import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
/** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */
const modules = {
imports: [OcCommonLibModule],
};
export default {
title: 'Get Started [BEM]',
component: OcAppGetStartedComponent,
decorators: [moduleMetadata(modules)],
argsTypes: { getStarted: { action: 'Get Started Button Pressed' } },
};
const GetStartedComponent = (args: OcAppGetStartedComponent) => ({
component: OcAppGetStartedComponent,
moduleMetadata: modules,
props: args,
});
export const DefaultHomePage = GetStartedComponent.bind({});
DefaultHomePage.args = {
getStartedHeader: 'List Your App in our App Store',
getStartedDescription: 'Register as an app developer and submit your app easily with our App Store Developer Portal',
getStartedButtonText: 'Get Started As An App Developer',
getStartedType: 'home',
};
export const SearchPage = GetStartedComponent.bind({});
SearchPage.args = {
getStartedType: 'search',
getStartedButtonText: 'More Apps For You',
getStartedHeader: 'Discover new apps',
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/portal-components/oc-chart/oc-chart.component.spec.ts
|
<filename>projects/angular-common-components/src/lib/portal-components/oc-chart/oc-chart.component.spec.ts
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { OcChartComponent } from './oc-chart.component';
import { MockDropdownButtonComponent, MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock';
import { By } from '@angular/platform-browser';
import { ChartLayoutTypeModel } from '@openchannel/angular-common-components/src/lib/portal-components';
import { SimpleChange, SimpleChanges } from '@angular/core';
// Needed for chart.js constructor
declare global {
interface Window {
ResizeObserver: any;
}
}
window.ResizeObserver =
window.ResizeObserver ||
jest.fn().mockImplementation(() => ({
disconnect: jest.fn(),
observe: jest.fn(),
unobserve: jest.fn(),
}));
const month = {
labelsY: [3, 10, 30, 50, 25, 40, 100, 70, 150, 200, 50, 85, 50],
labelsX: ['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar'],
tabularLabels: [
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
'January',
'February',
'March',
],
};
const periods = [
{
id: 'month',
label: 'Monthly',
tabularLabel: 'Month',
},
{
id: 'day',
label: 'Daily',
active: true,
tabularLabel: 'Day',
},
];
const fields = [
{
id: 'downloads',
label: 'Downloads',
active: true,
},
{
id: 'reviews',
label: 'Reviews',
},
{
id: 'leads',
label: 'Leads',
},
{
id: 'views',
label: 'Views',
},
];
const selectedApp = {
id: 'all-app',
label: 'All apps',
active: true,
};
const apps = {
activeItem: selectedApp,
items: [
selectedApp,
{
id: 'app-1',
label: 'API Connections',
},
{
id: 'app-2',
label: 'Lead Accounting',
},
{
id: 'app-3',
label: 'Full CRM',
},
{
id: 'app-4',
label: 'Intersect AI Prediction',
},
{
id: 'app-5',
label: 'Fuel CRM Lite',
},
{
id: 'app-6',
label: 'Long app name 12345678901234567890123456789012345678901234567890',
},
],
};
const tabularType = 'tabular';
const graphType = 'graph';
describe('OcChartComponent', () => {
let component: OcChartComponent;
let fixture: ComponentFixture<OcChartComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [OcChartComponent, MockDropdownButtonComponent, MockSvgIconComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(OcChartComponent);
component = fixture.componentInstance;
component.chartData = {
data: month,
layout: ChartLayoutTypeModel.standard,
periods,
fields,
apps,
};
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should set correct count and count text', () => {
const testCount = 10000;
const testCountText = 'Views count';
component.count = testCount;
component.countText = testCountText;
fixture.detectChanges();
const countElement = fixture.debugElement.query(By.css('.chart__data-container-total-count')).nativeElement;
const countTextElement = fixture.debugElement.query(By.css('.chart__data-container-total-text')).nativeElement;
expect(+countElement.textContent).toBe(testCount);
expect(countTextElement.textContent).toBe(testCountText);
});
it('should not render data container total, if count < 0', () => {
component.count = -1;
fixture.detectChanges();
const dataContainerTotal = fixture.debugElement.query(By.css('.chart__data-container-total'));
expect(dataContainerTotal).toBeNull();
});
it('should switch periods by corresponding button click', () => {
const updateChartPeriodFunction = jest.spyOn(component, 'updateChartPeriod');
const periodLabels = fixture.debugElement.queryAll(By.css('.chart__period-item-label'));
const disabledPeriod = periodLabels.find(periodLabel => periodLabel.query(By.css('.chart__period-item-radio:not(:checked)')));
disabledPeriod.triggerEventHandler('click', periods[0]);
expect(updateChartPeriodFunction).toHaveBeenCalledWith(periods[0]);
expect(component.chartData.periods[0].active).toBeTruthy();
expect(component.chartData.periods[1].active).toBeFalsy();
});
it('should switch data type (tabular, graph) by corresponding buttons click', () => {
const swapActiveDataTypeFunction = jest.spyOn(component, 'swapActiveDataType');
const tabularButton = fixture.debugElement.query(By.css('.chart__tabular-button'));
const graphButton = fixture.debugElement.query(By.css('.chart__graph-button'));
tabularButton.triggerEventHandler('click', {});
expect(swapActiveDataTypeFunction).toHaveBeenCalledWith(tabularType);
expect(component.activeDataType).toBe(tabularType);
graphButton.triggerEventHandler('click', {});
expect(swapActiveDataTypeFunction).toHaveBeenCalledWith(graphType);
expect(component.activeDataType).toBe(graphType);
});
it('should render correct data container depending on data type', () => {
component.activeDataType = graphType;
fixture.detectChanges();
const canvasContainer = fixture.debugElement.query(By.css('.chart__data-container-canvas'));
expect(canvasContainer).toBeTruthy();
component.activeDataType = tabularType;
fixture.detectChanges();
const tableContainer = fixture.debugElement.query(By.css('.chart__data-container-tabular'));
expect(tableContainer).toBeTruthy();
});
it('should reload chart, when active data type changed to graph', fakeAsync(() => {
const reloadChartFunction = jest.spyOn(component, 'reloadChart');
component.swapActiveDataType(graphType);
tick();
expect(reloadChartFunction).toHaveBeenCalled();
}));
it('should recreate chart, when chart data changed', () => {
const reloadChartFunction = jest.spyOn(component, 'reloadChart');
const setChartFunction = jest.spyOn(component, 'setChart');
const chart = component.getChart();
const changesObj: SimpleChanges = {
chartData: new SimpleChange(component.chartData, { ...component.chartData }, false),
};
// tslint:disable-next-line:no-lifecycle-call
component.ngOnChanges(changesObj);
expect(reloadChartFunction).toHaveBeenCalled();
expect(setChartFunction).toHaveBeenCalled();
expect(chart).not.toBe(component.getChart());
});
it('should update chart data, when active app changed with default app template', () => {
const changeChartOptionsEmitFunction = jest.spyOn(component.changeChartOptions, 'emit');
component.appDropdownTemplate = null;
fixture.detectChanges();
const chartApps = fixture.debugElement.query(By.css('.chart__type-apps')).componentInstance;
chartApps.selectedChange.emit(apps.items[1]);
expect(component.chartData.apps.activeItem).toBe(apps.items[1]);
expect(changeChartOptionsEmitFunction).toHaveBeenCalledWith({
field: component.chartData?.fields?.find(item => item?.active),
period: component.chartData?.periods?.find(item => item?.active),
selectedApp: component.chartData?.apps?.activeItem,
});
});
it('should sort tabular data by corresponding button click', () => {
component.activeDataType = tabularType;
fixture.detectChanges();
const changesObj: SimpleChanges = {
chartData: new SimpleChange(component.chartData, { ...component.chartData }, false),
};
// tslint:disable-next-line:no-lifecycle-call
component.ngOnChanges(changesObj);
const chartTableHeadings = fixture.debugElement.queryAll(By.css('.chart__table-view-heading'));
chartTableHeadings.forEach(chartTableHeading => {
chartTableHeading.triggerEventHandler('click', {});
fixture.detectChanges();
const by = component.activeTabularSort.by;
const ascending = component.activeTabularSort.ascending;
let correctSorted = true;
for (let i = 1; i < component.tabularData.length; i++) {
if (ascending) {
if (component.tabularData[i][by] < component.tabularData[i - 1][by]) {
correctSorted = false;
}
} else {
if (component.tabularData[i][by] > component.tabularData[i - 1][by]) {
correctSorted = false;
}
}
}
expect(correctSorted).toBeTruthy();
});
});
it('should emit change chart data, set new active type and parameter, when chart options updated', () => {
const changeChartOptionsEmitFunction = jest.spyOn(component.changeChartOptions, 'emit');
const disabledDropdownType = component.dropdownTypes.find(type => !type.active);
const chartTypesDropdown = fixture.debugElement.query(By.css('.chart__type-types')).componentInstance;
chartTypesDropdown.selectedChange.emit(disabledDropdownType);
const newActiveField = component.chartData.fields.find(field => field.active);
const enabledDropdownType = { ...disabledDropdownType, active: true };
expect(changeChartOptionsEmitFunction).toHaveBeenCalled();
expect(enabledDropdownType).toEqual(newActiveField);
expect(enabledDropdownType).toEqual(component.dropdownSelectedType);
});
it('should fill tabular data in fillTabularData method', () => {
(component as any).fillTabularData();
expect(component.tabularData.length).not.toBe(0);
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-dropdown/oc-dropdown.component.ts
|
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { DropdownModel } from '../model/components-basic.model';
@Component({
selector: 'oc-dropdown',
templateUrl: './oc-dropdown.component.html',
styleUrls: ['./oc-dropdown.component.css'],
})
export class OcDropdownComponent {
/**
* Defined selected dropdown model item in dropdown list
*/
@Input() selected: DropdownModel<any>;
/**
* Dropdown trigger button title
*/
@Input() title: string = 'Sort by';
/**
* List of dropdown model items
*/
@Input() options: DropdownModel<any>[];
/**
* Output event that emits when some item in the list was selected
*/
@Output() readonly selectedChange: EventEmitter<DropdownModel<any>> = new EventEmitter<DropdownModel<any>>();
/**
* Function that executes on click to item in dropdown list. Set selected item and emits it.
* @param {DropdownModel<any>} selected
*/
onSelect(selected: DropdownModel<any>): void {
this.selected = selected;
this.selectedChange.emit(selected);
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/service/rich-text-utils/rich-text.service.ts
|
export class RichTextUtils {
static SPACES = [' ', ' '];
static trimRichText(htmlText: string): string {
if (!htmlText || typeof htmlText !== 'string') {
return htmlText;
}
const subString: string[] = htmlText.split(/(<[^>]*>)/g);
const leftArr = [];
const rightArr = [];
let leftIndex: any;
let rightIndex: any;
for (leftIndex of Object.keys(subString).map(Number)) {
if (this.trimText(leftArr, subString[leftIndex], text => this.trimTextFromLeftSide(text))) {
break;
}
}
for (rightIndex of Object.keys(subString)
.slice(leftIndex + 1)
.reverse()
.map(Number)) {
if (this.trimText(rightArr, subString[rightIndex], text => this.trimTextFromRightSide(text))) {
break;
}
}
if (leftIndex + 1 === rightIndex) {
leftArr[leftIndex] = this.trimTextFromRightSide(leftArr[leftIndex]);
}
return [...leftArr, ...subString.slice(leftIndex + 1, rightIndex), ...rightArr.reverse()].join(''); // NOSONAR the reverse is correct for this case
}
private static trimText(result: string[], text: string, trimFn: (text: string) => string): boolean {
if (text.startsWith('<')) {
result.push(this.trimTextFromRightSide(this.trimTextFromLeftSide(text)));
} else {
const newText = trimFn(text);
result.push(newText);
if (newText) {
return true;
}
}
return false;
}
private static trimTextFromLeftSide(text: string): string {
let position = 0;
while (true) {
const cnt = this.SPACES.find(sp => text.startsWith(sp, position))?.length || 0;
if (!cnt) {
break;
}
position += cnt;
}
return position > 0 ? text.substring(position) : text;
}
private static trimTextFromRightSide(text: string): string {
let position = text.length;
while (true) {
const cnt = this.SPACES.find(sp => text.endsWith(sp, position))?.length || 0;
if (!cnt) {
break;
}
position -= cnt;
}
return position !== text.length ? text.substring(0, position) : text;
}
}
|
mukesh-openchannel/angular-template-libraries
|
src/multiSelectCheckboxList.stories.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { moduleMetadata } from '@storybook/angular';
import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
import { OcMultiSelectCheckboxListComponent } from '@openchannel/angular-common-components/src/lib/form-components';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { action } from '@storybook/addon-actions';
const modules = {
imports: [OcCommonLibModule, NgbModule],
};
export default {
title: 'Multi Select Checkbox List [BEM]',
component: OcMultiSelectCheckboxListComponent,
decorators: [moduleMetadata(modules)],
};
const MultiSelectCheckboxList = (args: OcMultiSelectCheckboxListComponent) => ({
component: OcMultiSelectCheckboxListComponent,
moduleMetadata: modules,
props: args,
});
export const BasicMultiSelectCheckboxList = MultiSelectCheckboxList.bind({});
BasicMultiSelectCheckboxList.args = {
checkboxItemsArray: [
{
label: 'checkbox 1',
},
{
label: 'checkbox 2',
},
{
label: 'checkbox 3',
},
],
resultFormData: action('resultFormData'),
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/meta-tag.service.ts
|
import { Meta } from '@angular/platform-browser';
import { NavigationEnd, Router } from '@angular/router';
import { get } from 'lodash';
import { OCMetaTagConfigType, MetaTagsPageConfig } from '../model/api/meta-tag.model';
/**
* Service used for updating meta-tags in html <head> by current router link.
*
* @example
*
* // Part 1. Init meta tags config.
* export const metaTagsConfig: MetaTagsPageConfig = {
* defaultMetaTags: [
* { name: 'author', content: 'OpenChannel' },
* { name: 'og:url', definitionPath: 'windowUrl' },
* { name: 'og:title', content: 'OpenChannel' },
* { name: 'og:image', content: 'OpenChannel' },
* ],
* pages: [
* {
* routerLinkStartsWith: '/',
* metaTags: [
* { name: 'description', content: 'Custom description.' },
* { name: 'og:title', content: 'Custom title.' },
* { name: 'og:image', content: 'Custom image.' },
* ],
* },
* {
* routerLinkStartsWith: '/details',
* metaTags: [
* { name: 'description', content: 'Default description text, when can\'t get data by definitionPath)', definitionPath: 'app.customData.summary' },
* { name: 'og:title', content: 'Default title text, when can\'t get data by definitionPath)', definitionPath: 'app.name' },
* { name: 'og:image', content: 'https://my.image.com/logo.svg', definitionPath: 'app.customData.logo' },
* ],
* },
* ],
*};
*
* // Part 2. Implement abstract OCMetaTagService for providing meta tags config.
*
* _@Injectable({
* providedIn: 'root',
*})
* export class CustomMetaTagService extends OCMetaTagService {
* constructor(metaService: Meta, router: Router) {
* super(metaService, router);
* }
*
* getMetaTagsConfig(): MetaTagsPageConfig {
* return metaTagsConfig;
* }
*
* initDefaultPageDataForAllPages(): { [name: string]: any } {
* return {
* windowUrl: window.location.href,
* };
* }
*}
*
* // Part 3. Provide this CustomMetaTagService in your main app component.
*
* _@Component({
* selector: 'app-root',
* templateUrl: './app.component.html',
* styleUrls: ['./app.component.scss'],
*})
* export class AppComponent {
* constructor(private customMetaTagService: CustomMetaTagService) {}
* }
*
* // Part 4. (Optional). When used 'definitionPath' field. Like:
* // {
* // routerLinkStartsWith: '/details',
* // metaTags: [
* // { name: 'description', content: 'Default description text, when can\'t get data by definitionPath)', definitionPath: 'app.customData.summary' },
* // { name: 'og:title', content: 'Default title text, when can\'t get data by definitionPath)', definitionPath: 'app.name' },
* // { name: 'og:image', content: 'https://my.image.com/logo.svg', definitionPath: 'app.customData.logo' },
* // ]
* // }
*
* _@Component({...})
* export class MyAppDetailsComponent implements OnInit {
* constructor(
* private appService: AppsService,
* private customMetaTagService: CustomMetaTagService
* ) {}
*
* ngOnInit(): void {
* this.appService.getAppBySafeName('your-safe-name')
* .pipe(
* tap(appResponse => {
* const bu = {
* app: appResponse
* };
* this.customMetaTagService.pushSelectedFieldsToTempPageData(newBufferDataFiled);
* })
* ).subscribe();
* }
* }
*
*/
export abstract class OCMetaTagService {
/**
* Main meta tags config. See: {@link MetaTagsPageConfig}.
*/
private metaTagsConfig: MetaTagsPageConfig = null;
/**
* It is a buffer object with custom data.
* Meta tags created with type {@link CustomMetaDefinition} will be use {@link OCMetaTagService.tempPageData} for getting data by path {@link CustomMetaDefinition#definitionPath}.
*/
private tempPageData = {};
/** List of meta tags patterns. See: {@link OCMetaTagConfigType} */
private rawMetaTags: OCMetaTagConfigType[] = [];
/** List of meta tags from the HTML <head>. When the router link changed, meta tags will be removed from HTML <head> */
private existsMetaTags: HTMLMetaElement[] = [];
constructor(private metaService: Meta, private router: Router) {
// setup meta tags config for different pages.
this.metaTagsConfig = this.getMetaTagsConfig();
// listener for current URL
this.router.events.subscribe(value => {
if (value instanceof NavigationEnd) {
this.initDefaultPageMetaTagsByCurrentRouterLink(value.url);
}
});
}
/**
* Abstract (required) function for getting meta tags config.
* @return {@link MetaTagsPageConfig}
*/
abstract getMetaTagsConfig(): MetaTagsPageConfig;
/**
* When routerLink changed, this function must init default values for {@link OCMetaTagService.tempPageData}.
*/
abstract initDefaultPageDataForAllPages(): { [name: string]: any };
/** Remove {@link OCMetaTagService.existsMetaTags} meta tags */
clearPreviousMetaTagsFromHeader(): void {
if (this.existsMetaTags) {
this.existsMetaTags.forEach(tag => this.metaService.removeTagElement(tag));
}
this.existsMetaTags = [];
}
/** Set a new {@link OCMetaTagService.tempPageData}.*/
setTempPageData<K extends {}>(tempData: K): void {
this.tempPageData = tempData;
}
/** Get old (cloned) {@link OCMetaTagService.tempPageData}.*/
getTempPageData(): any {
return this.tempPageData ? { ...this.tempPageData } : {};
}
/**
* Modify specific fields in {@link OCMetaTagService.tempPageData}. <br>
* After this will be updated field 'content' in meta tags and pushed to HTML <head>
* @example
* this.ocMetaTagService.pushSelectedFieldsToTempPageData({
* app: {
* customData: {
* image: 'https://my.image.com/image.png
* }
* }
* });
*/
pushSelectedFieldsToTempPageData<K extends {}>(partOfTempPageData: K): void {
if (!this.tempPageData) {
this.tempPageData = {};
}
if (partOfTempPageData) {
this.tempPageData = { ...this.tempPageData, ...partOfTempPageData };
}
this.pushMetaTagsToHtmlHead();
}
/**
* Push current tags to HTML <head>.
* Steps:
* 1) Remove previous meta tags from HTML <head>.
* 2) Merge default and custom (page) meta tags by 'name'. Fill content for custom meta tags {@link CustomMetaDefinition}.
* 3) Push filled meta tags to HTML <head>.
*/
private pushMetaTagsToHtmlHead(): void {
this.clearPreviousMetaTagsFromHeader();
this.existsMetaTags = this.metaService.addTags(this.fillContentFieldByTempSiteData(this.tempPageData, this.rawMetaTags));
}
/**
* Merge default and specific (page) meta tags by field 'name'.
*/
private fillContentFieldByTempSiteData<P extends OCMetaTagConfigType>(tempSiteData: any, metaTags: P[]): OCMetaTagConfigType[] {
const metaNames: string[] = [];
const uniqueMetaTags: OCMetaTagConfigType[] = [];
(metaTags || []).forEach(mt => {
if (mt.name && metaNames.indexOf(mt.name) === -1) {
metaNames.push(mt.name);
if (mt.definitionPath) {
uniqueMetaTags.push({
...mt,
content: this.replaceHtmlTags(get(tempSiteData, mt.definitionPath, mt.content)),
});
} else {
uniqueMetaTags.push({ ...mt });
}
}
});
return uniqueMetaTags;
}
private replaceHtmlTags(value: any): string | '' {
if (typeof value === 'string' && value.match(/<[^>]*>/g)) {
const tmp = document.createElement('div');
tmp.innerHTML = value;
return tmp.textContent || tmp.innerText || '';
}
return value ? String(value) : '';
}
private initDefaultPageMetaTagsByCurrentRouterLink(routerLink: string): void {
// find meta tag config by current router link.
const currentPage = (this?.getMetaTagsConfig().pages || []).find(
page =>
routerLink === page.routerLinkStartsWith ||
(page.routerLinkStartsWith !== '/' && routerLink.startsWith(page.routerLinkStartsWith)),
);
this.rawMetaTags = currentPage
? [...(currentPage.metaTags || []), ...(this.metaTagsConfig.defaultMetaTags || [])]
: [...(this.metaTagsConfig.defaultMetaTags || [])];
this.pushSelectedFieldsToTempPageData(this?.initDefaultPageDataForAllPages());
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/service/rich-text-utils/rich-text.service.spec.ts
|
<filename>projects/angular-common-components/src/lib/form-components/service/rich-text-utils/rich-text.service.spec.ts
import { RichTextUtils } from './rich-text.service';
describe('RichTextUtils', () => {
it('Rich text as NULL.', () => {
expect(RichTextUtils.trimRichText(null)).toBe(null);
});
it('Rich text 1', () => {
expect(RichTextUtils.trimRichText('<a></a>')).toBe('<a></a>');
});
it('Rich text 2', () => {
expect(RichTextUtils.trimRichText('<a> value</a>')).toBe('<a>value</a>');
});
it('Rich text 3', () => {
expect(RichTextUtils.trimRichText('<a>value </a>')).toBe('<a>value</a>');
});
it('Rich text 4', () => {
expect(RichTextUtils.trimRichText('<a> value </a>')).toBe('<a>value</a>');
});
it('Rich text 5', () => {
expect(RichTextUtils.trimRichText('<a> <a>value</a> </a>')).toBe('<a><a>value</a></a>');
});
it('Rich text 6', () => {
expect(RichTextUtils.trimRichText('<a> <a> value</a> </a>')).toBe('<a><a>value</a></a>');
});
it('Rich text 7', () => {
expect(RichTextUtils.trimRichText('<a> <a>value </a> </a>')).toBe('<a><a>value</a></a>');
});
it('Rich text 8', () => {
expect(RichTextUtils.trimRichText('<a> <a> value </a> </a>')).toBe('<a><a>value</a></a>');
});
it('Rich text 9', () => {
expect(RichTextUtils.trimRichText('<a> <a> value value </a> </a>')).toBe('<a><a>value value</a></a>');
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/country.service.ts
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CountriesModel, StatesModel } from '../model/api/country-state.model';
/**
* Description: API service for getting countries and states list.<br>
* Link - https://documenter.getpostman.com/view/1134062/T1LJjU52?version=latest <br>
* Version 0.1
* Endpoints:<br>
* GET 'https://countriesnow.space/api/v0.1/countries/iso'<br>
* POST 'https://countriesnow.space/api/v0.1/countries/states'<br>
*/
@Injectable({
providedIn: 'root',
})
export class CountryStateService {
constructor(private http: HttpClient) {}
/**
* Description: Get countries data.
* @returns {Observable<CountriesModel>} `Observable<CountriesModel>`
* ### Example
* `getCountries(): Observable<CountriesModel>;`
*/
getCountries(): Observable<CountriesModel> {
return this.http.get<CountriesModel>('https://countriesnow.space/api/v0.1/countries/iso');
}
/**
* Description: Get states of the chosen country.
* @param {string} countryName (required) full name of the country
* @param {HttpHeaders} headers (optional) additional headers for current request
* @returns {Observable<StatesModel>} `Observable<StatesModel>`
* ### Example
* `getStates("United States"): Observable<StatesModel>;`
*/
getStates(countryName: string, headers?: HttpHeaders): Observable<StatesModel> {
const countryBody = {
country: countryName,
};
return this.http.post<StatesModel>('https://countriesnow.space/api/v0.1/countries/states', countryBody, { headers });
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/title.service.ts
|
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivationStart, Router } from '@angular/router';
/**
*
* Description: Service to work with title.<br>
*
* @param {string} title
*
* Methods:
*
* setPrefix
*
* setPostfix
*
* setSpecialTitle
*
*/
@Injectable({
providedIn: 'root',
})
export class TitleService {
title: string;
constructor(private titleService: Title, private router: Router) {
this.router.events.subscribe(value => {
if (value instanceof ActivationStart) {
const subtitle = value.snapshot.data.title;
this.setPrefix(subtitle);
}
});
}
/**
* Description: Set subtitle on the left side of a pipe
*
* @param {string} subtitle
* @returns {void}
*
* ### Example
* ``
* setPrefix("Prefix")
* ``
*/
setPrefix(subtitle: string): void {
this.setTitleFromTwoParts(subtitle, this.title);
}
/**
* Description: Set subtitle on the right side of a pipe
*
* @param {string} subtitle
* @returns {void}
*
* ### Example
* ``
* setPostfix("Postfix")
* ``
*/
setPostfix(subtitle: string): void {
this.setTitleFromTwoParts(this.title, subtitle);
}
/**
* Description: Set custom title to the right or left side of a pipe.
*
* @param {string} newTitlePart - (required) new title part to override
* @param {boolean} rightPart - (optional) if its 'true' - set new title part on the right side
* @returns {void}
*
* ### Example
* ``
* setSpecialTitle("Title", true)
* ``
*/
setSpecialTitle(newTitlePart: string, rightPart?: boolean): void {
if (rightPart) {
this.setPostfix(newTitlePart);
} else {
this.setPrefix(newTitlePart);
}
}
private setTitleFromTwoParts(firstPart: string, secondPart: string): void {
const normalizedFirstPart = firstPart?.trim();
const normalizedSecondPart = secondPart?.trim();
if (normalizedFirstPart && normalizedSecondPart) {
this.titleService.setTitle(`${normalizedFirstPart} | ${normalizedSecondPart}`);
} else {
this.titleService.setTitle(normalizedFirstPart || normalizedSecondPart || '');
}
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/portal-components/utils/chart.utils.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
export class ChartUtils {
/**
* Number of ticks that should always be on axis.
*/
static PERSISTING_TICKS_NUMBER = 2;
/**
* Calculates visible indexes for axis according to skip ratio and including first and
* last ticks.
* @param {number} tickCount number of ticks on the axis
* @param {number} skipRatio interval according to which ticks should be skipped
* @return {number[]} Array of ticks indexes that should be rendered
*/
static calculateVisibleIndexes = (tickCount: number, skipRatio: number): number[] => {
return [...Array(tickCount).keys()].filter(i => {
const isLast = i === tickCount - 1;
const isFirst = i === 0;
const shouldSkipOneBeforeLast = i % skipRatio === 0 && i + skipRatio >= tickCount;
const shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || shouldSkipOneBeforeLast;
return !shouldSkip || isLast || isFirst;
});
};
/**
* Determines whether to increase skip ratio based on visible ticks and skip ratio.
* @param {number} skipRatio interval according to which ticks should be skipped
* @param {number[]} visibleTicksIndexes Array of ticks indexes that should be rendered
* @return {boolean} Whether to increase skip ratio
*/
static shouldIncreaseSkipRatio = (skipRatio: number, visibleTicksIndexes: number[]): boolean => {
const distanceBetweenLastTicks =
visibleTicksIndexes[visibleTicksIndexes.length - 1] - visibleTicksIndexes[visibleTicksIndexes.length - 2];
const incorrectLastTick = skipRatio === 1 && distanceBetweenLastTicks !== skipRatio;
const increaseSkipRatio = distanceBetweenLastTicks - 1 !== skipRatio || incorrectLastTick;
const evenlyDistributed =
distanceBetweenLastTicks === skipRatio || visibleTicksIndexes.length === ChartUtils.PERSISTING_TICKS_NUMBER;
return increaseSkipRatio && !evenlyDistributed;
};
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-app-list-grid/oc-app-list-grid.component.ts
|
import { Component, EventEmitter, Input, Output, TemplateRef } from '@angular/core';
import { FullAppData } from '@openchannel/angular-common-components/src/lib/common-components';
import { get } from 'lodash';
/**
* Shows vertical list of the apps
*/
@Component({
selector: 'oc-app-list-grid',
templateUrl: './oc-app-list-grid.component.html',
styleUrls: ['./oc-app-list-grid.component.css'],
})
export class OcAppListGridComponent {
/**
* The array of the apps what will be shown in this component.
* @default FullAppData[]
*/
@Input() appList: FullAppData[] = [];
/**
* Message that will be shown when appList array is empty.
* This input required if you want to show the message for case with no apps in component.
*/
@Input() noAppMessage: string = '';
/**
* (Optional)
* Path to the custom Default App Icon that will be shown when the app has no icon.
* @default: standard-app-icon.svg
*/
@Input() defaultAppIcon: string = 'assets/angular-common-components/standard-app-icon.svg';
/**
* (Optional)
* Custom template for the app card. If not set, default app card will be shown.
* @default null
*/
@Input() customAppCardTemplate: TemplateRef<FullAppData>;
/**
* (Optional)
* Base routerLink for one app. Path to the page to which will be redirected, by click on the default app card.
* For the custom app card template you should create your own router link.
*
* ### Example:
* ``
* "app-details" | "apps/details"
* ``
*
* @example
* 'app-details'
* 'apps/details'
*/
@Input() baseLinkForOneApp: string | any;
/**
* (Optional)
* Key name of the App object which will be chosen like navigation parameter for the Router link.
* If not set, no special parameter would be applied for routerLink.
*/
@Input() appNavigationParam: string = '';
/**
* @deprecated
* The emitter reports that current app card has been clicked. Return current app object data.
* It is deprecated. Use {@link baseLinkForOneApp} with {@link appNavigationParam} for redirect.
*/
@Output() readonly gotoDetails: EventEmitter<FullAppData> = new EventEmitter<FullAppData>();
/**
* Function which getting data about current App of the app card and emit it to parent.
* @param app app of the current app card
*/
viewDetails(app: FullAppData): void {
this.gotoDetails.emit(app);
}
/**
* Function which returns data from the App object by key {@link appNavigationParam}.
* If key does not applied - will return empty string.
* @param app app of the current app card
*/
getAppValueByParameter(app: FullAppData): string {
if (this.appNavigationParam) {
return get(app, this.appNavigationParam);
}
return '';
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/developer.model.ts
|
<filename>projects/angular-common-services/src/lib/model/api/developer.model.ts
export interface DeveloperModel {
developerId?: string;
accountCount?: number;
appCount?: number;
created?: number;
email?: string;
name?: string;
type?: string;
roles?: string[];
permissions?: string[];
customData?: any;
}
export interface DeveloperAccountModel extends DeveloperModel {
developerAccountId?: string;
}
export interface DeveloperDataModel {
developer?: DeveloperModel;
}
export interface DeveloperUpdateModel {
email?: string;
name?: string;
type?: string;
customData?: any;
}
export interface UpdateDeveloperAccountModel extends DeveloperUpdateModel {
developerId?: string;
}
export interface DeveloperTypeModel {
developerTypeId: string;
label: string;
description?: string;
createdDate: number;
fields: DeveloperTypeFieldModel[];
}
export interface DeveloperTypeFieldModel {
id: string;
label: string;
type: string;
attributes?: any;
description?: string;
fields?: DeveloperTypeFieldModel[];
subFieldDefinitions?: DeveloperTypeFieldModel[];
defaultValue?: any;
placeholder?: string;
options?: DeveloperTypeOptionModal[] | string[];
specialType?: string;
}
export interface DeveloperTypeOptionModal {
value: string;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-profile-navbar/oc-profile-navbar.component.ts
|
<gh_stars>0
import { Component, Input } from '@angular/core';
/**
* Profile navbar component. Used to navigate the profile pages.
* Consists of a button and ngb dropdown menu with items.
* @type {string}.
*/
@Component({
selector: 'oc-profile-navbar',
templateUrl: './oc-profile-navbar.component.html',
styleUrls: ['./oc-profile-navbar.component.css'],
})
export class OcProfileNavbarComponent {
/**
* Username initials that will be shown in the avatar circle.
* If not set - avatar circle will not be shown.
* @type {string}.
*/
@Input() initials: string;
/**
* Name of the user that will be shown at the top near the avatar circle.
* If not set - username text will not be shown.
* @type {string}.
*/
@Input() username: string;
/**
* Role of the user that will be shown at the bottom near the avatar circle.
* If not set - role text will not be shown.
* @type {string}.
*/
@Input() role: string;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/portal-components/oc-app-table/oc-app-table.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule, NgModel } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { BrowserModule, By } from '@angular/platform-browser';
import { OcAppTableCellPattern, OcAppTableComponent } from './oc-app-table.component';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { CamelcasePipe, GetTextByPathPipe, HtmlTagsReplacerPipe } from '@openchannel/angular-common-components/src/lib/common-components';
import { AppGridSortOptions, AppListing, FieldPathConfig } from '../models/app-listing.model';
import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock';
import { cloneDeep } from 'lodash';
import { TemplateRef } from '@angular/core';
const propertiesMock: AppListing = {
layout: 'table',
data: {
pageNumber: 1,
pages: 2,
count: 1,
list: [
{
appId: 'testId',
lastUpdated: 1616406353,
customData: { icon: 'test', summary: '<p class="text">Summary text</p>' },
version: 1,
name: 'name',
safeName: [],
developerId: 'devId',
model: [],
submittedDate: 1616406353,
created: 1616406353,
rating: 11,
reviewCount: 11,
status: { reason: 'test', lastUpdated: 1616406353, modifiedBy: 'test', value: 'pending' },
statistics: null,
isLive: false,
},
],
},
options: ['EDIT', 'DELETE', 'SUBMIT', 'PUBLISH', 'PREVIEW'],
};
describe('OcAppTableComponent', () => {
let component: OcAppTableComponent;
let fixture: ComponentFixture<OcAppTableComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
OcAppTableComponent,
MockSvgIconComponent,
CamelcasePipe,
HtmlTagsReplacerPipe,
GetTextByPathPipe,
OcAppTableCellPattern,
],
providers: [NgModel],
imports: [FormsModule, CommonModule, BrowserModule, InfiniteScrollModule, NgbModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcAppTableComponent);
component = fixture.componentInstance;
component.properties = cloneDeep(propertiesMock);
component.sortOptions = {
name: -1,
status: -1,
created: -1,
};
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should emit pageScrolled event, when table was scrolled', () => {
jest.spyOn(component.pageScrolled, 'emit');
const tableDE = fixture.debugElement.query(By.css('.app-grid-table'));
tableDE.triggerEventHandler('scrolled', {});
expect(component.pageScrolled.emit).toHaveBeenCalled();
});
it('should emit correct action, when action button was clicked', () => {
const appAction = 'EDIT';
jest.spyOn(component, 'action');
jest.spyOn(component.menuClicked, 'emit');
const editActionDE = fixture.debugElement.query(By.css('.menu-edit'));
editActionDE.triggerEventHandler('click', {});
const { appId, version } = propertiesMock.data.list[0];
const actionObjectToEmit = {
action: appAction,
appId,
appVersion: version,
isChild: false,
};
expect(component.action).toHaveBeenCalledWith(appAction, appId, version, false);
expect(component.menuClicked.emit).toHaveBeenCalledWith(actionObjectToEmit);
});
it('should emit correct sort option, when table header was clicked', () => {
const sortField = 'name';
const newSortOptions = {
name: 1,
status: -1,
created: -1,
};
jest.spyOn(component, 'sortAppsByKey');
jest.spyOn(component.sortOptionsChosen, 'emit');
const nameHeaderDE = fixture.debugElement.query(By.css(`.app-grid-table__header__cell-name-content`));
nameHeaderDE.triggerEventHandler('click', {});
expect(component.sortAppsByKey).toHaveBeenCalledWith(sortField);
expect(component.sortOptionsChosen.emit).toHaveBeenCalledWith({
sortOptions: newSortOptions,
changedSortOption: sortField,
});
});
it('should render correct actions', () => {
const actionsToRender = ['edit', 'delete', 'publish', 'submit', 'preview'];
component.properties.previewTemplate = 'template-url';
component.properties.data.list[0].status.value = 'inDevelopment';
fixture.detectChanges();
const actionButtonsDE = fixture.debugElement.queryAll(By.css('.menu'));
const renderedActions = actionButtonsDE.map(actionButtonDE => actionButtonDE.nativeElement.textContent.toLowerCase().trim());
expect(actionsToRender.sort()).toEqual(renderedActions.sort());
});
it('should correctly determine whether to render item action or not by needToShowItem function', () => {
expect(component.needToShowItem('SUSPEND', 'suspended', 'developer')).toBeFalsy();
expect(component.needToShowItem('UNSUSPEND', 'suspended', 'developer')).toBeTruthy();
expect(component.needToShowItem('UNSUSPEND', 'suspended', 'user')).toBeFalsy();
expect(component.needToShowItem('SUSPEND', 'approved', 'developer')).toBeTruthy();
});
it('table headers should invoke sortAppsBy function with correct value', () => {
const selectorSortCriteriaMap = {
'.app-grid-table__header__cell-name-content': 'name',
'.app-grid-table__header__cell-create-date-content': 'created',
'.app-grid-table__header__cell-status-content': 'status',
};
jest.spyOn(component, 'sortAppsByKey');
Object.entries(selectorSortCriteriaMap).forEach(([selector, sortCriteria]) => {
const headerDE = fixture.debugElement.query(By.css(selector));
headerDE.triggerEventHandler('click', {});
expect(component.sortAppsByKey).toHaveBeenCalledWith(sortCriteria);
});
});
it('should render correct text, if no apps were provided', () => {
const textToRender = 'No apps found';
component.noAppMessage = textToRender;
component.properties.data.list = [];
fixture.detectChanges();
const noDataTd = fixture.debugElement.query(By.css('.app-grid-table__bottom-empty-list')).nativeElement;
expect(noDataTd.textContent.trim()).toBe(textToRender);
});
it('should render correct sorting icon', () => {
const sortOptions: AppGridSortOptions = {
name: -1,
status: -1,
created: -1,
};
const ascendingSortIconPath = 'https://some-site.com/ascending-sort-icon-path';
const descendingSortIconPath = 'https://some-site.com/descending-sort-icon-path';
component.ascendingSortIcon = ascendingSortIconPath;
component.descendingSortIcon = descendingSortIconPath;
component.sortOptions = sortOptions;
fixture.detectChanges();
component.sortOptions = { ...sortOptions, name: -1 };
fixture.detectChanges();
let sortIcon = fixture.debugElement.query(By.css(`.app-grid-table__header__sort-icon`)).componentInstance;
expect(sortIcon.src).toBe(descendingSortIconPath);
component.sortOptions = { ...sortOptions, name: 1 };
fixture.detectChanges();
sortIcon = fixture.debugElement.query(By.css(`.app-grid-table__header__sort-icon`)).componentInstance;
expect(sortIcon.src).toBe(ascendingSortIconPath);
});
it('should render correct app icon', () => {
const defaultAppIconUrl = 'https://some-site.com/default-app-icon-path';
const appIconUrl = 'https://some-site.com/app-icon-path';
component.defaultAppIcon = defaultAppIconUrl;
component.properties.data.list[0].customData.icon = '';
fixture.detectChanges();
let appIcon = fixture.debugElement.query(By.css(`.app-grid-table__row__cell-name-content-icon`)).nativeElement;
expect(appIcon.src).toBe(defaultAppIconUrl);
component.properties.data.list[0].customData.icon = appIconUrl;
component.properties.data.list[0] = { ...component.properties.data.list[0] };
fixture.detectChanges();
appIcon = fixture.debugElement.query(By.css(`.app-grid-table__row__cell-name-content-icon`)).nativeElement;
expect(appIcon.src).toBe(appIconUrl);
});
it('should set correct src to dropdown dots', () => {
const dropdownDotsUrl = 'https://some-site.com/dropdown-dots-path';
component.menuUrl = dropdownDotsUrl;
fixture.detectChanges();
const dropdownDotsImg = fixture.debugElement.query(By.css(`.app-grid-table__row__cell-app-options-dropdown-dots`)).nativeElement;
expect(dropdownDotsImg.src).toBe(dropdownDotsUrl);
});
it('should render child elements for app, if they exist', () => {
let childTrDE = fixture.debugElement.query(By.css(`.app-grid-table__row_child`));
expect(childTrDE).toBeFalsy();
component.properties.data.list[0].children = [cloneDeep(component.properties.data.list[0])];
fixture.detectChanges();
childTrDE = fixture.debugElement.query(By.css(`.app-grid-table__row_child`));
expect(childTrDE).toBeTruthy();
});
it('should render correct app name, version, summary, created date and status', () => {
const { name, version } = component.properties.data.list[0];
const selectorExpectedValueMap = {
'.app-grid-table__row__cell-name-content-text-title': name,
'.app-grid-table__row__cell-name-content-text-version': `v. ${version}`,
'.app-grid-table__row__cell-summary-text': `Summary text`,
'.app-grid-table__row__cell-create-date-text': `1/19/1970`,
'.app-grid-table__row__cell-status-content-text': 'Pending',
};
Object.entries(selectorExpectedValueMap).forEach(([selector, expectedValue]) => {
const element = fixture.debugElement.query(By.css(selector)).nativeElement;
expect(element.textContent.trim()).toBe(expectedValue);
});
});
it('should set fieldsPathConfig in selectAppFieldByPathConfig', () => {
const newFieldsPathConfig: FieldPathConfig = {
appIconPath: 'customPathToIcon.icon',
appDescriptionPath: 'customData.summary',
};
component.selectAppFieldByPathConfig = { appIconPath: newFieldsPathConfig.appIconPath };
expect(component.fieldsPathConfig).toEqual(newFieldsPathConfig);
});
it('updateSortDirection function should set sort criteria to -1, if it was not defined', () => {
const sortOptions: AppGridSortOptions = {
name: null,
status: -1,
created: -1,
};
(component as any).updateSortDirection(sortOptions, 'name');
expect(sortOptions.name).toBe(-1);
});
it('should fill _defaultColumnsPattern in fillDefaultColumnsPattern function', () => {
(component as any)._defaultColumnsPattern = {};
component.fillDefaultColumnsPattern();
Object.entries((component as any)._defaultColumnsPattern).forEach(([_, template]) => {
const { headerCellTemplate, rowCellTemplate } = template as any;
expect(headerCellTemplate instanceof TemplateRef).toBeTruthy();
expect(rowCellTemplate instanceof TemplateRef).toBeTruthy();
});
});
it('modifyColumnsConfigByUserConfig should return correct config', () => {
const defaultConfig = (component as any)._defaultColumnsPattern;
const newConfig = {
name: {
headerCellTemplate: { customTemplate: 1 } as unknown as TemplateRef<any>,
rowCellTemplate: { customTemplate: 2 } as unknown as TemplateRef<any>,
},
};
const resultConfig = {
...defaultConfig,
...newConfig,
};
expect(component.modifyColumnsConfigByUserConfig(newConfig, defaultConfig)).toEqual(resultConfig);
});
it('modifyColumnsConfigByUserConfig should modify cellTemplate only if it is present in newConfig ', () => {
const defaultConfig = (component as any)._defaultColumnsPattern;
const newConfig = {
name: {
headerCellTemplate: { customTemplate: 1 } as unknown as TemplateRef<any>,
},
};
const resultConfig = {
...defaultConfig,
name: {
headerCellTemplate: newConfig.name.headerCellTemplate,
rowCellTemplate: defaultConfig.name.rowCellTemplate,
},
};
expect(component.modifyColumnsConfigByUserConfig(newConfig, defaultConfig)).toEqual(resultConfig);
});
it('mapColumnsConfigToColumnsArray should return correct columns', () => {
const defaultColumnsPattern = (component as any)._defaultColumnsPattern;
const activeColumns = ['name', 'summary'];
const resultColumns = activeColumns.map(column => {
return {
columnId: column,
headerCellTemplate: defaultColumnsPattern[column].headerCellTemplate,
rowCellTemplate: defaultColumnsPattern[column].rowCellTemplate,
};
});
expect(component.mapColumnsConfigToColumnsArray(activeColumns, defaultColumnsPattern)).toEqual(resultColumns);
});
it('mapColumnsConfigToColumnsArray should add column to return array only if headerCellTemplate and rowCellTemplate are present', () => {
const defaultColumnsPattern = (component as any)._defaultColumnsPattern;
const modifiedDefaultColumnsPattern = {
...defaultColumnsPattern,
summary: {
headerCellTemplate: null,
rowCellTemplate: defaultColumnsPattern.summary.rowCellTemplate,
},
status: {
headerCellTemplate: defaultColumnsPattern.status.headerCellTemplate,
rowCellTemplate: null,
},
};
const activeColumns = ['name', 'summary', 'status'];
const resultColumns = [
{
columnId: 'name',
headerCellTemplate: defaultColumnsPattern.name.headerCellTemplate,
rowCellTemplate: defaultColumnsPattern.name.rowCellTemplate,
},
];
expect(component.mapColumnsConfigToColumnsArray(activeColumns, modifiedDefaultColumnsPattern)).toEqual(resultColumns);
});
it('columnsPattern should be filled in ngAfterViewInit hook', () => {
jest.spyOn(component, 'ngAfterViewInit');
component.columnsPattern = [];
fixture.detectChanges();
// tslint:disable-next-line:no-lifecycle-call
component.ngAfterViewInit();
const columnsIds = component.columnsPattern.map(columnPattern => {
expect(columnPattern.rowCellTemplate instanceof TemplateRef).toBeTruthy();
expect(columnPattern.headerCellTemplate instanceof TemplateRef).toBeTruthy();
return columnPattern.columnId;
});
expect(columnsIds.sort()).toEqual(component.activeColumns.sort());
});
it('should call cdRef.detectChanges in ngAfterViewInit hook', () => {
jest.spyOn((component as any).cdRef, 'detectChanges');
// tslint:disable-next-line:no-lifecycle-call
component.ngAfterViewInit();
expect((component as any).cdRef.detectChanges).toHaveBeenCalled();
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-app-card/oc-app-card.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcAppCardComponent } from './oc-app-card.component';
import { By } from '@angular/platform-browser';
import { Location } from '@angular/common';
import { PricePipe } from '../../common-components/pipe/price.pipe';
import { FullAppData, StatElement, HtmlTagsReplacerPipe } from '@openchannel/angular-common-components/src/lib/common-components';
import { MockRatingComponent, MockRoutingComponent } from '@openchannel/angular-common-components/src/mock/mock';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
describe('OcAppCardComponent', () => {
let component: OcAppCardComponent;
let fixture: ComponentFixture<OcAppCardComponent>;
let location: Location;
let appData: FullAppData;
let router: Router;
const statElement: StatElement = {
'90day': 20,
'30day': 10,
total: 20,
};
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcAppCardComponent, MockRatingComponent, MockRoutingComponent, PricePipe, HtmlTagsReplacerPipe],
imports: [RouterTestingModule.withRoutes([])],
}).compileComponents();
location = TestBed.inject(Location);
router = TestBed.inject(Router);
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcAppCardComponent);
component = fixture.componentInstance;
appData = {
appId: '34343jfgi3423',
icon: '',
name: 'Test App',
model: [
{
type: 'recurring',
price: 5,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 4.2,
reviewCount: 20,
summary: 'Some test summary',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3232gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: 'approved',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: statElement,
downloads: statElement,
developerSales: statElement,
totalSales: statElement,
ownerships: statElement,
reviews: statElement,
},
isLive: true,
};
component.app = appData;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show data', () => {
const priceInfo: HTMLSpanElement = fixture.debugElement.query(By.css('.oc-card__content-price')).nativeElement;
const summaryInfo: HTMLParagraphElement = fixture.debugElement.query(By.css('.oc-card__content-summary')).nativeElement;
expect(priceInfo.textContent).toContain('€0.05/mon');
expect(summaryInfo.textContent).toContain('Some test summary');
});
it('should redirect on router link', async () => {
jest.spyOn(component.clickByAppCard, 'emit');
const dropbox = fixture.debugElement.query(By.css('.oc-card__content-name')).nativeElement;
dropbox.click();
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(component.clickByAppCard.emit).toHaveBeenCalledWith(appData);
});
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-featured-apps/oc-featured-apps.component.ts
|
import { Component, EventEmitter, Input, Output, TemplateRef } from '@angular/core';
import { FullAppData, HeadingTag } from '@openchannel/angular-common-components/src/lib/common-components';
import { get } from 'lodash';
/**
* Featured apps component. Renders a list of applications, that are featured by a user.
* Located on the main page.
* Shows a list with featured apps, which are clickable for more detailed description.
*/
@Component({
selector: 'oc-featured-apps',
templateUrl: './oc-featured-apps.component.html',
styleUrls: ['./oc-featured-apps.component.css'],
})
export class OcFeaturedAppsComponent {
/**
* List of Featured apps. Must contain the fields: "icon", "name", "summary", "appId".
* @type {FullAppData[]}.
* Default empty.
*/
@Input() data: FullAppData[] = [];
/**
* A title of the featured apps.
* @type {string}.
* @default: 'Featured'
*/
@Input() label: string = 'Featured';
/**
* Heading tag of label
* @type {HeadingTag}.
* @example.
* 'h2'.
*/
@Input() headingTag: HeadingTag = 'h2';
/**
* Heading tag of app label
* @type {HeadingTag}.
* @example.
* 'h2'.
*/
@Input() appHeadingTag: HeadingTag = 'h3';
/**
* The message that will be shown when there are no featured apps.
* @type {string}.
* @default: 'No Featured App'.
*/
@Input() emptyDataMessage: string = 'No Featured App';
/**
* List of classes that will be added to the default class list.
* @type {string}.
* @default: ''.
*/
@Input() customClasses: string = '';
/**
* Custom template for the featured app card.
* @type {FullAppData}.
*/
@Input() customFeaturedAppCardTemplate: TemplateRef<FullAppData>;
/**
* Router link for each app card.
* Will end with chosen navigation parameter.
* Using for the default app card. If you are using the custom card - you must create your own router link on the card template.
* @type {string}.
* @default: ''.
* @example.
* '/details/ap-application-regression-14may'.
*/
@Input() mainRouterLink: string = '';
/**
* Key name of the App object which will be chosen like navigation parameter for the Router link.
* Using only with the default app card template.
* @type {string}.
* @example.
* 'appId'.
*/
@Input() navigationParam: string;
/**
* @deprecated
* Emitter for click by App card. It is deprecated. If you want to get data for redirect only - use {@link mainRouterLink}
* with {@link navigationParam}.
* @type {FullAppData}.
*/
@Output() readonly clickByAppCard: EventEmitter<FullAppData> = new EventEmitter<FullAppData>();
/**
* It is used to get a part of an app router link.
* Returns app navigation param or empty string value.
*/
getAppValueByParameter(app: FullAppData): string {
if (this.navigationParam) {
return get(app, this.navigationParam);
}
return '';
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/user-account.service.ts
|
<filename>projects/angular-common-services/src/lib/service/user-account.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Page } from '../model/api/page.model';
import { HttpRequestService } from './http-request-services';
import { UserAccount } from '../model/api/user.model';
import { OcHttpParams } from '../model/api/http-params-encoder-model';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
*
* Description: API service for getting and modifying User Account model.<br>
*
* Documentation: <a href="https://support.openchannel.io/documentation/api/#481-user">Openchannel API</a><br>
*
* Endpoints:<br>
*
* GET 'v2/userAccounts/all'<br>
*
* GET 'v2/userAccounts/this'<br>
*
* PATCH 'v2/userAccounts/this'<br>
*
* DELETE 'v2/userAccounts/this'<br>
*
* GET 'v2/userAccounts/{userAccountId}'<br>
*
* DELETE 'v2/userAccounts/{userAccountId}'<br>
*
*/
@Injectable({
providedIn: 'root',
})
export class UserAccountService {
constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
* Description: Getting data about none-developer users
*
* @returns {Observable<UserAccount>} Observable<UserAccount>
*
* ### Example
*``
* getUserAccount()
*``
*/
getUserAccount(): Observable<UserAccount> {
return this.httpService.get(`${this.apiPaths.userAccounts}/this`);
}
/**
*
* Description: Get list of User Accounts with pagination
*
* @param {number} pageNumber - (optional) Current page index. Starts from >= 1.
* @param {number} limit - (optional) Count apps into response. Starts from >= 1.
* @param {string} sort - (optional) Sort apps by specific field.
* @param {string} query - (optional) Your specific search query.
* @returns {Observable<Page<UserAccount>>} Observable<Page<UserAccount>>
*
* ### Example
*``
* getUserAccounts(1,10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}")
*``
*/
getUserAccounts(pageNumber?: number, limit?: number, sort?: string, query?: string): Observable<Page<UserAccount>> {
const mainUrl = `${this.apiPaths.userAccounts}/all`;
const params = new OcHttpParams()
.append('pageNumber', String(pageNumber))
.append('limit', String(limit))
.append('query', query)
.append('sort', sort);
return this.httpService.get(mainUrl, { params });
}
/**
* Description: Update User Account fields for some particular user
*
* @param {string} userAccountId - (required)
* @param {boolean} skipTypeValidation - (optional)
* @param {any} body
* @returns {Observable<UserAccount>} Observable<UserAccount>
*
* ### Example
*``
* updateUserAccountFieldsForAnotherUser('8ahs9d87has8d7h', true, {name: 'Test'});
*``
*/
updateUserAccountFieldsForAnotherUser(userAccountId: string, skipTypeValidation: boolean, body: any): Observable<UserAccount> {
const mainUrl = `${this.apiPaths.userAccounts}/${encodeURIComponent(userAccountId)}`;
return this.httpService.patch(mainUrl, body, {
params: new OcHttpParams().append('skipTypeValidators', String(skipTypeValidation)),
});
}
/**
* Description: Updating user account fields
*
* @param {any} accountData - data from user profile form
* @returns {Observable<any>} Observable<any>
*
* ### Example
*``
* updateUserAccount({name: 'Test'});
*``
*/
updateUserAccount(accountData: any): Observable<any> {
return this.httpService.patch(`${this.apiPaths.userAccounts}/this`, accountData);
}
/**
* Description: Deleting User Account by Id
*
* @param {string} userAccountId - (required) Account Id to delete
* @returns {Observable<any>} Observable<any>
*
* ### Example
*``
* deleteUserAccount('a8s6gd978asgd8');
*``
*/
deleteUserAccount(userAccountId: string): Observable<any> {
return this.httpService.delete(`${this.apiPaths.userAccounts}/${encodeURIComponent(userAccountId)}`);
}
/**
* Description: Deleting User Accaunt of none-developer
*
* @returns {Observable<any>} Observable<any>
*
* ### Example
*``
* deleteCurrentUserAccount();
*``
*/
deleteCurrentUserAccount(): Observable<any> {
return this.httpService.delete(`${this.apiPaths.userAccounts}/this`);
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/invite-user.service.ts
|
<filename>projects/angular-common-services/src/lib/service/invite-user.service.ts
import { Injectable } from '@angular/core';
import { Page } from '../model/api/page.model';
import { InviteDeveloperModel, InviteUserModel } from '../model/api/invite-user.model';
import { Observable } from 'rxjs';
import { HttpRequestService } from './http-request-services';
import { OcHttpParams } from '../model/api/http-params-encoder-model';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
* Description: API service to manage User Invites.<br>
*
* Endpoints:<br>
*
* GET 'v2/invites/users'<br>
*
* GET 'v2/invites/users/byToken/{token}'<br>
*
* POST 'v2/invites/users/byId/{inviteId}'<br>
*
* DELETE 'v2/invites/users/byId/{inviteId}'<br>
*
* GET 'v2/invites/developers'<br>
*
* GET 'v2/invites/developers/byToken/{token}'<br>
*
* POST 'v2/invites/developers/byId/{inviteId}'<br>
*
* DELETE 'v2/invites/users/byId/{inviteId}'<br>
*
* POST 'v2/invites/{userType}'<br>
*/
@Injectable({
providedIn: 'root',
})
export class InviteUserService {
constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
* Description: Get list of user invites with pagination
*
* @param {number} pageNumber - (optional) Current page index. Starts from >= 1
* @param {number} limit - (optional) Count user invites into response. Starts from >= 1
* @param {string} sort - (optional) Sort user invites by specific field
* @param {string} query - (optional) Your specific search query
* @returns {Observable<Page<InviteUserModel>>} `Observable<Page<InviteUserModel>>`
*
* ### Example
*
* `getUserInvites(1,10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}")`
*/
getUserInvites(pageNumber?: number, limit?: number, sort?: string, query?: string): Observable<Page<InviteUserModel>> {
const mainUrl = `${this.apiPaths.invites}/users`;
const params = new OcHttpParams()
.append('pageNumber', String(pageNumber))
.append('limit', String(limit))
.append('sort', sort)
.append('query', query);
return this.httpService.get(mainUrl, { params });
}
/**
*
* Description: Get full invite info by token
*
* @param {string} token - (required)
* @returns {Observable<InviteUserModel>} `Observable<InviteUserModel>`
*
* ### Example
*
* getUserInviteInfoByToken('<PASSWORD>')
*/
getUserInviteInfoByToken(token: string): Observable<InviteUserModel> {
return this.httpService.get(`${this.apiPaths.invites}/users/byToken/${token}`);
}
/**
*
* Description: Sending invite to the user
*
* @param {any} inviteData - (required) data from invite form
* @param {string} templateId - (required) id of the email template
* @param {string} company - (required) name of the inviter company
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `sendUserInvite('ha9s8hd9a8shd','company', {});`
*/
sendUserInvite(company: string, inviteData: any, templateId: string = 'default'): Observable<any> {
return this.sendInvite('users', company, inviteData, { userInviteTemplateId: templateId });
}
/**
*
* Description: Edit developer invite
*
* @param {string} inviteData - (required) data from invite form
* @param {any} inviteId - (required) id of the invite
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* editUserInvite('807has87dha8', {})
*/
editUserInvite(inviteId: string, inviteData: any): Observable<any> {
return this.httpService.post(`${this.apiPaths.invites}/users/byId/${inviteId}`, inviteData);
}
/**
*
* Description: Delete developer invite
*
* @param {string} inviteId - (required)
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* deleteUserInvite('uahs09d8a9sd8h')
*/
deleteUserInvite(inviteId: string): Observable<any> {
return this.httpService.delete(`${this.apiPaths.invites}/users/byId/${inviteId}`);
}
/**
*
* Description: Get list of developer invites with pagination
*
* @param {number} pageNumber - (optional) Current page index. Starts from >= 1
* @param {number} limit - (optional) Count user invites into response. Starts from >= 1
* @param {string} sort - (optional) Sort user invites by specific field
* @param {string} query - (optional) Your specific search query
* @returns {Observable<Page<InviteDeveloperModel>>} `Observable<Page<InviteDeveloperModel>>`
*
* ### Example
*
* `getDeveloperInvites(1,10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}")`
*/
getDeveloperInvites(pageNumber?: number, limit?: number, sort?: string, query?: string): Observable<Page<InviteDeveloperModel>> {
const mainUrl = `${this.apiPaths.invites}/developers`;
const params = new OcHttpParams()
.append('pageNumber', String(pageNumber))
.append('limit', String(limit))
.append('query', query)
.append('sort', sort);
return this.httpService.get(mainUrl, { params });
}
/**
*
* Description: Sending invite to the user
*
* @param {any} inviteData - (required) data from invite form
* @param {string} templateId - (required) id of the email template
* @param {string} company - (required) name of the inviter company
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `sendDeveloperInvite('company', {})`
*/
sendDeveloperInvite(company: string, inviteData: any, templateId: string = 'default'): Observable<any> {
return this.sendInvite('developers', company, inviteData, { developerInviteTemplateId: templateId });
}
/**
*
* Description: Edit developer invite
*
* @param {any} inviteData - (required) data from invite form
* @param {string} inviteId - (required) id of the invite
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `editDeveloperInvite('9ahs09d8jas9d8', {})`
*/
editDeveloperInvite(inviteId: string, inviteData: any): Observable<any> {
return this.httpService.post(`${this.apiPaths.invites}/developers/byId/${inviteId}`, inviteData);
}
/**
*
* Description: In order to validate the invite token and get the details for the invite
*
* @param {string} token - (required)
* @returns {Observable<InviteDeveloperModel>} `Observable<InviteDeveloperModel>`
*
* ### Example
*
* `getDeveloperInviteInfoByToken('<PASSWORD>')`
*/
getDeveloperInviteInfoByToken(token: string): Observable<InviteDeveloperModel> {
return this.httpService.get(`${this.apiPaths.invites}/developers/byToken/${token}`);
}
/**
*
* Description: Delete user invite
*
* @param {string} inviteId - (required)
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `deleteDeveloperInvite('9ahs09d8jas9d')`
*/
deleteDeveloperInvite(inviteId: string): Observable<any> {
return this.httpService.delete(`${this.apiPaths.invites}/developers/byId/${inviteId}`);
}
/**
*
* Description: Send invite to user or developer
*
* @param {'developers'| 'users'} userType - (required) Chose user type
* @param {string} company - (required) Company name
* @param {any} userInviteData - (required) Invite data
* @param {{developerInviteTemplateId} | {userInviteTemplateId}} inviteIDs - (required)
* @returns {Observable<any>} `Observable<any>`
*
*
* ### Example
*
* `sendInvite('developers', 'company', {}, 'aos<PASSWORD>')`
*/
private sendInvite(
userType: 'developers' | 'users',
company: string,
userInviteData: any,
inviteIDs: { developerInviteTemplateId: string } | { userInviteTemplateId: string },
): Observable<any> {
const body = {
...userInviteData,
...inviteIDs,
customData: { company, ...(userInviteData?.customData ? userInviteData.customData : {}) },
};
return this.httpService.post(`${this.apiPaths.invites}/${userType}`, body);
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-text-search/oc-text-search.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcTextSearchComponent } from './oc-text-search.component';
import { By } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MockButtonComponent, MockSvgIconComponent, MockTagComponent } from '@openchannel/angular-common-components/src/mock/mock';
const tagsTitlesMocked = ['collections', 'categories', 'search criteria'];
describe('OcTextSearchComponent', () => {
let component: OcTextSearchComponent;
let fixture: ComponentFixture<OcTextSearchComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcTextSearchComponent, MockButtonComponent, MockSvgIconComponent, MockTagComponent],
imports: [FormsModule, HttpClientTestingModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcTextSearchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain value in input', () => {
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = '<NAME>!';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.searchText).toBe('Hello test!');
});
it('should emit text value', () => {
const input = fixture.debugElement.query(By.css('input'));
input.nativeElement.value = '<NAME>!';
const enterSearchEmitFunction = jest.spyOn(component.enterSearch, 'emit');
fixture.detectChanges();
input.nativeElement.dispatchEvent(new Event('input'));
input.triggerEventHandler('keydown.enter', {});
fixture.detectChanges();
expect(enterSearchEmitFunction).toHaveBeenCalledWith('Hello test!');
});
it('should emit text value on click', () => {
const input: HTMLInputElement = fixture.debugElement.query(By.css('input')).nativeElement;
const img: HTMLImageElement = fixture.debugElement.query(By.css('svg-icon')).nativeElement;
input.value = '<NAME>!';
const enterSearchEmitFunction = jest.spyOn(component.enterSearch, 'emit');
fixture.detectChanges();
input.dispatchEvent(new Event('input'));
img.click();
fixture.detectChanges();
expect(enterSearchEmitFunction).toHaveBeenCalledWith('Hello test!');
});
it('should emit tag index on close button tag click', () => {
const tagIndexToDelete = 0;
component.tagsTitles = [...tagsTitlesMocked];
fixture.detectChanges();
const tags = fixture.debugElement.queryAll(By.directive(MockTagComponent));
const tagInstanceToDelete = tags.find(tag => tag.componentInstance.title === tagsTitlesMocked[tagIndexToDelete]).componentInstance;
const tagToDeleteEmitFunction = jest.spyOn(component.tagDeleted, 'emit');
tagInstanceToDelete.clickEmitter.emit();
fixture.detectChanges();
expect(tagToDeleteEmitFunction).toHaveBeenCalledWith(tagIndexToDelete);
});
it('should emit on clear all button click', () => {
component.tagsTitles = [...tagsTitlesMocked];
fixture.detectChanges();
const clearAllButton = fixture.debugElement.query(By.css('.text-search__clear-tags-button')).nativeElement;
const clearAllTagsClickedEmitFunction = jest.spyOn(component.allTagsDeleted, 'emit');
clearAllButton.click();
fixture.detectChanges();
expect(clearAllTagsClickedEmitFunction).toHaveBeenCalled();
});
it('clear all button type should be same as clearAllButtonType passed value', () => {
const primaryType = 'primary';
component.tagsTitles = [...tagsTitlesMocked];
component.clearAllButtonType = primaryType;
fixture.detectChanges();
const clearAllButton = fixture.debugElement.query(By.css('.text-search__clear-tags-button')).componentInstance;
expect(clearAllButton.type).toBe(primaryType);
});
it('clear all button should be absent when showClearAllTagsButton = false', () => {
component.tagsTitles = [...tagsTitlesMocked];
component.showClearAllTagsButton = false;
fixture.detectChanges();
const clearAllButton = fixture.debugElement.query(By.css('.text-search__clear-tags-button'));
expect(clearAllButton).toBeNull();
});
it('clear all button customClass should depend on button type', () => {
component.tagsTitles = [...tagsTitlesMocked];
component.clearAllButtonType = 'primary';
fixture.detectChanges();
const clearAllButton = fixture.debugElement.query(By.css('.text-search__clear-tags-button')).componentInstance;
expect(clearAllButton.customClass).toBe('text-search__clear-tags-button-small');
component.clearAllButtonType = 'link';
fixture.detectChanges();
expect(clearAllButton.customClass).toBe('');
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-radio-button/oc-radio-button.component.ts
|
import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { TransformTextType } from '../model/text-transfrom-pipe.model';
/**
* Represents the simple radio button component. It supports the `ngModel` and `formControl`.
* @example
* <oc-radio-button [value]="myValue"
* labelText="Test label"
* [ngModel]="resultValue"
* (ngModelChange)="onValueChanged($event)"
* [requiredIndicator]="true"></oc-radio-button>
*/
@Component({
selector: 'oc-radio-button',
templateUrl: './oc-radio-button.component.html',
styleUrls: ['./oc-radio-button.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OcRadioButtonComponent),
multi: true,
},
],
})
export class OcRadioButtonComponent implements ControlValueAccessor {
/** Set value from AbstractControl, like `ngModel` or `formControl` */
@Input() set value(val: any) {
this.radioButtonValue = val;
}
/** Set `disable` state for color input. User can not interact with this component */
@Input() disabled: boolean = false;
/** Text of the radio button. Will be placed near this input */
@Input() labelText: string;
/** Sets asterisk near the label text. Which means that this control is required */
@Input() requiredIndicator: boolean = false;
/** Set radio button group name property for the Radio Button, this is necessary for creation of a radio button group */
@Input() radioButtonGroupName: string = '';
@Input() transformText: TransformTextType = null;
radioButtonValue: any;
isChecked: boolean = false;
/**
* Sending data to the formControl when this radio button has been clicked.
*/
onChosenRadio(): void {
this.onChange(this.radioButtonValue);
}
/**
* Register blur action. This is necessary for form control validation.
*/
onBlur(): void {
this.onTouched();
}
/**
* Calls this function with new value. When user wrote something in the component
* It needs to know that new data has been entered in the control.
*/
registerOnChange(onChange: (value: any) => void): void {
this.onChange = onChange;
}
/**
* Calls this function when user left chosen component.
* It needs for validation
*/
registerOnTouched(onTouched: () => void): void {
this.onTouched = onTouched;
}
/**
* (Optional)
* the method will be called by the control when the [disabled] state changes.
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/**
* this method will be called by the control to pass the value to our component.
* It is used if the value is changed through the code outside
* (setValue or changing the variable that ngModel is tied to),
* as well as to set the initial value.
*/
writeValue(obj: any): void {
this.isChecked = obj === this.radioButtonValue;
}
private onTouched = () => {
// nothing to do
};
private onChange: (value: any) => void = () => {
// nothing to do
};
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/model/text-transfrom-pipe.model.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
export type TransformTextType = 'titleCase';
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-title/oc-title.component.ts
|
<gh_stars>0
import { Component, Input } from '@angular/core';
@Component({
selector: 'oc-title',
templateUrl: './oc-title.component.html',
styleUrls: ['./oc-title.component.css'],
})
export class OcTitleComponent {
/**
* Sets a text for the title component.
* Required.
* If no title - throws an error.
* @type {string}.
*/
@Input() set title(title: string) {
if (!title) {
throw Error('Required @Input : title');
}
this.titleText = title;
}
/**
* Required fields indicator.
* Optional.
* Shows a red marker beside the fields that are required.
* @type {boolean}.
* Default: false
*/
@Input() required: boolean = false;
/**
* A description for the title.
* Optional.
* @type {string}.
* Default 'null'.
* Open small modal panel on the right side with this description text.
*/
@Input() description: string = null;
/**
* A tooltip icon for description text.
* Optional.
* @type {string}.
* Default 'assets/angular-common-components/info.svg'.
*/
@Input() infoTitleIconCsv: string = 'assets/angular-common-components/info.svg';
/**
* A custom class which can be added to the title for additional customizing.
* @type {string}.
* Optional.
* Default empty.
*/
@Input() customClass: string = '';
/**
* Custom styling which can be added to the title.
* @type {Object.<>}.
* Optional.
* Supposed to be the style object.
*/
@Input() customStyle: any;
titleText: string;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/util/query.util.ts
|
export class QueryUtil {
static DEFAULT_PAGE_LIMIT = 10;
static getAndQuery(queries: string[]): string {
if (queries && queries.length > 0) {
return `{'$and': [${queries.join(',')}]}`;
}
return '';
}
static getPaginationQuery(pageNumber: number, limit: number, defaultLimit?: number): string {
const normalizedDefaultLimit = defaultLimit > 0 ? defaultLimit : QueryUtil.DEFAULT_PAGE_LIMIT;
const normalizedPageNumber = pageNumber >= 1 ? pageNumber : 1;
const normalizedLimit = limit >= 0 ? limit : normalizedDefaultLimit;
return `pageNumber=${normalizedPageNumber}&limit=${normalizedLimit}`;
}
static getSearchTextQuery(searchText: string, searchByFields: string[]): string {
if (searchText && searchByFields && searchByFields.length > 0) {
return `text=${searchText}&fields=[${searchByFields.map(field => `\'${field}\'`).join(',')}]`;
}
return null;
}
static params(...param): string {
const newParam = param.filter(k => k);
if (newParam && newParam.length > 0) {
return `?${newParam.join('&')}`;
}
return '';
}
static safe(key: string, value: any): string {
if (value) {
return `${key}=${value}`;
}
return '';
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-dropdown-button/oc-dropdown-button.component.spec.ts
|
<filename>projects/angular-common-components/src/lib/common-components/oc-dropdown-button/oc-dropdown-button.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcDropdownButtonComponent } from './oc-dropdown-button.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock';
describe('OcDropdownButtonComponent', () => {
let component: OcDropdownButtonComponent;
let fixture: ComponentFixture<OcDropdownButtonComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcDropdownButtonComponent, MockSvgIconComponent],
imports: [NgbModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcDropdownButtonComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/login.model.ts
|
<filename>projects/angular-common-services/src/lib/model/api/login.model.ts
export class LoginRequest {
idToken: string;
accessToken: string;
constructor(idToken: string, accessToken: string) {
this.idToken = idToken;
this.accessToken = accessToken;
}
}
export interface LoginResponse {
refreshToken: string;
accessToken: string;
}
export interface RefreshTokenRequest {
refreshToken: string;
}
export interface SignUpByInviteRequest {
inviteToken: string;
userCustomData: any;
}
|
mukesh-openchannel/angular-template-libraries
|
src/edit-user-form.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
import { RouterTestingModule } from '@angular/router/testing';
import {
OcEditUserFormComponent,
OcEditUserFormConfig,
OCOrganization,
OcFormComponentsModule,
AppFormModel,
} from '@openchannel/angular-common-components';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { action } from '@storybook/addon-actions';
import { NgModule } from '@angular/core';
import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model';
const modules: NgModule = {
imports: [OcCommonLibModule, OcFormComponentsModule, ReactiveFormsModule, RouterTestingModule, FormsModule],
providers: [ERROR_MESSAGES_STORY_PROVIDER],
};
const accountTypeData: AppFormModel = {
fields: [
{
id: 'name',
type: 'text',
label: 'Name',
attributes: {
required: true,
},
},
{
id: 'email',
type: 'text',
label: 'Email',
attributes: {
required: true,
},
},
{
id: 'about-me',
type: 'text',
attributes: {
required: true,
},
label: 'About me',
},
],
};
const organizationTypeData: AppFormModel = {
fields: [
{
id: 'customData.company',
type: 'text',
label: 'Company',
attributes: {
required: true,
},
},
{
id: 'customData.country',
type: 'text',
label: 'Country',
attributes: {
required: true,
},
},
],
};
const multiConfigs: OcEditUserFormConfig[] = [
{
name: '<NAME>',
account: {
includeFields: ['name', 'email'],
typeData: accountTypeData,
type: 'first-account-form',
},
organization: {
includeFields: ['customData.organization'],
typeData: organizationTypeData,
type: 'first-organization-form',
},
fieldsOrder: ['email', 'name'],
},
{
name: '<NAME>',
account: {
includeFields: ['name', 'email', 'about-me'],
typeData: accountTypeData,
type: 'second-account-form',
},
organization: {
includeFields: ['customData.organization', 'customData.country'],
typeData: organizationTypeData,
type: 'second-organization-form',
},
},
];
const accountData: OCOrganization = {
name: '<NAME>',
email: '<EMAIL>',
};
const organizationData: OCOrganization = {
email: null,
customData: {
company: 'Test Company',
},
};
export default {
title: 'Edit user (organization & account) [BEM]',
component: OcEditUserFormComponent,
decorators: [moduleMetadata(modules)],
};
const EditUserFormComponent = (args: OcEditUserFormComponent) => ({
component: OcEditUserFormComponent,
moduleMetadata: modules,
props: args,
});
export const WithoutConfigs = EditUserFormComponent.bind({});
WithoutConfigs.args = {
formConfigs: null,
defaultAccountData: accountData,
defaultOrganizationData: organizationData,
resultFormData: action('resultFormData'),
};
export const ChangeType = EditUserFormComponent.bind({});
ChangeType.args = {
formConfigs: multiConfigs,
enableTypesDropdown: true,
defaultAccountData: accountData,
defaultOrganizationData: organizationData,
resultFormData: action('resultFormData'),
};
export const DisabledChangeType = EditUserFormComponent.bind({});
DisabledChangeType.args = {
formConfigs: multiConfigs,
enableTypesDropdown: false,
defaultAccountData: accountData,
defaultOrganizationData: organizationData,
resultFormData: action('resultFormData'),
};
export const PasswordAndCheckboxFields = EditUserFormComponent.bind({});
PasswordAndCheckboxFields.args = {
formConfigs: multiConfigs,
enableTypesDropdown: false,
enableTermsCheckbox: {
termsUrl: 'http://terms',
policyUrl: 'http://policy',
},
enablePasswordField: true,
defaultAccountData: accountData,
defaultOrganizationData: organizationData,
resultFormData: action('resultFormData'),
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/model/radio-button.model.ts
|
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0
export type RadioButtonLayout = 'vertical' | 'horizontal';
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/service/form-config.service.ts
|
<filename>projects/angular-common-components/src/lib/form-components/service/form-config.service.ts
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { merge } from 'lodash';
import { FormLabelPosition } from '../model/app-form-model';
import { ImageCropperOptions } from '../oc-file-upload/oc-file-upload.component';
import { TooltipPlacementArray } from '../oc-tooltip-label/oc-tooltip-label.component';
/**
* Use this injection token to provide custom form config.
*
* Provider example to provide custom form config:
* @example
* {
* provide: OC_FORM_CONFIG,
* useValue: {
* createApp: {
* longText: {
* rows: 20,
* },
* label: {
* tooltipPosition: 'top',
* },
* },
* default: {
* label: {
* tooltipPosition: 'bottom',
* },
* },
* },
* },
*/
export const OC_FORM_CONFIG = new InjectionToken<string>('Custom form config');
/**
* Id of the form to which you want to apply form inputs config.
*/
export type FormId = 'default' | 'createApp' | string;
/**
* Form input id with options that you can customize.
*/
export interface FormInputs {
longText: {
rows?: number;
[key: string]: any;
};
richText: {
options?: any;
[key: string]: any;
};
label: {
position?: FormLabelPosition;
tooltipPosition?: TooltipPlacementArray;
[key: string]: any;
};
multiselect: {
placeholder: string;
};
tags: {
labelText: string;
};
fileUpload: {
fileUploadButtonText: string;
imageUploadButtonText: string;
descriptionText: string;
imageCropperOptions: ImageCropperOptions;
[key: string]: any;
};
dfa: {
isShowPreviewMode: boolean;
[key: string]: any;
};
/** Your custom input */
[key: string]: any;
}
/** Interface for the custom form config */
export type FormConfig = {
[formId in FormId]: Partial<FormInputs>;
};
/**
* Injects to the {@link OcSingleFormComponent} to to configure form rows (labels, inputs).
*
* Use {@link OC_FORM_CONFIG} injection token to set custom form config.
*/
@Injectable({
providedIn: 'root',
})
export class FormConfigService {
private defaultConfig: Partial<FormInputs> = {
longText: {
rows: 5,
},
label: {
position: 'top',
tooltipPosition: 'right',
},
multiselect: {
placeholder: '',
},
tags: {
labelText: 'Close',
},
richText: {
options: {},
},
emailAddress: {
defaultPlaceholder: '<EMAIL>',
},
websiteUrl: {
defaultPlaceholder: 'https://my.website.com',
},
videoUrl: {
defaultPlaceholder: 'https://my.website.com',
},
fileUpload: {
fileUploadButtonText: 'Browse File',
imageUploadButtonText: 'Browse File',
descriptionText: 'Drag & drop file here or',
imageCropperOptions: {
headerText: 'Edit Image',
cancelText: 'Cancel',
confirmText: 'Confirm',
},
},
dfa: {
isShowPreviewMode: true,
},
};
config: FormConfig = {};
constructor(@Optional() @Inject(OC_FORM_CONFIG) private injectedConfig: FormConfig) {
this.setFormConfig(injectedConfig || {});
}
setFormConfig(injectedConfig: FormConfig): void {
// Set default values to each form config if specific values aren't provided
Object.keys(injectedConfig).forEach(formId => {
this.config[formId] = {};
merge(this.config[formId], this.defaultConfig, injectedConfig[formId]);
});
// Add separate default form config if it wasn't set
if (!this.config.default) {
this.config.default = this.defaultConfig;
}
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/app-data-model.ts
|
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0
import { SafeResourceUrl } from '@angular/platform-browser';
import { OwnershipModelResponse } from './ownership.model';
export interface AppModelResponse {
type: string;
price: number;
trial: number;
license: string;
modelId: string;
currency: string;
commission?: number;
feePayer?: string;
billingPeriod?: string | 'daily' | 'weekly' | 'monthly' | 'annually';
billingPeriodUnit?: any;
}
export interface RestrictResponse {
own: {
country: string[];
};
view: {
country: string[];
};
}
export type AppStatusValue = 'pending' | 'inReview' | 'inDevelopment' | 'approved' | 'suspended' | 'rejected';
export interface AppStatusResponse {
value: AppStatusValue;
lastUpdated: number;
modifiedBy: string;
reason: string;
}
export interface StatElementResponse {
'90day': number;
'30day': number;
total: number;
}
export interface StatisticsResponse {
views: StatElementResponse;
downloads: StatElementResponse;
developerSales: StatElementResponse;
totalSales: StatElementResponse;
ownerships: StatElementResponse;
reviews: StatElementResponse;
}
export interface GalleryItemResponse {
title: string;
description: string;
image: string;
}
export interface UpdateAppVersionModel {
name: string;
safeName?: string[];
approvalRequired?: boolean;
customData: any;
}
export interface CreateAppModel {
name: string;
type: string;
customData?: any;
model?: AppModelResponse[];
access?: string[];
}
export interface PublishAppVersionModel {
/**
* Current app version.
*/
version: number;
/**
* True if this app should be approved automatically.
*/
autoApprove?: boolean;
}
export interface ParentResponse {
status: AppStatusResponse;
}
export interface AppResponse {
appId: string;
customData?: any;
lastUpdated: Date | number;
version: number;
name: string;
safeName: string[];
developerId: string;
model: AppModelResponse[];
access?: string[];
restrict?: RestrictResponse | {};
allow?: RestrictResponse | {};
submittedDate: Date | number;
created: Date | number;
attributes?: any;
rating: number;
reviewCount: number;
status: AppStatusResponse;
statistics: StatisticsResponse;
isLive: boolean;
type?: string;
icon?: SafeResourceUrl | string;
}
export interface AppVersionResponse extends AppResponse {
isLatestVersion?: boolean;
children?: FullAppDataResponse[];
parent?: ParentResponse;
ownership?: OwnershipModelResponse;
}
export interface FullAppDataResponse {
appId: string;
customData?: any;
lastUpdated?: number | Date;
version?: number;
name?: string;
safeName?: string[];
developerId?: string;
model?: AppModelResponse[];
access?: string[];
restrict?: {} | RestrictResponse;
allow?: {} | RestrictResponse;
submittedDate?: number | Date;
created?: number | Date;
attributes?: any;
rating?: number;
reviewCount?: number;
status?: AppStatusResponse;
statistics?: StatisticsResponse;
isLive: boolean;
type?: string;
isLatestVersion?: boolean;
children?: FullAppDataResponse[];
parent?: ParentResponse;
ownership?: OwnershipModelResponse;
icon?: SafeResourceUrl | string;
logo?: SafeResourceUrl | string;
summary?: string;
description?: string;
video?: SafeResourceUrl | string;
images?: SafeResourceUrl[] | string[];
categories?: string[];
author?: string;
gallery?: GalleryItemResponse[];
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-review-list/oc-review-list.component.spec.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcReviewListComponent } from './oc-review-list.component';
import { By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { MockButtonComponent, MockHeadingTagDirective, MockRatingComponent } from '@openchannel/angular-common-components/src/mock/mock';
describe('OcReviewListComponent', () => {
let component: OcReviewListComponent;
let fixture: ComponentFixture<OcReviewListComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcReviewListComponent, MockButtonComponent, MockRatingComponent, MockHeadingTagDirective],
imports: [CommonModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcReviewListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show empty data message and heading', () => {
component.noReviewMessage = 'No reviews has been written yet';
component.reviewListTitle = 'Most Recent Reviews';
fixture.detectChanges();
const heading: HTMLHeadingElement = fixture.debugElement.query(By.css('.review-list__empty-result-heading')).nativeElement;
const emptyData: HTMLHeadingElement = fixture.debugElement.query(By.css('.review-list__header-heading')).nativeElement;
expect(heading.textContent).toContain('No reviews has been written yet');
expect(emptyData.textContent).toContain('Most Recent Reviews');
});
it('should show reviews', () => {
component.reviewsList = [
{
reviewOwnerName: '<NAME>',
rating: 5,
review: 'Cool App!',
reviewId: '43423df434gfg1212kkd',
},
{
reviewOwnerName: '<NAME>',
rating: 2,
review: '',
reviewId: '434jg43df434gfg1212kkd',
},
];
fixture.detectChanges();
const reviewName: HTMLHeadingElement = fixture.debugElement.query(By.css('.review-list__one-review-heading')).nativeElement;
const reviewText: HTMLDivElement = fixture.debugElement.query(By.css('#reviewText')).nativeElement;
expect(component.baseReviewsList.length).toBeGreaterThan(0);
expect(reviewName.textContent).toContain('<NAME>');
expect(reviewText.textContent).toContain('Cool App!');
});
it('should emit on button click', () => {
component.reviewListTitle = 'Most Recent Reviews';
jest.spyOn(component.writeAReview, 'emit');
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('oc-button')).nativeElement;
button.click();
expect(component.writeAReview.emit).toHaveBeenCalledTimes(1);
});
it('should toggle reviews', async () => {
const oneReview = {
reviewOwnerName: '<NAME>',
rating: 5,
review: 'Cool App!',
reviewId: '43423df434gfg1212kkd',
};
component.reviewListTitle = 'Most Recent Reviews';
component.maxReviewDisplay = 2;
component.reviewsList = [oneReview, oneReview, oneReview];
component.totalReview = 3;
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('.review-list__drop-down')).nativeElement;
button.click();
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(button.textContent).toContain('Collapse');
});
});
it('should hid the review button', () => {
component.allowWriteReview = false;
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.review-list__header-button'))).toBeFalsy();
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-featured-apps/oc-featured-apps.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcFeaturedAppsComponent } from './oc-featured-apps.component';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { By } from '@angular/platform-browser';
import { FullAppData, StatElement, HtmlTagsReplacerPipe } from '@openchannel/angular-common-components/src/lib/common-components';
import { MockHeadingTagDirective, MockRoutingComponent } from '@openchannel/angular-common-components/src/mock/mock';
const statElement: StatElement = {
'90day': 20,
'30day': 10,
total: 30,
};
const featuredApp: FullAppData = {
appId: '34343-jojo-s353-fg3423',
icon: 'assets/angular-common-components/get-started.svg',
logo: 'assets/angular-common-components/get-started.svg',
name: '<NAME>',
model: [
{
type: 'recurring',
price: 5,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 4.2,
reviewCount: 20,
summary: '',
description: 'With this plugin you can collaborate with teammates at any time.',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3232gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: 'approved',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: statElement,
downloads: statElement,
developerSales: statElement,
totalSales: statElement,
ownerships: statElement,
reviews: statElement,
},
isLive: true,
};
describe('OcFeaturedAppsComponent', () => {
let component: OcFeaturedAppsComponent;
let fixture: ComponentFixture<OcFeaturedAppsComponent>;
let location: Location;
let router: Router;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcFeaturedAppsComponent, MockRoutingComponent, HtmlTagsReplacerPipe, MockHeadingTagDirective],
imports: [RouterTestingModule.withRoutes([{ path: 'mock-router/:id', component: MockRoutingComponent }])],
}).compileComponents();
router = TestBed.inject(Router);
location = TestBed.inject(Location);
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcFeaturedAppsComponent);
component = fixture.componentInstance;
component.label = 'Featured Apps';
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show apps data', () => {
component.data = [featuredApp, featuredApp];
fixture.detectChanges();
const label: HTMLHeadingElement = fixture.debugElement.query(By.css('h2')).nativeElement;
const appName: HTMLHeadingElement = fixture.debugElement.query(By.css('h3')).nativeElement;
const appDescription: HTMLSpanElement = fixture.debugElement.query(By.css('span')).nativeElement;
const appImage: HTMLImageElement = fixture.debugElement.query(By.css('img')).nativeElement;
expect(label.textContent).toContain('Featured Apps');
expect(appName.textContent).toContain('Test App');
expect(appDescription.textContent).toContain('With this plugin you can collaborate with teammates at any time.');
expect(appImage).toBeTruthy();
expect(appImage.src).toContain('assets/angular-common-components/get-started.svg');
});
it('should show no data message', () => {
component.emptyDataMessage = 'No Featured Apps';
fixture.detectChanges();
const noAppsHeading: HTMLHeadingElement = fixture.debugElement.query(By.css('h3')).nativeElement;
expect(noAppsHeading.textContent).toContain('No Featured Apps');
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/pipe/text-transform.pipe.ts
|
import { Pipe, PipeTransform } from '@angular/core';
import { TransformTextType } from '../model/text-transfrom-pipe.model';
@Pipe({
name: 'transformText',
})
export class TransformTextPipe implements PipeTransform {
transform(text: any, type: TransformTextType = null): string | any {
if (typeof text === 'string') {
if (type === 'titleCase') {
return this.toTitleCase(text);
}
}
return text;
}
/**
* The first character will be in uppercase, other characters will be in lower case.
* 'my text' => 'My text'
*/
private toTitleCase(text: string): string {
return `${text.substring(0, 1).toUpperCase()}${text.substring(1).toLowerCase()}`;
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/model/oc-error.model.ts
|
<filename>projects/angular-common-components/src/lib/common-components/model/oc-error.model.ts
import { NgForm } from '@angular/forms';
/**
* All field validators for this library.
*/
export type FieldError =
| 'required'
| 'minlength'
| 'maxlength'
| 'minCount'
| 'maxCount'
| 'minElementsCount'
| 'maxElementsCount'
| 'pattern'
| 'emailValidator'
| 'email'
| 'websiteValidator'
| 'whiteSpaceValidator'
| 'serverErrorValidator'
| 'min'
| 'max'
| 'colorValidator'
| 'booleanTagsValidator'
| 'numberTagsValidator'
| 'passwordValidator'
| 'invalidDFAField'
| string;
/**
* Part of server validators.
*/
export type ServerError =
| 'email_is_incorrect'
| 'password_is_incorrect'
| 'password_reset_required'
| 'email_not_verified'
| 'defaultMessageHandler'
| string;
/**
* Form IDs, used for identification current form.<br>
* By this ID will be applied a custom error messages.<br>
* Note: these are all components that use a form.<br>
*/
export type ErrorMessageFormId = keyof FormErrorMessagePatterns;
/** Pattern for all field error messages */
export type FieldErrorMessagePattern = {
[key in FieldError]: (params: any) => string;
};
/** Pattern for all server error messages */
export type ServerErrorMessagePattern = {
[key in ServerError]?: (params: any) => string;
};
/** Interface for friendly showing a form ID and her fields. */
export type FormErrorMessagePatterns = {
/** Config for component : {@link OcActivationComponent} */
activation: 'code';
/** Config for component : {@link OcEditUserFormComponent} */
editUser: 'terms' | string;
/** Config for component : {@link OcForgotPasswordComponent} */
forgotPassword: 'email';
/** Config for component : {@link OcLoginComponent} */
login: 'email' | 'password';
/** Config for component : {@link OcResendActivationComponent} */
resendActivation: 'email' | 'code';
/** Config for component : {@link OcResetPasswordComponent} */
resetPassword: '<PASSWORD>';
/** Config for component : {@link OcSignupComponent} */
signup: 'uname' | 'email' | 'company' | 'password' | 'isChecked';
/** Config for component : {@link OcSignupCustomComponent} */
signupCustom: 'terms' | string;
/** Config for component : {@link OcReviewComponent} */
review: 'rating' | 'headline' | 'description';
/** Your custom form configurations. */
[name: string]: string;
};
/** Interface with field and server error messages. */
export interface ErrorMessage {
fieldValidators?: FieldErrorMessagePattern | null;
serverValidators?: ServerErrorMessagePattern | null;
}
/** Specific config for updating error message by field path. */
export interface ErrorMessageByFieldPath<T = string> extends ErrorMessage {
/** Path to form field. */
fieldPath: T;
}
export interface FormErrorMessage<T = string> extends ErrorMessage {
specificFields: ErrorMessageByFieldPath<T>[];
}
export type FormErrorMessageConfig = {
[name in keyof FormErrorMessagePatterns]?: FormErrorMessage<FormErrorMessagePatterns[name]>;
};
export type FormErrorMessages = {
[formId: string]: ErrorMessage & {
specificFields: {
[fieldPath: string]: ErrorMessage;
};
};
};
/**
* Used for creating custom error message HTML template.
* Store required data for creating custom error message.
* Used only for type in TemplateRef<ErrorContext>.
* Used in :<br>
* {@link OcLoginComponent#incorrectEmailErrorCodeTemplate},
* {@link OcLoginComponent#notVerifiedEmailErrorTemplate},
* {@link OcLoginComponent#passwordResetRequiredErrorTemplate},
*/
export interface ErrorContext {
/** field or server error data. */
params: any;
/** Parent form for this field. */
parentForm: NgForm | null;
}
/**
* Pattern for overriding validator error messages (field and server).<br>
*/
export interface ErrorMessageFormPattern extends ErrorMessage {
specificFormValidators: FormErrorMessageConfig;
}
/**
* Configuration for all field error messages.<br>
* Have default implementation {@link DefaultErrorMessageConfiguration}.
*/
export class AbstractErrorMessageConfiguration {
readonly fieldValidators: FieldErrorMessagePattern;
readonly serverValidators: ServerErrorMessagePattern;
readonly specificFormValidators: FormErrorMessages;
constructor(
fieldValidators: FieldErrorMessagePattern,
serverValidators: ServerErrorMessagePattern,
specificFormValidators: FormErrorMessageConfig,
) {
this.fieldValidators = fieldValidators || {};
this.serverValidators = serverValidators || {};
this.specificFormValidators = this.mapFormConfig(specificFormValidators);
}
private mapFormConfig(config: FormErrorMessageConfig): FormErrorMessages {
const temp: FormErrorMessages = {};
for (const formId of Object.keys(config)) {
temp[formId] = {
fieldValidators: temp[formId]?.fieldValidators || {},
serverValidators: temp[formId]?.serverValidators || {},
specificFields: config[formId]?.specificFields
?.filter(field => field.fieldPath)
.reduce((acc, field) => ({ ...acc, [field.fieldPath]: field }), {}),
};
}
return temp;
}
}
/**
* Error message configuration pattern {@link AbstractErrorMessageConfiguration}. Use for providing error messages config to the main project module.<br>
*
* Used for updating server and field validation messages.<br>
*
* @example modify error message, for default login component and two custom forms.
* import {
* AbstractErrorMessageConfiguration,
* DefaultErrorMessageConfiguration,
* } from '@openchannel/angular-common-components/src/lib/common-components';
*
* class CustomErrorMessageConfiguration extends DefaultErrorMessageConfiguration {
* constructor() {
* super(
* {
* required: () => '(default) Please fill out this field.',
* },
* {
* defaultMessageHandler: () => '(custom) Server error.',
* email_is_incorrect: () => '(custom) Email is incorrect.',
* },
* {
* login: {
* specificFields: [
* {
* fieldPath: 'email',
* fieldValidators: {
* required: () => '(custom) Email is required field.',
* },
* },
* ],
* },
* },
* );
* }
* }
*
* .@NgModule({
* providers: [
* { provide: AbstractErrorMessageConfiguration, useClass: CustomErrorMessageConfiguration },
* ],
* bootstrap: [AppComponent],
* entryComponents: [],
* })
* export class AppModule {}
*
* # Your component (ts)
* .@Component({
* ...
* })
* export class YourComponent {
* formJsonData: Partial<AppFormField> = {
* fields: [
* {
* id: 'text-id',
* type: 'text',
* label: 'My text label',
* attributes: {
* required: true,
* },
* },
* ],
* };
* }
*
* # Your component (html)
* <div class="my-forms">
* <!-- default login form, already have ID 'login' -->
* <oc-login></oc-login>
*
* <!-- your custom form, with ID 'MY_FIRST_FORM' -->
* <oc-form formId="MY_FIRST_FORM" [formJsonData]="formJsonData"></oc-form>
*
* <!-- your custom form with ID 'MY_SECOND_FORM'-->
* <oc-form formId="MY_SECOND_FORM" [formJsonData]="formJsonData"> </oc-form>
* </div>
*/
export class DefaultErrorMessageConfiguration extends AbstractErrorMessageConfiguration {
constructor(
fieldValidators?: FieldErrorMessagePattern,
serverValidators?: ServerErrorMessagePattern,
specificFormValidators?: FormErrorMessageConfig,
) {
super(
{
required: () => 'Please fill out this field',
minlength: params => 'The min number of characters is ' + params.requiredLength,
maxlength: params => 'The max allowed number of characters is ' + params.requiredLength,
minCount: () => '',
maxCount: () => '',
minElementsCount: params => `Minimum ${params.requiredCount} ${params.fieldLabel} are required`,
maxElementsCount: params => `Maximum ${params.requiredCount} ${params.fieldLabel} are required`,
pattern: params => 'The required pattern is: ' + params.requiredPattern,
emailValidator: () => 'Email seems to be invalid',
email: () => 'Email seems to be invalid',
websiteValidator: () => 'Please enter a valid URL',
whiteSpaceValidator: () => 'Please fill valid value',
min: params => 'The minimum possible value is ' + params.min,
max: params => 'The maximum possible value is ' + params.max,
colorValidator: () => 'Please enter a valid Color value.',
booleanTagsValidator: params => params.fieldTitle + " can only contain boolean values ('true' or 'false')",
numberTagsValidator: params => params.fieldTitle + ' can only contain numeric values',
passwordValidator: () =>
'Password must contain 1 uppercase, 1 lowercase, 1 digit, 1 special char (one of @#$%!^&) and at least 8 characters long',
invalidDFAField: params => `Please, check all fields inside ${params.fieldDefinition.label || ''}`,
...(fieldValidators || {}),
},
{
defaultMessageHandler: params => params.message,
...(serverValidators || {}),
},
{
signup: {
specificFields: [
{
fieldPath: 'isChecked',
fieldValidators: {
required: () => 'Please confirm this checkbox',
},
},
],
},
signupCustom: {
specificFields: [
{
fieldPath: 'terms',
fieldValidators: {
required: () => 'Please confirm this checkbox',
},
},
],
},
resetPassword: {
specificFields: [
{
fieldPath: 'newPassword',
fieldValidators: {
required: () => null,
},
},
],
},
...(specificFormValidators || {}),
},
);
}
}
export interface ServerErrorModel {
field?: string;
type?: string;
code?: string;
message?: string;
}
export interface ServerErrorEvent<T extends 'onNewErrors' | 'onRemovedError', V> {
type: T;
value: V;
}
export interface OnNewErrorsEvent extends ServerErrorEvent<'onNewErrors', ServerErrorModel[]> {}
export interface OnRemoveErrorEvent extends ServerErrorEvent<'onRemovedError', ServerErrorModel[]> {}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/public-api.ts
|
<gh_stars>0
export * from '@openchannel/angular-common-components/src/lib/common-components';
export * from '@openchannel/angular-common-components/src/lib/form-components';
export * from '@openchannel/angular-common-components/src/lib/auth-components';
export * from '@openchannel/angular-common-components/src/lib/management-components';
export * from '@openchannel/angular-common-components/src/lib/app-categories';
export * from '@openchannel/angular-common-components/src/lib/market-components';
export * from '@openchannel/angular-common-components/src/lib/portal-components';
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/developer-role.service.ts
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Page } from '../model/api/page.model';
import { HttpRequestService } from './http-request-services';
import { DeveloperRoleResponse } from '../model/api/account-role-model';
import { OcHttpParams } from '../model/api/http-params-encoder-model';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
* Description: API service for getting Developer Roles.<br>
*
* Endpoints:<br>
*
* GET 'v2/developerRoles'<br>
*/
@Injectable({
providedIn: 'root',
})
export class DeveloperRoleService {
constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
*
* Description: Get Developer Roles list with pagination
*
* @param {number} pageNumber - (optional) Current page index. Starts from >= 1
* @param {number} pageLimit - (optional) Count user types into response. Starts from >= 1
* @returns {Observable<Page<DeveloperRoleResponse | any>>} `Observable<Page<DeveloperRoleResponse | any>>`
*
* ### Example
*
* `getDeveloperRoles(1, 10)`
*/
getDeveloperRoles(pageNumber?: number, pageLimit?: number): Observable<Page<DeveloperRoleResponse | any>> {
return this.httpService.get(this.apiPaths.developerRoles, {
params: new OcHttpParams().append('pageNumber', String(pageNumber)).append('limit', String(pageLimit)),
});
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-overall-rating/oc-overall-rating.component.spec.ts
|
<gh_stars>0
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcOverallRatingComponent } from './oc-overall-rating.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { By } from '@angular/platform-browser';
import { OcLabelComponent } from '@openchannel/angular-common-components/src/lib/common-components';
describe('OcOverallRatingComponent', () => {
let component: OcOverallRatingComponent;
let fixture: ComponentFixture<OcOverallRatingComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcOverallRatingComponent, OcLabelComponent],
imports: [NgbModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcOverallRatingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show data', async () => {
component.allReviewSummary = {
rating: 4.2,
reviewCount: 10,
5: 3,
4: 4,
3: 2,
2: 1,
1: 0,
};
component.overallReviewLabel = 'Test Rating';
fixture.detectChanges();
const showRating = fixture.debugElement.query(By.css('.overall-rating__rating-result')).nativeElement;
const showLabel = fixture.debugElement.query(By.css('#reviewLabel')).nativeElement;
const reviewCount = fixture.debugElement.query(By.css('#reviewCount')).nativeElement;
await fixture.whenStable().then(() => {
expect(showRating.textContent).toContain('4.2');
expect(showLabel.textContent).toContain('Test Rating');
expect(reviewCount.textContent).toContain('10 reviews');
});
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/auth-holder.service.ts
|
import { Injectable } from '@angular/core';
import jwtDecode from 'jwt-decode';
import { AccessLevel, Permission, PermissionType, UserDetails } from '../model/api/user.model';
/**
* Description:
* 1. Service for store JWT tokens in local browser storage.
* 2. Decoding JWT accessToken and getting user data from him.
* 3. Checking permission (JWT accessToken have field 'permissions',
* it is array of user permission.
* Example: ['APPS.READ', 'ACCOUNTS.MODIFY', 'ORGANIZATIONS.MODIFY'])
*/
@Injectable({
providedIn: 'root',
})
export class AuthHolderService {
/**
* Get JWT accessToken from the browser local storage.
* @return string
*/
get accessToken(): string {
return window.localStorage.getItem(this.ACCESS_TOKEN_KEY);
}
/**
* Set JWT accessToken to the browser local storage.
* @param token (required) JWT accessToken.
* @return void;
*/
set accessToken(token: string) {
window.localStorage.setItem(this.ACCESS_TOKEN_KEY, token);
}
/**
* Get JWT refreshToken from the browser local storage.
* @return string;
*/
get refreshToken(): string {
return window.localStorage.getItem(this.REFRESH_TOKEN_KEY);
}
/**
* Set refreshToken to the browser local storage.
* @param token (required) JWT refreshToken
*/
set refreshToken(token: string) {
window.localStorage.setItem(this.REFRESH_TOKEN_KEY, token);
}
/**
* By this key will be store JWT accessToken in browser local storage.
*/
readonly ACCESS_TOKEN_KEY = 'accessToken';
/**
* By this key will be store JWT refreshToken in browser local storage.
*/
readonly REFRESH_TOKEN_KEY = 'refreshToken';
/**
* User data from derived from the decoded JWT accessToken.
*/
userDetails: UserDetails;
constructor() {
this.updateVariables();
}
/**
* Put JWT tokens in browser local storage. Update UserDetails by new claims from the accessToken.
* @param accessToken (required) JWT access token.
* @param refreshToken (required) JWT refresh token.
*
* @return void;
*/
persist(accessToken: string, refreshToken: string): void {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.updateVariables();
}
/**
* Put JWT access token in browser local storage. Update UserDetails by new claims from the accessToken.
* @param accessToken (required) JWT access token.
* @return void;
*/
updateAccessToken(accessToken: string): void {
this.accessToken = accessToken;
this.updateVariables();
}
/**
* When exists JWT tokens (access token and refresh token) in browser local storage, return true.
*/
isLoggedInUser(): boolean {
return !!this.accessToken && !!this.refreshToken;
}
/**
* Function for removing accessToken and refreshToken from the browser local storage.
*/
clearTokensInStorage(): void {
window.localStorage.removeItem(this.ACCESS_TOKEN_KEY);
window.localStorage.removeItem(this.REFRESH_TOKEN_KEY);
}
/**
* Function for creating user name by current user details.
* @return 'FirstName LastName'
*/
getUserName(): string {
if (this.userDetails) {
const firstName = this.userDetails?.firstName;
const lastName = this.userDetails?.lastName;
return `${firstName ? firstName : ''} ${lastName ? lastName : ''}`.trim();
}
return '';
}
/**
* Function for checking user permissions. Used for blocking access for some functions or hiding DOM elements.
*
* @param type (required) Permission type : 'APPS','ACCOUNTS','DEVELOPERS','USERS','FILES','FORMS','OWNERSHIPS','REVIEWS','ORGANIZATIONS';
* @param accessArray (required) Array of the access levels: 'READ', 'MODIFY', 'DELETE',
*
* @return boolean
*
* ### Example:
* ``
* Note: Now permissions in JWT accessToken are : ['APPS.READ', 'APPS.MODIFY']
*
* hasPermission('APPS', ['READ']);
* will be return true.
*
* hasPermission('APPS', ['MODIFY']);
* will be return true.
*
* hasPermission('APPS', ['DELETE']);
* will be return false.
* ``
*/
hasPermission(type: PermissionType, accessArray: AccessLevel[]): boolean {
if (this.userDetails?.permissions && type && accessArray) {
return !!this.userDetails?.permissions.find(permission => {
if (!permission) {
return false;
}
const validType = permission.startsWith(type) || permission.startsWith('*');
const hasAccess = accessArray.find(access => permission.endsWith(access));
return (validType && hasAccess) || permission.endsWith('*');
});
}
return false;
}
/**
* Function for checking the array of the user permissions.
* When will found the first match, from the incoming array 'permissions', the function returns true, else false.
* Used for blocking access for some functions or hiding DOM elements.
*
* @param permissions (required) The array of permission for searching into current user permissions.
*
* @return boolean;
*
* ### Example:
* ``
* Note: Now permissions in JWT accessToken are : ['ACCOUNTS.MODIFY', 'ORGANIZATIONS.MODIFY']
*
* const permissions: Permission [] = [
* {
* type: PermissionType.ACCOUNTS,
* access: [AccessLevel.READ]
* },{
* type: PermissionType.ORGANIZATIONS,
* access: [AccessLevel.READ, AccessLevel.MODIFY, AccessLevel.DELETE]
* }
* ]
*
* hasAnyPermission(permissions);
* return true;
* ``
*/
hasAnyPermission(permissions: Permission[]): boolean {
if (permissions) {
return !!permissions.find(p => this.hasPermission(p.type, p.access));
}
return false;
}
/**
* Function for decoding JWT accessToken and creating user details.
* When JWT signature is not valid, will be removed all JWT tokens from the browser local storage.
* @return void;
*/
private updateVariables(): void {
try {
this.userDetails = this.accessToken ? jwtDecode(this.accessToken) : null;
} catch (error) {
this.clearTokensInStorage();
}
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/interceptors/http-requests-watcher.interceptor.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { EMPTY, Observable } from 'rxjs';
import { PrerenderRequestsWatcherService } from '../service/prerender-requests-watcher.service';
import { PrerenderEndpointsConfig } from '../model/api/prerender-endpoints-config.model';
import isbot from 'isbot';
/**
* Interceptor which is watching every http request and sending information to the pre-render watcher.
* To connect interceptor to the app you need to import {@link NetlifyPrerenderModule} module to the app module
* with pre-render endpoints config if it exists.
* @example
* app.module.ts:
*
* NgModule({
* ...
* imports: [
* NetlifyPrerenderModule.withOptions({ endpointsConfigForPrerender: yourPrerenderConfig }),
* ],
* })
* export class AppModule {}
*/
@Injectable()
export class HttpRequestsWatcherInterceptor implements HttpInterceptor {
constructor(private endpoints: PrerenderEndpointsConfig, private requestWatcher: PrerenderRequestsWatcherService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const notForBotUrl = this.endpoints.excludeAPICall.find(url => request.url.includes(url));
if (isbot(navigator.userAgent) && notForBotUrl) {
return EMPTY;
}
return this.requestWatcher.addHttpEvent(next.handle(request));
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-error/oc-error.component.ts
|
import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, AbstractControlDirective, FormArray, NgModel, ValidationErrors } from '@angular/forms';
import { OcErrorService } from './oc-error-service';
import { AbstractErrorMessageConfiguration } from '../model/oc-error.model';
import { ControlUtils } from '../model/utils.model';
import { toPath, isEqual } from 'lodash';
/**
* An oc-error component. It is used to show error or errors list after validation.<br>
* Each error contains a text message.<br>
* You can provide {@link DefaultErrorMessageConfiguration}
* message configs for creating some error messages.
*/
@Component({
selector: 'oc-error',
templateUrl: './oc-error.component.html',
styleUrls: ['./oc-error.component.css'],
})
export class OcErrorComponent implements OnInit {
/**
* An input for a specific control, to which an error would be related.
* @type {AbstractControlDirective | AbstractControl | NgModel}.
*/
@Input() control: AbstractControlDirective | AbstractControl | NgModel;
/**
* Server error field name.
* @type {string}.
*/
@Input() field: string;
/**
* Params for server error message.
* @type {*}.
*/
@Input() errorParams: any;
/**
* Modifying an error component to have a custom validator and text message.
* @type {Object[]}.
*/
@Input() modifyErrors: [{ validator: string; message: string }];
/** Current form ID. Used for modifying error messages. Look: {@link ErrorMessageFormId} */
@Input() formId: string = null;
/**
* Path from control to parent form.
*/
private fullControlPath: string;
private pathSegments: string[];
constructor(public errorService: OcErrorService, private config: AbstractErrorMessageConfiguration) {}
ngOnInit(): void {
this.fullControlPath = ControlUtils.getFullControlPath(this.control);
this.pathSegments = toPath(this.fullControlPath);
if (this.control && this.control instanceof AbstractControl) {
const parent = ControlUtils.getParentControl(this.control);
if (parent instanceof FormArray) {
// removing first part of the path, it is part of form array.
this.pathSegments = this.pathSegments.slice(1);
this.fullControlPath = this.pathSegments.join('.');
}
}
}
/**
* This function defines whether to show or not validation errors.
* Checks for client-side and server-side errors.
* Creates an error validation object and passes it to a related control.
* Returns a boolean type.
*/
shouldShowErrors(): boolean {
// client side error validators check
if (this.control && this.control.errors && (this.control.dirty || this.control.touched)) {
return true;
}
// server side error validators check
if (
this.errorService.serverErrorList &&
this.errorService.serverErrorList.length &&
typeof this.errorService.serverErrorList === 'object'
) {
const error = this.errorService.serverErrorList.find(message => isEqual(toPath(message.field), this.pathSegments));
if (error) {
setTimeout(() => {
// clear error from service as we have fetched it
this.errorService.clearError(error);
// create error validation object an pass it to control
const errors = { serverErrorValidator: error };
if (this.control instanceof AbstractControlDirective) {
(this.control as AbstractControlDirective).control.setErrors(errors);
(this.control as AbstractControlDirective).control.markAsTouched();
} else if (this.control instanceof NgModel) {
(this.control as NgModel).control.setErrors(errors);
(this.control as NgModel).control.markAsTouched();
} else if (this.control) {
this.control.setErrors(errors);
this.control.markAsTouched();
}
});
return true;
}
}
if (this.field === 'customError' && this.errorParams) {
return true;
}
// no error
return false;
}
/**
* Returns an array of errors.
* @type {string[]}.
*/
listOfErrors(): string[] {
const { errors } = this.control;
if (this.control) {
if (!errors) {
return [];
}
return Object.keys(errors)
.map(field => this.getMessage(errors, field, errors[field]))
.filter(message => message);
} else if (this.field) {
const fieldErrorMsg = this.getMessage(null, this.field, this.errorParams);
return fieldErrorMsg ? [fieldErrorMsg] : [];
}
return [];
}
/**
* Finds a message with specific type and params.
*/
private getMessage(errors: ValidationErrors | null, type: string, params: any): any {
// old override message implementation
if (this.modifyErrors) {
const errorMsg = this.modifyErrors.filter(update => update.validator === type)[0];
if (errorMsg) {
// clean up an error message
return errorMsg?.message;
}
}
let messageFn;
if (errors?.serverErrorValidator) {
const serverErrorCode = errors?.serverErrorValidator?.code || errors?.serverErrorValidator?.type || 'defaultMessageHandler';
// server error message
messageFn =
this.getErrorMessageFunction(serverErrorCode, 'serverValidators') ||
this.getErrorMessageFunction('defaultMessageHandler', 'serverValidators');
} else {
// field server error message
messageFn = this.getErrorMessageFunction(type, 'fieldValidators');
}
return messageFn?.(params) || null;
}
/**
* Used for getting error message by specific error key.
*/
private getErrorMessageFunction(validatorId: string, validatorType: 'fieldValidators' | 'serverValidators'): (params: any) => string {
if (this.formId && this.config.specificFormValidators[this.formId]) {
const specificFieldFn =
this.config.specificFormValidators[this.formId].specificFields?.[this.fullControlPath]?.[validatorType]?.[validatorId];
if (specificFieldFn) {
return specificFieldFn;
}
const specificFn = this.config.specificFormValidators[this.formId][validatorType]?.[validatorId];
if (specificFn) {
return specificFn;
}
}
return this.config[validatorType]?.[validatorId];
}
}
|
mukesh-openchannel/angular-template-libraries
|
src/confirmaton-modal.stories.ts
|
<gh_stars>0
import { moduleMetadata } from '@storybook/angular';
import { OcConfirmationModalComponent, OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
const modules = {
imports: [OcCommonLibModule],
};
export default {
title: 'Confirmation modal [BEM]',
component: OcConfirmationModalComponent,
decorators: [moduleMetadata(modules)],
};
const ConfirmationModal = (args: OcConfirmationModalComponent) => ({
component: OcConfirmationModalComponent,
moduleMetadata: modules,
props: args,
});
export const DefaultConfirmation = ConfirmationModal.bind({});
DefaultConfirmation.args = {
modalTitle: 'Submit app',
modalText: 'Submit this app to the marketplace now?',
confirmButtonText: 'Yes, submit it',
};
export const WarningConfirmation = ConfirmationModal.bind({});
WarningConfirmation.args = {
modalTitle: 'Delete app',
modalText: 'Delete this app from the marketplace now?',
confirmButtonText: 'Yes, delete it',
confirmButtonType: 'danger',
};
|
mukesh-openchannel/angular-template-libraries
|
src/app-galary.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcAppGalleryComponent, OcMarketComponentsModule } from '@openchannel/angular-common-components/src/lib/market-components';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { FullAppData, StatElement } from '@openchannel/angular-common-components/src/lib/common-components';
const modules = {
imports: [OcMarketComponentsModule, BrowserAnimationsModule, RouterTestingModule],
};
const stat: StatElement = {
'90day': 10,
'30day': 20,
total: 20,
};
const app: FullAppData = {
appId: '344gfs3jfgi3423',
icon: '',
name: 'Test App',
model: [
{
type: 'recurring',
price: 5,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 4.2,
reviewCount: 20,
summary: 'Some test summary',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3232gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: 'approved',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
const app1 = { ...app };
const app2 = { ...app };
app2.description = 'Integrate directly with your account and make customer updates a breeze';
app2.logo = './assets/angular-common-components/get-started.svg';
app2.name = 'Application';
app2.model[0].price = 11.99;
app2.rating = 0;
app2.reviewCount = 0;
const app3 = { ...app };
app3.description = 'With this plugin you can communicate with your teammates any time';
app3.logo = './assets/angular-common-components/get-started.svg';
app3.name = 'Plugin';
app3.model[0].price = 0;
app3.model[0].type = 'free';
app3.rating = 3.5;
app3.reviewCount = 12;
const app4 = { ...app };
app4.description = 'Improve and extend your experience right from your own UI';
app4.logo = './assets/angular-common-components/get-started.svg';
app4.name = 'Integration';
app4.model[0].price = 4.99;
app4.rating = 4.9;
app4.reviewCount = 87;
export default {
title: 'App Gallery [BEM]',
component: OcAppGalleryComponent,
decorators: [moduleMetadata(modules)],
argTypes: { clickAppCard: { action: 'App Card was clicked' }, clickMoreApps: { action: 'More link was clicked' } },
};
const AppGalleryComponent = (args: OcAppGalleryComponent) => ({
component: OcAppGalleryComponent,
moduleMetadata: modules,
props: args,
});
export const RecentlyAddedEmpty = AppGalleryComponent.bind({});
RecentlyAddedEmpty.args = {
noAppMessage: 'No App Found',
appGalleryTitle: 'Recently Added',
appGalleryDescription: 'The latest apps that help you team work and build faster',
appsArr: [],
};
export const RecentlyAddedSome = AppGalleryComponent.bind({});
RecentlyAddedSome.args = {
noAppMessage: 'No App Found',
appGalleryTitle: 'Recently Added',
appGalleryDescription: 'The latest apps that help you team work and build faster',
appsArr: [app1, app2, app3],
seeAllUrl: '',
};
export const RecentlyAddedMax = AppGalleryComponent.bind({});
RecentlyAddedMax.args = {
noAppMessage: 'No App Found',
appGalleryTitle: 'Recently Added',
appGalleryDescription: 'The latest apps that help you team work and build faster',
appsArr: [app1, app2, app3, app4],
seeAllUrl: '',
};
export const MostPopular = AppGalleryComponent.bind({});
MostPopular.args = {
noAppMessage: 'No App Found',
appGalleryTitle: 'Most Popular',
appGalleryDescription: 'The most used apps that help you and your team get more done',
appsArr: [app1, app2, app3, app4, app1, app2],
seeAllUrl: '',
};
export const AppsForAnalytics = AppGalleryComponent.bind({});
AppsForAnalytics.args = {
noAppMessage: 'No App Found',
appGalleryTitle: 'Apps for Analytics',
appGalleryDescription: 'Get insights and analytics to make the better decisions',
appsArr: [app1, app2, app3, app4, app1, app2],
seeAllUrl: '',
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/native-login.service.ts
|
<filename>projects/angular-common-services/src/lib/service/native-login.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpRequestService } from './http-request-services';
import { OCNativeCustomSignup, OCNativeDefaultSignup, UserLoginModel } from '../model/api/user-login-model';
import { LoginResponse, SignUpByInviteRequest } from '../model/api/login.model';
import { UserResetPassword } from '../model/api/user-activation-model';
import { ChangePasswordRequest } from '../model/api/change-password.model';
import { OcHttpParams } from '../model/api/http-params-encoder-model';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
* Description: API service for Native authorization.<br>
*
* Endpoints:<br>
*
* POST 'auth/native/token'<br>
*
* POST 'auth/native/register'<br>
*
* POST 'auth/native/invite'<br>
*
* POST 'auth/native/activate'<br>
*
* POST 'auth/native/send-reset-code'<br>
*
* POST 'auth/native/reset-password'<br>
*
* POST 'auth/native/send-activate-code'<br>
*
* POST 'auth/native/change-password'<br>
*
*/
@Injectable({
providedIn: 'root',
})
export class NativeLoginService {
constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
*
* Description: Login to app
*
* @param {UserLoginModel} body - (required) User login data
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `signIn({
* email: '<EMAIL>',
* password: '<PASSWORD>!',
* isChecked: true
* })`
*
*/
signIn(body: UserLoginModel): Observable<any> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/token`, body);
}
/**
* Description: This service is responsible for user signup feature.
*
* @param {OCNativeDefaultSignup | OCNativeCustomSignup} userSignUp - (required) User Sign Up data
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `signup({
* uname:'Name',
* email:'<EMAIL>',
* company:'company',
* password:'password'
* })`
*
* OR
*
* `signup({
* account: {
* name: 'Acc',
* username: 'Name',
* type: 'Type',
* email: '<EMAIL>',
* customData: {},
* },
* organization: {
* name: 'Acc',
* username: 'Name',
* type: 'Type',
* email: '<EMAIL>',
* customData: {},
* }
* })`
*/
signup(userSignUp: OCNativeDefaultSignup | OCNativeCustomSignup): Observable<any> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/register`, userSignUp);
}
/**
* Description: Sign up a user by invite.
*
* @param {SignUpByInviteRequest} userSignUp - (required) Invited user Sign Up data and Token
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `signupByInvite({
* inviteToken: '<PASSWORD>',
* userCustomData: {name: 'Name'}
* })`
*/
signupByInvite(userSignUp: SignUpByInviteRequest): Observable<any> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/invite`, userSignUp);
}
/**
* Description: This method is responsible for submit user activation form.
*
* @param {any} activationModel - (required) Data from activation form
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `activate({
* name: 'Name'
* })`
*/
activate(activationModel: any): Observable<any> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/activate`, activationModel);
}
/**
* Description: This method is responsible for reset user password.
*
* @param {string} email - (required) User Email to send reset Code
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `sendResetCode('<EMAIL>');`
*/
sendResetCode(email: string): Observable<any> {
const params = new OcHttpParams().set('email', email);
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/send-reset-code`, null, { params });
}
/**
* Description: This method is responsible for reset user password.
*
* @param {UserResetPassword} request (required) Request params. New password and code.
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `resetPassword({
* newPassword: 'password'
* code: '123'
* })`
*/
resetPassword(request: UserResetPassword): Observable<any> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/reset-password`, request);
}
/**
* Description: This method is responsible for resend activation mail
*
* @param {string} email - (required) User Email to send Activation Code
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `sendActivationCode('<EMAIL>');`
*/
sendActivationCode(email: string): Observable<any> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/send-activate-code`, email);
}
/**
* Description: This method is responsible for change user password.
*
* @param {ChangePasswordRequest} request (required) Model with current and new passwords
* @returns {Observable<any>} `Observable<any>`
*
* ### Example
*
* `changePassword({
* password: 'password',
* newPassword: '<PASSWORD>'
* });`
*/
changePassword(request: ChangePasswordRequest): Observable<any | LoginResponse> {
return this.httpRequest.post(`${this.apiPaths.authorizationNative}/change-password`, request);
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-overall-rating/oc-overall-rating.component.ts
|
import { Component, Input } from '@angular/core';
import { OverallRatingSummary } from '../models/overall-rating-summary-model';
/**
* Overall rating component. Based on ngb-rating component. Represents rating template and logic.
*
* Inputs: <br>
* @param {string} overallReviewLabel
* @param {OverallRatingSummary} allReviewSummary
*
* @example <oc-overall-rating [overallReviewLabel]="Custom Label" [allReviewSummary]="{rating: 5, reviewCount:1}">
*/
@Component({
selector: 'oc-overall-rating',
templateUrl: './oc-overall-rating.component.html',
styleUrls: ['./oc-overall-rating.component.css'],
})
export class OcOverallRatingComponent {
/**
* Rates data.
*
* Default: `[5, 4, 3, 2, 1]`
*/
rates: number[] = [5, 4, 3, 2, 1];
/**
* Label for overall review.
*/
@Input() overallReviewLabel: string = 'Overall rating';
/**
* Review summary data.
*/
@Input() allReviewSummary: OverallRatingSummary = new OverallRatingSummary();
}
|
mukesh-openchannel/angular-template-libraries
|
src/app-list-grid.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcAppListGridComponent, OcRatingComponent } from '@openchannel/angular-common-components/src/lib/market-components';
import { AngularSvgIconModule } from 'angular-svg-icon';
import { PricePipe, StatElement } from '@openchannel/angular-common-components/src/lib/common-components';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
const modules = {
imports: [AngularSvgIconModule.forRoot(), NgbModule, HttpClientTestingModule, RouterTestingModule],
declarations: [OcRatingComponent, PricePipe],
};
const stat: StatElement = {
'90day': 30,
'30day': 10,
total: 40,
};
const app1 = {
appId: '344gf-43s3j-gi3423',
icon: '',
name: 'Plugin',
model: [
{
type: 'free',
price: 0,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 3.5,
reviewCount: 12,
summary: 'With this plugin you can communicate with your teammates any time',
description: 'With this plugin you can communicate with your teammates any time',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3<PASSWORD>gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: '',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
const app2 = {
appId: '343344gf-43s3j-gi3423',
icon: '',
name: 'Application',
model: [
{
type: 'recurring',
price: 11.99,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 2.4,
reviewCount: 2,
summary: 'Integrate directly with your account and make customer updates a breeze',
description: 'Integrate directly with your account and make customer updates a breeze',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '<PASSWORD>',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: '',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
const app3 = {
appId: '34ks344gf-43s3j-gi3423',
icon: '',
name: 'Plugin',
model: [
{
type: 'free',
price: 11.99,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 3.5,
reviewCount: 12,
summary: 'With this plugin you can communicate with your teammates any time',
description: 'With this plugin you can communicate with your teammates any time',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '<PASSWORD>',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: '',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
const app4 = {
appId: '35-344gf-43s3j-gi3423',
icon: '',
name: 'Integration',
model: [
{
type: 'single',
price: 5.99,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 4.9,
reviewCount: 87,
summary: 'Integrate directly with your account and make customer updates a breeze',
description: 'Integrate directly with your account and make customer updates a breeze',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '4<PASSWORD>',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: '',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
export default {
title: 'App List Grid [BEM]',
component: OcAppListGridComponent,
decorators: [moduleMetadata(modules)],
argTypes: { gotoDetails: { action: 'Go to details' } },
};
const AppListGridComponent = (args: OcAppListGridComponent) => ({
component: OcAppListGridComponent,
moduleMetadata: modules,
props: args,
});
export const EmptyGrid = AppListGridComponent.bind({});
EmptyGrid.args = {
appList: [],
noAppMessage: 'No App Found',
};
export const GridWithApps = AppListGridComponent.bind({});
GridWithApps.args = {
appList: [app1, app2, app3, app4],
noAppMessage: 'No App Found',
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/service/trim-text-utils/trim-text.service.ts
|
<filename>projects/angular-common-components/src/lib/form-components/service/trim-text-utils/trim-text.service.ts
import { cloneDeep, get, set } from 'lodash';
import { AppFormField, TrimFormFieldType } from '../../model/app-form-model';
import { RichTextUtils } from '../rich-text-utils/rich-text.service';
export class TrimTextUtils {
static updateByType(value: any, fieldType?: TrimFormFieldType): any {
switch (fieldType) {
case 'richText':
return RichTextUtils.trimRichText(value);
case 'password':
return value;
case 'websiteUrl':
const trimmedLink = this.trimAll(value);
if (!trimmedLink || trimmedLink.startsWith('http')) {
return trimmedLink;
} else {
return 'https://' + trimmedLink;
}
default:
return this.trimAll(value);
}
}
static trimTextFields<T extends {} | []>(value: T, fields: AppFormField[], trimFields: TrimFormFieldType[]): T {
return this.trimTextFieldsInternal(cloneDeep(value), fields, fieldType => trimFields?.includes(fieldType));
}
private static trimTextFieldsInternal<T>(
value: T,
fields: AppFormField[],
needToTrim: (type: TrimFormFieldType, value?: string) => boolean,
): T {
if (!value || !fields || typeof value !== 'object') {
return value;
}
fields.forEach(field => {
const valueByPath = get(value, field.id);
if (valueByPath === undefined) {
return;
}
if (field.type === 'dynamicFieldArray' && Array.isArray(valueByPath)) {
valueByPath.forEach(dfaItem => this.trimTextFieldsInternal(dfaItem, field.fields, needToTrim));
}
if (needToTrim(field.type, valueByPath)) {
set(value as any, field.id, this.updateByType(valueByPath, field.type));
}
});
return value;
}
private static trimAll(data: any): any {
// tslint:disable-next-line:switch-default
switch (typeof data) {
case 'string':
return data.trim();
case 'object':
Object.keys(data || []).forEach(key => (data[key] = this.trimAll(data[key])));
}
return data;
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/user-role.service.ts
|
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Page} from '../model/api/page.model';
import {HttpRequestService} from './http-request-services';
import {UserRoleResponse} from '../model/api/account-role-model';
import {OcHttpParams} from '../model/api/http-params-encoder-model';
import { OcApiPaths } from '../oc-ng-common-service.module';
@Injectable({
providedIn: 'root',
})
export class UserRoleService {
constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {
}
getUserRoles(pageNumber: number, pageLimit: number): Observable<Page<UserRoleResponse | any>> {
const params = new OcHttpParams()
.append('pageNumber', String(pageNumber))
.append('limit', String(pageLimit));
return this.httpService.get(this.apiPaths.userRoles, { params });
}
}
|
mukesh-openchannel/angular-template-libraries
|
src/app-number.stories.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { OcCommonLibModule } from '@openchannel/angular-common-components';
import { moduleMetadata } from '@storybook/angular';
import { OcNumberComponent } from '@openchannel/angular-common-components/src/lib/form-components';
import { FormsModule } from '@angular/forms';
/** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */
const modules = {
imports: [OcCommonLibModule, FormsModule],
};
export default {
title: 'Number Input Component [BEM]',
component: OcNumberComponent,
decorators: [moduleMetadata(modules)],
};
const NumberInputComponent = (args: OcNumberComponent) => ({
component: OcNumberComponent,
moduleMetadata: modules,
props: args,
});
export const SimpleNumberInput = NumberInputComponent.bind({});
SimpleNumberInput.args = {
autoFocus: true,
placeholder: 'Write any number here',
};
|
mukesh-openchannel/angular-template-libraries
|
src/oc-password.stories.ts
|
import { OcCommonLibModule, OcPasswordComponent } from '@openchannel/angular-common-components';
import { moduleMetadata } from '@storybook/angular';
/** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */
const modules = {
imports: [OcCommonLibModule],
};
export default {
title: 'Password [BEM]',
component: OcPasswordComponent,
decorators: [moduleMetadata(modules)],
argTypes: { modelNameChange: { action: 'Entered Password' } },
};
const PasswordComponent = (args: OcPasswordComponent) => ({
component: OcPasswordComponent,
moduleMetadata: modules,
props: args,
});
export const PasswordInput = PasswordComponent.bind({});
PasswordInput.args = {
placeholder: 'Enter password',
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-file-upload/oc-file-upload.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcFileUploadComponent } from './oc-file-upload.component';
import { NgModel } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { BrowserModule, By } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Observable, of } from 'rxjs';
import { HttpResponse, HttpUploadProgressEvent } from '@angular/common/http';
import { ImageCropperModuleMock, MockButtonComponent } from '@openchannel/angular-common-components/src/mock/mock';
import { FileDetails, FileUploaderService } from '../model/file.model';
const mockResponse: FileDetails = {
uploadDate: 214213,
fileId: 'fileId',
name: 'test1.jpg',
contentType: 'type',
size: 123123,
isPrivate: false,
mimeCheck: 'PASSED',
fileUrl: 'http://file-url.com',
isError: false,
fileUploadProgress: 100,
virusScan: {
started: 1457710762784,
finished: 1457710769567,
status: 'CLEAN',
foundViruses: [
{
fileName: 'jacks.docx',
virusName: 'H237 Worm',
},
],
},
fileIconUrl: '',
};
class FileUploadDownloadServiceStub extends FileUploaderService {
constructor() {
super();
}
fileUploadRequest(
file: FormData,
isPrivate: boolean,
hash?: string[],
): Observable<HttpResponse<FileDetails> | HttpUploadProgressEvent> {
return of(new HttpResponse({ body: mockResponse }));
}
fileDetailsRequest(fileId: string): Observable<FileDetails> {
return of(mockResponse);
}
}
describe('OcFileUploadComponent', () => {
let component: OcFileUploadComponent;
let fixture: ComponentFixture<OcFileUploadComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcFileUploadComponent, MockButtonComponent],
providers: [NgModel, { provide: FileUploaderService, useClass: FileUploadDownloadServiceStub }],
imports: [NgbModule, CommonModule, BrowserModule, ImageCropperModuleMock],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcFileUploadComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should receive file', async () => {
const onTouchFunc = jest.fn();
component.registerOnTouched(onTouchFunc);
const changeEvent = {
target: {
files: [new File([], 'test1.jpg')],
},
};
fixture.debugElement.query(By.css('input#fileDropRef')).triggerEventHandler('change', changeEvent);
fixture.detectChanges();
await fixture.whenStable().then(() => {
const fileNameSpan = fixture.debugElement.query(By.css('#fileName')).nativeElement;
expect(fileNameSpan.textContent).toContain('test1.jpg');
expect(onTouchFunc).toHaveBeenCalledTimes(1);
});
});
it('should upload image', async () => {
component.fileType = 'singleImage';
fixture.detectChanges();
const onChangeFunc = jest.fn();
component.registerOnChange(onChangeFunc);
const mockedFile = new File([], 'test1.jpg');
const changeEvent = {
target: {
files: [mockedFile],
},
};
fixture.debugElement.query(By.css('input#fileDropRef')).triggerEventHandler('change', changeEvent);
component.uploadFile(mockedFile);
fixture.detectChanges();
fixture.whenStable().then(() => {
const fileNameSpan = fixture.debugElement.query(By.css('#fileName')).nativeElement;
expect(fileNameSpan.textContent).toContain('test1.jpg');
expect(onChangeFunc).toHaveBeenCalled();
expect(onChangeFunc.mock.calls[0][0]).toBe('http://file-url.com');
});
});
it('should init file', async () => {
component.fileType = 'singleFile';
component.writeValue('http://someimage.com/213123.png');
fixture.detectChanges();
await fixture.whenStable().then(() => {
const fileNameSpan = fixture.debugElement.query(By.css('#fileName')).nativeElement;
expect(fileNameSpan.textContent).toContain('test1.jpg');
});
});
it('should init files', async () => {
component.fileType = 'multiFile';
component.writeValue(['http://someimage.com/213123.png', 'http://someimage2.com/213121233.png']);
fixture.detectChanges();
await fixture.whenStable().then(() => {
const fileNameSpan = fixture.debugElement.query(By.css('#fileName')).nativeElement;
expect(fileNameSpan.textContent).toContain('test1.jpg');
});
});
it('download public file', async () => {
global.open = jest.fn();
component.fileType = 'singleFile';
component.writeValue('http://someimage.com/213123.png');
fixture.detectChanges();
await fixture.whenStable().then(() => {
const downloadFile = fixture.debugElement.query(By.css('#downloadFile'));
downloadFile.triggerEventHandler('click', {});
expect(global.open).toHaveBeenCalledWith('http://file-url.com', '_blank');
});
});
it('download private file', async () => {
global.open = jest.fn();
component.fileType = 'privateSingleFile';
component.writeValue('http://someimageprivate.com/213123.png');
fixture.detectChanges();
await fixture.whenStable().then(() => {
const downloadFile = fixture.debugElement.query(By.css('#downloadFile'));
downloadFile.triggerEventHandler('click', {});
expect(global.open).toHaveBeenCalledWith('http://file-url.com', '_blank');
});
});
it('delete file', async () => {
const onChangeFunc = jest.fn();
component.registerOnChange(onChangeFunc);
component.fileType = 'privateSingleFile';
component.writeValue('http://someimageprivate.com/213123.png');
fixture.detectChanges();
await fixture.whenStable().then(() => {
const deleteFile = fixture.debugElement.query(By.css('#closeLink'));
deleteFile.triggerEventHandler('click', {});
expect(onChangeFunc.mock.calls[1][0]).toBe(null);
});
});
it('on file drop', async () => {
const fileDropped = {
dataTransfer: {
files: null,
},
};
fixture.debugElement.query(By.css('.file-container_without-files')).triggerEventHandler('fileDropped', fileDropped);
fixture.detectChanges();
await fixture.whenStable().then(() => {
const fileDrop = fixture.debugElement.query(By.css('#fileDropRef')).nativeElement;
expect(fileDrop).toBeTruthy();
});
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-recommended-apps/oc-recommended-apps.component.spec.ts
|
<filename>projects/angular-common-components/src/lib/market-components/oc-recommended-apps/oc-recommended-apps.component.spec.ts<gh_stars>0
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcRecommendedAppsComponent } from './oc-recommended-apps.component';
import { By } from '@angular/platform-browser';
import { FullAppData, StatElement } from '@openchannel/angular-common-components/src/lib/common-components';
import { MockAppCardComponent, MockHeadingTagDirective } from '@openchannel/angular-common-components/src/mock/mock';
import { RouterTestingModule } from '@angular/router/testing';
const stat: StatElement = {
'90day': 30,
'30day': 10,
total: 40,
};
const app: FullAppData = {
appId: '344gf-43s3j-gi3423',
icon: '',
name: '<NAME>',
model: [
{
type: 'recurring',
price: 5,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 4.2,
reviewCount: 20,
summary: 'Some test summary',
description: 'Some Description',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3232gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: 'pending',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
describe('OcRecommendedAppsComponent', () => {
let component: OcRecommendedAppsComponent;
let fixture: ComponentFixture<OcRecommendedAppsComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcRecommendedAppsComponent, MockAppCardComponent, MockHeadingTagDirective],
imports: [RouterTestingModule.withRoutes([])],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcRecommendedAppsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show data', () => {
component.appList = [app, app, app];
component.recommendedAppTitle = 'Test Recommended';
fixture.detectChanges();
const title: HTMLHeadingElement = fixture.debugElement.query(By.css('h2')).nativeElement;
expect(title.textContent).toContain('Test Recommended');
});
it('should show no data message', () => {
component.noAppMessage = 'There is no apps yet';
fixture.detectChanges();
const emptyMessage: HTMLHeadingElement = fixture.debugElement.query(By.css('h5')).nativeElement;
expect(emptyMessage.textContent).toContain('There is no apps yet');
});
});
|
mukesh-openchannel/angular-template-libraries
|
src/select.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcCommonLibModule, OcSelectComponent } from '@openchannel/angular-common-components/src/lib/common-components';
/**
* List of module dependencies and component declarations.
* Stored as separate var because they are shared among all stories
*/
const modules = {
imports: [OcCommonLibModule],
};
export default {
title: 'Select [BEM]',
component: OcSelectComponent,
decorators: [moduleMetadata(modules)],
};
const SelectComponent = (args: OcSelectComponent) => ({
component: OcSelectComponent,
moduleMetadata: modules,
props: args,
});
export const SimpleSelect = SelectComponent.bind({});
SimpleSelect.args = {
selectValArr: ['Assembly', 'Communication'],
};
export const ObjectSelect = SelectComponent.bind({});
ObjectSelect.args = {
selectValArr: [{ label: 1 }, { label: 2 }],
labelField: 'label',
};
export const SelectedObjectValue = SelectComponent.bind({});
SelectedObjectValue.args = {
selectValArr: [{ label: 1 }, { label: 2 }],
isObject: true,
labelField: 'label',
value: { label: 1 },
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/ownership.service.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { Injectable } from '@angular/core';
import { HttpRequestService } from './http-request-services';
import { Observable } from 'rxjs';
import { CreateOwnershipModel, OwnershipModelResponse } from '../model/api/ownership.model';
import { HttpHeaders } from '@angular/common/http';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
* Description: API service for managing Ownership.<br>
*
* Endpoints:<br>
*
* POST 'v2/ownership/install'<br>
*
* POST 'v2/ownership/uninstall/{ownershipId}'<br>
*/
@Injectable({
providedIn: 'root',
})
export class OwnershipService {
constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
*
* Description: Start new Ownership with provided data
*
* @param {CreateOwnershipModel} ownership - (required) Ownership Data to creation
* @param {HttpHeaders} headers (optional) (default: empty HttpHeaders object)
* @returns {Observable<OwnershipModelResponse>} `Observable<OwnershipModelResponse>`
*
* ### Example
*
* `installOwnership(
* {
* appId: '0a8hs09dhas09d8h9',
* modelId: '9a8hs9a86sgd97a6sgd'
* },
* {"Authorization":"Bearer as<PASSWORD>"}
* )`
*/
installOwnership(ownership: CreateOwnershipModel, headers: HttpHeaders = new HttpHeaders()): Observable<OwnershipModelResponse> {
return this.httpRequest.post(`${this.apiPaths.ownership}/install`, ownership, { headers });
}
/**
*
* Description: End Ownership with Id
*
* @param {CreateOwnershipModel} ownership - (required) Ownership Data to uninstall
* @param {HttpHeaders} headers (optional) (default: empty HttpHeaders object)
* @returns {Observable<OwnershipModelResponse>} `Observable<OwnershipModelResponse>`
*
* ### Example
*
* `uninstallOwnership('0a8hs09dhas09d8h9', {"Authorization":"Bearer as98hd90ahsd98has9d8ha98sd"})`
*/
uninstallOwnership(ownershipId: string, headers: HttpHeaders = new HttpHeaders()): Observable<OwnershipModelResponse> {
return this.httpRequest.post(`${this.apiPaths.ownership}/uninstall/${ownershipId}`, {}, { headers });
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-single-form/oc-single-form.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcSingleFormComponent } from './oc-single-form.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import {
MockButtonComponent,
MockCheckboxComponent,
MockColorComponent,
MockDateTimeComponent,
MockDropdownMultiApp,
MockDynamicFieldArrayComponent,
MockErrorComponent,
MockFileUploadComponent,
MockInputComponent,
MockMultiSelectCheckboxList,
MockMultiSelectComponent,
MockNumberComponent,
MockPasswordComponent,
MockRadioButtonListComponent,
MockRichEditorComponent,
MockSelectComponent,
MockTagsComponent,
MockTextareaComponent,
MockTooltipComponent,
MockVideoUrlComponent,
MockDropdownFormComponent,
MockAdditionalSelectComponent,
} from '@openchannel/angular-common-components/src/mock/mock';
import { ArraySearchPipe } from '@openchannel/angular-common-components/src/public-api';
describe('OcFormComponent', () => {
let component: OcSingleFormComponent;
let fixture: ComponentFixture<OcSingleFormComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
OcSingleFormComponent,
MockTooltipComponent,
MockRichEditorComponent,
MockTextareaComponent,
MockSelectComponent,
MockTagsComponent,
MockFileUploadComponent,
MockNumberComponent,
MockCheckboxComponent,
MockColorComponent,
MockVideoUrlComponent,
MockDateTimeComponent,
MockMultiSelectComponent,
MockDynamicFieldArrayComponent,
MockErrorComponent,
MockButtonComponent,
MockInputComponent,
MockPasswordComponent,
MockRadioButtonListComponent,
MockMultiSelectCheckboxList,
MockDropdownMultiApp,
MockDropdownFormComponent,
MockAdditionalSelectComponent,
ArraySearchPipe,
],
imports: [FormsModule, ReactiveFormsModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcSingleFormComponent);
component = fixture.componentInstance;
component.formJsonData = {
formId: '332323rfdf22323',
name: 'test-form',
fields: [
{
id: 'name',
label: 'name',
description: 'test',
defaultValue: null,
type: 'text',
attributes: {
maxChars: 20,
required: true,
minChars: 10,
},
options: null,
fields: null,
},
{
id: 'role',
label: 'role',
description: '',
defaultValue: 'user',
type: 'dropdownList',
attributes: { required: true },
options: ['admin', 'user', 'test'],
fields: null,
},
{
id: 'aboutme',
label: 'About Me',
description: '',
defaultValue: null,
type: 'richText',
attributes: {
maxChars: 150,
required: null,
minChars: 10,
},
options: null,
fields: null,
},
{
id: 'skills',
label: 'skills',
description: 'skills',
defaultValue: ['angular'],
type: 'tags',
attributes: {
minCount: 1,
maxCount: 5,
required: true,
},
options: null,
fields: null,
},
{
attributes: {
max: 25,
min: 5,
required: null,
},
defaultValue: null,
description: '',
id: 'test-number',
label: 'Test number',
placeholder: null,
type: 'number',
},
{
attributes: {
required: true,
},
category: 'CUSTOM',
defaultValue: true,
description: '',
id: 'test-checkbox',
label: 'Test Checkbox',
placeholder: null,
type: 'checkbox',
},
{
attributes: {
required: true,
},
defaultValue: null,
description: '',
id: 'test-email',
label: 'Test email',
placeholder: 'enter email',
type: 'emailAddress',
},
{
attributes: {
required: true,
},
defaultValue: null,
description: null,
id: 'test-url-component',
label: 'Test URL component',
placeholder: 'Enter your link here..',
type: 'websiteUrl',
},
{
attributes: {
required: true,
},
defaultValue: null,
description: null,
id: 'test-color-component',
label: 'Test Color Component',
placeholder: 'Choose your color',
type: 'color',
},
{
attributes: {
required: true,
maxCount: null,
minCount: null,
},
options: ['true', 'false'],
defaultValue: null,
description: null,
id: 'test-boolean-tags',
label: 'Test Boolean tags',
placeholder: null,
type: 'booleanTags',
},
{
attributes: {
required: true,
maxCount: 2,
minCount: 1,
},
options: ['1', '3', '45'],
category: 'CUSTOM',
defaultValue: [],
description: null,
id: 'test-number-tags',
label: 'Test number tags',
placeholder: null,
type: 'numberTags',
},
{
attributes: {
required: true,
},
defaultValue: null,
description: null,
id: 'test-date-picker',
label: 'Test Date picker',
placeholder: null,
type: 'date',
},
{
attributes: {
required: true,
},
defaultValue: 1602489693553,
description: null,
id: 'test-datetime-picker',
label: 'Test date-time picker',
placeholder: null,
type: 'datetime',
},
{
attributes: {
required: true,
},
defaultValue: 'https://www.youtube.com/watch?v=DGQwd1_dpuc',
description: null,
id: 'test-video-url-comp',
label: 'Test videoUrl component',
placeholder: null,
type: 'videoUrl',
},
{
attributes: {
required: true,
maxCount: 3,
minCount: 2,
},
options: ['One', 'Two', 'Three', 'Five'],
category: 'CUSTOM',
defaultValue: [],
description: null,
id: 'multi-select-test',
label: 'Multi Select test',
placeholder: null,
type: 'multiselectList',
},
{
attributes: {
required: true,
maxCount: 1,
minCount: null,
},
options: ['One', 'Two', 'Three', 'Five'],
category: 'CUSTOM',
defaultValue: [],
description: null,
id: 'multi-select-test2',
label: 'Multi Select test',
placeholder: null,
type: 'multiselectList',
},
{
attributes: {
maxCount: 3,
minCount: 1,
ordering: 'append',
required: true,
rowLabel: 'field1',
},
defaultValue: null,
description: '',
id: 'test-dynamic-field-array',
label: 'Test Dynamic field array',
placeholder: null,
fields: [
{
attributes: {
maxChars: null,
minChars: null,
required: null,
},
defaultValue: null,
description: 'some description',
id: 'field1',
label: 'field1',
placeholder: 'write some text',
type: 'text',
},
{
id: 'long-text-example',
label: 'Long Text Example',
type: 'longText',
placeholder: 'Write your text here...',
defaultValue: null,
attributes: {
maxChars: 200,
required: null,
minChars: 2,
},
},
],
type: 'dynamicFieldArray',
},
],
};
});
it('should create', () => {
jest.spyOn(component.createdForm, 'emit');
fixture.detectChanges();
expect(component).toBeTruthy();
expect(component.createdForm.emit).toHaveBeenCalledTimes(1);
});
it('should hide buttons', () => {
component.showButton = false;
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('oc-button'));
expect(button).toBeNull();
});
it('should show text on button', () => {
component.successButtonText = 'Text Button';
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('oc-button')).componentInstance;
expect(button.text).toEqual('Text Button');
});
it('should set form dirty', () => {
component.setFormDirty = true;
fixture.detectChanges();
const testControl = (Object as any).values(component.customForm.controls)[0];
expect(testControl.touched).toEqual(true);
expect(component.customForm.dirty).toEqual(true);
});
it('should show count validation errors', () => {
component.formJsonData.fields.push({
attributes: {
required: true,
maxCount: 3,
minCount: 2,
},
options: ['1', '3', '45'],
category: 'CUSTOM',
defaultValue: [],
description: null,
id: 'test-number-tags3',
label: 'Test number tags',
placeholder: null,
type: 'numberTags',
});
fixture.detectChanges();
const invalidControl = component.customForm.get('test-number-tags3');
invalidControl.setValue([1, 3, 5, 6]);
fixture.detectChanges();
expect(invalidControl.hasError('maxElementsCount')).toEqual(true);
invalidControl.setValue([1]);
fixture.detectChanges();
expect(invalidControl.hasError('minElementsCount')).toEqual(true);
});
it('should show url validation error', () => {
fixture.detectChanges();
const invalidControlEmail = component.customForm.get('test-url-component');
invalidControlEmail.setValue('mysite');
fixture.detectChanges();
expect(invalidControlEmail.hasError('websiteValidator')).toEqual(true);
});
it('should show color validation error', () => {
fixture.detectChanges();
const invalidControlColor = component.customForm.get('test-color-component');
invalidControlColor.setValue('333');
fixture.detectChanges();
expect(invalidControlColor.hasError('colorValidator')).toEqual(true);
});
it('should send data', () => {
jest.spyOn(component.formDataUpdated, 'emit');
component.showButton = true;
fixture.detectChanges();
const submitButton = fixture.debugElement.query(By.css('#successBtn')).nativeElement;
submitButton.click();
expect(component.formDataUpdated.emit).toHaveBeenCalledTimes(1);
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-dropdown-multi-app/oc-dropdown-multi-app.component.ts
|
<filename>projects/angular-common-components/src/lib/form-components/oc-dropdown-multi-app/oc-dropdown-multi-app.component.ts
import { Component, EventEmitter, forwardRef, Input, OnDestroy, OnInit, Output, TemplateRef } from '@angular/core';
import { Observable, of, Subject } from 'rxjs';
import { remove, isString } from 'lodash';
import { AppsSearchService } from '../model/dropdown-multi-app.model';
import { FullAppData } from '@openchannel/angular-common-components/src/lib/common-components';
import { switchMap, takeUntil, tap } from 'rxjs/operators';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'oc-dropdown-multi-app',
templateUrl: './oc-dropdown-multi-app.component.html',
styleUrls: ['./oc-dropdown-multi-app.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OcDropdownMultiAppComponent),
multi: true,
},
],
})
export class OcDropdownMultiAppComponent implements OnInit, OnDestroy, ControlValueAccessor {
@Input() dropdownPlaceholder: string = '';
@Input() dropdownClearTextAfterSelect: boolean = true;
@Input() dropdownCustomDropdownItemTemplateRef: TemplateRef<any>;
@Input() dropdownCustomTagTemplateRef: TemplateRef<any>;
@Input() defaultAppIDs: string[] = [];
@Input() itemPreviewName: string = 'App Name :';
@Input() itemPreviewId: string = 'Id :';
@Input() itemPreviewVersion: string = 'Version :';
@Input() tagTooltipLabelText: string = '';
@Input() set value(value: string[] | any) {
this.loadAppsByIDsAndPutToResultArray(this.selectAppIDs(value)).subscribe(() => this.updateOutputData());
}
@Output() readonly selectedAppsOutput: EventEmitter<FullAppData[]> = new EventEmitter<FullAppData[]>();
resultApps: FullAppData[] = [];
destroy$: Subject<boolean> = new Subject<boolean>();
constructor(private appSearchService: AppsSearchService) {}
appsSearchFn = (text$: Observable<string>) =>
text$.pipe(
switchMap(text => this.appSearchService.appsSearch(this.resultApps, text)),
takeUntil(this.destroy$),
);
ngOnInit(): void {
this.loadAppsByIDsAndPutToResultArray(this.defaultAppIDs).subscribe(() => this.updateOutputData());
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.unsubscribe();
}
addAppToResultArray(appResponse: FullAppData | any): void {
if (!this.resultApps.find(resultApp => resultApp.appId === appResponse.appId)) {
this.resultApps.push(appResponse);
this.updateOutputData();
}
}
removeAppFromResultArray(appResponse: FullAppData): void {
remove(this.resultApps, app => app?.appId === appResponse.appId);
this.updateOutputData();
}
registerOnChange(onChange: (value: any) => void): void {
this.onChange = onChange;
}
registerOnTouched(onTouched: () => void): void {
this.onTouched = onTouched;
}
// prettier-ignore
setDisabledState(isDisabled: boolean): void { // NOSONAR
}
writeValue(value: any): void {
this.loadAppsByIDsAndPutToResultArray(this.selectAppIDs(value)).subscribe();
}
onTouched = () => {
// nothing to do
};
private loadAppsByIDsAndPutToResultArray(appIdArray: string[]): Observable<FullAppData[]> {
if (appIdArray?.length > 0) {
return this.appSearchService.loadDefaultApps(appIdArray).pipe(
takeUntil(this.destroy$),
tap(apps => apps.forEach(app => this.addAppToResultArray(app))),
);
} else {
return of([]);
}
}
private updateOutputData(): void {
this.selectedAppsOutput.emit(this.resultApps);
this.onChange(this.resultApps.map(app => app.appId));
}
private selectAppIDs(data: any): string[] {
return Array.isArray(data) ? (data as []).filter(isString) : [];
}
private onChange: (value: any) => void = () => {
// nothing to do
};
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/custom-content.model.ts
|
<gh_stars>0
export interface SiteContentResponse {
siteId: string;
contentId: string;
type: string;
created: number;
lastUpdated: number;
customData: any;
}
export interface SecuritySettingsResponse {
/**
* The character limit for any string in the request body.
* Any request will be validated on the CAP side by this character limit.
* When any string value in the request body will be more then {@link maxCharacters}, CAP return response with 400 status.
*/
maxCharacters: number;
/**
* User can create a review without app ownership.
* Used for endpoint: https://support.openchannel.io/documentation/api/#448-reviews-create-review .
* When this property is true, CAP will inject property 'mustOwnApp' with the 'false' value.
*/
allowReviewsWithoutOwnership: boolean;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-form/oc-form-validator.spec.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { OcFormValidator } from './oc-form-validator';
import { AbstractControl, FormControl, ValidatorFn } from '@angular/forms';
describe('OcFormValidator', () => {
it('[Required] validator with empty objects.', () => {
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.required(null, false))).toBe(false);
expect(setValidatorAndValidate(new FormControl(''), OcFormValidator.required(null, false))).toBe(false);
expect(setValidatorAndValidate(new FormControl([]), OcFormValidator.required(null, false))).toBe(false);
});
it('[Required] validator with not empty objects.', () => {
expect(setValidatorAndValidate(new FormControl('a'), OcFormValidator.required(null, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(['a']), OcFormValidator.required(null, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(true), OcFormValidator.required(null, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(false), OcFormValidator.required(null, false))).toBe(true);
});
it('[Required] validator for [text] without trimming.', () => {
expect(setValidatorAndValidate(new FormControl(' '), OcFormValidator.required('text', false))).toBe(true);
});
it('[Required] validator for [text] with trimming.', () => {
expect(setValidatorAndValidate(new FormControl(' '), OcFormValidator.required('text', true))).toBe(false);
});
it('[Required] validator for [richText] without trimming.', () => {
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.required('richText', false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.required('richText', false))).toBe(false);
});
it('[Required] validator for [richText] with trimming.', () => {
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.required('richText', true))).toBe(false);
});
it('[Url] validator without trimming.', () => {
expect(setValidatorAndValidate(new FormControl('https://aaa.aaa.aaa/aaa'), OcFormValidator.urlValidator(false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(' https://aaa.aaa.aaa/aaa'), OcFormValidator.urlValidator(false))).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.urlValidator(false))).toBe(true);
// todo invalid regex, created ticket AT-1575.
// expect(setValidatorAndValidate(new FormControl('https---aaa.aaa.aaa/aaa'), OcFormValidator.urlValidator(false))).toBe(false);
});
it('[Url] validator with trimming.', () => {
expect(setValidatorAndValidate(new FormControl('https://aaa.aaa.aaa/aaa'), OcFormValidator.urlValidator(true))).toBe(true);
expect(setValidatorAndValidate(new FormControl(' https://aaa.aaa.aaa/aaa'), OcFormValidator.urlValidator(true))).toBe(true);
});
it('[Rich text min characters] validator without trimming.', () => {
expect(setValidatorAndValidate(new FormControl('<a>123<a>'), OcFormValidator.richTextMinCharactersValidator(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a>1234<a>'), OcFormValidator.richTextMinCharactersValidator(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.richTextMinCharactersValidator(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a>12<a>'), OcFormValidator.richTextMinCharactersValidator(3, false))).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.richTextMinCharactersValidator(3, false))).toBe(true);
});
it('[Rich text min characters] validator with trimming.', () => {
expect(setValidatorAndValidate(new FormControl('<a> 123 <a>'), OcFormValidator.richTextMinCharactersValidator(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a> 1234 <a>'), OcFormValidator.richTextMinCharactersValidator(3, true))).toBe(
true,
);
// Note: Removed all tags and spaces. Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.richTextMinCharactersValidator(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.richTextMinCharactersValidator(3, true))).toBe(true);
});
it('[Rich text max characters] validator without trimming.', () => {
expect(setValidatorAndValidate(new FormControl('<a>123<a>'), OcFormValidator.richTextMaxCharactersValidator(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.richTextMaxCharactersValidator(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a>1234<a>'), OcFormValidator.richTextMaxCharactersValidator(3, false))).toBe(
false,
);
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.richTextMaxCharactersValidator(3, false))).toBe(
false,
);
// Note: Removed all tags and spaces. Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.richTextMaxCharactersValidator(3, false))).toBe(true);
});
it('[Rich text max characters] validator with trimming.', () => {
expect(setValidatorAndValidate(new FormControl('<a>123<a>'), OcFormValidator.richTextMaxCharactersValidator(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a>1234<a>'), OcFormValidator.richTextMaxCharactersValidator(3, true))).toBe(false);
expect(setValidatorAndValidate(new FormControl('<a> 123 <a>'), OcFormValidator.richTextMaxCharactersValidator(3, true))).toBe(
true,
);
// Note: Removed all tags and spaces. Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.richTextMaxCharactersValidator(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('<a> <a>'), OcFormValidator.richTextMaxCharactersValidator(3, true))).toBe(true);
});
it('[Min length] validator without trimming.', () => {
expect(setValidatorAndValidate(new FormControl('123'), OcFormValidator.minLength(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('1234'), OcFormValidator.minLength(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(' '), OcFormValidator.minLength(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl(' '), OcFormValidator.minLength(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('12'), OcFormValidator.minLength(3, false))).toBe(false);
expect(setValidatorAndValidate(new FormControl(' '), OcFormValidator.minLength(3, false))).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.minLength(3, false))).toBe(true);
});
it('[Min length] validator with trimming.', () => {
expect(setValidatorAndValidate(new FormControl('123'), OcFormValidator.minLength(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl(' 123 '), OcFormValidator.minLength(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('12 '), OcFormValidator.minLength(3, true))).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.minLength(3, false))).toBe(true);
});
it('[Max length] validator without trimming.', () => {
expect(setValidatorAndValidate(new FormControl('12'), OcFormValidator.maxLength(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('12 '), OcFormValidator.maxLength(3, false))).toBe(true);
expect(setValidatorAndValidate(new FormControl('12 '), OcFormValidator.maxLength(3, false))).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.maxLength(3, false))).toBe(true);
});
it('[Max length] validator with trimming.', () => {
expect(setValidatorAndValidate(new FormControl('12 '), OcFormValidator.maxLength(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('123 '), OcFormValidator.maxLength(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl('1234 '), OcFormValidator.maxLength(3, true))).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.maxLength(3, true))).toBe(true);
expect(setValidatorAndValidate(new FormControl(' '), OcFormValidator.maxLength(3, true))).toBe(true);
});
it('[Password] validator without trimming.', () => {
// correct pass
expect(setValidatorAndValidate(new FormControl('aA@01119'), OcFormValidator.passwordValidator())).toBe(true);
// special character
expect(setValidatorAndValidate(new FormControl('aA001119'), OcFormValidator.passwordValidator())).toBe(false);
// upper case character
expect(setValidatorAndValidate(new FormControl('aa@01119'), OcFormValidator.passwordValidator())).toBe(false);
// lower case character
expect(setValidatorAndValidate(new FormControl('AA@01119'), OcFormValidator.passwordValidator())).toBe(false);
// numbers
expect(setValidatorAndValidate(new FormControl('aA@aaaaa'), OcFormValidator.passwordValidator())).toBe(false);
// test min length
expect(setValidatorAndValidate(new FormControl('aA<PASSWORD>'), OcFormValidator.passwordValidator())).toBe(false);
// Note: Valid, because used with 'required' validator
expect(setValidatorAndValidate(new FormControl(null), OcFormValidator.passwordValidator())).toBe(true);
expect(setValidatorAndValidate(new FormControl(''), OcFormValidator.passwordValidator())).toBe(true);
});
function setValidatorAndValidate<T extends AbstractControl>(control: T, validator: ValidatorFn): boolean {
control.setValidators(validator);
control.updateValueAndValidity();
return control.valid;
}
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/auth-components/models/signup-router-state.model.ts
|
/**
* State interface to pass to Signup page using Router if we want to show signup feedback page and skip
* the first step of signup.
*/
export interface SignupRouterState {
showSignupFeedbackPage: boolean;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-button/oc-button.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcButtonComponent } from './oc-button.component';
import { NgxSpinnerModule } from 'ngx-spinner';
describe('OcButtonComponent', () => {
let component: OcButtonComponent;
let fixture: ComponentFixture<OcButtonComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcButtonComponent],
imports: [NgxSpinnerModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcButtonComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain text value', () => {
component.text = 'Test button';
expect(component.text).toEqual('Test button');
});
it('should contain type value and exist', async () => {
component.buttonType = 'secondary';
const button = fixture.nativeElement.querySelector('button');
fixture.detectChanges();
expect(component.buttonType).toEqual('secondary');
await fixture.whenStable().then(() => {
expect(button).toBeTruthy();
});
});
it('button should be disabled', async () => {
component.disabled = true;
const button = fixture.nativeElement.querySelector('button');
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(button.disabled).toBeTruthy();
});
});
it('should click', async () => {
component.buttonType = 'secondary';
const button = fixture.nativeElement.querySelector('button');
button.dispatchEvent(new Event('click'));
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(component.buttonType).toBe('secondary');
});
});
});
|
mukesh-openchannel/angular-template-libraries
|
src/video-component.stories.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { moduleMetadata } from '@storybook/angular';
import { OcCommonLibModule, OcVideoComponent } from '@openchannel/angular-common-components/src/lib/common-components';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { EmbedVideoService } from 'ngx-embed-video';
import { OcVideoUrlComponent } from '@openchannel/angular-common-components/src/lib/form-components';
const modules = {
imports: [OcCommonLibModule, HttpClientModule],
providers: [EmbedVideoService, HttpClient],
};
export default {
title: 'Video component [BEM]',
component: OcVideoComponent,
decorators: [moduleMetadata(modules)],
};
const VideoComponent = (args: OcVideoUrlComponent) => ({
component: OcVideoComponent,
moduleMetadata: modules,
props: args,
});
export const DefaultVideo = VideoComponent.bind({});
DefaultVideo.args = {
videoUrl: 'https://www.youtube.com/watch?v=DGQwd1_dpuc',
};
export const WistiaVideo = VideoComponent.bind({});
WistiaVideo.args = {
videoUrl: 'https://softkit.wistia.com/medias/ou1sr5h6jt',
};
export const VidyardVideo = VideoComponent.bind({});
VidyardVideo.args = {
videoUrl: 'https://share.vidyard.com/watch/nmczXbtJDXrHm9LpLTkrEB',
};
export const BrightcoveVideo = VideoComponent.bind({});
BrightcoveVideo.args = {
videoUrl: 'https://players.brightcove.net/6259025838001/default_default/index.html?videoId=6259291147001',
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-app-card/oc-app-card.component.ts
|
<filename>projects/angular-common-components/src/lib/market-components/oc-app-card/oc-app-card.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { SafeResourceUrl } from '@angular/platform-browser';
import { AppModel, FullAppData } from '@openchannel/angular-common-components/src/lib/common-components';
@Component({
selector: 'oc-app-card',
templateUrl: './oc-app-card.component.html',
styleUrls: ['./oc-app-card.component.css'],
})
export class OcAppCardComponent implements OnInit {
/**
* The index of the price model in the array, default is 0
*/
@Input() priceModelIndex: number = 0;
/**
* One App to show. Must contain fields: "name", "model",
* "rating", "reviewCount", "summary" or "description"
* @type FullAppData
*/
@Input() set app(appData: FullAppData) {
this.appData = appData;
if (this.appData?.icon) {
this.appIcon = this.appData?.icon;
}
}
/**
* Emitting click by App card. Works only when appRedirectLink does not applied.
* Emmit Full App Data
*/
@Output() readonly clickByAppCard: EventEmitter<FullAppData> = new EventEmitter<FullAppData>();
appIcon: SafeResourceUrl | string = 'assets/angular-common-components/standard-app-icon.svg';
appData: FullAppData;
currentModel: AppModel;
constructor() {
// nothing to do
}
ngOnInit(): void {
this.currentModel = this.appData.model[this.priceModelIndex] || this.appData.model[0];
}
clickByApp(): void {
this.clickByAppCard.emit(this.appData);
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-color/oc-color.component.spec.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcColorComponent } from './oc-color.component';
import { FormsModule } from '@angular/forms';
import { ColorPickerModule } from 'ngx-color-picker';
describe('OcColorComponent', () => {
let component: OcColorComponent;
let fixture: ComponentFixture<OcColorComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcColorComponent],
imports: [FormsModule, ColorPickerModule],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcColorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain a color value', () => {
component.writeValue('#26c6da');
expect(component.colorValue).toEqual('#26c6da');
});
it('should set a color value', () => {
component.value = '#26c6da';
expect(component.colorValue).toEqual('#26c6da');
});
it('should change color picker position', () => {
component.colorPickerPosition = 'right';
expect(component.colorPickerPosition).toEqual('right');
});
it(
'should contain a color in input',
waitForAsync(() => {
component.writeValue('#26c6da');
const input = fixture.nativeElement.querySelector('.color-adjust__input');
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(input.value).toEqual('#26c6da');
});
}),
);
it('should bind color input value to field', () => {
const input = fixture.nativeElement.querySelector('.color-adjust__input');
const newInputVal = '#26c6da';
input.value = newInputVal;
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.colorValue).toBe(newInputVal);
});
it('input should contain placeholder', () => {
component.placeholder = 'test placeholder';
const input = fixture.nativeElement.querySelector('.color-adjust__input');
fixture.detectChanges();
expect(input.placeholder).toEqual('test placeholder');
});
it(
'should be disabled',
waitForAsync(() => {
component.setDisabledState(true);
const input = fixture.nativeElement.querySelector('.color-adjust__input');
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(input.disabled).toBeTruthy();
});
}),
);
it(
'should call onChange with value',
waitForAsync(() => {
const onChangeFunc = jest.fn();
component.registerOnChange(onChangeFunc);
const colorInput = fixture.nativeElement.querySelector('.color-adjust__input');
colorInput.value = '#26c6da';
colorInput.dispatchEvent(new Event('input'));
expect(onChangeFunc).toHaveBeenCalled();
expect(onChangeFunc.mock.calls[0][0]).toBe('#26c6da');
}),
);
it(
'should call onTouch',
waitForAsync(() => {
const onTouchedFunc = jest.fn();
component.registerOnTouched(onTouchedFunc);
const colorInput = fixture.nativeElement.querySelector('.color-adjust__input');
colorInput.dispatchEvent(new Event('focus'));
expect(onTouchedFunc).toHaveBeenCalled();
}),
);
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/service/developer-type.service.ts
|
import { Injectable } from '@angular/core';
import { HttpRequestService } from './http-request-services';
import { Observable } from 'rxjs';
import { DeveloperTypeModel } from '../model/api/developer.model';
import { Page } from '../model/api/page.model';
import { OcHttpParams } from '../model/api/http-params-encoder-model';
import { OcApiPaths } from '../oc-ng-common-service.module';
/**
* Description: API service for getting Developer Type related data. <br>
*
* Endpoints:<br>
*
* GET 'v2/developerTypes'<br>
*
* GET 'v2/developerTypes/{developerTypeId}'<br>
*/
@Injectable({
providedIn: 'root',
})
export class DeveloperTypeService {
constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {}
/**
*
* Description: Get developer type data
*
* @param {string} developerTypeId
* @param {any} httpOptions - (optional)
* @returns {Observable<DeveloperTypeModel>} `Observable<DeveloperTypeModel>`
*
* ### Example
*
* `getDeveloperType('jas9d9a8sjd',{headers: {Authorization: 'Bearer ba<PASSWORD>'}})`
*/
getDeveloperType(developerTypeId: string, httpOptions?: any): Observable<DeveloperTypeModel> {
const mainUrl = `${this.apiPaths.developerTypes}/${developerTypeId}`;
return this.httpRequest.get(mainUrl, httpOptions);
}
/**
*
* Description: Get list of all developer types with pagination
*
* @param {number} pageNumber - (optional) Current page index. Starts from >= 1.
* @param {number} limit - (optional) Count apps into response. Starts from >= 1.
* @param {string} query - (optional) Your specific search query.
* @returns {Observable<Page<DeveloperTypeModel>>} `Observable<Page<DeveloperTypeModel>>`
*
* ### Example
*
* `getAllDeveloperTypes(1,10,"{"name": {"$in":["first", "second"]}}")`
*/
getAllDeveloperTypes(pageNumber?: number, limit?: number, query?: string): Observable<Page<DeveloperTypeModel>> {
return this.httpRequest.get(this.apiPaths.developerTypes, {
params: new OcHttpParams().append('query', query).append('pageNumber', String(pageNumber)).append('limit', String(limit)),
});
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/management-components/oc-invite-modal/oc-invite-modal.component.ts
|
<reponame>mukesh-openchannel/angular-template-libraries
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { isString, merge } from 'lodash';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalInviteUserModel, ModalUpdateUserModel } from '../models/oc-modal.model';
import { ErrorMessageFormId } from '@openchannel/angular-common-components/src/lib/common-components';
/**
* Invite modal component. Represents component with configurable form for inviting user.
*
* @example <oc-invite-modal [modalData]="{
* userData: {userAccountId:"<KEY>"},
* requestUpdateAccount: (accountId: string, accountData: any) => Observable<any>
* }"></oc-invite-modal>
*/
@Component({
selector: 'oc-invite-modal',
templateUrl: './oc-invite-modal.component.html',
styleUrls: ['./oc-invite-modal.component.css'],
})
export class OcInviteModalComponent implements OnInit {
/**
* Data main data model for modal windows. Contain invite user or update user data model.
*/
@Input() modalData: ModalInviteUserModel | ModalUpdateUserModel;
/** Current form ID. Used for modifying error messages. Look: {@link ErrorMessageFormId} */
@Input() formId: ErrorMessageFormId = null;
/**
* Config for custom form generation
*/
formConfig: any = {};
/**
* Custom form
*/
formGroup: FormGroup;
/**
* Data from custom form
*/
formData: any;
/**
* Show spinner while inviting requests
*/
inProcess = false;
/**
* @private List of user roles
*/
private listRoles: any = {};
/**
* @private Active modal window instance
*/
private modal: NgbActiveModal;
constructor(modal: NgbActiveModal) {
this.modal = modal;
}
ngOnInit(): void {
this.makeFormConfig();
this.setUserRolesToForm();
}
/**
* Initialisation of form config
*/
makeFormConfig(): void {
this.formConfig.fields = [
{
id: 'name',
label: 'Name',
description: '',
placeholder: 'Enter Name',
defaultValue: null,
type: 'text',
required: null,
attributes: {
maxChars: null,
required: true,
minChars: null,
},
options: null,
},
{
id: 'email',
label: 'Email',
description: '',
placeholder: 'Email',
defaultValue: null,
type: 'emailAddress',
required: null,
attributes: {
maxChars: null,
required: true,
minChars: null,
},
options: null,
},
{
id: 'roles',
label: 'Select role',
description: '',
defaultValue: '',
type: 'dropdownList',
required: true,
attributes: { required: true },
options: [],
},
];
if (this.modalData instanceof ModalUpdateUserModel) {
const updateUserData: ModalUpdateUserModel = this.modalData;
this.formConfig.fields.forEach(field => {
field.defaultValue = updateUserData.userData[field.id];
});
}
}
/**
* Find user roles data and apply it to main form.
*/
setUserRolesToForm(): void {
this.modalData.requestFindUserRoles().subscribe(
result => {
if (result.list && result.list.length > 0) {
const roles: string[] = [];
result.list.forEach((r: { developerRoleId?: string; userRoleId?: string; name: string }) => {
if (r?.developerRoleId) {
this.listRoles[r.name] = r.developerRoleId;
} else if (r?.userRoleId) {
this.listRoles[r.name] = r.userRoleId;
}
roles.push(r.name);
});
this.formConfig.fields.find(field => field.id === 'roles').options = roles;
if (!(this.modalData instanceof ModalUpdateUserModel)) {
this.formConfig.fields.find(field => field.id === 'roles').defaultValue = roles[0];
}
} else {
this.dismiss();
}
},
() => this.dismiss(),
);
}
/**
* Set form to value
* @param {FormGroup} createdForm
*/
setCreatedForm(createdForm: FormGroup): void {
this.formGroup = createdForm;
}
/**
* Set data from form to value
* @param {any} data
*/
setDataFromForm(data: any): void {
this.formData = data;
}
/**
* Function that executes on click to confirm button. Check validity of form and calls request function.
*/
onClickConfirmButton(): void {
if (this.formGroup) {
this.formGroup.markAllAsTouched();
if (this.formGroup.valid && this.formData && !this.inProcess) {
this.inProcess = true;
const roles = (isString(this.formData?.roles) ? [this.formData.roles] : this.formData?.roles).map(r => this.listRoles[r]);
this.formData.roles = roles;
if (this.modalData instanceof ModalUpdateUserModel) {
this.updateUser(this.modalData);
} else {
this.inviteUser(this.modalData);
}
}
}
}
/**
* Dismiss modal function
*/
dismiss(): void {
this.modal.dismiss();
}
/**
* Function that call Update User method
* @param {ModalUpdateUserModel} updateModalData
*/
private updateUser(updateModalData: ModalUpdateUserModel): void {
updateModalData
.requestUpdateAccount(this.getAccountId(updateModalData.userData), merge(updateModalData.userData, this.formData))
.subscribe(
() => {
this.inProcess = false;
this.modal.close(true);
},
() => {
this.inProcess = false;
},
);
}
/**
* Function that call Invite user method
* @param {ModalInviteUserModel} inviteModalData
*/
private inviteUser(inviteModalData: ModalInviteUserModel): void {
inviteModalData.requestSendInvite(this.formData).subscribe(
() => {
this.inProcess = false;
this.modal.close(true);
},
() => {
this.inProcess = false;
},
);
}
/**
* Get developer or user account id
* @param {any} userData
* @returns `string` or `null`
*/
private getAccountId(userData: any): string {
if (userData?.userAccountId) {
return userData.userAccountId;
} else if (userData?.developerAccountId) {
return userData.developerAccountId;
}
return null;
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/model/progress-bar-item.model.ts
|
export interface FormProgressbarStep {
title: string;
state: 'pristine' | 'finished' | 'invalid';
}
|
mukesh-openchannel/angular-template-libraries
|
src/multiSelectList.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
import { OcMultiSelectListComponent } from '@openchannel/angular-common-components/src/lib/form-components';
const modules = {
imports: [OcCommonLibModule],
};
export default {
title: 'Multi Select List [BEM]',
component: OcMultiSelectListComponent,
decorators: [moduleMetadata(modules)],
};
const MultiSelectList = (args: OcMultiSelectListComponent) => ({
component: OcMultiSelectListComponent,
moduleMetadata: modules,
props: args,
});
export const BasicMultiSelectList = MultiSelectList.bind({});
BasicMultiSelectList.args = {
label: 'Multi Select Items List',
availableItemsList: ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'],
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-label/oc-label.component.spec.ts
|
<filename>projects/angular-common-components/src/lib/common-components/oc-label/oc-label.component.spec.ts<gh_stars>0
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcLabelComponent } from './oc-label.component';
describe('OcLabelComponent', () => {
let component: OcLabelComponent;
let fixture: ComponentFixture<OcLabelComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcLabelComponent],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcLabelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain a text', () => {
component.text = 'Test label';
const label = fixture.nativeElement.querySelector('label');
fixture.detectChanges();
expect(label.textContent.trim()).toBe('Test label');
});
it('should contain a required indicator', async () => {
component.required = true;
fixture.detectChanges();
const required = fixture.nativeElement.querySelector('.oc-form-label__required');
await fixture.whenStable().then(() => {
expect(required).toBeTruthy();
});
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-video/oc-video.component.spec.ts
|
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcVideoComponent } from './oc-video.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { EmbedVideoService } from 'ngx-embed-video';
import { NgxSpinnerModule, NgxSpinnerService } from 'ngx-spinner';
describe('OcVideoComponent', () => {
let component: OcVideoComponent;
let fixture: ComponentFixture<OcVideoComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcVideoComponent],
imports: [HttpClientTestingModule, NgxSpinnerModule],
providers: [EmbedVideoService, NgxSpinnerService],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcVideoComponent);
component = fixture.componentInstance;
});
it('should create', () => {
component.videoUrl = 'https://www.youtube.com/watch?v=DGQwd1_dpuc';
expect(component).toBeTruthy();
});
it('should load video', () => {
component.videoUrl = 'https://www.youtube.com/watch?v=DGQwd1_dpuc';
fixture.detectChanges();
const videoFrame = fixture.nativeElement.querySelector('iframe');
expect(videoFrame).toBeTruthy();
});
it('should mp4 video', () => {
component.videoUrl = 'http://techslides.com/demos/sample-videos/small.mp4';
fixture.detectChanges();
const videoFrame = fixture.nativeElement.querySelector('video');
expect(videoFrame).toBeTruthy();
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/pipe/get-text-by-path.pipe.spec.ts
|
<gh_stars>0
import { GetTextByPathPipe } from '@openchannel/angular-common-components/src/lib/common-components/pipe/get-text-by-path.pipe';
describe('GetTextByPathPipe', () => {
let pipe: GetTextByPathPipe;
let value: any;
beforeEach(() => {
pipe = new GetTextByPathPipe();
value = {
textField: 'text-value',
textFieldWithHtmlTags: '<a>text-value-with-tags</a>',
emptyTextField: '',
numberField: 0,
objectField: {
textField: 'text-value-from-object-field',
},
emptyObjectField: null,
};
});
it('Get text value by path', () => {
expect(pipe.transform(value, 'textField')).toBe('text-value');
});
it('Get text value by multi field path.', () => {
expect(pipe.transform(value, 'objectField.textField', 'default-value')).toBe('text-value-from-object-field');
});
it('Get number value by path. Convert to string.', () => {
expect(pipe.transform(value, 'numberField')).toBe('0');
});
it('Replace HTML tags.', () => {
expect(pipe.transform(value, 'textFieldWithHtmlTags')).toBe('text-value-with-tags');
});
it('Without HTML tag replacing.', () => {
expect(pipe.transform(value, 'textFieldWithHtmlTags', '', false)).toBe('<a>text-value-with-tags</a>');
});
it('Use default value, when value by path is empty or null.', () => {
expect(pipe.transform(value, 'emptyTextField', 'default-value')).toBe('default-value');
});
it('Use default value, when value by path is not text.', () => {
expect(pipe.transform(value, 'objectField', 'default-value')).toBe('default-value');
});
});
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/review.model.ts
|
<filename>projects/angular-common-services/src/lib/model/api/review.model.ts
import { User } from './user.model';
export interface Status {
value: string;
}
export interface UserReviewModel extends Omit<User, 'permissions' | 'roles'> {
accountCount: number;
}
export interface ReviewModel {
rating: number;
description: string;
headline: string;
type?: string;
customData?: any;
}
export interface CreateReviewRequest extends ReviewModel {
appId: string;
}
export interface UpdateReviewRequest extends ReviewModel {
reviewId: string;
}
export interface ReviewResponse extends ReviewModel {
reviewId: string;
appId: string;
userId: string;
appName: string;
status: Status;
appVersion: number;
reportDate: number | Date;
user: UserReviewModel;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/model/dropdown-multi-app.model.ts
|
import { Observable } from 'rxjs';
import { FullAppData } from '@openchannel/angular-common-components/src/lib/common-components';
export abstract class AppsSearchService {
abstract loadDefaultApps(existsAppIDs: string[]): Observable<FullAppData[]>;
abstract appsSearch(existsAppIDs: FullAppData[], searchText: string): Observable<FullAppData[]>;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/oc-content-modal/oc-content-modal.component.ts
|
import { AfterViewInit, Component, ElementRef, Input, TemplateRef, ViewChild } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'oc-content-modal',
templateUrl: './oc-content-modal.component.html',
styleUrls: ['./oc-content-modal.component.css'],
})
export class OcContentModalComponent implements AfterViewInit {
@ViewChild('contentModal', { static: false }) contentModal: ElementRef;
/**
* modal title at the top of the window (optional).
*/
@Input() modalTitle: string;
/**
* custom content, can contain any type of layout, including text, lists, tables, links etc.
*/
@Input() customContentTemplate: TemplateRef<any>;
/**
* allows to add a `close` button in the bottom of the modal.
*/
@Input() closeButton: boolean = false;
/**
* allows to change the close icon, adding a new source to it as a string.
*/
@Input() closeIconSource: string = 'assets/angular-common-components/close-icon.svg';
hasLongContent: boolean = false;
constructor(private modal: NgbActiveModal) {}
ngAfterViewInit(): void {
if (this.contentModal.nativeElement.offsetHeight > window.innerHeight / 2) {
this.hasLongContent = true;
}
}
dismiss(): void {
this.modal.dismiss();
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/form-components/oc-video-url/oc-video-url.component.spec.ts
|
import { async, ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcVideoUrlComponent } from './oc-video-url.component';
import { FormsModule } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Observable, of } from 'rxjs';
import { By } from '@angular/platform-browser';
import { EmbedVideoService } from 'ngx-embed-video';
import { OcVideoComponent } from '@openchannel/angular-common-components/src/lib/common-components';
import { NgxSpinnerModule } from 'ngx-spinner';
describe('OcVideoUrlComponent', () => {
let component: OcVideoUrlComponent;
let fixture: ComponentFixture<OcVideoUrlComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcVideoUrlComponent, OcVideoComponent],
imports: [FormsModule, HttpClientTestingModule, NgxSpinnerModule],
providers: [EmbedVideoService],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcVideoUrlComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should contain value in input', async () => {
component.writeValue('https://www.youtube.com/watch?v=DGQwd1_dpuc');
const input = fixture.debugElement.query(By.css('input')).nativeElement;
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(component.videoUrl).toEqual('https://www.youtube.com/watch?v=DGQwd1_dpuc');
expect(input.value).toContain('https://www.youtube.com/watch?v=DGQwd1_dpuc');
});
});
it('input should contain placeholder', () => {
component.placeholder = 'test input';
const input = fixture.debugElement.query(By.css('input')).nativeElement;
fixture.detectChanges();
expect(input.placeholder).toEqual('test input');
});
it('input should be disabled', async () => {
component.setDisabledState(true);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
fixture.detectChanges();
await fixture.whenStable().then(() => {
expect(input.disabled).toBeTruthy();
});
});
it('should call onChange with value', async () => {
const onChangeFunc = jest.fn();
component.registerOnChange(onChangeFunc);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'test on change';
input.dispatchEvent(new Event('input'));
expect(onChangeFunc).toHaveBeenCalled();
expect(onChangeFunc.mock.calls[0][0]).toBe('test on change');
});
it('should call onTouch', async () => {
const onTouchedFunc = jest.fn();
component.registerOnTouched(onTouchedFunc);
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'test on change';
input.dispatchEvent(new Event('focus'));
expect(onTouchedFunc).toHaveBeenCalled();
});
it('should load video', () => {
const input = fixture.debugElement.query(By.css('input')).nativeElement;
input.value = 'https://www.youtube.com/watch?v=DGQwd1_dpuc';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
const videoFrame = fixture.nativeElement.querySelector('iframe');
expect(videoFrame).toBeTruthy();
});
it('should mp4 video', () => {
component.videoUrl = 'https://techslides.com/demos/sample-videos/small.mp4';
component.emitChanges();
fixture.detectChanges();
const videoFrame = fixture.nativeElement.querySelector('video');
expect(videoFrame).toBeTruthy();
});
it('should not load video ', () => {
component.videoUrl = 'some text';
fixture.detectChanges();
const video = fixture.nativeElement.querySelector('video');
const videoFrame = fixture.nativeElement.querySelector('iframe');
expect(video).toBeFalsy();
expect(videoFrame).toBeFalsy();
});
});
class MockFleService {
getVideoData(videoUrl): Observable<any> {
if (videoUrl && !videoUrl.endsWith('.mp4')) {
return of({
html:
'<div><div style="left: 0; width: 100%; height: 0; position: relative; padding-bottom: 56.25%;">' +
'<iframe ' +
'src="https://cdn.iframe.ly/api/iframe?url=https%3A%2F%2Fyoutu.be%2FDGQwd1_dpuc&key=<KEY>" ' +
'style="border: 0; top: 0; left: 0; width: 100%; height: 100%; position: absolute;" ' +
'allowfullscreen scrolling="no" allow="encrypted-media *; accelerometer; gyroscope; picture-in-picture"></iframe>' +
'</div></div>',
});
} else {
return of({
error: true,
});
}
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-review/oc-review.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { OcReviewComponent } from './oc-review.component';
import {
MockButtonComponent,
MockErrorComponent,
MockInputComponent,
MockLabelComponent,
MockRatingComponent,
MockTextareaComponent,
} from '@openchannel/angular-common-components/src/mock/mock';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
describe('OcReviewComponent', () => {
let component: OcReviewComponent;
let fixture: ComponentFixture<OcReviewComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
OcReviewComponent,
MockRatingComponent,
MockButtonComponent,
MockInputComponent,
MockTextareaComponent,
MockErrorComponent,
MockLabelComponent,
],
imports: [FormsModule, ReactiveFormsModule],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(OcReviewComponent);
component = fixture.componentInstance;
component.enableButtons = true;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show heading', () => {
fixture.detectChanges();
component.heading = 'Test Heading';
fixture.detectChanges();
const heading = fixture.debugElement.query(By.css('.review__heading')).nativeElement;
expect(heading.textContent).toEqual('Test Heading');
});
it('should clear form on Cancel', () => {
fixture.detectChanges();
component.reviewForm.get('rating').setValue(300);
component.reviewForm.get('headline').setValue('Test Review');
component.reviewForm.get('description').setValue('Test');
fixture.detectChanges();
fixture.debugElement.query(By.css('.review__button-cancel')).nativeElement.click();
expect(component.reviewForm.getRawValue()).toEqual({ rating: null, headline: null, description: null });
});
it('should submit the review', () => {
fixture.detectChanges();
jest.spyOn(component.reviewFormData, 'emit');
component.reviewForm.get('rating').setValue(300);
component.reviewForm.get('headline').setValue('Test Review');
component.reviewForm.get('description').setValue('Test');
fixture.detectChanges();
fixture.debugElement.query(By.css('.review__button-submit')).nativeElement.click();
expect(component.reviewFormData.emit).toHaveBeenCalledTimes(1);
expect(component.reviewForm.getRawValue()).toEqual({ rating: 300, headline: 'Test Review', description: 'Test' });
});
it('should submit the review with disabled buttons', () => {
component.enableButtons = false;
fixture.detectChanges();
jest.spyOn(component.reviewFormData, 'emit');
component.reviewForm.get('rating').setValue(500);
component.reviewForm.get('headline').setValue('Test Review2');
component.reviewForm.get('description').setValue('Test2');
fixture.detectChanges();
expect(component.reviewFormData.emit).toHaveBeenCalledTimes(3);
});
});
|
mukesh-openchannel/angular-template-libraries
|
src/consent.stories.ts
|
import { moduleMetadata } from '@storybook/angular';
import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components';
import { OcConsentComponent } from '@openchannel/angular-common-components';
import { action } from '@storybook/addon-actions';
const modules = {
imports: [OcCommonLibModule],
};
export default {
title: 'Consent checkbox [BEM]',
component: OcConsentComponent,
decorators: [moduleMetadata(modules)],
argTypes: { checkedChange: action('Checkbox value') },
};
const ConsentComponent = (args: OcConsentComponent) => ({
component: OcConsentComponent,
moduleMetadata: modules,
props: args,
});
export const DefaultTermsAndConsent = ConsentComponent.bind({});
DefaultTermsAndConsent.args = {
termsUrl: 'https://support.openchannel.io/documentation/api/',
policyUrl: 'https://support.openchannel.io/documentation/api/',
value: false,
};
export const DisabledTermsAndConsent = ConsentComponent.bind({});
DisabledTermsAndConsent.args = {
termsUrl: 'https://support.openchannel.io/documentation/api/',
policyUrl: 'https://support.openchannel.io/documentation/api/',
value: true,
disabled: true,
};
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/validators/white-space-validator.ts
|
import { Directive } from '@angular/core';
import { FormControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms';
@Directive({
selector: '[ocWhiteSpaceValidator]',
providers: [{ provide: NG_VALIDATORS, useExisting: WhiteSpaceValidatorDirective, multi: true }],
})
export class WhiteSpaceValidatorDirective implements Validator {
validate(c: FormControl): ValidationErrors {
const isWhitespace = c.value ? c.value.trim().length === 0 : false;
const message = {
whiteSpaceValidator: {
message: 'Please fill out this field ',
},
};
return !isWhitespace ? null : message;
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-services/src/lib/model/api/market.model.ts
|
<gh_stars>0
export interface MarketModel {
marketplaceId: string;
customerId: string;
name: string;
type: string;
previewAppUrl: string;
viewAppUrl: string;
}
export type AuthType = 'EXTERNAL' | 'AUTH_20' | 'SAML_20';
export interface SiteAuthConfig {
type: AuthType;
clientId: string;
clientSecret: string;
issuer: string;
grantType: string;
scope: string;
validationMode: string;
clientAccessType: string;
/**
* SAML 2.0 link for sign-in.
*/
singleSignOnUrl: string;
/**
* SAML 2.0 link for sign-out.
*/
singleLogOutUrl: string;
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/common-components/validators/checkbox-required.directive.ts
|
import { Directive } from '@angular/core';
import { FormControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms';
@Directive({
selector: '[ocCheckboxRequired]',
providers: [{ provide: NG_VALIDATORS, useExisting: CheckboxRequiredDirective, multi: true }],
})
export class CheckboxRequiredDirective implements Validator {
validate(c: FormControl): ValidationErrors {
return c.value === true
? null
: {
required: {
message: 'Required checkbox!',
},
};
}
}
|
mukesh-openchannel/angular-template-libraries
|
projects/angular-common-components/src/lib/market-components/oc-app-list-grid/oc-app-list-grid.component.spec.ts
|
<filename>projects/angular-common-components/src/lib/market-components/oc-app-list-grid/oc-app-list-grid.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { OcAppListGridComponent } from './oc-app-list-grid.component';
import { By } from '@angular/platform-browser';
import { FullAppData, StatElement, PricePipe } from '@openchannel/angular-common-components/src/lib/common-components';
import { MockRatingComponent, MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock';
import { RouterTestingModule } from '@angular/router/testing';
const stat: StatElement = {
'90day': 20,
'30day': 10,
total: 30,
};
const app: FullAppData = {
appId: '344gf-42s3j-gi3423',
icon: '',
name: '<NAME>',
model: [
{
type: 'recurring',
price: 5,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 4.2,
reviewCount: 20,
summary: 'Some test summary',
description: 'Some Description',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3232gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: 'inDevelopment',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
};
describe('OcAppListGridComponent', () => {
let component: OcAppListGridComponent;
let fixture: ComponentFixture<OcAppListGridComponent>;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [OcAppListGridComponent, MockRatingComponent, PricePipe, MockSvgIconComponent],
imports: [RouterTestingModule.withRoutes([])],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(OcAppListGridComponent);
component = fixture.componentInstance;
component.appList = [
{
appId: '344gf-43s3j-gi3423',
icon: 'assets/angular-common-components/get-started.svg',
name: 'Plugin',
model: [
{
type: 'free',
price: 0,
trial: 1,
license: 'single',
modelId: '23235hfg4',
currency: 'EUR',
billingPeriod: 'monthly',
},
],
rating: 3.5,
reviewCount: 12,
summary: 'With this plugin you can communicate with your teammates any time',
description: 'With this plugin you can communicate with your teammates any time',
lastUpdated: new Date(),
version: 1.1,
safeName: ['test-app'],
developerId: '44555-3232gvdfdf',
submittedDate: new Date(),
created: new Date().getMonth() - 2,
status: {
value: 'approved',
lastUpdated: 1.1,
modifiedBy: '',
reason: '',
},
statistics: {
views: stat,
downloads: stat,
developerSales: stat,
totalSales: stat,
ownerships: stat,
reviews: stat,
},
isLive: true,
},
];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show no data message', () => {
component.noAppMessage = 'No app found';
component.appList = [];
fixture.detectChanges();
const emptyDataMessage: HTMLHeadingElement = fixture.debugElement.query(By.css('h5')).nativeElement;
expect(emptyDataMessage.textContent).toContain('No app found');
});
it('should show App data', async () => {
const appTitle: HTMLParagraphElement = fixture.debugElement.query(By.css('p')).nativeElement;
const appPrice: HTMLSpanElement = fixture.debugElement.query(By.css('span')).nativeElement;
const appIcon: HTMLImageElement = fixture.nativeElement.querySelector('#appImage');
await fixture.whenStable().then(() => {
expect(appTitle.textContent).toContain('Plugin');
expect(appPrice.textContent).toContain('Free');
expect(appIcon.src).toContain('assets/angular-common-components/get-started.svg');
});
});
it('should show Free price on empty model', () => {
app.model = [];
component.appList = [app];
fixture.detectChanges();
const priceField: HTMLSpanElement = fixture.debugElement.query(By.css('.app-list__card-price')).nativeElement;
expect(priceField.textContent).toContain('Free');
});
it('should check rating data', () => {
app.rating = 500;
component.appList = [app];
fixture.detectChanges();
const ratingComponent = fixture.debugElement.query(By.css('oc-rating'));
expect(ratingComponent).toBeTruthy();
});
});
|
lukemwillis/koinos-as-sdk-examples
|
token/assembly/Token.ts
|
import { authority, Base58, Protobuf, System } from "koinos-as-sdk";
import { token } from "./proto/token";
import { State } from "./State";
export class Token {
_name: string = "Token";
_symbol: string = "TKN";
_decimals: u32 = 8;
_contractId: Uint8Array;
_state: State;
constructor() {
this._contractId = System.getContractId();
this._state = new State(this._contractId);
}
name(args: token.name_arguments): token.name_result {
return new token.name_result(this._name);
}
symbol(args: token.symbol_arguments): token.symbol_result {
return new token.symbol_result(this._symbol);
}
decimals(args: token.decimals_arguments): token.decimals_result {
return new token.decimals_result(this._decimals);
}
total_supply(args: token.total_supply_arguments): token.total_supply_result {
const supply = this._state.GetSupply();
const res = new token.total_supply_result();
res.value = supply.value;
return res;
}
balance_of(args: token.balance_of_arguments): token.balance_of_result {
const owner = args.owner as Uint8Array;
const balanceObj = this._state.GetBalance(owner);
const res = new token.balance_of_result();
res.value = balanceObj.value;
return res;
}
transfer(args: token.transfer_arguments): token.transfer_result {
const from = args.from as Uint8Array;
const to = args.to as Uint8Array;
const value = args.value;
const fromB58 = Base58.encode(from);
const toB58 = Base58.encode(to);
const res = new token.transfer_result();
if (fromB58 == toB58) {
System.log('Cannot transfer to self');
return res;
}
System.requireAuthority(authority.authorization_type.contract_call, from);
const fromBalance = this._state.GetBalance(from);
if (fromBalance.value < value) {
System.log("'from' has insufficient balance");
return res;
}
const toBalance = this._state.GetBalance(to);
fromBalance.value -= value;
toBalance.value += value;
this._state.SaveBalance(from, fromBalance);
this._state.SaveBalance(to, toBalance);
const transferEvent = new token.transfer_event(from, to, value);
const impacted = [to, from];
System.event('token.transfer', Protobuf.encode(transferEvent, token.transfer_event.encode), impacted);
res.value = true;
return res;
}
mint(args: token.mint_arguments): token.mint_result {
const to = args.to as Uint8Array;
const value = args.value;
const res = new token.mint_result(false);
System.requireAuthority(authority.authorization_type.contract_call, this._contractId);
const supply = this._state.GetSupply();
const newSupply = supply.value + value;
if (newSupply < supply.value) {
System.log('Mint would overflow supply');
return res;
}
const toBalance = this._state.GetBalance(to);
toBalance.value += value;
supply.value = newSupply;
this._state.SaveSupply(supply);
this._state.SaveBalance(to, toBalance);
const mintEvent = new token.mint_event(to, value);
const impacted = [to];
System.event('token.mint', Protobuf.encode(mintEvent, token.mint_event.encode), impacted);
res.value = true;
return res;
}
}
|
lukemwillis/koinos-as-sdk-examples
|
chat/assembly/Chat.ts
|
<filename>chat/assembly/Chat.ts
import { Base58, StringBytes, System, value } from "koinos-as-sdk";
import { chat } from "./proto/chat";
import { State } from "./State";
export class Chat {
contractId: Uint8Array;
state: State;
constructor() {
this.contractId = System.getContractId();
this.state = new State(this.contractId);
}
send(args: chat.send_arguments): chat.send_result {
const message = args.message as string;
// get the block timestamp
const headInfo = System.getHeadInfo();
// get the sender address
const txField = System.getTransactionField('header.payer') as value.value_type;
const sender = txField.bytes_value as Uint8Array;
const newMessage = new chat.chat_message(sender, message, headInfo.head_block_time);
this.state.SaveMessage(newMessage);
return new chat.send_result();
}
read(
args: chat.read_arguments
): chat.read_result {
let number_messages = args.number_messages;
// add +1 to the last message id so that we can get the last message when calling GetPrevMessage
let prevMessageId = this.state.lastMessageId + 1;
const messages: string[] = [];
while (number_messages > 0) {
const msg = this.state.GetPrevMessage(prevMessageId);
if (!msg) {
break;
}
const sender = Base58.encode(msg.value.user as Uint8Array);
const message = msg.value.message as string;
const timestamp = new Date(msg.value.timestamp).toUTCString();
prevMessageId = parseInt(StringBytes.bytesToString(msg.key) as string) as u64;
messages.push(`${timestamp} - ${sender}: ${message}`);
number_messages -= 1;
}
// reverse the messages array to have the latest message showing at the bottom when printing in the cli
System.log(messages.reverse().join('\n'));
return new chat.read_result();
}
free_read(args: chat.free_read_arguments): chat.free_read_result {
let number_messages = args.number_messages;
const res = new chat.free_read_result();
res.messages = [];
// add +1 to the last message id so that we can get the last message when calling GetPrevMessage
let prevMessageId = this.state.lastMessageId + 1;
while (number_messages > 0) {
const msg = this.state.GetPrevMessage(prevMessageId);
if (!msg) {
break;
}
const sender = Base58.encode(msg.value.user as Uint8Array);
const message = msg.value.message as string;
const timestamp = new Date(msg.value.timestamp).toUTCString();
prevMessageId = parseInt(StringBytes.bytesToString(msg.key) as string) as u64;
res.messages.push(`${timestamp} - ${sender}: ${message}`);
number_messages -= 1;
}
// reverse the messages array to have the latest message showing at the bottom when printing in the cli
res.messages = res.messages.reverse();
return res;
}
}
|
lukemwillis/koinos-as-sdk-examples
|
calculator/assembly/Calculator.ts
|
import { calculator } from "./proto/calculator";
export class Calculator {
add(args: calculator.add_arguments): calculator.add_result {
const x = args.x;
const y = args.y;
const res = new calculator.add_result();
res.value = x + y;
return res;
}
sub(args: calculator.sub_arguments): calculator.sub_result {
const x = args.x;
const y = args.y;
const res = new calculator.sub_result();
res.value = x - y;
return res;
}
mul(args: calculator.mul_arguments): calculator.mul_result {
const x = args.x;
const y = args.y;
const res = new calculator.mul_result();
res.value = x * y;
return res;
}
div(args: calculator.div_arguments): calculator.div_result {
const x = args.x;
const y = args.y;
const res = new calculator.div_result();
res.value = x / y;
return res;
}
}
|
lukemwillis/koinos-as-sdk-examples
|
immutable/assembly/Immutable.ts
|
<reponame>lukemwillis/koinos-as-sdk-examples<gh_stars>0
import { authority } from "koinos-as-sdk";
import { immutable } from "./proto/immutable";
export class Immutable {
authorize(args: authority.authorize_arguments): authority.authorize_result {
// return false when trying to upload a new version of the contract
return new authority.authorize_result(false);
}
add(args: immutable.add_arguments): immutable.add_result {
return new immutable.add_result(args.x + args.y);
}
}
|
lukemwillis/koinos-as-sdk-examples
|
staking/assembly/Token.ts
|
import { Protobuf, System } from "koinos-as-sdk";
import { token } from "./proto/token";
enum entries {
name_entry = 0x82a3537f,
symbol_entry = 0xb76a7ca1,
decimals_entry = 0xee80fd2f,
total_supply_entry = 0xb0da3934,
balance_of_entry = 0x5c721497,
transfer_entry = 0x27f576ca,
mint_entry = 0xdc6f17bb
}
export class Token {
_contractId: Uint8Array;
constructor(contractId: Uint8Array) {
this._contractId = contractId;
}
name(): string {
const args = new token.name_arguments();
const buf = System.callContract(this._contractId, entries.name_entry, Protobuf.encode(args, token.name_arguments.encode));
const res = Protobuf.decode<token.name_result>(buf as Uint8Array, token.name_result.decode);
return res.value as string;
}
symbol(): string {
const args = new token.symbol_arguments();
const buf = System.callContract(this._contractId, entries.symbol_entry, Protobuf.encode(args, token.symbol_arguments.encode));
const res = Protobuf.decode<token.symbol_result>(buf as Uint8Array, token.symbol_result.decode);
return res.value as string;
}
decimals(): u32 {
const args = new token.decimals_arguments();
const buf = System.callContract(this._contractId, entries.decimals_entry, Protobuf.encode(args, token.decimals_arguments.encode));
const res = Protobuf.decode<token.decimals_result>(buf as Uint8Array, token.decimals_result.decode);
return res.value;
}
total_supply(): u64 {
const args = new token.total_supply_arguments();
const buf = System.callContract(this._contractId, entries.total_supply_entry, Protobuf.encode(args, token.total_supply_arguments.encode));
const res = Protobuf.decode<token.total_supply_result>(buf as Uint8Array, token.total_supply_result.decode);
return res.value;
}
balance_of(owner: Uint8Array): u64 {
const args = new token.balance_of_arguments(owner);
const buf = System.callContract(this._contractId, entries.balance_of_entry, Protobuf.encode(args, token.balance_of_arguments.encode));
const res = Protobuf.decode<token.balance_of_result>(buf as Uint8Array, token.balance_of_result.decode);
return res.value;
}
transfer(from: Uint8Array, to: Uint8Array, value: u64): bool {
const args = new token.transfer_arguments(from, to, value);
const buf = System.callContract(this._contractId, entries.transfer_entry, Protobuf.encode(args, token.transfer_arguments.encode));
if (buf) {
const res = Protobuf.decode<token.transfer_result>(buf, token.transfer_result.decode);
return res.value;
}
return false;
}
mint(to: Uint8Array, value: u64): bool {
const args = new token.mint_arguments(to, value);
const buf = System.callContract(this._contractId, entries.mint_entry, Protobuf.encode(args, token.mint_arguments.encode));
if (buf) {
const res = Protobuf.decode<token.mint_result>(buf as Uint8Array, token.mint_result.decode);
return res.value;
}
return false;
}
}
|
lukemwillis/koinos-as-sdk-examples
|
staking/assembly/Staking.ts
|
<filename>staking/assembly/Staking.ts
import { Base58, Protobuf, System } from "koinos-as-sdk";
import { staking } from "./proto/staking";
import { State } from "./State";
import { Token } from "./Token";
const TOKEN_CONTRACT_ID = Base58.decode('19JntSm8pSNETT9aHTwAUHC5RMoaSmgZPJ');
export class Staking {
_contractId: Uint8Array;
_state: State;
_token: Token;
constructor() {
this._contractId = System.getContractId();
this._state = new State(this._contractId);
this._token = new Token(TOKEN_CONTRACT_ID);
}
balance_of(args: staking.balance_of_arguments): staking.balance_of_result {
const account = args.account as Uint8Array;
const balanceObj = this._state.GetBalance(account);
const res = new staking.balance_of_result();
res.value = balanceObj.value;
return res;
}
stake(args: staking.stake_arguments): staking.stake_result {
const account = args.account as Uint8Array;
const value = args.value;
const res = new staking.stake_result(false);
if (!this._token.transfer(account, this._contractId, value)) {
System.log("Token transfer from 'account' failed");
return res;
}
const accountBalance = this._state.GetBalance(account);
accountBalance.value += value;
this._state.SaveBalance(account, accountBalance);
const stakeEvent = new staking.stake_event(account, value);
const impacted = [account];
System.event('staking.stake', Protobuf.encode(stakeEvent, staking.stake_event.encode), impacted);
res.value = true;
return res;
}
withdraw(args: staking.withdraw_arguments): staking.withdraw_result {
const account = args.account as Uint8Array;
const value = args.value;
const res = new staking.withdraw_result(false);
const accountBalance = this._state.GetBalance(account);
if (accountBalance.value < value) {
System.log("'account' has insufficient balance");
return res;
}
if (!this._token.transfer(this._contractId, account, value)) {
System.log('Contract had insufficient funds for withdraw ¯\\_(ツ)_/¯');
return res;
}
accountBalance.value -= value;
this._state.SaveBalance(account, accountBalance);
const withdrawEvent = new staking.withdraw_event(account, value);
const impacted = [account];
System.event('staking.withdraw', Protobuf.encode(withdrawEvent, staking.withdraw_event.encode), impacted);
res.value = true;
return res;
}
}
|
lukemwillis/koinos-as-sdk-examples
|
token/assembly/State.ts
|
import { chain, System } from "koinos-as-sdk";
import { token } from "./proto/token";
const SUPPLY_SPACE_ID = 0;
const SUPPLY_KEY = new Uint8Array(0);
const BALANCE_SPACE_ID = 1;
export class State {
contractId: Uint8Array;
supplySpace: chain.object_space;
balanceSpace: chain.object_space;
constructor(contractId: Uint8Array) {
this.contractId = contractId;
this.supplySpace = new chain.object_space(false, contractId,SUPPLY_SPACE_ID);
this.balanceSpace = new chain.object_space(false, contractId, BALANCE_SPACE_ID);
}
GetSupply(): token.balance_object {
const supply = System.getObject<Uint8Array, token.balance_object>(this.supplySpace, SUPPLY_KEY, token.balance_object.decode);
if (supply) {
return supply;
}
return new token.balance_object();
}
SaveSupply(supply: token.balance_object): void {
System.putObject(this.supplySpace, SUPPLY_KEY, supply, token.balance_object.encode);
}
GetBalance(owner: Uint8Array): token.balance_object {
const balance = System.getObject<Uint8Array, token.balance_object>(this.balanceSpace, owner, token.balance_object.decode);
if (balance) {
return balance;
}
return new token.balance_object();
}
SaveBalance(owner: Uint8Array, balance: token.balance_object): void {
System.putObject(this.balanceSpace, owner, balance, token.balance_object.encode);
}
}
|
lukemwillis/koinos-as-sdk-examples
|
chat/assembly/State.ts
|
<filename>chat/assembly/State.ts
import { chain, System } from "koinos-as-sdk";
import { chat } from "./proto/chat";
const METADATA_SPACE_ID = 0;
const METADATA_OBJECT_ID = "0";
const MESSAGES_SPACE_ID = 1;
export class State {
contractId: Uint8Array;
metadataSpace: chain.object_space;
messagesSpace: chain.object_space;
lastMessageId: u64 = 0;
constructor(contractId: Uint8Array) {
this.contractId = contractId;
this.metadataSpace = new chain.object_space();
this.metadataSpace.id = METADATA_SPACE_ID;
this.metadataSpace.zone = contractId;
this.messagesSpace = new chain.object_space();
this.messagesSpace.id = MESSAGES_SPACE_ID;
this.messagesSpace.zone = contractId;
const metadata = System.getObject<string, chat.metadata_object>(this.metadataSpace, METADATA_OBJECT_ID, chat.metadata_object.decode);
if (metadata) {
this.lastMessageId = metadata.last_message_id;
}
}
IncrementLastMessageId(): void {
this.lastMessageId += 1;
const metadata = new chat.metadata_object(this.lastMessageId);
System.putObject(this.metadataSpace, METADATA_OBJECT_ID, metadata, chat.metadata_object.encode);
}
SaveMessage(message: chat.chat_message): void {
this.IncrementLastMessageId();
System.putObject(this.messagesSpace, this.lastMessageId.toString(), message, chat.chat_message.encode);
}
GetMessage(messageId: u64): chat.chat_message | null {
return System.getObject<string, chat.chat_message>(this.messagesSpace, messageId.toString(), chat.chat_message.decode);
}
GetPrevMessage(messageId: u64): System.ProtoDatabaseObject<chat.chat_message> | null {
return System.getPrevObject<string, chat.chat_message>(this.messagesSpace, messageId.toString(), chat.chat_message.decode);
}
}
|
ConclaveTeam/ConclaveFront
|
src/components/atoms/index.ts
|
export { default as Button } from './Button.vue'
export { default as Link } from './Link.vue'
|
ConclaveTeam/ConclaveFront
|
tests/unit/example.spec.ts
|
<gh_stars>0
import { shallowMount } from '@vue/test-utils'
import { Button } from '@/components/atoms'
describe('Button atom', () => {
it('Renders test passed into via slot', () => {
const msg = 'button text'
const wrapped = `<span>${msg}</span>`
const wrapper = shallowMount(Button, {
scopedSlots: {
default: wrapped
}
})
expect(wrapper.text()).toMatch(msg)
})
})
|
mtolley/seeker-github-actions
|
src/seeker-compliance-reporting.ts
|
// seeker-compliance-reporting
// ///////////////////////////
//
// This action encapsulates the seeker-compliance-report and check-seeker-compliance
// actions. It checks Seeker Policy compliance and depending on the input values
// will do one or both of the following:
//
// * Generate the Compliance Report PDF and upload it as a build artefact.
// * Fail the build if the specified project is not in compliance.
import * as core from '@actions/core'
import { checkComplianceStatus, generateSeekerComplianceReportPDF, getInputOrEnvironmentVariable, uploadSeekerComplianceReport } from './utils'
async function run(): Promise<void> {
try {
core.info('⬇️ Downloading Seeker compliance report from the Seeker Server')
const seekerServerURL = getInputOrEnvironmentVariable(
'seekerServerUrl',
'SEEKER_SERVER_URL',
true // required
)
const seekerProjectKey = getInputOrEnvironmentVariable(
'seekerProjectKey',
'SEEKER_PROJECT_KEY',
true // required
)
const seekerAPIToken = getInputOrEnvironmentVariable(
'seekerAPIToken',
'SEEKER_API_TOKEN',
true // required
)
const generateComplianceReportPDFInput = core.getBooleanInput('generateComplianceReportPDF')
const failBuildIfNotInCompliance = core.getBooleanInput('failBuildIfNotInCompliance')
if (generateComplianceReportPDFInput) {
await generateSeekerComplianceReportPDF({
seekerServerURL,
seekerProjectKey,
seekerAPIToken
})
await uploadSeekerComplianceReport()
}
await checkComplianceStatus({
seekerServerURL,
seekerProjectKey,
seekerAPIToken,
failBuildIfNotInCompliance
})
} catch (error) {
core.setFailed(error.message)
}
}
run()
|
mtolley/seeker-github-actions
|
src/check-seeker-compliance.ts
|
// check-seeker-compliance.ts
// //////////////////////////
//
// Calls the Seeker API for the specified project to determine whether that
// project is currently in compliance with any assigned Compliance Policies
// or not. The Compliance status is written to the action output. Optionally,
// if failBuildIfNotInCompliance is true, the action will fail.
import * as core from '@actions/core'
import {getInputOrEnvironmentVariable, checkComplianceStatus} from './utils'
async function run(): Promise<void> {
try {
core.info('ℹ️ Checking Seeker Compliance Policy status')
// Get the action inputs (or environment variables)
const seekerServerURL = getInputOrEnvironmentVariable(
'seekerServerUrl',
'SEEKER_SERVER_URL',
true // required
)
const seekerProjectKey = getInputOrEnvironmentVariable(
'seekerProjectKey',
'SEEKER_PROJECT_KEY',
true // required
)
const seekerAPIToken = getInputOrEnvironmentVariable(
'seekerAPIToken',
'SEEKER_API_TOKEN',
true // required
)
const failBuildIfNotInCompliance = core.getBooleanInput('failBuildIfNotInCompliance')
await checkComplianceStatus({
seekerServerURL,
seekerProjectKey,
seekerAPIToken,
failBuildIfNotInCompliance
})
} catch (error) {
core.setFailed(error.message)
}
}
run()
|
mtolley/seeker-github-actions
|
src/download-seeker-agent.ts
|
<filename>src/download-seeker-agent.ts
// download-seeker-agent.ts
// ////////////////////////
//
// Downloads the Seeker agent installer script from the Seeker API and
// runs it. This will download the agent binary itself and display instructions
// for using it in the build output.
import * as core from '@actions/core'
import {getInputOrEnvironmentVariable} from './utils'
import axios from 'axios'
import child_process from 'child_process'
async function run(): Promise<void> {
try {
core.info('⬇️ Downloading Seeker agent from Seeker Server')
// Get the action inputs (or environment variables)
const seekerServerURL = getInputOrEnvironmentVariable(
'seekerServerUrl',
'SEEKER_SERVER_URL',
true // required
)
const seekerProjectKey = getInputOrEnvironmentVariable(
'seekerProjectKey',
'SEEKER_PROJECT_KEY',
true // required
)
const technology = core.getInput('technology', { required: true })
const osFamily = core.getInput('osFamily', { required: true })
try {
// First download the installer script from the Seeker server
const url = `${seekerServerURL}/rest/api/latest/installers/agents/scripts/${technology}?projectKey=${seekerProjectKey}&downloadWith=curl&osFamily=${osFamily}&flavor=DEFAULT`
const res = await axios.get(url)
// Then execute the installer script and echo any output.
const commandResult = child_process.execSync(res.data.toString())
core.info(commandResult.toString())
} catch(error) {
if (error.response) {
core.error(`Seeker Server responded with error code: ${error.response.status}`)
core.error(`Error message: ${error.response.data.message}`)
} else {
core.error("No response from Seeker Server")
}
}
} catch (error) {
core.setFailed(error.message)
}
}
run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.