2
0
mirror of https://expo.survex.com/repositories/troggle/.git synced 2024-11-25 08:41:51 +00:00

refactored and most recent wallet link fixed

This commit is contained in:
Philip Sargent 2023-02-03 17:13:29 +00:00
parent e70d51e52b
commit c1231ff451
2 changed files with 263 additions and 258 deletions

View File

@ -315,7 +315,7 @@ def walletedit(request, path=None):
wallet = f"{year}:{wnumber:02d}" wallet = f"{year}:{wnumber:02d}"
return (None, wallet) return (None, wallet)
def identify_most_recent_wallet(wallet, y): def identify_most_recent_wallet(wallet, currentyear):
""" Need to find the last wallet of the previous year """ Need to find the last wallet of the previous year
Has to cope with years when there are no wallets Has to cope with years when there are no wallets
Has to cope with weirdly named imported wallets from 1999 & earlier Has to cope with weirdly named imported wallets from 1999 & earlier
@ -328,47 +328,47 @@ def walletedit(request, path=None):
try: try:
allwallets = Wallet.objects.all().order_by('walletname') allwallets = Wallet.objects.all().order_by('walletname')
previous_wallet = allwallets.first() recent_wallet = allwallets.first()
for w in allwallets: for w in allwallets:
if len(w.walletname) < 5: if len(w.walletname) < 5:
continue continue
if w.walletname[4] != "#": if w.walletname[4] != "#":
continue continue
if w.walletname == current_name: if w.walletname == current_name:
break break
if int(w.walletyear.year) >= int(y): if int(w.walletyear.year) >= int(currentyear):
break break
previous_wallet = w recent_wallet = w
name = previous_wallet.walletname recent_name = recent_wallet.walletname
y = name[:4]
prevy = f"{int(y)-1}"
n = name[5:]
prev = f"{int(n):02d}"
except: except:
raise raise
prev = f"{int(n):02d}"
recent_year = recent_name[:4]
recent_number = recent_name[5:]
print(prev, prevy, y) print(f"---identify_most_recent_wallet: {recent_year=} {recent_number=}")
return prev, prevy, y return recent_year, recent_number
def create_nav_links(wallet): def create_nav_links(wallet):
"""Find the previous wallet and next wallet and create navigation shortcuts""" """Find the previous wallet and next wallet and create navigation shortcuts"""
y = wallet[:4] y = wallet[:4]
n = wallet[5:] n = wallet[5:]
nexty = f"{int(y)+1}"
prevy = f"{int(y)-1}"
next = f"{int(n)+1:02d}"
prev = f"{int(n)-1:02d}"
if int(n) == 0: if int(n) == 0:
prev, prevy, y = identify_most_recent_wallet(wallet, y) recent_year, recent_number = identify_most_recent_wallet(wallet, y)
prevy = recent_year # same as most recent wallet
return next, nexty, prev, prevy, y recent_number = f"{int(recent_number):02d}"
else:
prevy = f"{int(y)-1}" # the previous year
recent_year = y # current year
recent_number = f"{int(n)-1:02d}" # previous number
nexty = f"{int(y)+1}"
next = f"{int(n)+1:02d}"
return prevy, recent_year, recent_number, y, next, nexty
def read_json(): def read_json(contents_path):
"""Read JSON from the wallet metadata file in the repo """Read JSON from the wallet metadata file in the repo
or fills with blank data if that files can't be read or fills with blank data if that files can't be read
@ -476,7 +476,112 @@ def walletedit(request, path=None):
def get_logbook_trips(): def get_logbook_trips():
return None return None
def no_people(team):
return (team == ["Unknown"]
or team == [""]
or team == "")
def scan_survexblocks(svxfile):
"""Scans for *team people attached to all the survex blocks in this svxfile
This could be rather a lot for some compedious survex files! So would need
culling manually and only those relevant put in the JSON file"""
wallet_refs = []
dates = []
blocknames = []
team = []
try:
blocks = SurvexBlock.objects.filter(survexfile=svxfile)
for b in blocks:
print(f" - - {b=} {b.scanswallet=} {b.date=}")
if b.scanswallet:
wallet_refs.append(b.scanswallet) # other wallets
if b.scanswallet.walletname == wallet:
if b.date:
dates.append(b.date)
if b.name != b.title:
blocknames.append(str(b.name) + "|" + str(b.title))
else:
blocknames.append(str(b.name))
# we can use the people, across all blocks that have this *ref
QSpeople = SurvexPersonRole.objects.filter(survexblock=b)
# print(f" - - {QSpeople=}")
for p in QSpeople:
print(f" - - {p.personname} ")
team.append(p.personname)
except:
message = " - No associated survex blocks found for this wallet"
print(message)
return wallet_refs, dates, blocknames, team
def scan_survexfiles(survex_paths):
"""Read data from the list of survex file names attached to the wallet JSON file
NEED TO ALSO CHECK survex files which have a *ref to this wallet !
"""
cave_refs = []
wallet_refs = []
caves = []
dates = []
names = []
team = []
if not type(survex_paths) == list: # a string also is a sequence type, so do it this way
survex_paths = [survex_paths]
for svxf in survex_paths:
if not svxf: # not a blank string
continue
print(f" - - {svxf=} ")
svx = Path(svxf)
if svx.suffix.lower() != ".svx":
svx = svx.with_suffix(".svx")
f = Path(settings.SURVEX_DATA) / svx
if not f.is_file():
continue
fpath = svx.parent / svx.stem
# print(f' - {fpath=}')
try:
svxfile = SurvexFile.objects.get(path=fpath)
print(f" - {svxfile=}")
if svxfile.cave:
caves.append(svxfile.cave)
cave_refs.append(svxfile.cave.reference())
wallet_refs, dates, names, team = scan_survexblocks(svxfile)
except:
message = "Specified survex file not found - database may be empty."
print(message)
# This failure will also get picked up by the "S" colour code red or orange
if len(cave_refs) == 1:
caves = cave_refs[0]
elif len(cave_refs) > 1:
print(
f" - More than one Cave {caves} in this wallet {wallet}. Not managed in this troggle release."
)
if len(names) == 1:
names = names[0]
elif len(names) > 1:
names = f"several, please edit: {names}"
print(
f" - More than one block name is relevant {names} in this wallet {wallet}. Not managed in this troggle release."
)
cave_refs = list(set(cave_refs))
caves = list(set(caves))
firstdate = None
if dates:
firstdate = min(dates).isoformat()
return firstdate, list(set(team)), caves, cave_refs, wallet_refs, names
checkboxes = [ checkboxes = [
"description written", "description written",
"survex not required", "survex not required",
@ -493,7 +598,7 @@ def walletedit(request, path=None):
redirect, wallet = preprocess_path(path) redirect, wallet = preprocess_path(path)
if redirect: if redirect:
return redirect return redirect
next, nexty, prev, prevy, year = create_nav_links(wallet) prevy, recent_year, recent_number, year, next, nexty = create_nav_links(wallet)
wurl = f"/walletedit/{wallet}".replace("#", ":") wurl = f"/walletedit/{wallet}".replace("#", ":")
wallet = wallet.replace(":", "#") wallet = wallet.replace(":", "#")
@ -572,7 +677,7 @@ def walletedit(request, path=None):
multiple = request.FILES.getlist("uploadfiles") multiple = request.FILES.getlist("uploadfiles")
fs = FileSystemStorage(os.path.join(dirpath)) # creates wallet folder if necessary fs = FileSystemStorage(os.path.join(dirpath)) # creates wallet folder if necessary
waldata = read_json() waldata = read_json(contents_path)
actual_saved = [] actual_saved = []
if multiple: if multiple:
for f in multiple: for f in multiple:
@ -623,7 +728,7 @@ def walletedit(request, path=None):
if dirs: if dirs:
dirs = sorted(dirs) dirs = sorted(dirs)
try: try:
waldata = read_json() waldata = read_json(contents_path)
except: except:
message = f"Nasty failure in parsing wallets metadata in {contents_path}. Probably backslash not forward slash in filename path" message = f"Nasty failure in parsing wallets metadata in {contents_path}. Probably backslash not forward slash in filename path"
return render(request, "errors/generic.html", {"message": message}) return render(request, "errors/generic.html", {"message": message})
@ -646,251 +751,151 @@ def walletedit(request, path=None):
trips = [] trips = []
checked = {} checked = {}
context = {} context = {}
if waldata: # should always be true as populated by blank data if json file doesn't exist if not waldata: # should always be true as populated by blank data if json file doesn't exist
if 'notes not required' not in waldata: message = f" !! No Wallet data initialised or read ! Should not happen."
waldata['notes not required'] = False print(message)
return render(request, "errors/generic.html", {"message": message})
if ( if no_people(waldata["people"]):
not waldata["date"] team = []
or not waldata["people"] names = []
or waldata["people"] == ["Unknown"]
or waldata["people"] == [""] refs = []
or waldata["cave"] == ""
): # json file does not exist, blank data, or people not typed into JSON file if "survex file" in waldata:
# refactor into separate functions for no date set or no people set or no cave set date, team, caves, caverefs, wallet_refs, names = scan_survexfiles(waldata["survex file"])
# print(f'No date set')
print(f"\n - Incomplete, empty or default wallet data {wallet} {waldata=}") print(f"--- date from survexfiles scan {date}")
refs = [] print(f"--- date from django object {Wallet.objects.filter(walletname=wallet)[0].walletdate}")
dates = [] # Override the discovered values with those in the JSON file:
team = [] if not waldata["date"]: # either absent or empty string
caverefs = [] waldata["date"] = date
caves = []
names = []
svxf = ""
if waldata["survex file"]:
if not type(waldata["survex file"]) == list: # a string also is a sequence type, so do it this way
waldata["survex file"] = [waldata["survex file"]]
for svxf in waldata["survex file"]:
if svxf:
svx = Path(svxf)
if svx.suffix.lower() != ".svx":
svx = svx.with_suffix(".svx")
f = Path(settings.SURVEX_DATA) / svx
if f.is_file():
fpath = svx.parent / svx.stem
# print(f' - {fpath=}')
try:
svxfile = SurvexFile.objects.get(path=fpath)
print(f" - {svxfile=}") if "people" in waldata:
if svxfile.cave: people = waldata["people"] # text string
caves.append(svxfile.cave) else:
caverefs.append(svxfile.cave.reference()) people = team
blocks = SurvexBlock.objects.filter(survexfile=svxfile) waldata["people"] = team
for b in blocks:
print(f" - - {b=} {b.scanswallet=} {b.date=}")
if b.scanswallet:
refs.append(b.scanswallet)
if b.scanswallet.walletname == wallet:
if b.date:
dates.append(b.date)
if b.name != b.title:
names.append(str(b.name) + "|" + str(b.title))
else:
names.append(str(b.name))
# we can use the people, across all blocks that have this *ref
QSpeople = SurvexPersonRole.objects.filter(survexblock=b)
print(f" - - {QSpeople=}")
for p in QSpeople:
print(f" - - {p.personname} ")
team.append(p.personname)
# else:
# print(f' - Wallet not matching *ref {b.scanswallet=} {wallet}')
except:
message = "Specified survex file not found - database may be empty, or this survex file is not *included anywhere."
# return render(request, 'errors/generic.html', {'message': message})
pass
if dates: if "cave" in waldata:
waldata["date"] = min(dates).isoformat() cave = waldata["cave"] # text string
print(f" - - {team=} ") else:
team = list(set(team)) cave = caves
waldata["people"] = team waldata["cave"] = caves
if waldata["name"]:
psg = waldata["name"]
else:
psg = names
waldata["name"] = names
if "free text" in waldata:
freetext = waldata["free text"]
if 'notes not required' not in waldata: # cope with schema change
waldata['notes not required'] = False
caverefs = list(set(caverefs)) # for a in waldata:
caves = list(set(caves)) # print(f"'{waldata[a]}' {a}")
# find trips and survex files of the same date
if len(caverefs) == 1: if date:
waldata["cave"] = caverefs[0] datestr = date.replace(".", "-")
print(f" - Setting wallet cave to {caverefs[0]}") try:
# waldata["description url"] = caves[0] samedate = datetime.date.fromisoformat(datestr)
elif len(caverefs) == 0: except ValueError:
waldata["cave"] = "" # probably a single digit day number. HACKUS MAXIMUS.
# waldata["description url"] = "" # clearly we need to fix this when we first import date strings..
print(f" - No caves in this wallet {wallet}. ") datestr = datestr[:-1] + "0" + datestr[-1]
else: print(f" - {datestr=} ")
waldata["cave"] = "several caves"
# waldata["description url"] = "several.."
print(
f" - More than one Cave {caves} in this wallet {wallet}. Not managed in this troggle release."
)
if len(names) == 1:
if waldata["name"] == "":
waldata["name"] = names[0]
print(f" - Setting wallet name to {names[0]}")
elif len(names) == 0:
waldata["name"] = ""
print(" - Setting wallet name blank")
else:
waldata["name"] = f"several, please edit: {names}"
print(
f" - More than one block name is relevant {names} in this wallet {wallet}. Not managed in this troggle release."
)
if "cave" in waldata:
cave = waldata["cave"] # text string
else:
cave = ""
if waldata["name"]:
psg = waldata["name"]
if "free text" in waldata:
freetext = waldata["free text"]
# find trips and survex files of the same date
if waldata["date"]:
datestr = waldata["date"].replace(".", "-")
try: try:
samedate = datetime.date.fromisoformat(datestr) samedate = datetime.date.fromisoformat(datestr)
except ValueError: except:
# probably a single digit day number. HACKUS MAXIMUS.
# clearly we need to fix this when we first import date strings..
datestr = datestr[:-1] + "0" + datestr[-1]
print(f" - {datestr=} ")
try: try:
samedate = datetime.date.fromisoformat(datestr) samedate = datetime.date.fromisoformat(datestr[:10])
except: except:
try: samedate = None
samedate = datetime.date.fromisoformat(datestr[:10]) walletobject = make_wallet(wallet)
except: walletobject.walletdate = samedate
samedate = None walletobject.save()
walletobject = make_wallet(wallet)
walletobject.walletdate = samedate
walletobject.save()
try:
thisexpo = Expedition.objects.get(year=int(year))
except: # creating a wallet for an expo that does not exist perhaps
message = f"Trying to access an Expo for '{year}' which does not exist (yet)."
message += " See /handbook/computing/newyear.html"
print(message)
return render(request, "errors/generic.html", {"message": message})
if samedate:
svxothers = SurvexBlock.objects.filter(date=samedate)
trips = LogbookEntry.objects.filter(date=samedate)
else:
svxothers = None
trips = None
try:
thisexpo = Expedition.objects.get(year=int(year))
except: # creating a wallet for an expo that does not exist perhaps
message = f"Trying to access an Expo for '{year}' which does not exist (yet)."
message += " See /handbook/computing/newyear.html"
print(message)
return render(request, "errors/generic.html", {"message": message})
if samedate:
svxothers = SurvexBlock.objects.filter(date=samedate)
trips = LogbookEntry.objects.filter(date=samedate)
else: else:
svxothers = None svxothers = None
trips = None trips = None
# Survex and survex complaints, comes from json file on disc, not as pre-populated as above else:
complaints, caveobject = get_complaints([], waldata, svxfiles, files, wallet, wurl) svxothers = None
# print(f' - {caveobject=}') trips = None
for f in checkboxes: # Survex and survex complaints, comes from json file on disc, not as pre-populated as above
if waldata[f]: complaints, caveobject = get_complaints([], waldata, svxfiles, files, wallet, wurl)
checked[f] = "checked" # print(f' - {caveobject=}')
survexsize = str(min(len(str(waldata["survex file"])), 46)) for f in checkboxes:
if waldata[f]:
checked[f] = "checked"
try: survexsize = str(min(len(str(waldata["survex file"])), 46))
thiswallet = Wallet.objects.get(walletname=wallet)
caveifywallet(thiswallet)
thiswallet.ticks = thiswallet.get_ticks() # the complaints in colour form
# fixsurvextick(thiswallet, thiswallet.ticks)
# print(f"--- {wallet} {thiswallet} walletdate={thiswallet.walletdate} immediately before form render")
except:
thiswallet = None
context = {
"year": year,
"prev": prev,
"next": next,
"prevy": prevy,
"nexty": nexty,
"files": files,
"dirs": dirs,
"waldata": waldata,
"svxfiles": svxfiles,
"checked": checked,
"trips": trips,
"manywallets": [thiswallet],
"svxothers": svxothers,
"create": create,
"metadataurl": metadataurl,
"metadata": metadata,
"complaints": complaints,
"caveobject": caveobject,
"people": waldata["people"],
"peoplesize": str(len(str(waldata["people"]))),
"filesaved": filesaved,
"actual_saved": actual_saved,
}
return render( try:
request, thiswallet = Wallet.objects.get(walletname=wallet)
"walletform.html", caveifywallet(thiswallet)
{ thiswallet.ticks = thiswallet.get_ticks() # the complaints in colour form
"form": form, # fixsurvextick(thiswallet, thiswallet.ticks)
"wallet": wallet, # print(f"--- {wallet} {thiswallet} walletdate={thiswallet.walletdate} immediately before form render")
**context, except:
"date": waldata["date"], thiswallet = None
#'url': waldata["description url"], 'urlsize': str(len(str(waldata["description url"]))), context = {
"survex": waldata["survex file"], "year": year,
"survexsize": survexsize, "recent_year": recent_year,
"cave": cave, "recent_number": recent_number,
"psg": psg, "next": next,
"freetext": freetext, "prevy": prevy,
"psgsize": str(max(12, len(str(psg)))), "nexty": nexty,
"freetextsize": str(max(60, len(str(freetext)))), "files": files,
}, "dirs": dirs,
) "waldata": waldata,
else: # no wallet data: should never happen as there should be default data in all cases "svxfiles": svxfiles,
print(f"! - Should never get here ! Problem in wallet editing...") "checked": checked,
context = { "trips": trips,
"year": year, "manywallets": [thiswallet],
"prev": prev, "svxothers": svxothers,
"next": next, "create": create,
"prevy": prevy, "metadataurl": metadataurl,
"nexty": nexty, "metadata": metadata,
"files": files, "complaints": complaints,
"dirs": dirs, "caveobject": caveobject,
"waldata": waldata, "people": people,
"svxfiles": svxfiles, "peoplesize": str(len(str(people))),
"checked": checked, "filesaved": filesaved,
"create": create, "actual_saved": actual_saved,
"people": "", }
"peoplesize": 12,
"filesaved": filesaved, return render(
"actual_saved": actual_saved, request,
} "walletform.html",
{
"form": form,
"wallet": wallet,
**context,
"date": waldata["date"],
#'url': waldata["description url"], 'urlsize': str(len(str(waldata["description url"]))),
"survex": waldata["survex file"],
"survexsize": survexsize,
"cave": cave,
"psg": psg,
"freetext": freetext,
"psgsize": str(max(12, len(str(psg)))),
"freetextsize": str(max(60, len(str(freetext)))),
},
)
return render(
request,
"walletform.html",
{
"form": form,
"wallet": wallet,
**context,
"date": "",
#'url': "", 'urlsize': 12,
"survex": "",
"survexsize": 46,
"cave": cave,
"psg": psg,
"freetext": freetext,
"psgsize": 12,
"freetextsize": 20,
},
)

View File

@ -31,7 +31,7 @@
<p style="font-family: monospace; font-weight: bold; font-size: 130%; text-align: center"> <p style="font-family: monospace; font-weight: bold; font-size: 130%; text-align: center">
<a style="font-weight: normal;" href="/walletedit/{{prevy}}:01">{{prevy}}</a> <a style="font-weight: normal;" href="/walletedit/{{prevy}}:01">{{prevy}}</a>
&nbsp;...&nbsp; &nbsp;...&nbsp;
<a href="/walletedit/{{year}}:{{prev}}">{{year}}:{{prev}}</a> <a href="/walletedit/{{recent_year}}:{{recent_number}}">{{recent_year}}:{{recent_number}}</a>
&larr; {{wallet}} &rarr; &larr; {{wallet}} &rarr;
<a href="/walletedit/{{year}}:{{next}}">{{year}}:{{next}}</a> <a href="/walletedit/{{year}}:{{next}}">{{year}}:{{next}}</a>
&nbsp;...&nbsp; &nbsp;...&nbsp;
@ -254,7 +254,7 @@
<em>No other survex files found for this date.</em><br> <em>No other survex files found for this date.</em><br>
{% endif %} {% endif %}
{% if metadataurl %}<span style="font-size: 70%; "><details><summary> {% if metadataurl %}<span style="font-size: 70%; "><details open><summary>
JSON <br> JSON <br>
</summary> </summary>
<a href="{{metadataurl}}">{{metadataurl}}</a><br> <a href="{{metadataurl}}">{{metadataurl}}</a><br>