Combining Tag usage counts in App. Converting Tag edit table to SortableTable.

This commit is contained in:
Roland 2023-09-12 21:31:32 -06:00
parent edd348f9af
commit 095634a4ea
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
3 changed files with 39 additions and 44 deletions

View file

@ -9,10 +9,7 @@ import {
GridRow,
Label,
LabelGroup,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow,
} from "semantic-ui-react";
import {APIButton, contrastingColor, ErrorMessage, scrollToTopOfElement} from "./components/Common";
@ -25,8 +22,7 @@ import {
ModalActions,
ModalContent,
ModalHeader,
Segment,
Table
Segment
} from "./components/Theme";
import _ from "lodash";
import {HexColorPicker} from "react-colorful";
@ -34,6 +30,7 @@ import {useRecurringTimeout} from "./hooks/customHooks";
import {Media, ThemeContext} from "./contexts/contexts";
import {Link, useNavigate} from "react-router-dom";
import {TagPlaceholder} from "./components/Placeholder";
import {SortableTable} from "./components/SortableTable";
export const TagsContext = React.createContext({
NameToTagLabel: null,
@ -151,7 +148,7 @@ export const useTagsInterval = () => {
function EditTagRow({tag, onDelete, onEdit}) {
const {NameToTagLabel} = React.useContext(TagsContext);
const {name, color, id, count} = tag;
const {name, color, id, file_group_count, zim_entry_count} = tag;
const deleteConfirm = <>
<APIButton
@ -166,7 +163,8 @@ function EditTagRow({tag, onDelete, onEdit}) {
const nameLabel = <LabelGroup tag>
<NameToTagLabel name={name}/>
</LabelGroup>;
const countLabel = <Label>{count}</Label>;
const countColor = (file_group_count + zim_entry_count) > 0 ? 'black' : 'grey';
const countLabel = <Label color={countColor}>{file_group_count + zim_entry_count}</Label>;
return <TableRow>
<TableCell>{deleteConfirm}</TableCell>
@ -226,11 +224,12 @@ function EditTagsModal() {
setTagColor(DEFAULT_TAG_COLOR);
}
let content = <Dimmer><Loader inline active/></Dimmer>;
if (tags && tags.length) {
content = tags.map(i => <EditTagRow key={i['name']} tag={i} onDelete={localDeleteTag}
onEdit={localEditTag}/>);
}
const tableHeaders = [
{key: 'delete', text: 'Delete', sortBy: null, width: 2},
{key: 'edit', text: 'Edit', sortBy: null, width: 2},
{key: 'name', text: 'Name', sortBy: 'name', width: 8},
{key: 'count', text: 'Count', sortBy: 'file_group_count', width: 2},
];
return <>
<Modal closeIcon
@ -266,25 +265,14 @@ function EditTagsModal() {
>Save</APIButton>
<Divider/>
<Table striped basic='very' unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell width={2}>Delete</TableHeaderCell>
<TableHeaderCell width={2}>Edit</TableHeaderCell>
<TableHeaderCell width={8}>Tag</TableHeaderCell>
<Media greaterThanOrEqual='tablet'>
{(className, renderChildren) => {
return renderChildren ?
<TableHeaderCell className={className} width={2}>Count</TableHeaderCell>
: null;
}}
</Media>
</TableRow>
</TableHeader>
<TableBody>
{content}
</TableBody>
</Table>
<SortableTable
data={tags}
rowFunc={(i, sortData) => <EditTagRow key={i['name']} tag={i} onDelete={localDeleteTag}
onEdit={localEditTag}/>}
rowKey='name'
tableHeaders={tableHeaders}
/>
</div>
</Modal>
<Button onClick={() => setOpen(true)} color='violet' disabled={tags === undefined}>

View file

@ -95,6 +95,10 @@ class Tag(ModelHelper, Base):
tag = session.query(Tag).filter_by(name=name).one_or_none()
return tag
def has_relations(self) -> bool:
"""Returns True if this Tag has been used with any FileGroups or Zim Entries."""
return not self.tag_files and not self.tag_zim_entries
class TagsConfig(ConfigFile):
file_name = 'tags.yaml'
@ -217,9 +221,10 @@ def schedule_save(session: Session = None):
def get_tags() -> List[dict]:
with get_db_curs() as curs:
curs.execute('''
SELECT t.id, t.name, t.color, COUNT(tf.tag_id)
SELECT t.id, t.name, t.color, COUNT(tf.tag_id) AS file_group_count, COUNT(tz.tag_id) AS zim_entry_count
FROM tag t
LEFT JOIN tag_file tf on t.id = tf.tag_id
LEFT JOIN tag_file tf on t.id = tf.tag_id
LEFT OUTER JOIN tag_zim tz on t.id = tz.tag_id
GROUP BY t.id, t.name, t.color
ORDER BY t.name
''')
@ -308,15 +313,6 @@ def import_tags_config(session: Session = None):
if new_tags:
session.add_all(new_tags)
config_tag_names = [i for i in config.tags.keys()]
for tag in session.query(Tag):
if tag.name not in config_tag_names:
if tag.tag_files or tag.tag_zim_entries:
logger.warning(f'Refusing to delete {tag} because it is used.')
else:
logger.warning(f'Deleting {tag} because it is not in the config.')
session.delete(tag)
session.commit()
media_directory = get_media_directory()
@ -395,6 +391,17 @@ def import_tags_config(session: Session = None):
elif not tag:
logger.warning(f'Cannot find Tag for {repr(str(zim_path))}')
if config.tags:
config_tag_names = set(config.tags.keys())
for tag in session.query(Tag):
if tag.name not in config_tag_names:
if tag.has_relations():
logger.warning(f'Refusing to delete {tag} because it is used.')
else:
logger.warning(f'Deleting {tag} because it is not in the config.')
session.delete(tag)
need_commit = True
if need_commit:
session.commit()
except Exception as e:

View file

@ -129,7 +129,7 @@ def test_tags_crud(test_session, test_client, example_pdf, assert_tags_config):
# The tag can be retrieved.
request, response = test_client.get('/api/tag')
assert response.status_code == HTTPStatus.OK
assert response.json['tags'] == [dict(name='jardín', color='#123456', id=1, count=0)]
assert response.json['tags'] == [dict(name='jardín', color='#123456', id=1, file_group_count=0, zim_entry_count=0)]
# Apply the tag to the PDF.
tag = test_session.query(tags.Tag).one()
@ -141,7 +141,7 @@ def test_tags_crud(test_session, test_client, example_pdf, assert_tags_config):
request, response = test_client.post('/api/tag/1', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
request, response = test_client.get('/api/tag')
assert response.json['tags'] == [dict(name='ガーデン', color='#000000', id=1, count=1)]
assert response.json['tags'] == [dict(name='ガーデン', color='#000000', id=1, file_group_count=1, zim_entry_count=0)]
assert_tags_config(tags={'ガーデン': {'color': '#000000'}})
# Conflicting names return an error.