/
app.tsx
234 lines (220 loc) · 7.01 KB
/
app.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import * as React from 'react';
import { TextField, MessageBar, MessageBarType } from 'office-ui-fabric-react';
import { Header } from './header';
import { Waiting } from './waiting';
import { StockItem } from './StockItem';
import { ExcelTableUtil } from '../utils/ExcelTableUtil';
const ALPHAVANTAGE_APIKEY: string = '{{REPLACE_WITH_ALPHAVANTAGE_APIKEY}}';
export interface AppProps {
title: string;
}
export interface AppState {
listItems: string[];
waiting: boolean;
error: string;
}
export default class App extends React.Component<AppProps, AppState> {
tableUtil: ExcelTableUtil = new ExcelTableUtil('Portfolio', 'A1:H1', [
'Symbol',
'Last Price',
'Timestamp',
'Quantity',
'Price Paid',
'Total Gain',
'Total Gain %',
'Value'
]);
constructor(props, context) {
super(props, context);
this.state = {
listItems: [],
waiting: false,
error: ''
};
}
componentDidMount() {
// Sync stocks already in Excel table
this.syncTable().then(() => {});
}
// Adds symbol
addSymbol = async event => {
if (event.key === 'Enter') {
let element = this.refs.newSymbol as TextField;
let symbol = element.value.toUpperCase();
// Get quote and add to Excel table
this.setState({ waiting: true });
this.getQuote(symbol).then(
(res: any) => {
let data = [
res['1. symbol'], //Symbol
res['2. price'], //Last Price
res['4. timestamp'], // Timestamp of quote
0,
0,
'=(B:B * D:D) - (E:E * D:D)', //Total Gain $
'=H:H / (E:E * D:D) * 100', //Total Gain %
'=B:B * D:D' //Value
];
this.tableUtil.addRow(data).then(
() => {
let symbols = this.state.listItems;
symbols.unshift(element.state.value.toUpperCase());
this.setState({ listItems: symbols });
element.setState({ value: '' });
this.setState({ waiting: false });
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
}
}
// Delete symbol
deleteSymbol = async index => {
// Delete from Excel table by index number
let symbols = this.state.listItems;
let symbol = symbols[index];
this.setState({ waiting: true });
this.tableUtil.getColumnData('Symbol').then(
async (columnData: string[]) => {
// Ensure the symbol was found in the Excel table
if (columnData.indexOf(symbol) !== -1) {
this.tableUtil.deleteRow(columnData.indexOf(symbol)).then(
async () => {
symbols.splice(index, 1);
this.setState({ listItems: symbols });
this.setState({ waiting: false });
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
} else {
symbols.splice(index, 1);
this.setState({ waiting: false });
}
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
}
// Refresh symbol
refreshSymbol = async (index: number) => {
// Refresh stock quote and update Excel table
let symbols = this.state.listItems;
let symbol = symbols[index];
this.setState({ waiting: true });
this.tableUtil.getColumnData('Symbol').then(
async (columnData: string[]) => {
// Ensure the symbol was found in the Excel table
const rowIndex = columnData.indexOf(symbol);
if (rowIndex !== -1) {
this.getQuote(symbol).then((res: any) => {
// "last trade" is in column B with a row index offset of 2 (row 0 + the header row)
this.tableUtil
.updateCell(`B${rowIndex + 2}:B${rowIndex + 2}`, res['2. price'])
.then(
async () => {
this.setState({ waiting: false });
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
});
} else {
this.setState({ error: 'Symbol not in table' });
symbols.splice(index, 1);
this.setState({ waiting: false });
}
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
}
// Reads symbols from an existing Excel workbook and pre-populates them in the add-in
syncTable = async () => {
this.setState({ waiting: true });
this.tableUtil.getColumnData('Symbol').then(
async (columnData: string[]) => {
this.setState({ listItems: columnData });
this.setState({ waiting: false });
},
err => {
this.setState({ error: err });
this.setState({ waiting: false });
}
);
}
// Gets a quote by calling into the stock service
getQuote = async (symbol: string) => {
return new Promise((resolve, reject) => {
const queryEndpoint = `https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=${escape(
symbol
)}&interval=1min&apikey=${ALPHAVANTAGE_APIKEY}`;
fetch(queryEndpoint)
.then((res: any) => {
if (!res.ok) {
reject('Error getting quote');
}
return res.json();
})
.then((jsonResponse: any) => {
const quote: any = jsonResponse['Stock Quotes'][0];
resolve(quote);
});
});
}
render() {
const stocks = this.state.listItems.map((symbol, index) => (
<StockItem
symbol={symbol}
index={index}
onDelete={this.deleteSymbol.bind(this, index)}
onRefresh={this.refreshSymbol.bind(this, index)}
/>
));
return (
<div className="container">
{this.state.waiting && <Waiting />}
<Header title={this.props.title} />
{this.state.error != '' && (
<MessageBar
messageBarType={MessageBarType.error}
isMultiline={false}
onDismiss={() => {
this.setState({ error: '' });
}}>
{this.state.error}
</MessageBar>
)}
<div className="padding10">
<div className="pct100 tbl-head">
<span className="ms-font-l">Stock Symbols</span>
</div>
<div className="pct100">
<TextField
ref="newSymbol"
onKeyPress={this.addSymbol.bind(this)}
placeholder="Enter a stock symbol (ex: MSFT)"
/>
</div>
{stocks}
</div>
</div>
);
}
}