1 package NDWeb::Controller::Raids;
5 use parent 'Catalyst::Controller';
13 NDWeb::Controller::Raids - Catalyst Controller
28 sub index :Path :Args(0) {
29 my ( $self, $c ) = @_;
33 my $query = $dbh->prepare(q{SELECT r.id,released_coords AS releasedcoords,tick,waves*COUNT(DISTINCT rt.id) AS waves,
34 COUNT(rc.uid) AS claims, COUNT(nullif(rc.launched,false)) AS launched,COUNT(NULLIF(rc.uid > 0,true)) AS blocked
35 FROM raids r JOIN raid_targets rt ON r.id = rt.raid
36 LEFT OUTER JOIN raid_claims rc ON rt.id = rc.target
37 WHERE open AND not removed AND r.id
38 IN (SELECT raid FROM raid_access NATURAL JOIN groupmembers WHERE uid = ?)
39 GROUP BY r.id,released_coords,tick,waves});
40 $query->execute($c->user->id);
42 while (my $raid = $query->fetchrow_hashref){
43 $raid->{waves} -= $raid->{blocked};
44 $raid->{claims} -= $raid->{blocked};
45 delete $raid->{blocked};
46 $launched += $raid->{launched};
49 $c->stash(raids => \@raids);
51 if ($c->check_user_roles(qw/raids_info/)){
52 my $query = $dbh->prepare(q{SELECT r.id,open ,tick,waves*COUNT(DISTINCT rt.id) AS waves,
53 COUNT(rc.uid) AS claims, COUNT(nullif(rc.launched,false)) AS launched ,COUNT(NULLIF(uid > 0,true)) AS blocked
54 FROM raids r JOIN raid_targets rt ON r.id = rt.raid
55 LEFT OUTER JOIN raid_claims rc ON rt.id = rc.target
56 WHERE not removed AND (not open
57 OR r.id NOT IN (SELECT raid FROM raid_access NATURAL JOIN groupmembers WHERE uid = ?))
58 GROUP BY r.id,open,tick,waves});
59 $query->execute($c->user->id);
61 while (my $raid = $query->fetchrow_hashref){
62 $raid->{waves} -= $raid->{blocked};
63 $raid->{claims} -= $raid->{blocked};
64 delete $raid->{blocked};
65 $launched += $raid->{launched};
68 $c->stash(closedraids => \@raids);
71 $query = $dbh->prepare(q{SELECT r.id,tick,waves*COUNT(DISTINCT rt.id) AS waves,
72 COUNT(rc.uid) AS claims, COUNT(nullif(rc.launched,false)) AS launched ,COUNT(NULLIF(uid > 0,true)) AS blocked
73 FROM raids r JOIN raid_targets rt ON r.id = rt.raid
74 LEFT OUTER JOIN raid_claims rc ON rt.id = rc.target
76 GROUP BY r.id,tick,waves});
79 while (my $raid = $query->fetchrow_hashref){
80 $raid->{waves} -= $raid->{blocked};
81 $raid->{claims} -= $raid->{blocked};
82 delete $raid->{blocked};
83 $launched += $raid->{launched};
86 $c->stash(removedraids => \@oldraids);
87 $c->stash(launched => $launched);
93 my ( $self, $c, $raid ) = @_;
96 $c->forward('findRaid');
97 $raid = $c->stash->{raid};
100 $c->stash(raid => $raid->{id});
103 if ($c->user->planet){
104 my $query = $dbh->prepare("SELECT value, score,x,y FROM current_planet_stats WHERE id = ?");
105 $planet = $dbh->selectrow_hashref($query,undef,$c->user->planet);
106 $noingal = "AND NOT (x = $planet->{x} AND y = $planet->{y})";
108 $c->stash(message => parseMarkup($raid->{message}));
109 $c->stash(landingtick => $raid->{tick});
110 my $targetquery = $dbh->prepare(qq{SELECT r.id, r.planet, size, score, value
112 , p.value - p.size*200 -
113 COALESCE(ps.metal+ps.crystal+ps.eonium,0)/150 -
114 COALESCE(ss.total ,(SELECT
115 COALESCE(avg(total),0) FROM
116 structure_scans)::int)*1500 AS fleetvalue
117 ,(metal+crystal+eonium)/100 AS resvalue, comment
118 , hidden, light, medium, heavy
119 FROM current_planet_stats p
120 JOIN raid_targets r ON p.id = r.planet
121 LEFT OUTER JOIN current_planet_scans ps ON p.id = ps.planet
122 LEFT OUTER JOIN current_structure_scans ss ON p.id = ss.planet
126 $targetquery->execute($raid->{id});
128 my %production = (0 => 'None', 35 => 'Light', 65 => 'Medium', 100 => 'High');
129 while (my $target = $targetquery->fetchrow_hashref){
132 if ($planet->{x} == $target->{x}){
133 $target{style} = 'incluster';
135 $target{scorebash} = 'bash' if ($target->{score}/$planet->{score} < 0.4);
136 $target{valuebash} = 'bash' if ($target->{value}/$planet->{value} < 0.4);
137 #next if ($target->{score}/$planet->{score} < 0.4) && ($target->{value}/$planet->{value} < 0.4);
139 $target{id} = $target->{id};
140 $target{race} = $target->{race};
141 my $num = pow(10,length($target->{score})-2);
142 $target{score} = "Hidden"; #ceil($target->{score}/$num)*$num;
143 $num = pow(10,length($target->{value})-2);
144 $target{value} = "Hidden"; #ceil($target->{value}/$num)*$num;
145 $num = pow(10,length($target->{size})-2);
146 $target{size} = floor($target->{size}/$num)*$num;
147 $num = pow(10,length($target->{fleetvalue})-2);
148 $target{fleetvalue} = floor($target->{fleetvalue}/$num)*$num;
149 if (defined $target->{resvalue}){
150 $num = pow(10,length($target->{resvalue})-2);
151 $target{resvalue} = floor($target->{resvalue}/$num)*$num;
153 $target{comment} = parseMarkup($target->{comment}) if ($target->{comment});
155 $target{hidden} = int($target->{hidden} / 100);
156 $target{light} = $production{$target->{light}};
157 $target{medium} = $production{$target->{medium}};
158 $target{heavy} = $production{$target->{heavy}};
160 my $unitscans = $dbh->prepare(q{
161 SELECT DISTINCT ON (name) i.id,i.name, i.tick, i.amount
165 AND i.mission = 'Full fleet'
166 GROUP BY i.id,i.tick,i.name,i.amount
167 ORDER BY name,i.tick DESC
169 $unitscans->execute($target->{planet});
170 my $ships = $dbh->prepare(q{SELECT ship,amount FROM fleet_ships
171 WHERE id = ? ORDER BY num
174 while (my $mission = $unitscans->fetchrow_hashref){
176 $ships->execute($mission->{id});
177 while (my $ship = $ships->fetchrow_hashref){
180 push @ships, {ship => 'No', amount => 'ships'} if @ships == 0;
181 $mission->{ships} = \@ships;
182 $mission->{amount} =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g; #Add comma for ever 3 digits, i.e. 1000 => 1,000
183 delete $mission->{id};
184 push @missions,$mission;
186 $target{missions} = \@missions;
188 my $query = $dbh->prepare(q{SELECT DISTINCT ON(rid) tick,category,name,amount
189 FROM planet_data pd JOIN planet_data_types pdt ON pd.rid = pdt.id
190 WHERE pd.id = $1 AND rid in (1,2,3,4,5,6,9,10,14,15,16,17,18)
191 ORDER BY rid,tick DESC
193 $query->execute($target->{planet});
194 while (my $data = $query->fetchrow_hashref){
195 $data->{amount} =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g; #Add comma for ever 3 digits, i.e. 1000 => 1,000
196 $data->{name} =~ s/ /_/g;
197 $target{$data->{category}.$data->{name}} = $data->{amount};
202 my $size = $target{size};
203 for (my $i = 1; $i <= $raid->{waves}; $i++){
204 my $roids = floor(0.25*$size);
208 $xp = pa_xp($roids,$planet->{score},$planet->{value},$target->{score},$target->{value});
210 push @roids,{wave => $i, roids => $roids, xp => $xp};
211 push @claims,{wave => $i}
213 $target{roids} = \@roids;
214 $target{claims} = \@claims;
216 push @targets,\%target;
218 @targets = sort {$b->{roids}[0]{xp} <=> $a->{roids}[0]{xp} or $b->{size} <=> $a->{size}} @targets;
220 $c->stash(targets => \@targets);
224 my ($self, $c, $raid, $order) = @_;
227 my $query = $dbh->prepare(q{SELECT id,tick,waves,message,released_coords,open,ftid
228 FROM raids WHERE id = ?
230 $raid = $dbh->selectrow_hashref($query,undef,$raid);
232 $c->stash(raid => $raid);
234 $c->stash(errors => $c->flash->{errors});
236 my $groups = $dbh->prepare(q{SELECT g.gid,g.groupname,raid FROM groups g LEFT OUTER JOIN (SELECT gid,raid FROM raid_access WHERE raid = ?) AS ra ON g.gid = ra.gid WHERE g.attack});
237 $groups->execute($raid ? $raid->{id} : undef);
241 while (my $group = $groups->fetchrow_hashref){
243 push @remgroups,$group;
245 push @addgroups,$group;
248 $c->stash(removegroups => \@remgroups);
249 $c->stash(addgroups => \@addgroups);
251 if ($order && $order =~ /^(score|size|value|xp)rank$/){
253 }elsif ($order && $order eq 'race'){
256 $order .= 'p.x,p.y,p.z';
259 my $targetquery = $dbh->prepare(qq{SELECT r.id,coords(x,y,z),comment,size,score,value,race,planet_status AS planetstatus,relationship,comment,r.planet, s.scans
261 JOIN current_planet_stats p ON p.id = r.planet
262 LEFT OUTER JOIN ( SELECT planet, array_accum(s::text) AS scans
263 FROM ( SELECT DISTINCT ON (planet,type) planet,scan_id,type, tick
265 WHERE tick > tick() - 24
266 ORDER BY planet,type ,tick DESC
269 ) s ON s.planet = r.planet
273 my $claims = $dbh->prepare(q{ SELECT username,launched FROM raid_claims
274 NATURAL JOIN users WHERE target = ? AND wave = ?});
276 $targetquery->execute($raid->{id});
278 while (my $target = $targetquery->fetchrow_hashref){
280 for my $i (1 .. $raid->{waves}){
281 $claims->execute($target->{id},$i);
283 if ($claims->rows != 0){
286 while (my $claim = $claims->fetchrow_hashref){
287 $claim->{username} .= '*' if ($claim->{launched});
288 push @claimers,$claim->{username};
290 $claimers = join '/', @claimers;
292 push @waves,{wave => $i, claimers => $claimers};
294 $target->{waves} = \@waves;
296 $target->{scans} = array_expand $target->{scans};
297 push @targets,$target;
299 $c->stash(targets => \@targets);
301 $c->forward('listAlliances');
304 sub postraidupdate : Local {
305 my ($self, $c, $raid) = @_;
309 $dbh->do(q{UPDATE raids SET message = ?, tick = ?, waves = ? WHERE id = ?}
310 ,undef,html_escape $c->req->param('message')
311 ,$c->req->param('tick'),$c->req->param('waves')
314 $c->forward('log',[$raid, 'BC updated raid']);
316 my $groups = $dbh->prepare(q{SELECT gid,groupname FROM groups WHERE attack});
317 my $delgroup = $dbh->prepare(q{DELETE FROM raid_access WHERE raid = ? AND gid = ?});
318 my $addgroup = $dbh->prepare(q{INSERT INTO raid_access (raid,gid) VALUES(?,?)});
321 while (my $group = $groups->fetchrow_hashref){
323 next unless defined $c->req->param($group->{gid});
324 my $command = $c->req->param($group->{gid});
325 if ( $command eq 'remove'){
327 }elsif($command eq 'add'){
331 $query->execute($raid,$group->{gid});
332 $c->forward('log',[$raid, "BC '$command' access for $group->{gid} ($group->{groupname})"]);
337 $c->res->redirect($c->uri_for('edit',$raid));
340 sub postaddtargets : Local {
341 my ($self, $c, $raid) = @_;
344 my $sizelimit = $c->req->param('sizelimit');
345 $sizelimit = -1 unless $sizelimit;
347 my $targets = $c->req->param('targets');
348 my $addtarget = $dbh->prepare(qq{INSERT INTO raid_targets(raid,planet) (
349 SELECT ?, id FROM current_planet_stats p
350 WHERE x = ? AND y = ? AND COALESCE(z = ?,TRUE)
354 while ($targets =~ m/(\d+):(\d+)(?::(\d+))?/g){
355 my ($x,$y,$z) = ($1, $2, $3);
357 $addtarget->execute($raid,$1,$2,$3,$sizelimit);
360 if ($@ =~ /duplicate key value violates unique constraint "raid_targets_raid_key"/){
362 push @errors, "Planet already exists: $x:$y:$z";
364 push @errors, "A planet from $x:$y already exists in the raid,"
365 ." either remove it or add the planets separately.";
371 if ($c->req->param('alliance') =~ /^(\d+)$/ && $1 != 1){
372 my $addtarget = $dbh->prepare(qq{INSERT INTO raid_targets(raid,planet) (
373 SELECT ?,id FROM current_planet_stats p WHERE alliance_id = ? AND p.size > ?)
376 $addtarget->execute($raid,$1,$sizelimit);
377 $c->forward('log',[$raid,"BC adding alliance $1 to raid"]);
379 if ($@ =~ /duplicate key value violates unique constraint "raid_targets_raid_key"/){
380 push @errors, "A planet from this alliance has already been added to the raid,"
381 ." either remove it or add the planets separately.";
387 $c->flash(errors => \@errors) if @errors;
388 $c->res->redirect($c->uri_for('edit',$raid));
391 sub posttargetupdates : Local {
392 my ($self, $c, $raid) = @_;
396 my $comment = $dbh->prepare(q{UPDATE raid_targets SET comment = ? WHERE id = ?});
397 my $unclaim = $dbh->prepare(q{DELETE FROM raid_claims WHERE target = ? AND wave = ?});
398 my $block = $dbh->prepare(q{INSERT INTO raid_claims (target,uid,wave) VALUES(?,-2,?)});
399 my $claim = $dbh->prepare(q{INSERT INTO raid_claims (target,uid,wave)
400 VALUES($1,(SELECT uid FROM users WHERE username ILIKE $3),$2)
402 my $unblock = $dbh->prepare(q{DELETE FROM raid_claims
403 WHERE target = ? AND wave = ? AND uid = -2
405 my $remove = $dbh->prepare(q{DELETE FROM raid_targets WHERE raid = ? AND id = ?});
406 for $_ ($c->req->param()){
407 if (/^comment:(\d+)$/){
408 $comment->execute(html_escape $c->req->param($_),$1);
409 }elsif(/^unclaim:(\d+):(\d+)$/){
410 $unclaim->execute($1,$2);
411 $c->forward('log',[$raid,"BC unclaimed target $1 wave $2."]);
412 }elsif(/^block:(\d+):(\d+)$/){
413 $block->execute($1,$2);
414 $c->forward('log',[$raid,"BC blocked target $1 wave $2."]);
415 }elsif(/^claim:(\d+):(\d+)$/){
418 my @claims = split /[, ]+/, $c->req->param($_);
421 $claim->execute($target,$wave,$_);
423 if ($@ =~ /null value in column "uid"/){
424 push @errors, "Could not find user: " . html_escape $_;
425 }elsif ($@ =~ /more than one row returned by a subquery/){
426 push @errors, "This matched several users, please refine: " . html_escape $_;
432 $unblock->execute($target,$wave);
433 $c->forward('log',[$raid,"BC claimed target $1 wave $2 for @claims."]);
435 }elsif(/^remove:(\d+)$/){
436 $remove->execute($raid,$1);
437 $c->forward('log',[$raid,"BC removed target $1"]);
441 $c->flash(errors => \@errors) if @errors;
442 $c->res->redirect($c->uri_for('edit',$raid));
446 my ($self, $c, $raid) = @_;
448 $c->model->do(q{UPDATE raids SET open = TRUE, removed = FALSE WHERE id = ?}
450 $c->forward('log',[$raid, "BC opened raid"]);
452 $c->res->redirect($c->req->referer);
456 my ($self, $c, $raid) = @_;
458 $c->model->do(q{UPDATE raids SET open = FALSE WHERE id = ?}
460 $c->forward('log',[$raid, "BC closed raid"]);
462 $c->res->redirect($c->req->referer);
466 my ($self, $c, $raid) = @_;
468 $c->model->do(q{UPDATE raids SET open = FALSE, removed = TRUE WHERE id = ?}
470 $c->forward('log',[$raid, "BC removed raid"]);
472 $c->res->redirect($c->req->referer);
475 sub showcoords : Local {
476 my ($self, $c, $raid) = @_;
478 $c->model->do(q{UPDATE raids SET released_coords = TRUE WHERE id = ?}
480 $c->forward('log',[$raid, "BC released coords"]);
482 $c->res->redirect($c->req->referer);
485 sub hidecoords : Local {
486 my ($self, $c, $raid) = @_;
488 $c->model->do(q{UPDATE raids SET released_coords = FALSE WHERE id = ?}
490 $c->forward('log',[$raid, "BC hid coords"]);
492 $c->res->redirect($c->req->referer);
497 $c->stash(waves => 3);
499 $c->stash(landingtick => $c->stash->{TICK} + 24 - $time[2] + 12);
502 sub postcreate : Local {
506 my $query = $dbh->prepare(q{INSERT INTO raids (tick,waves,message) VALUES(?,?,?) RETURNING (id)});
507 $query->execute($c->req->param('tick'),$c->req->param('waves')
508 ,html_escape $c->req->param('message'));
509 my $raid = $query->fetchrow_array;
510 $c->forward('log',[$raid,"Created raid landing at tick: ".$c->req->param('tick')]);
512 if ($c->req->param('gal') || $c->req->param('target')) {
513 my @gals = $c->req->param('gal');
514 my @targets = $c->req->param('target');
516 my $addtarget = $dbh->prepare(q{INSERT INTO raid_targets(raid,planet) (
517 SELECT $1,id FROM current_planet_stats p WHERE (planet_status IN ('','Hostile')
518 AND (relationship IS NULL OR relationship IN ('','Hostile')))
519 AND (id = ANY ($2) OR ( size > $4 AND (x,y) IN (
520 SELECT x,y FROM current_planet_stats WHERE id = ANY ($3)))
524 $addtarget->execute($raid,\@targets,\@gals,$c->req->param('sizelimit'));
525 $c->forward('log',[$raid,"BC added planets (@targets) and the gals for (@gals)"]);
528 $c->res->redirect($c->uri_for('edit',$raid));
531 sub targetlist : Local {
532 my ($self, $c, $alliances, $order) = @_;
535 $c->stash(comma => \&comma_value);
536 $c->stash(allies => $alliances);
538 my @alliances = split /,/, $alliances;
540 $c->forward('listAlliances');
542 if ($order && $order =~ /^(sizerank|valuerank|scorerank|xprank|nfvalue|nfvalue2)$/){
547 $order = "p.$order" if $order =~ /rank$/;
549 my $query = $dbh->prepare(q{
550 SELECT p.id, coords(p.x,p.y,p.z),p.x,p.y,p.alliance, p.score, p.value, p.size, p.xp,nfvalue, nfvalue - sum(pa.value) AS nfvalue2, p.race
551 FROM current_planet_stats p
552 JOIN (SELECT g.x,g.y, sum(p.value) AS nfvalue
553 FROM galaxies g join current_planet_stats p on g.x = p.x AND g.y = p.y
554 WHERE g.tick = (SELECT max(tick) from galaxies)
555 AND (planet_status IN ('','Hostile')
556 AND (relationship IS NULL OR relationship IN ('','Hostile')))
558 ) g ON p.x = g.x AND p.y = g.y
559 JOIN current_planet_stats pa ON pa.x = g.x AND pa.y = g.y
561 AND p.alliance_id = ANY ($1)
562 AND pa.alliance_id = ANY ($1)
563 AND p.relationship IN ('','Hostile')
564 GROUP BY p.id, p.x,p.y,p.z,p.alliance, p.score, p.value, p.size, p.xp, nfvalue,p.race
565 ,p.scorerank,p.valuerank,p.sizerank,p.xprank
568 $query->execute(\@alliances);
569 $c->stash(planets => $query->fetchall_arrayref({}) );
570 $c->forward('create');
573 sub posttargetalliances : Local {
576 $c->res->redirect($c->uri_for('targetlist',join ',',$c->req->param('alliances')));
579 sub listAlliances : Private {
582 my $query = $c->model->prepare(q{SELECT id,name FROM alliances
583 WHERE relationship IN ('','Hostile')
584 AND id IN (SELECT alliance_id FROM planets)
588 push @alliances,{id => -1, name => ''};
589 while (my $ally = $query->fetchrow_hashref){
590 push @alliances,$ally;
592 $c->stash(alliances => \@alliances);
596 my ($self, $c, $raid, $message) = @_;
599 my $log = $dbh->prepare(q{INSERT INTO forum_posts (uid,ftid,message)
600 VALUES($1,(SELECT ftid FROM raids WHERE id = $2),$3)
602 $log->execute($c->user->id,$raid,$message);
605 sub findRaid : Private {
606 my ( $self, $c, $raid ) = @_;
609 my $query = $dbh->prepare(q{SELECT id,tick,waves,message,released_coords
610 FROM raids WHERE id = ? AND open AND not removed AND id IN
611 (SELECT raid FROM raid_access NATURAL JOIN groupmembers WHERE uid = ?)
613 $raid = $dbh->selectrow_hashref($query,undef,$raid,$c->user->id);
614 $c->stash(raid => $raid);
619 Michael Andreen (harv@ruin.nu)