-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsyncRefresh.js
More file actions
5 lines (4 loc) · 47.2 KB
/
Copy pathsyncRefresh.js
File metadata and controls
5 lines (4 loc) · 47.2 KB
1
2
3
4
5
/* mobilecaddy-utils - v3.2.1 - Bundle Time: 2024-10-22 11:36:49 */
/* git info: "2024-10-22 11:34:11 +0100": 4b69821f8a37db692d32cb588a22dc57e260d69b (v3) */
/* Copyright 2024 MobileCaddy Ltd */
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.refreshToken=refreshToken,exports.genProxyId=genProxyId,exports.addProxyIds=addProxyIds,exports.getSyncRecFailures=getSyncRecFailures,exports.p2mRefreshTable=p2mRefreshTable,exports.buildConnectionSession=buildConnectionSession,exports.m2pUpdateMobileTable=m2pUpdateMobileTable,exports.m2pRecoveryUpdateMobileTable=m2pRecoveryUpdateMobileTable,exports.heartBeat=heartBeat,exports._handleRefreshResponse=_handleRefreshResponse,exports.createUpdateJson=createUpdateJson,exports.syncMobileTable=syncMobileTable,exports.getRTSPendingconnSess=getRTSPendingconnSess,exports.cleanConnectionSessionHeartBeat=cleanConnectionSessionHeartBeat,exports.cleanConnectionSessionVFEvent=cleanConnectionSessionVFEvent,exports.csStatusCheck=csStatusCheck,exports.maybeSyncConnSess=maybeSyncConnSess,exports.processM2PUpdateResponse=processM2PUpdateResponse,exports.postProcessConnectionSession=postProcessConnectionSession,exports.handleUpdatedCS=handleUpdatedCS,exports.CONN_SESS_OK=exports.CLEAN_CS_OK=exports.HEARTBEAT_REFRESHED_OK=exports.HEARTBEAT_NOT_DEVICE=exports.HEARTBEAT_NO_CONNECTION=exports.HEARTBEAT_FAILURE=exports.HEARTBEAT_EXCEPTION=exports.HEARTBEAT_OK=exports.M2P_NO_RECS_TO_SYNC=exports.M2P_UPDATE_OK=exports.P2M_REFRESH_OK=exports.SYNC_NOK_STATUS=exports.SYNC_ALREADY_IN_PROGRESS_INC=exports.SYNC=exports.CSINHEAD_SYNC_VSN=void 0;var smartstore,mobileCaddy=_interopRequireWildcard(require("./constants")),smartStoreUtils=_interopRequireWildcard(require("./smartStoreUtils")),appDataUtils=_interopRequireWildcard(require("./appDataUtils")),logger=_interopRequireWildcard(require("./logger")),geoLocation=_interopRequireWildcard(require("./geoLocation")),_=_interopRequireWildcard(require("underscore"));function _interopRequireWildcard(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var o=Object.defineProperty&&Object.getOwnPropertyDescriptor?Object.getOwnPropertyDescriptor(e,n):{};o.get||o.set?Object.defineProperty(t,n,o):t[n]=e[n]}return t.default=e,t}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var LOCAL_DEV=!!window.LOCAL_DEV,USE_FORCETK=!!window.USE_FORCETK,SYNC_ALREADY_IN_PROGRESS_INC=98;exports.SYNC_ALREADY_IN_PROGRESS_INC=SYNC_ALREADY_IN_PROGRESS_INC;var SYNC=100400;exports.SYNC=SYNC;var SYNC_OK=SYNC,SYNC_NOK_STATUS=100402;exports.SYNC_NOK_STATUS=SYNC_NOK_STATUS;var CSINHEAD_SYNC_VSN="006";exports.CSINHEAD_SYNC_VSN=CSINHEAD_SYNC_VSN;var MC_FAILURE_KEY_PREFIX="mc_failure_tab_";function useSdkReq(){return!(!window[mobileCaddy.CONTAINER_VSN_KEY]||!window[mobileCaddy.CONTAINER_VSN_KEY].startsWith("3"))}function syncMobileTable(e,t,n,o,s,r){r&&r({status:0,table:e}),t=void 0===t||t;n||(n=0),o||(o=50),s||(s=!1);var a=function(e,t,o){var s={};p2mRefreshTable(e,n,!0,1,1,null,function(e){e.status==P2M_REFRESH_OK?(s.status=SYNC,t(s)):(s.status=e.status,s.mc_add_status=e.mc_add_status,e.sessNum&&(s.sessNum=e.sessNum),t(s))},o)},c=function e(t,s,r){var a={};smartStoreUtils.queryMobileTable("recsToSync","Mobile_Table_Name",t,function(c){if(c.length>0)try{m2pUpdateMobileTable(t,o,function(o){o.status==M2P_UPDATE_OK&&void 0===o.mc_add_status?(n=0,a.status=0,s(a)):o.status==M2P_UPDATE_OK&&"more-to-sync"===o.mc_add_status?e(t,s,r):(a.status=o.status,a.mc_add_status=o.mc_add_status,s(a))},r)}catch(e){}else a.status=2,a.mc_add_status="no-sync-no-updates",s(a)},r)},i=function(e,t,n,o,r){var i={};localStorage.removeItem("mcM2pMoreToSync"),"Dynamic (Submit First/Retain)"==t||"Dynamic (Submit First/Clear)"==t?c(e,function(t){!s&&(0===t.status||n&&2==t.status)?a(e,o,r):s&&0===t.status||2==t.status?(i.status=SYNC,i.mc_add_status=t.mc_add_status,o(i)):(i.status=SYNC_NOK_STATUS,i.mc_add_status=t.mc_add_status,o(i))},r):"Submit Only"==t||"Submit & Clear"==t||"Submit & Destroy"==t?c(e,function(e){0===e.status?(i.status=SYNC,o(i)):(i.status=SYNC_NOK_STATUS,i.mc_add_status=e.mc_add_status,o(i))},r):logger.errorAndDispatch("Unknown sync type",t,s)};return new Promise(function(n,o){var s={},c=function(t){localStorage.removeItem("syncInProgressTime"),r&&(t.table=e,r(t)),n(t)},u=function(t){localStorage.removeItem("syncInProgressTime"),r&&r({table:e,status:-1}),o(t)},d="syncTime"+e,l=localStorage.getItem(d),_=(new Date).valueOf(),p=l?parseInt(l)+5e3:0;"Connection_Session__mc"!=e&&_<p?(s.status=SYNC,s.mc_add_status="sync-too-soon",n(s)):(localStorage.setItem(d,_),localStorage.removeItem("tmpFailedRecordsAccum"),heartBeat(function(r){if(r.status==HEARTBEAT_OK||r.status==HEARTBEAT_NOT_DEVICE||r.status==HEARTBEAT_REFRESHED_OK){var d=localStorage.getItem("syncInProgressTime"),l=(new Date).valueOf();"Connection_Session__mc"!=e&&d&&d>l-12e4?(s.status=SYNC+SYNC_ALREADY_IN_PROGRESS_INC,u(s)):(localStorage.setItem("syncInProgressTime",l),smartStoreUtils.getTableDefnColumnValue(e,"Sync Type").then(function(r){getRTSPendingconnSess(function(d){"Mobile_Log__mc"!=e?null!==d&&void 0!==d?csStatusCheck(d,function(o){o.status==CONN_SESS_OK?"Refresh Only"==r||"Refresh & Clear"==r?a(e,c,u):i(e,r,t,c,u):(s.status=SYNC_OK,s.mc_add_status=o.status,n(s))},function(e){logger.errorAndDispatch(e),o(e)}):"Refresh Only"==r||"Refresh & Clear"==r?a(e,c,u):i(e,r,t,c,u):i(e,r,!1,c,u)},u)}).catch(function(e){u(e)}))}else s.status=SYNC_NOK_STATUS,s.mc_add_status=r.status,n(s),100101==s.mc_add_status||100102==s.mc_add_status?logger.error(s):logger.log(s)},u))})}function handleRefreshResponse(e){return new Promise(function(t,n){var o=function(e){n(e)},s=window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore"),r={},a={},c={},i=e.mt,u=s.buildExactQuerySpec("Mobile_Table_Name",i,mobileCaddy.QUERY_BUFFER_SIZE);smartStoreUtils.querySoupRecordsWithQuerySpec("recsToSync",u,function(n){n.forEach(function(e){if("Insert"==e.CRUD_Operation||"InsertUpdate"==e.CRUD_Operation)a[e.Id]=1;else{if("Update"!=e.CRUD_Operation&&"UpdateUpdate"!=e.CRUD_Operation)return void logger.error("RTS contains record with non support CRUD Operation"+e);c[e.Id]=1}}),smartStoreUtils.getProxyFieldName(i).then(function(u){var d=[],l=[];(e.records.forEach(function(e){var t=!0;null!==e.recordData.MC_Proxy_ID__c&&a.hasOwnProperty(e.recordData[u])&&(t=!1),t&&c.hasOwnProperty(e.recordData.Id)&&(t=!1),t&&d.push(e.recordData)}),e.ds)&&e.ds.oq.concat(e.ds.sd.concat(e.ds.hd.concat(e.ds.sh))).forEach(function(e){c.hasOwnProperty(e)||l.push(e)});var _=s.buildExactQuerySpec("Mobile_Table_Name",i,mobileCaddy.QUERY_BUFFER_SIZE);smartStoreUtils.querySoupRecordsWithQuerySpec("recsToSync",_,function(a){a.length==n.length?smartStoreUtils.deleteRecordsForExternalId2(i,l,"Id",function(){s.upsertSoupEntriesWithExternalId(i,d,"Id",function(){s.soupExists("SnapShot_"+i,function(n){n?smartStoreUtils.deleteRecordsForExternalId2("SnapShot_"+i,l,"Id",function(){s.upsertSoupEntriesWithExternalId("SnapShot_"+i,d,"Id",function(){checkForMigrateToInfo(e),setPlatAuthUrl(e.platAuthUrl),r.status=0,r.cs=e.cs,r.cp=e.cp,r.lastRefreshDatetime=e.lastRefreshDatetime,t(r)},o)},o):(checkForMigrateToInfo(e),setPlatAuthUrl(e.platAuthUrl),r.status=0,r.lastRefreshDatetime=e.lastRefreshDatetime,r.cs=e.cs,r.cp=e.cp,t(r))},o)},o)},o):(r.status=0,r.mc_add_status=1,r.cs=e.cs,r.cp=e.cp,r.lastRefreshDatetime=e.lastRefreshDatetime,t(r))},o)})},o)})}function setPlatAuthUrl(e){e||(e=""),appDataUtils.updateCurrentValueInAppSoup("platAuthUrl",e).catch(function(t){logger.error("setPlatAuthUrl",e,t)})}var P2M_REFRESH_OK=100500;exports.P2M_REFRESH_OK=P2M_REFRESH_OK;var SYNC_NOK=100402;function p2mRefreshTable(e,t,n,o,s,r,a,c){var i,u,d,l,_=function(i,d){if(d.status){var _,S,f=new RegExp("\n","g");i=i.replace(f,"\\n"),f=new RegExp("\r","g"),i=i.replace(f,""),handleRefreshResponse(S=JSON.parse(i)).then(function(t){return _=t,smartStoreUtils.setTableDefnColumnValue(e,"Last Refresh Date/Time",_.lastRefreshDatetime)}).then(function(){var t="P2M RE Records Processed";return"Connection_Session__mc"==e&&(t="P2M Conn_Sess Records Processed"),1==_.mc_add_status&&(t="P2M RE Abandoned"),l.connSessionRec.mobilecaddy1__Mobile_Process_Status__c=t,l.connSessionRec.Id=_.cs,postProcessConnectionSession(l.connSessionRec)}).then(function(){return handleUpdatedCS(S.csM2P)}).then(function(){n&&u<CSINHEAD_SYNC_VSN?maybeSyncConnSess(l.connSessionRec,function(){S["Session Number"]&&S["Session Number"]<S["Total Sessions"]?p2mRefreshTable(e,t,n,S["Session Number"]+1,S["Total Sessions"],S.CsPId,a,c):S.moreBatches?p2mRefreshTable(e,t,n,"newBatch",1,null,a,c):(p.status=P2M_REFRESH_OK,a(p))},c):S["Session Number"]&&S["Session Number"]<S["Total Sessions"]?p2mRefreshTable(e,t,n,S["Session Number"]+1,S["Total Sessions"],S.CsPId,a,c):S.moreBatches?p2mRefreshTable(e,t,n,"newBatch",1,null,a,c):(p.status=P2M_REFRESH_OK,a(p))}).catch(function(e){c(e)})}else"exception"===d.type&&logger.error("p2mRefresh",e,d.message,d.where),cleanConnectionSessionVFEvent(d,l,function(e){p.status=SYNC_NOK,p.mc_add_status=e.mc_add_status,o>1&&(p.csPId=r,p.sessNum=o,p.totalSess=s),a(p)},c)},p={},S="newBatch"==o;S&&(o=1);try{smartStoreUtils.getTableDefnColumnValue(e,"Last Refresh Date/Time").then(function(e){(d=e)&&"null"!=d||(d=0);var s=new Date;return d<s-t||o>1||S||!n?appDataUtils.getCachedCurrentValueFromAppSoup("audId"):(p.status=100402,p.status=100497,a(p),Promise.reject(p))}).then(function(e){return i=e,appDataUtils.getCachedCurrentValueFromAppSoup("syncRefreshVersion")}).then(function(e){return buildConnectionSession(u=e,"Sync - Refresh","P2M RE Process Called",o,s,r)}).then(function(e){if(l=e,!n){var t=JSON.parse(l.connSessJson);t.initialSync=!0,l.connSessJson=JSON.stringify(t)}if(S){var o=JSON.parse(l.connSessJson);o.firstBatch=!1,l.connSessJson=JSON.stringify(o)}return getCsUpdates(u,n)}).then(function(t){t&&(l.connSessJson=JSON.parse(l.connSessJson),l.connSessJson.csM2P=t,l.connSessJson=JSON.stringify(l.connSessJson)),useSdkReq()?plugin.mcsdk.request({method:"POST",path:"/services/apexrest/mobilecaddy1/p2mRefreshTable001",contentType:"application/json",data:{audId:i,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN,syncRefreshDataVersion:u,mobileTableName:e,deviceRefreshIds:[],lastRefreshDateTime:d,thirdPartyJson:"",connSessJson:l.connSessJson}},function(e){var t={status:e.status};_(JSON.parse(e.data),t)},function(e){_({},{type:"exception",status:null})}):!0===USE_FORCETK?force.request({method:"POST",path:"/services/apexrest/mobilecaddy1/p2mRefreshTable001",contentType:"application/json",data:{audId:i,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN,syncRefreshDataVersion:u,mobileTableName:e,deviceRefreshIds:[],lastRefreshDateTime:d,thirdPartyJson:"",connSessJson:l.connSessJson}},function(e,t){void 0===t&&((t={}).status="200"),_(e,t)},c):Visualforce.remoting.Manager.invokeAction("mobilecaddy1."+mobileCaddy.START_PAGE_CONTROLLER+".p2mRefreshTable",i,u,e,[],d,"",l.connSessJson,_,{buffer:!1,escape:!1,timeout:12e4})}).catch(function(e){100497==e.status?a(e):(logger.error(e),c(e))})}catch(e){logger.errorAndDispatch(e)}}function genProxyId(e,t,n){return new Promise(function(o,s){appDataUtils.getCachedCurrentValueFromAppSoup("audId").then(function(s){o("PROXY%"+e+"%"+n+"%"+t+"%"+s)}).catch(function(e){s(e)})})}function addProxyIds(e,t,n,o,s){var r;smartStoreUtils.getProxyFieldName(e).then(function(e){return r=e,appDataUtils.getCachedCurrentValueFromAppSoup("audId")}).then(function(a){t.forEach(function(t){var o="PROXY%"+e+"%"+n+"%"+t._soupEntryId+"%"+a;t.Id=o,t[r]=o}),(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntries(e,t,function(e){o(e)},s)}).catch(function(e){s(e)})}function nullHandler(e,t,n,o){var s;if("Throw Exception"==o)throw logger.errorAndDispatch("nullHandler - NULL value found",e,t,n.Id),"NULL value found for field "+t+" in Mobile Table "+e+" with Id = "+n.Id;return"Return NULL"==o?s=null:"Return Empty String"==o&&(s=""),s}function getCsUpdates(e,t){return new Promise(function(n,o){if(e<CSINHEAD_SYNC_VSN||!t)n();else{var s,r=[];smartStoreUtils.queryMobileTable("recsToSync","Mobile_Table_Name","Connection_Session__mc").then(function(e){return(s=e).length>0?smartStoreUtils.querySoupRecsPromise("Connection_Session__mc"):Promise.resolve([])}).then(function(e){s.forEach(function(t){for(var n,o=0;o<e.length;++o)if(e[o].Id===t.Id&&e[o].Id.length<20){n=e[o];break}n&&r.push({Id:t.Id,t:valFromCsSessionType(n.mobilecaddy1__Session_Type__c),s:valFromCsStatus(n.mobilecaddy1__Mobile_Process_Status__c)})}),n(r)}).catch(function(e){logger.error(e),n(null)})}})}function valFromCsStatus(e){switch(e){case"P2M RE Records Processed":return 1;case"P2M Conn_Sess Records Processed":return 2;case"P2M RE Abandoned":return 3;case"P2M RE Exception/Timeout":return 4;case"P2M RE Heartbeat Exception/Timeout":return 5;case"P2M RE Failure":return 6;case"P2M RE Hearbeat Failure":return 7;case"M2P Conn_Sess Records Processed":return 8;case"M2P Records Processed":return 9;case"M2P UP Failed - RTS Cleared":return 10;case"M2P SC - Status Check Processed":return 11;case"M2P SC Failure":return 12;case"M2P SC Exception/Timeout":return 13;case"M2P SC Heartbeat Exception/Timeout":return 14;case"M2P SC Heartbeat Failure":return 15;case"M2P UP Received - Records Processed":return 16;case"P2M InitialSync Faliure":return 17;default:return logger.error("Unknown CS status",e),0}}function valFromCsSessionType(e){switch(e){case"Sync - Refresh":return 1;case"Sync - Update":return 2;case"Status Check":return 3;default:return logger.error("Unkown Session_Type__c",e),0}}function createUpdateJson(e,t,n,o,s,r,a,c,i,u,d){var l={MobileTable:e,connSessProxyId:u,records:[]},_=[];a.forEach(function(a){for(var u,d=0;d<c.length;++d)if(c[d].Id===a.Id){u=c[d];break}if(u){var p={RTSRowNum:a._soupEntryId,RecordCRUD:mapCrudOpforM2P(a.CRUD_Operation),fields:[]};switch(p.RecordCRUD){case"I":case"T":p=createM2PInsertRecObj(p,e,t,n,o,s,r,u),l.records.push(p);break;case"D":case"U":case"Q":for(var S,f=0;f<i.length;++f)if(i[f].Id===a.Id){S=i[f];break}S?(p=createM2PUpdateRecObj(p,e,t,n,o,s,r,u,S),l.records.push(p)):logger.errorAndDispatch("createUpdateJson Missing snapShot",e,u.Id);break;default:logger.errorAndDispatch("createUpdateJson unknown CRUD",e,a.Id,a.CRUD_Operation)}}else{var m=!1,R=!0,h=!1,E=void 0;try{for(var C,T=c[Symbol.iterator]();!(R=(C=T.next()).done);R=!0){var y=C.value;"Insert"==a.CRUD_Operation&&y.mobilecaddy1__MC_Proxy_ID__c===a.Id&&(m=!0)}}catch(e){h=!0,E=e}finally{try{R||null==T.return||T.return()}finally{if(h)throw E}}m?(logger.warn("createUpdateJson RTS Rec matched against Proxy not Id.",a.Id),_.push(a._soupEntryId)):logger.errorAndDispatch("createUpdateJson Missing primary",e,a.Id)}_.length>0&&m2pRespDelRTSRecs(_)}),d(JSON.stringify(l))}function mapCrudOpforM2P(e){switch(e){case"Insert":return"I";case"InsertDelete":return"T";case"Update":return"U";case"UpdatetDelete":return"Q";case"Delete":return"D";default:return null}}function createM2PInsertRecObj(e,t,n,o,s,r,a,c){for(var i in c){var u={name:i};if("mobilecaddy1__Error_Text__c"==i)u.value=JSON.stringify(c[i]),e.fields.push(u);else if("_soupEntryId"!=i&&"_soupLastModifiedDate"!=i){var d,l={};l[o]=i;var p=_.findWhere(n,l);if(null===c[i])d=nullHandler(t,i,c,p[r]);else if(d=c[i],p)"M2P UP Unquoted"!=p[a]||"true"!=d&&"false"!=d||(d="true"==d);u.value=d,e.fields.push(u)}}return e}function createM2PUpdateRecObj(e,t,n,o,s,r,a,c,i){var u=!1;for(var d in c)if("_soupEntryId"!=d&&"_soupLastModifiedDate"!=d){var l={name:d};if(c[d]!=i[d]||"SystemModstamp"==d){var p,S;u=!0;var f=null,m=null,R={};R[o]=d;var h=_.findWhere(n,R);null===c[d]?p=nullHandler(t,d,c,f=h[r]):(p=c[d],h&&("M2P UP Unquoted"!=(m=h[a])||"true"!=p&&"false"!=p||(p="true"==p))),null===i[d]&&h?(f||(f=h[r]),S=nullHandler(t,d,i,f)):(S=i[d],h&&(m||(m=h[a]),"M2P UP Unquoted"!=m||"true"!=S&&"false"!=S||(S="true"==S))),l.previousValue=S,l.value=p,e.fields.push(l)}}return u?(e.fields.push({name:"Id",previousValue:i.Id,value:i.Id}),e):[]}function markRecsToSyncWithProxy(e,t,n,o){e.forEach(function(e){e.Current_Connection_Session=t}),(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntriesWithExternalId("recsToSync",e,"Id",n,o)}function createInsertSnapshotRecords(e,t,n,o,s){var r=[];t.forEach(function(e){var t={};n.forEach(function(n){if(e.Id==n.Id&&"Insert"==e.CRUD_Operation)for(var o in n)"_soupEntryId"!=o&&"_soupLastModifiedDate"!=o&&(t[o]=n[o])}),_.isEmpty(t)||r.push(t)}),0===r.length?o():smartStoreUtils.getProxyFieldName(e).then(function(t){(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntriesWithExternalId("SnapShot_"+e,r,t,o,s)})}function buildConnectionSession(e,t,n,o,s,r){return new Promise(function(e,a){var c={};geoLocation.getLocation(function(i){var u={mobilecaddy1__Session_Type__c:t,mobilecaddy1__Mobile_Process_Status__c:n,SystemModstamp:(new Date).getTime()},d=i.ErrorNumber;0!==d?u.mobilecaddy1__Session_Created_Location_Error__c=i.Error:(u.Session_Created_Location__Longitude__s=i.Latitude,u.Session_Created_Location__Latitude__s=i.Longitude),insertRecWithProxyId("Connection_Session__mc",u,function(t){var n=new Date,a={"Sync Session Proxy ID":null,"Total Sessions":s,"Session Number":o,"Device Call Date/Time":n.getTime(),"Connection Session Proxy ID":t.proxyId};r&&(a.CsPId=r),0!==d?a.ErrorNumber=d:(a["Location Long"]=i.Longitude,a["Location Lat"]=i.Latitude),c.status=0,c.connSessionRec=t.insertedRecord,c.connSessProxyId=t.proxyId;var u={version:"NULL"};window.device&&(u=window.device),appDataUtils.getCurrentValueFromAppSoup("containerVersion").then(function(t){a.containerVsn=t,a.OSVsn=u.version,c.connSessJson=JSON.stringify(a),e(c)}).catch(function(t){logger.error("buildConnectionSession - Could not get containerVsn",t),a.OSVsn=u.version,c.connSessJson=JSON.stringify(a),e(c)})},function(e){a(e)})},function(e){a(e)})})}function m2pRecoveryUpdateMobileTable(e){return new Promise(function(t,n){var o={},s=function(e){t(e)},r=function(e){n(e)},a=(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).buildExactQuerySpec("Mobile_Table_Name",e,mobileCaddy.QUERY_BUFFER_SIZE);smartStoreUtils.querySoupRecordsWithQuerySpec("recsToSync",a,function(t){if(0!==t.length){var n=!1;"Connection_Session__mc"!=e&&t.length>3e4&&(n=!0);var a=[];a=n?(a=_.sortBy(t,"_soupLastModifiedDate")).slice(0,3e4):t,smartStoreUtils.querySoupRecords(e,function(t){smartStoreUtils.querySoupRecords("SnapShot_"+e,function(n){smartStoreUtils.getSysDataRowMapColHeadings("Row Mapping TC",["Parent SOUP Name","Table Column Name","M2P Update Converter DEVICE","M2P Update NULL Handler DEVICE","M2P Update Formatter DEVICE"],function(c){var i=c[0],u=c[1],d=c[2],l=c[3],p=c[4];smartStoreUtils.queryMobileTableWithAnd("syncLib_system_data","MC_Var_String_001","Platform Table Column",i,e,function(c){var i=[];_.each(a,function(e){var n;n=e.Id,_.find(t,function(e){return e.Id==n})&&i.push(e)}),_.isEmpty(i)?smartStoreUtils.setTableDefnColumnValue(e,"Last Sync Date/Time",(new Date).getTime()).then(function(){o.status=M2P_UPDATE_OK,o.mc_add_status=M2P_NO_RECS_TO_SYNC,s(o)}).catch(function(e){logger.error(e)}):createUpdateJson(e,c,u,d,l,p,i,t,n,"",function(n){var c;appDataUtils.getCachedCurrentValueFromAppSoup("audId").then(function(e){return c=e,appDataUtils.getCachedCurrentValueFromAppSoup("syncRefreshVersion")}).then(function(i){createInsertSnapshotRecords(e,a,t,function(){var t=function(e,t){o.result=e,o.event=t,s(o)};n=n.replace(/: undefined/g,': "undefined"'),useSdkReq()?plugin.mcsdk.request({method:"POST",path:"/services/apexrest/mobilecaddy1/m2pUpdateTable001",contentType:"application/json",data:{audId:c,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN,syncRefreshDataVersion:i,mobileTableName:e,jsonRecords:n,connSessJson:"{}"}},function(e,n){void 0===n&&((n={}).status="200"),t(JSON.parse(e.data),n)},function(e){t({},{type:"exception",status:null})}):!0===USE_FORCETK?force.request({method:"POST",path:"/services/apexrest/mobilecaddy1/m2pUpdateTable001",contentType:"application/json",data:{audId:c,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN,syncRefreshDataVersion:i,mobileTableName:e,jsonRecords:n,connSessJson:"{}"}},function(e,n){void 0===n&&((n={}).status="200"),t(e,n)},r):Visualforce.remoting.Manager.invokeAction("mobilecaddy1."+mobileCaddy.START_PAGE_CONTROLLER+".m2pUpdateTable",c,i,e,n,JSON.stringify({"Session Number":1,"Location Long":10,"Location Lat":10,"Total Sessions":1,"Device Call Date/Time":(new Date).getTime(),"Connection Session Proxy ID":"1",ErrorNumber:2}),t,{buffer:!1,escape:!1,timeout:3e4})},r)}).catch(function(e){r(e)})},r)},r)},r)},r)},r)}else smartStoreUtils.setTableDefnColumnValue(e,"Last Sync Date/Time",(new Date).getTime()).then(function(){o.status=M2P_UPDATE_OK,o.mc_add_status=M2P_NO_RECS_TO_SYNC,s(o)}).catch(function(e){logger.log("No recs to sync")})},r)})}var M2P_UPDATE_OK=100300;exports.M2P_UPDATE_OK=M2P_UPDATE_OK;var M2P_NO_RECS_TO_SYNC=100310;function m2pUpdateMobileTable(e,t,n,o){var s,r,a={};try{appDataUtils.getCachedCurrentValueFromAppSoup("syncRefreshVersion").then(function(e){r=e;var t=localStorage.getItem("mcM2pMoreToSync")?2:1;return buildConnectionSession(r,"Sync - Update","M2P Process Called",t,t,null)}).then(function(e){return s=e,getCsUpdates(r,!0)}).then(function(c){c&&(s.connSessJson=JSON.parse(s.connSessJson),s.connSessJson.csM2P=c,s.connSessJson=JSON.stringify(s.connSessJson));var i=(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).buildExactQuerySpec("Mobile_Table_Name",e,mobileCaddy.QUERY_BUFFER_SIZE);smartStoreUtils.querySoupRecordsWithQuerySpec("recsToSync",i,function(c){var i=filterFailedRecsFromThisSync(c);if(0!==i.length){var u=!1;"Connection_Session__mc"!=e&&i.length>t?(u=!0,localStorage.setItem("mcM2pMoreToSync","true")):localStorage.removeItem("mcM2pMoreToSync");markRecsToSyncWithProxy(u?_.sortBy(i,"_soupLastModifiedDate").slice(0,t):i,s.connSessProxyId,function(t){smartStoreUtils.querySoupRecords(e,function(c){smartStoreUtils.querySoupRecords("SnapShot_"+e,function(i){smartStoreUtils.getSysDataRowMapColHeadings("Row Mapping TC",["Parent SOUP Name","Table Column Name","M2P Update Converter DEVICE","M2P Update NULL Handler DEVICE","M2P Update Formatter DEVICE"],function(d){var l=d[0],_=d[1],p=d[2],S=d[3],f=d[4];smartStoreUtils.queryMobileTableWithAnd("syncLib_system_data","MC_Var_String_001","Platform Table Column",l,e,function(d){createUpdateJson(e,d,_,p,S,f,t,c,i,s.connSessProxyId,function(i){var d;JSON.parse(i).records.length>0?appDataUtils.getCachedCurrentValueFromAppSoup("audId").then(function(l){d=l,createInsertSnapshotRecords(e,t,c,function(){var t=function(t,c){var d;c.status?(t=t.replace(/,}/g,"}"),processM2PUpdateResponse(d=JSON.parse(t),i,function(t){s.connSessionRec.mobilecaddy1__Mobile_Process_Status__c="Connection_Session__mc"==e?"M2P Conn_Sess Records Processed":"M2P Records Processed",s.connSessionRec.Id=t.csId,postProcessConnectionSession(s.connSessionRec).then(function(){return handleUpdatedCS(d.csM2P)}).then(function(){u?(a.status=M2P_UPDATE_OK,a.mc_add_status="more-to-sync",n(a)):r<CSINHEAD_SYNC_VSN?maybeSyncConnSess(s.connSessionRec,function(){a.status=M2P_UPDATE_OK,n(a)},o):(a.status=M2P_UPDATE_OK,n(a))}).catch(function(e){o(e)})},o)):"exception"===c.type?(a.status=M2P_UPDATE_OK,a.mc_add_status=HEARTBEAT_EXCEPTION,n(a),logger.error("m2pUpdate",e,c.message,c.where)):(a.status=M2P_UPDATE_OK,a.mc_add_status=HEARTBEAT_FAILURE,n(a),logger.error("m2pUpdate",e,c.message,c.where))};i=i.replace(/: undefined/g,': "undefined"'),useSdkReq()?plugin.mcsdk.request({method:"POST",path:"/services/apexrest/mobilecaddy1/m2pUpdateTable001",contentType:"application/json",data:{audId:d,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN,syncRefreshDataVersion:r,mobileTableName:e,jsonRecords:i,connSessJson:s.connSessJson}},function(e,n){void 0===n&&((n={}).status="200"),t(JSON.parse(e.data),n)},function(e){t({},{type:"exception",status:null})}):!0===USE_FORCETK?force.request({method:"POST",path:"/services/apexrest/mobilecaddy1/m2pUpdateTable001",contentType:"application/json",data:{audId:d,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN,syncRefreshDataVersion:r,mobileTableName:e,jsonRecords:i,connSessJson:s.connSessJson}},function(e,n){void 0===n&&((n={}).status="200"),t(e,n)},o):Visualforce.remoting.Manager.invokeAction("mobilecaddy1."+mobileCaddy.START_PAGE_CONTROLLER+".m2pUpdateTable",d,r,e,i,s.connSessJson,t,{buffer:!1,escape:!1,timeout:3e4})},o)}).catch(function(e){o(e)}):(logger.warn("m2pUpdateMobileTable Zero length records"),a.status=M2P_UPDATE_OK,n(a))},o)},o)},o)},o)},o)},o)}else smartStoreUtils.setTableDefnColumnValue(e,"Last Sync Date/Time",(new Date).getTime()).then(function(){a.status=M2P_UPDATE_OK,a.mc_add_status=M2P_NO_RECS_TO_SYNC,n(a)}).catch(function(e){o(e)})},o)},o)}catch(e){logger.errorAndDispatch(e)}}function filterFailedRecsFromThisSync(e){var t=JSON.parse(localStorage.getItem("tmpFailedRecordsAccum"));return t?e.filter(function(e){return!t[e.Id]}):e}function insertRecWithProxyId(e,t,n,o){var s={},r=new Date,a=window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore");smartStoreUtils.getProxyFieldName(e).then(function(c){a.upsertSoupEntries(e,[t],function(t){var i=t[0];genProxyId(e,i._soupEntryId,r.getTime()).then(function(t){i.Id=t,i[c]=t,a.upsertSoupEntries(e,[i],function(e){s.status=0,s.proxyId=t,s.insertedRecord=e[0],n(s)},o)}).catch(function(e){o(e)})},o)}).catch(function(e){o(e)})}exports.M2P_NO_RECS_TO_SYNC=M2P_NO_RECS_TO_SYNC;var HEARTBEAT_OK=100100;exports.HEARTBEAT_OK=HEARTBEAT_OK;var HEARTBEAT_EXCEPTION=100101;exports.HEARTBEAT_EXCEPTION=HEARTBEAT_EXCEPTION;var HEARTBEAT_FAILURE=100102;exports.HEARTBEAT_FAILURE=HEARTBEAT_FAILURE;var HEARTBEAT_NO_CONNECTION=100103;exports.HEARTBEAT_NO_CONNECTION=HEARTBEAT_NO_CONNECTION;var HEARTBEAT_NOT_DEVICE=100104;exports.HEARTBEAT_NOT_DEVICE=HEARTBEAT_NOT_DEVICE;var HEARTBEAT_REFRESHED_OK=100105;function heartBeat(e,t){var n={},o=navigator.appVersion.includes("Electron");o||navigator&&navigator.connection&&"undefined"!=typeof Connection?o||navigator.connection.type!=Connection.NONE?useSdkReq()?sendSDKHeartBeat(e,t):"undefined"==typeof Visualforce?(logger.log("Visualforce not currently defined"),resetStartPageAndScript().then(function(n){sendHeartBeat(e,t)}).catch(function(t){logger.errorAndDispatch("Startpage Load Error: "+window.location.pathname,t),n.status=HEARTBEAT_FAILURE,e(n)})):sendHeartBeat(e,t):(n.status=HEARTBEAT_NO_CONNECTION,e(n)):(localStorage.connection?n.status=localStorage.connection:n.status=HEARTBEAT_NOT_DEVICE,e(n))}function resetStartPageAndScript(){return new Promise(function(e,t){var n=window.location.pathname,o=new XMLHttpRequest;o.open("GET",n,!0),o.send(),o.onreadystatechange=function(){if(o.readyState==XMLHttpRequest.DONE&&200==o.status){logger.log("Startpage re-fetched",n);var e=new RegExp('"(\\S+VFRemote.js)"').exec(o.response);if(e&&e[0]){var s=e[1];getScript(s,function(){logger.log("remote script fetched",s),logger.log("set up Visualforce ref")})}else t("Could not find VFRemote.js mention in "+n)}else o.readyState==XMLHttpRequest.DONE&&t(o.status)}})}function getScript(e,t){var n=document.createElement("script"),o=document.getElementsByTagName("script")[0];n.async=1,n.onload=n.onreadystatechange=function(e,o){(o||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n=void 0,o||t&&t())},n.src=e,o.parentNode.insertBefore(n,o)}function sendSDKHeartBeat(e,t){var n={};plugin.mcsdk.request({method:"POST",path:"/services/apexrest/mobilecaddy1/heartBeat001",contentType:"application/json",data:{startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN}},function(t){t.status?(n.status=HEARTBEAT_OK,e(n)):(n.status=HEARTBEAT_FAILURE,e(n))},function(t){401===t.status?mcsdkRefreshToken(function(t){n.status=HEARTBEAT_REFRESHED_OK,e(n)},function(t){n.status=HEARTBEAT_EXCEPTION,e(n)}):(logger.error("sendSDKHeartBeat ERR",t),n.status=HEARTBEAT_FAILURE,e(n))})}function sendHeartBeat(e,t){var n={};Visualforce.remoting.Manager.invokeAction("mobilecaddy1."+mobileCaddy.START_PAGE_CONTROLLER+".heartBeat",function(t,o){o.status?(n.status=HEARTBEAT_OK,e(n)):"exception"===o.type?refreshToken(function(t){n.status=HEARTBEAT_REFRESHED_OK,e(n)},function(t){n.status=HEARTBEAT_EXCEPTION,e(n)}):(n.status=HEARTBEAT_FAILURE,e(n))},{escape:!1,timeout:3e4})}function refreshToken(e,t){useSdkReq()?mcsdkRefreshToken(e,t):smartStoreUtils.querySoupRecords("appSoup",function(n){var o={};n.forEach(function(e){o[e.Name]=e.CurrentValue}),refreshTokenRequest(o,e,t)},function(e){t(e)})}function refreshTokenRequest(e,t,n){arguments.length>3&&void 0!==arguments[3]&&arguments[3];var o="grant_type=refresh_token&identity_url="+e.identityUrl+"&client_id="+e.clientId+"&refresh_token="+e.refreshToken+"&orgId="+e.orgId+"&audId="+e.audId+"&userId="+e.userId,s=new XMLHttpRequest;s.open("POST","https://mobilecaddy.secure.force.com/apex/ProxyToken",!0),s.setRequestHeader("Content-type","application/x-www-form-urlencoded"),s.send(o),s.onreadystatechange=function(){if(s.readyState==XMLHttpRequest.DONE&&200==s.status){var e=JSON.parse(s.response);Visualforce.remoting.oauthAccessToken=e.access_token,Visualforce.remoting.last.refresh(function(){appDataUtils.updateCurrentValueInAppSoup("accessToken",e.access_token).then(function(){t(e.access_token)}).catch(function(e){n(e)})},function(e){logger.error("in VF last refresh error"),n(e)})}else s.readyState==XMLHttpRequest.DONE&&logger.error("refreshTokenRequest error.",s.status)}}function mcsdkRefreshToken(e,t){plugin.mcsdk.refreshAccessToken(function(n){n.result?appDataUtils.updateCurrentValueInAppSoup("accessToken",n.result).then(function(){e(n.result)}).catch(function(e){logger.error("mcsdkRefreshToken updateCurrentValueInAppSoup ERROR",e),t(e)}):(logger.error("mcsdkRefreshToken ERROR",n),t(n))},function(e){logger.error("mcsdkRefreshToken ERROR",e),t(e)})}function getRTSPendingconnSess(e,t){smartStoreUtils.querySoupRecords("recsToSync",function(n){for(var o=null,s=null,r=0;r<n.length;r++)if(null!==n[r].Current_Connection_Session&&void 0!==n[r].Current_Connection_Session){o=n[r].Current_Connection_Session,s=n[r];break}if(null!==o&&void 0!==o){var a=(new Date).getTime(),c=s._soupLastModifiedDate+3e4;if(a>c)e(o);else{var i={status:100498};t(i)}}else e(o)},t)}exports.HEARTBEAT_REFRESHED_OK=HEARTBEAT_REFRESHED_OK;var CONN_SESS_OK=100200;exports.CONN_SESS_OK=CONN_SESS_OK;var CONN_SESS_NOK=100201;function csStatusCheck(e,t,n){try{var o;appDataUtils.getCachedCurrentValueFromAppSoup("syncRefreshVersion").then(function(e){return buildConnectionSession(o=e,"Status Check","M2P SC Status Check Requested",1,1,null)}).then(function(s){heartBeat(function(r){var a;r.status==HEARTBEAT_OK||r.status==HEARTBEAT_NOT_DEVICE||r.status==HEARTBEAT_REFRESHED_OK?appDataUtils.getCachedCurrentValueFromAppSoup("audId").then(function(r){a=r;var c=function(o,r){var a;r.status?((a=JSON.parse(o)).cs_fc_jr&&(a.cs_fc_jr=JSON.parse(a.cs_fc_jr)),"Received Processed"==a.cs_fc_sc?handleCsStatusCheckRespReceivedProcessed(s,a,t,n):clearRTSRecs(e,function(){smartStoreUtils.queryMobileTable("Connection_Session__mc","mobilecaddy1__MC_Proxy_ID__c",e,function(e){if(e.length>0){var o=e[0];"Received Not Processed"==a.cs_fc_sc?handleCsStatusCheckRespReceivedNotProcessed(o,s,a,t,n):handleCsStatusCheckRespNotReceived(o,s,a,t,n)}else t({status:CONN_SESS_OK})},n)},n)):(logger.error("csStatusCheck",r.message),t({status:CONN_SESS_NOK}))},i=s.connSessJson,u=localStorage.getItem("lastErrorLog");u&&(localStorage.removeItem("lastErrorLog"),(i=JSON.parse(i)).lastErrorLog=u,i=JSON.stringify(i)),useSdkReq()?plugin.mcsdk.request({method:"POST",path:"/services/apexrest/mobilecaddy1/m2pCSStatusCheck001",contentType:"application/json",data:{audId:a,syncRefreshDataVersion:o,statusCheckCSProxyId:e,connSessJson:i,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN}},function(e,t){void 0===t&&((t={}).status="200"),c(JSON.parse(e.data),t)},function(e){logger.error("err -> "+JSON.stringify(e)),n(e)}):!0===USE_FORCETK?force.request({method:"POST",path:"/services/apexrest/mobilecaddy1/m2pCSStatusCheck001",contentType:"application/json",data:{audId:a,syncRefreshDataVersion:o,statusCheckCSProxyId:e,connSessJson:i,startPageControllerVersion:mobileCaddy.START_PAGE_CONTROLLER_VSN}},function(e,t){void 0===t&&((t={}).status="200"),c(e,t)},function(e){logger.error("err -> "+JSON.stringify(e)),n(e)}):Visualforce.remoting.Manager.invokeAction("mobilecaddy1."+mobileCaddy.START_PAGE_CONTROLLER+".m2pCSStatusCheck",a,o,e,i,c,{buffer:!1,escape:!1,timeout:3e4})}).catch(function(e){n(e)}):cleanConnectionSessionHeartBeat(r,s,function(e){t({status:CONN_SESS_OK,mc_add_status:e.mc_add_status})},n)},n)}).catch(function(e){n(e)})}catch(e){logger.errorAndDispatch(e)}}function handleCsStatusCheckRespReceivedProcessed(e,t,n,o){try{processM2PUpdateResponse(t.cs_fc_jr,function(s){e.connSessionRec.mobilecaddy1__Mobile_Process_Status__c="M2P SC - Status Check Processed",e.connSessionRec.SystemModstamp=(new Date).getTime(),e.connSessionRec.mobilecaddy1__Status__c="Closed",e.connSessionRec.Id=t.cs_sc_sf,smartStoreUtils.queryMobileTable("Connection_Session__mc","Id",t.cs_fc_jr.cp).then(function(n){if(n[0]){var o=n[0];return o.Id=t.cs_fc_jr.csId,o.SystemModstamp=(new Date).getTime(),o.mobilecaddy1__Mobile_Process_Status__c="M2P Records Processed",postProcessConnectionSession([e.connSessionRec,o])}return Promise.resolve()}).then(function(){n({status:CONN_SESS_OK})}).catch(function(e){o(e)})},o)}catch(e){logger.errorAndDispatch("processM2PUpdateResponse",e),o("processM2PUpdateResponse-error")}}function handleCsStatusCheckRespReceivedNotProcessed(e,t,n,o,s){e.mobilecaddy1__Mobile_Process_Status__c="M2P UP Failed - RTS Cleared",e.mobilecaddy1__Session_Type__c="Sync Update",e.mobilecaddy1__Status__c="Closed",e.SystemModstamp=(new Date).getTime(),e.Id=n.cs_fc_sf,postProcessConnectionSession(e).then(function(){t.connSessionRec.mobilecaddy1__Mobile_Process_Status__c="M2P SC - Status Check Processed",t.connSessionRec.SystemModstamp=(new Date).getTime(),t.connSessionRec.mobilecaddy1__Status__c="Closed",t.connSessionRec.Id=n.cs_sc_sf,postProcessConnectionSession(t.connSessionRec,function(){o({status:CONN_SESS_OK})},s)}).catch(function(e){s(e)})}function handleCsStatusCheckRespNotReceived(e,t,n,o,s){smartStoreUtils.deleteRecordsFromSoup([e],"Connection_Session__mc",function(e){t.connSessionRec.mobilecaddy1__Mobile_Process_Status__c="M2P SC - Status Check Processed",t.connSessionRec.SystemModstamp=(new Date).getTime(),t.connSessionRec.mobilecaddy1__Status__c="Closed",t.connSessionRec.Id=n.cs_sc_sf,t.connSessionRec.mobilecaddy1__Session_Type__c="Status Check",postProcessConnectionSession(t.connSessionRec).then(function(){o({status:CONN_SESS_OK})}).catch(function(e){s(e)})},s)}function processM2PUpdateResponse(e,t,n,o){o||(o=n,n=t,t="{}");var s=1,r=e.mt,a=void 0!==e.is?e.is:[],c=void 0!==e.id?e.id:[],i=void 0!==e.us?e.us:[],u=void 0!==e.ifmf?e.ifmf:[],d=void 0!==e.ufmf?e.ufmf:[],l=[],_=[],p=[],S=[],f=[],m=[],R=[],h=[],E=[],C=[],T=[];if(a=a.concat(c),storeSyncFailures(r,e.af,a,i),void 0===e.if)C=[];else if(void 0===e.if.if)C=e.if;else{s=2;var y=e.if.if.map(function(t){return{pd:t,fbe:void 0!==e.ifbe?e.ifbe:"K"}}),g=e.if.ifv.map(function(t){return{pd:t,fbe:void 0!==e.ifvbe?e.ifvbe:"K"}}),b=e.if.icv.map(function(t){return{pd:t,fbe:void 0!==e.icvbe?e.icvbe:"K"}});C=y.concat(g.concat(b))}addNonRespondedIds(t,a,C,u).then(function(t){if(C=t,void 0===e.uf)T=[];else if(void 0===e.uf.uf)T=e.uf;else{s=2;var n=e.uf.uf.map(function(t){return{Id:t,fbe:void 0!==e.ufbe?e.ufbe:"K"}}),o=e.uf.usv.map(function(t){return{Id:t,fbe:void 0!==e.usvbe?e.usvbe:"K"}}),a=e.uf.sdf.map(function(t){return{Id:t,fbe:void 0!==e.sdfbe?e.sdfbe:"K"}}),c=e.uf.hdf.map(function(t){return{Id:t,fbe:void 0!==e.hdfbe?e.hdfbe:"K"}}),i=e.uf.ufv.map(function(t){return{Id:t,fbe:void 0!==e.ufvbe?e.ufvbe:"K"}}),u=e.uf.ucv.map(function(t){return{Id:t,fbe:void 0!==e.ucvbe?e.ucvbe:"K"}});T=n.concat(o.concat(a.concat(c.concat(i.concat(u)))))}return querySoupRecsPromise("SnapShot_"+r)}).then(function(e){return E=e,querySoupRecsPromise(r)}).then(function(t){smartStoreUtils.queryMobileTable("recsToSync","Mobile_Table_Name",r,function(c){for(var y in c)if(c[y].Current_Connection_Session==e.cp){var g=!1,b={},I={};switch(c[y].CRUD_Operation){case"Insert":case"InsertUpdate":for(var P in a)if(c[y].Id==a[P].pd){if(a[P].crud=c[y].CRUD_Operation,I=priFromRespRec(a[P],t),"Insert"==c[y].CRUD_Operation){switch(e.stbe){case"D":R.push(I),h.push(a[P]);break;default:if("U"==a[P].pc){if(I.Id=a[P].Id,void 0!==a[P].an&&(void 0!==a[P].nf?I[a[P].nf]=a[P].an:I.Name=a[P].an),void 0!==a[P].lu)for(var O in a[P].lu)a[P].lu.hasOwnProperty(O),I[O]=a[P].lu[O];S.push(I),m.push(I)}}_.push(c[y]._soupEntryId)}else{if(I.Id=a[P].Id,void 0!==a[P].an&&(void 0!==a[P].nf?I[a[P].nf]=a[P].an:I.Name=a[P].an),void 0!==a[P].lu)for(var v in a[P].lu)a[P].lu.hasOwnProperty(v),I[v]=a[P].lu[v];S.push(I);var U=priFromRespRec(a[P],E);U.Id=a[P].Id,m.push(U),(b=c[y]).Current_Connection_Session=null,b.CRUD_Operation="Update",b.Id=a[P].Id,l.push(b)}g=!0;break}if(!g)for(P in C)if(c[y].Id==C[P].pd){if(C[P].crud=c[y].CRUD_Operation,"Insert"==c[y].CRUD_Operation)switch("K",1==s?getFailBehaviour(0,C[P].fl,e):C[P].fbe){case"K":(b=c[y]).Current_Connection_Session=null,l.push(b);break;case"R":break;default:I=priFromRespRec(C[P],t),R.push(I),_.push(c[y]._soupEntryId),h.push(C[P])}else"InsertUpdate"==c[y].CRUD_Operation&&((b=c[y]).Current_Connection_Session=null,b.CRUD_Operation="Insert",l.push(b));g=!0;break}if(!g)for(P in u)if(c[y].Id==u[P].pd){if(u[P].crud=c[y].CRUD_Operation,"Insert"==c[y].CRUD_Operation)switch(u[P].fbe){case"K":(b=c[y]).Current_Connection_Session=null,l.push(b);break;case"R":break;default:I=priFromRespRec(u[P],t),R.push(I),_.push(c[y]._soupEntryId),h.push(u[P])}else"InsertUpdate"==c[y].CRUD_Operation&&((b=c[y]).Current_Connection_Session=null,b.CRUD_Operation="Insert",l.push(b));g=!0;break}break;case"Update":case"UpdateUpdate":for(P in i)if(c[y].Id==i[P].Id){if(i[P].crud=c[y].CRUD_Operation,"Update"==c[y].CRUD_Operation){switch(I=priFromRespRec(i[P],t),e.stbe){case"D":R.push(I),h.push(i[P]);break;default:if("M"==i[P].pc&&(I.SystemModstamp=new Date(i[P].sm)),void 0!==i[P].lu)for(var N in i[P].lu)i[P].lu.hasOwnProperty(N)&&(I[N]=i[P].lu[N]);p.push(I),f.push(I)}_.push(c[y]._soupEntryId)}else"UpdateUpdate"==c[y].CRUD_Operation&&((b=c[y]).Current_Connection_Session=null,b.CRUD_Operation="Update",l.push(b));g=!0;break}if(!g)for(P in T)if(c[y].Id==T[P].Id){if("Update"==c[y].CRUD_Operation)switch("K",1==s?getFailBehaviour(1,T[P].fl,e):T[P].fbe){case"K":(b=c[y]).Current_Connection_Session=null,l.push(b);break;case"R":break;default:I=priFromRespRec(T[P],t),R.push(I),_.push(c[y]._soupEntryId),h.push(T[P])}else"UpdateUpdate"==c[y].CRUD_Operation&&((b=c[y]).Current_Connection_Session=null,b.CRUD_Operation="Update",l.push(b));g=!0;break}if(!g)for(P in d)if(c[y].Id==d[P].Id){if(d[P].crud=c[y].CRUD_Operation,"Update"==c[y].CRUD_Operation)switch(d[P].fbe){case"K":(b=c[y]).Current_Connection_Session=null,l.push(b);break;case"R":break;default:I=priFromRespRec(d[P],t),R.push(I),_.push(c[y]._soupEntryId),h.push(d[P])}else"UpdateUpdate"==c[y].CRUD_Operation&&((b=c[y]).Current_Connection_Session=null,b.CRUD_Operation="Update",l.push(b));g=!0;break}}}var A;smartStoreUtils.getProxyFieldName(r).then(function(e){return A=e,m2pRespUpRecs(r,"Id",p)}).then(function(e){return m2pRespUpRecs(r,A,S)}).then(function(e){return m2pRespUpRecs("SnapShot_"+r,"Id",f)}).then(function(e){return m2pRespUpRecs("SnapShot_"+r,A,m)}).then(function(e){return m2pRespDelRecs(r,R)}).then(function(e){return m2pRespDelRecs("SnapShot_"+r,h)}).then(function(e){return m2pRespUpRTSRecs(l)}).then(function(e){return m2pRespDelRTSRecs(_)}).then(function(t){return checkForMigrateToInfo(e)}).then(function(){var t={status:0};t.csId=e.csId,n(t)}).catch(function(e){logger.errorAndDispatch("m2pResp error for "+r,e),o(e)})},o)}).catch(function(e){logger.errorAndDispatch("Err reading table",r),o(e)})}function priFromRespRec(e,t){var n={};return"Insert"==e.crud||"InsertUpdate"==e.crud?n.Id=e.pd:n.Id=e.Id,_.findWhere(t,n)}function getFailBehaviour(e,t,n){switch(e){case 0:switch(t){case"DF":return n.ifbe;case"CV":return n.icvbe;case"FV":return n.ifvbe}break;case 1:switch(t){case"DF":return n.ufbe;case"SV":return n.usvbe;case"CV":return n.ucvbe;case"FV":return n.ufvbe;case"SD":return n.sdfbe;case"HD":return n.hdfbe}}}function addNonRespondedIds(e,t,n,o){return new Promise(function(s,r){e=JSON.parse(e);var a=n.concat(o),c=n;if(e.records&&e.records.length>t.length+a.length){var i=[];smartStoreUtils.getProxyFieldName(e.MobileTable).then(function(o){e.records.forEach(function(e){if("I"==e.RecordCRUD){var n=e.fields.find(function(e){return e.name==o}).value;_.findWhere(t,{pd:n})||_.findWhere(a,{pd:n})||i.push({pd:n,fbe:"K"})}}),i.length>0&&(c=n.concat(i)),s(c)})}else s(c)})}function querySoupRecsPromise(e){return new Promise(function(t,n){smartStoreUtils.querySoupRecords(e,function(e){t(e)},function(e){n(e)})})}function m2pRespUpRecs(e,t,n){return new Promise(function(o,s){n.length>0?(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntriesWithExternalId(e,n,t,function(e){o(e)},function(e){s(e)}):o("OK")})}function m2pRespDelRTSRecs(e){return new Promise(function(t,n){e.length>0?(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).removeFromSoup("recsToSync",e,function(e){t(e)},function(e){n(e)}):t("OK")})}function m2pRespUpRTSRecs(e){return new Promise(function(t,n){e.length>0?(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntries("recsToSync",e,function(e){t(e)},function(e){n(e)}):t("OK")})}function m2pRespDelRecs(e,t){return new Promise(function(n,o){if(t.length>0)if(-1==e.indexOf("SnapShot"))smartStoreUtils.deleteRecordsFromSoup(t,e,function(e){n(e)},function(e){o(e)});else{var s=t.filter(function(e){return e&&"Insert"==e.crud&&(e.Id=e.pd),null!==e&&void 0!==e});smartStoreUtils.deleteRecordsForExternalId(e,s,"Id",function(e){n(e)},function(e){logger.errorAndDispatch(e),o(e)})}else n("OK")})}function clearRTSRecs(e,t,n){smartStoreUtils.queryMobileTable("recsToSync","Current_Connection_Session",e,function(e){if(0!==e.length){for(var o=0;o<e.length;o++)e[o].Current_Connection_Session=null,"InsertUpdate"==e[o].CRUD_Operation?e[o].CRUD_Operation="Insert":"UpdateUpdate"==e[o].CRUD_Operation&&(e[o].CRUD_Operation="Update");(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntries("recsToSync",e,t,n)}else t()},n)}var CLEAN_CS_OK=100600;function cleanConnectionSessionVFEvent(e,t,n,o){var s={bogus:!0};"exception"===e.type?s.status=HEARTBEAT_EXCEPTION:s.status=HEARTBEAT_FAILURE,cleanConnectionSessionHeartBeat(s,t,n,o)}function cleanConnectionSessionHeartBeat(e,t,n,o){var s={},r=null;(e.status==HEARTBEAT_NO_CONNECTION?"Sync - Refresh"==t.connSessionRec.mobilecaddy1__Session_Type__c?r="P2M RE Heartbeat No Connection":"Status Check"==t.connSessionRec.mobilecaddy1__Session_Type__c&&(r="M2P SC Heartbeat No Connection"):e.status==HEARTBEAT_EXCEPTION?"Sync - Refresh"==t.connSessionRec.mobilecaddy1__Session_Type__c?r=e.bogus?"P2M RE Exception/Timeout":"P2M RE Heartbeat Exception/Timeout":"Status Check"==t.connSessionRec.mobilecaddy1__Session_Type__c&&(r=e.bogus?"M2P SC Exception/Timeout":"M2P SC Heartbeat Exception/Timeout"):e.status==HEARTBEAT_FAILURE&&("Sync - Refresh"==t.connSessionRec.mobilecaddy1__Session_Type__c?r=e.bogus?"P2M RE Failure":"P2M RE Hearbeat Failure":"Status Check"==t.connSessionRec.mobilecaddy1__Session_Type__c&&(r=e.bogus?"M2P SC Failure":"M2P SC Heartbeat Failure")),null!==r)?(t.connSessionRec.mobilecaddy1__Mobile_Process_Status__c=r,t.connSessionRec.SystemModstamp=(new Date).getTime(),t.connSessionRec.mobilecaddy1__Status__c="Closed",(window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore")).upsertSoupEntries("Connection_Session__mc",[t.connSessionRec],function(){s.status=CLEAN_CS_OK,s.mc_add_status=e.status,n(s)},o)):(logger.error("Unknown heartBeatObject.status. ",e.status),o())}function maybeSyncConnSess(e,t,n){var o={};smartStoreUtils.querySoupRecsPromise("recsToSync").then(function(s){var r=_.filter(s,function(e){return void 0!==e.currentConnectionSession});r.length>1||"M2P Conn_Sess Records Processed"!=e.mobilecaddy1__Mobile_Process_Status__c?syncMobileTable("Connection_Session__mc").then(function(e){o.status=0,t(o)}).catch(function(e){logger.warn("syncMobileTable ERROR -> ",e),n(e)}):(o.status=0,t(o))}).catch(function(e){logger.error("querySoupRecsPromise ERROR -> ",e),n(e)})}function postProcessConnectionSession(e){return new Promise(function(t,n){var o=function(e){logger.error("postProcessConnectionSession error",e),n(e)},s=Array.isArray(e)?e:[e],r={},a=window.smartstore?window.smartstore:cordova.require("com.salesforce.plugin.smartstore");a.upsertSoupEntries("Connection_Session__mc",s,function(n){var c=Array.isArray(e);c=s.map(function(e){return{Id:e.Id,SystemModstamp:e.SystemModstamp-1,mobilecaddy1__Session_Type__c:null,mobilecaddy1__Mobile_Process_Status__c:null,mobilecaddy1__Session_Created_Location_Error__c:null,mobilecaddy1__MC_Proxy_ID__c:null}}),a.upsertSoupEntries("SnapShot_Connection_Session__mc",c,function(e){var n=e.map(function(e){return{Mobile_Table_Name:"Connection_Session__mc",CRUD_Operation:"Update",SOUP_Record_Id:e._soupEntryId,Id:e.Id,LastModifiedDateTime:e.SystemModstamp}});a.upsertSoupEntries("recsToSync",n,function(){r.status=0,t(r)},o)},o)},o)})}function handleUpdatedCS(e){return new Promise(function(t,n){e&&e.us&&0!==e.us.length?smartStoreUtils.deleteRecordsForExternalId("Connection_Session__mc",e.us,"Id").then(function(t){return smartStoreUtils.deleteRecordsForExternalId("SnapShot_Connection_Session__mc",e.us,"Id")}).then(function(t){return smartStoreUtils.deleteRecordsForExternalId("recsToSync",e.us,"Id")}).then(function(e){t()}).catch(function(e){logger.error("handleUpdatedCS",e),t()}):t(),e&&e.uf&&0!==e.uf.length&&logger.error("handleUpdatedCS -> we have uf",e.uf)})}function getSyncRecFailures(e){return e?localStorage.getItem(MC_FAILURE_KEY_PREFIX+e)?JSON.parse(localStorage.getItem(MC_FAILURE_KEY_PREFIX+e)):{}:getAllSyncRecFailures()}function getAllSyncRecFailures(){var e=[];return getSyncFailureTableKeys().forEach(function(t){var n=getSyncRecFailures(t.replace(MC_FAILURE_KEY_PREFIX,""));_.isEmpty(n)||e.push({table:t.replace(MC_FAILURE_KEY_PREFIX,""),failures:n})}),e}function getSyncFailureTableKeys(){for(var e=[],t=0,n=localStorage.length;t<n;++t)localStorage.key(t).startsWith(MC_FAILURE_KEY_PREFIX)&&e.push(localStorage.key(t));return e}function storeSyncFailures(e,t,n,o){var s={};if(localStorage.getItem("mcM2pMoreToSync")){if(localStorage.getItem(MC_FAILURE_KEY_PREFIX+e)){localStorage.getItem(MC_FAILURE_KEY_PREFIX+e);s=JSON.parse(localStorage.getItem(MC_FAILURE_KEY_PREFIX+e)),n.forEach(function(e){delete s[e.pd]}),o.forEach(function(e){delete s[e.Id]})}}else localStorage.removeItem(MC_FAILURE_KEY_PREFIX+e),s={};if(t){var r={};t.forEach(function(e){r[e.Id]=e,s[e.Id]=e}),localStorage.setItem("tmpFailedRecordsAccum",JSON.stringify(r))}Object.keys(s).length>0?localStorage.setItem(MC_FAILURE_KEY_PREFIX+e,JSON.stringify(s)):localStorage.removeItem(MC_FAILURE_KEY_PREFIX+e)}function checkForMigrateToInfo(e){return new Promise(function(t,n){null!==e.migrateTo&&void 0!==e.migrateTo?appDataUtils.updateNewValueInAppSoup("dynVersionNumber",e.migrateTo).then(function(){t()}).catch(function(e){logger.error(e),n(e)}):t()})}function _handleRefreshResponse(e){return new Promise(function(t,n){handleRefreshResponse(e).then(function(e){t(e)}).catch(function(e){logger.error(e),n(e)})})}exports.CLEAN_CS_OK=CLEAN_CS_OK;