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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
|
// sqlite.go contains all database operations
package main
import (
"database/sql"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/fatih/color"
_ "github.com/mattn/go-sqlite3"
)
type project struct {
id int
name string
comment string
first time.Time
last time.Time
finished int // id of last paid bill
customer int
}
type task struct {
id int
projectid int
start time.Time
stop time.Time
taskname string
comment string
checkout int // id of bill
}
type customer struct {
id int
company string
name string
address string
satz float64
lastbill time.Time // Last time a bill was paid
}
type billitem struct {
Task string
Time string
Hours float64
Money float64
}
type bill struct {
id int
identity string //invoice number
timerange string
project int
projectname string
date time.Time
paid time.Time
items []billitem
}
var db *sql.DB
var err error
var currproject project
var opentask task
var pausetask int
// Database Operations
// initDB tries to open an sqlite database of given filename
// and if it doesnt exit create it in the propper structure.
func initDB(filename string) {
if _, err := os.Stat(filename); os.IsNotExist(err) {
db, err = sql.Open("sqlite3", filename)
checkErr(err)
fmt.Println("Creating new DB", filename)
sqlstmt := `
CREATE TABLE projects(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(240) NOT NULL,
comment VARCHAR(240) DEFAULT '',
first TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
finished INTEGER DEFAULT NULL,
customer INTEGER DEFAULT NULL);
CREATE TABLE timetable(
id INTEGER PRIMARY KEY AUTOINCREMENT,
project INTEGER NOT NULL,
start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
stop TIMESTAMP DEFAULT '1791-09-30 19:07',
task VARCHAR(240) NOT NULL,
comment VARCHAR(240) DEFAULT '',
checkout INTEGER DEFAULT NULL);
CREATE TABLE customers(
id INTEGER PRIMARY KEY AUTOINCREMENT,
company VARCHAR(240),
name VARCHAR(240),
address VARCHAR(240) DEFAULT 'None',
satz REAL DEFAULT 1,
lastbill TIMESTAMP DEFAULT '1791-09-30 19:07' );
CREATE TABLE bills(
id INTEGER PRIMARY KEY AUTOINCREMENT,
identity VARCHAR(240),
timerange VARCHAR(240),
project INTEGER NOT NULL,
tasks VARCHAR(240),
times VARCHAR(240),
hours VARCHAR(240),
moneys VARCHAR(240),
paid TIMESTAMP DEFAULT '1791-09-30 19:07',
date TIMESTAMP DEFAULT '1791-09-30 19:07' );
CREATE TABLE vars(
id INTEGER PRIMARY KEY AUTOINCREMENT,
pauseid INTEGER DEFAULT NULL,
last TIMESTAMP DEFAULT '1791-09-30 19:07',
color INTEGER DEFAULT 1 );
CREATE TRIGGER first AFTER INSERT ON timetable
BEGIN
update vars SET last = datetime('now') WHERE id = 1;
END;
CREATE TRIGGER latest AFTER UPDATE ON timetable
BEGIN
update vars SET last = datetime('now') WHERE id = 1;
END;
`
_, err = db.Exec(sqlstmt)
checkErr(err)
stmt, err := db.Prepare("INSERT INTO customers(id,company,name) values(?, ?, ?)")
checkErr(err)
_, err = stmt.Exec(0, "No one", "Specific")
checkErr(err)
stmt, err = db.Prepare("INSERT INTO projects(id,name,customer,finished) values(?, ?, ?, ?)")
checkErr(err)
_, err = stmt.Exec(0, "None", 0, 0)
checkErr(err)
stmt, err = db.Prepare("INSERT INTO vars(pauseid,last) values(?,datetime('now'))")
checkErr(err)
_, err = stmt.Exec(0)
checkErr(err)
} else {
db, err = sql.Open("sqlite3", filename)
checkErr(err)
fmt.Println("Opening DB", filename, " - Last Usage:", lastUsage())
}
}
func lastUsage() (out string) {
var dat time.Time
rows, err := db.Query("SELECT last FROM vars WHERE id = 1")
checkErr(err)
for rows.Next() {
err = rows.Scan(&dat)
checkErr(err)
}
out = dat.Local().Format("2006 Mon Jan _2 15:04")
return
}
func GetColor() (col int) {
col = 1
rows, err := db.Query("SELECT color FROM vars WHERE id = $1",1)
checkErr(err)
for rows.Next() {
err = rows.Scan(&col)
checkErr(err)
}
return
}
func SetColor(col int) {
stmt, err := db.Prepare("UPDATE vars SET color = ? WHERE id = 1")
checkErr(err)
_, err = stmt.Exec(col)
checkErr(err)
}
func getPauseTask() (id int) {
rows, err := db.Query("SELECT pauseid FROM vars WHERE id = 1")
checkErr(err)
for rows.Next() {
err = rows.Scan(&id)
checkErr(err)
}
return
}
func setPauseTask(id int) {
stmt, err := db.Prepare("UPDATE vars SET pauseid = ? WHERE id = 1 ")
checkErr(err)
_, err = stmt.Exec(id)
checkErr(err)
pausetask = id
}
func newTaskTime(tim string) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Starting Task at ", tim),true))
bonus := ""
if opentask.id == 0 {
timstr := "1791-09-30 19:07"
//zone, _ := time.Now().Zone()
if isDateTime(tim) {
timstr = getDateTime(tim)
//timst = timstr+" "+zone
} else if isTime(tim) {
currdate := time.Now().Local().Format("2006-01-02")
timstr = currdate + " " + getTime(tim)
//timst = timstr+" "+zone
} else {
fmt.Println(nli,tim, boldRed("is Not a Valid Timestring!"), "use: 'YYYY-MM-DD HH:MM' or 'HH:MM'")
fmt.Println(frame(negR(),false))
return
//os.Exit(0)
}
stmt, err := db.Prepare("INSERT INTO timetable(project, start, task, checkout) values(?, datetime(?,'utc'), ?, ?)")
checkErr(err)
fmt.Println(nli+timstr)
task := getInterInput(sli+"Specify Task: ")
if task == "" {
nm,st := GetTaskSums(currproject.id)
ch := Multichoice("What Task should be Started at "+timstr+"?",st)
task = nm[ch]
bonus = line("xxx",true)
}
//if proj == 0 {
_, err = stmt.Exec(currproject.id, timstr, task, 0)
//} else {
// _, err = stmt.Exec(proj, timstr, task, 0)
//}
checkErr(err)
fmt.Println(bonus+nli+"...new task inserted into", currproject.name, ": ", task)
fmt.Println(bonus+frame(posR(),false))
getOpenTask()
updateProject(currproject.id)
} else {
fmt.Println(nli+boldRed("Another Task is already Open"))
//fmt.Println(frame("Close Task First",false))
showCurrentTask()
}
}
func newTask(resume bool) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
task := ""
bonus := ""
if resume {
fmt.Println(frame(boldGreen("Resuming Task"),true))
}else{
fmt.Println(frame(boldGreen("Starting Task Now"),true))
}
if opentask.id > 0 {
fmt.Println(nli+boldRed("Another Task is already Open"))
//showOpenTask()
fmt.Println(frame(negR(),false))
return
}
if resume {
if pausetask == 0 {
fmt.Println(nli+boldRed("No Task was Paused"))
if isInterSure(nli+"Resume older task?"){
nm,st := GetTaskSums(currproject.id)
ch := Multichoice("What Task should be resumed?",st)
task = nm[ch]
bonus = line("xxx",true)
}else{
fmt.Println(frame(negR(),false))
return
}
} else {
idx := []int{pausetask}
tsks := GetSelectedTasks(idx)
fulltask := tsks[0]
fmt.Println(nli+"Resuming Task ", pausetask, " - ", fulltask.taskname)
//fmt.Println()
task = fulltask.taskname
}
} else {
//fmt.Println(boldGreen("Starting new Task"))
task = getInterInput(sli+"Specify Task: ")
if task == "" {
nm,st := GetTaskSums(currproject.id)
ch := Multichoice("What Task should be resumed?",st)
task = nm[ch]
bonus = line("xxx",true)
}
}
stmt, err := db.Prepare("INSERT INTO timetable(project, task, checkout) values(?, ?, ?)")
checkErr(err)
_, err = stmt.Exec(currproject.id, task, 0)
checkErr(err)
if !resume {
fmt.Println(bonus+nli+"...New Task inserted into", currproject.name, ": ", task)
}
fmt.Println(bonus+frame(posR(),false))
getOpenTask()
updateProject(currproject.id)
}
func newBill(proj int) (int, string) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
//boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
//Show 5 recent bills
showLastBills(5)
fmt.Println(frame(boldGreen("Creating New Bill"),true))
invno := getInterInput(sli+"Invoice Number: ")
stmt, err := db.Prepare("INSERT INTO bills (identity, project, date) values(?, ?, datetime('now'))")
checkErr(err)
answ, err := stmt.Exec(invno, proj)
checkErr(err)
lid, _ := answ.LastInsertId()
//fmt.Println(frame("Bill "+ invno+" Created with ID "+lid),false)
fmt.Println(nli+"Bill", invno, "Created with ID", lid)
return int(lid), invno
}
func saveBill(in bill) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
tasks, times, hours, moneys := items2strings(in.items)
fmt.Println(nli+boldGreen("Saving Bill"), in.id)
stmt, err := db.Prepare("UPDATE bills SET identity = ?, timerange = ?, tasks = ?, times = ?, hours = ?, moneys = ? WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(in.identity, in.timerange, tasks, times, hours, moneys, in.id)
checkErr(err)
fmt.Println(frame(posR(),false))
}
func showLastBills(count int) {
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
//cn := "all"
//if count > 0 {
// cn = fmt.Sprint(count)
//}
//fmt.Printf(boldGreen("Loading %s Bills\n"), cn)
rows, err := db.Query("SELECT * FROM timetable")
if count == 0 {
rows, err = db.Query("SELECT * FROM bills ORDER BY date ASC")
} else if count > 0 {
rows, err = db.Query("SELECT * FROM bills ORDER BY date ASC LIMIT ?", count)
}
checkErr(err)
var id, proj int
var ident, timerange string
var date, paid time.Time
var taskstr, timestr, hourstr, moneystr string
defer rows.Close()
//fmt.Println("___Open Task________________")
if count == 0 {
fmt.Println(frame(boldGreen("All Bills"),true))
//fmt.Print("___All Previous Bills_______\n")
} else {
str := fmt.Sprintf("Previous %v Bills", count)
fmt.Println(frame(boldGreen(str),true))
}
i := 0
for rows.Next() {
i++
err = rows.Scan(&id, &ident, &timerange, &proj, &taskstr, ×tr, &hourstr, &moneystr, &paid, &date)
checkErr(err)
prn, _ := getProjectName(proj)
hsum := sumFloatArray(string2FloatArray(hourstr, ";"))
msum := sumFloatArray(string2FloatArray(moneystr, ";"))
fmt.Printf("%s %v:%s - %s (%v) %.1f[h]: %.2f[€] - ",nli, id, ident, prn, date.Local().Format("2006.01.02"), hsum, msum)
p := fmt.Sprintf("%v", paid)
if p == "1791-09-30 19:07:00 +0000 UTC" {
fmt.Print(boldRed("OPEN\n"))
} else {
fmt.Printf(boldGreen("%v\n"), paid.Local().Format("2006.01.02"))
}
}
if i == 0 {
fmt.Println(nli+"\n"+nli,boldRed(" NONE"))
}
fmt.Println(nli)
fmt.Println(frame("",false))
}
func loadBills(in []int) (out []bill) {
ins := strings.Trim(strings.Replace(fmt.Sprint(in), " ", " , ", -1), "[]")
que := fmt.Sprintf("SELECT * FROM bills WHERE id IN (%s) ORDER BY project DESC", ins)
rows, err := db.Query(que)
var id, proj int
var ident, timerange string
var date, paid time.Time
var taskstr, timestr, hourstr, moneystr string
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id, &ident, &timerange, &proj, &taskstr, ×tr, &hourstr, &moneystr, &paid, &date)
checkErr(err)
itms := strings2items(taskstr, timestr, hourstr, moneystr)
prname, _ := getProjectName(proj)
bi := bill{id, ident, timerange, proj, prname, date, paid, itms}
out = append(out, bi)
}
return
}
func strings2items(tasks, times, hours, moneys string) (out []billitem) {
ta := string2StringArray(tasks, ";")
ti := string2StringArray(times, ";")
ho := string2FloatArray(hours, ";")
mo := string2FloatArray(moneys, ";")
for i, _ := range ta {
out = append(out, billitem{ta[i], ti[i], ho[i], mo[i]})
}
return
}
func items2strings(in []billitem) (tasks, times, hours, moneys string) {
var tsk, tim []string
var hrs, mny []float64
for _, item := range in {
tsk = append(tsk, item.Task)
tim = append(tim, item.Time)
hrs = append(hrs, item.Hours)
mny = append(mny, item.Money)
}
tasks = stringArray2String(tsk, ";")
times = stringArray2String(tim, ";")
hours = strings.Trim(strings.Replace(fmt.Sprint(hrs), " ", ";", -1), "[]")
moneys = strings.Trim(strings.Replace(fmt.Sprint(mny), " ", ";", -1), "[]")
return
}
func closeTaskTime(tim string) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
//fmt.Println(boldGreen("Stoping Task ", opentask.id, ":", opentask.taskname))
fmt.Println(frame(boldGreen("Stoping Task"),true))
if opentask.id == 0 {
fmt.Println(nli+boldRed("There is no Open Task"))
fmt.Println(frame(negR(),false))
return
}else{
fmt.Println(nli,"ID ",opentask.id, ":", opentask.taskname)
}
//timt,err := time.Parse("2006-01-02 15:04",tim)
timst, timstr := "1791-09-30 19:07", "1791-09-30 19:07"
zone, _ := time.Now().Zone()
if isDateTime(tim) {
timstr = getDateTime(tim)
timst = timstr + " " + zone
} else if isTime(tim) {
timstr = time.Now().Local().Format("2006-01-02") + " " + getTime(tim)
timst = timstr + " " + zone
} else {
fmt.Println(nli,tim, boldRed("is Not a Valid Timestring!"), "use: 'YYYY-MM-DD HH:MM' or 'HH:MM'")
fmt.Println(frame(negR(),false))
return
//os.Exit(0)
}
timt, err := time.Parse("2006-01-02 15:04 MST", timst)
checkErr(err)
//fmt.Println(timst,timt,opentask.start)
if timt.After(opentask.start) {
//timstr := timt.UTC().Format("2006-01-02 15:04")
com := ""
if isInterSure(sli+"Do You Want to enter a Comment?") {
com = getInterMultiInput(nli+"Comment:")
}
fmt.Println(nli,"...Closing Task", opentask.id, "at", timst)
stmt, err := db.Prepare("UPDATE timetable SET stop = datetime(?,'utc'), comment = ? WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(timstr, com, opentask.id)
checkErr(err)
opentask.id = 0
updateProject(opentask.projectid)
fmt.Println(frame(posR(),false))
} else {
fmt.Println(nli,boldRed("Cannot Stop before the Beginning!"))
fmt.Println(frame(negR(),false))
return
}
//fmt.Println(tim,timt)
}
func closeTask(loud bool) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
if loud {
fmt.Println(frame(boldGreen("Stoping Task"),true))
if opentask.id == 0 {
fmt.Println(nli,boldRed("There is no Open Task"))
fmt.Println(frame(negR(),false))
return
}else{
fmt.Println(nli,"ID ",opentask.id, ":", opentask.taskname)
}
//fmt.Println(boldGreen("Stoping Task ", opentask.id, ":", opentask.taskname))
}else{
if opentask.id == 0 {
fmt.Println(boldRed("There is no Open Task"))
}
}
if time.Now().After(opentask.start.Local()) {
com := ""
if loud {
if isInterSure(sli+"Do You Want to enter a Comment?") {
com = getInterMultiInput(nli+"Comment:")
}
fmt.Println(nli+"...Closing Task", opentask.id)
fmt.Println(frame(posR(),false))
}
stmt, err := db.Prepare("UPDATE timetable SET stop = datetime('now'), comment = ? WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(com, opentask.id)
checkErr(err)
opentask.id = 0
updateProject(opentask.projectid)
} else {
if loud {
fmt.Println(nli,boldRed("Cannot Stop before the Beginning!"))
fmt.Println(frame(negR(),false))
}else{
fmt.Println(boldRed("Cannot Stop before the Begining!"))
}
}
}
func checkBill(bid int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
var custid int
fmt.Println(frame(boldGreen("Checking Bill"),true))
if !isBill(bid) {
fmt.Println(nli,bid, boldRed("is not a known bill ID"))
fmt.Println(frame(negR(),false))
return
}
bar := []int{bid}
bill := loadBills(bar)
if len(bill) < 1 {
fmt.Println(nli, boldRed("The Bill cannot be loaded."))
fmt.Println(frame(negR(),false))
return
} else {
pr, cu := getProjectName(bill[0].project)
custid = getCustomerId(bill[0].project)
//fmt.Println(bill[0])
fmt.Println(nli+"Marking Bill ", bid, " as Paid:\n"+nli, bill[0].identity, "\n"+nli+" For", cu, " :", pr)
_, _, ho, ma := items2strings(bill[0].items)
hsum := sumFloatArray(string2FloatArray(ho, ";"))
msum := sumFloatArray(string2FloatArray(ma, ";"))
fmt.Printf(nli+" Date: %s Hours: %.1f[h] Sum: %.2f[€]\n"+nli, bill[0].date.Local().Format("2006-01-02"), hsum, msum)
//fmt.Println(ta)
}
//timst,timstr := "1791-09-30 19:07","1791-09-30 19:07"
//zone, _ := time.Now().Zone()
timstr := "1791-09-30 19:07"
timin := getInterInput(sli+"Specify Date (YYYY-MM-DD): ")
if isDateTime(timin) {
timstr = getDateTime(timin)
} else if isDate(timin) {
//currdate := time.Now().Local().Format("2006-01-02")
timstr = getDate(timin) + " 12:00"
} else {
fmt.Println(nli+timin, boldRed("is Not a Valid Datestring!"), "use: 'YYYY-MM-DD'")
fmt.Println(frame(negR(),false))
return
}
fmt.Println(nli+boldGreen(timstr))
stmt, err := db.Prepare("UPDATE bills SET paid = datetime(?,'utc') WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(timstr, bid)
checkErr(err)
stmt, err = db.Prepare("UPDATE customers SET lastbill = datetime(?,'utc') WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(timstr, custid)
checkErr(err)
fmt.Println(frame(posR(),false))
}
func checkTasks(in []int, billid int) {
ins := strings.Trim(strings.Replace(fmt.Sprint(in), " ", " , ", -1), "[]")
que := fmt.Sprintf("UPDATE timetable SET checkout = ? WHERE id IN (%s)", ins)
//rows,err := db.Query(que)
stmt, err := db.Prepare(que)
checkErr(err)
_, err = stmt.Exec(billid)
checkErr(err)
}
func uncheckTasks(billid int) {
//ins := strings.Trim(strings.Replace(fmt.Sprint(in)," "," , ",-1),"[]")
//que := fmt.Sprintf("UPDATE timetable SET checkout = ? WHERE id IN (%s)",ins)
//rows,err := db.Query(que)
//stmt, err := db.Prepare(que)
stmt, err := db.Prepare("UPDATE timetable SET checkout = 0 WHERE checkout = ?")
checkErr(err)
_, err = stmt.Exec(billid)
checkErr(err)
}
func updateProject(id int) {
stmt, err := db.Prepare("UPDATE projects SET last = datetime('now') WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(id)
checkErr(err)
}
func getCustomerId(id int) (cust int) {
rows, err := db.Query("SELECT customer FROM projects WHERE id = ?", id)
checkErr(err)
for rows.Next() {
err = rows.Scan(&cust)
checkErr(err)
}
return
}
func getCustomerName(id int) (cust string) {
rows, err := db.Query("SELECT company, name FROM customers WHERE id = ?", id)
checkErr(err)
var nam, com string
for rows.Next() {
err = rows.Scan(&com, &nam)
checkErr(err)
}
cust = fmt.Sprintf("%s: %s", com, nam)
cust = fmt.Sprintf("%s", com)
return
}
func getProjectName(id int) (pro string, cust string) {
rows, err := db.Query("SELECT name, customer FROM projects WHERE id = ?", id)
checkErr(err)
//rows, err := stmt.Exec(id)
//checkErr(err)
cid := 0
for rows.Next() {
err = rows.Scan(&pro, &cid)
checkErr(err)
}
cust = getCustomerName(cid)
return
}
func checkCustomerProjects(in []int) (multicust, multiproj bool, projid []int) {
ins := strings.Trim(strings.Replace(fmt.Sprint(in), " ", " , ", -1), "[]")
que := fmt.Sprintf("SELECT project FROM timetable WHERE id IN (%s) ORDER BY project DESC", ins)
rows, err := db.Query(que)
prid, cuid, altprid, altcuid := 0, 0, 0, 0
multicust, multiproj = false, false
defer rows.Close()
for rows.Next() {
err = rows.Scan(&prid)
checkErr(err)
if altprid == 0 {
altprid = prid
projid = append(projid, prid)
} else {
if altprid != prid {
multiproj = true
altprid = prid
projid = append(projid, prid)
}
}
crows, err := db.Query("SELECT customer FROM projects WHERE id = ?", prid)
checkErr(err)
for crows.Next() {
err = crows.Scan(&cuid)
checkErr(err)
if altcuid == 0 {
altcuid = cuid
} else {
if altcuid != cuid {
multicust = true
altcuid = cuid
}
}
}
}
return
}
func getProject(id int) (outpr project, outcu customer) {
rows, err := db.Query("SELECT * FROM projects WHERE id = ?", id)
checkErr(err)
var pid, customer, finished int
var first, last time.Time
var name, comm string
for rows.Next() {
err = rows.Scan(&pid, &name, &comm, &first, &last, &finished, &customer)
checkErr(err)
outpr.id = pid
outpr.name = name
outpr.comment = comm
outpr.first = first
outpr.last = last
outpr.finished = finished
outpr.customer = customer
}
row, err := db.Query("SELECT * FROM customers WHERE id = ?", customer)
checkErr(err)
var cid int
var comp, cuname, addy string
var satz float64
var lastb time.Time
for row.Next() {
err = row.Scan(&cid, &comp, &cuname, &addy, &satz, &lastb)
checkErr(err)
outcu.id = cid
outcu.company = comp
outcu.name = cuname
outcu.address = addy
outcu.satz = satz
outcu.lastbill = lastb
}
return
}
// Return the []tasks correspintding to an []int of task ids
func GetSelectedTasks(in []int) (outtask []task) {
ins := strings.Trim(strings.Replace(fmt.Sprint(in), " ", " , ", -1), "[]")
que := fmt.Sprintf("SELECT * FROM timetable WHERE id IN (%s)", ins)
rows, err := db.Query(que)
checkErr(err)
var id, project, checkout int
var start, stop time.Time
var tsk, com string
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id, &project, &start, &stop, &tsk, &com, &checkout)
outtask = append(outtask, task{id, project, start, stop, tsk, com, checkout})
}
return
}
//Return sum of Hours and Dateranges
func AnalyzeTasks(in []task) (count int, hours float64, duration string) {
var lstart, hstop time.Time
for i, t := range in {
if i == 0 {
lstart = t.start
hstop = t.stop
}
count++
dur := float64(t.stop.Sub(t.start)) / (1000000000 * 60 * 60)
hours = hours + dur
if lstart.After(t.start) {
lstart = t.start
}
if hstop.Before(t.stop) {
hstop = t.stop
}
//txt := fmt.Sprintf("%s - (%v) - %.2f h",task, durstr, dur)
}
duration = fmt.Sprintf("%v - %v", lstart.Local().Format("02.01."), hstop.Local().Format("02.01.2006"))
//duration = fmt.Sprintf("%v - %v",lstart.Local().Format("01.02.2006"),hstop.Local().Format("01.02.2006"))
return
}
func getProjectList(in []int) ([]int, []string) {
var outids []int
var outstr []string
ins := strings.Trim(strings.Replace(fmt.Sprint(in), " ", " , ", -1), "[]")
que := fmt.Sprintf("SELECT id, name FROM projects WHERE id IN (%s) ORDER BY last DESC", ins)
rows, err := db.Query(que)
checkErr(err)
var id int
var name string
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id, &name)
checkErr(err)
outids = append(outids, id)
outstr = append(outstr, name)
}
return outids, outstr
}
func getTaskList(in []int, showcust bool) ([]int, []string) {
var outids []int
var outstr []string
lastpr := 0
pre := ""
prelen := 0
ins := strings.Trim(strings.Replace(fmt.Sprint(in), " ", " , ", -1), "[]")
que := fmt.Sprintf("SELECT id, project, start, stop, task FROM timetable WHERE id IN (%s) ORDER BY project DESC, stop DESC", ins)
rows, err := db.Query(que)
checkErr(err)
//rows,err := db.Query("SELECT id, project, start, stop, task FROM timetable WHERE id IN (?) ORDER BY project DESC, stop DESC",ins)
//rows,err := db.Query("SELECT id, project, start, stop, task FROM timetable WHERE stop != '1791-09-30 19:07' AND checkout = 0 AND id IN ? ORDER BY project DESC, stop DESC",in)
if len(in) == 1 && in[0] == 0 {
rows, err = db.Query("SELECT id, project, start, stop, task FROM timetable WHERE stop != '1791-09-30 19:07' AND checkout = 0 ORDER BY project DESC, stop DESC")
} //else{
// rows,err = db.Query("SELECT id, project, start, stop, task FROM timetable WHERE stop != '1791-09-30 19:07' AND checkout = 0 AND id IN ? ORDER BY project DESC, stop DESC",in)
//}
var id, project int
var task string
var start, stop time.Time
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id, &project, &start, &stop, &task)
checkErr(err)
if project != lastpr {
pr, cu := getProjectName(project)
if showcust {
pre = fmt.Sprintf("%v| %v: ", cu, pr)
} else {
pre = fmt.Sprintf("%v: ", pr)
}
prelen = utf8.RuneCountInString(pre)
lastpr = project
//outstr[len(outstr)-1]=fmt.Sprintf("%s\n%s - %s",outstr[len(outstr)-1],cu,pr)
} else {
pre = strings.Repeat(" ", prelen)
}
dur := float64(stop.Sub(start)) / (1000000000 * 60 * 60)
durstr := fmt.Sprintf("%v - %v", start.Local().Format("Mon Jan _2 2006 15:04"), stop.Local().Format("15:04"))
txt := fmt.Sprintf("%s - (%v) - %.2f h", task, durstr, dur)
outids = append(outids, id)
outstr = append(outstr, fmt.Sprintf("%s%s", pre, txt))
}
return outids, outstr
}
func getProjectIds() []int {
var ids []int
rows, err := db.Query("SELECT id FROM projects WHERE id != 0") // ORDER BY id DESC")
checkErr(err)
var id int
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id)
checkErr(err)
ids = append(ids, id)
}
return ids
}
func getTaskIds() []int {
var ids []int
rows, err := db.Query("SELECT id FROM timetable WHERE stop != '1791-09-30 19:07'") // ORDER BY id DESC")
checkErr(err)
var id int
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id)
checkErr(err)
ids = append(ids, id)
}
return ids
}
// Get All Tasks of Project with prid as a slice of Tasknames and
// a curresponding slice of strings to display
func GetTaskSums(prid int) (names,strings []string ) {
rows, err := db.Query("SELECT task FROM timetable WHERE stop != '1791-09-30 19:07' AND project = $1",prid)
checkErr(err)
var nam string
for rows.Next() {
err = rows.Scan(&nam)
checkErr(err)
if !IsStrElement(nam,names){
names = append(names, nam)
}
}
for _,na := range names {
var ids []int
var id int
quer := fmt.Sprintf("SELECT id FROM timetable WHERE stop != '1791-09-30 19:07' AND task = '%s' AND project = %v",na,prid)
//rows, err = db.Query("SELECT id FROM timetable WHERE stop != '1791-09-30 19:07' AND task = ' $1 ' AND project = $2",na,prid)
rows, err = db.Query(quer)
checkErr(err)
for rows.Next() {
err = rows.Scan(&id)
checkErr(err)
ids = append(ids,id)
}
tsks := GetSelectedTasks(ids)
//fmt.Println(na,ids)
//fmt.Println(tsks)
count,hours,daterange := AnalyzeTasks(tsks)
full := fmt.Sprintf("%s: %vx (%s) %.2f[h]",na,count,daterange,hours)
strings = append(strings, full)
}
return
}
func getOpenTask() {
rows, err := db.Query("SELECT id, project, start, task, checkout FROM timetable WHERE stop = '1791-09-30 19:07'")
checkErr(err)
var id, project, checkout int
var task string
var start time.Time
defer rows.Close()
for rows.Next() {
err = rows.Scan(&id, &project, &start, &task, &checkout)
checkErr(err)
//fmt.Println(id, "Open Task:", task, project, start)
}
//rows.Close() //good habit to close
opentask.id = id
opentask.projectid = project
opentask.start = start
opentask.taskname = task
opentask.checkout = checkout
//opentask.checkout = checkout != 0
}
func showStatus(full bool) {
/* boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Status"),true))
fmt.Println(sub("Current Project"))
fmt.Println(nli,currproject.id, ":", currproject.name, "- Started:", currproject.first.Local().Format("Mon _2 Jan 2006"))
fmt.Println(nli," Last Changes", currproject.last.Local().Format("2006 Mon Jan _2 15:04"))
*/
showOpenProject(true)
if full {
ShowProjectSum()
getClosedTasks(0)
}
showCurrentTask()
/* if opentask.id == 0 {
if pausetask > 0 {
st := fmt.Sprintf("Task %v Paused", pausetask)
fmt.Println(frame(st,false))
} else {
fmt.Println(frame("No Open Tasks",false))
}
} else {
fmt.Println(sub("Open Task"))
dur := float64(time.Now().Sub(opentask.start)) / (1000000000 * 60 * 60)
fmt.Printf("%s %v: %v - (%v) - %.2f h\n", nli, opentask.id, opentask.taskname, opentask.start.Local().Format("Mon Jan _2 2006 15:04"), dur)
fmt.Println(frame("",false))
}
*/
}
// Get all Tasks of the current Project and display them with simmilar name
func ShowProjectSum() {
_,st := GetTaskSums(currproject.id)
fmt.Println(sub("Tasks"))
fmt.Println(StrLines(st,nli))
fmt.Println(sub(""))
}
func showCurrentTask() {
if opentask.id == 0 {
if pausetask > 0 {
//fmt.Printf("___Task %v Paused___________\n", pausetask)
st := fmt.Sprintf("Task %v Paused", pausetask)
fmt.Println(frame(st,false))
} else {
//fmt.Println("___No Open Tasks____________")
fmt.Println(frame("No Open Tasks",false))
}
} else {
//fmt.Println("___Open Task________________")
fmt.Println(sub("Open Task"))
dur := float64(time.Now().Sub(opentask.start)) / (1000000000 * 60 * 60)
//fmt.Printf(" %v: %v - (%v) - %.2f h\n", opentask.id, opentask.taskname, opentask.start.Local().Format("Mon Jan _2 2006 15:04"), dur)
//fmt.Println(opentask.id,":", opentask.taskname,"-", opentask.start.Local().Format("Mon Jan _2 2006 15:04"),dur,"h")
fmt.Printf("%s %v: %v - (%v) - %.2f h\n", nli, opentask.id, opentask.taskname, opentask.start.Local().Format("Mon Jan _2 2006 15:04"), dur)
fmt.Println(frame("",false))
}
}
func showOpenProject(alone bool) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
//fmt.Println("___Last Project_____________")
if alone {
fmt.Println(frame(boldGreen("Current Project"),true))
}
fmt.Println(nli,currproject.id, ":", currproject.name, "- Started:", currproject.first.Local().Format("Mon _2 Jan 2006"))
fmt.Println(nli," Last Changes", currproject.last.Local().Format("2006 Mon Jan _2 15:04"))
//fmt.Println(frame("Current Project",true))
}
func addCustomer() {
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Adding new Customer"),true))
com := getInterInput(sli+"Enter Customer Company: ")
nam := getInterInput(sli+"Enter Customer Name: ")
add := getInterInput(sli+"Enter Address (separate lines by ; [Street;Zip;City;Country]): ")
sat := 0.0
for {
satstr := getInterInput(sli+"Hourly Rate: ")
sat, err = strconv.ParseFloat(satstr, 64)
//checkErr(err)
if err != nil {
fmt.Println(nli,satstr, boldRed("can not be Parsed as a Float."), "Try a shape of X.X")
} else {
break
}
}
stmt, err := db.Prepare("INSERT INTO customers(company, name, address, satz) values(?, ?, ?, ?)")
checkErr(err)
_, err = stmt.Exec(com, nam, add, sat)
checkErr(err)
fmt.Println(nli,boldGreen(" Customer Successfully Added:"), com, nam, add, sat)
fmt.Println(frame(posR(),false))
}
func newProject() {
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Creating new Project"),true))
if opentask.id > 0 {
fmt.Println(nli,boldRed("There is an Open Task"))
fmt.Println(frame(negR(),false))
//showOpenTask()
return
}
if pausetask > 0 {
fmt.Println(sli,boldRed("Task ", pausetask, " pause status removed"))
fmt.Println(nli)
setPauseTask(0)
}
//fmt.Println(boldGreen("Creating new Project"))
nam := getInterInput(sli+"Enter Project Name: ")
icust := 0
allCustomers(true)
for {
cust := getInterInput(sli+"Enter Customer id: ")
icust, err = strconv.Atoi(cust)
if err == nil && (isCustomer(icust) || icust == 0) {
break
} else {
fmt.Println(nli,cust, boldRed("is an invalid ID or Not a known Customer"))
}
}
comm := ""
if isInterSure(sli+"Do you want to Comment the Project?") {
comm = getInterMultiInput(nli+"New Comment: ")
}
stmt, err := db.Prepare("INSERT INTO projects(name, comment, finished, customer) values(?, ?, ?, ?)")
checkErr(err)
_, err = stmt.Exec(nam, comm, 0, icust)
checkErr(err)
fmt.Println(nli," Project Created:", nam)
fmt.Println(frame(posR(),false))
getLastProject()
}
func getClosedTasks(num int) {
rows, err := db.Query("SELECT * FROM timetable WHERE stop != '1791-09-30 19:07' ORDER BY datetime(start)", currproject.id)
checkErr(err)
if num > 0 {
rows, err = db.Query("SELECT * FROM timetable WHERE project = $1 AND checkout > 0 AND stop != '1791-09-30 19:07' ORDER BY datetime(start) DESC LIMIT $2", currproject.id, num)
checkErr(err)
} else {
rows, err = db.Query("SELECT * FROM timetable WHERE project = $1 AND checkout > 0 AND stop != '1791-09-30 19:07' ORDER BY datetime(start)", currproject.id)
checkErr(err)
}
var id, proj, check int
var sta, sto time.Time
var tas, com string
var sum, dur float64 = 0.0, 0.0
checkErr(err)
first := true
//if err != nil && err != sql.ErrNoRows {
// fmt.Println("___Billed Tasks_______________")
//}
for rows.Next() {
if first {
//fmt.Println("___Billed Tasks_______________")
fmt.Println(sub("Billed Tasks"))
first = false
}
err = rows.Scan(&id, &proj, &sta, &sto, &tas, &com, &check)
checkErr(err)
dur = float64(sto.Sub(sta)) / (1000000000 * 60 * 60)
fmt.Printf("%s %v: %v (%v-%v) - %.2f h\n", nli, id, tas, sta.Local().Format("2006 Mon Jan _2 15:04"), sto.Local().Format("15:04"), dur)
//fmt.Println(id,tas,sta.Local().Format("2006 Mon Jan _2 15:04"),sto.Local().Format("15:04"),dur,"h")
sum += dur
}
if !first {
//fmt.Println("____________________________")
//fmt.Printf("Billed: %.2f h\n", sum)
st := fmt.Sprintf("Billed: %.2f h", sum)
fmt.Println(sub(st))
fmt.Println(nli)
}
rows.Close()
if num > 0 {
rows, err = db.Query("SELECT * FROM timetable WHERE project = $1 AND checkout = 0 AND stop != '1791-09-30 19:07'ORDER BY datetime(start) DESC LIMIT $2", currproject.id, num)
checkErr(err)
} else {
rows, err = db.Query("SELECT * FROM timetable WHERE project = $1 AND checkout = 0 AND stop != '1791-09-30 19:07'ORDER BY datetime(start)", currproject.id)
checkErr(err)
}
sum2 := 0.0
first = true
//if err != nil && err != sql.ErrNoRows{
// fmt.Println("___Past Tasks_______________")
//}
for rows.Next() {
if first {
//fmt.Println("___Past Tasks_______________")
fmt.Println(sub("Past Tasks"))
first = false
}
err = rows.Scan(&id, &proj, &sta, &sto, &tas, &com, &check)
checkErr(err)
dur = float64(sto.Sub(sta)) / (1000000000 * 60 * 60)
fmt.Printf("%s %v: %v (%v-%v) - %.2f h\n", nli, id, tas, sta.Local().Format("2006 Mon Jan _2 15:04"), sto.Local().Format("15:04"), dur)
//fmt.Println(id,tas,sta.Local().Format("2006 Mon Jan _2 15:04"),sto.Local().Format("15:04"),dur,"h")
sum2 += dur
}
//if err != nil && err != sql.ErrNoRows{
if !first {
//fmt.Println("____________________________")
//fmt.Printf("Unbilled: %.2f[h] Total: %.2f[h]\n", sum2, sum+sum2)
st := fmt.Sprintf("Unbilled: %.2f[h] Total: %.2f[h]", sum2, sum+sum2)
fmt.Println(sub(st))
}
rows.Close()
}
func getLastProject() {
rows, err := db.Query("SELECT * FROM projects")
checkErr(err)
var uid, nuid int
var prname, nprname, prcom, nprcom string
var first, nfirst time.Time
var last, nlast time.Time
var finish, nfinish int
var custom, ncustom int
for rows.Next() {
err = rows.Scan(&uid, &prname, &prcom, &first, &last, &finish, &custom)
checkErr(err)
if last.After(nlast) {
nuid = uid
nprname = prname
nprcom = prcom
nfirst = first
nlast = last
nfinish = finish
ncustom = custom
}
}
rows.Close() //good habit to close
currproject.id = nuid
currproject.name = nprname
currproject.comment = nprcom
currproject.first = nfirst
currproject.last = nlast
currproject.finished = nfinish
//currproject.finish = nfinish != 0
currproject.customer = ncustom
}
func setProject(nid int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Opening Project ", nid),true))
if opentask.id > 0 {
fmt.Println(nli,boldRed("There is an Open Task"))
//fmt.Println(frame("",false))
showCurrentTask()
return
}
if pausetask > 0 {
fmt.Println(sli,boldRed("Task ", pausetask, " pause status removed"))
fmt.Println(nli)
setPauseTask(0)
}
if !isProject(nid) {
//fmt.Println(boldGreen("Opening Project ", nid))
//} else {
fmt.Println(nli,boldRed("There is no Project"), nid)
fmt.Println(frame("",false))
return
}
rows, err := db.Query("SELECT * FROM projects WHERE id = $1", nid)
checkErr(err)
var uid int
var prname, comm string
var first time.Time
var last time.Time
var finish int
var custo int
for rows.Next() {
err = rows.Scan(&uid, &prname, &comm, &first, &last, &finish, &custo)
checkErr(err)
}
rows.Close() //good habit to close
currproject.id = uid
currproject.name = prname
currproject.comment = comm
currproject.first = first
currproject.last = last
currproject.finished = finish
//currproject.finish = finish != 0
currproject.customer = custo
updateProject(uid)
showOpenProject(false)
showCurrentTask()
}
func getCustomerList() (outint []int, outstr []string) {
rows, err := db.Query("SELECT id, company, name FROM customers")
checkErr(err)
var id int
var comp string
var name string
for rows.Next() {
err = rows.Scan(&id, &comp, &name)
checkErr(err)
st := fmt.Sprintf("%s: %s", comp, name)
outint = append(outint, id)
outstr = append(outstr, st)
}
return
}
func allCustomers(inline bool) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
rows, err := db.Query("SELECT * FROM customers")
//rows,err := db.Query("SELECT (id, company, name, address, satz, lastbill) FROM customers")
checkErr(err)
var uid int
var comp string
var name string
var addr string
var satz float64
var last time.Time
//fmt.Println("___All Customers________________")
if inline {
fmt.Println(sub(boldGreen("All Customers")))
}else{
fmt.Println(frame(boldGreen("All Customers"),true))
}
cnt := 0
for rows.Next() {
cnt++
err = rows.Scan(&uid, &comp, &name, &addr, &satz, &last)
checkErr(err)
lstr := last.Local().Format("2006-01-02 15:04 MST")
if lstr == "1791-09-30 20:12 LMT" {
lstr = "Never"
}
if uid > 0 {
fmt.Printf("%s %v:%s: %s, Rate: %.2f[€/h] , Last Paid Bill: %s\n", nli, uid, comp, name, satz, lstr)
}
}
if cnt==0 {
fmt.Println(nli," Nobody")
}
if inline {
fmt.Println(sub(""))
}else{
fmt.Println(frame("",false))
}
}
func allProjects() {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
//fmt.Println(boldGreen("Loading all customers"))
//fmt.Println("___All Projects________________")
fmt.Println(frame(boldGreen("All Projects"),true))
rows3, err := db.Query("SELECT * FROM customers")
checkErr(err)
var cid int
var com string
var nam string
var adr string
var sat float64
var lst time.Time
for rows3.Next() {
err = rows3.Scan(&cid, &com, &nam, &adr, &sat, &lst)
checkErr(err)
rows, err := db.Query("SELECT * FROM projects WHERE customer = $1", cid)
checkErr(err)
var uid int
var prname, comm string
var first time.Time
var last time.Time
var finish int
var customer, check int
var start, stop time.Time
fmt.Printf("%s%s %s: %s, %s\n",ssli,li,"For", com, nam)
for rows.Next() {
err = rows.Scan(&uid, &prname, &comm, &first, &last, &finish, &customer)
checkErr(err)
rows2, err := db.Query("SELECT start, stop, checkout FROM timetable WHERE project = $1 AND stop != '1791-09-30 19:07'", uid)
checkErr(err)
sumb, sumo := 0.0, 0.0
for rows2.Next() {
err = rows2.Scan(&start, &stop, &check)
checkErr(err)
if check == 0 {
sumo += float64(stop.Sub(start)) / (1000000000 * 60 * 60)
} else {
sumb += float64(stop.Sub(start)) / (1000000000 * 60 * 60)
}
}
//fmt.Printf(" %v:%s \n First: %s, Last:%s, Total:%.2f(h) ,Fin:%v, For:%v\n",uid,prname,first.Local().Format("2006-01-02 15:04 MST"),last.Local().Format("2006-01-02 15:04 MST"),sum,finish,customer)
if (sumo + sumb) > 0 {
fmt.Printf("%s %v:%s \n", sli, uid, prname)
fmt.Printf("%s Unbilled: %.2f[h] Billed: %.2f[h] | Total: %.2f[h]\n", nli, sumo, sumb, sumo+sumb)
//fmt.Printf(" First: %s, Last:%s, Fin:%v, For:%v\n\n",first.Local().Format("2006-01-02 15:04 MST"),last.Local().Format("2006-01-02 15:04 MST"),finish,customer)
fmt.Printf("%s First: %s, Last:%s, \n%s\n", nli, first.Local().Format("2006-01-02 15:04 MST"), last.Local().Format("2006-01-02 15:04 MST"),nli)
} else {
if uid >0 {
fmt.Print(sli," Nothing\n")
}
}
rows2.Close() //good habit to close
}
rows.Close() //good habit to close
}
rows3.Close() //good habit to close
fmt.Println(frame("",false))
//fmt.Println("_______________________________\n")
}
func deleteBill(id int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Deleting Bill ", id),true))
var prj int
var identity, moneys, hours string
var date time.Time
rows, err := db.Query("SELECT project, date, identity, hours, moneys FROM bills WHERE id = $1", id)
checkErr(err)
if rows.Next() {
err = rows.Scan(&prj, &date, &identity, &hours, &moneys)
checkErr(err)
rows.Close() //good habit to close
prstr, custr := getProjectName(prj)
hsum := sumFloatArray(string2FloatArray(hours, ";"))
msum := sumFloatArray(string2FloatArray(moneys, ";"))
fmt.Printf("%s %v: For %v- %v (%v) - %.1f[h] : %.2f[€]\n", nli, identity, custr, prstr, date.Local().Format("2006 Mon Jan _2"), hsum, msum)
if isInterSure(sli+"Are You Sure?") {
uncheckTasks(id) //Set corresponding Tasks to checkout=0
stmt, err := db.Prepare("DELETE FROM bills WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(id)
checkErr(err)
fmt.Println(nli,boldGreen("Bill ", id, " deleted successfully!"))
} else {
fmt.Println(frame(negR(),false))
return
}
} else {
fmt.Println(nli,boldRed(id, " is Not a known Bill!"))
showLastBills(0)
}
fmt.Println(frame("",false))
}
func deleteTask(id int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Deleting Task ", id),true))
var chk, prj int
var start, stop time.Time
var task, comm string
rows, err := db.Query("SELECT project, start, stop, task, comment, checkout FROM timetable WHERE id = $1", id)
checkErr(err)
if rows.Next() {
err = rows.Scan(&prj, &start, &stop, &task, &comm, &chk)
checkErr(err)
rows.Close() //good habit to close
//fmt.Println(boldGreen("Delete Task", id))
dur := float64(stop.Sub(start)) / (1000000000 * 60 * 60)
fmt.Printf("%s %v: %v (%v-%v) - %.2f h\n Comments:\n%s\n", nli, prj, task, start.Local().Format("2006 Mon Jan _2 15:04"), stop.Local().Format("15:04"), dur, comm)
if isInterSure(sli+"Are You Sure?") {
stmt, err := db.Prepare("DELETE FROM timetable WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(id)
checkErr(err)
fmt.Println(nli,boldGreen("Task ", id, " deleted successfully!"))
} else {
fmt.Println(frame(negR(),false))
return
}
} else {
fmt.Println(nli,boldRed(id, " is Not a known Task!"))
}
fmt.Println(frame("",false))
}
func editCustomer(id int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Editing Customer ", id),true))
var comp, name, addr string
var satz float64
rows, err := db.Query("SELECT company, name, address, satz FROM customers WHERE id = $1", id)
checkErr(err)
if rows.Next() {
err = rows.Scan(&comp, &name, &addr, &satz)
checkErr(err)
} else {
fmt.Println(nli+boldRed("There Is No Customer"), id)
return
//os.Exit(0)
}
rows.Close() //good habit to close
//fmt.Println(boldGreen("Edit Customer",id))
/*fmt.Println("Old Company Name:",comp)
in := getInterInput("Enter New:")
if in!=""{
comp=in
}*/
comp = getNewInterInput("New Company Name: ", comp, nli)
/*fmt.Println("Old Name:",name)
in = getInterInput("Enter New:")
if in!=""{
name=in
}*/
name = getNewInterInput("New Customer Name: ", name, nli)
/*fmt.Println("Old Adress:",addr)
in = getInterInput("Enter New:")
if in!=""{
addr=in
}*/
addr = getNewInterInput("New Adress: ", addr, nli)
//fmt.Println("Old Hourly Rate:",satz)
for {
satzstr := getNewInterInput("New Hourly Rate: ", fmt.Sprintf("%.2f", satz), nli)
satz, err = strconv.ParseFloat(satzstr, 64)
if err != nil {
fmt.Println(nli,satzstr, boldRed("can not be Parsed as a Float."), "Try a shape of X.X")
//os.Exit(0)
} else {
break
}
/*satzstr := getInterInput("Enter New:")
if satzstr!=""{
satz,err = strconv.ParseFloat(satzstr,64)
if err != nil {
fmt.Println(satzstr,boldRed("can not be Parsed as a Float."), "Try a shape of X.X")
//os.Exit(0)
}else{break}
}else{break}*/
}
stmt, err := db.Prepare("UPDATE customers SET company = ?, name = ?, address = ?, satz = ? WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(comp, name, addr, satz, id)
checkErr(err)
fmt.Println(nli,"...Customer", id, "Updated")
fmt.Println(frame("",false))
}
func editTask(id int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Edit Task ", id),true))
var chk, prj int
var start, stop time.Time
var task, startstr, stopstr, comm string
rows, err := db.Query("SELECT project, start, stop, task, comment, checkout FROM timetable WHERE id = $1", id)
checkErr(err)
if rows.Next() {
err = rows.Scan(&prj, &start, &stop, &task, &comm, &chk)
checkErr(err)
} else {
fmt.Println(nli,boldRed("There Is No Task"), id)
return
//os.Exit(0)
}
rows.Close() //good habit to close
/* fmt.Println("Old Name:",task)
in := getInterInput("Enter New:")
if in!=""{
task=in
}*/
task = getNewInterInput("New Task Name: ", task, nli)
startstr = start.Local().Format("2006-01-02 15:04")
stopstr = stop.Local().Format("2006-01-02 15:04")
for {
newstartstr := getNewInterInput("New Start time: ", startstr, nli)
if !isDateTime(newstartstr) {
fmt.Println(nli, newstartstr, boldRed("is Not a Valid Timestring!"), "use: 'YYYY-MM-DD HH:MM'")
} else {
startstr = newstartstr
break
}
}
//fmt.Println("Old End:",stopstr)
for {
newend := getNewInterInput("New Stop time: ", stopstr, nli)
if isDateTime(newend) {
stopstr = newend
break
} else {
fmt.Println(nli, newend, boldRed("is Not a Valid Timestring!"), "use: 'YYYY-MM-DD HH:MM' or 'HH:MM'")
}
}
//fmt.Println("Old Project:",prj)
for {
newprj := getNewInterInput("New Project id: ", fmt.Sprint(prj), nli)
prj, err = strconv.Atoi(newprj)
if err != nil {
fmt.Println(nli,newprj, boldRed("is Not a Valid id."), "Try an Integer instead")
}
if !isProject(prj) {
fmt.Println(nli, boldRed("There is no project"), prj)
} else {
break
}
}
comm = getNewInterMultiInput("New Comment: ", comm, nli)
stmt, err := db.Prepare("UPDATE timetable SET task = ?, comment = ?, start = datetime(?,'utc'), stop = datetime(?,'utc'), project = ? WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(task, comm, startstr, stopstr, prj, id)
checkErr(err)
updateProject(prj)
fmt.Println(nli, "...Task", id, "Updated")
fmt.Println(frame("",false))
}
func editProject(id int) {
boldGreen := color.New(color.FgGreen, color.Bold).SprintFunc()
boldRed := color.New(color.FgRed, color.Bold).SprintFunc()
fmt.Println(frame(boldGreen("Edit Project ", id),true))
var fin, cust int
var first time.Time
var name, nfirst, comm string
rows, err := db.Query("SELECT name, comment, first, finished, customer FROM projects WHERE id = $1", id)
checkErr(err)
if rows.Next() {
err = rows.Scan(&name, &comm, &first, &fin, &cust)
checkErr(err)
name = getNewInterInput("New Name: ", name, nli)
nfirst = first.Local().Format("2006-01-02 15:04")
// Get New PRoject Begin Date
for {
newfirststr := getNewInterInput("New Begin time: ", nfirst, nli)
if !isDateTime(newfirststr) {
fmt.Println(nli,newfirststr, boldRed("is Not a Valid Timestring!"), "use: 'YYYY-MM-DD HH:MM'")
} else {
nfirst = newfirststr
break
}
}
// Get New Customer
for {
newcu := getNewInterInput("New Customer id: ", fmt.Sprint(cust), nli)
icust, err := strconv.Atoi(newcu)
if err != nil {
fmt.Println(nli,newcu, boldRed("is Not a Valid id."), "Try an Integer instead")
} else if !isCustomer(icust) {
fmt.Println(nli,boldRed("There is no Customer"), icust)
} else {
cust = icust
break
}
}
// Get Comment
comm = getNewInterMultiInput("New Comment: ", comm, nli)
} else {
fmt.Println(nli,boldRed("There Is No Project"), id)
fmt.Println(frame(negR(),false))
return
//os.Exit(0)
}
rows.Close() //good habit to close
stmt, err := db.Prepare("UPDATE projects SET name = ?, comment = ?, last = datetime(?,'utc'), customer = ? WHERE id = ?")
checkErr(err)
_, err = stmt.Exec(name, comm, nfirst, cust, id)
checkErr(err)
updateProject(id)
fmt.Println(nli,"...Project", id, "Updated")
fmt.Println(frame("",false))
}
func PromptColor(col int) (mastercol *color.Color){
boldBlue := color.New(color.FgBlue, color.Bold)//.SprintFunc()
boldRed := color.New(color.FgRed, color.Bold)//.SprintFunc()
boldMag := color.New(color.FgMagenta, color.Bold)//.SprintFunc()
boldCyan := color.New(color.FgCyan, color.Bold)//.SprintFunc()
boldGreen := color.New(color.FgGreen, color.Bold)//.SprintFunc()
boldYell := color.New(color.FgYellow, color.Bold)//.SprintFunc()
//boldCol := color.New(color.FgYellow, color.Bold).SprintFunc()
SetColor(col)
switch col {
case 0:
mastercol = boldMag
case 1:
mastercol = boldBlue
case 2:
mastercol = boldCyan
case 3:
mastercol = boldGreen
case 4:
mastercol = boldYell
case 5:
mastercol = boldRed
}
return
}
func isBill(id int) bool {
rows, err := db.Query("SELECT * FROM bills WHERE id = $1", id)
checkErr(err)
defer rows.Close()
if rows.Next() {
return true
} else {
return false
}
}
func isTask(id int) bool {
rows, err := db.Query("SELECT * FROM timetable WHERE id = $1", id)
checkErr(err)
defer rows.Close()
if rows.Next() {
return true
} else {
return false
}
}
func isProject(id int) bool {
rows, err := db.Query("SELECT * FROM projects WHERE id = $1", id)
checkErr(err)
defer rows.Close()
if rows.Next() {
return true
} else {
return false
}
}
func isCustomer(id int) bool {
rows, err := db.Query("SELECT * FROM customers WHERE id = $1", id)
checkErr(err)
defer rows.Close()
if rows.Next() {
return true
} else {
return false
}
}
func getDateTime(in string) string {
r := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})`)
//r := regexp.MustCompile(`(\d{4})-(((0)[0-9])|((1)[0-2]))-([0-2][0-9]|(3)[0-1]) ([01]?[0-9]|2[0-3]):[0-5][0-9]`)
return r.FindString(in)
}
func getDate(in string) string {
//r := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)
r := regexp.MustCompile(`(\d{4})-(((0)[0-9])|((1)[0-2]))-([0-2][0-9]|(3)[0-1])`)
return r.FindString(in)
}
func getTime(in string) string {
//r := regexp.MustCompile(`(\d{2}):(\d{2})`)
r := regexp.MustCompile(`([01]?[0-9]|2[0-3]):[0-5][0-9]`)
return r.FindString(in)
}
func isDateTime(in string) bool {
//match, _ := regexp.MatchString(`(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})`, in)
//match, _ := regexp.MatchString(`(\d{4})-(((0)[0-9])|((1)[0-2]))-([0-2][0-9]|(3)[0-1]) ([01]?[0-9]|2[0-3]):[0-5][0-9]`, in)
const form = "2006-01-02 15:04"
_,err := time.Parse(form,in)
if err == nil {
return true
}
return false
}
func isDate(in string) bool {
//match, _ := regexp.MatchString(`(\d{4})-(\d{2})-(\d{2})`, in)
//match, _ := regexp.MatchString(`(\d{4})-(((0)[0-9])|((1)[0-2]))-([0-2][0-9]|(3)[0-1])`, in)
//return match
const form = "2006-01-02"
_,err := time.Parse(form,in)
if err == nil {
return true
}
return false
}
func isTime(in string) bool {
//match, _ := regexp.MatchString(`(\d{2}):(\d{2})`, in)
//match, _ := regexp.MatchString(`([01]?[0-9]|2[0-3]):[0-5][0-9]`, in)
//return match
const form = "15:04"
_,err := time.Parse(form,in)
if err == nil {
return true
}
return false
}
/*
func getInput(quest string) string {
fmt.Print(quest)
in := bufio.NewReader(os.Stdin)
line, err := in.ReadString('\n')
line = strings.TrimSuffix(line, "\n")
checkErr(err)
return line
}*/
/*
func isSure() bool {
fmt.Print("Are You Sure ? (type 'yes' to confirm) : ")
in := bufio.NewReader(os.Stdin)
line, err := in.ReadString('\n')
line = strings.TrimSuffix(line, "\n")
checkErr(err)
if line == "yes" {
return true
} else {
return false
}
}*/
/*
func isElement(some int, group []int) bool {
for _, e := range group {
if e == some {
return true
}
}
return false
}
func removeItems(master, rem []int) []int {
var out []int
for _, v := range master {
if !isElement(v, rem) {
out = append(out, v)
}
}
return out
}*/
/*
func checkErr(err error) {
if err != nil {
panic(err)
}
}*/
|