get_col( $wpdb->prepare( 'SELECT id FROM %i WHERE contact_id = %d', self::table(), $contact_id ) ) ); Nodebook_Props::delete_for( 'deal', $ids ); $wpdb->delete( self::table(), array( 'contact_id' => (int) $contact_id ) ); } public static function on_merge( $keep_id, $merge_id ) { global $wpdb; $wpdb->update( self::table(), array( 'contact_id' => (int) $keep_id ), array( 'contact_id' => (int) $merge_id ) ); } /* ------------------------------------------------------------------ * * Pipelines and stages * ------------------------------------------------------------------ */ /** Deals switched on (Settings → Your business, or the setup): Deals, Board and deal cards show. Data is kept either way. */ public static function on() { return false !== Nodebook_Settings::get( 'deals' ) && '0' !== (string) Nodebook_Settings::get( 'deals' ); } public static function default_stages() { if ( class_exists( 'Nodebook_Niche' ) && 'retreats' === Nodebook_Niche::current() ) { return array( 'enquiry' => __( 'Enquiry', 'nodebook' ), 'call' => __( 'Call', 'nodebook' ), 'applied' => __( 'Applied', 'nodebook' ), 'deposit' => __( 'Deposit paid', 'nodebook' ), ); } return array( 'new' => __( 'New', 'nodebook' ), 'qualified' => __( 'Qualified', 'nodebook' ), 'proposal' => __( 'Proposal sent', 'nodebook' ), 'negotiation' => __( 'Negotiating', 'nodebook' ), ); } /** * Pipelines: id => [ name, stages (key => label) ], in their order. * * @return array}> */ public static function pipelines() { $stages = get_option( self::STAGES, array() ); $stages = is_array( $stages ) && $stages ? $stages : self::default_stages(); /** * Pipelines: id => [ name, stages ]. * * @param array $pipelines Pipelines from Settings → Pipelines. */ return (array) apply_filters( 'nodebook_deal_pipelines', Nodebook_Pipelines::build( $stages ) ); } /** A deal's stage as people read it (from the deal's own pipeline). */ public static function stage_name( array $d ) { $stages = self::stages( (int) ( $d['pipeline_id'] ?? 1 ) ); return (string) ( $stages[ $d['stage'] ] ?? $d['stage'] ); } /** * The pipeline someone is looking at: from the address (and remembered per person), else the first. */ public static function current() { $all = self::pipelines(); list( $id, $save ) = class_exists( 'Nodebook_Admin' ) ? Nodebook_Admin::view_choice( 'pipeline' ) : array( '', false ); $id = absint( $id ); if ( $id && isset( $all[ $id ] ) ) { if ( $save ) { update_user_meta( get_current_user_id(), 'nodebook_pipeline', $id ); } return $id; } $saved = (int) get_user_meta( get_current_user_id(), 'nodebook_pipeline', true ); return isset( $all[ $saved ] ) ? $saved : (int) array_key_first( $all ); } public static function stages( $pipeline = 1 ) { $p = self::pipelines(); return isset( $p[ $pipeline ] ) ? (array) $p[ $pipeline ]['stages'] : (array) reset( $p )['stages']; } /** * Save the stages of a pipeline from a list of labels (in order). Existing stages keep their key, * so deals stay where they are; deals in a removed stage move to the first one. * Pipeline 1 is stored here; Nodebook_Pipelines stores the returned stages of the others. * * @param array $labels Ordered labels; [ old key => label ] keeps keys. * @param int $pipeline Pipeline ID. * @param array $old Stages before (default: the pipeline's current stages). * @return array */ public static function save_stages( array $labels, $pipeline = 1, $old = null ) { global $wpdb; $pipeline = (int) $pipeline; $old = is_array( $old ) ? $old : ( isset( self::pipelines()[ $pipeline ] ) ? self::stages( $pipeline ) : array() ); $new = array(); foreach ( $labels as $key => $label ) { $label = mb_substr( trim( sanitize_text_field( (string) $label ) ), 0, 60 ); if ( '' === $label ) { continue; } $keep = is_string( $key ) && isset( $old[ $key ] ); $k = $keep ? $key : trim( sanitize_key( substr( (string) preg_replace( '/[^a-z0-9]+/', '_', remove_accents( strtolower( $label ) ) ), 0, 30 ) ), '_' ); $k = '' === $k ? 'stage' : $k; $base = $k; // A new stage never takes the key of an existing stage that stays (its deals would jump). for ( $i = 2; isset( $new[ $k ] ) || ( ! $keep && isset( $old[ $k ], $labels[ $k ] ) ); $i++ ) { $k = $base . '_' . $i; } $new[ $k ] = $label; if ( count( $new ) >= self::MAX ) { break; } } if ( ! $new ) { $new = self::default_stages(); } $first = (string) array_key_first( $new ); foreach ( array_diff( array_keys( $old ), array_keys( $new ) ) as $gone ) { $wpdb->update( self::table(), array( 'stage' => $first ), array( 'stage' => $gone, 'pipeline_id' => $pipeline, ) ); } if ( 1 === $pipeline ) { update_option( self::STAGES, $new ); } return $new; } /* ------------------------------------------------------------------ * * CRUD * ------------------------------------------------------------------ */ public static function get( $id ) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', self::table(), $id ), ARRAY_A ); return $row ? $row : null; } /** Clean incoming fields. */ private static function prepare( array $in, array $current = array() ) { $out = array(); if ( isset( $in['title'] ) ) { $out['title'] = mb_substr( trim( sanitize_text_field( (string) $in['title'] ) ), 0, 190 ); } foreach ( array( 'contact_id', 'company_id', 'owner_id', 'pipeline_id' ) as $k ) { if ( isset( $in[ $k ] ) ) { $out[ $k ] = absint( $in[ $k ] ); } } if ( isset( $out['pipeline_id'] ) && ! isset( self::pipelines()[ $out['pipeline_id'] ] ) ) { $out['pipeline_id'] = (int) ( $current['pipeline_id'] ?? array_key_first( self::pipelines() ) ); } $pipeline = (int) ( $out['pipeline_id'] ?? ( $current['pipeline_id'] ?? 1 ) ); if ( isset( $in['stage'] ) ) { $stages = self::stages( $pipeline ); $out['stage'] = isset( $stages[ $in['stage'] ] ) ? (string) $in['stage'] : (string) array_key_first( $stages ); } elseif ( $current && isset( $out['pipeline_id'] ) && (int) $current['pipeline_id'] !== $pipeline ) { // Moved to another pipeline: same stage key if it exists there, else its first stage. $stages = self::stages( $pipeline ); $out['stage'] = isset( $stages[ $current['stage'] ] ) ? (string) $current['stage'] : (string) array_key_first( $stages ); } if ( isset( $in['value'] ) ) { $v = Nodebook_Props::to_number( $in['value'] ); $out['value'] = null === $v ? 0 : round( (float) $v, 4 ); } if ( isset( $in['currency'] ) ) { $c = strtoupper( trim( (string) $in['currency'] ) ); $out['currency'] = preg_match( '/^[A-Z]{3}$/', $c ) ? $c : ''; } if ( array_key_exists( 'expected_close', $in ) ) { $d = trim( (string) $in['expected_close'] ); $out['expected_close'] = preg_match( '/^\d{4}-\d{2}-\d{2}$/', $d ) ? $d : null; } if ( isset( $in['notes'] ) ) { $out['notes'] = mb_substr( sanitize_textarea_field( (string) $in['notes'] ), 0, 5000 ); } if ( isset( $in['source'] ) ) { $out['source'] = mb_substr( trim( sanitize_text_field( (string) $in['source'] ) ), 0, 100 ); } return $out; } /** * Create a deal. * * @param array $in title, contact_id, company_id, stage, value, currency, owner_id, expected_close, notes. * @return int Deal ID, or 0. */ public static function add( array $in ) { global $wpdb; $row = self::prepare( $in + array( 'stage' => '' ) ); if ( empty( $row['title'] ) ) { $c = ! empty( $row['contact_id'] ) ? Nodebook_Contacts::get( $row['contact_id'] ) : null; $row['title'] = $c ? Nodebook_Contacts::display_name( $c ) : __( 'New deal', 'nodebook' ); } if ( ! empty( $row['contact_id'] ) && empty( $row['company_id'] ) ) { $c = Nodebook_Contacts::get( $row['contact_id'] ); $row['company_id'] = $c ? (int) $c['company_id'] : 0; } if ( empty( $row['currency'] ) ) { $row['currency'] = Nodebook_Conversions::currency(); } if ( empty( $row['source'] ) && ! empty( $row['contact_id'] ) ) { $row['source'] = self::source_of( Nodebook_Contacts::get( $row['contact_id'] ) ); } $now = current_time( 'mysql', true ); $row['pipeline_id'] = $row['pipeline_id'] ?? (int) array_key_first( self::pipelines() ); $row['owner_id'] = $row['owner_id'] ?? get_current_user_id(); $row['created_by'] = get_current_user_id(); $row['created_at'] = $now; $row['updated_at'] = $now; $row['stage_at'] = $now; if ( false === $wpdb->insert( self::table(), $row ) ) { return 0; } $id = (int) $wpdb->insert_id; if ( ! empty( $in['props'] ) && is_array( $in['props'] ) ) { Nodebook_Props::set( 'deal', $id, $in['props'], 'overwrite' ); } self::log( $id, /* translators: %s: deal title */ sprintf( __( 'New deal: %s', 'nodebook' ), $row['title'] ) . self::value_suffix( $row ) ); do_action( 'nodebook_deal_added', $id, $row ); return $id; } /** Update fields; a stage change is logged on the timeline. */ public static function update( $id, array $in ) { global $wpdb; $d = self::get( $id ); if ( ! $d ) { return false; } $row = self::prepare( $in, $d ); if ( isset( $row['title'] ) && '' === $row['title'] ) { unset( $row['title'] ); } if ( ! empty( $in['props'] ) && is_array( $in['props'] ) ) { Nodebook_Props::set( 'deal', (int) $id, $in['props'], 'overwrite' ); } if ( ! $row ) { return true; } $moved = isset( $row['stage'] ) && $row['stage'] !== $d['stage'] && '' === $d['outcome']; if ( $moved ) { $row['stage_at'] = current_time( 'mysql', true ); } $row['updated_at'] = current_time( 'mysql', true ); $ok = false !== $wpdb->update( self::table(), $row, array( 'id' => (int) $id ) ); if ( $ok && $moved ) { $from = self::stages( (int) $d['pipeline_id'] ); $to = self::stages( (int) ( $row['pipeline_id'] ?? $d['pipeline_id'] ) ); self::log( $id, /* translators: 1: deal title, 2: old stage, 3: new stage */ sprintf( __( 'Deal %1$s: %2$s → %3$s', 'nodebook' ), $d['title'], $from[ $d['stage'] ] ?? $d['stage'], $to[ $row['stage'] ] ?? $row['stage'] ) ); do_action( 'nodebook_deal_stage_changed', (int) $id, $row['stage'], $d['stage'] ); } return $ok; } /** * Close a deal as won or lost (or reopen it with ''). * * @param int $id Deal. * @param string $outcome 'won', 'lost' or '' (reopen). * @param string $reason Why it was lost. */ public static function close( $id, $outcome, $reason = '', $activity_id = 0 ) { global $wpdb; $d = self::get( $id ); if ( ! $d || ! in_array( $outcome, array( 'won', 'lost', '' ), true ) || $outcome === $d['outcome'] ) { return false; } $reason = 'lost' === $outcome ? mb_substr( trim( sanitize_text_field( (string) $reason ) ), 0, 190 ) : ''; // Won with an order or booking of the same contact: the deal points at it, so its money is counted once. $link = 0; $paid = null; if ( 'won' === $outcome && $activity_id ) { $paid = self::purchase( (int) $activity_id, (int) $d['contact_id'] ); $link = $paid ? (int) $activity_id : 0; } $row = array( 'outcome' => $outcome, 'lost_reason' => $reason, 'activity_id' => $link, 'closed_at' => '' === $outcome ? null : current_time( 'mysql', true ), 'updated_at' => current_time( 'mysql', true ), ); // No value entered yet: take the order's. if ( $paid && ! (float) $d['value'] && $paid['value'] ) { $row['value'] = $paid['value']; $row['currency'] = '' !== $paid['currency'] ? $paid['currency'] : $d['currency']; $d['value'] = $row['value']; $d['currency'] = $row['currency']; } $wpdb->update( self::table(), $row, array( 'id' => (int) $id ) ); if ( 'won' === $outcome ) { /* translators: %s: deal title */ self::log( $id, sprintf( __( 'Deal won: %s', 'nodebook' ), $d['title'] ) . self::value_suffix( $d ) . ( $paid ? ' · ' . $paid['title'] : '' ) ); // A won deal makes the contact a customer (like a paid order does). $c = $d['contact_id'] ? Nodebook_Contacts::get( $d['contact_id'] ) : null; if ( $c && in_array( $c['status'], array( 'subscriber', 'lead', 'prospect', '' ), true ) ) { Nodebook_Contacts::update( (int) $c['id'], array( 'status' => 'customer' ) ); Nodebook_Activities::add( (int) $c['id'], 'status', __( 'Became a customer', 'nodebook' ), array( 'user_id' => get_current_user_id() ) ); } } elseif ( 'lost' === $outcome ) { /* translators: %s: deal title */ self::log( $id, sprintf( __( 'Deal lost: %s', 'nodebook' ), $d['title'] ) . ( '' !== $reason ? ' · ' . $reason : '' ) ); } else { /* translators: %s: deal title */ self::log( $id, sprintf( __( 'Deal reopened: %s', 'nodebook' ), $d['title'] ) ); } do_action( 'nodebook_deal_closed', (int) $id, $outcome, $reason ); return true; } public static function delete( $id ) { global $wpdb; Nodebook_Props::delete_for( 'deal', array( (int) $id ) ); $wpdb->update( Nodebook_Tasks::table(), array( 'deal_id' => 0 ), array( 'deal_id' => (int) $id ) ); return (bool) $wpdb->delete( self::table(), array( 'id' => (int) $id ) ); } /** Where a contact came from, as one line: "Google · paid", or the form or shop that created them. */ public static function source_of( $c ) { if ( ! $c ) { return ''; } if ( ! empty( $c['first_source'] ) ) { return mb_substr( Nodebook_Attribution::label( $c['first_source'], (string) $c['first_medium'] ), 0, 100 ); } return mb_substr( (string) $c['source'], 0, 100 ); } /** * Orders and bookings of a contact (newest first): activity id, title, value, currency, date. * * @param int $contact_id Contact. * @param string $since Only those after this moment (GMT), e.g. the deal's creation. */ public static function purchases( $contact_id, $since = '' ) { global $wpdb; if ( ! $contact_id ) { return array(); } $since = (string) $since; $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id FROM %i WHERE contact_id = %d AND type IN ('order','booking','appointment') AND ( %s = '' OR created_at >= %s ) ORDER BY created_at DESC, id DESC LIMIT 10", Nodebook_Activities::table(), $contact_id, $since, $since ), ARRAY_A ); $out = array(); foreach ( $rows as $r ) { $p = self::purchase( (int) $r['id'], (int) $contact_id ); if ( $p ) { $out[] = $p; } } return $out; } /** One order or booking of the contact, or null. */ public static function purchase( $activity_id, $contact_id ) { global $wpdb; $a = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = %d AND contact_id = %d AND type IN ('order','booking','appointment')", Nodebook_Activities::table(), $activity_id, $contact_id ), ARRAY_A ); if ( ! $a ) { return null; } $data = json_decode( (string) $a['data'], true ); $data = is_array( $data ) ? $data : array(); $val = $data['total'] ?? ( $data['value'] ?? 0 ); return array( 'id' => (int) $a['id'], 'type' => $a['type'], 'title' => (string) $a['title'], 'value' => is_numeric( $val ) ? round( (float) $val, 4 ) : 0.0, 'currency' => strtoupper( (string) ( $data['currency'] ?? '' ) ), 'at' => $a['created_at'], ); } /** Open deals whose contact ordered or booked after the deal was added: probably won. */ public static function ordered( $owner = 0 ) { global $wpdb; list( $scope, $scope_args ) = self::scope_where( 'd' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- $scope is fixed SQL with placeholders; values passed to prepare(). return (array) $wpdb->get_results( $wpdb->prepare( "SELECT d.*, c.first_name, c.last_name, c.email, c.phone, c.country, '' AS company FROM %i d INNER JOIN %i c ON c.id = d.contact_id WHERE d.outcome = '' AND EXISTS (SELECT 1 FROM %i a WHERE a.contact_id = d.contact_id AND a.type IN ('order','booking','appointment') AND a.created_at >= d.created_at) AND ( %d = 0 OR d.owner_id IN (0, %d) ) AND ( " . $scope . ' ) ORDER BY d.id DESC LIMIT 30', array_merge( array( self::table(), Nodebook_Contacts::table(), Nodebook_Activities::table(), (int) $owner, (int) $owner ), $scope_args ) ), ARRAY_A ); } /** " · $5,000.00" or ''. */ public static function value_suffix( array $d ) { return ! empty( $d['value'] ) && (float) $d['value'] ? ' · ' . self::money( $d ) : ''; } public static function money( array $d ) { return Nodebook_Admin::money( (float) ( $d['value'] ?? 0 ), (string) ( $d['currency'] ?? '' ) ); } /** A line on the contact's timeline (when the deal has a contact). */ private static function log( $id, $title ) { $d = self::get( $id ); if ( ! $d || ! $d['contact_id'] ) { return; } Nodebook_Activities::add( (int) $d['contact_id'], 'deal', $title, array( 'object_id' => (int) $id, 'user_id' => get_current_user_id(), 'data' => array_filter( array( 'deal' => (int) $id, 'stage' => $d['stage'], 'outcome' => $d['outcome'], 'value' => (float) $d['value'], 'currency' => $d['currency'], ) ), ) ); } /* ------------------------------------------------------------------ * * Queries * ------------------------------------------------------------------ */ /** * Deals with their contact and company names. * * @param array $args outcome ('open'|'won'|'lost'|'all'), stage, owner (0 = all), contact_id, company_id, * pipeline_id, closing_before (Y-m-d), closed_since (GMT), limit, order ('stage'|'close'|'closed'|'created'). */ public static function query( array $args = array() ) { global $wpdb; $a = wp_parse_args( $args, array( 'outcome' => 'open', 'stage' => '', 'owner' => 0, 'contact_id' => 0, 'company_id' => 0, 'pipeline_id' => 0, 'closing_before' => '', 'closed_since' => '', 'limit' => 200, 'order' => 'stage', 'fields' => array(), ) ); $where = array( self::scope_where( 'd' ) ); if ( $a['pipeline_id'] ) { $where[] = array( 'd.pipeline_id = %d', array( (int) $a['pipeline_id'] ) ); } if ( 'open' === $a['outcome'] ) { $where[] = array( "d.outcome = ''", array() ); } elseif ( in_array( $a['outcome'], array( 'won', 'lost' ), true ) ) { $where[] = array( 'd.outcome = %s', array( $a['outcome'] ) ); } if ( '' !== $a['stage'] ) { $where[] = array( 'd.stage = %s', array( (string) $a['stage'] ) ); } if ( $a['owner'] ) { $where[] = array( 'd.owner_id IN (0, %d)', array( (int) $a['owner'] ) ); } if ( $a['contact_id'] ) { $where[] = array( 'd.contact_id = %d', array( (int) $a['contact_id'] ) ); } if ( $a['company_id'] ) { $where[] = array( 'd.company_id = %d', array( (int) $a['company_id'] ) ); } if ( '' !== $a['closing_before'] ) { $where[] = array( 'd.expected_close IS NOT NULL AND d.expected_close <= %s', array( (string) $a['closing_before'] ) ); } if ( '' !== $a['closed_since'] ) { $where[] = array( 'd.closed_at >= %s', array( (string) $a['closed_since'] ) ); } // Deal fields: key => exact value (choice and yes/no fields on the board). $defs = Nodebook_Props::defs( 'deal' ); foreach ( (array) $a['fields'] as $k => $v ) { if ( isset( $defs[ $k ] ) && '' !== (string) $v ) { $where[] = array( "EXISTS (SELECT 1 FROM %i fv WHERE fv.object_type = 'deal' AND fv.object_id = d.id AND fv.field_key = %s AND fv.value_text = %s)", array( Nodebook_Props::table(), (string) $k, (string) $v ) ); } } // Fixed ORDER BY clauses only. $orders = array( 'stage' => ' ORDER BY d.stage_at DESC, d.id DESC', 'close' => ' ORDER BY d.expected_close IS NULL, d.expected_close ASC, d.id ASC', 'closed' => ' ORDER BY d.closed_at DESC, d.id DESC', 'created' => ' ORDER BY d.created_at DESC, d.id DESC', ); $order = $orders[ $a['order'] ] ?? $orders['stage']; list( $sql, $params ) = Nodebook_Sql::join( $where ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- $sql and $order are fixed SQL with placeholders; values passed to prepare(). return (array) $wpdb->get_results( $wpdb->prepare( 'SELECT d.*, c.first_name, c.last_name, c.email, c.phone, c.country, co.name AS company FROM %i d LEFT JOIN %i c ON c.id = d.contact_id LEFT JOIN %i co ON co.id = d.company_id WHERE ' . $sql . $order . ' LIMIT %d', array_merge( array( self::table(), Nodebook_Contacts::table(), Nodebook_Companies::table() ), $params, array( (int) $a['limit'] ) ) ), ARRAY_A ); } /** * Count and value per stage of open deals (value only in the main currency; others listed apart). * * @return array}> */ public static function stage_totals( $owner = 0, $pipeline = 1 ) { global $wpdb; $main = Nodebook_Conversions::currency(); $out = array(); foreach ( self::stages( $pipeline ) as $k => $label ) { $out[ $k ] = array( 'count' => 0, 'value' => 0.0, 'other' => array(), ); } list( $scope, $scope_args ) = self::scope_where( 'd' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- $scope is fixed SQL with placeholders; values passed to prepare(). foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT d.stage, d.currency, COUNT(*) n, SUM(d.value) v FROM %i d LEFT JOIN %i c ON c.id = d.contact_id WHERE d.pipeline_id = %d AND d.outcome = '' AND ( %d = 0 OR d.owner_id IN (0, %d) ) AND ( " . $scope . ' ) GROUP BY d.stage, d.currency', array_merge( array( self::table(), Nodebook_Contacts::table(), (int) $pipeline, (int) $owner, (int) $owner ), $scope_args ) ), ARRAY_A ) as $r ) { if ( ! isset( $out[ $r['stage'] ] ) ) { continue; } $out[ $r['stage'] ]['count'] += (int) $r['n']; $cur = strtoupper( (string) $r['currency'] ); if ( '' === $cur || '' === $main || $cur === $main ) { $out[ $r['stage'] ]['value'] += (float) $r['v']; } else { $out[ $r['stage'] ]['other'][ $cur ] = ( $out[ $r['stage'] ]['other'][ $cur ] ?? 0.0 ) + (float) $r['v']; } } return $out; } /** Open value over every pipeline (main currency only), for summaries. */ public static function open_value( $owner = 0 ) { $sum = 0.0; foreach ( array_keys( self::pipelines() ) as $p ) { $sum += array_sum( wp_list_pluck( self::stage_totals( $owner, (int) $p ), 'value' ) ); } return $sum; } /** "€12,400.00" plus other currencies, for a stage total. */ public static function total_label( array $t ) { $label = Nodebook_Admin::money( $t['value'] ); $other = Nodebook_Conversions::others_label( $t['other'] ); return '' !== $other ? $label . ' + ' . $other : $label; } /** Won in a period: count and value in the main currency. */ public static function won_since( $since, $until = '' ) { global $wpdb; $main = Nodebook_Conversions::currency(); $until = '' !== $until ? $until : gmdate( 'Y-m-d H:i:s', time() + 60 ); list( $scope, $scope_args ) = self::scope_where( 'd' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- $scope is fixed SQL with placeholders; values passed to prepare(). $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT d.currency, d.activity_id > 0 AS linked, COUNT(*) n, SUM(d.value) v FROM %i d LEFT JOIN %i c ON c.id = d.contact_id WHERE d.outcome = 'won' AND d.closed_at >= %s AND d.closed_at < %s AND ( " . $scope . ' ) GROUP BY d.currency, linked', array_merge( array( self::table(), Nodebook_Contacts::table(), $since, $until ), $scope_args ) ), ARRAY_A ); $n = 0; $v = 0.0; $paid = 0.0; foreach ( $rows as $r ) { $n += (int) $r['n']; $cur = strtoupper( (string) $r['currency'] ); if ( '' === $cur || '' === $main || $cur === $main ) { $v += (float) $r['v']; if ( (int) $r['linked'] ) { $paid += (float) $r['v']; } } } // [ count, value, part of the value that is an order or booking already counted as revenue ]. return array( $n, $v, $paid ); } /** * Deals a restricted user may see: their own, or on a contact they can see. A condition (see Nodebook_Sql), * always true for people who see everything. Needs the contacts table joined as "c". * * @param string $alias Alias of the deals table. * @return array{0:string,1:array} */ public static function scope_where( $alias = 'd' ) { $team = Nodebook_Team::scope_where( 'c.owner_id' ); if ( '1=1' === $team[0] ) { return $team; } $alias = preg_replace( '/[^a-z]/', '', (string) $alias ); return array( '%i.owner_id = %d OR ( %i.contact_id > 0 AND ' . $team[0] . ' )', array_merge( array( $alias, get_current_user_id(), $alias ), $team[1] ) ); } /** Whether the current user may see a deal. */ public static function can_see( array $d ) { if ( ! Nodebook_Team::restricted() ) { return true; } return (int) $d['owner_id'] === (int) get_current_user_id() || ( $d['contact_id'] && Nodebook_Contacts::get( (int) $d['contact_id'] ) && Nodebook_Team::can_see( (int) $d['contact_id'] ) ); } /** Whether a close date has passed. */ public static function is_late( array $d ) { return '' === $d['outcome'] && ! empty( $d['expected_close'] ) && $d['expected_close'] < wp_date( 'Y-m-d' ); } }