Compare commits
599 Commits
v1.2.9
...
Hargata/up
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29680cf0e9 | ||
|
|
723eb1a769 | ||
|
|
732a628c20 | ||
|
|
84d40edb0e | ||
|
|
9842f0e501 | ||
|
|
44c5f921a5 | ||
|
|
fae4aa31aa | ||
|
|
adb505c87c | ||
|
|
d21b0a9e29 | ||
|
|
15e4181aff | ||
|
|
3a4627ef02 | ||
|
|
d9e11273bd | ||
|
|
8e6f40a1b1 | ||
|
|
55f86ecb3f | ||
|
|
8eef1465cf | ||
|
|
fd0ffba7c4 | ||
|
|
afb710e6ad | ||
|
|
419b755e7a | ||
|
|
8cd5342c02 | ||
|
|
fa32ecdb5a | ||
|
|
d08726bd85 | ||
|
|
a87861069b | ||
|
|
b6d6a8765d | ||
|
|
f307c0933a | ||
|
|
9968ccb541 | ||
|
|
5d3746f168 | ||
|
|
df0c4eeca2 | ||
|
|
5b3c0aed72 | ||
|
|
040728b96d | ||
|
|
e8b7b3e4ba | ||
|
|
cf1f1a884b | ||
|
|
c470db0590 | ||
|
|
cb71650adf | ||
|
|
923d59af0a | ||
|
|
d68e1a3939 | ||
|
|
bf954a2946 | ||
|
|
d3f29be227 | ||
|
|
5afe88a33a | ||
|
|
6937eff576 | ||
|
|
6371cccc48 | ||
|
|
fc174160e0 | ||
|
|
876f99fd26 | ||
|
|
75c65b4681 | ||
|
|
76031d27d7 | ||
|
|
4079a93c3e | ||
|
|
d913ab2009 | ||
|
|
6bfbcc4374 | ||
|
|
73d9a7e6e9 | ||
|
|
3cbce8b584 | ||
|
|
e4fcb52b24 | ||
|
|
ae4f01ac9a | ||
|
|
46b3845b3e | ||
|
|
ffb126276f | ||
|
|
a9e4be823d | ||
|
|
56cae008a6 | ||
|
|
c2dd379ea3 | ||
|
|
baa569b323 | ||
|
|
64ce0f8c07 | ||
|
|
bd98e5a6cd | ||
|
|
83fc8b8682 | ||
|
|
89fa15bbb7 | ||
|
|
5e69be56aa | ||
|
|
b1112dc617 | ||
|
|
5a31460afe | ||
|
|
2bcedbc7d4 | ||
|
|
5047fdf1bc | ||
|
|
7c8c3fb1c8 | ||
|
|
9920bd472f | ||
|
|
d7839a8a05 | ||
|
|
7e07e73ef5 | ||
|
|
72a5960d40 | ||
|
|
3429f1e4f9 | ||
|
|
f8bea8bf81 | ||
|
|
43794dd223 | ||
|
|
5cc84a7b46 | ||
|
|
48248a4386 | ||
|
|
95305402e6 | ||
|
|
29f24c527f | ||
|
|
efa2bbf6cc | ||
|
|
66ed9ba699 | ||
|
|
e841e64f78 | ||
|
|
b0f46803c5 | ||
|
|
ac0bef5de0 | ||
|
|
08ea40a08e | ||
|
|
1d8e8059cd | ||
|
|
20b4396a4c | ||
|
|
4c39cb4d06 | ||
|
|
f58e6abd9f | ||
|
|
4f1e83a7d7 | ||
|
|
e39b38c2d5 | ||
|
|
b9ffa6ce91 | ||
|
|
76c6753785 | ||
|
|
54f5062377 | ||
|
|
7e60fd9e40 | ||
|
|
926947bae4 | ||
|
|
2652e47018 | ||
|
|
c1500b6ed0 | ||
|
|
125bc44d2e | ||
|
|
c317c0a058 | ||
|
|
beb9498399 | ||
|
|
4e74940684 | ||
|
|
c0f73080d2 | ||
|
|
cd0a35537b | ||
|
|
4d5020b607 | ||
|
|
7d8b7596ce | ||
|
|
08b5c9f25a | ||
|
|
82a4f8d57b | ||
|
|
538a79319e | ||
|
|
0555dcbc43 | ||
|
|
7b1f19ff9f | ||
|
|
9cac427eb9 | ||
|
|
1e5950028f | ||
|
|
7a7d343c3f | ||
|
|
ebf6388414 | ||
|
|
fa5426be53 | ||
|
|
4c60bb20c9 | ||
|
|
b02f3c8f8b | ||
|
|
d5f769e5a4 | ||
|
|
2afd1188eb | ||
|
|
1c6301242d | ||
|
|
06016727d9 | ||
|
|
1ee0c27ff9 | ||
|
|
7f03a630c6 | ||
|
|
2aa19f4f3b | ||
|
|
4be3c16adc | ||
|
|
f1f99a67dd | ||
|
|
a4f15ffe15 | ||
|
|
c11dad0cb3 | ||
|
|
2bf2469657 | ||
|
|
a23b02e962 | ||
|
|
905ee9bf27 | ||
|
|
e26869b30b | ||
|
|
90867792d9 | ||
|
|
1238802a75 | ||
|
|
8f7c50b88f | ||
|
|
df24434689 | ||
|
|
878748803d | ||
|
|
80bbf7f22f | ||
|
|
28b0ea565a | ||
|
|
07ccd1dea9 | ||
|
|
6a8fba535a | ||
|
|
f1b82ad0d3 | ||
|
|
0035bc09dd | ||
|
|
863c57d7fb | ||
|
|
00ccb68ce2 | ||
|
|
c2995dcd25 | ||
|
|
7b63366627 | ||
|
|
ababa6bf27 | ||
|
|
3f1f42d4f0 | ||
|
|
4d76bd6d36 | ||
|
|
ab34d1682c | ||
|
|
552b7a6356 | ||
|
|
f86acf673a | ||
|
|
c6f49bafca | ||
|
|
fdbb325611 | ||
|
|
8c557ced85 | ||
|
|
ad0f7de506 | ||
|
|
15ec9bb454 | ||
|
|
9fe7558cfe | ||
|
|
79633dbe1d | ||
|
|
f325306e20 | ||
|
|
4778656063 | ||
|
|
f7e00523c2 | ||
|
|
bf3df7230b | ||
|
|
c5182e0ed6 | ||
|
|
4081438cba | ||
|
|
b72fe2bf37 | ||
|
|
4d9c687709 | ||
|
|
3d4b970967 | ||
|
|
792f295c45 | ||
|
|
af28753558 | ||
|
|
24fb663599 | ||
|
|
140506c9c3 | ||
|
|
519f159c8c | ||
|
|
bb019cbcd9 | ||
|
|
84219627ff | ||
|
|
f218e878c6 | ||
|
|
520f47955b | ||
|
|
8110ee18f1 | ||
|
|
55bf817310 | ||
|
|
f2f55f8118 | ||
|
|
f48e7cd0d4 | ||
|
|
c82e0c8b9b | ||
|
|
c72877e16b | ||
|
|
ccc9076397 | ||
|
|
1c716ecf4a | ||
|
|
2cc471b944 | ||
|
|
a6c450109a | ||
|
|
e13707305b | ||
|
|
68bc0383f4 | ||
|
|
878f4f3687 | ||
|
|
48a721adda | ||
|
|
548e8da78c | ||
|
|
beb28214cf | ||
|
|
b4bb31491b | ||
|
|
0b5f007327 | ||
|
|
d31a4aeea3 | ||
|
|
97acd873eb | ||
|
|
5cf3538be3 | ||
|
|
a34921701d | ||
|
|
5fcf54de09 | ||
|
|
68372bf995 | ||
|
|
9f99ac1531 | ||
|
|
b7384fda6b | ||
|
|
8f4d610825 | ||
|
|
6bbf4b2575 | ||
|
|
32db884620 | ||
|
|
1b736b36f8 | ||
|
|
22dfe5eb04 | ||
|
|
8fd49e20d5 | ||
|
|
c791070126 | ||
|
|
807603fd4f | ||
|
|
a944e5e5ab | ||
|
|
33e916cac2 | ||
|
|
a99d71dc41 | ||
|
|
67d91f1a0d | ||
|
|
de2db7d24e | ||
|
|
b360f77ea0 | ||
|
|
e869528522 | ||
|
|
7c0317d232 | ||
|
|
0e49497da1 | ||
|
|
0380382c47 | ||
|
|
23201b8c86 | ||
|
|
5f357c9f84 | ||
|
|
244272621c | ||
|
|
5792b84880 | ||
|
|
8e644093f9 | ||
|
|
9421cb57ca | ||
|
|
bd7cbffe10 | ||
|
|
b293882f75 | ||
|
|
0984b2049b | ||
|
|
d4ec4989e7 | ||
|
|
230433f784 | ||
|
|
d4dda481be | ||
|
|
1d3b94f544 | ||
|
|
78434f0016 | ||
|
|
c75145de49 | ||
|
|
5e3480f9f3 | ||
|
|
f74fdc8ed4 | ||
|
|
9ba62f8bf8 | ||
|
|
f2b9dea2b6 | ||
|
|
f92aa22375 | ||
|
|
d65001f412 | ||
|
|
9ea223cd0a | ||
|
|
addf73bc27 | ||
|
|
3f853d0d5e | ||
|
|
4c46278be1 | ||
|
|
0edc51083c | ||
|
|
d906bec333 | ||
|
|
a47c4942b7 | ||
|
|
cd8df9e938 | ||
|
|
5c37f98274 | ||
|
|
f452436dbd | ||
|
|
9375bb103b | ||
|
|
3222579cb4 | ||
|
|
4348b50e54 | ||
|
|
3b7c58b6e8 | ||
|
|
664b89a5df | ||
|
|
628c22ad61 | ||
|
|
db62a041c4 | ||
|
|
ea3ffea797 | ||
|
|
c49c8d67a2 | ||
|
|
3b01df4c56 | ||
|
|
9221516bad | ||
|
|
1988cf54f5 | ||
|
|
8a8d8979a7 | ||
|
|
e983b39f8e | ||
|
|
b6c5cd4b46 | ||
|
|
210b27ab25 | ||
|
|
63e9e5ecec | ||
|
|
771ca15ea2 | ||
|
|
b6b403b5e2 | ||
|
|
9976c94481 | ||
|
|
b9dca8ceae | ||
|
|
03b9331a9a | ||
|
|
f629834d6a | ||
|
|
25952cce50 | ||
|
|
6eba83ccec | ||
|
|
3c1ce80528 | ||
|
|
b7851e87b2 | ||
|
|
d8e06fd968 | ||
|
|
c5a5de50a7 | ||
|
|
7715e7b4ab | ||
|
|
5a3ed3d3d4 | ||
|
|
c1e2394194 | ||
|
|
6abb569df1 | ||
|
|
e59e33bc3b | ||
|
|
a671dc1937 | ||
|
|
426b52aee4 | ||
|
|
87fe011565 | ||
|
|
30c03af5b0 | ||
|
|
c9c8fc8705 | ||
|
|
9cd8030808 | ||
|
|
5411d4152c | ||
|
|
c5a05afe1c | ||
|
|
5b44f2ae33 | ||
|
|
039b30da4f | ||
|
|
df45378bce | ||
|
|
3729d2c23f | ||
|
|
89ece413c8 | ||
|
|
c1b361397f | ||
|
|
ada0715343 | ||
|
|
5cdc687f6d | ||
|
|
48f0e16fde | ||
|
|
d6b6600ce9 | ||
|
|
82634e9e1b | ||
|
|
225e5e58bc | ||
|
|
21d135a8ab | ||
|
|
7a0636a48a | ||
|
|
0b9ca77281 | ||
|
|
feaf631b47 | ||
|
|
ec24c19821 | ||
|
|
36a120fa0f | ||
|
|
fb169d5054 | ||
|
|
59fa7b6a1d | ||
|
|
201d832b92 | ||
|
|
31b4ef5458 | ||
|
|
b06ad0cdaa | ||
|
|
f3914bc3b7 | ||
|
|
aea870974b | ||
|
|
7f6265ba05 | ||
|
|
85542cb278 | ||
|
|
f6e0873d83 | ||
|
|
745b262dfc | ||
|
|
73df755f70 | ||
|
|
762a1b98d3 | ||
|
|
571e87dd14 | ||
|
|
22eb38709a | ||
|
|
986a8420f8 | ||
|
|
cff5f8e8e9 | ||
|
|
0df6cea88c | ||
|
|
88ff2432f6 | ||
|
|
efb7fb999b | ||
|
|
1a2b503791 | ||
|
|
e68d4ffa3a | ||
|
|
d701a8964f | ||
|
|
b6929113bc | ||
|
|
fc1eac1049 | ||
|
|
189659ff1e | ||
|
|
cb19130119 | ||
|
|
1596bf1deb | ||
|
|
636cbb3d21 | ||
|
|
cff7845dd4 | ||
|
|
2d9cc3507f | ||
|
|
4c6ac96dd1 | ||
|
|
e5a594367e | ||
|
|
12aaf8c209 | ||
|
|
cafbb156af | ||
|
|
36ac61d848 | ||
|
|
df066a593e | ||
|
|
7ac9185e4c | ||
|
|
090cbba1a0 | ||
|
|
5e3529f9cc | ||
|
|
f90ddeabb4 | ||
|
|
f54419b993 | ||
|
|
cbbd7ff25f | ||
|
|
0c2c089828 | ||
|
|
6a1813399f | ||
|
|
4c8d2b3704 | ||
|
|
23f97ebd46 | ||
|
|
e3dccf0182 | ||
|
|
272596878c | ||
|
|
46953e9063 | ||
|
|
30f35855f2 | ||
|
|
df94132917 | ||
|
|
de37d689be | ||
|
|
4f941aad52 | ||
|
|
2febdf1259 | ||
|
|
349808a609 | ||
|
|
7d58d1bc40 | ||
|
|
5e91a26230 | ||
|
|
0942ae1742 | ||
|
|
cce9bd29e5 | ||
|
|
05fdeef862 | ||
|
|
dfa08b287c | ||
|
|
77920f94cd | ||
|
|
3631a036c6 | ||
|
|
1445959d05 | ||
|
|
0b45de5ba8 | ||
|
|
d86cdfcefd | ||
|
|
0c7aa304f7 | ||
|
|
e5114f491d | ||
|
|
e238bd8a12 | ||
|
|
f53ad74c72 | ||
|
|
3d456d1cd5 | ||
|
|
de32fe4d85 | ||
|
|
29a90fe814 | ||
|
|
3f31f091dc | ||
|
|
571b558181 | ||
|
|
ed0775ab71 | ||
|
|
19e19d7c15 | ||
|
|
b7e574889c | ||
|
|
2a66c97254 | ||
|
|
e14ef961b9 | ||
|
|
ec2c17be23 | ||
|
|
b5162d2044 | ||
|
|
ae428b94d1 | ||
|
|
3350f3c39a | ||
|
|
68caf82167 | ||
|
|
8c5f1c3a01 | ||
|
|
e1bbc232e1 | ||
|
|
fbc7a39996 | ||
|
|
1ce77ad1ee | ||
|
|
08cee8029f | ||
|
|
e33bcf5e57 | ||
|
|
cf5ceaa959 | ||
|
|
8293bed89c | ||
|
|
a830580c27 | ||
|
|
94c6cca25c | ||
|
|
78e0a0146c | ||
|
|
ea667ed950 | ||
|
|
f8b23b5f20 | ||
|
|
b69749b073 | ||
|
|
951eea844f | ||
|
|
f3e5aff0c9 | ||
|
|
ef3e450e4f | ||
|
|
8272fa20da | ||
|
|
9ef0a748a3 | ||
|
|
6de928aef4 | ||
|
|
34ff874949 | ||
|
|
a653f3ac7f | ||
|
|
dc96084406 | ||
|
|
e056aaa7dc | ||
|
|
73bb3c11b4 | ||
|
|
c88a040728 | ||
|
|
dfa56c2b12 | ||
|
|
104d4bab52 | ||
|
|
6916161e87 | ||
|
|
512852d217 | ||
|
|
a61c699417 | ||
|
|
1e832f014f | ||
|
|
e9a463e2e5 | ||
|
|
d0c19d0436 | ||
|
|
3428abf358 | ||
|
|
e6857331e2 | ||
|
|
1fd93d2efe | ||
|
|
84e44acbfe | ||
|
|
77014c71f2 | ||
|
|
2db01aa4ad | ||
|
|
6c3fa21cc5 | ||
|
|
26b7d101ab | ||
|
|
f3c3cdf0cb | ||
|
|
e62fa31485 | ||
|
|
5f283c1558 | ||
|
|
52163098d2 | ||
|
|
dfe27f0577 | ||
|
|
e415a3468f | ||
|
|
71302a52e4 | ||
|
|
762730eb0f | ||
|
|
3999a8a54d | ||
|
|
065291e146 | ||
|
|
99376aba1c | ||
|
|
698e8a0a95 | ||
|
|
b1b3a127dc | ||
|
|
ec55c95c71 | ||
|
|
e6eb2b473c | ||
|
|
a4b39820e4 | ||
|
|
4a20c81047 | ||
|
|
b72ab461e5 | ||
|
|
0be498d9bd | ||
|
|
00bad986e5 | ||
|
|
4710e84dcf | ||
|
|
ee55f8c884 | ||
|
|
3a74116e70 | ||
|
|
cfd83b5b4e | ||
|
|
e468261095 | ||
|
|
1362dc87df | ||
|
|
b89902bbdb | ||
|
|
f31b70a6dc | ||
|
|
47a1f0c4d5 | ||
|
|
3234b530d5 | ||
|
|
75d16544db | ||
|
|
7179b60116 | ||
|
|
7cb5d8254f | ||
|
|
6ab7ee6e4f | ||
|
|
a57ce55f8b | ||
|
|
190484762d | ||
|
|
78554ade5d | ||
|
|
364a13226a | ||
|
|
691813838c | ||
|
|
0defb0fadf | ||
|
|
08bf00ee37 | ||
|
|
522322ee2a | ||
|
|
062e3600e7 | ||
|
|
a92160f6d7 | ||
|
|
4adf967f7f | ||
|
|
fd6bd98a25 | ||
|
|
fe76f32778 | ||
|
|
897b4f2efe | ||
|
|
267f903ffe | ||
|
|
db884d0a6a | ||
|
|
d1190e7ddb | ||
|
|
dae8ab679e | ||
|
|
86ec9409c3 | ||
|
|
2c4ddb0c38 | ||
|
|
44d10f11ca | ||
|
|
6cf733b9c6 | ||
|
|
1eb6e2cedf | ||
|
|
ef4deaba8f | ||
|
|
e8c196c2fa | ||
|
|
f7c9db6353 | ||
|
|
4ce720ff97 | ||
|
|
a96011629b | ||
|
|
9dcdcf97e8 | ||
|
|
5148338f52 | ||
|
|
0d3c04d8f8 | ||
|
|
15328a14b4 | ||
|
|
2d092f722a | ||
|
|
8825cb9b9b | ||
|
|
2f17e303ab | ||
|
|
4b56c8a343 | ||
|
|
7b6b62c623 | ||
|
|
07f5e66491 | ||
|
|
fe633f3220 | ||
|
|
af1090553f | ||
|
|
92c2e66660 | ||
|
|
08372f9dcb | ||
|
|
64ea0e2eee | ||
|
|
7ab476a88f | ||
|
|
de41ca911d | ||
|
|
dde9688f96 | ||
|
|
c1ca63edc0 | ||
|
|
cbc430499f | ||
|
|
4da9fa4802 | ||
|
|
42586d9556 | ||
|
|
ea4387d4ab | ||
|
|
0707b515ab | ||
|
|
78ae71fc46 | ||
|
|
3f62cd40e7 | ||
|
|
47657c0093 | ||
|
|
a5b0fde4b6 | ||
|
|
78cc0b34b1 | ||
|
|
e3017e986b | ||
|
|
e12cd876db | ||
|
|
5292e4b814 | ||
|
|
dbdd16ab89 | ||
|
|
61c2600286 | ||
|
|
163a33ae3a | ||
|
|
37d064aa62 | ||
|
|
ddc3c2e1b5 | ||
|
|
49184b287b | ||
|
|
f6139bda0d | ||
|
|
a6471b823b | ||
|
|
7c34003647 | ||
|
|
1aa21f9980 | ||
|
|
ce4ca50939 | ||
|
|
fb28260c4a | ||
|
|
626a904747 | ||
|
|
893cdafdc5 | ||
|
|
dbfb7d7d9c | ||
|
|
a66538a7db | ||
|
|
2f77d87d4f | ||
|
|
de85ba984c | ||
|
|
caac1a05ae | ||
|
|
eb5793b819 | ||
|
|
5ef3e1e2ce | ||
|
|
d8b459e5ee | ||
|
|
7b40d58aa1 | ||
|
|
809e9b838e | ||
|
|
23ae36ebd9 | ||
|
|
9c3f7d20f5 | ||
|
|
083298303c | ||
|
|
224970a07e | ||
|
|
86d039e5b0 | ||
|
|
6a8038aac9 | ||
|
|
e748f08a8e | ||
|
|
3580963e9f | ||
|
|
b008ce2ab8 | ||
|
|
ea0c2c7061 | ||
|
|
0926220933 | ||
|
|
ca975bbdd3 | ||
|
|
b16c5c5302 | ||
|
|
cad05fe5d9 | ||
|
|
a7cd466d9c | ||
|
|
4472a67ec0 | ||
|
|
c84a4029ec | ||
|
|
d7d9ab505e | ||
|
|
c582f5f5c7 | ||
|
|
4c30939339 | ||
|
|
cecd6a1d2b | ||
|
|
853dcbb364 | ||
|
|
ae327ed26d | ||
|
|
3e416aa255 | ||
|
|
61c2c3fc83 | ||
|
|
ca749aaf1e | ||
|
|
2a2cb3bd0c | ||
|
|
44e3d19844 | ||
|
|
1e25fffc70 | ||
|
|
44645ed23d | ||
|
|
fa557e5f76 | ||
|
|
7202fda38e | ||
|
|
d05afe41d6 | ||
|
|
bfc0b58728 | ||
|
|
22e8aaca81 | ||
|
|
5cb1247fb2 | ||
|
|
17a6d99703 | ||
|
|
3e7917f767 | ||
|
|
e9277d4dd9 | ||
|
|
058edd8af6 |
7
.env
7
.env
@@ -2,12 +2,11 @@ LC_ALL=en_US.UTF-8
|
||||
LANG=en_US.UTF-8
|
||||
MailConfig__EmailServer=""
|
||||
MailConfig__EmailFrom=""
|
||||
MailConfig__UseSSL="false"
|
||||
MailConfig__Port=587
|
||||
MailConfig__Username=""
|
||||
MailConfig__Password=""
|
||||
LOGGING__LOGLEVEL__DEFAULT=Error
|
||||
|
||||
# * Uncoment this line if you use postgresSQL as database backend.
|
||||
# * Check the docker-compose.postgresql.yml file
|
||||
#POSTGRES_CONNECTION="Host=postgres;Username=lubelogger;Password=lubepass;Database=lubelogger;"
|
||||
# This file is provided as a GUIDELINE ONLY
|
||||
# Use the LubeLogger Configurator to configure your environment variables
|
||||
# https://lubelogger.com/configure
|
||||
50
.github/CONTRIBUTING.md
vendored
Normal file
50
.github/CONTRIBUTING.md
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
# Contributing Guidelines
|
||||
|
||||
## Asking Questions
|
||||
Before submitting a question, please check the [Troubleshooting Guide](https://docs.lubelogger.com/Installation/Troubleshooting) and search through existing issues.
|
||||
|
||||
Ideally, the Issues tab should only consist of bug reports and feature requests instead of debugging your LubeLogger installation.
|
||||
|
||||
## Feature Requests
|
||||
Feature Requests are cool, but we do want to avoid bloat and scope/feature creep.
|
||||
|
||||
Read [this](https://github.com/hargata/lubelog/wiki/Scope-and-Purpose) to better understand the scope and purpose of this project.
|
||||
|
||||
LubeLogger is a Vehicle Maintenance and Fuel Mileage Tracker.
|
||||
It is not and should not be used for the following:
|
||||
- Project Management Software(e.g.: Jira)
|
||||
- Budget Management(e.g: YNAB/Actual)
|
||||
- Inventory Management
|
||||
|
||||
Before submitting a feature request, please consider the following:
|
||||
- Will this feature benefit more than just a niche subset of users
|
||||
- Will this feature result in scope creep
|
||||
- Has this feature already been requested/exist
|
||||
|
||||
## Bug Reports
|
||||
Please fill out the issue template for bug reports.
|
||||
|
||||
## Security Vulnerabilities
|
||||
Contact us via [Email](mailto:hargatasoftworks@gmail.com)
|
||||
|
||||
## Submitting Pull Requests
|
||||
Pull Requests are welcome, but please consider the following:
|
||||
|
||||
CI/CD, Bugs, Tech-Debt Related PRs:
|
||||
- Make sure changes are not breaking.
|
||||
- If any dependencies are added, they must be cross-platform compatible.
|
||||
- Please test changes thoroughly.
|
||||
|
||||
Feature Related PRs:
|
||||
- Have you requested this feature in the Issues tab
|
||||
- Will this feature benefit more than just a niche subset of users
|
||||
- Will this feature result in scope creep
|
||||
- Do these changes fix a root cause or is it simply a workaround
|
||||
|
||||
Ideally, you should first submit a feature request in the Issues tab before submitting a PR just in case it's something we are already working on.
|
||||
|
||||
Note the following:
|
||||
|
||||
We(the maintainers) are not responsible for cleaning up, testing, or fixing your changes.
|
||||
|
||||
If your changes doesn't have a wide-ranging use-case, has not been thoroughly tested, or cannot be easily maintained, we won't merge your PR.
|
||||
14
.github/FUNDING.yml
vendored
Normal file
14
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: lubelogger
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
6
.github/ISSUE_TEMPLATE/bug_report.md
vendored
6
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Report a bug
|
||||
title: ''
|
||||
title: "[BUG]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
@@ -10,7 +10,7 @@ assignees: ''
|
||||
**Checklist**
|
||||
Please make sure you have performed the following steps before opening a new bug ticket, change `[ ]` to `[x]` to mark it as done
|
||||
|
||||
- [ ] I have read and tried the steps outlined in the [Troubleshooting Guide](https://docs.lubelogger.com/Troubleshooting)
|
||||
- [ ] I have read and tried the steps outlined in the [Troubleshooting Guide](https://docs.lubelogger.com/Installation/Troubleshooting)
|
||||
- [ ] I have searched through existing issues.
|
||||
|
||||
**Description**
|
||||
@@ -18,7 +18,7 @@ Please make sure you have performed the following steps before opening a new bug
|
||||
|
||||
**Platform**
|
||||
- [ ] Docker Image
|
||||
- [ ] Windows Standalone Executable
|
||||
- [ ] Windows/Linux Standalone Executable
|
||||
|
||||
**Browser Console Errors(F12)**
|
||||
<!-- Attach a screenshot or codeblock containing the browser console error -->
|
||||
|
||||
17
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
17
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: "[FEATURE REQUEST]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Checklist**
|
||||
Please make sure you have performed the following steps before submitting a new feature request, change `[ ]` to `[x]` to mark it as done
|
||||
|
||||
- [ ] I have read the [Contributing Guidelines](https://github.com/hargata/lubelog/blob/main/.github/CONTRIBUTING.md) and [Scope and Purpose](https://github.com/hargata/lubelog/wiki/Scope-and-Purpose)
|
||||
- [ ] I have searched through existing issues.
|
||||
|
||||
**Description**
|
||||
<!-- Describe the feature request below this line -->
|
||||
10
.gitignore
vendored
10
.gitignore
vendored
@@ -1,14 +1,6 @@
|
||||
.vs/
|
||||
bin/
|
||||
obj/
|
||||
wwwroot/images/
|
||||
cartracker.db
|
||||
data/cartracker.db
|
||||
wwwroot/documents/
|
||||
wwwroot/temp/
|
||||
wwwroot/imports/
|
||||
wwwroot/translations/
|
||||
config/userConfig.json
|
||||
data/
|
||||
CarCareTracker.csproj.user
|
||||
Properties/launchSettings.json
|
||||
data/cartracker-log.db
|
||||
|
||||
@@ -11,9 +11,10 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CsvHelper" Version="30.0.1" />
|
||||
<PackageReference Include="CsvHelper" Version="33.0.1" />
|
||||
<PackageReference Include="LiteDB" Version="5.0.17" />
|
||||
<PackageReference Include="Npgsql" Version="8.0.2" />
|
||||
<PackageReference Include="MailKit" Version="4.11.0" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.3" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.3.1" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.8.34330.188
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CarCareTracker", "CarCareTracker.csproj", "{0DB85611-6555-4127-A66E-DADD25A16526}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CarCareTracker", "CarCareTracker.csproj", "{0DB85611-6555-4127-A66E-DADD25A16526}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -22,15 +22,46 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
var viewModel = new AdminViewModel
|
||||
{
|
||||
Users = _loginLogic.GetAllUsers(),
|
||||
Users = _loginLogic.GetAllUsers().OrderBy(x=>x.Id).ToList(),
|
||||
Tokens = _loginLogic.GetAllTokens()
|
||||
};
|
||||
return View(viewModel);
|
||||
}
|
||||
public IActionResult GetTokenPartialView()
|
||||
{
|
||||
var viewModel = _loginLogic.GetAllTokens();
|
||||
return PartialView("_Tokens", viewModel);
|
||||
}
|
||||
public IActionResult GetUserPartialView()
|
||||
{
|
||||
var viewModel = _loginLogic.GetAllUsers().OrderBy(x => x.Id).ToList();
|
||||
return PartialView("_Users", viewModel);
|
||||
}
|
||||
public IActionResult GenerateNewToken(string emailAddress, bool autoNotify)
|
||||
{
|
||||
var result = _loginLogic.GenerateUserToken(emailAddress, autoNotify);
|
||||
return Json(result);
|
||||
if (emailAddress.Contains(","))
|
||||
{
|
||||
string[] emailAddresses = emailAddress.Split(',');
|
||||
foreach(string emailAdd in emailAddresses)
|
||||
{
|
||||
var trimmedEmail = emailAdd.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(trimmedEmail))
|
||||
{
|
||||
var result = _loginLogic.GenerateUserToken(emailAdd.Trim(), autoNotify);
|
||||
if (!result.Success)
|
||||
{
|
||||
//if fail, return prematurely
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
var successResponse = OperationResponse.Succeed("Token Generated!");
|
||||
return Json(successResponse);
|
||||
} else
|
||||
{
|
||||
var result = _loginLogic.GenerateUserToken(emailAddress, autoNotify);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteToken(int tokenId)
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
public IActionResult Unauthorized()
|
||||
{
|
||||
if (!User.IsInRole("CookieAuth"))
|
||||
if (User.IsInRole("APIAuth"))
|
||||
{
|
||||
Response.StatusCode = 403;
|
||||
return new EmptyResult();
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace CarCareTracker.Controllers
|
||||
var originalFileName = Path.GetFileNameWithoutExtension(file.FileName);
|
||||
if (originalFileName == "en_US")
|
||||
{
|
||||
return Json(new OperationResponse { Success = false, Message = "The translation file name en_US is reserved." });
|
||||
return Json(OperationResponse.Failed("The translation file name en_US is reserved."));
|
||||
}
|
||||
var fileName = UploadFile(file);
|
||||
//move file from temp to translation folder.
|
||||
@@ -41,9 +41,9 @@ namespace CarCareTracker.Controllers
|
||||
if (!string.IsNullOrWhiteSpace(uploadedFilePath))
|
||||
{
|
||||
var result = _fileHelper.RenameFile(uploadedFilePath, originalFileName);
|
||||
return Json(new OperationResponse { Success = result, Message = string.Empty });
|
||||
return Json(OperationResponse.Conditional(result));
|
||||
}
|
||||
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
@@ -81,7 +81,7 @@ namespace CarCareTracker.Controllers
|
||||
private string UploadFile(IFormFile fileToUpload)
|
||||
{
|
||||
string uploadDirectory = "temp/";
|
||||
string uploadPath = Path.Combine(_webEnv.WebRootPath, uploadDirectory);
|
||||
string uploadPath = Path.Combine(_webEnv.ContentRootPath, "data", uploadDirectory);
|
||||
if (!Directory.Exists(uploadPath))
|
||||
Directory.CreateDirectory(uploadPath);
|
||||
string fileName = Guid.NewGuid() + Path.GetExtension(fileToUpload.FileName);
|
||||
@@ -92,5 +92,18 @@ namespace CarCareTracker.Controllers
|
||||
}
|
||||
return Path.Combine("/", uploadDirectory, fileName);
|
||||
}
|
||||
public IActionResult UploadCoordinates(List<string> coordinates)
|
||||
{
|
||||
string uploadDirectory = "temp/";
|
||||
string uploadPath = Path.Combine(_webEnv.ContentRootPath, "data", uploadDirectory);
|
||||
if (!Directory.Exists(uploadPath))
|
||||
Directory.CreateDirectory(uploadPath);
|
||||
string fileName = Guid.NewGuid() + ".csv";
|
||||
string filePath = Path.Combine(uploadPath, fileName);
|
||||
string fileData = string.Join("\r\n", coordinates);
|
||||
System.IO.File.WriteAllText(filePath, fileData);
|
||||
var uploadedFile = new UploadedFiles { Name = "coordinates.csv", Location = Path.Combine("/", uploadDirectory, fileName) };
|
||||
return Json(uploadedFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ namespace CarCareTracker.Controllers
|
||||
private readonly IExtraFieldDataAccess _extraFieldDataAccess;
|
||||
private readonly IReminderRecordDataAccess _reminderRecordDataAccess;
|
||||
private readonly IReminderHelper _reminderHelper;
|
||||
private readonly ITranslationHelper _translationHelper;
|
||||
private readonly IMailHelper _mailHelper;
|
||||
public HomeController(ILogger<HomeController> logger,
|
||||
IVehicleDataAccess dataAccess,
|
||||
IUserLogic userLogic,
|
||||
@@ -31,7 +33,9 @@ namespace CarCareTracker.Controllers
|
||||
IFileHelper fileHelper,
|
||||
IExtraFieldDataAccess extraFieldDataAccess,
|
||||
IReminderRecordDataAccess reminderRecordDataAccess,
|
||||
IReminderHelper reminderHelper)
|
||||
IReminderHelper reminderHelper,
|
||||
ITranslationHelper translationHelper,
|
||||
IMailHelper mailHelper)
|
||||
{
|
||||
_logger = logger;
|
||||
_dataAccess = dataAccess;
|
||||
@@ -43,6 +47,8 @@ namespace CarCareTracker.Controllers
|
||||
_reminderHelper = reminderHelper;
|
||||
_loginLogic = loginLogic;
|
||||
_vehicleLogic = vehicleLogic;
|
||||
_translationHelper = translationHelper;
|
||||
_mailHelper = mailHelper;
|
||||
}
|
||||
private int GetUserID()
|
||||
{
|
||||
@@ -52,6 +58,58 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
return View(model: tab);
|
||||
}
|
||||
[Route("/kiosk")]
|
||||
public IActionResult Kiosk(string exclusions, KioskMode kioskMode = KioskMode.Vehicle)
|
||||
{
|
||||
try {
|
||||
var viewModel = new KioskViewModel
|
||||
{
|
||||
Exclusions = string.IsNullOrWhiteSpace(exclusions) ? new List<int>() : exclusions.Split(',').Select(x => int.Parse(x)).ToList(),
|
||||
KioskMode = kioskMode
|
||||
};
|
||||
return View(viewModel);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return View(new KioskViewModel());
|
||||
}
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult KioskContent(KioskViewModel kioskParameters)
|
||||
{
|
||||
var vehiclesStored = _dataAccess.GetVehicles();
|
||||
if (!User.IsInRole(nameof(UserData.IsRootUser)))
|
||||
{
|
||||
vehiclesStored = _userLogic.FilterUserVehicles(vehiclesStored, GetUserID());
|
||||
}
|
||||
vehiclesStored.RemoveAll(x => kioskParameters.Exclusions.Contains(x.Id));
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
if (userConfig.HideSoldVehicles)
|
||||
{
|
||||
vehiclesStored.RemoveAll(x => !string.IsNullOrWhiteSpace(x.SoldDate));
|
||||
}
|
||||
switch (kioskParameters.KioskMode)
|
||||
{
|
||||
case KioskMode.Vehicle:
|
||||
{
|
||||
var kioskResult = _vehicleLogic.GetVehicleInfo(vehiclesStored);
|
||||
return PartialView("_Kiosk", kioskResult);
|
||||
}
|
||||
case KioskMode.Plan:
|
||||
{
|
||||
var kioskResult = _vehicleLogic.GetPlans(vehiclesStored, true);
|
||||
return PartialView("_KioskPlan", kioskResult);
|
||||
}
|
||||
case KioskMode.Reminder:
|
||||
{
|
||||
var kioskResult = _vehicleLogic.GetReminders(vehiclesStored, false);
|
||||
return PartialView("_KioskReminder", kioskResult);
|
||||
}
|
||||
}
|
||||
var result = _vehicleLogic.GetVehicleInfo(vehiclesStored);
|
||||
return PartialView("_Kiosk", result);
|
||||
}
|
||||
public IActionResult Garage()
|
||||
{
|
||||
var vehiclesStored = _dataAccess.GetVehicles();
|
||||
@@ -59,21 +117,52 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
vehiclesStored = _userLogic.FilterUserVehicles(vehiclesStored, GetUserID());
|
||||
}
|
||||
var vehicleViewModels = vehiclesStored.Select(x => new VehicleViewModel
|
||||
var vehicleViewModels = vehiclesStored.Select(x =>
|
||||
{
|
||||
Id = x.Id,
|
||||
ImageLocation = x.ImageLocation,
|
||||
Year = x.Year,
|
||||
Make = x.Make,
|
||||
Model = x.Model,
|
||||
LicensePlate = x.LicensePlate,
|
||||
SoldDate = x.SoldDate,
|
||||
IsElectric = x.IsElectric,
|
||||
UseHours = x.UseHours,
|
||||
ExtraFields = x.ExtraFields,
|
||||
Tags = x.Tags,
|
||||
LastReportedMileage = _vehicleLogic.GetMaxMileage(x.Id),
|
||||
HasReminders = _vehicleLogic.GetVehicleHasUrgentOrPastDueReminders(x.Id)
|
||||
var vehicleVM = new VehicleViewModel
|
||||
{
|
||||
Id = x.Id,
|
||||
ImageLocation = x.ImageLocation,
|
||||
Year = x.Year,
|
||||
Make = x.Make,
|
||||
Model = x.Model,
|
||||
LicensePlate = x.LicensePlate,
|
||||
SoldDate = x.SoldDate,
|
||||
IsElectric = x.IsElectric,
|
||||
IsDiesel = x.IsDiesel,
|
||||
UseHours = x.UseHours,
|
||||
OdometerOptional = x.OdometerOptional,
|
||||
ExtraFields = x.ExtraFields,
|
||||
Tags = x.Tags,
|
||||
DashboardMetrics = x.DashboardMetrics,
|
||||
VehicleIdentifier = x.VehicleIdentifier
|
||||
};
|
||||
//dashboard metrics
|
||||
if (x.DashboardMetrics.Any())
|
||||
{
|
||||
var vehicleRecords = _vehicleLogic.GetVehicleRecords(x.Id);
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
var distanceUnit = x.UseHours ? "h" : userConfig.UseMPG ? "mi." : "km";
|
||||
if (vehicleVM.DashboardMetrics.Contains(DashboardMetric.Default))
|
||||
{
|
||||
vehicleVM.LastReportedMileage = _vehicleLogic.GetMaxMileage(vehicleRecords);
|
||||
vehicleVM.HasReminders = _vehicleLogic.GetVehicleHasUrgentOrPastDueReminders(x.Id, vehicleVM.LastReportedMileage);
|
||||
}
|
||||
if (vehicleVM.DashboardMetrics.Contains(DashboardMetric.CostPerMile))
|
||||
{
|
||||
var vehicleTotalCost = _vehicleLogic.GetVehicleTotalCost(vehicleRecords);
|
||||
var maxMileage = _vehicleLogic.GetMaxMileage(vehicleRecords);
|
||||
var minMileage = _vehicleLogic.GetMinMileage(vehicleRecords);
|
||||
var totalDistance = maxMileage - minMileage;
|
||||
vehicleVM.CostPerMile = totalDistance != default ? vehicleTotalCost / totalDistance : 0.00M;
|
||||
vehicleVM.DistanceUnit = distanceUnit;
|
||||
}
|
||||
if (vehicleVM.DashboardMetrics.Contains(DashboardMetric.TotalCost))
|
||||
{
|
||||
vehicleVM.TotalCost = _vehicleLogic.GetVehicleTotalCost(vehicleRecords);
|
||||
}
|
||||
}
|
||||
return vehicleVM;
|
||||
}).ToList();
|
||||
return PartialView("_GarageDisplay", vehicleViewModels);
|
||||
}
|
||||
@@ -84,19 +173,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
vehiclesStored = _userLogic.FilterUserVehicles(vehiclesStored, GetUserID());
|
||||
}
|
||||
List<ReminderRecordViewModel> reminders = new List<ReminderRecordViewModel>();
|
||||
foreach (Vehicle vehicle in vehiclesStored)
|
||||
{
|
||||
var vehicleReminders = _reminderRecordDataAccess.GetReminderRecordsByVehicleId(vehicle.Id);
|
||||
vehicleReminders.RemoveAll(x => x.Metric == ReminderMetric.Odometer);
|
||||
//we don't care about mileages so we can basically fake the current vehicle mileage.
|
||||
if (vehicleReminders.Any())
|
||||
{
|
||||
var reminderUrgency = _reminderHelper.GetReminderRecordViewModels(vehicleReminders, 0, DateTime.Now);
|
||||
reminderUrgency = reminderUrgency.Select(x => new ReminderRecordViewModel { Id = x.Id, Date = x.Date, Urgency = x.Urgency, Description = $"{vehicle.Year} {vehicle.Make} {vehicle.Model} #{vehicle.LicensePlate} - {x.Description}" }).ToList();
|
||||
reminders.AddRange(reminderUrgency);
|
||||
}
|
||||
}
|
||||
var reminders = _vehicleLogic.GetReminders(vehiclesStored, true);
|
||||
return PartialView("_Calendar", reminders);
|
||||
}
|
||||
public IActionResult ViewCalendarReminder(int reminderId)
|
||||
@@ -105,7 +182,7 @@ namespace CarCareTracker.Controllers
|
||||
var reminderUrgency = _reminderHelper.GetReminderRecordViewModels(new List<ReminderRecord> { reminder }, 0, DateTime.Now).FirstOrDefault();
|
||||
return PartialView("_ReminderRecordCalendarModal", reminderUrgency);
|
||||
}
|
||||
public IActionResult Settings()
|
||||
public async Task<IActionResult> Settings()
|
||||
{
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
var languages = _fileHelper.GetLanguages();
|
||||
@@ -116,6 +193,20 @@ namespace CarCareTracker.Controllers
|
||||
};
|
||||
return PartialView("_Settings", viewModel);
|
||||
}
|
||||
public async Task<IActionResult> Sponsors()
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpClient = new HttpClient();
|
||||
var sponsorsData = await httpClient.GetFromJsonAsync<Sponsors>(StaticHelper.SponsorsPath) ?? new Sponsors();
|
||||
return PartialView("_Sponsors", sponsorsData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Unable to retrieve sponsors: {ex.Message}");
|
||||
return PartialView("_Sponsors", new Sponsors());
|
||||
}
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult WriteToSettings(UserConfig userConfig)
|
||||
{
|
||||
@@ -136,10 +227,6 @@ namespace CarCareTracker.Controllers
|
||||
var result = _config.SaveUserConfig(User, existingConfig);
|
||||
return Json(result);
|
||||
}
|
||||
public IActionResult Privacy()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
public IActionResult GetExtraFieldsModal(int importMode = 0)
|
||||
{
|
||||
@@ -177,7 +264,8 @@ namespace CarCareTracker.Controllers
|
||||
return Json(result);
|
||||
}
|
||||
return Json(false);
|
||||
} catch (Exception ex)
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return Json(false);
|
||||
@@ -194,12 +282,12 @@ namespace CarCareTracker.Controllers
|
||||
var result = _loginLogic.UpdateUserDetails(userId, userAccount);
|
||||
return Json(result);
|
||||
}
|
||||
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage});
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
}
|
||||
[HttpGet]
|
||||
@@ -209,6 +297,290 @@ namespace CarCareTracker.Controllers
|
||||
var userName = User.Identity.Name;
|
||||
return PartialView("_AccountModal", new UserData() { EmailAddress = emailAddress, UserName = userName });
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpGet]
|
||||
public IActionResult GetRootAccountInformationModal()
|
||||
{
|
||||
var userName = User.Identity.Name;
|
||||
return PartialView("_RootAccountModal", new UserData() { UserName = userName });
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpGet]
|
||||
public IActionResult GetTranslatorEditor(string userLanguage)
|
||||
{
|
||||
var translationData = _translationHelper.GetTranslations(userLanguage);
|
||||
return PartialView("_TranslationEditor", translationData);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpPost]
|
||||
public IActionResult SaveTranslation(string userLanguage, Dictionary<string, string> translationData)
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(userLanguage, translationData);
|
||||
return Json(result);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpPost]
|
||||
public IActionResult ExportTranslation(Dictionary<string, string> translationData)
|
||||
{
|
||||
var result = _translationHelper.ExportTranslation(translationData);
|
||||
return Json(result);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAvailableTranslations()
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpClient = new HttpClient();
|
||||
var translations = await httpClient.GetFromJsonAsync<Translations>(StaticHelper.TranslationDirectoryPath) ?? new Translations();
|
||||
return PartialView("_Translations", translations);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Unable to retrieve translations: {ex.Message}");
|
||||
return PartialView("_Translations", new Translations());
|
||||
}
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> DownloadTranslation(string continent, string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpClient = new HttpClient();
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath(continent, name)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(name, translationData);
|
||||
if (!result.Success)
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError($"Unable to download translation: {name}");
|
||||
return Json(false);
|
||||
}
|
||||
return Json(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Unable to download translation: {ex.Message}");
|
||||
return Json(false);
|
||||
}
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> DownloadAllTranslations()
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpClient = new HttpClient();
|
||||
var translations = await httpClient.GetFromJsonAsync<Translations>(StaticHelper.TranslationDirectoryPath) ?? new Translations();
|
||||
int translationsDownloaded = 0;
|
||||
foreach (string translation in translations.Asia)
|
||||
{
|
||||
try
|
||||
{
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath("Asia", translation)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(translation, translationData);
|
||||
if (result.Success)
|
||||
{
|
||||
translationsDownloaded++;
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error Downloading Translation {translation}: {ex.Message} ");
|
||||
}
|
||||
}
|
||||
foreach (string translation in translations.Africa)
|
||||
{
|
||||
try
|
||||
{
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath("Africa", translation)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(translation, translationData);
|
||||
if (result.Success)
|
||||
{
|
||||
translationsDownloaded++;
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error Downloading Translation {translation}: {ex.Message} ");
|
||||
}
|
||||
}
|
||||
foreach (string translation in translations.Europe)
|
||||
{
|
||||
try
|
||||
{
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath("Europe", translation)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(translation, translationData);
|
||||
if (result.Success)
|
||||
{
|
||||
translationsDownloaded++;
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error Downloading Translation {translation}: {ex.Message} ");
|
||||
}
|
||||
}
|
||||
foreach (string translation in translations.NorthAmerica)
|
||||
{
|
||||
try
|
||||
{
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath("NorthAmerica", translation)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(translation, translationData);
|
||||
if (result.Success)
|
||||
{
|
||||
translationsDownloaded++;
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error Downloading Translation {translation}: {ex.Message} ");
|
||||
}
|
||||
}
|
||||
foreach (string translation in translations.SouthAmerica)
|
||||
{
|
||||
try
|
||||
{
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath("SouthAmerica", translation)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(translation, translationData);
|
||||
if (result.Success)
|
||||
{
|
||||
translationsDownloaded++;
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error Downloading Translation {translation}: {ex.Message} ");
|
||||
}
|
||||
}
|
||||
foreach (string translation in translations.Oceania)
|
||||
{
|
||||
try
|
||||
{
|
||||
var translationData = await httpClient.GetFromJsonAsync<Dictionary<string, string>>(StaticHelper.GetTranslationDownloadPath("Oceania", translation)) ?? new Dictionary<string, string>();
|
||||
if (translationData.Any())
|
||||
{
|
||||
var result = _translationHelper.SaveTranslation(translation, translationData);
|
||||
if (result.Success)
|
||||
{
|
||||
translationsDownloaded++;
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error Downloading Translation {translation}: {ex.Message} ");
|
||||
}
|
||||
}
|
||||
if (translationsDownloaded > 0)
|
||||
{
|
||||
return Json(OperationResponse.Succeed($"{translationsDownloaded} Translations Downloaded"));
|
||||
} else
|
||||
{
|
||||
return Json(OperationResponse.Failed("No Translations Downloaded"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Unable to retrieve translations: {ex.Message}");
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
}
|
||||
public ActionResult GetVehicleSelector(int vehicleId)
|
||||
{
|
||||
var vehiclesStored = _dataAccess.GetVehicles();
|
||||
if (!User.IsInRole(nameof(UserData.IsRootUser)))
|
||||
{
|
||||
vehiclesStored = _userLogic.FilterUserVehicles(vehiclesStored, GetUserID());
|
||||
}
|
||||
if (vehicleId != default)
|
||||
{
|
||||
vehiclesStored.RemoveAll(x => x.Id == vehicleId);
|
||||
}
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
if (userConfig.HideSoldVehicles)
|
||||
{
|
||||
vehiclesStored.RemoveAll(x => !string.IsNullOrWhiteSpace(x.SoldDate));
|
||||
}
|
||||
return PartialView("_VehicleSelector", vehiclesStored);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpGet]
|
||||
public IActionResult GetCustomWidgetEditor()
|
||||
{
|
||||
if (_config.GetCustomWidgetsEnabled())
|
||||
{
|
||||
var customWidgetData = _fileHelper.GetWidgets();
|
||||
return PartialView("_WidgetEditor", customWidgetData);
|
||||
}
|
||||
return Json(string.Empty);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpPost]
|
||||
public IActionResult SaveCustomWidgets(string widgetsData)
|
||||
{
|
||||
if (_config.GetCustomWidgetsEnabled())
|
||||
{
|
||||
var saveResult = _fileHelper.SaveWidgets(widgetsData);
|
||||
return Json(saveResult);
|
||||
}
|
||||
return Json(false);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpPost]
|
||||
public IActionResult DeleteCustomWidgets()
|
||||
{
|
||||
if (_config.GetCustomWidgetsEnabled())
|
||||
{
|
||||
var deleteResult = _fileHelper.DeleteWidgets();
|
||||
return Json(deleteResult);
|
||||
}
|
||||
return Json(false);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
public IActionResult GetServerConfiguration()
|
||||
{
|
||||
var viewModel = new ServerSettingsViewModel
|
||||
{
|
||||
PostgresConnection = _config.GetServerPostgresConnection(),
|
||||
AllowedFileExtensions = _config.GetAllowedFileUploadExtensions(),
|
||||
CustomLogoURL = _config.GetLogoUrl(),
|
||||
MessageOfTheDay = _config.GetMOTD(),
|
||||
WebHookURL = _config.GetWebHookUrl(),
|
||||
CustomWidgetsEnabled = _config.GetCustomWidgetsEnabled(),
|
||||
InvariantAPIEnabled = _config.GetInvariantApi(),
|
||||
SMTPConfig = _config.GetMailConfig(),
|
||||
OIDCConfig = _config.GetOpenIDConfig()
|
||||
};
|
||||
return PartialView("_ServerConfig", viewModel);
|
||||
}
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
public IActionResult SendTestEmail(string emailAddress)
|
||||
{
|
||||
var result = _mailHelper.SendTestEmail(emailAddress);
|
||||
return Json(result);
|
||||
}
|
||||
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
|
||||
public IActionResult Error()
|
||||
{
|
||||
|
||||
@@ -34,36 +34,62 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
var generatedState = Guid.NewGuid().ToString().Substring(0, 8);
|
||||
remoteAuthConfig.State = generatedState;
|
||||
var pkceKeyPair = _loginLogic.GetPKCEChallengeCode();
|
||||
remoteAuthConfig.CodeChallenge = pkceKeyPair.Value;
|
||||
if (remoteAuthConfig.ValidateState)
|
||||
{
|
||||
Response.Cookies.Append("OIDC_STATE", remoteAuthConfig.State, new CookieOptions { Expires = new DateTimeOffset(DateTime.Now.AddMinutes(5)) });
|
||||
}
|
||||
if (remoteAuthConfig.UsePKCE)
|
||||
{
|
||||
Response.Cookies.Append("OIDC_VERIFIER", pkceKeyPair.Key, new CookieOptions { Expires = new DateTimeOffset(DateTime.Now.AddMinutes(5)) });
|
||||
}
|
||||
var remoteAuthURL = remoteAuthConfig.RemoteAuthURL;
|
||||
return Redirect(remoteAuthURL);
|
||||
}
|
||||
return View(model: redirectURL);
|
||||
}
|
||||
public IActionResult Registration()
|
||||
public IActionResult Registration(string token = "", string email = "")
|
||||
{
|
||||
return View();
|
||||
if (_config.GetServerDisabledRegistration())
|
||||
{
|
||||
return RedirectToAction("Index");
|
||||
}
|
||||
var viewModel = new LoginModel
|
||||
{
|
||||
EmailAddress = string.IsNullOrWhiteSpace(email) ? string.Empty : email,
|
||||
Token = string.IsNullOrWhiteSpace(token) ? string.Empty : token
|
||||
};
|
||||
return View(viewModel);
|
||||
}
|
||||
public IActionResult ForgotPassword()
|
||||
{
|
||||
return View();
|
||||
}
|
||||
public IActionResult ResetPassword()
|
||||
public IActionResult ResetPassword(string token = "", string email = "")
|
||||
{
|
||||
return View();
|
||||
var viewModel = new LoginModel
|
||||
{
|
||||
EmailAddress = string.IsNullOrWhiteSpace(email) ? string.Empty : email,
|
||||
Token = string.IsNullOrWhiteSpace(token) ? string.Empty : token
|
||||
};
|
||||
return View(viewModel);
|
||||
}
|
||||
public IActionResult GetRemoteLoginLink()
|
||||
{
|
||||
var remoteAuthConfig = _config.GetOpenIDConfig();
|
||||
var generatedState = Guid.NewGuid().ToString().Substring(0, 8);
|
||||
remoteAuthConfig.State = generatedState;
|
||||
var pkceKeyPair = _loginLogic.GetPKCEChallengeCode();
|
||||
remoteAuthConfig.CodeChallenge = pkceKeyPair.Value;
|
||||
if (remoteAuthConfig.ValidateState)
|
||||
{
|
||||
Response.Cookies.Append("OIDC_STATE", remoteAuthConfig.State, new CookieOptions { Expires = new DateTimeOffset(DateTime.Now.AddMinutes(5)) });
|
||||
}
|
||||
if (remoteAuthConfig.UsePKCE)
|
||||
{
|
||||
Response.Cookies.Append("OIDC_VERIFIER", pkceKeyPair.Key, new CookieOptions { Expires = new DateTimeOffset(DateTime.Now.AddMinutes(5)) });
|
||||
}
|
||||
var remoteAuthURL = remoteAuthConfig.RemoteAuthURL;
|
||||
return Json(remoteAuthURL);
|
||||
}
|
||||
@@ -99,18 +125,54 @@ namespace CarCareTracker.Controllers
|
||||
new KeyValuePair<string, string>("client_secret", openIdConfig.ClientSecret),
|
||||
new KeyValuePair<string, string>("redirect_uri", openIdConfig.RedirectURL)
|
||||
};
|
||||
if (openIdConfig.UsePKCE)
|
||||
{
|
||||
//retrieve stored challenge verifier
|
||||
var storedVerifier = Request.Cookies["OIDC_VERIFIER"];
|
||||
if (!string.IsNullOrWhiteSpace(storedVerifier))
|
||||
{
|
||||
httpParams.Add(new KeyValuePair<string, string>("code_verifier", storedVerifier));
|
||||
Response.Cookies.Delete("OIDC_VERIFIER");
|
||||
}
|
||||
}
|
||||
var httpRequest = new HttpRequestMessage(HttpMethod.Post, openIdConfig.TokenURL)
|
||||
{
|
||||
Content = new FormUrlEncodedContent(httpParams)
|
||||
};
|
||||
var tokenResult = await httpClient.SendAsync(httpRequest).Result.Content.ReadAsStringAsync();
|
||||
var userJwt = JsonSerializer.Deserialize<OpenIDResult>(tokenResult)?.id_token ?? string.Empty;
|
||||
var decodedToken = JsonSerializer.Deserialize<OpenIDResult>(tokenResult);
|
||||
var userJwt = decodedToken?.id_token ?? string.Empty;
|
||||
var userAccessToken = decodedToken?.access_token ?? string.Empty;
|
||||
if (!string.IsNullOrWhiteSpace(userJwt))
|
||||
{
|
||||
//validate JWT token
|
||||
var tokenParser = new JwtSecurityTokenHandler();
|
||||
var parsedToken = tokenParser.ReadJwtToken(userJwt);
|
||||
var userEmailAddress = parsedToken.Claims.First(x => x.Type == "email").Value;
|
||||
var userEmailAddress = string.Empty;
|
||||
if (parsedToken.Claims.Any(x => x.Type == "email"))
|
||||
{
|
||||
userEmailAddress = parsedToken.Claims.First(x => x.Type == "email").Value;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(openIdConfig.UserInfoURL) && !string.IsNullOrWhiteSpace(userAccessToken))
|
||||
{
|
||||
//retrieve claims from userinfo endpoint if no email claims are returned within id_token
|
||||
var userInfoHttpRequest = new HttpRequestMessage(HttpMethod.Get, openIdConfig.UserInfoURL);
|
||||
userInfoHttpRequest.Headers.Add("Authorization", $"Bearer {userAccessToken}");
|
||||
var userInfoResult = await httpClient.SendAsync(userInfoHttpRequest).Result.Content.ReadAsStringAsync();
|
||||
var userInfo = JsonSerializer.Deserialize<OpenIDUserInfo>(userInfoResult);
|
||||
if (!string.IsNullOrWhiteSpace(userInfo?.email ?? string.Empty))
|
||||
{
|
||||
userEmailAddress = userInfo?.email ?? string.Empty;
|
||||
} else
|
||||
{
|
||||
_logger.LogError($"OpenID Provider did not provide an email claim via UserInfo endpoint");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var returnedClaims = parsedToken.Claims.Select(x => x.Type);
|
||||
_logger.LogError($"OpenID Provider did not provide an email claim, claims returned: {string.Join(",", returnedClaims)}");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(userEmailAddress))
|
||||
{
|
||||
var userData = _loginLogic.ValidateOpenIDUser(new LoginModel() { EmailAddress = userEmailAddress });
|
||||
@@ -137,6 +199,11 @@ namespace CarCareTracker.Controllers
|
||||
} else
|
||||
{
|
||||
_logger.LogInformation("OpenID Provider did not provide a valid id_token");
|
||||
if (!string.IsNullOrWhiteSpace(tokenResult))
|
||||
{
|
||||
//if something was returned from the IdP but it's invalid, we want to log it as an error.
|
||||
_logger.LogError($"Expected id_token, received {tokenResult}");
|
||||
}
|
||||
}
|
||||
} else
|
||||
{
|
||||
@@ -149,6 +216,126 @@ namespace CarCareTracker.Controllers
|
||||
}
|
||||
return new RedirectResult("/Login");
|
||||
}
|
||||
public async Task<IActionResult> RemoteAuthDebug(string code, string state = "")
|
||||
{
|
||||
List<OperationResponse> results = new List<OperationResponse>();
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
results.Add(OperationResponse.Succeed($"Received code from OpenID Provider: {code}"));
|
||||
//received code from OIDC provider
|
||||
//create http client to retrieve user token from OIDC
|
||||
var httpClient = new HttpClient();
|
||||
var openIdConfig = _config.GetOpenIDConfig();
|
||||
//check if validate state is enabled.
|
||||
if (openIdConfig.ValidateState)
|
||||
{
|
||||
var storedStateValue = Request.Cookies["OIDC_STATE"];
|
||||
if (!string.IsNullOrWhiteSpace(storedStateValue))
|
||||
{
|
||||
Response.Cookies.Delete("OIDC_STATE");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(storedStateValue) || string.IsNullOrWhiteSpace(state) || storedStateValue != state)
|
||||
{
|
||||
results.Add(OperationResponse.Failed($"Failed State Validation - Expected: {storedStateValue} Received: {state}"));
|
||||
} else
|
||||
{
|
||||
results.Add(OperationResponse.Succeed($"Passed State Validation - Expected: {storedStateValue} Received: {state}"));
|
||||
}
|
||||
}
|
||||
var httpParams = new List<KeyValuePair<string, string>>
|
||||
{
|
||||
new KeyValuePair<string, string>("code", code),
|
||||
new KeyValuePair<string, string>("grant_type", "authorization_code"),
|
||||
new KeyValuePair<string, string>("client_id", openIdConfig.ClientId),
|
||||
new KeyValuePair<string, string>("client_secret", openIdConfig.ClientSecret),
|
||||
new KeyValuePair<string, string>("redirect_uri", openIdConfig.RedirectURL)
|
||||
};
|
||||
if (openIdConfig.UsePKCE)
|
||||
{
|
||||
//retrieve stored challenge verifier
|
||||
var storedVerifier = Request.Cookies["OIDC_VERIFIER"];
|
||||
if (!string.IsNullOrWhiteSpace(storedVerifier))
|
||||
{
|
||||
httpParams.Add(new KeyValuePair<string, string>("code_verifier", storedVerifier));
|
||||
Response.Cookies.Delete("OIDC_VERIFIER");
|
||||
}
|
||||
}
|
||||
var httpRequest = new HttpRequestMessage(HttpMethod.Post, openIdConfig.TokenURL)
|
||||
{
|
||||
Content = new FormUrlEncodedContent(httpParams)
|
||||
};
|
||||
var tokenResult = await httpClient.SendAsync(httpRequest).Result.Content.ReadAsStringAsync();
|
||||
var decodedToken = JsonSerializer.Deserialize<OpenIDResult>(tokenResult);
|
||||
var userJwt = decodedToken?.id_token ?? string.Empty;
|
||||
var userAccessToken = decodedToken?.access_token ?? string.Empty;
|
||||
if (!string.IsNullOrWhiteSpace(userJwt))
|
||||
{
|
||||
results.Add(OperationResponse.Succeed($"Passed JWT Parsing - id_token: {userJwt}"));
|
||||
//validate JWT token
|
||||
var tokenParser = new JwtSecurityTokenHandler();
|
||||
var parsedToken = tokenParser.ReadJwtToken(userJwt);
|
||||
var userEmailAddress = string.Empty;
|
||||
if (parsedToken.Claims.Any(x => x.Type == "email"))
|
||||
{
|
||||
userEmailAddress = parsedToken.Claims.First(x => x.Type == "email").Value;
|
||||
results.Add(OperationResponse.Succeed($"Passed Claim Validation - email"));
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(openIdConfig.UserInfoURL) && !string.IsNullOrWhiteSpace(userAccessToken))
|
||||
{
|
||||
//retrieve claims from userinfo endpoint if no email claims are returned within id_token
|
||||
var userInfoHttpRequest = new HttpRequestMessage(HttpMethod.Get, openIdConfig.UserInfoURL);
|
||||
userInfoHttpRequest.Headers.Add("Authorization", $"Bearer {userAccessToken}");
|
||||
var userInfoResult = await httpClient.SendAsync(userInfoHttpRequest).Result.Content.ReadAsStringAsync();
|
||||
var userInfo = JsonSerializer.Deserialize<OpenIDUserInfo>(userInfoResult);
|
||||
if (!string.IsNullOrWhiteSpace(userInfo?.email ?? string.Empty))
|
||||
{
|
||||
userEmailAddress = userInfo?.email ?? string.Empty;
|
||||
results.Add(OperationResponse.Succeed($"Passed Claim Validation - Retrieved email via UserInfo endpoint"));
|
||||
} else
|
||||
{
|
||||
results.Add(OperationResponse.Failed($"Failed Claim Validation - Unable to retrieve email via UserInfo endpoint: {openIdConfig.UserInfoURL} using access_token: {userAccessToken} - Received {userInfoResult}"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var returnedClaims = parsedToken.Claims.Select(x => x.Type);
|
||||
results.Add(OperationResponse.Failed($"Failed Claim Validation - Expected: email Received: {string.Join(",", returnedClaims)}"));
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(userEmailAddress))
|
||||
{
|
||||
var userData = _loginLogic.ValidateOpenIDUser(new LoginModel() { EmailAddress = userEmailAddress });
|
||||
if (userData.Id != default)
|
||||
{
|
||||
results.Add(OperationResponse.Succeed($"Passed User Validation - Email: {userEmailAddress} Username: {userData.UserName}"));
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add(OperationResponse.Succeed($"Passed Email Validation - Email: {userEmailAddress} User not registered"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add(OperationResponse.Failed($"Failed Email Validation - No email received from OpenID Provider"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add(OperationResponse.Failed($"Failed to parse JWT - Expected: id_token Received: {tokenResult}"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
results.Add(OperationResponse.Failed("No code received from OpenID Provider"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
results.Add(OperationResponse.Failed($"Exception: {ex.Message}"));
|
||||
}
|
||||
return View(results);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult Login(LoginModel credentials)
|
||||
{
|
||||
@@ -209,6 +396,12 @@ namespace CarCareTracker.Controllers
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SendRegistrationToken(LoginModel credentials)
|
||||
{
|
||||
var result = _loginLogic.SendRegistrationToken(credentials);
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult RequestResetPassword(LoginModel credentials)
|
||||
{
|
||||
var result = _loginLogic.RequestResetPassword(credentials);
|
||||
@@ -220,7 +413,7 @@ namespace CarCareTracker.Controllers
|
||||
var result = _loginLogic.ResetPasswordByUser(credentials);
|
||||
return Json(result);
|
||||
}
|
||||
[Authorize] //User must already be logged in to do this.
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))] //User must already be logged in as root user to do this.
|
||||
[HttpPost]
|
||||
public IActionResult CreateLoginCreds(LoginModel credentials)
|
||||
{
|
||||
@@ -235,7 +428,7 @@ namespace CarCareTracker.Controllers
|
||||
}
|
||||
return Json(false);
|
||||
}
|
||||
[Authorize]
|
||||
[Authorize(Roles = nameof(UserData.IsRootUser))]
|
||||
[HttpPost]
|
||||
public IActionResult DestroyLoginCreds()
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Npgsql;
|
||||
using System.IO.Compression;
|
||||
using JsonSerializer=System.Text.Json.JsonSerializer;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
@@ -14,7 +15,7 @@ namespace CarCareTracker.Controllers
|
||||
private IConfigHelper _configHelper;
|
||||
private IFileHelper _fileHelper;
|
||||
private readonly ILogger<MigrationController> _logger;
|
||||
public MigrationController(IConfigHelper configHelper, IFileHelper fileHelper, IConfiguration serverConfig, ILogger<MigrationController> logger)
|
||||
public MigrationController(IConfigHelper configHelper, IFileHelper fileHelper, ILogger<MigrationController> logger)
|
||||
{
|
||||
_configHelper = configHelper;
|
||||
_fileHelper = fileHelper;
|
||||
@@ -34,6 +35,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
var cmds = new List<string>
|
||||
{
|
||||
"CREATE SCHEMA IF NOT EXISTS app",
|
||||
"CREATE TABLE IF NOT EXISTS app.vehicles (id INT GENERATED BY DEFAULT AS IDENTITY primary key, data jsonb not null)",
|
||||
"CREATE TABLE IF NOT EXISTS app.collisionrecords (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)",
|
||||
"CREATE TABLE IF NOT EXISTS app.upgraderecords (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)",
|
||||
@@ -64,7 +66,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_configHelper.GetServerPostgresConnection()))
|
||||
{
|
||||
return Json(new OperationResponse { Success = false, Message = "Postgres connection not set up" });
|
||||
return Json(OperationResponse.Failed("Postgres connection not set up"));
|
||||
}
|
||||
var tempFolder = $"temp/{Guid.NewGuid()}";
|
||||
var tempPath = $"{tempFolder}/cartracker.db";
|
||||
@@ -104,7 +106,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
Vehicle vehicle = System.Text.Json.JsonSerializer.Deserialize<Vehicle>(reader["data"] as string);
|
||||
Vehicle vehicle = JsonSerializer.Deserialize<Vehicle>(reader["data"] as string);
|
||||
vehicles.Add(vehicle);
|
||||
}
|
||||
}
|
||||
@@ -122,7 +124,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
repairrecords.Add(System.Text.Json.JsonSerializer.Deserialize<CollisionRecord>(reader["data"] as string));
|
||||
repairrecords.Add(JsonSerializer.Deserialize<CollisionRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in repairrecords)
|
||||
@@ -139,7 +141,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
upgraderecords.Add(System.Text.Json.JsonSerializer.Deserialize<UpgradeRecord>(reader["data"] as string));
|
||||
upgraderecords.Add(JsonSerializer.Deserialize<UpgradeRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in upgraderecords)
|
||||
@@ -156,7 +158,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
servicerecords.Add(System.Text.Json.JsonSerializer.Deserialize<ServiceRecord>(reader["data"] as string));
|
||||
servicerecords.Add(JsonSerializer.Deserialize<ServiceRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in servicerecords)
|
||||
@@ -175,7 +177,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
gasrecords.Add(System.Text.Json.JsonSerializer.Deserialize<GasRecord>(reader["data"] as string));
|
||||
gasrecords.Add(JsonSerializer.Deserialize<GasRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in gasrecords)
|
||||
@@ -192,7 +194,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
noterecords.Add(System.Text.Json.JsonSerializer.Deserialize<Note>(reader["data"] as string));
|
||||
noterecords.Add(JsonSerializer.Deserialize<Note>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in noterecords)
|
||||
@@ -209,7 +211,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
odometerrecords.Add(System.Text.Json.JsonSerializer.Deserialize<OdometerRecord>(reader["data"] as string));
|
||||
odometerrecords.Add(JsonSerializer.Deserialize<OdometerRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in odometerrecords)
|
||||
@@ -226,7 +228,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
reminderrecords.Add(System.Text.Json.JsonSerializer.Deserialize<ReminderRecord>(reader["data"] as string));
|
||||
reminderrecords.Add(JsonSerializer.Deserialize<ReminderRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in reminderrecords)
|
||||
@@ -245,7 +247,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
planrecords.Add(System.Text.Json.JsonSerializer.Deserialize<PlanRecord>(reader["data"] as string));
|
||||
planrecords.Add(JsonSerializer.Deserialize<PlanRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in planrecords)
|
||||
@@ -262,7 +264,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
planrecordtemplates.Add(System.Text.Json.JsonSerializer.Deserialize<PlanRecordInput>(reader["data"] as string));
|
||||
planrecordtemplates.Add(JsonSerializer.Deserialize<PlanRecordInput>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in planrecordtemplates)
|
||||
@@ -279,7 +281,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
supplyrecords.Add(System.Text.Json.JsonSerializer.Deserialize<SupplyRecord>(reader["data"] as string));
|
||||
supplyrecords.Add(JsonSerializer.Deserialize<SupplyRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in supplyrecords)
|
||||
@@ -296,7 +298,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
taxrecords.Add(System.Text.Json.JsonSerializer.Deserialize<TaxRecord>(reader["data"] as string));
|
||||
taxrecords.Add(JsonSerializer.Deserialize<TaxRecord>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in taxrecords)
|
||||
@@ -359,7 +361,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
userconfigrecords.Add(System.Text.Json.JsonSerializer.Deserialize<UserConfigData>(reader["data"] as string));
|
||||
userconfigrecords.Add(JsonSerializer.Deserialize<UserConfigData>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in userconfigrecords)
|
||||
@@ -403,7 +405,7 @@ namespace CarCareTracker.Controllers
|
||||
using (NpgsqlDataReader reader = ctext.ExecuteReader())
|
||||
while (reader.Read())
|
||||
{
|
||||
extrafields.Add(System.Text.Json.JsonSerializer.Deserialize<RecordExtraField>(reader["data"] as string));
|
||||
extrafields.Add(JsonSerializer.Deserialize<RecordExtraField>(reader["data"] as string));
|
||||
}
|
||||
}
|
||||
foreach (var record in extrafields)
|
||||
@@ -417,24 +419,24 @@ namespace CarCareTracker.Controllers
|
||||
#endregion
|
||||
var destFilePath = $"{fullFolderPath}.zip";
|
||||
ZipFile.CreateFromDirectory(fullFolderPath, destFilePath);
|
||||
return Json(new OperationResponse { Success = true, Message = $"/{tempFolder}.zip" });
|
||||
return Json(OperationResponse.Succeed($"/{tempFolder}.zip"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
}
|
||||
public IActionResult Import(string fileName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_configHelper.GetServerPostgresConnection()))
|
||||
{
|
||||
return Json(new OperationResponse { Success = false, Message = "Postgres connection not set up" });
|
||||
return Json(OperationResponse.Failed("Postgres connection not set up"));
|
||||
}
|
||||
var fullFileName = _fileHelper.GetFullFilePath(fileName);
|
||||
if (string.IsNullOrWhiteSpace(fullFileName))
|
||||
{
|
||||
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
try
|
||||
{
|
||||
@@ -474,7 +476,7 @@ namespace CarCareTracker.Controllers
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicle.Id);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(vehicle));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(vehicle));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -490,7 +492,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -506,7 +508,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -522,7 +524,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -540,7 +542,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -556,7 +558,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -572,7 +574,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -588,7 +590,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -606,7 +608,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -622,7 +624,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -638,7 +640,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -654,7 +656,7 @@ namespace CarCareTracker.Controllers
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("vehicleId", record.VehicleId);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -705,7 +707,7 @@ namespace CarCareTracker.Controllers
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
@@ -737,17 +739,17 @@ namespace CarCareTracker.Controllers
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", record.Id);
|
||||
ctext.Parameters.AddWithValue("data", System.Text.Json.JsonSerializer.Serialize(record));
|
||||
ctext.Parameters.AddWithValue("data", JsonSerializer.Serialize(record));
|
||||
ctext.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
return Json(new OperationResponse { Success = true, Message = "Data Imported Successfully" });
|
||||
return Json(OperationResponse.Succeed("Data Imported Successfully"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
209
Controllers/Vehicle/GasController.cs
Normal file
209
Controllers/Vehicle/GasController.cs
Normal file
@@ -0,0 +1,209 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetGasRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId);
|
||||
//check if the user uses MPG or Liters per 100km.
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
bool useMPG = userConfig.UseMPG;
|
||||
bool useUKMPG = userConfig.UseUKMPG;
|
||||
var computedResults = _gasHelper.GetGasRecordViewModels(result, useMPG, useUKMPG);
|
||||
if (userConfig.UseDescending)
|
||||
{
|
||||
computedResults = computedResults.OrderByDescending(x => DateTime.Parse(x.Date)).ThenByDescending(x => x.Mileage).ToList();
|
||||
}
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var vehicleIsElectric = vehicleData.IsElectric;
|
||||
var vehicleUseHours = vehicleData.UseHours;
|
||||
var viewModel = new GasRecordViewModelContainer()
|
||||
{
|
||||
UseKwh = vehicleIsElectric,
|
||||
UseHours = vehicleUseHours,
|
||||
GasRecords = computedResults
|
||||
};
|
||||
return PartialView("_Gas", viewModel);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveGasRecordToVehicleId(GasRecordInput gasRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), gasRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
if (gasRecord.Id == default && _config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = DateTime.Parse(gasRecord.Date),
|
||||
VehicleId = gasRecord.VehicleId,
|
||||
Mileage = gasRecord.Mileage,
|
||||
Notes = $"Auto Insert From Gas Record. {gasRecord.Notes}"
|
||||
});
|
||||
}
|
||||
gasRecord.Files = gasRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
var result = _gasRecordDataAccess.SaveGasRecordToVehicle(gasRecord.ToGasRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGasRecord(gasRecord.ToGasRecord(), gasRecord.Id == default ? "gasrecord.add" : "gasrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetAddGasRecordPartialView(int vehicleId)
|
||||
{
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var vehicleIsElectric = vehicleData.IsElectric;
|
||||
var vehicleUseHours = vehicleData.UseHours;
|
||||
return PartialView("_GasModal", new GasRecordInputContainer() { UseKwh = vehicleIsElectric, UseHours = vehicleUseHours, GasRecord = new GasRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.GasRecord).ExtraFields } });
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetGasRecordForEditById(int gasRecordId)
|
||||
{
|
||||
var result = _gasRecordDataAccess.GetGasRecordById(gasRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
var convertedResult = new GasRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Mileage = result.Mileage,
|
||||
VehicleId = result.VehicleId,
|
||||
Cost = result.Cost,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Files = result.Files,
|
||||
Gallons = result.Gallons,
|
||||
IsFillToFull = result.IsFillToFull,
|
||||
MissedFuelUp = result.MissedFuelUp,
|
||||
Notes = result.Notes,
|
||||
Tags = result.Tags,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.GasRecord).ExtraFields)
|
||||
};
|
||||
var vehicleData = _dataAccess.GetVehicleById(convertedResult.VehicleId);
|
||||
var vehicleIsElectric = vehicleData.IsElectric;
|
||||
var vehicleUseHours = vehicleData.UseHours;
|
||||
var viewModel = new GasRecordInputContainer()
|
||||
{
|
||||
UseKwh = vehicleIsElectric,
|
||||
UseHours = vehicleUseHours,
|
||||
GasRecord = convertedResult
|
||||
};
|
||||
return PartialView("_GasModal", viewModel);
|
||||
}
|
||||
private bool DeleteGasRecordWithChecks(int gasRecordId)
|
||||
{
|
||||
var existingRecord = _gasRecordDataAccess.GetGasRecordById(gasRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var result = _gasRecordDataAccess.DeleteGasRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGasRecord(existingRecord, "gasrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteGasRecordById(int gasRecordId)
|
||||
{
|
||||
var result = DeleteGasRecordWithChecks(gasRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveUserGasTabPreferences(string gasUnit, string fuelMileageUnit)
|
||||
{
|
||||
var currentConfig = _config.GetUserConfig(User);
|
||||
currentConfig.PreferredGasUnit = gasUnit;
|
||||
currentConfig.PreferredGasMileageUnit = fuelMileageUnit;
|
||||
var result = _config.SaveUserConfig(User, currentConfig);
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult GetGasRecordsEditModal(List<int> recordIds)
|
||||
{
|
||||
var extraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.GasRecord).ExtraFields;
|
||||
return PartialView("_GasRecordsModal", new GasRecordEditModel { RecordIds = recordIds, EditRecord = new GasRecord { ExtraFields = extraFields } });
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveMultipleGasRecords(GasRecordEditModel editModel)
|
||||
{
|
||||
var dateIsEdited = editModel.EditRecord.Date != default;
|
||||
var mileageIsEdited = editModel.EditRecord.Mileage != default;
|
||||
var consumptionIsEdited = editModel.EditRecord.Gallons != default;
|
||||
var costIsEdited = editModel.EditRecord.Cost != default;
|
||||
var noteIsEdited = !string.IsNullOrWhiteSpace(editModel.EditRecord.Notes);
|
||||
var tagsIsEdited = editModel.EditRecord.Tags.Any();
|
||||
var extraFieldIsEdited = editModel.EditRecord.ExtraFields.Any();
|
||||
//handle clear overrides
|
||||
if (tagsIsEdited && editModel.EditRecord.Tags.Contains("---"))
|
||||
{
|
||||
editModel.EditRecord.Tags = new List<string>();
|
||||
}
|
||||
if (noteIsEdited && editModel.EditRecord.Notes == "---")
|
||||
{
|
||||
editModel.EditRecord.Notes = "";
|
||||
}
|
||||
bool result = false;
|
||||
foreach (int recordId in editModel.RecordIds)
|
||||
{
|
||||
var existingRecord = _gasRecordDataAccess.GetGasRecordById(recordId);
|
||||
if (dateIsEdited)
|
||||
{
|
||||
existingRecord.Date = editModel.EditRecord.Date;
|
||||
}
|
||||
if (consumptionIsEdited)
|
||||
{
|
||||
existingRecord.Gallons = editModel.EditRecord.Gallons;
|
||||
}
|
||||
if (costIsEdited)
|
||||
{
|
||||
existingRecord.Cost = editModel.EditRecord.Cost;
|
||||
}
|
||||
if (mileageIsEdited)
|
||||
{
|
||||
existingRecord.Mileage = editModel.EditRecord.Mileage;
|
||||
}
|
||||
if (noteIsEdited)
|
||||
{
|
||||
existingRecord.Notes = editModel.EditRecord.Notes;
|
||||
}
|
||||
if (tagsIsEdited)
|
||||
{
|
||||
existingRecord.Tags = editModel.EditRecord.Tags;
|
||||
}
|
||||
if (extraFieldIsEdited)
|
||||
{
|
||||
foreach (ExtraField extraField in editModel.EditRecord.ExtraFields)
|
||||
{
|
||||
if (existingRecord.ExtraFields.Any(x => x.Name == extraField.Name))
|
||||
{
|
||||
var insertIndex = existingRecord.ExtraFields.FindIndex(x => x.Name == extraField.Name);
|
||||
existingRecord.ExtraFields.RemoveAll(x => x.Name == extraField.Name);
|
||||
existingRecord.ExtraFields.Insert(insertIndex, extraField);
|
||||
}
|
||||
else
|
||||
{
|
||||
existingRecord.ExtraFields.Add(extraField);
|
||||
}
|
||||
}
|
||||
}
|
||||
result = _gasRecordDataAccess.SaveGasRecordToVehicle(existingRecord);
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
665
Controllers/Vehicle/ImportController.cs
Normal file
665
Controllers/Vehicle/ImportController.cs
Normal file
@@ -0,0 +1,665 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.MapProfile;
|
||||
using CarCareTracker.Models;
|
||||
using CsvHelper;
|
||||
using CsvHelper.Configuration;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Globalization;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[HttpGet]
|
||||
public IActionResult GetBulkImportModalPartialView(ImportMode mode)
|
||||
{
|
||||
return PartialView("_BulkDataImporter", mode);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GenerateCsvSample(ImportMode mode)
|
||||
{
|
||||
string uploadDirectory = "temp/";
|
||||
string uploadPath = Path.Combine(_webEnv.ContentRootPath, "data", uploadDirectory);
|
||||
if (!Directory.Exists(uploadPath))
|
||||
Directory.CreateDirectory(uploadPath);
|
||||
var fileNameToExport = $"temp/{Guid.NewGuid()}.csv";
|
||||
var fullExportFilePath = _fileHelper.GetFullFilePath(fileNameToExport, false);
|
||||
switch (mode)
|
||||
{
|
||||
case ImportMode.ServiceRecord:
|
||||
case ImportMode.RepairRecord:
|
||||
case ImportMode.UpgradeRecord:
|
||||
{
|
||||
var exportData = new List<GenericRecordExportModel> { new GenericRecordExportModel
|
||||
{
|
||||
Date = DateTime.Now.ToShortDateString(),
|
||||
Description = "Test",
|
||||
Cost = 123.45M.ToString("C"),
|
||||
Notes = "Test Note",
|
||||
Odometer = 12345.ToString(),
|
||||
Tags = "test1 test2"
|
||||
} };
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WriteGenericRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ImportMode.GasRecord:
|
||||
{
|
||||
var exportData = new List<GasRecordExportModel> { new GasRecordExportModel
|
||||
{
|
||||
Date = DateTime.Now.ToShortDateString(),
|
||||
Odometer = 12345.ToString(),
|
||||
FuelConsumed = 12.34M.ToString(),
|
||||
Cost = 45.67M.ToString("C"),
|
||||
IsFillToFull = true.ToString(),
|
||||
MissedFuelUp = false.ToString(),
|
||||
Notes = "Test Note",
|
||||
Tags = "test1 test2"
|
||||
} };
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WriteGasRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ImportMode.OdometerRecord:
|
||||
{
|
||||
var exportData = new List<OdometerRecordExportModel> { new OdometerRecordExportModel
|
||||
{
|
||||
Date = DateTime.Now.ToShortDateString(),
|
||||
InitialOdometer = 12345.ToString(),
|
||||
Odometer = 12345.ToString(),
|
||||
Notes = "Test Note",
|
||||
Tags = "test1 test2"
|
||||
} };
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WriteOdometerRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ImportMode.TaxRecord:
|
||||
{
|
||||
var exportData = new List<TaxRecordExportModel> { new TaxRecordExportModel
|
||||
{
|
||||
Date = DateTime.Now.ToShortDateString(),
|
||||
Description = "Test",
|
||||
Cost = 123.45M.ToString("C"),
|
||||
Notes = "Test Note",
|
||||
Tags = "test1 test2"
|
||||
} };
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WriteTaxRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ImportMode.SupplyRecord:
|
||||
{
|
||||
var exportData = new List<SupplyRecordExportModel> { new SupplyRecordExportModel
|
||||
{
|
||||
Date = DateTime.Now.ToShortDateString(),
|
||||
PartNumber = "TEST-123456",
|
||||
PartSupplier = "Test Supplier",
|
||||
PartQuantity = 1.5M.ToString(),
|
||||
Description = "Test",
|
||||
Cost = 123.45M.ToString("C"),
|
||||
Notes = "Test Note",
|
||||
Tags = "test1 test2"
|
||||
} };
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WriteSupplyRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ImportMode.PlanRecord:
|
||||
{
|
||||
var exportData = new List<PlanRecordExportModel> { new PlanRecordExportModel
|
||||
{
|
||||
DateCreated = DateTime.Now.ToString(),
|
||||
DateModified = DateTime.Now.ToString(),
|
||||
Description = "Test",
|
||||
Type = ImportMode.RepairRecord.ToString(),
|
||||
Priority = PlanPriority.Normal.ToString(),
|
||||
Progress = PlanProgress.Testing.ToString(),
|
||||
Cost = 123.45M.ToString("C"),
|
||||
Notes = "Test Note"
|
||||
} };
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WritePlanRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return Json(OperationResponse.Failed("No parameters"));
|
||||
}
|
||||
try
|
||||
{
|
||||
var fileBytes = _fileHelper.GetFileBytes(fullExportFilePath, true);
|
||||
if (fileBytes.Length > 0)
|
||||
{
|
||||
return File(fileBytes, "text/csv", $"{mode.ToString().ToLower()}sample.csv");
|
||||
}
|
||||
else
|
||||
{
|
||||
return Json(OperationResponse.Failed("An error has occurred while generating CSV sample: file has zero bytes"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return Json(OperationResponse.Failed($"An error has occurred while generating CSV sample: {ex.Message}"));
|
||||
}
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult ExportFromVehicleToCsv(int vehicleId, ImportMode mode)
|
||||
{
|
||||
if (vehicleId == default && mode != ImportMode.SupplyRecord)
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
string uploadDirectory = "temp/";
|
||||
string uploadPath = Path.Combine(_webEnv.ContentRootPath, "data", uploadDirectory);
|
||||
if (!Directory.Exists(uploadPath))
|
||||
Directory.CreateDirectory(uploadPath);
|
||||
var fileNameToExport = $"temp/{Guid.NewGuid()}.csv";
|
||||
var fullExportFilePath = _fileHelper.GetFullFilePath(fileNameToExport, false);
|
||||
if (mode == ImportMode.ServiceRecord)
|
||||
{
|
||||
var vehicleRecords = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new GenericRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToShortDateString(),
|
||||
Description = x.Description,
|
||||
Cost = x.Cost.ToString("C"),
|
||||
Notes = x.Notes,
|
||||
Odometer = x.Mileage.ToString(),
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
//custom writer
|
||||
StaticHelper.WriteGenericRecordExportModel(csv, exportData);
|
||||
}
|
||||
writer.Dispose();
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.RepairRecord)
|
||||
{
|
||||
var vehicleRecords = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new GenericRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToShortDateString(),
|
||||
Description = x.Description,
|
||||
Cost = x.Cost.ToString("C"),
|
||||
Notes = x.Notes,
|
||||
Odometer = x.Mileage.ToString(),
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WriteGenericRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.UpgradeRecord)
|
||||
{
|
||||
var vehicleRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new GenericRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToShortDateString(),
|
||||
Description = x.Description,
|
||||
Cost = x.Cost.ToString("C"),
|
||||
Notes = x.Notes,
|
||||
Odometer = x.Mileage.ToString(),
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WriteGenericRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.OdometerRecord)
|
||||
{
|
||||
var vehicleRecords = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new OdometerRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToShortDateString(),
|
||||
Notes = x.Notes,
|
||||
InitialOdometer = x.InitialMileage.ToString(),
|
||||
Odometer = x.Mileage.ToString(),
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WriteOdometerRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.SupplyRecord)
|
||||
{
|
||||
var vehicleRecords = _supplyRecordDataAccess.GetSupplyRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new SupplyRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToShortDateString(),
|
||||
Description = x.Description,
|
||||
Cost = x.Cost.ToString("C"),
|
||||
PartNumber = x.PartNumber,
|
||||
PartQuantity = x.Quantity.ToString(),
|
||||
PartSupplier = x.PartSupplier,
|
||||
Notes = x.Notes,
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WriteSupplyRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.TaxRecord)
|
||||
{
|
||||
var vehicleRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new TaxRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToShortDateString(),
|
||||
Description = x.Description,
|
||||
Cost = x.Cost.ToString("C"),
|
||||
Notes = x.Notes,
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WriteTaxRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.PlanRecord)
|
||||
{
|
||||
var vehicleRecords = _planRecordDataAccess.GetPlanRecordsByVehicleId(vehicleId);
|
||||
if (vehicleRecords.Any())
|
||||
{
|
||||
var exportData = vehicleRecords.Select(x => new PlanRecordExportModel
|
||||
{
|
||||
DateCreated = x.DateCreated.ToString("G"),
|
||||
DateModified = x.DateModified.ToString("G"),
|
||||
Description = x.Description,
|
||||
Cost = x.Cost.ToString("C"),
|
||||
Type = x.ImportMode.ToString(),
|
||||
Priority = x.Priority.ToString(),
|
||||
Progress = x.Progress.ToString(),
|
||||
Notes = x.Notes,
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WritePlanRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.GasRecord)
|
||||
{
|
||||
var vehicleRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId);
|
||||
bool useMPG = _config.GetUserConfig(User).UseMPG;
|
||||
bool useUKMPG = _config.GetUserConfig(User).UseUKMPG;
|
||||
var convertedRecords = _gasHelper.GetGasRecordViewModels(vehicleRecords, useMPG, useUKMPG);
|
||||
var exportData = convertedRecords.Select(x => new GasRecordExportModel
|
||||
{
|
||||
Date = x.Date.ToString(),
|
||||
Cost = x.Cost.ToString(),
|
||||
FuelConsumed = x.Gallons.ToString(),
|
||||
FuelEconomy = x.MilesPerGallon.ToString(),
|
||||
Odometer = x.Mileage.ToString(),
|
||||
IsFillToFull = x.IsFillToFull.ToString(),
|
||||
MissedFuelUp = x.MissedFuelUp.ToString(),
|
||||
Notes = x.Notes,
|
||||
Tags = string.Join(" ", x.Tags),
|
||||
ExtraFields = x.ExtraFields
|
||||
});
|
||||
using (var writer = new StreamWriter(fullExportFilePath))
|
||||
{
|
||||
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
||||
{
|
||||
StaticHelper.WriteGasRecordExportModel(csv, exportData);
|
||||
}
|
||||
}
|
||||
return Json($"/{fileNameToExport}");
|
||||
}
|
||||
return Json(false);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult ImportToVehicleIdFromCsv(int vehicleId, ImportMode mode, string fileName)
|
||||
{
|
||||
if (vehicleId == default && mode != ImportMode.SupplyRecord)
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
var fullFileName = _fileHelper.GetFullFilePath(fileName);
|
||||
if (string.IsNullOrWhiteSpace(fullFileName))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
try
|
||||
{
|
||||
using (var reader = new StreamReader(fullFileName))
|
||||
{
|
||||
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
|
||||
config.MissingFieldFound = null;
|
||||
config.HeaderValidated = null;
|
||||
config.PrepareHeaderForMatch = args => { return args.Header.Trim().ToLower(); };
|
||||
using (var csv = new CsvReader(reader, config))
|
||||
{
|
||||
csv.Context.RegisterClassMap<ImportMapper>();
|
||||
var records = csv.GetRecords<ImportModel>().ToList();
|
||||
if (records.Any())
|
||||
{
|
||||
var requiredExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)mode).ExtraFields.Where(x => x.IsRequired).Select(y => y.Name);
|
||||
foreach (ImportModel importModel in records)
|
||||
{
|
||||
var parsedDate = DateTime.Now.Date;
|
||||
if (!string.IsNullOrWhiteSpace(importModel.Date))
|
||||
{
|
||||
parsedDate = DateTime.Parse(importModel.Date);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(importModel.Day) && !string.IsNullOrWhiteSpace(importModel.Month) && !string.IsNullOrWhiteSpace(importModel.Year))
|
||||
{
|
||||
parsedDate = new DateTime(int.Parse(importModel.Year), int.Parse(importModel.Month), int.Parse(importModel.Day));
|
||||
}
|
||||
if (mode == ImportMode.GasRecord)
|
||||
{
|
||||
//convert to gas model.
|
||||
var convertedRecord = new GasRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
Mileage = decimal.ToInt32(decimal.Parse(importModel.Odometer, NumberStyles.Any)),
|
||||
Gallons = decimal.Parse(importModel.FuelConsumed, NumberStyles.Any),
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
if (string.IsNullOrWhiteSpace(importModel.Cost) && !string.IsNullOrWhiteSpace(importModel.Price))
|
||||
{
|
||||
//cost was not given but price is.
|
||||
//fuelly sometimes exports CSVs without total cost.
|
||||
var parsedPrice = decimal.Parse(importModel.Price, NumberStyles.Any);
|
||||
convertedRecord.Cost = convertedRecord.Gallons * parsedPrice;
|
||||
}
|
||||
else
|
||||
{
|
||||
convertedRecord.Cost = decimal.Parse(importModel.Cost, NumberStyles.Any);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(importModel.IsFillToFull) && !string.IsNullOrWhiteSpace(importModel.PartialFuelUp))
|
||||
{
|
||||
var parsedBool = importModel.PartialFuelUp.Trim() == "1";
|
||||
convertedRecord.IsFillToFull = !parsedBool;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(importModel.IsFillToFull))
|
||||
{
|
||||
var possibleFillToFullValues = new List<string> { "1", "true", "full" };
|
||||
var parsedBool = possibleFillToFullValues.Contains(importModel.IsFillToFull.Trim().ToLower());
|
||||
convertedRecord.IsFillToFull = parsedBool;
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(importModel.MissedFuelUp))
|
||||
{
|
||||
var possibleMissedFuelUpValues = new List<string> { "1", "true" };
|
||||
var parsedBool = possibleMissedFuelUpValues.Contains(importModel.MissedFuelUp.Trim().ToLower());
|
||||
convertedRecord.MissedFuelUp = parsedBool;
|
||||
}
|
||||
//insert record into db, check to make sure fuelconsumed is not zero so we don't get a divide by zero error.
|
||||
if (convertedRecord.Gallons > 0)
|
||||
{
|
||||
_gasRecordDataAccess.SaveGasRecordToVehicle(convertedRecord);
|
||||
if (_config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = convertedRecord.Date,
|
||||
VehicleId = convertedRecord.VehicleId,
|
||||
Mileage = convertedRecord.Mileage,
|
||||
Notes = $"Auto Insert From Gas Record via CSV Import. {convertedRecord.Notes}"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.ServiceRecord)
|
||||
{
|
||||
var convertedRecord = new ServiceRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
Mileage = decimal.ToInt32(decimal.Parse(importModel.Odometer, NumberStyles.Any)),
|
||||
Description = string.IsNullOrWhiteSpace(importModel.Description) ? $"Service Record on {parsedDate.ToShortDateString()}" : importModel.Description,
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Cost = decimal.Parse(importModel.Cost, NumberStyles.Any),
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_serviceRecordDataAccess.SaveServiceRecordToVehicle(convertedRecord);
|
||||
if (_config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = convertedRecord.Date,
|
||||
VehicleId = convertedRecord.VehicleId,
|
||||
Mileage = convertedRecord.Mileage,
|
||||
Notes = $"Auto Insert From Service Record via CSV Import. {convertedRecord.Notes}"
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.OdometerRecord)
|
||||
{
|
||||
var convertedRecord = new OdometerRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
InitialMileage = string.IsNullOrWhiteSpace(importModel.InitialOdometer) ? 0 : decimal.ToInt32(decimal.Parse(importModel.InitialOdometer, NumberStyles.Any)),
|
||||
Mileage = decimal.ToInt32(decimal.Parse(importModel.Odometer, NumberStyles.Any)),
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_odometerRecordDataAccess.SaveOdometerRecordToVehicle(convertedRecord);
|
||||
}
|
||||
else if (mode == ImportMode.PlanRecord)
|
||||
{
|
||||
var progressIsEnum = Enum.TryParse(importModel.Progress, out PlanProgress parsedProgress);
|
||||
var typeIsEnum = Enum.TryParse(importModel.Type, out ImportMode parsedType);
|
||||
var priorityIsEnum = Enum.TryParse(importModel.Priority, out PlanPriority parsedPriority);
|
||||
var convertedRecord = new PlanRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
DateCreated = DateTime.Parse(importModel.DateCreated),
|
||||
DateModified = DateTime.Parse(importModel.DateModified),
|
||||
Progress = parsedProgress,
|
||||
ImportMode = parsedType,
|
||||
Priority = parsedPriority,
|
||||
Description = string.IsNullOrWhiteSpace(importModel.Description) ? $"Plan Record on {importModel.DateCreated}" : importModel.Description,
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Cost = decimal.Parse(importModel.Cost, NumberStyles.Any),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_planRecordDataAccess.SavePlanRecordToVehicle(convertedRecord);
|
||||
}
|
||||
else if (mode == ImportMode.RepairRecord)
|
||||
{
|
||||
var convertedRecord = new CollisionRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
Mileage = decimal.ToInt32(decimal.Parse(importModel.Odometer, NumberStyles.Any)),
|
||||
Description = string.IsNullOrWhiteSpace(importModel.Description) ? $"Repair Record on {parsedDate.ToShortDateString()}" : importModel.Description,
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Cost = decimal.Parse(importModel.Cost, NumberStyles.Any),
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_collisionRecordDataAccess.SaveCollisionRecordToVehicle(convertedRecord);
|
||||
if (_config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = convertedRecord.Date,
|
||||
VehicleId = convertedRecord.VehicleId,
|
||||
Mileage = convertedRecord.Mileage,
|
||||
Notes = $"Auto Insert From Repair Record via CSV Import. {convertedRecord.Notes}"
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.UpgradeRecord)
|
||||
{
|
||||
var convertedRecord = new UpgradeRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
Mileage = decimal.ToInt32(decimal.Parse(importModel.Odometer, NumberStyles.Any)),
|
||||
Description = string.IsNullOrWhiteSpace(importModel.Description) ? $"Upgrade Record on {parsedDate.ToShortDateString()}" : importModel.Description,
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Cost = decimal.Parse(importModel.Cost, NumberStyles.Any),
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_upgradeRecordDataAccess.SaveUpgradeRecordToVehicle(convertedRecord);
|
||||
if (_config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = convertedRecord.Date,
|
||||
VehicleId = convertedRecord.VehicleId,
|
||||
Mileage = convertedRecord.Mileage,
|
||||
Notes = $"Auto Insert From Upgrade Record via CSV Import. {convertedRecord.Notes}"
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (mode == ImportMode.SupplyRecord)
|
||||
{
|
||||
var convertedRecord = new SupplyRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
PartNumber = importModel.PartNumber,
|
||||
PartSupplier = importModel.PartSupplier,
|
||||
Quantity = decimal.Parse(importModel.PartQuantity, NumberStyles.Any),
|
||||
Description = importModel.Description,
|
||||
Cost = decimal.Parse(importModel.Cost, NumberStyles.Any),
|
||||
Notes = importModel.Notes,
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_supplyRecordDataAccess.SaveSupplyRecordToVehicle(convertedRecord);
|
||||
}
|
||||
else if (mode == ImportMode.TaxRecord)
|
||||
{
|
||||
var convertedRecord = new TaxRecord()
|
||||
{
|
||||
VehicleId = vehicleId,
|
||||
Date = parsedDate,
|
||||
Description = string.IsNullOrWhiteSpace(importModel.Description) ? $"Tax Record on {parsedDate.ToShortDateString()}" : importModel.Description,
|
||||
Notes = string.IsNullOrWhiteSpace(importModel.Notes) ? "" : importModel.Notes,
|
||||
Cost = decimal.Parse(importModel.Cost, NumberStyles.Any),
|
||||
Tags = string.IsNullOrWhiteSpace(importModel.Tags) ? [] : importModel.Tags.Split(" ").ToList(),
|
||||
ExtraFields = importModel.ExtraFields.Any() ? importModel.ExtraFields.Select(x => new ExtraField { Name = x.Key, Value = x.Value, IsRequired = requiredExtraFields.Contains(x.Key) }).ToList() : new List<ExtraField>()
|
||||
};
|
||||
_taxRecordDataAccess.SaveTaxRecordToVehicle(convertedRecord);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Json(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error Occurred While Bulk Inserting");
|
||||
return Json(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
100
Controllers/Vehicle/NoteController.cs
Normal file
100
Controllers/Vehicle/NoteController.cs
Normal file
@@ -0,0 +1,100 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetNotesByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _noteDataAccess.GetNotesByVehicleId(vehicleId);
|
||||
result = result.OrderByDescending(x => x.Pinned).ThenBy(x => x.Description).ToList();
|
||||
return PartialView("_Notes", result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetPinnedNotesByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _noteDataAccess.GetNotesByVehicleId(vehicleId);
|
||||
result = result.Where(x => x.Pinned).ToList();
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveNoteToVehicleId(Note note)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), note.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
note.Files = note.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
bool isCreate = note.Id == default; //needed here since Notes don't use an input object.
|
||||
var result = _noteDataAccess.SaveNoteToVehicle(note);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromNoteRecord(note, isCreate ? "noterecord.add" : "noterecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddNotePartialView()
|
||||
{
|
||||
return PartialView("_NoteModal", new Note());
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetNoteForEditById(int noteId)
|
||||
{
|
||||
var result = _noteDataAccess.GetNoteById(noteId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
return PartialView("_NoteModal", result);
|
||||
}
|
||||
private bool DeleteNoteWithChecks(int noteId)
|
||||
{
|
||||
var existingRecord = _noteDataAccess.GetNoteById(noteId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var result = _noteDataAccess.DeleteNoteById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromNoteRecord(existingRecord, "noterecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteNoteById(int noteId)
|
||||
{
|
||||
var result = DeleteNoteWithChecks(noteId);
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult PinNotes(List<int> noteIds, bool isToggle = false, bool pinStatus = false)
|
||||
{
|
||||
var result = false;
|
||||
foreach (int noteId in noteIds)
|
||||
{
|
||||
var existingNote = _noteDataAccess.GetNoteById(noteId);
|
||||
if (isToggle)
|
||||
{
|
||||
existingNote.Pinned = !existingNote.Pinned;
|
||||
}
|
||||
else
|
||||
{
|
||||
existingNote.Pinned = pinStatus;
|
||||
}
|
||||
result = _noteDataAccess.SaveNoteToVehicle(existingNote);
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
176
Controllers/Vehicle/OdometerController.cs
Normal file
176
Controllers/Vehicle/OdometerController.cs
Normal file
@@ -0,0 +1,176 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult ForceRecalculateDistanceByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId);
|
||||
result = _odometerLogic.AutoConvertOdometerRecord(result);
|
||||
return Json(result.Any());
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetOdometerRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId);
|
||||
//determine if conversion is needed.
|
||||
if (result.All(x => x.InitialMileage == default))
|
||||
{
|
||||
result = _odometerLogic.AutoConvertOdometerRecord(result);
|
||||
}
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ThenByDescending(x => x.Mileage).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ThenBy(x => x.Mileage).ToList();
|
||||
}
|
||||
return PartialView("_OdometerRecords", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveOdometerRecordToVehicleId(OdometerRecordInput odometerRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), odometerRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
//move files from temp.
|
||||
odometerRecord.Files = odometerRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
var result = _odometerRecordDataAccess.SaveOdometerRecordToVehicle(odometerRecord.ToOdometerRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromOdometerRecord(odometerRecord.ToOdometerRecord(), odometerRecord.Id == default ? "odometerrecord.add" : "odometerrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetAddOdometerRecordPartialView(int vehicleId)
|
||||
{
|
||||
return PartialView("_OdometerRecordModal", new OdometerRecordInput() { InitialMileage = _odometerLogic.GetLastOdometerRecordMileage(vehicleId, new List<OdometerRecord>()), ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.OdometerRecord).ExtraFields });
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult GetOdometerRecordsEditModal(List<int> recordIds)
|
||||
{
|
||||
var extraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.OdometerRecord).ExtraFields;
|
||||
return PartialView("_OdometerRecordsModal", new OdometerRecordEditModel { RecordIds = recordIds, EditRecord = new OdometerRecord { ExtraFields = extraFields } });
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveMultipleOdometerRecords(OdometerRecordEditModel editModel)
|
||||
{
|
||||
var dateIsEdited = editModel.EditRecord.Date != default;
|
||||
var initialMileageIsEdited = editModel.EditRecord.InitialMileage != default;
|
||||
var mileageIsEdited = editModel.EditRecord.Mileage != default;
|
||||
var noteIsEdited = !string.IsNullOrWhiteSpace(editModel.EditRecord.Notes);
|
||||
var tagsIsEdited = editModel.EditRecord.Tags.Any();
|
||||
var extraFieldIsEdited = editModel.EditRecord.ExtraFields.Any();
|
||||
//handle clear overrides
|
||||
if (tagsIsEdited && editModel.EditRecord.Tags.Contains("---"))
|
||||
{
|
||||
editModel.EditRecord.Tags = new List<string>();
|
||||
}
|
||||
if (noteIsEdited && editModel.EditRecord.Notes == "---")
|
||||
{
|
||||
editModel.EditRecord.Notes = "";
|
||||
}
|
||||
bool result = false;
|
||||
foreach (int recordId in editModel.RecordIds)
|
||||
{
|
||||
var existingRecord = _odometerRecordDataAccess.GetOdometerRecordById(recordId);
|
||||
if (dateIsEdited)
|
||||
{
|
||||
existingRecord.Date = editModel.EditRecord.Date;
|
||||
}
|
||||
if (initialMileageIsEdited)
|
||||
{
|
||||
existingRecord.InitialMileage = editModel.EditRecord.InitialMileage;
|
||||
}
|
||||
if (mileageIsEdited)
|
||||
{
|
||||
existingRecord.Mileage = editModel.EditRecord.Mileage;
|
||||
}
|
||||
if (noteIsEdited)
|
||||
{
|
||||
existingRecord.Notes = editModel.EditRecord.Notes;
|
||||
}
|
||||
if (tagsIsEdited)
|
||||
{
|
||||
existingRecord.Tags = editModel.EditRecord.Tags;
|
||||
}
|
||||
if (extraFieldIsEdited)
|
||||
{
|
||||
foreach (ExtraField extraField in editModel.EditRecord.ExtraFields)
|
||||
{
|
||||
if (existingRecord.ExtraFields.Any(x => x.Name == extraField.Name))
|
||||
{
|
||||
var insertIndex = existingRecord.ExtraFields.FindIndex(x => x.Name == extraField.Name);
|
||||
existingRecord.ExtraFields.RemoveAll(x => x.Name == extraField.Name);
|
||||
existingRecord.ExtraFields.Insert(insertIndex, extraField);
|
||||
}
|
||||
else
|
||||
{
|
||||
existingRecord.ExtraFields.Add(extraField);
|
||||
}
|
||||
}
|
||||
}
|
||||
result = _odometerRecordDataAccess.SaveOdometerRecordToVehicle(existingRecord);
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetOdometerRecordForEditById(int odometerRecordId)
|
||||
{
|
||||
var result = _odometerRecordDataAccess.GetOdometerRecordById(odometerRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new OdometerRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
InitialMileage = result.InitialMileage,
|
||||
Mileage = result.Mileage,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Files = result.Files,
|
||||
Tags = result.Tags,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.OdometerRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_OdometerRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteOdometerRecordWithChecks(int odometerRecordId)
|
||||
{
|
||||
var existingRecord = _odometerRecordDataAccess.GetOdometerRecordById(odometerRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var result = _odometerRecordDataAccess.DeleteOdometerRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromOdometerRecord(existingRecord, "odometerrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteOdometerRecordById(int odometerRecordId)
|
||||
{
|
||||
var result = DeleteOdometerRecordWithChecks(odometerRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
324
Controllers/Vehicle/PlanController.cs
Normal file
324
Controllers/Vehicle/PlanController.cs
Normal file
@@ -0,0 +1,324 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetPlanRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _planRecordDataAccess.GetPlanRecordsByVehicleId(vehicleId);
|
||||
return PartialView("_PlanRecords", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SavePlanRecordToVehicleId(PlanRecordInput planRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), planRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
//populate createdDate
|
||||
if (planRecord.Id == default)
|
||||
{
|
||||
planRecord.DateCreated = DateTime.Now.ToString("G");
|
||||
}
|
||||
planRecord.DateModified = DateTime.Now.ToString("G");
|
||||
//move files from temp.
|
||||
planRecord.Files = planRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
if (planRecord.Supplies.Any())
|
||||
{
|
||||
planRecord.RequisitionHistory.AddRange(RequisitionSupplyRecordsByUsage(planRecord.Supplies, DateTime.Parse(planRecord.DateCreated), planRecord.Description));
|
||||
if (planRecord.CopySuppliesAttachment)
|
||||
{
|
||||
planRecord.Files.AddRange(GetSuppliesAttachments(planRecord.Supplies));
|
||||
}
|
||||
}
|
||||
if (planRecord.DeletedRequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(planRecord.DeletedRequisitionHistory, planRecord.Description);
|
||||
}
|
||||
var result = _planRecordDataAccess.SavePlanRecordToVehicle(planRecord.ToPlanRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromPlanRecord(planRecord.ToPlanRecord(), planRecord.Id == default ? "planrecord.add" : "planrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SavePlanRecordTemplateToVehicleId(PlanRecordInput planRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), planRecord.VehicleId))
|
||||
{
|
||||
return Json(OperationResponse.Failed("Access Denied"));
|
||||
}
|
||||
//check if template name already taken.
|
||||
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplatesByVehicleId(planRecord.VehicleId).Where(x => x.Description == planRecord.Description).Any();
|
||||
if (planRecord.Id == default && existingRecord)
|
||||
{
|
||||
return Json(OperationResponse.Failed("A template with that description already exists for this vehicle"));
|
||||
}
|
||||
planRecord.Files = planRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
var result = _planRecordTemplateDataAccess.SavePlanRecordTemplateToVehicle(planRecord);
|
||||
return Json(OperationResponse.Conditional(result, "Template Added", string.Empty));
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetPlanRecordTemplatesForVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _planRecordTemplateDataAccess.GetPlanRecordTemplatesByVehicleId(vehicleId);
|
||||
return PartialView("_PlanRecordTemplateModal", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeletePlanRecordTemplateById(int planRecordTemplateId)
|
||||
{
|
||||
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
|
||||
if (existingRecord.Id == default)
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
var result = _planRecordTemplateDataAccess.DeletePlanRecordTemplateById(planRecordTemplateId);
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult OrderPlanSupplies(int planRecordTemplateId)
|
||||
{
|
||||
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
|
||||
if (existingRecord.Id == default)
|
||||
{
|
||||
return Json(OperationResponse.Failed("Unable to find template"));
|
||||
}
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return Json(OperationResponse.Failed("Access Denied"));
|
||||
}
|
||||
if (existingRecord.Supplies.Any())
|
||||
{
|
||||
var suppliesToOrder = CheckSupplyRecordsAvailability(existingRecord.Supplies);
|
||||
return PartialView("_PlanOrderSupplies", suppliesToOrder);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Json(OperationResponse.Failed("Template has No Supplies"));
|
||||
}
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult ConvertPlanRecordTemplateToPlanRecord(int planRecordTemplateId)
|
||||
{
|
||||
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
|
||||
if (existingRecord.Id == default)
|
||||
{
|
||||
return Json(OperationResponse.Failed("Unable to find template"));
|
||||
}
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return Json(OperationResponse.Failed("Access Denied"));
|
||||
}
|
||||
if (existingRecord.Supplies.Any())
|
||||
{
|
||||
//check if all supplies are available
|
||||
var supplyAvailability = CheckSupplyRecordsAvailability(existingRecord.Supplies);
|
||||
if (supplyAvailability.Any(x => x.Missing))
|
||||
{
|
||||
return Json(OperationResponse.Failed("Missing Supplies, Please Delete This Template and Recreate It."));
|
||||
}
|
||||
else if (supplyAvailability.Any(x => x.Insufficient))
|
||||
{
|
||||
return Json(OperationResponse.Failed("Insufficient Supplies"));
|
||||
}
|
||||
}
|
||||
if (existingRecord.ReminderRecordId != default)
|
||||
{
|
||||
//check if reminder still exists and is still recurring.
|
||||
var existingReminder = _reminderRecordDataAccess.GetReminderRecordById(existingRecord.ReminderRecordId);
|
||||
if (existingReminder is null || existingReminder.Id == default || !existingReminder.IsRecurring)
|
||||
{
|
||||
return Json(OperationResponse.Failed("Missing or Non-recurring Reminder, Please Delete This Template and Recreate It."));
|
||||
}
|
||||
}
|
||||
//populate createdDate
|
||||
existingRecord.DateCreated = DateTime.Now.ToString("G");
|
||||
existingRecord.DateModified = DateTime.Now.ToString("G");
|
||||
existingRecord.Id = default;
|
||||
if (existingRecord.Supplies.Any())
|
||||
{
|
||||
existingRecord.RequisitionHistory = RequisitionSupplyRecordsByUsage(existingRecord.Supplies, DateTime.Parse(existingRecord.DateCreated), existingRecord.Description);
|
||||
if (existingRecord.CopySuppliesAttachment)
|
||||
{
|
||||
existingRecord.Files.AddRange(GetSuppliesAttachments(existingRecord.Supplies));
|
||||
}
|
||||
}
|
||||
var result = _planRecordDataAccess.SavePlanRecordToVehicle(existingRecord.ToPlanRecord());
|
||||
return Json(OperationResponse.Conditional(result, "Plan Record Added", string.Empty));
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddPlanRecordPartialView()
|
||||
{
|
||||
return PartialView("_PlanRecordModal", new PlanRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.PlanRecord).ExtraFields });
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult GetAddPlanRecordPartialView(PlanRecordInput? planModel)
|
||||
{
|
||||
if (planModel is not null)
|
||||
{
|
||||
planModel.ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.PlanRecord).ExtraFields;
|
||||
return PartialView("_PlanRecordModal", planModel);
|
||||
}
|
||||
return PartialView("_PlanRecordModal", new PlanRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.PlanRecord).ExtraFields });
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult UpdatePlanRecordProgress(int planRecordId, PlanProgress planProgress, int odometer = 0)
|
||||
{
|
||||
if (planRecordId == default)
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
var existingRecord = _planRecordDataAccess.GetPlanRecordById(planRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
existingRecord.Progress = planProgress;
|
||||
existingRecord.DateModified = DateTime.Now;
|
||||
var result = _planRecordDataAccess.SavePlanRecordToVehicle(existingRecord);
|
||||
if (planProgress == PlanProgress.Done)
|
||||
{
|
||||
if (_config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = DateTime.Now.Date,
|
||||
VehicleId = existingRecord.VehicleId,
|
||||
Mileage = odometer,
|
||||
Notes = $"Auto Insert From Plan Record: {existingRecord.Description}",
|
||||
ExtraFields = existingRecord.ExtraFields
|
||||
});
|
||||
}
|
||||
//convert plan record to service/upgrade/repair record.
|
||||
if (existingRecord.ImportMode == ImportMode.ServiceRecord)
|
||||
{
|
||||
var newRecord = new ServiceRecord()
|
||||
{
|
||||
VehicleId = existingRecord.VehicleId,
|
||||
Date = DateTime.Now.Date,
|
||||
Mileage = odometer,
|
||||
Description = existingRecord.Description,
|
||||
Cost = existingRecord.Cost,
|
||||
Notes = existingRecord.Notes,
|
||||
Files = existingRecord.Files,
|
||||
RequisitionHistory = existingRecord.RequisitionHistory,
|
||||
ExtraFields = existingRecord.ExtraFields
|
||||
};
|
||||
_serviceRecordDataAccess.SaveServiceRecordToVehicle(newRecord);
|
||||
}
|
||||
else if (existingRecord.ImportMode == ImportMode.RepairRecord)
|
||||
{
|
||||
var newRecord = new CollisionRecord()
|
||||
{
|
||||
VehicleId = existingRecord.VehicleId,
|
||||
Date = DateTime.Now.Date,
|
||||
Mileage = odometer,
|
||||
Description = existingRecord.Description,
|
||||
Cost = existingRecord.Cost,
|
||||
Notes = existingRecord.Notes,
|
||||
Files = existingRecord.Files,
|
||||
RequisitionHistory = existingRecord.RequisitionHistory,
|
||||
ExtraFields = existingRecord.ExtraFields
|
||||
};
|
||||
_collisionRecordDataAccess.SaveCollisionRecordToVehicle(newRecord);
|
||||
}
|
||||
else if (existingRecord.ImportMode == ImportMode.UpgradeRecord)
|
||||
{
|
||||
var newRecord = new UpgradeRecord()
|
||||
{
|
||||
VehicleId = existingRecord.VehicleId,
|
||||
Date = DateTime.Now.Date,
|
||||
Mileage = odometer,
|
||||
Description = existingRecord.Description,
|
||||
Cost = existingRecord.Cost,
|
||||
Notes = existingRecord.Notes,
|
||||
Files = existingRecord.Files,
|
||||
RequisitionHistory = existingRecord.RequisitionHistory,
|
||||
ExtraFields = existingRecord.ExtraFields
|
||||
};
|
||||
_upgradeRecordDataAccess.SaveUpgradeRecordToVehicle(newRecord);
|
||||
}
|
||||
//push back any reminders
|
||||
if (existingRecord.ReminderRecordId != default)
|
||||
{
|
||||
PushbackRecurringReminderRecordWithChecks(existingRecord.ReminderRecordId, DateTime.Now, odometer);
|
||||
}
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetPlanRecordTemplateForEditById(int planRecordTemplateId)
|
||||
{
|
||||
var result = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
|
||||
return PartialView("_PlanRecordTemplateEditModal", result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetPlanRecordForEditById(int planRecordId)
|
||||
{
|
||||
var result = _planRecordDataAccess.GetPlanRecordById(planRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new PlanRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Description = result.Description,
|
||||
DateCreated = result.DateCreated.ToString("G"),
|
||||
DateModified = result.DateModified.ToString("G"),
|
||||
ImportMode = result.ImportMode,
|
||||
Priority = result.Priority,
|
||||
Progress = result.Progress,
|
||||
Cost = result.Cost,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Files = result.Files,
|
||||
RequisitionHistory = result.RequisitionHistory,
|
||||
ReminderRecordId = result.ReminderRecordId,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.PlanRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_PlanRecordModal", convertedResult);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeletePlanRecordById(int planRecordId)
|
||||
{
|
||||
var existingRecord = _planRecordDataAccess.GetPlanRecordById(planRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
//restore any requisitioned supplies if it has not been converted to other record types.
|
||||
if (existingRecord.RequisitionHistory.Any() && existingRecord.Progress != PlanProgress.Done)
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(existingRecord.RequisitionHistory, existingRecord.Description);
|
||||
}
|
||||
var result = _planRecordDataAccess.DeletePlanRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromPlanRecord(existingRecord, "planrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
187
Controllers/Vehicle/ReminderController.cs
Normal file
187
Controllers/Vehicle/ReminderController.cs
Normal file
@@ -0,0 +1,187 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
private List<ReminderRecordViewModel> GetRemindersAndUrgency(int vehicleId, DateTime dateCompare)
|
||||
{
|
||||
var currentMileage = _vehicleLogic.GetMaxMileage(vehicleId);
|
||||
var reminders = _reminderRecordDataAccess.GetReminderRecordsByVehicleId(vehicleId);
|
||||
List<ReminderRecordViewModel> results = _reminderHelper.GetReminderRecordViewModels(reminders, currentMileage, dateCompare);
|
||||
return results;
|
||||
}
|
||||
private bool GetAndUpdateVehicleUrgentOrPastDueReminders(int vehicleId)
|
||||
{
|
||||
var result = GetRemindersAndUrgency(vehicleId, DateTime.Now);
|
||||
//check if user wants auto-refresh past-due reminders
|
||||
if (_config.GetUserConfig(User).EnableAutoReminderRefresh)
|
||||
{
|
||||
//check for past due reminders that are eligible for recurring.
|
||||
var pastDueAndRecurring = result.Where(x => x.Urgency == ReminderUrgency.PastDue && x.IsRecurring);
|
||||
if (pastDueAndRecurring.Any())
|
||||
{
|
||||
foreach (ReminderRecordViewModel reminderRecord in pastDueAndRecurring)
|
||||
{
|
||||
//update based on recurring intervals.
|
||||
//pull reminderRecord based on ID
|
||||
var existingReminder = _reminderRecordDataAccess.GetReminderRecordById(reminderRecord.Id);
|
||||
existingReminder = _reminderHelper.GetUpdatedRecurringReminderRecord(existingReminder, null, null);
|
||||
//save to db.
|
||||
_reminderRecordDataAccess.SaveReminderRecordToVehicle(existingReminder);
|
||||
//set urgency to not urgent so it gets excluded in count.
|
||||
reminderRecord.Urgency = ReminderUrgency.NotUrgent;
|
||||
}
|
||||
}
|
||||
}
|
||||
//check for very urgent or past due reminders that were not eligible for recurring.
|
||||
var pastDueAndUrgentReminders = result.Where(x => x.Urgency == ReminderUrgency.VeryUrgent || x.Urgency == ReminderUrgency.PastDue);
|
||||
if (pastDueAndUrgentReminders.Any())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetVehicleHaveUrgentOrPastDueReminders(int vehicleId)
|
||||
{
|
||||
var result = GetAndUpdateVehicleUrgentOrPastDueReminders(vehicleId);
|
||||
return Json(result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetReminderRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = GetRemindersAndUrgency(vehicleId, DateTime.Now);
|
||||
result = result.OrderByDescending(x => x.Urgency).ToList();
|
||||
return PartialView("_ReminderRecords", result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetRecurringReminderRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = GetRemindersAndUrgency(vehicleId, DateTime.Now);
|
||||
result.RemoveAll(x => !x.IsRecurring);
|
||||
result = result.OrderByDescending(x => x.Urgency).ThenBy(x => x.Description).ToList();
|
||||
return PartialView("_RecurringReminderSelector", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult PushbackRecurringReminderRecord(int reminderRecordId)
|
||||
{
|
||||
var result = PushbackRecurringReminderRecordWithChecks(reminderRecordId, null, null);
|
||||
return Json(result);
|
||||
}
|
||||
private bool PushbackRecurringReminderRecordWithChecks(int reminderRecordId, DateTime? currentDate, int? currentMileage)
|
||||
{
|
||||
try
|
||||
{
|
||||
var existingReminder = _reminderRecordDataAccess.GetReminderRecordById(reminderRecordId);
|
||||
if (existingReminder is not null && existingReminder.Id != default && existingReminder.IsRecurring)
|
||||
{
|
||||
existingReminder = _reminderHelper.GetUpdatedRecurringReminderRecord(existingReminder, currentDate, currentMileage);
|
||||
//save to db.
|
||||
var reminderUpdateResult = _reminderRecordDataAccess.SaveReminderRecordToVehicle(existingReminder);
|
||||
if (!reminderUpdateResult)
|
||||
{
|
||||
_logger.LogError("Unable to update reminder either because the reminder no longer exists or is no longer recurring");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError("Unable to update reminder because it no longer exists.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveReminderRecordToVehicleId(ReminderRecordInput reminderRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), reminderRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
var result = _reminderRecordDataAccess.SaveReminderRecordToVehicle(reminderRecord.ToReminderRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromReminderRecord(reminderRecord.ToReminderRecord(), reminderRecord.Id == default ? "reminderrecord.add" : "reminderrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult GetAddReminderRecordPartialView(ReminderRecordInput? reminderModel)
|
||||
{
|
||||
if (reminderModel is not null)
|
||||
{
|
||||
return PartialView("_ReminderRecordModal", reminderModel);
|
||||
}
|
||||
else
|
||||
{
|
||||
return PartialView("_ReminderRecordModal", new ReminderRecordInput());
|
||||
}
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetReminderRecordForEditById(int reminderRecordId)
|
||||
{
|
||||
var result = _reminderRecordDataAccess.GetReminderRecordById(reminderRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new ReminderRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Description = result.Description,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Mileage = result.Mileage,
|
||||
Metric = result.Metric,
|
||||
IsRecurring = result.IsRecurring,
|
||||
UseCustomThresholds = result.UseCustomThresholds,
|
||||
CustomThresholds = result.CustomThresholds,
|
||||
ReminderMileageInterval = result.ReminderMileageInterval,
|
||||
ReminderMonthInterval = result.ReminderMonthInterval,
|
||||
CustomMileageInterval = result.CustomMileageInterval,
|
||||
CustomMonthInterval = result.CustomMonthInterval,
|
||||
CustomMonthIntervalUnit = result.CustomMonthIntervalUnit,
|
||||
Tags = result.Tags
|
||||
};
|
||||
return PartialView("_ReminderRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteReminderRecordWithChecks(int reminderRecordId)
|
||||
{
|
||||
var existingRecord = _reminderRecordDataAccess.GetReminderRecordById(reminderRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var result = _reminderRecordDataAccess.DeleteReminderRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromReminderRecord(existingRecord, "reminderrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteReminderRecordById(int reminderRecordId)
|
||||
{
|
||||
var result = DeleteReminderRecordWithChecks(reminderRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
131
Controllers/Vehicle/RepairController.cs
Normal file
131
Controllers/Vehicle/RepairController.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetCollisionRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ThenByDescending(x => x.Mileage).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ThenBy(x => x.Mileage).ToList();
|
||||
}
|
||||
return PartialView("_CollisionRecords", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveCollisionRecordToVehicleId(CollisionRecordInput collisionRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), collisionRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
if (collisionRecord.Id == default && _config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = DateTime.Parse(collisionRecord.Date),
|
||||
VehicleId = collisionRecord.VehicleId,
|
||||
Mileage = collisionRecord.Mileage,
|
||||
Notes = $"Auto Insert From Repair Record: {collisionRecord.Description}"
|
||||
});
|
||||
}
|
||||
//move files from temp.
|
||||
collisionRecord.Files = collisionRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
if (collisionRecord.Supplies.Any())
|
||||
{
|
||||
collisionRecord.RequisitionHistory.AddRange(RequisitionSupplyRecordsByUsage(collisionRecord.Supplies, DateTime.Parse(collisionRecord.Date), collisionRecord.Description));
|
||||
if (collisionRecord.CopySuppliesAttachment)
|
||||
{
|
||||
collisionRecord.Files.AddRange(GetSuppliesAttachments(collisionRecord.Supplies));
|
||||
}
|
||||
}
|
||||
if (collisionRecord.DeletedRequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(collisionRecord.DeletedRequisitionHistory, collisionRecord.Description);
|
||||
}
|
||||
//push back any reminders
|
||||
if (collisionRecord.ReminderRecordId.Any())
|
||||
{
|
||||
foreach (int reminderRecordId in collisionRecord.ReminderRecordId)
|
||||
{
|
||||
PushbackRecurringReminderRecordWithChecks(reminderRecordId, DateTime.Parse(collisionRecord.Date), collisionRecord.Mileage);
|
||||
}
|
||||
}
|
||||
var result = _collisionRecordDataAccess.SaveCollisionRecordToVehicle(collisionRecord.ToCollisionRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGenericRecord(collisionRecord.ToCollisionRecord(), collisionRecord.Id == default ? "repairrecord.add" : "repairrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddCollisionRecordPartialView()
|
||||
{
|
||||
return PartialView("_CollisionRecordModal", new CollisionRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.RepairRecord).ExtraFields });
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetCollisionRecordForEditById(int collisionRecordId)
|
||||
{
|
||||
var result = _collisionRecordDataAccess.GetCollisionRecordById(collisionRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new CollisionRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Cost = result.Cost,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Description = result.Description,
|
||||
Mileage = result.Mileage,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Files = result.Files,
|
||||
Tags = result.Tags,
|
||||
RequisitionHistory = result.RequisitionHistory,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.RepairRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_CollisionRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteCollisionRecordWithChecks(int collisionRecordId)
|
||||
{
|
||||
var existingRecord = _collisionRecordDataAccess.GetCollisionRecordById(collisionRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
//restore any requisitioned supplies.
|
||||
if (existingRecord.RequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(existingRecord.RequisitionHistory, existingRecord.Description);
|
||||
}
|
||||
var result = _collisionRecordDataAccess.DeleteCollisionRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGenericRecord(existingRecord, "repairrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteCollisionRecordById(int collisionRecordId)
|
||||
{
|
||||
var result = DeleteCollisionRecordWithChecks(collisionRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
734
Controllers/Vehicle/ReportController.cs
Normal file
734
Controllers/Vehicle/ReportController.cs
Normal file
@@ -0,0 +1,734 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Globalization;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetReportPartialView(int vehicleId)
|
||||
{
|
||||
//get records
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var vehicleRecords = _vehicleLogic.GetVehicleRecords(vehicleId);
|
||||
var serviceRecords = vehicleRecords.ServiceRecords;
|
||||
var gasRecords = vehicleRecords.GasRecords;
|
||||
var collisionRecords = vehicleRecords.CollisionRecords;
|
||||
var taxRecords = vehicleRecords.TaxRecords;
|
||||
var upgradeRecords = vehicleRecords.UpgradeRecords;
|
||||
var odometerRecords = vehicleRecords.OdometerRecords;
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
var viewModel = new ReportViewModel() { ReportHeaderForVehicle = new ReportHeader() };
|
||||
//check if custom widgets are configured
|
||||
viewModel.CustomWidgetsConfigured = _fileHelper.WidgetsExist();
|
||||
//get totalCostMakeUp
|
||||
viewModel.CostMakeUpForVehicle = new CostMakeUpForVehicle
|
||||
{
|
||||
ServiceRecordSum = serviceRecords.Sum(x => x.Cost),
|
||||
GasRecordSum = gasRecords.Sum(x => x.Cost),
|
||||
CollisionRecordSum = collisionRecords.Sum(x => x.Cost),
|
||||
TaxRecordSum = taxRecords.Sum(x => x.Cost),
|
||||
UpgradeRecordSum = upgradeRecords.Sum(x => x.Cost)
|
||||
};
|
||||
//get costbymonth
|
||||
List<CostForVehicleByMonth> allCosts = StaticHelper.GetBaseLineCosts();
|
||||
allCosts.AddRange(_reportHelper.GetServiceRecordSum(serviceRecords, 0));
|
||||
allCosts.AddRange(_reportHelper.GetRepairRecordSum(collisionRecords, 0));
|
||||
allCosts.AddRange(_reportHelper.GetUpgradeRecordSum(upgradeRecords, 0));
|
||||
allCosts.AddRange(_reportHelper.GetGasRecordSum(gasRecords, 0));
|
||||
allCosts.AddRange(_reportHelper.GetTaxRecordSum(taxRecords, 0));
|
||||
allCosts.AddRange(_reportHelper.GetOdometerRecordSum(odometerRecords, 0));
|
||||
viewModel.CostForVehicleByMonth = allCosts.GroupBy(x => new { x.MonthName, x.MonthId }).OrderBy(x => x.Key.MonthId).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthName = x.Key.MonthName,
|
||||
Cost = x.Sum(y => y.Cost),
|
||||
DistanceTraveled = x.Max(y => y.DistanceTraveled)
|
||||
}).ToList();
|
||||
//get reminders
|
||||
var reminders = GetRemindersAndUrgency(vehicleId, DateTime.Now);
|
||||
viewModel.ReminderMakeUpForVehicle = new ReminderMakeUpForVehicle
|
||||
{
|
||||
NotUrgentCount = reminders.Where(x => x.Urgency == ReminderUrgency.NotUrgent).Count(),
|
||||
UrgentCount = reminders.Where(x => x.Urgency == ReminderUrgency.Urgent).Count(),
|
||||
VeryUrgentCount = reminders.Where(x => x.Urgency == ReminderUrgency.VeryUrgent).Count(),
|
||||
PastDueCount = reminders.Where(x => x.Urgency == ReminderUrgency.PastDue).Count()
|
||||
};
|
||||
//populate year dropdown.
|
||||
var numbersArray = new List<int>();
|
||||
if (serviceRecords.Any())
|
||||
{
|
||||
numbersArray.Add(serviceRecords.Min(x => x.Date.Year));
|
||||
}
|
||||
if (collisionRecords.Any())
|
||||
{
|
||||
numbersArray.Add(collisionRecords.Min(x => x.Date.Year));
|
||||
}
|
||||
if (gasRecords.Any())
|
||||
{
|
||||
numbersArray.Add(gasRecords.Min(x => x.Date.Year));
|
||||
}
|
||||
if (upgradeRecords.Any())
|
||||
{
|
||||
numbersArray.Add(upgradeRecords.Min(x => x.Date.Year));
|
||||
}
|
||||
if (odometerRecords.Any())
|
||||
{
|
||||
numbersArray.Add(odometerRecords.Min(x => x.Date.Year));
|
||||
}
|
||||
var minYear = numbersArray.Any() ? numbersArray.Min() : DateTime.Now.AddYears(-5).Year;
|
||||
var yearDifference = DateTime.Now.Year - minYear + 1;
|
||||
for (int i = 0; i < yearDifference; i++)
|
||||
{
|
||||
viewModel.Years.Add(DateTime.Now.AddYears(i * -1).Year);
|
||||
}
|
||||
//get collaborators
|
||||
var collaborators = _userLogic.GetCollaboratorsForVehicle(vehicleId);
|
||||
viewModel.Collaborators = collaborators;
|
||||
//get MPG per month.
|
||||
var mileageData = _gasHelper.GetGasRecordViewModels(gasRecords, userConfig.UseMPG, userConfig.UseUKMPG);
|
||||
string preferredFuelMileageUnit = _config.GetUserConfig(User).PreferredGasMileageUnit;
|
||||
var fuelEconomyMileageUnit = StaticHelper.GetFuelEconomyUnit(vehicleData.IsElectric, vehicleData.UseHours, userConfig.UseMPG, userConfig.UseUKMPG);
|
||||
var averageMPG = _gasHelper.GetAverageGasMileage(mileageData, userConfig.UseMPG);
|
||||
mileageData.RemoveAll(x => x.MilesPerGallon == default);
|
||||
bool invertedFuelMileageUnit = fuelEconomyMileageUnit == "l/100km" && preferredFuelMileageUnit == "km/l";
|
||||
var monthlyMileageData = StaticHelper.GetBaseLineCostsNoMonthName();
|
||||
monthlyMileageData.AddRange(mileageData.GroupBy(x => x.MonthId).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
Cost = x.Average(y => y.MilesPerGallon)
|
||||
}));
|
||||
monthlyMileageData = monthlyMileageData.GroupBy(x => x.MonthId).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
}).ToList();
|
||||
if (invertedFuelMileageUnit)
|
||||
{
|
||||
foreach (CostForVehicleByMonth monthMileage in monthlyMileageData)
|
||||
{
|
||||
if (monthMileage.Cost != default)
|
||||
{
|
||||
monthMileage.Cost = 100 / monthMileage.Cost;
|
||||
}
|
||||
}
|
||||
var newAverageMPG = decimal.Parse(averageMPG, NumberStyles.Any);
|
||||
if (newAverageMPG != 0)
|
||||
{
|
||||
newAverageMPG = 100 / newAverageMPG;
|
||||
}
|
||||
averageMPG = newAverageMPG.ToString("F");
|
||||
}
|
||||
var mpgViewModel = new MPGForVehicleByMonth {
|
||||
CostData = monthlyMileageData,
|
||||
Unit = invertedFuelMileageUnit ? preferredFuelMileageUnit : fuelEconomyMileageUnit,
|
||||
SortedCostData = (userConfig.UseMPG || invertedFuelMileageUnit) ? monthlyMileageData.OrderByDescending(x => x.Cost).ToList() : monthlyMileageData.OrderBy(x => x.Cost).ToList()
|
||||
};
|
||||
viewModel.FuelMileageForVehicleByMonth = mpgViewModel;
|
||||
//report header
|
||||
|
||||
var maxMileage = _vehicleLogic.GetMaxMileage(vehicleRecords);
|
||||
var minMileage = _vehicleLogic.GetMinMileage(vehicleRecords);
|
||||
|
||||
viewModel.ReportHeaderForVehicle.TotalCost = _vehicleLogic.GetVehicleTotalCost(vehicleRecords);
|
||||
viewModel.ReportHeaderForVehicle.AverageMPG = $"{averageMPG} {mpgViewModel.Unit}";
|
||||
viewModel.ReportHeaderForVehicle.MaxOdometer = maxMileage;
|
||||
viewModel.ReportHeaderForVehicle.DistanceTraveled = maxMileage - minMileage;
|
||||
return PartialView("_Report", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetCollaboratorsForVehicle(int vehicleId)
|
||||
{
|
||||
var result = _userLogic.GetCollaboratorsForVehicle(vehicleId);
|
||||
return PartialView("_Collaborators", result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult AddCollaboratorsToVehicle(int vehicleId, string username)
|
||||
{
|
||||
var result = _userLogic.AddCollaboratorToVehicle(vehicleId, username);
|
||||
return Json(result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult DeleteCollaboratorFromVehicle(int userId, int vehicleId)
|
||||
{
|
||||
var result = _userLogic.DeleteCollaboratorFromVehicle(userId, vehicleId);
|
||||
return Json(result);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult GetSummaryForVehicle(int vehicleId, int year = 0)
|
||||
{
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var vehicleRecords = _vehicleLogic.GetVehicleRecords(vehicleId);
|
||||
|
||||
var serviceRecords = vehicleRecords.ServiceRecords;
|
||||
var gasRecords = vehicleRecords.GasRecords;
|
||||
var collisionRecords = vehicleRecords.CollisionRecords;
|
||||
var taxRecords = vehicleRecords.TaxRecords;
|
||||
var upgradeRecords = vehicleRecords.UpgradeRecords;
|
||||
var odometerRecords = vehicleRecords.OdometerRecords;
|
||||
|
||||
if (year != default)
|
||||
{
|
||||
serviceRecords.RemoveAll(x => x.Date.Year != year);
|
||||
gasRecords.RemoveAll(x => x.Date.Year != year);
|
||||
collisionRecords.RemoveAll(x => x.Date.Year != year);
|
||||
taxRecords.RemoveAll(x => x.Date.Year != year);
|
||||
upgradeRecords.RemoveAll(x => x.Date.Year != year);
|
||||
odometerRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
|
||||
var mileageData = _gasHelper.GetGasRecordViewModels(gasRecords, userConfig.UseMPG, userConfig.UseUKMPG);
|
||||
string preferredFuelMileageUnit = _config.GetUserConfig(User).PreferredGasMileageUnit;
|
||||
var fuelEconomyMileageUnit = StaticHelper.GetFuelEconomyUnit(vehicleData.IsElectric, vehicleData.UseHours, userConfig.UseMPG, userConfig.UseUKMPG);
|
||||
var averageMPG = _gasHelper.GetAverageGasMileage(mileageData, userConfig.UseMPG);
|
||||
bool invertedFuelMileageUnit = fuelEconomyMileageUnit == "l/100km" && preferredFuelMileageUnit == "km/l";
|
||||
|
||||
if (invertedFuelMileageUnit)
|
||||
{
|
||||
var newAverageMPG = decimal.Parse(averageMPG, NumberStyles.Any);
|
||||
if (newAverageMPG != 0)
|
||||
{
|
||||
newAverageMPG = 100 / newAverageMPG;
|
||||
}
|
||||
averageMPG = newAverageMPG.ToString("F");
|
||||
}
|
||||
|
||||
var mpgUnit = invertedFuelMileageUnit ? preferredFuelMileageUnit : fuelEconomyMileageUnit;
|
||||
|
||||
var maxMileage = _vehicleLogic.GetMaxMileage(vehicleRecords);
|
||||
var minMileage = _vehicleLogic.GetMinMileage(vehicleRecords);
|
||||
|
||||
var viewModel = new ReportHeader()
|
||||
{
|
||||
TotalCost = _vehicleLogic.GetVehicleTotalCost(vehicleRecords),
|
||||
AverageMPG = $"{averageMPG} {mpgUnit}",
|
||||
MaxOdometer = maxMileage,
|
||||
DistanceTraveled = maxMileage - minMileage
|
||||
};
|
||||
|
||||
return PartialView("_ReportHeader", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetCostMakeUpForVehicle(int vehicleId, int year = 0)
|
||||
{
|
||||
var serviceRecords = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId);
|
||||
var gasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId);
|
||||
var collisionRecords = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId);
|
||||
var taxRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId);
|
||||
var upgradeRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId);
|
||||
if (year != default)
|
||||
{
|
||||
serviceRecords.RemoveAll(x => x.Date.Year != year);
|
||||
gasRecords.RemoveAll(x => x.Date.Year != year);
|
||||
collisionRecords.RemoveAll(x => x.Date.Year != year);
|
||||
taxRecords.RemoveAll(x => x.Date.Year != year);
|
||||
upgradeRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
var viewModel = new CostMakeUpForVehicle
|
||||
{
|
||||
ServiceRecordSum = serviceRecords.Sum(x => x.Cost),
|
||||
GasRecordSum = gasRecords.Sum(x => x.Cost),
|
||||
CollisionRecordSum = collisionRecords.Sum(x => x.Cost),
|
||||
TaxRecordSum = taxRecords.Sum(x => x.Cost),
|
||||
UpgradeRecordSum = upgradeRecords.Sum(x => x.Cost)
|
||||
};
|
||||
return PartialView("_CostMakeUpReport", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetCostTableForVehicle(int vehicleId, int year = 0)
|
||||
{
|
||||
var vehicleRecords = _vehicleLogic.GetVehicleRecords(vehicleId);
|
||||
var serviceRecords = vehicleRecords.ServiceRecords;
|
||||
var gasRecords = vehicleRecords.GasRecords;
|
||||
var collisionRecords = vehicleRecords.CollisionRecords;
|
||||
var taxRecords = vehicleRecords.TaxRecords;
|
||||
var upgradeRecords = vehicleRecords.UpgradeRecords;
|
||||
var odometerRecords = vehicleRecords.OdometerRecords;
|
||||
if (year != default)
|
||||
{
|
||||
serviceRecords.RemoveAll(x => x.Date.Year != year);
|
||||
gasRecords.RemoveAll(x => x.Date.Year != year);
|
||||
collisionRecords.RemoveAll(x => x.Date.Year != year);
|
||||
taxRecords.RemoveAll(x => x.Date.Year != year);
|
||||
upgradeRecords.RemoveAll(x => x.Date.Year != year);
|
||||
odometerRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
var maxMileage = _vehicleLogic.GetMaxMileage(vehicleRecords);
|
||||
var minMileage = _vehicleLogic.GetMinMileage(vehicleRecords);
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
var totalDistanceTraveled = maxMileage - minMileage;
|
||||
var totalDays = _vehicleLogic.GetOwnershipDays(vehicleData.PurchaseDate, vehicleData.SoldDate, year, serviceRecords, collisionRecords, gasRecords, upgradeRecords, odometerRecords, taxRecords);
|
||||
var viewModel = new CostTableForVehicle
|
||||
{
|
||||
ServiceRecordSum = serviceRecords.Sum(x => x.Cost),
|
||||
GasRecordSum = gasRecords.Sum(x => x.Cost),
|
||||
CollisionRecordSum = collisionRecords.Sum(x => x.Cost),
|
||||
TaxRecordSum = taxRecords.Sum(x => x.Cost),
|
||||
UpgradeRecordSum = upgradeRecords.Sum(x => x.Cost),
|
||||
TotalDistance = totalDistanceTraveled,
|
||||
DistanceUnit = vehicleData.UseHours ? "Cost Per Hour" : userConfig.UseMPG ? "Cost Per Mile" : "Cost Per Kilometer",
|
||||
NumberOfDays = totalDays
|
||||
};
|
||||
return PartialView("_CostTableReport", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
public IActionResult GetReminderMakeUpByVehicle(int vehicleId, int daysToAdd)
|
||||
{
|
||||
var reminders = GetRemindersAndUrgency(vehicleId, DateTime.Now.AddDays(daysToAdd));
|
||||
var viewModel = new ReminderMakeUpForVehicle
|
||||
{
|
||||
NotUrgentCount = reminders.Where(x => x.Urgency == ReminderUrgency.NotUrgent).Count(),
|
||||
UrgentCount = reminders.Where(x => x.Urgency == ReminderUrgency.Urgent).Count(),
|
||||
VeryUrgentCount = reminders.Where(x => x.Urgency == ReminderUrgency.VeryUrgent).Count(),
|
||||
PastDueCount = reminders.Where(x => x.Urgency == ReminderUrgency.PastDue).Count()
|
||||
};
|
||||
return PartialView("_ReminderMakeUpReport", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult GetVehicleAttachments(int vehicleId, List<ImportMode> exportTabs)
|
||||
{
|
||||
List<GenericReportModel> attachmentData = new List<GenericReportModel>();
|
||||
if (exportTabs.Contains(ImportMode.ServiceRecord))
|
||||
{
|
||||
var records = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.ServiceRecord,
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (exportTabs.Contains(ImportMode.RepairRecord))
|
||||
{
|
||||
var records = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.RepairRecord,
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (exportTabs.Contains(ImportMode.UpgradeRecord))
|
||||
{
|
||||
var records = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.UpgradeRecord,
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (exportTabs.Contains(ImportMode.GasRecord))
|
||||
{
|
||||
var records = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.GasRecord,
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (exportTabs.Contains(ImportMode.TaxRecord))
|
||||
{
|
||||
var records = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.TaxRecord,
|
||||
Date = x.Date,
|
||||
Odometer = 0,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (exportTabs.Contains(ImportMode.OdometerRecord))
|
||||
{
|
||||
var records = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.OdometerRecord,
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (exportTabs.Contains(ImportMode.NoteRecord))
|
||||
{
|
||||
var records = _noteDataAccess.GetNotesByVehicleId(vehicleId).Where(x => x.Files.Any());
|
||||
attachmentData.AddRange(records.Select(x => new GenericReportModel
|
||||
{
|
||||
DataType = ImportMode.NoteRecord,
|
||||
Date = DateTime.Now,
|
||||
Odometer = 0,
|
||||
Files = x.Files
|
||||
}));
|
||||
}
|
||||
if (attachmentData.Any())
|
||||
{
|
||||
attachmentData = attachmentData.OrderBy(x => x.Date).ThenBy(x => x.Odometer).ToList();
|
||||
var result = _fileHelper.MakeAttachmentsExport(attachmentData);
|
||||
if (string.IsNullOrWhiteSpace(result))
|
||||
{
|
||||
return Json(OperationResponse.Failed());
|
||||
}
|
||||
return Json(OperationResponse.Succeed(result));
|
||||
}
|
||||
else
|
||||
{
|
||||
return Json(OperationResponse.Failed("No Attachments Found"));
|
||||
}
|
||||
}
|
||||
public IActionResult GetReportParameters()
|
||||
{
|
||||
var viewModel = new ReportParameter() {
|
||||
VisibleColumns = new List<string> {
|
||||
nameof(GenericReportModel.DataType),
|
||||
nameof(GenericReportModel.Date),
|
||||
nameof(GenericReportModel.Odometer),
|
||||
nameof(GenericReportModel.Description),
|
||||
nameof(GenericReportModel.Cost),
|
||||
nameof(GenericReportModel.Notes)
|
||||
}
|
||||
};
|
||||
//get all extra fields from service records, repairs, upgrades, and tax records.
|
||||
var recordTypes = new List<int>() { 0, 1, 3, 4 };
|
||||
var extraFields = new List<string>();
|
||||
foreach(int recordType in recordTypes)
|
||||
{
|
||||
extraFields.AddRange(_extraFieldDataAccess.GetExtraFieldsById(recordType).ExtraFields.Select(x => x.Name));
|
||||
}
|
||||
viewModel.ExtraFields = extraFields.Distinct().ToList();
|
||||
|
||||
return PartialView("_ReportParameters", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
public IActionResult GetVehicleHistory(int vehicleId, ReportParameter reportParameter)
|
||||
{
|
||||
var vehicleHistory = new VehicleHistoryViewModel();
|
||||
vehicleHistory.ReportParameters = reportParameter;
|
||||
vehicleHistory.VehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var vehicleRecords = _vehicleLogic.GetVehicleRecords(vehicleId);
|
||||
bool useMPG = _config.GetUserConfig(User).UseMPG;
|
||||
bool useUKMPG = _config.GetUserConfig(User).UseUKMPG;
|
||||
var gasViewModels = _gasHelper.GetGasRecordViewModels(vehicleRecords.GasRecords, useMPG, useUKMPG);
|
||||
//filter by tags
|
||||
if (reportParameter.Tags.Any())
|
||||
{
|
||||
if (reportParameter.TagFilter == TagFilter.Exclude)
|
||||
{
|
||||
vehicleRecords.OdometerRecords.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.ServiceRecords.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.CollisionRecords.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.UpgradeRecords.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.TaxRecords.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
gasViewModels.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.GasRecords.RemoveAll(x => x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
}
|
||||
else if (reportParameter.TagFilter == TagFilter.IncludeOnly)
|
||||
{
|
||||
vehicleRecords.OdometerRecords.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.ServiceRecords.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.CollisionRecords.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.UpgradeRecords.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.TaxRecords.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
gasViewModels.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
vehicleRecords.GasRecords.RemoveAll(x => !x.Tags.Any(y => reportParameter.Tags.Contains(y)));
|
||||
}
|
||||
}
|
||||
//filter by date range.
|
||||
if (reportParameter.FilterByDateRange && !string.IsNullOrWhiteSpace(reportParameter.StartDate) && !string.IsNullOrWhiteSpace(reportParameter.EndDate))
|
||||
{
|
||||
var startDate = DateTime.Parse(reportParameter.StartDate).Date;
|
||||
var endDate = DateTime.Parse(reportParameter.EndDate).Date;
|
||||
//validate date range
|
||||
if (endDate >= startDate) //allow for same day.
|
||||
{
|
||||
vehicleHistory.StartDate = reportParameter.StartDate;
|
||||
vehicleHistory.EndDate = reportParameter.EndDate;
|
||||
//remove all records with dates after the end date and dates before the start date.
|
||||
vehicleRecords.OdometerRecords.RemoveAll(x => x.Date.Date > endDate || x.Date.Date < startDate);
|
||||
vehicleRecords.ServiceRecords.RemoveAll(x => x.Date.Date > endDate || x.Date.Date < startDate);
|
||||
vehicleRecords.CollisionRecords.RemoveAll(x => x.Date.Date > endDate || x.Date.Date < startDate);
|
||||
vehicleRecords.UpgradeRecords.RemoveAll(x => x.Date.Date > endDate || x.Date.Date < startDate);
|
||||
vehicleRecords.TaxRecords.RemoveAll(x => x.Date.Date > endDate || x.Date.Date < startDate);
|
||||
gasViewModels.RemoveAll(x => DateTime.Parse(x.Date).Date > endDate || DateTime.Parse(x.Date).Date < startDate);
|
||||
vehicleRecords.GasRecords.RemoveAll(x => x.Date.Date > endDate || x.Date.Date < startDate);
|
||||
}
|
||||
}
|
||||
var maxMileage = _vehicleLogic.GetMaxMileage(vehicleRecords);
|
||||
vehicleHistory.Odometer = maxMileage.ToString("N0");
|
||||
var minMileage = _vehicleLogic.GetMinMileage(vehicleRecords);
|
||||
var distanceTraveled = maxMileage - minMileage;
|
||||
if (!string.IsNullOrWhiteSpace(vehicleHistory.VehicleData.PurchaseDate))
|
||||
{
|
||||
var endDate = vehicleHistory.VehicleData.SoldDate;
|
||||
int daysOwned = 0;
|
||||
if (string.IsNullOrWhiteSpace(endDate))
|
||||
{
|
||||
endDate = DateTime.Now.ToShortDateString();
|
||||
}
|
||||
try
|
||||
{
|
||||
daysOwned = (DateTime.Parse(endDate) - DateTime.Parse(vehicleHistory.VehicleData.PurchaseDate)).Days;
|
||||
vehicleHistory.DaysOwned = daysOwned.ToString("N0");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
vehicleHistory.DaysOwned = string.Empty;
|
||||
}
|
||||
//calculate depreciation
|
||||
var totalDepreciation = vehicleHistory.VehicleData.PurchasePrice - vehicleHistory.VehicleData.SoldPrice;
|
||||
//we only calculate depreciation if a sold price is provided.
|
||||
if (totalDepreciation != default && vehicleHistory.VehicleData.SoldPrice != default)
|
||||
{
|
||||
vehicleHistory.TotalDepreciation = totalDepreciation;
|
||||
if (daysOwned != default)
|
||||
{
|
||||
vehicleHistory.DepreciationPerDay = Math.Abs(totalDepreciation / daysOwned);
|
||||
}
|
||||
if (distanceTraveled != default)
|
||||
{
|
||||
vehicleHistory.DepreciationPerMile = Math.Abs(totalDepreciation / distanceTraveled);
|
||||
}
|
||||
}
|
||||
}
|
||||
List<GenericReportModel> reportData = new List<GenericReportModel>();
|
||||
string preferredFuelMileageUnit = _config.GetUserConfig(User).PreferredGasMileageUnit;
|
||||
vehicleHistory.DistanceUnit = vehicleHistory.VehicleData.UseHours ? "h" : useMPG ? "mi." : "km";
|
||||
vehicleHistory.TotalGasCost = gasViewModels.Sum(x => x.Cost);
|
||||
vehicleHistory.TotalCost = vehicleRecords.ServiceRecords.Sum(x => x.Cost) + vehicleRecords.CollisionRecords.Sum(x => x.Cost) + vehicleRecords.UpgradeRecords.Sum(x => x.Cost) + vehicleRecords.TaxRecords.Sum(x => x.Cost);
|
||||
if (distanceTraveled != default)
|
||||
{
|
||||
vehicleHistory.DistanceTraveled = distanceTraveled.ToString("N0");
|
||||
vehicleHistory.TotalCostPerMile = vehicleHistory.TotalCost / distanceTraveled;
|
||||
vehicleHistory.TotalGasCostPerMile = vehicleHistory.TotalGasCost / distanceTraveled;
|
||||
}
|
||||
var averageMPG = "0";
|
||||
if (gasViewModels.Any())
|
||||
{
|
||||
averageMPG = _gasHelper.GetAverageGasMileage(gasViewModels, useMPG);
|
||||
}
|
||||
var fuelEconomyMileageUnit = StaticHelper.GetFuelEconomyUnit(vehicleHistory.VehicleData.IsElectric, vehicleHistory.VehicleData.UseHours, useMPG, useUKMPG);
|
||||
if (fuelEconomyMileageUnit == "l/100km" && preferredFuelMileageUnit == "km/l")
|
||||
{
|
||||
//conversion needed.
|
||||
var newAverageMPG = decimal.Parse(averageMPG, NumberStyles.Any);
|
||||
if (newAverageMPG != 0)
|
||||
{
|
||||
newAverageMPG = 100 / newAverageMPG;
|
||||
}
|
||||
averageMPG = newAverageMPG.ToString("F");
|
||||
fuelEconomyMileageUnit = preferredFuelMileageUnit;
|
||||
}
|
||||
vehicleHistory.MPG = $"{averageMPG} {fuelEconomyMileageUnit}";
|
||||
//insert servicerecords
|
||||
reportData.AddRange(vehicleRecords.ServiceRecords.Select(x => new GenericReportModel
|
||||
{
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Description = x.Description,
|
||||
Notes = x.Notes,
|
||||
Cost = x.Cost,
|
||||
DataType = ImportMode.ServiceRecord,
|
||||
ExtraFields = x.ExtraFields,
|
||||
RequisitionHistory = x.RequisitionHistory
|
||||
}));
|
||||
//repair records
|
||||
reportData.AddRange(vehicleRecords.CollisionRecords.Select(x => new GenericReportModel
|
||||
{
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Description = x.Description,
|
||||
Notes = x.Notes,
|
||||
Cost = x.Cost,
|
||||
DataType = ImportMode.RepairRecord,
|
||||
ExtraFields = x.ExtraFields,
|
||||
RequisitionHistory = x.RequisitionHistory
|
||||
}));
|
||||
reportData.AddRange(vehicleRecords.UpgradeRecords.Select(x => new GenericReportModel
|
||||
{
|
||||
Date = x.Date,
|
||||
Odometer = x.Mileage,
|
||||
Description = x.Description,
|
||||
Notes = x.Notes,
|
||||
Cost = x.Cost,
|
||||
DataType = ImportMode.UpgradeRecord,
|
||||
ExtraFields = x.ExtraFields,
|
||||
RequisitionHistory = x.RequisitionHistory
|
||||
}));
|
||||
reportData.AddRange(vehicleRecords.TaxRecords.Select(x => new GenericReportModel
|
||||
{
|
||||
Date = x.Date,
|
||||
Odometer = 0,
|
||||
Description = x.Description,
|
||||
Notes = x.Notes,
|
||||
Cost = x.Cost,
|
||||
DataType = ImportMode.TaxRecord,
|
||||
ExtraFields = x.ExtraFields
|
||||
}));
|
||||
vehicleHistory.VehicleHistory = reportData.OrderBy(x => x.Date).ThenBy(x => x.Odometer).ToList();
|
||||
return PartialView("_VehicleHistory", vehicleHistory);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult GetMonthMPGByVehicle(int vehicleId, int year = 0)
|
||||
{
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var gasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId);
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
string preferredFuelMileageUnit = _config.GetUserConfig(User).PreferredGasMileageUnit;
|
||||
var fuelEconomyMileageUnit = StaticHelper.GetFuelEconomyUnit(vehicleData.IsElectric, vehicleData.UseHours, userConfig.UseMPG, userConfig.UseUKMPG);
|
||||
bool invertedFuelMileageUnit = fuelEconomyMileageUnit == "l/100km" && preferredFuelMileageUnit == "km/l";
|
||||
var mileageData = _gasHelper.GetGasRecordViewModels(gasRecords, userConfig.UseMPG, userConfig.UseUKMPG);
|
||||
if (year != 0)
|
||||
{
|
||||
mileageData.RemoveAll(x => DateTime.Parse(x.Date).Year != year);
|
||||
}
|
||||
mileageData.RemoveAll(x => x.MilesPerGallon == default);
|
||||
var monthlyMileageData = StaticHelper.GetBaseLineCostsNoMonthName();
|
||||
monthlyMileageData.AddRange(mileageData.GroupBy(x => x.MonthId).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
Cost = x.Average(y => y.MilesPerGallon)
|
||||
}));
|
||||
monthlyMileageData = monthlyMileageData.GroupBy(x => x.MonthId).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
}).ToList();
|
||||
if (invertedFuelMileageUnit)
|
||||
{
|
||||
foreach (CostForVehicleByMonth monthMileage in monthlyMileageData)
|
||||
{
|
||||
if (monthMileage.Cost != default)
|
||||
{
|
||||
monthMileage.Cost = 100 / monthMileage.Cost;
|
||||
}
|
||||
}
|
||||
}
|
||||
var mpgViewModel = new MPGForVehicleByMonth
|
||||
{
|
||||
CostData = monthlyMileageData,
|
||||
Unit = invertedFuelMileageUnit ? preferredFuelMileageUnit : fuelEconomyMileageUnit,
|
||||
SortedCostData = (userConfig.UseMPG || invertedFuelMileageUnit) ? monthlyMileageData.OrderByDescending(x => x.Cost).ToList() : monthlyMileageData.OrderBy(x => x.Cost).ToList()
|
||||
};
|
||||
return PartialView("_MPGByMonthReport", mpgViewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult GetCostByMonthByVehicle(int vehicleId, List<ImportMode> selectedMetrics, int year = 0)
|
||||
{
|
||||
List<CostForVehicleByMonth> allCosts = StaticHelper.GetBaseLineCosts();
|
||||
if (selectedMetrics.Contains(ImportMode.ServiceRecord))
|
||||
{
|
||||
var serviceRecords = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetServiceRecordSum(serviceRecords, year));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.RepairRecord))
|
||||
{
|
||||
var repairRecords = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetRepairRecordSum(repairRecords, year));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.UpgradeRecord))
|
||||
{
|
||||
var upgradeRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetUpgradeRecordSum(upgradeRecords, year));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.GasRecord))
|
||||
{
|
||||
var gasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetGasRecordSum(gasRecords, year));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.TaxRecord))
|
||||
{
|
||||
var taxRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetTaxRecordSum(taxRecords, year));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.OdometerRecord))
|
||||
{
|
||||
var odometerRecords = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetOdometerRecordSum(odometerRecords, year));
|
||||
}
|
||||
var groupedRecord = allCosts.GroupBy(x => new { x.MonthName, x.MonthId }).OrderBy(x => x.Key.MonthId).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthName = x.Key.MonthName,
|
||||
Cost = x.Sum(y => y.Cost),
|
||||
DistanceTraveled = x.Max(y => y.DistanceTraveled)
|
||||
}).ToList();
|
||||
return PartialView("_GasCostByMonthReport", groupedRecord);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult GetCostByMonthAndYearByVehicle(int vehicleId, List<ImportMode> selectedMetrics, int year = 0)
|
||||
{
|
||||
List<CostForVehicleByMonth> allCosts = StaticHelper.GetBaseLineCosts();
|
||||
if (selectedMetrics.Contains(ImportMode.ServiceRecord))
|
||||
{
|
||||
var serviceRecords = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetServiceRecordSum(serviceRecords, year, true));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.RepairRecord))
|
||||
{
|
||||
var repairRecords = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetRepairRecordSum(repairRecords, year, true));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.UpgradeRecord))
|
||||
{
|
||||
var upgradeRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetUpgradeRecordSum(upgradeRecords, year, true));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.GasRecord))
|
||||
{
|
||||
var gasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetGasRecordSum(gasRecords, year, true));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.TaxRecord))
|
||||
{
|
||||
var taxRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetTaxRecordSum(taxRecords, year, true));
|
||||
}
|
||||
if (selectedMetrics.Contains(ImportMode.OdometerRecord))
|
||||
{
|
||||
var odometerRecords = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId);
|
||||
allCosts.AddRange(_reportHelper.GetOdometerRecordSum(odometerRecords, year, true));
|
||||
}
|
||||
var groupedRecord = allCosts.GroupBy(x => new { x.MonthName, x.MonthId, x.Year }).OrderByDescending(x=>x.Key.Year).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
Year = x.Key.Year,
|
||||
MonthName = x.Key.MonthName,
|
||||
Cost = x.Sum(y => y.Cost),
|
||||
DistanceTraveled = x.Max(y => y.DistanceTraveled),
|
||||
MonthId = x.Key.MonthId
|
||||
}).ToList();
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
var userConfig = _config.GetUserConfig(User);
|
||||
var viewModel = new CostDistanceTableForVehicle { CostData = groupedRecord };
|
||||
viewModel.DistanceUnit = vehicleData.UseHours ? "h" : userConfig.UseMPG ? "mi." : "km";
|
||||
return PartialView("_CostDistanceTableReport", viewModel);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAdditionalWidgets()
|
||||
{
|
||||
var widgets = _fileHelper.GetWidgets();
|
||||
return PartialView("_ReportWidgets", widgets);
|
||||
}
|
||||
}
|
||||
}
|
||||
131
Controllers/Vehicle/ServiceController.cs
Normal file
131
Controllers/Vehicle/ServiceController.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetServiceRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ThenByDescending(x => x.Mileage).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ThenBy(x => x.Mileage).ToList();
|
||||
}
|
||||
return PartialView("_ServiceRecords", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveServiceRecordToVehicleId(ServiceRecordInput serviceRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), serviceRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
if (serviceRecord.Id == default && _config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = DateTime.Parse(serviceRecord.Date),
|
||||
VehicleId = serviceRecord.VehicleId,
|
||||
Mileage = serviceRecord.Mileage,
|
||||
Notes = $"Auto Insert From Service Record: {serviceRecord.Description}"
|
||||
});
|
||||
}
|
||||
//move files from temp.
|
||||
serviceRecord.Files = serviceRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
if (serviceRecord.Supplies.Any())
|
||||
{
|
||||
serviceRecord.RequisitionHistory.AddRange(RequisitionSupplyRecordsByUsage(serviceRecord.Supplies, DateTime.Parse(serviceRecord.Date), serviceRecord.Description));
|
||||
if (serviceRecord.CopySuppliesAttachment)
|
||||
{
|
||||
serviceRecord.Files.AddRange(GetSuppliesAttachments(serviceRecord.Supplies));
|
||||
}
|
||||
}
|
||||
if (serviceRecord.DeletedRequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(serviceRecord.DeletedRequisitionHistory, serviceRecord.Description);
|
||||
}
|
||||
//push back any reminders
|
||||
if (serviceRecord.ReminderRecordId.Any())
|
||||
{
|
||||
foreach (int reminderRecordId in serviceRecord.ReminderRecordId)
|
||||
{
|
||||
PushbackRecurringReminderRecordWithChecks(reminderRecordId, DateTime.Parse(serviceRecord.Date), serviceRecord.Mileage);
|
||||
}
|
||||
}
|
||||
var result = _serviceRecordDataAccess.SaveServiceRecordToVehicle(serviceRecord.ToServiceRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGenericRecord(serviceRecord.ToServiceRecord(), serviceRecord.Id == default ? "servicerecord.add" : "servicerecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddServiceRecordPartialView()
|
||||
{
|
||||
return PartialView("_ServiceRecordModal", new ServiceRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.ServiceRecord).ExtraFields });
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetServiceRecordForEditById(int serviceRecordId)
|
||||
{
|
||||
var result = _serviceRecordDataAccess.GetServiceRecordById(serviceRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new ServiceRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Cost = result.Cost,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Description = result.Description,
|
||||
Mileage = result.Mileage,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Files = result.Files,
|
||||
Tags = result.Tags,
|
||||
RequisitionHistory = result.RequisitionHistory,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.ServiceRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_ServiceRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteServiceRecordWithChecks(int serviceRecordId)
|
||||
{
|
||||
var existingRecord = _serviceRecordDataAccess.GetServiceRecordById(serviceRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
//restore any requisitioned supplies.
|
||||
if (existingRecord.RequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(existingRecord.RequisitionHistory, existingRecord.Description);
|
||||
}
|
||||
var result = _serviceRecordDataAccess.DeleteServiceRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGenericRecord(existingRecord, "servicerecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteServiceRecordById(int serviceRecordId)
|
||||
{
|
||||
var result = DeleteServiceRecordWithChecks(serviceRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
215
Controllers/Vehicle/SupplyController.cs
Normal file
215
Controllers/Vehicle/SupplyController.cs
Normal file
@@ -0,0 +1,215 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
private List<SupplyAvailability> CheckSupplyRecordsAvailability(List<SupplyUsage> supplyUsage)
|
||||
{
|
||||
//returns empty string if all supplies are available
|
||||
var result = new List<SupplyAvailability>();
|
||||
foreach (SupplyUsage supply in supplyUsage)
|
||||
{
|
||||
//get supply record.
|
||||
var supplyData = _supplyRecordDataAccess.GetSupplyRecordById(supply.SupplyId);
|
||||
if (supplyData == null)
|
||||
{
|
||||
result.Add(new SupplyAvailability { Missing = true });
|
||||
}
|
||||
else
|
||||
{
|
||||
result.Add(new SupplyAvailability { Missing = false, Description = supplyData.Description, Required = supply.Quantity, InStock = supplyData.Quantity });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
private List<UploadedFiles> GetSuppliesAttachments(List<SupplyUsage> supplyUsage)
|
||||
{
|
||||
List<UploadedFiles> results = new List<UploadedFiles>();
|
||||
foreach (SupplyUsage supply in supplyUsage)
|
||||
{
|
||||
var result = _supplyRecordDataAccess.GetSupplyRecordById(supply.SupplyId);
|
||||
results.AddRange(result.Files);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
private List<SupplyUsageHistory> RequisitionSupplyRecordsByUsage(List<SupplyUsage> supplyUsage, DateTime dateRequisitioned, string usageDescription)
|
||||
{
|
||||
List<SupplyUsageHistory> results = new List<SupplyUsageHistory>();
|
||||
foreach (SupplyUsage supply in supplyUsage)
|
||||
{
|
||||
//get supply record.
|
||||
var result = _supplyRecordDataAccess.GetSupplyRecordById(supply.SupplyId);
|
||||
var unitCost = (result.Quantity != 0) ? result.Cost / result.Quantity : 0;
|
||||
//deduct quantity used.
|
||||
result.Quantity -= supply.Quantity;
|
||||
//deduct cost.
|
||||
result.Cost -= (supply.Quantity * unitCost);
|
||||
//check decimal places to ensure that it always has a max of 3 decimal places.
|
||||
var roundedDecimal = decimal.Round(result.Cost, 3);
|
||||
if (roundedDecimal != result.Cost)
|
||||
{
|
||||
//Too many decimals
|
||||
result.Cost = roundedDecimal;
|
||||
}
|
||||
//create new requisitionrrecord
|
||||
var requisitionRecord = new SupplyUsageHistory
|
||||
{
|
||||
Id = supply.SupplyId,
|
||||
Date = dateRequisitioned,
|
||||
Description = usageDescription,
|
||||
Quantity = supply.Quantity,
|
||||
Cost = (supply.Quantity * unitCost)
|
||||
};
|
||||
result.RequisitionHistory.Add(requisitionRecord);
|
||||
//save
|
||||
_supplyRecordDataAccess.SaveSupplyRecordToVehicle(result);
|
||||
requisitionRecord.Description = result.Description; //change the name of the description for plan/service/repair/upgrade records
|
||||
requisitionRecord.PartNumber = result.PartNumber; //populate part number if not displayed in supplies modal.
|
||||
results.Add(requisitionRecord);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetSupplyRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _supplyRecordDataAccess.GetSupplyRecordsByVehicleId(vehicleId);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ToList();
|
||||
}
|
||||
return PartialView("_SupplyRecords", result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetSupplyRecordsForPlanRecordTemplate(int planRecordTemplateId)
|
||||
{
|
||||
var viewModel = new SupplyUsageViewModel();
|
||||
var planRecordTemplate = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
|
||||
if (planRecordTemplate != default && planRecordTemplate.VehicleId != default)
|
||||
{
|
||||
var supplies = _supplyRecordDataAccess.GetSupplyRecordsByVehicleId(planRecordTemplate.VehicleId);
|
||||
if (_config.GetServerEnableShopSupplies())
|
||||
{
|
||||
supplies.AddRange(_supplyRecordDataAccess.GetSupplyRecordsByVehicleId(0)); // add shop supplies
|
||||
}
|
||||
supplies.RemoveAll(x => x.Quantity <= 0);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
supplies = supplies.OrderByDescending(x => x.Date).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
supplies = supplies.OrderBy(x => x.Date).ToList();
|
||||
}
|
||||
viewModel.Supplies = supplies;
|
||||
viewModel.Usage = planRecordTemplate.Supplies;
|
||||
}
|
||||
return PartialView("_SupplyUsage", viewModel);
|
||||
}
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetSupplyRecordsForRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _supplyRecordDataAccess.GetSupplyRecordsByVehicleId(vehicleId);
|
||||
if (_config.GetServerEnableShopSupplies())
|
||||
{
|
||||
result.AddRange(_supplyRecordDataAccess.GetSupplyRecordsByVehicleId(0)); // add shop supplies
|
||||
}
|
||||
result.RemoveAll(x => x.Quantity <= 0);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ToList();
|
||||
}
|
||||
var viewModel = new SupplyUsageViewModel
|
||||
{
|
||||
Supplies = result
|
||||
};
|
||||
return PartialView("_SupplyUsage", viewModel);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveSupplyRecordToVehicleId(SupplyRecordInput supplyRecord)
|
||||
{
|
||||
//move files from temp.
|
||||
supplyRecord.Files = supplyRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
var result = _supplyRecordDataAccess.SaveSupplyRecordToVehicle(supplyRecord.ToSupplyRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromSupplyRecord(supplyRecord.ToSupplyRecord(), supplyRecord.Id == default ? "supplyrecord.add" : "supplyrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddSupplyRecordPartialView()
|
||||
{
|
||||
return PartialView("_SupplyRecordModal", new SupplyRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.SupplyRecord).ExtraFields });
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetSupplyRecordForEditById(int supplyRecordId)
|
||||
{
|
||||
var result = _supplyRecordDataAccess.GetSupplyRecordById(supplyRecordId);
|
||||
if (result.RequisitionHistory.Any())
|
||||
{
|
||||
//requisition history when viewed through the supply is always immutable.
|
||||
result.RequisitionHistory = result.RequisitionHistory.Select(x => new SupplyUsageHistory { Id = default, Cost = x.Cost, Description = x.Description, Date = x.Date, PartNumber = x.PartNumber, Quantity = x.Quantity }).ToList();
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new SupplyRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Cost = result.Cost,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Description = result.Description,
|
||||
PartNumber = result.PartNumber,
|
||||
Quantity = result.Quantity,
|
||||
PartSupplier = result.PartSupplier,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Files = result.Files,
|
||||
Tags = result.Tags,
|
||||
RequisitionHistory = result.RequisitionHistory,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.SupplyRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_SupplyRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteSupplyRecordWithChecks(int supplyRecordId)
|
||||
{
|
||||
var existingRecord = _supplyRecordDataAccess.GetSupplyRecordById(supplyRecordId);
|
||||
if (existingRecord.VehicleId != default)
|
||||
{
|
||||
//security check only if not editing shop supply.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
var result = _supplyRecordDataAccess.DeleteSupplyRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromSupplyRecord(existingRecord, "supplyrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteSupplyRecordById(int supplyRecordId)
|
||||
{
|
||||
var result = DeleteSupplyRecordWithChecks(supplyRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
122
Controllers/Vehicle/TaxController.cs
Normal file
122
Controllers/Vehicle/TaxController.cs
Normal file
@@ -0,0 +1,122 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetTaxRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ToList();
|
||||
}
|
||||
return PartialView("_TaxRecords", result);
|
||||
}
|
||||
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpPost]
|
||||
public IActionResult CheckRecurringTaxRecords(int vehicleId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = _vehicleLogic.UpdateRecurringTaxes(vehicleId);
|
||||
return Json(result);
|
||||
} catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return Json(false);
|
||||
}
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveTaxRecordToVehicleId(TaxRecordInput taxRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), taxRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
//move files from temp.
|
||||
taxRecord.Files = taxRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
//push back any reminders
|
||||
if (taxRecord.ReminderRecordId.Any())
|
||||
{
|
||||
foreach (int reminderRecordId in taxRecord.ReminderRecordId)
|
||||
{
|
||||
PushbackRecurringReminderRecordWithChecks(reminderRecordId, DateTime.Parse(taxRecord.Date), null);
|
||||
}
|
||||
}
|
||||
var result = _taxRecordDataAccess.SaveTaxRecordToVehicle(taxRecord.ToTaxRecord());
|
||||
_vehicleLogic.UpdateRecurringTaxes(taxRecord.VehicleId);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromTaxRecord(taxRecord.ToTaxRecord(), taxRecord.Id == default ? "taxrecord.add" : "taxrecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddTaxRecordPartialView()
|
||||
{
|
||||
return PartialView("_TaxRecordModal", new TaxRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.TaxRecord).ExtraFields });
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetTaxRecordForEditById(int taxRecordId)
|
||||
{
|
||||
var result = _taxRecordDataAccess.GetTaxRecordById(taxRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new TaxRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Cost = result.Cost,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Description = result.Description,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
IsRecurring = result.IsRecurring,
|
||||
RecurringInterval = result.RecurringInterval,
|
||||
CustomMonthInterval = result.CustomMonthInterval,
|
||||
CustomMonthIntervalUnit = result.CustomMonthIntervalUnit,
|
||||
Files = result.Files,
|
||||
Tags = result.Tags,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.TaxRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_TaxRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteTaxRecordWithChecks(int taxRecordId)
|
||||
{
|
||||
var existingRecord = _taxRecordDataAccess.GetTaxRecordById(taxRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var result = _taxRecordDataAccess.DeleteTaxRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromTaxRecord(existingRecord, "taxrecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteTaxRecordById(int taxRecordId)
|
||||
{
|
||||
var result = DeleteTaxRecordWithChecks(taxRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
131
Controllers/Vehicle/UpgradeController.cs
Normal file
131
Controllers/Vehicle/UpgradeController.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using CarCareTracker.Filter;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace CarCareTracker.Controllers
|
||||
{
|
||||
public partial class VehicleController
|
||||
{
|
||||
[TypeFilter(typeof(CollaboratorFilter))]
|
||||
[HttpGet]
|
||||
public IActionResult GetUpgradeRecordsByVehicleId(int vehicleId)
|
||||
{
|
||||
var result = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId);
|
||||
bool _useDescending = _config.GetUserConfig(User).UseDescending;
|
||||
if (_useDescending)
|
||||
{
|
||||
result = result.OrderByDescending(x => x.Date).ThenByDescending(x => x.Mileage).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
result = result.OrderBy(x => x.Date).ThenBy(x => x.Mileage).ToList();
|
||||
}
|
||||
return PartialView("_UpgradeRecords", result);
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult SaveUpgradeRecordToVehicleId(UpgradeRecordInput upgradeRecord)
|
||||
{
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), upgradeRecord.VehicleId))
|
||||
{
|
||||
return Json(false);
|
||||
}
|
||||
if (upgradeRecord.Id == default && _config.GetUserConfig(User).EnableAutoOdometerInsert)
|
||||
{
|
||||
_odometerLogic.AutoInsertOdometerRecord(new OdometerRecord
|
||||
{
|
||||
Date = DateTime.Parse(upgradeRecord.Date),
|
||||
VehicleId = upgradeRecord.VehicleId,
|
||||
Mileage = upgradeRecord.Mileage,
|
||||
Notes = $"Auto Insert From Upgrade Record: {upgradeRecord.Description}"
|
||||
});
|
||||
}
|
||||
//move files from temp.
|
||||
upgradeRecord.Files = upgradeRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
|
||||
if (upgradeRecord.Supplies.Any())
|
||||
{
|
||||
upgradeRecord.RequisitionHistory.AddRange(RequisitionSupplyRecordsByUsage(upgradeRecord.Supplies, DateTime.Parse(upgradeRecord.Date), upgradeRecord.Description));
|
||||
if (upgradeRecord.CopySuppliesAttachment)
|
||||
{
|
||||
upgradeRecord.Files.AddRange(GetSuppliesAttachments(upgradeRecord.Supplies));
|
||||
}
|
||||
}
|
||||
if (upgradeRecord.DeletedRequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(upgradeRecord.DeletedRequisitionHistory, upgradeRecord.Description);
|
||||
}
|
||||
//push back any reminders
|
||||
if (upgradeRecord.ReminderRecordId.Any())
|
||||
{
|
||||
foreach (int reminderRecordId in upgradeRecord.ReminderRecordId)
|
||||
{
|
||||
PushbackRecurringReminderRecordWithChecks(reminderRecordId, DateTime.Parse(upgradeRecord.Date), upgradeRecord.Mileage);
|
||||
}
|
||||
}
|
||||
var result = _upgradeRecordDataAccess.SaveUpgradeRecordToVehicle(upgradeRecord.ToUpgradeRecord());
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGenericRecord(upgradeRecord.ToUpgradeRecord(), upgradeRecord.Id == default ? "upgraderecord.add" : "upgraderecord.update", User.Identity.Name));
|
||||
}
|
||||
return Json(result);
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetAddUpgradeRecordPartialView()
|
||||
{
|
||||
return PartialView("_UpgradeRecordModal", new UpgradeRecordInput() { ExtraFields = _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.UpgradeRecord).ExtraFields });
|
||||
}
|
||||
[HttpGet]
|
||||
public IActionResult GetUpgradeRecordForEditById(int upgradeRecordId)
|
||||
{
|
||||
var result = _upgradeRecordDataAccess.GetUpgradeRecordById(upgradeRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), result.VehicleId))
|
||||
{
|
||||
return Redirect("/Error/Unauthorized");
|
||||
}
|
||||
//convert to Input object.
|
||||
var convertedResult = new UpgradeRecordInput
|
||||
{
|
||||
Id = result.Id,
|
||||
Cost = result.Cost,
|
||||
Date = result.Date.ToShortDateString(),
|
||||
Description = result.Description,
|
||||
Mileage = result.Mileage,
|
||||
Notes = result.Notes,
|
||||
VehicleId = result.VehicleId,
|
||||
Files = result.Files,
|
||||
Tags = result.Tags,
|
||||
RequisitionHistory = result.RequisitionHistory,
|
||||
ExtraFields = StaticHelper.AddExtraFields(result.ExtraFields, _extraFieldDataAccess.GetExtraFieldsById((int)ImportMode.UpgradeRecord).ExtraFields)
|
||||
};
|
||||
return PartialView("_UpgradeRecordModal", convertedResult);
|
||||
}
|
||||
private bool DeleteUpgradeRecordWithChecks(int upgradeRecordId)
|
||||
{
|
||||
var existingRecord = _upgradeRecordDataAccess.GetUpgradeRecordById(upgradeRecordId);
|
||||
//security check.
|
||||
if (!_userLogic.UserCanEditVehicle(GetUserID(), existingRecord.VehicleId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
//restore any requisitioned supplies.
|
||||
if (existingRecord.RequisitionHistory.Any())
|
||||
{
|
||||
_vehicleLogic.RestoreSupplyRecordsByUsage(existingRecord.RequisitionHistory, existingRecord.Description);
|
||||
}
|
||||
var result = _upgradeRecordDataAccess.DeleteUpgradeRecordById(existingRecord.Id);
|
||||
if (result)
|
||||
{
|
||||
StaticHelper.NotifyAsync(_config.GetWebHookUrl(), WebHookPayload.FromGenericRecord(existingRecord, "upgraderecord.delete", User.Identity.Name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[HttpPost]
|
||||
public IActionResult DeleteUpgradeRecordById(int upgradeRecordId)
|
||||
{
|
||||
var result = DeleteUpgradeRecordWithChecks(upgradeRecordId);
|
||||
return Json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
9
Enum/DashboardMetric.cs
Normal file
9
Enum/DashboardMetric.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public enum DashboardMetric
|
||||
{
|
||||
Default = 0,
|
||||
TotalCost = 1,
|
||||
CostPerMile = 2
|
||||
}
|
||||
}
|
||||
12
Enum/ExtraFieldType.cs
Normal file
12
Enum/ExtraFieldType.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public enum ExtraFieldType
|
||||
{
|
||||
Text = 0,
|
||||
Number = 1,
|
||||
Decimal = 2,
|
||||
Date = 3,
|
||||
Time = 4,
|
||||
Location = 5
|
||||
}
|
||||
}
|
||||
10
Enum/KioskMode.cs
Normal file
10
Enum/KioskMode.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public enum KioskMode
|
||||
{
|
||||
Vehicle = 0,
|
||||
Plan = 1,
|
||||
Reminder = 2,
|
||||
Cycle = 3
|
||||
}
|
||||
}
|
||||
8
Enum/ReminderIntervalUnit.cs
Normal file
8
Enum/ReminderIntervalUnit.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public enum ReminderIntervalUnit
|
||||
{
|
||||
Months = 1,
|
||||
Days = 2
|
||||
}
|
||||
}
|
||||
8
Enum/TagFilter.cs
Normal file
8
Enum/TagFilter.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public enum TagFilter
|
||||
{
|
||||
Exclude = 0,
|
||||
IncludeOnly = 1
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using CarCareTracker.External.Interfaces;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using LiteDB;
|
||||
|
||||
namespace CarCareTracker.External.Implementations
|
||||
{
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using CarCareTracker.External.Interfaces;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using LiteDB;
|
||||
|
||||
namespace CarCareTracker.External.Implementations
|
||||
{
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -147,7 +147,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT primary key, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT primary key, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -141,7 +141,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
} catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -16,7 +16,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, body TEXT not null, emailaddress TEXT not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, body TEXT not null, emailaddress TEXT not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, vehicleId INT not null, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -146,7 +146,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using CarCareTracker.External.Interfaces;
|
||||
using CarCareTracker.Models;
|
||||
using Npgsql;
|
||||
using System.Net.Mail;
|
||||
|
||||
namespace CarCareTracker.External.Implementations
|
||||
{
|
||||
@@ -17,7 +16,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (userId INT, vehicleId INT, PRIMARY KEY(userId, vehicleId))";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (userId INT, vehicleId INT, PRIMARY KEY(userId, vehicleId))";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -176,7 +175,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("vehicleId", vehicleId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -198,7 +198,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("userId", userId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT primary key, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT primary key, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
@@ -94,7 +94,8 @@ namespace CarCareTracker.External.Implementations
|
||||
using (var ctext = pgDataSource.CreateCommand(cmd))
|
||||
{
|
||||
ctext.Parameters.AddWithValue("id", userId);
|
||||
return ctext.ExecuteNonQuery() > 0;
|
||||
ctext.ExecuteNonQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -16,7 +16,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, username TEXT not null, emailaddress TEXT not null, password TEXT not null, isadmin BOOLEAN)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, username TEXT not null, emailaddress TEXT not null, password TEXT not null, isadmin BOOLEAN)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace CarCareTracker.External.Implementations
|
||||
try
|
||||
{
|
||||
//create table if not exist.
|
||||
string initCMD = $"CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, data jsonb not null)";
|
||||
string initCMD = $"CREATE SCHEMA IF NOT EXISTS app; CREATE TABLE IF NOT EXISTS app.{tableName} (id INT GENERATED BY DEFAULT AS IDENTITY primary key, data jsonb not null)";
|
||||
using (var ctext = pgDataSource.CreateCommand(initCMD))
|
||||
{
|
||||
ctext.ExecuteNonQuery();
|
||||
|
||||
@@ -19,27 +19,34 @@ namespace CarCareTracker.Filter
|
||||
{
|
||||
if (!filterContext.HttpContext.User.IsInRole(nameof(UserData.IsRootUser)))
|
||||
{
|
||||
var vehicleId = int.Parse(filterContext.ActionArguments["vehicleId"].ToString());
|
||||
if (vehicleId != default)
|
||||
if (filterContext.ActionArguments.ContainsKey("vehicleId"))
|
||||
{
|
||||
var userId = int.Parse(filterContext.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
|
||||
if (!_userLogic.UserCanEditVehicle(userId, vehicleId))
|
||||
var vehicleId = int.Parse(filterContext.ActionArguments["vehicleId"].ToString());
|
||||
if (vehicleId != default)
|
||||
{
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
var userId = int.Parse(filterContext.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
|
||||
if (!_userLogic.UserCanEditVehicle(userId, vehicleId))
|
||||
{
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var shopSupplyEndpoints = new List<string> { "ImportToVehicleIdFromCsv", "GetSupplyRecordsByVehicleId", "ExportFromVehicleToCsv" };
|
||||
if (shopSupplyEndpoints.Contains(filterContext.RouteData.Values["action"].ToString()) && !_config.GetServerEnableShopSupplies())
|
||||
{
|
||||
//user trying to access shop supplies but shop supplies is not enabled by root user.
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
}
|
||||
else if (!shopSupplyEndpoints.Contains(filterContext.RouteData.Values["action"].ToString()))
|
||||
{
|
||||
//user trying to access any other endpoints using 0 as vehicle id.
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
}
|
||||
}
|
||||
} else
|
||||
{
|
||||
var shopSupplyEndpoints = new List<string> { "ImportToVehicleIdFromCsv", "GetSupplyRecordsByVehicleId", "ExportFromVehicleToCsv" };
|
||||
if (shopSupplyEndpoints.Contains(filterContext.RouteData.Values["action"].ToString()) && !_config.GetServerEnableShopSupplies())
|
||||
{
|
||||
//user trying to access shop supplies but shop supplies is not enabled by root user.
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
}
|
||||
else if (!shopSupplyEndpoints.Contains(filterContext.RouteData.Values["action"].ToString()))
|
||||
{
|
||||
//user trying to access any other endpoints using 0 as vehicle id.
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
}
|
||||
filterContext.Result = new RedirectResult("/Error/Unauthorized");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace CarCareTracker.Helper
|
||||
{
|
||||
@@ -9,49 +10,69 @@ namespace CarCareTracker.Helper
|
||||
{
|
||||
OpenIDConfig GetOpenIDConfig();
|
||||
ReminderUrgencyConfig GetReminderUrgencyConfig();
|
||||
MailConfig GetMailConfig();
|
||||
UserConfig GetUserConfig(ClaimsPrincipal user);
|
||||
bool SaveUserConfig(ClaimsPrincipal user, UserConfig configData);
|
||||
bool AuthenticateRootUser(string username, string password);
|
||||
bool AuthenticateRootUserOIDC(string email);
|
||||
string GetWebHookUrl();
|
||||
bool GetCustomWidgetsEnabled();
|
||||
string GetMOTD();
|
||||
string GetLogoUrl();
|
||||
string GetSmallLogoUrl();
|
||||
string GetServerLanguage();
|
||||
bool GetServerDisabledRegistration();
|
||||
bool GetServerEnableShopSupplies();
|
||||
string GetServerPostgresConnection();
|
||||
string GetAllowedFileUploadExtensions();
|
||||
public bool DeleteUserConfig(int userId);
|
||||
string GetServerDomain();
|
||||
bool DeleteUserConfig(int userId);
|
||||
bool GetInvariantApi();
|
||||
bool GetServerOpenRegistration();
|
||||
}
|
||||
public class ConfigHelper : IConfigHelper
|
||||
{
|
||||
private readonly IConfiguration _config;
|
||||
private readonly IUserConfigDataAccess _userConfig;
|
||||
private readonly ILogger<IConfigHelper> _logger;
|
||||
private IMemoryCache _cache;
|
||||
public ConfigHelper(IConfiguration serverConfig,
|
||||
IUserConfigDataAccess userConfig,
|
||||
IMemoryCache memoryCache)
|
||||
IMemoryCache memoryCache,
|
||||
ILogger<IConfigHelper> logger)
|
||||
{
|
||||
_config = serverConfig;
|
||||
_userConfig = userConfig;
|
||||
_cache = memoryCache;
|
||||
_logger = logger;
|
||||
}
|
||||
public string GetWebHookUrl()
|
||||
{
|
||||
var webhook = _config["LUBELOGGER_WEBHOOK"];
|
||||
if (string.IsNullOrWhiteSpace(webhook))
|
||||
{
|
||||
webhook = "";
|
||||
}
|
||||
var webhook = CheckString("LUBELOGGER_WEBHOOK");
|
||||
return webhook;
|
||||
}
|
||||
public bool GetCustomWidgetsEnabled()
|
||||
{
|
||||
return CheckBool(CheckString("LUBELOGGER_CUSTOM_WIDGETS"));
|
||||
}
|
||||
public bool GetInvariantApi()
|
||||
{
|
||||
return CheckBool(CheckString("LUBELOGGER_INVARIANT_API"));
|
||||
}
|
||||
public string GetMOTD()
|
||||
{
|
||||
var motd = _config["LUBELOGGER_MOTD"];
|
||||
if (string.IsNullOrWhiteSpace(motd))
|
||||
{
|
||||
motd = "";
|
||||
}
|
||||
var motd = CheckString("LUBELOGGER_MOTD");
|
||||
return motd;
|
||||
}
|
||||
public string GetServerDomain()
|
||||
{
|
||||
var domain = CheckString("LUBELOGGER_DOMAIN");
|
||||
return domain;
|
||||
}
|
||||
public bool GetServerOpenRegistration()
|
||||
{
|
||||
return CheckBool(CheckString("LUBELOGGER_OPEN_REGISTRATION"));
|
||||
}
|
||||
public OpenIDConfig GetOpenIDConfig()
|
||||
{
|
||||
OpenIDConfig openIdConfig = _config.GetSection("OpenIDConfig").Get<OpenIDConfig>() ?? new OpenIDConfig();
|
||||
@@ -62,51 +83,64 @@ namespace CarCareTracker.Helper
|
||||
ReminderUrgencyConfig reminderUrgencyConfig = _config.GetSection("ReminderUrgencyConfig").Get<ReminderUrgencyConfig>() ?? new ReminderUrgencyConfig();
|
||||
return reminderUrgencyConfig;
|
||||
}
|
||||
public MailConfig GetMailConfig()
|
||||
{
|
||||
MailConfig mailConfig = _config.GetSection("MailConfig").Get<MailConfig>() ?? new MailConfig();
|
||||
return mailConfig;
|
||||
}
|
||||
public string GetLogoUrl()
|
||||
{
|
||||
var logoUrl = _config["LUBELOGGER_LOGO_URL"];
|
||||
if (string.IsNullOrWhiteSpace(logoUrl))
|
||||
{
|
||||
logoUrl = "/defaults/lubelogger_logo.png";
|
||||
}
|
||||
var logoUrl = CheckString("LUBELOGGER_LOGO_URL", "/defaults/lubelogger_logo.png");
|
||||
return logoUrl;
|
||||
}
|
||||
public string GetSmallLogoUrl()
|
||||
{
|
||||
var logoUrl = CheckString("LUBELOGGER_LOGO_SMALL_URL", "/defaults/lubelogger_logo_small.png");
|
||||
return logoUrl;
|
||||
}
|
||||
public string GetAllowedFileUploadExtensions()
|
||||
{
|
||||
var allowedFileExtensions = _config["LUBELOGGER_ALLOWED_FILE_EXTENSIONS"];
|
||||
if (string.IsNullOrWhiteSpace(allowedFileExtensions)){
|
||||
return StaticHelper.DefaultAllowedFileExtensions;
|
||||
}
|
||||
var allowedFileExtensions = CheckString("LUBELOGGER_ALLOWED_FILE_EXTENSIONS", StaticHelper.DefaultAllowedFileExtensions);
|
||||
return allowedFileExtensions;
|
||||
}
|
||||
public bool AuthenticateRootUser(string username, string password)
|
||||
{
|
||||
var rootUsername = _config[nameof(UserConfig.UserNameHash)] ?? string.Empty;
|
||||
var rootPassword = _config[nameof(UserConfig.UserPasswordHash)] ?? string.Empty;
|
||||
var rootUsername = CheckString(nameof(UserConfig.UserNameHash));
|
||||
var rootPassword = CheckString(nameof(UserConfig.UserPasswordHash));
|
||||
if (string.IsNullOrWhiteSpace(rootUsername) || string.IsNullOrWhiteSpace(rootPassword))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return username == rootUsername && password == rootPassword;
|
||||
}
|
||||
public bool AuthenticateRootUserOIDC(string email)
|
||||
{
|
||||
var rootEmail = CheckString(nameof(UserConfig.DefaultReminderEmail));
|
||||
var rootUserOIDC = CheckBool(CheckString(nameof(UserConfig.EnableRootUserOIDC)));
|
||||
if (!rootUserOIDC || string.IsNullOrWhiteSpace(rootEmail))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return email == rootEmail;
|
||||
}
|
||||
public string GetServerLanguage()
|
||||
{
|
||||
var serverLanguage = _config[nameof(UserConfig.UserLanguage)] ?? "en_US";
|
||||
var serverLanguage = CheckString(nameof(UserConfig.UserLanguage), "en_US");
|
||||
return serverLanguage;
|
||||
}
|
||||
public bool GetServerDisabledRegistration()
|
||||
{
|
||||
var registrationDisabled = CheckBool(CheckString(nameof(UserConfig.DisableRegistration)));
|
||||
return registrationDisabled;
|
||||
}
|
||||
public string GetServerPostgresConnection()
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_config["POSTGRES_CONNECTION"]))
|
||||
{
|
||||
return _config["POSTGRES_CONNECTION"];
|
||||
} else
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
var postgresConnection = CheckString("POSTGRES_CONNECTION");
|
||||
return postgresConnection;
|
||||
}
|
||||
public bool GetServerEnableShopSupplies()
|
||||
{
|
||||
return bool.Parse(_config[nameof(UserConfig.EnableShopSupplies)] ?? "false");
|
||||
return CheckBool(CheckString(nameof(UserConfig.EnableShopSupplies)));
|
||||
}
|
||||
public bool SaveUserConfig(ClaimsPrincipal user, UserConfig configData)
|
||||
{
|
||||
@@ -124,18 +158,19 @@ namespace CarCareTracker.Helper
|
||||
if (!File.Exists(StaticHelper.UserConfigPath))
|
||||
{
|
||||
//if file doesn't exist it might be because it's running on a mounted volume in docker.
|
||||
File.WriteAllText(StaticHelper.UserConfigPath, System.Text.Json.JsonSerializer.Serialize(new UserConfig()));
|
||||
File.WriteAllText(StaticHelper.UserConfigPath, JsonSerializer.Serialize(new UserConfig()));
|
||||
}
|
||||
var configFileContents = File.ReadAllText(StaticHelper.UserConfigPath);
|
||||
configData.EnableAuth = bool.Parse(_config[nameof(UserConfig.EnableAuth)] ?? "false");
|
||||
configData.UserNameHash = _config[nameof(UserConfig.UserNameHash)] ?? string.Empty;
|
||||
configData.UserPasswordHash = _config[nameof(UserConfig.UserPasswordHash)] ?? string.Empty;
|
||||
File.WriteAllText(StaticHelper.UserConfigPath, System.Text.Json.JsonSerializer.Serialize(configData));
|
||||
File.WriteAllText(StaticHelper.UserConfigPath, JsonSerializer.Serialize(configData));
|
||||
_cache.Set<UserConfig>($"userConfig_{userId}", configData);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex.Message);
|
||||
return false;
|
||||
}
|
||||
} else
|
||||
@@ -156,31 +191,75 @@ namespace CarCareTracker.Helper
|
||||
var result = _userConfig.DeleteUserConfig(userId);
|
||||
return result;
|
||||
}
|
||||
private bool CheckBool(string value, bool defaultValue = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
else if (bool.TryParse(value, out bool result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
} catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning($"ConfigHelper Warning: You might be missing keys in appsettings.json, Message: ${ex.Message}");
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
private string CheckString(string configName, string defaultValue = "")
|
||||
{
|
||||
try
|
||||
{
|
||||
var configValue = _config[configName] ?? defaultValue;
|
||||
return configValue;
|
||||
} catch(Exception ex)
|
||||
{
|
||||
_logger.LogWarning($"ConfigHelper Warning: You might be missing keys in appsettings.json, Message: ${ex.Message}");
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
public UserConfig GetUserConfig(ClaimsPrincipal user)
|
||||
{
|
||||
var serverConfig = new UserConfig
|
||||
{
|
||||
EnableCsvImports = bool.Parse(_config[nameof(UserConfig.EnableCsvImports)]),
|
||||
UseDarkMode = bool.Parse(_config[nameof(UserConfig.UseDarkMode)]),
|
||||
UseMPG = bool.Parse(_config[nameof(UserConfig.UseMPG)]),
|
||||
UseDescending = bool.Parse(_config[nameof(UserConfig.UseDescending)]),
|
||||
EnableAuth = bool.Parse(_config[nameof(UserConfig.EnableAuth)]),
|
||||
HideZero = bool.Parse(_config[nameof(UserConfig.HideZero)]),
|
||||
UseUKMPG = bool.Parse(_config[nameof(UserConfig.UseUKMPG)]),
|
||||
UseMarkDownOnSavedNotes = bool.Parse(_config[nameof(UserConfig.UseMarkDownOnSavedNotes)]),
|
||||
UseThreeDecimalGasCost = bool.Parse(_config[nameof(UserConfig.UseThreeDecimalGasCost)]),
|
||||
EnableAutoReminderRefresh = bool.Parse(_config[nameof(UserConfig.EnableAutoReminderRefresh)]),
|
||||
EnableAutoOdometerInsert = bool.Parse(_config[nameof(UserConfig.EnableAutoOdometerInsert)]),
|
||||
PreferredGasMileageUnit = _config[nameof(UserConfig.PreferredGasMileageUnit)],
|
||||
PreferredGasUnit = _config[nameof(UserConfig.PreferredGasUnit)],
|
||||
UserLanguage = _config[nameof(UserConfig.UserLanguage)],
|
||||
HideSoldVehicles = bool.Parse(_config[nameof(UserConfig.HideSoldVehicles)]),
|
||||
EnableShopSupplies = bool.Parse(_config[nameof(UserConfig.EnableShopSupplies)]),
|
||||
EnableExtraFieldColumns = bool.Parse(_config[nameof(UserConfig.EnableExtraFieldColumns)]),
|
||||
VisibleTabs = _config.GetSection(nameof(UserConfig.VisibleTabs)).Get<List<ImportMode>>(),
|
||||
EnableCsvImports = CheckBool(CheckString(nameof(UserConfig.EnableCsvImports)), true),
|
||||
UseDarkMode = CheckBool(CheckString(nameof(UserConfig.UseDarkMode))),
|
||||
UseSystemColorMode = CheckBool(CheckString(nameof(UserConfig.UseSystemColorMode))),
|
||||
UseMPG = CheckBool(CheckString(nameof(UserConfig.UseMPG)), true),
|
||||
UseDescending = CheckBool(CheckString(nameof(UserConfig.UseDescending))),
|
||||
EnableAuth = CheckBool(CheckString(nameof(UserConfig.EnableAuth))),
|
||||
EnableRootUserOIDC = CheckBool(CheckString(nameof(UserConfig.EnableRootUserOIDC))),
|
||||
HideZero = CheckBool(CheckString(nameof(UserConfig.HideZero))),
|
||||
AutomaticDecimalFormat = CheckBool(CheckString(nameof(UserConfig.AutomaticDecimalFormat))),
|
||||
UseUKMPG = CheckBool(CheckString(nameof(UserConfig.UseUKMPG))),
|
||||
UseMarkDownOnSavedNotes = CheckBool(CheckString(nameof(UserConfig.UseMarkDownOnSavedNotes))),
|
||||
UseThreeDecimalGasCost = CheckBool(CheckString(nameof(UserConfig.UseThreeDecimalGasCost)), true),
|
||||
UseThreeDecimalGasConsumption = CheckBool(CheckString(nameof(UserConfig.UseThreeDecimalGasConsumption)), true),
|
||||
EnableAutoReminderRefresh = CheckBool(CheckString(nameof(UserConfig.EnableAutoReminderRefresh))),
|
||||
EnableAutoOdometerInsert = CheckBool(CheckString(nameof(UserConfig.EnableAutoOdometerInsert))),
|
||||
PreferredGasMileageUnit = CheckString(nameof(UserConfig.PreferredGasMileageUnit)),
|
||||
PreferredGasUnit = CheckString(nameof(UserConfig.PreferredGasUnit)),
|
||||
UseUnitForFuelCost = CheckBool(CheckString(nameof(UserConfig.UseUnitForFuelCost))),
|
||||
UserLanguage = CheckString(nameof(UserConfig.UserLanguage), "en_US"),
|
||||
HideSoldVehicles = CheckBool(CheckString(nameof(UserConfig.HideSoldVehicles))),
|
||||
EnableShopSupplies = CheckBool(CheckString(nameof(UserConfig.EnableShopSupplies))),
|
||||
ShowCalendar = CheckBool(CheckString(nameof(UserConfig.ShowCalendar))),
|
||||
EnableExtraFieldColumns = CheckBool(CheckString(nameof(UserConfig.EnableExtraFieldColumns))),
|
||||
VisibleTabs = _config.GetSection(nameof(UserConfig.VisibleTabs)).Get<List<ImportMode>>() ?? new UserConfig().VisibleTabs,
|
||||
TabOrder = _config.GetSection(nameof(UserConfig.TabOrder)).Get<List<ImportMode>>() ?? new UserConfig().TabOrder,
|
||||
UserColumnPreferences = _config.GetSection(nameof(UserConfig.UserColumnPreferences)).Get<List<UserColumnPreference>>() ?? new List<UserColumnPreference>(),
|
||||
ReminderUrgencyConfig = _config.GetSection(nameof(UserConfig.ReminderUrgencyConfig)).Get<ReminderUrgencyConfig>() ?? new ReminderUrgencyConfig(),
|
||||
DefaultTab = (ImportMode)int.Parse(_config[nameof(UserConfig.DefaultTab)])
|
||||
DefaultTab = (ImportMode)int.Parse(CheckString(nameof(UserConfig.DefaultTab), "8")),
|
||||
DefaultReminderEmail = CheckString(nameof(UserConfig.DefaultReminderEmail)),
|
||||
DisableRegistration = CheckBool(CheckString(nameof(UserConfig.DisableRegistration))),
|
||||
ShowVehicleThumbnail = CheckBool(CheckString(nameof(UserConfig.ShowVehicleThumbnail)))
|
||||
};
|
||||
int userId = 0;
|
||||
if (user != null)
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace CarCareTracker.Helper
|
||||
public interface IFileHelper
|
||||
{
|
||||
string GetFullFilePath(string currentFilePath, bool mustExist = true);
|
||||
byte[] GetFileBytes(string fullFilePath, bool deleteFile = false);
|
||||
string MoveFileFromTemp(string currentFilePath, string newFolder);
|
||||
bool RenameFile(string currentFilePath, string newName);
|
||||
bool DeleteFile(string currentFilePath);
|
||||
@@ -13,6 +14,13 @@ namespace CarCareTracker.Helper
|
||||
bool RestoreBackup(string fileName, bool clearExisting = false);
|
||||
string MakeAttachmentsExport(List<GenericReportModel> exportData);
|
||||
List<string> GetLanguages();
|
||||
int ClearTempFolder();
|
||||
int ClearUnlinkedThumbnails(List<string> linkedImages);
|
||||
int ClearUnlinkedDocuments(List<string> linkedDocuments);
|
||||
string GetWidgets();
|
||||
bool WidgetsExist();
|
||||
bool SaveWidgets(string widgetsData);
|
||||
bool DeleteWidgets();
|
||||
}
|
||||
public class FileHelper : IFileHelper
|
||||
{
|
||||
@@ -27,7 +35,7 @@ namespace CarCareTracker.Helper
|
||||
}
|
||||
public List<string> GetLanguages()
|
||||
{
|
||||
var languagePath = Path.Combine(_webEnv.WebRootPath, "translations");
|
||||
var languagePath = Path.Combine(_webEnv.ContentRootPath, "data", "translations");
|
||||
var defaultList = new List<string>() { "en_US" };
|
||||
if (Directory.Exists(languagePath))
|
||||
{
|
||||
@@ -65,7 +73,7 @@ namespace CarCareTracker.Helper
|
||||
{
|
||||
currentFilePath = currentFilePath.Substring(1);
|
||||
}
|
||||
string oldFilePath = Path.Combine(_webEnv.WebRootPath, currentFilePath);
|
||||
string oldFilePath = currentFilePath.StartsWith("defaults/") ? Path.Combine(_webEnv.WebRootPath, currentFilePath) : Path.Combine(_webEnv.ContentRootPath, "data", currentFilePath);
|
||||
if (File.Exists(oldFilePath))
|
||||
{
|
||||
return oldFilePath;
|
||||
@@ -78,6 +86,19 @@ namespace CarCareTracker.Helper
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
public byte[] GetFileBytes(string fullFilePath, bool deleteFile = false)
|
||||
{
|
||||
if (File.Exists(fullFilePath))
|
||||
{
|
||||
var fileBytes = File.ReadAllBytes(fullFilePath);
|
||||
if (deleteFile)
|
||||
{
|
||||
File.Delete(fullFilePath);
|
||||
}
|
||||
return fileBytes;
|
||||
}
|
||||
return Array.Empty<byte>();
|
||||
}
|
||||
public bool RestoreBackup(string fileName, bool clearExisting = false)
|
||||
{
|
||||
var fullFilePath = GetFullFilePath(fileName);
|
||||
@@ -87,7 +108,7 @@ namespace CarCareTracker.Helper
|
||||
}
|
||||
try
|
||||
{
|
||||
var tempPath = Path.Combine(_webEnv.WebRootPath, $"temp/{Guid.NewGuid()}");
|
||||
var tempPath = Path.Combine(_webEnv.ContentRootPath, "data", $"temp/{Guid.NewGuid()}");
|
||||
if (!Directory.Exists(tempPath))
|
||||
Directory.CreateDirectory(tempPath);
|
||||
//extract zip file
|
||||
@@ -97,10 +118,11 @@ namespace CarCareTracker.Helper
|
||||
var documentPath = Path.Combine(tempPath, "documents");
|
||||
var translationPath = Path.Combine(tempPath, "translations");
|
||||
var dataPath = Path.Combine(tempPath, StaticHelper.DbName);
|
||||
var configPath = Path.Combine(tempPath, StaticHelper.UserConfigPath);
|
||||
var widgetPath = Path.Combine(tempPath, StaticHelper.AdditionalWidgetsPath);
|
||||
var configPath = Path.Combine(tempPath, StaticHelper.LegacyUserConfigPath);
|
||||
if (Directory.Exists(imagePath))
|
||||
{
|
||||
var existingPath = Path.Combine(_webEnv.WebRootPath, "images");
|
||||
var existingPath = Path.Combine(_webEnv.ContentRootPath, "data", "images");
|
||||
if (!Directory.Exists(existingPath))
|
||||
{
|
||||
Directory.CreateDirectory(existingPath);
|
||||
@@ -122,7 +144,7 @@ namespace CarCareTracker.Helper
|
||||
}
|
||||
if (Directory.Exists(documentPath))
|
||||
{
|
||||
var existingPath = Path.Combine(_webEnv.WebRootPath, "documents");
|
||||
var existingPath = Path.Combine(_webEnv.ContentRootPath, "data", "documents");
|
||||
if (!Directory.Exists(existingPath))
|
||||
{
|
||||
Directory.CreateDirectory(existingPath);
|
||||
@@ -144,7 +166,7 @@ namespace CarCareTracker.Helper
|
||||
}
|
||||
if (Directory.Exists(translationPath))
|
||||
{
|
||||
var existingPath = Path.Combine(_webEnv.WebRootPath, "translations");
|
||||
var existingPath = Path.Combine(_webEnv.ContentRootPath, "data", "translations");
|
||||
if (!Directory.Exists(existingPath))
|
||||
{
|
||||
Directory.CreateDirectory(existingPath);
|
||||
@@ -171,12 +193,16 @@ namespace CarCareTracker.Helper
|
||||
//data path will always exist as it is created on startup if not.
|
||||
File.Move(dataPath, StaticHelper.DbName, true);
|
||||
}
|
||||
if (File.Exists(widgetPath))
|
||||
{
|
||||
File.Move(widgetPath, StaticHelper.AdditionalWidgetsPath, true);
|
||||
}
|
||||
if (File.Exists(configPath))
|
||||
{
|
||||
//check if config folder exists.
|
||||
if (!Directory.Exists("config/"))
|
||||
if (!Directory.Exists("data/config"))
|
||||
{
|
||||
Directory.CreateDirectory("config/");
|
||||
Directory.CreateDirectory("data/config");
|
||||
}
|
||||
File.Move(configPath, StaticHelper.UserConfigPath, true);
|
||||
}
|
||||
@@ -191,7 +217,7 @@ namespace CarCareTracker.Helper
|
||||
public string MakeAttachmentsExport(List<GenericReportModel> exportData)
|
||||
{
|
||||
var folderName = Guid.NewGuid();
|
||||
var tempPath = Path.Combine(_webEnv.WebRootPath, $"temp/{folderName}");
|
||||
var tempPath = Path.Combine(_webEnv.ContentRootPath, "data", $"temp/{folderName}");
|
||||
if (!Directory.Exists(tempPath))
|
||||
Directory.CreateDirectory(tempPath);
|
||||
int fileIndex = 0;
|
||||
@@ -215,11 +241,12 @@ namespace CarCareTracker.Helper
|
||||
public string MakeBackup()
|
||||
{
|
||||
var folderName = $"db_backup_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}";
|
||||
var tempPath = Path.Combine(_webEnv.WebRootPath, $"temp/{folderName}");
|
||||
var imagePath = Path.Combine(_webEnv.WebRootPath, "images");
|
||||
var documentPath = Path.Combine(_webEnv.WebRootPath, "documents");
|
||||
var translationPath = Path.Combine(_webEnv.WebRootPath, "translations");
|
||||
var tempPath = Path.Combine(_webEnv.ContentRootPath, "data", $"temp/{folderName}");
|
||||
var imagePath = Path.Combine(_webEnv.ContentRootPath, "data", "images");
|
||||
var documentPath = Path.Combine(_webEnv.ContentRootPath, "data", "documents");
|
||||
var translationPath = Path.Combine(_webEnv.ContentRootPath, "data", "translations");
|
||||
var dataPath = StaticHelper.DbName;
|
||||
var widgetPath = StaticHelper.AdditionalWidgetsPath;
|
||||
var configPath = StaticHelper.UserConfigPath;
|
||||
if (!Directory.Exists(tempPath))
|
||||
Directory.CreateDirectory(tempPath);
|
||||
@@ -259,6 +286,12 @@ namespace CarCareTracker.Helper
|
||||
Directory.CreateDirectory(newPath);
|
||||
File.Copy(dataPath, $"{newPath}/{Path.GetFileName(dataPath)}");
|
||||
}
|
||||
if (File.Exists(widgetPath))
|
||||
{
|
||||
var newPath = Path.Combine(tempPath, "data");
|
||||
Directory.CreateDirectory(newPath);
|
||||
File.Copy(widgetPath, $"{newPath}/{Path.GetFileName(widgetPath)}");
|
||||
}
|
||||
if (File.Exists(configPath))
|
||||
{
|
||||
var newPath = Path.Combine(tempPath, "config");
|
||||
@@ -282,8 +315,8 @@ namespace CarCareTracker.Helper
|
||||
{
|
||||
currentFilePath = currentFilePath.Substring(1);
|
||||
}
|
||||
string uploadPath = Path.Combine(_webEnv.WebRootPath, newFolder);
|
||||
string oldFilePath = Path.Combine(_webEnv.WebRootPath, currentFilePath);
|
||||
string uploadPath = Path.Combine(_webEnv.ContentRootPath, "data", newFolder);
|
||||
string oldFilePath = Path.Combine(_webEnv.ContentRootPath, "data", currentFilePath);
|
||||
if (!Directory.Exists(uploadPath))
|
||||
Directory.CreateDirectory(uploadPath);
|
||||
string newFileUploadPath = oldFilePath.Replace(tempPath, newFolder);
|
||||
@@ -300,7 +333,7 @@ namespace CarCareTracker.Helper
|
||||
{
|
||||
currentFilePath = currentFilePath.Substring(1);
|
||||
}
|
||||
string filePath = Path.Combine(_webEnv.WebRootPath, currentFilePath);
|
||||
string filePath = Path.Combine(_webEnv.ContentRootPath, "data", currentFilePath);
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Delete(filePath);
|
||||
@@ -314,5 +347,116 @@ namespace CarCareTracker.Helper
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public int ClearTempFolder()
|
||||
{
|
||||
int filesDeleted = 0;
|
||||
var tempPath = GetFullFilePath("temp", false);
|
||||
if (Directory.Exists(tempPath))
|
||||
{
|
||||
//delete files
|
||||
var files = Directory.GetFiles(tempPath);
|
||||
foreach (var file in files)
|
||||
{
|
||||
File.Delete(file);
|
||||
filesDeleted++;
|
||||
}
|
||||
//delete folders
|
||||
var folders = Directory.GetDirectories(tempPath);
|
||||
foreach(var folder in folders)
|
||||
{
|
||||
Directory.Delete(folder, true);
|
||||
filesDeleted++;
|
||||
}
|
||||
}
|
||||
return filesDeleted;
|
||||
}
|
||||
public int ClearUnlinkedThumbnails(List<string> linkedImages)
|
||||
{
|
||||
int filesDeleted = 0;
|
||||
var imagePath = GetFullFilePath("images", false);
|
||||
if (Directory.Exists(imagePath))
|
||||
{
|
||||
var files = Directory.GetFiles(imagePath);
|
||||
foreach(var file in files)
|
||||
{
|
||||
if (!linkedImages.Contains(Path.GetFileName(file)))
|
||||
{
|
||||
File.Delete(file);
|
||||
filesDeleted++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return filesDeleted;
|
||||
}
|
||||
public int ClearUnlinkedDocuments(List<string> linkedDocuments)
|
||||
{
|
||||
int filesDeleted = 0;
|
||||
var documentPath = GetFullFilePath("documents", false);
|
||||
if (Directory.Exists(documentPath))
|
||||
{
|
||||
var files = Directory.GetFiles(documentPath);
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (!linkedDocuments.Contains(Path.GetFileName(file)))
|
||||
{
|
||||
File.Delete(file);
|
||||
filesDeleted++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return filesDeleted;
|
||||
}
|
||||
public string GetWidgets()
|
||||
{
|
||||
if (File.Exists(StaticHelper.AdditionalWidgetsPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
//read file
|
||||
var widgets = File.ReadAllText(StaticHelper.AdditionalWidgetsPath);
|
||||
return widgets;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
public bool WidgetsExist()
|
||||
{
|
||||
return File.Exists(StaticHelper.AdditionalWidgetsPath);
|
||||
}
|
||||
public bool SaveWidgets(string widgetsData)
|
||||
{
|
||||
try
|
||||
{
|
||||
//Delete Widgets if exists
|
||||
DeleteWidgets();
|
||||
File.WriteAllText(StaticHelper.AdditionalWidgetsPath, widgetsData);
|
||||
return true;
|
||||
} catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public bool DeleteWidgets()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(StaticHelper.AdditionalWidgetsPath))
|
||||
{
|
||||
File.Delete(StaticHelper.AdditionalWidgetsPath);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,10 @@ namespace CarCareTracker.Helper
|
||||
if (i > 0)
|
||||
{
|
||||
var deltaMileage = currentObject.Mileage - previousMileage;
|
||||
if (deltaMileage < 0)
|
||||
{
|
||||
deltaMileage = 0;
|
||||
}
|
||||
var gasRecordViewModel = new GasRecordViewModel()
|
||||
{
|
||||
Id = currentObject.Id,
|
||||
@@ -72,7 +76,8 @@ namespace CarCareTracker.Helper
|
||||
MissedFuelUp = currentObject.MissedFuelUp,
|
||||
Notes = currentObject.Notes,
|
||||
Tags = currentObject.Tags,
|
||||
ExtraFields = currentObject.ExtraFields
|
||||
ExtraFields = currentObject.ExtraFields,
|
||||
Files = currentObject.Files
|
||||
};
|
||||
if (currentObject.MissedFuelUp)
|
||||
{
|
||||
@@ -82,9 +87,9 @@ namespace CarCareTracker.Helper
|
||||
unFactoredConsumption = 0;
|
||||
unFactoredMileage = 0;
|
||||
}
|
||||
else if (currentObject.IsFillToFull)
|
||||
else if (currentObject.IsFillToFull && currentObject.Mileage != default)
|
||||
{
|
||||
//if user filled to full.
|
||||
//if user filled to full and an odometer is provided, otherwise we will defer calculations
|
||||
if (convertedConsumption > 0.00M && deltaMileage > 0)
|
||||
{
|
||||
try
|
||||
@@ -126,10 +131,14 @@ namespace CarCareTracker.Helper
|
||||
MissedFuelUp = currentObject.MissedFuelUp,
|
||||
Notes = currentObject.Notes,
|
||||
Tags = currentObject.Tags,
|
||||
ExtraFields = currentObject.ExtraFields
|
||||
ExtraFields = currentObject.ExtraFields,
|
||||
Files = currentObject.Files
|
||||
});
|
||||
}
|
||||
previousMileage = currentObject.Mileage;
|
||||
if (currentObject.Mileage != default)
|
||||
{
|
||||
previousMileage = currentObject.Mileage;
|
||||
}
|
||||
}
|
||||
return computedResults;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using CarCareTracker.Models;
|
||||
using System.Net.Mail;
|
||||
using System.Net;
|
||||
using MimeKit;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
|
||||
namespace CarCareTracker.Helper
|
||||
{
|
||||
@@ -10,149 +11,208 @@ namespace CarCareTracker.Helper
|
||||
OperationResponse NotifyUserForPasswordReset(string emailAddress, string token);
|
||||
OperationResponse NotifyUserForAccountUpdate(string emailAddress, string token);
|
||||
OperationResponse NotifyUserForReminders(Vehicle vehicle, List<string> emailAddresses, List<ReminderRecordViewModel> reminders);
|
||||
OperationResponse SendTestEmail(string emailAddress);
|
||||
}
|
||||
public class MailHelper : IMailHelper
|
||||
{
|
||||
private readonly MailConfig mailConfig;
|
||||
private readonly string serverLanguage;
|
||||
private readonly string serverDomain;
|
||||
private readonly IFileHelper _fileHelper;
|
||||
private readonly ITranslationHelper _translator;
|
||||
private readonly ILogger<MailHelper> _logger;
|
||||
public MailHelper(
|
||||
IConfiguration config,
|
||||
IFileHelper fileHelper
|
||||
IConfigHelper config,
|
||||
IFileHelper fileHelper,
|
||||
ITranslationHelper translationHelper,
|
||||
ILogger<MailHelper> logger
|
||||
) {
|
||||
//load mailConfig from Configuration
|
||||
mailConfig = config.GetSection("MailConfig").Get<MailConfig>();
|
||||
mailConfig = config.GetMailConfig();
|
||||
serverLanguage = config.GetServerLanguage();
|
||||
serverDomain = config.GetServerDomain();
|
||||
_fileHelper = fileHelper;
|
||||
_translator = translationHelper;
|
||||
_logger = logger;
|
||||
}
|
||||
public OperationResponse NotifyUserForRegistration(string emailAddress, string token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
|
||||
return OperationResponse.Failed("SMTP Server Not Setup");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(token)) {
|
||||
return new OperationResponse { Success = false, Message = "Email Address or Token is invalid" };
|
||||
return OperationResponse.Failed("Email Address or Token is invalid");
|
||||
}
|
||||
string emailSubject = "Your Registration Token for LubeLogger";
|
||||
string emailBody = $"A token has been generated on your behalf, please complete your registration for LubeLogger using the token: {token}";
|
||||
var result = SendEmail(emailAddress, emailSubject, emailBody);
|
||||
string emailSubject = _translator.Translate(serverLanguage, "Your Registration Token for LubeLogger");
|
||||
string tokenHtml = token;
|
||||
if (!string.IsNullOrWhiteSpace(serverDomain))
|
||||
{
|
||||
string cleanedURL = serverDomain.EndsWith('/') ? serverDomain.TrimEnd('/') : serverDomain;
|
||||
//construct registration URL.
|
||||
tokenHtml = $"<a href='{cleanedURL}/Login/Registration?email={emailAddress}&token={token}' target='_blank'>{token}</a>";
|
||||
}
|
||||
string emailBody = $"<span>{_translator.Translate(serverLanguage, "A token has been generated on your behalf, please complete your registration for LubeLogger using the token")}: {tokenHtml}</span>";
|
||||
var result = SendEmail(new List<string> { emailAddress }, emailSubject, emailBody);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "Email Sent!" };
|
||||
return OperationResponse.Succeed("Email Sent!");
|
||||
} else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public OperationResponse NotifyUserForPasswordReset(string emailAddress, string token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
|
||||
return OperationResponse.Failed("SMTP Server Not Setup");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Email Address or Token is invalid" };
|
||||
return OperationResponse.Failed("Email Address or Token is invalid");
|
||||
}
|
||||
string emailSubject = "Your Password Reset Token for LubeLogger";
|
||||
string emailBody = $"A token has been generated on your behalf, please reset your password for LubeLogger using the token: {token}";
|
||||
var result = SendEmail(emailAddress, emailSubject, emailBody);
|
||||
string emailSubject = _translator.Translate(serverLanguage, "Your Password Reset Token for LubeLogger");
|
||||
string tokenHtml = token;
|
||||
if (!string.IsNullOrWhiteSpace(serverDomain))
|
||||
{
|
||||
string cleanedURL = serverDomain.EndsWith('/') ? serverDomain.TrimEnd('/') : serverDomain;
|
||||
//construct registration URL.
|
||||
tokenHtml = $"<a href='{cleanedURL}/Login/ResetPassword?email={emailAddress}&token={token}' target='_blank'>{token}</a>";
|
||||
}
|
||||
string emailBody = $"<span>{_translator.Translate(serverLanguage, "A token has been generated on your behalf, please reset your password for LubeLogger using the token")}: {tokenHtml}</span>";
|
||||
var result = SendEmail(new List<string> { emailAddress }, emailSubject, emailBody);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "Email Sent!" };
|
||||
return OperationResponse.Succeed("Email Sent!");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public OperationResponse SendTestEmail(string emailAddress)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
|
||||
{
|
||||
return OperationResponse.Failed("SMTP Server Not Setup");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(emailAddress))
|
||||
{
|
||||
return OperationResponse.Failed("Email Address or Token is invalid");
|
||||
}
|
||||
string emailSubject = _translator.Translate(serverLanguage, "Test Email from LubeLogger");
|
||||
string emailBody = _translator.Translate(serverLanguage, "If you are seeing this email it means your SMTP configuration is functioning correctly");
|
||||
var result = SendEmail(new List<string> { emailAddress }, emailSubject, emailBody);
|
||||
if (result)
|
||||
{
|
||||
return OperationResponse.Succeed("Email Sent!");
|
||||
}
|
||||
else
|
||||
{
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public OperationResponse NotifyUserForAccountUpdate(string emailAddress, string token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
|
||||
return OperationResponse.Failed("SMTP Server Not Setup");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Email Address or Token is invalid" };
|
||||
return OperationResponse.Failed("Email Address or Token is invalid");
|
||||
}
|
||||
string emailSubject = "Your User Account Update Token for LubeLogger";
|
||||
string emailBody = $"A token has been generated on your behalf, please update your account for LubeLogger using the token: {token}";
|
||||
var result = SendEmail(emailAddress, emailSubject, emailBody);
|
||||
string emailSubject = _translator.Translate(serverLanguage, "Your User Account Update Token for LubeLogger");
|
||||
string emailBody = $"{_translator.Translate(serverLanguage, "A token has been generated on your behalf, please update your account for LubeLogger using the token")}: {token}";
|
||||
var result = SendEmail(new List<string> { emailAddress}, emailSubject, emailBody);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "Email Sent!" };
|
||||
return OperationResponse.Succeed("Email Sent!");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public OperationResponse NotifyUserForReminders(Vehicle vehicle, List<string> emailAddresses, List<ReminderRecordViewModel> reminders)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
|
||||
return OperationResponse.Failed("SMTP Server Not Setup");
|
||||
}
|
||||
if (!emailAddresses.Any())
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "No recipients could be found" };
|
||||
return OperationResponse.Failed("No recipients could be found");
|
||||
}
|
||||
if (!reminders.Any())
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "No reminders could be found" };
|
||||
return OperationResponse.Failed("No reminders could be found");
|
||||
}
|
||||
//get email template, this file has to exist since it's a static file.
|
||||
var emailTemplatePath = _fileHelper.GetFullFilePath(StaticHelper.ReminderEmailTemplate);
|
||||
string emailSubject = $"Vehicle Reminders From LubeLogger - {DateTime.Now.ToShortDateString()}";
|
||||
string emailSubject = $"{_translator.Translate(serverLanguage, "Vehicle Reminders From LubeLogger")} - {DateTime.Now.ToShortDateString()}";
|
||||
//construct html table.
|
||||
string emailBody = File.ReadAllText(emailTemplatePath);
|
||||
emailBody = emailBody.Replace("{VehicleInformation}", $"{vehicle.Year} {vehicle.Make} {vehicle.Model} #{vehicle.LicensePlate}");
|
||||
emailBody = emailBody.Replace("{VehicleInformation}", $"{vehicle.Year} {vehicle.Make} {vehicle.Model} #{StaticHelper.GetVehicleIdentifier(vehicle)}");
|
||||
string tableHeader = $"<th>{_translator.Translate(serverLanguage, "Urgency")}</th><th>{_translator.Translate(serverLanguage, "Description")}</th><th>{_translator.Translate(serverLanguage, "Due")}</th>";
|
||||
string tableBody = "";
|
||||
foreach(ReminderRecordViewModel reminder in reminders)
|
||||
{
|
||||
var dueOn = reminder.Metric == ReminderMetric.Both ? $"{reminder.Date} or {reminder.Mileage}" : reminder.Metric == ReminderMetric.Date ? $"{reminder.Date.ToShortDateString()}" : $"{reminder.Mileage}";
|
||||
tableBody += $"<tr class='{reminder.Urgency}'><td>{StaticHelper.GetTitleCaseReminderUrgency(reminder.Urgency)}</td><td>{reminder.Description}</td><td>{dueOn}</td></tr>";
|
||||
var dueOn = reminder.Metric == ReminderMetric.Both ? $"{reminder.Date.ToShortDateString()} or {reminder.Mileage}" : reminder.Metric == ReminderMetric.Date ? $"{reminder.Date.ToShortDateString()}" : $"{reminder.Mileage}";
|
||||
tableBody += $"<tr class='{reminder.Urgency}'><td>{_translator.Translate(serverLanguage, StaticHelper.GetTitleCaseReminderUrgency(reminder.Urgency))}</td><td>{reminder.Description}</td><td>{dueOn}</td></tr>";
|
||||
}
|
||||
emailBody = emailBody.Replace("{TableBody}", tableBody);
|
||||
emailBody = emailBody.Replace("{TableHeader}", tableHeader).Replace("{TableBody}", tableBody);
|
||||
try
|
||||
{
|
||||
foreach (string emailAddress in emailAddresses)
|
||||
var result = SendEmail(emailAddresses, emailSubject, emailBody);
|
||||
if (result)
|
||||
{
|
||||
SendEmail(emailAddress, emailSubject, emailBody, true, true);
|
||||
return OperationResponse.Succeed("Email Sent!");
|
||||
} else
|
||||
{
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
return new OperationResponse { Success = true, Message = "Email Sent!" };
|
||||
} catch (Exception ex)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = ex.Message };
|
||||
return OperationResponse.Failed(ex.Message);
|
||||
}
|
||||
}
|
||||
private bool SendEmail(string emailTo, string emailSubject, string emailBody, bool isBodyHtml = false, bool useAsync = false) {
|
||||
string to = emailTo;
|
||||
private bool SendEmail(List<string> emailTo, string emailSubject, string emailBody) {
|
||||
string from = mailConfig.EmailFrom;
|
||||
var server = mailConfig.EmailServer;
|
||||
MailMessage message = new MailMessage(from, to);
|
||||
message.Subject = emailSubject;
|
||||
message.Body = emailBody;
|
||||
message.IsBodyHtml = isBodyHtml;
|
||||
SmtpClient client = new SmtpClient(server);
|
||||
client.EnableSsl = mailConfig.UseSSL;
|
||||
client.Port = mailConfig.Port;
|
||||
client.Credentials = new NetworkCredential(mailConfig.Username, mailConfig.Password);
|
||||
try
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(new MailboxAddress(from, from));
|
||||
foreach(string emailRecipient in emailTo)
|
||||
{
|
||||
if (useAsync)
|
||||
{
|
||||
client.SendMailAsync(message, new CancellationToken());
|
||||
message.To.Add(new MailboxAddress(emailRecipient, emailRecipient));
|
||||
}
|
||||
message.Subject = emailSubject;
|
||||
|
||||
var builder = new BodyBuilder();
|
||||
|
||||
builder.HtmlBody = emailBody;
|
||||
|
||||
message.Body = builder.ToMessageBody();
|
||||
|
||||
using (var client = new SmtpClient())
|
||||
{
|
||||
client.Connect(server, mailConfig.Port, SecureSocketOptions.Auto);
|
||||
//perform authentication if either username or password is provided.
|
||||
//do not perform authentication if neither are provided.
|
||||
if (!string.IsNullOrWhiteSpace(mailConfig.Username) || !string.IsNullOrWhiteSpace(mailConfig.Password)) {
|
||||
client.Authenticate(mailConfig.Username, mailConfig.Password);
|
||||
}
|
||||
else
|
||||
try
|
||||
{
|
||||
client.Send(message);
|
||||
client.Disconnect(true);
|
||||
return true;
|
||||
} catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,14 @@ namespace CarCareTracker.Helper
|
||||
existingReminder.Date = newDate.AddMonths((int)existingReminder.ReminderMonthInterval);
|
||||
} else
|
||||
{
|
||||
existingReminder.Date = newDate.Date.AddMonths(existingReminder.CustomMonthInterval);
|
||||
if (existingReminder.CustomMonthIntervalUnit == ReminderIntervalUnit.Months)
|
||||
{
|
||||
existingReminder.Date = newDate.Date.AddMonths(existingReminder.CustomMonthInterval);
|
||||
}
|
||||
else if (existingReminder.CustomMonthIntervalUnit == ReminderIntervalUnit.Days)
|
||||
{
|
||||
existingReminder.Date = newDate.Date.AddDays(existingReminder.CustomMonthInterval);
|
||||
}
|
||||
}
|
||||
|
||||
if (existingReminder.ReminderMileageInterval != ReminderMileageInterval.Other)
|
||||
@@ -55,7 +62,14 @@ namespace CarCareTracker.Helper
|
||||
}
|
||||
else
|
||||
{
|
||||
existingReminder.Date = newDate.AddMonths(existingReminder.CustomMonthInterval);
|
||||
if (existingReminder.CustomMonthIntervalUnit == ReminderIntervalUnit.Months)
|
||||
{
|
||||
existingReminder.Date = newDate.AddMonths(existingReminder.CustomMonthInterval);
|
||||
}
|
||||
else if (existingReminder.CustomMonthIntervalUnit == ReminderIntervalUnit.Days)
|
||||
{
|
||||
existingReminder.Date = newDate.AddDays(existingReminder.CustomMonthInterval);
|
||||
}
|
||||
}
|
||||
}
|
||||
return existingReminder;
|
||||
@@ -66,6 +80,10 @@ namespace CarCareTracker.Helper
|
||||
var reminderUrgencyConfig = _config.GetReminderUrgencyConfig();
|
||||
foreach (var reminder in reminders)
|
||||
{
|
||||
if (reminder.UseCustomThresholds)
|
||||
{
|
||||
reminderUrgencyConfig = reminder.CustomThresholds;
|
||||
}
|
||||
var reminderViewModel = new ReminderRecordViewModel()
|
||||
{
|
||||
Id = reminder.Id,
|
||||
@@ -75,6 +93,7 @@ namespace CarCareTracker.Helper
|
||||
Description = reminder.Description,
|
||||
Notes = reminder.Notes,
|
||||
Metric = reminder.Metric,
|
||||
UserMetric = reminder.Metric,
|
||||
IsRecurring = reminder.IsRecurring,
|
||||
Tags = reminder.Tags
|
||||
};
|
||||
|
||||
@@ -5,93 +5,166 @@ namespace CarCareTracker.Helper
|
||||
{
|
||||
public interface IReportHelper
|
||||
{
|
||||
IEnumerable<CostForVehicleByMonth> GetOdometerRecordSum(List<OdometerRecord> odometerRecords, int year = 0);
|
||||
IEnumerable<CostForVehicleByMonth> GetServiceRecordSum(List<ServiceRecord> serviceRecords, int year = 0);
|
||||
IEnumerable<CostForVehicleByMonth> GetRepairRecordSum(List<CollisionRecord> repairRecords, int year = 0);
|
||||
IEnumerable<CostForVehicleByMonth> GetUpgradeRecordSum(List<UpgradeRecord> upgradeRecords, int year = 0);
|
||||
IEnumerable<CostForVehicleByMonth> GetGasRecordSum(List<GasRecord> gasRecords, int year = 0);
|
||||
IEnumerable<CostForVehicleByMonth> GetTaxRecordSum(List<TaxRecord> taxRecords, int year = 0);
|
||||
IEnumerable<CostForVehicleByMonth> GetOdometerRecordSum(List<OdometerRecord> odometerRecords, int year = 0, bool sortIntoYear = false);
|
||||
IEnumerable<CostForVehicleByMonth> GetServiceRecordSum(List<ServiceRecord> serviceRecords, int year = 0, bool sortIntoYear = false);
|
||||
IEnumerable<CostForVehicleByMonth> GetRepairRecordSum(List<CollisionRecord> repairRecords, int year = 0, bool sortIntoYear = false);
|
||||
IEnumerable<CostForVehicleByMonth> GetUpgradeRecordSum(List<UpgradeRecord> upgradeRecords, int year = 0, bool sortIntoYear = false);
|
||||
IEnumerable<CostForVehicleByMonth> GetGasRecordSum(List<GasRecord> gasRecords, int year = 0, bool sortIntoYear = false);
|
||||
IEnumerable<CostForVehicleByMonth> GetTaxRecordSum(List<TaxRecord> taxRecords, int year = 0, bool sortIntoYear = false);
|
||||
}
|
||||
public class ReportHelper: IReportHelper
|
||||
{
|
||||
public IEnumerable<CostForVehicleByMonth> GetOdometerRecordSum(List<OdometerRecord> odometerRecords, int year = 0)
|
||||
public IEnumerable<CostForVehicleByMonth> GetOdometerRecordSum(List<OdometerRecord> odometerRecords, int year = 0, bool sortIntoYear = false)
|
||||
{
|
||||
if (year != default)
|
||||
{
|
||||
odometerRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
return odometerRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
if (sortIntoYear)
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = 0,
|
||||
DistanceTraveled = x.Sum(y=>y.DistanceTraveled)
|
||||
});
|
||||
return odometerRecords.GroupBy(x => new { x.Date.Month, x.Date.Year }).OrderBy(x => x.Key.Month).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key.Month,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month),
|
||||
Year = x.Key.Year,
|
||||
Cost = 0,
|
||||
DistanceTraveled = x.Sum(y => y.DistanceTraveled)
|
||||
});
|
||||
} else
|
||||
{
|
||||
return odometerRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = 0,
|
||||
DistanceTraveled = x.Sum(y => y.DistanceTraveled)
|
||||
});
|
||||
}
|
||||
}
|
||||
public IEnumerable<CostForVehicleByMonth> GetServiceRecordSum(List<ServiceRecord> serviceRecords, int year = 0)
|
||||
public IEnumerable<CostForVehicleByMonth> GetServiceRecordSum(List<ServiceRecord> serviceRecords, int year = 0, bool sortIntoYear = false)
|
||||
{
|
||||
if (year != default)
|
||||
{
|
||||
serviceRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
return serviceRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
if (sortIntoYear)
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
return serviceRecords.GroupBy(x => new { x.Date.Month, x.Date.Year }).OrderBy(x => x.Key.Month).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key.Month,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month),
|
||||
Year = x.Key.Year,
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
} else
|
||||
{
|
||||
return serviceRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
}
|
||||
}
|
||||
public IEnumerable<CostForVehicleByMonth> GetRepairRecordSum(List<CollisionRecord> repairRecords, int year = 0)
|
||||
public IEnumerable<CostForVehicleByMonth> GetRepairRecordSum(List<CollisionRecord> repairRecords, int year = 0, bool sortIntoYear = false)
|
||||
{
|
||||
if (year != default)
|
||||
{
|
||||
repairRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
return repairRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
if (sortIntoYear)
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
return repairRecords.GroupBy(x => new { x.Date.Month, x.Date.Year }).OrderBy(x => x.Key.Month).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key.Month,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month),
|
||||
Year = x.Key.Year,
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
} else
|
||||
{
|
||||
return repairRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
}
|
||||
}
|
||||
public IEnumerable<CostForVehicleByMonth> GetUpgradeRecordSum(List<UpgradeRecord> upgradeRecords, int year = 0)
|
||||
public IEnumerable<CostForVehicleByMonth> GetUpgradeRecordSum(List<UpgradeRecord> upgradeRecords, int year = 0, bool sortIntoYear = false)
|
||||
{
|
||||
if (year != default)
|
||||
{
|
||||
upgradeRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
return upgradeRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
if (sortIntoYear)
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
return upgradeRecords.GroupBy(x => new { x.Date.Month, x.Date.Year }).OrderBy(x => x.Key.Month).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key.Month,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month),
|
||||
Year = x.Key.Year,
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
} else
|
||||
{
|
||||
return upgradeRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
}
|
||||
}
|
||||
public IEnumerable<CostForVehicleByMonth> GetGasRecordSum(List<GasRecord> gasRecords, int year = 0)
|
||||
public IEnumerable<CostForVehicleByMonth> GetGasRecordSum(List<GasRecord> gasRecords, int year = 0, bool sortIntoYear = false)
|
||||
{
|
||||
if (year != default)
|
||||
{
|
||||
gasRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
return gasRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
if (sortIntoYear)
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
return gasRecords.GroupBy(x => new { x.Date.Month, x.Date.Year }).OrderBy(x => x.Key.Month).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key.Month,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month),
|
||||
Year = x.Key.Year,
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
} else
|
||||
{
|
||||
return gasRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
}
|
||||
}
|
||||
public IEnumerable<CostForVehicleByMonth> GetTaxRecordSum(List<TaxRecord> taxRecords, int year = 0)
|
||||
public IEnumerable<CostForVehicleByMonth> GetTaxRecordSum(List<TaxRecord> taxRecords, int year = 0, bool sortIntoYear = false)
|
||||
{
|
||||
if (year != default)
|
||||
{
|
||||
taxRecords.RemoveAll(x => x.Date.Year != year);
|
||||
}
|
||||
return taxRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
if (sortIntoYear)
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
return taxRecords.GroupBy(x => new { x.Date.Month, x.Date.Year }).OrderBy(x => x.Key.Month).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key.Month,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month),
|
||||
Year = x.Key.Year,
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
} else
|
||||
{
|
||||
return taxRecords.GroupBy(x => x.Date.Month).OrderBy(x => x.Key).Select(x => new CostForVehicleByMonth
|
||||
{
|
||||
MonthId = x.Key,
|
||||
MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key),
|
||||
Cost = x.Sum(y => y.Cost)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
using CarCareTracker.Models;
|
||||
using CsvHelper;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace CarCareTracker.Helper
|
||||
{
|
||||
@@ -8,13 +12,19 @@ namespace CarCareTracker.Helper
|
||||
/// </summary>
|
||||
public static class StaticHelper
|
||||
{
|
||||
public static string VersionNumber = "1.2.9";
|
||||
public static string DbName = "data/cartracker.db";
|
||||
public static string UserConfigPath = "config/userConfig.json";
|
||||
public static string GenericErrorMessage = "An error occurred, please try again later";
|
||||
public static string ReminderEmailTemplate = "defaults/reminderemailtemplate.txt";
|
||||
public static string DefaultAllowedFileExtensions = ".png,.jpg,.jpeg,.pdf,.xls,.xlsx,.docx";
|
||||
|
||||
public const string VersionNumber = "1.4.8";
|
||||
public const string DbName = "data/cartracker.db";
|
||||
public const string UserConfigPath = "data/config/userConfig.json";
|
||||
public const string LegacyUserConfigPath = "config/userConfig.json";
|
||||
public const string AdditionalWidgetsPath = "data/widgets.html";
|
||||
public const string GenericErrorMessage = "An error occurred, please try again later";
|
||||
public const string ReminderEmailTemplate = "defaults/reminderemailtemplate.txt";
|
||||
public const string DefaultAllowedFileExtensions = ".png,.jpg,.jpeg,.pdf,.xls,.xlsx,.docx";
|
||||
public const string SponsorsPath = "https://hargata.github.io/hargata/sponsors.json";
|
||||
public const string TranslationPath = "https://hargata.github.io/lubelog_translations";
|
||||
public const string ReleasePath = "https://api.github.com/repos/hargata/lubelog/releases/latest";
|
||||
public const string TranslationDirectoryPath = $"{TranslationPath}/directory.json";
|
||||
public const string ReportNote = "Report generated by LubeLogger, a Free and Open Source Vehicle Maintenance Tracker - LubeLogger.com";
|
||||
public static string GetTitleCaseReminderUrgency(ReminderUrgency input)
|
||||
{
|
||||
switch (input)
|
||||
@@ -29,6 +39,66 @@ namespace CarCareTracker.Helper
|
||||
return input.ToString();
|
||||
}
|
||||
}
|
||||
public static string GetTitleCaseReminderUrgency(string input)
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case "NotUrgent":
|
||||
return "Not Urgent";
|
||||
case "VeryUrgent":
|
||||
return "Very Urgent";
|
||||
case "PastDue":
|
||||
return "Past Due";
|
||||
default:
|
||||
return input;
|
||||
}
|
||||
}
|
||||
public static string GetReminderUrgencyColor(ReminderUrgency input)
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case ReminderUrgency.NotUrgent:
|
||||
return "text-bg-success";
|
||||
case ReminderUrgency.VeryUrgent:
|
||||
return "text-bg-danger";
|
||||
case ReminderUrgency.PastDue:
|
||||
return "text-bg-secondary";
|
||||
default:
|
||||
return "text-bg-warning";
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetPlanRecordColor(PlanPriority input)
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case PlanPriority.Critical:
|
||||
return "text-bg-danger";
|
||||
case PlanPriority.Normal:
|
||||
return "text-bg-primary";
|
||||
case PlanPriority.Low:
|
||||
return "text-bg-info";
|
||||
default:
|
||||
return "text-bg-primary";
|
||||
}
|
||||
}
|
||||
|
||||
public static string GetPlanRecordProgress(PlanProgress input)
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case PlanProgress.Backlog:
|
||||
return "Planned";
|
||||
case PlanProgress.InProgress:
|
||||
return "Doing";
|
||||
case PlanProgress.Testing:
|
||||
return "Testing";
|
||||
case PlanProgress.Done:
|
||||
return "Done";
|
||||
default:
|
||||
return input.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public static string TruncateStrings(string input, int maxLength = 25)
|
||||
{
|
||||
@@ -118,6 +188,10 @@ namespace CarCareTracker.Helper
|
||||
new CostForVehicleByMonth { MonthId = 12, Cost = 0M}
|
||||
};
|
||||
}
|
||||
public static List<string> GetBarChartColors()
|
||||
{
|
||||
return new List<string> { "#00876c", "#43956e", "#67a371", "#89b177", "#a9be80", "#c8cb8b", "#e6d79b", "#e4c281", "#e3ab6b", "#e2925b", "#e07952", "#db5d4f" };
|
||||
}
|
||||
|
||||
public static ServiceRecord GenericToServiceRecord(GenericRecord input)
|
||||
{
|
||||
@@ -170,7 +244,8 @@ namespace CarCareTracker.Helper
|
||||
|
||||
public static List<ExtraField> AddExtraFields(List<ExtraField> recordExtraFields, List<ExtraField> templateExtraFields)
|
||||
{
|
||||
if (!templateExtraFields.Any()) {
|
||||
if (!templateExtraFields.Any())
|
||||
{
|
||||
return new List<ExtraField>();
|
||||
}
|
||||
if (!recordExtraFields.Any())
|
||||
@@ -188,16 +263,20 @@ namespace CarCareTracker.Helper
|
||||
//update isrequired setting
|
||||
foreach (ExtraField extraField in recordExtraFields)
|
||||
{
|
||||
extraField.IsRequired = templateExtraFields.Where(x => x.Name == extraField.Name).First().IsRequired;
|
||||
var firstMatchingField = templateExtraFields.First(x => x.Name == extraField.Name);
|
||||
extraField.IsRequired = firstMatchingField.IsRequired;
|
||||
extraField.FieldType = firstMatchingField.FieldType;
|
||||
}
|
||||
//append extra fields
|
||||
foreach(ExtraField extraField in templateExtraFields)
|
||||
foreach (ExtraField extraField in templateExtraFields)
|
||||
{
|
||||
if (!recordFieldNames.Contains(extraField.Name))
|
||||
{
|
||||
recordExtraFields.Add(extraField);
|
||||
}
|
||||
}
|
||||
//re-order extra fields
|
||||
recordExtraFields = recordExtraFields.OrderBy(x => templateExtraFields.FindIndex(y => y.Name == x.Name)).ToList();
|
||||
return recordExtraFields;
|
||||
}
|
||||
|
||||
@@ -237,27 +316,507 @@ namespace CarCareTracker.Helper
|
||||
if (mailConfig != null && !string.IsNullOrWhiteSpace(mailConfig.EmailServer))
|
||||
{
|
||||
Console.WriteLine($"SMTP Configured for {mailConfig.EmailServer}");
|
||||
} else
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("SMTP Not Configured");
|
||||
}
|
||||
var motd = config["LUBELOGGER_MOTD"] ?? "Not Configured";
|
||||
Console.WriteLine($"Message Of The Day: {motd}");
|
||||
if (string.IsNullOrWhiteSpace(CultureInfo.CurrentCulture.Name))
|
||||
{
|
||||
Console.WriteLine("WARNING: No Locale or Culture Configured for LubeLogger, Check Environment Variables");
|
||||
}
|
||||
//Create folders if they don't exist.
|
||||
if (!Directory.Exists("data"))
|
||||
{
|
||||
Directory.CreateDirectory("data");
|
||||
Console.WriteLine("Created data directory");
|
||||
}
|
||||
if (!Directory.Exists("data/images"))
|
||||
{
|
||||
Console.WriteLine("Created images directory");
|
||||
Directory.CreateDirectory("data/images");
|
||||
}
|
||||
if (!Directory.Exists("data/documents"))
|
||||
{
|
||||
Directory.CreateDirectory("data/documents");
|
||||
Console.WriteLine("Created documents directory");
|
||||
}
|
||||
if (!Directory.Exists("data/translations"))
|
||||
{
|
||||
Directory.CreateDirectory("data/translations");
|
||||
Console.WriteLine("Created translations directory");
|
||||
}
|
||||
if (!Directory.Exists("data/temp"))
|
||||
{
|
||||
Directory.CreateDirectory("data/temp");
|
||||
Console.WriteLine("Created translations directory");
|
||||
}
|
||||
if (!Directory.Exists("data/config"))
|
||||
{
|
||||
Directory.CreateDirectory("data/config");
|
||||
Console.WriteLine("Created config directory");
|
||||
}
|
||||
}
|
||||
public static async void NotifyAsync(string webhookURL, int vehicleId, string username, string action)
|
||||
public static void CheckMigration(string webRootPath, string webContentPath)
|
||||
{
|
||||
//check if current working directory differs from content root.
|
||||
if (Directory.GetCurrentDirectory() != webContentPath)
|
||||
{
|
||||
Console.WriteLine("WARNING: The Working Directory differs from the Web Content Path");
|
||||
Console.WriteLine($"Working Directory: {Directory.GetCurrentDirectory()}");
|
||||
Console.WriteLine($"Web Content Path: {webContentPath}");
|
||||
}
|
||||
//migrates all user-uploaded files from webroot to new data folder
|
||||
//images
|
||||
var imagePath = Path.Combine(webRootPath, "images");
|
||||
var docsPath = Path.Combine(webRootPath, "documents");
|
||||
var translationPath = Path.Combine(webRootPath, "translations");
|
||||
var tempPath = Path.Combine(webRootPath, "temp");
|
||||
if (File.Exists(LegacyUserConfigPath))
|
||||
{
|
||||
File.Move(LegacyUserConfigPath, UserConfigPath, true);
|
||||
}
|
||||
if (Directory.Exists(imagePath))
|
||||
{
|
||||
foreach (string fileToMove in Directory.GetFiles(imagePath))
|
||||
{
|
||||
var newFilePath = $"data/images/{Path.GetFileName(fileToMove)}";
|
||||
File.Move(fileToMove, newFilePath, true);
|
||||
Console.WriteLine($"Migrated Image: {Path.GetFileName(fileToMove)}");
|
||||
}
|
||||
}
|
||||
if (Directory.Exists(docsPath))
|
||||
{
|
||||
foreach (string fileToMove in Directory.GetFiles(docsPath))
|
||||
{
|
||||
var newFilePath = $"data/documents/{Path.GetFileName(fileToMove)}";
|
||||
File.Move(fileToMove, newFilePath, true);
|
||||
Console.WriteLine($"Migrated Document: {Path.GetFileName(fileToMove)}");
|
||||
}
|
||||
}
|
||||
if (Directory.Exists(translationPath))
|
||||
{
|
||||
foreach (string fileToMove in Directory.GetFiles(translationPath))
|
||||
{
|
||||
var newFilePath = $"data/translations/{Path.GetFileName(fileToMove)}";
|
||||
File.Move(fileToMove, newFilePath, true);
|
||||
Console.WriteLine($"Migrated Translation: {Path.GetFileName(fileToMove)}");
|
||||
}
|
||||
}
|
||||
if (Directory.Exists(tempPath))
|
||||
{
|
||||
foreach (string fileToMove in Directory.GetFiles(tempPath))
|
||||
{
|
||||
var newFilePath = $"data/temp/{Path.GetFileName(fileToMove)}";
|
||||
File.Move(fileToMove, newFilePath, true);
|
||||
Console.WriteLine($"Migrated Temp File: {Path.GetFileName(fileToMove)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
public static async void NotifyAsync(string webhookURL, WebHookPayload webHookPayload)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(webhookURL))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var httpClient = new HttpClient();
|
||||
var httpParams = new Dictionary<string, string>
|
||||
if (webhookURL.StartsWith("discord://"))
|
||||
{
|
||||
webhookURL = webhookURL.Replace("discord://", "https://"); //cleanurl
|
||||
//format to discord
|
||||
httpClient.PostAsJsonAsync(webhookURL, DiscordWebHook.FromWebHookPayload(webHookPayload));
|
||||
}
|
||||
else
|
||||
{
|
||||
httpClient.PostAsJsonAsync(webhookURL, webHookPayload);
|
||||
}
|
||||
}
|
||||
public static string GetImportModeIcon(ImportMode importMode)
|
||||
{
|
||||
switch (importMode)
|
||||
{
|
||||
case ImportMode.ServiceRecord:
|
||||
return "bi-card-checklist";
|
||||
case ImportMode.RepairRecord:
|
||||
return "bi-exclamation-octagon";
|
||||
case ImportMode.UpgradeRecord:
|
||||
return "bi-wrench-adjustable";
|
||||
case ImportMode.TaxRecord:
|
||||
return "bi-currency-dollar";
|
||||
case ImportMode.SupplyRecord:
|
||||
return "bi-shop";
|
||||
case ImportMode.PlanRecord:
|
||||
return "bi-bar-chart-steps";
|
||||
case ImportMode.OdometerRecord:
|
||||
return "bi-speedometer";
|
||||
case ImportMode.GasRecord:
|
||||
return "bi-fuel-pump";
|
||||
case ImportMode.NoteRecord:
|
||||
return "bi-journal-bookmark";
|
||||
case ImportMode.ReminderRecord:
|
||||
return "bi-bell";
|
||||
default:
|
||||
return "bi-file-bar-graph";
|
||||
}
|
||||
}
|
||||
public static string GetVehicleIdentifier(Vehicle vehicle)
|
||||
{
|
||||
if (vehicle.VehicleIdentifier == "LicensePlate")
|
||||
{
|
||||
return vehicle.LicensePlate;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (vehicle.ExtraFields.Any(x => x.Name == vehicle.VehicleIdentifier))
|
||||
{
|
||||
{ "vehicleId", vehicleId.ToString() },
|
||||
{ "username", username },
|
||||
{ "action", action },
|
||||
};
|
||||
httpClient.PostAsJsonAsync(webhookURL, httpParams);
|
||||
return vehicle.ExtraFields?.FirstOrDefault(x => x.Name == vehicle.VehicleIdentifier)?.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "N/A";
|
||||
}
|
||||
}
|
||||
}
|
||||
public static string GetVehicleIdentifier(VehicleViewModel vehicle)
|
||||
{
|
||||
if (vehicle.VehicleIdentifier == "LicensePlate")
|
||||
{
|
||||
return vehicle.LicensePlate;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (vehicle.ExtraFields.Any(x => x.Name == vehicle.VehicleIdentifier))
|
||||
{
|
||||
return vehicle.ExtraFields?.FirstOrDefault(x => x.Name == vehicle.VehicleIdentifier)?.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
return "N/A";
|
||||
}
|
||||
}
|
||||
}
|
||||
//Translations
|
||||
public static string GetTranslationDownloadPath(string continent, string name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(continent) || string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (continent)
|
||||
{
|
||||
case "NorthAmerica":
|
||||
continent = "North America";
|
||||
break;
|
||||
case "SouthAmerica":
|
||||
continent = "South America";
|
||||
break;
|
||||
}
|
||||
return $"{TranslationPath}/{continent}/{name}.json";
|
||||
}
|
||||
}
|
||||
public static string GetTranslationName(string name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
string cleanedName = name.Contains("_") ? name.Replace("_", "-") : name;
|
||||
string displayName = CultureInfo.GetCultureInfo(cleanedName).DisplayName;
|
||||
if (string.IsNullOrWhiteSpace(displayName))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
else
|
||||
{
|
||||
return displayName;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
//CSV Write Methods
|
||||
public static void WriteGenericRecordExportModel(CsvWriter _csv, IEnumerable<GenericRecordExportModel> genericRecords)
|
||||
{
|
||||
var extraHeaders = genericRecords.SelectMany(x => x.ExtraFields).Select(y => y.Name).Distinct();
|
||||
//write headers
|
||||
_csv.WriteField(nameof(GenericRecordExportModel.Date));
|
||||
_csv.WriteField(nameof(GenericRecordExportModel.Description));
|
||||
_csv.WriteField(nameof(GenericRecordExportModel.Cost));
|
||||
_csv.WriteField(nameof(GenericRecordExportModel.Notes));
|
||||
_csv.WriteField(nameof(GenericRecordExportModel.Odometer));
|
||||
_csv.WriteField(nameof(GenericRecordExportModel.Tags));
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
_csv.WriteField($"extrafield_{extraHeader}");
|
||||
}
|
||||
_csv.NextRecord();
|
||||
foreach (GenericRecordExportModel genericRecord in genericRecords)
|
||||
{
|
||||
_csv.WriteField(genericRecord.Date);
|
||||
_csv.WriteField(genericRecord.Description);
|
||||
_csv.WriteField(genericRecord.Cost);
|
||||
_csv.WriteField(genericRecord.Notes);
|
||||
_csv.WriteField(genericRecord.Odometer);
|
||||
_csv.WriteField(genericRecord.Tags);
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
var extraField = genericRecord.ExtraFields.Where(x => x.Name == extraHeader).FirstOrDefault();
|
||||
_csv.WriteField(extraField != null ? extraField.Value : string.Empty);
|
||||
}
|
||||
_csv.NextRecord();
|
||||
}
|
||||
}
|
||||
public static void WriteOdometerRecordExportModel(CsvWriter _csv, IEnumerable<OdometerRecordExportModel> genericRecords)
|
||||
{
|
||||
var extraHeaders = genericRecords.SelectMany(x => x.ExtraFields).Select(y => y.Name).Distinct();
|
||||
//write headers
|
||||
_csv.WriteField(nameof(OdometerRecordExportModel.Date));
|
||||
_csv.WriteField(nameof(OdometerRecordExportModel.InitialOdometer));
|
||||
_csv.WriteField(nameof(OdometerRecordExportModel.Odometer));
|
||||
_csv.WriteField(nameof(OdometerRecordExportModel.Notes));
|
||||
_csv.WriteField(nameof(OdometerRecordExportModel.Tags));
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
_csv.WriteField($"extrafield_{extraHeader}");
|
||||
}
|
||||
_csv.NextRecord();
|
||||
foreach (OdometerRecordExportModel genericRecord in genericRecords)
|
||||
{
|
||||
_csv.WriteField(genericRecord.Date);
|
||||
_csv.WriteField(genericRecord.InitialOdometer);
|
||||
_csv.WriteField(genericRecord.Odometer);
|
||||
_csv.WriteField(genericRecord.Notes);
|
||||
_csv.WriteField(genericRecord.Tags);
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
var extraField = genericRecord.ExtraFields.Where(x => x.Name == extraHeader).FirstOrDefault();
|
||||
_csv.WriteField(extraField != null ? extraField.Value : string.Empty);
|
||||
}
|
||||
_csv.NextRecord();
|
||||
}
|
||||
}
|
||||
public static void WriteTaxRecordExportModel(CsvWriter _csv, IEnumerable<TaxRecordExportModel> genericRecords)
|
||||
{
|
||||
var extraHeaders = genericRecords.SelectMany(x => x.ExtraFields).Select(y => y.Name).Distinct();
|
||||
//write headers
|
||||
_csv.WriteField(nameof(TaxRecordExportModel.Date));
|
||||
_csv.WriteField(nameof(TaxRecordExportModel.Description));
|
||||
_csv.WriteField(nameof(TaxRecordExportModel.Cost));
|
||||
_csv.WriteField(nameof(TaxRecordExportModel.Notes));
|
||||
_csv.WriteField(nameof(TaxRecordExportModel.Tags));
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
_csv.WriteField($"extrafield_{extraHeader}");
|
||||
}
|
||||
_csv.NextRecord();
|
||||
foreach (TaxRecordExportModel genericRecord in genericRecords)
|
||||
{
|
||||
_csv.WriteField(genericRecord.Date);
|
||||
_csv.WriteField(genericRecord.Description);
|
||||
_csv.WriteField(genericRecord.Cost);
|
||||
_csv.WriteField(genericRecord.Notes);
|
||||
_csv.WriteField(genericRecord.Tags);
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
var extraField = genericRecord.ExtraFields.Where(x => x.Name == extraHeader).FirstOrDefault();
|
||||
_csv.WriteField(extraField != null ? extraField.Value : string.Empty);
|
||||
}
|
||||
_csv.NextRecord();
|
||||
}
|
||||
}
|
||||
public static void WriteSupplyRecordExportModel(CsvWriter _csv, IEnumerable<SupplyRecordExportModel> genericRecords)
|
||||
{
|
||||
var extraHeaders = genericRecords.SelectMany(x => x.ExtraFields).Select(y => y.Name).Distinct();
|
||||
//write headers
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.Date));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.PartNumber));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.PartSupplier));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.PartQuantity));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.Description));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.Notes));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.Cost));
|
||||
_csv.WriteField(nameof(SupplyRecordExportModel.Tags));
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
_csv.WriteField($"extrafield_{extraHeader}");
|
||||
}
|
||||
_csv.NextRecord();
|
||||
foreach (SupplyRecordExportModel genericRecord in genericRecords)
|
||||
{
|
||||
_csv.WriteField(genericRecord.Date);
|
||||
_csv.WriteField(genericRecord.PartNumber);
|
||||
_csv.WriteField(genericRecord.PartSupplier);
|
||||
_csv.WriteField(genericRecord.PartQuantity);
|
||||
_csv.WriteField(genericRecord.Description);
|
||||
_csv.WriteField(genericRecord.Notes);
|
||||
_csv.WriteField(genericRecord.Cost);
|
||||
_csv.WriteField(genericRecord.Tags);
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
var extraField = genericRecord.ExtraFields.Where(x => x.Name == extraHeader).FirstOrDefault();
|
||||
_csv.WriteField(extraField != null ? extraField.Value : string.Empty);
|
||||
}
|
||||
_csv.NextRecord();
|
||||
}
|
||||
}
|
||||
public static void WritePlanRecordExportModel(CsvWriter _csv, IEnumerable<PlanRecordExportModel> genericRecords)
|
||||
{
|
||||
var extraHeaders = genericRecords.SelectMany(x => x.ExtraFields).Select(y => y.Name).Distinct();
|
||||
//write headers
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.DateCreated));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.DateModified));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.Description));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.Notes));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.Type));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.Priority));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.Progress));
|
||||
_csv.WriteField(nameof(PlanRecordExportModel.Cost));
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
_csv.WriteField($"extrafield_{extraHeader}");
|
||||
}
|
||||
_csv.NextRecord();
|
||||
foreach (PlanRecordExportModel genericRecord in genericRecords)
|
||||
{
|
||||
_csv.WriteField(genericRecord.DateCreated);
|
||||
_csv.WriteField(genericRecord.DateModified);
|
||||
_csv.WriteField(genericRecord.Description);
|
||||
_csv.WriteField(genericRecord.Notes);
|
||||
_csv.WriteField(genericRecord.Type);
|
||||
_csv.WriteField(genericRecord.Priority);
|
||||
_csv.WriteField(genericRecord.Progress);
|
||||
_csv.WriteField(genericRecord.Cost);
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
var extraField = genericRecord.ExtraFields.Where(x => x.Name == extraHeader).FirstOrDefault();
|
||||
_csv.WriteField(extraField != null ? extraField.Value : string.Empty);
|
||||
}
|
||||
_csv.NextRecord();
|
||||
}
|
||||
}
|
||||
public static string HideZeroCost(string input, bool hideZero, string decorations = "")
|
||||
{
|
||||
if (input == 0M.ToString("C2") && hideZero)
|
||||
{
|
||||
return "---";
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(decorations) ? input : $"{input}{decorations}";
|
||||
}
|
||||
}
|
||||
public static string HideZeroCost(decimal input, bool hideZero, string decorations = "")
|
||||
{
|
||||
if (input == default && hideZero)
|
||||
{
|
||||
return "---";
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(decorations) ? input.ToString("C2") : $"{input.ToString("C2")}{decorations}";
|
||||
}
|
||||
}
|
||||
public static JsonSerializerOptions GetInvariantOption()
|
||||
{
|
||||
var serializerOption = new JsonSerializerOptions();
|
||||
serializerOption.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||
serializerOption.Converters.Add(new InvariantConverter());
|
||||
return serializerOption;
|
||||
}
|
||||
public static void WriteGasRecordExportModel(CsvWriter _csv, IEnumerable<GasRecordExportModel> genericRecords)
|
||||
{
|
||||
var extraHeaders = genericRecords.SelectMany(x => x.ExtraFields).Select(y => y.Name).Distinct();
|
||||
//write headers
|
||||
_csv.WriteField(nameof(GasRecordExportModel.Date));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.Odometer));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.FuelConsumed));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.Cost));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.FuelEconomy));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.IsFillToFull));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.MissedFuelUp));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.Notes));
|
||||
_csv.WriteField(nameof(GasRecordExportModel.Tags));
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
_csv.WriteField($"extrafield_{extraHeader}");
|
||||
}
|
||||
_csv.NextRecord();
|
||||
foreach (GasRecordExportModel genericRecord in genericRecords)
|
||||
{
|
||||
_csv.WriteField(genericRecord.Date);
|
||||
_csv.WriteField(genericRecord.Odometer);
|
||||
_csv.WriteField(genericRecord.FuelConsumed);
|
||||
_csv.WriteField(genericRecord.Cost);
|
||||
_csv.WriteField(genericRecord.FuelEconomy);
|
||||
_csv.WriteField(genericRecord.IsFillToFull);
|
||||
_csv.WriteField(genericRecord.MissedFuelUp);
|
||||
_csv.WriteField(genericRecord.Notes);
|
||||
_csv.WriteField(genericRecord.Tags);
|
||||
foreach (string extraHeader in extraHeaders)
|
||||
{
|
||||
var extraField = genericRecord.ExtraFields.Where(x => x.Name == extraHeader).FirstOrDefault();
|
||||
_csv.WriteField(extraField != null ? extraField.Value : string.Empty);
|
||||
}
|
||||
_csv.NextRecord();
|
||||
}
|
||||
}
|
||||
public static byte[] RemindersToCalendar(List<ReminderRecordViewModel> reminders)
|
||||
{
|
||||
//converts reminders to iCal file
|
||||
StringBuilder sb = new StringBuilder();
|
||||
//start the calendar item
|
||||
sb.AppendLine("BEGIN:VCALENDAR");
|
||||
sb.AppendLine("VERSION:2.0");
|
||||
sb.AppendLine("PRODID:lubelogger.com");
|
||||
sb.AppendLine("CALSCALE:GREGORIAN");
|
||||
sb.AppendLine("METHOD:PUBLISH");
|
||||
|
||||
//create events.
|
||||
foreach(ReminderRecordViewModel reminder in reminders)
|
||||
{
|
||||
var dtStart = reminder.Date.Date.ToString("yyyyMMddTHHmm00");
|
||||
var dtEnd = reminder.Date.Date.AddDays(1).AddMilliseconds(-1).ToString("yyyyMMddTHHmm00");
|
||||
var calendarUID = new Guid(MD5.HashData(Encoding.UTF8.GetBytes($"{dtStart}_{reminder.Description}")));
|
||||
sb.AppendLine("BEGIN:VEVENT");
|
||||
sb.AppendLine("DTSTAMP:" + DateTime.Now.ToString("yyyyMMddTHHmm00"));
|
||||
sb.AppendLine("UID:" + calendarUID);
|
||||
sb.AppendLine("DTSTART:" + dtStart);
|
||||
sb.AppendLine("DTEND:" + dtEnd);
|
||||
sb.AppendLine($"SUMMARY:{reminder.Description}");
|
||||
sb.AppendLine($"DESCRIPTION:{reminder.Description}");
|
||||
switch (reminder.Urgency)
|
||||
{
|
||||
case ReminderUrgency.NotUrgent:
|
||||
sb.AppendLine("PRIORITY:3");
|
||||
break;
|
||||
case ReminderUrgency.Urgent:
|
||||
sb.AppendLine("PRIORITY:2");
|
||||
break;
|
||||
case ReminderUrgency.VeryUrgent:
|
||||
sb.AppendLine("PRIORITY:1");
|
||||
break;
|
||||
case ReminderUrgency.PastDue:
|
||||
sb.AppendLine("PRIORITY:1");
|
||||
break;
|
||||
}
|
||||
sb.AppendLine("END:VEVENT");
|
||||
}
|
||||
|
||||
//end calendar item
|
||||
sb.AppendLine("END:VCALENDAR");
|
||||
string calendarContent = sb.ToString();
|
||||
return Encoding.UTF8.GetBytes(calendarContent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace CarCareTracker.Helper
|
||||
@@ -6,17 +7,22 @@ namespace CarCareTracker.Helper
|
||||
public interface ITranslationHelper
|
||||
{
|
||||
string Translate(string userLanguage, string text);
|
||||
Dictionary<string, string> GetTranslations(string userLanguage);
|
||||
OperationResponse SaveTranslation(string userLanguage, Dictionary<string, string> translations);
|
||||
string ExportTranslation(Dictionary<string, string> translations);
|
||||
}
|
||||
public class TranslationHelper : ITranslationHelper
|
||||
{
|
||||
private readonly IFileHelper _fileHelper;
|
||||
private readonly IConfiguration _config;
|
||||
private readonly ILogger<ITranslationHelper> _logger;
|
||||
private IMemoryCache _cache;
|
||||
public TranslationHelper(IFileHelper fileHelper, IConfiguration config, IMemoryCache memoryCache)
|
||||
public TranslationHelper(IFileHelper fileHelper, IConfiguration config, IMemoryCache memoryCache, ILogger<ITranslationHelper> logger)
|
||||
{
|
||||
_fileHelper = fileHelper;
|
||||
_config = config;
|
||||
_cache = memoryCache;
|
||||
_logger = logger;
|
||||
}
|
||||
public string Translate(string userLanguage, string text)
|
||||
{
|
||||
@@ -36,11 +42,13 @@ namespace CarCareTracker.Helper
|
||||
return translationDictionary ?? new Dictionary<string, string>();
|
||||
} catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError($"Could not find translation file for {userLanguage}");
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
});
|
||||
@@ -52,10 +60,138 @@ namespace CarCareTracker.Helper
|
||||
{
|
||||
//create entry
|
||||
dictionary.Add(translationKey, text);
|
||||
_logger.LogInformation($"Translation key added to {userLanguage} for {translationKey} with value {text}");
|
||||
File.WriteAllText(translationFilePath, JsonSerializer.Serialize(dictionary));
|
||||
return text;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
private Dictionary<string, string> GetDefaultTranslation()
|
||||
{
|
||||
//this method always returns en_US translation.
|
||||
var translationFilePath = _fileHelper.GetFullFilePath($"/defaults/en_US.json");
|
||||
if (!string.IsNullOrWhiteSpace(translationFilePath))
|
||||
{
|
||||
//file exists.
|
||||
try
|
||||
{
|
||||
var translationFile = File.ReadAllText(translationFilePath);
|
||||
var translationDictionary = JsonSerializer.Deserialize<Dictionary<string, string>>(translationFile);
|
||||
return translationDictionary ?? new Dictionary<string, string>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
}
|
||||
_logger.LogError($"Could not find translation file for en_US");
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
public Dictionary<string, string> GetTranslations(string userLanguage)
|
||||
{
|
||||
var defaultTranslation = GetDefaultTranslation();
|
||||
if (userLanguage == "en_US")
|
||||
{
|
||||
return defaultTranslation;
|
||||
}
|
||||
var translationFilePath = _fileHelper.GetFullFilePath($"/translations/{userLanguage}.json");
|
||||
if (!string.IsNullOrWhiteSpace(translationFilePath))
|
||||
{
|
||||
//file exists.
|
||||
try
|
||||
{
|
||||
var translationFile = File.ReadAllText(translationFilePath);
|
||||
var translationDictionary = JsonSerializer.Deserialize<Dictionary<string, string>>(translationFile);
|
||||
if (translationDictionary != null)
|
||||
{
|
||||
foreach(var translation in translationDictionary)
|
||||
{
|
||||
if (defaultTranslation.ContainsKey(translation.Key))
|
||||
{
|
||||
defaultTranslation[translation.Key] = translation.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return defaultTranslation ?? new Dictionary<string, string>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
}
|
||||
_logger.LogError($"Could not find translation file for {userLanguage}");
|
||||
return new Dictionary<string, string>();
|
||||
}
|
||||
public OperationResponse SaveTranslation(string userLanguage, Dictionary<string, string> translations)
|
||||
{
|
||||
bool create = bool.Parse(_config["LUBELOGGER_TRANSLATOR"] ?? "false");
|
||||
bool isDefaultLanguage = userLanguage == "en_US";
|
||||
if (isDefaultLanguage && !create)
|
||||
{
|
||||
return OperationResponse.Failed("The translation file name en_US is reserved.");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(userLanguage))
|
||||
{
|
||||
return OperationResponse.Failed("File name is not provided.");
|
||||
}
|
||||
if (!translations.Any())
|
||||
{
|
||||
return OperationResponse.Failed("Translation has no data.");
|
||||
}
|
||||
var translationFilePath = isDefaultLanguage ? _fileHelper.GetFullFilePath($"/defaults/en_US.json") : _fileHelper.GetFullFilePath($"/translations/{userLanguage}.json", false);
|
||||
try
|
||||
{
|
||||
if (File.Exists(translationFilePath))
|
||||
{
|
||||
//write to file
|
||||
File.WriteAllText(translationFilePath, JsonSerializer.Serialize(translations));
|
||||
_cache.Remove($"lang_{userLanguage}"); //clear out cache, force a reload from file.
|
||||
} else
|
||||
{
|
||||
//check if directory exists first.
|
||||
var translationDirectory = _fileHelper.GetFullFilePath("translations/", false);
|
||||
if (!Directory.Exists(translationDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(translationDirectory);
|
||||
}
|
||||
//write to file
|
||||
File.WriteAllText(translationFilePath, JsonSerializer.Serialize(translations));
|
||||
}
|
||||
return OperationResponse.Succeed("Translation Updated");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public string ExportTranslation(Dictionary<string, string> translations)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tempFileName = $"/temp/{Guid.NewGuid()}.json";
|
||||
string uploadDirectory = _fileHelper.GetFullFilePath("temp/", false);
|
||||
if (!Directory.Exists(uploadDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(uploadDirectory);
|
||||
}
|
||||
var saveFilePath = _fileHelper.GetFullFilePath(tempFileName, false);
|
||||
//standardize translation format for export only.
|
||||
Dictionary<string, string> sortedTranslations = new Dictionary<string, string>();
|
||||
foreach (var translation in translations.OrderBy(x => x.Key))
|
||||
{
|
||||
sortedTranslations.Add(translation.Key, translation.Value);
|
||||
};
|
||||
File.WriteAllText(saveFilePath, JsonSerializer.Serialize(sortedTranslations, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return tempFileName;
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
7
LICENSE
7
LICENSE
@@ -1,11 +1,6 @@
|
||||
LubeLogger by Hargata Softworks is licensed under the MIT License for individual
|
||||
and personal use. Commercial users and/or corporate entities are required
|
||||
to maintain an active subscription in order to continue using LubeLogger.
|
||||
For pricing information please contact us at hargatasoftworks@gmail.com
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Hargata Softworks
|
||||
Copyright (c) 2024 Hargata Softworks
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
@@ -20,6 +21,7 @@ namespace CarCareTracker.Logic
|
||||
OperationResponse RequestResetPassword(LoginModel credentials);
|
||||
OperationResponse ResetPasswordByUser(LoginModel credentials);
|
||||
OperationResponse ResetUserPassword(LoginModel credentials);
|
||||
OperationResponse SendRegistrationToken(LoginModel credentials);
|
||||
UserData ValidateUserCredentials(LoginModel credentials);
|
||||
UserData ValidateOpenIDUser(LoginModel credentials);
|
||||
bool CheckIfUserIsValid(int userId);
|
||||
@@ -28,7 +30,7 @@ namespace CarCareTracker.Logic
|
||||
bool GenerateTokenForEmailAddress(string emailAddress, bool isPasswordReset);
|
||||
List<UserData> GetAllUsers();
|
||||
List<Token> GetAllTokens();
|
||||
|
||||
KeyValuePair<string, string> GetPKCEChallengeCode();
|
||||
}
|
||||
public class LoginLogic : ILoginLogic
|
||||
{
|
||||
@@ -70,13 +72,13 @@ namespace CarCareTracker.Logic
|
||||
var existingUser = _userData.GetUserRecordById(userId);
|
||||
if (existingUser.Id == default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Invalid user" };
|
||||
return OperationResponse.Failed("Invalid user");
|
||||
}
|
||||
//validate user token
|
||||
var existingToken = _tokenData.GetTokenRecordByBody(credentials.Token);
|
||||
if (existingToken.Id == default || existingToken.EmailAddress != existingUser.EmailAddress)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Invalid Token" };
|
||||
return OperationResponse.Failed("Invalid Token");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(credentials.UserName) && existingUser.UserName != credentials.UserName)
|
||||
{
|
||||
@@ -84,7 +86,7 @@ namespace CarCareTracker.Logic
|
||||
var existingUserWithUserName = _userData.GetUserRecordByUserName(credentials.UserName);
|
||||
if (existingUserWithUserName.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Username already taken" };
|
||||
return OperationResponse.Failed("Username already taken");
|
||||
}
|
||||
existingUser.UserName = credentials.UserName;
|
||||
}
|
||||
@@ -94,7 +96,7 @@ namespace CarCareTracker.Logic
|
||||
var existingUserWithEmailAddress = _userData.GetUserRecordByEmailAddress(credentials.EmailAddress);
|
||||
if (existingUserWithEmailAddress.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "A user with that email already exists" };
|
||||
return OperationResponse.Failed("A user with that email already exists");
|
||||
}
|
||||
existingUser.EmailAddress = credentials.EmailAddress;
|
||||
}
|
||||
@@ -106,7 +108,7 @@ namespace CarCareTracker.Logic
|
||||
//delete token
|
||||
_tokenData.DeleteToken(existingToken.Id);
|
||||
var result = _userData.SaveUserRecord(existingUser);
|
||||
return new OperationResponse { Success = result, Message = result ? "User Updated" : StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Conditional(result, "User Updated", string.Empty);
|
||||
}
|
||||
public OperationResponse RegisterOpenIdUser(LoginModel credentials)
|
||||
{
|
||||
@@ -114,21 +116,21 @@ namespace CarCareTracker.Logic
|
||||
var existingToken = _tokenData.GetTokenRecordByBody(credentials.Token);
|
||||
if (existingToken.Id == default || existingToken.EmailAddress != credentials.EmailAddress)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Invalid Token" };
|
||||
return OperationResponse.Failed("Invalid Token");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(credentials.EmailAddress) || string.IsNullOrWhiteSpace(credentials.UserName))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Username cannot be blank" };
|
||||
return OperationResponse.Failed("Username cannot be blank");
|
||||
}
|
||||
var existingUser = _userData.GetUserRecordByUserName(credentials.UserName);
|
||||
if (existingUser.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Username already taken" };
|
||||
return OperationResponse.Failed("Username already taken");
|
||||
}
|
||||
var existingUserWithEmail = _userData.GetUserRecordByEmailAddress(credentials.EmailAddress);
|
||||
if (existingUserWithEmail.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "A user with that email already exists" };
|
||||
return OperationResponse.Failed("A user with that email already exists");
|
||||
}
|
||||
_tokenData.DeleteToken(existingToken.Id);
|
||||
var newUser = new UserData()
|
||||
@@ -140,11 +142,11 @@ namespace CarCareTracker.Logic
|
||||
var result = _userData.SaveUserRecord(newUser);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "You will be logged in briefly." };
|
||||
return OperationResponse.Succeed("You will be logged in briefly.");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Something went wrong, please try again later." };
|
||||
return OperationResponse.Failed("Something went wrong, please try again later.");
|
||||
}
|
||||
}
|
||||
//handles user registration
|
||||
@@ -154,22 +156,22 @@ namespace CarCareTracker.Logic
|
||||
var existingToken = _tokenData.GetTokenRecordByBody(credentials.Token);
|
||||
if (existingToken.Id == default || existingToken.EmailAddress != credentials.EmailAddress)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Invalid Token" };
|
||||
return OperationResponse.Failed("Invalid Token");
|
||||
}
|
||||
//token is valid, check if username and password is acceptable and that username is unique.
|
||||
if (string.IsNullOrWhiteSpace(credentials.EmailAddress) || string.IsNullOrWhiteSpace(credentials.UserName) || string.IsNullOrWhiteSpace(credentials.Password))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Neither username nor password can be blank" };
|
||||
return OperationResponse.Failed("Neither username nor password can be blank");
|
||||
}
|
||||
var existingUser = _userData.GetUserRecordByUserName(credentials.UserName);
|
||||
if (existingUser.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Username already taken" };
|
||||
return OperationResponse.Failed("Username already taken");
|
||||
}
|
||||
var existingUserWithEmail = _userData.GetUserRecordByEmailAddress(credentials.EmailAddress);
|
||||
if (existingUserWithEmail.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "A user with that email already exists" };
|
||||
return OperationResponse.Failed("A user with that email already exists");
|
||||
}
|
||||
//username is unique then we delete the token and create the user.
|
||||
_tokenData.DeleteToken(existingToken.Id);
|
||||
@@ -182,11 +184,21 @@ namespace CarCareTracker.Logic
|
||||
var result = _userData.SaveUserRecord(newUser);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "You will be redirected to the login page briefly." };
|
||||
return OperationResponse.Succeed("You will be redirected to the login page briefly.");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Something went wrong, please try again later." };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public OperationResponse SendRegistrationToken(LoginModel credentials)
|
||||
{
|
||||
if (_configHelper.GetServerOpenRegistration())
|
||||
{
|
||||
return GenerateUserToken(credentials.EmailAddress, true);
|
||||
} else
|
||||
{
|
||||
return OperationResponse.Failed("Open Registration Disabled");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -204,24 +216,24 @@ namespace CarCareTracker.Logic
|
||||
}
|
||||
//for security purposes we want to always return true for this method.
|
||||
//otherwise someone can spam the reset password method to sniff out users.
|
||||
return new OperationResponse { Success = true, Message = "If your user exists in the system you should receive an email shortly with instructions on how to proceed." };
|
||||
return OperationResponse.Succeed("If your user exists in the system you should receive an email shortly with instructions on how to proceed.");
|
||||
}
|
||||
public OperationResponse ResetPasswordByUser(LoginModel credentials)
|
||||
{
|
||||
var existingToken = _tokenData.GetTokenRecordByBody(credentials.Token);
|
||||
if (existingToken.Id == default || existingToken.EmailAddress != credentials.EmailAddress)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Invalid Token" };
|
||||
return OperationResponse.Failed("Invalid Token");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(credentials.Password))
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "New Password cannot be blank" };
|
||||
return OperationResponse.Failed("New Password cannot be blank");
|
||||
}
|
||||
//if token is valid.
|
||||
var existingUser = _userData.GetUserRecordByEmailAddress(credentials.EmailAddress);
|
||||
if (existingUser.Id == default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Unable to locate user" };
|
||||
return OperationResponse.Failed("Unable to locate user");
|
||||
}
|
||||
existingUser.Password = GetHash(credentials.Password);
|
||||
var result = _userData.SaveUserRecord(existingUser);
|
||||
@@ -229,10 +241,10 @@ namespace CarCareTracker.Logic
|
||||
_tokenData.DeleteToken(existingToken.Id);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "Password resetted, you will be redirected to login page shortly." };
|
||||
return OperationResponse.Succeed("Password resetted, you will be redirected to login page shortly.");
|
||||
} else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
@@ -244,14 +256,7 @@ namespace CarCareTracker.Logic
|
||||
{
|
||||
if (UserIsRoot(credentials))
|
||||
{
|
||||
return new UserData()
|
||||
{
|
||||
Id = -1,
|
||||
UserName = credentials.UserName,
|
||||
IsAdmin = true,
|
||||
IsRootUser = true,
|
||||
EmailAddress = string.Empty
|
||||
};
|
||||
return GetRootUserData(credentials.UserName);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -270,6 +275,13 @@ namespace CarCareTracker.Logic
|
||||
}
|
||||
public UserData ValidateOpenIDUser(LoginModel credentials)
|
||||
{
|
||||
//validate for root user
|
||||
var isRootUser = _configHelper.AuthenticateRootUserOIDC(credentials.EmailAddress);
|
||||
if (isRootUser)
|
||||
{
|
||||
return GetRootUserData(credentials.EmailAddress);
|
||||
}
|
||||
|
||||
var result = _userData.GetUserRecordByEmailAddress(credentials.EmailAddress);
|
||||
if (result.Id != default)
|
||||
{
|
||||
@@ -309,7 +321,18 @@ namespace CarCareTracker.Logic
|
||||
var existingToken = _tokenData.GetTokenRecordByEmailAddress(emailAddress);
|
||||
if (existingToken.Id != default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "There is an existing token tied to this email address" };
|
||||
if (autoNotify) //re-send email
|
||||
{
|
||||
var notificationResult = _mailHelper.NotifyUserForRegistration(emailAddress, existingToken.Body);
|
||||
if (notificationResult.Success)
|
||||
{
|
||||
return OperationResponse.Failed($"There is an existing token tied to {emailAddress}, a new email has been sent out");
|
||||
} else
|
||||
{
|
||||
return notificationResult;
|
||||
}
|
||||
}
|
||||
return OperationResponse.Failed($"There is an existing token tied to {emailAddress}");
|
||||
}
|
||||
var token = new Token()
|
||||
{
|
||||
@@ -322,16 +345,16 @@ namespace CarCareTracker.Logic
|
||||
result = _mailHelper.NotifyUserForRegistration(emailAddress, token.Body).Success;
|
||||
if (!result)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Token Generated, but Email failed to send, please check your SMTP settings." };
|
||||
return OperationResponse.Failed("Token Generated, but Email failed to send, please check your SMTP settings.");
|
||||
}
|
||||
}
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "Token Generated!" };
|
||||
return OperationResponse.Succeed("Token Generated!");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
public bool DeleteUserToken(int tokenId)
|
||||
@@ -350,18 +373,18 @@ namespace CarCareTracker.Logic
|
||||
var existingUser = _userData.GetUserRecordByUserName(credentials.UserName);
|
||||
if (existingUser.Id == default)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Unable to find user" };
|
||||
return OperationResponse.Failed("Unable to find user");
|
||||
}
|
||||
var newPassword = Guid.NewGuid().ToString().Substring(0, 8);
|
||||
existingUser.Password = GetHash(newPassword);
|
||||
var result = _userData.SaveUserRecord(existingUser);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = newPassword };
|
||||
return OperationResponse.Succeed(newPassword);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "Something went wrong, please try again later." };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@@ -419,6 +442,17 @@ namespace CarCareTracker.Logic
|
||||
var hashedPassword = GetHash(credentials.Password);
|
||||
return _configHelper.AuthenticateRootUser(hashedUserName, hashedPassword);
|
||||
}
|
||||
private UserData GetRootUserData(string username)
|
||||
{
|
||||
return new UserData()
|
||||
{
|
||||
Id = -1,
|
||||
UserName = username,
|
||||
IsAdmin = true,
|
||||
IsRootUser = true,
|
||||
EmailAddress = string.Empty
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
private static string GetHash(string value)
|
||||
{
|
||||
@@ -439,6 +473,14 @@ namespace CarCareTracker.Logic
|
||||
{
|
||||
return Guid.NewGuid().ToString().Substring(0, 8);
|
||||
}
|
||||
public KeyValuePair<string, string> GetPKCEChallengeCode()
|
||||
{
|
||||
var verifierCode = Base64UrlEncoder.Encode(Guid.NewGuid().ToString().Replace("-", ""));
|
||||
var verifierBytes = Encoding.UTF8.GetBytes(verifierCode);
|
||||
var hashedCode = SHA256.Create().ComputeHash(verifierBytes);
|
||||
var encodedChallengeCode = Base64UrlEncoder.Encode(hashedCode);
|
||||
return new KeyValuePair<string, string>(verifierCode, encodedChallengeCode);
|
||||
}
|
||||
public bool GenerateTokenForEmailAddress(string emailAddress, bool isPasswordReset)
|
||||
{
|
||||
bool result = false;
|
||||
|
||||
@@ -33,6 +33,10 @@ namespace CarCareTracker.Logic
|
||||
}
|
||||
public bool AutoInsertOdometerRecord(OdometerRecord odometer)
|
||||
{
|
||||
if (odometer.Mileage == default)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var lastReportedMileage = GetLastOdometerRecordMileage(odometer.VehicleId, new List<OdometerRecord>());
|
||||
odometer.InitialMileage = lastReportedMileage != default ? lastReportedMileage : odometer.Mileage;
|
||||
|
||||
|
||||
@@ -51,16 +51,16 @@ namespace CarCareTracker.Logic
|
||||
var userAccess = _userAccess.GetUserAccessByVehicleAndUserId(existingUser.Id, vehicleId);
|
||||
if (userAccess != null)
|
||||
{
|
||||
return new OperationResponse { Success = false, Message = "User is already a collaborator" };
|
||||
return OperationResponse.Failed("User is already a collaborator");
|
||||
}
|
||||
var result = AddUserAccessToVehicle(existingUser.Id, vehicleId);
|
||||
if (result)
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = "Collaborator Added" };
|
||||
return OperationResponse.Succeed("Collaborator Added");
|
||||
}
|
||||
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
|
||||
return OperationResponse.Failed();
|
||||
}
|
||||
return new OperationResponse { Success = false, Message = $"Unable to find user {username} in the system" };
|
||||
return OperationResponse.Failed($"Unable to find user {username} in the system");
|
||||
}
|
||||
public bool DeleteCollaboratorFromVehicle(int userId, int vehicleId)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using CarCareTracker.External.Interfaces;
|
||||
using CarCareTracker.Controllers;
|
||||
using CarCareTracker.External.Interfaces;
|
||||
using CarCareTracker.Helper;
|
||||
using CarCareTracker.Models;
|
||||
|
||||
@@ -6,9 +7,19 @@ namespace CarCareTracker.Logic
|
||||
{
|
||||
public interface IVehicleLogic
|
||||
{
|
||||
VehicleRecords GetVehicleRecords(int vehicleId);
|
||||
decimal GetVehicleTotalCost(VehicleRecords vehicleRecords);
|
||||
int GetMaxMileage(int vehicleId);
|
||||
int GetMaxMileage(VehicleRecords vehicleRecords);
|
||||
int GetMinMileage(int vehicleId);
|
||||
bool GetVehicleHasUrgentOrPastDueReminders(int vehicleId);
|
||||
int GetMinMileage(VehicleRecords vehicleRecords);
|
||||
int GetOwnershipDays(string purchaseDate, string soldDate, int year, List<ServiceRecord> serviceRecords, List<CollisionRecord> repairRecords, List<GasRecord> gasRecords, List<UpgradeRecord> upgradeRecords, List<OdometerRecord> odometerRecords, List<TaxRecord> taxRecords);
|
||||
bool GetVehicleHasUrgentOrPastDueReminders(int vehicleId, int currentMileage);
|
||||
List<VehicleInfo> GetVehicleInfo(List<Vehicle> vehicles);
|
||||
List<ReminderRecordViewModel> GetReminders(List<Vehicle> vehicles, bool isCalendar);
|
||||
List<PlanRecord> GetPlans(List<Vehicle> vehicles, bool excludeDone);
|
||||
bool UpdateRecurringTaxes(int vehicleId);
|
||||
void RestoreSupplyRecordsByUsage(List<SupplyUsageHistory> supplyUsage, string usageDescription);
|
||||
}
|
||||
public class VehicleLogic: IVehicleLogic
|
||||
{
|
||||
@@ -16,25 +27,62 @@ namespace CarCareTracker.Logic
|
||||
private readonly IGasRecordDataAccess _gasRecordDataAccess;
|
||||
private readonly ICollisionRecordDataAccess _collisionRecordDataAccess;
|
||||
private readonly IUpgradeRecordDataAccess _upgradeRecordDataAccess;
|
||||
private readonly ITaxRecordDataAccess _taxRecordDataAccess;
|
||||
private readonly IOdometerRecordDataAccess _odometerRecordDataAccess;
|
||||
private readonly IReminderRecordDataAccess _reminderRecordDataAccess;
|
||||
private readonly IPlanRecordDataAccess _planRecordDataAccess;
|
||||
private readonly IReminderHelper _reminderHelper;
|
||||
private readonly IVehicleDataAccess _dataAccess;
|
||||
private readonly ISupplyRecordDataAccess _supplyRecordDataAccess;
|
||||
private readonly ILogger<VehicleLogic> _logger;
|
||||
|
||||
public VehicleLogic(
|
||||
IServiceRecordDataAccess serviceRecordDataAccess,
|
||||
IGasRecordDataAccess gasRecordDataAccess,
|
||||
ICollisionRecordDataAccess collisionRecordDataAccess,
|
||||
IUpgradeRecordDataAccess upgradeRecordDataAccess,
|
||||
ITaxRecordDataAccess taxRecordDataAccess,
|
||||
IOdometerRecordDataAccess odometerRecordDataAccess,
|
||||
IReminderRecordDataAccess reminderRecordDataAccess,
|
||||
IReminderHelper reminderHelper
|
||||
IPlanRecordDataAccess planRecordDataAccess,
|
||||
IReminderHelper reminderHelper,
|
||||
IVehicleDataAccess dataAccess,
|
||||
ISupplyRecordDataAccess supplyRecordDataAccess,
|
||||
ILogger<VehicleLogic> logger
|
||||
) {
|
||||
_serviceRecordDataAccess = serviceRecordDataAccess;
|
||||
_gasRecordDataAccess = gasRecordDataAccess;
|
||||
_collisionRecordDataAccess = collisionRecordDataAccess;
|
||||
_upgradeRecordDataAccess = upgradeRecordDataAccess;
|
||||
_taxRecordDataAccess = taxRecordDataAccess;
|
||||
_odometerRecordDataAccess = odometerRecordDataAccess;
|
||||
_planRecordDataAccess = planRecordDataAccess;
|
||||
_reminderRecordDataAccess = reminderRecordDataAccess;
|
||||
_reminderHelper = reminderHelper;
|
||||
_dataAccess = dataAccess;
|
||||
_supplyRecordDataAccess = supplyRecordDataAccess;
|
||||
_logger = logger;
|
||||
}
|
||||
public VehicleRecords GetVehicleRecords(int vehicleId)
|
||||
{
|
||||
return new VehicleRecords
|
||||
{
|
||||
ServiceRecords = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicleId),
|
||||
GasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicleId),
|
||||
CollisionRecords = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicleId),
|
||||
TaxRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId),
|
||||
UpgradeRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicleId),
|
||||
OdometerRecords = _odometerRecordDataAccess.GetOdometerRecordsByVehicleId(vehicleId),
|
||||
};
|
||||
}
|
||||
public decimal GetVehicleTotalCost(VehicleRecords vehicleRecords)
|
||||
{
|
||||
var serviceRecordSum = vehicleRecords.ServiceRecords.Sum(x => x.Cost);
|
||||
var repairRecordSum = vehicleRecords.CollisionRecords.Sum(x => x.Cost);
|
||||
var upgradeRecordSum = vehicleRecords.UpgradeRecords.Sum(x => x.Cost);
|
||||
var taxRecordSum = vehicleRecords.TaxRecords.Sum(x => x.Cost);
|
||||
var gasRecordSum = vehicleRecords.GasRecords.Sum(x => x.Cost);
|
||||
return serviceRecordSum + repairRecordSum + upgradeRecordSum + taxRecordSum + gasRecordSum;
|
||||
}
|
||||
public int GetMaxMileage(int vehicleId)
|
||||
{
|
||||
@@ -66,6 +114,31 @@ namespace CarCareTracker.Logic
|
||||
}
|
||||
return numbersArray.Any() ? numbersArray.Max() : 0;
|
||||
}
|
||||
public int GetMaxMileage(VehicleRecords vehicleRecords)
|
||||
{
|
||||
var numbersArray = new List<int>();
|
||||
if (vehicleRecords.ServiceRecords.Any())
|
||||
{
|
||||
numbersArray.Add(vehicleRecords.ServiceRecords.Max(x => x.Mileage));
|
||||
}
|
||||
if (vehicleRecords.CollisionRecords.Any())
|
||||
{
|
||||
numbersArray.Add(vehicleRecords.CollisionRecords.Max(x => x.Mileage));
|
||||
}
|
||||
if (vehicleRecords.GasRecords.Any())
|
||||
{
|
||||
numbersArray.Add(vehicleRecords.GasRecords.Max(x => x.Mileage));
|
||||
}
|
||||
if (vehicleRecords.UpgradeRecords.Any())
|
||||
{
|
||||
numbersArray.Add(vehicleRecords.UpgradeRecords.Max(x => x.Mileage));
|
||||
}
|
||||
if (vehicleRecords.OdometerRecords.Any())
|
||||
{
|
||||
numbersArray.Add(vehicleRecords.OdometerRecords.Max(x => x.Mileage));
|
||||
}
|
||||
return numbersArray.Any() ? numbersArray.Max() : 0;
|
||||
}
|
||||
public int GetMinMileage(int vehicleId)
|
||||
{
|
||||
var numbersArray = new List<int>();
|
||||
@@ -96,12 +169,281 @@ namespace CarCareTracker.Logic
|
||||
}
|
||||
return numbersArray.Any() ? numbersArray.Min() : 0;
|
||||
}
|
||||
public bool GetVehicleHasUrgentOrPastDueReminders(int vehicleId)
|
||||
public int GetMinMileage(VehicleRecords vehicleRecords)
|
||||
{
|
||||
var numbersArray = new List<int>();
|
||||
var _serviceRecords = vehicleRecords.ServiceRecords.Where(x => x.Mileage != default).ToList();
|
||||
if (_serviceRecords.Any())
|
||||
{
|
||||
numbersArray.Add(_serviceRecords.Min(x => x.Mileage));
|
||||
}
|
||||
var _repairRecords = vehicleRecords.CollisionRecords.Where(x => x.Mileage != default).ToList();
|
||||
if (_repairRecords.Any())
|
||||
{
|
||||
numbersArray.Add(_repairRecords.Min(x => x.Mileage));
|
||||
}
|
||||
var _gasRecords = vehicleRecords.GasRecords.Where(x => x.Mileage != default).ToList();
|
||||
if (_gasRecords.Any())
|
||||
{
|
||||
numbersArray.Add(_gasRecords.Min(x => x.Mileage));
|
||||
}
|
||||
var _upgradeRecords = vehicleRecords.UpgradeRecords.Where(x => x.Mileage != default).ToList();
|
||||
if (_upgradeRecords.Any())
|
||||
{
|
||||
numbersArray.Add(_upgradeRecords.Min(x => x.Mileage));
|
||||
}
|
||||
var _odometerRecords = vehicleRecords.OdometerRecords.Where(x => x.Mileage != default).ToList();
|
||||
if (_odometerRecords.Any())
|
||||
{
|
||||
numbersArray.Add(_odometerRecords.Min(x => x.Mileage));
|
||||
}
|
||||
return numbersArray.Any() ? numbersArray.Min() : 0;
|
||||
}
|
||||
public int GetOwnershipDays(string purchaseDate, string soldDate, int year, List<ServiceRecord> serviceRecords, List<CollisionRecord> repairRecords, List<GasRecord> gasRecords, List<UpgradeRecord> upgradeRecords, List<OdometerRecord> odometerRecords, List<TaxRecord> taxRecords)
|
||||
{
|
||||
var startDate = DateTime.Now;
|
||||
var endDate = DateTime.Now;
|
||||
bool usePurchaseDate = false;
|
||||
bool useSoldDate = false;
|
||||
if (!string.IsNullOrWhiteSpace(soldDate) && DateTime.TryParse(soldDate, out DateTime vehicleSoldDate))
|
||||
{
|
||||
if (year == default || year >= vehicleSoldDate.Year) //All Time is selected or the selected year is greater or equal to the year the vehicle is sold
|
||||
{
|
||||
endDate = vehicleSoldDate; //cap end date to vehicle sold date.
|
||||
useSoldDate = true;
|
||||
}
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(purchaseDate) && DateTime.TryParse(purchaseDate, out DateTime vehiclePurchaseDate))
|
||||
{
|
||||
if (year == default || year <= vehiclePurchaseDate.Year) //All Time is selected or the selected year is less or equal to the year the vehicle is purchased
|
||||
{
|
||||
startDate = vehiclePurchaseDate; //cap start date to vehicle purchase date
|
||||
usePurchaseDate = true;
|
||||
}
|
||||
}
|
||||
if (year != default)
|
||||
{
|
||||
var calendarYearStart = new DateTime(year, 1, 1);
|
||||
var calendarYearEnd = new DateTime(year + 1, 1, 1);
|
||||
if (!useSoldDate)
|
||||
{
|
||||
endDate = endDate > calendarYearEnd ? calendarYearEnd : endDate;
|
||||
}
|
||||
if (!usePurchaseDate)
|
||||
{
|
||||
startDate = startDate > calendarYearStart ? calendarYearStart : startDate;
|
||||
}
|
||||
var timeElapsed = (int)Math.Floor((endDate - startDate).TotalDays);
|
||||
return timeElapsed;
|
||||
}
|
||||
var dateArray = new List<DateTime>() { startDate };
|
||||
dateArray.AddRange(serviceRecords.Select(x => x.Date));
|
||||
dateArray.AddRange(repairRecords.Select(x => x.Date));
|
||||
dateArray.AddRange(gasRecords.Select(x => x.Date));
|
||||
dateArray.AddRange(upgradeRecords.Select(x => x.Date));
|
||||
dateArray.AddRange(odometerRecords.Select(x => x.Date));
|
||||
dateArray.AddRange(taxRecords.Select(x => x.Date));
|
||||
if (dateArray.Any())
|
||||
{
|
||||
startDate = dateArray.Min();
|
||||
var timeElapsed = (int)Math.Floor((endDate - startDate).TotalDays);
|
||||
return timeElapsed;
|
||||
} else
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
public bool GetVehicleHasUrgentOrPastDueReminders(int vehicleId, int currentMileage)
|
||||
{
|
||||
var currentMileage = GetMaxMileage(vehicleId);
|
||||
var reminders = _reminderRecordDataAccess.GetReminderRecordsByVehicleId(vehicleId);
|
||||
var results = _reminderHelper.GetReminderRecordViewModels(reminders, currentMileage, DateTime.Now);
|
||||
return results.Any(x => x.Urgency == ReminderUrgency.VeryUrgent || x.Urgency == ReminderUrgency.PastDue);
|
||||
}
|
||||
|
||||
public List<VehicleInfo> GetVehicleInfo(List<Vehicle> vehicles)
|
||||
{
|
||||
List<VehicleInfo> apiResult = new List<VehicleInfo>();
|
||||
|
||||
foreach (Vehicle vehicle in vehicles)
|
||||
{
|
||||
var currentMileage = GetMaxMileage(vehicle.Id);
|
||||
var reminders = _reminderRecordDataAccess.GetReminderRecordsByVehicleId(vehicle.Id);
|
||||
var results = _reminderHelper.GetReminderRecordViewModels(reminders, currentMileage, DateTime.Now);
|
||||
|
||||
var serviceRecords = _serviceRecordDataAccess.GetServiceRecordsByVehicleId(vehicle.Id);
|
||||
var repairRecords = _collisionRecordDataAccess.GetCollisionRecordsByVehicleId(vehicle.Id);
|
||||
var upgradeRecords = _upgradeRecordDataAccess.GetUpgradeRecordsByVehicleId(vehicle.Id);
|
||||
var gasRecords = _gasRecordDataAccess.GetGasRecordsByVehicleId(vehicle.Id);
|
||||
var taxRecords = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicle.Id);
|
||||
var planRecords = _planRecordDataAccess.GetPlanRecordsByVehicleId(vehicle.Id);
|
||||
|
||||
var resultToAdd = new VehicleInfo()
|
||||
{
|
||||
VehicleData = vehicle,
|
||||
LastReportedOdometer = currentMileage,
|
||||
ServiceRecordCount = serviceRecords.Count(),
|
||||
ServiceRecordCost = serviceRecords.Sum(x => x.Cost),
|
||||
RepairRecordCount = repairRecords.Count(),
|
||||
RepairRecordCost = repairRecords.Sum(x => x.Cost),
|
||||
UpgradeRecordCount = upgradeRecords.Count(),
|
||||
UpgradeRecordCost = upgradeRecords.Sum(x => x.Cost),
|
||||
GasRecordCount = gasRecords.Count(),
|
||||
GasRecordCost = gasRecords.Sum(x => x.Cost),
|
||||
TaxRecordCount = taxRecords.Count(),
|
||||
TaxRecordCost = taxRecords.Sum(x => x.Cost),
|
||||
VeryUrgentReminderCount = results.Count(x => x.Urgency == ReminderUrgency.VeryUrgent),
|
||||
PastDueReminderCount = results.Count(x => x.Urgency == ReminderUrgency.PastDue),
|
||||
UrgentReminderCount = results.Count(x => x.Urgency == ReminderUrgency.Urgent),
|
||||
NotUrgentReminderCount = results.Count(x => x.Urgency == ReminderUrgency.NotUrgent),
|
||||
PlanRecordBackLogCount = planRecords.Count(x => x.Progress == PlanProgress.Backlog),
|
||||
PlanRecordInProgressCount = planRecords.Count(x => x.Progress == PlanProgress.InProgress),
|
||||
PlanRecordTestingCount = planRecords.Count(x => x.Progress == PlanProgress.Testing),
|
||||
PlanRecordDoneCount = planRecords.Count(x => x.Progress == PlanProgress.Done)
|
||||
};
|
||||
//set next reminder
|
||||
if (results.Any(x => (x.Metric == ReminderMetric.Date || x.Metric == ReminderMetric.Both) && x.Date >= DateTime.Now.Date))
|
||||
{
|
||||
resultToAdd.NextReminder = results.Where(x => x.Date >= DateTime.Now.Date).OrderBy(x => x.Date).Select(x => new ReminderExportModel { Id = x.Id.ToString(), Description = x.Description, Urgency = x.Urgency.ToString(), Metric = x.Metric.ToString(), Notes = x.Notes, DueDate = x.Date.ToShortDateString(), DueOdometer = x.Mileage.ToString(), Tags = string.Join(' ', x.Tags) }).First();
|
||||
}
|
||||
else if (results.Any(x => (x.Metric == ReminderMetric.Odometer || x.Metric == ReminderMetric.Both) && x.Mileage >= currentMileage))
|
||||
{
|
||||
resultToAdd.NextReminder = results.Where(x => x.Mileage >= currentMileage).OrderBy(x => x.Mileage).Select(x => new ReminderExportModel { Id = x.Id.ToString(), Description = x.Description, Urgency = x.Urgency.ToString(), Metric = x.Metric.ToString(), Notes = x.Notes, DueDate = x.Date.ToShortDateString(), DueOdometer = x.Mileage.ToString(), Tags = string.Join(' ', x.Tags) }).First();
|
||||
}
|
||||
apiResult.Add(resultToAdd);
|
||||
}
|
||||
return apiResult;
|
||||
}
|
||||
public List<ReminderRecordViewModel> GetReminders(List<Vehicle> vehicles, bool isCalendar)
|
||||
{
|
||||
List<ReminderRecordViewModel> reminders = new List<ReminderRecordViewModel>();
|
||||
foreach (Vehicle vehicle in vehicles)
|
||||
{
|
||||
var vehicleReminders = _reminderRecordDataAccess.GetReminderRecordsByVehicleId(vehicle.Id);
|
||||
if (isCalendar)
|
||||
{
|
||||
vehicleReminders.RemoveAll(x => x.Metric == ReminderMetric.Odometer);
|
||||
//we don't care about mileages so we can basically fake the current vehicle mileage.
|
||||
}
|
||||
if (vehicleReminders.Any())
|
||||
{
|
||||
var vehicleMileage = isCalendar ? 0 : GetMaxMileage(vehicle.Id);
|
||||
var reminderUrgency = _reminderHelper.GetReminderRecordViewModels(vehicleReminders, vehicleMileage, DateTime.Now);
|
||||
reminderUrgency = reminderUrgency.Select(x => new ReminderRecordViewModel { Id = x.Id, Metric = x.Metric, Date = x.Date, Notes = x.Notes, Mileage = x.Mileage, Urgency = x.Urgency, Description = $"{vehicle.Year} {vehicle.Make} {vehicle.Model} #{StaticHelper.GetVehicleIdentifier(vehicle)} - {x.Description}" }).ToList();
|
||||
reminders.AddRange(reminderUrgency);
|
||||
}
|
||||
}
|
||||
return reminders.OrderByDescending(x=>x.Urgency).ToList();
|
||||
}
|
||||
public List<PlanRecord> GetPlans(List<Vehicle> vehicles, bool excludeDone)
|
||||
{
|
||||
List<PlanRecord> plans = new List<PlanRecord>();
|
||||
foreach (Vehicle vehicle in vehicles)
|
||||
{
|
||||
var vehiclePlans = _planRecordDataAccess.GetPlanRecordsByVehicleId(vehicle.Id);
|
||||
if (excludeDone)
|
||||
{
|
||||
vehiclePlans.RemoveAll(x => x.Progress == PlanProgress.Done);
|
||||
}
|
||||
if (vehiclePlans.Any())
|
||||
{
|
||||
var convertedPlans = vehiclePlans.Select(x => new PlanRecord { ImportMode = x.ImportMode, Priority = x.Priority, Progress = x.Progress, Notes = x.Notes, RequisitionHistory = x.RequisitionHistory, Description = $"{vehicle.Year} {vehicle.Make} {vehicle.Model} #{StaticHelper.GetVehicleIdentifier(vehicle)} - {x.Description}" });
|
||||
plans.AddRange(convertedPlans);
|
||||
}
|
||||
}
|
||||
return plans.OrderBy(x => x.Priority).ThenBy(x=>x.Progress).ToList();
|
||||
}
|
||||
public bool UpdateRecurringTaxes(int vehicleId)
|
||||
{
|
||||
var vehicleData = _dataAccess.GetVehicleById(vehicleId);
|
||||
if (!string.IsNullOrWhiteSpace(vehicleData.SoldDate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
bool RecurringTaxIsOutdated(TaxRecord taxRecord)
|
||||
{
|
||||
var monthInterval = taxRecord.RecurringInterval != ReminderMonthInterval.Other ? (int)taxRecord.RecurringInterval : taxRecord.CustomMonthInterval;
|
||||
bool addDays = taxRecord.RecurringInterval == ReminderMonthInterval.Other && taxRecord.CustomMonthIntervalUnit == ReminderIntervalUnit.Days;
|
||||
return addDays ? DateTime.Now > taxRecord.Date.AddDays(monthInterval) : DateTime.Now > taxRecord.Date.AddMonths(monthInterval);
|
||||
}
|
||||
var result = _taxRecordDataAccess.GetTaxRecordsByVehicleId(vehicleId);
|
||||
var outdatedRecurringFees = result.Where(x => x.IsRecurring && RecurringTaxIsOutdated(x));
|
||||
if (outdatedRecurringFees.Any())
|
||||
{
|
||||
var success = false;
|
||||
foreach (TaxRecord recurringFee in outdatedRecurringFees)
|
||||
{
|
||||
var monthInterval = recurringFee.RecurringInterval != ReminderMonthInterval.Other ? (int)recurringFee.RecurringInterval : recurringFee.CustomMonthInterval;
|
||||
bool isOutdated = true;
|
||||
bool addDays = recurringFee.RecurringInterval == ReminderMonthInterval.Other && recurringFee.CustomMonthIntervalUnit == ReminderIntervalUnit.Days;
|
||||
//update the original outdated tax record
|
||||
recurringFee.IsRecurring = false;
|
||||
_taxRecordDataAccess.SaveTaxRecordToVehicle(recurringFee);
|
||||
//month multiplier for severely outdated monthly tax records.
|
||||
int monthMultiplier = 1;
|
||||
var originalDate = recurringFee.Date;
|
||||
while (isOutdated)
|
||||
{
|
||||
try
|
||||
{
|
||||
var nextDate = addDays ? originalDate.AddDays(monthInterval * monthMultiplier) : originalDate.AddMonths(monthInterval * monthMultiplier);
|
||||
monthMultiplier++;
|
||||
var nextnextDate = addDays ? originalDate.AddDays(monthInterval * monthMultiplier) : originalDate.AddMonths(monthInterval * monthMultiplier);
|
||||
recurringFee.Date = nextDate;
|
||||
recurringFee.Id = default; //new record
|
||||
recurringFee.IsRecurring = DateTime.Now <= nextnextDate;
|
||||
_taxRecordDataAccess.SaveTaxRecordToVehicle(recurringFee);
|
||||
isOutdated = !recurringFee.IsRecurring;
|
||||
success = true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
isOutdated = false; //break out of loop if something broke.
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
return false; //no outdated recurring tax records.
|
||||
}
|
||||
public void RestoreSupplyRecordsByUsage(List<SupplyUsageHistory> supplyUsage, string usageDescription)
|
||||
{
|
||||
foreach (SupplyUsageHistory supply in supplyUsage)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (supply.Id == default)
|
||||
{
|
||||
continue; //no id, skip current supply.
|
||||
}
|
||||
var result = _supplyRecordDataAccess.GetSupplyRecordById(supply.Id);
|
||||
if (result != null && result.Id != default)
|
||||
{
|
||||
//supply exists, re-add the quantity and cost
|
||||
result.Quantity += supply.Quantity;
|
||||
result.Cost += supply.Cost;
|
||||
var requisitionRecord = new SupplyUsageHistory
|
||||
{
|
||||
Id = supply.Id,
|
||||
Date = DateTime.Now.Date,
|
||||
Description = $"Restored from {usageDescription}",
|
||||
Quantity = supply.Quantity,
|
||||
Cost = supply.Cost
|
||||
};
|
||||
result.RequisitionHistory.Add(requisitionRecord);
|
||||
//save
|
||||
_supplyRecordDataAccess.SaveSupplyRecordToVehicle(result);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError($"Unable to find supply with id {supply.Id}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError($"Error restoring supply with id {supply.Id} : {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,18 +8,21 @@ namespace CarCareTracker.MapProfile
|
||||
public ImportMapper()
|
||||
{
|
||||
Map(m => m.Date).Name(["date", "fuelup_date"]);
|
||||
Map(m => m.Day).Name(["day"]);
|
||||
Map(m => m.Month).Name(["month"]);
|
||||
Map(m => m.Year).Name(["year"]);
|
||||
Map(m => m.DateCreated).Name(["datecreated"]);
|
||||
Map(m => m.DateModified).Name(["datemodified"]);
|
||||
Map(m => m.InitialOdometer).Name(["initialodometer"]);
|
||||
Map(m => m.Odometer).Name(["odometer"]);
|
||||
Map(m => m.FuelConsumed).Name(["gallons", "liters", "litres", "consumption", "quantity", "fuelconsumed"]);
|
||||
Map(m => m.Odometer).Name(["odometer", "odo"]);
|
||||
Map(m => m.FuelConsumed).Name(["gallons", "liters", "litres", "consumption", "quantity", "fuelconsumed", "qty"]);
|
||||
Map(m => m.Cost).Name(["cost", "total cost", "totalcost", "total price"]);
|
||||
Map(m => m.Notes).Name("notes", "note");
|
||||
Map(m => m.Price).Name(["price"]);
|
||||
Map(m => m.PartialFuelUp).Name(["partial_fuelup"]);
|
||||
Map(m => m.PartialFuelUp).Name(["partial_fuelup", "partial tank", "partial_fill"]);
|
||||
Map(m => m.IsFillToFull).Name(["isfilltofull", "filled up"]);
|
||||
Map(m => m.Description).Name(["description"]);
|
||||
Map(m => m.MissedFuelUp).Name(["missed_fuelup", "missedfuelup"]);
|
||||
Map(m => m.MissedFuelUp).Name(["missed_fuelup", "missedfuelup", "missed fill up", "missed_fill"]);
|
||||
Map(m => m.PartSupplier).Name(["partsupplier"]);
|
||||
Map(m => m.PartQuantity).Name(["partquantity"]);
|
||||
Map(m => m.PartNumber).Name(["partnumber"]);
|
||||
@@ -27,6 +30,18 @@ namespace CarCareTracker.MapProfile
|
||||
Map(m => m.Type).Name(["type"]);
|
||||
Map(m => m.Priority).Name(["priority"]);
|
||||
Map(m => m.Tags).Name(["tags"]);
|
||||
Map(m => m.ExtraFields).Convert(row =>
|
||||
{
|
||||
var attributes = new Dictionary<string, string>();
|
||||
foreach (var header in row.Row.HeaderRecord)
|
||||
{
|
||||
if (header.ToLower().StartsWith("extrafield_"))
|
||||
{
|
||||
attributes.Add(header.Substring(11), row.Row.GetField(header));
|
||||
}
|
||||
}
|
||||
return attributes;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
|
||||
@@ -27,7 +28,7 @@ namespace CarCareTracker.Middleware
|
||||
_httpContext = httpContext;
|
||||
_dataProtector = securityProvider.CreateProtector("login");
|
||||
_loginLogic = loginLogic;
|
||||
enableAuth = bool.Parse(configuration["EnableAuth"]);
|
||||
enableAuth = bool.Parse(configuration["EnableAuth"] ?? "false");
|
||||
}
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
@@ -42,7 +43,7 @@ namespace CarCareTracker.Middleware
|
||||
new(ClaimTypes.Role, nameof(UserData.IsRootUser))
|
||||
};
|
||||
appIdentity.AddClaims(userIdentity);
|
||||
AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(appIdentity), this.Scheme.Name);
|
||||
AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(appIdentity), Scheme.Name);
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
else
|
||||
@@ -59,7 +60,7 @@ namespace CarCareTracker.Middleware
|
||||
{
|
||||
var cleanedHeader = request_header.ToString().Replace("Basic ", "").Trim();
|
||||
byte[] data = Convert.FromBase64String(cleanedHeader);
|
||||
string decodedString = System.Text.Encoding.UTF8.GetString(data);
|
||||
string decodedString = Encoding.UTF8.GetString(data);
|
||||
var splitString = decodedString.Split(":");
|
||||
if (splitString.Count() != 2)
|
||||
{
|
||||
@@ -74,7 +75,9 @@ namespace CarCareTracker.Middleware
|
||||
var userIdentity = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.Name, splitString[0]),
|
||||
new(ClaimTypes.NameIdentifier, userData.Id.ToString())
|
||||
new(ClaimTypes.NameIdentifier, userData.Id.ToString()),
|
||||
new(ClaimTypes.Email, userData.EmailAddress),
|
||||
new(ClaimTypes.Role, "APIAuth")
|
||||
};
|
||||
if (userData.IsAdmin)
|
||||
{
|
||||
@@ -85,7 +88,7 @@ namespace CarCareTracker.Middleware
|
||||
userIdentity.Add(new(ClaimTypes.Role, nameof(UserData.IsRootUser)));
|
||||
}
|
||||
appIdentity.AddClaims(userIdentity);
|
||||
AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(appIdentity), this.Scheme.Name);
|
||||
AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(appIdentity), Scheme.Name);
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
}
|
||||
@@ -133,7 +136,7 @@ namespace CarCareTracker.Middleware
|
||||
userIdentity.Add(new(ClaimTypes.Role, nameof(UserData.IsRootUser)));
|
||||
}
|
||||
appIdentity.AddClaims(userIdentity);
|
||||
AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(appIdentity), this.Scheme.Name);
|
||||
AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(appIdentity), Scheme.Name);
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
}
|
||||
@@ -153,6 +156,7 @@ namespace CarCareTracker.Middleware
|
||||
if (value.ToString().ToLower() == "api")
|
||||
{
|
||||
Response.StatusCode = 401;
|
||||
Response.Headers.Append("WWW-Authenticate", "Basic");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
18
Models/API/ReleaseVersion.cs
Normal file
18
Models/API/ReleaseVersion.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// For deserializing GitHub response for latest version
|
||||
/// </summary>
|
||||
public class ReleaseResponse
|
||||
{
|
||||
public string tag_name { get; set; }
|
||||
}
|
||||
/// <summary>
|
||||
/// For returning the version numbers via API.
|
||||
/// </summary>
|
||||
public class ReleaseVersion
|
||||
{
|
||||
public string CurrentVersion { get; set; }
|
||||
public string LatestVersion { get; set; }
|
||||
}
|
||||
}
|
||||
138
Models/API/TypeConverter.cs
Normal file
138
Models/API/TypeConverter.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class DummyType
|
||||
{
|
||||
|
||||
}
|
||||
class InvariantConverter : JsonConverter<DummyType>
|
||||
{
|
||||
public override void Write(Utf8JsonWriter writer, DummyType value, JsonSerializerOptions options)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
public override DummyType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
class FromDateOptional: JsonConverter<string>
|
||||
{
|
||||
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
var tokenType = reader.TokenType;
|
||||
if (tokenType == JsonTokenType.String)
|
||||
{
|
||||
return reader.GetString();
|
||||
}
|
||||
else if (tokenType == JsonTokenType.Number)
|
||||
{
|
||||
if (reader.TryGetInt64(out long intInput))
|
||||
{
|
||||
return DateTimeOffset.FromUnixTimeSeconds(intInput).Date.ToShortDateString();
|
||||
}
|
||||
}
|
||||
return reader.GetString();
|
||||
}
|
||||
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
|
||||
{
|
||||
if (options.Converters.Any(x => x.Type == typeof(DummyType)))
|
||||
{
|
||||
writer.WriteStringValue(DateTime.Parse(value).ToString("yyyy-MM-dd"));
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteStringValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
class FromDecimalOptional : JsonConverter<string>
|
||||
{
|
||||
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
var tokenType = reader.TokenType;
|
||||
if (tokenType == JsonTokenType.String)
|
||||
{
|
||||
return reader.GetString();
|
||||
}
|
||||
else if (tokenType == JsonTokenType.Number) {
|
||||
if (reader.TryGetDecimal(out decimal decimalInput))
|
||||
{
|
||||
return decimalInput.ToString();
|
||||
}
|
||||
}
|
||||
return reader.GetString();
|
||||
}
|
||||
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
|
||||
{
|
||||
if (options.Converters.Any(x=>x.Type == typeof(DummyType)))
|
||||
{
|
||||
writer.WriteNumberValue(decimal.Parse(value));
|
||||
} else
|
||||
{
|
||||
writer.WriteStringValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
class FromIntOptional : JsonConverter<string>
|
||||
{
|
||||
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
var tokenType = reader.TokenType;
|
||||
if (tokenType == JsonTokenType.String)
|
||||
{
|
||||
return reader.GetString();
|
||||
}
|
||||
else if (tokenType == JsonTokenType.Number)
|
||||
{
|
||||
if (reader.TryGetInt32(out int intInput))
|
||||
{
|
||||
return intInput.ToString();
|
||||
}
|
||||
}
|
||||
return reader.GetString();
|
||||
}
|
||||
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
|
||||
{
|
||||
if (options.Converters.Any(x => x.Type == typeof(DummyType)))
|
||||
{
|
||||
writer.WriteNumberValue(int.Parse(value));
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteStringValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
class FromBoolOptional : JsonConverter<string>
|
||||
{
|
||||
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
var tokenType = reader.TokenType;
|
||||
switch (tokenType)
|
||||
{
|
||||
case JsonTokenType.String:
|
||||
return reader.GetString();
|
||||
case JsonTokenType.True:
|
||||
return "True";
|
||||
case JsonTokenType.False:
|
||||
return "False";
|
||||
default:
|
||||
return reader.GetString();
|
||||
}
|
||||
}
|
||||
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
|
||||
{
|
||||
if (options.Converters.Any(x => x.Type == typeof(DummyType)))
|
||||
{
|
||||
writer.WriteBooleanValue(bool.Parse(value));
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteStringValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
27
Models/API/VehicleInfo.cs
Normal file
27
Models/API/VehicleInfo.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class VehicleInfo
|
||||
{
|
||||
public Vehicle VehicleData { get; set; } = new Vehicle();
|
||||
public int VeryUrgentReminderCount { get; set; }
|
||||
public int UrgentReminderCount { get; set;}
|
||||
public int NotUrgentReminderCount { get; set; }
|
||||
public int PastDueReminderCount { get; set; }
|
||||
public ReminderExportModel NextReminder { get; set; }
|
||||
public int ServiceRecordCount { get; set; }
|
||||
public decimal ServiceRecordCost { get; set; }
|
||||
public int RepairRecordCount { get; set; }
|
||||
public decimal RepairRecordCost { get; set; }
|
||||
public int UpgradeRecordCount { get; set; }
|
||||
public decimal UpgradeRecordCost { get; set; }
|
||||
public int TaxRecordCount { get; set; }
|
||||
public decimal TaxRecordCost { get; set; }
|
||||
public int GasRecordCount { get; set; }
|
||||
public decimal GasRecordCost { get; set; }
|
||||
public int LastReportedOdometer { get; set; }
|
||||
public int PlanRecordBackLogCount { get; set; }
|
||||
public int PlanRecordInProgressCount { get; set; }
|
||||
public int PlanRecordTestingCount { get; set; }
|
||||
public int PlanRecordDoneCount { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
public List<string> Tags { get; set; } = new List<string>();
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<SupplyUsageHistory> RequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
public List<SupplyUsageHistory> DeletedRequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
public bool CopySuppliesAttachment { get; set; } = false;
|
||||
public CollisionRecord ToCollisionRecord() { return new CollisionRecord {
|
||||
Id = Id,
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
{
|
||||
public string EmailServer { get; set; }
|
||||
public string EmailFrom { get; set; }
|
||||
public bool UseSSL { get; set; }
|
||||
public int Port { get; set; }
|
||||
public string Username { get; set; }
|
||||
public string Password { get; set; }
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
public string Notes { get; set; }
|
||||
public List<string> Tags { get; set; } = new List<string>();
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public bool IncludeInAverage { get { return MilesPerGallon > 0 || (!IsFillToFull && !MissedFuelUp); } }
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
public bool IncludeInAverage { get { return MilesPerGallon > 0 || (!IsFillToFull && !MissedFuelUp) || (Mileage == default && !MissedFuelUp); } }
|
||||
}
|
||||
}
|
||||
|
||||
14
Models/Kiosk/KioskViewModel.cs
Normal file
14
Models/Kiosk/KioskViewModel.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class KioskViewModel
|
||||
{
|
||||
/// <summary>
|
||||
/// List of vehicle ids to exclude from Kiosk Dashboard
|
||||
/// </summary>
|
||||
public List<int> Exclusions { get; set; } = new List<int>();
|
||||
/// <summary>
|
||||
/// Whether to retrieve data for vehicle, plans, or reminder view.
|
||||
/// </summary>
|
||||
public KioskMode KioskMode { get; set; } = KioskMode.Vehicle;
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,21 @@
|
||||
public string AuthURL { get; set; }
|
||||
public string TokenURL { get; set; }
|
||||
public string RedirectURL { get; set; }
|
||||
public string Scope { get; set; }
|
||||
public string Scope { get; set; } = "openid email";
|
||||
public string State { get; set; }
|
||||
public string CodeChallenge { get; set; }
|
||||
public bool ValidateState { get; set; } = false;
|
||||
public bool DisableRegularLogin { get; set; } = false;
|
||||
public bool UsePKCE { get; set; } = false;
|
||||
public string LogOutURL { get; set; } = "";
|
||||
public string RemoteAuthURL { get { return $"{AuthURL}?client_id={ClientId}&response_type=code&redirect_uri={RedirectURL}&scope={Scope}&state={State}"; } }
|
||||
public string UserInfoURL { get; set; } = "";
|
||||
public string RemoteAuthURL { get {
|
||||
var redirectUrl = $"{AuthURL}?client_id={ClientId}&response_type=code&redirect_uri={RedirectURL}&scope={Scope}&state={State}";
|
||||
if (UsePKCE)
|
||||
{
|
||||
redirectUrl += $"&code_challenge={CodeChallenge}&code_challenge_method=S256";
|
||||
}
|
||||
return redirectUrl;
|
||||
} }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,5 +3,6 @@
|
||||
public class OpenIDResult
|
||||
{
|
||||
public string id_token { get; set; }
|
||||
public string access_token { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
7
Models/OIDC/OpenIDUserInfo.cs
Normal file
7
Models/OIDC/OpenIDUserInfo.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class OpenIDUserInfo
|
||||
{
|
||||
public string email { get; set; } = "";
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,33 @@
|
||||
namespace CarCareTracker.Models
|
||||
using CarCareTracker.Helper;
|
||||
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class OperationResponse
|
||||
public class OperationResponseBase
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string Message { get; set; }
|
||||
}
|
||||
public class OperationResponse: OperationResponseBase
|
||||
{
|
||||
public static OperationResponse Succeed(string message = "")
|
||||
{
|
||||
return new OperationResponse { Success = true, Message = message };
|
||||
}
|
||||
public static OperationResponse Failed(string message = "")
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
{
|
||||
message = StaticHelper.GenericErrorMessage;
|
||||
}
|
||||
return new OperationResponse { Success = false, Message = message};
|
||||
}
|
||||
public static OperationResponse Conditional(bool result, string successMessage = "", string errorMessage = "")
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(errorMessage))
|
||||
{
|
||||
errorMessage = StaticHelper.GenericErrorMessage;
|
||||
}
|
||||
return new OperationResponse { Success = result, Message = result ? successMessage : errorMessage };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
public decimal Cost { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<SupplyUsageHistory> RequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
public List<SupplyUsageHistory> DeletedRequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
public bool CopySuppliesAttachment { get; set; } = false;
|
||||
public PlanRecord ToPlanRecord() { return new PlanRecord {
|
||||
Id = Id,
|
||||
|
||||
@@ -9,8 +9,11 @@
|
||||
public string Description { get; set; }
|
||||
public string Notes { get; set; }
|
||||
public bool IsRecurring { get; set; } = false;
|
||||
public bool UseCustomThresholds { get; set; } = false;
|
||||
public ReminderUrgencyConfig CustomThresholds { get; set; } = new ReminderUrgencyConfig();
|
||||
public int CustomMileageInterval { get; set; } = 0;
|
||||
public int CustomMonthInterval { get; set; } = 0;
|
||||
public ReminderIntervalUnit CustomMonthIntervalUnit { get; set; } = ReminderIntervalUnit.Months;
|
||||
public ReminderMileageInterval ReminderMileageInterval { get; set; } = ReminderMileageInterval.FiveThousandMiles;
|
||||
public ReminderMonthInterval ReminderMonthInterval { get; set; } = ReminderMonthInterval.OneYear;
|
||||
public ReminderMetric Metric { get; set; } = ReminderMetric.Date;
|
||||
|
||||
@@ -9,8 +9,11 @@
|
||||
public string Description { get; set; }
|
||||
public string Notes { get; set; }
|
||||
public bool IsRecurring { get; set; } = false;
|
||||
public bool UseCustomThresholds { get; set; } = false;
|
||||
public ReminderUrgencyConfig CustomThresholds { get; set; } = new ReminderUrgencyConfig();
|
||||
public int CustomMileageInterval { get; set; } = 0;
|
||||
public int CustomMonthInterval { get; set; } = 0;
|
||||
public ReminderIntervalUnit CustomMonthIntervalUnit { get; set; } = ReminderIntervalUnit.Months;
|
||||
public ReminderMileageInterval ReminderMileageInterval { get; set; } = ReminderMileageInterval.FiveThousandMiles;
|
||||
public ReminderMonthInterval ReminderMonthInterval { get; set; } = ReminderMonthInterval.OneYear;
|
||||
public ReminderMetric Metric { get; set; } = ReminderMetric.Date;
|
||||
@@ -26,10 +29,13 @@
|
||||
Description = Description,
|
||||
Metric = Metric,
|
||||
IsRecurring = IsRecurring,
|
||||
UseCustomThresholds = UseCustomThresholds,
|
||||
CustomThresholds = CustomThresholds,
|
||||
ReminderMileageInterval = ReminderMileageInterval,
|
||||
ReminderMonthInterval = ReminderMonthInterval,
|
||||
CustomMileageInterval = CustomMileageInterval,
|
||||
CustomMonthInterval = CustomMonthInterval,
|
||||
CustomMonthIntervalUnit = CustomMonthIntervalUnit,
|
||||
Notes = Notes,
|
||||
Tags = Tags
|
||||
};
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
public string Description { get; set; }
|
||||
public string Notes { get; set; }
|
||||
/// <summary>
|
||||
/// The metric the user selected to calculate the urgency of this reminder.
|
||||
/// </summary>
|
||||
public ReminderMetric UserMetric { get; set; } = ReminderMetric.Date;
|
||||
/// <summary>
|
||||
/// Reason why this reminder is urgent
|
||||
/// </summary>
|
||||
public ReminderMetric Metric { get; set; } = ReminderMetric.Date;
|
||||
|
||||
8
Models/Report/CostDistanceTableForVehicle.cs
Normal file
8
Models/Report/CostDistanceTableForVehicle.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class CostDistanceTableForVehicle
|
||||
{
|
||||
public string DistanceUnit { get; set; } = "mi.";
|
||||
public List<CostForVehicleByMonth> CostData { get; set; } = new List<CostForVehicleByMonth>();
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@
|
||||
{
|
||||
public class CostForVehicleByMonth
|
||||
{
|
||||
public int Year { get; set; }
|
||||
public int MonthId { get; set; }
|
||||
public string MonthName { get; set; }
|
||||
public decimal Cost { get; set; }
|
||||
public int DistanceTraveled { get; set; }
|
||||
public decimal CostPerDistanceTraveled { get { if (DistanceTraveled > 0) { return Cost / DistanceTraveled; } else { return 0M; } } }
|
||||
}
|
||||
}
|
||||
|
||||
27
Models/Report/CostTableForVehicle.cs
Normal file
27
Models/Report/CostTableForVehicle.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class CostTableForVehicle
|
||||
{
|
||||
public string DistanceUnit { get; set; } = "Cost Per Mile";
|
||||
public int TotalDistance { get; set; }
|
||||
public int NumberOfDays { get; set; }
|
||||
public decimal ServiceRecordSum { get; set; }
|
||||
public decimal GasRecordSum { get; set; }
|
||||
public decimal TaxRecordSum { get; set; }
|
||||
public decimal CollisionRecordSum { get; set; }
|
||||
public decimal UpgradeRecordSum { get; set; }
|
||||
public decimal ServiceRecordPerMile { get { return TotalDistance != default ? ServiceRecordSum / TotalDistance : 0; } }
|
||||
public decimal GasRecordPerMile { get { return TotalDistance != default ? GasRecordSum / TotalDistance : 0; } }
|
||||
public decimal CollisionRecordPerMile { get { return TotalDistance != default ? CollisionRecordSum / TotalDistance : 0; } }
|
||||
public decimal UpgradeRecordPerMile { get { return TotalDistance != default ? UpgradeRecordSum / TotalDistance : 0; } }
|
||||
public decimal TaxRecordPerMile { get { return TotalDistance != default ? TaxRecordSum / TotalDistance : 0; } }
|
||||
public decimal ServiceRecordPerDay { get { return NumberOfDays != default ? ServiceRecordSum / NumberOfDays : 0; } }
|
||||
public decimal GasRecordPerDay { get { return NumberOfDays != default ? GasRecordSum / NumberOfDays : 0; } }
|
||||
public decimal CollisionRecordPerDay { get { return NumberOfDays != default ? CollisionRecordSum / NumberOfDays : 0; } }
|
||||
public decimal UpgradeRecordPerDay { get { return NumberOfDays != default ? UpgradeRecordSum / NumberOfDays : 0; } }
|
||||
public decimal TaxRecordPerDay { get { return NumberOfDays != default ? TaxRecordSum / NumberOfDays : 0; } }
|
||||
public decimal TotalPerDay { get { return ServiceRecordPerDay + CollisionRecordPerDay + UpgradeRecordPerDay + GasRecordPerDay + TaxRecordPerDay; } }
|
||||
public decimal TotalPerMile { get { return ServiceRecordPerMile + CollisionRecordPerMile + UpgradeRecordPerMile + GasRecordPerMile + TaxRecordPerMile; } }
|
||||
public decimal TotalCost { get { return ServiceRecordSum + CollisionRecordSum + UpgradeRecordSum + GasRecordSum + TaxRecordSum; } }
|
||||
}
|
||||
}
|
||||
@@ -12,5 +12,7 @@
|
||||
public string Notes { get; set; }
|
||||
public decimal Cost { get; set; }
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<SupplyUsageHistory> RequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
}
|
||||
}
|
||||
|
||||
9
Models/Report/MPGForVehicleByMonth.cs
Normal file
9
Models/Report/MPGForVehicleByMonth.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class MPGForVehicleByMonth
|
||||
{
|
||||
public List<CostForVehicleByMonth> CostData { get; set; } = new List<CostForVehicleByMonth>();
|
||||
public List<CostForVehicleByMonth> SortedCostData { get; set; } = new List<CostForVehicleByMonth>();
|
||||
public string Unit { get; set; }
|
||||
}
|
||||
}
|
||||
10
Models/Report/ReportHeader.cs
Normal file
10
Models/Report/ReportHeader.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class ReportHeader
|
||||
{
|
||||
public int MaxOdometer { get; set; }
|
||||
public int DistanceTraveled { get; set; }
|
||||
public decimal TotalCost { get; set; }
|
||||
public string AverageMPG { get; set; }
|
||||
}
|
||||
}
|
||||
14
Models/Report/ReportParameter.cs
Normal file
14
Models/Report/ReportParameter.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class ReportParameter
|
||||
{
|
||||
public List<string> VisibleColumns { get; set; } = new List<string>();
|
||||
public List<string> ExtraFields { get; set; } = new List<string>();
|
||||
public TagFilter TagFilter { get; set; } = TagFilter.Exclude;
|
||||
public List<string> Tags { get; set; } = new List<string>();
|
||||
public bool FilterByDateRange { get; set; } = false;
|
||||
public string StartDate { get; set; } = "";
|
||||
public string EndDate { get; set; } = "";
|
||||
public bool PrintIndividualRecords { get; set; } = false;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
{
|
||||
public class ReportViewModel
|
||||
{
|
||||
public ReportHeader ReportHeaderForVehicle { get; set; } = new ReportHeader();
|
||||
public List<CostForVehicleByMonth> CostForVehicleByMonth { get; set; } = new List<CostForVehicleByMonth>();
|
||||
public List<CostForVehicleByMonth> FuelMileageForVehicleByMonth { get; set; } = new List<CostForVehicleByMonth>();
|
||||
public MPGForVehicleByMonth FuelMileageForVehicleByMonth { get; set; } = new MPGForVehicleByMonth();
|
||||
public CostMakeUpForVehicle CostMakeUpForVehicle { get; set; } = new CostMakeUpForVehicle();
|
||||
public ReminderMakeUpForVehicle ReminderMakeUpForVehicle { get; set; } = new ReminderMakeUpForVehicle();
|
||||
public List<int> Years { get; set; } = new List<int>();
|
||||
public List<UserCollaborator> Collaborators { get; set; } = new List<UserCollaborator>();
|
||||
public bool CustomWidgetsConfigured { get; set; } = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
{
|
||||
public Vehicle VehicleData { get; set; }
|
||||
public List<GenericReportModel> VehicleHistory { get; set; }
|
||||
public ReportParameter ReportParameters { get; set; }
|
||||
public string Odometer { get; set; }
|
||||
public string MPG { get; set; }
|
||||
public decimal TotalCost { get; set; }
|
||||
@@ -16,5 +17,7 @@
|
||||
public decimal TotalDepreciation { get; set; }
|
||||
public decimal DepreciationPerDay { get; set; }
|
||||
public decimal DepreciationPerMile { get; set; }
|
||||
public string StartDate { get; set; }
|
||||
public string EndDate { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
9
Models/SearchResult.cs
Normal file
9
Models/SearchResult.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class SearchResult
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public ImportMode RecordType { get; set; }
|
||||
public string Description { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
public List<string> Tags { get; set; } = new List<string>();
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<SupplyUsageHistory> RequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
public List<SupplyUsageHistory> DeletedRequisitionHistory { get; set; } = new List<SupplyUsageHistory>();
|
||||
public bool CopySuppliesAttachment { get; set; } = false;
|
||||
public ServiceRecord ToServiceRecord() { return new ServiceRecord {
|
||||
Id = Id,
|
||||
|
||||
17
Models/Settings/ServerSettingsViewModel.cs
Normal file
17
Models/Settings/ServerSettingsViewModel.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class ServerSettingsViewModel
|
||||
{
|
||||
public string LocaleInfo { get; set; }
|
||||
public string PostgresConnection { get; set; }
|
||||
public string AllowedFileExtensions { get; set; }
|
||||
public string CustomLogoURL { get; set; }
|
||||
public string MessageOfTheDay { get; set; }
|
||||
public string WebHookURL { get; set; }
|
||||
public bool CustomWidgetsEnabled { get; set; }
|
||||
public bool InvariantAPIEnabled { get; set; }
|
||||
public MailConfig SMTPConfig { get; set; } = new MailConfig();
|
||||
public OpenIDConfig OIDCConfig { get; set; } = new OpenIDConfig();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -5,5 +5,6 @@
|
||||
public string Name { get; set; }
|
||||
public string Value { get; set; }
|
||||
public bool IsRequired { get; set; }
|
||||
public ExtraFieldType FieldType { get; set; } = ExtraFieldType.Text;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace CarCareTracker.Models
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Import model used for importing records via CSV.
|
||||
@@ -6,6 +8,9 @@
|
||||
public class ImportModel
|
||||
{
|
||||
public string Date { get; set; }
|
||||
public string Day { get; set; }
|
||||
public string Month { get; set; }
|
||||
public string Year { get; set; }
|
||||
public string DateCreated { get; set; }
|
||||
public string DateModified { get; set; }
|
||||
public string Type { get; set; }
|
||||
@@ -25,6 +30,7 @@
|
||||
public string PartSupplier { get; set; }
|
||||
public string PartQuantity { get; set; }
|
||||
public string Tags { get; set; }
|
||||
public Dictionary<string,string> ExtraFields {get;set;}
|
||||
}
|
||||
|
||||
public class SupplyRecordExportModel
|
||||
@@ -37,62 +43,115 @@
|
||||
public string Cost { get; set; }
|
||||
public string Notes { get; set; }
|
||||
public string Tags { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
}
|
||||
|
||||
public class ServiceRecordExportModel
|
||||
public class GenericRecordExportModel
|
||||
{
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Id { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string Date { get; set; }
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Odometer { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Notes { get; set; }
|
||||
[JsonConverter(typeof(FromDecimalOptional))]
|
||||
public string Cost { get; set; }
|
||||
public string Tags { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
}
|
||||
public class OdometerRecordExportModel
|
||||
{
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Id { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string Date { get; set; }
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string InitialOdometer { get; set; }
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Odometer { get; set; }
|
||||
public string Notes { get; set; }
|
||||
public string Tags { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
}
|
||||
public class TaxRecordExportModel
|
||||
{
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Id { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string Date { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Notes { get; set; }
|
||||
[JsonConverter(typeof(FromDecimalOptional))]
|
||||
public string Cost { get; set; }
|
||||
public string Tags { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
}
|
||||
public class GasRecordExportModel
|
||||
{
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Id { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string Date { get; set; }
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Odometer { get; set; }
|
||||
[JsonConverter(typeof(FromDecimalOptional))]
|
||||
public string FuelConsumed { get; set; }
|
||||
[JsonConverter(typeof(FromDecimalOptional))]
|
||||
public string Cost { get; set; }
|
||||
[JsonConverter(typeof(FromDecimalOptional))]
|
||||
public string FuelEconomy { get; set; }
|
||||
[JsonConverter(typeof(FromBoolOptional))]
|
||||
public string IsFillToFull { get; set; }
|
||||
[JsonConverter(typeof(FromBoolOptional))]
|
||||
public string MissedFuelUp { get; set; }
|
||||
public string Notes { get; set; }
|
||||
public string Tags { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
}
|
||||
public class ReminderExportModel
|
||||
{
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Id { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Urgency { get; set; }
|
||||
public string Metric { get; set; }
|
||||
public string Notes { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string DueDate { get; set; }
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string DueOdometer { get; set; }
|
||||
public string Tags { get; set; }
|
||||
}
|
||||
public class PlanRecordExportModel
|
||||
{
|
||||
[JsonConverter(typeof(FromIntOptional))]
|
||||
public string Id { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string DateCreated { get; set; }
|
||||
[JsonConverter(typeof(FromDateOptional))]
|
||||
public string DateModified { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Notes { get; set; }
|
||||
public string Type { get; set; }
|
||||
public string Priority { get; set; }
|
||||
public string Progress { get; set; }
|
||||
[JsonConverter(typeof(FromDecimalOptional))]
|
||||
public string Cost { get; set; }
|
||||
public List<ExtraField> ExtraFields { get; set; } = new List<ExtraField>();
|
||||
public List<UploadedFiles> Files { get; set; } = new List<UploadedFiles>();
|
||||
}
|
||||
public class UserExportModel
|
||||
{
|
||||
public string Username { get; set; }
|
||||
public string EmailAddress { get; set; }
|
||||
[JsonConverter(typeof(FromBoolOptional))]
|
||||
public string IsAdmin { get; set; }
|
||||
[JsonConverter(typeof(FromBoolOptional))]
|
||||
public string IsRoot { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
11
Models/Shared/StickerViewModel.cs
Normal file
11
Models/Shared/StickerViewModel.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class StickerViewModel
|
||||
{
|
||||
public ImportMode RecordType { get; set; }
|
||||
public Vehicle VehicleData { get; set; } = new Vehicle();
|
||||
public List<ReminderRecord> ReminderRecords { get; set; } = new List<ReminderRecord>();
|
||||
public List<GenericRecord> GenericRecords { get; set; } = new List<GenericRecord>();
|
||||
public List<SupplyRecord> SupplyRecords { get; set; } = new List<SupplyRecord>();
|
||||
}
|
||||
}
|
||||
12
Models/Shared/VehicleRecords.cs
Normal file
12
Models/Shared/VehicleRecords.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
public class VehicleRecords
|
||||
{
|
||||
public List<ServiceRecord> ServiceRecords { get; set; } = new List<ServiceRecord>();
|
||||
public List<CollisionRecord> CollisionRecords { get; set; } = new List<CollisionRecord>();
|
||||
public List<UpgradeRecord> UpgradeRecords { get; set; } = new List<UpgradeRecord>();
|
||||
public List<GasRecord> GasRecords { get; set; } = new List<GasRecord>();
|
||||
public List<TaxRecord> TaxRecords { get; set; } = new List<TaxRecord>();
|
||||
public List<OdometerRecord> OdometerRecords { get; set; } = new List<OdometerRecord>();
|
||||
}
|
||||
}
|
||||
253
Models/Shared/WebHookPayload.cs
Normal file
253
Models/Shared/WebHookPayload.cs
Normal file
@@ -0,0 +1,253 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace CarCareTracker.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// WebHookPayload Object
|
||||
/// </summary>
|
||||
public class WebHookPayloadBase
|
||||
{
|
||||
public string Type { get; set; } = "";
|
||||
public string Timestamp
|
||||
{
|
||||
get { return DateTime.UtcNow.ToString("O"); }
|
||||
}
|
||||
public Dictionary<string, string> Data { get; set; } = new Dictionary<string, string>();
|
||||
/// <summary>
|
||||
/// Legacy attributes below
|
||||
/// </summary>
|
||||
public string VehicleId { get; set; } = "";
|
||||
public string Username { get; set; } = "";
|
||||
public string Action { get; set; } = "";
|
||||
}
|
||||
public class DiscordWebHook
|
||||
{
|
||||
public string Username { get { return "LubeLogger"; } }
|
||||
[JsonPropertyName("avatar_url")]
|
||||
public string AvatarUrl { get { return "https://hargata.github.io/hargata/lubelogger_logo_small.png"; } }
|
||||
public string Content { get; set; } = "";
|
||||
public static DiscordWebHook FromWebHookPayload(WebHookPayload webHookPayload)
|
||||
{
|
||||
return new DiscordWebHook
|
||||
{
|
||||
Content = webHookPayload.Action,
|
||||
};
|
||||
}
|
||||
}
|
||||
public class WebHookPayload: WebHookPayloadBase
|
||||
{
|
||||
private static string GetFriendlyActionType(string actionType)
|
||||
{
|
||||
var actionTypeParts = actionType.Split('.');
|
||||
if (actionTypeParts.Length == 2)
|
||||
{
|
||||
var recordType = actionTypeParts[0];
|
||||
var recordAction = actionTypeParts[1];
|
||||
switch (recordAction)
|
||||
{
|
||||
case "add":
|
||||
recordAction = "Added";
|
||||
break;
|
||||
case "update":
|
||||
recordAction = "Updated";
|
||||
break;
|
||||
case "delete":
|
||||
recordAction = "Deleted";
|
||||
break;
|
||||
}
|
||||
if (recordType.ToLower().Contains("record"))
|
||||
{
|
||||
var cleanedRecordType = recordType.ToLower().Replace("record", "");
|
||||
cleanedRecordType = $"{char.ToUpper(cleanedRecordType[0])}{cleanedRecordType.Substring(1)} Record";
|
||||
recordType = cleanedRecordType;
|
||||
} else
|
||||
{
|
||||
recordType = $"{char.ToUpper(recordType[0])}{recordType.Substring(1)}";
|
||||
}
|
||||
return $"{recordAction} {recordType}";
|
||||
} else if (actionTypeParts.Length == 3)
|
||||
{
|
||||
var recordType = actionTypeParts[0];
|
||||
var recordAction = actionTypeParts[1];
|
||||
var thirdPart = actionTypeParts[2];
|
||||
switch (recordAction)
|
||||
{
|
||||
case "add":
|
||||
recordAction = "Added";
|
||||
break;
|
||||
case "update":
|
||||
recordAction = "Updated";
|
||||
break;
|
||||
case "delete":
|
||||
recordAction = "Deleted";
|
||||
break;
|
||||
}
|
||||
if (recordType.ToLower().Contains("record"))
|
||||
{
|
||||
var cleanedRecordType = recordType.ToLower().Replace("record", "");
|
||||
cleanedRecordType = $"{char.ToUpper(cleanedRecordType[0])}{cleanedRecordType.Substring(1)} Record";
|
||||
recordType = cleanedRecordType;
|
||||
}
|
||||
else
|
||||
{
|
||||
recordType = $"{char.ToUpper(recordType[0])}{recordType.Substring(1)}";
|
||||
}
|
||||
if (thirdPart == "api")
|
||||
{
|
||||
return $"{recordAction} {recordType} via API";
|
||||
} else
|
||||
{
|
||||
return $"{recordAction} {recordType}";
|
||||
}
|
||||
}
|
||||
return actionType;
|
||||
}
|
||||
public static WebHookPayload FromGenericRecord(GenericRecord genericRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("description", genericRecord.Description);
|
||||
payloadDictionary.Add("odometer", genericRecord.Mileage.ToString());
|
||||
payloadDictionary.Add("vehicleId", genericRecord.VehicleId.ToString());
|
||||
payloadDictionary.Add("cost", genericRecord.Cost.ToString("F2"));
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = genericRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Description: {genericRecord.Description}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromGasRecord(GasRecord gasRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("odometer", gasRecord.Mileage.ToString());
|
||||
payloadDictionary.Add("fuelconsumed", gasRecord.Gallons.ToString());
|
||||
payloadDictionary.Add("vehicleId", gasRecord.VehicleId.ToString());
|
||||
payloadDictionary.Add("cost", gasRecord.Cost.ToString("F2"));
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = gasRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Odometer: {gasRecord.Mileage}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromOdometerRecord(OdometerRecord odometerRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("initialodometer", odometerRecord.InitialMileage.ToString());
|
||||
payloadDictionary.Add("odometer", odometerRecord.Mileage.ToString());
|
||||
payloadDictionary.Add("vehicleId", odometerRecord.VehicleId.ToString());
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = odometerRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Odometer: {odometerRecord.Mileage}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromTaxRecord(TaxRecord taxRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("description", taxRecord.Description);
|
||||
payloadDictionary.Add("vehicleId", taxRecord.VehicleId.ToString());
|
||||
payloadDictionary.Add("cost", taxRecord.Cost.ToString("F2"));
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = taxRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Description: {taxRecord.Description}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromPlanRecord(PlanRecord planRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("description", planRecord.Description);
|
||||
payloadDictionary.Add("vehicleId", planRecord.VehicleId.ToString());
|
||||
payloadDictionary.Add("cost", planRecord.Cost.ToString("F2"));
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = planRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Description: {planRecord.Description}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromReminderRecord(ReminderRecord reminderRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("description", reminderRecord.Description);
|
||||
payloadDictionary.Add("vehicleId", reminderRecord.VehicleId.ToString());
|
||||
payloadDictionary.Add("metric", reminderRecord.Metric.ToString());
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = reminderRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Description: {reminderRecord.Description}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromSupplyRecord(SupplyRecord supplyRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("description", supplyRecord.Description);
|
||||
payloadDictionary.Add("vehicleId", supplyRecord.VehicleId.ToString());
|
||||
payloadDictionary.Add("cost", supplyRecord.Cost.ToString("F2"));
|
||||
payloadDictionary.Add("quantity", supplyRecord.Quantity.ToString("F2"));
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = supplyRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Description: {supplyRecord.Description}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload FromNoteRecord(Note noteRecord, string actionType, string userName)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
payloadDictionary.Add("description", noteRecord.Description);
|
||||
payloadDictionary.Add("vehicleId", noteRecord.VehicleId.ToString());
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = noteRecord.VehicleId.ToString(),
|
||||
Username = userName,
|
||||
Action = $"{userName} {GetFriendlyActionType(actionType)} Description: {noteRecord.Description}"
|
||||
};
|
||||
}
|
||||
public static WebHookPayload Generic(string payload, string actionType, string userName, string vehicleId)
|
||||
{
|
||||
Dictionary<string, string> payloadDictionary = new Dictionary<string, string>();
|
||||
payloadDictionary.Add("user", userName);
|
||||
if (!string.IsNullOrWhiteSpace(payload))
|
||||
{
|
||||
payloadDictionary.Add("description", payload);
|
||||
}
|
||||
return new WebHookPayload
|
||||
{
|
||||
Type = actionType,
|
||||
Data = payloadDictionary,
|
||||
VehicleId = string.IsNullOrWhiteSpace(vehicleId) ? "N/A" : vehicleId,
|
||||
Username = userName,
|
||||
Action = string.IsNullOrWhiteSpace(payload) ? $"{userName} {GetFriendlyActionType(actionType)}" : $"{userName} {payload}"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user