1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

feat: tag badges choose the tag, untagged rows, counts in the tag list

On the VM and host lists a tag's badge chooses it in the tag list, the
tag list offers "No tag" for the rows without one, and each choice says
how many of the listed rows it shows ("prod (42)"); an owner counts only
their own VMs.
This commit is contained in:
catborise 2026-11-18 22:08:02 +03:00
parent f8cb6f1e0f
commit 904dd860d0
15 changed files with 110 additions and 57 deletions

View file

@ -1,3 +1,4 @@
from collections import Counter
from ipaddress import ip_address
from django.core.exceptions import ValidationError
@ -30,6 +31,13 @@ class Tag(Model):
def __str__(self):
return self.name
@staticmethod
def counts(rows):
"""The tag list's choices for rows (VMs or hosts, their tags read):
[(name, how many have it)] by name, and how many have no tag."""
counts = Counter(tag.name for row in rows for tag in row.tags.all())
return sorted(counts.items()), sum(1 for row in rows if not row.tags.all())
@classmethod
def named(cls, names):
"""The tags of names, those not there yet made."""

View file

@ -82,7 +82,7 @@
</div>
<div class="small text-body-secondary font-monospace mt-1">{{ compute.hostname }}</div>
{% if compute.details %}<div class="small text-body-secondary">{{ compute.details }}</div>{% endif %}
{% with tags=compute.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' %}</div>{% endif %}{% endwith %}
{% with tags=compute.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' with filter=True %}</div>{% endif %}{% endwith %}
{% if compute.status is not True %}
<div class="small text-danger">{{ compute.connection_error }}</div>
{% endif %}

View file

@ -106,5 +106,6 @@ class HostTagsTests(TestCase):
compute.tags.add(Tag.objects.create(name="rack-1"))
response = self.client.get(reverse("computes"))
self.assertContains(response, "rack-1")
self.assertContains(response, '<option value="rack-1">rack-1</option>', html=True)
self.assertContains(response, '<option value="rack-1">rack-1 (1)</option>', html=True)
self.assertContains(response, 'data-tag-filter="rack-1"')
self.assertContains(response, 'data-tags="rack-1"')

View file

@ -36,7 +36,7 @@ from computes.forms import (
TcpComputeForm,
TlsComputeForm,
)
from computes.models import ENDPOINT, Compute
from computes.models import ENDPOINT, Compute, Tag
from . import utils
@ -180,7 +180,7 @@ def computes(request):
totals["memory"] += given["memory"]
return render(request, "computes/list.html",
{"computes": computes, "totals": totals, "job_resource": claims.bulk_migrate_key(),
"tags": sorted({tag.name for compute in computes for tag in compute.tags.all()})})
"tags": Tag.counts(computes)})
@superuser_only

View file

@ -3,7 +3,7 @@
{# a VM's name, its title, and with owners its owners: the first as a badge, the others counted #}
<a class="fw-semibold text-break" href="{% url 'instances:instance' instance.id %}">{{ instance.name }}</a>
{% if instance.info and instance.title %}<div class="small text-body-secondary text-break">{{ instance.title }}</div>{% endif %}
{% with tags=instance.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' %}</div>{% endif %}{% endwith %}
{% with tags=instance.tags.all %}{% if tags %}<div class="mt-1">{% include 'common/tag_badges.html' with filter=True %}</div>{% endif %}{% endwith %}
{% if owners %}
{% with users=instance.userinstance_set.all %}
{% if users %}

View file

@ -115,6 +115,8 @@ filterInstances(page([group(tagged)], "", "", undefined, {tag: "pro"}));
assert.deepStrictEqual(visible(tagged), [], "a tag is a whole name");
filterInstances(page([group(tagged)], "", "", undefined, {tag: ""}));
assert.deepStrictEqual(visible(tagged), ["web-1", "db-1", "web-2"], "no tag chosen: all");
filterInstances(page([group(tagged)], "", "", undefined, {tag: "-"}));
assert.deepStrictEqual(visible(tagged), ["web-2"], "-: the rows without a tag");
const tagCounts = [count(""), count("Active"), count("Off")];
filterInstances(page([group(tagged)], "", "Active", undefined, {tag: "prod", counts: tagCounts}));
assert.deepStrictEqual(tagCounts.map((c) => c.textContent), [2, 1, 1], "the state counts follow the tag");
@ -142,9 +144,17 @@ assert.deepStrictEqual(visible(turkish), ["Şişli"]);
"state-pills": {querySelectorAll: () => pillList, querySelector: () => pillList[0], addEventListener() {}},
"tag-filter": {value: "", options: [{value: ""}, {value: "prod"}], addEventListener() {}},
};
const doc = {title: "VMs", getElementById: (id) => elements[id], querySelectorAll: () => []};
const listeners = {};
const doc = {title: "VMs", getElementById: (id) => elements[id], querySelectorAll: () => [],
addEventListener: (name, fn) => { listeners[name] = fn; }};
const storage = {getItem: (k) => stored[k] || null, setItem: (k, v) => { stored[k] = v; }, removeItem: (k) => { delete stored[k]; }};
vmModule.runInNewContext(fs.readFileSync(process.argv[2], "utf8"), {document: doc, sessionStorage: storage});
assert.strictEqual(elements["state-filter"].value, "Off");
assert.strictEqual(elements["tag-filter"].value, "prod", "the chosen tag is remembered too");
// a tag's badge chooses it in the list
const badge = {dataset: {tagFilter: "web"}};
elements["tag-filter"].options.push({value: "web"});
listeners.click({target: {closest: (s) => (s === "[data-tag-filter]" ? badge : null)}});
assert.strictEqual(elements["tag-filter"].value, "web", "a badge chooses its tag");
assert.strictEqual(stored["VMs_filter_tag"], "web", "and it is remembered");
}

View file

@ -76,10 +76,15 @@ class VmListTagFilterTests(TestCase):
patch.object(Compute, "status", new_callable=PropertyMock, return_value=True):
return lxml_html.fromstring(self.client.get(reverse("instances:index")).content)
def test_the_tag_list_has_the_tags_of_the_vms_listed(self):
def test_the_tag_list_has_the_tags_of_the_vms_listed_with_how_many(self):
Instance.objects.create(compute=Compute.objects.get(), name="bare", uuid="12345678-0000-0000-0000-00000000cc03")
doc = self.page(self.admin)
self.assertEqual(doc.xpath("//select[@id='tag-filter']/option/@value"), ["", "prod", "secret", "web"])
self.assertEqual(doc.xpath("//tr[@data-tags]/@data-tags"), ["prod web", "secret"])
self.assertEqual(doc.xpath("//select[@id='tag-filter']/option/@value"), ["", "-", "prod", "secret", "web"])
self.assertEqual([" ".join(o.split()) for o in doc.xpath("//select[@id='tag-filter']/option/text()")],
["All tags", "No tag (1)", "prod (1)", "secret (1)", "web (1)"])
self.assertEqual(doc.xpath("//tr[@data-tags]/@data-tags"), ["", "prod web", "secret"])
# a badge chooses its tag in the list
self.assertEqual(doc.xpath("//tr//button[@data-tag-filter]/@data-tag-filter"), ["prod", "web", "secret"])
def test_an_owner_sees_only_the_tags_of_their_vms(self):
doc = self.page(self.owner)

View file

@ -129,7 +129,7 @@ def index(request):
"reachable_computes": [c for c in computes if c.status is True and c.ram_usage is not None],
"unreachable_computes": [c for c in computes if c.status is not True],
"states": [label for label, _color in STATES.values()] + [UNKNOWN[0]],
"tags": sorted({tag.name for instance in instances for tag in instance.tags.all()}),
"tags": Tag.counts(instances),
"states_url": reverse("instances:states"), "vm_states": vm_states},
)

Binary file not shown.

View file

@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-18 18:30+0000\n"
"POT-Creation-Date: 2026-11-18 19:06+0000\n"
"PO-Revision-Date: 2020-11-04 12:00+0000\n"
"Last-Translator: catborise <muhammetalisag@gmail.com>, 2020\n"
"Language-Team: Turkish (https://www.transifex.com/catborise/teams/110663/tr/)\n"
@ -157,8 +157,8 @@ msgstr "en fazla yedek boyutu (GiB)"
msgid "Can change password"
msgstr "Parola değiştirebilir"
#: accounts/models.py:98 appsettings/models.py:9 computes/models.py:25
#: computes/models.py:44 instances/models.py:33
#: accounts/models.py:98 appsettings/models.py:9 computes/models.py:26
#: computes/models.py:52 instances/models.py:33
msgid "name"
msgstr "ad"
@ -2143,7 +2143,7 @@ msgstr "Dengele"
msgid "%(compute)s is in maintenance: Balance leaves it out"
msgstr "%(compute)s bakımda: Dengele onu hesaba katmaz"
#: computes/models.py:19
#: computes/models.py:20
msgid ""
"A tag is letters a-z, digits, dots, dashes and underscores, and begins with a"
" letter or digit"
@ -2151,27 +2151,27 @@ msgstr ""
"Etiket a-z harfleri, rakamlar, nokta, tire ve alt çizgiden oluşur ve harf ya "
"da rakamla başlar"
#: computes/models.py:45
#: computes/models.py:53
msgid "hostname"
msgstr "sunucuadı"
#: computes/models.py:46
#: computes/models.py:54
msgid "login"
msgstr "kullanıcı"
#: computes/models.py:47
#: computes/models.py:55
msgid "password"
msgstr "parola"
#: computes/models.py:48
#: computes/models.py:56
msgid "details"
msgstr "detaylar"
#: computes/models.py:51
#: computes/models.py:59
msgid "migration address"
msgstr "taşıma adresi"
#: computes/models.py:57
#: computes/models.py:65
msgid ""
"IP address or host name the other hosts send migrating VMs to; empty: the "
"address the panel reaches the host at"
@ -2179,11 +2179,11 @@ msgstr ""
"Diğer sunucuların taşınan sanal makineleri gönderdiği IP adresi veya ana "
"bilgisayar adı; boş: panelin bu sunucuya ulaştığı adres"
#: computes/models.py:62 computes/templates/computes/form.html:38
#: computes/models.py:70 computes/templates/computes/form.html:38
msgid "gstfsd key"
msgstr "gstfsd anahtarı"
#: computes/models.py:68
#: computes/models.py:76
msgid ""
"GSTFSD_KEY in the host's /etc/default/webvirt-gstfsd: the panel sets the root"
" password and SSH key of a shut-off VM with it; empty: they cannot be set "
@ -2193,16 +2193,16 @@ msgstr ""
"sanal makinenin root parolasını ve SSH anahtarını bununla ayarlar; boş: bu "
"sunucuda ayarlanamazlar"
#: computes/models.py:82 instances/models.py:38
#: computes/models.py:90 instances/models.py:38
msgid "tags"
msgstr "etiketler"
#: computes/models.py:98 computes/templates/computes/instances.html:12
#: computes/models.py:106 computes/templates/computes/instances.html:12
#, python-format
msgid "%(compute)s is in maintenance: no new VM or migration comes to it"
msgstr "%(compute)s bakımda: ona yeni sanal makine ya da taşıma gelmez"
#: computes/models.py:104
#: computes/models.py:112
#, python-format
msgid ""
"%(compute)s is in maintenance: its VMs cannot be started there; migrate the "
@ -2211,12 +2211,12 @@ msgstr ""
"%(compute)s bakımda: sanal makineleri orada başlatılamaz; başka bir sunucuda "
"başlatmak için sanal makineyi taşıyın"
#: computes/models.py:231
#: computes/models.py:239
#, python-format
msgid "This host is already added as %(name)s"
msgstr "Bu sunucu zaten %(name)s olarak ekli"
#: computes/models.py:234
#: computes/models.py:242
#, python-format
msgid ""
"The panel cannot reach the host to tell that its VMs are there: %(error)s"
@ -2224,7 +2224,7 @@ msgstr ""
"Panel sunucuya ulaşamadığı için VM'lerinin orada olduğunu doğrulayamıyor: "
"%(error)s"
#: computes/models.py:241
#: computes/models.py:249
msgid ""
"The host its VMs are on is not known yet: change the connection when the "
"panel has reached the host at its current one"
@ -2232,7 +2232,7 @@ msgstr ""
"VM'lerinin bulunduğu sunucu henüz bilinmiyor: bağlantıyı, panel sunucuya "
"mevcut bağlantısından ulaştıktan sonra değiştirin"
#: computes/models.py:244
#: computes/models.py:252
msgid "This is another host than the one its VMs are on: add it as a new host"
msgstr ""
"Bu, VM'lerinin bulunduğu sunucudan başka bir sunucu: yeni bir sunucu olarak "
@ -9666,10 +9666,19 @@ msgstr ""
msgid "Delete <strong>%(object)s</strong>?"
msgstr "<strong>%(object)s</strong> silinsin mi?"
#: templates/common/tag_badges.html:2
msgid "Show only this tag"
msgstr "Yalnız bu etiketi göster"
#: templates/common/tag_filter.html:4
msgid "All tags"
msgstr "Tüm etiketler"
#: templates/common/tag_filter.html:5
#, python-format
msgid "No tag (%(untagged)s)"
msgstr "Etiketsiz (%(untagged)s)"
#: templates/error.html:13
msgid "HTTP status"
msgstr "HTTP durumu"

Binary file not shown.

View file

@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-18 18:30+0000\n"
"POT-Creation-Date: 2026-11-18 19:06+0000\n"
"PO-Revision-Date: \n"
"Last-Translator: \n"
"Language-Team: \n"
@ -154,8 +154,8 @@ msgstr "最大备份大小 (GiB)"
msgid "Can change password"
msgstr "可修改密码"
#: accounts/models.py:98 appsettings/models.py:9 computes/models.py:25
#: computes/models.py:44 instances/models.py:33
#: accounts/models.py:98 appsettings/models.py:9 computes/models.py:26
#: computes/models.py:52 instances/models.py:33
msgid "name"
msgstr "名称"
@ -2061,43 +2061,43 @@ msgstr "均衡"
msgid "%(compute)s is in maintenance: Balance leaves it out"
msgstr "%(compute)s 正在维护:均衡不包括它"
#: computes/models.py:19
#: computes/models.py:20
msgid ""
"A tag is letters a-z, digits, dots, dashes and underscores, and begins with a"
" letter or digit"
msgstr "标签由字母 a-z、数字、点、短横线和下划线组成,并以字母或数字开头"
#: computes/models.py:45
#: computes/models.py:53
msgid "hostname"
msgstr "主机名"
#: computes/models.py:46
#: computes/models.py:54
msgid "login"
msgstr "登录名"
#: computes/models.py:47
#: computes/models.py:55
msgid "password"
msgstr "密码"
#: computes/models.py:48
#: computes/models.py:56
msgid "details"
msgstr "详情"
#: computes/models.py:51
#: computes/models.py:59
msgid "migration address"
msgstr "迁移地址"
#: computes/models.py:57
#: computes/models.py:65
msgid ""
"IP address or host name the other hosts send migrating VMs to; empty: the "
"address the panel reaches the host at"
msgstr "其他主机向此主机迁移虚拟机时使用的 IP 地址或主机名;留空:使用面板连接该主机的地址"
#: computes/models.py:62 computes/templates/computes/form.html:38
#: computes/models.py:70 computes/templates/computes/form.html:38
msgid "gstfsd key"
msgstr "gstfsd 密钥"
#: computes/models.py:68
#: computes/models.py:76
msgid ""
"GSTFSD_KEY in the host's /etc/default/webvirt-gstfsd: the panel sets the root"
" password and SSH key of a shut-off VM with it; empty: they cannot be set "
@ -2106,40 +2106,40 @@ msgstr ""
"主机 /etc/default/webvirt-gstfsd 中的 GSTFSD_KEY:面板用它为已关机的虚拟机设置 root 密码和 SSH "
"密钥;留空:无法在此设置"
#: computes/models.py:82 instances/models.py:38
#: computes/models.py:90 instances/models.py:38
msgid "tags"
msgstr "标签"
#: computes/models.py:98 computes/templates/computes/instances.html:12
#: computes/models.py:106 computes/templates/computes/instances.html:12
#, python-format
msgid "%(compute)s is in maintenance: no new VM or migration comes to it"
msgstr "%(compute)s 正在维护:不会在其上创建新虚拟机,也不会迁移虚拟机到它"
#: computes/models.py:104
#: computes/models.py:112
#, python-format
msgid ""
"%(compute)s is in maintenance: its VMs cannot be started there; migrate the "
"VM to start it on another host"
msgstr "%(compute)s 正在维护:其虚拟机无法在其上启动;请将虚拟机迁移到其他主机后再启动"
#: computes/models.py:231
#: computes/models.py:239
#, python-format
msgid "This host is already added as %(name)s"
msgstr "此主机已作为 %(name)s 添加"
#: computes/models.py:234
#: computes/models.py:242
#, python-format
msgid ""
"The panel cannot reach the host to tell that its VMs are there: %(error)s"
msgstr "面板无法连接该主机,因此无法确认其虚拟机在那里:%(error)s"
#: computes/models.py:241
#: computes/models.py:249
msgid ""
"The host its VMs are on is not known yet: change the connection when the "
"panel has reached the host at its current one"
msgstr "其虚拟机所在的主机尚不明确:请在面板通过当前连接访问到该主机后再更改连接"
#: computes/models.py:244
#: computes/models.py:252
msgid "This is another host than the one its VMs are on: add it as a new host"
msgstr "这不是其虚拟机所在的主机:请将其添加为新主机"
@ -9099,10 +9099,19 @@ msgstr "请重新加载页面重试。如果问题持续出现,请将时间告
msgid "Delete <strong>%(object)s</strong>?"
msgstr "删除 <strong>%(object)s</strong>?"
#: templates/common/tag_badges.html:2
msgid "Show only this tag"
msgstr "只显示此标签"
#: templates/common/tag_filter.html:4
msgid "All tags"
msgstr "所有标签"
#: templates/common/tag_filter.html:5
#, python-format
msgid "No tag (%(untagged)s)"
msgstr "无标签(%(untagged)s)"
#: templates/error.html:13
msgid "HTTP status"
msgstr "HTTP 状态"

View file

@ -5,7 +5,8 @@
// pattern. A row with data-search is searched in that text only, not in its
// buttons and menus. With a state list, the row's [data-state] must
// be the chosen state too; with a tag list (#tag-filter), the chosen tag
// one of the row's data-tags (names split by spaces). In a grouped list a search for a group's host
// one of the row's data-tags (names split by spaces), or "-" none of them.
// A tag's badge ([data-tag-filter]) chooses it in the list. In a grouped list a search for a group's host
// shows all of its rows, and its header row (data-group-header) shows while
// any of its rows does. A page's #no-match shows while no row does. The
// search is remembered for a day, per page, unless its box has data-forget.
@ -42,8 +43,9 @@ function filterTable(doc) {
}
var mark = row.querySelector("[data-state]");
var searched = row.dataset.search !== undefined ? row.dataset.search : row.textContent;
var found = (hostMatches || fold(searched).includes(text))
&& (!tag || (row.dataset.tags || "").split(" ").indexOf(tag) >= 0);
var rowTags = row.dataset.tags || "";
var tagged = !tag || (tag === "-" ? rowTags === "" : rowTags.split(" ").indexOf(tag) >= 0);
var found = (hostMatches || fold(searched).includes(text)) && tagged;
row.hidden = !((!state || (mark && mark.dataset.state === state)) && found);
shown = shown || !row.hidden;
if (mark) {
@ -126,6 +128,14 @@ if (typeof module !== "undefined") {
keep(tags.value, key + "_tag");
filterTable(document);
});
document.addEventListener("click", function (event) {
var badge = event.target.closest("[data-tag-filter]");
if (badge) {
tags.value = badge.dataset.tagFilter;
keep(tags.value, key + "_tag");
filterTable(document);
}
});
}
var pills = document.getElementById("state-pills");
function chooseState(pill) {

View file

@ -1,2 +1,2 @@
{% load bootstrap_icons %}{# tags: a VM's or host's tags (or their names), as badges #}
{% for tag in tags %}<span class="badge text-bg-light border">{% bs_icon 'tag' %} {{ tag }}</span>{% endfor %}
{% load i18n %}{% load bootstrap_icons %}{# tags: a VM's or host's tags (or their names), as badges; with filter, each chooses its tag in the list's tag filter (table_filter.js) #}
{% for tag in tags %}{% if filter %}<button type="button" class="badge text-bg-light border" data-tag-filter="{{ tag }}" title="{% trans "Show only this tag" %}">{% bs_icon 'tag' %} {{ tag }}</button>{% else %}<span class="badge text-bg-light border">{% bs_icon 'tag' %} {{ tag }}</span>{% endif %}{% endfor %}

View file

@ -1,7 +1,8 @@
{% load i18n %}{# tags: the names of the listed rows' tags; table_filter.js shows the rows with the one chosen #}
{% if tags %}
{% load i18n %}{# tags: Tag.counts of the listed rows; table_filter.js shows the rows with the one chosen #}
{% with names=tags.0 untagged=tags.1 %}{% if names %}
<select id="tag-filter" class="form-select w-auto" aria-label="{% trans "Tag" %}">
<option value="">{% trans "All tags" %}</option>
{% for tag in tags %}<option value="{{ tag }}">{{ tag }}</option>{% endfor %}
{% if untagged %}<option value="-">{% blocktrans %}No tag ({{ untagged }}){% endblocktrans %}</option>{% endif %}
{% for name, count in names %}<option value="{{ name }}">{{ name }} ({{ count }})</option>{% endfor %}
</select>
{% endif %}
{% endif %}{% endwith %}