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
|
import re
from pathlib import Path
from urllib.parse import urljoin
from django.db import models
from django.template import loader
from django.urls import reverse
import settings
from troggle.core.models.troggle import Expedition, TroggleModel
"""The model declarations LogBookEntry, PersonLogEntry, QM
"""
todo = """
"""
class LogbookEntry(TroggleModel):
"""Single parsed entry from Logbook
Gets deleted if the Expedition gets deleted"""
date = (
models.DateField()
)
expedition = models.ForeignKey(Expedition, blank=True, null=True, on_delete=models.CASCADE, db_index=True)
title = models.CharField(max_length=200)
cave = models.ForeignKey("Cave", blank=True, null=True, on_delete=models.SET_NULL, db_index=True)
place = models.CharField(
max_length=100, blank=True, null=True, help_text="Only use this if you haven't chosen a cave"
)
other_people = models.CharField(max_length=200, blank=True, null=True) # foreign_friends and *guests
text = models.TextField()
slug = models.SlugField(max_length=50) # this is tripid
time_underground = models.FloatField(null=True, help_text="In decimal hours")
class Meta:
verbose_name_plural = "Logbook Entries"
# several PersonLogEntrys point in to this object
ordering = ("-date",)
def isLogbookEntry(self): # Function used in templates
return True
def get_absolute_url(self):
# we do not use URL_ROOT any more.
return reverse("logbookentry", kwargs={"date": self.date, "slug": self.slug})
def __str__(self):
return f"{self.date}: {self.title}"
def get_participants(self):
'''the string that goes into an edited or rewritten logbook entry
which replaces this horrendous Django template code:
<div class="trippeople">{% for personlogentry in logbook_entry.personlogentry_set.all %}{% if personlogentry.is_logbook_entry_author %}<u>{% if personlogentry.nickname_used %}{{personlogentry.nickname_used|safe}}{% else %}{{personlogentry.personexpedition.person|safe}}{% endif %}</u>,{% endif %}{% endfor %}{% for personlogentry in logbook_entry.personlogentry_set.all %}{% if personlogentry.is_logbook_entry_author %}{% else %}{% if personlogentry.nickname_used %}{{personlogentry.nickname_used|safe}}{% else %}{{personlogentry.personexpedition.person|safe}}{% endif %},{% endif %}{% endfor %}{% if logbook_entry.other_people %}, {{logbook_entry.other_people}}{% endif %}</div>
'''
if author := (
PersonLogEntry.objects.filter(logbook_entry=self, is_logbook_entry_author=True)
.first()
):
if author.nickname_used:
expoer = author.nickname_used
else:
expoer = author.personexpedition.person.name()
else:
expoer = "nobody"
names = f"<u>{expoer}</u>"
participants = (
PersonLogEntry.objects.filter(logbook_entry=self, is_logbook_entry_author=False)
.order_by("personexpedition__person__slug")
.all()
)
for p in participants:
if p.nickname_used:
expoer = p.nickname_used
else:
expoer = p.personexpedition.person.name()
names += f", {expoer}"
if self.other_people:
names += f", {self.other_people}"
return names
def get_next_by_id(self):
LogbookEntry.objects.get(id=self.id + 1)
def get_previous_by_id(self):
LogbookEntry.objects.get(id=self.id - 1)
def DayIndex(self):
"""This is used to set different colours for the different trips on
the calendar view of the expedition"""
mx = 10
todays = list(LogbookEntry.objects.filter(date=self.date))
if self in todays:
index = todays.index(self)
else:
print(f"DayIndex: Synchronization error in logbook entries. Restart server or do full reset. {self}")
index = 0
if index not in range(0, mx):
print(f"DayIndex: More than {mx-1} LogbookEntry items on one day '{index}' {self}, restarting colour sequence.")
index = index % mx
return index
def writelogbook(year, filename):
"""Writes all the database logbook entries into a new logbook.html file
"""
current_expedition = Expedition.objects.get(year=year)
logbook_entries = LogbookEntry.objects.filter(expedition=current_expedition).order_by(
"slug"
) # now that slug, aka tripid, is in our standard date form, this will preserve ordering.
print(f" - Logbook to be exported has {len(logbook_entries)} entries in it.")
try:
t = loader.get_template("logbook2005style.html")
logbookfile = t.render({"logbook_entries": logbook_entries})
except:
print(" ! Very Bad Error RENDERING template ", t)
raise
# print(" - template rendered")
try:
try:
endpath = Path(settings.EXPOWEB, "years", str(year), "endmatter.html")
except:
print(" ! FAIL Path " + {(settings.EXPOWEB, "years", year, "endmatter.html")})
raise
# print(f" - endpath {endpath}")
endmatter = ""
if endpath.is_file():
# print(" - endpath")
try:
with open(endpath, "r") as end:
endmatter = end.read()
except:
print(" ! Very Bad Error opening " + endpath)
raise
except:
print(" ! FAIL endpath " + endpath)
raise
# print(" - endpath opened")
frontpath = Path(settings.EXPOWEB, "years", str(year), "frontmatter.html")
if frontpath.is_file():
try:
with open(frontpath, "r") as front:
frontmatter = front.read()
except:
print(" ! Very Bad Error opening " + frontpath)
logbookfile = re.sub(r"<body>", "<body>\n" + frontmatter + endmatter, logbookfile)
else:
logbookfile = re.sub(r"<body>", f"<body>\n<h1>Expo {year}</h1>\n" + endmatter, logbookfile)
dir = Path(settings.EXPOWEB) / "years" / str(year)
filepath = Path(dir, filename)
try:
with (open(filepath, "w")) as lb:
lb.writelines(logbookfile)
except:
print(" ! Very Bad Error writing to " + filepath)
raise
# print(f'Logbook exported to {filepath}')
class PersonLogEntry(TroggleModel):
"""Single Person going on a trip.
In future it could account for different T/U for people in same logbook entry.
CASCADE means that if the personexpedition or the logbookentry is deleted,
then this PersonLogEntry is deleted too
"""
personexpedition = models.ForeignKey("PersonExpedition", null=True, on_delete=models.CASCADE, db_index=True)
time_underground = models.FloatField(help_text="In decimal hours")
logbook_entry = models.ForeignKey(LogbookEntry, on_delete=models.CASCADE, db_index=True)
is_logbook_entry_author = models.BooleanField(default=False)
nickname_used = models.CharField(max_length=100,default="") # e.g. "Animal" or "Zonker", as it appears in the original logbook
class Meta:
ordering = ("nickname_used", "-personexpedition")
# order_with_respect_to = 'personexpedition' and then with nickname
# within the same logbook entry (which will always be the same expedition) this will
# now not re-order the participants in a trip every time we save the logbook.
# but this does not work.. need a function
def next_personlog(self):
futurePTs = (
PersonLogEntry.objects.filter(
personexpedition=self.personexpedition, logbook_entry__date__gt=self.logbook_entry.date
)
.order_by("logbook_entry__date")
.all()
)
if len(futurePTs) > 0:
return futurePTs[0]
else:
return None
def prev_personlog(self):
pastPTs = (
PersonLogEntry.objects.filter(
personexpedition=self.personexpedition, logbook_entry__date__lt=self.logbook_entry.date
)
.order_by("-logbook_entry__date")
.all()
)
if len(pastPTs) > 0:
return pastPTs[0]
else:
return None
def place(self):
return self.logbook_entry.cave and self.logbook_entry.cave or self.logbook_entry.place
def __str__(self):
return f"{self.personexpedition} ({self.logbook_entry.date})"
class QM(TroggleModel):
"""This is based on qm.csv in trunk/expoweb/1623/204 which has the fields:
"Number","Grade","Area","Description","Page reference","Nearest station","Completion description","Comment"
All the stuff handling TICK QMs is INCOMPLETE
"""
number = models.IntegerField(
help_text="this is the sequential number in the year, only unique for CSV imports",
)
grade = models.CharField(max_length=1, blank=True, null=True, help_text="A/B/C/D/X")
cave = models.ForeignKey("Cave", related_name="QMs", blank=True, null=True, on_delete=models.SET_NULL)
block = models.ForeignKey("SurvexBlock", null=True, on_delete=models.SET_NULL) # only for QMs from survex files
blockname = models.TextField(blank=True, null=True) # NB truncated copy of survexblock name with last char added
expoyear = models.CharField(max_length=4, blank=True, null=True)
ticked = models.BooleanField(default=False)
location_description = models.TextField(blank=True, null=True)
completion_description = models.TextField(blank=True, null=True)
completion_date = models.DateField(blank=True, null=True)
nearest_station_name = models.CharField(max_length=200, blank=True, null=True)
resolution_station_name = models.CharField(max_length=200, blank=True, null=True)
area = models.CharField(max_length=100, blank=True, null=True)
page_ref = models.TextField(blank=True, null=True)
comment = models.TextField(blank=True, null=True)
def __str__(self):
return f"{self.code()}"
def code(self):
if self.cave:
cavestr = str(self.cave.slug())[5:]
else:
cavestr = ""
if self.expoyear:
expoyearstr = str(self.expoyear)
else:
expoyearstr = str(self.cave.slug())[5:9]
if self.blockname:
blocknamestr = "-" + str(self.blockname)
else:
blocknamestr = ""
return f"{cavestr}-{expoyearstr}-{self.number}{self.grade}{blocknamestr}"
def newslug(self):
qmslug = f"{str(self.cave)}-{self.expoyear}-{self.blockname}{self.number}{self.grade}"
return qmslug
def get_absolute_url(self):
# This reverse resolution stuff is pure magic. Just change the regex in urls.py and everything changes to suit. Whacky.
return urljoin(
settings.URL_ROOT,
reverse(
"qm",
kwargs={
"cave_id": self.cave.slug(),
"year": self.expoyear,
"blockname": self.blockname,
"qm_id": self.number,
"grade": self.grade,
},
),
)
def get_next_by_id(self): # called in template
return QM.objects.get(id=self.id + 1)
def get_previous_by_id(self): # called in template
return QM.objects.get(id=self.id - 1)
|