// Optional browser QA: NODE_PATH must contain an installed playwright package.
const {chromium} = require('playwright');
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
const {execFileSync} = require('node:child_process');
const root = path.resolve(__dirname, '..');
const headers = JSON.parse(execFileSync('python', ['-c', 'import json; from manual_orders import HEADERS; print(json.dumps(HEADERS))'], {cwd: root, encoding: 'utf8'}));
const template = fs.readFileSync(path.join(root, 'templates/index.html'), 'utf8');
const markup = template.match(/{% if manual_orders_backend == 'postgres' %}([\s\S]*?){% else %}/)[1];
const html = ``;
let rows = [1, 2].map(id => ({id, version: 1, cells: headers.map((_, c) => c === 0 ? '2026-10-22 10:00:00' : c === 3 ? `테스트 고객 ${id}` : c === 4 ? 'TEST-0001' : c === 8 ? '00123' : '')}));
let failNext = false, conflictNext = false, exported = false, nextId = 3;
const server = http.createServer(async (req, res) => {
const reply = (code, data) => { res.writeHead(code, {'Content-Type': 'application/json'}); res.end(JSON.stringify(data)); };
if (req.url === '/') {res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});res.end(html);return;}
if (req.url.startsWith('/static/')) {res.writeHead(200, {'Content-Type': req.url.endsWith('.css') ? 'text/css' : 'application/javascript'});res.end(fs.readFileSync(path.join(root, req.url)));return;}
if (req.url === '/api/manual/orders' && req.method === 'GET') return reply(200, {headers, rows});
if (req.url === '/api/manual/orders' && req.method === 'POST') {rows.push({id: nextId++, version: 1, cells: headers.map(() => '')});return reply(200, {status: 'success'});}
if (req.url === '/api/manual/orders/cells') {
let body='';for await(const chunk of req)body+=chunk;
const changes=JSON.parse(body).changes;
if(failNext){failNext=false;return reply(503,{detail:'테스트 저장 장애'});}
if(conflictNext){conflictNext=false;const change=changes[0], row=rows.find(r=>r.id===change.id);row.cells[change.column]='다른 사용자의 최신값';row.version++;return reply(409,{detail:{message:'동시 수정 충돌',conflicts:[{id:row.id,column:change.column,value:row.cells[change.column]}]}});}
const updated=new Set();
for(const c of changes){const row=rows.find(r=>r.id===c.id);assert(row);assert(row.cells[c.column]===c.previous_value||row.cells[c.column]===c.value);row.cells[c.column]=c.value;updated.add(row.id);}
for(const id of updated)rows.find(r=>r.id===id).version++;
return reply(200,{rows:rows.filter(r=>updated.has(r.id))});
}
if(req.url==='/api/manual/orders/archive'){
let body='';for await(const chunk of req)body+=chunk;const selected=JSON.parse(body).rows;
for(const row of selected)assert.equal(rows.find(r=>r.id===row.id).version,row.version);
rows=rows.filter(r=>!selected.some(s=>s.id===r.id));return reply(200,{status:'success'});
}
if(req.url==='/api/sheet/download_and_clear'){exported=true;rows=[];res.writeHead(200,{'Content-Type':'application/octet-stream','Content-Disposition':"attachment; filename*=UTF-8''manual.xlsx"});res.end('exported rows');return;}
if(req.url==='/api/manual/orders/exports')return reply(200,exported?[{id:'test-export',filename:'manual.xlsx'}]:[]);
if(req.url==='/api/manual/orders/exports/test-export'){res.writeHead(200,{'Content-Disposition':'attachment; filename="manual.xlsx"'});res.end('exported rows');return;}
reply(404,{});
});
(async()=>{
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const browser=await chromium.launch({headless:true,executablePath:process.env.CORM_TEST_BROWSER||'C:/Program Files/Google/Chrome/Application/chrome.exe'});
try{
const page=await browser.newPage({viewport:{width:1440,height:900},acceptDownloads:true});
const errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(`http://127.0.0.1:${server.address().port}`);
await page.waitForSelector('td[data-id="1"]');
const cell=(id,column)=>page.locator(`td[data-id="${id}"][data-column="${column}"]`);
const saved=()=>page.waitForFunction(()=>document.getElementById('manual-save-status').textContent==='모든 변경사항 저장됨');
await cell(1,3).fill('자동 저장 고객');await saved();assert.equal(rows[0].cells[3],'자동 저장 고객');
await page.reload();await page.waitForSelector('td[data-id="1"]');assert.equal(await cell(1,3).textContent(),'자동 저장 고객');
await cell(1,3).focus();await page.keyboard.press('Tab');assert.equal(await page.locator(':focus').getAttribute('data-column'),'4');
await cell(1,4).evaluate(td=>{const data=new DataTransfer();data.setData('text/plain','CODE-A\t상품 A\nCODE-B\t상품 B');td.dispatchEvent(new ClipboardEvent('paste',{clipboardData:data,bubbles:true,cancelable:true}));});
await saved();assert.equal(rows[1].cells[5],'상품 B');
failNext=true;await cell(1,3).fill('장애 후 재시도');await page.waitForSelector('#manual-save-retry:not([hidden])');
assert.equal(await cell(1,3).textContent(),'장애 후 재시도');await page.click('#manual-save-retry');await saved();assert.equal(rows[0].cells[3],'장애 후 재시도');
conflictNext=true;await cell(1,3).fill('충돌 입력');await page.waitForSelector('#manual-save-retry:not([hidden])');
page.once('dialog',d=>d.dismiss());await page.click('#manual-save-retry');await saved();assert.equal(await cell(1,3).textContent(),'다른 사용자의 최신값');
await page.locator('body').click({position:{x:1300,y:800}});
fs.mkdirSync(path.join(root,'.cache'),{recursive:true});await page.screenshot({path:path.join(root,'.cache/manual-grid-qa.png')});
await page.click('#manual-add-row');await page.waitForSelector('td[data-id="3"]');
await cell(3,3).fill('삭제 전 수정');await page.check('input[data-row-id="3"]');
page.once('dialog',d=>d.accept());await page.click('#manual-delete-rows');await page.waitForFunction(()=>document.querySelectorAll('#manual-grid tbody tr').length===2);
page.once('dialog',d=>d.accept());const download=page.waitForEvent('download');await page.click('#manual-download');await download;
await page.waitForFunction(()=>document.getElementById('manual-grid-empty').hidden===false);
await page.click('#manual-exports summary');await page.waitForSelector('#manual-export-list a');assert.equal(await page.locator('#manual-export-list a').textContent(),'manual.xlsx');
assert.deepEqual(errors,[]);console.log('Browser QA passed: autosave, reload, Tab, multi-cell paste, failure retry, conflict, row add/delete, export and redownload link.');
}finally{await browser.close();server.close();}
})().catch(error=>{console.error(error);server.close();process.exitCode=1;});