Skip to content

Commit

Permalink
Merge pull request #189 from PASTA-ELN/sb_smallerBugs
Browse files Browse the repository at this point in the history
Repair smaller bugs that I found
  • Loading branch information
SteffenBrinckmann authored Jan 31, 2024
2 parents e171e20 + b3c36bc commit 151566e
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 49 deletions.
43 changes: 12 additions & 31 deletions pasta_eln/GUI/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,37 +433,18 @@ def execute(self, command:list[Any]) -> None:
# ---- if docType changed: save; no further save to db required ----
if hasattr(self, 'docTypeComboBox') and self.docTypeComboBox.currentData() != '':
self.doc['-type'] = [self.docTypeComboBox.currentData()]
if '_ids' in self.doc: #group update
self.doc = {k:v for k,v in self.doc.items() if v} # filter out empty items
for docID in self.doc.pop('_ids'):
doc = self.db.getDoc(docID)
doc.update( self.doc )
self.db.remove(doc['_id'])
del doc['_id']
del doc['_rev']
doc = fillDocBeforeCreate(doc, self.docTypeComboBox.currentData())
self.db.saveDoc(doc)
else: #single or sequential update
self.db.remove(self.doc['_id'])
del self.doc['_id']
del self.doc['_rev']
self.doc = fillDocBeforeCreate(self.doc, self.docTypeComboBox.currentData())
self.db.saveDoc(self.doc)
# ---- all other changes ----
else:
if '_ids' in self.doc: #group update
if '-name' in self.doc:
del self.doc['-name']
ids = self.doc.pop('_ids')
self.doc = {i:j for i,j in self.doc.items() if j!=''}
for docID in ids:
doc = self.db.getDoc(docID)
doc.update( self.doc )
self.comm.backend.editData(doc)
elif '_id' in self.doc: #default update on item
self.comm.backend.editData(self.doc)
else: #create new dataset
self.comm.backend.addData(self.doc['-type'][0], copy.deepcopy(self.doc), newProjID)
if '_ids' in self.doc: # group update
if '-name' in self.doc:
del self.doc['-name']
self.doc = {k:v for k,v in self.doc.items() if v} # filter out empty items
for docID in self.doc.pop('_ids'):
doc = self.db.getDoc(docID)
doc.update( self.doc )
self.comm.backend.editData(doc)
elif '_id' in self.doc: # default update on item
self.comm.backend.editData(self.doc)
else: # create new dataset
self.comm.backend.addData(self.doc['-type'][0], copy.deepcopy(self.doc), newProjID)
#!!! NO updates / redraw here since one does not know from where form came
# e.g. sequential edit cannot have redraw here
if command[0] is Command.FORM_SAVE_NEXT:
Expand Down
4 changes: 2 additions & 2 deletions pasta_eln/GUI/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,10 +339,10 @@ def modelChanged(self, item:QStandardItem) -> None:
item.setData(item.data() | {'hierStack': '/'.join(stackNew+[docID])})
# change siblings
for line in siblingsOld:
db.updateBranch(docID=line['id'], branch=line['value'][3], child=line['value'][0]-1)
db.updateBranch( docID=line['id'], branch=line['value'][4], child=line['value'][0]-1)
for line in siblingsNew:
if line['id']!=docID:
db.updateBranch(docID=line['id'], branch=line['value'][3], child=line['value'][0]+1)
db.updateBranch(docID=line['id'], branch=line['value'][4], child=line['value'][0]+1)
return


Expand Down
9 changes: 7 additions & 2 deletions pasta_eln/GUI/projectTreeView.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def contextMenuEvent(self, p:QPoint) -> None:
Args:
p (QPoint): point of clicking
"""
folder = self.currentIndex().data().split('/')[-1][0]=='x'
item = self.model().itemFromIndex(self.currentIndex())
folder = item.data()['hierStack'].split('/')[-1][0]=='x'
context = QMenu(self)
if folder:
Action('Add child folder', self, [Command.ADD_CHILD], context)
Expand Down Expand Up @@ -69,6 +70,7 @@ def execute(self, command:list[Any]) -> None:
child = QStandardItem('/'.join(hierStack+[docID]))
child.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled) # type: ignore
item.appendRow(child)
self.comm.changeProject.emit('','') #refresh project
#appendRow is not 100% correct:
# - better: insertRow before the first non-folder, depending on the child number
# -> get highest non 9999 childNumber
Expand All @@ -87,6 +89,7 @@ def execute(self, command:list[Any]) -> None:
child = QStandardItem('/'.join(hierStack+[docID]))
child.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled) # type: ignore
parent.appendRow(child)
self.comm.changeProject.emit('','') #refresh project
#++ TODO appendRow is not 100% correct: see above
elif command[0] is Command.DELETE:
ret = QMessageBox.critical(self, 'Warning', 'Are you sure you want to delete this data?',\
Expand Down Expand Up @@ -158,7 +161,9 @@ def tree2Clicked(self) -> None:
docID = item.data()['hierStack'].split('/')[-1]
doc = self.comm.backend.db.getDoc(docID)
self.comm.formDoc.emit(doc)
item = self.model().itemFromIndex(self.currentIndex())
docNew = self.comm.backend.db.getDoc(docID)
item.setText(docNew['-name'])
item.setData(item.data() | {"docType":docNew['-type'], "gui":docNew['-gui']})
item.emitDataChanged() #force redraw (resizing and repainting) of this item only
return

Expand Down
23 changes: 10 additions & 13 deletions pasta_eln/database.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
""" Class for interaction with couchDB """
import traceback, logging, time, json, os, re
import traceback, logging, time, json, os, re, base64, io
from typing import Any, Optional, Union
from pathlib import Path
from anytree import Node
from anytree.search import find_by_attr
from PIL import Image
from cloudant.client import CouchDB
from cloudant.replicator import Replicator
from PySide6.QtWidgets import QProgressBar # pylint: disable=no-name-in-module
from .fixedStringsJson import defaultDataHierarchy, defaultDataHierarchyNode
from .handleDictionaries import dataHierarchy_pre_to_V4
from .miscTools import tracebackString, DummyProgressBar
from .miscTools import tracebackString, DummyProgressBar, outputString

class Database:
"""
Expand Down Expand Up @@ -422,8 +423,7 @@ def updateBranch(self, docID:str, branch:int, child:int, stack:Optional[list[str
oldJsonContent = json.load(fIn)
oldDocID = oldJsonContent['_id']
if path is not None and (self.basePath/path).exists() and docID!=oldDocID:
print(f'**ERROR** Target folder already exist: {path}. Try to create a new path name')
logging.error('Target folder already exist: %s. Try to create a new path name', path)
logging.info('Target folder already exist: %s. I will try to create a new path name', path)
while path is not None and (self.basePath/path).exists() and docID!=oldDocID:
if re.search(r"_\d+$", path) is None:
path += '_1'
Expand Down Expand Up @@ -798,18 +798,15 @@ def checkDB(self, outputStyle:str='text', repair:bool=False, minimal:bool=False)
Returns:
str: output
"""
import base64, io
from PIL import Image
from .miscTools import outputString
outstring = ''
if outputStyle=='html':
outstring += '<div align="right">'
outstring+= outputString(outputStyle,'h2','LEGEND')
if not minimal:
outstring+= outputString(outputStyle,'ok','Green: perfect and as intended')
outstring+= outputString(outputStyle,'okish', 'Blue: ok-ish, can happen: empty files for testing, strange path for measurements')
outstring+= outputString(outputStyle,'unsure','Pink: unsure if bug or desired (e.g. move step to random path-name)')
outstring+= outputString(outputStyle,'warning','Yellow: WARNING should not happen (e.g. procedures without project)')
outstring+= outputString(outputStyle,'unsure', 'Dark magenta: unsure if bug or desired (e.g. move step to random path-name)')
outstring+= outputString(outputStyle,'warning','Orange-red: WARNING should not happen (e.g. procedures without project)')
outstring+= outputString(outputStyle,'error', 'Red: FAILURE and ERROR: NOT ALLOWED AT ANY TIME')
if outputStyle=='html':
outstring += '</div>'
Expand Down Expand Up @@ -910,12 +907,12 @@ def checkDB(self, outputStyle:str='text', repair:bool=False, minimal:bool=False)
#doc-type specific tests
if '-type' in doc and doc['-type'][0] == 'sample':
if 'qrCode' not in doc:
outstring+= outputString(outputStyle,'error',f"dch09: qrCode not in sample {doc['_id']}")
outstring+= outputString(outputStyle,'warning',f"dch09: qrCode not in sample {doc['_id']}")
elif '-type' in doc and doc['-type'][0] == 'measurement':
if 'shasum' not in doc:
outstring+= outputString(outputStyle,'error',f"dch10: shasum not in measurement {doc['_id']}")
outstring+= outputString(outputStyle,'warning',f"dch10: shasum not in measurement {doc['_id']}")
if 'image' not in doc:
outstring+= outputString(outputStyle,'error',f"dch11: image not in measurement {doc['_id']}")
outstring+= outputString(outputStyle,'warning',f"dch11: image not in measurement {doc['_id']}")
else:
if doc['image'].startswith('data:image'): #for jpg and png
try:
Expand Down Expand Up @@ -943,7 +940,7 @@ def checkDB(self, outputStyle:str='text', repair:bool=False, minimal:bool=False)
shasumKeys = []
for item in view:
if item['key']=='':
outstring+= outputString(outputStyle,'error', f"measurement without shasum: {item['id']} {item['value']}")
outstring+= outputString(outputStyle,'warning', f"measurement without shasum: {item['id']} {item['value']}")
else:
if item['key'] in shasumKeys:
key = item['key'] or '- empty string -'
Expand Down
2 changes: 1 addition & 1 deletion pasta_eln/miscTools.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def outputString(fmt:str='print', level:str='info', message:str='') -> str:
if 'text' in fmt:
return txtOutput
if fmt=='html':
colors = {'info':'black','error':'red','warning':'orange','ok':'green','okish':'blue','unsure':'magenta'}
colors = {'info':'black','error':'red','warning':'orangered','ok':'green','okish':'blue','unsure':'darkmagenta'}
if level[0]=='h':
return f'<{level}>{message}</{level}>'
if level not in colors:
Expand Down

0 comments on commit 151566e

Please sign in to comment.