summaryrefslogtreecommitdiffstats
path: root/update_mensa.sh
blob: 8c44fc783b317d4bc53bb8092092f28cc7951da2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env bash

# Source the common utils and the environment variable loader
source load_common_and_env.sh

# (Attempt to) take variable we need
BENUTZERID=${MENSA_USER}
PASSWORT=${MENSA_PASS}
FF3PAT=${FF3_PAT}
FF3URL=${FF3_URL}

# Fixed variables
AUTHORIZATION="S0FTVkM6ekt2NXlFMUxaVW12VzI5SQ=="
USER_AGENT="Mozilla/5.0 (Windows NT 10.0; rv:120.0) Gecko/20100101 Firefox/120.0"

# Function to format date to DD.MM.YYYY
format_date() {
    date -d "$1" '+%d.%m.%Y'
}

# Function to get Unix timestamp
get_unix_timestamp() {
    echo $(date +%s)
}

# Function to url-encode strings
url_encode() {
    local encoded=""
    local length="${#1}"
    for (( i=0; i<length; i++ )); do
        local c="${1:i:1}"
        case $c in
            [a-zA-Z0-9.~_-]) encoded+="$c" ;;
            *) encoded+=$(printf '%%%02X' "'$c") ;;
        esac
    done

    echo "$encoded"
}

# Function to log in and get auth token
login_and_get_token() {
    local login_url="https://ks.stw.berlin:4433/TL1/TLM/KASVC/LOGIN?karteNr=$BENUTZERID&format=JSON&datenformat=JSON"

    # Perform the login request and extract the authToken
    local login_response=$(curl -s -X POST "$login_url" \
        -H "User-Agent: $USER_AGENT" \
        -H 'Accept: application/json, text/javascript, */*; q=0.01' \
        -H 'Accept-Language: en-US,en;q=0.5' \
        -H 'Accept-Encoding: gzip, deflate, br' \
        -H 'Referer: https://ks.stw.berlin:4433/Kartenservice/' \
        -H "Authorization: Basic $AUTHORIZATION" \
        -H 'X-Requested-With: XMLHttpRequest' \
        -H 'DNT: 1' \
        -H 'Sec-GPC: 1' \
        -H 'Connection: keep-alive' \
        -H 'Sec-Fetch-Dest: empty' \
        -H 'Sec-Fetch-Mode: cors' \
        -H 'Sec-Fetch-Site: same-origin' \
        -H 'TE: trailers' \
        -H 'Content-Type: application/json' \
        --data-raw '{"BenutzerID":"'"$BENUTZERID"'","Passwort":"'"$PASSWORT"'"}')

    echo $(echo "$login_response" | jq -r '.[0].authToken')
}

# Default date range: From 10 days ago to today
START_DATE=$(format_date '10 days ago')
END_DATE=$(format_date 'tomorrow')

# Check for user-provided parameters
if [ "$#" -eq 2 ]; then
    START_DATE=$(format_date "$1")
    END_DATE=$(format_date "$2")
elif [ "$#" -ne 0 ]; then
    echo "Invalid number of arguments. Usage: $0 [start_date end_date]"
    exit 1
fi

# Login and get auth token
auth_token=$(login_and_get_token)
#echo "Auth token: $auth_token"
encoded_auth_token=$(url_encode "$auth_token")
#echo "Encoded Auth token: $encoded_auth_token"

# Modify these URLs and parameters as per your API documentation
data_retrieval_url1="https://ks.stw.berlin:4433/TL1/TLM/KASVC/TRANSPOS"
data_retrieval_url2="https://ks.stw.berlin:4433/TL1/TLM/KASVC/TRANS"

# Data Retrieval
DATA1=$(curl -s "$data_retrieval_url1?format=JSON&authToken=$encoded_auth_token&karteNr=$BENUTZERID&datumVon=$START_DATE&datumBis=$END_DATE&_=$(get_unix_timestamp)" \
-H "User-Agent: $USER_AGENT" \
-H 'Accept: application/json, text/javascript, */*; q=0.01' \
-H 'Accept-Language: en-US,en;q=0.5' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Referer: https://ks.stw.berlin:4433/Kartenservice/' \
-H "Authorization: Basic $AUTHORIZATION" \
-H 'X-Requested-With: XMLHttpRequest' \
-H 'DNT: 1' \
-H 'Sec-GPC: 1' \
-H 'Connection: keep-alive' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: same-origin' \
-H 'TE: trailers')

DATA2=$(curl -s "$data_retrieval_url2?format=JSON&authToken=$encoded_auth_token&karteNr=$BENUTZERID&datumVon=$START_DATE&datumBis=$END_DATE&_=$(get_unix_timestamp)" \
-H "User-Agent: $USER_AGENT" \
-H 'Accept: application/json, text/javascript, */*; q=0.01' \
-H 'Accept-Language: en-US,en;q=0.5' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Referer: https://ks.stw.berlin:4433/Kartenservice/' \
-H "Authorization: Basic $AUTHORIZATION" \
-H 'X-Requested-With: XMLHttpRequest' \
-H 'DNT: 1' \
-H 'Sec-GPC: 1' \
-H 'Connection: keep-alive' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Site: same-origin' \
-H 'TE: trailers')

## Print the retrieved data
#echo "Data from the first request:"
#echo "$DATA1"

#echo "Data from the second request:"
#echo "$DATA2"

# Assuming DATA1 and DATA2 are set with the respective JSON data
combine_data() {
    local positions="$1"
    local transactions="$2"

    echo "$transactions" | jq --argjson positions "$positions" '[
      .[] as $transaction |
      {
        date: $transaction.datum,
        mensa: $transaction.ortName,
        totalAmount: (-1 * $transaction.zahlBetrag),
        items: ($positions | map(select(.transFullId == $transaction.transFullId)) | map({name: .name, menge: .menge, epreis: .epreis}))
      }
    ]'
}

combined_data=$(combine_data "$DATA1" "$DATA2")

#echo "Combined data:"
#echo "$combined_data"

# Function to create a Firefly III transaction
create_firefly_transaction() {
    local transaction_data="$1"

    curl -X POST "$FF3URL/api/v1/transactions" \
      -H 'accept: application/vnd.api+json' \
      -H "Authorization: Bearer $FF3PAT" \
      -H 'Content-Type: application/json' \
      --data "$transaction_data"

    echo
}

format_date_for_firefly() {
    local input_date="$1"
    # Extract components from the input date format "DD.MM.YYYY HH:MM"
    local day=$(echo "$input_date" | cut -d. -f1)
    local month=$(echo "$input_date" | cut -d. -f2)
    local year=$(echo "$input_date" | cut -d. -f3 | cut -d' ' -f1)
    local ti_me=$(echo "$input_date" | cut -d' ' -f2)

    # Construct the date in the format "YYYY-MM-DDTHH:MM:00"
    local converted_date="${year}-${month}-${day}T${ti_me}:00"

    # Get the timezone offset for Berlin
    local timezone_offset=$(date '+%:z')

    # Combine the date and timezone offset
    local formatted_date="${converted_date}${timezone_offset}"

    echo "$formatted_date"
}

# Process and send each transaction
echo "$combined_data" | jq -c '.[]' | while read -r transaction; do
    # Check if the transaction is "Karte aufwerten"
    if echo "$transaction" | jq -e '.items[] | select(.name == "Karte aufwerten")' > /dev/null; then
        # Special handling for "Karte aufwerten"
        date=$(echo "$transaction" | jq -r '.date')
        formatted_date=$(format_date_for_firefly "$date")
        totalAmount=$(echo "$transaction" | jq -r '(-1 * .totalAmount)')

#        echo "Recharge:"

        firefly_data=$(jq -n \
          --arg date "$formatted_date" \
          --arg amount "$totalAmount" \
          '{
            error_if_duplicate_hash: true,
            apply_rules: false,
            transactions: [
              {
                type: "transfer",
                date: $date,
                amount: $amount,
                description: " 	Guthaben Mensa",
                category_id: 5,
                source_id: 31,
                destination_id: 45,
              }
            ]
          }')
    else
        # Extract and format transaction data
        date=$(echo "$transaction" | jq -r '.date')
        formatted_date=$(format_date_for_firefly "$date")
        totalAmount=$(echo "$transaction" | jq -r '.totalAmount')
        notes=$(echo "$transaction" | jq -c '[.items[] | "\(.menge): \(.name) (\(.epreis) €)"]')
        mensa=$(echo "$transaction" | jq -r '.mensa')

#        echo "$notes, $totalAmount"

        # Prepare the data for the Firefly III API
        firefly_data=$(jq -n \
          --arg date "$formatted_date" \
          --arg amount "$totalAmount" \
          --argjson notes "$notes" \
          --arg tag "$mensa" \
          '{
            error_if_duplicate_hash: true,
            apply_rules: false,
            transactions: [
              {
                type: "withdrawal",
                date: $date,
                amount: $amount,
                description: ("Essen " + $tag),
                budget_id: "2",
                category_id: "1",
                source_id: "45",
                destination_id: "191",
                tags: [$tag],
                notes: (if $notes | length == 0 then null else $notes | join("  \n") end)
              }
            ]
          }')
    fi

    # Create the transaction in Firefly III
#    echo "$firefly_data"
    create_firefly_transaction "$firefly_data"
done