Advertisement
umuro

001-server

Jul 3rd, 2025
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 207.94 KB | None | 0 0
  1. This file is a merged representation of a subset of the codebase, containing specifically included files, combined into a single document by Repomix.
  2.  
  3. ================================================================
  4. File Summary
  5. ================================================================
  6.  
  7. Purpose:
  8. --------
  9. This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
  10. It is designed to be easily consumable by AI systems for analysis, code review,
  11. or other automated processes.
  12.  
  13. File Format:
  14. ------------
  15. The content is organized as follows:
  16. 1. This summary section
  17. 2. Repository information
  18. 3. Directory structure
  19. 4. Repository files (if enabled)
  20. 5. Multiple file entries, each consisting of:
  21.  a. A separator line (================)
  22.  b. The file path (File: path/to/file)
  23.  c. Another separator line
  24.  d. The full contents of the file
  25.  e. A blank line
  26.  
  27. Usage Guidelines:
  28. -----------------
  29. - This file should be treated as read-only. Any changes should be made to the
  30.  original repository files, not this packed version.
  31. - When processing this file, use the file path to distinguish
  32.  between different files in the repository.
  33. - Be aware that this file may contain sensitive information. Handle it with
  34.  the same level of security as you would the original repository.
  35.  
  36. Notes:
  37. ------
  38. - Some files may have been excluded based on .gitignore rules and Repomix's configuration
  39. - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
  40. - Only files matching these patterns are included: gmm_client/src/tables
  41. - Files matching patterns in .gitignore are excluded
  42. - Files matching default ignore patterns are excluded
  43. - Files are sorted by Git change count (files with more changes are at the bottom)
  44.  
  45.  
  46. ================================================================
  47. Directory Structure
  48. ================================================================
  49. gmm_client/
  50.   src/
  51.     tables/
  52.       assets/
  53.         mod.rs
  54.         query.rs
  55.         resource.rs
  56.       dashboardjibs/
  57.         mod.rs
  58.         query.rs
  59.         resource.rs
  60.       dashboardrevenue/
  61.         mod.rs
  62.         query.rs
  63.         resource.rs
  64.       dashboardtotalreportedpayments/
  65.         mod.rs
  66.         query.rs
  67.         resource.rs
  68.       incominglocation/
  69.         mod.rs
  70.         query.rs
  71.         resource.rs
  72.       incomingproducts/
  73.         mod.rs
  74.         query.rs
  75.         resource.rs
  76.       incomingtable1/
  77.         mod.rs
  78.         query.rs
  79.         resource.rs
  80.       incomingtable2/
  81.         mod.rs
  82.         query.rs
  83.         resource.rs
  84.       iwv_qc_queries/
  85.         incomingtables/
  86.           mod.rs
  87.           query.rs
  88.           resource.rs
  89.         taxyearrev1099/
  90.           mod.rs
  91.           query.rs
  92.           resource.rs
  93.         mod.rs
  94.       jibdetails/
  95.         mod.rs
  96.         query.rs
  97.         resource.rs
  98.       jibnetting/
  99.         mod.rs
  100.         query.rs
  101.         resource.rs
  102.       jibsummary/
  103.         mod.rs
  104.         query.rs
  105.         resource.rs
  106.       leases/
  107.         mod.rs
  108.         query.rs
  109.         resource.rs
  110.       pieleasestatus/
  111.         mod.rs
  112.         query.rs
  113.         resource.rs
  114.       pieproducingwellscounty/
  115.         mod.rs
  116.         query.rs
  117.         resource.rs
  118.       pieproducingwellsstate/
  119.         mod.rs
  120.         query.rs
  121.         resource.rs
  122.       pierevenuebycounty/
  123.         mod.rs
  124.         query.rs
  125.         resource.rs
  126.       pierevenuebyoperator/
  127.         mod.rs
  128.         query.rs
  129.         resource.rs
  130.       pierevenuebyproduct/
  131.         mod.rs
  132.         query.rs
  133.         resource.rs
  134.       pierevenuebystate/
  135.         mod.rs
  136.         query.rs
  137.         resource.rs
  138.       piewellstatus/
  139.         mod.rs
  140.         query.rs
  141.         resource.rs
  142.       revenue/
  143.         mod.rs
  144.         query.rs
  145.         resource.rs
  146.       revjibdetails/
  147.         mod.rs
  148.         query.rs
  149.         resource.rs
  150.       revjibsummary/
  151.         mod.rs
  152.         query.rs
  153.         resource.rs
  154.       statslistofcounts/
  155.         mod.rs
  156.         query.rs
  157.         resource.rs
  158.       statsproduction/
  159.         mod.rs
  160.         query.rs
  161.         resource.rs
  162.       statstopoperators/
  163.         mod.rs
  164.         query.rs
  165.         resource.rs
  166.       surfacerevenue/
  167.         mod.rs
  168.         query.rs
  169.         resource.rs
  170.       taxyear1099details/
  171.         mod.rs
  172.         query.rs
  173.         resource.rs
  174.       taxyearfullyeartotals/
  175.         mod.rs
  176.         query.rs
  177.         resource.rs
  178.       taxyearinterestbystate/
  179.         mod.rs
  180.         query.rs
  181.         resource.rs
  182.       taxyearrevenueand1099s/
  183.         mod.rs
  184.         query.rs
  185.         resource.rs
  186.       taxyearwellsbystate/
  187.         mod.rs
  188.         query.rs
  189.         resource.rs
  190.       wellops/
  191.         mod.rs
  192.         query.rs
  193.         resource.rs
  194.       wellrev/
  195.         mod.rs
  196.         query.rs
  197.         resource.rs
  198.       ytdcurrentyear/
  199.         mod.rs
  200.         query.rs
  201.         resource.rs
  202.       ytdpasttaxyear/
  203.         mod.rs
  204.         query.rs
  205.         resource.rs
  206.       ytdpfibyoperator/
  207.         mod.rs
  208.         query.rs
  209.         resource.rs
  210.       ytdpfibyproduct/
  211.         mod.rs
  212.         query.rs
  213.         resource.rs
  214.       ytdrevenuebyoperator/
  215.         mod.rs
  216.         query.rs
  217.         resource.rs
  218.       mod.rs
  219.  
  220. ================================================================
  221. Files
  222. ================================================================
  223.  
  224. ================
  225. File: gmm_client/src/tables/assets/mod.rs
  226. ================
  227. pub(crate) mod query;
  228. pub(crate) mod resource;
  229.  
  230. ================
  231. File: gmm_client/src/tables/assets/query.rs
  232. ================
  233. use leptos::*;
  234. use serde::{Deserialize, Serialize};
  235.  
  236. /// Represents a row in the assets report.
  237. #[derive(Debug, Clone, Serialize, Deserialize)]
  238. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  239. pub struct AssetsRow {
  240.     pub canonical: String,
  241.     pub state: Option<String>,
  242.     pub county: Option<String>,
  243.     pub township: Option<String>,
  244.     pub land_range: Option<String>,
  245.     pub section: Option<String>,
  246.     pub portion_of_section: Option<String>,
  247.     pub survey_name: Option<String>,
  248.     pub abstract_number: Option<String>,
  249.     pub block: Option<String>,
  250.     pub full_legal_description: Option<String>,
  251.     pub interest_type: Option<String>,
  252.     pub area_share_nma: Option<f64>,
  253.     pub conveyance_type: Option<String>,
  254.     pub document: Option<String>,
  255. }
  256.  
  257. /// Fetches asset-related data from multiple tables.
  258. #[server]
  259. pub async fn assets_fetch_by_canonical_name(
  260.     canonical_name: String,
  261. ) -> Result<Vec<AssetsRow>, ServerFnError> {
  262.     pub use AssetsRow;
  263.  
  264.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  265.  
  266.     let records = sqlx::query_as::<_, AssetsRow>(
  267.         r#"
  268.        SELECT
  269.            asset.state,
  270.            asset.county,
  271.            asset.township,
  272.            asset.land_range,
  273.            asset.section,
  274.            asset.portion_of_section,
  275.            survey.name AS survey_name,
  276.            asset.abstract_number,
  277.            asset.block,
  278.            asset.full_legal_description,
  279.            mineral_interest_type.name AS interest_type,
  280.            ROUND(SUM(1.0 * asset.net_mineral_acres), 2) AS area_share_nma,
  281.            (
  282.                SELECT GROUP_CONCAT(DISTINCT doc_type.name)
  283.                FROM document
  284.                LEFT JOIN doc_type ON document.doc_type_id = doc_type.id
  285.                WHERE document.asset_id = asset.asset_id
  286.            ) AS conveyance_type,
  287.            (
  288.                SELECT GROUP_CONCAT(DISTINCT document.file_archive)
  289.                FROM document
  290.                WHERE document.asset_id = asset.asset_id
  291.            ) AS document
  292.        FROM asset
  293.        LEFT JOIN mineral_interest_type ON asset.mineral_interest_type_id = mineral_interest_type.id
  294.        LEFT JOIN survey ON survey.id = asset.survey_id
  295.        LEFT JOIN client ON asset.client_id = client.id
  296.        WHERE client.canonical = ?
  297.        GROUP BY
  298.            asset.state,
  299.            asset.county,
  300.            asset.township,
  301.            asset.land_range,
  302.            asset.section,
  303.            asset.portion_of_section,
  304.            survey.name,
  305.            asset.abstract_number,
  306.            asset.block,
  307.            asset.full_legal_description,
  308.            mineral_interest_type.name
  309.        ORDER BY
  310.            asset.state, asset.county;
  311.        "#
  312.     )
  313.     .bind(&canonical_name)
  314.     .fetch_all(&land_pool)
  315.     .await
  316.     .map(|rows| {
  317.         log::debug!("Query succeeded: {} rows", rows.len());
  318.         rows
  319.     })
  320.     .map_err(|e| {
  321.         log::error!("Query failed: {}", e);
  322.         ServerFnError::new(format!("Database error: {}", e))
  323.     })?;
  324.  
  325.     Ok(records)
  326. }
  327.  
  328. ================
  329. File: gmm_client/src/tables/assets/resource.rs
  330. ================
  331. use super::query::AssetsRow;
  332. use crate::client_main_app::ctx::*;
  333. use leptos::*;
  334.  
  335. /// Leptos resource for fetching asset-related data.
  336. #[derive(Clone)]
  337. pub(crate) struct AssetsResource {
  338.     pub revenue_rows: Resource<String, Result<Vec<AssetsRow>, ServerFnError>>,
  339. }
  340.  
  341. use super::query::*;
  342. impl AssetsResource {
  343.     pub fn new() -> Self {
  344.         let revenue_rows = create_resource(
  345.             move || {
  346.                 let account_ctx = AccountCtx::use_context();
  347.                 account_ctx
  348.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  349.                     .unwrap_or_default()
  350.             },
  351.             |canonical_name| async move {
  352.                 assets_fetch_by_canonical_name(canonical_name)
  353.                     .await
  354.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  355.                 // Fixed conversion
  356.             },
  357.         );
  358.  
  359.         Self { revenue_rows }
  360.     }
  361. }
  362.  
  363. ================
  364. File: gmm_client/src/tables/dashboardjibs/mod.rs
  365. ================
  366. pub mod query;
  367. pub mod resource;
  368.  
  369. ================
  370. File: gmm_client/src/tables/dashboardjibs/query.rs
  371. ================
  372. use leptos::*;
  373. use serde::{Deserialize, Serialize};
  374.  
  375. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  376. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  377. pub struct DashboardJibsRow {
  378.     pub operator_name: String,
  379.     pub jib_amount: f64,
  380.     pub netted_amount: Option<f64>,
  381.     pub difference: Option<f64>,
  382.     pub month: String,
  383. }
  384.  
  385. #[cfg(feature = "ssr")]
  386. use sqlx::{SqlitePool, query_as};
  387.  
  388. #[cfg(feature = "ssr")]
  389. pub async fn get_dashboard_jibs_data(
  390.     pool: &SqlitePool,
  391.     client_canonical: &str,
  392. ) -> Result<Vec<DashboardJibsRow>, leptos::ServerFnError> {
  393.     let query = r#"
  394.        WITH standardize_date AS (
  395.            SELECT
  396.                TRIM(pay_month) AS pay_month,
  397.                payor,
  398.                payee,
  399.                amount,
  400.                CASE
  401.                    WHEN pay_month LIKE '____-__-__' THEN pay_month
  402.                    WHEN pay_month LIKE '__/__/____' OR pay_month LIKE '_/__/____' OR pay_month LIKE '__/_/____' OR pay_month LIKE '_/_/____' THEN
  403.                        CASE
  404.                            WHEN LENGTH(pay_month) = 10 THEN strftime('%Y-%m-%d', substr(pay_month, 7, 4) || '-' || substr(pay_month, 1, 2) || '-' || substr(pay_month, 4, 2))
  405.                            WHEN LENGTH(pay_month) = 9 THEN strftime('%Y-%m-%d', substr(pay_month, 6, 4) || '-0' || substr(pay_month, 1, 1) || '-' || substr(pay_month, 3, 2))
  406.                            WHEN LENGTH(pay_month) = 8 THEN strftime('%Y-%m-%d', substr(pay_month, 5, 4) || '-' || substr(pay_month, 1, 2) || '-0' || substr(pay_month, 4, 1))
  407.                            ELSE strftime('%Y-%m-%d', substr(pay_month, 4, 4) || '-0' || substr(pay_month, 1, 1) || '-0' || substr(pay_month, 3, 1))
  408.                        END
  409.                    WHEN pay_month LIKE '___ __, ____' THEN strftime('%Y-%m-%d',
  410.                        substr(pay_month, -4, 4) || '-' ||
  411.                        CASE
  412.                            WHEN substr(pay_month, 1, 3) = 'Jan' THEN '01'
  413.                            WHEN substr(pay_month, 1, 3) = 'Feb' THEN '02'
  414.                            WHEN substr(pay_month, 1, 3) = 'Mar' THEN '03'
  415.                            WHEN substr(pay_month, 1, 3) = 'Apr' THEN '04'
  416.                            WHEN substr(pay_month, 1, 3) = 'May' THEN '05'
  417.                            WHEN substr(pay_month, 1, 3) = 'Jun' THEN '06'
  418.                            WHEN substr(pay_month, 1, 3) = 'Jul' THEN '07'
  419.                            WHEN substr(pay_month, 1, 3) = 'Aug' THEN '08'
  420.                            WHEN substr(pay_month, 1, 3) = 'Sep' THEN '09'
  421.                            WHEN substr(pay_month, 1, 3) = 'Oct' THEN '10'
  422.                            WHEN substr(pay_month, 1, 3) = 'Nov' THEN '11'
  423.                            WHEN substr(pay_month, 1, 3) = 'Dec' THEN '12'
  424.                            ELSE '01'
  425.                        END || '-' ||
  426.                        printf('%02d', CAST(trim(substr(pay_month, 5, 2)) AS INTEGER))
  427.                    )
  428.                    WHEN pay_month LIKE '__/__' THEN strftime('%Y-%m-%d', '20' || substr(pay_month, 4, 2) || '-' || substr(pay_month, 1, 2) || '-15')
  429.                    WHEN pay_month LIKE '____/__/__' THEN strftime('%Y-%m-%d', replace(pay_month, '/', '-'))
  430.                    WHEN pay_month LIKE '____-__' THEN pay_month || '-15'
  431.                    WHEN pay_month LIKE '__/__/__' THEN strftime('%Y-%m-%d', '20' || substr(pay_month, 7, 2) || '-' || substr(pay_month, 1, 2) || '-' || substr(pay_month, 4, 2))
  432.                    WHEN pay_month LIKE '__-__-____' OR pay_month LIKE '_-__-____' THEN
  433.                        strftime('%Y-%m-%d',
  434.                            substr(pay_month, -4) || '-' ||
  435.                            printf('%02d', CAST(substr(pay_month, 1, instr(pay_month, '-') - 1) AS INTEGER)) || '-' ||
  436.                            printf('%02d', CAST(substr(pay_month, instr(pay_month, '-') + 1, 2) AS INTEGER))
  437.                        )
  438.                    WHEN pay_month LIKE '__/____' OR pay_month LIKE '__-____' THEN
  439.                        strftime('%Y-%m-%d', substr(pay_month, 4, 4) || '-' || substr(pay_month, 1, 2) || '-15')
  440.                    WHEN pay_month LIKE '____/__' THEN
  441.                        strftime('%Y-%m-%d', substr(pay_month, 1, 4) || '-' || substr(pay_month, 6, 2) || '-15')
  442.                    WHEN pay_month LIKE '__-___-____' OR pay_month LIKE '_-___-____' THEN
  443.                        strftime('%Y-%m-%d',
  444.                            substr(pay_month, -4) || '-' ||
  445.                            CASE
  446.                                WHEN INSTR(UPPER(pay_month), '-JAN-') > 0 THEN '01'
  447.                                WHEN INSTR(UPPER(pay_month), '-FEB-') > 0 THEN '02'
  448.                                WHEN INSTR(UPPER(pay_month), '-MAR-') > 0 THEN '03'
  449.                                WHEN INSTR(UPPER(pay_month), '-APR-') > 0 THEN '04'
  450.                                WHEN INSTR(UPPER(pay_month), '-MAY-') > 0 THEN '05'
  451.                                WHEN INSTR(UPPER(pay_month), '-JUN-') > 0 THEN '06'
  452.                                WHEN INSTR(UPPER(pay_month), '-JUL-') > 0 THEN '07'
  453.                                WHEN INSTR(UPPER(pay_month), '-AUG-') > 0 THEN '08'
  454.                                WHEN INSTR(UPPER(pay_month), '-SEP-') > 0 THEN '09'
  455.                                WHEN INSTR(UPPER(pay_month), '-OCT-') > 0 THEN '10'
  456.                                WHEN INSTR(UPPER(pay_month), '-NOV-') > 0 THEN '11'
  457.                                WHEN INSTR(UPPER(pay_month), '-DEC-') > 0 THEN '12'
  458.                                ELSE '01'
  459.                            END || '-' ||
  460.                            printf('%02d', CAST(substr(pay_month, 1, instr(pay_month, '-') - 1) AS INTEGER))
  461.                        )
  462.                    ELSE NULL
  463.                END AS normalized_date
  464.            FROM jibs
  465.        ),
  466.        summary_jibs AS (
  467.            SELECT
  468.                payee,
  469.                STRFTIME('%Y-%m', normalized_date) AS normalized_month,
  470.                ROUND(SUM(1.0 * amount), 2) AS total_jib_amount
  471.            FROM standardize_date
  472.            WHERE payor = ?
  473.            GROUP BY payee, normalized_month
  474.        ),
  475.        summary_revenue AS (
  476.            SELECT
  477.                operator_purchaser,
  478.                STRFTIME('%Y-%m', check_date) AS revenue_month,
  479.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net_revenue
  480.            FROM revenue_raw
  481.            WHERE owner_name_client = ?
  482.              AND interest_type = 'jib net'
  483.            GROUP BY operator_purchaser, revenue_month
  484.        )
  485.        SELECT
  486.            COALESCE(op.name, sj.payee) AS operator_name,
  487.            sj.total_jib_amount AS jib_amount,
  488.            sr.total_share_net_revenue AS netted_amount,
  489.            CASE
  490.                WHEN sr.total_share_net_revenue IS NOT NULL
  491.                     AND ABS(sj.total_jib_amount + sr.total_share_net_revenue) < 0.01 THEN NULL
  492.                WHEN sr.total_share_net_revenue IS NULL THEN sj.total_jib_amount
  493.                ELSE ROUND(sj.total_jib_amount + sr.total_share_net_revenue, 2)
  494.            END AS difference,
  495.            sj.normalized_month AS month
  496.        FROM summary_jibs sj
  497.        LEFT JOIN summary_revenue sr
  498.            ON sj.payee = sr.operator_purchaser
  499.           AND sj.normalized_month = sr.revenue_month
  500.        LEFT JOIN operator op
  501.            ON LOWER(TRIM(op.canonical)) = LOWER(TRIM(sj.payee))
  502.        ORDER BY operator_name, month;
  503.    "#;
  504.  
  505.     let rows = query_as::<_, DashboardJibsRow>(query)
  506.         .bind(client_canonical)
  507.         .bind(client_canonical)
  508.         .fetch_all(pool)
  509.         .await
  510.         .map_err(|e| leptos::ServerFnError::new(format!("Database error: {}", e)))?;
  511.  
  512.     Ok(rows)
  513. }
  514.  
  515. #[server]
  516. pub async fn dashboardjibs_fetch_all(
  517.     client_canonical: String,
  518. ) -> Result<Vec<DashboardJibsRow>, ServerFnError> {
  519.     #[cfg(feature = "ssr")]
  520.     {
  521.         let pool = crate::state::ssr::app_pools()?.land_pool;
  522.         return get_dashboard_jibs_data(&pool, &client_canonical).await;
  523.     }
  524.  
  525.     #[cfg(not(feature = "ssr"))]
  526.     {
  527.         Err(ServerFnError::new("This function is only available on the server."))
  528.     }
  529. }
  530.  
  531. ================
  532. File: gmm_client/src/tables/dashboardjibs/resource.rs
  533. ================
  534. use leptos::*;
  535. use crate::client_main_app::ctx::*;
  536. use crate::tables::dashboardjibs::query::{DashboardJibsRow, dashboardjibs_fetch_all};
  537.  
  538. /// Leptos resource for fetching JIB vs revenue netting for dashboard display.
  539. #[derive(Clone)]
  540. pub(crate) struct DashboardJibsResource {
  541.     pub rows: Resource<String, Result<Vec<DashboardJibsRow>, ServerFnError>>,
  542. }
  543.  
  544. impl DashboardJibsResource {
  545.     pub fn new() -> Self {
  546.         let rows = create_resource(
  547.             move || {
  548.                 let account_ctx = AccountCtx::use_context();
  549.                 account_ctx
  550.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  551.                     .unwrap_or_default()
  552.             },
  553.             |canonical_name| async move {
  554.                 dashboardjibs_fetch_all(canonical_name)
  555.                     .await
  556.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  557.             },
  558.         );
  559.  
  560.         Self { rows }
  561.     }
  562. }
  563.  
  564. ================
  565. File: gmm_client/src/tables/dashboardrevenue/mod.rs
  566. ================
  567. pub mod query;
  568. pub mod resource;
  569.  
  570. ================
  571. File: gmm_client/src/tables/dashboardrevenue/query.rs
  572. ================
  573. use leptos::*;
  574. use serde::{Deserialize, Serialize};
  575.  
  576. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
  577. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  578. pub struct DashboardRevenueRow {
  579.     pub operator_purchaser: String,
  580.     pub gross_revenue: Option<f64>,
  581.     pub taxes: Option<f64>,
  582.     pub deductions: Option<f64>,
  583.     pub net_revenue: Option<f64>,
  584.     pub payment_amount: Option<f64>,
  585.     pub payment_date: String,
  586. }
  587.  
  588. #[cfg(feature = "ssr")]
  589. use sqlx::{SqlitePool, query_as};
  590.  
  591. #[cfg(feature = "ssr")]
  592. pub async fn get_dashboard_revenue_data(
  593.     pool: &SqlitePool,
  594.     client_canonical: &str,
  595. ) -> Result<Vec<DashboardRevenueRow>, leptos::ServerFnError> {
  596.     let query = r#"
  597.        SELECT
  598.            operator_purchaser,
  599.            SUM(1.0 * share_gross_revenue) AS gross_revenue,
  600.            SUM(share_taxes) AS taxes,
  601.            SUM(share_deductions) AS deductions,
  602.            SUM(1.0 * share_net_revenue) AS net_revenue,
  603.            1.0 * share_check_amount AS payment_amount,
  604.            check_date AS payment_date
  605.        FROM
  606.            revenue_raw
  607.        WHERE
  608.            owner_name_client = ?
  609.            AND aggregation_level IN ('e', 'h')
  610.            AND check_date >= date('now', '-1 month')
  611.            AND check_date < date('now')
  612.        GROUP BY    
  613.            operator_purchaser,
  614.            check_date,
  615.            share_check_amount,
  616.            check_reference_number
  617.        ORDER BY
  618.            operator_purchaser ASC,
  619.            check_date ASC;
  620.    "#;
  621.  
  622.     let rows = query_as::<_, DashboardRevenueRow>(query)
  623.         .bind(client_canonical)
  624.         .fetch_all(pool)
  625.         .await
  626.         .map_err(|e| leptos::ServerFnError::new(format!("Database error: {}", e)))?;
  627.  
  628.     Ok(rows)
  629. }
  630.  
  631. #[server]
  632. pub async fn dashboardrevenue_fetch_all(
  633.     client_canonical: String,
  634. ) -> Result<Vec<DashboardRevenueRow>, ServerFnError> {
  635.     #[cfg(feature = "ssr")]
  636.     {
  637.         let pool = crate::state::ssr::app_pools()?.land_pool;
  638.         return crate::tables::dashboardrevenue::query::get_dashboard_revenue_data(&pool, &client_canonical).await;
  639.     }
  640.  
  641.     #[cfg(not(feature = "ssr"))]
  642.     {
  643.         Err(ServerFnError::new("This function is only available on the server."))
  644.     }
  645. }
  646.  
  647. ================
  648. File: gmm_client/src/tables/dashboardrevenue/resource.rs
  649. ================
  650. use leptos::*;
  651. use crate::client_main_app::ctx::*;
  652. use crate::tables::dashboardrevenue::query::{DashboardRevenueRow, dashboardrevenue_fetch_all};
  653.  
  654. /// Leptos resource for fetching recent dashboard revenue data.
  655. #[derive(Clone)]
  656. pub(crate) struct DashboardRevenueResource {
  657.     pub rows: Resource<String, Result<Vec<DashboardRevenueRow>, ServerFnError>>,
  658. }
  659.  
  660. impl DashboardRevenueResource {
  661.     pub fn new() -> Self {
  662.         let rows = create_resource(
  663.             move || {
  664.                 let account_ctx = AccountCtx::use_context();
  665.                 account_ctx
  666.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  667.                     .unwrap_or_default()
  668.             },
  669.             |canonical_name| async move {
  670.                 dashboardrevenue_fetch_all(canonical_name)
  671.                     .await
  672.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  673.             },
  674.         );
  675.  
  676.         Self { rows }
  677.     }
  678. }
  679.  
  680. ================
  681. File: gmm_client/src/tables/dashboardtotalreportedpayments/mod.rs
  682. ================
  683. pub mod query;
  684. pub mod resource;
  685.  
  686. ================
  687. File: gmm_client/src/tables/dashboardtotalreportedpayments/query.rs
  688. ================
  689. use leptos::*;
  690. use serde::{Deserialize, Serialize};
  691.  
  692. #[derive(Debug, Clone, Serialize, Deserialize)]
  693. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  694. pub struct DashboardTotalReportedPaymentsRow {
  695.     pub total: f64,
  696.     pub count: u8,
  697.     pub year_month: String,
  698. }
  699.  
  700. #[cfg(feature = "ssr")]
  701. use sqlx::{SqlitePool, query_as};
  702.  
  703. #[cfg(feature = "ssr")]
  704. pub async fn get_dashboard_total_reported_payments(
  705.     pool: &SqlitePool,
  706.     client_canonical: &str,
  707. ) -> Result<DashboardTotalReportedPaymentsRow, leptos::ServerFnError> {
  708.     let query = r#"
  709.        SELECT
  710.            SUM(1.0 * share_check_amount) * 1.0 AS total,
  711.            COUNT(*) AS count,
  712.            strftime('%Y-%m', 'now', '-1 month') AS year_month
  713.        FROM (
  714.            SELECT DISTINCT operator_purchaser, check_date, share_check_amount
  715.            FROM revenue_raw
  716.            WHERE
  717.                owner_name_client = ? AND
  718.                check_date >= date('now', '-1 month', 'start of month') AND
  719.                check_date < date('now', 'start of month')
  720.            );
  721.    "#;
  722.  
  723.     let row = query_as::<_, DashboardTotalReportedPaymentsRow>(query)
  724.         .bind(client_canonical)
  725.         .fetch_one(pool)
  726.         .await
  727.         .map_err(|e| leptos::ServerFnError::new(format!("Database error: {}", e)))?;
  728.  
  729.     Ok(row)
  730. }
  731.  
  732. #[server]
  733. pub async fn dashboard_total_reported_payments_fetch(
  734.     client_canonical: String,
  735. ) -> Result<DashboardTotalReportedPaymentsRow, ServerFnError> {
  736.     #[cfg(feature = "ssr")]
  737.     {
  738.         let pool = crate::state::ssr::app_pools()?.land_pool;
  739.         crate::tables::dashboardtotalreportedpayments::query::get_dashboard_total_reported_payments(&pool, &client_canonical).await
  740.     }
  741.  
  742.     #[cfg(not(feature = "ssr"))]
  743.     {
  744.         Err(ServerFnError::new("This function is only available on the server."))
  745.     }
  746. }
  747.  
  748. ================
  749. File: gmm_client/src/tables/dashboardtotalreportedpayments/resource.rs
  750. ================
  751. use leptos::*;
  752. use crate::client_main_app::ctx::*;
  753. use crate::tables::dashboardtotalreportedpayments::query::{DashboardTotalReportedPaymentsRow, dashboard_total_reported_payments_fetch};
  754.  
  755. /// Leptos resource for fetching recent dashboard revenue data.
  756. #[derive(Clone)]
  757. pub(crate) struct DashboardTotalReportedPaymentsResource {
  758.     pub row: Resource<String, Result<DashboardTotalReportedPaymentsRow, ServerFnError>>,
  759. }
  760.  
  761. impl DashboardTotalReportedPaymentsResource {
  762.     pub fn new() -> Self {
  763.         let row = create_resource(
  764.             move || {
  765.                 let account_ctx = AccountCtx::use_context();
  766.                 account_ctx
  767.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  768.                     .unwrap_or_default()
  769.             },
  770.             |canonical_name| async move {
  771.                 dashboard_total_reported_payments_fetch(canonical_name)
  772.                     .await
  773.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  774.             },
  775.         );
  776.  
  777.         Self { row }
  778.     }
  779. }
  780.  
  781. ================
  782. File: gmm_client/src/tables/incominglocation/mod.rs
  783. ================
  784. pub(crate) mod query;
  785. pub(crate) mod resource;
  786.  
  787. ================
  788. File: gmm_client/src/tables/incominglocation/query.rs
  789. ================
  790. use leptos::*;
  791. use serde::{Deserialize, Serialize};
  792.  
  793. /// Represents a row in the incoming location report.
  794. #[derive(Debug, Clone, Serialize, Deserialize)]
  795. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  796. pub struct IncomingLocationRow {
  797.     pub owner_name_client: String,
  798.     pub state: Option<String>,
  799.     pub county: Option<String>,
  800.     pub gross_revenue: Option<f64>,
  801.     pub taxes: Option<f64>,
  802.     pub deductions: Option<f64>,
  803.     pub net_revenue: Option<f64>,
  804.     pub payment_date: Option<String>,
  805. }
  806.  
  807. /// Fetches incoming location data from `revenue_raw` by `canonical_name`.
  808. #[server]
  809. pub async fn incominglocation_fetch_by_canonical_name(
  810.     canonical_name: String,
  811. ) -> Result<Vec<IncomingLocationRow>, ServerFnError> {
  812.     pub use IncomingLocationRow;
  813.  
  814.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  815.  
  816.     let records = sqlx::query_as::<_, IncomingLocationRow>(
  817.         "SELECT
  818.            owner_name_client,
  819.            state,
  820.            county,
  821.            ROUND(SUM(1.0 * share_gross_revenue), 2) AS gross_revenue,
  822.            ROUND(SUM(share_taxes), 2) AS taxes,
  823.            ROUND(SUM(share_deductions), 2) AS deductions,
  824.            ROUND(SUM(1.0 * share_net_revenue), 2) AS net_revenue,
  825.            strftime('%Y-%m', check_date) AS payment_date
  826.        FROM
  827.            revenue_raw
  828.        WHERE
  829.            aggregation_level IN ('i', 'e', 'h')
  830.        AND
  831.            owner_name_client = ?
  832.        GROUP BY
  833.            state,
  834.            county,
  835.            strftime('%Y-%m', check_date)
  836.        ORDER BY
  837.            payment_date ASC,
  838.            state ASC,
  839.            county ASC"
  840.     )
  841.     .bind(&canonical_name)
  842.     .fetch_all(&land_pool)
  843.     .await
  844.     // log successful row count, then pass rows through
  845.     .map(|rows| {
  846.         log::debug!("Query succeeded: {} rows", rows.len());
  847.         rows
  848.     })
  849.     .map_err(|e| {
  850.         log::error!("Query failed: {}", e);
  851.         ServerFnError::new(format!("Database error: {}", e))
  852.     })?;
  853.  
  854.     Ok(records)
  855. }
  856.  
  857. ================
  858. File: gmm_client/src/tables/incominglocation/resource.rs
  859. ================
  860. use super::query::IncomingLocationRow;
  861. use crate::client_main_app::ctx::*;
  862. use leptos::*;
  863.  
  864. /// Leptos resource for fetching incoming location data.
  865. #[derive(Clone)]
  866. pub(crate) struct IncomingLocationResource {
  867.     pub revenue_rows: Resource<String, Result<Vec<IncomingLocationRow>, ServerFnError>>,
  868. }
  869.  
  870. use super::query::*;
  871. impl IncomingLocationResource {
  872.     pub fn new() -> Self {
  873.         let revenue_rows = create_resource(
  874.             move || {
  875.                 let account_ctx = AccountCtx::use_context();
  876.                 account_ctx
  877.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  878.                     .unwrap_or_default()
  879.             },
  880.             |canonical_name| async move {
  881.                 incominglocation_fetch_by_canonical_name(canonical_name)
  882.                     .await
  883.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  884.                 // Fixed conversion
  885.             },
  886.         );
  887.  
  888.         Self { revenue_rows }
  889.     }
  890. }
  891.  
  892. ================
  893. File: gmm_client/src/tables/incomingproducts/mod.rs
  894. ================
  895. pub(crate) mod query;
  896. pub(crate) mod resource;
  897.  
  898. ================
  899. File: gmm_client/src/tables/incomingproducts/query.rs
  900. ================
  901. use leptos::*;
  902. use serde::{Deserialize, Serialize};
  903.  
  904. /// Represents a row in the incoming products report.
  905. #[derive(Debug, Clone, Serialize, Deserialize)]
  906. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  907. pub struct IncomingProductsRow {
  908.     pub owner_name_client: String,
  909.     pub product: Option<String>,
  910.     pub gross_revenue: Option<f64>,
  911.     pub taxes: Option<f64>,
  912.     pub deductions: Option<f64>,
  913.     pub net_revenue: Option<f64>,
  914.     pub payment_date: Option<String>,
  915. }
  916.  
  917. /// Fetches incoming products data from `revenue_raw` by `canonical_name`.
  918. #[server]
  919. pub async fn incomingproducts_fetch_by_canonical_name(
  920.     canonical_name: String,
  921. ) -> Result<Vec<IncomingProductsRow>, ServerFnError> {
  922.     pub use IncomingProductsRow;
  923.  
  924.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  925.  
  926.     let records = sqlx::query_as::<_, IncomingProductsRow>(
  927.         "SELECT
  928.            owner_name_client,
  929.            product,
  930.            ROUND(SUM(1.0 * share_gross_revenue), 2) AS gross_revenue,
  931.            ROUND(SUM(share_taxes), 2) AS taxes,
  932.            ROUND(SUM(share_deductions), 2) AS deductions,
  933.            ROUND(SUM(1.0 * share_net_revenue), 2) AS net_revenue,
  934.            strftime('%Y-%m', check_date) AS payment_date
  935.        FROM
  936.            revenue_raw
  937.        WHERE
  938.            aggregation_level IN ('i', 'e', 'h')
  939.        AND
  940.            owner_name_client = ?
  941.        GROUP BY
  942.            product,
  943.            strftime('%Y-%m', check_date)
  944.        ORDER BY
  945.            payment_date ASC,
  946.            product ASC"
  947.     )
  948.     .bind(&canonical_name)
  949.     .fetch_all(&land_pool)
  950.     .await
  951.     // log successful row count, then pass rows through
  952.     .map(|rows| {
  953.         log::debug!("Query succeeded: {} rows", rows.len());
  954.         rows
  955.     })
  956.     .map_err(|e| {
  957.         log::error!("Query failed: {}", e);
  958.         ServerFnError::new(format!("Database error: {}", e))
  959.     })?;
  960.  
  961.     Ok(records)
  962. }
  963.  
  964. ================
  965. File: gmm_client/src/tables/incomingproducts/resource.rs
  966. ================
  967. use super::query::IncomingProductsRow;
  968. use crate::client_main_app::ctx::*;
  969. use leptos::*;
  970.  
  971. /// Leptos resource for fetching incoming products data.
  972. #[derive(Clone)]
  973. pub(crate) struct IncomingProductsResource {
  974.     pub revenue_rows: Resource<String, Result<Vec<IncomingProductsRow>, ServerFnError>>,
  975. }
  976.  
  977. use super::query::*;
  978. impl IncomingProductsResource {
  979.     pub fn new() -> Self {
  980.         let revenue_rows = create_resource(
  981.             move || {
  982.                 let account_ctx = AccountCtx::use_context();
  983.                 account_ctx
  984.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  985.                     .unwrap_or_default()
  986.             },
  987.             |canonical_name| async move {
  988.                 incomingproducts_fetch_by_canonical_name(canonical_name)
  989.                     .await
  990.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  991.                 // Fixed conversion
  992.             },
  993.         );
  994.  
  995.         Self { revenue_rows }
  996.     }
  997. }
  998.  
  999. ================
  1000. File: gmm_client/src/tables/incomingtable1/mod.rs
  1001. ================
  1002. pub(crate) mod query;
  1003. pub(crate) mod resource;
  1004.  
  1005. ================
  1006. File: gmm_client/src/tables/incomingtable1/query.rs
  1007. ================
  1008. use leptos::*;
  1009. use serde::{Deserialize, Serialize};
  1010.  
  1011. /// Represents a row in the incoming table report.
  1012. #[derive(Debug, Clone, Serialize, Deserialize)]
  1013. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  1014. pub struct IncomingTable1Row {
  1015.     pub owner_name_client: String,
  1016.     pub operator_name: String,
  1017.     pub gross_revenue: Option<f64>,
  1018.     pub taxes: Option<f64>,
  1019.     pub deductions: Option<f64>,
  1020.     pub net_revenue: Option<f64>,
  1021.     pub payment_amount: Option<f64>,
  1022.     pub payment_date: Option<String>,
  1023.     pub depletion_15: Option<f64>,
  1024.     pub net_post_depletion_15: Option<f64>,
  1025.     pub depletion_275: Option<f64>,
  1026.     pub net_post_depletion_275: Option<f64>,
  1027. }
  1028.  
  1029. /// Fetches incoming table data from `revenue_raw` by `canonical_name`.
  1030. #[server]
  1031. pub async fn incomingtable1_fetch_by_canonical_name(
  1032.     canonical_name: String,
  1033. ) -> Result<Vec<IncomingTable1Row>, ServerFnError> {
  1034.     pub use IncomingTable1Row;
  1035.  
  1036.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1037.  
  1038.     let records = sqlx::query_as::<_, IncomingTable1Row>(
  1039.         "SELECT
  1040.                rr.owner_name_client,
  1041.                o.name AS operator_name,
  1042.                ROUND(SUM(1.0 * rr.share_gross_revenue), 2) AS gross_revenue,
  1043.                ROUND(SUM(rr.share_taxes), 2) AS taxes,
  1044.                ROUND(SUM(rr.share_deductions), 2) AS deductions,
  1045.                ROUND(SUM(1.0 * rr.share_net_revenue), 2) AS net_revenue,
  1046.                1.0 * rr.share_check_amount AS payment_amount,
  1047.                rr.check_date AS payment_date,
  1048.                ROUND(SUM(rr.share_gross_revenue * 0.15), 2) AS depletion_15,
  1049.                ROUND(SUM(rr.share_gross_revenue - (rr.share_gross_revenue * 0.15)), 2) AS net_post_depletion_15,
  1050.                ROUND(SUM(rr.share_gross_revenue * 0.275), 2) AS depletion_275,
  1051.                ROUND(SUM(rr.share_gross_revenue - (rr.share_gross_revenue * 0.275)), 2) AS net_post_depletion_275
  1052.            FROM
  1053.                revenue_raw rr
  1054.            JOIN
  1055.                operator o ON o.canonical = rr.operator_purchaser
  1056.            WHERE
  1057.                rr.aggregation_level = 'i'
  1058.                AND rr.owner_name_client = ?
  1059.            GROUP BY
  1060.                rr.owner_name_client,
  1061.                o.name,
  1062.                rr.check_date,
  1063.                rr.share_check_amount,
  1064.                rr.check_reference_number
  1065.            ORDER BY
  1066.                operator_name ASC,
  1067.                rr.check_date ASC"
  1068.     )
  1069.     .bind(&canonical_name)
  1070.     .fetch_all(&land_pool)
  1071.     .await
  1072.     // log successful row count, then pass rows through
  1073.     .map(|rows| {
  1074.         log::debug!("Query succeeded: {} rows", rows.len());
  1075.         rows
  1076.     })
  1077.     .map_err(|e| {
  1078.         log::error!("Query failed: {}", e);
  1079.         ServerFnError::new(format!("Database error: {}", e))
  1080.     })?;
  1081.  
  1082.     Ok(records)
  1083. }
  1084.  
  1085. ================
  1086. File: gmm_client/src/tables/incomingtable1/resource.rs
  1087. ================
  1088. use super::query::IncomingTable1Row;
  1089. use crate::client_main_app::ctx::*;
  1090. use leptos::*;
  1091.  
  1092. /// Leptos resource for fetching incoming table data.
  1093. #[derive(Clone)]
  1094. pub(crate) struct IncomingTable1Resource {
  1095.     pub revenue_rows: Resource<String, Result<Vec<IncomingTable1Row>, ServerFnError>>,
  1096. }
  1097.  
  1098. use super::query::*;
  1099. impl IncomingTable1Resource {
  1100.     pub fn new() -> Self {
  1101.         let revenue_rows = create_resource(
  1102.             move || {
  1103.                 let account_ctx = AccountCtx::use_context();
  1104.                 account_ctx
  1105.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  1106.                     .unwrap_or_default()
  1107.             },
  1108.             |canonical_name| async move {
  1109.                 incomingtable1_fetch_by_canonical_name(canonical_name)
  1110.                     .await
  1111.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  1112.                 // Fixed conversion
  1113.             },
  1114.         );
  1115.  
  1116.         Self { revenue_rows }
  1117.     }
  1118. }
  1119.  
  1120. ================
  1121. File: gmm_client/src/tables/incomingtable2/mod.rs
  1122. ================
  1123. pub(crate) mod query;
  1124. pub(crate) mod resource;
  1125.  
  1126. ================
  1127. File: gmm_client/src/tables/incomingtable2/query.rs
  1128. ================
  1129. use leptos::*;
  1130. use serde::{Deserialize, Serialize};
  1131.  
  1132. #[derive(Debug, Clone, Serialize, Deserialize)]
  1133. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  1134. pub struct IncomingTable2Row {
  1135.     pub owner_name_client: String,
  1136.     pub operator_name: String,
  1137.     pub description: String,
  1138.     pub gross_revenue: Option<f64>,
  1139.     pub taxes: Option<f64>,
  1140.     pub deductions: Option<f64>,
  1141.     pub net_revenue: Option<f64>,
  1142.     pub payment_amount: Option<f64>,
  1143.     pub payment_date: Option<String>,
  1144. }
  1145.  
  1146. #[server]
  1147. pub async fn incomingtable2_fetch_by_canonical_name(
  1148.     canonical_name: String,
  1149. ) -> Result<Vec<IncomingTable2Row>, ServerFnError> {
  1150.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1151.  
  1152.     let records = sqlx::query_as::<_, IncomingTable2Row>(
  1153.         "SELECT
  1154.                rr.owner_name_client,
  1155.                o.name AS operator_name,
  1156.                rr.well_property_name AS description,
  1157.                ROUND(SUM(1.0 * rr.share_gross_revenue), 2) AS gross_revenue,
  1158.                ROUND(SUM(rr.share_taxes), 2) AS taxes,
  1159.                ROUND(SUM(rr.share_deductions), 2) AS deductions,
  1160.                ROUND(SUM(1.0 * rr.share_net_revenue), 2) AS net_revenue,
  1161.                1.0 * rr.share_check_amount AS payment_amount,
  1162.                rr.check_date AS payment_date
  1163.            FROM
  1164.                revenue_raw rr
  1165.            JOIN
  1166.                operator o ON o.canonical = rr.operator_purchaser
  1167.            WHERE
  1168.                rr.aggregation_level IN ('e', 'h')
  1169.                AND rr.owner_name_client = ?
  1170.            GROUP BY
  1171.                o.name,
  1172.                rr.well_property_name,
  1173.                rr.check_date,
  1174.                rr.share_check_amount,
  1175.                rr.check_reference_number
  1176.            ORDER BY
  1177.                operator_name ASC,
  1178.                rr.check_date ASC"
  1179.     )
  1180.     .bind(&canonical_name)
  1181.     .fetch_all(&land_pool)
  1182.     .await
  1183.     // log successful row count, then pass rows through
  1184.     .map(|rows| {
  1185.         log::debug!("Query succeeded: {} rows", rows.len());
  1186.         rows
  1187.     })
  1188.     .map_err(|e| {
  1189.         log::error!("Query failed: {}", e);
  1190.         ServerFnError::new(format!("Database error: {}", e))
  1191.     })?;
  1192.  
  1193.     Ok(records)
  1194. }
  1195.  
  1196. ================
  1197. File: gmm_client/src/tables/incomingtable2/resource.rs
  1198. ================
  1199. use super::query::IncomingTable2Row;
  1200. use crate::client_main_app::ctx::*;
  1201. use leptos::*;
  1202.  
  1203. /// Leptos resource for fetching incoming table 2 data.
  1204. #[derive(Clone)]
  1205. pub(crate) struct IncomingTable2Resource {
  1206.     pub rows: Resource<String, Result<Vec<IncomingTable2Row>, ServerFnError>>,
  1207. }
  1208.  
  1209. use super::query::*;
  1210. impl IncomingTable2Resource {
  1211.     pub fn new() -> Self {
  1212.         let rows = create_resource(
  1213.             move || {
  1214.                 let account_ctx = AccountCtx::use_context();
  1215.                 account_ctx
  1216.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  1217.                     .unwrap_or_default()
  1218.             },
  1219.             |canonical_name| async move {
  1220.                 incomingtable2_fetch_by_canonical_name(canonical_name)
  1221.                     .await
  1222.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  1223.             },
  1224.         );
  1225.  
  1226.         Self { rows }
  1227.     }
  1228. }
  1229.  
  1230. ================
  1231. File: gmm_client/src/tables/iwv_qc_queries/incomingtables/mod.rs
  1232. ================
  1233. pub(crate) mod query;
  1234. pub(crate) mod resource;
  1235.  
  1236. ================
  1237. File: gmm_client/src/tables/iwv_qc_queries/incomingtables/query.rs
  1238. ================
  1239. use leptos::*;
  1240. use serde::{Deserialize, Serialize};
  1241.  
  1242. /// Represents a row in the payment discrepancy report.
  1243. #[derive(Debug, Clone, Serialize, Deserialize)]
  1244. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  1245. pub struct PaymentDiscrepancyRow {
  1246.     pub owner_name_client: String,
  1247.     pub operator_purchaser: String,
  1248.     pub gross_revenue: Option<f64>,
  1249.     pub taxes: Option<f64>,
  1250.     pub deductions: Option<f64>,
  1251.     pub net_revenue: Option<f64>,
  1252.     pub payment_amount: Option<f64>,
  1253.     pub difference: Option<f64>,
  1254.     pub payment_date: Option<String>,
  1255.     pub issues: Option<String>,
  1256. }
  1257.  
  1258. /// Fetches payment discrepancy data by canonical name.
  1259. #[server]
  1260. pub async fn paymentdiscrepancy_fetch_by_canonical_name(
  1261.     canonical_name: String,
  1262. ) -> Result<Vec<PaymentDiscrepancyRow>, ServerFnError> {
  1263.     pub use PaymentDiscrepancyRow;
  1264.  
  1265.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1266.  
  1267.     let query = r#"
  1268.        SELECT
  1269.            owner_name_client,
  1270.            operator_purchaser,
  1271.            gross_revenue,
  1272.            taxes,
  1273.            deductions,
  1274.            net_revenue,
  1275.            payment_amount,
  1276.            ABS(net_revenue - payment_amount) AS difference,
  1277.            payment_date,
  1278.            CASE
  1279.                WHEN owner_name_client = 'paul.c.bundy.interests.llc'
  1280.                     AND operator_purchaser = 'own.resources'
  1281.                THEN 'known discrepancy from operator'
  1282.                WHEN net_revenue = 0 THEN 'no net revenue provided by operator'
  1283.                WHEN ROUND(ABS(net_revenue - payment_amount), 1) = ROUND(payment_amount, 1)
  1284.                THEN 'possible duplicate'
  1285.                ELSE NULL
  1286.            END AS issues
  1287.        FROM (
  1288.            SELECT
  1289.                owner_name_client,
  1290.                operator_purchaser,
  1291.                ROUND(SUM(1.0 * share_gross_revenue), 2) AS gross_revenue,
  1292.                ROUND(SUM(1.0 * share_taxes), 2) AS taxes,
  1293.                ROUND(SUM(1.0 * share_deductions), 2) AS deductions,
  1294.                ROUND(SUM(1.0 * share_net_revenue), 2) AS net_revenue,
  1295.                1.0 * share_check_amount AS payment_amount,
  1296.                check_date AS payment_date
  1297.            FROM
  1298.                revenue_raw
  1299.            WHERE
  1300.                aggregation_level IN ('i', 'e', 'h')
  1301.            AND
  1302.                owner_name_client = ?
  1303.            GROUP BY
  1304.                operator_purchaser,
  1305.                check_date,
  1306.                share_check_amount,
  1307.                check_reference_number
  1308.        ) AS aggregated_results
  1309.        WHERE
  1310.            ABS(net_revenue - payment_amount) > 0.01
  1311.        ORDER BY
  1312.            operator_purchaser,
  1313.            payment_date DESC
  1314.    "#;
  1315.  
  1316.     let records = sqlx::query_as::<_, PaymentDiscrepancyRow>(query)
  1317.         .bind(&canonical_name)
  1318.         .fetch_all(&land_pool)
  1319.         .await
  1320.         // log successful row count, then pass rows through
  1321.         .map(|rows| {
  1322.             log::debug!("Query succeeded: {} rows", rows.len());
  1323.             rows
  1324.         })
  1325.         .map_err(|e| {
  1326.             log::error!("Query failed: {}", e);
  1327.             ServerFnError::new(format!("Database error: {}", e))
  1328.         })?;
  1329.  
  1330.     Ok(records)
  1331. }
  1332.  
  1333. ================
  1334. File: gmm_client/src/tables/iwv_qc_queries/incomingtables/resource.rs
  1335. ================
  1336. use leptos::*;
  1337. use super::query::PaymentDiscrepancyRow;
  1338. use crate::client_main_app::ctx::*;
  1339.  
  1340. /// Leptos resource for fetching payment discrepancy data.
  1341. #[derive(Clone)]
  1342. pub(crate) struct PaymentDiscrepancyResource {
  1343.     pub rows: Resource<String, Result<Vec<PaymentDiscrepancyRow>, ServerFnError>>,
  1344. }
  1345.  
  1346. use super::query::*;
  1347. impl PaymentDiscrepancyResource {
  1348.     pub fn new() -> Self {
  1349.         let rows = create_resource(
  1350.             move || {
  1351.                 let account_ctx = AccountCtx::use_context();
  1352.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  1353.             },
  1354.             |canonical_name| async move {
  1355.                 paymentdiscrepancy_fetch_by_canonical_name(canonical_name)
  1356.                     .await
  1357.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  1358.             }
  1359.         );
  1360.  
  1361.         Self { rows }
  1362.     }
  1363. }
  1364.  
  1365. ================
  1366. File: gmm_client/src/tables/iwv_qc_queries/taxyearrev1099/mod.rs
  1367. ================
  1368. pub(crate) mod query;
  1369. pub(crate) mod resource;
  1370.  
  1371. ================
  1372. File: gmm_client/src/tables/iwv_qc_queries/taxyearrev1099/query.rs
  1373. ================
  1374. use leptos::*;
  1375. use serde::{Deserialize, Serialize};
  1376. use sqlx::FromRow;
  1377. use sqlx::query_as;
  1378.  
  1379. /// Represents a row in the Tax Year Revenue vs 1099 comparison report.
  1380. #[derive(Debug, Clone, Serialize, Deserialize)]
  1381. #[cfg_attr(feature = "ssr", derive(FromRow))]
  1382. pub struct TaxYearRev1099Row {
  1383.     pub client: String,
  1384.     pub operator: String,
  1385.     pub gross_revenue: Option<f64>,
  1386.     pub taxes: Option<f64>,
  1387.     pub deducts: Option<f64>,
  1388.     pub net_revenue: Option<f64>,
  1389.     pub amount_1099: Option<f64>,
  1390.     pub difference_dollars: Option<f64>,
  1391.     pub difference_percent: Option<f64>,
  1392.     pub material_difference: Option<String>,
  1393. }
  1394.  
  1395. /// Fetches the tax year revenue and 1099 comparison data.
  1396. #[server]
  1397. pub async fn taxyearrev1099_fetch_all() -> Result<Vec<TaxYearRev1099Row>, ServerFnError> {
  1398.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1399.  
  1400.     let query = r#"
  1401.    SELECT
  1402.        client,
  1403.        operator,
  1404.        ROUND(share_gross_revenue, 2) AS gross_revenue,
  1405.        ROUND(share_taxes, 2) AS taxes,
  1406.        ROUND(share_deductions, 2) AS deducts,
  1407.        ROUND(share_net_revenue, 2) AS net_revenue,
  1408.        ROUND(reported_amount, 2) AS amount_1099,
  1409.        ROUND(difference_dollars, 2) AS difference_dollars,
  1410.        CASE
  1411.            WHEN ROUND(SUM(difference_dollars)) IS NULL OR ROUND(SUM(difference_dollars)) = 0 THEN NULL
  1412.            ELSE ROUND(
  1413.                CASE
  1414.                    WHEN share_net_revenue = 0 THEN NULL
  1415.                    ELSE ROUND((difference_dollars * 100.0) / share_net_revenue, 2)
  1416.                END, 2
  1417.            )
  1418.        END AS difference_percent,
  1419.        CASE
  1420.            WHEN ROUND(SUM(difference_dollars)) = 0 THEN NULL
  1421.            ELSE CASE
  1422.                WHEN SUM(reported_amount) IS NULL OR SUM(reported_amount) = 0 THEN 'Outstanding 1099'
  1423.                WHEN (share_gross_revenue IS NULL OR share_gross_revenue = 0)
  1424.                     AND (share_taxes IS NULL OR share_taxes = 0)
  1425.                     AND (share_deductions IS NULL OR share_deductions = 0)
  1426.                     AND (share_net_revenue IS NULL OR share_net_revenue = 0) THEN 'Outstanding Revenue'
  1427.                WHEN share_gross_revenue = SUM(reported_amount) OR share_net_revenue = SUM(reported_amount) THEN ''
  1428.                WHEN (ABS(SUM(difference_dollars)) * 100.0) / NULLIF(share_net_revenue, 0) < 25 THEN 'No'
  1429.                ELSE 'Yes'
  1430.            END
  1431.        END AS material_difference
  1432.    FROM (
  1433.        SELECT * FROM (
  1434.            SELECT
  1435.                COALESCE(rr.payee, i.payee) AS client,
  1436.                CASE
  1437.                    WHEN rr.share_net_revenue < 600 THEN COALESCE(rr.operator_purchaser, i.operator) || '*'
  1438.                    ELSE COALESCE(rr.operator_purchaser, i.operator)
  1439.                END AS operator,
  1440.                1.0 * rr.share_gross_revenue AS share_gross_revenue,
  1441.                1.0 * rr.share_taxes AS share_taxes,
  1442.                1.0 * rr.share_deductions AS share_deductions,
  1443.                1.0 * rr.share_net_revenue AS share_net_revenue,
  1444.                ROUND(SUM(1.0 * i.reported_amount), 2) AS reported_amount,
  1445.                ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) AS difference_dollars,
  1446.                CASE
  1447.                    WHEN 1.0 * rr.share_net_revenue = 0 THEN NULL
  1448.                    ELSE (ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) * 100.0) / (1.0 * rr.share_net_revenue)
  1449.                END AS difference_percent,
  1450.                1 AS source_table
  1451.            FROM
  1452.                (SELECT DISTINCT
  1453.                    payee,
  1454.                    payor AS operator,
  1455.                    1.0 * REPLACE(REPLACE(reported_amount, '$', ''), ',', '') AS reported_amount,
  1456.                    tax_year
  1457.                 FROM items1099
  1458.                 WHERE
  1459.                   payee = ?
  1460.                   AND tax_year = 2024
  1461.                   AND box_name NOT LIKE '%withheld%'
  1462.                   AND box_number NOT LIKE 'nil'
  1463.                ) AS i
  1464.            LEFT JOIN
  1465.                (SELECT
  1466.                    owner_name_client AS payee,
  1467.                    operator_purchaser,
  1468.                    ROUND(SUM(1.0 * share_gross_revenue), 2) AS share_gross_revenue,
  1469.                    ROUND(SUM(1.0 * share_taxes), 2) AS share_taxes,
  1470.                    ROUND(SUM(1.0 * share_deductions), 2) AS share_deductions,
  1471.                    ROUND(SUM(1.0 * share_net_revenue), 2) AS share_net_revenue,
  1472.                    strftime('%Y', check_date), 2) AS year
  1473.                 FROM revenue_raw
  1474.                 WHERE
  1475.                   owner_name_client = ?
  1476.                   AND aggregation_level IN ('i', 'e', 'h')
  1477.                   AND strftime('%Y', check_date) = '2024'
  1478.                 GROUP BY owner_name_client, operator_purchaser, year
  1479.                ) AS rr
  1480.            ON rr.payee = i.payee AND rr.operator_purchaser = i.operator
  1481.            GROUP BY client, operator, share_gross_revenue, share_taxes, share_deductions, share_net_revenue
  1482.  
  1483.            UNION ALL
  1484.  
  1485.            SELECT
  1486.                COALESCE(rr.payee, i.payee) AS client,
  1487.                CASE
  1488.                    WHEN rr.share_net_revenue < 600 THEN COALESCE(rr.operator_purchaser, i.operator) || '*'
  1489.                    ELSE COALESCE(rr.operator_purchaser, i.operator)
  1490.                END AS operator,
  1491.                1.0 * rr.share_gross_revenue AS share_gross_revenue,
  1492.                1.0 * rr.share_taxes AS share_taxes,
  1493.                1.0 * rr.share_deductions AS share_deductions,
  1494.                1.0 * rr.share_net_revenue AS share_net_revenue,
  1495.                ROUND(SUM(1.0 * i.reported_amount), 2) AS reported_amount,
  1496.                ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) AS difference_dollars,
  1497.                CASE
  1498.                    WHEN 1.0 * rr.share_net_revenue = 0 THEN NULL
  1499.                    ELSE (ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) * 100.0) / (1.0 * rr.share_net_revenue)
  1500.                END AS difference_percent,
  1501.                2 AS source_table
  1502.            FROM
  1503.                (SELECT
  1504.                    payee,
  1505.                    payor AS operator,
  1506.                    1.0 * REPLACE(REPLACE(reported_amount, '$', ''), ',', '') AS reported_amount,
  1507.                    tax_year
  1508.                 FROM items1099
  1509.                 WHERE
  1510.                   payee = ?
  1511.                   AND tax_year = 2024
  1512.                   AND box_name NOT LIKE '%withheld%'
  1513.                   AND box_number NOT LIKE 'nil'
  1514.                ) AS i
  1515.            RIGHT JOIN
  1516.                (SELECT
  1517.                    owner_name_client AS payee,
  1518.                    operator_purchaser,
  1519.                    ROUND(SUM(1.0 * share_gross_revenue), 2) AS share_gross_revenue,
  1520.                    ROUND(SUM(1.0 * share_taxes), 2) AS share_taxes,
  1521.                    ROUND(SUM(1.0 * share_deductions), 2) AS share_deductions,
  1522.                    ROUND(SUM(1.0 * share_net_revenue), 2) AS share_net_revenue,
  1523.                    strftime('%Y', check_date), 2) AS year
  1524.                 FROM revenue_raw
  1525.                 WHERE
  1526.                   owner_name_client = ?
  1527.                   AND aggregation_level IN ('i', 'e', 'h')
  1528.                   AND strftime('%Y', check_date) = '2024'
  1529.                 GROUP BY owner_name_client, operator_purchaser, year
  1530.                ) AS rr
  1531.            ON rr.payee = i.payee AND rr.operator_purchaser = i.operator
  1532.            GROUP BY client, operator, share_gross_revenue, share_taxes, share_deductions, share_net_revenue
  1533.        ) AS combined_data_with_dupes
  1534.        GROUP BY client, operator, source_table
  1535.    ) AS combined_data
  1536.    GROUP BY client, operator, share_gross_revenue, share_taxes, share_deductions, share_net_revenue
  1537.    HAVING ROUND(COALESCE(difference_dollars, 0), 2) != 0
  1538.      AND difference_dollars IS NOT NULL;
  1539.    "#;
  1540.  
  1541.     let records = query_as::<_, TaxYearRev1099Row>(query)
  1542.         .fetch_all(&land_pool)
  1543.         .await
  1544.         // log successful row count, then pass rows through
  1545.         .map(|rows| {
  1546.             log::debug!("Query succeeded: {} rows", rows.len());
  1547.             rows
  1548.         })
  1549.         .map_err(|e| {
  1550.             log::error!("Query failed: {}", e);
  1551.             ServerFnError::new(format!("Database error: {}", e))
  1552.         })?;
  1553.  
  1554.     Ok(records)
  1555. }
  1556.  
  1557. ================
  1558. File: gmm_client/src/tables/iwv_qc_queries/taxyearrev1099/resource.rs
  1559. ================
  1560. use leptos::*;
  1561. use super::query::TaxYearRev1099Row;
  1562. use crate::tables::iwv_qc_queries::taxyearrev1099::query::taxyearrev1099_fetch_all;
  1563.  
  1564. /// Leptos resource for fetching tax year revenue vs 1099 data.
  1565. #[derive(Clone)]
  1566. pub(crate) struct TaxYearRev1099Resource {
  1567.     pub taxyear_rows: Resource<(), Result<Vec<TaxYearRev1099Row>, ServerFnError>>,
  1568. }
  1569.  
  1570. impl TaxYearRev1099Resource {
  1571.     pub fn new() -> Self {
  1572.         let taxyear_rows = create_resource(
  1573.             || (), // No canonical_name needed because query is fetch_all
  1574.             |_| async move {
  1575.                 taxyearrev1099_fetch_all()
  1576.                     .await
  1577.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  1578.             },
  1579.         );
  1580.  
  1581.         Self { taxyear_rows }
  1582.     }
  1583. }
  1584.  
  1585. ================
  1586. File: gmm_client/src/tables/iwv_qc_queries/mod.rs
  1587. ================
  1588. pub(crate) mod incomingtables;
  1589. // pub(crate) mod taxyearrev1099;
  1590.  
  1591. ================
  1592. File: gmm_client/src/tables/jibdetails/mod.rs
  1593. ================
  1594. pub(crate) mod query;
  1595. pub(crate) mod resource;
  1596.  
  1597. ================
  1598. File: gmm_client/src/tables/jibdetails/query.rs
  1599. ================
  1600. use leptos::*;
  1601. use serde::{Deserialize, Serialize};
  1602.  
  1603. /// Represents a row in the JIB details report.
  1604. #[derive(Debug, Clone, Serialize, Deserialize)]
  1605. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  1606. pub struct JibDetailsRow {
  1607.     pub payor: String,
  1608.     pub payee: String,
  1609.     pub payment_date: Option<String>,
  1610.     pub invoice_number: Option<String>,
  1611.     pub cost_center: Option<String>,
  1612.     pub venture_number: Option<String>,
  1613.     pub description: Option<String>,
  1614.     pub total_amount: Option<f64>,
  1615. }
  1616.  
  1617. /// Fetches JIB detail data from `jibs` table.
  1618. #[server]
  1619. pub async fn jibdetails_fetch_by_canonical_name(
  1620.     _canonical_name: String,
  1621. ) -> Result<Vec<JibDetailsRow>, ServerFnError> {
  1622.     pub use JibDetailsRow;
  1623.  
  1624.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1625.  
  1626.     let records = sqlx::query_as::<_, JibDetailsRow>(
  1627.         "WITH jibs_with_date AS (
  1628.            SELECT
  1629.                payor,
  1630.                payee,
  1631.                CASE
  1632.                    WHEN TRIM(pay_month) LIKE '____-__-__' THEN TRIM(pay_month)
  1633.                    WHEN TRIM(pay_month) LIKE '__/__/____' OR TRIM(pay_month) LIKE '_/__/____' OR TRIM(pay_month) LIKE '__/_/____' OR TRIM(pay_month) LIKE '_/_/____' THEN
  1634.                        CASE
  1635.                            WHEN length(TRIM(pay_month)) = 10 THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 7, 4) || '-' || substr(TRIM(pay_month), 1, 2) || '-' || substr(TRIM(pay_month), 4, 2))
  1636.                            WHEN length(TRIM(pay_month)) = 9 THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 6, 4) || '-0' || substr(TRIM(pay_month), 1, 1) || '-' || substr(TRIM(pay_month), 3, 2))
  1637.                            WHEN length(TRIM(pay_month)) = 8 THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 5, 4) || '-' || substr(TRIM(pay_month), 1, 2) || '-0' || substr(TRIM(pay_month), 4, 1))
  1638.                            ELSE strftime('%Y-%m-%d', substr(TRIM(pay_month), 4, 4) || '-0' || substr(TRIM(pay_month), 1, 1) || '-0' || substr(TRIM(pay_month), 3, 1))
  1639.                        END
  1640.                    WHEN TRIM(pay_month) LIKE '___ __, ____' THEN strftime('%Y-%m-%d',
  1641.                        substr(TRIM(pay_month), -4, 4) || '-' ||
  1642.                        CASE
  1643.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Jan' THEN '01'
  1644.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Feb' THEN '02'
  1645.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Mar' THEN '03'
  1646.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Apr' THEN '04'
  1647.                            WHEN substr(TRIM(pay_month), 1, 3) = 'May' THEN '05'
  1648.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Jun' THEN '06'
  1649.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Jul' THEN '07'
  1650.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Aug' THEN '08'
  1651.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Sep' THEN '09'
  1652.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Oct' THEN '10'
  1653.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Nov' THEN '11'
  1654.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Dec' THEN '12'
  1655.                        END || '-' ||
  1656.                        CASE
  1657.                            WHEN length(trim(substr(TRIM(pay_month), 5, 2))) = 1 THEN '0' || substr(TRIM(pay_month), 5, 1)
  1658.                            ELSE substr(TRIM(pay_month), 5, 2)
  1659.                        END
  1660.                    )
  1661.                    WHEN TRIM(pay_month) LIKE '__/__' THEN strftime('%Y-%m-%d', '20' || substr(TRIM(pay_month), 4, 2) || '-' || substr(TRIM(pay_month), 1, 2) || '-15')
  1662.                    WHEN TRIM(pay_month) LIKE '____/__/__' THEN strftime('%Y-%m-%d', replace(TRIM(pay_month), '/', '-'))
  1663.                    WHEN TRIM(pay_month) LIKE '% %' AND LENGTH(TRIM(pay_month)) > 5 THEN
  1664.                        CASE
  1665.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'JAN') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-01-15'
  1666.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'FEB') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-02-15'
  1667.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'MAR') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-03-15'
  1668.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'APR') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-04-15'
  1669.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'MAY') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-05-15'
  1670.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'JUN') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-06-15'
  1671.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'JUL') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-07-15'
  1672.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'AUG') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-08-15'
  1673.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'SEP') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-09-15'
  1674.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'OCT') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-10-15'
  1675.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'NOV') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-11-15'
  1676.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'DEC') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-12-15'
  1677.                        END
  1678.                    WHEN TRIM(pay_month) LIKE '____-__' THEN TRIM(pay_month) || '-15'
  1679.                    WHEN TRIM(pay_month) LIKE '__/__/__' THEN strftime('%Y-%m-%d', '20' || substr(TRIM(pay_month), 7, 2) || '-' || substr(TRIM(pay_month), 1, 2) || '-' || substr(TRIM(pay_month), 4, 2))
  1680.                    WHEN TRIM(pay_month) LIKE '__-__-____' OR TRIM(pay_month) LIKE '_-__-____' THEN
  1681.                        strftime('%Y-%m-%d',
  1682.                            substr(TRIM(pay_month), -4) || '-' ||
  1683.                            CASE WHEN length(TRIM(pay_month)) = 10 THEN substr(TRIM(pay_month), 1, 2) ELSE '0' || substr(TRIM(pay_month), 1, 1) END || '-' ||
  1684.                            CASE WHEN length(TRIM(pay_month)) = 10 THEN substr(TRIM(pay_month), 4, 2) ELSE substr(TRIM(pay_month), 3, 2) END
  1685.                        )
  1686.                    WHEN TRIM(pay_month) LIKE '__/____' OR TRIM(pay_month) LIKE '__-____' THEN
  1687.                        strftime('%Y-%m-%d', substr(TRIM(pay_month), 4, 4) || '-' || substr(TRIM(pay_month), 1, 2) || '-15')
  1688.                    WHEN TRIM(pay_month) LIKE '____/__' THEN
  1689.                        strftime('%Y-%m-%d', substr(TRIM(pay_month), 1, 4) || '-' || substr(TRIM(pay_month), 6, 2) || '-15')
  1690.                    WHEN TRIM(pay_month) LIKE '__-___-____' OR TRIM(pay_month) LIKE '_-___-____' THEN
  1691.                        strftime('%Y-%m-%d',
  1692.                            substr(TRIM(pay_month), -4) || '-' ||
  1693.                            CASE
  1694.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-JAN-') > 0 THEN '01'
  1695.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-FEB-') > 0 THEN '02'
  1696.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-MAR-') > 0 THEN '03'
  1697.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-APR-') > 0 THEN '04'
  1698.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-MAY-') > 0 THEN '05'
  1699.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-JUN-') > 0 THEN '06'
  1700.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-JUL-') > 0 THEN '07'
  1701.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-AUG-') > 0 THEN '08'
  1702.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-SEP-') > 0 THEN '09'
  1703.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-OCT-') > 0 THEN '10'
  1704.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-NOV-') > 0 THEN '11'
  1705.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-DEC-') > 0 THEN '12'
  1706.                            END || '-' ||
  1707.                            CASE
  1708.                                WHEN length(TRIM(pay_month)) = 11 THEN substr(TRIM(pay_month), 1, 2)
  1709.                                ELSE '0' || substr(TRIM(pay_month), 1, 1)
  1710.                            END
  1711.                        )
  1712.                END AS payment_date,
  1713.                invoice_number,
  1714.                cost_center,
  1715.                venture_number,
  1716.                description,
  1717.                amount
  1718.            FROM jibs
  1719.        )
  1720.        SELECT
  1721.            o.name AS operator_name,
  1722.            j.payment_date,
  1723.            j.invoice_number,
  1724.            j.cost_center,
  1725.            j.venture_number,
  1726.            j.description,
  1727.            SUM(1.0 * j.amount) AS total_amount
  1728.        FROM jibs_with_date j
  1729.        JOIN operator o ON o.canonical = j.payee
  1730.        WHERE j.payor = ?
  1731.        AND j.payment_date IS NOT NULL
  1732.        GROUP BY
  1733.            operator_name, j.payment_date, j.invoice_number, j.cost_center, j.venture_number, j.description"
  1734.     )
  1735.     .fetch_all(&land_pool)
  1736.     .await
  1737.     // log successful row count, then pass rows through
  1738.     .map(|rows| {
  1739.         log::debug!("Query succeeded: {} rows", rows.len());
  1740.         rows
  1741.     })
  1742.     .map_err(|e| {
  1743.         log::error!("Query failed: {}", e);
  1744.         ServerFnError::new(format!("Database error: {}", e))
  1745.     })?;
  1746.  
  1747.     Ok(records)
  1748. }
  1749.  
  1750. ================
  1751. File: gmm_client/src/tables/jibdetails/resource.rs
  1752. ================
  1753. use super::query::JibDetailsRow;
  1754. use crate::client_main_app::ctx::*;
  1755. use leptos::*;
  1756.  
  1757. /// Leptos resource for fetching JIB details data.
  1758. #[derive(Clone)]
  1759. pub(crate) struct JibDetailsResource {
  1760.     pub revenue_rows: Resource<String, Result<Vec<JibDetailsRow>, ServerFnError>>,
  1761. }
  1762.  
  1763. use super::query::*;
  1764. impl JibDetailsResource {
  1765.     pub fn new() -> Self {
  1766.         let revenue_rows = create_resource(
  1767.             move || {
  1768.                 let account_ctx = AccountCtx::use_context();
  1769.                 account_ctx
  1770.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  1771.                     .unwrap_or_default()
  1772.             },
  1773.             |canonical_name| async move {
  1774.                 jibdetails_fetch_by_canonical_name(canonical_name)
  1775.                     .await
  1776.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  1777.                 // Fixed conversion
  1778.             },
  1779.         );
  1780.  
  1781.         Self { revenue_rows }
  1782.     }
  1783. }
  1784.  
  1785. ================
  1786. File: gmm_client/src/tables/jibnetting/mod.rs
  1787. ================
  1788. pub(crate) mod query;
  1789. pub(crate) mod resource;
  1790.  
  1791. ================
  1792. File: gmm_client/src/tables/jibnetting/query.rs
  1793. ================
  1794. use leptos::*;
  1795. use serde::{Deserialize, Serialize};
  1796.  
  1797. /// Represents a row in the JIB netting report.
  1798. #[derive(Debug, Clone, Serialize, Deserialize)]
  1799. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  1800. pub struct JibNettingRow {
  1801.     pub owner_name_client: String,
  1802.     pub operator_purchaser: String,
  1803.     pub check_date: Option<String>,
  1804.     pub share_net_revenue: Option<f64>,
  1805. }
  1806.  
  1807. /// Fetches JIB netting data from `revenue_raw` for interest_type = 'jib net'.
  1808. #[server]
  1809. pub async fn jibnetting_fetch_by_canonical_name(
  1810.     canonical_name: String,
  1811. ) -> Result<Vec<JibNettingRow>, ServerFnError> {
  1812.     use JibNettingRow;
  1813.  
  1814.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1815.  
  1816.     let records = sqlx::query_as::<_, JibNettingRow>(
  1817.         "SELECT
  1818.                rr.owner_name_client,
  1819.                o.name AS operator_name,
  1820.                rr.check_date,
  1821.                1.0 * rr.share_net_revenue AS share_net_revenue
  1822.            FROM
  1823.                revenue_raw rr
  1824.            JOIN
  1825.                operator o ON o.canonical = rr.operator_purchaser
  1826.            WHERE
  1827.                rr.owner_name_client = ?
  1828.                AND rr.interest_type = 'jib net'
  1829.            ORDER BY
  1830.                rr.check_date DESC"
  1831.     )
  1832.     .bind(&canonical_name)
  1833.     .fetch_all(&land_pool)
  1834.     .await
  1835.     // log successful row count, then pass rows through
  1836.     .map(|rows| {
  1837.         log::debug!("Query succeeded: {} rows", rows.len());
  1838.         rows
  1839.     })
  1840.     .map_err(|e| {
  1841.         log::error!("Query failed: {}", e);
  1842.         ServerFnError::new(format!("Database error: {}", e))
  1843.     })?;
  1844.  
  1845.     Ok(records)
  1846. }
  1847.  
  1848. ================
  1849. File: gmm_client/src/tables/jibnetting/resource.rs
  1850. ================
  1851. use super::query::JibNettingRow;
  1852. use crate::client_main_app::ctx::*;
  1853. use leptos::*;
  1854.  
  1855. /// Leptos resource for fetching JIB netting data.
  1856. #[derive(Clone)]
  1857. pub(crate) struct JibNettingResource {
  1858.     pub revenue_rows: Resource<String, Result<Vec<JibNettingRow>, ServerFnError>>,
  1859. }
  1860.  
  1861. use super::query::*;
  1862. impl JibNettingResource {
  1863.     pub fn new() -> Self {
  1864.         let revenue_rows = create_resource(
  1865.             move || {
  1866.                 let account_ctx = AccountCtx::use_context();
  1867.                 account_ctx
  1868.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  1869.                     .unwrap_or_default()
  1870.             },
  1871.             |canonical_name| async move {
  1872.                 jibnetting_fetch_by_canonical_name(canonical_name)
  1873.                     .await
  1874.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  1875.                 // Fixed conversion
  1876.             },
  1877.         );
  1878.  
  1879.         Self { revenue_rows }
  1880.     }
  1881. }
  1882.  
  1883. ================
  1884. File: gmm_client/src/tables/jibsummary/mod.rs
  1885. ================
  1886. pub(crate) mod query;
  1887. pub(crate) mod resource;
  1888.  
  1889. ================
  1890. File: gmm_client/src/tables/jibsummary/query.rs
  1891. ================
  1892. use leptos::*;
  1893. use serde::{Deserialize, Serialize};
  1894.  
  1895. /// Represents a row in the JIB summary report.
  1896. #[derive(Debug, Clone, Serialize, Deserialize)]
  1897. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  1898. pub struct JibSummaryRow {
  1899.     pub payor: String,
  1900.     pub payment_date: Option<String>,
  1901.     pub invoice_number: Option<String>,
  1902.     pub total_amount: Option<f64>,
  1903. }
  1904.  
  1905. /// Fetches JIB summary data from `jibs`.
  1906. #[server]
  1907. pub async fn jibsummary_fetch_by_canonical_name(
  1908.     canonical_name: String,
  1909. ) -> Result<Vec<JibSummaryRow>, ServerFnError> {
  1910.     pub use JibSummaryRow;
  1911.  
  1912.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  1913.  
  1914.     let records = sqlx::query_as::<_, JibSummaryRow>(
  1915.         "WITH jibs_with_date AS (
  1916.            SELECT
  1917.                payor,
  1918.                payee,
  1919.                CASE
  1920.                    WHEN TRIM(pay_month) LIKE '____-__-__' THEN TRIM(pay_month)
  1921.                    WHEN TRIM(pay_month) LIKE '__/__/____' OR TRIM(pay_month) LIKE '_/__/____' OR TRIM(pay_month) LIKE '__/_/____' OR TRIM(pay_month) LIKE '_/_/____' THEN
  1922.                        CASE
  1923.                            WHEN length(TRIM(pay_month)) = 10 THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 7, 4) || '-' || substr(TRIM(pay_month), 1, 2) || '-' || substr(TRIM(pay_month), 4, 2))
  1924.                            WHEN length(TRIM(pay_month)) = 9 THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 6, 4) || '-0' || substr(TRIM(pay_month), 1, 1) || '-' || substr(TRIM(pay_month), 3, 2))
  1925.                            WHEN length(TRIM(pay_month)) = 8 THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 5, 4) || '-' || substr(TRIM(pay_month), 1, 2) || '-0' || substr(TRIM(pay_month), 4, 1))
  1926.                            ELSE strftime('%Y-%m-%d', substr(TRIM(pay_month), 4, 4) || '-0' || substr(TRIM(pay_month), 1, 1) || '-0' || substr(TRIM(pay_month), 3, 1))
  1927.                        END
  1928.                    WHEN TRIM(pay_month) LIKE '___ __, ____' THEN strftime('%Y-%m-%d',
  1929.                        substr(TRIM(pay_month), -4, 4) || '-' ||
  1930.                        CASE
  1931.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Jan' THEN '01'
  1932.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Feb' THEN '02'
  1933.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Mar' THEN '03'
  1934.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Apr' THEN '04'
  1935.                            WHEN substr(TRIM(pay_month), 1, 3) = 'May' THEN '05'
  1936.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Jun' THEN '06'
  1937.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Jul' THEN '07'
  1938.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Aug' THEN '08'
  1939.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Sep' THEN '09'
  1940.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Oct' THEN '10'
  1941.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Nov' THEN '11'
  1942.                            WHEN substr(TRIM(pay_month), 1, 3) = 'Dec' THEN '12'
  1943.                        END || '-' ||
  1944.                        CASE
  1945.                            WHEN length(trim(substr(TRIM(pay_month), 5, 2))) = 1 THEN '0' || substr(TRIM(pay_month), 5, 1)
  1946.                            ELSE substr(TRIM(pay_month), 5, 2)
  1947.                        END
  1948.                    )
  1949.                    WHEN TRIM(pay_month) LIKE '__/__' THEN strftime('%Y-%m-%d', '20' || substr(TRIM(pay_month), 4, 2) || '-' || substr(TRIM(pay_month), 1, 2) || '-15')
  1950.                    WHEN TRIM(pay_month) LIKE '____/__/__' THEN strftime('%Y-%m-%d', replace(TRIM(pay_month), '/', '-'))
  1951.                    WHEN TRIM(pay_month) LIKE '% %' AND LENGTH(TRIM(pay_month)) > 5 THEN
  1952.                        CASE
  1953.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'JAN') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-01-15'
  1954.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'FEB') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-02-15'
  1955.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'MAR') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-03-15'
  1956.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'APR') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-04-15'
  1957.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'MAY') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-05-15'
  1958.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'JUN') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-06-15'
  1959.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'JUL') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-07-15'
  1960.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'AUG') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-08-15'
  1961.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'SEP') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-09-15'
  1962.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'OCT') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-10-15'
  1963.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'NOV') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-11-15'
  1964.                            WHEN INSTR(UPPER(TRIM(pay_month)), 'DEC') > 0 THEN SUBSTR(TRIM(pay_month), -4) || '-12-15'
  1965.                        END
  1966.                    WHEN TRIM(pay_month) LIKE '____-__' THEN TRIM(pay_month) || '-15'
  1967.                    WHEN TRIM(pay_month) LIKE '__/__/__' THEN strftime('%Y-%m-%d', '20' || substr(TRIM(pay_month), 7, 2) || '-' || substr(TRIM(pay_month), 1, 2) || '-' || substr(TRIM(pay_month), 4, 2))
  1968.                    WHEN TRIM(pay_month) LIKE '__-__-____' OR TRIM(pay_month) LIKE '_-__-____' THEN
  1969.                        strftime('%Y-%m-%d',
  1970.                            substr(TRIM(pay_month), -4) || '-' ||
  1971.                            CASE WHEN length(TRIM(pay_month)) = 10 THEN substr(TRIM(pay_month), 1, 2) ELSE '0' || substr(TRIM(pay_month), 1, 1) END || '-' ||
  1972.                            CASE WHEN length(TRIM(pay_month)) = 10 THEN substr(TRIM(pay_month), 4, 2) ELSE substr(TRIM(pay_month), 3, 2) END
  1973.                        )
  1974.                    WHEN TRIM(pay_month) LIKE '__/____' OR TRIM(pay_month) LIKE '__-____' THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 4, 4) || '-' || substr(TRIM(pay_month), 1, 2) || '-15')
  1975.                    WHEN TRIM(pay_month) LIKE '____/__' THEN strftime('%Y-%m-%d', substr(TRIM(pay_month), 1, 4) || '-' || substr(TRIM(pay_month), 6, 2) || '-15')
  1976.                    WHEN TRIM(pay_month) LIKE '__-___-____' OR TRIM(pay_month) LIKE '_-___-____' THEN
  1977.                        strftime('%Y-%m-%d',
  1978.                            substr(TRIM(pay_month), -4) || '-' ||
  1979.                            CASE
  1980.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-JAN-') > 0 THEN '01'
  1981.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-FEB-') > 0 THEN '02'
  1982.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-MAR-') > 0 THEN '03'
  1983.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-APR-') > 0 THEN '04'
  1984.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-MAY-') > 0 THEN '05'
  1985.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-JUN-') > 0 THEN '06'
  1986.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-JUL-') > 0 THEN '07'
  1987.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-AUG-') > 0 THEN '08'
  1988.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-SEP-') > 0 THEN '09'
  1989.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-OCT-') > 0 THEN '10'
  1990.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-NOV-') > 0 THEN '11'
  1991.                                WHEN INSTR(UPPER(TRIM(pay_month)), '-DEC-') > 0 THEN '12'
  1992.                            END || '-' ||
  1993.                            CASE
  1994.                                WHEN length(TRIM(pay_month)) = 11 THEN substr(TRIM(pay_month), 1, 2)
  1995.                                ELSE '0' || substr(TRIM(pay_month), 1, 1)
  1996.                            END
  1997.                        )
  1998.                END AS payment_date,
  1999.                invoice_number,
  2000.                amount
  2001.            FROM jibs
  2002.        )
  2003.        SELECT
  2004.            o.name AS operator_name,
  2005.            j.payment_date,
  2006.            j.invoice_number,
  2007.            ROUND(SUM(1.0 * j.amount), 2) AS total_amount
  2008.        FROM jibs_with_date j
  2009.        JOIN operator o ON o.canonical = j.payor
  2010.        WHERE j.payor = ?
  2011.        AND j.payment_date IS NOT NULL
  2012.        GROUP BY
  2013.            operator_name, j.payment_date, j.invoice_number"
  2014.     )
  2015.     .bind(&canonical_name)
  2016.     .fetch_all(&land_pool)
  2017.     .await
  2018.     // log successful row count, then pass rows through
  2019.     .map(|rows| {
  2020.         log::debug!("Query succeeded: {} rows", rows.len());
  2021.         rows
  2022.     })
  2023.     .map_err(|e| {
  2024.         log::error!("Query failed: {}", e);
  2025.         ServerFnError::new(format!("Database error: {}", e))
  2026.     })?;
  2027.  
  2028.     Ok(records)
  2029. }
  2030.  
  2031. ================
  2032. File: gmm_client/src/tables/jibsummary/resource.rs
  2033. ================
  2034. use super::query::JibSummaryRow;
  2035. use crate::client_main_app::ctx::*;
  2036. use leptos::*;
  2037.  
  2038. /// Leptos resource for fetching JIB summary data.
  2039. #[derive(Clone)]
  2040. pub(crate) struct JibSummaryResource {
  2041.     pub revenue_rows: Resource<String, Result<Vec<JibSummaryRow>, ServerFnError>>,
  2042. }
  2043.  
  2044. use super::query::*;
  2045. impl JibSummaryResource {
  2046.     pub fn new() -> Self {
  2047.         let revenue_rows = create_resource(
  2048.             move || {
  2049.                 let account_ctx = AccountCtx::use_context();
  2050.                 account_ctx
  2051.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  2052.                     .unwrap_or_default()
  2053.             },
  2054.             |canonical_name| async move {
  2055.                 jibsummary_fetch_by_canonical_name(canonical_name)
  2056.                     .await
  2057.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  2058.                 // Fixed conversion
  2059.             },
  2060.         );
  2061.  
  2062.         Self { revenue_rows }
  2063.     }
  2064. }
  2065.  
  2066. ================
  2067. File: gmm_client/src/tables/leases/mod.rs
  2068. ================
  2069. pub(crate) mod query;
  2070. pub(crate) mod resource;
  2071.  
  2072. ================
  2073. File: gmm_client/src/tables/leases/query.rs
  2074. ================
  2075. use leptos::*;
  2076. use serde::{Deserialize, Serialize};
  2077.  
  2078. /// Represents a row in the leases report.
  2079. #[derive(Debug, Clone, Serialize, Deserialize)]
  2080. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2081. pub struct LeasesRow {
  2082.     pub client: String,
  2083.     pub lessee: String,
  2084.     pub effective: Option<String>,
  2085.     pub expiration: Option<String>,
  2086.     pub term: Option<i64>,
  2087.     pub royalty: Option<f64>,
  2088.     pub lease_type: Option<String>,
  2089.     pub status: Option<String>,
  2090. }
  2091.  
  2092. /// Fetches lease data by client canonical name.
  2093. #[server]
  2094. pub async fn leases_fetch_by_canonical_name(
  2095.     canonical_name: String,
  2096. ) -> Result<Vec<LeasesRow>, ServerFnError> {
  2097.     use LeasesRow;
  2098.  
  2099.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2100.  
  2101.     let query = r#"
  2102.    SELECT DISTINCT
  2103.        client.canonical AS client,
  2104.        document.grantee_lessee AS lessee,
  2105.        DATE(document.effective_date) AS effective,
  2106.        DATE(lease.expiration_date) AS expiration,
  2107.        lease.term,
  2108.        1.0 * lease.royalty_proportion AS royalty,
  2109.        lease_type.name AS lease_type,
  2110.        lease_status.name AS status
  2111.    FROM
  2112.        lease
  2113.    JOIN
  2114.        lease_type ON lease_type.id = lease.lease_type_id
  2115.    JOIN
  2116.        client ON client.id = lease.client_id
  2117.    JOIN
  2118.        lease_status ON lease_status.id = lease.lease_status_id
  2119.    JOIN
  2120.        document ON document.asset_id = lease.asset_id
  2121.    WHERE
  2122.        client.canonical = ?
  2123.        AND document.grantee_lessee NOT IN ('', '-')
  2124.        AND lease.term NOT IN ('', '-')
  2125.    ORDER BY
  2126.        lease.expiration_date DESC,
  2127.        document.grantee_lessee;
  2128.    "#;
  2129.  
  2130.     let records = sqlx::query_as::<_, LeasesRow>(query)
  2131.         .bind(&canonical_name)
  2132.         .fetch_all(&land_pool)
  2133.         .await
  2134.         // log successful row count, then pass rows through
  2135.         .map(|rows| {
  2136.             log::debug!("Query succeeded: {} rows", rows.len());
  2137.             rows
  2138.         })
  2139.         .map_err(|e| {
  2140.             log::error!("Query failed: {}", e);
  2141.             ServerFnError::new(format!("Database error: {}", e))
  2142.         })?;
  2143.  
  2144.     Ok(records)
  2145. }
  2146.  
  2147. ================
  2148. File: gmm_client/src/tables/leases/resource.rs
  2149. ================
  2150. use super::query::LeasesRow;
  2151. use crate::client_main_app::ctx::*;
  2152. use leptos::*;
  2153.  
  2154. /// Leptos resource for fetching lease data.
  2155. #[derive(Clone)]
  2156. pub(crate) struct LeasesResource {
  2157.     pub revenue_rows: Resource<String, Result<Vec<LeasesRow>, ServerFnError>>,
  2158. }
  2159.  
  2160. use super::query::*;
  2161. impl LeasesResource {
  2162.     pub fn new() -> Self {
  2163.         let revenue_rows = create_resource(
  2164.             move || {
  2165.                 let account_ctx = AccountCtx::use_context();
  2166.                 account_ctx
  2167.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  2168.                     .unwrap_or_default()
  2169.             },
  2170.             |canonical_name| async move {
  2171.                 leases_fetch_by_canonical_name(canonical_name)
  2172.                     .await
  2173.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  2174.                 // Fixed conversion
  2175.             },
  2176.         );
  2177.  
  2178.         Self { revenue_rows }
  2179.     }
  2180. }
  2181.  
  2182. ================
  2183. File: gmm_client/src/tables/pieleasestatus/mod.rs
  2184. ================
  2185. pub(crate) mod query;
  2186. pub(crate) mod resource;
  2187.  
  2188. ================
  2189. File: gmm_client/src/tables/pieleasestatus/query.rs
  2190. ================
  2191. use leptos::*;
  2192. use serde::{Deserialize, Serialize};
  2193.  
  2194. /// Represents a row in the pie Lease Status report.
  2195. #[derive(Debug, Clone, Serialize, Deserialize)]
  2196. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2197. pub struct PieLeaseStatusRow {
  2198.     pub canonical: String,
  2199.     pub status_name: String,
  2200.     pub percentage: f64,
  2201. }
  2202.  
  2203. /// Fetches lease status data for clients.
  2204. #[server]
  2205. pub async fn pieleasestatus_fetch_by_canonical_name(
  2206.     _canonical_name: String,
  2207. ) -> Result<Vec<PieLeaseStatusRow>, ServerFnError> {
  2208.     use PieLeaseStatusRow;
  2209.  
  2210.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2211.  
  2212.     let query = r#"
  2213.    WITH filtered_leases AS (
  2214.        SELECT
  2215.            client.canonical,
  2216.            lease_status.name AS status_name
  2217.        FROM
  2218.            client
  2219.        JOIN
  2220.            lease ON lease.client_id = client.id
  2221.        JOIN
  2222.            lease_status ON lease.lease_status_id = lease_status.id
  2223.        WHERE
  2224.            client.canonical = ?
  2225.            AND lease_status.name != '-'
  2226.    ),
  2227.    status_counts AS (
  2228.        SELECT
  2229.            canonical,
  2230.            status_name,
  2231.            COUNT(*) AS status_count
  2232.        FROM
  2233.            filtered_leases
  2234.        GROUP BY
  2235.            canonical, status_name
  2236.    ),
  2237.    total_counts AS (
  2238.        SELECT
  2239.            canonical,
  2240.            COUNT(*) AS total_count
  2241.        FROM
  2242.            filtered_leases
  2243.        GROUP BY
  2244.            canonical
  2245.    ),
  2246.    percentage_counts AS (
  2247.        SELECT
  2248.            c.canonical,
  2249.            c.status_name,
  2250.            c.status_count,
  2251.            t.total_count,
  2252.            ROUND((c.status_count * 100.0 / t.total_count), 2) AS raw_percentage
  2253.        FROM
  2254.            status_counts c
  2255.        JOIN
  2256.            total_counts t ON c.canonical = t.canonical
  2257.    )
  2258.    SELECT
  2259.        p.canonical,
  2260.        p.status_name,
  2261.        ROUND(
  2262.            CASE
  2263.                WHEN p.row_num = p.total_rows THEN
  2264.                    100 - SUM(p.raw_percentage) OVER (PARTITION BY p.canonical) + p.raw_percentage
  2265.                ELSE p.raw_percentage
  2266.            END, 2
  2267.        ) AS percentage
  2268.    FROM (
  2269.        SELECT
  2270.            p.*,
  2271.            ROW_NUMBER() OVER (PARTITION BY p.canonical ORDER BY p.status_name) AS row_num,
  2272.            COUNT(*) OVER (PARTITION BY p.canonical) AS total_rows
  2273.        FROM
  2274.            percentage_counts p
  2275.    ) AS p
  2276.    ORDER BY
  2277.        p.canonical, p.status_name;
  2278.    "#;
  2279.  
  2280.     let records = sqlx::query_as::<_, PieLeaseStatusRow>(query)
  2281.         .fetch_all(&land_pool)
  2282.         .await
  2283.         // log successful row count, then pass rows through
  2284.         .map(|rows| {
  2285.             log::debug!("Query succeeded: {} rows", rows.len());
  2286.             rows
  2287.         })
  2288.         .map_err(|e| {
  2289.             log::error!("Query failed: {}", e);
  2290.             ServerFnError::new(format!("Database error: {}", e))
  2291.         })?;
  2292.  
  2293.     Ok(records)
  2294. }
  2295.  
  2296. ================
  2297. File: gmm_client/src/tables/pieleasestatus/resource.rs
  2298. ================
  2299. use leptos::*;
  2300. use super::query::{PieLeaseStatusRow, pieleasestatus_fetch_by_canonical_name};
  2301. use crate::client_main_app::ctx::*;
  2302.  
  2303. /// Leptos resource for fetching lease status distribution data.
  2304. #[derive(Clone)]
  2305. pub(crate) struct PieLeaseStatusResource {
  2306.     pub revenue_rows: Resource<String, Result<Vec<PieLeaseStatusRow>, ServerFnError>>,
  2307. }
  2308.  
  2309. impl PieLeaseStatusResource {
  2310.     pub fn new() -> Self {
  2311.         let revenue_rows = create_resource(
  2312.             move || {
  2313.                 let account_ctx = AccountCtx::use_context();
  2314.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  2315.             },
  2316.             |canonical_name| async move {
  2317.                 pieleasestatus_fetch_by_canonical_name(canonical_name)
  2318.                     .await
  2319.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  2320.             }
  2321.         );
  2322.  
  2323.         Self { revenue_rows }
  2324.     }
  2325. }
  2326.  
  2327. ================
  2328. File: gmm_client/src/tables/pieproducingwellscounty/mod.rs
  2329. ================
  2330. pub(crate) mod query;
  2331. pub(crate) mod resource;
  2332.  
  2333. ================
  2334. File: gmm_client/src/tables/pieproducingwellscounty/query.rs
  2335. ================
  2336. use leptos::*;
  2337. use serde::{Deserialize, Serialize};
  2338.  
  2339. /// Represents a row in the producing wells distribution by county report.
  2340. #[derive(Debug, Clone, Serialize, Deserialize)]
  2341. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2342. pub struct PieProducingWellsCountyRow {
  2343.     pub canonical: String,
  2344.     pub county: String,
  2345.     pub percentage: Option<f64>,
  2346. }
  2347.  
  2348. /// Fetches producing wells distribution data by county.
  2349. #[server]
  2350. pub async fn pieproducingwellscounty_fetch_by_canonical_name(
  2351.     canonical_name: String,
  2352. ) -> Result<Vec<PieProducingWellsCountyRow>, ServerFnError> {
  2353.     pub use PieProducingWellsCountyRow;
  2354.  
  2355.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2356.  
  2357.     let records = sqlx::query_as::<_, PieProducingWellsCountyRow>(
  2358.         "WITH filtered_wells AS (
  2359.            SELECT
  2360.                client.canonical,
  2361.                well.county
  2362.            FROM
  2363.                client
  2364.            JOIN
  2365.                well_interest ON well_interest.client_id = client.id
  2366.            JOIN
  2367.                well ON well_interest.well_id = well.well_id
  2368.            JOIN
  2369.                well_status ON well.well_status_id = well_status.id
  2370.            WHERE
  2371.                client.canonical = ?
  2372.                AND well_status.name = 'Producing'
  2373.                AND well.county != ''
  2374.                AND well.api_or_uwi != ''
  2375.        ),
  2376.        county_counts AS (
  2377.            SELECT
  2378.                canonical,
  2379.                county,
  2380.                COUNT(*) AS county_count
  2381.            FROM
  2382.                filtered_wells
  2383.            GROUP BY
  2384.                canonical, county
  2385.        ),
  2386.        total_counts AS (
  2387.            SELECT
  2388.                canonical,
  2389.                COUNT(*) AS total_count
  2390.            FROM
  2391.                filtered_wells
  2392.            GROUP BY
  2393.                canonical
  2394.        ),
  2395.        percentage_counts AS (
  2396.            SELECT
  2397.                c.canonical,
  2398.                c.county,
  2399.                c.county_count,
  2400.                ROUND((c.county_count * 100.0 / t.total_count), 2) AS raw_percentage
  2401.            FROM
  2402.                county_counts c
  2403.            JOIN
  2404.                total_counts t ON c.canonical = t.canonical
  2405.        )
  2406.        SELECT
  2407.            p.canonical,
  2408.            p.county,
  2409.            CASE
  2410.                WHEN p.row_num = p.total_rows THEN ROUND(100 - SUM(p.raw_percentage) OVER (PARTITION BY p.canonical) + p.raw_percentage, 2)
  2411.                ELSE p.raw_percentage
  2412.            END AS percentage
  2413.        FROM (
  2414.            SELECT
  2415.                p.*,
  2416.                ROW_NUMBER() OVER (PARTITION BY p.canonical ORDER BY p.county) AS row_num,
  2417.                COUNT(*) OVER (PARTITION BY p.canonical) AS total_rows
  2418.            FROM
  2419.                percentage_counts p
  2420.        ) AS p
  2421.        ORDER BY
  2422.            p.canonical, p.county"
  2423.     )
  2424.     .bind(&canonical_name)
  2425.     .fetch_all(&land_pool)
  2426.     .await
  2427.     // log successful row count, then pass rows through
  2428.     .map(|rows| {
  2429.         log::debug!("Query succeeded: {} rows", rows.len());
  2430.         rows
  2431.     })
  2432.     .map_err(|e| {
  2433.         log::error!("Query failed: {}", e);
  2434.         ServerFnError::new(format!("Database error: {}", e))
  2435.     })?;
  2436.  
  2437.     Ok(records)
  2438. }
  2439.  
  2440. ================
  2441. File: gmm_client/src/tables/pieproducingwellscounty/resource.rs
  2442. ================
  2443. use leptos::*;
  2444. use super::query::PieProducingWellsCountyRow;
  2445. use crate::client_main_app::ctx::*;
  2446.  
  2447. /// Leptos resource for fetching producing wells distribution data by county.
  2448. #[derive(Clone)]
  2449. pub(crate) struct PieProducingWellsCountyResource {
  2450.     pub revenue_rows: Resource<String, Result<Vec<PieProducingWellsCountyRow>, ServerFnError>>,
  2451. }
  2452.  
  2453. use super::query::*;
  2454. impl PieProducingWellsCountyResource {
  2455.     pub fn new() -> Self {
  2456.         let revenue_rows = create_resource(
  2457.             move || {
  2458.                 let account_ctx = AccountCtx::use_context();
  2459.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  2460.             },
  2461.             |canonical_name| async move {
  2462.                 pieproducingwellscounty_fetch_by_canonical_name(canonical_name)
  2463.                     .await
  2464.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  2465.             }
  2466.         );
  2467.  
  2468.         Self { revenue_rows }
  2469.     }
  2470. }
  2471.  
  2472. ================
  2473. File: gmm_client/src/tables/pieproducingwellsstate/mod.rs
  2474. ================
  2475. pub(crate) mod query;
  2476. pub(crate) mod resource;
  2477.  
  2478. ================
  2479. File: gmm_client/src/tables/pieproducingwellsstate/query.rs
  2480. ================
  2481. use leptos::*;
  2482. use serde::{Deserialize, Serialize};
  2483.  
  2484. /// Represents a row in the producing wells distribution by state report.
  2485. #[derive(Debug, Clone, Serialize, Deserialize)]
  2486. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2487. pub struct PieProducingWellsStateRow {
  2488.     pub canonical: String,
  2489.     pub state: String,
  2490.     pub percentage: Option<f64>,
  2491. }
  2492.  
  2493. /// Fetches producing wells distribution data by state.
  2494. #[server]
  2495. pub async fn pieproducingwellsstate_fetch_by_canonical_name(
  2496.     canonical_name: String,
  2497. ) -> Result<Vec<PieProducingWellsStateRow>, ServerFnError> {
  2498.     pub use PieProducingWellsStateRow;
  2499.  
  2500.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2501.  
  2502.     let records = sqlx::query_as::<_, PieProducingWellsStateRow>(
  2503.         "WITH filtered_wells AS (
  2504.                SELECT
  2505.                    client.canonical,
  2506.                    state.name AS state_name
  2507.                FROM
  2508.                    client
  2509.                JOIN
  2510.                    well_interest ON well_interest.client_id = client.id
  2511.                JOIN
  2512.                    well ON well_interest.well_id = well.well_id
  2513.                JOIN
  2514.                    well_status ON well.well_status_id = well_status.id
  2515.                JOIN
  2516.                    state ON state.state = well.state
  2517.                WHERE
  2518.                    client.canonical = ?
  2519.                    AND well_status.name = 'Producing'
  2520.                    AND well.state != ''
  2521.                    AND well.api_or_uwi != ''
  2522.            ),
  2523.            state_counts AS (
  2524.                SELECT
  2525.                    canonical,
  2526.                    state_name AS state,
  2527.                    COUNT(*) AS state_count
  2528.                FROM
  2529.                    filtered_wells
  2530.                GROUP BY
  2531.                    canonical, state_name
  2532.            ),
  2533.            total_counts AS (
  2534.                SELECT
  2535.                    canonical,
  2536.                    COUNT(*) AS total_count
  2537.                FROM
  2538.                    filtered_wells
  2539.                GROUP BY
  2540.                    canonical
  2541.            ),
  2542.            percentage_counts AS (
  2543.                SELECT
  2544.                    c.canonical,
  2545.                    c.state,
  2546.                    c.state_count,
  2547.                    ROUND((c.state_count * 100.0 / t.total_count), 2) AS raw_percentage
  2548.                FROM
  2549.                    state_counts c
  2550.                JOIN
  2551.                    total_counts t ON c.canonical = t.canonical
  2552.            )
  2553.            SELECT
  2554.                p.canonical,
  2555.                p.state,
  2556.                CASE
  2557.                    WHEN p.row_num = p.total_rows THEN ROUND(100 - SUM(p.raw_percentage) OVER (PARTITION BY p.canonical) + p.raw_percentage, 2)
  2558.                    ELSE p.raw_percentage
  2559.                END AS percentage
  2560.            FROM (
  2561.                SELECT
  2562.                    p.*,
  2563.                    ROW_NUMBER() OVER (PARTITION BY p.canonical ORDER BY p.state) AS row_num,
  2564.                    COUNT(*) OVER (PARTITION BY p.canonical) AS total_rows
  2565.                FROM
  2566.                    percentage_counts p
  2567.            ) AS p
  2568.            ORDER BY
  2569.                p.canonical, p.state;"
  2570.     )
  2571.     .bind(&canonical_name)
  2572.     .fetch_all(&land_pool)
  2573.     .await
  2574.     // log successful row count, then pass rows through
  2575.     .map(|rows| {
  2576.         log::debug!("Query succeeded: {} rows", rows.len());
  2577.         rows
  2578.     })
  2579.     .map_err(|e| {
  2580.         log::error!("Query failed: {}", e);
  2581.         ServerFnError::new(format!("Database error: {}", e))
  2582.     })?;
  2583.  
  2584.     Ok(records)
  2585. }
  2586.  
  2587. ================
  2588. File: gmm_client/src/tables/pieproducingwellsstate/resource.rs
  2589. ================
  2590. use leptos::*;
  2591. use super::query::PieProducingWellsStateRow;
  2592. use crate::client_main_app::ctx::*;
  2593.  
  2594. /// Leptos resource for fetching producing wells distribution data by state.
  2595. #[derive(Clone)]
  2596. pub(crate) struct PieProducingWellsStateResource {
  2597.     pub revenue_rows: Resource<String, Result<Vec<PieProducingWellsStateRow>, ServerFnError>>,
  2598. }
  2599.  
  2600. use super::query::*;
  2601. impl PieProducingWellsStateResource {
  2602.     pub fn new() -> Self {
  2603.         let revenue_rows = create_resource(
  2604.             move || {
  2605.                 let account_ctx = AccountCtx::use_context();
  2606.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  2607.             },
  2608.             |canonical_name| async move {
  2609.                 pieproducingwellsstate_fetch_by_canonical_name(canonical_name)
  2610.                     .await
  2611.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  2612.             }
  2613.         );
  2614.  
  2615.         Self { revenue_rows }
  2616.     }
  2617. }
  2618.  
  2619. ================
  2620. File: gmm_client/src/tables/pierevenuebycounty/mod.rs
  2621. ================
  2622. pub(crate) mod query;
  2623. pub(crate) mod resource;
  2624.  
  2625. ================
  2626. File: gmm_client/src/tables/pierevenuebycounty/query.rs
  2627. ================
  2628. use leptos::*;
  2629. use serde::{Deserialize, Serialize};
  2630.  
  2631. /// Represents a row in the revenue distribution by county report.
  2632. #[derive(Debug, Clone, Serialize, Deserialize)]
  2633. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2634. pub struct PieRevenueByCountyRow {
  2635.     pub owner_name_client: String,
  2636.     pub county: String,
  2637.     pub share_net_percentage: Option<f64>,
  2638. }
  2639.  
  2640. /// Fetches revenue distribution data by county.
  2641. #[server]
  2642. pub async fn pierevenuebycounty_fetch_by_canonical_name(
  2643.     canonical_name: String,
  2644. ) -> Result<Vec<PieRevenueByCountyRow>, ServerFnError> {
  2645.     pub use PieRevenueByCountyRow;
  2646.  
  2647.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2648.  
  2649.     let records = sqlx::query_as::<_, PieRevenueByCountyRow>(
  2650.         "WITH total AS (
  2651.            SELECT
  2652.                owner_name_client,
  2653.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net
  2654.            FROM revenue_raw
  2655.            WHERE
  2656.                owner_name_client = ?
  2657.                AND aggregation_level IN ('i', 'e', 'h')
  2658.                AND 1.0 * share_net_revenue > 0
  2659.                AND (
  2660.                    (check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  2661.                     AND check_date < strftime('%Y-%m-01', 'now'))
  2662.                    OR
  2663.                    (strftime('%Y-%m', check_date) = strftime('%Y-%m', 'now', '-1 month'))
  2664.                )
  2665.            GROUP BY owner_name_client
  2666.        ),
  2667.        revenue_data AS (
  2668.            SELECT
  2669.                rd.owner_name_client,
  2670.                COALESCE(NULLIF(rd.county, ''), 'unreported') AS county,  
  2671.                1.0 * rd.share_net_revenue AS share_net_revenue,
  2672.                ROUND((1.0 * rd.share_net_revenue * 100.0 / t.total_share_net), 2) AS raw_percentage
  2673.            FROM revenue_raw rd
  2674.            JOIN total t ON rd.owner_name_client = t.owner_name_client
  2675.             WHERE
  2676.                rd.owner_name_client = ?
  2677.                AND aggregation_level IN ('i', 'e', 'h')
  2678.                AND 1.0 * rd.share_net_revenue > 0
  2679.                AND (
  2680.                    (rd.check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  2681.                     AND rd.check_date < strftime('%Y-%m-01', 'now'))
  2682.                    OR
  2683.                    (strftime('%Y-%m', rd.check_date) = strftime('%Y-%m', 'now', '-1 month'))
  2684.                )
  2685.        )
  2686.        SELECT
  2687.            p.owner_name_client,
  2688.            p.county,  
  2689.            ROUND(SUM(p.raw_percentage) * 100.0 / SUM(SUM(p.raw_percentage)) OVER (PARTITION BY p.owner_name_client), 2) AS share_net_percentage
  2690.        FROM revenue_data p
  2691.        GROUP BY p.owner_name_client, p.county  
  2692.        ORDER BY p.owner_name_client, p.county"
  2693.     )
  2694.     .bind(&canonical_name)
  2695.     .fetch_all(&land_pool)
  2696.     .await
  2697.     // log successful row count, then pass rows through
  2698.     .map(|rows| {
  2699.         log::debug!("Query succeeded: {} rows", rows.len());
  2700.         rows
  2701.     })
  2702.     .map_err(|e| {
  2703.         log::error!("Query failed: {}", e);
  2704.         ServerFnError::new(format!("Database error: {}", e))
  2705.     })?;
  2706.  
  2707.     Ok(records)
  2708. }
  2709.  
  2710. ================
  2711. File: gmm_client/src/tables/pierevenuebycounty/resource.rs
  2712. ================
  2713. use leptos::*;
  2714. use super::query::PieRevenueByCountyRow;
  2715. use crate::client_main_app::ctx::*;
  2716.  
  2717. /// Leptos resource for fetching revenue distribution data by county.
  2718. #[derive(Clone)]
  2719. pub(crate) struct PieRevenueByCountyResource {
  2720.     pub revenue_rows: Resource<String, Result<Vec<PieRevenueByCountyRow>, ServerFnError>>,
  2721. }
  2722.  
  2723. use super::query::*;
  2724. impl PieRevenueByCountyResource {
  2725.     pub fn new() -> Self {
  2726.         let revenue_rows = create_resource(
  2727.             move || {
  2728.                 let account_ctx = AccountCtx::use_context();
  2729.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  2730.             },
  2731.             |canonical_name| async move {
  2732.                 pierevenuebycounty_fetch_by_canonical_name(canonical_name)
  2733.                     .await
  2734.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  2735.             }
  2736.         );
  2737.  
  2738.         Self { revenue_rows }
  2739.     }
  2740. }
  2741.  
  2742. ================
  2743. File: gmm_client/src/tables/pierevenuebyoperator/mod.rs
  2744. ================
  2745. pub(crate) mod query;
  2746. pub(crate) mod resource;
  2747.  
  2748. ================
  2749. File: gmm_client/src/tables/pierevenuebyoperator/query.rs
  2750. ================
  2751. use leptos::*;
  2752. use serde::{Deserialize, Serialize};
  2753.  
  2754. /// Represents a row in the revenue distribution by operator report.
  2755. #[derive(Debug, Clone, Serialize, Deserialize)]
  2756. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2757. pub struct PieRevenueByOperatorRow {
  2758.     pub owner_name_client: String,
  2759.     pub operator_name: String,
  2760.     pub share_net_percentage: Option<f64>,
  2761. }
  2762.  
  2763. /// Fetches revenue distribution data by operator.
  2764. #[server]
  2765. pub async fn pierevenuebyoperator_fetch_by_canonical_name(
  2766.     canonical_name: String,
  2767. ) -> Result<Vec<PieRevenueByOperatorRow>, ServerFnError> {
  2768.     pub use PieRevenueByOperatorRow;
  2769.  
  2770.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2771.  
  2772.     let records = sqlx::query_as::<_, PieRevenueByOperatorRow>(
  2773.         r#"
  2774.        WITH total AS (
  2775.            SELECT
  2776.                owner_name_client,
  2777.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net  
  2778.            FROM
  2779.                revenue_raw
  2780.            WHERE
  2781.                owner_name_client = ?
  2782.                AND aggregation_level IN ('i', 'e', 'h')
  2783.                AND 1.0 * share_net_revenue > 0  
  2784.                AND (
  2785.                    (check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  2786.                    AND check_date < strftime('%Y-%m-01', 'now'))
  2787.                    OR
  2788.                    (strftime('%Y-%m', check_date) = strftime('%Y-%m', 'now', '-1 month'))
  2789.                )
  2790.            GROUP BY
  2791.                owner_name_client
  2792.        ),
  2793.        revenue_data AS (
  2794.            SELECT
  2795.                rd.owner_name_client,
  2796.                o.name AS operator_name,
  2797.                1.0 * rd.share_net_revenue AS share_net_revenue,  
  2798.                ROUND((1.0 * rd.share_net_revenue * 100.0 / t.total_share_net), 2) AS raw_percentage  
  2799.            FROM
  2800.                revenue_raw rd
  2801.            JOIN
  2802.                operator o ON o.canonical = rd.operator_purchaser
  2803.            JOIN
  2804.                total t ON rd.owner_name_client = t.owner_name_client
  2805.            WHERE
  2806.                rd.owner_name_client = ?
  2807.                AND aggregation_level IN ('i', 'e', 'h')
  2808.                AND 1.0 * rd.share_net_revenue > 0  
  2809.                AND (
  2810.                    (rd.check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  2811.                    AND rd.check_date < strftime('%Y-%m-01', 'now'))
  2812.                    OR
  2813.                    (strftime('%Y-%m', rd.check_date) = strftime('%Y-%m', 'now', '-1 month'))
  2814.                )
  2815.        )
  2816.        SELECT
  2817.            p.owner_name_client,
  2818.            p.operator_name,
  2819.            ROUND(SUM(p.raw_percentage), 2) AS share_net_percentage
  2820.        FROM
  2821.            revenue_data p
  2822.        GROUP BY
  2823.            p.owner_name_client, p.operator_name
  2824.        ORDER BY
  2825.            p.owner_name_client, p.operator_name
  2826.        "#
  2827.     )
  2828.     .bind(&canonical_name) // for total
  2829.     .bind(&canonical_name) // for revenue_data
  2830.     .fetch_all(&land_pool)
  2831.     .await
  2832.     .map(|rows| {
  2833.         log::debug!("Query succeeded: {} rows", rows.len());
  2834.         rows
  2835.     })
  2836.     .map_err(|e| {
  2837.         log::error!("Query failed: {}", e);
  2838.         ServerFnError::new(format!("Database error: {}", e))
  2839.     })?;
  2840.  
  2841.     Ok(records)
  2842. }
  2843.  
  2844. ================
  2845. File: gmm_client/src/tables/pierevenuebyoperator/resource.rs
  2846. ================
  2847. use leptos::*;
  2848. use super::query::PieRevenueByOperatorRow;
  2849. use crate::client_main_app::ctx::*;
  2850.  
  2851. /// Leptos resource for fetching revenue distribution data by operator.
  2852. #[derive(Clone)]
  2853. pub(crate) struct PieRevenueByOperatorResource {
  2854.     pub revenue_rows: Resource<String, Result<Vec<PieRevenueByOperatorRow>, ServerFnError>>,
  2855. }
  2856.  
  2857. use super::query::*;
  2858. impl PieRevenueByOperatorResource {
  2859.     pub fn new() -> Self {
  2860.         let revenue_rows = create_resource(
  2861.             move || {
  2862.                 let account_ctx = AccountCtx::use_context();
  2863.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  2864.             },
  2865.             |canonical_name| async move {
  2866.                 pierevenuebyoperator_fetch_by_canonical_name(canonical_name)
  2867.                     .await
  2868.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  2869.             }
  2870.         );
  2871.  
  2872.         Self { revenue_rows }
  2873.     }
  2874. }
  2875.  
  2876. ================
  2877. File: gmm_client/src/tables/pierevenuebyproduct/mod.rs
  2878. ================
  2879. pub(crate) mod query;
  2880. pub(crate) mod resource;
  2881.  
  2882. ================
  2883. File: gmm_client/src/tables/pierevenuebyproduct/query.rs
  2884. ================
  2885. use leptos::*;
  2886. use serde::{Deserialize, Serialize};
  2887.  
  2888. /// Represents a row in the revenue distribution by product report.
  2889. #[derive(Debug, Clone, Serialize, Deserialize)]
  2890. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  2891. pub struct PieRevenueByProductRow {
  2892.     pub owner_name_client: String,
  2893.     pub product: String,
  2894.     pub share_net_percentage: Option<f64>,
  2895. }
  2896.  
  2897. /// Fetches revenue distribution data by product.
  2898. #[server]
  2899. pub async fn pierevenuebyproduct_fetch_by_canonical_name(
  2900.     canonical_name: String,
  2901. ) -> Result<Vec<PieRevenueByProductRow>, ServerFnError> {
  2902.     pub use PieRevenueByProductRow;
  2903.  
  2904.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  2905.  
  2906.     let records = sqlx::query_as::<_, PieRevenueByProductRow>(
  2907.         "WITH total AS (
  2908.            SELECT
  2909.                owner_name_client,
  2910.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net  
  2911.            FROM revenue_raw
  2912.            WHERE
  2913.                owner_name_client = ?
  2914.                AND aggregation_level IN ('i', 'e', 'h')
  2915.                AND 1.0 * share_net_revenue > 0  
  2916.                AND (
  2917.                    (check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  2918.                     AND check_date < strftime('%Y-%m-01', 'now'))
  2919.                    OR
  2920.                    (strftime('%Y-%m', check_date) = strftime('%Y-%m', 'now', '-1 month'))
  2921.                )
  2922.            GROUP BY owner_name_client
  2923.        ),
  2924.        revenue_data AS (
  2925.            SELECT
  2926.                rd.owner_name_client,
  2927.                rd.product,
  2928.                1.0 * rd.share_net_revenue AS share_net_revenue,  
  2929.                ROUND((1.0 * rd.share_net_revenue * 100.0 / t.total_share_net), 2) AS raw_percentage  
  2930.            FROM revenue_raw rd
  2931.            JOIN total t ON rd.owner_name_client = t.owner_name_client
  2932.            WHERE
  2933.                rd.owner_name_client = ?
  2934.                AND aggregation_level IN ('i', 'e', 'h')
  2935.                AND 1.0 * rd.share_net_revenue > 0  
  2936.                AND (
  2937.                    (rd.check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  2938.                     AND rd.check_date < strftime('%Y-%m-01', 'now'))
  2939.                    OR
  2940.                    (strftime('%Y-%m', rd.check_date) = strftime('%Y-%m', 'now', '-1 month'))
  2941.                )
  2942.        )
  2943.        SELECT
  2944.            p.owner_name_client,
  2945.            p.product,
  2946.            ROUND(SUM(p.raw_percentage), 2) AS share_net_percentage
  2947.        FROM revenue_data p
  2948.        GROUP BY p.owner_name_client, p.product
  2949.        ORDER BY p.owner_name_client, p.product"
  2950.     )
  2951.     .bind(&canonical_name)
  2952.     .fetch_all(&land_pool)
  2953.     .await
  2954.     // log successful row count, then pass rows through
  2955.     .map(|rows| {
  2956.         log::debug!("Query succeeded: {} rows", rows.len());
  2957.         rows
  2958.     })
  2959.     .map_err(|e| {
  2960.         log::error!("Query failed: {}", e);
  2961.         ServerFnError::new(format!("Database error: {}", e))
  2962.     })?;
  2963.  
  2964.     Ok(records)
  2965. }
  2966.  
  2967. ================
  2968. File: gmm_client/src/tables/pierevenuebyproduct/resource.rs
  2969. ================
  2970. use leptos::*;
  2971. use super::query::PieRevenueByProductRow;
  2972. use crate::client_main_app::ctx::*;
  2973.  
  2974. /// Leptos resource for fetching revenue distribution data by product.
  2975. #[derive(Clone)]
  2976. pub(crate) struct PieRevenueByProductResource {
  2977.     pub revenue_rows: Resource<String, Result<Vec<PieRevenueByProductRow>, ServerFnError>>,
  2978. }
  2979.  
  2980. use super::query::*;
  2981. impl PieRevenueByProductResource {
  2982.     pub fn new() -> Self {
  2983.         let revenue_rows = create_resource(
  2984.             move || {
  2985.                 let account_ctx = AccountCtx::use_context();
  2986.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  2987.             },
  2988.             |canonical_name| async move {
  2989.                 pierevenuebyproduct_fetch_by_canonical_name(canonical_name)
  2990.                     .await
  2991.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  2992.             }
  2993.         );
  2994.  
  2995.         Self { revenue_rows }
  2996.     }
  2997. }
  2998.  
  2999. ================
  3000. File: gmm_client/src/tables/pierevenuebystate/mod.rs
  3001. ================
  3002. pub(crate) mod query;
  3003. pub(crate) mod resource;
  3004.  
  3005. ================
  3006. File: gmm_client/src/tables/pierevenuebystate/query.rs
  3007. ================
  3008. use leptos::*;
  3009. use serde::{Deserialize, Serialize};
  3010.  
  3011. /// Represents a row in the revenue distribution by state report.
  3012. #[derive(Debug, Clone, Serialize, Deserialize)]
  3013. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3014. pub struct PieRevenueByStateRow {
  3015.     pub owner_name_client: String,
  3016.     pub state: String,
  3017.     pub share_net_percentage: Option<f64>,
  3018. }
  3019.  
  3020. /// Fetches revenue distribution data by state.
  3021. #[server]
  3022. pub async fn pierevenuebystate_fetch_by_canonical_name(
  3023.     canonical_name: String,
  3024. ) -> Result<Vec<PieRevenueByStateRow>, ServerFnError> {
  3025.     pub use PieRevenueByStateRow;
  3026.  
  3027.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3028.  
  3029.     let records = sqlx::query_as::<_, PieRevenueByStateRow>(
  3030.         "WITH total AS (
  3031.            SELECT
  3032.                owner_name_client,
  3033.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net
  3034.            FROM revenue_raw
  3035.            WHERE
  3036.                owner_name_client = ?
  3037.                AND aggregation_level IN ('i', 'e', 'h')
  3038.                AND 1.0 * share_net_revenue > 0
  3039.                AND (
  3040.                    (check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  3041.                     AND check_date < strftime('%Y-%m-01', 'now'))
  3042.                    OR
  3043.                    (strftime('%Y-%m', check_date) = strftime('%Y-%m', 'now', '-1 month'))
  3044.                )
  3045.            GROUP BY owner_name_client
  3046.        ),
  3047.        revenue_data AS (
  3048.            SELECT
  3049.                rd.owner_name_client,
  3050.                COALESCE(NULLIF(rd.state, ''), 'unreported') AS state,
  3051.                1.0 * rd.share_net_revenue AS share_net_revenue,
  3052.                ROUND((1.0 * rd.share_net_revenue * 100.0 / t.total_share_net), 2) AS raw_percentage
  3053.            FROM revenue_raw rd
  3054.            JOIN total t ON rd.owner_name_client = t.owner_name_client
  3055.            WHERE
  3056.                rd.owner_name_client = ?
  3057.                AND aggregation_level IN ('i', 'e', 'h')
  3058.                AND 1.0 * rd.share_net_revenue > 0
  3059.                AND (
  3060.                    (rd.check_date >= strftime('%Y-%m-01', 'now', 'start of month', '-1 month')
  3061.                     AND rd.check_date < strftime('%Y-%m-01', 'now'))
  3062.                    OR
  3063.                    (strftime('%Y-%m', rd.check_date) = strftime('%Y-%m', 'now', '-1 month'))
  3064.                )
  3065.        )
  3066.        SELECT
  3067.            p.owner_name_client,
  3068.            p.state,
  3069.            ROUND(SUM(p.raw_percentage) * 100.0 / SUM(SUM(p.raw_percentage)) OVER (PARTITION BY p.owner_name_client), 2) AS share_net_percentage
  3070.        FROM revenue_data p
  3071.        GROUP BY p.owner_name_client, p.state
  3072.        ORDER BY p.owner_name_client, p.state"
  3073.     )
  3074.     .bind(&canonical_name)
  3075.     .fetch_all(&land_pool)
  3076.     .await
  3077.     // log successful row count, then pass rows through
  3078.     .map(|rows| {
  3079.         log::debug!("Query succeeded: {} rows", rows.len());
  3080.         rows
  3081.     })
  3082.     .map_err(|e| {
  3083.         log::error!("Query failed: {}", e);
  3084.         ServerFnError::new(format!("Database error: {}", e))
  3085.     })?;
  3086.  
  3087.     Ok(records)
  3088. }
  3089.  
  3090. ================
  3091. File: gmm_client/src/tables/pierevenuebystate/resource.rs
  3092. ================
  3093. use leptos::*;
  3094. use super::query::PieRevenueByStateRow;
  3095. use crate::client_main_app::ctx::*;
  3096.  
  3097. /// Leptos resource for fetching revenue distribution data by state.
  3098. #[derive(Clone)]
  3099. pub(crate) struct PieRevenueByStateResource {
  3100.     pub revenue_rows: Resource<String, Result<Vec<PieRevenueByStateRow>, ServerFnError>>,
  3101. }
  3102.  
  3103. use super::query::*;
  3104. impl PieRevenueByStateResource {
  3105.     pub fn new() -> Self {
  3106.         let revenue_rows = create_resource(
  3107.             move || {
  3108.                 let account_ctx = AccountCtx::use_context();
  3109.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  3110.             },
  3111.             |canonical_name| async move {
  3112.                 pierevenuebystate_fetch_by_canonical_name(canonical_name)
  3113.                     .await
  3114.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e))) // Fixed conversion
  3115.             }
  3116.         );
  3117.  
  3118.         Self { revenue_rows }
  3119.     }
  3120. }
  3121.  
  3122. ================
  3123. File: gmm_client/src/tables/piewellstatus/mod.rs
  3124. ================
  3125. pub(crate) mod query;
  3126. pub(crate) mod resource;
  3127.  
  3128. ================
  3129. File: gmm_client/src/tables/piewellstatus/query.rs
  3130. ================
  3131. use leptos::*;
  3132. use serde::{Deserialize, Serialize};
  3133.  
  3134. /// Represents a row in the well status distribution report.
  3135. #[derive(Debug, Clone, Serialize, Deserialize)]
  3136. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3137. pub struct PieWellStatusRow {
  3138.     pub canonical: String,
  3139.     pub status_name: String,
  3140.     pub percentage: Option<f64>,
  3141. }
  3142.  
  3143. /// Fetches well status distribution data from multiple tables.
  3144. #[server]
  3145. pub async fn piewellstatus_fetch_by_canonical_name(
  3146.     canonical_name: String,
  3147. ) -> Result<Vec<PieWellStatusRow>, ServerFnError> {
  3148.     pub use PieWellStatusRow;
  3149.  
  3150.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3151.  
  3152.     let records = sqlx::query_as::<_, PieWellStatusRow>(
  3153.         "WITH filtered_wells AS (
  3154.            SELECT
  3155.                client.canonical,
  3156.                well_status.name AS status_name
  3157.            FROM
  3158.                client
  3159.            JOIN
  3160.                well_interest ON well_interest.client_id = client.id
  3161.            JOIN
  3162.                well ON well_interest.well_id = well.well_id
  3163.            JOIN
  3164.                well_status ON well.well_status_id = well_status.id
  3165.            WHERE
  3166.                client.canonical = ?
  3167.                AND well_status.name != ''
  3168.                AND well.api_or_uwi != ''
  3169.        ),
  3170.        status_counts AS (
  3171.            SELECT
  3172.                canonical,
  3173.                status_name,
  3174.                COUNT(*) AS status_count
  3175.            FROM
  3176.                filtered_wells
  3177.            GROUP BY
  3178.                canonical, status_name
  3179.        ),
  3180.        total_counts AS (
  3181.            SELECT
  3182.                canonical,
  3183.                COUNT(*) AS total_count
  3184.            FROM
  3185.                filtered_wells
  3186.            GROUP BY
  3187.                canonical
  3188.        ),
  3189.        percentage_counts AS (
  3190.            SELECT
  3191.                c.canonical,
  3192.                c.status_name,
  3193.                c.status_count,
  3194.                ROUND((c.status_count * 100.0 / t.total_count), 2) AS raw_percentage
  3195.            FROM
  3196.                status_counts c
  3197.            JOIN
  3198.                total_counts t ON c.canonical = t.canonical
  3199.        )
  3200.        SELECT
  3201.            p.canonical,
  3202.            p.status_name,
  3203.            CASE
  3204.                WHEN p.row_num = p.total_rows THEN ROUND(100 - SUM(p.raw_percentage) OVER (PARTITION BY p.canonical) + p.raw_percentage, 2)
  3205.                ELSE p.raw_percentage
  3206.            END AS percentage
  3207.        FROM (
  3208.            SELECT
  3209.                p.*,
  3210.                ROW_NUMBER() OVER (PARTITION BY p.canonical ORDER BY p.status_name) AS row_num,
  3211.                COUNT(*) OVER (PARTITION BY p.canonical) AS total_rows
  3212.            FROM
  3213.                percentage_counts p
  3214.        ) AS p
  3215.        ORDER BY
  3216.            p.canonical, p.status_name"
  3217.     )
  3218.     .bind(&canonical_name)
  3219.     .fetch_all(&land_pool)
  3220.     .await
  3221.     // log successful row count, then pass rows through
  3222.     .map(|rows| {
  3223.         log::debug!("Query succeeded: {} rows", rows.len());
  3224.         rows
  3225.     })
  3226.     .map_err(|e| {
  3227.         log::error!("Query failed: {}", e);
  3228.         ServerFnError::new(format!("Database error: {}", e))
  3229.     })?;
  3230.  
  3231.     Ok(records)
  3232. }
  3233.  
  3234. ================
  3235. File: gmm_client/src/tables/piewellstatus/resource.rs
  3236. ================
  3237. use leptos::*;
  3238. use super::query::PieWellStatusRow;
  3239. use crate::client_main_app::ctx::*;
  3240.  
  3241. /// Leptos resource for fetching well status distribution data.
  3242. #[derive(Clone)]
  3243. pub(crate) struct PieWellStatusResource {
  3244.     pub revenue_rows: Resource<String, Result<Vec<PieWellStatusRow>, ServerFnError>>,
  3245. }
  3246.  
  3247. use super::query::*;
  3248. impl PieWellStatusResource {
  3249.     pub fn new() -> Self {
  3250.         let revenue_rows = create_resource(
  3251.             move || {
  3252.                 let account_ctx = AccountCtx::use_context();
  3253.                 account_ctx.map(|ctx| ctx.account_memo.get().canonical_name.clone()).unwrap_or_default()
  3254.             },
  3255.             |canonical_name| async move {
  3256.                 piewellstatus_fetch_by_canonical_name(canonical_name)
  3257.                     .await
  3258.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  3259.             }
  3260.         );
  3261.  
  3262.         Self { revenue_rows }
  3263.     }
  3264. }
  3265.  
  3266. ================
  3267. File: gmm_client/src/tables/revenue/mod.rs
  3268. ================
  3269. pub(crate) mod query;
  3270. pub(crate) mod resource;
  3271.  
  3272. ================
  3273. File: gmm_client/src/tables/revenue/query.rs
  3274. ================
  3275. use leptos::*;
  3276. use serde::{Deserialize, Serialize};
  3277.  
  3278. /// Represents a row in the revenue report.
  3279. #[derive(Debug, Clone, Serialize, Deserialize)]
  3280. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3281. pub struct RevenueRow {
  3282.     pub original_file_path: String,
  3283.     pub production_start_date: Option<String>,
  3284.     pub production_end_date: Option<String>,
  3285.     pub sale_date: Option<String>,
  3286.     pub payment_date: Option<String>,
  3287.     pub product: Option<String>,
  3288.     pub pie_gross_revenue: Option<f64>,
  3289.     pub share_net_revenue: Option<f64>,
  3290. }
  3291.  
  3292. /// Fetches revenue data from `revenue_raw` by `canonical_name`.
  3293. #[server]
  3294. pub async fn revenue_fetch_by_canonical_name(
  3295.     canonical_name: String,
  3296. ) -> Result<Vec<RevenueRow>, ServerFnError> {
  3297.     // use leptos::*;
  3298.     pub use RevenueRow;
  3299.  
  3300.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3301.  
  3302.     let records = sqlx::query_as::<_, RevenueRow>(
  3303.         "SELECT original_file_path, production_start_date, production_end_date,
  3304.                sale_date, payment_date, product,
  3305.                pie_gross_revenue, share_net_revenue
  3306.         FROM revenue_raw
  3307.         WHERE well_canonical = ?
  3308.         ORDER BY sale_date DESC",
  3309.     )
  3310.     .bind(&canonical_name)
  3311.     .fetch_all(&land_pool)
  3312.     .await
  3313.     // log successful row count, then pass rows through
  3314.     .map(|rows| {
  3315.         log::debug!("Query succeeded: {} rows", rows.len());
  3316.         rows
  3317.     })
  3318.     .map_err(|e| {
  3319.         log::error!("Query failed: {}", e);
  3320.         ServerFnError::new(format!("Database error: {}", e))
  3321.     })?;
  3322.  
  3323.     Ok(records)
  3324. }
  3325.  
  3326. ================
  3327. File: gmm_client/src/tables/revenue/resource.rs
  3328. ================
  3329. use super::query::RevenueRow;
  3330. use crate::client_main_app::ctx::*;
  3331. use leptos::*;
  3332.  
  3333. /// Leptos resource for fetching revenue report data.
  3334.  
  3335. #[derive(Clone)]
  3336. pub(crate) struct RevenueResource {
  3337.     pub revenue_rows: Resource<String, Result<Vec<RevenueRow>, ServerFnError>>,
  3338. }
  3339.  
  3340. use super::query::*;
  3341. impl RevenueResource {
  3342.     pub fn new() -> Self {
  3343.         let revenue_rows = create_resource(
  3344.             move || {
  3345.                 let account_ctx = AccountCtx::use_context();
  3346.                 account_ctx
  3347.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  3348.                     .unwrap_or_default()
  3349.             },
  3350.             |canonical_name| async move {
  3351.                 revenue_fetch_by_canonical_name(canonical_name)
  3352.                     .await
  3353.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  3354.                 // Fixed conversion
  3355.             },
  3356.         );
  3357.  
  3358.         Self { revenue_rows }
  3359.     }
  3360. }
  3361.  
  3362. ================
  3363. File: gmm_client/src/tables/revjibdetails/mod.rs
  3364. ================
  3365. pub(crate) mod query;
  3366. pub(crate) mod resource;
  3367.  
  3368. ================
  3369. File: gmm_client/src/tables/revjibdetails/query.rs
  3370. ================
  3371. use leptos::*;
  3372. use serde::{Deserialize, Serialize};
  3373.  
  3374. /// Represents a row in the revjibdetails report.
  3375. #[derive(Debug, Clone, Serialize, Deserialize)]
  3376. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3377. pub struct RevJibDetailsRow {
  3378.     pub client: String,
  3379.     pub well_name: String,
  3380.     pub total_share_gross_revenue: f64,
  3381.     pub total_share_taxes: f64,
  3382.     pub total_share_deductions: f64,
  3383.     pub total_share_net_revenue: f64,
  3384.     pub total_jib_amount: f64,
  3385.     pub year: String,
  3386. }
  3387.  
  3388. /// Fetches unmatched JIB and Revenue details.
  3389. #[server]
  3390. pub async fn revjibdetails_fetch_by_canonical_name(
  3391.     canonical_name: String,
  3392. ) -> Result<Vec<RevJibDetailsRow>, ServerFnError> {
  3393.     use RevJibDetailsRow;
  3394.  
  3395.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3396.  
  3397.     let query = r#"
  3398.    WITH standardize_date AS (
  3399.        SELECT
  3400.            TRIM(pay_month) AS pay_month,
  3401.            payor,
  3402.            payee,
  3403.            amount,
  3404.            CASE
  3405.                WHEN pay_month LIKE '____-__-__' THEN pay_month
  3406.                WHEN pay_month LIKE '__/__/____' OR pay_month LIKE '_/__/____' OR pay_month LIKE '__/_/____' OR pay_month LIKE '_/_/____' THEN
  3407.                    CASE
  3408.                        WHEN length(pay_month) = 10 THEN strftime('%Y-%m-%d', substr(pay_month, 7, 4) || '-' || substr(pay_month, 1, 2) || '-' || substr(pay_month, 4, 2))
  3409.                        WHEN length(pay_month) = 9 THEN strftime('%Y-%m-%d', substr(pay_month, 6, 4) || '-0' || substr(pay_month, 1, 1) || '-' || substr(pay_month, 3, 2))
  3410.                        WHEN length(pay_month) = 8 THEN strftime('%Y-%m-%d', substr(pay_month, 5, 4) || '-' || substr(pay_month, 1, 2) || '-0' || substr(pay_month, 4, 1))
  3411.                        ELSE strftime('%Y-%m-%d', substr(pay_month, 4, 4) || '-0' || substr(pay_month, 1, 1) || '-0' || substr(pay_month, 3, 1))
  3412.                    END
  3413.                WHEN pay_month LIKE '___ __, ____' THEN strftime('%Y-%m-%d',
  3414.                    substr(pay_month, -4, 4) || '-' ||
  3415.                    CASE
  3416.                        WHEN substr(pay_month, 1, 3) = 'Jan' THEN '01'
  3417.                        WHEN substr(pay_month, 1, 3) = 'Feb' THEN '02'
  3418.                        WHEN substr(pay_month, 1, 3) = 'Mar' THEN '03'
  3419.                        WHEN substr(pay_month, 1, 3) = 'Apr' THEN '04'
  3420.                        WHEN substr(pay_month, 1, 3) = 'May' THEN '05'
  3421.                        WHEN substr(pay_month, 1, 3) = 'Jun' THEN '06'
  3422.                        WHEN substr(pay_month, 1, 3) = 'Jul' THEN '07'
  3423.                        WHEN substr(pay_month, 1, 3) = 'Aug' THEN '08'
  3424.                        WHEN substr(pay_month, 1, 3) = 'Sep' THEN '09'
  3425.                        WHEN substr(pay_month, 1, 3) = 'Oct' THEN '10'
  3426.                        WHEN substr(pay_month, 1, 3) = 'Nov' THEN '11'
  3427.                        WHEN substr(pay_month, 1, 3) = 'Dec' THEN '12'
  3428.                        ELSE '01'
  3429.                    END || '-' ||
  3430.                    CASE
  3431.                        WHEN length(trim(substr(pay_month, 5, 2))) = 1 THEN '0' || substr(pay_month, 5, 1)
  3432.                        ELSE substr(pay_month, 5, 2)
  3433.                    END
  3434.                )
  3435.                WHEN pay_month LIKE '__/__' THEN strftime('%Y-%m-%d', '20' || substr(pay_month, 4, 2) || '-' || substr(pay_month, 1, 2) || '-15')
  3436.                WHEN pay_month LIKE '____/__/__' THEN strftime('%Y-%m-%d', replace(pay_month, '/', '-'))
  3437.                WHEN pay_month LIKE '____-__' THEN pay_month || '-15'
  3438.                WHEN pay_month LIKE '__/__/__' THEN strftime('%Y-%m-%d', '20' || substr(pay_month, 7, 2) || '-' || substr(pay_month, 1, 2) || '-' || substr(pay_month, 4, 2))
  3439.                WHEN pay_month LIKE '__-__-____' OR pay_month LIKE '_-__-____' THEN
  3440.                    strftime('%Y-%m-%d',
  3441.                        substr(pay_month, -4) || '-' ||
  3442.                        CASE
  3443.                            WHEN length(pay_month) = 10 THEN substr(pay_month, 1, 2)
  3444.                            ELSE '0' || substr(pay_month, 1, 1)
  3445.                        END || '-' ||
  3446.                        CASE
  3447.                            WHEN length(pay_month) = 10 THEN substr(pay_month, 4, 2)
  3448.                            ELSE substr(pay_month, 3, 2)
  3449.                        END
  3450.                    )
  3451.                WHEN pay_month LIKE '__/____' OR pay_month LIKE '__-____' THEN
  3452.                    strftime('%Y-%m-%d', substr(pay_month, 4, 4) || '-' || substr(pay_month, 1, 2) || '-15')
  3453.                WHEN pay_month LIKE '____/__' THEN
  3454.                    strftime('%Y-%m-%d', substr(pay_month, 1, 4) || '-' || substr(pay_month, 6, 2) || '-15')
  3455.                WHEN pay_month LIKE '__-___-____' OR pay_month LIKE '_-___-____' THEN
  3456.                    strftime('%Y-%m-%d',
  3457.                        substr(pay_month, -4) || '-' ||
  3458.                        CASE
  3459.                            WHEN INSTR(UPPER(pay_month), '-JAN-') > 0 THEN '01'
  3460.                            WHEN INSTR(UPPER(pay_month), '-FEB-') > 0 THEN '02'
  3461.                            WHEN INSTR(UPPER(pay_month), '-MAR-') > 0 THEN '03'
  3462.                            WHEN INSTR(UPPER(pay_month), '-APR-') > 0 THEN '04'
  3463.                            WHEN INSTR(UPPER(pay_month), '-MAY-') > 0 THEN '05'
  3464.                            WHEN INSTR(UPPER(pay_month), '-JUN-') > 0 THEN '06'
  3465.                            WHEN INSTR(UPPER(pay_month), '-JUL-') > 0 THEN '07'
  3466.                            WHEN INSTR(UPPER(pay_month), '-AUG-') > 0 THEN '08'
  3467.                            WHEN INSTR(UPPER(pay_month), '-SEP-') > 0 THEN '09'
  3468.                            WHEN INSTR(UPPER(pay_month), '-OCT-') > 0 THEN '10'
  3469.                            WHEN INSTR(UPPER(pay_month), '-NOV-') > 0 THEN '11'
  3470.                            WHEN INSTR(UPPER(pay_month), '-DEC-') > 0 THEN '12'
  3471.                            ELSE '01'
  3472.                        END || '-' ||
  3473.                        CASE
  3474.                            WHEN length(pay_month) = 11 THEN substr(pay_month, 1, 2)
  3475.                            ELSE '0' || substr(pay_month, 1, 1)
  3476.                        END
  3477.                    )
  3478.                ELSE NULL
  3479.            END AS normalized_date
  3480.        FROM jibs
  3481.    ),
  3482.    summary_jibs AS (
  3483.        SELECT
  3484.             payor,
  3485.            payee,
  3486.            STRFTIME('%Y', normalized_date) AS normalized_year,
  3487.            ROUND(SUM(1.0 * amount), 2) AS total_jib_amount
  3488.        FROM standardize_date
  3489.        GROUP BY payee, normalized_year
  3490.    ),
  3491.    summary_revenue AS (
  3492.        SELECT
  3493.             owner_name_client,
  3494.            well_property_name,
  3495.            STRFTIME('%Y', check_date) AS revenue_year,
  3496.            ROUND(SUM(1.0 * share_gross_revenue), 2) AS total_share_gross_revenue,
  3497.            ROUND(SUM(1.0 * share_taxes), 2) AS total_share_taxes,
  3498.            ROUND(SUM(1.0 * share_deductions), 2) AS total_share_deductions,
  3499.            ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net_revenue
  3500.        FROM revenue_raw
  3501.        WHERE aggregation_level IN ('i', 'e', 'h')
  3502.        GROUP BY well_property_name, revenue_year
  3503.    )
  3504.    SELECT
  3505.        sj.payee AS well_name,
  3506.        0.0 AS total_share_gross_revenue,
  3507.        0.0 AS total_share_taxes,
  3508.        0.0 AS total_share_deductions,
  3509.        0.0 AS total_share_net_revenue,
  3510.        sj.total_jib_amount,
  3511.        sj.normalized_year AS year
  3512.    FROM summary_jibs AS sj
  3513.    LEFT JOIN summary_revenue AS sr
  3514.      ON sj.payee = sr.well_property_name
  3515.      AND sj.normalized_year = sr.revenue_year
  3516.      AND sj.payor = sr.owner_name_client = ?
  3517.    WHERE sr.well_property_name IS NULL
  3518.  
  3519.    UNION ALL
  3520.  
  3521.    SELECT
  3522.        sr.well_property_name AS well_name,
  3523.        sr.total_share_gross_revenue,
  3524.        sr.total_share_taxes,
  3525.        sr.total_share_deductions,
  3526.        sr.total_share_net_revenue,
  3527.        0.0 AS total_jib_amount,
  3528.        sr.revenue_year AS year
  3529.    FROM summary_revenue AS sr
  3530.    LEFT JOIN summary_jibs AS sj
  3531.      ON sr.well_property_name = sj.payee
  3532.      AND sr.revenue_year = sj.normalized_year
  3533.      AND sr.owner_name_client = sj.payor = ?
  3534.    WHERE sj.payee IS NULL
  3535.    ORDER BY well_name, year;
  3536.    "#;
  3537.  
  3538.     let records = sqlx::query_as::<_, RevJibDetailsRow>(query)
  3539.         .bind(&canonical_name)
  3540.         .fetch_all(&land_pool)
  3541.         .await
  3542.         // log successful row count, then pass rows through
  3543.         .map(|rows| {
  3544.             log::debug!("Query succeeded: {} rows", rows.len());
  3545.             rows
  3546.         })
  3547.         .map_err(|e| {
  3548.             log::error!("Query failed: {}", e);
  3549.             ServerFnError::new(format!("Database error: {}", e))
  3550.         })?;
  3551.  
  3552.     Ok(records)
  3553. }
  3554.  
  3555. ================
  3556. File: gmm_client/src/tables/revjibdetails/resource.rs
  3557. ================
  3558. use super::query::RevJibDetailsRow;
  3559. use crate::client_main_app::ctx::*;
  3560. use leptos::*;
  3561.  
  3562. /// Leptos resource for fetching revenue and JIB details data.
  3563. #[derive(Clone)]
  3564. pub(crate) struct RevJibDetailsResource {
  3565.     pub revenue_rows: Resource<String, Result<Vec<RevJibDetailsRow>, ServerFnError>>,
  3566. }
  3567.  
  3568. use super::query::*;
  3569. impl RevJibDetailsResource {
  3570.     pub fn new() -> Self {
  3571.         let revenue_rows = create_resource(
  3572.             move || {
  3573.                 let account_ctx = AccountCtx::use_context();
  3574.                 account_ctx
  3575.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  3576.                     .unwrap_or_default()
  3577.             },
  3578.             |canonical_name| async move {
  3579.                 revjibdetails_fetch_by_canonical_name(canonical_name)
  3580.                     .await
  3581.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  3582.                 // Fixed conversion
  3583.             },
  3584.         );
  3585.  
  3586.         Self { revenue_rows }
  3587.     }
  3588. }
  3589.  
  3590. ================
  3591. File: gmm_client/src/tables/revjibsummary/mod.rs
  3592. ================
  3593. pub(crate) mod query;
  3594. pub(crate) mod resource;
  3595.  
  3596. ================
  3597. File: gmm_client/src/tables/revjibsummary/query.rs
  3598. ================
  3599. use leptos::*;
  3600. use serde::{Deserialize, Serialize};
  3601.  
  3602. /// Represents a row in the revjibsummary report.
  3603. #[derive(Debug, Clone, Serialize, Deserialize)]
  3604. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3605. pub struct RevJibSummaryRow {
  3606.     pub client: String,
  3607.     pub operator_name: String,
  3608.     pub total_share_net_revenue: f64,
  3609.     pub total_jib_amount: f64,
  3610.     pub year: String,
  3611. }
  3612.  
  3613. /// Fetches JIB/Revenue summary comparisons by client/operator/year.
  3614. #[server]
  3615. pub async fn revjibsummary_fetch_by_canonical_name(
  3616.     canonical_name: String,
  3617. ) -> Result<Vec<RevJibSummaryRow>, ServerFnError> {
  3618.     use RevJibSummaryRow;
  3619.  
  3620.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3621.  
  3622.     let query = r#"
  3623.        WITH standardize_date AS (
  3624.            SELECT
  3625.                TRIM(pay_month) AS pay_month,
  3626.                payor,
  3627.                payee,
  3628.                amount,
  3629.                CASE
  3630.                    WHEN pay_month LIKE '____-__-__' THEN pay_month
  3631.                    WHEN pay_month LIKE '__/__/____' OR pay_month LIKE '_/__/____' OR pay_month LIKE '__/_/____' OR pay_month LIKE '_/_/____' THEN
  3632.                        CASE
  3633.                            WHEN length(pay_month) = 10 THEN strftime('%Y-%m-%d', substr(pay_month, 7, 4) || '-' || substr(pay_month, 1, 2) || '-' || substr(pay_month, 4, 2))
  3634.                            WHEN length(pay_month) = 9 THEN strftime('%Y-%m-%d', substr(pay_month, 6, 4) || '-0' || substr(pay_month, 1, 1) || '-' || substr(pay_month, 3, 2))
  3635.                            WHEN length(pay_month) = 8 THEN strftime('%Y-%m-%d', substr(pay_month, 5, 4) || '-' || substr(pay_month, 1, 2) || '-0' || substr(pay_month, 4, 1))
  3636.                            ELSE strftime('%Y-%m-%d', substr(pay_month, 4, 4) || '-0' || substr(pay_month, 1, 1) || '-0' || substr(pay_month, 3, 1))
  3637.                        END
  3638.                    WHEN pay_month LIKE '___ __, ____' THEN strftime('%Y-%m-%d',
  3639.                        substr(pay_month, -4, 4) || '-' ||
  3640.                        CASE
  3641.                            WHEN substr(pay_month, 1, 3) = 'Jan' THEN '01'
  3642.                            WHEN substr(pay_month, 1, 3) = 'Feb' THEN '02'
  3643.                            WHEN substr(pay_month, 1, 3) = 'Mar' THEN '03'
  3644.                            WHEN substr(pay_month, 1, 3) = 'Apr' THEN '04'
  3645.                            WHEN substr(pay_month, 1, 3) = 'May' THEN '05'
  3646.                            WHEN substr(pay_month, 1, 3) = 'Jun' THEN '06'
  3647.                            WHEN substr(pay_month, 1, 3) = 'Jul' THEN '07'
  3648.                            WHEN substr(pay_month, 1, 3) = 'Aug' THEN '08'
  3649.                            WHEN substr(pay_month, 1, 3) = 'Sep' THEN '09'
  3650.                            WHEN substr(pay_month, 1, 3) = 'Oct' THEN '10'
  3651.                            WHEN substr(pay_month, 1, 3) = 'Nov' THEN '11'
  3652.                            WHEN substr(pay_month, 1, 3) = 'Dec' THEN '12'
  3653.                            ELSE '01'
  3654.                        END || '-' ||
  3655.                        CASE
  3656.                            WHEN length(trim(substr(pay_month, 5, 2))) = 1 THEN '0' || substr(pay_month, 5, 1)
  3657.                            ELSE substr(pay_month, 5, 2)
  3658.                        END
  3659.                    )
  3660.                    WHEN pay_month LIKE '__/__' THEN strftime('%Y-%m-%d', '20' || substr(pay_month, 4, 2) || '-' || substr(pay_month, 1, 2) || '-15')
  3661.                    WHEN pay_month LIKE '____/__/__' THEN strftime('%Y-%m-%d', replace(pay_month, '/', '-'))
  3662.                    WHEN pay_month LIKE '____-__' THEN pay_month || '-15'
  3663.                    WHEN pay_month LIKE '__/__/__' THEN strftime('%Y-%m-%d', '20' || substr(pay_month, 7, 2) || '-' || substr(pay_month, 1, 2) || '-' || substr(pay_month, 4, 2))
  3664.                    WHEN pay_month LIKE '__-__-____' OR pay_month LIKE '_-__-____' THEN
  3665.                        strftime('%Y-%m-%d',
  3666.                            substr(pay_month, -4) || '-' ||
  3667.                            CASE
  3668.                                WHEN length(pay_month) = 10 THEN substr(pay_month, 1, 2)
  3669.                                ELSE '0' || substr(pay_month, 1, 1)
  3670.                            END || '-' ||
  3671.                            CASE
  3672.                                WHEN length(pay_month) = 10 THEN substr(pay_month, 4, 2)
  3673.                                ELSE substr(pay_month, 3, 2)
  3674.                            END
  3675.                        )
  3676.                    WHEN pay_month LIKE '__/____' OR pay_month LIKE '__-____' THEN
  3677.                        strftime('%Y-%m-%d', substr(pay_month, 4, 4) || '-' || substr(pay_month, 1, 2) || '-15')
  3678.                    WHEN pay_month LIKE '____/__' THEN
  3679.                        strftime('%Y-%m-%d', substr(pay_month, 1, 4) || '-' || substr(pay_month, 6, 2) || '-15')
  3680.                    WHEN pay_month LIKE '__-___-____' OR pay_month LIKE '_-___-____' THEN
  3681.                        strftime('%Y-%m-%d',
  3682.                            substr(pay_month, -4) || '-' ||
  3683.                            CASE
  3684.                                WHEN INSTR(UPPER(pay_month), '-JAN-') > 0 THEN '01'
  3685.                                WHEN INSTR(UPPER(pay_month), '-FEB-') > 0 THEN '02'
  3686.                                WHEN INSTR(UPPER(pay_month), '-MAR-') > 0 THEN '03'
  3687.                                WHEN INSTR(UPPER(pay_month), '-APR-') > 0 THEN '04'
  3688.                                WHEN INSTR(UPPER(pay_month), '-MAY-') > 0 THEN '05'
  3689.                                WHEN INSTR(UPPER(pay_month), '-JUN-') > 0 THEN '06'
  3690.                                WHEN INSTR(UPPER(pay_month), '-JUL-') > 0 THEN '07'
  3691.                                WHEN INSTR(UPPER(pay_month), '-AUG-') > 0 THEN '08'
  3692.                                WHEN INSTR(UPPER(pay_month), '-SEP-') > 0 THEN '09'
  3693.                                WHEN INSTR(UPPER(pay_month), '-OCT-') > 0 THEN '10'
  3694.                                WHEN INSTR(UPPER(pay_month), '-NOV-') > 0 THEN '11'
  3695.                                WHEN INSTR(UPPER(pay_month), '-DEC-') > 0 THEN '12'
  3696.                                ELSE '01'
  3697.                            END || '-' ||
  3698.                            CASE
  3699.                                WHEN length(pay_month) = 11 THEN substr(pay_month, 1, 2)
  3700.                                ELSE '0' || substr(pay_month, 1, 1)
  3701.                            END
  3702.                        )
  3703.                    ELSE NULL
  3704.                END AS normalized_date
  3705.            FROM jibs
  3706.        ),
  3707.        summary_jibs AS (
  3708.            SELECT
  3709.                payor,
  3710.                payee,
  3711.                STRFTIME('%Y', normalized_date) AS normalized_year,
  3712.                ROUND(SUM(1.0 * amount), 2) AS total_jib_amount
  3713.            FROM standardize_date
  3714.            GROUP BY payee, normalized_year
  3715.        ),
  3716.        summary_revenue AS (
  3717.            SELECT
  3718.                owner_name_client,
  3719.                operator_purchaser,
  3720.                STRFTIME('%Y', check_date) AS revenue_year,
  3721.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net_revenue
  3722.            FROM revenue_raw
  3723.            WHERE aggregation_level IN ('i', 'e', 'h')
  3724.            GROUP BY operator_purchaser, revenue_year
  3725.        )
  3726.        SELECT
  3727.            COALESCE(op1.name, op2.name) AS operator_name,
  3728.            COALESCE(sr.total_share_net_revenue, 0.0) AS total_share_net_revenue,
  3729.            COALESCE(sj.total_jib_amount, 0.0) AS total_jib_amount,
  3730.            COALESCE(sj.normalized_year, sr.revenue_year) AS year
  3731.        FROM summary_jibs sj
  3732.        LEFT JOIN summary_revenue sr
  3733.            ON sj.payee = sr.operator_purchaser
  3734.        AND sj.normalized_year = sr.revenue_year
  3735.        AND sj.payor = sr.owner_name_client = ?
  3736.        LEFT JOIN operator op1
  3737.            ON op1.canonical = sj.payee
  3738.        LEFT JOIN operator op2
  3739.            ON op2.canonical = sr.operator_purchaser
  3740.        GROUP BY operator_name, year
  3741.        HAVING year IS NOT NULL
  3742.  
  3743.        UNION ALL
  3744.  
  3745.        SELECT
  3746.            COALESCE(op2.name, op1.name) AS operator_name,
  3747.            COALESCE(sr.total_share_net_revenue, 0.0) AS total_share_net_revenue,
  3748.            COALESCE(sj.total_jib_amount, 0.0) AS total_jib_amount,
  3749.            COALESCE(sr.revenue_year, sj.normalized_year) AS year
  3750.        FROM summary_revenue sr
  3751.        LEFT JOIN summary_jibs sj
  3752.            ON sr.operator_purchaser = sj.payee
  3753.        AND sr.revenue_year = sj.normalized_year
  3754.        AND sr.owner_name_client = sj.payor = ?
  3755.        LEFT JOIN operator op1
  3756.            ON op1.canonical = sj.payee
  3757.        LEFT JOIN operator op2
  3758.            ON op2.canonical = sr.operator_purchaser
  3759.        WHERE sj.payee IS NULL
  3760.        GROUP BY operator_name, year
  3761.        HAVING year IS NOT NULL
  3762.        ORDER BY operator_name, year;
  3763.    "#;
  3764.  
  3765.     let records = sqlx::query_as::<_, RevJibSummaryRow>(query)
  3766.         .bind(&canonical_name)
  3767.         .fetch_all(&land_pool)
  3768.         .await
  3769.         // log successful row count, then pass rows through
  3770.         .map(|rows| {
  3771.             log::debug!("Query succeeded: {} rows", rows.len());
  3772.             rows
  3773.         })
  3774.         .map_err(|e| {
  3775.             log::error!("Query failed: {}", e);
  3776.             ServerFnError::new(format!("Database error: {}", e))
  3777.         })?;
  3778.  
  3779.     Ok(records)
  3780. }
  3781.  
  3782. ================
  3783. File: gmm_client/src/tables/revjibsummary/resource.rs
  3784. ================
  3785. use super::query::RevJibSummaryRow;
  3786. use crate::client_main_app::ctx::*;
  3787. use leptos::*;
  3788.  
  3789. /// Leptos resource for fetching revenue and JIB summary data.
  3790. #[derive(Clone)]
  3791. pub(crate) struct RevJibSummaryResource {
  3792.     pub revenue_rows: Resource<String, Result<Vec<RevJibSummaryRow>, ServerFnError>>,
  3793. }
  3794.  
  3795. use super::query::*;
  3796. impl RevJibSummaryResource {
  3797.     pub fn new() -> Self {
  3798.         let revenue_rows = create_resource(
  3799.             move || {
  3800.                 let account_ctx = AccountCtx::use_context();
  3801.                 account_ctx
  3802.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  3803.                     .unwrap_or_default()
  3804.             },
  3805.             |canonical_name| async move {
  3806.                 revjibsummary_fetch_by_canonical_name(canonical_name)
  3807.                     .await
  3808.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  3809.                 // Fixed conversion
  3810.             },
  3811.         );
  3812.  
  3813.         Self { revenue_rows }
  3814.     }
  3815. }
  3816.  
  3817. ================
  3818. File: gmm_client/src/tables/statslistofcounts/mod.rs
  3819. ================
  3820. pub(crate) mod query;
  3821. pub(crate) mod resource;
  3822.  
  3823. ================
  3824. File: gmm_client/src/tables/statslistofcounts/query.rs
  3825. ================
  3826. use leptos::*;
  3827. use serde::{Deserialize, Serialize};
  3828.  
  3829. /// Represents a summary row of asset/well/lease stats for a client.
  3830. #[derive(Debug, Clone, Serialize, Deserialize)]
  3831. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3832. pub struct StatsListOfCountsRow {
  3833.     pub client: String,
  3834.     pub number_of_states: Option<i64>,
  3835.     pub number_of_counties: Option<i64>,
  3836.     pub number_of_assets: Option<i64>,
  3837.     pub number_of_leases: Option<i64>,
  3838.     pub number_of_wells: Option<i64>,
  3839. }
  3840.  
  3841. /// Fetches client-level stats on wells, leases, assets, etc.
  3842. #[server]
  3843. pub async fn statslistofcounts_fetch_by_canonical_name(
  3844.     canonical_name: String,
  3845. ) -> Result<Vec<StatsListOfCountsRow>, ServerFnError> {
  3846.     pub use StatsListOfCountsRow;
  3847.  
  3848.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3849.  
  3850.     let records = sqlx::query_as::<_, StatsListOfCountsRow>(
  3851.         "WITH metrics AS (
  3852.            SELECT
  3853.                client.canonical AS client,
  3854.                'Number of States' AS metric,
  3855.                COUNT(DISTINCT well.state) AS value
  3856.            FROM well
  3857.            JOIN well_status ON well_status.id = well.well_status_id
  3858.            JOIN well_interest ON well_interest.well_id = well.well_id
  3859.            JOIN client ON client.id = well_interest.client_id
  3860.            WHERE LOWER(well_status.name) = 'producing' AND well.state != ''
  3861.            AND client.canonical = ?
  3862.  
  3863.            UNION ALL
  3864.  
  3865.            SELECT
  3866.                client.canonical AS client,
  3867.                'Number of Counties' AS metric,
  3868.                COUNT(DISTINCT well.county) AS value
  3869.            FROM well
  3870.            JOIN well_status ON well_status.id = well.well_status_id
  3871.            JOIN well_interest ON well_interest.well_id = well.well_id
  3872.            JOIN client ON client.id = well_interest.client_id
  3873.            WHERE LOWER(well_status.name) = 'producing' AND well.state != ''
  3874.            AND client.canonical = ?
  3875.  
  3876.            UNION ALL
  3877.  
  3878.            SELECT
  3879.                client.canonical AS client,
  3880.                'Number of Assets' AS metric,
  3881.                COUNT(asset.asset_id) AS value
  3882.            FROM asset
  3883.            JOIN client ON client.id = asset.client_id
  3884.            WHERE client.canonical = ?
  3885.  
  3886.            UNION ALL
  3887.  
  3888.            SELECT
  3889.                client.canonical AS client,
  3890.                'Number of Leases' AS metric,
  3891.                COUNT(lease.lease_id) AS value
  3892.            FROM lease
  3893.            JOIN client ON client.id = lease.client_id
  3894.            WHERE client.canonical = ?
  3895.  
  3896.            UNION ALL
  3897.  
  3898.            SELECT
  3899.                client.canonical AS client,
  3900.                'Number of Wells' AS metric,
  3901.                COUNT(DISTINCT well_interest.well_id) AS value
  3902.            FROM well_interest
  3903.            JOIN client ON client.id = well_interest.client_id
  3904.            WHERE client.canonical = ?
  3905.        )
  3906.        SELECT
  3907.            client,
  3908.            MAX(CASE WHEN metric = 'Number of States' THEN value ELSE NULL END) AS number_of_states,
  3909.            MAX(CASE WHEN metric = 'Number of Counties' THEN value ELSE NULL END) AS number_of_counties,
  3910.            MAX(CASE WHEN metric = 'Number of Assets' THEN value ELSE NULL END) AS number_of_assets,
  3911.            MAX(CASE WHEN metric = 'Number of Leases' THEN value ELSE NULL END) AS number_of_leases,
  3912.            MAX(CASE WHEN metric = 'Number of Wells' THEN value ELSE NULL END) AS number_of_wells
  3913.        FROM metrics"
  3914.     )
  3915.     .bind(&canonical_name)
  3916.     .fetch_all(&land_pool)
  3917.     .await
  3918.     // log successful row count, then pass rows through
  3919.     .map(|rows| {
  3920.         log::debug!("Query succeeded: {} rows", rows.len());
  3921.         rows
  3922.     })
  3923.     .map_err(|e| {
  3924.         log::error!("Query failed: {}", e);
  3925.         ServerFnError::new(format!("Database error: {}", e))
  3926.     })?;
  3927.  
  3928.     Ok(records)
  3929. }
  3930.  
  3931. ================
  3932. File: gmm_client/src/tables/statslistofcounts/resource.rs
  3933. ================
  3934. use super::query::StatsListOfCountsRow;
  3935. use crate::client_main_app::ctx::*;
  3936. use leptos::*;
  3937.  
  3938. /// Leptos resource for fetching portfolio summary statistics.
  3939. #[derive(Clone)]
  3940. pub(crate) struct StatsListOfCountsResource {
  3941.     pub stats_rows: Resource<String, Result<Vec<StatsListOfCountsRow>, ServerFnError>>,
  3942. }
  3943.  
  3944. use super::query::*;
  3945. impl StatsListOfCountsResource {
  3946.     pub fn new() -> Self {
  3947.         let stats_rows = create_resource(
  3948.             move || {
  3949.                 let account_ctx = AccountCtx::use_context();
  3950.                 account_ctx
  3951.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  3952.                     .unwrap_or_default()
  3953.             },
  3954.             |canonical_name| async move {
  3955.                 statslistofcounts_fetch_by_canonical_name(canonical_name)
  3956.                     .await
  3957.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  3958.             },
  3959.         );
  3960.  
  3961.         Self { stats_rows }
  3962.     }
  3963. }
  3964.  
  3965. ================
  3966. File: gmm_client/src/tables/statsproduction/mod.rs
  3967. ================
  3968. pub(crate) mod query;
  3969. pub(crate) mod resource;
  3970.  
  3971. ================
  3972. File: gmm_client/src/tables/statsproduction/query.rs
  3973. ================
  3974. use leptos::*;
  3975. use serde::{Deserialize, Serialize};
  3976.  
  3977. /// Represents a row of product-level production and pricing statistics across all clients.
  3978. #[derive(Debug, Clone, Serialize, Deserialize)]
  3979. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  3980. pub struct StatsProductionRow {
  3981.     pub product: String,
  3982.     pub avg_price: Option<f64>,
  3983.     pub min_price: Option<f64>,
  3984.     pub max_price: Option<f64>,
  3985.     pub price_volatility: Option<f64>,      // actually price variance
  3986.     pub avg_prod_rate: Option<f64>,
  3987.     pub min_prod_rate: Option<f64>,
  3988.     pub max_prod_rate: Option<f64>,
  3989.     pub prod_volatility: Option<f64>,       // actually production variance
  3990.     pub gross_avg_rate: Option<f64>,
  3991. }
  3992.  
  3993. /// Fetches production and pricing statistics by product across all clients.
  3994. #[server]
  3995. pub async fn statsproduction_fetch_all() -> Result<Vec<StatsProductionRow>, ServerFnError> {
  3996.     pub use StatsProductionRow;
  3997.  
  3998.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  3999.  
  4000.     let records = sqlx::query_as::<_, StatsProductionRow>(
  4001.         r#"
  4002.        WITH base AS (
  4003.            SELECT
  4004.                product,
  4005.                1.0 * unit_price AS unit_price,
  4006.                1000.0 * 1.0 * share_volume / (julianday('now') - julianday('2019-11-01')) AS daily_prod_rate,
  4007.                1.0 * unit_price * (1000.0 * 1.0 * share_volume / (julianday('now') - julianday('2019-11-01'))) AS daily_revenue
  4008.            FROM revenue_raw
  4009.            WHERE
  4010.                1.0 * unit_price > 0 AND
  4011.                1.0 * share_volume > 0
  4012.        ),
  4013.        avg_stats AS (
  4014.            SELECT
  4015.                product,
  4016.                AVG(unit_price) AS avg_price,
  4017.                AVG(daily_prod_rate) AS avg_prod_rate
  4018.            FROM base
  4019.            GROUP BY product
  4020.        ),
  4021.        volatility_stats AS (
  4022.            SELECT
  4023.                b.product,
  4024.                -- Variance of price
  4025.                AVG((b.unit_price - a.avg_price) * (b.unit_price - a.avg_price)) AS price_volatility,
  4026.                -- Variance of production
  4027.                AVG((b.daily_prod_rate - a.avg_prod_rate) * (b.daily_prod_rate - a.avg_prod_rate)) AS prod_volatility
  4028.            FROM base b
  4029.            JOIN avg_stats a ON b.product = a.product
  4030.            GROUP BY b.product
  4031.        ),
  4032.        final_stats AS (
  4033.            SELECT
  4034.                product,
  4035.                MIN(unit_price) AS min_price,
  4036.                MAX(unit_price) AS max_price,
  4037.                MIN(daily_prod_rate) AS min_prod_rate,
  4038.                MAX(daily_prod_rate) AS max_prod_rate,
  4039.                AVG(daily_revenue) AS gross_avg_rate
  4040.            FROM base
  4041.            GROUP BY product
  4042.        )
  4043.        SELECT
  4044.            a.product,
  4045.            ROUND(a.avg_price, 2) AS avg_price,
  4046.            ROUND(f.min_price, 2) AS min_price,
  4047.            ROUND(f.max_price, 2) AS max_price,
  4048.            ROUND(v.price_volatility, 2) AS price_volatility,
  4049.            ROUND(a.avg_prod_rate, 2) AS avg_prod_rate,
  4050.            ROUND(f.min_prod_rate, 2) AS min_prod_rate,
  4051.            ROUND(f.max_prod_rate, 2) AS max_prod_rate,
  4052.            ROUND(v.prod_volatility, 2) AS prod_volatility,
  4053.            ROUND(f.gross_avg_rate, 2) AS gross_avg_rate
  4054.        FROM avg_stats a
  4055.        JOIN volatility_stats v ON a.product = v.product
  4056.        JOIN final_stats f ON a.product = f.product
  4057.        ORDER BY a.product;
  4058.        "#
  4059.     )
  4060.     .fetch_all(&land_pool)
  4061.     .await
  4062.     .map(|rows| {
  4063.         log::debug!("Query succeeded: {} rows", rows.len());
  4064.         rows
  4065.     })
  4066.     .map_err(|e| {
  4067.         log::error!("Query failed: {}", e);
  4068.         ServerFnError::new(format!("Database error: {}", e))
  4069.     })?;
  4070.  
  4071.     Ok(records)
  4072. }
  4073.  
  4074. ================
  4075. File: gmm_client/src/tables/statsproduction/resource.rs
  4076. ================
  4077. use super::query::StatsProductionRow;
  4078. use crate::tables::statsproduction::query::statsproduction_fetch_all;
  4079. use leptos::*;
  4080.  
  4081. /// Leptos resource for fetching product-level production and pricing statistics.
  4082. #[derive(Clone)]
  4083. pub(crate) struct StatsProductionResource {
  4084.     pub stats_rows: Resource<(), Result<Vec<StatsProductionRow>, ServerFnError>>,
  4085. }
  4086.  
  4087. impl StatsProductionResource {
  4088.     pub fn new() -> Self {
  4089.         let stats_rows = create_resource(
  4090.             || (),
  4091.             |_| async move {
  4092.                 statsproduction_fetch_all()
  4093.                     .await
  4094.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4095.             },
  4096.         );
  4097.  
  4098.         Self { stats_rows }
  4099.     }
  4100. }
  4101.  
  4102. ================
  4103. File: gmm_client/src/tables/statstopoperators/mod.rs
  4104. ================
  4105. pub(crate) mod query;
  4106. pub(crate) mod resource;
  4107.  
  4108. ================
  4109. File: gmm_client/src/tables/statstopoperators/query.rs
  4110. ================
  4111. use leptos::*;
  4112. use serde::{Deserialize, Serialize};
  4113.  
  4114. /// Represents a row showing top operators by client revenue.
  4115. #[derive(Debug, Clone, Serialize, Deserialize)]
  4116. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4117. pub struct StatsTopOperatorsRow {
  4118.     pub owner_name_client: String,
  4119.     pub operator_purchaser: String,
  4120.     pub owner_net_revenue: Option<f64>,
  4121.     pub exponential_mean: Option<f64>,
  4122.     pub scatter: Option<f64>,
  4123. }
  4124.  
  4125. /// Fetches top operators by revenue per client for the last month.
  4126. #[server]
  4127. pub async fn statstopoperators_fetch_by_canonical_name(
  4128.     canonical_name: String,
  4129. ) -> Result<Vec<StatsTopOperatorsRow>, ServerFnError> {
  4130.     pub use StatsTopOperatorsRow;
  4131.  
  4132.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4133.  
  4134.     let records = sqlx::query_as::<_, StatsTopOperatorsRow>(
  4135.         r#"
  4136.        WITH total AS (
  4137.            SELECT
  4138.                AVG(1.0 * share_net_revenue) AS avg_share_net
  4139.            FROM
  4140.                revenue_raw
  4141.            WHERE
  4142.                owner_name_client = ?
  4143.                AND 1.0 * share_net_revenue > 0
  4144.                AND strftime('%Y-%m', check_date) = strftime('%Y-%m', 'now', '-1 month')
  4145.        ),
  4146.        operator_stats AS (
  4147.            SELECT
  4148.                rr.owner_name_client,
  4149.                o.name AS operator_name,
  4150.                ROUND(SUM(1.0 * rr.share_net_revenue), 2) AS total_share_net,
  4151.                AVG(1.0 * rr.share_net_revenue) AS exponential_mean,  
  4152.                AVG((1.0 * rr.share_net_revenue - t.avg_share_net) *
  4153.                    (1.0 * rr.share_net_revenue - t.avg_share_net)) AS scatter
  4154.            FROM
  4155.                revenue_raw rr,
  4156.                total t
  4157.            JOIN
  4158.                operator o ON o.canonical = rr.operator_purchaser
  4159.            WHERE
  4160.                rr.owner_name_client = ?
  4161.                AND 1.0 * rr.share_net_revenue > 0
  4162.                AND strftime('%Y-%m', rr.check_date) = strftime('%Y-%m', 'now', '-1 month')
  4163.            GROUP BY
  4164.                o.name
  4165.        ),
  4166.        ranked_operator_stats AS (
  4167.            SELECT
  4168.                owner_name_client,
  4169.                operator_name,
  4170.                total_share_net,
  4171.                exponential_mean,
  4172.                scatter,
  4173.                ROW_NUMBER() OVER (PARTITION BY owner_name_client ORDER BY total_share_net DESC) AS row_num
  4174.            FROM
  4175.                operator_stats
  4176.        )
  4177.        SELECT
  4178.            owner_name_client,
  4179.            operator_name,
  4180.            total_share_net AS owner_net_revenue,
  4181.            exponential_mean,
  4182.            scatter
  4183.        FROM
  4184.            ranked_operator_stats
  4185.        WHERE
  4186.            row_num <= 10
  4187.        ORDER BY
  4188.            row_num
  4189.        "#
  4190.     )
  4191.     .bind(&canonical_name)
  4192.     .fetch_all(&land_pool)
  4193.     .await
  4194.     // log successful row count, then pass rows through
  4195.     .map(|rows| {
  4196.         log::debug!("Query succeeded: {} rows", rows.len());
  4197.         rows
  4198.     })
  4199.     .map_err(|e| {
  4200.         log::error!("Query failed: {}", e);
  4201.         ServerFnError::new(format!("Database error: {}", e))
  4202.     })?;
  4203.  
  4204.     Ok(records)
  4205. }
  4206.  
  4207. ================
  4208. File: gmm_client/src/tables/statstopoperators/resource.rs
  4209. ================
  4210. use super::query::StatsTopOperatorsRow;
  4211. use crate::client_main_app::ctx::*;
  4212. use leptos::*;
  4213.  
  4214. /// Leptos resource for fetching top operators by client revenue.
  4215. #[derive(Clone)]
  4216. pub(crate) struct StatsTopOperatorsResource {
  4217.     pub top_operators: Resource<String, Result<Vec<StatsTopOperatorsRow>, ServerFnError>>,
  4218. }
  4219.  
  4220. use super::query::*;
  4221. impl StatsTopOperatorsResource {
  4222.     pub fn new() -> Self {
  4223.         let top_operators = create_resource(
  4224.             move || {
  4225.                 let account_ctx = AccountCtx::use_context();
  4226.                 account_ctx
  4227.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  4228.                     .unwrap_or_default()
  4229.             },
  4230.             |canonical_name| async move {
  4231.                 statstopoperators_fetch_by_canonical_name(canonical_name)
  4232.                     .await
  4233.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4234.             },
  4235.         );
  4236.  
  4237.         Self { top_operators }
  4238.     }
  4239. }
  4240.  
  4241. ================
  4242. File: gmm_client/src/tables/surfacerevenue/mod.rs
  4243. ================
  4244. pub(crate) mod query;
  4245. pub(crate) mod resource;
  4246.  
  4247. ================
  4248. File: gmm_client/src/tables/surfacerevenue/query.rs
  4249. ================
  4250. use leptos::*;
  4251. use serde::{Deserialize, Serialize};
  4252.  
  4253. #[derive(Debug, Clone, Serialize, Deserialize)]
  4254. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4255. pub struct SurfaceRevenueRow {
  4256.     pub owner_name_client: String,
  4257.     pub operator_purchaser: String,
  4258.     pub description: String,
  4259.     pub gross_revenue: Option<f64>,
  4260.     pub taxes: Option<f64>,
  4261.     pub deductions: Option<f64>,
  4262.     pub net_revenue: Option<f64>,
  4263.     pub payment_amount: Option<f64>,
  4264.     pub payment_date: Option<String>,
  4265. }
  4266.  
  4267. #[server]
  4268. pub async fn surfacerevenue_fetch_by_canonical_name(
  4269.     canonical_name: String,
  4270. ) -> Result<Vec<SurfaceRevenueRow>, ServerFnError> {
  4271.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4272.  
  4273.     let records = sqlx::query_as::<_, SurfaceRevenueRow>(
  4274.         "SELECT
  4275.                rr.owner_name_client,
  4276.                o.name AS operator_name,
  4277.                rr.well_property_name AS description,
  4278.                ROUND(SUM(1.0 * rr.share_gross_revenue), 2) AS gross_revenue,
  4279.                ROUND(SUM(rr.share_taxes), 2) AS taxes,
  4280.                ROUND(SUM(rr.share_deductions), 2) AS deductions,
  4281.                ROUND(SUM(1.0 * rr.share_net_revenue), 2) AS net_revenue,
  4282.                1.0 * rr.share_check_amount AS payment_amount,
  4283.                rr.check_date AS payment_date
  4284.            FROM
  4285.                revenue_raw rr
  4286.            JOIN
  4287.                operator o ON o.canonical = rr.operator_purchaser
  4288.            WHERE
  4289.                rr.owner_name_client = ?
  4290.                AND rr.aggregation_level = 'u'
  4291.            GROUP BY
  4292.                o.name, rr.well_property_name, rr.check_date, rr.share_check_amount, rr.check_reference_number
  4293.            ORDER BY
  4294.                operator_name ASC, rr.check_date ASC"
  4295.     )
  4296.     .bind(&canonical_name)
  4297.     .fetch_all(&land_pool)
  4298.     .await
  4299.     // log successful row count, then pass rows through
  4300.     .map(|rows| {
  4301.         log::debug!("Query succeeded: {} rows", rows.len());
  4302.         rows
  4303.     })
  4304.     .map_err(|e| {
  4305.         log::error!("Query failed: {}", e);
  4306.         ServerFnError::new(format!("Database error: {}", e))
  4307.     })?;
  4308.  
  4309.     Ok(records)
  4310. }
  4311.  
  4312. ================
  4313. File: gmm_client/src/tables/surfacerevenue/resource.rs
  4314. ================
  4315. use leptos::*;
  4316. use super::query::SurfaceRevenueRow;
  4317. use crate::client_main_app::ctx::*;
  4318.  
  4319. /// Leptos resource for fetching summarized surface revenue data by operator and property.
  4320. #[derive(Clone)]
  4321. pub(crate) struct SurfaceRevenueResource {
  4322.     pub rows: Resource<String, Result<Vec<SurfaceRevenueRow>, ServerFnError>>,
  4323. }
  4324.  
  4325. use super::query::*;
  4326. impl SurfaceRevenueResource {
  4327.     pub fn new() -> Self {
  4328.         let rows = create_resource(
  4329.             move || {
  4330.                 let account_ctx = AccountCtx::use_context();
  4331.                 account_ctx
  4332.                     .map(|ctx| ctx.account_memo.get().canonical_name.clone())
  4333.                     .unwrap_or_default()
  4334.             },
  4335.             |canonical_name| async move {
  4336.                 surfacerevenue_fetch_by_canonical_name(canonical_name)
  4337.                     .await
  4338.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4339.             },
  4340.         );
  4341.  
  4342.         Self { rows }
  4343.     }
  4344. }
  4345.  
  4346. ================
  4347. File: gmm_client/src/tables/taxyear1099details/mod.rs
  4348. ================
  4349. pub(crate) mod query;
  4350. pub(crate) mod resource;
  4351.  
  4352. ================
  4353. File: gmm_client/src/tables/taxyear1099details/query.rs
  4354. ================
  4355. use leptos::*;
  4356. use serde::{Deserialize, Serialize};
  4357.  
  4358. /// Represents a row of 1099 tax details for the prior year.
  4359. #[derive(Debug, Clone, Serialize, Deserialize)]
  4360. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4361. pub struct TaxYear1099DetailsRow {
  4362.     pub payee: String,
  4363.     pub payor: String,
  4364.     pub tin: Option<String>,
  4365.     pub box_number: Option<String>,
  4366.     pub box_name: Option<String>,
  4367.     pub reported_amount: Option<f64>,
  4368. }
  4369.  
  4370. /// Fetches 1099 tax details from the prior tax year.
  4371. #[server]
  4372. pub async fn taxyear1099details_fetch_all() -> Result<Vec<TaxYear1099DetailsRow>, ServerFnError> {
  4373.     pub use TaxYear1099DetailsRow;
  4374.  
  4375.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4376.  
  4377.     let records = sqlx::query_as::<_, TaxYear1099DetailsRow>(
  4378.         "SELECT
  4379.                o.name AS operator_name,
  4380.                i.payor,
  4381.                i.tin,
  4382.                i.box_number,
  4383.                i.box_name,
  4384.                i.reported_amount
  4385.            FROM
  4386.                items1099 i
  4387.            JOIN
  4388.                operator o ON o.canonical = i.payee
  4389.            WHERE
  4390.                i.payee = ?
  4391.                AND i.tax_year = strftime('%Y', 'now', '-1 year')
  4392.            ORDER BY
  4393.                i.payor"
  4394.     )
  4395.     .fetch_all(&land_pool)
  4396.     .await
  4397.     // log successful row count, then pass rows through
  4398.     .map(|rows| {
  4399.         log::debug!("Query succeeded: {} rows", rows.len());
  4400.         rows
  4401.     })
  4402.     .map_err(|e| {
  4403.         log::error!("Query failed: {}", e);
  4404.         ServerFnError::new(format!("Database error: {}", e))
  4405.     })?;
  4406.  
  4407.     Ok(records)
  4408. }
  4409.  
  4410. ================
  4411. File: gmm_client/src/tables/taxyear1099details/resource.rs
  4412. ================
  4413. use super::query::TaxYear1099DetailsRow;
  4414. use leptos::*;
  4415.  
  4416. /// Leptos resource for fetching 1099 details for the prior tax year.
  4417. #[derive(Clone)]
  4418. pub(crate) struct TaxYear1099DetailsResource {
  4419.     pub details_rows: Resource<(), Result<Vec<TaxYear1099DetailsRow>, ServerFnError>>,
  4420. }
  4421.  
  4422. use super::query::*;
  4423. impl TaxYear1099DetailsResource {
  4424.     pub fn new() -> Self {
  4425.         let details_rows = create_resource(
  4426.             || (),
  4427.             |_| async move {
  4428.                 taxyear1099details_fetch_all()
  4429.                     .await
  4430.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4431.             },
  4432.         );
  4433.  
  4434.         Self { details_rows }
  4435.     }
  4436. }
  4437.  
  4438. ================
  4439. File: gmm_client/src/tables/taxyearfullyeartotals/mod.rs
  4440. ================
  4441. pub(crate) mod query;
  4442. pub(crate) mod resource;
  4443.  
  4444. ================
  4445. File: gmm_client/src/tables/taxyearfullyeartotals/query.rs
  4446. ================
  4447. use leptos::*;
  4448. use serde::{Deserialize, Serialize};
  4449.  
  4450. /// Represents a row of tax year totals for a client.
  4451. #[derive(Debug, Clone, Serialize, Deserialize)]
  4452. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4453. pub struct TaxYearFullYearTotalsRow {
  4454.     pub owner_name_client: String,
  4455.     pub gross_share: Option<f64>,
  4456.     pub share_taxes: Option<f64>,
  4457.     pub share_deductions: Option<f64>,
  4458.     pub net_revenue: Option<f64>,
  4459.     pub jibs: Option<f64>,
  4460. }
  4461.  
  4462. /// Fetches full-year tax totals from the previous calendar year.
  4463. #[server]
  4464. pub async fn taxyearfullyeartotals_fetch_all() -> Result<Vec<TaxYearFullYearTotalsRow>, ServerFnError> {
  4465.     pub use TaxYearFullYearTotalsRow;
  4466.  
  4467.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4468.  
  4469.     let records = sqlx::query_as::<_, TaxYearFullYearTotalsRow>(
  4470.         "WITH CalculatedValues AS (
  4471.            SELECT
  4472.                owner_name_client,
  4473.                1.0 * share_gross_revenue AS share_gross_revenue,
  4474.                1.0 * share_taxes AS share_taxes,
  4475.                1.0 * share_deductions AS share_deductions,
  4476.                1.0 * share_net_revenue AS share_net_revenue,
  4477.                1.0 * jibs.amount AS amount
  4478.            FROM
  4479.                revenue_raw
  4480.            JOIN
  4481.                jibs ON jibs.payor = revenue_raw.owner_name_client
  4482.            WHERE
  4483.                owner_name_client = ?
  4484.                AND aggregation_level IN ('i', 'e', 'h')
  4485.                AND check_date >= date('now', '-1 year', 'start of year')
  4486.                AND check_date < date('now', 'start of year')
  4487.        )
  4488.        SELECT
  4489.            owner_name_client,
  4490.            ROUND(SUM(share_gross_revenue), 2) AS gross_share,
  4491.            ROUND(SUM(share_taxes), 2) AS share_taxes,
  4492.            ROUND(SUM(share_deductions), 2) AS share_deductions,
  4493.            ROUND(SUM(share_net_revenue), 2) AS net_revenue,
  4494.            ROUND(SUM(amount), 2) AS jibs
  4495.        FROM
  4496.            CalculatedValues"
  4497.     )
  4498.     .fetch_all(&land_pool)
  4499.     .await
  4500.     // log successful row count, then pass rows through
  4501.     .map(|rows| {
  4502.         log::debug!("Query succeeded: {} rows", rows.len());
  4503.         rows
  4504.     })
  4505.     .map_err(|e| {
  4506.         log::error!("Query failed: {}", e);
  4507.         ServerFnError::new(format!("Database error: {}", e))
  4508.     })?;
  4509.  
  4510.     Ok(records)
  4511. }
  4512.  
  4513. ================
  4514. File: gmm_client/src/tables/taxyearfullyeartotals/resource.rs
  4515. ================
  4516. use super::query::TaxYearFullYearTotalsRow;
  4517. use leptos::*;
  4518.  
  4519. /// Leptos resource for fetching tax year full year totals.
  4520. #[derive(Clone)]
  4521. pub(crate) struct TaxYearFullYearTotalsResource {
  4522.     pub totals_rows: Resource<(), Result<Vec<TaxYearFullYearTotalsRow>, ServerFnError>>,
  4523. }
  4524.  
  4525. use super::query::*;
  4526. impl TaxYearFullYearTotalsResource {
  4527.     pub fn new() -> Self {
  4528.         let totals_rows = create_resource(
  4529.             || (),
  4530.             |_| async move {
  4531.                 taxyearfullyeartotals_fetch_all()
  4532.                     .await
  4533.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4534.             },
  4535.         );
  4536.  
  4537.         Self { totals_rows }
  4538.     }
  4539. }
  4540.  
  4541. ================
  4542. File: gmm_client/src/tables/taxyearinterestbystate/mod.rs
  4543. ================
  4544. pub(crate) mod query;
  4545. pub(crate) mod resource;
  4546.  
  4547. ================
  4548. File: gmm_client/src/tables/taxyearinterestbystate/query.rs
  4549. ================
  4550. use leptos::*;
  4551. use serde::{Deserialize, Serialize};
  4552.  
  4553. /// Represents a row of tax year revenue by state and interest type.
  4554. #[derive(Debug, Clone, Serialize, Deserialize)]
  4555. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4556. pub struct TaxYearInterestByStateRow {
  4557.     pub owner_name_client: String,
  4558.     pub state: String,
  4559.     pub interest_type: String,
  4560.     pub gross_revenue: Option<f64>,
  4561.     pub taxes: Option<f64>,
  4562.     pub deductions: Option<f64>,
  4563.     pub net_revenue: Option<f64>,
  4564. }
  4565.  
  4566. /// Fetches tax year totals by state and interest type.
  4567. #[server]
  4568. pub async fn taxyearinterestbystate_fetch_all() -> Result<Vec<TaxYearInterestByStateRow>, ServerFnError> {
  4569.     pub use TaxYearInterestByStateRow;
  4570.  
  4571.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4572.  
  4573.     let records = sqlx::query_as::<_, TaxYearInterestByStateRow>(
  4574.         "WITH CalculatedValues AS (
  4575.            SELECT
  4576.                owner_name_client,
  4577.                state,
  4578.                interest_type,
  4579.                1.0 * share_gross_revenue AS share_gross_revenue,
  4580.                1.0 * share_taxes AS share_taxes,
  4581.                1.0 * share_deductions AS share_deductions,
  4582.                1.0 * share_net_revenue AS share_net_revenue
  4583.            FROM
  4584.                revenue_raw
  4585.            WHERE
  4586.                owner_name_client = ?
  4587.                AND aggregation_level IN ('i', 'e', 'h')
  4588.                AND check_date >= date('now', '-1 year', 'start of year')
  4589.                AND check_date < date('now', 'start of year')
  4590.        ),
  4591.        StateRevenue AS (
  4592.            SELECT
  4593.                owner_name_client,
  4594.                state,
  4595.                interest_type,
  4596.                ROUND(SUM(share_gross_revenue), 2) AS gross_revenue,
  4597.                ROUND(SUM(share_taxes), 2) AS taxes,
  4598.                ROUND(SUM(share_deductions), 2) AS deductions,
  4599.                ROUND(SUM(share_net_revenue), 2) AS net_revenue
  4600.            FROM
  4601.                CalculatedValues
  4602.            GROUP BY
  4603.                state, interest_type
  4604.        )
  4605.        SELECT
  4606.            owner_name_client,
  4607.            state,
  4608.            interest_type,
  4609.            gross_revenue,
  4610.            taxes,
  4611.            deductions,
  4612.            net_revenue
  4613.        FROM
  4614.            StateRevenue
  4615.        ORDER BY
  4616.            state ASC"
  4617.     )
  4618.     .fetch_all(&land_pool)
  4619.     .await
  4620.     // log successful row count, then pass rows through
  4621.     .map(|rows| {
  4622.         log::debug!("Query succeeded: {} rows", rows.len());
  4623.         rows
  4624.     })
  4625.     .map_err(|e| {
  4626.         log::error!("Query failed: {}", e);
  4627.         ServerFnError::new(format!("Database error: {}", e))
  4628.     })?;
  4629.  
  4630.     Ok(records)
  4631. }
  4632.  
  4633. ================
  4634. File: gmm_client/src/tables/taxyearinterestbystate/resource.rs
  4635. ================
  4636. use super::query::TaxYearInterestByStateRow;
  4637. use leptos::*;
  4638.  
  4639. /// Leptos resource for fetching tax year interest-type revenue data grouped by state.
  4640. #[derive(Clone)]
  4641. pub(crate) struct TaxYearInterestByStateResource {
  4642.     pub state_rows: Resource<(), Result<Vec<TaxYearInterestByStateRow>, ServerFnError>>,
  4643. }
  4644.  
  4645. use super::query::*;
  4646. impl TaxYearInterestByStateResource {
  4647.     pub fn new() -> Self {
  4648.         let state_rows = create_resource(
  4649.             || (),
  4650.             |_| async move {
  4651.                 taxyearinterestbystate_fetch_all()
  4652.                     .await
  4653.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4654.             },
  4655.         );
  4656.  
  4657.         Self { state_rows }
  4658.     }
  4659. }
  4660.  
  4661. ================
  4662. File: gmm_client/src/tables/taxyearrevenueand1099s/mod.rs
  4663. ================
  4664. pub(crate) mod query;
  4665. pub(crate) mod resource;
  4666.  
  4667. ================
  4668. File: gmm_client/src/tables/taxyearrevenueand1099s/query.rs
  4669. ================
  4670. use leptos::*;
  4671. use serde::{Deserialize, Serialize};
  4672.  
  4673. /// Represents a row comparing revenue and 1099s for a client/operator.
  4674. #[derive(Debug, Clone, Serialize, Deserialize)]
  4675. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4676. pub struct TaxYearRevenueAnd1099sRow {
  4677.     pub client: String,
  4678.     pub operator: String,
  4679.     pub gross_revenue: Option<f64>,
  4680.     pub taxes: Option<f64>,
  4681.     pub deducts: Option<f64>,
  4682.     pub net_revenue: Option<f64>,
  4683.     pub amount_1099: Option<f64>,
  4684.     pub difference_dollars: Option<f64>,
  4685.     pub difference_percent: Option<f64>,
  4686.     pub material_difference: Option<String>,
  4687. }
  4688.  
  4689. /// Fetches reconciled revenue and 1099 values for the previous tax year.
  4690. #[server]
  4691. pub async fn taxyearrevenueand1099s_fetch_all() -> Result<Vec<TaxYearRevenueAnd1099sRow>, ServerFnError> {
  4692.     pub use TaxYearRevenueAnd1099sRow;
  4693.  
  4694.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4695.  
  4696.     let records = sqlx::query_as::<_, TaxYearRevenueAnd1099sRow>(
  4697.         r#"
  4698.        SELECT
  4699.            combined_data.client,
  4700.            CASE
  4701.                WHEN combined_data.share_net_revenue < 600 THEN COALESCE(o1.name, o2.name, combined_data.operator) || '*'
  4702.                ELSE COALESCE(o1.name, o2.name, combined_data.operator)
  4703.            END AS operator_name,
  4704.            combined_data.share_gross_revenue AS gross_revenue,
  4705.            combined_data.share_taxes AS taxes,
  4706.            combined_data.share_deductions AS deducts,
  4707.            combined_data.share_net_revenue AS net_revenue,
  4708.            combined_data.reported_amount AS amount_1099,
  4709.            ROUND(combined_data."difference ($)", 2) AS difference_dollars,
  4710.            CASE
  4711.                WHEN combined_data.share_net_revenue = 0 THEN NULL
  4712.                ELSE ROUND((combined_data."difference ($)" * 100.0) / combined_data.share_net_revenue, 2)
  4713.            END AS difference_percent,
  4714.            CASE
  4715.                WHEN combined_data."difference ($)" = 0 THEN NULL
  4716.                ELSE CASE
  4717.                    WHEN combined_data.reported_amount IS NULL OR combined_data.reported_amount = 0 THEN 'Outstanding 1099'
  4718.                    WHEN (combined_data.share_gross_revenue IS NULL OR combined_data.share_gross_revenue = 0)
  4719.                    AND (combined_data.share_taxes IS NULL OR combined_data.share_taxes = 0)
  4720.                    AND (combined_data.share_deductions IS NULL OR combined_data.share_deductions = 0)
  4721.                    AND (combined_data.share_net_revenue IS NULL OR combined_data.share_net_revenue = 0) THEN 'Outstanding Revenue'
  4722.                    WHEN combined_data.share_gross_revenue = combined_data.reported_amount
  4723.                    OR combined_data.share_net_revenue = combined_data.reported_amount THEN ''
  4724.                    WHEN (ABS(combined_data."difference ($)") * 100.0) / NULLIF(combined_data.share_net_revenue, 0) < 25 THEN 'No'
  4725.                    ELSE 'Yes'
  4726.                END
  4727.            END AS material_difference
  4728.        FROM (
  4729.            SELECT * FROM (
  4730.                SELECT
  4731.                    COALESCE(rr.owner_name_client, i.payee) AS client,
  4732.                    COALESCE(rr.operator_purchaser, i.payor) AS operator,
  4733.                    rr.share_gross_revenue,
  4734.                    rr.share_taxes,
  4735.                    rr.share_deductions,
  4736.                    rr.share_net_revenue,
  4737.                    ROUND(SUM(i.reported_amount), 2) AS reported_amount,
  4738.                    ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) AS "difference ($)",
  4739.                    CASE WHEN 1.0 * rr.share_net_revenue = 0 THEN NULL
  4740.                        ELSE (ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) * 100.0) / (1.0 * rr.share_net_revenue)
  4741.                    END AS "difference (%)",
  4742.                    1 AS source_table
  4743.                FROM
  4744.                    (SELECT DISTINCT payee, payor, 1.0 * REPLACE(reported_amount, ',', '') AS reported_amount, tax_year
  4745.                    FROM items1099
  4746.                    WHERE tax_year = 2024 AND box_name NOT LIKE '%withheld%' AND box_number NOT LIKE 'nil') AS i
  4747.                LEFT JOIN
  4748.                    (SELECT owner_name_client, operator_purchaser,
  4749.                            ROUND(SUM(1.0 * share_gross_revenue), 2) AS share_gross_revenue,
  4750.                            ROUND(SUM(1.0 * share_taxes), 2) AS share_taxes,
  4751.                            ROUND(SUM(1.0 * share_deductions), 2) AS share_deductions,
  4752.                            ROUND(SUM(1.0 * share_net_revenue), 2) AS share_net_revenue,
  4753.                            strftime('%Y', check_date), 2) AS year
  4754.                    FROM revenue_raw
  4755.                    WHERE owner_name_client = ?
  4756.                    AND aggregation_level IN ('i', 'e', 'h')
  4757.                    AND strftime('%Y', check_date) = '2024'
  4758.                    GROUP BY operator_purchaser, year) AS rr
  4759.                ON rr.owner_name_client = i.payee AND rr.operator_purchaser = i.payor
  4760.                GROUP BY client, operator, rr.share_gross_revenue, rr.share_taxes, rr.share_deductions, rr.share_net_revenue
  4761.  
  4762.                UNION ALL
  4763.  
  4764.                SELECT
  4765.                    COALESCE(rr.owner_name_client, i.payee) AS client,
  4766.                    COALESCE(rr.operator_purchaser, i.payor) AS operator,
  4767.                    rr.share_gross_revenue,
  4768.                    rr.share_taxes,
  4769.                    rr.share_deductions,
  4770.                    rr.share_net_revenue,
  4771.                    ROUND(SUM(i.reported_amount), 2) AS reported_amount,
  4772.                    ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) AS "difference ($)",
  4773.                    CASE WHEN 1.0 * rr.share_net_revenue = 0 THEN NULL
  4774.                        ELSE (ABS(1.0 * rr.share_gross_revenue - SUM(1.0 * i.reported_amount)) * 100.0) / (1.0 * rr.share_net_revenue)
  4775.                    END AS "difference (%)",
  4776.                    2 AS source_table
  4777.                FROM
  4778.                    (SELECT payee, payor, 1.0 * REPLACE(reported_amount, ',', '') AS reported_amount, tax_year
  4779.                    FROM items1099
  4780.                    WHERE tax_year = 2024
  4781.                    AND payee = ?
  4782.                    AND box_name NOT LIKE '%withheld%'
  4783.                    AND box_number NOT LIKE 'nil') AS i
  4784.                RIGHT JOIN
  4785.                    (SELECT owner_name_client, operator_purchaser,
  4786.                            ROUND(SUM(1.0 * share_gross_revenue), 2) AS share_gross_revenue,
  4787.                            ROUND(SUM(1.0 * share_taxes), 2) AS share_taxes,
  4788.                            ROUND(SUM(1.0 * share_deductions), 2) AS share_deductions,
  4789.                            ROUND(SUM(1.0 * share_net_revenue), 2) AS share_net_revenue,
  4790.                            strftime('%Y', check_date), 2) AS year
  4791.                    FROM revenue_raw
  4792.                    WHERE owner_name_client = ?
  4793.                    AND aggregation_level IN ('i', 'e', 'h')
  4794.                    AND strftime('%Y', check_date) = '2024'
  4795.                    GROUP BY owner_name_client, operator_purchaser, year) AS rr
  4796.                ON rr.owner_name_client = i.payee AND rr.operator_purchaser = i.payor
  4797.                GROUP BY client, operator, rr.share_gross_revenue, rr.share_taxes, rr.share_deductions, rr.share_net_revenue
  4798.            ) AS combined_data_with_dupes
  4799.            GROUP BY client, operator, source_table
  4800.        ) AS combined_data
  4801.        LEFT JOIN operator o1 ON o1.canonical = combined_data.operator
  4802.        LEFT JOIN operator o2 ON o2.canonical = combined_data.operator
  4803.        WHERE combined_data.client = ?
  4804.        GROUP BY combined_data.client, operator_name, combined_data.share_gross_revenue, combined_data.share_taxes, combined_data.share_deductions, combined_data.share_net_revenue
  4805.                "#
  4806.     )
  4807.     .fetch_all(&land_pool)
  4808.     .await
  4809.     // log successful row count, then pass rows through
  4810.     .map(|rows| {
  4811.         log::debug!("Query succeeded: {} rows", rows.len());
  4812.         rows
  4813.     })
  4814.     .map_err(|e| {
  4815.         log::error!("Query failed: {}", e);
  4816.         ServerFnError::new(format!("Database error: {}", e))
  4817.     })?;
  4818.  
  4819.     Ok(records)
  4820. }
  4821.  
  4822. ================
  4823. File: gmm_client/src/tables/taxyearrevenueand1099s/resource.rs
  4824. ================
  4825. use leptos::*;
  4826. use super::query::TaxYearRevenueAnd1099sRow;
  4827.  
  4828. /// Leptos resource for comparing revenue and 1099 data.
  4829. #[derive(Clone)]
  4830. pub(crate) struct TaxYearRevenueAnd1099sResource {
  4831.     pub rows: Resource<(), Result<Vec<TaxYearRevenueAnd1099sRow>, ServerFnError>>,
  4832. }
  4833.  
  4834. use super::query::*;
  4835. impl TaxYearRevenueAnd1099sResource {
  4836.     pub fn new() -> Self {
  4837.         let rows = create_resource(
  4838.             || (),
  4839.             |_| async move {
  4840.                 taxyearrevenueand1099s_fetch_all()
  4841.                     .await
  4842.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4843.             },
  4844.         );
  4845.  
  4846.         Self { rows }
  4847.     }
  4848. }
  4849.  
  4850. ================
  4851. File: gmm_client/src/tables/taxyearwellsbystate/mod.rs
  4852. ================
  4853. pub(crate) mod query;
  4854. pub(crate) mod resource;
  4855.  
  4856. ================
  4857. File: gmm_client/src/tables/taxyearwellsbystate/query.rs
  4858. ================
  4859. use leptos::*;
  4860. use serde::{Deserialize, Serialize};
  4861.  
  4862. /// Represents tax year revenue summary by state for a client.
  4863. #[derive(Debug, Clone, Serialize, Deserialize)]
  4864. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4865. pub struct TaxYearWellsByStateRow {
  4866.     pub owner_name_client: String,
  4867.     pub state: String,
  4868.     pub gross_revenue: Option<f64>,
  4869.     pub taxes: Option<f64>,
  4870.     pub deductions: Option<f64>,
  4871.     pub net_revenue: Option<f64>,
  4872.     pub percentage_of_portfolio: Option<f64>,
  4873. }
  4874.  
  4875. /// Fetches full-year state-level tax data and computes percentage of revenue per state.
  4876. #[server]
  4877. pub async fn taxyearwellsbystate_fetch_all() -> Result<Vec<TaxYearWellsByStateRow>, ServerFnError> {
  4878.     pub use TaxYearWellsByStateRow;
  4879.  
  4880.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  4881.  
  4882.     let records = sqlx::query_as::<_, TaxYearWellsByStateRow>(
  4883.         r#"
  4884.        WITH CalculatedValues AS (
  4885.            SELECT
  4886.                owner_name_client,
  4887.                state,
  4888.                1.0 * share_gross_revenue AS share_gross_revenue,
  4889.                1.0 * share_taxes AS share_taxes,
  4890.                1.0 * share_deductions AS share_deductions,
  4891.                1.0 * share_net_revenue AS share_net_revenue
  4892.            FROM
  4893.                revenue_raw
  4894.            WHERE
  4895.                owner_name_client = ?
  4896.                AND aggregation_level IN ('i', 'e', 'h')
  4897.                AND check_date >= date('now', '-1 year', 'start of year')
  4898.                AND check_date < date('now', 'start of year')
  4899.        ),
  4900.        StateRevenue AS (
  4901.            SELECT
  4902.                owner_name_client,
  4903.                state,
  4904.                ROUND(SUM(share_gross_revenue), 2) AS gross_revenue,
  4905.                ROUND(SUM(share_taxes), 2) AS taxes,
  4906.                ROUND(SUM(share_deductions), 2) AS deductions,
  4907.                ROUND(SUM(share_net_revenue), 2) AS net_revenue
  4908.            FROM
  4909.                CalculatedValues
  4910.            GROUP BY
  4911.                state
  4912.        ),
  4913.        TotalRevenuePerClient AS (
  4914.            SELECT
  4915.                owner_name_client,
  4916.                ROUND(SUM(net_revenue), 2) AS total_net_revenue
  4917.            FROM
  4918.                StateRevenue
  4919.        )
  4920.        SELECT
  4921.            sr.owner_name_client,
  4922.            sr.state,
  4923.            sr.gross_revenue,
  4924.            sr.taxes,
  4925.            sr.deductions,
  4926.            sr.net_revenue,
  4927.            ROUND((sr.net_revenue * 100.0) / NULLIF(trc.total_net_revenue, 0), 2) AS percentage_of_portfolio
  4928.        FROM
  4929.            StateRevenue sr
  4930.        JOIN
  4931.            TotalRevenuePerClient trc ON sr.owner_name_client = trc.owner_name_client
  4932.        ORDER BY
  4933.            sr.state ASC
  4934.        "#
  4935.     )
  4936.     .fetch_all(&land_pool)
  4937.     .await
  4938.     // log successful row count, then pass rows through
  4939.     .map(|rows| {
  4940.         log::debug!("Query succeeded: {} rows", rows.len());
  4941.         rows
  4942.     })
  4943.     .map_err(|e| {
  4944.         log::error!("Query failed: {}", e);
  4945.         ServerFnError::new(format!("Database error: {}", e))
  4946.     })?;
  4947.  
  4948.     Ok(records)
  4949. }
  4950.  
  4951. ================
  4952. File: gmm_client/src/tables/taxyearwellsbystate/resource.rs
  4953. ================
  4954. use super::query::TaxYearWellsByStateRow;
  4955. use leptos::*;
  4956.  
  4957. /// Leptos resource for tax year revenue distribution by state.
  4958. #[derive(Clone)]
  4959. pub(crate) struct TaxYearWellsByStateResource {
  4960.     pub rows: Resource<(), Result<Vec<TaxYearWellsByStateRow>, ServerFnError>>,
  4961. }
  4962.  
  4963. use super::query::*;
  4964. impl TaxYearWellsByStateResource {
  4965.     pub fn new() -> Self {
  4966.         let rows = create_resource(
  4967.             || (),
  4968.             |_| async move {
  4969.                 taxyearwellsbystate_fetch_all()
  4970.                     .await
  4971.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  4972.             },
  4973.         );
  4974.  
  4975.         Self { rows }
  4976.     }
  4977. }
  4978.  
  4979. ================
  4980. File: gmm_client/src/tables/wellops/mod.rs
  4981. ================
  4982. pub(crate) mod query;
  4983. pub(crate) mod resource;
  4984.  
  4985. ================
  4986. File: gmm_client/src/tables/wellops/query.rs
  4987. ================
  4988. use leptos::*;
  4989. use serde::{Deserialize, Serialize};
  4990.  
  4991. /// Represents a well's operational and location details.
  4992. #[derive(Debug, Clone, Serialize, Deserialize)]
  4993. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  4994. pub struct WellOpsRow {
  4995.     pub client: String,
  4996.     pub api: String,
  4997.     pub operator: String,
  4998.     pub status: String,
  4999.     pub well_name: String,
  5000.     pub state: String,
  5001.     pub county: String,
  5002.     pub township: Option<String>,
  5003.     pub land_range: Option<String>,
  5004.     pub section: Option<String>,
  5005.     pub portion_of_section: Option<String>,
  5006.     pub name: Option<String>, // survey name
  5007.     pub abstract_number: Option<String>,
  5008.     pub block: Option<String>,
  5009. }
  5010.  
  5011. /// Fetches detailed information about wells and their operators.
  5012. #[server]
  5013. pub async fn wellops_fetch_all() -> Result<Vec<WellOpsRow>, ServerFnError> {
  5014.     pub use WellOpsRow;
  5015.  
  5016.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5017.  
  5018.     let records = sqlx::query_as::<_, WellOpsRow>(
  5019.         r#"
  5020.        SELECT
  5021.            client.canonical AS client,
  5022.            well.api_or_uwi AS api,
  5023.            operator.name,
  5024.            well_status.name AS status,
  5025.            well.well_name,
  5026.            well.state,
  5027.            well.county,
  5028.            well.township,
  5029.            well.land_range,
  5030.            well.section,
  5031.            well.portion_of_section,
  5032.            survey.name,
  5033.            well.abstract_number,
  5034.            well.block
  5035.        FROM
  5036.            well
  5037.        JOIN
  5038.            operator ON operator.id = well.operator_id
  5039.        JOIN
  5040.            well_status ON well_status.id = well.well_status_id
  5041.        JOIN
  5042.            well_interest ON well_interest.well_id = well.well_id
  5043.        JOIN
  5044.            client ON client.id = well_interest.client_id
  5045.        JOIN
  5046.            survey ON survey.id = well.survey_id
  5047.        WHERE
  5048.            client.canonical = ?
  5049.        ORDER BY
  5050.            operator.name
  5051.        "#
  5052.     )
  5053.     .fetch_all(&land_pool)
  5054.     .await
  5055.     // log successful row count, then pass rows through
  5056.     .map(|rows| {
  5057.         log::debug!("Query succeeded: {} rows", rows.len());
  5058.         rows
  5059.     })
  5060.     .map_err(|e| {
  5061.         log::error!("Query failed: {}", e);
  5062.         ServerFnError::new(format!("Database error: {}", e))
  5063.     })?;
  5064.  
  5065.     Ok(records)
  5066. }
  5067.  
  5068. ================
  5069. File: gmm_client/src/tables/wellops/resource.rs
  5070. ================
  5071. use super::query::WellOpsRow;
  5072. use leptos::*;
  5073.  
  5074. /// Leptos resource for fetching well operations and metadata.
  5075. #[derive(Clone)]
  5076. pub(crate) struct WellOpsResource {
  5077.     pub rows: Resource<(), Result<Vec<WellOpsRow>, ServerFnError>>,
  5078. }
  5079.  
  5080. use super::query::*;
  5081. impl WellOpsResource {
  5082.     pub fn new() -> Self {
  5083.         let rows = create_resource(
  5084.             || (),
  5085.             |_| async move {
  5086.                 wellops_fetch_all()
  5087.                     .await
  5088.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5089.             },
  5090.         );
  5091.  
  5092.         Self { rows }
  5093.     }
  5094. }
  5095.  
  5096. ================
  5097. File: gmm_client/src/tables/wellrev/mod.rs
  5098. ================
  5099. pub(crate) mod query;
  5100. pub(crate) mod resource;
  5101.  
  5102. ================
  5103. File: gmm_client/src/tables/wellrev/query.rs
  5104. ================
  5105. use leptos::*;
  5106. use serde::{Deserialize, Serialize};
  5107.  
  5108. /// Represents monthly revenue details for a well.
  5109. #[derive(Debug, Clone, Serialize, Deserialize)]
  5110. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  5111. pub struct WellRevRow {
  5112.     pub owner_name_client: String,
  5113.     pub operator: String,
  5114.     pub well_property_name: String,
  5115.     pub well_number: Option<String>,
  5116.     pub production_date: Option<String>,
  5117.     pub product: Option<String>,
  5118.     pub unit_price: Option<f64>,
  5119.     pub pie_gross_volume: Option<f64>,
  5120.     pub owner_proportion: Option<f64>,
  5121.     pub share_revenue: Option<f64>,
  5122.     pub share_taxes: Option<f64>,
  5123.     pub share_deductions: Option<f64>,
  5124.     pub net_revenue: Option<f64>,
  5125. }
  5126.  
  5127. /// Fetches revenue data by well for the previous month.
  5128. #[server]
  5129. pub async fn wellrev_fetch_all() -> Result<Vec<WellRevRow>, ServerFnError> {
  5130.     pub use WellRevRow;
  5131.  
  5132.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5133.  
  5134.     let records = sqlx::query_as::<_, WellRevRow>(
  5135.         r#"
  5136.        SELECT
  5137.            rr.owner_name_client,
  5138.            o.name AS operator_name,
  5139.            rr.well_property_name AS well_property_name,
  5140.            rr.well_number,
  5141.            rr.production_date,
  5142.            rr.product,
  5143.            1.0 * rr.unit_price AS unit_price,
  5144.            1.0 * rr.pie_volume AS pie_gross_volume,
  5145.            ROUND(rr.owner_decimal, 8) AS owner_proportion,
  5146.            1.0 * rr.share_gross_revenue AS share_revenue,
  5147.            1.0 * rr.share_taxes AS share_taxes,
  5148.            1.0 * rr.share_deductions AS share_deductions,
  5149.            1.0 * rr.share_net_revenue AS net_revenue
  5150.        FROM
  5151.            revenue_raw rr
  5152.        JOIN
  5153.            operator o ON o.canonical = rr.operator_purchaser
  5154.        WHERE
  5155.            rr.owner_name_client = ?
  5156.            AND rr.aggregation_level IN ('i', 'e', 'h')
  5157.            AND rr.check_date >= date('now', 'start of month', '-1 month')
  5158.            AND rr.check_date < date('now', 'start of month')
  5159.        ORDER BY
  5160.            operator_name
  5161.        "#
  5162.     )
  5163.     .fetch_all(&land_pool)
  5164.     .await
  5165.     // log successful row count, then pass rows through
  5166.     .map(|rows| {
  5167.         log::debug!("Query succeeded: {} rows", rows.len());
  5168.         rows
  5169.     })
  5170.     .map_err(|e| {
  5171.         log::error!("Query failed: {}", e);
  5172.         ServerFnError::new(format!("Database error: {}", e))
  5173.     })?;
  5174.  
  5175.     Ok(records)
  5176. }
  5177.  
  5178. ================
  5179. File: gmm_client/src/tables/wellrev/resource.rs
  5180. ================
  5181. use super::query::WellRevRow;
  5182. use leptos::*;
  5183.  
  5184. /// Leptos resource for fetching last month’s revenue details by well.
  5185. #[derive(Clone)]
  5186. pub(crate) struct WellRevResource {
  5187.     pub rows: Resource<(), Result<Vec<WellRevRow>, ServerFnError>>,
  5188. }
  5189.  
  5190. use super::query::*;
  5191. impl WellRevResource {
  5192.     pub fn new() -> Self {
  5193.         let rows = create_resource(
  5194.             || (),
  5195.             |_| async move {
  5196.                 wellrev_fetch_all()
  5197.                     .await
  5198.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5199.             },
  5200.         );
  5201.  
  5202.         Self { rows }
  5203.     }
  5204. }
  5205.  
  5206. ================
  5207. File: gmm_client/src/tables/ytdcurrentyear/mod.rs
  5208. ================
  5209. pub(crate) mod query;
  5210. pub(crate) mod resource;
  5211.  
  5212. ================
  5213. File: gmm_client/src/tables/ytdcurrentyear/query.rs
  5214. ================
  5215. use leptos::*;
  5216. use serde::{Deserialize, Serialize};
  5217.  
  5218. /// Represents year-to-date revenue data grouped by month for each client.
  5219. #[derive(Debug, Clone, Serialize, Deserialize)]
  5220. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  5221. pub struct YTDCurrentYearRow {
  5222.     pub owner_name_client: String,
  5223.     pub month: String,
  5224.     pub gross_revenue: Option<f64>,
  5225.     pub taxes: Option<f64>,
  5226.     pub deductions: Option<f64>,
  5227.     pub net_revenue: Option<f64>,
  5228.     pub depletion_15: Option<f64>,
  5229.     pub net_post_depletion_15: Option<f64>,
  5230.     pub depletion_275: Option<f64>,
  5231.     pub net_post_depletion_275: Option<f64>,
  5232. }
  5233.  
  5234. /// Fetches YTD revenue summary with depletion values grouped by client and month.
  5235. #[server]
  5236. pub async fn ytdcurrentyear_fetch_all() -> Result<Vec<YTDCurrentYearRow>, ServerFnError> {
  5237.     pub use YTDCurrentYearRow;
  5238.  
  5239.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5240.  
  5241.     let records = sqlx::query_as::<_, YTDCurrentYearRow>(
  5242.         r#"
  5243.        WITH CalculatedValues AS (
  5244.            SELECT
  5245.                owner_name_client,
  5246.                strftime('%Y', check_date) AS check_year,
  5247.                strftime('%m', check_date) AS check_month,
  5248.                1.0 * share_gross_revenue AS gross_revenue,  
  5249.                1.0 * share_taxes AS taxes,  
  5250.                1.0 * share_deductions AS deductions,  
  5251.                1.0 * share_net_revenue AS net_revenue,  
  5252.                1.0 * share_gross_revenue * 0.15 AS depletion_15,
  5253.                1.0 * share_gross_revenue - (1.0 * share_gross_revenue * 0.15) AS net_post_depletion_15,
  5254.                1.0 * share_gross_revenue * 0.275 AS depletion_275,
  5255.                1.0 * share_gross_revenue - (1.0 * share_gross_revenue * 0.275) AS net_post_depletion_275
  5256.            FROM
  5257.                revenue_raw
  5258.            WHERE
  5259.                owner_name_client = ?
  5260.                AND aggregation_level IN ('i', 'e', 'h')
  5261.                AND check_date >= date('now', 'start of year')  
  5262.                AND check_date < date('now')  
  5263.        )
  5264.        SELECT
  5265.            owner_name_client,
  5266.            CASE
  5267.                WHEN check_month = '01' THEN 'Jan'
  5268.                WHEN check_month = '02' THEN 'Feb'
  5269.                WHEN check_month = '03' THEN 'Mar'
  5270.                WHEN check_month = '04' THEN 'Apr'
  5271.                WHEN check_month = '05' THEN 'May'
  5272.                WHEN check_month = '06' THEN 'Jun'
  5273.                WHEN check_month = '07' THEN 'Jul'
  5274.                WHEN check_month = '08' THEN 'Aug'
  5275.                WHEN check_month = '09' THEN 'Sep'
  5276.                WHEN check_month = '10' THEN 'Oct'
  5277.                WHEN check_month = '11' THEN 'Nov'
  5278.                WHEN check_month = '12' THEN 'Dec'
  5279.            END AS month,
  5280.            ROUND(SUM(gross_revenue), 2) AS gross_revenue,
  5281.            ROUND(SUM(taxes), 2) AS taxes,
  5282.            ROUND(SUM(deductions), 2) AS deductions,
  5283.            ROUND(SUM(net_revenue), 2) AS net_revenue,
  5284.            ROUND(SUM(depletion_15), 2) AS depletion_15,
  5285.            ROUND(SUM(net_post_depletion_15), 2) AS net_post_depletion_15,
  5286.            ROUND(SUM(depletion_275), 2) AS depletion_275,
  5287.            ROUND(SUM(net_post_depletion_275), 2) AS net_post_depletion_275
  5288.        FROM
  5289.            CalculatedValues
  5290.        GROUP BY
  5291.            check_month
  5292.        ORDER BY
  5293.            CAST(check_month AS INTEGER)
  5294.        "#
  5295.     )
  5296.     .fetch_all(&land_pool)
  5297.     .await
  5298.     // log successful row count, then pass rows through
  5299.     .map(|rows| {
  5300.         log::debug!("Query succeeded: {} rows", rows.len());
  5301.         rows
  5302.     })
  5303.     .map_err(|e| {
  5304.         log::error!("Query failed: {}", e);
  5305.         ServerFnError::new(format!("Database error: {}", e))
  5306.     })?;
  5307.  
  5308.     Ok(records)
  5309. }
  5310.  
  5311. ================
  5312. File: gmm_client/src/tables/ytdcurrentyear/resource.rs
  5313. ================
  5314. use super::query::YTDCurrentYearRow;
  5315. use leptos::*;
  5316.  
  5317. /// Leptos resource for fetching year-to-date revenue summaries.
  5318. #[derive(Clone)]
  5319. pub(crate) struct YTDCurrentYearResource {
  5320.     pub rows: Resource<(), Result<Vec<YTDCurrentYearRow>, ServerFnError>>,
  5321. }
  5322.  
  5323. use super::query::*;
  5324. impl YTDCurrentYearResource {
  5325.     pub fn new() -> Self {
  5326.         let rows = create_resource(
  5327.             || (),
  5328.             |_| async move {
  5329.                 ytdcurrentyear_fetch_all()
  5330.                     .await
  5331.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5332.             },
  5333.         );
  5334.  
  5335.         Self { rows }
  5336.     }
  5337. }
  5338.  
  5339. ================
  5340. File: gmm_client/src/tables/ytdpasttaxyear/mod.rs
  5341. ================
  5342. pub(crate) mod query;
  5343. pub(crate) mod resource;
  5344.  
  5345. ================
  5346. File: gmm_client/src/tables/ytdpasttaxyear/query.rs
  5347. ================
  5348. use leptos::*;
  5349. use serde::{Deserialize, Serialize};
  5350.  
  5351. /// Represents a row of YTD revenue data for the past tax year.
  5352. #[derive(Debug, Clone, Serialize, Deserialize)]
  5353. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  5354. pub struct YTDPastTaxYearRow {
  5355.     pub owner_name_client: String,
  5356.     pub month: String,
  5357.     pub gross_revenue: Option<f64>,
  5358.     pub taxes: Option<f64>,
  5359.     pub deductions: Option<f64>,
  5360.     pub net_revenue: Option<f64>,
  5361.     pub depletion_15: Option<f64>,
  5362.     pub net_post_depletion_15: Option<f64>,
  5363.     pub depletion_275: Option<f64>,
  5364.     pub net_post_depletion_275: Option<f64>,
  5365. }
  5366.  
  5367. /// Fetches YTD revenue summary for the previous calendar year grouped by client and month.
  5368. #[server]
  5369. pub async fn ytdpasttaxyear_fetch_all() -> Result<Vec<YTDPastTaxYearRow>, ServerFnError> {
  5370.     pub use YTDPastTaxYearRow;
  5371.  
  5372.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5373.  
  5374.     let records = sqlx::query_as::<_, YTDPastTaxYearRow>(
  5375.         r#"
  5376.        WITH CalculatedValues AS (
  5377.            SELECT
  5378.                owner_name_client,
  5379.                strftime('%Y', check_date) AS check_year,
  5380.                strftime('%m', check_date) AS check_month,
  5381.                1.0 * share_gross_revenue AS gross_revenue,  
  5382.                1.0 * share_taxes AS taxes,  
  5383.                1.0 * share_deductions AS deductions,  
  5384.                1.0 * share_net_revenue AS net_revenue,  
  5385.                1.0 * share_gross_revenue * 0.15 AS depletion_15,
  5386.                1.0 * share_gross_revenue - (1.0 * share_gross_revenue * 0.15) AS net_post_depletion_15,
  5387.                1.0 * share_gross_revenue * 0.275 AS depletion_275,
  5388.                1.0 * share_gross_revenue - (1.0 * share_gross_revenue * 0.275) AS net_post_depletion_275
  5389.            FROM
  5390.                revenue_raw
  5391.            WHERE
  5392.                owner_name_client = ?
  5393.                AND aggregation_level IN ('i', 'e', 'h')
  5394.                AND check_date >= date('now', 'start of year', '-1 year')
  5395.                AND check_date < date('now', 'start of year')
  5396.        )
  5397.        SELECT
  5398.            owner_name_client,
  5399.            CASE
  5400.                WHEN check_month = '01' THEN 'Jan'
  5401.                WHEN check_month = '02' THEN 'Feb'
  5402.                WHEN check_month = '03' THEN 'Mar'
  5403.                WHEN check_month = '04' THEN 'Apr'
  5404.                WHEN check_month = '05' THEN 'May'
  5405.                WHEN check_month = '06' THEN 'Jun'
  5406.                WHEN check_month = '07' THEN 'Jul'
  5407.                WHEN check_month = '08' THEN 'Aug'
  5408.                WHEN check_month = '09' THEN 'Sep'
  5409.                WHEN check_month = '10' THEN 'Oct'
  5410.                WHEN check_month = '11' THEN 'Nov'
  5411.                WHEN check_month = '12' THEN 'Dec'
  5412.            END AS month,
  5413.            ROUND(SUM(gross_revenue), 2) AS gross_revenue,
  5414.            ROUND(SUM(taxes), 2) AS taxes,
  5415.            ROUND(SUM(deductions), 2) AS deductions,
  5416.            ROUND(SUM(net_revenue), 2) AS net_revenue,
  5417.            ROUND(SUM(depletion_15), 2) AS depletion_15,
  5418.            ROUND(SUM(net_post_depletion_15), 2) AS net_post_depletion_15,
  5419.            ROUND(SUM(depletion_275), 2) AS depletion_275,
  5420.            ROUND(SUM(net_post_depletion_275), 2) AS net_post_depletion_275
  5421.        FROM
  5422.            CalculatedValues
  5423.        GROUP BY
  5424.            check_month
  5425.        ORDER BY
  5426.            CAST(check_month AS INTEGER)
  5427.        "#
  5428.     )
  5429.     .fetch_all(&land_pool)
  5430.     .await
  5431.     // log successful row count, then pass rows through
  5432.     .map(|rows| {
  5433.         log::debug!("Query succeeded: {} rows", rows.len());
  5434.         rows
  5435.     })
  5436.     .map_err(|e| {
  5437.         log::error!("Query failed: {}", e);
  5438.         ServerFnError::new(format!("Database error: {}", e))
  5439.     })?;
  5440.  
  5441.     Ok(records)
  5442. }
  5443.  
  5444. ================
  5445. File: gmm_client/src/tables/ytdpasttaxyear/resource.rs
  5446. ================
  5447. use super::query::YTDPastTaxYearRow;
  5448. use leptos::*;
  5449.  
  5450. /// Leptos resource for fetching YTD revenue summaries for the previous tax year.
  5451. #[derive(Clone)]
  5452. pub(crate) struct YtdPastTaxYearResource {
  5453.     pub rows: Resource<(), Result<Vec<YTDPastTaxYearRow>, ServerFnError>>, // ✅ updated
  5454. }
  5455.  
  5456. use super::query::*;
  5457. impl YtdPastTaxYearResource {
  5458.     pub fn new() -> Self {
  5459.         let rows = create_resource(
  5460.             || (),
  5461.             |_| async move {
  5462.                 ytdpasttaxyear_fetch_all()
  5463.                     .await
  5464.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5465.             },
  5466.         );
  5467.  
  5468.         Self { rows }
  5469.     }
  5470. }
  5471.  
  5472. ================
  5473. File: gmm_client/src/tables/ytdpfibyoperator/mod.rs
  5474. ================
  5475. pub(crate) mod query;
  5476. pub(crate) mod resource;
  5477.  
  5478. ================
  5479. File: gmm_client/src/tables/ytdpfibyoperator/query.rs
  5480. ================
  5481. use leptos::*;
  5482.  
  5483. use serde::{Deserialize, Serialize};
  5484.  
  5485. #[derive(Debug, Clone, Serialize, Deserialize)]
  5486. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  5487. pub struct YTDPFIByOperatorRow {
  5488.     pub owner_name_client: String,
  5489.     pub operator_purchaser: String,
  5490.     pub oil_volume: Option<f64>,
  5491.     pub natural_gas_volume: Option<f64>,
  5492.     pub oil_volume_60: Option<f64>,
  5493.     pub oil_volume_75: Option<f64>,
  5494.     pub oil_volume_90: Option<f64>,
  5495.     pub natural_gas_volume_2: Option<f64>,
  5496.     pub natural_gas_volume_25: Option<f64>,
  5497.     pub natural_gas_volume_3: Option<f64>,
  5498. }
  5499.  
  5500. #[server]
  5501. pub async fn ytdpfibyoperator_fetch_all() -> Result<Vec<YTDPFIByOperatorRow>, ServerFnError> {
  5502.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5503.  
  5504.     let records = sqlx::query_as::<_, YTDPFIByOperatorRow>(
  5505.         r#"
  5506.        WITH CalculatedVolumes AS (
  5507.            SELECT
  5508.                owner_name_client,
  5509.                operator_purchaser,
  5510.                ROUND(SUM(CASE WHEN product = 'oil' THEN 1.0 * share_volume / 12.0 ELSE 0 END), 2) AS oil_volume,
  5511.                ROUND(SUM(CASE WHEN product = 'natural gas' THEN 1.0 * share_volume / 12.0 ELSE 0 END), 2) AS natural_gas_volume
  5512.            FROM
  5513.                revenue_raw
  5514.            WHERE
  5515.                owner_name_client = ?
  5516.                AND aggregation_level IN ('i', 'e', 'h')
  5517.                AND check_date >= date('now', '-12 month')
  5518.                AND product IN ('oil', 'natural gas')
  5519.            GROUP BY
  5520.                operator_purchaser
  5521.        )
  5522.        SELECT
  5523.            cv.owner_name_client,
  5524.            o.name AS operator_name,
  5525.            cv.oil_volume,
  5526.            cv.natural_gas_volume,
  5527.            cv.oil_volume * 60 AS oil_volume_60,
  5528.            cv.oil_volume * 75 AS oil_volume_75,
  5529.            cv.oil_volume * 90 AS oil_volume_90,
  5530.            cv.natural_gas_volume * 2 AS natural_gas_volume_2,
  5531.            cv.natural_gas_volume * 2.50 AS natural_gas_volume_25,
  5532.            cv.natural_gas_volume * 3 AS natural_gas_volume_3
  5533.        FROM
  5534.            CalculatedVolumes cv
  5535.        JOIN
  5536.            operator o ON o.canonical = cv.operator_purchaser
  5537.        WHERE
  5538.            cv.oil_volume != 0 OR cv.natural_gas_volume != 0
  5539.        ORDER BY
  5540.            operator_name ASC
  5541.        "#
  5542.     )
  5543.     .fetch_all(&land_pool)
  5544.     .await
  5545.     // log successful row count, then pass rows through
  5546.     .map(|rows| {
  5547.         log::debug!("Query succeeded: {} rows", rows.len());
  5548.         rows
  5549.     })
  5550.     .map_err(|e| {
  5551.         log::error!("Query failed: {}", e);
  5552.         ServerFnError::new(format!("Database error: {}", e))
  5553.     })?;
  5554.  
  5555.     Ok(records)
  5556. }
  5557.  
  5558. ================
  5559. File: gmm_client/src/tables/ytdpfibyoperator/resource.rs
  5560. ================
  5561. use super::query::YTDPFIByOperatorRow;
  5562. use leptos::*;
  5563.  
  5564. #[derive(Clone)]
  5565. pub(crate) struct YtdPfiByOperatorResource {
  5566.     pub rows: Resource<(), Result<Vec<YTDPFIByOperatorRow>, ServerFnError>>, // ✅ updated
  5567. }
  5568.  
  5569. use super::query::*;
  5570. impl YtdPfiByOperatorResource {
  5571.     pub fn new() -> Self {
  5572.         let rows = create_resource(
  5573.             || (),
  5574.             |_| async move {
  5575.                 ytdpfibyoperator_fetch_all()
  5576.                     .await
  5577.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5578.             },
  5579.         );
  5580.  
  5581.         Self { rows }
  5582.     }
  5583. }
  5584.  
  5585. ================
  5586. File: gmm_client/src/tables/ytdpfibyproduct/mod.rs
  5587. ================
  5588. pub(crate) mod query;
  5589. pub(crate) mod resource;
  5590.  
  5591. ================
  5592. File: gmm_client/src/tables/ytdpfibyproduct/query.rs
  5593. ================
  5594. use leptos::*;
  5595. use serde::{Deserialize, Serialize};
  5596.  
  5597. /// Represents a row of average net revenue per product category.
  5598. #[derive(Debug, Clone, Serialize, Deserialize)]
  5599. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  5600. pub struct YTDPFIByProductRow {
  5601.     pub owner_name_client: String,
  5602.     pub product_category: String,
  5603.     pub last_month_avg_share_net: Option<f64>,
  5604.     pub three_months_avg_share_net: Option<f64>,
  5605.     pub six_months_avg_share_net: Option<f64>,
  5606.     pub twelve_months_avg_share_net: Option<f64>,
  5607. }
  5608.  
  5609. #[server]
  5610. pub async fn ytdpfibyproduct_fetch_all() -> Result<Vec<YTDPFIByProductRow>, ServerFnError> {
  5611.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5612.  
  5613.     let records = sqlx::query_as::<_, YTDPFIByProductRow>(
  5614.         r#"
  5615.        WITH ranked_products AS (
  5616.            SELECT
  5617.                owner_name_client,
  5618.                CASE
  5619.                    WHEN product = 'oil' THEN 'oil'
  5620.                    WHEN product = 'natural gas' THEN 'natural gas'
  5621.                    ELSE 'other'
  5622.                END AS product_category,
  5623.                ROUND(SUM(CASE WHEN strftime('%Y-%m', check_date) >= strftime('%Y-%m', 'now', '-1 month') THEN 1.0 * share_net_revenue ELSE 0 END), 2) AS last_month_avg_share_net,
  5624.                ROUND(SUM(CASE WHEN strftime('%Y-%m', check_date) >= strftime('%Y-%m', 'now', '-3 month') THEN 1.0 * share_net_revenue ELSE 0 END) / 3.0, 2) AS three_months_avg_share_net,
  5625.                ROUND(SUM(CASE WHEN strftime('%Y-%m', check_date) >= strftime('%Y-%m', 'now', '-6 month') THEN 1.0 * share_net_revenue ELSE 0 END) / 6.0, 2) AS six_months_avg_share_net,
  5626.                ROUND(SUM(CASE WHEN strftime('%Y-%m', check_date) >= strftime('%Y-%m', 'now', '-12 month') THEN 1.0 * share_net_revenue ELSE 0 END) / 12.0, 2) AS twelve_months_avg_share_net,
  5627.                RANK() OVER (
  5628.                    PARTITION BY owner_name_client
  5629.                    ORDER BY
  5630.                        SUM(CASE WHEN strftime('%Y-%m', check_date) >= strftime('%Y-%m', 'now', '-12 month') THEN 1.0 * share_net_revenue ELSE 0 END) DESC
  5631.                ) AS rank_num
  5632.            FROM revenue_raw
  5633.            WHERE owner_name_client = ?
  5634.            AND aggregation_level IN ('i', 'e', 'h')
  5635.            GROUP BY product_category
  5636.        )
  5637.        SELECT
  5638.            owner_name_client,
  5639.            product_category,
  5640.            last_month_avg_share_net,
  5641.            three_months_avg_share_net,
  5642.            six_months_avg_share_net,
  5643.            twelve_months_avg_share_net
  5644.        FROM ranked_products
  5645.        WHERE rank_num <= 3
  5646.        ORDER BY product_category
  5647.        "#
  5648.     )
  5649.     .fetch_all(&land_pool)
  5650.     .await
  5651.     // log successful row count, then pass rows through
  5652.     .map(|rows| {
  5653.         log::debug!("Query succeeded: {} rows", rows.len());
  5654.         rows
  5655.     })
  5656.     .map_err(|e| {
  5657.         log::error!("Query failed: {}", e);
  5658.         ServerFnError::new(format!("Database error: {}", e))
  5659.     })?;
  5660.  
  5661.     Ok(records)
  5662. }
  5663.  
  5664. ================
  5665. File: gmm_client/src/tables/ytdpfibyproduct/resource.rs
  5666. ================
  5667. use super::query::YTDPFIByProductRow;
  5668. use leptos::*;
  5669.  
  5670. #[derive(Clone)]
  5671. pub(crate) struct YtdPfiByProductResource {
  5672.     pub rows: Resource<(), Result<Vec<YTDPFIByProductRow>, ServerFnError>>, // ✅ updated
  5673. }
  5674.  
  5675. use super::query::*;
  5676. impl YtdPfiByProductResource {
  5677.     pub fn new() -> Self {
  5678.         let rows = create_resource(
  5679.             || (),
  5680.             |_| async move {
  5681.                 ytdpfibyproduct_fetch_all()
  5682.                     .await
  5683.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5684.             },
  5685.         );
  5686.  
  5687.         Self { rows }
  5688.     }
  5689. }
  5690.  
  5691. ================
  5692. File: gmm_client/src/tables/ytdrevenuebyoperator/mod.rs
  5693. ================
  5694. pub(crate) mod query;
  5695. pub(crate) mod resource;
  5696.  
  5697. ================
  5698. File: gmm_client/src/tables/ytdrevenuebyoperator/query.rs
  5699. ================
  5700. use leptos::*;
  5701.  
  5702. use serde::{Deserialize, Serialize};
  5703.  
  5704. /// Represents a row of YTD revenue totals per operator.
  5705. #[derive(Debug, Clone, Serialize, Deserialize)]
  5706. #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
  5707. pub struct YTDRevenueByOperatorRow {
  5708.     pub owner_name_client: String,
  5709.     pub operator_purchaser: String,
  5710.     pub total_share_net: Option<f64>,
  5711. }
  5712.  
  5713. #[server]
  5714. pub async fn ytdrevenuebyoperator_fetch_all() -> Result<Vec<YTDRevenueByOperatorRow>, ServerFnError>
  5715. {
  5716.     let land_pool = crate::state::ssr::app_pools()?.land_pool;
  5717.  
  5718.     let records = sqlx::query_as::<_, YTDRevenueByOperatorRow>(
  5719.         r#"
  5720.        WITH RevenueTotals AS (
  5721.            SELECT
  5722.                owner_name_client,
  5723.                operator_purchaser,
  5724.                ROUND(SUM(1.0 * share_net_revenue), 2) AS total_share_net
  5725.            FROM
  5726.                revenue_raw
  5727.            WHERE
  5728.                owner_name_client = ?
  5729.                AND aggregation_level IN ('i', 'e', 'h')
  5730.                AND strftime('%Y', check_date) = strftime('%Y', 'now')        
  5731.            GROUP BY
  5732.                operator_purchaser
  5733.        )
  5734.        SELECT
  5735.            rt.owner_name_client,
  5736.            o.name AS operator_name,
  5737.            rt.total_share_net
  5738.        FROM
  5739.            RevenueTotals rt
  5740.        JOIN
  5741.            operator o ON o.canonical = rt.operator_purchaser
  5742.        ORDER BY
  5743.            operator_name
  5744.        "#
  5745.     )
  5746.     .fetch_all(&land_pool)
  5747.     .await
  5748.     // log successful row count, then pass rows through
  5749.     .map(|rows| {
  5750.         log::debug!("Query succeeded: {} rows", rows.len());
  5751.         rows
  5752.     })
  5753.     .map_err(|e| {
  5754.         log::error!("Query failed: {}", e);
  5755.         ServerFnError::new(format!("Database error: {}", e))
  5756.     })?;
  5757.  
  5758.     Ok(records)
  5759. }
  5760.  
  5761. ================
  5762. File: gmm_client/src/tables/ytdrevenuebyoperator/resource.rs
  5763. ================
  5764. use super::query::YTDRevenueByOperatorRow;
  5765. use leptos::*;
  5766.  
  5767. #[derive(Clone)]
  5768. pub(crate) struct YtdRevenueByOperatorResource {
  5769.     pub rows: Resource<(), Result<Vec<YTDRevenueByOperatorRow>, ServerFnError>>, // ✅ updated
  5770. }
  5771.  
  5772. use super::query::*;
  5773. impl YtdRevenueByOperatorResource {
  5774.     pub fn new() -> Self {
  5775.         let rows = create_resource(
  5776.             || (),
  5777.             |_| async move {
  5778.                 ytdrevenuebyoperator_fetch_all()
  5779.                     .await
  5780.                     .map_err(|e| ServerFnError::new(format!("Database error: {}", e)))
  5781.             },
  5782.         );
  5783.  
  5784.         Self { rows }
  5785.     }
  5786. }
  5787.  
  5788. ================
  5789. File: gmm_client/src/tables/mod.rs
  5790. ================
  5791. // pub(crate) mod revenue;
  5792. pub(crate) mod assets;
  5793. pub(crate) mod dashboardtotalreportedpayments;
  5794. pub(crate) mod dashboardjibs;
  5795. pub(crate) mod dashboardrevenue;
  5796. pub(crate) mod incominglocation;
  5797. pub(crate) mod incomingproducts;
  5798. pub(crate) mod incomingtable1;
  5799. pub(crate) mod incomingtable2;
  5800. // pub(crate) mod iwv_qc_queries;
  5801. pub(crate) mod jibdetails;
  5802. pub(crate) mod jibnetting;
  5803. pub(crate) mod jibsummary;
  5804. pub(crate) mod leases;
  5805. pub(crate) mod pieleasestatus;
  5806. pub(crate) mod pieproducingwellscounty;
  5807. pub(crate) mod pieproducingwellsstate;
  5808. pub(crate) mod pierevenuebycounty;
  5809. pub(crate) mod pierevenuebyoperator;
  5810. pub(crate) mod pierevenuebyproduct;
  5811. pub(crate) mod pierevenuebystate;
  5812. pub(crate) mod piewellstatus;
  5813. pub(crate) mod revjibdetails;
  5814. pub(crate) mod revjibsummary;
  5815. pub(crate) mod statslistofcounts;
  5816. pub(crate) mod statsproduction;
  5817. pub(crate) mod statstopoperators;
  5818. // pub(crate) mod surfacerevenue;
  5819. pub(crate) mod taxyear1099details;
  5820. pub(crate) mod taxyearfullyeartotals;
  5821. pub(crate) mod taxyearinterestbystate;
  5822. pub(crate) mod taxyearrevenueand1099s;
  5823. pub(crate) mod taxyearwellsbystate;
  5824. pub(crate) mod wellops;
  5825. pub(crate) mod wellrev;
  5826. pub(crate) mod ytdcurrentyear;
  5827. pub(crate) mod ytdpasttaxyear;
  5828. pub(crate) mod ytdpfibyoperator;
  5829. pub(crate) mod ytdpfibyproduct;
  5830. pub(crate) mod ytdrevenuebyoperator;
  5831.  
  5832.  
  5833.  
  5834.  
  5835. ================================================================
  5836. End of Codebase
  5837. ================================================================
  5838.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement