Revision 296 (by ahitrov, 2013/03/26 17:59:01) Promosite (anthill) project source
#!/usr/bin/perl

use strict;
use warnings "all";
use locale;

use FindBin;
BEGIN {
	require "$FindBin::RealBin/../lib/Modules.pm";
}

use Contenido::Globals;
use Contenido::Init;
use ErrorTee;
use PidFile;
use JSON::XS;
use Data::Dumper;

# begin
Contenido::Init->init();

#PidFile->new($state);               # db-based locking   (run only on one host)
#PidFile->new($state, per_host=>1);  # db-based locking   (run on whole cluster)
#PidFile->new($state->{run_dir});    # file-based locking (run on whole cluster)

my $keeper_module = $state->project.'::Keeper';
$keeper = $keeper_module->new($state);

############################################
# please use:
#     $state->{log_dir} for logging
#     $state->{tmp_dir} for temporary files
###########################################
my @votings = $keeper->get_documents (
		class	=> 'promosuite::Voting',
		status	=> [1,2],
	);
my $SIZE = 400;
foreach my $voting ( @votings ) {
	my @voices; my $p = 0;
	my $voting_data = $voting->get_image('voting');
	while ( my @vs = $keeper->get_documents ( 
				class => 'promosuite::Voice', object_id => $voting->id,
				order_by => 'id', limit => $SIZE, offset => $SIZE * $p++ ) ) {
		push @voices, @vs;
	}

	if ( @voices ) {
		my %voting_data;
		foreach my $voice ( @voices ) {
			my $json = JSON::XS->new;
			my $voice_data = $json->decode($voice->voting);
			next	unless ref $voice_data eq 'HASH';
			while ( my ($qnum, $answer) = each %$voice_data ) {
				next	unless ref $answer eq 'HASH';
				while ( my ($anum, $value) = each %$answer ) {
					$voting_data{$qnum}{$anum}{total} = 0 	unless defined $voting_data{$qnum}{$anum}{total};
					$voting_data{$qnum}{$anum}{total} += $value;
					$voting_data{$qnum}{$anum}{count} = 0 	unless defined $voting_data{$qnum}{$anum}{count};
					$voting_data{$qnum}{$anum}{count}++;
				}
			}
	
		}
		for ( 1..$voting_data->{'question_amount'} ) {
			my $qnum = $_;
			if ( $voting_data->{questions}->[$qnum-1]->{amount} ) {
				for ( 1..$voting_data->{questions}->[$qnum-1]->{amount} ) {
					my $anum = $_ - 1;
					if ( exists $voting_data{$qnum} && exists $voting_data{$qnum}{$anum} ) {
						if ( $voting_data->{questions}->[$qnum-1]->{range} ) {
							$voting_data->{questions}->[$qnum-1]->{choices}->[$anum]->{votes} = $voting_data{$qnum}{$anum}{total}/$voting_data{$qnum}{$anum}{count};
						} else {
							$voting_data->{questions}->[$qnum-1]->{choices}->[$anum]->{votes} = $voting_data{$qnum}{$anum}{total};
						}
					}
				}
			}
		}
		$voting_data->{total} = scalar @voices;
		{
			local $Data::Dumper::Indent = 0;
			$voting->voting( Dumper($voting_data) );
		}
	}
	$voting->status(3)		if $voting->status == 2;
	$voting->store;

}