Merge pull request 'Add per-product date fields flag' (#35) from cursor/product-requires-dates into main

This commit was merged in pull request #35.
This commit is contained in:
2026-10-14 08:36:59 +00:00
14 changed files with 145 additions and 27 deletions

View File

@@ -4,7 +4,8 @@ from .models import Product, Order
@admin.register(Product) @admin.register(Product)
class ProductAdmin(admin.ModelAdmin): class ProductAdmin(admin.ModelAdmin):
list_display = ['code', 'description', 'default_net_weight', 'created_at'] list_display = ['code', 'description', 'default_net_weight', 'requires_dates', 'created_at']
list_editable = ['requires_dates']
search_fields = ['code', 'description'] search_fields = ['code', 'description']

View File

@@ -41,6 +41,7 @@ def restore_products(request, payload: List[ProductIn]):
defaults={ defaults={
'description': item.description, 'description': item.description,
'default_net_weight': item.default_net_weight, 'default_net_weight': item.default_net_weight,
'requires_dates': item.requires_dates,
}, },
) )
if was_created: if was_created:
@@ -81,14 +82,22 @@ def list_orders(request, status: Optional[str] = Query(None)):
return qs return qs
@api.post('/orders', response={201: OrderOut}, tags=['Orders']) @api.post('/orders', response={201: OrderOut, 400: dict}, tags=['Orders'])
def create_order(request, payload: OrderIn): def create_order(request, payload: OrderIn):
product = get_object_or_404(Product, id=payload.product_id) product = get_object_or_404(Product, id=payload.product_id)
if product.requires_dates:
if not payload.production_date or not payload.next_control_date:
return 400, {'detail': 'production_date and next_control_date are required'}
production_date = payload.production_date
next_control_date = payload.next_control_date
else:
production_date = None
next_control_date = None
order = Order( order = Order(
product=product, product=product,
batch_number=payload.batch_number, batch_number=payload.batch_number,
production_date=payload.production_date, production_date=production_date,
next_control_date=payload.next_control_date, next_control_date=next_control_date,
total_weight=payload.total_weight, total_weight=payload.total_weight,
canister_weight=payload.canister_weight, canister_weight=payload.canister_weight,
canisters_per_box=payload.canisters_per_box, canisters_per_box=payload.canisters_per_box,

View File

@@ -0,0 +1,39 @@
# Generated by Django 5.2.17 on 2026-10-14 08:25
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('slips', '0002_remove_order_net_weight_remove_order_pages_needed_and_more'),
]
operations = [
migrations.AddField(
model_name='product',
name='requires_dates',
field=models.BooleanField(default=True),
),
migrations.AlterField(
model_name='order',
name='box_count',
field=models.PositiveIntegerField(default=0),
),
migrations.AlterField(
model_name='order',
name='canister_count',
field=models.PositiveIntegerField(default=0),
),
migrations.AlterField(
model_name='order',
name='next_control_date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='order',
name='production_date',
field=models.DateField(blank=True, default=django.utils.timezone.now, null=True),
),
]

View File

@@ -7,6 +7,7 @@ class Product(models.Model):
code = models.CharField(max_length=50, unique=True) code = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=200) description = models.CharField(max_length=200)
default_net_weight = models.FloatField(default=5.0) default_net_weight = models.FloatField(default=5.0)
requires_dates = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
class Meta: class Meta:
@@ -26,8 +27,8 @@ class Order(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='orders') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='orders')
batch_number = models.CharField(max_length=50) batch_number = models.CharField(max_length=50)
production_date = models.DateField(default=timezone.now) production_date = models.DateField(default=timezone.now, null=True, blank=True)
next_control_date = models.DateField() next_control_date = models.DateField(null=True, blank=True)
total_weight = models.FloatField(default=0) total_weight = models.FloatField(default=0)
canister_weight = models.FloatField(default=5) canister_weight = models.FloatField(default=5)
canisters_per_box = models.PositiveIntegerField(default=4) canisters_per_box = models.PositiveIntegerField(default=4)

View File

@@ -8,19 +8,21 @@ class ProductOut(Schema):
code: str code: str
description: str description: str
default_net_weight: float default_net_weight: float
requires_dates: bool
class ProductIn(Schema): class ProductIn(Schema):
code: str code: str
description: str description: str
default_net_weight: float = 5.0 default_net_weight: float = 5.0
requires_dates: bool = True
class OrderIn(Schema): class OrderIn(Schema):
product_id: int product_id: int
batch_number: str batch_number: str
production_date: date production_date: Optional[date] = None
next_control_date: date next_control_date: Optional[date] = None
total_weight: float total_weight: float
canister_weight: float canister_weight: float
canisters_per_box: int canisters_per_box: int
@@ -32,8 +34,8 @@ class OrderOut(Schema):
product_code: str product_code: str
product_description: str product_description: str
batch_number: str batch_number: str
production_date: date production_date: Optional[date] = None
next_control_date: date next_control_date: Optional[date] = None
total_weight: float total_weight: float
canister_weight: float canister_weight: float
canisters_per_box: int canisters_per_box: int

View File

@@ -351,6 +351,19 @@ form {
min-width: 0; min-width: 0;
} }
.checkbox-label {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
}
.checkbox-label input[type="checkbox"] {
width: auto;
min-width: 0;
padding: 0;
}
label { label {
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 500; font-weight: 500;

View File

@@ -1,5 +1,6 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const productSelect = document.getElementById('product'); const productSelect = document.getElementById('product');
const dateFields = document.getElementById('date-fields');
const dateInput = document.getElementById('prod-date'); const dateInput = document.getElementById('prod-date');
const nextControlInput = document.getElementById('next-control'); const nextControlInput = document.getElementById('next-control');
const totalWeightInput = document.getElementById('total-weight'); const totalWeightInput = document.getElementById('total-weight');
@@ -26,6 +27,24 @@ document.addEventListener('DOMContentLoaded', () => {
const day = String(d.getDate()).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0');
return `${d.getFullYear()}-${m}-${day}`; return `${d.getFullYear()}-${m}-${day}`;
} }
function productRequiresDates() {
const opt = productSelect.options[productSelect.selectedIndex];
if (!opt || !opt.value) return true;
return opt.dataset.requiresDates !== 'false';
}
function syncDateFields() {
const needed = productRequiresDates();
dateFields.style.display = needed ? '' : 'none';
dateInput.required = needed;
nextControlInput.required = needed;
if (needed && !dateInput.value) {
dateInput.value = localDmy(new Date());
updateNextControl();
}
}
dateInput.value = localDmy(new Date()); dateInput.value = localDmy(new Date());
// Auto calculate +6 months // Auto calculate +6 months
@@ -61,31 +80,40 @@ document.addEventListener('DOMContentLoaded', () => {
canistersPerBoxInput.addEventListener('input', updatePreview); canistersPerBoxInput.addEventListener('input', updatePreview);
updatePreview(); updatePreview();
// Auto weight from product selection // Auto weight + date visibility from product selection
productSelect.addEventListener('change', (e) => { productSelect.addEventListener('change', (e) => {
const opt = e.target.options[e.target.selectedIndex]; const opt = e.target.options[e.target.selectedIndex];
if (opt && opt.dataset.weight) { if (opt && opt.dataset.weight) {
canisterWeightInput.value = opt.dataset.weight; canisterWeightInput.value = opt.dataset.weight;
updatePreview(); updatePreview();
} }
syncDateFields();
}); });
syncDateFields();
// Submit new order // Submit new order
form.addEventListener('submit', async (e) => { form.addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
const prodDate = parseDmy(dateInput.value); const needsDates = productRequiresDates();
const nextDate = parseDmy(nextControlInput.value); let production_date = null;
if (!prodDate || !nextDate) { let next_control_date = null;
showToast(currentLang === 'fa' ? 'تاریخ را به صورت روز/ماه/سال وارد کنید' : 'Use date format dd/mm/yyyy', true); if (needsDates) {
return; const prodDate = parseDmy(dateInput.value);
const nextDate = parseDmy(nextControlInput.value);
if (!prodDate || !nextDate) {
showToast(currentLang === 'fa' ? 'تاریخ را به صورت روز/ماه/سال وارد کنید' : 'Use date format dd/mm/yyyy', true);
return;
}
production_date = toYmd(prodDate);
next_control_date = toYmd(nextDate);
} }
const payload = { const payload = {
product_id: parseInt(productSelect.value), product_id: parseInt(productSelect.value),
batch_number: document.getElementById('batch').value, batch_number: document.getElementById('batch').value,
production_date: toYmd(prodDate), production_date,
next_control_date: toYmd(nextDate), next_control_date,
total_weight: parseFloat(totalWeightInput.value), total_weight: parseFloat(totalWeightInput.value),
canister_weight: parseFloat(canisterWeightInput.value), canister_weight: parseFloat(canisterWeightInput.value),
canisters_per_box: parseInt(canistersPerBoxInput.value) canisters_per_box: parseInt(canistersPerBoxInput.value)
@@ -103,6 +131,7 @@ document.addEventListener('DOMContentLoaded', () => {
form.reset(); form.reset();
dateInput.value = localDmy(new Date()); dateInput.value = localDmy(new Date());
updateNextControl(); updateNextControl();
syncDateFields();
updatePreview(); updatePreview();
setTimeout(() => window.location.reload(), 1000); setTimeout(() => window.location.reload(), 1000);
} else { } else {

View File

@@ -16,6 +16,8 @@ const translations = {
'product_code': 'Product Code', 'product_code': 'Product Code',
'description': 'Description', 'description': 'Description',
'default_weight': 'Default Weight', 'default_weight': 'Default Weight',
'requires_dates': 'Requires Date / Next Control',
'requires_dates_short': 'Dates',
'save': 'Save', 'save': 'Save',
'cancel': 'Cancel', 'cancel': 'Cancel',
'batch_number': 'Batch #', 'batch_number': 'Batch #',
@@ -65,6 +67,8 @@ const translations = {
'product_code': 'کد محصول', 'product_code': 'کد محصول',
'description': 'شرح', 'description': 'شرح',
'default_weight': 'وزن پیش‌فرض', 'default_weight': 'وزن پیش‌فرض',
'requires_dates': 'نیاز به تاریخ / کنترل بعدی',
'requires_dates_short': 'تاریخ',
'save': 'ذخیره', 'save': 'ذخیره',
'cancel': 'لغو', 'cancel': 'لغو',
'batch_number': 'شماره بچ', 'batch_number': 'شماره بچ',

View File

@@ -7,6 +7,7 @@ document.addEventListener('DOMContentLoaded', () => {
code: document.getElementById('prod-code').value.trim(), code: document.getElementById('prod-code').value.trim(),
description: document.getElementById('prod-desc').value.trim(), description: document.getElementById('prod-desc').value.trim(),
default_net_weight: parseFloat(document.getElementById('prod-weight').value), default_net_weight: parseFloat(document.getElementById('prod-weight').value),
requires_dates: document.getElementById('prod-requires-dates').checked,
}; };
if (!payload.code || !payload.description) { if (!payload.code || !payload.description) {
showToast(currentLang === 'fa' ? 'کد و شرح لازم است' : 'Code and Description are required', true); showToast(currentLang === 'fa' ? 'کد و شرح لازم است' : 'Code and Description are required', true);
@@ -51,6 +52,7 @@ function editProduct(btn) {
document.getElementById('prod-code').value = btn.dataset.code; document.getElementById('prod-code').value = btn.dataset.code;
document.getElementById('prod-desc').value = btn.dataset.desc; document.getElementById('prod-desc').value = btn.dataset.desc;
document.getElementById('prod-weight').value = btn.dataset.weight; document.getElementById('prod-weight').value = btn.dataset.weight;
document.getElementById('prod-requires-dates').checked = btn.dataset.requiresDates !== 'false';
setFormMode(true); setFormMode(true);
document.getElementById('prod-code').focus(); document.getElementById('prod-code').focus();
} }
@@ -59,6 +61,7 @@ function cancelEdit() {
document.getElementById('edit-id').value = ''; document.getElementById('edit-id').value = '';
document.getElementById('product-form').reset(); document.getElementById('product-form').reset();
document.getElementById('prod-weight').value = 5; document.getElementById('prod-weight').value = 5;
document.getElementById('prod-requires-dates').checked = true;
setFormMode(false); setFormMode(false);
} }
@@ -94,6 +97,7 @@ async function backupProducts() {
code: p.code, code: p.code,
description: p.description, description: p.description,
default_net_weight: p.default_net_weight, default_net_weight: p.default_net_weight,
requires_dates: p.requires_dates !== false,
})); }));
const blob = new Blob([JSON.stringify(payload, null, 2) + '\n'], { type: 'application/json' }); const blob = new Blob([JSON.stringify(payload, null, 2) + '\n'], { type: 'application/json' });
const a = document.createElement('a'); const a = document.createElement('a');
@@ -122,7 +126,8 @@ function parseProductsBackup(raw) {
const description = String(item.description || '').trim(); const description = String(item.description || '').trim();
const weight = Number(item.default_net_weight); const weight = Number(item.default_net_weight);
if (!code || !description || !Number.isFinite(weight)) throw new Error('invalid product: ' + code); if (!code || !description || !Number.isFinite(weight)) throw new Error('invalid product: ' + code);
return { code, description, default_net_weight: weight }; const requires_dates = item.requires_dates !== false;
return { code, description, default_net_weight: weight, requires_dates };
}); });
} }

View File

@@ -18,7 +18,7 @@
<select id="product" required> <select id="product" required>
<option value="">— Select —</option> <option value="">— Select —</option>
{% for p in products %} {% for p in products %}
<option value="{{ p.id }}" data-weight="{{ p.default_net_weight }}"> <option value="{{ p.id }}" data-weight="{{ p.default_net_weight }}" data-requires-dates="{{ p.requires_dates|yesno:'true,false' }}">
{{ p.code }} — {{ p.description }} {{ p.code }} — {{ p.description }}
</option> </option>
{% endfor %} {% endfor %}
@@ -30,14 +30,14 @@
<input type="text" id="batch" required placeholder="1028/26"> <input type="text" id="batch" required placeholder="1028/26">
</div> </div>
<div class="form-row"> <div class="form-row" id="date-fields">
<div class="form-group"> <div class="form-group">
<label for="prod-date" data-i18n="date">Date</label> <label for="prod-date" data-i18n="date">Date</label>
<input type="text" id="prod-date" required placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}" inputmode="numeric" autocomplete="off"> <input type="text" id="prod-date" placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}" inputmode="numeric" autocomplete="off">
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="next-control" data-i18n="next_control">Next Control Date</label> <label for="next-control" data-i18n="next_control">Next Control Date</label>
<input type="text" id="next-control" required placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}" inputmode="numeric" autocomplete="off"> <input type="text" id="next-control" placeholder="dd/mm/yyyy" pattern="\d{2}/\d{2}/\d{4}" inputmode="numeric" autocomplete="off">
</div> </div>
</div> </div>

View File

@@ -30,6 +30,7 @@
<span class="label" data-i18n="batch_number">Batch:</span> <span class="label" data-i18n="batch_number">Batch:</span>
<span class="value mono">{{ o.batch_number }}</span> <span class="value mono">{{ o.batch_number }}</span>
</div> </div>
{% if o.product.requires_dates %}
<div class="detail-col"> <div class="detail-col">
<span class="label" data-i18n="date">Date:</span> <span class="label" data-i18n="date">Date:</span>
<span class="value">{{ o.production_date|date:"d/m/Y" }}</span> <span class="value">{{ o.production_date|date:"d/m/Y" }}</span>
@@ -38,6 +39,7 @@
<span class="label" data-i18n="next_control">Next:</span> <span class="label" data-i18n="next_control">Next:</span>
<span class="value">{{ o.next_control_date|date:"d/m/Y" }}</span> <span class="value">{{ o.next_control_date|date:"d/m/Y" }}</span>
</div> </div>
{% endif %}
</div> </div>
<div class="print-meta"> <div class="print-meta">
<span class="badge badge-accent">{{ o.canister_pages|add:o.box_pages }} <span data-i18n="pages_unit">Page(s)</span></span> <span class="badge badge-accent">{{ o.canister_pages|add:o.box_pages }} <span data-i18n="pages_unit">Page(s)</span></span>

View File

@@ -199,8 +199,10 @@
{% for weight in page.slips %} {% for weight in page.slips %}
<div class="slip-quadrant"> <div class="slip-quadrant">
<div class="var-field val-batch">{{ order.batch_number }}</div> <div class="var-field val-batch">{{ order.batch_number }}</div>
{% if show_dates %}
<div class="var-field val-date">{{ date_formatted }}</div> <div class="var-field val-date">{{ date_formatted }}</div>
<div class="var-field val-next">{{ next_control_formatted }}</div> <div class="var-field val-next">{{ next_control_formatted }}</div>
{% endif %}
<div class="var-field val-weight">{{ weight }}</div> <div class="var-field val-weight">{{ weight }}</div>
</div> </div>
{% endfor %} {% endfor %}

View File

@@ -26,6 +26,12 @@
<label for="prod-weight" data-i18n="default_weight">Default Weight</label> <label for="prod-weight" data-i18n="default_weight">Default Weight</label>
<input type="number" id="prod-weight" value="5" step="1" min="1" required> <input type="number" id="prod-weight" value="5" step="1" min="1" required>
</div> </div>
<div class="form-group">
<label class="checkbox-label">
<input type="checkbox" id="prod-requires-dates" checked>
<span data-i18n="requires_dates">Requires Date / Next Control</span>
</label>
</div>
<div class="form-actions-inline"> <div class="form-actions-inline">
<button type="submit" class="btn btn-accent" id="product-save-btn" data-i18n="save">Save</button> <button type="submit" class="btn btn-accent" id="product-save-btn" data-i18n="save">Save</button>
<button type="button" class="btn btn-ghost" id="product-cancel-btn" style="display:none;" onclick="cancelEdit()" data-i18n="cancel">Cancel</button> <button type="button" class="btn btn-ghost" id="product-cancel-btn" style="display:none;" onclick="cancelEdit()" data-i18n="cancel">Cancel</button>
@@ -51,6 +57,7 @@
<th data-i18n="product_code">Code</th> <th data-i18n="product_code">Code</th>
<th data-i18n="description">Description</th> <th data-i18n="description">Description</th>
<th data-i18n="default_weight">Weight</th> <th data-i18n="default_weight">Weight</th>
<th data-i18n="requires_dates_short">Dates</th>
<th></th> <th></th>
</tr> </tr>
</thead> </thead>
@@ -60,12 +67,14 @@
<td class="mono">{{ p.code }}</td> <td class="mono">{{ p.code }}</td>
<td>{{ p.description }}</td> <td>{{ p.description }}</td>
<td class="mono">{{ p.default_net_weight }}</td> <td class="mono">{{ p.default_net_weight }}</td>
<td>{{ p.requires_dates|yesno:"✓,—" }}</td>
<td> <td>
<button type="button" class="btn btn-ghost btn-sm" <button type="button" class="btn btn-ghost btn-sm"
data-id="{{ p.id }}" data-id="{{ p.id }}"
data-code="{{ p.code }}" data-code="{{ p.code }}"
data-desc="{{ p.description }}" data-desc="{{ p.description }}"
data-weight="{{ p.default_net_weight }}" data-weight="{{ p.default_net_weight }}"
data-requires-dates="{{ p.requires_dates|yesno:'true,false' }}"
onclick="editProduct(this)" onclick="editProduct(this)"
data-i18n="edit">Edit</button> data-i18n="edit">Edit</button>
<button type="button" class="btn btn-ghost btn-sm btn-danger" <button type="button" class="btn btn-ghost btn-sm btn-danger"
@@ -74,7 +83,7 @@
</td> </td>
</tr> </tr>
{% empty %} {% empty %}
<tr><td colspan="4" class="empty-state" data-i18n="no_products">No products yet</td></tr> <tr><td colspan="5" class="empty-state" data-i18n="no_products">No products yet</td></tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>

View File

@@ -39,11 +39,13 @@ def print_page(request, order_id):
pages = build_print_pages(order) pages = build_print_pages(order)
cal = load_calibration() cal = load_calibration()
show_dates = order.product.requires_dates
return render(request, 'slips/print_page.html', { return render(request, 'slips/print_page.html', {
'order': order, 'order': order,
'pages': pages, 'pages': pages,
'date_formatted': order.production_date.strftime('%d/%m/%Y'), 'show_dates': show_dates,
'next_control_formatted': order.next_control_date.strftime('%d/%m/%Y'), 'date_formatted': order.production_date.strftime('%d/%m/%Y') if order.production_date else '',
'next_control_formatted': order.next_control_date.strftime('%d/%m/%Y') if order.next_control_date else '',
'calibration_css': css_vars(cal), 'calibration_css': css_vars(cal),
}) })