repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
jelly/patternfly-react | packages/react-table/src/components/Table/examples/LegacyTableSelectableRadio.tsx | <reponame>jelly/patternfly-react<gh_stars>100-1000
import React from 'react';
import { Table, TableHeader, TableBody, headerCol, TableProps } from '@patternfly/react-table';
interface Repository {
name: string;
branches: string;
prs: string;
workspaces: string;
lastCommit: string;
}
export const LegacyTableSelectableRadio: React.FunctionComponent = () => {
// In real usage, this data would come from some external source like an API via props.
const repositories: Repository[] = [
{ name: 'one', branches: 'two', prs: 'a', workspaces: 'four', lastCommit: 'five' },
{ name: 'a', branches: 'two', prs: 'k', workspaces: 'four', lastCommit: 'five' },
{ name: 'p', branches: 'two', prs: 'b', workspaces: 'four', lastCommit: 'five' }
];
const isRepoSelectable = (repo: Repository) => repo.name !== 'a'; // Arbitrary logic for this example
// In this example, selected rows are tracked by the repo names from each row. This could be any unique identifier.
// This is to prevent state from being based on row order index in case we later add sorting.
const [selectedRepoName, setSelectedRepoName] = React.useState<string | null>(null);
const columns: TableProps['cells'] = [
{ title: 'Repositories', cellTransforms: [headerCol()] },
'Branches',
{ title: 'Pull requests' },
'Workspaces',
'Last commit'
];
const rows: TableProps['rows'] = repositories.map(repo => ({
cells: [repo.name, repo.branches, repo.prs, repo.workspaces, repo.lastCommit],
selected: selectedRepoName === repo.name,
disableSelection: !isRepoSelectable(repo)
}));
return (
<Table
onSelect={(_event, _isSelecting, rowIndex) => {
const repo = repositories[rowIndex];
setSelectedRepoName(repo.name);
}}
selectVariant="radio"
aria-label="Selectable Table with Radio Buttons"
cells={columns}
rows={rows}
>
<TableHeader />
<TableBody />
</Table>
);
};
|
jelly/patternfly-react | packages/react-topology/src/components/factories/RegisterLayoutFactory.tsx | <reponame>jelly/patternfly-react<filename>packages/react-topology/src/components/factories/RegisterLayoutFactory.tsx
import * as React from 'react';
import useLayoutFactory from '../../hooks/useLayoutFactory';
import { LayoutFactory } from '../../types';
interface Props {
factory: LayoutFactory;
}
const RegisterLayoutFactory: React.FunctionComponent<Props> = ({ factory }) => {
useLayoutFactory(factory);
return null;
};
export default RegisterLayoutFactory;
|
jelly/patternfly-react | packages/react-core/src/components/Dropdown/__tests__/DropdownGroup.test.tsx | <reponame>jelly/patternfly-react<filename>packages/react-core/src/components/Dropdown/__tests__/DropdownGroup.test.tsx
import * as React from 'react';
import { render } from '@testing-library/react';
import { DropdownGroup } from '../DropdownGroup';
describe('dropdown groups', () => {
test('basic render', () => {
const { asFragment } = render(<DropdownGroup label="Group 1">Something</DropdownGroup>);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/DescriptionList/examples/DescriptionListDefaultInlineGrid.tsx | import React from 'react';
import {
Button,
DescriptionList,
DescriptionListTerm,
DescriptionListGroup,
DescriptionListDescription
} from '@patternfly/react-core';
import PlusCircleIcon from '@patternfly/react-icons/dist/esm/icons/plus-circle-icon';
export const DescriptionListDefaultInlineGrid: React.FunctionComponent = () => (
<DescriptionList columnModifier={{ default: '3Col' }} isInlineGrid>
<DescriptionListGroup>
<DescriptionListTerm>Name</DescriptionListTerm>
<DescriptionListDescription>Example</DescriptionListDescription>
</DescriptionListGroup>
<DescriptionListGroup>
<DescriptionListTerm>Namespace</DescriptionListTerm>
<DescriptionListDescription>
<a href="#">mary-test</a>
</DescriptionListDescription>
</DescriptionListGroup>
<DescriptionListGroup>
<DescriptionListTerm>Labels</DescriptionListTerm>
<DescriptionListDescription>example</DescriptionListDescription>
</DescriptionListGroup>
<DescriptionListGroup>
<DescriptionListTerm>Pod selector</DescriptionListTerm>
<DescriptionListDescription>
<Button variant="link" isInline icon={<PlusCircleIcon />}>
app=MyApp
</Button>
</DescriptionListDescription>
</DescriptionListGroup>
<DescriptionListGroup>
<DescriptionListTerm>Annotation</DescriptionListTerm>
<DescriptionListDescription>2 Annotations</DescriptionListDescription>
</DescriptionListGroup>
</DescriptionList>
);
|
jelly/patternfly-react | packages/react-topology/src/components/edges/terminals/terminalUtils.ts | import { Point } from '../../../geom';
export const getConnectorStartPoint = (startPoint: Point, endPoint: Point, size: number): [number, number] => {
const length = Math.sqrt((endPoint.x - startPoint.x) ** 2 + (endPoint.y - startPoint.y) ** 2);
if (!length) {
return [0, 0];
}
const ratio = (length - size) / length;
return [startPoint.x + (endPoint.x - startPoint.x) * ratio, startPoint.y + (endPoint.y - startPoint.y) * ratio];
};
export const getConnectorRotationAngle = (startPoint: Point, endPoint: Point): number =>
180 - (Math.atan2(endPoint.y - startPoint.y, startPoint.x - endPoint.x) * 180) / Math.PI;
export const getConnectorBoundingBox = (startPoint: Point, endPoint: Point, size: number): [number, number][] => {
const length = Math.sqrt((endPoint.x - startPoint.x) ** 2 + (endPoint.y - startPoint.y) ** 2);
if (!length) {
return null;
}
const padding = Math.max(size, 8);
const deltaY = padding / 2;
return [
[0, -deltaY],
[padding, -deltaY],
[padding, deltaY],
[0, deltaY]
];
};
|
jelly/patternfly-react | packages/react-table/src/components/Table/base/columns-are-equal.ts | /**
* columns-are-equal.ts
*
* Forked from reactabular-table version 8.14.0
* https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src
*/
import isEqualWith from 'lodash/isEqualWith';
import { ColumnsType } from './types';
/**
* @param {ColumnsType} oldColumns - previous columns
* @param {ColumnsType} newColumns - new columns
*/
export function columnsAreEqual(oldColumns: ColumnsType, newColumns: ColumnsType) {
return isEqualWith(oldColumns, newColumns, (a, b) => {
if (typeof a === 'function' && typeof b === 'function') {
return a === b;
}
return undefined;
});
}
|
jelly/patternfly-react | packages/react-core/src/components/DragDrop/Droppable.tsx | <gh_stars>100-1000
import * as React from 'react';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/DragDrop/drag-drop';
import { DroppableContext } from './DroppableContext';
interface DroppableProps extends React.HTMLProps<HTMLDivElement> {
/** Content rendered inside DragDrop */
children?: React.ReactNode;
/** Class to add to outer div */
className?: string;
/** Name of zone that items can be dragged between. Should specify if there is more than one Droppable on the page. */
zone?: string;
/** Id to be passed back on drop events */
droppableId?: string;
/** Don't wrap the component in a div. Requires passing a single child. */
hasNoWrapper?: boolean;
}
export const Droppable: React.FunctionComponent<DroppableProps> = ({
className,
children,
zone = 'defaultZone',
droppableId = 'defaultId',
hasNoWrapper = false,
...props
}: DroppableProps) => {
const childProps = {
'data-pf-droppable': zone,
'data-pf-droppableid': droppableId,
// if has no wrapper is set, don't overwrite children className with the className prop
className:
hasNoWrapper && React.Children.count(children) === 1
? css(styles.droppable, className, (children as React.ReactElement).props.className)
: css(styles.droppable, className),
...props
};
return (
<DroppableContext.Provider value={{ zone, droppableId }}>
{hasNoWrapper ? (
React.cloneElement(children as React.ReactElement, childProps)
) : (
<div {...childProps}>{children}</div>
)}
</DroppableContext.Provider>
);
};
Droppable.displayName = 'Droppable';
|
jelly/patternfly-react | packages/react-integration/cypress/integration/tabexpandabledemo.spec.ts | <filename>packages/react-integration/cypress/integration/tabexpandabledemo.spec.ts
describe('Tab Demo Test', () => {
it('Navigate to demo section', () => {
cy.visit('http://localhost:3000/');
cy.get('#tab-expandable-demo-nav-item-link').click();
cy.url().should('eq', 'http://localhost:3000/tab-expandable-demo-nav-link');
});
it('Verify controlled expandable vertical tabs ', () => {
cy.get('#expandable-controlled').should('exist');
cy.get('#expandable-controlled.pf-m-expanded').should('not.exist');
// tabs list should not exist
cy.get('#expandable-controlled').within(() => {
cy.get('.pf-c-tabs__list').should('not.be.visible');
});
cy.get('#expandable-controlled')
.find('.pf-c-tabs__toggle-icon')
.click();
cy.get('#expandable-controlled.pf-m-expanded').should('exist');
// tabs list should exist
cy.get('#expandable-controlled').within(() => {
cy.get('.pf-c-tabs__list').should('be.visible');
});
cy.get('#expandable-controlled')
.find('.pf-c-tabs__toggle-icon')
.click();
cy.get('#expandable-controlled.pf-m-expanded').should('not.exist');
// tabs list should not exist
cy.get('#expandable-controlled').within(() => {
cy.get('.pf-c-tabs__list').should('not.be.visible');
});
});
it('Verify uncontrolled expandable vertical tabs ', () => {
cy.get('#expandable-uncontrolled').should('exist');
cy.get('#expandable-uncontrolled.pf-m-expanded').should('not.exist');
// tabs list should not exist
cy.get('#expandable-uncontrolled').within(() => {
cy.get('.pf-c-tabs__list').should('not.be.visible');
});
cy.get('#expandable-uncontrolled')
.find('.pf-c-tabs__toggle-icon')
.click();
cy.get('#expandable-uncontrolled.pf-m-expanded').should('exist');
// tabs list should exist
cy.get('#expandable-uncontrolled').within(() => {
cy.get('.pf-c-tabs__list').should('be.visible');
});
cy.get('#expandable-uncontrolled')
.find('.pf-c-tabs__toggle-icon')
.click();
cy.get('#expandable-uncontrolled.pf-m-expanded').should('not.exist');
// tabs list should not exist
cy.get('#expandable-uncontrolled').within(() => {
cy.get('.pf-c-tabs__list').should('not.be.visible');
});
});
it('Verify expandable breakpoints are applied ', () => {
// expandable
cy.get('#expandable-breakpoints1.pf-m-expandable-on-sm').should('exist');
cy.get('#expandable-breakpoints1.pf-m-expandable-on-md').should('exist');
cy.get('#expandable-breakpoints1.pf-m-expandable-on-lg').should('exist');
cy.get('#expandable-breakpoints1.pf-m-expandable-on-xl').should('exist');
cy.get('#expandable-breakpoints1.pf-m-expandable-on-2xl').should('exist');
// non expandable
cy.get('#expandable-breakpoints2.pf-m-expandable').should('exist');
cy.get('#expandable-breakpoints2.pf-m-non-expandable-on-sm').should('exist');
cy.get('#expandable-breakpoints2.pf-m-non-expandable-on-md').should('exist');
cy.get('#expandable-breakpoints3.pf-m-expandable-on-xl').should('exist');
cy.get('#expandable-breakpoints1.pf-m-expandable-on-2xl').should('exist');
cy.get('#expandable-breakpoints3.pf-m-non-expandable').should('exist');
});
});
|
jelly/patternfly-react | packages/react-table/src/components/Table/examples/LegacyTableSortable.tsx | import React from 'react';
import {
TableProps,
sortable,
info,
cellWidth,
wrappable,
Table,
TableBody,
TableHeader
} from '@patternfly/react-table';
interface Repository {
name: string;
branches: string;
prs: string;
workspaces: string;
lastCommit: string;
}
export const LegacyTableSortable: React.FunctionComponent = () => {
// In real usage, this data would come from some external source like an API via props.
const repositories: Repository[] = [
{ name: 'one', branches: 'two', prs: 'a', workspaces: 'four', lastCommit: 'five' },
{ name: 'a', branches: 'two', prs: 'k', workspaces: 'four', lastCommit: 'five' },
{ name: 'p', branches: 'two', prs: 'b', workspaces: 'four', lastCommit: 'five' }
];
// Index of the currently sorted column
// Note: if you intend to make columns reorderable, you may instead want to use a non-numeric key
// as the identifier of the sorted column. See the "Compound expandable" example.
const [activeSortIndex, setActiveSortIndex] = React.useState<number | null>(null);
// Sort direction of the currently sorted column
const [activeSortDirection, setActiveSortDirection] = React.useState<'asc' | 'desc' | null>(null);
// Since OnSort specifies sorted columns by index, we need sortable values for our object by column index.
// This example is trivial since our data objects just contain strings, but if the data was more complex
// this would be a place to return simplified string or number versions of each column to sort by.
const getSortableRowValues = (repo: Repository): (string | number)[] => {
const { name, branches, prs, workspaces, lastCommit } = repo;
return [name, branches, prs, workspaces, lastCommit];
};
// Note that we perform the sort as part of the component's render logic and not in onSort.
// We shouldn't store the list of data in state because we don't want to have to sync that with props.
let sortedRepositories = repositories;
if (activeSortIndex !== null) {
sortedRepositories = repositories.sort((a, b) => {
const aValue = getSortableRowValues(a)[activeSortIndex];
const bValue = getSortableRowValues(b)[activeSortIndex];
if (typeof aValue === 'number') {
// Numeric sort
if (activeSortDirection === 'asc') {
return (aValue as number) - (bValue as number);
}
return (bValue as number) - (aValue as number);
} else {
// String sort
if (activeSortDirection === 'asc') {
return (aValue as string).localeCompare(bValue as string);
}
return (bValue as string).localeCompare(aValue as string);
}
});
}
const columns: TableProps['cells'] = [
{ title: 'Repositories', transforms: [sortable] },
{
title: 'Branches',
transforms: [
info({
tooltip: 'More information about branches'
}),
sortable
]
},
{ title: 'Pull requests', transforms: [sortable] },
{
title: 'Workspaces - Also this long header will wrap since we have applied the wrappable transform',
transforms: [sortable, wrappable, cellWidth(20)]
},
{
title: 'Last commit',
transforms: [
info({
tooltip: 'More information about commits'
})
]
}
];
const rows: TableProps['rows'] = sortedRepositories.map(repo => [
repo.name,
repo.branches,
repo.prs,
repo.workspaces,
repo.lastCommit
]);
return (
<Table
aria-label="Sortable Table"
sortBy={{
index: activeSortIndex,
direction: activeSortDirection,
defaultDirection: 'asc' // starting sort direction when first sorting a column. Defaults to 'asc'
}}
onSort={(_event, index, direction) => {
setActiveSortIndex(index);
setActiveSortDirection(direction);
}}
cells={columns}
rows={rows}
>
<TableHeader />
<TableBody />
</Table>
);
};
|
jelly/patternfly-react | packages/react-table/src/components/Table/HeaderCell.tsx | import * as React from 'react';
import { Th } from '../TableComposable/Th';
export interface HeaderCellProps {
'data-label'?: string;
className?: string;
component?: React.ReactNode;
isVisible?: boolean;
scope?: string;
textCenter?: boolean;
dataLabel?: string;
tooltip?: string;
onMouseEnter?: (event: any) => void;
children: React.ReactNode;
}
export const HeaderCell: React.FunctionComponent<HeaderCellProps> = ({
className = '',
component = 'th',
scope = '',
textCenter = false,
tooltip = '',
onMouseEnter = () => {},
children,
/* eslint-disable @typescript-eslint/no-unused-vars */
isVisible,
dataLabel = '',
/* eslint-enable @typescript-eslint/no-unused-vars */
...props
}: HeaderCellProps) => (
<Th
{...props}
scope={scope}
tooltip={tooltip}
onMouseEnter={onMouseEnter}
textCenter={textCenter}
component={component}
className={className}
>
{children}
</Th>
);
HeaderCell.displayName = 'HeaderCell';
|
KelvinWallet/kelvinjs-trx | src/index.spec.ts | import test from 'ava';
import { trxCurrencyUtil } from '.';
test('isValidNormAmount()', t => {
const f = trxCurrencyUtil.isValidNormAmount;
t.true(f('0'));
t.true(f('100'));
t.true(f('100.'));
t.true(f('1.000000'));
t.true(f('1.000001'));
t.true(f('100000000000.000000'));
t.false(f('.'));
t.false(f('.0'));
t.false(f('001'));
t.false(f('-1'));
t.false(f(' 123'));
t.false(f('123\n'));
t.false(f('1.1234567'));
t.false(f('100000000000.000001'));
});
test('convertNormAmountToBaseAmount()', t => {
const f = trxCurrencyUtil.convertNormAmountToBaseAmount;
t.is(f('0'), '0');
t.is(f('100'), '100000000');
t.is(f('100.1234'), '100123400');
t.is(f('100.123456'), '100123456');
t.throws(() => f('100.1234567'), Error);
t.throws(() => f('-100.1234'), Error);
});
test('convertBaseAmountToNormAmount()', t => {
const f = trxCurrencyUtil.convertBaseAmountToNormAmount;
t.is(f('0'), '0');
t.is(f('100'), '0.0001');
t.is(f('1000000'), '1');
t.is(f('10000000'), '10');
t.throws(() => f('10000000.1'), Error);
t.throws(() => f('-10'), Error);
});
test('isValidAddr()', t => {
const f = trxCurrencyUtil.isValidAddr;
t.true(f('mainnet', 'TLrMD9WqMUFQbJRMTfdHiZ4j5CHXfnUyyA'));
t.false(f('mainnet', '410000000000000000000000000000000000000000'));
t.false(f('mainnet', ' TLrMD9WqMUFQbJRMTfdHiZ4j5CHXfnUyyA'));
});
test('encodePubkeyToAddr()', t => {
const f = trxCurrencyUtil.encodePubkeyToAddr;
t.is(
f(
'mainnet',
'<KEY>'
),
'TQUauGLDR4tcvu8U71WJdnE5dy2tsLSgXb'
);
});
test('fee options', async t => {
t.throws(() => trxCurrencyUtil.isValidFeeOption('mainnet', ''), Error);
t.throws(() => trxCurrencyUtil.getFeeOptionUnit(), Error);
await t.throwsAsync(
async () => await trxCurrencyUtil.getFeeOptions('mainnet'),
Error
);
});
test('prepareCommandSignTx()', async t => {
const f = trxCurrencyUtil.prepareCommandSignTx;
await t.throwsAsync(
async () => {
const req = {
network: 'testnet',
accountIndex: 0,
toAddr: 'TQUauGLDR4tcvu8U71WJdnE5dy2tsLSgXb',
fromPubkey:
'<KEY>',
amount: '1.23'
};
await f(req);
},
{
instanceOf: Error,
message: 'Should not send to self: TQUauGLDR4tcvu8U71WJdnE5dy2tsLSgXb'
}
);
});
|
KelvinWallet/kelvinjs-trx | src/index.ts | <gh_stars>0
import TronGrid from 'trongrid';
import TronWeb from 'tronweb';
import { Tron, TRON_CMDID, TronTx } from 'kelvinjs-protob';
import crypto from 'crypto';
import secp256k1 from 'secp256k1';
import bn from 'bignumber.js';
import { Tron_Raw } from 'kelvinjs-protob/dist/tron-tx_pb';
import { ICurrencyUtil, ITransaction } from './ICurrencyUtil';
interface ITron {
web: any;
grid: any;
}
const mainnetProvider = new TronWeb.providers.HttpProvider(
'https://api.trongrid.io/',
5000 // timeout
);
const testnetProvider = new TronWeb.providers.HttpProvider(
'https://api.shasta.trongrid.io/',
5000 // timeout
);
const mainnet: ITron = {
web: new TronWeb({ fullHost: mainnetProvider }),
grid: undefined
};
const testnet: ITron = {
web: new TronWeb({ fullHost: testnetProvider }),
grid: undefined
};
mainnet.grid = new TronGrid(mainnet.web);
testnet.grid = new TronGrid(testnet.web);
function isNonNegativeInteger(x: any): x is number {
return typeof x === 'number' && Number.isSafeInteger(x) && x >= 0;
}
// Also acts as a guard (throws exception)
function getNetwork(network: string) {
if (network === 'mainnet') {
return mainnet;
} else if (network === 'testnet') {
return testnet;
}
throw new Error(`Invalid network ${network}`);
}
export const trxCurrencyUtil: ICurrencyUtil = {
getSupportedNetworks() {
return ['mainnet', 'testnet'];
},
getFeeOptionUnit() {
throw new Error('No fee options available');
},
isValidFeeOption(network, feeOpt) {
throw new Error('No fee options available');
},
isValidAddr(network, addr) {
getNetwork(network);
// because in isAddress(), '410000000000000000000000000000000000000000' is a valid address
return addr[0] !== '4' && TronWeb.isAddress(addr);
},
// <= 10^11 TRX
isValidNormAmount(amount) {
if (!/^(0|[1-9][0-9]*)(\.[0-9]*)?$/.test(amount)) {
return false;
}
const v = new bn(amount);
return (
!v.isNegative() &&
v.isLessThanOrEqualTo('100000000000') &&
v.decimalPlaces() <= 6
);
},
convertNormAmountToBaseAmount(amount) {
if (!trxCurrencyUtil.isValidNormAmount(amount)) {
throw Error(`not a valid norm amount: ${amount}`);
}
return new bn(amount).multipliedBy(new bn('1000000')).toString();
},
convertBaseAmountToNormAmount(amount) {
const v = new bn(amount);
if (
!(
v.isInteger() &&
!v.isNegative() &&
v.isLessThanOrEqualTo('100000000000000000')
)
) {
throw Error(`not a valid base amount: ${amount}`);
}
return new bn(amount).dividedBy(new bn('1000000')).toString();
},
getUrlForAddr(network, addr) {
getNetwork(network);
if (!trxCurrencyUtil.isValidAddr(network, addr)) {
throw new Error(`Invalid address ${addr}`);
}
if (network === 'mainnet') {
return `https://tronscan.org/#/address/${addr}`;
} else {
return `https://shasta.tronscan.org/#/address/${addr}`;
}
},
getUrlForTx(network, txid) {
getNetwork(network);
if (!/^[0-9a-f]{64}$/.test(txid)) {
throw new Error(`Invalid txid ${txid}`);
}
if (network === 'mainnet') {
return `https://tronscan.org/#/transaction/${txid}`;
} else {
return `https://shasta.tronscan.org/#/transaction/${txid}`;
}
},
encodePubkeyToAddr(network, pubkey) {
getNetwork(network);
if (!/^04[0-9a-f]{128}$/.test(pubkey)) {
throw Error('invalid input');
}
return TronWeb.utils.crypto.getBase58CheckAddress(
TronWeb.utils.crypto.computeAddress(Buffer.from(pubkey, 'hex').slice(1))
);
},
async getBalance(network, addr) {
const n = getNetwork(network);
if (!trxCurrencyUtil.isValidAddr(network, addr)) {
throw new Error(`Invalid address ${addr}`);
}
try {
const balance = await n.web.trx.getBalance(addr);
return trxCurrencyUtil.convertBaseAmountToNormAmount(balance.toString());
} catch (err) {
if ('code' in err && err.code === 'ECONNABORTED') {
throw new Error(`A timeout happend on url ${err.config.url}`);
}
throw new Error('unknown error');
}
},
getHistorySchema() {
return [
{ key: 'hash', label: 'Hash', format: 'hash' },
{ key: 'date', label: 'Date', format: 'date' },
// { key: 'from', label: 'From', format: 'address' },
// { key: 'to', label: 'To', format: 'address' },
{ key: 'amount', label: 'Amount', format: 'value' }
];
},
// Possible enhancements:
// 1. sort, 2. don't aggregate history (so that we can show to/from addrs)
// For tron, confirm/fail is almost instant, so we ignore the pending case
async getRecentHistory(network, addr) {
const n = getNetwork(network);
if (!trxCurrencyUtil.isValidAddr(network, addr)) {
throw new Error(`Invalid address ${addr}`);
}
const myAddrHex = TronWeb.address.toHex(addr);
// may fail or not return 200
let data;
try {
const { data: dataField } = await n.grid.account.getTransactions(addr);
data = dataField;
} catch (e) {
throw new Error(e);
}
return data.map(d => {
const {
txID,
raw_data: { contract }
} = d;
const outAmount = contract
.filter(
c =>
c.type === 'TransferContract' &&
c.parameter.value.owner_address === myAddrHex
)
.map(c => c.parameter.value.amount)
.reduce((acc, x) => acc + x, 0);
const inAmount = contract
.filter(
c =>
c.type === 'TransferContract' &&
c.parameter.value.to_address === myAddrHex
)
.map(c => c.parameter.value.amount)
.reduce((acc, x) => acc + x, 0);
const amount = inAmount - outAmount;
let amountNorm: string;
if (amount >= 0) {
amountNorm = trxCurrencyUtil.convertBaseAmountToNormAmount('' + amount);
} else {
amountNorm =
'-' + trxCurrencyUtil.convertBaseAmountToNormAmount('' + -amount);
}
return {
hash: { value: txID, link: trxCurrencyUtil.getUrlForTx(network, txID) },
date: { value: new Date(d.block_timestamp).toISOString() },
amount: {
value: amountNorm
}
};
});
},
async getFeeOptions(network) {
throw new Error('No fee options available');
},
async prepareCommandSignTx(req) {
// ---- Check ----
const n = getNetwork(req.network);
if (
!(
isNonNegativeInteger(req.accountIndex) && req.accountIndex <= 0x7fffffff
)
) {
throw Error(`invalid accountIndex: ${req.accountIndex}`);
}
if (!trxCurrencyUtil.isValidAddr(req.network, req.toAddr)) {
throw new Error(`Invalid to address ${req.toAddr}`);
}
if (!trxCurrencyUtil.isValidNormAmount(req.amount)) {
throw new Error(`Invalid norm amount ${req.amount}`);
}
const fromAddr = trxCurrencyUtil.encodePubkeyToAddr(
req.network,
req.fromPubkey
);
if (fromAddr === req.toAddr) {
throw new Error(`Should not send to self: ${fromAddr}`);
}
if (typeof req.feeOpt !== 'undefined') {
throw new Error('No fee options available');
}
// ---- Look up ----
let tx;
try {
tx = await n.web.transactionBuilder.sendTrx(
req.toAddr,
trxCurrencyUtil.convertNormAmountToBaseAmount(req.amount),
fromAddr
);
} catch (e) {
throw new Error(e);
}
// ---- Build ----
const msg = new Tron.TrxCommand.TrxSignTx();
msg.setAmount(tx.raw_data.contract[0].parameter.value.amount);
msg.setPathList([req.accountIndex + 0x80000000, 0, 0]);
msg.setRefBlockBytes(Buffer.from(tx.raw_data.ref_block_bytes, 'hex'));
msg.setRefBlockHash(Buffer.from(tx.raw_data.ref_block_hash, 'hex'));
// Change expiration (default ~ 60 secs, not enough for hardware)
msg.setExpiration(tx.raw_data.timestamp + 60 * 60 * 1000); // 60 mins
msg.setTimestamp(tx.raw_data.timestamp);
msg.setTo(
Buffer.from(
tx.raw_data.contract[0].parameter.value.to_address,
'hex'
).slice(1)
);
const cmd = new Tron.TrxCommand();
cmd.setSignTx(msg);
const metadata: ITransaction = {
from: { value: fromAddr },
to: { value: req.toAddr },
amount: { value: req.amount }
};
return [
{
commandId: TRON_CMDID,
payload: Buffer.from(cmd.serializeBinary())
},
metadata
];
},
getPreparedTxSchema() {
return [
{ key: 'from', label: 'From', format: 'address' },
{ key: 'amount', label: 'Amount', format: 'value' },
{ key: 'to', label: 'To', format: 'address' }
];
},
buildSignedTx(req, preparedTx, walletRsp) {
// TODO: We assume req and preparedTx are correct
const m = Tron.TrxCommand.deserializeBinary(preparedTx.payload);
const msg = m.getSignTx();
if (!/^04[0-9a-f]{128}$/.test(req.fromPubkey)) {
throw Error('invalid input');
}
const tx = {
visible: false,
txID: '',
raw_data: {
contract: [
{
parameter: {
value: {
amount: msg.getAmount(),
owner_address: Buffer.from(
TronWeb.utils.crypto.computeAddress(
Buffer.from(req.fromPubkey, 'hex').slice(1)
)
).toString('hex'),
to_address: '41' + Buffer.from(msg.getTo_asU8()).toString('hex')
},
type_url: 'type.googleapis.com/protocol.TransferContract'
},
type: 'TransferContract'
}
],
ref_block_bytes: Buffer.from(msg.getRefBlockBytes_asU8()).toString(
'hex'
),
ref_block_hash: Buffer.from(msg.getRefBlockHash_asU8()).toString('hex'),
expiration: msg.getExpiration(),
timestamp: msg.getTimestamp()
},
raw_data_hex: '',
signature: ['']
};
const transfer = new TronTx.Tron_Raw.TransferContract();
transfer.setAmount(msg.getAmount());
transfer.setToAddress(
Buffer.concat([Buffer.from('41', 'hex'), Buffer.from(msg.getTo_asU8())])
);
transfer.setOwnerAddress(
Buffer.from(
TronWeb.utils.crypto.computeAddress(
Buffer.from(req.fromPubkey, 'hex').slice(1)
)
)
);
const anyContract = new TronTx.Tron_Raw.Any();
anyContract.setTypeUrl('type.googleapis.com/protocol.TransferContract');
anyContract.setValue(transfer.serializeBinary());
const contract = new TronTx.Tron_Raw.Contract();
contract.setType(Tron_Raw.Contract.ContractType.TRANSFERCONTRACT);
contract.setParameter(anyContract);
const raw = new TronTx.Tron_Raw();
raw.addContract(contract);
raw.setRefBlockBytes(msg.getRefBlockBytes_asU8());
raw.setRefBlockHash(msg.getRefBlockHash_asU8());
raw.setTimestamp(msg.getTimestamp());
raw.setExpiration(msg.getExpiration());
const rawData = Buffer.from(raw.serializeBinary());
tx.raw_data_hex = rawData.toString('hex');
tx.txID = crypto
.createHash('sha256')
.update(rawData)
.digest('hex');
// Put signature
// TODO: deseiralize may err due to wrong response from wallet
const wrsp = Tron.TrxResponse.deserializeBinary(walletRsp.payload);
const wsig = wrsp.getSig();
if (typeof wsig === 'undefined') {
const msgCase = wrsp.getMsgCase();
if (msgCase === Tron.TrxResponse.MsgCase.ERROR) {
throw Error(
`unexpected walletRsp with Armadillo errorCode ${wrsp.getError()}`
);
}
throw Error(
`unexpected walletRsp payload: ${walletRsp.payload.toString('hex')}`
);
}
const sig = Buffer.from(wsig.getSig_asU8());
const recoveredPk = secp256k1.recover(Buffer.from(tx.txID, 'hex'), sig, 0);
const recoveredPkUncompressed = secp256k1.publicKeyConvert(
recoveredPk,
false
);
if (recoveredPkUncompressed.equals(Buffer.from(req.fromPubkey, 'hex'))) {
tx.signature = [`${sig.toString('hex')}00`];
} else {
tx.signature = [`${sig.toString('hex')}01`];
}
return JSON.stringify(tx);
},
async submitTransaction(network, signedTx) {
const n = getNetwork(network);
const tx = JSON.parse(signedTx);
let result;
try {
result = await n.web.trx.sendRawTransaction(tx);
} catch (e) {
throw new Error(e);
}
/*
{ result: true,
transaction:
{ visible: false,
txID:
'28782188e56ac613f99be803040d5c9ae0e467797a6f0f88e5c188d0c20b0b00',
.....
}
}
OR
{ code: 'SIGERROR',
message:
'.....' }
*/
if (typeof result.result !== 'undefined') {
if (result.result) {
return result.transaction.txID;
}
}
if (typeof result.message !== 'undefined') {
throw new Error(
`${result.code}: ` + Buffer.from(result.message, 'hex').toString()
);
}
if (typeof result.code === 'string') {
throw new Error(result.code);
}
throw new Error('unknown error');
},
prepareCommandGetPubkey(network, accountIndex) {
getNetwork(network);
if (!(isNonNegativeInteger(accountIndex) && accountIndex <= 0x7fffffff)) {
throw Error(`invalid accountIndex: ${accountIndex}`);
}
const msg = new Tron.TrxCommand.TrxGetPub();
msg.setPathList([0x80000000 + accountIndex, 0, 0]);
const cmd = new Tron.TrxCommand();
cmd.setGetPub(msg);
return {
commandId: TRON_CMDID,
payload: Buffer.from(cmd.serializeBinary())
};
},
parsePubkeyResponse(walletRsp) {
const wrsp = Tron.TrxResponse.deserializeBinary(walletRsp.payload);
const wpk = wrsp.getPk();
if (typeof wpk === 'undefined') {
const msgCase = wrsp.getMsgCase();
if (msgCase === Tron.TrxResponse.MsgCase.ERROR) {
throw Error(
`unexpected walletRsp with Armadillo errorCode ${wrsp.getError()}`
);
}
throw Error(
`unexpected walletRsp payload: ${walletRsp.payload.toString('hex')}`
);
}
return '04' + Buffer.from(wpk.getPubkey_asU8()).toString('hex');
},
prepareCommandShowAddr(network, accountIndex) {
getNetwork(network);
if (!(isNonNegativeInteger(accountIndex) && accountIndex <= 0x7fffffff)) {
throw Error(`invalid accountIndex: ${accountIndex}`);
}
const cmd = new Tron.TrxCommand();
const msg = new Tron.TrxCommand.TrxShowAddr();
cmd.setShowAddr(msg);
msg.setPathList([accountIndex + 0x80000000, 0, 0]);
return {
commandId: TRON_CMDID,
payload: Buffer.from(cmd.serializeBinary())
};
}
};
export default trxCurrencyUtil;
|
KelvinWallet/kelvinjs-trx | lib/index.d.ts | import { ICurrencyUtil } from './ICurrencyUtil';
export declare const trxCurrencyUtil: ICurrencyUtil;
export default trxCurrencyUtil;
|
KelvinWallet/kelvinjs-trx | test/index.ts | import test from 'ava';
import { KelvinWallet } from 'kelvinjs-usbhid';
import { trxCurrencyUtil } from '../src';
import { IArmadilloCommand, ISignTxRequest } from '../src/ICurrencyUtil';
async function send(command: IArmadilloCommand): Promise<string> {
const device = new KelvinWallet();
const [status, buffer] = device.send(command.commandId, command.payload);
device.close();
if (status !== 0) {
throw Error(`error status code ${status}`);
}
return buffer.toString('hex');
}
let publicKey = '';
let address = '';
let toAddress = '';
test('prepareCommandGetPubkey(accountId = 1)', async t => {
const command = trxCurrencyUtil.prepareCommandGetPubkey('testnet', 1);
const response = await send(command);
const toPublicKey = trxCurrencyUtil.parsePubkeyResponse({
payload: Buffer.from(response, 'hex')
});
toAddress = trxCurrencyUtil.encodePubkeyToAddr('testnet', toPublicKey);
t.is(toAddress, 'TKB7thq3aDS2gzqPfJPHj4g1KRSJbBCHzU');
console.log(toAddress);
});
test('prepareCommandGetPubkey(accountId = 0)', async t => {
const command = trxCurrencyUtil.prepareCommandGetPubkey('testnet', 0);
const response = await send(command);
publicKey = trxCurrencyUtil.parsePubkeyResponse({
payload: Buffer.from(response, 'hex')
});
address = trxCurrencyUtil.encodePubkeyToAddr('testnet', publicKey);
t.is(address, 'TQUauGLDR4tcvu8U71WJdnE5dy2tsLSgXb');
console.log(address);
});
test('prepareCommandShowAddr()', async t => {
const command = trxCurrencyUtil.prepareCommandShowAddr('testnet', 0);
const response = await send(command);
t.deepEqual(response, '0800');
});
test('getBalance()', async t => {
const balance = await trxCurrencyUtil.getBalance('testnet', address);
console.log(balance);
t.pass();
});
test('getRecentHistory()', async t => {
const schema = trxCurrencyUtil.getHistorySchema();
const txList = await trxCurrencyUtil.getRecentHistory('testnet', address);
for (let i = 0; i < txList.length && i < 10; i++) {
const tx = txList[i];
for (const field of schema) {
console.log(field.label, ':', tx[field.key].value);
}
console.log();
}
t.pass();
});
test('sign & submit tx', async t => {
const schema = trxCurrencyUtil.getPreparedTxSchema();
const req: ISignTxRequest = {
network: 'testnet',
accountIndex: 0,
toAddr: toAddress,
fromPubkey: publicKey,
amount: '100000'
};
const [command, txinfo] = await trxCurrencyUtil.prepareCommandSignTx(req);
for (const field of schema) {
console.log(field.label, ':', txinfo[field.key].value);
}
console.log();
const walletRsp = await send(command);
const signedTx = trxCurrencyUtil.buildSignedTx(req, command, {
payload: Buffer.from(walletRsp, 'hex')
});
const txid = await trxCurrencyUtil.submitTransaction('testnet', signedTx);
console.log(trxCurrencyUtil.getUrlForTx('testnet', txid));
t.pass();
});
|
lakshay-pant/vynoFinalBack | dist/src/address/address.module.d.ts | export declare class AddressModule {
}
|
lakshay-pant/vynoFinalBack | src/users/schemas/user.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type UserDocument = User & Document;
@Schema()
export class User {
@Prop()
first_name: string;
@Prop()
last_name: string;
@Prop()
email: string;
@Prop()
country_code: string;
@Prop()
phone_number: string;
@Prop()
verify_otp: string;
@Prop()
gender: string;
@Prop()
dob: string;
@Prop()
profession: string;
@Prop()
profile: string;
@Prop()
driving_licence: string;
@Prop()
cnic: string;
@Prop()
license: string;
@Prop()
registration: string;
@Prop()
insurance: string;
@Prop()
account_status: string;
@Prop()
fcm: string;
@Prop()
role: string;
@Prop({ required: true ,default: 0})
wallet_amount_user: number;
@Prop({ required: true ,default: 0})
wallet_amount_driver: number;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const UserSchema = SchemaFactory.createForClass(User); |
lakshay-pant/vynoFinalBack | dist/src/document/dto/update-document.dto.d.ts | import { CreateDocumentDto } from './create-document.dto';
declare const UpdateDocumentDto_base: import("@nestjs/mapped-types").MappedType<Partial<CreateDocumentDto>>;
export declare class UpdateDocumentDto extends UpdateDocumentDto_base {
}
export {};
|
lakshay-pant/vynoFinalBack | dist/src/lift/lift.module.d.ts | <filename>dist/src/lift/lift.module.d.ts<gh_stars>0
export declare class LiftModule {
}
|
lakshay-pant/vynoFinalBack | dist/src/singup/dto/create-singup.dto.d.ts | <reponame>lakshay-pant/vynoFinalBack
export declare class CreateSingupDto {
}
|
lakshay-pant/vynoFinalBack | dist/src/singup/singup.module.d.ts | export declare class SingupModule {
}
|
lakshay-pant/vynoFinalBack | dist/src/lift/schemas/virtualBuffer.schema.d.ts | import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import { LiftBooking } from '../schemas/liftBooking.schema';
import * as mongoose from 'mongoose';
export declare type VirtualBufferDocument = VirtualBuffer & Document;
export declare class VirtualBuffer {
user_id: User;
booking_id: LiftBooking;
amount: number;
created_at: string;
}
export declare const VirtualBufferSchema: mongoose.Schema<Document<VirtualBuffer, any, any>, mongoose.Model<Document<VirtualBuffer, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/payment/schemas/history.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import { Payment, PaymentSchema } from '../schemas/payment.schema';
import { LiftBooking, LiftBookingSchema } from '../../lift/schemas/liftBooking.schema';
import * as mongoose from 'mongoose';
export type HistoryDocument = History & Document;
@Schema()
export class History {
@Prop({
type: String,
required: true,
enum: ['credit','debit'],
})
type: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Payment' })
payment_id: Payment;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'LiftBooking' })
booking_id: LiftBooking;
@Prop()
created_at: string;
}
export const HistorySchema = SchemaFactory.createForClass(History); |
lakshay-pant/vynoFinalBack | src/address/address.controller.ts | import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import bodyParser from 'body-parser';
import { AddressService } from './address.service';
import { CreateAddressDto } from './dto/create-address.dto';
import { UpdateAddressDto } from './dto/update-address.dto';
@Controller({path:'address',version:'1'})
export class AddressController {
constructor(private readonly addressService: AddressService) {}
@Post('add-address')
async create(@Body() body, createAddressDto: CreateAddressDto) {
try{
createAddressDto = body;
createAddressDto['user_id'] = createAddressDto['user'].id;
delete createAddressDto['user'];
const addAddress = await this.addressService.create(createAddressDto);
if(addAddress){
return {status:true,message:"created successfully"};
}
}catch (e) {
if(e.hasOwnProperty('errors')){
return {"status":false,message:'validation error'};
}else{
return {"status":false,message:e};
}
}
}
@Get()
findAll() {
return this.addressService.findAll();
}
}
|
lakshay-pant/vynoFinalBack | src/lift/lift.service.ts | <gh_stars>0
import { Injectable } from '@nestjs/common';
import { CreateLiftDto } from './dto/create-lift.dto';
import { UpdateLiftDto } from './dto/update-lift.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Lift, LiftSchema } from './schemas/lift.schema';
import { LiftRequest, LiftRequestSchema } from './schemas/liftRequest.schema';
import { LiftBooking, LiftBookingSchema } from './schemas/liftBooking.schema';
import { LiftNotification, LiftNotificationSchema } from './schemas/liftNotification.schema';
import { VirtualLift, VirtualLiftSchema } from './schemas/virtualLift.schema';
import { VirtualBuffer, VirtualBufferSchema } from './schemas/virtualBuffer.schema';
import {GOOGEL_MAP_KEY, PUSH_NOTIFICATION , FIREBASE_SERVER_KEY} from '../../config/configuration'
var FCM = require('fcm-node');
var serverKey = FIREBASE_SERVER_KEY; //put your server key here
var fcm = new FCM(serverKey);
var moment = require('moment');
var mongoose = require('mongoose');
@Injectable()
export class LiftService {
constructor(
@InjectModel(Lift.name) private liftModel: Model<CreateLiftDto>,
@InjectModel(LiftRequest.name) private liftRequestModel: Model<{}>,
@InjectModel(LiftBooking.name) private liftBookingModel: Model<{}>,
@InjectModel(LiftNotification.name) private liftNotification: Model<{}>,
@InjectModel(VirtualLift.name) private virtualLift: Model<{}>,
@InjectModel(VirtualBuffer.name) private virtualBufferModel: Model<{}>,
) {}
create(createLiftDto: CreateLiftDto) {
try{
const createdlift = new this.liftModel(createLiftDto);
return createdlift.save();
} catch(e){
return e;
}
}
findAll() {
const alllift = this.liftModel.find().exec();
return alllift;
}
myAllList(id) {
const lift = this.liftModel.find({ user_id: mongoose.Types.ObjectId(id) }).exec();
return lift;
}
findOne(id: any) {
const lift = this.liftModel.findOne({_id: mongoose.Types.ObjectId(id) }).exec();
return lift;
}
activeBooking(id: any) {
return this.liftBookingModel.findOneAndUpdate({ _id: mongoose.Types.ObjectId(id) },{$set: {'status':'active'}})
}
fetchTodayBooking(user_id,date){
const mylift = this.liftBookingModel.aggregate([
{ $match: { "date": date } },
{ $match: {$or: [{'user_id': {$eq: mongoose.Types.ObjectId(user_id)}}, {'driver_id': mongoose.Types.ObjectId(user_id)}]}, },
{
$lookup:
{
from: 'users',
localField: 'driver_id',
foreignField: '_id',
as: 'rider'
}
},
{
$lookup:
{
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
}
]);
return mylift;
}
deleteLift(id){
const deletelift = this.liftModel.findByIdAndRemove(id);
return deletelift;
}
searchLift(query,user_id){
const dayname = moment(query.occasional, "D MMM YYYY").format("dddd");
const lift = this.liftModel.find({
$and : [
{'user_id': {$ne : mongoose.Types.ObjectId(user_id)}},
{"type": query.type},
{"to.address": query.to.address},
{"from.address": query.from.address},
{"passenger": query.passenger},
{$or: [{'pick_preferences.gender': {$eq: query.pick_preferences.gender}}, {'pick_preferences.gender': 'Any'}]},
{$or: [{'pick_preferences.air_condition': {$eq: query.pick_preferences.air_condition}}, {'pick_preferences.gender': 'Any'}]},
{$or: [{'pick_preferences.pvt_lift': {$eq: query.pick_preferences.pvt_lift}}, {'pick_preferences.pvt_lift': 'Any'}]},
{$or: [{'pick_preferences.car': {$eq: query.pick_preferences.car}}, {'pick_preferences.car': 'Any'}]},
]
} ).exec();
return lift;
}
update(id: any, updateLiftDto: UpdateLiftDto) {
return this.liftModel.findOneAndUpdate({ _id: mongoose.Types.ObjectId(id) },{$set: updateLiftDto})
}
checkRequestExits(data){
try{
const lift = this.liftRequestModel.findOne({
$and : [
{"user_id": mongoose.Types.ObjectId(data.user_id)},
{"lift_id": mongoose.Types.ObjectId(data.lift_id)},
{"driver_id": mongoose.Types.ObjectId(data.driver_id)},
{"driver_status": ''},
]
} ).exec();
return lift;
}catch(e){
return e;
}
}
createdLiftRequest(data){
try{
const createdliftRequest = new this.liftRequestModel(data);
return createdliftRequest.save();
} catch(e){
return e;
}
}
myLiftUserRequest(id){
try{
const mylift = this.liftRequestModel.aggregate([
{ $match: { "user_id": mongoose.Types.ObjectId(id) } },
{
$lookup:
{
from: 'users',
localField: 'driver_id',
foreignField: '_id',
as: 'rider'
}
},
{
$lookup:
{
from: 'lifts',
localField: 'lift_id',
foreignField: '_id',
as: 'lift'
}
}
]);
return mylift;
} catch(e){
return e;
}
}
myVirtualLiftRequest(id){
try{
const mylift = this.virtualLift.aggregate([
{ $match: { "user_id": mongoose.Types.ObjectId(id) } },
{
$lookup:
{
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
}
]);
return mylift;
} catch(e){
return e;
}
}
myLiftDriverRequest(id){
try{
const mylift = this.liftRequestModel.aggregate([
{ $match: { "driver_id": mongoose.Types.ObjectId(id) } },
{
$lookup:
{
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'rider'
}
},
{
$lookup:
{
from: 'lifts',
localField: 'lift_id',
foreignField: '_id',
as: 'lift'
}
}
]);
return mylift;
} catch(e){
return e;
}
}
actionLiftRequest(query){
return this.liftRequestModel.findOneAndUpdate({ _id: mongoose.Types.ObjectId(query.lift_request_id) },{$set: {'driver_status':query.action}})
}
createdLiftBooking(query){
try{
const createdLiftBooking = new this.liftBookingModel(query);
return createdLiftBooking.save();
} catch(e){
return e;
}
}
cancleBooking(data){
try{
return this.liftBookingModel.findOneAndUpdate({ _id: mongoose.Types.ObjectId(data.booking_id) },{$set: {'cancle_by':data.myrole,'is_cancle':true}})
} catch(e){
return e;
}
}
myBookingData(id,role){
try{
var condition;
var lookup;
if(role == 'driver'){
condition = { "driver_id": mongoose.Types.ObjectId(id) };
lookup = {$lookup:{
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
};
}else if(role == 'user'){
condition = { "user_id": mongoose.Types.ObjectId(id) };
lookup = { $lookup:
{
from: 'users',
localField: 'driver_id',
foreignField: '_id',
as: 'driver'
}
};
}
const fetchNotificationDriver = this.liftBookingModel.aggregate([
{ $match: condition },
lookup,
]);
return fetchNotificationDriver;
} catch(e){
return e;
}
}
createdNotification(data){
try{
const createdNotification = new this.liftNotification(data);
return createdNotification.save();
} catch(e){
return e;
}
}
fetchNotificationUser(userid){
try{
const fetchNotificationUser = this.liftNotification.aggregate([
{ $match: { "notify_from": 'driver' } },
{ $match: {"user_id": mongoose.Types.ObjectId(userid)} },
{
$lookup:
{
from: 'users',
localField: 'driver_id',
foreignField: '_id',
as: 'rider'
}
},
{"$sort":{"_id":-1}}
]);
return fetchNotificationUser;
} catch(e){
return e;
}
}
fetchNotificationDriver(driverid){
try{
const fetchNotificationDriver = this.liftNotification.aggregate([
{ $match: { "notify_from": 'user' } },
{ $match: {"driver_id": mongoose.Types.ObjectId(driverid)} },
{
$lookup:
{
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
},
{"$sort":{"_id":-1}}
]);
return fetchNotificationDriver;
} catch(e){
return e;
}
}
deleteAllNotification(notification_id){
// Site.deleteMany({ userUID: uid, id: { $in: [10, 2, 3, 5]}}, function(err) {})
const deleteNotifications = this.liftNotification.deleteMany({_id: { $in: notification_id}});
return deleteNotifications;
}
//virtual lift
createVirtualLift(data) {
try{
const createdlift = new this.virtualLift(data);
return createdlift.save();
} catch(e){
return e;
}
}
getVirtualLiftDetails(id){
const lift = this.virtualLift.findOne({_id: mongoose.Types.ObjectId(id) }).exec();
return lift;
}
updateVirtualLiftDetails(id,data){
return this.virtualLift.findOneAndUpdate({ _id: mongoose.Types.ObjectId(id) },{$set: {'rejected_id':data}})
}
getVirtualLift(user_id){
try{
const allVirtualLift = this.virtualLift.aggregate([
{"user_id": {$ne: mongoose.Types.ObjectId(user_id)}},
{
$lookup:
{
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
},
{"$sort":{"_id":-1}}
]).exec();
//const allVirtualLift = this.virtualLift.find().exec();
return allVirtualLift;
} catch(e){
return e;
}
}
acceptVirtualLiftFromDriver(lift_id,data){
return this.virtualLift.findOneAndUpdate({ _id: mongoose.Types.ObjectId(lift_id) },{$set: data});
}
removeVirtualLiftFromuser(lift_id){
return this.virtualLift.updateOne(
{ $unset: { accepted_id: ""} }
)
}
approvalVirtualLift(lift_id){
return this.virtualLift.findOneAndUpdate({ _id: mongoose.Types.ObjectId(lift_id) },{$set: {'approval':true}});
}
// virtual buffer
addAmountInVirtualBuffer(data){
try{
const addAmount = new this.virtualBufferModel(data);
return addAmount.save();
} catch(e){
return e;
}
}
getVirtualBuffer(id){
const bufferData = this.virtualBufferModel.findOne({booking_id: mongoose.Types.ObjectId(id) }).exec();
return bufferData;
}
removeBufferData(id){
const deleteData = this.virtualBufferModel.findByIdAndDelete(id);
return deleteData;
}
//virtual buffer
}
|
lakshay-pant/vynoFinalBack | src/address/schemas/address.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export type AddressDocument = Address & Document;
@Schema()
export class Address {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
user_id: User;
@Prop({ required: true })
type: string;
@Prop({ required: true })
lat: string;
@Prop({ required: true })
long: string;
@Prop({ required: true })
address: string;
@Prop()
landmark: string;
@Prop({ required: true })
country: string;
@Prop({ required: true })
state: string;
@Prop({ required: true })
city: string;
@Prop({ required: true })
pin_Code:string;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const AddressSchema = SchemaFactory.createForClass(Address); |
lakshay-pant/vynoFinalBack | dist/src/users/schemas/momo.schema.d.ts | <filename>dist/src/users/schemas/momo.schema.d.ts
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export declare type MomoDocument = Momo & Document;
export declare class Momo {
user_id: User;
username: string;
password: string;
created_at: string;
}
export declare const MomoSchema: mongoose.Schema<Document<Momo, any, any>, mongoose.Model<Document<Momo, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/users/schemas/momo.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export type MomoDocument = Momo & Document;
@Schema()
export class Momo {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop()
username: string;
@Prop()
password: string;
@Prop()
created_at: string;
}
export const MomoSchema = SchemaFactory.createForClass(Momo); |
lakshay-pant/vynoFinalBack | dist/config/environment.d.ts | <filename>dist/config/environment.d.ts
export declare const ENV: {
DB_URL: string;
DB_USER: string;
DB_PASS: string;
};
|
lakshay-pant/vynoFinalBack | src/users/users.module.ts | <gh_stars>0
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from './schemas/user.schema';
import { RatingReview, RatingReviewSchema } from './schemas/ratingReview.schema';
import { Momo, MomoSchema } from './schemas/momo.schema';
import { JwtModule } from '@nestjs/jwt';
import { HelperService } from '../common/helper';
import { MulterModule } from '@nestjs/platform-express';
@Module({
imports: [
MongooseModule.forFeature(
[
{ name: User.name, schema: UserSchema },
{ name: RatingReview.name, schema: RatingReviewSchema },
{ name: Momo.name, schema: MomoSchema },
]
),
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '365d' },
}),
MulterModule.register({
dest: './public/uploads/document/',
})
],
controllers: [UsersController],
providers: [UsersService,HelperService]
})
export class UsersModule {}
|
lakshay-pant/vynoFinalBack | src/admin/admin.controller.ts | <filename>src/admin/admin.controller.ts<gh_stars>0
import { Controller, Get, Post, Body, Patch, Param, Delete, Req ,Query} from '@nestjs/common';
import { AdminService } from './admin.service';
import { CreateAdminDto } from './dto/create-admin.dto';
import { UpdateAdminDto } from './dto/update-admin.dto';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
@Controller({path:'admin',version:'1'})
export class AdminController {
constructor(
private readonly adminService: AdminService,
private jwtService: JwtService,
private readonly usersService: UsersService,
) {}
@Post('login')
async create(@Body() body) {
if(!body.hasOwnProperty('user_name') || !body.hasOwnProperty('password')){
return {status:false,message:"provide Valid parameter"};
}else if(body['user_name'] == '<EMAIL>' && body['password'] == '!@#$%^'){
const payload = { user_name: '<EMAIL>'};
const jwtToken = await this.jwtService.signAsync(payload);
return {status:true,token: jwtToken,message:"login successfully"};
}else{
return {status:false,message:"login failed"};
}
}
@Get('get-user')
async findAll() {
return await this.usersService.findAll();
}
@Get('update-account-status')
async findOne(@Query() query,@Body() body) {
try{
const status = ["pending", "approved", "rejected"];
if(query.id && body.account_status){
if(status.includes(body.account_status)){
const finduser = await this.usersService.findDataFromId(query.id);
const documentStatus = {
'account_status' : body.account_status
};
var updateStatus = await this.usersService.update(query.id,documentStatus);
if(updateStatus){
return {status:true,message:"status change successfully"};
}
}else{
return {status:false,message:`your status doesn't match our records`};
}
}else{
return {status:false,message:"provide Valid parameter"};
}
} catch (e){
return {status:false,message:e};
}
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateAdminDto: UpdateAdminDto) {
return this.adminService.update(+id, updateAdminDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.adminService.remove(+id);
}
}
|
lakshay-pant/vynoFinalBack | src/document/document.service.ts | <filename>src/document/document.service.ts
import { Injectable } from '@nestjs/common';
import { CreateDocumentDto } from './dto/create-document.dto';
import { UpdateDocumentDto } from './dto/update-document.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Documents, DocumentsSchema } from './schemas/document.schema';
var mongoose = require('mongoose');
@Injectable()
export class DocumentService {
constructor(
@InjectModel(Documents.name) private documentsModel: Model<CreateDocumentDto>
) {}
create(createDocumentDto: CreateDocumentDto) {
return 'This action adds a new document';
}
findAll() {
return `This action returns all document`;
}
findOne(id: number) {
return `This action returns a #${id} document`;
}
checkData(id,role){
const checkData = this.documentsModel.findOne( {$and: [{'user_id': mongoose.Types.ObjectId(id)},{'role': role}]});
return checkData;
}
checkAccountStatusFromId(user_id){
const checkData = this.documentsModel.find({'user_id': mongoose.Types.ObjectId(user_id)});
return checkData;
}
updateInsert(id,role,data,type) {
data['user_id'] = id;
data['role'] = role;
if(type == 'insert'){
const uploadUser = new this.documentsModel(data);
return uploadUser.save();
}else if(type == 'update'){
const updateuser = this.documentsModel.findOneAndUpdate({$and: [{'user_id': mongoose.Types.ObjectId(id)},{'role': role}]},{$set: data});
return updateuser;
}
}
remove(id: number) {
return `This action removes a #${id} document`;
}
}
|
lakshay-pant/vynoFinalBack | dist/src/payment/schemas/history.schema.d.ts | import { Document } from 'mongoose';
import { Payment } from '../schemas/payment.schema';
import { LiftBooking } from '../../lift/schemas/liftBooking.schema';
import * as mongoose from 'mongoose';
export declare type HistoryDocument = History & Document;
export declare class History {
type: string;
payment_id: Payment;
booking_id: LiftBooking;
created_at: string;
}
export declare const HistorySchema: mongoose.Schema<Document<History, any, any>, mongoose.Model<Document<History, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | dist/src/users/schemas/user.schema.d.ts | <gh_stars>0
import { Document } from 'mongoose';
export declare type UserDocument = User & Document;
export declare class User {
first_name: string;
last_name: string;
email: string;
country_code: string;
phone_number: string;
verify_otp: string;
gender: string;
dob: string;
profession: string;
profile: string;
driving_licence: string;
cnic: string;
license: string;
registration: string;
insurance: string;
account_status: string;
fcm: string;
role: string;
wallet_amount_user: number;
wallet_amount_driver: number;
created_at: string;
updated_at: string;
}
export declare const UserSchema: import("mongoose").Schema<Document<User, any, any>, import("mongoose").Model<Document<User, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/payment/payment.module.ts | <filename>src/payment/payment.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from '../users/schemas/user.schema';
import { RatingReview, RatingReviewSchema } from '../users/schemas/ratingReview.schema';
import { Momo, MomoSchema } from '../users/schemas/momo.schema';
import { Payment, PaymentSchema } from './schemas/payment.schema';
import { History,HistorySchema } from './schemas/history.schema';
import { UsersService } from '.././users/users.service';
import { JwtModule } from '@nestjs/jwt';
import { HelperService } from '../common/helper';
import { MulterModule } from '@nestjs/platform-express';
import { PaymentService } from './payment.service';
import { PaymentController } from './payment.controller';
@Module({
imports: [
MongooseModule.forFeature([
{ name: User.name, schema: UserSchema },
{ name: RatingReview.name, schema: RatingReviewSchema },
{ name: Momo.name, schema: MomoSchema },
{ name: Payment.name, schema: PaymentSchema },
{ name: History.name, schema: HistorySchema }
]),
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '365d' },
}),
MulterModule.register({
dest: './public/uploads/document/',
})
],
controllers: [PaymentController],
providers: [PaymentService,UsersService,HelperService]
})
export class PaymentModule {}
|
lakshay-pant/vynoFinalBack | dist/src/users/schemas/ratingReview.schema.d.ts | <filename>dist/src/users/schemas/ratingReview.schema.d.ts
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export declare type RatingReviewDocument = RatingReview & Document;
export declare class RatingReview {
to: User;
rating: string;
rating_for: string;
created_at: string;
updated_at: string;
}
export declare const RatingReviewSchema: mongoose.Schema<Document<RatingReview, any, any>, mongoose.Model<Document<RatingReview, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/lift/schemas/liftRequest.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
import { Lift, LiftSchema } from './lift.schema';
export type LiftRequestDocument = LiftRequest & Document;
@Schema()
export class LiftRequest {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Lift' ,required: true })
lift_id: Lift;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
driver_id: User;
@Prop({ required: true })
passenger: number;
@Prop({
type: String,
required: true,
enum: ['inititate','accepted','rejected'],
})
user_status: string;
@Prop({
type: String,
required: true
})
date: string;
@Prop({
type: String,
enum: ['pending','accepted','rejected'],
})
driver_status: string;
@Prop()
created_at: string;
@Prop()
created_at_time: string;
@Prop()
updated_at: string;
}
export const LiftRequestSchema = SchemaFactory.createForClass(LiftRequest); |
lakshay-pant/vynoFinalBack | dist/src/document/document.module.d.ts | <gh_stars>0
export declare class DocumentModule {
}
|
lakshay-pant/vynoFinalBack | src/document/document.controller.ts | <reponame>lakshay-pant/vynoFinalBack
import { Controller, Get, Post, Res, Body, Patch, Param, Delete, ParseIntPipe, UseInterceptors, UploadedFile, UploadedFiles} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor ,FileFieldsInterceptor ,AnyFilesInterceptor } from "@nestjs/platform-express";
import { DocumentService } from './document.service';
import { CreateDocumentDto } from './dto/create-document.dto';
import { UpdateDocumentDto } from './dto/update-document.dto';
import { HelperService } from '../common/helper';
import { JwtService } from '@nestjs/jwt';
import * as fs from "fs";
@Controller({path:'document',version:'1'})
export class DocumentController {
constructor(
private readonly documentService: DocumentService,
private jwtService: JwtService,
private helperService:HelperService
) {}
@Post('')
create(@Body() createDocumentDto: CreateDocumentDto) {
return this.documentService.create(createDocumentDto);
}
@Get('get-account-status')
async accountStatus(@Body() body) {
const user_id = body.user.id;
const findstatus = await this.documentService.checkAccountStatusFromId(user_id);
var data={};
if(findstatus.length > 0){
findstatus.map((item,index)=>{
if(item && item['account_status'] && item['role'] == '0'){
data['user_status']= item['account_status'];
}else if(item && item['account_status'] && item['role'] == '1'){
data['driver_status']= item['account_status'];
}
})
if(!data['user_status']){
data['user_status'] = ''
}
if(!data['driver_status']){
data['driver_status'] = ''
}
return {"status":true,data:data};
}else{
return {"status":true,data:{user_status:'',driver_status:''}};
}
}
@Post('update-account-status')
async updateStatus(@Body() body) {
const id = body.user.id;
const role = body.role;
const status = body.account_status;
var statusArray = ["pending", "approved", "rejected"];
var checkStatus = statusArray.includes(status);
if(!role || !status || !checkStatus){
return {status:false , message:"provide valid parameter"};
}
const update = await this.documentService.updateInsert(id,role,{account_status:"approved"},'update');
if(update){
return {status:true, message:"update successfully"};
}else{
return {"status":true,message:"data not found"};
}
}
@Post('/upload-document')
@UseInterceptors(AnyFilesInterceptor())
async uploadFile(@Body() body,@UploadedFiles() files: Array<Express.Multer.File>) {
try{
var i = 0;
var fielddata = [];
var id = body.id;
var role = body.role;
var updateUser;
if(Array.isArray(files) && files.length){
for (let i = 0; i < files.length; i++) {
fielddata[files[i].fieldname] = files[i].path;
const extension = files[i].mimetype.split("/")[1];
fs.rename(files[i].path, files[i].path+'.'+extension, function(err) {
});
if(!id || !role){
console.log("delete"+" "+files[i].path+'.'+extension)
fs.unlinkSync(files[i].path+'.'+extension);
}else{
const updateUserDocument = {
[files[i].fieldname] : files[i].path+'.'+extension
};
//updateUser = await this.documentService.updateInsert(id,role,updateUserDocument);
const checkdata = await this.documentService.checkData(id,role);
if(checkdata){
updateUser = await this.documentService.updateInsert(id,role,updateUserDocument,'update');
}else{
updateUser = await this.documentService.updateInsert(id,role,updateUserDocument,'insert');
}
}
if( i == files.length - 1 ){
if(!id || !role){
return {status:false , message:"provide valid parameter"};
}else{
const documentStatus = {
'account_status' : 'pending'
};
await this.documentService.updateInsert(id,role,documentStatus,'update');
return {status:true , message:"document update successfully"};
}
}
}
}else{
return {"status":false,message:"minimum 1 file upload"};
}
}catch (e) {
return {"status":false,message:e};
}
}
}
|
lakshay-pant/vynoFinalBack | dist/src/payment/dto/create-payment.dto.d.ts | <gh_stars>0
export declare class CreatePaymentDto {
}
|
lakshay-pant/vynoFinalBack | src/payment/payment.controller.ts | <gh_stars>0
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { PaymentService } from './payment.service';
import { CreatePaymentDto } from './dto/create-payment.dto';
import { UpdatePaymentDto } from './dto/update-payment.dto';
import { UsersService } from '../users/users.service';
import { HelperService } from '../common/helper';
import { MOMO } from 'config/configuration';
import { v4 } from 'uuid';
import * as moment from 'moment';
import { async } from 'rxjs';
const { base64encode, base64decode } = require('nodejs-base64');
let fetch = require('node-fetch');
@Controller({path:'payment',version:'1'})
export class PaymentController {
constructor(
private readonly paymentService: PaymentService,
private readonly usersService: UsersService,
private helperService:HelperService
) {}
@Post('request-to-pay')
async create(@Body() body) {
const user_id = body.user.id;
const role = body.role;
if(!body['amount'] || !body['partyId'] || role !== 'user'){
return {"status":false,message:'provide valid parameter'};
}
const findMomoCredential = await this.usersService.findMomoCredential(body.user.id);
if(!findMomoCredential){
return {"status":false,message:'your account not found in momo mtn'};
}
// for genrate token
var url = MOMO.MOMO_URL+ '/collection/token/';
var headerfortoken = {
"Authorization": "Basic " + base64encode(findMomoCredential['username'] + ":" + findMomoCredential['password']),
'Content-Type' : 'application/json',
'Ocp-Apim-Subscription-Key':MOMO.OcpApimSubscriptionKey,
'Content-Length':'0'
};
return await fetch(url, {
method: 'POST',
headers: headerfortoken
})
.then(async responsedata => {
if(responsedata.status == 200){
var result = await responsedata.json();
const bodydata = {
"amount": body['amount'],
"currency": "EUR",
"externalId": "6353636",
"payer": {
"partyIdType": "MSISDN",
"partyId": body['partyId']
},
"payerMessage": "pay for ride",
"payeeNote": "pay for ride"
};
var url = MOMO.MOMO_URL+ '/collection/v1_0/requesttopay';
var uuidv4 = v4();
var headerForpayment = {
'Content-Type' : 'application/json',
'Ocp-Apim-Subscription-Key': MOMO.OcpApimSubscriptionKey,
'X-Reference-Id' : uuidv4,
'X-Target-Environment' : MOMO.XTargetEnvironment,
'Authorization' : 'Bearer '+result.access_token
};
return await fetch(url, {
method: 'POST',
headers: headerForpayment,
body: JSON.stringify(bodydata)
}).then(async response => {
var paymentData ={
'user_id':user_id,
'request_uuid':uuidv4,
'amount': body['amount'],
'created_at':moment().format('DD/MM/YYYY h:mm A')
}
if(response.status === 202){
paymentData['status'] = 'success';
paymentData['message'] = 'fund added successful';
const payment = await this.paymentService.create(paymentData);
const fetchUserDetails = await this.usersService.findDataFromId(user_id);
var amount = parseInt(fetchUserDetails['wallet_amount_user']) + parseInt(body['amount']);
const updateUserWallet = await this.usersService.updateUserWallet(user_id,amount);
const history = {
"type":'credit',
"payment_id": payment['_id'],
"created_at":moment().format('DD/MM/YYYY h:mm A')
}
const historyCreate = await this.paymentService.historyCreate(history);
return {status:true,message:"payment request successful"};
}else{
paymentData['status'] = 'failed';
paymentData['message'] = 'invalid number';
await this.paymentService.create(paymentData);
return {status:false,message:'invalid number'};
}
}).catch(error => {
return {status:false,message:error};
});
}else{
return {status:false,message:''};
}
})
.catch(error => {
return {status:false,message:error};
});
}
@Get()
findAll() {
return this.paymentService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.paymentService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updatePaymentDto: UpdatePaymentDto) {
return this.paymentService.update(+id, updatePaymentDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.paymentService.remove(+id);
}
}
|
lakshay-pant/vynoFinalBack | config/environment.ts | <reponame>lakshay-pant/vynoFinalBack
const DEV = {
DB_URL: 'mongodb://localhost/vyno',
DB_USER:'',
DB_PASS:'',
};
const PROD = {
DB_URL: 'mongodb://vyno:[email protected]:27017/vyno',
DB_USER:'vyno',
DB_PASS:'<PASSWORD>',
};
export const ENV = DEV;
|
lakshay-pant/vynoFinalBack | src/common/helper.ts | <filename>src/common/helper.ts
import { Injectable } from '@nestjs/common';
import * as fs from "fs";
import { time } from 'console';
import {GOOGEL_MAP_KEY, PUSH_NOTIFICATION , FIREBASE_SERVER_KEY} from '../../config/configuration'
const mime = require('mime');
const multer = require('multer');
const NodeGeocoder = require('node-geocoder');
const options = {
provider: 'google',
apiKey: '', // for Mapquest, OpenCage, Google Premier
formatter: null // 'gpx', 'string', ...
};
const geocoder = NodeGeocoder(options);
var FCM = require('fcm-node');
var serverKey = FIREBASE_SERVER_KEY; //put your server key here
var fcm = new FCM(serverKey);
@Injectable()
export class HelperService {
base64ImageUpload(imgBase64: any) {
try {
var matches = imgBase64.match(/^data:([A-Za-z-+/]+);base64,(.+)$/);
const response = {};
if (matches.length !== 3) {
return {"status":"false",message:'invalid format of images'};
}
var dir = './public/uploads/images/';
var pathDir = '/public/uploads/images/';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir , { recursive: true });
}
let imageBuffer = Buffer.from(matches[2], 'base64')
let type = matches[1];
let extension = mime.extension(type);
const d = new Date();
let time = d.getTime();
let fileName = "image"+time+"." + extension;
fs.writeFileSync(dir + fileName, imageBuffer, 'utf8');
let path = pathDir+fileName;
return {"status":true,path:path };
} catch (e) {
return {"status":false,message:e};
}
}
documentUpload(data){
try {
var dir = './public/uploads/document';
var pathDir = '/public/uploads/document';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir , { recursive: true });
}
var array =[];
data.map( (item, index) =>{
array.push(item);
});
return array;
} catch (e) {
return {"status":"false",message:e};
}
}
removeUnderscoreFromcolumn(data){
var User = JSON.parse(JSON.stringify(data));
User['id'] = User._id;
delete User.__v;
delete User._id;
return User;
}
getReverseGeocodingData(lat, lng) {
const res = geocoder.reverse({ lat: lat, lon: lng });
return res;
}
//push notification
pushNotifications(fcm_token,title_msg,msg){
if(PUSH_NOTIFICATION && fcm_token){
var message = {
to: fcm_token,
notification: {
title: title_msg,
body: msg
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
}
}
//push notifications
}
|
lakshay-pant/vynoFinalBack | dist/src/admin/entities/admin.entity.d.ts | <filename>dist/src/admin/entities/admin.entity.d.ts
export declare class Admin {
}
|
lakshay-pant/vynoFinalBack | dist/src/singup/singup.service.d.ts | <filename>dist/src/singup/singup.service.d.ts
import { CreateSingupDto } from './dto/create-singup.dto';
import { UpdateSingupDto } from './dto/update-singup.dto';
export declare class SingupService {
create(createSingupDto: CreateSingupDto): string;
findAll(): string;
findOne(id: number): string;
update(id: number, updateSingupDto: UpdateSingupDto): string;
remove(id: number): string;
}
|
lakshay-pant/vynoFinalBack | src/lift/lift.module.ts | <gh_stars>0
import { Module } from '@nestjs/common';
import { LiftService } from './lift.service';
import { LiftController } from './lift.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { Lift, LiftSchema } from './schemas/lift.schema';
import { User, UserSchema } from '../users/schemas/user.schema';
import { LiftRequest, LiftRequestSchema } from './schemas/liftRequest.schema';
import { LiftBooking, LiftBookingSchema } from './schemas/liftBooking.schema';
import { VirtualBuffer, VirtualBufferSchema } from './schemas/virtualBuffer.schema';
import { VirtualLift, VirtualLiftSchema } from './schemas/virtualLift.schema';
import { LiftNotification, LiftNotificationSchema } from './schemas/liftNotification.schema';
import { RatingReview, RatingReviewSchema } from '../users/schemas/ratingReview.schema';
import { Momo, MomoSchema } from '../users/schemas/momo.schema';
import { UsersService } from '.././users/users.service';
import { JwtModule } from '@nestjs/jwt';
import { HelperService } from '../common/helper';
import { MulterModule } from '@nestjs/platform-express';
@Module({
imports: [
MongooseModule.forFeature([
{ name: Lift.name, schema: LiftSchema },
{ name: LiftRequest.name, schema: LiftRequestSchema },
{ name: LiftBooking.name, schema: LiftBookingSchema },
{ name: LiftNotification.name, schema: LiftNotificationSchema },
{ name: User.name, schema: UserSchema },
{ name: RatingReview.name, schema: RatingReviewSchema },
{ name: VirtualLift.name, schema: VirtualLiftSchema },
{ name: Momo.name, schema: MomoSchema },
{ name: VirtualBuffer.name, schema: VirtualBufferSchema },
]),
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '365d' },
}),
MulterModule.register({
dest: './public/uploads/document/',
})
],
controllers: [LiftController],
providers: [LiftService,HelperService,UsersService]
})
export class LiftModule {}
|
lakshay-pant/vynoFinalBack | config/configuration.ts | export const GOOGEL_MAP_KEY = '<KEY>';
export const USER_ROLE ='0';
export const DRIVER_ROLE ='1';
export const VIRTUAL_LIFT =true;
export const PUSH_NOTIFICATION =true;
export const FIREBASE_SERVER_KEY ='<KEY>';
export const MOMO_URL = 'https://sandbox.momodeveloper.mtn.com';
// export const MOMO_URL = 'https://proxy.momoapi.mtn.com';
export const OcpApimSubscriptionKey = '<KEY>';
export const ERR_MSG = 'went something wrong';
export const MOMO = {
MOMO_URL:'https://sandbox.momodeveloper.mtn.com',
XTargetEnvironment:'sandbox',
OcpApimSubscriptionKey:'<KEY>',
} |
lakshay-pant/vynoFinalBack | dist/src/address/dto/create-address.dto.d.ts | <filename>dist/src/address/dto/create-address.dto.d.ts
export declare class CreateAddressDto {
}
|
lakshay-pant/vynoFinalBack | src/users/users.service.ts | import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserSchema } from './schemas/user.schema';
import { RatingReview, RatingReviewSchema } from './schemas/ratingReview.schema';
import { Momo, MomoSchema } from './schemas/momo.schema';
import { v4 } from 'uuid';
import { MOMO } from './../../config/configuration'
var mongoose = require('mongoose');
@Injectable()
export class UsersService {
constructor(
@InjectModel(User.name) private userModel: Model<CreateUserDto>,
@InjectModel(RatingReview.name) private ratingReviewModel: Model<{}>,
@InjectModel(Momo.name) private momoModel: Model<{}>
) {}
create(createUserDto: CreateUserDto) {
const createdUser = new this.userModel(createUserDto);
return createdUser.save();
}
findAll() {
const allUser = this.userModel.find().exec();
return allUser;
}
findData(item) {
const findUser = this.userModel.findOne(item).exec();
return findUser;
}
findDataFromId(id) {
const findUser = this.userModel.findOne({ _id: mongoose.Types.ObjectId(id) }).exec();
return findUser;
}
update(id:any ,updateUserDto: UpdateUserDto) {
//return updateUserDto;
const updateuser = this.userModel.findOneAndUpdate({ _id: mongoose.Types.ObjectId(id) },{$set: updateUserDto});
return updateuser;
}
createMomoCredential(data){
const createdMomo = new this.momoModel(data);
return createdMomo.save();
}
findMomoCredential(user_id){
return this.momoModel.findOne({ user_id: mongoose.Types.ObjectId(user_id) }).exec();
}
updateOtp(item) {
return this.userModel.findOneAndUpdate({"phone_number": item.phone_number,'country_code':item.country_code},{$set: {"verify_otp": "1234","updated_at": item.updated_at}});
}
updateUserWallet(user_id,amount){
return this.userModel.findOneAndUpdate({_id: mongoose.Types.ObjectId(user_id)},{$set: {"wallet_amount_user": amount}});
}
deleteUser(user_id){
return this.userModel.findByIdAndDelete(user_id);
}
review(data){
const review = new this.ratingReviewModel(data);
return review.save();
}
}
|
lakshay-pant/vynoFinalBack | dist/src/payment/payment.service.d.ts | import { CreatePaymentDto } from './dto/create-payment.dto';
import { UpdatePaymentDto } from './dto/update-payment.dto';
import { Model } from 'mongoose';
export declare class PaymentService {
private paymentModel;
private historyModel;
constructor(paymentModel: Model<CreatePaymentDto>, historyModel: Model<{}>);
create(createPaymentDto: CreatePaymentDto): any;
historyCreate(data: any): any;
findAll(): string;
findOne(id: number): string;
update(id: number, updatePaymentDto: UpdatePaymentDto): string;
remove(id: number): string;
}
|
lakshay-pant/vynoFinalBack | dist/src/lift/entities/lift.entity.d.ts | export declare class Lift {
}
|
lakshay-pant/vynoFinalBack | src/admin/admin.service.ts | import { Injectable } from '@nestjs/common';
import { CreateAdminDto } from './dto/create-admin.dto';
import { UpdateAdminDto } from './dto/update-admin.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserSchema } from '../users/schemas/user.schema';
import { UsersService } from '../users/users.service';
var mongoose = require('mongoose');
@Injectable()
export class AdminService {
constructor(
private readonly usersService: UsersService,
) {}
create(createAdminDto: CreateAdminDto) {
return 'This action adds a new admin';
}
async findAll() {
}
findOne(id: number) {
return `This action returns a #${id} admin`;
}
update(id: number, updateAdminDto: UpdateAdminDto) {
return `This action updates a #${id} admin`;
}
remove(id: number) {
return `This action removes a #${id} admin`;
}
}
|
lakshay-pant/vynoFinalBack | src/lift/dto/update-lift.dto.ts | import { PartialType } from '@nestjs/mapped-types';
import { CreateLiftDto } from './create-lift.dto';
export class UpdateLiftDto extends PartialType(CreateLiftDto) {}
|
lakshay-pant/vynoFinalBack | src/lift/schemas/liftNotification.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
import { Lift } from './lift.schema';
import { LiftRequest } from './liftRequest.schema';
export type LiftNotificationDocument = LiftNotification & Document;
@Schema()
export class LiftNotification {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'LiftRequest' ,required: true })
lift_request_id: LiftRequest;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
driver_id: User;
@Prop({
type: String,
required: true
})
notify_from: string;
@Prop({
type: String,
required: true
})
message: string;
@Prop({default: false})
is_virtual: boolean;
@Prop({
type: String,
required: false
})
virtual_lift_price: string;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const LiftNotificationSchema = SchemaFactory.createForClass(LiftNotification); |
lakshay-pant/vynoFinalBack | dist/src/admin/admin.controller.d.ts | /// <reference types="mongoose" />
import { AdminService } from './admin.service';
import { UpdateAdminDto } from './dto/update-admin.dto';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
export declare class AdminController {
private readonly adminService;
private jwtService;
private readonly usersService;
constructor(adminService: AdminService, jwtService: JwtService, usersService: UsersService);
create(body: any): Promise<{
status: boolean;
message: string;
token?: undefined;
} | {
status: boolean;
token: string;
message: string;
}>;
findAll(): Promise<(import("mongoose").Document<any, any, import("../users/dto/create-user.dto").CreateUserDto> & import("../users/dto/create-user.dto").CreateUserDto & {
_id: unknown;
})[]>;
findOne(query: any, body: any): Promise<{
status: boolean;
message: any;
}>;
update(id: string, updateAdminDto: UpdateAdminDto): string;
remove(id: string): string;
}
|
lakshay-pant/vynoFinalBack | src/lift/lift.controller.ts | import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { LiftService } from './lift.service';
import { CreateLiftDto } from './dto/create-lift.dto';
import { UpdateLiftDto } from './dto/update-lift.dto';
import { HelperService } from '../common/helper';
import { UsersService } from '.././users/users.service';
import * as moment from 'moment';
import bodyParser from 'body-parser';
import {GOOGEL_MAP_KEY, PUSH_NOTIFICATION , FIREBASE_SERVER_KEY} from '../../config/configuration'
import { map } from 'rxjs';
var mongoose = require('mongoose');
let fetch = require('node-fetch');
var Distance = require('geo-distance');
var FCM = require('fcm-node');
var serverKey = FIREBASE_SERVER_KEY; //put your server key here
var fcm = new FCM(serverKey);
@Controller({path:'lift',version:'1'})
export class LiftController {
constructor(
private readonly liftService: LiftService,
private helperService:HelperService,
private readonly usersService: UsersService,
) {}
@Post('create-lift')
async create(@Body() body) {
try {
const data = body;
const id = body.user.id;
delete data.user;
data['user_id'] = id;
var to = {lat: body.to.lat,lon: body.to.long};
var from = {lat: body.from.lat,lon: body.from.long};
var distanceCalculate = Distance.between(to, from);
body['distance'] = distanceCalculate.human_readable().distance;
const createlift = await this.liftService.create(data);
if(createlift){
return {status:true,message:"lift created successfully"};
}else{
return {status:true,message:"invalid argument"};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Post('update-lift')
async Update(@Body() body) {
try {
const data = body;
const usre_id = body.user.id;
delete data.user;
data['user_id']=usre_id;
const lift_id = body.id;
if(!body.id){
return {"status":false,message:'provide valid parameter'};
}
const updatelift = await this.liftService.update(lift_id,data);
if(updatelift){
return {status:true,message:"lift updated successfully"};
}else{
return {status:true,message:"invalid argument"};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Get('fetch-my-lift')
async fetchMyLift(@Body() body) {
const myid = body.user.id;
const inter = [];
const intra = [];
const fetchlift = await this.liftService.myAllList(myid);
fetchlift.map((item,index)=>{
console.log(item['type']+",,"+index);
if(item['type'] == 'intra'){
const data ={
"id" : item['_id'],
"passenger" : item['passenger'],
"price" : item['price'],
"to" : item['to']['address'],
"from" : item['from']['address'],
"is_active" : item['is_active'],
"is_virtual": (item['is_virtual']) ? item['is_virtual'] : false
};
intra.push(data);
}else if(item['type'] == 'inter'){
const data ={
"id": item['_id'],
"passenger": item['passenger'],
"price": item['price'],
"to": item['to']['address'],
"from": item['from']['address'],
"is_active": item['is_active'],
"is_virtual": (item['is_virtual']) ? item['is_virtual'] : false
};
inter.push(data);
}
})
return {"status":true,data:{inter:inter,intra:intra}};
// return fetchlift;
}
@Post('search-lift')
async SearchLift(@Body() body) {
try {
const data = body;
let id = body.user.id;
delete body.user;
var searchLift = await this.liftService.searchLift(body,id);
var searchDate = body.occasional_date;
var liftData = [];
//searchLift = JSON.parse(JSON.stringify(searchLift));
//return moment(body.occasional_time, 'HH:mm A').add(10, 'minutes').format('HH:mm A');
var inputdate1 = moment(body.occasional_time, 'HH:mm A').subtract(120, 'minutes').format('HH:mm');
var inputdate2 = moment(body.occasional_time, 'HH:mm A').add(120, 'minutes').format('HH:mm');
if(searchLift.length > 1){ //if data more then 1
searchLift.map((item,index)=>{
const lift ={
"id": item['_id'],
"driver_id":item['user_id'],
"price": item['price'],
"distance": item['distance'],
"passenger": item['passenger'],
"car": item['pick_preferences']['car'],
"date":searchDate,
};
if(body.occasional_date){ // check date
var dayname = moment(body.occasional_date, "D MMM YYYY").format("dddd");
dayname = 'Every '+dayname; // if rider create ride frequently chek acoording date if date to weekly
const date1 = moment(item['departure_time'], 'HH:mm A').format('HH:mm');
if((body.occasional_date == item['occasional'] || item['frequent'].includes(dayname))
){
if(date1 >=inputdate1 && date1 <=inputdate2 && body.is_pick_preference){
liftData.push(lift)
}else if(!body.is_pick_preference){
liftData.push(lift)
}
}
}
})
}else if (searchLift.length > 0){ // if data only one
const lift ={
"id": searchLift[0]['_id'],
"driver_id":searchLift[0]['user_id'],
"price": searchLift[0]['price'],
"distance": searchLift[0]['distance'],
"passenger": searchLift[0]['passenger'],
"car": searchLift[0]['pick_preferences']['car'],
"date":searchDate
};
const date1 = moment(searchLift[0]['departure_time'], 'HH:mm A').format('HH:mm');
if(body.occasional_date){ // check date
var dayname = moment(body.occasional_date, "D MMM YYYY").format("dddd");
dayname = 'Every '+dayname; // if rider create ride frequently chek acoording date if date to weekly
if((body.occasional_date == searchLift[0]['occasional'] || searchLift[0]['frequent'].includes(dayname))
){
if(date1 >=inputdate1 && date1 <=inputdate2 && body.is_pick_preference){
liftData.push(lift)
}else if(!body.is_pick_preference){
liftData.push(lift)
}else{
return {"status":true,data:liftData,message:"no data found"};
}
}
}
}else{
return {"status":true,data:liftData,message:"no data found"};
}
return {"status":true,data:liftData};
}catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Get('fetch-all')
findAll() {
return this.liftService.findAll();
}
@Get('fetch-single-lift/:id')
async findSinfetchgleLift(@Param('id') id: any) {
try{
const lift = await this.liftService.findOne(id);
if(lift){
var data = JSON.parse(JSON.stringify(lift));
data['id'] = data._id;
delete data._id;
delete data.__v;
return {"status":true,data:data};
}else{
return {"status":false,message:"no data found"};
}
}catch(e){
return {"status":false,message:e};
}
}
@Post('update-lift-status')
async findOne(@Body() body) {
try{
const data ={
is_active:body['is_active']
}
const id = body['lift_id'];
if(body['is_active'] != true && body['is_active'] != false){
return {"status":false,message:'your status not valid'};
}
const updateLiftStatus = await this.liftService.update(id,data);
if(updateLiftStatus){
return {status:true,message:"lift Updated successfully"};
}else{
return {status:false,message:"this id not match our record"};
}
}catch(e){
return {"status":false,message:e};
}
}
@Post('get-route-image')
async getStaticImageRoute(@Body() body) {
try{
const to = body.to;
const from = body.from;
const response = await fetch('https://maps.googleapis.com/maps/api/directions/json?origin='+to+'&destination='+from+'&mode=driving&key='+GOOGEL_MAP_KEY+'', {
method: 'GET',
headers: {'Content-Type': 'application/json'}
});
const data = await response.json();
const url = 'https://maps.googleapis.com/maps/api/staticmap?size=360x800&maptype=roadmap&scale=2&markers=size:mid|color:red|'+body.to+'|'+body.from+'&path=weight:2|enc%3A'+data.routes[0].overview_polyline.points+'&key='+GOOGEL_MAP_KEY+'';
return {status:true, url:url};
}catch(e){
return {"status":false,message:e};
}
}
@Get('get-place-api')
async getPlaceApi(){
const response = await fetch('https://maps.googleapis.com/maps/api/directions/json?origin=28.5355,77.3910&destination=28.9845,77.7064&sensor=true&avoid=highways&mode=driving&alternatives=true&key='+GOOGEL_MAP_KEY+'', {
method: 'GET',
headers: {'Content-Type': 'application/json'}
});
const data = await response.json();
return data;
}
@Post('create-lift-request')
async LiftRequestFromUSer(@Body() body) {
try {
const data = body;
const usre_id = body.user.id;
delete data.user;
data['user_id']=usre_id;
const lift_id = body.lift_id;
body['user_status'] = 'inititate';
body['driver_status'] = 'pending';
body['created_at'] = moment().format('LLL');
body['created_at_time'] = moment().format('YYYYMMDDhmm');
if(!body['passenger'] || !body['lift_id'] || !body['driver_id'] || !body['date']){
return {"status":false,message:'provide valid parameter'};
}
const chekLiftExits = await this.liftService.findOne(lift_id);
console.log(chekLiftExits)
if(!chekLiftExits){
return {"status":false,message:'this lift not match our record'};
}
const checkRequest = await this.liftService.checkRequestExits(data);
if(checkRequest){
return {"status":true,message:'your request already in process'};
}
const userdata = await this.usersService.findDataFromId(usre_id);
var useramount = parseInt(userdata['wallet_amount_user']);
var liftamount = parseInt(userdata['wallet_amount_user']) * parseInt(body['passenger']);
if(useramount < parseInt(chekLiftExits['price'])){
return {"status":false,message:'your wallet amount is low'};
}
const liftRequest = await this.liftService.createdLiftRequest(data);
if(liftRequest){
const notificationData={
'lift_request_id':liftRequest._id,
'user_id' :liftRequest.user_id,
'notify_from' :'user',
'driver_id' :liftRequest.driver_id,
'message' :'has sent requested a seat',
'created_at' :moment().format('DD/MM/YYYY h:mm A')
}
const notification = await this.liftService.createdNotification(notificationData);
const searchUser = await this.usersService.findDataFromId(liftRequest.user_id);
const searchDriver = await this.usersService.findDataFromId(liftRequest.driver_id);
if(searchUser && searchDriver){
let name = searchUser['first_name']+' '+searchUser['last_name'];
let bodymsg = name+' has sent you a request for '+data['passenger']+' seat';
await this.helperService.pushNotifications(searchDriver['fcm'],'vyno',bodymsg);
}
return {status:true,message:"request created successfully"};
}else{
return {status:true,message:"something went wrong"};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Get('get-lift-request/:role')
async fetchUserRequest(@Body() body,@Param('role') roles: string) {
try {
const user_id = body.user.id;
const role = ["user", "driver"];
const roleType = roles;
const inter =[];
const intra =[];
const all =[];
if(!role.includes(roles)){
return {"status":false,message:'provide valid parameter'};
}
if(roles == 'user'){
var myLiftRequest = await this.liftService.myLiftUserRequest(user_id);
var myVirtualLift = await this.liftService.myVirtualLiftRequest(user_id);
myVirtualLift.map((item,index)=>{
const data ={};
data['type'] = item.type;
data['to'] = item.to.address;
data['from'] = item.from.address;
data['passenger'] = item.passenger;
data['distance'] = (item.distance) ? item.distance : '';
data['price'] = (item.price) ? item.price : '';
data['profile'] = (item.user[0].profile) ? item.user[0].profile : '';
data['rating'] = Math.floor(Math.random() * (5 - 2 + 1) + 2);
data['lift_request_id'] = item._id;
data['name'] = item.user[0].first_name +' ' + item.user[0].last_name;
data['status'] = (item.approval) ? 'accepted' : 'pending';
data['is_virtual'] = true;
data['created_at'] = item.created_at;
if(item.type == 'intra'){
intra.push(data);
}else if(item.type == 'inter'){
inter.push(data);
}
all.push(data);
});
}else if(roles == 'driver'){
var myLiftRequest = await this.liftService.myLiftDriverRequest(user_id);
}
myLiftRequest.map((item,index)=>{
// console.log(item);
if(item.lift[0].type == 'intra'){
const data ={};
data['type'] = item.lift[0].type;
data['to'] = item.lift[0].to.address;
data['from'] = item.lift[0].from.address;
data['passenger'] = item.passenger;
data['distance'] = (item.lift[0].distance) ? item.lift[0].distance : '';
data['price'] = (item.lift[0].price) ? item.lift[0].price : '';
data['profile'] = (item.lift[0].profile) ? item.lift[0].profile : '';
data['rating'] = Math.floor(Math.random() * (5 - 2 + 1) + 2);
data['lift_request_id'] = item._id;
data['name'] = item.rider[0].first_name +' ' + item.rider[0].last_name;
data['status'] = item.driver_status;
data['is_virtual'] = false;
data['created_at'] = moment(item.created_at).format('DD/MM/YYYY h:mm A');
intra.push(data);
if(roles == 'driver' && data['status'] == 'pending'){
all.push(data);
}
}else if(item.lift[0].type == 'inter'){
const data ={};
data['type'] = item.lift[0].type;
data['to'] = item.lift[0].to.address;
data['from'] = item.lift[0].from.address;
data['passenger'] = item.passenger;
data['distance'] = (item.lift[0].distance) ? item.lift[0].distance : '';
data['price'] = (item.lift[0].price) ? item.lift[0].price : '';
data['profile'] = (item.lift[0].profile) ? item.lift[0].profile : '';
data['rating'] = Math.floor(Math.random() * (5 - 2 + 1) + 2);
data['lift_request_id'] = item._id;
data['name'] = item.rider[0].first_name +' ' + item.rider[0].last_name;
data['status'] = item.driver_status;
data['is_virtual'] = false;
data['created_at'] = moment(item.created_at).format('DD/MM/YYYY h:mm A');
inter.push(data);
if(roles == 'driver' && data['status'] == 'pending'){
all.push(data);
}
}
})
return {"status":true,data:{inter:inter,intra:intra,all:all}};
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Post('action-lift-request')
async accepctRejectLiftRequst(@Body() body) {
try {
const action = ["accepted", "rejected"];
var data={};
data['lift_request_id'] = body.lift_request_id;
data['action'] = body.action;
if(!body['action'] || !body['lift_request_id']){
return {"status":false,message:'provide valid parameter'};
}else if(!action.includes(body['action'])){
return {"status":false,message:'action not match our record'};
}else{
if(body['action'] == 'accepted'){
const liftRequestAccepted = await this.liftService.actionLiftRequest(data);
if(liftRequestAccepted){
const fetchLift = await this.liftService.findOne(liftRequestAccepted['lift_id']);
if(fetchLift){
var bookingdata={
'lift_request_id' :body['lift_request_id'],
'user_id' :liftRequestAccepted['user_id'],
'driver_id' :liftRequestAccepted['driver_id'],
'to' :fetchLift['to'],
'from' :fetchLift['from'],
'price' :fetchLift['price'],
'passenger' :fetchLift['passenger'],
'distance' :fetchLift['distance'],
'date' :liftRequestAccepted['date'],
'created_at' :moment().format('DD/MM/YYYY h:mm A')
};
const booking = await this.liftService.createdLiftBooking(bookingdata);
if(booking){
var userDeductAmount = parseInt(fetchLift['price']) * parseInt(liftRequestAccepted['passenger'])
//for amount deduct user and add amount in buffer
await this.addAmountInVirtualBuffer(booking['user_id'],booking['_id'],userDeductAmount);
//
const notificationData={
'lift_request_id':body['lift_request_id'],
'user_id' :liftRequestAccepted['user_id'],
'notify_from' :'driver',
'driver_id' :liftRequestAccepted['driver_id'],
'message' :'has accepted your lift request',
'created_at' :moment().format('DD/MM/YYYY h:mm A')
}
const notification = await this.liftService.createdNotification(notificationData);
//push notifications
const searchDriver = await this.usersService.findDataFromId(liftRequestAccepted['driver_id']);
const searchUser = await this.usersService.findDataFromId(liftRequestAccepted['user_id']);
if(searchUser && searchDriver){
let bodymsg = searchDriver['first_name']+' '+searchDriver['first_name']+' has accepted your request for '+fetchLift['passenger']+' seat';
this.helperService.pushNotifications(searchUser['fcm'],'vyno',bodymsg);
}
//push notifications
return {"status":true,message:'you accepcted this ride'};
}
}
}
}else if(body['action'] == 'rejected'){
const liftRequestRejected = await this.liftService.actionLiftRequest(data);
if(liftRequestRejected){
const notificationData={
'lift_request_id':body['lift_request_id'],
'user_id' :liftRequestRejected['user_id'],
'notify_from' :'driver',
'driver_id' :liftRequestRejected['driver_id'],
'message' :'has rejected your lift request',
'created_at' :moment().format('DD/MM/YYYY h:mm A')
}
const notification = await this.liftService.createdNotification(notificationData);
const searchDriver = await this.usersService.findDataFromId(liftRequestRejected['driver_id']);
const searchUser = await this.usersService.findDataFromId(liftRequestRejected['user_id']);
if(searchUser && searchDriver){
let bodymsg = searchDriver['first_name']+' '+searchDriver['first_name']+' has rejected your lift request';
this.helperService.pushNotifications(searchUser['fcm'],'vyno',bodymsg);
}
return {"status":true,message:'lift request rejected successfully'};
}else{
return {"status":false,message:'request not match our record'};
}
}
}
} catch(e){
}
}
async addAmountInVirtualBuffer(user_id,booking_id,amount){
const userdata = await this.usersService.findDataFromId(user_id);
var useramount = parseInt(userdata['wallet_amount_user']) - parseInt(amount);
var virtulBufferData= {
'user_id':user_id,
'booking_id':booking_id,
'amount' :amount,
'created_at': moment().format('DD/MM/YYYY h:mm A')
};
const updatevirtualBuffer = await this.liftService.addAmountInVirtualBuffer(virtulBufferData);
if(updatevirtualBuffer){
const userdata = await this.usersService.update(user_id,{'wallet_amount_user':useramount});
return userdata;
}
}
@Post('my-booking')
async myBooking(@Body() body) {
try{
const id = body.user.id;
const role = body.role;
const roledata = (role == 'user') ? 'driver' : 'user';
const action = ["user", "driver"];
if(!body['role'] || !action.includes(body['role'])){
return {"status":false,message:'provide valid parameter'};
}
const myBookingData = await this.liftService.myBookingData(id,role);
if(myBookingData){
myBookingData.map((item,index) => {
item['booking_id'] = item._id;
item['to'] = item.to.address;
item['from'] = item.from.address;
delete item._id;
delete item.__v;
const user = item[roledata][0];
delete item[roledata];
item['user_info'] ={
"profile":user.profile,
"name" :user.first_name+' '+user.last_name,
"rating" :Math.floor(Math.random() * 5)
};
})
return {"status":true,data:myBookingData};
}else{
return {"status":true,message:'no data found'};
}
}catch(e){
return {"status":false,message:e};
}
}
@Get('active-booking/:id')
async activeLift(@Body() body,@Param('id') id: any) {
try{
const lift = await this.liftService.activeBooking(id);
if(lift){
return {"status":true,message:'your booking active now'};
}else{
return {"status":false,message:"no data found"};
}
}catch(e){
return {"status":false,message:e};
}
}
@Get('get-booking-user-info')
async getBookingUserInfo(@Body() body) {
try{
const id = body.user.id;
// const date = moment().format('DD MMM YYYY');
const date = '27 Dec 2021';
const user = [];
const driver = [];
const getBookingUserInfo = await this.liftService.fetchTodayBooking(id,date);
getBookingUserInfo.map((item,index)=>{
if(item.driver_id == id){ // user
let data = {
'booking_id' :item._id,
'user_id' :item.user_id,
'name' : item.user[0].first_name+' '+item.user[0].last_name,
'profile' : item.user[0].profile,
'phone_number' : item.user[0].phone_number,
'rating' : 5,
'passenger':(item.passenger) ? item.passenger : 0,
'distance' : (item.distance) ? item.distance : 0,
'price' : (item.price) ? item.price : 0,
};
driver.push(data);
}else if(item.user_id == id){ //driver
let data = {
'booking_id' :item._id,
'driver_id' :item.driver_id,
'name' : item.driver[0].first_name+' '+item.driver[0].last_name,
'profile' : item.driver[0].profile,
'phone_number': item.driver[0].phone_number,
'rating' : 5,
'passenger' :(item.passenger) ? item.passenger : 0,
'distance' : (item.distance) ? item.distance : 0,
'price' : (item.price) ? item.price : 0,
};
user.push(data);
}
})
return {"status":true,user:{'driver_info':(user.length > 0) ? user : 'no data found'},driver:driver};
}catch(e){
return {"status":false,message:e};
}
}
@Post('my-notifications')
async myNotifications(@Body() body) {
const action = ["user", "driver"];
if(!body['role'] || !action.includes(body['role'])){
return {"status":false,message:'provide valid parameter'};
}
if(body['role'] == 'user'){
const fetchNotification = await this.liftService.fetchNotificationUser(body.user.id);
fetchNotification.map((item,index)=>{
item['notification_id'] = item['_id'];
item['name'] = item.rider[0].first_name +' '+ item.rider[0].last_name;
item['profile'] = item.rider[0].profile;
item['created_at']= moment(item['created_at'],'DD/MM/YYYY h:mm A').format('YYYY-MM-DD H:mm:ss');
delete item['_id'];
delete item['__v'];
delete item['rider'];
});
return {"status":true,data:fetchNotification};
}else{
const fetchNotification = await this.liftService.fetchNotificationDriver(body.user.id);
fetchNotification.map((item,index)=>{
item['notification_id'] = item['_id'];
item['name'] = item.user[0].first_name +' '+ item.user[0].last_name;
item['profile'] = item.user[0].profile;
item['created_at']= moment(item['created_at'],'DD/MM/YYYY h:mm A').format('YYYY-MM-DD H:mm');
delete item['user'];
delete item['_id'];
delete item['__v'];
});
return {"status":true,data:fetchNotification};
}
}
@Post('delete-notifications')
async deleteNotifications(@Body() body) {
try{
var notification_id = body['notification_id'];
if(!notification_id || notification_id.length < 1){
return {"status":false,message:'provide valid parameter'};
}
const deleteNotification = await this.liftService.deleteAllNotification(notification_id);
if(deleteNotification.deletedCount > 0){
return {"status":true,message:'notifications delete successfully'};
}else{
return {"status":false,message:'this data not match our records'};
}
}catch(e){
return {"status":false,message:'this data not match our records'};
}
}
@Post('create-virtual-lift')
async createVirtualLift(@Body() body) {
try {
const data = body;
const id = body.user.id;
delete data.user;
data['user_id'] = id;
var to = {lat: body.to.lat,lon: body.to.long};
var from = {lat: body.from.lat,lon: body.from.long};
var distanceCalculate = Distance.between(to, from);
body['distance'] = distanceCalculate.human_readable().distance;
data['created_at'] = moment().format('DD/MM/YYYY h:mm A')
const createlift = await this.liftService.createVirtualLift(data);
if(createlift){
return {status:true,message:"virtual lift created successfully"};
}else{
return {status:true,message:"invalid argument"};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Get('get-virtual-lift')
async getVirtualLift(@Body() body) {
try {
const user_id = body.user.id;
var virtualLift = await this.liftService.getVirtualLift(user_id);
virtualLift = JSON.parse(JSON.stringify(virtualLift));
const inter =[];
const intra =[];
if(virtualLift.length > 0){
virtualLift.map((item,index)=>{
var data={};
data['name'] = item.user[0].first_name+' '+item.user[0].last_name;
data['profile'] = item.user[0].profile;
data['passenger'] = item.passenger;
data['to'] = item.to.address;
data['from'] = item.from.address;
data['created_at'] = item.created_at;
data['virtual_lift_price'] = item.virtual_lift_price;
data['virtual_lift_id'] = item._id;
delete item._id;
delete item.user;
delete item.__v;
var is_rejected = 0;
if(item.rejected_id && item.rejected_id.includes(body.user.id)){
is_rejected = 1;
}
if(item.type == 'inter' && is_rejected == 0 && !item.accepted_id){
inter.push(data);
}else if(item.type == 'intra' && is_rejected == 0 && !item.accepted_id){
intra.push(data);
}
})
return {status:true,data:{'inter':inter,'intra':intra}};
}else{
return {status:true,message:"no virtual lift found"};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Post('get-virtual-lift-details')
async getSingleVirtualLift(@Body() body) {
try {
const id = body.virtual_lift_id;
if(!body['virtual_lift_id']){
return {"status":false,message:'provide valid parameter'};
}
var virtualLift = await this.liftService.getVirtualLiftDetails(id);
virtualLift = JSON.parse(JSON.stringify(virtualLift));
if(virtualLift){
virtualLift['id'] = virtualLift._id;
delete virtualLift._id;
delete virtualLift.__v;
delete virtualLift['user_id'];
return {status:true,data:virtualLift};
}else{
return {status:true,message:"no virtual lift found"};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Post('virtual-lift-accept-user')
async virtualLiftAcceptUser(@Body() body) {
try{
const lift_id = body['lift_request_id'];
const notification_id = body['notification_id'];
if(!lift_id || !notification_id){
return {"status":false,message:'provide valid parameter'};
}
const approvalVirtuallift = await this.liftService.approvalVirtualLift(lift_id);
if(approvalVirtuallift){
var data = JSON.parse(JSON.stringify(approvalVirtuallift))
data['user_id'] = data['accepted_id'];
data['is_virtual'] = true;
delete data['rejected_id'];
delete data.__v;
delete data._id;
delete data['created_at'];
delete data['updated_at'];
delete data['approval'];
delete data['accepted_id'];
const createlift = await this.liftService.create(data);
if(createlift){
var bookingdata={
'user_id' :body.user.id,
'driver_id' :createlift['user_id'],
'to' :createlift['to'],
'from' :createlift['from'],
'price' :createlift['price'],
'passenger' :createlift['passenger'],
'distance' :createlift['distance'],
'date' :createlift['occasional'],
'is_virtual' :true,
'created_at' :moment().format('DD/MM/YYYY h:mm A')
};
const booking = await this.liftService.createdLiftBooking(bookingdata);
if(booking){
const deleteNotification = await this.liftService.deleteAllNotification([notification_id]);
return {"status":true,message:'accepted successfully'};
}else{
const deletelift = await this.liftService.deleteLift(createlift['_id']);
return {"status":true,message:'something went wrong'};
}
}
}else{
return {"status":false,message:'this lift not exits our record'};
}
}catch(e){
return {"status":false,message:'something went wrong'};
}
}
@Post('virtual-lift-reject-user')
async virtualLiftRejectUser(@Body() body) {
const lift_id = body['lift_request_id'];
const notification_id = body['notification_id'];
if(!lift_id || !notification_id){
return {"status":false,message:'provide valid parameter'};
}
const rejectVirtualLiftFromUser = await this.liftService.removeVirtualLiftFromuser(lift_id);
if(rejectVirtualLiftFromUser && rejectVirtualLiftFromUser.modifiedCount > 0){
const deleteNotification = await this.liftService.deleteAllNotification([notification_id]);
return {"status":true,message:'rejected successfully'};
}else{
return {"status":false,message:'this lift not exits our record'};
}
}
@Post('virtual-lift-accept-reject')
async virtualLiftAcceptReject(@Body() body) {
try {
const action = ["rejected", "accepted"];
const driver_id = body.user.id;
const price = body.price;
var updatedData = body;
var lift_id =body['virtual_lift_id'];
if(!body['action'] || !lift_id || !action.includes(body['action'])){
return {"status":false,message:'provide valid parameter'};
}
var virtualLift = await this.liftService.getVirtualLiftDetails(lift_id);
virtualLift = JSON.parse(JSON.stringify(virtualLift));
if(!virtualLift || virtualLift['accepted_id']){
return {"status":false,message:'this lift has been already taken by another rider'};
}else if(body['action'] == 'rejected'){
if(virtualLift['rejected_id']){
const old_data = virtualLift['rejected_id'];
old_data.push(body.user.id);
const updateData = await this.liftService.updateVirtualLiftDetails(lift_id,old_data);
return {"status":true,message:'updated successfully'};
}else{
const updateData = await this.liftService.updateVirtualLiftDetails(lift_id,[body.user.id]);
return {"status":true,message:'updated successfully'};
}
}else if(body['action'] == 'accepted'){
delete updatedData.action;
delete updatedData.user;
delete updatedData.virtual_lift_id;
updatedData['accepted_id'] = driver_id;
updatedData['updated_at'] = moment().format('DD/MM/YYYY h:mm A');
const acceptVirtualLiftFromDriver = await this.liftService.acceptVirtualLiftFromDriver(lift_id,updatedData);
if(acceptVirtualLiftFromDriver){
const notificationData={
'lift_request_id' :acceptVirtualLiftFromDriver._id,
'user_id' :acceptVirtualLiftFromDriver['user_id'],
'notify_from' :'driver',
'driver_id' :driver_id,
'is_virtual' :true,
'virtual_lift_price' :price,
'message' :'has accepted your virtual lift request',
'created_at' :moment().format('DD/MM/YYYY h:mm A')
}
const user_id = acceptVirtualLiftFromDriver['user_id'];
this.createAndSendNotifications(notificationData,driver_id,user_id);
return {"status":true,message:'accepted successfully'};
}
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
@Post('cancle-booking')
async cancleBooking(@Body() body) {
try{
const booking_id = body.booking_id;
const my_role = body.myrole;
const user_id = body.user.id;
body['user_id'] = body.user.id;
delete body.user;
var action = ["user", "driver"];
if(!booking_id || !my_role || !action.includes(my_role)){
return {"status":false,message:'provide valid parameter'};
}
var cancleBooking = await this.liftService.cancleBooking(body);
if(cancleBooking
&& Object.keys(cancleBooking).length !== 0){
const getVirtualBuffer = await this.liftService.getVirtualBuffer(booking_id);
if(getVirtualBuffer){
var bufferId = getVirtualBuffer['_id'];
let userid = getVirtualBuffer['user_id'];
let amount = getVirtualBuffer['amount'];
const getUserData = await this.usersService.findDataFromId(userid);
const walleteAmount = getUserData["wallet_amount_user"];
const newAmount = getUserData["wallet_amount_user"] + parseInt(amount);
const updateWallete = await this.usersService.update(userid,{'wallet_amount_user':newAmount});
if(updateWallete){
const removeDataFromVirtualBuffer = await this.liftService.removeBufferData(bufferId);
return {"status":true,message:'cancle successfully'};
}
}else{
return {"status":false,message:'this booking already cancle'};
}
}else{
return {"status":false,message:'this booking not found our record'};
}
} catch(e){
if(e.hasOwnProperty('errors')){
return {"status":false,message:e};
}else{
return {"status":false,message:e};
}
}
}
async createAndSendNotifications(notificationData,driver_id,user_id,is_create_notification = false){
console.log(notificationData)
const notification = await this.liftService.createdNotification(notificationData);
console.log(notification);
const searchDriver = await this.usersService.findDataFromId(driver_id);
const searchUser = await this.usersService.findDataFromId(user_id);
if(searchUser && searchDriver){
let bodymsg = searchDriver['first_name']+' '+searchDriver['last_name']+' '+notificationData.message;
this.helperService.pushNotifications(searchUser['fcm'],'vyno',bodymsg);
}
}
}
|
lakshay-pant/vynoFinalBack | dist/src/lift/schemas/liftNotification.schema.d.ts | <reponame>lakshay-pant/vynoFinalBack<gh_stars>0
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
import { LiftRequest } from './liftRequest.schema';
export declare type LiftNotificationDocument = LiftNotification & Document;
export declare class LiftNotification {
lift_request_id: LiftRequest;
user_id: User;
driver_id: User;
notify_from: string;
message: string;
is_virtual: boolean;
virtual_lift_price: string;
created_at: string;
updated_at: string;
}
export declare const LiftNotificationSchema: mongoose.Schema<Document<LiftNotification, any, any>, mongoose.Model<Document<LiftNotification, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/payment/schemas/payment.schema.ts | <filename>src/payment/schemas/payment.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export type PaymentDocument = Payment & Document;
@Schema()
export class Payment {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop()
request_uuid: string;
@Prop()
amount: string;
@Prop()
status: string;
@Prop()
message:string;
@Prop()
created_at: string;
}
export const PaymentSchema = SchemaFactory.createForClass(Payment); |
lakshay-pant/vynoFinalBack | src/address/dto/create-address.dto.ts | export class CreateAddressDto {}
|
lakshay-pant/vynoFinalBack | dist/src/payment/schemas/payment.schema.d.ts | <filename>dist/src/payment/schemas/payment.schema.d.ts
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export declare type PaymentDocument = Payment & Document;
export declare class Payment {
user_id: User;
request_uuid: string;
amount: string;
status: string;
message: string;
created_at: string;
}
export declare const PaymentSchema: mongoose.Schema<Document<Payment, any, any>, mongoose.Model<Document<Payment, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | dist/src/singup/entities/singup.entity.d.ts | <reponame>lakshay-pant/vynoFinalBack
export declare class Singup {
}
|
lakshay-pant/vynoFinalBack | src/users/users.controller.ts | <gh_stars>0
import { Controller, Get, Post, Res, Body, Patch, Param, Delete, ParseIntPipe, UseInterceptors, UploadedFile, UploadedFiles} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor ,FileFieldsInterceptor ,AnyFilesInterceptor } from "@nestjs/platform-express";
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User, UserSchema } from './schemas/user.schema';
import { HelperService } from '../common/helper';
import * as moment from 'moment';
import { JwtService } from '@nestjs/jwt';
import { Request, Response, NextFunction } from 'express';
import * as fs from "fs";
import { time } from 'console';
import { connected } from 'process';
const mime = require('mime');
var mongoose = require('mongoose');
@Controller({path:'user',version:'1'})
export class UsersController {
constructor(
private readonly usersService: UsersService,
private jwtService: JwtService,
private helperService:HelperService
) {
}
@Get('allUser')
findAll() {
return this.usersService.findAll();
}
@Get('account-status')
async accountStatus(@Body() body) {
const id = body.user.id;
const finduser = await this.usersService.findDataFromId(id);
if(finduser && finduser['account_status']){
return {status:true,data:{account_status:finduser['account_status']}};
}else{
return {"status":true,data:{account_status:''}};
}
}
@Get('my-profile')
async myProfile(@Body() body) {
const id = body.user.id;
const finduser = await this.usersService.findDataFromId(id);
if(finduser){
return {status:true,data:finduser};
}else{
return {"status":false,message:"User not found"};
}
}
@Post('/update')
async updateUser(@Body() updateUserDto: UpdateUserDto) {
try{
if(updateUserDto.hasOwnProperty('profile')){
var imgBase64 = updateUserDto['profile'];
const uploadfile = this.helperService.base64ImageUpload(imgBase64);
if(uploadfile.status != true){
return {status:true,message:"invalid format of images"};
}else{
updateUserDto['profile'] = uploadfile.path;
}
}
const id = updateUserDto['user'].id;
delete updateUserDto['user'];
delete updateUserDto['otp'];
delete updateUserDto['phone_number'];
delete updateUserDto['account_verify'];
const updateUser = await this.usersService.update(id,updateUserDto);
if(updateUser){
const finduser = await this.usersService.findDataFromId(id);
return {status:true,message:"updated successfully",data:{profile:finduser['profile']}};
}else{
return {status:true,message:"User not found"};
}
}catch (e) {
return {"status":false,message:e};
}
}
@Post('/ratingReview')
async ratingReview(@Body() body) {
try{
var user_id = body.user.id;
var to = body.to;
var rating = body.rating;
var rating_for = body.rating_for;
var action = ["user", "driver"];
body['created_at'] = moment().format('DD/MM/YYYY h:mm A');
delete body.user;
if(!to || !rating || !action.includes(rating_for)) {
return {"status":false,message:'provide valid parameter'};
}else{
const finduser = await this.usersService.review(body);
if(finduser){
return {status:true,message:"successfully"}
}else{
return {status:true,message:"went somthing wrong"};
}
}
}catch (e) {
return {"status":false,message:e};
}
}
@Get('my-wallet')
async myWallet(@Body() body,@Param('role') roles: string) {
const user_id = body.user.id;
const finddata = await this.usersService.findDataFromId(user_id);
if(finddata){
return {"status":true,wallet_user:finddata['wallet_amount_user'],wallet_driver:finddata['wallet_amount_driver']};
}
}
// @Post('/upload-document')
// @UseInterceptors(AnyFilesInterceptor())
// async uploadFile(@Body() body,@UploadedFiles() files: Array<Express.Multer.File>) {
// try{
// var i = 0;
// var fielddata = [];
// var id = body.id;
// var updateUser;
// if(Array.isArray(files) && files.length){
// for (let i = 0; i < files.length; i++) {
// fielddata[files[i].fieldname] = files[i].path;
// const extension = files[i].mimetype.split("/")[1];
// fs.rename(files[i].path, files[i].path+'.'+extension, function(err) {
// });
// if(!id){
// console.log("delete"+" "+files[i].path+'.'+extension)
// fs.unlinkSync(files[i].path+'.'+extension);
// }else{
// const updateUserDocument = {
// [files[i].fieldname] : files[i].path+'.'+extension
// };
// updateUser = await this.usersService.update(id,updateUserDocument);
// }
// if( i == files.length - 1 ){
// if(!id){
// return {status:false , message:"provide valid parameter"};
// }else{
// const documentStatus = {
// 'account_status' : 'pending'
// };
// await this.usersService.update(id,documentStatus);
// return {status:true , message:"document update successfully"};
// }
// }
// }
// }else{
// return {"status":false,message:"minimum 1 file upload"};
// }
// }catch (e) {
// return {"status":false,message:e};
// }
// }
// @Get(':phone')
// async findOne(@Param('phone', ParseIntPipe) phone: string){
// var getData = await this.usersService.findOne(+phone);
// if(getData){
// return {status:'true',data:getData,'message':"find"};
// }else{
// return {status:'true',data:getData,'message':"not found"};
// }
// }
// @Patch(':phone')
// async update(@Param('phone') phone: string, @Body() updateUserDto: UpdateUserDto) {
// const updateUser = await this.usersService.update(+phone, updateUserDto);
// if(updateUser){
// return {status:'true',data:updateUser,'message':"update successfully"};
// }else{
// return {status:'true',data:updateUser,'message':"user not found"};
// }
// console.log(updateUserDto);
// //;
// }
// @Delete(':id')
// remove(@Param('id') id: string) {
// return this.usersService.remove(+id);
// }
}
|
lakshay-pant/vynoFinalBack | src/payment/payment.service.ts | <filename>src/payment/payment.service.ts
import { Injectable } from '@nestjs/common';
import { CreatePaymentDto } from './dto/create-payment.dto';
import { UpdatePaymentDto } from './dto/update-payment.dto';
import { Payment, PaymentSchema } from './schemas/payment.schema';
import { History,HistorySchema } from './schemas/history.schema';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
@Injectable()
export class PaymentService {
constructor(
@InjectModel(Payment.name) private paymentModel: Model<CreatePaymentDto>,
@InjectModel(History.name) private historyModel: Model<{}>
) {}
create(createPaymentDto: CreatePaymentDto) {
try{
const createdlift = new this.paymentModel(createPaymentDto);
return createdlift.save();
} catch(e){
return e;
}
}
historyCreate(data){
try{
const createdlift = new this.historyModel(data);
return createdlift.save();
} catch(e){
return e;
}
}
findAll() {
return `This action returns all payment`;
}
findOne(id: number) {
return `This action returns a #${id} payment`;
}
update(id: number, updatePaymentDto: UpdatePaymentDto) {
return `This action updates a #${id} payment`;
}
remove(id: number) {
return `This action removes a #${id} payment`;
}
}
|
lakshay-pant/vynoFinalBack | src/lift/schemas/virtualBuffer.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import { LiftBooking, LiftBookingSchema } from '../schemas/liftBooking.schema';
import * as mongoose from 'mongoose';
export type VirtualBufferDocument = VirtualBuffer & Document;
@Schema()
export class VirtualBuffer {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'LiftBooking' ,required: true })
booking_id: LiftBooking;
@Prop()
amount: number;
@Prop()
created_at: string;
}
export const VirtualBufferSchema = SchemaFactory.createForClass(VirtualBuffer); |
lakshay-pant/vynoFinalBack | src/singup/singup.module.ts | import { Module } from '@nestjs/common';
import { SingupService } from './singup.service';
import { UsersService } from '../users/users.service';
import { SingupController } from './singup.controller';
import { User, UserSchema } from '../users/schemas/user.schema';
import { RatingReview, RatingReviewSchema } from '../users/schemas/ratingReview.schema';
import { Momo, MomoSchema } from '../users/schemas/momo.schema';
import { MongooseModule } from '@nestjs/mongoose';
import { JwtModule } from '@nestjs/jwt';
import { HelperService } from '../common/helper';
@Module({
imports: [
MongooseModule.forFeature([
{ name: User.name, schema: UserSchema },
{ name: RatingReview.name, schema: RatingReviewSchema },
{ name: Momo.name, schema: MomoSchema },
]),
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '365d' },
}),
],
controllers: [SingupController],
providers: [SingupService,UsersService,HelperService]
})
export class SingupModule {}
|
lakshay-pant/vynoFinalBack | dist/src/document/entities/document.entity.d.ts | export declare class Document {
}
|
lakshay-pant/vynoFinalBack | src/singup/singup.controller.ts | <filename>src/singup/singup.controller.ts<gh_stars>0
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { SingupService } from './singup.service';
import { CreateSingupDto } from './dto/create-singup.dto';
import { UpdateSingupDto } from './dto/update-singup.dto';
import { UsersService } from '../users/users.service';
import { CreateUserDto } from '../users/dto/create-user.dto';
import { UpdateUserDto } from '../users/dto/update-user.dto';
import { User, UserSchema } from '../users/schemas/user.schema';
import { Request, Response, NextFunction } from 'express';
import { HelperService } from '../common/helper';
import { v4 } from 'uuid';
import * as moment from 'moment';
import { ERR_MSG, MOMO} from './../../config/configuration'
let fetch = require('node-fetch');
import { JwtService } from '@nestjs/jwt';
var mongoose = require('mongoose');
@Controller({path:'signup',version:'1'})
export class SingupController {
constructor(
private readonly singupService: SingupService,
private readonly usersService: UsersService,
private jwtService: JwtService,
private helperService:HelperService
) {}
@Post()
async create(@Body() createUserDto: CreateUserDto) {
try{
if(!createUserDto.hasOwnProperty('phone_number') || !createUserDto.hasOwnProperty('country_code')){
return {status:false,message:"provide Valid parameter"};
}
const checkUserExits = await this.usersService.findData({phone_number:createUserDto['phone_number'],country_code:createUserDto['country_code']});
const date= moment().format('DD/MM/YYYY HH:mm:ss');
if(checkUserExits){
createUserDto['updated_at'] = date;
var updateUser = await this.usersService.updateOtp(createUserDto);
updateUser = JSON.parse(JSON.stringify(updateUser));
return {status:true,id:updateUser._id,message:"user updated successfully"};
}else{
createUserDto['first_name'] = '';
createUserDto['last_name'] = '';
createUserDto['email'] = '';
createUserDto['gender'] = '';
createUserDto['dob'] = '';
createUserDto['profession'] = '';
createUserDto['driving_licence'] = '';
createUserDto['cni_number'] = '';
createUserDto['created_at'] = date;
createUserDto['updated_at'] = '';
createUserDto['verify_otp'] = '1234';
createUserDto['role'] = '1';
createUserDto['account_verify'] = '';
createUserDto['account_status'] = '';
var createUser = await this.usersService.create(createUserDto);
createUser = JSON.parse(JSON.stringify(createUser));
if(createUser){
var createMomoCredential = await this.createMomoAccountAndSaveCredential(createUser._id);
createMomoCredential = JSON.parse(JSON.stringify(createMomoCredential));
if(createMomoCredential['_id']){
return {status:true,id:createUser._id,message:"user created successfully"};
}else{
var deleteUser = await this.usersService.deleteUser(createUser._id);
return {status:false,message:ERR_MSG};
}
}
}
}catch (e){
return {status:false,message:e};
}
}
async createMomoAccountAndSaveCredential(user_id){
var url = MOMO.MOMO_URL+ '/v1_0/apiuser';
var uuidv4 = v4();
var header = {
'Content-Type' : 'application/json','Ocp-Apim-Subscription-Key':MOMO.OcpApimSubscriptionKey,
'X-Reference-Id' :uuidv4
};
// for creating user in momo
await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify({
"providerCallbackHost": "string"
})
}).then(async response => {
if(response.status == 201){
var url = MOMO.MOMO_URL+ '/v1_0/apiuser/'+uuidv4+'/apikey';
var header = {
'Ocp-Apim-Subscription-Key':MOMO.OcpApimSubscriptionKey
};
const response = await fetch(url, {
method: 'POST',
headers: header
}).then(async responseData => {
const content = await responseData.json();
const username = uuidv4;
const password = content.apiKey;
const data = {
'user_id' :user_id,
'username' :uuidv4,
'password' :password,
'created_at' :moment().format('DD/MM/YYYY h:mm A')
};
const createMomoCredential = await this.usersService.createMomoCredential(data);
return createMomoCredential;
})
}
});
}
@Post('/verify-otp')
async verifyotp(req: Request, res: Response,@Body() data) {
try {
if(!data.hasOwnProperty('id') || !data.hasOwnProperty('otp') ){
return {status:false,message:"provide Valid parameter"};
}
const verifyotp = await this.usersService.findData({ _id: mongoose.Types.ObjectId(data.id) ,verify_otp:data.otp});
if(verifyotp){
const updatefcm = await this.usersService.update(data.id,{'fcm':data.fcm});
const payload = { id: data.id};
const jwtToken = await this.jwtService.signAsync(payload);
const userdata = this.helperService.removeUnderscoreFromcolumn(verifyotp);
return {status:true,token: jwtToken,data:userdata,message:"otp verify successfully"};
}else{
return {status:false,message:"otp not match"};
}
}catch (err) {
return{ status: false,message:'invalid token' };
}
}
}
|
lakshay-pant/vynoFinalBack | dist/src/users/users.controller.d.ts | <reponame>lakshay-pant/vynoFinalBack<gh_stars>0
/// <reference types="mongoose" />
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { HelperService } from '../common/helper';
import { JwtService } from '@nestjs/jwt';
export declare class UsersController {
private readonly usersService;
private jwtService;
private helperService;
constructor(usersService: UsersService, jwtService: JwtService, helperService: HelperService);
findAll(): Promise<(import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
})[]>;
accountStatus(body: any): Promise<{
status: boolean;
data: {
account_status: any;
};
}>;
myProfile(body: any): Promise<{
status: boolean;
data: import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
};
message?: undefined;
} | {
status: boolean;
message: string;
data?: undefined;
}>;
updateUser(updateUserDto: UpdateUserDto): Promise<{
status: boolean;
message: string;
data: {
profile: any;
};
} | {
status: boolean;
message: any;
data?: undefined;
}>;
ratingReview(body: any): Promise<{
status: boolean;
message: any;
}>;
myWallet(body: any, roles: string): Promise<{
status: boolean;
wallet_user: any;
wallet_driver: any;
}>;
}
|
lakshay-pant/vynoFinalBack | dist/src/admin/dto/create-admin.dto.d.ts | export declare class CreateAdminDto {
}
|
lakshay-pant/vynoFinalBack | dist/config/configuration.d.ts | export declare const GOOGEL_MAP_KEY = "<KEY>";
export declare const USER_ROLE = "0";
export declare const DRIVER_ROLE = "1";
export declare const VIRTUAL_LIFT = true;
export declare const PUSH_NOTIFICATION = true;
export declare const FIREBASE_SERVER_KEY = "<KEY>";
export declare const MOMO_URL = "https://sandbox.momodeveloper.mtn.com";
export declare const OcpApimSubscriptionKey = "<KEY>";
export declare const ERR_MSG = "went something wrong";
export declare const MOMO: {
MOMO_URL: string;
XTargetEnvironment: string;
OcpApimSubscriptionKey: string;
};
|
lakshay-pant/vynoFinalBack | dist/src/address/entities/address.entity.d.ts | export declare class Address {
}
|
lakshay-pant/vynoFinalBack | dist/src/payment/dto/update-payment.dto.d.ts | import { CreatePaymentDto } from './create-payment.dto';
declare const UpdatePaymentDto_base: import("@nestjs/mapped-types").MappedType<Partial<CreatePaymentDto>>;
export declare class UpdatePaymentDto extends UpdatePaymentDto_base {
}
export {};
|
lakshay-pant/vynoFinalBack | src/app.module.ts | <filename>src/app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { UsersModule } from './users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { AuthModule } from './auth/auth.module';
import { SingupModule } from './singup/singup.module';
import { LoginMiddleware } from './common/login.middleware';
import { AdminMiddleware } from './common/admin.middleware';
import { ConfigModule } from '@nestjs/config';
import { ENV } from 'config/environment';
import { AddressModule } from './address/address.module';
import { MulterModule } from '@nestjs/platform-express';
import { AdminModule } from './admin/admin.module';
import { LiftModule } from './lift/lift.module';
import { DocumentModule } from './document/document.module';
import { PaymentModule } from './payment/payment.module';
@Module({
imports: [
MongooseModule.forRoot(ENV.DB_URL),
UsersModule,
JwtModule.register({
secret: 'secretKey',
signOptions: { expiresIn: '365d' },
}),
AuthModule,
SingupModule,
ConfigModule.forRoot(),
AddressModule,
MulterModule.register({
dest: './public/uploads/document/',
}),
ConfigModule.forRoot({ isGlobal: true }),
AdminModule,
LiftModule,
DocumentModule,
PaymentModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoginMiddleware)
.forRoutes('v1/user');
consumer
.apply(LoginMiddleware)
.forRoutes('v1/admin');
consumer
.apply(LoginMiddleware)
.forRoutes('v1/lift');
consumer
.apply(LoginMiddleware)
.forRoutes('v1/address');
consumer
.apply(LoginMiddleware)
.forRoutes('v1/document');
consumer
.apply(LoginMiddleware)
.forRoutes('v1/payment');
}
}
|
lakshay-pant/vynoFinalBack | dist/src/common/helper.d.ts | export declare class HelperService {
base64ImageUpload(imgBase64: any): {
status: string;
message: string;
path?: undefined;
} | {
status: boolean;
path: string;
message?: undefined;
} | {
status: boolean;
message: any;
path?: undefined;
};
documentUpload(data: any): any[] | {
status: string;
message: any;
};
removeUnderscoreFromcolumn(data: any): any;
getReverseGeocodingData(lat: any, lng: any): any;
pushNotifications(fcm_token: any, title_msg: any, msg: any): void;
}
|
lakshay-pant/vynoFinalBack | dist/src/address/address.service.d.ts | import { CreateAddressDto } from './dto/create-address.dto';
import { UpdateAddressDto } from './dto/update-address.dto';
import { Model } from 'mongoose';
export declare class AddressService {
private addressModel;
constructor(addressModel: Model<CreateAddressDto>);
create(createAddressDto: CreateAddressDto): Promise<import("mongoose").Document<any, any, CreateAddressDto> & CreateAddressDto & {
_id: unknown;
}>;
findAll(): string;
findOne(id: number): string;
update(id: number, updateAddressDto: UpdateAddressDto): string;
remove(id: number): string;
}
|
lakshay-pant/vynoFinalBack | src/singup/singup.service.ts | <gh_stars>0
import { Injectable } from '@nestjs/common';
import { CreateSingupDto } from './dto/create-singup.dto';
import { UpdateSingupDto } from './dto/update-singup.dto';
@Injectable()
export class SingupService {
create(createSingupDto: CreateSingupDto) {
return 'This action adds a new singup';
}
findAll() {
return `This action returns all singup`;
}
findOne(id: number) {
return `This action returns a #${id} singup`;
}
update(id: number, updateSingupDto: UpdateSingupDto) {
return `This action updates a #${id} singup`;
}
remove(id: number) {
return `This action removes a #${id} singup`;
}
}
|
lakshay-pant/vynoFinalBack | dist/src/lift/schemas/liftRequest.schema.d.ts | <reponame>lakshay-pant/vynoFinalBack
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
import { Lift } from './lift.schema';
export declare type LiftRequestDocument = LiftRequest & Document;
export declare class LiftRequest {
user_id: User;
lift_id: Lift;
driver_id: User;
passenger: number;
user_status: string;
date: string;
driver_status: string;
created_at: string;
created_at_time: string;
updated_at: string;
}
export declare const LiftRequestSchema: mongoose.Schema<Document<LiftRequest, any, any>, mongoose.Model<Document<LiftRequest, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | dist/src/singup/dto/update-singup.dto.d.ts | import { CreateSingupDto } from './create-singup.dto';
declare const UpdateSingupDto_base: import("@nestjs/mapped-types").MappedType<Partial<CreateSingupDto>>;
export declare class UpdateSingupDto extends UpdateSingupDto_base {
}
export {};
|
lakshay-pant/vynoFinalBack | dist/src/address/address.controller.d.ts | <gh_stars>0
import { AddressService } from './address.service';
import { CreateAddressDto } from './dto/create-address.dto';
export declare class AddressController {
private readonly addressService;
constructor(addressService: AddressService);
create(body: any, createAddressDto: CreateAddressDto): Promise<{
status: boolean;
message: any;
}>;
findAll(): string;
}
|
lakshay-pant/vynoFinalBack | src/lift/schemas/liftBooking.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
import { Lift } from './lift.schema';
import { LiftRequest } from './liftRequest.schema';
export type LiftBookingDocument = LiftBooking & Document;
@Schema()
export class LiftBooking {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'LiftRequest'})
lift_request_id: LiftRequest;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
driver_id: User;
@Prop({type: Object, required: true })
to: {
lat:string,
long:string,
address:string
};
@Prop({type: Object, required: true })
from:{
lat:string,
long:string,
address:string
};
@Prop({ required: true })
passenger: number;
@Prop({ required: true })
price: number;
@Prop({ required: true ,default: false})
is_virtual: boolean;
@Prop({default: ''})
distance: string;
@Prop({
type: String,
required: true
})
date: string;
@Prop({
type: String,
required: true,
default: false
})
is_cancle: boolean;
@Prop({
type: String,
enum: ['user','driver'],
})
cancle_by: string;
@Prop({
type: String,
enum: ['active','completed','inactive'],
default: 'inactive'
})
status: string;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const LiftBookingSchema = SchemaFactory.createForClass(LiftBooking); |
lakshay-pant/vynoFinalBack | dist/src/lift/schemas/liftBooking.schema.d.ts | <filename>dist/src/lift/schemas/liftBooking.schema.d.ts
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
import { LiftRequest } from './liftRequest.schema';
export declare type LiftBookingDocument = LiftBooking & Document;
export declare class LiftBooking {
lift_request_id: LiftRequest;
user_id: User;
driver_id: User;
to: {
lat: string;
long: string;
address: string;
};
from: {
lat: string;
long: string;
address: string;
};
passenger: number;
price: number;
is_virtual: boolean;
distance: string;
date: string;
is_cancle: boolean;
cancle_by: string;
status: string;
created_at: string;
updated_at: string;
}
export declare const LiftBookingSchema: mongoose.Schema<Document<LiftBooking, any, any>, mongoose.Model<Document<LiftBooking, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/singup/singup.controller.spec.ts | import { Test, TestingModule } from '@nestjs/testing';
import { SingupController } from './singup.controller';
import { SingupService } from './singup.service';
describe('SingupController', () => {
let controller: SingupController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [SingupController],
providers: [SingupService],
}).compile();
controller = module.get<SingupController>(SingupController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});
|
lakshay-pant/vynoFinalBack | dist/src/lift/lift.controller.d.ts | <reponame>lakshay-pant/vynoFinalBack
/// <reference types="mongoose" />
import { LiftService } from './lift.service';
import { CreateLiftDto } from './dto/create-lift.dto';
import { HelperService } from '../common/helper';
import { UsersService } from '.././users/users.service';
export declare class LiftController {
private readonly liftService;
private helperService;
private readonly usersService;
constructor(liftService: LiftService, helperService: HelperService, usersService: UsersService);
create(body: any): Promise<{
status: boolean;
message: any;
}>;
Update(body: any): Promise<{
status: boolean;
message: any;
}>;
fetchMyLift(body: any): Promise<{
status: boolean;
data: {
inter: any[];
intra: any[];
};
}>;
SearchLift(body: any): Promise<{
status: boolean;
data: any[];
message: string;
} | {
status: boolean;
data: any[];
message?: undefined;
} | {
status: boolean;
message: any;
data?: undefined;
}>;
findAll(): Promise<(import("mongoose").Document<any, any, CreateLiftDto> & CreateLiftDto & {
_id: unknown;
})[]>;
findSinfetchgleLift(id: any): Promise<{
status: boolean;
data: any;
message?: undefined;
} | {
status: boolean;
message: any;
data?: undefined;
}>;
findOne(body: any): Promise<{
status: boolean;
message: any;
}>;
getStaticImageRoute(body: any): Promise<{
status: boolean;
url: string;
message?: undefined;
} | {
status: boolean;
message: any;
url?: undefined;
}>;
getPlaceApi(): Promise<any>;
LiftRequestFromUSer(body: any): Promise<{
status: boolean;
message: any;
}>;
fetchUserRequest(body: any, roles: string): Promise<{
status: boolean;
data: {
inter: any[];
intra: any[];
all: any[];
};
message?: undefined;
} | {
status: boolean;
message: any;
data?: undefined;
}>;
accepctRejectLiftRequst(body: any): Promise<{
status: boolean;
message: string;
}>;
addAmountInVirtualBuffer(user_id: any, booking_id: any, amount: any): Promise<import("mongoose").Document<any, any, import("../users/dto/create-user.dto").CreateUserDto> & import("../users/dto/create-user.dto").CreateUserDto & {
_id: unknown;
}>;
myBooking(body: any): Promise<{
status: boolean;
data: any;
message?: undefined;
} | {
status: boolean;
message: any;
data?: undefined;
}>;
activeLift(body: any, id: any): Promise<{
status: boolean;
message: any;
}>;
getBookingUserInfo(body: any): Promise<{
status: boolean;
user: {
driver_info: string | any[];
};
driver: any[];
message?: undefined;
} | {
status: boolean;
message: any;
user?: undefined;
driver?: undefined;
}>;
myNotifications(body: any): Promise<{
status: boolean;
message: string;
data?: undefined;
} | {
status: boolean;
data: any;
message?: undefined;
}>;
deleteNotifications(body: any): Promise<{
status: boolean;
message: string;
}>;
createVirtualLift(body: any): Promise<{
status: boolean;
message: any;
}>;
getVirtualLift(body: any): Promise<{
status: boolean;
data: {
inter: any[];
intra: any[];
};
message?: undefined;
} | {
status: boolean;
message: any;
data?: undefined;
}>;
getSingleVirtualLift(body: any): Promise<{
status: boolean;
data: import("mongoose").Document<any, any, {}> & {
_id: unknown;
};
message?: undefined;
} | {
status: boolean;
message: any;
data?: undefined;
}>;
virtualLiftAcceptUser(body: any): Promise<{
status: boolean;
message: string;
}>;
virtualLiftRejectUser(body: any): Promise<{
status: boolean;
message: string;
}>;
virtualLiftAcceptReject(body: any): Promise<{
status: boolean;
message: any;
}>;
cancleBooking(body: any): Promise<{
status: boolean;
message: any;
}>;
createAndSendNotifications(notificationData: any, driver_id: any, user_id: any, is_create_notification?: boolean): Promise<void>;
}
|
lakshay-pant/vynoFinalBack | dist/src/users/users.service.d.ts | <gh_stars>0
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Model } from 'mongoose';
export declare class UsersService {
private userModel;
private ratingReviewModel;
private momoModel;
constructor(userModel: Model<CreateUserDto>, ratingReviewModel: Model<{}>, momoModel: Model<{}>);
create(createUserDto: CreateUserDto): Promise<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}>;
findAll(): Promise<(import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
})[]>;
findData(item: any): Promise<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}>;
findDataFromId(id: any): Promise<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}>;
update(id: any, updateUserDto: UpdateUserDto): import("mongoose").Query<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, {}, CreateUserDto>;
createMomoCredential(data: any): Promise<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}>;
findMomoCredential(user_id: any): Promise<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}>;
updateOtp(item: any): import("mongoose").Query<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, {}, CreateUserDto>;
updateUserWallet(user_id: any, amount: any): import("mongoose").Query<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, {}, CreateUserDto>;
deleteUser(user_id: any): import("mongoose").Query<import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateUserDto> & CreateUserDto & {
_id: unknown;
}, {}, CreateUserDto>;
review(data: any): Promise<import("mongoose").Document<any, any, {}> & {
_id: unknown;
}>;
}
|
lakshay-pant/vynoFinalBack | dist/src/lift/dto/create-lift.dto.d.ts | export declare class CreateLiftDto {
}
|
lakshay-pant/vynoFinalBack | dist/src/payment/entities/payment.entity.d.ts | <gh_stars>0
export declare class Payment {
}
|
lakshay-pant/vynoFinalBack | src/singup/entities/singup.entity.ts | <filename>src/singup/entities/singup.entity.ts
export class Singup {}
|
lakshay-pant/vynoFinalBack | dist/src/document/schemas/document.schema.d.ts | import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export declare type DocumentsDocument = Documents & Document;
export declare class Documents {
user_id: User;
role: string;
driving_licence: string;
cnic: string;
registration: string;
insurance: string;
account_status: string;
created_at: string;
updated_at: string;
}
export declare const DocumentsSchema: mongoose.Schema<Document<Documents, any, any>, mongoose.Model<Document<Documents, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/address/address.service.ts | <gh_stars>0
import { Injectable } from '@nestjs/common';
import { CreateAddressDto } from './dto/create-address.dto';
import { UpdateAddressDto } from './dto/update-address.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Address, AddressSchema } from './schemas/address.schema';
var mongoose = require('mongoose');
@Injectable()
export class AddressService {
constructor(@InjectModel(Address.name) private addressModel: Model<CreateAddressDto>) {}
create(createAddressDto: CreateAddressDto) {
const createdAddress = new this.addressModel(createAddressDto);
return createdAddress.save();
}
findAll() {
return `This action returns all address`;
}
findOne(id: number) {
return `This action returns a #${id} address`;
}
update(id: number, updateAddressDto: UpdateAddressDto) {
return `This action updates a #${id} address`;
}
remove(id: number) {
return `This action removes a #${id} address`;
}
}
|
lakshay-pant/vynoFinalBack | src/document/schemas/document.schema.ts | <reponame>lakshay-pant/vynoFinalBack
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export type DocumentsDocument = Documents & Document;
@Schema()
export class Documents {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop({ required: true })
role: string;
@Prop()
driving_licence: string;
@Prop()
cnic: string;
@Prop()
registration: string;
@Prop()
insurance: string;
@Prop()
account_status: string;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const DocumentsSchema = SchemaFactory.createForClass(Documents); |
lakshay-pant/vynoFinalBack | dist/src/lift/schemas/virtualLift.schema.d.ts | <filename>dist/src/lift/schemas/virtualLift.schema.d.ts
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export declare type VirtualLiftDocument = VirtualLift & Document;
export declare class VirtualLift {
user_id: User;
type: string;
to: {
lat: string;
long: string;
address: string;
};
from: {
lat: string;
long: string;
address: string;
};
passenger: number;
price: number;
departure_time: string;
is_occasional: boolean;
occasional: string;
is_frequent: boolean;
frequent: string;
is_come_back: boolean;
lift_come_back_time: string;
is_pick_preference: boolean;
distance: string;
drop_off: Object;
pick_preferences: {
pickup: Object;
gender: string;
air_condition: string;
pvt_lift: string;
car: string;
};
is_active: boolean;
rejected_id: string;
accepted_id: User;
approval: boolean;
created_at: string;
updated_at: string;
}
export declare const VirtualLiftSchema: mongoose.Schema<Document<VirtualLift, any, any>, mongoose.Model<Document<VirtualLift, any, any>, any, any, any>, {}>;
|
lakshay-pant/vynoFinalBack | src/lift/dto/create-lift.dto.ts | <reponame>lakshay-pant/vynoFinalBack
export class CreateLiftDto {}
|
lakshay-pant/vynoFinalBack | src/lift/schemas/lift.schema.ts | <reponame>lakshay-pant/vynoFinalBack<filename>src/lift/schemas/lift.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export type LiftDocument = Lift & Document;
@Schema()
export class Lift {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
user_id: User;
@Prop({ required: true })
type: string;
@Prop({type: Object, required: true })
to: {
lat:string,
long:string,
address:string
};
@Prop({type: Object, required: true })
from:{
lat:string,
long:string,
address:string
};
@Prop({ required: true })
passenger: number;
@Prop({ required: true })
price: number;
@Prop({ required: true })
departure_time: string;
@Prop({default: false})
is_occasional: boolean;
@Prop()
occasional: string;
@Prop({default: false})
is_frequent: boolean;
@Prop({type: Object})
frequent: string;
@Prop({default: false})
is_come_back: boolean;
@Prop()
lift_come_back_time: string;
@Prop({default: false})
is_pick_preference: boolean;
@Prop({default: ''})
distance: string;
@Prop({type: Object})
drop_off:Object;
@Prop({type: Object})
pick_preferences:{
pickup: Object,
gender: string,
air_condition: string,
pvt_lift: string,
car : string
}
@Prop({default: true})
is_active: boolean;
@Prop({ required: true ,default: false})
is_virtual: boolean;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const LiftSchema = SchemaFactory.createForClass(Lift); |
lakshay-pant/vynoFinalBack | dist/src/document/document.service.d.ts | <filename>dist/src/document/document.service.d.ts
import { CreateDocumentDto } from './dto/create-document.dto';
import { Model } from 'mongoose';
export declare class DocumentService {
private documentsModel;
constructor(documentsModel: Model<CreateDocumentDto>);
create(createDocumentDto: CreateDocumentDto): string;
findAll(): string;
findOne(id: number): string;
checkData(id: any, role: any): import("mongoose").Query<import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
}, {}, CreateDocumentDto>;
checkAccountStatusFromId(user_id: any): import("mongoose").Query<(import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
})[], import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
}, {}, CreateDocumentDto>;
updateInsert(id: any, role: any, data: any, type: any): import("mongoose").Query<import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
}, import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
}, {}, CreateDocumentDto> | Promise<import("mongoose").Document<any, any, CreateDocumentDto> & CreateDocumentDto & {
_id: unknown;
}>;
remove(id: number): string;
}
|
lakshay-pant/vynoFinalBack | src/lift/entities/lift.entity.ts | export class Lift {}
|
lakshay-pant/vynoFinalBack | dist/src/lift/dto/update-lift.dto.d.ts | <filename>dist/src/lift/dto/update-lift.dto.d.ts
import { CreateLiftDto } from './create-lift.dto';
declare const UpdateLiftDto_base: import("@nestjs/mapped-types").MappedType<Partial<CreateLiftDto>>;
export declare class UpdateLiftDto extends UpdateLiftDto_base {
}
export {};
|
lakshay-pant/vynoFinalBack | src/common/admin.middleware.ts | <gh_stars>0
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AdminMiddleware implements NestMiddleware {
constructor(private jwtService: JwtService) {}
async use(req: Request, res: Response, next: NextFunction) {
try {
const token = req.header('authorization').split(' ')[1]; // Authorization: 'Bearer TOKEN'
if (!token) {
throw new Error('Authentication failed!');
}
const verified = await this.jwtService.verifyAsync(token);
req.body.user = verified;
next();
} catch (err) {
res.status(400).send({ status: false,message:'invalid token' });
}
}
}
|
lakshay-pant/vynoFinalBack | dist/src/admin/admin.service.d.ts | <filename>dist/src/admin/admin.service.d.ts
import { CreateAdminDto } from './dto/create-admin.dto';
import { UpdateAdminDto } from './dto/update-admin.dto';
import { UsersService } from '../users/users.service';
export declare class AdminService {
private readonly usersService;
constructor(usersService: UsersService);
create(createAdminDto: CreateAdminDto): string;
findAll(): Promise<void>;
findOne(id: number): string;
update(id: number, updateAdminDto: UpdateAdminDto): string;
remove(id: number): string;
}
|
lakshay-pant/vynoFinalBack | dist/src/document/dto/create-document.dto.d.ts | export declare class CreateDocumentDto {
}
|
lakshay-pant/vynoFinalBack | src/users/schemas/ratingReview.schema.ts | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { User } from '../../users/schemas/user.schema';
import * as mongoose from 'mongoose';
export type RatingReviewDocument = RatingReview & Document;
@Schema()
export class RatingReview {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true })
to: User;
@Prop()
rating: string;
@Prop()
rating_for: string;
@Prop()
created_at: string;
@Prop()
updated_at: string;
}
export const RatingReviewSchema = SchemaFactory.createForClass(RatingReview); |
lakshay-pant/vynoFinalBack | src/singup/dto/update-singup.dto.ts | import { PartialType } from '@nestjs/mapped-types';
import { CreateSingupDto } from './create-singup.dto';
export class UpdateSingupDto extends PartialType(CreateSingupDto) {}
|
Subsets and Splits