Snippets Collections
sudo rm -rf ~/Library/Developer/CommandLineTools/
sudo rm -rf ~/Library/Developer/Xcode/
sudo rm -rf ~/Library/Application Support/Xcode
sudo rm -rf ~/Library/Caches/com.apple.dt.Xcode
sudo rm -rf ~/Library/Preferences/com.apple.dt.Xcode.plist
sudo rm -rf /Library/Preferences/com.apple.dt.Xcode.plist
sudo rm -rf /Applications/Xcode.app
sudo /Developer/Library/uninstall-devtools --mode=all
\author{
  \IEEEauthorblockN{Hrittik Raj Barua}
  \IEEEauthorblockA{\textit{Department of Electrical and Electronic Engineering} \\
    \textit{University of Science and Technology Chittagong}\\
    Chittagong, Bangladesh \\
    hrittik.rb2000@yahoo.com}
  \and
  \IEEEauthorblockN{Mohammad Mainul Hasan}
  \IEEEauthorblockA{\textit{Department of Electrical and Electronic Engineering} \\
    \textit{University of Science and Technology Chittagong}\\
    Chittagong, Bangladesh \\
    mainulhasan@ustc.ac.bd}
  \and
  \IEEEauthorblockN{Imtiaz Akber Chowdhury}
  \IEEEauthorblockA{\textit{Department of Electrical and Electronic Engineering} \\
    \textit{University of Science and Technology Chittagong}\\
    Chittagong, Bangladesh \\
    eee.imtiazakber@ustc.ac.bd}
  %\linebreakand % <------------- \and with a line-break
  \and
  \IEEEauthorblockN{Arpan Dey}
  \IEEEauthorblockA{\textit{Department of Electrical and Electronic Engineering} \\
    \textit{University of Science and Technology Chittagong}\\
    Chittagong, Bangladesh \\
    arpande.official@yahoo.com}
  \and
  \IEEEauthorblockN{Tridib Banik}
  \IEEEauthorblockA{\textit{Department of Computer Science \& Engineering} \\
    \textit{Assam Downtown University}\\
    Assam, India \\
    Tridibbanik34@gmail.com}
  \and
  \IEEEauthorblockN{Mohammad Rakibul Hoque Khan}
  \IEEEauthorblockA{\textit{Department of Electronics \& Telecommunications Engineering} \\
    \textit{International Islamic University Chittagong}\\
    Chittagong, Bangladesh \\
    rakibulhoquekhan@gmail.com}
}
\documentclass[conference]{IEEEtran}

\title{A title}

\makeatletter
\newcommand{\linebreakand}{%
  \end{@IEEEauthorhalign}
  \hfill\mbox{}\par
  \mbox{}\hfill\begin{@IEEEauthorhalign}
}
\makeatother

\author{
  \IEEEauthorblockN{1\textsuperscript{st} Given Name Surname}
  \IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\
    \textit{name of organization (of Aff.)}\\
    City, Country \\
    email address}
  \and
  \IEEEauthorblockN{2\textsuperscript{nd} Given Name Surname}
  \IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\
    \textit{name of organization (of Aff.)}\\
    City, Country \\
    email address}
  \and
  \IEEEauthorblockN{3\textsuperscript{rd} Given Name Surname}
  \IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\
    \textit{name of organization (of Aff.)}\\
    City, Country \\
    email address}
  \linebreakand % <------------- \and with a line-break
  \IEEEauthorblockN{4\textsuperscript{th} Given Name Surname}
  \IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\
    \textit{name of organization (of Aff.)}\\
    City, Country \\
    email address}
  \and
  \IEEEauthorblockN{5\textsuperscript{th} Given Name Surname}
  \IEEEauthorblockA{\textit{dept. name of organization (of Aff.)} \\
    \textit{name of organization (of Aff.)}\\
    City, Country \\
    email address}
}

\begin{document}

\maketitle

\end{document}
LINK
//https://help.zoho.com/portal/en/community/topic/get-a-list-of-date-in-zoho-analytics-database-query

For example,
 2009-01-01 
 2009-01-02 
 2009-01-03
 2009-01-04 
 2009-01-05
 2009-01-06
 2009-01-07
 2009-01-08 
 2009-01-09
 2009-01-10
 2009-01-11
 2009-01-12
 2009-01-13


Step1: Create 3 tables as below.
* Year - Add entries for year as a column (Eg 2009,2010,,,,2020) as number column
* Month  Add entries of 12 months (01,02,03....12) as plain text column
* Day -  Add entries of 31 dayss (01,02,03....31) as plain text column  

Step 2: Create a Query Table with the below query.

SELECT date(str_to_date(concat("Year"."Year", '-', "Month"."Month", '-', "Day"."Day"), '%Y-%m-%d')) as "Date"
FROM "Year",
"Month",
"Day"
WHERE (("Year" % 400 = 0
OR ("Year" % 100 != 0
AND "Year" % 4 = 0))
AND date_format(date(str_to_date(concat("Year"."Year", '-', "Month"."Month", '-', "Day"."Day"), '%Y-%m-%d')), '%m%d') not in ( '0230' , '0231' , '0431' , '0631' , '0931' , '1131' ))
OR (("Year" % 4 != 0
OR ("Year" % 100 = 0
AND "Year" % 400 != 0))
AND date_format(date(str_to_date(concat("Year"."Year", '-', "Month"."Month", '-', "Day"."Day"), '%Y-%m-%d')), '%m%d') not in ( '0229' , '0230' , '0231' , '0431' , '0631' , '0931' , '1131' ))


{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":x-connect: Boost Days: What's on in Melbourne this week! :x-connect:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday! \n\n Please see below for what's on this week as there is a change to the Boost Programme. "
			}
		},
		{
			"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: Classic Slices \n\n :coffee: *Weekly Café Special*: Butterscotch Latte"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Monday, 31st June :calendar-date-31:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": " :suit-up: *Wear your suit to work Day* - In Honour of the long-standing tradition in Australia :australia: Today we encourage you to come dressed in your sharpest suit or corporate attire. The nod that the old- school accountant and bookeeping dress policy our partners would have worn back in the day! \n\n *10.30am*: Photo time in the Breakout Space followed by morning tea :croissant:  "
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 2nd July :calendar-date-2:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":breakfast: *Breakfast*: from *8:30am - 10:30am* in the Level 3 Breakout Space. "
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 3rd July :calendar-date-3: \n ",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "plain_text",
				"text": " :Lunch: 12.00pm - Greek themed Lunch in the breakout Space on L-3. Menu in the :thread: \n :HANDS: 12.30pm - Please join us for the Australia All Hands screening in the breakout space on Level 3. ",
				"emoji": true
			}
		},
		{
			"type": "divider"
		}
	]
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Xero Boost Days! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Canberra! Please see below for what's on this week! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-2: Wednesday, 2nd July",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:Lunch: *Lunch*: Provided in our suite from *12pm*."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/u/0?cid=Y19jYzU3YWJkZTE4ZTE0YzVlYTYxMGU4OThjZjRhYWQ0MTNhYmIzMDBjZjBkMzVlNDg0M2M5NDQ4NDk3NDAyYjkyQGdyb3VwLmNhbGVuZGFyLmdvb2dsZS5jb20|*Canberra Social Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " :x-connect: What's On in Brisbane! :x-connect:  ",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Good morning Brisbane! Please see below for what's on this week."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-30: Monday, 30th June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café Partnership: Enjoy free coffee and café-style beverages from our partner, *Edward*. \n\n :lunch: *Lunch*: from *12pm* in the kitchen."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-2: Wednesday, 2nd June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":coffee: *Café Partnership*: Café Partnership: Enjoy coffee and café-style beverages from our partner, *Edward*. \n\n :late-cake: *Morning Tea*: from *10am* in the kitchen."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/u/0?cid=Y19uY2M4cDN1NDRsdTdhczE0MDhvYjZhNnRjb0Bncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Brisbane Social Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
/** 
 * log("sample logging statement") --> can be used to print any data in the browser console.
 * ZDK module can be used for customising the UI and other functionalities.
 * return false to prevent <SAVE> action
**/
var account_name = ZDK.Page.getField('Account_Name').getValue();
console.log("Account name value: ", account_name);
var contactnamefield= ZDK.Page.getField("Contact_Name").getValue();
console.log("Value of Contact name Field is ", contactnamefield);

var Show_Number_of_Unit=ZDK.Page.getField("Show_Number_of_Unit");
console.log("Show_Number_of_Unit = ", Show_Number_of_Unit);

var Show_Number_of_Unit_Vaule=ZDK.Page.getField("Show_Number_of_Unit").getValue();
console.log("Show_Number_of_Unit_value = ", Show_Number_of_Unit_Vaule);

if (account_name != null)
{
    console.log("Account Name is not Equal to Null");
var accountnameid = account_name['id'];
console.log("account name id: ", accountnameid);

var related_records = ZDK.Apps.CRM.Accounts.fetchRelatedRecords(accountnameid, "Contacts");
for (var i = 0; i < related_records.length; i++)
{
    console.log("related_records [i]", related_records[i]);
    //////////////////////
    var contact_id = related_records[i].id;
    var contact_tag = related_records[i];
    console.log("contact_id new",contact_id);
    console.log("Tags New", contact_tag.Tag);
    var tags_info = contact_tag.Tag;
    console.log("tag=========", tags_info);
    var Tags = [ 
  {name: "Bob", id: "32", occupation: "developer"}, 
  {name: "ERPHUB POC", id: "17", occupation: "delinquent"}, 
  {name: "Brad", id: "40", occupation: "yes"} 
]

    let matchedPOC = Tags.find(function (ele) {
    console.log("contact_id new poc",contact_id);
    return ele.name == "ERPHUB POC";
   
});
    console.log("matched: ", matchedPOC);

  
    // for (var i = 0; i < tags_info.length; i++)
    // {
    //     console.log("tags_info",contact_tag.Tag);

    // }


    


    ///////////////////////////
    console.log("related_records[i].Primary_Contact", related_records[i].Primary_Contact);
    if(related_records[i].Primary_Contact==true)
    {
        true_related_record = related_records[i];
        console.log("true_related_record",true_related_record);
    }
    else
    {
        true_related_record=related_records[0];
        console.log("true_related_record [0]",true_related_record);
        
    }
}

console.log("true_related_record Email",true_related_record.Email);
console.log("true_related_record Full_Name",true_related_record.Full_Name);
console.log("true_related_record id",true_related_record.id);

var emailfield = ZDK.Page.getField('Email');
console.log("email field value: ",emailfield);
console.log("set email address");
//emailfield.setValue(true_related_record.Email);
    var contactnamefield = ZDK.Page.getField("Contact_Name");








//contactnamefield.setValue({ "id": true_related_record.id, "name": true_related_record.Full_Name });
console.log("set contact name");
//console.log("id is :",true_related_record.id,"name is ",true_related_record.Full_Name);

var accounts = ZDK.Apps.CRM.Accounts.fetchById(accountnameid);
console.log("accounts: ", accounts);

var numofemployeesfield = ZDK.Page.getField("Number_of_Employees");
console.log("num of employees field: ",numofemployeesfield);
var foundingyearfield = ZDK.Page.getField("Founding_Year");

var lead_source = ZDK.Page.getField("Lead_Source");
lead_source.setValue(accounts.Lead_Source);

var websitee = ZDK.Page.getField("Website");
websitee.setValue(accounts.Website);

console.log("foundingyearfield", foundingyearfield);
if (accounts.Founding_Year == null)
{
    console.log("if condition Founding_Year");
    foundingyearfield.setValue(0);
}
else
{
    console.log("else condition Founding_Year");
    foundingyearfield.setValue(accounts.Founding_Year);
}

if (accounts.Number_of_Employees == null)
{
    console.log("if condition Number_of_Employees",accounts.Number_of_Employees);
    numofemployeesfield.setValue("-None-");
}
else
{
    console.log("else condition Number_of_Employees",accounts.Number_of_Employees);
    numofemployeesfield.setValue(accounts.Number_of_Employees);
}

var client_typefield = ZDK.Page.getField("Client_Type");
console.log("client_typefield = ", client_typefield);
if (accounts.Client_Type==null)
{
    console.log("if condition client_typefield is null",accounts.Client_Type);
    client_typefield.setValue("-None-");
}
else
{
    console.log("else condition in Client_type",accounts.Client_Type);
    client_typefield.setValue(accounts.Client_Type);
}



var industryfield = ZDK.Page.getField('Industry');
console.log("industryfield", industryfield);
if (accounts.Industry == null)
{
    console.log("if condition Industry");
    industryfield.setValue("-None-");
}
else
{
    console.log("else condition Industry");
    industryfield.setValue(accounts.Industry);
}


var serviceintrestedfield= ZDK.Page.getField("Services_Interested").getValue();
console.log("serviceintrestedfield",serviceintrestedfield);

    if (serviceintrestedfield=="Property Management Solution")
    {
        console.log("True");
        Show_Number_of_Unit.setValue(true);
    }
    else {
        console.log("False");
        Show_Number_of_Unit.setValue(false);
}
var client_tpye_value=ZDK.Page.getField("Client_Type").getValue();
console.log("client_tpye_value",client_tpye_value);

}
else
{
    console.log("Account Name is Equal to Null");
    var emailfield = ZDK.Page.getField('Email');
    emailfield.setValue(null);

    var contactnamefield= ZDK.Page.getField("Contact_Name");
    contactnamefield.setValue(null);

    var numofemployeesfield = ZDK.Page.getField("Number_of_Employees");
    numofemployeesfield.setValue("-None-");

    var foundingyearfield = ZDK.Page.getField("Founding_Year");
    foundingyearfield.setValue(null);




    var client_typefield = ZDK.Page.getField("Client_Type");
    client_typefield.setValue("-None-");
    
    var industryfield = ZDK.Page.getField('Industry');
    industryfield.setValue("-None-");
}
Route::get('/listings', function () {
    return view('listings',[ 'listings' => Listing::all()]);
});
from sqlalchemy import Column, Integer, Float, String, DateTime, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

Base = declarative_base()

class SensorData(Base):
    __tablename__ = 'sensor_data'

    id = Column(Integer, primary_key=True)
    timestamp = Column(DateTime, nullable=False)
    sensor_id = Column(String, nullable=False)
    rainfall_mm = Column(Float, nullable=False)
    water_level_cm = Column(Float, nullable=False)
    flow_rate_lps = Column(Float, nullable=False)

# --- ADD THIS ENTIRE NEW CLASS ---
class User(UserMixin, Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(64), unique=True, nullable=False)
    # email = Column(String(120), unique=True, nullable=False) # You can add email later if you want
    password_hash = Column(String(128), nullable=False)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f'<User {self.username}>'
# --- END OF NEW CLASS ---

    def __repr__(self):
        return f"<SensorData(sensor_id={self.sensor_id}, rainfall_mm={self.rainfall_mm})>"

# Database setup (SQLite for now)
engine = create_engine("sqlite:///suds.db")
Session = sessionmaker(bind=engine)
session = Session()
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Line } from 'react-chartjs-2';
import 'chart.js/auto';

const SensorGraph = () => {
  const [chartData, setChartData] = useState(null);
  const [allData, setAllData] = useState([]);
  const [selectedSensor, setSelectedSensor] = useState('All');
  const [showTimestamps, setShowTimestamps] = useState(true);
  const [showForecast, setShowForecast] = useState(false);
  const [forecastData, setForecastData] = useState([]);

  const [avgRainfall, setAvgRainfall] = useState(0);
  const [currentWaterLevel, setCurrentWaterLevel] = useState(0);
  const [last24hFlow, setLast24hFlow] = useState(0);

  const variable = 'rainfall_mm'; // forecasting variable

  const updateChart = (data, sensorFilter, forecastOverlay = []) => {
    const filteredData = sensorFilter === 'All'
      ? data
      : data.filter(entry => entry.sensor_id === sensorFilter);

    const timestamps = filteredData.map(entry => entry.timestamp);
    const rainfall = filteredData.map(entry => entry.rainfall_mm);
    const waterLevel = filteredData.map(entry => entry.water_level_cm);
    const flowRate = filteredData.map(entry => entry.flow_rate_lps);

    // Stats
    const avgRain = (rainfall.reduce((a, b) => a + b, 0) / rainfall.length || 0).toFixed(2);
    const currWater = waterLevel[waterLevel.length - 1] || 0;

    const now = new Date();
    const past24h = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    const flowLast24h = filteredData.filter(entry => new Date(entry.timestamp) > past24h)
      .map(e => e.flow_rate_lps);
    const sumFlow = (flowLast24h.reduce((a, b) => a + b, 0) / flowLast24h.length || 0).toFixed(2);

    setAvgRainfall(avgRain);
    setCurrentWaterLevel(currWater.toFixed(2));
    setLast24hFlow(sumFlow);

    const datasets = [
      {
        label: 'Rainfall',
        data: rainfall,
        borderColor: 'blue',
        backgroundColor: 'rgba(0, 0, 255, 0.1)',
        tension: 0.4,
        pointRadius: 3,
        fill: true,
        unit: ' mm'
      },
      {
        label: 'Water Level',
        data: waterLevel,
        borderColor: 'green',
        backgroundColor: 'rgba(0, 128, 0, 0.1)',
        tension: 0.4,
        pointRadius: 3,
        fill: true,
        unit: ' cm'
      },
      {
        label: 'Flow Rate',
        data: flowRate,
        borderColor: 'orange',
        backgroundColor: 'rgba(255, 165, 0, 0.1)',
        tension: 0.4,
        pointRadius: 3,
        fill: true,
        unit: ' lps'
      }
    ];

    if (forecastOverlay.length > 0) {
      datasets.push({
        label: 'Forecasted Rainfall',
        data: forecastOverlay.map(d => d.value),
        borderColor: 'purple',
        borderDash: [6, 4],
        backgroundColor: 'rgba(128, 0, 128, 0.1)',
        tension: 0.4,
        pointRadius: 2,
        fill: false,
        unit: ' mm'
      });

      const combinedLabels = [...timestamps, ...forecastOverlay.map(d => d.timestamp)];
      setChartData({ labels: combinedLabels, datasets });
    } else {
      setChartData({ labels: timestamps, datasets });
    }
  };

  const fetchForecast = async () => {
    try {
      const res = await axios.get(`http://localhost:5000/api/forecast?sensor_id=${selectedSensor}&variable=${variable}`);
      setForecastData(res.data.forecast);
      updateChart(allData, selectedSensor, res.data.forecast);
    } catch (err) {
      console.error("Forecast error:", err);
    }
  };

  useEffect(() => {
    axios.get('http://localhost:5000/get-sensor-data')
      .then((res) => setAllData(res.data))
      .catch(err => console.error("Error fetching sensor data:", err));
  }, []);

  useEffect(() => {
    if (allData.length > 0) {
      if (showForecast) {
        fetchForecast();
      } else {
        updateChart(allData, selectedSensor);
      }
    }
  }, [allData, selectedSensor, showForecast]);

  const chartOptions = {
    responsive: true,
    plugins: {
      tooltip: {
        callbacks: {
          label: function (context) {
            const label = context.dataset.label || '';
            const value = context.raw;
            const unit = context.dataset.unit || '';
            return `${label}: ${value}${unit}`;
          }
        }
      },
      legend: {
        position: 'top',
        labels: { font: { size: 14 } }
      },
      title: {
        display: true,
        text: 'SuDS Performance Over Time',
        font: { size: 20 }
      }
    },
    scales: {
      x: {
        ticks: {
          display: showTimestamps,
          maxRotation: 45,
          minRotation: 20,
          font: { size: 12 }
        }
      },
      y: {
        beginAtZero: true,
        ticks: { font: { size: 12 } }
      }
    }
  };

  return (
    <div style={{
      backgroundColor: '#f4f7fa',
      minHeight: '100vh',
      padding: '40px',
      fontFamily: 'Segoe UI, sans-serif'
    }}>
      <div style={{
        backgroundColor: '#ffffff',
        padding: '30px',
        borderRadius: '12px',
        boxShadow: '0 2px 12px rgba(0, 0, 0, 0.1)',
        maxWidth: '1000px',
        margin: '0 auto'
      }}>
        <h1 style={{
          fontSize: '24px',
          marginBottom: '20px',
          textAlign: 'center',
          color: '#333'
        }}>
          SuDS Sensor Data Dashboard
        </h1>

        {/* Controls */}
        <div style={{ textAlign: 'center', marginBottom: '10px' }}>
          <label style={{ fontWeight: 'bold', marginRight: 10 }}>Sensor ID:</label>
          <select
            value={selectedSensor}
            onChange={(e) => {
              setSelectedSensor(e.target.value);
              setForecastData([]);
            }}
            style={{
              padding: '6px 12px',
              fontSize: '14px',
              borderRadius: '6px',
              border: '1px solid #ccc',
              marginRight: '10px'
            }}
          >
            <option value="All">All Sensors</option>
            {[...new Set(allData.map(d => d.sensor_id))].map((id, idx) => (
              <option key={idx} value={id}>{id}</option>
            ))}
          </select>

          <button onClick={() => setShowTimestamps(prev => !prev)}
            style={{
              padding: '6px 12px',
              fontSize: '14px',
              borderRadius: '6px',
              backgroundColor: '#007bff',
              color: '#fff',
              marginRight: '10px',
              border: 'none'
            }}>
            {showTimestamps ? 'Hide Timestamps' : 'Show Timestamps'}
          </button>

          <button onClick={() => setShowForecast(prev => !prev)}
            style={{
              padding: '6px 12px',
              fontSize: '14px',
              borderRadius: '6px',
              backgroundColor: showForecast ? '#6c757d' : '#28a745',
              color: '#fff',
              border: 'none'
            }}>
            {showForecast ? 'Hide Forecast' : 'Show Forecast'}
          </button>
        </div>

        {/* Summary Stats */}
        <div style={{ display: 'flex', justifyContent: 'space-around', marginBottom: '20px' }}>
          <div style={{ background: '#e3f2fd', padding: '10px 20px', borderRadius: '8px' }}>
            <strong>Avg Rainfall:</strong> {avgRainfall} mm
          </div>
          <div style={{ background: '#e8f5e9', padding: '10px 20px', borderRadius: '8px' }}>
            <strong>Current Water Level:</strong> {currentWaterLevel} cm
          </div>
          <div style={{ background: '#fff8e1', padding: '10px 20px', borderRadius: '8px' }}>
            <strong>Last 24h Flow:</strong> {last24hFlow} lps
          </div>
        </div>

        {/* Chart */}
        {chartData ? (
          <Line data={chartData} options={chartOptions} />
        ) : (
          <p style={{ textAlign: 'center', color: '#888' }}>Loading chart...</p>
        )}
      </div>
    </div>
  );
};

export default SensorGraph;
MetaTrader Exchange Clone is a 100% replica of MetaTrader that comes with MT5 Exchange Clone Website Script and Clone App that replicates the existing features of MetaTrader with additional trading features plugins to launch a hassle-free trading and exchange platform.

Core Features of MetaTrader Exchange Clone  Script
Dual-Market Integration
AI-Powered Trading Bots
Real-Time Charts & Indicators
Secure Wallet System
Broker/Admin Dashboard
Fully Customizable UI/UX 
Liquidity Provider Integration
Mobile & Web Compatibility
And More

Bizvertex’s MetaTrader Exchange Clone is a multi-tested ready-made script to kick-start the famous forex and crypto exchange like MetaTrader 5.

Free demo & consultation

https://www.bizvertex.com/metatrader-clone-script
Call/WhatsApp - +918807211121
Telegram - https://t.me/bizvertex
import Tender from "../models/tenderSchema.js";
import Quotation from "../models/quotationSchema.js";
import { generateSignedUrl } from "../utils/minioClient.js";
import mongoose from "mongoose";
import User from "../models/userSchema.js"; // Replace with your actual user model path
import { sendMail } from "../utils/sendMail.js"; // You must have this utility created
import userModel from "../models/userSchema.js";
// ✅ Create Tender with bidding window + delivery window
import moment from "moment-timezone";

export const createTender = async (req, res) => {
  try {
    const {
      dispatchLocation,
      address,
      pincode,
      materials,
      transporters,
      remarks,
      closeDate,
      deliveryWindow,
      biddingStart,
      biddingEnd,
      totalWeight,
      totalQuantity,
      projectName,
      projectCode,
      purchaseOrder,
      projectRemark,
      maxBidAmount,
      maxBidUnit,
    } = req.body;

    console.log("Received Bidding Start (Local):", biddingStart);
    console.log("Received Bidding End (Local):", biddingEnd);

    // 🔐 Basic validations
    if (!projectName || !projectCode || !purchaseOrder) {
      return res.status(400).json({
        success: false,
        message: "Project name, code and PO are required",
      });
    }

    if (!biddingStart || !biddingEnd) {
      return res.status(400).json({
        success: false,
        message: "Bidding start and end time are required",
      });
    }

    if (
      maxBidAmount === undefined ||
      isNaN(maxBidAmount) ||
      Number(maxBidAmount) < 0) {
      return res.status(400).json({
        success: false,
        message: "Valid max bid amount is required and must be non-negative",
      });
    }

    if (!maxBidUnit || !["Per MT", "Per Tender"].includes(maxBidUnit)) {
      return res.status(400).json({
        success: false,
        message: "Valid max bid unit is required (Per MT or Per Tender)",
      });
    }

    if (!deliveryWindow?.from || !deliveryWindow?.to) {
      return res.status(400).json({
        success: false,
        message: "Delivery window (from and to dates) is required",
      });
    }

    if (!materials || !Array.isArray(materials) || materials.length === 0) {
      return res.status(400).json({
        success: false,
        message: "At least one material entry is required",
      });
    }

    // 🌐 Convert all date/time inputs from 'Asia/Kolkata' to UTC
    const timezone = "Asia/Kolkata";
    const utcBiddingStart = moment.tz(biddingStart, timezone).utc().toDate();
    const utcBiddingEnd = moment.tz(biddingEnd, timezone).utc().toDate();
    const utcDeliveryFrom = moment
      .tz(deliveryWindow.from, timezone)
      .utc()
      .toDate();
    const utcDeliveryTo = moment.tz(deliveryWindow.to, timezone).utc().toDate();
    let utcCloseDate = null;
    if (closeDate) {
      const [year, month, day] = closeDate.split("-").map(Number);
      utcCloseDate = new Date(Date.UTC(year, month - 1, day));
    }
    const normalizedMaterials = materials.map((mat) => ({
      material: mat.material,
      subMaterial: mat.subMaterial || "",
      weight: mat.weight,
      quantity: mat.quantity,
    }));

    const tender = new Tender({
      createdBy: req.user.id,
      dispatchLocation,
      address,
      pincode,
      materials: normalizedMaterials,
      transporters,
      remarks: remarks || "",
      closeDate: utcCloseDate,
      biddingStart: utcBiddingStart,
      biddingEnd: utcBiddingEnd,
      deliveryWindow: {
        from: utcDeliveryFrom,
        to: utcDeliveryTo,
      },
      totalWeight,
      totalQuantity,
      projectName,
      projectCode,
      purchaseOrder,
      projectRemark: projectRemark || "",
      maxBidAmount,
      maxBidUnit,
    });

    await tender.save();

    // ✅ Respond Immediately
    res.status(201).json({ success: true, data: tender });


    // 📨 Fire-and-forget Email Notification to Transporters
    (async () => {
      try {
        // 📨 Notify transporters
        const transporterUsers = await User.find({
          _id: { $in: transporters.map((id) => new mongoose.Types.ObjectId(id)) },
        });

        const transporterEmails = transporterUsers.map((user) => user.email);
        const subject = "📦 New Tender Invitation - RR ISPAT";

        // 🌟 Professional Multilingual Email Body
        const websiteUrl = "https://logiyatra.rrispat.in/signin";
        const supportEmail = "techsupport@rrispat.com";
        const backgroundImageUrl =
          "https://images.unsplash.com/photo-1526403227912-7d60d6cc6b4a?ixlib=rb-4.0.3&auto=format&fit=crop&w=1950&q=80";

        const htmlBody = `
      <div style="margin:0; padding:0; background-image: url('${backgroundImageUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat; background-color: #f4f4f4;">
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width:620px; background: #ffffff; margin-top:30px; margin-bottom:30px; border-radius:10px; overflow:hidden; box-shadow: 0 6px 20px rgba(0,0,0,0.15);">

          <tr>
            <td align="center" style="background:rgb(12, 25, 206); background-size: 600% 600%; animation: gradientBG 8s ease infinite; padding: 20px;">
             <div style="font-family: Arial, sans-serif; font-size: 28px; font-weight: bold;">
                 <span style="color: #e74c3c;">RR</span> <span style="color: #ffffff;">ISPAT</span>
             </div>
                <div style="font-family: Arial, sans-serif; font-size: 14px; margin-top: 5px; color:#ffffff;">
                  A Unit of Godawari Power and Ispat Limited
              </div>
            </td>
          </tr>

          <tr>
            <td style="padding: 40px 30px 30px 30px; font-family: Arial, sans-serif; color: #333; font-size: 16px;">

              <h2 style="color:#2E86C1; text-align:center;">📢 New Tender Invitation</h2>

              <p>Dear Transporter,<br/><small>(प्रिय ट्रांसपोर्टर)</small></p>

              <p>We are excited to invite you to participate in a new tender from <strong>RR ISPAT</strong>.<br/><small>(RR ISPAT द्वारा एक नए टेंडर में भाग लेने के लिए आपका स्वागत है।)</small></p>

              <table cellpadding="5" cellspacing="0" width="100%" style="margin: 25px 0;">
                <tr>
                  <td style="font-weight:bold; width:40%;">📍 Dispatch Location:</td>
                  <td>
                    ${dispatchLocation}
                    <br/>
                    <small style="color:#555;">(डिस्पैच स्थान: ${dispatchLocation})</small>
                  </td>
                </tr>
                <tr>
                  <td style="font-weight:bold;">🚚 Delivery Window:</td>
                  <td>
                    ${moment(utcDeliveryFrom)
            .tz(timezone)
            .format("DD MMM YYYY")} to ${moment(utcDeliveryTo)
              .tz(timezone)
              .format("DD MMM YYYY")}
                    <br/>
                    <small style="color:#555;">(वितरण अवधि: ${moment(
                utcDeliveryFrom
              )
            .tz(timezone)
            .format("DD MMM YYYY")} से ${moment(utcDeliveryTo)
              .tz(timezone)
              .format("DD MMM YYYY")})</small>
                  </td>
                </tr>
                <tr>
                  <td style="font-weight:bold;">🕒 Bidding Starts:</td>
                  <td>
                    ${moment(utcBiddingStart)
            .tz(timezone)
            .format("DD MMM YYYY, hh:mm A")}
                    <br/>
                    <small style="color:#555;">(बिडिंग प्रारंभ: ${moment(
              utcBiddingStart
            )
            .tz(timezone)
            .format("DD MMM YYYY, hh:mm A")})</small>
                  </td>
                </tr>
                <tr>
                  <td style="font-weight:bold;">⏳ Bidding Ends:</td>
                  <td>
                    ${moment(utcBiddingEnd)
            .tz(timezone)
            .format("DD MMM YYYY, hh:mm A")}
                    <br/>
                    <small style="color:#555;">(बिडिंग समाप्ति: ${moment(
              utcBiddingEnd
            )
            .tz(timezone)
            .format("DD MMM YYYY, hh:mm A")})</small>
                  </td>
                </tr>
              </table>

              <div style="text-align:center; margin:40px 0;">
                <a href="${websiteUrl}" target="_blank" style="background:rgb(12, 25, 206); color:#fff; padding:14px 28px; font-size:16px; border-radius:6px; text-decoration:none; display:inline-block; box-shadow:0 4px 8px rgba(0,0,0,0.2);">
                  🔗 Login to Dashboard<br/><small style="font-size:12px;">(डैशबोर्ड में लॉगिन करें)</small>
                </a>
              </div>

              <p style="text-align:center; margin-top:30px;">
                Need help? Email us at <a href="mailto:${supportEmail}" style="color:#2E86C1;">${supportEmail}</a><br/>
                <small>(सहायता चाहिए? हमें ईमेल करें: ${supportEmail})</small>
              </p>

            <p style="margin-top:50px; font-family: Arial, sans-serif; font-size: 16px; color: #333; text-align: center;">
               Thanks & Regards,<br>
               <span style="font-weight:bold; font-size:18px;">RR ISPAT</span><br>
               <small style="font-size: 13px; ">- A Unit of Godawari Power and Ispat Limited</small>
                </p>
      
            </td>
          </tr>

          <tr>
            <td style="background-color: #f1f1f1; text-align: center; padding: 20px; font-size: 12px; color: #777;">
              Growing Stronger Together | <a href="${websiteUrl}" style="color: #2E86C1; text-decoration: none;">www.logiyatra.rrispat.in</a><br/>
            </td>
          </tr>

        </table>

        <style>
          @keyframes gradientBG {
            0% {background-position: 0% 50%;}
            50% {background-position: 100% 50%;}
            100% {background-position: 0% 50%;}
          }
        </style>
      </div>`;

        for (const email of transporterEmails) {
          await sendMail({ to: email, subject, html: htmlBody });
        }
      } catch (emailErr) {
        console.error("Email sending failed:", emailErr.message);
      }
    })();
  } catch (error) {
    console.error("Tender creation failed:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

// ✅ 2. Finalize Tender

export const finalizeTender = async (req, res) => {
  try {
    const { quotationId, finalPrice } = req.body;
    console.log(finalPrice);

    // 🔎 Find tender
    const tender = await Tender.findById(req.params.id);
    if (!tender) {
      return res
        .status(404)
        .json({ success: false, message: "Tender not found" });
    }

    if (tender.status === "finalized" || tender.selectedQuotation) {
      return res.status(400).json({
        success: false,
        message: "Tender has already been finalized and cannot be changed.",
      });
    }

    if (tender.createdBy.toString() !== req.user.id) {
      return res.status(403).json({ success: false, message: "Unauthorized" });
    }

    // 🔎 Find quotation
    const quotation = await Quotation.findOne({
      _id: quotationId,
      tender: tender._id,
    });
    if (!quotation) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid quotation" });
    }

    // 🔎 Find transport user
    const transportUser = await userModel.findById(quotation.transportUser);
    if (!transportUser) {
      return res
        .status(400)
        .json({ success: false, message: "Transport user not found" });
    }

    // ✅ Update tender with finalization
    tender.selectedQuotation = quotation._id;
    tender.finalTransporter = quotation.transportUser;
    tender.finalPrice = finalPrice;
    tender.status = "finalized";
    await tender.save();

    // ✅ Email Notification to Transport User
    try {
      await sendMail({
        to: transportUser.email,
        subject:
          "🎉 Congratulations! Your Quotation Has Been Accepted - RR ISPAT",
        html: `
          <div style="margin:0; padding:0; background-color:#f4f4f4;">
            <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width:620px; background:#ffffff; margin-top:30px; margin-bottom:30px; border-radius:10px; overflow:hidden; box-shadow: 0 6px 20px rgba(0,0,0,0.15);">
              
              <tr>
                <td align="center" style="background: #ffffff; padding: 30px;">
                  <div style="font-family: Arial, sans-serif; font-size: 28px; font-weight: bold;">
                    <span style="color: #e74c3c;">RR</span> <span style="color: #000;">ISPAT</span>
                  </div>
                  <div style="font-family: Arial, sans-serif; font-size: 13px; margin-top: 5px; color: #777;">
                    A Unit of Godawari Power and Ispat Limited
                  </div>
                </td>
              </tr>

              <tr>
                <td style="padding: 40px 30px; font-family: Arial, sans-serif; color: #333; font-size: 16px;">

                  <p>Hello <strong>${transportUser.name}</strong>,</p>

                  <p style="margin-top:20px;">
                    🎉 <strong>Congratulations!</strong> Your quotation has been <span style="color: #2E86C1;">ACCEPTED</span> for the following journey:
                  </p>

                  <table cellpadding="5" cellspacing="0" width="100%" style="margin: 20px 0;">
                    <tr>
                      <td style="font-weight:bold;">📍 Dispatch Location:</td>
                      <td>${tender.dispatchLocation}</td>
                    </tr>
                    <tr>
                      <td style="font-weight:bold;">🚚 Delivery Window:</td>
                      <td>${moment(tender.deliveryWindow.from)
            .tz("Asia/Kolkata")
            .format("DD MMM YYYY")} to ${moment(
              tender.deliveryWindow.to
            )
              .tz("Asia/Kolkata")
              .format("DD MMM YYYY")}</td>
                    </tr>
                  </table>

                  <p style="margin-top:30px;"><strong>📦 Tender Items:</strong></p>
                  <ul style="margin-top:10px; padding-left:20px;">
                    ${tender.materials
            .map(
              (mat) => `
                      <li>${mat.material} (${mat.subMaterial || "N/A"}) - ${mat.weight
                } MT, ${mat.quantity} Qty</li>
                    `
            )
            .join("")}
                  </ul>

                  <p style="margin-top:30px;">
                    <strong>✅ Finalized Price:</strong> ₹${finalPrice}
                  </p>

                  <p style="margin-top:30px;">
                    We sincerely appreciate your cooperation. Further communication regarding dispatch schedules will follow shortly.
                  </p>

                  <p style="margin-top:40px;">
                    Thanks & Regards,<br>
                    <span style="font-weight:bold; font-size:18px;">RR ISPAT</span><br>
                    <small style="color:#777;">A Unit of Godawari Power and Ispat Limited</small>
                  </p>

                </td>
              </tr>

              <tr>
                <td style="background-color: #f1f1f1; text-align: center; padding: 15px; font-size: 12px; color: #777;">
                  Building Strong Foundations | <a href="https://www.rrispat.com" style="color: #2E86C1; text-decoration: none;">www.rrispat.com</a>
                </td>
              </tr>

            </table>
          </div>
        `,
      });
    } catch (emailErr) {
      console.error("Failed to send finalization email:", emailErr.message);
    }

    res.status(200).json({
      success: true,
      message: "Tender finalized and email sent to transport user",
      tender,
    });
  } catch (error) {
    console.error("Error in finalizeTender:", error);
    res.status(400).json({ success: false, message: error.message });
  }
};

// ✅ 3. Get All Tenders Created by RR User
export const getAllTendersByRRUser = async (req, res) => {
  try {
    const tenders = await Tender.find({ createdBy: req.user.id })
      .sort({ createdAt: -1 })
      .populate("selectedQuotation");

    res.status(200).json({ success: true, data: tenders });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
};

// ✅ 4. Get Tenders Assigned to a Transporter (excluding already quoted ones)

export const getTendersForTransporter = async (req, res) => {
  try {
    const transporterId = req.user.id;
    const now = new Date();

    // Step 1: Get all open tenders assigned to this transporter and within bidding window
    const tenders = await Tender.find({
      transporters: transporterId,
      status: "open",
      biddingStart: { $lte: now },
      biddingEnd: { $gte: now },
    }).sort({ createdAt: -1 });

    const tenderIds = tenders.map((t) => t._id);

    // Step 2: Get all quotations by this transporter for these tenders
    const transporterQuotations = await Quotation.find({
      transportUser: transporterId,
      tender: { $in: tenderIds },
    }).select("tender");

    const quotedTenderIds = new Set(
      transporterQuotations.map((q) => q.tender.toString())
    );

    // Count how many times transporter quoted per tender
    const bidCountMap = {};
    transporterQuotations.forEach((q) => {
      const id = q.tender.toString();
      bidCountMap[id] = (bidCountMap[id] || 0) + 1;
    });

    // Step 3: Prepare tender list with hasQuoted and bidsLeft
    const tendersWithStatus = tenders.map((tender) => {
      const tenderObj = tender.toObject();
      const tid = tender._id.toString();
      tenderObj.hasQuoted = quotedTenderIds.has(tid);
      tenderObj.bidsUsed = bidCountMap[tid] || 0;
      tenderObj.bidsRemaining = Math.max(0, 3 - tenderObj.bidsUsed);
      return tenderObj;
    });

    // Step 4: Populate createdBy field
    await Tender.populate(tendersWithStatus, {
      path: "createdBy",
      select: "name email",
    });

    res.status(200).json({ success: true, data: tendersWithStatus });
  } catch (error) {
    console.error("Error in getTendersForTransporter:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

//upcomming tender

export const getUpcomingTendersForTransporter = async (req, res) => {
  try {
    const transporterId = req.user.id;
    const now = new Date();

    // 🟡 Step 1: Find upcoming tenders assigned to this transporter
    const upcomingTenders = await Tender.find({
      transporters: transporterId,
      status: "open",
      biddingStart: { $gt: now },
    })
      .sort({ biddingStart: 1 })
      .populate("createdBy", "name email");

    // 🕒 Step 2: Add biddingOpensIn to each tender
    const tendersWithCountdown = upcomingTenders.map((tender) => {
      const tenderObj = tender.toObject();
      tenderObj.biddingOpensIn =
        new Date(tender.biddingStart).getTime() - now.getTime(); // in milliseconds
      return tenderObj;
    });

    res.status(200).json({ success: true, data: tendersWithCountdown });
  } catch (error) {
    console.error("Error in getUpcomingTendersForTransporter:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

// ✅ 5. Get Quotations for a Tender

export const getTenderQuotations = async (req, res) => {
  try {
    const tenderId = req.params.id;
    const userId = req.user.id;

    const tender = await Tender.findById(tenderId).populate(
      "createdBy",
      "name email"
    );
    if (!tender) {
      return res
        .status(404)
        .json({ success: false, message: "Tender not found" });
    }

    if (tender.createdBy._id.toString() !== userId) {
      return res.status(403).json({ success: false, message: "Unauthorized" });
    }

    const now = new Date();
    if (now < tender.biddingEnd) {
      return res.status(403).json({
        success: false,
        message:
          "Top quotations can be viewed only after the bidding window closes.",
      });
    }

    const allQuotes = await Quotation.find({ tender: tenderId })
      .populate("transportUser", "name email")
      .sort({ price: 1, createdAt: 1 });

    const seen = new Set();
    const bestQuotes = [];

    for (const q of allQuotes) {
      const uid = q.transportUser._id.toString();
      if (!seen.has(uid)) {
        seen.add(uid);
        bestQuotes.push(q);
      }
    }

    let quotesToReturn = [];
    if (tender.reopenCount === 0) {
      quotesToReturn = bestQuotes.slice(0, 3); // L1, L2, L3
    } else if (tender.reopenCount === 1) {
      quotesToReturn = bestQuotes.slice(1, 3); // L2, L3
    } else if (tender.reopenCount === 2) {
      quotesToReturn = bestQuotes.slice(2, 3); // Only L3
    }

    const ranked = quotesToReturn.map((q, index) => {
      const signedFiles = (q.files || []).map((file) => {
        const key = file.url?.split("/").pop();
        return { ...file, url: generateSignedUrl(key) };
      });

      return {
        rank: `L${bestQuotes.indexOf(q) + 1}`,
        transportUser: q.transportUser,
        price: q.price,
        vehicleNumber: q.vehicleNumber,
        createdAt: q.createdAt,
        files: signedFiles,
        _id: q._id,
      };
    });

    res.status(200).json({ success: true, data: ranked });
  } catch (error) {
    console.error("Error fetching top 3 quotations:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

//reopen tender
export const reopenTender = async (req, res) => {
  try {
    const { id } = req.params;
    const { reason } = req.body;

    if (!reason || reason.trim() === "") {
      return res.status(400).json({ error: "Reason is required." });
    }

    const tender = await Tender.findById(id);
    if (!tender)
      return res.status(404).json({ success: false, message: "Not found" });

    // 🚫 Prevent reopening more than twice
    if (tender.reopenCount >= 2) {
      return res.status(403).json({
        success: false,
        message:
          "This tender has already been reopened twice and cannot be reopened again.",
      });
    }

    // ✅ Perform reopen
    tender.status = "open";
    tender.selectedQuotation = null;
    tender.finalTransporter = null;
    tender.finalPrice = null;
    tender.reopenCount = (tender.reopenCount || 0) + 1; // ✅ increment counter
    tender.winnerComment = `[Reopened: ${reason}]`;

    await tender.save();

    res.status(200).json({
      success: true,
      message: "Tender reopened successfully",
      reopenCount: tender.reopenCount,
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
};

// ✅ 6. Get Single Tender
export const getSingleTender = async (req, res) => {
  try {
    const tender = await Tender.findById(req.params.id)
      .populate("createdBy", "name email")
      .populate("quotations")
      .populate("selectedQuotation");

    if (!tender) {
      return res
        .status(404)
        .json({ success: false, message: "Tender not found" });
    }

    res.status(200).json({ success: true, data: tender });
  } catch (error) {
    res.status(400).json({ success: false, message: error.message });
  }
};

// ✅ 7. Delete Tender (by RR User)
export const deleteTender = async (req, res) => {
  try {
    const tender = await Tender.findById(req.params.id);

    if (!tender) {
      return res
        .status(404)
        .json({ success: false, message: "Tender not found" });
    }

    if (tender.createdBy.toString() !== req.user.id) {
      return res.status(403).json({ success: false, message: "Unauthorized" });
    }

    await Tender.findByIdAndDelete(req.params.id);

    res
      .status(200)
      .json({ success: true, message: "Tender deleted successfully" });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
};

// ✅ Get Quotation History for Transporter

export const getQuotationHistoryForTransporter = async (req, res) => {
  try {
    const transporterId = new mongoose.Types.ObjectId(req.user.id);

    const today = new Date();
    today.setHours(0, 0, 0, 0); // normalize to start of today

    // ✅ Get all quotations by this transporter, grouped by tender
    const quotations = await Quotation.find({ transportUser: transporterId })
      .populate({
        path: "tender",
        populate: {
          path: "createdBy",
          select: "name email",
        },
      })
      .sort({ createdAt: 1 });

    const tenderQuotesMap = new Map();

    // ✅ Group quotations by tender ID (and skip tenders whose closeDate >= today)
    for (const q of quotations) {
      const tender = q.tender;
      const tenderId = tender?._id?.toString();
      if (!tenderId) continue;

      const biddingEndTime = new Date(tender.biddingEnd);
      if (biddingEndTime > new Date()) continue;

      if (!tenderQuotesMap.has(tenderId)) {
        tenderQuotesMap.set(tenderId, []);
      }
      tenderQuotesMap.get(tenderId).push(q);
    }

    const result = [];

    for (const [tenderId, tenderQuotes] of tenderQuotesMap.entries()) {
      const tender = tenderQuotes[0].tender;

      // ✅ Determine if any of the quotations match the selectedQuotation
      const isSelected =
        tender.selectedQuotation &&
        tenderQuotes.some(
          (q) => q._id.toString() === tender.selectedQuotation.toString()
        );

      const formattedQuotes = tenderQuotes.map((q) => {
        const signedFiles = (q.files || []).map((file) => {
          const key = file.url?.split("/").pop();
          return {
            ...file,
            url: generateSignedUrl(key),
          };
        });

        return {
          _id: q._id,
          price: q.price,
          vehicleNumber: q.vehicleNumber,
          createdAt: q.createdAt,
          files: signedFiles,
        };
      });

      result.push({
        tenderId: tender._id,
        tender: {
          dispatchLocation: tender.dispatchLocation,
          address: tender.address,
          deliveryWindow: tender.deliveryWindow || { from: null, to: null },
          closeDate: tender.closeDate,
          status: tender.status,
          remarks: tender.remarks,
          materials: tender.materials || [],
          totalWeight: tender.totalWeight,
          totalQuantity: tender.totalQuantity,
          createdBy: tender.createdBy || null,
          maxBidAmount: tender.maxBidAmount,
          maxBidUnit: tender.maxBidUnit || null,
          finalizedStatus: isSelected
            ? "Your quotation was finalized"
            : "Your quotation was not selected",
        },
        quotations: formattedQuotes,
      });
    }

    res.status(200).json({
      success: true,
      data: result,
    });
  } catch (error) {
    console.error("Error fetching quotation history:", error);
    res.status(500).json({ success: false, message: error.message });
  }
};

//all finalized tenders

// export const getAllFinalizedTendersWithQuotations = async (req, res) => {
//   try {
//     const rrUserId = req.user.id;

//     // ✅ Get all finalized tenders created by this RR user
//     const finalizedTenders = await Tender.find({
//       createdBy: rrUserId,
//       status: "finalized",
//     })
//       .populate({
//         path: "selectedQuotation",
//         populate: { path: "transportUser", select: "name email" },
//       })
//       .populate("createdBy", "name email")
//       .sort({ updatedAt: -1 });

//     const results = [];

//     for (const tender of finalizedTenders) {
//       // ✅ Get all quotations for this tender
//       const quotations = await Quotation.find({ tender: tender._id })
//         .populate("transportUser", "name email")
//         .sort({ createdAt: -1 });

//       const allQuotations = quotations.map((q) => {
//         const signedFiles = (q.files || []).map((file) => {
//           const key = file.url?.split("/").pop();
//           return {
//             ...file,
//             url: generateSignedUrl(key),
//           };
//         });

//         return {
//           _id: q._id,
//           price: q.price,
//           vehicleNumber: q.vehicleNumber,
//           createdAt: q.createdAt,
//           transportUser: q.transportUser,
//           files: signedFiles,
//         };
//       });

//       const selectedQuotationId = tender.selectedQuotation?._id?.toString();

//       results.push({
//         tender: {
//           _id: tender._id,
//           dispatchLocation: tender.dispatchLocation,
//           address: tender.address,
//           deliveryWindow: tender.deliveryWindow, // ✅ Updated from dateOfDelivery
//           closeDate: tender.closeDate,
//           remarks: tender.remarks,
//           status: tender.status,
//           finalPrice: tender.finalPrice,
//           materials: tender.materials,
//           totalWeight: tender.totalWeight,
//           totalQuantity: tender.totalQuantity,
//           createdBy: tender.createdBy,
//         },
//         selectedQuotation: tender.selectedQuotation
//           ? {
//               _id: tender.selectedQuotation._id,
//               price: tender.selectedQuotation.price,
//               vehicleNumber: tender.selectedQuotation.vehicleNumber,
//               transportUser: tender.selectedQuotation.transportUser,
//               files: (tender.selectedQuotation.files || []).map((file) => {
//                 const key = file.url?.split("/").pop();
//                 return {
//                   ...file,
//                   url: generateSignedUrl(key),
//                 };
//               }),
//             }
//           : null,
//         allQuotations: allQuotations.map((q) => ({
//           ...q,
//           selected: q._id.toString() === selectedQuotationId,
//         })),
//       });
//     }

//     res.status(200).json({ success: true, data: results });
//   } catch (error) {
//     console.error("Error fetching finalized tenders for RR user:", error);
//     res.status(500).json({ success: false, message: error.message });
//   }
// };

//your position for transporters

export const getMyQuotationPosition = async (req, res) => {
  try {
    const { tenderId } = req.params;
    const userId = req.user.id;

    console.log("Fetching position for tenderId:", tenderId);

    // ✅ Validate Tender ID
    if (!tenderId || !mongoose.Types.ObjectId.isValid(tenderId)) {
      return res.status(400).json({ message: "Invalid or missing Tender ID" });
    }

    // ✅ Get all quotations for the tender, sorted by price + createdAt
    const allQuotes = await Quotation.find({ tender: tenderId }).sort({
      price: 1,
      createdAt: 1,
    });

    // ✅ Group best (lowest) quote per transporter
    const bestQuotesMap = new Map(); // transportUserId => bestQuotation

    for (const quote of allQuotes) {
      const uid = quote.transportUser.toString();
      if (!bestQuotesMap.has(uid)) {
        bestQuotesMap.set(uid, quote); // first lowest quote per transporter
      }
    }

    // ✅ Sort those best quotes by price (and createdAt to break ties)
    const sortedBestQuotes = Array.from(bestQuotesMap.entries()).sort(
      ([, q1], [, q2]) => {
        if (q1.price === q2.price) {
          return new Date(q1.createdAt) - new Date(q2.createdAt);
        }
        return q1.price - q2.price;
      }
    );

    // ✅ Find current user's rank + their best quote
    let position = null;
    let bestQuote = null;

    for (let i = 0; i < sortedBestQuotes.length; i++) {
      const [uid, quote] = sortedBestQuotes[i];
      if (uid === userId) {
        position = `L${i + 1}`;
        bestQuote = {
          _id: quote._id,
          price: quote.price,
          vehicleNumber: quote.vehicleNumber,
          createdAt: quote.createdAt,
        };
        break;
      }
    }

    // ✅ No bids yet?
    if (!bestQuote) {
      return res.status(200).json({
        position: null,
        message: "You have not submitted any bids yet.",
      });
    }

    // ✅ Success response with rank + best bid
    res.status(200).json({
      position,
      bestQuotation: bestQuote,
    });
  } catch (error) {
    console.error("Error getting bid position:", error);
    res.status(500).json({ message: "Internal server error" });
  }
};
In recent years, cryptocurrency exchanges have become the backbone of the global crypto economy, offering seamless trading experiences to users worldwide. Among these, MEXC has emerged as a highly reputed and rapidly growing platform. For entrepreneurs and startups looking to replicate its success, the MEXC Clone Script offers a golden opportunity. This beginner-friendly guide will walk you through what a MEXC clone script is, how it works, and how you can leverage it to launch your own crypto exchange business.

What is a MEXC Clone Script?

A MEXC clone script is a ready-made, white-label software solution designed to replicate the core functionalities and features of the MEXC cryptocurrency exchange. It is fully customizable and can be tailored to suit your specific branding, trading pairs, security protocols, and more.
This script is an ideal choice for crypto entrepreneurs who want to enter the exchange business without investing time and resources into building a platform from scratch.

Key Features of MEXC Clone Script

Here’s a look at the must-have features that come integrated with a premium MEXC clone script:

Spot and Futures Trading – Support for real-time market, limit, and stop-limit trading.

Multi-Currency Wallet Integration – Seamless wallet support for storing and transacting with multiple cryptocurrencies.

High Liquidity Management – Integration with liquidity providers to ensure smooth trading experience.

KYC/AML Compliance – Built-in user verification modules for secure onboarding.

Robust Admin Dashboard – Admin panel to monitor user activity, trading volume, fees, and more.

Security Features – Two-factor authentication (2FA), SSL encryption, anti-DDoS protection, and wallet security.

Mobile Application Support – Dedicated mobile apps for Android and iOS.

Why Choose a MEXC Clone Script?
  
Launching a crypto exchange from the ground up can take months or even years, with enormous development costs and technical challenges. That’s where clone scripts shine. Here are some key advantages:

Faster Time-to-Market

You can get your platform up and running in a matter of weeks instead of months, enabling you to seize market opportunities quickly.

Cost-Efficient

Developing an exchange from scratch can be extremely expensive. A clone script reduces the cost significantly without compromising quality or performance.

Customizable

From UI/UX to trading pairs and revenue models, everything can be customized according to your business requirements.

Battle-Tested Architecture

Clone scripts replicate platforms like MEXC that already have a proven track record. This gives you a strong technical foundation to build upon.

Steps to Launch a Crypto Exchange Using MEXC Clone Script

Launching your exchange involves several critical steps. Here’s a quick roadmap:

Market Research

Understand your target audience, legal requirements, and regional regulations.

Choose a Reliable Script Provider

Partner with an experienced provider that offers robust, scalable, and secure MEXC clone scripts.

Customize the Platform

Tailor the branding, features, trading engine, and dashboard as per your needs.

Integrate Security Modules

Ensure multi-layered security measures are in place to protect user data and assets.

Test the Platform

Run extensive testing to identify and fix any bugs or performance issues.

Deploy and Promote

Once the platform is stable, launch it live and begin your marketing campaigns to onboard users.

Why Choose AppcloneX for MEXC Clone Script?
  
If you’re searching for a trustworthy and performance-driven solution, AppcloneX stands out as a preferred choice among crypto entrepreneurs. Here's why:

Battle-Tested Script modeled after the real-world performance of MEXC.

24/7 Technical Support to ensure smooth operations post-deployment.

End-to-End Customization so your exchange reflects your unique vision.

Strong Security Layers to gain users’ trust and ensure compliance.

Whether you're just stepping into the crypto space or are a seasoned blockchain enthusiast, AppcloneX’s MEXC clone script is designed to give you a powerful launchpad for your trading business.

Final Thoughts

The crypto trading industry is booming, and opportunities are abundant for those who take timely action. A MEXC clone script offers an ideal blend of speed, scalability, and security for launching your own crypto exchange platform. With the right strategy and a reliable tech partner like AppcloneX, you can enter the market confidently and carve your niche in the digital finance revolution.
-- RISK401	upi_p2p_intent_decline_oc76a	
-- "if (
--   ((initiationMode == ""04"") || (initiationMode == ""05"")) && (payerType == ""PERSON"") && (payeeType == ""PERSON"")
-- ){ BLOCK}"
-- DROP TABLE team_kingkong.tpap_risk401_breaches;

-- CREATE TABLE team_kingkong.tpap_risk401_breaches AS
INSERT INTO team_kingkong.tpap_risk401_breaches
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, scope_cust_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(created_on) as txn_date,
    MAX(amount) AS txn_amount,
    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'
    AND vpa IS NOT NULL
    GROUP BY 1,2,7)B
inner join
    (select txn_id, category
    , json_extract_scalar(extended_info, '$.initiationMode') as initiationMode
    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 json_extract_scalar(extended_info, '$.initiationMode') IN ('04', '05')
    AND category ='VPA2VPA'
    and upper(status) in ('SUCCESS')) C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') AS payerType
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') AS payeeType
    , JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode')
    , 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 (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 JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode') IN ('04', '05'))D
ON B.txn_id = D.txnid
WHERE payer_vpa IS NOT NULL;
-- RISK401	upi_p2p_intent_decline_oc76a	
-- "if (
--   ((initiationMode == ""04"") || (initiationMode == ""05"")) && (payerType == ""PERSON"") && (payeeType == ""PERSON"")
-- ){ BLOCK}"
-- DROP TABLE team_kingkong.tpap_risk401_breaches;

-- CREATE TABLE team_kingkong.tpap_risk401_breaches AS
INSERT INTO team_kingkong.tpap_risk401_breaches
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, scope_cust_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(created_on) as txn_date,
    MAX(amount) AS txn_amount,
    created_on AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-02-01' - INTERVAL '1' DAY) AND DATE'2025-02-28'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-02-01' - INTERVAL '1' DAY) AND DATE'2025-02-28'
    AND vpa IS NOT NULL
    GROUP BY 1,2,7)B
inner join
    (select txn_id, category
    , json_extract_scalar(extended_info, '$.initiationMode') as initiationMode
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-02-01' - INTERVAL '1' DAY) AND DATE'2025-02-28'
    and DATE(created_on) BETWEEN DATE(DATE'2025-02-01' - INTERVAL '1' DAY) AND DATE'2025-02-28'
    AND json_extract_scalar(extended_info, '$.initiationMode') IN ('04', '05')
    AND category ='VPA2VPA'
    and upper(status) in ('SUCCESS')) C
on B.txn_id = C.txn_id
INNER JOIN
    (SELECT txnid
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payerType') AS varchar),'"','') AS payerType
    , regexp_replace(cast(json_extract(request, '$.requestPayload.payeeType') AS varchar),'"','') AS payeeType
    , JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode')
    , 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-02-01' - INTERVAL '1' DAY) AND DATE'2025-02-28'
    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, '$.requestPayload.payeeType') AS varchar),'"','') = 'PERSON'
    AND  JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode') IN ('04', '05'))D
ON B.txn_id = D.txnid
WHERE payer_vpa IS NOT NULL;
-- upi_intent_merchant_decline_oc76a  RISK402
-- "if((initiationMode == ""04"") && (merchantGenre == ""OFFLINE"") && (isVerifiedMerchant == ""false"")){
-- ""BLOCK"""

-- DROP TABLE team_kingkong.tpap_risk402_breaches;

-- CREATE TABLE team_kingkong.tpap_risk402_breaches AS
INSERT INTO team_kingkong.tpap_risk402_breaches
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, scope_cust_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(created_on) as txn_date,
    MAX(amount) AS txn_amount,
    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' 
    AND vpa IS NOT NULL
    GROUP BY 1,2,7)B
inner join
    (select txn_id, category
    , json_extract_scalar(extended_info, '$.merchantGenre') as merchantGenre
    , json_extract_scalar(extended_info, '$.initiationMode') as initiationMode
    , json_extract_scalar(extended_info, '$.isVerifiedMerchant') as isVerifiedMerchant
    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 json_extract_scalar(extended_info, '$.merchantGenre') = 'OFFLINE'
    AND json_extract_scalar(extended_info, '$.initiationMode') = '04'
    AND json_extract_scalar(extended_info, '$.isVerifiedMerchant') = 'false'
    and upper(status) in ('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
    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 (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  JSON_EXTRACT_SCALAR(request, '$.requestPayload.initiationMode') = '04')D
ON B.txn_id = D.txnid
WHERE upi_subtype = 'UPI_TRANSACTION' AND payer_vpa IS NOT NULL
;
/**
 * Security Headers 
 */

function add_security_headers() {
    header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
    //header("Content-Security-Policy: default-src 'self';");
    header("X-Frame-Options: SAMEORIGIN");
    header("X-Content-Type-Options: nosniff");
    header("Referrer-Policy: no-referrer-when-downgrade");
    header("Permissions-Policy: geolocation=(self), microphone=()");
}
add_action('send_headers', 'add_security_headers');
To build a crypto wallet like Trust Wallet, you need to develop a secure, user-friendly mobile application that supports multiple cryptocurrencies, private key management, and seamless integration with decentralized apps (dApps). But starting from scratch can be time-consuming and expensive. A faster and more efficient way is to use a Trust Wallet clone script,a ready-made, customizable solution that replicates the core features of Trust Wallet.

For more info- ttps://www.alwin.io/trust-wallet-clone-script
916382359432

**var statment**;
**left --> right**;
**most complete to least complete**;
**everything to the left is included in the model**;
Proc MI Data=analysis nimpute=50 out=project.analysisMI seed=07112022;
   Class HFRS_cat Charlson_cat Elixhauser_cat
         sexf rural_residence
         ACS_cat PCI CABG
         polypharmacy
         SES
         inhospital_death mortality30d episode_LOSgt10 discharge_inst
         outcome_death
         outcome_AKI outcome_readmit1y outcome_ACSreadmit1y outcome_revasc1y outcome_MajorBleed1y outcome_StrokeTIA1y outcome_MACE1y
         uptake1y_statins uptake1y_BB uptake1y_ACEi uptake1y_ARB uptake1y_P2Y12 outcome_GDMT1y
         hypoalbuminemia lab_anemia
         APPROACH_dyslipedimia smoking  BMIcat
         episode_HF episode_PulEdema episode_CardiogenicShock episode_CardiacArrest 
         Prior_MI elix_diab  elix_hyper
         elix_PVD elix_CHF baseline_AF elix_renal
         elix_liver charlson_COPD charlson_dementia elix_cancer
         PriorCath PriorPCI PriorCABG
         STsegment elevated_cardiac_markers
         Killip
         GRACE_cat
         ;
   fcs discrim( / ClassEffects=include details) reg( / details);
   var HFRS_cat Charlson_cat Elixhauser_cat
       age_admission sexf rural_residence
       ACS_cat PCI CABG
       polypharmacy
       episode_HF episode_PulEdema episode_CardiogenicShock episode_CardiacArrest 
       Prior_MI elix_diab  elix_hyper
       elix_PVD elix_CHF baseline_AF elix_renal
       elix_liver charlson_COPD charlson_dementia elix_cancer
       SES
       inhospital_death mortality30d episode_LOS episode_LOSgt10 discharge_inst
       outcome_death outcome_death_time
       outcome_AKI outcome_readmit1y outcome_ACSreadmit1y outcome_revasc1y outcome_MajorBleed1y outcome_StrokeTIA1y outcome_MACE1y
       uptake1y_statins uptake1y_BB uptake1y_ACEi uptake1y_ARB uptake1y_P2Y12 outcome_GDMT1y
       hypoalbuminemia lab_anemia
       APPROACH_dyslipedimia smoking  BMIcat
       PriorCath PriorPCI PriorCABG
       baseline_creatinine_mg_dL elevated_cardiac_markers STsegment
       PresysBP PreHR_bpm 
       Killip
       GRACE_cat
       ;
run;
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " :x-connect: What's On in Brisbane! :x-connect:  ",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Good morning Brisbane! Please see below for what's on this week."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-9: Monday, 23rd June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café Partnership: Enjoy free coffee and café-style beverages from our partner, *Edward*. \n\n :lunch: *Lunch*: from *12pm* in the kitchen."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-25: Wednesday, 25th June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":coffee: *Café Partnership*: Café Partnership: Enjoy coffee and café-style beverages from our partner, *Edward*. \n\n :late-cake: *Morning Tea*: from *10am* in the kitchen."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-27: Friday, 27th June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":party: Social Happy Hour from 3.00pm: Wind down drinks and nibbles with your work pals."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/u/0?cid=Y19uY2M4cDN1NDRsdTdhczE0MDhvYjZhNnRjb0Bncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Brisbane Social Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":x-connect: Xero Boost Days! :x-connect:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Good morning Sydney! Please see below for what's on next week as we have a few changes to the Boost Programme. Also see the:thread: if you need to book a workstation on Level 1. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-23: Monday, 23th June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café Partnership: Enjoy free coffee and café-style beverages from our partner, *Naked Duck*. \n\n :breakfast: *Lunch*: from *12.00pm* in the All Hands Space."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-26: Wednesday, 25th June",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":coffee: *Café Partnership*: Café Partnership: Enjoy coffee and café-style beverages from our partner, *Naked Duck*.\n\n :breakfast: *Breakfast*: from *9.00am* in the All Hands Space."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/u/0/r?cid=Y185aW90ZWV0cXBiMGZwMnJ0YmtrOXM2cGFiZ0Bncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Sydney Social Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":x-connect: Boost Days - What's on for this week :x-connect:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Good morning Melbourne, hope you all had a wonderful weekend :smile: See below for what's in store this week as there is a change to our Boost Lunch Location: "
			}
		},
		{
			"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 bringing back the yummy cookies and slices. * \n\n  :coffee: *Weekly Café Special:* _ Hazelnut Latte_"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 25th June :calendar-date-25:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": " \n\n :lunch: *Italian themed Lunch*: Lunch is from *12pm* in the *Level-1 and Level-2 Kitchen* Lunch menu in:thread: \n \n :resilience-project: *Level 3 Breakout Space* :resilience-project: \n\n As part of our 2015 wellbeing initiative, *Belinda Tan & Sahar Zamanie* are excited to once again partner with *The Resilience Project* to Launch The *Authentic Connection Program*. This inspiring program explores how Vulnerability, imperfection, and passion can help us build deeper, more meaningful relationships with others and ourselves.\n\n  Grab your Lunch & Join us at 12.15pm, as there will be a special preview featuring a powerful 1 hour video presentation by Hugh Van Cuylenburg "
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 26th June, :Calendar-date-26:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":eggs: *Breakfast*: from *8:30am-10:30am* in the Wominjeka Breakout Space.   \n\n :massage: Massage Services from 9.00am in the Wellbeing Room on Level-1. \n :pizza: Pizza and an Italian Disco playlist from DJ Anya   \n\n  "
			}
		},
		{
			"type": "divider"
		}
	]
}
A crypto exchange clone script is a software solution modeled on successful crypto exchanges like Binance, Coinbase, or Kraken. These scripts serve as pre-built templates containing the core functionalities needed for launching a trading platform.

Hivelance has earned its reputation as a premier crypto exchange clone script development company by delivering more number of high-quality blockchain projects. With a decade of experience and a deep understanding of market dynamics, we build platforms that combine performance, security, and innovation.



Know More:

Visit - https://www.hivelance.com/crypto-exchange-clone-script
WhatsApp - +918438595928, +971505249877
Telegram - Hivelance
Mail - sales@hivelance.com
.ginput_container_checkbox {
    .gchoice {
      margin-bottom: 1rem;

      @media (min-width: $md) {
        margin-bottom: 0;
      }

      label {
        position: relative;
        right: -4px;

        @media (min-width: $md) {
          right: -8px;
        }


        &::before {
          position: absolute;
          content: ' ';
          width: 16px;
          height: 16px;
          border: 1px solid $elgray;
          background: $lwhite;
          top: 3px;
          left: -20px;
          border-radius: 5px;

          @media (min-width: $md) {
            width: 20px;
            height: 20px;
            top: 3px;
            left: -26px;
          }
        }

        &::after {
          content: "";
          position: absolute;
          border-bottom: 2px solid $elgray;
          border-left: 2px solid $elgray;
          height: 6px;
          left: -16px;
          opacity: 0;
          top: 7px;
          transform: rotate(-45deg);
          transition: all .3s linear;
          width: 9px;

          @media (min-width: $md) {
            top: 9px;
            width: 10px;
            left: -21px;
          }
        }
      }

      input {
        opacity: 0;
      }

      input[type="checkbox"]:checked~label:after {
        opacity: 1 !important;
      }
    }
  }

  .ginput_container_radio {
    .gchoice {
      margin-bottom: 1rem;

      @media (min-width: $md) {
        margin-bottom: 0;
      }

      label {
        position: relative;
        right: -4px;

        @media (min-width: $md) {
          right: -8px;
        }

        &::before {
          position: absolute;
          content: ' ';
          width: 16px;
          height: 16px;
          border: 2px solid $primary;
          background: $white;
          top: 3;
          left: -20px;
          border-radius: 50%;

          @media (min-width: $md) {
            width: 20px;
            height: 20px;
            top: 3px;
            left: -26px;
          }
        }

        &::after {
          content: "";
          position: absolute;
          width: 8px;
          height: 8px;
          left: -16px;
          opacity: 0;
          top: 7px;
          border-radius: 50%;
          background: $primary;
          transition: all .3s linear;

          @media (min-width: $md) {
            width: 10px;
            height: 10px;
            top: 8px;
            left: -21px;
          }
        }
      }

      input {
        opacity: 0;
      }

      input[type="radio"]:checked~label:after {
        opacity: 1 !important;
      }
    }
  }
SELECT count(*) AS tot_rows
, sum(IF((category IS NULL OR category = '' OR category = ' '), 1, 0)) AS null_category_rows 
, sum(IF((status IS NULL OR status = '' OR status = ' '), 1, 0)) AS null_status_rows 
, sum(IF((txn_id IS NULL OR txn_id = '' OR txn_id = ' '), 1, 0)) AS null_txn_id_rows 
FROM switch.txn_info_snapshot_v3 
WHERE dl_last_updated BETWEEN DATE'2025-05-01' AND DATE'2025-05-31';

SELECT count(*) AS tot_rows
, sum(IF((amount IS NULL), 1, 0)) AS null_amount_rows 
, sum(IF((participant_type IS NULL OR participant_type = '' OR participant_type = ' '), 1, 0)) AS null_participant_type_rows 
, sum(IF((scope_cust_id IS NULL AND participant_type = 'PAYER'), 1, 0)) AS null_scope_cust_id_rows 
, sum(IF((txn_id IS NULL OR txn_id = '' OR txn_id = ' '), 1, 0)) AS null_txn_id_rows 
, sum(IF((vpa IS NULL OR vpa = '' OR vpa = ' '), 1, 0)) AS null_vpa_rows 
FROM switch.txn_participants_snapshot_v3 
WHERE dl_last_updated BETWEEN DATE'2025-05-01' AND DATE'2025-05-31';

SELECT count(*) AS tot_rows 
, sum(IF((evaluationType IS NULL OR evaluationType = '' OR evaluationType = ' '), 1, 0)) AS null_evaluationType_rows 
, sum(IF((latitude IS NULL OR latitude = '' OR latitude = ' '), 1, 0)) AS null_latitude_rows 
, sum(IF((longitude IS NULL OR longitude = '' OR longitude = ' '), 1, 0)) AS null_longitude_rows 
, sum(IF((osVersion IS NULL OR osVersion = '' OR osVersion = ' '), 1, 0)) AS null_osVersion_rows 
, sum(IF((payeeType IS NULL OR payeeType = '' OR payeeType = ' '), 1, 0)) AS null_payeeType_rows 
, sum(IF((payeeVpa IS NULL OR payeeVpa = '' OR payeeVpa = ' '), 1, 0)) AS null_payeeVpa_rows 
, sum(IF((payerType IS NULL OR payerType = '' OR payerType = ' '), 1, 0)) AS null_payerType_rows 
, sum(IF((payerVpa IS NULL OR payerVpa = '' OR payerVpa = ' '), 1, 0)) AS null_payerVpa_rows 
, sum(IF((cst_risk_code IS NULL OR cst_risk_code = '' OR cst_risk_code = ' '), 1, 0)) AS null_cst_risk_code_rows 
, sum(IF((action_recommended IS NULL OR action_recommended = '' OR action_recommended = ' '), 1, 0)) AS null_action_recommended_rows  
FROM
(SELECT txnid
, lower(regexp_replace(cast(json_extract(request,	'$.evaluationType') as varchar), '"', '')) AS evaluationType
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.latitude') as varchar), '"', '')) AS latitude
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.longitude') as varchar), '"', '')) AS longitude
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.osVersion') as varchar), '"', '')) AS osVersion
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.payeeType') as varchar), '"', '')) AS payeeType
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.payeeVpa') as varchar), '"', '')) AS payeeVpa
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.payerType') as varchar), '"', '')) AS payerType
, lower(regexp_replace(cast(json_extract(request,	'$.requestPayload.payerVpa') as varchar), '"', '')) AS payerVpa
, regexp_replace(cast(json_extract(response, '$.messages.cst[0]') as varchar), '"', '') AS cst_risk_code
, json_extract_scalar(response, '$.action_recommended') AS action_recommended
FROM tpap_hss.upi_switchv2_dwh_risk_data_snapshot_v3 
WHERE dl_last_updated BETWEEN DATE'2025-05-01' AND DATE'2025-05-31');
Select * from attlog where employeeID = 275;


UPDATE attlog
SET personName = 'Parveen Naik'
WHERE employeeID = 275;

#INPUT NUMBER OF APPLES WANNA BUY
Apples = 7
#COST PER APPLE
Cost = 3
#THIS IS YOUR MONEY
Money = 50
MoneyNeeded = Apples * Cost

if MoneyNeeded > 20:
    MoneyNeeded = ( Apples * Cost ) - 5
else: MoneyNeeded = Apples * Cost

print("                                        ____________")
print("                                       |            |")
print("                                       | Apple Shop |")
print("                                       |____________|")
print()
print("                                         NEW DEAL:")
print("                                SPEND > $20 WE TAKE $5 OFF")
print("")
print("                                MoneyNeeded & Apples Bought")
print("                                      ---------------")
print("                                           $",MoneyNeeded)
print("                                        ", Apples, "Apples")

print("                                      ---------------")
print("")
    
if MoneyNeeded > Money:
    print("                                       Not Enough Money")
else:
    print("                                       Enough Money ")
// Remove tabs and sub-menu from ASE Pro for non superadmin
add_action('admin_head', function() {
    $current_user = wp_get_current_user();
    
    // Only add CSS if the current user is NOT 'mastaklance'
    if ($current_user->user_login !== 'mastaklance') {
        echo '<style>label[for="tab-content-management"], label[for="tab-admin-interface"], label[for="tab-login-logout"], label[for="tab-disable-components"], label[for="tab-security"], label[for="tab-optimizations"], .asenha-toggle.utilities.local-user-avatar, .asenha-toggle.utilities.multiple-user-roles, .asenha-toggle.utilities.image-sizes-panel, .asenha-toggle.utilities.view-admin-as-role, .asenha-toggle.utilities.enable-password-protection, .asenha-toggle.utilities.maintenance-mode, .asenha-toggle.utilities.redirect-404-to-homepage, .asenha-toggle.utilities.display-system-summary, .asenha-toggle.utilities.search-engine-visibility-status, .asenha-toggle.custom-code.enable-code-snippets-manager, .asenha-toggle.custom-code.enable-custom-admin-css, .asenha-toggle.custom-code.enable-custom-frontend-css, .asenha-toggle.custom-code.enable-custom-body-class, .asenha-toggle.custom-code.manage-robots-txt { display: none; }</style>';
    }
});
Mạng dân đen VN thì rẻ bèo ấy mà, bao nhiêu vụ rồi có gì mới đâu? Sống ở VN thì phải xác định bản thân chỉ là con kiến, bọn cai trị nó đạp chết thì phải chịu.

Lúc này thì không thấy thằng nào vào bảo VN đáng sống nữa nhỉ? Với tôi, 1 đất nước đáng sống hay không trước tiên phải nhìn vào mạng người ở nước đó đáng giá bao nhiêu, nhớ cái vụ 2 anh dân đen bị thằng chó vàng xua ra làm lá chắn thịt để cản tội phạm không? Được đền bù tổng cộng 8 củ thôi nhé, nên cái mạng dân VN đáng giá 4 củ/người. Tất nhiên cái mạng của tôi và gia đình tôi cao hơn thế nhiều, nên đéo thèm ở VN nữa, hehe.

Ở VN bị conan đập chết cũng đéo kêu được, như vụ bạn Mỹ Hằng rơi từ tầng 9 chung cư Centana đấy. Thằng chồng làm conan đánh chết bạn này, xong thả từ tầng 9 xuống, nguyên 1 đám súc vật bao che cho nhau, thi thể bầm dập nát nhừ không nhận ra nổi. 2 ông bà già đeo bảng đi kêu oan khắp nơi, mà không có kết quả. Tôi hỏi mấy fence: Gọi VN là cái xứ rác rưởi có xứng đáng không? Chửi chính quyền VN như thế nào mới đủ? Trời xanh ở đâu? Nhân quả ở đâu?

Thế nên mấy thằng bò đỏ và ngạo nghễ nên câm mẹ mõm lại, chúng mày còn không xứng đáng được so sánh với súc vật. Bọn súc vật còn có tình yêu thương đồng loại, bọn mày là thứ quỷ dữ được tạo ra bởi 1 XH quá tàn bạo, nói thật cảm thấy quá sức ghê tởm khi trên đời tồn tại những loại người như này.
-- Fastag_Trusted_VRN_CCDC_Weekly_Monthly_limitCheck

-- Enabling CC/DC in Fastag Weekly limit of 10K per VRN via CC/DC and monthly limit of 20K per VRN via CC on fastag recharge using Trusted sourcesWeekly limit of X per VRN via CC/DC 
-- and monthly limit of Y per VRN via CC on fastag recharge using Trusted sources	

-- "if(!(Seq(""BALANCE"",""COUPON"").contains(payMethod)) && !(payMethod contains ""DIGITAL_CREDIT"") && !(Seq(""ONE_CLICK_PAY"").contains(oneclick))){trusted_payload = 1}

-- if(Seq(""CREDIT_CARD"",""DEBIT_CARD"").contains(pay_method) &&
--  paytm_merchant_id==""PTMFVT32998068120662"" &&
-- ((event_amount+sm_gmv_rn_tid_fastag_trust_success_7d)>2529500||
-- (event_amount+sm_gmv_rn_tid_fastag_trust_success_30d)>5059000))
-- ""BLOCK"""

-- DROP TABLE team_kingkong.onus_Fastag_Trusted_VRN_CCDC_Weekly_Monthly_limitCheck_breaches;
 
-- CREATE TABLE team_kingkong.onus_Fastag_Trusted_VRN_CCDC_Weekly_Monthly_limitCheck_breaches AS
INSERT INTO team_kingkong.onus_Fastag_Trusted_VRN_CCDC_Weekly_Monthly_limitCheck_breaches
with onus_txn_base as
    (SELECT DISTINCT A.*, case when m1.mid is not null then category else 'Others' end as business_category FROM 
        (select userid, transactionid,
        cast(eventAmount as double) / 100 as amt,
        dateinserted,
        substr(cast(dateinserted as varchar(30)), 1, 7) as mnth,
        paymethod, paytmmerchantid, responsestatus, actionrecommended, velocitytimestamp
        , subscriberid as vrn
        FROM cdp_risk_transform.maquette_flattened_onus_snapshot_v3
        WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-01-01' - INTERVAL '30' DAY) AND DATE'2025-01-31'
        AND SOURCE = 'PG'
        AND responsestatus IN ('SUCCESS') AND actionrecommended = 'PASS'
        AND paytmmerchantid IN ('PTMFVT32998068120662') AND paymethod IN ('DEBIT_CARD', 'CREDIT_CARD')
        AND eventid IN (SELECT eventlinkid
        FROM risk_maquette_data_async.pplus_payment_result_prod_async_snapshot_v3
        WHERE dl_last_updated BETWEEN DATE(DATE'2025-01-01' - INTERVAL '30' DAY) AND DATE'2025-01-31')) a
    left join
        (select * from team_kingkong.voc_mid_categorization where mid != '') m1
    on a.paytmmerchantid = m1.mid)
 
SELECT * FROM 
    (SELECT A.*
    , SUM(IF(DATE(B.dateinserted) BETWEEN DATE(DATE(A.dateinserted) - INTERVAL '7' DAY) AND DATE(A.dateinserted), B.amt, NULL)) AS week_amt
    , 25295 AS week_threshold
    -- No.of attempted txns per calendar month > 30 (consider only the CCBP transactions)
    , SUM(IF(DATE(B.dateinserted) BETWEEN date_trunc('month', DATE(A.dateinserted)) AND DATE(A.dateinserted), B.amt, NULL)) AS month_amt
    , 50590 AS month_threshold
    FROM
        (SELECT * FROM onus_txn_base
        WHERE DATE(dateinserted) BETWEEN DATE'2025-01-01' AND DATE'2025-01-31'
        )A
    INNER JOIN
        (SELECT * FROM onus_txn_base)B
    ON A.vrn = B.vrn AND A.transactionid <> B.transactionid AND B.velocitytimestamp < A.velocitytimestamp
    AND DATE(B.dateinserted) BETWEEN DATE(A.dateinserted - INTERVAL '30' DAY) AND DATE(A.dateinserted)
    GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12)
WHERE ((amt + week_amt) >= week_threshold) OR ((amt + month_amt) >= month_threshold)
;
-- RISK235
-- if in previous 30 minutes distinct( lat,long)>=10 then block (Paytm specific)

-- CREATE TABLE team_kingkong.tpap_risk235_breaches AS
INSERT INTO team_kingkong.tpap_risk235_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
FROM
    (SELECT txn_id, scope_cust_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(created_on) as txn_date,
    MAX(amount) AS txn_amount,
    created_on AS txn_time
    FROM switch.txn_participants_snapshot_v3
    WHERE DATE(dl_last_updated) BETWEEN DATE(DATE'2025-03-01' - INTERVAL '1' DAY) AND DATE'2025-03-31'
    AND DATE(created_on) BETWEEN DATE(DATE'2025-03-01' - INTERVAL '1' DAY) AND DATE'2025-03-31'
    AND vpa IS NOT NULL
    GROUP BY 1,2,7)B
inner join
    (select txn_id, category
    from switch.txn_info_snapshot_v3
    where DATE(dl_last_updated) BETWEEN DATE(DATE'2025-03-01' - INTERVAL '1' DAY) AND DATE'2025-03-31'
    and DATE(created_on) BETWEEN DATE(DATE'2025-03-01' - INTERVAL '1' DAY) AND DATE'2025-03-31'
    and upper(status) in ('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
    , 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-03-01' - INTERVAL '1' DAY) AND DATE'2025-03-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')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.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,
      10 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 '1800' SECOND) AND t1.txn_time -- 30 MIN
      AND t1.txn_id <> t2.txn_id AND t1.txn_amount > 5000
      AND NOT (t1.latitude = t2.latitude AND t1.longitude = t2.longitude)
    GROUP BY t1.payer_vpa, t1.payee_vpa, t1.txn_id, t1.txn_amount, t1.category, t1.upi_subtype, t1.txn_time, DATE(t1.txn_time), t1.latitude, t1.longitude)
WHERE distinct_lat_lon_count >= lat_long_cnt_threshold
;
star

Tue Jun 24 2025 17:49:07 GMT+0000 (Coordinated Universal Time) https://www.spyhunter.com/shm/uninstall-xcode-mac/

@hmboyd

star

Tue Jun 24 2025 17:48:50 GMT+0000 (Coordinated Universal Time) https://www.spyhunter.com/shm/uninstall-xcode-mac/

@hmboyd

star

Tue Jun 24 2025 17:48:38 GMT+0000 (Coordinated Universal Time) https://www.spyhunter.com/shm/uninstall-xcode-mac/

@hmboyd

star

Tue Jun 24 2025 17:48:30 GMT+0000 (Coordinated Universal Time) https://www.spyhunter.com/shm/uninstall-xcode-mac/

@hmboyd

star

Tue Jun 24 2025 17:08:27 GMT+0000 (Coordinated Universal Time)

@MainulHasan #latex

star

Tue Jun 24 2025 16:53:54 GMT+0000 (Coordinated Universal Time) https://tex.stackexchange.com/questions/410274/centring-authors-in-ieeeconf

@MainulHasan #latex

star

Tue Jun 24 2025 15:28:51 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #sql

star

Tue Jun 24 2025 09:52:28 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Tue Jun 24 2025 09:40:31 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Tue Jun 24 2025 09:38:15 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/amazon-clone

@raydensmith #amazon #clone

star

Tue Jun 24 2025 09:37:52 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Tue Jun 24 2025 09:21:45 GMT+0000 (Coordinated Universal Time)

@usman13

star

Tue Jun 24 2025 09:17:13 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/white-label-nft-marketplace/

@Emmawoods #whitelabelnftmarketplace

star

Mon Jun 23 2025 17:28:16 GMT+0000 (Coordinated Universal Time)

@Joe_Devs #php #laravel

star

Mon Jun 23 2025 12:06:49 GMT+0000 (Coordinated Universal Time)

@AKAMAY001

star

Mon Jun 23 2025 11:50:08 GMT+0000 (Coordinated Universal Time)

@AKAMAY001

star

Mon Jun 23 2025 11:39:06 GMT+0000 (Coordinated Universal Time) https://www.bizvertex.com/metatrader-clone-script

@jamiesmith1605

star

Mon Jun 23 2025 10:09:17 GMT+0000 (Coordinated Universal Time)

@SrijanVerma

star

Mon Jun 23 2025 08:54:46 GMT+0000 (Coordinated Universal Time) https://www.kryptobees.com/blog/fantasy-sports-app-development

@Marcochatt01 #fantasysports #appdevelopment #sportstech #mobileappdevelopment

star

Mon Jun 23 2025 08:49:05 GMT+0000 (Coordinated Universal Time) https://www.kryptobees.com/blog/olymp-trade-clone-script

@Franklinclas

star

Mon Jun 23 2025 08:22:43 GMT+0000 (Coordinated Universal Time) https://www.appclonex.com/mexc-clone-script

@riyageorge0895 #mexc

star

Mon Jun 23 2025 07:04:22 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Mon Jun 23 2025 06:29:57 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Mon Jun 23 2025 06:26:54 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Sun Jun 22 2025 07:28:58 GMT+0000 (Coordinated Universal Time)

@omnixima #css

star

Fri Jun 20 2025 11:48:46 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/fantasy-sports-app-development-company

@raydensmith #crypto #exchange

star

Fri Jun 20 2025 07:54:36 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/tokenization-of-real-estate/

@LilianAnderson #realestatetokenization #tokenizedassets #blockchainrealestate #fractionalownership #proptech

star

Fri Jun 20 2025 05:53:12 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/blog/bybit-clone-script

@Seraphina

star

Fri Jun 20 2025 05:24:24 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/white-label-crypto-exchange-software

@edisongery #whitelabelcryptocurrency exchange #whitelabelcryptocurrencyexchange #cryptocurrency

star

Fri Jun 20 2025 02:57:56 GMT+0000 (Coordinated Universal Time)

@ddover

star

Fri Jun 20 2025 02:47:02 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Jun 19 2025 06:00:44 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Jun 19 2025 01:58:02 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Tue Jun 10 2025 07:31:07 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/forex-trading-bot

@steeve #forex #trading #bot

star

Tue Jun 10 2025 06:32:16 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/technologies-used-in-binance-dex-clone-app

@stevejohnson #techstack in build binance clone script #techstack in build binance dex app clone #binancedex app clone

star

Tue Jun 10 2025 06:31:24 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/pump-fun-clone-script

@stevejohnson #pumpfun clone #pumpfun clone script #pumpfun clone script development #pumpfun platform clone

star

Tue Jun 10 2025 06:30:32 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/paypal-clone-script

@stevejohnson #paypalclone script #paypalapp clone #paypalclone software

star

Tue Jun 10 2025 05:49:41 GMT+0000 (Coordinated Universal Time)

@divyasoni23 #css

star

Tue Jun 10 2025 05:49:11 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Tue Jun 10 2025 05:44:50 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Tue Jun 10 2025 01:01:30 GMT+0000 (Coordinated Universal Time)

@bobby #python

star

Mon Jun 09 2025 20:28:40 GMT+0000 (Coordinated Universal Time)

@mastaklance

star

Mon Jun 09 2025 18:48:20 GMT+0000 (Coordinated Universal Time) https://voz.vn/t/nu-sinh-bi-đut-lia-1-chan-sau-va-cham-voi-xe-sang-bmw.1106546/page-53

@abcabcabc

star

Mon Jun 09 2025 13:26:25 GMT+0000 (Coordinated Universal Time)

@shubhangi.b

star

Mon Jun 09 2025 13:00:00 GMT+0000 (Coordinated Universal Time) https://appticz.com/taxi-booking-app-development

@davidscott

star

Mon Jun 09 2025 11:37:00 GMT+0000 (Coordinated Universal Time) https://myrosmol.ru/participants

@tone3

star

Mon Jun 09 2025 09:40:25 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