Evo-ERP/app/web/views/transaction.py
2024-11-06 02:39:48 +08:00

60 lines
2.0 KiB
Python

from flask import Blueprint, render_template, redirect, url_for, flash, request
from ...services.transaction_service import TransactionService
from ...services.product_service import ProductService
from ..forms.transaction import TransactionForm
from datetime import datetime, time
bp = Blueprint('transaction', __name__)
@bp.route('/transactions')
def list_transactions():
transactions = TransactionService.get_all_transactions()
# 計算今日交易統計
today_start = datetime.combine(datetime.today(), time.min)
today_end = datetime.combine(datetime.today(), time.max)
today_transactions = [t for t in transactions
if today_start <= t.created_at <= today_end]
today_in = sum(1 for t in today_transactions if t.type == 'in')
today_out = sum(1 for t in today_transactions if t.type == 'out')
return render_template('transaction/list.html',
transactions=transactions,
today_in=today_in,
today_out=today_out)
@bp.route('/transactions/create', methods=['GET', 'POST'])
def create_transaction():
form = TransactionForm()
form.product_id.choices = [
(p.id, f'{p.name} ({p.code}) - 庫存: {p.quantity}')
for p in ProductService.get_all_products()
]
if form.validate_on_submit():
try:
data = {
'product_id': form.product_id.data,
'type': form.type.data,
'quantity': form.quantity.data
}
TransactionService.create_transaction(data)
flash('交易新增成功', 'success')
return redirect(url_for('transaction.list_transactions'))
except ValueError as e:
flash(str(e), 'error')
# 預設交易類型
if request.args.get('type'):
form.type.data = request.args.get('type')
# 預設商品
if request.args.get('product_id'):
form.product_id.data = int(request.args.get('product_id'))
return render_template('transaction/create.html', form=form)