PageSourceSearch

https://siranui.io/static/js/budget-allocator.js?v=288

js siranui.io collected 2026-09-24 15:04:26 UTC 118,040 bytes, 1 lines download raw bytes

1function checkBudgetAgentContract(){const t=document.getElementById("budget-agent-uncontracted-warning"),e=document.getElementById("btn-budget-simulate"),n=document.getElementById("btn-apply-prompt"),a=document.getElementById("btn-allocator-right-apply-prompt"),o=document.getElementById("btn-reset"),i=document.getElementById("btn-export"),r=document.getElementById("btn-calendar-save"),l=document.getElementById("config-form");let c=!0;if("function"==typeof window.isAgentContracted)c=window.isAgentContracted("bidding");else{const t=window.customerId||localStorage.getItem("siranui_auth_customer_id")||"mock-mode",e=localStorage.getItem("siranui_selected_agents_"+t);if(e)try{c=new Set(JSON.parse(e)).has("bidding")}catch(t){c=!1}else c=!1}const d=[e,n,a,o,i,r];c?(t&&(t.style.display="none"),d.forEach(t=>{t&&(t.disabled=!1,t.style.opacity="1",t.style.cursor="",t.style.pointerEvents="auto")}),l&&l.querySelectorAll("input, select, textarea").forEach(t=>{t.disabled=!1,t.style.pointerEvents="auto",t.style.opacity="1"})):(t&&(t.style.display="flex"),d.forEach(t=>{t&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none")}),l&&l.querySelectorAll("input, select, textarea").forEach(t=>{t.disabled=!0,t.style.pointerEvents="none",t.style.opacity="0.7"}))}document.addEventListener("DOMContentLoaded",()=>{let t=null,e=null,n="total",a="cumulative",o="bidding",i=1,r="all",l="all",c={},d=null;const s=new Map;let u=[],m="",p=null,g=null,f=[],y=null;function _(t,e){const n=String(t||"").trim();if(!n)return"";const a=n.replace("T"," ").replace(/\//g,"-").match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);if(a)return`${a[1]}-${String(a[2]).padStart(2,"0")}-${String(a[3]).padStart(2,"0")}`;const o=n.match(/^(\d{4})(\d{2})(\d{2})(?:\D|$)/);if(o)return`${o[1]}-${o[2]}-${o[3]}`;const i=n.match(/^(\d{1,2})[\/\-](\d{1,2})/);return i?`${Number.isFinite(e)?e:(new Date).getFullYear()}-${String(i[1]).padStart(2,"0")}-${String(i[2]).padStart(2,"0")}`:n.length>=10?n.slice(0,10):""}function h(t){const e=new Set;return(t=>{const n=String(t||"").trim();if(!n)return;e.add(n);const a=n.match(/^\d+_(\d+)$/);a&&e.add(a[1]);const o=n.match(/^(\d+)$/);o&&e.add(o[1])})(t),e}function b(t){const e=String(t||"");return e.includes("エージェント")||"手動承認"===e||"オプティマイザ記録"===e||/siranui|予算配分/i.test(e)}const w={google:"Google",yahoo:"Yahoo",microsoft:"Microsoft",facebook:"Meta"},v={google:"#4285F4",yahoo:"#FF0033",microsoft:"#00A4EF",facebook:"#1877F2"},C=["google","yahoo","microsoft","facebook"],E={};function $(t){return"function"==typeof window.getMediaPlatformIcon?window.getMediaPlatformIcon(t):window.MEDIA_PLATFORM_ICONS&&window.MEDIA_PLATFORM_ICONS[t]||null}function x(e){if(!e)return null;if(E[e])return E[e];const n=$(e);if(!n)return null;const a=new Image;return a.decoding="async",a.src=n,a.onload=()=>{if(t)try{t.draw()}catch(t){}},E[e]=a,a}function S(t){const e=String(t&&(t.platform||t.media||t._platform)||"").trim().toLowerCase();return"google"===e||"yahoo"===e||"microsoft"===e||"facebook"===e?e:""}function I(){const t=document.querySelectorAll("#detail-table thead th");return t&&t.length>0?t.length:11}function A(){const t=document.getElementById("detail-table");return t?t.closest(".table-container"):null}function L(){const t=A();if(!t)return;const e=t.querySelector(".sim-progress-table-overlay");e&&(e.classList.add("hidden"),e.setAttribute("aria-hidden","true"))}function k(t,e){return window.SimulationFetch&&window.SimulationFetch.SimulationProgress?window.SimulationFetch.SimulationProgress.buildInlineLoadingHtml(e,t):`<tr><td colspan="${t}" class="text-center text-muted" style="padding: 28px 12px;">\n            <div style="display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; min-height:72px; width:100%;">\n                <div class="spinner" style="margin: 0 0 10px;"></div>\n                <div>${e}</div>\n            </div>\n        </td></tr>`}function F(t){!function(t){const e=A();if(!e)return;const n=t||"シミュレーション準備中";let a=e.querySelector(".sim-progress-table-overlay");a||(a=document.createElement("div"),a.className="sim-progress-table-overlay",e.appendChild(a)),a.innerHTML=`\n            <div class="sim-progress-inline-content">\n                <div class="spinner" style="margin: 0 auto 10px;"></div>\n                <div><span data-sim-progress-inline-label>${n}</span> <strong data-sim-progress-inline-pct>3%</strong></div>\n                <div class="sim-progress-inline-track" aria-hidden="true"><div class="sim-progress-inline-fill" style="width:3%"></div></div>\n                <div style="font-size:0.72rem; opacity:0.85;" data-sim-progress-inline-elapsed>経過 0秒</div>\n            </div>\n        `,a.classList.remove("hidden"),a.setAttribute("aria-hidden","false"),ft&&(ft.innerHTML=`<tr><td colspan="${I()}" style="height:160px; border:none;"></td></tr>`)}(t||"シミュレーション準備中")}function B(t,e,n={}){const a=window.SimulationFetch&&window.SimulationFetch.beginSimulationProgress,o=window.SimulationFetch&&window.SimulationFetch.SimulationProgress;if(!o)return;const i={targets:["allocator-simulation-progress"],label:t||"シミュレーション取得中...",retry:Boolean(e)};null!=n.jobProgressPct&&Number.isFinite(Number(n.jobProgressPct))&&(i.jobProgressPct=Number(n.jobProgressPct)),a?a(i):o.isActive&&o.isActive()?o.attach(i):o.start(i)}function D(t,e){L();const n=window.SimulationFetch&&window.SimulationFetch.SimulationProgress;
1n&&(t?n.finish({label:e||"完了"}):n.fail({label:e||"取得に失敗しました"}))}function M(t){const e=String(t||"").split("-");if(2!==e.length)return t||"";const n=Number(e[0]),a=Number(e[1]);return Number.isFinite(n)&&Number.isFinite(a)?`${n}年${a}月`:t}function N(t){const e=t?`/api/allocation/month_view?month=${encodeURIComponent(t)}`:"/api/allocation/month_view";return"function"==typeof window.buildAgentApiUrl?window.buildAgentApiUrl(e,{platform:Kt()}):"function"==typeof window.appendAgentApiParams?window.appendAgentApiParams(e,{platform:Kt()}):e}function T(t,e){const n=document.getElementById("allocator-prior-month-banner"),a=document.getElementById("allocator-archive-view-bar"),o=document.getElementById("allocator-archive-view-label"),i=document.getElementById("config-form"),r=document.querySelector("#tab-budget-optimizer .config-panel");a&&a.classList.toggle("hidden",!t),o&&t&&(o.textContent=`${M(e)}の配分結果を表示中です(保存済みスナップショット・参照のみ)。`),n&&n.classList.toggle("hidden",t||!g?.available),i&&i.querySelectorAll("input, select, textarea, button").forEach(e=>{"btn-reset"!==e.id&&(e.disabled=!!t)}),r&&(r.style.opacity=t?"0.72":"")}window.setAllocatorChartChangeHistory=function(t){f=Array.isArray(t)?t:[],e&&Ee(e,{skipLoadingOverlay:!0})};const P=document.getElementById("allocator-view-prior-month-btn");P&&P.addEventListener("click",()=>{!async function(t){const e=t||g?.previous_month;if(e)try{const t=await fetch(N(e)),n=await t.json();if(!t.ok||"ok"!==n.status||!n.view)throw new Error(n.message||"前月データの取得に失敗しました");p=e;const a=n.view,o=a.rules||{};d={total_client_budget:o.total_client_budget,additional_budgets:o.additional_budgets||[],platforms:o.platforms||{}},function(t){if(!t)return;const e=(t,e)=>{const n=document.getElementById(t);n&&(n.value=e)};e("total_client_budget",t.total_client_budget??0);const n=t.platforms?.google||{};e("margin_rate",null!=n.margin_rate?displayInt(100*n.margin_rate):20),e("margin_type",n.margin_type||"net");const a=t.platforms?.yahoo||{};e("yahoo_margin_rate",null!=a.margin_rate?displayInt(100*a.margin_rate):20),e("yahoo_margin_type",a.margin_type||"net");const o=t.platforms?.microsoft||{};e("ms_margin_rate",null!=o.margin_rate?displayInt(100*o.margin_rate):20),e("ms_margin_type",o.margin_type||"net");const i=t.platforms?.amazon||{};e("amazon_margin_rate",null!=i.margin_rate?displayInt(100*i.margin_rate):20),e("amazon_margin_type",i.margin_type||"net");const r=t.platforms?.facebook||{};e("facebook_margin_rate",null!=r.margin_rate?displayInt(100*r.margin_rate):0),e("facebook_margin_type",r.margin_type||"net"),qt(Ot(t))}(o),_e({summary:a.summary||{},daily_records:a.daily_records||[],campaign_metadata:a.campaign_metadata||{},is_archive_view:!0,archive_month:e},!0),T(!0,e)}catch(t){"function"==typeof window.showPremiumToast?window.showPremiumToast(t.message||"前月の配分結果を開けませんでした","error"):alert(t.message||"前月の配分結果を開けませんでした")}}(g?.previous_month)});const O=document.getElementById("allocator-return-current-month-btn");function q(){return"function"==typeof window.resolveActiveAccountGroupId?window.resolveActiveAccountGroupId():window.selectedAccountGroupId||localStorage.getItem("siranui_active_account_group_id")||""}O&&O.addEventListener("click",()=>{p&&(p=null,T(!1),se())});
1const z=["2026-01-01","2026-01-12","2026-02-11","2026-02-23","2026-03-20","2026-04-29","2026-05-03","2026-05-04","2026-05-05","2026-05-06","2026-07-20","2026-08-11","2026-09-21","2026-09-22","2026-10-12","2026-11-03","2026-11-23"];function H(t){return["日","月","火","水","木","金","土"][new Date(t).getDay()]}function j(t){const e=new Date(t).getDay(),n=6===e,a=0===e,o=z.includes(t);return{isSat:n,isSunOrHoliday:a||o}}function R(t,e,n,a){const o=document.getElementById(`alloc-inputs-${t}`);if(!o)return;let i="";if("fixed"===e){const e=a&&a.fixed_value||0,n=document.getElementById("agency_mode")?.checked?"固定月予算(クライアント)":"固定月予算(ネット)";i+=`<input type="number" id="alloc-val-${t}" value="${e}" placeholder="${n}" title="${n}" style="margin-top: 4px; width: 100%;">`}if(n&&"equal"!==n){let e=50;a&&void 0!==a.boost_weight&&(e=Math.min(50,Math.max(0,displayInt(100*(a.boost_weight-1))))),i+=`\n                <div class="slider-container" style="margin-top: 4px; display: flex; align-items: center; gap: 8px; width: 100%;">\n                    <input type="range" id="alloc-range-${t}" min="0" max="50" step="5" value="${e}" oninput="document.getElementById('alloc-range-text-${t}').textContent = '+' + this.value + '%'" style="flex: 1;">\n                    <span id="alloc-range-text-${t}" style="font-size: 0.75rem; min-width: 32px;">+${e}%</span>\n                </div>\n            `}o.innerHTML=i||'<div style="color: var(--text-secondary); font-size: 0.75rem; padding-top: 4px;">--</div>'}let G=[],V=2026,W=8,U="delivery",Y=null;function J(){const t=String(p||"").trim().match(/^(\d{4})-(\d{1,2})$/);if(t)return{year:Number(t[1]),month:Number(t[2])};const n=e&&e.summary&&e.summary.run_date||"",a=String(n).match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);if(a)return{year:Number(a[1]),month:Number(a[2])};try{const t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Tokyo",year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),e=e=>Number((t.find(t=>t.type===e)||{}).value);return{year:e("year"),month:e("month")}}catch(t){const e=new Date;return{year:e.getFullYear(),month:e.getMonth()+1}}}function X(t){const e=String(t||"").match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);return e?`${e[1]}/${String(e[2]).padStart(2,"0")}/${String(e[3]).padStart(2,"0")}`:"日付を選択"}function Z(t){const e=document.getElementById("calendar-modal");if(!e)return;const n=document.getElementById("btn-calendar-select-all"),a=document.getElementById("btn-calendar-clear"),o=document.getElementById("btn-calendar-save"),i=e.querySelector(".calendar-picker-hint"),r="single"===t;n&&(n.style.display=r?"none":""),a&&(a.style.display=r?"none":""),o&&(o.style.display=r?"none":"",o.textContent="保存"),i&&(i.textContent=r?"日付を1つ選ぶと反映されます。":"配信を行いたい日付を選択(トグル)してください。選択された日のみ予算が配分され、それ以外の日は0円になります。")}function K(t,e){const n=document.getElementById("calendar-modal"),a=document.getElementById("calendar-camp-id"),o=n.querySelector(".modal-header h2")||n.querySelector("h2");U="delivery",Y=null,Z("delivery"),o&&(o.textContent=`📅 配信日カスタム選択 - ${e}`),a.value=t,G=[...c[t]||[]];const{year:i,month:r}=J();V=i,W=r,et(i,r),n.classList.remove("hidden"),n.style.display="flex"}function Q(t,e,n){const a=document.getElementById("calendar-modal");if(!a||!t)return;const o=a.querySelector(".modal-header h2")||a.querySelector("h2"),i=document.getElementById("calendar-camp-id");U="single",Y={input:t,display:e||null},Z("single"),o&&(o.textContent=n||"📅 日付を選択"),i&&(i.value="");const r=function(t){const e=String(t||"").match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);return e?{year:Number(e[1]),month:Number(e[2])}:null}(t.value),l=J();V=r&&r.year||l.year,W=r&&r.month||l.month,G=t.value?[t.value]:[],et(V,W),a.classList.remove("hidden"),a.style.display="flex"}function tt(t){if(!Y||!Y.input)return;Y.input.value=t,Y.display&&(Y.display.textContent=X(t));const e=document.getElementById("calendar-modal");e&&(e.classList.add("hidden"),e.style.display="none"),Y=null,U="delivery"}function et(t,e){const n=document.querySelector(".calendar-grid-container");if(!n)return;const a=document.getElementById("calendar-month-name");a&&(a.textContent=`${t}年 ${e}月`),n.innerHTML='\n            <div style="color: #ef4444; font-weight: bold; padding: 4px 0;">日</div>\n            <div style="color: var(--text-secondary); font-weight: bold; padding: 4px 0;">月</div>\n            <div style="color: var(--text-secondary); font-weight: bold; padding: 4px 0;">火</div>\n            <div style="color: var(--text-secondary); font-weight: bold; padding: 4px 0;">水</div>\n            <div style="color: var(--text-secondary); font-weight: bold; padding: 4px 0;">木</div>\n            <div style="color: var(--text-secondary); font-weight: bold; padding: 4px 0;">金</div>\n            <div style="color: #3b82f6; font-weight: bold; padding: 4px 0;">土</div>\n        ';const o=new Date(t,e-1,1).getDay(),i=new Date(t,e,0).getDate();for(let t=0;t<o;t++){const t=document.createElement("div");
1t.className="calendar-day-cell empty-cell",n.appendChild(t)}for(let a=1;a<=i;a++){const o=document.createElement("div");o.className="calendar-day-cell",o.textContent=a;const i=`${t}-${String(e).padStart(2,"0")}-${String(a).padStart(2,"0")}`;o.dataset.date=i;const{isSat:r,isSunOrHoliday:l}=j(i);r&&o.classList.add("sat-day"),l&&o.classList.add("sun-holiday-day"),(G.includes(i)||G.includes(String(a))||G.includes(a))&&o.classList.add("active-day"),o.addEventListener("click",()=>{"single"!==U?o.classList.contains("active-day")?(o.classList.remove("active-day"),G=G.filter(t=>t!==i&&String(t)!==String(a))):(o.classList.add("active-day"),G.push(i)):tt(i)}),n.appendChild(o)}}function nt(){const t=document.getElementById("detail-camp-select");if(!t)return;t.innerHTML="";const a=document.createElement("button");if(a.className="camp-filter-btn"+("all"===l?" active":""),a.dataset.campId="all",a.textContent="すべて",a.addEventListener("click",()=>at("all")),t.appendChild(a),!e||window.isBlendedMediaTab(n))return;const o=e.daily_records[0];if(!o||!o.campaigns)return;const i=[];if(Object.entries(o.campaigns).forEach(([t,e])=>
1{if(e.platform===n){if("yahoo"===n&&!ue(e))return;"all"!==r&&e.product_type!==r||i.push({id:t,name:e.campaign_name})}}),i.forEach(e=>{const n=document.createElement("button");n.className="camp-filter-btn"+(e.id===l?" active":""),n.dataset.campId=e.id,n.textContent=e.name,n.addEventListener("click",()=>at(e.id)),t.appendChild(n)}),!i.some(t=>t.id===l)&&"all"!==l){l="all";const e=t.querySelector('.camp-filter-btn[data-camp-id="all"]');e&&e.classList.add("active")}}function at(t){l=t;const n=document.getElementById("detail-camp-select");n&&n.querySelectorAll(".camp-filter-btn").forEach(e=>{e.dataset.campId===t?e.classList.add("active"):e.classList.remove("active")}),e&&(Se(e.daily_records,e.summary.run_date,{deferClear:!0}),Ee(e,{skipLoadingOverlay:!0}))}!function(){const t=document.getElementById("btn-close-calendar"),e=document.getElementById("btn-calendar-save"),n=document.getElementById("btn-calendar-select-all"),a=document.getElementById("btn-calendar-clear"),o=document.getElementById("calendar-modal");t&&t.addEventListener("click",()=>{o.classList.add("hidden"),o.style.display="none",Y=null,U="delivery"}),n&&n.addEventListener("click",()=>{if("single"===U)return;G=[];const t=new Date(V,W,0).getDate();for(let e=1;e<=t;e++)G.push(`${V}-${String(W).padStart(2,"0")}-${String(e).padStart(2,"0")}`);document.querySelectorAll(".calendar-day-cell:not(.empty-cell)").forEach(t=>{t.classList.add("active-day")})}),a&&a.addEventListener("click",()=>{"single"!==U&&(G=[],document.querySelectorAll(".calendar-day-cell:not(.empty-cell)").forEach(t=>{t.classList.remove("active-day")}))}),e&&e.addEventListener("click",()=>{if("single"===U)return;const t=document.getElementById("calendar-camp-id").value;c[t]=[...G];const e=document.getElementById(`btn-calendar-trigger-${t}`);e&&(e.textContent=`設定 (${G.length}日)`),we(t),o.classList.add("hidden"),o.style.display="none"});const i=document.getElementById("btn-calendar-prev-month"),r=document.getElementById("btn-calendar-next-month"),l=t=>{let e=V,n=W+t;for(;n<1;)n+=12,e-=1;for(;n>12;)n-=12,e+=1;V=e,W=n,et(e,n)};i&&i.addEventListener("click",()=>l(-1)),r&&r.addEventListener("click",()=>l(1))}(),isLoggedIn="true"===localStorage.getItem("siranui_auth_logged_in");const ot=document.getElementById("config-form"),it=document.getElementById("btn-reset"),rt=document.getElementById("btn-export"),lt=document.getElementById("btn-apply-prompt"),ct=document.getElementById("ai-prompt-input"),dt=document.getElementById("product-filters"),st=(document.getElementById("siranui-auth-panel"),document.getElementById("google-login-modal"),document.getElementById("kpi-total-budget")),ut=document.getElementById("kpi-spent"),mt=document.getElementById("kpi-spent-sub"),pt=document.getElementById("kpi-forecast"),gt=document.getElementById("kpi-forecast-diff"),ft=document.querySelector("#detail-table tbody");function yt(){const t=document.querySelector(".daily-detail-media-tabs");if(!t)return;const e=q(),n=(window.accountGroups||[]).find(t=>t.id===e)||null,a="function"==typeof window.isSingleAccountWorkspaceScope&&window.isSingleAccountWorkspaceScope();t.querySelectorAll(".tab-btn[data-tab]").forEach(t=>{const e=t.dataset.tab;if("total"===e)return void t.classList.remove("disabled");let o=!0;a&&window.activeAccountOverride&&window.activeAccountOverride.platform?o=window.activeAccountOverride.platform===e:n&&(o=Zt(n,e)),t.classList.toggle("disabled",!o)})}function _t(t,a={}){const o=document.querySelector(".daily-detail-media-tabs");if(!o)return!1;const i=String(t||"total").trim().toLowerCase(),c=o.querySelector(`.tab-btn[data-tab="${i}"]`);if("total"!==i&&c&&c.classList.contains("disabled"))return!1;o.querySelectorAll(".tab-btn").forEach(t=>t.classList.remove("active"));const d=c||o.querySelector('.tab-btn[data-tab="total"]');return d&&d.classList.add("active"),n=d&&d.dataset.tab||"total","total"!==n?dt.style.display="flex":(dt.style.display="none",r="all",document.querySelectorAll(".prod-filter-btn").forEach(t=>{t.classList.remove("active"),"all"===t.dataset.prod&&t.classList.add("active")})),a.keepCampaignFilter||(l="all"),nt(),!a.skipTableUpdate&&e&&(Se(e.daily_records,e.summary.run_date,{deferClear:!0}),Ee(e,{skipLoadingOverlay:!0})),!0}window.syncDailyDetailMediaTabsVisibility=yt,window.setDailyDetailMediaTab=_t,document.querySelectorAll(".daily-detail-media-tabs .tab-btn").forEach(t=>{t.addEventListener("click",()=>{if(t.classList.contains("disabled"))return;const e=t.dataset.tab;if("total"===e)return _t("total"),void("function"==typeof window.loadAllocatorChangeHistory&&window.loadAllocatorChangeHistory(null,{allPlatforms:!0}));Xt(e)})});const ht=document.querySelectorAll(".chart-toggle-btn");ht.forEach(t=>{t.addEventListener("click",n=>{ht.forEach(t=>t.classList.remove("active")),t.classList.add("active"),a=t.dataset.chartMode,e&&Ee(e,{skipLoadingOverlay:!0})})});const bt=document.querySelectorAll(".cv-mode-btn");function wt(t,e=!1,n="cv"){if(e)return'<span class="text-muted">--</span>';if(null==t||""===t)return'<span class="text-muted">--</span>';const a=parseFloat(t);return Number.isFinite(a)?"cvv"===n?"function"==typeof window.formatDisplayCurrency?formatDisplayCurrency(a):Math.round(a).toLocaleStr
1ing():"function"==typeof window.formatCvValue?window.formatCvValue(a):Math.round(a).toLocaleString():'<span class="text-muted">--</span>'}function vt(t){if(!t)return null;const e=t.strategy_metric_family;if("cpa"===e||"roas"===e)return e;const n=String(t.strategy||t.strategy_type_key||"").toUpperCase();return"MAXIMIZE_CONVERSION_VALUE"===n||"TARGET_ROAS"===n||"MAXCVV"===n||"TROAS"===n?"roas":"MAXIMIZE_CONVERSIONS"===n||"TARGET_CPA"===n||"MAXCV"===n||"TCPA"===n?"cpa":parseFloat(t.platform_target_roas)>0?"roas":parseFloat(t.target_cpa)>0?"cpa":null}function Ct(t){const e=function(t){if(!t)return 0;const e=parseFloat(t.actual_cv);return Number.isFinite(e)?e:0}(t);return"final"!==o?e:null!=t.actual_final_cv?parseFloat(t.actual_final_cv)||0:"function"==typeof window.scaleFinalCvValue?window.scaleFinalCvValue(e,i):e}function Et(t){const e=function(t){if(!t)return 0;const e=parseFloat(t.forecast_cv);return Number.isFinite(e)?e:0}(t);return"final"!==o?e:null!=t.forecast_final_cv?parseFloat(t.forecast_final_cv)||0:"function"==typeof window.scaleFinalCvValue?window.scaleFinalCvValue(e,i):e}function $t(t){const e=function(t){if(!t)return 0;const e=parseFloat(t.actual_cvv);return Number.isFinite(e)?e:0}(t);return"final"!==o?e:null!=t.actual_final_cvv?parseFloat(t.actual_final_cvv)||0:"function"==typeof window.scaleFinalCvValue?window.scaleFinalCvValue(e,i):e}function xt(t){const e=function(t){if(!t)return 0;const e=parseFloat(t.forecast_cvv);return Number.isFinite(e)?e:0}(t);return"final"!==o?e:null!=t.forecast_final_cvv?parseFloat(t.forecast_final_cvv)||0:"function"==typeof window.scaleFinalCvValue?window.scaleFinalCvValue(e,i):e}function St(t){if(!t)return'<span class="text-muted">--</span>';const e=vt(t),n=parseFloat(t.filtered_actual_cpa||t.base_actual_cpa||t.target_cpa||0),a=parseFloat(t.decision_actual_roas||t.base_actual_roas||t.platform_target_roas||t.reference_roas||0),o=n>0?formatDisplayCurrency(n):"--",i=function(t){const e=parseFloat(t);return!Number.isFinite(e)||e<=0?"--":e.toFixed(2)}(a);return"roas"===e?`<span style="font-weight:600">ROAS ${i}</span> / CPA ${o}`:`<span style="font-weight:600">CPA ${o}</span> / ROAS ${i}`}function It(t,e,n,a){const i=t.date<e,r=t.campaigns||{},l=n&&n.length?n:Object.keys(r);if(!n||!n.length){const n=function(t,e,n){const a=t.date<e,i="final"===o;if("actual"===n){if(!a)return null;const e=i?t.actual_final_cvv:t.actual_bidding_cvv;if(null==e)return null;const n=parseFloat(e);return Number.isFinite(n)?n:null}const r=i?t.forecast_final_cvv:t.forecast_bidding_cvv;if(null==r)return null;const l=parseFloat(r);return Number.isFinite(l)?l:0}(t,e,a);if(null!=n)return n}if("actual"===a){if(!i)return null;let t=0;return l.forEach(e=>{const n=r[e];n&&(t+=$t(n)||0)}),t}let c=0;return l.forEach(t=>{const e=r[t];e&&(c+=xt(e)||0)}),c}function At(t,e){if(e&&1===e.length&&t.length){const n=vt(t[0].campaigns?.[e[0]]||{}),a="roas"===n?"cvv":"cv";return{mode:a,metricLabel:"cvv"===a?"CVV":"CV",cpaCost:"cpa"===n?1:0,roasCost:"roas"===n?1:0}}let n=0,a=0;const o=new Set;t.forEach(t=>{Object.entries(t.campaigns||{}).forEach(([t,i])=>{if(e&&e.length&&!e.includes(t))return;if(o.has(t))return;o.add(t);const r=parseFloat(i.last_month_cost)||parseFloat(i.forecast_media)||parseFloat(i.plan_media)||0;"roas"===vt(i)?a+=r:n+=r})});const i=a>=n?"cvv":"cv";return{mode:i,metricLabel:"cvv"===i?"CVV":"CV",cpaCost:n,roasCost:a}}function Lt(t,e,n,a){const i=t.date<e,r=t.campaigns||{},l=n&&n.length?n:Object.keys(r);if(!n||!n.length){const n=function(t,e,n){const a=t.date<e,i="final"===o;if("actual"===n){if(!a)return null;const e=i?t.actual_final_cv:t.actual_bidding_cv;if(null==e)return null;const n=parseFloat(e);return Number.isFinite(n)?n:null}const r=i?t.forecast_final_cv:t.forecast_bidding_cv;if(null==r)return null;const l=parseFloat(r);return Number.isFinite(l)?l:0}(t,e,a);if(null!=n)return n}if("actual"===a){if(!i)return null;let t=0;return l.forEach(e=>{const n=r[e];n&&(t+=Ct(n)||0)}),t}let c=0;return l.forEach(t=>{const e=r[t];e&&(c+=Et(e)||0)}),c}function kt(t,e,n,a,o){return"cvv"===o?It(t,e,n,a):Lt(t,e,n,a)}function Ft(t,e,n){const a="actual"===e;return"cvv"===n?a?$t(t):xt(t):a?Ct(t):Et(t)}function Bt(t){if(!t||!t.length||window.isBlendedMediaTab(n))return null;const e=t[0],a=[];return Object.entries(e.campaigns||{}
1).forEach(([t,e])=>{if(e.platform===n){if("yahoo"===n&&!ue(e))return;"all"!==r&&e.product_type!==r||"all"!==l&&t!==l||a.push(t)}}),a}bt.forEach(t=>{t.addEventListener("click",()=>{bt.forEach(t=>{t.classList.remove("active"),t.style.background="transparent",t.style.color="var(--text-secondary)"}),t.classList.add("active"),t.style.background="var(--primary)",t.style.color="#fff",o=t.dataset.cvMode||"bidding",e&&(ye(e.summary),Se(e.daily_records,e.summary.run_date,{deferClear:!0}),Ee(e,{skipLoadingOverlay:!0}))})});const Dt=document.querySelectorAll(".prod-filter-btn");async function Mt(t,n,a,o,i){if(t){n.disabled=!0,n.textContent="siranui AI が解析中...",de("user",t);try{const n={prompt:t,config:d,simulation_summary:e?e.summary:null};if(e){const t=e.campaign_metadata||(e.daily_records&&e.daily_records[0]?e.daily_records[0].campaigns:{});t&&(n.campaigns=Object.entries(t).map(([t,e])=>({campaign_id:String(t),campaign_name:e.campaign_name||e.name||"",platform:e.platform||"google"})))}const i=await fetch("/api/parse_prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(i.ok){const t=await i.json();if(de("ai",t.answer||"指示を解析しました。"),"config"===t.mode){t.total_client_budget&&(document.getElementById("total_client_budget").value=t.total_client_budget),void 0!==t.additional_budgets&&(d||(d={}),d.additional_budgets=t.additional_budgets||[],le()),t.campaign_configs&&Object.entries(t.campaign_configs).forEach(([t,e])=>{const n=document.getElementById(`alloc-type-${t}`),a=document.getElementById(`dist-type-${t}`),o=document.getElementById(`delivery-cond-${t}`),i=document.getElementById(`btn-calendar-trigger-${t}`);if(n&&a){let o=e.allocation_type||"auto",i=e.distribution_type||"equal";o.startsWith("boost")&&(i=o,o="auto"),n.value=o,a.value=i,R(t,o,i,e)}o&&(e.delivery_condition&&(o.value=e.delivery_condition,i&&(i.style.display="custom"===e.delivery_condition?"inline-block":"none")),e.delivery_days&&(c[t]=e.delivery_days,i&&(i.textContent=`設定 (${e.delivery_days.length}日)`)))}),a.innerHTML="",o.innerHTML="";let e=!1;if(t.warnings&&t.warnings.length>0){e=!0;const n=document.createElement("h4");n.textContent="⚠️ 構成の矛盾・懸念点",a.appendChild(n);const o=document.createElement("ul");
1t.warnings.forEach(t=>{const e=document.createElement("li");e.textContent=t,o.appendChild(e)}),a.appendChild(o)}if(t.suggestions&&t.suggestions.length>0){e=!0;const n=document.createElement("h4");n.textContent="💡 運用・媒体特性への提案",o.appendChild(n);const a=document.createElement("ul");t.suggestions.forEach(t=>{const e=document.createElement("li");e.textContent=t,a.appendChild(e)}),o.appendChild(a)}((t,e,n)=>{const a=["ai-feedback-container","allocator-right-ai-feedback-container"],o=["ai-warnings","allocator-right-ai-warnings"],i=["ai-suggestions","allocator-right-ai-suggestions"];for(let r=0;r<2;r++){const l=document.getElementById(a[r]),c=document.getElementById(o[r]),d=document.getElementById(i[r]);l&&c&&d&&(c.innerHTML=t,d.innerHTML=e,l.style.display=n?"block":"none","ai-feedback-container"===a[r]&&(l.style.display=n?"flex":"none",l.style.flexDirection="column"))}})(a.innerHTML,o.innerHTML,e),[document.getElementById("ai-prompt-input"),document.getElementById("allocator-right-ai-prompt-input")].forEach(t=>{t&&(t.value="")}
1),ot.dispatchEvent(new Event("submit"))}else["ai-feedback-container","allocator-right-ai-feedback-container"].forEach(t=>{const e=document.getElementById(t);e&&(e.style.display="none")}),[document.getElementById("ai-prompt-input"),document.getElementById("allocator-right-ai-prompt-input")].forEach(t=>{t&&(t.value="")})}else alert("指示の解析に失敗しました。")}catch(t){alert("エラーが発生しました: "+t.message)}finally{n.disabled=!1}}else alert("siranui AI への配分指示を入力してください。")}Dt.forEach(t=>{t.addEventListener("click",n=>{Dt.forEach(t=>t.classList.remove("active")),t.classList.add("active"),r=t.dataset.prod,l="all",nt(),e&&(Se(e.daily_records,e.summary.run_date,{deferClear:!0}),Ee(e,{skipLoadingOverlay:!0}))})}),lt.addEventListener("click",()=>{Mt(ct.value.trim(),lt,document.getElementById("ai-warnings"),document.getElementById("ai-suggestions"),document.getElementById("ai-feedback-container"))});const Nt=document.getElementById("btn-allocator-right-apply-prompt"),Tt=document.getElementById("allocator-right-ai-prompt-input");Nt&&Tt&&Nt.addEventListener("click",()=>{Mt(Tt.value.trim(),Nt,document.getElementById("allocator-right-ai-warnings"),document.getElementById("allocator-right-ai-suggestions"),document.getElementById("allocator-right-ai-feedback-container"))}),ct&&Tt&&(ct.addEventListener("input",t=>{Tt.value=t.target.value}),Tt.addEventListener("input",t=>{ct.value=t.target.value}));const Pt=document.getElementById("agency_mode");function Ot(t){return t&&"boolean"==typeof t.agency_mode?t.agency_mode:!!function(t){const e=t&&t.platforms||{};return Object.values(e).some(t=>{if(!t||"object"!=typeof t)return!1;const e=Number(t.margin_rate);return Number.isFinite(e)&&e>0})}(t)||"true"===localStorage.getItem("siranui_agency_mode")}function qt(t,{persistLocal:n=!0}={}){const a=!!t;if(Pt&&(Pt.checked=a),n&&localStorage.setItem("siranui_agency_mode",a?"true":"false"),function(t){document.querySelectorAll(".margin-settings-wrapper").forEach(e=>{e.style.display=t?"block":"none"});const e=document.getElementById("config-form");if(e&&(t?e.classList.add("agency-mode-active"):e.classList.remove("agency-mode-active")),"function"==typeof window.updateMediaAccordionsVisibility){const t=window.accountGroups?.find(t=>t.id===window.selectedAccountGroupId)||window.accountGroups?.[0]||null;window.updateMediaAccordionsVisibility(t)}else[document.getElementById("margin_rate"),document.getElementById("yahoo_margin_rate"),document.getElementById("ms_margin_rate"),document.getElementById("amazon_margin_rate"),document.getElementById("facebook_margin_rate")].forEach(e=>{e&&(t?e.setAttribute("required","required"):e.removeAttribute("required"))})}(a),"function"==typeof window.applyDetailTableCostTypeForAgencyMode&&window.applyDetailTableCostTypeForAgencyMode(a),void 0!==e&&e)try{Ce(e,d,!0)}catch(t){}}function zt(t){const e=String(t||"").toLowerCase(),n={google:{rate:"margin_rate",type:"margin_type",defaultRate:.2},yahoo:{rate:"yahoo_margin_rate",type:"yahoo_margin_type",defaultRate:.2},microsoft:{rate:"ms_margin_rate",type:"ms_margin_type",defaultRate:.2},amazon:{rate:"amazon_margin_rate",type:"amazon_margin_type",defaultRate:.2},facebook:{rate:"facebook_margin_rate",type:"facebook_margin_type",defaultRate:0},meta:{rate:"facebook_margin_rate",type:"facebook_margin_type",defaultRate:0}},a=n[e]||{rate:null,type:null,defaultRate:0},o=d&&d.platforms&&d.platforms["meta"===e?"facebook":e]||{};if(!document.getElementById("agency_mode")?.checked)return{rate:0,type:o.margin_type||"net",platform:e||"unknown",source:"agency_off"};const i=a.rate?document.getElementById(a.rate):null,r=a.type?document.getElementById(a.type):null;let l=o.margin_rate,c="config";if(null!=l&&Number.isFinite(Number(l))?l=Number(l):(l=a.defaultRate,c=n[e]?"platform_default":"unknown_platform_zero"),i&&""!==String(i.value??"").trim()){const t=parseFloat(i.value);Number.isFinite(t)&&(l=t/100,c=`input:${a.rate}`)}const s=r&&r.value||o.margin_type||"net";return{rate:Number.isFinite(l)?l:0,type:s||"net",platform:e||"unknown",source:c}}function Ht(t,e,n){const a=Number(t)||0,o=Number(e)||0;return o<=0?a:"net"===n?a/(1-o):a*(1+o)}function jt(t,e,n){const a=Number(t)||0,o=Number(e)||0;return o<=0?a:"net"===n?a*(1-o):a/(1+o)}function Rt(t,e){const n=zt(e);return Ht(t,n.rate,n.type)}function Gt(t,e){const n=document.getElementById(`current-budget-${t}`);if(!n)return 0;const a=parseFloat(n.value)||0,o=zt(e),i=document.getElementById("agency_mode")?.checked?jt(a,o.rate,o.type):a;return n.dataset.mediaBudget=String(i),i}function Vt(t,e,n){const a=d&&d.platforms&&d.platforms[t]||{};if(!document.getElementById("agency_mode")?.checked)return{};const o=function(t,e){const n=document.getElementById(t),a=null!=e&&Number.isFinite(Number(e))?Number(e):null;if(!n||n.disabled)return a;const o=String(n.value??"").trim();if(!o)return a;const i=parseFloat(o);return Number.isFinite(i)?i/100:a}(e,a.margin_rate??("facebook"===t?0:.2));return{margin_rate:null!==o&&Number.isFinite(o)?o:0,margin_type:document.getElementById(n)?.value||a.margin_type||"net"}}window.resolvePlatformMargin=zt,window.mediaToClientCost=Ht,window.clientToMediaBudget=jt,window.fetchedAmountForDisplay=Rt;const Wt="true"===localStorage.getItem("siranui_agency_mode");Pt&&(qt(Wt,{persistLocal:!1}),Pt.addEventListener("change",t=>{qt(t.target.checked),ot&&ot.dispatchEvent(new Event("submit"))}));const Ut=document.getElementById("detail-table-cost-type");Ut&&Ut.addEventListener("change",()=>{e&&e.daily_records&&Se(e.daily_records,e.summary.run_date,{deferClear:!0})});const Yt=document.getElementById("detail-table-cost-toggle");if(Yt){const Ae=document.getElementById("detail-table-cost-toggle-knob"),Le=document.getElementById("cost-type-label-client"),ke=document.getElementById("cost-type-label-net"),Fe=document.getElementById("detail-table-cost-type");function Jt(t){Fe.value!==t&&(Fe.value=t,localStorage.setItem("siranui_detail_cost_type",t),"net"===t?(Ae&&(Ae.style.transform="translateX(22px)"),Yt.style.backgroundColor="var(--primary-color, #3b82f6)",Yt.style.borderColor="var(--primary-color, #3b82f6)",ke&&(ke.style.color="#fff"),Le&&(Le.style.color="var(--text-secondary)")):(Ae&&(Ae.style.transform="translateX(0px)"),Yt.style.backgroundColor="rgba(255, 255, 255, 0.1)",Yt.style.borderColor="var(--border-color)",Le&&(Le.style.color="#fff"),ke&&(ke.style.color="var(--text-secondary)")),Fe.dispatchEvent(new Event("change")))}Yt.addEventListener("click",t=>{t.stopPropagation(),Jt("client"===Fe.value?"net":"client")}
1),Le&&Le.addEventListener("click",t=>{t.stopPropagation(),Jt("client")}),ke&&ke.addEventListener("click",t=>{t.stopPropagation(),Jt("net")}),window.applyDetailTableCostTypeForAgencyMode=function(t){Jt(t?"client":"net")},Jt("function"==typeof window.resolveDetailTableCostType?window.resolveDetailTableCostType():document.getElementById("agency_mode")?.checked?"client":"net")}function Xt(t){if(!t)return;const e=document.getElementById(`campaign-dir-tab-${t}`);e&&!e.classList.contains("disabled")&&(window.activeCampaignDirectoryPlatform=t,document.querySelectorAll(".campaign-directory-tabs .structure-media-tab").forEach(t=>t.classList.remove("active")),e.classList.add("active"),document.querySelectorAll(".campaign-dir-tab-content").forEach(e=>{e.style.display=e.id===`media-accordion-${t}`?"block":"none"}),e.offsetWidth,"function"==typeof window.loadAllocatorChangeHistory&&window.loadAllocatorChangeHistory(null,{allPlatforms:!0}),_t(t,{skipTableUpdate:!1,keepCampaignFilter:!1}))}function Zt(t,e){if(!t)return!1;const n=new Set(["","(未選択)","(未連携)"]),a="function"==typeof window.syncGroupYahooFields?window.syncGroupYahooFields({...t}):t;if("yahoo"===e){if("function"==typeof window.resolveYahooIdsFromGroup){const{search:t,display:e}=window.resolveYahooIdsFromGroup(a);if(t&&!n.has(t)||e&&!n.has(e))return!0}const t=String(a.yahoo_account_id||"").trim();return t&&!n.has(t)}const o=String(a["microsoft"===e?"microsoft_customer_id":"facebook"===e?"facebook_ad_account_id":"google_customer_id"]||"").trim();return o&&!n.has(o)}function Kt(){if("function"==typeof window.isSingleAccountWorkspaceScope&&window.isSingleAccountWorkspaceScope()&&window.activeAccountOverride&&window.activeAccountOverride.platform)return window.activeAccountOverride.platform;const t=q(),e=(window.accountGroups||[]).find(e=>e.id===t);if(!e)return"google";for(const t of["google","yahoo","microsoft","facebook"])if(Zt(e,t))return t;return"google"}function Qt(t){if(!t)return;const e=(t,e)=>{const n=document.getElementById(t);n&&(n.value=e)},n=document.getElementById("total_client_budget");n&&(n.placeholder=""),e("total_client_budget",void 0!==t.total_client_budget&&null!==t.total_client_budget?t.total_client_budget:0);const a=t.platforms?.google||{};e("margin_rate",void 0!==a.margin_rate&&null!==a.margin_rate?displayInt(100*a.margin_rate):20),e("margin_type",a.margin_type||"net");const o=t.platforms?.yahoo||{};e("yahoo_margin_rate",void 0!==o.margin_rate&&null!==o.margin_rate?displayInt(100*o.margin_rate):20),e("yahoo_margin_type",o.margin_type||"net");const i=t.platforms?.microsoft||{};e("ms_margin_rate",void 0!==i.margin_rate&&null!==i.margin_rate?displayInt(100*i.margin_rate):20),e("ms_margin_type",i.margin_type||"net");const r=t.platforms?.amazon||{};e("amazon_margin_rate",void 0!==r.margin_rate&&null!==r.margin_rate?displayInt(100*r.margin_rate):20),e("amazon_margin_type",r.margin_type||"net");const l=t.platforms?.facebook||{};e("facebook_margin_rate",void 0!==l.margin_rate&&null!==l.margin_rate?displayInt(100*l.margin_rate):0),e("facebook_margin_type",l.margin_type||"net"),qt(Ot(t)),Array.isArray(t.additional_budgets)&&(d||(d={}),d.additional_budgets=t.additional_budgets,le(t.additional_budgets))}function te(){p&&(p=null,T(!1)),d=null;const t=window.accountGroups?.find(t=>t.id===q())||null;"function"==typeof window.updateMediaAccordionsVisibility&&window.updateMediaAccordionsVisibility(t),yt(),Xt(Kt());const e=document.getElementById("view-agent-workspace"),n=e&&!e.classList.contains("hidden"),a=document.getElementById("tab-budget-optimizer");n&&a&&!a.classList.contains("hidden")&&se();const o=document.getElementById("tab-optimizer");n&&o&&!o.classList.contains("hidden")&&"function"==typeof window.loadBiddingSimulationViews&&window.loadBiddingSimulationViews({forceRefresh:!0})}function ee(){window.SimulationFetch&&window.SimulationFetch.requestForceRefresh(),window.AgentDailyCache&&window.AgentDailyCache.invalidateAgent("simulation")}window.getActiveCampaignDirectoryPlatform=function(){const t=document.querySelector(".campaign-directory-tabs .structure-media-tab.active:not(.disabled)");return t&&t.dataset.tab?t.dataset.tab:window.activeCampaignDirectoryPlatform||"google"},window.switchCampaignDirectoryTab=Xt,window.updateAllocatorHistoryPlatformLabel=function(t){const e=document.getElementById("allocator-history-platform-label");if(!e)return;const n=Array.isArray(t)?t:t&&"all"!==t?[t]:[],a="function"==typeof window.renderHistoryPlatformLogosHtml?window.renderHistoryPlatformLogosHtml(n,{size:16,className:"history-platform-logo"}):"";a?e.innerHTML=`<span class="history-platform-logos">${a}</span>
1`:e.textContent="すべてのメディア"},window.syncCampaignDirectoryWithAccountFilter=te,document.querySelectorAll(".campaign-directory-tabs .structure-media-tab").forEach(t=>{t.addEventListener("click",e=>{e.stopPropagation(),t.classList.contains("disabled")||Xt(t.dataset.tab)})}),window.addEventListener("siranui-account-changed",()=>{te();const t=q(),e=s.get(t);d=e||null}),ot.addEventListener("submit",async t=>{if(t.preventDefault(),p)return void("function"==typeof window.showPremiumToast&&window.showPremiumToast("前月の参照表示中は設定を保存できません。当月に戻ってから保存してください。","error"));const e={google:{},yahoo:{},facebook:{},microsoft:{},amazon:{}};document.querySelectorAll(".camp-dir-row").forEach(t=>{const n=t.dataset.campId,a=t.dataset.platform;if(!n||!a)return;const o=document.getElementById(`prod-type-${n}`),i=document.getElementById(`alloc-type-${n}`),r=document.getElementById(`current-budget-${n}`),l=document.getElementById(`delivery-cond-${n}`),d=o?o.value:"search",s=i?i.value:"auto",u=r?Gt(n,a):0,m=l?l.value:"all",p=c[n]||[],g=document.getElementById(`dist-type-${n}`),f=g?g.value:"equal";if(e[a][n]={product_type:d,allocation_type:s,distribution_type:f,current_budget:u,delivery_condition:m,delivery_days:p},"fixed"===s){const t=document.getElementById(`alloc-val-${n}`);e[a][n].fixed_value=t&&parseFloat(t.value)||0}if("equal"!==f){const t=document.getElementById(`alloc-range-${n}`);e[a][n].boost_weight=t?1+parseFloat(t.value)/100:1.5}});const n=ie(),a=new FormData(ot),o=document.getElementById("agency_mode")?.checked||!1,i=Vt("google","margin_rate","margin_type"),r=Vt("yahoo","yahoo_margin_rate","yahoo_margin_type"),l=Vt("microsoft","ms_margin_rate","ms_margin_type"),u=Vt("amazon","amazon_margin_rate","amazon_margin_type"),m=Vt("facebook","facebook_margin_rate","facebook_margin_type"),g=parseFloat(a.get("total_client_budget")),f={total_client_budget:isNaN(g)?0:g,additional_budgets:n,account_group_id:q(),agency_mode:o,platforms:{google:{enabled:!0,...i,allocation_weight:1,filters:{exclude_campaign_ids:[],min_daily_budget:1e3,max_daily_budget:9999999},campaign_configs:e.google},yahoo:{enabled:!0,...r,allocation_weight:1,filters:{exclude_campaign_ids:[],min_daily_budget:1e3,max_daily_budget:9999999},campaign_configs:e.yahoo},microsoft:{enabled:!0,...l,allocation_weight:1,filters:{exclude_campaign_ids:[],min_daily_budget:0,max_daily_budget:9999999},campaign_configs:e.microsoft},amazon:{enabled:!0,...u,allocation_weight:1,filters:{exclude_campaign_ids:[],min_daily_budget:0,max_daily_budget:9999999},campaign_configs:e.amazon},facebook:{enabled:!0,...m,allocation_weight:1,filters:{exclude_campaign_ids:[],min_daily_budget:0,max_daily_budget:9999999},campaign_configs:e.facebook}}};try{const t=isMockMode()||!isProduction,e="function"==typeof window.buildAgentApiUrl?window.buildAgentApiUrl(`/api/config?mock=${t}`,{platform:"google"}):"function"==typeof window.appendAgentApiParams?window.appendAgentApiParams(`/api/config?mock=${t}`,{platform:"google"}):`/api/config?mock=${t}`;if((await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)})).ok){const e=q();ee();try{let n="function"==typeof window.buildAgentApiUrl?window.buildAgentApiUrl(`/api/config?mock=${t}`,{platform:"google"}):`/api/config?mock=${t}`;if(e){const t=n.includes("?")?"&":"?";n+=`${t}account_group_id=${encodeURIComponent(e)}`}const a=await fetch(n);if(a.ok){const t=await a.json();d=t,e&&s.set(e,t),Qt(t)}else d=f,e&&s.set(e,f)}catch(t){d=f,e&&s.set(e,f)}await he(!0,!0,{preserveCampaignDirectory:!0})}else alert("設定の保存に失敗しました。")}catch(t){}}),it.addEventListener("click",()=>{se()}),rt.addEventListener("click",()=>{e&&e.daily_records?function(t){const e="final"===o?"(最終)":"(入札)";let n=`\ufeffDate,Plan(クライアント),Adjustment(クライアント),Budget(クライアント),Actual(クライアント),Forecast(クライアント),Actual CV${e},Forecast CV${e},Recommended Allocation(クライアント)\n`;t.forEach(t=>{let e=0,a=0;const o=t.date<runDate;
1o||Object.entries(t.campaigns).forEach(([n,a])=>{const o=campAdjustments[n];if(o&&o.total_future_weight>0&&ve(n,o.cond,t.date)){const n=getBoostMultiplier(t.date,o.distType,o.boostWeight),a=o.remaining_budget*(n/o.total_future_weight);e+=a}}),Object.entries(t.campaigns).forEach(([e,n])=>{const o=campAdjustments[e];if(!o)return;if(!ve(e,o.cond,t.date))return;const i=$e(n);null!==i&&(a+=i)});const i=Lt(t,runDate,null,"actual"),r=Lt(t,runDate,null,"forecast"),l=[t.date,displayInt(t.plan_client),displayInt(o?0:e),displayInt(t.budget_client||0),displayInt(t.actual_client||0),displayInt(t.forecast_client||0),o?Math.round(i||0):"",Math.round(r||0),displayInt(a)].join(",");n+=l+"\n"});const a=new Blob([n],{type:"text/csv;charset=utf-8;"}),i=document.createElement("a"),r=URL.createObjectURL(a);i.setAttribute("href",r),i.setAttribute("download",`budget_simulation_${(new Date).toISOString().slice(0,10)}.csv`),document.body.appendChild(i),i.click(),document.body.removeChild(i)}(e.daily_records):alert("エクスポートするデータがありません。")});const ne=document.getElementById("btn-add-additional-budget");function ae(){if(Array.isArray(u)&&u.length)return u.slice();const t=[];return document.querySelectorAll("#table-campaign-google tbody tr[data-camp-id], #table-campaign-yahoo tbody tr[data-camp-id], #table-campaign-microsoft tbody tr[data-camp-id], #table-campaign-facebook tbody tr[data-camp-id]").forEach(e=>{const n=String(e.getAttribute("data-camp-id")||"").trim();if(!n)return;const a=e.querySelector(".campaign-name-cell, .camp-name, td"),o=String(e.dataset.platform||e.getAttribute("data-platform")||"google").toLowerCase();t.push({campaign_id:n,campaign_name:(a&&a.textContent||n).trim(),platform:o})}),t}function oe(t){const e=ae();let n='<option value="">全体 (アカウントグループ全体)</option>';if(!e.length)return n+='<option value="" disabled>キャンペーン読込待ち(シミュレーション後に選択可)</option>',n;const a={google:"Google",yahoo:"Yahoo",microsoft:"Microsoft",facebook:"Meta"};return e.slice().sort((t,e)=>String(t.campaign_name||"").localeCompare(String(e.campaign_name||""),"ja")).forEach(e=>{const o=String(e.campaign_id)===String(t||"")?"selected":"",i=a[e.platform]||String(e.platform||"").toUpperCase(),r=String(e.campaign_name||e.campaign_id).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;");n+=`<option value="${String(e.campaign_id).replace(/"/g,"&quot;")}" ${o}>[${i}] ${r}</option>`}),n}function ie(){const t=[];return document.querySelectorAll(".additional-budget-row").forEach(e=>{const n=e.querySelector(".add-budget-start")?.value||"",a=e.querySelector(".add-budget-end")?.value||"",o=parseFloat(e.querySelector(".add-budget-amount")?.value)||0,i=e.querySelector(".add-budget-campaign")?.value||null;n&&a&&o>0&&t.push({start_date:n,end_date:a,amount:o,campaign_id:i||null})}),t}function re(){document.querySelectorAll(".additional-budget-row .add-budget-campaign").forEach(t=>{const e=t.value||"";t.innerHTML=oe(e),e&&(t.value=e)});const t=document.getElementById("additional-budgets-empty-hint");if(t){const e=ae().length>0;t.style.display=e?"none":"block"}}function le(t){const e=document.getElementById("additional-budgets-container");e&&(e.innerHTML="",(Array.isArray(t)?t:d?.additional_budgets||[]).forEach(t=>{ce(t)}),re())}function ce(t={}){const e=document.getElementById("additional-budgets-container");if(!e)return;const n=document.createElement("div");n.className="additional-budget-row",n.style.cssText="display: flex; gap: 8px; align-items: center; flex-wrap: wrap; background: rgba(255,255,255,0.05); padding: 8px; border-radius: 6px; margin-bottom: 4px;";const a=t.start_date||"",o=t.end_date||"",i=oe(t.campaign_id);n.innerHTML=`\n            <button type="button" class="btn btn-secondary btn-sm add-budget-start-btn" style="flex: 1 1 110px; min-width: 110px; padding: 6px 8px; font-size: 0.8rem; border-radius: 4px;">${X(a)}</button>\n            <input type="hidden" class="add-budget-start" value="${a}">\n            <span style="font-size: 0.8rem; color: var(--text-secondary);">〜</span>\n            <button type="button" class="btn btn-secondary btn-sm add-budget-end-btn" style="flex: 1 1 110px; min-width: 110px; padding: 6px 8px; font-size: 0.8rem; border-radius: 4px;">${X(o)}</button>\n            <input type="hidden" class="add-budget-end" value="${o}">\n            <select class="add-budget-campaign" style="flex: 2 1 180px; min-width: 160px; padding: 6px 8px; border: 1px solid var(--border-color); background: rgba(0,0,0,0.2); color: var(--text-primary); border-radius: 4px; font-size: 0.8rem;">\n                ${i}\n            </select>\n            <input type="number" class="add-budget-amount" value="${t.amount||""}" placeholder="追加金額(円)" required min="0" style="flex: 1 1 120px; min-width: 110px; padding: 6px 8px; border: 1px solid var(--border-color); background: rgba(0,0,0,0.2); color: var(--text-primary); border-radius: 4px; font-size: 0.8rem;">\n            <button type="button" class="btn btn-danger btn-sm btn-delete-additional-budget" style="padding: 6px 8px; font-size: 0.75rem; border-radius: 4px;">削除</button>\n        `;const r=n.querySelector(".add-budget-start"),l=n.querySelector(".add-budget-end"),c=n.querySelector(".add-budget-start-btn"),d=n.querySelector(".add-budget-end-btn");c.addEventListener("click",()=>{Q(r,c,"📅 追加予算の開始日")}),d.addEventListener("click",()=>{Q(l,d,"📅 追加予算の終了日")}),n.querySelector(".btn-delete-additional-budget").addEventListener("click",()=>{n.remove()}),e.appendChild(n)}function de(t,e){["ai-chat-log-container","allocator-right-ai-chat-log-container"].forEach(n=>{const a=document.getElementById(n);if(!a)return;a.style.display="flex";const o=document.createElement("div");
1o.className="chat-bubble "+("user"===t?"user-bubble":"advisor-bubble"),o.textContent=e,a.appendChild(o),function(t){const e=document.getElementById(t);if(!e)return;const n=e.querySelectorAll(".chat-bubble");if(n.length>10)for(let t=0;t<n.length-10;t++)n[t].remove();const a=e.querySelectorAll(".chat-bubble");a.forEach((t,e)=>{e<a.length-2?(t.style.opacity="0.4",t.style.padding="6px 10px",t.style.fontSize="0.75rem",t.style.borderRadius="6px",t.style.whiteSpace="nowrap",t.style.overflow="hidden",t.style.textOverflow="ellipsis",t.style.maxWidth="75%"):(t.style.opacity="1",t.style.padding="12px",t.style.fontSize="0.8rem",t.style.whiteSpace="pre-wrap",t.style.overflow="visible",t.style.textOverflow="clip",t.style.maxWidth="85%")})}(n),a.scrollTop=a.scrollHeight})}async function se(){const t=document.getElementById("view-agent-workspace"),e=document.getElementById("tab-budget-optimizer"),n=(t&&!t.classList.contains("hidden")&&e&&e.classList.contains("hidden"),++currentConfigRequestId),a=isMockMode()||!isProduction,o=q(),i=s.get(o);i?(d=i,Qt(i)):d=null;const r=window.SimulationFetch?window.SimulationFetch.buildSimulationCacheKey(a,o):null;let l=!1;r&&window.AgentDailyCache&&(l=!!(window.AgentDailyCache.getPayloadAsync?await window.AgentDailyCache.getPayloadAsync(r):window.AgentDailyCache.getPayload(r)));const c=document.getElementById("total_client_budget");if(!i&&c&&(c.value="",c.placeholder="読み込み中..."),!l){const t=document.getElementById("allocator-change-history-list");t&&(t.innerHTML='<div style="font-size: 0.8rem; color: var(--text-secondary); text-align: center; padding: 20px 0;">履歴を読み込んでいます...</div>');const e=document.querySelector("#table-campaign-google tbody"),n=document.querySelector("#table-campaign-yahoo tbody"),a=document.querySelector("#table-campaign-facebook tbody"),o=document.querySelector("#table-campaign-microsoft tbody"),i=document.querySelector("#table-campaign-amazon tbody");e&&(e.innerHTML=k(7,"読み込み中...")),n&&(n.innerHTML=k(7,"読み込み中...")),a&&(a.innerHTML=k(7,"読み込み中...")),o&&(o.innerHTML=k(7,"読み込み中...")),i&&(i.innerHTML=k(7,"読み込み中..."))}try{let t="function"==typeof window.buildAgentApiUrl?window.buildAgentApiUrl(`/api/config?mock=${a}`,{platform:"google"}):"function"==typeof window.appendAgentApiParams?window.appendAgentApiParams(`/api/config?mock=${a}`,{platform:"google"}):`/api/config?mock=${a}`;if(o){const e=t.includes("?")?"&":"?";t+=`${e}account_group_id=${encodeURIComponent(o)}`}const i=await fetch(t);if(!i.ok)throw new Error(`HTTP error ${i.status}`);{const t=await i.json();if(n!==currentConfigRequestId)return;if(o!==q())return;d=t,s.set(o,t),Qt(t),p||he(!0,!1),async function(){const t=document.getElementById("allocator-prior-month-banner"),e=document.getElementById("allocator-prior-month-label");if(t&&e&&!p)try{const n=await fetch(N());if(!n.ok)return t.classList.add("hidden"),void(g=null);const a=await n.json();if(g=a,!a.available||!a.previous_month)return void t.classList.add("hidden");const o="function"==typeof formatDisplayCurrency?formatDisplayCurrency(a.total_client_budget||0):`${a.total_client_budget||0}円`;e.textContent=`${M(a.previous_month)}は月次総予算 ${o}
1 で配分済みです。保存された配分結果を確認できます。`,t.classList.remove("hidden")}catch(e){t.classList.add("hidden"),g=null}}(),restoreAgentTabLayout(e),"function"==typeof window.loadAllocatorChangeHistory&&window.loadAllocatorChangeHistory(null,{allPlatforms:!0,force:!l})}}catch(t){c&&(c.placeholder="");const e="localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname,n=t.message.includes("403")||t.message.includes("Forbidden")||t.message.includes("ACC")||t.message.includes("933");if((e||"undefined"!=typeof isProduction&&!isProduction)&&n&&"9999990010"!==selectedCustomerId)return selectedCustomerId="9999990010","undefined"!=typeof window&&(window.customerId="9999990010",window.selectedAccountGroupId="group_single_9999990010",localStorage.setItem("siranui_auth_customer_id","9999990010"),localStorage.setItem("siranui_active_account_group_id","group_single_9999990010"),window.activeAccountOverride={groupId:"group_single_9999990010",platform:"google",id:"9999990010"},localStorage.setItem("siranui_active_account_override",JSON.stringify(window.activeAccountOverride))),void setTimeout(()=>{se(),"function"==typeof window.syncHeaderAccountSelects&&window.syncHeaderAccountSelects(),"function"==typeof loadCampaignsForAccount&&loadCampaignsForAccount()},100);!function(t){const e=document.getElementById("tab-budget-optimizer");if(!e)return;let n=document.getElementById("budget-error-container");n||(n=document.createElement("div"),n.id="budget-error-container",e.appendChild(n)),n.innerHTML=`\n            <div class="error-panel glass fade-in" style="\n                display: flex;\n                flex-direction: column;\n                align-items: center;\n                justify-content: center;\n                padding: 3rem 2rem;\n                border-radius: 16px;\n                border: 1px solid rgba(239, 68, 68, 0.2);\n                background: rgba(15, 23, 42, 0.45);\n                backdrop-filter: blur(12px);\n                -webkit-backdrop-filter: blur(12px);\n                box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);\n                color: var(--text-primary);\n                text-align: center;\n                margin: 40px auto;\n                max-width: 650px;\n                gap: 20px;\n            ">\n                <div class="error-icon" style="\n                    font-size: 3rem;\n                    background: rgba(239, 68, 68, 0.1);\n                    width: 80px;\n                    height: 80px;\n                    display: flex;\n                    align-items: center;\n                    justify-content: center;\n                    border-radius: 50%;\n                    border: 1px solid rgba(239, 68, 68, 0.3);\n                    box-shadow: 0 0 20px rgba(239, 68, 68, 0.2);\n                ">❌</div>\n                <div style="display: flex; flex-direction: column; gap: 8px;">\n                    <h3 style="\n                        font-family: var(--font-display);\n                        font-size: 1.25rem;\n                        font-weight: 600;\n                        color: var(--accent-rose);\n                        margin: 0;\n                    ">予算配分データの取得に失敗しました</h3>\n                    <p style="\n                        font-size: 0.9rem;\n                        color: var(--text-secondary);\n                        line-height: 1.5;\n                        max-width: 500px;\n                        margin: 0 auto;\n                    ">\n                        実APIの連携状態、またはAPIキーを確認してください。<br>\n                        デモ・モック環境の場合は、Customer IDに 'mock' などの文字列を指定してください。\n                    </p>\n                </div>\n                <div class="error-details" style="\n                    background: rgba(0, 0, 0, 0.3);\n                    border: 1px solid var(--border-color);\n                    border-radius: 8px;\n                    padding: 12px 16px;\n                    font-family: monospace;\n                    font-size: 0.8rem;\n                    color: #fca5a5;\n                    max-width: 100%;\n                    word-break: break-all;\n                    text-align: left;\n                    overflow-x: auto;\n                    width: 100%;\n                    box-sizing: border-box;\n                ">\n                    エラー詳細: ${t}\n                </div>\n                <button type="button" id="btn-budget-retry" class="btn btn-primary" style="\n                    display: flex;\n                    align-items: center;\n                    gap: 8px;\n                    padding: 10px 24px;\n                    border-radius: 8px;\n                    font-weight: 600;\n                    cursor: pointer;\n                    background: var(--primary-color);\n                    border: none;\n                    color: white;\n                    transition: all 0.2s;\n                ">\n                    🔄 再試行する\n                </button>\n            </div>\n        `;const a=document.getElementById("btn-budget-retry");a&&a.addEventListener("click",()=>{!async function(){const t=document.getElementById("tab-budget-optimizer"),e=document.getElementById("btn-budget-retry");e&&(e.disabled=!0,e.style.opacity="0.7",e.style.cursor="wait",e.textContent="⏳ 再試行中…"),window.AgentDailyCache&&("function"==typeof window.AgentDailyCache.requestForceRefresh&&window.AgentDailyCache.requestForceRefresh("simulation"),"function"==typeof window.AgentDailyCache.cancelInFlightForAgent&&window.AgentDailyCache.cancelInFlightForAgent("simulation")),"function"==typeof restoreAgentTabLayout&&restoreAgentTabLayout(t);try{await he(!0,!0,{preserveCampaignDirectory:!1,retryPlatforms:["google"]})}catch(t){await se()}}()}),showAgentTabErrorMode(e,n)}("function"==typeof window.humanizeFetchError?window.humanizeFetchError(t,"simulation"):t.message)}}
1function ue(t){return"function"!=typeof window.yahooCampaignMatchesAccountScope||window.yahooCampaignMatchesAccountScope(t)}function me(t){const e=String(t||"").toLowerCase();if(!e)return!1;if("function"==typeof window.isSingleAccountWorkspaceScope&&window.isSingleAccountWorkspaceScope()&&window.activeAccountOverride&&window.activeAccountOverride.platform)return window.activeAccountOverride.platform===e;const n=q(),a=(window.accountGroups||[]).find(t=>t.id===n);return!!a&&Zt(a,e)}function pe(t,e,n,a){if(!me(n))return!1;if(!a)return!0;const o=window.cvGroups.find(t=>t.id===a);if(!o||!o.stages)return!0;const i=String(n||"").toLowerCase(),r=String(t),l=String(e||"").toLowerCase(),c=o.linked_campaigns;if(Array.isArray(c))return 0!==c.length&&c.some(t=>{const e=String(t.platform||"").toLowerCase(),n=String(t.campaign_id||""),a=String(t.campaign_name||"").toLowerCase();return!(e&&e!==i||(!n||r!==n)&&(!a||!l||a!==l&&!a.includes(l)&&!l.includes(a)))});for(const t of o.stages)for(const e of t.nodes){const t=e.platform?String(e.platform).toLowerCase():"",n=e.campaign_id?String(e.campaign_id):"";if((!t||t===i)&&n&&r===n)return!0}return!1}function ge(){t&&(t.destroy(),t=null),st&&(st.textContent="-"),ut&&(ut.textContent="-"),mt&&(mt.textContent=""),pt&&(pt.textContent="-"),gt&&(gt.textContent="")}function fe(){ge(),function(){const t=k(7,"読み込み中...");["#table-campaign-google tbody","#table-campaign-yahoo tbody","#table-campaign-facebook tbody","#table-campaign-microsoft tbody","#table-campaign-amazon tbody"].forEach(e=>{const n=document.querySelector(e);n&&(n.innerHTML=t)})}()}function ye(t){window.renderFinalCvMeasurementBanner("allocator-final-cv-measurement-banner",t,{active:"final"===o})}function _e(t,n){L(),t=function(t,e){const n=JSON.parse(JSON.stringify(t)),a="function"==typeof window.resolveMetricsCvGroupId?window.resolveMetricsCvGroupId():"";n.daily_records.forEach((t,o)=>{let i=0,r=0,l=0,c=0,d=0,s=0;const u={},m=t.date<n.summary.run_date;Object.entries(t.campaigns||{}).forEach(([t,n])=>{const a=n.platform||"google";me(a)&&(e&&!pe(t,n.campaign_name||"",a,e)||(u[t]=n,i+=m&&parseFloat(n.actual_media)||0,d+=parseFloat(n.plan_media)||0,s+=parseFloat(n.forecast_media)||m&&parseFloat(n.actual_media)||0,r+=parseFloat(n.actual_cv)||parseFloat(n.forecast_cv)||0,m&&(l+=parseFloat(n.actual_cv)||0),c+=parseFloat(n.forecast_cv)||0))}),t.campaigns=u;const p="function"==typeof window.resolveFunnelFinalCvRatio?window.resolveFunnelFinalCvRatio(a,n.summary):1;t.actual_bidding_cv=m?l:null,t.forecast_bidding_cv=c;const g="function"==typeof window.scaleFinalCvValue?window.scaleFinalCvValue:t=>t,f=a?p:1;t.actual_final_cv=m?g(l,f):null,t.forecast_final_cv=g(c,f);let y=0,_=0;Object.values(u).forEach(t=>{m&&(y+=parseFloat(t.actual_cvv)||0),_+=parseFloat(t.forecast_cvv)||0}),t.actual_bidding_cvv=m?y:null,t.forecast_bidding_cvv=_,t.actual_final_cvv=m?g(y,f):null,t.forecast_final_cvv=g(_,f);const h=document.getElementById("margin_rate")?.value?parseFloat(document.getElementById("margin_rate").value)/100:.2;if(t.actual_media=i,t.actual_client=i/(1-h),t.plan_media=d,t.plan_client=d/(1-h),t.forecast_media=s,t.forecast_client=s/(1-h),0===o)t.cum_actual_client=t.actual_client,t.cum_plan_client=t.plan_client,t.cum_forecast_client=t.forecast_client;else{const e=n.daily_records[o-1];t.cum_actual_client=e.cum_actual_client+t.actual_client,t.cum_plan_client=e.cum_plan_client+t.plan_client,t.cum_forecast_client=e.cum_forecast_client+t.forecast_client}});const o=n.daily_records[n.daily_records.length-1],i=n.daily_records.find(t=>t.date===n.summary.run_date)||o;if(n.summary.total_client_budget=(()=>{const e=parseFloat(document.getElementById("total_client_budget")?.value);if(!Number.isNaN(e)&&e>0)return e;const n=parseFloat(d?.total_client_budget);return!Number.isNaN(n)&&n>0?n:parseFloat(t.summary?.total_client_budget)||0})(),n.summary.spent_client_budget=i?i.cum_actual_client:0,n.summary.remaining_client_budget=Math.max(0,n.summary.total_client_budget-n.summary.spent_client_budget),n.summary.cum_forecast_client=o?o.cum_forecast_client:0,n.summary.funnel_final_cv_ratio="function"==typeof window.resolveFunnelFinalCvRatio?window.resolveFunnelFinalCvRatio(a,n.summary):n.summary.funnel_final_cv_ratio||1,n.campaign_metadata){const t={};
1Object.entries(n.campaign_metadata).forEach(([n,a])=>{const o=a.platform||"google";me(o)&&(e&&!pe(n,a.campaign_name||a.name||"",o,e)||(t[n]=a))}),n.campaign_metadata=t}return n}(t,("function"==typeof window.resolveCampaignFilterCvGroupId?window.resolveCampaignFilterCvGroupId():window.selectedCvGroupId||null)||null),e=t;const a="function"==typeof window.resolveMetricsCvGroupId?window.resolveMetricsCvGroupId():"";i="function"==typeof window.resolveFunnelFinalCvRatio?window.resolveFunnelFinalCvRatio(a,t.summary):1,function(t){const e=document.getElementById("allocator-platform-warning");if(!e)return;const n={google:"Google 広告",yahoo:"Yahoo! 広告",microsoft:"Microsoft 広告",facebook:"Meta 広告"},a=[],o=t&&t.platform_fetch_errors||{},i=t&&t.platform_fetch_warnings||{},r=t&&t.platform_status||{},l=(window.accountGroups||[]).find(t=>t.id===q())||null,c=[];if(i._cache_fallback&&a.push(String(i._cache_fallback)),["google","yahoo","microsoft","facebook"].forEach(t=>{if(!Zt(l,t))return;if(i[t])return void a.push(`${n[t]}: ${i[t]}`);if(o[t])return c.push(t),void a.push(`${n[t]}: ${o[t]}`);const e=r[t];e&&e.selected&&!e.live&&(c.push(t),a.push(`${n[t]}: OAuth 連携が完了していないため、キャンペーンを取得できません。`))}),c.length){const e=c.map(t=>n[t]).join("・"),o=t&&t.summary&&t.summary.allocation_incomplete_note||`【お知らせ】一部媒体(${e})の取得に失敗しました。現在の共有月予算の配分・予測は取得できたキャンペーンのみで計算されており、推奨予算・予測CVは不完全です。下の「失敗媒体のみ再取得」を押すと、失敗した媒体だけを取り直し、成功済み媒体と合わせてシミュレーションを再生成します。適用や判断の前に再取得してください。`;a.unshift(o)}else t&&t.summary&&t.summary.allocation_incomplete_note&&a.unshift(String(t.summary.allocation_incomplete_note));if(!a.length)return e.classList.add("hidden"),void(e.innerHTML="");e.innerHTML="",a.forEach(t=>{const n=document.createElement("div");n.textContent=t,e.appendChild(n)});const d=document.createElement("div");if(d.style.marginTop="10px",d.style.display="flex",d.style.flexWrap="wrap",d.style.gap="8px",d.style.alignItems="center",c.length){const t=document.createElement("button");t.type="button",t.className="btn btn-primary btn-sm";const e=c.map(t=>n[t]).join("・");t.textContent=`失敗媒体のみ再取得してシミュレーション再生成(${e})`,t.title="失敗した媒体だけ再取得し、成功済み媒体とマージしたうえでシミュレーション(配分・予測)を再生成します。",t.addEventListener("click",()=>{he(!0,!0,{preserveCampaignDirectory:!1,retryPlatforms:c.slice()})}),d.appendChild(t)}const s=document.createElement("button");s.type="button",s.className="btn btn-secondary btn-sm",s.textContent="全媒体を再取得してシミュレーション再生成",s.title="すべての媒体を再取得してシミュレーション(配分・予測)を再生成します。",s.addEventListener("click",()=>{he(!0,!0,{preserveCampaignDirectory:!1})}),d.appendChild(s),e.appendChild(d),e.classList.remove("hidden")}(t),ye(t.summary),yt(),function(t){const e=window.monthlyCapIsSet(t.total_client_budget);st.textContent=e?`${formatDisplayCurrency(t.total_client_budget)}`:window.MONTHLY_CAP_UNSET_LABEL,ut.textContent=`${formatDisplayCurrency(t.spent_client_budget)}`,mt.textContent=e?`残りの予算: ${formatDisplayCurrency(t.remaining_client_budget)}`:`残りの予算: ${window.MONTHLY_REMAINING_UNSET_LABEL}`,pt.textContent=`${formatDisplayCurrency(t.cum_forecast_client)}`;const n=t.cum_forecast_client-t.total_client_budget,a=window.monthlyCapDiffPercent(t.total_client_budget,t.cum_forecast_client);null===a?(gt.textContent=`着地予測との差分: ${formatDisplayCurrency(n)}(上限未設定)`,gt.className="kpi-sub"):n>0?(gt.textContent=`予算比: +${roundDisplayNum(a,1)}% (+${formatDisplayCurrency(n)})`,gt.className="kpi-sub down"):(gt.textContent=`予算比: ${roundDisplayNum(a,1)}% (${formatDisplayCurrency(n)})`,gt.className="kpi-sub up")}(t.summary),nt(),Ee(t),Se(t.daily_records,t.summary.run_date),Ce(t,d,n),Ie(t)}async function he(t=!1,n=!1,a={}){const o=!0===a.preserveCampaignDirectory,i=Array.isArray(a.retryPlatforms)?a.retryPlatforms.filter(
1Boolean):[];if(p)return;const r=document.getElementById("view-agent-workspace"),l=document.getElementById("tab-budget-optimizer");if(r&&r.classList.contains("hidden"))return;if(l&&l.classList.contains("hidden"))return;const c=++currentSimulationRequestId,d=isMockMode()||!isProduction,s=d?"":function(){if("function"==typeof window.resolveAgentCustomerIdForPlatform){const t=window.resolveAgentCustomerIdForPlatform("google");if(t)return t}const t=("function"==typeof window.resolveActiveAccountGroupId?window.resolveActiveAccountGroupId():"")||window.selectedAccountGroupId||localStorage.getItem("siranui_active_account_group_id")||"",e=(window.accountGroups||[]).find(e=>e.id===t);if(e&&e.google_customer_id)for(const t of String(e.google_customer_id).split(",")){const e=t.trim();if(e&&"(未選択)"!==e&&"(未連携)"!==e&&("function"!=typeof window.isDemoAccountId||!window.isDemoAccountId(e)))return e}if("function"==typeof window.getActiveCustomerId){const t=window.getActiveCustomerId();if(t)return t}return("undefined"!=typeof selectedCustomerId?selectedCustomerId:"")||window.customerId||localStorage.getItem("siranui_auth_customer_id")||""}();if(!d&&!s)return fe(),L(),void(ft&&(ft.innerHTML=`<tr><td colspan="${I()}" class="text-center text-muted">広告アカウントを選択してください。</td></tr>`));const u=i.length?"失敗媒体を再取得中":"シミュレーション準備中";o||fe(),F(u),B(`${u}...`,i.length>0||n),"function"==typeof setChartLoading&&setChartLoading("budgetChart",!0,`${u}...`);const m=q();window.AgentDailyCache&&"function"==typeof window.AgentDailyCache.refreshIfJstDateChanged&&window.AgentDailyCache.refreshIfJstDateChanged()&&(n=!0,e=null);const g=window.SimulationFetch?window.SimulationFetch.buildSimulationCacheKey(d,m):null,f=g&&window.AgentDailyCache?window.AgentDailyCache.getPayloadAsync?await window.AgentDailyCache.getPayloadAsync(g):window.AgentDailyCache.getPayload(g):null;if(!n&&!i.length&&function(t){if(!t)return!1;const e=t.campaign_metadata;return!!(e&&Object.keys(e).length>0)||(t.daily_records||[]).some(t=>t&&t.campaigns&&Object.keys(t.campaigns).length>0)}(f))return _e(f,t),D(!0),void("function"==typeof setChartLoading&&setChartLoading("budgetChart",!1));let y=null,_=null;if(!n&&!i.length&&window.SimulationFetch&&!d){try{y=await window.SimulationFetch.fetchSimulationReadiness({isMock:d,accountGroupId:m,platform:Kt()})}catch(t){}if("function"==typeof window.SimulationFetch.fetchSimulationJobStatus)try{_=await window.SimulationFetch.fetchSimulationJobStatus({accountGroupId:m,platform:Kt()})}catch(t){}}const h=window.SimulationFetch?window.SimulationFetch.resolveSimulationLoadingMessage(y,{forceRefresh:n,retryPlatforms:i,jobStatus:_}):i.length?"失敗媒体を再取得中...":"シミュレーション計算中...",b=window.SimulationFetch?window.SimulationFetch.resolveSimulationProgressLabel(y,{forceRefresh:n,retryPlatforms:i,jobStatus:_}):i.length?"失敗媒体を再取得中...":"シミュレーション取得中...";if(o)ge(),ft&&(ft.innerHTML=k(I(),"シミュレーション計算中..."),F("シミュレーション計算中")),"function"==typeof setChartLoading&&setChartLoading("budgetChart",!0,"グラフを集計中..."),F(h);else if(F(h),"function"==typeof setChartLoading){const t=(window.SimulationFetch&&"function"==typeof window.SimulationFetch.formatJobStageLabel?window.SimulationFetch.formatJobStageLabel(_):"")||(y&&y.preparing_required&&!n?"シミュレーション準備中...":"グラフを集計中...");setChartLoading("budgetChart",!0,t)}B(b,i.length>0||n,{jobProgressPct:_&&null!=_.progress_pct?_.progress_pct:void 0});try{let e;const a=Kt();if(window.SimulationFetch)e=await window.SimulationFetch.fetchSimulationData({isMock:d,accountGroupId:m,forceRefresh:n,platform:a,retryPlatforms:i.length?i:void 0,rallyPart:"budget"});else{let t="function"==typeof window.buildAgentApiUrl?window.buildAgentApiUrl(`/api/simulation?mock=${d}`,{platform:a}):`/api/simulation?mock=${d}`;i.length&&(t+=`&retry_platforms=${encodeURIComponent(i.join(","))}&force_refresh=1`);const n=await fetch(t);if(!n.ok)throw new Error(`HTTP error ${n.status}`);e=await n.json()}if(c!==currentSimulationRequestId)return;e&&e.is_token_expired?window.showTokenExpiredWarning&&window.showTokenExpiredWarning(!0):window.showTokenExpiredWarning&&window.showTokenExpiredWarning(!1),_e(e,t),D(!0)}catch(t){if(c!==currentSimulationRequestId)return;D(!1);const e="function"==typeof window.humanizeFetchError?window.humanizeFetchError(t,"simulation"):t&&t.message?t.message:"エラーが発生しました";ft&&(ft.innerHTML=`<tr><td colspan="${I()}" class="text-center text-danger" style="padding: 30px; font-weight: 500;">${e}</td></tr>`),o||function(t){const e=t||"キャンペーンを取得できませんでした。";["#table-campaign-google tbody","#table-campaign-yahoo tbody","#table-campaign-facebook tbody","#table-campaign-microsoft tbody","#table-campaign-amazon tbody"].forEach(t=>{const n=document.querySelector(t);n&&(n.textContent||"").trim().includes("読み込み中")&&(n.innerHTML=`<tr><td colspan="7" class="text-center text-muted">${e}</td></tr>`)})}(e)}finally{c===currentSimulationRequestId&&"function"==typeof setChartLoading&&setChartLoading("budgetChart",!1)}}function be(t,e){const{year:n,month:a}=J();let o=n,i=a-1;i<1&&(i=12,o-=1);const r=new Date(o,i,0).getDate(),l=`${o}-${String(i).padStart(2,"0")}`;if("all"===e)return r;if("weekday"===e){let t=0;for(let e=1;e<=r;e++){const n=`${l}-${String(e).padStart(2,"0")}`,a=new Date(o,i-1,e).getDay(),r=void 0!==z&&z.includes(n);0===a||6===a||r||t++}return t}if("custom"===e){const e=(c[t]||[]).filter(t=>String(t||"").slice(0,7)===l);return e.length>0?e.length:r}return r}function we(t){const e=document.getElementById(`last-month-budget-${t}`);if(!e||"true"!==String(e.dataset.fallback))return;const n=document.querySelector(`.delivery-cond-select[data-camp-id="${t}"]`),a=n?n.value:"all",o=document.getElementById(`current-budget-${t}`),i=o&&o.closest(".camp-dir-row"),r=i&&i.dataset.platform||"google";let l=parseFloat(o&&o.dataset.mediaBudget);
1if(!Number.isFinite(l)&&(l=parseFloat(o&&o.value)||0,document.getElementById("agency_mode")?.checked&&"function"==typeof window.clientToMediaBudget&&"function"==typeof window.resolvePlatformMargin)){const t=window.resolvePlatformMargin(r);l=window.clientToMediaBudget(l,t.rate,t.type)}const c=l*be(t,a);e.dataset.mediaAmount=String(c);let d=c;"function"==typeof window.fetchedAmountForDisplay&&(d=window.fetchedAmountForDisplay(c,r)),"function"==typeof formatDisplayCurrency?e.textContent=formatDisplayCurrency(d):e.textContent=String(Math.round(d))}function ve(t,e,n){const a=new Date(n),o=a.getDate(),i=String(n||"").slice(0,10);if("all"===e)return!0;if("weekday"===e){const t=a.getDay(),e=void 0!==z&&z.includes(i);return 0!==t&&6!==t&&!e}if("custom"===e){const e=c[t]||[];return e.includes(i)||e.includes(String(o))||e.includes(o)}return!0}function Ce(t,n,a=!1){const o=document.querySelector("#table-campaign-google tbody"),i=document.querySelector("#table-campaign-yahoo tbody"),r=document.querySelector("#table-campaign-facebook tbody"),l=document.querySelector("#table-campaign-microsoft tbody"),s=document.querySelector("#table-campaign-amazon tbody");if(!(o||i||l||r))return;const p=t.daily_records&&t.daily_records[0],g=t.campaign_metadata||(p?p.campaigns:{}),f=Object.entries(g).map(([t,e])=>`${e.platform||"google"}:${t}`).sort().join("|");u=Object.entries(g).map(([t,e])=>({campaign_id:String(t),campaign_name:e.campaign_name||e.name||"",platform:e.platform||"google"}));const y={};if(t.daily_records&&t.daily_records.length>0){let $=.2,x="net",S=.2,I="net",A=0,L="net",k=.2,F="net",B=.2,D="net";if(document.getElementById("agency_mode")?.checked){if(n&&n.platforms){const N=n.platforms.google||{};$=void 0!==N.margin_rate?N.margin_rate:.2,x=N.margin_type||"net";const T=n.platforms.yahoo||{};S=void 0!==T.margin_rate?T.margin_rate:.2,I=T.margin_type||"net";const P=n.platforms.facebook||{};A=void 0!==P.margin_rate?P.margin_rate:0,L=P.margin_type||"net";const O=n.platforms.microsoft||{};k=void 0!==O.margin_rate?O.margin_rate:.2,F=O.margin_type||"net";const q=n.platforms.amazon||{};B=void 0!==q.margin_rate?q.margin_rate:.2,D=q.margin_type||"net"}}else $=0,S=0,A=0,k=0,B=0;function _(t,e){let n=0,a="net";return"google"===e?(n=$,a=x):"yahoo"===e?(n=S,a=I):"facebook"===e?(n=A,a=L):"microsoft"===e?(n=k,a=F):"amazon"===e&&(n=B,a=D),"net"===a?t/(1-n):t*(1+n)}const M=t.summary?.run_date||(new Date).toISOString().split("T")[0];t.daily_records.forEach(t=>{const e=t.date<M;Object.entries(t.campaigns).forEach(([t,n])=>{y[t]||(y[t]={plan:0,forecast:0,actual_client_sum:0});const a=n.plan_media||0,o=e?n.actual_media||0:n.forecast_media||0;if(y[t].plan+=_(a,n.platform),y[t].forecast+=_(o,n.platform),e){const e=n.actual_media||0;y[t].actual_client_sum+=_(e,n.platform)}})})}if(!a&&f===m){const z=function(t){const e={google:0,yahoo:0,facebook:0,microsoft:0,amazon:0};return Object.values(t||{}).forEach(t=>{const n=t.platform||"google";void 0!==e[n]&&(e[n]+=1)}),e}(g);if([["google",o],["yahoo",i],["facebook",r],["microsoft",l],["amazon",s]].every(([t,e])=>!e||!function(t){return!!t&&(t.textContent||"").includes("読み込み中")}(e)&&function(t){return t?t.querySelectorAll(".camp-dir-row").length:0}(e)===(z[t]||0)))return void re()}m=f;const h=ie();h.length&&(d||(d={}),d.additional_budgets=h),le(),o&&(o.innerHTML=""),i&&(i.innerHTML=""),r&&(r.innerHTML=""),l&&(l.innerHTML=""),s&&(s.innerHTML="");const b=n?.platforms?.google?.campaign_configs||{},w=n?.platforms?.yahoo?.campaign_configs||{},v=n?.platforms?.facebook?.campaign_configs||{},C=n?.platforms?.microsoft?.campaign_configs||{},E=n?.platforms?.amazon?.campaign_configs||{};if((window.CampaignSort?window.CampaignSort.sortCampaignEntries(Object.entries(g)):Object.entries(g)).forEach(([t,e])=>{const n=e.platform||"google";if(!me(n))return;if("yahoo"===n&&!ue(e))return;if(window.selectedCvGroupId&&!pe(t,e.campaign_name||e.name||"",e.platform||"google",window.selectedCvGroupId))return;const a=String(e.status||"ENABLED").toUpperCase();if(Number(e.recent_impressions??e.last_month_impressions??0)<1&&"ENABLED"!==a)return;let d=null,u=null;if("google"===n?(d=o,u=b):"yahoo"===n?(d=i,u=w):"facebook"===n?(d=r,u=v):"microsoft"===n?(d=l,u=C):"amazon"===n&&(d=s,u=E),!d)return;const m=function(t,e){return t?t[String(e)]??t[e]??t[Number(e)]??null:null}(u,t)||{product_type:e.product_type||"search",allocation_type:"auto",delivery_condition:"all",delivery_days:[]};let p=m.product_type||e.product_type||"search";"facebook"!==n&&"meta"!==n||["search","display","video","pmax"].includes(String(p).toLowerCase())||(p="display");let g=m.allocation_type||"auto";"boost"===g&&(g="boost_end");const f=e.current_budget,y=m.current_budget,_=null!=f?Number(f):NaN,h=null!=y?Number(y):NaN,$=!Number.isFinite(_)||"lifetime_div_schedule_days"!==e.daily_budget_source&&"lifetime"!==e.budget_type&&Number.isFinite(h)?Number.isFinite(h)?h:Number.isFinite(_)?_:0:_,x=void 0!==e.last_month_cost?e.last_month_cost:0,S=void 0!==e.last_month_budget?e.last_month_budget:0,I=!1!==e.last_month_data_available,A=Rt($,n),L=Rt(x,n),k=m.delivery_condition||"all";
1if(!c[t]){const n=Array.isArray(e.schedule_delivery_days)?e.schedule_delivery_days:null,a=Array.isArray(m.delivery_days)?m.delivery_days:[],o="platform_schedule"===m.delivery_source||"all"===k&&0===a.length;"platform_schedule"===m.delivery_source&&a.length?c[t]=a.slice():o&&n&&n.length?c[t]=n.slice():c[t]=a.slice()}const F=c[t];let B=S;const D=be(t,k),M=F&&F.length?F.length:0,N=Number.isFinite($)&&$>0&&M>D&&Math.abs(Number(B)-$*M)<1,T=Number(e.lifetime_budget)>0&&Math.abs(Number(B)-Number(e.lifetime_budget))<1;let P=!0===e.is_fallback_budget||"true"===e.is_fallback_budget||!B||B<=0;(N||T)&&(P=!0,B=0),P&&(!B||B<=0)&&(B=$*D);const O=Rt(B,n),q=e.status||"ENABLED";let z="disabled";"ENABLED"===q?z="enabled":"PAUSED"===q&&(z="paused");const H=`<span class="status-dot ${z}"></span>`;let j=m.allocation_type||"auto",G=m.distribution_type||"equal";j.startsWith("boost")&&(G=j,j="auto");const V=document.createElement("tr");V.className="camp-dir-row",V.dataset.campId=t,V.dataset.platform=n;const W="custom"===k?"inline-block":"none";V.innerHTML=`\n                <td>${H}<span class="campaign-name-cell" title="${e.campaign_name}" style="display: inline-block; vertical-align: middle;">${e.campaign_name}</span></td>\n                <td>\n                    <select id="prod-type-${t}">\n                        <option value="search" ${"search"===p?"selected":""}>検索</option>\n                        <option value="pmax" ${"pmax"===p?"selected":""}>PMAX</option>\n                        <option value="video" ${"video"===p?"selected":""}>動画</option>\n                        <option value="display" ${"display"===p?"selected":""}>ディスプレイ</option>\n                    </select>\n                </td>\n                <td class="last-month-budget-cell prior-month-amount-cell" id="last-month-budget-${t}" data-fallback="${P}" data-media-amount="${B}">${formatDisplayCurrency(O)}</td>\n                <td class="prior-month-amount-cell" data-media-amount="${I?x:""}" data-unavailable="${!I}">${I?formatDisplayCurrency(L):'<span class="prior-month-unavailable" title="前月分のレポートを取得できませんでした。実績が0円だったわけではありません。再取得してください。">取得失敗</span>'}</td>\n                <td>\n                    <input type="number" id="current-budget-${t}" class="camp-current-budget" value="${Math.round(100*A)/100}" data-media-budget="${$}" placeholder="日予算" title="代理店モード時はクライアント換算で表示(保存時はネットに戻します)">\n                </td>\n                <td>\n                    <div class="alloc-setting-wrapper">\n                        <div style="display: flex; flex-direction: column; gap: 4px;">\n                            <select id="alloc-type-${t}" class="alloc-type-select" data-camp-id="${t}" style="width: 100%;">\n                                <option value="auto" ${"auto"===j?"selected":""}>自動</option>\n                                <option value="fixed" ${"fixed"===j?"selected":""}>固定</option>\n                            </select>\n                            <select id="dist-type-${t}" class="dist-type-select" data-camp-id="${t}" style="width: 100%;">\n                                <option value="equal" ${"equal"===G?"selected":""}>均等</option>\n                                <option value="boost_start" ${"boost_start"===G?"selected":""}>月初強化</option>\n                                <option value="boost_mid" ${"boost_mid"===G?"selected":""}>月中強化</option>\n                                <option value="boost_end" ${"boost_end"===G?"selected":""}>月末強化</option>\n                                <option value="boost_both" ${"boost_both"===G?"selected":""}>月末月初強化</option>\n                            </select>\n                            <div id="alloc-inputs-${t}" class="alloc-setting-row" style="display: flex; flex-direction: column; gap: 4px;">\n                                \x3c!-- 初期化されます --\x3e\n                            </div>\n                        </div>\n                    </div>\n                </td>\n                <td>\n                    <div class="alloc-setting-wrapper">\n                        <select id="delivery-cond-${t}" class="delivery-cond-select" data-camp-id="${t}">\n                            <option value="all" ${"all"===k?"selected":""}>全日</option>\n                            <option value="weekday" ${"weekday"===k?"selected":""}>土日祝除外</option>\n                            <option value="custom" ${"custom"===k?"selected":""}>
1カスタム</option>\n                        </select>\n                        <button type="button" class="btn btn-secondary btn-sm btn-calendar-trigger" id="btn-calendar-trigger-${t}" data-camp-id="${t}" data-camp-name="${e.campaign_name}" style="display: ${W}; margin-top: 4px; padding: 2px 6px; font-size: 0.75rem; width: 100%;">\n                            設定 (${F.length}日)\n                        </button>\n                    </div>\n                </td>\n            `,d.appendChild(V),R(t,j,G,m)}),o&&0===o.children.length){const H=t.platform_fetch_errors?.google,j=t.platform_fetch_warnings?.google,G=H||j||"Google 広告のキャンペーンはありません。";o.innerHTML=`<tr><td colspan="7" class="text-center text-muted">${G}</td></tr>`}if(i&&0===i.children.length){const V=t.platform_fetch_errors?.yahoo;i.innerHTML=`<tr><td colspan="7" class="text-center text-muted">${V||"Yahoo! 広告のキャンペーンはありません。"}</td></tr>`}if(r&&0===r.children.length&&(r.innerHTML='<tr><td colspan="7" class="text-center text-muted">Meta 広告のキャンペーンはありません。</td></tr>'),l&&0===l.children.length){const W=t.platform_fetch_errors?.microsoft;l.innerHTML=`<tr><td colspan="7" class="text-center text-muted">${W||"Microsoft 広告のキャンペーンはありません。"}</td></tr>`}s&&0===s.children.length&&(s.innerHTML='<tr><td colspan="7" class="text-center text-muted">Amazon 広告のキャンペーンはありません。</td></tr>'),document.querySelectorAll(".alloc-type-select").forEach(t=>{t.addEventListener("change",t=>{const n=t.target.dataset.campId,a=t.target.value,o=document.getElementById(`dist-type-${n}`),i=o?o.value:"equal",r=document.getElementById(`alloc-val-${n}`),l=document.getElementById(`alloc-range-${n}`);let d=r&&parseFloat(r.value)||0;"fixed"!==a||d>0||(d=function(t){const n=document.querySelector(`.camp-dir-row[data-camp-id="${t}"]`);let a=function(t,n){const a=document.querySelector(`.camp-dir-row[data-camp-id="${t}"]`);let o=a&&a.dataset.platform||n||"";if(!o&&e&&e.campaign_metadata){const n=e.campaign_metadata[t]||e.campaign_metadata[String(t)];o=n&&n.platform||""}if(!o&&a){const t=a.closest("table"),e=t&&t.id||"";/facebook/i.test(e)?o="facebook":/yahoo/i.test(e)?o="yahoo":/microsoft|ms-/i.test(e)?o="microsoft":/amazon/i.test(e)?o="amazon":/google/i.test(e)&&(o="google")}return String(o||"").toLowerCase()}(t,n&&n.dataset.platform||"");const o=document.getElementById(`current-budget-${t}`);let i=parseFloat(o&&o.dataset.mediaBudget),r="data-media-budget";if((!Number.isFinite(i)||i<=0)&&(i=parseFloat(o&&o.value)||0,r="input-display",document.getElementById("agency_mode")?.checked&&i>0)){const t=zt(a);i=jt(i,t.rate,t.type),r="input-display-to-media"}if(!(i>0)&&e&&e.campaign_metadata){const n=e.campaign_metadata[t]||e.campaign_metadata[String(t)];n&&(a||(a=String(n.platform||"").toLowerCase()),i=parseFloat(n.current_budget)||0,r="campaign_metadata")}const l=zt(a),d=Ht(i,l.rate,l.type),s=(c[t]||[]).filter(t=>{const e=J(),n=`${e.year}-${String(e.month).padStart(2,"0")}`;return String(t).startsWith(n)}).length,u=s>0?s:30;return Math.round(d*u)}(n)),R(n,a,i,{fixed_value:d||2e5,boost_weight:l?1+parseFloat(l.value)/100:1.5})})}),document.querySelectorAll(".dist-type-select").forEach(t=>{t.addEventListener("change",t=>{const e=t.target.dataset.campId,n=t.target.value,a=document.getElementById(`alloc-type-${e}`),o=a?a.value:"auto",i=document.getElementById(`alloc-val-${e}`),r=document.getElementById(`alloc-range-${e}`);R(e,o,n,{fixed_value:i?parseFloat(i.value)||0:2e5,boost_weight:r?1+parseFloat(r.value)/100:1.5})})}),document.querySelectorAll(".delivery-cond-select").forEach(t=>{t.addEventListener("change",t=>{const e=t.target.dataset.campId,n=document.getElementById(`btn-calendar-trigger-${e}`);"custom"===t.target.value?(n&&(n.style.display="inline-block"),K(e,t.target.closest("tr").querySelector(".campaign-name-cell").textContent)):n&&(n.style.display="none")})}),document.querySelectorAll(".btn-calendar-trigger").forEach(t=>{t.addEventListener("click",e=>{K(t.dataset.campId,t.dataset.campName)})}),document.querySelectorAll(".delivery-cond-select").forEach(t=>{t.addEventListener("change",t=>{we(t.target.dataset.campId)})}),document.querySelectorAll('.camp-dir-row input[id^="current-budget-"]').forEach(t=>{const e=t.id.replace("current-budget-",""),n=t.closest(".camp-dir-row"),a=n&&n.dataset.platform||"google";t.addEventListener("input",()=>{Gt(e,a),we(e)})})}function Ee(e,i={}){!0===i.skipLoadingOverlay||"function"!=typeof setChartLoading||setChartLoading("budgetChart",!0,"グラフを描画中...");const c=e.summary,d=e.daily_records,s=c.run_date,u=document.getElementById("agency_mode")?.checked||!1,m=window.isBlendedMediaTab(n)?{rate:0,type:"net"}:zt(n),p=u?m.rate:0,g=m.type||"net";function E(t){return Ht(t,p,g)}const I=d.map(t=>{const e=t.date.split("-");return`${e[1]}/${e[2]}`});let A,L=[],k=[],F=[];if(window.isBlendedMediaTab(n))"cumulative"===a?(L=d.map(t=>t.cum_plan_client),k=d.map(t=>t.cum_forecast_client),F=d.map(t=>t.date<s||t.date===s?t.cum_actual_client:null),A=c.total_client_budget):(L=d.map(t=>t.plan_client),k=d.map(t=>t.forecast_client),F=d.map(t=>t.date<s||t.date===s&&parseFloat(t.actual_client)>0?t.actual_client:null),A=void 0);else{let t=0,e=0,o=0;const i=d[0],c=[];
1Object.entries(i.campaigns).forEach(([t,e])=>{if(e.platform===n){if("yahoo"===n&&!ue(e))return;"all"!==r&&e.product_type!==r||"all"!==l&&t!==l||c.push(t)}});for(let n=0;n<d.length;n++){const i=d[n],r=i.date<s;let l=0,u=0,m=0;c.forEach(t=>{const e=i.campaigns[t]||{plan_media:0,actual_media:0,forecast_media:0};l+=e.plan_media,u+=e.actual_media,m+=e.forecast_media});const p=E(l),g=E(m),f=E(u);"cumulative"===a?(t+=p,L.push(t),o+=g,k.push(o),r?(e+=f,F.push(e)):i.date===s?F.push(e+f):F.push(null)):(L.push(p),k.push(g),r||i.date===s&&f>0?F.push(f):F.push(null))}A="cumulative"===a?L[L.length-1]:void 0}const B="final"===o?"(最終)":"(入札)",D=Bt(d),M=At(d,D),N="cvv"===M.mode;!function(t){const e=document.getElementById("budget-chart-metric-note");e&&t&&(t.cpaCost<=0&&t.roasCost<=0?e.textContent=`グラフ指標: ${t.metricLabel}`:e.textContent=`グラフ指標: ${t.metricLabel}(コスト加重: ROAS系 ${formatDisplayCurrency(t.roasCost)} / CPA系 ${formatDisplayCurrency(t.cpaCost)})`)}(M);const T=[],P=[];let O=0,q=0;d.forEach(t=>{const e=t.date<s,n=N?It(t,s,D,"actual")||0:Lt(t,s,D,"actual")||0,o=N?It(t,s,D,"forecast")||0:Lt(t,s,D,"forecast")||0;"cumulative"===a?((e||t.date===s)&&(O+=n),q+=o,e||t.date===s?T.push(O):T.push(null),P.push(q)):(T.push(e||t.date===s&&n>0?n:null),P.push(o))});const z=[{type:"line",label:"初期計画",data:L,yAxisID:"y",borderColor:"#94a3b8",borderWidth:2,fill:!1,pointRadius:0,order:3},{type:"line",label:"消化実績",data:F,yAxisID:"y",borderColor:"#3b82f6",borderWidth:3,backgroundColor:"#3b82f6",fill:!1,pointRadius:3,spanGaps:!1,order:4},{type:"line",label:"着地予測",data:k,yAxisID:"y",borderColor:"#10b981",borderWidth:2,borderDash:[5,5],fill:!1,pointRadius:2,order:5},{type:"bar",label:`実績${M.metricLabel}${B}`,data:T,yAxisID:"y1",backgroundColor:"rgba(239, 68, 68, 0.35)",borderColor:"#ef4444",borderWidth:2,borderRadius:3,order:1},{type:"bar",label:`予測${M.metricLabel}${B}`,data:P,yAxisID:"y1",backgroundColor:"rgba(59, 130, 246, 0.35)",borderColor:"#3b82f6",borderWidth:2,borderRadius:3,order:2}],H=document.getElementById("budgetChart").getContext("2d");t&&(function(){const t=document.getElementById("allocator-chart-tooltip");t&&(t.style.opacity="0")}(),t.destroy());const j=function(t,e){const a=[];if(!(Array.isArray(t)&&t.length&&Array.isArray(e)&&e.length))return a;const o=(()=>{const e=String(t[0]&&t[0].date||"").match(/^(\d{4})/);return e?Number(e[1]):(new Date).getFullYear()})(),i={},r={};t.forEach((t,e)=>{const n=_(t.date||t.date_iso,o);if(n){i[n]=e;const t=n.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);t&&(r[`${parseInt(t[2],10)}/${parseInt(t[3],10)}`]=e,r[`${String(t[2]).padStart(2,"0")}/${String(t[3]).padStart(2,"0")}`]=e)}const a=String(t.date||"").trim();a&&(r[a]=e)});const c=new Set;return function(t){let e=Array.isArray(t)?t.slice():[];if(n&&"total"!==n&&(e=e.filter(t=>{const e=S(t);return!e||e===n})),l&&"all"!==l){const t=String(l),n=h(t);e=e.filter(e=>{const a=String(e.campaign_id||"").trim();if(a){const t=h(a);for(const e of t)if(n.has(e))return!0}const o=String(e.campaign_name||"").trim();return!a&&o&&(o.includes(t)||t.includes(o))})}return e}(e).forEach(t=>{const e=(t=>{if(!t)return;if(void 0!==i[t])return i[t];const e=t.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);if(!e)return;const n=`${parseInt(e[2],10)}/${parseInt(e[3],10)}`;if(void 0!==r[n])return r[n];const a=`${String(e[2]).padStart(2,"0")}/${String(e[3]).padStart(2,"0")}`;return r[a]})(_(t.date_iso||t.date,o));if(void 0===e)return;const n=function(t){const e=t.change_type||"予算変更",n=t.old_value||"—",a=t.new_value||"",o=t.campaign_name?` [${t.campaign_name}]`:"";return a?`${e}: ${n} → ${a}${o}`:`${e}: ${n}${o}`}(t),l=S(t),d=`${e}|${l}|${n}`;c.has(d)||(c.add(d),l&&x(l),a.push({index:e,source:b(t.source)?"agent":"manual",label:n,platform:l}))}),a}(d,f),R=function(t,e){const n=Array.isArray(t)?t:[],a={};return n.forEach(t=>{a[t.index]||(a[t.index]=[]),a[t.index].push(t)}),{id:e||"allocatorChangeLines",afterDraw(t){const{ctx:e,chartArea:o,scales:i}=t,r=i&&i.x;if(!r||!o||!n.length)return;const{top:l,bottom:c}=o;
1e.save(),Object.keys(a).forEach(t=>{const n=Number(t),o=a[n]||[];if(!o.length)return;const i=function(t,e){return window.chartXForDataIndex(t,e)}(r,n);if(!Number.isFinite(i))return;const d=o.some(t=>"agent"===t.source),s=C.filter(t=>o.some(e=>e.platform===t));let u=d?"rgba(59, 130, 246, 0.4)":"rgba(245, 158, 11, 0.4)";1===s.length&&v[s[0]]&&(u=`${v[s[0]]}66`),e.strokeStyle=u,e.lineWidth=1.5,e.setLineDash([5,4]),e.beginPath(),e.moveTo(i,l),e.lineTo(i,c),e.stroke(),e.setLineDash([]);const m=(s.length?s.map(t=>({platform:t,img:x(t)})):[]).filter(t=>t.img&&t.img.complete&&t.img.naturalWidth>0);if(m.length){let t=i-(12*m.length+2*(m.length-1))/2;const n=l-12-4;m.forEach(a=>{try{e.drawImage(a.img,t,n,12,12)}catch(t){}t+=14})}else{const t=d?window.siranuiCssColor?window.siranuiCssColor("--accent-info","#60a5fa"):"#60a5fa":window.siranuiCssColor?window.siranuiCssColor("--accent-amber","#fbbf24"):"#fbbf24";e.fillStyle=t,e.font="bold 9px sans-serif",e.textAlign="center",e.fillText(d?"siranui AI":"手動",i,l-6)}const p=o.length,g=c-8,f=2.5+.8*p;if(e.beginPath(),e.arc(i,g,f,0,2*Math.PI),e.fillStyle=p>=3?"#ef4444":1===s.length&&v[s[0]]?v[s[0]]:"#3b82f6",e.fill(),p>=3){const t=Date.now(),n=f+5+3*Math.sin(t/150),a=.4-.2*Math.sin(t/150);e.beginPath(),e.arc(i,g,n,0,2*Math.PI),e.fillStyle=`rgba(239, 68, 68, ${a})`,e.fill()}}),e.restore()}}}(j,"allocatorChangeLines"),G="function"==typeof window.createChangeMarkerInteractionPlugin?window.createChangeMarkerInteractionPlugin({id:"allocatorChangeMarkerInteraction",getMarkers(){const t={};return j.forEach(e=>{t[e.index]=(t[e.index]||0)+1}),Object.keys(t).map(e=>({index:Number(e),count:t[e]}))}}):null,V=[{id:"horizontalLine",afterDraw:function(t){if(void 0!==A&&A>0){var e=t.scales.y,n=t.scales.x,a=e.getPixelForValue(A),o=t.ctx;o.save(),o.beginPath(),o.moveTo(n.left,a),o.lineTo(n.right,a),o.strokeStyle="#ef4444",o.lineWidth=1.5,o.setLineDash([5,5]),o.stroke(),o.fillStyle="#ef4444",o.font="bold 10px sans-serif",o.fillText("Target Limit: ¥"+formatDisplayNum(A),n.left+5,a-5),o.restore()}}},R];G&&V.push(G),t=new Chart(H,{type:"line",data:{labels:I,datasets:z},options:{responsive:!0,maintainAspectRatio:!1,layout:{padding:{top:j.length?18:0}},interaction:{mode:"index",intersect:!1},plugins:{legend:{display:!1},tooltip:{enabled:!1,external:t=>function(t,e){const{chart:n,tooltip:a}=t;let o=document.getElementById("allocator-chart-tooltip");if(o||(o=document.createElement("div"),o.id="allocator-chart-tooltip",o.className="allocator-chart-tooltip",document.body.appendChild(o)),!a||0===a.opacity)return void(o.style.opacity="0");const i=(a.title||[]).slice(),r=(a.body||[]).map(t=>(t.lines||[]).join(" ")).filter(Boolean),l=a.dataPoints&&a.dataPoints[0]?a.dataPoints[0].dataIndex:void 0,c=Number.isFinite(l)?(e||[]).filter(t=>t.index===l):[];let d="";i.length&&(d+=`<div class="allocator-chart-tooltip-title">${i.map(t=>String(t)).join("<br>")}</div>`),r.forEach(t=>{d+=`<div class="allocator-chart-tooltip-row">${String(t)}</div>`}),c.length&&(d+='<div class="allocator-chart-tooltip-changes-head">実施された施策</div>',c.forEach(t=>{const e=t.platform?function(t,e=12){if("function"==typeof window.renderMediaLogoHtml)return window.renderMediaLogoHtml(t,{size:e,className:"allocator-change-tip-logo",title:!1});const n=$(t),a=w[t]||t;return n?`<img src="${n}" alt="${a}" class="allocator-change-tip-logo" style="width:${e}px;height:${e}px;object-fit:contain;vertical-align:middle;">`:a?`<span>${a}</span>`:""}(t.platform,12):"";d+=`<div class="allocator-chart-tooltip-change">${e}<span>${String(t.label||"")}</span></div>`})),o.innerHTML=d;const s=n.canvas.getBoundingClientRect(),u=s.left+window.scrollX+a.caretX,m=s.top+window.scrollY+a.caretY;o.style.opacity="1",o.style.left=`${u}px`,o.style.top=`${m}px`}(t,j),callbacks:{label:function(t){let e=t.dataset.label||"";return e&&(e+=": "),null!==t.parsed.y&&("y1"===t.dataset.yAxisID?e+="function"==typeof window.formatCvValue?window.formatCvValue(t.parsed.y):Math.round(t.parsed.y).toLocaleString():e+=formatDisplayCurrency(t.parsed.y)),e}}}},scales:{x:{grid:{color:window.siranuiCssColor?window.siranuiCssColor("--chart-grid","rgba(15,23,42,0.08)"):"rgba(15,23,42,0.08)"},ticks:{color:window.siranuiCssColor?window.siranuiCssColor("--chart-tick","#64748b"):"#64748b",font:{size:10}}},y:{position:"left",grid:{color:window.siranuiCssColor?window.siranuiCssColor("--chart-grid","rgba(15,23,42,0.08)"):"rgba(15,23,42,0.08)"},ticks:{color:window.siranuiCssColor?window.siranuiCssColor("--chart-tick","#64748b"):"#64748b",font:{size:10},callback:function(t){return formatDisplayCurrency(t)}}},y1:{position:"right",grid:{drawOnChartArea:!1},ticks:{color:window.siranuiCssColor("--accent-info","#60a5fa"),font:{size:10},callback:function(t){return"function"==typeof window.formatCvValue?window.formatCvValue(t):Math.round(t).toLocaleStr
1ing()}},title:{display:!0,text:"final"===o?`最終${M.metricLabel}`:`入札${M.metricLabel}`,color:window.siranuiCssColor("--accent-info-soft","#93c5fd"),font:{size:11}}}}},plugins:V}),j.some(t=>j.filter(e=>e.index===t.index).length>=3)?function(){y&&(cancelAnimationFrame(y),y=null);let e=0;y=requestAnimationFrame(function n(a){t&&(a-e>60&&(t.render(),e=a),y=requestAnimationFrame(n))})}():y&&(cancelAnimationFrame(y),y=null),"function"==typeof setChartLoading&&setChartLoading("budgetChart",!1)}function $e(t){if(!t)return null;const e=parseFloat(t.recommended_media);if(Number.isFinite(e)&&e>0)return e;for(const e of["computed_budget","query_considered_budget","proposed_budget"]){const n=parseFloat(t[e]);if(Number.isFinite(n)&&n>0)return n}return null}function xe(t,e=!1){if(!t)return'<span class="text-muted">--</span>';const n=parseFloat(t.spend_factor);if(!Number.isFinite(n)||n<=0)return'<span class="text-muted">--</span>';let a=t.spend_factor_source||"default";if("measured"===a&&(a="month_average"),"none"===a)return'<span class="text-muted">--</span>';let o="",i="";if("daily"===a)o="当日の実績 ÷ 設定日予算(掲載実績日のみ)",i="日次";else if("budget_change"===a)o="予算変更日: 実績 ÷ 当日の設定日予算(月内平均からは除外)",i="変更日";else if("month_average"===a){const e=parseInt(t.spend_factor_sample_days,10);o=Number.isFinite(e)&&e>0?`当月の掲載実績 ${e} 日の平均(未来日の参考値)`:"当月の掲載実績日の平均(未来日の参考値)",i="月内平均"}else"default"===a?(o="掲載実績日が不足しているため k=1.00 を使用",i="既定"):(o=e?"過去日の消化係数(実績÷設定日予算)":"未来日の参考消化係数(月内平均)",i=e?"日次":"月内平均");return`<span class="currency-value"${o?` title="${o}"`:""}>${n.toFixed(2)}<br><span class="compact-th-sub" style="font-size:0.72rem;color:var(--text-secondary);">${i}</span></span>`}function Se(t,a,i={}){const c=document.querySelector("#detail-table thead"),s=!0===i.deferClear,u=s?document.createDocumentFragment():null,m=t=>{u?u.appendChild(t):ft.appendChild(t)},p=()=>{u&&ft.replaceChildren(u)};if(s||(ft.innerHTML=""),!t||0===t.length)return c.innerHTML="",void(ft.innerHTML='<tr><td class="text-center text-muted">データがありません。</td></tr>');const g=document.getElementById("detail-table-cost-type"),f=g?g.value:"client",y={};if(t&&t.length>0){function _(t,e,n){const a=Math.max(0,n-1);if(a<=0)return 1;const o=t.split("-"),i=parseInt(o[0],10),r=parseInt(o[1],10),l=parseInt(o[2],10),c=new Date(i,r,0).getDate(),d=(c+1)/2;return"boost_end"===e||"boost_end_only"===e?1+a*((l-1)/(c-1)):"boost_start"===e||"boost_start_only"===e?1+a*((c-l)/(c-1)):"boost_mid"===e?l<=d?d>1?1-a+2*a*((l-1)/(d-1)):1+a:c>d?1+a-2*a*((l-d)/(c-d)):1-a:"boost_both"===e?l<=d?d>1?1+a-2*a*((l-1)/(d-1)):1-a:c>d?1-a+2*a*((l-d)/(c-d)):1+a:1}t.forEach(t=>{const e=t.date<a;Object.entries(t.campaigns).forEach(([t,n])=>{y[t]||(y[t]={plan_sum:0,actual_sum:0,cond:"all"});let a=.2,o="net",i=.2,r="net",l=0,c="net",s=.2,u="net",m=.2,p="net";if(document.getElementById("agency_mode")?.checked){if(d&&d.platforms){const t=d.platforms.google||{};a=void 0!==t.margin_rate?t.margin_rate:.2,o=t.margin_type||"net";const e=d.platforms.yahoo||{};i=void 0!==e.margin_rate?e.margin_rate:.2,r=e.margin_type||"net";const n=d.platforms.facebook||{};l=void 0!==n.margin_rate?n.margin_rate:0,c=n.margin_type||"net";const g=d.platforms.microsoft||{};s=void 0!==g.margin_rate?g.margin_rate:.2,u=g.margin_type||"net";const f=d.platforms.amazon||{};m=void 0!==f.margin_rate?f.margin_rate:.2,p=f.margin_type||"net"}}else a=0,i=0,l=0,s=0,m=0;function g(t,e){if("net"===f)return t;let n=0,d="net";return"google"===e?(n=a,d=o):"yahoo"===e?(n=i,d=r):"facebook"===e?(n=l,d=c):"microsoft"===e?(n=s,d=u):"amazon"===e&&(n=m,d=p),"net"===d?t/(1-n):t*(1+n)}y[t].plan_sum+=g(n.plan_media||0,n.platform),e&&(y[t].actual_sum+=g(n.actual_media||0,n.platform))})}),Object.keys(y).forEach(e=>{let n="google";for(let a of t)if(a.campaigns[e]){n=a.campaigns[e].platform;break}const o=document.getElementById(`dist-type-${e}`);let i="equal";if(o)i=o.value;else if(d&&d.platforms&&d.platforms[n]){const t=(d.platforms[n].campaign_configs||{})[e]||{},a=t.allocation_type||"auto",o=t.distribution_type||"equal";i=a.startsWith("boost")?a:o}let r=1.5;const l=document.getElementById(`alloc-range-${e}`);if(l)r=1+parseFloat(l.value)/100;else if(d&&d.platforms&&d.platforms[n]){const t=(d.platforms[n].campaign_configs||{})[e]||{};r=void 0!==t.boost_weight?parseFloat(t.boost_weight):1.5}const c=document.getElementById(`delivery-cond-${e}`);let s="all";if(c)s=c.value;else if(d&&d.platforms&&d.platforms[n]){const t=(d.platforms[n].campaign_configs||{})[e]||{};s=t.delivery_condition||"all"}y[e].cond=s,y[e].distType=i,y[e].boostWeight=r;let u=0;t.forEach(t=>{t.date>=a&&ve(e,s,t.date)&&(u+=_(t.date,i,r))}),y[e].total_future_weight=u,y[e].raw_remaining_budget=Math.max(0,y[e].plan_sum-y[e].actual_sum)});let $=0;
1Object.keys(y).forEach(t=>{$+=y[t].raw_remaining_budget});let x=null;if("net"!==f&&void 0!==e&&e&&e.summary&&(x=parseFloat(e.summary.remaining_client_budget)),null===x||isNaN(x)){let I=0,A=0;Object.keys(y).forEach(t=>{I+=y[t].plan_sum,A+=y[t].actual_sum}),x=Math.max(0,I-A)}const S=null!==x&&!isNaN(x)&&$>x?x/$:1;Object.keys(y).forEach(t=>{y[t].remaining_budget=y[t].raw_remaining_budget*S})}const h="final"===o?"(最終)":"(入札)",b=Bt(t),w=At(t,b),v=`CV/CVV${h}`;if(window.isBlendedMediaTab(n)){const L="net"===f?"(ネット)":"(クライアント)";c.innerHTML="function"==typeof window.buildBlendedDailyDetailHeaderRow?window.buildBlendedDailyDetailHeaderRow(L,h):`\n                <tr>\n                    <th>日付</th>\n                    <th>計画${L}</th>\n                    <th>調整値${L}</th>\n                    <th>設定日予算${L}</th>\n                    <th>実績${L}</th>\n                    <th>着地予測${L}</th>\n                    <th>実績${v}</th>\n                    <th>予測${v}</th>\n                    <th>参照CPA/ROAS</th>\n                    <th>配信推奨${L}</th>\n                </tr>\n            `;let k=0,F=0,B=0,D=0,M=0,N=0,T=0,P=0,O=0,q=0,z=0,R=0,G=0;t.forEach(t=>{const e=document.createElement("tr"),n=t.date<a,o=n||t.date===a&&t.actual_client>0;o&&formatDisplayCurrency(t.actual_client);let i=0,r=0,l=0,c=0,s=0,u=0,p=0,g=.2,h="net",b=.2,v="net",C=0,E="net",$=.2,x="net",S=.2,I="net";if(document.getElementById("agency_mode")?.checked){if(d&&d.platforms){const t=d.platforms.google||{};g=void 0!==t.margin_rate?t.margin_rate:.2,h=t.margin_type||"net";const e=d.platforms.yahoo||{};b=void 0!==e.margin_rate?e.margin_rate:.2,v=e.margin_type||"net";const n=d.platforms.facebook||{};C=void 0!==n.margin_rate?n.margin_rate:0,E=n.margin_type||"net";const a=d.platforms.microsoft||{};$=void 0!==a.margin_rate?a.margin_rate:.2,x=a.margin_type||"net";const o=d.platforms.amazon||{};S=void 0!==o.margin_rate?o.margin_rate:.2,I=o.margin_type||"net"}}else g=0,b=0,C=0,$=0,S=0;Object.entries(t.campaigns).forEach(([e,a])=>{let o=0,d=0;const m=y[e];if(m&&m.total_future_weight>0){const i=ve(e,m.cond,t.date);if(!n&&i){const e=_(t.date,m.distType,m.boostWeight);o=m.remaining_budget*(e/m.total_future_weight)}if(i){const t=$e(a);null!==t&&(d=function(t,e){let n=0,a="net";return"google"===e?(n=g,a=h):"yahoo"===e?(n=b,a=v):"facebook"===e?(n=C,a=E):"microsoft"===e?(n=$,a=x):"amazon"===e&&(n=S,a=I),"net"===a?t/(1-n):t*(1+n)}(t,a.platform))}}u+=o,p+=d,"google"===a.platform?i+=d:"yahoo"===a.platform?r+=d:"facebook"===a.platform?l+=d:"microsoft"===a.platform?c+=d:"amazon"===a.platform&&(s+=d)});let A=0,L=0,V=0,W=0;"net"===f?Object.entries(t.campaigns).forEach(([t,e])=>{A+=e.plan_media||0,o&&(L+=e.actual_media||0),V+=e.forecast_media||0;let n=e.budget_media;void 0===n&&(n=e.current_budget||0),W+=n}):(A=t.plan_client||0,L=o&&t.actual_client||0,V=t.forecast_client||0,W=t.budget_client||0),k+=A,F+=L,B+=V,D+=u,M+=W,G+=p;const U=kt(t,a,null,"actual",w.mode),Y=kt(t,a,null,"forecast",w.mode);null!=U&&(N+=U),T+=Y||0,P+=i,O+=r,q+=l,z+=c,R+=s;const{isSat:J,isSunOrHoliday:X}=j(t.date),Z=H(t.date);J&&(e.className="sat-row"),X&&(e.className="sun-holiday-row"),t.date===a&&e.classList.add("table-today");const K=n?'<span class="text-muted">--</span>':`${formatDisplayCurrency(u)}`,Q=p<=0?'<span class="text-muted">--</span>':`${formatDisplayCurrency(p)}`,tt=o?`${formatDisplayCurrency(L)}`:'<span class="text-muted">--</span>',et=wt(U,!o,w.mode),nt=wt(Y,!1,w.mode);e.innerHTML=`\n                    <td>${t.date} (${Z})</td>\n                    <td>${formatDisplayCurrency(A)}</td>\n                    <td>${K}</td>\n                    <td>${formatDisplayCurrency(W)}</td>\n                    <td>${tt}</td>\n                    <td>${formatDisplayCurrency(V)}</td>\n                    <td>${et}</td>\n                    <td>${nt}</td>\n                    <td><span class="text-muted">--</span></td>\n                    <td>${Q}</td>\n                `,m(e)});const V=document.createElement("tr");V.className="total-row",V.innerHTML=`\n                <td>合計</td>\n                <td>${formatDisplayCurrency(k)}</td>\n                <td>${formatDisplayCurrency(D)}</td>\n                <td>${formatDisplayCurrency(M)}</td>\n                <td>${formatDisplayCurrency(F)}</td>\n                <td>${formatDisplayCurrency(B)}</td>\n                <td>${wt(N,!1,w.mode)}</td>\n                <td>${wt(T,!1,w.mode)}</td>\n                <td><span class="text-muted">--</span></td>\n                <td>${G>0?formatDisplayCurrency(G):'<span class="text-muted">--</span>'}</td>\n            `,m(V),p()}else{const W=t[0],U=[];
1Object.entries(W.campaigns).forEach(([t,e])=>{if(e.platform===n){if("yahoo"===n&&!ue(e))return;"all"!==r&&e.product_type!==r||U.push({id:t,name:e.campaign_name,productType:e.product_type||"search",allocationType:e.allocation_type||"auto"})}});const Y="net"===f?"(ネット)":"(クライアント)",J=11,X=()=>"function"==typeof window.buildPlatformDailyDetailHeaderRow?window.buildPlatformDailyDetailHeaderRow(Y,h):`\n                <tr>\n                    <th>日付</th>\n                    <th>計画${Y}</th>\n                    <th>調整値${Y}</th>\n                    <th>設定日予算${Y}</th>\n                    <th>実績${Y}</th>\n                    <th>着地予測${Y}</th>\n                    <th>実績${v}</th>\n                    <th>予測${v}</th>\n                    <th>参照CPA/ROAS</th>\n                    <th>配信推奨${Y}</th>\n                    <th>消化係数 k<br><span class="compact-th-sub">(過去:日次/未来:月内平均)</span></th>\n                </tr>\n            `;if(0===U.length)return c.innerHTML=X(),void(ft.innerHTML=`\n                    <tr>\n                        <td>--</td>\n                        <td colspan="${J-1}" class="text-center text-muted">該当するキャンペーンのデータがありません。</td>\n                    </tr>\n                `);c.innerHTML=X();let Z=0,K="net";if(document.getElementById("agency_mode")?.checked){const et=zt(n);Z=et.rate,K=et.type}function C(t){return"net"===f?t:Ht(t,Z,K)}function E(t,e,o,i){const r=e.campaigns[t]||{plan_media:0,actual_media:0,forecast_media:0,budget_media:0},l=i||("roas"===vt(r)?"cvv":"cv"),c=function(t){return y[t]?y[t].cond:d&&d.platforms&&d.platforms[n]&&((d.platforms[n].campaign_configs||{})[t]||{}).delivery_condition||"all"}(t),s=ve(t,c,e.date);let u=r.plan_media||0,m=r.actual_media||0,p=r.forecast_media||0,g=r.budget_media;void 0===g&&(g=r.current_budget||0),o||s||(u=0,p=0);const f=C(u),h=C(m),b=C(p),w=C(g);let v=0,E=0,$=!1;if(s){if(!o){const n=y[t];if(n&&n.total_future_weight>0){const t=_(e.date,n.distType,n.boostWeight);v=n.remaining_budget*(t/n.total_future_weight)}}const n=$e(r);null!==n&&($=!0,E=C(n))}const x=o||e.date===a&&h>0;let S=null,I=0;return o&&(S=Ft(r,"actual",l)),o&&!s||(I=Ft(r,"forecast",l)||0),{p_plan_client:f,p_actual_client:h,p_forecast_client:b,p_budget_client:w,p_adj_client:v,p_rec_client:E,p_actual_conversion:S,p_forecast_conversion:I,cpa_roas_ref:St(r),hasRecommendation:$,hasActual:x}}const Q="all"===l,tt=Q?U:U.filter(t=>t.id===l);if(!Q&&0===tt.length)return void(ft.innerHTML=`\n                    <tr>\n                        <td>--</td>\n                        <td colspan="${J-1}" class="text-center text-muted">該当するキャンペーンのデータがありません。</td>\n                    </tr>\n                `);if(Q){let nt=0,at=0,ot=0,it=0,rt=0,lt=0,ct=0,dt=0;const st=U.map(t=>t.id);t.forEach(t=>{const e=document.createElement("tr"),n=t.date<a;let o=0,i=0,r=0,l=0,c=0,d=0,s=!1;U.forEach(e=>{const a=E(e.id,t,n,w.mode);o+=a.p_plan_client,r+=a.p_forecast_client,l+=a.p_budget_client,c+=a.p_adj_client,d+=a.p_rec_client,a.hasActual&&(s=!0,i+=a.p_actual_client)});const u=kt(t,a,st,"actual",w.mode),p=kt(t,a,st,"forecast",w.mode);nt+=o,ot+=r,rt+=l,it+=c,lt+=d,at+=s?i:0,null!=u&&(ct+=u),dt+=p||0;const{isSat:g,isSunOrHoliday:f}=j(t.date),y=H(t.date);g&&(e.className="sat-row"),f&&(e.className="sun-holiday-row"),t.date===a&&e.classList.add("table-today");const _=n?'<span class="text-muted">--</span>':`${formatDisplayCurrency(c)}`,h=d<=0?'<span class="text-muted">--</span>':`${formatDisplayCurrency(d)}`,b=s?`${formatDisplayCurrency(i)}`:'<span class="text-muted">--</span>';e.innerHTML=`\n                        <td>${t.date} (${y})</td>\n                        <td>${formatDisplayCurrency(o)}</td>\n                        <td>${_}</td>\n                        <td>${formatDisplayCurrency(l)}</td>\n                        <td>${b}</td>\n                        <td>${formatDisplayCurrency(r)}</td>\n                        <td>${wt(u,!s,w.mode)}</td>\n                        <td>${wt(p,!1,w.mode)}</td>\n                        <td><span class="text-muted">--</span></td>\n                        <td>${h}</td>\n                        <td>${function(t,e,n){if(!t||!e||!e.length)return xe(null,n);const a=t.campaigns||{};let o=0,i=0,r=!1,l=n?"daily":"month_average",c=0;return e.forEach(t=>{const e=a[t];
1if(!e)return;const n=parseFloat(e.spend_factor);if(!Number.isFinite(n)||n<=0)return;let d=e.spend_factor_source||"default";if("measured"===d&&(d="month_average"),"none"===d)return;r=!0;const s=parseFloat(e.forecast_media)||parseFloat(e.plan_media)||parseFloat(e.last_month_cost)||1;o+=n*s,i+=s,"daily"!==d&&"budget_change"!==d||(l=d);const u=parseInt(e.spend_factor_sample_days,10);Number.isFinite(u)&&u>c&&(c=u)}),xe(!r||i<=0?null:{spend_factor:o/i,spend_factor_source:l,spend_factor_sample_days:c},n)}(t,st,n)}</td>\n                    `,m(e)});const ut=document.createElement("tr");return ut.className="total-row",ut.innerHTML=`\n                    <td>合計</td>\n                    <td>${formatDisplayCurrency(nt)}</td>\n                    <td>${formatDisplayCurrency(it)}</td>\n                    <td>${formatDisplayCurrency(rt)}</td>\n                    <td>${formatDisplayCurrency(at)}</td>\n                    <td>${formatDisplayCurrency(ot)}</td>\n                    <td>${wt(ct,!1,w.mode)}</td>\n                    <td>${wt(dt,!1,w.mode)}</td>\n                    <td><span class="text-muted">--</span></td>\n                    <td>${lt>0?formatDisplayCurrency(lt):'<span class="text-muted">--</span>'}</td>\n                    <td><span class="text-muted">--</span></td>\n                `,m(ut),void p()}tt.forEach(e=>{const n="roas"===vt(t[0]?.campaigns?.[e.id]||{})?"cvv":"cv";let o=0,i=0,r=0,l=0,c=0,d=0,s=0,u=0;t.forEach(t=>{const p=document.createElement("tr"),g=t.date<a,f=t.campaigns?.[e.id]||{},y=E(e.id,t,g,n);o+=y.p_plan_client,r+=y.p_forecast_client,d+=y.p_budget_client,l+=y.p_adj_client,c+=y.p_rec_client,i+=y.hasActual?y.p_actual_client:0,null!=y.p_actual_conversion&&(s+=y.p_actual_conversion),u+=y.p_forecast_conversion||0;const{isSat:_,isSunOrHoliday:h}=j(t.date),b=H(t.date);_&&(p.className="sat-row"),h&&(p.className="sun-holiday-row"),t.date===a&&p.classList.add("table-today");const w=g?'<span class="text-muted">--</span>':`${formatDisplayCurrency(y.p_adj_client)}`,v=y.hasRecommendation?`${formatDisplayCurrency(y.p_rec_client)}`:'<span class="text-muted">--</span>',C=y.hasActual?`${formatDisplayCurrency(y.p_actual_client)}`:'<span class="text-muted">--</span>';p.innerHTML=`\n                        <td>${t.date} (${b})</td>\n                        <td>${formatDisplayCurrency(y.p_plan_client)}</td>\n                        <td>${w}</td>\n                        <td>${formatDisplayCurrency(y.p_budget_client)}</td>\n                        <td>${C}</td>\n                        <td>${formatDisplayCurrency(y.p_forecast_client)}</td>\n                        <td>${wt(y.p_actual_conversion,!y.hasActual,n)}</td>\n                        <td>${wt(y.p_forecast_conversion,!1,n)}</td>\n                        <td>${y.cpa_roas_ref}</td>\n                        <td>${v}</td>\n                        <td>${xe(f,g)}</td>\n                    `,m(p)});const p=document.createElement("tr");p.className="total-row",p.innerHTML=`\n                    <td>合計</td>\n                    <td>${formatDisplayCurrency(o)}</td>\n                    <td>${formatDisplayCurrency(l)}</td>\n                    <td>${formatDisplayCurrency(d)}</td>\n                    <td>${formatDisplayCurrency(i)}</td>\n                    <td>${formatDisplayCurrency(r)}</td>\n                    <td>${wt(s,!1,n)}</td>\n                    <td>${wt(u,!1,n)}</td>\n                    <td><span class="text-muted">--</span></td>\n                    <td>${c>0?formatDisplayCurrency(c):'<span class="text-muted">--</span>'}</td>\n                    <td><span class="text-muted">--</span></td>\n                `,m(p)}),p()}}function Ie(t){const e=document.getElementById("budget-opt-notification-banner");if(!e)return;if(!t||!t.daily_records||!t.summary)return void e.classList.add("hidden");const n=t.summary.run_date,a=t.daily_records.find(t=>t.date===n);if(!a)return void e.classList.add("hidden");let o=!1;const i=t.summary?.monthly_budget_guard||{};for(const[t,e]of Object.entries(a.campaigns)){if("fixed"===e.allocation_type)continue;const t=e.budget_guard_proposal,n=e.budget_change_purpose||i.purpose;if(null!=t&&n&&Math.abs(t-(e.current_budget||0))>1){o=!0;break}}const r="function"==typeof window.isOptimizerProposalApproved&&window.isOptimizerProposalApproved(window.lastOptimizerApprovalSnapshot?.optimizerStatus);o&&!r?e.classList.remove("hidden"):e.classList.add("hidden")}ne&&ne.addEventListener("click",()=>{ce()}),window.cvGroups=window.cvGroups||[],window.isPlatformLinkedForActiveGroup=me,window.isCampaignInCvGroup=pe,window.isCampaignInSelectedCvGroup=function(t,e,n){return pe(t,e,n,window.selectedCvGroupId)},document.addEventListener("siranui:cv-group-changed",()=>{e&&_e(e,!0)}),window.addEventListener("siranui:jst-date-changed",()=>{e=null}),window.checkBudgetOptimizerProposalNotification=Ie,window.proposalHandlers&&(window.proposalHandlers.budget={showDetail
1s:async function(){window.OptimizerProposalView?await window.OptimizerProposalView.show({title:"💰 予算配分最適化エージェントの最適化提案",forceRefresh:!1,onApprove:window.proposalHandlers.budget.approve,onReject:async function(){const t=document.getElementById("budget-opt-notification-banner");t&&t.classList.add("hidden")}}):alert("提案ビューが読み込まれていません。")},approve:async function(){if("function"==typeof window.canApproveOptimizerProposalNow&&!window.canApproveOptimizerProposalNow(window.lastOptimizerApprovalSnapshot?.optimizerStatus)){const t="function"==typeof window.getOptimizerApprovalBlockedNotice?window.getOptimizerApprovalBlockedNotice(window.lastOptimizerApprovalSnapshot?.optimizerStatus):"本番適用開始後に承認できます。";return void("function"==typeof window.showPremiumToast?window.showPremiumToast(t,"warning"):alert(t))}if("function"!=typeof window.submitAutoOptimizationApproval){const t="承認機能を読み込めませんでした。ページを再読み込みしてからお試しください。";return void("function"==typeof window.showPremiumToast?window.showPremiumToast(t,"error"):alert(t))}await window.submitAutoOptimizationApproval(null)}}),window.loadConfig=se,window.loadBudgetOptimizerConfig=se,window.runSimulation=he,window.invalidateSimulationCache=ee,window.checkBudgetAgentContract=checkBudgetAgentContract}),window.checkBudgetAgentContract=checkBudgetAgentContract;

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.