repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
liyiligang/mxui
web/src/base/globals.ts
<reponame>liyiligang/mxui /* * Copyright 2021 liyiligang. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {ElMessage} from "element-plus"; import {protoManage} from "../proto/manage"; import {routerPath, routerName} from "../router"; import {reactive} from "vue"; import {websocket} from "./websocket"; import * as SparkMD5 from "spark-md5"; // export enum BlockType { export module globals { // NoneBlock = -1, // } // export interface BlockParm { // readonly width: number // readonly height: number // } // // export let blockParm: BlockParm = { // width: 50, // height: 50 // } export let globalsConfig = { localStorageKey:{ token:"token", autoLogin:"autoLogin", setting:"setting" }, httpConfig:{ requestTimeout: 10000 }, wsConfig:{ wsReconnectTime: 5000, }, pageConfig:{ sizeList:[9, 21, 54, 108], initSize:21, initNum:1, initCount:7 }, funcCallConfig:{ tablePageSize:100 }, userSetSave:{ isPageFix: true, autoUpdateInterval: 2, language:'eng' }, userSetTemp:{ autoRefresh: false, dataFilterView: false } } export let globalsData = { manager:reactive({info: protoManage.Manager.create()}), managerList:new Map<number, protoManage.IManager>(), managerSetting:reactive({setting:globals.globalsConfig.userSetSave}), tempSetting:reactive({setting:globals.globalsConfig.userSetTemp}), wsMessage:{ order:protoManage.Order.Unknow, message:reactive({ nodeFuncCallAns:protoManage.AnsNodeFuncCall.create() }) } } export function getManagerByID(id: number|undefined|null):protoManage.IManager|undefined { if (id == undefined) { return protoManage.Manager.create() } return globalsData.managerList.get(id) } export function updateManagerInfo(response:protoManage.Manager) { response.Token = globals.globalsData.manager.info.Token globals.globalsData.manager.info = reactive(response) } export function reLogin() { globals.globalsData.manager.info = protoManage.Manager.create() localStorage.removeItem(globals.globalsConfig.localStorageKey.token) websocket.wsClose() routerPath.toPath(routerName.login) } export function elButtonBlur(e) { let target = e.target; if(target.nodeName == 'SPAN' || target.nodeName == 'I'){ target = e.target.parentNode; } target.blur(); } export function viewInfo(msg:string) { ElMessage.info(msg); console.log(msg) } export function viewSuccess(msg:string) { ElMessage.success(msg); console.log(msg) } export function viewWarn(msg:string) { ElMessage.warning(msg); console.warn(msg) } export function viewError(msg:string) { ElMessage.error(msg); console.error(msg) } export function randomNum(lower:number, upper:number):number { return Math.floor(Math.random() * (upper - lower)) + lower; } export function randomColor ():string { return '#' + (function(h){ return new Array(7 - h.length).join("0") + h })((Math.random() * 0x1000000 << 0).toString(16)); } export function getCurrentTime():string { let yy = new Date().getFullYear(); let mm = new Date().getMonth()+1; let dd = new Date().getDate(); let hh = new Date().getHours(); let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes(); let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds(); return yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss; } export function getPageNumOffset(num:any):number { return Number(num) - 1; } export function isEllipsis(dom:any):boolean { let checkDom = dom.cloneNode(), parent, flag; checkDom.style.width = dom.offsetWidth + 'px'; checkDom.style.height = dom.offsetHeight + 'px'; checkDom.style.overflow = 'auto'; checkDom.style.position = 'absolute'; checkDom.style.zIndex = -1; checkDom.style.opacity = 0; checkDom.style.whiteSpace = "nowrap"; checkDom.innerHTML = dom.innerHTML; parent = dom.parentNode; parent.appendChild(checkDom); flag = checkDom.scrollWidth > checkDom.offsetWidth; parent.removeChild(checkDom); return flag; } export function isNull(para:any):boolean { if (para === 'undefined' || para === null){ return true } if (typeof para === 'number' && isNaN(para)){ return true } return false } export function isPositiveIntWithStr(str:string):boolean { let t = /^\+?[1-9][0-9]*$/;   return t.test(str); } export function isNoNegativeIntWithStr(str:string):boolean { let t = /^\d+$/; return t.test(str); } export function isJson (json:string):boolean { if (typeof json == 'string') { try { let obj=JSON.parse(json); if(typeof obj == 'object' && obj ){ return true; }else{ return false; } } catch(e) { return false; } } return false; } export function getJson (json:string):string|object { if (json == "") { return json } try { let obj=JSON.parse(json); if(typeof obj == 'object' && obj ){ return obj; }else{ return json } } catch(e) { return json } } export function calcFileMd5 (file:Blob, call:Function) { const fileReader = new FileReader() fileReader.readAsBinaryString(file); fileReader.onload = e => { call(SparkMD5.hashBinary(String(e.target?.result))) } fileReader.onerror = e => { viewError(String(e)) } } export function getHttpHost ():string{ let base = "" if (process.env.NODE_ENV === "development"){ base += "/api" } return location.protocol + "//" + window.location.host + base } export function getWsHost ():string{ let base = "" if (process.env.NODE_ENV === "development"){ base += "/api" } let protocol = "ws://" if (location.protocol === "https:"){ protocol = "wss://" } return protocol + "//" + window.location.host + base } }
ViniciusDev26/api-nest
src/auth/constants.ts
export const jwtConstants = { secret: 'gaby-eu-te-amo', };
ViniciusDev26/api-nest
src/products/entities/Product.ts
import { User } from 'src/users/entities/User'; import { Column, Entity, ManyToOne, PrimaryColumn } from 'typeorm'; import { v4 as uuidV4 } from 'uuid'; @Entity('products') class Product { @PrimaryColumn() id: string; @Column() name: string; @ManyToOne(() => User, (user) => user.products) user: User; constructor(name: string, user: User) { this.id = uuidV4(); this.name = name; this.user = user; } } export { Product };
ViniciusDev26/api-nest
src/products/products.service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { IPayload } from 'src/auth/dto/IPayload'; import { UsersService } from 'src/users/users.service'; import { Repository } from 'typeorm'; import { ICreateAndUpdateProduct } from './dtos/ICreateAndUpdateProduct'; import { Product } from './entities/Product'; @Injectable() export class ProductsService { constructor( @InjectRepository(Product) private readonly productsRepository: Repository<Product>, private readonly usersService: UsersService, ) {} async findAll(): Promise<Product[]> { return await this.productsRepository.find(); } async findOne(id: string): Promise<Product> { return await this.productsRepository.findOne(id); } async create(productData: ICreateAndUpdateProduct, userPayload: IPayload) { const user = await this.usersService.findBy('id', userPayload.sub); const product = new Product(productData.name, user); const registedProduct = await this.productsRepository.save(product); return { name: registedProduct.name, }; } }
ViniciusDev26/api-nest
src/products/dtos/ICreateAndUpdateProduct.ts
<reponame>ViniciusDev26/api-nest interface ICreateAndUpdateProduct { name: string; } export { ICreateAndUpdateProduct };
ViniciusDev26/api-nest
src/auth/helpers/encryptFunctions.ts
<reponame>ViniciusDev26/api-nest import { compareSync, hashSync } from 'bcrypt'; export function encryptPassword(password: string): string { return hashSync(password, 10); } export function comparePassword(password: string, hash: string): boolean { return compareSync(password, hash); }
ViniciusDev26/api-nest
src/auth/auth.service.ts
import { Injectable } from '@nestjs/common'; import { UsersService } from 'src/users/users.service'; import { JwtService } from '@nestjs/jwt'; import { comparePassword } from './helpers/encryptFunctions'; import { User } from 'src/users/entities/User'; import { IPayload } from './dto/IPayload'; @Injectable() export class AuthService { constructor( private usersService: UsersService, private jwtService: JwtService, ) {} async validateUser(email: string, password: string): Promise<any> { const user = await this.usersService.findOne(email); if (user && comparePassword(password, user.hashPassword)) { const { id, name, email } = user; return { id, email, name, }; } return null; } async login(user: User) { const payload: IPayload = { email: user.email, name: user.name, sub: user.id, }; return { user, access_token: this.jwtService.sign(payload), }; } }
ViniciusDev26/api-nest
src/users/users.controller.ts
<reponame>ViniciusDev26/api-nest<filename>src/users/users.controller.ts import { BadRequestException, Body, Controller, Post } from '@nestjs/common'; import { Public } from 'src/auth/decorators/public.decorator'; import { ICreateAndUpdateUser } from './dtos/ICreateAndUpdateUser'; import { UsersService } from './users.service'; @Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {} @Public() @Post('/') async create(@Body() userToRegister: ICreateAndUpdateUser) { const requiredFields = ['name', 'email', 'password']; for (const field of requiredFields) { if (!userToRegister[field]) { throw new BadRequestException(`${field} is required`); } } const user = await this.usersService.create(userToRegister); return user; } }
ViniciusDev26/api-nest
src/users/users.service.ts
<gh_stars>0 import { ConflictException, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { encryptPassword } from 'src/auth/helpers/encryptFunctions'; import { Repository } from 'typeorm'; import { ICreateAndUpdateUser } from './dtos/ICreateAndUpdateUser'; import { User } from './entities/User'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private readonly usersRepository: Repository<User>, ) {} async findBy(field: string, value: string): Promise<User | undefined> { return this.usersRepository.findOne({ where: { [field]: value, }, }); } async findOne(email: string): Promise<User | undefined> { return this.usersRepository.findOne({ where: { email: email, }, }); } async create({ name, email, password }: ICreateAndUpdateUser) { const userAlreadyExists = await this.findOne(email); if (userAlreadyExists) { throw new ConflictException('User already exist'); } const hashPassword = encryptPassword(password); const user = new User(name, email, hashPassword); const userRegisted = await this.usersRepository.save(user); return { email: userRegisted.email, name: userRegisted.name, }; } }
ViniciusDev26/api-nest
src/products/products.controller.ts
import { Body, Controller, Get, Param, Post, Request } from '@nestjs/common'; import { ICreateAndUpdateProduct } from './dtos/ICreateAndUpdateProduct'; import { Product } from './entities/Product'; import { ProductsService } from './products.service'; @Controller('products') export class ProductsController { constructor(private readonly productsService: ProductsService) {} @Get('/') async findAll(): Promise<Product[]> { const products = await this.productsService.findAll(); return products; } @Get('/:id') async findOne(@Param('id') id: string) { try { const product = await this.productsService.findOne(id); return product; } catch (error) { return {}; } } @Post('/') async create( @Request() req, @Body() productToRegister: ICreateAndUpdateProduct, ) { const product = await this.productsService.create( productToRegister, req.user, ); return product; } }
ViniciusDev26/api-nest
src/users/entities/User.ts
import { Product } from 'src/products/entities/Product'; import { Column, Entity, OneToMany, PrimaryColumn } from 'typeorm'; import { v4 as uuidV4 } from 'uuid'; @Entity('users') class User { @PrimaryColumn() id: string; @Column() name: string; @Column() email: string; @Column() hashPassword: string; @OneToMany(() => Product, (product) => product.user) products: Product[]; constructor(name: string, email: string, hashPassword: string) { this.id = uuidV4(); this.name = name; this.email = email; this.hashPassword = <PASSWORD>; } } export { User };
ViniciusDev26/api-nest
src/auth/dto/IPayload.ts
<gh_stars>0 interface IPayload { sub: string; email: string; name: string; } export { IPayload };
untangle-space/web-v2
src/components/issue.tsx
<reponame>untangle-space/web-v2<gh_stars>1-10 import React from "react" import { useStaticQuery, graphql } from "gatsby" import Image from "gatsby-image" const Issue = () => { return ( <div className="issues"> </div> ) } export default Issue
untangle-space/web-v2
src/pages/archive.tsx
import React from "react" import { Link } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" class Archive extends React.Component { render() { const { data } = this.props const siteTitle = data.site.siteMetadata.title const posts = data.allMarkdownRemark.edges return ( <Layout location={this.props.location} title={siteTitle}> <SEO title="Designletter | Archive" /> <section className="header_section"> <div className="container"> <div className="title-back"> <a href="/"><img src="/back.svg"/></a><h4>Archive</h4> </div> <div className="latest-issue"> {posts.map(({ node }) => { const title = node.frontmatter.title || node.fields.slug const date = node.frontmatter.date const link = node.frontmatter.mailchimp_link return ( <div className="mock-wrap"> <a href={link} className="issue-box"> <h2>{title}</h2> <h5>{date}</h5> </a> </div> ) })} </div> </div> </section> <footer className="footer"> <div className="container"> <div className="footer-wrap"> <div className="credit"> <h4>Designletter, 2021</h4> <ul className="menu-social"> <li> <a href="https://instagram.com/designletterco" target="__blank"><img src="/insta.svg"/></a> </li> <li> <a href="https://twitter.com/designletterco" target="__blank"><img src="/twitter.svg"/></a> </li> </ul> </div> <div className="quote"> <h4>Curated by <a href="http://aakarshna.co/?ref=designletterco" target="__blank">Aakarshna</a> & <a href="https://vijayverma.co/?ref=designletterco" target="__blank">vijay verma</a></h4> </div> </div> </div> </footer> </Layout> ) } } export default Archive export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } ) { edges { node { excerpt(format: HTML) html fields { slug } frontmatter { date(formatString: "MMM DD, YYYY") title description author category mailchimp_link } } } } } `
untangle-space/web-v2
src/pages/sponsership.tsx
<filename>src/pages/sponsership.tsx import React from "react" import { Link } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" class Sponsership extends React.Component { render() { const { data } = this.props const siteTitle = data.site.siteMetadata.title const posts = data.allMarkdownRemark.edges return ( <Layout location={this.props.location} title={siteTitle}> <SEO title="Designletter | Sponsership" /> <section className="header_section"> <div className="container"> <div className="title-back"> <a href="/"><img src="/back.svg"/></a><h4>Sponsership</h4> </div> <div className="sponser-details"> <p>Designletter is weekly newsletter that contains a list of the best and newest articles resource, job listing and more. It enterily focused on designer, developer and manager.</p> <h4>Newsletter Stats</h4> <p> Email subscribers: 2,146<br/> Newsletter open rate: 35%<br/> Newsletter click rate: 7% </p> <p> We only run <strong>1 ad per issue</strong> to provide our sponsor with maximum visibility while maintaining the quality of the newsletter. The newsletter is sent out every 7 days on Wednesday. <a href="http://bit.ly/sponsership-issue">Example.</a></p> ‍ <p><a href="https://forms.gle/CdoD7Eqjp8vFNwzC7">Click here</a> to learn more about the pricing and content requirements.</p> ‍ <p>If you have any questions or if you like to book an ad in more than just one issue, please email us on <a href="mailto:<EMAIL>?subject=designletter enquiry"><EMAIL></a> </p> </div> </div> </section> <footer className="footer"> <div className="container"> <div className="footer-wrap"> <div className="credit"> <h4>Designletter, 2021</h4> <ul className="menu-social"> <li> <a href="https://instagram.com/designletterco" target="__blank"><img src="/insta.svg"/></a> </li> <li> <a href="https://twitter.com/designletterco" target="__blank"><img src="/twitter.svg"/></a> </li> </ul> </div> <div className="quote"> <h4>Curated by <a href="http://aakarshna.co/?ref=designletterco" target="__blank">Aakarshna</a> & <a href="https://vijayverma.co/?ref=designletterco" target="__blank"><NAME></a></h4> </div> </div> </div> </footer> </Layout> ) } } export default Sponsership export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } ) { edges { node { excerpt(format: HTML) html fields { slug } frontmatter { date(formatString: "MMM DD, YYYY") title description author category mailchimp_link } } } } } `
untangle-space/web-v2
src/pages/index.tsx
<reponame>untangle-space/web-v2 // Gatsby supports TypeScript natively! import React from "react" import { PageProps, Link, graphql } from "gatsby" import Bio from "../components/bio" import Layout from "../components/layout" import SEO from "../components/seo" type Data = { site: { siteMetadata: { title: string } } allMarkdownRemark: { edges: { node: { excerpt: string frontmatter: { title: string date: string description: string } fields: { slug: string } } } } } const BlogIndex = ({ data, location }: PageProps<Data>) => { const siteTitle = data.site.siteMetadata.title const posts = data.allMarkdownRemark.edges return ( <Layout location={location} title={siteTitle}> <SEO title="Untangle - Mental Health Matters" /> <section className="header_section"> <div className="container"> <div className="main-title"> <h2 className="logo"> <div className="title-text"> <span className="heading">untangle</span> </div> </h2> </div> <div className="secondary-text"> <h1>Accelerating India's Mental Health Revolution</h1> <p>In view of the mental health crisis caused by the pandemic, we aim to support as many people as possible through our <b>#CopeWithCovid</b> Initiative.</p> </div> <div className="subscribe-box"> <div className="form"> <div id="mc_embed_signup"> <div id="mc_embed_signup_scroll" className="newsletter"> <div className="sub-action"> <div className="submit-button"> <a href="https://docs.google.com/forms/d/e/1FAIpQLSeZYMXu8SwreOd7Ze3N7_j7-1U8ufwA91Qxy1y-195am1zOeg/viewform" target="__blank"> <input type="submit" value="Sign up here" name="subscribe" id="mc-embedded-subscribe" className="button sub-button" /> </a> </div> </div> </div> </div> </div> <div className="social-p"> <p>200+ clients trust our 40+ Therapists</p> </div> </div> <div className="latest-issue"> <a href="https://bit.ly/untanglecwcfaq" target="__blank" className="issue-box"> <h2>Here are some FAQs</h2> <h5> for the ones who wish to seek Therapy/Counseling Sessions</h5> </a> <p>More questions? Contact us directly via <a href="https://wa.me/message/ISLOY4QZG7GTM1" target="__blank">Whatsapp</a></p> </div> <div className="join-us"> <a href="https://bit.ly/untanglecwcfaq" target="__blank"className="join-us-box"> <h2>Join us as a Psychologist</h2> </a> </div> </div> </section> <footer className="footer"> <div className="container"> <div className="footer-wrap"> <div className="credit"> <h4>untangle, 2020</h4> <ul className="menu-social"> <li> <a href="https://instagram.com/untangle.space" target="__blank"><img src="/insta.svg"/></a> </li> <li> <a href="https://twitter.com/untangle_space" target="__blank"><img src="/twitter.svg"/></a> </li> </ul> </div> <div className="quote"> <h4>Curated with love <a href="http://aakarshna.co/?ref=designletterco" target="__blank"></a><a href="https://vijayverma.co/?ref=designletterco" target="__blank"></a></h4> </div> </div> </div> </footer> </Layout> ) } export default BlogIndex export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { edges { node { excerpt fields { slug } frontmatter { date(formatString: "MMMM DD, YYYY") title description } } } } } `
lushu/gaxios
test/test.retry.ts
// Copyright 2018, Google, LLC. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import assert from 'assert'; import nock from 'nock'; import {GaxiosError, GaxiosOptions, request, Gaxios} from '../src'; const assertRejects = require('assert-rejects'); nock.disableNetConnect(); const url = 'https://example.com'; function getConfig(err: Error) { const e = err as GaxiosError; if (e && e.config && e.config.retryConfig) { return e.config.retryConfig; } return; } afterEach(() => { nock.cleanAll(); }); describe('🛸 retry & exponential backoff', () => { it('should provide an expected set of defaults', async () => { const scope = nock(url) .get('/') .times(4) .reply(500); await assertRejects(request({url, retry: true}), (e: Error) => { scope.done(); const config = getConfig(e); if (!config) { assert.fail('no config available'); } assert.strictEqual(config!.currentRetryAttempt, 3); assert.strictEqual(config!.retry, 3); assert.strictEqual(config!.noResponseRetries, 2); assert.strictEqual(config!.retryDelay, 100); const expectedMethods = ['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE']; for (const method of config!.httpMethodsToRetry!) { assert(expectedMethods.indexOf(method) > -1); } const expectedStatusCodes = [[100, 199], [429, 429], [500, 599]]; const statusCodesToRetry = config!.statusCodesToRetry!; for (let i = 0; i < statusCodesToRetry.length; i++) { const [min, max] = statusCodesToRetry[i]; const [expMin, expMax] = expectedStatusCodes[i]; assert.strictEqual(min, expMin); assert.strictEqual(max, expMax); } return true; }); }); it('should retry on 500 on the main export', async () => { const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') .reply(500), nock(url) .get('/') .reply(200, body), ]; const res = await request({ url, retry: true, }); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should not retry on a post', async () => { const scope = nock(url) .post('/') .reply(500); await assertRejects( request({url, method: 'POST', retry: true}), (e: Error) => { const config = getConfig(e); return config!.currentRetryAttempt === 0; } ); scope.done(); }); it('should retry at least the configured number of times', async () => { const body = {dippy: '🥚'}; const scopes = [ nock(url) .get('/') .times(3) .reply(500), nock(url) .get('/') .reply(200, body), ]; const cfg = {url, retryConfig: {retry: 4}}; const res = await request(cfg); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should not retry more than configured', async () => { const scope = nock(url) .get('/') .twice() .reply(500); const cfg = {url, retryConfig: {retry: 1}}; await assertRejects(request(cfg), (e: Error) => { return getConfig(e)!.currentRetryAttempt === 1; }); scope.done(); }); it('should not retry on 4xx errors', async () => { const scope = nock(url) .get('/') .reply(404); await assertRejects(request({url, retry: true}), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); scope.done(); }); it('should retain the baseUrl on retry', async () => { const body = {pumpkin: '🥧'}; const url = '/path'; const baseUrl = 'http://example.com'; const scope = nock(baseUrl) .get(url) .reply(500) .get(url) .reply(200, body); const gaxios = new Gaxios({ baseUrl, }); const res = await gaxios.request({ url, retry: true, }); assert.deepStrictEqual(res.data, body); scope.done(); }); it('should not retry if retries set to 0', async () => { const scope = nock(url) .get('/') .reply(500); const cfg = {url, retryConfig: {retry: 0}}; await assertRejects(request(cfg), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); scope.done(); }); it('should notify on retry attempts', async () => { const body = {buttered: '🥖'}; const scopes = [ nock(url) .get('/') .reply(500), nock(url) .get('/') .reply(200, body), ]; let flipped = false; const config: GaxiosOptions = { url, retryConfig: { onRetryAttempt: err => { const cfg = getConfig(err); assert.strictEqual(cfg!.currentRetryAttempt, 1); flipped = true; }, }, }; await request(config); assert.strictEqual(flipped, true); scopes.forEach(s => s.done()); }); it('should support overriding the shouldRetry method', async () => { const scope = nock(url) .get('/') .reply(500); const config = { url, retryConfig: { shouldRetry: () => { return false; }, }, }; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); scope.done(); }); it('should retry on ENOTFOUND', async () => { const body = {spicy: '🌮'}; const scopes = [ nock(url) .get('/') .replyWithError({code: 'ENOTFOUND'}), nock(url) .get('/') .reply(200, body), ]; const res = await request({url, retry: true}); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should retry on ETIMEDOUT', async () => { const body = {sizzling: '🥓'}; const scopes = [ nock(url) .get('/') .replyWithError({code: 'ETIMEDOUT'}), nock(url) .get('/') .reply(200, body), ]; const res = await request({url, retry: true}); assert.deepStrictEqual(res.data, body); scopes.forEach(s => s.done()); }); it('should allow configuring noResponseRetries', async () => { const scope = nock(url) .get('/') .replyWithError({code: 'ETIMEDOUT'}); const config = {url, retryConfig: {noResponseRetries: 0}}; await assertRejects(request(config), (e: Error) => { const cfg = getConfig(e); return cfg!.currentRetryAttempt === 0; }); scope.done(); }); });
Evgeniy-Polyak/CSharp.HelperPlus
src/filename-fixer.ts
<filename>src/filename-fixer.ts import * as vscode from "vscode"; import * as os from "os"; import * as path from "path"; export class FilenameFixer { public async fix() { const document = vscode.window.activeTextEditor?.document; if (typeof document === "undefined") { return; } const regexes = [ /class\s(\w+)/g, /interface\s(\w+)/g, /enum\s(\w+)/g, ]; let destinationFilename = ""; for (let i = 0; i < regexes.length; i++) { let regex = new RegExp(regexes[i]); for (let i = 0; i < document!.lineCount; i++) { let documentLine = document?.lineAt(i); let match; if ((match = regex.exec(documentLine!.text))) { destinationFilename = match[1]; break; } } if (destinationFilename !== "") { break; } } if (destinationFilename === "") { vscode.window.showInformationMessage( "Couldn't find class/interface/enum" ); return; } var pathSeparator = "/"; if (os.platform() === "win32") { pathSeparator = "\\"; } let destination = path.dirname(document.fileName) + pathSeparator + destinationFilename + ".cs"; if (destination !== document.fileName) { let sourceUri = vscode.Uri.file(document.fileName); let destinationUri = vscode.Uri.file(destination); vscode.workspace.fs.rename(sourceUri, destinationUri); } } }
Evgeniy-Polyak/CSharp.HelperPlus
src/code-embed.ts
<gh_stars>0 import * as vscode from 'vscode'; const codeBlocks: CodeBlock[] = [ { name: 'try { ... } catch(Exception ex) { ... }', template: 'trycatch.txt' }, { name: 'if (...) { ... }', template: 'if.txt' } ]; export class CodeEmbed { public async embedCode() { let document = vscode.window.activeTextEditor?.document!; let start = vscode.window.activeTextEditor?.selection?.start; let end = vscode.window.activeTextEditor?.selection?.end; // determine indentation to add to template let lineText = document.lineAt(start!.line).text; let emptySpaceMatch = lineText.match(/^[\s]+/g); let indentation = ''; if (emptySpaceMatch!.length > 0) { indentation = emptySpaceMatch![0]; } if (typeof start === 'undefined') { return; } const quickPickSelection = await vscode.window.showQuickPick(codeBlocks.map(c => c.name)); if (typeof quickPickSelection === 'undefined') { return; } const selectedCodeBlock = codeBlocks.find(c => c.name == quickPickSelection); const doc = await vscode.workspace.openTextDocument(vscode.extensions.getExtension('EvgeniyPolyak.csharp-helper-plus')!.extensionPath + '/templates/code-blocks/' + selectedCodeBlock?.template); const selectionRange = new vscode.Range(new vscode.Position(start!.line, 0), new vscode.Position(end!.line + 1, 0)); let codeToEmbed = document.getText(selectionRange); // indent all selected lines let codeToEmbedLines = codeToEmbed.split('\n'); if (codeToEmbedLines.length > 1) { codeToEmbed = codeToEmbedLines[0]; for (let i = 1; i < codeToEmbedLines.length; i++) { codeToEmbed += `\t${codeToEmbedLines[i]}`; } } // replace code await vscode.window.activeTextEditor?.edit(async (editBuilder: vscode.TextEditorEdit) => { editBuilder.delete(selectionRange); let codeBlockText = doc.getText(); codeBlockText = codeBlockText.replace(/\$indent /g, indentation); codeBlockText = codeBlockText.replace('$code', codeToEmbed.trimRight()); editBuilder.insert(new vscode.Position(start?.line!, 0), codeBlockText); }); } } interface CodeBlock { name: string; template: string; }
Evgeniy-Polyak/CSharp.HelperPlus
src/inject-dependency.ts
<gh_stars>0 'use strict' import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; const ignoredDirectories = [ 'obj', 'bin', 'node_modules', '.git', '.vscode', '.vs', '.github' ]; function findCsFilesRecursively(p: string) { let csFiles: string[] = []; let pathContent = fs.readdirSync(p, { withFileTypes: true }); for (let i = 0; i < pathContent.length; i++) { var pathItem = pathContent[i]; if (ignoredDirectories.includes(pathItem.name)) { continue; } if (pathItem.isDirectory()) { var dirFiles = findCsFilesRecursively(path.join(p, pathContent[i].name)); dirFiles.forEach(f => csFiles.push(f)); } else if (pathItem.isFile() && pathItem.name.endsWith(".cs")) { csFiles.push(pathItem.name); } } return csFiles; } export class DependencyInjector { public inject() { vscode.window.showInputBox({ ignoreFocusOut: true, prompt: 'Please enter class name.' }) .then(async (searchQuery) => { if (typeof searchQuery === 'undefined') { return; } // Find csharp file with name prompt let originalSearchQuery = searchQuery; searchQuery = searchQuery.toLowerCase(); let csharpfiles = findCsFilesRecursively(<string>vscode.workspace.rootPath); let matches: string[] = []; csharpfiles.forEach(file => { if (file.toLowerCase().includes(searchQuery!)) { let fileWithoutCsExtension = file.substr(0, file.length - 3); matches.push(fileWithoutCsExtension); } }); let className = ''; if (matches.length == 0) { const cont = await vscode.window.showQuickPick([`No matches, continue with '${originalSearchQuery}'?`]); if (typeof cont === 'undefined') { return; } className = originalSearchQuery; } else { const pick = await vscode.window.showQuickPick(matches); if (typeof pick === 'undefined') { return; } className = pick!; } // Set variable name let variableName = ''; if (className.startsWith('I')) { variableName = className.substr(1, className.length - 1); } else { variableName = className; } variableName = variableName[0].toLowerCase() + variableName.substring(1, variableName.length); let lessSignIndex = variableName.indexOf('<'); if (lessSignIndex != -1) { variableName = variableName.substr(0, lessSignIndex); } let document = vscode.window.activeTextEditor?.document; // Get class name and class start line let matchedClassName = ''; let classStartLine = -1; var classRegex = new RegExp(/(private|internal|public|protected)\s?(static)?\sclass\s(\w*)/g); for (let i = 0; i < document!.lineCount; i++) { let documentLine = document?.lineAt(i); let match; if ((match = classRegex.exec(documentLine!.text))) { matchedClassName = match[3]; classStartLine = i; break; } } // get start constructor line let constructorStartLine = -1; let constructorEndLine = -1; var constructorRegex = new RegExp("public\\s" + matchedClassName + "\\(", "g"); for (let i = 0; i < document!.lineCount; i++) { let documentLine = document?.lineAt(i); let match; if ((match = constructorRegex.exec(documentLine!.text))) { constructorStartLine = i; if (documentLine?.text.indexOf(')') != -1) { constructorEndLine = i; } break; } } if (constructorEndLine == -1 && constructorStartLine > 0) { // search from constructor start until ) is found - constructor end assumption for (let i = constructorStartLine; i < document!.lineCount; i++) { let documentLine = document?.lineAt(i); if (documentLine?.text.indexOf(')') != -1) { constructorEndLine = i; break; } } } // Get last private readonly field let readonlyFieldRegex = new RegExp(/private\sreadonly\s(\w*)/g); let lastReadonlyFieldLine = -1; let searchForFieldUntil = constructorStartLine; if (searchForFieldUntil == -1) { searchForFieldUntil = document?.lineCount!; } for (let i = 0; i < searchForFieldUntil; i++) { let documentLine = document?.lineAt(i); let match; if ((match = readonlyFieldRegex.exec(documentLine!.text))) { lastReadonlyFieldLine = i; } } // Insert read only field let addFieldAfterClass = false; if (lastReadonlyFieldLine == -1) { addFieldAfterClass = true; lastReadonlyFieldLine = classStartLine + 2; } else { lastReadonlyFieldLine += 1; } await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { let fieldText = `\t\tprivate readonly ${className} _${variableName};\n`; if (addFieldAfterClass) { fieldText += '\n'; } editBuilder.insert(new vscode.Position(lastReadonlyFieldLine, 0), fieldText); }); // constructor doesn't exist if (constructorStartLine == -1) { if (lastReadonlyFieldLine != -1) { constructorStartLine = lastReadonlyFieldLine + 2; } else { constructorStartLine = classStartLine + 2; } // insert constructor await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { let constructorText = `\t\tpublic ${matchedClassName}(${className} ${variableName})\n`; constructorText += `\t\t{\n`; constructorText += `\t\t\t_${variableName} = ${variableName};\n`; constructorText += `\t\t}\n\n`; editBuilder.insert(new vscode.Position(constructorStartLine, 0), constructorText); }); } // constructor exists else { if (constructorStartLine == constructorEndLine) { let constrcutorLineText = document?.lineAt(constructorStartLine + 1).text!; let endingParenIndex = constrcutorLineText.indexOf(')'); // insert type and variable await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { let constructorText = `${className} ${variableName}`; let constrctorHasVarRegex = new RegExp(/\w+\)/g); let match; if ((match = constrctorHasVarRegex.exec(constrcutorLineText))) { constructorText = ', ' + constructorText; } editBuilder.insert(new vscode.Position(constructorStartLine + 1, endingParenIndex), constructorText); let variableText = `\t\t\t_${variableName} = ${variableName};\n`; editBuilder.insert(new vscode.Position(constructorStartLine + 3, 0), variableText); }); // format constructor variables on separate lines let unformattedConstructor = document?.lineAt(constructorStartLine + 1); let variableListRegex = new RegExp(/public\s\w+\((.+)\)/g); let variableListMatch = variableListRegex.exec(unformattedConstructor!.text); let variableList = variableListMatch![1].split(','); await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { editBuilder.delete(new vscode.Range(constructorStartLine + 1, 0, constructorStartLine + 1, unformattedConstructor!.text.length)); let constructorText = `\t\tpublic ${matchedClassName}(\n`; for (let i = 0; i < variableList.length; i++) { constructorText += `\t\t\t${variableList[i].trim()}`; if (i < variableList.length - 1) { constructorText += ',\n'; } else { constructorText += ')'; } } editBuilder.insert(new vscode.Position(constructorStartLine + 1, 0), constructorText); }); } else { let constructorEndLineText = document?.lineAt(constructorEndLine + 1).text!; let variableOnSameLineRegex = new RegExp(/\w+\)/g); let match; // last variable and closing parens are on same line if ((match = variableOnSameLineRegex.exec(constructorEndLineText))) { let endingParenIndex = constructorEndLineText.indexOf(')')!; // insert type and variable between last variable end and closing paren start await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { let constructorText = `,\n\t\t\t${className} ${variableName}`; editBuilder.insert(new vscode.Position(constructorEndLine + 1, endingParenIndex), constructorText); let variableText = `\t\t\t_${variableName} = ${variableName};\n`; editBuilder.insert(new vscode.Position(constructorEndLine + 3, 0), variableText); }); } // last variable and closing parens are on different lines else { let lastConstructorVariableLineText = document?.lineAt(constructorEndLine).text!; await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { let constructorText = `,\n\t\t\t${className} ${variableName}`; editBuilder.insert(new vscode.Position(constructorEndLine, lastConstructorVariableLineText.length), constructorText); let variableText = `\t\t\t_${variableName} = ${variableName};\n`; editBuilder.insert(new vscode.Position(constructorEndLine + 3, 0), variableText); }); } } } }); } }
Evgeniy-Polyak/CSharp.HelperPlus
src/extension.ts
<reponame>Evgeniy-Polyak/CSharp.HelperPlus<gh_stars>0 import * as vscode from 'vscode'; import { DependencyInjector } from './inject-dependency'; import { FileCreator } from './file-creator'; import { CodeEmbed } from './code-embed'; import { NamespaceFixer } from './namespace-fixer'; import { MethodAsyncToggler } from './method-async-toggler'; import { FilenameFixer } from './filename-fixer'; export function activate(context: vscode.ExtensionContext) { const injector = new DependencyInjector() context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.inject-dependency', injector.inject)); const fileCreator = new FileCreator(); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.create-class', fileCreator.createClass)); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.create-interface', fileCreator.createInterface)); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.create-enum', fileCreator.createEnum)); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.create-test', fileCreator.createTest)); const codeEmbed = new CodeEmbed(); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.embed-code', codeEmbed.embedCode)); const namespaceFixer = new NamespaceFixer(); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.fix-namespace', namespaceFixer.fix)); const filenameFixer = new FilenameFixer(); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.fix-filename', filenameFixer.fix)); const methodAsyncToggler = new MethodAsyncToggler(); context.subscriptions.push(vscode.commands.registerCommand('csharp-helper-plus.toggle-method-sync', methodAsyncToggler.toggle)); } export function deactivate() { }
Evgeniy-Polyak/CSharp.HelperPlus
src/namespace-fixer.ts
import * as vscode from 'vscode'; import * as path from 'path'; import { findCsProjFile, generateNamespace } from './utilities'; export class NamespaceFixer { public async fix() { const document = vscode.window.activeTextEditor?.document; if (typeof document === 'undefined') { return; } const csProjFile = findCsProjFile(path.dirname(document.fileName)); if (typeof csProjFile === 'undefined') { return; } const namespace = generateNamespace(csProjFile, path.dirname(document.fileName)); let namespaceRegex = new RegExp(/namespace\s/g); let namespaceLine = -1; for (let i = 0; i < document!.lineCount; i++) { let documentLine = document?.lineAt(i); let match; if ((match = namespaceRegex.exec(documentLine!.text))) { namespaceLine = i; break; } } if (namespaceLine === -1) { vscode.window.showInformationMessage('Couldn\'t find namespace'); return; } await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { editBuilder.delete(new vscode.Range(namespaceLine, 0, namespaceLine + 1, 0)); editBuilder.insert(new vscode.Position(namespaceLine, 0), `namespace ${namespace}\n`); }); } }
Evgeniy-Polyak/CSharp.HelperPlus
src/utilities.ts
<filename>src/utilities.ts<gh_stars>0 import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; export function findCsProjFile(p: string) { for (let n = 0; n < 10; n++) { let pathContent = fs.readdirSync(p, { withFileTypes: true }); for (let i = 0; i < pathContent.length; i++) { var pathItem = pathContent[i]; if (pathItem.isDirectory()) { continue; } if (pathItem.name.endsWith('.csproj')) { return p; } } p = path.join(p, '..'); } return undefined; } export function generateNamespace(projectPath: string, currentPath: string) { const rootNamespace = projectPath.substr(projectPath.lastIndexOf('\\')); let namespace = rootNamespace + currentPath.replace(projectPath, ''); var pathSepRegEx = /\//g; if (os.platform() === "win32") { pathSepRegEx = /\\/g; } namespace = namespace.replace(pathSepRegEx, '.'); namespace = namespace.replace(/\s+/g, "_"); namespace = namespace.replace(/-/g, "_"); if (namespace.startsWith('.')) { namespace = namespace.substr(1); } return namespace; }
Evgeniy-Polyak/CSharp.HelperPlus
src/file-creator.ts
<filename>src/file-creator.ts import * as vscode from 'vscode'; import * as os from 'os'; import * as path from 'path'; import * as fs from 'fs'; const ignoredDirectories = [ 'obj', 'bin', 'node_modules', '.git', '.vscode', '.vs', '.github' ]; let _lastSelectedPath = ''; export class FileCreator { public async createClass() { await promptFileCreation('class'); } public async createInterface() { await promptFileCreation('interface'); } public async createEnum() { await promptFileCreation('enum'); } public async createTest() { await promptFileCreation('test'); } } async function promptFileCreation(fileType: string) { if (_lastSelectedPath == '') { const activeDoc = vscode.window.activeTextEditor?.document; if (typeof activeDoc !== 'undefined') { _lastSelectedPath = path.dirname(activeDoc.fileName); } else { _lastSelectedPath = vscode.workspace.rootPath!; } } const selectedPath = await promptForPath(); if (typeof selectedPath === 'undefined') { return; } const projPath = findCsProjFile(selectedPath); if (typeof projPath === 'undefined') { vscode.window.showErrorMessage('Failed to find C# project.'); return; } const namespace = generateNamespace(projPath, selectedPath); if (typeof namespace === 'undefined') { vscode.window.showErrorMessage('Failed to generate namespace.'); return; } const className = await vscode.window.showInputBox({ ignoreFocusOut: true, prompt: 'Please enter class name.' }); if (typeof className === 'undefined') { return; } const filename = path.join(selectedPath, className + '.cs'); await createFile(filename, fileType, className, namespace); const doc = await vscode.workspace.openTextDocument(filename); await vscode.window.showTextDocument(doc); _lastSelectedPath = selectedPath; } async function createFile(filename: string, templateName: string, objectName: string, namespace: string) { const doc = await vscode.workspace.openTextDocument(vscode.extensions.getExtension('EvgeniyPolyak.csharp-helper-plus')!.extensionPath + '/templates/' + templateName + '.txt') let text = doc.getText(); text = text.replace('$namespace', namespace); text = text.replace(/\$name/g, objectName); fs.writeFileSync(filename, text); } function generateNamespace(projectPath: string, selectedPath: string) { const rootNamespace = projectPath.substr(projectPath.lastIndexOf('\\')); let namespace = rootNamespace + selectedPath.replace(projectPath, ''); var pathSepRegEx = /\//g; if (os.platform() === "win32") { pathSepRegEx = /\\/g; } namespace = namespace.replace(pathSepRegEx, '.'); namespace = namespace.replace(/\s+/g, "_"); namespace = namespace.replace(/-/g, "_"); if (namespace.startsWith('.')) { namespace = namespace.substr(1); } return namespace; } async function promptForPath(): Promise<string> { let pathInput = _lastSelectedPath; let selectedPath = ''; while (selectedPath == '') { let pathSelectionArray = getDirectories(pathInput); let quickPickItems: vscode.QuickPickItem[] = []; if (pathInput != vscode.workspace.rootPath) { quickPickItems.push(<vscode.QuickPickItem>{ label: '<Up>', description: path.join(pathInput, '..') }); } quickPickItems.push(<vscode.QuickPickItem>{ label: '<Here>', description: pathInput }); pathSelectionArray.forEach(p => { quickPickItems.push(<vscode.QuickPickItem>{ label: p }); }); const selection = await vscode.window.showQuickPick(quickPickItems); if (typeof selection === 'undefined') { break; } if (selection.label === '<Here>') { selectedPath = pathInput; } else if (selection.label === '<Up>') { pathInput = path.join(pathInput, '..'); } else { pathInput = path.join(pathInput, selection.label); } } return selectedPath; } function getDirectories(p: string) { let directories = []; let pathContent = fs.readdirSync(p, { withFileTypes: true }); for (let i = 0; i < pathContent.length; i++) { var pathItem = pathContent[i]; if (ignoredDirectories.includes(pathItem.name)) { continue; } if (pathItem.isDirectory()) { directories.push(pathContent[i].name); } } return directories; } function findCsProjFile(p: string) { for (let n = 0; n < 10; n++) { let pathContent = fs.readdirSync(p, { withFileTypes: true }); for (let i = 0; i < pathContent.length; i++) { var pathItem = pathContent[i]; if (pathItem.isDirectory()) { continue; } if (pathItem.name.endsWith('.csproj')) { return p; } } p = path.join(p, '..'); } return undefined; }
Evgeniy-Polyak/CSharp.HelperPlus
src/method-async-toggler.ts
import * as vscode from 'vscode'; export class MethodAsyncToggler { public async toggle() { const document = vscode.window.activeTextEditor?.document; if (typeof document === 'undefined') { return; } const position = vscode.window.activeTextEditor?.selection?.active; if (typeof position?.line === "undefined") { return; } let methodRegex = new RegExp(/(public|private)\s?([A-Za-z\s]+)?\s([A-Za-z\[\]\<\>]+)\s\w+\(/); let methodText: string = ""; let methodMatch; let methodLine: number; for (let i = position?.line; i > 0; i--) { let documentLine = document?.lineAt(i); if ((methodMatch = methodRegex.exec(documentLine!.text))) { methodText = documentLine.text; methodLine = i; break; } } if (methodMatch == null) { vscode.window.showInformationMessage('Couldn\'t find a method'); return; } if (methodText.includes("Task<") || methodText.includes(" Task ")) { let returnType = methodMatch[3]; let syncReturnType = ""; if (returnType == "Task") { syncReturnType = "void"; } else { syncReturnType = returnType.substr(5, returnType.length - 6); } methodText = methodText?.replace(returnType, syncReturnType).replace(" async ", " "); } else { let returnType = methodMatch[3]; let asyncReturnType = "async"; if (returnType == "void") { asyncReturnType += " Task"; } else { asyncReturnType += ` Task<${returnType}>`; } methodText = methodText?.replace(returnType, asyncReturnType); } await vscode.window.activeTextEditor?.edit((editBuilder: vscode.TextEditorEdit) => { editBuilder.delete(new vscode.Range(methodLine + 1, 0, methodLine, 0)); editBuilder.insert(new vscode.Position(methodLine + 1, 0), `${methodText}\n`); }); } }
Project-Sustain/sustain-dataset-curator
src/Curate.ts
import csv = require('csv-parser'); import fs = require('fs') interface RelevantFieldCache { [key: string]: { [relevantField: string]: string | number } } type MathOperator = "TIMES" | "DIVIDE" | "ADD" | "SUBTRACT" | "EXPONATE" | null; interface OutputField { type: "copy" | "math", input: string | (number | string)[], label?: string, toInt?: "FLOOR" | "ROUND" } export interface ConfigInterface { inputFilenames: string[], outputFile: string, joinField: string, outputFields: { [fieldName: string]: OutputField } } export default async function Curate(config: ConfigInterface) { const { inputFilenames, joinField, outputFields, outputFile } = config; const relevantFields: Set<string> = Object.values(outputFields).reduce((acc, { input }) => { if (typeof input === 'string') { acc.add(input) } else { for (const val of input) { if (typeof val === 'string' && val.substring(0, 2) !== "@@") { acc.add(val); } } } return acc; }, new Set<string>()) console.log("Fields which are relevant to this curation process are: ") console.log(relevantFields) const cache: RelevantFieldCache = {}; await (async () => { for (const inputFilename of inputFilenames) { await new Promise<void>(resolve => { fs.createReadStream(inputFilename) .pipe(csv()) .on('data', (data) => { const joinValue = data[joinField] if (joinValue != null) { if (!cache[joinValue]) { cache[joinValue] = {}; } for (const relevantField of [...relevantFields]) { if (data[relevantField]) { if (!isNaN(Number(data[relevantField]))) { data[relevantField] = Number(data[relevantField]); } cache[joinValue][relevantField] = data[relevantField]; } } } else { throw `Joinfield ${joinField} was missing from\n${JSON.stringify(data, null, 4)}` } }) .on('end', () => { resolve(); }); }); } console.log("Cache is built, now building dataset") fs.writeFileSync(outputFile, '') fs.appendFileSync(outputFile, Object.keys(outputFields).join(',') + '\n'); for (const relevantFields of Object.values(cache)) { let csvLine = ''; for (const outputField of Object.values(outputFields) as OutputField[]) { if (outputField.type === 'copy' && typeof outputField.input === 'string') { csvLine += relevantFields[outputField.input] } else if (outputField.type === 'math' && typeof outputField.input !== 'string') { let result = doTheMath(outputField.input, relevantFields) if (outputField.toInt) { switch (outputField.toInt) { case "FLOOR": result = Math.floor(result); break; case "ROUND": result = Math.round(result); break; } } csvLine += result; } csvLine += ',' } fs.appendFileSync(outputFile, csvLine.substring(0, csvLine.length - 1) + '\n') } console.log("Finished curating") })() } const doTheMath = (arr: (string | number)[], relevantFields: {[key:string]: string | number}): number => { const parenStart = '@@('; const parenEnd = '@@)'; let indexOfParenStart = arr.lastIndexOf(parenStart) let indexOfLastParenEnd = arr.indexOf(parenEnd, indexOfParenStart) arr = JSON.parse(JSON.stringify(arr)) while (indexOfParenStart !== -1) { arr.splice(indexOfParenStart, indexOfLastParenEnd - indexOfParenStart + 1, doTheMath(arr.slice(indexOfParenStart + 1, indexOfLastParenEnd), relevantFields)) indexOfParenStart = arr.lastIndexOf(parenStart) indexOfLastParenEnd = arr.indexOf(parenEnd, indexOfParenStart) } let result: number = 0; let recentOperator: MathOperator = null; for (const step of arr) { if (typeof step === 'string' && step.substring(0, 2) === '@@') { const operator = step.substring(2, step.length); recentOperator = operator as MathOperator; continue; } let num: number; if (typeof step === 'number') { num = step; } else if (typeof relevantFields[step] === 'number') { num = relevantFields[step] as number; } else { throw `Couldnt find ${step} in\n${JSON.stringify(relevantFields, null, 4)}` } if (!recentOperator) { result = num; } else { switch (recentOperator) { case "ADD": result += num; break; case "DIVIDE": if (result === 0 && num === 0) { result = 0; } else { result /= num; } break; case "EXPONATE": result = Math.pow(result, num); break; case "SUBTRACT": result -= num; break; case "TIMES": result *= num; break; } } } return result; }
Project-Sustain/sustain-dataset-curator
src/Curate.test.ts
import Curate, { ConfigInterface } from './Curate' import fs = require('fs') test('Curation single input', async () => { const config: ConfigInterface = { inputFilenames: ['./mock/tests.csv'], outputFile: './out/singleInputTestOutput.csv', joinField: "item", outputFields: { item: { type: 'copy', input: 'item' }, itemCopy: { type: 'copy', input: 'item' }, remainingTommorow: { type: 'math', input: ['stock', '@@SUBTRACT', 'demand'] }, profitPerDay: { type: 'math', input: ['demand', '@@TIMES', 'price'] } } } await Curate(config) const fileStuff = fs.readFileSync(config.outputFile).toString(); console.log(fileStuff) const fileStuffExpected = fs.readFileSync('./mock/singleInputTestOutput.csv').toString(); expect(fileStuff).toBe(fileStuffExpected); }); test('Curation multi input', async () => { const config: ConfigInterface = { inputFilenames: ['./mock/tests.csv', './mock/tests2.csv'], outputFile: './out/multiInputTestOutput.csv', joinField: "item", outputFields: { item: { type: 'copy', input: 'item' }, itemCopy: { type: 'copy', input: 'item' }, remainingTommorow: { type: 'math', input: ['stock', '@@SUBTRACT', 'demand'] }, profitPerDay: { type: 'math', input: ['demand', '@@TIMES', 'price'] }, tossedValue: { type: 'math', input: ['stock', '@@SUBTRACT', '@@(', 'demand', '@@TIMES', 'expireTime', '@@)', '@@TIMES', 'price'] }, unstockedValue: { type: 'math', input: ['@@(', "price", "@@TIMES", "demand", "@@TIMES", "expireTime", "@@)", "@@SUBTRACT", '@@(', 'stock', '@@TIMES', 'price', '@@)'] }, roundedOneQuarterPrice: { type: 'math', input: [1, '@@DIVIDE', 4, '@@TIMES', 'price'], toInt: 'ROUND' }, flooredOneQuarterPrice: { type: 'math', input: [1, '@@DIVIDE', 4, '@@TIMES', 'price'], toInt: 'FLOOR' }, priceDoubledAdd: { type: 'math', input: ['price', '@@ADD', 'price'] }, priceSquared: { type: 'math', input: ['price', '@@EXPONATE', 2] }, someNumber: { type: 'math', input: ['price', '@@ADD', '@@(','price','@@SUBTRACT','@@(','price','@@TIMES','price','@@)','@@)'] } } } await Curate(config) const fileStuff = fs.readFileSync(config.outputFile).toString(); console.log(fileStuff) const fileStuffExpected = fs.readFileSync('./mock/multiInputTestOutput.csv').toString(); expect(fileStuff).toBe(fileStuffExpected); });
Project-Sustain/sustain-dataset-curator
src/config.ts
<filename>src/config.ts<gh_stars>0 import { ConfigInterface } from "./Curate"; //treat the filenames like you are in the ROOT of the project. const config: ConfigInterface = { "inputFilenames": [ "./temp/nhgis0056_ds244_20195_2019_tract.csv" ], "outputFile": "./out/out.csv", "joinField": "GISJOIN", "outputFields": { "GISJOIN": { "type": "copy", "input": "GISJOIN" }, "with_an_internet_subscription_per_1000": { "label": "Number of Households With an Internet Subscription per 1000 Households", "type": "math", "input": [ "AL2FE002", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "with_dialup_per_1000": { "label": "Number of Households With only a Dial-Up Internet Subscription per 1000 Households", "type": "math", "input": [ "AL2FE003", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "with_broadband_per_1000": { "label": "Number of Households With a Broadband Internet Subscription per 1000 Households", "type": "math", "input": [ "AL2FE004", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "with_satellite_per_1000": { "label": "Number of Households With a Satellite Internet Subscription per 1000 Households", "type": "math", "input": [ "AL2FE005", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "with_other_per_1000": { "label": "Number of Households Some Other Type of Internet Subscription per 1000 Households", "type": "math", "input": [ "AL2FE006", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "access_no_subscription_per_1000": { "label": "Number of Households With Internet Access, but no Subscription per 1000 Households", "type": "math", "input": [ "AL2FE007", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "no_internet_per_1000": { "label": "Number of Households With No Internet Access per 1000 Households", "type": "math", "input": [ "AL2FE008", "@@DIVIDE", "AL2FE001", "@@TIMES", 1000 ], "toInt": "FLOOR" }, "number_of_households": { "label": "Number of Households", "type": "copy", "input": "AL2FE001" } } } export default config;
OurCnC/react-native-calendars
index.d.ts
import * as React from 'react'; import { StyleProp, ViewStyle } from 'react-native'; interface formatters_info { i?: string; u?: string; xxx?: string; vvv?: (xdate: XDate, useutc: boolean) => string; } interface locale_detail { monthNames?: string []; monthNamesShort?: string []; dayNames?: string[]; dayNamesShort?: string []; amDesignator?: string; pmDesignator?: string; } declare class XDate { //------------ //Constructors //------------ public constructor(); public constructor(utcmode: boolean); /** * constructor */ public constructor(xdate: XDate, utcmode?: boolean) ; /** * constructor * @param {Date} [nativeDate] - JavaScript native date */ public constructor(nativeDate: Date, utcmode?: boolean) ; /** * constructor * @param {number} [milliseconds] - milliseconds */ public constructor(milliseconds: number, utcmode?: boolean) ; /** * constructor * @param {number} [year] - year * @param {number} [month] - month * @param {number} [date] - date * @param {number} [hours] - hours * @param {number} [minutes] - minutes * @param {number} [seconds] - seconds * @param {number} [milliseconds] - milliseconds */ public constructor(year: number, month: number, date: number, hours?: number, minutes?: number, seconds?: number, milliseconds?: number, utcmode?: boolean); /** * constructor * @param {string} [dateString] - formatted date string */ public constructor(dateString: string, utcmode?: boolean); //------------ //Getters //------------ /** * Returns the 4-digit year (ex: 2012) * @return {number} 4-digit year (ex: 2012) */ public getFullYear(): number ; /* *Returns the month of the year. (0-11) *Value is zero-index, meaning Jan=0, Feb=1, Mar=2, etc. */ public getMonth(): number; /* *Returns the ISO week number of the year. (1-53) */ public getWeek(): number; /* *Returns the date of the month. (1-31) */ public getDate(): number; /* *Returns the day-of-week as a number. (0-6) *Sun=0, Mon=1, Tue=2, etc. */ public getDay(): number; /* *Returns the hour of the day. (0-23) */ public getHours(): number; /* *Returns the minute of the hour. (0-59) */ public getMinutes(): number; /* *Returns the second of the minute. (0-59) */ public getSeconds(): number; /* *Returns the millisecond of the second. (0-999) */ public getMilliseconds(): number; /* *Returns the number of milliseconds since the epoch. */ public getTime(): number; /* *Returns the number of milliseconds since the epoch. Identical to getTime. */ public valueOf(): number; //------------ //Setters //------------ /* *year is a 4-digit year */ public setFullYear(year: number, preventOverflow?: boolean): XDate; /* month is zero-indexed, meaning Jan=0, Feb=1, Mar=2, etc. */ public setMonth(month: number, preventOverflow?: boolean): XDate; /* *Moves the xdate to the Monday of the given week with time 00:00:00. *The week is represented by a given ISO week number and an optional year. If year is omitted, the xdate's year with be used. */ public setWeek(week: number, year?: number): XDate; /* *Sets the date of the month. (1-31) */ public setDate(date: number): XDate; /* *Sets the hour of the day. (0-23) */ public setHours(hours: number): XDate; /* *Sets the minute of the hour. (0-59) */ public setMinutes(minutes: number): XDate; /* *Sets the second of the minute. (0-59) */ public setSeconds(seconds: number): XDate; /* *Sets the millisecond of the second. (0-999) */ public setMilliseconds(milliseconds: number): XDate; /* *Sets the number of milliseconds since the epoch. */ public setTime(milliseconds: number): XDate; //------------ //Adding //------------ public addYears(years: number, preventOverflow?: boolean): XDate; public addMonths(months: number, preventOverflow?: boolean): XDate; public addWeeks(weeks: number): XDate; public addDays(days: number): XDate; public addHours(hours: number): XDate; public addMinutes(minutes: number): XDate; public addSeconds(seconds: number): XDate; public addMilliseconds(milliseconds: number): XDate; //------------ //Diffing //------------ public diffYears(otherDate: string): number ; public diffYears(otherDate: XDate): number ; public diffMonths(otherDate: string): number ; public diffMonths(otherDate: XDate): number ; public diffWeeks(otherDate: string): number ; public diffWeeks(otherDate: XDate): number ; public diffDays(otherDate: string): number ; public diffDays(otherDate: XDate): number ; public diffHours(otherDate: string): number ; public diffHours(otherDate: XDate): number ; public diffMinutes(otherDate: string): number ; public diffMinutes(otherDate: XDate): number ; public diffSeconds(otherDate: string): number ; public diffSeconds(otherDate: XDate): number ; public diffMilliseconds(otherDate: string): number ; public diffMilliseconds(otherDate: XDate): number ; //------------ //Formatting //------------ /* *If formatString is not specified, a browser-produced IETF string will be returned. * settings can be a name of an available locale or an object that overrides the default locale's settings. */ public toString(formatString?: string, settings?: Object): string; /* *Same as toString but gets its values from the UTC version of the date. *As a result, "Z" will be displayed as the timezone. */ public toUTCString(formatString?: string, settings?: Object): string; public toGMTString(formatString?: string, settings?: Object): string; /* *Returns an ISO8601 string that has been normalized to UTC. Will have a "Z" timezone indicator. *See the native Date's specs for toISOString. */ public toISOString(): string; /* *Same as native Date's toDateString */ public toDateString(): string; /* *Same as native Date's toTimeString */ public toTimeString(): string; /* *Same as native Date's toLocaleString */ public toLocaleString(): string; /* *Same as native Date's toLocaleDateString */ public toLocaleDateString(): string; /* *Same as native Date's toLocaleTimeString */ public toLocaleTimeString(): string; //------------ //Formatting //------------ public getUTCFullYear(): number ; public getUTCMonth(): number ; public getUTCWeek(): number ; public getUTCDate(): number ; public getUTCDay(): number ; public getUTCHours(): number ; public getUTCMinutes(): number ; public getUTCSeconds(): number ; public getUTCMilliseconds(): number ; public setUTCFullYear(year: number): XDate; public setUTCMonth(month: number): XDate; public setUTCWeek(week: number, year?: number): XDate; public setUTCDate(date: number): XDate; public setUTCHours(hours: number): XDate; public setUTCMinutes(minutes: number): XDate; public setUTCSeconds(seconds: number): XDate; public setUTCMilliseconds(milliseconds: number): XDate; //------------ //UTC Mode //------------ /* *Returns true if the date is in UTC-mode and false otherwise */ public getUTCMode(): boolean; /* *utcMode must be either true or false. If the optional doCoercion parameters is set to true, *the underlying millisecond time of the date will be coerced in such a way that methods like *getDate and getHours will have the same values before and after the conversion. */ public setUTCMode(utcMode: boolean, doCoercion?: boolean): XDate; /* *Returns the number of minutes from UTC, just like the native Date's getTimezoneOffset. *However, if the XDate is in UTC-mode, 0 will be returned. */ public getTimezoneOffset(): number; //------------ //Utilities //------------ /* *returns a copy of the XDate */ public clone(): XDate; /* *sets the hours, minutes, seconds, and milliseconds to zero */ public clearTime(): XDate ; /* *return true if the XDate is a valid date, false otherwise */ public valid(): boolean ; /* *Returns a conversion to a native Date */ public toDate(): Date; //------------ //Static function //------------ /* *Returns the number of days in the given month */ public static getDaysInMonth(year: number, month: number): number; /* *Parses a date-string and returns milliseconds since the epoch. You'll probably want to use new XDate(dateString) instead. */ public static parse(dateString: string): number; /* *Returns the current date, as milliseconds since the epoch. You'll probably want to use new XDate() instead. */ public static now(): number ; /* *Returns the current date with time cleared, as an XDate object */ public static today(): XDate ; /* *Returns a milliseconds time since the epoch for the given UTC date */ public static UTC(year: number, month: number, date: number, hours: number, minutes: number, seconds: number, milliseconds: number ): XDate; public static locales: { [ key: string ]: locale_detail; }; public static defaultLocale: string; public static formatters: formatters_info; public static getDaysInMonth(year: number, month: number): number; public static UTC( year: number, month: number, day: number, hours?: number, minutes?: number, seconds?: number, ms?: number ): number; } export interface ParamDayProps { dateString: string, day: number, month: number, timestamp: number, year: number } interface CalendarProps { theme?: object, markedDates?: object, style?: StyleProp<ViewStyle>, current?: any, minDate?: any, maxDate?: any, firstDay?: number, markingType?: string, hideArrows?: boolean, displayLoadingIndicator?: boolean, hideExtraDays?: boolean, onDayPress?: (day: ParamDayProps) => any, onMonthChange?: Function, onVisibleMonthsChange?: Function, renderArrow?: Function, dayComponent?: any, extraDayComponent?: any, monthFormat?: string, disableMonthChange?: boolean, hideDayNames?: boolean, disabledByDefault?: boolean, showWeekNumbers?: boolean, calendarHeight?: number } interface CalendarListProps extends CalendarProps { pastScrollRange?: number, futureScrollRange?: number, scrollEnabled?: boolean, showScrollIndicator?: boolean, scrollsToTop?: boolean } interface AgendaProps { theme?: object, style?: StyleProp<ViewStyle>, items?: object, loadItemsForMonth?: Function, onCalendarToggled?: Function, onDayPress?: Function, onDaychange?: Function, renderItem?: Function, renderDay?: Function, renderKnob?: Function, renderEmptyDay?: Function, renderEmptyData?: Function, rowHasChanged?: Function, pastScrollRange?: number, futureScrollRange?: number, selected?: any, minDate?: any, maxDate?: any, markedDates?: object, markingType?: string, hideKnob?: boolean, monthFormat?: string } declare class Calendar extends React.Component<CalendarProps, any> {} declare class CalendarList extends React.Component<CalendarListProps, any> { scrollToDay(date: ParamDayProps, timeout: number, animation: boolean); } declare class Agenda extends React.Component<AgendaProps, any> {} declare class LocaleConfig extends XDate {} export { Calendar, CalendarList, Agenda, LocaleConfig };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/reviews.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { CreateReviewRequest, ReviewResponse, UpdateReviewRequest } from '../model/api/review.model'; import { Page } from '../model/api/page.model'; import { HttpRequestService } from './http-request-services'; import { map } from 'rxjs/operators'; import { UsersService } from './users.service'; import { QueryUtil } from '../util/query.util'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { OCReviewDetailsResponse } from '../model/components/frontend.model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting reviews.<br> * * Endpoints: * * GET 'v2/reviews' * */ @Injectable({ providedIn: 'root', }) export class ReviewsService { constructor(private httpService: HttpRequestService, private usersService: UsersService, private apiPaths: OcApiPaths) {} /** * * Description: Get reviews by App id and merge it with user data with pagination * * @param {string} appId (required) * @param {number} page (optional) Current page index. Starts from >= 1. * @param {number} limit (optional) Count Reviews into response. Starts from >= 1. * @param {string} sort (optional) Sort Reviews by specific field. * @param {string[]} filter (optional) Array for your specific search filters. * @returns {Observable<Page<OCReviewDetailsResponse>>} Observable<Page<OCReviewDetailsResponse>> * * ### Example * `` * getReviewsByAppId('a7hsd87ha8sdh8a7sd',1, 10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}") * `` */ getReviewsByAppId( appId: string, sort?: string, filter?: string[], page?: number, limit?: number, ): Observable<Page<OCReviewDetailsResponse>> { let queries = [`{'appId':'${appId}'}`]; if (filter) { queries = [...queries, ...filter]; } let params = new OcHttpParams().append('query', QueryUtil.getAndQuery(queries)).append('sort', sort); if (page > 0 && limit > 0) { params = params.append('pageNumber', String(page)).append('limit', String(limit)); } return this.httpService.get(this.apiPaths.reviews, { params }).pipe( map((reviewPage: Page<ReviewResponse>) => { return { ...reviewPage, list: reviewPage.list.map(review => ({ ...review, review: review.description, reviewOwnerName: review.user.name, })), }; }), ); } /** * Description: Create the new review. * @param {ReviewResponse} reviewData data of the review. Must contain fields `appId`, `headline`, `rating`, * `description` and optional field `customData`. * * ### Example: * `createReview({appId: 5565322ae4b0a70b13a4563b, headline: "Good App", rating: 400, description: ""})` */ createReview(reviewData: ReviewResponse | CreateReviewRequest): Observable<ReviewResponse> { return this.httpService.post(this.apiPaths.reviews, reviewData); } /** * Description: Updating an app review allows users to modify their reviews. * @param {ReviewResponse} reviewData data of the review. Must contain fields `reviewId`, `headline`, `rating`, * `description` and optional field `customData`. * * ### Example: * `updateReview({reviewId: "5565322ae4b0a70b13a4563b", headline: "Good App", rating: 400, description: ""})` */ updateReview(reviewData: ReviewResponse | UpdateReviewRequest): Observable<ReviewResponse> { return this.httpService.patch(`${this.apiPaths.reviews}/${reviewData.reviewId}`, reviewData); } /** * Description: Returns a single, specific, review record. * @param {string} reviewId ID of the review. * * ### Example: * `getOneReview("5565322ae4b0a70b13a4563b")` */ getOneReview(reviewId: string): Observable<ReviewResponse> { return this.httpService.get(`${this.apiPaths.reviews}/${reviewId}`); } /** * Description: Deletes a review. Returns an empty response on the success. * @param reviewId the ID of the review * * ### Example: * `deleteReview("5565322ae4b0a70b13a4563b")` */ deleteReview(reviewId: string): Observable<any> { return this.httpService.delete(`${this.apiPaths.reviews}/${reviewId}`); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-additional-select/oc-additional-select.component.spec.ts
<filename>projects/angular-common-components/src/lib/form-components/oc-additional-select/oc-additional-select.component.spec.ts import { ComponentFixture, TestBed } from '@angular/core/testing'; import { OcAdditionalSelectComponent } from './oc-additional-select.component'; import { MockSelectComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcAdditionalSelectComponent', () => { let component: OcAdditionalSelectComponent; let fixture: ComponentFixture<OcAdditionalSelectComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [OcAdditionalSelectComponent, MockSelectComponent], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OcAdditionalSelectComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/page.model.ts
export interface Page<T> { pages: number; count: number; pageNumber: number; list: T[]; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-image-gallery/oc-image-gallery.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcImageGalleryComponent } from './oc-image-gallery.component'; import { By } from '@angular/platform-browser'; import { SimpleChange } from '@angular/core'; import { GalleryItem } from '@openchannel/angular-common-components/src/lib/common-components'; import { MockVideoComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { CarouselModule } from 'ngx-owl-carousel-o'; describe('OcImageGalleryComponent', () => { let component: OcImageGalleryComponent; let fixture: ComponentFixture<OcImageGalleryComponent>; const imageItem: GalleryItem = { image: '', title: 'Test Image', description: 'Improve and extend your experience right from your own UI', }; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcImageGalleryComponent, MockVideoComponent], imports: [CarouselModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcImageGalleryComponent); component = fixture.componentInstance; component.gallery = [imageItem, imageItem, imageItem, imageItem, imageItem, imageItem]; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show images', () => { const imageTitle: HTMLParagraphElement = fixture.debugElement.query(By.css('p')).nativeElement; const imageDescription: HTMLSpanElement = fixture.debugElement.query(By.css('span')).nativeElement; expect(imageTitle.textContent).toContain('Test Image'); expect(imageDescription.textContent).toContain('Improve and extend your experience right from your own UI'); }); it('should splice images', () => { component.maxItems = 5; component.ngOnChanges({ maxItems: new SimpleChange(3, component.maxItems, true), }); fixture.detectChanges(); expect(component.displayGallery.length).toEqual(5); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/array-search.pipe.spec.ts
import { ArraySearchPipe } from './array-search.pipe'; describe('ArraySearchPipePipe', () => { it('create an instance', () => { const pipe = new ArraySearchPipe(); expect(pipe).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-app-short-info/oc-app-short-info.component.spec.ts
<filename>projects/angular-common-components/src/lib/market-components/oc-app-short-info/oc-app-short-info.component.spec.ts import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcAppShortInfoComponent } from '@openchannel/angular-common-components/src/lib/market-components'; import { MockRatingComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { FullAppData, HtmlTagsReplacerPipe, PricePipe, StatElement, } from '@openchannel/angular-common-components/src/lib/common-components'; const stat: StatElement = { '90day': 20, '30day': 10, total: 30, }; const app: FullAppData = { appId: '123', summary: 'summary summary', created: undefined, developerId: '321', isLive: false, lastUpdated: undefined, model: [ { type: 'recurring', price: 5, trial: 1, license: 'single', modelId: '23235hfg4', currency: 'EUR', billingPeriod: 'monthly', }, ], name: '<NAME>', reviewCount: 0, safeName: [], statistics: { views: stat, downloads: stat, developerSales: stat, totalSales: stat, ownerships: stat, reviews: stat, }, status: { value: 'inDevelopment', lastUpdated: 1.1, modifiedBy: '', reason: '', }, submittedDate: new Date(), version: 0, rating: 50, }; describe('OcAppShortInfoComponent', () => { let component: OcAppShortInfoComponent; let fixture: ComponentFixture<OcAppShortInfoComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcAppShortInfoComponent, MockRatingComponent, HtmlTagsReplacerPipe, PricePipe], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcAppShortInfoComponent); component = fixture.componentInstance; component.app = app; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/market.service.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpRequestService } from './http-request-services'; import { MarketModel } from '../model/api/market.model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting Market Data.<br> * * Endpoints:<br> * * GET 'v2/markets/this'<br> */ @Injectable({ providedIn: 'root', }) export class MarketService { constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {} /** * Description: Get Current Market Data * * @returns {Observable<MarketModel>} `Observable<MarketModel>` * * * ### Example * * getCurrentMarket() */ getCurrentMarket(): Observable<MarketModel> { const mainUrl = `${this.apiPaths.markets}/this`; return this.httpService.get(mainUrl); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/statistic.service.ts
import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { OcApiPaths } from '../oc-ng-common-service.module'; import { HttpHeaders } from '@angular/common/http'; /** * Description: API service for work with statistic.<br> * * Endpoints:<br> * * POST 'v2/stats/increment/views'<br> * */ @Injectable({ providedIn: 'root', }) export class StatisticService { constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * Description: Increment visits to app * * @param {string} appId - (required) * @param {HttpHeaders} headers - (optional) * @returns {Observable<any>} `Observable<any>` * * ### Example * * `recordVisitToApp('a2sd876ags7dd6g')` * */ recordVisitToApp(appId: string, headers?: HttpHeaders): Observable<any> { const mainUrl = `${this.apiPaths.stats}/increment/views`; return this.httpRequest.post(mainUrl, { appId }, headers ? { headers } : {}); } /** * Description: Increment app statistic field * * @param {string} field - (required) * @param {string} appId - (required) * @param {HttpHeaders} headers - (optional) * @returns {Observable<any>} `Observable<any>` * * ### Example * * `record('installs','a2sd876ags7dd6g')` * */ record(field: string, appId: string, headers?: HttpHeaders): Observable<any> { const mainUrl = `${this.apiPaths.stats}/increment/${field}`; return this.httpRequest.post(mainUrl, { appId }, headers ? { headers } : {}); } }
mukesh-openchannel/angular-template-libraries
src/label.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcLabelComponent, OcTooltipLabelComponent } from '@openchannel/angular-common-components/src/public-api'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules = { imports: [OcCommonLibModule, NgbModule], }; export default { title: 'Label [BEM]', component: OcLabelComponent, decorators: [moduleMetadata(modules)], }; const LabelComponent = (args: OcLabelComponent) => ({ component: OcLabelComponent, moduleMetadata: modules, props: args, }); export const DefaultLabel = LabelComponent.bind({}); DefaultLabel.args = { text: 'Name', }; export const RequiredLabel = LabelComponent.bind({}); RequiredLabel.args = { text: 'Name', required: true, }; const TooltipLabelComponent = (args: OcTooltipLabelComponent) => ({ component: OcTooltipLabelComponent, moduleMetadata: modules, props: args, }); export const TooltipLabel = TooltipLabelComponent.bind({}); TooltipLabel.args = { text: 'Name', description: 'Tooltip Text', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-input/oc-input.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcInputComponent } from './oc-input.component'; import { FormsModule } from '@angular/forms'; import { MockAutofocusDirective } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcInputComponent', () => { let component: OcInputComponent; let fixture: ComponentFixture<OcInputComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcInputComponent, MockAutofocusDirective], imports: [FormsModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcInputComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should contain value', () => { component.writeValue('Hello world!'); expect(component.inputValue).toEqual('Hello world!'); }); it('should contain value in input', async () => { component.writeValue('Hello world!'); const input = fixture.nativeElement.querySelector('input'); fixture.detectChanges(); await fixture.whenStable().then(() => { expect(input.value).toEqual('Hello world!'); }); }); it('should bind input value to field', () => { const hostElement = fixture.nativeElement; const input = hostElement.querySelector('input'); const newInputVal = 'quick BROWN fOx'; input.value = newInputVal; // dispatch a DOM event so that Angular learns of input value change. // use new Event utility function (not provided by Angular) for better browser compatibility input.dispatchEvent(new Event('input')); fixture.detectChanges(); expect(component.inputValue).toBe(newInputVal); }); it('input should contain placeholder', () => { component.placeholder = 'test input'; const input = fixture.nativeElement.querySelector('input'); fixture.detectChanges(); expect(input.placeholder).toEqual('test input'); }); it('input should be disabled', async () => { component.setDisabledState(true); const input = fixture.nativeElement.querySelector('input'); 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.nativeElement.querySelector('input'); input.value = '<NAME> <PASSWORD>'; 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.nativeElement.querySelector('input'); input.value = '<NAME> <PASSWORD>'; input.dispatchEvent(new Event('blur')); expect(onTouchedFunc).toHaveBeenCalled(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/prerender-endpoints-config.model.ts
/** * Class for the special Netlify prerender config. Using by {@link HttpRequestsWatcherInterceptor}. * It contains the API endpoints, which should have a special processing for the search crawlers. * * `excludeAPICall: string[]` - start string of the endpoints which should not be called for the search crawler. * @example * const prerenderEndpoints: PrerenderEndpointsConfig = { * excludeAPICall: ["/v2/stats/increment/"] * } */ export class PrerenderEndpointsConfig { /** * start string of the endpoints which should not be called for the search crawler. */ excludeAPICall?: string[]; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/app-form-model.ts
export interface AppFormFieldResponse { id: string; label: string; description: string; defaultValue: string; type: string; required?: any; attributes: string[]; options?: any; fields?: AppFormFieldResponse[]; placeholder: string; } /** * Used as response body for getting a form.<br> * [Get Forms API endpoint]{@link getForms}<br> * [Get Form by ID API endpoint]{@link getForm}<br> */ export interface AppFormModelResponse { formId: string; name: string; createdDate: number; fields?: AppFormFieldResponse[]; } /** * Status for form submission. Can be one of: 'open', 'closed'. */ export interface FormSubmissionStatus { value: string; } /** * Used as response body for create form submission.<br> * [API endpoint]{@link createFormSubmission}<br> * [Openchannel docs]{@link https://support.openchannel.io/documentation/api/user-api/forms/create-form-submission/} */ export interface FormSubmissionModel { formSubmissionId: string; formId: string; archived?: boolean; status?: FormSubmissionStatus; submittedDate: number; name: string; email: string; appId: string; developerId: string; userId?: string; formData: any; } /** * Used as request body for create form submission.<br> * [API endpoint]{@link createFormSubmission}<br> * [Openchannel docs]{@link https://support.openchannel.io/documentation/api/user-api/forms/create-form-submission/} */ export interface CreateFormSubmissionModel { name: string; appId: string; userId: string; email: string; formData: any; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/frontend.service.ts
import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { Page } from '../model/api/page.model'; import { FilterResponse, SortResponse } from '../model/components/frontend.model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * * Description: API service for getting available features for frontend.<br> * * Endpoints:<br> * * GET 'v2/frontEnd/sorts'<br> * * GET 'v2/frontEnd/filters'<br> */ @Injectable({ providedIn: 'root', }) export class FrontendService { constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Get available sorts for frontend * * @returns {Observable<Page<SortResponse>>} `Observable<Page<SortResponse>>` * * ### Example: * * `getSorts();` */ getSorts(): Observable<Page<SortResponse>> { return this.httpRequest.get(`${this.apiPaths.frontEnd}/sorts`); } /** * * Description: Get available filters for frontend * * @returns {Observable<Page<FilterResponse>>} `Observable<Page<FilterResponse>>` * * ### Example: * * `getFilters();` */ getFilters(): Observable<Page<FilterResponse>> { return this.httpRequest.get(`${this.apiPaths.frontEnd}/filters`); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/model/datetime.model.ts
/** Little interface for one day of the month in the {@link OcDatetimePickerComponent} */ export interface DayOfMonth { day: number; date: Date; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-full-image-gallery-view-modal/oc-full-image-gallery-view-modal.component.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>projects/angular-common-components/src/lib/common-components/oc-full-image-gallery-view-modal/oc-full-image-gallery-view-modal.component.ts import { Component, HostListener, Input, OnInit } from '@angular/core'; import { GalleryItem, GalleryIconsAssets } from '../model/image-gallery.model'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'oc-full-image-gallery-view-modal', templateUrl: './oc-full-image-gallery-view-modal.component.html', styleUrls: ['./oc-full-image-gallery-view-modal.component.scss'], }) export class OcFullImageGalleryViewModalComponent implements OnInit { /** * Items of the gallery to be shown in this modal by navigation. * This is required parameter. */ @Input() galleryItems: GalleryItem[]; /** * Index of the item in array to be shown. * First slide will be shown by default. * @default 0 */ @Input() activeItemIdx: number = 0; /** * Display of title and description of the gallery item. Details are displayed by default. * @default true */ @Input() showDetails: boolean = true; /** * Display the current item index and overall items count. * @default false */ @Input() isShowCounter: boolean = false; /** * Config for paths of the icons used in this component. * You can change icons by setting a new path in this config or create an `angular-common-components` * folder in your `assets`, and then add your icon with the name from this config. */ @Input() componentIconsPath: GalleryIconsAssets = { arrowLeft: 'assets/angular-common-components/arrow-left-analog.svg', arrowRight: 'assets/angular-common-components/arrow-right-analog.svg', closeIcon: 'assets/angular-common-components/close-icon.svg', }; constructor(private modal: NgbActiveModal) {} ngOnInit(): void { this.setWidthOfMedia(); } /** * Listening to the event of keyboard keys and changing slides by arrow keys. * @param event keyboard event with keys data */ @HostListener('window:keyup', ['$event']) handleKeyUp(event: KeyboardEvent): void { if (event.code === 'ArrowRight') { this.nextSlide(); } else if (event.code === 'ArrowLeft') { this.prevSlide(); } } /** * Changing media item to the next. If it was the last item - first item will be shown again. */ nextSlide(): void { if (this.activeItemIdx === this.galleryItems.length - 1) { this.activeItemIdx = 0; } else { this.activeItemIdx++; } } /** * Changing media item to the previous. If it was the first item - last item will be shown again. */ prevSlide(): void { if (this.activeItemIdx === 0) { this.activeItemIdx = this.galleryItems.length - 1; } else { this.activeItemIdx--; } } /** * Closing current modal. */ closeModal(): void { this.modal.dismiss(); } /** * Loading each image of the Gallery and getting the width if it is not set manually already. */ setWidthOfMedia(): void { this.galleryItems.forEach(item => { if (item.image && !item.mediaWidth) { const img = new Image(); img.src = item.image; img.onload = event => { item.mediaWidth = (event.target as HTMLImageElement).width; }; } }); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/camelcase.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'camelcase', }) export class CamelcasePipe implements PipeTransform { transform(input: string): string { if (!input) { return ''; } else { const spacedStr = input.split(/(?=[A-Z])/).join(' '); return spacedStr.substring(0, 1).toUpperCase() + spacedStr.substring(1, spacedStr.length); } } }
mukesh-openchannel/angular-template-libraries
src/resend-activation.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { ComponentsUserActivationModel, OcCommonLibModule, OcResendActivationComponent, } from 'projects/angular-common-components/src/public-api'; import { RouterTestingModule } from '@angular/router/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms'; import { action } from '@storybook/addon-actions'; import { NgModule } from '@angular/core'; import { ERROR_MESSAGES_STORY_PROVIDER } from './utils.model'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules: NgModule = { imports: [OcCommonLibModule, RouterTestingModule.withRoutes([]), BrowserAnimationsModule, FormsModule], providers: [ERROR_MESSAGES_STORY_PROVIDER], }; const activationEmpty = new ComponentsUserActivationModel(); const activationFilled = new ComponentsUserActivationModel(); activationFilled.email = '<EMAIL>'; activationFilled.code = 'fj45GHd34g'; activationFilled.password = '<PASSWORD>'; export default { title: 'Resend Activation Code [BEM]', component: OcResendActivationComponent, decorators: [moduleMetadata(modules)], argTypes: { buttonClick: action('Activation clicked') }, }; const ForgotPasswordComponent = (args: OcResendActivationComponent) => ({ component: OcResendActivationComponent, moduleMetadata: modules, props: args, }); export const Empty = ForgotPasswordComponent.bind({}); Empty.args = { activationModel: activationEmpty, loginUrl: 'login', signupUrl: 'signup', companyLogoUrl: './assets/angular-common-components/logo-company.png', }; export const Filled = ForgotPasswordComponent.bind({}); Filled.args = { activationModel: activationFilled, loginUrl: 'login', signupUrl: 'signup', companyLogoUrl: './assets/angular-common-components/logo-company.png', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/cms-site-content.service.ts
<gh_stars>0 import { Observable } from 'rxjs/internal/Observable'; import { forIn, get, has } from 'lodash'; import { catchError, defaultIfEmpty, map } from 'rxjs/operators'; import { of, Subject } from 'rxjs'; /** * Abstract RXJS service for working with CMS site data.<br> * Note (Important!): After creating service execute function {@link #initContent}<br> * * @example implementation * * import defaultCMSContent from '.../assets/content/_defaultContent.json'; * import { CMSSiteContentService, SiteContentService } from '@openchannel/angular-common-services'; * * @Injectable({ * providedIn: 'root', * }) * export class CmsContentService extends CMSSiteContentService { * * constructor(private contentAPIService: SiteContentService) { * super(); * super.initContent(); * } * * getContentFromAPI(): Observable<any> { * return this.contentAPIService.getContentById('siteId', 'contentId') * .pipe(map(response => response.customData)) * } * * getContentDefault(): any { * return defaultCMSContent; * } * } * * @example usage * constructor(private cmsService: CmsContentService) {...} * * this.cmsService * .getContentByPaths({ * logoImageURL: 'default-footer.logo', * contentColumns: 'default-footer.menu.items', * }) * .subscribe(content => { * this.cmsData.logoImageURL = content.logoImageURL as string; * this.cmsData.contentColumns = content.contentColumns as []; * }); * } */ export abstract class CMSSiteContentService { private cmsData: any; private modifyContentCMSSubject: Subject<boolean> = new Subject<boolean>(); /** * Get content from API. Result data structure mast be equals data from {@link #getContentDefault} * When will throw an Error or Observable will be empty, service will use data from {@link #getContentDefault} * @return Observable<any> - your CMS data. */ abstract getContentFromAPI(): Observable<any>; /** * Get local content. Use when {@link #getContentFromAPI} did not work correctly. * @return any - your CMS data. */ abstract getContentDefault(): any; /** * Getting content from API or local data. */ initContent(): void { this.getContentFromAPI() .pipe( catchError(() => of(this.getContentDefault())), defaultIfEmpty(this.getContentDefault()), ) .subscribe(content => { this.cmsData = content || {}; this.modifyContentCMSSubject.next(); }); } /** * Returns content by paths. See 'usage' section in {@link #CMSSiteContentService} */ getContentByPaths<P>(paths: P): Observable<{ [PK in keyof P]: any }> { if (this.cmsData) { return of(this.findContentByPaths(paths)); } else { return this.modifyContentCMSSubject.pipe(map(() => this.findContentByPaths(paths))); } } private findContentByPaths<P>(paths: P): { [PK in keyof P]: any } { const tempPathsData = { ...paths }; Object.keys(tempPathsData).forEach(key => (tempPathsData[key] = null)); forIn(paths, (path, name) => (tempPathsData[name] = this.tryGetContentByPath(this.cmsData, path))); return tempPathsData; } private tryGetContentByPath(cmsData: any, path: any): string { if (has(cmsData, path)) { return get(cmsData, path); } else { console.warn(`CMS content. Invalid content path: ${path}`); return undefined; } } }
mukesh-openchannel/angular-template-libraries
src/chart.stories.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>src/chart.stories.ts import { moduleMetadata } from '@storybook/angular'; import { ChartLayoutTypeModel, ChartStatisticAppModel, OcChartComponent, OcCommonLibModule, } from 'projects/angular-common-components/src/public-api'; import { sum } from 'lodash'; import { NgModule } from '@angular/core'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules: NgModule = { imports: [OcCommonLibModule], }; export default { title: 'Chart [BEM]', component: OcChartComponent, decorators: [moduleMetadata(modules)], }; 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 day = { labelsY: [200, 400, 100, 50, 700, 750, 250, 200, 400, 100, 50, 700, 750], labelsX: [ 'Jan 30', 'Jan 31', 'Feb 01', 'Feb 02', 'Feb 03', 'Feb 04', 'Feb 04', 'Feb 06', 'Feb 07', 'Feb 08', 'Feb 09', 'Feb 10', 'Feb 11', ], tabularLabels: [ 'Jan 30', 'Jan 31', 'Feb 01', 'Feb 02', 'Feb 03', 'Feb 04', 'Feb 04', 'Feb 06', 'Feb 07', 'Feb 08', 'Feb 09', 'Feb 10', 'Feb 11', ], }; 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 ChartComponent = (args: OcChartComponent) => ({ component: OcChartComponent, moduleMetadata: modules, props: args, }); export const Monthly = ChartComponent.bind({}); Monthly.args = { chartData: { layout: ChartLayoutTypeModel.standard, data: month, periods, fields, apps, }, count: sum(month.labelsY), countText: 'Total', downloadUrl: './assets/img/upload_icon.svg', isBackgroundColor: true, enablePoints: true, random: true, }; export const Daily = ChartComponent.bind({}); Daily.args = { chartData: { layout: ChartLayoutTypeModel.standard, data: day, periods, fields, apps, }, count: sum(day.labelsY), countText: 'Total', downloadUrl: './assets/img/upload_icon.svg', isBackgroundColor: true, enablePoints: true, random: true, }; export const WitoutAppsDropdown = ChartComponent.bind({}); WitoutAppsDropdown.args = { chartData: { layout: ChartLayoutTypeModel.standard, data: day, periods, fields, }, count: sum(day.labelsY), countText: 'Total', downloadUrl: './assets/img/upload_icon.svg', isBackgroundColor: true, enablePoints: true, random: true, }; export const Empty = ChartComponent.bind({}); Empty.args = { count: 0, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/developer-account.model.ts
<filename>projects/angular-common-services/src/lib/model/api/developer-account.model.ts export interface DeveloperAccount { developerId: string; name: string; email: string; customData: any; created: number; type: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/service/trim-text-utils/trim-text.service.spec.ts
import { TrimTextUtils } from './trim-text.service'; import { AppFormField, TrimFormFieldType } from '@openchannel/angular-common-components/src/lib/form-components'; import { AppTypeFieldModel } from '@openchannel/angular-common-components/src/lib/common-components'; type SimpleFieldType = { textKey: string; textNullKey: string; richTextKey: string; numberKey: number; numberNullKey: number; }; type CustomField<T extends SimpleFieldType> = (Omit<AppFormField, 'label'> & { id: keyof T })[]; describe('TrimTextUtils', () => { let trimFields: TrimFormFieldType[]; beforeEach(() => { trimFields = ['text', 'richText']; }); it('Trim simple fields [richText, text]', () => { expect(TrimTextUtils.trimTextFields(createSimpleData(), createSimpleFields() as AppFormField[], trimFields)).toEqual({ ...createSimpleData(), textKey: 'textValue', richTextKey: '<a>richTextValue</a>', }); }); it('Skip simple fields [richText]', () => { const newTrimFields = trimFields.filter(f => f !== 'richText'); expect(TrimTextUtils.trimTextFields(createSimpleData(), createSimpleFields() as AppFormField[], newTrimFields)).toEqual({ ...createSimpleData(), textKey: 'textValue', }); }); it('Trim fields into DFA', () => { const data = { dfaKey: [ { ...createSimpleData(), dfaNullKey: null, dfaKey: [ { ...createSimpleData(), }, ], }, ], }; expect(TrimTextUtils.trimTextFields(data, createDfaField(), trimFields)).toEqual({ dfaKey: [ { ...createSimpleData(), textKey: 'textValue', richTextKey: '<a>richTextValue</a>', dfaNullKey: null, dfaKey: [ { ...createSimpleData(), textKey: 'textValue', richTextKey: '<a>richTextValue</a>', }, ], }, ], }); }); it('Trim and update the URL text', () => { expect( TrimTextUtils.trimTextFields( { emptyUrl: '', urlKey: ' test-site.com ', spacedUrl: ' http://test-site.com ', }, [ { id: 'urlKey', type: 'websiteUrl' }, { id: 'spacedUrl', type: 'websiteUrl' }, ] as AppFormField[], ['websiteUrl'], ), ).toEqual({ emptyUrl: '', urlKey: 'https://test-site.com', spacedUrl: 'http://test-site.com', }); }); function createDfaField(): any { return [ { id: 'dfaKey', type: 'dynamicFieldArray', fields: [ ...createSimpleFields(), { id: 'dfaKey', type: 'dynamicFieldArray', fields: [...createSimpleFields()], }, { id: 'dfaNullKey', type: 'dynamicFieldArray', fields: [...createSimpleFields()], }, ], }, ]; } function createSimpleData(): SimpleFieldType { return { textKey: ' textValue ', textNullKey: null, richTextKey: '<a> richTextValue </a>', numberKey: 123, numberNullKey: null, }; } function createSimpleFields(): CustomField<SimpleFieldType> { return [ { id: 'numberKey', type: 'number' }, { id: 'numberNullKey', type: 'number' }, { id: 'richTextKey', type: 'richText' }, { id: 'textKey', type: 'text' }, { id: 'textNullKey', type: 'text' }, ]; } });
mukesh-openchannel/angular-template-libraries
src/profile-navbar.stories.ts
<gh_stars>0 import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcProfileNavbarComponent } from '@openchannel/angular-common-components/src/public-api'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; /** List of module dependencies and component declarations. Stored as separate var because they are shared among all stories */ const modules = { imports: [OcCommonLibModule, NgbModule], }; export default { title: 'Profile Navbar [BEM]', component: OcProfileNavbarComponent, decorators: [moduleMetadata(modules)], }; const ProfileNavbarComponent = (args: OcProfileNavbarComponent) => ({ component: OcProfileNavbarComponent, moduleMetadata: modules, props: args, }); export const ProfileWithAllData = ProfileNavbarComponent.bind({}); ProfileWithAllData.args = { initials: 'TU', username: 'Test Username', role: 'admin', }; export const ProfileWithTextOnly = ProfileNavbarComponent.bind({}); ProfileWithTextOnly.args = { username: 'Custom text', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/properties.service.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { toString } from 'lodash'; import { Page } from '../model/api/page.model'; import { OcPropertyModel } from '../model/api/properties.model'; import { HttpHeaders } from '@angular/common/http'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting Page Property.<br> * * Endpoints:<br> * * GET 'v2/properties'<br> */ @Injectable({ providedIn: 'root', }) export class PropertiesService { constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Get list of Properties with pagination * * @param {number} pageNumber - (optional) Current page index. Starts from >= 1 * @param {number} pageLimit - (optional) Count user types into response. Starts from >= 1 * @param {string} sort - (optional) Sort user types by specific field * @param {string} query - (optional) Your specific search query * @param {HttpHeaders} headers (optional) * @returns {Observable<Page<OcPropertyModel>>} `Observable<Page<OcPropertyModel>>` * * ### Example * * `getProperties( "{"name": {"$in":["first", "second"]}}", "{"name": 1}",1,10,{"Authorization":"Bearer as98hd90ahsd98has9d8ha98sd"})` */ getProperties( query?: string, sort?: string, pageNumber?: number, pageLimit?: number, headers?: HttpHeaders, ): Observable<Page<OcPropertyModel>> { const options: any = { params: new OcHttpParams() .append('query', query) .append('sort', sort) .append('pageNumber', toString(pageNumber)) .append('limit', toString(pageLimit)), }; if (headers) { options.headers = headers; } return this.httpRequest.get(this.apiPaths.properties, options); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/directive/only-number.directive.ts
<filename>projects/angular-common-components/src/lib/common-components/directive/only-number.directive.ts import { Directive, HostListener, Input, ElementRef } from '@angular/core'; @Directive({ selector: '[ocOnlyNumber]', }) export class OnlyNumberDirective { @Input() decimalCount: number; private readonly controlKeys: string[] = ['a', 'c', 'v', 'x']; private readonly navigationKeys: string[] = ['Home', 'End', 'ArrowRight', 'ArrowLeft', 'Backspace', '-', '.']; constructor(private el: ElementRef) {} @HostListener('keydown', ['$event']) handleKeyboardEvent(e: KeyboardEvent): void { if (e.key === '.' && this.decimalCount === 0) { e.preventDefault(); } else if ( // Allow: Ctrl(Meta) + (A or C or V or X) (this.controlKeys.includes(e.key) && (e.ctrlKey || e.metaKey)) || // Allow: home, end, left, right etc. this.navigationKeys.includes(e.key) ) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if (e.key === ' ' || isNaN(Number(e.key))) { e.preventDefault(); return; } if (this.decimalCount > 0) { this.processDecimalCount(e); } } processDecimalCount(event: KeyboardEvent): void { const value = this.el.nativeElement.value; if (value) { const decimalPart = value.toString().split('.')[1]; if (decimalPart && decimalPart.length >= this.decimalCount) { event.preventDefault(); } } } }
mukesh-openchannel/angular-template-libraries
src/social-links.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcSocialLinksComponent } from 'projects/angular-common-components/src/lib/common-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'App Social Links [BEM]', component: OcSocialLinksComponent, decorators: [moduleMetadata(modules)], }; const SocialLinksComponent = (args: OcSocialLinksComponent) => ({ component: OcSocialLinksComponent, moduleMetadata: modules, props: args, }); export const componentLinks = SocialLinksComponent.bind({}); componentLinks.args = { socialLinks: [ { link: 'https://facebook.com', iconSrc: './assets/img/edit_icon.svg', iconAlt: 'facebook', }, { link: 'https://twitter.com', iconSrc: './assets/img/close-icon.svg', }, ], };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-initials/oc-initials.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcInitialsComponent } from './oc-initials.component'; import { By } from '@angular/platform-browser'; describe('OcInitialsComponent', () => { let component: OcInitialsComponent; let fixture: ComponentFixture<OcInitialsComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcInitialsComponent], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcInitialsComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('null is safe', () => { component.tempInitialType = null; component.initialsImageURL = null; component.initialsName = null; component.primaryInitialType = null; component.initialsNameCharactersLimit = null; fixture.detectChanges(); }); it('set image', () => { component.initialsImageURL = 'assets/angular-common-components/get-started.svg'; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('#initials-image')) !== null).toBeTruthy(); }); it('set text', () => { component.initialsName = 'Fuel crm gold'; component.initialsNameCharactersLimit = 2; fixture.detectChanges(); const initialComponent = fixture.debugElement.query(By.css('#initials-text')); expect(initialComponent !== null).toBeTruthy(); expect(initialComponent.nativeElement.textContent).toBe('FC'); }); it('set text when image is not found', () => { component.primaryInitialType = 'image'; component.initialsImageURL = null; component.initialsName = 'Fuel crm gold'; component.initialsNameCharactersLimit = 2; fixture.detectChanges(); const initialComponent = fixture.debugElement.query(By.css('#initials-text')); expect(initialComponent !== null).toBeTruthy(); expect(initialComponent.nativeElement.textContent).toBe('FC'); }); it('set image when text is empty', () => { component.primaryInitialType = 'name'; component.initialsImageURL = 'assets/angular-common-components/get-started.svg'; component.initialsName = null; fixture.detectChanges(); expect(fixture.debugElement.query(By.css('#initials-image')) !== null).toBeTruthy(); }); it('set text when all values is empty', () => { fixture.detectChanges(); expect(fixture.debugElement.query(By.css('#initials-text')) !== null).toBeTruthy(); expect(fixture.debugElement.query(By.css('#initials-image')) === null).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-consent/oc-consent.component.spec.ts
<filename>projects/angular-common-components/src/lib/form-components/oc-consent/oc-consent.component.spec.ts<gh_stars>0 import { ComponentFixture, TestBed } from '@angular/core/testing'; import { OcConsentComponent } from './oc-consent.component'; import { MockCheckboxComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { FormsModule } from '@angular/forms'; describe('OcConsentComponent', () => { let component: OcConsentComponent; let fixture: ComponentFixture<OcConsentComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [OcConsentComponent, MockCheckboxComponent], imports: [FormsModule], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OcConsentComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should set a value', () => { component.value = true; expect(component.checked).toEqual(true); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-content-modal/oc-content-modal.component.spec.ts
<filename>projects/angular-common-components/src/lib/common-components/oc-content-modal/oc-content-modal.component.spec.ts import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { AngularSvgIconModule } from 'angular-svg-icon'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { OcContentModalComponent } from './oc-content-modal.component'; import { By } from '@angular/platform-browser'; import { MockButtonComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcContentModalComponent', () => { let component: OcContentModalComponent; let fixture: ComponentFixture<OcContentModalComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcContentModalComponent, MockButtonComponent], imports: [AngularSvgIconModule.forRoot(), HttpClientTestingModule], providers: [NgbActiveModal], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcContentModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have content with scroll', () => { component.hasLongContent = true; fixture.detectChanges(); const modalElement = fixture.debugElement.query(By.css('.content-modal')).nativeElement; expect(modalElement.className).toContain('content-modal_long-content'); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-dynamic-field-array/oc-dynamic-field-array.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcDynamicFieldArrayComponent } from './oc-dynamic-field-array.component'; import { By } from '@angular/platform-browser'; import { FormArray, FormGroup } from '@angular/forms'; import { OcFormGenerator } from '@openchannel/angular-common-components/src/lib/form-components/oc-form/oc-form-generator'; import { MockButtonComponent, MockDynamicArrayPreview, MockFormComponent, MockSvgIconComponent, } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcDynamicFieldArrayComponent', () => { let component: OcDynamicFieldArrayComponent; let fixture: ComponentFixture<OcDynamicFieldArrayComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ OcDynamicFieldArrayComponent, MockButtonComponent, MockSvgIconComponent, MockFormComponent, MockDynamicArrayPreview, ], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcDynamicFieldArrayComponent); component = fixture.componentInstance; component.fieldDefinitionData = { attributes: { maxCount: null, minCount: null, ordering: 'append', required: null, 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', }; component.dfaFormArray = new FormArray([]); }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should add array item and show form', () => { fixture.detectChanges(); const button = fixture.debugElement.query(By.css('.cards-interface__add-btn')).nativeElement; button.click(); fixture.detectChanges(); const arrayItem = fixture.debugElement.queryAll(By.css('.cards-interface__added-item')); const form = fixture.debugElement.query(By.css('oc-form')).nativeElement; expect(component.dfaFormArray.controls.length).toBeGreaterThan(0); expect(component.formsArrayConfig.length).toBeGreaterThan(0); expect(arrayItem.length).toBeGreaterThan(0); expect(form).toBeTruthy(); }); it('should throw error', () => { fixture.detectChanges(); expect(() => (component.fieldDefinitionData = undefined)).toThrowError('FieldDefinitionData is required @Input() parameter'); }); it('should save items value', () => { fixture.detectChanges(); fixture.debugElement.query(By.css('.cards-interface__add-btn')).nativeElement.click(); fixture.detectChanges(); component.dfaFormArray.controls[0].get('field1').setValue('Hello!'); component.dfaFormArray.controls[0].get('long-text-example').setValue('Long text data'); fixture.detectChanges(); fixture.debugElement.query(By.css('.cards-interface__preview-buttons-save')).nativeElement.click(); expect(component.formsArrayConfig[0].formData).toEqual({ field1: 'Hello!', 'long-text-example': 'Long text data', }); }); it('should delete array item', () => { const fields = component.fieldDefinition.fields; component.dfaFormArray = new FormArray([new FormGroup(OcFormGenerator.getFormByConfig(fields))]); fixture.detectChanges(); component.deleteDynamicItem(0); fixture.detectChanges(); expect(component.dfaFormArray.length).toEqual(0); expect(component.formsArrayConfig.length).toEqual(0); }); it('should cancel adding array item', () => { fixture.detectChanges(); fixture.debugElement.query(By.css('.cards-interface__add-btn')).nativeElement.click(); fixture.detectChanges(); fixture.debugElement.query(By.css('.cards-interface__preview-buttons-cancel')).nativeElement.click(); fixture.detectChanges(); expect(component.dfaFormArray.length).toEqual(0); expect(component.formsArrayConfig.length).toEqual(0); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-select/oc-select.component.spec.ts
<gh_stars>0 import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcSelectComponent } from './oc-select.component'; import { NgModel } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { BrowserModule, By } from '@angular/platform-browser'; import { NgbDropdownItem, NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { MockButtonComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { TransformTextPipe } from '@openchannel/angular-common-components/src/lib/common-components'; describe('OcSelectComponent', () => { let component: OcSelectComponent; let fixture: ComponentFixture<OcSelectComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcSelectComponent, MockButtonComponent, TransformTextPipe], providers: [NgModel], imports: [NgbModule, CommonModule, BrowserModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcSelectComponent); component = fixture.componentInstance; fixture.detectChanges(); component.selectValArr = ['item1', 'item2']; }); it('should create', () => { expect(component).toBeTruthy(); }); it('should contain selected value', () => { component.writeValue('item1'); expect(component.selectedValue).toEqual('item1'); }); it('should set selected value', () => { component.value = 'item1'; expect(component.selectedValue).toEqual('item1'); }); it('should contain value in select', async () => { component.writeValue('item1'); const select = fixture.debugElement.query(By.css('.select-component__dropdown')).nativeElement; fixture.detectChanges(); await fixture.whenStable().then(() => { expect(select.textContent).toContain('item1'); }); }); it('input should be disabled', async () => { component.setDisabledState(true); fixture.detectChanges(); const button: MockButtonComponent = fixture.debugElement.query(By.css('oc-button')).componentInstance; await fixture.whenStable().then(() => { expect(button.disabled).toBeTruthy(); }); }); it('should call onChange with value', async () => { const onChangeFunc = jest.fn(); component.registerOnChange(onChangeFunc); fixture.detectChanges(); const button: HTMLSelectElement = fixture.debugElement.query(By.directive(NgbDropdownItem)).nativeElement; button.dispatchEvent(new Event('click')); expect(onChangeFunc).toHaveBeenCalled(); expect(onChangeFunc.mock.calls[0][0]).toBe('item1'); }); it('should call onTouch', async () => { const onTouchedFunc = jest.fn(); component.registerOnTouched(onTouchedFunc); fixture.detectChanges(); const button: HTMLSelectElement = fixture.debugElement.query(By.css('.select-component__action')).nativeElement; button.dispatchEvent(new Event('blur')); expect(onTouchedFunc).toHaveBeenCalled(); }); });
mukesh-openchannel/angular-template-libraries
src/sidebar.stories.ts
<gh_stars>0 import { OcCommonLibModule, OcSidebarComponent } from '@openchannel/angular-common-components/src/lib/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: 'Sidebar [BEM]', component: OcSidebarComponent, decorators: [moduleMetadata(modules)], }; const SidebarComponent = (args: OcSidebarComponent) => ({ component: OcSidebarComponent, moduleMetadata: modules, props: args, }); // tslint:disable-next-line:variable-name export const OneLevel = SidebarComponent.bind({}); OneLevel.args = { title: 'App Category', sidebarModel: [ { label: 'Category 1', checked: false, }, { label: 'Category 2', checked: false, }, { label: 'Category 3', checked: false, expanded: false, values: [ { label: 'Subcategory 1', checked: false, }, { label: 'Subcategory 2', checked: false, }, ], }, { label: 'Category 4', checked: true, }, ], }; // tslint:disable-next-line:variable-name export const WithImages = SidebarComponent.bind({}); WithImages.args = { title: 'App Category', sidebarModel: [ { label: 'Category 1', checked: false, icon: 'assets/angular-common-components/star.svg', }, { label: 'Category 2', checked: false, icon: 'assets/angular-common-components/chart_point.svg', }, { label: 'Category 3', checked: false, expanded: false, icon: 'assets/angular-common-components/star.svg', values: [ { label: 'Subcategory 1', checked: false, icon: 'assets/angular-common-components/star.svg', }, { label: 'Subcategory 2', checked: false, icon: 'assets/angular-common-components/star.svg', }, ], }, { label: 'Category 4', checked: true, icon: 'assets/angular-common-components/star.svg', }, ], }; // tslint:disable-next-line:variable-name export const ManyCategories = SidebarComponent.bind({}); ManyCategories.args = { title: 'App Category', threshold: 8, expandText: 'Show more', collapseText: 'Show less', toggleListButtonType: 'link', sidebarModel: [ { label: 'Category 1', checked: false, }, { label: 'Category 2', checked: false, }, { label: 'Category 3', checked: false, expanded: false, values: [ { label: 'Subcategory 1', checked: false, }, { label: 'Subcategory 2', checked: false, }, ], }, { label: 'Category 4', checked: true, }, { label: 'Category 5', checked: false, }, { label: 'Category 6', checked: false, }, { label: 'Category 7', checked: false, }, { label: 'Category 8', checked: false, }, { label: 'Category 9', checked: false, }, { label: 'Category 10', checked: false, }, { label: 'Category 11', checked: false, }, { label: 'Category 12', checked: false, }, ], };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-progress-bar/oc-progress-bar.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcProgressBarComponent } from './oc-progress-bar.component'; import { FormsModule } from '@angular/forms'; import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcProgressBarComponent', () => { let component: OcProgressBarComponent; let fixture: ComponentFixture<OcProgressBarComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcProgressBarComponent, MockSvgIconComponent], imports: [FormsModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcProgressBarComponent); component = fixture.componentInstance; component.progressbarData = [ { title: 'Step 1', state: 'pristine', }, { title: 'Contact information', state: 'pristine', }, { title: 'Images', state: 'pristine', }, { title: 'Personal Data', state: 'pristine', }, { title: 'Step 5', state: 'pristine', }, ]; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have class equal to the variant', () => { component.currentStep = 3; fixture.detectChanges(); const steps = fixture.nativeElement.querySelectorAll('.form-progressbar__item'); expect(steps[component.currentStep - 1].className.includes('form-progressbar__item_current')).toBe(true); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/developer-account-types.service.ts
<gh_stars>0 import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpRequestService } from './http-request-services'; import { Page } from '../model/api/page.model'; import { DeveloperAccountTypeModel } from '../model/api/user-type.model'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting User Account Type model.<br> * * Endpoints:<br> * * GET 'v2/developerAccountTypes'<br> * * GET 'v2/developerAccountTypes/{type}'<br> */ @Injectable({ providedIn: 'root', }) export class DeveloperAccountTypesService { constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) { } /** * * Description: Get Developer account type data * * @param {string} type * @param {any} httpOptions * @returns {Observable<DeveloperAccountTypeModel>} `Observable<DeveloperAccountTypeModel>` * * ### Example * * `getAccountType('type', {headers: {Authorization: 'Bearer <PASSWORD>'}}});` */ getAccountType(type: string, httpOptions?: any): Observable<DeveloperAccountTypeModel> { return this.httpService.get(`${this.apiPaths.developerAccountTypes}/${type}`, httpOptions); } /** * * Description: Get Developer account types list with pagination * * @param {number} pageNumber - (optional) Current page index. Starts from >= 1. * @param {number} limit - (optional) Count Developer Account Types into response. Starts from >= 1. * @param {string} query - (optional) Your specific search query. * @returns {Observable<Page<DeveloperAccountTypeModel>>} `Observable<Page<DeveloperAccountTypeModel>>` * * ### Example * * `getAllDeveloperAccountsType(1, 10, "{"name": {"$in":["first", "second"]}}");` */ getAllDeveloperAccountsType(pageNumber?: number, limit?: number, query?: string): Observable<Page<DeveloperAccountTypeModel>> { const params = new OcHttpParams().append('pageNumber', String(pageNumber)).append('limit', String(limit)).append('query', query); return this.httpService.get(this.apiPaths.developerAccountTypes, { params }); } }
mukesh-openchannel/angular-template-libraries
src/progress-bar.stories.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>src/progress-bar.stories.ts import { moduleMetadata } from '@storybook/angular'; import { OcFormComponentsModule, OcProgressBarComponent } from '@openchannel/angular-common-components/src/lib/form-components'; const modules = { imports: [OcFormComponentsModule], }; export default { title: 'Progressbar [BEM]', component: OcProgressBarComponent, decorators: [moduleMetadata(modules)], }; const ProgressBarComponent = (args: OcProgressBarComponent) => ({ component: OcProgressBarComponent, moduleMetadata: modules, props: args, }); export const ProgressBarSteps = ProgressBarComponent.bind({}); ProgressBarSteps.args = { progressbarData: [ { title: 'Step 1', state: 'finished', }, { title: 'Contact information', state: 'invalid', }, { title: 'Images', state: 'pristine', }, { title: 'Personal Data', state: 'pristine', }, { title: 'Step 5', state: 'pristine', }, { title: 'Step 6', state: 'pristine', }, { title: 'Step 7', state: 'pristine', }, { title: 'Final data', state: 'pristine', }, ], currentStep: 3, maxStepsToShow: 5, enableTextTruncation: true, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/app-categories/oc-app-categories.module.ts
<gh_stars>0 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CarouselModule } from 'ngx-owl-carousel-o'; import { AngularSvgIconModule } from 'angular-svg-icon'; import { OcAppCategoriesComponent } from './oc-app-categories/oc-app-categories.component'; @NgModule({ declarations: [OcAppCategoriesComponent], imports: [CommonModule, CarouselModule, AngularSvgIconModule.forRoot()], exports: [OcAppCategoriesComponent], }) export class OcAppCategoriesModule {}
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/developer.service.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { DeveloperModel, DeveloperUpdateModel } from '../model/api/developer.model'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting and modifying Developer model.<br> * * Endpoints:<br> * * GET 'v2/developers/this'<br> * * PATCH 'v2/developers/this'<br> */ @Injectable({ providedIn: 'root', }) export class DeveloperService { constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Get Data about developer * * @returns {Observable<DeveloperModel>} `Observable<DeveloperModel>` * * ### Example * * `getDeveloper();` */ getDeveloper(): Observable<DeveloperModel> { return this.httpRequest.get(`${this.apiPaths.developer}/this`); } /** * * Description: Update developer data * * @param {DeveloperUpdateModel} updateDeveloperRequest - (required) Developer model to update * @returns {Observable<DeveloperModel>} `Observable<DeveloperModel>` * * ### Example * * `updateDeveloper({ * email:'<EMAIL>', * name:'Name', * type:'asd', * customData:{} * });` */ updateDeveloper(updateDeveloperRequest: DeveloperUpdateModel): Observable<DeveloperModel> { return this.httpRequest.patch(`${this.apiPaths.developer}/this`, updateDeveloperRequest); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/model/utils.model.ts
export const VIDEO_URL_REGEX = () => new RegExp(/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm);
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-sidebar/oc-sidebar.component.ts
<reponame>mukesh-openchannel/angular-template-libraries import { AfterViewInit, ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, Output, SimpleChanges, ViewChild } from '@angular/core'; import { OcSidebarSelectModel } from '../model/oc-sidebar-model'; import { SidebarValue } from '../model/components-basic.model'; import { HeadingTag } from '../model/heading-tag.interface'; /** * Sidebar component. It is used as a tool for quick search of applications. * Component represents a block with an unordered list of links, * which set filters to the search apps request. * * @example * <oc-sidebar baseNavigation="browse" * [title]="sidebar.name" * [sidebarModel]="sidebar.values" * [threshold]="12" * toggleListButtonType="button"></oc-sidebar> */ @Component({ selector: 'oc-sidebar', templateUrl: './oc-sidebar.component.html', styleUrls: ['./oc-sidebar.component.css'], }) export class OcSidebarComponent implements AfterViewInit, OnChanges { /** * Title of the sidebar. * @type {string}. * Default empty. */ @Input() title: string; /** * Heading tag of [title]{@link title} * @type {HeadingTag}. */ @Input() titleHeadingTag: HeadingTag = 'h2'; /** * Sidebar config, contains array of sidebar list items. * @type {SidebarValue[]}. */ @Input() set sidebarModel(model: SidebarValue[]) { this.mainSidebarModel = [...model]; this.updateThreshold(); } /** * Path to the custom toggle icon down. * @type {string}. * Default 'assets/angular-common-components/down-arrow.svg'. */ @Input() toggleIconDown: string = 'assets/angular-common-components/down-arrow.svg'; /** * Path to the custom toggle icon up. * @type {string}. * Default 'assets/angular-common-components/select-up.svg'. */ @Input() toggleIconUp: string = 'assets/angular-common-components/select-up.svg'; /** * Base url for the Router links in the sidebar component. * @type {string}. * Default empty. * @example * // returns '/browse/collections/allApps'. */ @Input() baseNavigation: string; /** * The limit for the shown items. They will be shown always, * the rest will be hidden until the user clicked a toggle button. * If a threshold value is bigger than the length of items - the toggle button will be not shown. * Default value: 10. * @default 10 */ @Input() threshold: number = 10; /** * Text that will be shown on the toggle button when the rest of the items are collapsed. */ @Input() expandText: string = 'Show more'; /** * Text that will be shown on the toggle button when the rest of the items are expanded. */ @Input() collapseText: string = 'Show less'; /** * Type of the toggle button. Can be `button` or `link`. * `link` type will be shown by default. * @type {'button' | 'link'}. */ @Input() toggleListButtonType: 'primary' | 'link' = 'link'; /** * Emits sidebar model changes and passes to the parent component. */ @Output() readonly sidebarChange: EventEmitter<OcSidebarSelectModel> = new EventEmitter<OcSidebarSelectModel>(); /** * @ignore * Collapsing list. Necessary for the collapse animation. */ @ViewChild('collapsingList', { static: false }) collapsingList; /** * @ignore * All items of the sidebar */ mainSidebarModel: SidebarValue[]; /** * @ignore * Always showed list of the sidebar items. */ showedSidebarModel: SidebarValue[]; /** * @ignore * List of the sidebar items that can be collapsed. */ hiddenSidebarModel: SidebarValue[] = []; /** * The flag that controls the showed status of the rest of the items. */ collapseList: boolean = false; /** * A height of the collapsing list. That need for the smooth transition animation. */ listHeight: number; constructor(private cdRef: ChangeDetectorRef) {} ngOnChanges(changes: SimpleChanges): void { if (changes.threshold && changes.threshold.previousValue !== changes.threshold.currentValue) { this.updateThreshold(); } } ngAfterViewInit(): void { if (this.hiddenSidebarModel.length > 0) { this.listHeight = this.collapsingList.nativeElement.offsetHeight; this.collapseList = true; this.cdRef.detectChanges(); } } /** * This method runs by click on the sidebar list item. * Checks for the sidebar changes. * Emits parent sidebar model and child sidebar model. */ onClickSidebar(parentSidebar: SidebarValue, childSidebar?: SidebarValue): void { if (parentSidebar.values?.length > 0 && !childSidebar) { parentSidebar.expanded = !parentSidebar.expanded; } else { this.sidebarChange.emit({ parent: parentSidebar, child: childSidebar }); } } /** * Updating lists on threshold value changes. */ updateThreshold(): void { this.showedSidebarModel = [...this.mainSidebarModel]; // tslint:disable-next-line:prefer-conditional-expression if (this.threshold && this.threshold < this.mainSidebarModel.length - 1) { this.hiddenSidebarModel = [...this.showedSidebarModel.splice(this.threshold, this.showedSidebarModel.length - 1)]; } else { this.hiddenSidebarModel = []; } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-social-links/oc-social-links.component.spec.ts
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { OcSocialLinksComponent } from './oc-social-links.component'; import { RouterTestingModule } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; describe('OcSocialLinksComponent', () => { let component: OcSocialLinksComponent; let fixture: ComponentFixture<OcSocialLinksComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcSocialLinksComponent], imports: [RouterTestingModule.withRoutes([])], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcSocialLinksComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should receive passed data', () => { component.socialLinks = [ { link: 'https://facebook.com', iconSrc: 'assets/img/facebook-icon.svg', iconAlt: 'facebook-icon', }, { link: 'https://twitter.com', iconSrc: 'assets/img/twitter-icon.svg', iconAlt: 'twitter-icon', }, ]; fixture.detectChanges(); expect(fixture.debugElement.queryAll(By.css('.social-links__item')).length).toBe(component.socialLinks.length); }); });
mukesh-openchannel/angular-template-libraries
src/date-time.stories.ts
import { OcDatetimePickerComponent, OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components'; import { moduleMetadata } from '@storybook/angular'; const modules = { imports: [OcFormComponentsModule], }; export default { title: 'Date component [BEM]', component: OcDatetimePickerComponent, decorators: [moduleMetadata(modules)], }; const DateTimeComponent = (args: OcDatetimePickerComponent) => ({ component: OcDatetimePickerComponent, moduleMetadata: modules, props: args, }); export const DisabledDate = DateTimeComponent.bind({}); DisabledDate.args = { disabled: true, }; export const DefaultDate = DateTimeComponent.bind({}); DefaultDate.args = { value: new Date().valueOf(), type: 'date', settings: { format: 'dd/MM/yyyy', }, disabled: false, }; export const DefaultDateTime = DateTimeComponent.bind({}); DefaultDateTime.args = { value: new Date().valueOf(), type: 'datetime', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-form-modal/oc-form-modal.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries<gh_stars>0 import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcFormModalComponent } from './oc-form-modal.component'; import { By } from '@angular/platform-browser'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { MockFormComponent, MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcFormModalComponent', () => { let component: OcFormModalComponent; let fixture: ComponentFixture<OcFormModalComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcFormModalComponent, MockFormComponent, MockSvgIconComponent], providers: [NgbActiveModal], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcFormModalComponent); component = fixture.componentInstance; component.formJsonData = { formId: 'test', name: 'test', createdDate: 1599982592157, fields: [ { id: 'name', label: 'name', description: 'test', defaultValue: null, type: 'text', required: null, attributes: { maxChars: 20, required: true, minChars: 10, }, options: null, }, { id: 'role', label: 'role', description: '', defaultValue: 'user', type: 'dropdownList', required: null, attributes: { required: true }, options: ['admin', 'user', 'test'], }, { id: 'aboutme', label: 'aboutme', description: '', defaultValue: null, type: 'richText', required: null, attributes: { maxChars: 150, required: null, minChars: 10, }, options: null, }, { id: 'skills', label: 'skills', description: 'skills', defaultValue: ['angular'], type: 'tags', required: null, attributes: { minCount: 1, maxCount: 5, required: true, }, options: null, }, ], }; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should show form', () => { fixture.detectChanges(); const formComponent = fixture.debugElement.query(By.css('oc-form')); expect(formComponent).toBeTruthy(); }); it('should catch form data', () => { fixture.detectChanges(); const formComponent: MockFormComponent = fixture.debugElement.query(By.css('oc-form')).componentInstance; formComponent.submitForm(); expect(component.formJsonData).toBeTruthy(); }); it('should close the modal', () => { jest.spyOn(component, 'dismiss'); fixture.detectChanges(); const closeBtn = fixture.debugElement.query(By.css('.form-modal__header-close-icon')).nativeElement; closeBtn.click(); expect(component.dismiss).toHaveBeenCalled(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/model/dynamic-array.model.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>projects/angular-common-components/src/lib/form-components/model/dynamic-array.model.ts import { AppTypeFieldModel } from '@openchannel/angular-common-components/src/lib/common-components'; import { FormArray } from '@angular/forms'; export interface FieldValueModel { fieldId: string; fieldValue: any; } export interface PreviewFieldModel extends AppTypeFieldModel { isValidField: boolean; fieldValue: any; formArrayDFA: FormArray; } export interface FormArrayItem { new: boolean; isEdit: boolean; formData: any; previewLabel: PreviewLabel; previewFiledValues: FieldValueModel[]; previewCollapsedDFAFields: boolean; } export interface PreviewLabel { defaultLabel: string; customLabelValue?: FieldValueModel[]; customLabelDefinition?: AppTypeFieldModel; isCollapsedPreviewFields?: boolean; } export interface FieldValueModel { fieldId: string; fieldValue: any; }
mukesh-openchannel/angular-template-libraries
src/app-description.stories.ts
<filename>src/app-description.stories.ts import { OcAppDescriptionComponent, OcCommonLibModule } 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: 'App Description Component [BEM]', component: OcAppDescriptionComponent, decorators: [moduleMetadata(modules)], argTypes: { getEditorContent: { action: 'Editor data' } }, }; const AppDescriptionComponent = (args: OcAppDescriptionComponent) => ({ component: OcAppDescriptionComponent, moduleMetadata: modules, props: args, }); const descriptionText = '<p> Nulla ut cursus mi. Nullam mi lacus, porttitor a sapien quis, scelerisque vestibulum massa.' + '<br> Phasellus tincidunt est eget fermentum dictum. Morbi consequat sed risus a maximus. ' + '<br>Proin aliquam libero eget tellus pharetra posuere. Praesent accumsan ipsum quam.' + ' <br> Suspendisse potenti. Maecenas id posuere dui, in semper urna. Sed mattis nec mauris eget tristique.' + ' <br>Phasellus id nulla id dolor sagittis placerat.' + ' <br>Aliquam posuere, magna sit amet vehicula posuere, elit purus facilisis elit, in lacinia enim diam consequat felis.' + ' <br>Nullam scelerisque in elit vitae feugiat. Nunc mattis eros leo, at finibus lacus ornare nec. Nulla facilisi.</p>'; export const ExpandableDescription = AppDescriptionComponent.bind({}); ExpandableDescription.args = { appDescription: descriptionText, header: 'About App', truncateTextLength: 250, }; export const FullDescription = AppDescriptionComponent.bind({}); FullDescription.args = { appDescription: descriptionText, header: 'About App', truncateTextLength: 250, showFullDescription: true, }; export const ShortDescription = AppDescriptionComponent.bind({}); ShortDescription.args = { appDescription: '<p> Nulla ut cursus mi. Nullam mi lacus, porttitor a sapien quis, scelerisque vestibulum massa.' + '<br> Phasellus tincidunt est eget fermentum dictum. Morbi consequat sed risus a maximus. ' + '<br>Proin aliquam libero eget tellus pharetra posuere. </p>', header: 'About App', };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/public-api.ts
<gh_stars>0 export * from './oc-app-card/oc-app-card.component'; export * from './oc-app-description/oc-app-description.component'; export * from './oc-app-gallery/oc-app-gallery.component'; export * from './oc-app-get-started/oc-app-get-started.component'; export * from './oc-app-list-grid/oc-app-list-grid.component'; export * from './oc-app-short-info/oc-app-short-info.component'; export * from './oc-featured-apps/oc-featured-apps.component'; export * from './oc-image-gallery/oc-image-gallery.component'; export * from './oc-overall-rating/oc-overall-rating.component'; export * from './oc-rating/oc-rating.component'; export * from './oc-recommended-apps/oc-recommended-apps.component'; export * from './oc-review-list/oc-review-list.component'; export * from './oc-text-search/oc-text-search.component'; export * from './oc-review/oc-review.component'; export * from './oc-market-components.module'; /** Models */ export * from './models/oc-review-details-model'; export * from './models/overall-rating-summary-model';
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/models/auth-types.model.ts
/** * Model for the [user activation]{@link OcActivationComponent} form. * * Interface includes * ``` typescript * { * password: string; * email: string; * code: string; * } * ``` */ export class ComponentsUserActivationModel { /** password data field */ password: string; /** email data field */ email: string; /** activation code from the email */ code: string; } /** * Interface for the [Reset Password]{@link OcResetPasswordComponent} form. * * Interface includes * ``` typescript * { * newPassword: string; * code: string; * } * ``` */ export class ComponentsUserResetPassword { /** new password data */ newPassword: string; /** activation code from the email */ code: string; } /** * Interface for the [Login Component]{@link OcLoginComponent} * * Interface includes * ``` typescript * { * password: string; * email: string; * isChecked: boolean; * } * ``` */ export class ComponentsUserLoginModel { /** email data field */ email: string; /** password data field */ password: string; /** status of the `remember me` field */ isChecked: boolean; } /** * Interface for the [Sign Up component]{@link OcSignupComponent}. * * Interface includes * ``` typescript * { * uname: string; * company: string; * password: string; * email: string; * isChecked: boolean; * } * ``` */ export class ComponentsUserRegistrationModel { /** field for the username data */ uname: string; /** field for the company data */ company: string; /** field for the password data */ password: string; /** field for the email data */ email: string; /** status of the agree with terms field */ isChecked: boolean; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/oc-edit-user-form/oc-edit-user-form.component.spec.ts
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { OcEditUserFormComponent } from './oc-edit-user-form.component'; import { MockCheckboxComponent, MockErrorComponent, MockFormComponent, MockPasswordComponent, MockSelectComponent, MockTooltipComponent, } from '@openchannel/angular-common-components/src/mock/mock'; import { FormGroup, FormsModule, NgModel, ReactiveFormsModule } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { BrowserModule, By } from '@angular/platform-browser'; import { OcFormGenerator } from '@openchannel/angular-common-components/src/lib/form-components'; import { OcEditUserFormConfig } from '../models/oc-edit-user-form.model'; const firstForm: OcEditUserFormConfig = { name: '<NAME>', account: { includeFields: ['name', 'email'], typeData: { 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', }, ], }, type: 'first-account-form', }, organization: { includeFields: ['customData.organization'], typeData: { fields: [ { id: 'customData.company', type: 'text', label: 'Company', attributes: { required: true, }, }, { id: 'customData.country', type: 'text', label: 'Country', attributes: { required: true, }, }, ], }, type: 'first-organization-form', }, fieldsOrder: ['email', 'name'], }; const secondForm: OcEditUserFormConfig = { name: '<NAME>', account: { includeFields: ['name', 'email', 'about-me'], typeData: { 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', }, ], }, type: 'second-account-form', }, organization: { includeFields: ['customData.organization', 'customData.country'], typeData: { fields: [ { id: 'customData.company', type: 'text', label: 'Company', attributes: { required: true, }, }, { id: 'customData.country', type: 'text', label: 'Country', attributes: { required: true, }, }, ], }, type: 'second-organization-form', }, }; describe('OcEditUserFormComponent', () => { let component: OcEditUserFormComponent; let fixture: ComponentFixture<OcEditUserFormComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ OcEditUserFormComponent, MockErrorComponent, MockPasswordComponent, MockCheckboxComponent, MockFormComponent, MockSelectComponent, MockTooltipComponent, ], providers: [NgModel], imports: [FormsModule, CommonModule, ReactiveFormsModule, BrowserModule], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OcEditUserFormComponent); component = fixture.componentInstance; component.formConfigs = [firstForm, secondForm]; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should change form type', () => { component.enableTypesDropdown = true; fixture.detectChanges(); component.buildFormByConfig(secondForm); fixture.detectChanges(); expect(component.currentFormConfig).toEqual(secondForm); }); it('should show terms checkbox', fakeAsync(() => { fixture.detectChanges(); component.enableTermsCheckbox = { termsUrl: 'http://terms', policyUrl: 'http://policy', }; component.setFormGroup(new FormGroup(OcFormGenerator.getFormByConfig(firstForm.account.typeData.fields))); fixture.detectChanges(); tick(1000); const checkbox = fixture.debugElement.query(By.css('.edit-user-form__consent-checkbox')); const termsText = fixture.debugElement.query(By.css('.edit-user-form__consent__label')); expect(checkbox).toBeTruthy(); expect(termsText).toBeTruthy(); })); it('should show error message when no config provided', () => { component.formConfigs = []; fixture.detectChanges(); const errorMessageBlock = fixture.debugElement.query(By.css('.edit-user-form__empty_form_configs')); expect(errorMessageBlock).toBeTruthy(); expect(errorMessageBlock.nativeElement.textContent).toEqual('There are no forms configured'); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/oc-auth-components.module.ts
<reponame>mukesh-openchannel/angular-template-libraries import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { OcActivationComponent } from './oc-activation/oc-activation.component'; import { OcResendActivationComponent } from './oc-resend-activation/oc-resend-activation.component'; import { OcResetPasswordComponent } from './oc-reset-password/oc-reset-password.component'; import { OcForgotPasswordComponent } from './oc-forgot-password/oc-forgot-password.component'; import { OcSignupComponent } from './oc-signup/oc-signup.component'; import { OcLoginComponent } from './oc-login/oc-login.component'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { OcEditUserFormComponent } from './oc-edit-user-form/oc-edit-user-form.component'; import { OcSignupCustomComponent } from './oc-signup-custom/oc-signup-custom.component'; import { OcFormComponentsModule } from '@openchannel/angular-common-components/src/lib/form-components'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ declarations: [ OcActivationComponent, OcResendActivationComponent, OcResetPasswordComponent, OcSignupComponent, OcLoginComponent, OcForgotPasswordComponent, OcSignupCustomComponent, OcEditUserFormComponent, ], imports: [CommonModule, FormsModule, RouterModule, OcCommonLibModule, OcFormComponentsModule, ReactiveFormsModule, NgbModule], exports: [ OcActivationComponent, OcResendActivationComponent, OcResetPasswordComponent, OcSignupComponent, OcLoginComponent, OcForgotPasswordComponent, OcSignupCustomComponent, OcEditUserFormComponent, ], }) export class OcAuthComponentsModule {}
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/apps-version.service.ts
import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { Page } from '../model/api/page.model'; import { AppVersionResponse, UpdateAppVersionModel } from '../model/api/app-data-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 apps by version.<br> * Documentation: <a href="https://support.openchannel.io/documentation/api/#531-apps">Openchannel API</a><br> * Endpoints:<br> * GET '/v2/apps/{appId}/versions/textSearch'<br> * GET '/v2/apps/{appId}/versions'<br> * GET '/v2/apps/{appId}/versions/{version}'<br> * POST '/v2/apps/{appId}/versions/{version}'<br> * DELETE '/v2/apps/{appId}/versions/{version}'<br> */ @Injectable({ providedIn: 'root', }) export class AppVersionService { constructor(private httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * Description: You can search for apps by specifying the text that you want to search for as well as a list of fields that you want to include in the search. * * @param pageNumber - (optional) Current page index. Starts from >= 1. * @param limit - (optional) Count apps into response. Starts from >= 1. * @param sort - (optional) Sort apps by specific field. * Documentation <a href="https://support.openchannel.io/documentation/api/#381-sort-document">Openchannel API</a> * @param query - (optional) Your specific search query. * Documentation <a href="https://support.openchannel.io/documentation/api/#380-query-document">Openchannel API</a> * @param searchText - (required) Text for searching. * @param searchTextByFields - (required) Fields for searching. * @return Observable<Page<AppVersionResponse>> * * ### Example: * `` * getAppsVersionsBySearchText(1, 10, "{"name": 1}", "{"name": {"$in":["first", "second"]}}", "AppName", ["name"]) * `` */ getAppsVersionsBySearchText( pageNumber: number, limit: number, sort: string, query: string, searchText: string, searchTextByFields: string[], ): Observable<Page<AppVersionResponse>> { const mainUrl = `${this.apiPaths.appsVersions}/versions/textSearch`; const params = new OcHttpParams() .append('pageNumber', String(pageNumber)) .append('limit', String(limit)) .append('sort', sort) .append('query', query) .append('fields', JSON.stringify(searchTextByFields)) .appendRequiredParam('searchText', searchText, ''); return this.httpRequest.get(mainUrl, { params }); } /** * Description: Listing app versions returns App Pages based on query and sort criteria. * * Documentation: <a href="https://support.openchannel.io/documentation/api/#411-apps-list-app-versions">Openchannel API</a> * * @param pageNumber - (optional) Current page index. Starts from >= 1. * @param limit - (optional) Count apps into response. Starts from >= 1. * @param sort - (optional) Sort apps by specific field. * Documentation <a href="https://support.openchannel.io/documentation/api/#381-sort-document">Openchannel API</a> * @param query - (optional) Your specific search query. * Documentation <a href="https://support.openchannel.io/documentation/api/#380-query-document">Openchannel API</a> * @return Observable<Page<AppVersionResponse>> * * ### Example: * `` * getAppsVersions(1, 10, null, null); * `` */ getAppsVersions(pageNumber: number, limit: number, sort: any, query: string): Observable<Page<AppVersionResponse>> { const mainUrl = `${this.apiPaths.appsVersions}/versions`; const params = new OcHttpParams() .append('pageNumber', String(pageNumber)) .append('limit', String(limit)) .append('sort', sort) .append('query', query); return this.httpRequest.get(mainUrl, { params }); } /** * Description: Retrieving an app version returns a single, specific version of an app. * * Documentation: <a href="https://support.openchannel.io/documentation/api/#413-apps-get-an-app-version">Openchannel API</a> * * @param appId (required) * @param version (required) Starts from >= 1. * @return Observable<AppVersionResponse> * * ### Example: * `` * getAppByVersion("6238426d0c0osf654208", 1); * `` */ getAppByVersion(appId: string, version: number): Observable<AppVersionResponse> { const mainUrl = `${this.apiPaths.appsVersions}/${appId}/versions/${version}`; return this.httpRequest.get(mainUrl); } /** * Description: Update app by version but the update may create a new app version * that cannot be viewed by a marketplace administrator until the developer publishes the new app version. * * Documentation: <a href="https://support.openchannel.io/documentation/api/#408-apps-update-app">Openchannel API</a> * * @param appId (required) * @param version (required) Starts from >= 1. * @return Observable<AppVersionResponse> * * ### Example: * `` * updateAppByVersion("6238426d0c0osf654208", 1, {"name": "New app name"}) * `` */ updateAppByVersion(appId: string, version: number, updateAppVersionModel: UpdateAppVersionModel): Observable<AppVersionResponse> { const mainUrl = `${this.apiPaths.appsVersions}/${appId}/versions/${version}`; return this.httpRequest.post(mainUrl, updateAppVersionModel); } /** * Description: Deleting an app version permanently removes that version. * * Documentation: <a href="https://support.openchannel.io/documentation/api/#410-apps-delete-app-version">Openchannel API</a> * @param appId (required) * @param version (required) Starts from >= 1. * @return Empty response {}; * * ### Example: * `` * deleteAppVersion("6238426d0c0osf654208", 1); * `` */ deleteAppVersion(appId: string, version: number): Observable<any> { const mainUrl = `${this.apiPaths.appsVersions}/${appId}/versions/${version}`; return this.httpRequest.delete(mainUrl); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/request.model.ts
export interface RequestModel { name: string; type: string; appId?: string; userId?: string; userAccountId?: string; developerId?: string; developerAccountId?: string; customData?: any; } export interface RequestModelResponse extends RequestModel { requestId: string; createdDate: number; archived: boolean; archivedDate?: number; status: RequestStatus; } export type RequestStatusValue = 'draft' | 'approved' | 'rejected' | 'pending' | 'inReview'; export interface RequestStatus { value: RequestStatusValue; reason?: string; } export interface RequestStatusModel { status: RequestStatusValue; reason?: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/xsrf/xsrf.ts
import { Inject, Injectable, InjectionToken, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { BroadcastChannel } from 'broadcast-channel'; import { API_URL } from '../oc-ng-common-service.module'; export const XSRF_HEADER_NAME = new InjectionToken<string>('XSRF_HEADER_NAME'); export const channel = new BroadcastChannel('openchannel-csrf-sync'); /** * `HttpXsrfTokenExtractor` which retrieves the token from a cookie. */ @Injectable() export class HttpXsrfExtractor implements HttpInterceptor { constructor(@Inject(XSRF_HEADER_NAME) private headerName: string, private memoryStorage: MemoryStorageService) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( map(event => { if (event instanceof HttpResponse) { const xsrfToken = event.headers.get(this.headerName); if (xsrfToken) { this.memoryStorage.setXsrfToken(xsrfToken); } } return event; }), ); } } /** * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests. */ @Injectable() export class HttpXsrfInterceptor implements HttpInterceptor { constructor( private memoryStorageService: MemoryStorageService, @Inject(XSRF_HEADER_NAME) private headerName: string, @Inject(API_URL) private apiUrl: string, ) {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = this.memoryStorageService.getXsrfToken(); // Be careful not to overwrite an existing header of the same name. if (!this.apiUrl || req.url.startsWith(this.apiUrl)) { if (token && !req.headers.has(this.headerName)) { req = req.clone({ headers: req.headers.set(this.headerName, token) }); } } return next.handle(req); } } @Injectable({ providedIn: 'root', }) export class MemoryStorageService implements OnDestroy { private xsrfToken: string; constructor() { channel.onmessage = msg => { this.xsrfToken = msg.data; }; } ngOnDestroy(): void { channel.close(); } getXsrfToken(): string { return this.xsrfToken; } setXsrfToken(xsrfToken: string): void { channel.postMessage(xsrfToken); this.xsrfToken = xsrfToken; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/management-components/oc-invite-modal/oc-invite-modal.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries<filename>projects/angular-common-components/src/lib/management-components/oc-invite-modal/oc-invite-modal.component.spec.ts import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { OcInviteModalComponent } from './oc-invite-modal.component'; import { MockButtonComponent, MockFormComponent, MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { Observable, of, throwError } from 'rxjs'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ComponentsPage } from '@openchannel/angular-common-components/src/lib/common-components'; import { ComponentsUserAccount, DeveloperRole, UserRole } from '../models/user-data.model'; import { ComponentsDeveloperAccountModel, ModalInviteUserModel, ModalUpdateUserModel } from '../models/oc-modal.model'; import { By } from '@angular/platform-browser'; import { cloneDeep } from 'lodash'; describe('OcInviteModalComponent', () => { let component: OcInviteModalComponent; let fixture: ComponentFixture<OcInviteModalComponent>; const mockFormGroupValid = { valid: true, markAllAsTouched: () => {}, }; const mockFormGroupInvalid = { valid: false, markAllAsTouched: () => {}, }; const mockFormData = { name: '<NAME>', roles: 'admin', aboutme: '', skills: ['angular'], }; const mockRoleFields = { created: 0, lastUpdated: 0, systemDefined: false, }; const mockResponseData: ComponentsPage<DeveloperRole | UserRole> = { count: 0, list: [ { userRoleId: 'user-role-id', name: 'first', ...mockRoleFields, }, { developerRoleId: 'dev-role-id', name: 'second', ...mockRoleFields, }, ], pageNumber: 0, pages: 0, }; const mockUserData: ComponentsUserAccount = { created: 0, userId: '', name: 'User', email: '<EMAIL>', customData: null, roles: [], permissions: null, userAccountId: 'user-account-id', }; const mockDeveloperData: ComponentsDeveloperAccountModel = { email: '<EMAIL>', name: 'Developer', roles: [], developerAccountId: 'dev-account-id', }; const mockRequestFindUserRoles = (): Observable<ComponentsPage<DeveloperRole | UserRole>> => of(mockResponseData); class ModalInviteUserModelStub extends ModalInviteUserModel { requestFindUserRoles = mockRequestFindUserRoles; requestSendInvite = (): Observable<any> => of({}); } class ModalUpdateUserModelStub extends ModalUpdateUserModel { requestFindUserRoles = mockRequestFindUserRoles; requestUpdateAccount = (): Observable<any> => of({}); } const updateUserModel = new ModalUpdateUserModelStub(); updateUserModel.userData = mockUserData; const updateDeveloperModel = new ModalUpdateUserModelStub(); updateDeveloperModel.userData = mockDeveloperData; const inviteUserModel = new ModalInviteUserModelStub(); const errorFunction = () => throwError('Error'); const successFunction = of; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcInviteModalComponent, MockButtonComponent, MockSvgIconComponent, MockFormComponent], providers: [NgbActiveModal], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcInviteModalComponent); component = fixture.componentInstance; component.modalData = cloneDeep(updateUserModel); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should set form config fields in makeFormConfig function', () => { component.makeFormConfig(); expect(component.formConfig.fields.length).not.toBe(0); }); it('should set form config default values in makeFormConfig function, if modal data contains update user data model', () => { component.modalData = updateUserModel; component.makeFormConfig(); component.formConfig.fields.forEach(field => { if (component.modalData instanceof ModalUpdateUserModel) { expect(field.defaultValue).toBe(component.modalData.userData[field.id]); } }); }); it('should dismiss modal, when requestFindUserRoles throws error', () => { jest.spyOn(component, 'dismiss'); component.modalData.requestFindUserRoles = errorFunction; component.setUserRolesToForm(); expect(component.dismiss).toHaveBeenCalled(); }); it('should dismiss modal, when requestFindUserRoles succeed', () => { jest.spyOn(component, 'dismiss'); component.modalData.requestFindUserRoles = () => of({ ...mockResponseData, list: [] }); component.setUserRolesToForm(); expect(component.dismiss).toHaveBeenCalled(); }); it('should dismiss modal, by corresponding button click', () => { jest.spyOn(component, 'dismiss'); const dismissButtonDE = fixture.debugElement.query(By.css('.invite-modal__dismiss-button')); dismissButtonDE.triggerEventHandler('click', {}); expect(component.dismiss).toHaveBeenCalled(); }); it('should dismiss modal, by close modal button click', () => { jest.spyOn(component, 'dismiss'); const closeButtonDE = fixture.debugElement.query(By.css('.invite-modal__header-close-icon')); closeButtonDE.triggerEventHandler('click', {}); expect(component.dismiss).toHaveBeenCalled(); }); it('should set data to template from modalData', () => { const testTitle = 'Test title'; const successText = 'Success text'; component.modalData.modalTitle = testTitle; component.modalData.successButtonText = successText; fixture.detectChanges(); const heading = fixture.debugElement.query(By.css('.invite-modal__header-heading')).nativeElement; expect(heading.textContent).toBe(testTitle); const confirmButton = fixture.debugElement.query(By.css('.invite-modal__confirm-button')).componentInstance; expect(confirmButton.text).toBe(successText); }); it('should fill formConfig and listRoles, when requestFindUserRoles returns list of roles', () => { const roleNames = mockResponseData.list.map(role => role.name); component.modalData = inviteUserModel; fixture.detectChanges(); component.setUserRolesToForm(); const listRoles = (component as any).listRoles; Object.entries(listRoles).forEach(([name, id]) => { const roleItem = mockResponseData.list.find(role => role.name === name); expect(roleItem).toBeTruthy(); const roleId = 'developerRoleId' in roleItem ? roleItem.developerRoleId : roleItem.userRoleId; expect(roleId).toBe(id); }); const formConfigRole = component.formConfig.fields.find(field => field.id === 'roles'); expect(formConfigRole.options).toEqual(roleNames); expect(formConfigRole.defaultValue).toEqual(roleNames[0]); }); it('should set formGroup when oc-form emits createdForm event', () => { component.formGroup = null; const formDE = fixture.debugElement.query(By.directive(MockFormComponent)); formDE.triggerEventHandler('createdForm', {}); expect(component.formGroup).toBeTruthy(); }); it('should set formData when oc-form emits formDataUpdated event', () => { component.formData = null; const formDE = fixture.debugElement.query(By.directive(MockFormComponent)); formDE.triggerEventHandler('formDataUpdated', {}); expect(component.formData).toBeTruthy(); }); it('should set inProcess to true, if confirm button was clicked', () => { expect(component.inProcess).toBeFalsy(); component.modalData = updateUserModel; (component as any).updateUser = jest.fn(); (component.formGroup as any) = cloneDeep(mockFormGroupValid); component.formData = cloneDeep(mockFormData); const confirmButtonDE = fixture.debugElement.query(By.css('.invite-modal__confirm-button')); confirmButtonDE.triggerEventHandler('click', {}); expect(component.inProcess).toBeTruthy(); }); it('should invoke requestUpdateAccount or requestSendInvite, when confirm method invoked', () => { component.modalData = updateUserModel; (component.formGroup as any) = cloneDeep(mockFormGroupValid); component.formData = cloneDeep(mockFormData); jest.spyOn(component.modalData, 'requestUpdateAccount'); component.onClickConfirmButton(); expect(component.modalData.requestUpdateAccount).toHaveBeenCalled(); component.modalData = inviteUserModel; jest.spyOn(component.modalData, 'requestSendInvite'); component.onClickConfirmButton(); expect(component.modalData.requestSendInvite).toHaveBeenCalled(); }); it('should not send user model, if formGroup is not valid', () => { component.modalData = updateUserModel; component.inProcess = false; (component.formGroup as any) = cloneDeep(mockFormGroupInvalid); component.formData = cloneDeep(mockFormData); const updateUserFunction = jest.spyOn(component as any, 'updateUser'); component.onClickConfirmButton(); expect(updateUserFunction).not.toHaveBeenCalled(); }); it('should not send user model, if formData is absent', () => { component.modalData = updateUserModel; component.inProcess = false; (component.formGroup as any) = cloneDeep(mockFormGroupValid); component.formData = null; const updateUserFunction = jest.spyOn(component as any, 'updateUser'); component.onClickConfirmButton(); expect(updateUserFunction).not.toHaveBeenCalled(); }); it('should not send user model, if inProcess is true', () => { component.modalData = updateUserModel; component.inProcess = true; (component.formGroup as any) = cloneDeep(mockFormGroupValid); component.formData = cloneDeep(mockFormData); const updateUserFunction = jest.spyOn(component as any, 'updateUser'); component.onClickConfirmButton(); expect(updateUserFunction).not.toHaveBeenCalled(); }); it('should close modal, when requestUpdateAccount or requestSendInvite completed successfully', fakeAsync(() => { const modalClose = jest.spyOn((component as any).modal, 'close'); (component as any).updateUser(updateUserModel); tick(); expect(modalClose).toHaveBeenCalledWith(true); modalClose.mockClear(); (component as any).inviteUser(inviteUserModel); tick(); expect(modalClose).toHaveBeenCalledWith(true); })); it('should set inProcess to false, when requestUpdateAccount or requestSendInvite completed', fakeAsync(() => { const testAsyncFunc = asyncFunction => { component.inProcess = true; asyncFunction(); tick(); expect(component.inProcess).toBeFalsy(); }; testAsyncFunc((component as any).updateUser.bind(component, { ...updateUserModel, requestUpdateAccount: successFunction })); testAsyncFunc((component as any).updateUser.bind(component, { ...updateUserModel, requestUpdateAccount: errorFunction })); testAsyncFunc((component as any).inviteUser.bind(component, { ...inviteUserModel, requestSendInvite: successFunction })); testAsyncFunc((component as any).inviteUser.bind(component, { ...inviteUserModel, requestSendInvite: errorFunction })); })); it('getAccountId should return correct account id or null', () => { const getAccountId = (component as any).getAccountId.bind(component); expect(getAccountId(mockUserData)).toBe(mockUserData.userAccountId); expect(getAccountId(mockDeveloperData)).toBe(mockDeveloperData.developerAccountId); expect(getAccountId({})).toBeNull(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/request.service.ts
import { Injectable } from '@angular/core'; import { HttpRequestService } from './http-request-services'; import { Observable } from 'rxjs'; import { Page } from '../model/api/page.model'; import { OcHttpParams } from '../model/api/http-params-encoder-model'; import { RequestModel, RequestModelResponse, RequestStatusModel } from '../model/api/request.model'; import { HttpHeaders } from '@angular/common/http'; import { OcApiPaths } from '../oc-ng-common-service.module'; /** * Description: API service for getting and modifying Request model.<br> * * Endpoints:<br> * * GET 'v2/requests'<br> * * POST 'v2/requests'<br> * * GET 'v2/requests/{requestId}'<br> * * PATCH 'v2/requests/{requestId}'<br> * * DELETE 'v2/requests/{requestId}'<br> * * POST 'v2/requests/{requestId}/status'<br> */ @Injectable({ providedIn: 'root', }) export class RequestService { constructor(private httpService: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Get requests list with pagination * * @param {number} pageNumber - (optional) Current page index. Starts from >= 1 * @param {number} limit - (optional) Count users into response. Starts from >= 1. * @param {HttpHeaders} headers - (optional) (default: empty HttpHeaders object) * @returns {Observable<Page<RequestModelResponse>>} `Observable<Page<RequestModelResponse>>` * * ### Example * * `getAllRequest(1,10,{"Authorization":"Bearer as98hd90ahsd98has9d8ha98sd"})` */ getAllRequest(pageNumber?: number, limit?: number, headers: HttpHeaders = new HttpHeaders()): Observable<Page<RequestModelResponse>> { const options: any = { params: new OcHttpParams().append('pageNumber', String(pageNumber)).append('limit', String(limit)), }; options.headers = headers; return this.httpService.get(this.apiPaths.requests, options); } /** * * Description: Create new request * * @param {RequestModel} request - (required) Request model for creation * @param {boolean} autoSubmit - (optional) (default: true) * @param {HttpHeaders} headers - (optional) (default: empty HttpHeaders object) * @returns {Observable<RequestModelResponse>} `Observable<RequestModelResponse>` * * ### Example * * `createRequest({ * name:'name', * type:'type', * appId:'iu2h34iuh23i4', * userId:'as8ujf098ausjd', * userAccountId:'9uanwej', * developerId:'ja9s8dj<PASSWORD>sjd', * developerAccountId:'<KEY>', * customData:{} * }, * false, * {"Authorization":"Bearer <PASSWORD>"} * )` */ createRequest(request: RequestModel, autoSubmit = true, headers: HttpHeaders = new HttpHeaders()): Observable<RequestModelResponse> { return this.httpService.post(this.apiPaths.requests, autoSubmit ? { ...request, autoSubmit } : request, { headers }); } /** * * Description: Find some request model with id and update * * @param {string} requestId - (required) Request Id to search * @param {RequestModel} request - (required) Request model to update * @param {HttpHeaders} headers - (optional) (default: empty HttpHeaders object) * @returns {Observable<RequestModelResponse>} `Observable<RequestModelResponse>` * * ### Example * * `updateRequest( * 'h0a978shd90ahs', * { * name:'name', * type:'type', * appId:'iu2h34iuh23i4', * userId:'as8ujf098ausjd', * userAccountId:'9uanwej', * developerId:'ja<PASSWORD>', * developerAccountId:'<KEY>', * customData:{} * }, * {"Authorization":"Bearer as98hd90ahsd98has<PASSWORD>sd"} * )` */ updateRequest(requestId: string, request: RequestModel, headers: HttpHeaders = new HttpHeaders()): Observable<RequestModelResponse> { return this.httpService.patch(`${this.apiPaths.requests}/${requestId}`, request, { headers }); } /** * * Description: Find some request model with id * * @param {string} requestId - (required) Request Id to search * @param {HttpHeaders} headers - (optional) (default: empty HttpHeaders object) * @returns {Observable<RequestModelResponse>} `Observable<RequestModelResponse>` * * ### Example * * `getRequest('8a7hs8d7has8d7', {"Authorization":"Bearer as98hd90ahsd98has<PASSWORD>ha98sd"})` */ getRequest(requestId: string, headers: HttpHeaders = new HttpHeaders()): Observable<RequestModelResponse> { return this.httpService.get(`${this.apiPaths.requests}/${requestId}`, { headers }); } /** * * Description: Find some request model with id and delete * * @param {string} requestId - (required) Request Id to search * @param {HttpHeaders} headers - (optional) (default: empty HttpHeaders object) * @returns {Observable<boolean>} `Observable<boolean>` * * ### Example * * `deleteRequest('8a7hs8d7has8d7', {"Authorization":"Bearer as98hd90ah<PASSWORD>has<PASSWORD>sd"});` */ deleteRequest(requestId: string, headers: HttpHeaders = new HttpHeaders()): Observable<boolean> { return this.httpService.delete(`${this.apiPaths.requests}/${requestId}`, { headers }); } /** * * Description: Find Request by id and update its status * * @param {string} requestId - (required) Request Id to search * @param {RequestStatusModel} status - (required) Status and reason(opt) to update * @param {HttpHeaders} headers - (optional) (default: empty HttpHeaders object) * @returns {Observable<RequestModelResponse>} `Observable<RequestModelResponse>` * * ### Example * * `updateRequestStatus( * 'ajs09d8ja9s8d', * { * status: 'draft' | 'approved' | 'rejected' | 'pending' | 'inReview', * reason: 'change pls' * }, * {"Authorization":"Bearer <PASSWORD>"} * );` */ updateRequestStatus( requestId: string, status: RequestStatusModel, headers: HttpHeaders = new HttpHeaders(), ): Observable<RequestModelResponse> { return this.httpService.post(`${this.apiPaths.requests}/${requestId}/status`, status, { headers }); } }
mukesh-openchannel/angular-template-libraries
src/tag-element.stories.ts
<filename>src/tag-element.stories.ts<gh_stars>0 import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule, OcTagElementComponent } from '@openchannel/angular-common-components/src/lib/common-components'; const modules = { imports: [OcCommonLibModule], }; export default { title: 'Tag element [BEM]', component: OcTagElementComponent, decorators: [moduleMetadata(modules)], }; const TagComponent = (args: OcTagElementComponent) => ({ component: OcTagElementComponent, moduleMetadata: modules, props: args, }); export const DefaultOneTag = TagComponent.bind({}); DefaultOneTag.args = { title: 'MyTag', width: '15%', closeMarker: true, }; export const CustomCloseMarker = TagComponent.bind({}); CustomCloseMarker.args = { title: 'MyTag', closeMarker: true, deleteTagImgUrl: 'assets/angular-common-components/delete.svg', }; export const WithoutCloseMarker = TagComponent.bind({}); WithoutCloseMarker.args = { title: 'MyTag', closeMarker: false, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/oc-dropdown-multi-app/oc-dropdown-multi-app.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcDropdownMultiAppComponent } from './oc-dropdown-multi-app.component'; import { MockDropboxComponent, MockInitialsComponent, MockTagComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { AppsSearchService } from '@openchannel/angular-common-components/src/lib/form-components'; import { FullAppData } from '../../common-components/model/app-data.model'; import { Observable, of } from 'rxjs'; const mockApps: Partial<FullAppData>[] = [ { appId: '<KEY>', version: 5, name: 'API Connect Play', }, { appId: '<KEY>', version: 3, name: 'Fuel CRM Gold', icon: 'assets/angular-common-components/standard-app-icon.svg', }, { appId: '<KEY>', version: 7, name: 'Intersect Connect', }, { appId: '<KEY>', version: 13, name: 'Lead Accounting', icon: 'assets/angular-common-components/star.svg', }, { appId: '<KEY>', version: 4, name: 'Fuel CRM Lite', }, ]; export class MockAppsSearchService extends AppsSearchService { constructor() { super(); } loadDefaultApps(existsAppIDs: string[]): Observable<FullAppData[]> { return of(mockApps.filter(app => existsAppIDs?.includes(app.appId)) as FullAppData[]); } appsSearch(existsApps: FullAppData[], searchText: string): Observable<FullAppData[]> { const existsAppIDs = (existsApps || []).map(app => app.appId); return of( mockApps.filter(app => !existsAppIDs.includes(app.appId) && app.name.toLowerCase().includes(searchText)) as FullAppData[], ); } } describe('OcDropdownMultiAppComponent', () => { let component: OcDropdownMultiAppComponent; let fixture: ComponentFixture<OcDropdownMultiAppComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcDropdownMultiAppComponent, MockTagComponent, MockDropboxComponent, MockInitialsComponent], providers: [{ provide: AppsSearchService, useClass: MockAppsSearchService }], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcDropdownMultiAppComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('null is safe', () => { component.dropdownPlaceholder = null; component.dropdownClearTextAfterSelect = null; component.dropdownCustomDropdownItemTemplateRef = null; component.dropdownCustomTagTemplateRef = null; component.defaultAppIDs = null; component.itemPreviewName = null; component.itemPreviewId = null; component.itemPreviewVersion = null; fixture.detectChanges(); }); it('load default apps', () => { const firstAppId = '<KEY>'; const secondAppId = '<KEY>'; component.defaultAppIDs = [firstAppId, secondAppId]; jest.spyOn(component.selectedAppsOutput, 'emit'); fixture.detectChanges(); expect(component.resultApps[0].appId).toEqual(firstAppId); expect(component.resultApps[1].appId).toEqual(secondAppId); expect(component.resultApps.length).toEqual(2); expect(component.selectedAppsOutput.emit).toHaveBeenCalledWith(component.resultApps); }); it('load default apps (duplicated apps)', () => { const firstAppId = '<KEY>'; component.defaultAppIDs = [firstAppId, firstAppId]; fixture.detectChanges(); expect(component.resultApps.length).toEqual(1); }); it('Add app to result array. Remove app from result array', () => { jest.spyOn(component.selectedAppsOutput, 'emit'); // add app const appData = mockApps[0]; component.addAppToResultArray(appData); component.addAppToResultArray(appData); fixture.detectChanges(); expect(component.resultApps.length).toEqual(1); expect(component.selectedAppsOutput.emit).toHaveBeenCalledWith([appData]); // remove app component.removeAppFromResultArray(appData as FullAppData); fixture.detectChanges(); expect(component.resultApps.length).toEqual(0); expect(component.selectedAppsOutput.emit).toHaveBeenCalledWith([]); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/model/confirmation-modal.model.ts
<filename>projects/angular-common-components/src/lib/common-components/model/confirmation-modal.model.ts import { OcButtonType } from '../model/components-basic.model'; export interface ConfirmationModalButton { /** * When a user clicks on this button, the ID will return as the modal result. */ id: string; /** * Type for creating button. */ type: OcButtonType; /** * Button text. */ text: string; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/portal-components/utils/normalizeCommonJSImport.ts
export function normalizeCommonJSImport<T>(importPromise: Promise<T>): Promise<T> { // CommonJS's `module.exports` is wrapped as `default` in ESModule. return importPromise.then((m: any) => (m.default || m) as T); }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/management-components/oc-menu-user-grid/oc-menu-user-grid.component.spec.ts
<gh_stars>0 import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcMenuUserGridComponent } from './oc-menu-user-grid.component'; import { MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { ComponentsUserAccountGridModel, UserGridOptionType } from '@openchannel/angular-common-components/src/lib/management-components'; import { By } from '@angular/platform-browser'; const user1: ComponentsUserAccountGridModel = { userId: 'userId1', name: '<NAME>', email: '<EMAIL>', customData: null, created: 0, userAccountId: 'userAccountId1', inviteStatus: 'ACTIVE', inviteId: 'inviteId1', inviteToken: 'invite<PASSWORD>', }; const optionsMock: UserGridOptionType[] = ['EDIT', 'DELETE']; describe('OcMenuUserGridComponent', () => { let component: OcMenuUserGridComponent; let fixture: ComponentFixture<OcMenuUserGridComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcMenuUserGridComponent, MockSvgIconComponent], imports: [InfiniteScrollModule], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcMenuUserGridComponent); component = fixture.componentInstance; component.properties = { data: { count: 0, list: [user1], pageNumber: 0, pages: 0 }, layout: 'table', options: optionsMock }; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should emit pageScrolled, when page was scrolled', () => { jest.spyOn(component.pageScrolled, 'emit'); const tableDE = fixture.debugElement.query(By.css('.user-table')); tableDE.triggerEventHandler('scrolled', {}); expect(component.pageScrolled.emit).toHaveBeenCalled(); }); it('should emit correct action data, when action button was clicked', () => { const actionToEmit = { action: 'DELETE', userId: user1.userId, userAccountId: user1.userAccountId, inviteId: user1.inviteId, inviteToken: user1.inviteToken, }; jest.spyOn(component.menuClicked, 'emit'); const deleteActionButtonDE = fixture.debugElement.query(By.css('.menu-delete')); deleteActionButtonDE.triggerEventHandler('click', {}); expect(component.menuClicked.emit).toHaveBeenCalledWith(actionToEmit); }); it('should emit chosen sort options, when sort button was clicked', () => { const sortField = 'name'; const newSortOptions = { name: 1, date: -1, email: -1, role: -1, }; jest.spyOn(component.sortChosen, 'emit'); jest.spyOn(component.sortOptionsChosen, 'emit'); const sortByNameButtonDE = fixture.debugElement.query(By.css('.user-table__head-name .user-table__th-row')); sortByNameButtonDE.triggerEventHandler('click', {}); expect(component.sortChosen.emit).toHaveBeenCalledWith(sortField); expect(component.sortOptionsChosen.emit).toHaveBeenCalledWith({ sortOptions: newSortOptions, changedSortOption: sortField, }); }); it('should set undefined sort field to default, if it was passed to sortUsersBy', () => { const sortField = 'name'; const newSortOptions = { name: -1, date: -1, email: -1, role: -1, }; jest.spyOn(component.sortOptionsChosen, 'emit'); component.sortOptions = { ...component.sortOptions, name: undefined }; fixture.detectChanges(); component.sortUsersBy(sortField); expect(component.sortOptionsChosen.emit).toHaveBeenCalledWith({ sortOptions: newSortOptions, changedSortOption: sortField, }); }); it('should set correct user initials', () => { const userInitials = 'NS'; const userInitialsElement = fixture.debugElement.query(By.css('.user-table__profile')).nativeElement; expect(userInitialsElement.textContent.trim()).toBe(userInitials); }); it('initials function should return empty string, if user name is absent', () => { expect(component.initials({ ...user1, name: null })).toBe(''); }); it('should set correct classes depending on user inviteStatus', () => { const invitedClasses = ['user-table__row_highlight-user', 'user-table__profile_invited']; const activeClasses = ['user-table__text_dark']; const checkClass = classSelector => { expect(fixture.debugElement.query(By.css(`.${classSelector}`))).toBeTruthy(); }; component.properties.data.list[0].inviteStatus = 'INVITED'; fixture.detectChanges(); invitedClasses.forEach(checkClass); component.properties.data.list[0].inviteStatus = 'ACTIVE'; fixture.detectChanges(); activeClasses.forEach(checkClass); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-confirmation-modal/oc-confirmation-modal.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcConfirmationModalComponent } from './oc-confirmation-modal.component'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { MockButtonComponent, MockHeadingTagDirective, MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcConfirmationModalComponent', () => { let component: OcConfirmationModalComponent; let fixture: ComponentFixture<OcConfirmationModalComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcConfirmationModalComponent, MockButtonComponent, MockSvgIconComponent, MockHeadingTagDirective], providers: [NgbActiveModal], }).compileComponents(); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcConfirmationModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/pipe/array-search.pipe.ts
<filename>projects/angular-common-components/src/lib/common-components/pipe/array-search.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { get } from 'lodash'; @Pipe({ name: 'arraySearch', }) export class ArraySearchPipe implements PipeTransform { transform<T>(array: T[], pathToValue: string, searchValue: any): T { if (!array) { return null; } return array.find(item => get(item, pathToValue) === searchValue); } }
mukesh-openchannel/angular-template-libraries
src/video-url.stories.ts
import { moduleMetadata } from '@storybook/angular'; import { OcCommonLibModule } from '@openchannel/angular-common-components/src/lib/common-components'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { OcVideoUrlComponent } from '@openchannel/angular-common-components/src/lib/form-components'; import { FormsModule } from '@angular/forms'; const modules = { imports: [OcCommonLibModule, HttpClientModule, FormsModule], providers: [HttpClient], }; export default { title: 'Video Url component [BEM]', component: OcVideoUrlComponent, decorators: [moduleMetadata(modules)], }; const VideoUrlComponent = (args: OcVideoUrlComponent) => ({ component: OcVideoUrlComponent, moduleMetadata: modules, props: args, }); export const DefaultVideoUrl = VideoUrlComponent.bind({}); DefaultVideoUrl.args = { value: 'https://www.youtube.com/watch?v=DGQwd1_dpuc', }; export const UrlWithoutPreview = VideoUrlComponent.bind({}); UrlWithoutPreview.args = { value: 'https://coub.com/view/1po8m3', }; export const EmptyField = VideoUrlComponent.bind({}); EmptyField.args = {};
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/stripe.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { ConnectStripeAccountResponse, StripeAccountsResponse, GetMarketplaceStripeSettingsResponse, UserCreditCardsResponse, ChangeableCreditCardFields, PaymentTaxesResponse, Purchase, } from '../model/api/stripe.model'; import { HttpRequestService } from './http-request-services'; import { OcApiPaths } from '../oc-ng-common-service.module'; import { HttpHeaders } from '@angular/common/http'; /** * Description: API service to work with Stripe.<br> * * [OpenChannel Documentation]{@link https://support.openchannel.io/documentation/api/#800-stripe-gateway} * * Endpoints:<br> * * GET 'v2/stripe-gateway/settings'<br> * * GET 'v2/stripe-gateway/user/this/cards'<br> * * POST 'v2/stripe-gateway/user/this/cards'<br> * * POST 'v2/stripe-gateway/user/this/cards/{cardId}'<br> * * DELETE 'v2/stripe-gateway/user/this/cards/{cardId}'<br> * * GET 'v2/stripe-gateway/developer/this/accounts'<br> * * POST 'v2/stripe-gateway/developer/this/accounts'<br> * * DELETE 'v2/stripe-gateway/developer/this/accounts/{stripeId}'<br> * * GET 'v2/stripe-gateway/preview'<br> * */ @Injectable({ providedIn: 'root', }) export class StripeService { constructor(public httpRequest: HttpRequestService, private apiPaths: OcApiPaths) {} /** * * Description: Returns the Stripe settings configured for this marketplace * * @returns {Observable<GetMarketplaceStripeSettingsResponse>} `Observable<GetMarketplaceStripeSettingsResponse>` * * ### Example * * `getMarketplaceStripeSettings();` */ getMarketplaceStripeSettings(): Observable<GetMarketplaceStripeSettingsResponse> { return this.httpRequest.get(`${this.apiPaths.stripeGateway}/settings`); } /** * * Description: Returns a list of credit cards configured for this user * * @returns {Observable<UserCreditCardsResponse>} `Observable<UserCreditCardsResponse>` * * ### Example * * `getUserCreditCards();` */ getUserCreditCards(): Observable<UserCreditCardsResponse> { return this.httpRequest.get(`${this.apiPaths.stripeGateway}/user/this/cards`); } /** * * Description: Adds user credit card, which can be used later * * @param {string} token - The Stripe token returned by the Stripe.js Stripe.card.createToken call * @param {string} isDefault - (optional) Set to true if this should be set to be the default credit card * @param {HttpHeaders} headers - (optional) HTTP request headers * * @returns {Observable<UserCreditCardsResponse>} `Observable<UserCreditCardsResponse>` * * ### Example * * `addUserCreditCard('some-token');` */ addUserCreditCard( token: string, isDefault: boolean = true, headers: HttpHeaders = new HttpHeaders(), ): Observable<UserCreditCardsResponse> { const body = { token, isDefault, }; return this.httpRequest.post(`${this.apiPaths.stripeGateway}/user/this/cards`, body, { headers }); } /** * * Description: Updates fields in user credit card * * @param {string} cardId - Id of the card to update * @param {Partial<ChangeableCreditCardFields>} body - Fields to update in credit card * @param {HttpHeaders} headers - (optional) HTTP request headers * * @returns {Observable<UserCreditCardsResponse>} `Observable<UserCreditCardsResponse>` * * ### Example * * `updateUserCreditCard('card-id-123', { address_city: 'New city', address_country: 'New country' });` */ updateUserCreditCard( cardId: string, body: Partial<ChangeableCreditCardFields>, headers: HttpHeaders = new HttpHeaders(), ): Observable<UserCreditCardsResponse> { return this.httpRequest.post(`${this.apiPaths.stripeGateway}/user/this/cards/${cardId}`, body, { headers }); } /** * * Description: Deletes card from user account * * @param {string} cardId - Id of the card to delete * @param {HttpHeaders} headers - (optional) HTTP request headers * @returns {Observable<UserCreditCardsResponse>} `Observable<UserCreditCardsResponse>` * * ### Example * * `deleteUserCreditCard('card-id-123');` */ deleteUserCreditCard(cardId: string, headers: HttpHeaders = new HttpHeaders()): Observable<UserCreditCardsResponse> { return this.httpRequest.delete(`${this.apiPaths.stripeGateway}/user/this/cards/${cardId}`, { headers }); } /** * * Description: Get all developer accounts connected to Stripe * * @returns {Observable<StripeAccountsResponse>} `Observable<StripeAccountsResponse>` * * ### Example * * `getConnectedAccounts();` */ getConnectedAccounts(): Observable<StripeAccountsResponse> { return this.httpRequest.get(`${this.apiPaths.stripeGateway}/developer/this/accounts`); } /** * * Description: Returns a link to Stripe, where developer can connect Stripe account * * @param {string} redirectUrl - The URL to redirect this developer after they have connected their Stripe account * @param {HttpHeaders} headers - (optional) HTTP request headers * @returns {Observable<ConnectStripeAccountResponse>} `Observable<ConnectStripeAccountResponse>` * * ### Example * * `connectAccount('https://my-market.com/land-here');` */ connectAccount(redirectUrl: string, headers: HttpHeaders = new HttpHeaders()): Observable<ConnectStripeAccountResponse> { const body = { redirectUrl }; return this.httpRequest.post(`${this.apiPaths.stripeGateway}/developer/this/accounts`, body, { headers }); } /** * * Description: Disconnects developer from Stripe * * @param {string} stripeId - The id of the Stripe account to disconnect * @param {HttpHeaders} headers - (optional) HTTP request headers * @returns {Observable<StripeAccountsResponse>} `Observable<StripeAccountsResponse>` * * ### Example * * `disconnectAccount('stripe-id');` */ disconnectAccount(stripeId: string, headers: HttpHeaders = new HttpHeaders()): Observable<StripeAccountsResponse> { return this.httpRequest.delete(`${this.apiPaths.stripeGateway}/developer/this/accounts/${stripeId}`, { headers }); } /** * * Description: the tax items calculated on the item (only possible after billing address is set). * You can get the tax amounts, subtotal and total. * * @param {string} country iso of the country from the billing data * @param {string} state name of the state * @param {string} appId id of the chosen app * @param {string} modelId id of the price model of the chosen app * @param {string} zipCode postal code of the chosen Address * @param {string} city city of the user * @param {HttpHeaders} headers (optional) additional http headers for this request * @returns {Observable<PaymentTaxesResponse>} `Observable<PaymentTaxesResponse>` * * ### Example * * `getTaxesAndPayment('CA', 'Ontario', '600eef7a7ec0f53371d1ca90', '60b0fa5240b4914e74c8d3fd');` */ getTaxesAndPayment( country: string, state: string, appId: string, modelId: string, zipCode: string, city: string, headers?: HttpHeaders, ): Observable<PaymentTaxesResponse> { const query = `country=${country}&state=${state}&appId=${appId}&modelId=${modelId}&zipCode=${zipCode}&city=${city}`; return this.httpRequest.get(`${this.apiPaths.stripeGateway}/preview?${query}`, { headers }); } /** * * Description: Returns a link to Stripe, where developer can connect Stripe account * * @param {Purchase} purchaseBody - object with an array of models that contains id of the chosen app and id of the chosen model. * Details at {@link Purchase} model. * @returns {Observable<ConnectStripeAccountResponse>} `Observable<ConnectStripeAccountResponse>` * * ### Example * * `makePurchase({ models: [{ appId: '5463cee5e4b042e3e26f1e41', modelId: '7349cew5e4b041e3c26y1e49' }]});` */ makePurchase(purchaseBody: Purchase): Observable<any> { return this.httpRequest.post(`${this.apiPaths.stripeGateway}/purchase`, purchaseBody); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/form-components/model/file.model.ts
<reponame>mukesh-openchannel/angular-template-libraries import { Observable } from 'rxjs'; import { HttpResponse, HttpUploadProgressEvent } from '@angular/common/http'; /** * File Details interface * @property {string} fileId - Unique identifier of file * @property {string} fileUrl - File URL link * @property {string} name - File name * @property {number} size - File size in px * @property {number} uploadDate - File upload date (timestamp) * @property {number} fileUploadProgress - Percentage of file upload process * @property {string} fileIconUrl - URL link for file icon * @property {string} contentType - MIME type for a upload file request * @property {boolean} isPrivate - Flag that show do we need to use file id or url * @property {'PASSED' | 'FAILED'} mimeCheck - result after mime check feature. Can be 'PASSED' or 'FAILED' * @property {VirusScanResult} virusScan - Object that was returned after virus scan check * @property {boolean} isError - Flag that shows up upload was with error or not */ export class FileDetails { fileId: string; fileUrl: string; name: string; size: number; uploadDate: number; fileUploadProgress: number; fileIconUrl: string; contentType: string; isPrivate: boolean; mimeCheck: 'PASSED' | 'FAILED'; virusScan: VirusScanResult; isError: boolean; } export interface VirusScanResult { started: number; finished: number; status: 'CLEAN' | 'NOT_SCANNED' | 'DIRTY'; foundViruses: FoundVirus[]; } export interface FoundVirus { fileName: string; virusName: string; } export type FileType = 'singleFile' | 'singleImage' | 'privateSingleFile' | 'multiFile' | 'multiImage' | 'multiPrivateFile'; export abstract class FileUploaderService { abstract fileUploadRequest( file: FormData, isPrivate: boolean, hash?: string[], ): Observable<HttpResponse<FileDetails> | HttpUploadProgressEvent>; abstract fileDetailsRequest(fileId: string, headers?: any): Observable<FileDetails>; }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/app-categories/public-api.ts
export * from './oc-app-categories.module'; export * from './oc-app-categories/oc-app-categories.component'; /** Models */ export * from './models/app-category-model';
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/auth-components/oc-signup-custom/oc-signup-custom.component.spec.ts
<reponame>mukesh-openchannel/angular-template-libraries import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcSignupCustomComponent } from './oc-signup-custom.component'; import { FormControl, FormGroup, FormsModule, NgModel } from '@angular/forms'; import { CommonModule, Location } from '@angular/common'; import { BrowserModule, By } from '@angular/platform-browser'; import { MockButtonComponent, MockCheckboxComponent, MockEditUserFormComponent, MockErrorComponent, MockHeadingTagDirective, MockInputComponent, MockLabelComponent, MockPasswordComponent, MockRoutingComponent, } from '@openchannel/angular-common-components/src/mock/mock'; import { RouterTestingModule } from '@angular/router/testing'; import { Router } from '@angular/router'; import { cloneDeep } from 'lodash'; const formConfigsMock = [ { name: 'My custom 123321', account: { type: 'check-config-type', typeData: null, includeFields: ['name', 'username', 'email'], }, }, ]; describe('OcSignupCustomComponent', () => { let component: OcSignupCustomComponent; let fixture: ComponentFixture<OcSignupCustomComponent>; let location: Location; let router: Router; const testUrl = 'https://some-site.com/test-img-123'; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ OcSignupCustomComponent, MockEditUserFormComponent, MockPasswordComponent, MockLabelComponent, MockInputComponent, MockErrorComponent, MockButtonComponent, MockCheckboxComponent, MockRoutingComponent, MockHeadingTagDirective, ], imports: [ FormsModule, CommonModule, BrowserModule, RouterTestingModule.withRoutes([ { path: 'login', component: MockRoutingComponent }, { path: 'activation', component: MockRoutingComponent }, ]), ], providers: [NgModel], }).compileComponents(); router = TestBed.inject(Router); location = TestBed.inject(Location); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcSignupCustomComponent); component = fixture.componentInstance; component.formConfigs = cloneDeep(formConfigsMock); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should redirect to sign up page', () => { component.loginUrl = '/login'; fixture.detectChanges(); const login: HTMLLinkElement = fixture.debugElement.query(By.css('.sign-up__login-link')).nativeElement; login.click(); expect(location.path()).toEqual('/login'); }); it('submit button should not emmit submit when process is on', () => { component.process = true; const resultUserDataEmitFunction = jest.spyOn(component.resultUserData, 'emit'); component.formConfigsLoading = false; fixture.detectChanges(); const button = fixture.debugElement.query(By.css('.sign-up__button')).nativeElement; button.click(); expect(resultUserDataEmitFunction).not.toHaveBeenCalled(); }); it('should redirect to activation', () => { component.showSignupFeedbackPage = true; component.activationUrl = '/activation'; fixture.detectChanges(); component.goToActivationPage(); fixture.whenStable().then(() => { expect(router.url).toEqual('/activation'); }); }); it('should emit show sign up feedback page change, when sign up link clicked', () => { const showSignupFeedbackPageChangeEmitFunction = jest.spyOn(component.showSignupFeedbackPageChange, 'emit'); component.showSignupFeedbackPage = true; fixture.detectChanges(); const signUpLink: HTMLLinkElement = fixture.debugElement.query(By.css('.result__link')).nativeElement; signUpLink.click(); expect(showSignupFeedbackPageChangeEmitFunction).toHaveBeenCalled(); }); it('should not show sign up button, when form configs loading', () => { const resultFormValue = { account: { name: 'Name', email: '<EMAIL>', }, password: '<PASSWORD>', }; const resultUserDataEmitFunction = jest.spyOn(component.resultUserData, 'emit'); component.formConfigsLoading = false; component.resultFormValue = resultFormValue; fixture.detectChanges(); const signUpButton = fixture.debugElement.query(By.css('.sign-up__button')).nativeElement; signUpButton.click(); expect(resultUserDataEmitFunction).toHaveBeenCalledWith(resultFormValue); }); it('should not show sign up button, when no form configs available', () => { component.formConfigs = []; fixture.detectChanges(); const signUpButton = fixture.debugElement.query(By.css('.sign-up__button')); expect(signUpButton).toBeNull(); }); it('should not show login link, when showLoginLink=false', () => { component.showLoginLink = false; fixture.detectChanges(); const loginLink = fixture.debugElement.query(By.css('.sign-up__login')); expect(loginLink).toBeNull(); }); it('should touch all form fields on submit', () => { component.formConfigsLoading = false; component.formGroup = new FormGroup({ email: new FormControl('email'), password: new FormControl('password'), }); fixture.detectChanges(); const signUpButton = fixture.debugElement.query(By.css('.sign-up__button')).nativeElement; signUpButton.click(); expect(component.formGroup.touched).toBeTruthy(); }); it('should pass correct src to company logo', () => { const companyLogoImages: HTMLImageElement[] = []; component.companyLogoUrl = testUrl; component.showSignupFeedbackPage = false; fixture.detectChanges(); companyLogoImages.push(fixture.debugElement.query(By.css('.company-logo')).nativeElement); component.showSignupFeedbackPage = true; fixture.detectChanges(); companyLogoImages.push(fixture.debugElement.query(By.css('.company-logo')).nativeElement); companyLogoImages.forEach(companyLogoImage => expect(companyLogoImage.src).toBe(testUrl)); }); it('should pass correct src to forgot password image', () => { component.forgotPasswordDoneUrl = testUrl; component.showSignupFeedbackPage = true; fixture.detectChanges(); const forgotPasswordImage: HTMLImageElement = fixture.debugElement.query(By.css('.result__message-img')).nativeElement; expect(forgotPasswordImage.src).toBe(testUrl); }); it('should set correct heading tag', () => { const testHeadingTag = 'h6'; component.headingTag = testHeadingTag; component.showSignupFeedbackPage = false; fixture.detectChanges(); const heading = fixture.debugElement.query(By.css('.sign-up__header-heading')).componentInstance; expect(heading.headingTag).toBe(testHeadingTag); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-app-gallery/oc-app-gallery.component.spec.ts
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { OcAppGalleryComponent } from './oc-app-gallery.component'; import { CommonModule, Location } from '@angular/common'; import { RouterTestingModule } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; import { Router } from '@angular/router'; import { FullAppData, StatElement } from '@openchannel/angular-common-components/src/lib/common-components'; import { MockAppCardComponent, MockHeadingTagDirective, MockRoutingComponent, MockSvgIconComponent } from '@openchannel/angular-common-components/src/mock/mock'; describe('OcAppGalleryComponent', () => { let component: OcAppGalleryComponent; let fixture: ComponentFixture<OcAppGalleryComponent>; let location: Location; let router: Router; const statElement: StatElement = { '90day': 20, '30day': 10, total: 20, }; const app: FullAppData = { 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, }; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [OcAppGalleryComponent, MockAppCardComponent, MockRoutingComponent, MockSvgIconComponent, MockHeadingTagDirective], imports: [CommonModule, RouterTestingModule.withRoutes([{ path: 'mock-router', component: MockRoutingComponent }])], }).compileComponents(); router = TestBed.inject(Router); location = TestBed.inject(Location); }), ); beforeEach(() => { fixture = TestBed.createComponent(OcAppGalleryComponent); component = fixture.componentInstance; component.appsArr = [app, app, app]; component.appGalleryTitle = 'Test Apps'; component.appGalleryDescription = 'The list of test apps'; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show data', () => { const galleryTitle = fixture.debugElement.query(By.css('h2')).nativeElement; const galleryDescription = fixture.debugElement.query(By.css('#description')).nativeElement; expect(galleryTitle.textContent).toContain('Test Apps'); expect(galleryDescription.textContent).toContain('The list of test apps'); }); it('should show no app message', () => { component.appsArr = []; component.noAppMessage = 'No Apps Added Yet'; fixture.detectChanges(); const noAppsMessage = fixture.debugElement.query(By.css('h5')).nativeElement; expect(noAppsMessage.textContent).toContain('No Apps Added Yet'); }); });
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-video/oc-video.component.ts
import { Component, Input } from '@angular/core'; import { SafeHtml } from '@angular/platform-browser'; import { NgxSpinnerService } from 'ngx-spinner'; import { OcEmbedVideoService } from './oc-embed-video.service'; @Component({ selector: 'oc-video', templateUrl: './oc-video.component.html', styleUrls: ['./oc-video.component.css'], }) export class OcVideoComponent { /** * The video url setter. Defines video source and calls loadVideo() method. * Default: empty */ @Input() set videoUrl(videoUrl: string) { this.url = videoUrl; this.loadVideo(); } /** * URL variable of the component. Defines through `videoUrl` Input. */ url: string; /** * Flag that indicates that the video should load in a frame */ loadInIframe: boolean = true; /** * Flag that indicates that the video should load in a video tag */ loadInVideo: boolean = false; /** * Flag for the video loader spinner. */ showVideoLoader: boolean = false; /** * Preview data for the video url */ previewData: SafeHtml; constructor(private embedService: OcEmbedVideoService, private spinner: NgxSpinnerService) {} /** * Loads video. Checks preview data and video format. Shows and hides spinner. */ loadVideo(): void { this.spinner.show(); this.showVideoLoader = true; const options = { attr: { width: '100%', height: '100%' }, }; this.previewData = this.embedService.embed(this.url, options); if (this.previewData) { this.loadInIframe = true; } else if (this.url.endsWith('.mp4') || this.url.endsWith('.webm') || this.url.endsWith('.ogv')) { this.loadInIframe = false; this.loadInVideo = true; } else { this.loadInIframe = false; this.loadInVideo = false; } this.spinner.hide(); this.showVideoLoader = false; } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/common-components/oc-button/oc-button.component.ts
import { Component, Input, OnChanges, SimpleChanges, TemplateRef } from '@angular/core'; import { NgxSpinnerService } from 'ngx-spinner'; import { OcButtonType } from '../model/components-basic.model'; /** * Special button component. Contains text and spinner. * Can be different type {@link OcButtonType}. */ @Component({ selector: 'oc-button', templateUrl: './oc-button.component.html', styleUrls: ['./oc-button.component.css'], }) export class OcButtonComponent implements OnChanges { /** * Text content of the button. * @default empty string */ @Input() text: string = ''; /** * Disable current button. User can not interact with this button. * Also, disabled button style will be applied. * Button is active by default. * @default false */ @Input() disabled: boolean = false; /** * Set custom inline style to button. * @default: empty * * ## Example for Docs * `` * <oc-button [style]="'width: 120px; color: green;'"></oc-button> * `` * @example * <oc-button [style]="'width: 120px; color: green;'"></oc-button> */ @Input() style: string = ''; /** * Set custom class from main style.scss file for the button. * ## Example for Docs * `` * <oc-button customClass=".example-class"></oc-button>. * `` * @example * <oc-button customClass=".example-class"></oc-button>. */ @Input() customClass: string = ''; /** * (Optional) * Template for the button content. If not set - default text or spinner will be applied. * @default: empty */ @Input() customTemplate: TemplateRef<any>; /** * Sets process status to the button. If it is `true` - button will show the spinner and become inactive. * @default false */ @Input() process: boolean = false; /** * Sets the button type which changing button style. * @param type type of the button {@link OcButtonType}. */ @Input() set type(type: OcButtonType) { this.buttonType = type; this.buttonTypeClass = type !== 'none' ? `oc-button_${this.buttonType}` : null; } /** variable which includes a button type */ buttonType: OcButtonType = 'primary'; /** switching button style according to the button `type` */ buttonTypeClass: string; /** unique pointer for the spinner of current button */ spinnerName: string; constructor(private spinner: NgxSpinnerService) { this.spinnerName = Math.random().toString(); } ngOnChanges(changes: SimpleChanges): void { if (changes.process && changes.process.previousValue !== changes.process.currentValue) { this.checkSpinner(); } } /** * Function that checking button `type` and `process` status. * Applies spinner if button is not `link` type and process status set to `true`. */ checkSpinner(): void { if (this.process && this.buttonType !== 'link') { this.spinner.show(this.spinnerName, { color: null, bdColor: null, type: 'ball-spin', size: 'small', fullScreen: false, }); } else { this.spinner.hide(this.spinnerName); } } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/model/api/user-registration-model.ts
export interface UserRegistrationModel { uname: string; company: string; password: string; email: string; isChecked: boolean; }
mukesh-openchannel/angular-template-libraries
src/app-rich-text-editor.stories.ts
<filename>src/app-rich-text-editor.stories.ts import { OcFormComponentsModule, OcRichTextEditorComponent } from '@openchannel/angular-common-components/src/lib/form-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: [OcFormComponentsModule], }; export default { title: 'Rich Text Editor Component [BEM]', component: OcRichTextEditorComponent, decorators: [moduleMetadata(modules)], argTypes: { getEditorContent: { action: 'Editor data' } }, }; const RichTextEditorComponent = (args: OcRichTextEditorComponent) => ({ component: OcRichTextEditorComponent, moduleMetadata: modules, props: args, }); export const SimpleRichTextEditor = RichTextEditorComponent.bind({}); SimpleRichTextEditor.args = { placeholder: 'Write here about yourself...', tinyOptions: { menubar: false, toolbar: 'bold italic underline strikethrough subscript superscript fontselect fontsizeselect |' + 'alignleft aligncenter alignright alignjustify | numlist bullist | outdent indent | link unlink | undo redo', plugins: 'lists link wordcount', placeholder: 'sdfasfd', max_height: 150, content_style: 'body { font-family: Arial; }', }, };
mukesh-openchannel/angular-template-libraries
projects/angular-common-components/src/lib/market-components/oc-app-get-started/oc-app-get-started.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { HeadingTag } from '@openchannel/angular-common-components/src/lib/common-components'; @Component({ selector: 'oc-app-get-started', templateUrl: './oc-app-get-started.component.html', styleUrls: ['./oc-app-get-started.component.css'], }) export class OcAppGetStartedComponent { /** Path to the main image of the component */ @Input() getStartedImage: string = 'assets/angular-common-components/get-started.svg'; /** * Main title of the component. * @default: 'List Your App in our App Store' */ @Input() getStartedHeader: string = 'List Your App in our App Store'; /** * Heading tag of header [getStartedHeader]{@link getStartedHeader} * @type {HeadingTag}. * @example. * 'h2'. */ @Input() getStartedHeadingTag: HeadingTag = 'h3'; /** * Main text of the component. Placed under title */ @Input() getStartedDescription: string = ''; /** * Main text of the component. Placed under title */ @Input() getStartedButtonText: string = ''; /** * Get Started component type. * * `home` type represents button, image and description. * * `search` type represents title and button. * @default 'home' */ @Input() getStartedType: 'home' | 'search' = 'home'; /** * Emmit click on the button of the component. * * Returns: {void} */ @Output() readonly getStarted: EventEmitter<void> = new EventEmitter<void>(); /** * This function triggers by click on the button of the component and emmit info that the button was pressed */ listAppGetStarted(): void { this.getStarted.emit(); } }
mukesh-openchannel/angular-template-libraries
projects/angular-common-services/src/lib/service/site-config.service.ts
import { Injectable } from '@angular/core'; import { Meta, MetaDefinition } from '@angular/platform-browser'; import { Observable } from 'rxjs/internal/Observable'; import { of, Subject } from 'rxjs'; import { map } from 'rxjs/operators'; import { SiteConfig } from '../model/components/frontend.model'; import { TitleService } from './title.service'; /** * Description: Service for setting up site config.<br> * * @param {string} siteConfig * * Methods: * * setMeta - set meta tags from the config array * * setFavicon - set favicon from the config * * initSiteConfiguration */ @Injectable({ providedIn: 'root', }) export class SiteConfigService { siteConfig: SiteConfig; private siteConfigSetupTrigger: Subject<void> = new Subject<void>(); constructor(private titleService: TitleService, private metaService: Meta) {} /** * Description: Set up meta tags for the site * @param {MetaDefinition[]} metaTags array of the meta tags that will be set on the current site * * * ### Example * ``` * const meta = [ * { * id: "customDescription", * name: "description", * content: "some description" * }, * { * id: "authorMeta", * name: "author", * content: "OpenChannel" * } * ] * * * setMeta(meta) * ``` */ setMeta(metaTags: MetaDefinition[]): void { this.metaService.addTags(metaTags); } /** * Description: Set up the favicon for the app * * @param {string} customPath - (optional) path to the favicon icon * @param {string} customIconType - (optional) type of the favicon icon. Default: 'image/x-icon' * @returns {void} * * ### Example * `` * setFavicon('/path/img', 'png') * `` */ setFavicon(customPath?: string, customIconType?: string): void { const iconLink: HTMLLinkElement = document.querySelector('#custom-favicon'); const type = customIconType ? customIconType : this.siteConfig.favicon.type ? this.siteConfig.favicon.type : 'image/x-icon'; const value = customPath ? customPath : this.siteConfig.favicon.href; if (iconLink) { iconLink.href = value; iconLink.type = type; } else { const linkElement = document.createElement('link'); linkElement.setAttribute('id', 'custom-favicon'); linkElement.setAttribute('rel', 'icon'); linkElement.setAttribute('type', type); linkElement.setAttribute('href', value); document.head.appendChild(linkElement); } } /** * Description: Set up a site by the Site Config * * @param {SiteConfig} config - Set initial site configuration * @returns {void} * * ### Example * `` * initSiteConfiguration({ * title: 'title'; * tagline: 'some'; * metaTags: Array<{ * charset: 'some string', * content: 'some string', * httpEquiv: 'some string', * id: 'some string', * itemprop: 'some string', * name: 'some string', * property: 'some string', * scheme: 'some string', * url: 'some string' * }>; * favicon: { * href: '/img' ; * type?: 'png'; * }; * }) * `` */ initSiteConfiguration(config: SiteConfig): void { this.siteConfig = config; this.titleService.title = this.siteConfig.title; this.setMeta(config.metaTags); this.setFavicon(); this.siteConfigSetupTrigger.next(); } getSiteConfigAsObservable(): Observable<SiteConfig> { return this.siteConfig ? of(this.siteConfig) : this.siteConfigSetupTrigger.pipe(map(() => this.siteConfig)); } }