[feat] negodata: 협력사 채팅 계정(supplier_users) 관리 — 발급·비번 재설정·활성상태

- 백엔드: supplier_users/supplier_user_tokens ORM 매핑, /v1/supplier/{id}/account 4종(조회·발급·재설정·상태), 회사 스코프 게이팅, 재설정·비활성 시 토큰 삭제로 기존 로그인 즉시 무효화
- 비밀번호: 발급=서버 자동생성(1회 반환), 재설정=커스텀 지정 가능(미지정 시 자동생성)
- 프론트: 협력사 상세 SupplierAccountManager 섹션 + 목록 '채팅 계정' 컬럼, orval 재생성(SupplierType 은 enumLabels 로컬 상수로 이동)
- 테스트: test_supplier_account.py 9건, 전체 스위트 green
This commit is contained in:
minaChoi committed 2026-07-10 10:14:00 +09:00
1 parent a80dac20ed
commit 7f1c0be2b3
37 files changed
+1385 -36

No files matched your search

@@ -13,6 +13,7 @@ import { PhoneInput } from '@/components/ui/phone-input';
import { Sheet } from '@/components/ui/sheet';
import { useAuthStore } from '@/stores/auth';
import { SupplierItemsManager } from './SupplierItemsManager';
import { SupplierAccountManager } from './SupplierAccountManager';
import { type Partner } from '../types';
const schema = z.object({
@@ -215,6 +216,9 @@ export function PartnerFormSheet({
{/* 취급상품 관리 — 수정 모드(협력사 확정)에서만. 추가/삭제/유형변경은 즉시 서버 반영. */}
{mode === 'edit' && partner && <SupplierItemsManager supplierId={partner.supplier_id} />}
{/* 채팅 계정 관리 — 수정 모드에서만. 발급/재설정/활성상태는 즉시 서버 반영. */}
{mode === 'edit' && partner && <SupplierAccountManager supplierId={partner.supplier_id} />}
{/* Buttons wrapper */}
<div className="pt-4 flex items-center gap-2 border-t border-border mt-8 justify-between">
{mode === 'edit' && partner && (
@@ -71,6 +71,20 @@ export function PartnerTable({
cellClassName: 'font-mono text-muted-foreground',
cell: (part) => (part.total_revenue != null ? `₩${Number(part.total_revenue).toLocaleString()}` : '-'),
},
{
header: '채팅 계정',
align: 'center',
cellClassName: 'font-mono whitespace-nowrap',
cell: (part) =>
part.account_login_id ? (
<span className="text-xs text-foreground">
{part.account_login_id}
{part.account_status === 2 && <span className="ml-1 text-[10px] text-rose-500">비활성</span>}
</span>
) : (
<span className="text-[10px] text-muted-foreground">미발급</span>
),
},
{
header: '작성자',
align: 'center',
@@ -0,0 +1,189 @@
import { useState } from 'react';
import { Copy, KeyRound } from 'lucide-react';
import { Typography } from '@/components/ui/typography';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { showToast } from '@/lib/notify';
import { confirm } from '@/lib/confirm';
import { useSupplierAccount } from '../hooks/useSupplierAccount';
// 협력사 상세의 채팅 계정 관리 섹션 — 발급/비번 재설정/활성상태, 각 조작 즉시 서버 반영.
// 비밀번호는 발급·재설정 직후 이 화면에서만 1회 표시된다(해시 저장이라 재조회 불가).
export function SupplierAccountManager({ supplierId }: { supplierId: string }) {
const { account, isLoading, create, resetPassword, setStatus } = useSupplierAccount(supplierId);
const [loginId, setLoginId] = useState('');
const [issuedPassword, setIssuedPassword] = useState<string | null>(null); // 방금 발급/재설정된 평문(1회 표시)
const [resetPw, setResetPw] = useState<string | null>(null); // 재설정 입력행 값(null=닫힘), 자동생성 프리필
const [busy, setBusy] = useState(false);
const run = async (fn: () => Promise<void>) => {
setBusy(true);
try {
await fn();
} catch (err) {
showToast(err instanceof Error ? err.message : '채팅 계정 처리 실패', 'error');
} finally {
setBusy(false);
}
};
const handleCreate = () =>
run(async () => {
const pw = await create(loginId.trim());
setIssuedPassword(pw);
showToast('채팅 계정이 발급되었습니다.', 'success');
});
const handleApplyReset = async () => {
const pw = (resetPw ?? '').trim();
if (pw.length < 4) {
showToast('비밀번호는 4자 이상으로 입력하세요.', 'error');
return;
}
await run(async () => {
const applied = await resetPassword(pw);
setIssuedPassword(applied);
setResetPw(null);
showToast('비밀번호가 재설정되었습니다. 새 비밀번호를 협력사에 전달해 주세요.', 'success');
});
};
const handleToggleStatus = async () => {
const deactivating = account?.status === 1;
if (
deactivating &&
!(await confirm({
title: '채팅 계정 비활성화',
description: '협력사가 협상 채팅에 로그인할 수 없게 되고, 이미 로그인된 세션도 즉시 끊깁니다. 계속하시겠습니까?',
confirmText: '비활성화',
destructive: true,
}))
)
return;
await run(async () => {
await setStatus(deactivating ? 2 : 1);
setIssuedPassword(null);
showToast(deactivating ? '채팅 계정이 비활성화되었습니다.' : '채팅 계정이 활성화되었습니다.', 'info');
});
};
return (
<div className="pt-4 border-t border-border space-y-2">
<Typography as="label" variant="label">채팅 계정 (협상 참여 로그인)</Typography>
{isLoading ? (
<Typography as="p" variant="small" className="p-3 text-muted-foreground text-[11px]">불러오는 중…</Typography>
) : account == null ? (
// 미발급 — 로그인 ID 직접 입력 후 발급(비밀번호는 서버 자동생성).
<div className="space-y-1">
<Typography as="p" variant="small" className="text-muted-foreground text-[11px]">
발급된 채팅 계정이 없습니다. 로그인 ID를 정해 발급하세요.
</Typography>
<div className="flex items-center gap-2">
<Input
id="chat-account-login-id"
type="text"
value={loginId}
onChange={(e) => setLoginId(e.target.value)}
maxLength={20}
className="text-foreground text-xs flex-1"
placeholder="로그인 ID (영문·숫자, 20자 이내)"
/>
<Button type="button" size="sm" onClick={handleCreate} disabled={busy || !loginId.trim()}>
<KeyRound />
계정 발급
</Button>
</div>
</div>
) : (
// 발급됨 — ID·상태 표시 + 비번 재설정/활성상태 토글.
<div className="border border-border rounded p-2 space-y-2">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0">
<Typography as="span" variant="small" className="font-mono font-semibold truncate">{account.login_id}</Typography>
<Typography
as="span"
variant="small"
className={`text-[10px] whitespace-nowrap ${account.status === 1 ? 'text-emerald-600' : 'text-rose-500'}`}
>
● {account.status === 1 ? '활성' : '비활성'}
</Typography>
</div>
<div className="flex items-center gap-1.5 shrink-0">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setIssuedPassword(null);
setResetPw(generatePassword());
}}
disabled={busy || resetPw != null}
>
비밀번호 재설정
</Button>
<Button type="button" variant="outline" size="sm" onClick={handleToggleStatus} disabled={busy}>
{account.status === 1 ? '비활성화' : '활성화'}
</Button>
</div>
</div>
{resetPw != null && (
<div className="space-y-1">
<div className="flex items-center gap-2">
<Input
id="chat-account-reset-pw"
type="text"
value={resetPw}
onChange={(e) => setResetPw(e.target.value)}
maxLength={72}
className="text-foreground text-xs font-mono flex-1"
placeholder="새 비밀번호 (4자 이상)"
/>
<Button type="button" size="sm" onClick={handleApplyReset} disabled={busy}>
적용
</Button>
<Button type="button" variant="outline" size="sm" onClick={() => setResetPw(null)} disabled={busy}>
취소
</Button>
</div>
<Typography as="p" variant="small" className="text-[10px] text-muted-foreground">
⚠ 적용 시 협력사의 기존 채팅 로그인이 즉시 끊깁니다.
</Typography>
</div>
)}
{issuedPassword && (
<div className="rounded bg-amber-500/10 border border-amber-500/30 p-2 space-y-1">
<div className="flex items-center justify-between gap-2">
<Typography as="span" variant="small" className="font-mono font-semibold">{issuedPassword}</Typography>
<button
type="button"
title="비밀번호 복사"
className="p-1 rounded text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
onClick={() => {
void navigator.clipboard?.writeText(issuedPassword);
showToast('비밀번호가 복사되었습니다.', 'info');
}}
>
<Copy size={14} />
</button>
</div>
<Typography as="p" variant="small" className="text-[10px] text-amber-700 dark:text-amber-500">
⚠ 비밀번호는 지금만 표시됩니다. 협력사에 전달해 주세요. (분실 시 재설정)
</Typography>
</div>
)}
</div>
)}
</div>
);
}
// 재설정 프리필용 임시 비밀번호(XXXX-XXXX) — 서버 자동생성과 같은 형식, 혼동 문자(0O1lI) 제외.
const PW_ALPHABET = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789';
function generatePassword(): string {
const block = () =>
Array.from(crypto.getRandomValues(new Uint32Array(4)), (n) => PW_ALPHABET[n % PW_ALPHABET.length]).join('');
return `${block()}-${block()}`;
}
@@ -1,12 +1,11 @@
import { useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { useListItems } from '@/api/generated/item/item';
import { SupplierType } from '@/api/generated/model';
import { Typography } from '@/components/ui/typography';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Combobox, type ComboOption } from '@/components/ui/combobox';
import { SUPPLIER_TYPE_OPTIONS, supplierTypeLabel } from '@/lib/enumLabels';
import { SUPPLIER_TYPE_OPTIONS, SupplierType, supplierTypeLabel } from '@/lib/enumLabels';
import { showToast } from '@/lib/notify';
import { useSupplierItems } from '../hooks/useSupplierItems';
@@ -0,0 +1,66 @@
import { useQueryClient } from '@tanstack/react-query';
import {
useGetSupplierAccount,
createSupplierAccount,
resetSupplierAccountPassword,
updateSupplierAccountStatus,
getGetSupplierAccountQueryKey,
} from '@/api/generated/supplier/supplier';
import type { SupplierAccountData } from '@/api/generated/model/supplierAccountData';
import type { ErrorInfo } from '@/api/generated/model/errorInfo';
// 서버 공통응답(result.success=false)을 한글 사유로 변환. 정상이면 null.
function supplierAccountError(result: ErrorInfo | undefined): string | null {
if (!result || result.success !== false) return null;
if (result.desc === 'SUPPLIER_ACCOUNT_LOGIN_ID_DUPLICATE') return '이미 사용 중인 로그인 ID입니다(다른 협력사 포함 전역 중복).';
if (result.desc === 'SUPPLIER_ACCOUNT_ALREADY_EXISTS') return '이미 발급된 채팅 계정이 있습니다.';
if (result.desc === 'SUPPLIER_ACCOUNT_NOT_FOUND') return '발급된 채팅 계정이 없습니다.';
return result.desc || '채팅 계정 처리에 실패했습니다.';
}
// 협력사 채팅(협상) 계정 서버 데이터 + 발급/비번재설정/활성상태. 협력사 상세(PartnerFormSheet)에서 쓴다.
// 발급/재설정 응답의 평문 비밀번호는 그 자리에서 1회만 반환된다(재조회 불가).
export function useSupplierAccount(supplierId: string | undefined) {
const queryClient = useQueryClient();
const query = useGetSupplierAccount(supplierId ?? '', { query: { enabled: !!supplierId } });
// 계정 상태는 목록의 '채팅 계정' 컬럼에도 실리므로 목록 쿼리까지 함께 재조회.
const refresh = () =>
Promise.all([
supplierId
? queryClient.invalidateQueries({ queryKey: getGetSupplierAccountQueryKey(supplierId) })
: Promise.resolve(),
queryClient.invalidateQueries({ queryKey: ['/v1/supplier/list'] }),
]);
const account: SupplierAccountData | null = (query.data?.account as SupplierAccountData | undefined) ?? null;
const create = async (loginId: string): Promise<string> => {
if (!supplierId) throw new Error('협력사가 지정되지 않았습니다.');
const res = await createSupplierAccount(supplierId, { login_id: loginId });
const msg = supplierAccountError(res.result);
if (msg) throw new Error(msg);
await refresh();
return res.initial_password ?? '';
};
// password 지정 시 그 값으로, 미지정 시 서버 자동생성.
const resetPassword = async (password?: string): Promise<string> => {
if (!supplierId) throw new Error('협력사가 지정되지 않았습니다.');
const res = await resetSupplierAccountPassword(supplierId, { password });
const msg = supplierAccountError(res.result);
if (msg) throw new Error(msg);
await refresh();
return res.new_password ?? '';
};
const setStatus = async (status: number) => {
if (!supplierId) throw new Error('협력사가 지정되지 않았습니다.');
const res = await updateSupplierAccountStatus(supplierId, { status });
const msg = supplierAccountError(res.result);
if (msg) throw new Error(msg);
await refresh();
};
return { account, isLoading: query.isLoading, create, resetPassword, setStatus };
}