1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
|
import subprocess
from datetime import datetime, timedelta, timezone
from pathlib import Path
from django import forms
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render
import settings
from troggle.core.models.caves import GetCaveLookup
from troggle.core.models.logbooks import LogbookEntry, PersonLogEntry, writelogbook
from troggle.core.models.survex import DrawingFile
from troggle.core.models.troggle import DataIssue, Expedition, PersonExpedition
from troggle.core.utils import (
COOKIE_MAX_AGE,
add_commit,
alphabet_suffix,
current_expo,
get_editor,
is_identified_user,
git_string,
sanitize_name,
unique_slug,
write_and_commit,
)
from troggle.parsers.people import GetPersonExpeditionNameLookup, known_foreigner
# from databaseReset import reinit_db # don't do this. databaseRest runs code *at import time*
from .auth import login_required_if_public
"""Logbook edit 'view'
Note that there are other file upload forms in views/wallet_edit.py views/uploads.py
and that core/forms.py contains Django class-based forms for caves and entrances.
"""
todo = """ - It's all still a bit messy.
- When this is used to create a totally new form, we could with some integration between the Logbook Entry author
and the git "--author" field which is used (only) for the version control attribution.
- Track down how James Waite crashes this every time he touches it. (Or did in 2024)
"""
def create_new_lbe_slug(date):
onthisdate = LogbookEntry.objects.filter(date=date)
n = len(onthisdate)
print(f" Already entries on this date: {n}\n {onthisdate}")
suffix = alphabet_suffix(n+1)
tid = f"{date}{suffix}"
if len(tid) <=4 :
print(f"BAD ERROR {tid=}")
tid = f"{date}_{LogbookEntry.objects.count()}_{n}" # fudged number
print(f"{tid=}")
return tid
def store_edited_entry_into_database(date, place, title, text, others, author, tu, slug):
"""saves a single logbook entry and related personlogentry items
need to select out *guest and foreign friends from others
Rather similar to similarly named function in parsers/logbooks but circular reference prevents us using it directly,
and they need refactoring anyway.
"""
year = slug[0:4]
expedition = Expedition.objects.get(year=year)
cave = GetCaveLookup().get(place.lower())
# print(f"store_edited_entry_into_database(): {place=} {cave=}")
if LogbookEntry.objects.filter(slug=slug).exists():
# oops.
message = f" ! - DUPLICATE SLUG for logbook entry {date} - {slug}"
DataIssue.objects.create(parser="logbooks", message=message)
slug = slug + "_" + unique_slug(text,2)
otherAttribs = {
"place": place,
"text": text,
"expedition": expedition,
"time_underground": tu,
"cave": cave,
"title": f"{place} - {title}",
# "other_people": others
}
coUniqueAttribs = {"slug": slug, "date": date }
lbo = LogbookEntry.objects.create(**otherAttribs, **coUniqueAttribs)
pt_list = []
# These entities have to be PersonExpedition objects
team = others.split(",")
team.append(author)
odds = []
for name in team:
name = name.strip()
if len(name) > 0:
if name[0] == "*": # a name prefix of "*" is special, just a string.
odds.append(name)
print(f" - adding * special name '{name}'")
else:
try:
personyear = GetPersonExpeditionNameLookup(expedition).get(name.lower())
if not personyear:
odds.append(name)
print(f" - adding unrecognised expoer '{name}'")
if known_foreigner(name):
message = f" ! - Known foreigner: '{name}' in entry {slug=}"
print(message)
else:
message = f" ! - No name match for: '{name}' in entry {slug=}"
print(message)
DataIssue.objects.create(parser="logbooks", message=message)
else:
coUniqueAttribs = {"personexpedition": personyear, "nickname_used": name, "logbook_entry": lbo} # lbo is primary key
otherAttribs = {"time_underground": tu, "is_logbook_entry_author": (name==author)}
pt_list.append(PersonLogEntry(**otherAttribs, **coUniqueAttribs))
except:
# This should not happen. We do not raise exceptions in that function
message = f" ! - EXCEPTION: '{name}' in entry {slug=}"
print(message)
DataIssue.objects.create(parser="logbooks", message=message)
raise
PersonLogEntry.objects.bulk_create(pt_list)
lbo.other_people = ", ".join(odds)
print(f" - Saving other_people '{lbo.other_people}'")
lbo.save()
@login_required_if_public
def logbookedit(request, year=None, slug=None):
"""Edit a logbook entry
This 'validates' the author as being on expo in the current year, but only indicates this by
putting the text of the form prompt in red (same as for an invalid date, which is arguably more important).
No check is done on the other people on the trip as this is picked up anyway by parsing on import
and we don't really care at this point.
"""
def yesterday():
yesterday = datetime.now() - timedelta(1)
return yesterday.strftime('%Y-%m-%d')
def validate_year(year):
try:
expo = Expedition.objects.get(year=year)
except:
year = current_expo() # creates new Expedition object if needed
return year
def new_entry_form():
# set the date to be "yesterday" as this will, hopefully, usually be the case
return render(
request,
"logbookform.html",
{
"form": form,
"year": year,
"yesterday": yesterday(),
"identified_login": identified_login,
"who_are_you": editor,
},
)
def clean_tu(tu):
if tu =="":
return 0
try:
tu = float(tu)/1 # check numeric
except:
return 0
return tu
if not year:
if not slug: # not in the URL, we have not read teh POST response yet.. wich might have a slug in it
year = current_expo()
else:
year = slug[0:4]
try:
year = str(int(year)) # but maybe slug was hand-edited to be a future year..
year = validate_year(year) # so fix that
except:
year = current_expo()
author = ""
identified_login = is_identified_user(request.user)
editor = get_editor(request)
if request.method == "POST":
prev_slug = "" # None value pending overwrite from submitted form
form = LogbookEditForm(request.POST)
if not form.is_valid():
message = f'Invalid form response for logbook entry creating "{request.POST}"'
print(message)
return render(request, "errors/generic.html", {"message": message})
else:
editor = form.cleaned_data["who_are_you"]
editor = git_string(editor)
# if there is no slug then this is probably a completely new lbe and we need to enter it into the db
# otherwise it is an update
# validation all to be done yet..
date = request.POST["date"].strip()
author = request.POST["author"].strip() # TODO check against personexpedition on submit
others = request.POST["others"].strip() # TODO check each against personexpedition on submit
place = request.POST["place"].strip().replace(' - ',' = ') # no hyphens !
title = request.POST["title"].strip()
entry = request.POST["text"].strip()
if "prev_slug" in request.POST:
prev_slug = request.POST["prev_slug"].strip() # if we are re-editing the same entry again
entry = entry.replace('\r','') # remove HTML-standard CR inserted from form.
entry = entry.replace('\n\n','\n<p>\n') # replace 2 \n with <p>
tu = request.POST["tu"].strip()
tu = clean_tu(tu)
try:
odate = datetime.strptime(date.replace(".", "-"), "%Y-%m-%d").date()
print(f"{odate.year=}")
if str(odate.year) == year:
dateflag = False
else:
print(f"Trying to change the year ! No!! {odate.year=}")
odate = datetime.strptime(f"{year}-01-01", "%Y-%m-%d").date()
dateflag = True
except:
odate = datetime.strptime(f"{year}-01-01", "%Y-%m-%d").date()
print(f"! Invalid date string {date}, setting to {odate}")
dateflag = True
date = odate.isoformat()
year = validate_year(year)
expo = Expedition.objects.get(year=year)
personyear = GetPersonExpeditionNameLookup(expo).get(author.lower())
if personyear:
authorflag = False
else:
authorflag = True
print(f"! Unrecognised author: {author}")
# if somehow we get a slug set to just '2024', not eg '2020-08-10b'
# because the URL of the page is /logbookedit/2022 for a new entry
# This is a hack, why can we not reproduce this bug on the dev system?
if slug not in locals():
slug = ""
if len(slug) < 11:
slug = ""
if len(prev_slug) < 11:
prev_slug = ""
if not prev_slug and not slug:
# Creating a new logbook entry with all the gubbins
slug = create_new_lbe_slug(date)
if prev_slug and not slug:
# if this was a previous post, then prev_slug will have been set on the form
# we are editing a previous thing, so we don't create a new lbe
slug = prev_slug
# OK we could patch the object in place, but if the people on the trip have changed this
# would get very messy. So we delete it, and thus all the dependent objects,
# and recreate it and all its links. It might not exist though.
print(f"- Deleting the LogBookEntry {slug}")
LogbookEntry.objects.filter(slug=slug).delete() # works even if it does not exist
print(f"- Creating the LogBookEntry {slug}")
year = slug[0:4]
try:
expedition = Expedition.objects.get(year=year)
except Expedition.DoesNotExist:
message = f'''! - This expo "{year}" not created yet
It needs to be created before you can save a logbook entry.
See /handbook/computing/newyear.html
WHAT TO DO NOW:
1. Press the Back button on your broswer to return to the screen where you typed up the entry,
2. Copy the text of what you wrote into a new text file,
3. Direct a nerd to fix this. It should take only a couple of minutes.'''
print(message)
return render(request, "errors/generic.html", {"message": message})
store_edited_entry_into_database(date, place, title, entry, others, author, tu, slug)
print(f"- Rewriting the entire {year} logbook to disc ")
filename= "logbook.html"
try:
print(f" - Logbook for {year} to be exported and written out.")
writelogbook(year, filename) # uses a template, not the code fragment below which is just a visible hint to logged on user
except:
message = f'! - Logbook saving failed - \n!! Permissions failure ?! on attempting to save file "logbook.html"'
print(message)
return render(request, "errors/generic.html", {"message": message})
# Code fragment illustration - not actually what gets saved to database
output = f'''
<div class="tripdate" id="{slug}">{date}</div>
<div class="trippeople"><u>{author}</u>, {others}</div>
<div class="triptitle">{place} - {title}</div>
{entry}
<div class="timeug">T/U {tu} hrs</div>
<hr />
'''
# Successful POST
# So save to database and then write out whole new logbook.html file
# We do author validation on the form as displayed by GET, not at the moment of POST.
# If we had JS validation then we could be more timely.
dirpath = Path(settings.EXPOWEB) / "years" / str(year)
contents_path = dirpath / filename
commit_msg = f"Online edit of logbookentry {slug}"
add_commit(contents_path, commit_msg, editor)
# This does not change the URL in the browser, so despite a new slug being created,
# the next time this code is run it thinks a new slug needs to be created. So we should
# actually redirect to a new URL (an edit not a create) not simply return a render object.
# logbookedit/2022-08-21a
# HOWEVER by doing a redirect rather than returning a rendered page, we lose all the
# error settings e.g dateflag and authroflag so the user gets no feedback about bad data entered.
# so we need to pass the flags explicitly in the url and then extract them from the request in the GET bit. sigh.
response = HttpResponseRedirect(f"/logbookedit/{slug}?dateflag={dateflag}&authorflag={authorflag}")
response.set_cookie('editor_id', editor, max_age=COOKIE_MAX_AGE) # cookie expires after COOKIE_MAX_AGE seconds
return response
# Do the redirect instead of this:
# return render(
# request,
# "logbookform.html",
# {
# "form": form,
# "year": year,
# "date": date, "dateflag": dateflag,
# "author": author, "authorflag": authorflag,
# "others": others,
# "place": place,
# "title": title,
# "tu": tu,
# "entry": entry,
# "output": output,
# "slug": slug,
# },
# )
# GET here. Does not fall-through from the POST section.
else:
# Since this form is manually made, not Django constructed, this "initial=" setting has no effect.
form = LogbookEditForm(initial={"who_are_you":editor})
year = validate_year(year)
if request.GET.get('dateflag', 'False') == "True":
dateflag = True
else:
dateflag = False
if request.GET.get('authorflag', 'False') == "True":
authorflag = True
else:
authorflag = False
if not slug: # no slug or bad slug for an lbe which does not exist
return new_entry_form()
else:
lbes = LogbookEntry.objects.filter(slug=slug)
if not lbes:
return new_entry_form()
else:
if len(lbes) > 1:
return render(request, "object_list.html", {"object_list": lbes}) # ie a bug
else:
lbe = lbes[0]
print(f"{lbe}")
tu = clean_tu(lbe.time_underground)
people = []
for p in lbe.personlogentry_set.filter(logbook_entry=lbe): # p is a PersonLogEntry object
if p.is_logbook_entry_author:
# author = p.personexpedition.person.fullname
author = p.nickname_used
else:
# people.append(p.personexpedition.person.fullname)
people.append(p.nickname_used)
others =', '.join(people)
if lbe.other_people:
others = others + ", " + lbe.other_people
lenothers = min(70,max(20, len(others)))
text = lbe.text
rows = max(5,len(text)/50)
return render(
request,
"logbookform.html",
{
"form": form,
"year": year,
"date": lbe.date.isoformat(), "dateflag": dateflag,
"author": author, "authorflag": authorflag,
"others": others,
"lenothers": lenothers,
"place": lbe.place,
"title": lbe.title.replace(f"{lbe.place} - ",""),
"tu": tu,
"entry": text,
"textrows": rows,
"slug": slug,
"identified_login": identified_login,
"who_are_you": editor,
},
)
class LogbookEditForm(forms.Form): # not a model-form, just a form-form
author = forms.CharField(strip=True, required=False)
identified_login = forms.BooleanField(required=False,widget=forms.CheckboxInput(attrs={"onclick":"return false"})) # makes it readonly
who_are_you = forms.CharField(
widget=forms.TextInput( # a manual form, not a Django generated form, so this widget is not used.
attrs={"size": 100, "placeholder": "You are editing this page, who are you ? e.g. 'Wookey' or 'Animal <mta@gasthof.expo>'",
"style": "vertical-align: text-top;"}
)
)
|