-
Notifications
You must be signed in to change notification settings - Fork 1
/
toggl-invoice
executable file
·298 lines (259 loc) · 7.26 KB
/
toggl-invoice
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env ruby
# rubocop:disable all
require 'csv'
require 'time'
require 'money'
require 'liquid'
require 'yaml'
require 'pdfkit'
I18n.config.enforce_available_locales = false
# uncomment the following on Windows and update config/pdfkit.rb with
# the wkhtmltopdf.exe path
# require './config/pdfkit.rb'
def round_number(n)
r = (n * 2).round / 2.0
r = r.to_i == r ? r.to_i : r
r.zero? ? 0.5 : r
end
def main
config = YAML.load_file(
File.join(
File.dirname(__FILE__),
'config',
'config.yml'
)
)
invoice = {
'date' => Time.now.strftime('%b %-d, %Y'),
'number' => Time.now.strftime('%Y%m%d'),
'bill_to' => '',
'total' => Money.new(0, 'USD'),
'hourly_rate' => Money.new(0, 'USD'),
'header' => %w[Description Start End Hours Rounded Rate Amount],
'bill_from' => config['company'],
'items' => [],
'summary' => {}
}
client = nil
invoice_save = ''
# Parse CSV
csv = CSV.read ARGV[0], :headers => true
csv.group_by{|row| row['Description']}.values.each do |group|
group.first['Client'] = 'Cast & Crew' unless group.first['Client']
if (client.nil?)
client = YAML.load_file(File.join(File.dirname(__FILE__),'config','clients.yml'))[group.first['Client']]
invoice['bill_to'] = client
invoice['hourly_rate'] = Money.new(client['rate']*100, "USD")
invoice_save = "archive/invoice-#{invoice['number']}-#{group.first['Client'].tr('^A-Za-z0-9', '')}."
end
hours = group.map{|r| hmsToFloat(r['Duration'])}.inject(:+)
amount = invoice['hourly_rate'] * round_number(hours.round(2))
project = group.first['Project'] || 'C&C'
invoice['total'] += amount
invoice['items'] << [
"#{project}: #{group.first['Description']}",
group.first['Start date'],
group.last['Start date'],
hours.round(2),
round_number(hours.round(2)),
invoice['hourly_rate'].format,
amount.format
]
invoice['summary'][project] ||= 0
invoice['summary'][project] += amount
end
# add the service fee
invoice['total'] += Money.new(2500, "USD")
invoice['items'] << [
"Service Fee",
invoice['items'][invoice['items'].length - 1][1],
invoice['items'][invoice['items'].length - 1][2],
1,
1,
'$25.00',
'$25.00'
]
invoice['summary']['C&C'] ||= 0
invoice['summary']['C&C'] += Money.new(2500, 'USD')
# Generate Text Invoice
tt = {
"name" => invoice['header'],
"width" => [90, 12, 12, 8, 8, 8, 8],
"linebetweenrows" => false
}
table = TextTable.new(tt)
table_txt = ''
invoice['items'].each do |item|
table_txt << table.printrow(item)
end
table_txt << table.printLine
tt = {
"name" => %w[Project Amount],
"width" => [20, 8],
"linebetweenrows" => false
}
table = TextTable.new(tt)
summary_txt = ''
invoice['summary'].each do |project, amount|
summary_txt << table.printrow([project, amount])
end
summary_txt << table.printLine
invoice_txt = <<HERE
INVOICE
#{invoice['bill_from']['name']}
#{invoice['bill_from']['street']}
#{invoice['bill_from']['locality']}
#{invoice['bill_from']['country']}
Invoice ##{invoice['number']}
Date: #{invoice['date']}
Bill To:
#{invoice['bill_to']['name']}
#{invoice['bill_to']['street']}
#{invoice['bill_to']['locality']}
#{invoice['bill_to']['country']}
#{table_txt}
#{summary_txt}
Total: #{invoice['total'].format}
Thank you for your business.
HERE
puts invoice_txt
# TODO: uncomment the next line if you want a text version
# File.open(invoice_save + 'txt', 'w') {|f| f.write(invoice_txt) }
# Generate HTML Invoice
invoice['total_amount'] = invoice['total'].format
invoice['summary'] = invoice['summary'].to_a
template_html = File.open("template/invoice.html").read
invoice_html = Liquid::Template.parse(template_html).render(invoice)
File.open(invoice_save + 'html', 'w') {|f| f.write(invoice_html) }
# Generate PDF Invoice
pdf_options = {
page_size: 'Letter',
lowquality: true,
dpi: 200,
margin_bottom: 10,
margin_left: 0,
margin_right: 0,
margin_top: 10,
zoom: 0.8,
disable_smart_shrinking: true
}
kit = PDFKit.new(invoice_html, pdf_options)
kit.to_file(invoice_save+'pdf')
end
def hmsToFloat(str)
sign = (str.chr == '-') ? str.slice!(0) : ''
parts = str.split(':').map(&:to_f)
(sign+(parts[0]+(parts[1]/60)+(parts[2]/3600)).to_s).to_f
end
#
# texttable.rb -- testing tool to output a nicely formatted table.
#
# John Allen, June 2005
# June 2010 -- Added support for word wrap fields
#
class TextTable
#
# tableinfo = Hash.new {
# "name" => Array(:string),
# "width" => Array(:fixnum),
# ["linebetweenrows" => Boolean,]
# ["hdrlinechar" => "=",]
# ["rowlinechar" => "-",]
# ["wordwrap" => Boolean]
# }
attr_accessor :names, :widths, :hdr_print_flg, :lbr_flg, :hdrchar, :linechar, :wordwrap
@hdr_print_flg = false
@ldr_flg = false
@wordwrap = false
def initialize(tableinfo)
@names = tableinfo["name"]
@widths = tableinfo["width"]
if tableinfo["linebetweenrows"]
@lbr_flg = true
end
if tableinfo["wordwrap"]
@wordwrap = true
end
@hdrchar = tableinfo["hdrlinechar"] || "="
@linechar = tableinfo["rowlinechar"] || "-"
end
def printrow(a)
# a = Array
a.map!(&:to_s) # Convert all array elements to string
buf = ""
if not @hdr_print_flg
buf << printHdr()
end
buf << "|"
extra = []
a.each_with_index do |n,i|
n ||= ''
if n.length > @widths[i] ## check to see if value is bigger than field; chop if so
b = n.slice(0..(@widths[i] -1))
extra[i] = n.slice(@widths[i]..-1)
else
b = n
end
buf << " #{b}#{" "*(@widths[i] - b.length)}|"
end
buf << "\n"
if @wordwrap and not extra.empty? ## Word Wrap
eflg = true
while eflg ## While stuff to word wrap
eflg = false
buf << "|"
extra.each_with_index do |n,i|
if not n.nil?
if n.length > @widths[i] ## check to see if value is bigger than field; chop if so
b = n.slice(0..(@widths[i] -1))
extra[i] = n.slice(@widths[i]..-1)
eflg = true ## still more to word wrap!!
else
b = n
extra[i] = nil
end
buf << " #{b}#{" "*(@widths[i] - b.length)}|"
else
buf << " #{" "*@widths[i]}|" ## add blank space for non-wordwrap field
end
end
buf << "\n"
end
end
buf << _line(@linechar) if @lbr_flg
return buf
end
def printHdr
buf = _line(@hdrchar)
buf << "|"
@names.each_with_index do |n,i|
buf << " #{n}#{" "*(@widths[i] - n.length)}|"
end
buf << "\n"
buf << _line(@hdrchar)
@hdr_print_flg = true
return buf
end
def printLine
buf = _line(@linechar)
return buf
end
#-------------------------------------------------------------------------------------------------------#
private
#-------------------------------------------------------------------------------------------------------#
def _line(char)
b = "+"
@names.each_with_index do |n,i|
b << char*@widths[i]
b << "#{char}+"
end
b << "\n"
return b
end
end
class Money
def to_liquid
format
end
end
main