repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
Proza1k/Node-Express-Template
|
src/routes/types.ts
|
<filename>src/routes/types.ts
import { Express, Request, Response } from 'express'
import { Model } from '../database/types'
import { RoutePath } from './router'
export type callback = <T>(request: Request, response: Response, option?: T) => void
export enum RequestType {
get = 'get',
post = 'post',
}
export type Route<T> = {
isEnabled: boolean
path: RoutePath
type: RequestType
option?: T
callback: callback
}
export interface RouterPayload {
routes: Route<unknown>[]
app: Express
database: Model
}
|
Proza1k/Node-Express-Template
|
src/database/helper.ts
|
import Sequelize from 'sequelize'
import { DATABASE } from '../tools/environment'
import { logger } from '../tools/logger'
import { Model } from './types'
const connect = (): Model => {
logger(`Database connection statused:`)
const sequelize = new Sequelize.Sequelize(DATABASE.name, DATABASE.user, DATABASE.password, {
dialect: DATABASE.dialect as any,
host: DATABASE.host,
port: DATABASE.port,
define: {
timestamps: false,
},
})
const opts = DATABASE.options
sequelize
.sync()
.then(() => {
logger(`Database connection is success`)
})
.catch((error) => {
logger(`Database connection is error: ${error}`)
})
return {}
}
export const getDatabase = (): Model => {
const db: Model = connect()
return db
}
|
zhjrate/pinecms
|
admin/src/cool/modules/base/service/system/setting.ts
|
import { BaseService, Service } from "/@/core";
@Service("setting")
class SysSetting extends BaseService {
groupList() {
return this.request({
url: "/groups",
method: "POST"
});
}
}
export default SysSetting;
|
zhjrate/pinecms
|
admin/src/cool/modules/wechat/service/material.ts
|
<reponame>zhjrate/pinecms
import { BaseService, Service } from "/@/core";
@Service("wechat/material")
class WechatMaterial extends BaseService {
total() {
return this.request({
url: "/total",
method: "POST"
});
}
upload(data: any) {
return this.request({
url: "/upload",
method: "POST",
data,
headers: { "Content-Type": "multipart/form-data" }
});
}
clear() {
return this.request({
url: "/clear",
method: "POST"
});
}
}
export default WechatMaterial;
|
zhjrate/pinecms
|
admin/vite.config.ts
|
import path from "path";
import type { UserConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { svgBuilder } from "./src/core/utils/svg";
function resolve(dir: string) {
return path.resolve(__dirname, ".", dir);
}
// https://vitejs.dev/config/
export default (): UserConfig => {
return {
base: "/",
plugins: [vue(), vueJsx(), svgBuilder("./src/icons/svg/")],
resolve: {
alias: {
"/@": resolve("src"),
"/#": resolve("types"),
"/$": resolve("src/cool/modules")
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: "@import './src/assets/css/common.scss';"
}
}
},
server: {
port: 9000,
hmr: {
overlay: true
},
proxy: {
"/dev": {
target: "http://localhost:2019/v2",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/dev/, "")
},
"/pro": {
target: "https://show.cool-admin.com",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/pro/, "/api")
}
}
},
build: {
sourcemap: false,
polyfillDynamicImport: false // 必须为false
},
optimizeDeps: {
exclude: ["vue-demi"]
}
};
};
|
zhjrate/pinecms
|
admin/src/cool/modules/base/service/system/user.ts
|
<gh_stars>0
import { BaseService, Service, Permission } from "/@/core";
@Service("user")
class SysUser extends BaseService {}
export default SysUser;
|
zhjrate/pinecms
|
admin/src/cool/modules/base/components/index.ts
|
<filename>admin/src/cool/modules/base/components/index.ts
import Avatar from "./avatar/index.vue";
import Scrollbar from "./scrollbar/index.vue";
import RouteNav from "./route-nav/index.vue";
import Process from "./process/index.vue";
import IconSvg from "./icon-svg/index.vue";
import DeptCheck from "./dept/check.vue";
import DeptMove from "./dept/move";
import DeptTree from "./dept/tree.vue";
import MenuSlider from "./menu/slider/index";
import MenuTopbar from "./menu/topbar.vue";
import MenuFile from "./menu/file.vue";
import MenuIcons from "./menu/icons.vue";
import MenuPerms from "./menu/perms.vue";
import MenuTree from "./menu/tree.vue";
import CategoryTree from "./category/tree.vue";
import DepartmentTree from "./department/tree.vue";
import RoleSelect from "./role/select.vue";
import RolePerms from "./role/perms.vue";
import EditorQuill from "./editor-quill/index.vue";
import Codemirror from "./codemirror/index.vue";
import CmsSelect from "./select/cms_select.vue";
import InputTags from "./input-tags/input_tags.vue";
import CmsCheckbox from "./components/cms_checkbox.vue";
import CmsRadio from "./components/cms_radio.vue";
export default {
Avatar,
Scrollbar,
RouteNav,
Process,
IconSvg,
DeptCheck,
DeptMove,
DeptTree,
MenuSlider,
MenuTopbar,
MenuFile,
MenuIcons,
MenuPerms,
MenuTree,
RoleSelect,
RolePerms,
EditorQuill,
Codemirror,
CategoryTree,
DepartmentTree,
CmsSelect,
InputTags,
CmsCheckbox,
CmsRadio
};
|
Prometeus-Network/service-node_ui
|
src/models/UploadDataRequest.ts
|
<reponame>Prometeus-Network/service-node_ui
export interface UploadDataRequest {
name: string,
dataOwnerAddress: string,
dataValidatorAddress: string,
serviceNodeAddress: string,
additional: Map<string, string>,
keepUntil: Date,
mimeType: string,
extension: string,
size: number
}
|
Prometeus-Network/service-node_ui
|
src/Account/utils/index.ts
|
export const getBalanceLabel = (balance?: number, currency: string = "PROM") => {
if (balance !== undefined && balance !== null) {
return `Balance: ${balance} ${currency}`;
} else {
return `Balance: 0 ${currency}`;
}
};
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/TransactionsTable.tsx
|
<gh_stars>0
import React, {Fragment, FunctionComponent} from "react";
import {
CircularProgress,
createStyles,
makeStyles,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Tooltip,
Typography
} from "@material-ui/core";
import {TransactionResponse, TransactionType} from "../../models";
import {makePreciseNumberString, shortenString} from "../../utils";
interface TransactionsTableProps {
transactions: TransactionResponse[],
pending: boolean,
onTransactionDetailsRequest: (transaction: TransactionResponse) => void
}
const useStyles = makeStyles(() => createStyles({
centered: {
marginRight: "auto",
marginLeft: "auto",
display: "table"
}
}));
export const TransactionsTable: FunctionComponent<TransactionsTableProps> = ({transactions, pending, onTransactionDetailsRequest}) => {
const classes = useStyles();
if (transactions.length === 0 && pending) {
return <CircularProgress size={50} color="primary" className={classes.centered}/>
} else {
return (
<Fragment>
<Table>
<TableHead>
<TableRow>
<TableCell>Txn Hash</TableCell>
<TableCell>Date</TableCell>
<TableCell>Value</TableCell>
<TableCell>Data Owner</TableCell>
<TableCell>Data Validator</TableCell>
<TableCell>Data Mart</TableCell>
<TableCell>Type</TableCell>
</TableRow>
</TableHead>
<TableBody>
{transactions.map(transaction => (
<TableRow key={transaction.hash}>
<TableCell>
<Tooltip title="View details">
<Typography variant="body1"
style={{
cursor: 'pointer',
}}
onClick={() => onTransactionDetailsRequest(transaction)}
>
<u>{shortenString(transaction.hash, 16)}</u>
</Typography>
</Tooltip>
</TableCell>
<TableCell>{transaction.created_at}</TableCell>
<TableCell>{makePreciseNumberString(transaction.value)}</TableCell>
<TableCell>{shortenString(transaction.dataOwner, 16)}</TableCell>
<TableCell>{shortenString(transaction.dataValidator, 16)}</TableCell>
<TableCell>
{transaction.type === TransactionType.DATA_PURCHASE
? shortenString(transaction.dataMart, 16)
: "N/A"
}
</TableCell>
<TableCell>{transaction.type === TransactionType.DATA_PURCHASE ? "Data sell" : "Data upload"}</TableCell>
<TableCell>
{transaction.status
? <Typography style={{color: 'green'}}>Success</Typography>
: <Typography style={{color: 'red'}}>Error</Typography>
}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{pending && <CircularProgress size={50} color="primary" className={classes.centered}/>}
</Fragment>
)
}
};
|
Prometeus-Network/service-node_ui
|
src/utils/index.ts
|
export * from "./file-utils";
export * from "./string-utils";
export * from "./types";
export * from "./validation-utils";
export * from "./sleep";
|
Prometeus-Network/service-node_ui
|
src/utils/validation-utils.ts
|
<reponame>Prometeus-Network/service-node_ui
import {isStringEmpty} from "./string-utils";
const ETHEREUM_ADDRESS_REGEXP = new RegExp("^0x[a-fA-F0-9]{40}$");
export const validateEthereumAddress = (address: string | undefined, acceptEmpty: boolean = false): string | undefined => {
if (isStringEmpty(address) && !acceptEmpty) {
return "Address must be specified";
}
if (!ETHEREUM_ADDRESS_REGEXP.test(address!)) {
return "Invalid ethereum address";
}
};
|
Prometeus-Network/service-node_ui
|
src/Navigation/components/NavigationMenu.tsx
|
<reponame>Prometeus-Network/service-node_ui
import React, {FunctionComponent} from "react";
import {inject} from "mobx-react";
import {createStyles, List, ListItemIcon, ListItemText, makeStyles, MenuItem} from "@material-ui/core";
import HomeIcon from "@material-ui/icons/Home";
import AccountBalanceWalletIcon from "@material-ui/icons/AccountBalanceWallet";
import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import MonetizationOnIcon from '@material-ui/icons/MonetizationOn';
import {Routes} from "../../router";
import {IAppState} from "../../store";
const {Link} = require("mobx-router");
interface NavigationMenuMobxProps {
store?: any
}
interface NavigationMenuOwnProps {
onItemClick?: () => void
}
type NavigationMenuProps = NavigationMenuMobxProps & NavigationMenuOwnProps;
const useStyles = makeStyles(() => createStyles({
undecoratedLink: {
textDecoration: 'none',
color: 'inherit'
}
}));
const _NavigationMenu: FunctionComponent<NavigationMenuProps> = ({
store,
onItemClick
}) => {
const classes = useStyles();
return (
<List>
<Link store={store}
view={Routes.home}
className={classes.undecoratedLink}
>
<MenuItem onClick={() => onItemClick && onItemClick()}>
<ListItemIcon>
<HomeIcon/>
</ListItemIcon>
<ListItemText>
Home
</ListItemText>
</MenuItem>
</Link>
<Link store={store}
view={Routes.dataUploads}
className={classes.undecoratedLink}
>
<MenuItem onClick={() => onItemClick && onItemClick()}>
<ListItemIcon>
<CloudUploadIcon/>
</ListItemIcon>
<ListItemText>
Data Uploads
</ListItemText>
</MenuItem>
</Link>
<Link store={store}
view={Routes.dataPurchases}
className={classes.undecoratedLink}
>
<MenuItem onClick={() => onItemClick && onItemClick()}>
<ListItemIcon>
<MonetizationOnIcon/>
</ListItemIcon>
<ListItemText>
Data Purchases
</ListItemText>
</MenuItem>
</Link>
<Link store={store}
view={Routes.wallets}
className={classes.undecoratedLink}
>
<MenuItem onClick={() => onItemClick && onItemClick()}>
<ListItemIcon>
<AccountBalanceWalletIcon/>
</ListItemIcon>
<ListItemText>
Wallets
</ListItemText>
</MenuItem>
</Link>
</List>
)
};
const mapMobxToProps = (state: IAppState): NavigationMenuMobxProps => ({
store: state.store
});
export const NavigationMenu = inject(mapMobxToProps)(_NavigationMenu) as FunctionComponent<NavigationMenuOwnProps>;
|
Prometeus-Network/service-node_ui
|
src/utils/types.ts
|
export type FormErrors<FormType> = {
[Key in keyof FormType]: string | undefined
}
export type Normalized<Type> = {
[key: string]: Type
}
export const normalize = <Type>(objects: Type[], property: keyof Type): Normalized<Type> => {
const result: Normalized<Type> = {};
objects.forEach((object: Type) => result[object[property] as unknown as string] = object);
return result;
};
|
Prometeus-Network/service-node_ui
|
src/pages/index.ts
|
export * from "./HomePage";
export * from "./NotFoundPage";
export * from "./ServiceNodeTransactionsHistoryPage";
export * from "./WalletsPage";
export * from "./DataUploadsPage";
export * from "./DataPurchasesPage";
|
Prometeus-Network/service-node_ui
|
src/Account/stores/AccountsStore.ts
|
import {action, computed, observable} from "mobx";
import {AccountResponse, AccountType} from "../../models";
import {AccountsService, ApiError, createErrorFromResponse} from "../../api";
import {AxiosError} from "axios";
export class AccountsStore {
@observable
accounts: AccountResponse[] = [];
@observable
fetchingAccounts: boolean = false;
@observable
accountsFetchingError?: ApiError = undefined;
@action
addAccount = (account: AccountResponse): void => {
this.accounts.push(account);
};
@action
fetchAccounts = (): void => {
AccountsService.fetchRegisteredAccounts()
.then(({data}) => this.accounts = data)
.catch((error: AxiosError) => this.accountsFetchingError = createErrorFromResponse(error));
};
@action
setDefaultAccount = (address: string): void => {
this.accounts = this.accounts.map(account => {
account.default = account.address === address;
return account;
});
}
}
|
Prometeus-Network/service-node_ui
|
src/Settings/stores/SettingsStore.ts
|
import {action, computed} from "mobx";
import {AccountsService, ApiError} from "../../api";
import {AccountResponse} from "../../models";
import {AccountsStore} from "../../Account";
export class SettingsStore {
private readonly accountsStore: AccountsStore;
@computed
get selectedServiceNodeAccount(): string | undefined{
if (this.accountsStore.accounts.length !== 0) {
return this.accountsStore.accounts
.filter(account => account.default)
.reduce(account => account)
.address
} else {
return undefined;
}
}
@computed
get serviceNodeAccounts(): AccountResponse[] {
return this.accountsStore.accounts;
}
@computed
get fetchingAccounts(): boolean {
return this.accountsStore.fetchingAccounts;
}
@computed
get fetchingAccountsError(): ApiError | undefined {
return this.accountsStore.accountsFetchingError;
}
constructor(accountsStore: AccountsStore) {
this.accountsStore = accountsStore;
}
@action
selectServiceNodeAccount = (accountAddress: string): void => {
AccountsService.setAccountAsDefault(accountAddress)
.then(() => {
this.accountsStore.setDefaultAccount(accountAddress);
})
};
}
|
Prometeus-Network/service-node_ui
|
src/Transaction/stores/DataUploadsTransactionsStore.ts
|
<filename>src/Transaction/stores/DataUploadsTransactionsStore.ts
import {action, computed, observable, reaction} from "mobx";
import {AxiosError} from "axios";
import {SettingsStore} from "../../Settings";
import {TransactionResponse, TransactionType} from "../../models";
import {ApiError, createErrorFromResponse, TransactionsService} from "../../api";
import {normalize, Normalized} from "../../utils";
export class DataUploadsTransactionsStore {
private readonly settingsStore: SettingsStore;
private static readonly PAGE_SIZE: number = 50;
@observable
transactions: Normalized<TransactionResponse> = {};
@observable
error?: ApiError = undefined;
@observable
pending: boolean = false;
@observable
currentPage: number = 0;
@observable
resetOnSelectedServiceNodeAccountChange: boolean = false;
@computed
get serviceNodeAccount(): string | undefined {
return this.settingsStore.selectedServiceNodeAccount;
}
constructor(settingsStore: SettingsStore) {
this.settingsStore = settingsStore;
reaction(
() => this.serviceNodeAccount,
() => {
if (this.resetOnSelectedServiceNodeAccountChange) {
this.reset();
this.fetchDataUploadsHistory();
}
}
)
}
@action
setResetOnSelectedServiceNodeAccountChange = (reset: boolean): void => {
this.resetOnSelectedServiceNodeAccountChange = reset;
};
@action
fetchDataUploadsHistory = (): void => {
if (this.serviceNodeAccount) {
this.pending = true;
this.error = undefined;
TransactionsService.getTransactionsOfAddressByType(
this.serviceNodeAccount,
TransactionType.DATA_UPLOAD,
{page: this.currentPage, size: DataUploadsTransactionsStore.PAGE_SIZE}
)
.then(({data}) => {
if (data.length !== 0) {
this.transactions = {
...this.transactions,
...normalize(data, "hash")
};
if (data.length === DataUploadsTransactionsStore.PAGE_SIZE) {
this.currentPage = this.currentPage + 1;
}
}
})
.catch((error: AxiosError) => this.error = createErrorFromResponse(error))
.finally(() => this.pending = false);
}
};
@action
reset = (): void => {
this.currentPage = 0;
this.pending = false;
this.error = undefined;
this.transactions = {};
}
}
|
Prometeus-Network/service-node_ui
|
src/AppBar/components/AppBar.tsx
|
import React, {Fragment, FunctionComponent, ReactElement} from "react";
import Headroom from "react-headroom";
import {inject} from "mobx-react";
import {
AppBar as MaterialUiAppBar,
createStyles,
Hidden,
ListItemIcon,
ListItemText,
makeStyles,
MenuItem,
Toolbar,
Typography
} from "@material-ui/core";
import {NavigationalDrawer} from "./NavigationalDrawer";
import {OpenDrawerButton} from "./OpenDrawerButton";
import {Routes} from "../../router";
import {IAppState} from "../../store";
import {PrometeusLogoIcon} from "../../icons";
const {Link} = require('mobx-router');
interface AppBarOwnProps {
title?: string,
sideBarItem?: ReactElement
}
interface AppBarMobxProps {
store: any
}
type AppBarProps = AppBarOwnProps & AppBarMobxProps;
const useStyles = makeStyles(() => createStyles({
grow: {
flexGrow: 1,
},
undecoratedLink: {
textDecoration: "none",
color: "inherit"
}
}));
const _AppBar: FunctionComponent<AppBarProps> = ({title, store, sideBarItem}) => {
const classes = useStyles();
const linkToHome = (
<Link store={store}
view={Routes.home}
className={classes.undecoratedLink}
>
<MenuItem>
<ListItemIcon>
<PrometeusLogoIcon/>
</ListItemIcon>
<ListItemText>
<Hidden xsDown>
Service Node Client
</Hidden>
</ListItemText>
</MenuItem>
</Link>
);
return (
<Fragment>
<Headroom style={{
position: 'fixed',
zIndex: 1300
}}>
<MaterialUiAppBar position="static"
className={classes.grow}
>
<Toolbar>
<Hidden lgUp>
<OpenDrawerButton/>
</Hidden>
<div className={classes.grow}
style={{display: 'flex'}}
>
<Typography variant="h6">
{title
?
<span>{linkToHome} <Hidden smDown> | {title}</Hidden></span>
: linkToHome
}
</Typography>
</div>
{sideBarItem && sideBarItem}
</Toolbar>
</MaterialUiAppBar>
</Headroom>
<NavigationalDrawer/>
</Fragment>
);
};
const mapMobxToProps = (appState: IAppState): AppBarMobxProps => ({
store: appState.store
});
export const AppBar = inject(mapMobxToProps)(_AppBar as FunctionComponent<AppBarOwnProps>);
|
Prometeus-Network/service-node_ui
|
src/Footer/components/Footer.tsx
|
<gh_stars>0
import * as React from "react";
import {Typography, createStyles, makeStyles} from "@material-ui/core";
const {version} = require("../../../package.json");
const useStyles = makeStyles(() => createStyles({
footer: {
position: 'fixed',
left: 0,
bottom: 0,
width: '100%',
textAlign: 'center'
}
}));
export const Footer: React.FC<{}> = () => {
const classes = useStyles();
return (
<div className={classes.footer}>
<Typography variant="body1"
color="primary"
>
Service node client v. {version}
</Typography>
</div>
);
};
|
Prometeus-Network/service-node_ui
|
src/Account/components/SelectedServiceNodeBalance.tsx
|
<reponame>Prometeus-Network/service-node_ui<filename>src/Account/components/SelectedServiceNodeBalance.tsx
import React, {FunctionComponent} from "react";
import {inject, observer} from "mobx-react";
import {TypographyProps} from "@material-ui/core/Typography";
import {AccountBalance} from "./AccountBalance";
import {IAppState} from "../../store";
interface SelectedServiceNodeBalanceMobxProps {
balance: number,
selectedServiceNode?: string
}
type SelectedServiceNodeBalanceProps = SelectedServiceNodeBalanceMobxProps & TypographyProps;
const _SelectedServiceNodeBalance: FunctionComponent<SelectedServiceNodeBalanceProps> = ({
balance,
selectedServiceNode,
...rest
}) => {
return selectedServiceNode
? <AccountBalance balance={balance} address={selectedServiceNode} {...rest}/>
: null;
};
console.log("hello")
const mapMobxToProps = (state: IAppState): SelectedServiceNodeBalanceMobxProps => ({
balance: state.settings.selectedServiceNodeAccount
? state.balances.accountsBalances[state.settings.selectedServiceNodeAccount] || 0
: 0,
selectedServiceNode: state.settings.selectedServiceNodeAccount
});
export const SelectedServiceNodeBalance = inject(mapMobxToProps)(observer(_SelectedServiceNodeBalance) as FunctionComponent<TypographyProps>);
|
Prometeus-Network/service-node_ui
|
src/api/api-client.ts
|
import Axios from "axios";
export const axiosInstance = Axios.create({
baseURL: process.env.REACT_APP_SERVICE_NODE_API_BASE_URL as string
});
|
Prometeus-Network/service-node_ui
|
src/models/GenerateRsaKeyPairResponse.ts
|
export interface GenerateRsaKeyPairResponse {
public_key: string,
private_key: string
}
|
Prometeus-Network/service-node_ui
|
src/AppBar/components/NavigationalDrawer.tsx
|
<reponame>Prometeus-Network/service-node_ui<gh_stars>1-10
import * as React from "react";
import {inject, observer} from "mobx-react";
import {SwipeableDrawer} from "@material-ui/core";
import {NavigationMenu} from "../../Navigation";
import {IAppState} from "../../store";
interface NavigationalDrawerProps {
drawerOpen: boolean,
setDrawerOpen: (open: boolean) => void
}
const _NavigationalDrawer: React.FC<NavigationalDrawerProps> = ({
drawerOpen,
setDrawerOpen
}) => (
<SwipeableDrawer onClose={() => setDrawerOpen(false)}
onOpen={() => setDrawerOpen(true)}
open={drawerOpen}
>
<NavigationMenu onItemClick={() => setDrawerOpen(false)}/>
</SwipeableDrawer>
);
const mapMobxToProps = (state: IAppState): NavigationalDrawerProps => ({
setDrawerOpen: state.drawer.setOpen,
drawerOpen: state.drawer.open
});
export const NavigationalDrawer = inject(mapMobxToProps)(observer(_NavigationalDrawer)) as React.FC<any>;
|
Prometeus-Network/service-node_ui
|
src/Settings/components/ServiceNodeAccountSettings.tsx
|
import * as React from "react";
import {inject, observer} from "mobx-react";
import {Grid} from "@material-ui/core";
import {ServiceNodeAccountsList} from "../../Account";
import {AccountBalanceMapping, AccountResponse} from "../../models";
import {IAppState} from "../../store";
interface ServiceNodeAccountSettingsMobxProps {
accounts: AccountResponse[],
balances: AccountBalanceMapping,
selectedAccount?: string,
selectAccount: (address: string) => void
}
const _ServiceNodeAccountSettings: React.FC<ServiceNodeAccountSettingsMobxProps> = ({
selectedAccount,
accounts,
balances,
selectAccount
}) => (
<Grid container spacing={2}>
<Grid item xs={12}>
<ServiceNodeAccountsList accounts={accounts}
balances={balances}
defaultAccount={selectedAccount}
onDefaultAccountSelected={selectAccount}
/>
</Grid>
</Grid>
);
const mapMobxToProps = (state: IAppState): ServiceNodeAccountSettingsMobxProps => ({
accounts: state.accounts.accounts,
balances: state.balances.accountsBalances,
selectedAccount: state.settings.selectedServiceNodeAccount,
selectAccount: state.settings.selectServiceNodeAccount
});
export const ServiceNodeAccountSettings = inject(mapMobxToProps)(observer(_ServiceNodeAccountSettings)) as React.FC<any>;
|
Prometeus-Network/service-node_ui
|
src/Settings/components/index.ts
|
export * from "./ServiceNodeAccountSettings";
|
Prometeus-Network/service-node_ui
|
src/themes/red.ts
|
<filename>src/themes/red.ts
import {createMuiTheme} from "@material-ui/core";
export const red = createMuiTheme({
"palette": {
"common": {
"black": "#000",
"white": "#fff"
},
"background": {
"paper": "#fff",
"default": "#fafafa"
},
"primary": {
"light": "rgb(218,124,105)",
"main": "rgb(207,104,89)",
"dark": "rgb(138,58,58)",
"contrastText": "#fff"
},
"secondary": {
"light": "rgba(94, 146, 243, 1)",
"main": "rgba(21, 101, 192, 1)",
"dark": "rgba(0, 60, 143, 1)",
"contrastText": "#fff"
},
"error": {
"light": "#e57373",
"main": "#f44336",
"dark": "#d32f2f",
"contrastText": "#fff"
},
"text": {
"primary": "rgba(0, 0, 0, 0.87)",
"secondary": "rgba(0, 0, 0, 0.54)",
"disabled": "rgba(0, 0, 0, 0.38)",
"hint": "rgba(0, 0, 0, 0.38)"
}
}
});
|
Prometeus-Network/service-node_ui
|
src/api/services/index.ts
|
<filename>src/api/services/index.ts
export * from "./AccountsService";
export * from "./TransactionsService";
|
Prometeus-Network/service-node_ui
|
src/Transaction/index.ts
|
<filename>src/Transaction/index.ts
export * from "./components";
export * from "./stores";
|
Prometeus-Network/service-node_ui
|
src/utils/file-utils.ts
|
<filename>src/utils/file-utils.ts
const getExtension = require("file-extension");
const FILE_EXTENSIONS_SUBSTITUTES = new Map<string, string>();
FILE_EXTENSIONS_SUBSTITUTES.set(".document", "docx");
FILE_EXTENSIONS_SUBSTITUTES.set("-excel", "xls");
FILE_EXTENSIONS_SUBSTITUTES.set("plain", "txt");
export const getFileExtension = (base64Data: string): string => {
const matches = base64Data.match(/[^:/]\w+(?=;|,)/);
if (matches !== null && matches.length !== 0) {
let fileExtension = matches[0];
if (FILE_EXTENSIONS_SUBSTITUTES.has(fileExtension)) {
fileExtension = FILE_EXTENSIONS_SUBSTITUTES.get(fileExtension)!;
}
return fileExtension;
}
return "unknown";
};
export const getFileMimeType = (base64Data: string): string => {
const matches = base64Data.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/);
if (matches !== null && matches.length !== 0) {
return matches[0];
}
return "unknown";
};
export const getFileSizeInBytes = (base64Data: string): number => {
const base64Length = base64Data.length - (base64Data.indexOf(',') + 1);
const padding = (base64Data.charAt(base64Data.length - 2) === '=') ? 2 : ((base64Data.charAt(base64Data.length - 1) === '=') ? 1 : 0);
return base64Length * 0.75 - padding;
};
export const convertToBase64 = (blob: Blob): Promise<string> => new Promise<string>((resolve, reject) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(blob);
fileReader.onload = () => resolve(fileReader.result as string);
fileReader.onerror = error => reject(error);
});
export const removeBase64Header = (base64String: string): string => base64String.substring(base64String.indexOf(";base64,") + ";base64,".length);
export const getFileExtensionFromName = (fileName: string): string => getExtension(fileName) as string;
|
Prometeus-Network/service-node_ui
|
src/Account/stores/AccountsBalanceStore.ts
|
<reponame>Prometeus-Network/service-node_ui<filename>src/Account/stores/AccountsBalanceStore.ts
import {action, observable, reaction} from "mobx";
import {AccountsStore} from "./AccountsStore";
import {AccountBalanceMapping} from "../../models";
import {AccountsService} from "../../api";
export class AccountsBalanceStore {
@observable
accountsBalances: AccountBalanceMapping = {};
private readonly accountsStore: AccountsStore;
constructor(accountsStore: AccountsStore) {
this.accountsStore = accountsStore;
reaction(
() => this.accountsStore.accounts,
() => this.fetchBalancesOfAllAccounts()
);
setInterval(this.fetchBalancesOfAllAccounts, 10000);
}
@action
fetchBalancesOfAllAccounts = (): void => {
AccountsService.getBalancesOfAllAccounts()
.then(({data}) => this.accountsBalances = {...this.accountsBalances, ...data})
.catch(ignored => {});
};
}
|
Prometeus-Network/service-node_ui
|
src/models/DataOwnersResponse.ts
|
<filename>src/models/DataOwnersResponse.ts
export interface DataOwnersResponse {
dataOwners: string[]
}
|
Prometeus-Network/service-node_ui
|
src/models/RegisterAccountResponse.ts
|
<filename>src/models/RegisterAccountResponse.ts
export interface RegisterAccountResponse {
success: boolean
}
|
Prometeus-Network/service-node_ui
|
src/store/store.ts
|
import Web3 from "web3";
import {IAppState} from "./IAppState";
import {AccountRegistrationStore, AccountsBalanceStore, AccountsStore,} from "../Account";
import {DrawerStore} from "../AppBar";
import {SettingsStore} from "../Settings";
import {ServiceNodeTransactionsStore, DataUploadsTransactionsStore, DataPurchasesTransactionsStore} from "../Transaction";
import {AccountType} from "../models";
const accounts = new AccountsStore();
const balances = new AccountsBalanceStore(accounts);
const settings = new SettingsStore(accounts);
const registration = new AccountRegistrationStore(accounts, new Web3());
const serviceNodeTransactions = new ServiceNodeTransactionsStore(settings);
const dataUploads = new DataUploadsTransactionsStore(settings);
const dataPurchases = new DataPurchasesTransactionsStore(settings);
export const store: IAppState = {
settings,
registration,
drawer: new DrawerStore(),
accounts,
balances,
serviceNodeTransactions,
dataPurchases,
dataUploads
};
|
Prometeus-Network/service-node_ui
|
src/Account/stores/AccountRegistrationStore.ts
|
import {action, observable, reaction} from "mobx";
import {AxiosError} from "axios";
import Web3 from "web3";
import {AccountsStore} from "./AccountsStore";
import {validateAccountType, validatePrivateKey} from "../validation";
import {FormErrors, validateEthereumAddress} from "../../utils";
import {AccountsService, ApiError, createErrorFromResponse} from "../../api";
import {AccountType, RegisterAccountRequest, RegisterAccountResponse} from "../../models";
export class AccountRegistrationStore {
@observable
registrationForm: Partial<RegisterAccountRequest> = {
address: undefined,
type: AccountType.SERVICE_NODE
};
@observable
formErrors: FormErrors<RegisterAccountRequest> = {
type: undefined,
address: undefined,
privateKey: undefined
};
@observable
pending: boolean = false;
@observable
submissionError?: ApiError = undefined;
@observable
response?: RegisterAccountResponse = undefined;
@observable
showSnackbar: boolean = false;
@observable
registrationDialogOpen: boolean = false;
private readonly accountsStore: AccountsStore;
private readonly web3: Web3;
constructor(accountsStore: AccountsStore, web3: Web3) {
this.accountsStore = accountsStore;
this.web3 = web3;
reaction(
() => this.registrationForm.type,
type => this.formErrors.type = validateAccountType(type)
);
reaction(
() => this.registrationForm.address,
address => this.formErrors.address = validateEthereumAddress(address)
);
}
@action
setField = (key: keyof RegisterAccountRequest, value: string | AccountType): void => {
this.registrationForm = {
...this.registrationForm,
[key]: value
}
};
@action
registerAccount = (): void => {
if (this.isFormValid()) {
this.pending = true;
this.submissionError = undefined;
AccountsService.registerAccount({
address: this.registrationForm.address!,
type: this.registrationForm.type!,
privateKey: this.registrationForm.privateKey!
})
.then(({data}) => {
this.accountsStore.addAccount({
type: this.registrationForm.type!,
address: this.registrationForm.address!,
default: false
});
this.response = data;
this.setShowSnackbar(true);
})
.catch((error: AxiosError) => this.submissionError = createErrorFromResponse(error))
.then(() => this.pending = false)
}
};
@action
isFormValid = (): boolean => {
this.formErrors.address = validateEthereumAddress(this.registrationForm.address);
if (!this.formErrors.address) {
this.formErrors = {
address: this.formErrors.address,
privateKey: validatePrivateKey(
this.registrationForm.address!,
this.web3,
this.registrationForm.privateKey
),
type: validateAccountType(this.registrationForm.type)
}
}
return !(Boolean(this.formErrors.address || this.formErrors.type || this.formErrors.privateKey))
};
@action
setShowSnackbar = (showSnackbar: boolean): void => {
this.showSnackbar = showSnackbar;
};
@action
setRegistrationDialogOpen = (registrationDialogOpen: boolean): void => {
this.registrationDialogOpen = registrationDialogOpen;
};
@action
reset = (): void => {
this.registrationForm = {
address: undefined,
type: AccountType.DATA_VALIDATOR
};
this.formErrors = {
address: undefined,
type: undefined,
privateKey: undefined
};
this.submissionError = undefined;
this.showSnackbar = false;
}
}
|
Prometeus-Network/service-node_ui
|
src/Account/stores/index.ts
|
export * from "./AccountsBalanceStore";
export * from "./AccountsStore";
export * from "./AccountRegistrationStore";
|
Prometeus-Network/service-node_ui
|
src/models/PurchaseFileResponse.ts
|
export interface PurchaseFileResponse {
success: boolean
}
|
Prometeus-Network/service-node_ui
|
src/api/endpoints.ts
|
<filename>src/api/endpoints.ts<gh_stars>0
export const ACCOUNTS = "api/v1/accounts";
export const BALANCES = "balances";
export const TRANSACTIONS = "api/v1/transactions";
export const DEFAULT = "default";
|
Prometeus-Network/service-node_ui
|
src/AppBar/stores/DrawerStore.ts
|
import {observable, action} from "mobx";
export class DrawerStore {
@observable
open: boolean = false;
@action
setOpen = (open: boolean): void => {
this.open = open;
}
}
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/index.ts
|
<filename>src/Transaction/components/index.ts
export * from "./ServiceNodeTransactionsCard";
export * from "./TransactionsTable";
export * from "./DataPurchaseInfoDialog";
export * from "./DataPurchasesTable";
export * from "./DataPurchasesTransactionsCard";
export * from "./DataUploadsTable";
export * from "./DataUploadInfoDialog";
export * from "./DataUploadsTransactionsCard";
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/DataPurchasesTransactionsCard.tsx
|
<reponame>Prometeus-Network/service-node_ui<filename>src/Transaction/components/DataPurchasesTransactionsCard.tsx
import React, {Fragment, FunctionComponent, ReactNode, useState} from "react";
import {inject, observer} from "mobx-react";
import {Button, Card, CardContent, CardHeader, Grid, Typography, createStyles, makeStyles} from "@material-ui/core";
import {DataPurchasesTable} from "./DataPurchasesTable";
import {DataPurchaseInfoDialog} from "./DataPurchaseInfoDialog";
import {ServiceNodeAccountSelect} from "../../Account";
import {IAppState} from "../../store";
import {TransactionResponse} from "../../models";
import {ApiError} from "../../api";
import {Normalized} from "../../utils";
interface DataPurchasesTransactionsCardMobxProps {
transactions: Normalized<TransactionResponse>,
serviceNode?: string,
pending: boolean,
error?: ApiError,
serviceNodes: string[],
fetchTransactions: () => void,
selectServiceNode: (serviceNode: string) => void
}
const useStyles = makeStyles(() => createStyles({
dataPurchasesCard: {
overflowX: 'auto'
}
}));
const _DataPurchasesTransactionsCard: FunctionComponent<DataPurchasesTransactionsCardMobxProps> = ({
transactions,
pending,
serviceNode,
error,
serviceNodes,
fetchTransactions,
selectServiceNode
}) => {
const [transactionInDialog, setTransactionInDialog] = useState<TransactionResponse | undefined>(undefined);
const classes = useStyles();
let content: ReactNode;
if (Object.keys(transactions).length === 0 && !pending) {
if (error) {
content = <Typography variant="body1">Error occurred when tried to fetch transactions</Typography>
} else {
content = <Typography variant="body1">No transactions have been found</Typography>
}
} else {
content = (
<DataPurchasesTable transactions={Object.keys(transactions).map(hash => transactions[hash])}
pending={pending}
onTransactionDetailsRequest={setTransactionInDialog}
/>
)
}
return (
<Fragment>
<Grid container spacing={2}>
<Grid item xs={12}>
<ServiceNodeAccountSelect accounts={serviceNodes}
onSelect={selectServiceNode}
selectedAccount={serviceNode}
/>
</Grid>
<Grid item xs={12}>
<Card className={classes.dataPurchasesCard}>
<CardHeader title={`Data purchases through service node ${serviceNode}`}/>
<CardContent>
{content}
</CardContent>
</Card>
</Grid>
<Grid item xs={12}>
<Button variant="outlined"
color="primary"
onClick={fetchTransactions}
disabled={pending}
>
Load more
</Button>
</Grid>
</Grid>
<DataPurchaseInfoDialog transaction={transactionInDialog}
onClose={() => setTransactionInDialog(undefined)}
/>
</Fragment>
)
};
const mapMobxToProps = (state: IAppState): DataPurchasesTransactionsCardMobxProps => ({
transactions: state.dataPurchases.transactions,
serviceNodes: state.accounts.accounts.map(account => account.address),
pending: state.dataPurchases.pending,
serviceNode: state.dataPurchases.serviceNodeAccount,
selectServiceNode: state.settings.selectServiceNodeAccount,
error: state.dataPurchases.error,
fetchTransactions: state.dataPurchases.fetchPurchasesHistory
});
export const DataPurchasesTransactionsCard = inject(mapMobxToProps)(observer(_DataPurchasesTransactionsCard) as FunctionComponent<{}>);
|
Prometeus-Network/service-node_ui
|
src/AppBar/stores/index.ts
|
export * from "./DrawerStore";
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/DataUploadInfoDialog.tsx
|
import React, {FunctionComponent} from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Table,
TableCell,
TableRow,
withMobileDialog
} from "@material-ui/core";
import {WithMobileDialog} from "@material-ui/core/withMobileDialog";
import {TransactionResponse} from "../../models";
import {makePreciseNumberString} from "../../utils";
interface DataUploadInfoDialogOwnProps {
transaction?: TransactionResponse,
onClose: () => void
}
type DataUploadInfoDialogProps = DataUploadInfoDialogOwnProps & WithMobileDialog;
const _DataUploadInfoDialog: FunctionComponent<DataUploadInfoDialogProps> = ({
transaction,
onClose,
fullScreen
}) => {
if (transaction) {
return (
<Dialog open={Boolean(transaction)}
onClose={onClose}
fullScreen={fullScreen}
fullWidth
maxWidth="md"
>
<DialogTitle>Data Upload Info</DialogTitle>
<DialogContent>
<Table>
<TableRow>
<TableCell>Txn Hash</TableCell>
<TableCell>{transaction?.hash}</TableCell>
</TableRow>
<TableRow>
<TableCell>Date</TableCell>
<TableCell>{transaction?.created_at}</TableCell>
</TableRow>
<TableRow>
<TableCell>Storage Price</TableCell>
<TableCell>{makePreciseNumberString(transaction?.value)}</TableCell>
</TableRow>
<TableRow>
<TableCell>Data Owner</TableCell>
<TableCell>{transaction?.dataOwner}</TableCell>
</TableRow>
<TableRow>
<TableCell>Data Validator</TableCell>
<TableCell>{transaction?.dataValidator}</TableCell>
</TableRow>
</Table>
</DialogContent>
<DialogActions>
<Button variant="outlined"
color="secondary"
onClick={onClose}
>
Close
</Button>
</DialogActions>
</Dialog>
)
} else {
return null;
}
}
export const DataUploadInfoDialog = withMobileDialog()(_DataUploadInfoDialog) as FunctionComponent<DataUploadInfoDialogOwnProps>;
|
Prometeus-Network/service-node_ui
|
src/utils/sleep.ts
|
export const sleep = (millisecondsToSleep: number) => new Promise(resolve => setTimeout(() => resolve(), millisecondsToSleep));
|
Prometeus-Network/service-node_ui
|
src/App.tsx
|
<filename>src/App.tsx
import * as React from "react";
import {MuiThemeProvider} from "@material-ui/core";
import {SnackbarProvider} from "notistack";
import enLocale from "date-fns/locale/en-GB";
import DateFnsUtils from '@date-io/date-fns';
import {MuiPickersUtilsProvider} from '@material-ui/pickers';
import {red} from "./themes";
const {MobxRouter} = require("mobx-router");
export const App: React.FC = () => (
<div id="app">
<SnackbarProvider maxSnack={3}>
<MuiThemeProvider theme={red}>
<MuiPickersUtilsProvider utils={DateFnsUtils}
locale={enLocale}
>
<MobxRouter/>
</MuiPickersUtilsProvider>
</MuiThemeProvider>
</SnackbarProvider>
</div>
);
|
Prometeus-Network/service-node_ui
|
src/models/EncryptorServiceResponse.ts
|
<filename>src/models/EncryptorServiceResponse.ts
export interface EncryptorServiceResponse<ResultType> {
result: ResultType,
error?: any
}
|
Prometeus-Network/service-node_ui
|
src/models/FileInfoResponse.ts
|
export interface FileInfoResponse {
id: string,
dataValidator: string,
price: number,
extension: string,
mimeType: string,
size: number,
name: string
}
|
Prometeus-Network/service-node_ui
|
src/icons/CopyToClipboardIcon.tsx
|
import React from "react";
import SvgIcon, {SvgIconProps} from "@material-ui/core/SvgIcon";
export const CopyToClipboardIcon: React.FC<SvgIconProps> = (props: SvgIconProps) => (
<SvgIcon {...props}>
<path d="M17,9H7V7H17M17,13H7V11H17M14,17H7V15H14M12,3A1,1 0 0,1 13,4A1,1 0 0,1 12,5A1,1 0 0,1 11,4A1,1 0 0,1 12,3M19,3H14.82C14.4,1.84 13.3,1 12,1C10.7,1 9.6,1.84 9.18,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5A2,2 0 0,0 19,3Z" />
</SvgIcon>
);
|
Prometeus-Network/service-node_ui
|
src/router/Routes.tsx
|
<filename>src/router/Routes.tsx
import * as React from "react";
import {
HomePage,
NotFoundPage,
ServiceNodeTransactionsHistoryPage,
WalletsPage,
DataPurchasesPage,
DataUploadsPage,
} from "../pages";
import {store} from "../store";
const Route = require("mobx-router").Route;
export const Routes = {
home: new Route({
path: '/',
component: <ServiceNodeTransactionsHistoryPage/>,
beforeEnter: () => {
store.serviceNodeTransactions.setResetOnSelectedServiceNodeAccountChange(true);
store.serviceNodeTransactions.fetchTransactions()
},
onExit: () => {
store.serviceNodeTransactions.setResetOnSelectedServiceNodeAccountChange(false);
store.serviceNodeTransactions.reset();
}
}),
wallets: new Route({
path: "/wallets",
component: <WalletsPage/>
}),
notFound: new Route({
path: '/404',
component: <NotFoundPage/>
}),
dataUploads: new Route({
path: '/data-uploads',
component: <DataUploadsPage/>,
beforeEnter: () => {
store.dataUploads.fetchDataUploadsHistory();
store.dataUploads.setResetOnSelectedServiceNodeAccountChange(true);
},
onExit: () => {
store.dataUploads.setResetOnSelectedServiceNodeAccountChange(false);
store.dataUploads.reset();
}
}),
dataPurchases: new Route({
path: '/data-purchases',
component: <DataPurchasesPage/>,
beforeEnter: () => {
store.dataPurchases.fetchPurchasesHistory();
store.dataPurchases.setResetOnSelectedServiceNodeAccountChange(true);
},
onExit: () => {
store.dataPurchases.setResetOnSelectedServiceNodeAccountChange(false);
store.dataPurchases.reset();
}
})
};
|
Prometeus-Network/service-node_ui
|
src/models/AccountBalanceMapping.ts
|
export interface AccountBalanceMapping {
[key: string]: number
}
|
Prometeus-Network/service-node_ui
|
src/api/ApiError.ts
|
export interface ApiError {
status: number,
message?: string
}
export const SERVICE_NODE_API_UNREACHABLE_CODE = 97498172992918265;
|
Prometeus-Network/service-node_ui
|
src/store/IAppState.ts
|
<reponame>Prometeus-Network/service-node_ui
import {
AccountsStore,
AccountsBalanceStore,
AccountRegistrationStore,
} from "../Account";
import {DrawerStore} from "../AppBar";
import {SettingsStore} from "../Settings";
import {ServiceNodeTransactionsStore, DataUploadsTransactionsStore, DataPurchasesTransactionsStore} from "../Transaction";
export interface IAppState {
store?: any, //needed for Mobx-router
registration: AccountRegistrationStore,
drawer: DrawerStore,
settings: SettingsStore,
accounts: AccountsStore,
balances: AccountsBalanceStore,
serviceNodeTransactions: ServiceNodeTransactionsStore,
dataUploads: DataUploadsTransactionsStore,
dataPurchases: DataPurchasesTransactionsStore
}
|
Prometeus-Network/service-node_ui
|
src/api/create-error-from-response.ts
|
import {AxiosError} from "axios";
import {ApiError, SERVICE_NODE_API_UNREACHABLE_CODE} from "./ApiError";
export const createErrorFromResponse = (axiosError: AxiosError): ApiError => {
if (axiosError.response) {
return {
status: axiosError.response.status
}
} else {
return {
status: SERVICE_NODE_API_UNREACHABLE_CODE
}
}
};
|
Prometeus-Network/service-node_ui
|
src/api/services/TransactionsService.ts
|
<reponame>Prometeus-Network/service-node_ui
import {AxiosPromise} from "axios";
import {axiosInstance} from "../api-client";
import {TransactionResponse, TransactionType} from "../../models";
import {TRANSACTIONS} from "../endpoints";
export class TransactionsService {
public static getTransactionsOfAddress(address: string, pagination: {page: number, size: number}): AxiosPromise<TransactionResponse[]> {
return axiosInstance.get(`/${TRANSACTIONS}/${address}?page=${pagination.page}&size=${pagination.size}`);
}
public static getTransactionsOfAddressByType(address: string,
transactionType: TransactionType,
pagination: {page: number, size: number}): AxiosPromise<TransactionResponse[]> {
return axiosInstance.get(`/${TRANSACTIONS}/${address}?page=${pagination.page}&size=${pagination.size}&type=${transactionType}`);
}
}
|
Prometeus-Network/service-node_ui
|
src/icons/PrometeusLogoIcon.tsx
|
<gh_stars>1-10
import React, {FunctionComponent} from "react";
import PrometeusLogo from "../logo.svg";
export const PrometeusLogoIcon: FunctionComponent<{}> = () => (
<img src={PrometeusLogo} style={{
width: "1.7em",
height: "1.7em"
}}/>
);
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/TransactionDialog.tsx
|
<filename>src/Transaction/components/TransactionDialog.tsx
import React, {FunctionComponent} from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Table,
TableCell,
TableRow,
withMobileDialog
} from "@material-ui/core";
import {WithMobileDialog} from "@material-ui/core/withMobileDialog";
import {TransactionResponse, TransactionType} from "../../models";
import {makePreciseNumberString} from "../../utils";
interface TransactionDialogOwnProps {
transaction?: TransactionResponse,
onClose: () => void
}
type TransactionDialogProps = TransactionDialogOwnProps & WithMobileDialog;
const _TransactionDialog: FunctionComponent<TransactionDialogProps> = ({
transaction,
onClose,
fullScreen
}) => {
if (transaction) {
return (
<Dialog open={Boolean(transaction)}
onClose={onClose}
fullScreen={fullScreen}
fullWidth
maxWidth="lg"
>
<DialogTitle>
Transaction Info
</DialogTitle>
<DialogContent>
<Table>
<TableRow>
<TableCell>Txn Hash</TableCell>
<TableCell>{transaction?.hash}</TableCell>
</TableRow>
<TableRow>
<TableCell>Date</TableCell>
<TableCell>{transaction?.created_at}</TableCell>
</TableRow>
<TableRow>
<TableCell>Txn Type</TableCell>
<TableCell>{transaction?.type === TransactionType.DATA_PURCHASE ? "Data Purchase" : "Data Upload"}</TableCell>
</TableRow>
<TableRow>
<TableCell>Value</TableCell>
<TableCell>{makePreciseNumberString(transaction?.value)}</TableCell>
</TableRow>
<TableRow>
<TableCell>Data Owner</TableCell>
<TableCell>{transaction?.dataOwner}</TableCell>
</TableRow>
<TableRow>
<TableCell>Data Validator</TableCell>
<TableCell>{transaction?.dataValidator}</TableCell>
</TableRow>
<TableRow>
<TableCell>Data Mart</TableCell>
<TableCell>
{transaction?.type === TransactionType.DATA_PURCHASE
? transaction.dataMart
: "N/A"
}
</TableCell>
</TableRow>
</Table>
</DialogContent>
<DialogActions>
<Button variant="outlined"
color="secondary"
onClick={onClose}
>
Close
</Button>
</DialogActions>
</Dialog>
)
} else {
return null;
}
};
export const TransactionDialog = withMobileDialog()(_TransactionDialog) as FunctionComponent<TransactionDialogOwnProps>;
|
Prometeus-Network/service-node_ui
|
src/Account/components/ServiceNodeAccountSelect.tsx
|
import React, {FunctionComponent, Fragment} from "react";
import {InputLabel, MenuItem, Select} from "@material-ui/core";
import uuid from "uuid/v4";
interface ServiceNodeAccountSelectProps {
accounts: string[],
onSelect: (account: string) => void,
selectedAccount?: string,
id?: string
}
export const ServiceNodeAccountSelect: FunctionComponent<ServiceNodeAccountSelectProps> = ({
accounts,
onSelect,
selectedAccount,
id = `serviceNodeAccountSelect-${uuid()}`
}) => (
<Fragment>
<InputLabel htmlFor={id}>
Wallet
</InputLabel>
<Select onChange={event => onSelect(event.target.value as string)}
value={selectedAccount || ""}
>
{accounts.map(account => (
<MenuItem key={account}
value={account}
>
{account}
</MenuItem>
))}
</Select>
</Fragment>
);
|
Prometeus-Network/service-node_ui
|
src/Account/components/AccountBalance.tsx
|
import React, {FunctionComponent} from "react";
import {Hidden} from "@material-ui/core";
import Typography, {TypographyProps} from "@material-ui/core/Typography";
import {makePreciseNumberString} from "../../utils";
export type AccountBalanceProps = TypographyProps & {balance: number, address: string};
export const AccountBalance: FunctionComponent<AccountBalanceProps> = ({balance, address,...rest}) => (
<Typography {...rest}>
<Hidden smDown><span style={{paddingRight: 30}}>Default Wallet ID {address}</span></Hidden> {makePreciseNumberString(balance)} PROM
</Typography>
);
|
Prometeus-Network/service-node_ui
|
src/models/PurchaseFileRequest.ts
|
<filename>src/models/PurchaseFileRequest.ts
export interface PurchaseFileRequest {
dataMartAddress: string
}
|
Prometeus-Network/service-node_ui
|
src/Transaction/stores/index.ts
|
<gh_stars>0
export * from "./ServiceNodeTransactionsStore";
export * from "./DataUploadsTransactionsStore";
export * from "./DataPurchasesTransactionsStore";
|
Prometeus-Network/service-node_ui
|
src/models/LocalFileRecordResponse.ts
|
export interface LocalFileRecordResponse {
id: string
}
|
Prometeus-Network/service-node_ui
|
src/Settings/stores/index.ts
|
export * from "./SettingsStore";
|
Prometeus-Network/service-node_ui
|
src/Account/components/AccountCard.tsx
|
<gh_stars>0
import * as React from "react";
import {Card, CardContent, CardHeader, Typography, Hidden} from "@material-ui/core";
import {getBalanceLabel} from "../utils";
import {AccountType} from "../../models";
interface AccountCardProps {
selectedAsDefault: boolean,
onSelect: (address: string) => void,
address: string,
balance: number,
type: AccountType
}
export const AccountCard: React.FC<AccountCardProps> = ({
balance,
address,
selectedAsDefault,
onSelect,
type
}) => {
return (
<Card elevation={selectedAsDefault ? 3 : 1}
onClick={() => !selectedAsDefault && onSelect(address)}
style={{cursor: 'pointer'}}
>
<CardHeader title={(
<React.Fragment>
<Hidden lgUp>
<Typography variant="caption">
{address}
</Typography>
</Hidden>
<Hidden mdDown>
{address}
</Hidden>
</React.Fragment>
)}
subheader={getBalanceLabel(balance)}
/>
{selectedAsDefault && (
<CardContent>
<Typography variant="h6" color="textSecondary">
Selected as default
</Typography>
</CardContent>
)}
</Card>
)
};
|
Prometeus-Network/service-node_ui
|
src/icons/index.ts
|
export * from "./CopyToClipboardIcon";
export * from "./PrometeusLogoIcon";
|
Prometeus-Network/service-node_ui
|
src/api/index.ts
|
export * from "./services";
export * from "./ApiError";
export * from "./create-error-from-response";
|
Prometeus-Network/service-node_ui
|
src/models/RegisterAccountRequest.ts
|
import {AccountType} from "./AccountType";
export interface RegisterAccountRequest {
address: string,
privateKey: string,
type: AccountType
}
|
Prometeus-Network/service-node_ui
|
src/Account/components/index.ts
|
<reponame>Prometeus-Network/service-node_ui
export * from "./AccountCard";
export * from "./ServiceNodeAccountsList";
export * from "./SelectedServiceNodeBalance";
export * from "./ServiceNodeAccountSelect";
export * from "./AccountsTable";
export * from "./OpenAccountRegistrationDialogButton";
export * from "./AccountRegistrationDialog";
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/DataPurchasesTable.tsx
|
<filename>src/Transaction/components/DataPurchasesTable.tsx<gh_stars>0
import React, {FunctionComponent, Fragment} from "react";
import {
CircularProgress,
createStyles,
makeStyles,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Tooltip,
Typography
} from "@material-ui/core";
import {TransactionResponse} from "../../models";
import {makePreciseNumberString, shortenString} from "../../utils"
interface DataPurchasesTableProps {
transactions: TransactionResponse[],
pending: boolean,
onTransactionDetailsRequest: (transaction: TransactionResponse) => void
}
const useStyles = makeStyles(() => createStyles({
centered: {
marginRight: "auto",
marginLeft: "auto",
display: "table"
},
hyperlinkLike: {
cursor: "pointer"
}
}));
export const DataPurchasesTable: FunctionComponent<DataPurchasesTableProps> = ({
transactions,
pending,
onTransactionDetailsRequest
}) => {
const classes = useStyles();
if (transactions.length === 0 && pending) {
return <CircularProgress size={50} color="primary" className={classes.centered}/>;
} else {
return (
<Fragment>
<Table>
<TableHead>
<TableRow>
<TableCell>Txn Hash</TableCell>
<TableCell>Date</TableCell>
<TableCell>Price</TableCell>
<TableCell>Data Owner</TableCell>
<TableCell>Data Validator</TableCell>
<TableCell>Data Mart</TableCell>
</TableRow>
</TableHead>
<TableBody>
{transactions.map(transaction => (
<TableRow>
<TableCell>
<Tooltip title="Show details">
<Typography variant="body1"
className={classes.hyperlinkLike}
onClick={() => onTransactionDetailsRequest(transaction)}
>
<u>{shortenString(transaction.hash, 16)}</u>
</Typography>
</Tooltip>
</TableCell>
<TableCell>{transaction.created_at}</TableCell>
<TableCell>{makePreciseNumberString(transaction.value)}</TableCell>
<TableCell>{shortenString(transaction.dataOwner, 16)}</TableCell>
<TableCell>{shortenString(transaction.dataValidator, 16)}</TableCell>
<TableCell>{shortenString(transaction.dataMart, 16)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{pending && <CircularProgress size={50} color="primary" className={classes.centered}/>}
</Fragment>
)
}
};
|
Prometeus-Network/service-node_ui
|
src/Transaction/components/ServiceNodeTransactionsCard.tsx
|
<filename>src/Transaction/components/ServiceNodeTransactionsCard.tsx<gh_stars>0
import React, {FunctionComponent, Fragment, useState, ReactNode} from "react";
import {inject, observer} from "mobx-react";
import {Card, CardHeader, CardContent, Grid, Button, Typography} from "@material-ui/core";
import {withSnackbar, WithSnackbarProps} from "notistack";
import {TransactionsTable} from "./TransactionsTable";
import {TransactionDialog} from "./TransactionDialog";
import {IAppState} from "../../store";
import {TransactionResponse} from "../../models";
import {ApiError} from "../../api";
import {Normalized} from "../../utils";
import {ServiceNodeAccountSelect} from "../../Account/components";
interface ServiceNodeTransactionsCardMobxProps {
transactions: Normalized<TransactionResponse>,
serviceNode?: string,
serviceNodes: string[],
pending: boolean,
error?: ApiError,
showSnackbar: boolean,
setShowSnackbar: (showSnackbar: boolean) => void,
fetchTransactions: () => void,
selectServiceNode: (serviceNode: string) => void
}
type ServiceNodeTransactionsCardProps = ServiceNodeTransactionsCardMobxProps & WithSnackbarProps;
const _ServiceNodeTransactionsCard: FunctionComponent<ServiceNodeTransactionsCardProps> = ({
transactions,
showSnackbar,
error,
pending,
serviceNode,
setShowSnackbar,
fetchTransactions,
enqueueSnackbar,
serviceNodes,
selectServiceNode
}) => {
const [transactionInDialog, setTransactionInDialog] = useState<TransactionResponse | undefined>(undefined);
if (showSnackbar) {
if (error) {
enqueueSnackbar("Error occurred when tried to fetch transactions", {variant: "error"});
}
setShowSnackbar(false);
}
let content: ReactNode;
if (Object.keys(transactions).length === 0 && !pending) {
if (error) {
content = <Typography variant="body1">Error occurred when tried to fetch transactions</Typography>
} else {
content = <Typography variant="body1">No transactions have been found</Typography>
}
} else {
content = (
<TransactionsTable transactions={Object.keys(transactions).map(key => transactions[key])}
pending={pending}
onTransactionDetailsRequest={transaction => setTransactionInDialog(transaction)}
/>
)
}
return (
<Fragment>
<Grid container spacing={2}>
<Grid item xs={12}>
<ServiceNodeAccountSelect accounts={serviceNodes}
onSelect={selectServiceNode}
selectedAccount={serviceNode}
/>
</Grid>
<Grid item xs={12}>
<Card style={{overflowX: 'auto'}}>
<CardHeader title={`Transactions of service node ${serviceNode}`}/>
<CardContent>
{content}
</CardContent>
</Card>
</Grid>
<Grid item xs={12}>
<Button variant="outlined"
color="primary"
onClick={fetchTransactions}
disabled={pending}
>
Load more
</Button>
</Grid>
</Grid>
<TransactionDialog transaction={transactionInDialog}
onClose={() => setTransactionInDialog(undefined)}
/>
</Fragment>
)
};
const mapMobxToProps = (state: IAppState): ServiceNodeTransactionsCardMobxProps => ({
pending: state.serviceNodeTransactions.pending,
transactions: state.serviceNodeTransactions.transactions,
error: state.serviceNodeTransactions.error,
serviceNode: state.serviceNodeTransactions.serviceNodeAddress,
showSnackbar: state.serviceNodeTransactions.showSnackbar,
setShowSnackbar: state.serviceNodeTransactions.setShowSnackbar,
fetchTransactions: state.serviceNodeTransactions.fetchTransactions,
selectServiceNode: state.settings.selectServiceNodeAccount,
serviceNodes: state.accounts.accounts.map(account => account.address)
});
export const ServiceNodeTransactionsCard = withSnackbar(
inject(mapMobxToProps)(observer(_ServiceNodeTransactionsCard) as FunctionComponent<{}>)
);
|
Prometeus-Network/service-node_ui
|
src/Account/components/AccountRegistrationDialog.tsx
|
<reponame>Prometeus-Network/service-node_ui
import React, {FunctionComponent} from "react";
import {inject, observer} from "mobx-react";
import {
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
Typography
} from "@material-ui/core";
import withMobileDialog, {WithMobileDialog} from "@material-ui/core/withMobileDialog";
import {withSnackbar, WithSnackbarProps} from "notistack";
import {RegisterAccountRequest} from "../../models";
import {FormErrors} from "../../utils";
import {ApiError} from "../../api";
import {IAppState} from "../../store";
interface AccountRegistrationDialogMobxProps {
registrationForm: Partial<RegisterAccountRequest>,
formErrors: FormErrors<RegisterAccountRequest>,
submissionError?: ApiError,
pending: boolean,
registrationDialogOpen: boolean,
showSnackbar: boolean,
setShowSnackbar: (showSnackbar: boolean) => void,
setFormValue: (key: keyof RegisterAccountRequest, value: string) => void,
setRegistrationDialogOpen: (registrationDialogOpen: boolean) => void,
registerAccount: () => void
}
type AccountRegistrationDialogInjectedProps = WithMobileDialog & WithSnackbarProps;
type AccountRegistrationDialogProps = AccountRegistrationDialogMobxProps & AccountRegistrationDialogInjectedProps;
const _AccountRegistrationDialog: FunctionComponent<AccountRegistrationDialogProps> = ({
registrationForm,
formErrors,
submissionError,
pending,
registrationDialogOpen,
showSnackbar,
setFormValue,
setRegistrationDialogOpen,
setShowSnackbar,
registerAccount,
fullScreen,
enqueueSnackbar
}) => {
if (showSnackbar) {
enqueueSnackbar("Account has been successfully registered");
setShowSnackbar(false);
setRegistrationDialogOpen(false);
}
return (
<Dialog open={registrationDialogOpen}
fullScreen={fullScreen}
fullWidth
maxWidth="md"
onClose={() => setRegistrationDialogOpen(false)}
>
<DialogTitle>Add wallet</DialogTitle>
<DialogContent>
<TextField label="Address"
value={registrationForm.address}
onChange={event => setFormValue("address", event.target.value)}
fullWidth
margin="dense"
error={Boolean(formErrors.address)}
helperText={formErrors.address && formErrors.address}
/>
<TextField label="Private key"
value={registrationForm.privateKey}
onChange={event => setFormValue("privateKey", event.target.value)}
fullWidth
margin="dense"
error={Boolean(formErrors.privateKey)}
helperText={formErrors.privateKey && formErrors.privateKey}
multiline
/>
{submissionError && (
<Typography variant="body1" style={{color: "red"}}>
</Typography>
)}
</DialogContent>
<DialogActions>
<Button variant="outlined"
color="secondary"
onClick={() => setRegistrationDialogOpen(false)}
>
Cancel
</Button>
<Button variant="contained"
color="primary"
onClick={registerAccount}
disabled={pending}
>
Register
</Button>
{pending && <CircularProgress color="primary" size={15}/>}
</DialogActions>
</Dialog>
)
};
const mapMobxToProps = (state: IAppState): AccountRegistrationDialogMobxProps => ({
registrationForm: state.registration.registrationForm,
formErrors: state.registration.formErrors,
submissionError: state.registration.submissionError,
showSnackbar: state.registration.showSnackbar,
pending: state.registration.pending,
registrationDialogOpen: state.registration.registrationDialogOpen,
registerAccount: state.registration.registerAccount,
setRegistrationDialogOpen: state.registration.setRegistrationDialogOpen,
setFormValue: state.registration.setField,
setShowSnackbar: state.registration.setShowSnackbar
});
export const AccountRegistrationDialog = withMobileDialog()(
withSnackbar(
inject(mapMobxToProps)(observer(_AccountRegistrationDialog) as FunctionComponent)
)
);
|
Prometeus-Network/service-node_ui
|
src/api/services/AccountsService.ts
|
import {AxiosPromise} from "axios";
import {axiosInstance} from "../api-client";
import {ACCOUNTS, BALANCES, DEFAULT} from "../endpoints";
import {AccountBalanceMapping, AccountResponse, RegisterAccountRequest, RegisterAccountResponse} from "../../models";
export class AccountsService {
public static registerAccount(registerAccountRequest: RegisterAccountRequest): AxiosPromise<RegisterAccountResponse> {
return axiosInstance.post(`/${ACCOUNTS}`, registerAccountRequest)
}
public static fetchRegisteredAccounts(): AxiosPromise<AccountResponse[]> {
return axiosInstance.get(`/${ACCOUNTS}`);
}
public static getBalancesOfAllAccounts(): AxiosPromise<AccountBalanceMapping> {
return axiosInstance.get(`/${ACCOUNTS}/${BALANCES}`);
}
public static setAccountAsDefault(address: string): AxiosPromise<{success: boolean}> {
return axiosInstance.patch(`/${ACCOUNTS}/${address}/${DEFAULT}`);
}
}
|
Prometeus-Network/service-node_ui
|
src/models/UploadFileChunkRequest.ts
|
<filename>src/models/UploadFileChunkRequest.ts
export interface UploadFileChunkRequest {
chunkData: string
}
|
Prometeus-Network/service-node_ui
|
src/themes/index.ts
|
export * from "./cyan";
export * from "./red";
|
Prometeus-Network/service-node_ui
|
src/models/EncryptFileResponse.ts
|
export interface EncryptFileResponse {
result: string
}
|
Prometeus-Network/service-node_ui
|
src/AppBar/components/index.ts
|
export * from "./AppBar";
export * from "./NavigationalDrawer";
export * from "./OpenDrawerButton";
|
Prometeus-Network/service-node_ui
|
src/Account/components/ServiceNodeAccountsList.tsx
|
<gh_stars>0
import * as React from "react";
import {Grid, Typography} from "@material-ui/core";
import {AccountCard} from "./AccountCard";
import {AccountBalanceMapping, AccountResponse, AccountType} from "../../models";
interface ServiceNodeAccountsListProps {
accounts: AccountResponse[],
balances: AccountBalanceMapping,
defaultAccount?: string,
onDefaultAccountSelected: (address: string) => void
}
export const ServiceNodeAccountsList: React.FC<ServiceNodeAccountsListProps> = ({
defaultAccount,
accounts,
balances,
onDefaultAccountSelected
}) => (
<Grid container spacing={2}>
<Grid item xs={12}>
<Typography variant="subtitle1">
Service node accounts
</Typography>
</Grid>
{accounts.map(account => (
<Grid item xs={12}>
<AccountCard selectedAsDefault={account.address === defaultAccount}
onSelect={onDefaultAccountSelected}
address={account.address}
balance={balances[account.address]}
type={AccountType.DATA_VALIDATOR}
/>
</Grid>
))}
</Grid>
);
|
Prometeus-Network/service-node_ui
|
src/Account/components/AccountsTable.tsx
|
<gh_stars>0
import React, {FunctionComponent} from "react";
import {inject, observer} from "mobx-react";
import {
Card,
CardContent,
CardHeader,
Checkbox,
createStyles,
makeStyles,
Table,
TableBody,
TableCell,
TableHead,
TableRow
} from "@material-ui/core";
import {AccountBalanceMapping, AccountResponse} from "../../models";
import {IAppState} from "../../store";
import {makePreciseNumberString} from "../../utils";
interface AccountsTableMobxProps {
accounts: AccountResponse[],
balances: AccountBalanceMapping,
defaultAccountAddress?: string,
setDefaultAccount: (address: string) => void
}
const useStyles = makeStyles(() => createStyles({
accountsTableCard: {
overflowX: "auto"
}
}));
const _AccountsTable: FunctionComponent<AccountsTableMobxProps> = ({
accounts,
balances,
defaultAccountAddress,
setDefaultAccount
}) => {
const classes = useStyles();
return (
<Card className={classes.accountsTableCard}>
<CardHeader title="Your Wallets"/>
<CardContent>
<Table>
<TableHead>
<TableRow>
<TableCell><b>Address</b></TableCell>
<TableCell><b>Balance</b></TableCell>
<TableCell><b>Is default</b></TableCell>
</TableRow>
</TableHead>
<TableBody>
{accounts.map(account => (
<TableRow>
<TableCell>{account.address}</TableCell>
<TableCell>{makePreciseNumberString(balances[account.address], 16)}</TableCell>
<TableCell>
<Checkbox checked={defaultAccountAddress === account.address}
onChange={() => setDefaultAccount(account.address)}
/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
)
};
const mapMobxToProps = (state: IAppState): AccountsTableMobxProps => ({
accounts: state.accounts.accounts,
balances: state.balances.accountsBalances,
defaultAccountAddress: state.settings.selectedServiceNodeAccount,
setDefaultAccount: state.settings.selectServiceNodeAccount
});
export const AccountsTable = inject(mapMobxToProps)(observer(_AccountsTable as FunctionComponent));
|
Prometeus-Network/service-node_ui
|
src/models/EncryptFileRequest.ts
|
export interface EncryptFileRequest {
public_key: string,
content: string
}
|
Prometeus-Network/service-node_ui
|
src/index.tsx
|
<reponame>Prometeus-Network/service-node_ui
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from "mobx-react"
import {App} from './App';
import {store} from "./store";
import {Routes} from "./router";
import * as serviceWorker from './serviceWorker';
const {RouterStore, startRouter} = require("mobx-router");
const routerStore = {
router: new RouterStore()
};
startRouter(Routes, routerStore, {
notfound: () => {
routerStore.router.goTo(Routes.notFound);
}
});
store.accounts.fetchAccounts();
ReactDOM.render(<Provider store={routerStore} {...store}>
<App/>
</Provider>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
lendilai/Quotes-app
|
src/app/days-since.pipe.ts
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'daysSince'
})
export class DaysSincePipe implements PipeTransform {
transform(value:any): number {
let today:Date = new Date();
let todayDateOnly:any = new Date(today.getFullYear(), today.getMonth(), today.getDate());
var milliSecondsPassed = Math.abs(todayDateOnly - value);
var secondsPassed = milliSecondsPassed*0.001;
const secondsPerDay = 86400;
var daysPassed = secondsPassed/secondsPerDay;
var newDaysPassed = Math.round(daysPassed);
if(newDaysPassed >= 1){
return newDaysPassed;
}else{
return 0;
}
}
}
|
lendilai/Quotes-app
|
src/app/quotes.ts
|
<reponame>lendilai/Quotes-app<filename>src/app/quotes.ts
export class Quotes {
showQuote: boolean;
constructor(public author:string, public description:string, public newDate:Date){
this.showQuote=false;
}
}
|
lendilai/Quotes-app
|
src/app/post-details/post-details.component.ts
|
<filename>src/app/post-details/post-details.component.ts
import { Component, HostBinding, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Quotes } from '../quotes';
@Component({
selector: 'app-post-details',
templateUrl: './post-details.component.html',
styleUrls: ['./post-details.component.css']
})
export class PostDetailsComponent implements OnInit {
@Input() quote:Quotes;
@Output() deleteIt = new EventEmitter<boolean>();
@HostBinding('attr.class') cssClass='row';
votes: number;
votesDown:number;
constructor() {
this.votes= 0;
this.votesDown= 0;
}
voteUp(){
this.votes += 1;
}
voteDown(){
this.votesDown += 1;
}
ngOnInit() {
}
quoteDelete(remove:boolean){
this.deleteIt.emit(remove);
}
}
|
lendilai/Quotes-app
|
src/app/post/post.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Quotes } from '../quotes';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
quotes = [
new Quotes("<NAME>", "Tell me and I forget. Teach me and I remember. Involve me and I learn.", new Date(1782, 3, 24)),
new Quotes("<NAME>", "One good thing about music, when it hits you, you feel no pain.", new Date(1963, 7, 2)),
new Quotes("<NAME>", "In the end, it's not the years in your life that count. It's the life in your years.", new Date(1860, 5, 13)),
new Quotes("The Notorius B.I.G", "Mo money mo problems.", new Date(1997, 1, 7)),
new Quotes("<NAME>", "I’d shoot for the moon but I’m too busy gazing at stars.", new Date(2010, 3, 29)),
];
showDescription(index){
this.quotes[index].showQuote = !this.quotes[index].showQuote;
}
removeIt(deleteIt, index){
if(deleteIt){
let confirmDelete = confirm("Are you sure you want to delete this quote?");
if(confirmDelete){
this.quotes.splice(index, 1);
}
}
}
fromUser(quote){
quote.newDate = new Date(quote.newDate);
this.quotes.unshift(quote);
}
constructor() { }
ngOnInit(){}
}
|
lendilai/Quotes-app
|
src/app/hideit.directive.ts
|
<reponame>lendilai/Quotes-app<gh_stars>1-10
import { Directive,ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHideit]'
})
export class HideitDirective {
constructor(private elem:ElementRef) { }
@HostListener("click") onClicks(){
this.cancelIt("white");
}
@HostListener("dblclick") onDoubleClicks(){
this.cancelIt("black")
}
private cancelIt(action:string){
this.elem.nativeElement.style.color=action;
}
}
|
projectbox99/mean
|
dev/app/Services/auth.guard.ts
|
import { Injectable } from "@angular/core";
import { Router, CanActivate } from "@angular/router";
import { AuthService } from "./authentication.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
// static methods
public canActivate(): boolean {
if (this.hasTokenInSessionStorage) {
return true;
}
this.navigateHome();
return false;
} // canActivate()
public canActivateRegularRoute(): boolean {
if (this.hasTokenInSessionStorage) {
return true;
}
this.navigateHome();
return false;
} // canActivateRegularRoute()
public canActivateSupervisorRoute(): boolean {
if (this.hasTokenInSessionStorage &&
(this.authService.currentUser.role === "supervisor" || this.authService.currentUser.role === "admin")) {
return true;
}
this.navigateHome();
return false;
} // canActivateSupervisorRoute()
public canActivateAdminRoute(): boolean {
if (this.hasTokenInSessionStorage && this.authService.currentUser.role === "admin") {
return true;
}
this.navigateHome();
return false;
} // canActivateAdminRoute()
// helpers
private hasTokenInSessionStorage(): boolean {
return sessionStorage.getItem("token") ? true : false;
} // hasTokenInSessionStorage()
private hasTokenInLocalStorage(): boolean {
return localStorage.getItem("token") ? true : false;
} // hasTokenInLocalStorage()
private navigateHome(): void {
let routeOut: string = "/";
this.router.navigate([ routeOut ]);
} // navigateHome()
} // class AuthGuard
|
projectbox99/mean
|
dev/app/ads/ads.routes.ts
|
<filename>dev/app/ads/ads.routes.ts
"use strict";
import { Routes, RouterModule } from "@angular/router";
import { AdDetailComponent } from "./ad-detail.component";
import { AdsComponent } from "./ads-list.component";
import { AdReviewComponent } from "./ad-review.component";
const adRoutes: Routes = [
{ path: "ads/list/:id", component: AdsComponent },
{ path: "ads/:id", component: AdDetailComponent },
{ path: "ads/preview/:id", component: AdReviewComponent }
];
export const adRouting = RouterModule.forChild(adRoutes);
|
projectbox99/mean
|
dev/app/Services/users.service.ts
|
"use strict";
import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
// import { AuthService } from "./authentication.service";
export class User {
constructor(
public id: string = null,
public username: string,
public password: string,
public namesFirst?: string,
public namesLast?: string,
public email?: string,
public phone1?: string,
public phone2?: string,
public skypeId?: string,
public photo?: string,
public role?: string,
public dateCreated?: Date) { }
public get names(): string {
return (this.namesFirst || "") + (this.namesLast || "");
} // get names()
} // class User
@Injectable()
export class UserService {
private userUrl: string =
window.location.protocol + "//" +
window.location.hostname +
((window.location.port === "80")
? ("")
: (":" + window.location.port)) + "/api/users";
private token: string;
constructor (private http: Http
/* private authService: AuthService */) {
this.token = JSON.parse(sessionStorage.getItem("token"));
}
// anyone can register a new user
public addUser(user: User): Observable<User> {
let headers: Headers = new Headers({ "Content-Type": "application/json" });
let options: RequestOptions = new RequestOptions({ headers: headers });
let body: string = JSON.stringify(user);
return this.http.post(this.userUrl, body, options) // returns Observable<Response>
.map(this.extractData) // success
.catch(this.handleError); // error
} // addUser()
public getUsers(): Observable<User[]> {
// add authorization header with jwt token
let headers = new Headers({ "Authorization": "Bearer " + this.token });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.userUrl, options)
.map((response: Response) => this.extractData(response))
.catch(this.handleError);
} // getUsers()
public getUser(id: string): Observable<User> {
if (!id) {
console.log(`getUser was called with a bad id argument: ${id.toString()}`);
return Observable.create(new User("", "", ""));
}
let headers = new Headers({ "Authorization": "Bearer " + this.token });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.userUrl + "/" + id, options)
.map((response: Response) => {
let userData = this.extractData(response);
if (userData._id && userData.username) {
userData.id = userData._id;
return userData;
} else {
return Observable.create(new User("", "", ""));
}
})
.catch(this.handleError);
} // getUser()
public putUser(user: User): Observable<User> {
if (!user || !user.id || !user.username || !user.password) {
console.log(`putUser was called with a bad user argument: ${JSON.stringify(user)}`);
return Observable.create(new User("", "", ""));
}
let headers = new Headers({ "Authorization": "Bearer " + this.token, "Content-Type": "application/json" });
let options = new RequestOptions({ headers: headers });
let body: string = JSON.stringify(user);
return this.http.put(this.userUrl + "/" + user.id, body, options)
.map((response: Response) => {
let userData = this.extractData(response);
if (userData._id && userData.username) {
userData.id = userData._id;
console.info(`putUser returns: ${JSON.stringify(userData)}`);
return userData;
} else {
return Observable.create(new User("", "", ""));
}
})
.catch(this.handleError);
} // putUser()
public deleteUser(id: string): Observable<boolean> {
if (!id) {
console.log(`deleteUser was called with a bad id argument: ${id.toString()}`);
return Observable.create(false);
}
let headers = new Headers({ "Authorization": "Bearer " + this.token });
let options = new RequestOptions({ headers: headers });
return this.http.delete(this.userUrl + "/" + id, options)
.map((response: Response) => {
console.log("deleteUser response: " + this.extractData(response));
return this.extractData(response) === "OK";
})
.catch((error) => {
this.handleError(error).map((errMsg) => console.error("deleteUser Error: " + errMsg));
return Observable.create(false);
});
} // deleteUser()
// private helpers
private extractData(res: Response) {
let body = res.json();
return body.data || {};
} // extractData()
private handleError (error: any) {
let errMsg =
(error.message)
? error.message
: (error.status)
? `${error.status} - ${error.statusText}`
: "Server Error";
return Observable.throw(errMsg);
} // handleError()
} // class RegisterService
|
projectbox99/mean
|
dev/app/register/register.component.ts
|
<gh_stars>0
"use strict";
import { Component, OnInit, OnDestroy, ElementRef, Input, Output, EventEmitter } from "@angular/core";
import { NgForm, Location } from "@angular/common";
import { Router, ActivatedRoute, Params } from "@angular/router";
import { Subscription } from "rxjs/Subscription";
import { User, UserService } from "../Services/users.service";
import { StandingData } from "../Services/standing.data.service";
import { AuthService } from "../Services/authentication.service";
import { RestoreService } from "../Services/restore.service";
@Component ({
templateUrl: "register.component.html",
styleUrls: [ "register.component.css" ],
providers: [ UserService, RestoreService ]
})
export class UserRegistrationComponent implements OnInit, OnDestroy {
@Output() canceled = new EventEmitter();
@Output() saved = new EventEmitter();
@Input()
set user (user: User) {
this.restoreService.setItem(user);
}
get user () {
return this.restoreService.getItem();
}
private password2: string;
private roles: string[];
private currentUser: User;
private isAdmin: boolean;
private sub: Subscription;
private isEditingUser: boolean;
private errorMsg: string;
private statusMsg: string;
private active: boolean;
public constructor(private authService: AuthService,
private userService: UserService,
private standingData: StandingData,
private restoreService: RestoreService<User>,
private location: Location,
private element: ElementRef,
private route: ActivatedRoute,
private router: Router) {
this.user = new User("", "", "");
}
// make sure two-way binding is working
public get diagnostic(): string { return JSON.stringify(this.user); }
public imgChange(event) {
let target = EventTarget;
let image = this.element.nativeElement.querySelector('.user-image-input');
let reader: any = new FileReader();
var self = this;
reader.onload = function(e) {
self.user.photo = e.target.result;
image.src = self.user.photo;
}
reader.readAsDataURL(event.target.files[0]);
} // imgChange()
public onSubmit(): void {
this.errorMsg = "";
this.statusMsg = "";
if (this.isEditingUser) {
this.modifyUser(this.user);
} else {
this.addUser(this.user);
}
if (this.errorMsg) {
this.active = true;
} else {
if (this.isEditingUser)
setTimeout(() => this.location.back(), 1000);
else
setTimeout(() => this.router.navigate([ "/" ]), 1000);
}
} // onSubmit()
public clearForm(): void {
// features a temporary workaround while we await a proper form reset feature
this.user = new User("" /* id */, "" /* username */, "" /* password */);
this.password2 = "";
this.active = false;
setTimeout(() => this.active = true, 0);
} // clearForm()
private addUser(user: User): void {
this.userService.addUser(this.user)
.subscribe( // we want an Observable returned
userData => { // function to invoke for each element in the observable sequence
this.user = userData;
this.password2 = "";
this.isAdmin = this.user.role === "admin";
this.statusMsg = "User created successfully";
this.active = false;
},
error => { // function to invoke on exceptional termination of the obs. sequence
this.errorMsg = <any>error;
},
() => {
// function to invoke upon graceful termination of the observable sequence
console.info("UserRegistrationComponent.addUser()'s observable completed gracefully");
});
} // addUser()
private modifyUser(user: User): void {
this.userService.putUser(this.user)
.subscribe(
userData => {
this.user = userData;
this.password2 = "";
this.statusMsg = "User modified successfully";
this.active = true;
},
error => {
this.errorMsg = <any>error;
},
() =>{
console.info("UserRegistrationComponent.modifyUser()'s observable completed gracefully");
});
} // modifyUser()
ngOnInit() {
this.currentUser = this.authService.currentUser;
this.isAdmin = this.authService.usrRole === "admin";
this.isEditingUser = false;
this.password2 = "";
this.sub = this.route.params.subscribe(
params => {
let id = params["id"];
if (id) {
this.isEditingUser = true;
this.userService.getUser(id).subscribe(
userData => this.user = userData,
error => this.errorMsg = <any>error
);
}
}
);
// this.roles = [ "admin", "supervisor", "regular" ];
this.roles = this.standingData.lists.roles;
this.errorMsg = "";
this.statusMsg = "";
this.active = true;
} // ngOnInit()
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
} // ngOnDestroy()
} // class UserRegistrationComponent
|
projectbox99/mean
|
dev/app/Services/authentication.service.ts
|
<filename>dev/app/Services/authentication.service.ts
import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { User } from "./users.service";
@Injectable()
export class AuthService {
public token: string;
public currentUser: User;
constructor(private http: Http) {
// set token if saved in session storage
this.currentUser = new User("", "", "");
this.token = JSON.parse(sessionStorage.getItem("token"));
}
public get usrLoggedIn(): boolean {
return this.currentUser.username &&
this.currentUser.username.trim() !== "" &&
this.token !== "";
}// get usrLoggedIn()
public get usrRole(): string {
if (this.currentUser.role && this.currentUser.role.trim() !== "")
return this.currentUser.role.trim();
return "";
} // get usrRole()
public get usrUsername(): string {
if (this.currentUser.username && this.currentUser.username.trim() !== "")
return this.currentUser.username.trim();
return "";
} // get usrUsername()
public get usrNamesFirst(): string {
if (this.currentUser.namesFirst && this.currentUser.namesFirst.trim() !== "")
return this.currentUser.namesFirst.trim();
return "";
} // get usrNamesFirst()
public login(username, password): Observable<boolean> {
let headers: Headers = new Headers({ "Content-Type": "application/json" });
let options: RequestOptions = new RequestOptions({ headers: headers });
let body: string = JSON.stringify({ username: username, password: password });
return this.http.post("/api/login", body, options)
.map((response: Response) => {
// login successful if there's a jwt token in the response
let token = response.json().data && response.json().data.token;
if (token) {
// set token property
this.token = token;
// store username and jwt token in local storage to keep user logged in between page refreshes
sessionStorage.removeItem("token");
sessionStorage.setItem("token", JSON.stringify(this.token));
}
let userData = JSON.stringify(response.json().data.user);
if (userData) {
// this.currentUser = JSON.parse(userData);
let usr = JSON.parse(userData);
this.currentUser = new User(
usr._id, usr.username, usr.password, usr.namesFirst, usr.namesLast, usr.email,
usr.phone1, usr.phone2, usr.skypeId, usr.photo, usr.role, usr.dateCreated);
}
if (!this.token || !this.currentUser) {
// return false to indicate failed login
return false;
}
// return true to indicate successful login
return true;
})
.catch((error) => this.handleError(error));
} // login()
public logout(): void {
// clear token remove user from local storage to log user out
this.token = null;
sessionStorage.removeItem("token");
this.currentUser = new User("", "", "");
} // logout()
private handleError (error: any) {
let errMsg =
(error.message)
? error.message
: (error.status)
? `${error.status} - ${error.statusText}`
: "Server Error";
return Observable.throw(errMsg);
} // handleError()
} // class AuthService
|
projectbox99/mean
|
dev/app/ads/ads.module.ts
|
"use strict";
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { HttpModule /*, XHRBackend */} from "@angular/http";
// components
import { AdDetailComponent } from "./ad-detail.component";
import { AdsComponent } from "./ads-list.component";
import { AdReviewComponent } from "./ad-review.component";
import { AdsService } from "../Services/ads.service";
import { StandingData } from "../Services/standing.data.service";
import { AuthService } from "../Services/authentication.service";
import { PagerService } from "../Services/pager.service";
import { UserService } from "../Services/users.service";
import { adRouting } from "./ads.routes";
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
adRouting
],
declarations: [
AdDetailComponent,
AdsComponent,
AdReviewComponent
],
providers: [
AdsService, StandingData, AuthService, PagerService, UserService
]
})
export class AdsModule { }
|
projectbox99/mean
|
dev/app/ads/ad-review.component.ts
|
<filename>dev/app/ads/ad-review.component.ts
"use strict";
import { Component, EventEmitter, Input, Output, OnInit, OnDestroy, ElementRef } from "@angular/core";
import { Router, ActivatedRoute, Params } from "@angular/router";
import { Response } from "@angular/http";
import { Location } from "@angular/common";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { User, UserService } from "../Services/users.service";
import { AdsService, Ad } from "../Services/ads.service";
import { StandingData, Lists } from "../Services/standing.data.service";
import { AuthService } from "../Services/authentication.service";
@Component ({
templateUrl: "ad-review.component.html",
styleUrls: [ "ad-review.component.css" ],
providers: [ AdsService, UserService ]
})
export class AdReviewComponent implements OnInit, OnDestroy {
private ad: Ad;
private adOwner: User;
private currentUser: User;
private usrRole: string;
private lists: Lists;
private sub: Subscription;
private errorMsg: string;
// Image data
private photoMain: string;
private photos: string[];
private percent: number;
constructor(private route: ActivatedRoute,
private router: Router,
private adsService: AdsService,
private standingData: StandingData,
private authService: AuthService,
private element: ElementRef,
private userService: UserService,
private location: Location) {
this.errorMsg = "";
this.adOwner = new User("", "", "");
this.currentUser = authService.currentUser;
this.usrRole = authService.usrRole;
this.lists = new Lists([], [], []);
this.loadStandingData();
this.photoMain = "";
this.photos = <string[]>[];
}
public loadStandingData(): void {
this.lists = this.standingData.getLists();
} // loadStandingData()
gotoAds() {
this.router.navigate(["/ads"]);
} // gotoAds()
ngOnInit() {
this.ad = new Ad();
this.sub = this.route.params.subscribe(
params => {
let id = params["id"];
if (id) {
this.adsService.getAd(id).subscribe(
adData => {
this.ad = adData;
this.photoMain = "/uploads/" + this.ad.photoMain;
for (let i = 0; i < this.ad.photos.length; i++) {
this.photos[i] = "/uploads/" + this.ad.photos[i];
}
this.userService.getUser(this.ad.owner).subscribe(
userData => {
this.adOwner = userData;
// console.log(`adOwner: ${JSON.stringify(this.adOwner)}`);
},
error => this.errorMsg = <any>error
);
}, error => this.errorMsg = <any>error
);
}
}
);
} // ngOnInit()
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
} // ngOnDestroy()
private handleError (error: any) {
this.errorMsg = (error.message)
? error.message
: error.status
? `${error.status} - ${error.statusText}`
: "Server error";
console.error(this.errorMsg);
return Observable.throw(this.errorMsg);
} // handleError()
}
|
projectbox99/mean
|
dev/app/Directives/nav-link-behavior.ts
|
<reponame>projectbox99/mean
import { Directive, ElementRef, HostListener, Input } from "@angular/core";
@Directive({
selector: "[nav-link-custom]"
})
export class NavLinkDirective {
private defaultHighlighColor = "DodgerBlue";
private el: HTMLElement;
constructor(el: ElementRef) { this.el = el.nativeElement; }
@Input("nav-link-custom") highlightColor: string;
@HostListener("mouseenter") onMouseEnter() {
this.highlight(this.highlightColor || this.defaultHighlighColor);
}
@HostListener("mouseleave") onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.style.backgroundColor = color;
}
} // class NavLinkDirective
|
projectbox99/mean
|
dev/app/users/users.component.ts
|
"use strict";
import { Component, OnInit, OnDestroy } from "@angular/core";
import { Router } from "@angular/router";
import { User, UserService } from "../Services/users.service";
import { Subscription } from "rxjs/Subscription";
@Component ({
selector: "user-list",
templateUrl: "./users.component.html",
styleUrls: [ "users.component.css" ],
providers: [ UserService ]
})
export class UsersComponent {
private users: User[];
private sub: Subscription;
private loading: boolean;
constructor(private userService: UserService,
private router: Router) {
this.loadUsers();
}
public loadUsers(): void {
this.sub = this.userService.getUsers()
.subscribe(
users => {
this.users = users;
},
error => {
console.log(`Error: ${JSON.stringify(error)}`);
},
() => {
console.info("The users Observable came through successfully!");
}
);
} // loadUsers()
public refresh(): void {
this.loading = true;
this.loadUsers();
this.loading = false;
} // refresh()
public delUser(id: string): void {
console.info(`delUser(${id}) started`);
this.loading = true;
if (id) {
this.userService.deleteUser(id).subscribe(
result => {
if (result === true) {
this.loadUsers();
} else {
console.error(`delUser(${id}) returned ${result}`);
}
},
error => {
console.log(`delUser(${id}) returned an Error: ${error.toString()}`);
},
() => {
console.info("delUser() Observable completed gracefully.");
this.loading = false;
});
}
} // delUser()
public editUser(id: string): void {
console.info(`editUser(${id}) started`);
this.loading = true;
if (id) {
this.router.navigate([ "/users", id ]).then(
result => {
if (result === true) {
console.info("Redirect to user profile succeeded!");
} else { // result === false
console.error("Redirect to user profile failed!");
}
}, error => {
console.error(`Error redirecting to user's profile: ${error.toString()}`);
}
);
}
this.loading = false;
} // editUser()
ngOnInit() {
this.loading = false;
}
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
}
} // class UsersComponent
|
projectbox99/mean
|
dev/app/ads/ad-detail.component.ts
|
"use strict";
import { Component, EventEmitter, Input, Output, OnInit, OnDestroy, ElementRef } from "@angular/core";
import { Router, ActivatedRoute, Params } from "@angular/router";
import { Response } from "@angular/http";
import { Location } from "@angular/common";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { User } from "../Services/users.service";
import { AdsService, Ad } from "../Services/ads.service";
import { StandingData, Lists } from "../Services/standing.data.service";
import { AuthService } from "../Services/authentication.service";
import { RestoreService } from "../Services/restore.service";
@Component ({
templateUrl: "ad-detail.component.html",
styleUrls: [ "ad-detail.component.css" ],
providers: [ AdsService, RestoreService ]
})
export class AdDetailComponent implements OnInit, OnDestroy {
@Output() canceled = new EventEmitter();
@Output() saved = new EventEmitter();
@Input()
set ad (ad: Ad) {
this.restoreService.setItem(ad);
}
get ad () {
return this.restoreService.getItem();
}
private currentUser: User;
private curUsrRole: string;
private selectedId: string;
private lists: Lists;
private sub: Subscription;
private active: boolean;
private loading: boolean;
private isEditingAd: boolean;
private errorMsg: string;
private statusMsg: string;
// Image uploads
private photoMain: string;
private photos: string[];
private percent: number;
constructor(private route: ActivatedRoute,
private router: Router,
private adsService: AdsService,
private standingData: StandingData,
private authService: AuthService,
private restoreService: RestoreService<Ad>,
private element: ElementRef,
private location: Location) {
this.curUsrRole = authService.usrRole;
this.lists = new Lists([], [], []);
this.loadStandingData();
this.percent = 0;
this.photoMain = "";
this.photos = <string[]>[];
}
public get diagnostic(): string { return JSON.stringify(this.ad); }
private drop(event: any, count: number = 0): void {
event.stopPropagation();
event.preventDefault();
let files = event.dataTransfer.files;
let filesCount = files.length;
for (let i = 0; i < filesCount; i++) {
console.info(`[${i}] ${files[i]} ${files[i].name} ${files[i].size}`);
}
let reader: any = new FileReader();
let image = this.element.nativeElement.querySelector("#photo" + count);
let file: File = files[0];
reader.onload = (e) => {
if (count == 0) {
console.log("Rendering photoMain...");
this.photoMain = e.target.result;
image.src = this.photoMain;
} else if (count <= 5) {
console.log(`Rendering photo[${count - 1}]...`);
this.photos[count - 1] = e.target.result;
image.src = this.photos[count - 1];
} else {
return;
}
}
reader.readAsDataURL(file);
this.uploadFile(file, count);
}
private uploadFile(file: File, count: number): void {
this.makeFileRequest("/upload", file)
.then(
result => {
if (count === 0) {
this.ad.photoMain = result.fileName;
console.log(`uploadFile setting this.ad.photoMain to ${this.ad.photoMain}`);
// this.photoMain = "uploads/" + this.ad.photoMain;
} else {
this.ad.photos[count - 1] = result.fileName;
console.log(`uploadFile setting this.ad.photos[${count - -1}] to ${this.ad.photos[count-1]}`);
// this.photos[count - 1] = "uploads/" + this.ad.photos[count - 1];
}
},
error => {
console.error(error);
}
);
} // uploadFile()
private makeFileRequest(url: string, file: File): any {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
let formData: any = new FormData();
formData.append("file", file, file.name);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.response.data);
} else {
this.percent = 0;
reject(xhr.response);
}
}
};
// xhr.upload.onprogress = (e) => {
// window.setTimeout(() => {
// this.percent = Math.ceil((e.loaded / e.total) * 100);
// console.log(this.percent + "%");
// }, 10);
// }
xhr.open("POST", url, true);
xhr.responseType = "json";
xhr.send(formData);
});
} // makeFileRequest()
private allowDrop(event): void {
event.stopPropagation();
event.preventDefault();
}
public imgChange(event: any, count: number = 0) {
let target = EventTarget;
let image = this.element.nativeElement.querySelector(`#photo${count}`);
let reader: any = new FileReader();
var self = this;
reader.onload = function(e) {
if (count === 0) {
console.log("Rendering main image...");
self.photoMain = e.target.result;
// self.ad.photoMain = self.photoMain;
image.src = self.photoMain;
} else {
console.log(`Rendering image ${count - 1}...`);
self.photos[count - 1] = e.target.result;
self.ad.photos[count - 1] = self.photos[count - 1];
image.src = self.photos[count - 1];
console.log(self.ad.photos.length);
}
}
reader.readAsDataURL(event.target.files[0]);
this.uploadFile(event.target.files[0], count);
} // imgChange()
public loadStandingData(): void {
this.lists = this.standingData.getLists();
} // loadStandingData()
public onSubmit(): void {
this.errorMsg = "";
this.statusMsg = "";
console.log(`Submitting: ${JSON.stringify(this.ad)}`);
if (this.isEditingAd) {
this.modifyAd(this.ad);
} else {
console.log('choosing addAd()');
this.addAd(this.ad);
}
if (this.errorMsg) {
this.active = true;
} else {
if (this.isEditingAd)
setTimeout(() => this.location.back(), 1000);
else
setTimeout(() => this.router.navigate([ "/" ]), 1000);
}
} // onSubmit()
public clearForm(): void {
// features a temporary workaround while we await a proper form reset feature
this.ad = new Ad();
this.active = false;
setTimeout(() => this.active = true, 0);
} // clearForm()
public gotoPreview(): void {
if (this.ad.id) {
this.router.navigate([ "/ads/preview", this.ad.id ]);
}
} // gotoPreview()
private addAd(ad: Ad): void {
console.log(`IN addAd: ${ad}`);
this.adsService.postAd(this.ad).subscribe( // we want an Observable returned
adData => { // function to invoke for each element in the observable sequence
this.ad = adData;
this.statusMsg = "Ad created successfully";
this.active = false;
},
error => { // function to invoke on exceptional termination of the obs. sequence
this.errorMsg = <any>error;
},
() => {
// function to invoke upon graceful termination of the observable sequence
console.info("UserRegistrationComponent.addUser()'s observable completed gracefully");
});
} // addAd()
private modifyAd(ad: Ad): void {
this.adsService.putAd(this.ad)
.subscribe(
adData => {
this.ad = adData;
this.statusMsg = "User modified successfully";
this.active = true;
},
error => {
this.errorMsg = <any>error;
},
() =>{
console.info("UserRegistrationComponent.modifyUser()'s observable completed gracefully");
});
} // modifyAd()
saveAd() {
if (this.ad.id) {
this.adsService.putAd(this.ad).subscribe(
ad => this.ad = ad,
error => this.handleError(error));
} else {
this.adsService.postAd(this.ad).subscribe(
ad => this.ad = ad,
error => this.handleError(error));
}
} // saveAd()
deleteAd(id: string, event: any): void {
event.stopPropagation();
this.loading = true;
if (id) {
this.adsService.deleteAd(id).subscribe(
result => {
if (result === true) {
this.selectedId = null;
this.gotoAds();
}
},
error => this.handleError(error),
() => {
this.loading = false;
});
}
} // deleteAd()
gotoAds() {
this.router.navigate(["/ads"]);
// let adId = this.ad ? this.ad.id : null;
// this.router.navigate(["/ads", { id: adId }]);
} // gotoAds()
ngOnInit() {
this.currentUser = this.authService.currentUser;
this.ad = new Ad();
this.ad.owner = this.currentUser.id;
this.isEditingAd = false;
this.sub = this.route.params.subscribe(
params => {
let id = params["id"];
if (id && id !== "create") {
this.isEditingAd = true;
this.adsService.getAd(id).subscribe(
adData => {
this.ad = adData;
console.log(`ngOnInit loads ad: ${JSON.stringify(this.ad)}`);
this.photoMain = this.ad.photoMain ? "/uploads/" + this.ad.photoMain : "";
console.log(`ngOnInit setting this.photoMain to ${this.photoMain}`);
for (let i = 0; i < this.ad.photos.length; i++) {
this.photos[i] = "/uploads/" + this.ad.photos[i];
console.log(`ngOnInit setting this.photos[${i}] to ${this.photos[i]}`);
}
}, error => this.errorMsg = <any>error
);
} else {
this.ad.approved = false;
}
}
);
this.errorMsg = "";
this.statusMsg = "";
this.active = true;
this.loading = false;
} // ngOnInit()
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
} // ngOnDestroy()
private handleError (error: any) {
this.errorMsg = (error.message)
? error.message
: error.status
? `${error.status} - ${error.statusText}`
: "Server error";
console.error(this.errorMsg);
return Observable.throw(this.errorMsg);
} // handleError()
}
|
projectbox99/mean
|
dev/app/app.layout.ts
|
"use strict";
import { Router } from "@angular/router";
import { Component, OnInit} from "@angular/core";
import { NgForm } from "@angular/common";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
// animation-specific imports
import { Input, trigger, state, style, transition, animate } from "@angular/core";
import { User, UserService } from "./Services/users.service";
import { AuthService } from "./Services/authentication.service";
import { Lists, StandingData } from "./Services/standing.data.service";
@Component ({
selector: "mean2-app",
templateUrl: "app.layout.html",
styleUrls: [ "app.layout.css" ],
animations: [
trigger("navLinkState", [
state("inactive", style({
transform: "scale(1)"
})),
state("active", style({
transform: "scale(1)"
})),
transition("inactive => active", animate("100ms ease-in")),
transition("active => inactive", animate("100ms ease-out"))
])
],
providers: [ UserService, AuthService ]
})
export class AppLayout implements OnInit {
public currentUser: User;
public loggedIn: boolean;
public currentUserRole: string;
private lists: Lists;
public pickedCategory;
public editedCategory;
public loading: boolean;
public active: boolean;
public submitted: boolean;
public error: string;
constructor(private router: Router,
private userService: UserService,
private authService: AuthService,
private standingData: StandingData) {
this.lists = new Lists([], [], []);
}
public linkState: string = "inactive";
public toggleLinkState() {
if (this.linkState === "active")
this.linkState = "inactive";
else
this.linkState = "active";
}
public loadStandingData(): void {
this.lists = this.standingData.getLists();
} // loadStandingData()
public login(): void {
this.loading = true;
this.submitted = true;
this.authService.login(this.currentUser.username, this.currentUser.password)
.subscribe(result => {
if (result === true) {
// login successful
this.loadStandingData();
this.currentUser = this.authService.currentUser;
this.currentUserRole = this.currentUser.role;
this.loggedIn = true;
this.setErrorMsg();
this.router.navigate(["/"]);
} else {
// login failed
this.currentUser.password = "";
this.loading = false;
this.loggedIn = false;
this.submitted = false;
this.setErrorMsg("Invalid Username or Password");
}
this.loading = false;
},
error => {
console.log(error);
this.currentUser.password = "";
this.loading = false;
this.loggedIn = false;
this.submitted = false;
if (error.indexOf("401") > -1)
this.setErrorMsg("Invalid Username or Password");
else
this.setErrorMsg(error);
});
} // login()
public logout(): void {
this.authService.logout();
this.active = false;
setTimeout(() => this.active = true, 0);
this.currentUser = this.authService.currentUser;
this.currentUserRole = "";
this.loggedIn = false;
this.router.navigate(["/"]);
this.loading = false;
} // logout()
private editCategory(): void {
let picked: string = this.pickedCategory || "";
let edited: string = this.editedCategory || "";
let result;
if (!edited)
return;
console.log(`picked: "${picked}"`);
if (!picked || picked === undefined || picked === "") { // add a new category entry
console.info(`Requesting ADD on category: ${edited}`);
result = this.standingData.addCategory(edited).subscribe(
res => {
if (res.categories && res.categories.length) {
this.lists = res;
console.log(`this.lists set to: ${JSON.stringify(this.lists)}`);
} else {
this.setErrorMsg(`Could not add category: ${JSON.stringify(res)}`);
console.log(this.error);
return;
}
},
error => {
this.setErrorMsg(`Error adding category: ${edited}`);
console.log(this.error);
return;
}
);
} else { // moodify an existing category entry
console.info(`Requesting MODIFY on category: ${picked} -> ${edited}`);
result = this.standingData.modifyCategory(picked, edited).subscribe(
res => {
if (res.categories && res.categories.length) {
this.lists = res;
console.log(`this.lists set to: ${JSON.stringify(this.lists)}`);
} else {
this.setErrorMsg(`Could not change category: ${picked} to ${edited}`);
console.log(this.error);
return;
}
},
error => {
this.setErrorMsg(`Error changing category: ${picked} to ${edited}`);
console.log(this.error);
return;
}
);
}
if (!result) {
this.setErrorMsg("Error updating category!");
return;
}
this.pickedCategory = "";
this.editedCategory = "";
} // editCategory()
private removeCategory(): void {
let picked: string = this.pickedCategory;
let edited: string = this.editedCategory;
if (!picked || edited)
return;
console.info(`Requesting REMOVE on category: ${picked}`);
this.standingData.removeCategory(picked).subscribe(
res => {
if (res.categories && res.categories.length) {
this.lists = res;
console.log(`this.lists set to: ${JSON.stringify(this.lists)}`);
} else {
this.setErrorMsg(`Could not remove category: ${JSON.stringify(res)}`);
console.log(this.error);
return;
}
},
error => {
this.setErrorMsg(`Error removing category: ${edited}`);
console.log(this.error);
return;
}
);
this.pickedCategory = "";
this.editedCategory = "";
} // removeCategory()
// private helpers
private setErrorMsg(errMsg?: string): void {
if (errMsg) {
this.error = errMsg.trim();
setTimeout(() => this.error = "", 5000 /* ms */);
}
else this.error = "";
} // setErrorMsg()
private gotoRegistration(): void {
this.router.navigate(["/register"]);
} // gotoRegistration()
private gotoProfile(): void {
if (this.currentUser && this.currentUser.id.length) {
this.router.navigate([ "/users", this.currentUser.id ]).then(
result => {
if (result) { // result === true
console.info("Redirect to user profile succeeded!");
} else { // result === false
console.error("Redirect to user profile failed!");
}
}, error => {
console.error(`Error redirecting to user's profile: ${error.toString()}`);
}
);
}
} // gotoProfile()
ngOnInit() {
this.authService.logout();
this.currentUser = this.authService.currentUser;
this.currentUserRole = "";
this.loggedIn = false;
this.loading = false;
this.active = true;
this.setErrorMsg();
} // ngOnInit()
} // class AppLayout
|
projectbox99/mean
|
dev/app/ads/ads-list.component.ts
|
"use strict";
import { Component, OnInit, OnDestroy } from "@angular/core";
import { Router } from "@angular/router";
import { Subscription } from "rxjs/Subscription";
import { User } from "../Services/users.service";
import { Ad, AdsService } from "../Services/ads.service";
import { AuthService } from "../Services/authentication.service";
@Component ({
selector: "ads-list",
templateUrl: "ads-list.component.html",
styleUrls: [ "ads-list.component.css" ],
providers: [ AdsService ]
})
export class AdsComponent {
private currentUser: User;
private usrRole: string;
private ads: Ad[];
private sub: Subscription;
private loading: boolean;
private currentList: string;
constructor(private router: Router,
private adsService: AdsService,
private authService: AuthService) {
this.currentUser = this.authService.currentUser;
this.usrRole = this.currentUser.role;
}
public loadAds(myList: string): void {
if (myList === "regular" || myList === "supervisor") {
let list_target: string = myList === "regular" ? this.currentUser.id : "__unapproved__";
this.sub = this.adsService.getMyAds(list_target).subscribe(
ads => {
this.ads = ads;
},
error => {
console.log(`Error: ${JSON.stringify(error)}`);
}
);
} else if (myList === "admin") {
console.log('loading admin ads...');
this.sub = this.adsService.getAds().subscribe(
ads => {
this.ads = ads;
// console.log(`Admins ads: ${JSON.stringify(this.ads)}`);
},
error => {
console.log(`Error: ${JSON.stringify(error)}`);
}
);
}
} // loadAds()
public refresh(myList: string = ""): void {
this.loading = true;
if (myList) {
this.currentList = myList;
this.loadAds(myList);
} else {
this.loadAds("regular");
}
this.loading = false;
} // refresh()
public delAd(id: string): void {
this.loading = true;
if (id) {
this.adsService.deleteAd(id).subscribe(
result => {
if (result == true) {
console.info(`delAd(${id}) returned SUCCESS!`);
this.refresh(this.currentList);
} else {
console.error(`delAd(${id}) returned ${result}`);
}
},
error => {
console.log(`delAd(${id}) returned an Error: ${error.toString()}`);
},
() => this.loading = false
);
}
} // delUser()
public editAd(id: string): void {
this.loading = true;
if (id) {
this.router.navigate([ "/ads", id ]).then(
result => {
if (result) { // result === true
console.info("Redirect to ad document succeeded!");
} else { // result === false
console.error("Redirect to ad document failed!");
}
}, error => {
console.error(`Error redirecting to ad document: ${error.toString()}`);
}
);
}
this.loading = false;
} // editUser()
public previewAd(id: string): void {
if (id) {
this.router.navigate([ "/ads/preview", id ]);
}
} // previewAd()
ngOnInit() {
this.loading = true;
this.refresh(this.usrRole);
this.loading = false;
}
ngOnDestroy() {
if (this.sub)
this.sub.unsubscribe();
}
} // class UsersComponent
|
projectbox99/mean
|
dev/app/Services/about.service.ts
|
<gh_stars>0
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { Injectable } from "@angular/core";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
@Injectable()
export class AboutService {
constructor(private http: Http) { }
private url: string =
window.location.protocol + "//" +
window.location.hostname +
((window.location.port === "80")
? ("")
: (":" + window.location.port)) + "/api/about";
public results: any;
public aboutInfo(): Observable<any> {
return this.http.get(`${this.url}`)
.map(
res => {
let data: any = this.extractData(res);
return data;
})
.catch(this.handleError);
}
// private helpers
private extractData(res: Response) {
let body = res.json();
return body.data || {};
} // extractData()
private handleError (error: any): Observable<string> {
let errMsg = (error.message)
? error.message
: (error.status)
? `${error.status} - ${error.statusText}`
: "Server Error";
console.error(errMsg);
return Observable.throw(errMsg);
} // handleError()
}
|
projectbox99/mean
|
dev/app/about/about.component.ts
|
<gh_stars>0
import { Component } from "@angular/core";
import { AboutService } from "../Services/about.service";
@Component ({
selector: "view",
templateUrl: "./about.component.html"
})
export class AboutComponent {
private info: any;
private items: string[];
public JSON;
constructor(private aboutService: AboutService){
this.JSON=JSON;
this.info = {};
this.items = <string[]>[];
this.getInfo();
}
private getInfo(): void {
this.aboutService.aboutInfo().subscribe(
res => {
this.info = res;
for (let inf in this.info) {
this.items.push(inf);
}
},
err => {
console.log(err);
}
)
}
}
|
projectbox99/mean
|
dev/app/app.routes.ts
|
"use strict";
import { Routes, RouterModule } from "@angular/router";
import { AuthGuard } from "./Services/auth.guard";
// components
import { HomeComponent } from "./home/home.component";
import { AboutComponent } from "./about/about.component";
import { UserRegistrationComponent } from "./register/register.component";
import { UsersComponent } from "./users/users.component";
import { PageNotFoundComponent } from "./404.component";
const routes: Routes = [
{ path: "", data: { title: "Home" }, component: HomeComponent },
{ path: "about", data: { title: "About the App" }, component: AboutComponent, canActivate: [AuthGuard] },
{ path: "register", data: { title: "Register User" }, component: UserRegistrationComponent },
{ path: "users", data: { title: "Users" }, component: UsersComponent },
{ path: "users/:id", data: { title: "User data" }, component: UserRegistrationComponent },
{ path: "**", component: PageNotFoundComponent }
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(routes);
|
projectbox99/mean
|
dev/app/app.layout.spec.ts
|
<gh_stars>0
"use strict";
import { addProviders, inject } from "@angular/core/testing";
import { AppLayout } from "./app.layout";
describe("App", () => {
beforeEach(() => {
addProviders([
AppLayout
]);
});
it ("should work", inject([AppLayout], (app: AppLayout) => {
// Add real test here
expect(2).toBe(2);
}));
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.