/ Gists / AW

Gists - AW

On gists

AfterSaveAction, events (own Kdyby implementation)

AW PHP Patterns

aftersaveEvent.php #

<?php

final class EshopOrderAfterSaveRegister extends Nette\Object {

	/**
	 * Nette callback array of after order save actions
	 * 
	 * @var array
	 */
	public $onAfterSave;

	/**
	 * Array with IAfterSaveAction objects
	 * 
	 * @var array
	 */
	private $afterSaveActions = array();

	/**
	 * Nette callback array of actions after success payment
	 * 
	 * @var array
	 */
	public $onAfterSuccessPayment;

	/**
	 * Array with IAfterSaveAction objects
	 * 
	 * @var array
	 */
	private $afterSuccessPaymentActions = array();

	/**
	 * Nette callback array of actions after fail payment
	 * 
	 * @var array
	 */
	public $onAfterFailPayment;

	/**
	 * Array with IAfterSaveAction objects
	 * 
	 * @var array
	 */
	private $afterFailPaymentActions = array();

	/**
	 * Instance of current presenter
	 * 
	 * @var Presenter
	 */
	private $presenter;

	/**
	 * Model EshopOrder
	 * 
	 * @var EshopOrder
	 */
	private $modelEshopOrder;

	public function __construct(EshopOrder $modelEshopOrder) {
		$this->modelEshopOrder = $modelEshopOrder;
	}

	/**
	 * Register after save action
	 * 
	 * @param IAfterSaveAction
	 */
	public function addAfterSaveAction(IAfterSaveAction $action) {
		$this->afterSaveActions[] = $action;
		return $this;
	}

	/**
	 * Register after success payment action
	 * 
	 * @param IAfterSaveAction
	 */
	public function addAfterSuccessPaymentAction(IAfterSaveAction $action) {
		$this->afterSuccessPaymentActions[] = $action;
		return $this;
	}

	/**
	 * Register after success payment action
	 * 
	 * @param IAfterSaveAction
	 */
	public function addAfterFailPaymentAction(IAfterSaveAction $action) {
		$this->afterFailPaymentActions[] = $action;
		return $this;
	}

	/**
	 * Application presenter setter
	 * 
	 * @param Presenter
	 */
	public function setPresenter(Presenter $presenter) {
		$this->presenter = $presenter;
		return $this;
	}

	/**
	 * Inicialize and invoke after save actions
	 * 
	 * @param  int
	 * @return void
	 */
	public function invokeAfterSaveActions($orderId) {
		foreach($this->afterSaveActions as $action) {
			$action->setPresenter($this->presenter);
			$this->onAfterSave[] = array($action, 'doAction');
		}

		$eshopOrder 	= $this->modelEshopOrder->getOrder($orderId);
		$orderItems 	= $this->modelEshopOrder->getOrderItems($orderId);
		$orderVouchers 	= $this->modelEshopOrder->getOrderVouchers($orderId);

		$this->onAfterSave($eshopOrder, $orderItems, $orderVouchers);
	}

	/**
	 * Inicialize and invoke after success payment actions
	 * 
	 * @param  int
	 * @return void
	 */
	public function invokeAfterSuccessPaymentActions($orderId) {
		foreach($this->afterSuccessPaymentActions as $action) {
			$action->setPresenter($this->presenter);
			$this->onAfterSuccessPayment[] = array($action, 'doAction');
		}

		$eshopOrder 	= $this->modelEshopOrder->getOrder($orderId);
		$orderItems 	= $this->modelEshopOrder->getOrderItems($orderId);
		$orderVouchers 	= $this->modelEshopOrder->getOrderVouchers($orderId);

		$this->onAfterSuccessPayment($eshopOrder, $orderItems, $orderVouchers);
	}

	/**
	 * Inicialize and invoke after success payment actions
	 * 
	 * @param  int
	 * @return void
	 */
	public function invokeAfterFailPaymentActions($orderId) {
		foreach($this->afterFailPaymentActions as $action) {
			$action->setPresenter($this->presenter);
			$this->onAfterFailPayment[] = array($action, 'doAction');
		}

		$eshopOrder 	= $this->modelEshopOrder->getOrder($orderId);
		$orderItems 	= $this->modelEshopOrder->getOrderItems($orderId);
		$orderVouchers 	= $this->modelEshopOrder->getOrderVouchers($orderId);

		$this->onAfterFailPayment($eshopOrder, $orderItems, $orderVouchers);
	}

}

On gists

Workaround

AW

selection-workaround.php #

<?php

	public function filterAllowedPayments(&$payments)
	{
		// pokud je v kosiku la degustacion nelze platit kartou
		if ($this->isLDBBInBasket() && isset($payments[2])) {
			// $payments->where('NOT id', 2);
			unset($payments[2]);
		}

		// pokud je v kosiku merche, neumoznime platbu kartou pri prevzeti
		if ($this->isMerchInBasket() && isset($payments[4])) {
			// $payments->where('NOT id', 4);
			unset($payments[4]);
		}

		if (!$this->isLDBBInBasket() && isset($payments[4])) {
			unset($payments[4]);
		}

	}

	public function filterAllowedTransports(&$transports)
	{
		// pokud v kosiku neni merche, nelze vyzvednout v ambi kancelari
		if (!$this->isMerchInBasket() && isset($transports[2047])) {
			// $transports->where('NOT id', 2047);
			unset($transports[2047]);
		}
	}

On gists

MSP Vat resolver

PHP AW PHP Patterns

solution.php #

<?php

namespace Model;
use Nette;


class VatCzSkResolver
{
	private static $instance;

	public $eshopOrderFormMasoprofit;
	
	public function __construct(EshopOrderFormMasoprofit $eshopOrderFormMasoprofit)
	{
		self::$instance = $this;
		$this->eshopOrderFormMasoprofit = $eshopOrderFormMasoprofit;
	}

	public static function getDphRewrite()
	{
		if (!self::$instance) { // nejsme na frontendu
			return null;
		}
		
		if ($billingAddress = self::$instance->eshopOrderFormMasoprofit->getBillingAddress()) {
			if (isset($billingAddress['country_id']) && $billingAddress['country_id'] == 186) {
				if (isset($billingAddress['ic_vat']) && $billingAddress['ic_vat'] && isset($billingAddress['dic']) && $billingAddress['dic']) {
					return 0;
				}

				return 20;
			}
		}

		return null;
	}
}

On gists

OnInvalidClick - Nette form

Nette-Forms AW

onInvalidClick.php #

<?php
  // https://git.andweb.cz/brandcloud/app/-/blob/bcnew/app/BrandCloudModule/components/SharingForm.php#L148

	$form->addSubmit('share', 'Share')
			->onInvalidClick[] = function () use ($form) {
				// we have to set recipients as items to revalidate recipients field
				// TODO: posibly change multiselectbox to some other implementation which works only with raw value
				if ($form['sharing_type']->getValue() === 'email') {
					$form['recipients']->setItems((array) $form['recipients']->getRawValue(), false);
					$form->validate();
				}
			};

		$form->onValidate[] = [$this, 'validateForm'];
		$form->onSubmit[] = [$this, 'submitForm'];
		$form->onSuccess[] = [$this, 'successForm'];
		$form->setDefaults($this->getFormDefaults());
		return $form;

On gists

Test datových typů, Nette 2.0 AW

AW

dataTypes.php #

<?php

		/**
		 * TEST DATOVYCH TYPU
		 */

		call_user_func(function() { 

			// krabice
			$krabiceActiveRow = $this->connection->table('eshop_item')->where('id', 1467)->fetch();
			$krabiceDataset = $krabiceActiveRow->getDataset();
			$pv = $krabiceDataset->getPrimaryVariant();
			_bardump($krabiceActiveRow);

		});

		call_user_func(function() { 

			// varianta
			$varianta = $this->connection->table('eshop_item_variant')->where('id', 5411)->fetch();
			$krabiceActiveRow = $varianta->eshop_item;
			$krabiceDataset = $krabiceActiveRow->getDataset();
			$pv = $krabiceDataset->getPrimaryVariant(); // nerfunkcni viz http://bit.ly/2zzn4NI

			_bardump($krabiceActiveRow);

		});

On gists

BC Dummy data - SQL

AW

dummy-data-sql.sql #

-- dokumenty, regiony, klient, konkretni klient
SET @clientId = 10809;

INSERT INTO 

bc_stats (bc_document_id, bc_region_id, bc_client_id)

SELECT
id, 
bc_region_id,
@clientId
FROM 

bc_document 
WHERE bc_client_id = @clientId
AND bc_category_id != 0;


-- vsichni klienti
INSERT INTO 
bc_stats (bc_document_id, bc_region_id, bc_client_id)
SELECT
id, 
bc_region_id,
bc_client_id
FROM 
bc_document 
WHERE 1
AND bc_category_id != 0;



-- storage_id
update bc_stats t
    set bc_storage_id = elt(floor(rand()*12) + 1, 
	 8640,
     8641,
	 4409,
     5318,
     5338,
     6901,
     5314,
     3949,
     3332,
     3333,
     3404,
     11311
	);


-- emaily
update bc_stats t
    set email = elt(floor(rand()*15) + 1, 
	 
	 'janko@andweb.cz',
	  'stancek@andweb.cz', 
	  'netolicky@andweb.cz',
	  
	  'aaa@andweb.cz',
	  'bbb@andweb.cz', 
	  'ccc@andweb.cz',
	  
	  'ddd@andweb.cz',
	  'eee@andweb.cz', 
	  'fff@andweb.cz',
	  
	  'ggg@andweb.cz',
	  'hhh@andweb.cz', 
	  'iii@andweb.cz',
	  
	    
	  'jjj@andweb.cz',
	  'kkk@andweb.cz', 
	  'lll@andweb.cz'
	);
	

-- datumy
SET @MIN = '2017-06-29 00:53:27';
SET @MAX = '2020-04-29 13:53:27';
 
UPDATE bc_stats
SET created = TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN);


-- akce
update bc_stats t
    set action_type = elt(floor(rand()*7) + 1, 
	 		'login',
			'view',
			'share',
			'publish',
			'download',
			'upload',
			'comment'
	 );


 -- uzivatele
SELECT substring_index(GROUP_CONCAT(id), ',', 50) FROM bc_user 
WHERE lastname != ''
ORDER BY id ASC into @users;

SET @sql:= CONCAT('update bc_stats t set bc_user_id = elt(floor(rand()*50) + 1,', ' ', @users, ' )');

PREPARE stmt FROM @sql;
EXECUTE stmt;

-- share
update bc_stats t
    set bc_share_id = FLOOR( RAND() * (11100-11000+1) + 11000 );
	 


-- zopakovat radky
INSERT INTO bc_stats (action_type,created,bc_client_id,bc_user_id,bc_document_id,bc_region_id,bc_share_id,bc_comment_id,bc_upload_id,bc_storage_id,email) 
SELECT action_type,created,bc_client_id,bc_user_id,bc_document_id,bc_region_id,bc_share_id,bc_comment_id,bc_upload_id,bc_storage_id,email 
FROM bc_stats

On gists

ProductDeliveryDateInfo component

Nette Nette-Controls AW

ProductDeliveryDateInfo.php #

<?php

namespace FrontModule\Components;

use Nette,
	Andweb,
	Model;

class ProductDeliveryDateInfo extends Andweb\Application\UI\FrontControl 
{


	const HOUR = 13;



	protected $items = array(
				
			'Praha' => array(
			
				'Osobní odběr Praha'              => 0,
				'Expresní večerní doručení Praha' => 0,
			
			),
			
			'Česká republika' => array(
			
				'Česká pošta'    => 1,
				'Zásilkovna'     => 1,
				'Kurýrní služba' => 1,
			),			
			
			
			'Slovensko' => array(
			
				'Česká pošta'    => 2,
				'Zásilkovna'     => 2,
				'Kurýrní služba' => 2,
			),

	);


	public function __construct() 
	{

	}


	public function renderDefault() 
	{

		$template        = $this->template;
		$template->items = $this->items;

		// Fucking php5.3 on production
		$that = $this;

		$template->registerHelper('formatDate', function($s) use ($that) {
			return $that->formatDate($s);
		});
		
	}	



	public function renderNotAvailable() 
	{
		$template   = $this->template;
		$this->view = 'default';

		$template->notAvailable = TRUE;
		
		$template->items = $this->items;

		// Fucking php5.3 on production
		$that = $this;

		$template->registerHelper('formatDate', function($s) use ($that) {
			return $that->formatDate($s);
		});


		$this->render();
		
	}



	public function formatDate($s)
	{
		$today = new \DateTime();
		$tomorrow = clone $today;
		$tomorrow->modify('+ 1 day');

		if ($today->format('j.n.Y') == $s)
			return $this->presenter->translator->translate('dnes');			

		if ($tomorrow->format('j.n.Y') == $s)
			return $this->presenter->translator->translate( 'zítra');

		return $s;
	}


	// ukaze na velikonocni nedeli, napric vsemi casovymi pasmy, jinak funkce easter_day se chova obcas divne, viz php.net
	public function getEasterDateTime($year) 
	{
		$base = new \DateTime("$year-03-21");
		$days = easter_days($year);
	    return $base->add(new \DateInterval("P{$days}D"));
	}


	public function isNotHoliday(\Datetime $date)
	{
		// statni svatky
		$holidays = array('01-01', '05-01', '05-08', '07-05', '07-06', '09-28', '10-28', '11-17', '12-24', '12-25', '12-26');
		
		// velikonocni pondeli
		$holidays[] = $this->getEasterDateTime(date('Y'))->modify('+1day')->format('m-d');
		
		// velky patek, (pred velikonocnim pondelim)
		$holidays[] = $this->getEasterDateTime(date('Y'))->modify('-2day')->format('m-d');
		
		$day        = $date->format('w');

		if ($day == 0 || $day == 6) 
			return FALSE;

		if (in_array($date->format('m-d'), $holidays)) 
			return FALSE;

		return TRUE;
	}


	function getDeliveryDate($actualDate, $dayDelay = 0)
	{
		$actualDate = new \DateTime($actualDate);
		$actualDate->modify("+$dayDelay day");

		while (!$this->isNotHoliday($actualDate))
		{	
			$actualDate->modify('+1 day');
		}

		return $actualDate;
	}


	public function formatter($dayDelay)
	{
		// 13h a vic + 1 day
		if (date('H') >= self::HOUR)
			$dayDelay += 1;

		return $this->getDeliveryDate(date('Y-m-d'), $dayDelay);
	}





}

On gists

Recontruct nav cache

AW

reconcstruct-nav-cache.sql #

TRUNCATE navigation_cache;

INSERT INTO navigation_cache 
(navigation_id, language_id, path, id_path)
(
    SELECT navigation_id, language_id, NavigationPath(navigation_id, language_id, title), CONCAT(NavigationIdPath(navigation_id, language_id), "/")
    FROM navigation_lang
);

On gists

AwOverlay

AW

overlay.js #


(function(window, $, undefined) {

if (typeof $ !== 'function') {
	return console.error('AW Overlay: jQuery is missing, load it please');
}

var AWOverlay = function () {
	var inner = {
		self: this,
		initialized: false,
		settings: {},
	};




	this.load = function (settings) {

		$("<link/>", {
		   rel: "stylesheet",
		   type: "text/css",
		   href: "https://aw-overlay.pripravujeme.eu/assets/css/screen.css"
		}).appendTo("head");
		inner.settings = settings;

		// Using YQL and JSONP
		$.ajax({
		    url: "https:\/\/aw-overlay.pripravujeme.eu\/index\/overlay",
		 
		    // The name of the callback parameter, as specified by the YQL service
		    jsonp: "callback",
		 
		    // Tell jQuery we're expecting JSONP
		    dataType: "jsonp",
		 
		    // Tell YQL what we want and that we want JSON
		    data: settings,
		 
		    // Work with the response
		    success: function( response ) {
		        $('body').append(response);

		        if(settings.onLoad)
		        	settings.onLoad(inner.self);
		    }
		});
		
	};

	this.open = function() {
		//e.preventDefault();
		$('.aw-overlay').fadeIn();
		$('#aw-overlay-full').fadeIn();
		$('#aw-overlay-short').fadeOut();
		$('#aw-main-content').addClass('open').removeClass('close');

		//return false;
	};

	this.close = function() {
		$('.aw-overlay').fadeOut();
		$('#aw-overlay-full').fadeOut();
		$('#aw-overlay-short').fadeIn();
		$('#aw-main-content').addClass('close').removeClass('open');
		if(inner.settings.onClose)
			inner.settings.onClose(this);
		//return false;
	};

	this.closeImmediate = function(){
		$('.aw-overlay').hide();
		$('#aw-overlay-full').hide();
		$('#aw-overlay-short').show();
		$('#aw-main-content').addClass('close').removeClass('open');		
	}

};

window.awOverlay = new AWOverlay();


})(window, window.jQuery);

On gists

Factory - elastic

AW

factory.php #

<?php

namespace Andweb\Model;

use Nette,
	Andweb,
	Andweb\Database\Context;

use Andweb\Model\ElasticSearch;
use Andweb\Model\ElasticSearchResponse;

class ElasticSearchWrapperFactory  
{
	use Nette\SmartObject;

	/**
	 * @var ElasticSearch
	 */
	protected $elasticSearch;


	/**
	 * @var Nette\DI\Container
	 */
	protected $dic;


	public function __construct(ElasticSearch $elasticSearch, Nette\DI\Container $dic) 
	{
		$this->elasticSearch = $elasticSearch;
		$this->dic = $dic;
	}


	/**
	 * @param string $langName
	 * @return Andweb\Model\ElasticSearchWrapper
	 */
	public function create($langName)
	{
		$parameters = $this->dic->getParameters();
		return new ElasticSearchWrapper($parameters["searchQuery-$langName"], $parameters["searchIndex-$langName"], $this->elasticSearch);
		
	}
	
}