repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
nitesh55/assignment-wednesday
node_modules/@formatjs/intl-numberformat/lib/intl-numberformat.d.ts
<filename>node_modules/@formatjs/intl-numberformat/lib/intl-numberformat.d.ts import { NumberFormatDigitInternalSlots } from '@formatjs/intl-utils'; import { NumberFormatDigitOptions } from '@formatjs/intl-utils'; import { NumberFormatLocaleInternalData } from '@formatjs/intl-utils'; import { NumberFormatNotation } from '@formatjs/intl-utils'; import { RawNumberLocaleData } from '@formatjs/intl-utils'; /** * Check if a formatting number with unit is supported * @public * @param unit unit to check */ export declare function isUnitSupported(unit: string): boolean; export declare type NumberFormat = import('./types').NumberFormat; /** * https://tc39.es/ecma402/#sec-intl-numberformat-constructor */ export declare const NumberFormat: NumberFormatConstructor; declare interface NumberFormat_2 { resolvedOptions(): ResolvedNumberFormatOptions; formatToParts(x: number): NumberFormatPart[]; format(x: number): string; } declare interface NumberFormatConstructor { new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat_2; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat_2; __addLocaleData(...data: RawNumberLocaleData[]): void; supportedLocalesOf(locales: string | string[], options?: Pick<NumberFormatOptions, 'localeMatcher'>): string[]; getDefaultLocale(): string; __defaultLocale: string; localeData: Record<string, NumberFormatLocaleInternalData>; availableLocales: string[]; polyfilled: boolean; } declare interface NumberFormatInternal extends NumberFormatDigitInternalSlots { locale: string; dataLocale: string; style: NumberFormatOptionsStyle; currency?: string; currencyDisplay: NumberFormatOptionsCurrencyDisplay; unit?: string; unitDisplay: NumberFormatOptionsUnitDisplay; currencySign: NumberFormatOptionsCurrencySign; notation: NumberFormatOptionsNotation; compactDisplay: NumberFormatOptionsCompactDisplay; signDisplay: NumberFormatOptionsSignDisplay; useGrouping: boolean; pl: Intl.PluralRules; boundFormat?: Intl.NumberFormat['format']; numberingSystem: string; dataLocaleData: NumberFormatLocaleInternalData; } export declare type NumberFormatOptions = Intl.NumberFormatOptions & NumberFormatDigitOptions & { localeMatcher?: NumberFormatOptionsLocaleMatcher; style?: NumberFormatOptionsStyle; compactDisplay?: NumberFormatOptionsCompactDisplay; currencyDisplay?: NumberFormatOptionsCurrencyDisplay; currencySign?: NumberFormatOptionsCurrencySign; notation?: NumberFormatOptionsNotation; signDisplay?: NumberFormatOptionsSignDisplay; unit?: string; unitDisplay?: NumberFormatOptionsUnitDisplay; numberingSystem?: string; }; declare type NumberFormatOptionsCompactDisplay = 'short' | 'long'; declare type NumberFormatOptionsCurrencyDisplay = 'symbol' | 'code' | 'name' | 'narrowSymbol'; declare type NumberFormatOptionsCurrencySign = 'standard' | 'accounting'; declare type NumberFormatOptionsLocaleMatcher = 'lookup' | 'best fit'; declare type NumberFormatOptionsNotation = NumberFormatNotation; declare type NumberFormatOptionsSignDisplay = 'auto' | 'always' | 'never' | 'exceptZero'; declare type NumberFormatOptionsStyle = 'decimal' | 'percent' | 'currency' | 'unit'; declare type NumberFormatOptionsUnitDisplay = 'long' | 'short' | 'narrow'; declare interface NumberFormatPart { type: NumberFormatPartTypes; value: string; } declare type NumberFormatPartTypes = Intl.NumberFormatPartTypes | 'exponentSeparator' | 'exponentMinusSign' | 'exponentInteger' | 'compact' | 'unit' | 'literal'; declare type ResolvedNumberFormatOptions = Intl.ResolvedNumberFormatOptions & Pick<NumberFormatInternal, 'currencySign' | 'unit' | 'unitDisplay' | 'notation' | 'compactDisplay' | 'signDisplay'>; /** * Number.prototype.toLocaleString ponyfill * https://tc39.es/ecma402/#sup-number.prototype.tolocalestring */ export declare function toLocaleString(x: number, locales?: string | string[], options?: NumberFormatOptions): string; export { }
nitesh55/assignment-wednesday
node_modules/@formatjs/intl-utils/dist/index.d.ts
export { selectUnit } from './diff'; export { defaultNumberOption, getInternalSlot, getMultiInternalSlots, getNumberOption, getOption, isLiteralPart, LiteralPart, partitionPattern, setInternalSlot, setMultiInternalSlots, setNumberFormatDigitOptions, toObject, objectIs, isWellFormedCurrencyCode, toString, formatNumericToString, toRawFixed, toRawPrecision, getMagnitude, repeat, hasOwnProperty, isWellFormedUnitIdentifier, defineProperty, } from './polyfill-utils'; export { createResolveLocale, getLocaleHierarchy, supportedLocales, unpackData, isMissingLocaleDataError, } from './resolve-locale'; export * from './units'; export * from './relative-time-types'; export * from './list-types'; export * from './plural-rules-types'; export * from './number-types'; export * from './displaynames-types'; export { removeUnitNamespace } from './units'; export { invariant } from './invariant'; //# sourceMappingURL=index.d.ts.map
nitesh55/assignment-wednesday
node_modules/react-intl/src/formatters/message.ts
<reponame>nitesh55/assignment-wednesday<filename>node_modules/react-intl/src/formatters/message.ts /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. * See the accompanying LICENSE file for terms. */ import * as React from 'react'; import {invariant} from '@formatjs/intl-utils'; import { Formatters, IntlConfig, MessageDescriptor, CustomFormats, } from '../types'; import IntlMessageFormat, { FormatXMLElementFn, PrimitiveType, } from 'intl-messageformat'; import {MessageFormatError, MissingTranslationError} from '../error'; function setTimeZoneInOptions( opts: Record<string, Intl.DateTimeFormatOptions>, timeZone: string ): Record<string, Intl.DateTimeFormatOptions> { return Object.keys(opts).reduce( (all: Record<string, Intl.DateTimeFormatOptions>, k) => { all[k] = { timeZone, ...opts[k], }; return all; }, {} ); } function deepMergeOptions( opts1: Record<string, Intl.DateTimeFormatOptions>, opts2: Record<string, Intl.DateTimeFormatOptions> ): Record<string, Intl.DateTimeFormatOptions> { const keys = Object.keys({...opts1, ...opts2}); return keys.reduce((all: Record<string, Intl.DateTimeFormatOptions>, k) => { all[k] = { ...(opts1[k] || {}), ...(opts2[k] || {}), }; return all; }, {}); } function deepMergeFormatsAndSetTimeZone( f1: CustomFormats, timeZone?: string ): CustomFormats { if (!timeZone) { return f1; } const mfFormats = IntlMessageFormat.formats; return { ...mfFormats, ...f1, date: deepMergeOptions( setTimeZoneInOptions(mfFormats.date, timeZone), setTimeZoneInOptions(f1.date || {}, timeZone) ), time: deepMergeOptions( setTimeZoneInOptions(mfFormats.time, timeZone), setTimeZoneInOptions(f1.time || {}, timeZone) ), }; } function prepareIntlMessageFormatHtmlOutput( chunks: React.ReactNode, shouldWrap?: boolean ): React.ReactNode { return Array.isArray(chunks) && shouldWrap ? React.createElement(React.Fragment, null, ...chunks) : chunks; } export function formatMessage( { locale, formats, messages, defaultLocale, defaultFormats, onError, }: Pick< IntlConfig, | 'locale' | 'formats' | 'messages' | 'defaultLocale' | 'defaultFormats' | 'onError' >, state: Formatters, messageDescriptor?: MessageDescriptor, values?: Record<string, PrimitiveType> ): string; export function formatMessage( { locale, formats, messages, defaultLocale, defaultFormats, onError, timeZone, wrapRichTextChunksInFragment, }: Pick< IntlConfig, | 'locale' | 'formats' | 'messages' | 'defaultLocale' | 'defaultFormats' | 'onError' | 'timeZone' | 'wrapRichTextChunksInFragment' >, state: Formatters, messageDescriptor: MessageDescriptor = {id: ''}, values: | Record< string, | React.ReactNode | Date | FormatXMLElementFn<React.ReactNode, React.ReactNode> > | undefined ): React.ReactNode { const {id, defaultMessage} = messageDescriptor; // `id` is a required field of a Message Descriptor. invariant(!!id, '[React Intl] An `id` must be provided to format a message.'); const message = messages && messages[String(id)]; // IMPORTANT: Hot path straight lookup for performance if (!values && message && typeof message === 'string') { return message.replace(/'\{(.*?)\}'/gi, `{$1}`); } formats = deepMergeFormatsAndSetTimeZone(formats, timeZone); defaultFormats = deepMergeFormatsAndSetTimeZone(defaultFormats, timeZone); if (!message) { if ( !defaultMessage || (locale && locale.toLowerCase() !== defaultLocale.toLowerCase()) ) { // This prevents warnings from littering the console in development // when no `messages` are passed into the <IntlProvider> for the // default locale. onError(new MissingTranslationError(messageDescriptor, locale)); } if (defaultMessage) { try { const formatter = state.getMessageFormat( defaultMessage, defaultLocale, defaultFormats ); return prepareIntlMessageFormatHtmlOutput( formatter.format(values), wrapRichTextChunksInFragment ); } catch (e) { onError( new MessageFormatError( `Error formatting default message for: "${id}", rendering default message verbatim`, locale, messageDescriptor, e ) ); return defaultMessage; } } return id; } // We have the translated message try { const formatter = state.getMessageFormat(message, locale, formats, { formatters: state, }); return prepareIntlMessageFormatHtmlOutput( formatter.format<React.ReactNode>(values), wrapRichTextChunksInFragment ); } catch (e) { onError( new MessageFormatError( `Error formatting message: "${id}", using ${ defaultMessage ? 'default message' : 'id' } as fallback.`, locale, messageDescriptor, e ) ); } if (defaultMessage) { try { const formatter = state.getMessageFormat( defaultMessage, defaultLocale, defaultFormats ); return prepareIntlMessageFormatHtmlOutput( formatter.format(values), wrapRichTextChunksInFragment ); } catch (e) { onError( new MessageFormatError( `Error formatting the default message for: "${id}", rendering message verbatim`, locale, messageDescriptor, e ) ); } } return message || defaultMessage || id; }
CharlesGuillot/angular-instantsearch
src/search-box/__tests__/search-box.spec.ts
<reponame>CharlesGuillot/angular-instantsearch import { createRenderer } from "../../../helpers/test-renderer"; import { NgAisSearchBox } from "../search-box"; const defaultState = { query: "foo", refine: jest.fn() }; const render = createRenderer({ defaultState, template: "<ais-search-box></ais-search-box>", TestedWidget: NgAisSearchBox }); // FIXME: find way to render SVG describe("SearchBox", () => { it.skip("renders markup without state", () => { const fixture = render(); expect(fixture).toMatchSnapshot(); }); it.skip("renders markup with state", () => { const fixture = render({}); expect(fixture).toMatchSnapshot(); }); });
CharlesGuillot/angular-instantsearch
examples/angular-router/src/app/components/menu-select/menu-select.component.ts
<reponame>CharlesGuillot/angular-instantsearch import { Component, Inject, forwardRef } from "@angular/core"; import { BaseWidget, NgAisInstantSearch } from "angular-instantsearch"; import { connectMenu } from "instantsearch.js/es/connectors"; @Component({ selector: "ais-menu-select", template: ` <select class="menu-select" (change)="state.refine($event.target.value)" > <option *ngFor="let item of state.items" [value]="item.value" [selected]="item.isRefined" > {{item.label}} </option> </select> ` }) export class MenuSelect extends BaseWidget { state: { items: { label: string; value: string }[]; createURL: () => string; refine: (value: string) => void; canRefine: boolean; isShowingMore: boolean; toggleShowMore: () => void; canToggleShowMore: boolean; }; constructor( @Inject(forwardRef(() => NgAisInstantSearch)) public instantSearchParent: any ) { super("MenuSelect"); } public ngOnInit() { this.createWidget(connectMenu, { attributeName: "materials" }); super.ngOnInit(); } }
IIPEKOLICT/express-lambda
src/controllers/file.controller.ts
<gh_stars>0 import { NextFunction, Request, Response } from 'express'; import { safeCall } from '../shared/decorators'; import ApiError from '../errors/api.error'; import { ErrorMessage } from '../shared/enums'; import S3Service from '../services/s3.service'; import { UploadedFile } from 'express-fileupload'; import { extname } from 'path'; import { JSON_EXT } from '../shared/constants'; export default class FileController { @safeCall(ApiError.internal(ErrorMessage.File)) static async getFile(req: Request, res: Response, next: NextFunction) { const { name } = req.params; const isJson = extname(name) === JSON_EXT; let file = await S3Service.loadFile(name); if (isJson) { file = JSON.parse(file); } return res.json(file); } @safeCall(ApiError.internal(ErrorMessage.File)) static async uploadFile(req: Request, res: Response, next: NextFunction) { let file: UploadedFile | UploadedFile[] = req.files.data; if (Array.isArray(file)) { file = file[0]; } const location: string = await S3Service.uploadFile(file.name, file.data); return res.json({ location, url: `/file/${file.name}` }); } }
IIPEKOLICT/express-lambda
src/routes/attendee.ts
import { Router} from 'express'; import AttendeeController from '../controllers/attendee.controller'; const attendeeRouter = Router(); attendeeRouter.post('/', AttendeeController.addAttendee); attendeeRouter.patch('/', AttendeeController.attendeePhraseAssignment); attendeeRouter.put('/', AttendeeController.mergeAttendees); export default attendeeRouter;
IIPEKOLICT/express-lambda
src/middlewares/error.middleware.ts
<reponame>IIPEKOLICT/express-lambda import { NextFunction, Request, Response } from 'express'; import { ErrorCode, ErrorMessage } from '../shared/enums'; import ApiError from '../errors/api.error'; export default function errorMiddleware(err: Error, req: Request, res: Response, next: NextFunction) { const { message, name } = err; if (err instanceof ApiError) { return res.status(err.status).json({ status: err.status, message, name }); } return res.status(ErrorCode.InternalServerError).json({ message: ErrorMessage.Unknown, name }); }
IIPEKOLICT/express-lambda
src/routes/index.ts
<reponame>IIPEKOLICT/express-lambda import { Router } from 'express'; import testRouter from './test'; import attendeeRouter from './attendee'; import fileRouter from './file'; const apiRouter = Router(); apiRouter.use('/', testRouter); apiRouter.use('/attendee', attendeeRouter); apiRouter.use('/file', fileRouter); export default apiRouter;
IIPEKOLICT/express-lambda
src/shared/models.ts
export type Replica = { Index: number, Text: string, Speaker: string, Type: string, [property: string]: any, } export type Attendee = { attendee: string, Name: string, email: string, is_host: boolean, [property: string]: any, } export type Data = { transcript: Replica[]; attendees: Attendee[]; }
IIPEKOLICT/express-lambda
src/app.ts
import express from 'express'; import cors from 'cors'; import { config } from 'dotenv'; import apiRouter from './routes'; import errorMiddleware from './middlewares/error.middleware'; import { resolve } from 'path'; import fileUpload from 'express-fileupload'; config(); export const createApp = () => { const app = express(); app.use(cors()); app.use(express.json()); app.use(fileUpload()); app.use(express.static(resolve(__dirname, '..', 'public'))); app.use('/', apiRouter); app.use(errorMiddleware); return app; }
IIPEKOLICT/express-lambda
src/routes/file.ts
import { Router } from 'express'; import FileController from '../controllers/file.controller'; const fileRouter = Router(); fileRouter.get('/:name', FileController.getFile); fileRouter.post('/', FileController.uploadFile); export default fileRouter;
IIPEKOLICT/express-lambda
src/local.ts
import { createApp } from './app'; import { LOCAL_PORT } from './shared/constants'; createApp().listen(LOCAL_PORT, () => console.log(`Server started on port ${LOCAL_PORT}`));
IIPEKOLICT/express-lambda
src/controllers/attendee.controller.ts
import { NextFunction, Request, Response } from 'express'; import { Data, Replica } from '../shared/models'; import { safeCall } from '../shared/decorators'; import ApiError from '../errors/api.error'; import { ErrorMessage } from '../shared/enums'; import S3Service from '../services/s3.service'; import { DATA_FILE } from '../shared/constants'; import { Attendee } from '../dist/express-lambda'; export default class AttendeeController { @safeCall() static async addAttendee(req: Request, res: Response, next: NextFunction) { const { Name, email, is_host, ...fields } = req.body; const data: Data = JSON.parse(await S3Service.loadFile(DATA_FILE)); const attendeeId = Math.max( ...data.attendees.map( (attendee: Attendee) => +attendee.attendee.slice(4) ) ) + 1; data.attendees.push({ Name, email, is_host, attendee: `spk_${attendeeId}`, ...fields, }); await S3Service.uploadFile(DATA_FILE, new Buffer(JSON.stringify(data))); return res.json(data); } @safeCall(ApiError.badRequest(ErrorMessage.InvalidData)) static async attendeePhraseAssignment( req: Request, res: Response, next: NextFunction ) { let { attendeeId, blocks } = req.body; const data: Data = JSON.parse(await S3Service.loadFile(DATA_FILE)); if (data.attendees.every(({ attendee }) => attendee !== attendeeId)) { return next(ApiError.badRequest(ErrorMessage.NoAttendee)); } if (!Array.isArray(blocks)) { return next(ApiError.badRequest(ErrorMessage.InvalidData)); } blocks = blocks.map((index: string | number) => +index); data.transcript .filter(({ Index }) => blocks.includes(Index)) .forEach((replica: Replica) => { replica.Speaker = attendeeId; }); await S3Service.uploadFile(DATA_FILE, new Buffer(JSON.stringify(data))); return res.json(data); } @safeCall(ApiError.badRequest(ErrorMessage.InvalidData)) static async mergeAttendees(req: Request, res: Response, next: NextFunction) { let { attendeeId, attendeeToMerge } = req.body; const data: Data = JSON.parse(await S3Service.loadFile(DATA_FILE)); if (data.attendees.every(({ attendee }) => attendee !== attendeeId)) { return next(ApiError.badRequest(ErrorMessage.NoAttendee)); } if (!Array.isArray(attendeeToMerge)) { return next(ApiError.badRequest(ErrorMessage.InvalidData)); } data.transcript .filter(({ Speaker }) => attendeeToMerge.includes(Speaker)) .forEach((replica: Replica) => { replica.Speaker = attendeeId; }); await S3Service.uploadFile(DATA_FILE, new Buffer(JSON.stringify(data))); return res.json(data); } }
IIPEKOLICT/express-lambda
src/aws.ts
import aws, { S3 } from 'aws-sdk'; import { config } from 'dotenv'; config(); aws.config.update({ accessKeyId: process.env.ID, secretAccessKey: process.env.SECRET, }); export const s3 = new S3(); export const bucketName: string = process.env.BUCKET_NAME;
IIPEKOLICT/express-lambda
src/lambda.ts
<gh_stars>0 import { createServer, proxy } from 'aws-serverless-express'; import { APIGatewayProxyEvent, Context } from 'aws-lambda'; import { createApp } from './app'; const server = createServer(createApp(), undefined); export default function(event: APIGatewayProxyEvent, context: Context) { console.log(`Event: ${JSON.stringify(event)}`); return proxy(server, event, context); }
IIPEKOLICT/express-lambda
src/shared/enums.ts
export enum ErrorCode { Unauthorized = 401, Forbidden = 403, NotFound = 404, InternalServerError = 500, } export enum ErrorMessage { Unknown = 'Unknown error', File = 'File error', NoAttendee = 'Attendee with this id don`t exists', InvalidData = 'Invalid request data' }
IIPEKOLICT/express-lambda
src/shared/decorators.ts
import ApiError from '../errors/api.error'; import { NextFunction, Request, Response } from 'express'; export function safeCall(error?: ApiError): MethodDecorator { return function ( target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor ): void { const original = descriptor.value; descriptor.value = async function ( req: Request, res: Response, next: NextFunction ) { try { await original.call(target, req, res, next); } catch (e) { return next(error || e); } }; }; }
IIPEKOLICT/express-lambda
src/services/s3.service.ts
<gh_stars>0 import { s3, bucketName } from '../aws'; export default class S3Service { static async loadFile(fileName: string): Promise<any> { try { const data = await s3.getObject({ Bucket: bucketName, Key: fileName }); return (await data.promise()).Body.toString('utf8'); } catch (e) { throw `File load error: ${e.message}`; } } static async uploadFile(fileName: string, fileContent: Buffer): Promise<string> { try { const data = await s3.upload({ Bucket: bucketName, Key: fileName, Body: fileContent }); const result = await data.promise(); return result.Location; } catch (e) { throw `File upload error: ${e.message}`; } } }
IIPEKOLICT/express-lambda
src/services/file.service.ts
// import { Data } from '../shared/models'; // import { writeFile, readFile } from 'fs/promises'; // import { FILE_PATH } from '../shared/constants'; // // export default class FileService { // static async readFile(): Promise<Data> { // try { // return JSON.parse((await readFile(FILE_PATH)).toString()); // } catch (e) { // throw `File read error: ${e.message}`; // } // } // // static async writeFile(data: Data): Promise<void> { // try { // await writeFile(FILE_PATH, JSON.stringify(data), { flag: 'w+' }); // } catch (e) { // throw `File write error: ${e.message}`; // } // } // }
IIPEKOLICT/express-lambda
src/shared/constants.ts
export const LOCAL_PORT = 5000; export const DATA_FILE = 'data.json'; export const JSON_EXT = '.json';
IIPEKOLICT/express-lambda
src/routes/test.ts
<filename>src/routes/test.ts import { NextFunction, Request, Response, Router } from 'express'; const testRouter = Router(); testRouter.get('/', async (req: Request, res: Response, next: NextFunction) => { return res.json({ message: 'api worked' }); }); export default testRouter;
hanming2033/typescript-graphql-server
src/types/schema.d.ts
<filename>src/types/schema.d.ts // tslint:disable // graphql typescript definitions declare namespace GQL { interface IGraphQLResponseRoot { data?: IQuery | IMutation; errors?: Array<IGraphQLResponseError>; } interface IGraphQLResponseError { /** Required for all errors */ message: string; locations?: Array<IGraphQLResponseErrorLocation>; /** 7.2.2 says 'GraphQL servers may provide additional entries to error' */ [propName: string]: any; } interface IGraphQLResponseErrorLocation { line: number; column: number; } interface IQuery { __typename: 'Query'; info: string; feed: Array<ILink>; link: ILink | null; } interface ILinkOnQueryArguments { id: string; } interface ILink { __typename: 'Link'; id: string; description: string; url: string; } interface IMutation { __typename: 'Mutation'; post: ILink; updateLink: ILink | null; deleteLink: ILink | null; } interface IPostOnMutationArguments { url: string; description: string; } interface IUpdateLinkOnMutationArguments { id: string; url?: string | null; description?: string | null; } interface IDeleteLinkOnMutationArguments { id: string; } } // tslint:enable
hanming2033/typescript-graphql-server
src/data/resolvers.ts
// https://github.com/kelektiv/node.bcrypt.js/ // import * as bcrypt from 'bcryptjs' export interface IResolverMap { readonly [key: string]: { readonly [key: string]: (parent: any, args: any, context: {}, info: any) => any } } // tslint:disable-next-line:no-let readonly-array prefer-const readonly-keyword let links: Array<{ id: string; url: string; description: string }> = [ { id: 'link-0', url: 'www.howtographql.com', description: 'Fullstack tutorial for GraphQL' } ] // tslint:disable-next-line:no-let let idCount = links.length export const resolvers: IResolverMap = { // query resolvers: graphql will run all the resolvers // for every nested level of query Query: { info: () => `This is the API of a Hackernews Clone`, // when calling feed, it will return the links(defined elsewhere in this case) feed: () => links, link: (_, args: GQL.ILinkOnQueryArguments) => links.find(link => link.id === args.id) }, Mutation: { post: (_, args: GQL.IPostOnMutationArguments) => { const link = { id: `link-${idCount++}`, description: args.description, url: args.url } // tslint:disable-next-line:no-expression-statement links.push(link) return link }, updateLink: (_, args: GQL.IUpdateLinkOnMutationArguments) => { const linkToUpdate = links.find(link => link.id === args.id) // tslint:disable-next-line:no-if-statement if (!linkToUpdate) return null // tslint:disable-next-line:no-expression-statement no-object-mutation linkToUpdate.description = args.description ? args.description : linkToUpdate.description // tslint:disable-next-line:no-expression-statement no-object-mutation linkToUpdate.url = args.url ? args.url : linkToUpdate.url return linkToUpdate }, deleteLink: (_, args: GQL.IDeleteLinkOnMutationArguments) => { const linkToDelete = links.find(link => link.id === args.id) const index = links.findIndex(link => link.id === args.id) // tslint:disable-next-line:no-expression-statement links.splice(index, 1) return linkToDelete } } }
hanming2033/typescript-graphql-server
src/index.ts
<reponame>hanming2033/typescript-graphql-server<filename>src/index.ts import { GraphQLServer } from 'graphql-yoga' import { resolvers } from './data/resolvers' const server = new GraphQLServer({ typeDefs: './src/data/schema.graphql', resolvers }) // tslint:disable-next-line:no-expression-statement server.start(() => console.log('Server is running on localhost:4000')) // uuid: https://github.com/kelektiv/node-uuid import { v4 as uuidv4 } from 'uuid' export const uid = uuidv4()
bpauley14/word-guessing-game
src/App.tsx
<reponame>bpauley14/word-guessing-game import { InformationCircleIcon, ChartBarIcon, SunIcon, } from '@heroicons/react/outline' import { useState, useEffect } from 'react' import { Alert } from './components/alerts/Alert' import { Grid } from './components/grid/Grid' import { Keyboard } from './components/keyboard/Keyboard' import { AboutModal } from './components/modals/AboutModal' import { InfoModal } from './components/modals/InfoModal' import { StatsModal } from './components/modals/StatsModal' import { GAME_TITLE, WIN_MESSAGES, GAME_COPIED_MESSAGE, ABOUT_GAME_MESSAGE, NOT_ENOUGH_LETTERS_MESSAGE, WORD_NOT_FOUND_MESSAGE, CORRECT_WORD_MESSAGE, } from './constants/strings' import { isWordInWordList, isWinningWord, solution } from './lib/words' import { addStatsForCompletedGame, loadStats } from './lib/stats' import { loadGameStateFromLocalStorage, saveGameStateToLocalStorage, } from './lib/localStorage' import './App.css' const ALERT_TIME_MS = 2000 function App() { const prefersDarkMode = window.matchMedia( '(prefers-color-scheme: dark)' ).matches const [currentGuess, setCurrentGuess] = useState('') const [isGameWon, setIsGameWon] = useState(false) const [isInfoModalOpen, setIsInfoModalOpen] = useState(false) const [isAboutModalOpen, setIsAboutModalOpen] = useState(false) const [isNotEnoughLetters, setIsNotEnoughLetters] = useState(false) const [isStatsModalOpen, setIsStatsModalOpen] = useState(false) const [isWordNotFoundAlertOpen, setIsWordNotFoundAlertOpen] = useState(false) const [isGameLost, setIsGameLost] = useState(false) const [isDarkMode, setIsDarkMode] = useState( localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : prefersDarkMode ? true : false ) const [successAlert, setSuccessAlert] = useState('') const [guesses, setGuesses] = useState<string[]>(() => { const loaded = loadGameStateFromLocalStorage() if (loaded?.solution !== solution) { return [] } const gameWasWon = loaded.guesses.includes(solution) if (gameWasWon) { setIsGameWon(true) } if (loaded.guesses.length === 6 && !gameWasWon) { setIsGameLost(true) } return loaded.guesses }) const [stats, setStats] = useState(() => loadStats()) useEffect(() => { if (isDarkMode) { document.documentElement.classList.add('dark') } else { document.documentElement.classList.remove('dark') } }, [isDarkMode]) const handleDarkMode = (isDark: boolean) => { setIsDarkMode(isDark) localStorage.setItem('theme', isDark ? 'dark' : 'light') } useEffect(() => { saveGameStateToLocalStorage({ guesses, solution }) }, [guesses]) useEffect(() => { if (isGameWon) { setSuccessAlert( WIN_MESSAGES[Math.floor(Math.random() * WIN_MESSAGES.length)] ) setTimeout(() => { setSuccessAlert('') setIsStatsModalOpen(true) }, ALERT_TIME_MS) } if (isGameLost) { setTimeout(() => { setIsStatsModalOpen(true) }, ALERT_TIME_MS) } }, [isGameWon, isGameLost]) const onChar = (value: string) => { if (currentGuess.length < 6 && guesses.length < 6 && !isGameWon) { setCurrentGuess(`${currentGuess}${value}`) } } const onDelete = () => { setCurrentGuess(currentGuess.slice(0, -1)) } const onEnter = () => { if (isGameWon || isGameLost) { return } if (!(currentGuess.length === 6)) { setIsNotEnoughLetters(true) return setTimeout(() => { setIsNotEnoughLetters(false) }, ALERT_TIME_MS) } if (!isWordInWordList(currentGuess)) { setIsWordNotFoundAlertOpen(true) return setTimeout(() => { setIsWordNotFoundAlertOpen(false) }, ALERT_TIME_MS) } const winningWord = isWinningWord(currentGuess) if (currentGuess.length === 6 && guesses.length < 6 && !isGameWon) { setGuesses([...guesses, currentGuess]) setCurrentGuess('') if (winningWord) { setStats(addStatsForCompletedGame(stats, guesses.length)) return setIsGameWon(true) } if (guesses.length === 5) { setStats(addStatsForCompletedGame(stats, guesses.length + 1)) setIsGameLost(true) } } } return ( <div className="py-8 max-w-7xl mx-auto sm:px-6 lg:px-8"> <div className="flex w-80 mx-auto items-center mb-8 mt-12"> <h1 className="text-xl grow font-bold dark:text-white">{GAME_TITLE}</h1> <SunIcon className="h-6 w-6 cursor-pointer dark:stroke-white" onClick={() => handleDarkMode(!isDarkMode)} /> <InformationCircleIcon className="h-6 w-6 cursor-pointer dark:stroke-white" onClick={() => setIsInfoModalOpen(true)} /> <ChartBarIcon className="h-6 w-6 cursor-pointer dark:stroke-white" onClick={() => setIsStatsModalOpen(true)} /> </div> <Grid guesses={guesses} currentGuess={currentGuess} /> <Keyboard onChar={onChar} onDelete={onDelete} onEnter={onEnter} guesses={guesses} /> <InfoModal isOpen={isInfoModalOpen} handleClose={() => setIsInfoModalOpen(false)} /> <StatsModal isOpen={isStatsModalOpen} handleClose={() => setIsStatsModalOpen(false)} guesses={guesses} gameStats={stats} isGameLost={isGameLost} isGameWon={isGameWon} handleShare={() => { setSuccessAlert(GAME_COPIED_MESSAGE) return setTimeout(() => setSuccessAlert(''), ALERT_TIME_MS) }} /> <AboutModal isOpen={isAboutModalOpen} handleClose={() => setIsAboutModalOpen(false)} /> <button type="button" className="mx-auto mt-8 flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 select-none" onClick={() => setIsAboutModalOpen(true)} > {ABOUT_GAME_MESSAGE} </button> <Alert message={NOT_ENOUGH_LETTERS_MESSAGE} isOpen={isNotEnoughLetters} /> <Alert message={WORD_NOT_FOUND_MESSAGE} isOpen={isWordNotFoundAlertOpen} /> <Alert message={CORRECT_WORD_MESSAGE(solution)} isOpen={isGameLost} /> <Alert message={successAlert} isOpen={successAlert !== ''} variant="success" /> </div> ) } export default App
KarinaFernandez/GastosAngular
Gastos/src/app/register/register.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { UserService } from '../services/user.service'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { registerForm; errMsg; constructor( private formBuilder: FormBuilder, private userService: UserService, private router: Router, ) { this.registerForm = this.formBuilder.group({ email: '', password: '' }); } ngOnInit() {} onSubmit(registerData) { this.errMsg = undefined; this.registerForm.reset(); console.warn("Register information", registerData); const { email, password } = registerData; if (email == "" || password == "") { this.errMsg = "Por favor valide los datos ingresados" } else { // Call to service and if is okey redirect this.userService.register(email, password).subscribe(user => { this.userService.setUser(user); console.log(user); this.router.navigate(['/expenses']); }, err => { if (err.status === 409) { this.errMsg = 'Ya existe un usuario registrado con ese nombre'; } }); } } }
KarinaFernandez/GastosAngular
Gastos/src/app/expense-list/expense-list.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ExpenseServiceService } from '../services/expense.service'; @Component({ selector: 'app-expense-list', templateUrl: './expense-list.component.html', styleUrls: ['./expense-list.component.css'] }) export class ExpenseListComponent implements OnInit { todosGastos; gastos = []; titulos = []; total; errMsg; constructor( private expenseService: ExpenseServiceService, private router: Router, ) { } ngOnInit() { this.getExpenses(); } getExpenses() { this.expenseService.getExpenses().subscribe((a: any) => { this.expenseService.setExpenses(a.gastos); this.todosGastos = a.gastos; this.gastos = this.todosGastos.slice(0, 10); this.getLastExpensesAmount(); }) } getLastExpensesAmount() { let suma = 0; this.gastos.forEach(gasto => { let monto = parseInt(gasto.monto, 10); suma += monto; }); this.total = suma; if (this.gastos.length > 0) { this.titulos = ["Nombre", "Monto", ""]; } } addExpense() { this.router.navigate(['/addExpense']); } removeExpense(index) { let idGasto = this.todosGastos[index].id this.expenseService.removeExpense(idGasto).subscribe((a: any) => { if (a.codigo == 200) { this.getExpenses(); } else { this.errMsg = a.mensaje; } }) } }
KarinaFernandez/GastosAngular
Gastos/src/app/services/user.service.ts
<reponame>KarinaFernandez/GastosAngular<gh_stars>0 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class UserService { user; constructor( private http: HttpClient ) {} isLoggedIn(){ return !!this.user; } getUser() { return this.user; } setUser(user){ this.user = user; } register(usuario, password){ const headers = { 'Content-Type': 'application/json' }; const body = JSON.stringify({ usuario, password }); return this.http.post("http://xpense.develotion.com/usuarios.php", body,{ headers }) } login(usuario, password) { const headers = { 'Content-Type': 'application/json' }; const body = JSON.stringify({ usuario, password}); return this.http.post("http://xpense.develotion.com/login.php", body,{ headers }); } }
KarinaFernandez/GastosAngular
Gastos/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { TopBarComponent } from './top-bar/top-bar.component'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { ExpenseListComponent } from './expense-list/expense-list.component'; import { AddExpenseComponent } from './add-expense/add-expense.component'; import { ExpensesPerTypeComponent } from './expenses-per-type/expenses-per-type.component'; import { PurchaseByTypeComponent } from './purchase-by-type/purchase-by-type.component'; import { TotalAmountWastedComponent } from './total-amount-wasted/total-amount-wasted.component'; @NgModule({ declarations: [ AppComponent, TopBarComponent, LoginComponent, RegisterComponent, ExpenseListComponent, AddExpenseComponent, ExpensesPerTypeComponent, PurchaseByTypeComponent, TotalAmountWastedComponent ], imports: [ BrowserModule, ReactiveFormsModule, HttpClientModule, RouterModule.forRoot([ { path: '', component: LoginComponent }, { path: 'register', component: RegisterComponent }, { path: 'expenses', component: ExpenseListComponent }, { path: 'addExpense', component: AddExpenseComponent } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
KarinaFernandez/GastosAngular
Gastos/src/app/add-expense/add-expense.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { ExpenseServiceService } from '../services/expense.service'; import { UserService } from '../services/user.service'; @Component({ selector: 'app-add-expense', templateUrl: './add-expense.component.html', styleUrls: ['./add-expense.component.css'] }) export class AddExpenseComponent implements OnInit { rubros; addExpenseForm; errMsg; constructor( private expenseService: ExpenseServiceService, private router: Router, private formBuilder: FormBuilder, private userService: UserService) { this.addExpenseForm = this.formBuilder.group({ name: '', amount: '', expenseType: '' }); } ngOnInit() { this.getExpenseTypes(); } getExpenseTypes() { this.expenseService.getExpenseTypes().subscribe((a: any) => { this.rubros = a.rubros; console.log(a); }) } onSubmit(expenseData) { this.errMsg = undefined; this.addExpenseForm.reset(); console.warn("Expense information", expenseData); const { name, amount, expenseType } = expenseData; if (name == "" || amount == "") { this.errMsg = "Por favor valide los datos ingresados" } else { // Call to service and if is okey redirect this.expenseService.addExpense(name, amount, this.userService.getUser().id, 3).subscribe(expense => { console.log(expense); this.router.navigate(['/expenses']); }, err => { if (err.status === 409) { this.errMsg = 'Valide los datos ingresados'; } }); } } }
KarinaFernandez/GastosAngular
Gastos/src/app/total-amount-wasted/total-amount-wasted.component.ts
<reponame>KarinaFernandez/GastosAngular<filename>Gastos/src/app/total-amount-wasted/total-amount-wasted.component.ts import { Component, OnInit } from '@angular/core'; import { ExpenseServiceService } from '../services/expense.service'; @Component({ selector: 'app-total-amount-wasted', templateUrl: './total-amount-wasted.component.html', styleUrls: ['./total-amount-wasted.component.css'] }) export class TotalAmountWastedComponent implements OnInit { todosGastos; totalGastado = 0; constructor(private expenseService: ExpenseServiceService) { } ngOnInit() { this.getExpenses(); } getExpenses() { /* TODO: Change this service's call by value in service because it's not updated after a changed in main view (ex: remove element) */ this.expenseService.getExpenses().subscribe((a: any) => { this.todosGastos = a.gastos; this.getTotalAmount(); }) } getTotalAmount() { this.totalGastado = this.todosGastos.reduce((n, {monto}) => n + parseInt(monto), 0) } }
KarinaFernandez/GastosAngular
Gastos/src/app/expenses-per-type/expenses-per-type.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { ExpenseServiceService } from '../services/expense.service'; @Component({ selector: 'app-expenses-per-type', templateUrl: './expenses-per-type.component.html', styleUrls: ['./expenses-per-type.component.css'] }) export class ExpensesPerTypeComponent implements OnInit { todosGastos; rubros; errMsg; constructor(private expenseService: ExpenseServiceService) { } ngOnInit() { this.getExpenses(); } getExpenses() { // TODO: Change this service's call by value in service this.expenseService.getExpenses().subscribe((a: any) => { this.todosGastos = a.gastos; this.getSumByExpenseType(); }) } getSumByExpenseType() { var result = this.todosGastos.reduce(function (acc, val) { var o = acc.filter(function (obj) { return obj.rubro == val.rubro; }).pop() || { rubro: val.rubro, monto: 0 }; o.monto += parseInt(val.monto); acc.push(o); return acc; }, []); this.rubros = Array.from(new Set(result)); } }
KarinaFernandez/GastosAngular
Gastos/src/app/purchase-by-type/purchase-by-type.component.ts
import { Component, OnInit } from '@angular/core'; import { ExpenseServiceService } from '../services/expense.service'; @Component({ selector: 'app-purchase-by-type', templateUrl: './purchase-by-type.component.html', styleUrls: ['./purchase-by-type.component.css'] }) export class PurchaseByTypeComponent implements OnInit { todosGastos; rubros = []; constructor(private expenseService: ExpenseServiceService) { } ngOnInit() { this.getExpenses(); } getExpenses() { /* TODO: Change this service's call by value in service because it's not updated after a changed in main view (ex: remove element) */ this.expenseService.getExpenses().subscribe((a: any) => { this.todosGastos = a.gastos; this.getCountByExpenseType(); }) } getCountByExpenseType() { var result = this.todosGastos.reduce(function (acc, val) { var o = acc.filter(function (obj) { return obj.rubro == val.rubro; }).pop() || val.rubro; acc.push(o); return acc; }, []); result.sort(); var current = null; var count = 0; for (var i = 0; i < result.length; i++) { if (result[i] != current) { if (count > 0) { this.rubros.push({ rubro: current, cant: count }); } current = result[i]; count = 1; } else { count++; } } if (count > 0) { this.rubros.push({ rubro: current, cant: count }); } console.log(this.rubros); } }
KarinaFernandez/GastosAngular
Gastos/src/app/services/expense.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { UserService } from './user.service'; @Injectable({ providedIn: 'root' }) export class ExpenseServiceService { expenses = []; types = []; constructor( private http: HttpClient, private userService: UserService ) { } setExpenses(expenses) { this.expenses = expenses; } setExpenseTypes(types) { this.types = types } getExpenses() { const headers = { 'Content-Type': 'application/json', 'apiKey': this.userService.getUser().apiKey }; const params = new HttpParams().append('id', this.userService.getUser().id); return this.http.get("http://xpense.develotion.com/gastos.php", { headers, params }); } getExpenseTypes() { const headers = { 'Content-Type': 'application/json', 'apiKey': this.userService.getUser().apiKey }; return this.http.get("http://xpense.develotion.com/rubros.php", { headers }); } addExpense(nombre, monto, idUsuario, idRubro) { const headers = { 'Content-Type': 'application/json', 'apiKey': this.userService.getUser().apiKey }; const body = JSON.stringify({ nombre, monto, idUsuario, idRubro}); return this.http.post("http://xpense.develotion.com/gastos.php", body,{ headers }); } removeExpense(idGasto) { const headers = { 'Content-Type': 'application/json', 'apiKey': this.userService.getUser().apiKey }; const body = JSON.stringify({ idGasto}); return this.http.request('delete', "http://xpense.develotion.com/gastos.php", { body, headers }); } }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/structures/OperationType.ts
<filename>Node.js/ignite-desafio-tests-challenge/src/modules/statements/structures/OperationType.ts export enum OperationType { DEPOSIT = 'deposit', WITHDRAW = 'withdraw', TRANSFER = 'transfer' }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/createTransfer/ICreateTransferDTO.ts
import { Statement } from "../../entities/Statement"; export type ICreateTransferDTO = { sender_id: string; recipient_id: string; } & Pick< Statement, 'amount' >
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/createTransfer/CreateTransferError.ts
import { AppError } from "../../../../shared/errors/AppError"; export namespace CreateTransferError { export class SenderNotFound extends AppError { constructor() { super('Sender not found', 404); } } export class RecipientNotFound extends AppError { constructor() { super('Recipient not found', 404); } } export class InvalidAmount extends AppError { constructor() { super('Invalid amount', 400); } } export class InsufficientSenderFunds extends AppError { constructor() { super('Insufficient sender funds', 400); } } }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/users/useCases/showUserProfile/ShowUserProfileUseCase.spec.ts
process.env = { JWT_SECRET: 'b69f8a78-d26b-47b1-a9d0-6999f73d06eb' }; import { hash } from "bcryptjs"; import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { ShowUserProfileError } from "./ShowUserProfileError"; import { ShowUserProfileUseCase } from "./ShowUserProfileUseCase"; describe("Show User Profile", () => { let showUserProfileUseCase: ShowUserProfileUseCase; let usersRepository: InMemoryUsersRepository; beforeEach(() => { usersRepository = new InMemoryUsersRepository(); showUserProfileUseCase = new ShowUserProfileUseCase( usersRepository, ); }) it("should show profile for an existing user", async () => { const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: await hash('<PASSWORD>', 8) }); const response = await showUserProfileUseCase.execute( user.id as string ) expect(response).toMatchObject(user); }) it("should not show profile for a non-existing user", async () => { const invalidUserId = 'ed445280-f891-4559-b95a-98308e44f760'; await expect(showUserProfileUseCase.execute( invalidUserId )).rejects.toBeInstanceOf(ShowUserProfileError); }) })
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-introducao-ao-solid/src/modules/users/useCases/listAllUsers/ListAllUsersUseCase.ts
import { User } from "../../model/User"; import { IUsersRepository } from "../../repositories/IUsersRepository"; interface IRequest { user_id: string; } class ListAllUsersUseCase { constructor(private usersRepository: IUsersRepository) {} execute({ user_id }: IRequest): User[] { const currentUser = this.usersRepository.findById(user_id); if (!currentUser) { throw new Error("User not found, cannot list."); } if (!currentUser.admin) { throw new Error("Current user is not an administrator, cannot list."); } return this.usersRepository.list(); } } export { ListAllUsersUseCase };
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/createTransfer/CreateTransferUseCase.spec.ts
import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { InMemoryStatementsRepository } from "../../repositories/in-memory/InMemoryStatementsRepository"; import { CreateTransferUseCase } from "./CreateTransferUseCase" import { CreateTransferError } from "./CreateTransferError"; import { OperationType } from "../../structures/OperationType"; describe("Create Transfer", () => { let createTransferUseCase: CreateTransferUseCase; let usersRepository: InMemoryUsersRepository; let statementsRepository: InMemoryStatementsRepository beforeEach(() => { usersRepository = new InMemoryUsersRepository(); statementsRepository = new InMemoryStatementsRepository(); createTransferUseCase = new CreateTransferUseCase( usersRepository, statementsRepository ); }) it("should transfer when data is valid", async () => { const senderUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); await statementsRepository.create({ user_id: senderUser.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 1000 }) const recipientUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const amount = 100; const transferData = { sender_id: senderUser.id as string, recipient_id: recipientUser.id as string, amount: amount } const response = await createTransferUseCase.execute(transferData); expect(response).toMatchObject({ user_id: senderUser.id, sender_id: senderUser.id, type: OperationType.TRANSFER, recipient_id: recipientUser.id, amount: amount, description: 'Transferência de valor enviada' }) }) it("should not transfer when amount are invalid", async () => { const senderUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); await statementsRepository.create({ user_id: senderUser.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 1000 }) const recipientUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const InvalidAmount = -100; const transferData = { sender_id: senderUser.id as string, recipient_id: recipientUser.id as string, amount: InvalidAmount } await expect(createTransferUseCase.execute(transferData)) .rejects.toBeInstanceOf(CreateTransferError.InvalidAmount) }) it("should not transfer when sender is invalid", async () => { const invalidSenderId = '62935b89-3a67-46ff-9cea-42a9169a4943'; const recipientUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const amount = 100; const transferData = { sender_id: invalidSenderId, recipient_id: recipientUser.id as string, amount: amount } await expect(createTransferUseCase.execute(transferData)) .rejects.toBeInstanceOf(CreateTransferError.SenderNotFound) }) it("should not transfer when recipient is invalid", async () => { const senderUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); await statementsRepository.create({ user_id: senderUser.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 1000 }) const invalidRecipientId = '8538deff-ee25-420e-8e80-2fcad2ff6cb2'; const amount = 100; const transferData = { sender_id: senderUser.id as string, recipient_id: invalidRecipientId, amount: amount } await expect(createTransferUseCase.execute(transferData)) .rejects.toBeInstanceOf(CreateTransferError.RecipientNotFound) }) it("should not transfer when sender has no funds", async () => { const senderUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); await statementsRepository.create({ user_id: senderUser.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 99 }) const recipientUser = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const amount = 100; const transferData = { sender_id: senderUser.id as string, recipient_id: recipientUser.id as string, amount: amount } await expect(createTransferUseCase.execute(transferData)) .rejects.toBeInstanceOf(CreateTransferError.InsufficientSenderFunds) }) })
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/users/useCases/authenticateUser/AuthenticateUserUseCase.spec.ts
<gh_stars>0 process.env = { JWT_SECRET: 'b69f8a78-d26b-47b1-a9d0-6999f73d06eb' }; import { hash } from "bcryptjs"; import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { AuthenticateUserUseCase } from "./AuthenticateUserUseCase"; import { IncorrectEmailOrPasswordError } from "./IncorrectEmailOrPasswordError"; describe("Authenticate User", () => { let authenticateUserUseCase: AuthenticateUserUseCase; let usersRepository: InMemoryUsersRepository; beforeEach(() => { usersRepository = new InMemoryUsersRepository(); authenticateUserUseCase = new AuthenticateUserUseCase( usersRepository, ); }) it("should authenticate an existing user", async () => { const password = '<PASSWORD>'; const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: await hash(password, 8) }); const response = await authenticateUserUseCase.execute({ email: user.email, password }) expect(response.user).toMatchObject({ id: user.id, name: user.name, email: user.email }); }) it("should not authenticate an non-existing user", async () => { const email = '<EMAIL>' const password = '<PASSWORD>'; await expect(authenticateUserUseCase.execute({ email: email, password })).rejects.toBeInstanceOf(IncorrectEmailOrPasswordError); }) it("should authenticate an existing user with incorrect password", async () => { const password = '<PASSWORD>'; const incorrectPassword = '<PASSWORD>' const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: await hash(password, 8) }); await expect(authenticateUserUseCase.execute({ email: user.email, password: <PASSWORD>, })).rejects.toBeInstanceOf(IncorrectEmailOrPasswordError); }) })
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/createTransfer/CreateTransferUseCase.ts
import { inject, injectable } from "tsyringe"; import { IUsersRepository } from "../../../users/repositories/IUsersRepository"; import { IStatementsRepository } from "../../repositories/IStatementsRepository"; import { OperationType } from "../../structures/OperationType"; import { CreateTransferError } from "./CreateTransferError"; import { ICreateTransferDTO } from "./ICreateTransferDTO"; @injectable() export class CreateTransferUseCase { constructor( @inject('UsersRepository') private usersRepository: IUsersRepository, @inject('StatementsRepository') private statementsRepository: IStatementsRepository ) {} async execute({ sender_id, recipient_id, amount }: ICreateTransferDTO) { if (amount < 0) { throw new CreateTransferError.InvalidAmount(); } const sender = await this.usersRepository.findById(sender_id); if(!sender) { throw new CreateTransferError.SenderNotFound(); } const recipient = await this.usersRepository.findById(recipient_id); if(!recipient) { throw new CreateTransferError.RecipientNotFound(); } const { balance: senderBalance } = await this.statementsRepository.getUserBalance({ user_id: sender_id }); if (senderBalance < amount) { throw new CreateTransferError.InsufficientSenderFunds() } const senderOperation = await this.statementsRepository.create({ user_id: sender_id, sender_id, recipient_id, type: OperationType.TRANSFER, amount: amount, description: 'Transferência de valor enviada' }); await this.statementsRepository.create({ user_id: recipient_id, sender_id, recipient_id, type: OperationType.TRANSFER, amount: amount, description: 'Transferência de valor recebida' }); return senderOperation; } }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/createTransfer/CreateTransferController.ts
<reponame>arfurlaneto/rocketseat-ignite-challenges<gh_stars>0 import { Request, Response } from 'express'; import { container } from 'tsyringe'; import { CreateTransferUseCase } from './CreateTransferUseCase'; export class CreateTransferController { async execute(request: Request, response: Response) { const { id: sender_id } = request.user; const { recipient_id} = request.params; const { amount } = request.body; const createTransfer = container.resolve(CreateTransferUseCase); const transfer = await createTransfer.execute({ sender_id, recipient_id, amount }); return response.status(201).json(transfer); } }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/users/useCases/createUser/CreateUserUseCase.spec.ts
process.env = { JWT_SECRET: 'b69f8a78-d26b-47b1-a9d0-6999f73d06eb' }; import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { CreateUserError } from "./CreateUserError"; import { CreateUserUseCase } from "./CreateUserUseCase"; describe("Create User", () => { let createUserUseCase: CreateUserUseCase; let usersRepository: InMemoryUsersRepository; beforeEach(() => { usersRepository = new InMemoryUsersRepository(); createUserUseCase = new CreateUserUseCase( usersRepository, ); }) it("should create an user", async () => { const email= "<EMAIL>"; const name = "User"; const password = "<PASSWORD>"; const response = await createUserUseCase.execute({ email, name, password }) expect(response.id).toBeDefined() expect(response.email).toBe(email) expect(response.name).toBe(name) }) it("should not create an user if e-mail is already taken", async () => { const email= "<EMAIL>"; const name = "User"; const password = "<PASSWORD>"; await usersRepository.create({ name, email, password, }); await expect(createUserUseCase.execute({ email, name, password })).rejects.toBeInstanceOf(CreateUserError); }) })
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-introducao-ao-solid/src/index.ts
<filename>Node.js/ignite-desafio-introducao-ao-solid/src/index.ts<gh_stars>0 import express, { Request, Response, NextFunction } from "express"; import { usersRoutes } from "./routes/users.routes"; const app = express(); app.use(express.json()); app.use("/users", usersRoutes); app.use( (error: Error, request: Request, response: Response, next: NextFunction) => { switch (error.message) { case "Current user is not an administrator, cannot list.": case "The specified e-mail is already taken.": case "User not found, cannot list.": response.status(400).send({ error: error.message }); break; case "User not found.": response.status(404).send({ error: error.message }); break; default: next(); } } ); export { app };
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/getBalance/GetBalanceUseCase.spec.ts
<gh_stars>0 import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { InMemoryStatementsRepository } from "../../repositories/in-memory/InMemoryStatementsRepository"; import { GetBalanceError } from "./GetBalanceError"; import { GetBalanceUseCase } from "./GetBalanceUseCase"; import { OperationType } from "../../structures/OperationType"; describe("Get Balance", () => { let getBalanceUseCase: GetBalanceUseCase; let statementsRepository: InMemoryStatementsRepository let usersRepository: InMemoryUsersRepository; beforeEach(() => { statementsRepository = new InMemoryStatementsRepository(); usersRepository = new InMemoryUsersRepository(); getBalanceUseCase = new GetBalanceUseCase( statementsRepository, usersRepository ); }) it("should get balance for an existing user", async () => { const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const deposit = await statementsRepository.create({ user_id: user.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 1000, }) const response = await getBalanceUseCase.execute({ user_id: user.id as string }) expect(response.balance).toBe(deposit.amount); }) it("should not get balance for an invalid user", async () => { const invalidUserId = 'ed445280-f891-4559-b95a-98308e44f760'; await expect(getBalanceUseCase.execute({ user_id: invalidUserId })) .rejects.toBeInstanceOf(GetBalanceError) }) })
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-serverless/src/functions/listUserTodos.ts
import { APIGatewayProxyHandler } from 'aws-lambda/trigger/api-gateway-proxy'; import { document } from '../utils/dynamodbClient' export const handle : APIGatewayProxyHandler = async (event) => { const user_id = event.pathParameters.user_id; const data = await document.scan({ TableName: "todos", FilterExpression: "user_id = :user_id", ExpressionAttributeValues: { ":user_id": user_id } }).promise(); return { statusCode: 200, body: JSON.stringify(data.Items), headers: { "Content-Type": "application/json" } }; };
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-serverless/src/functions/createTodo.ts
import { APIGatewayProxyHandler } from 'aws-lambda/trigger/api-gateway-proxy'; import { v4 as uuidv4 } from 'uuid'; import { document } from '../utils/dynamodbClient' export const handle : APIGatewayProxyHandler = async (event) => { const user_id = event.pathParameters.user_id; if (!event.body) { return { statusCode: 400, body: null, headers: { "Content-Type": "application/json" } }; } const { title, deadline } = JSON.parse(event.body) if (!title || !deadline) { return { statusCode: 400, body: null, headers: { "Content-Type": "application/json" } }; } await document.put({ TableName: "todos", Item: { id: uuidv4(), user_id, title, done: false, deadline: new Date(deadline).toISOString() } }).promise() return { statusCode: 201, body: null, headers: { "Content-Type": "application/json" } }; };
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/database/migrations/1621479084804-update-statements-table.ts
<reponame>arfurlaneto/rocketseat-ignite-challenges import { query } from "express"; import {MigrationInterface, QueryRunner} from "typeorm"; export class updateStatementsTable1621479084804 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query("ALTER TABLE statements ALTER COLUMN type TYPE VARCHAR(255);"); await queryRunner.query("DROP TYPE IF EXISTS statements_type_enum;"); await queryRunner.query("CREATE TYPE statements_type_enum AS ENUM('deposit', 'withdraw', 'transfer');"); await queryRunner.query("ALTER TABLE statements ALTER COLUMN type TYPE statements_type_enum USING type::statements_type_enum"); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query("ALTER TABLE statements ALTER COLUMN type TYPE VARCHAR(255);"); await queryRunner.query("DROP TYPE IF EXISTS statements_type_enum;"); await queryRunner.query("CREATE TYPE statements_type_enum AS ENUM('deposit', 'withdraw');"); await queryRunner.query("ALTER TABLE statements ALTER COLUMN type TYPE statements_type_enum USING type::statements_type_enum"); } }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/database/migrations/1621473563329-add-sender-recipient-statements-table.ts
<reponame>arfurlaneto/rocketseat-ignite-challenges import { MigrationInterface, QueryRunner, TableColumn, TableForeignKey } from "typeorm"; export class addSenderRecipientStatementsTable1621473563329 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.addColumns('statements',[ new TableColumn({ name: 'sender_id', type: 'uuid', isNullable: true }), new TableColumn({ name: 'recipient_id', type: 'uuid', isNullable: true }) ]); await queryRunner.createForeignKey("statements", new TableForeignKey({ name: 'fk_statements_users_sender', columnNames: ['sender_id'], referencedTableName: 'users', referencedColumnNames: ['id'], onUpdate: 'CASCADE', onDelete: 'CASCADE' })); await queryRunner.createForeignKey("statements", new TableForeignKey({ name: 'fk_statements_users_recipient', columnNames: ['recipient_id'], referencedTableName: 'users', referencedColumnNames: ['id'], onUpdate: 'CASCADE', onDelete: 'CASCADE' })); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.dropColumn('statements', 'sender_id') await queryRunner.dropColumn('statements', 'recipient_id') } }
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/createStatement/CreateStatementUseCase.spec.ts
<gh_stars>0 import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { InMemoryStatementsRepository } from "../../repositories/in-memory/InMemoryStatementsRepository"; import { CreateStatementUseCase } from "./CreateStatementUseCase" import { CreateStatementError } from "./CreateStatementError"; import { OperationType } from "../../structures/OperationType"; describe("Create Statement", () => { let createStatementUseCase: CreateStatementUseCase; let usersRepository: InMemoryUsersRepository; let statementsRepository: InMemoryStatementsRepository beforeEach(() => { usersRepository = new InMemoryUsersRepository(); statementsRepository = new InMemoryStatementsRepository(); createStatementUseCase = new CreateStatementUseCase( usersRepository, statementsRepository ); }) it("should withdraw when funds are sufficient", async () => { const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); await statementsRepository.create({ user_id: user.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 1000 }) const withdrawData = { user_id: user.id as string, type: OperationType.WITHDRAW, description:'Sample withdraw.', amount: 100 }; const response = await createStatementUseCase.execute(withdrawData) expect(response).toMatchObject(withdrawData) }) it("should not withdraw when funds are insufficient", async () => { const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const withdraw = { user_id: user.id as string, type: OperationType.WITHDRAW, description:'Sample withdraw.', amount: 100, }; await expect(createStatementUseCase.execute(withdraw)) .rejects.toBeInstanceOf(CreateStatementError.InsufficientFunds) }) it("should not withdraw when user are invalid", async () => { const invalidUserId = 'ed445280-f891-4559-b95a-98308e44f760'; const withdrawData = { user_id: invalidUserId, type: OperationType.WITHDRAW, description:'Sample withdraw.', amount: 100 }; await expect(createStatementUseCase.execute(withdrawData)) .rejects.toBeInstanceOf(CreateStatementError.UserNotFound) }) })
arfurlaneto/rocketseat-ignite-challenges
Node.js/ignite-desafio-tests-challenge/src/modules/statements/useCases/getStatementOperation/GetStatementOperationUseCase.spec.ts
import { InMemoryUsersRepository } from "../../../users/repositories/in-memory/InMemoryUsersRepository"; import { InMemoryStatementsRepository } from "../../repositories/in-memory/InMemoryStatementsRepository"; import { GetStatementOperationUseCase } from "./GetStatementOperationUseCase"; import { GetStatementOperationError } from "./GetStatementOperationError"; import { OperationType } from "../../structures/OperationType"; describe("Get Statement Operation", () => { let getStatementOperationUseCase: GetStatementOperationUseCase; let usersRepository: InMemoryUsersRepository; let statementsRepository: InMemoryStatementsRepository beforeEach(() => { statementsRepository = new InMemoryStatementsRepository(); usersRepository = new InMemoryUsersRepository(); getStatementOperationUseCase = new GetStatementOperationUseCase( usersRepository, statementsRepository, ); }) it("should get an existing statement for an user", async () => { const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const deposit = await statementsRepository.create({ user_id: user.id as string, type: OperationType.DEPOSIT, description: 'Sample deposit.', amount: 1000, }) const response = await getStatementOperationUseCase.execute({ user_id: user.id as string, statement_id: deposit.id as string }) expect(response).toMatchObject(deposit); }) it("should not get an statement for an invalid user", async () => { const invalidUserId = 'ed445280-f891-4559-b95a-98308e44f760'; const invalidStatementId = '6d73fac4-0d31-41cb-9809-0d38aa2ca4b6'; await expect(getStatementOperationUseCase.execute({ user_id: invalidUserId, statement_id: invalidStatementId })) .rejects.toBeInstanceOf(GetStatementOperationError.UserNotFound) }) it("should not get an invalid statement", async () => { const user = await usersRepository.create({ name: 'User', email: '<EMAIL>', password: '<PASSWORD>' }); const invalidStatementId = '6d73fac4-0d31-41cb-9809-0d38aa2ca4b6'; await expect(getStatementOperationUseCase.execute({ user_id: user.id as string, statement_id: invalidStatementId as string })) .rejects.toBeInstanceOf(GetStatementOperationError.StatementNotFound) }) })
lterfloth/BotBuilder-Samples
samples/typescript_nodejs/05.multi-turn-prompt/src/index.ts
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { config } from "dotenv"; import * as path from "path"; import * as restify from "restify"; // Import required bot services. // See https://aka.ms/bot-services to learn more about the different parts of a bot. import { BotFrameworkAdapter, ConversationState, MemoryStorage, UserState } from "botbuilder"; // This bot's main dialog. import { DialogBot } from "./bots/dialogBot"; import { FyiPostDialog } from "./dialogs/fyiPostDialog"; // Read environment variables from .env file const ENV_FILE = path.join(__dirname, ".env"); config({ path: ENV_FILE }); // Create the adapter. See https://aka.ms/about-bot-adapter to learn more about using information from // the .bot file when configuring your adapter. const adapter = new BotFrameworkAdapter({ appId: process.env.MicrosoftAppId, appPassword: <PASSWORD>.MicrosoftAppPassword }); // Catch-all for errors. adapter.onTurnError = async (context, error) => { // This check writes out errors to console log .vs. app insights. // NOTE: In production environment, you should consider logging this to Azure // application insights. console.error(`\n [onTurnError] unhandled error: ${error}`); // Send a trace activity, which will be displayed in Bot Framework Emulator await context.sendTraceActivity( "OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError" ); // Send a message to the user await context.sendActivity("The bot encounted an error or bug."); await context.sendActivity( "To continue to run this bot, please fix the bot source code." ); // Clear out state await conversationState.delete(context); }; // Define the state store for your bot. // See https://aka.ms/about-bot-state to learn more about using MemoryStorage. // A bot requires a state storage system to persist the dialog and user state between messages. const memoryStorage = new MemoryStorage(); // Create conversation state with in-memory storage provider. const conversationState = new ConversationState(memoryStorage); const userState = new UserState(memoryStorage); // Create the main dialog. const dialog = new FyiPostDialog(userState); const bot = new DialogBot(conversationState, userState, dialog); // Create HTTP server. const server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, () => { console.log(`\n${server.name} listening to ${server.url}.`); console.log( "\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator" ); console.log('\nTo talk to your bot, open the emulator select "Open Bot"'); }); // Listen for incoming requests. server.post("/api/messages", (req, res) => { adapter.processActivity(req, res, async context => { // Route the message to the bot's main handler. await bot.run(context); }); });
lterfloth/BotBuilder-Samples
samples/typescript_nodejs/05.multi-turn-prompt/src/dialogs/fyiPostDialog.ts
<reponame>lterfloth/BotBuilder-Samples // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { StatePropertyAccessor, TurnContext, UserState } from "botbuilder"; import { ChoiceFactory, ChoicePrompt, ComponentDialog, ConfirmPrompt, DialogSet, DialogTurnStatus, PromptValidatorContext, TextPrompt, WaterfallDialog, WaterfallStepContext } from "botbuilder-dialogs"; import { FyiPost } from "../fyiPost"; const SOURCETYPE_PROMPT = "SOURCETYPE_PROMPT"; const CONFIRM_PROMPT = "CONFIRM_PROMPT"; const DESCRIPTION_PROMPT = "DESCRIPTION_PROMPT"; const URL_PROMPT = "URL_PROMPT"; const PRIORITY_PROMPT = "PRIORITY_PROMPT"; const USER_PROFILE = "USER_PROFILE"; const WATERFALL_DIALOG = "WATERFALL_DIALOG"; export class FyiPostDialog extends ComponentDialog { private fyiPost: StatePropertyAccessor<FyiPost>; constructor(userState: UserState) { super("fyiPostDialog"); this.fyiPost = userState.createProperty(USER_PROFILE); this.addDialog(new TextPrompt(DESCRIPTION_PROMPT)); this.addDialog(new TextPrompt(URL_PROMPT)); this.addDialog(new ChoicePrompt(SOURCETYPE_PROMPT)); this.addDialog(new ChoicePrompt(PRIORITY_PROMPT)); this.addDialog(new ConfirmPrompt(CONFIRM_PROMPT)); this.addDialog( new WaterfallDialog(WATERFALL_DIALOG, [ this.sourceTypeStep.bind(this), this.urlStep.bind(this), this.descriptionStep.bind(this), this.priorityStep.bind(this), this.confirmStep.bind(this), this.summaryStep.bind(this) ]) ); this.initialDialogId = WATERFALL_DIALOG; } /** * The run method handles the incoming activity (in the form of a TurnContext) and passes it through the dialog system. * If no dialog is active, it will start the default dialog. * @param {*} turnContext * @param {*} accessor */ public async run(turnContext: TurnContext, accessor: StatePropertyAccessor) { const dialogSet = new DialogSet(accessor); dialogSet.add(this); const dialogContext = await dialogSet.createContext(turnContext); const results = await dialogContext.continueDialog(); if (results.status === DialogTurnStatus.empty) { await dialogContext.beginDialog(this.id); } } private async sourceTypeStep(stepContext: WaterfallStepContext<FyiPost>) { // WaterfallStep always finishes with the end of the Waterfall or with another dialog; here it is a Prompt Dialog. // Running a prompt here means the next WaterfallStep will be run when the users response is received. return await stepContext.prompt(SOURCETYPE_PROMPT, { choices: ChoiceFactory.toChoices([ "Website", "Konferenz", "Literatur", "Sonstiges" ]), prompt: "Bitte sage mir kurz, um was für eine Quelle es sich handelt" }); } private async urlStep(stepContext: WaterfallStepContext<FyiPost>) { stepContext.options.sourceType = stepContext.result.value; return await stepContext.prompt( URL_PROMPT, "Bitte gebe mir die URL des Webinhaltes." ); } private async descriptionStep(stepContext: WaterfallStepContext<FyiPost>) { stepContext.options.url = stepContext.result; return await stepContext.prompt( DESCRIPTION_PROMPT, "Was möchtest du den anderen hinsichtlich der Quelle sagen (diese Angabe wird 1 zu 1 in übernommen)?" ); } private async priorityStep(stepContext: WaterfallStepContext<FyiPost>) { stepContext.options.description = stepContext.result; return await stepContext.prompt(PRIORITY_PROMPT, { choices: ChoiceFactory.toChoices([ "Eher unwichtig", "Wichtig", "Dringend" ]), prompt: "Bitte sage mir kurz, wie wichtig diese Quelle ist." }); } private async confirmStep(stepContext: WaterfallStepContext<FyiPost>) { // WaterfallStep always finishes with the end of the Waterfall or with another dialog, here it is a Prompt Dialog. stepContext.options.priority = stepContext.result.value; return await stepContext.prompt(CONFIRM_PROMPT, { prompt: "Sind deine Angaben so in Ordnung?" }); } private async summaryStep(stepContext: WaterfallStepContext<FyiPost>) { if (stepContext.result) { // Get the current profile object from user state. const fyiPost = await this.fyiPost.get( stepContext.context, new FyiPost() ); const stepContextOptions = stepContext.options; fyiPost.sourceType = stepContextOptions.sourceType; fyiPost.url = stepContextOptions.url; fyiPost.description = stepContextOptions.description; fyiPost.priority = stepContextOptions.priority; let msg = `Ich hab deine Empfehlung vom Typ *${fyiPost.sourceType}* wie folgt abgespeichert:\n\n`; msg += `**URL:** ${fyiPost.url}. \n \n`; msg += `\n`; msg += ` **Beschreibung:** ${fyiPost.description}.\n`; msg += `\n`; msg += ` Ebenfalls habe ich die Quelle als *${fyiPost.priority}* einsortiert.`; await stepContext.context.sendActivity(msg); } else { await stepContext.context.sendActivity( "Die Daten wurden nicht gespeichert." ); } // WaterfallStep always finishes with the end of the Waterfall or with another dialog, here it is the end. return await stepContext.endDialog(); } private async descriptionPromptValidator( promptContext: PromptValidatorContext<Text> ) { // This condition is our validation rule. You can also change the value at this point. return promptContext.recognized.succeeded; } }
lterfloth/BotBuilder-Samples
samples/typescript_nodejs/05.multi-turn-prompt/src/fyiPost.ts
<gh_stars>0 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. export class FyiPost { public sourceType: string; public url: string; public description: string; public priority: number; }
brainup-readby/readby-admin-portal
src/app/routes/chapters/add-topic/model/topic.model.ts
<reponame>brainup-readby/readby-admin-portal export class AddTopicModel { TOPIC_NAME?: string; TOPIC_CODE?: string; IS_ACTIVE?: string; VIDEO_URL?: string; BOOK_URL?: string; CHAPTER_ID?: number; TOPIC_SUBSCRIPTION?: string; }
brainup-readby/readby-admin-portal
src/app/routes/topics/topics.component.ts
<reponame>brainup-readby/readby-admin-portal import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MtxGridColumn } from '@ng-matero/extensions'; import { TopicModel } from './model/topic-interface'; import { EditTopicComponent } from './edit-topic/edit-topic.component'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { FilterModel } from './model/topic-filter.model'; @Component({ selector: 'app-topics', templateUrl: './topics.component.html', styleUrls: ['./topics.component.scss'] }) export class TopicsComponent implements OnInit { @ViewChild('pdfLinkTpl') pdfLinkTpl: TemplateRef<any>; filterMdl = new FilterModel(); boardFilterList = []; boardIdSelected: any; courseList = []; masStreamList = []; masYearList = []; subjectList = []; chapterList = []; chapterId: number; yearSelected: any; columns: MtxGridColumn[] = [ { header: 'Topic Code', field: 'TOPIC_CODE', sortable: true}, { header: 'Icon', field: 'icon_path', type: 'image'}, { header: 'Pdf Link', field: 'BOOK_URL'}, { header: 'Video Link', field: 'VIDEO_URL'}, { header: 'Topic Name', field: 'TOPIC_NAME', sortable: true }, { header: 'Subscription', field: 'TOPIC_SUBSCRIPTION', sortable: true, type: 'tag', tag: { p: { text: 'Paid', color: 'green-100' }, f: { text: 'Free', color: '0xff229ff7' }, } }, { header: 'Status', field: 'IS_ACTIVE', sortable: true, type: 'tag', tag: { t: { text: 'Active', color: 'green-100' }, f: { text: 'In-Active', color: 'red-100' }, } }, { header: 'Operation', field: 'operation', width: '140px', pinned: 'right', type: 'button', buttons: [ { icon: 'mode_edit', tooltip: 'Edit Course', type: 'icon', click: record => this.edit(record), }, { icon: 'delete_forever', tooltip: 'Delete Course', color: 'warn', type: 'icon', pop: true, popTitle: 'Are you sure want to delete topic ?', click: record => this.delete(record), } ], }, ]; topocList: TopicModel[]; isLoading = true; multiSelectable = true; rowSelectable = true; hideRowSelectionCheckbox = false; showToolbar = true; columnHideable = true; columnMovable = true; rowHover = false; rowStriped = false; showPaginator = true; expandable = false; boardList = []; constructor(public dialog: MatDialog, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService) { } ngOnInit(): void { this.getTopicList(); this.getBoardList(); } getTopicList() { this.spiner.show(); this.service.sendGetRequest('getTopicList').subscribe( res => { this.topocList = res.data; console.log(this.topocList); this.spiner.hide(); }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } edit(record) { this.dialog.open(EditTopicComponent, { data: record, disableClose: true }); } delete(record) { this.spiner.show(); this.service.sendDeleteRequest('deleteTopic?topicId=' + record.TOPIC_ID).subscribe((res) => { this.spiner.hide(); if (res.status === '200') { Swal.fire( 'Topic!', 'Topic removed successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } getBoardList() { this.service.sendAppGetRequest('getBoardDetail').subscribe( (res) => { if (res.data) { this.boardFilterList = res.data; this.boardFilterList.forEach(brdEl => { const json = { BOARD_ID: brdEl.BOARD_ID, BOARD_NAME: brdEl.BOARD_NAME }; this.boardList.push(json); }); } console.log(this.boardFilterList); }); } onBoardChange(event) { this.courseList = []; this.masStreamList = []; this.subjectList = []; this.masYearList = []; this.chapterList = []; this.boardFilterList.filter(f => f.BOARD_ID === event.value).forEach(el => { el.MAS_COURSE.forEach(element => { const courseJson = { COURSE_ID: element.COURSE_ID, COURSE_NAME: element.COURSE_NAME }; this.courseList.push(element); }); }); } onCourseChange(event) { this.masStreamList = []; this.subjectList = []; this.masYearList = []; this.chapterList = []; this.courseList.filter(f => f.COURSE_ID === event.value).forEach(el => { el.MAS_STREAM.forEach(element => { this.masStreamList.push(element); }); if (el.MAS_COURSE_YEAR !== null && el.MAS_COURSE_YEAR !== undefined) { this.masYearList.push(el.MAS_COURSE_YEAR[0]); this.yearSelected = this.masYearList[0].YEAR_ID; } // console.log(this.masYearList); }); } onStreamChange(event) { this.subjectList = []; this.chapterList = []; this.service.sendGetRequest('getSubjectByStreamOrYear?streamId=' + event.value).subscribe( (res) => { this.subjectList = res.data; }); } onSubjectChange(event) { this.chapterList = []; this.service.sendGetRequest('getChaptersBySubject?subjectId=' + event.value).subscribe( (res) => { this.chapterList = res.data; }); } onChapterChange(event) { this.chapterId = event.value; } getFilteredTopicList() { this.topocList = []; this.spiner.show(); this.service.sendGetRequest('getTopicsByChapter?chapterId=' + this.chapterId).subscribe( (res) => { this.spiner.hide(); this.topocList = res.data; // tslint:disable-next-line:no-string-literal this.topocList['CourseYear'] = this.yearSelected; }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } }
brainup-readby/readby-admin-portal
src/app/routes/subjects/edit-subject/edit-subject.component.ts
<gh_stars>0 import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2'; import { SubjectModel } from '../model/subject-interface'; @Component({ selector: 'app-edit-subject', templateUrl: './edit-subject.component.html', styleUrls: ['./edit-subject.component.scss'] }) export class EditSubjectComponent implements OnInit { public imagePath; public imgURL: any; public message: string; // subjectModel: SubjectModel; isImageUpdate: boolean; fileIcon: any; editedImagePath: any; serverResponse: any; boardTypeList = []; masStreamList = []; masStreamAddList = []; courseYearList = []; courseYearAddList = []; subjectModel = { SUBJECT_ID: null, SUBJECT_CODE: '', SUBJECT_NAME: '', IS_ACTIVE: 't', icon_path: 'c:/test', STREAM_ID: null, YEAR_ID: null, COURSE_ID: null }; constructor(public dialogRef: MatDialogRef<EditSubjectComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private router: Router) { this.subjectModel.SUBJECT_ID = data.SUBJECT_ID; this.subjectModel.SUBJECT_CODE = data.SUBJECT_CODE; this.subjectModel.SUBJECT_NAME = data.SUBJECT_NAME; this.subjectModel.STREAM_ID = data.STREAM_ID; this.subjectModel.YEAR_ID = data.YEAR_ID; this.subjectModel.COURSE_ID = data.COURSE_ID; this.subjectModel.icon_path = data.icon_path; console.log(this.subjectModel); this.imgURL = this.subjectModel.icon_path; this.getStreamListByCourseId(data.COURSE_ID); this.getYearListByCourseId(data.COURSE_ID); } ngOnInit(): void { this.boardTypeList = this.localStorage.get('boardType'); /* this.masStreamList = this.localStorage.get('MasStreamList'); const masStreams = this.localStorage.get('MasStreamList'); masStreams.forEach(element => { const json = { STREAM_ID: element.STREAM_ID, STREAM_CODE: element.STREAM_CODE, STREAM_NAME: element.STREAM_NAME }; this.masStreamAddList.push(json); }); this.courseYearList = this.localStorage.get('MasStreamYear'); const masStreamsYears = this.localStorage.get('MasStreamYear'); masStreamsYears.forEach(el => { const json = { YEAR: el.YEAR, DISPLAY_NAME: el.DISPLAY_NAME }; this.courseYearAddList.push(json); }); */ } destroyDailog() { this.dialogRef.close(); } onFileSelected(event) { this.isImageUpdate = true; this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.editedImagePath; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } preview(files) { if (files.length === 0) { return; } const mimeType = files[0].type; if (mimeType.match(/image\/*/) == null) { this.message = 'Only images are supported.'; return; } const reader = new FileReader(); this.imagePath = files; reader.readAsDataURL(files[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } updateSubject() { this.spiner.show(); const blob = new Blob(); const formData: FormData = new FormData(); // this.getMasStreamName(this.subjectModel.MAS_STREAM.STREAM_CODE, this.subjectModel.MAS_COURSE_YEAR.YEAR); if (this.isImageUpdate) { formData.append('file', this.fileIcon[0], this.fileIcon[0].name); } else { formData.append('file', blob, this.fileIcon); } formData.append('masSubjects', JSON.stringify(this.subjectModel)); this.service.sendPostFormRequest('editSubjects', formData).subscribe( (res: any) => { this.serverResponse = res; this.spiner.hide(); }, (error) => { // console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire('Success', 'Subject successfully Updated', 'success').then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } addCourseEditModel(addCourseEditModel: any): string | Blob { throw new Error('Method not implemented.'); } /* getMasStreamName(streamId: any, yearId: any) { console.log(streamId); this.subjectModel.MAS_STREAM = this.masStreamList.filter( f => f.STREAM_CODE === streamId)[0]; this.subjectModel.MAS_COURSE_YEAR = this.courseYearList.filter( f => f.YEAR_ID === yearId)[0]; } */ getStreamListByCourseId(courseId: any) { this.spiner.show(); this.service.sendGetRequest('getMasStreamList?courseId=' + courseId).subscribe((res) => { this.spiner.hide(); if (res.status === '200') { this.masStreamAddList = res.data; } }); } getYearListByCourseId(courseId: any) { this.spiner.hide(); this.service.sendGetRequest('getMasYearList?courseId=' + courseId).subscribe((res) => { this.spiner.hide(); if (res.status === '200') { this.courseYearAddList = res.data; } }); } }
brainup-readby/readby-admin-portal
src/app/routes/courses/add-stream/add-stream.component.ts
<reponame>brainup-readby/readby-admin-portal import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import { AddSubjectComponent } from '../add-subject/add-subject.component'; import Swal from 'sweetalert2/dist/sweetalert2.js'; @Component({ selector: 'app-add-stream', templateUrl: './add-stream.component.html', styleUrls: ['./add-stream.component.scss'] }) export class AddStreamComponent implements OnInit { addStreamModel = new AddStreamModel(); constructor(public dialogRef: MatDialogRef<AddSubjectComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private service: ApiService) { this.addStreamModel.COURSE_ID = data.courseId; this.addStreamModel.IS_ACTIVE = 't'; } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } addStream() { this.spiner.show(); this.service.sendPostFormRequest('addStream', this.addStreamModel).subscribe( (res: any) => { if (res.status === '200') { Swal.fire( 'Success', 'Stream has been add in course .', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } console.log(res); this.spiner.hide(); }, (error) => { console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire( 'Success', 'Stream has been add in course .', 'success' ); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } } export class AddStreamModel { STREAM_CODE?: string; STREAM_NAME?: string; IS_ACTIVE?: string; COURSE_ID?: string; }
brainup-readby/readby-admin-portal
src/app/routes/courses/edit-course/edit-course.component.ts
import { Component, Inject, OnInit, ViewChild } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { CourseModel } from '../model/course-interface'; import { LocalStorageService } from '../../../shared/services/storage.service'; import { NgxSpinnerService } from 'ngx-spinner'; import { AddCourseModel, MasCourseYear } from './model/course-model'; import { NgForm } from '@angular/forms'; import { ApiService } from '../../../shared/services/api.services'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { timeout } from 'rxjs/operators'; @Component({ selector: 'app-add-course', templateUrl: './edit-course.component.html', styleUrls: ['./edit-course.component.scss'] }) export class EditCourseComponent implements OnInit { @ViewChild('courseForm', {static: false}) courseForm: NgForm; courseModel: CourseModel; fileIcon: any; addCourseEditModel = { COURSE_ID: null, COURSE_CODE: '', COURSE_NAME: '', IS_ACTIVE: 't', COURSE_TYPE_ID: null, BOARD_ID: null, icon_path: 'c:/test', COURSE_PRICE: null }; /* addCourseEditModel = { COURSE_ID: null, COURSE_CODE: '', COURSE_NAME: '', IS_ACTIVE: 't', COURSE_TYPE_ID: null, BOARD_ID: null, icon_path: 'c:/test', COURSE_PRICE: null, MAS_STREAM: [{ STREAM_ID: null, STREAM_CODE: '', STREAM_NAME: '' }], MAS_COURSE_YEAR : [{ YEAR_ID: '', YEAR: '', DISPLAY_NAME: '' }] }; */ isUpdate: boolean; courseTypeList = []; boardTypeList = []; courseYearList = []; masStreamList = []; masStreamAddList = []; courseYearAddList = []; serverResponse: any; imagePath: any; imgURL: string | ArrayBuffer; editedImagePath: string | ArrayBuffer; isImageUpdate = false; constructor(public dialogRef: MatDialogRef<EditCourseComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private service: ApiService) { this.courseModel = data.selectedData; console.log(this.courseModel); this.isUpdate = data.isUpdate; if (this.isUpdate) { this.addCourseEditModel.COURSE_ID = data.selectedData.courseId; this.addCourseEditModel.COURSE_CODE = data.selectedData.courseCode; this.addCourseEditModel.COURSE_NAME = data.selectedData.courseName; this.addCourseEditModel.COURSE_TYPE_ID = data.selectedData.courseTypeId; this.addCourseEditModel.BOARD_ID = data.selectedData.boardId; // this.addCourseEditModel.MAS_STREAM = data.selectedData.masCourse; this.addCourseEditModel.icon_path = data.selectedData.iconPath; this.imgURL = this.courseModel.iconPath; // this.addCourseEditModel.MAS_COURSE_YEAR = data.selectedData.masCourseYear; this.addCourseEditModel.COURSE_PRICE = data.selectedData.coursePrice; console.log(this.addCourseEditModel); } } ngOnInit(): void { this.courseTypeList = this.localStorage.get('courseType'); this.boardTypeList = this.localStorage.get('boardType'); this.masStreamList = this.localStorage.get('MasStreamList'); const masStreams = this.localStorage.get('MasStreamList'); masStreams.forEach(element => { const json = { STREAM_CODE: element.STREAM_CODE, STREAM_NAME: element.STREAM_NAME }; this.masStreamAddList.push(json); }); this.courseYearList = this.localStorage.get('MasStreamYear'); const masStreamsYears = this.localStorage.get('MasStreamYear'); masStreamsYears.forEach(el => { const json = { YEAR: el.YEAR, DISPLAY_NAME: el.DISPLAY_NAME }; this.courseYearAddList.push(json); }); // console.log(this.courseYearAddList); } destroyDailog() { this.dialogRef.close(); } onSubmit() { console.log(this.courseModel); } onFileSelected(event) { this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.fileIcon; // this.addCourseModel.icon_path = this.fileIcon; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } onFileChange(event) { this.isImageUpdate = true; this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.editedImagePath; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } editCousrse() { this.spiner.show(); const blob = new Blob(); // this.getEditMasStreamName(this.addCourseEditModel.MAS_STREAM[0].STREAM_CODE, this.addCourseEditModel.MAS_COURSE_YEAR[0].YEAR); const formData: FormData = new FormData(); if (this.isImageUpdate) { formData.append('file', this.fileIcon[0], this.fileIcon[0].name); } else { formData.append('file', blob, this.fileIcon); } formData.append('masCourse', JSON.stringify(this.addCourseEditModel)); this.service.sendPostFormRequest('editCourses', formData).subscribe( (res: any) => { this.serverResponse = res; if (res === 'course added successfully') { this.destroyDailog(); Swal.fire( 'Success', 'Course update successfully', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } this.spiner.hide(); }, (error) => { // console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire('Success', 'Course update successfully', 'success').then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } /* getMasStreamName(streamId: any, yearId: any) { console.log(streamId); this.addCourseModel.MAS_STREAM = this.masStreamList.filter( f => f.STREAM_ID === streamId); this.addCourseModel.MAS_COURSE_YEAR = this.courseYearList.filter( f => f.YEAR_ID === yearId); } */ /* getAddMasStreamName(streamCode: any, year: any) { // console.log(streamCode + ' ' + +year); this.addCourseModel.MAS_STREAM = this.masStreamAddList.filter( f => f.STREAM_CODE === streamCode); // console.log(this.addCourseModel.MAS_STREAM); this.addCourseModel.MAS_COURSE_YEAR = this.courseYearAddList.filter( f => f.YEAR === year); // console.log(this.addCourseModel.MAS_COURSE_YEAR); } getEditMasStreamName(streamCode: any, year: any) { const streams = this.masStreamList.filter( f => f.STREAM_CODE === streamCode); this.addCourseEditModel.MAS_STREAM[0].STREAM_NAME = streams[0].STREAM_NAME; // console.log(this.addCourseEditModel.MAS_STREAM); // this.addCourseEditModel.MAS_COURSE_YEAR = this.courseYearList.filter( f => f.YEAR === year); } changeSelected(event) { console.log(event); } */ }
brainup-readby/readby-admin-portal
src/app/routes/topics/model/topic-interface.ts
<gh_stars>0 export interface TopicModel { TOPIC_ID?: number; TOPIC_NAME?: string; TOPIC_CODE?: string; IS_ACTIVE?: string; icon_path?: string; VIDEO_URL?: string; BOOK_URL?: string; CHAPTER_ID?: number; CourseYear?: string; TOPIC_SUBSCRIPTION?: string; }
brainup-readby/readby-admin-portal
src/app/routes/subjects/add-chapter/add-chapter.component.ts
import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2'; import { AddChapterModel } from './model/chapter-model'; @Component({ selector: 'app-add-chapter', templateUrl: './add-chapter.component.html' }) export class AddChapterComponent implements OnInit { addChapterModel = new AddChapterModel(); fileIcon: any; imagePath: any; imgURL: string | ArrayBuffer; constructor(public dialogRef: MatDialogRef<AddChapterComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private service: ApiService) { console.log(data); this.addChapterModel.SUBJECT_ID = data.SUBJECT_ID; this.addChapterModel.IS_ACTIVE = 't'; this.addChapterModel.icon_path = 'c://tmp'; } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } addChapter() { this.spiner.show(); const formData: FormData = new FormData(); formData.append('file', this.fileIcon[0], this.fileIcon[0].name); formData.append('masChapters', JSON.stringify(this.addChapterModel)); this.service.sendPostFormRequest('addChapters', formData).subscribe( (res: any) => { /* if (res === 'course added successfully') { this.destroyDailog(); Swal.fire( 'Success', 'Course saved successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } */ console.log(res); this.spiner.hide(); }, (error) => { console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire( 'Success', 'Chapter Added In Subject.', 'success' ); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } onFileSelected(event) { this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.fileIcon; // this.addCourseModel.icon_path = this.fileIcon; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } }
brainup-readby/readby-admin-portal
src/app/routes/board/edit-board/edit-board.component.ts
import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import { BoardModel } from '../model/board-interface'; import Swal from 'sweetalert2/dist/sweetalert2.js'; @Component({ selector: 'app-edit-board', templateUrl: './edit-board.component.html', styleUrls: ['./edit-board.component.scss'] }) export class EditBoardComponent implements OnInit { boardModel: BoardModel; constructor(public dialogRef: MatDialogRef<EditBoardComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private service: ApiService, private spiner: NgxSpinnerService) { this.boardModel = data; } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } editBoard() { this.spiner.show(); this.boardModel.IS_ACTIVE = 'T'; this.service.sendPostFormRequest('editBoard', this.boardModel).subscribe( res => { this.spiner.hide(); Swal.fire( 'Success', 'Board successfully Updated.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } }
brainup-readby/readby-admin-portal
src/app/routes/subjects/add-chapter/model/chapter-model.ts
export class AddChapterModel { CHAPTER_NAME?: string; CHAPTER_CODE?: string; IS_ACTIVE?: string; // tslint:disable-next-line:variable-name icon_path?: string; SUBJECT_ID?: number; }
brainup-readby/readby-admin-portal
src/app/routes/users/users.component.ts
import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MtxGridColumn } from '@ng-matero/extensions'; import { UserModel } from './model/user-interface'; import { ApiService } from '../../shared/services/api.services'; import { LocalStorageService } from '../../shared/services/storage.service'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2/dist/sweetalert2.js'; @Component({ selector: 'app-users', templateUrl: './users.component.html', styleUrls: ['./users.component.scss'] }) export class UsersComponent implements OnInit { columns: MtxGridColumn[] = [ { header: 'User Name', field: 'USERNAME', sortable: true, showExpand: true }, { header: 'Name', field: 'FIRST_NAME', sortable: true}, { header: 'Email Id', field: 'EMAIL_ID', sortable: true, }, { header: 'Mobile No', field: 'MOBILE_NO', sortable: true, }, { header: 'Device Id', field: 'DEVICE_ID', sortable: true, }, { header: 'State', field: 'STATE', sortable: true, }, { header: 'City', field: 'CITY', sortable: true, }, { header: 'Pincode', field: 'PINCODE', sortable: true}, { header: 'Logout', field: 'logout', sortable: true}, { header: 'Status', field: 'IS_ACTIVE', type: 'tag', tag: { true: { text: 'Active', color: 'green-100' }, false: { text: 'In-Active', color: 'red-100' }, } } ]; nestedColumn: MtxGridColumn[] = [ { header: 'SUBSCRIPTION ID', field: 'SUBSCRIPTION_ID', sortable: true, }, { header: 'INSTITUTION NAME', field: 'INSTITUTION_NAME', sortable: true}, { header: 'EXPIRED', field: 'IS_EXPIRED', type: 'tag', tag: { n: { text: 'No', color: 'green-100' }, y: { text: 'Yes', color: 'red-100' }, } }, { header: 'STATUS', field: 'IS_ACTIVE', type: 'tag', tag: { t: { text: 'Active', color: 'green-100' }, f: { text: 'In-Active', color: 'red-100' }, } } ]; userlist: UserModel[]; isLoading = true; multiSelectable = true; rowSelectable = true; hideRowSelectionCheckbox = false; showToolbar = true; columnHideable = true; columnMovable = true; rowHover = false; rowStriped = false; showPaginator = true; expandable = false; constructor(private dialog: MatDialog, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService) { } ngOnInit(): void { this.getUserList(); } getUserList() { this.spiner.show(); this.service.sendGetRequest('getUserList').subscribe((res) => { this.spiner.hide(); this.userlist = res.data; console.log(this.userlist); }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } logoutUser(mobileNo: any) { this.spiner.show(); this.service.sendGetRequest('getLogoutDetail?mobileNo=' + mobileNo).subscribe((res) => { this.spiner.hide(); if (res.status === '200') { Swal.fire( 'Success', 'User Successfully Logout', 'success' ); } }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } }
brainup-readby/readby-admin-portal
src/app/routes/chapters/add-topic/add-topic.component.ts
import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { AddTopicModel } from './model/topic.model'; @Component({ selector: 'app-add-topic', templateUrl: './add-topic.component.html', styleUrls: ['./add-topic.component.scss'] }) export class AddTopicComponent implements OnInit { public imagePath; public imgURL: any; public message: string; fileIcon: any; topicModel = new AddTopicModel(); constructor(public dialogRef: MatDialogRef<AddTopicComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private service: ApiService) { this.topicModel.CHAPTER_ID = data.CHAPTER_ID; this.topicModel.IS_ACTIVE = 't'; } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } onFileSelected(event) { this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.fileIcon; // this.addCourseModel.icon_path = this.fileIcon; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } addTopic() { this.spiner.show(); const formData: FormData = new FormData(); formData.append('file', this.fileIcon[0], this.fileIcon[0].name); formData.append('masTopics', JSON.stringify(this.topicModel)); this.service.sendPostFormRequest('addTopics', formData).subscribe( (res: any) => { /* if (res === 'course added successfully') { this.destroyDailog(); Swal.fire( 'Success', 'Course saved successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } */ console.log(res); this.spiner.hide(); }, (error) => { console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire( 'Success', 'Subject Added In Course.', 'success' ); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } }
brainup-readby/readby-admin-portal
src/app/routes/board/board.component.ts
<filename>src/app/routes/board/board.component.ts<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MtxGridColumn } from '@ng-matero/extensions'; import { BoardModel } from './model/board-interface'; import { AddBoardComponent } from './add-board/add-board.component'; import { EditBoardComponent } from './edit-board/edit-board.component'; import { ApiService } from '../../shared/services/api.services'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { NgxSpinnerService } from 'ngx-spinner'; import { AddCourseComponent } from './add-course/add-course.component'; @Component({ selector: 'app-board', templateUrl: './board.component.html', styleUrls: ['./board.component.scss'], }) export class BoardComponent implements OnInit { columns: MtxGridColumn[] = [ { header: 'Code', field: 'BOARD_CODE', sortable: true }, { header: 'Name', field: 'BOARD_NAME', sortable: true }, { header: 'Status', field: 'IS_ACTIVE', sortable: true, type: 'tag', tag: { true: { text: 'Active', color: 'green-100' }, false: { text: 'In-Active', color: 'red-100' }, }, }, { header: 'Operation', field: 'operation', width: '160px', pinned: 'right', type: 'button', buttons: [ { icon: 'mode_edit', tooltip: 'Edit Board', type: 'icon', click: record => this.edit(record), }, { icon: 'delete_forever', tooltip: 'Delete Board', color: 'warn', type: 'icon', click: record => this.delete(record), }, { icon: 'add_circle_outline', tooltip: 'Add Course', type: 'icon', click: record => this.addCourse(record), }, ], }, ]; list: BoardModel[]; isLoading = true; multiSelectable = true; rowSelectable = true; hideRowSelectionCheckbox = false; showToolbar = true; columnHideable = true; columnMovable = true; rowHover = false; rowStriped = false; showPaginator = true; expandable = false; boardList = []; constructor( public dialog: MatDialog, private service: ApiService, private spiner: NgxSpinnerService ) {} ngOnInit(): void { this.getBoardList(); } getBoardList() { this.service.sendGetRequest('getBoardList').subscribe(res => { if (res.data) { // tslint:disable-next-line:prefer-for-of for (let index = 0; index < res.data.length; index++) { const json = { BOARD_ID: res.data[index].BOARD_ID, BOARD_NAME: res.data[index].BOARD_NAME, BOARD_CODE: res.data[index].BOARD_CODE, IS_ACTIVE: res.data[index].IS_ACTIVE.toUpperCase() === 'T' ? true : false, }; this.boardList.push(json); } } this.list = this.boardList; }); } edit(record: any) { this.dialog.open(EditBoardComponent, { data: record, disableClose: true, }); } delete(record: any) { Swal.fire({ title: 'Are you sure?', text: 'Want to delete board', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, go ahead.', cancelButtonText: 'No, let me think', }).then(result => { if (result.value) { this.spiner.show(); this.service.sendDeleteRequest('deleteBoard?boardId=' + record.BOARD_ID).subscribe( res => { this.spiner.hide(); if (res.status === '200') { Swal.fire('Deleted!', 'Board removed successfully.', 'success').then(okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire('Cancelled!', 'Something went worng, please try later', 'error'); } }, error => { this.spiner.hide(); Swal.fire(error.split(',')[0], error.split(',')[1], 'error'); } ); } else if (result.dismiss === Swal.DismissReason.cancel) { Swal.fire('Request Cancelled', 'Board still in our database.)', 'error'); } }); } addBoard() { this.dialog.open(AddBoardComponent, { disableClose: true, }); } addCourse(record) { this.dialog.open(AddCourseComponent, { data: record, disableClose: true, }); } }
brainup-readby/readby-admin-portal
src/app/routes/board/model/board-interface.ts
<reponame>brainup-readby/readby-admin-portal<gh_stars>0 export class BoardModel { BOARD_ID: number; BOARD_CODE: string; BOARD_NAME: string; IS_ACTIVE: string; MAS_COURSE: null; }
brainup-readby/readby-admin-portal
src/app/routes/chapters/model/chapter-interface.ts
export interface ChapterModel { CHAPTER_ID?: number; CHAPTER_NAME?: string; CHAPTER_CODE?: string; IS_ACTIVE?: string; icon_path?: File | null; SUBJECT_ID?: number; }
brainup-readby/readby-admin-portal
src/app/routes/users/model/user-interface.ts
<gh_stars>0 export interface UserModel { USER_ID?: number; USERNAME?: string; ROLE_ID?: number; FIRST_NAME?: string; MIDDLE_NAME?: string; LAST_NAME?: string; MOBILE_NO?: number; EMAIL_ID?: string; CITY?: string; STATE?: string; PINCODE?: string; IS_ACTIVE?: string; DEVICE_ID?: string; SESSION_TOKEN?: string; USER_SUBSCRIPTION?: UserSubscription[]; } export interface UserSubscription { SUBSCRIPTION_ID: number; USER_ID: number; STREAM_ID: number; YEAR_ID: number; IS_ACTIVE: string; IS_EXPIRED: string; SUBSCRIPTION_FLAG: string; COURSE_ID: number; BOARD_ID: number; MOBILE_NO: number; COURSE_STREAM_ID: number; MAS_STREAM: string; MAS_COURSE_YEAR: string; MAS_BOARD: string; MAS_COURSE: string; STUDENT_STUDY_STATE: string; INSTITUTION_NAME: string; }
brainup-readby/readby-admin-portal
src/app/routes/topics/model/topic-filter.model.ts
export class FilterModel { boardId: number; courseId: number; streamId: number; subjectId: number; chapterId: number; yearId: number; }
brainup-readby/readby-admin-portal
src/app/routes/board/add-board/add-board.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { NgForm } from '@angular/forms'; import { MatDialog, MatDialogRef } from '@angular/material/dialog'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import { BoardModel } from '../model/board-interface'; import Swal from 'sweetalert2/dist/sweetalert2.js'; @Component({ selector: 'app-add-board', templateUrl: './add-board.component.html', styleUrls: ['./add-board.component.scss'] }) export class AddBoardComponent implements OnInit { @ViewChild('addBoardForm', {static: false}) addBoardForm: NgForm; boardModel = { BOARD_CODE: '', BOARD_NAME: '', IS_ACTIVE: 'T' }; constructor(public dialogRef: MatDialogRef<AddBoardComponent>, public dialog: MatDialog, private service: ApiService, private spiner: NgxSpinnerService) { } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } addBoard() { this.spiner.show(); this.service.sendPostFormRequest('saveBoard', this.boardModel).subscribe( res => { this.spiner.hide(); Swal.fire( 'Success', 'Board successfully added.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } }
brainup-readby/readby-admin-portal
src/app/routes/courses/edit-course/model/course-model.ts
<reponame>brainup-readby/readby-admin-portal export class AddCourseModel { COURSE_CODE: string; COURSE_NAME: string; IS_ACTIVE: string; // tslint:disable-next-line:variable-name icon_path: string; COURSE_TYPE_ID: number; BOARD_ID: number; MAS_STREAM: MasStream[]; MAS_COURSE_YEAR: MasCourseYear[]; COURSE_TYPE: string; COURSE_PRICE: number; } export class MasCourseYear { YEAR: number; DISPLAY_NAME: string; } export class MasStream { STREAM_CODE: string; STREAM_NAME: string; }
brainup-readby/readby-admin-portal
src/app/routes/courses/courses.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { MtxDialog } from '@ng-matero/extensions/dialog'; import { MtxGridColumn } from '@ng-matero/extensions'; import { MatDialog } from '@angular/material/dialog'; import { AddSubjectComponent } from './add-subject/add-subject.component'; import { CourseModel } from './model/course-interface'; import { ApiService } from '../../shared/services/api.services'; import { LocalStorageService } from '../../shared/services/storage.service'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { NavigationEnd, Router } from '@angular/router'; import { EditCourseComponent } from './edit-course/edit-course.component'; import { AddStreamComponent } from './add-stream/add-stream.component'; import { AddYearComponent } from './add-year/add-year.component'; @Component({ selector: 'app-courses', templateUrl: './courses.component.html', styleUrls: ['./courses.component.scss'] }) export class CoursesComponent implements OnInit { courseModel: CourseModel[]; @ViewChild('statusCourse', { static: true }) statusCourse: TemplateRef<any>; columns: MtxGridColumn[] = [ { header: 'Code', field: 'courseCode', sortable: true }, { header: 'Board', field: 'boardName', sortable: true }, { header: 'Name', field: 'courseName', sortable: true}, { header: 'Image', field: 'iconPath', type: 'image'}, /* { header: 'Year', field: 'courseYear', sortable: true, }, { header: 'Stream', field: 'courseStream', sortable: true, }, */ { header: 'Type', field: 'courseType', sortable: true }, { header: 'Status', field: 'status', sortable: true, type: 'tag', tag: { true: { text: 'Active', color: 'green-100' }, false: { text: 'In-Active', color: 'red-100' }, } }, { header: 'Operation', field: 'operation', width: '240px', pinned: 'right', type: 'button', buttons: [ { icon: 'mode_edit', tooltip: 'Edit Course', type: 'icon', click: record => this.edit(record), }, { icon: 'delete_forever', tooltip: 'Delete Course', color: 'warn', type: 'icon', click: record => this.delete(record), }, { icon: 'add_circle_outline', tooltip: 'Add Subject', type: 'icon', click: record => this.addSubject(record), }, { icon: 'add_circle_outline', tooltip: 'Add Stream', type: 'icon', click: record => this.addStream(record), }, { icon: 'add_circle_outline', tooltip: 'Add Year', type: 'icon', click: record => this.addYear(record), }, ], }, ]; isLoading = true; multiSelectable = true; rowSelectable = true; hideRowSelectionCheckbox = false; showToolbar = true; columnHideable = true; columnMovable = true; rowHover = false; rowStriped = false; showPaginator = true; expandable = false; courseList = []; courseTypeList = []; mySubscription: any; constructor(private dialog: MatDialog, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private router: Router) { this.getCourseList(); this.courseTypeList = this.localStorage.get('courseType'); } ngOnInit(): void { } getCourseList() { this.spiner.show(); this.service.sendGetRequest('getCourseList').subscribe((res) => { // tslint:disable-next-line:prefer-for-of for (let index = 0; index < res.data.length; index++) { const element = { courseCode: res.data[index].COURSE_CODE, courseId: res.data[index].COURSE_ID, courseName: res.data[index].COURSE_NAME, boardId: res.data[index].BOARD_ID, courseStream: res.data[index].MAS_STREAM.length > 0 ? res.data[index].MAS_STREAM[0].STREAM_NAME : '', masStreamCode: res.data[index].MAS_STREAM.length > 0 ? res.data[index].MAS_STREAM[0].STREAM_CODE : '', courseType: res.data[index].MAS_COURSE_TYPE !== null ? res.data[index].MAS_COURSE_TYPE.COURSE_TYPE_NAME : '', courseTypeId: res.data[index].COURSE_TYPE_ID, courseYear: res.data[index].MAS_COURSE_YEAR.length > 0 ? res.data[index].MAS_COURSE_YEAR[0].YEAR : '', iconPath: res.data[index].icon_path, masCourse: res.data[index].MAS_STREAM, masCourseYear: res.data[index].MAS_COURSE_YEAR, status: res.data[index].IS_ACTIVE === 'f' ? false : true, boardName: res.data[index].BOARD_NAME, coursePrice: res.data[index].COURSE_PRICE }; this.courseList.push(element); } this.courseModel = this.courseList; this.spiner.hide(); }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } edit(record: any) { console.log(record); this.dialog.open(EditCourseComponent, { data: { selectedData: record, isUpdate: true }, disableClose: true }); } delete(record: any) { Swal.fire({ title: 'Are you sure?', text: 'Want to delete course', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, go ahead.', cancelButtonText: 'No, let me think' }).then((result) => { if (result.value) { this.spiner.show(); this.service.sendGetRequest('deleteCourse?courseId=' + record.courseId) .subscribe( res => { this.spiner.hide(); if (res.status === '200') { this.getCourseList(); Swal.fire( 'Deleted!', 'Course removed successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( 'Cancelled!', 'Something went worng, please try later', 'error' ); } }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } else if (result.dismiss === Swal.DismissReason.cancel) { Swal.fire( 'Cancelled', 'Course still in our database.)', 'error' ); } }); } addSubject(record: any) { this.dialog.open(AddSubjectComponent, { data: record, disableClose: true }); } addCourse() { this.dialog.open(EditCourseComponent, { data: { selectedData: null, isUpdate: false }, height: 'auto', disableClose: true }); } addStream(record) { this.dialog.open(AddStreamComponent, { data: record, height: 'auto', disableClose: true }); } addYear(record) { this.dialog.open(AddYearComponent, { data: record, height: 'auto', disableClose: true }); } }
brainup-readby/readby-admin-portal
src/app/routes/subjects/model/subject-interface.ts
export interface SubjectModel { SUBJECT_ID?: number; SUBJECT_NAME?: string; SUBJECT_CODE?: string; SUBJECT_PRICE?: number; // tslint:disable-next-line:variable-name icon_path?: string; }
brainup-readby/readby-admin-portal
src/app/shared/services/api.services.ts
import { Injectable, OnInit } from '@angular/core'; import { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest } from '@angular/common/http'; import { Observable, throwError, of, Subject } from 'rxjs'; import { retry, catchError, map, shareReplay, timeoutWith, share, tap } from 'rxjs/operators'; import { environment } from '../../../environments/environment'; @Injectable({ providedIn: 'root' }) export class ApiService implements OnInit { private readonly serviceOrigin = environment.SERVER_ORIGIN; private readonly serviceAppOrigin = environment.SERVER_APP_ORIGIN; private requestTimeoutLogger = of('logging request timeout'); private _refreshNeeded$ = new Subject<void>(); private timeoutThreshold = 5000; constructor(private http: HttpClient){} ngOnInit(): void { // throw new Error('Method not implemented.'); } getRefreshNeeded() { return this._refreshNeeded$; } public sendGetRequest(url: string): Observable<any> { return this.http.get<any>(this.serviceOrigin + url) .pipe( shareReplay(), // timeoutWith(timeoutThreshold), catchError(this.getServerErrorMessage), ); } public sendAppGetRequest(url: string): Observable<any> { return this.http.get<any>(this.serviceAppOrigin + url) .pipe( shareReplay(), // timeoutWith(timeoutThreshold), catchError(this.getServerErrorMessage), ); } public sendDeleteRequest(url: string): Observable<any> { return this.http.delete<any>(this.serviceOrigin + url) .pipe( shareReplay(), // timeoutWith(timeoutThreshold), catchError(this.getServerErrorMessage), ); } public sendPostFormRequest(url: string, body: any): Observable<any> { // let headers = new HttpHeaders(); // const headers = new HttpHeaders().set('Content-Type', 'multipart/form-data'); // tslint:disable-next-line:object-literal-shorthand return this.http.post<any>(this.serviceOrigin + url, body) .pipe( catchError(this.getServerErrorMessage) ); } private getServerErrorMessage(error: HttpErrorResponse) { switch (error.status) { case 404: { return throwError('404 Not Found, The URL has not been modified accordingly, or that you have misspelled the URL'); } case 405: { return throwError('405 Media Type not Supported, Method Not Allowed'); } case 403: { return throwError('403 Forbidden, You don’t have permission to access on this server'); } case 500: { return throwError('500 Internal Server Error, The server encountered an unexpected condition that prevented it from fulfilling the request.'); } case 400: { // this.toast.error('Bad request'); return throwError('400 Bad Request, The server can not process the request'); } case 201: { return throwError('Success'); } default: { return throwError('Unknown Server Error, An unknown server error occurred'); } } } }
brainup-readby/readby-admin-portal
src/app/shared/directives/numbers-only.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; import { NgControl } from '@angular/forms'; @Directive({ // tslint:disable-next-line:directive-selector selector: 'input[numbersOnly]' }) export class NumberDirective { constructor(private _el: ElementRef) { } @HostListener('input', ['$event']) onInputChange(event) { const initalValue = this._el.nativeElement.value; this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, ''); if ( initalValue !== this._el.nativeElement.value) { event.stopPropagation(); } } }
brainup-readby/readby-admin-portal
src/app/routes/courses/model/course-interface.ts
<filename>src/app/routes/courses/model/course-interface.ts import { StringLiteral } from 'typescript'; export interface CourseModel { courseCode: string; courseId: number; courseName: string; courseStream: string; courseType: string; courseYear: number; status: boolean; iconPath: string; masCourseType: string; masCourseYear: any; masStreamCode: string; boardId: number; courseTypeId: number; masStream: any; boardName: string; }
brainup-readby/readby-admin-portal
src/app/routes/chapters/edit-chapters/edit-chapters.component.ts
<filename>src/app/routes/chapters/edit-chapters/edit-chapters.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2'; import { ChapterModel } from '../model/chapter-interface'; @Component({ selector: 'app-edit-chapters', templateUrl: './edit-chapters.component.html', styleUrls: ['./edit-chapters.component.scss'] }) export class EditChaptersComponent implements OnInit { public imagePath; public imgURL: any; public message: string; chapterModel: ChapterModel; isImageUpdate: boolean; fileIcon: any; editedImagePath: any; serverResponse: any; constructor(public dialogRef: MatDialogRef<EditChaptersComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private router: Router) { this.chapterModel = data; console.log(this.chapterModel); this.imgURL = this.chapterModel.icon_path; } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } onFileSelected(event) { this.isImageUpdate = true; this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.editedImagePath; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } preview(files) { if (files.length === 0) { return; } const mimeType = files[0].type; if (mimeType.match(/image\/*/) == null) { this.message = 'Only images are supported.'; return; } const reader = new FileReader(); this.imagePath = files; reader.readAsDataURL(files[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } updateChapter() { const file: File = FileList[0]; const blob = new Blob(); this.spiner.show(); const formData: FormData = new FormData(); if (this.isImageUpdate) { formData.append('file', this.fileIcon[0], this.fileIcon[0].name); } else { formData.append('file', blob, this.fileIcon); } formData.append('masChapters', JSON.stringify(this.chapterModel)); this.service.sendPostFormRequest('editChapters', formData).subscribe( (res: any) => { this.serverResponse = res; this.spiner.hide(); }, (error) => { // console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire('Success', 'Chapter successfully Updated', 'success').then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } subjectModel(subjectModel: any): string | Blob { throw new Error('Method not implemented.'); } }
brainup-readby/readby-admin-portal
src/app/routes/topics/edit-topic/edit-topic.component.ts
<gh_stars>0 import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import { TopicModel } from '../model/topic-interface'; import Swal from 'sweetalert2/dist/sweetalert2.js'; @Component({ selector: 'app-edit-topic', templateUrl: './edit-topic.component.html', styleUrls: ['./edit-topic.component.scss'] }) export class EditTopicComponent implements OnInit { public imagePath; public imgURL: any; public message: string; topicModel: TopicModel; isImageUpdate: any; fileIcon: any; editedImagePath: any; serverResponse: any; constructor(public dialogRef: MatDialogRef<EditTopicComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private router: Router) { this.topicModel = data; this.topicModel.IS_ACTIVE = 't'; this.topicModel.VIDEO_URL = data.VIDEO_URL; this.imgURL = data.icon_path; this.topicModel.TOPIC_SUBSCRIPTION = data.TOPIC_SUBSCRIPTION; } ngOnInit(): void { } destroyDailog() { this.dialogRef.close(); } onSubmit() { console.log(this.topicModel); } onFileSelected(event) { this.isImageUpdate = true; this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.editedImagePath; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } preview(files) { if (files.length === 0) { return; } const mimeType = files[0].type; if (mimeType.match(/image\/*/) == null) { this.message = 'Only images are supported.'; return; } const reader = new FileReader(); this.imagePath = files; reader.readAsDataURL(files[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } updateTopic() { this.spiner.show(); const blob = new Blob(); const formData: FormData = new FormData(); delete this.topicModel.icon_path; if (this.isImageUpdate) { formData.append('file', this.fileIcon[0], this.fileIcon[0].name); } else { formData.append('file', blob, this.fileIcon); } formData.append('masTopics', JSON.stringify(this.topicModel)); this.service.sendPostFormRequest('editTopics', formData).subscribe( (res: any) => { this.serverResponse = res; this.spiner.hide(); }, (error) => { // console.log(error); this.spiner.hide(); if (error === 'Success') { this.destroyDailog(); Swal.fire('Success', 'Chapter successfully Updated', 'success').then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } }
brainup-readby/readby-admin-portal
src/app/routes/board/add-course/add-course.component.ts
<filename>src/app/routes/board/add-course/add-course.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2/dist/sweetalert2.js'; @Component({ selector: 'app-add-course', templateUrl: './add-course.component.html', styleUrls: ['./add-course.component.scss'] }) export class AddCourseComponent implements OnInit { courseTypeList = []; addCourseModel = { COURSE_CODE: '', COURSE_NAME: '', IS_ACTIVE: 't', COURSE_TYPE_ID: null, BOARD_ID: null, icon_path: 'c:/test', COURSE_PRICE: null }; fileIcon: any; imagePath: any; imgURL: string | ArrayBuffer; serverResponse: any; constructor(public dialogRef: MatDialogRef<AddCourseComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private localStorage: LocalStorageService, private spiner: NgxSpinnerService, private service: ApiService) { this.addCourseModel.BOARD_ID = data.BOARD_ID; } ngOnInit(): void { this.courseTypeList = this.localStorage.get('courseType'); } addCourse() { this.spiner.show(); this.addCourseModel.COURSE_PRICE = Number(this.addCourseModel.COURSE_PRICE); if (this.addCourseModel.COURSE_PRICE <= 0) { Swal.fire( 'Error', 'Price should be grater than 0', 'error' ); this.spiner.hide(); return; } const formData: FormData = new FormData(); formData.append('file', this.fileIcon[0], this.fileIcon[0].name); formData.append('masCourse', JSON.stringify(this.addCourseModel)); this.service.sendPostFormRequest('addCourses', formData).subscribe( (res: any) => { this.serverResponse = res; if (res === 'course added successfully') { this.destroyDailog(); Swal.fire( 'Success', 'Course saved successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } this.spiner.hide(); }, (error) => { console.log(error); this.spiner.hide(); if (error === 'Success') { Swal.fire( 'Success', 'Course saved successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); } }); } destroyDailog() { this.dialogRef.close(); } onFileSelected(event) { this.fileIcon = event.target.files; const reader = new FileReader(); this.imagePath = this.fileIcon; // this.addCourseModel.icon_path = this.fileIcon; reader.readAsDataURL(this.fileIcon[0]); reader.onload = (_event) => { this.imgURL = reader.result; }; } }
brainup-readby/readby-admin-portal
src/app/routes/chapters/chapters.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MtxGridColumn } from '@ng-matero/extensions'; import { ChapterModel } from './model/chapter-interface'; import { EditChaptersComponent } from './edit-chapters/edit-chapters.component'; import { AddTopicComponent } from './add-topic/add-topic.component'; import { LocalStorageService } from '@shared'; import { ApiService } from '@shared/services/api.services'; import { NgxSpinnerService } from 'ngx-spinner'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { FilterChpModel } from './model/filter.chapter.model'; @Component({ selector: 'app-chapters', templateUrl: './chapters.component.html', styleUrls: ['./chapters.component.scss'] }) export class ChaptersComponent implements OnInit { filterChpMdl = new FilterChpModel(); boardList = []; boardFilterList = []; boardIdSelected: any; courseList = []; masYearList = []; masStreamList = []; subjectList = []; subjectId: number; yearSelected: any; columns: MtxGridColumn[] = [ { header: 'Chapter Code', field: 'CHAPTER_CODE', sortable: true, }, { header: 'Icon', field: 'icon_path', type: 'image'}, { header: 'Chapter Name', field: 'CHAPTER_NAME', sortable: true, }, { header: 'Status', field: 'IS_ACTIVE', sortable: true, type: 'tag', tag: { t: { text: 'Active', color: 'green-100' }, f: { text: 'In-Active', color: 'red-100' }, } }, { header: 'Operation', field: 'operation', width: '160px', pinned: 'right', type: 'button', buttons: [ { icon: 'mode_edit', tooltip: 'Edit Course', type: 'icon', click: record => this.edit(record), }, { icon: 'delete_forever', tooltip: 'Delete Course', color: 'warn', type: 'icon', click: record => this.delete(record), }, { icon: 'add_circle_outline', tooltip: 'Add Topic', type: 'icon', click: record => this.add(record), }, ], }, ]; chapterList: ChapterModel[]; isLoading = true; multiSelectable = true; rowSelectable = true; hideRowSelectionCheckbox = false; showToolbar = true; columnHideable = true; columnMovable = true; rowHover = false; rowStriped = false; showPaginator = true; expandable = false; constructor(public dialog: MatDialog, private service: ApiService, private localStorage: LocalStorageService, private spiner: NgxSpinnerService) { } ngOnInit(): void { this.getChapterList(); this.getBoardList(); } getChapterList() { this.spiner.show(); this.service.sendGetRequest('getChapterList').subscribe((res) => { this.spiner.hide(); this.chapterList = res.data; }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } edit(record) { this.dialog.open(EditChaptersComponent, { data: record, disableClose: true }); } delete(record: any) { Swal.fire({ title: 'Are you sure?', text: 'Want to delete chapter', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, go ahead.', cancelButtonText: 'No, let me think' }).then((result) => { if (result.value) { this.spiner.show(); this.service.sendDeleteRequest('deleteChapter?chapterId=' + record.CHAPTER_ID) .subscribe( res => { this.spiner.hide(); if (res.status === '200') { Swal.fire( 'Deleted!', 'Chapter removed successfully.', 'success' ).then( okay => { if (okay) { window.location.reload(); } }); } else { Swal.fire( 'Cancelled!', 'Something went worng, please try later', 'error' ); } }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } else if (result.dismiss === Swal.DismissReason.cancel) { Swal.fire( 'Cancelled', 'Chapter still in our database.)', 'error' ); } }); } add(record) { this.dialog.open(AddTopicComponent, { data: record, disableClose: true }); } getBoardList() { this.service.sendAppGetRequest('getBoardDetail').subscribe( (res) => { if (res.data) { this.boardFilterList = res.data; this.boardFilterList.forEach(brdEl => { const json = { BOARD_ID: brdEl.BOARD_ID, BOARD_NAME: brdEl.BOARD_NAME }; this.boardList.push(json); }); } console.log(this.boardFilterList); }); } onBoardChange(event) { this.courseList = []; this.masStreamList = []; this.subjectList = []; this.masYearList = []; this.boardFilterList.filter(f => f.BOARD_ID === event.value).forEach(el => { el.MAS_COURSE.forEach(element => { const courseJson = { COURSE_ID: element.COURSE_ID, COURSE_NAME: element.COURSE_NAME }; this.courseList.push(element); }); }); } onCourseChange(event) { this.masStreamList = []; this.subjectList = []; this.masYearList = []; this.courseList.filter(f => f.COURSE_ID === event.value).forEach(el => { el.MAS_STREAM.forEach(element => { this.masStreamList.push(element); }); if (el.MAS_COURSE_YEAR !== null && el.MAS_COURSE_YEAR !== undefined) { this.masYearList.push(el.MAS_COURSE_YEAR[0]); this.yearSelected = this.masYearList[0].YEAR_ID; } }); } onStreamChange(event) { this.subjectList = []; this.service.sendGetRequest('getSubjectByStreamOrYear?streamId=' + event.value).subscribe( (res) => { this.subjectList = res.data; }); } onSubjectChange(event) { this.subjectId = event.value; } getFilteredChapterList() { this.chapterList = []; this.spiner.show(); this.service.sendGetRequest('getChaptersBySubject?subjectId=' + this.subjectId).subscribe( (res) => { this.spiner.hide(); this.chapterList = res.data; }, (error) => { this.spiner.hide(); Swal.fire( error.split(',')[0], error.split(',')[1], 'error' ); }); } }
predominant/builder
components/builder-web/app/side-nav/side-nav.component.ts
<reponame>predominant/builder // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { Component, Input } from '@angular/core'; import config from '../config'; @Component({ selector: 'hab-side-nav', template: require('./side-nav.component.html') }) export class SideNavComponent { @Input() isSignedIn; get config() { return config; } }
predominant/builder
components/builder-web/app/actions/oauth.ts
<filename>components/builder-web/app/actions/oauth.ts // Copyright (c) 2018 Chef Software Inc. and/or applicable contributors // // 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 'whatwg-fetch'; import config from '../config'; import { setCurrentUsername, addNotification, fetchMyOrigins, fetchMyOriginInvitations, fetchProfile, setPrivileges, signingIn, signInFailed } from './index'; import { DANGER } from './notifications'; import { setBldrSessionToken } from './sessions'; import { Browser } from '../browser'; import { OAuthProvider } from '../oauth-providers'; const uuid = require('uuid').v4; const authenticateEndpoint = '/v1/authenticate'; export const LOAD_OAUTH_STATE = 'LOAD_OAUTH_STATE'; export const POPULATE_GITHUB_INSTALLATIONS = 'POPULATE_GITHUB_INSTALLATIONS'; export const POPULATE_GITHUB_REPOSITORIES = 'POPULATE_GITHUB_REPOSITORIES'; export const SET_OAUTH_PROVIDER = 'SET_OAUTH_PROVIDER'; export const SET_OAUTH_STATE = 'SET_OAUTH_STATE'; export const SET_OAUTH_TOKEN = 'SET_OAUTH_TOKEN'; export function authenticate(oauthToken: string, bldrToken: string) { return (dispatch, getState) => { if (oauthToken) { dispatch(setOAuthToken(oauthToken)); } if (bldrToken) { dispatch(setBldrSessionToken(bldrToken)); dispatch(fetchMyOrigins(bldrToken)); dispatch(fetchMyOriginInvitations(bldrToken)); dispatch(fetchProfile(bldrToken)); } }; } export function exchangeOAuthCode(code: string, state: string) { return (dispatch, getState) => { if (getState().oauth.provider.useState && state !== getState().oauth.state) { dispatch(signInFailed()); return; } dispatch(signingIn(true)); fetch(`${authenticateEndpoint}/${code}`).then(response => { return response.json(); }) .then(data => { dispatch(signingIn(false)); if (data.oauth_token && data.token) { dispatch(authenticate(data.oauth_token, data.token)); dispatch(setCurrentUsername(data.login)); dispatch(setPrivileges(data.flags)); } else { dispatch(signInFailed()); dispatch(addNotification({ title: 'Authentication Failed', body: `[err=${data.code}] ${data.msg}`, type: DANGER })); } }) .catch(error => { dispatch(signingIn(false)); dispatch(signInFailed()); dispatch(addNotification({ title: 'Authentication Failed', body: 'Unable to retrieve OAuth token.', type: DANGER })); }); }; } export function loadOAuthState() { return { type: LOAD_OAUTH_STATE, payload: { token: Browser.getCookie('oauthToken'), state: Browser.getCookie('oauthState') }, }; } export function removeSession() { return dispatch => { Browser.removeCookie('oauthState'); Browser.removeCookie('oauthToken'); Browser.removeCookie('bldrSessionToken'); }; } export function setOAuthState() { let payload = Browser.getCookie('oauthState') || uuid(); Browser.setCookie('oauthState', payload); return { type: SET_OAUTH_STATE, payload }; } export function loadOAuthProvider() { return (dispatch, getState) => { dispatch(setOAuthState()); dispatch(setOAuthProvider( OAuthProvider.fromConfig( config.oauth_provider, config.oauth_client_id, config.oauth_authorize_url, config.oauth_redirect_url, config.oauth_signup_url, getState().oauth.state ) )); }; } function setOAuthProvider(payload) { return { type: SET_OAUTH_PROVIDER, payload }; } export function setOAuthToken(payload) { Browser.setCookie('oauthToken', payload); return { type: SET_OAUTH_TOKEN, payload }; }
predominant/builder
components/builder-web/app/origin/origin-page/origin-page.module.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { CommonModule, } from '@angular/common'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { MatTabsModule, MatRadioModule, MatButtonModule, MatDialogModule } from '@angular/material'; import { IntegrationDeleteConfirmDialog } from './origin-integrations-tab/dialog/integration-delete-confirm/integration-delete-confirm.dialog'; import { GenerateKeysConfirmDialog } from './origin-keys-tab/dialog/generate-keys-confirm/generate-keys-confirm.dialog'; import { KeyAddFormDialog } from './origin-keys-tab/key-add-form/key-add-form.dialog'; import { OriginPageRoutingModule } from './origin-page-routing.module'; import { OriginPageComponent } from './origin-page.component'; import { OriginPackagesTabComponent } from './origin-packages-tab/origin-packages-tab.component'; import { OriginMembersTabComponent } from './origin-members-tab/origin-members-tab.component'; import { OriginKeysTabComponent } from './origin-keys-tab/origin-keys-tab.component'; import { OriginSettingsTabComponent } from './origin-settings-tab/origin-settings-tab.component'; import { OriginIntegrationsTabComponent } from './origin-integrations-tab/origin-integrations-tab.component'; import { IntegrationCredentialsFormDialog } from './integration-credentials-form/integration-credentials-form.dialog'; import { SharedModule } from '../../shared/shared.module'; import { OriginJobsTabComponent } from './origin-jobs-tab/origin-jobs-tab.component'; import { OriginJobsListComponent } from './origin-jobs-tab/jobs-list/jobs-list.component'; import { OriginJobDetailComponent } from './origin-job-detail/origin-job-detail.component'; export const imports = [ BrowserAnimationsModule, CommonModule, FormsModule, MatTabsModule, MatRadioModule, MatDialogModule, MatButtonModule, ReactiveFormsModule, RouterModule, OriginPageRoutingModule, SharedModule ]; export const declarations = [ IntegrationCredentialsFormDialog, GenerateKeysConfirmDialog, IntegrationDeleteConfirmDialog, KeyAddFormDialog, OriginKeysTabComponent, OriginMembersTabComponent, OriginPackagesTabComponent, OriginPageComponent, OriginSettingsTabComponent, OriginIntegrationsTabComponent, OriginJobsTabComponent, OriginJobsListComponent, OriginJobDetailComponent ]; const entryComponents = [ IntegrationCredentialsFormDialog, GenerateKeysConfirmDialog, IntegrationDeleteConfirmDialog, KeyAddFormDialog ]; @NgModule({ imports, declarations, entryComponents }) export class OriginPageModule { }
predominant/builder
components/builder-web/app/shared/guards/signed-in.guard.ts
<reponame>predominant/builder<filename>components/builder-web/app/shared/guards/signed-in.guard.ts // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; import { AppStore } from '../../app.store'; import { Browser } from '../../browser'; import { requestRoute, signOut } from '../../actions/index'; @Injectable() export class SignedInGuard implements CanActivate { constructor(private store: AppStore, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, routerState: RouterStateSnapshot): Promise<boolean> { const state = this.store.getState(); const signedIn = !!state.session.token; const signingIn = state.users.current.isSigningIn; const signInFailed = state.users.current.failedSignIn; return new Promise((resolve, reject) => { if (signedIn) { resolve(true); } else if (signInFailed) { reject(() => this.redirectToSignIn()); } else if (signingIn) { this.handleSigningIn(resolve, reject); } else { reject(() => { if (routerState.url === '/origins') { this.sendHome(); } else { this.redirectToSignIn(routerState.url); } }); } }) .catch(next => next()) .then(() => true); } private handleSigningIn(resolve, reject) { const unsub = this.store.subscribe(state => { if (state.oauth.token && state.session.token) { const name = 'redirectPath'; const path = Browser.getCookie(name); Browser.removeCookie(name); if (path) { this.router.navigate([path]); } resolve(true); unsub(); } else if (state.users.current.failedSignIn) { reject(() => this.redirectToSignIn()); unsub(); } }); } private sendHome() { this.store.dispatch(requestRoute(['/pkgs'])); } private redirectToSignIn(url?: string) { this.store.dispatch(signOut(true, url)); } }
predominant/builder
components/builder-web/app/profile/profile/profile.component.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { Component, OnInit, OnDestroy} from '@angular/core'; import { MatDialog } from '@angular/material'; import { Title } from '@angular/platform-browser'; import { AppStore } from '../../app.store'; import { SimpleConfirmDialog } from '../../shared/dialog/simple-confirm/simple-confirm.dialog'; import { clearAccessTokens, clearNewAccessToken, deleteAccessToken, fetchProfile, fetchAccessTokens, generateAccessToken, saveProfile } from '../../actions/index'; import config from '../../config'; @Component({ template: require('./profile.component.html') }) export class ProfileComponent implements OnInit, OnDestroy { constructor( private confirmDialog: MatDialog, private store: AppStore, private title: Title ) { this.title.setTitle(`My Profile | Habitat`); } ngOnInit() { this.fetch(); } ngOnDestroy() { this.clearAccessTokens(); } generateToken(regenerate = false) { if (regenerate) { this.confirmDialog .open(SimpleConfirmDialog, { width: '480px', data: { heading: 'Regenerate token', body: `Are you sure you want to regenerate your token? Doing so will invalidate and replace the current token.`, action: `I'm sure` } }) .afterClosed() .subscribe((confirmed) => { if (confirmed) { this.store.dispatch(generateAccessToken(this.token)); } }); } else { this.store.dispatch(generateAccessToken(this.token)); } } deleteToken(id) { this.confirmDialog .open(SimpleConfirmDialog, { width: '480px', data: { heading: 'Delete token', body: `Are you sure you want to delete this token? You will no longer be able to interact with Builder via the CLI.`, action: `I'm sure` } }) .afterClosed() .subscribe((confirmed) => { if (confirmed) { this.store.dispatch(deleteAccessToken(id, this.token)); this.clearAccessTokens(); } }); } save(form) { this.store.dispatch(saveProfile({ email: form.email }, this.token)); } get accessToken() { return this.store.getState().users.current.accessTokens[0]; } get config() { return config; } get newAccessToken() { return this.store.getState().users.current.newAccessToken; } get loadingAccessTokens() { return this.store.getState().users.current.ui.accessTokens.loading; } get generatingAccessToken() { return this.store.getState().users.current.ui.accessTokens.generating; } get deletingAccessToken() { return this.store.getState().users.current.ui.accessTokens.deleting; } get buttonLabel() { return (this.accessToken || this.newAccessToken) ? 'Regenerate' : 'Generate Token'; } get processingLabel() { if (this.generatingAccessToken) { return 'Generating token'; } if (this.deletingAccessToken) { return 'Deleting'; } } get profile() { return this.store.getState().users.current.profile; } get providerType() { return this.store.getState().oauth.provider.type; } get providerName() { return this.store.getState().oauth.provider.name; } get token() { return this.store.getState().session.token; } private fetch() { this.store.dispatch(fetchProfile(this.token)); this.store.dispatch(fetchAccessTokens(this.token)); } private clearAccessTokens() { this.store.dispatch(clearAccessTokens()); this.store.dispatch(clearNewAccessToken()); } }
predominant/builder
components/builder-web/app/shared/platform-icon/platform-icon.component.ts
<gh_stars>1-10 import { Component, Input } from '@angular/core'; import { targetToPlatform } from '../../util'; @Component({ selector: 'hab-platform-icon', template: `<hab-icon [symbol]="os" class="icon-os" [title]="title"></hab-icon>` }) export class PlatformIconComponent { @Input() platform; get os() { return targetToPlatform(this.platform); } get title() { return { linux: 'Linux', kernel2: 'Linux (Kernel Version 2)', windows: 'Windows' }[this.os] || ''; } }
predominant/builder
components/builder-web/app/shared/job-status-icon/job-status-icon.component.ts
import { Component, Input } from '@angular/core'; import { iconForJobState, labelForJobState } from '../../util'; @Component({ selector: 'hab-job-status-icon', template: `<hab-icon [ngClass]="classes" [symbol]="symbol" [title]="label" [attr.title]="label"></hab-icon>` }) export class JobStatusIconComponent { @Input() job: any; @Input() status: string; @Input() animate: boolean = false; private get _status() { return this.status || (this.job && this.job.state ? this.job.state : ''); } private get classes() { let c = [this._status.toLowerCase()]; if (this.animate) { c.push('animate'); } return c; } private get symbol() { if (this._status) { return iconForJobState(this._status); } } private get label() { if (this._status) { return labelForJobState(this._status); } } }
predominant/builder
components/builder-web/app/client/depot-api.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 'whatwg-fetch'; import config from '../config'; import { packageString } from '../util'; import { AppStore } from '../app.store'; import { addNotification, signOut } from '../actions/index'; import { WARNING } from '../actions/notifications'; const urlPrefix = '/v1'; function opts() { const store = new AppStore(); let token = store.getState().session.token; let o: any = {}; if (token) { o.headers = { Authorization: `Bearer ${token}` }; } return o; } function handleError(error, reject) { const store = new AppStore(); const state = store.getState(); store.dispatch(signOut(true, state.router.route.url)); reject(error); if (state.session.token) { setTimeout(() => { store.dispatch(addNotification({ title: 'Session Expired', body: 'Please sign in again.', type: WARNING })); }, 1000); } } function handleUnauthorized(response, reject) { if (response.status === 401) { throw new Error('Unauthorized'); } return response; } export function demotePackage(origin: string, name: string, version: string, release: string, target: string, channel: string, token: string) { const url = `${urlPrefix}/depot/channels/${origin}/${channel}/pkgs/${name}/${version}/${release}/demote?target=${target}`; return new Promise((resolve, reject) => { fetch(url, { headers: { Authorization: `Bearer ${token}`, }, method: 'PUT', }) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.ok) { resolve(true); } else { reject(new Error(response.statusText)); } }) .catch(error => handleError(error, reject)); }); } export function getUnique(origin: string, nextRange: number = 0, token: string = '') { const url = `${urlPrefix}/depot/${origin}/pkgs?range=${nextRange}`; return new Promise((resolve, reject) => { fetch(url, opts()) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.status >= 400) { reject(new Error(response.statusText)); } else { response.json().then(resultsObj => { let results; const endRange = parseInt(resultsObj.range_end, 10); const totalCount = parseInt(resultsObj.total_count, 10); const nextRange = totalCount > (endRange + 1) ? endRange + 1 : 0; if (resultsObj['data']) { results = resultsObj['data']; } else { results = resultsObj; } resolve({ results, totalCount, nextRange }); }); } }) .catch(error => handleError(error, reject)); }); } export function getLatest(origin: string, pkg: string) { const url = `${urlPrefix}/depot/pkgs/${origin}/${pkg}/latest?target=x86_64-linux`; return new Promise((resolve, reject) => { fetch(url, opts()) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.status >= 400) { reject(new Error(response.statusText)); } else { response.json().then(results => { resolve(results); }); } }) .catch(error => handleError(error, reject)); }); } export function getLatestInChannel(origin: string, name: string, channel: string, version: string = undefined) { const url = `${urlPrefix}/depot/channels/${origin}/${channel}/pkgs/${name}/${version ? version + '/' : ''}latest?target=x86_64-linux`; return new Promise((resolve, reject) => { fetch(url, opts()) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.status >= 400) { reject(new Error(response.statusText)); } else { response.json().then(results => { resolve(results); }); } }) .catch(error => handleError(error, reject)); }); } export function get(params, nextRange: number = 0) { let url = `${urlPrefix}/depot/pkgs/` + (params['query'] ? `search/${params['query']}` : packageString(params)) + `?range=${nextRange}`; if (params['distinct']) { url += '&distinct=true'; } return new Promise((resolve, reject) => { fetch(url, opts()) .then(response => handleUnauthorized(response, reject)) .then(response => { // Fail the promise if an error happens. // // If we're hitting the fake api, the 4xx response will show up // here, but if we're hitting the real Builder, it will show up in the // catch below. if (response.status >= 400) { reject(new Error(response.statusText)); } else { response.json().then(resultsObj => { let results; const endRange = parseInt(resultsObj.range_end, 10); const totalCount = parseInt(resultsObj.total_count, 10); const nextRange = totalCount > (endRange + 1) ? endRange + 1 : 0; if (resultsObj['data']) { results = resultsObj['data']; } else { results = resultsObj; } resolve({ results, totalCount, nextRange }); }); } }) .catch(error => handleError(error, reject)); }); } export function getPackageChannels(origin: string, name: string, version: string, release: string) { const url = `${urlPrefix}/depot/pkgs/${origin}/${name}/${version}/${release}/channels`; return new Promise((resolve, reject) => { fetch(url, opts()) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.status >= 400) { reject(new Error(response.statusText)); } else { response.json().then(results => { resolve(results); }); } }) .catch(error => handleError(error, reject)); }); } export function getPackageVersions(origin: string, pkg: string) { const url = `${urlPrefix}/depot/pkgs/${origin}/${pkg}/versions`; return new Promise((resolve, reject) => { fetch(url, opts()) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.status >= 400) { reject(new Error(response.statusText)); } else { response.json().then(results => { resolve(results); }); } }) .catch(error => handleError(error, reject)); }); } export function promotePackage(origin: string, name: string, version: string, release: string, target: string, channel: string, token: string) { const url = `${urlPrefix}/depot/channels/${origin}/${channel}/pkgs/${name}/${version}/${release}/promote?target=${target}`; return new Promise((resolve, reject) => { fetch(url, { headers: { Authorization: `Bearer ${token}`, }, method: 'PUT', }) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.ok) { resolve(true); } else { reject(new Error(response.statusText)); } }) .catch(error => handleError(error, reject)); }); } export function submitJob(origin: string, pkg: string, token: string) { const url = `${urlPrefix}/depot/pkgs/schedule/${origin}/${pkg}`; return new Promise((resolve, reject) => { fetch(url, { headers: { Authorization: `Bearer ${token}`, }, method: 'POST', }) .then(response => handleUnauthorized(response, reject)) .then(response => { if (response.ok) { resolve(true); } else { reject(new Error(response.statusText)); } }) .catch(error => handleError(error, reject)); }); }
predominant/builder
components/builder-web/app/origin/origin.module.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatButtonModule } from '@angular/material'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { SharedModule } from '../shared/shared.module'; import { OriginPageModule } from './origin-page/origin-page.module'; import { OriginRoutingModule } from './origin-routing.module'; import { OriginsPageComponent } from './origins-page/origins-page.component'; import { OriginCreatePageComponent } from './origin-create-page/origin-create-page.component'; import { OriginService } from './origin.service'; // This is so we can test that the ordering of the modules is correct. // Ordering matters in this case because we have a static route 'create' // that can get interpreted as the route variable :origin export const imports = [ CommonModule, FormsModule, MatButtonModule, OriginRoutingModule, OriginPageModule, ReactiveFormsModule, SharedModule ]; export const declarations = [ OriginsPageComponent, OriginCreatePageComponent ]; @NgModule({ imports, declarations, providers: [ OriginService ] }) export class OriginModule { }
predominant/builder
components/builder-web/app/banner/banner.component.ts
<filename>components/builder-web/app/banner/banner.component.ts import { Component } from '@angular/core'; import { AppStore } from '../app.store'; @Component({ selector: 'hab-banner', template: require('./banner.component.html') }) export class BannerComponent { dismissed: boolean = false; constructor(private store: AppStore) {} get hidden() { return this.profile.id && !this.dismissed; } get profile() { return this.store.getState().users.current.profile; } dismiss() { this.dismissed = true; } }
predominant/builder
components/builder-web/app/origin/origin-routing.spec.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { Location } from '@angular/common'; import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { MatButtonModule } from '@angular/material'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { Router } from '@angular/router'; import { imports, declarations } from './origin.module'; imports.push(RouterTestingModule); describe('Router: Origin', () => { let location: Location; let router: Router; beforeEach(() => { TestBed.configureTestingModule({ imports, declarations }); router = TestBed.get(Router); location = TestBed.get(Location); router.initialNavigation(); }); it('navigate to origins/create takes you to create page', () => { router.navigate(['/origins/create']).then(() => { expect(location.path()).toBe('/origins/create'); }); }); it('navigate to origins/create takes you to the correct place', () => { router.navigate(['/origins/create']).then(() => { expect(location.path()).toBe('/origins/create'); }); }); });
predominant/builder
components/builder-web/app/origin/origin-page/origin-job-detail/origin-job-detail.component.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { MatDialog } from '@angular/material'; import { AppStore } from '../../../app.store'; import { Title } from '@angular/platform-browser'; import { Subscription } from 'rxjs'; import { JobCancelDialog } from '../../../shared/dialog/job-cancel/job-cancel.dialog'; import { fetchJobGroup, cancelJobGroup } from '../../../actions/index'; import { parseDate, iconForJobState } from '../../../util'; @Component({ selector: 'hab-origin-job-detail', template: require('./origin-job-detail.component.html') }) export class OriginJobDetailComponent implements OnInit, OnDestroy { origin: string; name: string; id: string; selected: object; private sub: Subscription; private parentSub: Subscription; private poll: number; private completedStates = ['success', 'failure']; private cancelableStates = ['notstarted', 'inprogress']; constructor( private route: ActivatedRoute, private store: AppStore, private router: Router, private cancelDialog: MatDialog, private title: Title ) { this.sub = this.route.params.subscribe((params) => { this.id = params['id']; this.title.setTitle(`Packages › Build Job Groups > ${this.id} | Habitat`); }); this.parentSub = this.route.parent.params.subscribe((params) => this.origin = params['origin']); } ngOnInit() { this.poll = window.setInterval(() => { this.fetchJobGroup(); }, 5000); this.fetchJobGroup(); } ngOnDestroy() { if (this.sub) { this.sub.unsubscribe(); this.parentSub.unsubscribe(); } window.clearInterval(this.poll); } get cancelableCount() { return this.cancelableStates.reduce((total, state) => { const stateList = this.group.projects_by_state[state]; total += stateList ? stateList.length : 0; return total; }, 0); } get completedCount() { return this.completedStates.reduce((total, state) => { const stateList = this.group.projects_by_state[state]; total += stateList ? stateList.length : 0; return total; }, 0); } get group() { return this.store.getState().jobGroups.selected; } get projects() { return this.group.projects; } get token() { return this.store.getState().session.token; } get totalCount() { return this.group.projects.length; } projectStateCount(param) { const stateList = this.group.projects_by_state[param]; return stateList ? stateList.length : 0; } dateFor(timestamp) { return parseDate(timestamp, 'YYYY-MM-DD HH:mm:ss'); } onSelectJob(name, job) { this.router.navigate(['pkgs', ...name.split('/'), 'jobs', job]); } backToGroups() { this.router.navigate(['origins', this.origin, 'jobs']); } hasJobId(project) { return project.job_id !== '0'; } cancel(id) { this.cancelDialog .open(JobCancelDialog, { width: '480px', data: { cancelableCount: this.cancelableCount } }) .afterClosed() .subscribe(confirmed => { if (confirmed) { this.store.dispatch(cancelJobGroup(this.id, this.token)); } }); } private fetchJobGroup() { if (this.token) { this.store.dispatch(fetchJobGroup(this.id, this.token)); } } }
predominant/builder
components/builder-web/app/reducers/index.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { combineReducers } from 'redux'; import app from './app'; import gitHub from './gitHub'; import jobs from './jobs'; import jobGroups from './jobGroups'; import features from './features'; import notifications from './notifications'; import oauth from './oauth'; import origins from './origins'; import packages from './packages'; import projects from './projects'; import router from './router'; import session from './sessions'; import users from './users'; import ui from './ui'; export default combineReducers({ app, gitHub, jobs, jobGroups, features, notifications, oauth, origins, packages, projects, router, session, ui, users });
predominant/builder
components/builder-web/app/app.store.ts
<reponame>predominant/builder<filename>components/builder-web/app/app.store.ts // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { Injectable } from '@angular/core'; import { applyMiddleware, compose, createStore } from 'redux'; import rootReducer from './reducers/index'; import thunk from 'redux-thunk'; import reduxReset from 'redux-reset'; const composeEnhancers = window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] || compose; const finalCreateStore = composeEnhancers( // The thunk middleware allows an action to return a function that takes a // dispatch argument instead of returning an object directly. This allows // actions to make async calls. applyMiddleware(thunk), // Allows resetting of the store reduxReset() )(createStore); const appStore = finalCreateStore(rootReducer); @Injectable() export class AppStore { private store = appStore; getState(): any { return this.store.getState(); } dispatch(action) { this.store.dispatch(action); } subscribe(listener: Function) { return this.store.subscribe(() => listener(this.getState())); } }
predominant/builder
components/builder-web/app/search/search/search.component.spec.ts
<gh_stars>0 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { DebugElement } from '@angular/core'; import { TestBed, ComponentFixture } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of } from 'rxjs'; import { List } from 'immutable'; import { MockComponent } from 'ng2-mock-component'; import * as actions from '../../actions/index'; import { AppStore } from '../../app.store'; import { SearchComponent } from './search.component'; class MockAppStore { static state; getState() { return MockAppStore.state; } dispatch() { } } class MockRoute { get params() { return of({}); } } describe('SearchComponent', () => { let fixture: ComponentFixture<SearchComponent>; let component: SearchComponent; let element: DebugElement; let store: AppStore; beforeEach(() => { MockAppStore.state = { packages: { visible: List(), ui: { visible: {} } } }; }); beforeEach(() => { TestBed.configureTestingModule({ imports: [ ReactiveFormsModule, RouterTestingModule, MatInputModule, NoopAnimationsModule ], declarations: [ MockComponent({ selector: 'hab-package-breadcrumbs', inputs: ['ident'] }), MockComponent({ selector: 'hab-icon', inputs: ['symbol'] }), MockComponent({ selector: 'hab-search-results', inputs: ['errorMessage', 'noPackages', 'layout', 'packages', 'versions'] }), SearchComponent ], providers: [ { provide: AppStore, useClass: MockAppStore }, { provide: ActivatedRoute, useClass: MockRoute } ] }); fixture = TestBed.createComponent(SearchComponent); component = fixture.componentInstance; element = fixture.debugElement; store = TestBed.get(AppStore); }); describe('given the core origin', () => { beforeEach(() => { component.origin = 'core'; fixture.detectChanges(); }); it('shows the Search Packages heading', () => { let heading = element.query(By.css('.search-component h1')); expect(heading.nativeElement.textContent).toBe('Search Packages'); }); }); describe('search', () => { describe('given a query', () => { beforeEach(() => { let query = 'foo'; component.query = query; MockAppStore.state.packages.searchQuery = query; fixture.detectChanges(); }); it('shows the Search Packages heading', () => { let heading = element.query(By.css('.search-component h1')); expect(heading.nativeElement.textContent).toBe('Search Packages'); }); it('shows the search box', () => { expect(element.query(By.css('.body input[type=\'search\']'))).not.toBeNull(); }); describe('fetchPackages', () => { it('fetches with the distinct parameter', () => { spyOn(actions, 'filterPackagesBy'); component.fetchPackages(); expect(actions.filterPackagesBy).toHaveBeenCalledWith( { origin: 'core' }, 'foo', true, 0 ); }); }); }); }); });
predominant/builder
components/builder-web/app/package/package-sidebar/package-sidebar.component.spec.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { TestBed, ComponentFixture } from '@angular/core/testing'; import { Component, DebugElement, SimpleChange } from '@angular/core'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { List } from 'immutable'; import { MockComponent } from 'ng2-mock-component'; import { AppStore } from '../../app.store'; import * as actions from '../../actions/index'; import { Package } from '../../records/Package'; import { PackageSidebarComponent } from './package-sidebar.component'; class MockAppStore { static state; getState() { return MockAppStore.state; } dispatch() { } } describe('PackageSidebarComponent', () => { let fixture: ComponentFixture<PackageSidebarComponent>; let component: PackageSidebarComponent; let element: DebugElement; let store: MockAppStore; beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ PackageSidebarComponent, MockComponent({ selector: 'hab-copyable', inputs: ['style', 'text'] }), MockComponent({ selector: 'hab-platform-icon', inputs: ['platform'] }), MockComponent({ selector: 'hab-icon', inputs: ['symbol'] }), MockComponent({ selector: 'hab-visibility-icon', inputs: ['visibility', 'prefix'] }) ], providers: [ { provide: AppStore, useClass: MockAppStore } ] }); fixture = TestBed.createComponent(PackageSidebarComponent); component = fixture.componentInstance; element = fixture.debugElement; store = TestBed.get(AppStore); }); beforeEach(() => { MockAppStore.state = { packages: { latestInChannel: { stable: { ident: { origin: 'core', name: 'nginx', version: '1.11.10' } } }, }, projects: { current: { visibility: 'private', vcs_data: 'https://github.com/cnunciato/testapp.git', auto_rebuild: false } }, session: { token: undefined }, oauth: { token: undefined }, origins: { mine: List() } }; }); describe('given an origin and name', () => { beforeEach(() => { spyOn(store, 'dispatch'); spyOn(actions, 'fetchLatestInChannel'); component.ngOnChanges({ origin: new SimpleChange(undefined, 'core', true), name: new SimpleChange(undefined, 'nginx', true) }); }); it('fetches the latest package', () => { expect(store.dispatch).toHaveBeenCalled(); expect(actions.fetchLatestInChannel).toHaveBeenCalledWith('core', 'nginx', 'stable'); }); it('hides the build button', () => { expect(element.query(By.css('.package-sidebar-component button.build'))).toBeNull(); }); describe('when buildable', () => { beforeEach(() => { component.buildable = true; }); it('shows the build button', () => { fixture.detectChanges(); expect(element.query(By.css('.package-sidebar-component button.build'))).not.toBeNull(); }); describe('and building', () => { beforeEach(() => { component.building = true; }); it('disables the build button', () => { fixture.detectChanges(); let el = element.query(By.css('.package-sidebar-component button.build')).nativeElement; expect(el.getAttribute('disabled')).not.toBeNull(); }); }); }); }); });
predominant/builder
components/builder-web/app/app.module.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // 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 { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { LocationStrategy, HashLocationStrategy } from '@angular/common'; import { MatButtonModule, MatIconModule, MatRadioModule, MatTabsModule, MAT_LABEL_GLOBAL_OPTIONS } from '@angular/material'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { routing } from './routes'; import { AppStore } from './app.store'; import { AppComponent } from './app.component'; import { BannerComponent } from './banner/banner.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NotificationsComponent } from './notifications/notifications.component'; import { SideNavComponent } from './side-nav/side-nav.component'; import { SignInPageComponent } from './sign-in-page/sign-in-page.component'; import { StatuspageIndicatorComponent } from './statuspage/statuspage-indicator.component'; import { UserNavComponent } from './user-nav/user-nav.component'; import { OriginModule } from './origin/origin.module'; import { PackageModule } from './package/package.module'; import { ProfileModule } from './profile/profile.module'; import { SearchModule } from './search/search.module'; import { SharedModule } from './shared/shared.module'; @NgModule({ imports: [ MatIconModule, MatRadioModule, MatTabsModule, BrowserModule, FormsModule, HttpClientModule, MatButtonModule, OriginModule, PackageModule, ProfileModule, ReactiveFormsModule, RouterModule, SearchModule, SharedModule, routing ], declarations: [ AppComponent, BannerComponent, NotificationsComponent, SideNavComponent, SignInPageComponent, StatuspageIndicatorComponent, UserNavComponent ], providers: [ { provide: LocationStrategy, useClass: HashLocationStrategy, }, { provide: MAT_LABEL_GLOBAL_OPTIONS, useValue: { float: 'always' } }, AppStore ], bootstrap: [AppComponent] }) export class AppModule {}