/** @OnlyCurrentDoc */ // AGI Tools Lab — 아파트 매매 실거래 알림. 템플릿에 연결된 Google Apps Script용. // Plain ECMAScript shared by the web exercise and the standalone Apps Script. const APARTMENT_TRADE_HEADERS = Object.freeze({ '관심단지': ['지역코드 (5자리)', '법정동명', '단지명', '전용면적 (㎡, 선택)', '지번 (선택)'], '거래기록': ['감지 시각 (KST)', '변경 유형', '단지', '계약일', '전용면적 (㎡)', '층', '매매가 (만원)', '직전 대비 (만원)', '해제일', '알림 상태', '기계용 기록 (편집 금지)'], '실행기록': ['실행 시각 (KST)', '결과', '초기 기록', '신규', '중복', '해제', '발송', '안내'], }); const APARTMENT_TRADE_MAIL = Object.freeze({ none: '기록만', pending: '대기', ambiguous: '발송 여부 확인 필요', sent: '발송', }); function watchedMonths(yearMonth, count = 3) { if (!/^\d{4}(0[1-9]|1[0-2])$/.test(yearMonth)) throw Error('월 형식 오류'); const year = Number(yearMonth.slice(0, 4)), month = Number(yearMonth.slice(4)); return Array.from({ length: count }, (_, i) => { const n = year * 12 + month - 1 - i; return String(Math.floor(n / 12)).padStart(4, '0') + String(n % 12 + 1).padStart(2, '0'); }); } function trimTradeField(value) { return String(value ?? '').normalize('NFC').trim(); } function normalizeTradeField(value) { return trimTradeField(value).replace(/\s+/gu, '').toLowerCase(); } function tradeDate(year, month, day) { const d = new Date(Date.UTC(year, month - 1, day)); if (!Number.isInteger(year) || year < 2000 || year > 2199 || !Number.isInteger(month) || !Number.isInteger(day) || d.getUTCDate() !== day || d.getUTCMonth() + 1 !== month) throw Error('계약일 형식 오류'); return [year, String(month).padStart(2, '0'), String(day).padStart(2, '0')].join('-'); } function tradeRow({ region, dong, name, lot, area, floor, amount, date, cancelledOn = '', cancelled = false, complexId = '' }) { region = trimTradeField(region); dong = trimTradeField(dong); name = trimTradeField(name); lot = trimTradeField(lot); complexId = trimTradeField(complexId); if (!/^\d{5}$/.test(region) || !dong || !name || !(lot || complexId) || !Number.isInteger(area) || area <= 0 || !Number.isInteger(floor) || !Number.isSafeInteger(amount) || amount <= 0 || !/^\d{4}-\d{2}-\d{2}$/.test(date) || (cancelledOn && !/^\d{4}-\d{2}-\d{2}$/.test(cancelledOn))) throw Error('거래 행 형식 오류'); const group = [region, normalizeTradeField(dong), normalizeTradeField(name), normalizeTradeField(lot || complexId), area]; return { key: JSON.stringify([...group, date, floor, amount]), group: JSON.stringify(group), region, name, dong, lot, area, floor, amount, date, cancelled: Boolean(cancelled || cancelledOn), cancelledOn, }; } function isWatchedTrade(trade, target) { return target.region === trade.region && normalizeTradeField(target.dong) === normalizeTradeField(trade.dong) && normalizeTradeField(target.name) === normalizeTradeField(trade.name) && (!target.lot || normalizeTradeField(trade.lot) === normalizeTradeField(target.lot)) && (!target.area || trade.area === target.area); } function foldTradeHistory(events) { const state = new Map(); for (const event of events) state.set(event.row.key, event.row); return state; } function applyTradeSnapshot(history, snapshot, baseline) { const latest = foldTradeHistory(history), unique = new Map(), duplicates = new Set(), ambiguous = new Set(); for (const row of snapshot) { const existing = unique.get(row.key); if (existing) { // The public API does not identify individual transactions. An active // row and a cancellation with identical fields may be different deals. if (existing.cancelled !== row.cancelled || existing.cancelledOn !== row.cancelledOn) ambiguous.add(row.key); else duplicates.add(row.key); } else unique.set(row.key, row); } const counts = { baseline: 0, new: 0, duplicate: duplicates.size, cancel: 0, ambiguous: ambiguous.size }; const events = []; const known = new Map([...latest]); for (const row of unique.values()) { if (ambiguous.has(row.key)) continue; const previous = latest.get(row.key); if (!previous || (row.cancelled && !previous.cancelled)) known.set(row.key, row); } const comparable = new Map(); for (const candidate of known.values()) { if (candidate.cancelled || ambiguous.has(candidate.key)) continue; if (!comparable.has(candidate.group)) comparable.set(candidate.group, []); comparable.get(candidate.group).push(candidate); } for (const group of comparable.values()) group.sort((a, b) => b.date.localeCompare(a.date)); for (const row of [...unique.values()].sort((a, b) => a.date.localeCompare(b.date) || a.key.localeCompare(b.key))) { if (ambiguous.has(row.key)) continue; const previous = latest.get(row.key); const type = !previous ? (baseline || row.cancelled ? 'baseline' : 'new') : row.cancelled && !previous.cancelled ? 'cancel' : 'duplicate'; counts[type] += 1; if (type === 'duplicate') continue; const peers = row.cancelled ? [] : comparable.get(row.group) ?? []; const i = peers.findIndex(r => r.date < row.date); // No ordering claim for several rows on the same "previous" day. const delta = i >= 0 && peers[i].date !== peers[i + 1]?.date ? row.amount - peers[i].amount : null; events.push({ type, row, delta }); } return { events, counts, current: [...known.values()].sort((a, b) => b.date.localeCompare(a.date) || a.key.localeCompare(b.key)) }; } function sameTradeWatchScope(watch) { return JSON.stringify(watch.map(target => [target.region, normalizeTradeField(target.dong), normalizeTradeField(target.name), target.area, normalizeTradeField(target.lot)]) .map(x => JSON.stringify(x)).sort()); } function collectTradePages(getPage, { limit = 60 } = {}) { const rows = []; let target, expectedPageSize; for (let page = 1; page <= limit; page++) { const { total, pageSize, pageNumber, items } = getPage(page); if (!Number.isSafeInteger(total) || total < 0 || !Number.isSafeInteger(pageSize) || pageSize <= 0 || pageNumber !== page || (target !== undefined && (target !== total || expectedPageSize !== pageSize)) || items.length !== Math.min(pageSize, Math.max(0, total - (page - 1) * pageSize))) throw Error('공공데이터 페이지 응답이 일치하지 않습니다.'); target = total; expectedPageSize = pageSize; rows.push(...items); if (rows.length === target) return rows; } throw Error('한 번에 조회할 페이지 한도를 넘었습니다.'); } const TRADE_SCRIPT_ENDPOINT = 'https://apis.data.go.kr/1613000/RTMSDataSvcAptTradeDev/getRTMSDataSvcAptTradeDev'; const TRADE_SCRIPT_ZONE = 'Asia/Seoul'; const TRADE_SCRIPT_KIND = Object.freeze({ baseline: '초기 기록', new: '신규', cancel: '해제' }); function onOpen() { SpreadsheetApp.getUi().createMenu('실거래 알림') .addItem('지금 확인', 'tradeCheckNow').addItem('시험 메일 보내기', 'tradeTestMail') .addSeparator().addItem('매일 자동 켜기', 'tradeEnableDaily').addItem('매일 자동 끄기', 'tradeDisableDaily').addToUi(); } function tradeSettings_() { const props = PropertiesService.getScriptProperties(); const input = trimTradeField(props.getProperty('MOLIT_SERVICE_KEY')); let key; try { key = decodeURIComponent(input); } catch { throw Error('MOLIT_SERVICE_KEY의 형식을 확인하세요.'); } if (!key || !/^[a-z0-9+/_=-]+$/i.test(key)) throw Error('MOLIT_SERVICE_KEY를 스크립트 속성에 입력하세요.'); const recipient = trimTradeField(props.getProperty('ALERT_EMAIL')); if (!/^[^\s@,;<>()]+@[^\s@,;<>()]+\.[^\s@,;<>()]+$/.test(recipient)) throw Error('ALERT_EMAIL에 수신자 한 명만 입력하세요.'); return { key, recipient, props }; } function tradeWorkbook_() { const ss = SpreadsheetApp.getActiveSpreadsheet(); if (!ss) throw Error('Google 시트에 연결한 Apps Script에서 실행하세요.'); const sheets = {}; for (const [name, headers] of Object.entries(APARTMENT_TRADE_HEADERS)) { const sheet = ss.getSheetByName(name); if (!sheet || sheet.getRange(1, 1, 1, headers.length).getDisplayValues()[0].some((cell, i) => cell !== headers[i])) { throw Error('템플릿 탭과 첫 줄 제목을 원래대로 유지하세요: ' + name); } sheets[name] = sheet; } return sheets; } function tradeTime_() { return Utilities.formatDate(new Date(), TRADE_SCRIPT_ZONE, 'yyyy-MM-dd HH:mm:ss'); } function tradeSheetText_(value) { const s = String(value); return /^[\s\u0000-\u001f]*[=+\-@]/.test(s) ? "'" + s : s; } function tradeWatch_(sheet) { const last = sheet.getLastRow(); const rows = last < 2 ? [] : sheet.getRange(2, 1, last - 1, 5).getDisplayValues(); const watch = []; for (const [i, raw] of rows.entries()) { const [region, dong, name, area, lot] = raw.map(trimTradeField); if (![region, dong, name, area, lot].some(Boolean)) continue; if (!/^\d{5}$/.test(region) || !dong || !name || (area && (!/^\d{1,4}(?:\.\d{1,4})?$/.test(area) || Number(area) <= 0))) { throw Error('관심단지 ' + (i + 2) + '행의 지역코드·법정동명·단지명·전용면적을 확인하세요.'); } watch.push({ region, dong, name, area: area ? Math.round(Number(area) * 10000) : 0, lot }); } if (!watch.length || watch.length > 12 || new Set(watch.map(x => x.region)).size > 5) throw Error('관심단지는 1~12행, 지역코드는 최대 5개까지 등록하세요.'); return watch; } function tradeXmlPage_(xml) { let root; try { root = XmlService.parse(xml).getRootElement(); } catch { throw Error('공공데이터 응답이 XML이 아닙니다.'); } const header = root.getChild('header'); if (!header || !['000', '00'].includes(trimTradeField(header.getChildText('resultCode')))) { const code = trimTradeField(header?.getChildText('resultCode') || root.getChild('cmmMsgHeader')?.getChildText('returnReasonCode')); throw Error('공공데이터에서 조회 오류를 반환했습니다.' + (/^[0-9]{1,3}$/.test(code) ? ' 응답코드 ' + code : '')); } const body = root.getChild('body'); if (!body) throw Error('공공데이터에 결과 본문이 없습니다.'); const n = tag => { const raw = trimTradeField(body.getChildText(tag)); return /^\d+$/.test(raw) ? Number(raw) : NaN; }; return { total: n('totalCount'), pageSize: n('numOfRows'), pageNumber: n('pageNo'), items: body.getChild('items')?.getChildren('item') || [] }; } function tradeXmlRow_(item, region, month) { const field = tag => trimTradeField(item.getChildText(tag)); const area = field('excluUseAr'), floor = field('floor'), amount = field('dealAmount').replace(/[\s,]/g, ''); const date = tradeDate(Number(field('dealYear')), Number(field('dealMonth')), Number(field('dealDay'))); if (date.slice(0, 7).replace('-', '') !== month || (field('sggCd') && field('sggCd') !== region)) throw Error('요청 지역·계약월과 거래 응답이 다릅니다.'); if (!/^\d+(?:\.\d{1,4})?$/.test(area) || !/^-?\d+$/.test(floor) || !/^\d+$/.test(amount)) throw Error('거래 금액·면적·층 값의 형식이 바뀌었습니다.'); const rawDay = field('cdealDay').replace(/[.\-/\s]/g, ''); if (rawDay && !/^(?:\d{6}|\d{8})$/.test(rawDay)) throw Error('공공데이터 해제일 형식이 바뀌었습니다.'); const d = rawDay.length === 6 ? '20' + rawDay : rawDay; const cancelledOn = d ? tradeDate(Number(d.slice(0, 4)), Number(d.slice(4, 6)), Number(d.slice(6, 8))) : ''; const flag = field('cdealType'); return tradeRow({ region, dong: field('umdNm'), name: field('aptNm'), lot: field('jibun'), complexId: field('aptSeq'), area: Math.round(Number(area) * 10000), floor: Number(floor), amount: Number(amount), date, cancelledOn, cancelled: flag === 'O' || flag === 'Y' }); } function tradeFetch_(key, watch, months) { const bounds = Date.now() + 200000; let calls = 0; const snapshot = []; const regions = [...new Set(watch.map(x => x.region))]; for (const region of regions) { for (const month of months) { const xmlItems = collectTradePages(page => { if (++calls > 100 || Date.now() > bounds) throw Error('실행 조회 한도를 넘었습니다. 관심 지역을 줄인 뒤 다시 조회하세요.'); const url = TRADE_SCRIPT_ENDPOINT + '?serviceKey=' + encodeURIComponent(key) + '&LAWD_CD=' + region + '&DEAL_YMD=' + month + '&pageNo=' + page + '&numOfRows=1000'; let res; try { res = UrlFetchApp.fetch(url, { muteHttpExceptions: true, followRedirects: false, validateHttpsCertificates: true, escaping: false }); } catch { throw Error('공공데이터에 연결하지 못했습니다.'); } const status = res.getResponseCode(); if (status !== 200) throw Error('공공데이터 HTTP ' + status + (status === 403 ? ': 매매 상세 API 활용 승인과 키 설정을 확인하세요.' : '')); return tradeXmlPage_(res.getContentText()); }); for (const item of xmlItems) { if (!watch.some(w => w.region === region && normalizeTradeField(item.getChildText('umdNm')) === normalizeTradeField(w.dong) && normalizeTradeField(item.getChildText('aptNm')) === normalizeTradeField(w.name))) continue; const row = tradeXmlRow_(item, region, month); if (watch.some(w => isWatchedTrade(row, w))) snapshot.push(row); } } } return snapshot; } function tradeHistory_(sheet) { const n = sheet.getLastRow() - 1; if (n <= 0) return []; return sheet.getRange(2, 10, n, 2).getDisplayValues().map(([mail, raw], i) => { let event; try { event = JSON.parse(raw); if (!event?.row?.key || !Object.hasOwn(TRADE_SCRIPT_KIND, event.type) || !Object.values(APARTMENT_TRADE_MAIL).includes(mail)) throw Error(); } catch { throw Error('거래기록 ' + (i + 2) + '행의 원본 상태가 손상됐습니다. 백업본을 확인하세요.'); } return { event, mail, line: i + 2 }; }); } function tradeAppend_(sheet, events, now) { const first = sheet.getLastRow() + 1; const rows = events.map((event, i) => ({ event, line: first + i, mail: event.type === 'baseline' ? APARTMENT_TRADE_MAIL.none : APARTMENT_TRADE_MAIL.pending })); if (rows.length) { if (first + rows.length - 1 > sheet.getMaxRows()) sheet.insertRowsAfter(sheet.getMaxRows(), first + rows.length - 1 - sheet.getMaxRows()); sheet.getRange(first, 4, rows.length, 1).setNumberFormat('@'); sheet.getRange(first, 9, rows.length, 1).setNumberFormat('@'); sheet.getRange(first, 1, rows.length, 11).setValues(rows.map(({ event, mail }) => { const r = event.row; return [now, TRADE_SCRIPT_KIND[event.type], tradeSheetText_(r.name), r.date, r.area / 10000, r.floor, r.amount, event.delta ?? '', r.cancelledOn, mail, JSON.stringify(event)]; })); SpreadsheetApp.flush(); } return rows; } function tradePlainMail_(rows) { return rows.map(({ event: e }) => { const r = e.row; return TRADE_SCRIPT_KIND[e.type] + ' | ' + r.name + ' | 계약 ' + r.date + ' | ' + r.area / 10000 + '㎡ | ' + r.floor + '층 | ' + r.amount.toLocaleString('ko-KR') + '만원' + (r.cancelledOn ? ' | 해제일 ' + r.cancelledOn : '') + (e.delta === null ? '' : ' | 같은 전용면적의 앞선 거래 대비 ' + (e.delta > 0 ? '+' : '') + e.delta.toLocaleString('ko-KR') + '만원'); }).join('\n'); } function tradeSend_(sheet, recipient, items) { if (!items.length) return 0; if (MailApp.getRemainingDailyQuota() < 1) throw Error('오늘 메일 한도가 소진되어 대기 상태로 보관했습니다.'); const range = sheet.getRangeList(items.map(r => 'J' + r.line)); // If the send request is interrupted, Google might already have sent the // mail. Reserve the rows before asking it to send, to avoid automatic repeats. range.setValue(APARTMENT_TRADE_MAIL.ambiguous); SpreadsheetApp.flush(); try { MailApp.sendEmail(recipient, '[실거래 알림] 변경 ' + items.length + '건', '국토교통부에 공개된 매매 기록의 변경입니다.\n\n' + tradePlainMail_(items) + '\n\n거래 조건별 단순 비교이며 시세 산정이 아닙니다.'); } catch { throw Error('메일 발송 결과를 확인하지 못했습니다. 보낸편지함과 거래기록을 먼저 확인하세요.'); } range.setValue(APARTMENT_TRADE_MAIL.sent); SpreadsheetApp.flush(); return items.length; } function tradeRun_() { const lock = LockService.getScriptLock(); if (!lock.tryLock(1200)) throw Error('이미 다른 조회가 실행 중입니다.'); let log, counts = {}, delivered = 0, now = tradeTime_(); try { const sheets = tradeWorkbook_(), ledger = sheets['거래기록']; log = sheets['실행기록']; const { key, recipient, props } = tradeSettings_(); const watch = tradeWatch_(sheets['관심단지']), scope = sameTradeWatchScope(watch); const month = Utilities.formatDate(new Date(), TRADE_SCRIPT_ZONE, 'yyyyMM'); const history = tradeHistory_(ledger); const snapshot = tradeFetch_(key, watch, watchedMonths(month)); const result = applyTradeSnapshot(history.map(x => x.event), snapshot, props.getProperty('TRADE_WATCH_BASELINE') !== scope); counts = result.counts; const rows = tradeAppend_(ledger, result.events, now); props.setProperty('TRADE_WATCH_BASELINE', scope); const pending = [...history, ...rows].filter(x => x.mail === APARTMENT_TRADE_MAIL.pending); delivered = tradeSend_(ledger, recipient, pending.slice(0, 80)); const notes = [counts.ambiguous ? '같은 식별값의 상태 충돌 ' + counts.ambiguous + '건은 보류' : '', history.some(x => x.mail === APARTMENT_TRADE_MAIL.ambiguous) ? '이전 발송 여부 확인 필요' : '', pending.length > delivered ? '발송 대기 ' + (pending.length - delivered) + '건 남음' : ''].filter(Boolean); log.appendRow([now, '정상', counts.baseline, counts.new, counts.duplicate, counts.cancel, delivered, notes.join(' · ')]); return '초기 기록 ' + counts.baseline + ' · 신규 ' + counts.new + ' · 중복 ' + counts.duplicate + ' · 해제 ' + counts.cancel + ' · 발송 ' + delivered + (notes.length ? '\n' + notes.join(' · ') : ''); } catch (err) { // Underlying Google exceptions may contain URLs, recipients or credentials. const msg = /^(?:공공데이터|템플릿|관심단지|MOLIT_SERVICE_KEY|ALERT_EMAIL|거래기록|거래 금액|거래 행|계약일|요청 지역|한 번에 조회|실행 조회|오늘 메일|메일 발송)/.test(err?.message || '') ? err.message : '시트 또는 Google 서비스 실행 오류입니다.'; if (log) log.appendRow([now, '실패', counts.baseline ?? '', counts.new ?? '', counts.duplicate ?? '', counts.cancel ?? '', delivered, msg]); throw Error(msg); } finally { lock.releaseLock(); } } function tradeCheckNow() { tradeUi_(tradeRun_); } function tradeCheckDaily() { tradeRun_(); } function tradeUi_(fn) { const ui = SpreadsheetApp.getUi(); try { ui.alert(fn()); } catch (err) { ui.alert(err?.message === '이미 다른 조회가 실행 중입니다.' || /^(?:공공데이터|템플릿|관심단지|MOLIT_SERVICE_KEY|ALERT_EMAIL|거래기록|거래 금액|거래 행|계약일|요청 지역|한 번에 조회|실행 조회|오늘 메일|메일 발송|시트 또는 Google|먼저 지금 확인)/.test(err?.message || '') ? err.message : '설정 또는 Google 서비스 연결을 확인하세요.'); } } function tradeTestMail() { tradeUi_(() => { const { recipient } = tradeSettings_(); if (MailApp.getRemainingDailyQuota() < 1) throw Error('오늘 메일 한도가 소진됐습니다.'); MailApp.sendEmail(recipient, '[실거래 알림] 시험 메일', '사용자가 직접 요청한 시험입니다. 실제 거래 내역이나 API 키는 포함하지 않습니다.'); return '시험 메일을 보냈습니다. 받은편지함 또는 스팸함을 확인하세요.'; }); } function tradeChangeDaily_(enable) { const lock = LockService.getScriptLock(); if (!lock.tryLock(1200)) throw Error('이미 다른 조회가 실행 중입니다.'); try { if (enable) { const { props } = tradeSettings_(); if (props.getProperty('TRADE_WATCH_BASELINE') !== sameTradeWatchScope(tradeWatch_(tradeWorkbook_()['관심단지']))) { throw Error('먼저 지금 확인으로 현재 관심단지의 첫 수집을 실행하세요.'); } } const existing = ScriptApp.getProjectTriggers().filter(t => t.getHandlerFunction() === 'tradeCheckDaily'); if (!enable) { existing.forEach(t => ScriptApp.deleteTrigger(t)); return '내 계정의 자동 조회를 껐습니다.'; } if (existing.length) { existing.slice(1).forEach(t => ScriptApp.deleteTrigger(t)); return '내 계정의 기존 일일 조회를 유지합니다.'; } ScriptApp.newTrigger('tradeCheckDaily').timeBased().atHour(9).everyDays(1).inTimezone(TRADE_SCRIPT_ZONE).create(); return '매일 한국 시간 오전 9~10시 사이에 조회합니다.'; } finally { lock.releaseLock(); } } function tradeEnableDaily() { tradeUi_(() => tradeChangeDaily_(true)); } function tradeDisableDaily() { tradeUi_(() => tradeChangeDaily_(false)); }