This commit is contained in:
timur 2026-09-29 00:59:47 +05:00
parent 4e1a99390f
commit 342fcef0e0
26 changed files with 610 additions and 91 deletions

View File

@ -15,19 +15,23 @@ Swagger доступен по `/api/v1/docs/`, OpenAPI-схема — по `/api
Статусы изменений являются фиксированными системными значениями и доступны
только для чтения через `/change-statuses/`:
| `code` | Название |
| `code` | `name` |
| --- | --- |
| `new` | Создан |
| `assessment` | На оценке |
| `assessment_completed` | Оценка предоставлена |
| `pending_approval` | На согласовании |
| `rejected` | Отклонен |
| `approved` | Авторизован / Запланирован |
| `in_progress` | В работе |
| `review` | Проверка |
| `review_completed` | Проверка проведена |
| `closed` | Закрыт |
| `cancelled` | Отменен |
| `new` | Created |
| `assessment` | Under assessment |
| `assessment_completed` | Assessment completed |
| `pending_approval` | Pending approval |
| `rejected` | Rejected |
| `approved` | Authorized / Scheduled |
| `pending` | Pending |
| `in_progress` | In progress |
| `review` | Review |
| `review_completed` | Review completed |
| `closed` | Closed |
| `cancelled` | Cancelled |
Поля `name` и `description` системных статусов содержат английские значения.
Локализованные подписи формируются клиентом по стабильному полю `code`.
Тип изменения содержит настройки этапов:
@ -159,6 +163,9 @@ POST /api/v1/main/chn/changes/45/reject/
- `positive_output` — единственный выход успешного завершения;
- `negative_output` — единственный выход неуспешного завершения.
Значения системных enum-полей передаются стабильными английскими кодами. Их
отображаемые и локализованные подписи формируются клиентом.
Для каждого типа изменения допускается не более одного системного блока каждого
вида. При создании нового типа изменения API автоматически создаёт все три
системных блока. Их идентификаторы возвращает запрос списка блоков:

View File

@ -64,6 +64,10 @@ Swagger доступен по `/api/v1/docs/`, исходная OpenAPI-схем
- `closed` — закрыто;
- `cancelled` — отменено.
Поля `name` и `description` системных статусов содержат английские значения.
Остальные системные enum-поля также передаются английскими кодами. Перевод для
отображения выполняется клиентом.
Исполнитель задачи или сотрудник назначенного подразделения может выполнить
переходы `new → in_progress`, `in_progress → pending`, `pending → in_progress`
и `in_progress → resolved`.

View File

@ -34,11 +34,11 @@ def _ensure_stage_task(change):
stage_config = {
ChangeStatus.Code.ASSESSMENT: (
Task.ChangeStage.ASSESSMENT, change.change_type.assessment_task_type,
"Провести оценку изменения",
"Assess the change",
),
ChangeStatus.Code.REVIEW: (
Task.ChangeStage.TESTING, change.change_type.testing_task_type,
"Провести проверку изменения",
"Review the change",
),
}
config = stage_config.get(change.status.code)

View File

@ -623,8 +623,9 @@ sys_field_data = [
{"id":320371,"name":"srv_type","sysname":"srv_type","type":"rel","sys_object_id":3203,"rel_object_id":3204,"searchtype":"","searchname":"","searchlist":"","searchlistname":""},
{"id":320372,"name":"srv_status","sysname":"srv_status","type":"rel","sys_object_id":3203,"rel_object_id":3201,"searchtype":"","searchname":"","searchlist":"","searchlistname":""},
{"id":320401,"name":"id","sysname":"id","type":"int","sys_object_id":3204,"rel_object_id":None,"searchtype":"int","searchname":"","searchlist":"","searchlistname":""},
{"id":320402,"name":"name","sysname":"name","type":"str","sys_object_id":3204,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
{"id":320403,"name":"description","sysname":"description","type":"str","sys_object_id":3204,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
{"id":320402,"name":"name","sysname":"name","type":"str","sys_object_id":3204,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
{"id":320403,"name":"description","sysname":"description","type":"str","sys_object_id":3204,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
{"id":320404,"name":"color","sysname":"color","type":"str","sys_object_id":3204,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
{"id":320501,"name":"id","sysname":"id","type":"int","sys_object_id":3205,"rel_object_id":None,"searchtype":"int","searchname":"","searchlist":"","searchlistname":""},
{"id":320502,"name":"name","sysname":"name","type":"str","sys_object_id":3205,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
{"id":320503,"name":"description","sysname":"description","type":"str","sys_object_id":3205,"rel_object_id":None,"searchtype":"str","searchname":"","searchlist":"","searchlistname":""},
@ -1726,7 +1727,8 @@ sys_field_search_data = [
{"sys_object_id":3201,"name":"isactive","val":"isactive","type":"bool"},
{"sys_object_id":3204,"name":"id","val":"id","type":"int"},
{"sys_object_id":3204,"name":"name","val":"name","type":"str"},
{"sys_object_id":3204,"name":"description","val":"description","type":"str"},
{"sys_object_id":3204,"name":"description","val":"description","type":"str"},
{"sys_object_id":3204,"name":"color","val":"color","type":"str"},
{"sys_object_id":3203,"name":"id","val":"id","type":"int"},
{"sys_object_id":3203,"name":"name","val":"name","type":"str"},
{"sys_object_id":3203,"name":"description","val":"description","type":"str"},

View File

@ -0,0 +1,143 @@
from django.db import migrations, models
CHANGE_STATUSES = {
"new": (
"Created",
"An RFC describing the change, risks, and plan has been registered.",
),
"assessment": (
"Under assessment",
"The impact and risks are being assessed and the change type is being selected.",
),
"assessment_completed": (
"Assessment completed",
"The change assessment has been provided.",
),
"pending_approval": (
"Pending approval",
"The change is being reviewed by the CAB or change owner.",
),
"rejected": (
"Rejected",
"The change has been rejected as impractical or unsafe.",
),
"approved": (
"Authorized / Scheduled",
"The change has been approved and its implementation window scheduled.",
),
"pending": (
"Pending",
"The change is waiting for child work to finish.",
),
"in_progress": ("In progress", "Implementation work is in progress."),
"review": ("Review", "A post-implementation review is in progress."),
"review_completed": (
"Review completed",
"The post-implementation review has been completed.",
),
"closed": (
"Closed",
"The change has been completed and its outcome recorded.",
),
"cancelled": (
"Cancelled",
"The change has been cancelled or rolled back.",
),
}
TASK_STATUSES = {
"new": (
"New",
"The task has been registered and work has not started.",
),
"in_progress": (
"In progress",
"The task has been assigned and is being worked on.",
),
"pending": ("Pending", "Work on the task has been temporarily suspended."),
"resolved": (
"Resolved",
"A solution has been found and is awaiting confirmation.",
),
"closed": (
"Closed",
"The result has been confirmed and the lifecycle is complete.",
),
"cancelled": ("Cancelled", "The task has been cancelled."),
}
def translate_fixed_statuses(apps, schema_editor):
ChangeStatus = apps.get_model("wanitil", "ChangeStatus")
TaskStatus = apps.get_model("wanitil", "TaskStatus")
Task = apps.get_model("wanitil", "Task")
WorkflowNode = apps.get_model("wanitil", "WorkflowNode")
for code, (name, description) in CHANGE_STATUSES.items():
ChangeStatus.objects.filter(code=code).update(
name=name, description=description,
)
for code, (name, description) in TASK_STATUSES.items():
TaskStatus.objects.filter(code=code).update(
name=name, description=description,
)
system_node_titles = {
"input": "Start",
"positive_output": "Completed",
"negative_output": "Not completed",
}
for kind, title in system_node_titles.items():
WorkflowNode.objects.filter(kind=kind).update(title=title)
Task.objects.filter(change_stage="assessment").update(title="Assess the change")
Task.objects.filter(change_stage="testing").update(title="Review the change")
class Migration(migrations.Migration):
dependencies = [("wanitil", "0093_sysemployee_avatar")]
operations = [
migrations.AlterField(
model_name="changestatus",
name="code",
field=models.CharField(
choices=[
("new", "Created"),
("assessment", "Under assessment"),
("assessment_completed", "Assessment completed"),
("pending_approval", "Pending approval"),
("rejected", "Rejected"),
("approved", "Authorized / Scheduled"),
("pending", "Pending"),
("in_progress", "In progress"),
("review", "Review"),
("review_completed", "Review completed"),
("closed", "Closed"),
("cancelled", "Cancelled"),
],
max_length=32,
unique=True,
),
),
migrations.AlterField(
model_name="taskstatus",
name="code",
field=models.CharField(
blank=True,
choices=[
("new", "New"),
("in_progress", "In progress"),
("pending", "Pending"),
("resolved", "Resolved"),
("closed", "Closed"),
("cancelled", "Cancelled"),
],
max_length=32,
null=True,
unique=True,
),
),
migrations.RunPython(translate_fixed_statuses, migrations.RunPython.noop),
]

View File

@ -0,0 +1,48 @@
from django.db import migrations, models
def add_color_catalog_entries(apps, schema_editor):
SysObject = apps.get_model("wanitil", "SysObject")
SysField = apps.get_model("wanitil", "SysField")
SysFieldSearch = apps.get_model("wanitil", "SysFieldSearch")
# System catalog metadata is optional and is not populated in every
# installation. The SrvType.color column itself does not depend on it.
if not SysObject.objects.filter(pk=3204).exists():
return
SysField.objects.update_or_create(
pk=320404,
defaults={
"name": "color",
"sysname": "color",
"type": "str",
"sys_object_id": 3204,
"rel_object_id": None,
"searchtype": "str",
"searchname": "",
"searchlist": "",
"searchlistname": "",
},
)
SysFieldSearch.objects.get_or_create(
sys_object_id=3204,
val="color",
defaults={"name": "color", "type": "str"},
)
class Migration(migrations.Migration):
dependencies = [("wanitil", "0094_english_fixed_statuses")]
operations = [
migrations.AddField(
model_name="srvtype",
name="color",
field=models.CharField(
blank=True,
default="",
help_text="Color used to highlight the service type",
max_length=7,
),
),
migrations.RunPython(add_color_catalog_entries, migrations.RunPython.noop),
]

View File

@ -0,0 +1,128 @@
import django.core.validators
import re
from django.db import migrations, models
COLOR_MODELS = (
'ChangeStatus', 'CrmClientCategory', 'CrmClientType', 'IncImpact',
'IncPriority', 'IncStatus', 'RepCollection', 'ReqCriticality', 'ReqStatus',
'SrvStatus', 'SrvType', 'SysTag', 'TaskPriority', 'TaskStatus',
)
COLOR_NAMES = {
'cyan': '#06B6D4',
'green': '#22C55E',
'blue': '#3B82F6',
'yellow': '#EAB308',
'red': '#EF4444',
'orange': '#F59E0B',
}
def normalize_color_fields(apps, schema_editor):
pattern = re.compile(r'^#[0-9A-Fa-f]{6}$')
for model_name in COLOR_MODELS:
model = apps.get_model('wanitil', model_name)
for item in model.objects.only('pk', 'color').iterator():
source = (item.color or '').strip()
normalized = COLOR_NAMES.get(source.lower(), source)
if pattern.fullmatch(normalized):
normalized = normalized.upper()
else:
normalized = ''
if normalized != item.color:
model.objects.filter(pk=item.pk).update(color=normalized)
employee_model = apps.get_model('wanitil', 'SysEmployee')
for employee in employee_model.objects.only('pk', 'theme_color').iterator():
source = (employee.theme_color or '').strip()
normalized = source.upper() if pattern.fullmatch(source) else '#2196F3'
if normalized != employee.theme_color:
employee_model.objects.filter(pk=employee.pk).update(
theme_color=normalized,
)
class Migration(migrations.Migration):
dependencies = [
('wanitil', '0095_srvtype_color'),
]
operations = [
migrations.RunPython(normalize_color_fields, migrations.RunPython.noop),
migrations.AlterField(
model_name='changestatus',
name='color',
field=models.CharField(blank=True, default='', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='crmclientcategory',
name='color',
field=models.CharField(blank=True, default='', help_text='Color used to highlight the CRM category', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='crmclienttype',
name='color',
field=models.CharField(blank=True, default='', help_text='Color used to highlight the CRM type', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='incimpact',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the incident impact', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='incpriority',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the incident priority', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='incstatus',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the incident status', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='repcollection',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the collection', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='reqcriticality',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the request criticality', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='reqstatus',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the request status', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='srvstatus',
name='color',
field=models.CharField(blank=True, default='', help_text='Color of the service status', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='srvtype',
name='color',
field=models.CharField(blank=True, default='', help_text='Color used to highlight the service type', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='sysemployee',
name='theme_color',
field=models.CharField(default='#2196F3', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='systag',
name='color',
field=models.CharField(blank=True, default='', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='taskpriority',
name='color',
field=models.CharField(blank=True, default='', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
migrations.AlterField(
model_name='taskstatus',
name='color',
field=models.CharField(blank=True, default='', max_length=7, validators=[django.core.validators.RegexValidator(message='Color must be in #RRGGBB format.', regex='^#[0-9A-Fa-f]{6}$')]),
),
]

View File

@ -2,6 +2,7 @@ from django.core.exceptions import ValidationError
from django.db import models
from .modelSys import SysDepartment, SysEmployee
from ..validators import HEX_COLOR_VALIDATOR
class ChnReferenceModel(models.Model):
@ -26,22 +27,26 @@ class TaskType(ChnReferenceModel):
class TaskStatus(ChnReferenceModel):
class Code(models.TextChoices):
NEW = "new", "Новое"
IN_PROGRESS = "in_progress", "В работе"
PENDING = "pending", "Ожидание"
RESOLVED = "resolved", "Решено"
CLOSED = "closed", "Закрыто"
CANCELLED = "cancelled", "Отменено"
NEW = "new", "New"
IN_PROGRESS = "in_progress", "In progress"
PENDING = "pending", "Pending"
RESOLVED = "resolved", "Resolved"
CLOSED = "closed", "Closed"
CANCELLED = "cancelled", "Cancelled"
code = models.CharField(
max_length=32, choices=Code.choices, unique=True, null=True, blank=True,
)
color = models.CharField(max_length=7, blank=True)
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
)
is_closed = models.BooleanField(default=False, db_index=True)
class TaskPriority(ChnReferenceModel):
color = models.CharField(max_length=7, blank=True)
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
)
weight = models.PositiveSmallIntegerField(default=0)
class Meta(ChnReferenceModel.Meta):
@ -62,21 +67,23 @@ class TaskCategory(ChnReferenceModel):
class ChangeStatus(ChnReferenceModel):
class Code(models.TextChoices):
NEW = "new", "Создан"
ASSESSMENT = "assessment", "На оценке"
ASSESSMENT_COMPLETED = "assessment_completed", "Оценка предоставлена"
PENDING_APPROVAL = "pending_approval", "На согласовании"
REJECTED = "rejected", "Отклонен"
APPROVED = "approved", "Авторизован / Запланирован"
PENDING = "pending", "Ожидание"
IN_PROGRESS = "in_progress", "В работе"
REVIEW = "review", "Проверка"
REVIEW_COMPLETED = "review_completed", "Проверка проведена"
CLOSED = "closed", "Закрыт"
CANCELLED = "cancelled", "Отменен"
NEW = "new", "Created"
ASSESSMENT = "assessment", "Under assessment"
ASSESSMENT_COMPLETED = "assessment_completed", "Assessment completed"
PENDING_APPROVAL = "pending_approval", "Pending approval"
REJECTED = "rejected", "Rejected"
APPROVED = "approved", "Authorized / Scheduled"
PENDING = "pending", "Pending"
IN_PROGRESS = "in_progress", "In progress"
REVIEW = "review", "Review"
REVIEW_COMPLETED = "review_completed", "Review completed"
CLOSED = "closed", "Closed"
CANCELLED = "cancelled", "Cancelled"
code = models.CharField(max_length=32, choices=Code.choices, unique=True)
color = models.CharField(max_length=7, blank=True)
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
)
class ChangeType(ChnReferenceModel):

View File

@ -2,6 +2,7 @@ from django.db import models
from django.contrib.auth.models import User
from .modelCon import ConPerson
from .modelSys import SysEmployee, SysProfileEmployee
from ..validators import HEX_COLOR_VALIDATOR
from .baseModel import BaseModel, BaseCreateDateModel, BaseCreateModel, BaseUpdateModel, BaseExtraModel, BaseExtraCreateDateModel, BaseExtraCreateModel, BaseExtraUpdateModel
@ -13,7 +14,7 @@ class CrmClientType(BaseModel):
name = models.CharField(max_length=64, blank=True, help_text="Name of the CRM type")
description = models.CharField(max_length=1024, blank=True, help_text="Description of the CRM type")
color = models.CharField(
max_length=60, blank=True, default="",
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color used to highlight the CRM type",
)
@ -23,7 +24,7 @@ class CrmClientCategory(BaseModel):
name = models.CharField(max_length=64, blank=True, help_text="Name of the CRM category")
description = models.CharField(max_length=1024, blank=True, help_text="Description of the CRM category")
color = models.CharField(
max_length=60, blank=True, default="",
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color used to highlight the CRM category",
)

View File

@ -4,7 +4,8 @@ from ..global_constants import MANAGMENT_DEV, MANAGMENT_CI, MANAGMENT_REQ, MANAG
from ..cast import safeCast
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.db import models
from django.db import models
from ..validators import HEX_COLOR_VALIDATOR
from django.contrib.auth.models import User
from .modelCon import ConContact, ConPerson
from .modelSys import SysProfileEmployee
@ -41,7 +42,10 @@ class IncStatus(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the incident status")
name = models.CharField(max_length=60, blank=True, help_text="Name of the incident status")
description = models.CharField(max_length=1000, blank=True, help_text="Description of the incident status")
color = models.CharField(max_length=60, blank=True, help_text="Color of the incident status")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the incident status",
)
class IncStatusTransit(BaseModel):
@ -58,14 +62,20 @@ class IncImpact(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the incident impact")
name = models.CharField(max_length=60, blank=True, help_text="Name of the incident impact")
description = models.CharField(max_length=1000, blank=True, help_text="Description of the incident impact")
color = models.CharField(max_length=60, blank=True, help_text="Color of the incident impact")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the incident impact",
)
class IncPriority(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the incident priority")
name = models.CharField(max_length=60, blank=True, help_text="Name of the incident priority")
description = models.CharField(max_length=1000, blank=True, help_text="Description of the incident priority")
color = models.CharField(max_length=60, blank=True, help_text="Color of the incident priority")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the incident priority",
)
class IncCategory(BaseModel):

View File

@ -3,6 +3,7 @@ from django.contrib.auth.models import User
from .baseModel import BaseModel, BaseCreateDateModel, BaseCreateModel, BaseUpdateModel, BaseExtraModel, BaseExtraCreateDateModel, BaseExtraCreateModel, BaseExtraUpdateModel
from .modelSys import SysObject, SysField
from ..validators import HEX_COLOR_VALIDATOR
class RepCollection(BaseModel):
@ -11,7 +12,10 @@ class RepCollection(BaseModel):
sys_object = models.ForeignKey(
SysObject, null=True, related_name='rep_collection', on_delete=models.SET_NULL, help_text="System object associated with the collection")
is_active = models.BooleanField(default=True, help_text="Indicates if the collection is active")
color = models.CharField(max_length=60, blank=True, help_text="Color of the collection")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the collection",
)
# sys_field = models.ForeignKey(

View File

@ -9,7 +9,8 @@ from django.db import models
from django.contrib.auth.models import User
from .modelCon import ConContact, ConPerson
from .modelSys import SysProfileEmployee
from django.forms.models import model_to_dict
from django.forms.models import model_to_dict
from ..validators import HEX_COLOR_VALIDATOR
from simple_history.models import HistoricalRecords
@ -37,7 +38,10 @@ class ReqStatus(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the request status")
name = models.CharField(max_length=60, blank=True, help_text="Name of the request status")
description = models.CharField(max_length=1000, blank=True, help_text="Description of the request status")
color = models.CharField(max_length=60, blank=True, help_text="Color of the request status")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the request status",
)
class ReqStatusTransit(BaseModel):
@ -54,7 +58,10 @@ class ReqCriticality(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the request criticality")
name = models.CharField(max_length=60, blank=True, help_text="Name of the request criticality")
description = models.CharField(max_length=1000, blank=True, help_text="Description of the request criticality")
color = models.CharField(max_length=60, blank=True, help_text="Color of the request criticality")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the request criticality",
)
class ReqRequest(BaseExtraUpdateModel):

View File

@ -1,21 +1,29 @@
from django.db import models
from django.contrib.auth.models import User
from ..cast import safeCast
from ..cast import safeCast
from ..validators import HEX_COLOR_VALIDATOR
from .baseModel import BaseModel, BaseCreateDateModel, BaseCreateModel, BaseUpdateModel, BaseExtraModel, BaseExtraCreateDateModel, BaseExtraCreateModel, BaseExtraUpdateModel
class SrvType(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the service type")
name = models.CharField(max_length=64, blank=True, help_text="Name of the service type")
description = models.CharField(max_length=1024, blank=True, help_text="Description of the service type")
class SrvType(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the service type")
name = models.CharField(max_length=64, blank=True, help_text="Name of the service type")
description = models.CharField(max_length=1024, blank=True, help_text="Description of the service type")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color used to highlight the service type",
)
class SrvStatus(BaseModel):
id = models.BigAutoField(primary_key=True, help_text="Unique identifier of the service status")
name = models.CharField(max_length=60, blank=True, help_text="Name of the service status")
description = models.CharField(max_length=1000, blank=True, help_text="Description of the service status")
color = models.CharField(max_length=60, blank=True, help_text="Color of the service status")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
help_text="Color of the service status",
)
isactive = models.BooleanField(default=False, help_text="Indicates if the status is active")

View File

@ -2,7 +2,7 @@ from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.validators import RegexValidator
from ..validators import HEX_COLOR_VALIDATOR
from ..cast import safeCast
@ -180,10 +180,7 @@ class SysEmployee(models.Model):
theme_color = models.CharField(
max_length=7,
default="#2196F3",
validators=[RegexValidator(
regex=r"^#[0-9A-Fa-f]{6}$",
message="Theme color must be in #RRGGBB format.",
)],
validators=[HEX_COLOR_VALIDATOR],
)
timezone = models.IntegerField(default=0)
is_active = models.BooleanField(default=True, db_index=True)
@ -295,7 +292,9 @@ class SysTag(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=128, unique=True)
description = models.CharField(max_length=1024, blank=True)
color = models.CharField(max_length=16, blank=True, default="")
color = models.CharField(
max_length=7, blank=True, default="", validators=[HEX_COLOR_VALIDATOR],
)
created_by = models.ForeignKey(
User, null=True, related_name="created_sys_tags", on_delete=models.SET_NULL,
)

View File

@ -13,10 +13,12 @@ from ..models.modelCon import ConPerson
from ..models.modelAdr import AdrHouse
from ..funcs.funcAdr import AdrHouseGetGeo
from .baseSerializerSys import SysEmployeeNestedBaseSerializer
from .fields import HexColorField
class CrmClientTypeBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
class CrmClientTypeBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
color = HexColorField(allow_blank=True, required=False, default="")
info = serializers.SerializerMethodField()
def get_info(self, obj) -> str:
@ -37,8 +39,9 @@ class CrmClientTypeNestedBaseSerializer(serializers.HyperlinkedModelSerializer):
fields = ('id', 'name', 'description', 'color')
class CrmClientCategoryBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
class CrmClientCategoryBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
color = HexColorField(allow_blank=True, required=False, default="")
info = serializers.SerializerMethodField()
def get_info(self, obj) -> str:

View File

@ -11,7 +11,8 @@ from django.db import models
from .baseSerializerSys import SysObjectBaseSerializer
from ..models.modelSys import SysObject, SysField
from ..models.modelRep import RepCollection, RepCollectionData, RepCollectionField, RepChartOnline
from ..models.modelRep import RepCollection, RepCollectionData, RepCollectionField, RepChartOnline
from .fields import HexColorField
class SysObjectReadBaseSerializer(serializers.HyperlinkedModelSerializer):
@ -185,9 +186,10 @@ class RepCollectionDataBaseSerializer(serializers.HyperlinkedModelSerializer):
return instance
class RepCollectionBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(allow_blank=False)
class RepCollectionBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(allow_blank=False)
color = HexColorField(allow_blank=True, required=False, default="")
sys_object = RepSysObjectNestedBaseSerializer(many=False)
is_active = serializers.BooleanField()
rep_collection_field = RepCollectionFieldReadBaseSerializer(
@ -199,9 +201,9 @@ class RepCollectionBaseSerializer(serializers.HyperlinkedModelSerializer):
return obj.name
class Meta:
model = RepCollection
fields = ('id', 'name', 'sys_object', 'color',
'is_active', 'rep_collection_field')
model = RepCollection
fields = ('id', 'name', 'sys_object', 'color',
'is_active', 'rep_collection_field', 'info')
def create(self, validated_data):
el_obj = None

View File

@ -14,22 +14,24 @@ from ..models.modelSrv import SrvType, SrvService, SrvRequest, SrvSolution, SrvS
from .fields import HexColorField
class SrvTypeBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
info = serializers.SerializerMethodField()
class SrvTypeBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)
color = HexColorField(allow_blank=True, required=False, default="")
info = serializers.SerializerMethodField()
def get_info(self, obj) -> str:
return obj.name
class Meta:
model = SrvType
fields = ('id', 'name', 'description', 'info')
fields = ('id', 'name', 'description', 'color', 'info')
class SrvTypeNestedBaseSerializer(serializers.HyperlinkedModelSerializer):
class SrvTypeNestedBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField()
name = serializers.CharField(read_only=True)
description = serializers.CharField(read_only=True)
description = serializers.CharField(read_only=True)
color = serializers.CharField(read_only=True)
info = serializers.SerializerMethodField()
def get_info(self, obj) -> str:
@ -37,7 +39,7 @@ class SrvTypeNestedBaseSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = SrvType
fields = ('id', 'name', 'description', 'info')
fields = ('id', 'name', 'description', 'color', 'info')
class SrvStatusReadBaseSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(read_only=True)

View File

@ -1,9 +1,10 @@
import re
from rest_framework import serializers
from wanitil.validators import HEX_COLOR_PATTERN
HEX_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
HEX_COLOR_RE = re.compile(HEX_COLOR_PATTERN)
class HexColorField(serializers.CharField):

View File

@ -3,6 +3,7 @@ from django.contrib.auth.models import User
from rest_framework import serializers
from .serializerSys import SysUserSerializer
from .fields import HexColorField
class ErrorResponseSerializer(serializers.Serializer):
@ -88,12 +89,7 @@ class SelfChangePasswordRequestSerializer(ChangePasswordRequestSerializer):
class UpdateProfileRequestSerializer(serializers.Serializer):
lang = serializers.CharField(required=False, max_length=8)
theme_is_light = serializers.BooleanField(required=False)
theme_color = serializers.RegexField(
r"^#[0-9A-Fa-f]{6}$", required=False, max_length=7,
error_messages={
"invalid": "Theme color must be in #RRGGBB format.",
},
)
theme_color = HexColorField(required=False)
timezone = serializers.IntegerField(required=False)

View File

@ -7,6 +7,7 @@ from ..models.modelChn import (
WorkflowNode, WorkflowRun,
)
from ..models.modelSys import SysEmployee
from .fields import HexColorField
class ChnReferenceSerializer(serializers.ModelSerializer):
@ -22,6 +23,8 @@ class TaskTypeSerializer(ChnReferenceSerializer):
class TaskStatusSerializer(ChnReferenceSerializer):
color = HexColorField(read_only=True)
class Meta(ChnReferenceSerializer.Meta):
model = TaskStatus
fields = ChnReferenceSerializer.Meta.fields + ("code", "color", "is_closed")
@ -29,6 +32,8 @@ class TaskStatusSerializer(ChnReferenceSerializer):
class TaskPrioritySerializer(ChnReferenceSerializer):
color = HexColorField(allow_blank=True, required=False, default="")
class Meta(ChnReferenceSerializer.Meta):
model = TaskPriority
fields = ChnReferenceSerializer.Meta.fields + ("color", "weight")
@ -46,6 +51,8 @@ class TaskCategorySerializer(ChnReferenceSerializer):
class ChangeStatusSerializer(ChnReferenceSerializer):
color = HexColorField(read_only=True)
class Meta(ChnReferenceSerializer.Meta):
model = ChangeStatus
fields = ChnReferenceSerializer.Meta.fields + ("code", "color")
@ -110,15 +117,15 @@ class ChangeTypeSerializer(ChnReferenceSerializer):
WorkflowNode.objects.bulk_create([
WorkflowNode(
change_type=change_type, kind=WorkflowNode.Kind.INPUT,
title="Начало", x=0, y=0,
title="Start", x=0, y=0,
),
WorkflowNode(
change_type=change_type, kind=WorkflowNode.Kind.POSITIVE_OUTPUT,
title="Выполнено", x=600, y=0,
title="Completed", x=600, y=0,
),
WorkflowNode(
change_type=change_type, kind=WorkflowNode.Kind.NEGATIVE_OUTPUT,
title="Не выполнено", x=600, y=160,
title="Not completed", x=600, y=160,
),
])
return change_type

View File

@ -2,6 +2,7 @@ from rest_framework import serializers
from wanitil.domains.dsk.services import public_target_label
from wanitil.models.modelSys import SysTag, SysTagAssignment
from .fields import HexColorField
class SysTagAssignmentSerializer(serializers.ModelSerializer):
@ -18,6 +19,7 @@ class SysTagAssignmentSerializer(serializers.ModelSerializer):
class SysTagSerializer(serializers.ModelSerializer):
assignments_count = serializers.IntegerField(read_only=True, default=0)
color = HexColorField(allow_blank=True, required=False, default="")
class Meta:
model = SysTag

View File

@ -719,8 +719,9 @@ VALUES
--(3204,'srvtype','srvtype',3200,'SRTYP',''),
(320401,'id','id','int',3204,null,'int','','',''),
(320402,'name','name','str',3204,null,'str','','',''),
(320403,'description','description','str',3204,null,'str','','',''),
(320402,'name','name','str',3204,null,'str','','',''),
(320403,'description','description','str',3204,null,'str','','',''),
(320404,'color','color','str',3204,null,'str','','',''),
--(3205,'srvrequest','srvrequest',3200,'SRREQ',''),
@ -2035,7 +2036,8 @@ INSERT INTO wanitil_sysfieldsearch (sys_object_id, name,val,type) VALUES
--SrvType
(3204,'id','id','int'),
(3204,'name','name','str'),
(3204,'description','description','str'),
(3204,'description','description','str'),
(3204,'color','color','str'),
--SrvService
(3203,'id','id','int'),
(3203,'name','name','str'),

View File

@ -0,0 +1,29 @@
from importlib import import_module
from django.test import SimpleTestCase
from wanitil.models.modelChn import ChangeStatus, TaskStatus
from wanitil.serializers.serializerChn import (
ChangeStatusSerializer, TaskStatusSerializer,
)
class ChnFixedStatusTests(SimpleTestCase):
def test_all_choice_labels_are_english(self):
self.assertEqual(ChangeStatus.Code.NEW.label, "Created")
self.assertEqual(ChangeStatus.Code.PENDING_APPROVAL.label, "Pending approval")
self.assertEqual(TaskStatus.Code.NEW.label, "New")
self.assertEqual(TaskStatus.Code.IN_PROGRESS.label, "In progress")
def test_migration_covers_every_fixed_status(self):
migration = import_module("wanitil.migrations.0094_english_fixed_statuses")
self.assertEqual(
set(ChangeStatus.Code.values), set(migration.CHANGE_STATUSES),
)
self.assertEqual(set(TaskStatus.Code.values), set(migration.TASK_STATUSES))
def test_status_api_has_no_server_side_translation_fields(self):
self.assertNotIn("name_en", ChangeStatusSerializer.Meta.fields)
self.assertNotIn("name_ru", ChangeStatusSerializer.Meta.fields)
self.assertNotIn("name_en", TaskStatusSerializer.Meta.fields)
self.assertNotIn("name_ru", TaskStatusSerializer.Meta.fields)

View File

@ -0,0 +1,62 @@
from django.test import SimpleTestCase
from wanitil.models.modelChn import ChangeStatus, TaskPriority, TaskStatus
from wanitil.models.modelCrm import CrmClientCategory, CrmClientType
from wanitil.models.modelInc import IncImpact, IncPriority, IncStatus
from wanitil.models.modelRep import RepCollection
from wanitil.models.modelReq import ReqCriticality, ReqStatus
from wanitil.models.modelSrv import SrvStatus, SrvType
from wanitil.models.modelSys import SysEmployee, SysTag
from wanitil.serializers.baseSerializerCrm import (
CrmClientCategoryBaseSerializer, CrmClientTypeBaseSerializer,
)
from wanitil.serializers.baseSerializerInc import (
IncImpactBaseSerializer, IncPriorityBaseSerializer, IncStatusBaseSerializer,
)
from wanitil.serializers.baseSerializerRep import RepCollectionBaseSerializer
from wanitil.serializers.baseSerializerReq import (
ReqCriticalityBaseSerializer, ReqStatusBaseSerializer,
)
from wanitil.serializers.baseSerializerSrv import (
SrvStatusBaseSerializer, SrvTypeBaseSerializer,
)
from wanitil.serializers.fields import HexColorField
from wanitil.serializers.serializerApi import UpdateProfileRequestSerializer
from wanitil.serializers.serializerChn import TaskPrioritySerializer
from wanitil.serializers.serializerTag import SysTagSerializer
class ColorFieldConsistencyTests(SimpleTestCase):
optional_color_models = (
ChangeStatus, CrmClientCategory, CrmClientType, IncImpact, IncPriority,
IncStatus, RepCollection, ReqCriticality, ReqStatus, SrvStatus, SrvType,
SysTag, TaskPriority, TaskStatus,
)
writable_serializers = (
CrmClientCategoryBaseSerializer, CrmClientTypeBaseSerializer,
IncImpactBaseSerializer, IncPriorityBaseSerializer,
IncStatusBaseSerializer, RepCollectionBaseSerializer,
ReqCriticalityBaseSerializer, ReqStatusBaseSerializer,
SrvStatusBaseSerializer, SrvTypeBaseSerializer, SysTagSerializer,
TaskPrioritySerializer,
)
def test_optional_model_colors_have_the_same_shape(self):
for model in self.optional_color_models:
field = model._meta.get_field("color")
self.assertEqual(field.max_length, 7, model.__name__)
self.assertTrue(field.blank, model.__name__)
self.assertEqual(field.default, "", model.__name__)
self.assertTrue(field.validators, model.__name__)
def test_writable_api_colors_use_the_shared_field(self):
for serializer_class in self.writable_serializers:
field = serializer_class().fields["color"]
self.assertIsInstance(field, HexColorField, serializer_class.__name__)
def test_profile_color_uses_the_shared_field(self):
field = UpdateProfileRequestSerializer().fields["theme_color"]
self.assertIsInstance(field, HexColorField)
model_field = SysEmployee._meta.get_field("theme_color")
self.assertEqual(model_field.max_length, 7)
self.assertEqual(model_field.default, "#2196F3")

View File

@ -0,0 +1,37 @@
from django.test import SimpleTestCase
from wanitil.models.modelSrv import SrvType
from wanitil.serializers.baseSerializerSrv import (
SrvTypeBaseSerializer, SrvTypeNestedBaseSerializer,
)
class SrvTypeColorTests(SimpleTestCase):
def test_color_is_normalized(self):
serializer = SrvTypeBaseSerializer(data={
"name": "Internet",
"description": "Internet access",
"color": "#1a2b3c",
})
self.assertTrue(serializer.is_valid(), serializer.errors)
self.assertEqual(serializer.validated_data["color"], "#1A2B3C")
def test_invalid_color_is_rejected(self):
serializer = SrvTypeBaseSerializer(data={
"name": "Internet",
"color": "red",
})
self.assertFalse(serializer.is_valid())
self.assertIn("color", serializer.errors)
def test_color_is_returned_by_full_and_nested_serializers(self):
srv_type = SrvType(
id=1, name="Internet", description="Internet access", color="#123ABC",
)
self.assertEqual(SrvTypeBaseSerializer(srv_type).data["color"], "#123ABC")
self.assertEqual(
SrvTypeNestedBaseSerializer(srv_type).data["color"], "#123ABC",
)

8
wanitil/validators.py Normal file
View File

@ -0,0 +1,8 @@
from django.core.validators import RegexValidator
HEX_COLOR_PATTERN = r"^#[0-9A-Fa-f]{6}$"
HEX_COLOR_VALIDATOR = RegexValidator(
regex=HEX_COLOR_PATTERN,
message="Color must be in #RRGGBB format.",
)