forked from danielcft/ynab-export-csv-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
78 lines (71 loc) · 2 KB
/
background.js
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
/* global browser */
import { isEmpty, allOptions } from '/defaults.js'
var selectedText = ''
browser.storage.local.get().then((options) => {
if (isEmpty(options)) {
browser.storage.local.set(allOptions[0])
}
})
browser.menus.create({
id: 'export-ynab-csv',
title: 'Export to YNAB CSV',
contexts: ['all']
})
browser.runtime.onMessage.addListener(handleMessage)
function handleMessage (request) {
selectedText = request.textFromSelection
}
browser.menus.onClicked.addListener(handleClicked)
function handleClicked (info) {
switch (info.menuItemId) {
case 'export-ynab-csv':
browser.storage.local.get().then((options) => {
downloadYnabFile(selectedText, options)
})
break
}
}
function downloadYnabFile (selectedText, options) {
var textAsCsv = WriteAsCsv(
Parse(selectedText, options.regexp, options.newLineSeparator),
options.format,
options.hasSeparateFieldForSign
)
var blob = new Blob([textAsCsv],
{
type: 'text/plain'
})
var url = URL.createObjectURL(blob)
var downloadOptions = {
filename: 'ynab.csv',
saveAs: true,
url: url
}
browser.downloads.download(downloadOptions)
}
function Parse (copiedText, regex, newLineSeparator) {
return copiedText.split(newLineSeparator || '\n').map(line => {
var r = regex.exec(line)
regex.lastIndex = 0
return r
})
}
function WriteAsCsv (parsed, format, hasSeparateFieldForSign) {
var result = 'Date;Payee;Memo;Inflow\n'
parsed.forEach((line, index) => {
// sometimes there are double \n terminators - so we have to deal with empty lines
if (line !== null) {
line.shift()
var date = line[format.indexOf('D')]
var payee = line[format.indexOf('P')]
var inflow = line[format.indexOf('I')]
if (hasSeparateFieldForSign) {
var sign = line[format.indexOf('S')] === 'C' ? '+' : '-'
console.log(sign)
inflow = sign + inflow
}
result = result.concat(`${date};${payee};${payee};${inflow}\n`)
}
})
return result
}