Snippets Collections
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<int> segTree;
    vector<int> arr;

    void build(int p, int l, int r) {
        if (l == r) {
            segTree[p] = arr[l];
            return;
        }
        int mid = (l + r) >> 1;
        build(p << 1, l, mid);
        build(p << 1 | 1, mid + 1, r);
        segTree[p] = min(segTree[p << 1], segTree[p << 1 | 1]);
    }

    int query(int p, int l, int r, int ql, int qr) {
        if (qr < l || ql > r) return INT_MAX;
        if (ql <= l && r <= qr) return segTree[p];
        int mid = (l + r) >> 1;
        return min(
            query(p << 1, l, mid, ql, qr),
            query(p << 1 | 1, mid + 1, r, ql, qr)
        );
    }

    void update(int p, int l, int r, int pos, int val) {
        if (l == r) {
            segTree[p] = val;
            return;
        }
        int mid = (l + r) >> 1;
        if (pos <= mid) update(p << 1, l, mid, pos, val);
        else update(p << 1 | 1, mid + 1, r, pos, val);
        segTree[p] = min(segTree[p << 1], segTree[p << 1 | 1]);
    }

    void solve(vector<int>& input) {
        arr = input;
        int n = arr.size();
        segTree.assign(4 * n, 0);
        build(1, 0, n - 1);
    }
};
class Solution {
public:
    int segTree[400007];
    vector<int>baskets;
    void build(int p,int l,int r){
        if(l == r){
            segTree[p] = baskets[l];
            return ;
        }
        int mid = (l + r)>>1;
        build(p<<1,l,mid);
        build(p<<1|1,mid+1,r);
        segTree[p] = max(segTree[p<<1],segTree[p<<1|1]);
    }
    int query(int p,int l,int r,int ql,int qr){
        if(ql > r || qr < l)
        return INT_MIN;
        if(ql <= l && r <= qr)
        return segTree[p];
        int mid = (l + r)>>1;
        return max(query(p<<1,l,mid,ql,qr),query(p<<1|1,mid+1,r,ql,qr));
    }
    void update(int p,int l,int r,int pos,int val){
        if(l==r){
            segTree[p] = val;
            return ;
        }
        int mid = (l + r)>>1;
        if(pos <= mid){
            update(p<<1,l,mid,pos,val);
        }
        else{
            update(p<<1|1,mid+1,r,pos,val);
        }
        segTree[p] = max(segTree[p<<1],segTree[p<<1|1]);
    }
    int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
        this->baskets = baskets;
        int m = baskets.size();
        int count = 0;
        if(m == 0)
        return fruits.size();
        build(1,0,m-1);
        for(int i = 0;i<m;i++){
            int l= 0, r = m-1,res = -1;
            while(l<= r){
                int mid = (l + r)>>1;
                if(query(1,0,m-1,0,mid)>=fruits[i])
                {
                    res = mid;
                    r = mid - 1;
                }
                else{
                    l = mid +1;
                }
            }
            if(res!=-1 && baskets[res] >= fruits[i]){
                update(1,0,m-1,res,INT_MIN);
            }
            else count++;
        }
        return count;
    }
};
 public function crear(Request $request)
    {

        if ($request->isMethod('post')) {
            
            DB::beginTransaction();

            try {
                // Primero crea la persona
                $persona = \App\Models\Personas::create([
                    'cedula' => $request->documento,
                    'nombres' => mb_strtoupper($request->nombres, 'UTF-8'),
                    'apellidos' => mb_strtoupper($request->apellidos, 'UTF-8'),
                    'telefono' => $request->telefono,
                    'email' => $request->email,
                    'fecha_nacimiento' => $request->fecha_nacimiento ?: null,
                    'genero_id' => $request->genero_id,
                ]);

                // Luego crea el usuario, asignando el persona_id recién creado
                $usuario = User::create([
                    'activo' => true,
                    'role_id' => 3,
                    'username' => $request->username,
                    'password' => Hash::make($request->contrasena),
                    'fecha_registro' => now(),
                    'persona_id' => $persona->id,
                    'user_id' => Auth::id(), // equivalente a Auth::user()->id y más seguro
                    'ip' => $request->ip(),
                ]);

                // Finalmente crea la relación con el ente/instituto
                $user_ente = \App\Models\UserInstituto::create([
                    'user_id' => $usuario->id,
                    'instituto_id' => $request->instituto_id,
                    'activo' => true,
                ]);

                DB::commit();

                return redirect()->route('usuarios.index')->with('success', 'Usuario creado exitosamente');
            } catch (\Exception $e) {
                DB::rollback();
                return redirect()->back()->withErrors(['error' => 'Error al crear el usuario: ' . $e->getMessage()]);
            }
            // return redirect()->route('usuarios.crear', ['success' => 'Usuario creado exitosamente.']);
            return redirect()->route('usuarios.index')->with('success', 'Usuario creado exitosamente.');

        } else {
            $Genero = \App\Models\Genero::get()->pluck("nombre", "id");
            $Instituto = \App\Models\Instituto::get()->pluck("nombre", "id");

            //  dd($Ente);
            return view('users.crear', compact('Instituto', 'Genero'));
           


        }
    }
sudo apt install libayatana-appindicator3-1 gir1.2-ayatanaappindicator3-0.1 gnome-shell-extension-appindicator
echo "0b14e71586b22e498eb20926c48c7b434b751149b1f2af9902ef1cfe6b03e180 protonvpn-stable-release_1.0.8_all.deb" | sha256sum --check -
sudo dpkg -i ./protonvpn-stable-release_1.0.8_all.deb && sudo apt update
wget https://repo.protonvpn.com/debian/dists/stable/main/binary-all/protonvpn-stable-release_1.0.8_all.deb
class DataviewUtils {
	static async loadScript(source, args={}){
		const promise = (this._isURL(source)) ?
			this._fetch(source) : app.vault.adapter.read(source)
		return promise.then(str => {
			return new Promise((resolve, reject) => {
				try {
					const argNames = Object.keys(args)
					const argValues = Object.values(args)
					const fn = new Function(...argNames, str)
					fn(...argValues)
					resolve()
				} catch (error) {
					reject(error)
				}
			})
		})
	}
	static async loadCSS(source) {
		const promise = (this._isURL(source)) ?
			this._fetch(source) : app.vault.adapter.read(source)
		return promise.then(str => {
			return new Promise((resolve) => {
				const elm = document.createElement('style')
				elm.textContent = str
				dv.container.appendChild(elm)
				resolve()
			})
		})
	}
	static _isURL(str) {
		return /^https?:\/\/[^\s/$.?#].[^\s]*$/i.test(str)
	}
	static async _fetch(url){
		return fetch(url).then(response => {
			if (!response.ok)
				throw new Error(`Failed to fetch file from ${url}: ${response.statusText}`)
			console.log(`loaded: ${url}`)
			return response.text()
		})
	}
}
We offer end-to-end Web3 development services for startups, enterprises, and blockchain-based platforms. Our expertise includes dApp development, smart contracts, NFT marketplaces, DeFi solutions, and blockchain integration. Based in Seattle, we help businesses adopt decentralized technology with secure, scalable, and future-ready systems. Custom solutions available across Ethereum, Binance Smart Chain, Polygon, and more.
📩 Reach out for a free consultation or project quote today >>>> 
Looking to Launch Your Own Stablecoin? We Can Help!
We are a leading Stablecoin Development Company offering end-to-end solutions to build secure, scalable, and regulation-compliant stablecoins. Whether you're a startup, fintech company, or crypto entrepreneur, we make stablecoin creation simple and reliable.

Our services include:
Fiat or crypto-collateralized stablecoin development
Smart contract creation and auditing
Wallet integration and KYC/AML compliance
Private or public blockchain deployment

Why choose us?
We offer customizable solutions, fast delivery, and ongoing support—perfect for both beginners and experienced blockchain users.Bring stability to the crypto market—start your stablecoin journey today!
  
Contact us now for a free consultation >>> sales@maticz.com 

A1: ID       B1: Name         C1: Department
A2: 1        B2: Aamir        C2: Admin
A3: 2        B3: Priya        C3: HR
A4: 3        B4: John         C4: IT

Sub SearchFilter()
    Dim ws As Worksheet
    Dim searchValue As String
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change sheet name if needed
    searchValue = ws.Range("E3").Value

    ' Clear any previous filter
    On Error Resume Next
    ws.Range("A1").AutoFilter Field:=1
    ws.Range("A1").AutoFilter Field:=2
    ws.Range("A1").AutoFilter Field:=3
    On Error GoTo 0

    ' Apply filter if searchValue is not blank
    If searchValue <> "" Then
        ws.Range("A1:C100").AutoFilter Field:=2, Criteria1:="*" & searchValue & "*"
    Else
        ws.Range("A1:C100").AutoFilter
    End If
End Sub

In Excel, press Alt + F11 to open the VBA Editor.
If the Project Explorer is not visible, press Ctrl + R
Find your sheet name (e.g., "DataSheet"), you might see
Sheet1 (DataSheet)

Paste the below code

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("E3")) Is Nothing Then
        Application.EnableEvents = False
        Call SearchFilter
        Application.EnableEvents = True
    End If
End Sub
kill $(ps -ef | grep "airflow scheduler" | awk '{print $2}')

kill $(ps -ef | grep "airflow worker" | awk '{print $2}')

sudo lsof -i :8080
For startups entering the crypto space, automated trading bots offer a scalable way to operate with fewer resources. Crypto trading bot development helps reduce manual workload and makes trading more consistent. Entrepreneurs can use bots to test strategies, manage risks, and stay active in volatile markets. A crypto trading bot development company can build solutions that work across multiple exchanges with custom logic. This gives startups an edge in both speed and decision-making. Bots are not just a tech upgrade—they're a core part of how lean teams stay competitive. With clear goals, automation becomes an asset from day one.
Looking for a trusted Polygon zkEVM development company? We specialize in building scalable, secure, and high-performance dApps using Polygon’s zkEVM technology. Whether you're launching DeFi, NFT, or enterprise-grade solutions, our experts deliver end-to-end development from smart contracts to full-stack integration. Get EVM compatibility with lower gas fees and faster throughput. Perfect for startups and enterprises aiming to scale on Layer 2. Partner with us for reliable and future-ready Polygon zkEVM development services. Contact now to kickstart your blockchain journey!

Contact Us: +91 9384587998 | sales@maticz.com
Social Media Links: @MaticzTech
<!--%%[  
 
SET @SubscriberKey = AttributeValue("FII_ContactContractRoleRelationship__c:ContactId__r:Id")  
 
SET @Nombre = AttributeValue("FII_ContactContractRoleRelationship__c:ContactId__r:FirstName")
 
SET @Apellido = AttributeValue("FII_ContactContractRoleRelationship__c:ContactId__r:LastName") 


SET @patternNombre = "^(?=.*[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ])[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ' -]+$" 
SET @patternApellido = "^(?=.*[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ])[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ' ., -]+$" 
 
SET @matchNombre = RegExMatch(@Nombre, @patternNombre, 0) 
SET @matchApellido = RegExMatch(@Apellido, @patternApellido, 0) 
 
IF Length(@matchNombre) > 0 THEN 
  SET @NombreSaludo = ProperCase(@Nombre) 
ELSEIF Length(@matchApellido) > 0 THEN 
  SET @NombreSaludo = ProperCase(@Apellido) 
ELSE 
  SET @NombreSaludo = '' 
ENDIF


IF Length(@NombreSaludo) >= 1 THEN 

  SET @Saludo = Concat(" ", @NombreSaludo, ",") 

ELSE 

  SET @Saludo = Concat(",") 

ENDIF 


IF Length(@matchNombre) > 0 AND Length(@matchApellido) > 0 THEN 

  SET @NombreCompleto = Concat(ProperCase(@Nombre), " ", ProperCase(@Apellido)) 

ELSEIF Length(@matchApellido) > 0 THEN 

  SET @NombreCompleto = ProperCase(@Apellido) 

ELSE 

  SET @NombreCompleto = '' 

ENDIF 


SET @SubscriberKey2 = AttributeValue("FII_ContactContractRoleRelationship__c:FII_CCR_LKP_ContactoTitularMKT__r:Id")  
 
SET @Nombre2 = AttributeValue("FII_ContactContractRoleRelationship__c:FII_CCR_LKP_ContactoTitularMKT__r:FirstName")  
 
SET @Apellido2 = AttributeValue("FII_ContactContractRoleRelationship__c:FII_CCR_LKP_ContactoTitularMKT__r:LastName")


SET @patternNombre2 = "^(?=.*[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ])[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ' -]+$" 
SET @patternApellido2 = "^(?=.*[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ])[a-zA-ZñÑáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙ' ., -]+$"

SET @matchNombre2 = RegExMatch(@Nombre2, @patternNombre2, 0) 
SET @matchApellido2 = RegExMatch(@Apellido2, @patternApellido2, 0) 
  

IF Length(@matchNombre2) > 0 AND Length(@matchApellido2) > 0 THEN 

  SET @NombreCompleto2 = Concat(ProperCase(@Nombre2), " ", ProperCase(@Apellido2)) 

ELSEIF Length(@matchApellido2) > 0 THEN 

  SET @NombreCompleto2 = ProperCase(@Apellido2) 
  
ELSEIF Length(@matchNombre2) > 0 THEN 

  SET @NombreCompleto2 = ProperCase(@Nombre2) 

ELSE 

  SET @NombreCompleto2 = '' 

ENDIF 

 
]%% -->
<p>Absolutely loved how well this article was structured—insightful and fresh. I recently came across a piece that beautifully channels Carrie Bradshaw’s essence with her signature fashion. If you’re into chic knitwear inspired by the show, the <a href="https://www.vansonjackets.com/product/and-just-like-that-s03-carrie-bradshaw-blue-knit-cardigan/" rel="dofollow">And Just Like That S03 Carrie Bradshaw Blue Knit Cardigan</a> is a real standout.</p>
Wechseln Sie oben zur Registerkarte "Ansicht" und wählen Sie links als Darstellungsform das "Seitenlayout".
Markieren Sie die gewünschten Zeilen oder Spalten und klicken Sie mit der rechten Maustaste auf deren Buchstaben oder Zahlen.
Wählen Sie anschließend im Kontextmenü die Option "Zeilenhöhe" oder "Spaltenbreite".
Hier können Sie die gewünschte genaue Höhe oder Breite in Zentimetern eingeben. So sparen Sie sich die ständigen Umrechnungen.
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 tx = db.transaction("books", "readonly");
const store = tx.objectStore("books");
const index = store.index("by_author");

const request = index.openCursor(IDBKeyRange.only("Fred"));
request.onsuccess = function() {
  const cursor = request.result;
  if (cursor) {
    // Called for each matching record.
    report(cursor.value.isbn, cursor.value.title, cursor.value.author);
    cursor.continue();
  } else {
    // No more matching records.
    report(null);
  }
};
const tx = db.transaction("books", "readwrite");
const store = tx.objectStore("books");
const request = store.put({title: "Water Buffaloes", author: "Slate", isbn: 987654});
request.onerror = function(event) {
  // The uniqueness constraint of the "by_title" index failed.
  report(request.error);
  // Could call event.preventDefault() to prevent the transaction from aborting.
};
tx.onabort = function() {
  // Otherwise the transaction will automatically abort due the failed request.
  report(tx.error);
};
const request = indexedDB.open("library", 3); // Request version 3.
let db;

request.onupgradeneeded = function(event) {
  const db = request.result;
  if (event.oldVersion < 1) {
    // Version 1 is the first version of the database.
    const store = db.createObjectStore("books", {keyPath: "isbn"});
    const titleIndex = store.createIndex("by_title", "title", {unique: true});
    const authorIndex = store.createIndex("by_author", "author");
  }
  if (event.oldVersion < 2) {
    // Version 2 introduces a new index of books by year.
    const bookStore = request.transaction.objectStore("books");
    const yearIndex = bookStore.createIndex("by_year", "year");
  }
  if (event.oldVersion < 3) {
    // Version 3 introduces a new object store for magazines with two indexes.
    const magazines = db.createObjectStore("magazines");
    const publisherIndex = magazines.createIndex("by_publisher", "publisher");
    const frequencyIndex = magazines.createIndex("by_frequency", "frequency");
  }
};

request.onsuccess = function() {
  db = request.result; // db.version will be 3.
};
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'))
;
star

Thu Aug 07 2025 06:59:04 GMT+0000 (Coordinated Universal Time) https://www.flyproxy.com/

@Flyproxy

star

Thu Aug 07 2025 06:28:47 GMT+0000 (Coordinated Universal Time) https://croxy.com/

@croxymini

star

Thu Aug 07 2025 04:52:37 GMT+0000 (Coordinated Universal Time)

@piyushpar7 #c++

star

Thu Aug 07 2025 04:24:34 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/fruits-into-baskets-iii/?envType=daily-question&envId=2025-08-06

@piyushpar7 #c++

star

Wed Aug 06 2025 13:35:49 GMT+0000 (Coordinated Universal Time)

@jrg_300i #php #laravel

star

Wed Aug 06 2025 09:22:36 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/binance-clone-script

@Seraphina

star

Wed Aug 06 2025 05:42:09 GMT+0000 (Coordinated Universal Time) https://protonvpn.com/support/official-linux-vpn-ubuntu?srsltid

@v1ral_ITS

star

Wed Aug 06 2025 05:42:00 GMT+0000 (Coordinated Universal Time) https://protonvpn.com/support/official-linux-vpn-ubuntu?srsltid

@v1ral_ITS

star

Wed Aug 06 2025 05:41:57 GMT+0000 (Coordinated Universal Time) https://protonvpn.com/support/official-linux-vpn-ubuntu?srsltid

@v1ral_ITS

star

Wed Aug 06 2025 05:41:54 GMT+0000 (Coordinated Universal Time) https://protonvpn.com/support/official-linux-vpn-ubuntu?srsltid

@v1ral_ITS

star

Wed Aug 06 2025 05:41:46 GMT+0000 (Coordinated Universal Time) https://protonvpn.com/support/official-linux-vpn-ubuntu?srsltid

@v1ral_ITS

star

Tue Aug 05 2025 15:15:32 GMT+0000 (Coordinated Universal Time)

@touchSort

star

Tue Aug 05 2025 12:24:46 GMT+0000 (Coordinated Universal Time) https://maticz.com/web3-development-company

@Maeve43 #blockchain #web3

star

Tue Aug 05 2025 12:15:48 GMT+0000 (Coordinated Universal Time) https://maticz.com/stablecoin-development-company

@Maeve43 #blockchain #stablecoin

star

Tue Aug 05 2025 11:05:26 GMT+0000 (Coordinated Universal Time)

@Aamir #vba

star

Tue Aug 05 2025 08:46:19 GMT+0000 (Coordinated Universal Time) https://www.kryptobees.com/blog/coindcx-clone-script

@Franklinclas

star

Tue Aug 05 2025 07:47:14 GMT+0000 (Coordinated Universal Time)

@Saravana_Kumar #bash

star

Tue Aug 05 2025 07:33:20 GMT+0000 (Coordinated Universal Time) https://www.b2bcert.com/soc-1-certification-in-texas/

@b2bcert #soc1 consultants in texas

star

Tue Aug 05 2025 07:32:23 GMT+0000 (Coordinated Universal Time) https://www.b2bcert.com/iso-27001-certification-in-texas/

@b2bcert #iso27001 consultants in texas

star

Mon Aug 04 2025 11:53:32 GMT+0000 (Coordinated Universal Time) https://maticz.com/polygon-zkevm-development

@Maeve43 #polygon #zkevm #blockchain

star

Mon Aug 04 2025 11:26:25 GMT+0000 (Coordinated Universal Time)

@andresrivera #ampscript

star

Mon Aug 04 2025 10:05:26 GMT+0000 (Coordinated Universal Time) https://www.vansonjackets.com/product/and-just-like-that-s03-carrie-bradshaw-blue-knit-cardigan/

@mikestallion #html

star

Sun Aug 03 2025 18:38:37 GMT+0000 (Coordinated Universal Time) https://praxistipps.chip.de/excel-zellen-von-pixel-in-cm-umrechnen_29771

@2late #excel

star

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

@Asneedarazali #javascript

star

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

@Asneedarazali #javascript

star

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

@Asneedarazali #javascript

star

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

@Asneedarazali #javascript

star

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

@Asneedarazali #javascript

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

Save snippets that work with our extensions

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