Browse Source

first commit

master
fraz 10 months ago
parent
commit
28ca3c349b
21 changed files with 16464 additions and 405 deletions
  1. +1
    -0
      .eslintcache
  2. +71
    -68
      README.md
  3. +15993
    -0
      package-lock.json
  4. +10
    -0
      package.json
  5. +3
    -26
      public/index.html
  6. BIN
      public/logo192.png
  7. BIN
      public/logo512.png
  8. +0
    -25
      public/manifest.json
  9. +0
    -39
      src/App.css
  10. +35
    -50
      src/App.js
  11. +0
    -15
      src/App.test.js
  12. +10
    -5
      src/app/store.js
  13. +0
    -60
      src/features/counter/Counter.js
  14. +0
    -74
      src/features/counter/Counter.module.css
  15. +0
    -42
      src/features/counter/counterSlice.js
  16. +118
    -0
      src/features/filter/Filter.js
  17. +43
    -0
      src/features/filter/filterStore.js
  18. +55
    -0
      src/features/filter/filterUtils.js
  19. +95
    -0
      src/features/payments/Payments.js
  20. +30
    -0
      src/features/payments/paymentsStore.js
  21. +0
    -1
      src/logo.svg

+ 1
- 0
.eslintcache View File

@@ -0,0 +1 @@
[{"c:\\Projects\\dashboard\\frontend\\src\\features\\payments\\Payments.js":"1","c:\\Projects\\dashboard\\frontend\\src\\features\\filter\\Filter.js":"2","c:\\Projects\\dashboard\\frontend\\src\\App.js":"3"},{"size":2687,"mtime":1608679401714,"results":"4","hashOfConfig":"5"},{"size":3307,"mtime":1608679121363,"results":"6","hashOfConfig":"5"},{"size":1098,"mtime":1608679151897,"results":"7","hashOfConfig":"5"},{"filePath":"8","messages":"9","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1cpz9ju",{"filePath":"10","messages":"11","errorCount":0,"warningCount":1,"fixableErrorCount":0,"fixableWarningCount":0,"source":null},{"filePath":"12","messages":"13","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"c:\\Projects\\dashboard\\frontend\\src\\features\\payments\\Payments.js",[],"c:\\Projects\\dashboard\\frontend\\src\\features\\filter\\Filter.js",["14"],"c:\\Projects\\dashboard\\frontend\\src\\App.js",[],{"ruleId":"15","severity":1,"message":"16","line":3,"column":10,"nodeType":"17","messageId":"18","endLine":3,"endColumn":19},"no-unused-vars","'Container' is defined but never used.","Identifier","unusedVar"]

+ 71
- 68
README.md View File

@@ -1,68 +1,71 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) template.

## Available Scripts

In the project directory, you can run:

### `yarn start`

Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br />
You will also see any lint errors in the console.

### `yarn test`

Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `yarn build`

Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `yarn eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

### Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

### Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

### Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

### Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

### `yarn build` fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
## Running The Frontend

`npm install` in the frontend directory to install the required modules then `npm run start` to start the dev server by default on [localhost:3000](http://localhost:3000)

`yarn install && yarn start` should work too.

### Design Choices

- Frameworks
- I decided to use `ReactJS and Redux`
- I'm pretty comfortable with it but it's been a while since I used it without TypeScript
- Decided to use `createSlice` from the redux toolkit since this appears to be standard now
- I used `material-ui` for some nice prebuilt visual components
- I used `react-flip-move` for some list animations

## Features

### Payments

- Payments are displayed in a nice material-ui card.
- I added a bit more information to each card.
- I found and added `react-flip-move` which adds some nice animations
- I believe there's an issue when running it in dev that swapping tabs can cause some strange behavior
- removing react-flip-move and replacing with an alternative is a simple fix
#### Polling
- Payments are polled using setInterval with an interval of 1
- Since it's doing an IO request it's pretty unreliable and likely to miss some requests
- A good alternative could be modifying the server to use websockets
#### Redux Payments Store
- Holds all payments
- uses unshift to add to front of list which is most likely inefficient (not sure on JavaScript implementation of unshift).
- allows for the nice animation
- Only holds 25 payments at any one time
- We only care about 25 payments from the specification so this should be okay
- Holds latest error information
- Only holds a single error
- In a larger system I'd give errors their own store
- I originally thought the /GET endpoint was similar to the /POST endpoint and would return errors sometimes

### Filters
- You can filter based on each field and remove filters as you progress
- The implementation allows for multiple filters on the same field
- Useful for searching memos
- Could be extended to a "person" filter which looks only at receiver and sender name

#### 'any' type filter

I gave some thought onto implementing a filter type that searches through all fields. Some implementation ideas I had were

- Apply each filter to the original payments input and add all outputs to an array then remove duplicates
- Combine all fields to a single string and use indexOf
- has obvious possible undesirable results
#### Redux Filter Store
- Handles the current user input
- Type & Query
- Handles the current active filters
- User input could be changed to use useState() or in it's own store

## Directory Layout

I used the default directory structure that is recommended with `create-react-app`.

## Code Quality & Cleanliness

Generally I'd use an airbnb eslint configuration, this instance the setup complained too long and it's been a while since I messed around with non TypeScript eslint.

There's no tests but tests could be added to ensure reducers work correctly and components have the correct behaviour. Jasmine / Jest tests could be easily implemented.

+ 15993
- 0
package-lock.json
File diff suppressed because it is too large
View File


+ 10
- 0
package.json View File

@@ -3,12 +3,14 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.2",
"@reduxjs/toolkit": "^1.1.0",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-flip-move": "^3.0.4",
"react-redux": "^7.1.3",
"react-scripts": "4.0.1"
},
@@ -32,5 +34,13 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint": "^7.16.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0"
}
}

+ 3
- 26
public/index.html View File

@@ -3,41 +3,18 @@
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React Redux App</title>
<title>Circle Dashboard</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
public/logo192.png View File

Before After
Width: 192  |  Height: 192  |  Size: 4.1 KiB

BIN
public/logo512.png View File

Before After
Width: 512  |  Height: 512  |  Size: 12 KiB

+ 0
- 25
public/manifest.json View File

@@ -1,25 +0,0 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

+ 0
- 39
src/App.css View File

@@ -1,39 +0,0 @@
.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-float infinite 3s ease-in-out;
}
}

.App-header {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
}

.App-link {
color: rgb(112, 76, 182);
}

@keyframes App-logo-float {
0% {
transform: translateY(0);
}
50% {
transform: translateY(10px)
}
100% {
transform: translateY(0px)
}
}

+ 35
- 50
src/App.js View File

@@ -1,56 +1,41 @@
import React from 'react';
import logo from './logo.svg';
import { Counter } from './features/counter/Counter';
import './App.css';
import { makeStyles } from '@material-ui/core/styles';
import { Container, Paper, Typography } from '@material-ui/core';
import Filter from './features/filter/Filter.js';
import Payments from './features/payments/Payments.js';

function App() {

const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
backgroundColor: "#64bbfe",
backgroundImage: 'url("https://www.transparenttextures.com/patterns/gplay.png")',
height: '100%',
minHeight: '100vh',
},
content: {
flexGrow: 1,
height: '100vh',
overflow: 'auto',
},
paper: {
marginTop: '2rem',
padding: theme.spacing(2)
}
}));

const App = () => {
const classes = useStyles();
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Counter />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<span>
<span>Learn </span>
<a
className="App-link"
href="https://reactjs.org/"
target="_blank"
rel="noopener noreferrer"
>
React
</a>
<span>, </span>
<a
className="App-link"
href="https://redux.js.org/"
target="_blank"
rel="noopener noreferrer"
>
Redux
</a>
<span>, </span>
<a
className="App-link"
href="https://redux-toolkit.js.org/"
target="_blank"
rel="noopener noreferrer"
>
Redux Toolkit
</a>
,<span> and </span>
<a
className="App-link"
href="https://react-redux.js.org/"
target="_blank"
rel="noopener noreferrer"
>
React Redux
</a>
</span>
</header>
<div className={classes.root}>
<Container maxWidth="lg" className={classes.container}>
<Paper className={classes.paper} elevation={0}>
<Typography variant='h2' style={{textAlign: 'center'}}>Payment Information</Typography>
<Filter />
<hr />
<Payments />
</Paper>
</Container>
</div>
);
}


+ 0
- 15
src/App.test.js View File

@@ -1,15 +0,0 @@
import React from 'react';
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from './app/store';
import App from './App';

test('renders learn react link', () => {
const { getByText } = render(
<Provider store={store}>
<App />
</Provider>
);

expect(getByText(/learn/i)).toBeInTheDocument();
});

+ 10
- 5
src/app/store.js View File

@@ -1,8 +1,13 @@
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import filterReducer from '../features/filter/filterStore';
import paymentsReducer from '../features/payments/paymentsStore';


export default configureStore({
reducer: {
counter: counterReducer,
},
reducer: combineReducers(
{
payments: paymentsReducer,
filter: filterReducer,
}
),
});

+ 0
- 60
src/features/counter/Counter.js View File

@@ -1,60 +0,0 @@
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
decrement,
increment,
incrementByAmount,
incrementAsync,
selectCount,
} from './counterSlice';
import styles from './Counter.module.css';

export function Counter() {
const count = useSelector(selectCount);
const dispatch = useDispatch();
const [incrementAmount, setIncrementAmount] = useState('2');

return (
<div>
<div className={styles.row}>
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
+
</button>
<span className={styles.value}>{count}</span>
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
-
</button>
</div>
<div className={styles.row}>
<input
className={styles.textbox}
aria-label="Set increment amount"
value={incrementAmount}
onChange={e => setIncrementAmount(e.target.value)}
/>
<button
className={styles.button}
onClick={() =>
dispatch(incrementByAmount(Number(incrementAmount) || 0))
}
>
Add Amount
</button>
<button
className={styles.asyncButton}
onClick={() => dispatch(incrementAsync(Number(incrementAmount) || 0))}
>
Add Async
</button>
</div>
</div>
);
}

+ 0
- 74
src/features/counter/Counter.module.css View File

@@ -1,74 +0,0 @@
.row {
display: flex;
align-items: center;
justify-content: center;
}

.row:not(:last-child) {
margin-bottom: 16px;
}

.value {
font-size: 78px;
padding-left: 16px;
padding-right: 16px;
margin-top: 2px;
font-family: 'Courier New', Courier, monospace;
}

.button {
appearance: none;
background: none;
font-size: 32px;
padding-left: 12px;
padding-right: 12px;
outline: none;
border: 2px solid transparent;
color: rgb(112, 76, 182);
padding-bottom: 4px;
cursor: pointer;
background-color: rgba(112, 76, 182, 0.1);
border-radius: 2px;
transition: all 0.15s;
}

.textbox {
font-size: 32px;
padding: 2px;
width: 64px;
text-align: center;
margin-right: 8px;
}

.button:hover, .button:focus {
border: 2px solid rgba(112, 76, 182, 0.4);
}

.button:active {
background-color: rgba(112, 76, 182, 0.2);
}

.asyncButton {
composes: button;
position: relative;
margin-left: 8px;
}

.asyncButton:after {
content: "";
background-color: rgba(112, 76, 182, 0.15);
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
opacity: 0;
transition: width 1s linear, opacity 0.5s ease 1s;
}

.asyncButton:active:after {
width: 0%;
opacity: 1;
transition: 0s
}

+ 0
- 42
src/features/counter/counterSlice.js View File

@@ -1,42 +0,0 @@
import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});

export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// The function below is called a thunk and allows us to perform async logic. It
// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This
// will call the thunk with the `dispatch` function as the first argument. Async
// code can then be executed and other actions can be dispatched
export const incrementAsync = amount => dispatch => {
setTimeout(() => {
dispatch(incrementByAmount(amount));
}, 1000);
};

// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state) => state.counter.value)`
export const selectCount = state => state.counter.value;

export default counterSlice.reducer;

+ 118
- 0
src/features/filter/Filter.js View File

@@ -0,0 +1,118 @@
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Container, Paper, Typography, Button, Chip } from '@material-ui/core';
import { useSelector, useDispatch } from 'react-redux';

import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import TextField from '@material-ui/core/TextField';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import {filterKeys, selectFilterType, setFilterType, setFilterQuery, selectFilterQuery, addFilter, selectFilters, removeFilter} from './filterStore';

const useStyles = makeStyles((theme) => ({
filterRoot: {
margin: theme.spacing(2),
padding: theme.spacing(2)
},
formControl: {
minWidth: '10rem',
margin: theme.spacing(1),
},
filterChip: {
margin: theme.spacing(1)
}
}));



const Filter = () => {
const classes = useStyles();
return (
<Paper elevation={1} className={classes.filterRoot}>
<Typography variant='subtitle1'>Select Filters:</Typography>
<FilterTypeSelector />
<SearchFilter />
<AddFilterButton />
<div>
<DisplayFilterChips/>
</div>
</Paper>
);
}

const FilterTypeSelector = () => {
const classes = useStyles();
const toTitleCase = (s) => s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();
const filterType = useSelector(selectFilterType);
const dispatch = useDispatch();
return (
<FormControl className={classes.formControl}>
<InputLabel id="selectFilterTypeLabel">Filter Type</InputLabel>
<Select
labelId="selectFilterTypeLabel"
id="selectFilter"
value={filterType}
onChange={(e) => dispatch(setFilterType(e.target.value))}
>
{filterKeys.map((k) => {
return <MenuItem value={k}>{toTitleCase(k)}</MenuItem>
})}
</Select>
</FormControl>
);
}

const SearchFilter = () => {
const classes = useStyles();
const filterQuery = useSelector(selectFilterQuery);
const dispatch = useDispatch();
return (
<FormControl className={classes.formControl}>
<TextField
id="searchQuery"
label="Filter Query"
value={filterQuery}
onChange={(e) => dispatch(setFilterQuery(e.target.value))}
>
</TextField>
</FormControl>
);
}

const AddFilterButton = () => {
const classes = useStyles();
const dispatch = useDispatch();
return (
<FormControl className={classes.formControl} style={{marginTop: '1.2em'}}>
<Button variant="contained" color="primary" onClick={() => dispatch(addFilter())}>
Add Filter
</Button>
</FormControl>
);
}

const DisplayFilterChips = () => {
const filters = useSelector(selectFilters);
console.log("Filters", filters)
return (
filters.map((filter) => {
return <DisplayFilterChip type={filter.type} value={filter.value} />
})
);
}

const DisplayFilterChip = (props) => {
const classes = useStyles();
const dispatch = useDispatch();
const payload = {
type: props.type,
value: props.value,
}
console.log(payload)
return (
<Chip className={classes.filterChip} label={`${props.type} - ${props.value}`} onDelete={() => dispatch(removeFilter(payload))} color="primary" />
);
}

export default Filter;

+ 43
- 0
src/features/filter/filterStore.js View File

@@ -0,0 +1,43 @@
import { createSlice } from '@reduxjs/toolkit'

export const filterKeys = [
'id',
'date',
'sender',
'receiver',
'amount',
'currency',
'memo',
];

const initialState = { filterType: 'any', filterQuery: '', filters: []}

const filterSlice = createSlice({
name: 'filter',
initialState,
reducers: {
setFilterType: (state, action) => {
state.filterType = action.payload
},
setFilterQuery: (state, action) => {
state.filterQuery = action.payload
},
addFilter: (state) => {
state.filters.push(
{type: state.filterType, value: state.filterQuery}
)
state.filterQuery = "";
},
removeFilter: (state, action) => {
state.filters = state.filters.filter((f) => f.type !== action.payload.type || f.value !== action.payload.value)
}
},
})

export const { setFilterType, setFilterQuery, addFilter, removeFilter } = filterSlice.actions

export const selectFilterType = state => state.filter.filterType;
export const selectFilterQuery = state => state.filter.filterQuery;
export const selectFilters = state => state.filter.filters;

export default filterSlice.reducer

+ 55
- 0
src/features/filter/filterUtils.js View File

@@ -0,0 +1,55 @@
import {filterKeys} from './filterStore';

export const filterPayments = (payments, filters) => {
const applyFilter = (payments, filter) => {
switch(filter.type) {
case 'id': {
payments = payments.filter((payment) => payment.data.id.indexOf(filter.value) >= 0)
break;
}
case 'date': {
payments = payments.filter((payment) => new Date(payment.data.date).toLocaleDateString().indexOf(filter.value) >= 0)
break;
}
case 'sender': {
payments = payments.filter((payment) => {
let sender = payment.data.sender.id + ' ' + payment.data.sender.name
return sender.toLowerCase().indexOf(filter.value.toLowerCase()) >= 0
})
break;
}
case 'receiver': {
payments = payments.filter((payment) => {
let receiver = payment.data.sender.id + ' ' + payment.data.sender.name
return receiver.toLowerCase().indexOf(filter.value.toLowerCase()) >= 0
})
break;
}
case 'amount': {
payments = payments.filter((payment) => payment.data.amount.indexOf(filter.value) >= 0)
break;
}
case 'currency': {
payments = payments.filter((payment) => payment.data.currency.toLowerCase().indexOf(filter.value.toLowerCase()) >= 0)
break;
}
case 'memo': {
payments = payments.filter((payment) => payment.data.memo.toLowerCase().indexOf(filter.value.toLowerCase()) >= 0)
break;
}
}
return payments
}

for (let i = 0; i < filters.length; i++) {
console.log(i)
console.log(filters)
console.log(payments)
payments = applyFilter(payments, filters[i])
console.log(payments)
}
return payments
}


+ 95
- 0
src/features/payments/Payments.js View File

@@ -0,0 +1,95 @@
import React, { useEffect, forwardRef } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Paper, Typography, } from '@material-ui/core';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import { useDispatch, useSelector } from 'react-redux';
import { addPayment, selectPayments } from './paymentsStore';
import FlipMove from 'react-flip-move';
import { filterPayments } from '../filter/filterUtils';
import { selectFilters } from '../filter/filterStore';


const useStyles = makeStyles({
root: {
minWidth: 275,
margin: '2em',
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
});

const PAYMENTS_URL = 'http://localhost:8080/payments'

const formatDate = (dataDate) => {
const d = new Date(dataDate).toLocaleDateString();
return d;
}

const Payment = forwardRef((props,ref) => {
const classes = useStyles();
return (
<Card className={classes.root} ref={ref}>
<CardContent>
<Typography className={classes.title} color="textSecondary" gutterBottom>
{formatDate(props.data.date)}
</Typography>
<Typography variant="h5" component="h1">
{props.data.sender.name} &#10230; {props.data.receiver.name}
</Typography>
<Typography variant="h6" component="h2">
{props.data.amount}
</Typography>
<Typography className={classes.pos} color="textSecondary">
{props.data.currency}
</Typography>
<Typography variant="body2" component="p">
{props.data.memo}
</Typography>
</CardContent>
<CardActions>
<Typography variant="caption" component="p">
Transaction ID - {props.data.id}
</Typography>

</CardActions>
</Card>
)
});

const Payments = () => {
const payments = useSelector(selectPayments);
const dispatch = useDispatch();
const filters = useSelector(selectFilters);
useEffect(() => {
const pollPayments = () => {
fetch(PAYMENTS_URL).then((resp) => resp.json()).then((res) => {
dispatch(addPayment(res))
}).catch((err) => {
// catch server errors
// dispatch(setPaymentError(err.message))
// dispatch(setPaymentErrorCode(err.code))
})
}
setInterval(pollPayments, 1000);
}, [dispatch])
const filteredPayments = filterPayments(payments, filters)
console.log(filteredPayments)
return (
<Paper>
<FlipMove>
{filteredPayments.map((payment) => {
return <Payment key={payment.data.id} {...payment} />
})}
</FlipMove>
</Paper>
);
}

export default Payments;

+ 30
- 0
src/features/payments/paymentsStore.js View File

@@ -0,0 +1,30 @@
import { createSlice } from '@reduxjs/toolkit'


const initialState = { payments: [], paymentsError: '', paymentsErrorCode: ''}

const paymentsSlice = createSlice({
name: 'payments',
initialState,
reducers: {
addPayment: (state, action) => {
// expects a payment
state.payments.unshift(action.payload)
if (state.payments.length > 25)
state.payments = state.payments.slice(0, 25)
},
setPaymentError: (state, action) => {
state.paymentsError = action.payload
},
setPaymentErrorCode: (state, action) => {
state.paymentsErrorCode = action.payload
}
},
})

export const { addPayment, setPaymentError, setPaymentErrorCode } = paymentsSlice.actions

export const selectError = state => `${state.paymentsErrorCode} ${state.paymentsError}`;
export const selectPayments = state => state.payments.payments;

export default paymentsSlice.reducer

+ 0
- 1
src/logo.svg View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g fill="#764ABC"><path d="M65.6 65.4c2.9-.3 5.1-2.8 5-5.8-.1-3-2.6-5.4-5.6-5.4h-.2c-3.1.1-5.5 2.7-5.4 5.8.1 1.5.7 2.8 1.6 3.7-3.4 6.7-8.6 11.6-16.4 15.7-5.3 2.8-10.8 3.8-16.3 3.1-4.5-.6-8-2.6-10.2-5.9-3.2-4.9-3.5-10.2-.8-15.5 1.9-3.8 4.9-6.6 6.8-8-.4-1.3-1-3.5-1.3-5.1-14.5 10.5-13 24.7-8.6 31.4 3.3 5 10 8.1 17.4 8.1 2 0 4-.2 6-.7 12.8-2.5 22.5-10.1 28-21.4z"/><path d="M83.2 53c-7.6-8.9-18.8-13.8-31.6-13.8H50c-.9-1.8-2.8-3-4.9-3h-.2c-3.1.1-5.5 2.7-5.4 5.8.1 3 2.6 5.4 5.6 5.4h.2c2.2-.1 4.1-1.5 4.9-3.4H52c7.6 0 14.8 2.2 21.3 6.5 5 3.3 8.6 7.6 10.6 12.8 1.7 4.2 1.6 8.3-.2 11.8-2.8 5.3-7.5 8.2-13.7 8.2-4 0-7.8-1.2-9.8-2.1-1.1 1-3.1 2.6-4.5 3.6 4.3 2 8.7 3.1 12.9 3.1 9.6 0 16.7-5.3 19.4-10.6 2.9-5.8 2.7-15.8-4.8-24.3z"/><path d="M32.4 67.1c.1 3 2.6 5.4 5.6 5.4h.2c3.1-.1 5.5-2.7 5.4-5.8-.1-3-2.6-5.4-5.6-5.4h-.2c-.2 0-.5 0-.7.1-4.1-6.8-5.8-14.2-5.2-22.2.4-6 2.4-11.2 5.9-15.5 2.9-3.7 8.5-5.5 12.3-5.6 10.6-.2 15.1 13 15.4 18.3 1.3.3 3.5 1 5 1.5-1.2-16.2-11.2-24.6-20.8-24.6-9 0-17.3 6.5-20.6 16.1-4.6 12.8-1.6 25.1 4 34.8-.5.7-.8 1.8-.7 2.9z"/></g></svg>

Loading…
Cancel
Save