/* ════════════════════════════════════════════════════════════════ PCHS — National Safety and Quality Primary and Community Healthcare Standards ════════════════════════════════════════════════════════════════ */ (function () { 'use strict'; var PC = window.portalContext || {}; var config = { fee: parseFloat(PC.pchsFee) || 0, surchargeRate: parseFloat(PC.pchsSurchargeRate) || 0.01927, gstRate: parseFloat(PC.pchsGSTRate) || 0.10, contactTypeId: PC.contactTypeId || '', businessId: PC.businessId || '' }; var STEPS = 6; var STEP_LABELS = ['Contact', 'Scope', 'Services', 'Info', 'Assessment', 'Authorisation']; var currentStep = 1; var isBusy = false; var sigCtx = null; var sigDrawing = false; var leadId = null; var leadRef = null; var evidenceId = null; var accountId = null; var SK = { leadId: 'pchs_registration_lead_id', leadRef: 'pchs_registration_lead_ref', evidence: 'pchs_registration_evidence_id', accountId: 'pchs_registration_account_id', inProgress: 'pchs_payment_in_progress' }; function injectSpinner() { if (document.getElementById('pchs-spinner-overlay')) return; var style = document.createElement('style'); style.textContent = '@keyframes pchs-spin{to{transform:rotate(360deg)}}#pchs-spinner-overlay{display:none;position:fixed;inset:0;background:rgba(29,47,67,.65);z-index:99999;align-items:center;justify-content:center;flex-direction:column;gap:18px;}'; document.head.appendChild(style); var o = document.createElement('div'); o.id = 'pchs-spinner-overlay'; o.innerHTML = '
Please wait\u2026
'; document.body.appendChild(o); } function setBusy(busy, msg) { isBusy = busy; var o = document.getElementById('pchs-spinner-overlay'); var m = document.getElementById('pchs-spinner-msg'); if (o) o.style.display = busy ? 'flex' : 'none'; if (m && msg) m.textContent = msg; if (m && !busy) m.textContent = 'Please wait\u2026'; document.querySelectorAll('button').forEach(function (btn) { if (busy) { btn.setAttribute('data-wd', btn.disabled ? '1' : '0'); btn.disabled = true; } else { btn.disabled = btn.getAttribute('data-wd') === '1'; } }); } /* CSRF Token */ function waitForToken() { return new Promise(function (resolve, reject) { var pc = window.portalContext || {}; var c = pc.csrfToken || pc.requestVerificationToken; if (c && c.length > 20) { resolve(c); return; } var d = document.querySelector('input[name="__RequestVerificationToken"]'); if (d && d.value) { resolve(d.value); return; } var e = document.getElementById('csrf-token-value'); if (e && e.value && e.value.length > 20) { resolve(e.value); return; } var n = 0; var poll = setInterval(function () { n++; var pv = (window.portalContext || {}).csrfToken; if (pv && pv.length > 20) { clearInterval(poll); resolve(pv); return; } var el = document.getElementById('csrf-token-value'); if (el && el.value && el.value.length > 20) { clearInterval(poll); resolve(el.value); return; } if (n >= 30) { clearInterval(poll); fetch('/Account/Login', { credentials: 'same-origin', headers: { 'Accept': 'text/html' } }) .then(function (r) { return r.text(); }) .then(function (html) { var m = html.match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/); if (!m) m = html.match(/value="([^"]{40,})"[^>]*name="__RequestVerificationToken"/); if (m && m[1]) resolve(m[1]); else reject(new Error('CSRF not found')); }).catch(reject); } }, 150); }); } /* CRM post request */ function extractId(data, resp) { if (data && typeof data === 'object') { var b = data.accountid || data.leadid || data.contactid || data.ongc_paymentevidenceid || data.ongc_siteid; if (!b && data['@odata.id']) { var mo = data['@odata.id'].match(/\(([0-9a-f-]{36})\)/i); if (mo) b = mo[1]; } if (b) return b; } var hv = resp && typeof resp.headers.get === 'function' ? (resp.headers.get('OData-EntityId') || '') : ''; var m2 = hv.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i); return m2 ? m2[0] : null; } async function dataversePost(entitySet, payload) { var token = await waitForToken(); var resp = await fetch('/_api/' + entitySet, { method: 'POST', headers: { 'Content-Type': 'application/json', '__RequestVerificationToken': token, 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Prefer': 'return=representation' }, body: JSON.stringify(payload) }); if (!resp.ok) { var em = 'API error ' + resp.status; try { var ej = await resp.json(); em = (ej && ej.error && ej.error.message) || em; } catch (e) { } throw new Error(em); } var data = {}; try { data = await resp.json(); } catch (e) { } return { id: extractId(data, resp), data: data }; } async function fetchLeadRef(lid) { try { var token = await waitForToken(); var r = await fetch('/_api/leads(' + lid + ')?$select=ongc_leadrefid,ongc_clientid', { method: 'GET', headers: { '__RequestVerificationToken': token, 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Accept': 'application/json' } }); if (!r.ok) return null; var d = await r.json(); return (d && (d.ongc_leadrefid || d.ongc_clientid)) || null; } catch (e) { return null; } } function clearSession() { [SK.leadId, SK.leadRef, SK.evidence, SK.accountId, SK.inProgress].forEach(function (k) { try { sessionStorage.removeItem(k); } catch (e) { } }); leadId = null; leadRef = null; evidenceId = null; accountId = null; } function saveSession() { try { if (accountId) sessionStorage.setItem(SK.accountId, accountId); if (leadId) sessionStorage.setItem(SK.leadId, leadId); if (leadRef) sessionStorage.setItem(SK.leadRef, leadRef); if (evidenceId) sessionStorage.setItem(SK.evidence, evidenceId); } catch (e) { } } /* Helper */ function round2(n) { return Math.round(n * 100) / 100; } function gVal(id) { var e = document.getElementById(id); return e ? e.value.trim() : ''; } function radioVal(name) { var e = document.querySelector('input[name="' + name + '"]:checked'); return e ? e.value : ''; } function getChecked(sel) { return Array.prototype.slice.call(document.querySelectorAll(sel + ':checked')).map(function (e) { return e.value; }); } function strip(p) { Object.keys(p).forEach(function (k) { if (p[k] === '' || p[k] === null || p[k] === undefined) delete p[k]; }); return p; } function calcFees() { var base = config.fee, sur = round2(base * config.surchargeRate), gst = round2((base + sur) * config.gstRate); return { base: base, surcharge: sur, gst: gst, total: round2(base + sur + gst) }; } function renderFee() { var el = document.getElementById('pchsFeeAmount'); if (el) el.textContent = config.fee > 0 ? config.fee.toLocaleString('en-AU', { minimumFractionDigits: 2 }) : 'TBC'; } /* Payload account */ function buildAccountPayload() { var org = gVal('healthcareServiceName') || gVal('businessName'); return strip({ name: org, telephone1: gVal('phone'), emailaddress1: gVal('email'), websiteurl: gVal('website'), address1_line1: gVal('streetAddress1'), address1_line2: gVal('streetAddress2'), address1_city: gVal('streetSuburb'), address1_stateorprovince: gVal('streetState'), address1_postalcode: gVal('streetPostcode'), address1_country: 'Australia' }); } /* Payload ongc_site */ function buildSitePayload(site, acctId) { var p = { ongc_locationname: site.name, ongc_street1: site.addr1, ongc_street2: site.addr2, ongc_suburb: site.suburb, ongc_postcode: site.postcode, ongc_country: 107150000 }; if (site.state && site.state !== '') p.ongc_state = parseInt(site.state, 10); if (acctId) p['ongc_Account@odata.bind'] = '/accounts(' + acctId + ')'; return strip(p); } /* Progress step */ function buildProgress() { var c = document.getElementById('pchsProgressSteps'); if (!c) return; c.innerHTML = ''; for (var i = 1; i <= STEPS; i++) { var div = document.createElement('div'); div.className = 'pchs-step-item' + (currentStep === i ? ' active' : '') + (currentStep > i ? ' done' : ''); div.innerHTML = '
' + (currentStep > i ? '✓' : i) + '
' + '
' + (STEP_LABELS[i - 1] || i) + '
'; c.appendChild(div); } var counter = document.getElementById('pchsPageCounter'); if (counter) counter.textContent = 'Step ' + currentStep + ' of ' + STEPS; document.querySelectorAll('.pchs-page-counter-nav').forEach(function (el) { el.textContent = 'Step ' + currentStep + ' of ' + STEPS; }); } function showStep(step) { if (isBusy && typeof step === 'number') return; currentStep = step; document.querySelectorAll('.pchs-form-page').forEach(function (el) { el.classList.remove('active'); }); var target = document.querySelector('.pchs-form-page[data-step="' + step + '"]'); if (target) { target.classList.add('active'); window.scrollTo({ top: 0, behavior: 'smooth' }); } buildProgress(); if (step === 3) buildScopeSections(); if (step === 6) { initSig(); renderFee(); } } /* Validation */ function showErr(id, show) { var el = document.getElementById(id); if (el) el.classList.toggle('show', show); } function reqVal(id, errId) { var ok = gVal(id) !== ''; showErr(errId, !ok); return ok; } function reqRadio(name, errId) { var ok = !!document.querySelector('input[name="' + name + '"]:checked'); showErr(errId, !ok); return ok; } function reqChecked(id, errId) { var el = document.getElementById(id); var ok = el && el.checked; showErr(errId, !ok); return !!ok; } function validateStep(step) { var ok = true; if (step === 1) { ok = reqVal('healthcareServiceName', 'err_healthcareServiceName') && ok; ok = reqVal('contactFirst', 'err_contactFirst') && ok; ok = reqVal('contactLast', 'err_contactLast') && ok; ok = reqVal('phone', 'err_phone') && ok; ok = reqVal('businessName', 'err_businessName') && ok; ok = reqVal('abn', 'err_abn') && ok; var emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(gVal('email')); showErr('err_email', !emailOk); if (!emailOk) ok = false; var addrOk = gVal('streetAddress1') && gVal('streetSuburb') && gVal('streetState') && gVal('streetPostcode'); showErr('err_streetAddress', !addrOk); if (!addrOk) ok = false; var postalYes = document.getElementById('postalDiffYes'); if (postalYes && postalYes.checked) { var postalOk = gVal('postalAddress1') && gVal('postalSuburb') && gVal('postalPostcode'); showErr('err_postalAddress', !postalOk); if (!postalOk) ok = false; } } if (step === 2) { ok = reqRadio('governance', 'err_governance') && ok; ok = reqRadio('locationType', 'err_locationType') && ok; ok = reqRadio('discipline', 'err_discipline') && ok; var aofOk = document.querySelectorAll('.aof-cb:checked').length > 0; showErr('err_areaOfFocus', !aofOk); if (!aofOk) ok = false; ok = reqRadio('corporateEntity', 'err_corporateEntity') && ok; ok = reqRadio('prevAccredited', 'err_prevAccredited') && ok; var vw = document.getElementById('voluntaryBasisWrap'); if (vw && !vw.classList.contains('pchs-hidden')) { ok = reqRadio('voluntaryBasis', 'err_voluntaryBasis') && ok; } ok = reqRadio('fundingLicensing', 'err_fundingLicensing') && ok; ok = reqVal('accreditationExpiry', 'err_accreditationExpiry') && ok; ok = reqVal('numSites', 'err_numSites') && ok; var siteCnt = parseInt(gVal('numSites')) || 0; for (var s = 1; s <= siteCnt; s++) { ok = reqVal('siteName_' + s, 'err_siteName_' + s) && ok; ok = reqVal('siteFteTotal_' + s, 'err_siteFteTotal_' + s) && ok; ok = reqVal('siteFteProviders_' + s, 'err_siteFteProviders_' + s) && ok; ok = reqVal('siteFteAdmin_' + s, 'err_siteFteAdmin_' + s) && ok; } } if (step === 4) { ok = reqRadio('physicalExams', 'err_physicalExams') && ok; } if (step === 5) { ok = reqRadio('assessmentProcess', 'err_assessmentProcess') && ok; if (radioVal('assessmentProcess').indexOf('virtual') !== -1) { ok = reqRadio('commissionPermission', 'err_commissionPermission') && ok; if (radioVal('commissionPermission') === 'Yes') ok = reqRadio('itInfra', 'err_itInfra') && ok; } } if (step === 6) { ok = reqChecked('declarationCheck', 'err_declaration') && ok; ok = reqChecked('consentCheck', 'err_consent') && ok; ok = reqVal('authRepName', 'err_authRepName') && ok; ok = reqVal('authRepPosition', 'err_authRepPosition') && ok; /* Signature validation — not required yet var sigEmpty = isSigEmpty(); showErr('err_signature', sigEmpty); if (sigEmpty) ok = false; */ } if (!ok) { var first = document.querySelector('.pchs-form-page.active .pchs-error-text.show'); if (first) first.scrollIntoView({ behavior: 'smooth', block: 'center' }); } return ok; } /* Conditions check */ window.pchs = { togglePostal: function () { var yes = document.getElementById('postalDiffYes'); document.getElementById('postalAddressBlock').classList.toggle('pchs-hidden', !(yes && yes.checked)); }, toggleGovernanceOther: function () { document.getElementById('governanceOtherWrap').classList.toggle('pchs-hidden', radioVal('governance') !== 'Other'); }, toggleAofOther: function () { var cb = document.querySelector('.aof-other-cb'); document.getElementById('aofOtherWrap').classList.toggle('pchs-hidden', !(cb && cb.checked)); }, toggleCorporate: function () { document.getElementById('corporateNameWrap').classList.toggle('pchs-hidden', radioVal('corporateEntity') !== 'Yes'); }, togglePrevAccredited: function () { document.getElementById('prevAccreditedBlock').classList.toggle('pchs-hidden', radioVal('prevAccredited') !== 'Yes'); }, toggleAssessment: function () { var isVirtual = radioVal('assessmentProcess').indexOf('virtual') !== -1; document.getElementById('commissionPermissionWrap').classList.toggle('pchs-hidden', !isVirtual); if (!isVirtual) { document.querySelectorAll('input[name="commissionPermission"]').forEach(function (e) { e.checked = false; }); document.getElementById('itInfraWrap').classList.add('pchs-hidden'); document.querySelectorAll('input[name="itInfra"]').forEach(function (e) { e.checked = false; }); } }, toggleITInfra: function () { document.getElementById('itInfraWrap').classList.toggle('pchs-hidden', radioVal('commissionPermission') !== 'Yes'); }, onSiteCountChange: function () { var v = gVal('numSites'); buildSiteSections(parseInt(v) || 0); document.getElementById('moreThan10Advisory').classList.toggle('pchs-hidden', v !== 'more'); }, clearSig: function () { var c = document.getElementById('pchsSigCanvas'); if (sigCtx && c) sigCtx.clearRect(0, 0, c.width, c.height); }, toggleVoluntaryBasis: function () { var cb = document.getElementById('nsqhsStdCb'), w = document.getElementById('voluntaryBasisWrap'); if (w) w.classList.toggle('pchs-hidden', !(cb && cb.checked)); if (cb && !cb.checked) { document.querySelectorAll('input[name="voluntaryBasis"]').forEach(function (e) { e.checked = false; }); } }, save: function () { alert('Your progress has been saved. Use the link sent to your registered email to resume.'); } }; /* site section */ function buildSiteSections(count) { var container = document.getElementById('siteSectionsContainer'); if (!container) return; Array.prototype.slice.call(container.querySelectorAll('.pchs-site-section')).forEach(function (el, i) { if (i >= count) el.remove(); }); for (var i = 1; i <= count; i++) { if (container.querySelector('[data-site="' + i + '"]')) continue; var sec = document.createElement('div'); sec.className = 'pchs-site-section'; sec.setAttribute('data-site', i); sec.innerHTML = '
Main/Site ' + i + ' — Name (exact name for certificate) *
' + '
' + '' + '
Site name is required.
' + '
Main/Site ' + i + ' Address
' + '' + 'Street Address' + '' + 'Address Line 2' + '
' + '
Suburb
' + '
State
' + '
Postcode
' + '
' + '
' + '
' + '
' + '
' + '' + '
Required.
' + '
' + '' + '
Required.
' + '
' + '' + '
Required.
' + '
'; container.appendChild(sec); } } /* scope section */ function buildScopeSections() { var container = document.getElementById('scopeSectionsContainer'); if (!container) return; container.innerHTML = ''; var checked = Array.prototype.slice.call(document.querySelectorAll('.aof-cb:checked')); if (!checked.length) { container.innerHTML = '
Please go back to Step 2 and select at least one area of focus.
'; return; } checked.forEach(function (cb) { var area = cb.value; var safeId = area.replace(/[^a-zA-Z0-9]/g, '_'); var sec = document.createElement('div'); sec.className = 'pchs-scope-section'; sec.innerHTML = '
' + area + '
' + (area === 'Other' ? '
' + '
' : '') + '
' + '
' + '
' + '
' + '
' + '
'; container.appendChild(sec); }); } /* Signature box */ function initSig() { var c = document.getElementById('pchsSigCanvas'); if (!c) return; var fresh = c.cloneNode(true); c.parentNode.replaceChild(fresh, c); c = fresh; c.width = c.parentElement.clientWidth || 680; c.height = 130; sigCtx = c.getContext('2d'); sigCtx.strokeStyle = '#1d2f43'; sigCtx.lineWidth = 2.2; sigCtx.lineCap = 'round'; sigCtx.lineJoin = 'round'; var ctx = sigCtx; function pos(e) { var r = c.getBoundingClientRect(); var pt = e.touches ? e.touches[0] : e; return { x: pt.clientX - r.left, y: pt.clientY - r.top }; } c.addEventListener('mousedown', function (e) { sigDrawing = true; ctx.beginPath(); var p = pos(e); ctx.moveTo(p.x, p.y); }); c.addEventListener('mousemove', function (e) { if (!sigDrawing) return; var p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); }); c.addEventListener('mouseup', function () { sigDrawing = false; }); c.addEventListener('mouseleave', function () { sigDrawing = false; }); c.addEventListener('touchstart', function (e) { e.preventDefault(); sigDrawing = true; ctx.beginPath(); var p = pos(e); ctx.moveTo(p.x, p.y); }, { passive: false }); c.addEventListener('touchmove', function (e) { e.preventDefault(); if (!sigDrawing) return; var p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); }, { passive: false }); c.addEventListener('touchend', function () { sigDrawing = false; }); } function isSigEmpty() { var c = document.getElementById('pchsSigCanvas'); if (!c || !sigCtx) return true; var d = sigCtx.getImageData(0, 0, c.width, c.height).data; for (var i = 3; i < d.length; i += 4) { if (d[i] > 0) return false; } return true; } /* collect payloads */ function collectSites() { var n = parseInt(gVal('numSites')) || 0, sites = []; for (var i = 1; i <= n; i++) sites.push({ name: gVal('siteName_' + i), addr1: gVal('siteAddr1_' + i), addr2: gVal('siteAddr2_' + i), suburb: gVal('siteSuburb_' + i), state: gVal('siteState_' + i), postcode: gVal('sitePostcode_' + i), fteTotal: gVal('siteFteTotal_' + i), fteProviders: gVal('siteFteProviders_' + i), fteAdmin: gVal('siteFteAdmin_' + i) }); return sites; } function collectScope() { var result = []; Array.prototype.slice.call(document.querySelectorAll('.aof-cb:checked')).forEach(function (cb) { var sid = cb.value.replace(/[^a-zA-Z0-9]/g, '_'); result.push({ area: cb.value, practitioners: gVal('scope_prac_' + sid), services: gVal('scope_svc_' + sid), otherDetails: cb.value === 'Other' ? gVal('scope_other_details') : '' }); }); return result; } function buildWebResponseHtml() { var postalDiff = document.getElementById('postalDiffYes') && document.getElementById('postalDiffYes').checked; var sites = collectSites(); var scope = collectScope(); var now = new Date().toLocaleString('en-AU', { timeZone: 'Australia/Sydney', dateStyle: 'medium', timeStyle: 'short' }); function row(label, value) { if (!value && value !== 0) value = '\u2014'; return '' + '' + label + '' + '' + value + '' + ''; } function section(title) { return '' + title + ''; } var html = '
' + ''; /* Header */ html += ''; html += ''; /* 1. Contact Details */ html += section('1. Contact Details'); html += row('QIP Client ID', gVal('clientId')); html += row('Healthcare Service Name', gVal('healthcareServiceName')); html += row('Contact Name', gVal('contactFirst') + ' ' + gVal('contactLast')); html += row('Email', gVal('email')); html += row('Phone', gVal('phone')); html += row('Website', gVal('website')); html += row('Business / Trading Name', gVal('businessName')); html += row('ABN', gVal('abn')); html += row('ACN', gVal('acn')); /* Street address */ var streetAddr = [gVal('streetAddress1'), gVal('streetAddress2'), gVal('streetSuburb'), gVal('streetState'), gVal('streetPostcode'), 'Australia'].filter(Boolean).join(', '); html += row('Street Address', streetAddr); /* Postal address */ if (postalDiff) { var postalAddr = [gVal('postalAddress1'), gVal('postalSuburb'), gVal('postalState'), gVal('postalPostcode'), 'Australia'].filter(Boolean).join(', '); html += row('Postal Address', postalAddr); } else { html += row('Postal Address', 'Same as street address'); } /* 2. Scope */ html += section('2. Scope of Service'); html += row('Governance Structure', radioVal('governance') === 'Other' ? 'Other: ' + gVal('governanceOther') : radioVal('governance')); html += row('Location Type', radioVal('locationType')); html += row('Discipline', radioVal('discipline')); var aofChecked = getChecked('.aof-cb'); var aofDisplay = aofChecked.length ? aofChecked.join(', ') : '\u2014'; if (aofChecked.indexOf('Other') !== -1 && gVal('aofOtherText')) aofDisplay += ' (' + gVal('aofOtherText') + ')'; html += row('Area(s) of Focus', aofDisplay); html += row('Corporate Entity', radioVal('corporateEntity') === 'Yes' ? 'Yes \u2014 ' + gVal('corporateName') : radioVal('corporateEntity')); html += row('Previously Accredited', radioVal('prevAccredited')); if (radioVal('prevAccredited') === 'Yes') { var stds = getChecked('.std-cb'); html += row('Current Standards', stds.length ? stds.join(', ') : '\u2014'); html += row('Current Provider', gVal('currentProvider')); html += row('Voluntary Basis', radioVal('voluntaryBasis')); html += row('Funding / Licensing', radioVal('fundingLicensing')); html += row('Accreditation Expiry', gVal('accreditationExpiry')); } /* 3. Sites */ html += section('3. Service Locations (' + (sites.length || 0) + ' site(s))'); if (sites.length) { sites.forEach(function (s, i) { var num = i + 1; var siteName = s.name || ('Site ' + num); var siteAddr = [s.addr1, s.addr2, s.suburb, s.postcode].filter(Boolean).join(', ') || '—'; /* Per-site divider header */ html += '' + ''; html += row('Site Name', siteName); html += row('Address', siteAddr); html += row('Total FTE Staff', s.fteTotal || '—'); html += row('FTE Healthcare Providers', s.fteProviders || '—'); html += row('FTE Mgmt & Admin', s.fteAdmin || '—'); if (i < sites.length - 1) { html += ''; } }); } else { html += ''; } /* Scope detail — grouped per area (sub-header + Practitioners + Services) */ if (scope.length) { html += section('3b. Scope Detail'); scope.forEach(function (sc, i) { /* Area group sub-header */ html += '' + ''; /* Practitioners row */ html += '' + '' + '' + ''; /* Services row */ html += '' + '' + '' + ''; /* Other details */ if (sc.otherDetails) { html += '' + '' + '' + ''; } /* spacer between groups */ if (i < scope.length - 1) { html += ''; } }); } /* 4. Additional Information */ html += section('4. Additional Information'); html += row('Physical Examinations', radioVal('physicalExams')); html += row('Further Information', gVal('furtherInfo')); /* 5. Assessment Preferences */ html += section('5. Assessment Preferences'); html += row('Assessment Process', radioVal('assessmentProcess')); if (radioVal('assessmentProcess').indexOf('virtual') !== -1) { html += row('Commission Permission', radioVal('commissionPermission')); if (radioVal('commissionPermission') === 'Yes') html += row('IT Infrastructure', radioVal('itInfra')); } html += row('Other Frameworks', gVal('otherFrameworks')); /* 6. Authorisation */ html += section('6. Authorisation'); html += row('Authorised Representative', gVal('authRepName')); html += row('Position', gVal('authRepPosition')); html += row('Declaration Accepted', document.getElementById('declarationCheck') && document.getElementById('declarationCheck').checked ? 'Yes' : 'No'); html += row('Consent to Disclosure', document.getElementById('consentCheck') && document.getElementById('consentCheck').checked ? 'Yes' : 'No'); html += '
' + 'PCHS Registration — Scope of Service
' + 'Submitted: ' + now + '
' + '📍 Site ' + num + (siteName ? ' — ' + siteName : '') + '
No sites entered.
' + sc.area + '
Practitioners' + (sc.practitioners || '—') + '
Services' + (sc.services || '—') + '
Details' + sc.otherDetails + '
'; return html; } function buildLeadPayload(acctId) { var org = gVal('healthcareServiceName') || gVal('businessName'); var postalDiff = document.getElementById('postalDiffYes') && document.getElementById('postalDiffYes').checked; var p = strip({ subject: 'National Safety and Quality Primary and Community Healthcare Standards \u2013 ' + org, firstname: gVal('contactFirst'), lastname: gVal('contactLast') || org, emailaddress1: gVal('email'), telephone1: gVal('phone'), companyname: org, websiteurl: gVal('website'), leadsourcecode: 8, address1_line1: gVal('streetAddress1'), address1_line2: gVal('streetAddress2'), address1_city: gVal('streetSuburb'), address1_stateorprovince: gVal('streetState'), address1_postalcode: gVal('streetPostcode'), address1_country: 'Australia', address2_line1: postalDiff ? gVal('postalAddress1') : '', address2_city: postalDiff ? gVal('postalSuburb') : '', address2_stateorprovince: postalDiff ? gVal('postalState') : '', address2_postalcode: postalDiff ? gVal('postalPostcode') : '', address2_country: postalDiff ? 'Australia' : '', ongc_enquirytype: 5, ongc_practicename: org, ongc_practiceabn: gVal('abn'), ongc_practicephone: gVal('phone'), ongc_clientid: gVal('clientId'), ongc_postalsameasstreet: !postalDiff, ongc_webresponse: buildWebResponseHtml() //description: JSON.stringify({ // clientId: gVal('clientId'), businessName: gVal('businessName'), acn: gVal('acn'), // governance: radioVal('governance'), governanceOther: gVal('governanceOther'), // locationType: radioVal('locationType'), discipline: radioVal('discipline'), // areaOfFocus: getChecked('.aof-cb'), aofOther: gVal('aofOtherText'), // corporateEntity: radioVal('corporateEntity'), corporateName: gVal('corporateName'), // prevAccredited: radioVal('prevAccredited'), currentStandards: getChecked('.std-cb'), // currentProvider: gVal('currentProvider'), voluntaryBasis: radioVal('voluntaryBasis'), // fundingLicensing: radioVal('fundingLicensing'), expiryDate: gVal('accreditationExpiry'), // numSites: gVal('numSites'), sites: collectSites(), scope: collectScope(), // physicalExams: radioVal('physicalExams'), furtherInfo: gVal('furtherInfo'), // assessmentProcess: radioVal('assessmentProcess'), commissionPermission: radioVal('commissionPermission'), // itInfra: radioVal('itInfra'), otherFrameworks: gVal('otherFrameworks'), // authRepName: gVal('authRepName'), authRepPosition: gVal('authRepPosition') //}) }); if (config.businessId) p['ongc_Business@odata.bind'] = '/ongc_businesses(' + config.businessId + ')'; if (acctId) p['parentaccountid@odata.bind'] = '/accounts(' + acctId + ')'; return p; } function buildContactPayload() { var p = { firstname: gVal('contactFirst'), lastname: gVal('contactLast') || gVal('healthcareServiceName'), emailaddress1: gVal('email'), telephone1: gVal('phone') }; if (accountId) p['parentcustomerid_account@odata.bind'] = '/accounts(' + accountId + ')'; if (leadId) p['originatingleadid@odata.bind'] = '/leads(' + leadId + ')'; if (config.contactTypeId) p['ongc_ContactType@odata.bind'] = '/ongc_contacttypes(' + config.contactTypeId + ')'; return strip(p); } function buildEvidencePayload() { var fees = calcFees(); var p = { ongc_payername: (gVal('contactFirst') + ' ' + gVal('contactLast')).trim(), ongc_paymentamount: fees.base, ongc_surchargefee: fees.surcharge, ongc_gst: fees.gst, ongc_totalamount: fees.total, ongc_paymentstatus: 'pending-cc', ongc_transactionstatus: 'pending', ongc_paymentdate: new Date().toISOString(), ongc_responsemessage: 'Pending \u2013 PCHS Stripe credit-card checkout initiated' }; if (leadId) p['ongc_Lead@odata.bind'] = '/leads(' + leadId + ')'; return strip(p); } /* RECORD CREATION */ async function createAllRecords() { ///* Step 1: Create Account from healthcareServiceName */ //setBusy(true, 'Creating account record\u2026'); //var acct = await dataversePost('accounts', buildAccountPayload()); //accountId = acct.id; //if (!accountId) throw new Error('Account GUID not returned. Check Dataverse Web API permissions.'); //console.log('[PCHS] Account:', accountId); var accountId = null; /* Step 2: Create Lead linked to Account */ setBusy(true, 'Creating registration record\u2026'); var lead = await dataversePost('leads', buildLeadPayload(accountId)); leadId = lead.id; if (!leadId) throw new Error('Lead GUID not returned. Check Dataverse Web API permissions.'); console.log('[PCHS] Lead:', leadId); /* Step 3: Fetch reference number */ setBusy(true, 'Fetching registration reference\u2026'); leadRef = await fetchLeadRef(leadId); saveSession(); ///* Step 4: Create Contact */ //setBusy(true, 'Creating contact record\u2026'); //try { // var cr = await Promise.allSettled([dataversePost('contacts', buildContactPayload())]); // if (cr[0].status === 'rejected') console.warn('[PCHS] Contact failed:', cr[0].reason && cr[0].reason.message); // else console.log('[PCHS] Contact:', cr[0].value && cr[0].value.id); //} catch (e) { console.warn('[PCHS] Contact error:', e.message); } ///* Step 5: Create ongc_site records (one per site and linked to Account) */ //var siteCnt = parseInt(gVal('numSites')) || 0; //if (siteCnt > 0) { // setBusy(true, 'Creating site records\u2026'); // var sitesData = collectSites(); // for (var s = 0; s < sitesData.length; s++) { // try { // var sr = await dataversePost('ongc_sites', buildSitePayload(sitesData[s], accountId)); // console.log('[PCHS] Site ' + (s + 1) + ':', sr.id); // } catch (e) { console.warn('[PCHS] Site ' + (s + 1) + ' failed:', e.message); } // } //} /* STRIPE PAYMENT EVIDENCE setBusy(true, 'Creating payment record\u2026'); var ev = await dataversePost('ongc_paymentevidences', buildEvidencePayload()); if (ev && ev.id) { evidenceId = ev.id; console.log('[PCHS] Evidence:', evidenceId); } else console.warn('[PCHS] Evidence GUID not returned'); saveSession(); ── END STRIPE PAYMENT EVIDENCE ── */ } /* STRIPE REDIRECT function initiateStripePayment() { var fees = calcFees(), org = gVal('healthcareServiceName') || gVal('businessName'); var params = new URLSearchParams({ leadId: leadId || '', leadRef: leadRef || '', paymentEvidenceId: evidenceId || '', amount: fees.total.toFixed(2), base: fees.base.toFixed(2), surcharge: fees.surcharge.toFixed(2), gst: fees.gst.toFixed(2), email: gVal('email'), name: (gVal('contactFirst') + ' ' + gVal('contactLast')).trim(), ref: 'National Safety and Quality Primary and Community Healthcare Standards \u2013 ' + org, returnUrl: window.location.href.split('?')[0] }); try { sessionStorage.setItem(SK.inProgress, '1'); if (leadId) sessionStorage.setItem(SK.leadId, leadId); if (leadRef) sessionStorage.setItem(SK.leadRef, leadRef); if (evidenceId) sessionStorage.setItem(SK.evidence, evidenceId); } catch (e) { } window.location.replace('/agpal-stripe-checkout?' + params.toString()); } END STRIPE REDIRECT */ /* Result page */ function showResult(success, ref, errMsg) { var wrap = document.querySelector('.pchs-wrap'); if (!wrap) return; var shell = wrap.querySelector('.pchs-form-shell'); if (shell) shell.style.display = 'none'; var progress = wrap.querySelector('.pchs-progress-wrap'); if (progress) progress.style.display = 'none'; var hero = wrap.querySelector('.pchs-hero'); if (hero) hero.style.display = 'none'; var resultDiv = document.getElementById('pchsResultPage'); if (!resultDiv) { resultDiv = document.createElement('div'); resultDiv.id = 'pchsResultPage'; wrap.appendChild(resultDiv); } if (success) { resultDiv.innerHTML = '
' + '
' + '

Registration Submitted Successfully

' + '

Thank you for submitting your NSQPCH accreditation scope of service. A QIP team member will be in touch shortly.

' + '
Your Reference Number' + (ref || '\u2014') + '
' + '

Please keep this reference number for your records.

' + '
'; } else { resultDiv.innerHTML = '
' + '
' + '

Submission Failed

' + '

We were unable to complete your registration. Please try again or contact QIP for assistance.

' + (errMsg ? '

' + errMsg + '

' : '') + '' + '
'; } resultDiv.style.display = 'block'; window.scrollTo({ top: 0, behavior: 'smooth' }); } /* INIT */ function bindNav() { /* Bind individual Next/Prev buttons by ID */ var navMap = [[1, 'next1', 'prev2'], [2, 'next2', 'prev3'], [3, 'next3', 'prev4'], [4, 'next4', 'prev5'], [5, 'next5', 'prev6']]; navMap.forEach(function (item) { var step = item[0], nextId = item[1], prevId = item[2]; var nextBtn = document.getElementById(nextId); var prevBtn = document.getElementById(prevId); if (nextBtn) nextBtn.addEventListener('click', function () { if (!isBusy && validateStep(step)) showStep(step + 1); }); if (prevBtn) prevBtn.addEventListener('click', function () { if (!isBusy) showStep(step); }); }); /* Prev on step 2 goes to step 1 */ var p2 = document.getElementById('prev2'); if (p2) p2.addEventListener('click', function () { if (!isBusy) showStep(1); }); /* Submit */ var sub = document.getElementById('finalSubmitBtn'); if (sub) sub.addEventListener('click', async function () { if (isBusy) return; if (!validateStep(6)) return; var errEl = document.getElementById('pchsSubmitError'); if (errEl) errEl.classList.remove('show'); try { await createAllRecords(); setBusy(false); showResult(true, leadRef || leadId || '\u2014'); /* STRIPE REDIRECT setBusy(true, 'Redirecting to payment\u2026'); initiateStripePayment(); */ } catch (err) { console.error('[PCHS] Submit failed:', err); setBusy(false); showResult(false, null, err.message || 'Could not submit. Please try again.'); } }); /* Postal toggle */ document.querySelectorAll('input[name="postalDiff"]').forEach(function (el) { el.addEventListener('change', pchs.togglePostal); }); /* Governance Other */ document.querySelectorAll('input[name="governance"]').forEach(function (el) { el.addEventListener('change', pchs.toggleGovernanceOther); }); } function bindFieldClearError() { document.addEventListener('input', function (e) { var fg = e.target.closest('.pchs-field-group'); if (fg) { var et = fg.querySelector('.pchs-error-text'); if (et) et.classList.remove('show'); } }); document.addEventListener('change', function (e) { var fg = e.target.closest('.pchs-field-group'); if (fg) { var et = fg.querySelector('.pchs-error-text'); if (et) et.classList.remove('show'); } }); } function ready(fn) { if (document.readyState !== 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function () { injectSpinner(); clearSession(); bindFieldClearError(); bindNav(); showStep(1); }); window.addEventListener('resize', function () { if (sigCtx) initSig(); }); }());