Snippets Collections
const tx = db.transaction("books", "readonly");
const store = tx.objectStore("books");
const index = store.index("by_title");

const request = index.get("Bedrock Nights");
request.onsuccess = function() {
  const matching = request.result;
  if (matching !== undefined) {
    // A match was found.
    report(matching.isbn, matching.title, matching.author);
  } else {
    // No match was found.
    report(null);
  }
};
const tx = db.transaction("books", "readwrite");
const store = tx.objectStore("books");

store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});

tx.oncomplete = function() {
  // All requests have succeeded and the transaction has committed.
};
const request = indexedDB.open("library");
let db;

request.onupgradeneeded = function() {
  // The database did not previously exist, so create object stores and indexes.
  const db = request.result;
  const store = db.createObjectStore("books", {keyPath: "isbn"});
  const titleIndex = store.createIndex("by_title", "title", {unique: true});
  const authorIndex = store.createIndex("by_author", "author");

  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});
};

request.onsuccess = function() {
  db = request.result;
};
Partner with Fourchain Technologies, a top DeFi Development Company, to launch your own decentralized platform. We specialize in DEX development, DeFi lending & borrowing, staking, yield farming, liquidity pools, and crypto wallet solutions. Our team ensures enterprise-grade security, smart contract precision, and customized features to help your business grow in the DeFi ecosystem. Launch your DeFi project today with experts you can trust.
SELECT DISTINCT ON (tech_opn_no)
    tech_opn_no,
    datapoint_spindle_override,
    COUNT(*) AS count
FROM public.machine_dataset_copy
WHERE po_sr_no = '72034808_002'
GROUP BY tech_opn_no, datapoint_spindle_override
ORDER BY tech_opn_no, COUNT(*) DESC;
void automation.Send_Contract_Via_Zoho_Sign(String deal_id)
{
//////////Get the zoho crm data///
//////////
deals_Data = zoho.crm.getRecordById("Deals",deal_id);
landlords_details = deals_Data.get("Landlords");
Floor = deals_Data.get("Floor");
Passport_Number = deals_Data.get("Passport_Number");
Unit_Number = deals_Data.get("Unit_Number");
// ===  Pick Template Dynamically Based on Signer Count ===
template_id = null;
landlord_count = landlords_details.size();
if(landlord_count == 1)
{
	template_id = 489483000000043453;
}
else if(landlord_count == 2)
{
	template_id = 489483000000043243;
}
else if(landlord_count == 3)
{
	template_id = 489483000000043483;
}
else if(landlord_count == 4)
{
	template_id = 489483000000043521;
}
else
{
	info "Unsupported number of landlords: " + landlord_count;
}
// === Get Template Details from Zoho Sign ===
//info template_id;
templateResp = zoho.sign.getTemplateById(template_id,"zoho_sign");
//info templateResp;
signerActionList = List();
if(templateResp.containKey("templates"))
{
	templateData = templateResp.get("templates");
	signerActionList = templateData.get("actions");
}
actionsList = List();
index = 0;
// ===  Map Landlords to Signer Actions ===
for each  data in landlords_details
{
	Email = data.get("Email_1");
	Buyer_Name = data.get("Buyer_Name");
	if(Email != null && Email != "" && index < signerActionList.size())
	{
		templateAction = signerActionList.get(index);
		action_id = templateAction.get("action_id");
		signer = Map();
		signer.put("action_id",action_id);
		signer.put("recipient_name",Buyer_Name);
		signer.put("recipient_email",Email);
		signer.put("action_type","SIGN");
		actionsList.add(signer);
		index = index + 1;
	}
}
// === Add Manager Signer If Present in Template ===
for each  actionMap in signerActionList
{
	if(actionMap.get("role") == "Manager")
	{
		managerSigner = Map();
		managerSigner.put("action_id",actionMap.get("action_id"));
		managerSigner.put("recipient_name","Awais");
		managerSigner.put("recipient_email","m.awais@leosuk.com");
		managerSigner.put("action_type","SIGN");
		actionsList.add(managerSigner);
		break;
	}
}
////////////////Add the fields data for zoho sign
//////////////////
field_text_data = Map();
field_text_data.put("Unit Number",Unit_Number);
field_text_data.put("Passport Number",Passport_Number);
field_text_data.put("Owner",Buyer_Name);
field_text_data.put("Floor",Floor);
field_data = Map();
field_data.put("field_text_data",field_text_data);
////////////
///////////////////////////
//////////////////
// === Prepare Payload and Send ===
templateActions = Map();
templateActions.put("actions",actionsList);
templateActions.put("field_data",field_data);
submitMap = Map();
submitMap.put("templates",templateActions);
parameters = Map();
parameters.put("is_quicksend","true");
parameters.put("data",submitMap);
//info "Final Payload: " + parameters;
response = zoho.sign.createUsingTemplate(template_id,parameters,"zoho_sign");
info response;
//===  Update CRM Deal Record with Zoho Sign Info ===
reqId = response.get("requests").get("request_id");
docId = response.get("requests").get("document_ids").get(0);
Document_id = response.get("requests").get("document_fields").get(0).get("document_id");
mpdocx = Map();
mpdocx.put("request_id",reqId);
mpdocx.put("Zoho_Sign_Document_ID",Document_id.toString());
mpdocx.put("Stage","Contract Sent");
update = zoho.crm.updateRecord("Deals",deal_id,mpdocx);
info update;
}
dataMap = Map();
dataMap.put("Signer_Name",recipient_name);
dataMap.put("Status",action_status);
blueprintMap = Map();
blueprintMap.put("transition_id","6893650000000704005");
// contract signed
blueprintMap.put("data",dataMap);
blueprintList = List();
blueprintList.add(blueprintMap);
param = Map();
param.put("blueprint",blueprintList);
response = invokeurl
[
	url :"https://www.zohoapis.com/crm/v8/Deals/" + deal_id + "/actions/blueprint"
	type :PUT
	parameters:param.toString()
	connection:"zoho_crm"
];
info response;
void automation.Test_usman()
{
	get_deals_details = zoho.crm.getRecordById("Deals", 6893650000000704360);
	info "get_deals_details ==>"+get_deals_details;
	
	recordId = "6893650000000787001"; // Replace with your actual Invoice record ID

	response = invokeurl
	[
	url : "https://www.zohoapis.com/crm/v8/Deals/" + recordId + "/actions/blueprint"
	type : GET
	connection : "zoho_crm"
	];

	info response.toString(); // Optional: Logs the full response for debugging
	
	transitions = response.get("blueprint").get("transitions");
	info "transitions ==>"+transitions;
	transitionId = "";
	for each transition in transitions
	{
			transitionId = transition.get("id");
			info "transitionId ==>"+transitionId;
			transitionname= transition.get("name");
			info "transitionname ==>"+transitionname;
	}
	dataMap = Map();
	dataMap.put("Notes","Updated via blueprint");
	blueprintMap = Map();
	blueprintMap.put("transition_id","6893650000000727106");
	blueprintMap.put("data",dataMap);
	blueprintList = List();
	blueprintList.add(blueprintMap);
	param = Map();
	param.put("blueprint",blueprintList);
	response = invokeurl
	[
	url :"https://www.zohoapis.com/crm/v8/Deals/" + recordId + "/actions/blueprint"
	type :PUT
	parameters:param.toString()
	connection:"zoho_crm"
	];
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: What's on in Melbourne this week! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday and hope you all had a Fabulous weekend! Please see below for what's on this week. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: *This week we are offering:* \n\n :caramel-slice: *Sweet Treats*: Cookies \n\n :coffee: *Weekly Café Special*: English Toffee Coffee"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 6th August :calendar-date-6:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n:lunch: :flag-it: Join us for an Italian lunch From *12pm* in the L3 kitchen + Wominjeka breakout space! Menu in the:thread: "
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 7th August :calendar-date-7:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":breakfast: *Breakfast*: Join us for our Breakfast Buffet from *8:30am - 10:30am* in the Wominjeka Breakout Space. Menu in the :thread: \n\n:cheese:*Social Happy Hour*: Join us for nibbles and drinks from *4.00pm - 5.30pm* in the Wominjeka Breakout Space.\n\n *What Else? :green_heart:*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": " Feedback on our Boost Offerings? We want to hear more. Let us know what you love by filling out our form <https://docs.google.com/forms/d/e/1FAIpQLScGOSeS5zUI8WXEl0K4WGoQUkmpIHzAjLlEKWBob4sMPhDXmA/viewform|here.>  \n\n Stay tuned to this channel, and make sure you're subscribed to the <https://calendar.google.com/calendar/u/0?cid=Y19xczkyMjk5ZGlsODJzMjA4aGt1b3RnM2t1MEBncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Melbourne Social Calendar*> :party-wx:"
			}
		}
	]
}
const handleDownloadReport = async () => {
        setIsGeneratingReport(true); setForecastError('');
        try {
            const res = await axios.get('http://localhost:5000/api/generate-report-data', { withCredentials: true });
            setReportData({ ...res.data, historicalLabels: filteredData.map(d => d.timestamp) });

            setTimeout(async () => {
                const pdf = new jsPDF('p', 'mm', 'a4');
                const margin = 15;
                const pdfWidth = pdf.internal.pageSize.getWidth();
                const textWidth = pdfWidth - (margin * 2);
                let currentY = margin;

                pdf.setFontSize(22).setFont('helvetica', 'bold');
                pdf.text('SuDS Performance & Forecast Report', pdfWidth / 2, currentY, { align: 'center' });
                currentY += 10;
                pdf.setFontSize(14).setFont('helvetica', 'normal');
                pdf.text(`Generated on: ${new Date().toLocaleDateString('en-GB')}`, pdfWidth / 2, currentY, { align: 'center' });
                currentY += 15;
                const firstDate = new Date(filteredData[0].timestamp).toLocaleDateString('en-GB');
                const lastDate = new Date(filteredData[filteredData.length - 1].timestamp).toLocaleDateString('en-GB');
                const introText = `This report analyzes the performance of a Sustainable Drainage System (SuDS) using historical data from ${firstDate} to ${lastDate}, and provides a 24-hour forecast. The system is evaluated on three key performance metrics:`;
                const splitIntro = pdf.splitTextToSize(introText, textWidth);
                pdf.setFontSize(12).setFont('helvetica', 'normal');
                pdf.text(splitIntro, margin, currentY);
                currentY += (splitIntro.length * 5) + 5;
                const bulletPoints = ["Rainfall (mm): Measures the amount of rain entering the system.","Water Level (cm): Measures the height of water collected within the SuDS infrastructure.","Flow Rate (lps): Measures the volume of water the system is discharging."];
                pdf.setFontSize(11).setFont('helvetica', 'normal');
                bulletPoints.forEach(point => { pdf.text(`\u2022 ${point}`, margin + 5, currentY); currentY += 7; });
                currentY += 5;
                const conclusionText = `To provide a robust outlook, two different forecasting methods were used: a traditional statistical model and a modern machine learning model. \nThis dual-model approach allows for a comprehensive evaluation of potential future system behavior.`;
                const splitConclusion = pdf.splitTextToSize(conclusionText, textWidth);
                pdf.setFontSize(12).setFont('helvetica', 'normal');
                pdf.text(splitConclusion, margin, currentY);
                currentY += (splitConclusion.length * 5) + 10;
                
                const chart1_canvas = reportRefs.chart1Ref.current.canvas;
                const chart1_img = chart1_canvas.toDataURL('image/png', 2.5);
                const chart1_img_height = (chart1_canvas.height * (pdfWidth - margin*2)) / chart1_canvas.width;
                pdf.addImage(chart1_img, 'PNG', margin, currentY, pdfWidth - (margin*2), chart1_img_height);
                
                pdf.addPage();
                currentY = margin;
                const chart2_canvas = reportRefs.chart2Ref.current.canvas;
                const chart2_img = chart2_canvas.toDataURL('image/png', 2.5);
                const chart2_img_height = (chart2_canvas.height * (pdfWidth - margin*2)) / chart2_canvas.width;
                pdf.addImage(chart2_img, 'PNG', margin, currentY, pdfWidth - (margin*2), chart2_img_height);
                currentY += chart2_img_height + 10;

                const chart3_canvas = reportRefs.chart3Ref.current.canvas;
                const chart3_img = chart3_canvas.toDataURL('image/png', 2.5);
                const chart3_img_height = (chart3_canvas.height * (pdfWidth - margin*2)) / chart3_canvas.width;
                pdf.addImage(chart3_img, 'PNG', margin, currentY, pdfWidth - (margin*2), chart3_img_height);
                
                pdf.save("SuDS_Forecast_Report.pdf");
                setReportData(null);
                setIsGeneratingReport(false);
            }, 500);
        } catch (err) { setForecastError("Failed to generate report data."); setIsGeneratingReport(false); }
    };
-- RISK115
DROP TABLE team_kingkong.tpap_risk115_breaches;

-- CREATE TABLE team_kingkong.tpap_risk115_breaches AS
INSERT INTO team_kingkong.tpap_risk115_breaches
SELECT DISTINCT B.*, C.category, C.txn_type, C.payer_os, C.initiationMode, C.amount_limit
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
, 'upi_oc141_mcc5816_onlinegaming_v3' as rule_name
, CASE
  WHEN lower(payer_os) LIKE 'android%' AND txn_type = 'COLLECT'
    THEN 'Android Collect Txn'

  WHEN lower(payer_os) LIKE 'ios%' AND txn_amount > amount_limit AND txn_type = 'COLLECT'
    THEN 'iOS High Amount Collect Txn'

  WHEN initiationMode = '00' AND txn_type NOT IN ('PAY', 'DEBIT', 'CR')
    THEN 'Invalid Txn Type with Initiation Mode 00'

  WHEN initiationMode NOT IN ('00', '10', '04', '05')
    THEN 'Unexpected Initiation Mode'

  ELSE NULL END AS breach_reason FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN mcc END) AS payeeMccCode,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31' 
    GROUP BY 1)B
inner join
    (select DISTINCT txn_id, category, "type" AS txn_type
    , json_extract_scalar(extended_info, '$.payerOsApp') AS payer_os
    , json_extract_scalar(extended_info, '$.initiationMode') as initiationMode
    , 2000 as amount_limit
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    -- , JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode') AS initiationMode
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    -- AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) LIKE '%@paytm%'
    -- or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) like '%@pt%')
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') IS NOT NULL
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') IS NOT NULL
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') <> ''
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') <> ''
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON')D
ON B.txn_id = D.txnid
WHERE upi_subtype = 'UPI_TRANSACTION' AND payer_vpa IS NOT NULL
AND (((payeeMccCode = '5816') AND (lower(payer_os) LIKE 'android%') AND (txn_type = 'COLLECT'))
OR ((payeeMccCode = '5816') AND (lower(payer_os) LIKE 'iOS%') AND (txn_amount > amount_limit) AND (txn_type = 'COLLECT'))
OR ((payeeMccCode= '5816') AND (initiationMode = '00') AND (txn_type NOT IN ('PAY', 'DEBIT', 'CR')))
OR ((payeeMccCode = '5816') AND ((initiationMode NOT IN ('00', '10', '04', '05')))));
-- RISK201
DROP TABLE team_kingkong.tpap_risk201_breaches;

-- CREATE TABLE team_kingkong.tpap_risk201_breaches AS
INSERT INTO team_kingkong.tpap_risk201_breaches
with tpap_base as
(SELECT DISTINCT B.*, C.category, C.txn_type
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(CASE WHEN participant_type = 'PAYER' THEN masked_account_number END) AS sender_masked_account_number,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN mcc END) AS payee_mcc,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    GROUP BY 1)B
inner join
    (select txn_id, category, "type" AS txn_type
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND "type" <> 'CREDIT'
    AND category = 'VPA2MERCHANT') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE ((payer_vpa LIKE '%@paytm%') OR (payer_vpa LIKE '%@pt%'))
AND payee_vpa LIKE '%@%' AND payee_mcc = '6010')
 
SELECT *, 'upi_cash_mcc6010_amount_payer_account_oc83' as rule_name, '24 hr amt threshold breached' as breach_reason FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.txn_time,
      t1.txn_date,
      SUM(t2.txn_amount) AS amt_24hr,
      1000 AS threshold_24hr
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.sender_masked_account_number = t2.sender_masked_account_number
      AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '86400' SECOND) AND t1.txn_time -- 24 hr
      AND t1.txn_id <> t2.txn_id AND t1.txn_date BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, t1.txn_date)
WHERE (txn_amount + amt_24hr) > threshold_24hr
;
-- -- RISK268
DROP TABLE team_kingkong.tpap_risk268_breaches;

-- CREATE TABLE team_kingkong.tpap_risk268_breaches AS
INSERT INTO team_kingkong.tpap_risk268_breaches
with tpap_base as
(SELECT DISTINCT B.*, C.category, C.txn_type
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
, D.requestType
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(CASE WHEN participant_type = 'PAYER' THEN masked_account_number END) AS sender_masked_account_number,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    GROUP BY 1)B
inner join
    (select txn_id, category, "type" AS txn_type
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND "type" <> 'CREDIT'
    AND category in ('VPA2ACCOUNT', 'VPA2MERCHANT', 'VPA2VPA')) C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    , json_extract_scalar(request, '$.requestPayload.requestType') AS requestType
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND json_extract_scalar(request, '$.requestPayload.requestType') = 'VPA'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_LITE_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE payee_vpa LIKE '%@%')
 
SELECT *, 'upi_lite_txn_amount_limit_24hr' AS rule_name, '24 hr amt threshold breached' as breach_reason FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.txn_time,
      t1.txn_date,
      SUM(t2.txn_amount) AS amt_24hr,
      10000 AS threshold_24hr
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.payer_vpa = t2.payer_vpa
    -- t1.sender_masked_account_number = t2.sender_masked_account_number
      AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '86400' SECOND) AND t1.txn_time -- 24 hr
      AND t1.txn_id <> t2.txn_id AND t1.txn_date BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, t1.txn_date)
WHERE (txn_amount + amt_24hr) > threshold_24hr;
-- RISK002
DROP TABLE team_kingkong.tpap_risk002_breaches;

-- CREATE TABLE team_kingkong.tpap_risk002_breaches AS
INSERT INTO team_kingkong.tpap_risk002_breaches
with tpap_base as
(SELECT DISTINCT B.*, C.category, C.txn_type
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
, D.payer_ifsc, D.payer_account_num
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    -- MAX(CASE WHEN participant_type = 'PAYER' THEN masked_account_number END) AS sender_masked_account_number,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-06-01' - INTERVAL '1' DAY) AND DATE'2025-06-30'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-06-01' - INTERVAL '1' DAY) AND DATE'2025-06-30'
    GROUP BY 1)B
inner join
    (select txn_id, category, "type" AS txn_type
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-06-01' - INTERVAL '1' DAY) AND DATE'2025-06-30'
    and DATE(created_on) BETWEEN DATE(DATE'2025-06-01' - INTERVAL '1' DAY) AND DATE'2025-06-30'
    and upper(status) = 'SUCCESS' AND "type" <> 'CREDIT') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    , json_extract_scalar(request, '$.requestPayload.payerIfsc') AS payer_ifsc
    , json_extract_scalar(request, '$.requestPayload.payerAccountNum') AS payer_account_num
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-06-01' - INTERVAL '1' DAY) AND DATE'2025-06-30'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') = 'PERSON'
    AND  regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE (payer_vpa LIKE '%@paytm%') OR (payer_vpa LIKE '%@pt%')
AND payee_vpa LIKE '%@%')
 
SELECT * FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.payer_account_num,
      t1.payer_ifsc,
      t1.txn_time,
      t1.txn_date,
      SUM(t2.txn_amount) AS amt_24hr,
      100000 AS threshold_24hr
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.payer_account_num = t2.payer_account_num AND t1.payer_ifsc = t2.payer_ifsc
    AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '86400' SECOND) AND t1.txn_time -- 24 hr
    AND t1.txn_id <> t2.txn_id AND t1.txn_date BETWEEN DATE'2025-06-01' AND DATE'2025-06-30'
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.payer_account_num, t1.payer_ifsc, t1.txn_time, t1.txn_date
    )
WHERE (txn_amount + amt_24hr) > threshold_24hr;
-- RISK303
-- if( (txnAmount > 100000 && ((payeeType == ""ENTITY"") || (payeeMccCode == ""7407"")) && txnType == ""PAY"")){""PASS""}
-- if((in_oc_185_mcc_list == false) && (in_oc_86_mcc_list == false) && !(initiationMode == ""12"" || ((purposeCode == ""15"" && payeeMccCode !=""5969"")))){""BLOCK""}

DROP TABLE team_kingkong.tpap_risk303_breaches;

-- CREATE TABLE team_kingkong.tpap_risk303_breaches AS
INSERT INTO team_kingkong.tpap_risk303_breaches
SELECT DISTINCT B.*, C.category, C.txn_type, C.initiationMode, D.payeeType
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
, D.purposeCode
, 'oc_120_p2m_p2pm_txn_limit' as rule_name
, 'NA' as breach_reason
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN mcc END) AS payeeMccCode,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31' 
    GROUP BY 1)B
inner join
    (select DISTINCT txn_id, category, "type" AS txn_type
    , json_extract_scalar(extended_info, '$.initiationMode') as initiationMode
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND category IN ('VPA2MERCHANT', 'VPA2VPA')
    AND "type" = 'PAY') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    -- , JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode') AS initiationMode
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') AS payeeType
    , json_extract_scalar(request, '$.requestPayload.purposeCode') AS purposeCode
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    -- AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) LIKE '%@paytm%'
    -- or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) like '%@pt%')
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') IS NOT NULL
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') IS NOT NULL
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') <> ''
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') <> ''
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE payer_vpa IS NOT NULL
AND txn_amount > 100000 
AND (payeeType = 'ENTITY' OR payeeMccCode = '7407')
AND payeeMccCode NOT IN ('8299', '8042', '8220', '8099', '742', '8049', '8021', '8244', '8211', '9311', '8031', '8041', '8071', '8062', '8249', '8011', '8241', '8050')
AND payeeMccCode NOT IN ('6012', '6529', '6300', '5960', '6211', '7322', '5413')
AND NOT (C.initiationMode = '12' OR (purposeCode = '15' AND payeeMccCode != '5969'))
;
Fast trade execution, real-time market data, and ironclad security, that’s the core of our Centralized Crypto Exchange Script at Beleaf Technologies. Designed for high-performance trading environments, our platform features a lightning-fast matching engine, an intuitive user interface, and advanced security layers that safeguard every transaction. Whether you're launching a global exchange or a region-specific platform, our script is fully customizable to match your vision. Designed to handle high-volume traffic with ease, it supports multi-currency wallets, seamless KYC/AML integration, and a responsive design that adapts to various devices. At Beleaf Technologies, we don’t just deliver software; we provide a strategic foundation for crypto entrepreneurs to scale confidently. From initial deployment to post-launch support, our team is committed to providing you with technical excellence and industry insight. If you're ready to lead in the crypto revolution, partner with us and launch your exchange with the tools, trust, and technology it takes to develop in today’s dynamic market.
Get a free Demo and Consultation >>> https://beleaftechnologies.com/centralized-cryptocurrency-exchange-development


WhatsApp: +91 8056786622


Mail to: business@beleaftechnologies.com

  private function processNotificationData(&$NotificationData)
    {
        $machineIds = collect($NotificationData)->pluck('machine_id')->unique()->filter()->toArray();
        $operatorIds = collect($NotificationData)->pluck('operator_id')->unique()->filter()->toArray();
        $techsheetHeaderIds = collect($NotificationData)->pluck('techsheet_header_id')->unique()->filter()->toArray();
        $poSrTechOpns = collect($NotificationData)->map(function ($data) {
            return [
                'machine_id' => $data->machine_id,
                'po_sr_no' => $data->po_sr_no,
                'tech_opn_no' => $data->tech_opn_no,
            ];
        });

        // Bulk load data
        $machines = MachineMaster::whereIn('id', $machineIds)->get()->keyBy('id');
        $users = UserMaster::whereIn('id', $operatorIds)->get()->keyBy('id');

        // Bulk fetch queue data
        $queueData = DB::table('tech_operation_queue_dataset')
            ->whereIn('machine_id', $machineIds)
            ->whereIn('po_sr_no', $NotificationData->pluck('po_sr_no')->unique())
            ->get()
            ->groupBy(fn($item) => $item->machine_id . '_' . $item->po_sr_no . '_' . $item->tech_opn_no);

        // Bulk fetch techsheet_data
        $techData = DB::table('techsheet_data')
            ->whereIn('fk_techsheet_header_id', $techsheetHeaderIds)
            ->get()
            ->groupBy(fn($item) => $item->fk_techsheet_header_id . '_' . $item->opn_no);

        // Update each row
        foreach ($NotificationData as $data) {
            $data->sah = $data->estimated_mrr + $data->estimated_nva;

            $machine = $machines[$data->machine_id] ?? null;
            $data->machine_shop_name = $machine->machine_shop_name ?? '';
            $data->fk_area_master_id = $machine->fk_area_master_id ?? null;

            $user = $users[$data->operator_id] ?? null;
            $data->reported_by = $user->profile_name ?? '';

            $queueKey = $data->machine_id . '_' . $data->po_sr_no . '_' . $data->tech_opn_no;
            $queue = $queueData[$queueKey][0] ?? null;
            $data->actual_time_taken = $data->sah + ($queue->duration ?? 0);
            $data->shift_date = $queue->shift_date ?? '';

            // Handling multiple opn_no's
            $opnArray = collect(explode(',', $data->tech_opn_no))
                ->map(fn($val) => (int) trim($val))
                ->filter()
                ->unique()
                ->toArray();

            foreach ($opnArray as $opn) {
                $key = $data->techsheet_header_id . '_' . $opn;
                $tech = $techData[$key][0] ?? null;

                if ($tech) {
                    $data->m_c_no = $tech->m_c_no ?? '';
                    $data->actual_m_c_no = $tech->actual_m_c_no ?? '';
                    break;
                }
            }
        }
    }
A white label crypto exchange gives you all the core features, custom branding, user dashboards, liquidity integration, real-time charts, KYC modules, and more. Building everything from scratch, you get a fully functional, ready-to-deploy solution. Simply customize it to match your brand, and you're all set
Launch your Winzo Clone App with an end-to-end technological solution.  Our Winzo Clone Script is designed for gaming entrepreneurs and investors seeking scalable, secure, and revenue-ready platforms. Addus Technologies provides white-label, real-money gaming scripts with multi-game integration and wallet systems. Step strongly into the growing online gaming sector by choosing Addus.
<?php
#--------------------------------------------------------------------------------------#
#Add Custom frontEnd Script to Iridium 9555 – FREE Phone and Isat 2 Product
#--------------------------------------------------------------------------------------#

add_action('woocommerce_shop_loop_item_title', 'my_update', 10, 1);
function my_update(){
    $producPage = basename(rtrim($_SERVER['REQUEST_URI'],'/'));
    if($producPage == "iridium-phones-purchase"){
        ?>
        <script>
            jQuery(document).ready(function($){
                $('.post-246776').find('div[class="price"]').remove();
            })
        </script>
        <?php
    }
}
add_action('woocommerce_before_single_product', 'custom_function_before_single_product');
function custom_function_before_single_product() {
    try{
        $productName = basename(rtrim($_SERVER['REQUEST_URI'],'/'));
        if($productName == 'iridium-9555-free-phone' || $productName == 'isat-2' || $productName == 'iridium-9575-free-phone' || $productName == 'starlink-standard-gen-3' || $productName == 'starlink-mini-terminal'){
            ?>
            <script>
                jQuery(document).ready(function($){
                    const getProductName = "<?php echo $productName ?>"
                    $('.product-details').css('padding','0px');
                    $('.woocommerce-product-rating').remove();
                    $('.bundled_product_checkbox').prop('checked', true);
                    $('#pa_minute-subscription').val('150-min-plan-90-00-month');
                    $('#pa_inmarsat-voice').val('60-voice-min-month-64-99-month');
                    $('#pa_usa-phone-number').val('yes');
                    $('#pa_rollover-minutes').val('yes');
                    $('#pa_rollover-minutes').before('<span style="color:black">Rollover Minutes</span>');
                    $('#pa_usa-phone-number').before('<span style="color:black">USA Phone Number</span>');
                    // $('pa_starlink-13-month-plan').val('local-us-unlimited-data-1tb-priority-290-00'); // bundle_attribute_pa_starlink-13-month-plan_282
                    
                    function appendPriceIfNotAppended(productName, price) {
                        if ($('.item_title:contains("' + productName + '")').closest('h4').find('.price-appended').length === 0) {
                            $('.item_title:contains("' + productName + '")').each(function() {
                                $(this).closest('h4').append('<span class="price-appended" style="color:black">&nbsp;' + price + '</span>');
                            });
                        }
                    }
                    function appendPriceAfterSolarCharger() {
                        appendPriceIfNotAppended("Solar Charger", "$34.99");
                        appendPriceIfNotAppended("Hard Case", "$44.99");
                        var batteryPrice = '$99.00';
                        if(getProductName == "isat-2"){
                            batteryPrice  =  '$55.00';
                        }else if(getProductName == "iridium-9555-free-phone"){
                            batteryPrice  =  '$99.00';
                        }
                        appendPriceIfNotAppended("Extra battery", batteryPrice);
                    }
                    function uncheckIfChecked($checkbox) {
                        if ($checkbox.is(':checked')) {
                            $checkbox.trigger('click');
                        }
                    }
                    if ($('.item_title:contains("Solar Charger")').length === 0) {
                        $(document).ajaxComplete(function(event, xhr, settings) {
                            appendPriceAfterSolarCharger();
                            const $isatCheckbox = $('.item_title:contains(IsatPhone Voice Yearly)').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');
                            const $isatCheckboxMonthly = $('.item_title:contains(IsatPhone Voice Monthly)').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');
                            const $iridiumCheckbox = $('.item_title:contains(Iridium Monthly Minute Plans (Paid Yearly))').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox'); 
                            const $iridiumCheckboxMonthly = $('.item_title:contains(Iridium Monthly Minute Plans)').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox'); 
                            const $starlinkOneMonthCheckbox = $('.item_title:contains(Plans with a one-month minimum term)').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');
                            const $starlinkYearlyCheckbox = $('.item_title:contains(Promo Plan (Paid Yearly))').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');
                            const $starlinkmonthlyCheckbox = $('.item_title:contains(Promo Plan (Six Months))').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');

                            // const $starlinkMTOneMonthCheckbox = $('.item_title:contains(Plans with a one-month minimum term)').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');
                            const $starlinkMTYearlyCheckbox = $('.item_title:contains(Starlink Promo Plan (Paid Yearly))').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');
                            const $starlinkMTmonthlyCheckbox = $('.item_title:contains(Starlink Promo Plan (Six Months))').closest('.bundled_product_optional_checkbox').find('.bundled_product_checkbox');

                            uncheckIfChecked($isatCheckbox);
                            uncheckIfChecked($iridiumCheckbox);
                            uncheckIfChecked($starlinkYearlyCheckbox);
                            uncheckIfChecked($starlinkmonthlyCheckbox);

                            uncheckIfChecked($starlinkMTYearlyCheckbox);
                            uncheckIfChecked($starlinkMTmonthlyCheckbox);
                            let hrefValue;
                            hrefValue = $('a.checkout-btn.single_add_to_cart_button.bundle_add_to_cart_button').attr('href');
                            $('.checkout-btn.single_add_to_cart_button.bundle_add_to_cart_button').removeAttr('href');
                            $(document).on('click', 'a.checkout-btn.single_add_to_cart_button.bundle_add_to_cart_button', function() {
                                checkoutFunction();
                                $(this).off('click');
                            });
                            function checkoutFunction() {
                                $('.checkout-btn.single_add_to_cart_button.bundle_add_to_cart_button').attr('href', hrefValue).trigger('click');
                            }
                            function disableCartButtons(){
                                $('.single_add_to_cart_button.bundle_add_to_cart_button').prop('disabled', true).attr('type', 'button');
                                $('.checkout-btn.single_add_to_cart_button.bundle_add_to_cart_button').addClass('disabled').removeAttr('href').on('click', function(e) {e.preventDefault();});
                            }

                            function enableCartButtons(){
                                $('.single_add_to_cart_button.bundle_add_to_cart_button').prop('disabled', false).attr('type', 'submit');
                                $('.checkout-btn.single_add_to_cart_button.bundle_add_to_cart_button').removeClass('disabled').off('click');
                            }

                            let isatVoiceBox = $isatCheckboxMonthly.parent().parent().find('#pa_inmarsat-voice');
                            let isatMinuteBox = $isatCheckboxMonthly.parent().parent().find('#pa_rollover-minutes');
                            let isatNumberBox = $isatCheckboxMonthly.parent().parent().find('#pa_usa-phone-number');
                            isatVoiceBox.add(isatMinuteBox).add(isatNumberBox).on('change',function(){
                                if(isatVoiceBox.val() == '' || isatMinuteBox.val() == '' || isatNumberBox.val() == ''){
                                    disableCartButtons();
                                }else{
                                    enableCartButtons();
                                }
                            })

                            let starlinkVoiceBox = $starlinkOneMonthCheckbox.parent().parent().find('#pa_starlink-13-month-plan'); 
                            starlinkVoiceBox.on('change',function(){
                                if(starlinkVoiceBox.val() == ''){
                                    disableCartButtons();
                                }else{
                                    enableCartButtons();
                                }
                            })

                            let iridiumVoiceBox = $iridiumCheckboxMonthly.parent().parent().find('#pa_minute-subscription');
                            let iridiumMinuteBox = $iridiumCheckboxMonthly.parent().parent().find('#pa_rollover-minutes');
                            let iridiumNumberBox = $iridiumCheckboxMonthly.parent().parent().find('#pa_usa-phone-number');
                            iridiumVoiceBox.add(iridiumMinuteBox).add(iridiumNumberBox).on('change',function(){
                                if(iridiumVoiceBox.val() == '' || iridiumMinuteBox.val() == '' || iridiumNumberBox.val() == ''){
                                    disableCartButtons();
                                }else{
                                    enableCartButtons();
                                }
                            })
                            
                            $starlinkOneMonthCheckbox.add($starlinkYearlyCheckbox).add($starlinkmonthlyCheckbox).on('click', function() {                                
                                if (!$starlinkOneMonthCheckbox.is(':checked') && !$starlinkYearlyCheckbox.is(':checked') && !$starlinkmonthlyCheckbox.is(':checked')){
                                    disableCartButtons();
                                }else{
                                   let starlinkOneMonthCheckboxVoice = $(this).parent().parent().find('#pa_starlink-13-month-plan');
                                   let starlinkYearlyCheckboxVoice = $(this).parent().parent().find('#pa_starlink-promo-plan');
                                   let starlinkmonthlyCheckboxVoice = $(this).parent().parent().find('#pa_starlink-promo-plan');

                                    starlinkOneMonthCheckboxVoice.val('stationary-unlimited-data-40gb-priority');
                                    starlinkYearlyCheckboxVoice.val('500gb-mobile-priority-us-device-included');
                                    starlinkmonthlyCheckboxVoice.val('1tb-mobile-priority-us-device-included');

                                   starlinkOneMonthCheckboxVoice.add(starlinkYearlyCheckboxVoice).add(starlinkmonthlyCheckboxVoice).on('change',function(){
                                        if(starlinkOneMonthCheckboxVoice.val() == '' || starlinkYearlyCheckboxVoice.val() == '' || starlinkmonthlyCheckboxVoice.val() == ''){
                                            disableCartButtons();
                                        }else{
                                            enableCartButtons();
                                        }
                                    })
                                    enableCartButtons();
                                }
                            });

                            $starlinkOneMonthCheckbox.add($starlinkMTYearlyCheckbox).add($starlinkMTmonthlyCheckbox).on('click', function() {                                
                                if (!$starlinkOneMonthCheckbox.is(':checked') && !$starlinkYearlyCheckbox.is(':checked') && !$starlinkmonthlyCheckbox.is(':checked')){
                                    disableCartButtons();
                                }else{
                                   let starlinkOneMonthCheckboxVoice = $(this).parent().parent().find('#pa_starlink-13-month-plan');
                                   let starlinkYearlyCheckboxVoice = $(this).parent().parent().find('#pa_starlink-promo-plan');
                                   let starlinkmonthlyCheckboxVoice = $(this).parent().parent().find('#pa_starlink-promo-plan');

                                    starlinkOneMonthCheckboxVoice.val('stationary-unlimited-data-40gb-priority');
                                    starlinkYearlyCheckboxVoice.val('500gb-mobile-priority-us');
                                    starlinkmonthlyCheckboxVoice.val('1tb-mobile-priority-us-accessories-included');

                                   starlinkOneMonthCheckboxVoice.add(starlinkYearlyCheckboxVoice).add(starlinkmonthlyCheckboxVoice).on('change',function(){
                                        if(starlinkOneMonthCheckboxVoice.val() == '' || starlinkYearlyCheckboxVoice.val() == '' || starlinkmonthlyCheckboxVoice.val() == ''){
                                            disableCartButtons();
                                        }else{
                                            enableCartButtons();
                                        }
                                    })
                                    enableCartButtons();
                                }
                            });

                            $isatCheckbox.add($isatCheckboxMonthly).on('click', function() {
                                if (!$isatCheckbox.is(':checked') && !$isatCheckboxMonthly.is(':checked')){
                                    disableCartButtons();
                                }else{
                                   let isatVoice = $(this).parent().parent().find('#pa_inmarsat-voice');
                                   let isatMinute = $(this).parent().parent().find('#pa_rollover-minutes');
                                   let isatNumber = $(this).parent().parent().find('#pa_usa-phone-number');

                                   isatVoice.val('60-voice-min-month-64-99-month');
                                   isatMinute.val('yes');
                                   isatNumber.val('yes');
                                   isatVoice.add(isatMinute).add(isatNumber).on('change',function(){
                                        if(isatVoice.val() == '' || isatMinute.val() == '' || isatNumber.val() == ''){
                                            disableCartButtons();
                                        }else{
                                            enableCartButtons();
                                        }
                                    })
                                    enableCartButtons();
                                }
                            });

                            $iridiumCheckbox.add($iridiumCheckboxMonthly).on('click', function() {
                                if (!$iridiumCheckbox.is(':checked') && !$iridiumCheckboxMonthly.is(':checked')){
                                    disableCartButtons();
                                }else{
                                    const iridiumVoice = $(this).parent().parent().find('#pa_minute-subscription');
                                    const iridiumMinute = $(this).parent().parent().find('#pa_rollover-minutes');
                                    const iridiumNumber = $(this).parent().parent().find('#pa_usa-phone-number');

                                    iridiumVoice.val('150-min-plan-90-00-month');
                                    iridiumMinute.val('yes');
                                    iridiumNumber.val('yes');
                                    iridiumVoice.add(iridiumMinute).add(iridiumNumber).on('change',function(){
                                            if(iridiumVoice.val() == '' || iridiumMinute.val() == '' || iridiumNumber.val() == ''){
                                                disableCartButtons();
                                            }else{
                                                enableCartButtons();
                                            }
                                        })
                                        enableCartButtons();
                                }
                            });
                        });
                    }
                })
            </script>
            <?php
        }
    }catch(Exception $e){
        error_log("An error occurred: custom_function_before_single_product>>(CustomProductfrontEndScript.php)" . $e->getMessage());
    }
	
}

#--------------------------------------------------------------------------------------#
# Add check for promo phones
#--------------------------------------------------------------------------------------#
add_filter('woocommerce_add_to_cart_validation', 'validate_optional_bundle_items_selected', 10, 5);

function validate_optional_bundle_items_selected($passed, $product_id, $quantity, $variation_id = 0, $cart_item_data = []) {
	try{
		$product = wc_get_product($product_id);
		$productNameArray = ['Iridium 9555 - Almost Free Phone','Iridium 9575 - Promo Phone','Inmarsat IsatPhone 2 (Promo)','Starlink Standard GEN 3','Starlink Mini Terminal'];
		$required_optional_ids = [243,266,238,265,267,268,282,284,286,283,290,291];
		$selectedIds = array_filter($required_optional_ids, function($id) {
			return isset($_REQUEST["bundle_selected_optional_{$id}"]);
		});

        if ( empty($selectedIds) && in_array($product->get_name(),$productNameArray) ){
            WC()->session->set('custom_validation_notice', true);
			return false;
		}

		return $passed;
	}catch(Exception $e){
			error_log("An error occurred: validate_optional_bundle_items_selected>>(functions.php)" . $e->getMessage());
            return $passed;
		}
}

add_action('template_redirect', 'notice_on_empty_cart_plans');
function notice_on_empty_cart_plans(){
    try{
        $show_notice  = WC()->session->get('custom_validation_notice');
        if ($show_notice ){
            wc_add_notice(__('Please select at least one applicable plan before proceeding.', 'woocommerce'), 'error');
            WC()->session->__unset('custom_validation_notice');
        }
    }catch(Exception $e){
			error_log("An error occurred: notice_on_empty_cart_plans()" . $e->getMessage());
		}
}

add_action("woocommerce_cart_is_empty","notice_on_empty_cart_plans_cart_page");
function notice_on_empty_cart_plans_cart_page(){
    try{
        ?>
        <style>
            .woocommerce-error {
                display:flex;
                border-radius: 8px;
                background-color: #faf6f6;
                color: #333;
                padding: 15px 20px;
                margin: 20px 0;
                font-size: 16px;
                font-family: inherit;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            }
            .woocommerce-error ul {
                margin: 0;
                padding: 0;
                list-style: none;
            }
            .woocommerce-error li {
                margin: 0;
            }
            .woocommerce-error::before {
                display: none;
            }
        </style>
        <div class="woocommerce-error" role="alert">
            <ul>
                <li>Please select at least one applicable plan before proceeding.</li>
            </ul>
        </div>
        <?php
    }catch(Exception $e){
			error_log("An error occurred: notice_on_empty_cart_plans_cart_page()" . $e->getMessage());
	}
    
}
?>
DROP TABLE team_kingkong.tpap_risk114_breaches;

-- CREATE TABLE team_kingkong.tpap_risk114_breaches AS
INSERT INTO team_kingkong.tpap_risk114_breaches
SELECT DISTINCT B.*, C.category, C.txn_type, C.payer_os, C.initiationMode
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN mcc END) AS payeeMccCode,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE'2025-01-01' AND DATE'2025-04-30' 
    GROUP BY 1)B
inner join
    (select DISTINCT txn_id, category, "type" AS txn_type
    , json_extract_scalar(extended_info, '$.payerOsApp') AS payer_os
    , json_extract_scalar(extended_info, '$.initiationMode') as initiationMode
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND category = 'VPA2MERCHANT') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    -- , JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode') AS initiationMode
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    -- AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) LIKE '%@paytm%'
    -- or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) like '%@pt%')
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') IS NOT NULL
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') IS NOT NULL
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') <> ''
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') <> ''
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') =  'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE payer_vpa IS NOT NULL
AND ((payeeMccCode = '6513' AND initiationMode = '00' AND txn_type NOT IN ('PAY', 'DEBIT', 'CR'))
OR (payeeMccCode = '6513' AND initiationMode NOT IN ('00', '04', '05', '01', '02', '03', '10') ))
;


Opris delivers high-performance crypto exchange development solutions built for serious scalability, security, and speed. Whether you're launching a centralized or decentralized platform, we provide end-to-end support—from robust trading engines to KYC, liquidity integration, and multi-currency wallets. Want to launch your own crypto exchange? Opris gets you there, fast.

The Trust Wallet Clone Script is a ready-to-deploy crypto wallet solution that lets you build a secure, multi-chain wallet app just like Trust Wallet. It supports major cryptocurrencies, tokens, and dApps, with features like private key control, in-app swaps, and biometric security. Fully customizable and built for scalability, this script gives you everything you need to launch a trusted, user-friendly wallet. Opris helps you launch your own crypto wallet like Trust Wallet—faster, smarter, and fully tailored.

entityMap = crmAPIRequest.toMap().get("record");
response = Map();
Unit_ID = ifNull(entityMap.get("Unit_No"),{"id":""}).get("id");
current_Sales_Type_Identification = ifnull(entityMap.get("Sales_Type_Identification"),"");
current_POP_Status = ifnull(entityMap.get("Pick_List_1"),"");
Edit_Record = ifNull(entityMap.get("Edit_Record"),"");
if(Edit_Record == false)
{
	if(Unit_ID != "")
	{
		if(current_Sales_Type_Identification == "New Sale")
		{
			Unit_name = ifNull(entityMap.get("Unit_No"),{"name":""}).get("name");
			search_resp = zoho.crm.searchRecords("POP","(Unit_No:equals:" + Unit_name + ")");
			if(search_resp.size() > 0)
			{
				for each  pop in search_resp
				{
					existing_Pop_status = ifnull(pop.get("Pick_List_1"),"");
					info "existing Pop_status ==>" + existing_Pop_status;
					existing_Sales_Type_Identification = ifnull(pop.get("Sales_Type_Identification"),"");
					info "existing_Sales_Type_Identification ==>" + existing_Sales_Type_Identification;
					if(existing_Sales_Type_Identification == "New Sale")
					{
						if(existing_Pop_status == "Payment Lost")
						{
							response.put('status','success');
						}
						else
						{
							response.put('status','error');
							response.put('message','An POP with Same Unit No already exist in systen');
							break;
						}
					}
					else if(existing_Sales_Type_Identification == "Existing Sale")
					{
						get_salestracker_records = zoho.crm.getRelatedRecords("Sales_Tracker","Products",Unit_ID);
						for each  record in get_salestracker_records
						{
							Cancelled_Units_Yes_No = ifnull(record.get("Cancelled_Units_Yes_No"),"");
							if(Cancelled_Units_Yes_No != "Yes")
							{
								response.put('status','error');
								response.put('message','An active reservation already associated with this Unit.');
								break;
							}
							else if(Cancelled_Units_Yes_No == "Yes")
							{
								response.put('status','success');
							}
						}
					}
				}
			}
			else
			{
				get_salestracker_records = zoho.crm.getRelatedRecords("Sales_Tracker","Products",Unit_ID);
				for each  record in get_salestracker_records
				{
					Cancelled_Units_Yes_No = ifnull(record.get("Cancelled_Units_Yes_No"),"");
					if(Cancelled_Units_Yes_No != "Yes")
					{
						response.put('status','error');
						response.put('message','An active reservation already associated with this Unit.');
						break;
					}
					else if(Cancelled_Units_Yes_No == "Yes")
					{
						response.put('status','success');
					}
				}
			}
		}
		else if(current_Sales_Type_Identification == "Existing Sale")
		{
			// 			get_salestracker_records = zoho.crm.getRelatedRecords("Sales_Tracker","Products",Unit_ID);
			// 			if(get_salestracker_records.size() > 0)
			// 			{
			// 				for each  record in get_salestracker_records
			// 				{
			// 					Cancelled_Units_Yes_No = ifnull(record.get("Cancelled_Units_Yes_No"),"");
			// 					if(Cancelled_Units_Yes_No != "Yes")
			// 					{
			// 						response.put('status','error');
			// 						response.put('message','An active reservation already associated with this Unit.');
			// 						break;
			// 					}
			// 					else if(Cancelled_Units_Yes_No == "Yes")
			// 					{
			// 						response.put('status','success');
			// 					}
			// 				}
			// 			}
			// 			else
			// 			{
			// 				response.put('status','success');
			// 			}
			response.put('status','success');
		}
	}
}
if(response.isEmpty())
{
	response.put('status','success');
}
return response;
import axios from 'axios';
import { logout } from '../middelware/auth';

export const LOGIN_TOKEN = 'token';
export const keys = [LOGIN_TOKEN];

  // export const BASE_URL = 'http://192.168.1.29:8888/.netlify/functions/api/';
export const BASE_URL = 'https://diamand-api.netlify.app/.netlify/functions/api/';
// export const BASE_URL = 'http://192.168.2.36:8000/api/';
const apiAxios = axios.create({
  baseURL: BASE_URL,
  headers: {
    Accept: 'application/json',
    'Content-type': 'application/json',
  },
});
const uploadImageAxiosApi = axios.create({
  baseURL: BASE_URL,
  headers: {
    Accept: 'application/json',    'content-type': 'multipart/form-data',
  },
});

export const getToken = async () => {
    return await localStorage.getItem(LOGIN_TOKEN);
};

export const setToken = async (token:any) => {
    // apiAxios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
    return await localStorage.setItem(LOGIN_TOKEN, token);
  };

apiAxios.interceptors.request.use(async (config) => {
  const token = await getToken();

  if (token) {
    config.headers.Authorization = ` ${token}`;
  }
  return config;
});

uploadImageAxiosApi.interceptors.request.use(async (config) => {
  const token = await getToken();

  if (token) {
    config.headers.Authorization = ` ${token}`;
  }

  return config;
});
 const axiosError = (setIsLoggedIn:any)=>{
   apiAxios.interceptors.response.use(
    function (response) {
      return response;
    },
    function (error) {
      if (error && error.response && error.response.status === 401) {
        logout()
        setIsLoggedIn(false)
      }
      return Promise.reject(error);
    }
  );
  uploadImageAxiosApi.interceptors.response.use(
    function (response) {
      return response;
    },
    function (error) {
      if (error && error.response && error.response.status === 401) {
        logout()
        setIsLoggedIn(false)
      }
      return Promise.reject(error);
    }
  );
}
export {uploadImageAxiosApi , axiosError}

export default apiAxios;

////////////////////////////////////////////////

middlewer

=========
// auth.js

import UserService from "../Services/UserService";

// Constants
const TOKEN_KEY = 'token';

// Function to set the user's authentication token in AsyncStorage
export const setAuthToken = async (token:any) => {
  try {
    await localStorage.setItem(TOKEN_KEY, token);
  } catch (error) {
    console.error('Error setting auth token:', error);
  }
};

// Function to get the user's authentication token from localStorage
export const getAuthToken = async () => {
  try {
    const token = await localStorage.getItem(TOKEN_KEY);
    return token;
  } catch (error) {
    console.error('Error getting auth token:', error);
    return null;
  }
};

// Function to remove the user's authentication token from localStorage
export const removeAuthToken = async () => {
  try {
    await localStorage.removeItem(TOKEN_KEY);
  } catch (error) {
    console.error('Error removing auth token:', error);
  }
};

// Function to check if the user is authenticated
export const isAuthenticated = async () => {
  const token = await getAuthToken();
  return !!token; // Returns true if the token exists, indicating the user is authenticated
};

// Function to perform user login
export const login = async (values:any) => {
  try {
    const response = await UserService.userLogin(values)
    if (response.status === 200) {
      const token = response.data.token; 
    //   const userId = response.data.user.id;
      await setAuthToken(token);
    //   await localStorage.setItem('userId',userId)
      return { success: true, data: response.data };
    } else {
      console.error('Login failed:', response.data);
      return { success: false, error: response.data };
    }
  } catch (error) {
    console.error('Error during login:', error);
    return false; 
  }
};

// Function to perform user logout
export const logout = async () => {
  await removeAuthToken();
  await localStorage.removeItem('userId');
};


////////////////////////////////////////

import axiosApi,{uploadImageAxiosApi} from "../utils/axiosapi"


const UserService = {

    userLogin: (data:any) => axiosApi.post('user/password-login', data).then((resp:any) => {
        return resp
    }).catch((error:any) => {
        return error.response;
    }),

    //product list
    fetchProductList: ({data,type}:any) => axiosApi.get(`${type}/`,data).then((resp: any) => {
        return resp
    }),

};
export default UserService;
  
```dataviewjs
class PersistentData {
	static #constructKey = Symbol()
	static #instance
	static _dataFilePath
	static _defaultData
	_dataFilePath
	_defaultData
	_data
	constructor(constructKey, dataFilePath, defaultData) {
		if (constructKey !== PersistentData.#constructKey)
			throw new Error('constructor is private')
		this._dataFilePath = dataFilePath
		this._defaultData = defaultData
	}
	static setConfig(dataFilePath, dafaultData){
		this._dataFilePath = dataFilePath
		this._defaultData = dafaultData
	}
	static async getInstance(){
		if (!this.#instance){
			this.#instance = new PersistentData(
				this.#constructKey,
				this._dataFilePath,
				this._defaultData
			)
			await this.#instance.initialize()
		}
		return this.#instance
	}
	async initialize(){
		const exists = await app.vault.adapter.exists(this._dataFilePath)
		if (exists) {
			const str = await app.vault.adapter.read(this._dataFilePath)
			const data = JSON.parse(str)
			// 保存されているデータとdefaultDataのキーが不一致の場合、データの仕様が変わったと判断し、保存データをdefaultDataにリセットする
			if (this._haveSameKeys(data, this._defaultData)){
				this._data = data
				return
			}
		}
		this._data = this._defaultData
		await this.saveData()
	}
	getData(key){
		return this._data[key]
	}
	async setData(key, value){
		this._data[key] = value
		await this.saveData()
	}
	async saveData(){
		await app.vault.adapter.write(this._dataFilePath, this._toJSON(this._data))
	}
	_haveSameKeys(obj1, obj2) {
		const keys1 = Object.keys(obj1).sort()
		const keys2 = Object.keys(obj2).sort()
		return keys1.length === keys2.length && keys1.every((key, index) => key === keys2[index])
	}
	_toJSON(obj){
		return JSON.stringify(obj, null, 2)
	}
}

class DomUtils {
	static #registry = new Map()
	static setRegistry(key, element){
		if (this.#registry.has(key))
			throw new Error(`Element with key "${key}" is already registered`)
		if (!(element instanceof HTMLElement))
			throw new Error('Invalid element')
		this.#registry.set(key, element)
	}
	static getRegistry(key){
		return this.#registry.get(key) || null
	}
	static createElement(tagName, attributes = {}){
		const elm = document.createElement(tagName)
		if (attributes.container instanceof HTMLElement)
			attributes.container.appendChild(elm)
		if (attributes.data){
			Object.entries(attributes.data).forEach(([key, value]) => {
				elm.setAttribute(`data-${key}`, value)
			})
		}
		if (attributes.registryKey)
			this.setRegistry(attributes.registryKey, elm)
		if (attributes.onClick)
			elm.addEventListener('click', attributes.onClick)
		if (attributes.onChange)
			elm.addEventListener('change', attributes.onChange)
		if (attributes.onInput)
			elm.addEventListener('input', attributes.onInput)
		return elm
	}
	static createSelectElement(options = [], defaultValue = null, attributes = {}){
		const elm = this.createElement('select', attributes)
		const optionElms = this.createSelectOptions(options, defaultValue)
		elm.appendChild(optionElms)
		return elm
	}
	static createSelectOptions(options = [], defaultValue = null){
		const fragment = document.createDocumentFragment()
		options.forEach(option => {
			const optionElm = document.createElement('option')
			optionElm.value = option.value
			optionElm.textContent = option.text
			if (option.value === defaultValue)
				optionElm.selected = true
			fragment.appendChild(optionElm)
		})
		return fragment
	}
	static replaceSelectOptions(selectElement, options, defaultValue = null){
		const optionElms = this.createSelectOptions(options, defaultValue)
		selectElement.replaceChildren(optionElms)
	}
	static createInputElement(type = 'text', value = '', attributes = {}){
		const elm = this.createElement('input', attributes)
		elm.type = type
		elm.value = value
		if (attributes.placeholder)
			elm.placeholder = attributes.placeholder
		return elm
	}
	static createAnchorElement(href = '#', text = '', attributes = {}){
		const elm = this.createElement('a', attributes)
		elm.href = href
		elm.textContent = text
		if (attributes.target)
			elm.target = attributes.target
		return elm
	}
}

class ViewUtils {
	static clearScreen(){
		dv.container.replaceChildren()
	}
	static createSelectDays(){
		DomUtils.createSelectElement(
			config.selectDaysOptions.map(v => ({value:v, text:`${v}日`})),
			(v => {
				return config.selectDaysOptions.includes(v) ? v : config.persistentData.defaultData.selectDaysValue
			})(persistentData.getData('selectDaysValue')),
			{
				container: dv.container,
				registryKey: 'selectDays',
				onChange: async (e) => {
					persistentData.setData('selectDaysValue', e.target.value),
					ViewUtils.updateList()
				}
			}
		)
	}
	static createSelectFolder(){
		DomUtils.createSelectElement(
			[],
			null,
			{
				container: dv.container,
				registryKey: 'selectFolder',
				onChange: async (e) => {
					persistentData.setData('currentFolder', e.target.value)
					ViewUtils.updateList()
				}
			}
		)
	}
	static createInputSearch(){
		DomUtils.createInputElement(
			'text',
			persistentData.getData('searchString'),
			{
				placeholder: '検索',
				container: dv.container,
				registryKey: 'searchInput',
				onInput: debounce(async (e) => {
					persistentData.setData('searchString', e.target.value.trim())
					ViewUtils.updateList()
				}, 1000)
			}
		)
	}
	static createListContainer(){
		DomUtils.createElement(
			'div',
			{
				container: dv.container,
				registryKey: 'listContainer',
				onClick: (e) => {
					if (e.target.tagName === 'A')
						app.workspace.openLinkText(e.target.dataset.url, '', true)
				}
			}
		)
	}
	static async updateList() {
		const daysBack = persistentData.getData('selectDaysValue')
		let currentFolder = persistentData.getData('currentFolder')
		const searchString = persistentData.getData('searchString')
		const now = dv.date('now')
		const startDate = now.minus({days: parseInt(daysBack) - 1}).startOf('day')
		let pages = dv.pages()
			.where(p => {
				const mtime = dv.date(p.file.mtime)
				return mtime >= startDate && mtime <= now
			})
		if (searchString)
			pages = pages.where(p => p.file.name.toLowerCase().includes(searchString.toLowerCase()))

		const folderCounts = {}
		pages.forEach(page => {
			const folder = page.file.folder || ''
			folderCounts[folder] = (folderCounts[folder] || 0) + 1
		})
		const folders = Array.from(pages.file.folder.distinct()).sort()
		folders.unshift('すべてのフォルダ')

		if (!folders.includes(currentFolder)){
			currentFolder = 'すべてのフォルダ'
			persistentData.setData('currentFolder', currentFolder)
		}

		DomUtils.replaceSelectOptions(
			DomUtils.getRegistry('selectFolder'),
			folders.map(folder => {
				let count, text
				if (folder === 'すべてのフォルダ'){
					count = pages.length
					text = `${folder} (${count})`
				} else {
					count = folderCounts[folder]
					text = `/${folder} (${count})`
				}
				return {value:folder, text:text}
			}),
			currentFolder
		)

		if (currentFolder !== 'すべてのフォルダ')
			pages = pages.where(p => p.file.folder === currentFolder)

		const ul = DomUtils.createElement('ul')
		pages
			.sort(p => p.file.mtime, 'desc')
			.forEach(page => {
				const li = DomUtils.createElement('li')
				DomUtils.createAnchorElement('#', page.file.name, {container: li, data:{url:page.file.name}})
				ul.appendChild(li)
			})
		DomUtils.getRegistry('listContainer').replaceChildren(ul)
	}
}

function debounce(func, wait) {
	let timeout = null
	return function(...args) {
		if (timeout)
			clearTimeout(timeout)
		timeout = setTimeout(() => {
			func(...args)
			timeout = null
		}, wait)
	}
}

const config = {
	persistentData: {
		// 永続データ保存ファイルのVault内パス
		// 親ディレクトリは前もって作成しておく
		dataFilePath: '/Scripts/Dataview/PersistentData/touchSort.json',

		// 永続データのデフォルト値
		defaultData: {selectDaysValue: '10', currentFolder: 'すべてのフォルダ', searchString: ''}
	},
	// 日数の選択肢
	selectDaysOptions: ['1', '2', '3', '5', '7', '10', '14', '20', '30', '60', '90', '120']
}

PersistentData.setConfig(
	config.persistentData.dataFilePath,
	config.persistentData.defaultData
)
const persistentData = await PersistentData.getInstance()

// 稀に古い要素が残るので明示的に画面をクリアする
ViewUtils.clearScreen()

ViewUtils.createSelectDays()
ViewUtils.createSelectFolder()
ViewUtils.createInputSearch()
ViewUtils.createListContainer()

ViewUtils.updateList()

```
```dataviewjs
class PersistentData {
	static #constructKey = Symbol()
	static #instance
	static _dataFilePath
	static _defaultData
	_dataFilePath
	_defaultData
	_data
	constructor(constructKey, dataFilePath, defaultData) {
		if (constructKey !== PersistentData.#constructKey)
			throw new Error('constructor is private')
		this._dataFilePath = dataFilePath
		this._defaultData = defaultData
	}
	static setConfig(dataFilePath, dafaultData){
		this._dataFilePath = dataFilePath
		this._defaultData = dafaultData
	}
	static async getInstance(){
		if (!this.#instance){
			this.#instance = new PersistentData(
				this.#constructKey,
				this._dataFilePath,
				this._defaultData
			)
			await this.#instance.initialize()
		}
		return this.#instance
	}
	async initialize(){
		const exists = await app.vault.adapter.exists(this._dataFilePath)
		if (exists) {
			const str = await app.vault.adapter.read(this._dataFilePath)
			const data = JSON.parse(str)
			// 保存されているデータとdefaultDataのキーが不一致の場合、データの仕様が変わったと判断し、保存データをdefaultDataにリセットする
			if (this._haveSameKeys(data, this._defaultData)){
				this._data = data
				return
			}
		}
		this._data = this._defaultData
		await this.saveData()
	}
	getData(key){
		return this._data[key]
	}
	async setData(key, value){
		this._data[key] = value
		await this.saveData()
	}
	async saveData(){
		await app.vault.adapter.write(this._dataFilePath, this._toJSON(this._data))
	}
	_haveSameKeys(obj1, obj2) {
		const keys1 = Object.keys(obj1).sort()
		const keys2 = Object.keys(obj2).sort()
		return keys1.length === keys2.length && keys1.every((key, index) => key === keys2[index])
	}
	_toJSON(obj){
		return JSON.stringify(obj, null, 2)
	}
}

class DomUtils {
	static #registry = new Map()
	static setRegistry(key, element){
		if (this.#registry.has(key))
			throw new Error(`Element with key "${key}" is already registered`)
		if (!(element instanceof HTMLElement))
			throw new Error('Invalid element')
		this.#registry.set(key, element)
	}
	static getRegistry(key){
		return this.#registry.get(key) || null
	}
	static createElement(tagName, attributes = {}){
		const elm = document.createElement(tagName)
		if (attributes.container instanceof HTMLElement)
			attributes.container.appendChild(elm)
		if (attributes.data){
			Object.entries(attributes.data).forEach(([key, value]) => {
				elm.setAttribute(`data-${key}`, value)
			})
		}
		if (attributes.registryKey)
			this.setRegistry(attributes.registryKey, elm)
		if (attributes.onClick)
			elm.addEventListener('click', attributes.onClick)
		if (attributes.onChange)
			elm.addEventListener('change', attributes.onChange)
		if (attributes.onInput)
			elm.addEventListener('input', attributes.onInput)
		return elm
	}
	static createSelectElement(options = [], defaultValue = null, attributes = {}){
		const elm = this.createElement('select', attributes)
		const optionElms = this.createSelectOptions(options, defaultValue)
		elm.appendChild(optionElms)
		return elm
	}
	static createSelectOptions(options = [], defaultValue = null){
		const fragment = document.createDocumentFragment()
		options.forEach(option => {
			const optionElm = document.createElement('option')
			optionElm.value = option.value
			optionElm.textContent = option.text
			if (option.value === defaultValue)
				optionElm.selected = true
			fragment.appendChild(optionElm)
		})
		return fragment
	}
	static replaceSelectOptions(selectElement, options, defaultValue = null){
		const optionElms = this.createSelectOptions(options, defaultValue)
		selectElement.replaceChildren(optionElms)
	}
	static createInputElement(type = 'text', value = '', attributes = {}){
		const elm = this.createElement('input', attributes)
		elm.type = type
		elm.valye = value
		if (attributes.placeholder)
			elm.placeholder = attributes.placeholder
		return elm
	}
	static createAnchorElement(href = '#', text = '', attributes = {}){
		const elm = this.createElement('a', attributes)
		elm.href = href
		elm.textContent = text
		if (attributes.target)
			elm.target = attributes.target
		return elm
	}
}

class ViewUtils {
	static clearScreen(){
		dv.container.replaceChildren()
	}
	static createSelectDays(){
		DomUtils.createSelectElement(
			config.selectDaysOptions.map(v => ({value:v, text:`${v}日`})),
			(v => {
				return config.selectDaysOptions.includes(v) ? v : config.persistentData.defaultData.selectDaysValue
			})(persistentData.getData('selectDaysValue')),
			{
				container: dv.container,
				registryKey: 'selectDays',
				onChange: async (e) => {
					persistentData.setData('selectDaysValue', e.target.value),
					ViewUtils.updateList()
				}
			}
		)
	}
	static createSelectFolder(){
		DomUtils.createSelectElement(
			[],
			null,
			{
				container: dv.container,
				registryKey: 'selectFolder',
				onChange: async (e) => {
					persistentData.setData('currentFolder', e.target.value)
					ViewUtils.updateList()
				}
			}
		)
	}
	static createInputSearch(){
		DomUtils.createInputElement(
			'text',
			persistentData.getData('searchString'),
			{
				placeholder: '検索',
				container: dv.container,
				registryKey: 'searchInput',
				onInput: debounce(async (e) => {
					persistentData.setData('searchString', e.target.value.trim())
					ViewUtils.updateList()
				}, 1000)
			}
		)
	}
	static createListContainer(){
		DomUtils.createElement(
			'div',
			{
				container: dv.container,
				registryKey: 'listContainer',
				onClick: (e) => {
					if (e.target.tagName === 'A')
						app.workspace.openLinkText(e.target.dataset.url, '', true)
				}
			}
		)
	}
	static async updateList() {
		const daysBack = persistentData.getData('selectDaysValue')
		let currentFolder = persistentData.getData('currentFolder')
		const searchString = persistentData.getData('searchString')
		const now = dv.date('now')
		const startDate = now.minus({days: parseInt(daysBack) - 1}).startOf('day')
		let pages = dv.pages()
			.where(p => {
				const mtime = dv.date(p.file.mtime)
				return mtime >= startDate && mtime <= now
			})
		if (searchString)
			pages = pages.where(p => p.file.name.toLowerCase().includes(searchString.toLowerCase()))

		const folderCounts = {}
		pages.forEach(page => {
			const folder = page.file.folder || ''
			folderCounts[folder] = (folderCounts[folder] || 0) + 1
		})
		const folders = Array.from(pages.file.folder.distinct()).sort()
		folders.unshift('すべてのフォルダ')

		if (!folders.includes(currentFolder)){
			currentFolder = 'すべてのフォルダ'
			persistentData.setData('currentFolder', currentFolder)
		}

		DomUtils.replaceSelectOptions(
			DomUtils.getRegistry('selectFolder'),
			folders.map(folder => {
				let count, text
				if (folder === 'すべてのフォルダ'){
					count = pages.length
					text = `${folder} (${count})`
				} else {
					count = folderCounts[folder]
					text = `/${folder} (${count})`
				}
				return {value:folder, text:text}
			}),
			currentFolder
		)

		if (currentFolder !== 'すべてのフォルダ')
			pages = pages.where(p => p.file.folder === currentFolder)

		const ul = DomUtils.createElement('ul')
		pages
			.sort(p => p.file.mtime, 'desc')
			.forEach(page => {
				const li = DomUtils.createElement('li')
				DomUtils.createAnchorElement('#', page.file.name, {container: li, data:{url:page.file.name}})
				ul.appendChild(li)
			})
		DomUtils.getRegistry('listContainer').replaceChildren(ul)
	}
}

function debounce(func, wait) {
	let timeout = null
	return function(...args) {
		if (timeout)
			clearTimeout(timeout)
		timeout = setTimeout(() => {
			func(...args)
			timeout = null
		}, wait)
	}
}

const config = {
	persistentData: {
		// 永続データ保存ファイルのVault内パス
		// 親ディレクトリは前もって作成しておく
		dataFilePath: '/Scripts/Dataview/PersistentData/touchSort.json',

		// 永続データのデフォルト値
		defaultData: {selectDaysValue: '10', currentFolder: 'すべてのフォルダ', searchString: ''}
	},
	// 日数の選択肢
	selectDaysOptions: ['1', '2', '3', '5', '7', '10', '14', '20', '30', '60', '90', '120']
}

PersistentData.setConfig(
	config.persistentData.dataFilePath,
	config.persistentData.defaultData
)
const persistentData = await PersistentData.getInstance()

// 稀に古い要素が残るので明示的に画面をクリアする
ViewUtils.clearScreen()

ViewUtils.createSelectDays()
ViewUtils.createSelectFolder()
ViewUtils.createInputSearch()
ViewUtils.createListContainer()

ViewUtils.updateList()

```
The rise of cryptocurrency has revolutionized how we think about money, investments, and transactions. In this digital era, businesses are constantly looking for innovative ways to simplify payments, enhance security, and meet the growing demands of tech-savvy consumers. One such innovation is the crypto payment gateway script, which offers a streamlined, efficient, and secure way to accept cryptocurrency payments. But what exactly is a crypto payment gateway script, and why should businesses integrate it into their systems? Let’s dive into the details.

What is a Crypto Payment Gateway Script?
A crypto payment gateway script is a software solution that allows merchants and businesses to accept payments in various cryptocurrencies such as Bitcoin, Ethereum, and Litecoin. These scripts act as the bridge between a buyer and a seller in a crypto transaction, providing a seamless and secure platform to process payments. It functions similarly to traditional payment gateways like PayPal or Stripe but is designed specifically to handle digital currencies.

The script generally includes a set of APIs, user interfaces, and tools that enable businesses to receive, process, and manage crypto payments in real time. Crypto payment gateways work by converting the digital currency into the local currency or offering the option to retain it as crypto.

Key Features of a Crypto Payment Gateway Script
Multiple Cryptocurrency Support:
One of the standout features of a crypto payment gateway script is its ability to support a wide range of digital currencies. Whether it’s Bitcoin, Ethereum, or newer altcoins, businesses can easily customize their payment systems to accept multiple types of crypto. This flexibility is essential for attracting a global customer base that prefers different cryptocurrencies.

Instant Transaction Processing:
Traditional payment methods often involve several intermediaries and can take time for the transaction to clear. With crypto payment gateways, the transaction process is fast and typically happens in minutes, even across borders. This is due to the decentralized nature of cryptocurrencies, which eliminates the need for banks or payment processors.

Low Transaction Fees:
Crypto payments often come with lower fees compared to credit card payments or PayPal transfers. The blockchain technology behind cryptocurrencies minimizes the middlemen involved, reducing the costs associated with traditional banking systems.

Security and Fraud Prevention:
Crypto payment gateway scripts offer enhanced security features, such as encryption and multi-signature wallets. The use of blockchain technology ensures that transactions are transparent, immutable, and verifiable. This significantly reduces the risk of fraud and chargebacks that are common in traditional online payments.

Easy Integration:
Crypto payment gateway scripts are designed to integrate seamlessly with existing e-commerce platforms, such as Shopify, WooCommerce, and Magento. This makes it easier for businesses to implement and start accepting crypto payments without a complete overhaul of their systems.

Customizable Payment Solutions:
Crypto payment gateway scripts allow businesses to offer a customized experience to their customers. Whether it’s setting payment thresholds, providing automatic invoice generation, or offering discounts for crypto payments, the flexibility to tailor payment processes is a huge benefit for both merchants and consumers.

How Does a Crypto Payment Gateway Script Work?
The process of using a crypto payment gateway script is quite straightforward:

Customer Chooses Cryptocurrency:
When making a purchase, the customer selects a cryptocurrency as the payment method at checkout.

Generate Payment Request:
The payment gateway generates a unique crypto address for the transaction. This is usually a QR code or a payment link that the customer can scan or click on to send the funds.

Transaction Verification:
Once the payment is sent by the customer, the gateway verifies the transaction on the blockchain. This may take a few minutes, depending on the cryptocurrency and the network load.

Confirmation:
Once the payment is confirmed, the crypto payment gateway notifies the business and customer of the successful transaction. The merchant may then convert the crypto into fiat currency or keep it as digital currency, depending on their business preferences.

Advantages of Using a Crypto Payment Gateway Script
Global Reach:
Cryptocurrency transcends borders, allowing businesses to reach a global audience without the need to worry about currency exchange rates or international payment restrictions. This is especially beneficial for e-commerce businesses looking to expand their customer base.

No Chargebacks:
Chargebacks, a common issue with credit card payments, are not possible with cryptocurrencies. Once a transaction is confirmed on the blockchain, it cannot be reversed. This reduces the risk of fraud and protects merchants from losing revenue.

Enhanced Privacy:
Cryptocurrency transactions offer a higher level of privacy than traditional payment methods. While they aren’t completely anonymous, they do provide users with greater control over their personal information, which is particularly appealing to privacy-conscious customers.

Future-Proof Payments:
As cryptocurrencies continue to gain adoption, integrating a crypto payment gateway script allows businesses to future-proof their payment systems. By adopting this technology now, businesses can stay ahead of the curve and position themselves as innovative leaders in their industry.

Challenges to Consider
Price Volatility:
Cryptocurrencies are known for their volatility. The value of a coin can fluctuate significantly in a short period, which may lead to uncertainty for both merchants and customers. However, many crypto payment gateways allow businesses to instantly convert crypto into fiat currency to mitigate this risk.

Regulatory Uncertainty:
Cryptocurrency regulations vary from country to country and are still evolving. Businesses need to stay updated on local laws regarding cryptocurrency payments to ensure compliance and avoid potential legal issues.

Customer Education:
While cryptocurrency adoption is growing, many consumers still don’t fully understand how it works. Businesses may need to invest in educating their customers on how to use the payment gateway and the benefits of paying with crypto.

Conclusion
Integrating a crypto payment gateway script into your business not only simplifies the payment process but also opens doors to a global market. With features like low transaction fees, enhanced security, and the potential for faster payments, businesses can improve their bottom line while offering customers a modern, frictionless payment experience. However, like any new technology, there are challenges that businesses must consider, such as price volatility and regulatory concerns.

Ultimately, embracing cryptocurrency payments today is an investment in the future, allowing your business to stay competitive and relevant in an increasingly digital world.
void automation.SEND_NEWLEAD_AGREEMENT_ON_RENEWAL(Int leaseID)
{
try 
{
	///////////////////////-get renewal lease id------///////////
	Expiring_leasesDetails = zoho.crm.getRelatedRecords("Related_List_Name_1","Leases",leaseID);
	info Expiring_leasesDetails;
	for each  leaseDetail in Expiring_leasesDetails
	{
		lease_id = leaseDetail.get("id");
	}
	info lease_id;
	//////////////////////------get renewal lease info-----////////////
	lease_detail = zoho.crm.getRecordById("Leases",lease_id);
	// 	info lease_detail;
	opp_id = lease_detail.get("Opportunity").get("id");
	// 	info opp_id;
	oppData = zoho.crm.getRecordById("Deals",opp_id);
	info oppData;
	siteid = oppData.get("Site").get("id");
	info "siteid: " + siteid;
	//////////---------
	siteinfo = zoho.crm.getRecordById("Accounts",siteid);
	initial_lead_inspection_result = siteinfo.get("Initial_Lead_Inspection_Result");
	info initial_lead_inspection_result;
	///////////////////////////////////////////////////////////////////
	oppName = oppData.get("Deal_Name");
	info "opp name: " + oppName;
	siteName = oppData.get("Site").get("name");
	info "siteName: " + siteName;
	if(oppData.get("Property_Manager") != null)
	{
		propertyManager = oppData.get("Property_Manager").get("name");
		pm_id = oppData.get("Property_Manager").get("id");
	}
	info "pm:" + propertyManager;
	///////////////////////////////////////////////////////////////////////////////
	petPolicyCharges = oppData.get("Pet_Policy_Charges_USD");
	waterMonthlyCharges = oppData.get("Monthly_Water_Charges_USD");
	info waterMonthlyCharges;
	info petPolicyCharges;
	if(waterMonthlyCharges == null || waterMonthlyCharges == 0)
	{
		waterMonthlyCharges = "Water utility (Monthly Charges) will be charged on actual consumption.";
	}
	else
	{
		waterMonthlyCharges = "Constant of $ " + waterMonthlyCharges + " will be charged for water utility per month residing in the property.";
	}
	if(petPolicyCharges == null || petPolicyCharges == 0 || petPolicyCharges == 200)
	{
		petPolicyCharges = "200";
	}
	info "Test Only";
	/////////////////////////property manager Email///////////////////////
	NewAccessTokenRequest = invokeurl
	[
		url :"https://accounts.zoho.com/oauth/v2/token?refresh_token=1000.0d787bd93f09618b2dbd194ce87a3ac4.c64ff75b9cb389b49ebf42844e9673f3&client_id=1000.6S03ETCF3SEM8YHEQ9BUGXDK6O7Q1H&client_secret=418fb1c600b10085070ca461e6a5e2b8c4a0632133&redirect_uri=https://clevelandbricks.com/&grant_type=refresh_token"
		type :POST
	];
	NewAccessToken = NewAccessTokenRequest.get("access_token");
	//---------------------------Authtoken---------------------------------------
	Authtoken = Map();
	Authtoken.put("Authorization","Zoho-oauthtoken " + NewAccessToken + "");
	Org_Data = invokeurl
	[
		url :"https://www.zohoapis.com/crm/v2/users/" + pm_id
		type :GET
		headers:Authtoken
	];
	info "pm_id" + pm_id;
	info Org_Data;
	propertyManagerEmail = Org_Data.get("users").get(0).get("email");
	info "Property Manager Email: " + propertyManagerEmail;
	////////	///------------------GET INFO FROM NEW LEASE--------------////////
	leaseTerm_months = lease_detail.get("Least_Rental_Term_Months");
	leaseTerm_days = lease_detail.get("Lease_Term_Number_of_Days");
	monthlyRent = lease_detail.get("Monthly_Rent");
	paymentTerms = lease_detail.get("Payment_Terms");
	leaseStartDate = lease_detail.get("Lease_Start_Date").toString("MM/dd/yyyy");
	leaseEndDate = lease_detail.get("Lease_End_Date").toString("MM/dd/yyyy");
	////////////////////////////////////GET INFO FROM OPP///////////////////////////////////////
	securityDeposit = 0;
	tenantName = ifnull(oppData.get("Contact_Name").get("name"),"");
	tenantId = ifnull(oppData.get("Contact_Name").get("id"),"");
	tenantEmail = zoho.crm.getRecordById("Contacts",tenantId).get("Email");
	info "Primary tenant Email: " + tenantEmail;
	//------------------------------------------------------------------------
	coTenant1Data = oppData.get("Sub_Contact_1");
	coTenant2Data = oppData.get("Sub_Contact_2");
	coTenant3Data = oppData.get("Sub_Contact_3");
	coTenant4Data = oppData.get("Sub_Contact_4");
	totalTenant = 1;
	coTenants = {1,2,3,4};
	for each  data in coTenants
	{
		count = oppData.get("Sub_Contact_" + data);
		if(count != null)
		{
			totalTenant = totalTenant + 1;
		}
	}
	info "Total Tenant/s = " + totalTenant;
	/////////-------------------------------lead+lease-------------------------------------
	if(initial_lead_inspection_result = "Fail")
	{
		info "initial_lead_inspection_result=failed";
		if(totalTenant == 1)
		{
			templateResp = zoho.sign.getTemplateById(53924000002918479);
			info "fail 1 tenant";
			//old was 
		}
		else if(totalTenant == 2)
		{
			templateResp = zoho.sign.getTemplateById(53924000002918253);
			info "fail 2 tenants";
		}
		else if(totalTenant == 3)
		{
			templateResp = zoho.sign.getTemplateById(53924000002918031);
			info "fail 3 tenants";
		}
		else if(totalTenant == 4)
		{
			templateResp = zoho.sign.getTemplateById(53924000002916523);
			info "fail 4 tenants";
		}
	}
	else
	{
		info "pass or blank";
		if(totalTenant == 1)
		{
			templateResp = zoho.sign.getTemplateById(53924000002918659);
			info "pass 1 tenant";
			//old was 
		}
		else if(totalTenant == 2)
		{
			templateResp = zoho.sign.getTemplateById(53924000002918839);
			info "pass 2 tenants";
		}
		else if(totalTenant == 3)
		{
			templateResp = zoho.sign.getTemplateById(53924000002919039);
			info "pass 3 tenants";
		}
		else if(totalTenant == 4)
		{
			templateResp = zoho.sign.getTemplateById(53924000002919261);
			info "pass 4 tenants";
		}
	}
	/////////////////////////////////////////////////////////////
	templateRec = templateResp.get("templates");
	actionRec1 = templateRec.get("actions").get(0);
	actionRole1 = actionRec1.get("role");
	actionId1 = actionRec1.get("action_id");
	actionType1 = actionRec1.get("action_type");
	eachActionMap1 = Map();
	eachActionMap1.put("recipient_name",tenantName);
	eachActionMap1.put("recipient_email",tenantEmail);
	eachActionMap1.put("action_type",actionType1);
	eachActionMap1.put("action_id",actionId1);
	eachActionMap1.put("role",actionRole1);
	eachActionMap1.put("verify_recipient","false");
	//////////////////////////////////////property manager/////////////////////////////////////
	if(totalTenant == 1)
	{
		actionPM = templateRec.get("actions").get(1);
	}
	else if(totalTenant == 2)
	{
		actionPM = templateRec.get("actions").get(2);
	}
	else if(totalTenant == 3)
	{
		actionPM = templateRec.get("actions").get(3);
	}
	else if(totalTenant == 4)
	{
		actionPM = templateRec.get("actions").get(4);
	}
	// 	else if(totalTenant == 5)
	// 	{
	// 		actionPM = templateRec.get("actions").get(5);
	// 	}
	PMRole = actionPM.get("role");
	PMId = actionPM.get("action_id");
	PMType = actionPM.get("action_type");
	PMMap1 = Map();
	PMMap1.put("recipient_name",propertyManager);
	PMMap1.put("recipient_email",propertyManagerEmail);
	PMMap1.put("action_type",PMType);
	PMMap1.put("action_id",PMId);
	PMMap1.put("role",PMRole);
	PMMap1.put("verify_recipient","false");
	//////////////////////////////--------------------------///////////////////
	actionMap0 = Map();
	fieldTextData = Map();
	field_boolean_data = Map();
	//-------------------------------------------------------------------------
	//--------------------------------------------------------------------------
	if(coTenant1Data != null)
	{
		coTenant2 = coTenant1Data.get("name");
		coTenant1Id = coTenant1Data.get("id");
		coTenantEmail2 = zoho.crm.getRecordById("Contacts",coTenant1Id).get("Email");
		actionRec2 = templateRec.get("actions").get(1);
		actionRole2 = actionRec2.get("role");
		actionId2 = actionRec2.get("action_id");
		actionType2 = actionRec2.get("action_type");
		eachActionMap2 = Map();
		eachActionMap2.put("recipient_name",coTenant2);
		eachActionMap2.put("recipient_email",coTenantEmail2);
		eachActionMap2.put("action_type",actionType2);
		eachActionMap2.put("action_id",actionId2);
		eachActionMap2.put("role",actionRole2);
		eachActionMap2.put("verify_recipient","false");
		fieldTextData.put("Tenant-2 2b",coTenant2);
		// 		fieldTextData.put("co tenant 01",coTenant2);
		fieldTextData.put("co tenant 001",coTenant2);
	}
	if(coTenant2Data != null)
	{
		coTenant3 = coTenant2Data.get("name");
		coTenant2Id = coTenant2Data.get("id");
		coTenantEmail3 = zoho.crm.getRecordById("Contacts",coTenant2Id).get("Email");
		actionRec3 = templateRec.get("actions").get(2);
		actionRole3 = actionRec3.get("role");
		actionId3 = actionRec3.get("action_id");
		actionType3 = actionRec3.get("action_type");
		eachActionMap3 = Map();
		eachActionMap3.put("recipient_name",coTenant3);
		eachActionMap3.put("recipient_email",coTenantEmail3);
		eachActionMap3.put("action_type",actionType3);
		eachActionMap3.put("action_id",actionId3);
		eachActionMap3.put("role",actionRole3);
		eachActionMap3.put("verify_recipient","false");
		fieldTextData.put("co tenant 2",coTenant3);
		// 		fieldTextData.put("co tenant 02",coTenant3);
		fieldTextData.put("co tenant 002",coTenant3);
	}
	if(coTenant3Data != null)
	{
		coTenant4 = coTenant3Data.get("name");
		coTenant3Id = coTenant3Data.get("id");
		coTenantEmail4 = zoho.crm.getRecordById("Contacts",coTenant3Id).get("Email");
		actionRec4 = templateRec.get("actions").get(3);
		actionRole4 = actionRec4.get("role");
		actionId4 = actionRec4.get("action_id");
		actionType4 = actionRec4.get("action_type");
		eachActionMap4 = Map();
		eachActionMap4.put("recipient_name",coTenant4);
		eachActionMap4.put("recipient_email",coTenantEmail4);
		eachActionMap4.put("action_type",actionType4);
		eachActionMap4.put("action_id",actionId4);
		eachActionMap4.put("role",actionRole4);
		eachActionMap4.put("verify_recipient","false");
		fieldTextData.put("co tenant 3",coTenant4);
		// 		fieldTextData.put("co tenant 03",coTenant4);
		fieldTextData.put("co tenant 003",coTenant4);
	}
	if(coTenant4Data != null)
	{
		coTenant5 = coTenant4Data.get("name");
		coTenant4Id = coTenant4Data.get("id");
		coTenantEmail5 = zoho.crm.getRecordById("Contacts",coTenant4Id).get("Email");
		actionRec5 = templateRec.get("actions").get(4);
		actionRole5 = actionRec5.get("role");
		actionId5 = actionRec5.get("action_id");
		actionType5 = actionRec5.get("action_type");
		eachActionMap5 = Map();
		eachActionMap5.put("recipient_name",coTenant5);
		eachActionMap5.put("recipient_email",coTenantEmail5);
		eachActionMap5.put("action_type",actionType5);
		eachActionMap5.put("action_id",actionId5);
		eachActionMap5.put("role",actionRole5);
		eachActionMap5.put("verify_recipient","false");
		fieldTextData.put("co tenant 4",coTenant5);
		fieldTextData.put("co tenant 04",coTenant5);
		fieldTextData.put("co tenant 004",coTenant5);
	}
	//---------------------------------------------------------------------------
	fieldTextData.put("site name",siteName);
	fieldTextData.put("opportunity name",oppName);
	fieldTextData.put("lease term",leaseTerm_months + " Months");
	if(leaseTerm_days != null && leaseTerm_days != 0)
	{
		fieldTextData.put("lease term",leaseTerm_months + " Month/s and  " + leaseTerm_days + " Days");
	}
	fieldTextData.put("monthly rent","$ " + monthlyRent);
	fieldTextData.put("security deposite","$ " + securityDeposit);
	fieldTextData.put("lease start date",leaseStartDate);
	fieldTextData.put("lease end date",leaseEndDate);
	fieldTextData.put("tenant name",tenantName);
	// 	fieldTextData.put("tenant name 1",tenantName);
	fieldTextData.put("site name1",siteName);
	fieldTextData.put("lease start date 1",leaseStartDate);
	fieldTextData.put("lease end date 1",leaseEndDate);
	fieldTextData.put("lease start date 2",leaseStartDate);
	fieldTextData.put("mo",leaseTerm_months + " Months");
	/////////////////
	if(leaseTerm_days != null && leaseTerm_days != 0)
	{
		fieldTextData.put("mo",leaseTerm_months + " Month/s and  " + leaseTerm_days + " Days");
	}
	fieldTextData.put("rent per month","$ " + monthlyRent);
	// 	fieldTextData.put("tenant name 1",tenantName);
	fieldTextData.put("tenant name 2",tenantName);
	fieldTextData.put("property manager",propertyManager);
	fieldTextData.put("water_monthly",waterMonthlyCharges);
	fieldTextData.put("pet_charges",petPolicyCharges);
	///////////////////////////////////////
	///////////-------new changes phase 2 lead----/////////////
	fieldTextData.put("By_PMname",propertyManager);
	////////////////////------section 4 ---site info------//////////////
	Site_type = siteinfo.get("Account_Type");
	if(Site_type == "Single Unit")
	{
		field_boolean_data.put("Single_Family",true);
	}
	else if(Site_type == "Multi Unit")
	{
		field_boolean_data.put("Multi_Family",true);
	}
	else if(Site_type == "Apartment")
	{
		field_boolean_data.put("Apartment",true);
	}
	///////////////////////////////////------add new INFO IN SECTION 13 ---------------////////
	// 	siteinfo = zoho.crm.getRecordById("Accounts",siteid);
	u_vendors = siteinfo.get("Utilities_Vendors");
	// info siteinfo;
	otherapps = "";
	all_apps = siteinfo.get("Appliances");
	info all_apps;
	for each  machine in all_apps
	{
		info machine;
		if(machine == "Dishwasher")
		{
			field_boolean_data.put("L-Dishwasher",true);
		}
		if(machine == "Stove/Oven")
		{
			field_boolean_data.put("L-StoveOven",true);
		}
		if(machine == "Washing Machine")
		{
			field_boolean_data.put("L-WashingMachine",true);
		}
		if(machine == "Dryer")
		{
			field_boolean_data.put("L-dryer",true);
		}
		if(machine == "Microwave")
		{
			// 			field_boolean_data.put("L-other",true);
			otherapps = otherapps + machine;
			fieldTextData.put("13a other",otherapps);
		}
		if(machine == "Refrigerator")
		{
			field_boolean_data.put("L-Refrigerator",true);
		}
		if(machine == "Air Conditioner")
		{
			// 			field_boolean_data.put("L-other",true);
			otherapps = otherapps + machine;
			fieldTextData.put("13a other",otherapps);
		}
		// 		info fieldTextData;
	}
	/////////////////////---------------ADD INFO IN SECTION 12 -NEW-------------//////////
	if(u_vendors != null || u_vendors != "")
	{
		for each  utility in u_vendors
		{
			Type_of_Service = utility.get("Type_of_Service");
			Payment_Responsibility = utility.get("Payment_Responsibility");
			if(Type_of_Service == "Electricity")
			{
				fieldTextData.put("12.Electric",Payment_Responsibility);
			}
			if(Type_of_Service == "Gas")
			{
				fieldTextData.put("12.Gas",Payment_Responsibility);
			}
			if(Type_of_Service == "Water")
			{
				fieldTextData.put("12.Water",Payment_Responsibility);
			}
			if(Type_of_Service == "Sewer")
			{
				fieldTextData.put("12.Sewer",Payment_Responsibility);
			}
			if(Type_of_Service == "Trash")
			{
				fieldTextData.put("12.Trash",Payment_Responsibility);
			}
			if(Type_of_Service == "Landscaping")
			{
				fieldTextData.put("12.Landscaping",Payment_Responsibility);
			}
			if(Type_of_Service == "Snow Plow")
			{
				fieldTextData.put("12.Snowplow",Payment_Responsibility);
			}
			if(Type_of_Service == "HOA")
			{
				fieldTextData.put("12.HOA",Payment_Responsibility);
			}
		}
	}
	///////////////////////////////
	info waterMonthlyCharges;
	info petPolicyCharges;
	temp_map = Map();
	temp_map.put("field_text_data",fieldTextData);
	temp_map.put("field_boolean_data",field_boolean_data);
	actionMap0.put("field_data",temp_map);
	// 	actionMap0.put("field_data",{"field_boolean_data":field_boolean_data});
	fieldList = List();
	if(totalTenant == 1)
	{
		fieldList.add(eachActionMap1);
		fieldList.add(PMMap1);
	}
	else if(totalTenant == 2)
	{
		fieldList.add(eachActionMap1);
		fieldList.add(eachActionMap2);
		fieldList.add(PMMap1);
	}
	else if(totalTenant == 3)
	{
		fieldList.add(eachActionMap1);
		fieldList.add(eachActionMap2);
		fieldList.add(eachActionMap3);
		fieldList.add(PMMap1);
	}
	else if(totalTenant == 4)
	{
		fieldList.add(eachActionMap1);
		fieldList.add(eachActionMap2);
		fieldList.add(eachActionMap3);
		fieldList.add(eachActionMap4);
		fieldList.add(PMMap1);
	}
	else if(totalTenant == 5)
	{
		fieldList.add(eachActionMap1);
		fieldList.add(eachActionMap2);
		fieldList.add(eachActionMap3);
		fieldList.add(eachActionMap4);
		fieldList.add(eachActionMap5);
		fieldList.add(PMMap1);
	}
	//////////////////
	// 	fields=map();
	// 	fields.put("field_data",{"field_text_data":fieldTextData});
	// 	fields.put("field_data",{"field_boolean_data":field_boolean_data});
	// // 	////
	// 	actionMap0.put("field_data",fields);
	// 	actionMap0.put("field_data",{"field_boolean_data":field_boolean_data});
	////////////////
	actionMap0.put("actions",fieldList);
	submitMap = Map();
	submitMap.put("templates",actionMap0);
	parameters = Map();
	parameters.put("is_quicksend","true");
	parameters.put("data",submitMap);
	info "Parameters: " + parameters;
	// 	////////////////////-----------------lead+lease-------------//////
	if(initial_lead_inspection_result == "Fail")
	{
		info "fail, create using template";
		if(totalTenant == 1)
		{
			response = zoho.sign.createUsingTemplate(53924000002918479,parameters);
			info "Here: 1 agree";
			info response;
		}
		else if(totalTenant == 2)
		{
			response = zoho.sign.createUsingTemplate(53924000002918253,parameters);
		}
		else if(totalTenant == 3)
		{
			response = zoho.sign.createUsingTemplate(53924000002918031,parameters);
		}
		else if(totalTenant == 4)
		{
			response = zoho.sign.createUsingTemplate(53924000002916523,parameters);
		}
	}
	else
	{
		info "pass or blank create using template";
		if(totalTenant == 1)
		{
			response = zoho.sign.createUsingTemplate(53924000002918659,parameters);
			info "Here: 1 agree";
			info response;
		}
		else if(totalTenant == 2)
		{
			response = zoho.sign.createUsingTemplate(53924000002918839,parameters);
		}
		else if(totalTenant == 3)
		{
			response = zoho.sign.createUsingTemplate(53924000002919039,parameters);
		}
		else if(totalTenant == 4)
		{
			response = zoho.sign.createUsingTemplate(53924000002919261,parameters);
		}
	}
	info "Template: " + response;
	/////////////////
	if(response != null)
	{
		lease_update_map = Map();
		lease_update_map.put("Lease_Status","Sent");
		lease_update_map.put("Lease_Document_Status","In Process");
		update_lease = zoho.crm.updateRecord("Leases",lease_id,lease_update_map);
	}
	docxId = response.get("requests").get("request_id");
	info "Document ID: " + docxId;
	mpdocx = Map();
	mpdocx.put("renewal_document_id",docxId);
	update = zoho.crm.updateRecord("Deals",opp_id,mpdocx);
	info "Deal: " + update;
	///////////////////////////////////////////////////////////////////////////////
}
catch (e)
{
	sendmail
	[
		from :zoho.loginuserid
		to :"erp@clevelandbricks.com","rabia@erphub.biz"
		subject :"Send new agreement on Renewal/ CRM"
		message :"Name: " + oppName + " Leaseid " + lease_id + " Root Cause: " + e
	]
}
}
-- RISK009
DROP TABLE team_kingkong.tpap_risk009_breaches;

-- CREATE TABLE team_kingkong.tpap_risk009_breaches AS
INSERT INTO team_kingkong.tpap_risk009_breaches
with tpap_base as
(
SELECT DISTINCT B.*, C.category, C.txn_type
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
, D.payerType, D.payeeType
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    GROUP BY 1)B
INNER join
    (select txn_id, category, "type" AS txn_type
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND  DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND "type" = 'COLLECT' AND category = 'VPA2VPA') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') as payerType
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') as payeeType
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%'
    OR lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) like '%@pt%')
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') IS NOT NULL
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') IS NOT NULL
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') <> ''
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') <> ''
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE payer_vpa IS NOT NULL AND payee_vpa IS NOT NULL
)
 
SELECT *, 'upi_collect_request_p2p_vpa_v1' as rule_name, CASE
  WHEN txn_succ_24hr >= threshold_24hr AND txn_succ_week >= threshold_week THEN '24hr & week breach'
  WHEN txn_succ_24hr >= threshold_24hr THEN '24hr breach'
  WHEN txn_succ_week >= threshold_week THEN 'week breach'
  ELSE NULL END AS breach_reason FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.txn_time,
      DATE(t1.txn_time) AS txn_date
      , COUNT(DISTINCT IF(DATE(t2.txn_time) BETWEEN DATE(DATE(t1.txn_time) - INTERVAL '86400' SECOND) AND DATE(t1.txn_time), t2.txn_id, NULL)) AS txn_succ_24hr
      , 10 as threshold_24hr
      , COUNT(DISTINCT IF(DATE(t2.txn_time) BETWEEN DATE(DATE(t1.txn_time) - INTERVAL '604800' SECOND) AND DATE(t1.txn_time), t2.txn_id, NULL)) AS txn_succ_week
      , 25 as threshold_week
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.payee_vpa = t2.payee_vpa AND t1.payer_vpa = t2.payer_vpa
      AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '604800' SECOND) AND t1.txn_time 
      AND t1.txn_id <> t2.txn_id AND t1.txn_date BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, t1.txn_date)
WHERE (txn_succ_24hr >= threshold_24hr) OR (txn_succ_week >= threshold_week)
;
-- RISK_151
-- if in previous 20 minutes distinct(payer vpa)>=35 and txn amt > 1500 then block
DROP TABLE team_kingkong.tpap_risk151_breaches;

-- CREATE TABLE team_kingkong.tpap_risk151_breaches AS
INSERT INTO team_kingkong.tpap_risk151_breaches
with tpap_base as
(SELECT DISTINCT B.*, C.category
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    GROUP BY 1)B
inner join
    (select txn_id, category
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND category = 'VPA2VPA') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '')) like '%@pt%')
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') IS NOT NULL
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') IS NOT NULL
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeVpa') as varchar), '"', '') <> ''
    -- AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '') <> ''
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE payee_vpa <> 'jio@citibank' AND payer_vpa IS NOT NULL
)
 
SELECT * FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.txn_time,
      t1.txn_date AS txn_date,
      COUNT(DISTINCT t2.payer_vpa) AS distinct_payer_vpa,
      50 AS payer_vpa_threshold
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.payee_vpa = t2.payee_vpa
      AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '1800' SECOND) AND t1.txn_time -- 30 MINS
      AND t1.txn_id <> t2.txn_id AND t1.payer_vpa <> t1.payer_vpa
      AND t1.txn_amount > 1500 AND t1.txn_date BETWEEN DATE'2025-07-01' AND DATE'2025-07-27'
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, t1.txn_date)
WHERE distinct_payer_vpa >= payer_vpa_threshold
;
-- RISK_239
-- if in previous 20 minutes distinct(payer vpa)>=35 and txn amt > 1500 then block

DROP TABLE team_kingkong.tpap_risk239_breaches;

-- CREATE TABLE team_kingkong.tpap_risk239_breaches AS
INSERT INTO team_kingkong.tpap_risk239_breaches
with tpap_base as
(
SELECT DISTINCT B.*, C.category
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-05-01' - INTERVAL '1' DAY) AND DATE'2025-05-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-05-01' - INTERVAL '1' DAY) AND DATE'2025-05-31'
    GROUP BY 1)B
inner join
    (select txn_id, category
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-05-01' - INTERVAL '1' DAY) AND DATE'2025-05-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-05-01' - INTERVAL '1' DAY) AND DATE'2025-05-31'
    and upper(status) = 'SUCCESS' AND category = 'VPA2VPA') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-05-01' - INTERVAL '1' DAY) AND DATE'2025-05-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') =  'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE ((payer_vpa LIKE '%@paytm%') OR (payer_vpa LIKE '%@pt%') OR (payee_vpa LIKE '%@paytm%') OR (payee_vpa LIKE '%@pt%'))
AND payee_vpa LIKE '%@%' AND payee_vpa <> 'jio@citibank'
)
 
SELECT *, 'upi_p2p_multiple_senders_20min' as rule_name FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.txn_time,
      t1.txn_date,
      COUNT(DISTINCT t2.payer_vpa) AS distinct_payer_vpa,
      35 AS payer_vpa_threshold
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.payee_vpa = t2.payee_vpa AND t1.payer_vpa <> t2.payer_vpa
      AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '1200' SECOND) AND t1.txn_time -- 20 MINS
      AND t1.txn_id <> t2.txn_id AND t1.payer_vpa <> t1.payer_vpa
      AND t1.txn_amount > 1500
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, t1.txn_date)
WHERE distinct_payer_vpa >= payer_vpa_threshold
;
-- RISK510
DROP TABLE team_kingkong.tpap_risk510_breaches;

-- CREATE TABLE team_kingkong.tpap_risk510_breaches AS
INSERT INTO team_kingkong.tpap_risk510_breaches
with tpap_base as
(
SELECT DISTINCT B.*, C.category
, IF(D.upi_subtype IS NOT NULL, D.upi_subtype, IF(C.category = 'LITE_MANDATE', 'UPI_LITE_MANDATE', '')) AS upi_subtype
, D.latitude, D.longitude
, 'upi_p2p_multiple_locations_mcc_7407_v2Description' as rule_name
, 'p2m Txns from >50 locations in 24 hrs' as breach_reason
FROM
    (SELECT txn_id,
    MAX(CASE WHEN participant_type = 'PAYER' THEN vpa END) AS payer_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN vpa END) AS payee_vpa,
    MAX(CASE WHEN participant_type = 'PAYEE' THEN mcc END) AS payee_mcc,
    MAX(DATE(created_on)) as txn_date,
    MAX(amount) AS txn_amount,
    MAX(created_on) AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    GROUP BY 1)B
inner join
    (select txn_id, category
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    and upper(status) = 'SUCCESS' AND category = 'VPA2MERCHANT') C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') AS upi_subtype
    , regexp_replace(cast(json_extract(request, '$.requestPayload.latitude') as varchar), '"', '') as latitude
    , regexp_replace(cast(json_extract(request, '$.requestPayload.longitude') as varchar), '"', '') as longitude
    FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '1' DAY) AND DATE'2025-01-31'
    AND (lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) LIKE '%@paytm%'
    or lower(regexp_replace(cast(json_extract(request, '$.requestPayload.payerVpa') as varchar), '"', '')) like '%@pt%')
    AND json_extract_scalar(response, '$.action_recommended') <> 'BLOCK'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') = 'PERSON'
    AND regexp_replace(cast(json_extract(request, '$.evaluationType') as varchar), '"', '') = 'UPI_TRANSACTION')D
ON B.txn_id = D.txnid
WHERE ((payer_vpa LIKE '%@paytm%') OR (payer_vpa LIKE '%@pt%'))
AND payee_vpa LIKE '%@%'
)
 
SELECT * FROM
    (SELECT t1.payer_vpa,
      t1.payee_vpa,
      t1.payee_mcc,
      t1.txn_id,
      t1.txn_amount,
      t1.category,
      t1.upi_subtype,
      t1.txn_time,
      t1.latitude,
      t1.longitude,
      DATE(t1.txn_time) AS txn_date,
      COUNT(DISTINCT CONCAT(t2.latitude, '_', t2.longitude)) AS distinct_lat_lon_count,
      50 AS lat_long_cnt_threshold
    FROM tpap_base t1
    INNER JOIN tpap_base t2
    ON t1.payee_vpa = t2.payee_vpa
      AND t2.txn_time BETWEEN (t1.txn_time - INTERVAL '86400' SECOND) AND t1.txn_time -- 24 hrs
      AND t1.txn_id <> t2.txn_id AND t1.payee_mcc = '7407'
      AND NOT (t1.latitude = t2.latitude AND t1.longitude = t2.longitude)
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.payee_mcc, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, t1.txn_date, t1.latitude, t1.longitude)
WHERE distinct_lat_lon_count >= lat_long_cnt_threshold
;
Unlock the potential of automated crypto trading with our professional crypto trading bot development solutions. From flash loan arbitrage bots to smart grid strategies, we build tailored bots that monitor markets, execute trades, and generate consistent results.
 Explore the future of automated trading today.
{
  "DFIntTaskSchedulerTargetFps": 5588562,
  "FFlagDebugSkyGray": true,
  "FFlagDebugDisplayFPS": false,
  "DFFlagDebugRenderForceTechnologyVoxel": true,
  "DFFlagDebugPauseVoxelizer": true,
  "FFlagNewLightAttenuation": true,
  "FIntRenderShadowIntensity": 0,
  "FFlagDisablePostFx": true,
  "DFFlagTextureQualityOverrideEnabled": true,
  "DFIntTextureQualityOverride": 0,
  "FIntRenderShadowmapBias": 0,
  "FFlagLuaAppSystemBar": false,
  "FIntFontSizePadding": 3,
  "FFlagAdServiceEnabled": false,
  "FFlagDebugDisableTelemetryEphemeralCounter": true,
  "FFlagDebugDisableTelemetryEphemeralStat": true,
  "FFlagDebugDisableTelemetryEventIngest": true,
  "FFlagDebugDisableTelemetryPoint": true,
  "FFlagDebugDisableTelemetryV2Counter": true,
  "FFlagDebugDisableTelemetryV2Event": true,
  "FFlagDebugDisableTelemetryV2Stat": true,
  "DFIntCSGLevelOfDetailSwitchingDistance": 1
}
star

Sat Aug 02 2025 19:46:58 GMT+0000 (Coordinated Universal Time) https://www.w3.org/TR/2025/WD-IndexedDB-3-20250731/

@Asneedarazali #javascript

star

Sat Aug 02 2025 19:46:51 GMT+0000 (Coordinated Universal Time) https://www.w3.org/TR/2025/WD-IndexedDB-3-20250731/

@Asneedarazali #javascript

star

Sat Aug 02 2025 19:46:41 GMT+0000 (Coordinated Universal Time) https://www.w3.org/TR/2025/WD-IndexedDB-3-20250731/

@Asneedarazali #javascript

star

Sat Aug 02 2025 01:37:01 GMT+0000 (Coordinated Universal Time) Torito.com

@Carlosblgl

star

Fri Aug 01 2025 13:43:33 GMT+0000 (Coordinated Universal Time) https://www.fourchain.com/services/defi-development-company

@zainabegum #defi #defidevelopment

star

Fri Aug 01 2025 12:54:14 GMT+0000 (Coordinated Universal Time)

@mohinibhojane #php

star

Fri Aug 01 2025 11:00:39 GMT+0000 (Coordinated Universal Time) https://maticz.com/uniswap-clone-script

@carolinemax

star

Fri Aug 01 2025 10:17:44 GMT+0000 (Coordinated Universal Time) https://mikefrobbins.com/2023/06/22/determine-disk-usage-from-the-command-line-on-macos/

@teressider

star

Fri Aug 01 2025 09:36:08 GMT+0000 (Coordinated Universal Time) https://maticz.com/multicurrency-wallet-development

@austinparker

star

Fri Aug 01 2025 06:28:36 GMT+0000 (Coordinated Universal Time)

@usman13

star

Fri Aug 01 2025 06:24:51 GMT+0000 (Coordinated Universal Time)

@usman13

star

Fri Aug 01 2025 04:47:56 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Jul 31 2025 11:28:00 GMT+0000 (Coordinated Universal Time)

@AKAMAY001

star

Thu Jul 31 2025 09:39:19 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Jul 31 2025 09:37:40 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Jul 31 2025 09:36:12 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Jul 31 2025 09:34:22 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Jul 31 2025 09:07:11 GMT+0000 (Coordinated Universal Time) https://www.uniccm.com/course/professional-diploma-in-building-information-modeling-bim

@bubbleroe

star

Thu Jul 31 2025 08:38:29 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Thu Jul 31 2025 07:19:59 GMT+0000 (Coordinated Universal Time) https://beleaftechnologies.com/centralized-cryptocurrency-exchange-development

@ShellyJackson #cryptoexchange #cryptoplatform #cryptolaunch

star

Thu Jul 31 2025 06:56:58 GMT+0000 (Coordinated Universal Time)

@mohinibhojane #php

star

Thu Jul 31 2025 06:36:54 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/white-label-cryptocurrency-exchange-development/

@catelyn #whitelabel crypto exchange #exchange #crypto

star

Thu Jul 31 2025 06:28:40 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/blog/winzo-clone-app

@Seraphina

star

Thu Jul 31 2025 05:37:08 GMT+0000 (Coordinated Universal Time)

@anmoltyagi

star

Thu Jul 31 2025 05:35:12 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Wed Jul 30 2025 12:45:00 GMT+0000 (Coordinated Universal Time) https://metrixalgo.vercel.app/

@Huzaifa

star

Wed Jul 30 2025 11:03:43 GMT+0000 (Coordinated Universal Time) https://maticz.com/spot-trading-software-development

@carolinemax

star

Wed Jul 30 2025 07:25:20 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/white-label-crypto-exchange-cost/

@CharleenStewar #whitelabel crypto exchange cost

star

Wed Jul 30 2025 03:44:10 GMT+0000 (Coordinated Universal Time)

@Ajay1212

star

Wed Jul 30 2025 03:39:43 GMT+0000 (Coordinated Universal Time)

@touchSort

star

Tue Jul 29 2025 20:24:46 GMT+0000 (Coordinated Universal Time)

@touchSort

star

Tue Jul 29 2025 13:16:14 GMT+0000 (Coordinated Universal Time) https://www.appclonex.com/crypto-payment-gateway-script

@riyageorge0895

star

Tue Jul 29 2025 12:06:26 GMT+0000 (Coordinated Universal Time)

@usman13

star

Tue Jul 29 2025 11:03:53 GMT+0000 (Coordinated Universal Time) https://maticz.com/how-much-does-crypto-wallet-development-cost

@austinparker

star

Tue Jul 29 2025 10:46:33 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Tue Jul 29 2025 10:27:13 GMT+0000 (Coordinated Universal Time) https://cyberspace.in/services/responsive-website/

@cyberspace #web #design

star

Tue Jul 29 2025 09:14:25 GMT+0000 (Coordinated Universal Time) https://www.newassignmenthelpaus.com/sql-assignment-help

@henryjones0116

star

Tue Jul 29 2025 06:57:24 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Tue Jul 29 2025 06:11:45 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Tue Jul 29 2025 05:52:40 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Mon Jul 28 2025 12:38:03 GMT+0000 (Coordinated Universal Time) https://www.fourchain.com/services/cryptocurrency-trading-bot-development

@zainabegum #cryptotrading #bot

star

Mon Jul 28 2025 12:21:18 GMT+0000 (Coordinated Universal Time) https://www.firebeetechnoservices.com/crypto-trading-bot-development

@aanaethan ##crypto ##cryptocurrency ##blockchain

star

Mon Jul 28 2025 09:00:03 GMT+0000 (Coordinated Universal Time)

@enojiro7

star

Mon Jul 28 2025 07:02:13 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/white-label-crypto-wallet/

@catelyn #whitelabelcryptowallet

star

Mon Jul 28 2025 06:53:24 GMT+0000 (Coordinated Universal Time) https://ae.assignmenthelppro.com/

@anyanovak #assignmenthelp #assignmenthelper #onlineassignmenthelper #assignmenthelpservices

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension