-
Notifications
You must be signed in to change notification settings - Fork 150
/
beyahad-bishvilha.ts
176 lines (153 loc) · 5.91 KB
/
beyahad-bishvilha.ts
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
import { Page } from 'puppeteer';
import moment from 'moment';
import { BaseScraperWithBrowser, LoginResults, PossibleLoginResults } from './base-scraper-with-browser';
import { ScaperOptions, ScraperCredentials } from './base-scraper';
import { Transaction, TransactionStatuses, TransactionTypes } from '../transactions';
import { pageEval, pageEvalAll, waitUntilElementFound } from '../helpers/elements-interactions';
import { getDebug } from '../helpers/debug';
import { filterOldTransactions } from '../helpers/transactions';
import {
DOLLAR_CURRENCY,
DOLLAR_CURRENCY_SYMBOL, EURO_CURRENCY,
EURO_CURRENCY_SYMBOL,
SHEKEL_CURRENCY,
SHEKEL_CURRENCY_SYMBOL,
} from '../constants';
const debug = getDebug('beyahadBishvilha');
const DATE_FORMAT = 'DD/MM/YY';
const LOGIN_URL = 'https://www.hist.org.il/login';
const SUCCESS_URL = 'https://www.hist.org.il/';
const CARD_URL = 'https://www.hist.org.il/card/balanceAndUses';
interface ScrapedTransaction {
date: string;
description: string;
type: string;
chargedAmount: string;
identifier: string;
}
function getAmountData(amountStr: string) {
const amountStrCln = amountStr.replace(',', '');
let currency: string | null = null;
let amount: number | null = null;
if (amountStrCln.includes(SHEKEL_CURRENCY_SYMBOL)) {
amount = parseFloat(amountStrCln.replace(SHEKEL_CURRENCY_SYMBOL, ''));
currency = SHEKEL_CURRENCY;
} else if (amountStrCln.includes(DOLLAR_CURRENCY_SYMBOL)) {
amount = parseFloat(amountStrCln.replace(DOLLAR_CURRENCY_SYMBOL, ''));
currency = DOLLAR_CURRENCY;
} else if (amountStrCln.includes(EURO_CURRENCY_SYMBOL)) {
amount = parseFloat(amountStrCln.replace(EURO_CURRENCY_SYMBOL, ''));
currency = EURO_CURRENCY;
} else {
const parts = amountStrCln.split(' ');
[currency] = parts;
amount = parseFloat(parts[1]);
}
return {
amount,
currency,
};
}
function convertTransactions(txns: ScrapedTransaction[]): Transaction[] {
debug(`convert ${txns.length} raw transactions to official Transaction structure`);
return txns.map((txn) => {
const chargedAmountTuple = getAmountData(txn.chargedAmount || '');
const txnProcessedDate = moment(txn.date, DATE_FORMAT);
const result: Transaction = {
type: TransactionTypes.Normal,
status: TransactionStatuses.Completed,
date: txnProcessedDate.toISOString(),
processedDate: txnProcessedDate.toISOString(),
originalAmount: chargedAmountTuple.amount,
originalCurrency: chargedAmountTuple.currency,
chargedAmount: chargedAmountTuple.amount,
chargedCurrency: chargedAmountTuple.currency,
description: txn.description || '',
memo: '',
identifier: txn.identifier,
};
return result;
});
}
async function fetchTransactions(page: Page, options: ScaperOptions) {
await page.goto(CARD_URL);
await waitUntilElementFound(page, '.react-loading.hide', false);
const defaultStartMoment = moment().subtract(1, 'years');
const startDate = options.startDate || defaultStartMoment.toDate();
const startMoment = moment.max(defaultStartMoment, moment(startDate));
const accountNumber = await pageEval(page, '.wallet-details div:nth-of-type(2)', null, (element) => {
return (element as any).innerText.replace('מספר כרטיס ', '');
});
const balance = await pageEval(page, '.wallet-details div:nth-of-type(4) > span:nth-of-type(2)', null, (element) => {
return (element as any).innerText;
});
debug('fetch raw transactions from page');
const rawTransactions: (ScrapedTransaction | null)[] = await pageEvalAll<(ScrapedTransaction | null)[]>(page, '.transaction-container, .transaction-component-container', [], (items) => {
return (items).map((el) => {
const columns: NodeListOf<HTMLSpanElement> = el.querySelectorAll('.transaction-item > span');
if (columns.length === 7) {
return {
date: columns[0].innerText,
identifier: columns[1].innerText,
description: columns[3].innerText,
type: columns[5].innerText,
chargedAmount: columns[6].innerText,
};
}
return null;
});
});
debug(`fetched ${rawTransactions.length} raw transactions from page`);
const accountTransactions = convertTransactions(rawTransactions.filter((item) => !!item) as ScrapedTransaction[]);
debug('filer out old transactions');
const txns = filterOldTransactions(accountTransactions, startMoment, false);
debug(`found ${txns.length} valid transactions out of ${accountTransactions.length} transactions for account ending with ${accountNumber.substring(accountNumber.length - 2)}`);
return {
accountNumber,
balance: getAmountData(balance).amount,
txns,
};
}
function getPossibleLoginResults(): PossibleLoginResults {
const urls: PossibleLoginResults = {};
urls[LoginResults.Success] = [SUCCESS_URL];
urls[LoginResults.ChangePassword] = []; // TODO
urls[LoginResults.InvalidPassword] = []; // TODO
urls[LoginResults.UnknownError] = []; // TODO
return urls;
}
function createLoginFields(credentials: ScraperCredentials) {
return [
{ selector: '#loginId', value: credentials.id },
{ selector: '#loginPassword', value: credentials.password },
];
}
class BeyahadBishvilhaScraper extends BaseScraperWithBrowser {
protected getViewPort(): { width: number, height: number } {
return {
width: 1500,
height: 800,
};
}
getLoginOptions(credentials: ScraperCredentials) {
return {
loginUrl: LOGIN_URL,
fields: createLoginFields(credentials),
submitButtonSelector: async () => {
const [button] = await this.page.$x("//button[contains(., 'התחבר')]");
if (button) {
await button.click();
}
},
possibleResults: getPossibleLoginResults(),
};
}
async fetchData() {
const account = await fetchTransactions(this.page, this.options);
return {
success: true,
accounts: [account],
};
}
}
export default BeyahadBishvilhaScraper;