feat: Phase 5 — part counter update, replacement, replacement history
All checks were successful
Deploy to Production / deploy (push) Successful in 1m5s
All checks were successful
Deploy to Production / deploy (push) Successful in 1m5s
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useMachine, useEquipmentParts } from '@/lib/hooks';
|
||||
import { useMachine, useEquipmentParts, useReplacements } from '@/lib/hooks';
|
||||
import { useToast } from '@/lib/toast-context';
|
||||
import { api } from '@/lib/api';
|
||||
import type { EquipmentPart } from '@/lib/types';
|
||||
import type { EquipmentPart, PartReplacementLog } from '@/lib/types';
|
||||
|
||||
const LIFECYCLE_TYPES = [
|
||||
{ value: 'hours', label: '시간 (Hours)' },
|
||||
@@ -56,6 +56,16 @@ export default function MachineDetailPage() {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [editPart, setEditPart] = useState<EquipmentPart | null>(null);
|
||||
|
||||
// Phase 5: 카운터, 교체, 교체이력 모달
|
||||
const [counterPart, setCounterPart] = useState<EquipmentPart | null>(null);
|
||||
const [counterValue, setCounterValue] = useState('');
|
||||
const [replacePart, setReplacePart] = useState<EquipmentPart | null>(null);
|
||||
const [replaceReason, setReplaceReason] = useState('');
|
||||
const [replaceNotes, setReplaceNotes] = useState('');
|
||||
const [historyPart, setHistoryPart] = useState<EquipmentPart | null>(null);
|
||||
const [replacements, setReplacements] = useState<PartReplacementLog[]>([]);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
|
||||
const openAddPart = useCallback(() => {
|
||||
setEditPart(null);
|
||||
setPartForm(INITIAL_PART_FORM);
|
||||
@@ -117,6 +127,87 @@ export default function MachineDetailPage() {
|
||||
}
|
||||
}, [partForm, tenantId, machineId, editPart, mutateParts, mutateMachine, closePartModal, addToast]);
|
||||
|
||||
const openCounterModal = useCallback((part: EquipmentPart) => {
|
||||
setCounterPart(part);
|
||||
setCounterValue(String(part.counter?.current_value ?? 0));
|
||||
}, []);
|
||||
|
||||
const closeCounterModal = useCallback(() => {
|
||||
setCounterPart(null);
|
||||
setCounterValue('');
|
||||
}, []);
|
||||
|
||||
const handleCounterSubmit = useCallback(async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!counterPart) return;
|
||||
const val = parseFloat(counterValue);
|
||||
if (isNaN(val) || val < 0) {
|
||||
addToast('0 이상의 숫자를 입력해주세요.', 'error');
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await api.put<EquipmentPart>(`/api/${tenantId}/parts/${counterPart.id}/counter`, { value: val });
|
||||
addToast('카운터가 업데이트되었습니다.', 'success');
|
||||
mutateParts();
|
||||
closeCounterModal();
|
||||
} catch {
|
||||
addToast('카운터 업데이트에 실패했습니다.', 'error');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, [counterPart, counterValue, tenantId, mutateParts, closeCounterModal, addToast]);
|
||||
|
||||
const openReplaceModal = useCallback((part: EquipmentPart) => {
|
||||
setReplacePart(part);
|
||||
setReplaceReason('');
|
||||
setReplaceNotes('');
|
||||
}, []);
|
||||
|
||||
const closeReplaceModal = useCallback(() => {
|
||||
setReplacePart(null);
|
||||
setReplaceReason('');
|
||||
setReplaceNotes('');
|
||||
}, []);
|
||||
|
||||
const handleReplaceSubmit = useCallback(async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!replacePart) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await api.post<{ status: string }>(`/api/${tenantId}/parts/${replacePart.id}/replace`, {
|
||||
reason: replaceReason.trim() || null,
|
||||
notes: replaceNotes.trim() || null,
|
||||
});
|
||||
addToast('부품이 교체되었습니다. 카운터가 초기화되었습니다.', 'success');
|
||||
mutateParts();
|
||||
closeReplaceModal();
|
||||
} catch {
|
||||
addToast('부품 교체에 실패했습니다.', 'error');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, [replacePart, replaceReason, replaceNotes, tenantId, mutateParts, closeReplaceModal, addToast]);
|
||||
|
||||
const openHistoryModal = useCallback(async (part: EquipmentPart) => {
|
||||
setHistoryPart(part);
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const data = await api.get<{ replacements: PartReplacementLog[] }>(`/api/${tenantId}/parts/${part.id}/replacements`);
|
||||
setReplacements(data.replacements);
|
||||
} catch {
|
||||
addToast('교체 이력을 불러오지 못했습니다.', 'error');
|
||||
setReplacements([]);
|
||||
} finally {
|
||||
setHistoryLoading(false);
|
||||
}
|
||||
}, [tenantId, addToast]);
|
||||
|
||||
const closeHistoryModal = useCallback(() => {
|
||||
setHistoryPart(null);
|
||||
setReplacements([]);
|
||||
}, []);
|
||||
|
||||
const handleDeletePart = useCallback(async (part: EquipmentPart) => {
|
||||
if (!confirm(`"${part.name}" 부품을 삭제하시겠습니까?`)) return;
|
||||
try {
|
||||
@@ -229,6 +320,15 @@ export default function MachineDetailPage() {
|
||||
<td>{COUNTER_SOURCES.find((s) => s.value === part.counter_source)?.label || part.counter_source}</td>
|
||||
<td>
|
||||
<div className="part-actions">
|
||||
<button className="btn-icon" onClick={() => openCounterModal(part)} title="카운터 업데이트">
|
||||
<span className="material-symbols-outlined">speed</span>
|
||||
</button>
|
||||
<button className="btn-icon" onClick={() => openReplaceModal(part)} title="부품 교체">
|
||||
<span className="material-symbols-outlined">swap_horiz</span>
|
||||
</button>
|
||||
<button className="btn-icon" onClick={() => openHistoryModal(part)} title="교체 이력">
|
||||
<span className="material-symbols-outlined">history</span>
|
||||
</button>
|
||||
<button className="btn-icon" onClick={() => openEditPart(part)} title="수정">
|
||||
<span className="material-symbols-outlined">edit</span>
|
||||
</button>
|
||||
@@ -364,6 +464,172 @@ export default function MachineDetailPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{counterPart && (
|
||||
<div className="modal-overlay" onClick={closeCounterModal}>
|
||||
<div className="modal-content modal-sm" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-header">
|
||||
<h3>카운터 업데이트</h3>
|
||||
<button className="modal-close" onClick={closeCounterModal}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleCounterSubmit}>
|
||||
<div className="counter-modal-info">
|
||||
<p className="counter-part-name">{counterPart.name}</p>
|
||||
<div className="counter-info-row">
|
||||
<span>수명 유형:</span>
|
||||
<strong>{LIFECYCLE_TYPES.find((t) => t.value === counterPart.lifecycle_type)?.label}</strong>
|
||||
</div>
|
||||
<div className="counter-info-row">
|
||||
<span>한계값:</span>
|
||||
<strong>{counterPart.lifecycle_limit}</strong>
|
||||
</div>
|
||||
<div className="counter-info-row">
|
||||
<span>현재값:</span>
|
||||
<strong>{counterPart.counter?.current_value ?? 0}</strong>
|
||||
</div>
|
||||
<div className="counter-info-row">
|
||||
<span>수명 %:</span>
|
||||
<strong>{(counterPart.counter?.lifecycle_pct ?? 0).toFixed(1)}%</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>새 카운터 값 *</label>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="예: 1500"
|
||||
value={counterValue}
|
||||
onChange={(e) => setCounterValue(e.target.value)}
|
||||
disabled={submitting}
|
||||
min="0"
|
||||
step="any"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="btn-outline" onClick={closeCounterModal} disabled={submitting}>
|
||||
취소
|
||||
</button>
|
||||
<button type="submit" className="btn-primary" disabled={submitting || !counterValue}>
|
||||
{submitting ? (
|
||||
<span className="material-symbols-outlined spinning">progress_activity</span>
|
||||
) : (
|
||||
<span className="material-symbols-outlined">speed</span>
|
||||
)}
|
||||
업데이트
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{replacePart && (
|
||||
<div className="modal-overlay" onClick={closeReplaceModal}>
|
||||
<div className="modal-content modal-sm" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-header">
|
||||
<h3>부품 교체</h3>
|
||||
<button className="modal-close" onClick={closeReplaceModal}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleReplaceSubmit}>
|
||||
<div className="replace-warning">
|
||||
<span className="material-symbols-outlined">warning</span>
|
||||
<p><strong>{replacePart.name}</strong> 부품을 교체합니다. 카운터가 0으로 초기화됩니다.</p>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>교체 사유</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="예: 수명 만료, 불량 교체"
|
||||
value={replaceReason}
|
||||
onChange={(e) => setReplaceReason(e.target.value)}
|
||||
disabled={submitting}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="form-field">
|
||||
<label>비고</label>
|
||||
<textarea
|
||||
className="form-textarea"
|
||||
placeholder="추가 메모 (선택)"
|
||||
value={replaceNotes}
|
||||
onChange={(e) => setReplaceNotes(e.target.value)}
|
||||
disabled={submitting}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="btn-outline" onClick={closeReplaceModal} disabled={submitting}>
|
||||
취소
|
||||
</button>
|
||||
<button type="submit" className="btn-primary btn-warning" disabled={submitting}>
|
||||
{submitting ? (
|
||||
<span className="material-symbols-outlined spinning">progress_activity</span>
|
||||
) : (
|
||||
<span className="material-symbols-outlined">swap_horiz</span>
|
||||
)}
|
||||
교체 확인
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{historyPart && (
|
||||
<div className="modal-overlay" onClick={closeHistoryModal}>
|
||||
<div className="modal-content modal-lg" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-header">
|
||||
<h3>{historyPart.name} — 교체 이력</h3>
|
||||
<button className="modal-close" onClick={closeHistoryModal}>
|
||||
<span className="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="replacement-history">
|
||||
{historyLoading ? (
|
||||
<div className="loading-sm">
|
||||
<span className="material-symbols-outlined spinning">progress_activity</span>
|
||||
</div>
|
||||
) : replacements.length === 0 ? (
|
||||
<div className="empty-state-sm">
|
||||
<span className="material-symbols-outlined">history</span>
|
||||
<p>교체 이력이 없습니다.</p>
|
||||
</div>
|
||||
) : (
|
||||
<table className="history-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>교체일시</th>
|
||||
<th>교체 시 카운터</th>
|
||||
<th>교체 시 수명%</th>
|
||||
<th>사유</th>
|
||||
<th>비고</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{replacements.map((log) => (
|
||||
<tr key={log.id}>
|
||||
<td>{log.replaced_at ? new Date(log.replaced_at).toLocaleString('ko-KR') : '-'}</td>
|
||||
<td>{log.counter_at_replacement}</td>
|
||||
<td>{log.lifecycle_pct_at_replacement.toFixed(1)}%</td>
|
||||
<td>{log.reason || '-'}</td>
|
||||
<td>{log.notes || '-'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="btn-outline" onClick={closeHistoryModal}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1655,6 +1655,118 @@ a {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* ===== Phase 5: Counter / Replace / History ===== */
|
||||
|
||||
.modal-sm {
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
.counter-modal-info {
|
||||
padding: 16px;
|
||||
background: var(--md-surface-variant);
|
||||
border-radius: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.counter-part-name {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
color: var(--md-on-surface);
|
||||
}
|
||||
|
||||
.counter-info-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 4px 0;
|
||||
font-size: 14px;
|
||||
color: var(--md-on-surface-variant);
|
||||
}
|
||||
|
||||
.counter-info-row strong {
|
||||
color: var(--md-on-surface);
|
||||
}
|
||||
|
||||
.replace-warning {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
background: #fff3e0;
|
||||
border: 1px solid #ffb74d;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 14px;
|
||||
color: #e65100;
|
||||
}
|
||||
|
||||
.replace-warning .material-symbols-outlined {
|
||||
font-size: 22px;
|
||||
flex-shrink: 0;
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.btn-warning {
|
||||
background: #e65100 !important;
|
||||
border-color: #e65100 !important;
|
||||
}
|
||||
|
||||
.btn-warning:hover {
|
||||
background: #bf360c !important;
|
||||
}
|
||||
|
||||
.replacement-history {
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.history-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.history-table th {
|
||||
text-align: left;
|
||||
padding: 10px 14px;
|
||||
background: var(--md-surface-variant);
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
color: var(--md-on-surface-variant);
|
||||
border-bottom: 1px solid var(--md-outline-variant);
|
||||
}
|
||||
|
||||
.history-table td {
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--md-outline-variant);
|
||||
color: var(--md-on-surface);
|
||||
}
|
||||
|
||||
.history-table tbody tr:hover {
|
||||
background: var(--md-surface-variant);
|
||||
}
|
||||
|
||||
.loading-sm {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 32px;
|
||||
color: var(--md-primary);
|
||||
}
|
||||
|
||||
.empty-state-sm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 32px;
|
||||
color: var(--md-on-surface-variant);
|
||||
}
|
||||
|
||||
.empty-state-sm .material-symbols-outlined {
|
||||
font-size: 40px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ===== Responsive ===== */
|
||||
@media (max-width: 768px) {
|
||||
.topnav-center {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import useSWR from 'swr';
|
||||
import { fetcher, getTenantUrl } from './api';
|
||||
import type { Tenant, Machine, MachineDetail, EquipmentPart, InspectionTemplate, InspectionSession } from './types';
|
||||
import type { Tenant, Machine, MachineDetail, EquipmentPart, InspectionTemplate, InspectionSession, PartReplacementLog } from './types';
|
||||
|
||||
export function useTenants() {
|
||||
const { data, error, isLoading, mutate } = useSWR<{ tenants: Tenant[] }>(
|
||||
@@ -109,6 +109,22 @@ export function useTemplate(tenantId?: string, templateId?: string) {
|
||||
};
|
||||
}
|
||||
|
||||
export function useReplacements(tenantId?: string, partId?: string) {
|
||||
const url = tenantId && partId ? `/api/${tenantId}/parts/${partId}/replacements` : null;
|
||||
const { data, error, isLoading, mutate } = useSWR<{ replacements: PartReplacementLog[] }>(
|
||||
url,
|
||||
fetcher,
|
||||
{ dedupingInterval: 2000 },
|
||||
);
|
||||
|
||||
return {
|
||||
replacements: data?.replacements || [],
|
||||
error,
|
||||
isLoading,
|
||||
mutate,
|
||||
};
|
||||
}
|
||||
|
||||
export function useInspections(tenantId?: string, status?: string, templateId?: string) {
|
||||
const params = new URLSearchParams();
|
||||
if (status) params.set('status', status);
|
||||
|
||||
@@ -132,6 +132,17 @@ export interface InspectionSession {
|
||||
updated_at: string | null;
|
||||
}
|
||||
|
||||
export interface PartReplacementLog {
|
||||
id: string;
|
||||
equipment_part_id: string;
|
||||
replaced_by: string | null;
|
||||
replaced_at: string | null;
|
||||
counter_at_replacement: number;
|
||||
lifecycle_pct_at_replacement: number;
|
||||
reason: string | null;
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
export interface InspectionTemplate {
|
||||
id: string;
|
||||
tenant_id: string;
|
||||
|
||||
@@ -9,7 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from src.database.config import get_db
|
||||
from src.database.models import Machine, EquipmentPart, PartCounter
|
||||
from src.database.models import Machine, EquipmentPart, PartCounter, PartReplacementLog
|
||||
from src.auth.models import TokenData
|
||||
from src.auth.dependencies import require_auth, verify_tenant_access
|
||||
|
||||
@@ -37,6 +37,15 @@ class PartUpdate(BaseModel):
|
||||
counter_source: Optional[str] = None
|
||||
|
||||
|
||||
class CounterUpdate(BaseModel):
|
||||
value: float
|
||||
|
||||
|
||||
class ReplaceRequest(BaseModel):
|
||||
reason: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
def _format_ts(val) -> Optional[str]:
|
||||
if val is None:
|
||||
return None
|
||||
@@ -297,3 +306,154 @@ async def delete_part(
|
||||
await db.commit()
|
||||
|
||||
return {"status": "success", "message": "부품이 비활성화되었습니다."}
|
||||
|
||||
|
||||
@router.put("/api/{tenant_id}/parts/{part_id}/counter")
|
||||
async def update_counter(
|
||||
body: CounterUpdate,
|
||||
tenant_id: str = Path(...),
|
||||
part_id: UUID = Path(...),
|
||||
current_user: TokenData = Depends(require_auth),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
verify_tenant_access(tenant_id, current_user)
|
||||
|
||||
stmt = (
|
||||
select(EquipmentPart)
|
||||
.options(selectinload(EquipmentPart.counter))
|
||||
.where(
|
||||
EquipmentPart.id == part_id,
|
||||
EquipmentPart.tenant_id == tenant_id,
|
||||
EquipmentPart.is_active == True,
|
||||
)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
part = result.scalar_one_or_none()
|
||||
if not part:
|
||||
raise HTTPException(status_code=404, detail="부품을 찾을 수 없습니다.")
|
||||
|
||||
counter = part.counter
|
||||
if not counter:
|
||||
raise HTTPException(status_code=404, detail="카운터를 찾을 수 없습니다.")
|
||||
|
||||
if body.value < 0:
|
||||
raise HTTPException(status_code=400, detail="카운터 값은 0 이상이어야 합니다.")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
counter.current_value = body.value
|
||||
counter.lifecycle_pct = (
|
||||
(body.value / float(part.lifecycle_limit)) * 100
|
||||
if float(part.lifecycle_limit) > 0
|
||||
else 0
|
||||
)
|
||||
counter.last_updated_at = now
|
||||
counter.version = (counter.version or 0) + 1
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(counter)
|
||||
|
||||
return _part_to_dict(part, counter)
|
||||
|
||||
|
||||
@router.post("/api/{tenant_id}/parts/{part_id}/replace")
|
||||
async def replace_part(
|
||||
tenant_id: str = Path(...),
|
||||
part_id: UUID = Path(...),
|
||||
body: Optional[ReplaceRequest] = None,
|
||||
current_user: TokenData = Depends(require_auth),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
verify_tenant_access(tenant_id, current_user)
|
||||
|
||||
stmt = (
|
||||
select(EquipmentPart)
|
||||
.options(selectinload(EquipmentPart.counter))
|
||||
.where(
|
||||
EquipmentPart.id == part_id,
|
||||
EquipmentPart.tenant_id == tenant_id,
|
||||
EquipmentPart.is_active == True,
|
||||
)
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
part = result.scalar_one_or_none()
|
||||
if not part:
|
||||
raise HTTPException(status_code=404, detail="부품을 찾을 수 없습니다.")
|
||||
|
||||
counter = part.counter
|
||||
if not counter:
|
||||
raise HTTPException(status_code=404, detail="카운터를 찾을 수 없습니다.")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
log = PartReplacementLog(
|
||||
tenant_id=tenant_id,
|
||||
equipment_part_id=part.id,
|
||||
replaced_by=UUID(current_user.user_id),
|
||||
replaced_at=now,
|
||||
counter_at_replacement=float(counter.current_value or 0),
|
||||
lifecycle_pct_at_replacement=float(counter.lifecycle_pct or 0),
|
||||
reason=body.reason if body else None,
|
||||
notes=body.notes if body else None,
|
||||
)
|
||||
db.add(log)
|
||||
|
||||
counter.current_value = 0
|
||||
counter.lifecycle_pct = 0
|
||||
counter.last_reset_at = now
|
||||
counter.last_updated_at = now
|
||||
counter.version = (counter.version or 0) + 1
|
||||
|
||||
part.installed_at = now
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(part)
|
||||
await db.refresh(counter)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "부품이 교체되었습니다.",
|
||||
"part": _part_to_dict(part, counter),
|
||||
}
|
||||
|
||||
|
||||
def _replacement_to_dict(log: PartReplacementLog) -> dict:
|
||||
return {
|
||||
"id": str(log.id),
|
||||
"equipment_part_id": str(log.equipment_part_id),
|
||||
"replaced_by": str(log.replaced_by) if log.replaced_by else None,
|
||||
"replaced_at": _format_ts(log.replaced_at),
|
||||
"counter_at_replacement": float(log.counter_at_replacement),
|
||||
"lifecycle_pct_at_replacement": float(log.lifecycle_pct_at_replacement),
|
||||
"reason": str(log.reason) if log.reason else None,
|
||||
"notes": str(log.notes) if log.notes else None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/{tenant_id}/parts/{part_id}/replacements")
|
||||
async def list_replacements(
|
||||
tenant_id: str = Path(...),
|
||||
part_id: UUID = Path(...),
|
||||
current_user: TokenData = Depends(require_auth),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
verify_tenant_access(tenant_id, current_user)
|
||||
|
||||
part_stmt = select(EquipmentPart).where(
|
||||
EquipmentPart.id == part_id, EquipmentPart.tenant_id == tenant_id
|
||||
)
|
||||
part = (await db.execute(part_stmt)).scalar_one_or_none()
|
||||
if not part:
|
||||
raise HTTPException(status_code=404, detail="부품을 찾을 수 없습니다.")
|
||||
|
||||
stmt = (
|
||||
select(PartReplacementLog)
|
||||
.where(
|
||||
PartReplacementLog.equipment_part_id == part_id,
|
||||
PartReplacementLog.tenant_id == tenant_id,
|
||||
)
|
||||
.order_by(PartReplacementLog.replaced_at.desc())
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
logs = result.scalars().all()
|
||||
|
||||
return {"replacements": [_replacement_to_dict(log) for log in logs]}
|
||||
|
||||
@@ -223,3 +223,131 @@ async def test_delete_machine_with_parts_rejected(client: AsyncClient, seeded_db
|
||||
|
||||
resp = await client.delete(f"/api/test-co/machines/{machine_id}", headers=headers)
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
async def _create_part(client: AsyncClient, headers: dict, machine_id: str) -> dict:
|
||||
resp = await client.post(
|
||||
f"/api/test-co/machines/{machine_id}/parts",
|
||||
json={
|
||||
"name": "카운터 테스트 부품",
|
||||
"lifecycle_type": "count",
|
||||
"lifecycle_limit": 1000,
|
||||
"alarm_threshold": 80.0,
|
||||
"counter_source": "manual",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
return resp.json()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_counter(client: AsyncClient, seeded_db):
|
||||
headers = await get_auth_headers(client)
|
||||
machine_id = await _create_machine(client, headers)
|
||||
part = await _create_part(client, headers, machine_id)
|
||||
|
||||
resp = await client.put(
|
||||
f"/api/test-co/parts/{part['id']}/counter",
|
||||
json={"value": 500},
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["counter"]["current_value"] == 500
|
||||
assert data["counter"]["lifecycle_pct"] == 50.0
|
||||
assert data["counter"]["version"] == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_counter_exceeds_limit(client: AsyncClient, seeded_db):
|
||||
headers = await get_auth_headers(client)
|
||||
machine_id = await _create_machine(client, headers)
|
||||
part = await _create_part(client, headers, machine_id)
|
||||
|
||||
resp = await client.put(
|
||||
f"/api/test-co/parts/{part['id']}/counter",
|
||||
json={"value": 1200},
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["counter"]["lifecycle_pct"] == 120.0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_counter_negative_rejected(client: AsyncClient, seeded_db):
|
||||
headers = await get_auth_headers(client)
|
||||
machine_id = await _create_machine(client, headers)
|
||||
part = await _create_part(client, headers, machine_id)
|
||||
|
||||
resp = await client.put(
|
||||
f"/api/test-co/parts/{part['id']}/counter",
|
||||
json={"value": -10},
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_replace_part_resets_counter(client: AsyncClient, seeded_db):
|
||||
headers = await get_auth_headers(client)
|
||||
machine_id = await _create_machine(client, headers)
|
||||
part = await _create_part(client, headers, machine_id)
|
||||
|
||||
await client.put(
|
||||
f"/api/test-co/parts/{part['id']}/counter",
|
||||
json={"value": 800},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
resp = await client.post(
|
||||
f"/api/test-co/parts/{part['id']}/replace",
|
||||
json={"reason": "수명 도달", "notes": "교체 완료"},
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["part"]["counter"]["current_value"] == 0
|
||||
assert data["part"]["counter"]["lifecycle_pct"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_replacements(client: AsyncClient, seeded_db):
|
||||
headers = await get_auth_headers(client)
|
||||
machine_id = await _create_machine(client, headers)
|
||||
part = await _create_part(client, headers, machine_id)
|
||||
|
||||
await client.put(
|
||||
f"/api/test-co/parts/{part['id']}/counter",
|
||||
json={"value": 500},
|
||||
headers=headers,
|
||||
)
|
||||
await client.post(
|
||||
f"/api/test-co/parts/{part['id']}/replace",
|
||||
json={"reason": "1차 교체"},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
await client.put(
|
||||
f"/api/test-co/parts/{part['id']}/counter",
|
||||
json={"value": 300},
|
||||
headers=headers,
|
||||
)
|
||||
await client.post(
|
||||
f"/api/test-co/parts/{part['id']}/replace",
|
||||
json={"reason": "2차 교체"},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
resp = await client.get(
|
||||
f"/api/test-co/parts/{part['id']}/replacements",
|
||||
headers=headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["replacements"]) == 2
|
||||
assert data["replacements"][0]["reason"] == "2차 교체"
|
||||
assert data["replacements"][0]["counter_at_replacement"] == 300
|
||||
assert data["replacements"][1]["reason"] == "1차 교체"
|
||||
assert data["replacements"][1]["counter_at_replacement"] == 500
|
||||
|
||||
Reference in New Issue
Block a user