<commit_before><?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * Billing abstract subscriber class
 *
 * @package  Billing
 * @since    5.3
 */
class Billrun_Balance_Prepaid extends Billrun_Balance {

	protected $connection_type = 'prepaid';

	/**
	 * minimum values for balance usage (on prepaid)
	 * @var array()
	 */
	protected $granted = array();

	/**
	 * Saves the name of the selected balance type cost/usagev/total_cost.
	 * Used to acces remaining balance in the balance object.
	 * 
	 * @var string
	 */
	protected $selectedBalance = '';

	/**
	 * the total key of the balance (on prepaid)
	 * @var string
	 */
	protected $chargingTotalsKey = null;

	
	public function __construct($values = null, $collection = null) {
		parent::__construct($values, $collection);
		$this->selectedBalance = self::getSelectedBalanceKey($this->getRawData());
	}
	
	protected function init() {
		if (isset($this->row['granted_usagev']) && is_numeric($this->row['granted_usagev'])) {
			$this->granted['usagev'] = (-1) * $this->row['granted_usagev'];
		}

		if (isset($this->row['granted_cost']) && is_numeric($this->row['granted_cost'])) {
			$this->granted['cost'] = (-1) * $this->row['granted_cost'];
		}
	}

	/**
	 * on prepaid there is no default balance, return no balance (empty array)
	 * @param array $options settings
	 * @return array
	 */
	protected function getDefaultBalance($options) {
		return array();
	}

	protected function loadQuerySort() {
		return array('priority' => -1, 'to' => 1,);
	}

	protected function getBalanceLoadQuery($query = array()) {
		$usageType = $this->row['usaget'];
		if (isset($this->granted['usagev'])) {
			$minUsage = $this->granted['usagev'];
		} else {
			$minUsage = (float) Billrun_Factory::config()->getConfigValue('balance.minUsage.' . $usageType, Billrun_Factory::config()->getConfigValue('balance.minUsage', -3, 'float')); // float avoid set type to int
		}

		if (isset($this->granted['cost'])) {
			$minCost = $this->granted['cost'];
		} else {
			$minCost = (float) Billrun_Factory::config()->getConfigValue('balance.minCost' . $usageType, Billrun_Factory::config()->getConfigValue('balance.minCost', -0.1, 'float')); // float avoid set type to int
		}

		$query['$and'] = array();
		$query['$and'][] = array(
			'$or' => array(
				array("balance.totals.$usageType.usagev" => array('$lte' => $minUsage)),
				array("balance.totals.$usageType.cost" => array('$lte' => $minCost)),
				array("balance.cost" => array('$lte' => $minCost)),
			),
		);
		$query['$and'][] = array(
			'$or' => array(
				array('sid' => 0),
				array('sid' => $this->row['sid']),
			),
		);

		$query['aid'] = $this->row['aid'];
		$query['from'] = array('$lte' => $this->row['urt']);
		$query['to'] = array('$gte' => $this->row['urt']);

		$this->applyAllowInRates($query);
		
		Billrun_Factory::dispatcher()->trigger('getBalanceLoadQuery', array(&$query, $this->row, $this));

		return $query;
	}
	
	/**
	 * apply only allowed in rates in pre-paid includes
	 * includes also pre-paid includes entries that support all rates (allowed_in field does not exists)
	 * the filter is using nin operator as it filter out all the entries that does not match
	 * 
	 * @param void
	 */
	protected function applyAllowInRates(&$query) {
		$basePlanName = "BASE";
		$planName = $this->row->get('plan');
		$rateName = $this->row->get('arate_key');
		
		$allowedInQuery = array('$or' => array(
				array('$and' => array(
						array("allowed_in." . $planName => array('$exists' => 1)),
						array("allowed_in." . $planName => array('$nin' => array($rateName))),
					)),
				array('$and' => array(
						array("allowed_in." . $planName => array('$exists' => 0)),
						array("allowed_in." . $basePlanName => array('$exists' => 1)),
						array("allowed_in." . $basePlanName => array('$nin' => array($rateName))),
					)),
		));
		
		$prepaidIncludesCollection = Billrun_Factory::db()->prepaidincludesCollection();
		$ppIncludes = $prepaidIncludesCollection->query($allowedInQuery)->cursor();
		$notAllowedPPIncludes = array();
		if ($ppIncludes->count() > 0) {
			$notAllowedPPIncludes = array_map(function($doc) {
				return $doc['external_id'];
			}, iterator_to_array($ppIncludes));
			$query['pp_includes_external_id'] = array('$nin' => array_values($notAllowedPPIncludes));
		}
	}

	/**
	 * Gets the key of the current balance
	 * 
	 * @param type $balance
	 * @return string balance key
	 * @todo use only on prepaid; require refactoring
	 */
	public static function getSelectedBalanceKey($balance) {
		$selectedBalance = false;

		if (isset($balance['balance']['totals'])) {
			foreach ($balance['balance']['totals'] as $usageType => $value) {
				foreach (array_keys($value) as $usageBy) {
					$selectedBalance = 'balance.totals.' . $usageType . '.' . $usageBy;
				}
			}
		} else if (isset($balance['balance']['cost'])) {
			$selectedBalance = 'balance.cost';
		}
<commit_msg>improve name convention<commit_after><?php

/**
 * @package         Billing
 * @copyright       Copyright (C) 2012-2016 BillRun Technologies Ltd. All rights reserved.
 * @license         GNU Affero General Public License Version 3; see LICENSE.txt
 */

/**
 * Billing abstract subscriber class
 *
 * @package  Billing
 * @since    5.3
 */
class Billrun_Balance_Prepaid extends Billrun_Balance {

	protected $connection_type = 'prepaid';

	/**
	 * minimum values for balance usage (on prepaid)
	 * @var array()
	 */
	protected $granted = array();

	/**
	 * Saves the name of the selected balance type cost/usagev/total_cost.
	 * Used to acces remaining balance in the balance object.
	 * 
	 * @var string
	 */
	protected $selectedBalance = '';

	/**
	 * the total key of the balance (on prepaid)
	 * @var string
	 */
	protected $chargingTotalsKey = null;

	
	public function __construct($values = null, $collection = null) {
		parent::__construct($values, $collection);
		$this->selectedBalance = self::getSelectedBalanceKey($this->getRawData());
	}
	
	protected function init() {
		if (isset($this->row['granted_usagev']) && is_numeric($this->row['granted_usagev'])) {
			$this->granted['usagev'] = (-1) * $this->row['granted_usagev'];
		}

		if (isset($this->row['granted_cost']) && is_numeric($this->row['granted_cost'])) {
			$this->granted['cost'] = (-1) * $this->row['granted_cost'];
		}
	}

	/**
	 * on prepaid there is no default balance, return no balance (empty array)
	 * @param array $options settings
	 * @return array
	 */
	protected function getDefaultBalance($options) {
		return array();
	}

	protected function loadQuerySort() {
		return array('priority' => -1, 'to' => 1,);
	}

	protected function getBalanceLoadQuery($query = array()) {
		$usageType = $this->row['usaget'];
		if (isset($this->granted['usagev'])) {
			$minUsage = $this->granted['usagev'];
		} else {
			$minUsage = (float) Billrun_Factory::config()->getConfigValue('balance.minUsage.' . $usageType, Billrun_Factory::config()->getConfigValue('balance.minUsage', -3, 'float')); // float avoid set type to int
		}

		if (isset($this->granted['cost'])) {
			$minCost = $this->granted['cost'];
		} else {
			$minCost = (float) Billrun_Factory::config()->getConfigValue('balance.minCost' . $usageType, Billrun_Factory::config()->getConfigValue('balance.minCost', -0.1, 'float')); // float avoid set type to int
		}

		$query['$and'] = array();
		$query['$and'][] = array(
			'$or' => array(
				array("balance.totals.$usageType.usagev" => array('$lte' => $minUsage)),
				array("balance.totals.$usageType.cost" => array('$lte' => $minCost)),
				array("balance.cost" => array('$lte' => $minCost)),
			),
		);
		$query['$and'][] = array(
			'$or' => array(
				array('sid' => 0),
				array('sid' => $this->row['sid']),
			),
		);

		$query['aid'] = $this->row['aid'];
		$query['from'] = array('$lte' => $this->row['urt']);
		$query['to'] = array('$gte' => $this->row['urt']);

		$this->applyAllowInRates($query);
		
		Billrun_Factory::dispatcher()->trigger('getBalanceLoadQuery', array(&$query, $this->row, $this));

		return $query;
	}
	
	/**
	 * apply only allowed in rates in pre-paid includes
	 * includes also pre-paid includes entries that support all rates (allowed_in field does not exists)
	 * the filter is using nin operator as it filter out all the entries that does not match
	 * 
	 * @param void
	 */
	protected function applyAllowInRates(&$query) {
		$basePlanName = "BASE";
		$planName = $this->row->get('plan');
		$rateName = $this->row->get('arate_key');
		
		$disallowedPrepaidIncludesQuery = array('$or' => array(
				array('$and' => array(
						array("allowed_in." . $planName => array('$exists' => 1)),
						array("allowed_in." . $planName => array('$nin' => array($rateName))),
					)),
				array('$and' => array(
						array("allowed_in." . $planName => array('$exists' => 0)),
						array("allowed_in." . $basePlanName => array('$exists' => 1)),
						array("allowed_in." . $basePlanName => array('$nin' => array($rateName))),
					)),
		));
		
		$prepaidIncludesCollection = Billrun_Factory::db()->prepaidincludesCollection();
		$ppIncludes = $prepaidIncludesCollection->query($disallowedPrepaidIncludesQuery)->cursor();
		$disallowedPrepaidIncludes = array();
		if ($ppIncludes->count() > 0) {
			$disallowedPrepaidIncludes = array_map(function($doc) {
				return $doc['external_id'];
			}, iterator_to_array($ppIncludes));
			$query['pp_includes_external_id'] = array('$nin' => array_values($disallowedPrepaidIncludes));
		}
	}

	/**
	 * Gets the key of the current balance
	 * 
	 * @param type $balance
	 * @return string balance key
	 * @todo use only on prepaid; require refactoring
	 */
	public static function getSelectedBalanceKey($balance) {
		$selectedBalance = false;

		if (isset($balance['balance']['totals'])) {
			foreach ($balance['balance']['totals'] as $usageType => $value) {
				foreach (array_keys($value) as $usageBy) {
					$selectedBalance = 'balance.totals.' . $usageType . '.' . $usageBy;
				}
			}
		} else if (isset($balance['balance']['cost'])) {
			$selectedBalance = 'balance.cost';
		}

{'fraction_non_alphanumeric': 0.18754291319274155, 'fraction_numerical': 0.004512015693967631, 'mean_word_length': 4.115905669844455, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 131, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2252637', 'n_tokens_mistral': 3666, 'n_tokens_neox': 3250, 'n_words': 726}